repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
thedraked/darkstar | scripts/zones/Norg/npcs/Gimb.lua | 14 | 1159 | -----------------------------------
-- Area: Norg
-- NPC: Gimb
-- Type: Begins the "Sahagin Key Quest" but it doesn't appear in the log. See http://wiki.ffxiclopedia.org/wiki/Sahagin_Key_Quest
-- @zone 252
-- @pos -4.975 -1.975 -44.039
--
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Norg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0045);
player:setVar("SahaginKeyProgress",1);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
mtroyka/Zero-K | scripts/hoveraa.lua | 11 | 1989 | local base = piece 'base'
local body = piece 'body'
local turret = piece 'turret'
local ground1 = piece 'ground1'
local missile = piece 'missile'
local firepoint = piece 'firepoint'
local wakes = {}
for i = 1, 8 do
wakes[i] = piece ('wake' .. i)
end
include "constants.lua"
local SIG_MOVE = 1
local SIG_AIM = 2
local function WobbleUnit()
local wobble = true
while true do
if wobble == true then
Move(base, y_axis, 1.2, 1.6)
end
if wobble == false then
Move(base, y_axis, -1.2, 1.6)
end
wobble = not wobble
Sleep(750)
end
end
local sfxNum = 0
function script.setSFXoccupy(num)
sfxNum = num
end
local function MoveScript()
while Spring.GetUnitIsStunned(unitID) do
Sleep(2000)
end
while true do
if not Spring.GetUnitIsCloaked(unitID) then
if (sfxNum == 1 or sfxNum == 2) and select(2, Spring.GetUnitPosition(unitID)) == 0 then
for i = 1, 8 do
EmitSfx(wakes[i], 3)
end
else
EmitSfx(ground1, 1024)
end
end
Sleep(150)
end
end
function script.Create()
Turn(firepoint, x_axis, math.rad(-90))
StartThread(SmokeUnit, {base})
StartThread(WobbleUnit)
StartThread(MoveScript)
end
function script.AimFromWeapon()
return turret
end
function script.AimWeapon()
return true
end
function script.QueryWeapon()
return firepoint
end
local function ReloadMissileThread()
Hide(missile)
Sleep(1000)
Show(missile)
end
function script.BlockShot(num, targetID)
return GG.OverkillPrevention_CheckBlock(unitID, targetID, 374, 50)
end
function script.FireWeapon()
StartThread(ReloadMissileThread)
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage / maxHealth
if severity <= 0.25 then
Explode(body, sfxNone)
return 1
end
if severity <= 0.50 then
Explode(body, sfxNone)
Explode(turret, sfxShatter)
return 1
end
if severity <= 0.99 then
Explode(body, sfxNone)
Explode(turret, sfxShatter)
return 2
end
Explode(body, sfxNone)
Explode(turret, sfxShatter)
return 2
end
| gpl-2.0 |
fhedberg/ardupilot | libraries/AP_Scripting/examples/LED_matrix_image.lua | 27 | 12280 | --[[
Script to control LED strips based on the roll of the aircraft. This is an example to demonstrate
the LED interface for WS2812 LEDs
--]]
--[[
for this demo we will use a single strip with 30 LEDs
--]]
local matrix_x = 7
local matrix_y = 7
-- matrix to convert from x y pos to location in the strip
local id = {}
-- because my strips go diagonally to get the led's closer together this is a odd ordering
id[1] = {}
id[1][1] = 21
id[1][2] = 20
id[1][3] = 10
id[1][4] = 9
id[1][5] = 3
id[1][6] = 2
id[1][7] = 0
id[2] = {}
id[2][1] = 33
id[2][2] = 22
id[2][3] = 19
id[2][4] = 11
id[2][5] = 8
id[2][6] = 4
id[2][7] = 1
id[3] = {}
id[3][1] = 34
id[3][2] = 32
id[3][3] = 23
id[3][4] = 18
id[3][5] = 12
id[3][6] = 7
id[3][7] = 5
id[4] = {}
id[4][1] = 42
id[4][2] = 35
id[4][3] = 31
id[4][4] = 24
id[4][5] = 17
id[4][6] = 13
id[4][7] = 6
id[5] = {}
id[5][1] = 43
id[5][2] = 41
id[5][3] = 36
id[5][4] = 30
id[5][5] = 25
id[5][6] = 16
id[5][7] = 14
id[6] = {}
id[6][1] = 47
id[6][2] = 44
id[6][3] = 40
id[6][4] = 37
id[6][5] = 29
id[6][6] = 26
id[6][7] = 15
id[7] = {}
id[7][1] = 48
id[7][2] = 46
id[7][3] = 45
id[7][4] = 39
id[7][5] = 38
id[7][6] = 28
id[7][7] = 27
-- ArduPilot logo 7 x 48, RGB
image = {}
image[1] = {}
image[2] = {}
image[3] = {}
image[4] = {}
image[5] = {}
image[6] = {}
image[7] = {}
image[1][1] = {0, 0, 0}
image[2][1] = {0, 0, 0}
image[3][1] = {0, 0, 0}
image[4][1] = {0, 0, 0}
image[5][1] = {0, 0, 0}
image[6][1] = {0, 0, 0}
image[7][1] = {0, 0, 0}
image[1][2] = {0, 0, 0}
image[2][2] = {0, 0, 0}
image[3][2] = {0, 0, 0}
image[4][2] = {0, 0, 0}
image[5][2] = {0, 0, 0}
image[6][2] = {0, 0, 0}
image[7][2] = {191, 191, 191}
image[1][3] = {0, 0, 0}
image[2][3] = {0, 0, 0}
image[3][3] = {0, 0, 0}
image[4][3] = {0, 0, 0}
image[5][3] = {0, 0, 0}
image[6][3] = {191, 191, 191}
image[7][3] = {0, 0, 0}
image[1][4] = {0, 0, 0}
image[2][4] = {0, 0, 0}
image[3][4] = {0, 0, 0}
image[4][4] = {196, 196, 196}
image[5][4] = {191, 191, 191}
image[6][4] = {0, 0, 0}
image[7][4] = {191, 191, 191}
image[1][5] = {0, 0, 0}
image[2][5] = {0, 0, 0}
image[3][5] = {0, 0, 0}
image[4][5] = {191, 191, 191}
image[5][5] = {0, 0, 0}
image[6][5] = {0, 0, 0}
image[7][5] = {191, 191, 191}
image[1][6] = {0, 0, 0}
image[2][6] = {0, 0, 0}
image[3][6] = {191, 191, 191}
image[4][6] = {0, 0, 0}
image[5][6] = {191, 191, 191}
image[6][6] = {0, 0, 0}
image[7][6] = {191, 191, 191}
image[1][7] = {0, 0, 0}
image[2][7] = {191, 191, 191}
image[3][7] = {0, 0, 0}
image[4][7] = {0, 0, 0}
image[5][7] = {191, 191, 191}
image[6][7] = {0, 0, 0}
image[7][7] = {191, 191, 191}
image[1][8] = {191, 191, 191}
image[2][8] = {191, 191, 191}
image[3][8] = {191, 191, 191}
image[4][8] = {191, 191, 191}
image[5][8] = {191, 191, 191}
image[6][8] = {191, 191, 191}
image[7][8] = {191, 191, 191}
image[1][9] = {0, 0, 0}
image[2][9] = {0, 0, 0}
image[3][9] = {0, 0, 0}
image[4][9] = {0, 0, 0}
image[5][9] = {0, 0, 0}
image[6][9] = {0, 0, 0}
image[7][9] = {191, 191, 191}
image[1][10] = {0, 0, 0}
image[2][10] = {191, 191, 191}
image[3][10] = {191, 191, 191}
image[4][10] = {191, 191, 191}
image[5][10] = {191, 191, 191}
image[6][10] = {191, 191, 191}
image[7][10] = {191, 191, 191}
image[1][11] = {191, 191, 191}
image[2][11] = {190, 190, 190}
image[3][11] = {0, 0, 0}
image[4][11] = {0, 0, 0}
image[5][11] = {0, 0, 0}
image[6][11] = {0, 0, 0}
image[7][11] = {191, 191, 191}
image[1][12] = {191, 191, 191}
image[2][12] = {192, 192, 192}
image[3][12] = {0, 0, 0}
image[4][12] = {191, 191, 191}
image[5][12] = {0, 0, 0}
image[6][12] = {0, 0, 0}
image[7][12] = {191, 191, 191}
image[1][13] = {191, 191, 191}
image[2][13] = {191, 191, 191}
image[3][13] = {191, 191, 191}
image[4][13] = {191, 191, 191}
image[5][13] = {193, 193, 193}
image[6][13] = {0, 0, 0}
image[7][13] = {191, 191, 191}
image[1][14] = {0, 0, 0}
image[2][14] = {191, 191, 191}
image[3][14] = {191, 191, 191}
image[4][14] = {0, 0, 0}
image[5][14] = {191, 191, 191}
image[6][14] = {187, 187, 187}
image[7][14] = {191, 191, 191}
image[1][15] = {0, 0, 0}
image[2][15] = {191, 191, 191}
image[3][15] = {191, 191, 191}
image[4][15] = {191, 191, 191}
image[5][15] = {191, 191, 191}
image[6][15] = {191, 191, 191}
image[7][15] = {191, 191, 191}
image[1][16] = {195, 195, 195}
image[2][16] = {191, 191, 191}
image[3][16] = {191, 191, 191}
image[4][16] = {191, 191, 191}
image[5][16] = {191, 191, 191}
image[6][16] = {191, 191, 191}
image[7][16] = {191, 191, 191}
image[1][17] = {191, 191, 191}
image[2][17] = {190, 190, 190}
image[3][17] = {0, 0, 0}
image[4][17] = {0, 0, 0}
image[5][17] = {190, 190, 190}
image[6][17] = {191, 191, 191}
image[7][17] = {191, 191, 191}
image[1][18] = {191, 191, 191}
image[2][18] = {191, 191, 191}
image[3][18] = {0, 0, 0}
image[4][18] = {0, 0, 0}
image[5][18] = {191, 191, 191}
image[6][18] = {191, 191, 191}
image[7][18] = {191, 191, 191}
image[1][19] = {0, 0, 0}
image[2][19] = {191, 191, 191}
image[3][19] = {191, 191, 191}
image[4][19] = {191, 191, 191}
image[5][19] = {191, 191, 191}
image[6][19] = {0, 0, 0}
image[7][19] = {191, 191, 191}
image[1][20] = {0, 0, 0}
image[2][20] = {0, 0, 0}
image[3][20] = {0, 0, 0}
image[4][20] = {0, 0, 0}
image[5][20] = {0, 0, 0}
image[6][20] = {0, 0, 0}
image[7][20] = {191, 191, 191}
image[1][21] = {0, 0, 0}
image[2][21] = {191, 191, 191}
image[3][21] = {191, 191, 191}
image[4][21] = {191, 191, 191}
image[5][21] = {191, 191, 191}
image[6][21] = {0, 0, 0}
image[7][21] = {191, 191, 191}
image[1][22] = {191, 191, 191}
image[2][22] = {192, 192, 192}
image[3][22] = {192, 192, 192}
image[4][22] = {192, 192, 192}
image[5][22] = {191, 191, 191}
image[6][22] = {191, 191, 191}
image[7][22] = {191, 191, 191}
image[1][23] = {0, 0, 0}
image[2][23] = {0, 0, 0}
image[3][23] = {0, 0, 0}
image[4][23] = {0, 0, 0}
image[5][23] = {191, 191, 191}
image[6][23] = {191, 191, 191}
image[7][23] = {191, 191, 191}
image[1][24] = {191, 191, 191}
image[2][24] = {191, 191, 191}
image[3][24] = {191, 191, 191}
image[4][24] = {191, 191, 191}
image[5][24] = {191, 191, 191}
image[6][24] = {0, 0, 0}
image[7][24] = {191, 191, 191}
image[1][25] = {192, 192, 192}
image[2][25] = {192, 192, 192}
image[3][25] = {192, 192, 192}
image[4][25] = {192, 192, 192}
image[5][25] = {0, 0, 0}
image[6][25] = {0, 0, 0}
image[7][25] = {191, 191, 191}
image[1][26] = {0, 0, 0}
image[2][26] = {254, 210, 15}
image[3][26] = {251, 195, 20}
image[4][26] = {249, 179, 23}
image[5][26] = {249, 163, 26}
image[6][26] = {244, 150, 28}
image[7][26] = {191, 191, 191}
image[1][27] = {255, 223, 11}
image[2][27] = {254, 211, 18}
image[3][27] = {244, 196, 36}
image[4][27] = {242, 181, 41}
image[5][27] = {240, 166, 41}
image[6][27] = {237, 152, 46}
image[7][27] = {191, 191, 191}
image[1][28] = {255, 221, 12}
image[2][28] = {253, 210, 20}
image[3][28] = {0, 0, 0}
image[4][28] = {249, 179, 23}
image[5][28] = {0, 0, 0}
image[6][28] = {0, 0, 0}
image[7][28] = {191, 191, 191}
image[1][29] = {252, 222, 12}
image[2][29] = {253, 210, 18}
image[3][29] = {252, 195, 20}
image[4][29] = {249, 179, 23}
image[5][29] = {0, 0, 0}
image[6][29] = {0, 0, 0}
image[7][29] = {191, 191, 191}
image[1][30] = {0, 0, 0}
image[2][30] = {253, 210, 18}
image[3][30] = {251, 195, 20}
image[4][30] = {248, 179, 23}
image[5][30] = {0, 0, 0}
image[6][30] = {0, 0, 0}
image[7][30] = {191, 191, 191}
image[1][31] = {0, 0, 0}
image[2][31] = {0, 0, 0}
image[3][31] = {0, 0, 0}
image[4][31] = {0, 0, 0}
image[5][31] = {0, 0, 0}
image[6][31] = {0, 0, 0}
image[7][31] = {191, 191, 191}
image[1][32] = {0, 0, 0}
image[2][32] = {253, 210, 18}
image[3][32] = {251, 195, 20}
image[4][32] = {249, 179, 23}
image[5][32] = {249, 163, 26}
image[6][32] = {244, 150, 28}
image[7][32] = {191, 191, 191}
image[1][33] = {0, 0, 0}
image[2][33] = {0, 0, 0}
image[3][33] = {0, 0, 0}
image[4][33] = {0, 0, 0}
image[5][33] = {0, 0, 0}
image[6][33] = {0, 0, 0}
image[7][33] = {191, 191, 191}
image[1][34] = {0, 0, 0}
image[2][34] = {253, 210, 17}
image[3][34] = {251, 195, 20}
image[4][34] = {249, 179, 23}
image[5][34] = {249, 163, 26}
image[6][34] = {244, 150, 28}
image[7][34] = {191, 191, 191}
image[1][35] = {0, 0, 0}
image[2][35] = {0, 0, 0}
image[3][35] = {0, 0, 0}
image[4][35] = {0, 0, 0}
image[5][35] = {250, 162, 26}
image[6][35] = {244, 150, 28}
image[7][35] = {191, 191, 191}
image[1][36] = {0, 0, 0}
image[2][36] = {0, 0, 0}
image[3][36] = {0, 0, 0}
image[4][36] = {0, 0, 0}
image[5][36] = {249, 163, 26}
image[6][36] = {244, 150, 28}
image[7][36] = {191, 191, 191}
image[1][37] = {0, 0, 0}
image[2][37] = {0, 0, 0}
image[3][37] = {252, 196, 21}
image[4][37] = {248, 179, 23}
image[5][37] = {0, 0, 0}
image[6][37] = {0, 0, 0}
image[7][37] = {191, 191, 191}
image[1][38] = {0, 0, 0}
image[2][38] = {253, 210, 18}
image[3][38] = {0, 0, 0}
image[4][38] = {0, 0, 0}
image[5][38] = {249, 163, 26}
image[6][38] = {0, 0, 0}
image[7][38] = {191, 191, 191}
image[1][39] = {249, 223, 14}
image[2][39] = {0, 0, 0}
image[3][39] = {244, 193, 22}
image[4][39] = {247, 187, 41}
image[5][39] = {0, 0, 0}
image[6][39] = {245, 149, 28}
image[7][39] = {191, 191, 191}
image[1][40] = {252, 222, 14}
image[2][40] = {0, 0, 0}
image[3][40] = {249, 196, 18}
image[4][40] = {249, 179, 19}
image[5][40] = {0, 0, 0}
image[6][40] = {0, 0, 0}
image[7][40] = {191, 191, 191}
image[1][41] = {255, 222, 13}
image[2][41] = {250, 214, 18}
image[3][41] = {0, 0, 0}
image[4][41] = {0, 0, 0}
image[5][41] = {247, 164, 22}
image[6][41] = {244, 147, 32}
image[7][41] = {191, 191, 191}
image[1][42] = {0, 0, 0}
image[2][42] = {255, 209, 17}
image[3][42] = {251, 195, 20}
image[4][42] = {249, 179, 23}
image[5][42] = {247, 164, 26}
image[6][42] = {0, 0, 0}
image[7][42] = {191, 191, 191}
image[1][43] = {0, 0, 0}
image[2][43] = {249, 213, 15}
image[3][43] = {0, 0, 0}
image[4][43] = {0, 0, 0}
image[5][43] = {0, 0, 0}
image[6][43] = {0, 0, 0}
image[7][43] = {191, 191, 191}
image[1][44] = {249, 221, 15}
image[2][44] = {244, 211, 18}
image[3][44] = {0, 0, 0}
image[4][44] = {0, 0, 0}
image[5][44] = {0, 0, 0}
image[6][44] = {0, 0, 0}
image[7][44] = {191, 191, 191}
image[1][45] = {255, 221, 12}
image[2][45] = {253, 210, 18}
image[3][45] = {251, 195, 20}
image[4][45] = {249, 179, 23}
image[5][45] = {249, 163, 26}
image[6][45] = {245, 149, 26}
image[7][45] = {191, 191, 191}
image[1][46] = {255, 221, 12}
image[2][46] = {251, 211, 17}
image[3][46] = {0, 0, 0}
image[4][46] = {0, 0, 0}
image[5][46] = {0, 0, 0}
image[6][46] = {0, 0, 0}
image[7][46] = {191, 191, 191}
image[1][47] = {255, 221, 12}
image[2][47] = {0, 0, 0}
image[3][47] = {0, 0, 0}
image[4][47] = {0, 0, 0}
image[5][47] = {0, 0, 0}
image[6][47] = {0, 0, 0}
image[7][47] = {0, 0, 0}
image[1][48] = {0, 0, 0}
image[2][48] = {0, 0, 0}
image[3][48] = {0, 0, 0}
image[4][48] = {0, 0, 0}
image[5][48] = {0, 0, 0}
image[6][48] = {0, 0, 0}
image[7][48] = {0, 0, 0}
--[[
use SERVOn_FUNCTION 94 for LED. We can control up to 16 separate strips of LEDs
by putting them on different channels
--]]
local chan = SRV_Channels:find_channel(94)
if not chan then
gcs:send_text(6, "LEDs: channel not set")
return
end
-- find_channel returns 0 to 15, convert to 1 to 16
chan = chan + 1
gcs:send_text(6, "LEDs: chan=" .. tostring(chan))
-- initialisation code
--serialLED:set_num_neopixel(chan, matrix_x * matrix_y)
serialLED:set_num_profiled(chan, matrix_x * matrix_y)
local offset = 8;
local function display_image(image_in,offset_in,brightness_in)
local im_offset = 0
if offset_in then
im_offset = offset_in
end
local brightness = 1
if brightness_in then
brightness = brightness_in
end
local i
local j
for i = 1, 48 do
local x_index = i + im_offset
if x_index >= 1 and x_index <= matrix_x then
for j = 1, matrix_y do
serialLED:set_RGB(chan, id[j][x_index], math.floor(image_in[j][i][1]*brightness), math.floor(image_in[j][i][2]*brightness), math.floor(image_in[j][i][3]*brightness))
end
end
end
end
function update_LEDs()
serialLED:set_RGB(chan, -1, 0, 0, 0)
display_image(image,offset,0.05)
serialLED:send(chan)
offset = offset - 1
-- scroll until it is off the left edge
if offset < - 48 - 8 then
-- start with the stuff off the right edge of the display
offset = 8
end
return update_LEDs, 100
end
return update_LEDs, 1000
| gpl-3.0 |
thedraked/darkstar | scripts/zones/Metalworks/npcs/Cid.lua | 14 | 11944 | -----------------------------------
-- Area: Metalworks
-- NPC: Cid
-- Starts & Finishes Quest: Cid's Secret, The Usual, Dark Puppet (start)
-- Involved in Mission: Bastok 7-1
-- @pos -12 -12 1 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getCurrentMission(BASTOK) == THE_CRYSTAL_LINE and player:getVar("MissionStatus") == 1) then
if (trade:getItemQty(613,1) and trade:getItemCount() == 1) then
player:startEvent(0x01fa);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local currentday = tonumber(os.date("%j"));
local CidsSecret = player:getQuestStatus(BASTOK,CID_S_SECRET);
local LetterKeyItem = player:hasKeyItem(UNFINISHED_LETTER);
local currentMission = player:getCurrentMission(BASTOK);
local currentCOPMission = player:getCurrentMission(COP);
local UlmiaPath = player:getVar("COP_Ulmia_s_Path");
local TenzenPath = player:getVar("COP_Tenzen_s_Path");
local LouverancePath = player:getVar("COP_Louverance_s_Path");
local TreePathAv=0;
if (currentCOPMission == DAWN and player:getVar("PromathiaStatus")==3 and player:getVar("Promathia_kill_day")~=currentday and player:getVar("COP_tenzen_story")== 0 ) then
player:startEvent(0x0381); -- COP event
elseif (currentCOPMission == CALM_BEFORE_THE_STORM and player:hasKeyItem(LETTERS_FROM_ULMIA_AND_PRISHE) == false and player:getVar("COP_Dalham_KILL") == 2 and player:getVar("COP_Boggelmann_KILL") == 2 and player:getVar("Cryptonberry_Executor_KILL")==2) then
player:startEvent(0x037C); -- COP event
elseif (currentCOPMission == FIRE_IN_THE_EYES_OF_MEN and player:getVar("PromathiaStatus")==2 and player:getVar("Promathia_CID_timer")~=VanadielDayOfTheYear()) then
player:startEvent(0x037A); -- COP event
elseif (currentCOPMission == FIRE_IN_THE_EYES_OF_MEN and player:getVar("PromathiaStatus")==1) then
player:startEvent(0x0359); -- COP event
elseif (currentCOPMission == ONE_TO_BE_FEARED and player:getVar("PromathiaStatus")==0) then
player:startEvent(0x0358); -- COP event
elseif (currentCOPMission == THREE_PATHS and LouverancePath == 6 ) then
player:startEvent(0x0354); -- COP event
elseif (currentCOPMission == THREE_PATHS and LouverancePath == 9 ) then
if (TenzenPath==11 and UlmiaPath==8) then
TreePathAv=6;
elseif (TenzenPath==11) then
TreePathAv=2;
elseif (UlmiaPath==8) then
TreePathAv=4;
else
TreePathAv=1;
end
player:startEvent(0x0355,TreePathAv); -- COP event
elseif (currentCOPMission == THREE_PATHS and TenzenPath == 10 ) then
if (UlmiaPath==8 and LouverancePath==10) then
TreePathAv=5;
elseif (LouverancePath==10) then
TreePathAv=3;
elseif (UlmiaPath==8) then
TreePathAv=4;
else
TreePathAv=1;
end
player:startEvent(0x0356,TreePathAv); -- COP event
elseif (currentCOPMission == THREE_PATHS and UlmiaPath == 7 ) then
if (TenzenPath==11 and LouverancePath==10) then
TreePathAv=3;
elseif (LouverancePath==10) then
TreePathAv=1;
elseif (TenzenPath==11) then
TreePathAv=2;
else
TreePathAv=0;
end
player:startEvent(0x0357,TreePathAv); -- COP event
elseif (currentCOPMission == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus") > 8) then
player:startEvent(0x0352); -- COP event
elseif (currentCOPMission == THE_ENDURING_TUMULT_OF_WAR and player:getVar("PromathiaStatus")==1) then
player:startEvent(0x0351); -- COP event
elseif (currentCOPMission == THE_CALL_OF_THE_WYRMKING and player:getVar("PromathiaStatus")==1) then
player:startEvent(0x034D); -- COP event
elseif (currentCOPMission == THE_ROAD_FORKS and player:getVar("EMERALD_WATERS_Status")== 7 and player:getVar("MEMORIES_OF_A_MAIDEN_Status")== 12) then --two paths are finished ?
player:startEvent(0x034F); -- COP event 3.3
elseif (player:getMainJob() == JOBS.DRK and player:getMainLvl() >= AF2_QUEST_LEVEL and
player:getQuestStatus(BASTOK,DARK_LEGACY) == QUEST_COMPLETED and player:getQuestStatus(BASTOK,DARK_PUPPET) == QUEST_AVAILABLE) then
player:startEvent(0x02f8); -- Start Quest "Dark Puppet"
elseif (currentMission == GEOLOGICAL_SURVEY) then
if (player:hasKeyItem(RED_ACIDITY_TESTER)) then
player:startEvent(0x01f8);
elseif (player:hasKeyItem(BLUE_ACIDITY_TESTER) == false) then
player:startEvent(0x01f7);
end
elseif (currentMission == THE_CRYSTAL_LINE) then
if (player:hasKeyItem(C_L_REPORTS)) then
player:showText(npc,MISSION_DIALOG_CID_TO_AYAME);
else
player:startEvent(0x01f9);
end
elseif (currentMission == THE_FINAL_IMAGE and player:getVar("MissionStatus") == 0) then
player:startEvent(0x02fb); -- Bastok Mission 7-1
elseif (currentMission == THE_FINAL_IMAGE and player:getVar("MissionStatus") == 2) then
player:startEvent(0x02fc); -- Bastok Mission 7-1 (with Ki)
--Begin Cid's Secret
elseif (player:getFameLevel(BASTOK) >= 4 and CidsSecret == QUEST_AVAILABLE) then
player:startEvent(0x01fb);
elseif (CidsSecret == QUEST_ACCEPTED and LetterKeyItem == false and player:getVar("CidsSecret_Event") == 1) then
player:startEvent(0x01fc); --After talking to Hilda, Cid gives information on the item she needs
elseif (CidsSecret == QUEST_ACCEPTED and LetterKeyItem == false) then
player:startEvent(0x01f6); --Reminder dialogue from Cid if you have not spoken to Hilda
elseif (CidsSecret == QUEST_ACCEPTED and LetterKeyItem) then
player:startEvent(0x01fd);
--End Cid's Secret
else
player:startEvent(0x01f4); -- Standard Dialogue
end
end;
-- 0x01f7 0x01f8 0x01f9 0x01fa 0x01f4 0x01f6 0x02d0 0x01fb 0x01fc 0x01fd 0x025b 0x02f3 0x02f8 0x03f2 0x02fb 0x02fc
-- 0x030c 0x030e 0x031b 0x031c 0x031d 0x031e 0x031f 0x035d 0x034e 0x0350 0x035e 0x035f 0x0353 0x035a 0x034d 0x034f
-- 0x0351 0x0352 0x0354 0x0355 0x0356 0x0357 0x0358 0x0359 0x0364 0x0365 0x0373 0x0374 0x037a 0x037b 0x037c 0x037d
-- 0x037e 0x037f 0x0381 0x0382
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- local currentday = tonumber(os.date("%j"));
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0381) then
player:setVar("COP_tenzen_story",1);
elseif (csid == 0x037C) then
player:addKeyItem(LETTERS_FROM_ULMIA_AND_PRISHE);
player:messageSpecial(KEYITEM_OBTAINED,LETTERS_FROM_ULMIA_AND_PRISHE);
elseif (csid == 0x037A) then
player:setVar("PromathiaStatus",0);
player:setVar("Promathia_CID_timer",0);
player:completeMission(COP,FIRE_IN_THE_EYES_OF_MEN);
player:addMission(COP,CALM_BEFORE_THE_STORM);
elseif (csid == 0x0359) then
player:setVar("PromathiaStatus",2);
player:setVar("Promathia_CID_timer",VanadielDayOfTheYear());
elseif (csid == 0x0357) then
player:setVar("COP_Ulmia_s_Path",8);
elseif (csid == 0x0356) then
player:setVar("COP_Tenzen_s_Path",11);
elseif (csid == 0x0355) then
player:setVar("COP_Louverance_s_Path",10);
elseif (csid == 0x0354) then
player:setVar("COP_Louverance_s_Path",7);
elseif (csid == 0x0352) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,DESIRES_OF_EMPTINESS);
player:addMission(COP,THREE_PATHS);
elseif (csid == 0x0351) then
player:setVar("PromathiaStatus",2);
elseif (csid == 0x0358) then
player:setVar("PromathiaStatus",1);
elseif (csid == 0x034D) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,THE_CALL_OF_THE_WYRMKING);
player:addMission(COP,A_VESSEL_WITHOUT_A_CAPTAIN);
elseif (csid == 0x034F) then
-- finishing mission 3.3 and all sub missions
player:setVar("EMERALD_WATERS_Status",0);
player:setVar("MEMORIES_OF_A_MAIDEN_Status",0);
player:completeMission(COP,THE_ROAD_FORKS);
player:addMission(COP,DESCENDANTS_OF_A_LINE_LOST);
player:completeMission(COP,DESCENDANTS_OF_A_LINE_LOST);
player:addMission(COP,COMEDY_OF_ERRORS_ACT_I);
player:completeMission(COP,COMEDY_OF_ERRORS_ACT_I);
player:addMission(COP,TENDING_AGED_WOUNDS ); --starting 3.4 COP mission
elseif (csid == 0x02f8) then
player:addQuest(BASTOK,DARK_PUPPET);
player:setVar("darkPuppetCS",1);
elseif (csid == 0x01f7) then
player:addKeyItem(BLUE_ACIDITY_TESTER);
player:messageSpecial(KEYITEM_OBTAINED, BLUE_ACIDITY_TESTER);
elseif (csid == 0x01f8 or csid == 0x02fc) then
finishMissionTimeline(player,1,csid,option);
elseif (csid == 0x01f9 and option == 0) then
if (player:getVar("MissionStatus") == 0) then
if (player:getFreeSlotsCount(0) >= 1) then
crystal = math.random(4096,4103);
player:addItem(crystal);
player:messageSpecial(ITEM_OBTAINED, crystal);
player:setVar("MissionStatus",1);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal);
end
end
elseif (csid == 0x01fa and option == 0) then
player:tradeComplete();
player:addKeyItem(C_L_REPORTS);
player:messageSpecial(KEYITEM_OBTAINED, C_L_REPORTS);
elseif (csid == 0x02fb) then
player:setVar("MissionStatus",1);
elseif (csid == 0x01fb) then
player:addQuest(BASTOK,CID_S_SECRET);
elseif (csid == 0x01fd) then
if (player:getFreeSlotsCount(0) >= 1) then
player:delKeyItem(UNFINISHED_LETTER);
player:setVar("CidsSecret_Event",0);
player:addItem(13570);
player:messageSpecial(ITEM_OBTAINED,13570); -- Ram Mantle
player:addFame(BASTOK,30);
player:completeQuest(BASTOK,CID_S_SECRET);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13570);
end
end
-- complete chapter "tree path"
if (csid == 0x0355 or csid == 0x0356 or csid == 0x0357) then
if (player:getVar("COP_Tenzen_s_Path")==11 and player:getVar("COP_Ulmia_s_Path")==8 and player:getVar("COP_Louverance_s_Path")==10) then
player:completeMission(COP,THREE_PATHS);
player:addMission(COP,FOR_WHOM_THE_VERSE_IS_SUNG);
player:setVar("PromathiaStatus",0);
end
end
end;
| gpl-3.0 |
mohmedsa773/dmdm9 | plugins/meee.lua | 1 | 9996 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀ BY SAJAD NOORI (@SAJJADNOORI) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀ info user : معلوماتي ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
local Arian = 206839802 --put your id here(BOT OWNER ID)
local function setrank(msg, name, value) -- setrank function
local hash = nil
if msg.to.type == 'chat' then
hash = 'rank:'..msg.to.id..':variables'
end
if hash then
redis:hset(hash, name, value)
return send_msg('chat#id'..msg.to.id, 'set Rank for ('..name..') To : '..value, ok_cb, true)
end
end
local function res_user_callback(extra, success, result) -- /info <username> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = '----'
end
local text = '❣ الاسم : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'❣ المعرف : '..Username..'\n'
..'❣ ايدي : '..result.id..'\n\n'
..'❣ اسم المجموعه : '..msg.to.title..'\n'
..'❣ ايدي المجموعه : '..msg.to.id..'\n'
local hash = 'rank:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(Arian) then
text = text..'❣ رتبتك : Executive Admin \n\n'
elseif is_sudo(result.id) then
text = text..'❣ رتبتك : المطور مالتي 😻🙊\n\n'
elseif is_owner(result.id, extra.chat2) then
text = text..'❣ رتبتك : مدير المجموعه 🌺😍\n\n'
elseif is_momod(result.id, extra.chat2) then
text = text..'❣ رتبتك : ادمن 👍🏻☺️\n\n'
else
text = text..'❣ رتبتك : مجرد عضو 😒💔 \n\n'
end
else
text = text..'❣ رتبتك : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'❣ عدد الرسائل المرسله : '..user_info_msgs..'\n\n'
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, ' Username not found.', ok_cb, false)
end
end
local function action_by_id(extra, success, result) -- /info <ID> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = '----'
end
local text = '❣ الاسم : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'❣ المعرف : '..Username..'\n'
..'❣ ايدي : '..result.id..'\n\n'
..'❣ ايدي المجموعه : '..msg.to.id..'\n'
..'❣ اسم المجموعه : '..msg.to.title..'\n'
local hash = 'rank:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(Arian) then
text = text..'❣ رتبتك : Executive Admin \n\n'
elseif is_sudo(result.id) then
text = text..'❣ رتبتك : المطور مالتي 😻🙊\n\n'
elseif is_owner(result.id, extra.chat2) then
text = text..'❣ رتبتك : مدير المجموعه 🌺😍\n\n'
elseif is_momod(result.id, extra.chat2) then
text = text..'❣ رتبتك : ادمن 👍🏻☺️\n\n'
else
text = text..'❣ رتبتك : مجرد عضو 😒💔\n\n'
end
else
text = text..'❣ رتبتك : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'❣ عدد الرسائل المرسله : '..user_info_msgs..'\n\n'
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, 'id not found.\nuse : /info @username', ok_cb, false)
end
end
local function action_by_reply(extra, success, result)-- (reply) /info function
if result.from.username then
Username = '@'..result.from.username
else
Username = '----'
end
local text = '❣ الاسم : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n'
..'❣ المعرف : '..Username..'\n'
..'❣ ايدي : '..result.from.id..'\n\n'
local hash = 'rank:'..result.to.id..':variables'
local value = redis:hget(hash, result.from.id)
if not value then
if result.from.id == tonumber(Arian) then
text = text..'❣ رتبتك :Executive Admin \n\n'
elseif is_sudo(result.from.id) then
text = text..'❣ رتبتك : المطور مالتي 😻🙊\n\n'
elseif is_owner(result.from.id, result.to.id) then
text = text..'❣ رتبتك : مدير المجموعه 🌺😍\n\n'
elseif is_momod(result.from.id, result.to.id) then
text = text..'❣ رتبتك : ادمن 👍🏻☺️\n\n'
else
text = text..'❣ رتبتك : مجرد عضو 😒💔\n\n'
end
else
text = text..'❣ رتبتك : '..value..'\n\n'
end
local user_info = {}
local uhash = 'user:'..result.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.from.id..':'..result.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'❣ عدد الرسائل المرسله : '..user_info_msgs..'\n\n'
send_msg(extra.receiver, text, ok_cb, true)
end
local function action_by_reply2(extra, success, result)
local value = extra.value
setrank(result, result.from.id, value)
end
local function run(msg, matches)
if matches[1]:lower() == 'setrank' then
local hash = 'usecommands:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
if not is_sudo(msg) then
return "😠 لآَ تـمسـلتَ أَلمطـور فـقطَ يفَـعل هأَذأَ ✔️👍"
end
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
local value = string.sub(matches[2], 1, 1000)
msgr = get_message(msg.reply_id, action_by_reply2, {receiver=receiver, Reply=Reply, value=value})
else
local name = string.sub(matches[2], 1, 50)
local value = string.sub(matches[3], 1, 1000)
local text = setrank(msg, name, value)
return text
end
end
if matches[1]:lower() == 'معلوماتي' and not matches[2] then
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver, Reply=Reply})
else
if msg.from.username then
Username = '@'..msg.from.username
else
Username = '----'
end
local text = '❣ الاسم الاول : '..(msg.from.first_name or '----')..'\n'
local text = text..'❣ الاسم الاخير : '..(msg.from.last_name or '----')..'\n'
local text = text..'❣ المعرف : '..Username..'\n'
local text = text..'❣ رقم هاتفك : '..(msg.from.phone or 'لايوجد')..'\n'
local text = text..'❣ ايدي : '..msg.from.id..'\n'
local text = text..'❣ اسم المجموعه : '..msg.to.title..'\n'
local text = text..'❣ ايدي المجموعه : '..msg.to.id..'\n'
local hash = 'rank:'..msg.to.id..':variables'
if hash then
local value = redis:hget(hash, msg.from.id)
if not value then
if msg.from.id == tonumber(Arian) then
text = text..'❣ رتبتك : Executive Admin \n\n'
elseif is_sudo(msg) then
text = text..'❣ رتبتك : المطور مالتي 😻🙊\n\n'
elseif is_owner(msg) then
text = text..'❣ رتبتك : مدير المجموعه 🌺😍\n\n'
elseif is_momod(msg) then
text = text..'❣ رتبتك : ادمن 👍🏻☺️\n\n'
else
text = text..'❣ رتبتك : مجرد عضو 😒💔\n\n'
end
else
text = text..'❣ رتبتك : '..value..'\n'
end
end
local uhash = 'user:'..msg.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..msg.from.id..':'..msg.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'❣ عدد الرسائل المرسله : '..user_info_msgs..'\n\n'
if msg.to.type == 'chat' then
text = text..'❣ اسم المجموعه : '..msg.to.title..'\n'
text = text..'❣ ايدي المجموعه : '..msg.to.id
end
return send_msg(receiver, text, ok_cb, true)
end
end
if matches[1]:lower() == 'معلوماتي' and matches[2] then
local user = matches[2]
local chat2 = msg.to.id
local receiver = get_receiver(msg)
if string.match(user, '^%d+$') then
user_info('user#id'..user, action_by_id, {receiver=receiver, user=user, text=text, chat2=chat2})
elseif string.match(user, '^@.+$') then
username = string.gsub(user, '@', '')
msgr = res_user(username, res_user_callback, {receiver=receiver, user=user, text=text, chat2=chat2})
end
end
end
return {
description = 'Know your information or the info of a chat members.',
usage = {
'!info: Return your info and the chat info if you are in one.',
'(Reply)!info: Return info of replied user if used by reply.',
'!info <id>: Return the info\'s of the <id>.',
'!info @<user_name>: Return the member @<user_name> information from the current chat.',
'!setrank <userid> <rank>: change members rank.',
'(Reply)!setrank <rank>: change members rank.',
},
patterns = {
"^([Ii][Nn][Ff][Oo])$",
"^([Ii][Nn][Ff][Oo]) (.*)$",
"^(معلوماتي)$",
"^(معلوماتي)(.*)$",
"^([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$",
"^([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$"
},
run = run
}
end
| gpl-3.0 |
Xkeeper0/emu-lua | nes-fceux/irc game genie engine/main.lua | 1 | 6975 |
-- Twitch.tv
local user = "xkeeper_"
local pass = "*"
local ircserver = "irc.twitch.tv"
local ircchannel = "#xkeeper_"
package.path = package.path .. ";./?/init.lua"
local playBoy = nil -- the PlayBoy instance.
local chat = nil
local socket = require("socket")
ggCodeMaxLife = 5000
resetStrings = {
"GAMEOVER ... Wiping codes.",
"Your codes suck. NoFun Try that again.",
"CatBag AndKnuckles Clearing codes.",
"WanWan MiniK MiniC CatBagChamp Nice crash!",
"WanWan WanBag woof AWOO",
"CatBagSleeper game froze.",
"CabBag Restarting driver.",
"GatoBolso Empezar de nuevo.",
"BlushBag that was interesting.",
"FeaturingDanteFromTheDevilMayCrySeries AndKnuckles and also resets.",
"BlushBag CatBagBack GatoBolso BagCat CatBagChamp CatBag CatBagSleeper SwagBag WanBag",
"FrankerZ LilZ GAMEOVER ZliL ZreknarF",
"GAMEOVER AndKnuckles",
"NoFun CatBagSleeper",
"WanWan bark",
}
resetStringsC = 15
function displayGGCodes()
local x = 227
local y = -13
if timer - 3 < timergg or true then
--if table.getn(gameGenieCodes) > 0 then
-- gui.box(x - 10, y + 9, x + 28, y + 10 + 8 * table.getn(gameGenieCodes), "#000000a0", "#000000a0")
--end
local n = 1
local rem = nil
local codes = table.getn(gameGenieCodes)
for k, v in ipairs(gameGenieCodes) do
-- --[[
local lifepct = v.life / ggCodeMaxLife
if not rem and v.life <= 0 then
rem = v.code
end
v.life = v.life - (codes - k)
local c = ((v.life / codes) < 30) and (math.fmod(gtimer, 2) == 0 and "white" or "#ffffff") or "#ffffff"
local cdisplay = v.isRAM and string.format("%03X=%02X", v.code, v.value) or v.code
if v.isRAM then
-- what a great place to write this, ne?
memory.writebyte(v.code, v.value)
end
gui.box(x - 10, y + 10 + 11 * k, x - 10 + (lifepct * 38), y + 10 + 11 * k + 2, "#ffffff", "black")
--]]
gui.box(x - 10, y + 2 + 11 * k, x + 28, y + 2 + 11 * k + 10, "#000000a0", "#000000a0")
gui.text(x - 9, y + 3 + 11 * k, cdisplay, c, "clear")
n = n + 1
end
if rem then
removeGGCode(rem)
end
end
end
function isGGCodeActive(code)
for k, v in ipairs(gameGenieCodes) do
if v.code == code then
return k
end
end
return false
end
function addGGCode(code, name, isRAM, value)
timergg = timer
if not isGGCodeActive(code) then
table.insert(gameGenieCodes, { code = code, life = ggCodeMaxLife, isRAM = isRAM, value = value })
if not isRAM then
emu.addgamegenie(code)
end
else
-- removeGGCode(code)
-- addGGCode(code)
end
end
function wipeGGCodes()
for k, v in ipairs(gameGenieCodes) do
if not v.isRAM then
emu.delgamegenie(v.code)
end
end
gameGenieCodes = {}
end
function removeGGCode(code)
local codeNum = isGGCodeActive(code)
if codeNum then
if not gameGenieCodes[codeNum].isRAM then
emu.delgamegenie(code)
end
table.remove(gameGenieCodes, codeNum)
end
end
do
local crashCheck = 0
function resetCrashDetection()
crashCheck = 0
end
function doCrashCheck()
--gui.text(1, 1, writes0000)
if writes0000 <= 20 or writes0000 >= 120 then -- @todo: configurable
--if writes0000 < 1 or writes0000 >= 10 then -- @todo: configurable
crashCheck = crashCheck + 1
else
crashCheck = 0
end
if crashCheck > 15 then -- @todo: configurable
return true
end
return false
end
end
function memoryCheck()
writes0000 = writes0000 + 1
end
function doIRCBullshit()
timer = timer + 1/59
if timer - 5 > timer2 then
chat:sendCommand("PING", ":".. tostring(math.random(0, 9999999)))
timer2 = timer
end
repeat
message = playBoy:update(dt)
if message then
-- :Xkeeper!xkeeper@netadmin.badnik.net PRIVMSG #fart :gas
--local name, key = string.match(message, ":(.+)!.+ PRIVMSG #.+ :([^ ]+)")
--* :irc.glados.tv PONG :irc.glados.tv 5831781
--* :Xkeeper!Xkeeper@ip.Xkeeper.chat.hitbox.tv PRIVMSG #xkeeper :reset
local name, msg = string.match(message, "^:([^!]+)![^ ]+ PRIVMSG #.+ :(.*)")
code = nil
if msg then
code = string.match(msg, "^([AEPOZXLUGKISTVYNaepozxlugkistvyn]+)")
raddr, rvalue, rimm = string.match(msg, "^([0-9A-Fa-f]+)[ =]+([0-9A-Fa-f]+)(!?)")
if string.lower(msg:sub(1, 6)) == "remove" then
code = string.match(msg:sub(8), "^([AEPOZXLUGKISTVYNaepozxlugkistvyn]+)")
if code and string.len(code) == 6 then
code = string.upper(code)
removeGGCode(code)
print(name .. "> Removing code ".. code)
end
elseif raddr and rvalue then
local addr = tonumber(raddr, 16)
local value = tonumber(rvalue, 16)
if (addr <= 0x7FF) and (value <= 0xFF) then
if rimm and rimm == "!" then
-- One time write
print(name .." > Write immediate: ".. string.format("%04X = %02X", addr, value))
memory.writebyte(addr, value)
else
print(name .." > Adding mem: ".. string.format("%04X = %02X", addr, value))
-- game genie add here
addGGCode(addr, nil, true, value)
end
end
elseif code and string.len(code) == 6 then
code = string.upper(code)
print(name .." > Adding code: ".. code)
-- game genie add here
addGGCode(code)
elseif string.lower(msg) == "clear" then
-- Clear all game genie codes
print(name .." > Clearing all codes")
wipeGGCodes()
elseif string.lower(msg) == "reset" then
-- Reset the game
print(name .." > Resetting game")
resetGame()
else
print(name .."> ".. msg)
end
else
print("* ".. message);
end
end
until not message
end
function resetGame()
--savestate.load(state)
emu.poweron()
end
lastcrashmsg = 0
crashtimer = 0
gtimer = 0
timer = 0
timer2 = 0
timergg = 0
gameGenieCodes = {}
writes0000 = 0
memory.registerwrite(0x0000, memoryCheck)
state = savestate.object(1)
-- --[[
playBoy = require("playboy"):new(ircserver, 6667, user, user, user, ircchannel, pass)
playBoy:connect()
chat = playBoy:returnChat()
chat:sendChatMessage(ircchannel, "[*] connected to chat. let's get this party started WanWan")
--]]
while true do
memory.writebyte(0x07A2, 0) -- start demo immediately
memory.writebyte(0x0750, math.random(0, 0xFF)) -- write random areas
memory.writebyte(0x0717, math.fmod(memory.readbyte(0x0717), 0x10)) -- keep demo going infinitely
doIRCBullshit()
displayGGCodes()
local crashed = doCrashCheck()
inpt = input.get()
if inpt['X'] then
wipeGGCodes()
end
if crashed then
print("RIP. CT = ".. crashtimer)
if crashtimer <= 60 then
wipeGGCodes()
if lastcrashmsg < 0 then
local chatMsg = resetStrings[math.random(1, resetStringsC)]
chat:sendChatMessage(ircchannel, "[*] " .. chatMsg)
lastcrashmsg = 600
end
end
resetGame()
crashtimer = 0
resetCrashDetection()
end
writes0000 = 0
emu.frameadvance()
crashtimer = crashtimer + 1
gtimer = gtimer + 1
lastcrashmsg = lastcrashmsg - 1
end
| mit |
thedraked/darkstar | scripts/zones/Port_Windurst/npcs/Kameel.lua | 30 | 1272 | -----------------------------------
-- Area: Port Windurst
-- NPC: Kameel
-- Type: Standard NPC
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local vHour = VanadielHour();
local vMin = VanadielMinute();
while vHour >= 4 do
vHour = vHour - 6;
end
if ( vHour == -2) then vHour = 4;
elseif ( vHour == -1) then vHour = 5;
end
local seconds = math.floor(2.4 * ((vHour * 60) + vMin));
player:startEvent( 0x00C1, seconds, 0, 0, 0, 0, 0, 0, 0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Xkeeper0/emu-lua | playstation-pscx/silent hill/silenthill.lua | 1 | 15469 | require "x_functions";
-- Set to "true" to disable all hotkeys
-- Set to "false" to enable hotkeys
NO_HOT_KEYS = true
-- -------------------------------------------------------------------------------
function forcez()
if memory.readdwordsigned(0x800BA028) == 32768 then
memory.writedword(0x800BA028, 26000);
end;
end;
function drawmap(x, y)
--gui.gdoverlay(0, 0, mapimage, 0.25);
locx = memory.readdwordsigned(0x800BA024);
locy = memory.readdwordsigned(0x800BA02C);
drawmapdot(x, y, locx, locy, "#ff00ff");
--[[
locx = 623575;
locy = 502062;
drawmapdot(x, y, locx, locy);
locx = 82662;
locy = 230944;
drawmapdot(x, y, locx, locy);
locx = 0;
locy = 0;
drawmapdot(x, y, locx, locy, "#ff0000");
locx = 0;
locy = -1500000;
drawmapdot(x, y, locx, locy, "#ff00ff");
--]]
end;
function drawmapdot(x, y, posx, posy, c)
if not c then
c = "#ffffff";
end;
xadd = 1622739;
xdiv = 17500;
yadd = 987500;
ydiv = 17500;
mapx = math.floor((posx + xadd) / xdiv);
mapy = 112 - math.floor((posy + yadd) / ydiv);
if (mapx < 0 or mapx > 160) and mapy >= 0 and mapy <= 120 then
if mapx < 0 then
line( 4 + x, mapy + y - 2, 5 + x, mapy + y - 2, c);
line( 2 + x, mapy + y - 1, 5 + x, mapy + y - 1, c);
line( 0 + x, mapy + y + 0, 5 + x, mapy + y + 0, c);
line( 2 + x, mapy + y + 1, 5 + x, mapy + y + 1, c);
line( 4 + x, mapy + y + 2, 5 + x, mapy + y + 2, c);
text( 7 + x, mapy + y - 3, string.format("%d", mapx * -1));
else
line( 155 + x, mapy + y - 2, 156 + x, mapy + y - 2, c);
line( 155 + x, mapy + y - 1, 158 + x, mapy + y - 1, c);
line( 155 + x, mapy + y + 0, 160 + x, mapy + y + 0, c);
line( 155 + x, mapy + y + 1, 158 + x, mapy + y + 1, c);
line( 155 + x, mapy + y + 2, 156 + x, mapy + y + 2, c);
text( 139 + x, mapy + y - 3, string.format("%4d", mapx - 160));
end;
elseif (mapx >= 0 and mapx <= 160) and (mapy < 0 or mapy >= 120) then
if mapy < 0 then
line( -2 + mapx + x, y + 4, -2 + mapx + x, y + 5, c);
line( -1 + mapx + x, y + 2, -1 + mapx + x, y + 5, c);
line( 0 + mapx + x, y + 0, 0 + mapx + x, y + 5, c);
line( 1 + mapx + x, y + 2, 1 + mapx + x, y + 5, c);
line( 2 + mapx + x, y + 4, 2 + mapx + x, y + 5, c);
text( -5 + mapx + x, y + 6, string.format("%3d", mapy * -1));
else
line( -2 + mapx + x, y + -5 + 120, -2 + mapx + x, y + -4 + 120, c);
line( -1 + mapx + x, y + -5 + 120, -1 + mapx + x, y + -2 + 120, c);
line( 0 + mapx + x, y + -5 + 120, 0 + mapx + x, y + -0 + 120, c);
line( 1 + mapx + x, y + -5 + 120, 1 + mapx + x, y + -2 + 120, c);
line( 2 + mapx + x, y + -5 + 120, 2 + mapx + x, y + -4 + 120, c);
text( -5 + mapx + x, y + -12 + 120, string.format("%3d", mapy - 120));
end;
else
box (mapx - 1 + x, mapy - 1 + y, mapx + 1 + x, mapy + 1 + y, c);
pixel(mapx - 1 + x, mapy - 1 + y, mapx + 1 + x, mapy + 1 + y, c);
end;
end;
function quickscreen(x, y, fmt, addr, isnotaddr)
local crud = addr;
if not isnotaddr then
-- double negatives
crud = memory.readdwordsigned(addr);
end;
gui.text(x, y * 8, string.format(fmt, crud));
end;
function quickscreen2(x, y, fmt, addr, isnotaddr)
local crud = addr;
if not isnotaddr then
-- double negatives
crud = memory.readwordsigned(addr);
end;
gui.text(x, y * 8, string.format(fmt, crud));
end;
function forcecam()
-- Force X, Y, Z
memory.writedword(0x800B9D20, memory.readdwordsigned(0x800BA024));
memory.writedword(0x800B9D28, memory.readdwordsigned(0x800BA02C));
memory.writedword(0x800B9D24, memory.readdwordsigned(0x800BA028) - 0xC000);
-- Z is set a ways above the player to give top-down perspective
-- Force straight-down
memory.writeword(0x800B9D8a, 0);
memory.writeword(0x800B9D88, -1000);
memory.writeword(0x800B9D8c, 0);
end;
function rangediv(min, max, val, mlt)
if not mlt then
mlt = 1;
end;
local base = min + max;
local val2 = val + min;
return math.min(math.max(0, val2 / base), 1) * mlt;
end;
derp = false;
fcam = false;
-- memory.register(0x0BA028, forcez);
last = {};
--[[
mapfile = assert(io.open("lua\\map.gd", "rb"));
mapimage = mapfile:read("*all");
io.close(mapfile);
--]]
mspeed = 100;
timer = 0;
inkey = input.get();
showcam = false;
camforce = {
x = 0,
y = 0,
z = -0xC000,
pan = 0,
tilt = -1000,
roll = 0
}
camforcel = {
min = {
x = -0x80000,
y = -0x80000,
z = -0xC000,
pan = -2000,
tilt = -1000,
roll = 0
},
max = {
x = 0x80000,
y = 0x80000,
z = 0xC000,
pan = 2000,
tilt = -1000,
roll = 0
}
};
while true do
timer = timer + 1;
lastkey = table.clone(inkey);
inkey = input.get();
if NO_HOT_KEYS then
inkey = {}
inkey.xmouse = 0
inkey.ymouse = 0
end
if inkey['P'] and not lastkey['P'] then
showcam = not showcam;
end;
-- Status goes yellow below 0550 (1360)
-- Status goes orange below 0410 (1040)
-- -- Status pulsates faster if health goes below 0320 ( 800)
-- Status goes red if below 0270 ( 624)
-- -- Pulsates even faster if health goes below 00A0 ( 160)
-- Health drinks recover 640 HP
if inkey['numpad3'] or (inkey['numpad6'] and not lastkey['numpad6']) then
hpt = hpt + 1;
hp2 = math.floor(hpt / 0x100);
hp1 = math.fmod(hpt, 0x100);
memory.writeword(0x800BA0BE, hp2);
memory.writebyte(0x800BA0BD, hp1);
elseif inkey['numpad2'] or (inkey['numpad5'] and not lastkey['numpad5']) then
hpt = hpt - 1;
hp2 = math.floor(hpt / 0x100);
hp1 = math.fmod(hpt, 0x100);
memory.writeword(0x800BA0BE, hp2);
memory.writebyte(0x800BA0BD, hp1);
end;
-- if (inkey['M']) then
-- memory.writebyte(0x80B9FC8, 9);
-- text(1, 1, "fart");
-- end;
--[[
loct = memory.readdwordsigned(0x800B9E08);
camt = memory.readdwordsigned(0x801FFD70);
text( 100, 176, string.format("C Pos %8d %8d", loct, camt));
--]]
quickscreen(200, 1, "X %8d", 0x800BA024);
quickscreen(200, 2, "Y %8d", 0x800BA02C);
quickscreen(200, 3, "Z %8d", 0x800BA028);
quickscreen(200, 4, "A %8.2f", memory.readdwordsigned(0x800BA030) / 0x0FFFFFFF * 360, true);
quickscreen(260, 1, "DCamX %8d", 0x800B9D14);
quickscreen(260, 2, "DCamY %8d", 0x800B9D1C);
quickscreen(260, 3, "DCamZ %8d", 0x800B9D18);
quickscreen(260, 5, "Cam X %8d", 0x800B9D20);
quickscreen(260, 6, "Cam Y %8d", 0x800B9D28);
quickscreen(260, 7, "Cam Z %8d", 0x800B9D24);
quickscreen(260, 8, "Cam ? %8d", 0x800B9D2C);
quickscreen2(260, 10, "Pan %8d", 0x800B9D8a);
quickscreen2(260, 11, "Tilt %8d", 0x800B9D88);
quickscreen2(260, 12, "Roll %8d", 0x800B9D8c);
quickscreen2(240, 20, "HP %d/1600", 0x800BA0BD);
quickscreen(240, 21, "Winded: %8d", 0x800BA108);
--[[
quickscreen(130, 1, "Z1 %8d", 0x800B9DE8);
quickscreen(130, 2, "Z2 %8d", 0x800B9DF0);
quickscreen(130, 3, "Z3 %8d", 0x800BA028);
quickscreen(130, 4, "Z4 %8d", 0x800BA0F8);
quickscreen(130, 5, "Z5 %8d", 0x800C459C);
--]]
if inkey['Y'] then
memory.writedword(0x800B9DE8, 0);
memory.writedword(0x800B9DF0, 0);
memory.writedword(0x800BA028, 0);
memory.writedword(0x800BA0F8, 0);
memory.writedword(0x800C459C, 0);
end;
if inkey['P'] then
test = math.abs(math.sin(timer / 50) * 0xFFFF);
memory.writedword(0x800BC360, test);
end;
--[[
-- Camera movement speed; lock to 0 to stop camera from moving
quickscreen(260, 9, "CSpd? %8d", 0x800B9D30);
quickscreen(260, 10, "Cspd? %8d", 0x800B9D34);
quickscreen(260, 11, "Cspd? %8d", 0x800B9D38);
quickscreen(260, 12, "Cspd? %8d", 0x800B9D3C);
quickscreen2(260, 14, "RCm A %8d", 0x800B9D80);
quickscreen2(260, 15, "RCm B %8d", 0x800B9D82);
quickscreen2(260, 16, "RCm C %8d", 0x800B9D84);
quickscreen2(260, 17, "RCm D %8d", 0x800B9D86);
quickscreen2(260, 18, "RCm E %8d", 0x800B9D88);
quickscreen2(260, 19, "RCm F %8d", 0x800B9D8a);
quickscreen2(260, 20, "RCm G %8d", 0x800B9D8c);
quickscreen2(260, 21, "RCm H %8d", 0x800B9D8e);
--]]
if inkey['U'] then
gui.text(0, 20, "uuuuuuuuuuuuuuuu");
pukemode = math.ceil(math.sin(timer / 50) * 0x7FF);
-- memory.writeword(0x800B9D80, pukemode);
-- memory.writeword(0x800B9D82, pukemode);
-- memory.writeword(0x800B9D84, pukemode);
-- memory.writeword(0x800B9D86, pukemode);
memory.writeword(0x800B9D88, 0);
memory.writeword(0x800B9D8a, pukemode);
memory.writeword(0x800B9D8c, 0);
-- memory.writeword(0x800B9D8e, pukemode);
end;
--quickscreen(260, 8, "Cam ? %8d", 0x800B9D2C);
--quickscreen(260, 9, "Cam ? %8.2f", memory.readdwordsigned(0x800B9D2C) / 0xFFFF * 360, true);
if inkey['M'] then
forcecam();
else
fcam = false;
end;
if inkey['N'] then
memory.writedword(0x800B9D2C,
memory.readdwordsigned(0x800B9D2C) + 0x1000
);
gui.text(0, 8, "fart plus PLUS");
end;
wind = memory.readdword(0x800BA108);
mspeed = math.min(500, mspeed);
if inkey['left'] then
memory.writedword(0x800BA024, memory.readdwordsigned(0x800BA024) - mspeed);
text(100, 169, "LEEEEEEEFT");
mspeed = mspeed + 10;
elseif inkey['right'] then
memory.writedword(0x800BA024, memory.readdwordsigned(0x800BA024) + mspeed);
text(100, 169, "RIIIIIIGHT");
mspeed = mspeed + 10;
elseif inkey['up'] then
memory.writedword(0x800BA02C, memory.readdwordsigned(0x800BA02C) + mspeed);
text(100, 169, "UUUUUUUP");
mspeed = mspeed + 10;
elseif inkey['down'] then
memory.writedword(0x800BA02C, memory.readdwordsigned(0x800BA02C) - mspeed);
text(100, 169, "DOOOOOOWN");
mspeed = mspeed + 10;
elseif inkey['numpad1'] then
memory.writedword(0x800BA028, memory.readdwordsigned(0x800BA028) + mspeed);
text(100, 169, "HIGHHERRRRRRR");
mspeed = mspeed + 10;
elseif inkey['numpad0'] then
memory.writedword(0x800BA028, memory.readdwordsigned(0x800BA028) - mspeed);
text(100, 169, "LOWWWWERRRRRR");
mspeed = mspeed + 10;
else
mspeed = 100;
end;
temp1 = memory.readword(0x8006A5B8);
temp2 = memory.readword(0x8006A5BA);
temp3 = memory.readword(0x8006A594);
temp4 = memory.readword(0x8006A596);
-- text( 1, 30, string.format("?? %04X %04X %04X %04X", temp1, temp2, temp3, temp4));
-- text( 0, 130, string.format("0x800B9DFC = %08X", memory.readdword(0x800B9DFC)));
-- text( 0, 137, string.format("0x800B9FC8 = %08X", memory.readdword(0x800B9FC8)));
addresses = {
0x800B9DE4, -- X?
0x800B9DEC, -- Y? Seems higher than the other one
0x800B9DF4, -- Z? Bigger, doesn't react to input
0x800B9DFC, -- Z? Smaller, doesn't react to input either
0x800B9E24, -- Y? Seems lower than the other one
0x800B9E2C, -- ?
-- 0x800B9DE1,
-- 0x800B9DE2,
-- 0x800B9DE3,
-- 0x800B9DE9,
-- 0x800B9DEA,
-- 0x800B9DEB,
-- 0x800B9DED,
-- 0x800B9E21,
-- 0x800B9E22,
-- 0x800B9E23,
-- 0x800B9D45,
-- 0x800B9D46,
-- 0x800B9D47,
-- 0x800B9DE0,
-- 0x800B9DE4,
-- 0x800B9DE8,
-- 0x800B9DEC,
}
i = 1;
for k, v in pairs(addresses) do
i = i + 1;
vnow = memory.readdwordsigned(v);
-- text(1, i * 7 + 30, string.format("%08X = %12d", v, vnow));
update = true;
if last[v] then
chg = vnow - last[v][2];
if chg == 0 and not last[v][3] then
update = false;
end;
m = 1;
if chg == 0 and last[v][1] then
chgd = last[v][1];
else
chgd = chg;
end;
if chgd < 0 then
m = -1;
end;
-- box( 100, i * 7 + 33, 100 + math.sqrt(math.abs(chgd)) * m, i * 7 + 34, "#ff0000");
--text( 100, i * 7 + 30, math.sqrt(chg));
end;
if update then
last[v] = {chg, vnow};
else
last[v][3] = true;
end;
end;
-- pos1 = memory.readdwordsigned(0x800B9DE4);
-- lifebar( 50, 1, 200, 8, pos1 + 0x80000, 770000, "#ffffff", "#000000");
-- text( 120, 4, string.format("%11d", pos1));
-- pos2 = memory.readdwordsigned(0x800B9DEC);
-- lifebar( 50, 12, 200, 8, pos2 + 0x80000, 0xFFFFF, "#ffffff", "#000000");
-- text( 120, 15, string.format("%11d", pos2));
-- temp1 = memory.readdword(0x800B9D14);
-- text( 1, 30, string.format("%08X", temp1));
spd1 = last[0x800B9DE4][1];
spd2 = last[0x800B9DEC][1];
if spd1 and spd2 then
text(100, 100, string.format("%12d\n%12d", spd1, spd2));
spd1 = spd1 / 37.8;
spd2 = spd2 / -37.8;
line(128, 128, 128 + spd1, 128 + spd2, "#ffffff");
end;
xpos = memory.readdwordsigned(0x800B9DE4);
ypos = memory.readdwordsigned(0x800B9DEC);
--[[
xpos2 = 300000 + xpos;
xmax = 300000 + 770000;
ypos2 = 900000 - ypos;
ymax = 300000 + 600000;
xposa = xpos2 / xmax * 100 + 150;
yposa = ypos2 / ymax * 100 + 50;
-- box ( 150, 50, 250, 150, "#ffffff");
-- line( xposa, 40, xposa, 160, "#ffffff");
-- line( 140, yposa, 255, yposa, "#ffffff");
-- text(150, 50, string.format("X %d - Y %d", xposa, yposa));
--]]
if inkey['Z'] then
walkthroughwalls = true;
elseif inkey['X'] then
walkthroughwalls = false;
end;
if walkthroughwalls then
text( 255, 10, "NOCLIP");
memory.writeword(0x8006A5B8, 0xA997);
memory.writeword(0x8006A5BA, 0x0801);
memory.writeword(0x8006A694, 0xA9AE);
memory.writeword(0x8006A696, 0x0801);
-- memory.writeword(0x800BC35C, 0x0100); -- flashlight
else
memory.writeword(0x8006A5B8, 0x000C);
memory.writeword(0x8006A5BA, 0x1040);
memory.writeword(0x8006A694, 0x0134);
memory.writeword(0x8006A696, 0xAFA9);
-- memory.writeword(0x800BC35C, 0x0000);
end;
-- memory.writedword(0x800BCC08, 0xFFFFFFFF);
-- memory.writedword(0x800BCC0C, 0xFFFFFFFF);
-- memory.writedword(0x800BCC10, 0xFFFFFFFF);
drawmap(0, 0);
--[[
strange values:
0x800BC37A
0x800BC3AE
0x800BC4B2
0x800C4186
0x800CC933
0x800DDABE
0x800DFA39
0x801EEE12
]]
--[[
memory.writebyte(0x800BC37A, 0xFF);
memory.writebyte(0x800BC3AE, 0xFF);
memory.writebyte(0x800BC4B2, 0xFF);
memory.writebyte(0x800C4186, 0xFF);
memory.writebyte(0x800CC933, 0xFF);
memory.writebyte(0x800DDABE, 0xFF);
memory.writebyte(0x800DFA39, 0xFF);
memory.writebyte(0x801EEE12, 0xFF);
--]]
--[[
memory.writedword(0x800BC378, 0x00000000);
memory.writedword(0x800BC3AC, 0x00000000);
memory.writedword(0x800BC4B0, 0x00000000);
memory.writedword(0x800C4180, 0x44444444);
--]]
-- This magical piece of code turns the lights on (sometimes)
--quickscreen(0, 1, "%08x", 0x800C4180)
magic = 0x60606060
-- magic = magic * 0x00000001
-- magic = 0x20202020
for i = 0x00, 0x8F do
--quickscreen(0 + 40 * math.fmod(i, 4), math.floor(i / 4), "%08x", 0x800C4180 + 4 * i)
memory.writedword(0x800C4180 + 4 * i, magic);
--[[
-- wtf were these for again
memory.writedword(0x800CC930 + 4 * i, magic);
memory.writedword(0x800CC980 + 4 * i, magic);
memory.writedword(0x800DDAB0 + 4 * i, magic);
memory.writedword(0x801EEE10 + 4 * i, magic);
--]]
end;
memory.writedword(0x800C4180, 0x00000000);
-- memory.writedword(0x801A9150 + 4 * i, 0x10101010);
-- memory.writedword(0x801A9220 + 4 * i, 0x10101010);
-- text(240, 100, string.format("0x800BC37A = %02X", memory.readbyte(0x800BC37A)));
if showcam then
gui.box(0, 0, 100, 100, 0xffffffff);
menux = rangediv(camforcel['min']['x'], camforcel['max']['x'], camforce['x'], 100);
menuy = rangediv(camforcel['min']['y'], camforcel['max']['y'], camforce['y'], 100);
gui.line(0, menuy, 100, menuy, 0xffffffff);
gui.line(menux, 0, menux, 100, 0xffffffff);
if hitbox(inkey['xmouse'], inkey['ymouse'], inkey['xmouse'], inkey['ymouse'], 0, 0, 100, 100, "white", "red") then
gui.text(0, 0, "welp");
end;
--inpt['xmouse'] < 100 and inpt['ymouse'] < 100 then
end;
pcsx.frameadvance();
end; | mit |
alalazo/wesnoth | data/ai/micro_ais/cas/ca_forest_animals_new_rabbit.lua | 2 | 2749 | local H = wesnoth.require "helper"
local W = H.set_wml_action_metatable {}
local AH = wesnoth.require "ai/lua/ai_helper.lua"
local ca_forest_animals_new_rabbit = {}
function ca_forest_animals_new_rabbit:evaluation(cfg)
-- Put new rabbits on map if there are fewer than cfg.rabbit_number
-- To end this, we'll let the CA black-list itself
if (not cfg.rabbit_type) then return 0 end
return cfg.ca_score
end
function ca_forest_animals_new_rabbit:execution(cfg)
local number = cfg.rabbit_number or 6
local rabbit_enemy_distance = cfg.rabbit_enemy_distance or 3
-- Get the locations of all items on that map (which could be rabbit holes)
W.store_items { variable = 'holes_wml' }
local all_items = H.get_variable_array('holes_wml')
W.clear_variable { name = 'holes_wml' }
-- Eliminate all holes that have an enemy within 'rabbit_enemy_distance' hexes
-- We also add a random number to the ones we keep, for selection of the holes later
local holes = {}
for _,item in ipairs(all_items) do
local enemies = AH.get_attackable_enemies {
{ "filter_location", { x = item.x, y = item.y, radius = rabbit_enemy_distance } }
}
if (not enemies[1]) then
-- If cfg.rabbit_hole_img is set, only items with that image or halo count as holes
if cfg.rabbit_hole_img then
if (item.image == cfg.rabbit_hole_img) or (item.halo == cfg.rabbit_hole_img) then
item.random = math.random(100)
table.insert(holes, item)
end
else
item.random = math.random(100)
table.insert(holes, item)
end
end
end
table.sort(holes, function(a, b) return a.random > b.random end)
local rabbits = wesnoth.get_units { side = wesnoth.current.side, type = cfg.rabbit_type }
number = number - #rabbits
number = math.min(number, #holes)
-- Now we simply take the first 'number' (randomized) holes
local tmp_unit = wesnoth.get_units { side = wesnoth.current.side }[1]
for i = 1,number do
local x, y = -1, -1
if tmp_unit then
x, y = wesnoth.find_vacant_tile(holes[i].x, holes[i].y, tmp_unit)
else
x, y = wesnoth.find_vacant_tile(holes[i].x, holes[i].y)
end
local command = "wesnoth.put_unit({ side = "
.. wesnoth.current.side
.. ", type = '"
.. cfg.rabbit_type
.. "' }, x1, y1)"
ai.synced_command(command, x, y)
end
if wesnoth.sides[wesnoth.current.side].shroud then
wesnoth.wml_actions.redraw { side = wesnoth.current.side }
end
end
return ca_forest_animals_new_rabbit
| gpl-2.0 |
mtroyka/Zero-K | LuaRules/Configs/MetalSpots/EvoRTS - Altored Divide - v10.lua | 12 | 3303 | return {
spots = {
{x = 5592, z = 856, metal = 2.15},
{x = 392, z = 2952, metal = 2.15},
{x = 5592, z = 2792, metal = 2.15},
{x = 2680, z = 904, metal = 2.15},
{x = 2408, z = 728, metal = 2.15},
{x = 5928, z = 504, metal = 2.15},
{x = 7640, z = 3832, metal = 2.15},
{x = 6024, z = 3080, metal = 4.3},
{x = 7784, z = 7208, metal = 2.15},
{x = 3912, z = 5176, metal = 2.15},
{x = 3256, z = 5272, metal = 2.15},
{x = 4168, z = 7832, metal = 2.15},
{x = 1032, z = 936, metal = 2.15},
{x = 7128, z = 872, metal = 2.15},
{x = 2712, z = 5176, metal = 2.15},
{x = 6424, z = 4168, metal = 2.15},
{x = 6088, z = 744, metal = 2.15},
{x = 3768, z = 7576, metal = 2.15},
{x = 4968, z = 1656, metal = 2.15},
{x = 968, z = 4328, metal = 2.15},
{x = 856, z = 1000, metal = 2.15},
{x = 856, z = 1224, metal = 2.15},
{x = 6632, z = 4248, metal = 2.15},
{x = 1356, z = 4517, metal = 2.15},
{x = 1491, z = 4460, metal = 2.15},
{x = 7944, z = 6488, metal = 2.15},
{x = 760, z = 7400, metal = 2.15},
{x = 3192, z = 4120, metal = 2.15},
{x = 5208, z = 7480, metal = 2.15},
{x = 2248, z = 7448, metal = 2.15},
{x = 1752, z = 7432, metal = 2.15},
{x = 3976, z = 7352, metal = 2.15},
{x = 7336, z = 7240, metal = 2.15},
{x = 3128, z = 3992, metal = 2.15},
{x = 5928, z = 7320, metal = 2.15},
{x = 4456, z = 7272, metal = 2.15},
{x = 4840, z = 4408, metal = 2.15},
{x = 1704, z = 6488, metal = 2.15},
{x = 184, z = 7336, metal = 2.15},
{x = 2200, z = 7176, metal = 2.15},
{x = 4008, z = 1016, metal = 2.15},
{x = 984, z = 1672, metal = 2.15},
{x = 6472, z = 1704, metal = 2.15},
{x = 6296, z = 4328, metal = 2.15},
{x = 7480, z = 4376, metal = 2.15},
{x = 2232, z = 4664, metal = 4.3},
{x = 3112, z = 2376, metal = 2.15},
{x = 7400, z = 824, metal = 2.15},
{x = 4280, z = 552, metal = 2.15},
{x = 4184, z = 3000, metal = 2.15},
{x = 1864, z = 7144, metal = 2.15},
{x = 1128, z = 1128, metal = 2.15},
{x = 7512, z = 4056, metal = 2.15},
{x = 6632, z = 3048, metal = 2.15},
{x = 5384, z = 7016, metal = 2.15},
{x = 5800, z = 6936, metal = 2.15},
{x = 7128, z = 6808, metal = 2.15},
{x = 4008, z = 3112, metal = 2.15},
{x = 5144, z = 5928, metal = 2.15},
{x = 5848, z = 5880, metal = 2.15},
{x = 104, z = 2856, metal = 2.15},
{x = 408, z = 5880, metal = 2.15},
{x = 4664, z = 4360, metal = 2.15},
{x = 7768, z = 5352, metal = 2.15},
{x = 7448, z = 4920, metal = 2.15},
{x = 7144, z = 7144, metal = 2.15},
{x = 4584, z = 4152, metal = 2.15},
{x = 2456, z = 1144, metal = 2.15},
{x = 6408, z = 2808, metal = 2.15},
{x = 7016, z = 5048, metal = 2.15},
{x = 7976, z = 2184, metal = 2.15},
{x = 408, z = 7032, metal = 2.15},
{x = 424, z = 3752, metal = 2.15},
{x = 4744, z = 2808, metal = 2.15},
{x = 2360, z = 2424, metal = 2.15},
{x = 6232, z = 568, metal = 2.15},
{x = 2232, z = 968, metal = 2.15},
{x = 1224, z = 3432, metal = 2.15},
{x = 840, z = 7096, metal = 2.15},
{x = 2792, z = 3832, metal = 2.15},
{x = 7432, z = 1208, metal = 2.15},
{x = 1896, z = 3736, metal = 2.15},
{x = 3976, z = 648, metal = 2.15},
{x = 7544, z = 968, metal = 2.15},
{x = 3832, z = 6440, metal = 2.15},
{x = 3592, z = 5240, metal = 2.15},
{x = 4392, z = 888, metal = 2.15},
}
} | gpl-2.0 |
xinmingyao/skynet | service/gate.lua | 23 | 1833 | local skynet = require "skynet"
local gateserver = require "snax.gateserver"
local netpack = require "netpack"
local watchdog
local connection = {} -- fd -> connection : { fd , client, agent , ip, mode }
local forwarding = {} -- agent -> connection
skynet.register_protocol {
name = "client",
id = skynet.PTYPE_CLIENT,
}
local handler = {}
function handler.open(source, conf)
watchdog = conf.watchdog or source
end
function handler.message(fd, msg, sz)
-- recv a package, forward it
local c = connection[fd]
local agent = c.agent
if agent then
skynet.redirect(agent, c.client, "client", 0, msg, sz)
else
skynet.send(watchdog, "lua", "socket", "data", fd, netpack.tostring(msg, sz))
end
end
function handler.connect(fd, addr)
local c = {
fd = fd,
ip = addr,
}
connection[fd] = c
skynet.send(watchdog, "lua", "socket", "open", fd, addr)
end
local function unforward(c)
if c.agent then
forwarding[c.agent] = nil
c.agent = nil
c.client = nil
end
end
local function close_fd(fd)
local c = connection[fd]
if c then
unforward(c)
connection[fd] = nil
end
end
function handler.disconnect(fd)
close_fd(fd)
skynet.send(watchdog, "lua", "socket", "close", fd)
end
function handler.error(fd, msg)
close_fd(fd)
skynet.send(watchdog, "lua", "socket", "error", fd, msg)
end
local CMD = {}
function CMD.forward(source, fd, client, address)
local c = assert(connection[fd])
unforward(c)
c.client = client or 0
c.agent = address or source
forwarding[c.agent] = c
gateserver.openclient(fd)
end
function CMD.accept(source, fd)
local c = assert(connection[fd])
unforward(c)
gateserver.openclient(fd)
end
function CMD.kick(source, fd)
gateserver.closeclient(fd)
end
function handler.command(cmd, source, ...)
local f = assert(CMD[cmd])
return f(source, ...)
end
gateserver.start(handler)
| mit |
Bpalkmim/ProjetoFinal | Logic/ConstantsForNatD.lua | 4 | 1536 | -------------------------------------------------------------------------------
-- Constants for Natural Deduction Module
--
-- Contains all the constants used by the Natural Deduction Logic Module.
--
-- @authors: Vitor, Jefferson, Bernardo
--
-------------------------------------------------------------------------------
-- Operators definitions
opAnd = {}
opAnd.tex = '\\land'
opAnd.print = '&'
opAnd.graph = "and"
opOr = {}
opOr.tex = '\\lor'
opOr.print = '|'
opOr.graph = "or"
opImp = {}
opImp.tex = '\\to'
opImp.print = '->'
opImp.graph = "imp"
opNot = {}
opNot.tex = '\\neg'
opNot.print = '~'
opNot.graph = "not"
lblBot = {}
lblBot.tex = '\\bot'
lblBot.print = 'Bottom'
lblBot.graph = "bot"
operators = {} -- Tabela que contém todos os operadores
operators[1] = opAnd
operators[2] = opOr
operators[3] = opImp
operators[4] = opNot
-- Labels for graph definitions
lblRootEdge = "root"
lblEdgeEsq = "left"
lblEdgeDir = "right"
lblEdgeDeduction = "DED"
lblEdgeImpIntro = "impIntro"
lblEdgeImpElim = "impElim"
lblEdgeHypothesis = "hyp"
lblEdgePredicate = "pred"
lblEdgeGoal = "Goal"
lblEdgeCounterModel = "COUNTER"
lblEdgeAccessability = "Access"
lblEdgeSatisfy = "sat"
lblEdgeUnsatisfy = "unsat"
lblFormulaReference = "ref"
lblNodeGG = "GG"
lblNodeEsq = "e"
lblNodeDir = "d"
lblNodeWorld = "w"
lblRuleImpLeft = "REMOVER IMPLY LEFT"
lblRuleImpRight = "REMOVER IMPLY RIGHT"
lblRuleImpIntro = "impIntro"
lblRuleImpElim = "impElim"
lblRuleRestart = "restart"
-- Side definitions
leftSide = "Left"
rightSide = "Right"
| gpl-2.0 |
savant2212/packages | net/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan/rule.lua | 80 | 4829 | -- ------ extra functions ------ --
function ruleCheck() -- determine if rules needs a proper protocol configured
uci.cursor():foreach("mwan3", "rule",
function (section)
local sourcePort = ut.trim(sys.exec("uci -p /var/state get mwan3." .. section[".name"] .. ".src_port"))
local destPort = ut.trim(sys.exec("uci -p /var/state get mwan3." .. section[".name"] .. ".dest_port"))
if sourcePort ~= "" or destPort ~= "" then -- ports configured
local protocol = ut.trim(sys.exec("uci -p /var/state get mwan3." .. section[".name"] .. ".proto"))
if protocol == "" or protocol == "all" then -- no or improper protocol
error_protocol_list = error_protocol_list .. section[".name"] .. " "
end
end
end
)
end
function ruleWarn() -- display warning messages at the top of the page
if error_protocol_list ~= " " then
return "<font color=\"ff0000\"><strong>WARNING: some rules have a port configured with no or improper protocol specified! Please configure a specific protocol!</strong></font>"
else
return ""
end
end
-- ------ rule configuration ------ --
dsp = require "luci.dispatcher"
sys = require "luci.sys"
ut = require "luci.util"
error_protocol_list = " "
ruleCheck()
m5 = Map("mwan3", translate("MWAN Rule Configuration"),
translate(ruleWarn()))
m5:append(Template("mwan/config_css"))
mwan_rule = m5:section(TypedSection, "rule", translate("Traffic Rules"),
translate("Rules specify which traffic will use a particular MWAN policy based on IP address, port or protocol<br />" ..
"Rules are matched from top to bottom. Rules below a matching rule are ignored. Traffic not matching any rule is routed using the main routing table<br />" ..
"Traffic destined for known (other than default) networks is handled by the main routing table. Traffic matching a rule, but all WAN interfaces for that policy are down will be blackholed<br />" ..
"Names may contain characters A-Z, a-z, 0-9, _ and no spaces<br />" ..
"Rules may not share the same name as configured interfaces, members or policies"))
mwan_rule.addremove = true
mwan_rule.anonymous = false
mwan_rule.dynamic = false
mwan_rule.sectionhead = "Rule"
mwan_rule.sortable = true
mwan_rule.template = "cbi/tblsection"
mwan_rule.extedit = dsp.build_url("admin", "network", "mwan", "configuration", "rule", "%s")
function mwan_rule.create(self, section)
TypedSection.create(self, section)
m5.uci:save("mwan3")
luci.http.redirect(dsp.build_url("admin", "network", "mwan", "configuration", "rule", section))
end
src_ip = mwan_rule:option(DummyValue, "src_ip", translate("Source address"))
src_ip.rawhtml = true
function src_ip.cfgvalue(self, s)
return self.map:get(s, "src_ip") or "—"
end
src_port = mwan_rule:option(DummyValue, "src_port", translate("Source port"))
src_port.rawhtml = true
function src_port.cfgvalue(self, s)
return self.map:get(s, "src_port") or "—"
end
dest_ip = mwan_rule:option(DummyValue, "dest_ip", translate("Destination address"))
dest_ip.rawhtml = true
function dest_ip.cfgvalue(self, s)
return self.map:get(s, "dest_ip") or "—"
end
dest_port = mwan_rule:option(DummyValue, "dest_port", translate("Destination port"))
dest_port.rawhtml = true
function dest_port.cfgvalue(self, s)
return self.map:get(s, "dest_port") or "—"
end
proto = mwan_rule:option(DummyValue, "proto", translate("Protocol"))
proto.rawhtml = true
function proto.cfgvalue(self, s)
return self.map:get(s, "proto") or "all"
end
sticky = mwan_rule:option(DummyValue, "sticky", translate("Sticky"))
sticky.rawhtml = true
function sticky.cfgvalue(self, s)
if self.map:get(s, "sticky") == "1" then
stickied = 1
return "Yes"
else
stickied = nil
return "No"
end
end
timeout = mwan_rule:option(DummyValue, "timeout", translate("Sticky timeout"))
timeout.rawhtml = true
function timeout.cfgvalue(self, s)
if stickied then
local timeoutValue = self.map:get(s, "timeout")
if timeoutValue then
return timeoutValue .. "s"
else
return "600s"
end
else
return "—"
end
end
ipset = mwan_rule:option(DummyValue, "ipset", translate("IPset"))
ipset.rawhtml = true
function ipset.cfgvalue(self, s)
return self.map:get(s, "ipset") or "—"
end
use_policy = mwan_rule:option(DummyValue, "use_policy", translate("Policy assigned"))
use_policy.rawhtml = true
function use_policy.cfgvalue(self, s)
return self.map:get(s, "use_policy") or "—"
end
errors = mwan_rule:option(DummyValue, "errors", translate("Errors"))
errors.rawhtml = true
function errors.cfgvalue(self, s)
if not string.find(error_protocol_list, " " .. s .. " ") then
return ""
else
return "<span title=\"No protocol specified\"><img src=\"/luci-static/resources/cbi/reset.gif\" alt=\"error\"></img></span>"
end
end
return m5
| gpl-2.0 |
SnabbCo/snabbswitch | src/apps/intel/intel_app.lua | 6 | 18343 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local basic_apps = require("apps.basic.basic_apps")
local ffi = require("ffi")
local lib = require("core.lib")
local shm = require("core.shm")
local counter = require("core.counter")
local pci = require("lib.hardware.pci")
local register = require("lib.hardware.register")
local macaddress = require("lib.macaddress")
local intel10g = require("apps.intel.intel10g")
local receive, transmit, empty = link.receive, link.transmit, link.empty
Intel82599 = {
config = {
pciaddr = {required=true},
mtu = {},
macaddr = {},
vlan = {},
vmdq = {},
mirror = {},
rxcounter = {default=0},
txcounter = {default=0},
rate_limit = {default=0},
priority = {default=1.0},
ring_buffer_size = {default=intel10g.ring_buffer_size()}
}
}
Intel82599.__index = Intel82599
local C = ffi.C
-- The `driver' variable is used as a reference to the driver class in
-- order to interchangably use NIC drivers.
driver = Intel82599
-- table pciaddr => {pf, vflist}
local devices = {}
local function firsthole(t)
for i = 1, #t+1 do
if t[i] == nil then
return i
end
end
end
-- Create an Intel82599 App for the device with 'pciaddress'.
function Intel82599:new (conf)
local self = {}
-- FIXME: ring_buffer_size is really a global variable for this
-- driver; taking the parameter as an initarg is just to make the
-- intel_mp transition easier.
intel10g.ring_buffer_size(conf.ring_buffer_size)
if conf.vmdq then
if devices[conf.pciaddr] == nil then
local pf = intel10g.new_pf(conf):open()
devices[conf.pciaddr] = { pf = pf,
vflist = {},
stats = { s = pf.s, r = pf.r, qs = pf.qs } }
end
local dev = devices[conf.pciaddr]
local poolnum = firsthole(dev.vflist)-1
local vf = dev.pf:new_vf(poolnum)
dev.vflist[poolnum+1] = vf
self.dev = vf:open(conf)
self.stats = devices[conf.pciaddr].stats
else
self.dev = assert(intel10g.new_sf(conf):open(), "Can not open device.")
self.stats = { s = self.dev.s, r = self.dev.r, qs = self.dev.qs }
self.zone = "intel"
end
if not self.stats.shm then
self.stats.shm = shm.create_frame(
"pci/"..conf.pciaddr,
{dtime = {counter, C.get_unix_time()},
mtu = {counter, self.dev.mtu},
speed = {counter, 10000000000}, -- 10 Gbits
status = {counter, 2}, -- Link down
promisc = {counter},
macaddr = {counter},
rxbytes = {counter},
rxpackets = {counter},
rxmcast = {counter},
rxbcast = {counter},
rxdrop = {counter},
rxerrors = {counter},
txbytes = {counter},
txpackets = {counter},
txmcast = {counter},
txbcast = {counter},
txdrop = {counter},
txerrors = {counter}})
self.stats.sync_timer = lib.throttle(0.001)
if not conf.vmdq and conf.macaddr then
counter.set(self.stats.shm.macaddr, macaddress:new(conf.macaddr).bits)
end
end
return setmetatable(self, Intel82599)
end
function Intel82599:stop()
local close_pf = nil
if self.dev.pf and devices[self.dev.pf.pciaddress] then
local poolnum = self.dev.poolnum
local pciaddress = self.dev.pf.pciaddress
local dev = devices[pciaddress]
if dev.vflist[poolnum+1] == self.dev then
dev.vflist[poolnum+1] = nil
end
if next(dev.vflist) == nil then
close_pf = devices[pciaddress].pf
devices[pciaddress] = nil
end
end
self.dev:close()
if close_pf then
close_pf:close()
end
if not self.dev.pf or close_pf then
shm.delete_frame(self.stats.shm)
end
end
function Intel82599:reconfig (conf)
assert((not not self.dev.pf) == (not not conf.vmdq), "Can't reconfig from VMDQ to single-port or viceversa")
self.dev:reconfig(conf)
if not self.dev.pf and conf.macaddr then
counter.set(self.stats.shm.macaddr,
macaddress:new(conf.macaddr).bits)
end
end
-- Allocate receive buffers from the given freelist.
function Intel82599:set_rx_buffer_freelist (fl)
self.rx_buffer_freelist = fl
end
-- Pull in packets from the network and queue them on our 'tx' link.
function Intel82599:pull ()
local l = self.output.tx
if l == nil then return end
self.dev:sync_receive()
for i = 1, engine.pull_npackets do
if not self.dev:can_receive() then break end
transmit(l, self.dev:receive())
end
self:add_receive_buffers()
if self.stats.sync_timer() then
self:sync_stats()
end
end
function Intel82599:rxdrop ()
return self.dev:rxdrop()
end
function Intel82599:add_receive_buffers ()
-- Generic buffers
while self.dev:can_add_receive_buffer() do
self.dev:add_receive_buffer(packet.allocate())
end
end
-- Synchronize self.stats.s/r a and self.stats.shm.
local link_up_mask = lib.bits{Link_up=30}
local promisc_mask = lib.bits{UPE=9}
function Intel82599:sync_stats ()
local counters = self.stats.shm
local s, r, qs = self.stats.s, self.stats.r, self.stats.qs
counter.set(counters.rxbytes, s.GORC64())
counter.set(counters.rxpackets, s.GPRC())
local mprc, bprc = s.MPRC(), s.BPRC()
counter.set(counters.rxmcast, mprc + bprc)
counter.set(counters.rxbcast, bprc)
-- The RX receive drop counts are only available through the RX stats
-- register. We only read stats register #0 here.
counter.set(counters.rxdrop, qs.QPRDC[0]())
counter.set(counters.rxerrors, s.CRCERRS() + s.ILLERRC() + s.ERRBC() +
s.RUC() + s.RFC() + s.ROC() + s.RJC())
counter.set(counters.txbytes, s.GOTC64())
counter.set(counters.txpackets, s.GPTC())
local mptc, bptc = s.MPTC(), s.BPTC()
counter.set(counters.txmcast, mptc + bptc)
counter.set(counters.txbcast, bptc)
if bit.band(r.LINKS(), link_up_mask) == link_up_mask then
counter.set(counters.status, 1) -- Up
else
counter.set(counters.status, 2) -- Down
end
if bit.band(r.FCTRL(), promisc_mask) ~= 0ULL then
counter.set(counters.promisc, 1) -- True
else
counter.set(counters.promisc, 2) -- False
end
end
-- Push packets from our 'rx' link onto the network.
function Intel82599:push ()
local l = self.input.rx
if l == nil then return end
while not empty(l) and self.dev:can_transmit() do
-- We must not send packets that are bigger than the MTU. This
-- check is currently disabled to satisfy some selftests until
-- agreement on this strategy is reached.
-- if p.length > self.dev.mtu then
-- counter.add(self.stats.shm.txdrop)
-- packet.free(p)
-- else
do local p = receive(l)
self.dev:transmit(p)
--packet.deref(p)
end
end
self.dev:sync_transmit()
end
-- Report on relevant status and statistics.
function Intel82599:report ()
print("report on intel device", self.dev.pciaddress or self.dev.pf.pciaddress)
register.dump(self.dev.s)
if self.dev.rxstats then
for name,v in pairs(self.dev:get_rxstats()) do
io.write(string.format('%30s: %d\n', 'rx '..name, v))
end
end
if self.dev.txstats then
for name,v in pairs(self.dev:get_txstats()) do
io.write(string.format('%30s: %d\n', 'tx '..name, v))
end
end
local function r(n)
return self.dev.r[n] or self.dev.pf.r[n]
end
register.dump({
r'TDH', r'TDT',
r'RDH', r'RDT',
r'AUTOC',
r'LINKS',
})
end
function selftest ()
print("selftest: intel_app")
local pcideva = lib.getenv("SNABB_PCI_INTEL0")
local pcidevb = lib.getenv("SNABB_PCI_INTEL1")
if not pcideva or not pcidevb then
print("SNABB_PCI_INTEL[0|1] not set or not suitable.")
os.exit(engine.test_skipped_code)
end
print ("100 VF initializations:")
manyreconf(pcideva, pcidevb, 100, false)
print ("100 PF full cycles")
manyreconf(pcideva, pcidevb, 100, true)
mq_sw(pcideva)
engine.main({duration = 1, report={showlinks=true, showapps=false}})
do
local a0Sends = link.stats(engine.app_table.nicAm0.input.rx).txpackets
local a1Gets = link.stats(engine.app_table.nicAm1.output.tx).rxpackets
-- Check propertions with some modest margin for error
if a1Gets < a0Sends * 0.45 or a1Gets > a0Sends * 0.55 then
print("mq_sw: wrong proportion of packets passed/discarded")
os.exit(1)
end
end
local device_info_a = pci.device_info(pcideva)
local device_info_b = pci.device_info(pcidevb)
sq_sq(pcideva, pcidevb)
if device_info_a.model == pci.model["82599_T3"] or
device_info_b.model == pci.model["82599_T3"] then
-- Test experience in the lab suggests that the 82599 T3 NIC
-- requires at least two seconds before it will reliably pass
-- traffic. The test case sleeps for this reason.
-- See https://github.com/SnabbCo/snabb/pull/569
C.usleep(2e6)
end
engine.main({duration = 1, report={showlinks=true, showapps=false}})
do
local aSends = link.stats(engine.app_table.nicA.input.rx).txpackets
local aGets = link.stats(engine.app_table.nicA.output.tx).rxpackets
local bSends = link.stats(engine.app_table.nicB.input.rx).txpackets
local bGets = link.stats(engine.app_table.nicB.output.tx).rxpackets
if bGets < aSends/2
or aGets < bSends/2
or bGets < aGets/2
or aGets < bGets/2
then
print("sq_sq: missing packets")
os.exit (1)
end
end
mq_sq(pcideva, pcidevb)
if device_info_a.model == pci.model["82599_T3"] or
device_info_b.model == pci.model["82599_T3"] then
C.usleep(2e6)
end
engine.main({duration = 1, report={showlinks=true, showapps=false}})
do
local aSends = link.stats(engine.app_table.nicAs.input.rx).txpackets
local b0Gets = link.stats(engine.app_table.nicBm0.output.tx).rxpackets
local b1Gets = link.stats(engine.app_table.nicBm1.output.tx).rxpackets
if b0Gets < b1Gets/2 or
b1Gets < b0Gets/2 or
b0Gets+b1Gets < aSends/2
then
print("mq_sq: missing packets")
os.exit (1)
end
end
print("selftest: ok")
end
-- open two singlequeue drivers on both ends of the wire
function sq_sq(pcidevA, pcidevB)
engine.configure(config.new())
local c = config.new()
print("-------")
print("Transmitting bidirectionally between nicA and nicB")
config.app(c, 'source1', basic_apps.Source)
config.app(c, 'source2', basic_apps.Source)
config.app(c, 'nicA', Intel82599, {pciaddr=pcidevA})
config.app(c, 'nicB', Intel82599, {pciaddr=pcidevB})
config.app(c, 'sink', basic_apps.Sink)
config.link(c, 'source1.out -> nicA.rx')
config.link(c, 'source2.out -> nicB.rx')
config.link(c, 'nicA.tx -> sink.in1')
config.link(c, 'nicB.tx -> sink.in2')
engine.configure(c)
end
-- one singlequeue driver and a multiqueue at the other end
function mq_sq(pcidevA, pcidevB)
local d1 = lib.hexundump ([[
52:54:00:02:02:02 52:54:00:01:01:01 08 00 45 00
00 54 c3 cd 40 00 40 01 f3 23 c0 a8 01 66 c0 a8
01 01 08 00 57 ea 61 1a 00 06 5c ba 16 53 00 00
00 00 04 15 09 00 00 00 00 00 10 11 12 13 14 15
16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25
26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35
36 37
]], 98) -- src: As dst: Bm0
local d2 = lib.hexundump ([[
52:54:00:03:03:03 52:54:00:01:01:01 08 00 45 00
00 54 c3 cd 40 00 40 01 f3 23 c0 a8 01 66 c0 a8
01 01 08 00 57 ea 61 1a 00 06 5c ba 16 53 00 00
00 00 04 15 09 00 00 00 00 00 10 11 12 13 14 15
16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25
26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35
36 37
]], 98) -- src: As dst: Bm1
engine.configure(config.new())
local c = config.new()
config.app(c, 'source_ms', basic_apps.Join)
config.app(c, 'repeater_ms', basic_apps.Repeater)
config.app(c, 'nicAs', Intel82599,
{-- Single App on NIC A
pciaddr = pcidevA,
macaddr = '52:54:00:01:01:01'})
config.app(c, 'nicBm0', Intel82599,
{-- first VF on NIC B
pciaddr = pcidevB,
vmdq = true,
macaddr = '52:54:00:02:02:02'})
config.app(c, 'nicBm1', Intel82599,
{-- second VF on NIC B
pciaddr = pcidevB,
vmdq = true,
macaddr = '52:54:00:03:03:03'})
print("-------")
print("Send traffic from a nicA (SF) to nicB (two VFs)")
print("The packets should arrive evenly split between the VFs")
config.app(c, 'sink_ms', basic_apps.Sink)
config.link(c, 'source_ms.output -> repeater_ms.input')
config.link(c, 'repeater_ms.output -> nicAs.rx')
config.link(c, 'nicAs.tx -> sink_ms.in1')
config.link(c, 'nicBm0.tx -> sink_ms.in2')
config.link(c, 'nicBm1.tx -> sink_ms.in3')
engine.configure(c)
link.transmit(engine.app_table.source_ms.output.output, packet.from_string(d1))
link.transmit(engine.app_table.source_ms.output.output, packet.from_string(d2))
end
-- one multiqueue driver with two apps and do switch stuff
function mq_sw(pcidevA)
local d1 = lib.hexundump ([[
52:54:00:02:02:02 52:54:00:01:01:01 08 00 45 00
00 54 c3 cd 40 00 40 01 f3 23 c0 a8 01 66 c0 a8
01 01 08 00 57 ea 61 1a 00 06 5c ba 16 53 00 00
00 00 04 15 09 00 00 00 00 00 10 11 12 13 14 15
16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25
26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35
36 37
]], 98) -- src: Am0 dst: Am1
local d2 = lib.hexundump ([[
52:54:00:03:03:03 52:54:00:01:01:01 08 00 45 00
00 54 c3 cd 40 00 40 01 f3 23 c0 a8 01 66 c0 a8
01 01 08 00 57 ea 61 1a 00 06 5c ba 16 53 00 00
00 00 04 15 09 00 00 00 00 00 10 11 12 13 14 15
16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25
26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35
36 37
]], 98) -- src: Am0 dst: ---
engine.configure(config.new())
local c = config.new()
config.app(c, 'source_ms', basic_apps.Join)
config.app(c, 'repeater_ms', basic_apps.Repeater)
config.app(c, 'nicAm0', Intel82599,
{-- first VF on NIC A
pciaddr = pcidevA,
vmdq = true,
macaddr = '52:54:00:01:01:01'})
config.app(c, 'nicAm1', Intel82599,
{-- second VF on NIC A
pciaddr = pcidevA,
vmdq = true,
macaddr = '52:54:00:02:02:02'})
print ('-------')
print ("Send a bunch of packets from Am0")
print ("half of them go to nicAm1 and half go nowhere")
config.app(c, 'sink_ms', basic_apps.Sink)
config.link(c, 'source_ms.output -> repeater_ms.input')
config.link(c, 'repeater_ms.output -> nicAm0.rx')
config.link(c, 'nicAm0.tx -> sink_ms.in1')
config.link(c, 'nicAm1.tx -> sink_ms.in2')
engine.configure(c)
link.transmit(engine.app_table.source_ms.output.output, packet.from_string(d1))
link.transmit(engine.app_table.source_ms.output.output, packet.from_string(d2))
end
function manyreconf(pcidevA, pcidevB, n, do_pf)
io.write ('\n')
local d1 = lib.hexundump ([[
52:54:00:02:02:02 52:54:00:01:01:01 08 00 45 00
00 54 c3 cd 40 00 40 01 f3 23 c0 a8 01 66 c0 a8
01 01 08 00 57 ea 61 1a 00 06 5c ba 16 53 00 00
00 00 04 15 09 00 00 00 00 00 10 11 12 13 14 15
16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25
26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35
36 37
]], 98) -- src: Am0 dst: Am1
local d2 = lib.hexundump ([[
52:54:00:03:03:03 52:54:00:01:01:01 08 00 45 00
00 54 c3 cd 40 00 40 01 f3 23 c0 a8 01 66 c0 a8
01 01 08 00 57 ea 61 1a 00 06 5c ba 16 53 00 00
00 00 04 15 09 00 00 00 00 00 10 11 12 13 14 15
16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25
26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35
36 37
]], 98) -- src: Am0 dst: ---
-- engine.configure(config.new())
local prevsent = 0
local cycles, redos, maxredos, waits = 0, 0, 0, 0
io.write("Running iterated VMDq test...\n")
for i = 1, (n or 100) do
local c = config.new()
config.app(c, 'source_ms', basic_apps.Join)
config.app(c, 'repeater_ms', basic_apps.Repeater)
config.app(c, 'nicAm0', Intel82599, {
-- first VF on NIC A
pciaddr = pcidevA,
vmdq = true,
macaddr = '52:54:00:01:01:01',
vlan = 100+i,
})
config.app(c, 'nicAm1', Intel82599, {
-- second VF on NIC A
pciaddr = pcidevA,
vmdq = true,
macaddr = '52:54:00:02:02:02',
vlan = 100+i,
})
config.app(c, 'sink_ms', basic_apps.Sink)
config.link(c, 'source_ms.output -> repeater_ms.input')
config.link(c, 'repeater_ms.output -> nicAm0.rx')
config.link(c, 'nicAm0.tx -> sink_ms.in1')
config.link(c, 'nicAm1.tx -> sink_ms.in2')
if do_pf then engine.configure(config.new()) end
engine.configure(c)
link.transmit(engine.app_table.source_ms.output.output, packet.from_string(d1))
link.transmit(engine.app_table.source_ms.output.output, packet.from_string(d2))
engine.main({duration = 0.1, no_report=true})
cycles = cycles + 1
redos = redos + engine.app_table.nicAm1.dev.pf.redos
maxredos = math.max(maxredos, engine.app_table.nicAm1.dev.pf.redos)
waits = waits + engine.app_table.nicAm1.dev.pf.waitlu_ms
local sent = link.stats(engine.app_table.nicAm0.input.rx).txpackets
io.write (('test #%3d: VMDq VLAN=%d; 100ms burst. packet sent: %s\n'):format(i, 100+i, lib.comma_value(sent-prevsent)))
if sent == prevsent then
io.write("error: NIC transmit counter did not increase\n")
os.exit(2)
end
end
io.write (pcidevA, ": avg wait_lu: ", waits/cycles, ", max redos: ", maxredos, ", avg: ", redos/cycles, '\n')
end
| apache-2.0 |
thedraked/darkstar | scripts/zones/Windurst_Waters/npcs/Pursuivant.lua | 14 | 1052 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Pursuivant
-- Type: Pursuivant
-- @zone 238
-- @pos 113.971 -3.077 51.524
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0366);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
thedraked/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Tombstone_Prototype.lua | 23 | 1257 | -----------------------------------
-- Area: Dynamis Xarcabard
-- MOB: Tombstone Prototype
-----------------------------------
package.loaded["scripts/zones/Dynamis-Xarcabard/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob,target)
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
local mobID = mob:getID();
-- Time Bonus: 010 060
if (mobID == 17330531 and mob:isInBattlefieldList() == false) then
player:addTimeToDynamis(30);
mob:addInBattlefieldList();
elseif (mobID == 17330830 and mob:isInBattlefieldList() == false) then
player:addTimeToDynamis(30);
mob:addInBattlefieldList();
end
end; | gpl-3.0 |
dmccuskey/dmc-utils | dmc_corona/lib/dmc_lua/lua_bytearray/pack_bytearray.lua | 7 | 6402 | --====================================================================--
-- dmc_lua/lua_bytearray/pack_bytearray.lua
--
-- Documentation: http://docs.davidmccuskey.com/
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2014-2015 David McCuskey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--[[
based off work from zrong(zengrong.net)
https://github.com/zrong/lua#ByteArray
https://github.com/zrong/lua/blob/master/lib/zrong/zr/utils/ByteArray.lua
--]]
--====================================================================--
--== DMC Lua Library: Lua Byte Array (pack)
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.0"
--====================================================================--
--== Imports
require 'pack'
--====================================================================--
--== Pack Byte Array Class
--====================================================================--
local ByteArray = {}
ByteArray.ENDIAN_LITTLE = 'endian_little'
ByteArray.ENDIAN_BIG = 'endian_big'
--====================================================================--
--== Public Methods
function ByteArray:readDouble()
self:_checkAvailable(8)
local _, val = string.unpack(self:readBuf(8), self:_getLC("d"))
return val
end
function ByteArray:writeDouble( double )
local str = string.pack( self:_getLC("d"), double )
self:writeBuf( str )
return self
end
function ByteArray:readFloat()
self:_checkAvailable(4)
local _, val = string.unpack(self:readBuf(4), self:_getLC("f"))
return val
end
function ByteArray:writeFloat( float )
local str = string.pack( self:_getLC("f"), float)
self:writeBuf( str )
return self
end
function ByteArray:readInt()
self:_checkAvailable(4)
local _, val = string.unpack(self:readBuf(4), self:_getLC("i"))
return val
end
function ByteArray:writeInt( int )
local str = string.pack( self:_getLC("i"), int )
self:writeBuf( str )
return self
end
function ByteArray:readLong()
self:_checkAvailable(8)
local _, val = string.unpack(self:readBuf(8), self:_getLC("l"))
return val
end
function ByteArray:writeLong( long )
local str = string.pack( self:_getLC("l"), long )
self:writeBuf( str )
return self
end
function ByteArray:readMultiByte( len )
error("not implemented")
return val
end
function ByteArray:writeMultiByte( int )
error("not implemented")
return self
end
function ByteArray:readStringBytes( len )
assert( len , "Need a length of the string!")
if len == 0 then return "" end
self:_checkAvailable( len )
local __, __v = string.unpack(self:readBuf( len ), self:_getLC( "A".. len ))
return __v
end
function ByteArray:writeStringBytes(__string)
local __s = string.pack(self:_getLC("A"), __string)
self:writeBuf(__s)
return self
end
function ByteArray:readStringUnsignedShort()
local len = self:readUShort()
return self:readStringBytes( len )
end
ByteArray.readStringUShort = ByteArray.readStringUnsignedShort
function ByteArray:writeStringUnsignedShort( ustr )
local str = string.pack(self:_getLC("P"), ustr )
self:writeBuf( str )
return self
end
ByteArray.writeStringUShort = ByteArray.writeStringUnsignedShort
function ByteArray:readShort()
self:_checkAvailable(2)
local _, val = string.unpack(self:readBuf(2), self:_getLC("h"))
return val
end
function ByteArray:writeShort( short )
local str = string.pack( self:_getLC("h"), short )
self:writeBuf( str )
return self
end
function ByteArray:readUnsignedByte()
self:_checkAvailable(1)
local _, val = string.unpack(self:readChar(), "b")
return val
end
ByteArray.readUByte = ByteArray.readUnsignedByte
function ByteArray:writeUnsignedByte( ubyte )
local str = string.pack("b", ubyte )
self:writeBuf( str )
return self
end
ByteArray.writeUByte = ByteArray.writeUnsignedByte
function ByteArray:readUInt()
self:_checkAvailable(4)
local _, val = string.unpack(self:readBuf(4), self:_getLC("I"))
return val
end
ByteArray.readUInt = ByteArray.readUnsignedInt
function ByteArray:writeUInt( uint )
local str = string.pack(self:_getLC("I"), uint )
self:writeBuf( str )
return self
end
ByteArray.writeUInt = ByteArray.writeUnsignedInt
function ByteArray:readUnsignedLong()
self:_checkAvailable(4)
local _, val = string.unpack(self:readBuf(4), self:_getLC("L"))
return val
end
ByteArray.readULong = ByteArray.readUnsignedLong
function ByteArray:writeUnsignedLong( ulong )
local str = string.pack( self:_getLC("L"), ulong )
self:writeBuf( str )
return self
end
ByteArray.writeULong = ByteArray.writeUnsignedLong
function ByteArray:readUnsignedShort()
self:_checkAvailable(2)
local _, val = string.unpack(self:readBuf(2), self:_getLC("H"))
return val
end
ByteArray.readUShort = ByteArray.readUnsignedShort
function ByteArray:writeUnsignedShort( ushort )
local str = string.pack(self:_getLC("H"), ushort )
self:writeBuf( str )
return self
end
ByteArray.writeUShort = ByteArray.writeUnsignedShort
--====================================================================--
--== Private Methods
function ByteArray:_getLC( format )
format = format or ""
if self._endian == ByteArray.ENDIAN_LITTLE then
return "<".. format
elseif self._endian == ByteArray.ENDIAN_BIG then
return ">".. format
end
return "=".. format
end
return ByteArray
| mit |
SnabbCo/snabbswitch | src/program/alarms/purge/purge.lua | 9 | 1999 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local common = require("program.config.common")
local lib = require("core.lib")
function show_usage(command, status, err_msg)
if err_msg then print('error: '..err_msg) end
print(require("program.alarms.purge.README_inc"))
main.exit(status)
end
local function fatal()
show_usage(nil, 1)
end
local function parse_args (args)
local handlers = {}
local opts = {}
local function table_size (t)
local count = 0
for _ in pairs(t) do count = count + 1 end
return count
end
local function without_opts (args)
local ret = {}
for i=1,#args do
local arg = args[i]
if opts[arg] then
i = i + 2
else
table.insert(ret, arg)
end
end
return ret
end
handlers['by-older-than'] = function (arg) opts.older_than = arg end
handlers['by-severity'] = function (arg) opts.severity = arg end
handlers['by-operator-state'] = function (arg)
opts.operator_state_filter = arg
end
args = lib.dogetopt(args, handlers, "", { ['by-older-than']=1,
['by-severity']=1, ['by-operator-state']=1 })
opts.status = table.remove(args, #args)
if table_size(opts) == 0 then fatal() end
local args = without_opts(args)
return opts, args
end
function run(args)
local l_args, args = parse_args(args)
local opts = { command='purge-alarms', with_path=false, is_config=false,
usage = show_usage }
args = common.parse_command_line(args, opts)
local response = common.call_leader(
args.instance_id, 'purge-alarms',
{ schema = args.schema_name, alarm_status = l_args.status,
older_than = l_args.older_than, severity = l_args.severity,
operator_state_filter = l_args.operator_state_filter,
print_default = args.print_default, format = args.format })
common.print_and_exit(response, "purged_alarms")
end
| apache-2.0 |
mtroyka/Zero-K | ModelMaterials_103/0_customskins.lua | 16 | 2011 | -- $Id$
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local materials = {
altSkinS3o = {
shaderDefinitions = {
},
shader = include("ModelMaterials/Shaders/default.lua"),
deferred = include("ModelMaterials/Shaders/default.lua"),
force = true,
usecamera = false,
culling = GL.BACK,
texunits = {
[0] = '%ALTSKIN',
[1] = '%ALTSKIN2',
[2] = '$shadow',
[3] = '$specular',
[4] = '$reflection',
[5] = '%NORMALTEX',
},
},
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local unitMaterials = {}
for i=1,#UnitDefs do
local udef = UnitDefs[i]
if (udef.customParams.altskin and VFS.FileExists(udef.customParams.altskin)) then
local tex2 = "%%"..i..":1"
unitMaterials[i] = {"altSkinS3o", ALTSKIN = udef.customParams.altskin, ALTSKIN2 = udef.customParams.altskin2 or tex2}
end --if
end --for
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local skinDefs = include("LuaRules/Configs/dynamic_comm_skins.lua")
for name, data in pairs(skinDefs) do
local altskin2 = data.altskin2
if not altskin2 then
altskin2 = "%%" .. UnitDefNames["dyn" .. data.chassis .. "0"].id .. ":1"
end
unitMaterials[name] = {"altSkinS3o", ALTSKIN = data.altskin, ALTSKIN2 = altskin2}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
return materials, unitMaterials
--------------------------------------------------------------------------------
-------------------------------------------------------------------------------- | gpl-2.0 |
filug/nodemcu-firmware | lua_modules/bmp085/bmp085.lua | 69 | 5037 | --------------------------------------------------------------------------------
-- BMP085 I2C module for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Christee <Christee@nodemcu.com>
--------------------------------------------------------------------------------
local moduleName = ...
local M = {}
_G[moduleName] = M
--default value for i2c communication
local id=0
--default oversampling setting
local oss = 0
--CO: calibration coefficients table.
local CO = {}
-- read reg for 1 byte
local function read_reg(dev_addr, reg_addr)
i2c.start(id)
i2c.address(id, dev_addr ,i2c.TRANSMITTER)
i2c.write(id,reg_addr)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr,i2c.RECEIVER)
local c=i2c.read(id,1)
i2c.stop(id)
return c
end
--write reg for 1 byte
local function write_reg(dev_addr, reg_addr, reg_val)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, reg_addr)
i2c.write(id, reg_val)
i2c.stop(id)
end
--get signed or unsigned 16
--parameters:
--reg_addr: start address of short
--signed: if true, return signed16
local function getShort(reg_addr, signed)
local tH = string.byte(read_reg(0x77, reg_addr))
local tL = string.byte(read_reg(0x77, (reg_addr + 1)))
local temp = tH*256 + tL
if (temp > 32767) and (signed == true) then
temp = temp - 65536
end
return temp
end
-- initialize i2c
--parameters:
--d: sda
--l: scl
function M.init(d, l)
if (d ~= nil) and (l ~= nil) and (d >= 0) and (d <= 11) and (l >= 0) and ( l <= 11) and (d ~= l) then
sda = d
scl = l
else
print("iic config failed!") return nil
end
print("init done")
i2c.setup(id, sda, scl, i2c.SLOW)
--get calibration coefficients.
CO.AC1 = getShort(0xAA, true)
CO.AC2 = getShort(0xAC, true)
CO.AC3 = getShort(0xAE, true)
CO.AC4 = getShort(0xB0)
CO.AC5 = getShort(0xB2)
CO.AC6 = getShort(0xB4)
CO.B1 = getShort(0xB6, true)
CO.B2 = getShort(0xB8, true)
CO.MB = getShort(0xBA, true)
CO.MC = getShort(0xBC, true)
CO.MD = getShort(0xBE, true)
end
--get temperature from bmp085
--parameters:
--num_10x: bool value, if true, return number of 0.1 centi-degree
-- default value is false, which return a string , eg: 16.7
function M.getUT(num_10x)
write_reg(0x77, 0xF4, 0x2E);
tmr.delay(10000);
local temp = getShort(0xF6)
local X1 = (temp - CO.AC6) * CO.AC5 / 32768
local X2 = CO.MC * 2048/(X1 + CO.MD)
local r = (X2 + X1 + 8)/16
if(num_10x == true) then
return r
else
return ((r/10).."."..(r%10))
end
end
--get raw data of pressure from bmp085
--parameters:
--oss: over sampling setting, which is 0,1,2,3. Default value is 0
function M.getUP_raw(oss)
local os = 0
if ((oss == 0) or (oss == 1) or (oss == 2) or (oss == 3)) and (oss ~= nil) then
os = oss
end
local ov = os * 64
write_reg(0x77, 0xF4, (0x34 + ov));
tmr.delay(30000);
--delay 30ms, according to bmp085 document, wait time are:
-- 4.5ms 7.5ms 13.5ms 25.5ms respectively according to oss 0,1,2,3
local MSB = string.byte(read_reg(0x77, 0xF6))
local LSB = string.byte(read_reg(0x77, 0xF7))
local XLSB = string.byte(read_reg(0x77, 0xF8))
local up_raw = (MSB*65536 + LSB *256 + XLSB)/2^(8 - os)
return up_raw
end
--get calibrated data of pressure from bmp085
--parameters:
--oss: over sampling setting, which is 0,1,2,3. Default value is 0
function M.getUP(oss)
local os = 0
if ((oss == 0) or (oss == 1) or (oss == 2) or (oss == 3)) and (oss ~= nil) then
os = oss
end
local raw = M.getUP_raw(os)
local B5 = M.getUT(true) * 16 - 8;
local B6 = B5 - 4000
local X1 = CO.B2 * (B6 * B6 /4096)/2048
local X2 = CO.AC2 * B6 / 2048
local X3 = X1 + X2
local B3 = ((CO.AC1*4 + X3)*2^os + 2)/4
X1 = CO.AC3 * B6 /8192
X2 = (CO.B1 * (B6 * B6 / 4096))/65536
X3 = (X1 + X2 + 2)/4
local B4 = CO.AC4 * (X3 + 32768) / 32768
local B7 = (raw -B3) * (50000/2^os)
local p = B7/B4 * 2
X1 = (p/256)^2
X1 = (X1 *3038)/65536
X2 = (-7357 *p)/65536
p = p +(X1 + X2 + 3791)/16
return p
end
--get estimated data of altitude from bmp085
--parameters:
--oss: over sampling setting, which is 0,1,2,3. Default value is 0
function M.getAL(oss)
--Altitudi can be calculated by pressure refer to sea level pressure, which is 101325
--pressure changes 100pa corresponds to 8.43m at sea level
return (M.getUP(oss) - 101325)*843/10000
end
return M | mit |
rjeli/luvit | tests/to-convert/test-tls-remote.lua | 5 | 1493 | --[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
require('helper')
local fixture = require('./fixture-tls')
local tls = require('tls')
local options = {
key = fixture.loadPEM('agent1-key'),
cert = fixture.loadPEM('agent1-cert')
}
local server = tls.createServer(options, function(s)
assert(s:address().address == s.socket:address().address)
assert(s:address().port == s.socket:address().port)
assert(s.remoteAddress == s.socket.remoteAddress)
assert(s.remotePort == s.socket.remotePort)
s:done()
end)
server:listen(fixture.commonPort, '127.0.0.1', function()
assert(server:address().address == '127.0.0.1')
assert(server:address().port == fixture.commonPort)
local c
c = tls.connect({port = fixture.commonPort, host = '127.0.0.1'}, function()
assert(c:address().address == c.socket:address().address)
assert(c:address().port == c.socket:address().port)
end)
c:on('end', function()
server:close()
end)
end)
| apache-2.0 |
Privateblackl/ultra | plugins/floodmanager.lua | 5 | 5901 | local function do_keyboard_flood(chat_id, ln)
--no: enabled, yes: disabled
local status = db:hget('chat:'..chat_id..':settings', 'Flood') or config.chat_settings['settings']['Flood'] --check (default: disabled)
if status == 'on' then
status = '✅ | ON'
elseif status == 'off' then
status = '❌ | OFF'
end
local hash = 'chat:'..chat_id..':flood'
local action = (db:hget(hash, 'ActionFlood')) or config.chat_settings['flood']['ActionFlood']
if action == 'kick' then
action = '⚡️ '..action
else
action = '⛔ ️'..action
end
local num = (db:hget(hash, 'MaxFlood')) or config.chat_settings['flood']['MaxFlood']
local keyboard = {
inline_keyboard = {
{
{text = status, callback_data = 'flood:status:'..chat_id},
{text = action, callback_data = 'flood:action:'..chat_id},
},
{
{text = '➖', callback_data = 'flood:dim:'..chat_id},
{text = num, callback_data = 'flood:alert:num'},
{text = '➕', callback_data = 'flood:raise:'..chat_id},
}
}
}
local exceptions = {
['text'] = lang[ln].floodmanager.text,
['sticker'] = lang[ln].floodmanager.sticker,
['image'] = lang[ln].floodmanager.image,
['gif'] = lang[ln].floodmanager.gif,
['video'] = lang[ln].floodmanager.video
}
hash = 'chat:'..chat_id..':floodexceptions'
for media, translation in pairs(exceptions) do
--ignored by the antiflood-> yes, no
local exc_status = (db:hget(hash, media)) or config.chat_settings['floodexceptions'][media]
if exc_status == 'yes' then
exc_status = '✅'
else
exc_status = '❌'
end
local line = {
{text = translation, callback_data = 'flood:alert:voice'},
{text = exc_status, callback_data = 'flood:exc:'..media..':'..chat_id},
}
table.insert(keyboard.inline_keyboard, line)
end
--back button
table.insert(keyboard.inline_keyboard, {{text = '🔙', callback_data = 'config:back:'..chat_id}})
return keyboard
end
local function action(msg, blocks)
if not msg.cb and msg.chat.type == 'private' then return end
local chat_id = msg.target_id or msg.chat.id
local text, keyboard
if blocks[1] == 'antiflood' then
if not roles.is_admin_cached(msg) then return end
if blocks[2]:match('%d%d?') then
if tonumber(blocks[2]) < 4 or tonumber(blocks[2]) > 25 then
api.sendReply(msg, make_text(lang[msg.ln].floodmanager.number_invalid, blocks[1]), true)
else
local new = tonumber(blocks[2])
local old = tonumber(db:hget('chat:'..msg.chat.id..':flood', 'MaxFlood')) or config.chat_settings['flood']['MaxFlood']
if new == old then
api.sendReply(msg, make_text(lang[msg.ln].floodmanager.not_changed, new), true)
else
db:hset('chat:'..msg.chat.id..':flood', 'MaxFlood', new)
api.sendReply(msg, make_text(lang[msg.ln].floodmanager.changed_plug, old, new), true)
end
end
return
end
else
if not msg.cb then return end --avaoid trolls
if blocks[1] == 'config' then
text = lang[msg.ln].floodmanager.header
keyboard = do_keyboard_flood(chat_id, msg.ln)
api.editMessageText(msg.chat.id, msg.message_id, text, keyboard, true)
return
end
if blocks[1] == 'alert' then
if blocks[2] == 'num' then
text = '⚖'..lang[msg.ln].floodmanager.number_cb
elseif blocks[2] == 'voice' then
text = '⚠️ '..lang[msg.ln].bonus.menu_cb_settings
end
api.answerCallbackQuery(msg.cb_id, text)
return
end
if blocks[1] == 'exc' then
local media = blocks[2]
local hash = 'chat:'..chat_id..':floodexceptions'
local status = (db:hget(hash, media)) or 'no'
if status == 'no' then
db:hset(hash, media, 'yes')
text = '❎ '..make_text(lang[msg.ln].floodmanager.ignored, media)
else
db:hset(hash, media, 'no')
text = '🚫 '..make_text(lang[msg.ln].floodmanager.not_ignored, media)
end
end
local action
if blocks[1] == 'action' or blocks[1] == 'dim' or blocks[1] == 'raise' then
if blocks[1] == 'action' then
action = (db:hget('chat:'..chat_id..':flood', 'ActionFlood')) or 'kick'
elseif blocks[1] == 'dim' then
action = -1
elseif blocks[1] == 'raise' then
action = 1
end
text = misc.changeFloodSettings(chat_id, action, msg.ln):mEscape_hard()
end
if blocks[1] == 'status' then
local status = db:hget('chat:'..chat_id..':settings', 'Flood') or config.chat_settings['settings']['Flood']
text = misc.changeSettingStatus(chat_id, 'Flood', msg.ln):mEscape_hard()
end
keyboard = do_keyboard_flood(chat_id, msg.ln)
api.editMessageText(msg.chat.id, msg.message_id, lang[msg.ln].floodmanager.header, keyboard, true)
api.answerCallbackQuery(msg.cb_id, text)
end
end
return {
action = action,
triggers = {
config.cmd..'(antiflood) (%d%d?)$',
'^###cb:flood:(alert):(%w+)$',
'^###cb:flood:(status):(-%d+)$',
'^###cb:flood:(action):(-%d+)$',
'^###cb:flood:(dim):(-%d+)$',
'^###cb:flood:(raise):(-%d+)$',
'^###cb:flood:(exc):(%a+):(-%d+)$',
'^###cb:(config):antiflood:'
}
} | gpl-2.0 |
NPLPackages/main | script/kids/3DMapSystemApp/WebBrowser/app_main.lua | 1 | 25158 | --[[
Title: WebBrowser app for Paraworld
Author(s): LiXizhi
Date: 2008/1/28
Desc:
---++ File.WebBrowser
other app can open an browser using this command with this app.
<verbatim>
Map3DSystem.App.Commands.Call("File.WebBrowser", url);
</verbatim>
---++ File.MCMLBrowser
the second param can be a table of {name, title, url, DisplayNavBar, x,y, width, height, icon, iconsize}
<verbatim>
Map3DSystem.App.Commands.Call("File.MCMLBrowser", {url="", name="MyBrowser", title="My browser", DisplayNavBar = true, DestroyOnClose=nil});
</verbatim>
| *name* | *desc* |
| url | mcml url |
| name | unique string of window name. |
| title | string of window title |
| DisplayNavBar | true to display navigation bar|
| DestroyOnClose | default to nil. if true, it will destroy the window if user clicks close window button |
---++ File.MCMLWindowFrame
create and show a window frame using pure mcml. app_key is for which application the winframe is created if nil WebBrowserApp key is used. name is the window name.
<verbatim>
-- show create
Map3DSystem.App.Commands.Call("File.MCMLWindowFrame", {url="", name="MyBrowser", app_key, bToggleShowHide=true, DestroyOnClose=nil, [win frame parameters]});
-- hide a window frame
Map3DSystem.App.Commands.Call("File.MCMLWindowFrame", {name="MyBrowser", app_key, bShow=false});
-- refresh page
Map3DSystem.App.Commands.Call("File.MCMLWindowFrame", {name="MyBrowser", app_key, bRefresh=true});
-- show page with advanced parameters
local params = {
url = "script/apps/Aries/Desktop/AriesMinRequirementPage.html",
name = "AriesMinRequirementWnd",
isShowTitleBar = false,
--DestroyOnClose = true, -- prevent many ViewProfile pages staying in memory
style = CommonCtrl.WindowFrame.ContainerStyle,
zorder = 2,
isTopLevel = true,
directPosition = true,
align = "_ct",
x = -550/2,
y = -380/2,
width = 550,
height = 380,
}
System.App.Commands.Call("File.MCMLWindowFrame", params);
params._page.OnClose = function()
end
</verbatim>
the second param can be a table with following field
| *name* | *desc* |
| url | mcml url |
| refresh | if true, it will refresh url even it is the same as last. |
| bShow | boolean: show or hide the window |
| bAutoSize, bAutoWidth, bAutoHeight | if true, the window size is based on the inner mcml page. Please note that one can still specify width and height of the window params. they are similar to the max size allowed. Page must be local in order for this to behave correctly. this may be improved in future. |
| bDestroy | if true, it will destroy the window |
| bRefresh | if true to refresh the page. only name and app_key input are required. |
| bToggleShowHide | if true, it will toggle show hide |
| DestroyOnClose | default to nil. if true, it will destroy the window if user clicks close window button |
| enable_esc_key | enable esc key. if true, the esc key will hide or close the window. |
| DesignResolutionWidth | |
| DesignResolutionHeight | |
| SelfPaint | use a render texture to paint on |
| [win frame parameters] | all windowsframe property are support. |
Return values are via input params table.
| _page | the page control object. One may overwrite the OnClose Method |
---++ File.WinExplorer
Open a file or directory using default windows explorer.
<verbatim>
Map3DSystem.App.Commands.Call("File.WinExplorer", "readme.txt");
-- silent mode.
Map3DSystem.App.Commands.Call("File.WinExplorer", {filepath="readme.txt", silentmode=true});
</verbatim>
the second param can be a table with following field
| *name* | *desc* |
| filepath | it can be relative or absolute file path |
| silentmode | boolean: if true, no dialog is displayed for confirmation. otherwise a dialog is displayed for confirmation. defrault to false. |
db registration insert script
INSERT INTO apps VALUES (NULL, 'WebBrowser_GUID', 'WebBrowser', '1.0.0', 'http://www.paraengine.com/apps/WebBrowser_v1.zip', 'YourCompany', 'enUS', 'script/kids/3DMapSystemApp/WebBrowser/IP.xml', '', 'script/kids/3DMapSystemApp/WebBrowser/app_main.lua', 'Map3DSystem.App.WebBrowser.MSGProc', 1);
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/kids/3DMapSystemApp/WebBrowser/app_main.lua");
------------------------------------------------------------
]]
NPL.load("(gl)script/kids/3DMapSystemApp/mcml/PageCtrl.lua");
-- create class
local WebBrowser = commonlib.gettable("Map3DSystem.App.WebBrowser");
-------------------------------------------
-- event handlers
-------------------------------------------
-- OnConnection method is the obvious point to place your UI (menus, mainbars, tool buttons) through which the user will communicate to the app.
-- This method is also the place to put your validation code if you are licensing the add-in. You would normally do this before putting up the UI.
-- If the user is not a valid user, you would not want to put the UI into the IDE.
-- @param app: the object representing the current application in the IDE.
-- @param connectMode: type of Map3DSystem.App.ConnectMode.
function Map3DSystem.App.WebBrowser.OnConnection(app, connectMode)
if(connectMode == Map3DSystem.App.ConnectMode.UI_Setup) then
-- TODO: place your UI (menus,toolbars, tool buttons) through which the user will communicate to the app
-- e.g. MainBar.AddItem(), MainMenu.AddItem().
-- e.g. Create a WebBrowser command link in the main menu
local commandName = "File.WebBrowser";
local command = Map3DSystem.App.Commands.GetCommand(commandName);
if(command ~= nil) then
local pos_category = commandName;
-- insert before File.GroupLast.
local index = Map3DSystem.UI.MainMenu.GetItemIndex("File.GroupLast");
-- add to front.
command:AddControl("mainmenu", pos_category, index);
end
else
-- place the app's one time initialization code here.
-- during one time init, its message handler may need to update the app structure with static integration points,
-- i.e. app.about, HomeButtonText, HomeButtonText, HasNavigation, NavigationButtonText, HasQuickAction, QuickActionText, See app template for more information.
-- e.g.
app.about = "Embedded web browser."
Map3DSystem.App.WebBrowser.app = app;
app.HideHomeButton = true;
local commandName = "File.WinExplorer";
local command = Map3DSystem.App.Commands.GetCommand(commandName);
if(command == nil) then
command = Map3DSystem.App.Commands.AddNamedCommand(
{name = commandName,app_key = app.app_key, ButtonText = L"外部浏览器", icon = app.icon, });
end
local commandName = "File.WebBrowser";
local command = Map3DSystem.App.Commands.GetCommand(commandName);
if(command == nil) then
command = Map3DSystem.App.Commands.AddNamedCommand(
{name = commandName,app_key = app.app_key, ButtonText = L"Web浏览器", icon = app.icon, });
end
local commandName = "File.MCMLBrowser";
local command = Map3DSystem.App.Commands.GetCommand(commandName);
if(command == nil) then
command = Map3DSystem.App.Commands.AddNamedCommand(
{name = commandName,app_key = app.app_key, ButtonText = L"MCML浏览器", icon="Texture/3DMapSystem/AppIcons/FrontPage_64.dds", });
end
local commandName = "File.MCMLWindowFrame";
local command = Map3DSystem.App.Commands.GetCommand(commandName);
if(command == nil) then
command = Map3DSystem.App.Commands.AddNamedCommand(
{name = commandName,app_key = app.app_key, ButtonText = "MCML Window Frame", icon = app.icon, });
end
local commandName = "File.DropFiles";
local command = Map3DSystem.App.Commands.GetCommand(commandName);
if(command == nil) then
command = Map3DSystem.App.Commands.AddNamedCommand(
{name = commandName,app_key = app.app_key, ButtonText = "drop file event", icon = app.icon, });
end
end
end
-- Receives notification that the Add-in is being unloaded.
function Map3DSystem.App.WebBrowser.OnDisconnection(app, disconnectMode)
if(disconnectMode == Map3DSystem.App.DisconnectMode.UserClosed or disconnectMode == Map3DSystem.App.DisconnectMode.WorldClosed)then
-- TODO: remove all UI elements related to this application, since the IDE is still running.
-- e.g. remove command from mainbar
local command = Map3DSystem.App.Commands.GetCommand("File.WebBrowser");
if(command == nil) then
command:Delete();
end
end
-- TODO: just release any resources at shutting down.
end
-- This is called when the command's availability is updated
-- When the user clicks a command (menu or mainbar button), the QueryStatus event is fired.
-- The QueryStatus event returns the current status of the specified named command, whether it is enabled, disabled,
-- or hidden in the CommandStatus parameter, which is passed to the msg by reference (or returned in the event handler).
-- @param commandName: The name of the command to determine state for. Usually in the string format "Category.SubCate.Name".
-- @param statusWanted: what status of the command is queried. it is of type Map3DSystem.App.CommandStatusWanted
-- @return: returns according to statusWanted. it may return an integer by adding values in Map3DSystem.App.CommandStatus.
function Map3DSystem.App.WebBrowser.OnQueryStatus(app, commandName, statusWanted)
if(statusWanted == Map3DSystem.App.CommandStatusWanted) then
-- return enabled and supported
return (Map3DSystem.App.CommandStatus.Enabled + Map3DSystem.App.CommandStatus.Supported)
end
end
-- message proc for File.MCMLWindowFrame
local function MCMLWinFrameMSGProc(window, msg)
if(msg.type == CommonCtrl.os.MSGTYPE.WM_CLOSE) then
local preVisibility = nil;
if(window and window:IsVisible() == true) then
preVisibility = true;
end
if(window.MyPage and window.MyPage.OnClose and not window.isOnCloseCalled) then
window.MyPage:OnClose(window.DestroyOnClose or msg.bDestroy);
end
-- fix a bug where on close is not called when window is show and closed immediately, instead of using preVisibility.
if(not window.isOnCloseCalled) then
window.isOnCloseCalled = true;
end
if(window.DestroyOnClose or msg.bDestroy) then
window:DestroyWindowFrame();
else
window:ShowWindowFrame(false);
end
-- NOTE 2009/11/10: if the hook is called before the close process, another File.MCMLWindowFrame bShow = false call will
-- find the window frame not destoryed or closed then it will also call the OnMCMLWindowFrameInvisible hook
-- call hook OnMCMLWindowFrameInvisible
if(preVisibility == true) then
local msg = { aries_type = "OnMCMLWindowFrameInvisible", name = window.name, wndName = "main"};
CommonCtrl.os.hook.Invoke(CommonCtrl.os.hook.HookType.WH_CALLWNDPROCRET, 0, "Aries", msg);
end
elseif(msg.type == CommonCtrl.os.MSGTYPE.WM_SHOW) then
if(msg.param1) then
window.isOnCloseCalled = false;
if(window.DesignResolutionWidth) then
System.Windows.Screen:PushDesignResolution(window.DesignResolutionWidth, window.DesignResolutionHeight)
end
else
if(window.DesignResolutionWidth) then
System.Windows.Screen:PopDesignResolution()
end
end
if(window.enable_esc_key) then -- and System.options.isAB_SDK
-- esc key logics here
if(msg.param1) then
window.esc_state = window.esc_state or {name = "McmlEscKey", OnEscKey = function()
window:SendMessage(nil,{type=CommonCtrl.os.MSGTYPE.WM_CLOSE});
end}
System.PushState(window.esc_state);
elseif(window.esc_state) then
System.PopState(window.esc_state)
end
end
-- commonlib.echo({"WM_SHOW", window.name, msg.param1}
elseif(msg.type == CommonCtrl.os.MSGTYPE.WM_DROPFILES) then
if(window.MyPage and window.MyPage.OnDropFiles) then
--window.MyPage:OnClose(window.DestroyOnClose or msg.bDestroy);
return window.MyPage.OnDropFiles(msg.filelist);
end
end
end
-- show File.MCMLWindowFrame in the parent window
-- @param bShow: boolean to show or hide. if nil, it will toggle current setting.
-- @param _parent: parent window inside which the content is displayed. it can be nil.
-- @param parentWindow: parent os window object, parent window for sending messages
local function MCMLWinFrameShow(bShow, _parent, parentWindow)
local page_name = tostring(_parent.id); -- use id of parent as the page name.
local _this = _parent:GetChild(page_name);
if(_this:IsValid())then
if(bShow==nil) then
bShow = not _this.visible;
end
if(_this.visible ~= bShow) then
_this.visible = bShow;
end
else
if(bShow == false) then return end
bShow = true;
parentWindow.MyPage = Map3DSystem.mcml.PageCtrl:new({url=parentWindow.url});
if(parentWindow.SelfPaint) then
parentWindow.MyPage.SelfPaint = true;
end
if(_parent:GetField("ClickThrough", false)) then
parentWindow.MyPage.click_through = true;
end
parentWindow.MyPage:Create(page_name, _parent, "_fi", 0, 0, 0, 0)
end
end
-- This is called when the command is invoked.The Exec is fired after the QueryStatus event is fired, assuming that the return to the statusOption parameter of QueryStatus is supported and enabled.
-- This is the event where you place the actual code for handling the response to the user click on the command.
-- @param commandName: The name of the command to determine state for. Usually in the string format "Category.SubCate.Name".
function Map3DSystem.App.WebBrowser.OnExec(app, commandName, params)
if(commandName == "File.WebBrowser") then
-- if params is nil, the current url is shown
-- if params is string, the url is params
-- if params is table {BrowserName, URL}, it opens a url with a given texture name.
-- e.g.
NPL.load("(gl)script/kids/3DMapSystemApp/WebBrowser/BrowserWnd.lua");
local url;
if(type(params) == "table") then
if(params.BrowserName~=nil) then
Map3DSystem.App.WebBrowser.BrowserWnd.BrowserName = params.BrowserName;
end
if(params.URL~=nil) then
url = params.URL;
end
elseif(type(params) == "string") then
url = params;
end
if(url~=nil) then
-- using mcml page instead
if(url ~= "#") then
if System.os.GetPlatform() == 'android' then
if (string.match(url, "screenOrientation=(%w+)") == "portrait") then
WebView.setOrientation(1)
commonlib.TimerManager.SetTimeout(function()
ParaGlobal.ShellExecute("open", url, "", "", 1);
end, 500)
return
end
end
ParaGlobal.ShellExecute("open", url, "", "", 1);
--NPL.load("(gl)script/kids/3DMapSystemApp/WebBrowser/OpenInBrowserDlgPage.lua");
--Map3DSystem.App.WebBrowser.OpenInBrowserDlgPage.Show(url)
else
_guihelper.MessageBox("本功能此版本中未开放,敬请期待");
end
else
Map3DSystem.App.WebBrowser.BrowserWnd.DisplayNavBar = true;
Map3DSystem.App.WebBrowser.BrowserWnd.ShowWnd(app._app)
end
elseif(commandName == "File.MCMLBrowser") then
if(type(params) == "string") then
params = {url = params};
elseif(type(params) ~= "table") then
params = {url="", name="MyMCMLBrowser", title="MCML browser", DisplayNavBar = true, DestroyOnClose=true};
--log("warning: File.MCMLBrowser command must have input of a table\n")
--return;
end
NPL.load("(gl)script/kids/3DMapSystemApp/WebBrowser/MCMLBrowserWnd.lua");
local _wnd = Map3DSystem.App.WebBrowser.MCMLBrowserWnd.ShowWnd(app._app, params)
elseif(commandName == "File.WinExplorer") then
if(type(params) == "string") then
params = {filepath = params};
elseif(type(params) ~= "table") then
log("warning: File.WinExplorer command must have input of a table\n")
return;
end
if(params.filepath~=nil) then
local absPath;
if(commonlib.Files.IsAbsolutePath(params.filepath)) then
absPath = params.filepath
else
absPath = ParaIO.GetCurDirectory(0)..params.filepath;
end
absPath = commonlib.Files.ToCanonicalFilePath(absPath);
if(absPath~=nil) then
NPL.load("(gl)script/ide/System/os/os.lua");
local platform = System.os.GetPlatform();
if platform == 'android' or platform == 'ios' then
return false;
end
if(not params.silentmode) then
if platform == 'win32' then
_guihelper.MessageBox(string.format(L"您确定要使用Windows浏览器打开文件 %s?", commonlib.Encoding.DefaultToUtf8(absPath)), function()
ParaGlobal.ShellExecute("open", "explorer.exe", absPath, "", 1);
end);
elseif platform == 'mac' then
_guihelper.MessageBox(string.format(L"路径:%s 已经复制到剪切板,请在Finder中打开", absPath), function()
ParaMisc.CopyTextToClipboard(absPath);
end);
else
_guihelper.MessageBox(string.format(L"您确定要使用文件浏览器打开文件 %s?", commonlib.Encoding.DefaultToUtf8(absPath)), function()
ParaGlobal.ShellExecute("open", "explorer.exe", absPath, "", 1);
end);
end
else
ParaGlobal.ShellExecute("open", "explorer.exe", absPath, "", 1);
end
end
end
elseif(commandName == "File.MCMLWindowFrame") then
if(GameLogic and GameLogic.GetFilters) then
params = GameLogic.GetFilters():apply_filters("File.MCMLWindowFrame", params) or params;
end
if(type(params) ~= "table" or not params.name) then
log("warning: File.MCMLWindowFrame command must have input of a table or name field is nonexistent\n")
return;
end
if(params.bAutoSize or params.bAutoWidth or params.bAutoHeight) then
if(params.cancelShowAnimation== nil) then
params.cancelShowAnimation = true;
end
end
params.app_key = params.app_key or app.app_key;
local _app = CommonCtrl.os.GetApp(params.app_key); -- Map3DSystem.App.AppManager.GetApp(params.app_key);
if(_app) then
local _wnd = _app:FindWindow(params.name) or _app:RegisterWindow(params.name, nil, MCMLWinFrameMSGProc);
if(params.bRefresh) then
if(_wnd.MyPage) then
_wnd.MyPage:Refresh(0);
end
elseif(params.bDestroy) then
-- hide the window
_wnd:SendMessage(nil,{type=CommonCtrl.os.MSGTYPE.WM_CLOSE, bDestroy=true});
elseif(params.bShow == false) then
-- hide the window
_wnd:SendMessage(nil,{type=CommonCtrl.os.MSGTYPE.WM_CLOSE});
else
-- show the window frame
local _wndFrame = _wnd:GetWindowFrame();
local isFrameExist = true;
if(not _wndFrame) then
isFrameExist = false;
params.wnd = _wnd;
params.ShowUICallback = MCMLWinFrameShow;
_wndFrame = _wnd:CreateWindowFrame(params);
end
_wnd.url = params.url or _wnd.url;
_wnd.DestroyOnClose = params.DestroyOnClose;
_wnd.enable_esc_key = params.enable_esc_key;
_wnd.DesignResolutionWidth = params.DesignResolutionWidth;
_wnd.DesignResolutionHeight = params.DesignResolutionHeight;
_wnd.SelfPaint = params.SelfPaint;
_wnd.isPinned = params.isPinned;
if(params.bToggleShowHide and params.bShow==nil) then
if(_wnd.MyPage and _wnd.MyPage.url~=_wnd.url and _wnd.url and _wnd.MyPage.url) then
_wnd:ShowWindowFrame(true);
else
if(_wnd.DestroyOnClose and _wnd:IsVisible()) then
_wnd:SendMessage(nil,{type=CommonCtrl.os.MSGTYPE.WM_CLOSE, bDestroy=true});
else
_wnd:ShowWindowFrame();
end
end
else
_wnd:ShowWindowFrame(true);
end
if(params.text or params.title or params.icon) then
_wnd:SetWindowText(params.text or params.title, params.icon)
end
-- refresh if url has changed.
if(_wnd.MyPage) then
if(not _wnd.MyPage.window) then
_wnd.MyPage.window = _wnd;
end
if(_wnd.MyPage.url~=_wnd.url or params.refresh or (_wnd.MyPage.url == _wnd.url and params.refreshEvenSameURLIfFrameExist and isFrameExist)) then
if(params.bAutoSize or params.bAutoWidth or params.bAutoHeight) then
_wndFrame:MoveWindow(nil, nil, params.width, params.height);
end
_wnd.MyPage:Goto(_wnd.url);
end
if(params.bAutoSize or params.bAutoWidth or params.bAutoHeight) then
-- adjust the size according to inner html page
local width, height = _wnd.MyPage:GetUsedSize();
if(width and height) then
if(params.align=="_ct") then
if(not params.bAutoSize and not params.bAutoWidth) then width=params.width or width end
if(not params.bAutoSize and not params.bAutoHeight) then height=params.height or height end
local left, top;
left, top = -math.floor(width / 2), -math.floor(height/2);
_wndFrame:Reposition(params.align, left, top, width, height);
else
if(not params.bAutoSize and not params.bAutoWidth) then width=nil end
if(not params.bAutoSize and not params.bAutoHeight) then height=nil end
_wndFrame:MoveWindow(left, top, width, height);
end
end
end
end
end
params._page = _wnd.MyPage;
else
commonlib.log("warning: app with app_key %s is not found when calling File.MCMLWindowFrame\n", params.app_key);
end
elseif (commandName == "File.DropFiles") then
local filelist = params;
if(filelist) then
params.app_key = params.app_key or app.app_key;
local _app = CommonCtrl.os.GetApp(params.app_key);
if (_app) then
local _wnd = _app:GetActiveWindow();
if _wnd then
-- return true to tell caller we're interested in this message
return _wnd:SendMessage(nil, {type = CommonCtrl.os.MSGTYPE.WM_DROPFILES, filelist = filelist});
end
end
end
elseif(app:IsHomepageCommand(commandName)) then
Map3DSystem.App.WebBrowser.GotoHomepage();
elseif(app:IsNavigationCommand(commandName)) then
Map3DSystem.App.WebBrowser.Navigate();
elseif(app:IsQuickActionCommand(commandName)) then
Map3DSystem.App.WebBrowser.DoQuickAction();
end
end
-- Change and render the 3D world with mcml data that is usually retrieved from the current user's profile page for this application.
function Map3DSystem.App.WebBrowser.OnRenderBox(mcmlData)
end
-- called when the user wants to nagivate to the 3D world location relavent to this application
function Map3DSystem.App.WebBrowser.Navigate()
end
-- called when user clicks to check out the homepage of this application. Homepage usually includes:
-- developer info, support, developer worlds information, app global news, app updates, all community user rating, active users, trade, currency transfer, etc.
function Map3DSystem.App.WebBrowser.GotoHomepage()
end
-- called when user clicks the quick action for this application.
function Map3DSystem.App.WebBrowser.DoQuickAction()
end
-------------------------------------------
-- client world database function helpers.
-------------------------------------------
------------------------------------------
-- all related messages
------------------------------------------
-----------------------------------------------------
-- APPS can be invoked in many ways:
-- Through app Manager
-- mainbar or menu command or buttons
-- Command Line
-- 3D World installed apps
-----------------------------------------------------
function Map3DSystem.App.WebBrowser.MSGProc(window, msg)
----------------------------------------------------
-- application plug-in messages here
----------------------------------------------------
if(msg.type == Map3DSystem.App.MSGTYPE.APP_CONNECTION) then
-- Receives notification that the Add-in is being loaded.
Map3DSystem.App.WebBrowser.OnConnection(msg.app, msg.connectMode);
elseif(msg.type == Map3DSystem.App.MSGTYPE.APP_DISCONNECTION) then
-- Receives notification that the Add-in is being unloaded.
Map3DSystem.App.WebBrowser.OnDisconnection(msg.app, msg.disconnectMode);
elseif(msg.type == Map3DSystem.App.MSGTYPE.APP_QUERY_STATUS) then
-- This is called when the command's availability is updated.
-- NOTE: this function returns a result.
msg.status = Map3DSystem.App.WebBrowser.OnQueryStatus(msg.app, msg.commandName, msg.statusWanted);
elseif(msg.type == Map3DSystem.App.MSGTYPE.APP_EXEC) then
-- This is called when the command is invoked.
msg.bInterested = Map3DSystem.App.WebBrowser.OnExec(msg.app, msg.commandName, msg.params);
elseif(msg.type == Map3DSystem.App.MSGTYPE.APP_RENDER_BOX) then
-- Change and render the 3D world with mcml data that is usually retrieved from the current user's profile page for this application.
Map3DSystem.App.WebBrowser.OnRenderBox(msg.mcml);
elseif(msg.type == Map3DSystem.App.MSGTYPE.APP_NAVIGATION) then
-- Receives notification that the user wants to nagivate to the 3D world location relavent to this application
Map3DSystem.App.WebBrowser.Navigate();
elseif(msg.type == Map3DSystem.App.MSGTYPE.APP_HOMEPAGE) then
-- called when user clicks to check out the homepage of this application.
Map3DSystem.App.WebBrowser.GotoHomepage();
elseif(msg.type == Map3DSystem.App.MSGTYPE.APP_QUICK_ACTION) then
-- called when user clicks the quick action for this application.
Map3DSystem.App.WebBrowser.DoQuickAction();
----------------------------------------------------
-- normal windows messages here
----------------------------------------------------
elseif(msg.type == CommonCtrl.os.MSGTYPE.WM_CLOSE) then
elseif(msg.type == CommonCtrl.os.MSGTYPE.WM_SIZE) then
elseif(msg.type == CommonCtrl.os.MSGTYPE.WM_HIDE) then
elseif(msg.type == CommonCtrl.os.MSGTYPE.WM_SHOW) then
end
end | gpl-2.0 |
garlick/flux-core | src/shell/lua.d/mvapich.lua | 4 | 1463 | -------------------------------------------------------------
-- Copyright 2020 Lawrence Livermore National Security, LLC
-- (c.f. AUTHORS, NOTICE.LLNS, COPYING)
--
-- This file is part of the Flux resource manager framework.
-- For details, see https://github.com/flux-framework.
--
-- SPDX-License-Identifier: LGPL-3.0
-------------------------------------------------------------
local f, err = require 'flux'.new ()
if not f then error (err) end
-- Lua implementation of dirname(3) to avoid pulling in posix module
local function dirname (d)
if not d:match ("/") then return "." end
return d:match ("^(.*[^/])/.-$")
end
local function setenv_prepend (var, val)
local path = shell.getenv (var)
-- If path not already set, then set it to val
if not path then
shell.setenv (var, val)
-- O/w, if val is not already set in path, prepend it
elseif path:match ("^[^:]+") ~= val then
shell.setenv (var, val .. ':' .. path)
end
-- O/w, val already first in path. Do nothing
end
local libpmi = f:getattr ('conf.pmi_library_path')
setenv_prepend ("LD_LIBRARY_PATH", dirname (libpmi))
shell.setenv ("MPIRUN_NTASKS", shell.info.ntasks)
shell.setenv ("MPIRUN_RSH_LAUNCH", 1)
plugin.register {
name = "mvapich",
handlers = {
{
topic = "task.init",
fn = function ()
local rank = task.info.rank
task.setenv ("MPIRUN_RANK", rank)
end
}
}
}
| lgpl-3.0 |
ukoloff/rufus-lua-win | vendor/lua/lib/lua/luarocks/build.lua | 2 | 11554 |
--- Module implementing the LuaRocks "build" command.
-- Builds a rock, compiling its C parts if any.
module("luarocks.build", package.seeall)
local pack = require("luarocks.pack")
local path = require("luarocks.path")
local util = require("luarocks.util")
local rep = require("luarocks.rep")
local fetch = require("luarocks.fetch")
local fs = require("luarocks.fs")
local dir = require("luarocks.dir")
local deps = require("luarocks.deps")
local manif = require("luarocks.manif")
local cfg = require("luarocks.cfg")
help_summary = "Build/compile a rock."
help_arguments = "[--pack-binary-rock] {<rockspec>|<rock>|<name> [<version>]}"
help = [[
Build and install a rock, compiling its C parts if any.
Argument may be a rockspec file, a source rock file
or the name of a rock to be fetched from a repository.
If --pack-binary-rock is passed, the rock is not installed;
instead, a .rock file with the contents of compilation is produced
in the current directory.
]]
--- Install files to a given location.
-- Takes a table where the array part is a list of filenames to be copied.
-- In the hash part, other keys, if is_module_path is set, are identifiers
-- in Lua module format, to indicate which subdirectory the file should be
-- copied to. For example, install_files({["foo.bar"] = "src/bar.lua"}, "boo")
-- will copy src/bar.lua to boo/foo.
-- @param files table or nil: A table containing a list of files to copy in
-- the format described above. If nil is passed, this function is a no-op.
-- Directories should be delimited by forward slashes as in internet URLs.
-- @param location string: The base directory files should be copied to.
-- @param is_module_path boolean: True if string keys in files should be
-- interpreted as dotted module paths.
-- @return boolean or (nil, string): True if succeeded or
-- nil and an error message.
local function install_files(files, location, is_module_path)
assert(type(files) == "table" or not files)
assert(type(location) == "string")
if files then
for k, file in pairs(files) do
local dest = location
if type(k) == "string" then
if is_module_path then
dest = dir.path(location, path.module_to_path(k))
fs.make_dir(dest)
else
dest = dir.path(location, dir.dir_name(k))
fs.make_dir(dest)
dest = dir.path(dest, dir.base_name(k))
end
else
fs.make_dir(dest)
end
local ok = fs.copy(dir.path(file), dest)
if not ok then
return nil, "Failed copying "..file
end
end
end
return true
end
--- Write to the current directory the contents of a table,
-- where each key is a file name and its value is the file content.
-- @param files table: The table of files to be written.
local function extract_from_rockspec(files)
for name, content in pairs(files) do
local fd = io.open(dir.path(fs.current_dir(), name), "w+")
fd:write(content)
fd:close()
end
end
--- Applies patches inlined in the build.patches section
-- and extracts files inlined in the build.extra_files section
-- of a rockspec.
-- @param rockspec table: A rockspec table.
-- @return boolean or (nil, string): True if succeeded or
-- nil and an error message.
function apply_patches(rockspec)
assert(type(rockspec) == "table")
local build = rockspec.build
if build.extra_files then
extract_from_rockspec(build.extra_files)
end
if build.patches then
extract_from_rockspec(build.patches)
for patch, patchdata in util.sortedpairs(build.patches) do
util.printout("Applying patch "..patch.."...")
local ok, err = fs.apply_patch(tostring(patch), patchdata)
if not ok then
return nil, "Failed applying patch "..patch
end
end
end
return true
end
--- Build and install a rock given a rockspec.
-- @param rockspec_file string: local or remote filename of a rockspec.
-- @param need_to_fetch boolean: true if sources need to be fetched,
-- false if the rockspec was obtained from inside a source rock.
-- @param minimal_mode boolean: true if there's no need to fetch,
-- unpack or change dir (this is used by "luarocks make"). Implies
-- need_to_fetch = false.
-- @param no_deps boolean: true if dependency check needs to be skipped
-- @return boolean or (nil, string, [string]): True if succeeded or
-- nil and an error message followed by an error code.
function build_rockspec(rockspec_file, need_to_fetch, minimal_mode, no_deps)
assert(type(rockspec_file) == "string")
assert(type(need_to_fetch) == "boolean")
local rockspec, err, errcode = fetch.load_rockspec(rockspec_file)
if err then
return nil, err, errcode
elseif not rockspec.build then
return nil, "Rockspec error: build table not specified"
elseif not rockspec.build.type then
return nil, "Rockspec error: build type not specified"
end
if no_deps then
util.printerr("Warning: skipping dependency checks.")
else
local ok, err, errcode = deps.fulfill_dependencies(rockspec)
if err then
return nil, err, errcode
end
end
ok, err, errcode = deps.check_external_deps(rockspec, "build")
if err then
return nil, err, errcode
end
local name, version = rockspec.name, rockspec.version
if rep.is_installed(name, version) then
rep.delete_version(name, version)
end
if not minimal_mode then
local _, source_dir
if need_to_fetch then
ok, source_dir, errcode = fetch.fetch_sources(rockspec, true)
if not ok then
return nil, source_dir, errcode
end
fs.change_dir(source_dir)
elseif rockspec.source.file then
local ok, err = fs.unpack_archive(rockspec.source.file)
if not ok then
return nil, err
end
end
fs.change_dir(rockspec.source.dir)
end
local dirs = {
lua = { name = path.lua_dir(name, version), is_module_path = true },
lib = { name = path.lib_dir(name, version), is_module_path = true },
conf = { name = path.conf_dir(name, version), is_module_path = false },
bin = { name = path.bin_dir(name, version), is_module_path = false },
}
for _, d in pairs(dirs) do
fs.make_dir(d.name)
end
local rollback = util.schedule_function(function()
fs.delete(path.install_dir(name, version))
fs.remove_dir_if_empty(path.versions_dir(name))
end)
local build = rockspec.build
if not minimal_mode then
ok, err = apply_patches(rockspec)
if err then
return nil, err
end
end
if build.type ~= "none" then
-- Temporary compatibility
if build.type == "module" then
util.printout("Do not use 'module' as a build type. Use 'builtin' instead.")
build.type = "builtin"
end
local build_type
ok, build_type = pcall(require, "luarocks.build." .. build.type)
if not ok or not type(build_type) == "table" then
return nil, "Failed initializing build back-end for build type '"..build.type.."': "..build_type
end
ok, err = build_type.run(rockspec)
if not ok then
return nil, "Build error: " .. err
end
end
if build.install then
for id, install_dir in pairs(dirs) do
ok, err = install_files(build.install[id], install_dir.name, install_dir.is_module_path)
if not ok then
return nil, err
end
end
end
local copy_directories = build.copy_directories or {"doc"}
for _, copy_dir in pairs(copy_directories) do
if fs.is_dir(copy_dir) then
local dest = dir.path(path.install_dir(name, version), copy_dir)
fs.make_dir(dest)
fs.copy_contents(copy_dir, dest)
end
end
for _, d in pairs(dirs) do
fs.remove_dir_if_empty(d.name)
end
fs.pop_dir()
fs.copy(rockspec.local_filename, path.rockspec_file(name, version))
if need_to_fetch then
fs.pop_dir()
end
ok, err = manif.make_rock_manifest(name, version)
if err then return nil, err end
ok, err = rep.deploy_files(name, version, rep.should_wrap_bin_scripts(rockspec))
if err then return nil, err end
util.remove_scheduled_function(rollback)
rollback = util.schedule_function(function()
rep.delete_version(name, version)
end)
ok, err = rep.run_hook(rockspec, "post_install")
if err then return nil, err end
ok, err = manif.update_manifest(name, version)
if err then return nil, err end
local license = ""
if rockspec.description and rockspec.description.license then
license = ("(license: "..rockspec.description.license..")")
end
local root_dir = path.root_dir(cfg.rocks_dir)
util.printout()
util.printout(name.." "..version.." is now built and installed in "..root_dir.." "..license)
util.remove_scheduled_function(rollback)
return true
end
--- Build and install a rock.
-- @param rock_file string: local or remote filename of a rock.
-- @param need_to_fetch boolean: true if sources need to be fetched,
-- false if the rockspec was obtained from inside a source rock.
-- @return boolean or (nil, string, [string]): True if build was successful,
-- or false and an error message and an optional error code.
function build_rock(rock_file, need_to_fetch, no_deps)
assert(type(rock_file) == "string")
assert(type(need_to_fetch) == "boolean")
local unpack_dir, err, errcode = fetch.fetch_and_unpack_rock(rock_file)
if not unpack_dir then
return nil, err, errcode
end
local rockspec_file = path.rockspec_name_from_rock(rock_file)
fs.change_dir(unpack_dir)
local ok, err, errcode = build_rockspec(rockspec_file, need_to_fetch, false, no_deps)
fs.pop_dir()
return ok, err, errcode
end
local function do_build(name, version, no_deps)
if name:match("%.rockspec$") then
return build_rockspec(name, true, false, no_deps)
elseif name:match("%.src%.rock$") then
return build_rock(name, false, no_deps)
elseif name:match("%.all%.rock$") then
local install = require("luarocks.install")
return install.install_binary_rock(name, no_deps)
elseif name:match("%.rock$") then
return build_rock(name, true, no_deps)
elseif not name:match(dir.separator) then
local search = require("luarocks.search")
return search.act_on_src_or_rockspec(run, name:lower(), version, no_deps and "--nodeps")
end
return nil, "Don't know what to do with "..name
end
--- Driver function for "build" command.
-- @param name string: A local or remote rockspec or rock file.
-- If a package name is given, forwards the request to "search" and,
-- if returned a result, installs the matching rock.
-- @param version string: When passing a package name, a version number may
-- also be given.
-- @return boolean or (nil, string): True if build was successful; nil and an
-- error message otherwise.
function run(...)
local flags, name, version = util.parse_flags(...)
if type(name) ~= "string" then
return nil, "Argument missing, see help."
end
assert(type(version) == "string" or not version)
if flags["pack-binary-rock"] then
return pack.pack_binary_rock(name, version, do_build, name, version, flags["nodeps"])
else
local ok, err = fs.check_command_permissions(flags)
if not ok then return nil, err end
return do_build(name, version, flags["nodeps"])
end
end
| mit |
thedraked/darkstar | scripts/globals/spells/shellra_v.lua | 26 | 1101 | -----------------------------------------
-- Spell: Shellra
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local meritBonus = caster:getMerit(MERIT_SHELLRA_V);
local duration = 1800;
local power = 62;
if (meritBonus > 0) then -- certain mobs can cast this spell, so don't apply the -2 for having 0 merits.
power = power + meritBonus - 2;
end
power = power * 100/256; -- doing it this way because otherwise the merit power would have to be 0.78125.
--printf("Shellra V Power: %d", power);
duration = calculateDurationForLvl(duration, 75, target:getMainLvl());
local typeEffect = EFFECT_SHELL;
if (target:addStatusEffect(typeEffect, power, 0, duration)) then
spell:setMsg(230);
else
spell:setMsg(75); -- no effect
end
return typeEffect;
end;
| gpl-3.0 |
mtroyka/Zero-K | effects/gundam_crawlexplode.lua | 50 | 8555 | -- small_nuke_explosion_fx
return {
["small_nuke_explosion_fx"] = {
usedefaultexplosions = false,
g_blast = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.87,
colormap = [[1 0.25 0 0.01 0.4 0.3 0.2 0.01 0 0 0 0.01 0 0 0 0.01]],
directional = true,
emitrot = 80,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 150,
particlelife = 60,
particlelifespread = 30,
particlesize = 32,
particlesizespread = 10,
particlespeed = 17,
particlespeedspread = 18,
pos = [[3 r-3, 1 r-2, 3 r-3]],
sizegrowth = 0.14,
sizemod = 1.0,
texture = [[splash]],
},
},
g_blast11 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.88,
colormap = [[0 0 0 0.01 0.2 0.2 0.2 0.9 0 0 0 0.01]],
directional = true,
emitrot = 80,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 50,
particlelife = 180,
particlelifespread = 30,
particlesize = 48,
particlesizespread = 24,
particlespeed = 1,
particlespeedspread = 32,
pos = [[3 r-3, 1 r-2, 3 r-3]],
sizegrowth = 0.14,
sizemod = 1.0,
texture = [[smoke]],
},
},
g_blast2 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.87,
colormap = [[1 0.25 0 0.01 0.3 0.2 0.1 0.01 0 0 0 0.01 0 0 0 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 80,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 200,
particlelife = 60,
particlelifespread = 30,
particlesize = 32,
particlesizespread = 13,
particlespeed = 17,
particlespeedspread = 15,
pos = [[3 r-3, 1 r-2, 3 r-3]],
sizegrowth = 0.14,
sizemod = 1.0,
texture = [[splash]],
},
},
g_blast22 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.88,
colormap = [[0 0 0 0.01 0.1 0.1 0.1 0.5 0 0 0 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 80,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 50,
particlelife = 180,
particlelifespread = 30,
particlesize = 48,
particlesizespread = 24,
particlespeed = 1,
particlespeedspread = 32,
pos = [[3 r-3, 1 r-2, 3 r-3]],
sizegrowth = 0.14,
sizemod = 1.0,
texture = [[smoke]],
},
},
g_smokewave1 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.92,
colormap = [[1 0.3 0.2 0.01 1 0.5 0.2 0.01 0.1 0.1 0.1 0.01 0.1 0.1 0.1 0.01 0 0 0 0.01]],
directional = false,
emitrot = 80,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 35,
particlelife = 38,
particlelifespread = 15,
particlesize = 13,
particlesizespread = 1,
particlespeed = 20,
particlespeedspread = 1,
pos = [[0, 1, 0]],
sizegrowth = 0.16,
sizemod = 1.0,
texture = [[YELLOWBLAST]],
},
},
g_smokewave2 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.92,
colormap = [[1 0.3 0.2 0.01 1 0.5 0.2 0.01 0.1 0.1 0.1 0.01 0.1 0.1 0.1 0.01 0 0 0 0.01]],
directional = false,
emitrot = 80,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 35,
particlelife = 38,
particlelifespread = 15,
particlesize = 13,
particlesizespread = 1,
particlespeed = 20,
particlespeedspread = 1,
pos = [[0, 1, 0]],
sizegrowth = 0.16,
sizemod = 1.0,
texture = [[YELLOWBLAST1]],
},
},
g_smokewave3 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.92,
colormap = [[1 0.3 0.2 0.01 1 0.5 0.2 0.01 0.1 0.1 0.1 0.01 0.1 0.1 0.1 0.01 0 0 0 0.01]],
directional = false,
emitrot = 80,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 35,
particlelife = 38,
particlelifespread = 15,
particlesize = 13,
particlesizespread = 1,
particlespeed = 20,
particlespeedspread = 1,
pos = [[0, 1, 0]],
sizegrowth = 0.16,
sizemod = 1.0,
texture = [[YELLOWBLAST2]],
},
},
g_smokewave4 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.92,
colormap = [[1 0.3 0.2 0.01 1 0.5 0.2 0.01 0.1 0.1 0.1 0.01 0.1 0.1 0.1 0.01 0 0 0 0.01]],
directional = false,
emitrot = 80,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 35,
particlelife = 38,
particlelifespread = 15,
particlesize = 13,
particlesizespread = 1,
particlespeed = 20,
particlespeedspread = 1,
pos = [[0, 1, 0]],
sizegrowth = 0.16,
sizemod = 1.0,
texture = [[YELLOWBLAST3]],
},
},
spikesofhell = {
air = true,
class = [[explspike]],
count = 30,
ground = true,
water = true,
properties = {
alpha = 1,
alphadecay = 0.05,
color = [[1.0, 0.7, 0.2]],
dir = [[-25 r50,-25 r50,-25 r50]],
length = 1,
width = 40,
},
},
windsphere = {
air = true,
class = [[CSpherePartSpawner]],
count = 3,
ground = true,
water = true,
properties = {
alpha = 0.22,
color = [[1.0, 0.8, 0.1]],
expansionspeed = [[10 r4]],
ttl = 27,
},
},
},
}
| gpl-2.0 |
Devul/DarkRP | gamemode/modules/fadmin/fadmin/playeractions/god/cl_init.lua | 10 | 1557 | FAdmin.StartHooks["God"] = function()
FAdmin.Messages.RegisterNotification{
name = "god",
hasTarget = true,
message = {"instigator", " enabled godmode for ", "targets"},
receivers = "everyone",
}
FAdmin.Messages.RegisterNotification{
name = "ungod",
hasTarget = true,
message = {"instigator", " disabled godmode for ", "targets"},
receivers = "everyone",
}
FAdmin.Access.AddPrivilege("God", 2)
FAdmin.Commands.AddCommand("god", nil, "<Player>")
FAdmin.Commands.AddCommand("ungod", nil, "<Player>")
FAdmin.ScoreBoard.Player:AddActionButton(function(ply)
if ply:FAdmin_GetGlobal("FAdmin_godded") then return "Ungod" end
return "God"
end, function(ply)
if ply:FAdmin_GetGlobal("FAdmin_godded") then return "fadmin/icons/god", "fadmin/icons/disable" end
return "fadmin/icons/god"
end, Color(255, 130, 0, 255),
function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "God") end, function(ply, button)
if not ply:FAdmin_GetGlobal("FAdmin_godded") then
RunConsoleCommand("_FAdmin", "god", ply:UserID())
else
RunConsoleCommand("_FAdmin", "ungod", ply:UserID())
end
if not ply:FAdmin_GetGlobal("FAdmin_godded") then button:SetImage2("fadmin/icons/disable") button:SetText("Ungod") button:GetParent():InvalidateLayout() return end
button:SetImage2("null")
button:SetText("God")
button:GetParent():InvalidateLayout()
end)
end
| mit |
thedraked/darkstar | scripts/zones/Yhoator_Jungle/npcs/qm2.lua | 14 | 1953 | -----------------------------------
-- Area: Yhoator Jungle
-- NPC: ??? Used for Norg quest "Stop Your Whining"
-- @pos -94.073 -0.999 22.295 124
-----------------------------------
package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Yhoator_Jungle/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local StopWhining = player:getQuestStatus(OUTLANDS,STOP_YOUR_WHINING);
if (StopWhining == QUEST_ACCEPTED and player:hasKeyItem(BARREL_OF_OPOOPO_BREW) == false and player:hasKeyItem(EMPTY_BARREL)) then
player:messageSpecial(TREE_CHECK);
player:addKeyItem(BARREL_OF_OPOOPO_BREW); --Filled Barrel
player:messageSpecial(KEYITEM_OBTAINED,BARREL_OF_OPOOPO_BREW);
player:delKeyItem(EMPTY_BARREL); --Empty Barrel
elseif (StopWhining == QUEST_ACCEPTED and player:hasKeyItem(BARREL_OF_OPOOPO_BREW) == true) then
player:messageSpecial(TREE_FULL); --Already have full barrel
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0001) then
player:addKeyItem(SEA_SERPENT_STATUE);
player:messageSpecial(KEYITEM_OBTAINED,SEA_SERPENT_STATUE);
end
end; | gpl-3.0 |
thorsummoner/polycode | Examples/Lua/3D_Physics/3DPhysics_Vehicle/Scripts/Main.lua | 10 | 4127 | scene = PhysicsScene(0, Vector3(200, 200, 200))
ground = ScenePrimitive(ScenePrimitive.TYPE_PLANE, 30, 30)
ground:loadTexture("Resources/green_texture.png")
scene:addPhysicsChild(ground, 0, 0)
-- Some obstacles
local box = ScenePrimitive(ScenePrimitive.TYPE_BOX, 4,4,6)
box:setPitch(25)
box:setPosition(7, -1, 0)
box:setColor(0.5, 0.5, 1,1)
box:loadTexture("Resources/green_texture.png")
scene:addPhysicsChild(box, 0, 0)
box = ScenePrimitive(ScenePrimitive.TYPE_BOX, 4, 4, 6)
box:setPitch(25)
box:setPosition(-7, -1, 0)
box:setColor(0.5,0.5,1,1)
box:loadTexture("Resources/green_texture.png")
scene:addPhysicsChild(box, 0, 0)
box = ScenePrimitive(ScenePrimitive.TYPE_BOX, 20,2,5)
box:setPosition(0,1, -4.3)
box:setColor(0.5,0.5,1,1)
box:loadTexture("Resources/green_texture.png")
scene:addPhysicsChild(box, 0, 0)
for i = 1, 10 do
box = ScenePrimitive(ScenePrimitive.TYPE_BOX, 0.7,0.7,0.7)
box:loadTexture("Resources/pink_texture.png")
box:Roll(-45 + math.random() % 90)
box:Pitch(-45 + (math.random() % 90))
box:setPosition(-3 + (math.random() % 6), 2 + i*0.5, -5 + math.random() % 3)
scene:addPhysicsChild(box, 0, 1)
end
-- The vehicle
vehicle = ScenePrimitive(ScenePrimitive.TYPE_BOX, 1, 0.5, 2)
vehicle:loadTexture("Resources/pink_texture.png")
vehicle:setColor(1, 1, 0, 1)
vehicle:setPosition(6,1,5)
vehicleController = scene:addVehicleChild(vehicle, 5, 1)
local wheel = ScenePrimitive(ScenePrimitive.TYPE_SPHERE, 0.3, 10, 10)
wheel:loadTexture("Resources/pink_texture.png")
wheel:setColor(0, 1, 0, 1)
vehicleController:addWheel(wheel, Vector3(0.6, 0, -0.5), Vector3(0, -1, 0), Vector3(-1,0,0), 0.2, 0.3, true)
scene:addEntity(wheel)
wheel = ScenePrimitive(ScenePrimitive.TYPE_SPHERE, 0.3, 10, 10)
wheel:loadTexture("Resources/pink_texture.png")
wheel:setColor(0, 1, 0, 1)
vehicleController:addWheel(wheel, Vector3(-0.6,0,-0.5), Vector3(0,-1,0), Vector3(-1,0,0), 0.2, 0.3, true)
scene:addEntity(wheel)
wheel = ScenePrimitive(ScenePrimitive.TYPE_SPHERE, 0.3, 10, 10)
wheel:loadTexture("Resources/pink_texture.png")
wheel:setColor(0, 1, 0, 1)
vehicleController:addWheel(wheel, Vector3(0.6,0,0.5), Vector3(0,-1,0), Vector3(-1,0,0), 0.2, 0.3, false)
scene:addEntity(wheel)
wheel = ScenePrimitive(ScenePrimitive.TYPE_SPHERE, 0.3, 10, 10)
wheel:loadTexture("Resources/pink_texture.png")
wheel:setColor(0, 1, 0, 1)
vehicleController:addWheel(wheel, Vector3(-0.6,0,0.5), Vector3(0,-1,0), Vector3(-1,0,0), 0.2, 0.3, false)
scene:addEntity(wheel)
local steeringValue = 0
local engineForce = 0
local breaking = false
local testBox = ScenePrimitive(ScenePrimitive.TYPE_BOX, 4, 4, 4)
testBox:loadTexture("Resources/pink_texture.png")
testBox:setColor(0.3, 0.5, 1, 0.4)
testBox:setPosition(-5, 2, 7)
scene:addCollisionChild(testBox, 0)
scene:getDefaultCamera():setPosition(16, 16, 16)
scene:getDefaultCamera():lookAt(Vector3(0, 0, 0), Vector3(0, 1, 0))
function onKeyDown(keyCode)
if keyCode == KEY_r then
vehicleController:warpVehicle(Vector3(6,1,5))
elseif keyCode == KEY_UP then
engineForce = -15
elseif keyCode == KEY_DOWN then
engineForce = 15
elseif keyCode == KEY_LEFT then
steeringValue = 0.5
elseif keyCode == KEY_RIGHT then
steeringValue = -0.5
elseif keyCode == KEY_SPACE then
breaking = true
end
end
function onKeyUp(keyCode)
if keyCode == KEY_DOWN or keyCode == KEY_UP then
engineForce = 0
elseif keyCode == KEY_RIGHT or keyCode == KEY_LEFT then
steeringValue = 0
elseif keyCode == KEY_SPACE then
breaking = false
end
end
function Update(elapsed)
if breaking then
vehicleController:setBrake(20, 2)
vehicleController:setBrake(20, 3)
vehicleController:applyEngineForce(0, 2)
vehicleController:applyEngineForce(0, 3)
else
vehicleController:setBrake(0, 2)
vehicleController:setBrake(0, 3)
vehicleController:applyEngineForce(engineForce, 2)
vehicleController:applyEngineForce(engineForce, 3)
end
vehicleController:setSteeringValue(steeringValue, 0)
vehicleController:setSteeringValue(steeringValue, 1)
local res = scene:testCollision(vehicle, testBox)
if res.collided then
testBox:setColor(1,1,0,0.5)
else
testBox:setColor(0,1,1,0.5)
end
end | mit |
brimworks/zile | src/help.lua | 1 | 4556 | -- Self documentation facility functions
--
-- Copyright (c) 2010-2011 Free Software Foundation, Inc.
--
-- This file is part of GNU Zile.
--
-- GNU Zile is free software; you can redistribute it and/or modify it
-- under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3, or (at your option)
-- any later version.
--
-- GNU Zile is distributed in the hope that it will be useful, but
-- WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with GNU Zile; see the file COPYING. If not, write to the
-- Free Software Foundation, Fifth Floor, 51 Franklin Street, Boston,
-- MA 02111-1301, USA.
-- FIXME: Add apropos
Defun ("zile-version",
{},
[[
Show the version of Zile that is running.
]],
true,
function ()
minibuf_write (string.format ("%s of %s on %s", ZILE_VERSION_STRING, CONFIGURE_DATE, CONFIGURE_HOST))
end
)
local function show_file (filename)
if not exist_file (filename) then
minibuf_error (string.format ("Unable to read file `%s'", filename))
return leNIL
end
find_file (filename)
cur_bp.readonly = true
cur_bp.noundo = true
cur_bp.needname = true
cur_bp.nosave = true
return leT
end
Defun ("view-emacs-FAQ",
{},
[[
Display the Zile Frequently Asked Questions (FAQ) file.
]],
true,
function ()
return show_file (PATH_DATA .. "/FAQ")
end
)
local function write_function_description (name, doc)
insert_string (string.format ("%s is %s built-in function in `C source code'.\n\n%s",
name,
get_function_interactive (name) and "an interactive" or "a",
doc))
end
Defun ("describe-function",
{"string"},
[[
Display the full documentation of a function.
]],
true,
function (func)
if not func then
func = minibuf_read_function_name ("Describe function: ")
if not func then
return leNIL
end
end
local doc = get_function_doc (func)
if not doc then
return leNIL
else
write_temp_buffer ("*Help*", true, write_function_description, func, doc)
end
return leT
end
)
local function write_key_description (name, doc, binding)
local interactive = get_function_interactive (name)
assert (interactive ~= nil)
insert_string (string.format ("%s runs the command %s, which is %s built-in\n" ..
"function in `C source code'.\n\n%s",
binding, name,
interactive and "an interactive" or "a",
doc))
end
Defun ("describe-key",
{"string"},
[[
Display documentation of the command invoked by a key sequence.
]],
true,
function (keystr)
local name, binding, keys
if keystr then
keys = keystrtovec (keystr)
if not keys then
return false
end
name = get_function_by_keys (keys)
binding = keyvectostr (keys)
else
minibuf_write ("Describe key:")
keys = get_key_sequence ()
name = get_function_by_keys (keys)
binding = keyvectostr (keys)
if not name then
minibuf_error (binding .. " is undefined")
return false
end
end
minibuf_write (string.format ("%s runs the command `%s'", binding, name))
local doc = get_function_doc (name)
if not doc then
return false
end
write_temp_buffer ("*Help*", true, write_key_description, name, doc, binding)
return true
end
)
local function write_variable_description (name, curval, doc)
insert_string (string.format ("%s is a variable defined in `C source code'.\n\n" ..
"Its value is %s\n\n%s",
name, curval, doc))
end
Defun ("describe-variable",
{"string"},
[[
Display the full documentation of a variable.
]],
true,
function (name)
local ok = leT
if not name then
name = minibuf_read_variable_name ("Describe variable: ")
end
if not name then
ok = leNIL
else
local doc = main_vars[name].doc
if not doc then
ok = leNIL
else
write_temp_buffer ("*Help*", true,
write_variable_description,
name, get_variable (name), doc)
end
end
return ok
end
)
| gpl-3.0 |
thedraked/darkstar | scripts/globals/items/plate_of_salmon_sushi_+1.lua | 18 | 1470 | -----------------------------------------
-- ID: 5664
-- Item: plate_of_salmon_sushi_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Strength 2
-- Accuracy % 15
-- Ranged ACC % 15
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5663);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 2);
target:addMod(MOD_FOOD_ACCP, 15);
target:addMod(MOD_FOOD_ACC_CAP, 999);
target:addMod(MOD_FOOD_RACCP, 15);
target:addMod(MOD_FOOD_RACC_CAP, 999);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 1);
target:delMod(MOD_FOOD_ACCP, 15);
target:delMod(MOD_FOOD_ACC_CAP, 999);
target:delMod(MOD_FOOD_RACCP, 15);
target:delMod(MOD_FOOD_RACC_CAP, 999);
end;
| gpl-3.0 |
pevers/OpenRA | mods/cnc/maps/funpark01/scj01ea.lua | 19 | 3521 | RifleReinforcments = { "e1", "e1", "e1", "bike" }
BazookaReinforcments = { "e3", "e3", "e3", "bike" }
BikeReinforcments = { "bike" }
ReinforceWithLandingCraft = function(units, transportStart, transportUnload, rallypoint)
local transport = Actor.Create("oldlst", true, { Owner = nod, Facing = 0, Location = transportStart })
local subcell = 0
Utils.Do(units, function(a)
transport.LoadPassenger(Actor.Create(a, false, { Owner = transport.Owner, Facing = transport.Facing, Location = transportUnload, SubCell = subcell }))
subcell = subcell + 1
end)
transport.ScriptedMove(transportUnload)
transport.CallFunc(function()
Utils.Do(units, function()
local a = transport.UnloadPassenger()
a.IsInWorld = true
a.MoveIntoWorld(transport.Location - CVec.New(0, 1))
if rallypoint ~= nil then
a.Move(rallypoint)
end
end)
end)
transport.Wait(5)
transport.ScriptedMove(transportStart)
transport.Destroy()
Media.PlaySpeechNotification(player, "Reinforce")
end
WorldLoaded = function()
nod = Player.GetPlayer("Nod")
dinosaur = Player.GetPlayer("Dinosaur")
civilian = Player.GetPlayer("Civilian")
InvestigateObj = nod.AddPrimaryObjective("Investigate the nearby village for reports of \nstrange activity.")
Trigger.OnObjectiveAdded(nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(nod, function()
Media.PlaySpeechNotification(nod, "Win")
end)
Trigger.OnPlayerLost(nod, function()
Media.PlaySpeechNotification(nod, "Lose")
end)
ReachVillageObj = nod.AddPrimaryObjective("Reach the village.")
Trigger.OnPlayerDiscovered(civilian, function(_, discoverer)
if discoverer == nod and not nod.IsObjectiveCompleted(ReachVillageObj) then
if not dinosaur.HasNoRequiredUnits() then
KillDinos = nod.AddPrimaryObjective("Kill all creatures in the area.")
end
nod.MarkCompletedObjective(ReachVillageObj)
end
end)
DinoTric.Patrol({WP0.Location, WP1.Location}, true, 3)
DinoTrex.Patrol({WP2.Location, WP3.Location}, false)
Trigger.OnIdle(DinoTrex, DinoTrex.Hunt)
ReinforceWithLandingCraft(RifleReinforcments, SeaEntryA.Location, BeachReinforceA.Location, BeachReinforceA.Location)
Trigger.AfterDelay(DateTime.Seconds(1), function() InitialUnitsArrived = true end)
Trigger.AfterDelay(DateTime.Seconds(15), function() ReinforceWithLandingCraft(BazookaReinforcments, SeaEntryB.Location, BeachReinforceB.Location, BeachReinforceB.Location) end)
if Map.Difficulty == "Easy" then
Trigger.AfterDelay(DateTime.Seconds(25), function() ReinforceWithLandingCraft(BikeReinforcments, SeaEntryA.Location, BeachReinforceA.Location, BeachReinforceA.Location) end)
Trigger.AfterDelay(DateTime.Seconds(30), function() ReinforceWithLandingCraft(BikeReinforcments, SeaEntryB.Location, BeachReinforceB.Location, BeachReinforceB.Location) end)
end
Camera.Position = CameraStart.CenterPosition
end
Tick = function()
if InitialUnitsArrived then
if nod.HasNoRequiredUnits() then
nod.MarkFailedObjective(InvestigateObj)
end
if dinosaur.HasNoRequiredUnits() then
if KillDinos then nod.MarkCompletedObjective(KillDinos) end
nod.MarkCompletedObjective(InvestigateObj)
end
end
end
| gpl-3.0 |
mtroyka/Zero-K | effects/gundam_miofskyparticles.lua | 25 | 1564 | -- miofskyparticles
return {
["miofskyparticles"] = {
poof01 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.95,
colormap = [[0.3 0.5 0.01 1.0 0.15 0.2 0.15 0.1 0 0 0 0.01]],
directional = true,
emitrot = 90,
emitrotspread = 10,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.3, 0]],
numparticles = 5,
particlelife = 10,
particlelifespread = 10,
particlesize = 20,
particlesizespread = 0,
particlespeed = 17,
particlespeedspread = 2,
pos = [[r-1 r1, r-1 r1, r-1 r1]],
sizegrowth = 0.8,
sizemod = 1.0,
texture = [[dirt]],
useairlos = true,
},
},
smoke = {
air = true,
count = 3,
ground = true,
water = true,
properties = {
agespeed = 0.05,
alwaysvisible = true,
color = 0.1,
pos = [[r-800 r800, 3, r-800 r800]],
size = 2,
sizeexpansion = 0.6,
sizegrowth = 5,
speed = [[r-3 r3, 1 r2.3, r-3 r3]],
startsize = 1,
},
},
},
}
| gpl-2.0 |
Devul/DarkRP | gamemode/modules/fpp/pp/server/defaultblockedmodels.lua | 9 | 2488 | /*
DEFAULT BLOCKED MODELS
THIS FILE WILL ONLY BE RUN ONCE, WHICH IS THE FIRST TIME YOU INSTALL FPP, OR AFTER THE SQLITE DATABASE IS RESET
DO NOT EDIT THIS FILE AS IT IS USELESS
GO TO Q>UTILITIES>FPP ADMIN SETTINGS > BLOCKED MODEL OPTIONS TO ADD OR REMOVE BLOCKED MODELS
*/
FPP = FPP or {}
local defaultblocked = {
"models/cranes/crane_frame.mdl",
"models/items/item_item_crate.mdl",
"models/props/cs_militia/silo_01.mdl",
"models/props/cs_office/microwave.mdl",
"models/props/de_train/biohazardtank.mdl",
"models/props_buildings/building_002a.mdl",
"models/props_buildings/collapsedbuilding01a.mdl",
"models/props_buildings/project_building01.mdl",
"models/props_buildings/row_church_fullscale.mdl",
"models/props_c17/consolebox01a.mdl",
"models/props_c17/oildrum001_explosive.mdl",
"models/props_c17/paper01.mdl",
"models/props_c17/trappropeller_engine.mdl",
"models/props_canal/canal_bridge01.mdl",
"models/props_canal/canal_bridge02.mdl",
"models/props_canal/canal_bridge03a.mdl",
"models/props_canal/canal_bridge03b.mdl",
"models/props_combine/combine_citadel001.mdl",
"models/props_combine/combine_mine01.mdl",
"models/props_combine/combinetrain01.mdl",
"models/props_combine/combinetrain02a.mdl",
"models/props_combine/combinetrain02b.mdl",
"models/props_combine/prison01.mdl",
"models/props_combine/prison01c.mdl",
"models/props_industrial/bridge.mdl",
"models/props_junk/garbage_takeoutcarton001a.mdl",
"models/props_junk/gascan001a.mdl",
"models/props_junk/glassjug01.mdl",
"models/props_junk/trashdumpster02.mdl",
"models/props_phx/amraam.mdl",
"models/props_phx/ball.mdl",
"models/props_phx/cannonball.mdl",
"models/props_phx/huge/evildisc_corp.mdl",
"models/props_phx/misc/flakshell_big.mdl",
"models/props_phx/misc/potato_launcher_explosive.mdl",
"models/props_phx/mk-82.mdl",
"models/props_phx/oildrum001_explosive.mdl",
"models/props_phx/torpedo.mdl",
"models/props_phx/ww2bomb.mdl",
"models/props_wasteland/cargo_container01.mdl",
"models/props_wasteland/cargo_container01.mdl",
"models/props_wasteland/cargo_container01b.mdl",
"models/props_wasteland/cargo_container01c.mdl",
"models/props_wasteland/depot.mdl",
"models/xqm/coastertrack/special_full_corkscrew_left_4.mdl",
}
-- Add to SQLite database
function FPP.AddDefaultBlockedModels()
MySQLite.begin()
for k,v in pairs(defaultblocked) do
FPP.BlockedModels[v] = true
MySQLite.query("REPLACE INTO FPP_BLOCKEDMODELS1 VALUES(" .. MySQLite.SQLStr(v) .. ");")
end
MySQLite.commit()
end
| mit |
NPLPackages/main | script/ide/timer.lua | 1 | 10669 | --[[
Title: timer functions
Author(s): LiXizhi
Date: 2009/1/17, refactored to use virtual timers 2009/9/25
Desc: Provides a mechanism for executing a method at specified intervals.
It just wraps the raw NPL timer function. One can create any number of timers as one like,
only one high resolution real timer is used to dispatch all instances of timer object.
TODO: currently a single timer pool is used, in future we may sort timers to different pool according to their periods.
This will allow large number of virtual timers to coexist with lower performance penalty.
Note: virtual timers are not cleared during scene reset.
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/ide/timer.lua");
local mytimer = commonlib.Timer:new({callbackFunc = function(timer)
commonlib.log({"ontimer", timer.id, timer.delta, timer.lastTick})
end})
-- start the timer after 0 milliseconds, and signal every 1000 millisecond
mytimer:Change(0, 1000)
-- start the timer after 1000 milliseconds, and stop it immediately.
mytimer:Change(1000, nil)
-- now kill the timer.
mytimer:Change()
-- kill all timers in the pool
commonlib.TimerManager.Clear()
-- dump timer info
commonlib.TimerManager.DumpTimerCount()
-- get the current time in millisecond. This may be faster than ParaGlobal_timeGetTime() since it is updated only at rendering frame rate.
commonlib.TimerManager.GetCurrentTime();
-- one time timer
commonlib.TimerManager.SetTimeout(function() end, 1000)
------------------------------------------------------------
]]
NPL.load("(gl)script/ide/STL/List.lua");
local Timer = {
-- must be unique
id = nil,
-- call back function (timer) end
callbackFunc = nil,
-- The amount of time to delay before the invoking the callback method specified in milliseconds
-- Specify zero (0) to restart the timer immediately. Specify nil to prevent the timer from restarting.
dueTime = nil,
-- The time interval between invocations of the callback method in milliseconds.
-- Specify nil to disable periodic signaling.
period = nil,
-- whether the timer is enabled or not.
enabled = nil,
-- value returned from last activation call of ParaGlobal.timeGetTime()
lastTick = 0,
}
commonlib.Timer = Timer;
local TimerManager = {timer_id = 1025}
commonlib.TimerManager = TimerManager
local pairs = pairs;
local ipairs = ipairs;
local type = type;
local ParaGlobal_timeGetTime = ParaGlobal.timeGetTime
-- max allowed timer due time. 30 days.
local MAX_TIMER_DUE_TIME = 30*24*60*60*1000;
-- mapping from id to the timer object.
local activeTimerList = commonlib.List:new();
-- a new timer class with infinite time.
function Timer:new(o)
o = o or {};
o.id = o.id or Timer.GetNextTimerID();
setmetatable(o, self)
self.__index = self
if(o.dueTime) then
o:Change(o.dueTime, o.period);
end
-- not neccessary, we will ensure it is always valid.
-- TimerManager.CheckTimer();
return o
end
local next_id = 1025;
-- get the next timer id
function Timer.GetNextTimerID()
next_id = next_id+1;
return next_id;
end
-- change the timer
-- @param dueTime The amount of time to delay before the invoking the callback method specified in milliseconds
-- Specify zero (0) to restart the timer immediately. Specify nil to prevent the timer from restarting.
-- @param period The time interval between invocations of the callback method in milliseconds.
-- Specify nil to disable periodic signaling.
function Timer:Change(dueTime,period)
self.dueTime = dueTime;
self.period = period;
if(not dueTime) then
TimerManager.RemoveTimer(self);
else
self.lastTick = (TimerManager.last_tick or ParaGlobal_timeGetTime()) + dueTime - (period or 0);
TimerManager.AddTimer(self);
end
end
-- call this function to enable the timer if not
function Timer:Enable()
TimerManager.AddTimer(self);
end
-- this function is called by the timer manager to process the time.
-- set the tick count. it will return true, if the timer is activated.
-- call this function regularly with new tick count.
-- @param nTickCount: it should be ::GetTickCount() in millisecond. if nil, we will call the system ::GetTickCount() to get the current tick count.
-- @return true if timer is activated.
function Timer:Tick(nTickCount)
if(not nTickCount) then
nTickCount = ParaGlobal_timeGetTime();
end
local lastTick = self.lastTick;
if( (nTickCount-lastTick)>=(self.period or 0) or ((nTickCount<lastTick) and ((nTickCount+MAX_TIMER_DUE_TIME)<lastTick))) then
self.delta = nTickCount - lastTick;
self.lastTick = nTickCount;
if(self.period == nil) then
TimerManager.RemoveTimer(self);
end
-- do activation
self:Activate();
return true;
end
end
-- get the delta in time since last tick.
-- @param max_delta: if the delta is bigger than this value we will return max_delta rather than the big value.
-- if this is nil, it will be 2 times of self.period
function Timer:GetDelta(max_delta)
max_delta = max_delta or (self.period or 10000) * 2;
if(self.delta) then
if(max_delta > self.delta) then
return self.delta;
else
return max_delta;
end
else
return 0;
end
end
-- activate the call back.
function Timer:Activate()
if(self.callbackFunc) then
self:callbackFunc();
end
end
-- whether the timer is going to be called at least once in the future.
-- NOTE: this may not be accurate if scene is reset.
function Timer:IsEnabled()
return self.enabled;
end
--------------------------------------
-- timer manager: it groups timers with their intervals and check if any of them needs to be activated.
--------------------------------------
-- a table of newly added timers.
local new_timers;
-- if timer is started.
local IsStarted = false;
local npl_profiler;
-- create a global timer for all sub timers.
function TimerManager.Start()
-- clear all timers
NPL.SetTimer(TimerManager.timer_id, 0.01, ";commonlib.TimerManager.OnTimer();");
NPL.load("(gl)script/ide/Debugger/NPLProfiler.lua");
npl_profiler = npl_profiler or commonlib.gettable("commonlib.npl_profiler");
end
function TimerManager.Stop()
NPL.KillTimer(TimerManager.timer_id);
end
function TimerManager.Restart()
NPL.KillTimer(TimerManager.timer_id);
NPL.SetTimer(TimerManager.timer_id, 0.01, ";commonlib.TimerManager.OnTimer();");
end
-- check if c++ timer is still valid
function TimerManager.CheckTimer()
local last_tick = ParaGlobal_timeGetTime();
if (not TimerManager.last_tick or (last_tick - TimerManager.last_tick) > 200) then
TimerManager.Restart();
end
end
-- clear all timers
function TimerManager.Clear()
new_timers = {};
activeTimerList:clear();
TimerManager.Stop()
IsStarted = false;
end
-- call this function to either add a timer to the pool or change the timer settings.
-- it will automatically set timer.enabled to true.
-- @param timer: the timer object
function TimerManager.AddTimer(timer)
if(not timer.enabled) then
timer.enabled = true;
-- only add if not already in list
if(not timer.prev and not timer.next) then
-- start immediately on load
if(not IsStarted) then
IsStarted = true;
TimerManager.Start();
end
-- note: we should never modify the timer pool directly, since this function may be inside the timer loop.
-- add to new timer pool if not added before
new_timers = new_timers or {};
new_timers[timer.id] = timer;
end
end
end
-- remove the given timer by id
function TimerManager.RemoveTimer(timer)
timer.enabled = nil;
if(new_timers) then
new_timers[timer.id] = nil;
end
-- note: we should never modify the timer pool directly, since this function may be inside the timer loop.
end
-- dump timer info.
function TimerManager.DumpTimerCount()
local activeCount, totalCount = 0,0;
local timer = activeTimerList:first();
while (timer) do
totalCount = totalCount + 1
if(timer.enabled) then
activeCount = activeCount + 1
end
timer = activeTimerList:next(timer)
end
LOG.std(nil, "info", "timer", "Current Timer Info: Active Timers: %d, Total Timers: %d", activeCount, totalCount);
return activeCount, totalCount;
end
-- the global ParaEngine high resolution timer.
function TimerManager.OnTimer()
npl_profiler.perf_begin("TimerManager.OnTimer");
local last_tick = ParaGlobal_timeGetTime();
TimerManager.last_tick = last_tick;
-- add new timers from the pool
if(new_timers) then
for id, timer in pairs(new_timers) do
-- only add if not already in list
if(not timer.prev and not timer.next) then
activeTimerList:addtail(timer)
end
end
new_timers = nil;
end
-- frame move all timers (Tick timers)
local timer = activeTimerList:first();
while (timer) do
if(timer.enabled) then
timer:Tick(last_tick);
timer = activeTimerList:next(timer)
else
timer = activeTimerList:remove(timer)
end
end
npl_profiler.perf_end("TimerManager.OnTimer");
end
-- get the current time in millisecond. This may be faster than ParaGlobal_timeGetTime() since it is updated only at rendering frame rate.
-- @note the resolution of the timer is same as the scripting frame move rate.
function TimerManager.GetCurrentTime()
return TimerManager.last_tick or TimerManager.timeGetTime();
end
-- same as ParaGlobal.timeGetTime(), it does not cache, but using the current system time.
function TimerManager.timeGetTime()
return ParaGlobal_timeGetTime();
end
-- wait a specified number of milliseconds, and then execute a specified function,
-- and it will continue to execute the function, once at every given time-interval.
-- @return the timer object which can be used to call ClearInterval
function TimerManager.SetInterval(func, milliSecond)
local timer = Timer:new({callbackFunc = func});
timer:Change(milliSecond, milliSecond);
return timer;
end
function TimerManager.ClearInterval(timer)
timer:Change();
end
local timeoutTimers = {};
-- create a timer object that will timeout once and call func.
-- @param milliSecond: default to 1000ms (1 second)
-- @param timerName: if nil, a new timer will always be created for this timeout, if not, we will reuse the same timer object.
-- and reset the timeout, if the same timer is being called in short interval.
-- @return the timer object.
function TimerManager.SetTimeout(func, milliSecond, timerName)
local timer
if(not timerName) then
timer = Timer:new({callbackFunc = func});
else
timer = timeoutTimers[timerName]
if(not timer) then
timer = Timer:new({callbackFunc = func});
timeoutTimers[timerName] = timer;
end
timer.callbackFunc = func or timer.callbackFunc;
end
timer:Change(milliSecond);
return timer;
end
function TimerManager.ClearTimeout(timeoutVariable)
timeoutVariable:Change();
end | gpl-2.0 |
TitanTeamGit/SelfBot | plugins/tools.lua | 1 | 7524 | --set--
local function save_value(msg, name, value)
if (not name or not value) then
return
end
local hash = nil
if msg.to.type == 'channel' then
hash = 'chat:'..msg.to.id..':variables'
end
if msg.to.type == 'chat' then
hash = 'chat:'..msg.to.id..':variables'
end
if msg.to.type == 'user' then
hash = 'user:'..msg.from.id..':variables'
end
if hash then
redis:hset(hash, name, value)
return "Saved "..name.." 👠"..value
end
end
--get--
local function get_variables_hash(msg)
if msg.to.type == 'channel' then
return 'chat:'..msg.to.id..':variables'
end
if msg.to.type == 'chat' then
return 'chat:'..msg.to.id..':variables'
end
if msg.to.type == 'user' then
return 'user:'..msg.from.id..':variables'
end
end
local function list_variables(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
text = text..names[i]..'\n'
end
return text
end
end
local function get_value(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
--insta--
local access_token = "3084249803.280d5d7.999310365c8248f8948ee0f6929c2f02"
local function instagramUser(msg, query)
local receiver = get_receiver(msg)
local url = "https://api.instagram.com/v1/users/search?q="..URL.escape(query).."&access_token="..access_token
local jstr, res = https.request(url)
if res ~= 200 then
return "No Connection"
end
local jdat = json:decode(jstr)
if #jdat.data == 0 then
send_msg(receiver,"#Error\nUsername not found",ok_cb,false)
end
if jdat.meta.error_message then
send_msg(receiver,"#Error\n"..jdat.meta.error_message,ok_cb,false)
end
local id = jdat.data[1].id
local gurl = "https://api.instagram.com/v1/users/"..id.."/?access_token="..access_token
local ress = https.request(gurl)
local user = json:decode(ress)
if user.meta.error_message then
send_msg(receiver,"#Error\n"..user.meta.error_message,ok_cb,false)
end
local text = ''
if user.data.bio ~= '' then
text = text.."Username: "..user.data.username:upper().."\n\n"
else
text = text.."Username: "..user.data.username:upper().."\n"
end
if user.data.bio ~= '' then
text = text..user.data.bio.."\n\n"
end
if user.data.full_name ~= '' then
text = text.."Name: "..user.data.full_name.."\n"
end
text = text.."Media Count: "..user.data.counts.media.."\n"
text = text.."Following: "..user.data.counts.follows.."\n"
text = text.."Followers: "..user.data.counts.followed_by.."\n"
if user.data.website ~= '' then
text = text.."Website: "..user.data.website.."\n"
end
text = text
local file_path = download_to_file(user.data.profile_picture,"insta.png") -- disable this line if you want to send profile photo as sticker
local file_path = download_to_file(user.data.profile_picture,"insta.webp") -- enable this line if you want to send profile photo as sticker
local cb_extra = {file_path=file_path}
local mime_type = mimetype.get_content_type_no_sub(ext)
send_photo(receiver, file_path, rmtmp_cb, cb_extra) -- disable this line if you want to send profile photo as sticker
--send_document(receiver, file_path, rmtmp_cb, cb_extra) -- enable this line if you want to send profile photo as sticker
send_msg(receiver,text,ok_cb,false)
end
local function instagramMedia(msg, query)
local receiver = get_receiver(msg)
local url = "https://api.instagram.com/v1/media/shortcode/"..URL.escape(query).."?access_token="..access_token
local jstr, res = https.request(url)
if res ~= 200 then
return "No Connection"
end
local jdat = json:decode(jstr)
if jdat.meta.error_message then
send_msg(receiver,"#Error\n"..jdat.meta.error_type.."\n"..jdat.meta.error_message,ok_cb,false)
end
local text = ''
local data = ''
if jdat.data.caption then
data = jdat.data.caption
text = text.."Username: "..data.from.username:upper().."\n\n"
text = text..data.from.full_name.."\n\n"
text = text..data.text.."\n\n"
text = text.."Like Count: "..jdat.data.likes.count.."\n"
else
text = text.."Username: "..jdat.data.user.username:upper().."\n"
text = text.."Name: "..jdat.data.user.full_name.."\n"
text = text.."Like Count: "..jdat.data.likes.count.."\n"
end
text = text
send_msg(receiver,text,ok_cb,false)
end
--google--
local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
if matches[1] == 'google' then
local results = googlethat(matches[1])
return 'نتایج جستجو\n\n'..stringlinks(results)
end
if matches[1] == 'webshot' then
local find = get_webshot_url(matches[2])
if find then
local imgurl = base .. find
local receiver = get_receiver(msg)
send_photo_from_url(receiver, imgurl)
end
end
if matches[1] == 'sticker' then
local texturl = "http://latex.codecogs.com/png.download?".."\\dpi{800}%20\\LARGE%20"..URL.escape(matches[2])
local receiver = get_receiver(msg)
local file = download_to_file(texturl,'text.webp')
send_document('chat#id'..msg.to.id, file, ok_cb , false)
send_document('channel#id'..msg.to.id, file, ok_cb , false)
end
if matches[1] == 'voice' then
local voiceapi = "http://tts.baidu.com/text2audio?lan=en&ie=UTF-8&text="..URL.escape(matches[2])
local receiver = get_receiver(msg)
local file = download_to_file(voiceapi,'text.ogg')
send_audio('channel#id'..msg.to.id, file, ok_cb , false)
send_audio('chat#id'..msg.to.id, file, ok_cb , false)
end
if matches[1] == "insta" and not matches[3] and is_sudo(msg) then
return instagramUser(msg,matches[2])
end
if matches[1] == "insta" and matches[3] and is_sudo(msg) then
local media = matches[3]
if string.match(media , '/') then media = media:gsub("/", "") end
return instagramMedia(msg,media)
end
if matches[1] == 'set' and is_sudo(msg) then
local name = string.sub(matches[2], 1, 50)
local value = string.sub(matches[3], 1, 1000)
local text = save_value(msg, name, value)
return text
end
if matches[1] == 'get' and is_sudo(msg) then
if matches[2] then
return get_value(msg, matches[2])
else
return list_variables(msg)
end
end
end
return {
description = "funny plugin",
usage = "see commands in patterns",
patterns = {
"^(google) (.*)$",
"^(webshot) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^(voice) (.+)$",
"^(insta) ([Hh]ttps://www.instagram.com/p/)([^%s]+)$",
"^(insta) ([Hh]ttps://instagram.com/p/)([^%s]+)$",
"^(insta) ([Hh]ttp://www.instagram.com/p/)([^%s]+)$",
"^(insta) ([Hh]ttp://instagram.com/p/)([^%s]+)$",
"^(insta) (.*)$",
"^(set) ([^%s]+) (.*)$",
"^(get) (.*)$",
"^(sticker) (.*)$",
},
run = run
}
| gpl-2.0 |
OpenNMT/OpenNMT | test/onmt/RNNTest.lua | 8 | 2416 | require('onmt.init')
local tester = ...
local rnnTest = torch.TestSuite()
local function checkModuleCount(obj, name, exp)
local count = 0
obj:apply(function (m)
if torch.typename(m) == name then
count = count + 1
end
end)
tester:eq(count, exp)
end
local function buildStates(count, batchSize, dim)
local states = {}
for _ = 1, count do
table.insert(states, torch.Tensor(batchSize, dim):zero())
end
return states
end
local function testRNN(cell, layers, inputSize, hiddenSize, dropout, residual, dropout_input)
local rnn = cell(layers, inputSize, hiddenSize, dropout, residual, dropout_input)
local numStates = torch.typename(rnn) == 'onmt.GRU' and 1 or 2
local inputs = buildStates(layers * numStates, 2, hiddenSize)
table.insert(inputs, torch.Tensor(2, inputSize):uniform())
local expectedDropout = 0
expectedDropout = expectedDropout + layers - 1
if dropout_input then
expectedDropout = expectedDropout + 1
end
checkModuleCount(rnn, 'nn.Dropout', expectedDropout)
local outputs = rnn:forward(inputs)
if type(outputs) ~= 'table' then
tester:eq(layers, 1)
tester:eq(numStates, 1)
outputs = { outputs }
end
tester:eq(#outputs, layers * numStates)
for i = 1, #outputs do
tester:eq(outputs[i]:size(), torch.LongStorage({2, hiddenSize}))
end
end
function rnnTest.LSTM_oneLayer()
testRNN(onmt.LSTM, 1, 10, 20)
end
function rnnTest.LSTM_oneLayerWithInputDropout()
testRNN(onmt.LSTM, 1, 10, 20, 0.3, false, true)
end
function rnnTest.LSTM_oneLayerWithoutInputDropout()
testRNN(onmt.LSTM, 1, 10, 20, 0, false, true)
end
function rnnTest.LSTM_twoLayers()
testRNN(onmt.LSTM, 2, 10, 20)
end
function rnnTest.LSTM_twoLayersWithDropout()
testRNN(onmt.LSTM, 2, 10, 20, 0.3)
end
function rnnTest.LSTM_twoLayersWithInputDropout()
testRNN(onmt.LSTM, 2, 10, 20, 0.3, false, true)
end
function rnnTest.GRU_oneLayer()
testRNN(onmt.GRU, 1, 10, 20)
end
function rnnTest.GRU_oneLayerWithInputDropout()
testRNN(onmt.GRU, 1, 10, 20, 0.3, false, true)
end
function rnnTest.GRU_oneLayerWithoutInputDropout()
testRNN(onmt.LSTM, 1, 10, 20, 0, false, true)
end
function rnnTest.GRU_twoLayers()
testRNN(onmt.GRU, 2, 10, 20)
end
function rnnTest.GRU_twoLayersWithDropout()
testRNN(onmt.GRU, 2, 10, 20, 0.3)
end
function rnnTest.GRU_twoLayersWithInputDropout()
testRNN(onmt.GRU, 2, 10, 20, 0.3, false, true)
end
return rnnTest
| mit |
NPLPackages/main | script/ide/System/Database/SqliteIndexTable.lua | 1 | 10869 | --[[
Title: Index table for sqlitestore
Author(s): LiXizhi,
Date: 2016/5/11
Desc: mostly for index-intersection, this is very different from CompoundIndex.
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/ide/System/Database/SqliteIndexTable.lua");
local IndexTable = commonlib.gettable("System.Database.SqliteStore.IndexTable");
------------------------------------------------------------
]]
local IndexTable = commonlib.inherit(nil, commonlib.gettable("System.Database.SqliteStore.IndexTable"));
local tostring = tostring;
local kIndexTableColumns = [[
(name BLOB UNIQUE PRIMARY KEY,
cid TEXT)]];
function IndexTable:ctor()
self.names = {};
self.statements = {};
end
function IndexTable:init(name, parent)
self.name = name;
self:AddKeyName(name);
self.parent = parent;
return self;
end
function IndexTable:GetName()
return self.name;
end
-- get all key names {name=true, ...}, where this index can be used for query
function IndexTable:GetKeyNames()
return self.names;
end
function IndexTable:AddKeyName(name)
self.names[name] = true;
end
-- return true if this index support query for the given key name
function IndexTable:HasKeyName(name)
return name and self.names[name];
end
-- check if this index fully contains another index.
function IndexTable:isSuperSetOf(otherIndex)
for name, _ in pairs(otherIndex:GetKeyNames()) do
if(not self:HasKeyName(name)) then
return false;
end
end
return true;
end
function IndexTable:GetDB()
return self.parent._db;
end
function IndexTable:GetTableName()
if(not self.tableName) then
-- TODO: normalize name?
self.tableName = self.name.."Index";
end
return self.tableName;
end
function IndexTable:CloseSQLStatement(name)
if(self[name]) then
self[name]:close();
self[name] = nil;
end
end
-- get cached sql statement
function IndexTable:GetStatement(sql)
local stat = self.statements[sql];
if(not stat) then
local err;
stat, err = self:GetDB():prepare(sql);
if(not stat and err) then
LOG.std(nil, "error", "SqliteStore", "error for sql statement %s, reason: %s", sql, tostring(err));
end
self.statements[sql] = stat;
end
return stat;
end
-- When sqlite_master table(schema) is changed, such as when new index table is created,
-- all cached statements becomes invalid. And this function should be called to purge all statements created before.
function IndexTable:ClearStatementCache()
self:CloseSQLStatement("add_stat");
self:CloseSQLStatement("del_stat");
self:CloseSQLStatement("select_stat");
self:CloseSQLStatement("select_gt_stat");
self:CloseSQLStatement("select_ids_stat");
self:CloseSQLStatement("sel_all_stat");
self:CloseSQLStatement("update_stat");
if(next(self.statements)) then
for name, stat in pairs(self.statements) do
stat:close();
end
self.statements = {};
end
end
-- get first matching row id
-- @param value: value of the key to get
-- @return id: where id is the collection id number or nil if not found
function IndexTable:getId(value)
local ids = self:getIds(value);
if(ids) then
return tonumber(ids:match("^%d+"));
end
end
-- get total key count.
-- @param value: value of the key to get
function IndexTable:getCount(value)
local ids = self:getIds(value);
if(ids) then
local count = 1;
for _ in ids:gmatch(",") do
count = count + 1;
end
return count
else
return 0;
end
end
-- @param value: any number or string value. or table { [1]=value, gt = value, lt=value, limit = number, offset|skip=number }.
-- value.gt: greater than this value, result in accending order
-- value.lt: less than this value
-- value[1]: equal to this value
-- value.limit: max number of rows to return, default to 20. if there are duplicated items, it may exceed this number.
-- value.offset|skip: default to 0.
-- return all ids as commar separated string
function IndexTable:getIds(value)
if(value) then
local greaterthan, lessthan, eq, limit, offset;
if(type(value) == "table") then
greaterthan = value["gt"];
lessthan = value["lt"];
eq = value[1];
limit = value.limit or 20;
offset = value.offset or value.skip or 0;
if(not greaterthan and not lessthan and not eq) then
LOG.std(nil, "error", "IndexTable", "operator not found");
return;
end
else
eq = value;
end
if(eq~=nil and not greaterthan and not lessthan) then
self.select_stat = self.select_stat or self:GetDB():prepare([[SELECT cid FROM ]]..self:GetTableName()..[[ WHERE name=?]]);
if(self.select_stat) then
self.select_stat:bind(eq);
self.select_stat:reset();
local row = self.select_stat:first_row();
if(row) then
return row.cid;
end
else
LOG.std(nil, "error", "IndexTable", "failed to create select statement");
end
elseif(greaterthan) then
if(not self.select_gt_stat) then
self.select_gt_stat = self:GetDB():prepare([[SELECT cid FROM ]]..self:GetTableName()..[[ WHERE name>? ORDER BY name ASC LIMIT ?,?]]);
end
if(self.select_gt_stat) then
self.select_gt_stat:bind(greaterthan, offset, limit);
self.select_gt_stat:reset();
local cid;
for row in self.select_gt_stat:rows() do
cid = cid and (cid .. "," .. row.cid) or tostring(row.cid);
end
return cid;
else
LOG.std(nil, "error", "IndexTable", "failed to create select statement");
end
else
LOG.std(nil, "error", "IndexTable", "unknown operator %s", tostring(operator));
end
end
end
-- @param cid: collection id
-- @param newRow: can be partial row containing the changed value
-- @param oldRow: can be partial row containing the old value
function IndexTable:updateIndex(cid, newRow, oldRow)
if(newRow) then
local newIndexValue = newRow[self.name];
if(newIndexValue~=nil) then
if(newRow and oldRow) then
local oldIndexValue = oldRow[self.name];
if(newIndexValue ~= oldIndexValue) then
if(oldIndexValue~=nil) then
self:removeIndex(oldRow, cid);
end
self:addIndex(newRow, cid);
end
else
self:addIndex(newRow, cid);
end
end
end
end
-- add index to collection row id
-- @param row: row data
-- @param cid: collection row id
function IndexTable:addIndex(row, cid)
local value;
if(type(row) == "table") then
value = row[self.name];
end
if(value~=nil and cid) then
cid = tostring(cid);
local ids = self:getIds(value);
if(not ids) then
self.add_stat = self.add_stat or self:GetDB():prepare([[INSERT INTO ]]..self:GetTableName()..[[(name, cid) VALUES (?, ?)]]);
self.add_stat:bind(value, cid);
self.add_stat:exec();
elseif(ids ~= cid and not self:hasIdInIds(cid, ids)) then
ids = self:addIdToIds(cid, ids);
self.update_stat = self.update_stat or self:GetDB():prepare([[UPDATE ]]..self:GetTableName()..[[ Set cid=? Where name=?]]);
self.update_stat:bind(ids, value);
self.update_stat:exec();
end
end
end
-- this will remove the index to collection db for the given keyvalue.
-- but it does not remove the real data item in collection db.
-- @param row: table row
-- @param cid: default to nil. if not nil we will only remove when collection row id matches this one.
function IndexTable:removeIndex(row, cid)
local value;
if(type(row) == "table") then
value = row[self.name];
end
if(value~=nil) then
if(cid) then
cid = tostring(cid);
local ids = self:getIds(value);
if(ids) then
if(ids == cid) then
self:removeIndex(row);
else
local new_ids = self:removeIdInIds(cid, ids);
if(new_ids ~= ids) then
if(new_ids ~= "") then
self.update_stat = self.update_stat or self:GetDB():prepare([[UPDATE ]]..self:GetTableName()..[[ Set cid=? Where name=?]]);
self.update_stat:bind(new_ids, value);
self.update_stat:exec();
else
self:removeIndex(row);
end
else
-- no index found
end
end
end
else
self.del_stat = self.del_stat or self:GetDB():prepare([[DELETE FROM ]]..self:GetTableName()..[[ WHERE name=?]]);
if(self.del_stat) then
self.del_stat:bind(value);
self.del_stat:exec();
else
LOG.std(nil, "error", "IndexTable", "failed to create delete statement");
end
end
end
end
-- private:
-- @param cid, ids: must be string
-- return true if cid string is in ids string.
function IndexTable:hasIdInIds(cid, ids)
if(cid == ids) then
return true;
else
-- TODO: optimize this function with C++
ids = ","..ids..",";
return ids:match(","..cid..",") ~= nil;
end
end
-- private:
-- @param cid, ids: must be string
-- @return ids: new ids with cid removed
function IndexTable:removeIdInIds(cid, ids)
if(cid == ids) then
return "";
else
-- TODO: optimize this function with C++
local tmp_ids = ","..ids..",";
local new_ids = tmp_ids:gsub(",("..cid..",)", ",");
if(new_ids~=tmp_ids) then
return new_ids:gsub("^,", ""):gsub(",$", "");
else
return ids;
end
end
end
function IndexTable:addIdToIds(cid, ids)
return ids..(","..cid)
end
-- creating index for existing rows
function IndexTable:CreateTable()
self.parent:FlushAll();
-- fetch all index before creating table, otherwise we will need to call ClearStatementCache twice.
local indexmap = {};
local name = self.name;
self.parent:find({}, function(err, rows)
if(rows) then
for _, row in ipairs(rows) do
if(row and row[name]) then
local keyValue = row[name]
if(keyValue) then
if(not indexmap[keyValue]) then
indexmap[keyValue] = tostring(row._id);
else
indexmap[keyValue] = indexmap[keyValue]..(","..tostring(row._id));
end
end
end
end
end
end)
-- create table
local stat = self:GetDB():prepare([[INSERT INTO Indexes (name, tablename) VALUES (?, ?)]]);
stat:bind(self.name, self:GetTableName());
stat:exec();
stat:close();
local sql = "CREATE TABLE IF NOT EXISTS ";
sql = sql..self:GetTableName().." "
sql = sql..kIndexTableColumns;
self:GetDB():exec(sql);
-- rebuild all indices
self.parent:Begin();
local count = 0;
local stmt = self:GetDB():prepare([[INSERT INTO ]]..self:GetTableName()..[[ (name, cid) VALUES (?, ?)]]);
for name, cid in pairs(indexmap) do
stmt:bind(name, cid);
stmt:exec();
count = count + 1;
end
stmt:close();
LOG.std(nil, "info", "SqliteStore", "index table is created for `%s` with %d records", self.name, count);
self.parent:End();
self.parent:FlushAll();
-- after inserting tables, all statements shoudl be purged
self.parent:ClearStatementCache();
end
function IndexTable:Destroy()
self.parent:FlushAll();
self:ClearStatementCache();
self:GetDB():exec(format("DELETE FROM Indexes WHERE name='%s'", self.name));
self:GetDB():exec("DROP TABLE "..self:GetTableName());
-- self:GetDB():exec("DELETE FROM "..self:GetTableName());
LOG.std(nil, "info", "SqliteStore", "index `%s` removed from %s", self.name, self.parent:GetFileName());
self.parent:ClearStatementCache();
end | gpl-2.0 |
thedraked/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Loillie.lua | 14 | 1633 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Loillie
-- @zone 80
-- @pos 78 -8 -23
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 2) then
local mask = player:getVar("GiftsOfGriffonPlumes");
if (trade:hasItemQty(2528,1) and trade:getItemCount() == 1 and not player:getMaskBit(mask,6)) then
player:startEvent(0x01D) -- Gifts of Griffon Trade
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0265); -- Default Dialogue
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x01D) then -- Gifts Of Griffon Trade
player:tradeComplete();
local mask = player:getVar("GiftsOfGriffonPlumes");
player:setMaskBit(mask,"GiftsOfGriffonPlumes",6,true);
end
end; | gpl-3.0 |
thedraked/darkstar | scripts/zones/Nashmau/npcs/Chichiroon.lua | 17 | 1298 | -----------------------------------
-- Area: Nashmau
-- NPC: Chichiroon
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Nashmau/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,CHICHIROON_SHOP_DIALOG);
stock = {0x1579,99224, --Bolter's Die
0x157a,85500, --Caster's Die
0x157b,97350, --Courser's Die
0x157c,100650, --Blitzer's Die
0x157d,109440, --Tactician's Die
0x157e,116568} --Allies' Die
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
mtroyka/Zero-K | lups/lups.lua | 1 | 31289 | -- $Id: lups.lua 4099 2009-03-16 05:18:45Z jk $
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
--
-- file: api_gfx_lups.lua
-- brief: Lua Particle System
-- authors: jK
-- last updated: Jan. 2008
--
-- Copyright (C) 2007,2008.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
local function GetInfo()
return {
name = "Lups",
desc = "Lua Particle System",
author = "jK",
date = "2008-2014",
license = "GNU GPL, v2 or later",
layer = 1000,
api = true,
enabled = true
}
end
--// FIXME
-- 1. add los handling (inRadar,alwaysVisible, etc.)
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// Error Log Handling
PRIO_MAJOR = 0
PRIO_ERROR = 1
PRIO_LESS = 2
local errorLog = {}
local printErrorsAbove = PRIO_MAJOR
function print(priority,...)
local errorMsg = ""
for i=1,select('#',...) do
errorMsg = errorMsg .. select(i,...)
end
errorLog[#errorLog+1] = {priority=priority,message=errorMsg}
if (priority<=printErrorsAbove) then
Spring.Echo(...)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// locals
local push = table.insert
local pop = table.remove
local StrToLower = string.lower
local pairs = pairs
local ipairs = ipairs
local next = next
local spGetUnitRadius = Spring.GetUnitRadius
local spIsUnitVisible = Spring.IsUnitVisible
local spIsSphereInView = Spring.IsSphereInView
local spGetUnitLosState = Spring.GetUnitLosState
local spGetUnitViewPosition = Spring.GetUnitViewPosition
local spGetUnitDirection = Spring.GetUnitDirection
local spGetHeadingFromVector = Spring.GetHeadingFromVector
local spGetUnitIsActive = Spring.GetUnitIsActive
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local spGetGameFrame = Spring.GetGameFrame
local spGetFrameTimeOffset = Spring.GetFrameTimeOffset
local spGetUnitPieceList = Spring.GetUnitPieceList
local spGetSpectatingState = Spring.GetSpectatingState
local spGetLocalAllyTeamID = Spring.GetLocalAllyTeamID
local scGetReadAllyTeam = Script.GetReadAllyTeam
local spGetUnitPieceMap = Spring.GetUnitPieceMap
local spValidUnitID = Spring.ValidUnitID
local spGetUnitIsStunned = Spring.GetUnitIsStunned
local spGetProjectilePosition = Spring.GetProjectilePosition
local glUnitPieceMatrix = gl.UnitPieceMatrix
local glPushMatrix = gl.PushMatrix
local glPopMatrix = gl.PopMatrix
local glTranslate = gl.Translate
local glRotate = gl.Rotate
local glScale = gl.Scale
local glBlending = gl.Blending
local glAlphaTest = gl.AlphaTest
local glDepthTest = gl.DepthTest
local glDepthMask = gl.DepthMask
local glUnitMultMatrix = gl.UnitMultMatrix
local glUnitPieceMultMatrix = gl.UnitPieceMultMatrix
local GL_GREATER = GL.GREATER
local GL_ONE = GL.ONE
local GL_SRC_ALPHA = GL.SRC_ALPHA
local GL_ONE_MINUS_SRC_ALPHA = GL.ONE_MINUS_SRC_ALPHA
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// hardware capabilities
local GL_VENDOR = 0x1F00
local GL_RENDERER = 0x1F01
local GL_VERSION = 0x1F02
local glVendor = gl.GetString(GL_VENDOR)
local glRenderer = (gl.GetString(GL_RENDERER)):lower()
isNvidia = (glVendor:find("NVIDIA"))
isATI = (glVendor:find("ATI "))
isMS = (glVendor:find("Microsoft"))
isIntel = (glVendor:find("Intel"))
canCTT = (gl.CopyToTexture ~= nil)
canFBO = (gl.DeleteTextureFBO ~= nil)
canRTT = (gl.RenderToTexture ~= nil)
canShader = (gl.CreateShader ~= nil)
canDistortions = false --// check Initialize()
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// widget/gadget handling
local handler = (widget and widgetHandler)or(gadgetHandler)
local GG = (widget and WG)or(GG)
local VFSMODE = (widget and VFS.RAW_FIRST)or(VFS.ZIP_ONLY)
--// locations
local LUPS_LOCATION = 'lups/'
local PCLASSES_DIRNAME = LUPS_LOCATION .. 'ParticleClasses/'
local HEADERS_DIRNAME = LUPS_LOCATION .. 'headers/'
--// helpers
VFS.Include(LUPS_LOCATION .. 'loadconfig.lua',nil,VFSMODE)
--// load some headers
VFS.Include(HEADERS_DIRNAME .. 'general.lua',nil,VFSMODE)
VFS.Include(HEADERS_DIRNAME .. 'mathenv.lua',nil,VFSMODE)
VFS.Include(HEADERS_DIRNAME .. 'figures.lua',nil,VFSMODE)
VFS.Include(HEADERS_DIRNAME .. 'vectors.lua',nil,VFSMODE)
VFS.Include(HEADERS_DIRNAME .. 'hsl.lua',nil,VFSMODE)
VFS.Include(HEADERS_DIRNAME .. 'nanoupdate.lua',nil,VFSMODE)
--// load binary insert library
VFS.Include(HEADERS_DIRNAME .. 'tablebin.lua')
local flayer_comp = function( partA,partB )
return ( partA==partB )or
( (partA.layer==partB.layer)and((partA.unit or -1)<(partB.unit or -1)) )or
( partA.layer<partB.layer )
end
--// workaround for broken UnitDraw() callin
local nilDispList
--// global function (fx classes can use it) for easier access to Lups.cfg
function GetLupsSetting(key, default)
local value = LupsConfig[key]
if (value~=nil) then
return value
else
return default
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// some global vars (so the effects can use them)
vsx, vsy, vpx, vpy = Spring.GetViewGeometry() --// screen pos & view pos (view pos only unequal zero if dualscreen+minimapOnTheLeft)
LocalAllyTeamID = 0
thisGameFrame = 0
frameOffset = 0
LupsConfig = {}
local noDrawUnits = {}
function SetUnitLuaDraw(unitID,nodraw)
if (nodraw) then
noDrawUnits[unitID] = (noDrawUnits[unitID] or 0) + 1
if (noDrawUnits[unitID]==1) then
--if (Game.version=="0.76b1") then
Spring.UnitRendering.ActivateMaterial(unitID,1)
--Spring.UnitRendering.SetLODLength(unitID,1,-1000)
for pieceID in ipairs(Spring.GetUnitPieceList(unitID) or {}) do
Spring.UnitRendering.SetPieceList(unitID,1,pieceID,nilDispList)
end
--else
-- Spring.UnitRendering.SetUnitLuaDraw(unitID,true)
--end
end
else
noDrawUnits[unitID] = (noDrawUnits[unitID] or 0) - 1
if (noDrawUnits[unitID]==0) then
--if (Game.version=="0.76b1") then
Spring.UnitRendering.DeactivateMaterial(unitID,1)
--else
-- Spring.UnitRendering.SetUnitLuaDraw(unitID,false)
--end
noDrawUnits[unitID] = nil
end
end
end
local function DrawUnit(_,unitID,drawMode)
--[[
drawMode:
notDrawing = 0,
normalDraw = 1,
shadowDraw = 2,
reflectionDraw = 3,
refractionDraw = 4
--]]
if (drawMode==1)and(noDrawUnits[unitID]) then
return true
end
return false
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local oldVsx,oldVsy = vsx-1,vsy-1
--// load particle classes
local fxClasses = {}
local DistortionClass
local files = VFS.DirList(PCLASSES_DIRNAME, "*.lua",VFSMODE)
for _,filename in ipairs(files) do
local Class = VFS.Include(filename,nil,VFSMODE)
if (Class) then
if (Class.GetInfo) then
Class.pi = Class.GetInfo()
local sClassName = string.lower(Class.pi.name)
if (fxClasses[sClassName]) then
print(PRIO_LESS,'LUPS: duplicated particle class name "' .. sClassName .. '"')
else
fxClasses[sClassName] = Class
end
else
print(PRIO_ERROR,'LUPS: "' .. Class .. '" is missing GetInfo() ')
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// saves all particles
particles = {}
local particles = particles
local particlesCount = 0
local RenderSequence = {} --// mult-dim table with: [layer][partClass][unitID][fx]
local effectsInDelay = {} --// fxs which use the delay tag, and waiting for their spawn
local partIDCount = 0 --// increasing ID used to identify the particles
--[[
local function DebugPieces(unit,piecenum,level)
local piece = Spring.GetUnitPieceInfo(unit,piecenum)
Spring.Echo( string.rep(" ", level) .. "->" .. piece.name .. " (" .. piecenum .. ")")
for _,pieceChildName in ipairs(piece.children) do
local pieceNum = spGetUnitPieceMap(unit)[pieceChildName]
DebugPieces(unit,pieceNum,level+1)
end
end
--]]
--// the id param is internal don't use it!
function AddParticles(Class,Options ,__id)
if (not Options) then
print(PRIO_LESS,'LUPS->AddFX: no options given');
return -1;
end
if Options.quality and Options.quality > GetLupsSetting("quality", 3) then
return -1;
end
if (Options.delay and Options.delay~=0) then
partIDCount = partIDCount+1
newOptions = {}; CopyTable(newOptions,Options); newOptions.delay=nil
effectsInDelay[#effectsInDelay+1] = {frame=thisGameFrame+Options.delay, class=Class, options=newOptions, id=partIDCount};
return partIDCount
end
Class = StrToLower(Class)
local particleClass = fxClasses[Class]
if (not particleClass) then
print(PRIO_LESS,'LUPS->AddFX: couldn\'t find a particle class named "' .. Class .. '"');
return -1;
end
if (Options.unit)and(not spValidUnitID(Options.unit)) then
print(PRIO_LESS,'LUPS->AddFX: unit is already dead/invalid "' .. Class .. '"');
return -1;
end
--// piecename to piecenum conversion (spring >=76b1 only!)
if (Options.unit and Options.piece) then
local pieceMap = spGetUnitPieceMap(Options.unit)
Options.piecenum = pieceMap and pieceMap[Options.piece] --added check. switching spectator view can cause "attempt to index a nil value"
if (not Options.piecenum) then
local udid = Spring.GetUnitDefID(Options.unit)
if (not udid) then
print(PRIO_LESS,"LUPS->AddFX:wrong unitID")
else
print(PRIO_ERROR,"LUPS->AddFX:wrong unitpiece " .. Options.piece .. "(" .. UnitDefs[udid].name .. ")")
end
return -1;
end
end
--Spring.Echo("-------------")
--DebugPieces(Options.unit,1,0)
local newParticles,reusedFxID = particleClass.Create(Options)
if (newParticles) then
particlesCount = particlesCount + 1;
if (__id) then
newParticles.id = __id
else
partIDCount = partIDCount+1
newParticles.id = partIDCount
end
particles[ newParticles.id ] = newParticles
local space = ((not newParticles.worldspace) and newParticles.unit) or (-1)
local fxTable = CreateSubTables(RenderSequence,{newParticles.layer,particleClass,space})
newParticles.fxTable = fxTable
fxTable[#fxTable+1] = newParticles
return newParticles.id;
else
if (reusedFxID) then
return reusedFxID;
else
if (newParticles~=false) then
print(PRIO_LESS,"LUPS->AddFX:FX creation failed");
end
return -1;
end
end
end
function AddParticlesArray(array)
local class = ""
for i=1,#array do
local fxSettings = array[i]
class = fxSettings.class
fxSettings.class = nil
AddParticles(class,fxSettings)
end
end
function GetParticles(particlesID)
return particles[particlesID]
end
function RemoveParticles(particlesID)
local fx = particles[particlesID]
if (fx) then
if (type(fx.fxTable)=="table") then
for j,w in pairs(fx.fxTable) do
if (w.id==particlesID) then
pop(fx.fxTable,j)
end
end
end
fx:Destroy()
particles[particlesID] = nil
particlesCount = particlesCount-1;
return
else
local status,err = pcall(function()
--//FIXME
for i=1,#effectsInDelay do
if (effectsInDelay[i].id==particlesID) then
table.remove(effectsInDelay,i)
return
end
end
--//
end)
if (not status) then
Spring.Echo("Error (Lups) - "..(#effectsInDelay).." :"..err)
for i=1,#effectsInDelay do
Spring.Echo("->",effectsInDelay[i],type(effectsInDelay[i]))
end
effectsInDelay = {}
end
end
end
function GetStats()
local count = particlesCount
local effects = {}
local layers = 0
for i=-50,50 do
if (RenderSequence[i]) then
local layer = RenderSequence[i];
if (next(layer or {})) then layers=layers+1 end
for partClass,Units in pairs(layer) do
if (not effects[partClass.pi.name]) then
effects[partClass.pi.name] = {0,0} --//[1]:=fx count [2]:=part count
end
for unitID,UnitEffects in pairs(Units) do
for _,fx in pairs(UnitEffects) do
effects[partClass.pi.name][1] = effects[partClass.pi.name][1] + 1
effects[partClass.pi.name][2] = effects[partClass.pi.name][2] + (fx.count or 0)
--count = count+1
end
end
end
end
end
return count,layers,effects
end
function HasParticleClass(ClassName)
local Class = StrToLower(ClassName)
return (fxClasses[Class] and true)or(false)
end
function GetErrorLog(minPriority)
if (minPriority) then
local log = ""
for i=1,#errorLog do
if (errorLog[i].priority<=minPriority) then
log = log .. errorLog[i].message .. "\n"
end
end
if (log~="") then
local sysinfo = "Vendor:" .. glVendor ..
"\nRenderer:" .. glRenderer ..
(((isATI)and("\nisATI: true"))or("")) ..
(((isMS)and("\nisMS: true"))or("")) ..
(((isIntel)and("\nisIntel: true"))or("")) ..
"\ncanFBO:" .. tostring(canFBO) ..
"\ncanRTT:" .. tostring(canRTT) ..
"\ncanCTT:" .. tostring(canCTT) ..
"\ncanShader:" .. tostring(canShader) .. "\n"
log = sysinfo..log
end
return log
else
if (errorlog~="") then
local sysinfo = "Vendor:" .. glVendor ..
"\nRenderer:" .. glRenderer ..
"\nisATI:" .. tostring(isATI) ..
"\nisMS:" .. tostring(isMS) ..
"\nisIntel:" .. tostring(isIntel) ..
"\ncanFBO:" .. tostring(canFBO) ..
"\ncanRTT:" .. tostring(canRTT) ..
"\ncanCTT:" .. tostring(canCTT) ..
"\ncanShader:" .. tostring(canShader) .. "\n"
return sysinfo..errorLog
else
return errorLog
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local anyFXVisible = false
local anyDistortionsVisible = false
local function Draw(extension,layer)
local FxLayer = RenderSequence[layer];
if (not FxLayer) then return end
local BeginDrawPass = "BeginDraw"..extension
local DrawPass = "Draw"..extension
local EndDrawPass = "EndDraw"..extension
for partClass,Units in pairs(FxLayer) do
local beginDraw = partClass[BeginDrawPass]
if (beginDraw) then
beginDraw()
local drawfunc = partClass[DrawPass]
if (not next(Units)) then
FxLayer[partClass]=nil
else
for unitID,UnitEffects in pairs(Units) do
if (not UnitEffects[1]) then
Units[unitID]=nil
else
if (unitID>-1) then
------------------------------------------------------------------------------------
-- render in unit/piece space ------------------------------------------------------
------------------------------------------------------------------------------------
glPushMatrix()
glUnitMultMatrix(unitID)
--// render effects
for i=1,#UnitEffects do
local fx = UnitEffects[i]
if (fx.alwaysVisible or fx.visible) then
if (fx.piecenum) then
--// enter piece space
glPushMatrix()
glUnitPieceMultMatrix(unitID,fx.piecenum)
glScale(1,1,-1)
drawfunc(fx)
glPopMatrix()
--// leave piece space
else
fx[DrawPass](fx)
end
end
end
--// leave unit space
glPopMatrix()
else
------------------------------------------------------------------------------------
-- render in world space -----------------------------------------------------------
------------------------------------------------------------------------------------
for i=1,#UnitEffects do
local fx = UnitEffects[i]
if (fx.alwaysVisible or fx.visible) then
glPushMatrix()
if fx.projectile and not fx.worldspace then
local x,y,z = spGetProjectilePosition(fx.projectile)
glTranslate(x,y,z)
end
drawfunc(fx)
glPopMatrix()
end
end -- for
end -- if
end --if
end --for
end
partClass[EndDrawPass]()
end
end
end
local function DrawDistortionLayers()
glBlending(GL_ONE,GL_ONE)
for i=-50,50 do
Draw("Distortion",i)
end
glBlending(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)
end
local function DrawParticlesOpaque()
if ( not anyFXVisible ) then return end
vsx, vsy, vpx, vpy = Spring.GetViewGeometry()
if (vsx~=oldVsx)or(vsy~=oldVsy) then
for _,partClass in pairs(fxClasses) do
if partClass.ViewResize then partClass.ViewResize(vsx, vsy) end
end
oldVsx, oldVsy = vsx, vsy
end
glDepthTest(true)
glDepthMask(true)
for i=-50,50 do
Draw("Opaque",i)
end
glDepthMask(false)
glDepthTest(false)
end
local function DrawParticles()
if ( not anyFXVisible ) then return end
glDepthTest(true)
--// Draw() (layers: -50 upto 0)
glAlphaTest(GL_GREATER, 0)
for i=-50,0 do
Draw("",i)
end
glAlphaTest(false)
--// DrawDistortion()
if (anyDistortionsVisible)and(DistortionClass) then
DistortionClass.BeginDraw()
gl.ActiveFBO(DistortionClass.fbo,DrawDistortionLayers)
DistortionClass.EndDraw()
end
--// Draw() (layers: 1 upto 50)
glAlphaTest(GL_GREATER, 0)
for i=1,50 do
Draw("",i)
end
glAlphaTest(false)
glDepthTest(false)
end
local function DrawParticlesWater()
if ( not anyFXVisible ) then return end
glDepthTest(true)
--// DrawOpaque()
glDepthMask(true)
for i=-50,50 do
Draw("Opaque",i)
end
glDepthMask(false)
--// Draw() (layers: -50 upto 50)
glAlphaTest(GL_GREATER, 0)
for i=-50,50 do
Draw("",i)
end
glAlphaTest(false)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local DrawWorldPreUnitVisibleFx
local DrawWorldVisibleFx
local DrawWorldReflectionVisibleFx
local DrawWorldRefractionVisibleFx
local DrawWorldShadowVisibleFx
local DrawScreenEffectsVisibleFx
local DrawInMiniMapVisibleFx
function IsPosInLos(x,y,z)
return LocalAllyTeamID == Script.ALL_ACCESS_TEAM or (LocalAllyTeamID ~= Script.NO_ACCESS_TEAM and Spring.IsPosInLos(x,y,z, LocalAllyTeamID))
end
function IsPosInRadar(x,y,z)
return LocalAllyTeamID == Script.ALL_ACCESS_TEAM or (LocalAllyTeamID ~= Script.NO_ACCESS_TEAM and Spring.IsPosInRadar(x,y,z, LocalAllyTeamID))
end
function IsPosInAirLos(x,y,z)
return LocalAllyTeamID == Script.ALL_ACCESS_TEAM or (LocalAllyTeamID ~= Script.NO_ACCESS_TEAM and Spring.IsPosInAirLos(x,y,z, LocalAllyTeamID))
end
function GetUnitLosState(unitID)
return LocalAllyTeamID == Script.ALL_ACCESS_TEAM or (LocalAllyTeamID ~= Script.NO_ACCESS_TEAM and (Spring.GetUnitLosState(unitID, LocalAllyTeamID) or {}).los) or false
end
local function IsUnitFXVisible(fx)
local unitActive = true
local unitID = fx.unit
if fx.onActive then
unitActive = ((spGetUnitIsActive(unitID) or spGetUnitRulesParam(unitID, "unitActiveOverride") == 1)
and (spGetUnitRulesParam(unitID, "disarmed") ~= 1)
and (spGetUnitRulesParam(unitID, "morphDisable") ~= 1)
and not spGetUnitIsStunned(unitID))
if (unitActive == nil) then
unitActive = true
end
end
if (not fx.onActive) or (unitActive) then
if fx.alwaysVisible then
return true
elseif (fx.Visible) then
return fx:Visible()
else
local unitRadius = (spGetUnitRadius(unitID) or 0) + 40
local r = fx.radius or 0
return Spring.IsUnitVisible(unitID, unitRadius + r)
end
else
return fx.alwaysVisible
end
end
local function IsProjectileFXVisible(fx)
if fx.alwaysVisible then
return true
elseif fx.Visible then
return fx:Visible()
else
local proID = fx.projectile
local x,y,z = Spring.GetProjectilePosition(proID)
if (IsPosInLos(x,y,z)and (spIsSphereInView(x,y,z,(fx.radius or 200)+100)) ) then
return true
end
end
end
local function IsWorldFXVisible(fx)
if fx.alwaysVisible then
return true
elseif (fx.Visible) then
return fx:Visible()
elseif (fx.pos) then
local pos = fx.pos
if (IsPosInLos(pos[1],pos[2],pos[3]))and
(spIsSphereInView(pos[1],pos[2],pos[3],(fx.radius or 200)+100))
then
return true
end
end
end
local function CreateVisibleFxList()
local removeFX = {}
local removeCnt = 1
local foo = 0
for _,fx in pairs(particles) do
foo = foo + 1
if ((fx.unit or -1) > -1) then
fx.visible = IsUnitFXVisible(fx)
if (fx.visible) then
if (not anyFXVisible) then anyFXVisible = true end
if (not anyDistortionsVisible) then anyDistortionsVisible = fx.pi.distortion end
end
elseif ((fx.projectile or -1) > -1) then
fx.visible = IsProjectileFXVisible(fx)
if (fx.visible) then
if (not anyFXVisible) then anyFXVisible = true end
if (not anyDistortionsVisible) then anyDistortionsVisible = fx.pi.distortion end
end
else
fx.visible = IsWorldFXVisible(fx)
if (fx.visible) then
if (not anyFXVisible) then anyFXVisible = true end
if (not anyDistortionsVisible) then anyDistortionsVisible = fx.pi.distortion end
elseif (fx.Valid and (not fx:Valid())) then
removeFX[removeCnt] = fx.id
removeCnt = removeCnt + 1
end
end
end
--Spring.Echo("Lups fx cnt", foo)
for i=1,removeCnt-1 do
RemoveParticles(removeFX[i])
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function CleanInvalidUnitFX()
local removeFX = {}
local removeCnt = 1
for layerID,layer in pairs(RenderSequence) do
for partClass,Units in pairs(layer) do
for unitID,UnitEffects in pairs(Units) do
if (not UnitEffects[1]) then
Units[unitID] = nil
else
if (unitID>-1) then
if (not spValidUnitID(unitID)) then --// UnitID isn't valid anymore, remove all its effects
for i=1,#UnitEffects do
local fx = UnitEffects[i]
removeFX[removeCnt] = fx.id
removeCnt = removeCnt + 1
end
Units[unitID]=nil
end
end
end
end
end
end
for i=1,removeCnt-1 do
RemoveParticles(removeFX[i])
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--// needed to allow to use RemoveParticles in :Update of the particleclasses
local fxRemoveList = {}
function BufferRemoveParticles(id) fxRemoveList[#fxRemoveList+1] = id end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local lastGameFrame = 0
local function GameFrame(_,n)
thisGameFrame = n
if ((not next(particles)) and (not effectsInDelay[1])) then return end
--// update team/player status
local spec, specFullView = spGetSpectatingState()
if (specFullView) then
LocalAllyTeamID = scGetReadAllyTeam() or 0
else
LocalAllyTeamID = spGetLocalAllyTeamID() or 0
end
--// create delayed FXs
if (effectsInDelay[1]) then
local remaingFXs,cnt={},1
for i=1,#effectsInDelay do
local fx = effectsInDelay[i]
if (fx.frame>thisGameFrame) then
remaingFXs[cnt]=fx
cnt=cnt+1
else
AddParticles(fx.class,fx.options, fx.id)
if (fx.frame-thisGameFrame>0) then
particles[fx.id]:Update(fx.frame-thisGameFrame)
end
end
end
effectsInDelay = remaingFXs
end
--// cleanup FX from dead/invalid units
CleanInvalidUnitFX()
--// we can't remove items from a table we are iterating atm, so just buffer them and remove them later
local RemoveParticles_old = RemoveParticles
RemoveParticles = BufferRemoveParticles
--// update FXs
framesToUpdate = thisGameFrame - lastGameFrame
for _,partFx in pairs(particles) do
if (n>=partFx.dieGameFrame) then
--// lifetime ended
if (partFx.repeatEffect) then
if (type(partFx.repeatEffect)=="number") then
partFx.repeatEffect = partFx.repeatEffect - 1
if (partFx.repeatEffect==1) then partFx.repeatEffect = nil end
end
if (partFx.ReInitialize) then
partFx:ReInitialize()
else
partFx.dieGameFrame = partFx.dieGameFrame + partFx.life
end
else
RemoveParticles(partFx.id)
end
else
--// update particles
if (partFx.Update) then
partFx:Update(framesToUpdate)
end
end
end
--// now we can remove them
RemoveParticles = RemoveParticles_old
if (#fxRemoveList>0) then
for i=1,#fxRemoveList do
RemoveParticles(fxRemoveList[i])
end
fxRemoveList = {}
end
end
local function Update(_,dt)
--// update frameoffset
frameOffset = spGetFrameTimeOffset()
--// Game Frame Update
local x = spGetGameFrame()
if ((x-lastGameFrame)>=1) then
GameFrame(nil,x)
lastGameFrame = x
end
--// check which fxs are visible
anyFXVisible = false
anyDistortionsVisible = false
if (next(particles)) then
CreateVisibleFxList()
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function CheckParticleClassReq(pi)
return
(canShader or (not pi.shader))and
(canFBO or (not pi.fbo))and
(canRTT or (not pi.rtt))and
(canCTT or (not pi.ctt))and
(canDistortions or (not pi.distortion))and
((not isIntel) or (pi.intel~=0))and
((not isMS) or (pi.ms~=0))
end
local function Initialize()
LupsConfig = LoadConfig("./lups.cfg")
--// set verbose level
local showWarnings = LupsConfig.showwarnings
if showWarnings then
local t = type(showWarnings)
if (t=="number") then
printErrorsAbove = showWarnings
elseif (t=="boolean") then
printErrorsAbove = PRIO_LESS
end
end
--// is distortion is supported?
DistortionClass = fxClasses["postdistortion"]
if DistortionClass then
fxClasses["postdistortion"]=nil --// remove it from default classes
local di = DistortionClass.pi
if (di) and CheckParticleClassReq(di) then
local fine = true
if (DistortionClass.Initialize) then fine = DistortionClass.Initialize() end
if (fine~=nil)and(fine==false) then
print(PRIO_LESS,'LUPS: disabled Distortions');
DistortionClass=nil
end
else
print(PRIO_LESS,'LUPS: disabled Distortions');
DistortionClass=nil
end
end
canDistortions = (DistortionClass~=nil)
--// get list of user disabled fx classes
local disableFX = {}
for i,v in pairs(LupsConfig.disablefx or {}) do
disableFX[i:lower()]=v;
end
local linkBackupFXClasses = {}
--// initialize particle classes
for fxName,fxClass in pairs(fxClasses) do
local fi = fxClass.pi --// .fi = fxClass.GetInfo()
if (not disableFX[fxName]) and (fi) and CheckParticleClassReq(fi) then
local fine = true
if (fxClass.Initialize) then fine = fxClass.Initialize() end
if (fine~=nil)and(fine==false) then
print(PRIO_LESS,'LUPS: "' .. fi.name .. '" FXClass removed (class requested it during initialization)');
fxClasses[fxName]=nil
if (fi.backup and fi.backup~="") then
linkBackupFXClasses[fxName] = fi.backup:lower()
end
if (fxClass.Finalize) then fxClass.Finalize() end
end
else --// unload particle class (not supported by this computer)
print(PRIO_LESS,'LUPS: "' .. fi.name .. '" FXClass removed (hardware doesn\'t support it)');
fxClasses[fxName]=nil
if (fi.backup and fi.backup~="") then
linkBackupFXClasses[fxName] = fi.backup:lower()
end
end
end
--// link backup FXClasses
for className,backupName in pairs(linkBackupFXClasses) do
fxClasses[className]=fxClasses[backupName]
end
--// link Distortion Class
fxClasses["postdistortion"]=DistortionClass
--// update screen geometric
--ViewResize(_,handler:GetViewSizes())
--// make global
GG.Lups = {}
GG.Lups.GetStats = GetStats
GG.Lups.GetErrorLog = GetErrorLog
GG.Lups.AddParticles = AddParticles
GG.Lups.GetParticles = GetParticles
GG.Lups.RemoveParticles = RemoveParticles
GG.Lups.AddParticlesArray = AddParticlesArray
GG.Lups.HasParticleClass = HasParticleClass
for fncname,fnc in pairs(GG.Lups) do
handler:RegisterGlobal('Lups_'..fncname,fnc)
end
GG.Lups.Config = LupsConfig
nilDispList = gl.CreateList(function() end)
end
local function Shutdown()
for fncname,fnc in pairs(GG.Lups) do
handler:DeregisterGlobal('Lups_'..fncname)
end
GG.Lups = nil
for _,fxClass in pairs(fxClasses) do
if (fxClass.Finalize) then
fxClass.Finalize()
end
end
gl.DeleteList(nilDispList)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local this = widget or gadget
this.GetInfo = GetInfo
this.Initialize = Initialize
this.Shutdown = Shutdown
this.DrawWorldPreUnit = DrawParticlesOpaque
this.DrawWorld = DrawParticles
this.DrawWorldReflection = DrawParticlesWater
this.DrawWorldRefraction = DrawParticlesWater
this.ViewResize = ViewResize
this.Update = Update
if gadget then
this.DrawUnit = DrawUnit
--this.GameFrame = GameFrame; // doesn't work for unsynced parts >yet<
end
| gpl-2.0 |
thedraked/darkstar | scripts/zones/Selbina/npcs/Falgima.lua | 17 | 1240 | -----------------------------------
-- Area: Selbina
-- NPC: Falgima
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,FALGIMA_SHOP_DIALOG);
stock = {0x1288,5351, -- Scroll of Invisible
0x1289,2325, -- Scroll of Sneak
0x128A,1204, -- Scroll of Deodorize
0x13F0,30360} -- Scroll of Flurry
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
thedraked/darkstar | scripts/zones/Garlaige_Citadel_[S]/npcs/Randecque.lua | 29 | 1746 | -----------------------------------
-- Area: Garlaige Citadel [S]
-- NPC: Randecque
-- @pos 61 -6 137 164
-- Notes: Gives Red Letter required to start "Steamed Rams"
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Garlaige_Citadel_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCampaignAllegiance() > 0) then
if (player:getCampaignAllegiance() == 2) then
player:startEvent(3);
else
-- message for other nations missing
player:startEvent(3);
end
elseif (player:hasKeyItem(RED_RECOMMENDATION_LETTER) == true) then
player:startEvent(2);
elseif (player:hasKeyItem(RED_RECOMMENDATION_LETTER) == false) then
player:startEvent(1);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1 and option == 0) then
player:addKeyItem(RED_RECOMMENDATION_LETTER);
player:messageSpecial(KEYITEM_OBTAINED, RED_RECOMMENDATION_LETTER);
end
end; | gpl-3.0 |
SnabbCo/snabbswitch | src/apps/lwaftr/lwutil.lua | 4 | 5728 | module(..., package.seeall)
local constants = require("apps.lwaftr.constants")
local S = require("syscall")
local bit = require("bit")
local ffi = require("ffi")
local lib = require("core.lib")
local cltable = require("lib.cltable")
local binary = require("lib.yang.binary")
local band = bit.band
local cast = ffi.cast
local uint16_ptr_t = ffi.typeof("uint16_t*")
local uint32_ptr_t = ffi.typeof("uint32_t*")
local constants_ipv6_frag = constants.ipv6_frag
local ehs = constants.ethernet_header_size
local o_ipv4_flags = constants.o_ipv4_flags
local ntohs = lib.ntohs
-- Return device PCI address, queue ID, and queue configuration.
function parse_instance(conf)
if conf.worker_config then
local device = conf.worker_config.device
local id = conf.worker_config.queue_id
local queue = conf.softwire_config.instance[device].queue[id]
return device, id, queue
else
local device, id
for dev in pairs(conf.softwire_config.instance) do
assert(not device, "Config contains more than one device")
device = dev
end
for queue in pairs(conf.softwire_config.instance[device].queue) do
assert(not id, "Config contains more than one queue")
id = queue
end
return device, id, conf.softwire_config.instance[device].queue[id]
end
end
function is_on_a_stick(conf, device)
local instance = conf.softwire_config.instance[device]
if not instance.external_device then return true end
return device == instance.external_device
end
function is_lowest_queue(conf)
local device, id = parse_instance(conf)
for n in pairs(conf.softwire_config.instance[device].queue) do
if id > n then return false end
end
return true
end
function num_queues(conf)
local n = 0
local device, id = parse_instance(conf)
for _ in pairs(conf.softwire_config.instance[device].queue) do
n = n + 1
end
return n
end
function select_instance(conf)
local copier = binary.config_copier_for_schema_by_name('snabb-softwire-v3')
local device, id = parse_instance(conf)
local copy = copier(conf)()
local instance = copy.softwire_config.instance
for other_device, queues in pairs(conf.softwire_config.instance) do
if other_device ~= device then
instance[other_device] = nil
else
for other_id, _ in pairs(queues.queue) do
if other_id ~= id then
instance[device].queue[other_id] = nil
end
end
end
end
return copy
end
function merge_instance (conf)
local function table_merge(t1, t2)
local ret = {}
for k,v in pairs(t1) do ret[k] = v end
for k,v in pairs(t2) do ret[k] = v end
return ret
end
local copier = binary.config_copier_for_schema_by_name('snabb-softwire-v3')
local copy = copier(conf)()
local _, _, queue = parse_instance(conf)
copy.softwire_config.external_interface = table_merge(
conf.softwire_config.external_interface, queue.external_interface)
copy.softwire_config.internal_interface = table_merge(
conf.softwire_config.internal_interface, queue.internal_interface)
return copy
end
function get_ihl_from_offset(pkt, offset)
local ver_and_ihl = pkt.data[offset]
return band(ver_and_ihl, 0xf) * 4
end
-- The rd16/wr16/rd32/wr32 functions are provided for convenience.
-- They do NO conversion of byte order; that is the caller's responsibility.
function rd16(offset)
return cast(uint16_ptr_t, offset)[0]
end
function wr16(offset, val)
cast(uint16_ptr_t, offset)[0] = val
end
function rd32(offset)
return cast(uint32_ptr_t, offset)[0]
end
function wr32(offset, val)
cast(uint32_ptr_t, offset)[0] = val
end
function keys(t)
local result = {}
for k,_ in pairs(t) do
table.insert(result, k)
end
return result
end
local uint64_ptr_t = ffi.typeof('uint64_t*')
function ipv6_equals(a, b)
local x, y = ffi.cast(uint64_ptr_t, a), ffi.cast(uint64_ptr_t, b)
return x[0] == y[0] and x[1] == y[1]
end
-- Local bindings for constants that are used in the hot path of the
-- data plane. Not having them here is a 1-2% performance penalty.
local o_ethernet_ethertype = constants.o_ethernet_ethertype
local n_ethertype_ipv4 = constants.n_ethertype_ipv4
local n_ethertype_ipv6 = constants.n_ethertype_ipv6
function is_ipv6(pkt)
return rd16(pkt.data + o_ethernet_ethertype) == n_ethertype_ipv6
end
function is_ipv4(pkt)
return rd16(pkt.data + o_ethernet_ethertype) == n_ethertype_ipv4
end
function is_ipv6_fragment(pkt)
if not is_ipv6(pkt) then return false end
return pkt.data[ehs + constants.o_ipv6_next_header] == constants_ipv6_frag
end
function is_ipv4_fragment(pkt)
if not is_ipv4(pkt) then return false end
-- Either the packet has the "more fragments" flag set,
-- or the fragment offset is non-zero, or both.
local flag_more_fragments_mask = 0x2000
local non_zero_offset = 0x1FFF
local flags_and_frag_offset = ntohs(rd16(pkt.data + ehs + o_ipv4_flags))
return band(flags_and_frag_offset, flag_more_fragments_mask) ~= 0 or
band(flags_and_frag_offset, non_zero_offset) ~= 0
end
function write_to_file(filename, content)
local fd, err = io.open(filename, "wt+")
if not fd then error(err) end
fd:write(content)
fd:close()
end
function fatal (msg)
print(msg)
main.exit(1)
end
function file_exists(path)
local stat = S.stat(path)
return stat and stat.isreg
end
function dir_exists(path)
local stat = S.stat(path)
return stat and stat.isdir
end
function nic_exists(pci_addr)
local devices="/sys/bus/pci/devices"
return dir_exists(("%s/%s"):format(devices, pci_addr)) or
dir_exists(("%s/0000:%s"):format(devices, pci_addr))
end
| apache-2.0 |
telergybot/1984joorge | plugins/all.lua | 264 | 4202 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'chat stats! \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
if not data[tostring(target)] then
return 'Group is not added.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group \n \n"
local settings = show_group_settings(target)
text = text.."Group settings \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\n"..modlist
local link = get_link(target)
text = text.."\n\n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] and msg.to.id ~= our_id then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
return
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end | gpl-2.0 |
nicholas-leonard/dp | examples/languagemodel.lua | 5 | 7124 | require 'dp'
--[[command line arguments]]--
cmd = torch.CmdLine()
cmd:text()
cmd:text('Train a Language Model on BillionWords dataset using a Neural Network and SoftmaxTree')
cmd:text('The network contains 3 or more layers. An input dictionary, one ore many dense hidden layer, and a fully connected output layer')
cmd:text('Example:')
cmd:text('$> th languagemodel.lua --small --batchSize 512 ')
cmd:text('$> th languagemodel.lua --tiny --batchSize 512 ')
cmd:text('$> th languagemodel.lua --tiny --batchSize 512 --accUpdate --validEpochSize 10000 --trainEpochSize 100000 --softmaxtree')
cmd:text('Options:')
cmd:option('--learningRate', 0.1, 'learning rate at t=0')
cmd:option('--schedule', '{[250]=0.01, [350]=0.001}', 'learning rate schedule')
cmd:option('--momentum', 0, 'momentum')
cmd:option('--maxOutNorm', 2, 'max norm each layers output neuron weights')
cmd:option('--batchSize', 256, 'number of examples per batch')
cmd:option('--cuda', false, 'use CUDA')
cmd:option('--useDevice', 1, 'sets the device (GPU) to use')
cmd:option('--maxEpoch', 400, 'maximum number of epochs to run')
cmd:option('--maxTries', 30, 'maximum number of epochs to try to find a better local minima for early-stopping')
cmd:option('--accUpdate', false, 'accumulate updates inplace using accUpdateGradParameters')
cmd:option('--contextSize', 5, 'number of words preceding the next word used to predict the target word')
cmd:option('--inputEmbeddingSize', 100, 'number of neurons per word embedding')
cmd:option('--hiddenSize', '{200}', 'number of hidden units used for hidden layer')
cmd:option('--outputEmbeddingSize', 100, 'number of hidden units at softmaxtree')
cmd:option('--softmaxtree', false, 'use SoftmaxTree instead of the inefficient (full) softmax')
cmd:option('--softmaxforest', false, 'use SoftmaxForest instead of SoftmaxTree (uses more memory)')
cmd:option('--forestGaterSize', '{}', 'size of hidden layers used for forest gater (trees are experts)')
cmd:option('--batchNorm', false, 'use batch normalization. dropout is mostly redundant with this')
cmd:option('--dropout', false, 'use dropout on hidden units')
cmd:option('--small', false, 'use a small (1/30th) subset of the training set')
cmd:option('--tiny', false, 'use a tiny (1/100th) subset of the training set')
cmd:option('--trainEpochSize', 1000000, 'number of train examples seen between each epoch')
cmd:option('--validEpochSize', 100000, 'number of valid examples used for early stopping and cross-validation')
cmd:option('--trainOnly', false, 'forget the validation and test sets, focus on the training set')
cmd:option('--progress', false, 'print progress bar')
cmd:option('--silent', false, 'dont print anything to stdout')
cmd:text()
opt = cmd:parse(arg or {})
opt.hiddenSize = dp.returnString(opt.hiddenSize)
opt.forestGaterSize = dp.returnString(opt.forestGaterSize)
opt.schedule = dp.returnString(opt.schedule)
if not opt.silent then
table.print(opt)
end
--[[data]]--
local train_file = 'train_data.th7'
if opt.small then
train_file = 'train_small.th7'
elseif opt.tiny then
train_file = 'train_tiny.th7'
end
local ds = dp.BillionWords{
context_size = opt.contextSize, train_file = train_file
}
--[[Model]]--
-- neural network language model
nnlm = nn.Sequential()
-- input layer
-- lookuptable that contains the word embeddings that will be learned
nnlm:extend(
nn.Dictionary(ds:vocabularySize(), opt.inputEmbeddingSize, opt.accUpdate),
nn.Collapse(2)
)
dp.vprint(not opt.silent, "Input to first hidden layer has "..
opt.contextSize*opt.inputEmbeddingSize.." neurons.")
-- hidden layer(s)
inputSize = opt.contextSize*opt.inputEmbeddingSize
opt.hiddenSize[#opt.hiddenSize + 1] = opt.outputEmbeddingSize
for i,hiddenSize in ipairs(opt.hiddenSize) do
if opt.dropout then
nnlm:add(nn.Dropout())
end
nnlm:add(nn.Linear(inputSize, hiddenSize))
if opt.batchNorm then
nnlm:add(nn.BatchNormalization(hiddenSize))
end
nnlm:add(nn.Tanh())
inputSize = hiddenSize
end
-- output layer
if opt.dropout then
nnlm:add(nn.Dropout())
end
if opt.softmaxforest or opt.softmaxtree then
-- input to nnlm is {inputs, targets} for nn.SoftMaxTree
local para = nn.ParallelTable()
para:add(nnlm):add(opt.cuda and nn.Convert() or nn.Identity())
nnlm = nn.Sequential()
nnlm:add(para)
if opt.softmaxforest then -- requires a lot more memory
local trees = {ds:hierarchy('word_tree1.th7'), ds:hierarchy('word_tree2.th7'), ds:hierarchy('word_tree3.th7')}
local rootIds = {880542,880542,880542}
nnlm:add(nn.SoftMaxForest(inputSize, trees, rootIds, opt.forestGaterSize, nn.Tanh(), opt.accUpdate))
opt.softmaxtree = true
elseif opt.softmaxtree then
local tree, root = ds:frequencyTree()
nnlm:add(nn.SoftMaxTree(inputSize, tree, root, opt.accUpdate))
end
else
print("Warning: you are using full LogSoftMax for last layer, which "..
"is really slow (800,000 x outputEmbeddingSize multiply adds "..
"per example. Try --softmaxtree instead.")
nnlm:add(nn.Linear(inputSize, ds:vocabularySize()))
nnlm:add(nn.LogSoftMax())
end
--[[Propagators]]--
train = dp.Optimizer{
loss = opt.softmaxtree and nn.TreeNLLCriterion() or nn.ModuleCriterion(nn.ClassNLLCriterion(), nil, nn.Convert()),
callback = function(model, report)
opt.learningRate = opt.schedule[report.epoch] or opt.learningRate
if opt.accUpdate then
model:accUpdateGradParameters(model.dpnn_input, model.output, opt.learningRate)
else
model:updateGradParameters(opt.momentum) -- affects gradParams
model:updateParameters(opt.learningRate) -- affects params
end
model:maxParamNorm(opt.maxOutNorm) -- affects params
model:zeroGradParameters() -- affects gradParams
end,
feedback = dp.Perplexity(),
sampler = dp.RandomSampler{
epoch_size = opt.trainEpochSize, batch_size = opt.batchSize
},
acc_update = opt.accUpdate,
progress = opt.progress
}
if not opt.trainOnly then
valid = dp.Evaluator{
feedback = dp.Perplexity(),
sampler = dp.Sampler{
epoch_size = opt.validEpochSize, batch_size = opt.batchSize
},
progress = opt.progress
}
tester = dp.Evaluator{
feedback = dp.Perplexity(),
sampler = dp.Sampler{batch_size = opt.batchSize}
}
end
--[[Experiment]]--
xp = dp.Experiment{
model = nnlm,
optimizer = train,
validator = valid,
tester = tester,
observer = {
dp.FileLogger(),
dp.EarlyStopper{
max_epochs = opt.maxTries,
error_report={opt.trainOnly and 'optimizer' or 'validator','feedback','perplexity','ppl'}
}
},
random_seed = os.time(),
max_epoch = opt.maxEpoch
}
if opt.softmaxtree then
-- makes it forward {input, target} instead of just input
xp:includeTarget()
end
--[[GPU or CPU]]--
if opt.cuda then
require 'cutorch'
require 'cunn'
if opt.softmaxtree then
require 'cunnx'
end
cutorch.setDevice(opt.useDevice)
xp:cuda()
end
xp:verbose(not opt.silent)
if not opt.silent then
print"Model :"
print(nnlm)
end
xp:run(ds)
| bsd-3-clause |
NPLPackages/main | script/ide/SaveFileDialog.lua | 1 | 1191 | --[[
Title: Save File Dialog
Author(s): LiXizhi
Date: 2009/1/30
Desc: it inherits from OpenFileDialog, except that it does not check for file existence.
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/ide/SaveFileDialog.lua");
local ctl = CommonCtrl.SaveFileDialog:new{
name = "SaveFileDialog1",
alignment = "_ct",
left=-256, top=-150,
width = 512,
height = 380,
parent = nil,
-- initial file name to be displayed, usually ""
FileName = "",
fileextensions = {"all files(*.*)", "images(*.jpg; *.png; *.dds)", "animations(*.swf; *.wmv; *.avi)", "web pages(*.htm; *.html)", },
folderlinks = {
{path = "model/", text = "model"},
{path = "Texture/", text = "Texture"},
{path = "character/", text = "character"},
{path = "script/", text = "script"},
},
onopen = function(ctrlName, filename)
end
};
ctl:Show(true);
-------------------------------------------------------
]]
NPL.load("(gl)script/ide/OpenFileDialog.lua");
local L = CommonCtrl.Locale("IDE");
local SaveFileDialog = commonlib.inherit(CommonCtrl.OpenFileDialog, {
CheckFileExists=false,
OpenButtonName = L"save",
})
CommonCtrl.SaveFileDialog = SaveFileDialog; | gpl-2.0 |
thedraked/darkstar | scripts/zones/Castle_Oztroja/npcs/Treasure_Coffer.lua | 13 | 4293 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: Treasure Coffer
-- @zone 151
-- @pos
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/globals/quests");
require("scripts/zones/Castle_Oztroja/TextIDs");
local TreasureType = "Coffer";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1044,1); -- Treasure Key
-- trade:hasItemQty(1115,1); -- Skeleton Key
-- trade:hasItemQty(1023,1); -- Living Key
-- trade:hasItemQty(1022,1); -- Thief's Tools
local questItemNeeded = 0;
-- Player traded a key.
if ((trade:hasItemQty(1044,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
local zone = player:getZoneID();
-- IMPORTANT ITEM: AF Keyitems, AF Items, & Map -----------
local mJob = player:getMainJob();
local listAF = getAFbyZone(zone);
for nb = 1,#listAF,3 do
if (player:getQuestStatus(JEUNO,listAF[nb + 1]) ~= QUEST_AVAILABLE and mJob == listAF[nb] and player:hasItem(listAF[nb + 2]) == false) then
questItemNeeded = 2;
break
end
end
--------------------------------------
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if (pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if (success ~= -2) then
player:tradeComplete();
if (math.random() <= success) then -- 0 or 1
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if (questItemNeeded == 2) then
for nb = 1,#listAF,3 do
if (mJob == listAF[nb]) then
player:addItem(listAF[nb + 2]);
player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]);
break
end
end
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = cofferLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if (loot[1]=="gil") then
player:addGil(loot[2]*GIL_RATE);
player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID());
else
player:messageSpecial(CHEST_MIMIC);
spawnMimic(zone,npc,player);
UpdateTreasureSpawnPoint(npc:getID(), true);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1044);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
thedraked/darkstar | scripts/zones/Upper_Jeuno/npcs/Sibila-Mobla.lua | 17 | 1382 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Sibila-Mobla
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Upper_Jeuno/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatJeuno = player:getVar("WildcatJeuno");
if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,5) == false) then
player:startEvent(10083);
else
player:startEvent(0x0062);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 10083) then
player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",5,true);
end
end;
| gpl-3.0 |
josh-perry/VNEngine | kikito-middleclass-extras/Invoker.lua | 1 | 1554 | -----------------------------------------------------------------------------------
-- Invoker.lua
-- Enrique García ( enrique.garcia.cota [AT] gmail [DOT] com ) - 4 Mar 2010
-- Helper function that simplifies method invocation via method names or functions
-----------------------------------------------------------------------------------
--[[ Usage:
require 'middleclass' -- or similar
require 'middleclass-extras.init' -- or 'middleclass-extras'
MyClass = class('MyClass')
MyClass:includes(Invoker)
function MyClass:foo(x,y) print('foo executed with params', x, y) end
local obj = MyClass:new()
obj:invoke('foo', 1,2) -- foo executed with params 1 2
obj:invoke( function(self, x, y)
print('nameless function executed with params', x, y)
, 3, 4) -- nameless function executed with params 3, 4
Notes:
* The function first parameter must allways be self
* You can use Invoker independently: Invoker.invoke(obj, 'method')
]]
assert(Object~=nil and class~=nil, 'MiddleClass not detected. Please require it before using Beholder')
Invoker = {
invoke = function(self, methodOrName, ...)
local tm = type(methodOrName)
assert(tm == 'string' or tm == 'function', 'methodOrName should be either a function or string. It was a '..tm.. ': ' .. tostring(methodOrName))
local method = methodOrName
if tm =='string' then
method = self[methodOrName]
assert(type(method)=='function', 'Could not find ' .. methodOrName .. ' in ' .. tostring(self))
end
return method(self, ...)
end
}
| mit |
jefferai/vlcfix | share/lua/playlist/cue.lua | 11 | 3972 | --[[
Parse CUE files
$Id$
Copyright (C) 2009 Laurent Aimar
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
if( not string.match( string.upper( vlc.path ), ".CUE$" ) ) then
return false
end
header = vlc.peek( 2048 )
return string.match( header, "FILE.*WAVE%s*[\r\n]+" ) or
string.match( header, "FILE.*AIFF%s*[\r\n]+" ) or
string.match( header, "FILE.*MP3%s*[\r\n]+" )
end
-- Helpers
function is_utf8( src )
return vlc.strings.from_charset( "UTF-8", src ) == src
end
function cue_string( src )
if not is_utf8( src ) then
-- Convert to UTF-8 since it's probably Latin1
src = vlc.strings.from_charset( "ISO_8859-1", src )
end
local sub = string.match( src, "^\"(.*)\".*$" );
if( sub ) then
return sub
end
return string.match( src, "^(%S+).*$" )
end
function cue_path( src )
if( string.match( src, "^/" ) or
string.match( src, "^\\" ) or
string.match( src, "^[%l%u]:\\" ) ) then
return vlc.strings.make_uri(src)
end
local slash = string.find( string.reverse( vlc.path ), '/' )
local prefix = vlc.access .. "://" .. string.sub( vlc.path, 1, -slash )
-- FIXME: postfix may not be encoded correctly (esp. slashes)
local postfix = vlc.strings.encode_uri_component(src)
return prefix .. postfix
end
function cue_track( global, track )
if( track.index01 == nil ) then
return nil
end
t = {}
t.path = cue_path( track.file or global.file )
t.title = track.title
t.album = global.title
t.artist = track.performer or global.performer
t.genre = track.genre or global.genre
t.date = track.date or global.date
t.description = global.comment
t.tracknum = track.num
t.options = { ":start-time=" .. math.floor(track.index01) }
return t
end
function cue_append( tracks, global, track )
local t = cue_track( global, track )
if( t ~= nil ) then
if( #tracks > 0 ) then
local prev = tracks[#tracks]
table.insert( prev.options, ":stop-time=" .. math.floor(track.index01) )
end
table.insert( tracks, t )
end
end
-- Parse function.
function parse()
p = {}
global_data = nil
data = {}
file = nil
while true
do
line = vlc.readline()
if not line then break end
cmd, arg = string.match( line, "^%s*(%S+)%s*(.*)$" )
if( cmd == "REM" and arg ) then
subcmd, value = string.match( arg, "^(%S+)%s*(.*)$" )
if( subcmd == "GENRE" and value ) then
data.genre = cue_string( value )
elseif( subcmd == "DATE" and value ) then
data.date = cue_string( value )
elseif( subcmd == "COMMENT" and value ) then
data.comment = cue_string( value )
end
elseif( cmd == "PERFORMER" and arg ) then
data.performer = cue_string( arg )
elseif( cmd == "TITLE" and arg ) then
data.title = cue_string( arg )
elseif( cmd == "FILE" ) then
file = cue_string( arg )
elseif( cmd == "TRACK" ) then
if( not global_data ) then
global_data = data
else
cue_append( p, global_data, data )
end
data = { file = file, num = string.match( arg, "^(%d+)" ) }
elseif( cmd == "INDEX" ) then
local idx, m, s, f = string.match( arg, "(%d+)%s+(%d+):(%d+):(%d+)" )
if( idx == "01" and m ~= nil and s ~= nil and f ~= nil ) then
data.index01 = m * 60 + s + f / 75
end
end
end
cue_append( p, global_data, data )
return p
end
| gpl-2.0 |
Xkeeper0/emu-lua | playstation-pscx/silent hill/x_functions.lua | 1 | 6308 |
x_func_version = 7;
--[[
Minor version history:
v5 -----------
- Added Bisqwit's 'clone table' function.
v6 -----------
- added pairs by keys
- added hitbox functions
v7 -----------
- added memory.readword, memory.readwordsigned, etc
]]
-- Draws a line from x1,y1 to x2,y2 using color
function line(x1,y1,x2,y2,color)
if (x1 >= 0 and x1 <= 9999 and x2 >= 0 and x2 <= 9999 and y1 >= 0 and y1 <= 9999 and y2 >= 0 and y2 <= 9999) then
local success = pcall(function() gui.drawline(x1,y1,x2,y2,color) end);
if not success then
text(60, 224, "ERROR: ".. x1 ..",".. y1 .." ".. x2 ..",".. y2);
end;
end;
end;
-- Puts text on-screen (duh)
function text(x,y,str)
if str == nil then
str = "nil";
end;
if (x >= 0 and x <= 9999 and y >= 0 and y <= 240) then
gui.text(x,y,str);
end;
end;
-- Sets the pixel at x, y to color
function pixel(x,y,color)
if (x >= 0 and x <= 9999 and y >= 0 and y <= 240) then
gui.drawpixel(x,y,color);
end;
end;
-- Draws a rectangle from x1,y1 to x2, y2
function box(x1,y1,x2,y2,color)
if (x1 >= 0 and x1 <= 9999 and x2 >= 0 and x2 <= 9999 and y1 >= 0 and y1 <= 9999 and y2 >= 0 and y2 <= 9999) then
--[[ local success = pcall(function() gui.drawbox(x1,y1,x2,y2,color); end);
if not success then
text(60, 150, string.format("%3d %3d %3d %3d", x1, y1, x2, y2));
FCEU.pause();
end;
]] gui.drawbox(x1,y1,x2,y2,color);
end;
end;
-- Draws a filled box from x1, y1 to x2, y2 (warning: can be slow if drawing large boxes)
function filledbox(x1,y1,x2,y2,color)
for i = 0, math.abs(y1 - y2) do
line(x1,y1 + i,x2,y1 + i,color);
end;
end;
-- Draws a life-bar.
-- x, y: position of top-right
-- sx, sy: width and height of ACTUAL BAR (0 is the smallest height (1px))
-- a1, a2: Amounts (a1/a2*100 = % of bar filled)
-- oncolor, offcolor: "bar", "background"
-- noborder: set to "true" if you just want a black outline without the white
function lifebar(x, y, sx, sy, a1, a2, oncolor, offcolor, outerborder, innerborder)
-- this function will have the effect of drawing an HP bar
-- keep in mind xs and ys are 2px larger to account for borders
x1 = x;
x2 = x + sx + 4;
y1 = y;
y2 = y + sy + 4;
w = math.floor(a1 / math.max(1, a1, a2) * sx);
if not a2 then w = 0 end;
outer = outerborder;
inner = innerborder;
if (outer == true or outer == false) and (inner == nil) then
-- legacy
outer = nil;
inner = "#000000";
elseif outer == nil and inner == nil then
outer = "#000000";
inner = "#ffffff";
elseif inner == nil then
inner = "#ffffff";
end;
if (inner) then
box(x1 + 1, y1 + 1, x2 - 1, y2 - 1, inner);
end;
if (outer) then
box(x1 , y1 , x2 , y2 , outer);
end;
if (w < sx) then
filledbox(x1 + w + 2, y1 + 2, x2 - 2, y2 - 2, offcolor);
end;
if (w > 0) then
filledbox(x1 + 2, y1 + 2, x1 + 2 + w, y2 - 2, oncolor);
end;
end;
function graph(x, y, sx, sy, minx, miny, maxx, maxy, xval, yval, color, border, filled)
if (filled ~= nil) then
filledbox(x + 1, y + 1, x+sx, y+sy, "#000000");
end;
if (border ~= nil) then
box(x, y, x+sx+1, y+sy+1, color);
end;
xp = (xval - minx) / (maxx - minx) * sx;
yp = (yval - miny) / (maxy - miny) * sy;
line(x + 1 , yp + y + 1, x + sx + 1, yp + y + 1, color);
line(xp + x + 1, y + 1 , xp + x + 1, y + sy + 1, color);
return true;
end;
-- Bisqwit's clone table feature.
table.clone = function(table)
local res = {}
for k,v in pairs(table)do
res[k]=v
end
return res
end
spairs = function (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
-- ****************************************************************************
-- * hitbox( coords1, coords2, con, coff )
-- * Checks if any point of coords1 is within coords2.
-- * con/coff determine what colors of box to draw.
-- ****************************************************************************
function hitbox(b1x1, b1y1, b1x2, b1y2, b2x1, b2y1, b2x2, b2y2, con, coff)
if not b1x1 then
text(0, 8, "ERROR!!!!");
return;
end;
local noboxes = false;
if con == nil and coff == nil then
noboxes = true;
else
if coff == nil then
coff = "#00ff00"
end;
if con == nil then
con = "#dd0000";
end;
if coff == nil then
coff = "#00ff00"
end;
end;
boxes = {{
x = {b1x1, b1x2},
y = {b1y1, b1y2},
}, {
x = {b2x1, b2x2},
y = {b2y1, b2y2},
}};
hit = false;
for xc = 1, 2 do
for yc = 1, 2 do
if (boxes[1]['x'][xc] >= boxes[2]['x'][1]) and
(boxes[1]['y'][yc] >= boxes[2]['y'][1]) and
(boxes[1]['x'][xc] <= boxes[2]['x'][2]) and
(boxes[1]['y'][yc] <= boxes[2]['y'][2]) then
hit = true;
-- TODO: make this break out of the for loop? might not be worth it
end;
end;
end;
if hit == true then
if not noboxes then box(b2x1, b2y1, b2x2, b2y2, con); end;
return true;
else
if not noboxes then box(b2x1, b2y1, b2x2, b2y2, coff); end;
return false;
end;
return true;
end;
if not memory.readword then
memory.readword = function(address)
return memory.readbyte(address + 1) * 0x100 + memory.readbyte(address);
end;
memory.readwordsigned = function(address)
t = memory.readbyte(address + 1) * 0x100 + memory.readbyte(address);
if t >= 32768 then
t = t - 65536;
end;
return t;
end;
end;
function x_requires(required)
-- Sanity check. If they require a newer version, let them know.
timer = 1;
if x_func_version < required then
while (true) do
timer = timer + 1;
for i = 0, 32 do
box( 6, 28 + i, 250, 92 - i, "#000000");
end;
text( 10, 32, string.format("This Lua script requires version %02d or greater.", required));
text( 43, 42, string.format("Your x_functions.lua is version %02d.", x_func_version));
text( 29, 58, "Please check for an updated version at");
text( 14, 69, "http://xkeeper.shacknet.nu:5/");
text(114, 78, "emu/nes/lua/x_functions.lua");
warningboxcolor = string.format("%02X", math.floor(math.abs(30 - math.fmod(timer, 60)) / 30 * 0xFF));
box(7, 29, 249, 91, "#ff" .. warningboxcolor .. warningboxcolor);
FCEU.frameadvance();
end;
end;
end; | mit |
NPLPackages/main | script/ide/MultiLineEditbox_old.lua | 1 | 13337 | --[[
Title: OBSOLETED use MultiLineEditbox: multiline editbox from a collection of single line editbox
Author(s): LiXizhi
Date: 2007/2/7
Note: if you use an auto strench alignment, auto strench is only enabled on creation. which means that if one change the window size after creation, it does not work out as expected.
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/ide/MultiLineEditbox.lua");
local ctl = CommonCtrl.MultiLineEditbox:new{
name = "MultiLineEditbox1",
alignment = "_lt",
left=0, top=0,
width = 256,
height = 90,
line_count = 3,
parent = nil,
};
ctl:Show(true);
-------------------------------------------------------
]]
-- common control library
NPL.load("(gl)script/ide/common_control.lua");
-- define a new control in the common control libary
-- default member attributes
local MultiLineEditbox = {
-- the top level control name
name = "MultiLineEditbox1",
-- normal window size
alignment = "_lt",
left = 0,
top = 0,
width = 512,
height = 290,
textwidth = nil,
WordWrap = true,
line_count = 3,
line_height = 26,
line_spacing = 2,
parent = nil,
-- appearance
main_bg = "Texture/EBook/text_bg.png",
editbox_bg = "Texture/EBook/line.png",
}
CommonCtrl.MultiLineEditbox = MultiLineEditbox;
-- constructor
function MultiLineEditbox:new (o)
o = o or {} -- create object if user does not provide one
setmetatable(o, self)
self.__index = self
return o
end
-- Destroy the UI control
function MultiLineEditbox:Destroy ()
ParaUI.Destroy(self.name);
end
--@param bShow: boolean to show or hide. if nil, it will toggle current setting.
function MultiLineEditbox:Show(bShow)
local _this,_parent;
if(self.name==nil)then
log("MultiLineEditbox instance name can not be nil\r\n");
return
end
_this=ParaUI.GetUIObject(self.name);
if(_this:IsValid() == false) then
if(bShow == false) then return end
bShow = true;
_this=ParaUI.CreateUIObject("container",self.name,self.alignment,self.left,self.top,self.width,self.height);
_this.background=self.main_bg;
-- note: uncomment the following line to enable auto scrolling. It does not work correctly at the moment.
--if( (self.line_height+self.line_spacing)*self.line_count > self.height ) then
--_this.scrollable = true;
--end
_parent = _this;
if(self.parent==nil) then
_this:AttachToRoot();
else
self.parent:AddChild(_this);
end
CommonCtrl.AddControl(self.name, self);
local _,_, absWidth, absHeight = _parent:GetAbsPosition();
if(not self.textwidth) then
self.textwidth = absWidth - self.line_spacing*2-12;
end
-- item count
local i;
for i=0, self.line_count-1 do
_this=ParaUI.CreateUIObject("imeeditbox",self.name.."EditBoxLine"..(i+1),"_mt",self.line_spacing,i*(self.line_height+self.line_spacing), self.line_spacing, self.line_height);
_this.onkeyup=string.format([[;CommonCtrl.MultiLineEditbox.OnText("%s", %d);]], self.name, i+1);
_this.background=self.editbox_bg;
_parent:AddChild(_this);
end
else
if(bShow == nil) then
bShow = (_this.visible == false);
end
_this.visible = bShow;
end
end
-- close the given control
function MultiLineEditbox.OnClose(sCtrlName)
local self = CommonCtrl.GetControl(sCtrlName);
if(self==nil)then
log("error getting MultiLineEditbox instance "..sCtrlName.."\r\n");
return;
end
ParaUI.Destroy(self.name);
end
-- called when the text changes
function MultiLineEditbox.OnText(sCtrlName, nLineIndex)
local self = CommonCtrl.GetControl(sCtrlName);
if(self==nil)then
log("error getting MultiLineEditbox instance "..sCtrlName.."\r\n");
return;
end
if(virtual_key == Event_Mapping.EM_KEY_DOWN) then
-- if the user pressed the enter key, change to the next line.
if(nLineIndex < self.line_count) then
local nextLine = ParaUI.GetUIObject(self.name.."EditBoxLine"..(nLineIndex+1));
local thisLine = ParaUI.GetUIObject(self.name.."EditBoxLine"..nLineIndex);
if(thisLine:IsValid() and nextLine:IsValid()) then
nextLine:Focus();
nextLine:SetCaretPosition(thisLine:GetCaretPosition());
end
ParaUI.GetUIObject(self.name.."EditBoxLine"..(nLineIndex+1)):Focus();
end
elseif(virtual_key == Event_Mapping.EM_KEY_RETURN or virtual_key == Event_Mapping.EM_KEY_NUMPADENTER ) then
-- insert return key
self:ProcessLine(nLineIndex, 2, true);
elseif(virtual_key == Event_Mapping.EM_KEY_UP) then
-- if the user pressed the up key, change to the previous line.
if(nLineIndex >=2 ) then
local lastLine = ParaUI.GetUIObject(self.name.."EditBoxLine"..(nLineIndex-1));
local thisLine = ParaUI.GetUIObject(self.name.."EditBoxLine"..nLineIndex);
if(thisLine:IsValid() and lastLine:IsValid()) then
lastLine:Focus();
lastLine:SetCaretPosition(thisLine:GetCaretPosition());
end
end
elseif(virtual_key == Event_Mapping.EM_KEY_BACKSPACE or virtual_key == Event_Mapping.EM_KEY_DELETE) then
local thisLine = ParaUI.GetUIObject(self.name.."EditBoxLine"..nLineIndex);
if(thisLine:IsValid()) then
local thisCharPos = thisLine:GetCaretPosition();
local thisLineCharCount = thisLine:GetTextSize();
if(thisLine.text == "") then
-- only delete the current line if it is already empty
self:ProcessLine(nLineIndex, 5);
if(virtual_key == Event_Mapping.EM_KEY_BACKSPACE) then
-- move to the previous line
if(nLineIndex >=2 ) then
local lastLine = ParaUI.GetUIObject(self.name.."EditBoxLine"..(nLineIndex-1));
if(lastLine:IsValid()) then
lastLine:Focus();
lastLine:SetCaretPosition(-1);
end
end
end
else
if(virtual_key == Event_Mapping.EM_KEY_BACKSPACE and thisCharPos ==0) then
-- backspace key when the caret is at beginning.
if(nLineIndex>=2) then
local lastLine = ParaUI.GetUIObject(self.name.."EditBoxLine"..(nLineIndex-1));
if(lastLine:IsValid()) then
local caretPos = lastLine:GetTextSize();
local oldtext = thisLine.text;
thisLine.text = "";
self:ProcessLine(nLineIndex-1, 4, oldtext);
lastLine:SetCaretPosition(caretPos);
lastLine:Focus();
end
end
elseif(virtual_key == Event_Mapping.EM_KEY_DELETE and thisCharPos ==thisLineCharCount) then
-- delete key when the caret is at ending.
if(nLineIndex < self.line_count) then
local nextLine = ParaUI.GetUIObject(self.name.."EditBoxLine"..(nLineIndex+1));
if(nextLine:IsValid()) then
local caretPos = thisLine:GetCaretPosition();
local oldtext = nextLine.text;
nextLine.text = "";
self:ProcessLine(nLineIndex, 4, oldtext);
thisLine:SetCaretPosition(caretPos);
end
end
end
end
end
else
-- if there is input, switch to the next line.
-- GetFirstVisibleCharIndex
self:ProcessLine(nLineIndex, 0, true);
end
end
-- update the given line; if necessary, it will also update subsequent lines recursively.
-- @param nLineIndex: line index
-- @param command:
-- 0: update the line. If param1 is nil, it will not change the focus, otherwise change the focus if necessary.
-- 1: prepend text(param1) to the given line
-- 4: append text(param1) to the given line
-- 2: insert return key at the current caret position.If param1 is nil, it will not change the focus, otherwise change the focus if necessary.
-- 3: insert a new line of text(param1) at the current line
-- 5: delete a given line
function MultiLineEditbox:ProcessLine(nLineIndex, command, param1)
local thisLine = ParaUI.GetUIObject(self.name.."EditBoxLine"..nLineIndex);
if(thisLine:IsValid()) then
if(command == 0)then
local oldtext = thisLine.text;
if(self.WordWrap) then
-- for word wrapping
local nCharsCount = thisLine:GetTextSize();
local nTrailPos = nCharsCount;
if(nTrailPos>0) then
-- find the last word position that can be displayed within self.textwidth
while true do
local x,y = thisLine:CPtoXY(nTrailPos, true, 0,0);
if(x<=self.textwidth or x==0) then
break;
end
local nTestTrailPos = thisLine:GetPriorWordPos(nTrailPos, 0);
--log(string.format("trailpos=%s, testPriorWordPos=%s, charcount = %s\r\n", nTrailPos, nTestTrailPos, nCharsCount))
x=0;
if(nTestTrailPos<nTrailPos) then
if(nTestTrailPos == 0) then
nTrailPos = nCharsCount;
break;
end
else
if(nTestTrailPos == 0) then
nTrailPos = nCharsCount;
end
break;
end
-- if the last word has trailing space characters, just regard each space as a word and try again.
local wordTextLastChar = ParaMisc.UniSubString(oldtext, nTrailPos, nTrailPos);
--log(string.format("wordTextLastChar = %s oldtext = <%s>\r\n", tostring(wordTextLastChar), oldtext))
if(wordTextLastChar == " ") then
nTrailPos = nTrailPos -1;
else
nTrailPos = nTestTrailPos;
end
end
end
-- if the line is full, break to the next line
if(nTrailPos<nCharsCount) then
-- only break, if it is not the last line
if(nLineIndex < self.line_count) then
local CharCount = ParaMisc.GetUnicodeCharNum(oldtext); -- need a unicode version for Chinese characters.
local oldCaretPosThisLine = thisLine:GetCaretPosition();
thisLine.text = ParaMisc.UniSubString(oldtext, 1, nTrailPos);
local leftovertext = ParaMisc.UniSubString(oldtext, nTrailPos+1,-1);
self:ProcessLine(nLineIndex+1, 1, leftovertext);
if(param1) then
local newSize = thisLine:GetTextSize();
if(oldCaretPosThisLine >= newSize) then
local nextline = ParaUI.GetUIObject(self.name.."EditBoxLine"..(nLineIndex+1));
if(nextline:IsValid()) then
nextline:Focus();
nextline:SetCaretPosition(oldCaretPosThisLine-nTrailPos);
end
else
thisLine:SetCaretPosition(oldCaretPosThisLine);
end
end
end
end
else
-- no word wrapping. Find the first \r or \n in the text and move the rest to the next line
local nFrom, nTo = string.find(oldtext, "[\r\n]+");
if(nFrom~=nil) then
if(nFrom>1) then
thisLine.text = string.sub(oldtext, 1, nFrom-1)
else
thisLine.text = "";
end
self:ProcessLine(nLineIndex+1, 1, string.sub(oldtext, nTo+1, -1));
end
end
elseif(command == 1)then
-- 1: prepend text(param1) to the given line
if(type(param1) == "string") then
thisLine.text = param1..thisLine.text;
--thisLine:SetCaretPosition(-1); -- this is tricky: set caret to the end of the string for firstCharIndex updating
self:ProcessLine(nLineIndex, 0);
end
elseif(command == 4)then
-- 1: append text(param1) to the given line
if(type(param1) == "string") then
thisLine.text = thisLine.text..param1;
self:ProcessLine(nLineIndex, 0);
end
elseif(command == 2)then
-- 2: insert return key at the current caret position.
-- only break, if it is not the last line
if(nLineIndex < self.line_count) then
if(param1) then
ParaUI.GetUIObject(self.name.."EditBoxLine"..(nLineIndex+1)):Focus();
end
local oldtext = thisLine.text;
local CharCount = ParaMisc.GetUnicodeCharNum(oldtext); -- need a unicode version for Chinese characters.
local CaretPos = thisLine:GetCaretPosition();
if(CaretPos < (CharCount))then
thisLine.text = ParaMisc.UniSubString(oldtext, 1, CaretPos);
local leftovertext = ParaMisc.UniSubString(oldtext, CaretPos+1,-1);
self:ProcessLine(nLineIndex+1, 3, leftovertext);
else
self:ProcessLine(nLineIndex+1, 3, "");
end
end
elseif(command == 3)then
-- 3: insert a new line of text(param1) at the current line
if(nLineIndex < self.line_count) then
if(type(param1) == "string") then
local oldtext = thisLine.text;
thisLine.text = param1;
self:ProcessLine(nLineIndex+1, 3, oldtext);
end
else
if(type(param1) == "string") then
thisLine.text = param1..thisLine.text;
end
end
elseif(command == 5)then
-- 5: delete a given line
local i;
for i = nLineIndex, self.line_count-1 do
ParaUI.GetUIObject(self.name.."EditBoxLine"..i).text = ParaUI.GetUIObject(self.name.."EditBoxLine"..(i+1)).text;
end
ParaUI.GetUIObject(self.name.."EditBoxLine"..self.line_count).text = ""
else
-- TODO:
end
end
end
-- set the text
function MultiLineEditbox:SetText(text)
local line_text;
local i = 1;
for line_text in string.gfind(text, "([^\r\n]+)") do
if(i<=self.line_count) then
ParaUI.GetUIObject(self.name.."EditBoxLine"..i).text = line_text;
i=i+1;
else
break
end
end
local k;
for k=i,self.line_count do
ParaUI.GetUIObject(self.name.."EditBoxLine"..k).text = "";
end
end
-- return the concartenated text
function MultiLineEditbox:GetText()
local text="";
local i;
for i = 1, self.line_count do
local line_text = ParaUI.GetUIObject(self.name.."EditBoxLine"..i).text;
if(line_text ~= nil and line_text ~= "") then
if(self.WordWrap) then
line_text = string.gsub(line_text, "([^\r\n]+)", "%1");
text = text..line_text;
else
text = text..line_text.."\r\n";
end
else
if(i<self.line_count) then
text = text.."\n"
end
end
end
--log(text.." gettext\r\n"..self.line_count.." numbers\r\n")
return text;
end
| gpl-2.0 |
MonkeyFirst/Urho3D | bin/Data/LuaScripts/27_Urho2DPhysics.lua | 24 | 7973 | -- Urho2D physics sample.
-- This sample demonstrates:
-- - Creating both static and moving 2D physics objects to a scene
-- - Displaying physics debug geometry
require "LuaScripts/Utilities/Sample"
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create the scene content
CreateScene()
-- Create the UI content
CreateInstructions()
-- Setup the viewport for displaying the scene
SetupViewport()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_FREE)
-- Hook up to the frame update events
SubscribeToEvents()
end
function CreateScene()
scene_ = Scene()
-- Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
-- show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates it
-- is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
-- optimizing manner
scene_:CreateComponent("Octree")
scene_:CreateComponent("DebugRenderer")
-- Create a scene node for the camera, which we will move around
-- The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
cameraNode = scene_:CreateChild("Camera")
-- Set an initial position for the camera scene node above the plane
cameraNode.position = Vector3(0.0, 0.0, -10.0)
local camera = cameraNode:CreateComponent("Camera")
camera.orthographic = true
camera.orthoSize = graphics.height * PIXEL_SIZE
camera.zoom = 1.2 * Min(graphics.width / 1280, graphics.height / 800) -- Set zoom according to user's resolution to ensure full visibility (initial zoom (1.2) is set for full visibility at 1280x800 resolution)
-- Create 2D physics world component
scene_:CreateComponent("PhysicsWorld2D")
local boxSprite = cache:GetResource("Sprite2D", "Urho2D/Box.png")
local ballSprite = cache:GetResource("Sprite2D", "Urho2D/Ball.png")
-- Create ground.
local groundNode = scene_:CreateChild("Ground")
groundNode.position = Vector3(0.0, -3.0, 0.0)
groundNode.scale = Vector3(200.0, 1.0, 0.0)
-- Create 2D rigid body for gound
local groundBody = groundNode:CreateComponent("RigidBody2D")
local groundSprite = groundNode:CreateComponent("StaticSprite2D")
groundSprite.sprite = boxSprite
-- Create box collider for ground
local groundShape = groundNode:CreateComponent("CollisionBox2D")
-- Set box size
groundShape.size = Vector2(0.32, 0.32)
-- Set friction
groundShape.friction = 0.5
local NUM_OBJECTS = 100
for i = 1, NUM_OBJECTS do
local node = scene_:CreateChild("RigidBody")
node.position = Vector3(Random(-0.1, 0.1), 5.0 + i * 0.4, 0.0)
-- Create rigid body
local body = node:CreateComponent("RigidBody2D")
body.bodyType = BT_DYNAMIC
local staticSprite = node:CreateComponent("StaticSprite2D")
local shape = nil
if i % 2 == 0 then
staticSprite.sprite = boxSprite
-- Create box
shape = node:CreateComponent("CollisionBox2D")
-- Set size
shape.size = Vector2(0.32, 0.32)
else
staticSprite.sprite = ballSprite
-- Create circle
shape = node:CreateComponent("CollisionCircle2D")
-- Set radius
shape.radius = 0.16
end
-- Set density
shape.density = 1.0
-- Set friction
shape.friction = 0.5
-- Set restitution
shape.restitution = 0.1
end
end
function CreateInstructions()
-- Construct new Text object, set string to display and font to use
local instructionText = ui.root:CreateChild("Text")
instructionText:SetText("Use WASD keys and mouse to move, Use PageUp PageDown to zoom.")
instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
-- Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER
instructionText.verticalAlignment = VA_CENTER
instructionText:SetPosition(0, ui.root.height / 4)
end
function SetupViewport()
-- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
-- at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
-- use, but now we just use full screen and default render path configured in the engine command line options
local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
renderer:SetViewport(0, viewport)
end
function MoveCamera(timeStep)
-- Do not move if the UI has a focused element (the console)
if ui.focusElement ~= nil then
return
end
-- Movement speed as world units per second
local MOVE_SPEED = 4.0
-- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if input:GetKeyDown(KEY_W) then
cameraNode:Translate(Vector3(0.0, 1.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_S) then
cameraNode:Translate(Vector3(0.0, -1.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_A) then
cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_D) then
cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_PAGEUP) then
local camera = cameraNode:GetComponent("Camera")
camera.zoom = camera.zoom * 1.01
end
if input:GetKeyDown(KEY_PAGEDOWN) then
local camera = cameraNode:GetComponent("Camera")
camera.zoom = camera.zoom * 0.99
end
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate")
-- Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
UnsubscribeFromEvent("SceneUpdate")
end
function HandleUpdate(eventType, eventData)
-- Take the frame time step, which is stored as a float
local timeStep = eventData["TimeStep"]:GetFloat()
-- Move the camera, scale movement with time step
MoveCamera(timeStep)
end
-- Create XML patch instructions for screen joystick layout specific to this sample app
function GetScreenJoystickPatchString()
return
"<patch>" ..
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"KeyBinding\" />" ..
" <attribute name=\"Text\" value=\"PAGEUP\" />" ..
" </element>" ..
" </add>" ..
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"KeyBinding\" />" ..
" <attribute name=\"Text\" value=\"PAGEDOWN\" />" ..
" </element>" ..
" </add>" ..
"</patch>"
end
| mit |
shahabsaf1/TELESEED-V2 | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
X-Coder/wire | lua/wire/stools/lever.lua | 9 | 2109 | WireToolSetup.setCategory( "Input, Output" )
WireToolSetup.open( "lever", "Lever", "gmod_wire_lever", nil, "Levers" )
if CLIENT then
language.Add( "tool.wire_lever.name", "Lever Tool (Wire)" )
language.Add( "tool.wire_lever.desc", "Spawns a Lever for use with the wire system." )
language.Add( "tool.wire_lever.0", "Primary: Create/Update Lever" )
language.Add( "tool.wire_lever.minvalue", "Max Value:" )
language.Add( "tool.wire_lever.maxvalue", "Min Value:" )
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax( 10 )
if SERVER then
function TOOL:GetConVars()
return self:GetClientNumber( "min" ), self:GetClientNumber( "max" )
end
function TOOL:MakeEnt( ply, model, Ang, trace )
//return WireLib.MakeWireEnt( ply, {Class = self.WireClass, Pos=trace.HitPos, Angle=Ang, Model=model}, self:GetConVars() )
local ent = WireLib.MakeWireEnt(ply, {Class = self.WireClass, Pos=(trace.HitPos + trace.HitNormal*22), Angle=Ang, Model=model}, self:GetConVars()) // +trace.HitNormal*46
local ent2 = ents.Create( "prop_physics" )
ent2:SetModel("models/props_wasteland/tram_leverbase01.mdl")
ent2:SetPos(trace.HitPos) // +trace.HitNormal*26
ent2:SetAngles(Ang)
ent2:Spawn()
ent2:Activate()
ent.BaseEnt = ent2
constraint.Weld(ent, ent2, 0, 0, 0, true)
ent:SetParent(ent2)
-- Parented + Weld seems more stable than a physical axis
--local LPos = ent:WorldToLocal(ent:GetPos() + ent:GetUp() * 10)
--local Cons = constraint.Ballsocket( ent2, ent, 0, 0, LPos, 0, 0, 1)
--LPos = ent:WorldToLocal(ent:GetPos() + ent:GetUp() * -10)
--Cons = constraint.Ballsocket( ent2, ent, 0, 0, LPos, 0, 0, 1)
--constraint.Axis(ent, ent2, 0, 0, ent:WorldToLocal(ent2:GetPos()), ent2:GetRight()*0.15)
return ent2
end
-- Uses default WireToolObj:MakeEnt's WireLib.MakeWireEnt function
end
TOOL.ClientConVar = {
model = "models/props_wasteland/tram_lever01.mdl",
min = 0,
max = 1
}
function TOOL.BuildCPanel(panel)
panel:NumSlider("#Tool.wire_lever.minvalue", "wire_lever_min", -10, 10, 2 )
panel:NumSlider("#Tool.wire_lever.maxvalue", "wire_lever_max", -10, 10, 2 )
end
| gpl-3.0 |
thedraked/darkstar | scripts/zones/Kuftal_Tunnel/npcs/qm1.lua | 14 | 1162 | -----------------------------------
-- Area: Kuftal Tunnel
-- NPC: ??? (qm1)
-- Note: Used to spawn Phantom Worm
-- @pos 75.943 29.916 118.854 174
-----------------------------------
package.loaded["scripts/zones/Kuftal_Tunnel/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Kuftal_Tunnel/TextIDs");
-----------------------------------
-- onSpawn Action
-----------------------------------
function onSpawn(npc)
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local x = npc:getXPos();
local y = npc:getYPos();
local z = npc:getZPos();
local mob = GetMobByID(Phantom_Worm);
-- Trade Darksteel ore
if (GetMobAction(Phantom_Worm) == 0 and trade:hasItemQty(645,1) and trade:getItemCount() == 1) then
player:tradeComplete();
SpawnMob(Phantom_Worm):updateClaim(player); -- Phantom Worm
mob:setPos(x+1,y,z+1);
npc:setStatus(STATUS_DISAPPEAR);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
end;
| gpl-3.0 |
mtroyka/Zero-K | LuaRules/Gadgets/unit_refuel_pad_handler.lua | 2 | 15507 | function gadget:GetInfo()
return {
name = "Refuel Pad Handler",
desc = "Replaces the engine implementation of the refuel pad.",
author = "Google Frog",
date = "5 Jan 2014", --changes: 22 March 2014
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true, -- loaded by default?
}
end
if (not gadgetHandler:IsSyncedCode()) then
return false -- no unsynced code
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spGetUnitBasePosition = Spring.GetUnitBasePosition
local spGetUnitHeading = Spring.GetUnitHeading
local spGetUnitDefID = Spring.GetUnitDefID
local spSetUnitVelocity = Spring.SetUnitVelocity
local spSetUnitLeaveTracks = Spring.SetUnitLeaveTracks
local spGetUnitVelocity = Spring.GetUnitVelocity
local spGetUnitRotation = Spring.GetUnitRotation
local spGetUnitHealth = Spring.GetUnitHealth
local spSetUnitHealth = Spring.SetUnitHealth
local spGetUnitIsStunned = Spring.GetUnitIsStunned
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local spGetUnitIsDead = Spring.GetUnitIsDead
local mcSetVelocity = Spring.MoveCtrl.SetVelocity
local mcSetRotationVelocity = Spring.MoveCtrl.SetRotationVelocity
local mcSetPosition = Spring.MoveCtrl.SetPosition
local mcSetRotation = Spring.MoveCtrl.SetRotation
local mcDisable = Spring.MoveCtrl.Disable
local mcEnable = Spring.MoveCtrl.Enable
local coroutine = coroutine
local Sleep = coroutine.yield
local assert = assert
-- South is 0 radians and increases counter-clockwise
local HEADING_TO_RAD = (math.pi*2/2^16)
local RAD_TO_HEADING = 1/HEADING_TO_RAD
local PI = math.pi
local cos = math.cos
local sin = math.sin
local acos = math.acos
local floor = math.floor
local sqrt = math.sqrt
local exp = math.exp
local min = math.min
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local mobilePadDefs = {
[UnitDefNames["armcarry"].id] = true,
[UnitDefNames["shipcarrier"].id] = true,
}
local turnRadius = {}
local rotateUnit = {}
for i=1,#UnitDefs do
local movetype = Spring.Utilities.getMovetype(UnitDefs[i])
if movetype == 0 then -- fixedwing
local ud = UnitDefs[i]
if ud.customParams and ud.customParams.refuelturnradius then
turnRadius[i] = tonumber(ud.customParams.refuelturnradius)
else
turnRadius[i] = ud.turnRadius
end
rotateUnit[i] = true
elseif movetype == 1 then -- gunship
turnRadius[i] = 20
rotateUnit[i] = false
end
end
local padSnapRangeSqr = 80^2
local REFUEL_TIME = 5*30
local PAD_ENERGY_DRAIN = 2.5
local REFUEL_HALF_SECONDS = REFUEL_TIME/15
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local landingUnit = {}
local unitNewScript = {}
local unitMovectrled = {}
local coroutines = {}
local function StartScript(fn)
local co = coroutine.create(fn)
coroutines[#coroutines + 1] = co
end
local function SitOnPad(unitID)
local landData = landingUnit[unitID]
local px, py, pz, dx, dy, dz = Spring.GetUnitPiecePosDir(landData.padID, landData.padPieceID)
local heading = spGetUnitHeading(unitID)*HEADING_TO_RAD
local ud = UnitDefs[Spring.GetUnitDefID(unitID)]
local cost = ud.metalCost
local maxHP = ud.health
local healPerHalfSecond = 2*PAD_ENERGY_DRAIN*maxHP/(cost*2)
if not unitMovectrled[unitID] then
mcEnable(unitID)
spSetUnitLeaveTracks(unitID, false)
unitMovectrled[unitID] = true
end
mcSetRotation(unitID,0,heading,0)
local padHeading = acos(dz)
if dx < 0 then
padHeading = 2*PI-padHeading
end
-- Spring.Echo(dx)
-- Spring.Echo(dy)
-- Spring.Echo(dz)
-- Spring.Echo(padHeading*180/PI)
local headingDiff = heading - padHeading
spSetUnitVelocity(unitID, 0, 0, 0)
mcSetVelocity(unitID, 0, 0, 0)
mcSetPosition(unitID, px, py, pz)
-- deactivate unit to cause the lups jets away
Spring.SetUnitCOBValue(unitID, COB.ACTIVATION, 0)
local function SitLoop()
local landDuration = 0
local refuelProgress = GG.RequireRefuel(unitID) and 0
local drainingEnergy = false
while true do
if (not landingUnit[unitID]) or landingUnit[unitID].abort or (not landingUnit[unitID].landed) then
if not spGetUnitIsDead(unitID) then
spSetUnitLeaveTracks(unitID, true)
spSetUnitVelocity(unitID, 0, 0, 0)
Spring.SetUnitResourcing(unitID, "uue" ,0)
mcDisable(unitID)
unitMovectrled[unitID] = nil
GG.UpdateUnitAttributes(unitID)
end
landingUnit[unitID] = nil
return
end
if landData.mobilePad then
local px, py, pz, dx, dy, dz = Spring.GetUnitPiecePosDir(landData.padID, landData.padPieceID)
local newPadHeading = acos(dz)
if dx < 0 then
newPadHeading = 2*PI-newPadHeading
end
mcSetPosition(unitID, px, py, pz)
mcSetRotation(unitID,0,headingDiff+newPadHeading,0)
end
landDuration = landDuration + 1
if landDuration%15 == 0 then
local stunned_or_inbuild = spGetUnitIsStunned(landData.padID) or (spGetUnitRulesParam(landData.padID,"disarmed") == 1)
if stunned_or_inbuild then
if drainingEnergy then
Spring.SetUnitResourcing(unitID, "uue" ,0)
drainingEnergy = false
end
else
local slowState = 1 - (spGetUnitRulesParam(landData.padID,"slowState") or 0)
if refuelProgress then
refuelProgress = refuelProgress + slowState
if refuelProgress >= REFUEL_HALF_SECONDS then
refuelProgress = false
GG.RefuelComplete(unitID)
end
end
if not refuelProgress then
if GG.HasCombatRepairPenalty(unitID) then
slowState = slowState/4
end
local hp = spGetUnitHealth(unitID)
if hp < maxHP then
if drainingEnergy ~= slowState then
Spring.SetUnitResourcing(unitID, "uue" ,PAD_ENERGY_DRAIN*slowState)
drainingEnergy = slowState
end
local _,_,_,energyUse = Spring.GetUnitResources(unitID)
spSetUnitHealth(unitID, min(maxHP, hp + healPerHalfSecond*energyUse/PAD_ENERGY_DRAIN))
else
if drainingEnergy then
Spring.SetUnitResourcing(unitID, "uue" ,0)
drainingEnergy = false
end
break
end
end
end
end
-- Check crashing every 10s as safety for a rare bug. Otherwise the pad will be oocupied forever.
if landDuration%300 == 0 then
if Spring.GetUnitMoveTypeData(unitID).aircraftState == "crashing" then
if drainingEnergy then
Spring.SetUnitResourcing(unitID, "uue" ,0)
drainingEnergy = false
Spring.DestroyUnit(unitID)
end
end
end
Sleep()
end
spSetUnitLeaveTracks(unitID, true)
spSetUnitVelocity(unitID, 0, 0, 0)
Spring.SetUnitResourcing(unitID, "uue" ,0)
mcDisable(unitID)
GG.UpdateUnitAttributes(unitID) --update pending attribute changes in unit_attributes.lua if available
unitMovectrled[unitID] = nil
landingUnit[unitID] = nil
-- activate unit and its jets
Spring.SetUnitCOBValue(unitID, COB.ACTIVATION, 1)
GG.LandComplete(unitID)
end
StartScript(SitLoop)
end
local function CircleToLand(unitID, goal)
unitNewScript[unitID] = true
local start = {spGetUnitBasePosition(unitID)}
local unitDefID = spGetUnitDefID(unitID)
local ud = unitDefID and UnitDefs[unitDefID]
if not (unitDefID and ud and turnRadius[unitDefID]) then
return
end
local turnCircleRadius = turnRadius[unitDefID]
local turnCircleRadiusSq = turnCircleRadius^2
local disSq = (goal[1] - start[1])^2 + (goal[2] - start[2])^2 + (goal[3] - start[3])^2
if disSq < padSnapRangeSqr then
turnCircleRadius = 1
end
local vx,vy,vz = spGetUnitVelocity(unitID)
local maxSpeed = sqrt(vx*vx + vy*vy + vz*vz)
local targetSpeed = ud.speed/30
local heading = spGetUnitHeading(unitID)*HEADING_TO_RAD
-- Find position of focus points for left or right turning circles
local leftFocus = {
[1] = start[1] + turnCircleRadius*sin(heading + PI/2),
[3] = start[3] + turnCircleRadius*cos(heading + PI/2)
}
local rightFocus = {
[1] = start[1] + turnCircleRadius*sin(heading - PI/2),
[3] = start[3] + turnCircleRadius*cos(heading - PI/2)
}
-- Decide upon direction to turn
local leftDistSq = (goal[1] - leftFocus[1])^2 + (goal[3] - leftFocus[3])^2
local rightDistSq = (goal[1] - rightFocus[1])^2 + (goal[3] - rightFocus[3])^2
--Spring.MarkerAddPoint(leftFocus[1],0,leftFocus[3],sqrt(leftDistSq))
--Spring.MarkerAddPoint(rightFocus[1],0,rightFocus[3],sqrt(rightDistSq))
local turnDir -- 1 is left, -1 is right.
local focus
if rightDistSq < turnCircleRadiusSq then
turnDir = 1
focus = leftFocus
elseif leftDistSq < turnCircleRadiusSq then
turnDir = -1
focus = rightFocus
elseif leftDistSq < rightDistSq then
turnDir = 1
focus = leftFocus
else
turnDir = -1
focus = rightFocus
end
-- Determine the equations of the two lines tangent to the circle passing through the goal.
local fx,fz,gx,gz,r = focus[1], focus[3], goal[1], goal[3], turnCircleRadius
local denom = (fx^2 - 2*fx*gx + gx^2 - r^2)
if denom == 0 then
denom = 0.0001
end
local determinateSqrt = sqrt(fx^2*r^2 + fz^2*r^2 - 2*fx*gx*r^2 + gx^2*r^2 - 2*fz*gz*r^2 + gz^2*r^2 - r^4)
local otherBit = fx*fz - fz*gx - fx*gz + gx*gz
local grad1 = (otherBit - determinateSqrt)/denom
local grad2 = (otherBit + determinateSqrt)/denom
-- Choose a line
local gradToFocus = (fz - gz)/(fx == gx and 0.0001 or fx - gx)
local grad
if (grad1 < gradToFocus and gradToFocus < grad2) or (grad2 < gradToFocus and gradToFocus < grad1) then
if grad1*turnDir < grad2*turnDir then
grad = grad1
else
grad = grad2
end
else
if grad1*turnDir < grad2*turnDir then
grad = grad2
else
grad = grad1
end
end
-- Find the intersection of the line and circle.
local ix = (fx + fz*grad - gz*grad + gx*grad^2)/(1 + grad^2)
local iz = grad*(ix-gx)+gz
-- Find the angle to the intersection and the distance to it along the circle.
local sAngle = (heading - turnDir*PI/2)
local iAngle = acos((iz-fz)/turnCircleRadius) or PI/2
if ix < fx then
iAngle = -iAngle
end
iAngle = iAngle%(2*PI)
local angularDist = turnDir*(iAngle - sAngle)%(2*PI)
local circleDist = angularDist*turnCircleRadius
-- Calculate linear distance after turning and vector to follow
local lineDist = sqrt((gx - ix)^2 + (gz - iz)^2)
local lineVectorX = (gx - ix)/lineDist
local lineVectorZ = (gz - iz)/lineDist
local totalDist = circleDist + lineDist
-- Functions which determine position and direction based on distance travelled
local function DistanceToPosition(distance)
if distance < circleDist then
return fx + turnCircleRadius*sin(sAngle + turnDir*distance/turnCircleRadius), fz + turnCircleRadius*cos(sAngle + turnDir*distance/turnCircleRadius)
else
return ix + (distance - circleDist)*lineVectorX, iz + (distance - circleDist)*lineVectorZ
end
end
local linearDirection = acos(lineVectorZ)
if lineVectorX < 0 then
linearDirection = -linearDirection
end
local function DistanceToDirection(distance)
if distance < circleDist then
return heading + turnDir*distance/turnCircleRadius
else
return linearDirection
end
end
-- Calculate speeds and acceleration
local currentSpeed = maxSpeed
local currentTime = 1
local estimatedTime = (2*totalDist)/(maxSpeed+targetSpeed)
local acceleration = (targetSpeed^2 - maxSpeed^2)/(2*totalDist)
-- Sigmoid Version (have problem with landing on mobile airpad)
-- local function TimeToVerticalPositon(t)
-- return start[2] + (goal[2] - start[2])*(1/(1 + exp(6*(-2*t/estimatedTime +1))))
-- end
-- Straight line Version
local function TimeToVerticalPositon(t)
return start[2] + (goal[2] - start[2])*t/estimatedTime
end
--[[
for i = 0, totalDist, maxSpeed do
local px, pz = DistanceToPosition(i)
Spring.MarkerAddPoint(px,0,pz,"")
end
Spring.MarkerAddLine(gx,0,gz,ix,0,iz)
Spring.Echo(sqrt(lineVectorX^2 + lineVectorZ^2))
--]]
-- Roll Animation
local roll = 0
--local _,_,roll = spGetUnitRotation(unitID) -- function not present in 91.0
roll = -roll
local rollStopFudgeDistance = maxSpeed*25
local rollSpeed = 0.03
local maxRoll = 0.8
-- Move control stuff
if not unitMovectrled[unitID] then
mcEnable(unitID)
if rotateUnit[unitDefID] then
mcSetRotation(unitID,0,heading,roll+currentTime/50)
end
spSetUnitLeaveTracks(unitID, false)
unitMovectrled[unitID] = true
end
local currentDistance = currentSpeed
local function LandLoop()
local prevX, prevY, prevZ = start[1], start[2], start[3]
while currentDistance + currentSpeed < totalDist do
if (not landingUnit[unitID]) or landingUnit[unitID].abort then
if not spGetUnitIsDead(unitID) then
spSetUnitLeaveTracks(unitID, true)
mcDisable(unitID)
unitMovectrled[unitID] = nil
GG.UpdateUnitAttributes(unitID)
end
landingUnit[unitID] = nil
return
end
local px, pz = DistanceToPosition(currentDistance)
local py = TimeToVerticalPositon(currentTime)
local direction = DistanceToDirection(currentDistance)
if rotateUnit[unitDefID] then
mcSetRotation(unitID,0,direction,roll)
end
mcSetPosition(unitID, px, py, pz)
mcSetVelocity(unitID, px - prevX, py - prevY, pz - prevZ)
spSetUnitVelocity(unitID, px - prevX, 0, pz - prevZ)
currentDistance = currentDistance + currentSpeed
currentSpeed = currentSpeed + acceleration
currentTime = currentTime + 1
if currentDistance < circleDist - rollStopFudgeDistance then
if -roll*turnDir < maxRoll then
roll = roll - turnDir*rollSpeed
elseif -roll*turnDir > maxRoll + rollSpeed then
roll = roll + turnDir*rollSpeed
end
else
if -roll*turnDir > 0 then
roll = roll + turnDir*rollSpeed
elseif -roll*turnDir < -rollSpeed then
roll = roll - turnDir*rollSpeed
end
end
prevX, prevY, prevZ = px, py, pz
Sleep()
if unitNewScript[unitID] and currentTime ~= 2 then
return
else
unitNewScript[unitID] = nil
end
end
local px, pz = DistanceToPosition(totalDist)
if landingUnit[unitID] and not landingUnit[unitID].abort then
landingUnit[unitID].landed = true
SitOnPad(unitID)
end
end
StartScript(LandLoop)
end
function GG.SendBomberToPad(unitID, padID, padPieceID)
local padDefID = Spring.GetUnitDefID(padID)
landingUnit[unitID] = {
mobilePad = padDefID and mobilePadDefs[padDefID],
padID = padID,
padPieceID = padPieceID,
}
local px, py, pz = Spring.GetUnitPiecePosDir(padID, padPieceID)
CircleToLand(unitID, {px,py,pz})
end
function GG.LandAborted(unitID)
if landingUnit[unitID] then
landingUnit[unitID].abort = true
end
end
local function UpdateCoroutines()
local newCoroutines = {}
for i=1, #coroutines do
local co = coroutines[i]
if (coroutine.status(co) ~= "dead") then
newCoroutines[#newCoroutines + 1] = co
end
end
coroutines = newCoroutines
for i=1, #coroutines do
assert(coroutine.resume(coroutines[i]))
end
end
local function UpdatePadLocations(f)
for unitID, data in pairs(landingUnit) do
if data.mobilePad and not data.landed then
local px, py, pz = Spring.GetUnitPiecePosDir(data.padID, data.padPieceID)
CircleToLand(unitID, {px,py,pz})
end
end
end
function gadget:GameFrame(f)
UpdateCoroutines()
if f%3 == 1 then
UpdatePadLocations()
end
end
| gpl-2.0 |
bizkut/BudakJahat | Rotations/Priest/Shadow/ShadowWinstonv8.lua | 1 | 79577 | local rotationName = "Winstonv8"
---------------
--- Toggles ---
---------------
local function createToggles()
-- Rotation Button
RotationModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Automatic Rotation", tip = "Swaps between Single and Multiple based on number of targets in range.", highlight = 1, icon = br.player.spell.shadowform },
[2] = { mode = "Mult", value = 2 , overlay = "Multiple Target Rotation", tip = "Multiple target rotation used.", highlight = 0, icon = br.player.spell.mindSear },
[3] = { mode = "Sing", value = 3 , overlay = "Single Target Rotation", tip = "Single target rotation used.", highlight = 0, icon = br.player.spell.mindFlay },
[4] = { mode = "Off", value = 4 , overlay = "DPS Rotation Disabled", tip = "Disable DPS Rotation", highlight = 0, icon = br.player.spell.shadowMend}
};
CreateButton("Rotation",1,0)
-- Cooldown Button
CooldownModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Cooldowns Automated", tip = "Automatic Cooldowns - Boss Detection.", highlight = 1, icon = br.player.spell.mindBlast },
[2] = { mode = "On", value = 1 , overlay = "Cooldowns Enabled", tip = "Cooldowns used regardless of target.", highlight = 0, icon = br.player.spell.mindBlast },
[3] = { mode = "Off", value = 3 , overlay = "Cooldowns Disabled", tip = "No Cooldowns will be used.", highlight = 0, icon = br.player.spell.mindBlast }
};
CreateButton("Cooldown",2,0)
-- Defensive Button
DefensiveModes = {
[1] = { mode = "On", value = 1 , overlay = "Defensive Enabled", tip = "Includes Defensive Cooldowns.", highlight = 1, icon = br.player.spell.dispersion },
[2] = { mode = "Off", value = 2 , overlay = "Defensive Disabled", tip = "No Defensives will be used.", highlight = 0, icon = br.player.spell.dispersion }
};
CreateButton("Defensive",3,0)
-- Void Form Button
VoidFormModes = {
[1] = { mode = "On", value = 1 , overlay = "Void Form Enabled", tip = "Bot will shift to Void Form.", highlight = 1, icon = br.player.spell.voidEruption },
[2] = { mode = "Off", value = 2 , overlay = "Void Form Disabled", tip = "Bot will NOT shift to Void Form.", highlight = 0, icon = br.player.spell.voidEruption }
};
CreateButton("VoidForm",4,0)
-- Interrupt button
InterruptToggleModes = {
[1] = { mode = "On", value = 1 , overlay = "Interrupts Enabled", tip = "Includes Basic Interrupts.", highlight = 1, icon = br.player.spell.silence},
[2] = { mode = "Off", value = 2 , overlay = "Interrupts Disabled", tip = "No Interrupts will be used.", highlight = 0, icon = br.player.spell.silence}
};
CreateButton("InterruptToggle",5,0)
end
---------------
--- OPTIONS ---
---------------
local function createOptions()
local optionTable
local function rotationOptions()
local section
-- General Options
section = br.ui:createSection(br.ui.window.profile, "General")
-- Dummy DPS Test
br.ui:createSpinner(section, "DPS Testing", 1, 1, 60, 1, "Set to desired time for test in minuts. Min: 5 / Max: 60 / Interval: 5")
-- Pre-Pull Timer
br.ui:createSpinner(section, "Pre-Pull Timer", 5, 1, 10, 1, "Set to desired time to start Pre-Pull (DBM Required). Min: 1 / Max: 10 / Interval: 1")
-- Body and Soul
br.ui:createCheckbox(section,"PWS: Body and Soul")
-- Auto Buff Fortitude
br.ui:createCheckbox(section,"Power Word: Fortitude", "Check to auto buff Fortitude on party.")
-- Out of Combat Attack
br.ui:createCheckbox(section,"Pull OoC", "Check to Engage the Target out of Combat.")
-- Elixir
br.ui:createDropdownWithout(section,"Elixir", {"Flask of Endless Fathoms","Repurposed Fel Focuser","Oralius' Whispering Crystal","None"}, 1, "Set Elixir to use.")
-- Mouseover Dotting
br.ui:createCheckbox(section,"Mouseover Dotting")
-- SWP before VT
br.ui:createCheckbox(section,"SWP b4 VT", "Check to dot SWP before VT.")
-- Use 1st Trinket off CD
--br.ui:createCheckbox(section,"Trinket 1 Off CD", "Use Trinket 1 off Cooldown. Might Overrides individual trinket usage below.")
--br.ui:createCheckbox(section,"Trinket 2 Off CD", "Use Trinket 1 off Cooldown. Might Overrides individual trinket usage below.")
br.ui:checkSectionState(section)
-- AoE Options
section = br.ui:createSection(br.ui.window.profile, "AoE Options")
-- Shadow Crash
br.ui:createCheckbox(section,"Shadow Crash")
-- SWP Max Targets
br.ui:createSpinnerWithout(section, "SWP Max Targets", 3, 1, 7, 1, "Unit Count Limit that SWP will be cast on.")
-- VT Max Targets
br.ui:createSpinnerWithout(section, "VT Max Targets", 3, 1, 7, 1, "Unit Count Limit that VT will be cast on.")
-- Mind Sear Targets
br.ui:createSpinnerWithout(section, "Mind Sear Targets", 2, 2, 10, 1, "Unit Count Limit before Mind Sear is being used.")
-- Dark Void Targets
br.ui:createSpinnerWithout(section, "Dark Void Targets", 5, 1, 10, 1, "Unit Count Limit before Dark Void is being used.")
-- Dark Ascension AoE
br.ui:createSpinner(section, "Dark Ascension AoE", 5, 1, 10, 1, "Use DA as AoE Damage Burst at desired Unit Count Limit.")
br.ui:checkSectionState(section)
-- Cooldown Options
section = br.ui:createSection(br.ui.window.profile, "Cooldowns")
-- Int Pot
br.ui:createCheckbox(section,"Int Pot")
-- Trinkets
br.ui:createCheckbox(section,"Trinket 1", "Use Trinket 1 on Cooldown.")
br.ui:createCheckbox(section,"Trinket 2", "Use Trinket 2 on Cooldown.")
-- Dark Ascension
--if hasTalent(darkAscension) then
br.ui:createCheckbox(section,"Dark Ascension", "Use Dark Ascension as Insanity Boost")
-- Dark Ascension Burst
br.ui:createCheckbox(section,"Dark Ascension Burst", "Use Dark Ascension for another Void Form Burst")
-- Memory of Lucid Dreams
br.ui:createCheckbox(section,"Lucid Dreams", "Use Memory of Lucid Dreams Essence")
br.ui:createSpinnerWithout(section, " Lucid Dreams VF Stacks", 20, 1, 50, 1, "Voidform Stacks when to use Lucid Dreams.")
br.ui:createSpinnerWithout(section, " Lucid Dreams Insanity", 50, 25, 100, 1, "Insanity Power when to use Lucid Dreams.")
-- Shadowfiend
br.ui:createCheckbox(section, "Shadowfiend / Mindbender", "Use Shadowfiend or Mindbender on CD")
br.ui:createSpinner(section, " Mindbender in VF", 10, 0, 50, 1, "Set to desired Void Form stacks to use at.")
-- Surrender To Madness
br.ui:createCheckbox(section,"Surrender To Madness")
-- Dispersion
--br.ui:createCheckbox(section, "Dispersion S2M")
--br.ui:createSpinnerWithout(section, " Dispersion Stacks", 10, 5, 100, 5, "Set to desired Void Form stacks to use at.")
-- Void Torrent
br.ui:createCheckbox(section,"Void Torrent")
--br.ui:createSpinnerWithout(section, " Void Torrent Stacks", 0, 0, 100, 1, "Set to desired Void Form stacks to use at.")
br.ui:checkSectionState(section)
-- Defensive Options
section = br.ui:createSection(br.ui.window.profile, "Defensive")
-- Healthstone
br.ui:createSpinner(section, "Healthstone", 60, 0, 100, 5, "Health Percentage to use at.")
-- Gift of The Naaru
--if br.player.race == "Draenei" then
-- br.ui:createSpinner(section, "Gift of the Naaru", 50, 0, 100, 5, "Health Percent to Cast At")
--end
--if br.player.race == "Dwarf" then
-- br.ui:createSpinner(section, "Stoneform", 50, 0, 100, 5, "Health Percent to Cast At")
--end
-- Dispel Magic
br.ui:createCheckbox(section,"Dispel Magic")
-- Dispersion
br.ui:createSpinner(section, "Dispersion", 20, 0, 100, 5, "Health Percentage to use at.")
-- Fade
br.ui:createCheckbox(section, "Fade")
-- Vampiric Embrace
br.ui:createSpinner(section, "Vampiric Embrace", 25, 0, 100, 5, "Health Percentage to use at.")
-- Power Word: Shield
br.ui:createSpinner(section, "Power Word: Shield", 60, 0, 100, 5, "Health Percentage to use at.")
-- Shadow Mend
br.ui:createSpinner(section, "Shadow Mend", 60, 0, 100, 5, "Health Percentage to use at.")
-- Psychic Scream / Mind Bomb
br.ui:createSpinner(section, "Psychic Scream / Mind Bomb", 40, 0, 100, 5, "Health Percentage to use at.")
br.ui:checkSectionState(section)
-- Interrupt Options
section = br.ui:createSection(br.ui.window.profile, "Interrupts")
-- Silence
br.ui:createCheckbox(section, "Silence")
-- Psychic Horror
br.ui:createCheckbox(section, "Psychic Horror")
-- Psychic Scream
br.ui:createCheckbox(section, "Psychic Scream")
-- Mind Bomb
br.ui:createCheckbox(section, "Mind Bomb")
-- Interrupt Target
--br.ui:createDropdownWithout(section,"Interrupt Unit", {"1. All in Range", "2. Target", "3. Focus"}, 1, "Interrupt your focus, your target, or all enemies in range.")
-- Interrupt Percentage
br.ui:createSpinner(section, "Interrupt At", 45, 0, 95, 5, "Cast Percent to Cast At")
br.ui:checkSectionState(section)
-- Toggle Key Options
section = br.ui:createSection(br.ui.window.profile, "Toggle Keys")
-- Single/Multi Toggle
br.ui:createDropdown(section, "Rotation Mode", br.dropOptions.Toggle, 4)
-- Cooldown Key Toggle
br.ui:createDropdown(section, "Cooldown Mode", br.dropOptions.Toggle, 3)
-- Void Form
br.ui:createDropdown(section, "Void Form Mode", br.dropOptions.Toggle, 6)
-- Interrupts Key Toggle
br.ui:createDropdown(section, "Interrupt Mode", br.dropOptions.Toggle, 6)
-- Pause Toggle
br.ui:createDropdown(section, "Pause Mode", br.dropOptions.Toggle, 6)
br.ui:checkSectionState(section)
end
optionTable = {{
[1] = "Rotation Options",
[2] = rotationOptions,
}}
return optionTable
end
----------------
--- ROTATION ---
----------------
local function runRotation()
--if br.timer:useTimer("debugShadow", 0.1) then
--Print("Running: "..rotationName)
---------------
--- Toggles ---
---------------
UpdateToggle("Rotation",0.25)
UpdateToggle("Cooldown",0.25)
UpdateToggle("Defensive",0.25)
UpdateToggle("VoidForm",0.25)
UpdateToggle("Interrupt",0.25)
br.player.ui.mode.voidForm = br.data.settings[br.selectedSpec].toggles["VoidForm"]
--br.player.ui.mode.interruptToggle = br.data.settings[br.selectedSpec].toggles["InterruptToggle"]
--------------
--- Locals ---
--------------
local addsExist = false
local addsIn = 999
local artifact = br.player.artifact
local buff = br.player.buff
local cast = br.player.cast
local castable = br.player.cast.debug
local channelDelay = 0.1
local combatTime = getCombatTime()
local cd = br.player.cd
local charges = br.player.charges
local deadtar, attacktar, hastar, playertar = deadtar or UnitIsDeadOrGhost("target"), attacktar or UnitCanAttack("target", "player"), hastar or GetObjectExists("target"), UnitIsPlayer("target")
local debuff = br.player.debuff
local enemies = br.player.enemies
local essence = br.player.essence
local falling, swimming, flying, moving = getFallTime(), IsSwimming(), IsFlying(), GetUnitSpeed("player")>0
local friendly = friendly or GetUnitIsFriend("target", "player")
local gcd = br.player.gcd
local gcdMax = br.player.gcdMax
local gHaste = br.player.gcdMax / (1 + GetHaste() / 100)
local healPot = getHealthPot()
local hasMouse = GetObjectExists("mouseover")
local inCombat = br.player.inCombat
local inInstance = br.player.instance=="party"
local inRaid = br.player.instance=="raid"
local item = br.player.items
local level = br.player.level
local lootDelay = getOptionValue("LootDelay")
local lowestHP = br.friend[1].unit
local mode = br.player.ui.mode
local moveIn = 999
local moving = (isMoving("player") and not br.player.buff.norgannonsForesight.exists() and not br.player.buff.surrenderToMadness.exists())
local mrdm = math.random
local perk = br.player.perk
local pHaste = 1 / (1 + GetHaste() / 100)
local php = br.player.health
local playerMouse = UnitIsPlayer("mouseover")
local power, powmax, powgen, powerDeficit = br.player.power.insanity.amount(), br.player.power.insanity.max(), br.player.power.insanity.regen(), br.player.power.insanity.deficit()
local pullTimer = br.DBM:getPulltimer()
local racial = br.player.getRacial()
local solo = #br.friend < 2
local spell = br.player.spell
local t18_2pc = TierScan("T18")>=2
local t19_2pc = TierScan("T19")>=2
local t19_4pc = TierScan("T19")>=4
local t20_4pc = TierScan("T20")>=4
local t21_4pc = TierScan("T21")>=4
local talent = br.player.talent
local traits = br.player.traits
local thp = getHP("target")
local ttd = getTTD
local ttm = br.player.power.insanity.ttm()
local units = br.player.units
local use = br.player.use
local chgMax = max(0.75, 1.5 * 2 / (1 + GetHaste() / 100))
local DAmaxTargets = getOptionValue("Dark Ascension AoE")
local MSmaxTargets = getOptionValue("Mind Sear Targets")
local SWPmaxTargets = getOptionValue("SWP Max Targets")
local VTmaxTargets = getOptionValue("VT Max Targets")
local mindFlayRecast = br.timer:useTimer("mindFlayRecast", chgMax)
local mindSearRecast = br.timer:useTimer("mindSearRecast", chgMax)
local executeHP = 20
units.get(5)
units.get(8)
units.get(12)
units.get(15)
units.get(30)
units.get(40)
enemies.get(5)
enemies.get(8)
enemies.get(8,"target")
enemies.get(12)
enemies.get(15)
enemies.get(15, "target")
enemies.get(20)
enemies.get(20, "target")
enemies.get(30)
enemies.get(40)
enemies.get(40, "target")
if leftCombat == nil then leftCombat = GetTime() end
if profileStop == nil then profileStop = false end
if cmbLast == nil or not UnitExists(units.dyn40) then cmbLast = UnitGUID("player") end
if cmvtLast == nil or not UnitExists(units.dyn40) then cmvtLast = UnitGUID("player") end
if cmvtaLast == nil or not UnitExists(thisUnit) then cmvtaLast = UnitGUID("player") end
if cswpb4vtLast == nil or not UnitExists(units.dyn40) then cswpb4vtLast = UnitGUID("player") end
if cswvLast == nil or not UnitExists(units.dyn40) then cswvLast = UnitGUID("player") end
if cvtaLast == nil or not UnitExists(thisUnit) then cvtaLast = UnitGUID("player") end
if cvtLast == nil or not UnitExists(units.dyn40) then cvtLast = UnitGUID("player") end
if mbLast == nil or not UnitExists("target") then mbLast = UnitGUID("player") end
if mvtLast == nil or not UnitExists("target") then mvtLast = UnitGUID("player") end
if pmbLast == nil or not UnitExists("target") then pmbLast = UnitGUID("player") end
if pswvLast == nil or not UnitExists("target") then pswvLast = UnitGUID("player") end
if pvtLast == nil or not UnitExists("target") then pvtLast = UnitGUID("player") end
if swpb4vtLast == nil or not UnitExists(units.dyn40) then swpb4vtLast = UnitGUID("player") end
if swvLast == nil or not UnitExists("target") then swvLast = UnitGUID("player") end
if vtLast == nil or not UnitExists("target") then vtLast = UnitGUID("player") end
if vtVFLast == nil or not UnitExists("target") then vtVFLast = UnitGUID("player") end
-- if HackEnabled("NoKnockback") ~= nil then HackEnabled("NoKnockback", false) end
--if t19_2pc then t19pc2 = 1 else t19pc2 = 0 end
--if t20_4pc then t20pc4 = 1 else t20pc4 = 0 end
--if t21_4pc then t21pc4 = 1 else t21pc4 = 0 end
if hasBloodLust() then lusting = 1 else lusting = 0 end
if talent.auspiciousSpirits then auspiciousSpirits = 1 else auspiciousSpirits = 0 end
if talent.fortressOfTheMind then fortressOfTheMind = 1 else fortressOfTheMind = 0 end
if talent.legacyOfTheVoid then legacyOfTheVoid = 1 else legacyOfTheVoid = 0 end
if talent.lingeringInsanity then lingeringInsanity = 1 else lingeringInsanity = 0 end
if talent.mindbender then mindbender = 1 else mindbender = 0 end
if talent.sanlayn then sanlayn = 1 else sanlayn = 0 end
--if hasEquiped(132864) then mangaMad = 1 else mangaMad = 0 end
if #enemies.yards40 == 1 then singleEnemy = 1 else singleEnemy = 0 end
local raidMovementWithin15 = 0 -- trying to come up with a clever way to manage this, maybe a toggle or something. For now, just assume we always have to move soon
-- searEnemmies represents the number of enemies in mind sear range of the primary target.
local activeEnemies = #enemies.yards20t
local dAEnemies = getEnemies(units.dyn40, 8, true)
local dVEnemies = getEnemies(units.dyn40, 8, true)
local searEnemies = getEnemies(units.dyn40, 8, true)
if mode.rotation == 3 then
activeEnemies = 1
MSmaxTargets = 1
SWPmaxTargets = 1
VTmaxTargets = 1
end
--print(tostring(cast.able.voidBolt()))
-- Keep track of Drain Stacks
-- Drain stacks will be equal to Voidform stacks, minus any time spent in diepersion and minus any time spent channeling void torrent
if buff.voidForm.stack() == 0 then
nonDrainTicks = 0
drainStacks = 0
else
if inCombat and (buff.dispersion.exists() or buff.voidTorrent.exists()) then
if br.timer:useTimer("drainStacker", 1) then
nonDrainTicks = nonDrainTicks + 1
end
end
drainStacks = buff.voidForm.stack() - nonDrainTicks
end
-- Insanity Drain
insanityDrain = 6 + (0.68 * (drainStacks))
--insanityDrained = insanityDrain + (15.6 * gcdMax)
insanityDrained = insanityDrain * gcdMax * 3
local lucisDreams = essence.memoryOfLucidDreams.active
local dotsUp = debuff.shadowWordPain.exists() and debuff.vampiricTouch.exists()
local dotsTick = debuff.shadowWordPain.remain() > 4.3 and debuff.vampiricTouch.remain() > 4.3
local noHarvest = not buff.harvestedThoughts.exists() and not cast.current.mindSear()
local noSdHarvest = not traits.searingDialogue.active and not cast.current.mindSear()
local noTH = noHarvest or noSdHarvest
local SWPb4VT = isChecked("SWP b4 VT") --or debuff.shadowWordPain.exists()
local mindblastTargets = math.floor((4.5 + traits.whispersOfTheDamned.rank) / (1 + 0.27 * traits.searingDialogue.rank))
local swp_trait_ranks_check = (1 - 0.07 * traits.deathThroes.rank + 0.2 * traits.thoughtHarvester.rank) * (1 - 0.09 * traits.thoughtHarvester.rank * traits.searingDialogue.rank)
local vt_trait_ranks_check = (1 - 0.04 * traits.thoughtHarvester.rank - 0.05 * traits.spitefulApparitions.rank)
local vt_mis_trait_ranks_check = (1 - 0.07 * traits.deathThroes.rank - 0.03 * traits.thoughtHarvester.rank - 0.055 * traits.spitefulApparitions.rank) * (1 - 0.27 * traits.thoughtHarvester.rank * traits.searingDialogue.rank)
local vt_mis_sd_check = 1 - 0.014 * traits.searingDialogue.rank
--Clear last cast table ooc to avoid strange casts
if not inCombat and #br.lastCast.tracker > 0 then
wipe(br.lastCast.tracker)
end
--------------------
--- Action Lists ---
--------------------
-- Action list - Extras
function actionList_Extra()
-- Dispel Magic
if isChecked("Dispel Magic") and canDispel("target",spell.dispelMagic) and not isBoss() and GetObjectExists("target") then
if cast.dispelMagic() then return end
end
-- Dummy Test
if isChecked("DPS Testing") then
if GetObjectExists("target") then
if getCombatTime() >= (tonumber(getOptionValue("DPS Testing"))*60) and isDummy() then
StopAttack()
ClearTarget()
Print(tonumber(getOptionValue("DPS Testing")) .." Minute Dummy Test Concluded - Profile Stopped")
profileStop = true
end
end
end -- End Dummy Test
end -- End Action List - Extra
-- Action List - Defensive
function actionList_Defensive()
if mode.defensive == 1 and getHP("player")>0 then
-- Pot/Stoned
if isChecked("Healthstone") and php <= getOptionValue("Healthstone")
and inCombat and (hasHealthPot() or hasItem(5512))
then
if canUseItem(5512) then
useItem(5512)
elseif canUseItem(healPot) then
useItem(healPot)
end
end
-- Gift of the Naaru
--[[if isChecked("Gift of the Naaru") and php <= getOptionValue("Gift of the Naaru") and php > 0 and br.player.race=="Draenei" then
if castSpell("player",racial,false,false,false) then return end
end--]]
-- Psychic Scream / Mind Bomb
if isChecked("Vampiric Embrace") and inCombat and php <= getOptionValue("Vampiric Embrace") then
if #enemies.yards40 > 0 then
if cast.vampiricEmbrace("player") then return end
end
end
--[[ Stoneform - Dwarf racial
if isChecked("Stoneform") and php <= getOptionValue("Stoneform") and php > 0 and br.player.race=="Dwarf" then
if castSpell("player",racial,false,false,false) then return end
end--]]
-- Dispersion
if isChecked("Dispersion") and php <= getOptionValue("Dispersion") then
if cast.dispersion("player") then return end
end
-- Fade
if isChecked("Fade") then
for i = 1, #enemies.yards40 do
local thisUnit = enemies.yards40[i]
if not solo and hasThreat(thisUnit) then
cast.fade("player")
end
end
end
-- Psychic Scream / Mind Bomb
if isChecked("Psychic Scream / Mind Bomb") and inCombat and php <= getOptionValue("Psychic Scream / Mind Bomb") then
if not talent.mindBomb and #enemies.yards8 > 0 then
if cast.psychicScream("player") then return end
else
if cast.mindBomb(units.dyn30) then return end
end
end
-- Psychic Horror
--if isChecked("Psychic Horror") and inCombat and php <= getOptionValue("Psychic Horror") then
-- if talent.psychichHorror and #enemies.yards8 > 0 then
-- if cast.psychicHorror(units.dyn30) then return end
-- end
-- Power Word: Shield
if isChecked("Power Word: Shield") and php <= getOptionValue("Power Word: Shield") and not buff.powerWordShield.exists() then
if cast.powerWordShield("player") then return end
end
-- Shadow Mend
if isChecked("Shadow Mend") and php <= getOptionValue("Shadow Mend") then
if cast.shadowMend("player") then return end
end
end -- End Defensive Check
end -- End Action List - Defensive
-- Action List - Interrupts
function actionList_Interrupts()
if useInterrupts() then
-- Silence
if isChecked("Silence") then
for i=1, #enemies.yards30 do
thisUnit = enemies.yards30[i]
if canInterrupt(thisUnit,getOptionValue("Interrupt At")) then
if cast.silence(thisUnit) then return end
end
end
end
-- Psychic Horror
if talent.psychicHorror and isChecked("Psychic Horror") and (cd.silence.exists() or not isChecked("Silence")) then
for i=1, #enemies.yards30 do
thisUnit = enemies.yards30[i]
if canInterrupt(thisUnit,getOptionValue("Interrupt At")) then
if cast.psychicHorror(thisUnit) then return end --Print("pH on any") return end
end
end
end
-- Psychic Scream
if isChecked("Psychic Scream") then
for i=1, #enemies.yards8 do
thisUnit = enemies.yards8[i]
if canInterrupt(thisUnit,getOptionValue("Interrupt At")) then
if cast.psychicScream("player") then return end
end
end
end
-- Mind Bomb
if talent.mindBomb and isChecked("Mind Bomb") then
for i=1, #enemies.yards30 do
thisUnit = enemies.yards30[i]
if canInterrupt(thisUnit,99) then
if cast.mindBomb(thisUnit) then return end
end
end
end
end
end -- End Action List - Interrupts
-- Action List - Cooldowns
function actionList_Cooldowns()
if useCDs() then
-- Touch of the Void
if isChecked("Touch of the Void") and getDistance("target") <= 40 then
if hasEquiped(128318) then
if GetItemCooldown(128318)==0 then
useItem(128318)
end
end
end
-- KJ Burning Wish
if isChecked("KJ Burning Wish") and getDistance("target") <= 40 then
if hasEquiped(144259) then
if GetItemCooldown(144259)==0 then
useItem(144259)
end
end
end
-- Tarnished Sentinel Medallion
if isChecked("Tarnished Sentinel Medallion") and getDistance("target") <= 40 then
if hasEquiped(147017) then
if GetItemCooldown(147017)==0 then
useItem(147017)
end
end
end
-- Wriggling Sinew
if isChecked("Wriggling Sinew") and getDistance("target") <= 40 then
if hasEquiped(139326) then
if GetItemCooldown(139326)==0 then
useItem(139326)
end
end
end
-- Pharameres Forbidden Grimoire
if isChecked("Pharameres Forbidden Grimoire") and getDistance("target") <= 40 then
if hasEquiped(140800) then
if GetItemCooldown(140800)==0 then
useItem(140800)
end
end
end
-- Mrrgias Favor
if isChecked("Mrrgias Favor") and getDistance("target") <= 40 then
if hasEquiped(142160) then
if GetItemCooldown(142160)==0 then
useItem(142160)
end
end
end
-- Moonlit Prism
if isChecked("Moonlit Prism") and getDistance("target") <= 40 and buff.voidForm.stack() >= getOptionValue(" Prism Stacks") then
if hasEquiped(137541) then
if GetItemCooldown(137541)==0 then
useItem(137541)
end
end
end
-- Tome of Unravelling Sanity
if isChecked("Tome of Unravelling Sanity") and getDistance("target") <= 40 and buff.voidForm.stack() >= getOptionValue(" Tome Stacks") then
if hasEquiped(147019) then
if GetItemCooldown(147019)==0 then
useItem(147019)
end
end
end
-- Charm of the Rising Tide
if isChecked("Charm of the Rising Tide") and getDistance("target") <= 40 and buff.voidForm.stack() >= getOptionValue(" Charm Stacks") then
if hasEquiped(147002) then
if GetItemCooldown(147002)==0 then
useItem(147002)
end
end
end
-- Obelisk of the Void
if isChecked("Obelisk of the Void") and getDistance("target") <= 40 and buff.voidForm.stack() >= getOptionValue(" Obelisk Stacks") then
if hasEquiped(137433) then
if GetItemCooldown(137433)==0 then
useItem(137433)
end
end
end
-- Horn of Valor
if isChecked("Horn of Valor") and getDistance("target") <= 40 and buff.voidForm.stack() >= getOptionValue(" Horn Stacks") then
if hasEquiped(133642) then
if GetItemCooldown(133642)==0 then
useItem(133642)
end
end
end
-- Skull of Guldan
if isChecked("Skull of Guldan") and getDistance("target") <= 40 and buff.voidForm.stack() >= getOptionValue(" Skull Stacks") then
if hasEquiped(150522) then
if GetItemCooldown(150522)==0 then
useItem(150522)
end
end
end
-- Figurehead of the Naglfar
if isChecked("Figurehead of the Naglfar") and getDistance("target") <= 40 and buff.voidForm.stack() >= getOptionValue(" Figurehead Stacks") then
if hasEquiped(137329) then
if GetItemCooldown(137329)==0 then
useItem(137329)
end
end
end
-- Azurethos' Singed Plumage
if isChecked("Azurethos' Singed Plumage") and getDistance("target") <= 40 and buff.voidForm.stack() >= getOptionValue(" Plumage Stacks") then
if hasEquiped(161377) then
if GetItemCooldown(161377)==0 then
useItem(161377)
end
end
end
-- T'zane's Barkspines
if isChecked("T'zane's Barkspines") and getDistance("target") <= 40 and buff.voidForm.exists() then
if hasEquiped(161411) then
if GetItemCooldown(161411)==0 then
useItem(161411)
end
end
end
-- Trinkets
--if isChecked("Trinkets") then
-- if canUseItem(11) then
-- useItem(11)
-- end
-- if canUseItem(12) then
-- useItem(12)
-- end
-- if canUseItem(13) then
-- useItem(13)
-- end
-- if canUseItem(14) then
-- useItem(14)
-- end
--end
if isChecked("Trinket 1") and canUseItem(13) then
useItem(13)
return true
end
if isChecked("Trinket 2") and canUseItem(14) then
useItem(14)
return true
end
-- Potion
-- potion,name=prolonged_power,if=buff.bloodlust.react|target.time_to_die<=80|(target.health.pct<35&cooldown.power_infusion.remains<30)
-- TODO
end
end -- End Action List - Cooldowns
-- Action List - Pre-Combat
function actionList_PreCombat()
-- Shadow Form
-- shadowform,if=!buff.shadowform.up
if not buff.shadowform.exists() then
cast.shadowform()
end
-- comment out Fort so you are not over casting other priests in raids. if you uncomment it will keep applying so its your fort up. easier to just manual cast i think.
-- Power Word: Fortitude
--if not buff.powerWordFortitude.exists() then
-- cast.powerWordFortitude()
--end
if isChecked("Power Word: Fortitude") and br.timer:useTimer("PW:F Delay", mrdm(3,5)) then
for i = 1, #br.friend do
if not buff.powerWordFortitude.exists(br.friend[i].unit,"any") and getDistance("player", br.friend[i].unit) < 40 and not UnitIsDeadOrGhost(br.friend[i].unit) and UnitIsPlayer(br.friend[i].unit) then
if cast.powerWordFortitude() then return end
end
end
end
-- Flask/Elixir
-- flask,type=flask_of_the_whispered_pact
-- Endless Fathoms Flask
if getOptionValue("Elixir") == 1 and inRaid and not buff.flaskOfEndlessFathoms.exists() and canUseItem(item.flaskOfEndlessFathoms) then
if buff.whispersOfInsanity.exists() then buff.whispersOfInsanity.cancel() end
if buff.felFocus.exists() then buff.felFocus.cancel() end
if use.flaskOfEndlessFathoms() then return end
end
if getOptionValue("Elixir") == 2 and not buff.felFocus.exists() and canUseItem(item.repurposedFelFocuser) then
if buff.flaskOfTheWhisperedPact.exists() then buff.flaskOfTheWhisperedPact.cancel() end
if buff.whispersOfInsanity.exists() then buff.whispersOfInsanity.cancel() end
if use.repurposedFelFocuser() then return end
end
if getOptionValue("Elixir") == 3 and not buff.whispersOfInsanity.exists() and canUseItem(item.oraliusWhisperingCrystal) then
if buff.flaskOfTheWhisperedPact.exists() then buff.flaskOfTheWhisperedPact.cancel() end
if buff.felFocus.exists() then buff.felFocus.cancel() end
if use.oraliusWhisperingCrystal() then return end
end
-- Mind Blast
if isChecked("Pull OoC") and isValidUnit("target") then
if activeEnemies == 1 or mode.rotation == 3 then
if not moving then
if not talent.shadowWordVoid and br.timer:useTimer("mbRecast", gcdMax + getSpellCD(spell.mindBlast)) then
if UnitExists("target") and UnitGUID("target") ~= pmbLast then
if cast.mindBlast("target") then pmbLast = UnitGUID("target")
--Print("OoC MB")
return end
end
elseif talent.shadowWordVoid and charges.shadowWordVoid.count() > 1 and br.timer:useTimer("swvRecast", gcdMax + getSpellCD(spell.mindBlast)) then
if UnitExists("target") and UnitGUID("target") ~= pswvLast then
if cast.shadowWordVoid("target") then pswvLast = UnitGUID("target")
--Print("OoC swv")
return end
end
end
elseif moving then
if not debuff.shadowWordPain.exists() then
if cast.shadowWordPain("target") then
--Print("OoC SWP")
return end
end
end
elseif activeEnemies > 1 or mode.rotation == 2 then
if not moving then
if not debuff.vampiricTouch.exists() and not cast.current.vampiricTouch() and br.timer:useTimer("vtRecast", gcdMax + getSpellCD(spell.vampiricTouch)) then
if UnitExists("target") and UnitGUID("target") ~= pvtLast then
if cast.vampiricTouch("target") then pvtLast = UnitGUID("target")
--Print("OoC VT")
return end
end
end
elseif moving then
if not debuff.shadowWordPain.exists() then
if cast.shadowWordPain("target") then
--Print("OoC SWP")
return end
end
end
end
end
--[[ Power Word: Shield Body and Soul
-- if isChecked("PWS: Body and Soul") and talent.bodyAndSoul and isMoving("player") and buff.powerWordShield.remain() <= 8.5 and not buff.classHallSpeed.exists() then
-- if cast.powerWordShield("player") then return end
-- end
if IsMovingTime(mrdm(60,120)/100) then
if bnSTimer == nil then bnSTimer = GetTime() - 6 end
if isChecked("PWS: Body and Soul") and talent.bodyAndSoul and buff.powerWordShield.remain("player") <= mrdm(6,8) and GetTime() >= bnSTimer + 6 then
if cast.powerWordShield("player") then
bnSTimer = GetTime() return end
end
end--]]
end -- End Action List - Pre-Combat
-- Action List - Cleave
function actionList_Cleave()
--Mouseover Dotting
if isChecked("Mouseover Dotting") and hasMouse and (UnitIsEnemy("player","mouseover") or isDummy("mouseover")) and not moving then
if getDebuffRemain("mouseover",spell.vampiricTouch,"player") <= 6.3 then
if cast.vampiricTouch("mouseover") then
return
end
end
end
if isChecked("Mouseover Dotting") and hasMouse and (UnitIsEnemy("player","mouseover") or isDummy("mouseover")) then
if getDebuffRemain("mouseover",spell.shadowWordPain,"player") <= 4.8 then
if cast.shadowWordPain("mouseover") then
return
end
end
end
--Void Eruption
-- void_eruption
if mode.voidForm == 1 and cast.able.voidEruption() and not moving then
if talent.darkVoid and cd.darkVoid.remain() ~= 30 then
if cast.voidEruption(units.dyn40) then return end
elseif not talent.darkVoid then
if cast.voidEruption(units.dyn40) then return end
end
end
--Dark Ascension
if isChecked("Dark Ascension") and not isChecked("Dark Ascension AoE") and useCDs() then
if power <= 60 and not buff.voidForm.exists() then
if cast.darkAscension(units.dyn40) then
--Print("Cleave DA no VF")
return end
end
end
--Dark Ascension
--if power <= getOptionValue(" Insanity Percentage") and buff.voidForm.exists() then
if isChecked("Dark Ascension Burst") and useCDs() then --and #searEnemies < mindblastTargets then
if insanityDrain * gcdMax > power and buff.voidForm.exists() or not isChecked("Dark Ascension AoE") and #dAEnemies < getOptionValue("Dark Ascension AoE") and not buff.voidForm.exists() then
if cast.darkAscension(units.dyn40) then
--Print("Cleave DA Burst VF")
return end
end
end
-- Vampiric Touch + Thought Harvester
if traits.thoughtHarvester.active and traits.thoughtHarvester.rank >= 1 and not debuff.vampiricTouch.exists(units.dyn40) and not cast.current.vampiricTouch() then
if UnitExists(units.dyn40) and UnitGUID(units.dyn40) ~= cvtLast or not cast.last.vampiricTouch() then
if cast.vampiricTouch(units.dyn40) then cvtLast = UnitGUID(units.dyn40) return end
end
end
-- Mind Sear
--mind_sear,if=buff.harvested_thoughts.up
if traits.thoughtHarvester.active and buff.harvestedThoughts.exists() and not cast.current.mindSear() then
if cast.mindSear() then
--Print("Cleave TH MS")
return end
end
--Void Bolt
if buff.voidForm.exists() and cast.able.voidBolt() then
if cast.voidBolt(units.dyn40) then return end
end
--Lucid Dreams
--memory_of_lucid_dreams,if=buff.voidform.stack>(20+5*buff.bloodlust.up)&insanity<=50
if lucisDreams and isChecked("Lucid Dreams") and cast.able.memoryOfLucidDreams() and buff.voidForm.exists() and useCDs() then
if hasBloodLust() and buff.voidForm.stack() > (getOptionValue(" Lucid Dreams VF Stacks") + 5 + 5 * lusting) then
if cast.memoryOfLucidDreams("player") then --[[Print("Lucid")--]] return end
elseif buff.voidForm.stack() > getOptionValue(" Lucid Dreams VF Stacks") or power <= getOptionValue(" Lucid Dreams Insanity") or insanityDrained > power then
if cast.memoryOfLucidDreams("player") then --[[Print("Lucid")--]] return end
end
end
--Shadow Word: Death
-- shadow_word_death,target_if=target.time_to_die<3|buff.voidform.down
if talent.shadowWordDeath and thp < 20 then
if ttd(units.dyn40) < 3 or not buff.voidForm.exists() then
if cast.shadowWordDeath(units.dyn40) then return end
end
end
--Surrender To Madness
-- surrender_to_madness,if=buff.voidform.stack>10+(10*buff.bloodlust.up)
if isChecked("Surrender To Madness") and useCDs() then
if talent.surrenderToMadness and buff.voidForm.stack() > 10 + (10 * lusting) then
if cast.surrenderToMadness() then return end
end
end
-- Dark Void
-- dark_void,if=raid_event.adds.in>10&(dot.shadow_word_pain.refreshable|target.time_to_die>30)
if not buff.voidForm.exists() and not moving then
if talent.darkVoid and #dVEnemies >= getOptionValue("Dark Void Targets") and (debuff.shadowWordPain.refresh(units.dyn40) or ttd(units.dyn40) > 30) then
if cast.darkVoid(units.dyn40) then
--Print("Cleave DV AoE")
return end
end
end
--Dark Ascension AoE
if isChecked("Dark Ascension AoE") and not buff.voidForm.exists() then
if #dAEnemies >= getOptionValue("Dark Ascension AoE") or (talent.darkVoid and cd.darkVoid.remain() ~= 30) then --or debuff.shadowWordPain.count() >= 3 then --math.min(getOptionValue("SWP Max Targets"),getOptionValue("Dark Ascension AoE")) then
if cast.darkAscension(units.dyn40) then
--Print("Cleave DA AoE")
return end
end
end
--Shadowfiend / Mindbender
-- mindbender,if=talent.mindbender.enabled|(buff.voidform.stack>18|target.time_to_die<15)
if isChecked("Shadowfiend / Mindbender") and talent.mindbender and useCDs() then
if isChecked(" Mindbender in VF") and getOptionValue(" Mindbender in VF") > 0 then
if buff.voidForm.stack() >= getOptionValue(" Mindbender in VF") then
if cast.mindbender() then return end --Print("SFMB VF Stack") return end
end
elseif not isChecked(" Mindbender in VF") and useCDs() then
if not buff.voidForm.exists() or buff.voidForm.stack() >= 1 then
if cast.mindbender() then return end --Print("SFMB CD") return end
end
end
end
if isChecked("Shadowfiend / Mindbender") and not talent.mindbender and useCDs() and dotsUp then
if isChecked(" Mindbender in VF") and getOptionValue(" Mindbender in VF") > 0 then
if buff.voidForm.stack() >= getOptionValue(" Mindbender in VF") then
if cast.shadowfiend() then return end --Print("SF CD") return end
end
elseif not isChecked(" Mindbender in VF") and ttd("target") < 15 and useCDs() then
if cast.shadowfiend() then return end --Print("SF CD") return end
end
end
--Mind Blast
-- mind_blast,target_if=spell_targets.mind_sear<variable.mind_blast_targets
if buff.voidForm.exists() and #searEnemies < mindblastTargets and cd.voidBolt.remain() >= mrdm(0.9,1.02) and noTH and not moving then
if not talent.shadowWordVoid then
if UnitExists(units.dyn40) and UnitGUID(units.dyn40) ~= cmbLast or not cast.last.mindBlast() then
if cast.mindBlast(units.dyn40) then cmbLast = UnitGUID(units.dyn40)
--if cast.mindBlast(units.dyn40) then
--Print("Cleave MB VF")
--Print(mindblastTargets)
return end
end
elseif talent.shadowWordVoid and charges.shadowWordVoid.frac() >= 1.01 then
if UnitExists(units.dyn40) and UnitGUID(units.dyn40) ~= cswvLast or not cast.last.shadowWordVoid() then
if cast.shadowWordVoid(units.dyn40) then cswvLast = UnitGUID(units.dyn40)
--Print("CLeave swv VF")
--Print(mindblastTargets)
return end
end
end
end
--Shadow Crash
-- shadow_crash,if=raid_event.adds.in>5&raid_event.adds.duration<20
if isChecked("Shadow Crash") and talent.shadowCrash and not isMoving("target") then
if cast.shadowCrash("best",nil,1,8) then return end
end
--Shadow Word: Pain - on dyn40 target and extra targets with no Misery
-- shadow_word_pain,target_if=refreshable&target.time_to_die>((-1.2+3.3*spell_targets.mind_sear)*variable.swp_trait_ranks_check*(1-0.012*azerite.searing_dialogue.rank*spell_targets.mind_sear)),if=!talent.misery.enabled
if not talent.misery and noHarvest and SWPb4VT then
if debuff.shadowWordPain.remain(units.dyn40) < 4.8 and ttd(units.dyn40) > ((-1.2 + 3.3 * #searEnemies) * swp_trait_ranks_check * (1 - 0.012 * traits.searingDialogue.rank * #searEnemies)) then
if UnitExists(units.dyn40) and UnitGUID(units.dyn40) ~= cswpb4vtLast or not cast.last.shadowWordPain() then
if cast.shadowWordPain(units.dyn40) then cswpb4vtLast = UnitGUID(units.dyn40)
--Print("cast Cleave SWPb4VT on dyn40")
return end
end
end
if debuff.shadowWordPain.remainCount(3) < SWPmaxTargets and SWPb4VT then
for i = 1, #enemies.yards40 do
local thisUnit = enemies.yards40[i]
if debuff.shadowWordPain.remain(thisUnit) < 3 and ttd(thisUnit) > ((-1.2 + 3.3 * #searEnemies) * swp_trait_ranks_check * (1 - 0.012 * traits.searingDialogue.rank * #searEnemies)) then
if UnitExists(units.dyn40) and UnitGUID(units.dyn40) ~= cswpb4vtLast or not cast.last.shadowWordPain() then
if cast.shadowWordPain(thisUnit) then
--Print("cast Cleave SWPb4VT on adds")
return end
end
end
end
end
end
--Vampiric Touch - on dyn40 target and extra targets with no Misery
-- vampiric_touch,target_if=refreshable,if=target.time_to_die>((1+3.3*spell_targets.mind_sear)*variable.vt_trait_ranks_check*(1+0.10*azerite.searing_dialogue.rank*spell_targets.mind_sear))
if not talent.misery and not moving and not cast.current.vampiricTouch() and noTH then
if debuff.vampiricTouch.remain(units.dyn40) < 6.3 and ttd(units.dyn40) > ((1 + 3.3 * #searEnemies) * vt_trait_ranks_check * (1 + 0.10 * traits.searingDialogue.rank * #searEnemies)) then
if UnitExists(units.dyn40) and UnitGUID(units.dyn40) ~= cvtLast or not cast.last.vampiricTouch() then
if cast.vampiricTouch(units.dyn40) then cvtLast = UnitGUID(units.dyn40)
-- Print("cast Cleave VT on dyn40")
return end
end
end
if debuff.vampiricTouch.remainCount(4) < VTmaxTargets then
for i = 1, #enemies.yards40 do
local thisUnit = enemies.yards40[i]
if debuff.vampiricTouch.remain(thisUnit) < 4 and ttd(thisUnit) > ((1 + 3.3 * #searEnemies) * vt_trait_ranks_check * (1 + 0.10 * traits.searingDialogue.rank * #searEnemies)) then
if UnitExists(thisUnit) and UnitGUID(thisUnit) ~= cvtaLast or not cast.last.vampiricTouch() then
if cast.vampiricTouch(thisUnit) then cvtaLast = UnitGUID(thisUnit)
-- Print("cast Cleave VT on adds")
return end
end
end
end
end
end
-- Vampiric Touch - on dyn target and extra targets with Misery
-- vampiric_touch,target_if=dot.shadow_word_pain.refreshable,if=(talent.misery.enabled&target.time_to_die>((1.0+2.0*spell_targets.mind_sear)*variable.vt_mis_trait_ranks_check*(variable.vt_mis_sd_check*spell_targets.mind_sear)))
if talent.misery and not moving and not cast.current.vampiricTouch() and noTH then
if debuff.shadowWordPain.remain(units.dyn40) < 4.8 or not debuff.vampiricTouch.exists() and ttd(units.dyn40) > ((1.0 + 2.0 * #searEnemies) * vt_mis_trait_ranks_check * (vt_mis_sd_check * #searEnemies)) then
if UnitExists(units.dyn40) and UnitGUID(units.dyn40) ~= cmvtLast or not cast.last.vampiricTouch() then
if cast.vampiricTouch(units.dyn40) then cmvtLast = UnitGUID(units.dyn40)
--Print("cast Cleave Mis VT on dyn40")
return end
end
end
--[[if debuff.shadowWordPain.count() < VTmaxTargets then
for i = 1, #enemies.yards40 do
local thisUnit = enemies.yards40[i]
if not debuff.shadowWordPain.exists(thisUnit) and ttd(thisUnit) > ((1.0 + 2.0 * #searEnemies) * vt_mis_trait_ranks_check * (vt_mis_sd_check * #searEnemies)) then --and not cast.last.vampiricTouch(1) then
if UnitExists(thisUnit) and UnitGUID(thisUnit) ~= cmvtaLast or not cast.last.vampiricTouch() then
if cast.vampiricTouch(thisUnit) then cmvtaLast = UnitGUID(thisUnit)
Print("cast Cleave Mis VT on adds")
return end
end
end
end
end--]]
if debuff.shadowWordPain.remainCount(4) < VTmaxTargets then
for i = 1, #enemies.yards40 do
local thisUnit = enemies.yards40[i]
if debuff.shadowWordPain.remain(thisUnit) < 4 or not debuff.vampiricTouch.exists() and ttd(thisUnit) > ((1.0 + 2.0 * #searEnemies) * vt_mis_trait_ranks_check * (vt_mis_sd_check * #searEnemies)) then
if UnitExists(thisUnit) and UnitGUID(thisUnit) ~= cmvtaLast or not cast.last.vampiricTouch() then
if cast.vampiricTouch(thisUnit) then cmvtaLast = UnitGUID(thisUnit)
--Print("rfrsh Cleave Mis VT on adds")
return end
end
end
end
end
end
--Shadow Word: Pain - on dyn40 target and extra targets with no Misery
-- shadow_word_pain,target_if=refreshable&target.time_to_die>((-1.2+3.3*spell_targets.mind_sear)*variable.swp_trait_ranks_check*(1-0.012*azerite.searing_dialogue.rank*spell_targets.mind_sear)),if=!talent.misery.enabled
if not talent.misery and noTH then
if debuff.shadowWordPain.remain(units.dyn40) < 4.8 and ttd(units.dyn40) > ((-1.2 + 3.3 * #searEnemies) * swp_trait_ranks_check * (1 - 0.012 * traits.searingDialogue.rank * #searEnemies)) then
if cast.shadowWordPain(units.dyn40) then
--Print("cast Cleave SWP on dyn40")
return end
end
if debuff.shadowWordPain.remainCount(3) < SWPmaxTargets then
for i = 1, #enemies.yards40 do
local thisUnit = enemies.yards40[i]
if debuff.shadowWordPain.remain(thisUnit) < 3 and ttd(thisUnit) > ((-1.2 + 3.3 * #searEnemies) * swp_trait_ranks_check * (1 - 0.012 * traits.searingDialogue.rank * #searEnemies)) then
if cast.shadowWordPain(thisUnit) then
--Print("cast Cleave SWP on adds")
return end
end
end
end
end
--Mind Blast
-- mind_blast,target_if=spell_targets.mind_sear<variable.mind_blast_targets
if not buff.voidForm.exists() and #searEnemies < mindblastTargets and noTH and not moving then
if not talent.shadowWordVoid then
if UnitExists(units.dyn40) and UnitGUID(units.dyn40) ~= cmbLast or not cast.last.mindBlast() then
if cast.mindBlast(units.dyn40) then cmbLast = UnitGUID(units.dyn40)
--Print("Cleave MB no VF")
return end
end
elseif talent.shadowWordVoid and charges.shadowWordVoid.frac() >= 1.01 then
if UnitExists(units.dyn40) and UnitGUID(units.dyn40) ~= cswvLast or not cast.last.shadowWordVoid() then
if cast.shadowWordVoid(units.dyn40) then cswvLast = UnitGUID(units.dyn40)
--Print("CLeave swv no VF")
return end
end
end
end
-- Void Torrent
-- void_torrent,if=buff.voidform.up
if isChecked("Void Torrent") and talent.voidTorrent and useCDs() and buff.voidForm.exists() and noTH then
if cast.voidTorrent() then return end
end
--Mind Sear
-- mind_sear,target_if=spell_targets.mind_sear>1,chain=1,interrupt_immediate=1,interrupt_if=ticks>=2
if #searEnemies >= getOptionValue("Mind Sear Targets") and buff.voidForm.exists() and noTH then
if not moving and not cast.current.mindSear() then
if cast.mindSear() then
--Print("Cleave VF MS")
return end
end
elseif #searEnemies >= getOptionValue("Mind Sear Targets") and not buff.voidForm.exists() and noTH then
if not moving and not cast.current.mindSear() or (cast.active.mindSear() and mindSearRecast) then
if cast.mindSear() then
--Print("Cleave MS")
return end
end
end
--Mind Flay
-- mind_flay,chain=1,interrupt_immediate=1,interrupt_if=ticks>=2&(cooldown.void_bolt.up|cooldown.mind_blast.up)
if #searEnemies < getOptionValue("Mind Sear Targets") and not buff.voidForm.exists() and noTH then
if not moving and not cast.current.mindFlay() and (cd.mindBlast.remain() > 0.5 or talent.shadowWordVoid and cd.shadowWordVoid.remain() < 4.2) or (cast.active.mindFlay() and mindFlayRecast) then
if cast.mindFlay() then
--Print("refresh Cleave mf")
return end
end
elseif #searEnemies < getOptionValue("Mind Sear Targets") and buff.voidForm.exists() and noTH then
if not moving and not cast.current.mindFlay() and cd.voidBolt.remain() < 3.4 then --or cd.mindBlast.remain() < 4.2 * gHaste) then
if cast.mindFlay() then
--Print("refresh Cleave VF mf")
return end
end
end
--Shaow Word: Pain
-- shadow_word_pain
if moving then
for i = 1, #enemies.yards40 do
local thisUnit = enemies.yards40[i]
if not debuff.shadowWordPain.exists(thisUnit) then
if cast.shadowWordPain(thisUnit) then
--Print("cast SWP last resort")
return end
end
end
end
end
-- Action List - Single
function actionList_Single()
--Mouseover Dotting
if isChecked("Mouseover Dotting") and hasMouse and (UnitIsEnemy("player","mouseover") or isDummy("mouseover")) and not moving then
if getDebuffRemain("mouseover",spell.vampiricTouch,"player") <= 6.3 then
if cast.vampiricTouch("mouseover") then
return
end
end
end
if isChecked("Mouseover Dotting") and hasMouse and (UnitIsEnemy("player","mouseover") or isDummy("mouseover")) then
if getDebuffRemain("mouseover",spell.shadowWordPain,"player") <= 4.8 then
if cast.shadowWordPain("mouseover") then
return
end
end
end
--Void Eruption
-- void_eruption
if cast.current.mindFlay() and not buff.voidForm.exists() and (power >= 90 or talent.legacyOfTheVoid and power >= 60) then
RunMacroText('/stopcasting')
--Print("stop for VE2")
return true end
--end
if mode.voidForm == 1 and cast.able.voidEruption() and not moving then
if cast.voidEruption() then return end
end
--Dark Ascension
if isChecked("Dark Ascension") and dotsUp and useCDs() then
if power <= 60 and not buff.voidForm.exists() then
if cast.darkAscension(units.dyn40) then
--Print("no VF")
return end
end
end
--Dark Ascension
--if power <= getOptionValue(" Insanity Percentage") and buff.voidForm.exists() then
if isChecked("Dark Ascension Burst") and useCDs() then
if insanityDrain * gcdMax > power and buff.voidForm.exists() then
if cast.darkAscension(units.dyn40) then
--Print("VF")
return end
end
end
--Void Bolt
if buff.voidForm.exists() and cast.able.voidBolt() then
if cast.voidBolt(units.dyn40) then return end
end
--Lucid Dreams
--memory_of_lucid_dreams,if=buff.voidform.stack>(20+5*buff.bloodlust.up)&insanity<=50
if lucisDreams and isChecked("Lucid Dreams") and cast.able.memoryOfLucidDreams() and buff.voidForm.exists() and useCDs() then
if hasBloodLust() and buff.voidForm.stack() > (getOptionValue(" Lucid Dreams VF Stacks") + 5 + 5 * lusting) then
if cast.memoryOfLucidDreams("player") then --[[Print("Lucid")--]] return end
elseif buff.voidForm.stack() > getOptionValue(" Lucid Dreams VF Stacks") or power <= getOptionValue(" Lucid Dreams Insanity") or insanityDrained > power then
if cast.memoryOfLucidDreams("player") then --[[Print("Lucid")--]] return end
end
end
--Mind Sear
--mind_sear,if=buff.harvested_thoughts.up&cooldown.void_bolt.remains>=1.5&azerite.searing_dialogue.rank>=1
if traits.searingDialogue.active and traits.thoughtHarvester.active and buff.voidForm.exists() then
if buff.harvestedThoughts.exists() and cd.voidBolt.remain() >= 1.5 and traits.searingDialogue.rank >= 1 and not cast.current.mindSear() then
if cast.mindSear() then
--Print("MS TH ST")
return end
end
end
--Shadow Word: Death
-- shadow_word_death,if=target.time_to_die<3|cooldown.shadow_word_death.charges=2|(cooldown.shadow_word_death.charges=1&cooldown.shadow_word_death.remains<gcd.max)
if talent.shadowWordDeath and thp < 20 then
if ttd("target") < 3 or charges.shadowWordDeath.count() == 2 or (charges.shadowWordDeath.count() == 1 and cd.shadowWordDeath.remain() < gcdMax) then
if cast.shadowWordDeath(units.dyn40) then return end
end
end
--Surrender To Madness
-- surrender_to_madness,if=buff.voidform.stack>10+(10*buff.bloodlust.up)
if isChecked("Surrender To Madness") and useCDs() then
if talent.surrenderToMadness and buff.voidForm.stack() > 10 + (10 * lusting) then
if cast.surrenderToMadness() then return end
end
end
--Shadowfiend / Mindbender
-- mindbender,if=talent.mindbender.enabled|(buff.voidform.stack>18|target.time_to_die<15)
if isChecked("Shadowfiend / Mindbender") and talent.mindbender and useCDs() then
if isChecked(" Mindbender in VF") and getOptionValue(" Mindbender in VF") > 0 then
if buff.voidForm.stack() >= getOptionValue(" Mindbender in VF") then
if cast.mindbender() then return end --Print("SFMB VF Stack") return end
end
elseif not isChecked(" Mindbender in VF") and useCDs() then
if not buff.voidForm.exists() or buff.voidForm.stack() >= 1 then
if cast.mindbender() then return end --Print("SFMB CD") return end
end
end
end
if isChecked("Shadowfiend / Mindbender") and not talent.mindbender and useCDs() and dotsUp then
if isChecked(" Mindbender in VF") and getOptionValue(" Mindbender in VF") > 0 then
if buff.voidForm.stack() >= getOptionValue(" Mindbender in VF") then
if cast.shadowfiend() then return end --Print("SF CD") return end
end
elseif not isChecked(" Mindbender in VF") and ttd("target") < 15 and useCDs() then
if cast.shadowfiend() then return end --Print("SF CD") return end
end
end
--Shadow Word: Death
-- shadow_word_death,if=!buff.voidform.up|(cooldown.shadow_word_death.charges=2&buff.voidform.stack<15)
if talent.shadowWordDeath and thp < 20 then
if not buff.voidForm.exists() or (charges.shadowWordDeath.count() == 2 and buff.voidForm.stack() < 15) then
if cast.shadowWordDeath(units.dyn40) then return end
end
end
--Shadow Crash
-- shadow_crash,if=raid_event.adds.in>5&raid_event.adds.duration<20
if isChecked("Shadow Crash") and talent.shadowCrash and not isMoving("target") then
if cast.shadowCrash("best",nil,1,8) then return end
end
--Mind Blast
-- mind_blast,if=variable.dots_up&((!talent.shadow_word_void.enabled|buff.voidform.down|buff.voidform.stack>14&(insanity<70|charges_fractional>1.33)|buff.voidform.stack<=14&(insanity<60|charges_fractional>1.33))
if buff.voidForm.exists() and dotsUp and noTH and cd.voidBolt.remain() >= mrdm(0.93,1.02) or ((buff.voidForm.stack() > 14 and power < 75) or (buff.voidForm.stack() <= 14 and power < 64)) and not moving then
if not talent.shadowWordVoid then
if UnitExists("target") and UnitGUID("target") ~= mbLast or not cast.last.mindBlast() then
if cast.mindBlast("target") then mbLast = UnitGUID("target")
--Print("mb VF")
return end
end
elseif talent.shadowWordVoid and charges.shadowWordVoid.frac() >= 1.02 then
if UnitExists("target") and UnitGUID("target") ~= swvLast or not cast.last.shadowWordVoid() then
if cast.shadowWordVoid("target") then swvLast = UnitGUID("target")
--Print("swv VF")
return end
end
end
--[[elseif talent.shadowWordVoid then
if (buff.voidForm.stack() > 14 and (power < 70 or charges.shadowWordVoid.frac() >= 1.03)) or (buff.voidForm.stack() <= 14 and (power < 60 or charges.shadowWordVoid.frac() >= 1.03)) then
if UnitExists("target") and UnitGUID("target") ~= swvLast or not cast.last.shadowWordVoid() then
if cast.shadowWordVoid("target") then swvLast = UnitGUID("target")
--Print("swv VF")
return end
end
end
end--]]
--[[if UnitExists("target") and UnitGUID("target") ~= mbLast or not cast.last.mindBlast() then
if cast.mindBlast("target") then mbLast = UnitGUID("target")
--Print("mb no lotv")
return end
end--]]
end
--Void Torrent
-- void_torrent,if=dot.shadow_word_pain.remains>4&dot.vampiric_touch.remains>4&buff.voidform.up
if isChecked("Void Torrent") and talent.voidTorrent and useCDs() and dotsTick and buff.voidForm.exists() then
if cast.voidTorrent(units.dyn40) then return end
end
--Shadow Word: Pain -- cast on target and refresh if expiring soon
-- shadow_word_pain,if=refreshable&target.time_to_die>4&!talent.misery.enabled&!talent.dark_void.enabled
if not talent.misery and buff.voidForm.exists() and noTH and SWPb4VT then
if debuff.shadowWordPain.remain("target") < 2.4 then
if UnitExists(units.dyn40) and UnitGUID(units.dyn40) ~= swpb4vtLast or not cast.last.shadowWordPain() then
if cast.shadowWordPain(units.dyn40) then swpb4vtLast = UnitGUID(units.dyn40)
--Print("cast VF SWPb4VT on target not misery")
return end
end
end
elseif not talent.misery and not buff.voidForm.exists() and SWPb4VT then
if debuff.shadowWordPain.remain("target") < 4.8 and ttd("target") > 4 then
if UnitExists(units.dyn40) and UnitGUID(units.dyn40) ~= swpb4vtLast or not cast.last.shadowWordPain() then
if cast.shadowWordPain(units.dyn40) then swpb4vtLast = UnitGUID(units.dyn40)
--Print("cast SWPb4VT on target not misery")
return end
end
end
end
--Vampiric Touch -- cast target and refresh if expiring soon
-- vampiric_touch,if=refreshable&target.time_to_die>6|(talent.misery.enabled&dot.shadow_word_pain.refreshable)
if not talent.misery and buff.voidForm.exists() and noTH then
if debuff.vampiricTouch.remain("target") < 3.1 and ttd("target") > 6 and not moving and not cast.current.vampiricTouch() then
if UnitExists("target") and UnitGUID("target") ~= vtLast or not cast.last.vampiricTouch() then
if cast.vampiricTouch("target") then vtLast = UnitGUID("target")
--Print("cast VF VT on target")
return end
end
end
elseif not talent.misery and not buff.voidForm.exists() then
if debuff.vampiricTouch.remain("target") < 6.3 and ttd("target") > 6 and not moving and not cast.current.vampiricTouch() then
if UnitExists("target") and UnitGUID("target") ~= vtLast or not cast.last.vampiricTouch() then
if cast.vampiricTouch("target") then vtLast = UnitGUID("target")
--Print("cast VT on target")
return end
end
end
end
if talent.misery and buff.voidForm.exists() and noTH then
if debuff.shadowWordPain.remain("target") < 2.4 or not debuff.vampiricTouch.exists() and not moving and not cast.current.vampiricTouch() then
if UnitExists("target") and UnitGUID("target") ~= mvtLast or not cast.last.vampiricTouch() then
if cast.vampiricTouch("target") then mvtLast = UnitGUID("target")
--if cast.vampiricTouch(units.dyn40) then
--Print("cast VF VT / Mis VT on target")
return end
end
end
elseif talent.misery and not buff.voidForm.exists() then
if debuff.shadowWordPain.remain("target") < 4.8 or not debuff.vampiricTouch.exists() and not moving and not cast.current.vampiricTouch() then
if UnitExists("target") and UnitGUID("target") ~= mvtLast or not cast.last.vampiricTouch() then
if cast.vampiricTouch("target") then mvtLast = UnitGUID("target")
--Print("cast Mis VT on target")
return end
end
end
end
--Shadow Word: Pain -- cast on target and refresh if expiring soon
-- shadow_word_pain,if=refreshable&target.time_to_die>4&!talent.misery.enabled&!talent.dark_void.enabled
if not talent.misery and buff.voidForm.exists() and noTH then
if debuff.shadowWordPain.remain("target") < 2.4 then
if cast.shadowWordPain(units.dyn40) then
--Print("cast VF SWP on target not misery")
return end
end
elseif not talent.misery and not buff.voidForm.exists() then
if debuff.shadowWordPain.remain("target") < 4.8 and ttd("target") > 4 then
if cast.shadowWordPain(units.dyn40) then
--Print("cast SWP on target not misery")
return end
end
end
--Mind Blast
-- mind_blast,if=variable.dots_up
if not buff.voidForm.exists() and dotsUp --[[and debuff.vampiricTouch.remain(units.dyn40) > 9.3 * gHaste and not cast.current.mindBlast() then --]] and not moving then
if not talent.shadowWordVoid then
if UnitExists("target") and UnitGUID("target") ~= mbLast or not cast.last.mindBlast() then
if cast.mindBlast("target") then mbLast = UnitGUID("target")
--Print("mb no VF")
return end
end
elseif talent.shadowWordVoid and charges.shadowWordVoid.frac() >= 1.01 then
if UnitExists("target") and UnitGUID("target") ~= swvLast or not cast.last.shadowWordVoid() then
if cast.shadowWordVoid("target") then swvLast = UnitGUID("target")
--Print("swv no VF")
return end
end
end
end
--[[Mind Sear
-- mind_sear,if=azerite.searing_dialogue.rank>=3,chain=1,interrupt_immediate=1,interrupt_if=ticks>=2
if traits.searingDialogue.active and not buff.voidForm.exists() then
if not moving and traits.searingDialogue.rank >= 3 and not cast.current.mindSear() or (cast.active.mindSear() and mindSearRecast) then
if cast.mindSear() then
return end
end
elseif traits.searingDialogue.active and buff.voidForm.exists() and noTH then
if not moving and traits.searingDialogue.rank >= 3 and not cast.current.mindSear() then
if cast.mindSear() then
return end
end
end--]]
--Mind Flay
-- mind_flay,chain=1,interrupt_immediate=1,interrupt_if=ticks>=2&(cooldown.void_bolt.up|cooldown.mind_blast.up)
if activeEnemies == 1 and not buff.voidForm.exists() then --and --[[and not cast.able.voidEruption()--]] (power < 90 or talent.legacyOfTheVoid and power < 60) then --or mode.voidForm == 2 then--]]
--if cast.active.mindFlay() and cast.able.voidEruption() then
--RunMacroText('/stopcasting')
-- Print("stop for VE2")
-- return true end
if not moving and (not cast.able.voidEruption() or mode.voidForm == 2) and not cast.current.mindFlay() and (cd.mindBlast.remain() > 0.5 or talent.shadowWordVoid and cd.shadowWordVoid.remain() < 4.2) or (cast.active.mindFlay() and mindFlayRecast) then
if cast.mindFlay() then
--Print("refresh mf")
return end
end
elseif activeEnemies == 1 and buff.voidForm.exists() and noTH then
if not moving and not cast.current.mindFlay() and cd.voidBolt.remain() < 3.4 then --or (cd.mindBlast.remain() > 0.5 or talent.shadowWordVoid and cd.shadowWordVoid.remain() < 4.2)) then
if cast.mindFlay() then
--Print("refresh VF mf")
return end
end
end
--Shaow Word: Pain
-- shadow_word_pain
if moving then
for i = 1, #enemies.yards40 do
local thisUnit = enemies.yards40[i]
if not debuff.shadowWordPain.exists(thisUnit) then
if cast.shadowWordPain(thisUnit) then
--Print("cast SWP last resort")
return
end
end
end
end
end
---------------------
--- Begin Profile ---
---------------------
-- Profile Stop | Pause
if not inCombat and not hastar and profileStop==true then
profileStop = false
elseif (inCombat and profileStop==true) or IsMounted() or IsFlying() or (pause(true) and not isCastingSpell(spell.mindFlay)) or mode.rotation==4 then
return true
else
-----------------
--- Rotations ---
-----------------
if actionList_Extra() then return end
--PowerWord: Shield
if IsMovingTime(mrdm(60,120)/100) and not IsFalling() then
if bnSTimer == nil then bnSTimer = GetTime() - 6 end
if isChecked("PWS: Body and Soul") and talent.bodyAndSoul and buff.powerWordShield.remain("player") <= mrdm(6,8) and GetTime() >= bnSTimer + 6 then
if cast.powerWordShield("player") then
bnSTimer = GetTime() return end
end
end
---------------------------------
--- Out Of Combat - Rotations ---
---------------------------------
if not inCombat then -- and GetObjectExists("target") and not UnitIsDeadOrGhost("target") and UnitCanAttack("target", "player")
if actionList_PreCombat() then return end
end
-----------------------------
--- In Combat - Rotations ---
-----------------------------
if inCombat and not IsMounted() and isValidUnit(units.dyn40) and getDistance(units.dyn40) < 40 and not isCastingSpell(spell.voidTorrent) and not isCastingSpell(spell.mindBlast) and not isCastingSpell(303769) then
-- Action List - Defensive
if actionList_Defensive() then return end
-- Action List - Cooldowns
actionList_Cooldowns()
-- Action List - Interrupts
--if useInterrupts() then
if actionList_Interrupts() then return end
--end
-- Trinkets off Cooldown
--if isChecked("Trinket 1 Off CD") and canUseItem(13) then
-- useItem(13)
-- return true
--end
--if isChecked("Trinket 2 Off CD") and canUseItem(14) then
-- useItem(14)
-- return true
--end
-- Action List - Cleave
-- run_action_list,name=cleave,if=active_enemies>1
if activeEnemies > 1 or (mode.rotation == 2 and not mode.rotation == 3) then --Print("Cleave")
--Print(mindblastTargets)
if actionList_Cleave() then return end
end
-- Action List - Main
-- run_action_list,name=single,if=active_enemies=1
if activeEnemies == 1 or mode.rotation == 3 then --Print(insanityDrained) --Print("Single")
if actionList_Single() then return end
end
end -- End Combat Rotation
end
end -- Run Rotation
local id = 258
if br.rotations[id] == nil then br.rotations[id] = {} end
tinsert(br.rotations[id],{
name = rotationName,
toggles = createToggles,
options = createOptions,
run = runRotation,
})
| gpl-3.0 |
collinmsn/thrift | lib/lua/TServer.lua | 30 | 3992 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
require 'Thrift'
require 'TFramedTransport'
require 'TBinaryProtocol'
-- TServer
TServer = __TObject:new{
__type = 'TServer'
}
-- 2 possible constructors
-- 1. {processor, serverTransport}
-- 2. {processor, serverTransport, transportFactory, protocolFactory}
function TServer:new(args)
if ttype(args) ~= 'table' then
error('TServer must be initialized with a table')
end
if args.processor == nil then
terror('You must provide ' .. ttype(self) .. ' with a processor')
end
if args.serverTransport == nil then
terror('You must provide ' .. ttype(self) .. ' with a serverTransport')
end
-- Create the object
local obj = __TObject.new(self, args)
if obj.transportFactory then
obj.inputTransportFactory = obj.transportFactory
obj.outputTransportFactory = obj.transportFactory
obj.transportFactory = nil
else
obj.inputTransportFactory = TFramedTransportFactory:new{}
obj.outputTransportFactory = obj.inputTransportFactory
end
if obj.protocolFactory then
obj.inputProtocolFactory = obj.protocolFactory
obj.outputProtocolFactory = obj.protocolFactory
obj.protocolFactory = nil
else
obj.inputProtocolFactory = TBinaryProtocolFactory:new{}
obj.outputProtocolFactory = obj.inputProtocolFactory
end
-- Set the __server variable in the handler so we can stop the server
obj.processor.handler.__server = self
return obj
end
function TServer:setServerEventHandler(handler)
self.serverEventHandler = handler
end
function TServer:_clientBegin(content, iprot, oprot)
if self.serverEventHandler and
type(self.serverEventHandler.clientBegin) == 'function' then
self.serverEventHandler:clientBegin(iprot, oprot)
end
end
function TServer:_preServe()
if self.serverEventHandler and
type(self.serverEventHandler.preServe) == 'function' then
self.serverEventHandler:preServe(self.serverTransport:getSocketInfo())
end
end
function TServer:_handleException(err)
if string.find(err, 'TTransportException') == nil then
print(err)
end
end
function TServer:serve() end
function TServer:handle(client)
local itrans, otrans =
self.inputTransportFactory:getTransport(client),
self.outputTransportFactory:getTransport(client)
local iprot, oprot =
self.inputProtocolFactory:getProtocol(itrans),
self.outputProtocolFactory:getProtocol(otrans)
self:_clientBegin(iprot, oprot)
while true do
local ret, err = pcall(self.processor.process, self.processor, iprot, oprot)
if ret == false and err then
if not string.find(err, "TTransportException") then
self:_handleException(err)
end
break
end
end
itrans:close()
otrans:close()
end
function TServer:close()
self.serverTransport:close()
end
-- TSimpleServer
-- Single threaded server that handles one transport (connection)
TSimpleServer = __TObject:new(TServer, {
__type = 'TSimpleServer',
__stop = false
})
function TSimpleServer:serve()
self.serverTransport:listen()
self:_preServe()
while not self.__stop do
client = self.serverTransport:accept()
self:handle(client)
end
self:close()
end
function TSimpleServer:stop()
self.__stop = true
end
| apache-2.0 |
vladimir-kotikov/clink | clink/dll/arguments.lua | 4 | 20679 | --
-- Copyright (c) 2012 Martin Ridgers
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
--
--------------------------------------------------------------------------------
clink.arg = {}
--------------------------------------------------------------------------------
local parsers = {}
local is_parser
local is_sub_parser
local new_sub_parser
local parser_go_impl
local merge_parsers
local parser_meta_table = {}
local sub_parser_meta_table = {}
--------------------------------------------------------------------------------
function parser_meta_table.__concat(lhs, rhs)
if not is_parser(rhs) then
error("Right-handside must be parser.", 2)
end
local t = type(lhs)
if t == "table" then
local ret = {}
for _, i in ipairs(lhs) do
table.insert(ret, i .. rhs)
end
return ret
elseif t ~= "string" then
error("Left-handside must be a string or a table.", 2)
end
return new_sub_parser(lhs, rhs)
end
--------------------------------------------------------------------------------
local function unfold_table(source, target)
for _, i in ipairs(source) do
if type(i) == "table" and getmetatable(i) == nil then
unfold_table(i, target)
else
table.insert(target, i)
end
end
end
--------------------------------------------------------------------------------
local function parser_is_flag(parser, part)
if part == nil then
return false
end
local prefix = part:sub(1, 1)
return prefix == "-" or prefix == "/"
end
--------------------------------------------------------------------------------
local function parser_add_arguments(parser, ...)
for _, i in ipairs({...}) do
-- Check all arguments are tables.
if type(i) ~= "table" then
error("All arguments to add_arguments() must be tables.", 2)
end
-- Only parsers are allowed to be specified without being wrapped in a
-- containing table.
if getmetatable(i) ~= nil then
if is_parser(i) then
table.insert(parser.arguments, i)
else
error("Tables can't have meta-tables.", 2)
end
else
-- Expand out nested tables and insert into object's arguments table.
local arguments = {}
unfold_table(i, arguments)
table.insert(parser.arguments, arguments)
end
end
return parser
end
--------------------------------------------------------------------------------
local function parser_set_arguments(parser, ...)
parser.arguments = {}
return parser:add_arguments(...)
end
--------------------------------------------------------------------------------
local function parser_add_flags(parser, ...)
local flags = {}
unfold_table({...}, flags)
-- Validate the specified flags.
for _, i in ipairs(flags) do
if is_sub_parser(i) then
i = i.key
end
-- Check all flags are strings.
if type(i) ~= "string" then
error("All parser flags must be strings. Found "..type(i), 2)
end
-- Check all flags start with a - or a /
if not parser:is_flag(i) then
error("Flags must begin with a '-' or a '/'", 2)
end
end
-- Append flags to parser's existing table of flags.
for _, i in ipairs(flags) do
table.insert(parser.flags, i)
end
return parser
end
--------------------------------------------------------------------------------
local function parser_set_flags(parser, ...)
parser.flags = {}
return parser:add_flags(...)
end
--------------------------------------------------------------------------------
local function parser_flatten_argument(parser, index, func_thunk)
-- Sanity check the 'index' param to make sure it's valid.
if type(index) == "number" then
if index <= 0 or index > #parser.arguments then
return parser.use_file_matching
end
end
-- index == nil is a special case that returns the parser's flags
local opts = {}
local arg_opts
if index == nil then
arg_opts = parser.flags
else
arg_opts = parser.arguments[index]
end
-- Convert each argument option into a string and collect them in a table.
for _, i in ipairs(arg_opts) do
if is_sub_parser(i) then
table.insert(opts, i.key)
else
local t = type(i)
if t == "function" then
local results = func_thunk(i)
local t = type(results)
if not results then
return parser.use_file_matching
elseif t == "boolean" then
return (results and parser.use_file_matching)
elseif t == "table" then
for _, j in ipairs(results) do
table.insert(opts, j)
end
end
elseif t == "string" or t == "number" then
table.insert(opts, tostring(i))
end
end
end
return opts
end
--------------------------------------------------------------------------------
local function parser_go_args(parser, state)
local exhausted_args = false
local exhausted_parts = false
local part = state.parts[state.part_index]
local arg_index = state.arg_index
local arg_opts = parser.arguments[arg_index]
local arg_count = #parser.arguments
-- Is the next argument a parser? Parse control directly on to it.
if is_parser(arg_opts) then
state.arg_index = 1
return parser_go_impl(arg_opts, state)
end
-- Advance parts state.
state.part_index = state.part_index + 1
if state.part_index > #state.parts then
exhausted_parts = true
end
-- Advance argument state.
state.arg_index = arg_index + 1
if arg_index > arg_count then
exhausted_args = true
end
-- We've exhausted all available arguments. We either loop or we're done.
if parser.loop_point > 0 and state.arg_index > arg_count then
state.arg_index = parser.loop_point
if state.arg_index > arg_count then
state.arg_index = arg_count
end
end
-- Is there some state to process?
if not exhausted_parts and not exhausted_args then
local exact = false
for _, arg_opt in ipairs(arg_opts) do
-- Is the argument a key to a sub-parser? If so then hand control
-- off to it.
if is_sub_parser(arg_opt) then
if arg_opt.key == part then
state.arg_index = 1
return parser_go_impl(arg_opt.parser, state)
end
end
-- Check so see if the part has an exact match in the argument. Note
-- that only string-type options are considered.
if type(arg_opt) == "string" then
exact = exact or arg_opt == part
else
exact = true
end
end
-- If the parser's required to be precise then check here.
if parser.precise and not exact then
exhausted_args = true
else
return nil
end
end
-- If we've no more arguments to traverse but there's still parts remaining
-- then we start skipping arguments but keep going so that flags still get
-- parsed (as flags have no position).
if exhausted_args then
state.part_index = state.part_index - 1
if not exhausted_parts then
if state.depth <= 1 then
state.skip_args = true
return
end
return parser.use_file_matching
end
end
-- Now we've an index into the parser's arguments that matches the line
-- state. Flatten it.
local func_thunk = function(func)
return func(part)
end
return parser:flatten_argument(arg_index, func_thunk)
end
--------------------------------------------------------------------------------
local function parser_go_flags(parser, state)
local part = state.parts[state.part_index]
-- Advance parts state.
state.part_index = state.part_index + 1
if state.part_index > #state.parts then
return parser:flatten_argument()
end
for _, arg_opt in ipairs(parser.flags) do
if is_sub_parser(arg_opt) then
if arg_opt.key == part then
local arg_index_cache = state.arg_index
local skip_args_cache = state.skip_args
state.arg_index = 1
state.skip_args = false
state.depth = state.depth + 1
local ret = parser_go_impl(arg_opt.parser, state)
if type(ret) == "table" then
return ret
end
state.depth = state.depth - 1
state.skip_args = skip_args_cache
state.arg_index = arg_index_cache
end
end
end
end
--------------------------------------------------------------------------------
function parser_go_impl(parser, state)
local has_flags = #parser.flags > 0
while state.part_index <= #state.parts do
local part = state.parts[state.part_index]
local dispatch_func
if has_flags and parser:is_flag(part) then
dispatch_func = parser_go_flags
elseif not state.skip_args then
dispatch_func = parser_go_args
end
if dispatch_func ~= nil then
local ret = dispatch_func(parser, state)
if ret ~= nil then
return ret
end
else
state.part_index = state.part_index + 1
end
end
return parser.use_file_matching
end
--------------------------------------------------------------------------------
local function parser_go(parser, parts)
-- Validate 'parts'.
if type(parts) ~= "table" then
error("'Parts' param must be a table of strings ("..type(parts)..").", 2)
else
if #parts == 0 then
part = { "" }
end
for i, j in ipairs(parts) do
local t = type(parts[i])
if t ~= "string" then
error("'Parts' table can only contain strings; "..j.."="..t, 2)
end
end
end
local state = {
arg_index = 1,
part_index = 1,
parts = parts,
skip_args = false,
depth = 1,
}
return parser_go_impl(parser, state)
end
--------------------------------------------------------------------------------
local function parser_dump(parser, depth)
if depth == nil then
depth = 0
end
function prt(depth, index, text)
local indent = string.sub(" ", 1, depth)
text = tostring(text)
print(indent..depth.."."..index.." - "..text)
end
-- Print arguments
local i = 0
for _, arg_opts in ipairs(parser.arguments) do
for _, arg_opt in ipairs(arg_opts) do
if is_sub_parser(arg_opt) then
prt(depth, i, arg_opt.key)
arg_opt.parser:dump(depth + 1)
else
prt(depth, i, arg_opt)
end
end
i = i + 1
end
-- Print flags
for _, flag in ipairs(parser.flags) do
prt(depth, "F", flag)
end
end
--------------------------------------------------------------------------------
function parser_be_precise(parser)
parser.precise = true
return parser
end
--------------------------------------------------------------------------------
function is_parser(p)
return type(p) == "table" and getmetatable(p) == parser_meta_table
end
--------------------------------------------------------------------------------
function is_sub_parser(sp)
return type(sp) == "table" and getmetatable(sp) == sub_parser_meta_table
end
--------------------------------------------------------------------------------
local function get_sub_parser(argument, str)
for _, arg in ipairs(argument) do
if is_sub_parser(arg) then
if arg.key == str then
return arg.parser
end
end
end
end
--------------------------------------------------------------------------------
function new_sub_parser(key, parser)
local sub_parser = {}
sub_parser.key = key
sub_parser.parser = parser
setmetatable(sub_parser, sub_parser_meta_table)
return sub_parser
end
--------------------------------------------------------------------------------
local function parser_disable_file_matching(parser)
parser.use_file_matching = false
return parser
end
--------------------------------------------------------------------------------
local function parser_loop(parser, loop_point)
if loop_point == nil or type(loop_point) ~= "number" or loop_point < 1 then
loop_point = 1
end
parser.loop_point = loop_point
return parser
end
--------------------------------------------------------------------------------
local function parser_initialise(parser, ...)
for _, word in ipairs({...}) do
local t = type(word)
if t == "string" then
parser:add_flags(word)
elseif t == "table" then
if is_sub_parser(word) and parser_is_flag(nil, word.key) then
parser:add_flags(word)
else
parser:add_arguments(word)
end
else
error("Additional arguments to new_parser() must be tables or strings", 2)
end
end
end
--------------------------------------------------------------------------------
function clink.arg.new_parser(...)
local parser = {}
-- Methods
parser.set_flags = parser_set_flags
parser.add_flags = parser_add_flags
parser.set_arguments = parser_set_arguments
parser.add_arguments = parser_add_arguments
parser.dump = parser_dump
parser.go = parser_go
parser.flatten_argument = parser_flatten_argument
parser.be_precise = parser_be_precise
parser.disable_file_matching = parser_disable_file_matching
parser.loop = parser_loop
parser.is_flag = parser_is_flag
-- Members.
parser.flags = {}
parser.arguments = {}
parser.precise = false
parser.use_file_matching = true
parser.loop_point = 0
setmetatable(parser, parser_meta_table)
-- If any arguments are provided treat them as parser's arguments or flags
if ... then
success, msg = pcall(parser_initialise, parser, ...)
if not success then
error(msg, 2)
end
end
return parser
end
--------------------------------------------------------------------------------
function merge_parsers(lhs, rhs)
-- Merging parsers is not a trivial matter and this implementation is far
-- from correct. It is however sufficient for the majority of cases.
-- Merge flags.
for _, rflag in ipairs(rhs.flags) do
table.insert(lhs.flags, rflag)
end
-- Remove (and save value of) the first argument in RHS.
local rhs_arg_1 = table.remove(rhs.arguments, 1)
if rhs_arg_1 == nil then
return
end
-- Get reference to the LHS's first argument table (creating it if needed).
local lhs_arg_1 = lhs.arguments[1]
if lhs_arg_1 == nil then
lhs_arg_1 = {}
table.insert(lhs.arguments, lhs_arg_1)
end
-- Link RHS to LHS through sub-parsers.
for _, rarg in ipairs(rhs_arg_1) do
local child
-- Split sub parser
if is_sub_parser(rarg) then
child = rarg.parser
rarg = rarg.key
else
child = rhs
end
-- If LHS's first argument has rarg in it which links to a sub-parser
-- then we need to recursively merge them.
local lhs_sub_parser = get_sub_parser(lhs_arg_1, rarg)
if lhs_sub_parser then
merge_parsers(lhs_sub_parser, child)
else
local to_add = rarg
if type(rarg) ~= "function" then
to_add = rarg .. child
end
table.insert(lhs_arg_1, to_add)
end
end
end
--------------------------------------------------------------------------------
function clink.arg.register_parser(cmd, parser)
if not is_parser(parser) then
local p = clink.arg.new_parser()
p:set_arguments({ parser })
parser = p
end
cmd = cmd:lower()
local prev = parsers[cmd]
if prev ~= nil then
merge_parsers(prev, parser)
else
parsers[cmd] = parser
end
end
--------------------------------------------------------------------------------
local function argument_match_generator(text, first, last)
local leading = rl_state.line_buffer:sub(1, first - 1):lower()
-- Extract the command.
local cmd_l, cmd_r
if leading:find("^%s*\"") then
-- Command appears to be surround by quotes.
cmd_l, cmd_r = leading:find("%b\"\"")
if cmd_l and cmd_r then
cmd_l = cmd_l + 1
cmd_r = cmd_r - 1
end
else
-- No quotes so the first, longest, non-whitespace word is extracted.
cmd_l, cmd_r = leading:find("[^%s]+")
end
if not cmd_l or not cmd_r then
return false
end
local regex = "[\\/:]*([^\\/:.]+)(%.*[%l]*)%s*$"
local _, _, cmd, ext = leading:sub(cmd_l, cmd_r):lower():find(regex)
-- Check to make sure the extension extracted is in pathext.
if ext and ext ~= "" then
if not clink.get_env("pathext"):lower():match(ext.."[;$]", 1, true) then
return false
end
end
-- Find a registered parser.
local parser = parsers[cmd]
if parser == nil then
return false
end
-- Split the command line into parts.
local str = rl_state.line_buffer:sub(cmd_r + 2, last)
local parts = {}
for _, sub_str in ipairs(clink.quote_split(str, "\"")) do
-- Quoted strings still have their quotes. Look for those type of
-- strings, strip the quotes and add it completely.
if sub_str:sub(1, 1) == "\"" then
local l, r = sub_str:find("\"[^\"]+")
if l then
local part = sub_str:sub(l + 1, r)
table.insert(parts, part)
end
else
-- Extract non-whitespace parts.
for _, r, part in function () return sub_str:find("^%s*([^%s]+)") end do
table.insert(parts, part)
sub_str = sub_str:sub(r + 1)
end
end
end
-- If 'text' is empty then add it as a part as it would have been skipped
-- by the split loop above.
if text == "" then
table.insert(parts, text)
end
-- Extend rl_state with match generation state; text, first, and last.
rl_state.text = text
rl_state.first = first
rl_state.last = last
-- Call the parser.
local needle = parts[#parts]
local ret = parser:go(parts)
if type(ret) ~= "table" then
return not ret
end
-- Iterate through the matches the parser returned and collect matches.
for _, match in ipairs(ret) do
if clink.is_match(needle, match) then
clink.add_match(match)
end
end
return true
end
--------------------------------------------------------------------------------
clink.register_match_generator(argument_match_generator, 25)
-- vim: expandtab
| gpl-3.0 |
matija-hustic/OpenRA | mods/d2k/maps/atreides-02b/atreides02b.lua | 5 | 3387 |
HarkonnenBase = { HConyard, HOutpost, HBarracks }
HarkonnenReinforcements = { }
HarkonnenReinforcements["Easy"] =
{
{ "light_inf", "trike" },
{ "light_inf", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" }
}
HarkonnenReinforcements["Normal"] =
{
{ "light_inf", "trike" },
{ "light_inf", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" },
{ "light_inf", "light_inf" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" },
}
HarkonnenReinforcements["Hard"] =
{
{ "trike", "trike" },
{ "light_inf", "trike" },
{ "light_inf", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" },
{ "light_inf", "light_inf" },
{ "trike", "trike" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" },
{ "trike", "trike" }
}
HarkonnenAttackPaths =
{
{ HarkonnenEntry1.Location, HarkonnenRally1.Location },
{ HarkonnenEntry1.Location, HarkonnenRally3.Location },
{ HarkonnenEntry2.Location, HarkonnenRally2.Location },
{ HarkonnenEntry2.Location, HarkonnenRally4.Location }
}
HarkonnenAttackDelay =
{
Easy = DateTime.Minutes(5),
Normal = DateTime.Minutes(2) + DateTime.Seconds(40),
Hard = DateTime.Minutes(1) + DateTime.Seconds(20)
}
HarkonnenAttackWaves =
{
Easy = 3,
Normal = 6,
Hard = 9
}
wave = 0
SendHarkonnen = function()
Trigger.AfterDelay(HarkonnenAttackDelay[Map.Difficulty], function()
wave = wave + 1
if wave > HarkonnenAttackWaves[Map.Difficulty] then
return
end
local path = Utils.Random(HarkonnenAttackPaths)
local units = Reinforcements.ReinforceWithTransport(harkonnen, "carryall.reinforce", HarkonnenReinforcements[Map.Difficulty][wave], path, { path[1] })[2]
Utils.Do(units, IdleHunt)
SendHarkonnen()
end)
end
IdleHunt = function(unit)
Trigger.OnIdle(unit, unit.Hunt)
end
Tick = function()
if player.HasNoRequiredUnits() then
harkonnen.MarkCompletedObjective(KillAtreides)
end
if harkonnen.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillHarkonnen) then
Media.DisplayMessage("The Harkonnen have been anihilated!", "Mentat")
player.MarkCompletedObjective(KillHarkonnen)
end
end
WorldLoaded = function()
harkonnen = Player.GetPlayer("Harkonnen")
player = Player.GetPlayer("Atreides")
InitObjectives()
Camera.Position = AConyard.CenterPosition
Trigger.OnAllKilled(HarkonnenBase, function()
Utils.Do(harkonnen.GetGroundAttackers(), IdleHunt)
end)
SendHarkonnen()
end
InitObjectives = function()
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
KillAtreides = harkonnen.AddPrimaryObjective("Kill all Atreides units.")
KillHarkonnen = player.AddPrimaryObjective("Destroy all Harkonnen forces.")
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerLost(player, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(player, "Lose")
end)
end)
Trigger.OnPlayerWon(player, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(player, "Win")
end)
end)
end
| gpl-3.0 |
iceman1001/proxmark3 | client/scripts/14araw.lua | 1 | 4914 | local cmds = require('commands')
local getopt = require('getopt')
local lib14a = require('read14a')
example = "script run 14araw -x 6000F57b"
author = "Martin Holst Swende"
desc =
[[
This is a script to allow raw 1444a commands to be sent and received.
Arguments:
-o do not connect - use this only if you previously used -p to stay connected
-r do not read response
-c calculate and append CRC
-p stay connected - dont inactivate the field
-x <payload> Data to send (NO SPACES!)
-d Debug flag
-t Topaz mode
-3 ISO14443-4 (use RATS)
Examples :
# 1. Connect and don't disconnect
script run 14araw -p
# 2. Send mf auth, read response (nonce)
script run 14araw -o -x 6000F57b -p
# 3. disconnect
script run 14araw -o
# All three steps in one go:
script run 14araw -x 6000F57b
]]
--[[
This script communicates with
/armsrc/iso14443a.c, specifically ReaderIso14443a() at around line 1779 and onwards.
Check there for details about data format and how commands are interpreted on the
device-side.
]]
-- Some globals
local TIMEOUT = 2000 -- Shouldn't take longer than 2 seconds
local DEBUG = false -- the debug flag
-------------------------------
-- Some utilities
-------------------------------
---
-- A debug printout-function
local function dbg(args)
if DEBUG then
print("###", args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print("ERROR: ",err)
end
---
-- Usage help
local function help()
print(desc)
print("Example usage")
print(example)
end
---
-- The main entry point
function main(args)
if args == nil or #args == 0 then return help() end
local ignore_response = false
local append_crc = false
local stayconnected = false
local payload = nil
local doconnect = true
local topaz_mode = false
local no_rats = false
-- Read the parameters
for o, a in getopt.getopt(args, 'orcpx:dt3') do
if o == "o" then doconnect = false end
if o == "r" then ignore_response = true end
if o == "c" then append_crc = true end
if o == "p" then stayconnected = true end
if o == "x" then payload = a end
if o == "d" then DEBUG = true end
if o == "t" then topaz_mode = true end
if o == "3" then no_rats = true end
end
-- First of all, connect
if doconnect then
dbg("doconnect")
-- We reuse the connect functionality from a
-- common library
info, err = lib14a.read(true, no_rats)
if err then return oops(err) end
print(("Connected to card, uid = %s"):format(info.uid))
end
-- The actual raw payload, if any
if payload then
res,err = sendRaw(payload,{ignore_response = ignore_response, topaz_mode = topaz_mode, append_crc = append_crc})
if err then return oops(err) end
if not ignoreresponse then
-- Display the returned data
showdata(res)
end
end
-- And, perhaps disconnect?
if not stayconnected then
disconnect()
end
end
--- Picks out and displays the data read from a tag
-- Specifically, takes a usb packet, converts to a Command
-- (as in commands.lua), takes the data-array and
-- reads the number of bytes specified in arg1 (arg0 in c-struct)
-- and displays the data
-- @param usbpacket the data received from the device
function showdata(usbpacket)
local cmd_response = Command.parse(usbpacket)
local len = tonumber(cmd_response.arg1) *2
--print("data length:",len)
local data = string.sub(tostring(cmd_response.data), 0, len);
print("<< ",data)
--print("----------------")
end
function sendRaw(rawdata, options)
print(">> ", rawdata)
local flags = lib14a.ISO14A_COMMAND.ISO14A_NO_DISCONNECT + lib14a.ISO14A_COMMAND.ISO14A_RAW
if options.topaz_mode then
flags = flags + lib14a.ISO14A_COMMAND.ISO14A_TOPAZMODE
end
if options.append_crc then
flags = flags + lib14a.ISO14A_COMMAND.ISO14A_APPEND_CRC
end
local command = Command:new{cmd = cmds.CMD_READER_ISO_14443a,
arg1 = flags, -- Send raw
-- arg2 contains the length, which is half the length
-- of the ASCII-string rawdata
arg2 = string.len(rawdata)/2,
data = rawdata}
return lib14a.sendToDevice(command, options.ignore_response)
end
-- Sends an instruction to do nothing, only disconnect
function disconnect()
local command = Command:new{cmd = cmds.CMD_READER_ISO_14443a, arg1 = 0, }
-- We can ignore the response here, no ACK is returned for this command
-- Check /armsrc/iso14443a.c, ReaderIso14443a() for details
return lib14a.sendToDevice(command,true)
end
-------------------------
-- Testing
-------------------------
function selftest()
DEBUG = true
dbg("Performing test")
main()
main("-p")
main(" -o -x 6000F57b -p")
main("-o")
main("-x 6000F57b")
dbg("Tests done")
end
-- Flip the switch here to perform a sanity check.
-- It read a nonce in two different ways, as specified in the usage-section
if "--test"==args then
selftest()
else
-- Call the main
main(args)
end
| gpl-2.0 |
bigdogmat/wire | lua/entities/gmod_wire_gimbal.lua | 10 | 2231 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Gimbal"
ENT.WireDebugName = "Gimbal"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:GetPhysicsObject():EnableGravity(false)
self.Inputs = WireLib.CreateInputs(self,{"On", "X", "Y", "Z", "Target [VECTOR]", "Direction [VECTOR]", "Angle [ANGLE]"})
self.XYZ = Vector()
end
function ENT:TriggerInput(name,value)
if name == "On" then
self.On = value ~= 0
else
self.TargetPos = nil
self.TargetDir = nil
self.TargetAng = nil
if name == "X" then
self.XYZ.x = value
self.TargetPos = self.XYZ
elseif name == "Y" then
self.XYZ.y = value
self.TargetPos = self.XYZ
elseif name == "Z" then
self.XYZ.z = value
self.TargetPos = self.XYZ
elseif name == "Target" then
self.XYZ = Vector(value.x, value.y, value.z)
self.TargetPos = self.XYZ
elseif name == "Direction" then
self.TargetDir = value
elseif name == "Angle" then
self.TargetAng = value
end
end
self:ShowOutput()
return true
end
function ENT:Think()
if self.On then
local ang
if self.TargetPos then
ang = (self.TargetPos - self:GetPos()):Angle()
elseif self.TargetDir then
ang = self.TargetDir:Angle()
elseif self.TargetAng then
ang = self.TargetAng
end
if ang then self:SetAngles(ang + Angle(90,0,0)) end
-- TODO: Put an option in the CPanel for Angle(90,0,0), and other useful directions
self:GetPhysicsObject():Wake()
end
self:NextThink(CurTime())
return true
end
function ENT:ShowOutput()
if not self.On then
self:SetOverlayText("Off")
elseif self.TargetPos then
self:SetOverlayText(string.format("Aiming towards (%.2f, %.2f, %.2f)", self.XYZ.x, self.XYZ.y, self.XYZ.z))
elseif self.TargetDir then
self:SetOverlayText(string.format("Aiming (%.4f, %.4f, %.4f)", self.TargetDir.x, self.TargetDir.y, self.TargetDir.z))
elseif self.TargetAng then
self:SetOverlayText(string.format("Aiming (%.1f, %.1f, %.1f)", self.TargetAng.pitch, self.TargetAng.yaw, self.TargetAng.roll))
end
end
duplicator.RegisterEntityClass("gmod_wire_gimbal", WireLib.MakeWireEnt, "Data")
| apache-2.0 |
tianxiawuzhei/cocos-quick-lua | libs/quick/framework/cocos2dx/OpenglConstants.lua | 78 | 27074 | --Encapsulate opengl constants.
gl = gl or {}
gl.GCCSO_SHADER_BINARY_FJ = 0x9260
gl._3DC_XY_AMD = 0x87fa
gl._3DC_X_AMD = 0x87f9
gl.ACTIVE_ATTRIBUTES = 0x8b89
gl.ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8b8a
gl.ACTIVE_PROGRAM_EXT = 0x8259
gl.ACTIVE_TEXTURE = 0x84e0
gl.ACTIVE_UNIFORMS = 0x8b86
gl.ACTIVE_UNIFORM_MAX_LENGTH = 0x8b87
gl.ALIASED_LINE_WIDTH_RANGE = 0x846e
gl.ALIASED_POINT_SIZE_RANGE = 0x846d
gl.ALL_COMPLETED_NV = 0x84f2
gl.ALL_SHADER_BITS_EXT = 0xffffffff
gl.ALPHA = 0x1906
gl.ALPHA16F_EXT = 0x881c
gl.ALPHA32F_EXT = 0x8816
gl.ALPHA8_EXT = 0x803c
gl.ALPHA8_OES = 0x803c
gl.ALPHA_BITS = 0xd55
gl.ALPHA_TEST_FUNC_QCOM = 0xbc1
gl.ALPHA_TEST_QCOM = 0xbc0
gl.ALPHA_TEST_REF_QCOM = 0xbc2
gl.ALREADY_SIGNALED_APPLE = 0x911a
gl.ALWAYS = 0x207
gl.AMD_compressed_3DC_texture = 0x1
gl.AMD_compressed_ATC_texture = 0x1
gl.AMD_performance_monitor = 0x1
gl.AMD_program_binary_Z400 = 0x1
gl.ANGLE_depth_texture = 0x1
gl.ANGLE_framebuffer_blit = 0x1
gl.ANGLE_framebuffer_multisample = 0x1
gl.ANGLE_instanced_arrays = 0x1
gl.ANGLE_pack_reverse_row_order = 0x1
gl.ANGLE_program_binary = 0x1
gl.ANGLE_texture_compression_dxt3 = 0x1
gl.ANGLE_texture_compression_dxt5 = 0x1
gl.ANGLE_texture_usage = 0x1
gl.ANGLE_translated_shader_source = 0x1
gl.ANY_SAMPLES_PASSED_CONSERVATIVE_EXT = 0x8d6a
gl.ANY_SAMPLES_PASSED_EXT = 0x8c2f
gl.APPLE_copy_texture_levels = 0x1
gl.APPLE_framebuffer_multisample = 0x1
gl.APPLE_rgb_422 = 0x1
gl.APPLE_sync = 0x1
gl.APPLE_texture_format_BGRA8888 = 0x1
gl.APPLE_texture_max_level = 0x1
gl.ARM_mali_program_binary = 0x1
gl.ARM_mali_shader_binary = 0x1
gl.ARM_rgba8 = 0x1
gl.ARRAY_BUFFER = 0x8892
gl.ARRAY_BUFFER_BINDING = 0x8894
gl.ATC_RGBA_EXPLICIT_ALPHA_AMD = 0x8c93
gl.ATC_RGBA_INTERPOLATED_ALPHA_AMD = 0x87ee
gl.ATC_RGB_AMD = 0x8c92
gl.ATTACHED_SHADERS = 0x8b85
gl.BACK = 0x405
gl.BGRA8_EXT = 0x93a1
gl.BGRA_EXT = 0x80e1
gl.BGRA_IMG = 0x80e1
gl.BINNING_CONTROL_HINT_QCOM = 0x8fb0
gl.BLEND = 0xbe2
gl.BLEND_COLOR = 0x8005
gl.BLEND_DST_ALPHA = 0x80ca
gl.BLEND_DST_RGB = 0x80c8
gl.BLEND_EQUATION = 0x8009
gl.BLEND_EQUATION_ALPHA = 0x883d
gl.BLEND_EQUATION_RGB = 0x8009
gl.BLEND_SRC_ALPHA = 0x80cb
gl.BLEND_SRC_RGB = 0x80c9
gl.BLUE_BITS = 0xd54
gl.BOOL = 0x8b56
gl.BOOL_VEC2 = 0x8b57
gl.BOOL_VEC3 = 0x8b58
gl.BOOL_VEC4 = 0x8b59
gl.BUFFER = 0x82e0
gl.BUFFER_ACCESS_OES = 0x88bb
gl.BUFFER_MAPPED_OES = 0x88bc
gl.BUFFER_MAP_POINTER_OES = 0x88bd
gl.BUFFER_OBJECT_EXT = 0x9151
gl.BUFFER_SIZE = 0x8764
gl.BUFFER_USAGE = 0x8765
gl.BYTE = 0x1400
gl.CCW = 0x901
gl.CLAMP_TO_BORDER_NV = 0x812d
gl.CLAMP_TO_EDGE = 0x812f
gl.COLOR_ATTACHMENT0 = 0x8ce0
gl.COLOR_ATTACHMENT0_NV = 0x8ce0
gl.COLOR_ATTACHMENT10_NV = 0x8cea
gl.COLOR_ATTACHMENT11_NV = 0x8ceb
gl.COLOR_ATTACHMENT12_NV = 0x8cec
gl.COLOR_ATTACHMENT13_NV = 0x8ced
gl.COLOR_ATTACHMENT14_NV = 0x8cee
gl.COLOR_ATTACHMENT15_NV = 0x8cef
gl.COLOR_ATTACHMENT1_NV = 0x8ce1
gl.COLOR_ATTACHMENT2_NV = 0x8ce2
gl.COLOR_ATTACHMENT3_NV = 0x8ce3
gl.COLOR_ATTACHMENT4_NV = 0x8ce4
gl.COLOR_ATTACHMENT5_NV = 0x8ce5
gl.COLOR_ATTACHMENT6_NV = 0x8ce6
gl.COLOR_ATTACHMENT7_NV = 0x8ce7
gl.COLOR_ATTACHMENT8_NV = 0x8ce8
gl.COLOR_ATTACHMENT9_NV = 0x8ce9
gl.COLOR_ATTACHMENT_EXT = 0x90f0
gl.COLOR_BUFFER_BIT = 0x4000
gl.COLOR_BUFFER_BIT0_QCOM = 0x1
gl.COLOR_BUFFER_BIT1_QCOM = 0x2
gl.COLOR_BUFFER_BIT2_QCOM = 0x4
gl.COLOR_BUFFER_BIT3_QCOM = 0x8
gl.COLOR_BUFFER_BIT4_QCOM = 0x10
gl.COLOR_BUFFER_BIT5_QCOM = 0x20
gl.COLOR_BUFFER_BIT6_QCOM = 0x40
gl.COLOR_BUFFER_BIT7_QCOM = 0x80
gl.COLOR_CLEAR_VALUE = 0xc22
gl.COLOR_EXT = 0x1800
gl.COLOR_WRITEMASK = 0xc23
gl.COMPARE_REF_TO_TEXTURE_EXT = 0x884e
gl.COMPILE_STATUS = 0x8b81
gl.COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93bb
gl.COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93b8
gl.COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93b9
gl.COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93ba
gl.COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93bc
gl.COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93bd
gl.COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93b0
gl.COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93b1
gl.COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93b2
gl.COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93b3
gl.COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93b4
gl.COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93b5
gl.COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93b6
gl.COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93b7
gl.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8c03
gl.COMPRESSED_RGBA_PVRTC_2BPPV2_IMG = 0x9137
gl.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8c02
gl.COMPRESSED_RGBA_PVRTC_4BPPV2_IMG = 0x9138
gl.COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83f1
gl.COMPRESSED_RGBA_S3TC_DXT3_ANGLE = 0x83f2
gl.COMPRESSED_RGBA_S3TC_DXT5_ANGLE = 0x83f3
gl.COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8c01
gl.COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8c00
gl.COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83f0
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93db
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93d8
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93d9
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93da
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93dc
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93dd
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93d0
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93d1
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93d2
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93d3
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93d4
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93d5
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93d6
gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93d7
gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV = 0x8c4d
gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV = 0x8c4e
gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV = 0x8c4f
gl.COMPRESSED_SRGB_S3TC_DXT1_NV = 0x8c4c
gl.COMPRESSED_TEXTURE_FORMATS = 0x86a3
gl.CONDITION_SATISFIED_APPLE = 0x911c
gl.CONSTANT_ALPHA = 0x8003
gl.CONSTANT_COLOR = 0x8001
gl.CONTEXT_FLAG_DEBUG_BIT = 0x2
gl.CONTEXT_ROBUST_ACCESS_EXT = 0x90f3
gl.COUNTER_RANGE_AMD = 0x8bc1
gl.COUNTER_TYPE_AMD = 0x8bc0
gl.COVERAGE_ALL_FRAGMENTS_NV = 0x8ed5
gl.COVERAGE_ATTACHMENT_NV = 0x8ed2
gl.COVERAGE_AUTOMATIC_NV = 0x8ed7
gl.COVERAGE_BUFFERS_NV = 0x8ed3
gl.COVERAGE_BUFFER_BIT_NV = 0x8000
gl.COVERAGE_COMPONENT4_NV = 0x8ed1
gl.COVERAGE_COMPONENT_NV = 0x8ed0
gl.COVERAGE_EDGE_FRAGMENTS_NV = 0x8ed6
gl.COVERAGE_SAMPLES_NV = 0x8ed4
gl.CPU_OPTIMIZED_QCOM = 0x8fb1
gl.CULL_FACE = 0xb44
gl.CULL_FACE_MODE = 0xb45
gl.CURRENT_PROGRAM = 0x8b8d
gl.CURRENT_QUERY_EXT = 0x8865
gl.CURRENT_VERTEX_ATTRIB = 0x8626
gl.CW = 0x900
gl.DEBUG_CALLBACK_FUNCTION = 0x8244
gl.DEBUG_CALLBACK_USER_PARAM = 0x8245
gl.DEBUG_GROUP_STACK_DEPTH = 0x826d
gl.DEBUG_LOGGED_MESSAGES = 0x9145
gl.DEBUG_NEXT_LOGGED_MESSAGE_LENGTH = 0x8243
gl.DEBUG_OUTPUT = 0x92e0
gl.DEBUG_OUTPUT_SYNCHRONOUS = 0x8242
gl.DEBUG_SEVERITY_HIGH = 0x9146
gl.DEBUG_SEVERITY_LOW = 0x9148
gl.DEBUG_SEVERITY_MEDIUM = 0x9147
gl.DEBUG_SEVERITY_NOTIFICATION = 0x826b
gl.DEBUG_SOURCE_API = 0x8246
gl.DEBUG_SOURCE_APPLICATION = 0x824a
gl.DEBUG_SOURCE_OTHER = 0x824b
gl.DEBUG_SOURCE_SHADER_COMPILER = 0x8248
gl.DEBUG_SOURCE_THIRD_PARTY = 0x8249
gl.DEBUG_SOURCE_WINDOW_SYSTEM = 0x8247
gl.DEBUG_TYPE_DEPRECATED_BEHAVIOR = 0x824d
gl.DEBUG_TYPE_ERROR = 0x824c
gl.DEBUG_TYPE_MARKER = 0x8268
gl.DEBUG_TYPE_OTHER = 0x8251
gl.DEBUG_TYPE_PERFORMANCE = 0x8250
gl.DEBUG_TYPE_POP_GROUP = 0x826a
gl.DEBUG_TYPE_PORTABILITY = 0x824f
gl.DEBUG_TYPE_PUSH_GROUP = 0x8269
gl.DEBUG_TYPE_UNDEFINED_BEHAVIOR = 0x824e
gl.DECR = 0x1e03
gl.DECR_WRAP = 0x8508
gl.DELETE_STATUS = 0x8b80
gl.DEPTH24_STENCIL8_OES = 0x88f0
gl.DEPTH_ATTACHMENT = 0x8d00
gl.DEPTH_BITS = 0xd56
gl.DEPTH_BUFFER_BIT = 0x100
gl.DEPTH_BUFFER_BIT0_QCOM = 0x100
gl.DEPTH_BUFFER_BIT1_QCOM = 0x200
gl.DEPTH_BUFFER_BIT2_QCOM = 0x400
gl.DEPTH_BUFFER_BIT3_QCOM = 0x800
gl.DEPTH_BUFFER_BIT4_QCOM = 0x1000
gl.DEPTH_BUFFER_BIT5_QCOM = 0x2000
gl.DEPTH_BUFFER_BIT6_QCOM = 0x4000
gl.DEPTH_BUFFER_BIT7_QCOM = 0x8000
gl.DEPTH_CLEAR_VALUE = 0xb73
gl.DEPTH_COMPONENT = 0x1902
gl.DEPTH_COMPONENT16 = 0x81a5
gl.DEPTH_COMPONENT16_NONLINEAR_NV = 0x8e2c
gl.DEPTH_COMPONENT16_OES = 0x81a5
gl.DEPTH_COMPONENT24_OES = 0x81a6
gl.DEPTH_COMPONENT32_OES = 0x81a7
gl.DEPTH_EXT = 0x1801
gl.DEPTH_FUNC = 0xb74
gl.DEPTH_RANGE = 0xb70
gl.DEPTH_STENCIL_OES = 0x84f9
gl.DEPTH_TEST = 0xb71
gl.DEPTH_WRITEMASK = 0xb72
gl.DITHER = 0xbd0
gl.DMP_shader_binary = 0x1
gl.DONT_CARE = 0x1100
gl.DRAW_BUFFER0_NV = 0x8825
gl.DRAW_BUFFER10_NV = 0x882f
gl.DRAW_BUFFER11_NV = 0x8830
gl.DRAW_BUFFER12_NV = 0x8831
gl.DRAW_BUFFER13_NV = 0x8832
gl.DRAW_BUFFER14_NV = 0x8833
gl.DRAW_BUFFER15_NV = 0x8834
gl.DRAW_BUFFER1_NV = 0x8826
gl.DRAW_BUFFER2_NV = 0x8827
gl.DRAW_BUFFER3_NV = 0x8828
gl.DRAW_BUFFER4_NV = 0x8829
gl.DRAW_BUFFER5_NV = 0x882a
gl.DRAW_BUFFER6_NV = 0x882b
gl.DRAW_BUFFER7_NV = 0x882c
gl.DRAW_BUFFER8_NV = 0x882d
gl.DRAW_BUFFER9_NV = 0x882e
gl.DRAW_BUFFER_EXT = 0xc01
gl.DRAW_FRAMEBUFFER_ANGLE = 0x8ca9
gl.DRAW_FRAMEBUFFER_APPLE = 0x8ca9
gl.DRAW_FRAMEBUFFER_BINDING_ANGLE = 0x8ca6
gl.DRAW_FRAMEBUFFER_BINDING_APPLE = 0x8ca6
gl.DRAW_FRAMEBUFFER_BINDING_NV = 0x8ca6
gl.DRAW_FRAMEBUFFER_NV = 0x8ca9
gl.DST_ALPHA = 0x304
gl.DST_COLOR = 0x306
gl.DYNAMIC_DRAW = 0x88e8
gl.ELEMENT_ARRAY_BUFFER = 0x8893
gl.ELEMENT_ARRAY_BUFFER_BINDING = 0x8895
gl.EQUAL = 0x202
gl.ES_VERSION_2_0 = 0x1
gl.ETC1_RGB8_OES = 0x8d64
gl.ETC1_SRGB8_NV = 0x88ee
gl.EXTENSIONS = 0x1f03
gl.EXT_blend_minmax = 0x1
gl.EXT_color_buffer_half_float = 0x1
gl.EXT_debug_label = 0x1
gl.EXT_debug_marker = 0x1
gl.EXT_discard_framebuffer = 0x1
gl.EXT_map_buffer_range = 0x1
gl.EXT_multi_draw_arrays = 0x1
gl.EXT_multisampled_render_to_texture = 0x1
gl.EXT_multiview_draw_buffers = 0x1
gl.EXT_occlusion_query_boolean = 0x1
gl.EXT_read_format_bgra = 0x1
gl.EXT_robustness = 0x1
gl.EXT_sRGB = 0x1
gl.EXT_separate_shader_objects = 0x1
gl.EXT_shader_framebuffer_fetch = 0x1
gl.EXT_shader_texture_lod = 0x1
gl.EXT_shadow_samplers = 0x1
gl.EXT_texture_compression_dxt1 = 0x1
gl.EXT_texture_filter_anisotropic = 0x1
gl.EXT_texture_format_BGRA8888 = 0x1
gl.EXT_texture_rg = 0x1
gl.EXT_texture_storage = 0x1
gl.EXT_texture_type_2_10_10_10_REV = 0x1
gl.EXT_unpack_subimage = 0x1
gl.FALSE = 0x0
gl.FASTEST = 0x1101
gl.FENCE_CONDITION_NV = 0x84f4
gl.FENCE_STATUS_NV = 0x84f3
gl.FIXED = 0x140c
gl.FJ_shader_binary_GCCSO = 0x1
gl.FLOAT = 0x1406
gl.FLOAT_MAT2 = 0x8b5a
gl.FLOAT_MAT3 = 0x8b5b
gl.FLOAT_MAT4 = 0x8b5c
gl.FLOAT_VEC2 = 0x8b50
gl.FLOAT_VEC3 = 0x8b51
gl.FLOAT_VEC4 = 0x8b52
gl.FRAGMENT_SHADER = 0x8b30
gl.FRAGMENT_SHADER_BIT_EXT = 0x2
gl.FRAGMENT_SHADER_DERIVATIVE_HINT_OES = 0x8b8b
gl.FRAGMENT_SHADER_DISCARDS_SAMPLES_EXT = 0x8a52
gl.FRAMEBUFFER = 0x8d40
gl.FRAMEBUFFER_ATTACHMENT_ANGLE = 0x93a3
gl.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT = 0x8210
gl.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT = 0x8211
gl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8cd1
gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8cd0
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES = 0x8cd4
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8cd3
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8cd2
gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT = 0x8d6c
gl.FRAMEBUFFER_BINDING = 0x8ca6
gl.FRAMEBUFFER_COMPLETE = 0x8cd5
gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8cd6
gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8cd9
gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8cd7
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE = 0x8d56
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE = 0x8d56
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT = 0x8d56
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG = 0x9134
gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_NV = 0x8d56
gl.FRAMEBUFFER_UNDEFINED_OES = 0x8219
gl.FRAMEBUFFER_UNSUPPORTED = 0x8cdd
gl.FRONT = 0x404
gl.FRONT_AND_BACK = 0x408
gl.FRONT_FACE = 0xb46
gl.FUNC_ADD = 0x8006
gl.FUNC_REVERSE_SUBTRACT = 0x800b
gl.FUNC_SUBTRACT = 0x800a
gl.GENERATE_MIPMAP_HINT = 0x8192
gl.GEQUAL = 0x206
gl.GPU_OPTIMIZED_QCOM = 0x8fb2
gl.GREATER = 0x204
gl.GREEN_BITS = 0xd53
gl.GUILTY_CONTEXT_RESET_EXT = 0x8253
gl.HALF_FLOAT_OES = 0x8d61
gl.HIGH_FLOAT = 0x8df2
gl.HIGH_INT = 0x8df5
gl.IMG_multisampled_render_to_texture = 0x1
gl.IMG_program_binary = 0x1
gl.IMG_read_format = 0x1
gl.IMG_shader_binary = 0x1
gl.IMG_texture_compression_pvrtc = 0x1
gl.IMG_texture_compression_pvrtc2 = 0x1
gl.IMPLEMENTATION_COLOR_READ_FORMAT = 0x8b9b
gl.IMPLEMENTATION_COLOR_READ_TYPE = 0x8b9a
gl.INCR = 0x1e02
gl.INCR_WRAP = 0x8507
gl.INFO_LOG_LENGTH = 0x8b84
gl.INNOCENT_CONTEXT_RESET_EXT = 0x8254
gl.INT = 0x1404
gl.INT_10_10_10_2_OES = 0x8df7
gl.INT_VEC2 = 0x8b53
gl.INT_VEC3 = 0x8b54
gl.INT_VEC4 = 0x8b55
gl.INVALID_ENUM = 0x500
gl.INVALID_FRAMEBUFFER_OPERATION = 0x506
gl.INVALID_OPERATION = 0x502
gl.INVALID_VALUE = 0x501
gl.INVERT = 0x150a
gl.KEEP = 0x1e00
gl.KHR_debug = 0x1
gl.KHR_texture_compression_astc_ldr = 0x1
gl.LEQUAL = 0x203
gl.LESS = 0x201
gl.LINEAR = 0x2601
gl.LINEAR_MIPMAP_LINEAR = 0x2703
gl.LINEAR_MIPMAP_NEAREST = 0x2701
gl.LINES = 0x1
gl.LINE_LOOP = 0x2
gl.LINE_STRIP = 0x3
gl.LINE_WIDTH = 0xb21
gl.LINK_STATUS = 0x8b82
gl.LOSE_CONTEXT_ON_RESET_EXT = 0x8252
gl.LOW_FLOAT = 0x8df0
gl.LOW_INT = 0x8df3
gl.LUMINANCE = 0x1909
gl.LUMINANCE16F_EXT = 0x881e
gl.LUMINANCE32F_EXT = 0x8818
gl.LUMINANCE4_ALPHA4_OES = 0x8043
gl.LUMINANCE8_ALPHA8_EXT = 0x8045
gl.LUMINANCE8_ALPHA8_OES = 0x8045
gl.LUMINANCE8_EXT = 0x8040
gl.LUMINANCE8_OES = 0x8040
gl.LUMINANCE_ALPHA = 0x190a
gl.LUMINANCE_ALPHA16F_EXT = 0x881f
gl.LUMINANCE_ALPHA32F_EXT = 0x8819
gl.MALI_PROGRAM_BINARY_ARM = 0x8f61
gl.MALI_SHADER_BINARY_ARM = 0x8f60
gl.MAP_FLUSH_EXPLICIT_BIT_EXT = 0x10
gl.MAP_INVALIDATE_BUFFER_BIT_EXT = 0x8
gl.MAP_INVALIDATE_RANGE_BIT_EXT = 0x4
gl.MAP_READ_BIT_EXT = 0x1
gl.MAP_UNSYNCHRONIZED_BIT_EXT = 0x20
gl.MAP_WRITE_BIT_EXT = 0x2
gl.MAX_3D_TEXTURE_SIZE_OES = 0x8073
gl.MAX_COLOR_ATTACHMENTS_NV = 0x8cdf
gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8b4d
gl.MAX_CUBE_MAP_TEXTURE_SIZE = 0x851c
gl.MAX_DEBUG_GROUP_STACK_DEPTH = 0x826c
gl.MAX_DEBUG_LOGGED_MESSAGES = 0x9144
gl.MAX_DEBUG_MESSAGE_LENGTH = 0x9143
gl.MAX_DRAW_BUFFERS_NV = 0x8824
gl.MAX_EXT = 0x8008
gl.MAX_FRAGMENT_UNIFORM_VECTORS = 0x8dfd
gl.MAX_LABEL_LENGTH = 0x82e8
gl.MAX_MULTIVIEW_BUFFERS_EXT = 0x90f2
gl.MAX_RENDERBUFFER_SIZE = 0x84e8
gl.MAX_SAMPLES_ANGLE = 0x8d57
gl.MAX_SAMPLES_APPLE = 0x8d57
gl.MAX_SAMPLES_EXT = 0x8d57
gl.MAX_SAMPLES_IMG = 0x9135
gl.MAX_SAMPLES_NV = 0x8d57
gl.MAX_SERVER_WAIT_TIMEOUT_APPLE = 0x9111
gl.MAX_TEXTURE_IMAGE_UNITS = 0x8872
gl.MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84ff
gl.MAX_TEXTURE_SIZE = 0xd33
gl.MAX_VARYING_VECTORS = 0x8dfc
gl.MAX_VERTEX_ATTRIBS = 0x8869
gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8b4c
gl.MAX_VERTEX_UNIFORM_VECTORS = 0x8dfb
gl.MAX_VIEWPORT_DIMS = 0xd3a
gl.MEDIUM_FLOAT = 0x8df1
gl.MEDIUM_INT = 0x8df4
gl.MIN_EXT = 0x8007
gl.MIRRORED_REPEAT = 0x8370
gl.MULTISAMPLE_BUFFER_BIT0_QCOM = 0x1000000
gl.MULTISAMPLE_BUFFER_BIT1_QCOM = 0x2000000
gl.MULTISAMPLE_BUFFER_BIT2_QCOM = 0x4000000
gl.MULTISAMPLE_BUFFER_BIT3_QCOM = 0x8000000
gl.MULTISAMPLE_BUFFER_BIT4_QCOM = 0x10000000
gl.MULTISAMPLE_BUFFER_BIT5_QCOM = 0x20000000
gl.MULTISAMPLE_BUFFER_BIT6_QCOM = 0x40000000
gl.MULTISAMPLE_BUFFER_BIT7_QCOM = 0x80000000
gl.MULTIVIEW_EXT = 0x90f1
gl.NEAREST = 0x2600
gl.NEAREST_MIPMAP_LINEAR = 0x2702
gl.NEAREST_MIPMAP_NEAREST = 0x2700
gl.NEVER = 0x200
gl.NICEST = 0x1102
gl.NONE = 0x0
gl.NOTEQUAL = 0x205
gl.NO_ERROR = 0x0
gl.NO_RESET_NOTIFICATION_EXT = 0x8261
gl.NUM_COMPRESSED_TEXTURE_FORMATS = 0x86a2
gl.NUM_PROGRAM_BINARY_FORMATS_OES = 0x87fe
gl.NUM_SHADER_BINARY_FORMATS = 0x8df9
gl.NV_coverage_sample = 0x1
gl.NV_depth_nonlinear = 0x1
gl.NV_draw_buffers = 0x1
gl.NV_draw_instanced = 0x1
gl.NV_fbo_color_attachments = 0x1
gl.NV_fence = 0x1
gl.NV_framebuffer_blit = 0x1
gl.NV_framebuffer_multisample = 0x1
gl.NV_generate_mipmap_sRGB = 0x1
gl.NV_instanced_arrays = 0x1
gl.NV_read_buffer = 0x1
gl.NV_read_buffer_front = 0x1
gl.NV_read_depth = 0x1
gl.NV_read_depth_stencil = 0x1
gl.NV_read_stencil = 0x1
gl.NV_sRGB_formats = 0x1
gl.NV_shadow_samplers_array = 0x1
gl.NV_shadow_samplers_cube = 0x1
gl.NV_texture_border_clamp = 0x1
gl.NV_texture_compression_s3tc_update = 0x1
gl.NV_texture_npot_2D_mipmap = 0x1
gl.OBJECT_TYPE_APPLE = 0x9112
gl.OES_EGL_image = 0x1
gl.OES_EGL_image_external = 0x1
gl.OES_compressed_ETC1_RGB8_texture = 0x1
gl.OES_compressed_paletted_texture = 0x1
gl.OES_depth24 = 0x1
gl.OES_depth32 = 0x1
gl.OES_depth_texture = 0x1
gl.OES_element_index_uint = 0x1
gl.OES_fbo_render_mipmap = 0x1
gl.OES_fragment_precision_high = 0x1
gl.OES_get_program_binary = 0x1
gl.OES_mapbuffer = 0x1
gl.OES_packed_depth_stencil = 0x1
gl.OES_required_internalformat = 0x1
gl.OES_rgb8_rgba8 = 0x1
gl.OES_standard_derivatives = 0x1
gl.OES_stencil1 = 0x1
gl.OES_stencil4 = 0x1
gl.OES_surfaceless_context = 0x1
gl.OES_texture_3D = 0x1
gl.OES_texture_float = 0x1
gl.OES_texture_float_linear = 0x1
gl.OES_texture_half_float = 0x1
gl.OES_texture_half_float_linear = 0x1
gl.OES_texture_npot = 0x1
gl.OES_vertex_array_object = 0x1
gl.OES_vertex_half_float = 0x1
gl.OES_vertex_type_10_10_10_2 = 0x1
gl.ONE = 0x1
gl.ONE_MINUS_CONSTANT_ALPHA = 0x8004
gl.ONE_MINUS_CONSTANT_COLOR = 0x8002
gl.ONE_MINUS_DST_ALPHA = 0x305
gl.ONE_MINUS_DST_COLOR = 0x307
gl.ONE_MINUS_SRC_ALPHA = 0x303
gl.ONE_MINUS_SRC_COLOR = 0x301
gl.OUT_OF_MEMORY = 0x505
gl.PACK_ALIGNMENT = 0xd05
gl.PACK_REVERSE_ROW_ORDER_ANGLE = 0x93a4
gl.PALETTE4_R5_G6_B5_OES = 0x8b92
gl.PALETTE4_RGB5_A1_OES = 0x8b94
gl.PALETTE4_RGB8_OES = 0x8b90
gl.PALETTE4_RGBA4_OES = 0x8b93
gl.PALETTE4_RGBA8_OES = 0x8b91
gl.PALETTE8_R5_G6_B5_OES = 0x8b97
gl.PALETTE8_RGB5_A1_OES = 0x8b99
gl.PALETTE8_RGB8_OES = 0x8b95
gl.PALETTE8_RGBA4_OES = 0x8b98
gl.PALETTE8_RGBA8_OES = 0x8b96
gl.PERCENTAGE_AMD = 0x8bc3
gl.PERFMON_GLOBAL_MODE_QCOM = 0x8fa0
gl.PERFMON_RESULT_AMD = 0x8bc6
gl.PERFMON_RESULT_AVAILABLE_AMD = 0x8bc4
gl.PERFMON_RESULT_SIZE_AMD = 0x8bc5
gl.POINTS = 0x0
gl.POLYGON_OFFSET_FACTOR = 0x8038
gl.POLYGON_OFFSET_FILL = 0x8037
gl.POLYGON_OFFSET_UNITS = 0x2a00
gl.PROGRAM = 0x82e2
gl.PROGRAM_BINARY_ANGLE = 0x93a6
gl.PROGRAM_BINARY_FORMATS_OES = 0x87ff
gl.PROGRAM_BINARY_LENGTH_OES = 0x8741
gl.PROGRAM_OBJECT_EXT = 0x8b40
gl.PROGRAM_PIPELINE_BINDING_EXT = 0x825a
gl.PROGRAM_PIPELINE_OBJECT_EXT = 0x8a4f
gl.PROGRAM_SEPARABLE_EXT = 0x8258
gl.QCOM_alpha_test = 0x1
gl.QCOM_binning_control = 0x1
gl.QCOM_driver_control = 0x1
gl.QCOM_extended_get = 0x1
gl.QCOM_extended_get2 = 0x1
gl.QCOM_perfmon_global_mode = 0x1
gl.QCOM_tiled_rendering = 0x1
gl.QCOM_writeonly_rendering = 0x1
gl.QUERY = 0x82e3
gl.QUERY_OBJECT_EXT = 0x9153
gl.QUERY_RESULT_AVAILABLE_EXT = 0x8867
gl.QUERY_RESULT_EXT = 0x8866
gl.R16F_EXT = 0x822d
gl.R32F_EXT = 0x822e
gl.R8_EXT = 0x8229
gl.READ_BUFFER_EXT = 0xc02
gl.READ_BUFFER_NV = 0xc02
gl.READ_FRAMEBUFFER_ANGLE = 0x8ca8
gl.READ_FRAMEBUFFER_APPLE = 0x8ca8
gl.READ_FRAMEBUFFER_BINDING_ANGLE = 0x8caa
gl.READ_FRAMEBUFFER_BINDING_APPLE = 0x8caa
gl.READ_FRAMEBUFFER_BINDING_NV = 0x8caa
gl.READ_FRAMEBUFFER_NV = 0x8ca8
gl.RED_BITS = 0xd52
gl.RED_EXT = 0x1903
gl.RENDERBUFFER = 0x8d41
gl.RENDERBUFFER_ALPHA_SIZE = 0x8d53
gl.RENDERBUFFER_BINDING = 0x8ca7
gl.RENDERBUFFER_BLUE_SIZE = 0x8d52
gl.RENDERBUFFER_DEPTH_SIZE = 0x8d54
gl.RENDERBUFFER_GREEN_SIZE = 0x8d51
gl.RENDERBUFFER_HEIGHT = 0x8d43
gl.RENDERBUFFER_INTERNAL_FORMAT = 0x8d44
gl.RENDERBUFFER_RED_SIZE = 0x8d50
gl.RENDERBUFFER_SAMPLES_ANGLE = 0x8cab
gl.RENDERBUFFER_SAMPLES_APPLE = 0x8cab
gl.RENDERBUFFER_SAMPLES_EXT = 0x8cab
gl.RENDERBUFFER_SAMPLES_IMG = 0x9133
gl.RENDERBUFFER_SAMPLES_NV = 0x8cab
gl.RENDERBUFFER_STENCIL_SIZE = 0x8d55
gl.RENDERBUFFER_WIDTH = 0x8d42
gl.RENDERER = 0x1f01
gl.RENDER_DIRECT_TO_FRAMEBUFFER_QCOM = 0x8fb3
gl.REPEAT = 0x2901
gl.REPLACE = 0x1e01
gl.REQUIRED_TEXTURE_IMAGE_UNITS_OES = 0x8d68
gl.RESET_NOTIFICATION_STRATEGY_EXT = 0x8256
gl.RG16F_EXT = 0x822f
gl.RG32F_EXT = 0x8230
gl.RG8_EXT = 0x822b
gl.RGB = 0x1907
gl.RGB10_A2_EXT = 0x8059
gl.RGB10_EXT = 0x8052
gl.RGB16F_EXT = 0x881b
gl.RGB32F_EXT = 0x8815
gl.RGB565 = 0x8d62
gl.RGB565_OES = 0x8d62
gl.RGB5_A1 = 0x8057
gl.RGB5_A1_OES = 0x8057
gl.RGB8_OES = 0x8051
gl.RGBA = 0x1908
gl.RGBA16F_EXT = 0x881a
gl.RGBA32F_EXT = 0x8814
gl.RGBA4 = 0x8056
gl.RGBA4_OES = 0x8056
gl.RGBA8_OES = 0x8058
gl.RGB_422_APPLE = 0x8a1f
gl.RG_EXT = 0x8227
gl.SAMPLER = 0x82e6
gl.SAMPLER_2D = 0x8b5e
gl.SAMPLER_2D_ARRAY_SHADOW_NV = 0x8dc4
gl.SAMPLER_2D_SHADOW_EXT = 0x8b62
gl.SAMPLER_3D_OES = 0x8b5f
gl.SAMPLER_CUBE = 0x8b60
gl.SAMPLER_CUBE_SHADOW_NV = 0x8dc5
gl.SAMPLER_EXTERNAL_OES = 0x8d66
gl.SAMPLES = 0x80a9
gl.SAMPLE_ALPHA_TO_COVERAGE = 0x809e
gl.SAMPLE_BUFFERS = 0x80a8
gl.SAMPLE_COVERAGE = 0x80a0
gl.SAMPLE_COVERAGE_INVERT = 0x80ab
gl.SAMPLE_COVERAGE_VALUE = 0x80aa
gl.SCISSOR_BOX = 0xc10
gl.SCISSOR_TEST = 0xc11
gl.SGX_BINARY_IMG = 0x8c0a
gl.SGX_PROGRAM_BINARY_IMG = 0x9130
gl.SHADER = 0x82e1
gl.SHADER_BINARY_DMP = 0x9250
gl.SHADER_BINARY_FORMATS = 0x8df8
gl.SHADER_BINARY_VIV = 0x8fc4
gl.SHADER_COMPILER = 0x8dfa
gl.SHADER_OBJECT_EXT = 0x8b48
gl.SHADER_SOURCE_LENGTH = 0x8b88
gl.SHADER_TYPE = 0x8b4f
gl.SHADING_LANGUAGE_VERSION = 0x8b8c
gl.SHORT = 0x1402
gl.SIGNALED_APPLE = 0x9119
gl.SLUMINANCE8_ALPHA8_NV = 0x8c45
gl.SLUMINANCE8_NV = 0x8c47
gl.SLUMINANCE_ALPHA_NV = 0x8c44
gl.SLUMINANCE_NV = 0x8c46
gl.SRC_ALPHA = 0x302
gl.SRC_ALPHA_SATURATE = 0x308
gl.SRC_COLOR = 0x300
gl.SRGB8_ALPHA8_EXT = 0x8c43
gl.SRGB8_NV = 0x8c41
gl.SRGB_ALPHA_EXT = 0x8c42
gl.SRGB_EXT = 0x8c40
gl.STACK_OVERFLOW = 0x503
gl.STACK_UNDERFLOW = 0x504
gl.STATE_RESTORE = 0x8bdc
gl.STATIC_DRAW = 0x88e4
gl.STENCIL_ATTACHMENT = 0x8d20
gl.STENCIL_BACK_FAIL = 0x8801
gl.STENCIL_BACK_FUNC = 0x8800
gl.STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802
gl.STENCIL_BACK_PASS_DEPTH_PASS = 0x8803
gl.STENCIL_BACK_REF = 0x8ca3
gl.STENCIL_BACK_VALUE_MASK = 0x8ca4
gl.STENCIL_BACK_WRITEMASK = 0x8ca5
gl.STENCIL_BITS = 0xd57
gl.STENCIL_BUFFER_BIT = 0x400
gl.STENCIL_BUFFER_BIT0_QCOM = 0x10000
gl.STENCIL_BUFFER_BIT1_QCOM = 0x20000
gl.STENCIL_BUFFER_BIT2_QCOM = 0x40000
gl.STENCIL_BUFFER_BIT3_QCOM = 0x80000
gl.STENCIL_BUFFER_BIT4_QCOM = 0x100000
gl.STENCIL_BUFFER_BIT5_QCOM = 0x200000
gl.STENCIL_BUFFER_BIT6_QCOM = 0x400000
gl.STENCIL_BUFFER_BIT7_QCOM = 0x800000
gl.STENCIL_CLEAR_VALUE = 0xb91
gl.STENCIL_EXT = 0x1802
gl.STENCIL_FAIL = 0xb94
gl.STENCIL_FUNC = 0xb92
gl.STENCIL_INDEX1_OES = 0x8d46
gl.STENCIL_INDEX4_OES = 0x8d47
gl.STENCIL_INDEX8 = 0x8d48
gl.STENCIL_PASS_DEPTH_FAIL = 0xb95
gl.STENCIL_PASS_DEPTH_PASS = 0xb96
gl.STENCIL_REF = 0xb97
gl.STENCIL_TEST = 0xb90
gl.STENCIL_VALUE_MASK = 0xb93
gl.STENCIL_WRITEMASK = 0xb98
gl.STREAM_DRAW = 0x88e0
gl.SUBPIXEL_BITS = 0xd50
gl.SYNC_CONDITION_APPLE = 0x9113
gl.SYNC_FENCE_APPLE = 0x9116
gl.SYNC_FLAGS_APPLE = 0x9115
gl.SYNC_FLUSH_COMMANDS_BIT_APPLE = 0x1
gl.SYNC_GPU_COMMANDS_COMPLETE_APPLE = 0x9117
gl.SYNC_OBJECT_APPLE = 0x8a53
gl.SYNC_STATUS_APPLE = 0x9114
gl.TEXTURE = 0x1702
gl.TEXTURE0 = 0x84c0
gl.TEXTURE1 = 0x84c1
gl.TEXTURE10 = 0x84ca
gl.TEXTURE11 = 0x84cb
gl.TEXTURE12 = 0x84cc
gl.TEXTURE13 = 0x84cd
gl.TEXTURE14 = 0x84ce
gl.TEXTURE15 = 0x84cf
gl.TEXTURE16 = 0x84d0
gl.TEXTURE17 = 0x84d1
gl.TEXTURE18 = 0x84d2
gl.TEXTURE19 = 0x84d3
gl.TEXTURE2 = 0x84c2
gl.TEXTURE20 = 0x84d4
gl.TEXTURE21 = 0x84d5
gl.TEXTURE22 = 0x84d6
gl.TEXTURE23 = 0x84d7
gl.TEXTURE24 = 0x84d8
gl.TEXTURE25 = 0x84d9
gl.TEXTURE26 = 0x84da
gl.TEXTURE27 = 0x84db
gl.TEXTURE28 = 0x84dc
gl.TEXTURE29 = 0x84dd
gl.TEXTURE3 = 0x84c3
gl.TEXTURE30 = 0x84de
gl.TEXTURE31 = 0x84df
gl.TEXTURE4 = 0x84c4
gl.TEXTURE5 = 0x84c5
gl.TEXTURE6 = 0x84c6
gl.TEXTURE7 = 0x84c7
gl.TEXTURE8 = 0x84c8
gl.TEXTURE9 = 0x84c9
gl.TEXTURE_2D = 0xde1
gl.TEXTURE_3D_OES = 0x806f
gl.TEXTURE_BINDING_2D = 0x8069
gl.TEXTURE_BINDING_3D_OES = 0x806a
gl.TEXTURE_BINDING_CUBE_MAP = 0x8514
gl.TEXTURE_BINDING_EXTERNAL_OES = 0x8d67
gl.TEXTURE_BORDER_COLOR_NV = 0x1004
gl.TEXTURE_COMPARE_FUNC_EXT = 0x884d
gl.TEXTURE_COMPARE_MODE_EXT = 0x884c
gl.TEXTURE_CUBE_MAP = 0x8513
gl.TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516
gl.TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518
gl.TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851a
gl.TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515
gl.TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517
gl.TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519
gl.TEXTURE_DEPTH_QCOM = 0x8bd4
gl.TEXTURE_EXTERNAL_OES = 0x8d65
gl.TEXTURE_FORMAT_QCOM = 0x8bd6
gl.TEXTURE_HEIGHT_QCOM = 0x8bd3
gl.TEXTURE_IMAGE_VALID_QCOM = 0x8bd8
gl.TEXTURE_IMMUTABLE_FORMAT_EXT = 0x912f
gl.TEXTURE_INTERNAL_FORMAT_QCOM = 0x8bd5
gl.TEXTURE_MAG_FILTER = 0x2800
gl.TEXTURE_MAX_ANISOTROPY_EXT = 0x84fe
gl.TEXTURE_MAX_LEVEL_APPLE = 0x813d
gl.TEXTURE_MIN_FILTER = 0x2801
gl.TEXTURE_NUM_LEVELS_QCOM = 0x8bd9
gl.TEXTURE_OBJECT_VALID_QCOM = 0x8bdb
gl.TEXTURE_SAMPLES_IMG = 0x9136
gl.TEXTURE_TARGET_QCOM = 0x8bda
gl.TEXTURE_TYPE_QCOM = 0x8bd7
gl.TEXTURE_USAGE_ANGLE = 0x93a2
gl.TEXTURE_WIDTH_QCOM = 0x8bd2
gl.TEXTURE_WRAP_R_OES = 0x8072
gl.TEXTURE_WRAP_S = 0x2802
gl.TEXTURE_WRAP_T = 0x2803
gl.TIMEOUT_EXPIRED_APPLE = 0x911b
gl.TIMEOUT_IGNORED_APPLE = 0xffffffffffffffff
gl.TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE = 0x93a0
gl.TRIANGLES = 0x4
gl.TRIANGLE_FAN = 0x6
gl.TRIANGLE_STRIP = 0x5
gl.TRUE = 0x1
gl.UNKNOWN_CONTEXT_RESET_EXT = 0x8255
gl.UNPACK_ALIGNMENT = 0xcf5
gl.UNPACK_ROW_LENGTH = 0xcf2
gl.UNPACK_SKIP_PIXELS = 0xcf4
gl.UNPACK_SKIP_ROWS = 0xcf3
gl.UNSIGNALED_APPLE = 0x9118
gl.UNSIGNED_BYTE = 0x1401
gl.UNSIGNED_INT = 0x1405
gl.UNSIGNED_INT64_AMD = 0x8bc2
gl.UNSIGNED_INT_10_10_10_2_OES = 0x8df6
gl.UNSIGNED_INT_24_8_OES = 0x84fa
gl.UNSIGNED_INT_2_10_10_10_REV_EXT = 0x8368
gl.UNSIGNED_NORMALIZED_EXT = 0x8c17
gl.UNSIGNED_SHORT = 0x1403
gl.UNSIGNED_SHORT_1_5_5_5_REV_EXT = 0x8366
gl.UNSIGNED_SHORT_4_4_4_4 = 0x8033
gl.UNSIGNED_SHORT_4_4_4_4_REV_EXT = 0x8365
gl.UNSIGNED_SHORT_4_4_4_4_REV_IMG = 0x8365
gl.UNSIGNED_SHORT_5_5_5_1 = 0x8034
gl.UNSIGNED_SHORT_5_6_5 = 0x8363
gl.UNSIGNED_SHORT_8_8_APPLE = 0x85ba
gl.UNSIGNED_SHORT_8_8_REV_APPLE = 0x85bb
gl.VALIDATE_STATUS = 0x8b83
gl.VENDOR = 0x1f00
gl.VERSION = 0x1f02
gl.VERTEX_ARRAY_BINDING_OES = 0x85b5
gl.VERTEX_ARRAY_OBJECT_EXT = 0x9154
gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889f
gl.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 0x88fe
gl.VERTEX_ATTRIB_ARRAY_DIVISOR_NV = 0x88fe
gl.VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622
gl.VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886a
gl.VERTEX_ATTRIB_ARRAY_POINTER = 0x8645
gl.VERTEX_ATTRIB_ARRAY_SIZE = 0x8623
gl.VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624
gl.VERTEX_ATTRIB_ARRAY_TYPE = 0x8625
gl.VERTEX_SHADER = 0x8b31
gl.VERTEX_SHADER_BIT_EXT = 0x1
gl.VIEWPORT = 0xba2
gl.VIV_shader_binary = 0x1
gl.WAIT_FAILED_APPLE = 0x911d
gl.WRITEONLY_RENDERING_QCOM = 0x8823
gl.WRITE_ONLY_OES = 0x88b9
gl.Z400_BINARY_AMD = 0x8740
gl.ZERO = 0x0
| mit |
Movimento5StelleLazio/WebMCP | libraries/mondelefant/mondelefant_atom_connector.lua | 2 | 4670 | #!/usr/bin/env lua
local _G = _G
local _VERSION = _VERSION
local assert = assert
local error = error
local getmetatable = getmetatable
local ipairs = ipairs
local next = next
local pairs = pairs
local print = print
local rawequal = rawequal
local rawget = rawget
local rawlen = rawlen
local rawset = rawset
local select = select
local setmetatable = setmetatable
local tonumber = tonumber
local tostring = tostring
local type = type
local math = math
local string = string
local table = table
local mondelefant = require("mondelefant")
local atom = require("atom")
local _M = {}
if _ENV then
_ENV = _M
else
_G[...] = _M
setfenv(1, _M)
end
input_converters = setmetatable({}, { __mode = "k" })
input_converters["boolean"] = function(conn, value)
if value then return "TRUE" else return "FALSE" end
end
input_converters["number"] = function(conn, value)
local str = tostring(value)
if string.find(str, "^[0-9%.e%-]+$") then
return str
else
return "'NaN'"
end
end
input_converters[atom.fraction] = function(conn, value)
if value.invalid then
return "'NaN'"
else
local n, d = tostring(value.numerator), tostring(value.denominator)
if string.find(n, "^%-?[0-9]+$") and string.find(d, "^%-?[0-9]+$") then
return "(" .. n .. "::numeric / " .. d .. "::numeric)"
else
return "'NaN'"
end
end
end
input_converters[atom.date] = function(conn, value)
return conn:quote_string(tostring(value)) .. "::date"
end
input_converters[atom.timestamp] = function(conn, value)
return conn:quote_string(tostring(value)) -- don't define type
end
input_converters[atom.time] = function(conn, value)
return conn:quote_string(tostring(value)) .. "::time"
end
output_converters = setmetatable({}, { __mode = "k" })
output_converters.int8 = function(str) return atom.integer:load(str) end
output_converters.int4 = function(str) return atom.integer:load(str) end
output_converters.int2 = function(str) return atom.integer:load(str) end
output_converters.numeric = function(str) return atom.number:load(str) end
output_converters.float4 = function(str) return atom.number:load(str) end
output_converters.float8 = function(str) return atom.number:load(str) end
output_converters.bool = function(str) return atom.boolean:load(str) end
output_converters.date = function(str) return atom.date:load(str) end
local timestamp_loader_func = function(str)
local year, month, day, hour, minute, second = string.match(
str,
"^([0-9][0-9][0-9][0-9])%-([0-9][0-9])%-([0-9][0-9]) ([0-9]?[0-9]):([0-9][0-9]):([0-9][0-9])"
)
if year then
return atom.timestamp{
year = tonumber(year),
month = tonumber(month),
day = tonumber(day),
hour = tonumber(hour),
minute = tonumber(minute),
second = tonumber(second)
}
else
return atom.timestamp.invalid
end
end
output_converters.timestamp = timestamp_loader_func
output_converters.timestamptz = timestamp_loader_func
local time_loader_func = function(str)
local hour, minute, second = string.match(
str,
"^([0-9]?[0-9]):([0-9][0-9]):([0-9][0-9])"
)
if hour then
return atom.time{
hour = tonumber(hour),
minute = tonumber(minute),
second = tonumber(second)
}
else
return atom.time.invalid
end
end
output_converters.time = time_loader_func
output_converters.timetz = time_loader_func
mondelefant.postgresql_connection_prototype.type_mappings = {
int8 = atom.integer,
int4 = atom.integer,
int2 = atom.integer,
bool = atom.boolean,
date = atom.date,
timestamp = atom.timestamp,
time = atom.time,
text = atom.string,
varchar = atom.string,
}
function mondelefant.postgresql_connection_prototype.input_converter(conn, value, info)
if value == nil then
return "NULL"
else
local converter =
input_converters[getmetatable(value)] or
input_converters[type(value)]
if converter then
return converter(conn, value)
else
return conn:quote_string(tostring(value))
end
end
end
function mondelefant.postgresql_connection_prototype.output_converter(conn, value, info)
if value == nil then
return nil
else
local converter = output_converters[info.type]
if converter then
return converter(value)
else
return value
end
end
end
return _M
--[[
db = assert(mondelefant.connect{engine='postgresql', dbname='test'})
result = db:query{'SELECT ? + 1', atom.date{ year=1999, month=12, day=31}}
print(result[1][1].year)
--]]
| mit |
silverhammermba/awesome | tests/examples/wibox/container/arcchart/border_width.lua | 1 | 1158 | --DOC_HIDE_ALL
local parent = ...
local wibox = require( "wibox" )
local beautiful = require( "beautiful" )
local cols = {"#ff000022","#00ff0022","#0000ff22","#ff00ff22"}
local l = wibox.layout.fixed.horizontal()
l.spacing = 10
parent:add(l)
for _, v in ipairs {0,1,3,6.5} do
l:add(wibox.widget {
{
{
{
text = v,
align = "center",
valign = "center",
widget = wibox.widget.textbox,
},
bg= "#ff000044",
widget = wibox.container.background,
},
colors = {
beautiful.bg_normal,
beautiful.bg_highlight,
beautiful.border_color,
},
values = {
1,
2,
3,
},
max_value = 10,
min_value = 0,
rounded_edge = false,
bg = "#00ff0033",
border_width = v,
border_color = "#000000",
widget = wibox.container.arcchart
},
bg = cols[_],
widget = wibox.container.background
})
end
return nil, 60
| gpl-2.0 |
ioiasff/qrt | plugins/meme.lua | 637 | 5791 | local helpers = require "OAuth.helpers"
local _file_memes = './data/memes.lua'
local _cache = {}
local function post_petition(url, arguments)
local response_body = {}
local request_constructor = {
url = url,
method = "POST",
sink = ltn12.sink.table(response_body),
headers = {},
redirect = false
}
local source = arguments
if type(arguments) == "table" then
local source = helpers.url_encode_arguments(arguments)
end
request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded"
request_constructor.headers["Content-Length"] = tostring(#source)
request_constructor.source = ltn12.source.string(source)
local ok, response_code, response_headers, response_status_line = http.request(request_constructor)
if not ok then
return nil
end
response_body = json:decode(table.concat(response_body))
return response_body
end
local function upload_memes(memes)
local base = "http://hastebin.com/"
local pet = post_petition(base .. "documents", memes)
if pet == nil then
return '', ''
end
local key = pet.key
return base .. key, base .. 'raw/' .. key
end
local function analyze_meme_list()
local function get_m(res, n)
local r = "<option.*>(.*)</option>.*"
local start = string.find(res, "<option.*>", n)
if start == nil then
return nil, nil
end
local final = string.find(res, "</option>", n) + #"</option>"
local sub = string.sub(res, start, final)
local f = string.match(sub, r)
return f, final
end
local res, code = http.request('http://apimeme.com/')
local r = "<option.*>(.*)</option>.*"
local n = 0
local f, n = get_m(res, n)
local ult = {}
while f ~= nil do
print(f)
table.insert(ult, f)
f, n = get_m(res, n)
end
return ult
end
local function get_memes()
local memes = analyze_meme_list()
return {
last_time = os.time(),
memes = memes
}
end
local function load_data()
local data = load_from_file(_file_memes)
if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then
data = get_memes()
-- Upload only if changed?
link, rawlink = upload_memes(table.concat(data.memes, '\n'))
data.link = link
data.rawlink = rawlink
serialize_to_file(data, _file_memes)
end
return data
end
local function match_n_word(list1, list2)
local n = 0
for k,v in pairs(list1) do
for k2, v2 in pairs(list2) do
if v2:find(v) then
n = n + 1
end
end
end
return n
end
local function match_meme(name)
local _memes = load_data()
local name = name:lower():split(' ')
local max = 0
local id = nil
for k,v in pairs(_memes.memes) do
local n = match_n_word(name, v:lower():split(' '))
if n > 0 and n > max then
max = n
id = v
end
end
return id
end
local function generate_meme(id, textup, textdown)
local base = "http://apimeme.com/meme"
local arguments = {
meme=id,
top=textup,
bottom=textdown
}
return base .. "?" .. helpers.url_encode_arguments(arguments)
end
local function get_all_memes_names()
local _memes = load_data()
local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n'
for k, v in pairs(_memes.memes) do
text = text .. '- ' .. v .. '\n'
end
text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/'
return text
end
local function callback_send(cb_extra, success, data)
if success == 0 then
send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false)
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == 'list' then
local _memes = load_data()
return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link
elseif matches[1] == 'listall' then
if not is_sudo(msg) then
return "You can't list this way, use \"!meme list\""
else
return get_all_memes_names()
end
elseif matches[1] == "search" then
local meme_id = match_meme(matches[2])
if meme_id == nil then
return "I can't match that search with any meme."
end
return "With that search your meme is " .. meme_id
end
local searchterm = string.gsub(matches[1]:lower(), ' ', '')
local meme_id = _cache[searchterm] or match_meme(matches[1])
if not meme_id then
return 'I don\'t understand the meme name "' .. matches[1] .. '"'
end
_cache[searchterm] = meme_id
print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3])
local url_gen = generate_meme(meme_id, matches[2], matches[3])
send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen})
return nil
end
return {
description = "Generate a meme image with up and bottom texts.",
usage = {
"!meme search (name): Return the name of the meme that match.",
"!meme list: Return the link where you can see the memes.",
"!meme listall: Return the list of all memes. Only admin can call it.",
'!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.',
'!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.',
},
patterns = {
"^!meme (search) (.+)$",
'^!meme (list)$',
'^!meme (listall)$',
'^!meme (.+) "(.*)" "(.*)"$',
'^!meme "(.+)" "(.*)" "(.*)"$',
"^!meme (.+) %- (.*) %- (.*)$"
},
run = run
}
| gpl-2.0 |
boundary/boundary-nagios-plugins | utils.lua | 1 | 1388 | -- Copyright 2014 Boundary,Inc.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
require("exec_proc")
math.randomseed(os.time())
function getHostName()
local exec = ExecProc:new()
exec:setPath("hostname")
exec:execute()
local hostname = string.gsub(exec:getOutput(),"\n","")
return hostname
end
function dumpTable(t)
print(t)
for i, j in pairs(t) do
print(i,j)
end
end
function getRandomValue(lower, upper)
return math.random(lower,upper)
end
function split(str, pat)
local t = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
return t
end
| apache-2.0 |
Source-Saraya/S.R.A | plugins/supergruop.lua | 1 | 95811 | local function check_member_super(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
if success == 0 then
send_large_msg(receiver, "لتبحبش لا يمكنك التحكم بلبوت🌚🖕")
end
for k,v in pairs(result) do
local member_id = v.peer_id
if member_id ~= our_id then
-- SuperGroup configuration
data[tostring(msg.to.id)] = {
group_type = 'SuperGroup',
long_id = msg.to.peer_id,
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.title, '_', ' '),
lock_arabic = 'no',
lock_link = "no",
flood = 'yes',
lock_spam = 'yes',
lock_sticker = 'no',
member = 'no',
public = 'no',
lock_rtl = 'no',
lock_contacts = 'no',
strict = 'no'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
local text = '🔰✔️تم تفعيل المجموعه✔️🔰'
return reply_msg(msg.id, text, ok_cb, false)
end
end
end
--Check Members #rem supergroup
local function check_member_superrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local text = '❌⚠️تم تعطيل المجموعه⚠️❌'
return reply_msg(msg.id, text, ok_cb, false)
end
end
end
--Function to Add supergroup
local function superadd(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg})
end
--Function to remove supergroup
local function superrem(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg})
end
--Get and output admins and bots in supergroup
local function callback(cb_extra, success, result)
local i = 1
local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ")
local member_type = cb_extra.member_type
local text = member_type.." for "..chat_name..":\n"
for k,v in pairsByKeys(result) do
if not v.first_name then
name = " "
else
vname = v.first_name:gsub("", "")
name = vname:gsub("_", " ")
end
text = text.."\n"..i.." - "..name.."["..v.peer_id.."]"
i = i + 1
end
send_large_msg(cb_extra.receiver, text)
end
--Get and output info about supergroup
local function callback_info(cb_extra, success, result)
local title =" 🔰معلومات المجموعه : ["..result.title.."]\n\n"
local admin_num = "🔰 عدد الادمنيه : "..result.admins_count.."\n"
local user_num = "🔰عدد الاعضاء : "..result.participants_count.."\n"
local kicked_num = " 🔰الاعضاء المتفاعلون: "..result.kicked_count.."\n"
local channel_id = "🔰ايدي المجموعه 🆔: "..result.peer_id.."\n"
if result.username then
channel_username = "🔰معرف المجموعه : @"..result.username
else
channel_username = ""
end
local text = title..admin_num..user_num..kicked_num..channel_id..channel_username
send_large_msg(cb_extra.receiver, text)
end
--Get and output members of supergroup
local function callback_who(cb_extra, success, result)
local text = "👻 اعضاء المجموعه 👻"..cb_extra.receiver
local i = 1
for k,v in pairsByKeys(result) do
if not v.print_name then
name = " "
else
vname = v.print_name:gsub("", "")
name = vname:gsub("_", " ")
end
if v.username then
username = " @"..v.username
else
username = ""
end
text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n"
--text = text.."\n"..username
i = i + 1
end
local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w")
file:write(text)
file:flush()
file:close()
send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false)
post_msg(cb_extra.receiver, text, ok_cb, false)
end
--Get and output list of kicked users for supergroup
local function callback_kicked(cb_extra, success, result)
--vardump(result)
local text = "🔰قائمه ايديات الاعضاء 🆔"..cb_extra.receiver.."\n\n"
local i = 1
for k,v in pairsByKeys(result) do
if not v.print_name then
name = " "
else
vname = v.print_name:gsub("", "")
name = vname:gsub("_", " ")
end
if v.username then
name = name.." @"..v.username
end
text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n"
i = i + 1
end
local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w")
file:write(text)
file:flush()
file:close()
send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false)
--send_large_msg(cb_extra.receiver, text)
end
--Begin supergroup locks
local function lock_group_links(msg, data, target)
if not is_momod(msg) then
return
end
local group_ads_lock = data[tostring(target)]['settings']['lock_ads']
if group_ads_lock == 'yes' then
return '{الروابط بالفعل ✔️مقفولة🔐🌚❤️}[@'..msg.from.username..']'
else
data[tostring(target)]['settings']['lock_ads'] = 'yes'
save_data(_config.moderation.data, data)
return '❤️🌚تم ✔️قفل🔐 الروابط في المجموعه كبد عمري\n@'..msg.from.username..''
end
end
local function unlock_group_ads(msg, data, target)
if not is_momod(msg) then
return
end
local group_ads_lock = data[tostring(target)]['settings']['lock_ads']
if group_ads_lock == 'no' then
return 'الروابط بالفعل ✔️مفتوحه🔓🌚\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['lock_ads'] = 'no'
save_data(_config.moderation.data, data)
return 'تم ✔️فتح🔐 الروابط في المجموعه كبد عمري❤️🌚\n@'..msg.from.username..''
end
end
local function lock_group_spam(msg, data, target)
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return " لتبحبش"
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'yes' then
return 'الكلايش مقفولة 🔐بالفعل🌚❤️@'..msg.from.username..''
else
data[tostring(target)]['settings']['lock_spam'] = 'yes'
save_data(_config.moderation.data, data)
return 'تم ✔️قفل🔐 الكلايش🌚❤️\n@'..msg.from.username..''
end
end
local function unlock_group_spam(msg, data, target)
if not is_momod(msg) then
return
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'no' then
return 'الكلايش مفتوحه 🔓بالفعل🌚❤️\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['lock_spam'] = 'no'
save_data(_config.moderation.data, data)
return 'تم ✔️فتح 🔓 الكلايش🌚❤️\n@'..msg.from.username..''
end
end
local function lock_group_flood(msg, data, target)
if not is_momod(msg) then
return
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'التكرار ♻️مقفول 🔐بالفعل🌚❤️\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'تم ✔️قفل🔐 التكرار🌚❤️\n@'..msg.from.username..''
end
end
local function unlock_group_flood(msg, data, target)
if not is_momod(msg) then
return
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'التكرار ♻️مفتوح 🔓بالفعل🌚❤️\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return '{}\n[@'..msg.from.username..']'
end
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'اللغة العربيه مقفولة 🔐بالفعل🌚❤️\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'تم ✔️قفل🔐 العربيه❤️🌚\n@'..msg.from.username..''
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'اللغة العربيه مفتوحه 🔓بالفعل🌚❤️\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'تم ✔️فتح🔓 العربيه❤️🌚\n@'..msg.from.username..''
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'الاضافة مقفولة 🔐بالفعل🌚❤️\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'تم ✔️قفل🔐 الاضافه🌚❤️\n@'..msg.from.username..''
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'الاضافة مفتوحه 🔓بالفعل🌚❤️\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'تم ✔️فتح 🔓الاضافه🌚❤️\n@'..msg.from.username..''
end
end
local function lock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'yes' then
return 'الاضافة الجماعيه مفتوحه 🔓بالفعل🌚❤️\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['lock_rtl'] = 'yes'
save_data(_config.moderation.data, data)
return 'تم ✔️قفل 🔐الاضافة الجماعيه🌚❤️\n@'..msg.from.username..''
end
end
local function unlock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'no' then
return 'الاضافة الجماعية مفتوحه 🔐بالفعل🌚❤️\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['lock_rtl'] = 'no'
save_data(_config.moderation.data, data)
return 'تم✔️ فتح 🔓الاضافة الجماعيه🌚❤️\n@'..msg.from.username..''
end
end
local function lock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return 'الملصقات مقفولة 🔐بالفعل🌚❤️\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
return 'تم ✔️قفل🔐 الملصقات🌚❤️\n@'..msg.from.username..''
end
end
local function unlock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return 'الملصقات مفتوحه 🔓بالفعل🌚❤️\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'تم ✔️فتح🔓 الملصقات🌚❤️\n@'..msg.from.username..''
end
end
local function lock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'yes' then
return 'جهات الاتصال مقفولة🔐 بالفعل🌚❤️\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['lock_contacts'] = 'yes'
save_data(_config.moderation.data, data)
return 'تم✔️ قفل🔐 جهات اتصال🌚❤️\n@'..msg.from.username..''
end
end
local function unlock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'no' then
return 'جهات الاتصال مفتوحه🔓 بالفعل🌚❤️\n@'..msg.from.username..''
else
data[tostring(target)]['settings']['lock_contacts'] = 'no'
save_data(_config.moderation.data, data)
return 'تم✔️فتح🔓 جهات اتصال🌚❤️\n@'..msg.from.username..''
end
end
local function enable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_strict_lock = data[tostring(target)]['settings']['strict']
if group_strict_lock == 'yes' then
return 'الاعدادت⚙ مقفولة🔐 بالفعل🌚❤️\n@'..msg.from.username..']'
else
data[tostring(target)]['settings']['strict'] = 'yes'
save_data(_config.moderation.data, data)
return 'تم✔️ قفل 🔐الاعدادات🌚❤️\n@'..msg.from.username..''
end
end
local function disable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_strict_lock = data[tostring(target)]['settings']['strict']
if group_strict_lock == 'no' then
return ' الاعدادت⚙ مقفولة🔐 بالفعل🌚❤️@'..msg.from.username..''
else
data[tostring(target)]['settings']['strict'] = 'no'
save_data(_config.moderation.data, data)
return 'تم ✔️فتح 🔓جميع الاعدادات⚙🌚❤️\n@'..msg.from.username..''
end
end
--End supergroup locks
--'Set supergroup rules' function
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return '⚜تم وضع القوانين⚜'
end
--'Get supergroup rules' function
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return '❌لا توجد قوانين❌'
end
local rules = data[tostring(msg.to.id)][data_cat]
local group_name = data[tostring(msg.to.id)]['settings']['set_name']
local rules = group_name..' 🔰القوانين🔰\n\n'..rules:gsub("/n", " ")
return rules
end
--Set supergroup to public or not public function
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "لتبحبش لا يمكنك التحكم بلبوت🌚🖕"
end
local group_public_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
if group_public_lock == 'yes' then
return '{بالفعل عامه}[@'..msg.from.username..']'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return '{اصبحت عامه}\n[@'..msg.from.username..']'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_public_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
if group_public_lock == 'no' then
return '{غير عامه}[@'..msg.from.username..']'
else
data[tostring(target)]['settings']['public'] = 'no'
data[tostring(target)]['long_id'] = msg.to.long_id
save_data(_config.moderation.data, data)
return '{ليست عامه}\n[@'..msg.from.username..']'
end
end
--Show supergroup settings; function
function show_supergroup_settingsmod(msg, target)
if not is_momod(msg) then
return
end
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['public'] then
data[tostring(target)]['settings']['public'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_rtl'] then
data[tostring(target)]['settings']['lock_rtl'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_member'] then
data[tostring(target)]['settings']['lock_member'] = 'no'
end
end
local settings = data[tostring(target)]['settings']
local text = "🔰 اعـدادات الـمـجـ🤖ـمـوعـه 🔰\n🔒قفل الروابط : "..settings.lock_link.."\n🔒 قفل التكرار : "..settings.flood.."\n🔰 عدد التكرار : "..NUM_MSG_MAX.."\n🔒 قفل الكلايش الطويله: "..settings.lock_spam.."\n🔒 قفل اللغه العربيه: "..settings.lock_arabic.."\n🔰🔒 قفل الاضافه: "..settings.lock_member.."\n🔒 قفل المغادره: "..settings.lock_rtl.."\n🔒 قفل الملصقات: "..settings.lock_sticker.."\n 🔰المراقبه: "..settings.public.."\n🔒🔰 قفل جميع الاعدادات: "..settings.strict
return text
end
local function promote_admin(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
local member_tag_username = string.gsub(member_username, '@', '(at)')
if not data[group] then
return
end
if data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username..'هوة بالفعل✔️ ضمن الادمنيه🌚❤️ ')
end
data[group]['moderators'][tostring(user_id)] = member_tag_username
save_data(_config.moderation.data, data)
end
local function demote_admin(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
if not data[group] then
return
end
if not data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_tag_username..'هوة بالفعل✔️ ضمن الاعضاء👤🌚❤️')
end
data[group]['moderators'][tostring(user_id)] = nil
save_data(_config.moderation.data, data)
end
local function promote2(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
local member_tag_username = string.gsub(member_username, '@', '(at)')
if not data[group] then
return send_large_msg(receiver, '⚠️❌المجموعه ليست مفعلة❌⚠️')
end
if data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username..'هوة بالفعل✔️ ضمن الادمنيه🌚❤️')
end
data[group]['moderators'][tostring(user_id)] = member_tag_username
save_data(_config.moderation.data, data)
send_large_msg(receiver, member_username..'تم✔️رفعك ادمن 👱🏻كبد روحي شد حيلك🌚❤️')
end
local function demote2(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
if not data[group] then
return '⚠️❌المجموعه ليست مفعلة❌⚠️'
end
if not data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username..'تم ✔️تنزيلك ❌من الادمنيه لانك وكح🌚❤️')
end
data[group]['moderators'][tostring(user_id)] = nil
save_data(_config.moderation.data, data)
send_large_msg(receiver, member_username..'تم ✔️تنزيلك ❌من الادمنيه لانك وكح🌚❤️')
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return '⚠️❌المجموعه ليست مفعلة❌⚠️'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then
return 'لا يوجد ادمنيه '
end
local i = 1
local message = '\n 🔰قائمه الادمنيه🔰 ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
-- Start by reply actions
function get_message_callback(extra, success, result)
local get_cmd = extra.get_cmd
local msg = extra.msg
local data = load_data(_config.moderation.data)
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
if get_cmd == "ايدي" and not result.action then
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]")
id1 = send_large_msg(channel, result.from.peer_id)
elseif get_cmd == 'ايدي' and result.action then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
else
user_id = result.peer_id
end
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]")
id1 = send_large_msg(channel, user_id)
end
elseif get_cmd == "idfrom" then
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]")
id2 = send_large_msg(channel, result.fwd_from.peer_id)
elseif get_cmd == 'channel_block' and not result.action then
local member_id = result.from.peer_id
local channel_id = result.to.peer_id
if member_id == msg.from.id then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then
return send_large_msg("channel#id"..channel_id, "لتبحبش لا يمكنك طرد الاادمن او المدير🌚🖕")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "لتبحبش لا يمكنك طرد الاادمن او المدير🌚🖕")
end
--savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply")
kick_user(member_id, channel_id)
elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then
local user_id = result.action.user.peer_id
local channel_id = result.to.peer_id
if member_id == msg.from.id then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then
return send_large_msg("channel#id"..channel_id, "لتبحبش لا يمكنك طرد الاادمن او المدير🌚🖕")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "لتبحبش لا يمكنك طرد الاادمن او المدير🌚🖕")
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.")
kick_user(user_id, channel_id)
elseif get_cmd == "مسح" then
delete_msg(result.id, ok_cb, false)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply")
elseif get_cmd == "رفع اداري" then
local user_id = result.from.peer_id
local channel_id = "channel#id"..result.to.peer_id
channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false)
if result.from.username then
text = "@"..result.from.username.." تم رفعك في الادارة كبد ضلعي🌚❤️"
else
text = "[ "..user_id.." ] تم رفعك في الادارة كبد ضلعي🌚❤️ "
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply")
send_large_msg(channel_id, text)
elseif get_cmd == "تنزيل اداري" then
local user_id = result.from.peer_id
local channel_id = "channel#id"..result.to.peer_id
if is_admin2(result.from.peer_id) then
return send_large_msg(channel_id, "لتبحبش لا يمكنك تنزيل اداري🌚🖕 ")
end
channel_demote(channel_id, "user#id"..user_id, ok_cb, false)
if result.from.username then
text = "@"..result.from.username.." عمت عيني عليك تم ✔️تنزيلك ⚠️من الادارة🌚😹 "
else
text = "[ "..user_id.." ] عمت عيني عليك تم ✔️تنزيلك ⚠️من الادارة🌚😹"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply")
send_large_msg(channel_id, text)
elseif get_cmd == "رفع المدير" then
local group_owner = data[tostring(result.to.peer_id)]['set_owner']
if group_owner then
local channel_id = 'channel#id'..result.to.peer_id
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(channel_id, user, ok_cb, false)
end
local user_id = "user#id"..result.from.peer_id
channel_set_admin(channel_id, user_id, ok_cb, false)
data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply")
if result.from.username then
text = "@"..result.from.username.." [ "..result.from.peer_id.." ] شد حيلك رفعوك مدير ضلعي🌚❤️ "
else
text = "[ "..result.from.peer_id.." ] شد حيلك رفعوك مدير ضلعي🌚❤️"
end
send_large_msg(channel_id, text)
end
elseif get_cmd == "رفع ادمن" then
local receiver = result.to.peer_id
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
local member_name = full_name:gsub("", "")
local member_username = member_name:gsub("_", " ")
if result.from.username then
member_username = '@'.. result.from.username
end
local member_id = result.from.peer_id
if result.to.peer_type == 'channel' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply")
promote2("channel#id"..result.to.peer_id, member_username, member_id)
--channel_set_mod(channel_id, user, ok_cb, false)
end
elseif get_cmd == "تنزيل ادمن" then
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
local member_name = full_name:gsub("", "")
local member_username = member_name:gsub("_", " ")
if result.from.username then
member_username = '@'.. result.from.username
end
local member_id = result.from.peer_id
--local user = "user#id"..result.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] تنزيل ادمن: @"..member_username.."["..result.from.peer_id.."] by reply")
demote2("channel#id"..result.to.peer_id, member_username, member_id)
--channel_demote(channel_id, user, ok_cb, false)
elseif get_cmd == 'mute_user' then
if result.service then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
end
end
if action == 'chat_add_user_link' then
if result.from then
user_id = result.from.peer_id
end
end
else
user_id = result.from.peer_id
end
local receiver = extra.receiver
local chat_id = msg.to.id
print(user_id)
print(chat_id)
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
send_large_msg(receiver, "["..user_id.."] راح الكتم منك دردش بحي بس صير عاقل🌚😹 ")
elseif is_admin1(msg) then
mute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] هيج احسلك تم كتمك🌚💔")
end
end
end
-- End by reply actions
--By ID actions
local function cb_user_info(extra, success, result)
local receiver = extra.receiver
local user_id = result.peer_id
local get_cmd = extra.get_cmd
local data = load_data(_config.moderation.data)
--[[if get_cmd == "setadmin" then
local user_id = "user#id"..result.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been set as an admin"
else
text = "[ "..result.peer_id.." ] has been set as an admin"
end
send_large_msg(receiver, text)]]
if get_cmd == "تنزيل اداري" then
if is_admin2(result.peer_id) then
return send_large_msg(receiver, " لتبحبش لا يمكنك تنزيل اداري🌚🖕")
end
local user_id = "user#id"..result.peer_id
channel_demote(receiver, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." عمت عيني عليك تم ✔️تنزيلك ⚠️من الادارة🌚😹 "
send_large_msg(receiver, text)
else
text = "[ "..result.peer_id.." ] عمت عيني عليك تم ✔️تنزيلك ⚠️من الادارة🌚😹 "
send_large_msg(receiver, text)
end
elseif get_cmd == "رفع ادمن" then
if result.username then
member_username = "@"..result.username
else
member_username = string.gsub(result.print_name, '_', ' ')
end
promote2(receiver, member_username, user_id)
elseif get_cmd == "تنزيل ادمن" then
if result.username then
member_username = "@"..result.username
else
member_username = string.gsub(result.print_name, '_', ' ')
end
demote2(receiver, member_username, user_id)
end
end
-- Begin resolve username actions
local function callbackres(extra, success, result)
local member_id = result.peer_id
local member_username = "@"..result.username
local get_cmd = extra.get_cmd
if get_cmd == "الايدي" then
local user = result.peer_id
local name = string.gsub(result.print_name, "_", " ")
local channel = 'channel#id'..extra.channelid
send_large_msg(channel, user..'\n'..name)
return user
elseif get_cmd == "ايدي" then
local user = result.peer_id
local channel = 'channel#id'..extra.channelid
send_large_msg(channel, user)
return user
elseif get_cmd == "invite" then
local receiver = extra.channel
local user_id = "user#id"..result.peer_id
channel_invite(receiver, user_id, ok_cb, false)
--[[elseif get_cmd == "channel_block" then
local user_id = result.peer_id
local channel_id = extra.channelid
local sender = extra.sender
if member_id == sender then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(sender) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
kick_user(user_id, channel_id)
elseif get_cmd == "setadmin" then
local user_id = "user#id"..result.peer_id
local channel_id = extra.channel
channel_set_admin(channel_id, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been set as an admin"
send_large_msg(channel_id, text)
else
text = "@"..result.peer_id.." has been set as an admin"
send_large_msg(channel_id, text)
end
elseif get_cmd == "setowner" then
local receiver = extra.channel
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = extra.from_id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
local user = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_demote(receiver, user, ok_cb, false)
end
local user_id = "user#id"..result.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
data[tostring(channel)]['set_owner'] = tostring(result.peer_id)
save_data(_config.moderation.data, data)
savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username")
if result.username then
text = member_username.." [ "..result.peer_id.." ] added as owner"
else
text = "[ "..result.peer_id.." ] added as owner"
end
send_large_msg(receiver, text)
end]]
elseif get_cmd == "رفع ادمن" then
local receiver = extra.channel
local user_id = result.peer_id
--local user = "user#id"..result.peer_id
promote2(receiver, member_username, user_id)
--channel_set_mod(receiver, user, ok_cb, false)
elseif get_cmd == "تنزيل ادمن" then
local receiver = extra.channel
local user_id = result.peer_id
local user = "user#id"..result.peer_id
demote2(receiver, member_username, user_id)
elseif get_cmd == "تنزيل اداري" then
local user_id = "user#id"..result.peer_id
local channel_id = extra.channel
if is_admin2(result.peer_id) then
return send_large_msg(receiver, "لتبحبش لا يمكنك تنزيل اداري🌚🖕")
end
channel_demote(channel_id, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.."عمت عيني عليك تم ✔️تنزيلك ⚠️من الادارة🌚😹 "
send_large_msg(channel_id, text)
else
text = "@"..result.peer_id.."عمت عيني عليك تم ✔️تنزيلك ⚠️من الادارة🌚😹 "
send_large_msg(channel_id, text)
end
local receiver = extra.channel
local user_id = result.peer_id
demote_admin(receiver, member_username, user_id)
elseif get_cmd == 'mute_user' then
local user_id = result.peer_id
local receiver = extra.receiver
local chat_id = string.gsub(receiver, 'channel#id', '')
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] removed from muted user list")
elseif is_owner(extra.msg) then
mute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] added to muted user list")
end
end
end
--End resolve username actions
--Begin non-channel_invite username actions
local function in_channel_cb(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local msg = cb_extra.msg
local data = load_data(_config.moderation.data)
local print_name = user_print_name(cb_extra.msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
local member = cb_extra.username
local memberid = cb_extra.user_id
if member then
text = 'لايوجد عضو @'..member..' في هذه المجموعه.'
else
text = 'لايوجد عضو ['..memberid..'] في هذه المجموعه.'
end
if get_cmd == "channel_block" then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local user_id = v.peer_id
local channel_id = cb_extra.msg.to.id
local sender = cb_extra.msg.from.id
if user_id == sender then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(user_id, channel_id) and not is_admin2(sender) then
return send_large_msg("channel#id"..channel_id, "لتبحبش لا يمكنك طرد الاادمن او المدير🌚🖕")
end
if is_admin2(user_id) then
return send_large_msg("channel#id"..channel_id, "لتبحبش لا يمكنك طرد الاداري🌚🖕")
end
if v.username then
text = ""
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]")
else
text = ""
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]")
end
kick_user(user_id, channel_id)
return
end
end
elseif get_cmd == "رفع اداري" then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local user_id = "user#id"..v.peer_id
local channel_id = "channel#id"..cb_extra.msg.to.id
channel_set_admin(channel_id, user_id, ok_cb, false)
if v.username then
text = "@"..v.username.." ["..v.peer_id.."]تم رفعك في الادارة كبد ضلعي🌚❤️"
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]")
else
text = "["..v.peer_id.."] تم رفعك في الادارة كبد ضلعي🌚❤️"
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id)
end
if v.username then
member_username = "@"..v.username
else
member_username = string.gsub(v.print_name, '_', ' ')
end
local receiver = channel_id
local user_id = v.peer_id
promote_admin(receiver, member_username, user_id)
end
send_large_msg(channel_id, text)
return
end
elseif get_cmd == 'رفع المدير' then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = cb_extra.msg.from.id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(receiver, user, ok_cb, false)
end
local user_id = "user#id"..v.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
data[tostring(channel)]['set_owner'] = tostring(v.peer_id)
save_data(_config.moderation.data, data)
savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username")
if result.username then
text = member_username.." ["..v.peer_id.."] شد حيلك رفعوك مدير ضلعي🌚❤️ "
else
text = "["..v.peer_id.."] شد حيلك رفعوك مدير ضلعي🌚❤️ "
end
end
elseif memberid and vusername ~= member and vpeer_id ~= memberid then
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = cb_extra.msg.from.id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(receiver, user, ok_cb, false)
end
data[tostring(channel)]['set_owner'] = tostring(memberid)
save_data(_config.moderation.data, data)
savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username")
text = "["..memberid.."] ❤️🌚شد حيلك رفعوك ضلعي"
end
end
end
end
send_large_msg(receiver, text)
end
--End non-channel_invite username actions
--'Set supergroup photo' function
local function set_supergroup_photo(msg, success, result)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return
end
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
channel_set_photo(receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
--Run function
local function run(msg, matches)
if msg.to.type == 'chat' then
if matches[1] == 'ترقيه سوبر' then
if not is_admin1(msg) then
return
end
local receiver = get_receiver(msg)
chat_upgrade(receiver, ok_cb, false)
end
elseif msg.to.type == 'channel'then
if matches[1] == 'ترقيه سوبر' then
if not is_admin1(msg) then
return
end
return "المجموعه 👥سوبر بالفعل✔️"
end
end
if msg.to.type == 'channel' then
local support_id = msg.from.id
local receiver = get_receiver(msg)
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
local data = load_data(_config.moderation.data)
if matches[1] == 'تفعيل' and not matches[2] then
if not is_admin1(msg) and not is_support(support_id) then
return
end
if is_super_group(msg) then
return reply_msg(msg.id, '❌⚠️المجموعه معطله بالفعل⚠️❌', ok_cb, false)
end
print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup")
superadd(msg)
set_mutes(msg.to.id)
channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false)
end
if matches[1] == 'تعطيل' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then
return reply_msg(msg.id, '❌⚠️المجموعه معطله بالفعل⚠️❌', ok_cb, false)
end
print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed")
superrem(msg)
rem_mutes(msg.to.id)
end
if not data[tostring(msg.to.id)] then
return
end
if matches[1] == "معلومات المجموعه" then
if not is_owner(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info")
channel_info(receiver, callback_info, {receiver = receiver, msg = msg})
end
if matches[1] == "الاداريين" then
if not is_owner(msg) and not is_support(msg.from.id) then
return
end
member_type = '⚜قائمه الاداريين⚜'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list")
admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type})
end
if matches[1] == "مدير المجموعه" then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "❌لا يوجد مدير❌"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return " مدير المجموعة المحترم ["..group_owner..']'
end
if matches[1] == "الادمنيه" then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
-- channel_get_admins(receiver,callback, {receiver = receiver})
end
if matches[1] == "كشف بوت" and is_momod(msg) then
member_type = '🔰✔️تم كشف البوتات✔️🔰'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list")
channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type})
end
if matches[1] == "ايدي الاعضاء" and not matches[2] and is_momod(msg) then
local user_id = msg.from.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list")
channel_get_users(receiver, callback_who, {receiver = receiver})
end
if matches[1] == "kicked" and is_momod(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list")
channel_get_kicked(receiver, callback_kicked, {receiver = receiver})
end
if matches[1] == 'مسح' and is_momod(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'مسح',
msg = msg
}
delete_msg(msg.id, ok_cb, false)
get_message(msg.reply_id, get_message_callback, cbreply_extra)
end
end
if matches[1] == 'بلوك' and is_momod(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'channel_block',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'بلوك' and string.match(matches[2], '^%d+$') then
--[[local user_id = matches[2]
local channel_id = msg.to.id
if is_momod2(user_id, channel_id) and not is_admin2(user_id) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]")
kick_user(user_id, channel_id)]]
local get_cmd = 'channel_block'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif msg.text:match("@[%a%d]") then
--[[local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'channel_block',
sender = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username)
resolve_username(username, callbackres, cbres_extra)]]
local get_cmd = 'channel_block'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'ايدي' then
if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then
local cbreply_extra = {
get_cmd = 'ايدي',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then
local cbreply_extra = {
get_cmd = 'idfrom',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif msg.text:match("@[%a%d]") then
local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'ايدي'
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username)
resolve_username(username, callbackres, cbres_extra)
else
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID")
return "ايدي المجموعه ☑️"..string.gsub(msg.to.print_name, "_", " ")..": "..msg.to.id
end
end
if matches[1] == 'دعبلني' then
if msg.to.type == 'channel' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] left via kickme")
channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if matches[1] == 'تغير الرابط' and is_momod(msg)then
local function callback_link (extra , success, result)
local receiver = get_receiver(msg)
if success == 0 then
send_large_msg(receiver, '🚫 عذرٱ ⚠️لا يمكنك تغيير الرابط \nالمجموعه 👥 ليست من صنع البوت 🚫\n\nيرجى استخدام ❗️الرابط الخاص بها في عدادات المجموعه 🚫')
data[tostring(msg.to.id)]['settings']['set_link'] = nil
save_data(_config.moderation.data, data)
else
send_large_msg(receiver, "⚜تم تغير رابط المجموعه⚜")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link")
export_channel_link(receiver, callback_link, false)
end
if matches[1] == 'ضع رابط' and is_owner(msg) then
data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting'
save_data(_config.moderation.data, data)
return '⚜ارسل رابط المجموعه لحفظه🔰'
end
if msg.text then
if msg.text:match("^(https://t.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_ads'] == 'waiting' and is_owner(msg) then
data[tostring(msg.to.id)]['settings']['set_ads'] = msg.text
save_data(_config.moderation.data, data)
return "⚜تم حفظ الرابط⚜"
end
end
if matches[1] == 'الرابط' then
if not is_momod(msg) then
return
end
local group_ads = data[tostring(msg.to.id)]['settings']['set_ads']
if not group_ads then
return "يرجى ارسال تغير الرابط لتغير رابط المجموعه🌚❤️"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "🔰رابط المجموعه🔰:\n"..group_link
end
if matches[1] == "invite" and is_sudo(msg) then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = "invite"
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username)
resolve_username(username, callbackres, cbres_extra)
end
if matches[1] == 'الايدي' and is_owner(msg) then
local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'الايدي'
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username)
resolve_username(username, callbackres, cbres_extra)
end
--[[if matches[1] == 'kick' and is_momod(msg) then
local receiver = channel..matches[3]
local user = "user#id"..matches[2]
chaannel_kick(receiver, user, ok_cb, false)
end]]
if matches[1] == 'رفع اداري' then
if not is_support(msg.from.id) and not is_owner(msg) then
return
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'رفع اداري',
msg = msg
}
setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'رفع اداري' and string.match(matches[2], '^%d+$') then
--[[] local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'setadmin'
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]]
local get_cmd = 'رفع اداري'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif matches[1] == 'رفع اداري' and not string.match(matches[2], '^%d+$') then
--[[local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'setadmin'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username)
resolve_username(username, callbackres, cbres_extra)]]
local get_cmd = 'رفع اداري'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'تنزيل اداري' then
if not is_support(msg.from.id) and not is_owner(msg) then
return
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'تنزيل اداري',
msg = msg
}
demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'تنزيل اداري' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'تنزيل اداري'
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == 'تنزيل اداري' and not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'تنزيل اداري'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username)
resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == 'رفع المدير' and is_owner(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'رفع المدير',
msg = msg
}
setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'رفع المدير' and string.match(matches[2], '^%d+$') then
--[[ local group_owner = data[tostring(msg.to.id)]['set_owner']
if group_owner then
local receiver = get_receiver(msg)
local user_id = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_demote(receiver, user_id, ok_cb, false)
end
local user = "user#id"..matches[2]
channel_set_admin(receiver, user, ok_cb, false)
data[tostring(msg.to.id)]['set_owner'] = tostring(matches[2])
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = "[ "..matches[2].." ] added as owner"
return text
end]]
local get_cmd = 'رفع المدير'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif matches[1] == 'رفع المدير' and not string.match(matches[2], '^%d+$') then
local get_cmd = 'رفع المدير'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'رفع ادمن' then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "لتبحبش🌚🖕"
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'رفع ادمن',
msg = msg
}
promote = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'رفع ادمن' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'رفع ادمن'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2])
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == 'رفع ادمن' and not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'رفع ادمن',
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == 'mp' and is_sudo(msg) then
channel = get_receiver(msg)
user_id = 'user#id'..matches[2]
channel_set_mod(channel, user_id, ok_cb, false)
return "ok"
end
if matches[1] == 'md' and is_sudo(msg) then
channel = get_receiver(msg)
user_id = 'user#id'..matches[2]
channel_demote(channel, user_id, ok_cb, false)
return "ok"
end
if matches[1] == 'تنزيل ادمن' then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "لتبحبش🌚🖕"
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'تنزيل ادمن',
msg = msg
}
demote = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'تنزيل ادمن' and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'تنزيل ادمن'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2])
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'تنزيل ادمن'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == "ضع اسم" and is_momod(msg) then
local receiver = get_receiver(msg)
local set_name = string.gsub(matches[2], '_', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2])
rename_channel(receiver, set_name, ok_cb, false)
end
if msg.service and msg.action.type == 'chat_rename' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title)
data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title
save_data(_config.moderation.data, data)
end
if matches[1] == "ضع وصف" and is_momod(msg) then
local receiver = get_receiver(msg)
local about_text = matches[2]
local data_cat = 'description'
local target = msg.to.id
data[tostring(target)][data_cat] = about_text
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text)
channel_set_about(receiver, about_text, ok_cb, false)
return "تم تعين الوصف\n\nاذهب الى حول لمشاهدة الوصف الجديد"
end
if matches[1] == "ضع معرف" and is_admin1(msg) then
local function ok_username_cb (extra, success, result)
local receiver = extra.receiver
if success == 1 then
send_large_msg(receiver, "تم✔️ الوضع كبدي🌚❤️\n\nاذهب الى حول لمشاهدة التغيرات")
elseif success == 0 then
send_large_msg(receiver, " فشل تعين المعرف \nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.")
end
end
local username = string.gsub(matches[2], '@', '')
channel_set_username(receiver, username, ok_username_cb, {receiver=receiver})
end
if matches[1] == 'ضع قوانين' and is_momod(msg) then
rules = matches[2]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]")
return set_rulesmod(msg, data, target)
end
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo")
load_photo(msg.id, set_supergroup_photo, msg)
return
end
end
if matches[1] == 'ضع صوره' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo")
return '🔰ارسل الصورة الان🔰'
end
if matches[1] == 'مسح' then
if not is_momod(msg) then
return
end
if not is_momod(msg) then
return "لتبحبش🌚🖕"
end
if matches[2] == 'الادمنيه' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then
return 'لا يوجد ادمنيه لمسحهم '
end
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
return ''
end
if matches[2] == 'القوانين' then
local data_cat = 'rules'
if data[tostring(msg.to.id)][data_cat] == nil then
return "لا❌ يوجد قوانين لمسحها🌚❤️"
end
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
return ''
end
if matches[2] == 'الوصف' then
local receiver = get_receiver(msg)
local about_text = 'تم✔️ مسح♻️ الوصف بنجاح🌚❤️'
local data_cat = 'description'
if data[tostring(msg.to.id)][data_cat] == nil then
return 'لا يوجد وصف لمسحه'
end
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
channel_set_about(receiver, about_text, ok_cb, false)
return "تم✔️ مسح♻️ القائمة 📋بعد روحي🌚❤️"
end
if matches[2] == 'المكتومين' then
chat_id = msg.to.id
local hash = 'mute_user:'..chat_id
redis:del(hash)
return ""
end
if matches[2] == 'المعرف' and is_admin1(msg) then
local function ok_username_cb (extra, success, result)
local receiver = extra.receiver
if success == 1 then
send_large_msg(receiver, "تم✔️ المسح ♻️ضلعي🌚❤️")
elseif success == 0 then
send_large_msg(receiver, "فشل❌ المسح ♻️حياتي🌚❤️")
end
end
local username = ""
channel_set_username(receiver, username, ok_username_cb, {receiver=receiver})
end
end
if matches[1] == 'قفل' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'الروابط' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ")
return lock_group_links(msg, data, target)
end
if matches[2] == 'الكلايش' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ")
return lock_group_spam(msg, data, target)
end
if matches[2] == 'التكرار' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_flood(msg, data, target)
end
if matches[2] == 'العربيه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'الاضافه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2]:lower() == 'الاضافه الجماعيه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names")
return lock_group_rtl(msg, data, target)
end
if matches[2] == 'الملصقات' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting")
return lock_group_sticker(msg, data, target)
end
if matches[2] == 'جهات الاتصال' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting")
return lock_group_contacts(msg, data, target)
end
if matches[2] == 'الكل' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings")
return enable_strict_rules(msg, data, target)
end
end
if matches[1] == 'فتح' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'الروابط' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting")
return unlock_group_links(msg, data, target)
end
if matches[2] == 'الكلايش' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam")
return unlock_group_spam(msg, data, target)
end
if matches[2] == 'التكرار' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood")
return unlock_group_flood(msg, data, target)
end
if matches[2] == 'العربيه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked Arabic")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'الاضافه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2]:lower() == 'الاضافه الجماعيه' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names")
return unlock_group_rtl(msg, data, target)
end
if matches[2] == 'الملصقات' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting")
return unlock_group_sticker(msg, data, target)
end
if matches[2] == 'جهات الاتصال' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting")
return unlock_group_contacts(msg, data, target)
end
if matches[2] == 'الكل' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings")
return disable_strict_rules(msg, data, target)
end
end
if matches[1] == 'ضع تكرار' then
if not is_momod(msg) then
return
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return " التكرار من 🌚❤️{5-25} 🚩"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'تم تعين التكرار🌚❤️: '..matches[2]
end
if matches[1] == 'المراقبه' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'نعم' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'لا' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: not public")
return unset_public_membermod(msg, data, target)
end
end
if matches[1] == 'قفل' and is_momod(msg) then
local chat_id = msg.to.id
if matches[2] == 'الصوت' then
local msg_type = 'Audio'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return 'تم ✔️قفل 🔐الصوتيات🌚❤️\n@'..msg.from.username..''
else
return 'الصوتيات مقفولة🔐 بالفعل🌚❤️\n@'..msg.from.username..''
end
end
if matches[2] == 'الصور' then
local msg_type = 'Photo'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return 'تم قفل الصور❤️🌚\n@'..msg.from.username..''
else
return 'الصور مقفولة 🔐بالفعل🌚❤️\n@'..msg.from.username..''
end
end
if matches[2] == 'الفيديو' then
local msg_type = 'Video'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return '🌚❤️تم قفل الفيديوهات\n@'..msg.from.username..']'
else
return 'لفيديوهات مقفولة🔐 بالفعل🌚❤️\n@'..msg.from.username..']'
end
end
if matches[2] == 'الصور المتحركه' then
local msg_type = 'Gifs'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return 'تم قفل🔐الصور المتحركه🌚❤️\n@'..msg.from.username..''
else
return 'الصور المتحركه مقفولة 🔐بالفعل🌚❤️\n@'..msg.from.username..''
end
end
if matches[2] == 'الفايلات' then
local msg_type = 'Documents'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return 'تم ✔️قفل🔐 الفايلات🌚❤️\n@'..msg.from.username..''
else
return 'الفايلات مقفولة 🔐بالفعل🌚❤️\n@'..msg.from.username..''
end
end
if matches[2] == 'الدردشه' then
local msg_type = 'Text'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return '❤️🌚تم قفل الدردشه\n@'..msg.from.username..''
else
return 'الدردشة مقفولة🔐 بالفعل🌚❤\n@'..msg.from.username..''
end
end
if matches[2] == 'المجموعه' then
local msg_type = 'All'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return 'تم ✔️قفل 🔐المجموعه🌚❤️\n[@'..msg.from.username..''
else
return 'لمجموعه مقفولة🔐 بالفعل🌚❤️\n@'..msg.from.username..''
end
end
end
if matches[1] == 'فتح' and is_momod(msg) then
local chat_id = msg.to.id
if matches[2] == 'الصوت' then
local msg_type = 'Audio'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return 'تم✔️ فتح🔓 الصوتيات🌚❤️\n@'..msg.from.username..''
else
return 'الصوتيات مفتوحه🔓 بالفعل🌚❤️\n@'..msg.from.username..''
end
end
if matches[2] == 'الصور' then
local msg_type = 'Photo'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return 'تم✔️ فتح 🔓الصور🌚❤️\n@'..msg.from.username..''
else
return 'الصور مفتوحه🔓 بالفعل🌚❤️\n@'..msg.from.username..''
end
end
if matches[2] == 'الفيديو' then
local msg_type = 'Video'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return 'تم ✔️فتح🔓 الفيديوهات🌚❤️\n@'..msg.from.username..''
else
return 'لفيديوهات مفتوحه 🔓بالفعل🌚❤️\n@'..msg.from.username..''
end
end
if matches[2] == 'الصور المتحركه' then
local msg_type = 'Gifs'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return 'تم✔️ فتح 🔓الصور المتحركة🌚❤️\n@'..msg.from.username..''
else
return 'الصور المتحركه مفتوحه 🔓بالفعل🌚❤️\n@'..msg.from.username..''
end
end
if matches[2] == 'الفايلات' then
local msg_type = 'Documents'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return 'تم✔️ فتح🔓 الفايلات🌚❤️\n@'..msg.from.username..''
else
return 'الفايلات مفتوحه🔓 بالفعل🌚❤️\n@'..msg.from.username..''
end
end
if matches[2] == 'الدردشه' then
local msg_type = 'Text'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute message")
unmute(chat_id, msg_type)
return 'تم ✔️فتح 🔓الدردشه🌚❤️\n@'..msg.from.username..''
else
return 'الدردشة مفتوحه🔓 بالفعل🌚❤️\n@'..msg.from.username..''
end
end
if matches[2] == 'المجموعه' then
local msg_type = 'All'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return 'تم✔️ فتح 🔓المجموعه🌚❤️\n@'..msg.from.username..''
else
return 'لمجموعه مفتوحه🔓 بالفعل🌚❤️@'..msg.from.username..''
end
end
end
if matches[1] == "كتم" and is_momod(msg) then
local chat_id = msg.to.id
local hash = "mute_user"..chat_id
local user_id = ""
if type(msg.reply_id) ~= "nil" then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
muteuser = get_message(msg.reply_id, get_message_callback, {receiver = receiver, get_cmd = get_cmd, msg = msg})
elseif matches[1] == "كتم" and string.match(matches[2], '^%d+$') then
local user_id = matches[2]
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list")
return "["..user_id.."] removed from the muted users list"
elseif is_momod(msg) then
mute_user(chat_id, user_id)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list")
return "["..user_id.."] added to the muted user list"
end
elseif matches[1] == "كتم" and not string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
resolve_username(username, callbackres, {receiver = receiver, get_cmd = get_cmd, msg=msg})
end
end
if matches[1] == "اعدادات الوسائط" and is_momod(msg) then
local chat_id = msg.to.id
if not has_mutes(chat_id) then
set_mutes(chat_id)
return mutes_list(chat_id)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist")
return mutes_list(chat_id)
end
if matches[1] == "المكتومين" and is_momod(msg) then
local chat_id = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist")
return muted_user_list(chat_id)
end
if matches[1] == 'الاعدادات' and is_momod(msg) then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ")
return show_supergroup_settingsmod(msg, target)
end
if matches[1] == 'القوانين' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'help' and not is_owner(msg) then
text = "Message /superhelp to @Teleseed in private for SuperGroup help"
reply_msg(msg.id, text, ok_cb, false)
elseif matches[1] == 'help' and is_owner(msg) then
local name_log = user_print_name(msg.from)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp")
return super_help()
end
if matches[1] == 'peer_id' and is_admin1(msg)then
text = msg.to.peer_id
reply_msg(msg.id, text, ok_cb, false)
post_large_msg(receiver, text)
end
if matches[1] == 'msg.to.id' and is_admin1(msg) then
text = msg.to.id
reply_msg(msg.id, text, ok_cb, false)
post_large_msg(receiver, text)
end
--Admin Join Service Message
if msg.service then
local action = msg.action.type
if action == 'chat_add_user_link' then
if is_owner2(msg.from.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.from.id
savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link")
channel_set_admin(receiver, user, ok_cb, false)
end
if is_support(msg.from.id) and not is_owner2(msg.from.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.from.id
savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup")
channel_set_mod(receiver, user, ok_cb, false)
end
end
if action == 'chat_add_user' then
if is_owner2(msg.action.user.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.action.user.id
savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]")
channel_set_admin(receiver, user, ok_cb, false)
end
if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.action.user.id
savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]")
channel_set_mod(receiver, user, ok_cb, false)
end
end
end
if matches[1] == 'msg.to.peer_id' then
post_large_msg(receiver, msg.to.peer_id)
end
end
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
end
return {
patterns = {
"^(تفعيل)$",
"^(تعطيل)$",
"^([Mm]ove) (.*)$",
"^(معلومات المجموعه)$",
"^(الاداريين)$",
"^(مدير المجموعه)$",
"^(الادمنيه)$",
"^(كشف بوت)$",
"^(ايدي الاعضاء)$",
"^([Kk]icked)$",
"^(بلوك) (.*)",
"^(بلوك)",
"^(ترقيه سوبر)$",
"^(ايدي)$",
"^(ايدي) (.*)$",
"^(مغادره)$",
"^[#!/]([Kk]ick) (.*)$",
"^(تغير الرابط)$",
"^(ضع رابط)$",
"^(الرابط)$",
"^(الايدي) (.*)$",
"^(رفع اداري) (.*)$",
"^(رفع اداري)",
"^(تنزيل اداري) (.*)$",
"^(تنزيل اداري)",
"^(رفع المدير) (.*)$",
"^(رفع المدير)$",
"^(رفع ادمن) (.*)$",
"^(رفع ادمن)",
"^(تنزيل ادمن) (.*)$",
"^(تنزيل ادمن)",
"^(ضع اسم) (.*)$",
"^(ضع وصف) (.*)$",
"^(ضع قوانين) (.*)$",
"^(ضع صوره)$",
"^(ضع معرف) (.*)$",
"^(مسح)$",
"^(قفل) (.*)$",
"^(فتح) (.*)$",
"^(قفل) ([^%s]+)$",
"^(فتح) ([^%s]+)$",
"^(كتم)$",
"^(كتم) (.*)$",
"^(المراقبه) (.*)$",
"^(الاعدادات)$",
"^(القوانين)$",
"^(ضع تكرار) (%d+)$",
"^(مسح) (.*)$",
"^[#!/]([Hh]elpp)$",
"^(اعدادات الوسائط)$",
"^(المكتومين)$",
"[#!/](mp) (.*)",
"[#!/](md) (.*)",
"^(https://telegram.me/joinchat/%S+)$",
"msg.to.peer_id",
"%[(document)%]",
"%[(photo)%]",
"%[(video)%]",
"%[(audio)%]",
"%[(contact)%]",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
| gpl-3.0 |
mqmaker/witi-openwrt | package/ramips/ui/luci-mtk/src/protocols/ppp/luasrc/model/cbi/admin_network/proto_pppoe.lua | 59 | 3798 | --[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local username, password, ac, service
local ipv6, defaultroute, metric, peerdns, dns,
keepalive_failure, keepalive_interval, demand, mtu
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
ac = section:taboption("general", Value, "ac",
translate("Access Concentrator"),
translate("Leave empty to autodetect"))
ac.placeholder = translate("auto")
service = section:taboption("general", Value, "service",
translate("Service Name"),
translate("Leave empty to autodetect"))
service.placeholder = translate("auto")
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", Flag, "ipv6",
translate("Enable IPv6 negotiation on the PPP link"))
ipv6.default = ipv6.disabled
end
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure",
translate("LCP echo failure threshold"),
translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures"))
function keepalive_failure.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^(%d+)[ ,]+%d+") or v)
end
end
function keepalive_failure.write() end
function keepalive_failure.remove() end
keepalive_failure.placeholder = "0"
keepalive_failure.datatype = "uinteger"
keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval",
translate("LCP echo interval"),
translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold"))
function keepalive_interval.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^%d+[ ,]+(%d+)"))
end
end
function keepalive_interval.write(self, section, value)
local f = tonumber(keepalive_failure:formvalue(section)) or 0
local i = tonumber(value) or 5
if i < 1 then i = 1 end
if f > 0 then
m:set(section, "keepalive", "%d %d" %{ f, i })
else
m:del(section, "keepalive")
end
end
keepalive_interval.remove = keepalive_interval.write
keepalive_interval.placeholder = "5"
keepalive_interval.datatype = "min(1)"
demand = section:taboption("advanced", Value, "demand",
translate("Inactivity timeout"),
translate("Close inactive connection after the given amount of seconds, use 0 to persist connection"))
demand.placeholder = "0"
demand.datatype = "uinteger"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(9200)"
| gpl-2.0 |
LuaDist2/lzmq-ffi | src/lua/lzmq/llthreads/ex.lua | 9 | 5950 | --
-- Author: Alexey Melnichuk <mimir@newmail.ru>
--
-- Copyright (C) 2013-2014 Alexey Melnichuk <mimir@newmail.ru>
--
-- Licensed according to the included 'LICENCE' document
--
-- This file is part of lua-lzqm library.
--
--- Wraps the low-level threads object.
--
-- @module llthreads2.ex
--
-- Notes for lzmq.threads.ex
-- When you create zmq socket in child thread and your main thread crash
-- lua state could be deadlocked if you use attached thread because it calls
-- in gc thread join or context destroy and no one could be done.
-- So by default for zmq more convinient use dettached joinable thread.
--
-- Example with deadlock
-- local thread = zthreads.xfork(function(pipe)
-- -- break when context destroy
-- while pipe:recv() do end
-- end):start(false, true)
--
--
-- Note! Define this function prior all `local` definitions
-- to prevent use upvalue by accident
--
local bootstrap_code = require"string".dump(function(lua_init, prelude, code, ...)
local loadstring = loadstring or load
local unpack = table.unpack or unpack
local function load_src(str)
local f, n
if str:sub(1,1) == '@' then
n = str:sub(2)
f = assert(loadfile(n))
else
n = '=(loadstring)'
f = assert(loadstring(str))
end
return f, n
end
local function pack_n(...)
return { n = select("#", ...), ... }
end
local function unpack_n(t)
return unpack(t, 1, t.n)
end
if lua_init and #lua_init > 0 then
local init = load_src(lua_init)
init()
end
local args
if prelude and #prelude > 0 then
prelude = load_src(prelude)
args = pack_n(prelude(...))
else
args = pack_n(...)
end
local func
func, args[0] = load_src(code)
rawset(_G, "arg", args)
arg = args
return func(unpack_n(args))
end)
local ok, llthreads = pcall(require, "llthreads2")
if not ok then llthreads = require"llthreads" end
local os = require"os"
local string = require"string"
local table = require"table"
local setmetatable, tonumber, assert = setmetatable, tonumber, assert
-------------------------------------------------------------------------------
local LUA_INIT = "LUA_INIT" do
local lua_version_t
local function lua_version()
if not lua_version_t then
local version = assert(_G._VERSION)
local maj,min = version:match("^Lua (%d+)%.(%d+)$")
if maj then lua_version_t = {tonumber(maj),tonumber(min)}
elseif not math.mod then lua_version_t = {5,2}
elseif table.pack and not pack then lua_version_t = {5,2}
else lua_version_t = {5,2} end
end
return lua_version_t[1], lua_version_t[2]
end
local LUA_MAJOR, LUA_MINOR = lua_version()
local IS_LUA_51 = (LUA_MAJOR == 5) and (LUA_MINOR == 1)
local LUA_INIT_VER
if not IS_LUA_51 then
LUA_INIT_VER = LUA_INIT .. "_" .. LUA_MAJOR .. "_" .. LUA_MINOR
end
LUA_INIT = LUA_INIT_VER and os.getenv( LUA_INIT_VER ) or os.getenv( LUA_INIT ) or ""
end
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
local thread_mt = {} do
thread_mt.__index = thread_mt
--- Thread object.
--
-- @type thread
--- Start thread.
--
-- @tparam ?boolean detached
-- @tparam ?boolean joinable
-- @return self
function thread_mt:start(...)
local ok, err
if select("#", ...) == 0 then ok, err = self.thread:start(true, true)
else ok, err = self.thread:start(...) end
if not ok then return nil, err end
return self
end
--- Join thread.
--
-- @tparam ?number timeout Windows suppurts arbitrary value, but POSIX supports only 0
function thread_mt:join(...)
return self.thread:join(...)
end
--- Check if thread still working.
-- You can call `join` to get returned values if thiread is not alive.
function thread_mt:alive()
return self.thread:alive()
end
--- Check if thread was started.
--
function thread_mt:started()
return self.thread:started()
end
--- Check if thread is detached.
-- This function returns valid value only for started thread.
function thread_mt:detached()
return self.thread:detached()
end
--- Check if thread is joinable.
-- This function returns valid value only for started thread.
function thread_mt:joinable()
return self.thread:joinable()
end
end
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
local threads = {} do
local function new_thread(lua_init, prelude, code, ...)
if type(lua_init) == "function" then
lua_init = string.dump(lua_init)
end
if type(prelude) == "function" then
prelude = string.dump(prelude)
end
if type(code) == "function" then
code = string.dump(code)
end
local thread = llthreads.new(bootstrap_code, lua_init, prelude, code, ...)
return setmetatable({
thread = thread,
}, thread_mt)
end
--- Create new thread object
--
-- @tparam string|function|THREAD_OPTIONS source thread source code.
--
threads.new = function (code, ...)
assert(code)
if type(code) == "table" then
local source = assert(code.source or code[1])
local init = (code.lua_init == nil) and LUA_INIT or code.lua_init
return new_thread(init, code.prelude, source, ...)
end
return new_thread(LUA_INIT, nil, code, ...)
end
end
-------------------------------------------------------------------------------
--- A table describe threads constructor options.
--
-- @tfield string|function source thread source code (or first value of table)
-- @tfield ?string|function prelude thread prelude code. This code can change thread arguments.
-- e.g. it can remove some values or change their type.
-- @lua_init ?string|function|false by default child lua state try use LUA_INIT environment variable
-- just like regular lua interpretator.
--
-- @table THREAD_OPTIONS
return threads
| mit |
interfaceware/iguana-web-apps | shared/basicauth.lua | 2 | 1733 | require 'stringutil'
-- Notice that the namespace for the module matches the module name - i.e. basicauth
-- When we use it within the code it is desirable to do:
-- basicauth = require 'basicauth'
-- Since this keeps the name of the module very consistent.
-- Basic authentication is part of the HTTP protocol. See this reference:
-- http://en.wikipedia.org/wiki/Basic_access_authentication
-- This module takes the user name and password from the user and validates the user id
-- against the local Iguana user id. If an invalid user name and password is given it won't be possilble to login.
local basicauth = {}
local function getCreds(Headers)
if not Headers.Authorization then
return false
end
local Auth64Str = Headers.Authorization:sub(#"Basic " + 1)
local Creds = filter.base64.dec(Auth64Str):split(":")
return {username=Creds[1], password=Creds[2]}
end
function basicauth.isAuthorized(Request)
local Credentials = getCreds(Request.headers)
if not Credentials then
return false
end
-- webInfo requires Iguana 5.6.4 or above
local WebInfo = iguana.webInfo()
-- TODO - it would be really nice if we could have a Lua API
-- to do this against the local Iguana instance - it would be
-- a tinsy winsy bit faster.
local Status, Code = net.http.post{
url=WebInfo.ip..":"..WebInfo.web_config.port.."/status",
auth=Credentials,
live=true}
return Code == 200
end
function basicauth.requireAuthorization()
net.http.respond{
code=401,
headers={["WWW-Authenticate"]='Basic realm=Channel Manager'},
body="Please Authenticate"}
end
function basicauth.getCredentials(HttpMsg)
return getCreds(HttpMsg.headers)
end
return basicauth | mit |
dicebox/minetest-france | mods/playeranim/init.lua | 1 | 8203 | -- Version of player model.
-- default_character_v1:
-- minetest_game before 25 nov 2016
-- 3d_armor before 27 nov 2016 (overrides model from minetest_game)
-- default_character_v2:
-- minetest_game after 25 nov 2016
-- 3d_armor after 27 nov 2016 (overrides model from minetest_game)
local valid_player_model_versions = {
default_character_v1 = true,
default_character_v2 = true,
}
local player_model_version = minetest.setting_get("player_model_version")
if not player_model_version or player_model_version == "" then
player_model_version = "default_character_v2"
elseif not valid_player_model_versions[player_model_version] then
error("Invalid value for player_model_version in minetest.conf: " .. player_model_version)
end
-- Localize to avoid table lookups
local vector_new = vector.new
local math_pi = math.pi
local math_sin = math.sin
local table_remove = table.remove
local get_animation = default.player_get_animation
-- Animation alias
local STAND = 1
local WALK = 2
local MINE = 3
local WALK_MINE = 4
local SIT = 5
local LAY = 6
-- Bone alias
local BODY = "Body"
local HEAD = "Head"
local CAPE = "Cape"
local LARM = "Arm_Left"
local RARM = "Arm_Right"
local LLEG = "Leg_Left"
local RLEG = "Leg_Right"
local bone_positions = {
default_character_v1 = {
[BODY] = vector_new(0, -3.5, 0),
[HEAD] = vector_new(0, 6.75, 0),
[CAPE] = vector_new(0, 6.75, 1.1),
[LARM] = vector_new(2, 6.75, 0),
[RARM] = vector_new(-2, 6.75, 0),
[LLEG] = vector_new(-1, 0, 0),
[RLEG] = vector_new(1, 0, 0)
},
default_character_v2 = {
[BODY] = vector_new(0, -3.5, 0),
[HEAD] = vector_new(0, 6.75, 0),
[CAPE] = vector_new(0, 6.75, 1.2),
[LARM] = vector_new(3, 5.75, 0),
[RARM] = vector_new(-3, 5.75, 0),
[LLEG] = vector_new(1, 0, 0),
[RLEG] = vector_new(-1, 0, 0)
}
}
local bone_rotations = {
default_character_v1 = {
[BODY] = vector_new(0, 0, 0),
[HEAD] = vector_new(0, 0, 0),
[CAPE] = vector_new(180, 0, 0),
[LARM] = vector_new(180, 0, 9),
[RARM] = vector_new(180, 0, -9),
[LLEG] = vector_new(0, 0, 0),
[RLEG] = vector_new(0, 0, 0)
},
default_character_v2 = {
[BODY] = vector_new(0, 0, 0),
[HEAD] = vector_new(0, 0, 0),
[CAPE] = vector_new(0, 0, 0),
[LARM] = vector_new(0, 0, 0),
[RARM] = vector_new(0, 0, 0),
[LLEG] = vector_new(0, 0, 0),
[RLEG] = vector_new(0, 0, 0)
}
}
local bone_rotation = bone_rotations[player_model_version]
local bone_position = bone_positions[player_model_version]
if not bone_rotation or not bone_position then
error("Internal error: invalid player_model_version: " .. player_model_version)
end
local bone_rotation_cache = {}
local function rotate(player, bone, x, y, z)
local default_rotation = bone_rotation[bone]
local rotation = {
x = (x or 0) + default_rotation.x,
y = (y or 0) + default_rotation.y,
z = (z or 0) + default_rotation.z
}
local player_cache = bone_rotation_cache[player]
local rotation_cache = player_cache[bone]
if not rotation_cache
or rotation.x ~= rotation_cache.x
or rotation.y ~= rotation_cache.y
or rotation.z ~= rotation_cache.z then
player_cache[bone] = rotation
player:set_bone_position(bone, bone_position[bone], rotation)
end
end
local step = 0
local look_pitch = {}
local animation_speed = {}
local animations = {
[STAND] = function(player)
rotate(player, BODY)
rotate(player, CAPE)
rotate(player, LARM)
rotate(player, RARM)
rotate(player, LLEG)
rotate(player, RLEG)
end,
[WALK] = function(player)
local swing = math_sin(step * 4 * animation_speed[player])
rotate(player, CAPE, swing * -30 - 35)
rotate(player, LARM, swing * -40)
rotate(player, RARM, swing * 40)
rotate(player, LLEG, swing * 40)
rotate(player, RLEG, swing * -40)
end,
[MINE] = function(player)
local pitch = look_pitch[player]
local speed = animation_speed[player]
local swing = math_sin(step * 4 * speed)
local hand_swing = math_sin(step * 8 * speed)
rotate(player, CAPE, swing * -5 - 10)
rotate(player, LARM)
rotate(player, RARM, hand_swing * 20 + 80 + pitch, hand_swing * 5 - 3, 10)
rotate(player, LLEG)
rotate(player, RLEG)
end,
[WALK_MINE] = function(player)
local pitch = look_pitch[player]
local speed = animation_speed[player]
local swing = math_sin(step * 4 * speed)
local hand_swing = math_sin(step * 8 * speed)
rotate(player, CAPE, swing * -30 - 35)
rotate(player, LARM, swing * -40)
rotate(player, RARM, hand_swing * 20 + 80 + pitch, hand_swing * 5 - 3, 10)
rotate(player, LLEG, swing * 40)
rotate(player, RLEG, swing * -40)
end,
[SIT] = function(player)
local body_position = vector_new(bone_position[BODY])
body_position.y = body_position.y - 6
player:set_bone_position(BODY, body_position, {x = 0, y = 0, z = 0})
rotate(player, LARM)
rotate(player, RARM)
rotate(player, LLEG, 90)
rotate(player, RLEG, 90)
end,
[LAY] = function(player)
rotate(player, HEAD)
rotate(player, CAPE)
rotate(player, LARM)
rotate(player, RARM)
rotate(player, LLEG)
rotate(player, RLEG)
local body_position = {x = 0, y = -9, z = 0}
local body_rotation = {x = 270, y = 0, z = 0}
player:set_bone_position(BODY, body_position, body_rotation)
end
}
local function update_look_pitch(player)
local pitch = -player:get_look_vertical() * 180 / math_pi
if look_pitch[player] ~= pitch then
look_pitch[player] = pitch
end
end
local function set_animation_speed(player, sneak)
local speed = sneak and 0.75 or 2
if animation_speed[player] ~= speed then
animation_speed[player] = speed
end
end
local previous_animation = {}
local function set_animation(player, anim)
if (anim == WALK or anim == MINE or anim == WALK_MINE)
or (previous_animation[player] ~= anim) then
previous_animation[player] = anim
animations[anim](player)
end
end
local previous_yaw = {}
local function body_moving(player, sneak, no_rotate_body)
local yaw = player:get_look_horizontal()
local player_previous_yaw = previous_yaw[player]
local index = #player_previous_yaw + 1
player_previous_yaw[index] = yaw
local next_yaw = yaw
if index > 7 then
next_yaw = player_previous_yaw[1]
table_remove(player_previous_yaw, 1)
end
local x, y = 0, 0
if not no_rotate_body then
x = sneak and 5 or 0
y = (yaw - next_yaw) * 180 / math_pi
end
rotate(player, BODY, x, y)
rotate(player, HEAD, look_pitch[player], -y)
end
local players = {}
local player_list = {}
local player_count = 0
local function update_players()
players = {}
local position = 0
for player, joined in pairs(player_list) do
if joined and player:is_player_connected() then
position = position + 1
players[position] = player
end
end
player_count = position
end
minetest.register_on_joinplayer(function(player)
bone_rotation_cache[player] = {}
previous_yaw[player] = {}
player_list[player] = true
update_players()
end)
minetest.register_on_leaveplayer(function(player)
bone_rotation_cache[player] = nil
look_pitch[player] = nil
animation_speed[player] = nil
previous_yaw[player] = nil
previous_animation[player] = nil
player_list[player] = nil
update_players()
end)
minetest.register_globalstep(function(dtime)
if player_count == 0 then return end
step = step + dtime
if step >= 3600 then
step = 1
end
for i = 1, player_count do
local player = players[i]
local animation = get_animation(player).animation
if animation == "lay" then
set_animation(player, LAY)
if #previous_yaw[player] ~= 0 then
previous_yaw[player] = {}
end
else
local controls = player:get_player_control()
local sneak = controls.sneak
update_look_pitch(player)
if animation == "walk" then
set_animation_speed(player, sneak)
set_animation(player, WALK)
body_moving(player, sneak)
elseif animation == "mine" then
set_animation_speed(player, sneak)
set_animation(player, MINE)
body_moving(player, sneak)
elseif animation == "walk_mine" then
set_animation_speed(player, sneak)
set_animation(player, WALK_MINE)
body_moving(player, sneak)
elseif animation == "sit" then
set_animation(player, SIT)
body_moving(player, sneak, true)
else
set_animation(player, STAND)
body_moving(player, sneak)
end
end
end
end)
| gpl-3.0 |
cshore/luci | applications/luci-app-asterisk/luasrc/model/cbi/asterisk-mod-codec.lua | 68 | 1959 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
cbimap = Map("asterisk", "asterisk", "")
module = cbimap:section(TypedSection, "module", "Modules", "")
module.anonymous = true
codec_a_mu = module:option(ListValue, "codec_a_mu", "A-law and Mulaw direct Coder/Decoder", "")
codec_a_mu:value("yes", "Load")
codec_a_mu:value("no", "Do Not Load")
codec_a_mu:value("auto", "Load as Required")
codec_a_mu.rmempty = true
codec_adpcm = module:option(ListValue, "codec_adpcm", "Adaptive Differential PCM Coder/Decoder", "")
codec_adpcm:value("yes", "Load")
codec_adpcm:value("no", "Do Not Load")
codec_adpcm:value("auto", "Load as Required")
codec_adpcm.rmempty = true
codec_alaw = module:option(ListValue, "codec_alaw", "A-law Coder/Decoder", "")
codec_alaw:value("yes", "Load")
codec_alaw:value("no", "Do Not Load")
codec_alaw:value("auto", "Load as Required")
codec_alaw.rmempty = true
codec_g726 = module:option(ListValue, "codec_g726", "ITU G.726-32kbps G726 Transcoder", "")
codec_g726:value("yes", "Load")
codec_g726:value("no", "Do Not Load")
codec_g726:value("auto", "Load as Required")
codec_g726.rmempty = true
codec_gsm = module:option(ListValue, "codec_gsm", "GSM/PCM16 (signed linear) Codec Translation", "")
codec_gsm:value("yes", "Load")
codec_gsm:value("no", "Do Not Load")
codec_gsm:value("auto", "Load as Required")
codec_gsm.rmempty = true
codec_speex = module:option(ListValue, "codec_speex", "Speex/PCM16 (signed linear) Codec Translator", "")
codec_speex:value("yes", "Load")
codec_speex:value("no", "Do Not Load")
codec_speex:value("auto", "Load as Required")
codec_speex.rmempty = true
codec_ulaw = module:option(ListValue, "codec_ulaw", "Mu-law Coder/Decoder", "")
codec_ulaw:value("yes", "Load")
codec_ulaw:value("no", "Do Not Load")
codec_ulaw:value("auto", "Load as Required")
codec_ulaw.rmempty = true
return cbimap
| apache-2.0 |
dicebox/minetest-france | minetest/builtin/mainmenu/common.lua | 1 | 10818 | --Minetest
--Copyright (C) 2014 sapier
--
--This program is free software; you can redistribute it and/or modify
--it under the terms of the GNU Lesser General Public License as published by
--the Free Software Foundation; either version 2.1 of the License, or
--(at your option) any later version.
--
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
--GNU Lesser General Public License for more details.
--
--You should have received a copy of the GNU Lesser General Public License along
--with this program; if not, write to the Free Software Foundation, Inc.,
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--------------------------------------------------------------------------------
-- Global menu data
--------------------------------------------------------------------------------
menudata = {}
--------------------------------------------------------------------------------
-- Local cached values
--------------------------------------------------------------------------------
local min_supp_proto, max_supp_proto
function common_update_cached_supp_proto()
min_supp_proto = core.get_min_supp_proto()
max_supp_proto = core.get_max_supp_proto()
end
common_update_cached_supp_proto()
--------------------------------------------------------------------------------
-- Menu helper functions
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function render_client_count(n)
if n > 99 then return '99+'
elseif n >= 0 then return tostring(n)
else return '?' end
end
local function configure_selected_world_params(idx)
local worldconfig = modmgr.get_worldconfig(menudata.worldlist:get_list()[idx].path)
if worldconfig.creative_mode then
core.setting_set("creative_mode", worldconfig.creative_mode)
end
if worldconfig.enable_damage then
core.setting_set("enable_damage", worldconfig.enable_damage)
end
end
--------------------------------------------------------------------------------
function image_column(tooltip, flagname)
return "image,tooltip=" .. core.formspec_escape(tooltip) .. "," ..
"0=" .. core.formspec_escape(defaulttexturedir .. "blank.png") .. "," ..
"1=" .. core.formspec_escape(defaulttexturedir .. "server_flags_" .. flagname .. ".png") .. "," ..
"2=" .. core.formspec_escape(defaulttexturedir .. "server_ping_4.png") .. "," ..
"3=" .. core.formspec_escape(defaulttexturedir .. "server_ping_3.png") .. "," ..
"4=" .. core.formspec_escape(defaulttexturedir .. "server_ping_2.png") .. "," ..
"5=" .. core.formspec_escape(defaulttexturedir .. "server_ping_1.png")
end
--------------------------------------------------------------------------------
function order_favorite_list(list)
local res = {}
--orders the favorite list after support
for i = 1, #list do
local fav = list[i]
if is_server_protocol_compat(fav.proto_min, fav.proto_max) then
res[#res + 1] = fav
end
end
for i = 1, #list do
local fav = list[i]
if not is_server_protocol_compat(fav.proto_min, fav.proto_max) then
res[#res + 1] = fav
end
end
return res
end
--------------------------------------------------------------------------------
function render_serverlist_row(spec, is_favorite)
local text = ""
if spec.name then
text = text .. core.formspec_escape(spec.name:trim())
elseif spec.address then
text = text .. spec.address:trim()
if spec.port then
text = text .. ":" .. spec.port
end
end
local details = ""
local grey_out = not is_server_protocol_compat(spec.proto_min, spec.proto_max)
if is_favorite then
details = "1,"
else
details = "0,"
end
if spec.ping then
local ping = spec.ping * 1000
if ping <= 50 then
details = details .. "2,"
elseif ping <= 100 then
details = details .. "3,"
elseif ping <= 250 then
details = details .. "4,"
else
details = details .. "5,"
end
else
details = details .. "0,"
end
if spec.clients and spec.clients_max then
local clients_color = ''
local clients_percent = 100 * spec.clients / spec.clients_max
-- Choose a color depending on how many clients are connected
-- (relatively to clients_max)
if grey_out then clients_color = '#aaaaaa'
elseif spec.clients == 0 then clients_color = '' -- 0 players: default/white
elseif clients_percent <= 60 then clients_color = '#a1e587' -- 0-60%: green
elseif clients_percent <= 90 then clients_color = '#ffdc97' -- 60-90%: yellow
elseif clients_percent == 100 then clients_color = '#dd5b5b' -- full server: red (darker)
else clients_color = '#ffba97' -- 90-100%: orange
end
details = details .. clients_color .. ',' ..
render_client_count(spec.clients) .. ',/,' ..
render_client_count(spec.clients_max) .. ','
elseif grey_out then
details = details .. '#aaaaaa,?,/,?,'
else
details = details .. ',?,/,?,'
end
if spec.creative then
details = details .. "1,"
else
details = details .. "0,"
end
if spec.damage then
details = details .. "1,"
else
details = details .. "0,"
end
if spec.pvp then
details = details .. "1,"
else
details = details .. "0,"
end
return details .. (grey_out and '#aaaaaa,' or ',') .. text
end
--------------------------------------------------------------------------------
os.tempfolder = function()
if core.setting_get("TMPFolder") then
return core.setting_get("TMPFolder") .. DIR_DELIM .. "MT_" .. math.random(0,10000)
end
local filetocheck = os.tmpname()
os.remove(filetocheck)
local randname = "MTTempModFolder_" .. math.random(0,10000)
if DIR_DELIM == "\\" then
local tempfolder = os.getenv("TEMP")
return tempfolder .. filetocheck
else
local backstring = filetocheck:reverse()
return filetocheck:sub(0,filetocheck:len()-backstring:find(DIR_DELIM)+1) ..randname
end
end
--------------------------------------------------------------------------------
function menu_render_worldlist()
local retval = ""
local current_worldlist = menudata.worldlist:get_list()
for i, v in ipairs(current_worldlist) do
if retval ~= "" then retval = retval .. "," end
retval = retval .. core.formspec_escape(v.name) ..
" \\[" .. core.formspec_escape(v.gameid) .. "\\]"
end
return retval
end
--------------------------------------------------------------------------------
function menu_handle_key_up_down(fields, textlist, settingname)
local oldidx, newidx = core.get_textlist_index(textlist), 1
if fields.key_up or fields.key_down then
if fields.key_up and oldidx and oldidx > 1 then
newidx = oldidx - 1
elseif fields.key_down and oldidx and
oldidx < menudata.worldlist:size() then
newidx = oldidx + 1
end
core.setting_set(settingname, menudata.worldlist:get_raw_index(newidx))
configure_selected_world_params(newidx)
return true
end
return false
end
--------------------------------------------------------------------------------
function asyncOnlineFavourites()
if not menudata.public_known then
menudata.public_known = {{
name = fgettext("Loading..."),
description = fgettext_ne("Try reenabling public serverlist and check your internet connection.")
}}
end
menudata.favorites = menudata.public_known
menudata.favorites_is_public = true
if not menudata.public_downloading then
menudata.public_downloading = true
else
return
end
core.handle_async(
function(param)
return core.get_favorites("online")
end,
nil,
function(result)
menudata.public_downloading = nil
local favs = order_favorite_list(result)
if favs[1] then
menudata.public_known = favs
menudata.favorites = menudata.public_known
menudata.favorites_is_public = true
end
core.event_handler("Refresh")
end
)
end
--------------------------------------------------------------------------------
function text2textlist(xpos, ypos, width, height, tl_name, textlen, text, transparency)
local textlines = core.splittext(text, textlen)
local retval = "textlist[" .. xpos .. "," .. ypos .. ";" .. width ..
"," .. height .. ";" .. tl_name .. ";"
for i = 1, #textlines do
textlines[i] = textlines[i]:gsub("\r", "")
retval = retval .. core.formspec_escape(textlines[i]) .. ","
end
retval = retval .. ";0;"
if transparency then retval = retval .. "true" end
retval = retval .. "]"
return retval
end
--------------------------------------------------------------------------------
function is_server_protocol_compat(server_proto_min, server_proto_max)
if (not server_proto_min) or (not server_proto_max) then
-- There is no info. Assume the best and act as if we would be compatible.
return true
end
return min_supp_proto <= server_proto_max and max_supp_proto >= server_proto_min
end
--------------------------------------------------------------------------------
function is_server_protocol_compat_or_error(server_proto_min, server_proto_max)
if not is_server_protocol_compat(server_proto_min, server_proto_max) then
local server_prot_ver_info, client_prot_ver_info
local s_p_min = server_proto_min
local s_p_max = server_proto_max
if s_p_min ~= s_p_max then
server_prot_ver_info = fgettext_ne("Server supports protocol versions between $1 and $2. ",
s_p_min, s_p_max)
else
server_prot_ver_info = fgettext_ne("Server enforces protocol version $1. ",
s_p_min)
end
if min_supp_proto ~= max_supp_proto then
client_prot_ver_info= fgettext_ne("We support protocol versions between version $1 and $2.",
min_supp_proto, max_supp_proto)
else
client_prot_ver_info = fgettext_ne("We only support protocol version $1.", min_supp_proto)
end
gamedata.errormessage = fgettext_ne("Protocol version mismatch. ")
.. server_prot_ver_info
.. client_prot_ver_info
return false
end
return true
end
--------------------------------------------------------------------------------
function menu_worldmt(selected, setting, value)
local world = menudata.worldlist:get_list()[selected]
if world then
local filename = world.path .. DIR_DELIM .. "world.mt"
local world_conf = Settings(filename)
if value then
if not world_conf:write() then
core.log("error", "Failed to write world config file")
end
world_conf:set(setting, value)
world_conf:write()
else
return world_conf:get(setting)
end
else
return nil
end
end
function menu_worldmt_legacy(selected)
local modes_names = {"creative_mode", "enable_damage", "server_announce"}
for _, mode_name in pairs(modes_names) do
local mode_val = menu_worldmt(selected, mode_name)
if mode_val then
core.setting_set(mode_name, mode_val)
else
menu_worldmt(selected, mode_name, core.setting_get(mode_name))
end
end
end
| gpl-3.0 |
AntiSpammer1313/mranti3 | plugins/boobs.lua | 731 | 1601 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. 🔞",
"!butts: Get a butts NSFW image. 🔞"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
| gpl-2.0 |
hfjgjfg/shatel | plugins/boobs.lua | 731 | 1601 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. 🔞",
"!butts: Get a butts NSFW image. 🔞"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
| gpl-2.0 |
135yshr/Holocraft-server | world/Plugins/APIDump/Hooks/OnPostCrafting.lua | 36 | 1584 | return
{
HOOK_POST_CRAFTING =
{
CalledWhen = "After the built-in recipes are checked and a recipe was found.",
DefaultFnName = "OnPostCrafting", -- also used as pagename
Desc = [[
This hook is called when a {{cPlayer|player}} changes contents of their
{{cCraftingGrid|crafting grid}}, after the recipe has been established by Cuberite. Plugins may use
this to modify the resulting recipe or provide an alternate recipe.</p>
<p>
If a plugin implements custom recipes, it should do so using the {{OnPreCrafting|HOOK_PRE_CRAFTING}}
hook, because that will save the server from going through the built-in recipes. The
HOOK_POST_CRAFTING hook is intended as a notification, with a chance to tweak the result.</p>
<p>
Note that this hook is not called if a built-in recipe is not found;
{{OnCraftingNoRecipe|HOOK_CRAFTING_NO_RECIPE}} is called instead in such a case.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has changed their crafting grid contents" },
{ Name = "Grid", Type = "{{cCraftingGrid}}", Notes = "The new crafting grid contents" },
{ Name = "Recipe", Type = "{{cCraftingRecipe}}", Notes = "The recipe that Cuberite has decided to use (can be tweaked by plugins)" },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called. If the function
returns true, no other callbacks are called for this event. In either case, Cuberite uses the value
of Recipe as the recipe to be presented to the player.
]],
}, -- HOOK_POST_CRAFTING
}
| mit |
adamel/sysdig | userspace/sysdig/chisels/fdcount_by.lua | 2 | 2356 | --[[
Copyright (C) 2013-2014 Draios inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--]]
-- Chisel description
description = "Groups all the active FDs based on the given filter field, and returns the fd count for each key. For example, it can be used to list the number of connections per process or per IP end-point."
short_description = "FD count, aggregated by an arbitrary filter field"
category = "I/O"
-- Chisel argument list
args =
{
{
name = "key",
description = "The filter field used for grouping",
argtype = "string"
},
}
-- The number of items to show
TOP_NUMBER = 0
require "common"
grtable = {}
key_fld = ""
-- Argument notification callback
function on_set_arg(name, val)
if name == "key" then
key_fld = val
return true
end
return false
end
-- Initialization callback
function on_init()
-- Request the fields we need
fkey = chisel.request_field(key_fld)
ffdnum = chisel.request_field("fd.num")
ffdname = chisel.request_field("fd.name")
return true
end
-- Event parsing callback
function on_event()
key = evt.field(fkey)
fdnum = evt.field(ffdnum)
fdname = evt.field(ffdname)
if key ~= nil and fdnum ~= nil and fdnum > 0 and fdname ~= nil and fdname ~= "" then
entryval = grtable[key]
fdkey = tostring(fdnum) .. fdname
if entryval == nil then
grtable[key] = {}
grtable[key][fdkey] = 1
grtable[key]["c"] = 1
else
fdentry = grtable[key][fdkey]
if fdentry == nil then
grtable[key][fdkey] = 1
grtable[key]["c"] = grtable[key]["c"] + 1
end
end
end
return true
end
-- Called by the engine at the end of the capture (Ctrl-C)
function on_capture_end()
sorted_grtable = pairs_top_by_val(grtable, TOP_NUMBER, function(t,a,b) return t[b]["c"] < t[a]["c"] end)
etime = evt.field(ftime)
for k,v in sorted_grtable do
print(k, v["c"])
end
return true
end
| gpl-2.0 |
ChristopherBiscardi/kong | spec/plugins/logging_spec.lua | 6 | 6583 | local IO = require "kong.tools.io"
local utils = require "kong.tools.utils"
local cjson = require "cjson"
local stringy = require "stringy"
local spec_helper = require "spec.spec_helpers"
local http_client = require "kong.tools.http_client"
local STUB_GET_URL = spec_helper.STUB_GET_URL
local TCP_PORT = spec_helper.find_port()
local UDP_PORT = spec_helper.find_port({TCP_PORT})
local HTTP_PORT = spec_helper.find_port({TCP_PORT, UDP_PORT})
local HTTP_DELAY_PORT = spec_helper.find_port({TCP_PORT, UDP_PORT, HTTP_PORT})
local FILE_LOG_PATH = os.tmpname()
local function create_mock_bin()
local res, status = http_client.post("http://mockbin.org/bin/create", '{ "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "headers": [], "cookies": [], "content": { "mimeType" : "application/json" }, "redirectURL": "", "headersSize": 0, "bodySize": 0 }', { ["content-type"] = "application/json" })
assert.are.equal(201, status)
return res:sub(2, res:len() - 1)
end
local mock_bin = create_mock_bin()
describe("Logging Plugins", function()
setup(function()
spec_helper.prepare_db()
spec_helper.insert_fixtures {
api = {
{ name = "tests tcp logging", public_dns = "tcp_logging.com", target_url = "http://mockbin.com" },
{ name = "tests tcp logging2", public_dns = "tcp_logging2.com", target_url = "http://localhost:"..HTTP_DELAY_PORT },
{ name = "tests udp logging", public_dns = "udp_logging.com", target_url = "http://mockbin.com" },
{ name = "tests http logging", public_dns = "http_logging.com", target_url = "http://mockbin.com" },
{ name = "tests https logging", public_dns = "https_logging.com", target_url = "http://mockbin.com" },
{ name = "tests file logging", public_dns = "file_logging.com", target_url = "http://mockbin.com" }
},
plugin_configuration = {
{ name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 1 },
{ name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 2 },
{ name = "udplog", value = { host = "127.0.0.1", port = UDP_PORT }, __api = 3 },
{ name = "httplog", value = { http_endpoint = "http://localhost:"..HTTP_PORT.."/" }, __api = 4 },
{ name = "httplog", value = { http_endpoint = "https://mockbin.org/bin/"..mock_bin }, __api = 5 },
{ name = "filelog", value = { path = FILE_LOG_PATH }, __api = 6 }
}
}
spec_helper.start_kong()
end)
teardown(function()
spec_helper.stop_kong()
end)
it("should log to TCP", function()
local thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "tcp_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log proper latencies", function()
local http_thread = spec_helper.start_http_server(HTTP_DELAY_PORT) -- Starting the mock TCP server
local tcp_thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(spec_helper.PROXY_URL.."/delay", nil, { host = "tcp_logging2.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = tcp_thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.truthy(log_message.latencies.proxy < 3000)
assert.truthy(log_message.latencies.request >= log_message.latencies.kong + log_message.latencies.proxy)
http_thread:join()
end)
it("should log to UDP", function()
local thread = spec_helper.start_udp_server(UDP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "udp_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to HTTP", function()
local thread = spec_helper.start_http_server(HTTP_PORT) -- Starting the mock TCP server
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "http_logging.com" })
assert.are.equal(200, status)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.truthy(ok)
assert.truthy(res)
-- Making sure it's alright
assert.are.same("POST / HTTP/1.1", res[1])
local log_message = cjson.decode(res[7])
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to HTTPs", function()
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil, { host = "https_logging.com" })
assert.are.equal(200, status)
local total_time = 0
local res, status, body
repeat
assert.truthy(total_time <= 10) -- Fail after 10 seconds
res, status = http_client.get("http://mockbin.org/bin/"..mock_bin.."/log", nil, { accept = "application/json" })
assert.are.equal(200, status)
body = cjson.decode(res)
local wait = 1
os.execute("sleep "..tostring(wait))
total_time = total_time + wait
until(#body.log.entries > 0)
assert.are.equal(1, #body.log.entries)
local log_message = cjson.decode(body.log.entries[1].request.postData.text)
-- Making sure it's alright
assert.are.same("127.0.0.1", log_message.client_ip)
end)
it("should log to file", function()
local uuid = utils.random_string()
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil,
{ host = "file_logging.com", file_log_uuid = uuid }
)
assert.are.equal(200, status)
while not (IO.file_exists(FILE_LOG_PATH)) do
-- Wait for the file to be created
end
while not (IO.file_size(FILE_LOG_PATH) > 0) do
-- Wait for the log to be appended
end
local file_log = IO.read_file(FILE_LOG_PATH)
local log_message = cjson.decode(stringy.strip(file_log))
assert.are.same("127.0.0.1", log_message.client_ip)
assert.are.same(uuid, log_message.request.headers.file_log_uuid)
os.remove(FILE_LOG_PATH)
end)
end)
| mit |
NSAKEY/prosody-modules | mod_auth_custom_http/mod_auth_custom_http.lua | 32 | 1346 | -- Prosody IM
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local new_sasl = require "util.sasl".new;
local json_encode = require "util.json";
local http = require "socket.http";
local options = module:get_option("auth_custom_http");
local post_url = options and options.post_url;
assert(post_url, "No HTTP POST URL provided");
local provider = {};
function provider.test_password(username, password)
return nil, "Not supported"
end
function provider.get_password(username)
return nil, "Not supported"
end
function provider.set_password(username, password)
return nil, "Not supported"
end
function provider.user_exists(username)
return true;
end
function provider.create_user(username, password)
return nil, "Not supported"
end
function provider.delete_user(username)
return nil, "Not supported"
end
function provider.get_sasl_handler()
local getpass_authentication_profile = {
plain_test = function(sasl, username, password, realm)
local postdata = json_encode({ username = username, password = password });
local result = http.request(post_url, postdata);
return result == "true", true;
end,
};
return new_sasl(module.host, getpass_authentication_profile);
end
module:provides("auth", provider);
| mit |
mahdikord/baran | plugins/get.lua | 613 | 1067 | local function get_variables_hash(msg)
if msg.to.type == 'chat' then
return 'chat:'..msg.to.id..':variables'
end
if msg.to.type == 'user' then
return 'user:'..msg.from.id..':variables'
end
end
local function list_variables(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
text = text..names[i]..'\n'
end
return text
end
end
local function get_value(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return'Not found, use "!get" to list variables'
else
return var_name..' => '..value
end
end
end
local function run(msg, matches)
if matches[2] then
return get_value(msg, matches[2])
else
return list_variables(msg)
end
end
return {
description = "Retrieves variables saved with !set",
usage = "!get (value_name): Returns the value_name value.",
patterns = {
"^(!get) (.+)$",
"^!get$"
},
run = run
}
| gpl-2.0 |
arventwei/WioEngine | Tools/jamplus/src/luaplus/Src/Modules/lanes/tests/timer.lua | 6 | 2574 | --
-- TIMER.LUA
--
-- Sample program for Lua Lanes
--
-- On MSYS, stderr is buffered. In this test it matters.
io.stderr:setvbuf "no"
local lanes = require "lanes".configure()
local linda= lanes.linda()
local function PRINT(str)
io.stderr:write(str.."\n")
end
local T1= "1s" -- these keys can be anything...
local T2= "5s"
local step= {}
lanes.timer( linda, T1, 1.0, 1.0 )
step[T1]= 1.0
PRINT( "\n*** Timers every second (not synced to wall clock) ***\n" )
local v_first
local v_last= {} -- { [channel]= num }
local T2_first_round= true
local caught= {} -- { [T1]= bool, [T2]= bool }
while true do
io.stderr:write("waiting...\t")
local channel, v = linda:receive( 6.0, T1,T2 )
assert( channel==T1 or channel==T2 )
caught[channel]= true
io.stderr:write( ((channel==T1) and "" or "\t\t").. string.format("%.3f",v),"\n" )
assert( type(v)=="number" )
if v_last[channel] then
if channel==T2 and T2_first_round then
-- do not make measurements, first round is not 5secs due to wall clock adjustment
T2_first_round= false
else
assert( math.abs(v-v_last[channel]- step[channel]) < 0.02 )
end
end
if not v_first then
v_first= v
elseif v-v_first > 3.0 and (not step[T2]) then
PRINT( "\n*** Adding timers every 5 second (synced to wall clock) ***\n" )
-- The first event can be in the past (just cut seconds down to 5s)
--
local date= os.date("*t")
date.sec = date.sec - date.sec%5
lanes.timer( linda, T2, date, 5.0 )
step[T2]= 5.0
elseif v-v_first > 10 then -- exit condition
break
end
v_last[channel]= v
end
-- Windows version had a bug where T2 timers were not coming through, at all.
-- AKa 24-Jan-2009
--
assert( caught[T1] )
assert( caught[T2] )
PRINT( "\n*** Listing timers ***\n" )
local r = lanes.timers() -- list of {linda, key, {}}
for _,t in ipairs( r) do
local linda, key, timer = t[1], t[2], t[3]
print( tostring( linda), key, timer[1], timer[2])
end
PRINT( "\n*** Clearing timers ***\n" )
lanes.timer( linda, T1, 0 ) -- reset; no reoccuring ticks
lanes.timer( linda, T2, 0 )
linda:receive( 0, T1 ) -- clear out; there could be one tick left
linda:receive( 0, T2 )
assert( linda:get(T1) == nil )
assert( linda:get(T2) == nil )
PRINT "...making sure no ticks are coming..."
local k,v= linda:receive( 10, T1,T2 ) -- should not get any
assert(v==nil)
lanes.timer_lane:cancel()
print (lanes.timer_lane[1], lanes.timer_lane[2]) | mit |
philanc/plc | plc/box.lua | 2 | 2457 | -- Copyright (c) 2017 Pierre Chapuis -- see LICENSE file
------------------------------------------------------------
--[[
High-level encryption routines
]]
local salsa20 = require "plc.salsa20"
local ec25519 = require "plc.ec25519"
local poly1305 = require "plc.poly1305"
local function public_key(sk)
assert(type(sk) == "string", "sk must be a string")
assert(#sk == 32, "#sh must be 32")
sk = table.pack(sk:byte(1, 32))
local pk = {}
ec25519.crypto_scalarmult_base(pk, sk)
return string.char(table.unpack(pk))
end
local function unpack_nonce(nonce)
assert(#nonce == 24, "#nonce must be 24")
local nonce1 = nonce:sub(1, 8)
local counter = string.unpack("<I8", nonce:sub(9, 16))
local nonce2 = nonce:sub(17, 24)
return counter, nonce1, nonce2
end
local function secretbox(pt, nonce, key)
assert(#key == 32, "#key must be 32")
local counter, nonce1, nonce2 = unpack_nonce(nonce)
local key2 = salsa20.hsalsa20(key, counter, nonce1)
local et = salsa20.encrypt(key2, 0, nonce2, string.rep("\0", 32) .. pt)
local key3 = et:sub(1, 32)
et = et:sub(33)
local mac = poly1305.auth(et, key3)
return mac .. et
end
local function secretbox_open(et, nonce, key)
assert(#key == 32, "#key must be 32")
assert(#et >= 16, "#et must be at least 16")
local counter, nonce1, nonce2 = unpack_nonce(nonce)
local key2 = salsa20.hsalsa20(key, counter, nonce1)
local key3 = salsa20.stream(key2, 0, nonce2, 32)
local mac = et:sub(1, 16)
local mac2 = poly1305.auth(et:sub(17), key3)
if mac2 ~= mac then return nil, "invalid MAC" end
local pt = salsa20.encrypt(key2, 0, nonce2, string.rep("\0", 16) .. et)
return pt:sub(33)
end
local function stream_key(pk, sk)
assert(#pk == 32, "#pk must be 32")
assert(#sk == 32, "#pk must be 32")
pk = table.pack(pk:byte(1, 32))
sk = table.pack(sk:byte(1, 32))
local k = {}
ec25519.crypto_scalarmult(k, sk, pk)
k = string.char(table.unpack(k))
return salsa20.hsalsa20(k, 0, string.rep("\0", 8))
end
local function box(pt, nonce, pk_b, sk_a)
return secretbox(pt, nonce, stream_key(pk_b, sk_a))
end
local function box_open(et, nonce, pk_a, sk_b)
return secretbox_open(et, nonce, stream_key(pk_a, sk_b))
end
return {
public_key = public_key,
secretbox = secretbox,
secretbox_open = secretbox_open,
stream_key = stream_key,
box = box,
box_open = box_open,
}
| mit |
bocaaust/BellBoy | App/BellBoy Console/Libs/RuntimeResources.bundle/socket.lua | 6 | 4446 | -----------------------------------------------------------------------------
-- LuaSocket helper module
-- Author: Diego Nehab
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local string = require("string")
local math = require("math")
local socket = require("socket")
local _M = socket
-----------------------------------------------------------------------------
-- Exported auxiliar functions
-----------------------------------------------------------------------------
function _M.connect4(address, port, laddress, lport)
return socket.connect(address, port, laddress, lport, "inet")
end
function _M.connect6(address, port, laddress, lport)
return socket.connect(address, port, laddress, lport, "inet6")
end
function _M.bind(host, port, backlog)
if host == "*" then host = "0.0.0.0" end
local addrinfo, err = socket.dns.getaddrinfo(host);
if not addrinfo then return nil, err end
local sock, res
err = "no info on address"
for i, alt in base.ipairs(addrinfo) do
if alt.family == "inet" then
sock, err = socket.tcp()
else
sock, err = socket.tcp6()
end
if not sock then return nil, err end
sock:setoption("reuseaddr", true)
res, err = sock:bind(alt.addr, port)
if not res then
sock:close()
else
res, err = sock:listen(backlog)
if not res then
sock:close()
else
return sock
end
end
end
return nil, err
end
_M.try = _M.newtry()
function _M.choose(table)
return function(name, opt1, opt2)
if base.type(name) ~= "string" then
name, opt1, opt2 = "default", name, opt1
end
local f = table[name or "nil"]
if not f then base.error("unknown key (".. base.tostring(name) ..")", 3)
else return f(opt1, opt2) end
end
end
-----------------------------------------------------------------------------
-- Socket sources and sinks, conforming to LTN12
-----------------------------------------------------------------------------
-- create namespaces inside LuaSocket namespace
local sourcet, sinkt = {}, {}
_M.sourcet = sourcet
_M.sinkt = sinkt
_M.BLOCKSIZE = 2048
sinkt["close-when-done"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if not chunk then
sock:close()
return 1
else return sock:send(chunk) end
end
})
end
sinkt["keep-open"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if chunk then return sock:send(chunk)
else return 1 end
end
})
end
sinkt["default"] = sinkt["keep-open"]
_M.sink = _M.choose(sinkt)
sourcet["by-length"] = function(sock, length)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if length <= 0 then return nil end
local size = math.min(socket.BLOCKSIZE, length)
local chunk, err = sock:receive(size)
if err then return nil, err end
length = length - string.len(chunk)
return chunk
end
})
end
sourcet["until-closed"] = function(sock)
local done
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if done then return nil end
local chunk, err, partial = sock:receive(socket.BLOCKSIZE)
if not err then return chunk
elseif err == "closed" then
sock:close()
done = 1
return partial
else return nil, err end
end
})
end
sourcet["default"] = sourcet["until-closed"]
_M.source = _M.choose(sourcet)
return _M
| apache-2.0 |
sohrab96/cyrax | plugins/stats.lua | 79 | 4014 | do
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(receiver, chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false)
return --text
end
local function chat_stats2(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nGroups: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == 'teleseed' then -- Put everything you like :)
local about = _config.about_text
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ")
return about
end
if matches[1]:lower() == "statslist" then
if not is_momod(msg) then
return "For mods only !"
end
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats2(chat_id)
end
if matches[1]:lower() == "stats" then
if not matches[2] then
if not is_momod(msg) then
return "For mods only !"
end
if msg.to.type == 'chat' or msg.to.type == 'channel' then
local receiver = get_receiver(msg)
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats(receiver, chat_id)
else
return
end
end
if matches[2] == "teleseed" then -- Put everything you like :)
if not is_admin1(msg) then
return "For admins only !"
else
return bot_stats()
end
end
if matches[2] == "group" then
if not is_admin1(msg) then
return "For admins only !"
else
return chat_stats(matches[3])
end
end
end
end
return {
patterns = {
"^[#!/]([Ss]tats)$",
"^[#!/]([Ss]tatslist)$",
"^[#!/]([Ss]tats) (group) (%d+)",
"^[#!/]([Ss]tats) (teleseed)",
"^[#!/]([Tt]eleseed)"
},
run = run
}
end | gpl-2.0 |
hleuwer/luayats | examples/test-7.lua | 1 | 3503 | require "yats.stdlib"
require "yats.src"
require "yats.muxdmx"
require "yats.misc"
-- Example test-1.lua: Derived from yats example 'tst'.
--
-- cbrsrc_1 --> |\ /|--> line_1 --> sink_1
-- cbrsrc_2 --> | | | |--> line_2 --> sink_2
-- cbrsrc_3 --> | | -->| |--> line_3 --> sink_3
-- cbrsrc_4 --> | | | |--> line_4 --> sink_4
-- cbrsrc_n --> |/ \|--> line_n --> sink_n
-- mux demux
-- Setting test non nil provides additional output.
test = nil
-- Show a list of loaded packages.
print("Loaded packages: \n"..ptostring(_LOADED))
-- Init the yats random generator.
print("Init random generator.")
yats.sim:SetRand(10)
-- Reset simulation time.
print("Reset simulation time.")
yats.sim:ResetTime()
-- Use any number you like here
nsrc = 6
-- Create luacontrol object
luactrl = yats.luacontrol{
"luactrl",
file = "examples/test-7-control.lua",
}
-- Create Sources
src = {}
for i = 1, nsrc do
src[i] = yats.cbrsrc{"src"..i, delta = 2, vci = i, out = {"mux", "in"..i}}
end
-- Create Multiplexer
mx = yats.mux{"mux", ninp=nsrc, buff=10, out={"demux", "demux"}}
-- Create Demultiplexer
-- We first create the list of otputs.
local dout = {}
for i = 1, nsrc do
dout[i] = {"line"..i, "line"}
end
dmx = yats.demux{"demux", maxvci = nsrc, nout = nsrc, out = dout}
-- Create Lines and Sinks
lin, snk = {}, {}
for i = 1, nsrc do
lin[i] = yats.line{"line"..i, delay = 2, out = {"sink"..i, "sink"}}
snk[i] = yats.sink{"sink"..i}
-- Provide a routing table entry for this source
dmx:signal{i,i,i}
end
-- Some test output
if test then
print(yats.sim:list("\nList of objects","\t"))
print("List of objects:"..tostring(yats.sim:list()))
print("\nA more detailed look on objects:")
print(pretty(yats.sim.objectlist))
end
-- Connection management
--yats.sim:run(0,0)
yats.sim:connect()
-- Check connection
print("Connection check:")
for i = 1, nsrc do
print("\tsuc of "..src[i].name..": "..src[i]:get_suc().name, src[i]:get_shand())
print("\tsuc "..i.." of "..dmx.name..": "..dmx:get_suc(i).name, dmx:get_shand(i))
print("\tsuc of "..lin[i].name..": "..lin[i]:get_suc().name, lin[i]:get_shand())
end
-- Display demux switch table
print("demux switch table: "..tostring(dmx:getRouting()))
local st, entries
st, entries = dmx:getRouting()
print("Table has "..entries.." entries.")
for i = 1, table.getn(st) do
print("(from, to, outp) = ("..st[i].from..", "..st[i].to..", "..st[i].outp..")")
end
-- Run simulation: 1. path
result = {}
yats.sim:run(1000000, 100000)
print("Mux Queue Len: "..mx:getQLen())
-- Run simulation: 2. path (optional)
yats.sim:run(1000000, 100000)
-- Display some values from the Multiplexer.
print("Mux Queue Len: "..mx:getQLen())
print("Mux Queue MaxLen: "..mx:getQMaxLen())
table.insert(result, mx:getQLen())
table.insert(result, mx:getQMaxLen())
for i = 1, nsrc do
print("Mux "..mx.name.." Loss "..i..": "..mx:getLoss(i).." "..mx:getLossVCI(i))
table.insert(result, mx:getLoss(i))
-- Note: tolua maps lua table index 1 to C index 0.
-- Hence, we to add 1 to the vci index in mx.yatsobj.lostVCI[i]
print("Mux "..mx.name.." Loss "..i..": "..mx.lost[i].." "..mx.lostVCI[i+1])
end
-- Display source counters.
for i = 1, nsrc do
print("Source "..src[i].name.." couont: "..src[i]:getCounter())
table.insert(result, src[i]:getCounter())
end
-- Display sink counter.
for i = 1, nsrc do
print("Sink "..snk[i].name.." count: "..snk[i]:getCounter())
table.insert(result, snk[i]:getCounter())
end
return result
| gpl-2.0 |
alirezanile/Nilebot | plugins/inpm.lua | 59 | 3138 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
--Copyright; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
tianxiawuzhei/cocos-quick-lua | quick/samples/tests/src/tests/framework/interfaceTest.lua | 8 | 4367 |
local InterfaceTestScene = game.createSceneClass("InterfaceTestScene")
function InterfaceTestScene:ctor()
self:prepare({
description = "Please check console output"
})
local items = {
"register",
"modebase",
"functions"
}
self:addChild(game.createMenu(items, handler(self, self.runTest)))
cc.FileUtils:getInstance():addSearchPath("res/")
end
function InterfaceTestScene:registerTest()
local register = require("framework.cc.Registry")
local eventProtocol = register.newObject("components.behavior.EventProtocol")
if not eventProtocol then
printError("ERROR some thing wrong please check Register")
end
register.setObject(eventProtocol, "cryptoTest1")
if not register.isObjectExists("cryptoTest1") then
printError("ERROR some thing wrong please check Register")
end
register.getObject("cryptoTest1")
register.removeObject("cryptoTest1")
if register.isObjectExists("cryptoTest1") then
printError("ERROR some thing wrong please check Register")
end
if not register.exists("components.behavior.EventProtocol") then
printError("ERROR some thing wrong please check Register")
end
end
function InterfaceTestScene:modebaseTest()
local mvcBase = require("framework.cc.mvc.ModelBase")
end
function InterfaceTestScene:functionsTest()
-- iskindof
local Animal = class("Animal")
local Duck = class("Duck", Animal)
if not iskindof(Duck.new(), "Animal") then
printError("ERROR somenthing wrong in iskindof()")
end
local subNode = class("subNode", function() return display.newNode() end).new()
if not iskindof(subNode, "subNode") then
printError("ERROR somenthing wrong in iskindof()")
end
local val = math.round(0.1)
print("val want 0, actual is " .. val)
val = math.round(1.5)
print("val want 2, actual is " .. val)
val = math.round("string")
print("val want 0, actual is " .. val)
val = math.angle2radian(1)
print("val want 0.017453292519943, actual is " .. val)
val = math.radian2angle(1)
print("val want 57.295779513082, actual is " .. val)
local path = cc.FileUtils:getInstance():fullPathForFilename("testFile.dat")
if not io.exists(path) then
printError("ERROR somenthing wrong in io.exists()")
end
print("io.readfile content:" .. io.readfile(path))
io.writefile(io.pathinfo(path).dirname .. "testFile1.dat", "1232kddk")
val = io.filesize(path)
print("io.filesize size:" .. val)
-- table
local table1 = {key1 = "val1", "val2", key3 = "val3"}
local array = {45, 25, "name1", "name2", "same", "htl", "same"}
val = table.nums(table1)
print("table.nums want 3, actual " .. val)
dump(table.keys(table1), "table.keys want {1, key1, key3}, actual:")
dump(table.values(table1), "table.values want {val2, val1, val3}, actual:")
local table2 = {3, key11 = "val11"}
table.merge(table2, table1)
dump(table2, "tabel.merge want {val2, key1 = val1, key11 = val11, key3 = val3, actual:")
local src = {4, 5}
local dest = {1, 2}
table.insertto(dest, src, 4)
dump(dest, "tabel.insertto want {1, 2, 4, 5, actual:")
val = table.indexof(dest, 2)
print("table.indexof want 2, actual " .. val)
val = table.keyof(table2, "val11")
print("table.keyof want key11, actual " .. val)
val = table.removebyvalue(array, "same", true)
print("table.removebyvalue want 2, actual " .. val)
local t = {name = "dualface", comp = "chukong"}
table.map(table2, function(v, k)
return "[" .. v .. "]"
end)
table.walk(table2, function(v, k)
print(v)
end)
table.filter(table2, function(v, k)
return v ~= "[val11]"
end)
table.walk(table2, function(v, k)
print(v)
end)
table2[102] = "same"
table2[103] = "same"
table2 = table.unique(table2)
dump(table2, "should just have one \"same\" value:")
print(string.htmlspecialchars("<ABC>"))
print(string.restorehtmlspecialchars(string.htmlspecialchars("<ABC>")))
print(string.nl2br("Hello\nWorld"))
print(string.text2html("<Hello>\nWorld"))
local input = "Hello-+-World-+-Quick"
local res = string.split(input, "-+-")
dump(res, "string.split :")
print(string.ltrim(" ABC"))
print(string.rtrim("ABC "))
print(string.trim(" ABC "))
print(string.ucfirst("aBC"))
print(string.urlencode("ABC ABC"))
print(string.urldecode(string.urlencode("ABC ABC")))
print(string.utf8len("你好World"))
print(string.formatnumberthousands(1924235))
end
return InterfaceTestScene
| mit |
tianxiawuzhei/cocos-quick-lua | quick/samples/ui/src/app/scenes/TestUIPageViewScene.lua | 8 | 1893 |
local TestUIPageViewScene = class("TestUIPageViewScene", function()
return display.newScene("TestUIPageViewScene")
end)
function TestUIPageViewScene:ctor()
app:createGrid(self)
self:createPageView()
app:createTitle(self, "Test UIPageView")
app:createNextButton(self)
end
function TestUIPageViewScene:createPageView()
self.pv = cc.ui.UIPageView.new {
-- bgColor = cc.c4b(200, 200, 200, 120),
-- bg = "sunset.png",
viewRect = cc.rect(80, 80, 780, 480),
column = 3, row = 3,
padding = {left = 20, right = 20, top = 20, bottom = 20},
columnSpace = 10, rowSpace = 10}
:onTouch(handler(self, self.touchListener))
:addTo(self)
-- add items
for i=1,18 do
local item = self.pv:newItem()
local content
-- content = cc.ui.UILabel.new(
-- {text = "item"..i,
-- size = 20,
-- align = cc.ui.TEXT_ALIGN_CENTER,
-- color = display.COLOR_BLACK})
content = cc.LayerColor:create(
cc.c4b(math.random(250),
math.random(250),
math.random(250),
250))
content:setContentSize(240, 140)
content:setTouchEnabled(false)
item:addChild(content)
self.pv:addItem(item)
end
self.pv:reload()
-- clone Test code
-- local clonePV
-- clonePV = self.pv:clone()
-- if clonePV then
-- clonePV:reload()
-- clonePV:addTo(self)
-- self.pv:removeSelf()
-- end
end
function TestUIPageViewScene:touchListener(event)
dump(event, "TestUIPageViewScene - event:")
local listView = event.listView
if 3 == event.itemPos then
listView:removeItem(event.item, true)
else
-- event.item:setItemSize(120, 80)
end
end
return TestUIPageViewScene
| mit |
stanfordhpccenter/soleil-x | testcases/legacy/taylor_with_smaller_particles/taylor_green_vortex_1024_1024_512.lua | 1 | 4167 | -- This is a Lua config file for the Soleil code.
return {
xnum = 1024, -- number of cells in the x-direction
ynum = 1024, -- number of cells in the y-direction
znum = 512, -- number of cells in the z-direction
-- if you increase the cell number and the calculation diverges
-- right away, decrease the time step on the next line
delta_time = 1.0e-4,
-- Control max iterations here. Set to a very high number if
-- you want to run the full calculation (it will stop once
-- it hits the 20.0 second max time set below)
max_iter = 20,
-- Output options. All output is off by default, but we
-- will need to turn it on to check results/make visualizations
consoleFrequency = 5, -- Iterations between console output of statistics
wrtRestart = 'OFF',
wrtVolumeSolution = 'OFF',
wrt1DSlice = 'OFF',
wrtParticleEvolution = 'OFF',
particleEvolutionIndex = 0,
outputEveryTimeSteps = 50,
restartEveryTimeSteps = 50,
-------------------------------------------
--[ SHOULD NOT NEED TO MODIFY BELOW HERE]--
-------------------------------------------
-- Flow Initialization Options --
initCase = 'TaylorGreen3DVortex', -- Uniform, Restart, TaylorGreen2DVortex, TaylorGreen3DVortex
initParams = {1.0,100.0,2.0,0.0,0.0}, -- for TGV: first three are density, pressure, velocity
bodyForce = {0,0.0,0}, -- body force in x, y, z
turbForcing = 'OFF', -- Turn turbulent forcing on or off
turbForceCoeff = 0.0, -- Turbulent linear forcing coefficient (f = A*rho*u)
restartIter = 10000,
-- Grid Options -- PERIODICITY
origin = {0.0, 0.0, 0.0}, -- spatial origin of the computational domain
xWidth = 6.283185307179586,
yWidth = 6.283185307179586,
zWidth = 6.283185307179586,
-- BCs on each boundary: 'periodic,' 'symmetry,' or 'wall'
xBCLeft = 'periodic',
xBCLeftVel = {0.0, 0.0, 0.0},
xBCLeftTemp = 0.0,
xBCRight = 'periodic',
xBCRightVel = {0.0, 0.0, 0.0},
xBCRightTemp = 0.0,
yBCLeft = 'periodic',
yBCLeftVel = {0.0, 0.0, 0.0},
yBCLeftTemp = 0.0,
yBCRight = 'periodic',
yBCRightVel = {0.0, 0.0, 0.0},
yBCRightTemp = 0.0,
zBCLeft = 'periodic',
zBCLeftVel = {0.0, 0.0, 0.0},
zBCLeftTemp = 0.0,
zBCRight = 'periodic',
zBCRightVel = {0.0, 0.0, 0.0},
zBCRightTemp = 0.0,
--Time Integration Options --
cfl = 1.0, -- Negative CFL implies that we will used fixed delta T
final_time = 20.00001,
--- File Output Options --
headerFrequency = 200000,
outputFormat = 'Tecplot', --Tecplot or Python
-- Fluid Options --
gasConstant = 20.4128,
gamma = 1.4,
viscosity_model = 'PowerLaw', -- Constant, PowerLaw, Sutherland
constant_visc = 0.004491, -- Value for a constant viscosity [kg/m/s]
powerlaw_visc_ref = 0.00044,
powerlaw_temp_ref = 1.0,
prandtl = 0.7,
suth_visc_ref = 1.716E-5, -- Sutherland's Law reference viscosity [kg/m/s]
suth_temp_ref = 273.15, -- Sutherland's Law reference temperature [K]
suth_s_ref = 110.4, -- Sutherland's Law S constant [K]
-- Particle Options --
-- completely disable particles, including all data
modeParticles = 'ON',
initParticles = 'Uniform', -- 'Random' or 'Restart'
restartParticleIter = 0,
particleType = 'Free', -- Fixed or Free
twoWayCoupling = 'OFF', -- ON or OFF
num = 32000000,
restitutionCoefficient = 1.0,
convectiveCoefficient = 0.7, -- W m^-2 K^-1
heatCapacity = 0.7, -- J Kg^-1 K^-1
initialTemperature = 20, -- K
density = 8900, -- kg/m^3
diameter_mean = 5e-3, -- m
diameter_maxDeviation = 1e-3, -- m, for statistical distribution
bodyForceParticles = {0.0,0.0,0.0},
absorptivity = 1.0, -- Equal to emissivity in thermal equilibrium
maximum_num = 32000000, -- upper bound on particles with insertion
insertion_rate = 0, -- per face and per time step
insertion_mode = {0,0,0,0,0,0}, --bool, MinX MaxX MinY MaxY MinZ MaxZ
deletion_mode = {0,0,0,0,0,0}, --bool, MinX MaxX MinY MaxY MinZ MaxZ
-- (Kirchhoff law of thermal radiation)
-- Radiation Options --
radiationType = 'Algebraic', -- ON or OFF
radiationIntensity = 1e3,
zeroAvgHeatSource = 'OFF'
}
| gpl-2.0 |
rickvanbodegraven/nodemcu-firmware | lua_modules/redis/redis.lua | 86 | 2621 | ------------------------------------------------------------------------------
-- Redis client module
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <dronnikov@gmail.com>
--
-- Example:
-- local redis = dofile("redis.lua").connect(host, port)
-- redis:publish("chan1", foo")
-- redis:subscribe("chan1", function(channel, msg) print(channel, msg) end)
------------------------------------------------------------------------------
local M
do
-- const
local REDIS_PORT = 6379
-- cache
local pairs, tonumber = pairs, tonumber
--
local publish = function(self, chn, s)
self._fd:send(("*3\r\n$7\r\npublish\r\n$%d\r\n%s\r\n$%d\r\n%s\r\n"):format(
#chn, chn, #s, s
))
-- TODO: confirmation? then queue of answers needed
end
local subscribe = function(self, chn, handler)
-- TODO: subscription to all channels, with single handler
self._fd:send(("*2\r\n$9\r\nsubscribe\r\n$%d\r\n%s\r\n"):format(
#chn, chn
))
self._handlers[chn] = handler
-- TODO: confirmation? then queue of answers needed
end
local unsubscribe = function(self, chn)
self._handlers[chn] = false
end
-- NB: pity we can not just augment what net.createConnection returns
local close = function(self)
self._fd:close()
end
local connect = function(host, port)
local _fd = net.createConnection(net.TCP, 0)
local self = {
_fd = _fd,
_handlers = { },
-- TODO: consider metatables?
close = close,
publish = publish,
subscribe = subscribe,
unsubscribe = unsubscribe,
}
_fd:on("connection", function()
--print("+FD")
end)
_fd:on("disconnection", function()
-- FIXME: this suddenly occurs. timeout?
--print("-FD")
end)
_fd:on("receive", function(fd, s)
--print("IN", s)
-- TODO: subscription to all channels
-- lookup message pattern to determine channel and payload
-- NB: pairs() iteration gives no fixed order!
for chn, handler in pairs(self._handlers) do
local p = ("*3\r\n$7\r\nmessage\r\n$%d\r\n%s\r\n$"):format(#chn, chn)
if s:find(p, 1, true) then
-- extract and check message length
-- NB: only the first TCP packet considered!
local _, start, len = s:find("(%d-)\r\n", #p)
if start and tonumber(len) == #s - start - 2 and handler then
handler(chn, s:sub(start + 1, -2)) -- ends with \r\n
end
end
end
end)
_fd:connect(port or REDIS_PORT, host)
return self
end
-- expose
M = {
connect = connect,
}
end
return M
| mit |
Neui/cc-things | minccweeper.lua | 1 | 8482 | --[[
+---=== minccweeper ===---+
| This is a 'recreation' |
| of minesweeper for the |
| Minecraft modification |
| computercraft. |
+-------------------------+
Made by Neui
]]
local currVer = 0 -- Version of this program
local w, h = term.getSize() -- Size of the screen
local running = true -- Program runs
local f = {} -- Functions
f.draw = {} -- Drawing functions
local v = {} -- Variables
v.state = 1 -- State 0 = startup, 1 = Main menu, 2 = Ingame
v.sel = { ["title"] = 1; ["customField"] = 0; }
v.titleSelection = {}
v.field = { ["width"] = 9; ["height"] = 9; ["mines"] = 10; }
v.time = 0
v.draw = {}
v.draw.fieldMoved = true
v.draw.redraw = true
local c = {} -- constants
c.name = "minCCweeper"
c.title = "~[ " .. c.name .. " ]~"
c.field = { ["maxwidth"] = 30; ["maxheight"] = 24; ["minmines"] = 10; ["maxmines"] = 668; }
c.field.draw = {}
c.field.draw.unknown = { ["char"] = '#'; ["fgmono"] = colors.white; ["bgadv"] = colors.gray; ["bgmono"] = colors.black; }
c.field.draw.nothing = { ["char"] = ' '; }
c.field.draw.mine = { ["char"] = 'O'; ["fgadv"] = colors.red; }
c.field.draw.mightMine = { ["char"] = 'P'; ["fgadv"] = colors.lightGray; }
c.field.draw.numbers = { ["fg"] = { colors.blue, colors.green, colors.red, colors.blue, colors.brown, colors.lightBlue, colors.gray, colors.lightGray }; }
c.field.presets = {} -- Also taken form windows minesweeper
c.field.presets.beginner = { ["name"] = "Beginner"; ["width"] = 9; ["height"] = 9; ["mines"] = 10; }
c.field.presets.advanced = { ["name"] = "Advanced"; ["width"] = 16; ["height"] = 16; ["mines"] = 40; }
c.field.presets.pro = { ["name"] = "Professional"; ["width"] = 30; ["height"] = 16; ["mines"] = 99; }
local playfield = {} -- Contains all of the bombs etc.
local playerfiled = {} -- What the players sees
local function csleep(sec)
local timer, p1 = os.startTimer(tonumber(sec or 0))
repeat
local _, p1 = os.pullEventRaw("timer")
until p1 == timer
end
-- Main Drawing Loop
function f.drawLoop()
while running do
if v.draw.redraw then
f.draw.setTBGColor(term, colors.white, colors.black)
term.clear()
end
if v.state == 1 or v.state == 2 then -- Main Selection
f.draw.title(term, w, h)
f.draw.titleSelection(term, w, h)
f.draw.fieldSizeAndWidth(term, w, h)
if v.state == 2 then
term.setCursorPos(w, h-1)
term.setCursorBlink(true)
else
end
elseif v.state == 3 then -- ingame
if v.draw.fieldMoved or v.draw.redraw then
f.draw.field(term, w, h, field)
end
f.draw.footer(term, w, h)
end
csleep(0)
end
end
function f.draw.field(term, w, h, field)
end
function f.draw.footer(term, w, h)
-- [FHxFW MI TIMEs]
f.draw.setBGColor(term, colors.black)
term.setCursorPos(1, h)
f.draw.setTextColor(term, colors.green)
term.write(tostring(v.field.width))
f.draw.setTextColor(term, colors.white)
term.write("x")
f.draw.setTextColor(term, colors.green)
term.write(tostring(v.field.height))
f.draw.setTextColor(term, colors.brown)
term.write(" " .. tostring(v.field.mines))
end
function f.draw.title(term, w, h)
term.setCursorPos((w/2)-(#c.title/2), h/#v.titleSelection)
term.write(c.title)
end
function f.draw.titleSelection(term, w, h)
for k, val in ipairs(v.titleSelection) do
term.setCursorPos((w/2)-((#val.name+2)/2), (h/2)-(#v.titleSelection/2)+k)
if k == v.sel.title then
f.draw.setTBGColor(term, colors.black, colors.lightGray, colors.white)
else
f.draw.setTBGColor(term, colors.white, colors.black)
end
term.write(" " .. val.name .. " ")
end
end
function f.draw.fieldSizeAndWidth(term, w, h)
term.setCursorPos(w/2-7, h-1)
f.draw.setTBGColor(term, colors.white, colors.black)
term.write(" x Mines")
term.setCursorPos(w/2-7, h-1)
f.draw.setTBGColor(term, colors.orange, colors.black, colors.white)
if v.field.width < 10 then
term.write("0")
end
term.write(tostring(v.field.width))
term.setCursorPos(w/2-4, h-1)
if v.field.height < 10 then
term.write("0")
end
term.write(tostring(v.field.height))
term.setCursorPos(w/2-1, h-1)
if v.field.mines < 100 then
term.write("0")
elseif v.field.mines < 10 then
term.write("00")
end
term.write(tostring(v.field.mines))
end
function f.draw.setTextColor(term, adv, mono)
local mono, adv = tonumber(mono) or tonumber(adv) or 1, tonumber(adv) or 1
if term.isColor and term.isColor() then
term.setTextColor(adv)
else
term.setTextColor(mono)
end
end
function f.draw.setBGColor(term, adv, mono)
local mono, adv = tonumber(mono) or tonumber(adv) or colors.black, tonumber(adv) or colors.black
if term.isColor and term.isColor() then
term.setBackgroundColor(adv)
else
term.setBackgroundColor(mono)
end
end
function f.draw.setTBGColor(term, advt, advbg, monot, monobg)
f.draw.setTextColor(term, advt, monot)
f.draw.setBGColor(term, advbg, monobg)
end
function f.getFromFieldPos(x, y, field)
return field[x*y]
end
function f.doSelection(sel, tsel, field)
if tsel[sel]["function"] == "exit" then
running = false
elseif tsel[sel]["function"] == "custom" then
else
v.state = 3
end
end
function f.inputLoop()
while running do
local ev, p1, p2, p3, p4, p5 = os.pullEventRaw()
if ev == "terminate" then
running = false
elseif ev == "term.resize" then
w, h = term.getSize()
elseif ev == "key" then
if v.state == 1 then -- Main menu
if p1 == 200 then -- Up Arrow
v.sel.title = ((v.sel.title - 2) % #v.titleSelection) + 1
elseif p1 == 208 then -- Down Arrow
v.sel.title = (v.sel.title % #v.titleSelection) + 1
elseif p1 == 28 then -- Enter
f.doSelection(v.sel.title, v.titleSelection, v.field)
end
if not v.titleSelection[v.sel.title]["function"] then
v.field.width = v.titleSelection[v.sel.title]["width"]
v.field.height = v.titleSelection[v.sel.title]["height"]
v.field.mines = v.titleSelection[v.sel.title]["mines"]
end
elseif v.mode == 2 then -- Custom selection
elseif v.mode == 3 then -- Ingame
end
elseif ev == "mouse_click" or ev == "mouse_drag" then
if v.state == 1 then -- Main menu
for k = 1, #v.titleSelection do
local hpos = math.floor((h/2)-(#v.titleSelection/2)+k)
if hpos == p3 then
if p1 == 1 and ev == "mouse_click" then
v.sel.title = k
os.queueEvent("key", 28) -- Enter, i am too lazy
else
if v.sel.title == k and ev == "mouse_click" then
os.queueEvent("key", 28) -- Enter
else
v.sel.title = k
end
end
break
end
end
elseif v.mode == 2 then -- Custom selection
elseif v.mode == 3 then -- Ingame
end
end
end
end
-- Main Program
local function main()
parallel.waitForAny(f.inputLoop, f.drawLoop)
end
-- Initalise
local function init()
local notice = false
f.draw.setTextColor(term, colors.white)
-- Setup the titlescreen selection
for k, val in pairs(c.field.presets) do
v.titleSelection[#v.titleSelection + 1] = val
end
v.titleSelection[#v.titleSelection + 1] = {["name"] = "Custom"; ["function"] = "custom";}
v.titleSelection[#v.titleSelection + 1] = {["name"] = "Exit"; ["function"] = "exit"; }
if notice and running then
write("\nPress a key to continue... (or wait 10s)")
local tim, ev, p1 = os.startTimer(10)
repeat
ev, p1 = os.pullEventRaw()
until (ev == "key") or (ev == "timer" and p1 == tim)
end
end
local est, emsg = pcall(init)
if not running or not est then -- error
if not est then
write(string.format("\nAn error happend during init:\n%s\n", tostring(emsg)))
else
write("\nProgram terminated.\n")
end
else
local _gsStart = os.clock()
local est, emsg = pcall(main)
term.setTextColor(1)
term.setBackgroundColor(32768)
term.clear()
term.setCursorPos(1,1)
if not est then
write(string.format("An error happend:\n%s\n", tostring(emsg)))
else
write("Program terminated.\n")
end
local _gs = math.floor(os.clock() - _gsStart + 0.5)
local _h, _m, _s = _gs / 3600, (_gs / 60) % 60, _gs % 60
write(string.format("Ran for %uh%um%us (%us)\n", _h, _m, _s, _gs))
end | mit |
cshore/luci | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/interface.lua | 68 | 1060 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
require("luci.sys")
m = Map("luci_statistics",
translate("Interface Plugin Configuration"),
translate(
"The interface plugin collects traffic statistics on " ..
"selected interfaces."
))
-- collectd_interface config section
s = m:section( NamedSection, "collectd_interface", "luci_statistics" )
-- collectd_interface.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_interface.interfaces (Interface)
interfaces = s:option( MultiValue, "Interfaces", translate("Monitor interfaces") )
interfaces.widget = "select"
interfaces.size = 5
interfaces:depends( "enable", 1 )
for k, v in pairs(luci.sys.net.devices()) do
interfaces:value(v)
end
-- collectd_interface.ignoreselected (IgnoreSelected)
ignoreselected = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") )
ignoreselected.default = 0
ignoreselected:depends( "enable", 1 )
return m
| apache-2.0 |
ld-test/oil | lua/oil/properties.lua | 6 | 2776 | -- $Id$
--******************************************************************************
-- Copyright 2002 Noemi Rodriquez & Roberto Ierusalimschy. All rights reserved.
--******************************************************************************
--------------------------------------------------------------------------------
------------------------------ ##### ## ------------------------------
------------------------------ ## ## # ## ------------------------------
------------------------------ ## ## ## ## ------------------------------
------------------------------ ## ## # ## ------------------------------
------------------------------ ##### ### ###### ------------------------------
-------------------------------- --------------------------------
----------------------- An Object Request Broker in Lua ------------------------
--------------------------------------------------------------------------------
-- Project: OiL - ORB in Lua: An Object Request Broker in Lua --
-- Release: 0.5 --
-- Title : Properties management package for OiL --
-- Authors: Leonardo S. A. Maciel <leonardo@maciel.org> --
--------------------------------------------------------------------------------
-- Interface: --
--------------------------------------------------------------------------------
-- Notes: --
--------------------------------------------------------------------------------
local require = require
local rawget = rawget
local rawset = rawset
local oo = require "loop.base"
module("oil.properties", oo.class) --[[VERBOSE]] local verbose = require "oil.verbose"
--------------------------------------------------------------------------------
-- Key constants ---------------------------------------------------------------
local PARENT = {}
local DEFAULT = {}
--------------------------------------------------------------------------------
-- Properties implementation ---------------------------------------------------
function __index(self, key)
if key then
local parent = rawget(self, PARENT)
local default = rawget(self, DEFAULT)
local value = parent and parent[key] or default and default[key] or nil
rawset(self, key, value)
return value
else
return nil
end
end
function __init(self, parent, default)
return oo.rawnew(self, {[PARENT] = parent,
[DEFAULT]= default})
end
| mit |
hleuwer/luayats | yats/polshap.lua | 1 | 3246 | -----------------------------------------------------------------------------------
-- @copyright GNU Public License.
-- @author Herbert Leuwer, Backnang.
-- @release 3.0 $Id: polshap.lua 420 2010-01-06 21:39:36Z leuwer $
-- @description LuaYats - Policers and shapers.
-- <br>
-- <br><b>module: yats</b><br>
-- <br>
-- Lua classes for policers and shapers.
-----------------------------------------------------------------------------------
module("yats", yats.seeall)
--==========================================================================
-- Leaky Bucket Object.
--==========================================================================
_lb = lb
--- Definition of sourceo object 'lb' (Leaky Bucket).
lb = class(_lb)
--- Constructor for class 'lb'.
-- Constant bit rate (CBR) source.
-- @param param table - Parameter list
-- <ul>
-- <li>name (optional)<br>
-- Name of the display. Default: "objNN"
-- <li>delta<br>
-- Cell rate in ticks
-- <li>vci<br>
-- Virtual connection id for the cell
-- <li>out<br>
-- Connection to successor
-- Format: {"name-of-successor", "input-pin-of-successor"}
-- </ul>.
-- @return table - Reference to object instance.
function lb:init(param)
self = _lb:new()
self.name = autoname(param)
self.clname = "cbrsrc"
self.parameters = {
inc = true, dec = true, size = true, vci = false,
out = true
}
self:adjust(param)
-- 1. create a yats object
-- 2. set object vars in yats object
self.lb_inc = param.inc
self.lb_dec = param.dec
self.vci = param.vci
if self.vci then
self.inp_type = CellType
else
self.inp_type = DataType
end
self.lb_size = 0
self.last_time = 0
-- 3. init output table
self:defout(param.out)
-- 3. init input table
self:definp(self.clname)
-- 4 to 6 can be summarised in a utility method finish()
return self:finish()
end
--==========================================================================
-- Peak Rate Shaper Object.
--==========================================================================
_shap2 = shap2
--- Definition of sourceo object 'shaper2' (Shaper).
shap2 = class(_shap2)
--- Constructor for class 'shap2'.
-- Peak rate shaper with buffer.
-- @param param table - Parameter list
-- <ul>
-- <li>name (optional)<br>
-- Name of the display. Default: "objNN".
-- <li>delta<br>
-- Peak cell rate in ticks.
-- <li>buff<br>
-- Cell buffer size.
-- <li>out<br>
-- Connection to successor.
-- Format: {"name-of-successor", "input-pin-of-successor"}.
-- </ul>.
-- @return table - Reference to object instance.
function shap2:init(param)
self = _shap2:new()
self.name = autoname(param)
self.clname = "shap2"
self.parameters = {
delta = true, buff = true, out = true
}
self:adjust(param)
-- 2. set object vars in yats object
assert(param.delta > 1, self.name ..": delta must be >= 1.")
self.delta = param.delta
self.q_max = param.buff
self.q_len = 0
self.next_time = 0
self. bucket = 0
self.delta_short = self.delta
self.delta_long = self.delta_short + 1
self.splash = self.delta_long - self.delta
-- Outputs
self:defout(param.out)
-- Inputs
self:definp(self.clname)
return self:finish()
end
return yats
| gpl-2.0 |
adamel/sysdig | userspace/sysdig/chisels/topconns.lua | 12 | 1766 | --[[
Copyright (C) 2013-2014 Draios inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--]]
-- Chisel description
description = "Shows the top network connections in terms of total (in+out) bandwidth. This chisel is compatable with containers using the sysdig -pc or -pcontainer argument, otherwise no container information will be shown.";
short_description = "Top network connections by total bytes";
category = "Net";
-- Chisel argument list
args = {}
-- The number of items to show
TOP_NUMBER = 30
-- Argument notification callback
function on_set_arg(name, val)
return false
end
-- Initialization callback
function on_init()
-- The -pc or -pcontainer options was supplied on the cmd line
print_container = sysdig.is_print_container_data()
if print_container then
chisel.exec("table_generator",
"container.name,fd.l4proto,fd.name",
"container.name,Proto,Conn",
"evt.rawarg.res",
"Bytes",
"(fd.type=ipv4 or fd.type=ipv6) and evt.is_io=true",
"" .. TOP_NUMBER,
"bytes")
else
chisel.exec("table_generator",
"fd.l4proto,fd.name",
"Proto,Conn",
"evt.rawarg.res",
"Bytes",
"(fd.type=ipv4 or fd.type=ipv6) and evt.is_io=true",
"" .. TOP_NUMBER,
"bytes")
end
return true
end
| gpl-2.0 |
bizkut/BudakJahat | Libs/DiesalGUI-1.0/Objects/ScrollingEditBox.lua | 4 | 10992 | -- $Id: ScrollingEditBox.lua 60 2016-11-04 01:34:23Z diesal2010 $
local DiesalGUI = LibStub('DiesalGUI-1.0')
-- ~~| Libraries |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local DiesalTools = LibStub('DiesalTools-1.0')
local DiesalStyle = LibStub("DiesalStyle-1.0")
-- ~~| Diesal Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local Colors = DiesalStyle.Colors
local HSL, ShadeColor, TintColor = DiesalTools.HSL, DiesalTools.ShadeColor, DiesalTools.TintColor
-- ~~| Lua Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local type, select, pairs, tonumber = type, select, pairs, tonumber
local setmetatable, getmetatable, next = setmetatable, getmetatable, next
local sub, format, lower, upper = string.sub, string.format, string.lower, string.upper
local floor, ceil, min, max, abs, modf = math.floor, math.ceil, math.min, math.max, math.abs, math.modf
-- ~~| WoW Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local GetCursorPosition = GetCursorPosition
-- ~~| ScrollingEditBox |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local Type = 'ScrollingEditBox'
local Version = 3
-- ~~| ScrollingEditBox Stylesheets |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local Stylesheet = {
['track-background'] = {
type = 'texture',
layer = 'BACKGROUND',
color = '000000',
alpha = .3,
},
['grip-background'] = {
type = 'texture',
layer = 'BACKGROUND',
color = Colors.UI_400,
},
['grip-inline'] = {
type = 'outline',
layer = 'BORDER',
color = 'FFFFFF',
alpha = .02,
},
}
local wireFrame = {
['frame-white'] = {
type = 'outline',
layer = 'OVERLAY',
color = 'ffffff',
},
['scrollFrameContainer-yellow'] = {
type = 'outline',
layer = 'BACKGROUND',
color = 'fffc00',
},
['scrollFrame-orange'] = {
type = 'outline',
layer = 'BORDER',
color = 'ffd400',
},
['editBox-red'] = {
type = 'outline',
layer = 'ARTWORK',
color = 'ff0000',
aplha = .5,
},
['scrollBar-blue'] = {
type = 'outline',
layer = 'OVERLAY',
color = '00aaff',
},
['track-green'] = {
type = 'outline',
layer = 'OVERLAY',
color = '55ff00',
},
}
-- ~~| ScrollingEditBox Locals |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- ~~| ScrollingEditBox Methods |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local methods = {
['OnAcquire'] = function(self)
self:ApplySettings()
self:SetStylesheet(Stylesheet)
-- self:SetStylesheet(wireFrame)
self:Show()
end,
['OnRelease'] = function(self) end,
['ApplySettings'] = function(self)
local settings = self.settings
self.scrollFrame:SetPoint('TOPLEFT',settings.contentPadding[1],-settings.contentPadding[3])
self.scrollFrame:SetPoint('BOTTOMRIGHT',-settings.contentPadding[2],settings.contentPadding[4])
self.scrollBar:SetPoint('TOPRIGHT',0,-settings.contentPadding[3] + 1)
self.scrollBar:SetPoint('BOTTOMRIGHT',0,settings.contentPadding[4] - 1)
self.scrollBar:SetWidth(settings.scrollBarWidth)
self.buttonDown:SetHeight(settings.scrollBarButtonHeight)
self.buttonUp:SetHeight(settings.scrollBarButtonHeight)
self.editBox:SetJustifyH(settings.justifyH)
self.editBox:SetJustifyV(settings.justifyV)
end,
['ShowScrollBar'] = function(self,show)
if show then
self.scrollFrameContainer:SetPoint('BOTTOMRIGHT',-(self.settings.scrollBarWidth + 1),0)
self.scrollBar:Show()
else
self.scrollBar:Hide()
self.scrollFrameContainer:SetPoint('BOTTOMRIGHT',0,0)
end
end,
['SetContentHeight'] = function(self,height)
self.settings.contentHeight = height
self.content:SetHeight(height)
end,
['SetGripSize'] = function(self)
local contentSize = self.scrollFrame:GetVerticalScrollRange() + self.scrollFrame:GetHeight()
local windowSize = self.scrollFrame:GetHeight()
local trackSize = self.track:GetHeight()
local windowContentRatio = windowSize / contentSize
local gripSize = DiesalTools.Round(trackSize * windowContentRatio)
gripSize = max(gripSize, 10) -- might give this a setting?
gripSize = min(gripSize, trackSize)
self.grip:SetHeight(gripSize)
end,
['SetScrollThumbPosition'] = function(self)
local verticalScrollRange = self.scrollFrame:GetVerticalScrollRange() -- windowScrollAreaSize (rounded no need to round)
if verticalScrollRange < 1 then self.grip:SetPoint('TOP',0,0) return end
local verticalScroll = self.scrollFrame:GetVerticalScroll() -- windowPosition
local trackSize = self.track:GetHeight()
local gripSize = self.grip:GetHeight()
local windowPositionRatio = verticalScroll / verticalScrollRange
local trackScrollAreaSize = trackSize - gripSize
local gripPositionOnTrack = DiesalTools.Round(trackScrollAreaSize * windowPositionRatio)
self.grip:SetPoint('TOP',0,-gripPositionOnTrack)
end,
['SetVerticalScroll'] = function(self,scroll) -- user scrolled only
self.settings.forceScrollBottom = DiesalTools.Round(scroll) == DiesalTools.Round(self.scrollFrame:GetVerticalScrollRange())
self.scrollFrame:SetVerticalScroll(scroll)
end,
['SetText'] = function(self,txt)
self.settings.text = txt
self.editBox:SetText(txt or '')
end,
}
-- ~~| ScrollingEditBox Constructor |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local function Constructor()
local self = DiesalGUI:CreateObjectBase(Type)
local frame = CreateFrame('Frame',nil,UIParent)
self.frame = frame
-- ~~ Default Settings ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
self.defaults = {
scrollBarButtonHeight = 1,
scrollBarWidth = 4,
contentPadding = {0,0,0,0},
justifyH = "LEFT",
justifyV = "TOP",
forceScrollBottom = true,
}
-- ~~ Events ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- OnAcquire, OnRelease, OnHeightSet, OnWidthSet
-- OnHide
-- ~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
frame:SetScript("OnHide",function(this) self:FireEvent("OnHide") end)
local scrollFrameContainer = self:CreateRegion("Frame", 'scrollFrameContainer', frame)
scrollFrameContainer:SetAllPoints()
local scrollFrame = self:CreateRegion("ScrollFrame", 'scrollFrame', scrollFrameContainer)
scrollFrame:EnableMouseWheel(true)
scrollFrame:SetScript("OnMouseWheel", function(this,delta)
DiesalGUI:OnMouse(this,'MouseWheel')
if delta > 0 then
self:SetVerticalScroll(max( this:GetVerticalScroll() - 50, 0))
else
self:SetVerticalScroll(min( this:GetVerticalScroll() + 50, this:GetVerticalScrollRange()))
end
end)
scrollFrame:SetScript("OnVerticalScroll", function(this,offset)
-- self.scrollFrame:GetVerticalScrollRange() windowScrollAreaSize
if this:GetVerticalScrollRange() < 1 then -- nothing to scroll
self:ShowScrollBar(false)
else
self:ShowScrollBar(true)
end
self:SetScrollThumbPosition()
end)
scrollFrame:SetScript("OnScrollRangeChanged", function(this,xOffset, verticalScrollRange)
if verticalScrollRange < 1 then -- nothing to scroll
this:SetVerticalScroll(0)
self:ShowScrollBar(false)
return end
if self.settings.forceScrollBottom then
this:SetVerticalScroll(verticalScrollRange)
else
this:SetVerticalScroll(min(this:GetVerticalScroll(),verticalScrollRange))
end
self:ShowScrollBar(true)
self:SetGripSize()
self:SetScrollThumbPosition()
end)
scrollFrame:SetScript("OnSizeChanged", function(this,width,height)
self.editBox:SetWidth(width)
end)
local editBox = self:CreateRegion("EditBox", 'editBox', scrollFrame)
editBox:SetPoint("TOPLEFT")
editBox:SetPoint("TOPRIGHT")
editBox:SetAutoFocus(false)
editBox:SetMultiLine(true)
editBox:HookScript('OnEditFocusLost',function(this)
this:HighlightText(0,0)
this:SetText(self.settings.text)
end)
editBox:HookScript('OnEditFocusGained',function(this)
self:FireEvent("OnEditFocusGained")
end)
editBox:HookScript('OnEscapePressed',function(this)
self:FireEvent("OnEscapePressed")
end)
editBox:HookScript('OnTabPressed',function(this)
self:FireEvent("OnTabPressed")
end)
editBox:HookScript('OnCursorChanged',function(this,...)
self:FireEvent("OnCursorChanged",...)
end)
editBox:HookScript('OnTextChanged',function(this)
self:FireEvent("OnTextChanged")
end)
scrollFrame:SetScrollChild(editBox)
local scrollBar = self:CreateRegion("Frame", 'scrollBar', frame)
scrollBar:Hide()
local buttonUp = self:CreateRegion("Frame", 'buttonUp', scrollBar)
buttonUp:SetPoint('TOPLEFT')
buttonUp:SetPoint('TOPRIGHT')
local buttonDown = self:CreateRegion("Frame", 'buttonDown', scrollBar)
buttonDown:SetPoint('BOTTOMLEFT')
buttonDown:SetPoint('BOTTOMRIGHT')
local track = self:CreateRegion("Frame", 'track', scrollBar)
track:SetPoint('LEFT')
track:SetPoint('RIGHT')
track:SetPoint('TOP',buttonUp,'BOTTOM',0,0)
track:SetPoint('BOTTOM',buttonDown,'TOP',0,0)
local grip = self:CreateRegion("Frame", 'grip', track)
grip:SetPoint('LEFT')
grip:SetPoint('RIGHT')
grip:SetPoint('TOP')
grip:EnableMouse(true)
grip:SetScript("OnMouseDown", function(this,button)
DiesalGUI:OnMouse(this,button)
if button ~= 'LeftButton' then return end
local MouseY = select(2, GetCursorPosition()) / this:GetEffectiveScale()
local effectiveScale = this:GetEffectiveScale()
local trackScrollAreaSize = track:GetHeight() - this:GetHeight()
local gripPositionOnTrack = abs(select(5,this:GetPoint(1)))
this:SetScript("OnUpdate", function(this)
local newGripPosition = gripPositionOnTrack + (MouseY - (select(2, GetCursorPosition()) / effectiveScale ))
newGripPosition = min(max(newGripPosition,0),trackScrollAreaSize)
-- local newGripPositionRatio = newGripPosition / trackScrollAreaSize
-- local windowPosition = newGripPositionRatio * scrollArea:GetVerticalScrollRange()
self:SetVerticalScroll((newGripPosition / trackScrollAreaSize) * scrollFrame:GetVerticalScrollRange())
end)
end)
grip:SetScript("OnMouseUp", function(this,button)
this:SetScript("OnUpdate", function(this) end)
end)
-- ~~ Methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for method, func in pairs(methods) do self[method] = func end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
return self
end
DiesalGUI:RegisterObjectConstructor(Type,Constructor,Version)
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.