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
AmirFieBeR/Amir_FieBeR
plugins/time.lua
771
2865
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Displays the local time in an area", usage = "!time [area]: Displays the local time in that area", patterns = {"^!time (.*)$"}, run = run }
gpl-2.0
minetest-games/Minetest_TNG
mods/default/lua/mapgen/mapgenv57.lua
2
14170
-- mods/default/lua/mapgenv57.lua -- -- Register biomes -- core.clear_registered_biomes() -- Permanent ice core.register_biome({ name = "glacier", node_dust = "default:snowblock", node_top = "default:snowblock", depth_top = 1, node_filler = "default:snowblock", depth_filler = 3, node_stone = "default:ice", node_water_top = "default:ice", depth_water_top = 5, --node_water = "", node_river_water = "default:ice", y_min = -8, y_max = 31000, heat_point = -5, humidity_point = 50, }) core.register_biome({ name = "glacier_ocean", node_dust = "default:snowblock", node_top = "default:gravel", depth_top = 1, node_filler = "default:gravel", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = -9, heat_point = -5, humidity_point = 50, }) -- Cold core.register_biome({ name = "tundra", node_dust = "default:snow", node_top = "default:dirt_with_snow", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 2, y_max = 31000, heat_point = 20, humidity_point = 25, }) core.register_biome({ name = "tundra_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = 1, heat_point = 20, humidity_point = 25, }) core.register_biome({ name = "taiga", node_dust = "default:snow", node_top = "default:snowblock", depth_top = 1, node_filler = "default:dirt", depth_filler = 4, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 2, y_max = 31000, heat_point = 20, humidity_point = 75, }) core.register_biome({ name = "taiga_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = 1, heat_point = 20, humidity_point = 75, }) -- Temperate core.register_biome({ name = "stone_grassland", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 4, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 5, y_max = 31000, heat_point = 45, humidity_point = 25, }) core.register_biome({ name = "stone_grassland_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = 4, heat_point = 45, humidity_point = 25, }) core.register_biome({ name = "coniferous_forest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 4, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 9, y_max = 31000, heat_point = 45, humidity_point = 75, }) core.register_biome({ name = "coniferous_forest_dunes", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 6, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 5, y_max = 8, heat_point = 45, humidity_point = 75, }) core.register_biome({ name = "coniferous_forest_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 4, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = 4, heat_point = 45, humidity_point = 75, }) core.register_biome({ name = "sandstone_grassland", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, node_stone = "default:sandstone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 5, y_max = 31000, heat_point = 70, humidity_point = 25, }) core.register_biome({ name = "sandstone_grassland_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, node_stone = "default:sandstone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = 4, heat_point = 70, humidity_point = 25, }) core.register_biome({ name = "deciduous_forest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 1, y_max = 31000, heat_point = 70, humidity_point = 75, }) core.register_biome({ name = "deciduous_forest_swamp", --node_dust = "", node_top = "default:dirt", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -3, y_max = 0, heat_point = 70, humidity_point = 75, }) core.register_biome({ name = "deciduous_forest_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = -4, heat_point = 70, humidity_point = 75, }) core.register_biome({ name = "maple_forest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 6, node_stone = "default:stone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 2, y_max = 31000, heat_point = 65, humidity_point = 75, }) core.register_biome({ name = "red_maple_forest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 6, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 2, y_max = 31000, heat_point = 65, humidity_point = 70, }) core.register_biome({ name = "mixed_maple_forest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 6, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 1, y_max = 31000, heat_point = 70, humidity_point = 70, }) core.register_biome({ name = "cherry_tree_forest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 5, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 1, y_max = 31000, heat_point = 68, humidity_point = 70, }) core.register_biome({ name = "birch_forest_sandstone", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, node_stone = "default:sandstone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 5, y_max = 31000, heat_point = 70, humidity_point = 25, }) -- Hot core.register_biome({ name = "desert", --node_dust = "", node_top = "default:desert_sand", depth_top = 1, node_filler = "default:desert_sand", depth_filler = 3, node_stone = "default:desert_stone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 5, y_max = 31000, heat_point = 95, humidity_point = 10, }) core.register_biome({ name = "desert_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 5, node_stone = "default:desert_stone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = 4, heat_point = 95, humidity_point = 10, }) core.register_biome({ name = "savanna", --node_dust = "", node_top = "default:dirt_with_dry_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 1, y_max = 31000, heat_point = 90, humidity_point = 50, }) core.register_biome({ name = "savanna_swamp", --node_dust = "", node_top = "default:dirt", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -3, y_max = 0, heat_point = 90, humidity_point = 50, }) core.register_biome({ name = "savanna_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = -4, heat_point = 90, humidity_point = 50, }) core.register_biome({ name = "rainforest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 4, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 1, y_max = 31000, heat_point = 80, humidity_point = 90, }) core.register_biome({ name = "rainforest_swamp", --node_dust = "", node_top = "default:dirt", depth_top = 1, node_filler = "default:dirt", depth_filler = 3, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -3, y_max = 0, heat_point = 80, humidity_point = 90, }) core.register_biome({ name = "rainforest_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = -4, heat_point = 80, humidity_point = 90, }) -- Underground core.register_biome({ name = "underground", --node_dust = "", --node_top = "", --depth_top = , --node_filler = "", --depth_filler = , --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -31000, y_max = -113, heat_point = 50, humidity_point = 50, }) -- -- Register decorations -- local function register_grass_decoration(offset, scale, length, dry) local name = "default:grass_" local biome = {"stone_grassland", "sandstone_grassland", "birch_forest_sandstone", "deciduous_forest", "coniferous_forest", "coniferous_forest_dunes", "maple_forest", "red_maple_forest", "mixed_maple_forest", "cherry_tree_forest"} local place_on = {"default:dirt_with_grass", "default:sand"} if dry then name = "default:dry_grass_" biome = {"savanna"} place_on = {"default:dirt_with_dry_grass"} end core.register_decoration({ deco_type = "simple", place_on = place_on, sidelen = 16, noise_params = { offset = offset, scale = scale, spread = {x = 250, y = 250, z = 250}, seed = 329, octaves = 3, persist = 0.6 }, biomes = biome, y_min = 1, y_max = 31000, decoration = name .. length, }) end core.clear_registered_decorations() -- Large cactus core.register_decoration({ deco_type = "schematic", place_on = {"default:desert_sand"}, sidelen = 80, noise_params = { offset = -0.0005, scale = 0.0015, spread = {x = 200, y = 200, z = 200}, seed = 230, octaves = 3, persist = 0.6 }, biomes = {"desert"}, y_min = 5, y_max = 31000, schematic = core.get_modpath("default").."/schematics/large_cactus.mts", flags = "place_center_x", rotation = "random", }) -- Cactus core.register_decoration({ deco_type = "simple", place_on = {"default:desert_sand"}, sidelen = 80, noise_params = { offset = -0.0005, scale = 0.0015, spread = {x = 200, y = 200, z = 200}, seed = 230, octaves = 3, persist = 0.6 }, biomes = {"desert"}, y_min = 5, y_max = 31000, decoration = "default:cactus", height = 2, height_max = 5, }) -- Papyrus core.register_decoration({ deco_type = "schematic", place_on = {"default:dirt"}, sidelen = 16, noise_params = { offset = -0.3, scale = 0.7, spread = {x = 200, y = 200, z = 200}, seed = 354, octaves = 3, persist = 0.7 }, biomes = {"savanna_swamp"}, y_min = 0, y_max = 0, schematic = core.get_modpath("default").."/schematics/papyrus.mts", }) -- Grasses register_grass_decoration(-0.03, 0.4, 5) register_grass_decoration(-0.015, 0.2, 4) register_grass_decoration(0, 0.1, 3) register_grass_decoration(0.015, 0.05, 2) register_grass_decoration(0.03, 0.03, 1) -- Dry grasses register_grass_decoration(0.01, 0.4, 5, true) register_grass_decoration(0.03, 0.1, 4, true) register_grass_decoration(0.05, 0.08, 3, true) register_grass_decoration(0.07, -0.04, 2, true) register_grass_decoration(0.09, -0.06, 1, true) -- Junglegrass core.register_decoration({ deco_type = "simple", place_on = {"default:dirt_with_grass"}, sidelen = 80, fill_ratio = 0.6, biomes = {"rainforest"}, y_min = 1, y_max = 31000, decoration = "default:junglegrass", }) -- Dry shrub core.register_decoration({ deco_type = "simple", place_on = {"default:desert_sand", "default:dirt_with_snow"}, sidelen = 16, noise_params = { offset = 0, scale = 0.02, spread = {x = 200, y = 200, z = 200}, seed = 329, octaves = 3, persist = 0.6 }, biomes = {"desert", "tundra"}, y_min = 2, y_max = 31000, decoration = "default:dry_shrub", }) core.register_on_generated(default.generate_nyancats) core.register_on_generated(default.generate_ruins)
gpl-3.0
czfshine/Don-t-Starve
data/scripts/components/teamleader.lua
1
8905
local TeamLeader = Class(function(self, inst ) self.inst = inst self.team_type = "monster" self.min_team_size = 3 self.max_team_size = 6 self.team = {} self.threat = nil self.searchradius = 50 self.theta = 0 self.thetaincrement = 1 self.radius = 5 self.reverse = false self.timebetweenattacks = 3 self.attackinterval = 3 self.inst:StartUpdatingComponent(self) self.lifetime = 0 self.attack_grp_size = nil self.chk_state = true self.maxchasetime = 30 self.chasetime = 0 end) local function getteamsize(team) local count = 0 for k,v in pairs(team) do if v ~= nil and not v:HasTag("teamleader") then count = count + 1 end end return count end function TeamLeader:OrganizeTeams() local teams = {} local x,y,z = self.inst.Transform:GetWorldPosition() local ents = TheSim:FindEntities(x,y,z, self.searchradius) local oldestteam = 0 for k,v in pairs(ents) do if v.components.teamleader and v.components.teamleader.threat == self.threat then table.insert(teams, v) end end local sort = function(w1, w2) if w1.components.teamleader.lifetime > w2.components.teamleader.lifetime then return true end end table.sort(teams, sort) if teams[1] ~= self.inst then return end local radius = 5 local reverse = false local thetaincrement = 1 local maxteam = 6 for k,v in pairs(teams) do local leader = v.components.teamleader leader.radius = radius leader.reverse = reverse leader.thetaincrement = thetaincrement leader.max_team_size = maxteam radius = radius + 5 reverse = not reverse thetaincrement = thetaincrement * 0.6 maxteam = maxteam + 6 end end function TeamLeader:IsTeamFull() if self.team and getteamsize(self.team) >= self.max_team_size then return true end end function TeamLeader:ValidMember(member) if member:HasTag(self.team_type) and member.components.combat and not (member.components.health and member.components.health:IsDead()) and not member.components.teamattacker.inteam then return true end end function TeamLeader:DisbandTeam() local team = {} for k,v in pairs(self.team) do team[k]=v end for k,v in pairs(team) do self:OnLostTeammate(v) end self.threat = nil self.team = {} self.inst:Remove() end function TeamLeader:TeamSizeControl() if getteamsize(self.team) > self.max_team_size then local teamcount = 0 local team = {} for k,v in pairs(self.team) do team[k]=v end for k,v in pairs(team) do teamcount = teamcount + 1 if teamcount > self.max_team_size then self:OnLostTeammate(v) end end end end function TeamLeader:NewTeammate(member) --listen for: Attacked, Death, OnAttackOther if self:ValidMember(member) then member.deathfn = function() self:OnLostTeammate(member) end member.attackedfn = function() self:BroadcastDistress(member) end member.attackedotherfn = function() self.chasetime = 0 member.components.combat.target = nil member.components.teamattacker.orders = "HOLD" end self.team[member] = member self.inst:ListenForEvent("death", member.deathfn, member) self.inst:ListenForEvent("attacked", member.attackedfn, member) self.inst:ListenForEvent("onattackother", member.attackedotherfn, member) self.inst:ListenForEvent("onremove", member.deathfn, member) member.components.teamattacker.teamleader = self member.components.teamattacker.inteam = true end end function TeamLeader:BroadcastDistress(member) if not member then member = self.inst end if member:IsValid() then local x,y,z = member.Transform:GetWorldPosition() local ents = TheSim:FindEntities(x,y,z, self.searchradius, { self.team_type } ) -- filter by tag? { self.team_type } for k,v in pairs(ents) do if v ~= member and self:ValidMember(v) then self:NewTeammate(v) end end end end function TeamLeader:OnLostTeammate(member) if member and member:IsValid() then self.inst:RemoveEventCallback("death", member.deathfn, member) self.inst:RemoveEventCallback("attacked", member.attackedfn, member) self.inst:RemoveEventCallback("onattackother", member.attackedotherfn, member) self.inst:RemoveEventCallback("onremove", member.deathfn, member) self.team[member] = nil member.components.teamattacker.teamleader = nil member.components.teamattacker.order = nil member.components.teamattacker.inteam = false member.components.combat.target = nil end end function TeamLeader:CanAttack() return getteamsize(self.team) >= self.min_team_size end function TeamLeader:CenterLeader() local updatedPos = nil local validMembers = 0 for k,v in pairs(self.team) do if not updatedPos then updatedPos = Vector3(k.Transform:GetWorldPosition() ) else updatedPos = updatedPos + Vector3(k.Transform:GetWorldPosition() ) end validMembers = validMembers + 1 end if updatedPos then updatedPos = updatedPos / validMembers self.inst.Transform:SetPosition(updatedPos:Get() ) end end function TeamLeader:GetFormationPositions() local target = self.threat local team = self.team local pt = Vector3(target.Transform:GetWorldPosition()) local theta = self.theta local radius = self.radius local steps = getteamsize(team) for k,v in pairs(team) do radius = self.radius if v.components.teamattacker.orders == "WARN" then radius = self.radius - 1 end local offset = Vector3(radius * math.cos(theta), 0, -radius * math.sin(theta)) v.components.teamattacker.formationpos = pt + offset theta = theta - (2 * PI/steps) end end function TeamLeader:GiveOrders(order, num) local temp = {} for k,v in pairs(self.team) do if v ~= nil then v.components.teamattacker.orders = nil table.insert(temp, v) end end if num > #temp then num = #temp end local successfulorders = 0 while successfulorders < num do local attempt = temp[math.random(1, #temp)] if attempt.components.teamattacker.orders == nil then attempt.components.teamattacker.orders = order successfulorders = successfulorders + 1 end end for k,v in pairs(self.team) do if v ~= nil and v.components.teamattacker.orders == nil then v.components.teamattacker.orders = "HOLD" end end end function TeamLeader:GiveOrdersToAllWithOrder(order, oldorder) for k,v in pairs(self.team) do if v ~= nil and v.components.teamattacker.orders == oldorder then v.components.teamattacker.orders = order end end end function TeamLeader:AllInState(state) local b = true for k,v in pairs(self.team) do if v ~= nil and not ( self.chk_state and (v:HasTag("frozen") or v:HasTag("fire")) ) and not (v.components.teamattacker.orders == nil or v.components.teamattacker.orders == state) then b = false end end return b end function TeamLeader:IsTeamEmpty() if not next(self.team) then return true else return false end end function TeamLeader:SetNewThreat(threat) self.threat = threat self.inst:ListenForEvent("onremove", function() self:DisbandTeam() end, self.threat) --The threat has died end function TeamLeader:GetTheta(dt) if self.reverse then return self.theta - (dt * self.thetaincrement) else return self.theta + (dt * self.thetaincrement) end end function TeamLeader:SetAttackGrpSize(val) self.attack_grp_size = val end function TeamLeader:NumberToAttack() if type(self.attack_grp_size) == "function" then return self.attack_grp_size() elseif type(self.attack_grp_size) == "number" then return self.attack_grp_size end if math.random() > 0.25 then return 1 else return 2 end end function TeamLeader:ManageChase(dt) self.chasetime = self.chasetime + dt if self.chasetime > self.maxchasetime then self:DisbandTeam() end end function TeamLeader:ValidateTeam() local team = {} for k,v in pairs(self.team) do team[k]=v end for k,v in pairs(team) do if not v:IsValid() then self:OnLostTeammate(v) end end end function TeamLeader:OnUpdate(dt) --self:ValidateTeam() self:ManageChase(dt) self:CenterLeader() self.lifetime = self.lifetime + dt self:OrganizeTeams() self:TeamSizeControl() if self.threat and self.threat:IsValid() and self:CanAttack() then --Is there a target and is the team strong enough? self.theta = self:GetTheta(dt) --Spin the formation! self:GetFormationPositions() if self:AllInState("HOLD") then self.timebetweenattacks = self.timebetweenattacks - dt if self.timebetweenattacks <= 0 then self.timebetweenattacks = self.attackinterval self:GiveOrders("WARN", self:NumberToAttack()) self.inst:DoTaskInTime(0.5, function() self:GiveOrdersToAllWithOrder("ATTACK", "WARN") end) else end end else end if self:IsTeamEmpty() or (self.threat and not self.threat:IsValid()) then self:DisbandTeam() end end return TeamLeader
gpl-2.0
Yelen719/Deep2048
dqn/train_agent.lua
1
9536
--[[ Copyright (c) 2014 Google Inc. See LICENSE file for full terms of limited license. ]] require 'optim' require 'gnuplot' logger = optim.Logger('score_2.txt') gnuplot.setterm("png") if not dqn then require "initenv" end local cmd = torch.CmdLine() cmd:text() cmd:text('Train Agent in Environment:') cmd:text() cmd:text('Options:') cmd:option('-framework', '', 'name of training framework') cmd:option('-env', '', 'name of environment to use') cmd:option('-game_path', '', 'path to environment file (ROM)') cmd:option('-env_params', '', 'string of environment parameters') cmd:option('-pool_frms', '', 'string of frame pooling parameters (e.g.: size=2,type="max")') cmd:option('-actrep', 1, 'how many times to repeat action') cmd:option('-random_starts', 0, 'play action 0 between 1 and random_starts ' .. 'number of times at the start of each training episode') cmd:option('-name', '', 'filename used for saving network and training history') cmd:option('-network', '', 'reload pretrained network') cmd:option('-agent', '', 'name of agent file to use') cmd:option('-agent_params', '', 'string of agent parameters') cmd:option('-seed', 1, 'fixed input seed for repeatable experiments') cmd:option('-saveNetworkParams', false, 'saves the agent network in a separate file') cmd:option('-prog_freq', 5*10^3, 'frequency of progress output') cmd:option('-save_freq', 5*10^4, 'the model is saved every save_freq steps') cmd:option('-eval_freq', 10^4, 'frequency of greedy evaluation') cmd:option('-save_versions', 0, '') cmd:option('-steps', 10^5, 'number of training steps to perform') cmd:option('-eval_steps', 10^5, 'number of evaluation steps') cmd:option('-verbose', 2, 'the higher the level, the more information is printed to screen') cmd:option('-threads', 1, 'number of BLAS threads') cmd:option('-gpu', -1, 'gpu flag') cmd:text() local opt = cmd:parse(arg) --- General setup. ------ Nan Yang ------ -- local framework = require(opt.framework) -- gameEnv = framework.GameEnvironment(opt) -- gameActions = gameEnv:getActions() -- dqn = {} -- agent = dqn[_opt.agent](_opt.agent_params) -- opt = torch options local game_env, game_actions, agent, opt = setup(opt) -- override print to always flush the output local old_print = print local print = function(...) old_print(...) io.flush() end -- Number of steps after which learning starts. local learn_start = agent.learn_start local start_time = sys.clock() local reward_counts = {} local episode_counts = {} local time_history = {} local v_history = {} local qmax_history = {} local td_history = {} local reward_history = {} local step = 0 time_history[1] = 0 local total_reward local total_score local nrewards local nepisodes local episode_reward local episode_score game_env.initGrid(); local screen, reward, terminal, score = game_env.getState() print("Iteration ..", step) local win = nil while step < opt.steps do step = step + 1 -- 0 is over local action_index = agent:perceive(reward, screen, terminal) -- print(action_index); -- game over? get next game! if not terminal then -- screen, reward, terminal = game_env.step(game_actions[action_index], true) -- print(game_actions[action_index]); screen, reward, terminal, score = game_env.step(game_actions[action_index]) -- print(reward); else if opt.random_starts > 0 then game_env.nextRandomGame() screen, reward, terminal, score = game_env.getState(); else game_env.restart(); screen, reward, terminal, score = game_env.getState(); end end -- display screen -- win = image.display({image=screen, win=win}) -- print(screen); if step % opt.prog_freq == 0 then assert(step==agent.numSteps, 'trainer step: ' .. step .. ' & agent.numSteps: ' .. agent.numSteps) print("Steps: ", step) agent:report() collectgarbage() end if step%1000 == 0 then collectgarbage() end if step % opt.eval_freq == 0 and step > learn_start then game_env.restart(); screen, reward, terminal, score= game_env.getState(); total_reward = 0 total_score = 0 nrewards = 0 nepisodes = 0 episode_reward = 0 episode_score = 0; highest_reward = 0; highest_score = 0; local eval_time = sys.clock() for estep=1,opt.eval_steps do -- 0.05 is used for egreedy local action_index = agent:perceive(reward, screen, terminal, true, 0.05) -- Play game in test mode (episodes don't end when losing a life) screen, reward, terminal, score = game_env.step(game_actions[action_index]) -- display screen -- win = image.display({image=screen, win=win}) if estep%1000 == 0 then collectgarbage() end -- record every reward episode_reward = episode_reward + reward episode_score = episode_score + score; if reward > 0 then nrewards = nrewards + 1 elseif reward < 0 then nrewards = nrewards - 1 end if terminal then total_reward = total_reward + episode_reward total_score = total_score + episode_score; if episode_score > highest_score then highest_score = episode_score; highest_grid = screen; end episode_reward = 0 episode_score = 0 nepisodes = nepisodes + 1 screen, reward, terminal, score = game_env.nextRandomGame() screen, reward, terminal, score = game_env.getState(); end end eval_time = sys.clock() - eval_time start_time = start_time + eval_time agent:compute_validation_statistics() local ind = #reward_history+1 total_reward = total_reward/math.max(1, nepisodes) total_score = total_score/math.max(1, nepisodes) if #reward_history == 0 or total_reward > torch.Tensor(reward_history):max() then agent.best_network = agent.network:clone() end if agent.v_avg then v_history[ind] = agent.v_avg td_history[ind] = agent.tderr_avg qmax_history[ind] = agent.q_max end print("V", v_history[ind], "TD error", td_history[ind], "Qmax", qmax_history[ind]) reward_history[ind] = total_reward reward_counts[ind] = nrewards episode_counts[ind] = nepisodes time_history[ind+1] = sys.clock() - start_time local time_dif = time_history[ind+1] - time_history[ind] local training_rate = opt.actrep*opt.eval_freq/time_dif print(string.format( '\nSteps: %d (frames: %d), score: %.2f, higheset score: %d, epsilon: %.2f, lr: %G, ' .. 'training time: %ds, training rate: %dfps, testing time: %ds, ' .. 'testing rate: %dfps, num. ep.: %d, num. rewards: %d', step, step*opt.actrep, total_score, highest_score, agent.ep, agent.lr, time_dif, training_rate, eval_time, opt.actrep*opt.eval_steps/eval_time, nepisodes, nrewards)) logger:add{['average score'] = total_score} --logger:add{['highest score'] = highest_score} logger:style{['average score'] = '-'} --logger:style{['highest score'] = '-'} logger:plot() print(highest_grid) end if step % opt.save_freq == 0 or step == opt.steps then local s, a, r, s2, term = agent.valid_s, agent.valid_a, agent.valid_r, agent.valid_s2, agent.valid_term agent.valid_s, agent.valid_a, agent.valid_r, agent.valid_s2, agent.valid_term = nil, nil, nil, nil, nil, nil, nil local w, dw, g, g2, delta, delta2, deltas, tmp = agent.w, agent.dw, agent.g, agent.g2, agent.delta, agent.delta2, agent.deltas, agent.tmp agent.w, agent.dw, agent.g, agent.g2, agent.delta, agent.delta2, agent.deltas, agent.tmp = nil, nil, nil, nil, nil, nil, nil, nil local filename = opt.name if opt.save_versions > 0 then filename = filename .. "_" .. math.floor(step / opt.save_versions) end filename = filename torch.save(filename .. ".t7", {agent = agent, model = agent.network, best_model = agent.best_network, reward_history = reward_history, reward_counts = reward_counts, episode_counts = episode_counts, time_history = time_history, v_history = v_history, td_history = td_history, qmax_history = qmax_history, arguments=opt}) if opt.saveNetworkParams then local nets = {network=w:clone():float()} torch.save(filename..'.params.t7', nets, 'ascii') end agent.valid_s, agent.valid_a, agent.valid_r, agent.valid_s2, agent.valid_term = s, a, r, s2, term agent.w, agent.dw, agent.g, agent.g2, agent.delta, agent.delta2, agent.deltas, agent.tmp = w, dw, g, g2, delta, delta2, deltas, tmp print('Saved:', filename .. '.t7') io.flush() collectgarbage() end end
mit
czfshine/Don-t-Starve
data/scripts/prefabs/devtool.lua
1
3567
local assets= { Asset("ANIM", "anim/axe.zip"), Asset("ANIM", "anim/goldenaxe.zip"), Asset("ANIM", "anim/swap_axe.zip"), Asset("ANIM", "anim/swap_goldenaxe.zip"), } local function onfinished(inst) inst:Remove() end local function giveitems(inst, data) if data.owner.components.inventory and data.recipe then for ik, iv in pairs(data.recipe.ingredients) do if not data.owner.components.inventory:Has(iv.type, iv.amount) then for i = 1, iv.amount do local item = SpawnPrefab(iv.type) data.owner.components.inventory:GiveItem(item) end end end end end local function onequipgold(inst, owner) owner.AnimState:OverrideSymbol("swap_object", "swap_goldenaxe", "swap_goldenaxe") owner.SoundEmitter:PlaySound("dontstarve/wilson/equip_item_gold") owner.AnimState:Show("ARM_carry") owner.AnimState:Hide("ARM_normal") inst.Light:Enable(true) inst.task = inst:DoPeriodicTask(0.25, function() if owner.components.health then owner.components.health:DoDelta(500) end if owner.components.hunger then owner.components.hunger:DoDelta(500) end end) owner.components.hunger:SetRate(0) owner:ListenForEvent("cantbuild", giveitems) end local function onunequip(inst, owner) inst.Light:Enable(false) owner.AnimState:Hide("ARM_carry") owner.AnimState:Show("ARM_normal") if inst.task then inst.task:Cancel() inst.task = nil end owner.components.hunger:SetRate(TUNING.WILSON_HUNGER_RATE) owner:RemoveEventCallback("cantbuild", giveitems) end local function fn(Sim) local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() inst.entity:AddSoundEmitter() MakeInventoryPhysics(inst) anim:SetBank("axe") anim:SetBuild("goldenaxe") anim:PlayAnimation("idle") inst:AddTag("sharp") ----- inst:AddComponent("inspectable") inst:AddComponent("inventoryitem") inst.components.inventoryitem:ChangeImageName("goldenaxe") if BRANCH == "dev" then inst:AddComponent("weapon") inst.components.weapon:SetRange(20) inst.components.weapon:SetDamage(10000) inst:AddComponent("heater") inst.components.heater.equippedheat = math.huge inst:AddComponent("blinkstaff") inst:AddComponent("tool") inst.components.tool:SetAction(ACTIONS.CHOP, 100) inst.components.tool:SetAction(ACTIONS.MINE, 100) inst.components.tool:SetAction(ACTIONS.HAMMER) inst.components.tool:SetAction(ACTIONS.DIG, 100) inst.components.tool:SetAction(ACTIONS.NET) inst:AddComponent("dapperness") inst.components.dapperness.dapperness = math.huge inst.entity:AddLight() inst.Light:SetColour(255/255,255/255,192/255) inst.Light:SetIntensity(.8) inst.Light:SetRadius(5) inst.Light:SetFalloff(.33) inst:AddComponent("prototyper") inst.components.prototyper.trees = {SCIENCE = 100, MAGIC = 100, ANCIENT = 100} inst:AddTag("prototyper") inst:AddComponent("equippable") inst.components.equippable:SetOnEquip( onequipgold ) inst.components.equippable:SetOnUnequip( onunequip) inst.components.equippable.walkspeedmult = 2 else inst:Remove() end return inst end return Prefab( "common/inventory/devtool", fn, assets)
gpl-2.0
EMCTEAM-IRAN/superflux-bot
plugins/welcome.lua
1
3523
local add_user_cfg = load_from_file('data/add_user_cfg.lua') --create by RoyalTeam ID CHANNEL : @RoyalTeamCh local function template_add_user(base, to_username, from_username, chat_name, chat_id) base = base or '' to_username = '@' .. (to_username or '') from_username = '@' .. (from_username or '') chat_name = string.gsub(chat_name, '_', ' ') or '' chat_id = "chat#id" .. (chat_id or '') if to_username == "@" then to_username = '' end if from_username == "@" then from_username = '' end base = string.gsub(base, "{to_username}", to_username) base = string.gsub(base, "{from_username}", from_username) base = string.gsub(base, "{chat_name}", chat_name) base = string.gsub(base, "{chat_id}", chat_id) return base end function chat_new_user_link(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.from.username local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')' local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end function chat_new_user(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.action.user.username local from_username = msg.from.username local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end local function description_rules(msg, nama) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then local about = "" local rules = "" if data[tostring(msg.to.id)]["description"] then about = data[tostring(msg.to.id)]["description"] about = "\nAbout :\n"..about.."\n" end if data[tostring(msg.to.id)]["rules"] then rules = data[tostring(msg.to.id)]["rules"] rules = "\nRules :\n"..rules.."\n" end local sambutan = "Hi "..nama.." Welcome to [ "..string.gsub(msg.to.print_name, "_", " ").." ]" local text = sambutan.."\n" local receiver = get_receiver(msg) send_large_msg(receiver, text, ok_cb, false) end end local function run(msg, matches) if not msg.service then return "Are you trying to troll me?" end --vardump(msg) if matches[1] == "chat_add_user" then if not msg.action.user.username then nama = string.gsub(msg.action.user.print_name, "_", " ") else nama = "@"..msg.action.user.username end chat_new_user(msg) description_rules(msg, nama) elseif matches[1] == "chat_add_user_link" then if not msg.from.username then nama = string.gsub(msg.from.print_name, "_", " ") else nama = "@"..msg.from.username end chat_new_user_link(msg) description_rules(msg, nama) elseif matches[1] == "chat_del_user" then local bye_name = msg.action.user.first_name return 'Bye '..bye_name end end M return { description = "Welcoming Message", usage = "send message to new member", patterns = { "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_add_user_link)$", "^!!tgservice (chat_del_user)$", }, run = run }
gpl-3.0
matthewhesketh/mattata
plugins/administration/ban.lua
2
4549
--[[ Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]] local ban = {} local mattata = require('mattata') function ban:init() ban.commands = mattata.commands(self.info.username):command('ban').table ban.help = '/ban [user] - Bans a user from the current chat. This command can only be used by moderators and administrators of a supergroup.' end function ban:on_message(message, _, language) if message.chat.type ~= 'supergroup' then local output = language['errors']['supergroup'] return mattata.send_reply(message, output) elseif not mattata.is_group_admin(message.chat.id, message.from.id) then local output = language['errors']['admin'] return mattata.send_reply(message, output) end local reason = false local user = false local input = mattata.input(message) -- check the message object for any users this command -- is intended to be executed on if message.reply then user = message.reply.from.id if input then reason = input end elseif input and input:match(' ') then user, reason = input:match('^(.-) (.-)$') elseif input then user = input end if not user then local output = language['ban']['1'] local success = mattata.send_force_reply(message, output) if success then mattata.set_command_action(message.chat.id, success.result.message_id, '/ban') end return end if reason and type(reason) == 'string' and reason:match('^[Ff][Oo][Rr] ') then reason = reason:match('^[Ff][Oo][Rr] (.-)$') end if tonumber(user) == nil and not user:match('^%@') then user = '@' .. user end local user_object = mattata.get_user(user) or mattata.get_chat(user) -- resolve the username/ID to a user object if not user_object then return mattata.send_reply(message, language.errors.unknown) elseif user_object.result.id == self.info.id then return false -- don't let the bot ban itself end user_object = user_object.result local status = mattata.get_chat_member(message.chat.id, user_object.id) local is_admin = mattata.is_group_admin(message.chat.id, user_object.id) if not status then local output = language['errors']['generic'] return mattata.send_reply(message, output) elseif is_admin then -- we won't try and ban moderators and administrators. local output = language['ban']['2'] return mattata.send_reply(message, output) elseif status.result.status == 'kicked' then -- check if the user has already been kicked local output = language['ban']['4'] return mattata.send_reply(message, output) end local success = mattata.ban_chat_member(message.chat.id, user_object.id) -- attempt to ban the user from the group if not success then -- since we've ruled everything else out, it's safe to say if it wasn't a success then the bot just isn't an administrator in the group local output = language['ban']['5'] return mattata.send_reply(message, output) end mattata.increase_administrative_action(message.chat.id, user_object.id, 'bans') reason = reason and '\nReason: ' .. reason or '' local admin_username = mattata.get_formatted_user(message.from.id, message.from.first_name, 'html') local banned_username = mattata.get_formatted_user(user_object.id, user_object.first_name, 'html') local output if mattata.get_setting(message.chat.id, 'log administrative actions') then local log_chat = mattata.get_log_chat(message.chat.id) output = string.format(language['ban']['6'], admin_username, message.from.id, banned_username, user_object.id, mattata.escape_html(message.chat.title), message.chat.id, reason, '#chat' .. tostring(message.chat.id):gsub('^-100', ''), '#user' .. user_object.id) mattata.send_message(log_chat, output, 'html') else output = string.format(language['ban']['7'], admin_username, banned_username, reason) mattata.send_message(message.chat.id, output, 'html') end if message.reply and mattata.get_setting(message.chat.id, 'delete reply on action') then mattata.delete_message(message.chat.id, message.reply.message_id) end return mattata.delete_message(message.chat.id, message.message_id) end return ban
mit
czfshine/Don-t-Starve
data/scripts/components/useableitem.lua
1
1037
local UseableItem = Class(function(self, inst) self.inst = inst self.onusefn = nil self.onstopusefn = nil self.inuse = false self.caninteractfn = nil self.stopuseevents = nil end) function UseableItem:SetCanInteractFn(fn) self.caninteractfn = fn end function UseableItem:SetOnUseFn(fn) self.onusefn = fn end function UseableItem:SetOnStopUseFn(fn) self.onstopusefn = fn end function UseableItem:CanInteract() if self.caninteractfn then return self.caninteractfn(self.inst) else return not self.inuse and self.inst.components.equippable.isequipped end end function UseableItem:StartUsingItem() self.inuse = true if self.onusefn then self.onusefn(self.inst) end if self.stopuseevents then self.stopuseevents(self.inst) end end function UseableItem:StopUsingItem() self.inuse = false if self.onstopusefn then self.onstopusefn(self.inst) end end function UseableItem:CollectInventoryActions(doer, actions) if self:CanInteract() then table.insert(actions, ACTIONS.USEITEM) end end return UseableItem
gpl-2.0
CrazyEddieTK/Zero-K
units/chicken_shield.lua
2
5686
unitDef = { unitname = [[chicken_shield]], name = [[Blooper]], description = [[Shield/Anti-Air]], acceleration = 0.36, activateWhenBuilt = true, brakeRate = 0.205, buildCostEnergy = 0, buildCostMetal = 0, builder = false, buildPic = [[chicken_shield.png]], buildTime = 1200, canGuard = true, canMove = true, canPatrol = true, category = [[LAND]], customParams = { shield_emit_height = 26, shield_emit_offset = 0, }, explodeAs = [[NOWEAPON]], footprintX = 4, footprintZ = 4, iconType = [[walkershield]], idleAutoHeal = 20, idleTime = 300, leaveTracks = true, maxDamage = 1600, maxSlope = 37, maxVelocity = 1.8, maxWaterDepth = 5000, minCloakDistance = 75, movementClass = [[AKBOT6]], noAutoFire = false, noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE GUNSHIP SUB]], objectName = [[chicken_shield.s3o]], power = 350, selfDestructAs = [[NOWEAPON]], sfxtypes = { explosiongenerators = { [[custom:blood_spray]], [[custom:blood_explode]], [[custom:dirt]], }, }, sightDistance = 512, trackOffset = 7, trackStrength = 9, trackStretch = 1, trackType = [[ChickenTrack]], trackWidth = 34, turnRate = 806, upright = false, workerTime = 0, weapons = { { def = [[FAKE_WEAPON]], onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER]], }, { def = [[SHIELD]], }, { def = [[AEROSPORES]], onlyTargetCategory = [[FIXEDWING GUNSHIP]], }, }, weaponDefs = { AEROSPORES = { name = [[Anti-Air Spores]], areaOfEffect = 24, avoidFriendly = false, burst = 3, burstrate = 0.2, canAttackGround = false, collideFriendly = false, craterBoost = 0, craterMult = 0, customParams = { light_radius = 0, }, damage = { default = 60, planes = 60, subs = 6, }, dance = 60, explosionGenerator = [[custom:NONE]], fireStarter = 0, fixedlauncher = 1, flightTime = 5, groundbounce = 1, heightmod = 0.5, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 2, model = [[chickeneggblue.s3o]], noSelfDamage = true, range = 700, reloadtime = 2.5, smokeTrail = true, startVelocity = 100, texture1 = [[]], texture2 = [[sporetrailblue]], tolerance = 10000, tracks = true, turnRate = 24000, turret = true, waterweapon = true, weaponAcceleration = 100, weaponType = [[MissileLauncher]], weaponVelocity = 500, wobble = 32000, }, FAKE_WEAPON = { name = [[Fake]], areaOfEffect = 8, avoidFriendly = false, collideFriendly = false, craterBoost = 0, craterMult = 0, damage = { default = 0.01, planes = 0.01, subs = 0.01, }, explosionGenerator = [[custom:NONE]], impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, noSelfDamage = true, range = 420, reloadtime = 10, size = 0, soundHit = [[]], soundStart = [[]], targetborder = 1, tolerance = 5000, turret = true, waterWeapon = false, weaponType = [[Cannon]], weaponVelocity = 500, }, SHIELD = { name = [[Shield]], craterMult = 0, damage = { default = 10, }, exteriorShield = true, impulseFactor = 0, interceptedByShieldType = 1, shieldAlpha = 0.15, shieldBadColor = [[1.0 1 0.1 1]], shieldGoodColor = [[0.1 1.0 0.1 1]], shieldInterceptType = 3, shieldPower = 2500, shieldPowerRegen = 180, shieldPowerRegenEnergy = 0, shieldRadius = 300, shieldRepulser = false, smartShield = true, visibleShield = false, visibleShieldRepulse = false, --texture1 = [[wakelarge]], --visibleShield = true, --visibleShieldHitFrames = 30, --visibleShieldRepulse = false, weaponType = [[Shield]], }, }, } return lowerkeys({ chicken_shield = unitDef })
gpl-2.0
TimSimpson/Macaroni
Main/Generators/Cpp/UnitFileGenerator.lua
1
14255
require "Cpp/Common"; require "Plugin"; require "Cpp/ClassCppFileGenerator"; require "Cpp/ClassHFileGenerator"; local EnumFileGenerator = require "Cpp/EnumFileGenerator"; local FunctionGenerator = require "Cpp/FunctionFileGenerator"; require "Cpp/TypedefFileGenerator"; require "Cpp/UnitBlockGenerator"; local Access = require "Macaroni.Model.Cpp.Access"; local CodeGraph = require "Macaroni.Generators.Cpp.CodeGraph" local Context = require "Macaroni.Model.Context"; local EnumFileGenerator = EnumFileGenerator.EnumFileGenerator local EnumCppFileGenerator = EnumFileGenerator.EnumCppFileGenerator local FunctionFileGenerator = FunctionGenerator.FunctionFileGenerator local LibraryTarget = require "Macaroni.Model.Project.LibraryTarget" local Node = require "Macaroni.Model.Node"; local UnitFileGenerator = require "Macaroni.Generators.Cpp.Unit.UnitFileGenerator" local TypeNames = Macaroni.Model.TypeNames; -- The older method of generating is to iterate by Node, and for each type -- (class, function, etc) figure out whether or not to generate a file and -- proceed from there. -- That isn't quite flexible enough, so the new system is this. It iterates by -- unit, building the header and cpp file for each one before proceeding. FileWriters = { Block = function(library, node, writer, type) return UnitBlockGenerator.new{ writer=writer, node=node, type=type}; end, Class = function(library, node, writer, type) if type == "H" then return ClassHFileGenerator.new{ node = node, targetLibrary=library, writer=writer}; else return ClassCppFileGenerator.new{ node = node, targetLibrary=library, writer=writer}; end end, Enum = function(library, node, writer, type) return EnumFileGenerator.new{ node=node, targetLibrary=library, writer=writer, }; end, FunctionOverload = function(library, node, writer, type) return FunctionFileGenerator.new{ node = node, targetLibrary=library, writer=writer, fileType = type, insertIntoNamespaces=true, ownedByClass=false, classPrefix=nil, }; end, Typedef = function(library, node, writer, type) return TypedefFileGenerator.new{node=node, targetLibrary=library, writer=writer}; end, }; local CreateElementList = function(unit) -- Create an ordered list of elements so that the unit will be -- generated in the correct way, with any Nodes that depend on other -- Nodes in the unit being written later. local elements = unit:CreateElementList() local swappedNodes = {} for i = 1, #elements do ::elementCheck:: local node = elements[i].Node info = NodeInfoList[node] -- Now, check if this node depends on Nodes which will be -- written to the file after this, and swap the two nodes if that's -- true. for k, dependencyNode in pairs(info.dependencies.heavy) do if dependencyNode == node then -- In other words, the node is it's own dependency (duh). -- Skip it. goto nextDependencyNodeContinue end for j = i, #elements do local node2 = elements[j].Node if dependencyNode == node2 then -- Check if we already swapped these, raise an error -- if we have. for k2, v2 in pairs(swappedNodes) do if v2 == elements[j] then error("Can't determine how to order the nodes " .. tostring(k2) .. " and " .. tostring(v2) .. " in Unit " .. tostring(unit) .. ".") end end swappedNodes[elements[i]] = elements[j] local swap = elements[i] elements[i] = elements[j] elements[j] = swap goto elementCheck -- reiterate this index end end ::nextDependencyNodeContinue:: end end return elements end local UnitGuardName = function(unit, fileType) return "MACARONI_UNIT_COMPILE_GUARD_" .. unit:GetShortCId() .. "_" .. fileType; end WriteUnitFileOpening = function(unit, writer, fileType) local guardName = UnitGuardName(unit, fileType) writer:WriteLine("#ifndef " .. guardName) writer:WriteLine("#define " .. guardName) if fileType == "Cpp" then local hGuardName = UnitGuardName(unit, "H") writer:WriteLine("// Force the use of the Internal Header:") writer:WriteLine("#define " .. hGuardName) end end WriteUnitFileClosing = function(unit, writer, fileType) local guardName = UnitGuardName(unit, fileType) writer:WriteLine("#endif //" .. guardName) end LibraryTargetGenerator = { new = function(library) if (library == nil) then error("No library argument given."); end self = {} setmetatable(self, LibraryTargetGenerator); self.library = library; -- if path == nil then -- error("Argument #2, 'path', cannot be nil.") -- end -- self.rootPath = path; self.graph = CodeGraph.Create(); self.libDecl = LibraryDecl(self.library) LibraryTargetGenerator.__index = function(t, k) local v = LibraryTargetGenerator[k]; return v; end; return self; end, IterateUnits = function (self, library, rootPath) for unit in Plugin.IterateChildDependencies(library) do self:writeUnitFiles(unit, rootPath); end end, writeUnitFiles = function(self, unit, rootPath) if not unit.Generated then log:Write("Skipping unit " .. tostring(unit) .. ".") return end log:Write("Writing unit files for " .. tostring(unit) .. ".") args = { library = self.library, unit = unit, rootPath = rootPath, fileType = "H", }; -- NEW! UnitFileGenerator.Generate(true, self.library, unit, self.graph, rootPath); --local ug = UnitFileGenerator.CreateDebug(self.library, unit); --local ug = UnitFileGenerator.Create(self.library, unit); --ug:Generate(self.graph, rootPath); -- EXCITING! -- local h = UnitFileGeneratorOldLua.new(args); -- h:WriteFile(); -- args.fileType = "Cpp" -- local cpp = UnitFileGeneratorOldLua.new(args); -- cpp:WriteFile(); end, } --TODO: CHANGE THIS in a major way to: -- * Iterate the targets multiple times: first writing top blocks, -- In H files: -- library configs, -- include statements, -- "light defs", -- impls, -- then, in CPP files, also: -- "internal header" version of above -- using statements -- cpp blocks -- definitions UnitFileGeneratorOldLua = { new = function(self) if (self.library == nil) then error("No library argument given."); end if (self.unit == nil) then error("No library argument given."); end if (self.rootPath == nil) then error("No root path argument given."); end if (self.fileType == nil) then error("No file type argument given."); end self.libDecl = LibraryDecl(self.library) setmetatable(self, UnitFileGeneratorOldLua); UnitFileGeneratorOldLua.__index = function(t, k) local v = UnitFileGeneratorOldLua[k]; return v; end; self.elements = CreateElementList(self.unit) self.requiresFileProp = "Requires" .. self.fileType .. "File" return self; end, foreachWriter = function(self, func) for i, w in ipairs(self.elementWriters) do if w[func] ~= nil then w[func](w) end end end, requiresFile = function(self, element) if MACARONI_VERSION ~= "0.2.3" then -- TODO: Fix the bug in Block which makes it not understand if it -- does or does not require a file property. if element.TypeName == "Block" then return true else return element[self.requiresFileProp] end else return element[self.requiresFileProp] end end, writeConfigFile = function(self) WriteLibraryConfigFileInclude(self.library, self.writer, self.fileType~="Cpp") end, writeClosing = function(self) self:foreachWriter('WriteBottomBlocks'); WriteUnitFileClosing(self.unit, self.writer, self.fileType) end, writeForwardDeclarations = function(self) self.writer:WriteLine("// Forward declaration necessary for anything which also depends on this.\n"); -- for i = 1, #elements do -- log:Write(tostring(i) .. '=' .. tostring(elements[i])) -- local element = elements[i] -- if element[requiresFileProp] then -- local node = element.Node -- local typeName = node.TypeName -- local func = FileWriters[self.fileType][typeName] -- if func == nil then -- error("No way to write the element " .. tostring(element) -- .. ". fileType=" .. tostring(self.fileType) -- .. ", typeName=" .. tostring(typeName)) -- end -- func(self.library, node, self.writer, self.unit) -- else -- -- TODO: Find some way to disable the constant -- -- generation of the cpp file. -- end -- end end, writeOpening = function(self) WriteUnitFileOpening(self.unit, self.writer, self.fileType) -- TODO: Iterate all blocks, if they are "top" blocks write them here. if "Cpp" == self.fileType then self.writer:WriteLine( "// The following configures symbols for export if needed.") self.writer:WriteLine("#define " .. LibraryCreate(self.library) .. "\n"); -- No need to #include the header for this unit- the various items -- will include their own definition. else -- Header file. end self:foreachWriter('WriteTopBlocks') --TODO: Write "top" blocks --self:writeConfigFile() end, writeHeader = function(self) self:writeConfigFile() self:foreachWriter('WriteForwardDeclarations'); self:foreachWriter('WriteIncludeStatements') self:foreachWriter('WriteForwardDeclarationsOfDependencies'); self:foreachWriter('WritePreDefinitionBlocks'); self:foreachWriter('WriteHeaderDefinitions'); self:foreachWriter('WritePostDefinitionBlocks'); -- for i, w in ipairs(self.elementWriters) do -- self.elementWriters[i].WriteHeader() -- end end, writeImplementation = function(self) self.writer:WriteLine("/*--------------------------------------------------------------------------*"); self.writer:WriteLine(" * Internal Header *"); self.writer:WriteLine(" *--------------------------------------------------------------------------*/"); self:writeHeader(); self.writer:WriteLine("\n"); self.writer:WriteLine("/*--------------------------------------------------------------------------*"); self.writer:WriteLine(" * Implementation *"); self.writer:WriteLine(" *--------------------------------------------------------------------------*/"); self:foreachWriter('WriteImplementationIncludeStatements') self:foreachWriter('WriteUsingStatements') self:foreachWriter('WriteImplementation') end, WriteFile = function(self) local fileProp = self.fileType .. "File" -- HFile or CppFile local setFunc = "Set" .. self.fileType .. "FileRootDirectory" -- The unit file will be some kind of relative path with an empty root -- path, such as "", "/Company/Namespace/blah.h". -- This code changes the root path part to the output path sent into -- this function (self.rootPath), which will be something like -- "C:\MyFiles\MyProject\target". if (self.unit[fileProp] == nil) then log:Error("Unit " .. tostring(self.unit) .. " has no " .. self.fileType .. "File!") end self.unit[setFunc](self.unit, self.rootPath); log:Write("Creating " .. self.fileType .. " file at " .. tostring(self.unit[fileProp])); self.writer = self.unit[fileProp]:CreateFile(); -- Initialize all of the Element writers self.elementWriters = {} for i = 1, #self.elements do local element = self.elements[i] if self:requiresFile(element) then local node = element.Node local typeName = node.TypeName local func = FileWriters[typeName] if func == nil then error("No way to write the element " .. tostring(element) .. ". fileType=" .. tostring(self.fileType) .. ", typeName=" .. tostring(typeName)) end local writer = func(self.library, node, self.writer, self.fileType) self.elementWriters[#self.elementWriters + 1] = writer end end self:writeOpening() if self.fileType == "H" then self:writeHeader() else self:writeImplementation() end self:writeClosing() end, };
apache-2.0
andywingo/snabbswitch
lib/ljsyscall/syscall/osx/c.lua
18
1783
-- This sets up the table of C functions -- For OSX we hope we do not need many overrides local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local abi = require "syscall.abi" local ffi = require "ffi" local voidp = ffi.typeof("void *") local function void(x) return ffi.cast(voidp, x) end -- basically all types passed to syscalls are int or long, so we do not need to use nicely named types, so we can avoid importing t. local int, long = ffi.typeof("int"), ffi.typeof("long") local uint, ulong = ffi.typeof("unsigned int"), ffi.typeof("unsigned long") local function inlibc_fn(k) return ffi.C[k] end -- Syscalls that just return ENOSYS but are in libc. Note these might vary by version in future local nosys_calls = { mlockall = true, } local C = setmetatable({}, { __index = function(C, k) if nosys_calls[k] then return nil end if pcall(inlibc_fn, k) then C[k] = ffi.C[k] -- add to table, so no need for this slow path again return C[k] else return nil end end }) -- new stat structure, else get legacy one; could use syscalls instead C.stat = C.stat64 C.fstat = C.fstat64 C.lstat = C.lstat64 -- TODO create syscall table. Except I cannot find how to call them, neither C.syscall nor C._syscall seems to exist --[[ local getdirentries = 196 local getdirentries64 = 344 function C.getdirentries(fd, buf, len, basep) return C._syscall(getdirentries64, int(fd), void(buf), int(len), void(basep)) end ]] -- cannot find these anywhere! --C.getdirentries = ffi.C._getdirentries --C.sigaction = ffi.C._sigaction return C
apache-2.0
victorperin/tibia-server
data/npc/scripts/Dalbrect.lua
2
3189
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "My name is Dalbrect Windtrouser, of the once proud windtrouser family."}) keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "I am merely a humble fisher now that nothing is left of my noble legacy."}) keywordHandler:addKeyword({'legacy'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "Once my family was once noble and wealthy, but fate turned against us and threw us into poverty."}) keywordHandler:addKeyword({'poverty'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "When Carlin tried to colonize the region now known as the ghostlands, my ancestors put their fortune in that project."}) keywordHandler:addKeyword({'fate'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "When Carlin tried to colonize the region now known as the ghostlands, my ancestors put their fortune in that project."}) keywordHandler:addKeyword({'ghostlands'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "Our family fortune was lost when the colonization of those cursed lands failed. Now nothing is left of our fame or our fortune. If I only had something as a reminder of those better times. <sigh>"}) keywordHandler:addKeyword({'brooch'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "What? You want me to examine a brooch?"}) keywordHandler:addKeyword({'carlin'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "To think my family used to belong to the local nobility! And now those arrogant women are in charge!"}) keywordHandler:addKeyword({'passage'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "I have only sailed to the isle of the kings once or twice. I dare not anger the monks by bringing travellers there without their permission."}) keywordHandler:addKeyword({'ship'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "My ship is my only pride and joy."}) local travelNode = keywordHandler:addKeyword({'isle of the kings'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you seek a passage to the isle of the kings for 10 gold coins?'}) travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = false, level = 0, cost = 10, destination = {x = 32190, y = 31957, z = 6} }) travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'We would like to serve you some time.'}) npcHandler:setMessage(MESSAGE_FAREWELL, "Good bye. You are welcome.") npcHandler:setMessage(MESSAGE_GREET, "Be greeted, traveler.") npcHandler:addModule(FocusModule:new())
apache-2.0
andywingo/snabbswitch
src/program/snabbnfv/traffic/traffic.lua
6
5208
module(..., package.seeall) local lib = require("core.lib") local nfvconfig = require("program.snabbnfv.nfvconfig") local usage = require("program.snabbnfv.traffic.README_inc") local ffi = require("ffi") local C = ffi.C local timer = require("core.timer") local pci = require("lib.hardware.pci") local counter = require("core.counter") local long_opts = { benchmark = "B", help = "h", ["link-report-interval"] = "k", ["load-report-interval"] = "l", ["debug-report-interval"] = "D", ["busy"] = "b", ["long-help"] = "H" } function run (args) local opt = {} local benchpackets local linkreportinterval = 0 local loadreportinterval = 1 local debugreportinterval = 0 function opt.B (arg) benchpackets = tonumber(arg) end function opt.h (arg) print(short_usage()) main.exit(1) end function opt.H (arg) print(long_usage()) main.exit(1) end function opt.k (arg) linkreportinterval = tonumber(arg) end function opt.l (arg) loadreportinterval = tonumber(arg) end function opt.D (arg) debugreportinterval = tonumber(arg) end function opt.b (arg) engine.busywait = true end args = lib.dogetopt(args, opt, "hHB:k:l:D:b", long_opts) if #args == 3 then local pciaddr, confpath, sockpath = unpack(args) local ok, info = pcall(pci.device_info, pciaddr) if not ok then print("Error: device not found " .. pciaddr) os.exit(1) end if not info.driver then print("Error: no driver for device " .. pciaddr) os.exit(1) end if loadreportinterval > 0 then local t = timer.new("nfvloadreport", engine.report_load, loadreportinterval*1e9, 'repeating') timer.activate(t) end if linkreportinterval > 0 then local t = timer.new("nfvlinkreport", engine.report_links, linkreportinterval*1e9, 'repeating') timer.activate(t) end if debugreportinterval > 0 then local t = timer.new("nfvdebugreport", engine.report_apps, debugreportinterval*1e9, 'repeating') timer.activate(t) end if benchpackets then print("snabbnfv traffic starting (benchmark mode)") bench(pciaddr, confpath, sockpath, benchpackets) else print("snabbnfv traffic starting") traffic(pciaddr, confpath, sockpath) end else print("Wrong number of arguments: " .. tonumber(#args)) print() print(short_usage()) main.exit(1) end end function short_usage () return (usage:gsub("%s*CONFIG FILE FORMAT:.*", "")) end function long_usage () return usage end -- Run in real traffic mode. function traffic (pciaddr, confpath, sockpath) engine.log = true local mtime = 0 if C.stat_mtime(confpath) == 0 then print(("WARNING: File '%s' does not exist."):format(confpath)) end while true do local mtime2 = C.stat_mtime(confpath) if mtime2 ~= mtime then print("Loading " .. confpath) engine.configure(nfvconfig.load(confpath, pciaddr, sockpath)) mtime = mtime2 end engine.main({duration=1, no_report=true}) -- Flush buffered log messages every 1s io.flush() end end -- Run in benchmark mode. function bench (pciaddr, confpath, sockpath, npackets) npackets = tonumber(npackets) local ports = dofile(confpath) local nic = (nfvconfig.port_name(ports[1])).."_NIC" engine.log = true engine.Hz = false print("Loading " .. confpath) engine.configure(nfvconfig.load(confpath, pciaddr, sockpath)) -- From designs/nfv local start, packets, bytes = 0, 0, 0 local done = function () local input = link.stats(engine.app_table[nic].input.rx) if start == 0 and input.rxpackets > 0 then -- started receiving, record time and packet count packets = input.rxpackets bytes = input.rxbytes start = C.get_monotonic_time() if os.getenv("NFV_PROF") then require("jit.p").start(os.getenv("NFV_PROF"), os.getenv("NFV_PROF_FILE")) else print("No LuaJIT profiling enabled ($NFV_PROF unset).") end if os.getenv("NFV_DUMP") then require("jit.dump").start(os.getenv("NFV_DUMP"), os.getenv("NFV_DUMP_FILE")) main.dumping = true else print("No LuaJIT dump enabled ($NFV_DUMP unset).") end end return input.rxpackets - packets >= npackets end engine.main({done = done, no_report = true}) local finish = C.get_monotonic_time() local runtime = finish - start local breaths = tonumber(counter.read(engine.breaths)) local input = link.stats(engine.app_table[nic].input.rx) packets = input.rxpackets - packets bytes = input.rxbytes - bytes engine.report() print() print(("Processed %.1f million packets in %.2f seconds (%d bytes; %.2f Gbps)"):format(packets / 1e6, runtime, bytes, bytes * 8.0 / 1e9 / runtime)) print(("Made %s breaths: %.2f packets per breath; %.2fus per breath"):format(lib.comma_value(breaths), packets / breaths, runtime / breaths * 1e6)) print(("Rate(Mpps):\t%.3f"):format(packets / runtime / 1e6)) require("jit.p").stop() end
apache-2.0
cloudwu/skynet
lualib/skynet/db/mysql.lua
5
29544
-- Copyright (C) 2012 Yichun Zhang (agentzh) -- Copyright (C) 2014 Chang Feng -- This file is modified version from https://github.com/openresty/lua-resty-mysql -- The license is under the BSD license. -- Modified by Cloud Wu (remove bit32 for lua 5.3) -- protocol detail: https://mariadb.com/kb/en/clientserver-protocol/ local socketchannel = require "skynet.socketchannel" local crypt = require "skynet.crypt" local sub = string.sub local strgsub = string.gsub local strformat = string.format local strbyte = string.byte local strchar = string.char local strrep = string.rep local strunpack = string.unpack local strpack = string.pack local sha1 = crypt.sha1 local setmetatable = setmetatable local error = error local tonumber = tonumber local tointeger = math.tointeger local _M = {_VERSION = "0.14"} -- the following charset map is generated from the following mysql query: -- SELECT CHARACTER_SET_NAME, ID -- FROM information_schema.collations -- WHERE IS_DEFAULT = 'Yes' ORDER BY id; local CHARSET_MAP = { _default = 0, big5 = 1, dec8 = 3, cp850 = 4, hp8 = 6, koi8r = 7, latin1 = 8, latin2 = 9, swe7 = 10, ascii = 11, ujis = 12, sjis = 13, hebrew = 16, tis620 = 18, euckr = 19, koi8u = 22, gb2312 = 24, greek = 25, cp1250 = 26, gbk = 28, latin5 = 30, armscii8 = 32, utf8 = 33, ucs2 = 35, cp866 = 36, keybcs2 = 37, macce = 38, macroman = 39, cp852 = 40, latin7 = 41, utf8mb4 = 45, cp1251 = 51, utf16 = 54, utf16le = 56, cp1256 = 57, cp1257 = 59, utf32 = 60, binary = 63, geostd8 = 92, cp932 = 95, eucjpms = 97, gb18030 = 248 } -- constants local COM_QUERY = "\x03" local COM_PING = "\x0e" local COM_STMT_PREPARE = "\x16" local COM_STMT_EXECUTE = "\x17" local COM_STMT_CLOSE = "\x19" local COM_STMT_RESET = "\x1a" local CURSOR_TYPE_NO_CURSOR = 0x00 local SERVER_MORE_RESULTS_EXISTS = 8 local mt = {__index = _M} -- mysql field value type converters local converters = {} for i = 0x01, 0x05 do -- tiny, short, long, float, double converters[i] = tonumber end converters[0x08] = tonumber -- long long converters[0x09] = tonumber -- int24 converters[0x0d] = tonumber -- year converters[0xf6] = tonumber -- newdecimal local function _get_byte1(data, i) return strbyte(data, i), i + 1 end local function _get_int1(data, i, is_signed) if not is_signed then return strunpack("<I1", data, i) end return strunpack("<i1", data, i) end local function _get_byte2(data, i) return strunpack("<I2", data, i) end local function _get_int2(data, i, is_signed) if not is_signed then return strunpack("<I2", data, i) end return strunpack("<i2", data, i) end local function _get_byte3(data, i) return strunpack("<I3", data, i) end local function _get_int3(data, i, is_signed) if not is_signed then return strunpack("<I3", data, i) end return strunpack("<i3", data, i) end local function _get_byte4(data, i) return strunpack("<I4", data, i) end local function _get_int4(data, i, is_signed) if not is_signed then return strunpack("<I4", data, i) end return strunpack("<i4", data, i) end local function _get_byte8(data, i) return strunpack("<I8", data, i) end local function _get_int8(data, i, is_signed) if not is_signed then return strunpack("<I8", data, i) end return strunpack("<i8", data, i) end local function _get_float(data, i) return strunpack("<f", data, i) end local function _get_double(data, i) return strunpack("<d", data, i) end local function _set_byte2(n) return strpack("<I2", n) end -- local function _set_byte3(n) -- return strpack("<I3", n) -- end -- local function _set_byte4(n) -- return strpack("<I4", n) -- end -- local function _set_byte8(n) -- return strpack("<I8", n) -- end local function _set_int8(n) return strpack("<i8", n) end -- local function _set_float(n) -- return strpack("<f", n) -- end local function _set_double(n) return strpack("<d", n) end local function _from_cstring(data, i) return strunpack("z", data, i) end -- local function _dumphex(bytes) -- return strgsub(bytes, ".", -- function(x) -- return strformat("%02x ", strbyte(x)) -- end) -- end local function _compute_token(password, scramble) if password == "" then return "" end --_dumphex(scramble) local stage1 = sha1(password) --print("stage1:", _dumphex(stage1) ) local stage2 = sha1(stage1) local stage3 = sha1(scramble .. stage2) local i = 0 return strgsub(stage3, ".", function(x) i = i + 1 -- ~ is xor in lua 5.3 return strchar(strbyte(x) ~ strbyte(stage1, i)) end ) end local function _compose_packet(self, req) self.packet_no = self.packet_no + 1 local size = #req return strpack("<I3Bc" .. size, size, self.packet_no, req) end local function _recv_packet(self, sock) local data = sock:read(4) if not data then return nil, nil, "failed to receive packet header: " end local len, pos = _get_byte3(data, 1) if len == 0 then return nil, nil, "empty packet" end self.packet_no = strbyte(data, pos) data = sock:read(len) if not data then return nil, nil, "failed to read packet content: " end local field_count = strbyte(data, 1) local typ if field_count == 0x00 then typ = "OK" elseif field_count == 0xff then typ = "ERR" elseif field_count == 0xfe then typ = "EOF" else typ = "DATA" end return data, typ end local function _from_length_coded_bin(data, pos) local first = strbyte(data, pos) if not first then return nil, pos end if first >= 0 and first <= 250 then return first, pos + 1 end if first == 251 then return nil, pos + 1 end if first == 252 then pos = pos + 1 return _get_byte2(data, pos) end if first == 253 then pos = pos + 1 return _get_byte3(data, pos) end if first == 254 then pos = pos + 1 return _get_byte8(data, pos) end return false, pos + 1 end local function _set_length_coded_bin(n) if n < 251 then return strchar(n) end if n < (1 << 16) then return strpack("<BI2", 0xfc, n) end if n < (1 << 24) then return strpack("<BI3", 0xfd, n) end return strpack("<BI8", 0xfe, n) end local function _from_length_coded_str(data, pos) local len len, pos = _from_length_coded_bin(data, pos) if len == nil then return nil, pos end return sub(data, pos, pos + len - 1), pos + len end local function _parse_ok_packet(packet) local res = {} local pos res.affected_rows, pos = _from_length_coded_bin(packet, 2) res.insert_id, pos = _from_length_coded_bin(packet, pos) res.server_status, pos = _get_byte2(packet, pos) res.warning_count, pos = _get_byte2(packet, pos) local message = sub(packet, pos) if message and message ~= "" then res.message = message end return res end local function _parse_eof_packet(packet) local pos = 2 local warning_count, pos = _get_byte2(packet, pos) local status_flags = _get_byte2(packet, pos) return warning_count, status_flags end local function _parse_err_packet(packet) local errno, pos = _get_byte2(packet, 2) local marker = sub(packet, pos, pos) local sqlstate if marker == '#' then -- with sqlstate pos = pos + 1 sqlstate = sub(packet, pos, pos + 5 - 1) pos = pos + 5 end local message = sub(packet, pos) return errno, message, sqlstate end local function _parse_result_set_header_packet(packet) local field_count, pos = _from_length_coded_bin(packet, 1) return field_count, _from_length_coded_bin(packet, pos) end local function _parse_field_packet(data) local col = {} local catalog, db, table, orig_table, orig_name, charsetnr, length local pos catalog, pos = _from_length_coded_str(data, 1) db, pos = _from_length_coded_str(data, pos) table, pos = _from_length_coded_str(data, pos) orig_table, pos = _from_length_coded_str(data, pos) col.name, pos = _from_length_coded_str(data, pos) orig_name, pos = _from_length_coded_str(data, pos) pos = pos + 1 -- ignore the filler charsetnr, pos = _get_byte2(data, pos) length, pos = _get_byte4(data, pos) col.type = strbyte(data, pos) pos = pos + 1 local flags, pos = _get_byte2(data, pos) if flags & 0x20 == 0 then -- https://mariadb.com/kb/en/resultset/ col.is_signed = true end --[[ col.decimals = strbyte(data, pos) pos = pos + 1 local default = sub(data, pos + 2) if default and default ~= "" then col.default = default end --]] return col end local function _parse_row_data_packet(data, cols, compact) local value, col, conv local pos = 1 local ncols = #cols local row = {} for i = 1, ncols do value, pos = _from_length_coded_str(data, pos) col = cols[i] if value ~= nil then conv = converters[col.type] if conv then value = conv(value) end end if compact then row[i] = value else row[col.name] = value end end return row end local function _recv_field_packet(self, sock) local packet, typ, err = _recv_packet(self, sock) if not packet then return nil, err end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) return nil, msg, errno, sqlstate end if typ ~= "DATA" then return nil, "bad field packet type: " .. typ end -- typ == 'DATA' return _parse_field_packet(packet) end local function _recv_decode_packet_resp(self) return function(sock) local packet, typ, err = _recv_packet(self, sock) if not packet then return false, "failed to receive the result packet" .. err end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) return false, strformat("errno:%d, msg:%s,sqlstate:%s", errno, msg, sqlstate) end if typ == "EOF" then return false, "old pre-4.1 authentication protocol not supported" end return true, packet end end local function _mysql_login(self, user, password, charset, database, on_connect) return function(sockchannel) local dispatch_resp = _recv_decode_packet_resp(self) local packet = sockchannel:response(dispatch_resp) self.protocol_ver = strbyte(packet) local server_ver, pos = _from_cstring(packet, 2) if not server_ver then error "bad handshake initialization packet: bad server version" end self._server_ver = server_ver local thread_id, pos = _get_byte4(packet, pos) local scramble1 = sub(packet, pos, pos + 8 - 1) if not scramble1 then error "1st part of scramble not found" end pos = pos + 9 -- skip filler -- two lower bytes self._server_capabilities, pos = _get_byte2(packet, pos) self._server_lang = strbyte(packet, pos) pos = pos + 1 self._server_status, pos = _get_byte2(packet, pos) local more_capabilities more_capabilities, pos = _get_byte2(packet, pos) self._server_capabilities = self._server_capabilities | more_capabilities << 16 local len = 21 - 8 - 1 pos = pos + 1 + 10 local scramble_part2 = sub(packet, pos, pos + len - 1) if not scramble_part2 then error "2nd part of scramble not found" end local scramble = scramble1 .. scramble_part2 local token = _compute_token(password, scramble) local client_flags = 260047 local req = strpack("<I4I4c1c23zs1z", client_flags, self._max_packet_size, strchar(charset), strrep("\0", 23), user, token, database ) local authpacket = _compose_packet(self, req) sockchannel:request(authpacket, dispatch_resp) if on_connect then on_connect(self) end end end -- 构造ping数据包 local function _compose_ping(self) self.packet_no = -1 return _compose_packet(self, COM_PING) end local function _compose_query(self, query) self.packet_no = -1 local cmd_packet = COM_QUERY .. query return _compose_packet(self, cmd_packet) end local function _compose_stmt_prepare(self, query) self.packet_no = -1 local cmd_packet = COM_STMT_PREPARE .. query return _compose_packet(self, cmd_packet) end --参数字段类型转换 local store_types = { number = function(v) if not tointeger(v) then return _set_byte2(0x05), _set_double(v) else return _set_byte2(0x08), _set_int8(v) end end, string = function(v) return _set_byte2(0x0f), _set_length_coded_bin(#v) .. v end, --bool转换为0,1 boolean = function(v) if v then return _set_byte2(0x01), strchar(1) else return _set_byte2(0x01), strchar(0) end end } store_types["nil"] = function(v) return _set_byte2(0x06), "" end local function _compose_stmt_execute(self, stmt, cursor_type, args) local arg_num = args.n if arg_num ~= stmt.param_count then error("require stmt.param_count " .. stmt.param_count .. " get arg_num " .. arg_num) end self.packet_no = -1 local cmd_packet = strpack("<c1I4BI4", COM_STMT_EXECUTE, stmt.prepare_id, cursor_type, 0x01) if arg_num > 0 then local f, ts, vs local types_buf = "" local values_buf = "" --生成NULL位图 local null_count = (arg_num + 7) // 8 local null_map = "" local field_index = 1 for i = 1, null_count do local byte = 0 for j = 0, 7 do if field_index < arg_num then if args[field_index] == nil then byte = byte | (1 << j) else byte = byte | (0 << j) end end field_index = field_index + 1 end null_map = null_map .. strchar(byte) end for i = 1, arg_num do local v = args[i] f = store_types[type(v)] if not f then error("invalid parameter type " .. type(v)) end ts, vs = f(v) types_buf = types_buf .. ts values_buf = values_buf .. vs end cmd_packet = cmd_packet .. null_map .. strchar(0x01) .. types_buf .. values_buf end return _compose_packet(self, cmd_packet) end local function read_result(self, sock) local packet, typ, err = _recv_packet(self, sock) if not packet then return nil, err --error( err ) end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) return nil, msg, errno, sqlstate --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) end if typ == "OK" then local res = _parse_ok_packet(packet) if res and res.server_status & SERVER_MORE_RESULTS_EXISTS ~= 0 then return res, "again" end return res end if typ ~= "DATA" then return nil, "packet type " .. typ .. " not supported" --error( "packet type " .. typ .. " not supported" ) end -- typ == 'DATA' local field_count, extra = _parse_result_set_header_packet(packet) local cols = {} for i = 1, field_count do local col, err, errno, sqlstate = _recv_field_packet(self, sock) if not col then return nil, err, errno, sqlstate --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) end cols[i] = col end local packet, typ, err = _recv_packet(self, sock) if not packet then --error( err) return nil, err end if typ ~= "EOF" then --error ( "unexpected packet type " .. typ .. " while eof packet is ".. "expected" ) return nil, "unexpected packet type " .. typ .. " while eof packet is " .. "expected" end -- typ == 'EOF' local compact = self.compact local rows = {} local i = 0 while true do packet, typ, err = _recv_packet(self, sock) if not packet then --error (err) return nil, err end if typ == "EOF" then local warning_count, status_flags = _parse_eof_packet(packet) if status_flags & SERVER_MORE_RESULTS_EXISTS ~= 0 then return rows, "again" end break end -- if typ ~= 'DATA' then -- return nil, 'bad row packet type: ' .. typ -- end -- typ == 'DATA' i = i + 1 rows[i] = _parse_row_data_packet(packet, cols, compact) end return rows end local function _query_resp(self) return function(sock) local res, err, errno, sqlstate = read_result(self, sock) if not res then local badresult = {} badresult.badresult = true badresult.err = err badresult.errno = errno badresult.sqlstate = sqlstate return true, badresult end if err ~= "again" then return true, res end local multiresultset = {res} multiresultset.multiresultset = true local i = 2 while err == "again" do res, err, errno, sqlstate = read_result(self, sock) if not res then multiresultset.badresult = true multiresultset.err = err multiresultset.errno = errno multiresultset.sqlstate = sqlstate return true, multiresultset end multiresultset[i] = res i = i + 1 end return true, multiresultset end end function _M.connect(opts) local self = setmetatable({}, mt) local max_packet_size = opts.max_packet_size if not max_packet_size then max_packet_size = 1024 * 1024 -- default 1 MB end self._max_packet_size = max_packet_size self.compact = opts.compact_arrays local database = opts.database or "" local user = opts.user or "" local password = opts.password or "" local charset = CHARSET_MAP[opts.charset or "_default"] local channel = socketchannel.channel { host = opts.host, port = opts.port or 3306, auth = _mysql_login(self, user, password, charset, database, opts.on_connect), overload = opts.overload } self.sockchannel = channel -- try connect first only once channel:connect(true) return self end function _M.disconnect(self) self.sockchannel:close() setmetatable(self, nil) end function _M.query(self, query) local querypacket = _compose_query(self, query) local sockchannel = self.sockchannel if not self.query_resp then self.query_resp = _query_resp(self) end return sockchannel:request(querypacket, self.query_resp) end local function read_prepare_result(self, sock) local resp = {} local packet, typ, err = _recv_packet(self, sock) if not packet then resp.badresult = true resp.errno = 300101 resp.err = err return false, resp end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) resp.badresult = true resp.errno = errno resp.err = msg resp.sqlstate = sqlstate return true, resp end --第一节只能是OK if typ ~= "OK" then resp.badresult = true resp.errno = 300201 resp.err = "first typ must be OK,now" .. typ return false, resp end resp.prepare_id, resp.field_count, resp.param_count, resp.warning_count = strunpack("<I4I2I2xI2", packet, 2) resp.params = {} resp.fields = {} if resp.param_count > 0 then local param = _recv_field_packet(self, sock) while param do table.insert(resp.params, param) param = _recv_field_packet(self, sock) end end if resp.field_count > 0 then local field = _recv_field_packet(self, sock) while field do table.insert(resp.fields, field) field = _recv_field_packet(self, sock) end end return true, resp end local function _prepare_resp(self, sql) return function(sock) return read_prepare_result(self, sock, sql) end end -- 注册预处理语句 function _M.prepare(self, sql) local querypacket = _compose_stmt_prepare(self, sql) local sockchannel = self.sockchannel if not self.prepare_resp then self.prepare_resp = _prepare_resp(self) end return sockchannel:request(querypacket, self.prepare_resp) end local function _get_datetime(data, pos) local len, year, month, day, hour, minute, second local value len, pos = _from_length_coded_bin(data, pos) if len == 7 then year, month, day, hour, minute, second, pos = string.unpack("<I2BBBBB", data, pos) value = strformat("%04d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second) else value = "2017-09-09 20:08:09" --unsupported format pos = pos + len end return value, pos end -- 字段类型参考 https://dev.mysql.com/doc/dev/mysql-server/8.0.12/binary__log__types_8h.html enum_field_types 枚举类型定义 local _binary_parser = { [0x01] = _get_int1, [0x02] = _get_int2, [0x03] = _get_int4, [0x04] = _get_float, [0x05] = _get_double, [0x07] = _get_datetime, [0x08] = _get_int8, [0x09] = _get_int3, [0x0c] = _get_datetime, [0x0f] = _from_length_coded_str, [0x10] = _from_length_coded_str, [0xf5] = _from_length_coded_str, [0xf9] = _from_length_coded_str, [0xfa] = _from_length_coded_str, [0xfb] = _from_length_coded_str, [0xfc] = _from_length_coded_str, [0xfd] = _from_length_coded_str, [0xfe] = _from_length_coded_str } local function _parse_row_data_binary(data, cols, compact) local ncols = #cols -- 空位图,前两个bit系统保留 (列数量 + 7 + 2) / 8 local null_count = (ncols + 9) // 8 local pos = 2 + null_count local value --空字段表 local null_fields = {} local field_index = 1 local byte for i = 2, pos - 1 do byte = strbyte(data, i) for j = 0, 7 do if field_index > 2 then if byte & (1 << j) == 0 then null_fields[field_index - 2] = false else null_fields[field_index - 2] = true end end field_index = field_index + 1 end end local row = {} local parser for i = 1, ncols do local col = cols[i] local typ = col.type local name = col.name if not null_fields[i] then parser = _binary_parser[typ] if not parser then error("_parse_row_data_binary()error,unsupported field type " .. typ) end value, pos = parser(data, pos, col.is_signed) if compact then row[i] = value else row[name] = value end end end return row end local function read_execute_result(self, sock) local packet, typ, err = _recv_packet(self, sock) if not packet then return nil, err --error( err ) end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) return nil, msg, errno, sqlstate --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) end if typ == "OK" then local res = _parse_ok_packet(packet) if res and res.server_status & SERVER_MORE_RESULTS_EXISTS ~= 0 then return res, "again" end return res end if typ ~= "DATA" then return nil, "packet type " .. typ .. " not supported" --error( "packet type " .. typ .. " not supported" ) end -- typ == 'DATA' -- local field_count, extra = _parse_result_set_header_packet(packet) local cols = {} local col while true do packet, typ, err = _recv_packet(self, sock) if typ == "EOF" then local warning_count, status_flags = _parse_eof_packet(packet) break end col = _parse_field_packet(packet) if not col then break --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) end table.insert(cols, col) end --没有记录集返回 if #cols < 1 then return {} end local compact = self.compact local rows = {} local row while true do packet, typ, err = _recv_packet(self, sock) if typ == "EOF" then local warning_count, status_flags = _parse_eof_packet(packet) if status_flags & SERVER_MORE_RESULTS_EXISTS ~= 0 then return rows, "again" end break end row = _parse_row_data_binary(packet, cols, compact) if not col then break end table.insert(rows, row) end return rows end local function _execute_resp(self) return function(sock) local res, err, errno, sqlstate = read_execute_result(self, sock) if not res then local badresult = {} badresult.badresult = true badresult.err = err badresult.errno = errno badresult.sqlstate = sqlstate return true, badresult end if err ~= "again" then return true, res end local mulitresultset = {res} mulitresultset.mulitresultset = true local i = 2 while err == "again" do res, err, errno, sqlstate = read_execute_result(self, sock) if not res then mulitresultset.badresult = true mulitresultset.err = err mulitresultset.errno = errno mulitresultset.sqlstate = sqlstate return true, mulitresultset end mulitresultset[i] = res i = i + 1 end return true, mulitresultset end end --[[ 执行预处理语句 失败返回字段 errno badresult sqlstate err ]] function _M.execute(self, stmt, ...) local querypacket, er = _compose_stmt_execute(self, stmt, CURSOR_TYPE_NO_CURSOR, table.pack(...)) if not querypacket then return { badresult = true, errno = 30902, err = er } end local sockchannel = self.sockchannel if not self.execute_resp then self.execute_resp = _execute_resp(self) end return sockchannel:request(querypacket, self.execute_resp) end local function _compose_stmt_reset(self, stmt) self.packet_no = -1 local cmd_packet = strpack("c1<I4", COM_STMT_RESET, stmt.prepare_id) return _compose_packet(self, cmd_packet) end --重置预处理句柄 function _M.stmt_reset(self, stmt) local querypacket = _compose_stmt_reset(self, stmt) local sockchannel = self.sockchannel if not self.query_resp then self.query_resp = _query_resp(self) end return sockchannel:request(querypacket, self.query_resp) end local function _compose_stmt_close(self, stmt) self.packet_no = -1 local cmd_packet = strpack("c1<I4", COM_STMT_CLOSE, stmt.prepare_id) return _compose_packet(self, cmd_packet) end --关闭预处理句柄 function _M.stmt_close(self, stmt) local querypacket = _compose_stmt_close(self, stmt) local sockchannel = self.sockchannel return sockchannel:request(querypacket) end function _M.ping(self) local querypacket, er = _compose_ping(self) if not querypacket then return { badresult = true, errno = 30902, err = er } end local sockchannel = self.sockchannel if not self.query_resp then self.query_resp = _query_resp(self) end return sockchannel:request(querypacket, self.query_resp) end function _M.server_ver(self) return self._server_ver end local escape_map = { ['\0'] = "\\0", ['\b'] = "\\b", ['\n'] = "\\n", ['\r'] = "\\r", ['\t'] = "\\t", ['\26'] = "\\Z", ['\\'] = "\\\\", ["'"] = "\\'", ['"'] = '\\"', } function _M.quote_sql_str( str) return strformat("'%s'", strgsub(str, "[\0\b\n\r\t\26\\\'\"]", escape_map)) end function _M.set_compact_arrays(self, value) self.compact = value end return _M
mit
nvoron23/tarantool
test/big/tree_pk.test.lua
1
4618
dofile('utils.lua') s0 = box.schema.space.create('tweedledum') i0 = s0:create_index('primary', { type = 'tree', parts = {1, 'num'}, unique = true }) -- integer keys s0:insert{1, 'tuple'} box.snapshot() s0:insert{2, 'tuple 2'} box.snapshot() s0:insert{3, 'tuple 3'} s0.index['primary']:get{1} s0.index['primary']:get{2} s0.index['primary']:get{3} -- Cleanup s0:delete{1} s0:delete{2} s0:delete{3} -- Test incorrect keys - supplied key field type does not match index type -- https://bugs.launchpad.net/tarantool/+bug/1072624 s0:insert{'xxxxxxx'} s0:insert{''} s0:insert{'12'} s1 = box.schema.space.create('tweedledee') i1 = s1:create_index('primary', { type = 'tree', parts = {1, 'str'}, unique = true }) s2 = box.schema.space.create('alice') i2 = s2:create_index('primary', { type = 'tree', parts = {1, 'str'}, unique = true }) -- string keys s1:insert{'identifier', 'tuple'} box.snapshot() s1:insert{'second', 'tuple 2'} box.snapshot() s1.index['primary']:select('second', { limit = 100, iterator = 'GE' }) s1.index['primary']:select('identifier', { limit = 100, iterator = 'GE' }) s1:insert{'third', 'tuple 3'} s1.index['primary']:get{'identifier'} s1.index['primary']:get{'second'} s1.index['primary']:get{'third'} -- Cleanup s1:delete{'identifier'} s1:delete{'second'} s1:delete{'third'} --# setopt delimiter ';' function crossjoin(space0, space1, limit) local result = {} for state, v0 in space0:pairs() do for state, v1 in space1:pairs() do if limit <= 0 then return result end newtuple = v0:totable() for _, v in v1:pairs() do table.insert(newtuple, v) end table.insert(result, box.tuple.new(newtuple)) limit = limit - 1 end end return result end; --# setopt delimiter '' s2:insert{'1', 'tuple'} s1:insert{'1', 'tuple'} s1:insert{'2', 'tuple'} crossjoin(s1, s1, 0) crossjoin(s1, s1, 5) crossjoin(s1, s1, 10000) crossjoin(s1, s2, 10000) s1:truncate() s2:truncate() -- Bug #922520 - select missing keys s0:insert{200, 'select me!'} s0.index['primary']:get{200} s0.index['primary']:get{199} s0.index['primary']:get{201} -- Test partially specified keys in TREE indexes s1:insert{'abcd'} s1:insert{'abcda'} s1:insert{'abcda_'} s1:insert{'abcdb'} s1:insert{'abcdb_'} s1:insert{'abcdb__'} s1:insert{'abcdb___'} s1:insert{'abcdc'} s1:insert{'abcdc_'} box.sort(s1.index['primary']:select('abcdb', { limit = 3, iterator = 'GE' })) s1:drop() s1 = nil s2:drop() s2 = nil -- -- tree::replace tests -- s0:truncate() i1 = s0:create_index('i1', { type = 'tree', parts = {2, 'num'}, unique = true }) i2 = s0:create_index('i2', { type = 'tree', parts = {3, 'num'}, unique = false }) i3 = s0:create_index('i3', { type = 'tree', parts = {4, 'num'}, unique = true }) s0:insert{0, 0, 0, 0} s0:insert{1, 1, 1, 1} s0:insert{2, 2, 2, 2} -- OK s0:replace{1, 1, 1, 1} s0:replace{1, 10, 10, 10} s0:replace{1, 1, 1, 1} s0.index['primary']:get{10} s0.index['i1']:select{10} s0.index['i2']:select{10} s0.index['i3']:select{10} s0.index['primary']:get{1} s0.index['i1']:select{1} s0.index['i2']:select{1} s0.index['i3']:select{1} -- OK s0:insert{10, 10, 10, 10} s0:delete{10} s0.index['primary']:get{10} s0.index['i1']:select{10} s0.index['i2']:select{10} s0.index['i3']:select{10} -- TupleFound (primary key) s0:insert{1, 10, 10, 10} s0.index['primary']:get{10} s0.index['i1']:select{10} s0.index['i2']:select{10} s0.index['i3']:select{10} s0.index['primary']:get{1} -- TupleNotFound (primary key) s0:replace{10, 10, 10, 10} s0.index['primary']:get{10} s0.index['i1']:select{10} s0.index['i2']:select{10} s0.index['i3']:select{10} -- TupleFound (key #1) s0:insert{10, 0, 10, 10} s0.index['primary']:get{10} s0.index['i1']:select{10} s0.index['i2']:select{10} s0.index['i3']:select{10} s0.index['i1']:select{0} -- TupleFound (key #1) s0:replace{2, 0, 10, 10} s0.index['primary']:get{10} s0.index['i1']:select{10} s0.index['i2']:select{10} s0.index['i3']:select{10} s0.index['i1']:select{0} -- TupleFound (key #3) s0:insert{10, 10, 10, 0} s0.index['primary']:get{10} s0.index['i1']:select{10} s0.index['i2']:select{10} s0.index['i3']:select{10} s0.index['i3']:select{0} -- TupleFound (key #3) s0:replace{2, 10, 10, 0} s0.index['primary']:get{10} s0.index['i1']:select{10} s0.index['i2']:select{10} s0.index['i3']:select{10} s0.index['i3']:select{0} -- Non-Uniq test (key #2) s0:insert{4, 4, 0, 4} s0:insert{5, 5, 0, 5} s0:insert{6, 6, 0, 6} s0:replace{5, 5, 0, 5} box.sort(s0.index['i2']:select(0)) s0:delete{5} box.sort(s0.index['i2']:select(0)) s0:drop() s0 = nil
bsd-2-clause
imfoollink/NPLRuntime
Server/trunk/LuaJIT-2.1/src/jit/v.lua
54
5783
---------------------------------------------------------------------------- -- Verbose mode of the LuaJIT compiler. -- -- Copyright (C) 2005-2017 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module shows verbose information about the progress of the -- JIT compiler. It prints one line for each generated trace. This module -- is useful to see which code has been compiled or where the compiler -- punts and falls back to the interpreter. -- -- Example usage: -- -- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end" -- luajit -jv=myapp.out myapp.lua -- -- Default output is to stderr. To redirect the output to a file, pass a -- filename as an argument (use '-' for stdout) or set the environment -- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the -- module is started. -- -- The output from the first example should look like this: -- -- [TRACE 1 (command line):1 loop] -- [TRACE 2 (1/3) (command line):1 -> 1] -- -- The first number in each line is the internal trace number. Next are -- the file name ('(command line)') and the line number (':1') where the -- trace has started. Side traces also show the parent trace number and -- the exit number where they are attached to in parentheses ('(1/3)'). -- An arrow at the end shows where the trace links to ('-> 1'), unless -- it loops to itself. -- -- In this case the inner loop gets hot and is traced first, generating -- a root trace. Then the last exit from the 1st trace gets hot, too, -- and triggers generation of the 2nd trace. The side trace follows the -- path along the outer loop and *around* the inner loop, back to its -- start, and then links to the 1st trace. Yes, this may seem unusual, -- if you know how traditional compilers work. Trace compilers are full -- of surprises like this -- have fun! :-) -- -- Aborted traces are shown like this: -- -- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50] -- -- Don't worry -- trace aborts are quite common, even in programs which -- can be fully compiled. The compiler may retry several times until it -- finds a suitable trace. -- -- Of course this doesn't work with features that are not-yet-implemented -- (NYI error messages). The VM simply falls back to the interpreter. This -- may not matter at all if the particular trace is not very high up in -- the CPU usage profile. Oh, and the interpreter is quite fast, too. -- -- Also check out the -jdump module, which prints all the gory details. -- ------------------------------------------------------------------------------ -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local jutil = require("jit.util") local vmdef = require("jit.vmdef") local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo local type, format = type, string.format local stdout, stderr = io.stdout, io.stderr -- Active flag and output file handle. local active, out ------------------------------------------------------------------------------ local startloc, startex local function fmtfunc(func, pc) local fi = funcinfo(func, pc) if fi.loc then return fi.loc elseif fi.ffid then return vmdef.ffnames[fi.ffid] elseif fi.addr then return format("C:%x", fi.addr) else return "(?)" end end -- Format trace error message. local function fmterr(err, info) if type(err) == "number" then if type(info) == "function" then info = fmtfunc(info) end err = format(vmdef.traceerr[err], info) end return err end -- Dump trace states. local function dump_trace(what, tr, func, pc, otr, oex) if what == "start" then startloc = fmtfunc(func, pc) startex = otr and "("..otr.."/"..(oex == -1 and "stitch" or oex)..") " or "" else if what == "abort" then local loc = fmtfunc(func, pc) if loc ~= startloc then out:write(format("[TRACE --- %s%s -- %s at %s]\n", startex, startloc, fmterr(otr, oex), loc)) else out:write(format("[TRACE --- %s%s -- %s]\n", startex, startloc, fmterr(otr, oex))) end elseif what == "stop" then local info = traceinfo(tr) local link, ltype = info.link, info.linktype if ltype == "interpreter" then out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n", tr, startex, startloc)) elseif ltype == "stitch" then out:write(format("[TRACE %3s %s%s %s %s]\n", tr, startex, startloc, ltype, fmtfunc(func, pc))) elseif link == tr or link == 0 then out:write(format("[TRACE %3s %s%s %s]\n", tr, startex, startloc, ltype)) elseif ltype == "root" then out:write(format("[TRACE %3s %s%s -> %d]\n", tr, startex, startloc, link)) else out:write(format("[TRACE %3s %s%s -> %d %s]\n", tr, startex, startloc, link, ltype)) end else out:write(format("[TRACE %s]\n", what)) end out:flush() end end ------------------------------------------------------------------------------ -- Detach dump handlers. local function dumpoff() if active then active = false jit.attach(dump_trace) if out and out ~= stdout and out ~= stderr then out:close() end out = nil end end -- Open the output file and attach dump handlers. local function dumpon(outfile) if active then dumpoff() end if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stderr end jit.attach(dump_trace, "trace") active = true end -- Public module functions. return { on = dumpon, off = dumpoff, start = dumpon -- For -j command line option. }
gpl-2.0
czfshine/Don-t-Starve
data/scripts/fx.lua
1
5742
local FX = { { name = "sanity_raise", bank = "blocker_sanity_fx", build = "blocker_sanity_fx", anim = "raise", sound = nil, sounddelay = nil, tint = nil, tintalpha = 0.5, }, { name = "sanity_lower", bank = "blocker_sanity_fx", build = "blocker_sanity_fx", anim = "lower", sound = nil, sounddelay = nil, tint = nil, tintalpha = 0.5, }, { name = "die_fx", bank = "die_fx", build = "die", anim = "small", sound = "dontstarve/common/deathpoof", sounddelay = nil, tint = Vector3(90/255, 66/255, 41/255), tintalpha = nil, }, { name = "sparks_fx", bank = "sparks", build = "sparks", anim = {"sparks_1", "sparks_2", "sparks_3"}, sound = nil, sounddelay = nil, tint = nil, tintalpha = nil, }, { name = "firework_fx", bank = "firework", build = "accomplishment_fireworks", anim = "single_firework", sound = "dontstarve/common/shrine/sadwork_fire", sound2 = "dontstarve/common/shrine/sadwork_explo", sounddelay2 = 26/30, tint = nil, tintalpha = nil, fn = function() GetClock():DoLightningLighting(.25) end, fntime = 26/30 }, { name = "multifirework_fx", bank = "firework", build = "accomplishment_fireworks", anim = "multi_firework", sound = "dontstarve/common/shrine/sadwork_fire", sound2 = "dontstarve/common/shrine/firework_explo", sounddelay2 = 26/30, tint = nil, tintalpha = nil, fn = function() GetClock():DoLightningLighting(1) end, fntime = 26/30 }, { name = "explode_small", bank = "explode", build = "explode", anim = "small", sound = nil, sounddelay = nil, tint = nil, tintalpha = nil, }, { name = "lightning_rod_fx", bank = "lightning_rod_fx", build = "lightning_rod_fx", anim = "idle", sound = nil, sounddelay = nil, tint = nil, tintalpha = nil, }, { name = "splash", bank = "splash", build = "splash", anim = "splash", sound = nil, sounddelay = nil, tint = nil, tintalpha = nil, }, { name = "small_puff", bank = "small_puff", build = "smoke_puff_small", anim = "puff", sound = "dontstarve/common/deathpoof", sounddelay = nil, tint = nil, tintalpha = nil, }, { name = "splash_ocean", bank = "splash", build = "splash_ocean", anim = "idle", sound = nil, sounddelay = nil, tint = nil, tintalpha = nil, }, { name = "maxwell_smoke", bank = "max_fx", build = "max_fx", anim = "anim", sound = nil, sounddelay = nil, tint = nil, tintalpha = nil, }, { name = "shovel_dirt", bank = "shovel_dirt", build = "shovel_dirt", anim = "anim", sound = nil, sounddelay = nil, tint = nil, tintalpha = nil, }, { name = "mining_fx", bank = "mining_fx", build = "mining_fx", anim = "anim", sound = nil, sounddelay = nil, tint = nil, tintalpha = nil, }, { name = "pine_needles", bank = "pine_needles", build = "pine_needles", anim = {"chop", "fall"}, sound = nil, sounddelay = nil, tint = nil, tintalpha = nil, }, { name = "dr_warm_loop_1", bank = "diviningrod_fx", build = "diviningrod_fx", anim = "warm_loop", sound = nil, sounddelay = nil, tint = Vector3(105/255, 160/255, 255/255), tintalpha = nil, }, { name = "dr_warm_loop_2", bank = "diviningrod_fx", build = "diviningrod_fx", anim = "warm_loop", sound = nil, sounddelay = nil, tint = Vector3(105/255, 182/255, 239/255), tintalpha = nil, }, { name = "dr_warmer_loop", bank = "diviningrod_fx", build = "diviningrod_fx", anim = "warmer_loop", sound = nil, sounddelay = nil, tint = Vector3(255/255, 163/255, 26/255), tintalpha = nil, }, { name = "dr_hot_loop", bank = "diviningrod_fx", build = "diviningrod_fx", anim = "hot_loop", sound = nil, sounddelay = nil, tint = Vector3(181/255, 32/255, 32/255), tintalpha = nil, }, { name = "statue_transition", bank = "statue_ruins_fx", build = "statue_ruins_fx", anim = "transform_nightmare", sound = nil, sounddelay = nil, tint = nil, tintalpha = 0.6, }, { name = "statue_transition_2", bank = "die_fx", build = "die", anim = "small", sound = "dontstarve/common/deathpoof", sounddelay = nil, tint = Vector3(0,0,0), tintalpha = 0.6, }, { name = "sparklefx", bank = "sparklefx", build = "sparklefx", anim = "sparkle", sounddelay = nil, tint = nil, --transform = Vector3(1.5, 1, 1) }, { name = "book_fx", bank = "book_fx", build = "book_fx", anim = "book_fx", sound = nil, sounddelay = nil, tint = nil, tintalpha = 0.4, --transform = Vector3(1.5, 1, 1) }, { name = "waxwell_book_fx", bank = "book_fx", build = "book_fx", anim = "book_fx", sound = nil, sounddelay = nil, tint = Vector3(0,0,0), tintalpha = nil, --transform = Vector3(1.5, 1, 1) }, { name = "chester_transform_fx", bank = "die_fx", build = "die", anim = "small", }, } return FX
gpl-2.0
TimSimpson/Macaroni
Next/Release/cavatappi.lua
2
2888
dependency {group=upper.Group, name="Macaroni.Tests.Bugs", version=upper.Version} dependency {group="Macaroni.Examples", name="Hello", version="1.0.0.0"} sources = { "source/scripts", "source/www" } output = "target" local manifestDir = Path.New(manifestDirectory) function newPath(suffix) return manifestDir:NewPathForceSlash(suffix):CreateWithCurrentAsRoot(); end function copyCppFiles(src, dst) copyFiles(src, dst, [[\.(c|cpp|h|hpp)?$]]); end function copyFiles(src, dst, regex) local filePaths = src:GetPaths(regex) for i = 1, #filePaths do local fp = filePaths[i]; fp:CopyToDifferentRootPath(dst, true); -- print(tostring(fp)); end end function copyJamFiles(src, dst) copyFiles(src, dst, [[\.jam?$]]); end function copyResourceFiles(src, dst) copyFiles(src, dst, [[\.(ico|rc|rc2|h)?$]]); end function createDistributionDirectory() local dstDir = newPath("target/macaroni-" .. upper.Version); createDistributionDirectoryBase(dstDir) newPath("../Main/App/GeneratedSource/release/release"):NewPath("/macaroni.exe") :CopyToDifferentRootPath(dstDir, true); newPath("../Main/App/GeneratedSource/release/release"):NewPath("/messages.txt") :CopyToDifferentRootPath(dstDir, true); end function createDebugDistributionDirectory() local dstDir = newPath("target/macaroni-" .. upper.Version .. "-debug"); createDistributionDirectoryBase(dstDir) newPath("../Main/App/GeneratedSource/release/debug"):NewPath("/macaroni.exe") :CopyToDifferentRootPath(dstDir, true); newPath("../Main/App/GeneratedSource/release/debug"):NewPath("/messages.txt") :CopyToDifferentRootPath(dstDir, true); end function createDistributionDirectoryBase(dstDir) copyFiles(newPath("../Main"):NewPath("/Generators"), dstDir, [[\.lua?$]]); copyFiles(newPath("../Main"):NewPath("/Libraries"), dstDir, [[\.(jam|lua|mh)?$]]); end function createPureCpp() local dstDir = newPath("target/macaroni-" .. upper.Version .. "-pureCpp"); copyCppFiles(newPath("../Main/Dependencies/Lua/target"), dstDir); copyCppFiles(newPath("../Main/App/Source/main/mcpp"), dstDir); copyResourceFiles(newPath("../Main/App/Source/main/resources"), dstDir); copyCppFiles(newPath("../Main/App/GeneratedSource"), dstDir); copyFiles(newPath("../Main/App/Source/main/pureCppExtraFiles"), dstDir, [[\.(jam|txt)?$]]); end function build() createDistributionDirectory(); createDebugDistributionDirectory(); createPureCpp(); run("Site"); local versionDownloads = manifestDir:NewPathForceSlash( "target/www/site/downloads/" .. upper.Version); versionDownloads:CreateDirectory(); print("TODO: Zip up distirubiton directory and pure CPP directory and place in " .. tostring(versionDownloads) .. '.'); print("TODO: Zip up the directory " .. tostring(versionDownloads) .. " - it is your release artifact."); end
apache-2.0
Drudoo/Factionizer
Locales/esES.lua
2
19753
-- Español (Spanish) -------------------- -------------------- if (GetLocale() =="esES" or GetLocale() =="esMX") then -- Binding names BINDING_HEADER_FACTIONIZER = "Factionizer" BINDING_NAME_SHOWCONFIG = "Las opciones de Mostrar ventana" BINDING_NAME_SHOWDETAILS = "Mostrar ventana reputación detalle" FIZ_TXT = {} FIZ_TXT.Mob = {} -- help FIZ_TXT.help = "Una herramienta para gestionar tu reputación" FIZ_TXT.command = "No se pudo analizar comando" FIZ_TXT.usage = "Uso" FIZ_TXT.helphelp = "Mostrar este texto de ayuda" FIZ_TXT.helpabout = "Afficher les informations sur l'auteur" FIZ_TXT.helpstatus = "Mostrar estado de configuración" -- about FIZ_TXT.by = "por" FIZ_TXT.version = "Versión" FIZ_TXT.date = "fecha" FIZ_TXT.web = "sitio web" FIZ_TXT.slash = "tala comando" FIZ_TXT_STAND_LV = {} FIZ_TXT_STAND_LV[0] = "Desconocido" FIZ_TXT_STAND_LV[1] = "Odiado" FIZ_TXT_STAND_LV[2] = "Hostil" FIZ_TXT_STAND_LV[3] = "Antipático" FIZ_TXT_STAND_LV[4] = "Neutral" FIZ_TXT_STAND_LV[5] = "Amistoso" FIZ_TXT_STAND_LV[6] = "Honrado" FIZ_TXT_STAND_LV[7] = "Venerado" FIZ_TXT_STAND_LV[8] = "Exaltado" -- status FIZ_TXT.status = "estado" FIZ_TXT.disabled = "discapacitado" FIZ_TXT.enabled = "habilitado" FIZ_TXT.statMobs = "Mostrar Mobs [M]" FIZ_TXT.statQuests = "Mostrar Misiones [Q]" FIZ_TXT.statInstances = "Mostrar instancias [D]" FIZ_TXT.statItems = "Mostrar elementos [I]" FIZ_TXT.statGeneral = "Mostrar general [G]" FIZ_TXT.statMissing = "Mostrar reputación falta" FIZ_TXT.statDetails = "Mostrar detalles de la trama extendida" FIZ_TXT.statChat = "Mensaje de chat detallada" FIZ_TXT.statNoGuildChat = "No gremio de chat para rep" FIZ_TXT.statSuppress = "Eliminar mensaje de chat originales" FIZ_TXT.statPreview = "Mostrar vista previa en el marco rep reputación" FIZ_TXT.statSwitch = "Cambiar automáticamente de rep facción bar" FIZ_TXT.statNoGuildSwitch = "Sin conmutación por gremio representante" FIZ_TXT.statSilentSwitch = "No hay ningún mensaje cuando se cambia bar" FIZ_TXT.statGuildCap = "Mostrar tapón gremio reputación en el chat" -- XML UI elements FIZ_TXT.showQuests = "Mostrar Misiones" FIZ_TXT.showInstances = "Mostrar instancias" FIZ_TXT.showMobs = "Mostrar Mobs" FIZ_TXT.showItems = "Mostrar elementos" FIZ_TXT.showGeneral = "Mostrar general" FIZ_TXT.showAll = "Mostrar todo" FIZ_TXT.showNone = "Mostrar Ninguno" FIZ_TXT.expand = "expandir" FIZ_TXT.collapse = "colapso" FIZ_TXT.supressNoneFaction = "Exclusión clara por facción" FIZ_TXT.supressNoneGlobal = "Exclusión transparente para todos" FIZ_TXT.suppressHint = "Haga clic en una búsqueda para excluirla del resumen" FIZ_TXT.clearSessionGain = "Borrar contador sesión ganancia" -- options dialog FIZ_TXT.showMissing = "Mostrar reputación que falta en el marco de la reputación" FIZ_TXT.extendDetails = "Mostrar detalles de la trama extendida reputación" FIZ_TXT.gainToChat = "Escribir mensajes detallados ganancia facción a la ventana de chat" FIZ_TXT.noGuildGain = "No escriba a chatear reputación gremio" FIZ_TXT.suppressOriginalGain = "Reprimir originales mensajes ganancia facción" FIZ_TXT.showPreviewRep = "Mostrar reputación que pueden ser entregados en el marco de la reputación" FIZ_TXT.switchFactionBar = "Bar Interruptor de reputación con la facción para quien acaba de ganar reputación" FIZ_TXT.noGuildSwitch = "No encienda bar reputación de reputación gremio" FIZ_TXT.silentSwitch = "No hay ningún mensaje para charlar cuando se cambia bar" FIZ_TXT.guildCap = "Mostrar tapón gremio reputación en el chat" FIZ_TXT.defaultChatFrame = "El uso de fotogramas predeterminada de chat" FIZ_TXT.chatFrame = "Usando marco del chat %d (%s)" FIZ_TXT.usingDefaultChatFrame = "Ahora, utilizando fotogramas predeterminada de chat" FIZ_TXT.usingChatFrame = "Ahora, utilizando marco del chat" -- various LUA FIZ_TXT.options = "Opciones" FIZ_TXT.orderByStanding = "Ordenar por pie" FIZ_TXT.lookup = "Mirando hacia arriba facción" FIZ_TXT.allFactions = "Listado de todas las facciones" FIZ_TXT.missing = "(al siguiente)" FIZ_TXT.missing2 = "que falta" FIZ_TXT.heroic = "heroico" FIZ_TXT.normal = "normal" FIZ_TXT.switchBar = "Cambiar bar reputación" -- FIZ_ShowFactions FIZ_TXT.faction = "Faction" FIZ_TXT.is = "is" FIZ_TXT.withStanding = "with standing" FIZ_TXT.needed = "needed" FIZ_TXT.mob = "[Mob]" FIZ_TXT.limited = "is limited to" FIZ_TXT.limitedPl = "are limited to" FIZ_TXT.quest = "[Quest]" FIZ_TXT.instance = "[Instance]" FIZ_TXT.items = "[Items]" FIZ_TXT.unknown = "is not known to this player" -- mob Details FIZ_TXT.tmob = "Todos los jefes" FIZ_TXT.oboss = "Otros jefes" FIZ_TXT.aboss = "Todos los jefes" FIZ_TXT.pboss = "Por Fundador" FIZ_TXT.fclear = "completas" FIZ_TXT.AU = "Any Unnamed" FIZ_TXT.AN = "Any named" FIZ_TXT.BB = "Bloodsail Buccaneer" FIZ_TXT.SSP = "Southsea Pirate" FIZ_TXT.Wa = "Wastewander" FIZ_TXT.VCm = "Any Venture Co. mob" FIZ_TXT.Mob.MoshOgg_Spellcrafter = "Creaconjuros Mosh'Ogg" FIZ_TXT.Mob.BoulderfistOgre = "Ogro Puño de Roca" -- Quest Details FIZ_TXT.cdq = "Ciudad principal cocinar misiones diarias" FIZ_TXT.coq = "Otra ciudad cocinar misiones diarias" FIZ_TXT.fdq = "Ciudad principal pesca misiones diarias" FIZ_TXT.foq = "Otra ciudad pesca misiones diarias" FIZ_TXT.ndq = "no misiones diarias" FIZ_TXT.deleted = "anticuado" FIZ_TXT.Championing = "Defender (Tabardo)" FIZ_TXT.bpqfg = "Por ciento de ganancia facción búsqueda" -- items Details FIZ_TXT.cbadge = "Distintivo de mención de Otra ciudad" -- instance Details FIZ_TXT.srfd = "Spillover representante de mazmorras" FIZ_TXT.tbd = "ToBe Done" FIZ_TXT.nci = "Cualquier mob basura (normal)" FIZ_TXT.hci = "Cualquier mob basura (heroico)" -- ToBeDone general FIZ_TXT.tfr = "Los Labradores La agricultura rep" FIZ_TXT.nswts = "No estoy seguro si esto empieza" FIZ_TXT.mnd = "Número máximo de misiones diarias" FIZ_TXT.mnds = "El número máximo de diarios es" -- ReputationDetails FIZ_TXT.currentRep = "Current reputation" FIZ_TXT.neededRep = "Reputation needed" FIZ_TXT.missingRep = "Reputation missing" FIZ_TXT.repInBag = "Reputation in bag" FIZ_TXT.repInBagBank = "Reputation in bag & bank" FIZ_TXT.repInQuest = "Reputation in quests" FIZ_TXT.factionGained = "Gained this session" FIZ_TXT.noInfo = "No information available for this faction/reputation." FIZ_TXT.toExalted = "Reputation to exalted" -- to chat FIZ_TXT.stats = " (Total: %s%d, Left: %d)" -- config changed FIZ_TXT.configQuestion = "Some (new) settings were enabled. This is only done once for a setting. It is recommended that you verify the Factionizer options." FIZ_TXT.showConfig = "View config" FIZ_TXT.later = "Later" -- UpdateList FIZ_TXT.mobShort = "[M]" FIZ_TXT.questShort = "[Q]" FIZ_TXT.instanceShort = "[D]" FIZ_TXT.itemsShort = "[I]" FIZ_TXT.generalShort = "[G]" FIZ_TXT.mobHead = "Gain reputation by killing this mob" FIZ_TXT.questHead = "Gain reputation by doing this quest" FIZ_TXT.instanceHead = "Gain reputation by running this instance" FIZ_TXT.itemsHead = "Gain reputation by handing in items" FIZ_TXT.generalHead = "General information about gaining reputation" FIZ_TXT.mobTip = "Each time you kill this mob, you gain reputation. Doing this often enough, will help you reach the next level." FIZ_TXT.questTip = "Each time you complete this repeatable or daily quest, you gain reputation. Doing this often enough, will help you reach the next level." FIZ_TXT.instanceTip = "Each time you run this instance, you gain reputation. Doing this often enough, will help you reach the next level." FIZ_TXT.itemsName = "Item hand-in" FIZ_TXT.itemsTip = "Each time you hand in the listed items, you will gain reputation. Doing this often enough, will help you reach the next level." FIZ_TXT.generalTip = "This is information about reputation gain with a faction that does not necessarily relate to repeatable gain methods." FIZ_TXT.allOfTheAbove = "Summary of %d quests listed above" FIZ_TXT.questSummaryHead = FIZ_TXT.allOfTheAbove FIZ_TXT.questSummaryTip = "This entry shows a summary of all the quests listed above.\r\nThis is useful assuming that all the quests listed are daily quests, as this will show you how many days it will take you to reach the next reputation level if you do all the daily quests each day." FIZ_TXT.complete = "complete" FIZ_TXT.active = "active" FIZ_TXT.inBag = "In bags" FIZ_TXT.turnIns = "Turn-ins:" FIZ_TXT.reputation = "Reputation:" FIZ_TXT.reputationCap = "Reputation cap:" FIZ_TXT.reputationCapCurrent = "Current reputation:" FIZ_TXT.inBagBank = "In bags and bank" FIZ_TXT.questCompleted = "Quest completed" FIZ_TXT.timesToDo = "Times to do:" FIZ_TXT.instance2 = "Instance:" FIZ_TXT.mode = "Mode:" FIZ_TXT.timesToRun = "Times to run:" FIZ_TXT.mob2 = "Mob:" FIZ_TXT.location = "Location:" FIZ_TXT.toDo = "To do:" FIZ_TXT.quest2 = "Quest:" FIZ_TXT.itemsRequired = "Items required" FIZ_TXT.general2 = "General:" FIZ_TXT.maxStanding = "Yields reputation until" -- skills FIZ_TXT.skillHerb = "Herboristería" FIZ_TXT.skillMine = "Minería" FIZ_TXT.skillSkin = "Desuello" FIZ_TXT.skillAlch = "Alquimia" FIZ_TXT.skillBlack = "Herrería" FIZ_TXT.skillEnch = "Encantamiento" FIZ_TXT.skillEngi = "Ingeniería" FIZ_TXT.skillIncrip = "Inscripción" FIZ_TXT.skillJewel = "Joyería" FIZ_TXT.skillLeath = "Peletería" FIZ_TXT.skillTail = "Sastrería" FIZ_TXT.skillAid = "Primeros auxilios" FIZ_TXT.skillArch = "Arqueología" FIZ_TXT.skillCook = "Cocina" FIZ_TXT.skillFish = "Pesca" -- Tooltip FIZ_TXT.elements = {} FIZ_TXT.elements.name = {} FIZ_TXT.elements.tip = {} FIZ_TXT.elements.name.FIZ_OptionsButton = FIZ_TXT.options FIZ_TXT.elements.tip.FIZ_OptionsButton = "Abra una ventana para configurar Factionizer." FIZ_TXT.elements.name.FIZ_OrderByStandingCheckBox = FIZ_TXT.orderByStanding FIZ_TXT.elements.tip.FIZ_OrderByStandingCheckBox = "Si esta casilla no está marcada, la lista facción se muestra mediante una clasificación por defecto (ventisca), agrupados por orden lógico y alfabético. \r\n\r\n Si se marca esta casilla, la lista se ordena por la facción de pie. \r\n\r\n Para ver los | cFFFAA0A0inactive |r facciones , desactive esta casilla y vaya a la parte inferior de la lista." FIZ_TXT.elements.name.FIZ_ShowMobsButton = FIZ_TXT.showMobs FIZ_TXT.elements.tip.FIZ_ShowMobsButton = "Marque este botón para ver las turbas se puede matar a mejorar su reputación." FIZ_TXT.elements.name.FIZ_ShowQuestButton = FIZ_TXT.showQuests FIZ_TXT.elements.tip.FIZ_ShowQuestButton = "Marque este botón para ver las misiones que puede hacer para mejorar su reputación." FIZ_TXT.elements.name.FIZ_ShowItemsButton = FIZ_TXT.showItems FIZ_TXT.elements.tip.FIZ_ShowItemsButton = "Marque este botón para ver los elementos que puede entregar a mejorar su reputación." FIZ_TXT.elements.name.FIZ_ShowInstancesButton = FIZ_TXT.showInstances FIZ_TXT.elements.tip.FIZ_ShowInstancesButton = "Marque este botón para ver las instancias que puede ejecutar para mejorar su reputación." FIZ_TXT.elements.name.FIZ_ShowGeneralButton = FIZ_TXT.showGeneral FIZ_TXT.elements.tip.FIZ_ShowGeneralButton = "Marque este botón para ver la información general sobre la mejora de su reputación." FIZ_TXT.elements.name.FIZ_ShowAllButton = FIZ_TXT.showAll FIZ_TXT.elements.tip.FIZ_ShowAllButton = "Pulse este botón para comprobar las cuatro casillas de la izquierda. \r\nEsto mostrará mobs, misiones, objetos e instancias que le dan fama de la facción seleccionada." FIZ_TXT.elements.name.FIZ_ShowNoneButton = FIZ_TXT.showNone FIZ_TXT.elements.tip.FIZ_ShowNoneButton = "Pulse este botón para anular la selección de las cuatro casillas de la izquierda. \r\nDesde aquí puedes ver ninguna de las maneras de ganar reputación de la facción seleccionada." FIZ_TXT.elements.name.FIZ_ExpandButton = FIZ_TXT.expand FIZ_TXT.elements.tip.FIZ_ExpandButton = "Pulse este botón para expandir todas las entradas de la lista. Esto le mostrará los materiales necesarios para la mano en los quests recolección de elementos." FIZ_TXT.elements.name.FIZ_CollapseButton = FIZ_TXT.collapse FIZ_TXT.elements.tip.FIZ_CollapseButton = "Pulse este botón para cerrar todas las entradas de la lista. Esto ocultará los materiales necesarios a la mano en la recolección de búsquedas." FIZ_TXT.elements.name.FIZ_SupressNoneFactionButton = FIZ_TXT.supressNoneFaction FIZ_TXT.elements.tip.FIZ_SupressNoneFactionButton = "Pulse este botón para volver a activar todas las misiones de esta facción que ha excluido por righ-clic sobre él." FIZ_TXT.elements.name.FIZ_SupressNoneGlobalButton = FIZ_TXT.supressNoneGlobal FIZ_TXT.elements.tip.FIZ_SupressNoneGlobalButton = "Pulse este botón para volver a activar todas las misiones de todas las facciones que se han excluido, haga clic en él." FIZ_TXT.elements.name.FIZ_ClearSessionGainButton = FIZ_TXT.clearSessionGain FIZ_TXT.elements.tip.FIZ_ClearSessionGainButton = "Pulse este botón para borrar a cero el contador de la reputación adquirida en esta sesión." FIZ_TXT.elements.name.FIZ_EnableMissingBox = FIZ_TXT.showMissing FIZ_TXT.elements.tip.FIZ_EnableMissingBox = "Active esta opción para agregar los puntos de reputación faltantes necesarias para el próximo nivel de reputación detrás de la posición actual de cada facción en el marco de reputación." FIZ_TXT.elements.name.FIZ_ExtendDetailsBox = FIZ_TXT.extendDetails FIZ_TXT.elements.tip.FIZ_ExtendDetailsBox = "Active esta opción para mostrar un cuadro detalle reputación extendida. \r\nEn Además, la información que se muestra en el cuadro detalle original, esto mostrará la reputación faltante necesaria para alcanzar el siguiente nivel de reputación y una lista de maneras de ganar esta reputación mediante anuncio quests , las multitudes, los elementos e instancias que producen reputación de la facción elegida." FIZ_TXT.elements.name.FIZ_GainToChatBox = FIZ_TXT.gainToChat FIZ_TXT.elements.tip.FIZ_GainToChatBox = "Activez ce paramètre pour afficher réputation acquise pour toutes les factions chaque fois que vous gagnez réputation. \r\nCela diffère de la manière standard de reporting gain de réputation, car normalement, seul le gain avec la faction principale est répertorié." FIZ_TXT.elements.name.FIZ_NoGuildGainBox = FIZ_TXT.noGuildGain FIZ_TXT.elements.tip.FIZ_NoGuildGainBox = "Active este ajuste si no desea imprimir mensajes de chat reputación gremio." FIZ_TXT.elements.name.FIZ_SupressOriginalGainBox = FIZ_TXT.suppressOriginalGain FIZ_TXT.elements.tip.FIZ_SupressOriginalGainBox = "Active esta opción para suprimir los mensajes de ganar reputación estándar. \r\nEsto tiene sentido si se ha habilitado los mensajes ganancia facción detallados, por lo que no consigue listados idénticos a las versiones estándar y extendida." FIZ_TXT.elements.name.FIZ_ShowPreviewRepBox = FIZ_TXT.showPreviewRep FIZ_TXT.elements.tip.FIZ_ShowPreviewRepBox = "Active esta opción para mostrar la reputación se puede obtener mediante la presentación de artículos y Misiones como una barra gris superpuesto sobre la barra normal de reputación en el marco de reputación." FIZ_TXT.elements.name.FIZ_SwitchFactionBarBox = FIZ_TXT.switchFactionBar FIZ_TXT.elements.tip.FIZ_SwitchFactionBarBox = "Active esta opción para cambiar automáticamente la facción que se observaba a la facción último a quien le han ganado la reputación de." FIZ_TXT.elements.name.FIZ_NoGuildSwitchBox = FIZ_TXT.noGuildSwitch FIZ_TXT.elements.tip.FIZ_NoGuildSwitchBox = "Active esta opción para no cambiar la facción observó por ganancias de reputación del clan." FIZ_TXT.elements.name.FIZ_SilentSwitchBox = FIZ_TXT.silentSwitch FIZ_TXT.elements.tip.FIZ_SilentSwitchBox = "Active esta opción para cambiar la barra de reputación silenciosamente (sin mensaje de chat)." FIZ_TXT.elements.name.FIZ_GuildCapBox = FIZ_TXT.guildCap FIZ_TXT.elements.name.FIZ_ChatFrameSlider = "chatear marco" FIZ_TXT.elements.tip.FIZ_ChatFrameSlider = "Seleccione la charla marco Factionizer imprime sus mensajes" FIZ_TXT.elements.name.FIZ_OptionEnableMissing = FIZ_TXT.elements.name.FIZ_EnableMissingBox FIZ_TXT.elements.tip.FIZ_OptionEnableMissing = FIZ_TXT.elements.tip.FIZ_EnableMissingBox FIZ_TXT.elements.name.FIZ_OptionEnableMissingCB = FIZ_TXT.elements.name.FIZ_EnableMissingBox FIZ_TXT.elements.tip.FIZ_OptionEnableMissingCB = FIZ_TXT.elements.tip.FIZ_EnableMissingBox FIZ_TXT.elements.name.FIZ_OptionExtendDetails = FIZ_TXT.elements.name.FIZ_ExtendDetailsBox FIZ_TXT.elements.tip.FIZ_OptionExtendDetails = FIZ_TXT.elements.tip.FIZ_ExtendDetailsBox FIZ_TXT.elements.name.FIZ_OptionExtendDetailsCB = FIZ_TXT.elements.name.FIZ_ExtendDetailsBox FIZ_TXT.elements.tip.FIZ_OptionExtendDetailsCB = FIZ_TXT.elements.tip.FIZ_ExtendDetailsBox FIZ_TXT.elements.name.FIZ_OptionGainToChat = FIZ_TXT.elements.name.FIZ_GainToChatBox FIZ_TXT.elements.tip.FIZ_OptionGainToChat = FIZ_TXT.elements.tip.FIZ_GainToChatBox FIZ_TXT.elements.name.FIZ_OptionGainToChatCB = FIZ_TXT.elements.name.FIZ_GainToChatBox FIZ_TXT.elements.tip.FIZ_OptionGainToChatCB = FIZ_TXT.elements.tip.FIZ_GainToChatBox FIZ_TXT.elements.name.FIZ_OptionNoGuildGain = FIZ_TXT.elements.name.FIZ_NoGuildGainBox FIZ_TXT.elements.tip.FIZ_OptionNoGuildGain = FIZ_TXT.elements.tip.FIZ_NoGuildGainBox FIZ_TXT.elements.name.FIZ_OptionNoGuildGainCB = FIZ_TXT.elements.name.FIZ_NoGuildGainBox FIZ_TXT.elements.tip.FIZ_OptionNoGuildGainCB = FIZ_TXT.elements.tip.FIZ_NoGuildGainBox FIZ_TXT.elements.name.FIZ_OptionSupressOriginalGain = FIZ_TXT.elements.name.FIZ_SupressOriginalGainBox FIZ_TXT.elements.tip.FIZ_OptionSupressOriginalGain = FIZ_TXT.elements.tip.FIZ_SupressOriginalGainBox FIZ_TXT.elements.name.FIZ_OptionSupressOriginalGainCB = FIZ_TXT.elements.name.FIZ_SupressOriginalGainBox FIZ_TXT.elements.tip.FIZ_OptionSupressOriginalGainCB = FIZ_TXT.elements.tip.FIZ_SupressOriginalGainBox FIZ_TXT.elements.name.FIZ_OptionShowPreviewRep = FIZ_TXT.elements.name.FIZ_ShowPreviewRepBox FIZ_TXT.elements.tip.FIZ_OptionShowPreviewRep = FIZ_TXT.elements.tip.FIZ_ShowPreviewRepBox FIZ_TXT.elements.name.FIZ_OptionShowPreviewRepCB = FIZ_TXT.elements.name.FIZ_ShowPreviewRepBox FIZ_TXT.elements.tip.FIZ_OptionShowPreviewRepCB = FIZ_TXT.elements.tip.FIZ_ShowPreviewRepBox FIZ_TXT.elements.name.FIZ_OptionSwitchFactionBar = FIZ_TXT.elements.name.FIZ_SwitchFactionBarBox FIZ_TXT.elements.tip.FIZ_OptionSwitchFactionBar = FIZ_TXT.elements.tip.FIZ_SwitchFactionBarBox FIZ_TXT.elements.name.FIZ_OptionSwitchFactionBarCB = FIZ_TXT.elements.name.FIZ_SwitchFactionBarBox FIZ_TXT.elements.tip.FIZ_OptionSwitchFactionBarCB = FIZ_TXT.elements.tip.FIZ_SwitchFactionBarBox FIZ_TXT.elements.name.FIZ_OptionNoGuildSwitch = FIZ_TXT.elements.name.FIZ_NoGuildSwitchBox FIZ_TXT.elements.tip.FIZ_OptionNoGuildSwitch = FIZ_TXT.elements.tip.FIZ_NoGuildSwitchBox FIZ_TXT.elements.name.FIZ_OptionNoGuildSwitchCB = FIZ_TXT.elements.name.FIZ_NoGuildSwitchBox FIZ_TXT.elements.tip.FIZ_OptionNoGuildSwitchCB = FIZ_TXT.elements.tip.FIZ_NoGuildSwitchBox FIZ_TXT.elements.name.FIZ_OptionSilentSwitch = FIZ_TXT.elements.name.FIZ_SilentSwitchBox FIZ_TXT.elements.tip.FIZ_OptionSilentSwitch = FIZ_TXT.elements.tip.FIZ_SilentSwitchBox FIZ_TXT.elements.name.FIZ_OptionSilentSwitchCB = FIZ_TXT.elements.name.FIZ_SilentSwitchBox FIZ_TXT.elements.tip.FIZ_OptionSilentSwitchCB = FIZ_TXT.elements.tip.FIZ_SilentSwitchBox FIZ_TXT.elements.name.FIZ_OptionGuildCap = FIZ_TXT.elements.name.FIZ_GuildCapBox FIZ_TXT.elements.tip.FIZ_OptionGuildCap = FIZ_TXT.elements.tip.FIZ_GuildCapBox FIZ_TXT.elements.name.FIZ_OptionGuildCapCB = FIZ_TXT.elements.name.FIZ_GuildCapBox FIZ_TXT.elements.tip.FIZ_OptionGuildCapCB = FIZ_TXT.elements.tip.FIZ_GuildCapBox FIZ_TXT.elements.name.FIZ_OptionChatFrameSlider = FIZ_TXT.elements.name.FIZ_ChatFrameSlider FIZ_TXT.elements.tip.FIZ_OptionChatFrameSlider = FIZ_TXT.elements.tip.FIZ_ChatFrameSlider end
gpl-3.0
czfshine/Don-t-Starve
data/scripts/map/tasks/ruins.lua
1
5428
------------------------------------------------------------ -- Caves Ruins Level ------------------------------------------------------------ -- AddTask("CityInRuins", { -- locks={LOCKS.RUINS}, -- keys_given=KEYS.RUINS, -- entrance_room="RuinedCityEntrance", -- room_choices={ -- ["BGMaze"] = 10+math.random(SIZE_VARIATION), -- }, -- room_bg=GROUND.TILES, -- maze_tiles = {rooms={"default", "hallway_shop", "hallway_residential", "room_residential" }, bosses={"room_residential"}}, -- background_room="BGMaze", -- colour={r=1,g=0,b=0.6,a=1}, -- }) -- AddTask("AlterAhead", { -- locks={LOCKS.RUINS}, -- keys_given=KEYS.RUINS, -- entrance_room="LabyrinthCityEntrance", -- room_choices={ -- ["BGMaze"] = 6+math.random(SIZE_VARIATION), -- }, -- room_bg=GROUND.TILES, -- maze_tiles = {rooms={"default", "hallway", "hallway_armoury", "room_armoury" }, bosses={"room_armoury"}} , -- background_room="BGMaze", -- colour={r=1,g=0,b=0.6,a=1}, -- }) -- AddTask("TownSquare", { -- locks = {LOCKS.LABYRINTH}, -- keys_given = KEYS.NONE, -- entrance_room = "RuinedCityEntrance", -- room_choices = -- { -- ["BGMaze"] = 6+math.random(SIZE_VARIATION), -- }, -- room_bg = GROUND.TILES, -- maze_tiles = {"room_open"}, -- background_room="BGMaze", -- colour={r=1,g=0,b=0.6,a=1}, -- }) AddTask("RuinsStart", { locks={LOCKS.NONE}, keys_given= {KEYS.LABYRINTH, KEYS.RUINS}, room_choices={ ["PondWilds"] = math.random(1,3), ["SlurperWilds"] = math.random(1,3), ["LushWilds"] = math.random(1,2), ["LightWilds"] = math.random(1,3), }, room_bg=GROUND.MUD, background_room="BGWilds", colour={r=1,g=0,b=0.6,a=1}, }) AddTask("TheLabyrinth", { locks={LOCKS.LABYRINTH}, keys_given= {KEYS.SACRED}, entrance_room="LabyrinthEntrance", room_choices={ ["BGLabyrinth"] = 3+math.random(SIZE_VARIATION), ["LabyrinthGuarden"] = 1, }, room_bg=GROUND.BRICK, background_room="BGLabyrinth", colour={r=1,g=0,b=0.6,a=1}, }) AddTask("Residential", { locks = {LOCKS.RUINS}, keys_given = KEYS.NONE, entrance_room = "RuinedCityEntrance", room_choices = { ["Vacant"] = math.random(SIZE_VARIATION), ["BGMonkeyWilds"] = 4 + math.random(SIZE_VARIATION), }, room_bg = GROUND.TILES, maze_tiles = {rooms = {"room_residential", "room_residential_two", "hallway_residential", "hallway_residential_two"}, bosses = {"room_residential"}}, background_room="BGMonkeyWilds", colour={r=1,g=0,b=0.6,a=1}, }) AddTask("Military", { locks = {LOCKS.RUINS}, keys_given = KEYS.NONE, entrance_room = "MilitaryEntrance", room_choices = { ["BGMilitary"] = 4+math.random(SIZE_VARIATION), }, room_bg = GROUND.TILES, maze_tiles = {rooms = {"room_armoury", "hallway_armoury", "room_armoury_two"}, bosses = {"room_armoury_two"}}, background_room="BGMilitary", colour={r=1,g=0,b=0.6,a=1}, }) AddTask("Sacred", { locks = {LOCKS.SACRED}, keys_given = {KEYS.SACRED}, room_choices = { ["Barracks"] = math.random(1,2), ["Bishops"] = math.random(1,2), ["Spiral"] = math.random(1,2), ["BrokenAltar"] = math.random(1,2), ["Altar"] = 1 }, room_bg = GROUND.TILES, background_room="BGSacredGround", colour={r=1,g=0,b=0.6,a=1}, }) ----Optional Ruins Tasks---- AddTask("MoreAltars", { locks = {LOCKS.SACRED}, keys_given = {KEYS.SACRED}, room_choices = { ["BrokenAltar"] = math.random(1,2), ["Altar"] = math.random(1,2) }, room_bg = GROUND.TILES, background_room="BGSacredGround", colour={r=1,g=0,b=0.6,a=1}, }) AddTask("SacredDanger", { locks = {LOCKS.SACRED}, keys_given = {KEYS.SACRED}, room_choices = { ["Barracks"] = math.random(1,2), }, room_bg = GROUND.TILES, background_room="BGSacredGround", colour={r=1,g=0,b=0.6,a=1}, }) AddTask("FailedCamp", { locks={LOCKS.RUINS}, keys_given= {KEYS.NONE}, room_choices={ ["RuinsCamp"] = 1, }, room_bg=GROUND.MUD, background_room="BGWilds", colour={r=1,g=0,b=0.6,a=1}, }) AddTask("Military2", { locks = {LOCKS.RUINS}, keys_given = KEYS.NONE, entrance_room = "MilitaryEntrance", room_choices = { ["BGMilitary"] = 1+math.random(SIZE_VARIATION), }, room_bg = GROUND.TILES, maze_tiles = {rooms = {"room_armoury", "hallway_armoury", "room_armoury_two"}, bosses = {"room_armoury_two"}}, background_room="BGMilitary", colour={r=1,g=0,b=0.6,a=1}, }) AddTask("Sacred2", { locks = {LOCKS.SACRED}, keys_given = {KEYS.SACRED}, room_choices = { ["Barracks"] = math.random(1,2), ["Bishops"] = math.random(1,2), ["Spiral"] = math.random(1,2), ["BrokenAltar"] = math.random(1,2), }, room_bg = GROUND.TILES, background_room="BGSacredGround", colour={r=1,g=0,b=0.6,a=1}, }) AddTask("Residential2", { locks = {LOCKS.RUINS}, keys_given = KEYS.NONE, entrance_room = "RuinedCityEntrance", room_choices = { ["BGMonkeyWilds"] = 1 + math.random(SIZE_VARIATION), }, room_bg = GROUND.TILES, maze_tiles = {rooms = {"room_residential", "room_residential_two", "hallway_residential", "hallway_residential_two"}, bosses = {"room_residential"}}, background_room="BGMonkeyWilds", colour={r=1,g=0,b=0.6,a=1}, }) AddTask("Residential3", { locks = {LOCKS.RUINS}, keys_given = KEYS.NONE, room_choices = { ["Vacant"] = 1 + math.random(SIZE_VARIATION), }, room_bg = GROUND.TILES, background_room="BGWilds", colour={r=1,g=0,b=0.6,a=1}, })
gpl-2.0
victorperin/tibia-server
data/actions/scripts/in service of yalahar quest/inServiceOfYalaharQuestMechanism.lua
2
1728
local mechanisms = { [3091] = {pos = {x = 32744, y = 31161, z = 5}, value = 21}, -- Alchemist [3092] = {pos = {x = 32744, y = 31164, z = 5}, value = 21}, [3093] = {pos = {x = 32833, y = 31269, z = 5}, value = 24}, -- Trade [3094] = {pos = {x = 32833, y = 31266, z = 5}, value = 24}, [3095] = {pos = {x = 32729, y = 31200, z = 5}, value = 29}, -- Arena [3096] = {pos = {x = 32734, y = 31200, z = 5}, value = 29}, [3097] = {pos = {x = 32776, y = 31141, z = 5}, value = 35}, -- Cemetery [3098] = {pos = {x = 32776, y = 31145, z = 5}, value = 35}, [3099] = {pos = {x = 32874, y = 31202, z = 5}, value = 41}, -- Sunken [3100] = {pos = {x = 32869, y = 31202, z = 5}, value = 41}, [3101] = {pos = {x = 32856, y = 31251, z = 5}, value = 45}, -- Factory [3102] = {pos = {x = 32854, y = 31248, z = 5}, value = 45} } local mechanisms2 = { [9235] = {pos = {x = 32773, y = 31116, z = 7}}, [9236] = {pos = {x = 32780, y = 31115, z = 7}} } function onUse(cid, item, fromPosition, itemEx, toPosition) local player = Player(cid) if(mechanisms[item.uid]) then if(player:getStorageValue(Storage.InServiceofYalahar.Questline) >= mechanisms[item.uid].value) then player:getPosition():sendMagicEffect(CONST_ME_TELEPORT) player:teleportTo(mechanisms[item.uid].pos) player:getPosition():sendMagicEffect(CONST_ME_TELEPORT) else player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "The gate mechanism won't move. You probably have to find a way around until you figure out how to operate the gate.") end elseif(mechanisms2[item.uid]) then player:getPosition():sendMagicEffect(CONST_ME_TELEPORT) player:teleportTo(mechanisms2[item.uid].pos) player:getPosition():sendMagicEffect(CONST_ME_TELEPORT) end return true end
apache-2.0
mohammadrezajijitg/maikel
plugins/msg-checks.lua
1
21461
--Begin msg_checks.lua By @SoLiD local TIME_CHECK = 2 local function pre_process(msg) local data = load_data(_config.moderation.data) local chat = msg.to.id local user = msg.from.id local is_channel = msg.to.type == "channel" local is_chat = msg.to.type == "chat" local auto_leave = 'auto_leave_bot' local hash = "gp_lang:"..chat local lang = redis:get(hash) if is_channel or is_chat then if msg.text then if msg.text:match("(.*)") then if not data[tostring(msg.to.id)] and not redis:get(auto_leave) and not is_admin(msg) then tdcli.sendMessage(msg.to.id, "", 0, "_This Is Not One Of My_ *Groups*", 0, "md") tdcli.changeChatMemberStatus(chat, our_id, 'Left', dl_cb, nil) end end end if data[tostring(chat)] and data[tostring(chat)]['settings'] then settings = data[tostring(chat)]['settings'] else return end if settings.mute_all then mute_all = settings.mute_all else mute_all = 'no' end if settings.mute_gif then mute_gif = settings.mute_gif else mute_gif = 'no' end if settings.mute_photo then mute_photo = settings.mute_photo else mute_photo = 'no' end if settings.mute_sticker then mute_sticker = settings.mute_sticker else mute_sticker = 'no' end if settings.mute_contact then mute_contact = settings.mute_contact else mute_contact = 'no' end if settings.mute_inline then mute_inline = settings.mute_inline else mute_inline = 'no' end if settings.mute_game then mute_game = settings.mute_game else mute_game = 'no' end if settings.mute_text then mute_text = settings.mute_text else mute_text = 'no' end if settings.mute_keyboard then mute_keyboard = settings.mute_keyboard else mute_keyboard = 'no' end if settings.mute_forward then mute_forward = settings.mute_forward else mute_forward = 'no' end if settings.mute_location then mute_location = settings.mute_location else mute_location = 'no' end if settings.mute_document then mute_document = settings.mute_document else mute_document = 'no' end if settings.mute_voice then mute_voice = settings.mute_voice else mute_voice = 'no' end if settings.mute_audio then mute_audio = settings.mute_audio else mute_audio = 'no' end if settings.mute_video then mute_video = settings.mute_video else mute_video = 'no' end if settings.mute_tgservice then mute_tgservice = settings.mute_tgservice else mute_tgservice = 'no' end if settings.lock_link then lock_link = settings.lock_link else lock_link = 'no' end if settings.lock_tag then lock_tag = settings.lock_tag else lock_tag = 'no' end if settings.english then english = settings.english else english = 'no' end if settings.views then views = settings.views else views = 'no' end if settings.emoji then emoji = settings.emoji else emoji = 'no' end if settings.lock_pin then lock_pin = settings.lock_pin else lock_pin = 'no' end if settings.lock_arabic then lock_arabic = settings.lock_arabic else lock_arabic = 'no' end if settings.lock_mention then lock_mention = settings.lock_mention else lock_mention = 'no' end if settings.lock_edit then lock_edit = settings.lock_edit else lock_edit = 'no' end if settings.lock_spam then lock_spam = settings.lock_spam else lock_spam = 'no' end if settings.flood then lock_flood = settings.flood else lock_flood = 'no' end if settings.fosh then fosh = settings.fosh else fosh = 'no' end if settings.ads then ads = settings.ads else ads = 'no' end if settings.lock_markdown then lock_markdown = settings.lock_markdown else lock_markdown = 'no' end if settings.lock_webpage then lock_webpage = settings.lock_webpage else lock_webpage = 'no' end if msg.adduser or msg.joinuser or msg.deluser then if mute_tgservice == "yes" then del_msg(chat, tonumber(msg.id)) end end if msg.pinned and is_channel then if lock_pin == "yes" then if is_owner(msg) then return end if tonumber(msg.from.id) == our_id then return end local pin_msg = data[tostring(chat)]['pin'] if pin_msg then tdcli.pinChannelMessage(msg.to.id, pin_msg, 1) elseif not pin_msg then tdcli.unpinChannelMessage(msg.to.id) end if lang then tdcli.sendMessage(msg.to.id, msg.id, 0, '<b>User ID :</b> <code>'..msg.from.id..'</code>\n<b>Username :</b> '..('@'..msg.from.username or '<i>No Username</i>')..'\n<i>شما اجازه دسترسی به سنجاق پیام را ندارید، به همین دلیل پیام قبلی مجدد سنجاق میگردد</i>', 0, "html") elseif not lang then tdcli.sendMessage(msg.to.id, msg.id, 0, '<b>User ID :</b> <code>'..msg.from.id..'</code>\n<b>Username :</b> '..('@'..msg.from.username or '<i>No Username</i>')..'\n<i>You Have Not Permission To Pin Message, Last Message Has Been Pinned Again</i>', 0, "html") end end end if not is_mod(msg) then if msg.edited and lock_edit == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.forward_info_ and mute_forward == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.photo_ and mute_photo == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.video_ and mute_video == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.document_ and mute_document == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.sticker_ and mute_sticker == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.animation_ and mute_gif == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.contact_ and mute_contact == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.location_ and mute_location == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.voice_ and mute_voice == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.content_ and mute_keyboard == "yes" then if msg.reply_markup_ and msg.reply_markup_.ID == "ReplyMarkupInlineKeyboard" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end if tonumber(msg.via_bot_user_id_) ~= 0 and mute_inline == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.game_ and mute_game == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.audio_ and mute_audio == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.media.caption then local link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Dd][Oo][Gg]/") or msg.media.caption:match("[Tt].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if link_caption and lock_link == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local english_caption = msg.media.caption:match("[ASDFGHJKLQWERTYUIOPZXCVBNMasdfghjklqwertyuiopzxcvbnm]") if english_caption and english == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local tag_caption = msg.media.caption:match("@") or msg.media.caption:match("#") if tag_caption and lock_tag == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local fosh_caption = msg.media.caption:match("کص")or msg.media.caption:match("کون")or msg.media.caption:match("ممه")or msg.media.caption:match("کیری")or msg.media.caption:match("حرومی")or msg.media.caption:match("ننه") or msg.media.caption:match("کصده")or msg.media.caption:match("کث")or msg.media.caption:match("کسکش")or msg.media.caption:match("کصکش")or msg.media.caption:match("لاشی")or msg.media.caption:match("ناموس")or msg.media.caption:match("جنده")or msg.media.caption:match("یتیم")or msg.media.caption:match("خارکسده")or msg.media.caption:match("مادرجنده")or msg.media.caption:match("حرومزاده")or msg.media.caption:match("خواهرجنده")or msg.media.caption:match("خواهرتو")or msg.media.caption:match("مادرتو")or msg.media.caption:match("کونی")or msg.media.caption:match("اوبی")or msg.media.caption:match("لاشی")or msg.media.caption:match("kir")or msg.media.caption:match("kos")or msg.media.caption:match("lashi") if fosh_caption and fosh == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local ads_caption = msg.media.caption:match("شارژ") or msg.media.caption:match("چالش") or msg.media.caption:match("عضو چنل شید") or msg.media.caption:match("ایرانسل") or msg.media.caption:match("همراه اول") or msg.media.caption:match("رایتل") or msg.media.caption:match("جایزه نفر اول") or msg.media.caption:match("جایزه نفر دوم") or msg.media.caption:match("جایزه نفر سوم") or msg.media.caption:match("پیج اینستا") or msg.media.caption:match("instagram.com") or msg.media.caption:match("www") or msg.media.caption:match("t.me/") or msg.media.caption:match("telegram.me/") or msg.media.caption:match("چالش") or msg.media.caption:match("کد شارژ") or msg.media.caption:match("شارژ رایگان") or msg.media.caption:match("پیج تلگرام") or msg.media.caption:match("کانال تلگرامی ما") or msg.media.caption:match("جایزه جایزه") or msg.media.caption:match("پخش کنید") or msg.media.caption:match("چالش داریم") or msg.media.caption:match("تبلیغات") or msg.media.caption:match("پذیرفتن تبلیغ") if ads_caption and ads == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local english_caption = msg.media.caption:match("[ASDFGHJKLQWERTYUIOPZXCVBNMasdfghjklqwertyuiopzxcvbnm]") if english_caption and english == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local emoji_caption = msg.media.caption:match("[😀😬😁😂😃😄😅☺️🙃🙂😊😉😇😆😋😌😍😘😗😙😚🤗😎🤓🤑😛😝😜😏😶😐😑😒🙄🤔😕😔😡😠😟😞😳🙁☹️😣😖😫😩😤😧😦😯😰😨😱😮😢😥😪😓😭😵😲💩💤😴🤕🤒😷🤐😈👿👹👺💀👻👽😽😼😻😹😸😺🤖🙀😿😾🙌🏻👏🏻👋🏻👍🏻👎🏻👊🏻✊🏻✌🏻👌🏻✋🏻👐🏻💪🏻🙏🏻☝🏻️👆🏻👇🏻👈🏻👉🏻🖕🏻🖐🏻🤘🏻🖖🏻✍🏻💅🏻👄👅👂🏻👃🏻👁👀👤👥👱🏻👩🏻👨🏻👧🏻👦🏻👶🏻🗣👴🏻👵🏻👲🏻🏃🏻🚶🏻💑👩‍❤️‍👩👨‍❤️‍👨💏👩‍❤️‍💋‍👩👨‍❤️‍💋‍👨👪👩‍👩‍👧‍👦👩‍👩‍👧👩‍👩‍👦👨‍👩‍👧‍👧👨‍👩‍👦‍👦👨‍👩‍👧‍👦👨‍👩‍👧👩‍👩‍👦‍👦👩‍👩‍👧‍👧👨‍👨‍👦👨‍👨‍👧👨‍👨‍👧‍👦👨‍👨‍👦‍👦👨‍👨‍👧‍👧👘👙👗👔👖👕👚💄💋👣👠👡👢👞🎒⛑👑🎓🎩👒👟👝👛👜💼👓🕶💍🌂🐶🐱🐭🐹🐰🐻🐼🐸🐽🐷🐮🦁🐯🐨🐙🐵🙈🙉🙊🐒🐔🐗🐺🐥🐣🐤🐦🐧🐴🦄🐝🐛🐌🐞🐜🕷🦂🦀🐍🐢🐠🐟🐅🐆🐊🐋🐬🐡🐃🐂🐄🐪🐫🐘🐐🐓🐁🐀🐖🐎🐑🐏🦃🕊🐕]") if emoji_caption and emoji == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if is_filter(msg, msg.media.caption) then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local arabic_caption = msg.media.caption:match("[\216-\219][\128-\191]") if arabic_caption and lock_arabic == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end if msg.text then local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') local _nl, real_digits = string.gsub(msg.text, '%d', '') if lock_spam == "yes" then if string.len(msg.text) > 2049 or ctrl_chars > 40 or real_digits > 2000 then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end if views =="yes" and msg.views_ ~= 0 then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Dd][Oo][Gg]/") or msg.text:match("[Tt].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if link_msg and lock_link == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local tag_msg = msg.text:match("@") or msg.text:match("#") if tag_msg and lock_tag == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local lock_reply = msg.reply_id if lock_reply and lock_reply == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local fosh_msg = msg.text:match("کص")or msg.text:match("کون")or msg.text:match("ممه")or msg.text:match("کیری")or msg.text:match("حرومی")or msg.text:match("ننه") or msg.text:match("کصده")or msg.text:match("کث")or msg.text:match("کسکش")or msg.text:match("کصکش")or msg.text:match("لاشی")or msg.text:match("ناموس")or msg.text:match("جنده")or msg.text:match("یتیم")or msg.text:match("خارکسده")or msg.text:match("مادرجنده")or msg.text:match("حرومزاده")or msg.text:match("خواهرجنده")or msg.text:match("خواهرتو")or msg.text:match("مادرتو")or msg.text:match("کونی")or msg.text:match("اوبی")or msg.text:match("لاشی")or msg.text:match("kir")or msg.text:match("kos")or msg.text:match("lashi") if fosh_msg and fosh == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local ads_msg =msg.text:match("شارژ") or msg.text:match("چالش") or msg.text:match("عضو چنل شید") or msg.text:match("ایرانسل") or msg.text:match("همراه اول") or msg.text:match("رایتل") or msg.text:match("جایزه نفر اول") or msg.text:match("جایزه نفر دوم") or msg.text:match("جایزه نفر سوم") or msg.text:match("پیج اینستا") or msg.text:match("instagram.com") or msg.text:match("www") or msg.text:match("t.me/") or msg.text:match("telegram.me/") or msg.text:match("چالش") or msg.text:match("کد شارژ") or msg.text:match("شارژ رایگان") or msg.text:match("پیج تلگرام") or msg.text:match("کانال تلگرامی ما") or msg.text:match("جایزه جایزه") or msg.text:match("پخش کنید") or msg.text:match("چالش داریم") or msg.text:match("تبلیغات") or msg.text:match("پذیرفتن تبلیغ") if ads_msg and ads == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local english_msg = msg.text:match("[ASDFGHJKLQWERTYUIOPZXCVBNMasdfghjklqwertyuiopzxcvbnm]") if english_msg and english == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local emoji_msg = msg.text:match("[😀😬😁😂😃😄😅☺️🙃🙂😊😉😇😆😋😌😍😘😗😙😚🤗😎🤓🤑😛😝😜😏😶😐😑😒🙄🤔😕😔😡😠😟😞😳🙁☹️😣😖😫😩😤😧😦😯😰😨😱😮😢😥😪😓😭😵😲💩💤😴🤕🤒😷🤐😈👿👹👺💀👻👽😽😼😻😹😸😺🤖🙀😿😾🙌🏻👏🏻👋🏻👍🏻👎🏻👊🏻✊🏻✌🏻👌🏻✋🏻👐🏻💪🏻🙏🏻☝🏻️👆🏻👇🏻👈🏻👉🏻🖕🏻🖐🏻🤘🏻🖖🏻✍🏻💅🏻👄👅👂🏻👃🏻👁👀👤👥👱🏻👩🏻👨🏻👧🏻👦🏻👶🏻🗣👴🏻👵🏻👲🏻🏃🏻🚶🏻💑👩‍❤️‍👩👨‍❤️‍👨💏👩‍❤️‍💋‍👩👨‍❤️‍💋‍👨👪👩‍👩‍👧‍👦👩‍👩‍👧👩‍👩‍👦👨‍👩‍👧‍👧👨‍👩‍👦‍👦👨‍👩‍👧‍👦👨‍👩‍👧👩‍👩‍👦‍👦👩‍👩‍👧‍👧👨‍👨‍👦👨‍👨‍👧👨‍👨‍👧‍👦👨‍👨‍👦‍👦👨‍👨‍👧‍👧👘👙👗👔👖👕👚💄💋👣👠👡👢👞🎒⛑👑🎓🎩👒👟👝👛👜💼👓🕶💍🌂🐶🐱🐭🐹🐰🐻🐼🐸🐽🐷🐮🦁🐯🐨🐙🐵🙈🙉🙊🐒🐔🐗🐺🐥🐣🐤🐦🐧🐴🦄🐝🐛🐌🐞🐜🕷🦂🦀🐍🐢🐠🐟🐅🐆🐊🐋🐬🐡🐃🐂🐄🐪🐫🐘🐐🐓🐁🐀🐖🐎🐑🐏🦃🕊🐕]") if emoji_msg and emoji == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if is_filter(msg, msg.text) then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end local arabic_msg = msg.text:match("[\216-\219][\128-\191]") if arabic_msg and lock_arabic == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.text:match("(.*)") and mute_text == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end if mute_all == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end if msg.content_.entities_ and msg.content_.entities_[0] then if msg.content_.entities_[0].ID == "MessageEntityMentionName" then if lock_mention == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end if msg.content_.entities_[0].ID == "MessageEntityUrl" or msg.content_.entities_[0].ID == "MessageEntityTextUrl" then if lock_webpage == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end if msg.content_.entities_[0].ID == "MessageEntityBold" or msg.content_.entities_[0].ID == "MessageEntityCode" or msg.content_.entities_[0].ID == "MessageEntityPre" or msg.content_.entities_[0].ID == "MessageEntityItalic" then if lock_markdown == "yes" then if is_channel then del_msg(chat, tonumber(msg.id)) elseif is_chat then kick_user(user, chat) end end end end if msg.to.type ~= 'pv' then if lock_flood == "yes" then local hash = 'user:'..user..':msgs' local msgs = tonumber(redis:get(hash) or 0) local NUM_MSG_MAX = 5 if data[tostring(chat)] then if data[tostring(chat)]['settings']['num_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(chat)]['settings']['num_msg_max']) end end if msgs > NUM_MSG_MAX then if is_mod(msg) then return end if msg.adduser and msg.from.id then return end if msg.from.username then user_name = "@"..msg.from.username else user_name = msg.from.first_name end if redis:get('sender:'..user..':flood') then return else del_msg(chat, msg.id) kick_user(user, chat) if not lang then tdcli.sendMessage(chat, msg.id, 0, "_User_ "..user_name.." `[ "..user.." ]` _has been_ *kicked* _because of_ *flooding*", 0, "md") elseif lang then tdcli.sendMessage(chat, msg.id, 0, "_کاربر_ "..user_name.." `[ "..user.." ]` _به دلیل ارسال پیام های مکرر اخراج شد_", 0, "md") end redis:setex('sender:'..user..':flood', 30, true) end end redis:setex(hash, TIME_CHECK, msgs+1) end end end end end return { patterns = {}, pre_process = pre_process } --End msg_checks.lua--
gpl-3.0
AntonioModer/skeletor
main.lua
1
3940
-- uncomment to run unit tests -- require 'skeletor.unittests.run' -- load the skeletor module with property adjustments local Skeletor = require('skeletor.skeletor') skeletor = Skeletor({ boundariesCalculate = true, boundariesShow = true, shapeShow = true }) opts = { x = 400, y = 200, angle = 0, speed = 100, sx = 1, sy = 1, scaleSpeed = 1, boneArmLeftAngle = 150, boneArmLeftLength = 80 } function love.load() skeletor:newSkeleton('man', {x = opts.x, y = opts.y, angle = opts.angle, sx = opts.sx, sy = opts.sy}) skeletor:newBone('man.head', { length = 50, angle = math.rad(110), -- you can use utils methods when loading skeletor. -- this should be changed as it isn't transparent. -- the shape is modified for a more headlike shape. shapeShape = utils:getEllipseVertices(0, 0, 1, 1, math.rad(0), 30), }) skeletor:newBone('man.head.body', {length = 100, angle = math.rad(90)}) skeletor:newBone('man.head.armRight', {length = 80, angle = math.rad(30)}) skeletor:newBone('man.head.armRight.forearm', {length = 40, angle = math.rad(300)}) skeletor:newBone('man.head.armLeft', {length = opts.boneArmLeftLength, angle = math.rad(opts.boneArmLeftAngle)}) skeletor:newBone('man.head.armLeft.forearm', {length = 40, angle = math.rad(30)}) skeletor:newBone('man.head.body.legRight', {length = 100, angle = math.rad(45)}) skeletor:newBone('man.head.body.legRight.foot', {length = 50, angle = math.rad(120)}) skeletor:newBone('man.head.body.legLeft', {length = 100, angle = math.rad(100)}) skeletor:newBone('man.head.body.legLeft.foot', {length = 50, angle = math.rad(160)}) end function love.update(dt) -- move skeleton sideways if love.keyboard.isDown('left') then opts.x = opts.x - (opts.speed*dt) elseif love.keyboard.isDown('right') then opts.x = opts.x + (opts.speed*dt) end skeletor:editSkeleton('man', {x = opts.x}) -- move skeleton up and down if love.keyboard.isDown('up') then opts.y = opts.y - (opts.speed*dt) elseif love.keyboard.isDown('down') then opts.y = opts.y + (opts.speed*dt) end skeletor:editSkeleton('man', {y = opts.y}) -- rotate skeleton if love.keyboard.isDown('q') then opts.angle = opts.angle + (opts.speed*dt) elseif love.keyboard.isDown('w') then opts.angle = opts.angle - (opts.speed*dt) end skeletor:editSkeleton('man', {angle = math.rad(opts.angle)}) -- mofify x scale if love.keyboard.isDown('a') then opts.sx = opts.sx + (opts.scaleSpeed*dt) elseif love.keyboard.isDown('s') then opts.sx = opts.sx - (opts.scaleSpeed*dt) end skeletor:editSkeleton('man', {sx = opts.sx}) -- mofify y scale if love.keyboard.isDown('z') then opts.sy = opts.sy + (opts.scaleSpeed*dt) elseif love.keyboard.isDown('x') then opts.sy = opts.sy - (opts.scaleSpeed*dt) end skeletor:editSkeleton('man', {sy = opts.sy}) -- rotate arm left bone if love.keyboard.isDown('e') then opts.boneArmLeftAngle = opts.boneArmLeftAngle + (opts.speed*dt) elseif love.keyboard.isDown('r') then opts.boneArmLeftAngle = opts.boneArmLeftAngle - (opts.speed*dt) end skeletor:editBone('man.head.armLeft', {angle = math.rad(opts.boneArmLeftAngle)}) -- mofify left arm's length if love.keyboard.isDown('d') then opts.boneArmLeftLength = opts.boneArmLeftLength - (opts.speed*dt) elseif love.keyboard.isDown('f') then opts.boneArmLeftLength = opts.boneArmLeftLength + (opts.speed*dt) end skeletor:editBone('man.head.armLeft', {length = opts.boneArmLeftLength}) end function love.draw() love.graphics.setColor({255, 255, 255}) love.graphics.print("- use arrows to move skeleton", 10, 10) love.graphics.print("- use q and w to rotate skeleton", 10, 30) love.graphics.print("- use a and s to modify x scaling", 10, 50) love.graphics.print("- use z and x to modify y scaling", 10, 70) love.graphics.print("- use e and r to rotate left arm", 10, 90) love.graphics.print("- use d and f to change the left arm's length", 10, 110) skeletor:draw() end
mit
CrazyEddieTK/Zero-K
LuaUI/Widgets/gui_chili_display_keys.lua
4
9831
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Display Keys 2", desc = "Displays the current key combination.", author = "GoogleFrog", date = "12 August 2015", license = "GNU GPL, v2 or later", layer = -10000, enabled = true } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- include("keysym.h.lua") local keyData, mouseData -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Options options_path = 'Settings/HUD Panels/Extras/Display Keys' options_order = { 'enable', 'keyReleaseTimeout', 'mouseReleaseTimeout', } options = { enable = { name = "Show input visualizer", desc = "Shows pressed key combinations and mouse buttons. Useful for video tutorials.", type = "bool", value = false, }, keyReleaseTimeout = { name = "Key Release Timeout", type = "number", value = 0.6, min = 0, max = 2, step = 0.025, }, mouseReleaseTimeout = { name = "Mouse Release Timeout", type = "number", value = 0.3, min = 0, max = 2, step = 0.025, }, } local panelColor = {1,1,1,0.8} local highlightColor = {1,0.7, 0, 1} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Window Creation local function InitializeDisplayLabelControl(name) local data = {} local screenWidth, screenHeight = Spring.GetWindowGeometry() local window = Chili.Window:New{ parent = screen0, dockable = true, name = name, padding = {0,0,0,0}, x = 0, y = 740, clientWidth = 380, clientHeight = 64, classname = "main_window_small_very_flat", draggable = false, resizable = false, tweakDraggable = true, tweakResizable = true, minimizable = false, OnMouseDown = ShowOptions, } local displayLabel = Chili.Label:New{ parent = window, x = 15, y = 10, right = 10, bottom = 12, caption = "", valign = "center", align = "center", autosize = false, font = { size = 36, outline = true, outlineWidth = 2, outlineWeight = 2, }, } local function UpdateWindow(val) displayLabel:SetCaption(val) end local function Dispose() window:Dispose() end local data = { UpdateWindow = UpdateWindow, Dispose = Dispose, } return data end local function InitializeMouseButtonControl(name) local window = Chili.Window:New{ parent = screen0, backgroundColor = {0, 0, 0, 0}, color = {0, 0, 0, 0}, dockable = true, name = name, padding = {0,0,0,0}, x = 60, y = 676, clientWidth = 260, clientHeight = 64, draggable = false, resizable = false, tweakDraggable = true, tweakResizable = true, minimizable = false, OnMouseDown = ShowOptions, } local leftPanel = Chili.Panel:New{ backgroundColor = panelColor, color = panelColor, parent = window, padding = {0,0,0,0}, y = 0, x = 0, right = "60%", bottom = 0, classname = "panel_button_rounded", dockable = false; draggable = false, resizable = false, OnMouseDown = ShowOptions, } local middlePanel = Chili.Panel:New{ backgroundColor = panelColor, color = panelColor, parent = window, padding = {0,0,0,0}, y = 0, x = "40%", right = "40%", bottom = 0, classname = "panel_button_rounded", dockable = false; draggable = false, resizable = false, OnMouseDown = ShowOptions, } local rightPanel = Chili.Panel:New{ backgroundColor = panelColor, color = panelColor, parent = window, padding = {0,0,0,0}, y = 0, x = "60%", right = 0, bottom = 0, classname = "panel_button_rounded", dockable = false; draggable = false, resizable = false, OnMouseDown = ShowOptions, } local leftLabel = Chili.Label:New{ parent = leftPanel, x = 15, y = 10, right = 10, bottom = 12, caption = "", align = "center", autosize = false, font = { size = 36, outline = true, outlineWidth = 2, outlineWeight = 2, }, } local rightLabel = Chili.Label:New{ parent = rightPanel, x = 15, y = 10, right = 10, bottom = 12, caption = "", align = "center", autosize = false, font = { size = 36, outline = true, outlineWidth = 2, outlineWeight = 2, }, } local function UpdateWindow(val) if val == 1 then leftPanel.backgroundColor = highlightColor leftPanel.color = highlightColor middlePanel.backgroundColor = panelColor middlePanel.color = panelColor rightPanel.backgroundColor = panelColor rightPanel.color = panelColor leftLabel:SetCaption("Left") rightLabel:SetCaption("") elseif val == 2 then leftPanel.backgroundColor = panelColor leftPanel.color = panelColor middlePanel.backgroundColor = highlightColor middlePanel.color = highlightColor rightPanel.backgroundColor = panelColor rightPanel.color = panelColor leftLabel:SetCaption("") rightLabel:SetCaption("") elseif val == 3 then leftPanel.backgroundColor = panelColor leftPanel.color = panelColor middlePanel.backgroundColor = panelColor middlePanel.color = panelColor rightPanel.backgroundColor = highlightColor rightPanel.color = highlightColor leftLabel:SetCaption("") rightLabel:SetCaption("Right") else leftPanel.backgroundColor = panelColor leftPanel.color = panelColor middlePanel.backgroundColor = panelColor middlePanel.color = panelColor rightPanel.backgroundColor = panelColor rightPanel.color = panelColor leftLabel:SetCaption("") rightLabel:SetCaption("") end leftPanel:Invalidate() middlePanel:Invalidate() rightPanel:Invalidate() window:Invalidate() end local function Dispose() window:Dispose() end local data = { UpdateWindow = UpdateWindow, Dispose = Dispose, } return data end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- General Functions local function DoDelayedUpdate(data, dt) if not data.updateTime then return end data.updateTime = data.updateTime - dt if data.updateTime > 0 then return end data.UpdateWindow(data.updateData) data.updateTime = false end function widget:Update(dt) if mouseData.pressed then local x, y, lmb, mmb, rmb = Spring.GetMouseState() if not (lmb or mmb or rmb) then mouseData.pressed = false mouseData.updateData = false mouseData.updateTime = options.mouseReleaseTimeout.value end end DoDelayedUpdate(keyData, dt) DoDelayedUpdate(mouseData, dt) end function widget:Initialize() Chili = WG.Chili screen0 = Chili.Screen0 options.enable.OnChange(options.enable) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Keys local function IsMod(key) return key == 32 or key >= 128 end local onlyMods = false local function Conc(str, add, val) if val then if onlyMods then return (str or "") .. (str and " + " or "") .. add else return (str or "") .. add .. " + " end else return str end end function widget:KeyPress(key, modifier, isRepeat) onlyMods = IsMod(key) and not keyData.pressed local keyText = Conc(false, "Space", modifier.meta) keyText = Conc(keyText, "Ctrl", modifier.ctrl) keyText = Conc(keyText, "Alt", modifier.alt) keyText = Conc(keyText, "Shift", modifier.shift) if not onlyMods then if not keyData.pressed then keyData.pressedString = string.upper(tostring(string.char(key))) end keyData.pressed = true keyText = (keyText or "") .. keyData.pressedString end keyData.UpdateWindow(keyText or "") keyData.updateData = keyText or "" keyData.updateTime = false end function widget:KeyRelease(key, modifier, isRepeat) if not IsMod(key) then keyData.pressed = false end onlyMods = not keyData.pressed local keyText = Conc(false, "Space", modifier.meta) keyText = Conc(keyText, "Ctrl", modifier.ctrl) keyText = Conc(keyText, "Alt", modifier.alt) keyText = Conc(keyText, "Shift", modifier.shift) if not onlyMods then keyText = (keyText or "") .. keyData.pressedString end keyData.updateData = keyText or "" keyData.updateTime = options.keyReleaseTimeout.value end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Mouse function widget:MousePress(x, y, button) mouseData.pressed = true mouseData.UpdateWindow(button) mouseData.updateTime = false end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local callins = {"Update", "KeyPress", "KeyRelease", "MousePress"} local function Enable() if not mouseData then mouseData = InitializeMouseButtonControl("Mouse Display") end if not keyData then keyData = InitializeDisplayLabelControl("Key Display") end for _, callin in pairs(callins) do widgetHandler:UpdateCallIn(callin) end end local function Disable() if keyData then keyData.Dispose() keyData = nil end if mouseData then mouseData.Dispose() mouseData = nil end for _, callin in pairs(callins) do widgetHandler:RemoveCallIn(callin) end end options.enable.OnChange = function(self) if self.value then Enable() else Disable() end end function widget:Shutdown() Disable() end
gpl-2.0
wincent/command-t
lua/wincent/commandt/init.lua
1
16335
-- SPDX-FileCopyrightText: Copyright 2010-present Greg Hurrell and contributors. -- SPDX-License-Identifier: BSD-2-Clause local concat = require('wincent.commandt.private.concat') local contains = require('wincent.commandt.private.contains') local copy = require('wincent.commandt.private.copy') local is_integer = require('wincent.commandt.private.is_integer') local is_table = require('wincent.commandt.private.is_table') local keys = require('wincent.commandt.private.keys') local merge = require('wincent.commandt.private.merge') local commandt = {} local open = function(buffer, command) buffer = vim.fn.fnameescape(buffer) local is_visible = require('wincent.commandt.private.buffer_visible')(buffer) if is_visible then -- In order to be useful, `:sbuffer` needs `vim.o.switchbuf = 'usetab'`. vim.cmd('sbuffer ' .. buffer) else vim.cmd(command .. ' ' .. buffer) end end local help_opened = false local options_spec = { kind = 'table', keys = { always_show_dot_files = { kind = 'boolean' }, finders = { kind = 'table', values = { kind = 'table', keys = { candidates = { kind = { one_of = { { kind = 'function' }, { kind = 'list', of = { kind = 'string' }, }, }, }, optional = true, }, command = { kind = { one_of = { { kind = 'function' }, { kind = 'string' }, }, }, optional = true, }, fallback = { kind = 'boolean', optional = true }, open = { kind = 'function', optional = true }, }, }, meta = function(t) local errors = {} if is_table(t) then for key, value in pairs(t) do if value.candidates and value.command then value.command = nil table.insert(errors, string.format('%s: `candidates` and `command` should not both be set', key)) elseif value.candidates == nil and value.command == nil then value.candidates = {} table.insert(errors, string.format('%s: either `candidates` or `command` should be set', key)) end end end return errors end, }, height = { kind = 'number' }, ignore_case = { kind = 'boolean', optional = true, }, mappings = { kind = 'table', keys = { i = { kind = 'table', values = { kind = 'string' }, }, n = { kind = 'table', values = { kind = 'string' }, }, }, }, margin = { kind = 'number', meta = function(context) if not is_integer(context.margin) or context.margin < 0 then context.margin = 0 return { '`margin` must be a non-negative integer' } end end, }, never_show_dot_files = { kind = 'boolean' }, order = { kind = { one_of = { 'forward', 'reverse' } } }, position = { kind = { one_of = { 'bottom', 'center', 'top' } } }, open = { kind = 'function' }, scanners = { kind = 'table', keys = { git = { kind = 'table', keys = { submodules = { kind = 'boolean', optional = true, }, untracked = { kind = 'boolean', optional = true, }, }, meta = function(t) if is_table(t) and t.submodules == true and t.untracked == true then t.submodules = false t.untracked = false return { '`submodules` and `untracked` should not both be true' } end end, optional = true, }, }, }, selection_highlight = { kind = 'string' }, smart_case = { kind = 'boolean', optional = true, }, threads = { kind = 'number', optional = true, }, }, meta = function(t) if t.always_show_dot_files == true and t.never_show_dot_files == true then t.always_show_dot_files = false t.never_show_dot_files = false return { '`always_show_dot_files` and `never_show_dot_files` should not both be true' } end end, } local default_options = { always_show_dot_files = false, finders = { -- Returns the list of paths currently loaded into buffers. buffer = { candidates = function() -- TODO: don't include unlisted buffers unless user wants them (need some way -- for them to signal that) local handles = vim.api.nvim_list_bufs() local paths = {} for _, handle in ipairs(handles) do if vim.api.nvim_buf_is_loaded(handle) then local name = vim.api.nvim_buf_get_name(handle) if name ~= '' then local relative = vim.fn.fnamemodify(name, ':~:.') table.insert(paths, relative) end end end return paths end, }, find = { command = function(directory) if vim.startswith(directory, './') then directory = directory:sub(3, -1) end if directory ~= '' and directory ~= '.' then directory = vim.fn.shellescape(directory) end local drop = 0 if directory == '' or directory == '.' then -- Drop 2 characters because `find` will prefix every result with "./", -- making it look like a dotfile. directory = '.' drop = 2 -- TODO: decide what to do if somebody passes '..' or similar, because that -- will also make the results get filtered out as though they were dotfiles. -- I may end up needing to do some fancy, separate micromanagement of -- prefixes and let the matcher operate on paths without prefixes. end -- TODO: support max depth, dot directory filter etc local command = 'find -L ' .. directory .. ' -type f -print0 2> /dev/null' return command, drop end, fallback = true, }, git = { command = function(directory, options) if directory ~= '' then directory = vim.fn.shellescape(directory) end local command = 'git ls-files --exclude-standard --cached -z' if options.submodules then command = command .. ' --recurse-submodules' elseif options.untracked then command = command .. ' --others' end if directory ~= '' then command = command .. ' -- ' .. directory end command = command .. ' 2> /dev/null' return command end, fallback = true, }, help = { candidates = function() -- Neovim doesn't provide an easy way to get a list of all help tags. -- `tagfiles()` only shows the tagfiles for the current buffer, so you need -- to already be in a buffer of `'buftype'` `help` for that to work. -- Likewise, `taglist()` only shows tags that apply to the current file -- type, and `:tag` has the same restriction. -- -- So, we look for "doc/tags" files at every location in the `'runtimepath'` -- and try to manually parse it. local helptags = {} local tagfiles = vim.api.nvim_get_runtime_file('doc/tags', true) for _, tagfile in ipairs(tagfiles) do if vim.fn.filereadable(tagfile) then for _, tag in ipairs(vim.fn.readfile(tagfile)) do local _, _, tag_text = tag:find('^%s*(%S+)%s+') if tag_text ~= nil then table.insert(helptags, tag_text) end end end end -- TODO: memoize this? (ie. add `memoize = true`)? return helptags end, open = function(item, kind) local command = 'help' if kind == 'split' then -- Split is the default, so for this finder, we abuse "split" mode to do -- the opposite of the default, using tricks noted in `:help help-curwin`. -- -- See also: https://github.com/vim/vim/issues/7534 if not help_opened then vim.cmd([[ silent noautocmd keepalt help silent noautocmd keepalt helpclose ]]) help_opened = true end if vim.fn.empty(vim.fn.getcompletion(item, 'help')) == 0 then vim.cmd('silent noautocmd keepalt edit ' .. vim.o.helpfile) end elseif kind == 'tabedit' then command = 'tab help' elseif kind == 'vsplit' then command = 'vertical help' end -- E434 "Can't find tag pattern" is innocuous, so swallow it. For more -- context, see: https://github.com/autozimu/LanguageClient-neovim/pull/731 vim.cmd('try | ' .. command .. ' ' .. item .. ' | catch /E434/ | endtry') end, }, line = { candidates = function() local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false) local result = {} for i, line in ipairs(lines) do -- Skip blank/empty lines. if not line:match('^%s*$') then table.insert(result, vim.trim(line) .. ':' .. tostring(i)) end end return result end, open = function(item) -- Extract line number from (eg) "some line contents:100". local suffix = string.find(item, '%d+$') local index = tonumber(item:sub(suffix)) vim.api.nvim_win_set_cursor(0, { index, 0 }) end, }, rg = { command = function(directory) if vim.startswith(directory, './') then directory = directory:sub(3, -1) end if directory ~= '' and directory ~= '.' then directory = vim.fn.shellescape(directory) end local drop = 0 if directory == '.' then drop = 2 end local command = 'rg --files --null' if #directory > 0 then command = command .. ' ' .. directory end command = command .. ' 2> /dev/null' return command, drop end, fallback = true, }, }, height = 15, ignore_case = nil, -- If nil, will infer from Neovim's `'ignorecase'`. -- Note that because of the way we merge mappings recursively, you can _add_ -- or _replace_ a mapping easily, but to _remove_ it you have to assign it to -- `false` (`nil` won't work, because Lua will just skip over it). mappings = { i = { ['<C-a>'] = '<Home>', ['<C-c>'] = 'close', ['<C-e>'] = '<End>', ['<C-h>'] = '<Left>', ['<C-j>'] = 'select_next', ['<C-k>'] = 'select_previous', ['<C-l>'] = '<Right>', ['<C-n>'] = 'select_next', ['<C-p>'] = 'select_previous', ['<C-s>'] = 'open_split', ['<C-t>'] = 'open_tab', ['<C-v>'] = 'open_vsplit', ['<C-w>'] = '<C-S-w>', ['<CR>'] = 'open', ['<Down>'] = 'select_next', ['<Up>'] = 'select_previous', }, n = { ['<C-a>'] = '<Home>', ['<C-c>'] = 'close', ['<C-e>'] = '<End>', ['<C-h>'] = '<Left>', ['<C-j>'] = 'select_next', ['<C-k>'] = 'select_previous', ['<C-l>'] = '<Right>', ['<C-n>'] = 'select_next', ['<C-p>'] = 'select_previous', ['<C-s>'] = 'open_split', ['<C-t>'] = 'open_tab', ['<C-u>'] = 'clear', -- Not needed in insert mode. ['<C-v>'] = 'open_vsplit', ['<CR>'] = 'open', ['<Down>'] = 'select_next', ['<Esc>'] = 'close', -- Only in normal mode. ['<Up>'] = 'select_previous', ['H'] = 'select_first', -- Only in normal mode. ['M'] = 'select_middle', -- Only in normal mode. ['G'] = 'select_last', -- Only in normal mode. ['L'] = 'select_last', -- Only in normal mode. ['gg'] = 'select_first', -- Only in normal mode. ['j'] = 'select_next', -- Only in normal mode. ['k'] = 'select_previous', -- Only in normal mode. }, }, margin = 10, never_show_dot_files = false, order = 'forward', -- 'forward', 'reverse'. position = 'center', -- 'bottom', 'center', 'top'. open = open, scanners = { git = { submodules = true, untracked = false, }, }, selection_highlight = 'PMenuSel', smart_case = nil, -- If nil, will infer from Neovim's `'smartcase'`. threads = nil, -- Let heuristic apply. } -- Have to add some of these explicitly otherwise the ones with `nil` defaults -- won't come through (eg. `ignore_case` etc). local allowed_options = concat(keys(default_options), { 'ignore_case', 'smart_case', 'threads', }) commandt.default_options = function() return copy(default_options) end commandt.file_finder = function(directory) directory = vim.trim(directory) if directory == '' then directory = '.' end local ui = require('wincent.commandt.private.ui') local options = commandt.options() local finder = require('wincent.commandt.private.finders.file')(directory, options) ui.show(finder, merge(options, { name = 'file' })) end commandt.finder = function(name, directory) local options = commandt.options() local config = options.finders[name] if config == nil then error('commandt.finder(): no finder registered with name ' .. tostring(name)) end if directory ~= nil then directory = vim.trim(directory) end local finder = nil options.open = function(item, kind) if config.open then config.open(item, kind) else commandt.open(item, kind) end end if config.candidates then finder = require('wincent.commandt.private.finders.list')(directory, config.candidates, options) else finder = require('wincent.commandt.private.finders.command')(directory, config.command, options) end if config.fallback then finder.fallback = require('wincent.commandt.private.finders.fallback')(finder, directory, options) end local ui = require('wincent.commandt.private.ui') ui.show(finder, merge(options, { name = name })) end -- "Smart" open that will switch to an already open window containing the -- specified `buffer`, if one exists; otherwise, it will open a new window using -- `command` (which should be one of `edit`, `tabedit`, `split`, or `vsplit`). commandt.open = open local _options = copy(default_options) commandt.options = function() return copy(_options) end commandt.setup = function(options) local errors = {} if vim.g.CommandTPreferredImplementation == 'ruby' then table.insert(errors, '`commandt.setup()` was called, but `g:CommandTPreferredImplementation` is set to "ruby"') else vim.g.CommandTPreferredImplementation = 'lua' end if options == nil then options = {} elseif not is_table(options) then table.insert(errors, '`commandt.setup() expects a table of options but received ' .. type(options)) options = {} end _options = merge(_options, options) -- Inferred from Neovim settings if not explicitly set. if _options.ignore_case == nil then _options.ignore_case = vim.o.ignorecase end if _options.smart_case == nil then _options.smart_case = vim.o.smartcase end local validate = require('wincent.commandt.private.validate') errors = merge(errors, validate('', nil, _options, options_spec, default_options)) if not pcall(function() local lib = require('wincent.commandt.private.lib') -- We can require it. lib.epoch() -- We can use it. end) then table.insert(errors, 'unable to load and use C library - run `:checkhealth wincent.commandt`') end if #errors > 0 then table.insert(errors, 1, 'commandt.setup():') for i, message in ipairs(errors) do local indent = i == 1 and '' or ' ' errors[i] = { indent .. message .. '\n', 'WarningMsg' } end vim.api.nvim_echo(errors, true, {}) end end commandt.watchman_finder = function(directory) directory = vim.trim(directory) local ui = require('wincent.commandt.private.ui') local options = commandt.options() local finder = require('wincent.commandt.private.finders.watchman')(directory, options) ui.show(finder, merge(options, { name = 'watchman' })) end return commandt
bsd-2-clause
andywingo/snabbswitch
src/dasm_x86.lua
11
74171
------------------------------------------------------------------------------ -- DynASM x86/x64 module. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ local x64 = rawget(_G, "x64") --rawget so it works with strict.lua -- Module information: local _info = { arch = x64 and "x64" or "x86", description = "DynASM x86/x64 module", version = "1.4.0_luamode", vernum = 10400, release = "2015-10-18", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, unpack, setmetatable = assert, unpack or table.unpack, setmetatable local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local find, match, gmatch, gsub = _s.find, _s.match, _s.gmatch, _s.gsub local concat, sort, remove = table.concat, table.sort, table.remove local bit = bit or require("bit") local band, bxor, shl, shr = bit.band, bit.bxor, bit.lshift, bit.rshift -- Inherited tables and callbacks. local g_opt, g_arch, g_map_def local wline, werror, wfatal, wwarn -- Global flag to generate Lua code instead of C code. local luamode -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { -- int arg, 1 buffer pos: "DISP", "IMM_S", "IMM_B", "IMM_W", "IMM_D", "IMM_WB", "IMM_DB", -- action arg (1 byte), int arg, 1 buffer pos (reg/num): "VREG", "SPACE", -- ptrdiff_t arg, 1 buffer pos (address): !x64 "SETLABEL", "REL_A", -- action arg (1 byte) or int arg, 2 buffer pos (link, offset): "REL_LG", "REL_PC", -- action arg (1 byte) or int arg, 1 buffer pos (link): "IMM_LG", "IMM_PC", -- action arg (1 byte) or int arg, 1 buffer pos (offset): "LABEL_LG", "LABEL_PC", -- action arg (1 byte), 1 buffer pos (offset): "ALIGN", -- action args (2 bytes), no buffer pos. "EXTERN", -- action arg (1 byte), no buffer pos. "ESC", -- no action arg, no buffer pos. "MARK", -- action arg (1 byte), no buffer pos, terminal action: "SECTION", -- no args, no buffer pos, terminal action: "STOP" } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number (dynamically generated below). local map_action = {} -- First action number. Everything below does not need to be escaped. local actfirst = 256-#action_names -- Action list buffer and string (only used to remove dupes). local actlist, actstr -- Argument list for next dasm_put(). local actargs -- Current number of section buffer positions for dasm_put(). local secpos local function init_actionlist() actlist = {} actstr = "" actargs = { 0 } -- Start with offset 0 into the action list. secpos = 1 end -- VREG kind encodings, pre-shifted by 5 bits. local map_vreg = { ["modrm.rm.m"] = 0x00, ["modrm.rm.r"] = 0x20, ["opcode"] = 0x20, ["sib.base"] = 0x20, ["sib.index"] = 0x40, ["modrm.reg"] = 0x80, ["vex.v"] = 0xa0, ["imm.hi"] = 0xc0, } -- Current number of VREG actions contributing to REX/VEX shrinkage. local vreg_shrink_count = 0 ------------------------------------------------------------------------------ -- Compute action numbers for action names. for n,name in ipairs(action_names) do local num = actfirst + n - 1 map_action[name] = num end -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist local last = actlist[nn] or 255 actlist[nn] = nil -- Remove last byte. if nn == 0 then nn = 1 end if luamode then out:write("local ", name, " = ffi.new('const uint8_t[", nn, "]', {\n") else out:write("static const unsigned char ", name, "[", nn, "] = {\n") end local s = " " for n,b in ipairs(actlist) do s = s..b.."," if #s >= 75 then assert(out:write(s, "\n")) s = " " end end if luamode then out:write(s, last, "\n})\n\n") -- Add last byte back. else out:write(s, last, "\n};\n\n") -- Add last byte back. end end ------------------------------------------------------------------------------ -- Add byte to action list. local function wputxb(n) assert(n >= 0 and n <= 255 and n % 1 == 0, "byte out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, a, num) wputxb(assert(map_action[action], "bad action name `"..action.."'")) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Optionally add a VREG action. local function wvreg(kind, vreg, psz, sk, defer) if not vreg then return end waction("VREG", vreg) local b = assert(map_vreg[kind], "bad vreg kind `"..vreg.."'") if b < (sk or 0) then vreg_shrink_count = vreg_shrink_count + 1 end if not defer then b = b + vreg_shrink_count * 8 vreg_shrink_count = 0 end wputxb(b + (psz or 0)) end -- Add call to embedded DynASM C code. local function wcall(func, args) if luamode then wline(format("dasm.%s(Dst, %s)", func, concat(args, ", ")), true) else wline(format("dasm_%s(Dst, %s);", func, concat(args, ", ")), true) end end -- Delete duplicate action list chunks. A tad slow, but so what. local function dedupechunk(offset) local al, as = actlist, actstr local chunk = char(unpack(al, offset+1, #al)) local orig = find(as, chunk, 1, true) if orig then actargs[1] = orig-1 -- Replace with original offset. for i=offset+1,#al do al[i] = nil end -- Kill dupe. else actstr = as..chunk end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) local offset = actargs[1] if #actlist == offset then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. dedupechunk(offset) wcall("put", actargs) -- Add call to dasm_put(). actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped byte. local function wputb(n) if n >= actfirst then waction("ESC") end -- Need to escape byte. wputxb(n) end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global, map_global local globals_meta = { __index = function(t, name) if not match(name, "^[%a_][%w_@]*$") then werror("bad global label") end local n = next_global if n > 246 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end} local function init_map_global() next_global = 10 map_global = setmetatable({}, globals_meta) end -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=10,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end if luamode then local n = 0 for i=10,next_global-1 do out:write("local ", prefix, gsub(t[i], "@.*", ""), "\t= ", n, "\n") n = n + 1 end out:write("local ", prefix, "_MAX\t= ", n, "\n") --for compatibility with the C protocol out:write("local DASM_MAXGLOBAL\t= ", n, "\n") else out:write("enum {\n") for i=10,next_global-1 do out:write(" ", prefix, gsub(t[i], "@.*", ""), ",\n") end out:write(" ", prefix, "_MAX\n};\n") end end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end if luamode then out:write("local ", name, " = {\n") for i=10,next_global-1 do out:write(" ", i == 10 and "[0] = " or "", "\"", t[i], "\",\n") end out:write("}\n") else out:write("static const char *const ", name, "[] = {\n") for i=10,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern, map_extern local extern_meta = { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n < -256 then werror("too many extern labels") end next_extern = n - 1 t[name] = n return n end} local function init_map_extern() next_extern = -1 map_extern = setmetatable({}, extern_meta) end -- Dump extern labels. local function dumpexterns(out, lvl) local t = {} for name, n in pairs(map_extern) do t[-n] = name end out:write("Extern labels:\n") for i=1,-next_extern-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) local t = {} for name, n in pairs(map_extern) do t[-n] = name end if luamode then out:write("local ", name, " = {\n") for i=1,-next_extern-1 do out:write(i==1 and "[0] = " or "", "\"", t[i], "\",\n") end out:write("}\n") else out:write("static const char *const ", name, "[] = {\n") for i=1,-next_extern-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end end ------------------------------------------------------------------------------ -- Arch-specific maps. local map_archdef = {} -- Ext. register name -> int. name. local map_reg_rev = {} -- Int. register name -> ext. name. local map_reg_num = {} -- Int. register name -> register number. local map_reg_opsize = {} -- Int. register name -> operand size. local map_reg_valid_base = {} -- Int. register name -> valid base register? local map_reg_valid_index = {} -- Int. register name -> valid index register? local map_reg_needrex = {} -- Int. register name -> need rex vs. no rex. local reg_list = {} -- Canonical list of int. register names. local map_type -- Type name -> { ctype, reg } local ctypenum -- Type number (for _PTx macros). local function init_map_type() map_type = {} ctypenum = 0 end local addrsize = x64 and "q" or "d" -- Size for address operands. -- Helper functions to fill register maps. local function mkrmap(sz, cl, names) local cname = format("@%s", sz) reg_list[#reg_list+1] = cname map_archdef[cl] = cname map_reg_rev[cname] = cl map_reg_num[cname] = -1 map_reg_opsize[cname] = sz if sz == addrsize or sz == "d" then map_reg_valid_base[cname] = true map_reg_valid_index[cname] = true end if names then for n,name in ipairs(names) do local iname = format("@%s%x", sz, n-1) reg_list[#reg_list+1] = iname map_archdef[name] = iname map_reg_rev[iname] = name map_reg_num[iname] = n-1 map_reg_opsize[iname] = sz if sz == "b" and n > 4 then map_reg_needrex[iname] = false end if sz == addrsize or sz == "d" then map_reg_valid_base[iname] = true map_reg_valid_index[iname] = true end end end for i=0,(x64 and sz ~= "f") and 15 or 7 do local needrex = sz == "b" and i > 3 local iname = format("@%s%x%s", sz, i, needrex and "R" or "") if needrex then map_reg_needrex[iname] = true end local name if sz == "o" or sz == "y" then name = format("%s%d", cl, i) elseif sz == "f" then name = format("st%d", i) else name = format("r%d%s", i, sz == addrsize and "" or sz) end map_archdef[name] = iname if not map_reg_rev[iname] then reg_list[#reg_list+1] = iname map_reg_rev[iname] = name map_reg_num[iname] = i map_reg_opsize[iname] = sz if sz == addrsize or sz == "d" then map_reg_valid_base[iname] = true map_reg_valid_index[iname] = true end end end reg_list[#reg_list+1] = "" end -- Integer registers (qword, dword, word and byte sized). if x64 then mkrmap("q", "Rq", {"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi"}) end mkrmap("d", "Rd", {"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"}) mkrmap("w", "Rw", {"ax", "cx", "dx", "bx", "sp", "bp", "si", "di"}) mkrmap("b", "Rb", {"al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"}) map_reg_valid_index[map_archdef.esp] = false if x64 then map_reg_valid_index[map_archdef.rsp] = false end if x64 then map_reg_needrex[map_archdef.Rb] = true end map_archdef["Ra"] = "@"..addrsize -- FP registers (internally tword sized, but use "f" as operand size). mkrmap("f", "Rf") -- SSE registers (oword sized, but qword and dword accessible). mkrmap("o", "xmm") -- AVX registers (yword sized, but oword, qword and dword accessible). mkrmap("y", "ymm") -- Operand size prefixes to codes. local map_opsize = { byte = "b", word = "w", dword = "d", qword = "q", oword = "o", yword = "y", tword = "t", aword = addrsize, } -- Operand size code to number. local map_opsizenum = { b = 1, w = 2, d = 4, q = 8, o = 16, y = 32, t = 10, } -- Operand size code to name. local map_opsizename = { b = "byte", w = "word", d = "dword", q = "qword", o = "oword", y = "yword", t = "tword", f = "fpword", } -- Valid index register scale factors. local map_xsc = { ["1"] = 0, ["2"] = 1, ["4"] = 2, ["8"] = 3, } -- Condition codes. local map_cc = { o = 0, no = 1, b = 2, nb = 3, e = 4, ne = 5, be = 6, nbe = 7, s = 8, ns = 9, p = 10, np = 11, l = 12, nl = 13, le = 14, nle = 15, c = 2, nae = 2, nc = 3, ae = 3, z = 4, nz = 5, na = 6, a = 7, pe = 10, po = 11, nge = 12, ge = 13, ng = 14, g = 15, } -- Reverse defines for registers. function _M.revdef(s) return gsub(s, "@%w+", map_reg_rev) end -- Dump register names and numbers local function dumpregs(out) out:write("Register names, sizes and internal numbers:\n") for _,reg in ipairs(reg_list) do if reg == "" then out:write("\n") else local name = map_reg_rev[reg] local num = map_reg_num[reg] local opsize = map_opsizename[map_reg_opsize[reg]] out:write(format(" %-5s %-8s %s\n", name, opsize, num < 0 and "(variable)" or num)) end end end ------------------------------------------------------------------------------ -- Put action for label arg (IMM_LG, IMM_PC, REL_LG, REL_PC). local function wputlabel(aprefix, imm, num) if type(imm) == "number" then if imm < 0 then waction("EXTERN") wputxb(aprefix == "IMM_" and 0 or 1) imm = -imm-1 else waction(aprefix.."LG", nil, num); end wputxb(imm) else waction(aprefix.."PC", imm, num) end end -- Put signed byte or arg. local function wputsbarg(n) if type(n) == "number" then if n < -128 or n > 127 then werror("signed immediate byte out of range") end if n < 0 then n = n + 256 end wputb(n) else waction("IMM_S", n) end end -- Put unsigned byte or arg. local function wputbarg(n) if type(n) == "number" then if n < 0 or n > 255 then werror("unsigned immediate byte out of range") end wputb(n) else waction("IMM_B", n) end end -- Put unsigned word or arg. local function wputwarg(n) if type(n) == "number" then if shr(n, 16) ~= 0 then werror("unsigned immediate word out of range") end wputb(band(n, 255)); wputb(shr(n, 8)); else waction("IMM_W", n) end end -- Put signed or unsigned dword or arg. local function wputdarg(n) local tn = type(n) if tn == "number" then wputb(band(n, 255)) wputb(band(shr(n, 8), 255)) wputb(band(shr(n, 16), 255)) wputb(shr(n, 24)) elseif tn == "table" then wputlabel("IMM_", n[1], 1) else waction("IMM_D", n) end end -- Put operand-size dependent number or arg (defaults to dword). local function wputszarg(sz, n) if not sz or sz == "d" or sz == "q" then wputdarg(n) elseif sz == "w" then wputwarg(n) elseif sz == "b" then wputbarg(n) elseif sz == "s" then wputsbarg(n) else werror("bad operand size") end end -- Put multi-byte opcode with operand-size dependent modifications. local function wputop(sz, op, rex, vex, vregr, vregxb) local psz, sk = 0, nil if vex then local tail if vex.m == 1 and band(rex, 11) == 0 then if x64 and vregxb then sk = map_vreg["modrm.reg"] else wputb(0xc5) tail = shl(bxor(band(rex, 4), 4), 5) psz = 3 end end if not tail then wputb(0xc4) wputb(shl(bxor(band(rex, 7), 7), 5) + vex.m) tail = shl(band(rex, 8), 4) psz = 4 end local reg, vreg = 0, nil if vex.v then reg = vex.v.reg if not reg then werror("bad vex operand") end if reg < 0 then reg = 0; vreg = vex.v.vreg end end if sz == "y" or vex.l then tail = tail + 4 end wputb(tail + shl(bxor(reg, 15), 3) + vex.p) wvreg("vex.v", vreg) rex = 0 if op >= 256 then werror("bad vex opcode") end else if rex ~= 0 then if not x64 then werror("bad operand size") end elseif (vregr or vregxb) and x64 then rex = 0x10 sk = map_vreg["vex.v"] end end local r if sz == "w" then wputb(102) end -- Needs >32 bit numbers, but only for crc32 eax, word [ebx] if op >= 4294967296 then r = op%4294967296 wputb((op-r)/4294967296) op = r end if op >= 16777216 then wputb(shr(op, 24)); op = band(op, 0xffffff) end if op >= 65536 then if rex ~= 0 then local opc3 = band(op, 0xffff00) if opc3 == 0x0f3a00 or opc3 == 0x0f3800 then wputb(64 + band(rex, 15)); rex = 0; psz = 2 end end wputb(shr(op, 16)); op = band(op, 0xffff); psz = psz + 1 end if op >= 256 then local b = shr(op, 8) if b == 15 and rex ~= 0 then wputb(64 + band(rex, 15)); rex = 0; psz = 2 end wputb(b); op = band(op, 255); psz = psz + 1 end if rex ~= 0 then wputb(64 + band(rex, 15)); psz = 2 end if sz == "b" then op = op - 1 end wputb(op) return psz, sk end -- Put ModRM or SIB formatted byte. local function wputmodrm(m, s, rm, vs, vrm) assert(m < 4 and s < 16 and rm < 16, "bad modrm operands") wputb(shl(m, 6) + shl(band(s, 7), 3) + band(rm, 7)) end -- Put ModRM/SIB plus optional displacement. local function wputmrmsib(t, imark, s, vsreg, psz, sk) local vreg, vxreg local reg, xreg = t.reg, t.xreg if reg and reg < 0 then reg = 0; vreg = t.vreg end if xreg and xreg < 0 then xreg = 0; vxreg = t.vxreg end if s < 0 then s = 0 end -- Register mode. if sub(t.mode, 1, 1) == "r" then wputmodrm(3, s, reg) wvreg("modrm.reg", vsreg, psz+1, sk, vreg) wvreg("modrm.rm.r", vreg, psz+1, sk) return end local disp = t.disp local tdisp = type(disp) -- No base register? if not reg then local riprel = false if xreg then -- Indexed mode with index register only. -- [xreg*xsc+disp] -> (0, s, esp) (xsc, xreg, ebp) wputmodrm(0, s, 4) if imark == "I" then waction("MARK") end wvreg("modrm.reg", vsreg, psz+1, sk, vxreg) wputmodrm(t.xsc, xreg, 5) wvreg("sib.index", vxreg, psz+2, sk) else -- Pure 32 bit displacement. if x64 and tdisp ~= "table" then wputmodrm(0, s, 4) -- [disp] -> (0, s, esp) (0, esp, ebp) wvreg("modrm.reg", vsreg, psz+1, sk) if imark == "I" then waction("MARK") end wputmodrm(0, 4, 5) else riprel = x64 wputmodrm(0, s, 5) -- [disp|rip-label] -> (0, s, ebp) wvreg("modrm.reg", vsreg, psz+1, sk) if imark == "I" then waction("MARK") end end end if riprel then -- Emit rip-relative displacement. if match("UWSiI", imark) then werror("NYI: rip-relative displacement followed by immediate") end -- The previous byte in the action buffer cannot be 0xe9 or 0x80-0x8f. wputlabel("REL_", disp[1], 2) else wputdarg(disp) end return end local m if tdisp == "number" then -- Check displacement size at assembly time. if disp == 0 and band(reg, 7) ~= 5 then -- [ebp] -> [ebp+0] (in SIB, too) if not vreg then m = 0 end -- Force DISP to allow [Rd(5)] -> [ebp+0] elseif disp >= -128 and disp <= 127 then m = 1 else m = 2 end elseif tdisp == "table" then m = 2 end -- Index register present or esp as base register: need SIB encoding. if xreg or band(reg, 7) == 4 then wputmodrm(m or 2, s, 4) -- ModRM. if m == nil or imark == "I" then waction("MARK") end wvreg("modrm.reg", vsreg, psz+1, sk, vxreg or vreg) wputmodrm(t.xsc or 0, xreg or 4, reg) -- SIB. wvreg("sib.index", vxreg, psz+2, sk, vreg) wvreg("sib.base", vreg, psz+2, sk) else wputmodrm(m or 2, s, reg) -- ModRM. if (imark == "I" and (m == 1 or m == 2)) or (m == nil and (vsreg or vreg)) then waction("MARK") end wvreg("modrm.reg", vsreg, psz+1, sk, vreg) wvreg("modrm.rm.m", vreg, psz+1, sk) end -- Put displacement. if m == 1 then wputsbarg(disp) elseif m == 2 then wputdarg(disp) elseif m == nil then waction("DISP", disp) end end ------------------------------------------------------------------------------ -- Return human-readable operand mode string. local function opmodestr(op, args) local m = {} for i=1,#args do local a = args[i] m[#m+1] = sub(a.mode, 1, 1)..(a.opsize or "?") end return op.." "..concat(m, ",") end -- Convert number to valid integer or nil. local function toint(expr) local n = tonumber(expr) if n then if n % 1 ~= 0 or n < -2147483648 or n > 4294967295 then werror("bad integer number `"..expr.."'") end return n end end -- Parse immediate expression. local function immexpr(expr) -- &expr (pointer) if sub(expr, 1, 1) == "&" then return "iPJ", format(luamode and "(%s)" or "(ptrdiff_t)(%s)", sub(expr,2)) end local prefix = sub(expr, 1, 2) -- =>expr (pc label reference) if prefix == "=>" then return "iJ", sub(expr, 3) end -- ->name (global label reference) if prefix == "->" then return "iJ", map_global[sub(expr, 3)] end -- [<>][1-9] (local label reference) local dir, lnum = match(expr, "^([<>])([1-9])$") if dir then -- Fwd: 247-255, Bkwd: 1-9. return "iJ", lnum + (dir == ">" and 246 or 0) end local extname = match(expr, "^extern%s+(%S+)$") if extname then return "iJ", map_extern[extname] end -- expr (interpreted as immediate) return "iI", expr end -- Parse displacement expression: +-num, +-expr, +-opsize*num local function dispexpr(expr) local disp = expr == "" and 0 or toint(expr) if disp then return disp end local c, dispt = match(expr, "^([+-])%s*(.+)$") if c == "+" then expr = dispt elseif not c then werror("bad displacement expression `"..expr.."'") end local opsize, tailops = match(dispt, "^(%w+)%s*%*%s*(.+)$") local ops, imm = map_opsize[opsize], toint(tailops) if ops and imm then if c == "-" then imm = -imm end return imm*map_opsizenum[ops] end local mode, iexpr = immexpr(dispt) if mode == "iJ" then if c == "-" then werror("cannot invert label reference") end return { iexpr } end return expr -- Need to return original signed expression. end -- Parse register or type expression. local function rtexpr(expr) if not expr then return end local tname, ovreg = match(expr, "^([%w_]+):(@[%w_]+)$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg local rnum = map_reg_num[reg] if not rnum then werror("type `"..(tname or expr).."' needs a register override") end if not map_reg_valid_base[reg] then werror("bad base register override `"..(map_reg_rev[reg] or reg).."'") end return reg, rnum, tp end return expr, map_reg_num[expr] end -- Parse operand and return { mode, opsize, reg, xreg, xsc, disp, imm }. local function parseoperand(param) local t = {} local expr = param local opsize, tailops = match(param, "^(%w+)%s*(.+)$") if opsize then t.opsize = map_opsize[opsize] if t.opsize then expr = tailops end end local br = match(expr, "^%[%s*(.-)%s*%]$") repeat if br then t.mode = "xm" -- [disp] t.disp = toint(br) if t.disp then t.mode = x64 and "xm" or "xmO" break end -- [reg...] local tp local reg, tailr = match(br, "^([@%w_:]+)%s*(.*)$") reg, t.reg, tp = rtexpr(reg) if not t.reg then -- [expr] t.mode = x64 and "xm" or "xmO" t.disp = dispexpr("+"..br) break end if t.reg == -1 then t.vreg, tailr = match(tailr, "^(%b())(.*)$") if not t.vreg then werror("bad variable register expression") end end -- [xreg*xsc] or [xreg*xsc+-disp] or [xreg*xsc+-expr] local xsc, tailsc = match(tailr, "^%*%s*([1248])%s*(.*)$") if xsc then if not map_reg_valid_index[reg] then werror("bad index register `"..map_reg_rev[reg].."'") end t.xsc = map_xsc[xsc] t.xreg = t.reg t.vxreg = t.vreg t.reg = nil t.vreg = nil t.disp = dispexpr(tailsc) break end if not map_reg_valid_base[reg] then werror("bad base register `"..map_reg_rev[reg].."'") end -- [reg] or [reg+-disp] t.disp = toint(tailr) or (tailr == "" and 0) if t.disp then break end -- [reg+xreg...] local xreg, tailx = match(tailr, "^+%s*([@%w_:]+)%s*(.*)$") xreg, t.xreg, tp = rtexpr(xreg) if not t.xreg then -- [reg+-expr] t.disp = dispexpr(tailr) break end if not map_reg_valid_index[xreg] then werror("bad index register `"..map_reg_rev[xreg].."'") end if t.xreg == -1 then t.vxreg, tailx = match(tailx, "^(%b())(.*)$") if not t.vxreg then werror("bad variable register expression") end end -- [reg+xreg*xsc...] local xsc, tailsc = match(tailx, "^%*%s*([1248])%s*(.*)$") if xsc then t.xsc = map_xsc[xsc] tailx = tailsc end -- [...] or [...+-disp] or [...+-expr] t.disp = dispexpr(tailx) else -- imm or opsize*imm local imm = toint(expr) if not imm and sub(expr, 1, 1) == "*" and t.opsize then imm = toint(sub(expr, 2)) if imm then imm = imm * map_opsizenum[t.opsize] t.opsize = nil end end if imm then if t.opsize then werror("bad operand size override") end local m = "i" if imm == 1 then m = m.."1" end if imm >= 4294967168 and imm <= 4294967295 then imm = imm-4294967296 end if imm >= -128 and imm <= 127 then m = m.."S" end t.imm = imm t.mode = m break end local tp local reg, tailr = match(expr, "^([@%w_:]+)%s*(.*)$") reg, t.reg, tp = rtexpr(reg) if t.reg then if t.reg == -1 then t.vreg, tailr = match(tailr, "^(%b())(.*)$") if not t.vreg then werror("bad variable register expression") end end -- reg if tailr == "" then if t.opsize then werror("bad operand size override") end t.opsize = map_reg_opsize[reg] if t.opsize == "f" then t.mode = t.reg == 0 and "fF" or "f" else if reg == "@w4" or (x64 and reg == "@d4") then wwarn("bad idea, try again with `"..(x64 and "rsp'" or "esp'")) end t.mode = t.reg == 0 and "rmR" or (reg == "@b1" and "rmC" or "rm") end t.needrex = map_reg_needrex[reg] break end -- type[idx], type[idx].field, type->field -> [reg+offset_expr] if not tp then werror("bad operand `"..param.."'") end t.mode = "xm" if luamode then t.disp = tp.ctypefmt(tailr) else t.disp = format(tp.ctypefmt, tailr) end else t.mode, t.imm = immexpr(expr) if sub(t.mode, -1) == "J" then if t.opsize and t.opsize ~= addrsize then werror("bad operand size override") end t.opsize = addrsize end end end until true return t end ------------------------------------------------------------------------------ -- x86 Template String Description -- =============================== -- -- Each template string is a list of [match:]pattern pairs, -- separated by "|". The first match wins. No match means a -- bad or unsupported combination of operand modes or sizes. -- -- The match part and the ":" is omitted if the operation has -- no operands. Otherwise the first N characters are matched -- against the mode strings of each of the N operands. -- -- The mode string for each operand type is (see parseoperand()): -- Integer register: "rm", +"R" for eax, ax, al, +"C" for cl -- FP register: "f", +"F" for st0 -- Index operand: "xm", +"O" for [disp] (pure offset) -- Immediate: "i", +"S" for signed 8 bit, +"1" for 1, -- +"I" for arg, +"P" for pointer -- Any: +"J" for valid jump targets -- -- So a match character "m" (mixed) matches both an integer register -- and an index operand (to be encoded with the ModRM/SIB scheme). -- But "r" matches only a register and "x" only an index operand -- (e.g. for FP memory access operations). -- -- The operand size match string starts right after the mode match -- characters and ends before the ":". "dwb" or "qdwb" is assumed, if empty. -- The effective data size of the operation is matched against this list. -- -- If only the regular "b", "w", "d", "q", "t" operand sizes are -- present, then all operands must be the same size. Unspecified sizes -- are ignored, but at least one operand must have a size or the pattern -- won't match (use the "byte", "word", "dword", "qword", "tword" -- operand size overrides. E.g.: mov dword [eax], 1). -- -- If the list has a "1" or "2" prefix, the operand size is taken -- from the respective operand and any other operand sizes are ignored. -- If the list contains only ".", all operand sizes are ignored. -- If the list has a "/" prefix, the concatenated (mixed) operand sizes -- are compared to the match. -- -- E.g. "rrdw" matches for either two dword registers or two word -- registers. "Fx2dq" matches an st0 operand plus an index operand -- pointing to a dword (float) or qword (double). -- -- Every character after the ":" is part of the pattern string: -- Hex chars are accumulated to form the opcode (left to right). -- "n" disables the standard opcode mods -- (otherwise: -1 for "b", o16 prefix for "w", rex.w for "q") -- "X" Force REX.W. -- "r"/"R" adds the reg. number from the 1st/2nd operand to the opcode. -- "m"/"M" generates ModRM/SIB from the 1st/2nd operand. -- The spare 3 bits are either filled with the last hex digit or -- the result from a previous "r"/"R". The opcode is restored. -- "u" Use VEX encoding, vvvv unused. -- "v"/"V" Use VEX encoding, vvvv from 1st/2nd operand (the operand is -- removed from the list used by future characters). -- "L" Force VEX.L -- -- All of the following characters force a flush of the opcode: -- "o"/"O" stores a pure 32 bit disp (offset) from the 1st/2nd operand. -- "s" stores a 4 bit immediate from the last register operand, -- followed by 4 zero bits. -- "S" stores a signed 8 bit immediate from the last operand. -- "U" stores an unsigned 8 bit immediate from the last operand. -- "W" stores an unsigned 16 bit immediate from the last operand. -- "i" stores an operand sized immediate from the last operand. -- "I" dito, but generates an action code to optionally modify -- the opcode (+2) for a signed 8 bit immediate. -- "J" generates one of the REL action codes from the last operand. -- ------------------------------------------------------------------------------ -- Template strings for x86 instructions. Ordered by first opcode byte. -- Unimplemented opcodes (deliberate omissions) are marked with *. local map_op = { -- 00-05: add... -- 06: *push es -- 07: *pop es -- 08-0D: or... -- 0E: *push cs -- 0F: two byte opcode prefix -- 10-15: adc... -- 16: *push ss -- 17: *pop ss -- 18-1D: sbb... -- 1E: *push ds -- 1F: *pop ds -- 20-25: and... es_0 = "26", -- 27: *daa -- 28-2D: sub... cs_0 = "2E", -- 2F: *das -- 30-35: xor... ss_0 = "36", -- 37: *aaa -- 38-3D: cmp... ds_0 = "3E", -- 3F: *aas inc_1 = x64 and "m:FF0m" or "rdw:40r|m:FF0m", dec_1 = x64 and "m:FF1m" or "rdw:48r|m:FF1m", push_1 = (x64 and "rq:n50r|rw:50r|mq:nFF6m|mw:FF6m" or "rdw:50r|mdw:FF6m").."|S.:6AS|ib:n6Ai|i.:68i", pop_1 = x64 and "rq:n58r|rw:58r|mq:n8F0m|mw:8F0m" or "rdw:58r|mdw:8F0m", -- 60: *pusha, *pushad, *pushaw -- 61: *popa, *popad, *popaw -- 62: *bound rdw,x -- 63: x86: *arpl mw,rw movsxd_2 = x64 and "rm/qd:63rM", fs_0 = "64", gs_0 = "65", o16_0 = "66", a16_0 = not x64 and "67" or nil, a32_0 = x64 and "67", -- 68: push idw -- 69: imul rdw,mdw,idw -- 6A: push ib -- 6B: imul rdw,mdw,S -- 6C: *insb -- 6D: *insd, *insw -- 6E: *outsb -- 6F: *outsd, *outsw -- 70-7F: jcc lb -- 80: add... mb,i -- 81: add... mdw,i -- 82: *undefined -- 83: add... mdw,S test_2 = "mr:85Rm|rm:85rM|Ri:A9ri|mi:F70mi", -- 86: xchg rb,mb -- 87: xchg rdw,mdw -- 88: mov mb,r -- 89: mov mdw,r -- 8A: mov r,mb -- 8B: mov r,mdw -- 8C: *mov mdw,seg lea_2 = "rx1dq:8DrM", -- 8E: *mov seg,mdw -- 8F: pop mdw nop_0 = "90", xchg_2 = "Rrqdw:90R|rRqdw:90r|rm:87rM|mr:87Rm", cbw_0 = "6698", cwde_0 = "98", cdqe_0 = "4898", cwd_0 = "6699", cdq_0 = "99", cqo_0 = "4899", -- 9A: *call iw:idw wait_0 = "9B", fwait_0 = "9B", pushf_0 = "9C", pushfd_0 = not x64 and "9C", pushfq_0 = x64 and "9C", popf_0 = "9D", popfd_0 = not x64 and "9D", popfq_0 = x64 and "9D", sahf_0 = "9E", lahf_0 = "9F", mov_2 = "OR:A3o|RO:A1O|mr:89Rm|rm:8BrM|rib:nB0ri|ridw:B8ri|mi:C70mi", movsb_0 = "A4", movsw_0 = "66A5", movsd_0 = "A5", cmpsb_0 = "A6", cmpsw_0 = "66A7", cmpsd_0 = "A7", -- A8: test Rb,i -- A9: test Rdw,i stosb_0 = "AA", stosw_0 = "66AB", stosd_0 = "AB", lodsb_0 = "AC", lodsw_0 = "66AD", lodsd_0 = "AD", scasb_0 = "AE", scasw_0 = "66AF", scasd_0 = "AF", -- B0-B7: mov rb,i -- B8-BF: mov rdw,i -- C0: rol... mb,i -- C1: rol... mdw,i ret_1 = "i.:nC2W", ret_0 = "C3", -- C4: *les rdw,mq -- C5: *lds rdw,mq -- C6: mov mb,i -- C7: mov mdw,i -- C8: *enter iw,ib leave_0 = "C9", -- CA: *retf iw -- CB: *retf int3_0 = "CC", int_1 = "i.:nCDU", into_0 = "CE", -- CF: *iret -- D0: rol... mb,1 -- D1: rol... mdw,1 -- D2: rol... mb,cl -- D3: rol... mb,cl -- D4: *aam ib -- D5: *aad ib -- D6: *salc -- D7: *xlat -- D8-DF: floating point ops -- E0: *loopne -- E1: *loope -- E2: *loop -- E3: *jcxz, *jecxz -- E4: *in Rb,ib -- E5: *in Rdw,ib -- E6: *out ib,Rb -- E7: *out ib,Rdw call_1 = x64 and "mq:nFF2m|J.:E8nJ" or "md:FF2m|J.:E8J", jmp_1 = x64 and "mq:nFF4m|J.:E9nJ" or "md:FF4m|J.:E9J", -- short: EB -- EA: *jmp iw:idw -- EB: jmp ib -- EC: *in Rb,dx -- ED: *in Rdw,dx -- EE: *out dx,Rb -- EF: *out dx,Rdw lock_0 = "F0", int1_0 = "F1", repne_0 = "F2", repnz_0 = "F2", rep_0 = "F3", repe_0 = "F3", repz_0 = "F3", -- F4: *hlt cmc_0 = "F5", -- F6: test... mb,i; div... mb -- F7: test... mdw,i; div... mdw clc_0 = "F8", stc_0 = "F9", -- FA: *cli cld_0 = "FC", std_0 = "FD", -- FE: inc... mb -- FF: inc... mdw -- misc ops not_1 = "m:F72m", neg_1 = "m:F73m", mul_1 = "m:F74m", imul_1 = "m:F75m", div_1 = "m:F76m", idiv_1 = "m:F77m", imul_2 = "rmqdw:0FAFrM|rIqdw:69rmI|rSqdw:6BrmS|riqdw:69rmi", imul_3 = "rmIqdw:69rMI|rmSqdw:6BrMS|rmiqdw:69rMi", movzx_2 = "rm/db:0FB6rM|rm/qb:|rm/wb:0FB6rM|rm/dw:0FB7rM|rm/qw:", movsx_2 = "rm/db:0FBErM|rm/qb:|rm/wb:0FBErM|rm/dw:0FBFrM|rm/qw:", bswap_1 = "rqd:0FC8r", bsf_2 = "rmqdw:0FBCrM", bsr_2 = "rmqdw:0FBDrM", bt_2 = "mrqdw:0FA3Rm|miqdw:0FBA4mU", btc_2 = "mrqdw:0FBBRm|miqdw:0FBA7mU", btr_2 = "mrqdw:0FB3Rm|miqdw:0FBA6mU", bts_2 = "mrqdw:0FABRm|miqdw:0FBA5mU", shld_3 = "mriqdw:0FA4RmU|mrC/qq:0FA5Rm|mrC/dd:|mrC/ww:", shrd_3 = "mriqdw:0FACRmU|mrC/qq:0FADRm|mrC/dd:|mrC/ww:", rdtsc_0 = "0F31", -- P1+ rdpmc_0 = "0F33", -- P6+ cpuid_0 = "0FA2", -- P1+ -- floating point ops fst_1 = "ff:DDD0r|xd:D92m|xq:nDD2m", fstp_1 = "ff:DDD8r|xd:D93m|xq:nDD3m|xt:DB7m", fld_1 = "ff:D9C0r|xd:D90m|xq:nDD0m|xt:DB5m", fpop_0 = "DDD8", -- Alias for fstp st0. fist_1 = "xw:nDF2m|xd:DB2m", fistp_1 = "xw:nDF3m|xd:DB3m|xq:nDF7m", fild_1 = "xw:nDF0m|xd:DB0m|xq:nDF5m", fxch_0 = "D9C9", fxch_1 = "ff:D9C8r", fxch_2 = "fFf:D9C8r|Fff:D9C8R", fucom_1 = "ff:DDE0r", fucom_2 = "Fff:DDE0R", fucomp_1 = "ff:DDE8r", fucomp_2 = "Fff:DDE8R", fucomi_1 = "ff:DBE8r", -- P6+ fucomi_2 = "Fff:DBE8R", -- P6+ fucomip_1 = "ff:DFE8r", -- P6+ fucomip_2 = "Fff:DFE8R", -- P6+ fcomi_1 = "ff:DBF0r", -- P6+ fcomi_2 = "Fff:DBF0R", -- P6+ fcomip_1 = "ff:DFF0r", -- P6+ fcomip_2 = "Fff:DFF0R", -- P6+ fucompp_0 = "DAE9", fcompp_0 = "DED9", fldenv_1 = "x.:D94m", fnstenv_1 = "x.:D96m", fstenv_1 = "x.:9BD96m", fldcw_1 = "xw:nD95m", fstcw_1 = "xw:n9BD97m", fnstcw_1 = "xw:nD97m", fstsw_1 = "Rw:n9BDFE0|xw:n9BDD7m", fnstsw_1 = "Rw:nDFE0|xw:nDD7m", fclex_0 = "9BDBE2", fnclex_0 = "DBE2", fnop_0 = "D9D0", -- D9D1-D9DF: unassigned fchs_0 = "D9E0", fabs_0 = "D9E1", -- D9E2: unassigned -- D9E3: unassigned ftst_0 = "D9E4", fxam_0 = "D9E5", -- D9E6: unassigned -- D9E7: unassigned fld1_0 = "D9E8", fldl2t_0 = "D9E9", fldl2e_0 = "D9EA", fldpi_0 = "D9EB", fldlg2_0 = "D9EC", fldln2_0 = "D9ED", fldz_0 = "D9EE", -- D9EF: unassigned f2xm1_0 = "D9F0", fyl2x_0 = "D9F1", fptan_0 = "D9F2", fpatan_0 = "D9F3", fxtract_0 = "D9F4", fprem1_0 = "D9F5", fdecstp_0 = "D9F6", fincstp_0 = "D9F7", fprem_0 = "D9F8", fyl2xp1_0 = "D9F9", fsqrt_0 = "D9FA", fsincos_0 = "D9FB", frndint_0 = "D9FC", fscale_0 = "D9FD", fsin_0 = "D9FE", fcos_0 = "D9FF", -- SSE, SSE2 andnpd_2 = "rmo:660F55rM", andnps_2 = "rmo:0F55rM", andpd_2 = "rmo:660F54rM", andps_2 = "rmo:0F54rM", fxsave_1 = "x.:0FAE0m", fxrstor_1 = "x.:0FAE1m", clflush_1 = "x.:0FAE7m", cmppd_3 = "rmio:660FC2rMU", cmpps_3 = "rmio:0FC2rMU", cmpsd_3 = "rrio:F20FC2rMU|rxi/oq:", cmpss_3 = "rrio:F30FC2rMU|rxi/od:", comisd_2 = "rro:660F2FrM|rx/oq:", comiss_2 = "rro:0F2FrM|rx/od:", cvtdq2pd_2 = "rro:F30FE6rM|rx/oq:", cvtdq2ps_2 = "rmo:0F5BrM", cvtpd2dq_2 = "rmo:F20FE6rM", cvtpd2ps_2 = "rmo:660F5ArM", cvtpi2pd_2 = "rx/oq:660F2ArM", cvtpi2ps_2 = "rx/oq:0F2ArM", cvtps2dq_2 = "rmo:660F5BrM", cvtps2pd_2 = "rro:0F5ArM|rx/oq:", cvtsd2si_2 = "rr/do:F20F2DrM|rr/qo:|rx/dq:|rxq:", cvtsd2ss_2 = "rro:F20F5ArM|rx/oq:", cvtsi2sd_2 = "rm/od:F20F2ArM|rm/oq:F20F2ArXM", cvtsi2ss_2 = "rm/od:F30F2ArM|rm/oq:F30F2ArXM", cvtss2sd_2 = "rro:F30F5ArM|rx/od:", cvtss2si_2 = "rr/do:F30F2DrM|rr/qo:|rxd:|rx/qd:", cvttpd2dq_2 = "rmo:660FE6rM", cvttps2dq_2 = "rmo:F30F5BrM", cvttsd2si_2 = "rr/do:F20F2CrM|rr/qo:|rx/dq:|rxq:", cvttss2si_2 = "rr/do:F30F2CrM|rr/qo:|rxd:|rx/qd:", fxsave_1 = "x.:0FAE0m", fxrstor_1 = "x.:0FAE1m", ldmxcsr_1 = "xd:0FAE2m", lfence_0 = "0FAEE8", maskmovdqu_2 = "rro:660FF7rM", mfence_0 = "0FAEF0", movapd_2 = "rmo:660F28rM|mro:660F29Rm", movaps_2 = "rmo:0F28rM|mro:0F29Rm", movd_2 = "rm/od:660F6ErM|rm/oq:660F6ErXM|mr/do:660F7ERm|mr/qo:", movdqa_2 = "rmo:660F6FrM|mro:660F7FRm", movdqu_2 = "rmo:F30F6FrM|mro:F30F7FRm", movhlps_2 = "rro:0F12rM", movhpd_2 = "rx/oq:660F16rM|xr/qo:n660F17Rm", movhps_2 = "rx/oq:0F16rM|xr/qo:n0F17Rm", movlhps_2 = "rro:0F16rM", movlpd_2 = "rx/oq:660F12rM|xr/qo:n660F13Rm", movlps_2 = "rx/oq:0F12rM|xr/qo:n0F13Rm", movmskpd_2 = "rr/do:660F50rM", movmskps_2 = "rr/do:0F50rM", movntdq_2 = "xro:660FE7Rm", movnti_2 = "xrqd:0FC3Rm", movntpd_2 = "xro:660F2BRm", movntps_2 = "xro:0F2BRm", movq_2 = "rro:F30F7ErM|rx/oq:|xr/qo:n660FD6Rm", movsd_2 = "rro:F20F10rM|rx/oq:|xr/qo:nF20F11Rm", movss_2 = "rro:F30F10rM|rx/od:|xr/do:F30F11Rm", movupd_2 = "rmo:660F10rM|mro:660F11Rm", movups_2 = "rmo:0F10rM|mro:0F11Rm", orpd_2 = "rmo:660F56rM", orps_2 = "rmo:0F56rM", pause_0 = "F390", pextrw_3 = "rri/do:660FC5rMU|xri/wo:660F3A15nRmU", -- Mem op: SSE4.1 only. pinsrw_3 = "rri/od:660FC4rMU|rxi/ow:", pmovmskb_2 = "rr/do:660FD7rM", prefetchnta_1 = "xb:n0F180m", prefetcht0_1 = "xb:n0F181m", prefetcht1_1 = "xb:n0F182m", prefetcht2_1 = "xb:n0F183m", pshufd_3 = "rmio:660F70rMU", pshufhw_3 = "rmio:F30F70rMU", pshuflw_3 = "rmio:F20F70rMU", pslld_2 = "rmo:660FF2rM|rio:660F726mU", pslldq_2 = "rio:660F737mU", psllq_2 = "rmo:660FF3rM|rio:660F736mU", psllw_2 = "rmo:660FF1rM|rio:660F716mU", psrad_2 = "rmo:660FE2rM|rio:660F724mU", psraw_2 = "rmo:660FE1rM|rio:660F714mU", psrld_2 = "rmo:660FD2rM|rio:660F722mU", psrldq_2 = "rio:660F733mU", psrlq_2 = "rmo:660FD3rM|rio:660F732mU", psrlw_2 = "rmo:660FD1rM|rio:660F712mU", rcpps_2 = "rmo:0F53rM", rcpss_2 = "rro:F30F53rM|rx/od:", rsqrtps_2 = "rmo:0F52rM", rsqrtss_2 = "rmo:F30F52rM", sfence_0 = "0FAEF8", shufpd_3 = "rmio:660FC6rMU", shufps_3 = "rmio:0FC6rMU", stmxcsr_1 = "xd:0FAE3m", ucomisd_2 = "rro:660F2ErM|rx/oq:", ucomiss_2 = "rro:0F2ErM|rx/od:", unpckhpd_2 = "rmo:660F15rM", unpckhps_2 = "rmo:0F15rM", unpcklpd_2 = "rmo:660F14rM", unpcklps_2 = "rmo:0F14rM", xorpd_2 = "rmo:660F57rM", xorps_2 = "rmo:0F57rM", -- SSE3 ops fisttp_1 = "xw:nDF1m|xd:DB1m|xq:nDD1m", addsubpd_2 = "rmo:660FD0rM", addsubps_2 = "rmo:F20FD0rM", haddpd_2 = "rmo:660F7CrM", haddps_2 = "rmo:F20F7CrM", hsubpd_2 = "rmo:660F7DrM", hsubps_2 = "rmo:F20F7DrM", lddqu_2 = "rxo:F20FF0rM", movddup_2 = "rmo:F20F12rM", movshdup_2 = "rmo:F30F16rM", movsldup_2 = "rmo:F30F12rM", -- SSSE3 ops pabsb_2 = "rmo:660F381CrM", pabsd_2 = "rmo:660F381ErM", pabsw_2 = "rmo:660F381DrM", palignr_3 = "rmio:660F3A0FrMU", phaddd_2 = "rmo:660F3802rM", phaddsw_2 = "rmo:660F3803rM", phaddw_2 = "rmo:660F3801rM", phsubd_2 = "rmo:660F3806rM", phsubsw_2 = "rmo:660F3807rM", phsubw_2 = "rmo:660F3805rM", pmaddubsw_2 = "rmo:660F3804rM", pmulhrsw_2 = "rmo:660F380BrM", pshufb_2 = "rmo:660F3800rM", psignb_2 = "rmo:660F3808rM", psignd_2 = "rmo:660F380ArM", psignw_2 = "rmo:660F3809rM", -- SSE4.1 ops blendpd_3 = "rmio:660F3A0DrMU", blendps_3 = "rmio:660F3A0CrMU", blendvpd_3 = "rmRo:660F3815rM", blendvps_3 = "rmRo:660F3814rM", dppd_3 = "rmio:660F3A41rMU", dpps_3 = "rmio:660F3A40rMU", extractps_3 = "mri/do:660F3A17RmU|rri/qo:660F3A17RXmU", insertps_3 = "rrio:660F3A41rMU|rxi/od:", movntdqa_2 = "rxo:660F382ArM", mpsadbw_3 = "rmio:660F3A42rMU", packusdw_2 = "rmo:660F382BrM", pblendvb_3 = "rmRo:660F3810rM", pblendw_3 = "rmio:660F3A0ErMU", pcmpeqq_2 = "rmo:660F3829rM", pextrb_3 = "rri/do:660F3A14nRmU|rri/qo:|xri/bo:", pextrd_3 = "mri/do:660F3A16RmU", pextrq_3 = "mri/qo:660F3A16RmU", -- pextrw is SSE2, mem operand is SSE4.1 only phminposuw_2 = "rmo:660F3841rM", pinsrb_3 = "rri/od:660F3A20nrMU|rxi/ob:", pinsrd_3 = "rmi/od:660F3A22rMU", pinsrq_3 = "rmi/oq:660F3A22rXMU", pmaxsb_2 = "rmo:660F383CrM", pmaxsd_2 = "rmo:660F383DrM", pmaxud_2 = "rmo:660F383FrM", pmaxuw_2 = "rmo:660F383ErM", pminsb_2 = "rmo:660F3838rM", pminsd_2 = "rmo:660F3839rM", pminud_2 = "rmo:660F383BrM", pminuw_2 = "rmo:660F383ArM", pmovsxbd_2 = "rro:660F3821rM|rx/od:", pmovsxbq_2 = "rro:660F3822rM|rx/ow:", pmovsxbw_2 = "rro:660F3820rM|rx/oq:", pmovsxdq_2 = "rro:660F3825rM|rx/oq:", pmovsxwd_2 = "rro:660F3823rM|rx/oq:", pmovsxwq_2 = "rro:660F3824rM|rx/od:", pmovzxbd_2 = "rro:660F3831rM|rx/od:", pmovzxbq_2 = "rro:660F3832rM|rx/ow:", pmovzxbw_2 = "rro:660F3830rM|rx/oq:", pmovzxdq_2 = "rro:660F3835rM|rx/oq:", pmovzxwd_2 = "rro:660F3833rM|rx/oq:", pmovzxwq_2 = "rro:660F3834rM|rx/od:", pmuldq_2 = "rmo:660F3828rM", pmulld_2 = "rmo:660F3840rM", ptest_2 = "rmo:660F3817rM", roundpd_3 = "rmio:660F3A09rMU", roundps_3 = "rmio:660F3A08rMU", roundsd_3 = "rrio:660F3A0BrMU|rxi/oq:", roundss_3 = "rrio:660F3A0ArMU|rxi/od:", -- SSE4.2 ops crc32_2 = "rmqd:F20F38F1rM|rm/dw:66F20F38F1rM|rm/db:F20F38F0rM|rm/qb:", pcmpestri_3 = "rmio:660F3A61rMU", pcmpestrm_3 = "rmio:660F3A60rMU", pcmpgtq_2 = "rmo:660F3837rM", pcmpistri_3 = "rmio:660F3A63rMU", pcmpistrm_3 = "rmio:660F3A62rMU", popcnt_2 = "rmqdw:F30FB8rM", -- SSE4a extrq_2 = "rro:660F79rM", extrq_3 = "riio:660F780mUU", insertq_2 = "rro:F20F79rM", insertq_4 = "rriio:F20F78rMUU", lzcnt_2 = "rmqdw:F30FBDrM", movntsd_2 = "xr/qo:nF20F2BRm", movntss_2 = "xr/do:F30F2BRm", -- popcnt is also in SSE4.2 -- AES-NI aesdec_2 = "rmo:660F38DErM", aesdeclast_2 = "rmo:660F38DFrM", aesenc_2 = "rmo:660F38DCrM", aesenclast_2 = "rmo:660F38DDrM", aesimc_2 = "rmo:660F38DBrM", aeskeygenassist_3 = "rmio:660F3ADFrMU", pclmulqdq_3 = "rmio:660F3A44rMU", -- AVX FP ops vaddsubpd_3 = "rrmoy:660FVD0rM", vaddsubps_3 = "rrmoy:F20FVD0rM", vandpd_3 = "rrmoy:660FV54rM", vandps_3 = "rrmoy:0FV54rM", vandnpd_3 = "rrmoy:660FV55rM", vandnps_3 = "rrmoy:0FV55rM", vblendpd_4 = "rrmioy:660F3AV0DrMU", vblendps_4 = "rrmioy:660F3AV0CrMU", vblendvpd_4 = "rrmroy:660F3AV4BrMs", vblendvps_4 = "rrmroy:660F3AV4ArMs", vbroadcastf128_2 = "rx/yo:660F38u1ArM", vcmppd_4 = "rrmioy:660FVC2rMU", vcmpps_4 = "rrmioy:0FVC2rMU", vcmpsd_4 = "rrrio:F20FVC2rMU|rrxi/ooq:", vcmpss_4 = "rrrio:F30FVC2rMU|rrxi/ood:", vcomisd_2 = "rro:660Fu2FrM|rx/oq:", vcomiss_2 = "rro:0Fu2FrM|rx/od:", vcvtdq2pd_2 = "rro:F30FuE6rM|rx/oq:|rm/yo:", vcvtdq2ps_2 = "rmoy:0Fu5BrM", vcvtpd2dq_2 = "rmoy:F20FuE6rM", vcvtpd2ps_2 = "rmoy:660Fu5ArM", vcvtps2dq_2 = "rmoy:660Fu5BrM", vcvtps2pd_2 = "rro:0Fu5ArM|rx/oq:|rm/yo:", vcvtsd2si_2 = "rr/do:F20Fu2DrM|rx/dq:|rr/qo:|rxq:", vcvtsd2ss_3 = "rrro:F20FV5ArM|rrx/ooq:", vcvtsi2sd_3 = "rrm/ood:F20FV2ArM|rrm/ooq:F20FVX2ArM", vcvtsi2ss_3 = "rrm/ood:F30FV2ArM|rrm/ooq:F30FVX2ArM", vcvtss2sd_3 = "rrro:F30FV5ArM|rrx/ood:", vcvtss2si_2 = "rr/do:F30Fu2DrM|rxd:|rr/qo:|rx/qd:", vcvttpd2dq_2 = "rmo:660FuE6rM|rm/oy:660FuLE6rM", vcvttps2dq_2 = "rmoy:F30Fu5BrM", vcvttsd2si_2 = "rr/do:F20Fu2CrM|rx/dq:|rr/qo:|rxq:", vcvttss2si_2 = "rr/do:F30Fu2CrM|rxd:|rr/qo:|rx/qd:", vdppd_4 = "rrmio:660F3AV41rMU", vdpps_4 = "rrmioy:660F3AV40rMU", vextractf128_3 = "mri/oy:660F3AuL19RmU", vextractps_3 = "mri/do:660F3Au17RmU", vhaddpd_3 = "rrmoy:660FV7CrM", vhaddps_3 = "rrmoy:F20FV7CrM", vhsubpd_3 = "rrmoy:660FV7DrM", vhsubps_3 = "rrmoy:F20FV7DrM", vinsertf128_4 = "rrmi/yyo:660F3AV18rMU", vinsertps_4 = "rrrio:660F3AV21rMU|rrxi/ood:", vldmxcsr_1 = "xd:0FuAE2m", vmaskmovps_3 = "rrxoy:660F38V2CrM|xrroy:660F38V2ERm", vmaskmovpd_3 = "rrxoy:660F38V2DrM|xrroy:660F38V2FRm", vmovapd_2 = "rmoy:660Fu28rM|mroy:660Fu29Rm", vmovaps_2 = "rmoy:0Fu28rM|mroy:0Fu29Rm", vmovd_2 = "rm/od:660Fu6ErM|rm/oq:660FuX6ErM|mr/do:660Fu7ERm|mr/qo:", vmovq_2 = "rro:F30Fu7ErM|rx/oq:|xr/qo:660FuD6Rm", vmovddup_2 = "rmy:F20Fu12rM|rro:|rx/oq:", vmovhlps_3 = "rrro:0FV12rM", vmovhpd_2 = "xr/qo:660Fu17Rm", vmovhpd_3 = "rrx/ooq:660FV16rM", vmovhps_2 = "xr/qo:0Fu17Rm", vmovhps_3 = "rrx/ooq:0FV16rM", vmovlhps_3 = "rrro:0FV16rM", vmovlpd_2 = "xr/qo:660Fu13Rm", vmovlpd_3 = "rrx/ooq:660FV12rM", vmovlps_2 = "xr/qo:0Fu13Rm", vmovlps_3 = "rrx/ooq:0FV12rM", vmovmskpd_2 = "rr/do:660Fu50rM|rr/dy:660FuL50rM", vmovmskps_2 = "rr/do:0Fu50rM|rr/dy:0FuL50rM", vmovntpd_2 = "xroy:660Fu2BRm", vmovntps_2 = "xroy:0Fu2BRm", vmovsd_2 = "rx/oq:F20Fu10rM|xr/qo:F20Fu11Rm", vmovsd_3 = "rrro:F20FV10rM", vmovshdup_2 = "rmoy:F30Fu16rM", vmovsldup_2 = "rmoy:F30Fu12rM", vmovss_2 = "rx/od:F30Fu10rM|xr/do:F30Fu11Rm", vmovss_3 = "rrro:F30FV10rM", vmovupd_2 = "rmoy:660Fu10rM|mroy:660Fu11Rm", vmovups_2 = "rmoy:0Fu10rM|mroy:0Fu11Rm", vorpd_3 = "rrmoy:660FV56rM", vorps_3 = "rrmoy:0FV56rM", vpermilpd_3 = "rrmoy:660F38V0DrM|rmioy:660F3Au05rMU", vpermilps_3 = "rrmoy:660F38V0CrM|rmioy:660F3Au04rMU", vperm2f128_4 = "rrmiy:660F3AV06rMU", vptestpd_2 = "rmoy:660F38u0FrM", vptestps_2 = "rmoy:660F38u0ErM", vrcpps_2 = "rmoy:0Fu53rM", vrcpss_3 = "rrro:F30FV53rM|rrx/ood:", vrsqrtps_2 = "rmoy:0Fu52rM", vrsqrtss_3 = "rrro:F30FV52rM|rrx/ood:", vroundpd_3 = "rmioy:660F3AV09rMU", vroundps_3 = "rmioy:660F3AV08rMU", vroundsd_4 = "rrrio:660F3AV0BrMU|rrxi/ooq:", vroundss_4 = "rrrio:660F3AV0ArMU|rrxi/ood:", vshufpd_4 = "rrmioy:660FVC6rMU", vshufps_4 = "rrmioy:0FVC6rMU", vsqrtps_2 = "rmoy:0Fu51rM", vsqrtss_2 = "rro:F30Fu51rM|rx/od:", vsqrtpd_2 = "rmoy:660Fu51rM", vsqrtsd_2 = "rro:F20Fu51rM|rx/oq:", vstmxcsr_1 = "xd:0FuAE3m", vucomisd_2 = "rro:660Fu2ErM|rx/oq:", vucomiss_2 = "rro:0Fu2ErM|rx/od:", vunpckhpd_3 = "rrmoy:660FV15rM", vunpckhps_3 = "rrmoy:0FV15rM", vunpcklpd_3 = "rrmoy:660FV14rM", vunpcklps_3 = "rrmoy:0FV14rM", vxorpd_3 = "rrmoy:660FV57rM", vxorps_3 = "rrmoy:0FV57rM", vzeroall_0 = "0FuL77", vzeroupper_0 = "0Fu77", -- AVX2 FP ops vbroadcastss_2 = "rx/od:660F38u18rM|rx/yd:|rro:|rr/yo:", vbroadcastsd_2 = "rx/yq:660F38u19rM|rr/yo:", -- *vgather* (!vsib) vpermpd_3 = "rmiy:660F3AuX01rMU", vpermps_3 = "rrmy:660F38V16rM", -- AVX, AVX2 integer ops -- In general, xmm requires AVX, ymm requires AVX2. vaesdec_3 = "rrmo:660F38VDErM", vaesdeclast_3 = "rrmo:660F38VDFrM", vaesenc_3 = "rrmo:660F38VDCrM", vaesenclast_3 = "rrmo:660F38VDDrM", vaesimc_2 = "rmo:660F38uDBrM", vaeskeygenassist_3 = "rmio:660F3AuDFrMU", vlddqu_2 = "rxoy:F20FuF0rM", vmaskmovdqu_2 = "rro:660FuF7rM", vmovdqa_2 = "rmoy:660Fu6FrM|mroy:660Fu7FRm", vmovdqu_2 = "rmoy:F30Fu6FrM|mroy:F30Fu7FRm", vmovntdq_2 = "xroy:660FuE7Rm", vmovntdqa_2 = "rxoy:660F38u2ArM", vmpsadbw_4 = "rrmioy:660F3AV42rMU", vpabsb_2 = "rmoy:660F38u1CrM", vpabsd_2 = "rmoy:660F38u1ErM", vpabsw_2 = "rmoy:660F38u1DrM", vpackusdw_3 = "rrmoy:660F38V2BrM", vpalignr_4 = "rrmioy:660F3AV0FrMU", vpblendvb_4 = "rrmroy:660F3AV4CrMs", vpblendw_4 = "rrmioy:660F3AV0ErMU", vpclmulqdq_4 = "rrmio:660F3AV44rMU", vpcmpeqq_3 = "rrmoy:660F38V29rM", vpcmpestri_3 = "rmio:660F3Au61rMU", vpcmpestrm_3 = "rmio:660F3Au60rMU", vpcmpgtq_3 = "rrmoy:660F38V37rM", vpcmpistri_3 = "rmio:660F3Au63rMU", vpcmpistrm_3 = "rmio:660F3Au62rMU", vpextrb_3 = "rri/do:660F3Au14nRmU|rri/qo:|xri/bo:", vpextrw_3 = "rri/do:660FuC5rMU|xri/wo:660F3Au15nRmU", vpextrd_3 = "mri/do:660F3Au16RmU", vpextrq_3 = "mri/qo:660F3Au16RmU", vphaddw_3 = "rrmoy:660F38V01rM", vphaddd_3 = "rrmoy:660F38V02rM", vphaddsw_3 = "rrmoy:660F38V03rM", vphminposuw_2 = "rmo:660F38u41rM", vphsubw_3 = "rrmoy:660F38V05rM", vphsubd_3 = "rrmoy:660F38V06rM", vphsubsw_3 = "rrmoy:660F38V07rM", vpinsrb_4 = "rrri/ood:660F3AV20rMU|rrxi/oob:", vpinsrw_4 = "rrri/ood:660FVC4rMU|rrxi/oow:", vpinsrd_4 = "rrmi/ood:660F3AV22rMU", vpinsrq_4 = "rrmi/ooq:660F3AVX22rMU", vpmaddubsw_3 = "rrmoy:660F38V04rM", vpmaxsb_3 = "rrmoy:660F38V3CrM", vpmaxsd_3 = "rrmoy:660F38V3DrM", vpmaxuw_3 = "rrmoy:660F38V3ErM", vpmaxud_3 = "rrmoy:660F38V3FrM", vpminsb_3 = "rrmoy:660F38V38rM", vpminsd_3 = "rrmoy:660F38V39rM", vpminuw_3 = "rrmoy:660F38V3ArM", vpminud_3 = "rrmoy:660F38V3BrM", vpmovmskb_2 = "rr/do:660FuD7rM|rr/dy:660FuLD7rM", vpmovsxbw_2 = "rroy:660F38u20rM|rx/oq:|rx/yo:", vpmovsxbd_2 = "rroy:660F38u21rM|rx/od:|rx/yq:", vpmovsxbq_2 = "rroy:660F38u22rM|rx/ow:|rx/yd:", vpmovsxwd_2 = "rroy:660F38u23rM|rx/oq:|rx/yo:", vpmovsxwq_2 = "rroy:660F38u24rM|rx/od:|rx/yq:", vpmovsxdq_2 = "rroy:660F38u25rM|rx/oq:|rx/yo:", vpmovzxbw_2 = "rroy:660F38u30rM|rx/oq:|rx/yo:", vpmovzxbd_2 = "rroy:660F38u31rM|rx/od:|rx/yq:", vpmovzxbq_2 = "rroy:660F38u32rM|rx/ow:|rx/yd:", vpmovzxwd_2 = "rroy:660F38u33rM|rx/oq:|rx/yo:", vpmovzxwq_2 = "rroy:660F38u34rM|rx/od:|rx/yq:", vpmovzxdq_2 = "rroy:660F38u35rM|rx/oq:|rx/yo:", vpmuldq_3 = "rrmoy:660F38V28rM", vpmulhrsw_3 = "rrmoy:660F38V0BrM", vpmulld_3 = "rrmoy:660F38V40rM", vpshufb_3 = "rrmoy:660F38V00rM", vpshufd_3 = "rmioy:660Fu70rMU", vpshufhw_3 = "rmioy:F30Fu70rMU", vpshuflw_3 = "rmioy:F20Fu70rMU", vpsignb_3 = "rrmoy:660F38V08rM", vpsignw_3 = "rrmoy:660F38V09rM", vpsignd_3 = "rrmoy:660F38V0ArM", vpslldq_3 = "rrioy:660Fv737mU", vpsllw_3 = "rrmoy:660FVF1rM|rrioy:660Fv716mU", vpslld_3 = "rrmoy:660FVF2rM|rrioy:660Fv726mU", vpsllq_3 = "rrmoy:660FVF3rM|rrioy:660Fv736mU", vpsraw_3 = "rrmoy:660FVE1rM|rrioy:660Fv714mU", vpsrad_3 = "rrmoy:660FVE2rM|rrioy:660Fv724mU", vpsrldq_3 = "rrioy:660Fv733mU", vpsrlw_3 = "rrmoy:660FVD1rM|rrioy:660Fv712mU", vpsrld_3 = "rrmoy:660FVD2rM|rrioy:660Fv722mU", vpsrlq_3 = "rrmoy:660FVD3rM|rrioy:660Fv732mU", vptest_2 = "rmoy:660F38u17rM", -- AVX2 integer ops vbroadcasti128_2 = "rx/yo:660F38u5ArM", vinserti128_4 = "rrmi/yyo:660F3AV38rMU", vextracti128_3 = "mri/oy:660F3AuL39RmU", vpblendd_4 = "rrmioy:660F3AV02rMU", vpbroadcastb_2 = "rro:660F38u78rM|rx/ob:|rr/yo:|rx/yb:", vpbroadcastw_2 = "rro:660F38u79rM|rx/ow:|rr/yo:|rx/yw:", vpbroadcastd_2 = "rro:660F38u58rM|rx/od:|rr/yo:|rx/yd:", vpbroadcastq_2 = "rro:660F38u59rM|rx/oq:|rr/yo:|rx/yq:", vpermd_3 = "rrmy:660F38V36rM", vpermq_3 = "rmiy:660F3AuX00rMU", -- *vpgather* (!vsib) vperm2i128_4 = "rrmiy:660F3AV46rMU", vpmaskmovd_3 = "rrxoy:660F38V8CrM|xrroy:660F38V8ERm", vpmaskmovq_3 = "rrxoy:660F38VX8CrM|xrroy:660F38VX8ERm", vpsllvd_3 = "rrmoy:660F38V47rM", vpsllvq_3 = "rrmoy:660F38VX47rM", vpsravd_3 = "rrmoy:660F38V46rM", vpsrlvd_3 = "rrmoy:660F38V45rM", vpsrlvq_3 = "rrmoy:660F38VX45rM", } ------------------------------------------------------------------------------ -- Arithmetic ops. for name,n in pairs{ add = 0, ["or"] = 1, adc = 2, sbb = 3, ["and"] = 4, sub = 5, xor = 6, cmp = 7 } do local n8 = shl(n, 3) map_op[name.."_2"] = format( "mr:%02XRm|rm:%02XrM|mI1qdw:81%XmI|mS1qdw:83%XmS|Ri1qdwb:%02Xri|mi1qdwb:81%Xmi", 1+n8, 3+n8, n, n, 5+n8, n) end -- Shift ops. for name,n in pairs{ rol = 0, ror = 1, rcl = 2, rcr = 3, shl = 4, shr = 5, sar = 7, sal = 4 } do map_op[name.."_2"] = format("m1:D1%Xm|mC1qdwb:D3%Xm|mi:C1%XmU", n, n, n) end -- Conditional ops. for cc,n in pairs(map_cc) do map_op["j"..cc.."_1"] = format("J.:n0F8%XJ", n) -- short: 7%X map_op["set"..cc.."_1"] = format("mb:n0F9%X2m", n) map_op["cmov"..cc.."_2"] = format("rmqdw:0F4%XrM", n) -- P6+ end -- FP arithmetic ops. for name,n in pairs{ add = 0, mul = 1, com = 2, comp = 3, sub = 4, subr = 5, div = 6, divr = 7 } do local nc = 0xc0 + shl(n, 3) local nr = nc + (n < 4 and 0 or (n % 2 == 0 and 8 or -8)) local fn = "f"..name map_op[fn.."_1"] = format("ff:D8%02Xr|xd:D8%Xm|xq:nDC%Xm", nc, n, n) if n == 2 or n == 3 then map_op[fn.."_2"] = format("Fff:D8%02XR|Fx2d:D8%XM|Fx2q:nDC%XM", nc, n, n) else map_op[fn.."_2"] = format("Fff:D8%02XR|fFf:DC%02Xr|Fx2d:D8%XM|Fx2q:nDC%XM", nc, nr, n, n) map_op[fn.."p_1"] = format("ff:DE%02Xr", nr) map_op[fn.."p_2"] = format("fFf:DE%02Xr", nr) end map_op["fi"..name.."_1"] = format("xd:DA%Xm|xw:nDE%Xm", n, n) end -- FP conditional moves. for cc,n in pairs{ b=0, e=1, be=2, u=3, nb=4, ne=5, nbe=6, nu=7 } do local nc = 0xdac0 + shl(band(n, 3), 3) + shl(band(n, 4), 6) map_op["fcmov"..cc.."_1"] = format("ff:%04Xr", nc) -- P6+ map_op["fcmov"..cc.."_2"] = format("Fff:%04XR", nc) -- P6+ end -- SSE / AVX FP arithmetic ops. for name,n in pairs{ sqrt = 1, add = 8, mul = 9, sub = 12, min = 13, div = 14, max = 15 } do map_op[name.."ps_2"] = format("rmo:0F5%XrM", n) map_op[name.."ss_2"] = format("rro:F30F5%XrM|rx/od:", n) map_op[name.."pd_2"] = format("rmo:660F5%XrM", n) map_op[name.."sd_2"] = format("rro:F20F5%XrM|rx/oq:", n) if n ~= 1 then map_op["v"..name.."ps_3"] = format("rrmoy:0FV5%XrM", n) map_op["v"..name.."ss_3"] = format("rrro:F30FV5%XrM|rrx/ood:", n) map_op["v"..name.."pd_3"] = format("rrmoy:660FV5%XrM", n) map_op["v"..name.."sd_3"] = format("rrro:F20FV5%XrM|rrx/ooq:", n) end end -- SSE2 / AVX / AVX2 integer arithmetic ops (66 0F leaf). for name,n in pairs{ paddb = 0xFC, paddw = 0xFD, paddd = 0xFE, paddq = 0xD4, paddsb = 0xEC, paddsw = 0xED, packssdw = 0x6B, packsswb = 0x63, packuswb = 0x67, paddusb = 0xDC, paddusw = 0xDD, pand = 0xDB, pandn = 0xDF, pavgb = 0xE0, pavgw = 0xE3, pcmpeqb = 0x74, pcmpeqd = 0x76, pcmpeqw = 0x75, pcmpgtb = 0x64, pcmpgtd = 0x66, pcmpgtw = 0x65, pmaddwd = 0xF5, pmaxsw = 0xEE, pmaxub = 0xDE, pminsw = 0xEA, pminub = 0xDA, pmulhuw = 0xE4, pmulhw = 0xE5, pmullw = 0xD5, pmuludq = 0xF4, por = 0xEB, psadbw = 0xF6, psubb = 0xF8, psubw = 0xF9, psubd = 0xFA, psubq = 0xFB, psubsb = 0xE8, psubsw = 0xE9, psubusb = 0xD8, psubusw = 0xD9, punpckhbw = 0x68, punpckhwd = 0x69, punpckhdq = 0x6A, punpckhqdq = 0x6D, punpcklbw = 0x60, punpcklwd = 0x61, punpckldq = 0x62, punpcklqdq = 0x6C, pxor = 0xEF } do map_op[name.."_2"] = format("rmo:660F%02XrM", n) map_op["v"..name.."_3"] = format("rrmoy:660FV%02XrM", n) end ------------------------------------------------------------------------------ local map_vexarg = { u = false, v = 1, V = 2 } -- Process pattern string. local function dopattern(pat, args, sz, op, needrex) local digit, addin, vex local opcode = 0 local szov = sz local narg = 1 local rex = 0 -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 6 positions. if secpos+6 > maxsecpos then wflush() end -- Process each character. for c in gmatch(pat.."|", ".") do if match(c, "%x") then -- Hex digit. digit = byte(c) - 48 if digit > 48 then digit = digit - 39 elseif digit > 16 then digit = digit - 7 end opcode = opcode*16 + digit addin = nil elseif c == "n" then -- Disable operand size mods for opcode. szov = nil elseif c == "X" then -- Force REX.W. rex = 8 elseif c == "L" then -- Force VEX.L. vex.l = true elseif c == "r" then -- Merge 1st operand regno. into opcode. addin = args[1]; opcode = opcode + (addin.reg % 8) if narg < 2 then narg = 2 end elseif c == "R" then -- Merge 2nd operand regno. into opcode. addin = args[2]; opcode = opcode + (addin.reg % 8) narg = 3 elseif c == "m" or c == "M" then -- Encode ModRM/SIB. local s if addin then s = addin.reg opcode = opcode - band(s, 7) -- Undo regno opcode merge. else s = band(opcode, 15) -- Undo last digit. opcode = shr(opcode, 4) end local nn = c == "m" and 1 or 2 local t = args[nn] if narg <= nn then narg = nn + 1 end if szov == "q" and rex == 0 then rex = rex + 8 end if t.reg and t.reg > 7 then rex = rex + 1 end if t.xreg and t.xreg > 7 then rex = rex + 2 end if s > 7 then rex = rex + 4 end if needrex then rex = rex + 16 end local psz, sk = wputop(szov, opcode, rex, vex, s < 0, t.vreg or t.vxreg) opcode = nil local imark = sub(pat, -1) -- Force a mark (ugly). -- Put ModRM/SIB with regno/last digit as spare. wputmrmsib(t, imark, s, addin and addin.vreg, psz, sk) addin = nil elseif map_vexarg[c] ~= nil then -- Encode using VEX prefix local b = band(opcode, 255); opcode = shr(opcode, 8) local m = 1 if b == 0x38 then m = 2 elseif b == 0x3a then m = 3 end if m ~= 1 then b = band(opcode, 255); opcode = shr(opcode, 8) end if b ~= 0x0f then werror("expected `0F', `0F38', or `0F3A' to precede `"..c.. "' in pattern `"..pat.."' for `"..op.."'") end local v = map_vexarg[c] if v then v = remove(args, v) end b = band(opcode, 255) local p = 0 if b == 0x66 then p = 1 elseif b == 0xf3 then p = 2 elseif b == 0xf2 then p = 3 end if p ~= 0 then opcode = shr(opcode, 8) end if opcode ~= 0 then wputop(nil, opcode, 0); opcode = 0 end vex = { m = m, p = p, v = v } else if opcode then -- Flush opcode. if szov == "q" and rex == 0 then rex = rex + 8 end if needrex then rex = rex + 16 end if addin and addin.reg == -1 then local psz, sk = wputop(szov, opcode - 7, rex, vex, true) wvreg("opcode", addin.vreg, psz, sk) else if addin and addin.reg > 7 then rex = rex + 1 end wputop(szov, opcode, rex, vex) end opcode = nil end if c == "|" then break end if c == "o" then -- Offset (pure 32 bit displacement). wputdarg(args[1].disp); if narg < 2 then narg = 2 end elseif c == "O" then wputdarg(args[2].disp); narg = 3 else -- Anything else is an immediate operand. local a = args[narg] narg = narg + 1 local mode, imm = a.mode, a.imm if mode == "iJ" and not match("iIJ", c) then werror("bad operand size for label") end if c == "S" then wputsbarg(imm) elseif c == "U" then wputbarg(imm) elseif c == "W" then wputwarg(imm) elseif c == "i" or c == "I" then if mode == "iJ" then wputlabel("IMM_", imm, 1) elseif mode == "iI" and c == "I" then waction(sz == "w" and "IMM_WB" or "IMM_DB", imm) else wputszarg(sz, imm) end elseif c == "J" then if mode == "iPJ" then waction("REL_A", imm) -- !x64 (secpos) else wputlabel("REL_", imm, 2) end elseif c == "s" then local reg = a.reg if reg < 0 then wputb(0) wvreg("imm.hi", a.vreg) else wputb(shl(reg, 4)) end else werror("bad char `"..c.."' in pattern `"..pat.."' for `"..op.."'") end end end end end ------------------------------------------------------------------------------ -- Mapping of operand modes to short names. Suppress output with '#'. local map_modename = { r = "reg", R = "eax", C = "cl", x = "mem", m = "mrm", i = "imm", f = "stx", F = "st0", J = "lbl", ["1"] = "1", I = "#", S = "#", O = "#", } -- Return a table/string showing all possible operand modes. local function templatehelp(template, nparams) if nparams == 0 then return "" end local t = {} for tm in gmatch(template, "[^%|]+") do local s = map_modename[sub(tm, 1, 1)] s = s..gsub(sub(tm, 2, nparams), ".", function(c) return ", "..map_modename[c] end) if not match(s, "#") then t[#t+1] = s end end return t end -- Match operand modes against mode match part of template. local function matchtm(tm, args) for i=1,#args do if not match(args[i].mode, sub(tm, i, i)) then return end end return true end -- Handle opcodes defined with template strings. map_op[".template__"] = function(params, template, nparams) if not params then return templatehelp(template, nparams) end local args = {} -- Zero-operand opcodes have no match part. if #params == 0 then dopattern(template, args, "d", params.op, nil) return end -- Determine common operand size (coerce undefined size) or flag as mixed. local sz, szmix, needrex for i,p in ipairs(params) do args[i] = parseoperand(p) local nsz = args[i].opsize if nsz then if sz and sz ~= nsz then szmix = true else sz = nsz end end local nrex = args[i].needrex if nrex ~= nil then if needrex == nil then needrex = nrex elseif needrex ~= nrex then werror("bad mix of byte-addressable registers") end end end -- Try all match:pattern pairs (separated by '|'). local gotmatch, lastpat for tm in gmatch(template, "[^%|]+") do -- Split off size match (starts after mode match) and pattern string. local szm, pat = match(tm, "^(.-):(.*)$", #args+1) if pat == "" then pat = lastpat else lastpat = pat end if matchtm(tm, args) then local prefix = sub(szm, 1, 1) if prefix == "/" then -- Exactly match leading operand sizes. for i = #szm,1,-1 do if i == 1 then dopattern(pat, args, sz, params.op, needrex) -- Process pattern. return elseif args[i-1].opsize ~= sub(szm, i, i) then break end end else -- Match common operand size. local szp = sz if szm == "" then szm = x64 and "qdwb" or "dwb" end -- Default sizes. if prefix == "1" then szp = args[1].opsize; szmix = nil elseif prefix == "2" then szp = args[2].opsize; szmix = nil end if not szmix and (prefix == "." or match(szm, szp or "#")) then dopattern(pat, args, szp, params.op, needrex) -- Process pattern. return end end gotmatch = true end end local msg = "bad operand mode" if gotmatch then if szmix then msg = "mixed operand size" else msg = sz and "bad operand size" or "missing operand size" end end werror(msg.." in `"..opmodestr(params.op, args).."'") end ------------------------------------------------------------------------------ -- x64-specific opcode for 64 bit immediates and displacements. if x64 then function map_op.mov64_2(params) if not params then return { "reg, imm", "reg, [disp]", "[disp], reg" } end if secpos+2 > maxsecpos then wflush() end local opcode, op64, sz, rex, vreg local op64 = match(params[1], "^%[%s*(.-)%s*%]$") if op64 then local a = parseoperand(params[2]) if a.mode ~= "rmR" then werror("bad operand mode") end sz = a.opsize rex = sz == "q" and 8 or 0 opcode = 0xa3 else op64 = match(params[2], "^%[%s*(.-)%s*%]$") local a = parseoperand(params[1]) if op64 then if a.mode ~= "rmR" then werror("bad operand mode") end sz = a.opsize rex = sz == "q" and 8 or 0 opcode = 0xa1 else if sub(a.mode, 1, 1) ~= "r" or a.opsize ~= "q" then werror("bad operand mode") end op64 = params[2] if a.reg == -1 then vreg = a.vreg opcode = 0xb8 else opcode = 0xb8 + band(a.reg, 7) end rex = a.reg > 7 and 9 or 8 end end local psz, sk = wputop(sz, opcode, rex, nil, vreg) wvreg("opcode", vreg, psz, sk) if luamode then waction("IMM_D", format("ffi.cast(\"uintptr_t\", %s) %% 2^32", op64)) waction("IMM_D", format("ffi.cast(\"uintptr_t\", %s) / 2^32", op64)) else waction("IMM_D", format("(unsigned int)(%s)", op64)) waction("IMM_D", format("(unsigned int)((%s)>>32)", op64)) end end end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. local function op_data(params) if not params then return "imm..." end local sz = sub(params.op, 2, 2) if sz == "a" then sz = addrsize end for _,p in ipairs(params) do local a = parseoperand(p) if sub(a.mode, 1, 1) ~= "i" or (a.opsize and a.opsize ~= sz) then werror("bad mode or size in `"..p.."'") end if a.mode == "iJ" then wputlabel("IMM_", a.imm, 1) else wputszarg(sz, a.imm) end if secpos+2 > maxsecpos then wflush() end end end map_op[".byte_*"] = op_data map_op[".sbyte_*"] = op_data map_op[".word_*"] = op_data map_op[".dword_*"] = op_data map_op[".aword_*"] = op_data ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_2"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr [, addr]" end if secpos+2 > maxsecpos then wflush() end local a = parseoperand(params[1]) local mode, imm = a.mode, a.imm if type(imm) == "number" and (mode == "iJ" or (imm >= 1 and imm <= 9)) then -- Local label (1: ... 9:) or global label (->global:). waction("LABEL_LG", nil, 1) wputxb(imm) elseif mode == "iJ" then -- PC label (=>pcexpr:). waction("LABEL_PC", imm) else werror("bad label definition") end -- SETLABEL must immediately follow LABEL_LG/LABEL_PC. local addr = params[2] if addr then local a = parseoperand(addr) if a.mode == "iPJ" then waction("SETLABEL", a.imm) else werror("bad label assignment") end end end map_op[".label_1"] = map_op[".label_2"] ------------------------------------------------------------------------------ -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) or map_opsizenum[map_opsize[params[1]]] if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", nil, 1) wputxb(align-1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end -- Spacing pseudo-opcode. map_op[".space_2"] = function(params) if not params then return "num [, filler]" end if secpos+1 > maxsecpos then wflush() end waction("SPACE", params[1]) local fill = params[2] if fill then fill = tonumber(fill) if not fill or fill < 0 or fill > 255 then werror("bad filler") end end wputxb(fill or 0) end map_op[".space_1"] = map_op[".space_2"] ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end if reg and not map_reg_valid_base[reg] then werror("bad base register `"..(map_reg_rev[reg] or reg).."'") end -- Add #type to current defines table. g_map_def["#"..name] = luamode and "ffi.sizeof(\""..ctype.."\")" or "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 local ctypefmt if luamode then ctypefmt = function(tailr) local index, field index, field = match(tailr, "^(%b[])(.*)") index = index and sub(index, 2, -2) field = field or tailr field = match(field, "^%->(.*)") or match(field, "^%.(.*)") if not (index or field) then werror("invalid syntax `"..tailr.."`") end local Da = index and format("Da%X(%s)", num, index) local Dt = field and format("Dt%X(\"%s\")", num, field) return Da and Dt and Da.."+"..Dt or Da or Dt end else ctypefmt = format("Dt%X(%%s)", num) end map_type[name] = { ctype = ctype, ctypefmt = ctypefmt, reg = reg, } if luamode then wline(format("local Dt%X; do local ct=ffi.typeof(\"%s\"); function Dt%X(f) return ffi.offsetof(ct,f) or error(string.format(\"'struct %s' has no member named '%%s'\", f)) end; end", num, ctype, num, ctype)) wline(format("local Da%X; do local sz=ffi.sizeof(\"%s\"); function Da%X(i) return i*sz end; end", num, ctype, num)) else wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) end ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg and map_reg_rev[tp.reg] or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION") wputxb(num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpregs(out) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt luamode = g_opt.lang == "lua" init_actionlist() init_map_global() init_map_extern() init_map_type() end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) -- Hold a ref. to map_def to store `#type` defines in. g_map_def = map_def return map_op, map_def end return _M ------------------------------------------------------------------------------
apache-2.0
minetest-games/Minetest_TNG
mods/default/lua/mapgen/aliases.lua
2
1967
-- This file is part of Minetest TNG -- ================================= -- mods/default/lua/mapgen/aliases.lua -- -- Aliases for map generator outputs -- core.register_alias("mapgen_air", "air") core.register_alias("mapgen_stone", "default:stone") core.register_alias("mapgen_dirt", "default:dirt") core.register_alias("mapgen_dirt_with_grass", "default:dirt_with_grass") core.register_alias("mapgen_sand", "default:sand") core.register_alias("mapgen_water_source", "default:water_source") core.register_alias("mapgen_river_water_source", "default:water_source") core.register_alias("mapgen_lava_source", "default:lava_source") core.register_alias("mapgen_gravel", "default:gravel") core.register_alias("mapgen_desert_stone", "default:desert_stone") core.register_alias("mapgen_desert_sand", "default:desert_sand") core.register_alias("mapgen_dirt_with_snow", "default:dirt_with_snow") core.register_alias("mapgen_snowblock", "default:snowblock") core.register_alias("mapgen_snow", "default:snow") core.register_alias("mapgen_ice", "default:ice") core.register_alias("mapgen_sandstone", "default:sandstone") -- Flora core.register_alias("mapgen_tree", "default:tree") core.register_alias("mapgen_leaves", "default:leaves") core.register_alias("mapgen_apple", "default:leaves_with_apple") core.register_alias("mapgen_jungletree", "default:jungletree") core.register_alias("mapgen_jungleleaves", "default:jungleleaves") core.register_alias("mapgen_junglegrass", "default:junglegrass") core.register_alias("mapgen_pine_tree", "default:pine_tree") core.register_alias("mapgen_pine_needles", "default:pine_needles") -- Dungeons core.register_alias("mapgen_cobble", "default:cobble") core.register_alias("mapgen_stair_cobble", "stairs:stair_cobble") core.register_alias("mapgen_mossycobble", "default:mossycobble") core.register_alias("mapgen_sandstonebrick", "default:sandstonebrick") core.register_alias("mapgen_stair_sandstonebrick", "stairs:stair_sandstonebrick")
gpl-3.0
ranisalt/forgottenserver
data/spells/scripts/custom/polymorph.lua
10
1084
local condition = Condition(CONDITION_OUTFIT) condition:setParameter(CONDITION_PARAM_TICKS, 20000) condition:setOutfit(0, 230, 0, 0, 0, 0) condition:setOutfit(0, 231, 0, 0, 0, 0) condition:setOutfit(0, 232, 0, 0, 0, 0) condition:setOutfit(0, 233, 0, 0, 0, 0) condition:setOutfit(0, 234, 0, 0, 0, 0) condition:setOutfit(0, 235, 0, 0, 0, 0) condition:setOutfit(0, 236, 0, 0, 0, 0) condition:setOutfit(0, 237, 0, 0, 0, 0) condition:setOutfit(0, 238, 0, 0, 0, 0) condition:setOutfit(0, 239, 0, 0, 0, 0) condition:setOutfit(0, 240, 0, 0, 0, 0) condition:setOutfit(0, 241, 0, 0, 0, 0) condition:setOutfit(0, 242, 0, 0, 0, 0) condition:setOutfit(0, 243, 0, 0, 0, 0) condition:setOutfit(0, 244, 0, 0, 0, 0) condition:setOutfit(0, 245, 0, 0, 0, 0) condition:setOutfit(0, 246, 0, 0, 0, 0) condition:setOutfit(0, 247, 0, 0, 0, 0) local combat = Combat() combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_GREEN) combat:setArea(createCombatArea(AREA_SQUARE1X1)) combat:addCondition(condition) function onCastSpell(creature, variant, isHotkey) return combat:execute(creature, variant) end
gpl-2.0
czfshine/Don-t-Starve
data/scripts/scenarios/statue_enemywave.lua
1
2304
enemytypes = {"knight", "bishop", "rook"} local function OnEnemyKilled(inst, enemy, scenariorunner) if enemy.scene_deathfn then inst:RemoveEventCallback("death", enemy.scene_deathfn, enemy) enemy.scene_deathfn = nil end inst.wave[enemy] = nil if not next(inst.wave) then GetPlayer().components.sanity:SetPercent(1) scenariorunner:ClearScenario() end end local function ListenForDeath(inst, scenariorunner) for k,v in pairs(inst.wave) do if v.components.combat then v.scene_deathfn = function() OnEnemyKilled(inst, v, scenariorunner) end inst:ListenForEvent("death", v.scene_deathfn, v) end end end local function TrapInRocks(inst) GetPlayer().components.sanity:SetPercent(0.5) end local function StartWave(inst) inst:PushEvent("MaxwellThreat") local pt = Vector3(inst.Transform:GetWorldPosition()) local theta = math.random() * 2 * PI local radius = 4 local steps = math.random(3,4) local ground = GetWorld() local player = GetPlayer() local spawnedguards = {} local settarget = function(inst, player) if inst and inst.brain then inst.brain.followtarget = player end end for i = 1, steps do local offset = Vector3(radius * math.cos( theta ), 0, -radius * math.sin( theta )) local wander_point = pt + offset if ground.Map and ground.Map:GetTileAtPoint(wander_point.x, wander_point.y, wander_point.z) ~= GROUND.IMPASSABLE then local particle = SpawnPrefab("poopcloud") particle.Transform:SetPosition( wander_point.x, wander_point.y, wander_point.z ) local enemy = SpawnPrefab(enemytypes[math.random(1, #enemytypes)]) enemy.Transform:SetPosition( wander_point.x, wander_point.y, wander_point.z ) enemy:DoTaskInTime(1, settarget, player) spawnedguards[enemy] = enemy end theta = theta - (2 * PI / steps) end return spawnedguards end local function PlayerNear(inst) end local function PlayerFar(inst) end local function OnLoad(inst, scenariorunner) inst:ListenForEvent("onremove", function() inst.wave = StartWave(inst) ListenForDeath(inst, scenariorunner) TrapInRocks(inst) end) end local function OnDestroy(inst) end return { OnLoad = OnLoad }
gpl-2.0
timroes/awesome
tests/test-miss-handlers.lua
8
1668
-- Test set_{,new}index_miss_handler local mouse = mouse local class = tag local obj = class({}) local handler = require("gears.object.properties") local wibox = require("wibox") awesome.connect_signal("debug::index::miss", error) awesome.connect_signal("debug::newindex::miss", error) class.set_index_miss_handler(function(o, k) assert(o == obj) assert(k == "key") return 42 end) assert(obj.key == 42) local called = false class.set_newindex_miss_handler(function(o, k, v) assert(o == obj) assert(k == "key") assert(v == 42) called = true end) obj.key = 42 assert(called) handler(class, {auto_emit=true}) assert(not obj.key) obj.key = 1337 assert(obj.key == 1337) -- The the custom mouse handler mouse.foo = "bar" assert(mouse.foo == "bar") local w = wibox() w.foo = "bar" assert(w.foo == "bar") -- Test if read-only properties really are read-only screen[1].clients = 42 assert(screen[1].clients ~= 42) -- Test the wibox declarative widget system (drawin proxy) local w2 = wibox { visible = true, wisth = 100, height = 100 } w2:setup{ { text = "Awesomeness!", id = "main_textbox", widget = wibox.widget.textbox, }, id = "main_background", widget = wibox.container.background } assert(w2.main_background) assert(w2:get_children_by_id("main_background")[1]) assert(w2:get_children_by_id("main_textbox")[1]) assert(w2.main_background.main_textbox) assert(w2.main_background == w2:get_children_by_id("main_background")[1]) require("_runner").run_steps({ function() return true end }) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
czfshine/Don-t-Starve
data/scripts/prefabs/lightbulb.lua
1
1674
local assets = { Asset("ANIM", "anim/bulb.zip"), } local function fn(Sim) local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() MakeInventoryPhysics(inst) inst.AnimState:SetBank("bulb") inst.AnimState:SetBuild("bulb") inst.AnimState:PlayAnimation("idle") inst:AddComponent("stackable") inst.components.stackable.maxsize = TUNING.STACK_SIZE_SMALLITEM inst:AddComponent("tradable") inst:AddComponent("inspectable") inst:AddComponent("fuel") inst.components.fuel.fuelvalue = TUNING.MED_LARGE_FUEL inst.components.fuel.fueltype = "CAVE" MakeSmallBurnable(inst, TUNING.TINY_BURNTIME) MakeSmallPropagator(inst) inst:AddComponent("inventoryitem") inst:AddComponent("edible") inst.components.edible.healthvalue = TUNING.HEALING_TINY inst.components.edible.hungervalue = 0 inst.components.edible.foodtype = "VEGGIE" inst:AddComponent("perishable") inst.components.perishable:SetPerishTime(TUNING.PERISH_FAST) inst.components.perishable:StartPerishing() inst.components.perishable.onperishreplacement = "spoiled_food" local light = inst.entity:AddLight() light:SetFalloff(0.7) light:SetIntensity(.5) light:SetRadius(0.5) light:SetColour(237/255, 237/255, 209/255) light:Enable(true) inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" ) inst.components.inventoryitem:SetOnDroppedFn(function() inst.Light:Enable(true) end) inst.components.inventoryitem:SetOnPickupFn(function() inst.Light:Enable(false) end) return inst end return Prefab( "common/inventory/lightbulb", fn, assets)
gpl-2.0
czfshine/Don-t-Starve
data/scripts/prefabs/spiderden.lua
1
12873
local prefabs = { "spider", "spider_warrior", "silk", "spidereggsack", "spiderqueen", } local assets = { Asset("ANIM", "anim/spider_cocoon.zip"), Asset("SOUND", "sound/spider.fsb"), } local function SetStage(inst, stage) if stage <= 3 then inst.SoundEmitter:PlaySound("dontstarve/creatures/spider/spiderLair_grow") if inst.components.childspawner then inst.components.childspawner:SetMaxChildren(TUNING.SPIDERDEN_SPIDERS[stage]) end if inst.components.health then inst.components.health:SetMaxHealth(TUNING.SPIDERDEN_HEALTH[stage]) end inst.AnimState:PlayAnimation(inst.anims.init) inst.AnimState:PushAnimation(inst.anims.idle, true) end inst.data.stage = stage -- track here, as growable component may go away end local function SetSmall(inst) inst.anims = { hit="cocoon_small_hit", idle="cocoon_small", init="grow_sac_to_small", freeze="frozen_small", thaw="frozen_loop_pst_small", } SetStage(inst, 1) inst.components.lootdropper:SetLoot({ "silk","silk"}) if inst.components.burnable then inst.components.burnable:SetFXLevel(3) inst.components.burnable:SetBurnTime(10) end if inst.components.freezable then inst.components.freezable:SetShatterFXLevel(3) inst.components.freezable:SetResistance(2) end inst.GroundCreepEntity:SetRadius( 5 ) end local function SetMedium(inst) inst.anims = { hit="cocoon_medium_hit", idle="cocoon_medium", init="grow_small_to_medium", freeze="frozen_medium", thaw="frozen_loop_pst_medium", } SetStage(inst, 2) inst.components.lootdropper:SetLoot({ "silk","silk","silk","silk"}) if inst.components.burnable then inst.components.burnable:SetFXLevel(3) inst.components.burnable:SetBurnTime(10) end if inst.components.freezable then inst.components.freezable:SetShatterFXLevel(4) inst.components.freezable:SetResistance(3) end inst.GroundCreepEntity:SetRadius( 9 ) end local function SetLarge(inst) inst.anims = { hit="cocoon_large_hit", idle="cocoon_large", init="grow_medium_to_large", freeze="frozen_large", thaw="frozen_loop_pst_large", } SetStage(inst, 3) inst.components.lootdropper:SetLoot({ "silk","silk","silk","silk","silk","silk", "spidereggsack"}) if inst.components.burnable then inst.components.burnable:SetFXLevel(4) inst.components.burnable:SetBurnTime(15) end if inst.components.freezable then inst.components.freezable:SetShatterFXLevel(5) inst.components.freezable:SetResistance(4) end inst.GroundCreepEntity:SetRadius( 9 ) end local function AttemptMakeQueen(inst) if inst.data.stage == nil or inst.data.stage ~= 3 then -- we got here directly (probably by loading), so reconfigure to the level 3 state. SetLarge(inst) end local player = GetPlayer() if not player or player:GetDistanceSqToInst(inst) > 30*30 then inst.components.growable:StartGrowing(60 + math.random(60) ) return end local check_range = 60 local cap = 4 local x, y, z = inst.Transform:GetWorldPosition() local ents = TheSim:FindEntities(x,y,z, check_range) local num_dens = 0 for k,v in pairs(ents) do if v:HasTag("spiderden") or v.prefab == "spiderqueen" then num_dens = num_dens + 1 end if num_dens >= cap then break end end local should_duplicate = num_dens < cap inst.components.growable:SetStage(1) inst.AnimState:PlayAnimation("cocoon_large_burst") inst.AnimState:PushAnimation("cocoon_large_burst_pst") inst.AnimState:PushAnimation("cocoon_small", true) inst.SoundEmitter:PlaySound("dontstarve/creatures/spiderqueen/legburst") inst:DoTaskInTime(5*FRAMES, function() inst.SoundEmitter:PlaySound("dontstarve/creatures/spiderqueen/legburst") end) inst:DoTaskInTime(15*FRAMES, function() inst.SoundEmitter:PlaySound("dontstarve/creatures/spiderqueen/legburst") end) inst:DoTaskInTime(35*FRAMES, function() local queen = SpawnPrefab("spiderqueen") local pt = Vector3(inst.Transform:GetWorldPosition()) local rad = 1.25 local angle = math.random(2*PI) pt = pt + Vector3(rad*math.cos(angle), 0, rad*math.sin(angle)) queen.Transform:SetPosition(pt:Get()) queen.sg:GoToState("birth") if not should_duplicate then inst:Remove() end end) inst.components.growable:StartGrowing(60) end local function onspawnspider(inst, spider) spider.sg:GoToState("taunt") end local function OnKilled(inst) inst.AnimState:PlayAnimation("cocoon_dead") if inst.components.childspawner then inst.components.childspawner:ReleaseAllChildren() end inst.Physics:ClearCollisionMask() inst.SoundEmitter:KillSound("loop") inst.SoundEmitter:PlaySound("dontstarve/creatures/spider/spiderLair_destroy") inst.components.lootdropper:DropLoot(Vector3(inst.Transform:GetWorldPosition())) end local function SpawnDefenders(inst, attacker) if not inst.components.health:IsDead() then inst.SoundEmitter:PlaySound("dontstarve/creatures/spider/spiderLair_hit") inst.AnimState:PlayAnimation(inst.anims.hit) inst.AnimState:PushAnimation(inst.anims.idle) if inst.components.childspawner then local max_release_per_stage = {2, 4, 6} local num_to_release = math.min( max_release_per_stage[inst.data.stage] or 1, inst.components.childspawner.childreninside) local num_warriors = math.min(num_to_release, TUNING.SPIDERDEN_WARRIORS[inst.data.stage]) num_warriors = num_warriors - inst.components.childspawner:CountChildrenOutside(function(child) return child.prefab == "spider_warrior" end) for k = 1,num_to_release do if k <= num_warriors then inst.components.childspawner.childname = "spider_warrior" else inst.components.childspawner.childname = "spider" end local spider = inst.components.childspawner:SpawnChild() if spider and attacker and spider.components.combat then spider.components.combat:SetTarget(attacker) spider.components.combat:BlankOutAttacks(1.5 + math.random()*2) end end inst.components.childspawner.childname = "spider" end end end local function SpawnInvestigators(inst, data) if not inst.components.health:IsDead() and not (inst.components.freezable and inst.components.freezable:IsFrozen()) then inst.AnimState:PlayAnimation(inst.anims.hit) inst.AnimState:PushAnimation(inst.anims.idle) if inst.components.childspawner then local max_release_per_stage = {1, 2, 3} local num_to_release = math.min( max_release_per_stage[inst.data.stage] or 1, inst.components.childspawner.childreninside) local num_investigators = inst.components.childspawner:CountChildrenOutside(function(child) return child.components.knownlocations:GetLocation("investigate") ~= nil end) num_to_release = num_to_release - num_investigators for k = 1,num_to_release do local spider = inst.components.childspawner:SpawnChild() if spider and data and data.target then spider.components.knownlocations:RememberLocation("investigate", Vector3(data.target.Transform:GetWorldPosition() ) ) end end end end end local function StartSpawning(inst) if inst.components.childspawner then local frozen = (inst.components.freezable and inst.components.freezable:IsFrozen()) if not frozen and not GetClock():IsDay() then inst.components.childspawner:StartSpawning() end end end local function StopSpawning(inst) if inst.components.childspawner then inst.components.childspawner:StopSpawning() end end local function OnIgnite(inst) if inst.components.childspawner then SpawnDefenders(inst) inst:RemoveComponent("childspawner") end inst.SoundEmitter:KillSound("loop") DefaultBurnFn(inst) end local function OnBurnt(inst) end local function OnFreeze(inst) print(inst, "OnFreeze") inst.SoundEmitter:PlaySound("dontstarve/common/freezecreature") inst.AnimState:PlayAnimation(inst.anims.freeze, true) inst.AnimState:OverrideSymbol("swap_frozen", "frozen", "frozen") StopSpawning(inst) if inst.components.growable then inst.components.growable:Pause() end end local function OnThaw(inst) print(inst, "OnThaw") inst.AnimState:PlayAnimation(inst.anims.thaw, true) inst.SoundEmitter:PlaySound("dontstarve/common/freezethaw", "thawing") inst.AnimState:OverrideSymbol("swap_frozen", "frozen", "frozen") end local function OnUnFreeze(inst) print(inst, "OnUnFreeze") inst.AnimState:PlayAnimation(inst.anims.idle, true) inst.SoundEmitter:KillSound("thawing") inst.AnimState:ClearOverrideSymbol("swap_frozen") StartSpawning(inst) if inst.components.growable then inst.components.growable:Resume() end end local function GetSmallGrowTime(inst) return TUNING.SPIDERDEN_GROW_TIME[1] + math.random()*TUNING.SPIDERDEN_GROW_TIME[1] end local function GetMedGrowTime(inst) return TUNING.SPIDERDEN_GROW_TIME[2]+ math.random()*TUNING.SPIDERDEN_GROW_TIME[2] end local function GetLargeGrowTime(inst) return TUNING.SPIDERDEN_GROW_TIME[3]+ math.random()*TUNING.SPIDERDEN_GROW_TIME[3] end local function OnEntityWake(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/spider/spidernest_LP", "loop") end local function OnEntitySleep(inst) inst.SoundEmitter:KillSound("loop") end local growth_stages = { {name="small", time = GetSmallGrowTime, fn = SetSmall }, {name="med", time = GetMedGrowTime , fn = SetMedium }, {name="large", time = GetLargeGrowTime, fn = SetLarge}, {name="queen", fn = AttemptMakeQueen}} local function MakeSpiderDenFn(den_level) local spiderden_fn = function(Sim) local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() inst.entity:AddGroundCreepEntity() inst.entity:AddSoundEmitter() inst.data = {} MakeObstaclePhysics(inst, .5) local minimap = inst.entity:AddMiniMapEntity() minimap:SetIcon( "spiderden.png" ) anim:SetBank("spider_cocoon") anim:SetBuild("spider_cocoon") anim:PlayAnimation("cocoon_small", true) inst:AddTag("structure") inst:AddTag("hostile") inst:AddTag("spiderden") inst:AddTag("hive") ------------------- inst:AddComponent("health") inst.components.health:SetMaxHealth(200) ------------------- inst:AddComponent("childspawner") inst.components.childspawner.childname = "spider" inst.components.childspawner:SetRegenPeriod(TUNING.SPIDERDEN_REGEN_TIME) inst.components.childspawner:SetSpawnPeriod(TUNING.SPIDERDEN_RELEASE_TIME) inst.components.childspawner:SetSpawnedFn(onspawnspider) --inst.components.childspawner:SetMaxChildren(TUNING.SPIDERDEN_SPIDERS[stage]) --inst.components.childspawner:ScheduleNextSpawn(0) inst:ListenForEvent("creepactivate", SpawnInvestigators) --------------------- inst:AddComponent("lootdropper") --------------------- --------------------- MakeMediumBurnable(inst) inst.components.burnable:SetOnIgniteFn(OnIgnite) ------------------- --------------------- MakeMediumFreezableCharacter(inst) inst:ListenForEvent("freeze", OnFreeze) inst:ListenForEvent("onthaw", OnThaw) inst:ListenForEvent("unfreeze", OnUnFreeze) ------------------- inst:ListenForEvent("dusktime", function() StartSpawning(inst) end, GetWorld()) inst:ListenForEvent("daytime", function() StopSpawning(inst) end , GetWorld()) ------------------- inst:AddComponent("combat") inst.components.combat:SetOnHit(SpawnDefenders) inst:ListenForEvent("death", OnKilled) --------------------- MakeLargePropagator(inst) --------------------- inst:AddComponent("growable") inst.components.growable.stages = growth_stages inst.components.growable:SetStage(den_level) inst.components.growable:StartGrowing() --------------------- --inst:AddComponent( "spawner" ) --inst.components.spawner:Configure( "resident", max, initial, rate ) --inst.spawn_weight = global_spawn_weight inst:AddComponent("inspectable") MakeSnowCovered(inst) inst:SetPrefabName("spiderden") inst.OnEntitySleep = OnEntitySleep inst.OnEntityWake = OnEntityWake return inst end return spiderden_fn end return Prefab( "forest/monsters/spiderden", MakeSpiderDenFn(1), assets, prefabs ), Prefab( "forest/monsters/spiderden_2", MakeSpiderDenFn(2), assets, prefabs ), Prefab( "forest/monsters/spiderden_3", MakeSpiderDenFn(3), assets, prefabs )
gpl-2.0
czfshine/Don-t-Starve
data/scripts/cooking.lua
1
5697
require "tuning" local cookerrecipes = {} function AddCookerRecipe(cooker, recipe) if not cookerrecipes[cooker] then cookerrecipes[cooker] = {} end cookerrecipes[cooker][recipe.name] = recipe end local ingredients = {} function AddIngredientValues(names, tags, cancook, candry) for _,name in pairs(names) do ingredients[name] = { tags= {}} if cancook then ingredients[name.."_cooked"] = {tags={}} end if candry then ingredients[name.."_dried"] = {tags={}} end for tagname,tagval in pairs(tags) do ingredients[name].tags[tagname] = tagval --print(name,tagname,tagval,ingtable[name].tags[tagname]) if cancook then ingredients[name.."_cooked"].tags.precook = 1 ingredients[name.."_cooked"].tags[tagname] = tagval end if candry then ingredients[name.."_dried"].tags.dried = 1 ingredients[name.."_dried"].tags[tagname] = tagval end end end end function IsModCookingProduct(cooker, name) local enabledmods = ModManager:GetEnabledModNames() for i,v in ipairs(enabledmods) do local mod = ModManager:GetMod(v) if mod.cookerrecipes and mod.cookerrecipes[cooker] and table.contains(mod.cookerrecipes[cooker], name) then return true end end return false end local fruits = {"pomegranate", "dragonfruit", "cave_banana"} AddIngredientValues(fruits, {fruit=1}, true) AddIngredientValues({"berries"}, {fruit=.5}, true) AddIngredientValues({"durian"}, {fruit=1, monster=1}, true) AddIngredientValues({"honey", "honeycomb"}, {sweetener=1}, true) local veggies = {"carrot", "corn", "pumpkin", "eggplant", "cutlichen"} AddIngredientValues(veggies, {veggie=1}, true) local mushrooms = {"red_cap", "green_cap", "blue_cap"} AddIngredientValues(mushrooms, {veggie=.5}, true) AddIngredientValues({"meat"}, {meat=1}, true, true) AddIngredientValues({"monstermeat"}, {meat=1, monster=1}, true, true) AddIngredientValues({"froglegs", "drumstick"}, {meat=.5}, true) AddIngredientValues({"smallmeat"}, {meat=.5}, true, true) AddIngredientValues({"fish", "eel"}, {meat=.5,fish=1}, true) AddIngredientValues({"mandrake"}, {veggie=1, magic=1}, true) AddIngredientValues({"egg"}, {egg=1}, true) AddIngredientValues({"tallbirdegg"}, {egg=4}, true) AddIngredientValues({"bird_egg"}, {egg=1}, true) AddIngredientValues({"butterflywings"}, {decoration=2}) AddIngredientValues({"butter"}, {fat=1, dairy=1}) AddIngredientValues({"twigs"}, {inedible=1}) --our naming conventions aren't completely consistent, sadly local aliases= { cookedsmallmeat = "smallmeat_cooked", cookedmonstermeat = "monstermeat_cooked", cookedmeat = "meat_cooked" } local function IsCookingIngredient(prefabname) local name = aliases[prefabname] or prefabname if ingredients[name] then return true end end local null_ingredient = {tags={}} local function GetIngredientData(prefabname) local name = aliases.prefabname or prefabname return ingredients[name] or null_ingredient end local foods = require("preparedfoods") for k,recipe in pairs (foods) do AddCookerRecipe("cookpot", recipe) end local function GetIngredientValues(prefablist) local prefabs = {} local tags = {} for k,v in pairs(prefablist) do local name = aliases[v] or v prefabs[name] = prefabs[name] and prefabs[name] + 1 or 1 local data = GetIngredientData(name) if data then for kk, vv in pairs(data.tags) do tags[kk] = tags[kk] and tags[kk] + vv or vv end end end return {tags = tags, names = prefabs} end function GetCandidateRecipes(cooker, ingdata) local recipes = cookerrecipes[cooker] or {} local candidates = {} --find all potentially valid recipes for k,v in pairs(recipes) do if v.test(cooker, ingdata.names, ingdata.tags) then table.insert(candidates, v) end end table.sort( candidates, function(a,b) return (a.priority or 0) > (b.priority or 0) end ) if #candidates > 0 then --find the set of highest priority recipes local top_candidates = {} local idx = 1 local val = candidates[1].priority or 0 for k,v in ipairs(candidates) do if k > 1 and (v.priority or 0) < val then break end table.insert(top_candidates, v) end return top_candidates end return candidates end local function CalculateRecipe(cooker, names) local ingdata = GetIngredientValues(names) local candidates = GetCandidateRecipes(cooker, ingdata) table.sort( candidates, function(a,b) return (a.weight or 1) > (b.weight or 1) end ) local total = 0 for k,v in pairs(candidates) do total = total + (v.weight or 1) end local val = math.random()*total local idx = 1 while idx <= #candidates do val = val - candidates[idx].weight if val <= 0 then return candidates[idx].name, candidates[idx].cooktime or 1 end idx = idx+1 end end local function TestRecipes(cooker, prefablist) local ingdata = GetIngredientValues(prefablist) print ("Ingredients:") for k,v in pairs(prefablist) do if not IsCookingIngredient(v) then print ("NOT INGREDIENT:", v) end end for k,v in pairs(ingdata.names) do print (v,k) end print ("\nIngredient tags:") for k,v in pairs(ingdata.tags) do print (tostring(v), k) end print ("\nPossible recipes:") local candidates = GetCandidateRecipes(cooker, ingdata) for k,v in pairs(candidates) do print("\t"..v.name, v.weight or 1) end local recipe = CalculateRecipe(cooker, prefablist) print ("Make:", recipe) print ("total health:", foods[recipe].health) print ("total hunger:", foods[recipe].hunger) end --TestRecipes("cookpot", {"tallbirdegg","meat","carrot","meat"}) return { CalculateRecipe = CalculateRecipe, IsCookingIngredient = IsCookingIngredient, recipes = cookerrecipes, ingredients=ingredients}
gpl-2.0
shkan/telebot1
plugins/time.lua
120
2804
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'In "'..area..'" they dont have time' end local localTime, timeZoneId = get_time(lat,lng) return "Local: "..timeZoneId.."\nTime: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Get Time Give by Local Name", usage = "/time (local) : view local time", patterns = {"^[!/]time (.*)$"}, run = run }
gpl-2.0
kevdoran/nifi-minifi-cpp
thirdparty/civetweb-1.10/test/page3.lua
10
1626
-- This test checks if a query string has been given. -- It sends the file identified by the query string. -- Do not use it in a real server in this way! if not mg.request_info.query_string then mg.write("HTTP/1.0 200 OK\r\n") mg.write("Connection: close\r\n") mg.write("Content-Type: text/html; charset=utf-8\r\n") mg.write("\r\n") mg.write("<html><head><title>Civetweb Lua script test page 3</title></head>\r\n") mg.write("<body>No query string!</body></html>\r\n") elseif mg.request_info.query_string:match("/") or mg.request_info.query_string:match("\\") then mg.write("HTTP/1.0 403 Forbidden\r\n") mg.write("Connection: close\r\n") mg.write("Content-Type: text/html; charset=utf-8\r\n") mg.write("\r\n") mg.write("<html><head><title>Civetweb Lua script test page 3</title></head>\r\n") mg.write("<body>No access!</body></html>\r\n") else file = mg.get_var(mg.request_info.query_string, "file"); if not file then mg.write("HTTP/1.0 400 Bad Request\r\n") mg.write("Connection: close\r\n") mg.write("Content-Type: text/html; charset=utf-8\r\n") mg.write("\r\n") mg.write("<html>\r\n<head><title>Civetweb Lua script test page 3</title></head>\r\n") mg.write("<body>\r\nQuery string does not contain a 'file' variable.<br>\r\n") mg.write("Try <a href=\"?file=page3.lua&somevar=something\">?file=page3.lua&somevar=something</a>\r\n") mg.write("</body>\r\n</html>\r\n") else filename = mg.document_root .. "/" .. file mg.send_file(filename) end end
apache-2.0
timroes/awesome
tests/examples/wibox/layout/grid/min_size.lua
4
1465
local generic_widget = ... --DOC_HIDE_ALL local wibox = require("wibox") --DOC_HIDE local beautiful = require("beautiful") --DOC_HIDE local w = wibox.widget { { { markup = "<b>min_cols_size</b> = <i>0</i>", widget = wibox.widget.textbox }, { { generic_widget( "first" ), generic_widget( "second" ), forced_num_cols = 2, min_cols_size = 0, homogeneous = true, layout = wibox.layout.grid, }, margins = 1, color = beautiful.border_color, layout = wibox.container.margin, }, layout = wibox.layout.fixed.vertical }, { { markup = "<b>min_cols_size</b> = <i>100</i>", widget = wibox.widget.textbox }, { { generic_widget( "first" ), generic_widget( "second" ), forced_num_cols = 2, min_cols_size = 100, homogeneous = true, layout = wibox.layout.grid, }, margins = 1, color = beautiful.border_color, layout = wibox.container.margin, }, layout = wibox.layout.fixed.vertical }, layout = wibox.layout.fixed.horizontal } return w, w:fit({dpi=96}, 9999, 9999) --return w, 500, 50
gpl-2.0
luvit/lit
commands/serve.lua
2
3311
local args = {...} return function () local uv = require 'uv' local log = require('log').log local makeRemote = require('codec').makeRemote local core = require('core')() local cachedDb = require('db-cached') local handlers = require('handlers')(core) -- use cached db local db = cachedDb(core.db) local handleRequest = require('api')(db, args[2]) local app = require('weblit-app') require 'weblit-websocket' -- Listen on port 4822 app.bind({ host = "0.0.0.0", port = 4822, }) -- Log requests app.use(function (req, res, go) -- Record start time local now = uv.now() -- Process the request go() -- And then log after everything is done, inserting a header for the delay local delay = (uv.now() - now) .. "ms" res.headers["X-Request-Time"] = delay local useragent = req.headers["user-agent"] if useragent then log("http", string.format("%s %s %s %s %s", req.method, req.path, useragent, res.code, delay )) end end) app.use(require('weblit-auto-headers')) .route({ method = "GET", path = "/snapshots"}, require('snapshots')) .route({ method = "GET", path = "/stats"}, require('stats')) -- Handle websocket clients app.websocket({ protocol = "lit" }, function (req, read, write) -- Log the client connection local peerName = req.socket:getpeername() peerName = peerName.ip .. ':' .. peerName.port log("client connected", peerName) -- Process the client using server handles local remote = makeRemote(read, write) local success, err = xpcall(function () for command, data in remote.read do log("client command", peerName .. " - " .. command) local handler = handlers[command] if handler then handler(remote, data) else remote.writeAs("error", "no such command " .. command) end end remote.close() end, debug.traceback) if not success then log("client error", err, "err") remote.writeAs("error", string.match(err, ":%d+: *([^\n]*)")) remote.close() end log("client disconnected", peerName) end) app.use(function (req, res, go) if req.method == "OPTIONS" then -- Wide open CORS headers return { code = 204, {"Access-Control-Allow-Origin", "*"}, {'Access-Control-Allow-Credentials', 'true'}, {'Access-Control-Allow-Methods', 'GET, OPTIONS'}, -- Custom headers and headers various browsers *should* be OK with but aren't {'Access-Control-Allow-Headers', 'DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control'}, -- Tell client that this pre-flight info is valid for 20 days {'Access-Control-Max-Age', 1728000}, {'Content-Type', 'text/plain charset=UTF-8'}, {'Content-Length', 0}, } end go() -- Add CORS headers res.headers['Access-Control-Allow-Origin'] = '*' res.headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS' res.headers['Access-Control-Allow-Headers'] = 'DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control' end) -- Handle HTTP clients .use(handleRequest) .start() -- Never return so that the command keeps running. coroutine.yield() end
apache-2.0
czfshine/Don-t-Starve
data/scripts/prefabs/tentacle_arm.lua
1
4417
require "stategraphs/SGtentacle_arm" -- TODO -- change gotoState to eventpush -- move newcombat event handling to stategraph -- unset persistant flag local assets= { Asset("ANIM", "anim/tentacle_arm.zip"), Asset("ANIM", "anim/tentacle_arm_build.zip"), Asset("SOUND", "sound/tentacle.fsb"), } local prefabs = { "monstermeat", } local function retargetfn(inst) return FindEntity(inst, TUNING.TENTACLE_PILLAR_ARM_ATTACK_DIST, function(guy) if guy.components.combat and guy.components.health and not guy.components.health:IsDead() then return ( guy:HasTag("character") or guy:HasTag("monster") or guy:HasTag("animal")) and not guy:HasTag("WORM_DANGER") and not guy:HasTag("prey") and not (guy.prefab == inst.prefab) end end) end local function onfar(inst) inst:PushEvent("retract") end local function onnear(inst) inst:PushEvent("emerge") Dbg(inst,true,"ON NEAR - emerge") --[[ Very bad practice to directly set a state from outside the statemachine! if inst.sg:HasStateTag("idle") and not inst.sg:HasStateTag("emerge") and not inst.sg:HasStateTag("attack") and not inst.components.health:IsDead() then inst.sg:GoToState("emerge") end --]] end local function shouldKeepTarget(inst, target) if target and target:IsValid() and target.components.health and not target.components.health:IsDead() then local distsq = target:GetDistanceSqToInst(inst) --dprint(TUNING.TENTACLE_PILLAR_ARM_STOPATTACK_DIST," shouldkeeptarget:",distsq<TUNING.TENTACLE_PILLAR_ARM_STOPATTACK_DIST*TUNING.TENTACLE_PILLAR_ARM_STOPATTACK_DIST) return distsq < TUNING.TENTACLE_PILLAR_ARM_STOPATTACK_DIST*TUNING.TENTACLE_PILLAR_ARM_STOPATTACK_DIST else return false end end local function OnHit(inst, attacker, damage) if attacker.components.combat and attacker ~= GetPlayer() and math.random() > 0.5 then -- Followers should stop hitting the pillar attacker.components.combat:SetTarget(nil) if inst.components.health.currenthealth and inst.components.health.currenthealth < 0 then inst.components.health:DoDelta(damage*.6, false, attacker) end end end local function fn(Sim) local ARM_SCALE = 0.95 local inst = CreateEntity() inst.persists = false -- don't need to save these inst.entity:AddTransform() inst.Transform:SetScale(ARM_SCALE, ARM_SCALE, ARM_SCALE) inst.entity:AddPhysics() inst.Physics:SetCylinder(0.6,2) inst.entity:AddAnimState() inst.AnimState:SetBank("tentacle_arm") inst.AnimState:SetScale(ARM_SCALE,ARM_SCALE) inst.AnimState:SetBuild("tentacle_arm_build") inst.AnimState:PlayAnimation("breach_pre") inst.entity:AddSoundEmitter() -- inst.AnimState:SetMultColour(.2, 1, .2, 1.0) inst:AddTag("monster") inst:AddTag("hostile") inst:AddTag("wet") inst:AddTag("WORM_DANGER") inst:AddComponent("health") inst.components.health:SetMaxHealth(TUNING.TENTACLE_PILLAR_ARM_HEALTH) inst:AddComponent("combat") inst.components.combat:SetRange(TUNING.TENTACLE_PILLAR_ARM_ATTACK_DIST) inst.components.combat:SetDefaultDamage(TUNING.TENTACLE_PILLAR_ARM_DAMAGE) inst.components.combat:SetAttackPeriod(TUNING.TENTACLE_PILLAR_ARM_ATTACK_PERIOD) inst.components.combat:SetRetargetFunction(GetRandomWithVariance(1, 0.5), retargetfn) inst.components.combat:SetKeepTargetFunction(shouldKeepTarget) inst.components.combat:SetOnHit(OnHit) MakeLargeFreezableCharacter(inst) inst:AddComponent("playerprox") inst.components.playerprox:SetDist(4, 15) inst.components.playerprox:SetOnPlayerNear(onnear) inst.components.playerprox:SetOnPlayerFar(onfar) inst:AddComponent("sanityaura") inst.components.sanityaura.aura = -TUNING.SANITYAURA_MED inst:AddComponent("inspectable") inst:AddComponent("lootdropper") -- inst.components.lootdropper:SetLoot({"monstermeat", "monstermeat"}) -- inst.components.lootdropper:AddChanceLoot("tentaclespike", 0.5) -- inst.components.lootdropper:AddChanceLoot("tentaclespots", 0.2) inst:SetStateGraph("SGtentacle_arm") return inst end return Prefab( "cave/monsters/tentacle_pillar_arm", fn, assets, prefabs )
gpl-2.0
blueyed/awesome
tests/test-awful-widget-calendar_popup.lua
10
2181
--- Test for awful.widget.calendar local runner = require("_runner") local awful = require("awful") local calendar = require("awful.widget.calendar_popup") local wa = awful.screen.focused().workarea local cmonth = calendar.month() local cyear = calendar.year() local current_date = os.date("*t") local day, month, year = current_date.day, current_date.month, current_date.year local steps = { -- Check center geometry function(count) if count == 1 then cmonth:call_calendar(0, 'cc') else local geo = cmonth:geometry() assert( math.abs((wa.x + wa.width/2.0) - (geo.x + geo.width/2.0)) < 2 ) assert( math.abs((wa.y + wa.height/2.0) - (geo.y + geo.height/2.0)) < 2 ) return true end end, -- Check top-right geometry function(count) if count == 1 then cmonth:call_calendar(0, 'tr') else local geo = cmonth:geometry() assert(wa.x + wa.width == geo.x + geo.width) assert(wa.y == geo.y) return true end end, -- Check visibility function() local v = cyear.visible cyear:toggle() assert(v == not cyear.visible) return true end, -- Check current date function() local mdate = cmonth:get_widget():get_date() assert(mdate.day==day and mdate.month==month and mdate.year==year) local ydate = cyear:get_widget():get_date() assert(ydate.year==year) return true end, -- Check new date function(count) if count == 1 then -- Increment cmonth:call_calendar(1) cyear:call_calendar(-1) else local mdate = cmonth:get_widget():get_date() assert( mdate.day==nil and ((mdate.month==month+1 and mdate.year==year) or (mdate.month==1 and mdate.year==year+1)) ) local ydate = cyear:get_widget():get_date() assert(ydate.year==year-1) return true end end, } runner.run_steps(steps) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
TimSimpson/Macaroni
Main/Generators/Cpp/UnitNodeGenerator.lua
2
4055
require "Cpp/Common"; local Access = Macaroni.Model.Cpp.Access; local Context = Macaroni.Model.Context; local Node = Macaroni.Model.Node; local TypeNames = Macaroni.Model.TypeNames; UnitNodeFileGenerator = { iterateNodes = function (self, nodeChildren, writer) for i = 1, #(nodeChildren) do n = nodeChildren[i]; self:parseNode(n, writer); end end, createNamespaceFileGenerator = function (self, node, writer) return nil; end, memberIsInTargetLibrary = function(self, member) if MACARONI_VERSION ~= "0.1.0.23" then return member:OwnedBy(self.targetLibrary) else return member.Library == self.targetLibrary end end, parseClass = function (self, node, writer) assert(node.Member.TypeName == TypeNames.Class); log:Write("Time to parse class."); local cg = self:createClassGenerator(node, writer); log:Write("PFSF!"); cg:parse(); log:Write("Oh, that was a sweet parse!"); end, parseNamespace = function (self, node, writer) if (node.Member == nil or node.Member.TypeName ~= TypeNames.Namespace) then error("node argument must be namespace.", 2); end writer:CreateDirectory(); local ng = self:createNamespaceFileGenerator(node, writer); if (ng ~= nil and ng:hasEntriesInLibrary(self.targetLibrary)) then ng:parse(); end self:iterateNodes(node.Children, writer); end, parseNode = function (self, node, writer) log:Write("~~~ " .. node.FullName); if (not NodeHelper.worthIteration(node)) then log:Write(" Skipped.\n"); return; end local m = node.Member; if (m == nil) then return; end log:Write(" Same library. Generation time!"); local typeName = m.TypeName; log:Write("typeName = " .. m.TypeName); -- Don't generate Nodes from other libraries which are in this Context. if (typeName ~= TypeNames.Namespace and not self:memberIsInTargetLibrary(m)) then if (typeName ~= TypeNames.Typedef or node.HFilePath ~= nil) then log:Write(" Different library, not generating.\n"); return; end end log:Write(" " .. typeName); log:Write("writer = " .. tostring(writer)); local newPath = writer:NewPath("/" .. node.Name); --if (newPath.IsDirectory) then -- newPath.CreateDirectory(); --end local handlerFunc = nil; if (typeName == TypeNames.Namespace) then handlerFunc = self.parseNamespace; elseif (typeName == TypeNames.Class) then handlerFunc = self.parseClass; elseif (typeName == TypeNames.Typedef) then handlerFunc = self.parseTypedef; elseif (typeName == TypeNames.Function) then -- A type or namespace will handle these. return; elseif (typeName == TypeNames.Variable) then -- A type or namespace will handle these. return; else error("I don't think the code should be here..." .. node.FullName) end if (handlerFunc ~= nil) then handlerFunc(self, node, newPath); else log:Write(" ~ Skipping"); end log:Write(" ^-- Conclude parse."); end, parseTypedef = function (self, node, writer) log:Error("Not implemented.") error("Not implemented (yet)") if (node.Member == nil or node.Member.TypeName ~= TypeNames.Typedef) then error("node argument must be typedef.", 2); end -- writer:CreateDirectory(); local ng = self:createTypedefFileGenerator(node, writer); if (ng ~= nil and ng:hasEntriesInLibrary(self.targetLibrary)) then ng:parse(); end self:iterateNodes(node.Children, writer); end, };
apache-2.0
ioiasff/creawq
bot/utils.lua
646
23489
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
czfshine/Don-t-Starve
data/DLC0001/scripts/components/burnable.lua
1
13553
local function OnKilled(inst) if inst.components.burnable and inst.components.burnable:IsBurning() then inst.AnimState:SetMultColour(.2,.2,.2,1) end end local function DoneBurning(inst) local burnable = inst.components.burnable if burnable then inst:RemoveTag("wildfirestarter") inst:RemoveTag("burnable") if burnable.dragonflypriority then inst:RemoveTag(burnable.dragonprioritytag[burnable.dragonflypriority]) end if burnable.onburnt then burnable.onburnt(inst) end if inst.components.explosive then --explosive explode inst.components.explosive:OnBurnt() end if burnable.extinguishimmediately then burnable:Extinguish() end end end local Burnable = Class(function(self, inst) self.inst = inst self.flammability = 1 self.fxdata = {} self.fxlevel = 1 self.fxchildren = {} self.burning = false self.burntime = nil self.extinguishimmediately = true self.onignite = nil self.onextinguish = nil self.onburnt = nil self.canlight = true self.lightningimmune = false self.smoldering = false self.inst:AddTag("wildfirestarter") self.inst:AddTag("burnable") self.inst:ListenForEvent("rainstart", function(it, data) inst:DoTaskInTime(2, function(inst) if self:IsSmoldering() then self:StopSmoldering() end end) end, GetWorld()) self.dragonprioritytag = { "dragonflybait_lowprio", "dragonflybait_medprio", "dragonflybait_highprio", } end) --- Set the function that will be called when the object starts burning function Burnable:SetOnIgniteFn(fn) self.onignite = fn end --- Set the function that will be called when the object has burned completely function Burnable:SetOnBurntFn(fn) self.onburnt = fn end --- Set the function that will be called when the object stops burning function Burnable:SetOnExtinguishFn(fn) self.onextinguish = fn end --- Set the prefab to use for the burning effect. Overrides the default function Burnable:SetBurningFX(name) self.fxprefab = name end function Burnable:SetBurnTime(time) self.burntime = time end function Burnable:IsSmoldering() return self.smoldering end --- Add an effect to be spawned when burning -- @param prefab The prefab to spawn as the effect -- @param offset The offset from the burning entity/symbol that the effect should appear at -- @param followsymbol Optional symbol for the effect to follow function Burnable:AddBurnFX(prefab, offset, followsymbol) table.insert(self.fxdata, {prefab=prefab, x = offset.x, y = offset.y, z = offset.z, follow=followsymbol}) end --- Set the level of any current or future burning effects function Burnable:SetFXLevel(level, percent) self.fxlevel = level for k,v in pairs(self.fxchildren) do if v.components.firefx then v.components.firefx:SetLevel(level) v.components.firefx:SetPercentInLevel(percent or 1) end end end function Burnable:GetLargestLightRadius() local largestRadius = nil for k,v in pairs(self.fxchildren) do if v.Light and v.Light:IsEnabled() then local radius = v.Light:GetCalculatedRadius() if not largestRadius or radius > largestRadius then largestRadius = radius end end end return largestRadius end function Burnable:IsBurning() return self.burning end function Burnable:GetDebugString() return string.format("%s ", self.burning and "BURNING" or "NOT BURNING") end function Burnable:OnRemoveEntity() self:StopSmoldering() self:KillFX() end function Burnable:StartWildfire() if not self.burning and not self.smoldering and not self.inst:HasTag("fireimmune") then self.smoldering = true self.inst:AddTag("smolder") self.smoke = SpawnPrefab("smoke_plant") if self.smoke then if #self.fxdata == 1 and self.fxdata[1].follow then local follower = self.smoke.entity:AddFollower() follower:FollowSymbol( self.inst.GUID, self.fxdata[1].follow, self.fxdata[1].x,self.fxdata[1].y,self.fxdata[1].z) else self.inst:AddChild(self.smoke) end self.smoke.Transform:SetPosition(0,0,0) end print("Starting a wildfire with "..self.inst.prefab) self.smolder_task = self.inst:DoTaskInTime(math.random(TUNING.MIN_SMOLDER_TIME, TUNING.MAX_SMOLDER_TIME), function() if self.inst then self:Ignite() end self.smolder_task = nil end) end end function Burnable:MakeNotWildfireStarter() self.inst:RemoveTag("wildfirestarter") self.no_wildfire = true end function Burnable:MakeDragonflyBait(priority) if self.dragonflypriority then self.inst:RemoveTag(self.dragonprioritytag[self.dragonflypriority]) end self.dragonflypriority = priority or 1 self.inst:AddTag(self.dragonprioritytag[self.dragonflypriority]) end function Burnable:Ignite(immediate) if not self.burning and not self.inst:HasTag("fireimmune") then if self.smoldering then self.smoldering = false self.inst:RemoveTag("smolder") if self.inst.components.inspectable then self.inst.components.inspectable.smoldering = false end if self.smoke then self.smoke.SoundEmitter:KillSound("smolder") self.smoke:Remove() end end self.inst:AddTag("fire") self.burning = true self.inst:RemoveTag("wildfirestarter") if self.dragonflypriority then self.inst:RemoveTag(self.dragonprioritytag[self.dragonflypriority]) end self.inst:ListenForEvent("death", OnKilled) self:SpawnFX(immediate) self.inst:PushEvent("onignite") if self.onignite then self.onignite(self.inst) end if self.inst.components.explosive then --explosive on ignite self.inst.components.explosive:OnIgnite() end if self.inst.components.fueled then self.inst.components.fueled:StartConsuming() end if self.inst.components.propagator then self.inst.components.propagator:StartSpreading() end if self.burntime then if self.task then self.task:Cancel() self.task = nil end self.task = self.inst:DoTaskInTime(self.burntime, DoneBurning) end end end function Burnable:LongUpdate(dt) --kind of a coarse assumption... if self.burning then if self.task then self.task:Cancel() self.task = nil end DoneBurning(self.inst) end end function Burnable:SmotherSmolder(smotherer) if smotherer and smotherer.components.finiteuses then smotherer.components.finiteuses:Use() elseif smotherer and smotherer.components.stackable then smotherer.components.stackable:Get(1):Remove() elseif smotherer and smotherer.components.health and smotherer.components.combat then smotherer.components.health:DoFireDamage(TUNING.SMOTHER_DAMAGE, nil, true) smotherer:PushEvent("burnt") end self:StopSmoldering() end function Burnable:StopSmoldering() if self.smoldering then if self.smoke then self.smoke.SoundEmitter:KillSound("smolder") self.smoke:Remove() end self.smoldering = false self.inst:RemoveTag("smolder") if self.smolder_task then self.smolder_task:Cancel() self.smolder_task = nil end end end function Burnable:RestoreInventoryItemData() if self.inst.inventoryitemdata and not self.inst.inventoryitem then self.inst:AddComponent("inventoryitem") if self.inst.inventoryitemdata["foleysound"] then self.inst.components.inventoryitem.foleysound = self.inst.inventoryitemdata["foleysound"] end if self.inst.inventoryitemdata["onputininventoryfn"] then self.inst.components.inventoryitem.onputininventoryfn = self.inst.inventoryitemdata["onputininventoryfn"] end if self.inst.inventoryitemdata["cangoincontainer"] then self.inst.components.inventoryitem.cangoincontainer = self.inst.inventoryitemdata["cangoincontainer"] end if self.inst.inventoryitemdata["nobounce"] then self.inst.components.inventoryitem.nobounce = self.inst.inventoryitemdata["nobounce"] end if self.inst.inventoryitemdata["canbepickedup"] then self.inst.components.inventoryitem.canbepickedup = self.inst.inventoryitemdata["canbepickedup"] end if self.inst.inventoryitemdata["imagename"] then self.inst.components.inventoryitem.imagename = self.inst.inventoryitemdata["imagename"] self.inst:PushEvent("imagechange") end if self.inst.inventoryitemdata["atlasname"] then self.inst.components.inventoryitem.atlasname = self.inst.inventoryitemdata["atlasname"] end if self.inst.inventoryitemdata["ondropfn"] then self.inst.components.inventoryitem.ondropfn = self.inst.inventoryitemdata["ondropfn"] end if self.inst.inventoryitemdata["onpickupfn"] then self.inst.components.inventoryitem.onpickupfn = self.inst.inventoryitemdata["onpickupfn"] end if self.inst.inventoryitemdata["trappable"] then self.inst.components.inventoryitem.trappable = self.inst.inventoryitemdata["trappable"] end if self.inst.inventoryitemdata["isnew"] then self.inst.components.inventoryitem.isnew = self.inst.inventoryitemdata["isnew"] end if self.inst.inventoryitemdata["keepondeath"] then self.inst.components.inventoryitem.keepondeath = self.inst.inventoryitemdata["keepondeath"] end if self.inst.inventoryitemdata["onactiveitemfn"] then self.inst.components.inventoryitem.onactiveitemfn = self.inst.inventoryitemdata["onactiveitemfn"] end if self.inst.inventoryitemdata["candrop"] then self.inst.components.inventoryitem.candrop = self.inst.inventoryitemdata["candrop"] end end end function Burnable:Extinguish(resetpropagator, pct, smotherer) if self.smoldering then if self.smoke then self.smoke.SoundEmitter:KillSound("smolder") self.smoke:Remove() end self.smoldering = false self.inst:RemoveTag("smolder") if self.smolder_task then self.smolder_task:Cancel() self.smolder_task = nil end end if smotherer and smotherer.components.finiteuses then smotherer.components.finiteuses:Use() elseif smotherer and smotherer.components.stackable then smotherer.components.stackable:Get(1):Remove() end if not self.no_wildfire then self.inst:AddTag("wildfirestarter") end if self.dragonflypriority then self.inst:AddTag(self.dragonprioritytag[self.dragonflypriority]) end if self.burning then if self.task then self.task:Cancel() self.task = nil end if self.inst.components.propagator then if resetpropagator then self.inst.components.propagator:StopSpreading(true, pct) else self.inst.components.propagator:StopSpreading() end end self:RestoreInventoryItemData() self.inst:RemoveTag("fire") self.burning = false self:KillFX() if self.inst.components.fueled then self.inst.components.fueled:StopConsuming() end if self.onextinguish then self.onextinguish(self.inst) end self.inst:PushEvent("onextinguish") end end function Burnable:SpawnFX(immediate) self:KillFX() if not self.fxdata then self.fxdata = { x = 0, y = 0, z = 0, level=self:GetDefaultFXLevel() } end if self.fxdata then for k,v in pairs(self.fxdata) do local fx = SpawnPrefab(v.prefab) if fx then fx.Transform:SetScale(self.inst.Transform:GetScale()) if v.follow then local follower = fx.entity:AddFollower() follower:FollowSymbol( self.inst.GUID, v.follow, v.x,v.y,v.z) else self.inst:AddChild(fx) fx.Transform:SetPosition(v.x, v.y, v.z) end table.insert(self.fxchildren, fx) if fx.components.firefx then fx.components.firefx:SetLevel(self.fxlevel, immediate) end end end end end function Burnable:KillFX() for k,v in pairs(self.fxchildren) do if v.components.firefx and v.components.firefx:Extinguish() then v:ListenForEvent("animover", function(inst) inst:Remove() end) --remove once the pst animation has finished else v:Remove() end self.fxchildren[k] = nil end end function Burnable:OnRemoveFromEntity() self:StopSmoldering() self:Extinguish() self.inst:RemoveTag("wildfirestarter") self.inst:RemoveTag("burnable") if self.dragonflypriority then self.inst:RemoveTag(self.dragonprioritytag[self.dragonflypriority]) end if self.task then self.task:Cancel() self.task = nil end end function Burnable:CollectSceneActions(doer, actions) if doer.components.health and self:IsSmoldering() then table.insert(actions, ACTIONS.SMOTHER) end end return Burnable
gpl-2.0
fabiopichler/FPM-Player
themes/omicron-media-player/RecorderWindow.lua
1
8728
--[[ ******************************************************************************* Omicron Media Player Author: Fábio Pichler Website: http://fabiopichler.net License: BSD 3-Clause License Copyright (c) 2015-2019, Fábio Pichler All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Omicron Media Player nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************* --]] ------------------------------------------------------------------------------- -- new() -- ------------------------------------------------------------------------------- mainWindow = Widget.new(m_mainWindow) titleBarWidget = Widget.new(m_titleBar) local centralWidget = Widget.new(m_centralWidget) local statusWidget = Widget.new() local menuBar = Widget.new(m_menuBar) local playlistView = Widget.new(m_playlistView) local playButton = PushButton.new(m_playButton) local stopButton = PushButton.new(m_stopButton) local recordButton = PushButton.new(m_recordButton) local timeLabel = Label.new(m_timeLabel) local statusLabel = Label.new(m_statusLabel) local leftChProgressBar = ProgressBar.new(m_leftChProgressBar) local rightChProgressBar = ProgressBar.new(m_rightChProgressBar) local timeSlider = Slider.new(m_timeSlider) local deviceComboBox = ComboBox.new(m_deviceComboBox) local encoderComboBox = ComboBox.new(m_encoderComboBox) local bitrateComboBox = ComboBox.new(m_bitrateComboBox) local deleteButton = PushButton.new(m_deleteButton) ------------------------------------------------------------------------------- -- setObjectName() -- ------------------------------------------------------------------------------- mainWindow:setObjectName("window") --titleBarWidget:setObjectName("") --centralWidget:setObjectName("") statusWidget:setObjectName("statusWidget") --menuBar:setObjectName("") --playlistView:setObjectName("") playButton:setObjectName("playButton") stopButton:setObjectName("stopButton") recordButton:setObjectName("recordButton") timeLabel:setObjectName("timeLabel") statusLabel:setObjectName("statusLabel") leftChProgressBar:setObjectName("channelsProgressBar") rightChProgressBar:setObjectName("channelsProgressBar") timeSlider:setObjectName("timeSlider") ------------------------------------------------------------------------------- -- setToolTip() -- ------------------------------------------------------------------------------- mainWindow:setToolTip("") titleBarWidget:setToolTip("") centralWidget:setToolTip("") statusWidget:setToolTip("") menuBar:setToolTip("") --playlistView:setToolTip("") playButton:setToolTip("") stopButton:setToolTip("") recordButton:setToolTip("") timeLabel:setToolTip("") statusLabel:setToolTip("") leftChProgressBar:setToolTip("") rightChProgressBar:setToolTip("") ------------------------------------------------------------------------------- -- setText() -- ------------------------------------------------------------------------------- timeLabel:setText("--:--:--") statusLabel:setText("---") ------------------------------------------------------------------------------- -- setEnabled() -- ------------------------------------------------------------------------------- timeSlider:setEnabled(false) stopButton:setEnabled(false) ------------------------------------------------------------------------------- -- setTextVisible() -- ------------------------------------------------------------------------------- leftChProgressBar:setTextVisible(false) rightChProgressBar:setTextVisible(false) ------------------------------------------------------------------------------- -- setAlignment() -- ------------------------------------------------------------------------------- statusLabel:setAlignment(Alignment.AlignCenter) ------------------------------------------------------------------------------- -- setOrientation() -- ------------------------------------------------------------------------------- leftChProgressBar:setOrientation(Orientation.Horizontal) rightChProgressBar:setOrientation(Orientation.Horizontal) timeSlider:setOrientation(Orientation.Horizontal) ------------------------------------------------------------------------------- -- setInvertedAppearance() -- ------------------------------------------------------------------------------- leftChProgressBar:setInvertedAppearance(true) ------------------------------------------------------------------------------- -- setMaximumHeight() -- ------------------------------------------------------------------------------- statusWidget:setMaximumHeight(20) ------------------------------------------------------------------------------- -- setMaximumHeight() -- ------------------------------------------------------------------------------- statusLabel:setMinimumWidth(110) ------------------------------------------------------------------------------- -- require -- ------------------------------------------------------------------------------- require "TitleBar" ------------------------------------------------------------------------------- -- BoxLayout -- ------------------------------------------------------------------------------- local menuLayout = BoxLayout.new(BoxLayout.Vertical) menuLayout:setContentsMargins(0, 0, 0, 8) menuLayout:addWidget(menuBar) ----------------------------------------------------------- local statusLayout = BoxLayout.new(BoxLayout.Horizontal) statusLayout:setSpacing(0) statusLayout:setMargin(0) statusLayout:addWidget(statusLabel, 1) statusWidget:setLayout(statusLayout) ----------------------------------------------------------- local topLayout = BoxLayout.new(BoxLayout.Horizontal) topLayout:setSpacing(8) topLayout:setContentsMargins(8, 0, 8, 8) topLayout:addWidget(deviceComboBox) topLayout:addWidget(encoderComboBox) topLayout:addWidget(bitrateComboBox) topLayout:addWidget(deleteButton) ----------------------------------------------------------- local playlistLayout = BoxLayout.new(BoxLayout.Vertical) playlistLayout:setContentsMargins(8, 0, 8, 8) playlistLayout:addWidget(playlistView) ----------------------------------------------------------- local infoLayout = BoxLayout.new(BoxLayout.Horizontal) infoLayout:setSpacing(8) infoLayout:setContentsMargins(8, 0, 8, 0) infoLayout:addWidget(timeLabel) infoLayout:addWidget(timeSlider) ----------------------------------------------------------- local channelLayout = BoxLayout.new(BoxLayout.Horizontal) channelLayout:setSpacing(1) channelLayout:addWidget(leftChProgressBar) channelLayout:addWidget(rightChProgressBar) ----------------------------------------------------------- local bottomLayout = BoxLayout.new(BoxLayout.Horizontal) bottomLayout:setSpacing(5) bottomLayout:setContentsMargins(8, 8, 8, 8) bottomLayout:addWidget(recordButton) bottomLayout:addWidget(stopButton) bottomLayout:addWidget(playButton) bottomLayout:addLayout(channelLayout, 1) bottomLayout:addWidget(statusWidget) ----------------------------------------------------------- local mainLayout = BoxLayout.new(BoxLayout.Vertical) mainLayout:setSpacing(0) mainLayout:setMargin(0) mainLayout:addWidget(titleBarWidget) mainLayout:addLayout(menuLayout) mainLayout:addLayout(topLayout) mainLayout:addLayout(playlistLayout) mainLayout:addLayout(infoLayout) mainLayout:addLayout(bottomLayout) centralWidget:setLayout(mainLayout)
bsd-3-clause
StoneDot/luasocket
test/smtptest.lua
44
5376
local sent = {} local from = "diego@localhost" local server = "localhost" local rcpt = "luasocket@localhost" local files = { "/var/spool/mail/luasocket", "/var/spool/mail/luasock1", "/var/spool/mail/luasock2", "/var/spool/mail/luasock3", } local t = socket.time() local err dofile("mbox.lua") local parse = mbox.parse dofile("testsupport.lua") local total = function() local t = 0 for i = 1, #sent do t = t + sent[i].count end return t end local similar = function(s1, s2) return string.lower(string.gsub(s1, "%s", "")) == string.lower(string.gsub(s2, "%s", "")) end local fail = function(s) s = s or "failed!" print(s) os.exit() end local readfile = function(name) local f = io.open(name, "r") if not f then fail("unable to open file!") return nil end local s = f:read("*a") f:close() return s end local empty = function() for i,v in ipairs(files) do local f = io.open(v, "w") if not f then fail("unable to open file!") end f:close() end end local get = function() local s = "" for i,v in ipairs(files) do s = s .. "\n" .. readfile(v) end return s end local check_headers = function(sent, got) sent = sent or {} got = got or {} for i,v in pairs(sent) do if not similar(v, got[i]) then fail("header " .. v .. "failed!") end end end local check_body = function(sent, got) sent = sent or "" got = got or "" if not similar(sent, got) then fail("bodies differ!") end end local check = function(sent, m) io.write("checking ", m.headers.title, ": ") for i = 1, #sent do local s = sent[i] if s.title == m.headers.title and s.count > 0 then check_headers(s.headers, m.headers) check_body(s.body, m.body) s.count = s.count - 1 print("ok") return end end fail("not found") end local insert = function(sent, message) if type(message.rcpt) == "table" then message.count = #message.rcpt else message.count = 1 end message.headers = message.headers or {} message.headers.title = message.title table.insert(sent, message) end local mark = function() local time = socket.time() return { time = time } end local wait = function(sentinel, n) local to io.write("waiting for ", n, " messages: ") while 1 do local mbox = parse(get()) if n == #mbox then break end if socket.time() - sentinel.time > 50 then to = 1 break end socket.sleep(1) io.write(".") io.stdout:flush() end if to then fail("timeout") else print("ok") end end local stuffed_body = [[ This message body needs to be stuffed because it has a dot . by itself on a line. Otherwise the mailer would think that the dot . is the end of the message and the remaining text would cause a lot of trouble. ]] insert(sent, { from = from, rcpt = { "luasocket@localhost", "luasock3@dell-diego.cs.princeton.edu", "luasock1@dell-diego.cs.princeton.edu" }, body = "multiple rcpt body", title = "multiple rcpt", }) insert(sent, { from = from, rcpt = { "luasock2@localhost", "luasock3", "luasock1" }, headers = { header1 = "header 1", header2 = "header 2", header3 = "header 3", header4 = "header 4", header5 = "header 5", header6 = "header 6", }, body = stuffed_body, title = "complex message", }) insert(sent, { from = from, rcpt = rcpt, server = server, body = "simple message body", title = "simple message" }) insert(sent, { from = from, rcpt = rcpt, server = server, body = stuffed_body, title = "stuffed message body" }) insert(sent, { from = from, rcpt = rcpt, headers = { header1 = "header 1", header2 = "header 2", header3 = "header 3", header4 = "header 4", header5 = "header 5", header6 = "header 6", }, title = "multiple headers" }) insert(sent, { from = from, rcpt = rcpt, title = "minimum message" }) io.write("testing host not found: ") local c, e = socket.connect("wrong.host", 25) local ret, err = socket.smtp.mail{ from = from, rcpt = rcpt, server = "wrong.host" } if ret or e ~= err then fail("wrong error message") else print("ok") end io.write("testing invalid from: ") local ret, err = socket.smtp.mail{ from = ' " " (( _ * ', rcpt = rcpt, } if ret or not err then fail("wrong error message") else print(err) end io.write("testing no rcpt: ") local ret, err = socket.smtp.mail{ from = from, } if ret or not err then fail("wrong error message") else print(err) end io.write("clearing mailbox: ") empty() print("ok") io.write("sending messages: ") for i = 1, #sent do ret, err = socket.smtp.mail(sent[i]) if not ret then fail(err) end io.write("+") io.stdout:flush() end print("ok") wait(mark(), total()) io.write("parsing mailbox: ") local mbox = parse(get()) print(#mbox .. " messages found!") for i = 1, #mbox do check(sent, mbox[i]) end print("passed all tests") print(string.format("done in %.2fs", socket.time() - t))
mit
matthewhesketh/mattata
plugins/meme.lua
2
12424
--[[ Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]] local meme = {} local mattata = require('mattata') function meme:init() meme.commands = mattata.commands(self.info.username) :command('meme') :command('memegen').table meme.help = '/meme <top line> | <bottom line> - Generates an image macro with the given text, on your choice of the available selection of templates. This command can only be used inline. Alias: /memegen.' end function meme.escape(str) if not str or type(str) ~= 'string' then return str end str = str:lower() return str :gsub('%s', '_') :gsub('%?', '~q') :gsub('%%', '~p') :gsub('#', '~h') :gsub('/', '~s') :gsub('"', '\'\'') end meme.memes = { 'ggg', 'elf', 'fwp', 'yuno', 'aag', 'badchoice', 'happening', 'scc', 'sad-obama', 'fbf', 'ants', 'ive', 'biw', 'crazypills', 'remembers', 'oag', 'ski', 'oprah', 'wonka', 'regret', 'fa', 'keanu', 'kermit', 'both', 'awkward', 'dodgson', 'bad', 'mmm', 'ch', 'live', 'firsttry', 'noidea', 'sad-biden', 'buzz', 'blb', 'fry', 'morpheus', 'cbg', 'xy', 'rollsafe', 'yodawg', 'fetch', 'sarcasticbear', 'cb', 'hipster', 'success', 'bd', 'bender', 'fine', 'bs', 'toohigh', 'mw', 'money', 'interesting', 'sb', 'doge', 'ermg', 'fmr', 'sparta', 'older', 'philosoraptor', 'awkward-awesome', 'awesome', 'chosen', 'alwaysonbeat', 'ackbar', 'sadfrog', 'sohot', 'imsorry', 'tenguy', 'winter', 'red', 'awesome-awkward', 'jw', 'sf', 'ss', 'patrick', 'center', 'boat', 'saltbae', 'tried', 'mb', 'hagrid', 'mordor', 'snek', 'sad-bush', 'nice', 'sad-clinton', 'afraid', 'stew', 'icanhas', 'away', 'dwight', 'facepalm', 'yallgot', 'jetpack', 'captain', 'inigo', 'iw', 'dsm', 'sad-boehner', 'll', 'joker', 'sohappy', 'officespace' } meme.meme_info = { ['tenguy'] = { ['width'] = 600, ['height'] = 544 }, ['afraid'] = { ['width'] = 600, ['height'] = 588 }, ['older'] = { ['width'] = 600, ['height'] = 255 }, ['aag'] = { ['width'] = 600, ['height'] = 502 }, ['tried'] = { ['width'] = 600, ['height'] = 600 }, ['biw'] = { ['width'] = 600, ['height'] = 450 }, ['stew'] = { ['width'] = 600, ['height'] = 448 }, ['blb'] = { ['width'] = 600, ['height'] = 600 }, ['kermit'] = { ['width'] = 600, ['height'] = 421 }, ['bd'] = { ['width'] = 600, ['height'] = 597 }, ['ch'] = { ['width'] = 600, ['height'] = 450 }, ['cbg'] = { ['width'] = 600, ['height'] = 368 }, ['wonka'] = { ['width'] = 600, ['height'] = 431 }, ['cb'] = { ['width'] = 600, ['height'] = 626 }, ['keanu'] = { ['width'] = 600, ['height'] = 597 }, ['dsm'] = { ['width'] = 600, ['height'] = 900 }, ['live'] = { ['width'] = 600, ['height'] = 405 }, ['ants'] = { ['width'] = 600, ['height'] = 551 }, ['doge'] = { ['width'] = 600, ['height'] = 600 }, ['alwaysonbeat'] = { ['width'] = 600, ['height'] = 337 }, ['ermg'] = { ['width'] = 600, ['height'] = 901 }, ['facepalm'] = { ['width'] = 600, ['height'] = 529 }, ['firsttry'] = { ['width'] = 600, ['height'] = 440 }, ['fwp'] = { ['width'] = 600, ['height'] = 423 }, ['fa'] = { ['width'] = 600, ['height'] = 600 }, ['fbf'] = { ['width'] = 600, ['height'] = 597 }, ['fmr'] = { ['width'] = 600, ['height'] = 385 }, ['fry'] = { ['width'] = 600, ['height'] = 449 }, ['ggg'] = { ['width'] = 600, ['height'] = 375 }, ['hipster'] = { ['width'] = 600, ['height'] = 899 }, ['icanhas'] = { ['width'] = 600, ['height'] = 874 }, ['crazypills'] = { ['width'] = 600, ['height'] = 408 }, ['mw'] = { ['width'] = 600, ['height'] = 441 }, ['noidea'] = { ['width'] = 600, ['height'] = 382 }, ['regret'] = { ['width'] = 600, ['height'] = 536 }, ['boat'] = { ['width'] = 600, ['height'] = 441 }, ['hagrid'] = { ['width'] = 600, ['height'] = 446 }, ['sohappy'] = { ['width'] = 600, ['height'] = 700 }, ['captain'] = { ['width'] = 600, ['height'] = 439 }, ['bender'] = { ['width'] = 600, ['height'] = 445 }, ['inigo'] = { ['width'] = 600, ['height'] = 326 }, ['iw'] = { ['width'] = 600, ['height'] = 600 }, ['ackbar'] = { ['width'] = 600, ['height'] = 777 }, ['happening'] = { ['width'] = 600, ['height'] = 364 }, ['joker'] = { ['width'] = 600, ['height'] = 554 }, ['ive'] = { ['width'] = 600, ['height'] = 505 }, ['ll'] = { ['width'] = 600, ['height'] = 399 }, ['away'] = { ['width'] = 600, ['height'] = 337 }, ['morpheus'] = { ['width'] = 600, ['height'] = 363 }, ['mb'] = { ['width'] = 600, ['height'] = 534 }, ['badchoice'] = { ['width'] = 600, ['height'] = 478 }, ['mmm'] = { ['width'] = 600, ['height'] = 800 }, ['jetpack'] = { ['width'] = 600, ['height'] = 450 }, ['imsorry'] = { ['width'] = 600, ['height'] = 337 }, ['red'] = { ['width'] = 600, ['height'] = 557 }, ['mordor'] = { ['width'] = 600, ['height'] = 353 }, ['oprah'] = { ['width'] = 600, ['height'] = 449 }, ['oag'] = { ['width'] = 600, ['height'] = 450 }, ['remembers'] = { ['width'] = 600, ['height'] = 458 }, ['philosoraptor'] = { ['width'] = 600, ['height'] = 600 }, ['jw'] = { ['width'] = 600, ['height'] = 401 }, ['patrick'] = { ['width'] = 600, ['height'] = 1056 }, ['rollsafe'] = { ['width'] = 600, ['height'] = 335 }, ['sad-obama'] = { ['width'] = 600, ['height'] = 600 }, ['sad-clinton'] = { ['width'] = 600, ['height'] = 542 }, ['sadfrog'] = { ['width'] = 600, ['height'] = 600 }, ['sad-bush'] = { ['width'] = 600, ['height'] = 455 }, ['sad-biden'] = { ['width'] = 600, ['height'] = 600 }, ['sad-boehner'] = { ['width'] = 600, ['height'] = 479 }, ['saltbae'] = { ['width'] = 600, ['height'] = 603 }, ['sarcasticbear'] = { ['width'] = 600, ['height'] = 450 }, ['dwight'] = { ['width'] = 600, ['height'] = 393 }, ['sb'] = { ['width'] = 600, ['height'] = 421 }, ['ss'] = { ['width'] = 600, ['height'] = 604 }, ['sf'] = { ['width'] = 600, ['height'] = 376 }, ['dodgson'] = { ['width'] = 600, ['height'] = 559 }, ['money'] = { ['width'] = 600, ['height'] = 337 }, ['snek'] = { ['width'] = 600, ['height'] = 513 }, ['sohot'] = { ['width'] = 600, ['height'] = 480 }, ['nice'] = { ['width'] = 600, ['height'] = 432 }, ['awesome-awkward'] = { ['width'] = 600, ['height'] = 601 }, ['awesome'] = { ['width'] = 600, ['height'] = 600 }, ['awkward-awesome'] = { ['width'] = 600, ['height'] = 600 }, ['awkward'] = { ['width'] = 600, ['height'] = 600 }, ['fetch'] = { ['width'] = 600, ['height'] = 450 }, ['success'] = { ['width'] = 600, ['height'] = 578 }, ['scc'] = { ['width'] = 600, ['height'] = 326 }, ['ski'] = { ['width'] = 600, ['height'] = 404 }, ['officespace'] = { ['width'] = 600, ['height'] = 501 }, ['interesting'] = { ['width'] = 600, ['height'] = 759 }, ['toohigh'] = { ['width'] = 600, ['height'] = 408 }, ['bs'] = { ['width'] = 600, ['height'] = 600 }, ['fine'] = { ['width'] = 600, ['height'] = 582 }, ['sparta'] = { ['width'] = 600, ['height'] = 316 }, ['center'] = { ['width'] = 600, ['height'] = 370 }, ['both'] = { ['width'] = 600, ['height'] = 600 }, ['winter'] = { ['width'] = 600, ['height'] = 460 }, ['xy'] = { ['width'] = 600, ['height'] = 455 }, ['buzz'] = { ['width'] = 600, ['height'] = 455 }, ['yodawg'] = { ['width'] = 600, ['height'] = 399 }, ['yuno'] = { ['width'] = 600, ['height'] = 450 }, ['yallgot'] = { ['width'] = 600, ['height'] = 470 }, ['bad'] = { ['width'] = 600, ['height'] = 450 }, ['elf'] = { ['width'] = 600, ['height'] = 369 }, ['chosen'] = { ['width'] = 600, ['height'] = 342 } } function meme.get_memes(offset, first_line, last_line) local first = ( offset and type(offset) == 'number' ) and offset + 1 or 1 local last = first + 49 if first >= last then return elseif last > #meme.memes then last = #meme.memes end local output = {} local id = first for i = first, last do local image = 'https://memegen.link/' .. meme.memes[i] .. '/' .. meme.escape(first_line) if last_line then image = image .. '/' .. meme.escape(last_line) end image = image .. '.jpg?font=impact' table.insert( output, mattata.inline_result() :type('photo') :id( tostring(id) ) :photo_url(image) :thumb_url(image) :photo_width( tostring(meme.meme_info[meme.memes[i]]['width']) ) :photo_height( tostring(meme.meme_info[meme.memes[i]]['height']) ) ) id = id + 1 end if last == #meme.memes then last = false end return output, last end function meme:on_inline_query(inline_query) local input = mattata.input(inline_query.query) if not input then return false end input = input:gsub('\n', ' | ') local first_line, last_line = input, false if input:match('^.- | .-$') then first_line, last_line = input:match('^(.-) | (.-)$') end first_line = first_line:gsub(' | ', ' ') if last_line then last_line = last_line:gsub(' | ', ' ') end local offset = inline_query.offset and tonumber(inline_query.offset) or 0 local output, next_offset = meme.get_memes( offset, first_line, last_line ) return mattata.answer_inline_query( inline_query.id, output, 0, false, next_offset and tostring(next_offset) or nil ) end function meme:on_message(message) return mattata.send_message( message.chat.id, 'This command can only be used inline!' ) end return meme
mit
ranisalt/forgottenserver
data/scripts/actions/others/doors.lua
5
9218
local openOddDoors = { [12695] = { locked = 13237, closed = 12692 }, [12703] = { locked = 13236, closed = 12701 }, [14635] = { locked = 14634, closed = 14633 }, [17435] = { locked = 14641, closed = 14640 }, [26533] = { locked = 26530, closed = 26529 }, [26534] = { locked = 26532, closed = 26531 }, [31176] = { locked = 31175, closed = 27559 }, [31024] = { locked = 31021, closed = 31020 }, [31025] = { locked = 31023, closed = 31022 }, [31541] = { locked = 31314, closed = 31314 }, [31542] = { locked = 31315, closed = 31315 }, [32691] = { locked = 32705, closed = 32689 }, [32692] = { locked = 32706, closed = 32690 }, [32695] = { locked = 32707, closed = 32693 }, [32696] = { locked = 32708, closed = 32694 }, [33432] = { locked = 33429, closed = 33428 }, [33433] = { locked = 33431, closed = 33430 }, [33493] = { locked = 33490, closed = 33489 }, [33494] = { locked = 33492, closed = 33491 }, [34152] = { locked = 34150, closed = 34150 }, [34153] = { locked = 34151, closed = 34151 }, [36292] = { locked = 36289, closed = 36288 }, [36293] = { locked = 36291, closed = 36290 }, [37596] = { locked = 37593, closed = 37592 }, [37597] = { locked = 37595, closed = 37594 }, [39119] = { locked = 39116, closed = 39115 }, [39120] = { locked = 39118, closed = 39117 } } local closedOddDoors = { [12692] = { locked = 13237, open = 12695 }, [12701] = { locked = 13236, open = 12703 }, [14633] = { locked = 14634, open = 14635 }, [14640] = { locked = 14641, open = 17435 }, [26529] = { locked = 26530, open = 26533 }, [26531] = { locked = 26532, open = 26534 }, [27559] = { locked = 31175, open = 31176 }, [31020] = { locked = 31021, open = 31024 }, [31022] = { locked = 31023, open = 31025 }, [31314] = { locked = 31314, open = 31541 }, [31315] = { locked = 31315, open = 31542 }, [32689] = { locked = 32705, open = 32691 }, [32690] = { locked = 32706, open = 32692 }, [32693] = { locked = 32707, open = 32695 }, [32694] = { locked = 32708, open = 32696 }, [33428] = { locked = 33429, open = 33432 }, [33430] = { locked = 33431, open = 33433 }, [33489] = { locked = 33490, open = 33493 }, [33491] = { locked = 33492, open = 33494 }, [34150] = { locked = 34150, open = 34152 }, [34151] = { locked = 34151, open = 34153 }, [36288] = { locked = 36289, open = 36292 }, [36290] = { locked = 36291, open = 36293 }, [37592] = { locked = 37593, open = 37596 }, [37594] = { locked = 37595, open = 37597 }, [39115] = { locked = 39116, open = 39119 }, [39117] = { locked = 39118, open = 39120 } } local lockedOddDoors = { [13237] = { closed = 12692, open = 12695 }, [13236] = { closed = 12701, open = 12703 }, [14634] = { closed = 14633, open = 14635 }, [14641] = { closed = 14640, open = 17435 }, [26530] = { closed = 26529, open = 26533 }, [26532] = { closed = 26531, open = 26534 }, [31175] = { closed = 27559, open = 31176 }, [31021] = { closed = 31020, open = 31024 }, [31023] = { closed = 31022, open = 31025 }, [32705] = { closed = 32689, open = 32691 }, [32706] = { closed = 32690, open = 32692 }, [32707] = { closed = 32693, open = 32695 }, [32708] = { closed = 32694, open = 32696 }, [33429] = { closed = 33428, open = 33432 }, [33431] = { closed = 33430, open = 33433 }, [33490] = { closed = 33489, open = 33493 }, [33492] = { closed = 33491, open = 33494 }, [36289] = { closed = 36288, open = 36292 }, [36291] = { closed = 36290, open = 36293 }, [37593] = { closed = 37592, open = 37596 }, [37595] = { closed = 37594, open = 37597 }, [39116] = { closed = 39115, open = 39119 }, [39118] = { closed = 39117, open = 39120 } } local positionOffsets = { {x = 1, y = 0}, -- east {x = 0, y = 1}, -- south {x = -1, y = 0}, -- west {x = 0, y = -1}, -- north } --[[ When closing a door with a creature in it findPushPosition will find the most appropriate adjacent position following a prioritization order. The function returns the position of the first tile that fulfills all the checks in a round. The function loops trough east -> south -> west -> north on each following line in that order. In round 1 it checks if there's an unhindered walkable tile without any creature. In round 2 it checks if there's a tile with a creature. In round 3 it checks if there's a tile blocked by a movable tile-blocking item. In round 4 it checks if there's a tile blocked by a magic wall or wild growth. ]] local function findPushPosition(creature, round) local pos = creature:getPosition() for _, offset in ipairs(positionOffsets) do local offsetPosition = Position(pos.x + offset.x, pos.y + offset.y, pos.z) local tile = Tile(offsetPosition) if tile then local creatureCount = tile:getCreatureCount() if round == 1 then if tile:queryAdd(creature) == RETURNVALUE_NOERROR and creatureCount == 0 then if not tile:hasFlag(TILESTATE_PROTECTIONZONE) or (tile:hasFlag(TILESTATE_PROTECTIONZONE) and creature:canAccessPz()) then return offsetPosition end end elseif round == 2 then if creatureCount > 0 then if not tile:hasFlag(TILESTATE_PROTECTIONZONE) or (tile:hasFlag(TILESTATE_PROTECTIONZONE) and creature:canAccessPz()) then return offsetPosition end end elseif round == 3 then local topItem = tile:getTopDownItem() if topItem then if topItem:getType():isMovable() then return offsetPosition end end else if tile:getItemById(ITEM_MAGICWALL) or tile:getItemById(ITEM_WILDGROWTH) then return offsetPosition end end end end if round < 4 then return findPushPosition(creature, round + 1) end end local door = Action() function door.onUse(player, item, fromPosition, target, toPosition, isHotkey) local itemId = item:getId() local transformTo = 0 if table.contains(closedQuestDoors, itemId) then if player:getStorageValue(item.actionid) ~= -1 or player:getGroup():getAccess() then item:transform(itemId + 1) player:teleportTo(toPosition, true) else player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "The door seems to be sealed against unwanted intruders.") end return true elseif table.contains(closedLevelDoors, itemId) then if item.actionid > 0 and player:getLevel() >= item.actionid - actionIds.levelDoor or player:getGroup():getAccess() then item:transform(itemId + 1) player:teleportTo(toPosition, true) else player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "Only the worthy may pass.") end return true elseif table.contains(keys, itemId) then local tile = Tile(toPosition) if not tile then return false end target = tile:getTopVisibleThing() if target.actionid == 0 then return false end if table.contains(keys, target.itemid) then return false end if not table.contains(openDoors, target.itemid) and not table.contains(closedDoors, target.itemid) and not table.contains(lockedDoors, target.itemid) then return false end if item.actionid ~= target.actionid then player:sendTextMessage(MESSAGE_STATUS_SMALL, "The key does not match.") return true end if lockedOddDoors[target.itemid] then transformTo = lockedOddDoors[target.itemid].open else transformTo = target.itemid + 2 end if table.contains(openDoors, target.itemid) then if openOddDoors[target.itemid] then transformTo = openOddDoors[target.itemid].locked else transformTo = target.itemid - 2 end elseif table.contains(closedDoors, target.itemid) then if closedOddDoors[target.itemid] then transformTo = closedOddDoors[target.itemid].locked else transformTo = target.itemid - 1 end end target:transform(transformTo) return true elseif table.contains(lockedDoors, itemId) then player:sendTextMessage(MESSAGE_INFO_DESCR, "It is locked.") return true elseif table.contains(openDoors, itemId) or table.contains(openExtraDoors, itemId) or table.contains(openHouseDoors, itemId) then local creaturePositionTable = {} local doorCreatures = Tile(toPosition):getCreatures() if doorCreatures and #doorCreatures > 0 then for _, doorCreature in pairs(doorCreatures) do local pushPosition = findPushPosition(doorCreature, 1) if not pushPosition then player:sendCancelMessage(RETURNVALUE_NOTENOUGHROOM) return true end table.insert(creaturePositionTable, {creature = doorCreature, position = pushPosition}) end for _, tableCreature in ipairs(creaturePositionTable) do tableCreature.creature:teleportTo(tableCreature.position, true) end end if openOddDoors[itemId] then transformTo = openOddDoors[itemId].closed else transformTo = itemId - 1 end item:transform(transformTo) return true elseif table.contains(closedDoors, itemId) or table.contains(closedExtraDoors, itemId) or table.contains(closedHouseDoors, itemId) then if closedOddDoors[itemId] then transformTo = closedOddDoors[itemId].open else transformTo = itemId + 1 end item:transform(transformTo) return true end return false end local doorTables = {keys, openDoors, closedDoors, lockedDoors, openExtraDoors, closedExtraDoors, openHouseDoors, closedHouseDoors, closedQuestDoors, closedLevelDoors} for _, doors in pairs(doorTables) do for _, doorId in pairs(doors) do door:id(doorId) end end door:register()
gpl-2.0
CrazyEddieTK/Zero-K
effects/gundam_artillery_explosion.lua
25
3488
-- artillery_explosion return { ["artillery_explosion"] = { dirt = { count = 4, ground = true, properties = { alphafalloff = 2, alwaysvisible = true, color = [[0.2, 0.1, 0.05]], pos = [[r-25 r25, 0, r-25 r25]], size = 30, speed = [[r1.5 r-1.5, 2, r1.5 r-1.5]], }, }, groundflash = { air = true, alwaysvisible = true, circlealpha = 0.6, circlegrowth = 9, flashalpha = 0.9, flashsize = 150, ground = true, ttl = 13, water = true, color = { [1] = 1, [2] = 0.20000000298023, [3] = 0.10000000149012, }, }, poof01 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 0.8, alwaysvisible = true, colormap = [[1.0 1.0 1.0 0.04 0.9 0.2 0.2 0.01 0.8 0.1 0.0 0.01]], directional = true, emitrot = 45, emitrotspread = 32, emitvector = [[0, 1, 0]], gravity = [[0, -0.05, 0]], numparticles = 8, particlelife = 10, particlelifespread = 0, particlesize = 30, particlesizespread = 0, particlespeed = 5, particlespeedspread = 5, pos = [[0, 2, 0]], sizegrowth = 1, sizemod = 1.0, texture = [[flashside1]], useairlos = false, }, }, pop1 = { air = true, class = [[heatcloud]], count = 2, ground = true, water = true, properties = { alwaysvisible = true, heat = 10, heatfalloff = 1.1, maxheat = 15, pos = [[r-2 r2, 5, r-2 r2]], size = 1, sizegrowth = 16, speed = [[0, 1 0, 0]], texture = [[crimsonnovaexplo]], }, }, smoke = { air = true, count = 4, ground = true, water = true, properties = { agespeed = 0.01, alwaysvisible = true, color = 0.1, pos = [[r-20 r20, 34, r-20 r20]], size = 50, sizeexpansion = 0.6, sizegrowth = 15, speed = [[r-2 r2, 1 r2.3, r-2 r2]], startsize = 10, }, }, whiteglow = { air = true, class = [[heatcloud]], count = 2, ground = true, water = true, properties = { alwaysvisible = true, heat = 10, heatfalloff = 3.5, maxheat = 15, pos = [[0, 0, 0]], size = 5, sizegrowth = 40, speed = [[0, 0, 0]], texture = [[laserend]], }, }, }, }
gpl-2.0
starkos/premake-core
src/base/container.lua
23
8189
--- -- container.lua -- Implementation of configuration containers. -- Copyright (c) 2014 Jason Perkins and the Premake project --- local p = premake p.container = {} local container = p.container --- -- Keep a master dictionary of container class, so they can be easily looked -- up by name (technically you could look at premake["name"] but that is just -- a coding convention and I don't want to count on it) --- container.classes = {} --- -- Define a new class of containers. -- -- @param name -- The name of the new container class. Used wherever the class needs to -- be shown to the end user in a readable way. -- @param parent (optional) -- If this class of container is intended to be contained within another, -- the containing class object. -- @param extraScopes (optional) -- Each container can hold fields scoped to itself (by putting the container's -- class name into its scope attribute), or any of the container's children. -- If a container can hold scopes other than these (i.e. "config"), it can -- provide a list of those scopes in this argument. -- @return -- If successful, the new class descriptor object (a table). Otherwise, -- returns nil and an error message. --- function container.newClass(name, parent, extraScopes) local class = p.configset.new(parent) class.name = name class.pluralName = name:plural() class.containedClasses = {} class.extraScopes = extraScopes if parent then table.insert(parent.containedClasses, class) end container.classes[name] = class return class end --- -- Create a new instance of a configuration container. This is just the -- generic base implementation, each container class will define their -- own version. -- -- @param parent -- The class of container being instantiated. -- @param name -- The name for the new container instance. -- @return -- A new container instance. --- function container.new(class, name) local self = p.configset.new() setmetatable(self, p.configset.metatable(self)) self.class = class self.name = name self.filename = name self.script = _SCRIPT self.basedir = os.getcwd() self.external = false for childClass in container.eachChildClass(class) do self[childClass.pluralName] = {} end return self end --- -- Add a new child to an existing container instance. -- -- @param self -- The container instance to hold the child. -- @param child -- The child container instance. --- function container.addChild(self, child) local children = self[child.class.pluralName] table.insert(children, child) children[child.name] = child child.parent = self child[self.class.name] = self if self.class.alias then child[self.class.alias] = self end end --- -- Process the contents of a container, which were populated by the project -- script, in preparation for doing work on the results, such as exporting -- project files. --- function container.bake(self) if self._isBaked then return self end self._isBaked = true local ctx = p.context.new(self) for key, value in pairs(self) do ctx[key] = value end local parent = self.parent if parent then ctx[parent.class.name] = parent end for class in container.eachChildClass(self.class) do for child in container.eachChild(self, class) do child.parent = ctx child[self.class.name] = ctx end end if type(self.class.bake) == "function" then self.class.bake(ctx) end return ctx end function container.bakeChildren(self) for class in container.eachChildClass(self.class) do local children = self[class.pluralName] for i = 1, #children do local ctx = container.bake(children[i]) children[i] = ctx children[ctx.name] = ctx end end end --- -- Returns true if the container can hold any of the specified field scopes. -- -- @param class -- The container class to test. -- @param scope -- A scope string (e.g. "project", "config") or an array of scope strings. -- @return -- True if this container can hold any of the specified scopes. --- function container.classCanContain(class, scope) if type(scope) == "table" then for i = 1, #scope do if container.classCanContain(class, scope[i]) then return true end end return false end -- if I have child classes, check with them first, since scopes -- are usually specified for leaf nodes in the hierarchy for child in container.eachChildClass(class) do if (container.classCanContain(child, scope)) then return true end end if class.name == scope or class.alias == scope then return true end -- is it in my extra scopes list? if class.extraScopes and table.contains(class.extraScopes, scope) then return true end return false end --- -- Return true if a container class is or inherits from the -- specified class. -- -- @param class -- The container class to be tested. -- @param scope -- The name of the class to be checked against. If the container -- class matches this scope (i.e. class is a project and the -- scope is "project"), or if it is a parent object of it (i.e. -- class is a workspace and scope is "project"), then returns -- true. --- function container.classIsA(class, scope) while class do if class.name == scope or class.alias == scope then return true end class = class.parent end return false end --- -- Enumerate all of the registered child classes of a specific container class. -- -- @param class -- The container class to be enumerated. -- @return -- An iterator function for the container's child classes. --- function container.eachChildClass(class) local children = class.containedClasses local i = 0 return function () i = i + 1 if i <= #children then return children[i] end end end --- -- Enumerate all of the registered child instances of a specific container. -- -- @param self -- The container to be queried. -- @param class -- The class of child containers to be enumerated. -- @return -- An iterator function for the container's child classes. --- function container.eachChild(self, class) local children = self[class.pluralName] local i = 0 return function () i = i + 1 if i <= #children then return children[i] end end end --- -- Retrieve the child container with the specified class and name. -- -- @param self -- The container instance to query. -- @param class -- The class of the child container to be fetched. -- @param name -- The name of the child container to be fetched. -- @return -- The child instance if it exists, nil otherwise. --- function container.getChild(self, class, name) local children = self[class.pluralName] return children[name] end --- -- Retrieve a container class object. -- -- @param name -- The name of the container class to retrieve. -- @return -- The container class object if it exists, nil otherwise. --- function container.getClass(name) return container.classes[name] end --- -- Determine if the container contains a child of the specified class which -- meets the criteria of a testing function. -- -- @param self -- The container to be queried. -- @param class -- The class of the child containers to be enumerated. -- @param func -- A function that takes a child container as its only argument, and -- returns true if it meets the selection criteria for the call. -- @return -- True if the test function returns true for any child. --- function container.hasChild(self, class, func) for child in container.eachChild(self, class) do if func(child) then return true end end end --- -- Call out to the container validation to make sure everything -- is as it should be before handing off to the actions. --- function container.validate(self) if type(self.class.validate) == "function" then self.class.validate(self) end end function container.validateChildren(self) for class in container.eachChildClass(self.class) do local children = self[class.pluralName] for i = 1, #children do container.validate(children[i]) end end end
bsd-3-clause
imfoollink/NPLRuntime
Client/trunk/externals/bullet3/btgui/GwenOpenGLTest/premake4.lua
6
1439
project "Test_Gwen_OpenGL" kind "ConsoleApp" flags {"Unicode"} defines { "GWEN_COMPILE_STATIC" , "_HAS_EXCEPTIONS=0", "_STATIC_CPPLIB" } defines { "DONT_USE_GLUT"} targetdir "../../bin" includedirs { "..", ".", } initOpenGL() initGlew() links { "gwen", } files { "../OpenGLWindow/OpenSans.cpp", "../OpenGLWindow/TwFonts.cpp", "../OpenGLWindow/TwFonts.h", "../OpenGLWindow/LoadShader.cpp", "../OpenGLWindow/LoadShader.h", "../OpenGLWindow/GLPrimitiveRenderer.cpp", "../OpenGLWindow/GLPrimitiveRenderer.h", "../OpenGLWindow/GwenOpenGL3CoreRenderer.h", "../OpenGLWindow/fontstash.cpp", "../OpenGLWindow/fontstash.h", "../OpenGLWindow/opengl_fontstashcallbacks.cpp", "../OpenGLWindow/opengl_fontstashcallbacks.h", "../Bullet3AppSupport/b3Clock.cpp", "../Bullet3AppSupport/b3Clock.h", "**.cpp", "**.h", } if os.is("Windows") then files { "../OpenGLWindow/Win32OpenGLWindow.cpp", "../OpenGLWindow/Win32OpenGLWindow.h", "../OpenGLWindow/Win32Window.cpp", "../OpenGLWindow/Win32Window.h", } end if os.is("Linux") then initX11() files{ "../OpenGLWindow/X11OpenGLWindow.h", "../OpenGLWindow/X11OpenGLWindow.cpp" } links{"pthread"} end if os.is("MacOSX") then links{"Cocoa.framework"} print("hello!") files{ "../OpenGLWindow/MacOpenGLWindow.mm", "../OpenGLWindow/MacOpenGLWindow.h", } end
gpl-2.0
tcprescott/DBM-VictorySound
localization.es.lua
2
1455
DBM_VictorySound_Translations = {} local L = DBM_VictorySound_Translations L.MainTab = "DBM-VictorySound - " --L.FileOptionsSubtab = "File Options" -- to be deleted L.StartOptionsSubtab = "Start Options" L.VictoryOptionsSubtab = "Victory Options" L.DefeatOptionsSubtab = "Defeat Options" L.VictorySound_Options = "VictorySound Options" L.Activate = "Enable VictorySound" L.AreaGeneral = "General Options" L.VictorySound_Victory = "Sound on Victory" L.VictorySound_Wipe = "Sound on Defeat" L.VictorySound_Start = "Music on Start" L.MasterSound = "Use master audio channel to play sound files." L.VictorySound_DisableMusic = "Override music settings for combat" L.StartWarning = "Notice: This setting is reliant on your music volume." L.AreaEnable = "Enable" L.VictoryPath = "Victory sound filename (in 'Wow/Interface/AddOns/DBM-VictorySound/sounds/')" L.WipePath = "Defeat sound filename (in 'Wow/Interface/AddOns/DBM-VictorySound/sounds/')" L.StartPath = "Start sound filename (in 'Wow/Interface/AddOns/DBM-VictorySound/sounds/')" L.VictoryAreaPath = "Victory Sound File Configuration" L.DefeatAreaPaths = "Defeat Sound File Configuration" L.StartAreaPaths = "Start Sound File Configuration" L.Button_ResetSettings = "Reset to Defaults" L.Button_Play = "Test" L.Button_Stop = "Stop" L.VictorySoundList = "Or choose a Premade Victory Sound" L.WipeSoundList = "Or choose a Premade Defeat Sound" L.StartSoundList = "Or choose a Premade Start Sound"
apache-2.0
rgieseke/textadept
modules/ansi_c/init.lua
1
4247
-- Copyright 2007-2022 Mitchell. See LICENSE. local M = {} --[[ This comment is for LuaDoc. --- -- The ansi_c module. -- It provides utilities for editing C code. -- @field autocomplete_snippets (boolean) -- Whether or not to include snippets in autocompletion lists. -- The default value is `true`. module('_M.ansi_c')]] -- Autocompletion and documentation. --- -- List of ctags files to use for autocompletion in addition to the current project's top-level -- *tags* file or the current directory's *tags* file. -- @class table -- @name tags M.tags = { _HOME .. '/modules/ansi_c/tags', _HOME .. '/modules/ansi_c/lua_tags', _USERHOME .. '/modules/ansi_c/tags' } M.autocomplete_snippets = true -- LuaFormatter off local XPM = textadept.editing.XPM_IMAGES local xpms = setmetatable({c=XPM.CLASS,d=XPM.SLOT,e=XPM.VARIABLE,f=XPM.METHOD,g=XPM.TYPEDEF,m=XPM.VARIABLE,s=XPM.STRUCT,t=XPM.TYPEDEF,v=XPM.VARIABLE},{__index=function()return 0 end}) -- LuaFormatter on textadept.editing.autocompleters.ansi_c = function() -- Retrieve the symbol behind the caret. local line, pos = buffer:get_cur_line() local symbol, op, part = line:sub(1, pos - 1):match('([%w_]-)([%.%->]*)([%w_]*)$') if symbol == '' and part == '' then return nil end -- nothing to complete if op ~= '' and op ~= '.' and op ~= '->' then return nil end -- Attempt to identify the symbol type. if symbol ~= '' then local decl = '([%w_]+)[%s%*&]+' .. symbol:gsub('%p', '%%%0') .. '[^%w_]' for i = buffer:line_from_position(buffer.current_pos) - 1, 1, -1 do local class = buffer:get_line(i):match(decl) if class then symbol = class break end end end -- Search through ctags for completions for that symbol. local tags_files = {} for i = 1, #M.tags do tags_files[#tags_files + 1] = M.tags[i] end tags_files[#tags_files + 1] = (io.get_project_root(buffer.filename) or lfs.currentdir()) .. '/tags' local name_patt = '^' .. part local sep = string.char(buffer.auto_c_type_separator) ::rescan:: local list = {} for _, filename in ipairs(tags_files) do if not lfs.attributes(filename) then goto continue end for tag_line in io.lines(filename) do local name = tag_line:match('^%S+') if (name:find(name_patt) and not name:find('^!') and not list[name]) or (name == symbol and op == '') then local fields = tag_line:match(';"\t(.*)$') local type = fields:match('class:(%S+)') or fields:match('enum:(%S+)') or fields:match('struct:(%S+)') or '' if type == symbol then list[#list + 1] = name .. sep .. xpms[fields:sub(1, 1)] list[name] = true elseif name == symbol and fields:match('typeref:') then -- For typeref, change the lookup symbol to the referenced name and rescan tags files. symbol = fields:match('[^:]+$') goto rescan end end end ::continue:: end if symbol == '' and M.autocomplete_snippets then local _, snippets = textadept.editing.autocompleters.snippet() for i = 1, #snippets do list[#list + 1] = snippets[i] end end return #part, list end for _, tags in ipairs(M.tags) do table.insert(textadept.editing.api_files.ansi_c, (tags:gsub('tags$', 'api'))) end -- Snippets. local snip = snippets.ansi_c snip.func = '%1(int) %2(name)(%3(args)) {\n\t%0\n\treturn %4(0);\n}' snip.vfunc = 'void %1(name)(%2(args)) {\n\t%0\n}' snip['if'] = 'if (%1) {\n\t%0\n}' snip.eif = 'else if (%1) {\n\t%0\n}' snip['else'] = 'else {\n\t%0\n}' snip['for'] = 'for (%1; %2; %3) {\n\t%0\n}' snip['fori'] = 'for (%1(int) %2(i) = %3(0); %2 %4(<) %5(count); %2%6(++)) {\n\t%0\n}' snip['while'] = 'while (%1) {\n\t%0\n}' snip['do'] = 'do {\n\t%0\n} while (%1);' snip.sw = 'switch (%1) {\n\tcase %2:\n\t\t%0\n\t\tbreak;\n}' snip.case = 'case %1:\n\t%0\n\tbreak;' snip.st = 'struct %1(name) {\n\t%0\n};' snip.td = 'typedef %1(int) %2(name_t);' snip.tds = 'typedef struct %1(name) {\n\t%0\n} %1%2(_t);' snip.def = '#define %1(name) %2(value)' snip.inc = '#include "%1"' snip.Inc = '#include <%1>' snip.pif = '#if %1\n%0\n#endif' snip.main = 'int main(int argc, const char **argv) {\n\t%0\n\treturn 0;\n}' snip.printf = 'printf("%1(%s)\\n", %2);' return M
mit
vrld/shine
sketch.lua
2
2214
--[[ The MIT License (MIT) Copyright (c) 2015 Martin Felis Copyright (c) 2017 Matthias Richter 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. ]]-- return function(moonshine) local noisetex = love.image.newImageData(256,256) noisetex:mapPixel(function() return love.math.random() * 255,love.math.random() * 255, 0, 0 end) noisetex = love.graphics.newImage(noisetex) noisetex:setWrap ("repeat", "repeat") noisetex:setFilter("nearest", "nearest") local shader = love.graphics.newShader[[ extern Image noisetex; extern number amp; extern vec2 center; vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _) { vec2 displacement = Texel(noisetex, tc + center).rg; tc += normalize(displacement * 2.0 - vec2(1.0)) * amp; return Texel(texture, tc); }]] shader:send("noisetex", noisetex) local setters = {} setters.amp = function(v) shader:send("amp", math.max(0, tonumber(v) or 0)) end setters.center = function(v) assert(type(v) == "table" and #v == 2, "Invalid value for `center'") shader:send("center", v) end return moonshine.Effect{ name = "sketch", shader = shader, setters = setters, defaults = {amp = .0007, center = {0,0}} } end
mit
CrazyEddieTK/Zero-K
LuaRules/Utilities/glVolumes.lua
6
10355
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Exported Functions: -- gl.Utilities.DrawMyBox(minX,minY,minZ, maxX,maxY,maxZ) -- gl.Utilities.DrawMyCylinder(x,y,z, height,radius,divs) -- gl.Utilities.DrawMyHollowCylinder(x,y,z, height,radius,innerRadius,divs) -- gl.Utilities.DrawGroundRectangle(x1,z1,x2,z2) -- gl.Utilities.DrawGroundCircle(x,z,radius) -- gl.Utilities.DrawGroundHollowCircle(x,z,radius,innerRadius) -- gl.Utilities.DrawVolume(vol_dlist) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if (not gl) then return end gl.Utilities = gl.Utilities or {} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local min = math.min local max = math.max local sin = math.sin local cos = math.cos local floor = math.floor local TWO_PI = math.pi * 2 local glVertex = gl.Vertex GL.KEEP = 0x1E00 GL.INCR_WRAP = 0x8507 GL.DECR_WRAP = 0x8508 GL.INCR = 0x1E02 GL.DECR = 0x1E03 GL.INVERT = 0x150A local stencilBit1 = 0x01 local stencilBit2 = 0x10 -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gl.Utilities.DrawMyBox(minX,minY,minZ, maxX,maxY,maxZ) gl.BeginEnd(GL.QUADS, function() --// top glVertex(minX, maxY, minZ) glVertex(minX, maxY, maxZ) glVertex(maxX, maxY, maxZ) glVertex(maxX, maxY, minZ) --// bottom glVertex(minX, minY, minZ) glVertex(maxX, minY, minZ) glVertex(maxX, minY, maxZ) glVertex(minX, minY, maxZ) end) gl.BeginEnd(GL.QUAD_STRIP, function() --// sides glVertex(minX, maxY, minZ) glVertex(minX, minY, minZ) glVertex(minX, maxY, maxZ) glVertex(minX, minY, maxZ) glVertex(maxX, maxY, maxZ) glVertex(maxX, minY, maxZ) glVertex(maxX, maxY, minZ) glVertex(maxX, minY, minZ) glVertex(minX, maxY, minZ) glVertex(minX, minY, minZ) end) end function gl.Utilities.DrawMy3DTriangle(x1,z1, x2, z2, x3,z3, minY, maxY) gl.BeginEnd(GL.TRIANGLES, function() --// top glVertex(x1, maxY, z1) glVertex(x2, maxY, z2) glVertex(x3, maxY, z3) --// bottom glVertex(x1, minY, z1) glVertex(x3, minY, z3) glVertex(x2, minY, z2) end) gl.BeginEnd(GL.QUAD_STRIP, function() --// sides glVertex(x1, maxY, z1) glVertex(x1, minY, z1) glVertex(x2, maxY, z2) glVertex(x2, minY, z2) glVertex(x3, maxY, z3) glVertex(x3, minY, z3) glVertex(x1, maxY, z1) glVertex(x1, minY, z1) end) end local function CreateSinCosTable(divs) local sinTable = {} local cosTable = {} local divAngle = TWO_PI / divs local alpha = 0 local i = 1 repeat sinTable[i] = sin(alpha) cosTable[i] = cos(alpha) alpha = alpha + divAngle i = i + 1 until (alpha >= TWO_PI) sinTable[i] = 0.0 -- sin(TWO_PI) cosTable[i] = 1.0 -- cos(TWO_PI) return sinTable, cosTable end function gl.Utilities.DrawMyCylinder(x,y,z, height,radius,divs) divs = divs or 25 local sinTable, cosTable = CreateSinCosTable(divs) local bottomY = y - (height / 2) local topY = y + (height / 2) gl.BeginEnd(GL.TRIANGLE_STRIP, function() --// top for i = #sinTable, 1, -1 do glVertex(x + radius*sinTable[i], topY, z + radius*cosTable[i]) glVertex(x, topY, z) end --// degenerate glVertex(x, topY , z) glVertex(x, bottomY, z) glVertex(x, bottomY, z) --// bottom for i = #sinTable, 1, -1 do glVertex(x + radius*sinTable[i], bottomY, z + radius*cosTable[i]) glVertex(x, bottomY, z) end --// degenerate glVertex(x, bottomY, z) glVertex(x, bottomY, z+radius) glVertex(x, bottomY, z+radius) --// sides for i = 1, #sinTable do local rx = x + radius * sinTable[i] local rz = z + radius * cosTable[i] glVertex(rx, topY , rz) glVertex(rx, bottomY, rz) end end) end function gl.Utilities.DrawMyCircle(x,y,radius,divs) divs = divs or 25 local sinTable, cosTable = CreateSinCosTable(divs) gl.BeginEnd(GL.LINE_LOOP, function() for i = #sinTable, 1, -1 do glVertex(x + radius*sinTable[i], y + radius*cosTable[i], 0) end end) end function gl.Utilities.DrawMyHollowCylinder(x,y,z, height,radius,inRadius,divs) divs = divs or 25 local sinTable, cosTable = CreateSinCosTable(divs) local bottomY = y - (height / 2) local topY = y + (height / 2) gl.BeginEnd(GL.TRIANGLE_STRIP, function() --// top for i = 1, #sinTable do local sa = sinTable[i] local ca = cosTable[i] glVertex(x + inRadius*sa, topY, z + inRadius*ca) glVertex(x + radius*sa, topY, z + radius*ca) end --// sides for i = 1, #sinTable do local rx = x + radius * sinTable[i] local rz = z + radius * cosTable[i] glVertex(rx, topY , rz) glVertex(rx, bottomY, rz) end --// bottom for i = 1, #sinTable do local sa = sinTable[i] local ca = cosTable[i] glVertex(x + radius*sa, bottomY, z + radius*ca) glVertex(x + inRadius*sa, bottomY, z + inRadius*ca) end if (inRadius > 0) then --// inner sides for i = 1, #sinTable do local rx = x + inRadius * sinTable[i] local rz = z + inRadius * cosTable[i] glVertex(rx, bottomY, rz) glVertex(rx, topY , rz) end end end) end local heightMargin = 2000 local minheight, maxheight = Spring.GetGroundExtremes() --the returned values do not change even if we terraform the map local averageGroundHeight = (minheight + maxheight) / 2 local shapeHeight = heightMargin + (maxheight - minheight) + heightMargin local box = gl.CreateList(gl.Utilities.DrawMyBox,0,-0.5,0,1,0.5,1) function gl.Utilities.DrawGroundRectangle(x1,z1,x2,z2) if (type(x1) == "table") then local rect = x1 x1,z1,x2,z2 = rect[1],rect[2],rect[3],rect[4] end gl.PushMatrix() gl.Translate(x1, averageGroundHeight, z1) gl.Scale(x2-x1, shapeHeight, z2-z1) gl.Utilities.DrawVolume(box) gl.PopMatrix() end local triangles = {} function gl.Utilities.DrawGroundTriangle(args) if not triangles[args] then triangles[args] = gl.CreateList(gl.Utilities.DrawMy3DTriangle, args[1], args[2], args[3], args[4], args[5], args[6], -0.5, 0.5) end gl.PushMatrix() gl.Translate(0, averageGroundHeight, 0) gl.Scale(1, shapeHeight, 1) gl.Utilities.DrawVolume(triangles[args]) gl.PopMatrix() end local cylinder = gl.CreateList(gl.Utilities.DrawMyCylinder,0,0,0,1,1,35) function gl.Utilities.DrawGroundCircle(x,z,radius) gl.PushMatrix() gl.Translate(x, averageGroundHeight, z) gl.Scale(radius, shapeHeight, radius) gl.Utilities.DrawVolume(cylinder) gl.PopMatrix() end local circle = gl.CreateList(gl.Utilities.DrawMyCircle,0,0,1,35) function gl.Utilities.DrawCircle(x,y,radius) gl.PushMatrix() gl.Translate(x, y, 0) gl.Scale(radius, radius, 1) gl.Utilities.DrawVolume(circle) gl.PopMatrix() end -- See comment in DrawMergedVolume function gl.Utilities.DrawMergedGroundCircle(x,z,radius) gl.PushMatrix() gl.Translate(x, averageGroundHeight, z) gl.Scale(radius, shapeHeight, radius) gl.Utilities.DrawMergedVolume(cylinder) gl.PopMatrix() end local hollowCylinders = { [ 0 ] = cylinder, } local function GetHollowCylinder(radius, innerRadius) if (innerRadius >= 1) then innerRadius = min(innerRadius / radius, 1.0) end innerRadius = floor(innerRadius * 100 + 0.5) / 100 if (not hollowCylinders[innerRadius]) then hollowCylinders[innerRadius] = gl.CreateList(gl.Utilities.DrawMyHollowCylinder,0,0,0,1,1,innerRadius,35) end return hollowCylinders[innerRadius] end --// when innerRadius is < 1, its value is treated as relative to radius --// when innerRadius is >=1, its value is treated as absolute value in elmos function gl.Utilities.DrawGroundHollowCircle(x,z,radius,innerRadius) local hollowCylinder = GetHollowCylinder(radius, innerRadius) gl.PushMatrix() gl.Translate(x, averageGroundHeight, z) gl.Scale(radius, shapeHeight, radius) gl.Utilities.DrawVolume(hollowCylinder) gl.PopMatrix() end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gl.Utilities.DrawVolume(vol_dlist) gl.DepthMask(false) if (gl.DepthClamp) then gl.DepthClamp(true) end gl.StencilTest(true) gl.Culling(false) gl.DepthTest(true) gl.ColorMask(false, false, false, false) gl.StencilOp(GL.KEEP, GL.INCR, GL.KEEP) --gl.StencilOp(GL.KEEP, GL.INVERT, GL.KEEP) gl.StencilMask(1) gl.StencilFunc(GL.ALWAYS, 0, 1) gl.CallList(vol_dlist) gl.Culling(GL.FRONT) gl.DepthTest(false) gl.ColorMask(true, true, true, true) gl.StencilOp(GL.ZERO, GL.ZERO, GL.ZERO) gl.StencilMask(1) gl.StencilFunc(GL.NOTEQUAL, 0, 1) gl.CallList(vol_dlist) if (gl.DepthClamp) then gl.DepthClamp(false) end gl.StencilTest(false) -- gl.DepthTest(true) gl.Culling(false) end -- Make sure that you start with a clear stencil and that you -- clear it using gl.Clear(GL.STENCIL_BUFFER_BIT, 0) -- after finishing all the merged volumes function gl.Utilities.DrawMergedVolume(vol_dlist) gl.DepthMask(false) if (gl.DepthClamp) then gl.DepthClamp(true) end gl.StencilTest(true) gl.Culling(false) gl.DepthTest(true) gl.ColorMask(false, false, false, false) gl.StencilOp(GL.KEEP, GL.INVERT, GL.KEEP) --gl.StencilOp(GL.KEEP, GL.INVERT, GL.KEEP) gl.StencilMask(1) gl.StencilFunc(GL.ALWAYS, 0, 1) gl.CallList(vol_dlist) gl.Culling(GL.FRONT) gl.DepthTest(false) gl.ColorMask(true, true, true, true) gl.StencilOp(GL.KEEP, GL.INCR, GL.INCR) gl.StencilMask(3) gl.StencilFunc(GL.EQUAL, 1, 3) gl.CallList(vol_dlist) if (gl.DepthClamp) then gl.DepthClamp(false) end gl.StencilTest(false) -- gl.DepthTest(true) gl.Culling(false) end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
CrazyEddieTK/Zero-K
LuaUI/Widgets/unit_default_commands.lua
5
1639
function widget:GetInfo() return { name = "Misc default command replacements", license = "Public Domain", layer = 0, enabled = Script.IsEngineMinVersion(104, 0, 53), -- 53 on maintenance branch, 211 on develob } end VFS.Include("LuaRules/Configs/customcmds.h.lua") -- for CMD_RAW_MOVE options_path = 'Settings/Unit Behaviour' options = { guard_facs = { name = "Right click guards factories", type = "bool", value = true, desc = "If enabled, rightclicking a factory will always Guard it.\nIf disabled, the command can be Repair.", noHotkey = true, }, guard_cons = { name = "Right click guards constructors", type = "bool", value = true, desc = "If enabled, rightclicking a constructor will always Guard it.\nIf disabled, the command can be Repair.", noHotkey = true, }, } local cons, facs = {}, {} for unitDefID, unitDef in pairs(UnitDefs) do if unitDef.isMobileBuilder then cons[unitDefID] = true end if unitDef.isFactory then facs[unitDefID] = true end end local handlers = { [CMD.RECLAIM] = function (unitID) if (select(5, Spring.GetUnitHealth(unitID)) or 1) < 1 then return end return CMD_RAW_MOVE end, [CMD.REPAIR] = function (unitID) if select(5, Spring.GetUnitHealth(unitID)) < 1 then return end local unitDefID = Spring.GetUnitDefID(unitID) if cons[unitDefID] and options.guard_cons.value or facs[unitDefID] and options.guard_facs.value then return CMD.GUARD end end, } function widget:DefaultCommand(targetType, targetID, engineCmd) if targetType ~= "unit" then return end if handlers[engineCmd] then return handlers[engineCmd](targetID) end end
gpl-2.0
SecUSo/openwrt-traffic-analyzer
package-dev/luci-trafficanalyzer/dist/www/cgi-bin/warningpage_content.lua
2
3762
require("luci.sys") local warningpage_content = {}; function warningpage_content.html(backend) print("Status: 200 OK") print("Content-Type: text/html\n") print('<?xml version="1.0" encoding="utf-8"?>') print('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">') print('<html xmlns="http://www.w3.org/1999/xhtml">') print('<head>') warningpage_content.stylesheets(backend) warningpage_content.javascript(backend) print('</head>') print('<body>') warningpage_content.body(backend) print('</body>') print('</html>') end function warningpage_content.stylesheets(backend) if backend == false then print('<link rel="stylesheet" href="/luci-static/resources/warningpage/css/reset.css">') print('<link rel="stylesheet" href="/luci-static/resources/warningpage/css/basic.css">') end print('<link rel="stylesheet" href="/luci-static/resources/warningpage/css/main.css">') if backend == true then print('<link rel="stylesheet" href="/luci-static/resources/warningpage/css/backend.css">') end end function warningpage_content.javascript(backend) print('<script type="text/javascript">') print('window.onload = function () {') print('var userLang = navigator.language || navigator.userLanguage;') print('if (userLang.indexOf("de") > -1) {') print('document.getElementById("english").style.display = \'none\';') print('} else {') print('document.getElementById("german").style.display = \'none\';') print('}') print('}') print('</script>') end function warningpage_content.body(backend) local referer = luci.sys.getenv("HTTP_REFERER") print('<div class="warningpage">') print('<div class="container logo_container">') print('<img src="/luci-static/resources/warningpage/img/tud_logo.svg" class="logo" />') print('<img src="/luci-static/resources/warningpage/img/secuso_logo.svg" class="logo" />') print('</div>') print('<div class="container content_container">') print('<div id="english">') print('<h1 class="warning">Warning</h1>') print('<p>You have entered your password at the page <a href="' .. referer .. '">' .. referer .. '</a>.</p>') print('<p>Data transfer has been stopped because this WiFi network is a cloned fake which is unencrypted and not secure. Additionally, the page where you entered your login credentials does not use encryption.</p>') print('<p>Please change the password for the website listed above. It is possible that sombody who uses this network has captured your credentials. You should use a secure connection for this procedure (HTTPS).</p>') print('<p><a href="https://www.secuso.informatik.tu-darmstadt.de/en/secuso-home/" class="more_info">More information...</a></p>') print('</div>') print('<div id="german">') print('<h1 class="warning">Warnung</h1>') print('<p>Sie haben auf der Webseite mit der URL <a href="' .. referer .. '">' .. referer .. '</a> ihr Passwort eingegeben.</p>') print('<p>Der Aufruf wurde umgeleitet, da das Funknetzwerk ein nicht vertrauensw&uuml;rdiger Klon eines anderen Netzwerks ist. Dar&uuml;ber hinaus verwendet die Webseite, auf der Sie Ihre Login-Daten eingegeben haben, keine verschl&uuml;sselte Verbindung.</p>') print('<p>Bitte &auml;ndern Sie Ihr Passwort f&uuml;r die oben angegebene Webseite, da nicht auszuschlie&szlig;en ist, dass Ihre Zugangsdaten von einem anderen Nutzer dieses Netzwerks abgefangen wurden. Bitte benutzen Sie f&uuml;r die Passwort&auml;nderung eine sichere Verbindung (HTTPS).</p>') print('<p><a href="https://www.secuso.informatik.tu-darmstadt.de/de/secuso-home/" class="more_info">Mehr Informationen...</a></p>') print('</div>') print('</div>') print('</div>') end return warningpage_content
apache-2.0
starkos/premake-core
modules/vstudio/tests/vc2010/test_manifest.lua
14
1667
-- -- tests/actions/vstudio/vc2010/test_manifest.lua -- Validate generation of Manifest block in Visual Studio 201x C/C++ projects. -- Copyright (c) 2009-2013 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vs2010_manifest") local vc2010 = p.vstudio.vc2010 local project = p.project -- -- Setup -- local wks, prj function suite.setup() p.action.set("vs2010") wks, prj = test.createWorkspace() kind "ConsoleApp" end local function prepare(platform) local cfg = test.getconfig(prj, "Debug", platform) vc2010.manifest(cfg) end -- -- Check the basic element structure with default settings. -- function suite.defaultSettings() files { "source/test.manifest" } prepare() test.capture [[ <Manifest> <AdditionalManifestFiles>source/test.manifest;%(AdditionalManifestFiles)</AdditionalManifestFiles> </Manifest> ]] end -- -- Check that there is no manifest when using static lib -- function suite.staticLib() kind "StaticLib" files { "test.manifest" } prepare() test.isemptycapture() end -- -- Check that DPI Awareness emits correctly -- function suite.dpiAwareness_None() dpiawareness "None" prepare() test.capture [[ <Manifest> <EnableDpiAwareness>false</EnableDpiAwareness> </Manifest> ]] end function suite.dpiAwareness_High() dpiawareness "High" prepare() test.capture [[ <Manifest> <EnableDpiAwareness>true</EnableDpiAwareness> </Manifest> ]] end function suite.dpiAwareness_HighPerMonitor() dpiawareness "HighPerMonitor" prepare() test.capture [[ <Manifest> <EnableDpiAwareness>PerMonitorHighDPIAware</EnableDpiAwareness> </Manifest> ]] end
bsd-3-clause
czfshine/Don-t-Starve
data/scripts/prefabs/books.lua
1
5669
local assets = { Asset("ANIM", "anim/books.zip"), --Asset("SOUND", "sound/common.fsb"), } local prefabs = { "tentacle", "splash_ocean", "book_fx" } function tentaclesfn(inst, reader) local pt = Vector3(reader.Transform:GetWorldPosition()) local numtentacles = 3 reader.components.sanity:DoDelta(-TUNING.SANITY_HUGE) reader:StartThread(function() for k = 1, numtentacles do local theta = math.random() * 2 * PI local radius = math.random(3, 8) -- we have to special case this one because birds can't land on creep local result_offset = FindValidPositionByFan(theta, radius, 12, function(offset) local x,y,z = (pt + offset):Get() local ents = TheSim:FindEntities(x,y,z , 1) return not next(ents) end) if result_offset then local tentacle = SpawnPrefab("tentacle") tentacle.Transform:SetPosition((pt + result_offset):Get()) GetPlayer().components.playercontroller:ShakeCamera(reader, "FULL", 0.2, 0.02, .25, 40) --need a better effect local fx = SpawnPrefab("splash_ocean") local pos = pt + result_offset fx.Transform:SetPosition(pos.x, pos.y, pos.z) --PlayFX((pt + result_offset), "splash", "splash_ocean", "idle") tentacle.sg:GoToState("attack_pre") end Sleep(.33) end end) return true end function birdsfn(inst, reader) if not GetWorld().components.birdspawner then return false end reader.components.sanity:DoDelta(-TUNING.SANITY_HUGE) local num = 20 + math.random(10) --we can actually run out of command buffer memory if we allow for infinite birds local x, y, z = reader.Transform:GetWorldPosition() local ents = TheSim:FindEntities(x,y,z, 10, nil, nil, {'magicalbird'}) if #ents > 30 then num = 0 reader.components.talker:Say(GetString(reader.prefab, "ANNOUNCE_WAYTOOMANYBIRDS")) elseif #ents > 20 then reader.components.talker:Say(GetString(reader.prefab, "ANNOUNCE_TOOMANYBIRDS")) num = 10 + math.random(10) end if num > 0 then reader:StartThread(function() for k = 1, num do local pt = GetWorld().components.birdspawner:GetSpawnPoint(Vector3(reader.Transform:GetWorldPosition() )) if pt then local bird = GetWorld().components.birdspawner:SpawnBird(pt, true) bird:AddTag("magicalbird") end Sleep(math.random(.2, .25)) end end) end return true end function firefn(inst, reader) local num_lightnings = 16 reader.components.sanity:DoDelta(-TUNING.SANITY_LARGE) reader:StartThread(function() for k = 0, num_lightnings do local rad = math.random(3, 15) local angle = k*((4*PI)/num_lightnings) local pos = Vector3(reader.Transform:GetWorldPosition()) + Vector3(rad*math.cos(angle), 0, rad*math.sin(angle)) GetSeasonManager():DoLightningStrike(pos) Sleep(math.random( .3, .5)) end end) return true end function sleepfn(inst, reader) reader.components.sanity:DoDelta(-TUNING.SANITY_LARGE) local range = 30 local pos = Vector3(reader.Transform:GetWorldPosition()) local ents = TheSim:FindEntities(pos.x,pos.y,pos.z, range) for k,v in pairs(ents) do if v.components.sleeper and v ~= reader then v.components.sleeper:AddSleepiness(10, 20) end end return true end function growfn(inst, reader) reader.components.sanity:DoDelta(-TUNING.SANITY_LARGE) local range = 30 local pos = Vector3(reader.Transform:GetWorldPosition()) local ents = TheSim:FindEntities(pos.x,pos.y,pos.z, range) for k,v in pairs(ents) do if v.components.pickable then v.components.pickable:FinishGrowing() end if v.components.crop then v.components.crop:DoGrow(TUNING.TOTAL_DAY_TIME*3) end if v:HasTag("tree") and v.components.growable and not v:HasTag("stump") then v.components.growable:DoGrowth() end end return true end function onfinished(inst) inst:Remove() end function MakeBook(name, usefn, bookuses ) local function fn(Sim) local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() local sound = inst.entity:AddSoundEmitter() anim:SetBank("books") anim:SetBuild("books") anim:PlayAnimation(name) MakeInventoryPhysics(inst) ----------------------------------- inst:AddComponent("inspectable") inst:AddComponent("book") inst.components.book.onread = usefn inst:AddComponent("characterspecific") inst.components.characterspecific:SetOwner("wickerbottom") inst:AddComponent("inventoryitem") inst:AddComponent("finiteuses") inst.components.finiteuses:SetMaxUses( bookuses ) inst.components.finiteuses:SetUses( bookuses ) inst.components.finiteuses:SetOnFinished( onfinished ) MakeSmallBurnable(inst) MakeSmallPropagator(inst) return inst end return Prefab( "common/"..name, fn, assets, prefabs) end return MakeBook("book_sleep", sleepfn, 5), MakeBook("book_gardening", growfn, 5), MakeBook("book_brimstone", firefn, 5), MakeBook("book_birds", birdsfn, 3), MakeBook("book_tentacles", tentaclesfn, 5)
gpl-2.0
CrazyEddieTK/Zero-K
LuaRules/Gadgets/unit_starlight_satellite_capture.lua
5
1259
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if not gadgetHandler:IsSyncedCode() then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Starlight Satellite Capture", desc = "Whenever a Starlight with an active satellite is transferred, also transfer the satellite", author = "Anarchid", date = "1.07.2016", license = "Public domain", layer = 21, enabled = true } end local transfers = {} local alreadyAdded function gadget:UnitGiven(unitID, unitDefID, newTeam) local satID = Spring.GetUnitRulesParam(unitID,'has_satellite'); if not satID then return end transfers[satID] = newTeam if alreadyAdded then return end gadgetHandler:UpdateCallIn("GameFrame") alreadyAdded = true end function gadget:Initialize() alreadyAdded = false gadgetHandler:RemoveCallIn("GameFrame") end function gadget:GameFrame(f) for satID, team in pairs(transfers) do Spring.TransferUnit(satID, team, false) transfers[satID] = nil end gadget:Initialize() end
gpl-2.0
czfshine/Don-t-Starve
data/scripts/components/nis.lua
1
1979
local NIS = Class(function(self, inst) self.inst = inst self.playing = false self.skippable = false self.data = {} self.name = "" self.inputhandlers = {} table.insert(self.inputhandlers, TheInput:AddControlHandler(CONTROL_PRIMARY, function() self:OnClick() end)) table.insert(self.inputhandlers, TheInput:AddControlHandler(CONTROL_SECONDARY, function() self:OnClick() end)) table.insert(self.inputhandlers, TheInput:AddControlHandler(CONTROL_ATTACK, function() self:OnClick() end)) table.insert(self.inputhandlers, TheInput:AddControlHandler(CONTROL_INSPECT, function() self:OnClick() end)) table.insert(self.inputhandlers, TheInput:AddControlHandler(CONTROL_ACTION, function() self:OnClick() end)) table.insert(self.inputhandlers, TheInput:AddControlHandler(CONTROL_CONTROLLER_ACTION, function() self:OnClick() end)) end) function NIS:OnRemoveEntity() for k,v in pairs(self.inputhandlers) do v:Remove() end end function NIS:SetName(name) self.name = name end function NIS:SetScript(fn) self.script = fn end function NIS:SetInit(fn) self.init = fn end function NIS:SetCancel(fn) self.cancel = fn end function NIS:OnFinish() self.playing = false self.task = nil self.inst:Remove() end function NIS:Cancel() IncTrackingStat(self.name, "nis_skip") if self.task then KillThread(self.task) end if self.cancel then self.cancel(self.data) end self:OnFinish() end function NIS:OnClick() if self.skippable then self:Cancel() end end function NIS:Play(lines) self.playing = true if self.init then self.init(self.data) end if self.script then self.task = self.inst:StartThread( function() self.script(self, self.data, lines) self:OnFinish() end) else self:OnFinish() end end return NIS
gpl-2.0
lephong/iornn-depparse
source/eval_depparser_rerank.lua
1
1238
require 'depparser_rerank' require 'utils' require 'dict' require 'xlua' require 'dpiornn_gen' require 'dp_spec' torch.setnumthreads(1) if #arg >= 3 then treebank_path = arg[2] kbesttreebank_path = arg[3] output = arg[4] print('load net') local net = IORNN:load(arg[1]) -- print(net.Wh:size()) print('create parser') local parser = Depparser:new(net.voca_dic, net.pos_dic, net.deprel_dic) -- local u = arg[1]:find('/model') -- if u == nil then parser.mail_subject = path -- else parser.mail_subject = arg[1]:sub(1,u-1) end --print(parser.mail_subject) print('eval') print('\n\n--- oracle-best ---') parser:eval('best', kbesttreebank_path, treebank_path, output..'.oracle-best') print('\n\n--- oracle-worst ---') parser:eval('worst', kbesttreebank_path, treebank_path, output..'.oracle-worst') print('\n\n--- first ---') parser:eval('first', kbesttreebank_path, treebank_path, output..'.first') print('\n\n--- rescore ---') parser:eval(net, kbesttreebank_path, treebank_path, kbesttreebank_path..'.iornnscores') print('\n\n--- mix. reranking ---') parser:eval(kbesttreebank_path..'.iornnscores', kbesttreebank_path, treebank_path, output..'.reranked') else print("[net] [gold/input] [kbest] [output]") end
apache-2.0
matthewhesketh/mattata
plugins/xkcd.lua
2
2793
--[[ Based on a plugin by topkecleon. Licensed under GNU AGPLv3 https://github.com/topkecleon/otouto/blob/master/LICENSE. Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]] local xkcd = {} local mattata = require('mattata') local https = require('ssl.https') local url = require('socket.url') local json = require('dkjson') function xkcd:init() xkcd.commands = mattata.commands( self.info.username ):command('xkcd').table xkcd.help = [[/xkcd [query] - Returns the latest xkcd strip and its alt text. If a number is given, returns that number strip. If 'r' is passed in place of a number, returns a random strip. Any other text passed as the command argument will search Google for a relevant strip and, if applicable, return it.]] local jstr = https.request('https://xkcd.com/info.0.json') if jstr then local jdat = json.decode(jstr) if jdat then xkcd.latest = jdat.num end end xkcd.latest = xkcd.latest end function xkcd:on_message(message, configuration, language) local input = mattata.input(message.text) if not input then input = xkcd.latest end if input == 'r' then input = math.random(xkcd.latest) elseif tonumber(input) ~= nil then input = tonumber(input) else input = 'inurl:xkcd.com ' .. input local search, res = https.request('https://relevantxkcd.appspot.com/process?action=xkcd&query=' .. url.escape(input)) if res ~= 200 then return mattata.send_reply( message, language['errors']['results'] ) end input = tonumber( search:match('^.-\n.-\n(%d*) %/') ) end local url = string.format( 'https://xkcd.com/%s/info.0.json', tostring(input) ) local jstr, res = https.request(url) if res == 404 then return mattata.send_message( message.chat.id, '[<a href="https://xkcd.com/404">404</a>] <b>404 Not Found</b>, 1/4/2008', 'html' ) elseif res ~= 200 then return mattata.send_reply( message, language['errors']['connection'] ) end local jdat = json.decode(jstr) return mattata.send_message( message.chat.id, string.format( '[<a href="%s">%s</a>] <b>%s</b>, %s/%s/%s\n<i>%s</i>', jdat.img, jdat.num, mattata.escape_html(jdat.safe_title), jdat.day, jdat.month, jdat.year, mattata.escape_html(jdat.alt) ), 'html', false ) end return xkcd
mit
rzh/mongocraft
world/Plugins/APIDump/Classes/Projectiles.lua
27
6665
return { cArrowEntity = { Desc = [[ Represents the arrow when it is shot from the bow. A subclass of the {{cProjectileEntity}}. ]], Functions = { CanPickup = { Params = "{{cPlayer|Player}}", Return = "bool", Notes = "Returns true if the specified player can pick the arrow when it's on the ground" }, GetDamageCoeff = { Params = "", Return = "number", Notes = "Returns the damage coefficient stored within the arrow. The damage dealt by this arrow is multiplied by this coeff" }, GetPickupState = { Params = "", Return = "PickupState", Notes = "Returns the pickup state (one of the psXXX constants, above)" }, IsCritical = { Params = "", Return = "bool", Notes = "Returns true if the arrow should deal critical damage. Based on the bow charge when the arrow was shot." }, SetDamageCoeff = { Params = "number", Return = "", Notes = "Sets the damage coefficient. The damage dealt by this arrow is multiplied by this coeff" }, SetIsCritical = { Params = "bool", Return = "", Notes = "Sets the IsCritical flag on the arrow. Critical arrow deal additional damage" }, SetPickupState = { Params = "PickupState", Return = "", Notes = "Sets the pickup state (one of the psXXX constants, above)" }, }, Constants = { psInCreative = { Notes = "The arrow can be picked up only by players in creative gamemode" }, psInSurvivalOrCreative = { Notes = "The arrow can be picked up by players in survival or creative gamemode" }, psNoPickup = { Notes = "The arrow cannot be picked up at all" }, }, ConstantGroups = { PickupState = { Include = "ps.*", TextBefore = [[ The following constants are used to signalize whether the arrow, once it lands, can be picked by players: ]], }, }, Inherits = "cProjectileEntity", }, -- cArrowEntity cExpBottleEntity = { Desc = [[ Represents a thrown ExpBottle. A subclass of the {{cProjectileEntity}}. ]], Functions = { }, Inherits = "cProjectileEntity", }, -- cExpBottleEntity cFireChargeEntity = { Desc = [[ Represents a fire charge that has been shot by a Blaze or a {{cDispenserEntity|Dispenser}}. A subclass of the {{cProjectileEntity}}. ]], Functions = {}, Inherits = "cProjectileEntity", }, -- cFireChargeEntity cFireworkEntity = { Desc = [[ Represents a firework rocket. ]], Functions = { GetItem = { Params = "", Return = "{{cItem}}", Notes = "Returns the item that has been used to create the firework rocket. The item's m_FireworkItem member contains all the firework-related data." }, GetTicksToExplosion = { Params = "", Return = "number", Notes = "Returns the number of ticks left until the firework explodes." }, SetItem = { Params = "{{cItem}}", Return = "", Notes = "Sets a new item to be used for the firework." }, SetTicksToExplosion = { Params = "NumTicks", Return = "", Notes = "Sets the number of ticks left until the firework explodes." }, }, Inherits = "cProjectileEntity", }, -- cFireworkEntity cFloater = { Desc = "", Functions = {}, Inherits = "cProjectileEntity", }, -- cFloater cGhastFireballEntity = { Desc = "", Functions = {}, Inherits = "cProjectileEntity", }, -- cGhastFireballEntity cProjectileEntity = { Desc = "", Functions = { GetCreator = { Params = "", Return = "{{cEntity}} descendant", Notes = "Returns the entity who created this projectile. May return nil." }, GetMCAClassName = { Params = "", Return = "string", Notes = "Returns the string that identifies the projectile type (class name) in MCA files" }, GetProjectileKind = { Params = "", Return = "ProjectileKind", Notes = "Returns the kind of this projectile (pkXXX constant)" }, IsInGround = { Params = "", Return = "bool", Notes = "Returns true if this projectile has hit the ground." }, }, Constants = { pkArrow = { Notes = "The projectile is an {{cArrowEntity|arrow}}" }, pkEgg = { Notes = "The projectile is a {{cThrownEggEntity|thrown egg}}" }, pkEnderPearl = { Notes = "The projectile is a {{cThrownEnderPearlEntity|thrown enderpearl}}" }, pkExpBottle = { Notes = "The projectile is a {{cExpBottleEntity|thrown exp bottle}}" }, pkFireCharge = { Notes = "The projectile is a {{cFireChargeEntity|fire charge}}" }, pkFirework = { Notes = "The projectile is a (flying) {{cFireworkEntity|firework}}" }, pkFishingFloat = { Notes = "The projectile is a {{cFloater|fishing float}}" }, pkGhastFireball = { Notes = "The projectile is a {{cGhastFireballEntity|ghast fireball}}" }, pkSnowball = { Notes = "The projectile is a {{cThrownSnowballEntity|thrown snowball}}" }, pkSplashPotion = { Notes = "The projectile is a {{cSplashPotionEntity|thrown splash potion}}" }, pkWitherSkull = { Notes = "The projectile is a {{cWitherSkullEntity|wither skull}}" }, }, ConstantGroups = { ProjectileKind = { Include = "pk.*", TextBefore = "The following constants are used to distinguish between the different projectile kinds:", }, }, Inherits = "cEntity", }, -- cProjectileEntity cSplashPotionEntity = { Desc = [[ Represents a thrown splash potion. ]], Functions = { GetEntityEffect = { Params = "", Return = "{{cEntityEffect}}", Notes = "Returns the entity effect in this potion" }, GetEntityEffectType = { Params = "", Return = "{{cEntityEffect|Entity effect type}}", Notes = "Returns the effect type of this potion" }, GetPotionColor = { Params = "", Return = "number", Notes = "Returns the color index of the particles emitted by this potion" }, SetEntityEffect = { Params = "{{cEntityEffect}}", Return = "", Notes = "Sets the entity effect for this potion" }, SetEntityEffectType = { Params = "{{cEntityEffect|Entity effect type}}", Return = "", Notes = "Sets the effect type of this potion" }, SetPotionColor = { Params = "number", Return = "", Notes = "Sets the color index of the particles for this potion" }, }, Inherits = "cProjectileEntity", }, -- cSplashPotionEntity cThrownEggEntity = { Desc = [[ Represents a thrown egg. ]], Functions = {}, Inherits = "cProjectileEntity", }, -- cThrownEggEntity cThrownEnderPearlEntity = { Desc = "Represents a thrown ender pearl.", Functions = {}, Inherits = "cProjectileEntity", }, -- cThrownEnderPearlEntity cThrownSnowballEntity = { Desc = "Represents a thrown snowball.", Functions = {}, Inherits = "cProjectileEntity", }, -- cThrownSnowballEntity cWitherSkullEntity = { Desc = "Represents a wither skull being shot.", Functions = {}, Inherits = "cProjectileEntity", }, -- cWitherSkullEntity }
apache-2.0
devlua/TEAM_PRO.get
plugins/invite.lua
43
1335
do local function callbackres(extra, success, result) --vardump(result) local user = 'user#id'..result.peer_id local chat = 'chat#id'..extra.chatid local channel = 'channel#id'..extra.chatid if is_banned(result.id, extra.chatid) then send_large_msg(chat, 'User is banned.') send_large_msg(channel, 'User is banned.') elseif is_gbanned(result.id) then send_large_msg(chat, 'User is globaly banned.') send_large_msg(channel, 'User is globaly banned.') else chat_add_user(chat, user, ok_cb, false) channel_invite(channel, user, ok_cb, false) end end function run(msg, matches) local data = load_data(_config.moderation.data) if not is_momod(msg) then return end if not is_admin1(msg) then -- For admins only ! return 'Only admins can invite.' end if not is_realm(msg) then if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin1(msg) then return 'Group is private.' end end if msg.to.type ~= 'chat' or msg.to.type ~= 'channel' then local cbres_extra = {chatid = msg.to.id} local username = matches[1] local username = username:gsub("@","") resolve_username(username, callbackres, cbres_extra) end end return { patterns = { "^اضافه (.*)$" }, run = run } end
gpl-2.0
starkos/premake-core
src/_premake_init.lua
1
31795
-- -- _premake_init.lua -- -- Prepares the runtime environment for the add-ons and user project scripts. -- -- Copyright (c) 2012-2015 Jason Perkins and the Premake project -- local p = premake local api = p.api local DOC_URL = "See https://github.com/premake/premake-core/wiki/" ----------------------------------------------------------------------------- -- -- Register the core API functions. -- ----------------------------------------------------------------------------- api.register { name = "architecture", scope = "config", kind = "string", allowed = { "universal", p.X86, p.X86_64, p.ARM, p.ARM64, }, aliases = { i386 = p.X86, amd64 = p.X86_64, x32 = p.X86, -- these should be DEPRECATED x64 = p.X86_64, }, } api.register { name = "atl", scope = "config", kind = "string", allowed = { "Off", "Dynamic", "Static", }, } api.register { name = "basedir", scope = "project", kind = "path" } api.register { name = "buildaction", scope = "config", kind = "string", } api.register { name = "buildcommands", scope = { "config", "rule" }, kind = "list:string", tokens = true, pathVars = true, } api.register { name = "buildcustomizations", scope = "project", kind = "list:string", } api.register { name = "builddependencies", scope = { "rule" }, kind = "list:string", tokens = true, pathVars = true, } api.register { name = "buildlog", scope = { "config" }, kind = "path", tokens = true, pathVars = true, } api.register { name = "buildmessage", scope = { "config", "rule" }, kind = "string", tokens = true, pathVars = true, } api.register { name = "buildoptions", scope = "config", kind = "list:string", tokens = true, pathVars = true, } api.register { name = "buildoutputs", scope = { "config", "rule" }, kind = "list:path", tokens = true, pathVars = false, } api.register { name = "buildinputs", scope = "config", kind = "list:path", tokens = true, pathVars = false, } api.register { name = "buildrule", -- DEPRECATED scope = "config", kind = "table", tokens = true, } api.register { name = "characterset", scope = "config", kind = "string", allowed = { "Default", "ASCII", "MBCS", "Unicode", } } api.register { name = "cleancommands", scope = "config", kind = "list:string", tokens = true, pathVars = true, } api.register { name = "cleanextensions", scope = "config", kind = "list:string", } api.register { name = "clr", scope = "config", kind = "string", allowed = { "Off", "On", "Pure", "Safe", "Unsafe", "NetCore", } } api.register { name = "compilebuildoutputs", scope = "config", kind = "boolean" } api.register { name = "compileas", scope = "config", kind = "string", allowed = { "Default", "C", "C++", "Objective-C", "Objective-C++", "Module", "ModulePartition", "HeaderUnit" } } api.register { name = "configmap", scope = "project", kind = "list:keyed:array:string", } api.register { name = "configurations", scope = "project", kind = "list:string", } api.register { name = "copylocal", scope = "config", kind = "list:mixed", tokens = true, } api.register { name = "debugargs", scope = "config", kind = "list:string", tokens = true, pathVars = true, allowDuplicates = true, } api.register { name = "debugcommand", scope = "config", kind = "path", tokens = true, pathVars = true, } api.register { name = "debugconnectcommands", scope = "config", kind = "list:string", tokens = true, } api.register { name = "debugdir", scope = "config", kind = "path", tokens = true, pathVars = true, } api.register { name = "debugenvs", scope = "config", kind = "list:string", tokens = true, pathVars = true, } api.register { name = "debugextendedprotocol", scope = "config", kind = "boolean", } api.register { name = "debugformat", scope = "config", kind = "string", allowed = { "Default", "c7", "Dwarf", "SplitDwarf", }, } api.register { name = "debugger", scope = "config", kind = "string", allowed = { "Default", "GDB", "LLDB", } } api.register { name = "debuggertype", scope = "config", kind = "string", allowed = { "Mixed", "NativeOnly", "ManagedOnly", } } api.register { name = "debugpathmap", scope = "config", kind = "list:keyed:path", tokens = true, } api.register { name = "debugport", scope = "config", kind = "integer", } api.register { name = "debugremotehost", scope = "config", kind = "string", tokens = true, } api.register { name = "debugsearchpaths", scope = "config", kind = "list:path", tokens = true, } api.register { name = "debugstartupcommands", scope = "config", kind = "list:string", tokens = true, } api.register { name = "debugtoolargs", scope = "config", kind = "list:string", tokens = true, pathVars = true, } api.register { name = "debugtoolcommand", scope = "config", kind = "path", tokens = true, pathVars = true, } api.register { name = "defaultplatform", scope = "project", kind = "string", } api.register { name = "defines", scope = "config", kind = "list:string", tokens = true, } api.register { name = "dependson", scope = "config", kind = "list:string", tokens = true, } api.register { name = "disablewarnings", scope = "config", kind = "list:string", tokens = true, } api.register { name = "display", scope = "rule", kind = "string", } api.register { name = "dpiawareness", scope = "config", kind = "string", allowed = { "Default", "None", "High", "HighPerMonitor", } } api.register { name = "editandcontinue", scope = "config", kind = "string", allowed = { "Default", "On", "Off", }, } api.register { name = "exceptionhandling", scope = "config", kind = "string", allowed = { "Default", "On", "Off", "SEH", "CThrow", }, } api.register { name = "enablewarnings", scope = "config", kind = "list:string", tokens = true, } api.register { name = "endian", scope = "config", kind = "string", allowed = { "Default", "Little", "Big", }, } api.register { name = "entrypoint", scope = "config", kind = "string", } api.register { name = "fastuptodate", scope = "project", kind = "boolean", } api.register { name = "fatalwarnings", scope = "config", kind = "list:string", tokens = true, } api.register { name = "fileextension", scope = "rule", kind = "list:string", } api.register { name = "filename", scope = { "project", "rule" }, kind = "string", tokens = true, } api.register { name = "files", scope = "config", kind = "list:file", tokens = true, } api.register { name = "functionlevellinking", scope = "config", kind = "boolean" } api.register { name = "flags", scope = "config", kind = "list:string", allowed = { "Component", -- DEPRECATED "DebugEnvsDontMerge", "DebugEnvsInherit", "EnableSSE", -- DEPRECATED "EnableSSE2", -- DEPRECATED "ExcludeFromBuild", "ExtraWarnings", -- DEPRECATED "FatalCompileWarnings", "FatalLinkWarnings", "FloatFast", -- DEPRECATED "FloatStrict", -- DEPRECATED "LinkTimeOptimization", "Managed", -- DEPRECATED "Maps", "MFC", "MultiProcessorCompile", "NativeWChar", -- DEPRECATED "No64BitChecks", "NoCopyLocal", "NoEditAndContinue", -- DEPRECATED "NoFramePointer", -- DEPRECATED "NoImplicitLink", "NoImportLib", "NoIncrementalLink", "NoManifest", "NoMinimalRebuild", "NoNativeWChar", -- DEPRECATED "NoPCH", "NoRuntimeChecks", "NoBufferSecurityCheck", "NoWarnings", -- DEPRECATED "OmitDefaultLibrary", "Optimize", -- DEPRECATED "OptimizeSize", -- DEPRECATED "OptimizeSpeed", -- DEPRECATED "RelativeLinks", "ReleaseRuntime", -- DEPRECATED "ShadowedVariables", "StaticRuntime", -- DEPRECATED "Symbols", -- DEPRECATED "UndefinedIdentifiers", "WinMain", -- DEPRECATED "WPF", "C++11", -- DEPRECATED "C++14", -- DEPRECATED "C90", -- DEPRECATED "C99", -- DEPRECATED "C11", -- DEPRECATED }, aliases = { FatalWarnings = { "FatalWarnings", "FatalCompileWarnings", "FatalLinkWarnings" }, Optimise = 'Optimize', OptimiseSize = 'OptimizeSize', OptimiseSpeed = 'OptimizeSpeed', }, } api.register { name = "floatingpoint", scope = "config", kind = "string", allowed = { "Default", "Fast", "Strict", } } api.register { name = "floatingpointexceptions", scope = "config", kind = "boolean" } api.register { name = "inlining", scope = "config", kind = "string", allowed = { "Default", "Disabled", "Explicit", "Auto" } } api.register { name = "callingconvention", scope = "config", kind = "string", allowed = { "Cdecl", "FastCall", "StdCall", "VectorCall", } } api.register { name = "forceincludes", scope = "config", kind = "list:mixed", tokens = true, } api.register { name = "forceusings", scope = "config", kind = "list:file", tokens = true, } api.register { name = "fpu", scope = "config", kind = "string", allowed = { "Software", "Hardware", } } api.register { name = "dotnetframework", scope = "config", kind = "string", } api.register { name = "enabledefaultcompileitems", scope = "config", kind = "boolean", default = false } api.register { name = "csversion", scope = "config", kind = "string", } api.register { name = "gccprefix", scope = "config", kind = "string", tokens = true, } api.register { name = "ignoredefaultlibraries", scope = "config", kind = "list:mixed", tokens = true, } api.register { name = "icon", scope = "project", kind = "file", tokens = true, } api.register { name = "imageoptions", scope = "config", kind = "list:string", tokens = true, } api.register { name = "imagepath", scope = "config", kind = "path", tokens = true, } api.register { name = "implibdir", scope = "config", kind = "path", tokens = true, } api.register { name = "implibextension", scope = "config", kind = "string", tokens = true, } api.register { name = "implibname", scope = "config", kind = "string", tokens = true, } api.register { name = "implibprefix", scope = "config", kind = "string", tokens = true, } api.register { name = "implibsuffix", scope = "config", kind = "string", tokens = true, } api.register { name = "includedirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "intrinsics", scope = "config", kind = "boolean" } api.register { name = "bindirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "kind", scope = "config", kind = "string", allowed = { "ConsoleApp", "Makefile", "None", "SharedLib", "StaticLib", "WindowedApp", "Utility", "SharedItems", }, } api.register { name = "sharedlibtype", scope = "project", kind = "string", allowed = { "OSXBundle", "OSXFramework", "XCTest", }, } api.register { name = "language", scope = "project", kind = "string", allowed = { "C", "C++", "C#", "F#" } } api.register { name = "cdialect", scope = "config", kind = "string", allowed = { "Default", "C89", "C90", "C99", "C11", "gnu89", "gnu90", "gnu99", "gnu11", } } api.register { name = "cppdialect", scope = "config", kind = "string", allowed = { "Default", "C++latest", "C++98", "C++0x", "C++11", "C++1y", "C++14", "C++1z", "C++17", "C++2a", "C++20", "gnu++98", "gnu++0x", "gnu++11", "gnu++1y", "gnu++14", "gnu++1z", "gnu++17", "gnu++2a", "gnu++20", } } api.register { name = "conformancemode", scope = "config", kind = "boolean" } api.register { name = "usefullpaths", scope = "config", kind = "boolean" } api.register { name = "removeunreferencedcodedata", scope = "config", kind = "boolean" } api.register { name = "swiftversion", scope = "config", kind = "string", allowed = { "4.0", "4.2", "5.0", } } api.register { name = "libdirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "frameworkdirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "linkbuildoutputs", scope = "config", kind = "boolean" } api.register { name = "linkoptions", scope = "config", kind = "list:string", tokens = true, } api.register { name = "links", scope = "config", kind = "list:mixed", tokens = true, } api.register { name = "linkgroups", scope = "config", kind = "string", allowed = { "Off", "On", } } api.register { name = "locale", scope = "config", kind = "string", tokens = false, } api.register { name = "location", scope = { "project", "rule" }, kind = "path", tokens = true, } api.register { name = "makesettings", scope = "config", kind = "list:string", tokens = true, } api.register { name = "namespace", scope = "project", kind = "string", tokens = true, } api.register { name = "nativewchar", scope = "config", kind = "string", allowed = { "Default", "On", "Off", } } api.register { name = "nuget", scope = "config", kind = "list:string", tokens = true, } api.register { name = "nugetsource", scope = "project", kind = "string", tokens = true, } api.register { name = "objdir", scope = "config", kind = "path", tokens = true, } api.register { name = "optimize", scope = "config", kind = "string", allowed = { "Off", "On", "Debug", "Size", "Speed", "Full", } } api.register { name = "runpathdirs", scope = "config", kind = "list:path", tokens = true, } api.register { name = "runtime", scope = "config", kind = "string", allowed = { "Debug", "Release", } } api.register { name = "pchheader", scope = "config", kind = "string", tokens = true, } api.register { name = "pchsource", scope = "config", kind = "path", tokens = true, } api.register { name = "pic", scope = "config", kind = "string", allowed = { "Off", "On", } } api.register { name = "platforms", scope = "project", kind = "list:string", } api.register { name = "postbuildcommands", scope = "config", kind = "list:string", tokens = true, pathVars = true, allowDuplicates = true, } api.register { name = "postbuildmessage", scope = "config", kind = "string", tokens = true, pathVars = true, } api.register { name = "prebuildcommands", scope = "config", kind = "list:string", tokens = true, pathVars = true, allowDuplicates = true, } api.register { name = "prebuildmessage", scope = "config", kind = "string", tokens = true, pathVars = true, } api.register { name = "prelinkcommands", scope = "config", kind = "list:string", tokens = true, pathVars = true, } api.register { name = "prelinkmessage", scope = "config", kind = "string", tokens = true, pathVars = true, } api.register { name = "propertydefinition", scope = "rule", kind = "list:table", } api.register { name = "rebuildcommands", scope = "config", kind = "list:string", tokens = true, pathVars = true, } api.register { name = "resdefines", scope = "config", kind = "list:string", tokens = true, } api.register { name = "resincludedirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "resoptions", scope = "config", kind = "list:string", tokens = true, } api.register { name = "resourcegenerator", scope = "project", kind = "string", allowed = { "internal", "public" } } api.register { name = "rtti", scope = "config", kind = "string", allowed = { "Default", "On", "Off", }, } api.register { name = "rules", scope = "project", kind = "list:string", } api.register { name = "startproject", scope = "workspace", kind = "string", tokens = true, } api.register { name = "staticruntime", scope = "config", kind = "string", allowed = { "Default", "On", "Off" } } api.register { name = "strictaliasing", scope = "config", kind = "string", allowed = { "Off", "Level1", "Level2", "Level3", } } api.register { name = "stringpooling", scope = "config", kind = "boolean" } api.register { name = "symbols", scope = "config", kind = "string", allowed = { "Default", "On", "Off", "FastLink", -- Visual Studio 2015+ only, considered 'On' for all other cases. "Full", -- Visual Studio 2017+ only, considered 'On' for all other cases. }, } api.register { name = "symbolspath", scope = "config", kind = "path", tokens = true, } api.register { name = "sysincludedirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "syslibdirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "system", scope = "config", kind = "string", allowed = { "aix", "bsd", "haiku", "ios", "linux", "macosx", "solaris", "wii", "windows", }, } api.register { name = "systemversion", scope = "config", kind = "string", } api.register { name = "tags", scope = "config", kind = "list:string", } api.register { name = "tailcalls", scope = "config", kind = "boolean" } api.register { name = "targetdir", scope = "config", kind = "path", tokens = true, } api.register { name = "targetextension", scope = "config", kind = "string", tokens = true, } api.register { name = "targetname", scope = "config", kind = "string", tokens = true, } api.register { name = "targetprefix", scope = "config", kind = "string", tokens = true, } api.register { name = "targetsuffix", scope = "config", kind = "string", tokens = true, } api.register { name = "toolset", scope = "config", kind = "string", allowed = function(value) value = value:lower() local tool, version = p.tools.canonical(value) if tool then return p.tools.normalize(value) else return nil end end, } api.register { name = "toolsversion", scope = "project", kind = "string", tokens = true, } api.register { name = "customtoolnamespace", scope = "config", kind = "string", } api.register { name = "undefines", scope = "config", kind = "list:string", tokens = true, } api.register { name = "usingdirs", scope = "config", kind = "list:directory", tokens = true, } api.register { name = "uuid", scope = "project", kind = "string", allowed = function(value) local ok = true if (#value ~= 36) then ok = false end for i=1,36 do local ch = value:sub(i,i) if (not ch:find("[ABCDEFabcdef0123456789-]")) then ok = false end end if (value:sub(9,9) ~= "-") then ok = false end if (value:sub(14,14) ~= "-") then ok = false end if (value:sub(19,19) ~= "-") then ok = false end if (value:sub(24,24) ~= "-") then ok = false end if (not ok) then return nil, "invalid UUID" end return value:upper() end } api.register { name = "vectorextensions", scope = "config", kind = "string", allowed = { "Default", "AVX", "AVX2", "IA32", "SSE", "SSE2", "SSE3", "SSSE3", "SSE4.1", "SSE4.2", } } api.register { name = "isaextensions", scope = "config", kind = "list:string", allowed = { "MOVBE", "POPCNT", "PCLMUL", "LZCNT", "BMI", "BMI2", "F16C", "AES", "FMA", "FMA4", "RDRND", } } api.register { name = "vpaths", scope = "project", kind = "list:keyed:list:path", tokens = true, pathVars = true, } api.register { name = "warnings", scope = "config", kind = "string", allowed = { "Off", "Default", "High", "Extra", "Everything", } } api.register { name = "largeaddressaware", scope = "config", kind = "boolean", } api.register { name = "editorintegration", scope = "workspace", kind = "boolean", } api.register { name = "preferredtoolarchitecture", scope = "workspace", kind = "string", allowed = { "Default", p.X86, p.X86_64, } } api.register { name = "unsignedchar", scope = "config", kind = "boolean", } p.api.register { name = "structmemberalign", scope = "config", kind = "integer", allowed = { "1", "2", "4", "8", "16", } } api.register { name = "omitframepointer", scope = "config", kind = "string", allowed = { "Default", "On", "Off" } } api.register { name = "visibility", scope = "config", kind = "string", allowed = { "Default", "Hidden", "Internal", "Protected" } } api.register { name = "inlinesvisibility", scope = "config", kind = "string", allowed = { "Default", "Hidden" } } api.register { name = "assemblydebug", scope = "config", kind = "boolean" } api.register { name = "justmycode", scope = "project", kind = "string", allowed = { "On", "Off" } } api.register { name = "openmp", scope = "project", kind = "string", allowed = { "On", "Off" } } ----------------------------------------------------------------------------- -- -- Field name aliases for backward compatibility -- ----------------------------------------------------------------------------- api.alias("buildcommands", "buildCommands") api.alias("builddependencies", "buildDependencies") api.alias("buildmessage", "buildMessage") api.alias("buildoutputs", "buildOutputs") api.alias("cleanextensions", "cleanExtensions") api.alias("dotnetframework", "framework") api.alias("editandcontinue", "editAndContinue") api.alias("fileextension", "fileExtension") api.alias("propertydefinition", "propertyDefinition") api.alias("removefiles", "excludes") ----------------------------------------------------------------------------- -- -- Handlers for deprecated fields and values. -- ----------------------------------------------------------------------------- -- 13 Apr 2017 api.deprecateField("buildrule", 'Use `buildcommands`, `buildoutputs`, and `buildmessage` instead.', function(value) if value.description then buildmessage(value.description) end buildcommands(value.commands) buildoutputs(value.outputs) end) api.deprecateValue("flags", "Component", 'Use `buildaction "Component"` instead.', function(value) buildaction "Component" end) api.deprecateValue("flags", "EnableSSE", 'Use `vectorextensions "SSE"` instead.', function(value) vectorextensions("SSE") end, function(value) vectorextensions "Default" end) api.deprecateValue("flags", "EnableSSE2", 'Use `vectorextensions "SSE2"` instead.', function(value) vectorextensions("SSE2") end, function(value) vectorextensions "Default" end) api.deprecateValue("flags", "FloatFast", 'Use `floatingpoint "Fast"` instead.', function(value) floatingpoint("Fast") end, function(value) floatingpoint "Default" end) api.deprecateValue("flags", "FloatStrict", 'Use `floatingpoint "Strict"` instead.', function(value) floatingpoint("Strict") end, function(value) floatingpoint "Default" end) api.deprecateValue("flags", "NativeWChar", 'Use `nativewchar "On"` instead."', function(value) nativewchar("On") end, function(value) nativewchar "Default" end) api.deprecateValue("flags", "NoNativeWChar", 'Use `nativewchar "Off"` instead."', function(value) nativewchar("Off") end, function(value) nativewchar "Default" end) api.deprecateValue("flags", "Optimize", 'Use `optimize "On"` instead.', function(value) optimize ("On") end, function(value) optimize "Off" end) api.deprecateValue("flags", "OptimizeSize", 'Use `optimize "Size"` instead.', function(value) optimize ("Size") end, function(value) optimize "Off" end) api.deprecateValue("flags", "OptimizeSpeed", 'Use `optimize "Speed"` instead.', function(value) optimize ("Speed") end, function(value) optimize "Off" end) api.deprecateValue("flags", "ReleaseRuntime", 'Use `runtime "Release"` instead.', function(value) runtime "Release" end, function(value) end) api.deprecateValue("flags", "ExtraWarnings", 'Use `warnings "Extra"` instead.', function(value) warnings "Extra" end, function(value) warnings "Default" end) api.deprecateValue("flags", "NoWarnings", 'Use `warnings "Off"` instead.', function(value) warnings "Off" end, function(value) warnings "Default" end) api.deprecateValue("flags", "Managed", 'Use `clr "On"` instead.', function(value) clr "On" end, function(value) clr "Off" end) api.deprecateValue("flags", "NoEditAndContinue", 'Use editandcontinue "Off"` instead.', function(value) editandcontinue "Off" end, function(value) editandcontinue "On" end) -- 21 June 2016 api.deprecateValue("flags", "Symbols", 'Use `symbols "On"` instead', function(value) symbols "On" end, function(value) symbols "Default" end) -- 31 January 2017 api.deprecateValue("flags", "C++11", 'Use `cppdialect "C++11"` instead', function(value) cppdialect "C++11" end, function(value) cppdialect "Default" end) api.deprecateValue("flags", "C++14", 'Use `cppdialect "C++14"` instead', function(value) cppdialect "C++14" end, function(value) cppdialect "Default" end) api.deprecateValue("flags", "C90", 'Use `cdialect "gnu90"` instead', function(value) cdialect "gnu90" end, function(value) cdialect "Default" end) api.deprecateValue("flags", "C99", 'Use `cdialect "gnu99"` instead', function(value) cdialect "gnu99" end, function(value) cdialect "Default" end) api.deprecateValue("flags", "C11", 'Use `cdialect "gnu11"` instead', function(value) cdialect "gnu11" end, function(value) cdialect "Default" end) -- 13 April 2017 api.deprecateValue("flags", "WinMain", 'Use `entrypoint "WinMainCRTStartup"` instead', function(value) entrypoint "WinMainCRTStartup" end, function(value) entrypoint "mainCRTStartup" end) -- 31 October 2017 api.deprecateValue("flags", "StaticRuntime", 'Use `staticruntime "On"` instead', function(value) staticruntime "On" end, function(value) staticruntime "Default" end) -- 08 April 2018 api.deprecateValue("flags", "NoFramePointer", 'Use `omitframepointer "On"` instead.', function(value) omitframepointer("On") end, function(value) omitframepointer("Default") end) ----------------------------------------------------------------------------- -- -- Install Premake's default set of command line arguments. -- ----------------------------------------------------------------------------- newoption { category = "compilers", trigger = "cc", value = "VALUE", description = "Choose a C/C++ compiler set", allowed = { { "clang", "Clang (clang)" }, { "gcc", "GNU GCC (gcc/g++)" }, { "mingw", "MinGW GCC (gcc/g++)" }, } } newoption { category = "compilers", trigger = "dotnet", value = "VALUE", description = "Choose a .NET compiler set", allowed = { { "msnet", "Microsoft .NET (csc)" }, { "mono", "Novell Mono (mcs)" }, { "pnet", "Portable.NET (cscc)" }, } } newoption { trigger = "fatal", description = "Treat warnings from project scripts as errors" } newoption { trigger = "debugger", description = "Start MobDebug remote debugger. Works with ZeroBrane Studio" } newoption { trigger = "file", value = "FILE", description = "Read FILE as a Premake script; default is 'premake5.lua'" } newoption { trigger = "help", description = "Display this information" } newoption { trigger = "verbose", description = "Generate extra debug text output" } newoption { trigger = "interactive", description = "Interactive command prompt" } newoption { trigger = "os", value = "VALUE", description = "Generate files for a different operating system", allowed = { { "aix", "IBM AIX" }, { "bsd", "OpenBSD, NetBSD, or FreeBSD" }, { "haiku", "Haiku" }, { "hurd", "GNU/Hurd" }, { "ios", "iOS" }, { "linux", "Linux" }, { "macosx", "Apple Mac OS X" }, { "solaris", "Solaris" }, { "windows", "Microsoft Windows" }, } } newoption { trigger = "scripts", value = "PATH", description = "Search for additional scripts on the given path" } newoption { trigger = "systemscript", value = "FILE", description = "Override default system script (premake5-system.lua)" } newoption { trigger = "version", description = "Display version information" } if http ~= nil then newoption { trigger = "insecure", description = "forfit SSH certification checks." } end ----------------------------------------------------------------------------- -- -- Set up the global environment for the systems I know about. I would like -- to see at least some if not all of this moved into add-ons in the future. -- ----------------------------------------------------------------------------- characterset "Default" clr "Off" editorintegration "Off" exceptionhandling "Default" rtti "Default" symbols "Default" nugetsource "https://api.nuget.org/v3/index.json" -- Setting a default language makes some validation easier later language "C++" -- Use Posix-style target naming by default, since it is the most common. filter { "kind:SharedLib" } targetprefix "lib" targetextension ".so" filter { "kind:StaticLib" } targetprefix "lib" targetextension ".a" -- Add variations for other Posix-like systems. filter { "system:darwin", "kind:WindowedApp" } targetextension ".app" filter { "system:darwin", "kind:SharedLib" } targetextension ".dylib" filter { "system:darwin", "kind:SharedLib", "sharedlibtype:OSXBundle" } targetprefix "" targetextension ".bundle" filter { "system:darwin", "kind:SharedLib", "sharedlibtype:OSXFramework" } targetprefix "" targetextension ".framework" filter { "system:darwin", "kind:SharedLib", "sharedlibtype:XCTest" } targetprefix "" targetextension ".xctest" -- Windows and friends. filter { "system:Windows or language:C# or language:F#", "kind:ConsoleApp or WindowedApp" } targetextension ".exe" filter { "system:Windows", "kind:SharedLib" } targetprefix "" targetextension ".dll" implibextension ".lib" filter { "system:Windows", "kind:StaticLib" } targetprefix "" targetextension ".lib" filter { "language:C# or language:F#", "kind:SharedLib" } targetprefix "" targetextension ".dll" implibextension ".dll" filter { "kind:SharedLib", "system:not Windows" } pic "On" filter { "system:darwin" } toolset "clang" filter { "platforms:Win64" } architecture "x86_64" filter {}
bsd-3-clause
timroes/awesome
tests/examples/shims/awesome.lua
3
1322
local gears_obj = require("gears.object") -- Emulate the C API classes. They differ from C API objects as connect_signal -- doesn't take an object as first argument and they support fallback properties -- handlers. local function _shim_fake_class() local obj = gears_obj() obj.data = {} local meta = { __index = function()end, __newindex = function()end, } obj._connect_signal = obj.connect_signal function obj.connect_signal(name, func) return obj._connect_signal(obj, name, func) end function obj.set_index_miss_handler(handler) meta.__index = handler end function obj.set_newindex_miss_handler(handler) meta.__newindex = handler end function obj.emit_signal(name, c, ...) local conns = obj._signals[name] or {strong={}} for func in pairs(conns.strong) do func(c, ...) end end return obj, meta end local awesome = _shim_fake_class() awesome._shim_fake_class = _shim_fake_class -- Avoid c.screen = acreen.focused() to be called, all tests will fail awesome.startup = true function awesome.register_xproperty() end -- Always show deprecated messages awesome.version = "v9999" return awesome -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
omidtarh/fire
plugins/stats.lua
24
3698
do local NUM_MSG_MAX = 1 local TIME_CHECK = 1 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- 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(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 = '' 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 pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood local kick = chat_del_user(chat_id , user_id, ok_cb, true) vardump(kick) if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false) print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end 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..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
TimSimpson/Macaroni
Main/Generators/Cpp/HFileGenerator.lua
2
2569
require "Cpp/Common"; require "Cpp/ClassHFileGenerator"; require "Cpp/LibraryConfigGenerator"; require "Cpp/NamespaceHFileGenerator"; require "Cpp/NodeFileGenerator"; require "Cpp/TypedefFileGenerator"; require "Macaroni.Model.FileName"; require "Macaroni.Model.Reason"; require "Macaroni.Model.Source"; local Access = require "Macaroni.Model.Cpp.Access"; local Context = require "Macaroni.Model.Context"; local Node = require "Macaroni.Model.Node"; local TypeNames = Macaroni.Model.TypeNames; HFileGenerator = { new = function(library) if (library == nil) then error("No library argument given."); end args = {} setmetatable(args, HFileGenerator); args.targetLibrary = library; HFileGenerator.__index = function(t, k) local v = HFileGenerator[k]; if (not v) then v = NodeFileGenerator[k]; end return v; end; args.libDecl = LibraryDecl(args.targetLibrary); return args; end, attemptShortName = false, createClassGenerator = function (self, node, path) log:Write("HcreateClassGenerator 1"); local reason = node.Member.ReasonCreated; local srcFile = reason.Source.FileName.OsName; log:Write("HcreateClassGenerator 1.5"); local filePath = path:NewPath(".h"); log:Write("HcreateClassGenerator 2"); log:Write("Htype of filePath is " .. type(filePath) .. "."); log:Write("HsrcFile is " .. srcFile .. "."); if (filePath:IsFileOlderThan(srcFile)) then log:Write("HcreateClassGenerator 2.2"); local cg = ClassHFileGenerator.new{node = node, targetLibrary=self.targetLibrary, path = filePath}; return cg; else log:Write("HcreateClassGenerator 2.5"); -- Skip if no new changes detected. return { parse = function() end }; end end, createNamespaceFileGenerator = function (self, node, path) local filePath = path:NewPath("/_.h"); local ng = NamespaceHFileGenerator.new{ node = node, path = filePath, targetLibrary = self.targetLibrary }; return ng; end, createTypedefFileGenerator = function (self, node, path) local filePath = path:NewPath(".h"); local tg = TypedefFileGenerator.new{ node = node, path = filePath, targetLibrary = self.targetLibrary }; return tg; end, }; -- end HFileGenerator
apache-2.0
botzedspam/blackplus
plugins/inSuper.lua
1
75011
--Begin supergrpup.lua --Check members #Add supergroup 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, "Promote me to admin first!") 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_tgservice = 'yes', 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 = 'SuperGroup has been added!' 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 = 'SuperGroup has been removed' 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 ="Info for SuperGroup > ["..result.title.."]\n\n" local admin_num = "Admin count > "..result.admins_count.."\n" local user_num = "User count > "..result.participants_count.."\n" local kicked_num = "Kicked user count > "..result.kicked_count.."\n" local channel_id = "ID > "..result.peer_id.."\n" if result.username then channel_username = "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 = "Members for "..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 = "Kicked Members for SuperGroup "..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_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return '*Link posting is already locked' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return '*Link posting has been locked' end end local function unlock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return '*Link posting is not locked' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return '*Link posting has been unlocked' 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 "*Owners only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return '*SuperGroup spam is already locked' else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return '*SuperGroup spam has been locked' 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 '*SuperGroup spam is not locked' else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return '*SuperGroup spam has been unlocked' 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 '*Spamming is already locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return '*Spamming has been locked' 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 '*Spamming is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return '*Spamming has been unlocked' 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 '*Arabic/Persian is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return '*Arabic/Persian has been locked' 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 '*Arabic/Persian is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return '*Arabic/Persian has been unlocked' 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 '*SuperGroup members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return '*SuperGroup members has been locked' 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 '*SuperGroup members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return '*SuperGroup members has been unlocked' 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 '*RTL is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return '*RTL has been locked' 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 '*RTL is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return '*RTL has been unlocked' end end local function lock_group_tgservice(msg, data, target) if not is_momod(msg) then return end local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice'] if group_tgservice_lock == 'yes' then return '*TGservice is already locked' else data[tostring(target)]['settings']['lock_tgservice'] = 'yes' save_data(_config.moderation.data, data) return '*TGservice has been locked' end end local function unlock_group_tgservice(msg, data, target) if not is_momod(msg) then return end local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice'] if group_tgservice_lock == 'no' then return '*TGService Is Not Locked!' else data[tostring(target)]['settings']['lock_tgservice'] = 'no' save_data(_config.moderation.data, data) return '*TGservice has been unlocked' 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 '*Sticker posting is already locked' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return '*Sticker posting has been locked' 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 '*Sticker posting is already unlocked' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return '*Sticker posting has been unlocked' end end local function lock_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 == 'yes' then return '*Contact posting is already locked' else data[tostring(target)]['settings']['lock_contacts'] = 'yes' save_data(_config.moderation.data, data) return '*Contact posting has been locked' 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 '**Contact posting is already unlocked' else data[tostring(target)]['settings']['lock_contacts'] = 'no' save_data(_config.moderation.data, data) return '*Contact posting has been unlocked' 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 '*Settings are already strictly enforced' else data[tostring(target)]['settings']['strict'] = 'yes' save_data(_config.moderation.data, data) return '*Settings will be strictly enforced' 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 '*Settings are not strictly enforced' else data[tostring(target)]['settings']['strict'] = 'no' save_data(_config.moderation.data, data) return '*Settings will not be strictly enforced' 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 '*SuperGroup rules set' 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 '*No rules available.' 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..' rules:\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 "*For moderators only!" 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 '*Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return '*SuperGroup is now: public' 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 '*Group is not public' else data[tostring(target)]['settings']['public'] = 'no' data[tostring(target)]['long_id'] = msg.to.long_id save_data(_config.moderation.data, data) return '*SuperGroup is now: not public' 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_tgservice'] then data[tostring(target)]['settings']['lock_tgservice'] = '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 = "SuperGroup settings:\n\nLock Links > "..settings.lock_link.."\nLock Flood > "..settings.flood.."\nFlood sensitivity > "..NUM_MSG_MAX.."\nLock Spam > "..settings.lock_spam.."\nLock Arabic/Persian > "..settings.lock_arabic.."\nLock Member > "..settings.lock_member.."\nLock RTL > "..settings.lock_rtl.."\nLock TGservice > "..settings.lock_tgservice.."\nLock Sticker > "..settings.lock_sticker.."\nPublic > "..settings.public.."\nStrict Settings > "..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..' is already a moderator.') 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..' is not a moderator.') 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, 'SuperGroup is not added.') end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been promoted.') 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 send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' is not a moderator.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been demoted.') 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 '*SuperGroup is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then return '*No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. 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 == "id" 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 == 'id' 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, "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 --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, "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 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 == "del" 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 == "setadmin" 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.." set as an admin" else text = "[ "..user_id.." ]set as an admin" 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 == "demoteadmin" 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, "You can't demote global admins!") end channel_demote(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." has been demoted from admin" else text = "[ "..user_id.." ] has been demoted from admin" 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 == "setowner" 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.." ] added as owner" else text = "[ "..result.from.peer_id.." ] added as owner" end send_large_msg(channel_id, text) end elseif get_cmd == "promote" 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 == "demote" 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.."] demoted mod: @"..member_username.."["..user_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.."] removed from the muted user list") elseif is_admin1(msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to the muted user list") 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 == "demoteadmin" then if is_admin2(result.peer_id) then return send_large_msg(receiver, "You can't demote global admins!") end local user_id = "user#id"..result.peer_id channel_demote(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(receiver, text) else text = "[ "..result.peer_id.." ] has been demoted from admin" send_large_msg(receiver, text) end elseif get_cmd == "promote" 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 == "demote" 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 == "res" 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 == "id" 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 == "promote" 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 == "demote" 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 == "demoteadmin" 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(channel_id, "You can't demote global admins!") end channel_demote(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been demoted from admin" 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 = '*No user @'..member..' in this SuperGroup.' else text = '*No user ['..memberid..'] in this SuperGroup.' 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, "You can't kick mods/owner/admins") end if is_admin2(user_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") 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 == "setadmin" 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.."] has been set as an admin" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]") else text = "> ["..v.peer_id.."] has been set as an admin" 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 == 'setowner' 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.."] added as owner" else text = "> ["..v.peer_id.."] added as owner" 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.."] added as owner" 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] == 'upchat' 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] == 'upchat' then if not is_admin1(msg) then return end return "Already a SuperGroup" 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] == 'add' 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, 'SuperGroup is already added.', 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] == 'rem' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then return reply_msg(msg.id, 'SuperGroup is not added.', 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] == "info" 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] == "admins" then if not is_owner(msg) and not is_support(msg.from.id) then return end member_type = 'Admins' 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] == "owner" then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "*no owner,ask admins in support groups to set owner for your SuperGroup" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "SuperGroup owner is > ["..group_owner..']' end if matches[1] == "modlist" 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] == "bots" and is_momod(msg) then member_type = 'Bots' 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] == "who" 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] == 'del' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'del', msg = msg } delete_msg(msg.id, ok_cb, false) get_message(msg.reply_id, get_message_callback, cbreply_extra) end end if matches[1] == 'kick' 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] == 'kick' 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] == 'id' then if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then local cbreply_extra = { get_cmd = 'id', 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 = 'id' } 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 "> Group ID: "..msg.to.id.."\n> Group Name: "..msg.to.title.."\n> First Name: "..(msg.from.first_name or '').."\n> Last Name: "..(msg.from.last_name or '').."\n> Your ID: "..msg.from.id.."\n> Username: @"..(msg.from.username or '').."\n> Phone Number: +"..(msg.from.phone or '') end end if matches[1] == 'kickme' 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] == 'newlink' 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, '*Error \nReason: Not creator \n please use /setlink to set it') data[tostring(msg.to.id)]['settings']['set_link'] = nil save_data(_config.moderation.data, data) else send_large_msg(receiver, "Created a new link") 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] == 'setlink' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send the new group link now!' end if msg.text then if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = msg.text save_data(_config.moderation.data, data) return "New link set !" end end if matches[1] == 'link' then if not is_momod(msg) then return end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "> Create a link using /newlink first!\n\nOr if I am not creator use /setlink to set your link" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\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] == 'res' and is_owner(msg) then local cbres_extra = { channelid = msg.to.id, get_cmd = 'res' } 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] == 'setadmin' 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 = 'setadmin', msg = msg } setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'setadmin' 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 = 'setadmin' 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] == 'setadmin' 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 = 'setadmin' 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] == 'demoteadmin' 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 = 'demoteadmin', msg = msg } demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'demoteadmin' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demoteadmin' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'demoteadmin' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demoteadmin' } 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] == 'setowner' and is_owner(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'setowner', msg = msg } setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'setowner' 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 = 'setowner' 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] == 'setowner' and not string.match(matches[2], '^%d+$') then local get_cmd = 'setowner' 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] == 'promote' then if not is_momod(msg) then return end if not is_owner(msg) then return "*Error \nOnly owner/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'promote', msg = msg } promote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'promote' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'promote' 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] == 'promote' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'promote', } 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 "Done" 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 "Done" end if matches[1] == 'demote' then if not is_momod(msg) then return end if not is_owner(msg) then return "*Error \nOnly owner/support/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demote', msg = msg } demote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'demote' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demote' 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 = 'demote' } 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] == "setname" 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] == "setabout" 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 "Description has been set.\n\nSelect the chat again to see the changes." end if matches[1] == "setusername" 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, "SuperGroup username Set.\n\nSelect the chat again to see the changes.") elseif success == 0 then send_large_msg(receiver, "Failed to set SuperGroup username.\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] == 'setrules' 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] == 'setphoto' 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 '> Please send the new group photo now!' end if matches[1] == 'clean' then if not is_momod(msg) then return end if not is_momod(msg) then return "Only owner can clean" end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'No moderator(s) in this SuperGroup!' 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 'Modlist has been cleaned!' end if matches[2] == 'rules' then local data_cat = 'rules' if data[tostring(msg.to.id)][data_cat] == nil then return "Rules have not been set" 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 'Rules have been cleaned' end if matches[2] == 'about' then local receiver = get_receiver(msg) local about_text = ' ' local data_cat = 'description' if data[tostring(msg.to.id)][data_cat] == nil then return 'About is not set' 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 "About has been cleaned" end if matches[2] == 'mutelist' then chat_id = msg.to.id local hash = 'mute_user:'..chat_id redis:del(hash) return "Mutelist Cleaned" end if matches[2] == 'username' 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, "SuperGroup username cleaned.") elseif success == 0 then send_large_msg(receiver, "Failed to clean SuperGroup username.") end end local username = "" channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end end if matches[1] == 'lock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ") return lock_group_links(msg, data, target) end if matches[2] == 'spam' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ") return lock_group_spam(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_flood(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2]:lower() == 'rtl' 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] == 'tgservice' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked Tgservice Actions") return lock_group_tgservice(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting") return lock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting") return lock_group_contacts(msg, data, target) end if matches[2] == 'strict' 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] == 'unlock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting") return unlock_group_links(msg, data, target) end if matches[2] == 'spam' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam") return unlock_group_spam(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood") return unlock_group_flood(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked Arabic") return unlock_group_arabic(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2]:lower() == 'rtl' 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] == 'tgservice' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tgservice actions") return unlock_group_tgservice(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting") return unlock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting") return unlock_group_contacts(msg, data, target) end if matches[2] == 'strict' 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] == 'setflood' then if not is_momod(msg) then return end if tonumber(matches[2]) < 2 or tonumber(matches[2]) > 50 then return "Wrong number,range is [2-50]" 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 'Flood has been set to: '..matches[2] end if matches[1] == 'public' and is_momod(msg) then local target = msg.to.id if matches[2] == 'yes' 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] == 'no' 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] == 'mute' and is_owner(msg) then local chat_id = msg.to.id if matches[2] == 'audio' 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 msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'photo' 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 msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'video' 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 msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'gifs' 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 msg_type.." have been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'documents' 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 msg_type.." have been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'text' 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 msg_type.." has been muted" else return "Mute "..msg_type.." is already on" end end if matches[2] == 'all' 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 "Mute "..msg_type.." has been enabled" else return "Mute "..msg_type.." is already on" end end end if matches[1] == 'unmute' and is_momod(msg) then local chat_id = msg.to.id if matches[2] == 'audio' 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 msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'photo' 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 msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'video' 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 msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'gifs' 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 msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'documents' 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 msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'text' 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 msg_type.." has been unmuted" else return "Mute text is already off" end end if matches[2] == 'all' 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 "> Mute "..msg_type.." has been disabled" else return "> Mute "..msg_type.." is already disabled" end end end if matches[1] == "muteuser" 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] == "muteuser" 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_owner(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] == "muteuser" 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] == "muteslist" 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] == "mutelist" 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] == 'settings' 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] == 'rules' 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 @BlackPlus 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 = { "^[#!/]([Aa]dd)$", "^[#!/]([Rr]em)$", "^[#!/]([Mm]ove) (.*)$", "^[#!/]([Ii]nfo)$", "^[#!/]([Aa]dmins)$", "^[#!/]([Oo]wner)$", "^[#!/]([Mm]odlist)$", "^[#!/]([Bb]ots)$", "^[#!/]([Ww]ho)$", "^[#!/]([Kk]icked)$", "^[#!/]([Kk]ick) (.*)", "^[#!/]([Kk]ick)", "^[#!/]([Uu]pchat)$", "^[#!/]([Ii][Dd])$", "^[#!/]([Ii][Dd]) (.*)$", "^[#!/]([Kk]ickme)$", "^[#!/]([Kk]ick) (.*)$", "^[#!/]([Nn]ewlink)$", "^[#!/]([Ss]etlink)$", "^[#!/]([Ll]ink)$", "^[#!/]([Rr]es) (.*)$", "^[#!/]([Ss]etadmin) (.*)$", "^[#!/]([Ss]etadmin)", "^[#!/]([Dd]emoteadmin) (.*)$", "^[#!/]([Dd]emoteadmin)", "^[#!/]([Ss]etowner) (.*)$", "^[#!/]([Ss]etowner)$", "^[#!/]([Pp]romote) (.*)$", "^[#!/]([Pp]romote)", "^[#!/]([Dd]emote) (.*)$", "^[#!/]([Dd]emote)", "^[#!/]([Ss]etname) (.*)$", "^[#!/]([Ss]etabout) (.*)$", "^[#!/]([Ss]etrules) (.*)$", "^[#!/]([Ss]etphoto)$", "^[#!/]([Ss]etusername) (.*)$", "^[#!/]([Dd]el)$", "^[#!/]([Ll]ock) (.*)$", "^[#!/]([Uu]nlock) (.*)$", "^[#!/]([Mm]ute) ([^%s]+)$", "^[#!/]([Uu]nmute) ([^%s]+)$", "^[#!/]([Mm]uteuser)$", "^[#!/]([Mm]uteuser) (.*)$", "^[#!/]([Pp]ublic) (.*)$", "^[#!/]([Ss]ettings)$", "^[#!/]([Rr]ules)$", "^[#!/]([Ss]etflood) (%d+)$", "^[#!/]([Cc]lean) (.*)$", "^[#!/]([Hh]elp)$", "^[#!/]([Mm]uteslist)$", "^[#!/]([Mm]utelist)$", "[#!/](mp) (.*)", "[#!/](md) (.*)", "([Hh][Tt][Tt][Pp][Ss]://[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/[Jj][Oo][Ii][Nn][Cc][Hh][Aa][Tt]/%S+)", "msg.to.peer_id", "%[(document)%]", "%[(photo)%]", "%[(video)%]", "%[(audio)%]", "%[(contact)%]", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
blueyed/awesome
lib/awful/keygrabber.lua
4
2973
--------------------------------------------------------------------------- --- Keygrabber Stack -- -- @author dodo -- @copyright 2012 dodo -- @module awful.keygrabber --------------------------------------------------------------------------- local ipairs = ipairs local table = table local capi = { keygrabber = keygrabber } local keygrabber = {} -- Private data local grabbers = {} local keygrabbing = false local function grabber(mod, key, event) for _, keygrabber_function in ipairs(grabbers) do -- continue if the grabber explicitly returns false if keygrabber_function(mod, key, event) ~= false then break end end end --- Stop grabbing the keyboard for the provided callback. -- When no callback is given, the last grabber gets removed (last one added to -- the stack). -- @param g The key grabber that must be removed. function keygrabber.stop(g) for i, v in ipairs(grabbers) do if v == g then table.remove(grabbers, i) break end end -- Stop the global key grabber if the last grabber disappears from stack. if #grabbers == 0 then keygrabbing = false capi.keygrabber.stop() end end --- -- Grab keyboard input and read pressed keys, calling the least callback -- function from the stack at each keypress, until the stack is empty. -- -- Calling run with the same callback again will bring the callback -- to the top of the stack. -- -- The callback function receives three arguments: -- -- * a table containing modifiers keys -- * a string with the pressed key -- * a string with either "press" or "release" to indicate the event type -- -- A callback can return `false` to pass the events to the next -- keygrabber in the stack. -- @param g The key grabber callback that will get the key events until it will be deleted or a new grabber is added. -- @return the given callback `g`. -- @usage -- -- The following function can be bound to a key, and be used to resize a -- -- client using the keyboard. -- -- function resize(c) -- local grabber = awful.keygrabber.run(function(mod, key, event) -- if event == "release" then return end -- -- if key == 'Up' then c:relative_move(0, 0, 0, 5) -- elseif key == 'Down' then c:relative_move(0, 0, 0, -5) -- elseif key == 'Right' then c:relative_move(0, 0, 5, 0) -- elseif key == 'Left' then c:relative_move(0, 0, -5, 0) -- else awful.keygrabber.stop(grabber) -- end -- end) -- end function keygrabber.run(g) -- Remove the grabber if it is in the stack. keygrabber.stop(g) -- Record the grabber that has been added most recently. table.insert(grabbers, 1, g) -- Start the keygrabber if it is not running already. if not keygrabbing then keygrabbing = true capi.keygrabber.run(grabber) end return g end return keygrabber -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
CrazyEddieTK/Zero-K
LuaRules/Gadgets/dbg_animator.lua
5
6266
------------------------ function gadget:GetInfo() return { name = "Animator", desc = "v0.002 Moves and turns pieces.", author = "CarRepairer & knorke", date = "2010-03-05", license = "raubkopierer sind verbrecher", layer = 0, enabled = false, } end local function tobool(val) local t = type(val) if (t == 'nil') then return false elseif (t == 'boolean') then return val elseif (t == 'number') then return (val ~= 0) elseif (t == 'string') then return ((val ~= '0') and (val ~= 'false')) end return false end local devMode = tobool(Spring.GetModOptions().devmode) --if not devMode then return end local echo = Spring.Echo if (gadgetHandler:IsSyncedCode()) then local function WriteCurrent( unitID ) local env = true -- Spring.UnitScript.GetScriptEnv(unitID) if not env then return end local allpieces = Spring.GetUnitPieceMap(unitID) local s = "function POSENAME (mspeed, tspeed)\n" local allpieces2 = {} for pname,pid in pairs(allpieces) do allpieces2[#allpieces2+1] = { pname,pid } end table.sort(allpieces2, function(a,b) return a[1] < b[1]; end ) local unitDefID = Spring.GetUnitDefID(unitID) local swapYandZ = UnitDefs[unitDefID].model.type ~= 's3o' --for pname,pid in pairs(allpieces) do for _,item in pairs(allpieces2) do local pname = item[1] local pid = item[2] --local pieceInfo = Spring.GetUnitPieceInfo( unitID, pid ) --local pname = pieceInfo.name --local mx,my,mz = Spring.UnitScript.GetPieceTranslation (p) local rx,ry,rz = Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.GetPieceRotation, pid) local px,py,pz = Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.GetPieceTranslation, pid) -- [[ s=s.. "\tMove (" .. pname .. ", x_axis, " ..px ..", mspeed)\n" s=s.. "\tMove (" .. pname .. ", y_axis, " ..py ..", mspeed)\n" s=s.. "\tMove (" .. pname .. ", z_axis, " ..pz ..", mspeed)\n" if swapYandZ then s=s.. "\tTurn (" .. pname .. ", x_axis, math.rad(" .. math.deg(rx) .."), tspeed)\n" s=s.. "\tTurn (" .. pname .. ", y_axis, math.rad(" .. math.deg(rz) .."), tspeed)\n" s=s.. "\tTurn (" .. pname .. ", z_axis, math.rad(" .. math.deg(ry) .."), tspeed)\n" else s=s.. "\tTurn (" .. pname .. ", x_axis, math.rad(" .. math.deg(rx) .."), tspeed)\n" s=s.. "\tTurn (" .. pname .. ", y_axis, math.rad(" .. math.deg(ry) .."), tspeed)\n" s=s.. "\tTurn (" .. pname .. ", z_axis, math.rad(" .. math.deg(rz) .."), tspeed)\n" end --]] end s=s.. "end" echo (s) end local function Reset(unitID) local env = true -- Spring.UnitScript.GetScriptEnv(unitID) if env and Spring.UnitScript.GetPieceRotation then local allpieces = Spring.GetUnitPieceMap(unitID) for pname,pid in pairs(allpieces) do for axisnum = 1,3 do Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.Move, pid, axisnum, 0 ) Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.Turn, pid, axisnum, 0 ) end end end end local function CallUnitScript(unitID, funcName, ...) if Spring.UnitScript.GetScriptEnv(unitID) and Spring.UnitScript.GetScriptEnv(unitID).script[funcName] then Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.GetScriptEnv(unitID).script[funcName], ...) end end function gadget:RecvLuaMsg(msg, playerID) if not Spring.IsCheatingEnabled() then return end --echo (msg) pre = "animator" --if (msg:find(pre,1,true)) then Spring.Echo ("its a loveNtrolls message") end local data = Spring.Utilities.ExplodeString( '|', msg ) if data[1] ~= pre then return end local cmd = data[2] local param1 = data[3] local param2 = data[4] local param3 = data[5] local param4 = data[6] if cmd == 'sel' and param1 then local unitID = param1+0 --convert to int! euID = unitID --Spring.Echo ("now editing: " .. euID) elseif cmd == 'getpieceinfo' and param1 and param2 then local unitID = param1+0 --convert to int! local pieceNum = param2+0 --convert to int! local env = true -- Spring.UnitScript.GetScriptEnv(unitID) if env and Spring.UnitScript.GetPieceRotation then local rx,ry,rz = Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.GetPieceRotation, pieceNum) local px,py,pz = Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.GetPieceTranslation, pieceNum) local pieceInfo = {rx, ry, rz, px,py,pz} SendToUnsynced("PieceInfo", table.concat(pieceInfo,'|') ) end elseif cmd == 'move' or cmd == 'turn' then local axis = param1 local unitID = param2+0 --convert to num! local pieceNum = param3+0 --convert to num! local val = param4+0 --convert to num! local axisnum = 1 if axis == 'y' then axisnum = 2 elseif axis == 'z' then axisnum = 3 end local env = true --Spring.UnitScript.GetScriptEnv(unitID) if env then if cmd == 'move' then Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.Move, pieceNum, axisnum, val ) elseif cmd == 'turn' then Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.Turn, pieceNum, axisnum, val ) end echo("> " .. cmd .. ' on ' .. axis .. '-axis to ' .. val) end elseif cmd == 'write' then local unitID = param1+0 --convert to num! WriteCurrent(unitID) elseif cmd == 'reset' then local unitID = param1+0 --convert to num! Reset(unitID) elseif cmd == 'hide' then local unitID = param1+0 --convert to num! local pieceNum = param2+0 --convert to num! Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.Hide, pieceNum ) elseif cmd == 'show' then local unitID = param1+0 --convert to num! local pieceNum = param2+0 --convert to num! Spring.UnitScript.CallAsUnit(unitID, Spring.UnitScript.Show, pieceNum ) elseif cmd == 'testthread' then local unitID = param1+0 --convert to num! CallUnitScript(unitID, "TestThread" ) end --Spring.Echo ("RecvLuaMsg: " .. msg .. " from " .. playerID) end function gadget:Initialize() Spring.SetGameRulesParam('devmode', 1) end else -- ab hier unsync local function PieceInfo(_, pieceInfo) Script.LuaUI.PieceInfo(pieceInfo) end function gadget:Initialize() gadgetHandler:AddSyncAction("PieceInfo", PieceInfo) end function gadget:Shutdown() gadgetHandler:RemoveSyncAction("PieceInfo") end end
gpl-2.0
starkos/premake-core
modules/xcode/tests/test_xcode_project.lua
1
121504
-- -- tests/actions/xcode/test_xcode_project.lua -- Automated test suite for Xcode project generation. -- Copyright (c) 2009-2011 Jason Perkins and the Premake project -- local suite = test.declare("xcode_project") local p = premake local xcode = p.modules.xcode --------------------------------------------------------------------------- -- Setup/Teardown --------------------------------------------------------------------------- local tr, wks function suite.teardown() tr = nil end function suite.setup() _TARGET_OS = "macosx" p.action.set('xcode4') p.eol("\n") wks = test.createWorkspace() end local function prepare() wks = p.oven.bakeWorkspace(wks) xcode.prepareWorkspace(wks) local prj = test.getproject(wks, 1) tr = xcode.buildprjtree(prj) end --------------------------------------------------------------------------- -- PBXBuildFile tests --------------------------------------------------------------------------- function suite.PBXBuildFile_ListsCppSources() files { "source.h", "source.c", "source.cpp", "Info.plist" } prepare() xcode.PBXBuildFile(tr) test.capture [[ /* Begin PBXBuildFile section */ 7018C364CB5A16D69EB461A4 /* source.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B47484CB259E37EA275DE8C /* source.cpp */; }; F3989C244A260696229F1A64 /* source.c in Sources */ = {isa = PBXBuildFile; fileRef = 7DC6D30C8137A53E02A4494C /* source.c */; }; /* End PBXBuildFile section */ ]] end function suite.PBXBuildFile_ListsObjCSources() files { "source.h", "source.m", "source.mm", "Info.plist" } prepare() xcode.PBXBuildFile(tr) test.capture [[ /* Begin PBXBuildFile section */ 8A01A092B9936F8494A0AED2 /* source.mm in Sources */ = {isa = PBXBuildFile; fileRef = CCAA329A6F98594CFEBE38DA /* source.mm */; }; CBA890782235FAEAFAAF0EB8 /* source.m in Sources */ = {isa = PBXBuildFile; fileRef = 3AFE9C203E6F6E52BFDC1260 /* source.m */; }; /* End PBXBuildFile section */ ]] end function suite.PBXBuildFile_ListsSwiftSources() files { "source.swift", "Info.plist" } prepare() xcode.PBXBuildFile(tr) test.capture [[ /* Begin PBXBuildFile section */ 4616E7383FD8A3AA79D7A578 /* source.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B2BDAE0539CBF12983B9120 /* source.swift */; }; /* End PBXBuildFile section */ ]] end function suite.PBXBuildFile_ListsMetalFileInResources() files { "source.metal", "Info.plist" } prepare() xcode.PBXBuildFile(tr) test.capture [[ /* Begin PBXBuildFile section */ 3873A08432355CF66C345EC4 /* source.metal in Resources */ = {isa = PBXBuildFile; fileRef = 35B2856C7E23699EC2C23BAC /* source.metal */; }; /* End PBXBuildFile section */ ]] end function suite.PBXBuildFile_ListsResourceFilesOnlyOnceWithGroupID() files { "English.lproj/MainMenu.xib", "French.lproj/MainMenu.xib" } prepare() xcode.PBXBuildFile(tr) test.capture [[ /* Begin PBXBuildFile section */ 6FE0F2A3E16C0B15906D30E3 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 6CB8FB6B191BBB9DD7A431AB /* MainMenu.xib */; }; /* End PBXBuildFile section */ ]] end function suite.PBXBuildFile_ListsFrameworks() links { "Cocoa.framework", "ldap" } prepare() xcode.PBXBuildFile(tr) test.capture [[ /* Begin PBXBuildFile section */ F8E8DBA28B76A594F44F49E2 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8D6BC6AA50D7885C8F7B2CEA /* Cocoa.framework */; }; /* End PBXBuildFile section */ ]] end function suite.PBXBuildFile_ListsDylibs() links { "../libA.dylib", "libB.dylib", "/usr/lib/libC.dylib" } prepare() xcode.PBXBuildFile(tr) test.capture [[ /* Begin PBXBuildFile section */ 3C98627697D9B5E86B3400B6 /* libB.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = D413533EEB25EE70DB41E97E /* libB.dylib */; }; 91686CDFDECB631154EA631F /* libA.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5F9AE5C74A870BB9926CD407 /* libA.dylib */; }; A7E42B5676077F08FD15D196 /* libC.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = CF0547FE2A469B70FDA0E63E /* libC.dylib */; }; /* End PBXBuildFile section */ ]] end function suite.PBXBuildFile_ListsFrameworksAndDylibsForSigning() links { "../libA.dylib", "libB.dylib", "/usr/lib/libC.dylib", "../D.framework", "../E.framework", } embedAndSign { "libA.dylib", "D.framework", } embed { "libB.dylib", "E.framework", } prepare() xcode.PBXBuildFile(tr) test.capture [[ /* Begin PBXBuildFile section */ 12F1B82D44EB02DFBECA3E6D /* E.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A817AE35FEA518A7D71E2C75 /* E.framework */; }; 6557012668C7D358EA347766 /* E.framework in Embed Libraries */ = {isa = PBXBuildFile; fileRef = A817AE35FEA518A7D71E2C75 /* E.framework */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 3C98627697D9B5E86B3400B6 /* libB.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = D413533EEB25EE70DB41E97E /* libB.dylib */; }; AC7C2020DB2274123463CE60 /* libB.dylib in Embed Libraries */ = {isa = PBXBuildFile; fileRef = D413533EEB25EE70DB41E97E /* libB.dylib */; }; 91686CDFDECB631154EA631F /* libA.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5F9AE5C74A870BB9926CD407 /* libA.dylib */; }; E054F1BF0EFB45B1683C9FFF /* libA.dylib in Embed Libraries */ = {isa = PBXBuildFile; fileRef = 5F9AE5C74A870BB9926CD407 /* libA.dylib */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; A7E42B5676077F08FD15D196 /* libC.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = CF0547FE2A469B70FDA0E63E /* libC.dylib */; }; F56B754B2764BFFDA143FB8B /* D.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F3987C734A25E6E5229EFAB3 /* D.framework */; }; 966D8A4599DE5C771B4B0085 /* D.framework in Embed Libraries */ = {isa = PBXBuildFile; fileRef = F3987C734A25E6E5229EFAB3 /* D.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; /* End PBXBuildFile section */ ]] end function suite.PBXBuildFile_IgnoresVpaths() files { "source.h", "source.c", "source.cpp", "Info.plist" } vpaths { ["Source Files"] = { "**.c", "**.cpp" } } prepare() xcode.PBXBuildFile(tr) test.capture [[ /* Begin PBXBuildFile section */ 7018C364CB5A16D69EB461A4 /* source.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9B47484CB259E37EA275DE8C /* source.cpp */; }; F3989C244A260696229F1A64 /* source.c in Sources */ = {isa = PBXBuildFile; fileRef = 7DC6D30C8137A53E02A4494C /* source.c */; }; /* End PBXBuildFile section */ ]] end --- -- Verify that files listed in xcodebuildresources are marked as resources --- function suite.PBXBuildFile_ListsXcodeBuildResources() files { "file1.txt", "file01.png", "file02.png", "file-3.png" } xcodebuildresources { "file1.txt", "**.png" } prepare() xcode.PBXBuildFile(tr) test.capture [[ /* Begin PBXBuildFile section */ 628F3826BDD08B98912AD666 /* file-3.png in Resources */ = {isa = PBXBuildFile; fileRef = 992385EEB0362120A0521C2E /* file-3.png */; }; 93485EDEC2DA2DD09DE76D1E /* file1.txt in Resources */ = {isa = PBXBuildFile; fileRef = 9F78562642667CD8D18C5C66 /* file1.txt */; }; C87AFEAA23BC521CF7169CEA /* file02.png in Resources */ = {isa = PBXBuildFile; fileRef = D54D8E32EC602964DC7C2472 /* file02.png */; }; EE9FC5C849E1193A1D3B6408 /* file01.png in Resources */ = {isa = PBXBuildFile; fileRef = 989B7E70AFAE19A29FCA14B0 /* file01.png */; }; /* End PBXBuildFile section */ ]] end --------------------------------------------------------------------------- -- PBXFileReference tests --------------------------------------------------------------------------- function suite.PBXFileReference_ListsConsoleTarget() prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 19A5C4E61D1697189E833B26 /* MyProject */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = MyProject; path = MyProject; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListsWindowedTarget() kind "WindowedApp" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ E5FB9875FD0E33A7ED2A2EB5 /* MyProject.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; name = MyProject.app; path = MyProject.app; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListsIOSWindowedTarget() _TARGET_OS = "ios" kind "WindowedApp" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ E5FB9875FD0E33A7ED2A2EB5 /* MyProject.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; name = MyProject.app; path = MyProject.app; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListsStaticLibTarget() kind "StaticLib" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ FDCF31ACF735331EEAD08FEC /* libMyProject.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; name = libMyProject.a; path = libMyProject.a; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListsIOSStaticLibTarget() _TARGET_OS = "ios" kind "StaticLib" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ FDCF31ACF735331EEAD08FEC /* libMyProject.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; name = libMyProject.a; path = libMyProject.a; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListsSharedLibTarget() kind "SharedLib" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 2781AF7F7E0F19F156882DBF /* libMyProject.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; name = libMyProject.dylib; path = libMyProject.dylib; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListsIOSSharedLibTarget() _TARGET_OS = "ios" kind "SharedLib" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 2781AF7F7E0F19F156882DBF /* libMyProject.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; name = libMyProject.dylib; path = libMyProject.dylib; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListsOSXBundleTarget() kind "SharedLib" sharedlibtype "OSXBundle" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 8AD066EE75BC8CE0BDA2552E /* MyProject.bundle */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = MyProject.bundle; path = MyProject.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListsIOSOSXBundleTarget() _TARGET_OS = "ios" kind "SharedLib" sharedlibtype "OSXBundle" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 8AD066EE75BC8CE0BDA2552E /* MyProject.bundle */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = MyProject.bundle; path = MyProject.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListsXCTestTarget() kind "SharedLib" sharedlibtype "XCTest" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ F573990FE05FBF012845874F /* MyProject.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = MyProject.xctest; path = MyProject.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListsIOSXCTestTarget() _TARGET_OS = "ios" kind "SharedLib" sharedlibtype "XCTest" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ F573990FE05FBF012845874F /* MyProject.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = MyProject.xctest; path = MyProject.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListsOSXFrameworkTarget() kind "SharedLib" sharedlibtype "OSXFramework" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 2D914F2255CC07D43D679562 /* MyProject.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = MyProject.framework; path = MyProject.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListsIOSOSXFrameworkTarget() _TARGET_OS = "ios" kind "SharedLib" sharedlibtype "OSXFramework" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 2D914F2255CC07D43D679562 /* MyProject.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = MyProject.framework; path = MyProject.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListsSourceFiles() files { "source.c" } prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 19A5C4E61D1697189E833B26 /* MyProject */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = MyProject; path = MyProject; sourceTree = BUILT_PRODUCTS_DIR; }; 7DC6D30C8137A53E02A4494C /* source.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; name = source.c; path = source.c; sourceTree = "<group>"; }; ]] end function suite.PBXFileReference_ListsSourceFilesCompileAs() files { "source.c", "objsource.c", "objsource.cpp" } filter { "files:source.c" } compileas "C++" filter { "files:objsource.c" } compileas "Objective-C" filter { "files:objsource.cpp" } compileas "Objective-C++" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 19A5C4E61D1697189E833B26 /* MyProject */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = MyProject; path = MyProject; sourceTree = BUILT_PRODUCTS_DIR; }; 7DC6D30C8137A53E02A4494C /* source.c */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.cpp; name = source.c; path = source.c; sourceTree = "<group>"; }; C8C6CC62F1018514D89D12A2 /* objsource.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; name = objsource.cpp; path = objsource.cpp; sourceTree = "<group>"; }; E4BF12E20AE5429471EC3922 /* objsource.c */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.objc; name = objsource.c; path = objsource.c; sourceTree = "<group>"; }; ]] end function suite.PBXFileReference_ListsXibCorrectly() files { "English.lproj/MainMenu.xib", "French.lproj/MainMenu.xib" } prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 19A5C4E61D1697189E833B26 /* MyProject */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = MyProject; path = MyProject; sourceTree = BUILT_PRODUCTS_DIR; }; 31594983623D4175755577C3 /* French */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = French; path = French.lproj/MainMenu.xib; sourceTree = "<group>"; }; 625C7BEB5C1E385D961D3A2B /* English */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = English; path = English.lproj/MainMenu.xib; sourceTree = "<group>"; }; ]] end function suite.PBXFileReference_ListsStringsCorrectly() files { "English.lproj/InfoPlist.strings", "French.lproj/InfoPlist.strings" } prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 19A5C4E61D1697189E833B26 /* MyProject */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = MyProject; path = MyProject; sourceTree = BUILT_PRODUCTS_DIR; }; A329C1B0714D1562F85B67F0 /* English */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/InfoPlist.strings; sourceTree = "<group>"; }; C3BECE4859358D7AC7D1E488 /* French */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = French; path = French.lproj/InfoPlist.strings; sourceTree = "<group>"; }; ]] end function suite.PBXFileReference_ListFrameworksCorrectly() links { "Cocoa.framework/" } prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 19A5C4E61D1697189E833B26 /* MyProject */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = MyProject; path = MyProject; sourceTree = BUILT_PRODUCTS_DIR; }; 8D6BC6AA50D7885C8F7B2CEA /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_ListDylibsCorrectly() links { "../libA.dylib", "libB.dylib", "/usr/lib/libC.dylib" } prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 19A5C4E61D1697189E833B26 /* MyProject */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = MyProject; path = MyProject; sourceTree = BUILT_PRODUCTS_DIR; }; 5F9AE5C74A870BB9926CD407 /* libA.dylib */ = {isa = PBXFileReference; lastKnownFileType = compiled.mach-o.dylib; name = libA.dylib; path = ../libA.dylib; sourceTree = SOURCE_ROOT; }; CF0547FE2A469B70FDA0E63E /* libC.dylib */ = {isa = PBXFileReference; lastKnownFileType = compiled.mach-o.dylib; name = libC.dylib; path = /usr/lib/libC.dylib; sourceTree = "<absolute>"; }; D413533EEB25EE70DB41E97E /* libB.dylib */ = {isa = PBXFileReference; lastKnownFileType = compiled.mach-o.dylib; name = libB.dylib; path = libB.dylib; sourceTree = SOURCE_ROOT; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_leavesFrameworkLocationsAsIsWhenSupplied_pathIsSetToInput() local inputFrameWork = 'somedir/Foo.framework' links(inputFrameWork) prepare() --io.capture() xcode.PBXFileReference(tr) --local str = io.captured() --test.istrue(str:find('path = "'..inputFrameWork..'"')) --ms check end function suite.PBXFileReference_relativeFrameworkPathSupplied_callsError() local inputFrameWork = '../somedir/Foo.framework' links(inputFrameWork) prepare() -- ms no longer and error -- valid case for linking relative frameworks --local error_called = false --local old_error = error --error = function( ... )error_called = true end xcode.PBXFileReference(tr) --error = old_error --test.istrue(error_called) end function suite.PBXFileReference_ListsIconFiles() files { "Icon.icns" } prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 19A5C4E61D1697189E833B26 /* MyProject */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = MyProject; path = MyProject; sourceTree = BUILT_PRODUCTS_DIR; }; 1A07B4D0BCF5DB824C1BBB10 /* Icon.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; name = Icon.icns; path = Icon.icns; sourceTree = "<group>"; }; ]] end function suite.PBXFileReference_IgnoresTargetDir() targetdir "bin" kind "WindowedApp" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ E5FB9875FD0E33A7ED2A2EB5 /* MyProject.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; name = MyProject.app; path = MyProject.app; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_UsesTargetSuffix() targetsuffix "-d" kind "SharedLib" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 9E361150CDC7E042A8D51F90 /* libMyProject-d.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; name = "libMyProject-d.dylib"; path = "libMyProject-d.dylib"; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_UsesFullPath_WhenParentIsVirtual() files { "src/source.c" } vpaths { ["Source Files"] = "**.c" } prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 19A5C4E61D1697189E833B26 /* MyProject */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = MyProject; path = MyProject; sourceTree = BUILT_PRODUCTS_DIR; }; 721A4003892CDB357948D643 /* source.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; name = source.c; path = src/source.c; sourceTree = "<group>"; }; ]] end --------------------------------------------------------------------------- -- PBXFrameworksBuildPhase tests --------------------------------------------------------------------------- function suite.PBXFrameworksBuildPhase_OnNoFiles() prepare() xcode.PBXFrameworksBuildPhase(tr) test.capture [[ /* Begin PBXFrameworksBuildPhase section */ 9FDD37564328C0885DF98D96 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ ]] end function suite.PBXFrameworksBuild_ListsFrameworksCorrectly() links { "Cocoa.framework" } prepare() xcode.PBXFrameworksBuildPhase(tr) test.capture [[ /* Begin PBXFrameworksBuildPhase section */ 9FDD37564328C0885DF98D96 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( F8E8DBA28B76A594F44F49E2 /* Cocoa.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ ]] end --------------------------------------------------------------------------- -- PBXCopyFilesBuildPhaseForEmbedFrameworks tests --------------------------------------------------------------------------- function suite.PBXCopyFilesBuildPhaseForEmbedFrameworks_OnNoFiles() prepare() xcode.PBXCopyFilesBuildPhaseForEmbedFrameworks(tr) test.capture [[ /* Begin PBXCopyFilesBuildPhase section */ E1D3B542862652F4985E9B82 /* Embed Libraries */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 10; files = ( ); name = "Embed Libraries"; runOnlyForDeploymentPostprocessing = 0; }; /* End PBXCopyFilesBuildPhase section */ ]] end function suite.PBXCopyFilesBuildPhaseForEmbedFrameworks_ListsEmbeddedLibrariesCorrectly() links { "../libA.dylib", "../D.framework", } embed { "libA.dylib" } embedAndSign { "D.framework" } prepare() xcode.PBXCopyFilesBuildPhaseForEmbedFrameworks(tr) test.capture [[ /* Begin PBXCopyFilesBuildPhase section */ E1D3B542862652F4985E9B82 /* Embed Libraries */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 10; files = ( E054F1BF0EFB45B1683C9FFF /* libA.dylib in Frameworks */, 966D8A4599DE5C771B4B0085 /* D.framework in Frameworks */, ); name = "Embed Libraries"; runOnlyForDeploymentPostprocessing = 0; }; /* End PBXCopyFilesBuildPhase section */ ]] end --------------------------------------------------------------------------- -- PBXGroup tests --------------------------------------------------------------------------- function suite.PBXGroup_OnNoFiles() prepare() xcode.PBXGroup(tr) test.capture [[ /* Begin PBXGroup section */ 12F5A37D963B00EFBF8281BD /* MyProject */ = { isa = PBXGroup; children = ( A6C936B49B3FADE6EA134CF4 /* Products */, ); name = MyProject; sourceTree = "<group>"; }; A6C936B49B3FADE6EA134CF4 /* Products */ = { isa = PBXGroup; children = ( 19A5C4E61D1697189E833B26 /* MyProject */, ); name = Products; sourceTree = "<group>"; }; /* End PBXGroup section */ ]] end function suite.PBXGroup_OnSourceFiles() files { "source.h" } prepare() xcode.PBXGroup(tr) test.capture [[ /* Begin PBXGroup section */ 12F5A37D963B00EFBF8281BD /* MyProject */ = { isa = PBXGroup; children = ( 5C62B7965FD389C8E1402DD6 /* source.h */, A6C936B49B3FADE6EA134CF4 /* Products */, ); name = MyProject; sourceTree = "<group>"; }; A6C936B49B3FADE6EA134CF4 /* Products */ = { isa = PBXGroup; children = ( 19A5C4E61D1697189E833B26 /* MyProject */, ); name = Products; sourceTree = "<group>"; }; /* End PBXGroup section */ ]] end function suite.PBXGroup_OnSourceSubdirs() files { "include/premake/source.h" } prepare() xcode.PBXGroup(tr) test.capture [[ /* Begin PBXGroup section */ 12F5A37D963B00EFBF8281BD /* MyProject */ = { isa = PBXGroup; children = ( 5C62B7965FD389C8E1402DD6 /* source.h */, A6C936B49B3FADE6EA134CF4 /* Products */, ); name = MyProject; sourceTree = "<group>"; }; A6C936B49B3FADE6EA134CF4 /* Products */ = { isa = PBXGroup; children = ( 19A5C4E61D1697189E833B26 /* MyProject */, ); name = Products; sourceTree = "<group>"; }; /* End PBXGroup section */ ]] end function suite.PBXGroup_pathHasPlusPlus_PathIsQuoted() files { "RequiresQuoting++/h.h" } prepare() xcode.PBXGroup(tr) local str = p.captured() --test.istrue(str:find('path = "RequiresQuoting%+%+";')) end function suite.PBXGroup_SortsFiles() files { "test.h", "source.h", "source.cpp" } prepare() xcode.PBXGroup(tr) test.capture [[ /* Begin PBXGroup section */ 12F5A37D963B00EFBF8281BD /* MyProject */ = { isa = PBXGroup; children = ( 9B47484CB259E37EA275DE8C /* source.cpp */, 5C62B7965FD389C8E1402DD6 /* source.h */, ABEF15744F3A9EA66A0B6BB4 /* test.h */, A6C936B49B3FADE6EA134CF4 /* Products */, ); name = MyProject; sourceTree = "<group>"; }; A6C936B49B3FADE6EA134CF4 /* Products */ = { isa = PBXGroup; children = ( 19A5C4E61D1697189E833B26 /* MyProject */, ); name = Products; sourceTree = "<group>"; }; /* End PBXGroup section */ ]] end function suite.PBXGroup_OnResourceFiles() files { "English.lproj/MainMenu.xib", "French.lproj/MainMenu.xib", "Info.plist" } prepare() xcode.PBXGroup(tr) test.capture [[ /* Begin PBXGroup section */ 12F5A37D963B00EFBF8281BD /* MyProject */ = { isa = PBXGroup; children = ( ACC2AED4C3D54A06B3F14514 /* Info.plist */, 6CB8FB6B191BBB9DD7A431AB /* MainMenu.xib */, A6C936B49B3FADE6EA134CF4 /* Products */, ); name = MyProject; sourceTree = "<group>"; }; A6C936B49B3FADE6EA134CF4 /* Products */ = { isa = PBXGroup; children = ( 19A5C4E61D1697189E833B26 /* MyProject */, ); name = Products; sourceTree = "<group>"; }; /* End PBXGroup section */ ]] end function suite.PBXGroup_OnFrameworks() links { "Cocoa.framework" } prepare() xcode.PBXGroup(tr) test.capture [[ /* Begin PBXGroup section */ 12F5A37D963B00EFBF8281BD /* MyProject */ = { isa = PBXGroup; children = ( BBF76781A7E87333FA200DC1 /* Frameworks */, A6C936B49B3FADE6EA134CF4 /* Products */, ); name = MyProject; sourceTree = "<group>"; }; A6C936B49B3FADE6EA134CF4 /* Products */ = { isa = PBXGroup; children = ( 19A5C4E61D1697189E833B26 /* MyProject */, ); name = Products; sourceTree = "<group>"; }; BBF76781A7E87333FA200DC1 /* Frameworks */ = { isa = PBXGroup; children = ( 8D6BC6AA50D7885C8F7B2CEA /* Cocoa.framework */, ); name = Frameworks; sourceTree = "<group>"; }; ]] end function suite.PBXGroup_OnVpaths() files { "include/premake/source.h" } vpaths { ["Headers"] = "**.h" } prepare() xcode.PBXGroup(tr) test.capture [[ /* Begin PBXGroup section */ 12F5A37D963B00EFBF8281BD /* MyProject */ = { isa = PBXGroup; children = ( 20D885C0C52B2372D7636C00 /* Headers */, A6C936B49B3FADE6EA134CF4 /* Products */, ); name = MyProject; sourceTree = "<group>"; }; 20D885C0C52B2372D7636C00 /* Headers */ = { isa = PBXGroup; children = ( E91A2DDD367D240FAC9C241D /* source.h */, ); name = Headers; sourceTree = "<group>"; }; ]] end --------------------------------------------------------------------------- -- PBXNativeTarget tests --------------------------------------------------------------------------- function suite.PBXNativeTarget_OnConsoleApp() prepare() xcode.PBXNativeTarget(tr) test.capture [[ /* Begin PBXNativeTarget section */ 48B5980C775BEBFED09D464C /* MyProject */ = { isa = PBXNativeTarget; buildConfigurationList = 8E187FB5316408E74C34D5F5 /* Build configuration list for PBXNativeTarget "MyProject" */; buildPhases = ( 0FC4B7F6B3104128CDE10E36 /* Resources */, 7971D14D1CBD5A7F378E278D /* Sources */, 9FDD37564328C0885DF98D96 /* Frameworks */, E1D3B542862652F4985E9B82 /* Embed Libraries */, ); buildRules = ( ); dependencies = ( ); name = MyProject; productInstallPath = "$(HOME)/bin"; productName = MyProject; productReference = 19A5C4E61D1697189E833B26 /* MyProject */; productType = "com.apple.product-type.tool"; }; /* End PBXNativeTarget section */ ]] end function suite.PBXNativeTarget_OnWindowedApp() kind "WindowedApp" prepare() xcode.PBXNativeTarget(tr) test.capture [[ /* Begin PBXNativeTarget section */ D2C7B5BBD37AB2AD475C83FB /* MyProject */ = { isa = PBXNativeTarget; buildConfigurationList = 8DCCE3C4913DB5F612AA5A04 /* Build configuration list for PBXNativeTarget "MyProject" */; buildPhases = ( 0F791C0512E9EE3794569245 /* Resources */, 7926355C7C97078EFE03AB9C /* Sources */, 9F919B65A3026D97246F11A5 /* Frameworks */, A0315911431F7FC3D2455F51 /* Embed Libraries */, ); buildRules = ( ); dependencies = ( ); name = MyProject; productInstallPath = "$(HOME)/Applications"; productName = MyProject; productReference = E5FB9875FD0E33A7ED2A2EB5 /* MyProject.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ ]] end function suite.PBXNativeTarget_OnSharedLib() kind "SharedLib" prepare() xcode.PBXNativeTarget(tr) test.capture [[ /* Begin PBXNativeTarget section */ CD0213851572F7B75A11C9C5 /* MyProject */ = { isa = PBXNativeTarget; buildConfigurationList = 1F5D05CE18C307400C5E640E /* Build configuration list for PBXNativeTarget "MyProject" */; buildPhases = ( A1093E0F9A6F3F818E0A9C4F /* Resources */, 0AB65766041C58D8F7B7B5A6 /* Sources */, 3121BD6F2A87BEE11E231BAF /* Frameworks */, D652259BC13E4B8D092413DB /* Embed Libraries */, ); buildRules = ( ); dependencies = ( ); name = MyProject; productName = MyProject; productReference = 2781AF7F7E0F19F156882DBF /* libMyProject.dylib */; productType = "com.apple.product-type.library.dynamic"; }; /* End PBXNativeTarget section */ ]] end function suite.PBXNativeTarget_OnBuildCommands() prebuildcommands { "prebuildcmd" } prelinkcommands { "prelinkcmd" } postbuildcommands { "postbuildcmd" } files { "file.in" } filter { "files:file.in" } buildcommands { "buildcmd" } buildoutputs { "file.out" } prepare() xcode.PBXNativeTarget(tr) test.capture [[ /* Begin PBXNativeTarget section */ 48B5980C775BEBFED09D464C /* MyProject */ = { isa = PBXNativeTarget; buildConfigurationList = 8E187FB5316408E74C34D5F5 /* Build configuration list for PBXNativeTarget "MyProject" */; buildPhases = ( 9607AE1010C857E500CD1376 /* Prebuild */, C06220C983CDE27BC2718709 /* Build "file.in" */, 0FC4B7F6B3104128CDE10E36 /* Resources */, 7971D14D1CBD5A7F378E278D /* Sources */, 9607AE3510C85E7E00CD1376 /* Prelink */, 9FDD37564328C0885DF98D96 /* Frameworks */, E1D3B542862652F4985E9B82 /* Embed Libraries */, 9607AE3710C85E8F00CD1376 /* Postbuild */, ); buildRules = ( ); dependencies = ( ); name = MyProject; productInstallPath = "$(HOME)/bin"; productName = MyProject; productReference = 19A5C4E61D1697189E833B26 /* MyProject */; productType = "com.apple.product-type.tool"; }; /* End PBXNativeTarget section */ ]] end function suite.PBXNativeTarget_OnBuildCommandsFilesFilterDependency() files { "file.1", "file.2", "file.3" } filter { "files:file.1" } buildcommands { "first" } buildoutputs { "file.2" } filter { "files:file.3" } buildcommands { "last" } buildoutputs { "file.4" } filter { "files:file.2" } buildcommands { "second" } buildoutputs { "file.3" } prepare() xcode.PBXNativeTarget(tr) test.capture [[ /* Begin PBXNativeTarget section */ 48B5980C775BEBFED09D464C /* MyProject */ = { isa = PBXNativeTarget; buildConfigurationList = 8E187FB5316408E74C34D5F5 /* Build configuration list for PBXNativeTarget "MyProject" */; buildPhases = ( A50DBDBDC6D96AEF038E93FD /* Build "file.1" */, 71E4A5FF93B05331D0657C3F /* Build "file.2" */, 3EBB8E4160873B739D3C6481 /* Build "file.3" */, 0FC4B7F6B3104128CDE10E36 /* Resources */, 7971D14D1CBD5A7F378E278D /* Sources */, 9FDD37564328C0885DF98D96 /* Frameworks */, E1D3B542862652F4985E9B82 /* Embed Libraries */, ); buildRules = ( ); dependencies = ( ); name = MyProject; productInstallPath = "$(HOME)/bin"; productName = MyProject; productReference = 19A5C4E61D1697189E833B26 /* MyProject */; productType = "com.apple.product-type.tool"; }; /* End PBXNativeTarget section */ ]] end function suite.PBXNativeTarget_OnBuildCommandsBuildInputsDependency() files { "file.1", "file.2", "file.3" } filter { "files:file.1" } buildcommands { "first" } buildoutputs { "file.4" } filter { "files:file.3" } buildcommands { "last" } buildinputs { "file.5" } buildoutputs { "file.6" } filter { "files:file.2" } buildcommands { "second" } buildinputs { "file.4" } buildoutputs { "file.5" } prepare() xcode.PBXNativeTarget(tr) test.capture [[ /* Begin PBXNativeTarget section */ 48B5980C775BEBFED09D464C /* MyProject */ = { isa = PBXNativeTarget; buildConfigurationList = 8E187FB5316408E74C34D5F5 /* Build configuration list for PBXNativeTarget "MyProject" */; buildPhases = ( A50DBDBDC6D96AEF038E93FD /* Build "file.1" */, 71E4A5FF93B05331D0657C3F /* Build "file.2" */, 3EBB8E4160873B739D3C6481 /* Build "file.3" */, 0FC4B7F6B3104128CDE10E36 /* Resources */, 7971D14D1CBD5A7F378E278D /* Sources */, 9FDD37564328C0885DF98D96 /* Frameworks */, E1D3B542862652F4985E9B82 /* Embed Libraries */, ); buildRules = ( ); dependencies = ( ); name = MyProject; productInstallPath = "$(HOME)/bin"; productName = MyProject; productReference = 19A5C4E61D1697189E833B26 /* MyProject */; productType = "com.apple.product-type.tool"; }; /* End PBXNativeTarget section */ ]] end --------------------------------------------------------------------------- -- PBXAggregateTarget tests --------------------------------------------------------------------------- function suite.PBXAggregateTarget_OnUtility() kind "Utility" prepare() xcode.PBXAggregateTarget(tr) test.capture [[ /* Begin PBXAggregateTarget section */ 48B5980C775BEBFED09D464C /* MyProject */ = { isa = PBXAggregateTarget; buildConfigurationList = 8E187FB5316408E74C34D5F5 /* Build configuration list for PBXAggregateTarget "MyProject" */; buildPhases = ( ); buildRules = ( ); dependencies = ( ); name = MyProject; productName = MyProject; }; /* End PBXAggregateTarget section */ ]] end function suite.PBXAggregateTarget_OnBuildCommands() kind "Utility" prebuildcommands { "prebuildcmd" } prelinkcommands { "prelinkcmd" } postbuildcommands { "postbuildcmd" } files { "file.in" } filter { "files:file.in" } buildcommands { "buildcmd" } buildoutputs { "file.out" } prepare() xcode.PBXAggregateTarget(tr) test.capture [[ /* Begin PBXAggregateTarget section */ 48B5980C775BEBFED09D464C /* MyProject */ = { isa = PBXAggregateTarget; buildConfigurationList = 8E187FB5316408E74C34D5F5 /* Build configuration list for PBXAggregateTarget "MyProject" */; buildPhases = ( 9607AE1010C857E500CD1376 /* Prebuild */, C06220C983CDE27BC2718709 /* Build "file.in" */, 9607AE3510C85E7E00CD1376 /* Prelink */, 9607AE3710C85E8F00CD1376 /* Postbuild */, ); buildRules = ( ); dependencies = ( ); name = MyProject; productName = MyProject; }; /* End PBXAggregateTarget section */ ]] end --------------------------------------------------------------------------- -- PBXProject tests --------------------------------------------------------------------------- function suite.PBXProject_OnProject() prepare() xcode.PBXProject(tr) test.capture [[ /* Begin PBXProject section */ 08FB7793FE84155DC02AAC07 /* Project object */ = { isa = PBXProject; buildConfigurationList = 1DEB928908733DD80010E9CD /* Build configuration list for PBXProject "MyProject" */; compatibilityVersion = "Xcode 3.2"; hasScannedForEncodings = 1; mainGroup = 12F5A37D963B00EFBF8281BD /* MyProject */; projectDirPath = ""; projectRoot = ""; targets = ( 48B5980C775BEBFED09D464C /* MyProject */, ); }; /* End PBXProject section */ ]] end function suite.PBXProject_OnSystemCapabilities() xcodesystemcapabilities { ["com.apple.InAppPurchase"] = "ON", ["com.apple.iCloud"] = "ON", ["com.apple.GameCenter.iOS"] = "OFF", } prepare() xcode.PBXProject(tr) test.capture [[ /* Begin PBXProject section */ 08FB7793FE84155DC02AAC07 /* Project object */ = { isa = PBXProject; attributes = { TargetAttributes = { 48B5980C775BEBFED09D464C = { SystemCapabilities = { com.apple.GameCenter.iOS = { enabled = 0; }; com.apple.InAppPurchase = { enabled = 1; }; com.apple.iCloud = { enabled = 1; }; }; }; }; }; buildConfigurationList = 1DEB928908733DD80010E9CD /* Build configuration list for PBXProject "MyProject" */; compatibilityVersion = "Xcode 3.2"; hasScannedForEncodings = 1; mainGroup = 12F5A37D963B00EFBF8281BD /* MyProject */; projectDirPath = ""; projectRoot = ""; targets = ( 48B5980C775BEBFED09D464C /* MyProject */, ); }; /* End PBXProject section */ ]] end --------------------------------------------------------------------------- -- PBXResourceBuildPhase tests --------------------------------------------------------------------------- function suite.PBXResourcesBuildPhase_OnNoResources() prepare() xcode.PBXResourcesBuildPhase(tr) test.capture [[ /* Begin PBXResourcesBuildPhase section */ 0FC4B7F6B3104128CDE10E36 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ ]] end function suite.PBXResourcesBuildPhase_OnResources() files { "English.lproj/MainMenu.xib", "French.lproj/MainMenu.xib", "Info.plist" } prepare() xcode.PBXResourcesBuildPhase(tr) test.capture [[ /* Begin PBXResourcesBuildPhase section */ 0FC4B7F6B3104128CDE10E36 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 6FE0F2A3E16C0B15906D30E3 /* MainMenu.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ ]] end --------------------------------------------------------------------------- -- PBXShellScriptBuildPhase tests --------------------------------------------------------------------------- function suite.PBXShellScriptBuildPhase_OnNoScripts() prepare() xcode.PBXShellScriptBuildPhase(tr) test.capture [[ ]] end function suite.PBXShellScriptBuildPhase_OnPrebuildScripts() prebuildcommands { 'ls src', 'cp "a" "b"' } prepare() xcode.PBXShellScriptBuildPhase(tr) test.capture [[ /* Begin PBXShellScriptBuildPhase section */ 9607AE1010C857E500CD1376 /* Prebuild */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = Prebuild; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "set -e\nif [ \"${CONFIGURATION}\" = \"Debug\" ]; then\nls src\ncp \"a\" \"b\"\nfi\nif [ \"${CONFIGURATION}\" = \"Release\" ]; then\nls src\ncp \"a\" \"b\"\nfi"; }; /* End PBXShellScriptBuildPhase section */ ]] end function suite.PBXShellScriptBuildPhase_OnBuildComandScripts() files { "file.in1" } filter { "files:file.in1" } buildcommands { 'ls src', 'cp "a" "b"' } buildinputs { "file.in2" } buildoutputs { "file.out" } prepare() xcode.PBXShellScriptBuildPhase(tr) test.capture [[ /* Begin PBXShellScriptBuildPhase section */ 9AE2196BE8450F9D5E640FAB /* Build "file.in1" */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( "file.in1", "file.in2", ); name = "Build \"file.in1\""; outputPaths = ( "file.out", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "set -e\nif [ \"${CONFIGURATION}\" = \"Debug\" ]; then\n\tls src\n\tcp \"a\" \"b\"\nfi\nif [ \"${CONFIGURATION}\" = \"Release\" ]; then\n\tls src\n\tcp \"a\" \"b\"\nfi"; }; /* End PBXShellScriptBuildPhase section */ ]] end function suite.PBXShellScriptBuildPhase_OnPerConfigCmds() prebuildcommands { 'ls src' } configuration "Debug" prebuildcommands { 'cp a b' } prepare() xcode.PBXShellScriptBuildPhase(tr) test.capture [[ /* Begin PBXShellScriptBuildPhase section */ 9607AE1010C857E500CD1376 /* Prebuild */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = Prebuild; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "set -e\nif [ \"${CONFIGURATION}\" = \"Debug\" ]; then\nls src\ncp a b\nfi\nif [ \"${CONFIGURATION}\" = \"Release\" ]; then\nls src\nfi"; }; /* End PBXShellScriptBuildPhase section */ ]] end function suite.PBXShellScriptBuildPhase_OnBuildInputsAnddOutputsOrder() files { "file.a" } filter { "files:file.a" } buildcommands { "buildcmd" } buildinputs { "file.3", "file.1", "file.2" } buildoutputs { "file.5", "file.6", "file.4" } prepare() xcode.PBXShellScriptBuildPhase(tr) test.capture [[ /* Begin PBXShellScriptBuildPhase section */ 0D594A1D2F24F74F6BDA205D /* Build "file.a" */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( "file.a", "file.3", "file.1", "file.2", ); name = "Build \"file.a\""; outputPaths = ( "file.5", "file.6", "file.4", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "set -e\nif [ \"${CONFIGURATION}\" = \"Debug\" ]; then\n\tbuildcmd\nfi\nif [ \"${CONFIGURATION}\" = \"Release\" ]; then\n\tbuildcmd\nfi"; }; /* End PBXShellScriptBuildPhase section */ ]] end --------------------------------------------------------------------------- -- PBXSourcesBuildPhase tests --------------------------------------------------------------------------- function suite.PBXSourcesBuildPhase_OnNoSources() prepare() xcode.PBXSourcesBuildPhase(tr) test.capture [[ /* Begin PBXSourcesBuildPhase section */ 7971D14D1CBD5A7F378E278D /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ ]] end function suite.PBXSourcesBuildPhase_OnSources() files { "hello.cpp", "goodbye.cpp" } prepare() xcode.PBXSourcesBuildPhase(tr) test.capture [[ /* Begin PBXSourcesBuildPhase section */ 7971D14D1CBD5A7F378E278D /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( D7426C94082664861B3E9AD4 /* goodbye.cpp in Sources */, EF69EEEA1EFBBDDCFA08FD2A /* hello.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ ]] end --------------------------------------------------------------------------- -- PBXVariantGroup tests --------------------------------------------------------------------------- function suite.PBXVariantGroup_OnNoGroups() prepare() xcode.PBXVariantGroup(tr) test.capture [[ /* Begin PBXVariantGroup section */ /* End PBXVariantGroup section */ ]] end function suite.PBXVariantGroup_OnNoResourceGroups() files { "English.lproj/MainMenu.xib", "French.lproj/MainMenu.xib" } prepare() xcode.PBXVariantGroup(tr) test.capture [[ /* Begin PBXVariantGroup section */ 6CB8FB6B191BBB9DD7A431AB /* MainMenu.xib */ = { isa = PBXVariantGroup; children = ( 625C7BEB5C1E385D961D3A2B /* English */, 31594983623D4175755577C3 /* French */, ); name = MainMenu.xib; sourceTree = "<group>"; }; /* End PBXVariantGroup section */ ]] end --------------------------------------------------------------------------- -- XCBuildConfiguration_Target tests --------------------------------------------------------------------------- function suite.XCBuildConfigurationTarget_OnConsoleApp() prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnConsoleApp_dwarf() debugformat "Dwarf" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = dwarf; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnConsoleApp_split_dwarf() debugformat "SplitDwarf" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnConsoleApp_default() debugformat "Default" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnWindowedApp() kind "WindowedApp" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ F1C0BE8A138C6BBC504194CA /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = "\"$(HOME)/Applications\""; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnStaticLib() kind "StaticLib" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 92D99EC1EE1AF233C1753D01 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/lib; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnSharedLib() kind "SharedLib" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 144A3F940E0BFC06480AFDD4 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; EXECUTABLE_PREFIX = lib; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/lib; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnOSXBundle() kind "SharedLib" sharedlibtype "OSXBundle" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 5C54F6038D38EDF5A0512443 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Bundles"; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnXCTest() kind "SharedLib" sharedlibtype "XCTest" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 0C14B9243CF8B1165010E764 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnOSXFramework() kind "SharedLib" sharedlibtype "OSXFramework" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 2EC4D23760BE1CE9DA9D5877 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnTargetPrefix() kind "SharedLib" targetprefix "xyz" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 33365BC82CF8183A66F71A08 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; EXECUTABLE_PREFIX = xyz; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/lib; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnConsoleAppTargetExtension() kind "ConsoleApp" targetextension ".xyz" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 4FD8665471A41386AE593C94 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject.xyz; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnConsoleAppNoTargetExtension() kind "ConsoleApp" targetextension "" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnSharedLibTargetExtension() kind "SharedLib" targetextension ".xyz" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 8FB8842BC09C7C1DD3B4B26B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; EXECUTABLE_EXTENSION = xyz; EXECUTABLE_PREFIX = lib; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/lib; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnSharedLibNoTargetExtension() kind "SharedLib" targetextension "" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 5E2996528DBB654468C8A492 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; EXECUTABLE_EXTENSION = ""; EXECUTABLE_PREFIX = lib; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/lib; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnStaticLibTargetExtension() kind "StaticLib" targetextension ".xyz" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 8FB8842BC09C7C1DD3B4B26B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; EXECUTABLE_EXTENSION = xyz; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/lib; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnStaticLibNoTargetExtension() kind "StaticLib" targetextension "" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 5E2996528DBB654468C8A492 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; EXECUTABLE_EXTENSION = ""; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/lib; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnWindowedAppTargetExtension() kind "WindowedApp" targetextension ".xyz" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 4FD8665471A41386AE593C94 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = "\"$(HOME)/Applications\""; PRODUCT_NAME = MyProject; WRAPPER_EXTENSION = xyz; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnWindowedAppNoTargetExtension() kind "WindowedApp" targetextension "" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = "\"$(HOME)/Applications\""; PRODUCT_NAME = MyProject; WRAPPER_EXTENSION = ""; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnOSXBundleTargetExtension() kind "SharedLib" sharedlibtype "OSXBundle" targetextension ".xyz" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 4FD8665471A41386AE593C94 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Bundles"; PRODUCT_NAME = MyProject; WRAPPER_EXTENSION = xyz; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnOSXBundleNoTargetExtension() kind "SharedLib" sharedlibtype "OSXBundle" targetextension "" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Bundles"; PRODUCT_NAME = MyProject; WRAPPER_EXTENSION = ""; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnOSXFrameworkTargetExtension() kind "SharedLib" sharedlibtype "OSXFramework" targetextension ".xyz" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 4FD8665471A41386AE593C94 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; PRODUCT_NAME = MyProject; WRAPPER_EXTENSION = xyz; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnOSXFrameworkNoTargetExtension() kind "SharedLib" sharedlibtype "OSXFramework" targetextension "" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; PRODUCT_NAME = MyProject; WRAPPER_EXTENSION = ""; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnOSXMinVersion() _TARGET_OS = "macosx" systemversion "10.11" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; MACOSX_DEPLOYMENT_TARGET = 10.11; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnOSXUnSpecificedVersion() _TARGET_OS = "macosx" -- systemversion "10.11" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnInfoPlist() files { "./a/b/c/MyProject-Info.plist" } prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INFOPLIST_FILE = "a/b/c/MyProject-Info.plist"; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnSymbols() symbols "On" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnTargetSuffix() targetsuffix "-d" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ 46BCF44C6EF7ACFE56933A8C /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = "MyProject-d"; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnSinglePlatform() platforms { "Universal32" } prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Universal32/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnMultiplePlatforms() workspace("MyWorkspace") platforms { "Universal32", "Universal64" } prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CONFIGURATION_BUILD_DIR = bin/Universal32/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnIOS() _TARGET_OS = "ios" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject; SDKROOT = iphoneos; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnIOSMinVersion() _TARGET_OS = "ios" systemversion "8.3" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; IPHONEOS_DEPLOYMENT_TARGET = 8.3; PRODUCT_NAME = MyProject; SDKROOT = iphoneos; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnIOSMinMaxVersion() _TARGET_OS = "ios" systemversion "8.3:9.1" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; IPHONEOS_DEPLOYMENT_TARGET = 8.3; PRODUCT_NAME = MyProject; SDKROOT = iphoneos; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnIOSCodeSigningIdentity() _TARGET_OS = "ios" xcodecodesigningidentity "Premake Developers" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "Premake Developers"; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject; SDKROOT = iphoneos; }; name = Debug; }; ]] end function suite.XCBuildConfigurationTarget_OnIOSFamily() _TARGET_OS = "ios" iosfamily "Universal" prepare() xcode.XCBuildConfiguration_Target(tr, tr.products.children[1], tr.configs[1]) test.capture [[ FDC4CBFB4635B02D8AD4823B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CONFIGURATION_BUILD_DIR = bin/Debug; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = NO; INSTALL_PATH = /usr/local/bin; PRODUCT_NAME = MyProject; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; }; ]] end --------------------------------------------------------------------------- -- XCBuildConfiguration_Project tests --------------------------------------------------------------------------- function suite.XCBuildConfigurationProject_OnConsoleApp() prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnOptimizeSize() optimize "Size" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = s; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnOptimizeSpeed() optimize "Speed" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 3; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnStaticRuntime() flags { "StaticRuntime" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; STANDARD_C_PLUS_PLUS_LIBRARY_TYPE = static; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnTargetDir() targetdir "bin" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnDefines() defines { "_DEBUG", "DEBUG" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( _DEBUG, DEBUG, ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnIncludeDirs() includedirs { "../include", "../libs", "../name with spaces" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; USER_HEADER_SEARCH_PATHS = ( ../include, ../libs, "\"../name with spaces\"", ); }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnSysIncludeDirs() sysincludedirs { "../include", "../libs", "../name with spaces" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; SYSTEM_HEADER_SEARCH_PATHS = ( ../include, ../libs, "\"../name with spaces\"", "$(inherited)", ); }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnBuildOptions() buildoptions { "build option 1", "build option 2" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; OTHER_CFLAGS = ( "build option 1", "build option 2", ); SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnRunPathSearchPaths() runpathdirs { "plugins" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; LD_RUNPATH_SEARCH_PATHS = ( "@loader_path/../../plugins", ); OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnLinks() links { "Cocoa.framework", "ldap" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; OTHER_LDFLAGS = ( "-lldap", ); SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnLinkOptions() linkoptions { "link option 1", "link option 2" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; OTHER_LDFLAGS = ( "link option 1", "link option 2", ); SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnNoWarnings() warnings "Off" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; WARNING_CFLAGS = "-w"; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnHighWarnings() warnings "High" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; WARNING_CFLAGS = "-Wall"; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnExtraWarnings() warnings "Extra" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; WARNING_CFLAGS = "-Wall -Wextra"; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnEverythingWarnings() warnings "Everything" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; WARNING_CFLAGS = "-Weverything"; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnFatalWarnings() flags { "FatalWarnings" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_TREAT_WARNINGS_AS_ERRORS = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnFloatFast() flags { "FloatFast" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; OTHER_CFLAGS = ( "-ffast-math", ); SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnFloatStrict() floatingpoint "Strict" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnNoEditAndContinue() editandcontinue "Off" symbols "On" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; COPY_PHASE_STRIP = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = YES; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnNoExceptions() exceptionhandling "Off" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_ENABLE_CPP_EXCEPTIONS = NO; GCC_ENABLE_OBJC_EXCEPTIONS = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnNoFramePointer() flags { "NoFramePointer" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; OTHER_CFLAGS = ( "-fomit-frame-pointer", ); SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnOmitFramePointer() omitframepointer "On" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; OTHER_CFLAGS = ( "-fomit-frame-pointer", ); SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnNoOmitFramePointer() omitframepointer "Off" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; OTHER_CFLAGS = ( "-fno-omit-frame-pointer", ); SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnNoPCH() pchheader "MyProject_Prefix.pch" flags { "NoPCH" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnNoRTTI() rtti "Off" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_ENABLE_CPP_RTTI = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnSymbols() symbols "On" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; COPY_PHASE_STRIP = NO; GCC_ENABLE_FIX_AND_CONTINUE = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = YES; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnLibDirs() libdirs { "mylibs1", "mylibs2" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; LIBRARY_SEARCH_PATHS = ( mylibs1, mylibs2, ); OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnSysLibDirs() libdirs { "mylibs1", "mylibs2" } syslibdirs { "mysyslib3", "mysyslib4" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; LIBRARY_SEARCH_PATHS = ( mylibs1, mylibs2, mysyslib3, mysyslib4, ); OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnPCH() pchheader "MyProject_Prefix.pch" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = MyProject_Prefix.pch; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnUniversal() workspace("MyWorkspace") platforms { "Universal" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(ARCHS_STANDARD_32_64_BIT)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Universal/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Universal/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnUniversal32() workspace("MyWorkspace") platforms { "Universal32" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(ARCHS_STANDARD_32_BIT)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Universal32/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Universal32/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnUniversal64() workspace("MyWorkspace") platforms { "Universal64" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(ARCHS_STANDARD_64_BIT)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Universal64/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Universal64/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnNative() workspace("MyWorkspace") platforms { "Native" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Native/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Native/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnX86() workspace("MyWorkspace") platforms { "x86" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = i386; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/x86/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/x86/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnX86_64() workspace("MyWorkspace") platforms { "x86_64" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = x86_64; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/x86_64/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/x86_64/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnMultiplePlatforms() workspace("MyWorkspace") platforms { "Universal32", "Universal64" } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(ARCHS_STANDARD_32_BIT)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Universal32/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Universal32/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCDefault() workspace("MyWorkspace") cdialect("Default") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_C_LANGUAGE_STANDARD = "compiler-default"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnC89() workspace("MyWorkspace") cdialect("C89") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_C_LANGUAGE_STANDARD = c89; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnC90() workspace("MyWorkspace") cdialect("C90") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_C_LANGUAGE_STANDARD = c90; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnC99() workspace("MyWorkspace") cdialect("C99") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_C_LANGUAGE_STANDARD = c99; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnC11() workspace("MyWorkspace") cdialect("C11") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_C_LANGUAGE_STANDARD = c11; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnGnu89() workspace("MyWorkspace") cdialect("gnu89") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_C_LANGUAGE_STANDARD = gnu89; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnGnu90() workspace("MyWorkspace") cdialect("gnu90") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_C_LANGUAGE_STANDARD = gnu90; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnGnu99() workspace("MyWorkspace") cdialect("gnu99") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnGnu11() workspace("MyWorkspace") cdialect("gnu11") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCppDefault() workspace("MyWorkspace") cppdialect("Default") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "compiler-default"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCpp98() workspace("MyWorkspace") cppdialect("C++98") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "c++98"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCpp11() workspace("MyWorkspace") cppdialect("C++11") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "c++11"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCpp0x() workspace("MyWorkspace") cppdialect("C++0x") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "c++11"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCpp14() workspace("MyWorkspace") cppdialect("C++14") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "c++14"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCpp1y() workspace("MyWorkspace") cppdialect("C++1y") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "c++14"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCpp17() workspace("MyWorkspace") cppdialect("C++17") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "c++1z"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCpp1z() workspace("MyWorkspace") cppdialect("C++1z") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "c++1z"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCpp20() workspace("MyWorkspace") cppdialect("C++20") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "c++2a"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCpp2a() workspace("MyWorkspace") cppdialect("C++2a") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "c++2a"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCppGnu98() workspace("MyWorkspace") cppdialect("gnu++98") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++98"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCppGnu11() workspace("MyWorkspace") cppdialect("gnu++11") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCppGnu0x() workspace("MyWorkspace") cppdialect("gnu++0x") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCppGnu14() workspace("MyWorkspace") cppdialect("gnu++14") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCppGnu1y() workspace("MyWorkspace") cppdialect("gnu++1y") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCppGnu17() workspace("MyWorkspace") cppdialect("gnu++17") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++1z"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCppGnu1z() workspace("MyWorkspace") cppdialect("gnu++1z") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++1z"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCppGnu20() workspace("MyWorkspace") cppdialect("gnu++20") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++2a"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnCppGnu2a() workspace("MyWorkspace") cppdialect("gnu++2a") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++2a"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnUnsignedCharOn() workspace("MyWorkspace") unsignedchar "On" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_CHAR_IS_UNSIGNED_CHAR = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnUnsignedCharOff() workspace("MyWorkspace") unsignedchar "Off" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_CHAR_IS_UNSIGNED_CHAR = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnRemoveXcodebuildSettings() xcodebuildsettings { ARCHS = false } prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnSwift4_0() workspace("MyWorkspace") swiftversion("4.0") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SWIFT_VERSION = 4.0; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnSwift4_2() workspace("MyWorkspace") swiftversion("4.2") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SWIFT_VERSION = 4.2; SYMROOT = bin/Debug; }; name = Debug; }; ]] end function suite.XCBuildConfigurationProject_OnSwift5_0() workspace("MyWorkspace") swiftversion("5.0") prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ A14350AC4595EE5E57CE36EC /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = NO; SWIFT_VERSION = 5.0; SYMROOT = bin/Debug; }; name = Debug; }; ]] end --------------------------------------------------------------------------- -- XCBuildConfigurationList tests --------------------------------------------------------------------------- function suite.XCBuildConfigurationList_OnNoPlatforms() prepare() xcode.XCBuildConfigurationList(tr) test.capture [[ /* Begin XCConfigurationList section */ 1DEB928908733DD80010E9CD /* Build configuration list for PBXProject "MyProject" */ = { isa = XCConfigurationList; buildConfigurations = ( A14350AC4595EE5E57CE36EC /* Debug */, F3C205E6F732D818789F7C26 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Debug; }; 8E187FB5316408E74C34D5F5 /* Build configuration list for PBXNativeTarget "MyProject" */ = { isa = XCConfigurationList; buildConfigurations = ( FDC4CBFB4635B02D8AD4823B /* Debug */, C8EAD1B5F1258A67D8C117F5 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Debug; }; /* End XCConfigurationList section */ ]] end function suite.XCBuildConfigurationList_OnSinglePlatforms() platforms { "Universal32" } prepare() xcode.XCBuildConfigurationList(tr) test.capture [[ /* Begin XCConfigurationList section */ 1DEB928908733DD80010E9CD /* Build configuration list for PBXProject "MyProject" */ = { isa = XCConfigurationList; buildConfigurations = ( A14350AC4595EE5E57CE36EC /* Debug */, F3C205E6F732D818789F7C26 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Debug; }; 8E187FB5316408E74C34D5F5 /* Build configuration list for PBXNativeTarget "MyProject" */ = { isa = XCConfigurationList; buildConfigurations = ( FDC4CBFB4635B02D8AD4823B /* Debug */, C8EAD1B5F1258A67D8C117F5 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Debug; }; /* End XCConfigurationList section */ ]] end function suite.XCBuildConfigurationList_OnMultiplePlatforms() workspace("MyWorkspace") platforms { "Universal32", "Universal64" } prepare() xcode.XCBuildConfigurationList(tr) test.capture [[ /* Begin XCConfigurationList section */ 1DEB928908733DD80010E9CD /* Build configuration list for PBXProject "MyProject" */ = { isa = XCConfigurationList; buildConfigurations = ( A14350AC4595EE5E57CE36EC /* Debug */, A14350AC4595EE5E57CE36EC /* Debug */, F3C205E6F732D818789F7C26 /* Release */, F3C205E6F732D818789F7C26 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Debug; }; 8E187FB5316408E74C34D5F5 /* Build configuration list for PBXNativeTarget "MyProject" */ = { isa = XCConfigurationList; buildConfigurations = ( FDC4CBFB4635B02D8AD4823B /* Debug */, FDC4CBFB4635B02D8AD4823B /* Debug */, C8EAD1B5F1258A67D8C117F5 /* Release */, C8EAD1B5F1258A67D8C117F5 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Debug; }; /* End XCConfigurationList section */ ]] end function suite.defaultVisibility_settingIsFound() prepare() xcode.XCBuildConfiguration(tr) local str = p.captured() test.istrue(str:find('GCC_SYMBOLS_PRIVATE_EXTERN')) end function suite.defaultVisibilitySetting_setToNo() prepare() xcode.XCBuildConfiguration(tr) local str = p.captured() test.istrue(str:find('GCC_SYMBOLS_PRIVATE_EXTERN = NO;')) end function suite.releaseBuild_onlyDefaultArch_equalsNo() optimize "On" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[2]) local str = p.captured() test.istrue(str:find('ONLY_ACTIVE_ARCH = NO;')) end function suite.debugBuild_onlyDefaultArch_equalsYes() symbols "On" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) local str = p.captured() test.istrue(str:find('ONLY_ACTIVE_ARCH = YES;')) end
bsd-3-clause
czfshine/Don-t-Starve
data/scripts/screens/modsscreen.lua
1
31972
local Screen = require "widgets/screen" local AnimButton = require "widgets/animbutton" local Spinner = require "widgets/spinner" local ImageButton = require "widgets/imagebutton" local TextButton = require "widgets/textbutton" local Text = require "widgets/text" local Image = require "widgets/image" local NumericSpinner = require "widgets/numericspinner" local Widget = require "widgets/widget" local UIAnim = require "widgets/uianim" local Menu = require "widgets/menu" local PopupDialogScreen = require "screens/popupdialog" local ModConfigurationScreen = require "screens/modconfigurationscreen" local text_font = DEFAULTFONT--NUMBERFONT local display_rows = 5 local DISABLE = 0 local ENABLE = 1 local mid_col = RESOLUTION_X*.07 local left_col = -RESOLUTION_X*.3 local right_col = RESOLUTION_X*.37 local ModsScreen = Class(Screen, function(self, cb) Widget._ctor(self, "ModsScreen") self.cb = cb -- save current mod index before user configuration KnownModIndex:CacheSaveData() -- get the latest mod info KnownModIndex:UpdateModInfo() self.modnames = KnownModIndex:GetModNames() local function alphasort(moda, modb) if not moda then return false end if not modb then return true end return string.lower(KnownModIndex:GetModFancyName(moda)) < string.lower(KnownModIndex:GetModFancyName(modb)) end table.sort(self.modnames, alphasort) self.infoprefabs = {} self.bg = self:AddChild(Image("images/ui.xml", "bg_plain.tex")) if IsDLCEnabled(REIGN_OF_GIANTS) then self.bg:SetTint(BGCOLOURS.PURPLE[1],BGCOLOURS.PURPLE[2],BGCOLOURS.PURPLE[3], 1) else self.bg:SetTint(BGCOLOURS.RED[1],BGCOLOURS.RED[2],BGCOLOURS.RED[3], 1) end self.bg:SetVRegPoint(ANCHOR_MIDDLE) self.bg:SetHRegPoint(ANCHOR_MIDDLE) self.bg:SetVAnchor(ANCHOR_MIDDLE) self.bg:SetHAnchor(ANCHOR_MIDDLE) self.bg:SetScaleMode(SCALEMODE_FILLSCREEN) self.root = self:AddChild(Widget("root")) self.root:SetVAnchor(ANCHOR_MIDDLE) self.root:SetHAnchor(ANCHOR_MIDDLE) self.root:SetScaleMode(SCALEMODE_PROPORTIONAL) -- self.cancelbutton = self.root:AddChild(ImageButton()) -- self.cancelbutton:SetText(STRINGS.UI.MODSSCREEN.CANCEL) -- self.cancelbutton:SetPosition(Vector3(80,-220,0)) -- self.cancelbutton:SetOnClick(function() self:Cancel() end) -- self.applybutton = self.root:AddChild(ImageButton()) -- self.applybutton:SetText(STRINGS.UI.MODSSCREEN.APPLY) -- self.applybutton:SetPosition(Vector3(-80, -220, 0)) -- self.applybutton:SetOnClick(function() self:Apply() end) -- mod details panel self:CreateDetailPanel() self.mainmenu = self.root:AddChild(Menu(nil, 0, true)) self.mainmenu:SetPosition(mid_col, 0, 0) self.applybutton = self.mainmenu:AddItem(STRINGS.UI.MODSSCREEN.APPLY, function() self:Apply() end, Vector3(-90,-285,0)) self.cancelbutton = self.mainmenu:AddItem(STRINGS.UI.MODSSCREEN.CANCEL, function() self:Cancel() end, Vector3(90,-285,0)) self.modconfigbutton = self.mainmenu:AddItem(STRINGS.UI.MODSSCREEN.CONFIGUREMOD, function() self:ConfigureSelectedMod() end, Vector3(0, -165, 0)) self.modconfigbutton:SetScale(.85) self.option_offset = 0 self.optionspanel = self.root:AddChild(Menu(nil, -98, false)) self.optionspanel:SetPosition(left_col,0,0) self.optionspanelbg = self.optionspanel:AddChild(Image("images/fepanels.xml", "panel_mod1.tex")) self:CreateTopModsPanel() --------Build controller support self.optionspanel:SetFocusChangeDir(MOVE_RIGHT, self.mainmenu) self.applybutton:SetFocusChangeDir(MOVE_LEFT, self.optionspanel) self.applybutton:SetFocusChangeDir(MOVE_RIGHT, self.cancelbutton) self.applybutton:SetFocusChangeDir(MOVE_UP, self.modconfigbutton) self.cancelbutton:SetFocusChangeDir(MOVE_LEFT, self.applybutton) self.cancelbutton:SetFocusChangeDir(MOVE_RIGHT, self.morebutton) self.cancelbutton:SetFocusChangeDir(MOVE_UP, self.modconfigbutton) self.morebutton:SetFocusChangeDir(MOVE_LEFT, self.cancelbutton) self.morebutton:SetFocusChangeDir(MOVE_UP, self.featuredbutton) self.morebutton:SetFocusChangeDir(MOVE_DOWN, self.modlinks[1]) self.featuredbutton:SetFocusChangeDir(MOVE_DOWN, self.morebutton) self.featuredbutton:SetFocusChangeDir(MOVE_UP, self.modlinks[5]) self.featuredbutton:SetFocusChangeDir(MOVE_LEFT, self.cancelbutton) self.modconfigbutton:SetFocusChangeDir(MOVE_LEFT, self.optionspanel) self.modconfigbutton:SetFocusChangeDir(MOVE_RIGHT, self.morebutton) self.modconfigbutton:SetFocusChangeDir(MOVE_DOWN, self.applybutton) for i = 1, 5 do if self.modlinks[i+1] ~= nil then self.modlinks[i]:SetFocusChangeDir(MOVE_DOWN, self.modlinks[i+1]) else self.modlinks[i]:SetFocusChangeDir(MOVE_DOWN, self.featuredbutton) end if self.modlinks[i-1] ~= nil then self.modlinks[i]:SetFocusChangeDir(MOVE_UP, self.modlinks[i-1]) else self.modlinks[i]:SetFocusChangeDir(MOVE_UP, self.morebutton) end self.modlinks[i]:SetFocusChangeDir(MOVE_LEFT, self.cancelbutton) end ----------- self.leftbutton = self.optionspanel:AddChild(ImageButton("images/ui.xml", "scroll_arrow.tex", "scroll_arrow_over.tex", "scroll_arrow_disabled.tex")) self.leftbutton:SetPosition(0, 290, 0) --self.leftbutton:SetScale(-1,1,1) self.leftbutton:SetRotation(-90) self.leftbutton:SetOnClick( function() self:Scroll(-display_rows) end) self.rightbutton = self.optionspanel:AddChild(ImageButton("images/ui.xml", "scroll_arrow.tex", "scroll_arrow_over.tex", "scroll_arrow_disabled.tex")) self.rightbutton:SetPosition(0, -300, 0) self.rightbutton:SetRotation(90) self.rightbutton:SetOnClick( function() self:Scroll(display_rows) end) ---- Workshop blinker --self.workshopupdatenote = self.optionspanel:AddChild(Text(TITLEFONT, 40)) --self.workshopupdatenote:SetHAlign(ANCHOR_MIDDLE) --self.workshopupdatenote:SetPosition(0, 0, 0) --self.workshopupdatenote:SetString("Updating Steam Workshop Info...") --self.workshopupdatenote:Hide() self.optionwidgets = {} self:StartWorkshopUpdate() self.default_focus = self.cancelbutton self.cancelbutton:MoveToFront() self.applybutton:MoveToFront() end) function ModsScreen:GenerateRandomPicks(num, numrange) local picks = {} while #picks < num do local num = math.random(1, numrange) if not table.contains(picks, num) then table.insert(picks, num) end end return picks end function ModsScreen:OnStatsQueried( result, isSuccessful, resultCode ) if TheFrontEnd.screenstack[#TheFrontEnd.screenstack] ~= self then return end if not result or not isSuccessful or string.len(result) <= 1 then return end local status, jsonresult = pcall( function() return json.decode(result) end ) if not jsonresult or not status then return end local randomPicks = self:GenerateRandomPicks(#self.modlinks, 20) for i = 1, #self.modlinks do local title = jsonresult["modnames"][randomPicks[i]] if title then local url = jsonresult["modlinks"][title] title = string.gsub(title, "(ws%-)", "") if string.len(title) > 25 then title = string.sub(title, 0, 25).."..." end self.modlinks[i]:SetText(title) if url then self.modlinks[i]:SetOnClick(function() VisitURL(url) end) end end end local title, url = next(jsonresult["modfeature"]) if title and url then title = string.gsub(title, "(ws%-)", "") self.featuredbutton:SetText(title) self.featuredbutton:SetOnClick(function() VisitURL(url) end) end end function ModsScreen:CreateTopModsPanel() --Top Mods Stuff-- self.topmods = self.root:AddChild(Widget("topmods")) self.topmods:SetPosition(right_col,0,0) self.topmodsbg = self.topmods:AddChild( Image( "images/fepanels.xml", "panel_topmods.tex" ) ) self.topmodsbg:SetScale(1,1,1) self.morebutton = self.topmods:AddChild(ImageButton()) self.morebutton:SetText(STRINGS.UI.MODSSCREEN.MOREMODS) self.morebutton:SetPosition(Vector3(0,-220,0)) self.morebutton:SetOnClick(function() self:MoreMods() end) self.title = self.topmods:AddChild(Text(TITLEFONT, 40)) self.title:SetPosition(Vector3(0,225,0)) self.title:SetString(STRINGS.UI.MODSSCREEN.TOPMODS) self.modlinks = {} local yoffset = 170 for i = 1, 5 do local modlink = self.topmods:AddChild(TextButton("images/ui.xml", "blank.tex","blank.tex","blank.tex","blank.tex")) modlink:SetPosition(Vector3(0,yoffset,0)) modlink:SetText(STRINGS.UI.MODSSCREEN.LOADING.."...") modlink:SetFont(BUTTONFONT) modlink:SetTextColour(0.9,0.8,0.6,1) modlink:SetTextFocusColour(1,1,1,1) table.insert(self.modlinks, modlink) yoffset = yoffset - 45 end self.featuredtitle = self.topmods:AddChild(Text(TITLEFONT, 40)) self.featuredtitle:SetPosition(Vector3(0,-70,0)) self.featuredtitle:SetString(STRINGS.UI.MODSSCREEN.FEATUREDMOD) self.featuredbutton = self.topmods:AddChild(TextButton("images/ui.xml", "blank.tex","blank.tex","blank.tex","blank.tex")) self.featuredbutton:SetPosition(Vector3(0,-130,0)) self.featuredbutton:SetText(STRINGS.UI.MODSSCREEN.LOADING.."...") self.featuredbutton:SetFont(BUTTONFONT) self.featuredbutton:SetTextColour(0.9,0.8,0.6,1) self.featuredbutton:SetTextFocusColour(1,1,1,1) end function ModsScreen:CreateDetailPanel() if self.detailpanel then self.detailpanel:Kill() end self.detailpanel = self.root:AddChild(Widget("detailpanel")) self.detailpanel:SetPosition(mid_col,90,0) self.detailpanelbg = self.detailpanel:AddChild(Image("images/fepanels.xml", "panel_mod2.tex")) self.detailpanelbg:SetScale(1,1,1) if #self.modnames > 0 then self.detailimage = self.detailpanel:AddChild(Image("images/ui.xml", "portrait_bg.tex")) self.detailimage:SetSize(102, 102) --self.detailimage:SetScale(0.8,0.8,0.8) self.detailimage:SetPosition(-130,127,0) self.detailtitle = self.detailpanel:AddChild(Text(TITLEFONT, 40)) self.detailtitle:SetHAlign(ANCHOR_LEFT) self.detailtitle:SetPosition(70, 155, 0) self.detailtitle:SetRegionSize( 270, 70 ) --self.detailversion = self.detailpanel:addchild(text(titlefont, 20)) --self.detailversion:setvalign(anchor_top) --self.detailversion:sethalign(anchor_left) --self.detailversion:setposition(200, 100, 0) --self.detailversion:setregionsize( 180, 70 ) self.detailauthor = self.detailpanel:AddChild(Text(TITLEFONT, 30)) self.detailauthor:SetColour(1.0,1.0,1.0,1) --self.detailauthor:SetColour(0.9,0.8,0.6,1) -- link colour self.detailauthor:SetHAlign(ANCHOR_LEFT) self.detailauthor:SetPosition(70, 113, 0) self.detailauthor:SetRegionSize( 270, 70 ) self.detailauthor:EnableWordWrap(true) self.detailcompatibility = self.detailpanel:AddChild(Text(TITLEFONT, 25)) self.detailcompatibility:SetColour(1.0,1.0,1.0,1) self.detailcompatibility:SetHAlign(ANCHOR_LEFT) self.detailcompatibility:SetPosition(70, 83, 0) self.detailcompatibility:SetRegionSize( 270, 70 ) self.detaildesc = self.detailpanel:AddChild(Text(BODYTEXTFONT, 25)) self.detaildesc:SetPosition(6, -8, 0) self.detaildesc:SetRegionSize( 352, 165 ) self.detaildesc:EnableWordWrap(true) self.detailwarning = self.detailpanel:AddChild(Text(BODYTEXTFONT, 25)) self.detailwarning:SetColour(0.9,0,0,1) self.detailwarning:SetPosition(15, -160, 0) self.detailwarning:SetRegionSize( 600, 107 ) self.detailwarning:EnableWordWrap(true) self.modlinkbutton = self.detailpanel:AddChild(TextButton("images/ui.xml", "blank.tex","blank.tex","blank.tex","blank.tex" )) self.modlinkbutton:SetPosition(5, -119, 0) self.modlinkbutton:SetText(STRINGS.UI.MODSSCREEN.MODLINK) self.modlinkbutton:SetFont(BUTTONFONT) self.modlinkbutton:SetTextSize(30) self.modlinkbutton:SetTextColour(0.9,0.8,0.6,1) self.modlinkbutton:SetTextFocusColour(1,1,1,1) self.modlinkbutton:SetOnClick( function() self:ModLinkCurrent() end ) --local enableoptions = {{text="Disabled", data=DISABLE},{text="Enabled",data=ENABLE}} --self.enablespinner = self.detailpanel:AddChild(Spinner(enableoptions, 200, 60)) --self.enablespinner:SetTextColour(0,0,0,1) --self.enablespinner:SetPosition(-100, -150, 0) --self.enablespinner.OnChanged = function( _, data ) --self:EnableCurrent(data) --end else self.detaildesc = self.detailpanel:AddChild(Text(BODYTEXTFONT, 25)) self.detaildesc:SetString(STRINGS.UI.MODSSCREEN.NO_MODS) self.detaildesc:SetPosition(6, -8, 0) self.detaildesc:SetRegionSize( 352, 165 ) self.detaildesc:EnableWordWrap(true) self.modlinkbutton = self.detailpanel:AddChild(TextButton("images/ui.xml", "blank.tex","blank.tex","blank.tex","blank.tex" )) self.modlinkbutton:SetPosition(5, -119, 0) self.modlinkbutton:SetFont(BUTTONFONT) self.modlinkbutton:SetTextSize(30) self.modlinkbutton:SetTextColour(0.9,0.8,0.6,1) self.modlinkbutton:SetTextFocusColour(1,1,1,1) self.modlinkbutton:SetText(STRINGS.UI.MODSSCREEN.NO_MODS_LINK) self.modlinkbutton:SetOnClick( function() self:MoreMods() end ) end end -- Not currently used, for testing only. local function OnUpdateWorkshopModsComplete(success, msg) print("OnUpdateWorkshopModsComplete", success, msg) local status = TheSim:GetWorkshopUpdateStatus() for k,v in pairs(status) do print("-", k, v) end local modInfo = TheSim:GetWorkshopMods() for i,v in ipairs(modInfo) do print(" ", i) for k,v in pairs(v) do print(" ", k, v) end end end function ModsScreen:StartWorkshopUpdate() self:WorkshopUpdateComplete() end function ModsScreen:WorkshopUpdateComplete(status, message) --bool, string if self.updatetask then self.updatetask:Cancel() self.updatetask = nil end if self.workshopupdatenote then TheFrontEnd:PopScreen() self.workshopupdatenote = nil end KnownModIndex:UpdateModInfo() self.modnames = KnownModIndex:GetModNames() local function alphasort(moda, modb) if not moda then return false end if not modb then return true end return string.lower(KnownModIndex:GetModFancyName(moda)) < string.lower(KnownModIndex:GetModFancyName(modb)) end table.sort(self.modnames, alphasort) self:ReloadModInfoPrefabs() self:CreateDetailPanel() self:Scroll(0) if #self.modnames > 0 then self:ShowModDetails(1) end --Now update the top mods local linkpref = (PLATFORM == "WIN32_STEAM" and "external") or "klei" TheSim:QueryStats( '{ "req":"modrank", "field":"Session.Loads.Mods.list", "fieldop":"unwind", "linkpref":"'..linkpref..'", "limit": 20}', function(result, isSuccessful, resultCode) self:OnStatsQueried(result, isSuccessful, resultCode) end) end function ModsScreen:ShowWorkshopStatus() if not self.workshopupdatenote then self.workshopupdatenote = PopupDialogScreen( STRINGS.UI.MODSSCREEN.WORKSHOP.UPDATE_TITLE, "", { }) TheFrontEnd:PushScreen( self.workshopupdatenote ) end local status = TheSim:GetWorkshopUpdateStatus() local statetext = "" if status.state == "list" then statetext = STRINGS.UI.MODSSCREEN.WORKSHOP.STATE_LIST elseif status.state == "details" then statetext = STRINGS.UI.MODSSCREEN.WORKSHOP.STATE_DETAILS elseif status.state == "download" then local progressstring = "" if status.progress == 0 then progressstring = STRINGS.UI.MODSSCREEN.WORKSHOP.STATE_DOWNLOAD_0 else progressstring = string.format( STRINGS.UI.MODSSCREEN.WORKSHOP.STATE_DOWNLOAD_PERCENT , string.match( tostring(status.progress*100), "^%d*")) end statetext = STRINGS.UI.MODSSCREEN.WORKSHOP.STATE_DOWNLOAD .."\n".. progressstring end self.workshopupdatenote.text:SetString(statetext) end function ModsScreen:OnControl(control, down) if ModsScreen._base.OnControl(self, control, down) then return true end if not down and control == CONTROL_CANCEL then TheFrontEnd:PopScreen() return true end end function ModsScreen:RefreshOptions() for k,v in pairs(self.optionwidgets) do v:Kill() end self.optionwidgets = {} self.optionspanel:Clear() local page_total = math.min(#self.modnames - self.option_offset, display_rows) for k = 1, page_total do local idx = self.option_offset+k local modname = self.modnames[idx] local modinfo = KnownModIndex:GetModInfo(modname) local opt = self.optionspanel:AddCustomItem(Widget("option")) opt.idx = idx opt.bg = opt:AddChild(UIAnim()) opt.bg:GetAnimState():SetBuild("savetile") opt.bg:GetAnimState():SetBank("savetile") opt.bg:GetAnimState():PlayAnimation("anim") opt.checkbox = opt:AddChild(Image("images/ui.xml", "button_checkbox1.tex")) opt.checkbox:SetPosition(-140, 0, 0) opt.checkbox:SetScale(0.5,0.5,0.5) opt.image = opt:AddChild(Image("images/ui.xml", "portrait_bg.tex")) --opt.image:SetScale(imscale,imscale,imscale) opt.image:SetPosition(-75,0,0) if modinfo and modinfo.icon and modinfo.icon_atlas then opt.image:SetTexture("../mods/"..modname.."/"..modinfo.icon_atlas, modinfo.icon) end opt.image:SetSize(76,76) opt.name = opt:AddChild(Text(TITLEFONT, 35)) opt.name:SetVAlign(ANCHOR_MIDDLE) opt.name:SetHAlign(ANCHOR_LEFT) opt.name:SetString(modname) if modinfo and modinfo.name then opt.name:SetString(modinfo.name) end opt.name:SetPosition(65, 8, 0) opt.name:SetRegionSize( 200, 50 ) opt.status = opt:AddChild(Text(BODYTEXTFONT, 20)) opt.status:SetVAlign(ANCHOR_MIDDLE) opt.status:SetHAlign(ANCHOR_LEFT) opt.status:SetString(modname) local modStatus = self:GetBestModStatus(modname) if modStatus == "WORKING_NORMALLY" then opt.status:SetString(STRINGS.UI.MODSSCREEN.STATUS.WORKING_NORMALLY) elseif modStatus == "WILL_ENABLE" then opt.status:SetString(STRINGS.UI.MODSSCREEN.STATUS.WILL_ENABLE) elseif modStatus == "WILL_DISABLE" then opt.status:SetColour(.7,.7,.7,1) opt.status:SetString(STRINGS.UI.MODSSCREEN.STATUS.WILL_DISABLE) elseif modStatus == "DISABLED_ERROR" then opt.status:SetColour(0.9,0.3,0.3,1) opt.status:SetString(STRINGS.UI.MODSSCREEN.STATUS.DISABLED_ERROR) elseif modStatus == "DISABLED_OLD" then opt.status:SetColour(0.8,0.8,0.3,1) opt.status:SetString(STRINGS.UI.MODSSCREEN.STATUS.DISABLED_OLD) elseif modStatus == "DISABLED_MANUAL" then opt.status:SetColour(.7,.7,.7,1) opt.status:SetString(STRINGS.UI.MODSSCREEN.STATUS.DISABLED_MANUAL) end opt.status:SetPosition(66, -22, 0) opt.status:SetRegionSize( 200, 50 ) opt.RoGcompatible = opt:AddChild(Image("images/ui.xml", "rog_off.tex")) if modinfo and modinfo.reign_of_giants_compatible then if modinfo.reign_of_giants_compatibility_specified == false then opt.RoGcompatible:SetTexture("images/ui.xml", "rog_unknown.tex") else opt.RoGcompatible:SetTexture("images/ui.xml", "rog_on.tex") end end opt.RoGcompatible:SetClickable(false) opt.RoGcompatible:SetScale(.35,.33,1) opt.RoGcompatible:SetPosition(144, -21, 0) opt.DScompatible = opt:AddChild(Image("images/ui.xml", "ds_off.tex")) if modinfo and modinfo.dont_starve_compatible then if modinfo.dont_starve_compatibility_specified == false then opt.DScompatible:SetTexture("images/ui.xml", "ds_unknown.tex") else opt.DScompatible:SetTexture("images/ui.xml", "ds_on.tex") end end opt.DScompatible:SetClickable(false) opt.DScompatible:SetScale(.35,.33,1) opt.DScompatible:SetPosition(100, -21, 0) if KnownModIndex:IsModEnabled(modname) then opt.image:SetTint(1,1,1,1) opt.checkbox:SetTexture("images/ui.xml", "button_checkbox2.tex") opt.checkbox:SetTint(1,1,1,1) opt.name:SetColour(1,1,1,1) opt.RoGcompatible:SetTint(1,1,1,1) opt.DScompatible:SetTint(1,1,1,1) else opt.image:SetTint(1.0,0.5,0.5,1) opt.checkbox:SetTexture("images/ui.xml", "button_checkbox1.tex") opt.checkbox:SetTint(1.0,0.5,0.5,1) opt.name:SetColour(.7,.7,.7,1) opt.RoGcompatible:SetTint(1.0,0.5,0.5,1) opt.DScompatible:SetTint(1.0,0.5,0.5,1) end local spacing = 105 opt.OnGainFocus = function() TheFrontEnd:GetSound():PlaySound("dontstarve/HUD/click_mouseover") self:ShowModDetails(idx) opt:SetScale(1.1,1.1,1) opt.bg:GetAnimState():PlayAnimation("over") end opt.OnLoseFocus = function() opt:SetScale(1,1,1) opt.bg:GetAnimState():PlayAnimation("anim") end opt.OnControl =function(_, control, down) if Widget.OnControl(opt, control, down) then return true end if control == CONTROL_ACCEPT and not down then self:EnableCurrent() self.optionspanel.items[k]:SetFocus() -- this menu gets recreated in EnableCurrent so refocus. return true end end opt:SetPosition(0, (display_rows-1)*spacing*.5 - (k-1)*spacing - 00, 0) table.insert(self.optionwidgets, opt) end for k,v in ipairs(self.optionspanel.items) do if k > 1 then self.optionspanel.items[k]:SetFocusChangeDir(MOVE_UP, function() self:ShowModDetails(self.optionspanel.items[k-1].idx) return self.optionspanel.items[k-1] end) end if k < #self.optionspanel.items then self.optionspanel.items[k]:SetFocusChangeDir(MOVE_DOWN, function() self:ShowModDetails(self.optionspanel.items[k+1].idx) return self.optionspanel.items[k+1] end) end end if self.optionspanel.items == nil or #self.optionspanel.items == 0 then return end self.optionspanel.items[1]:SetFocusChangeDir(MOVE_UP, function() if not self:OnFirstPage() then self:ShowModDetails(self.optionspanel.items[1].idx-1) self:Scroll(-display_rows) return self.optionspanel.items[#self.optionspanel.items] end return self.optionspanel.items[1] end) self.optionspanel.items[#self.optionspanel.items]:SetFocusChangeDir(MOVE_DOWN, function() if not self:OnLastPage() then self:ShowModDetails(self.optionspanel.items[#self.optionspanel.items].idx+1) self:Scroll(display_rows) return self.optionspanel.items[1] end return self.optionspanel.items[#self.optionspanel.items] end) end function ModsScreen:OnFirstPage() return self.option_offset == 0 end function ModsScreen:OnLastPage() return self.option_offset + display_rows >= #self.modnames end function ModsScreen:Scroll(dir) if (dir > 0 and (self.option_offset + display_rows) < #self.modnames) or (dir < 0 and self.option_offset + dir >= 0) then self.option_offset = self.option_offset + dir end self:RefreshOptions() if self.option_offset > 0 then self.leftbutton:Show() else self.leftbutton:Hide() end if self.option_offset + display_rows < #self.modnames then self.rightbutton:Show() else self.rightbutton:Hide() end end function ModsScreen:GetBestModStatus(modname) local modinfo = KnownModIndex:GetModInfo(modname) if KnownModIndex:IsModEnabled(modname) then if KnownModIndex:WasModEnabled(modname) then return "WORKING_NORMALLY" else return "WILL_ENABLE" end else if KnownModIndex:WasModEnabled(modname) then return "WILL_DISABLE" else if KnownModIndex:GetModInfo(modname).failed or KnownModIndex:IsModKnownBad(modname) then return "DISABLED_ERROR" elseif KnownModIndex:GetModInfo(modname).old then return "DISABLED_OLD" else return "DISABLED_MANUAL" end end end end function ModsScreen:ShowModDetails(idx) self.currentmod = idx local modname = self.modnames[idx] local modinfo = KnownModIndex:GetModInfo(modname) if modinfo.icon and modinfo.icon_atlas then self.detailimage:SetTexture("../mods/"..modname.."/"..modinfo.icon_atlas, modinfo.icon) self.detailimage:SetSize(102, 102) else self.detailimage:SetTexture("images/ui.xml", "portrait_bg.tex") self.detailimage:SetSize(102, 102) end if modinfo.name then self.detailtitle:SetString(modinfo.name) else self.detailtitle:SetString(modname) end if modinfo.version then --self.detailversion:setstring( string.format(strings.ui.modsscreen.version, modinfo.version)) else --self.detailversion:setstring( string.format(strings.ui.modsscreen.version, 0)) end if modinfo.author then self.detailauthor:SetString( string.format(STRINGS.UI.MODSSCREEN.AUTHORBY, modinfo.author)) else self.detailauthor:SetString( string.format(STRINGS.UI.MODSSCREEN.AUTHORBY, "unknown")) end if modinfo.description then self.detaildesc:SetString(modinfo.description) else self.detaildesc:SetString("") end if modinfo.forumthread then self.modlinkbutton:SetText(STRINGS.UI.MODSSCREEN.MODLINK) else self.modlinkbutton:SetText(STRINGS.UI.MODSSCREEN.MODLINKGENERIC) end if modinfo.dont_starve_compatible and modinfo.reign_of_giants_compatible then if modinfo.dont_starve_compatibility_specified == false and modinfo.reign_of_giants_compatibility_specified == false then self.detailcompatibility:SetString(STRINGS.UI.MODSSCREEN.COMPATIBILITY_UNKNOWN) else self.detailcompatibility:SetString(STRINGS.UI.MODSSCREEN.COMPATIBILITY_ALL) end else if modinfo.dont_starve_compatible and not modinfo.reign_of_giants_compatible then self.detailcompatibility:SetString(STRINGS.UI.MODSSCREEN.COMPATIBILITY_DS_ONLY) elseif not modinfo.dont_starve_compatible and modinfo.reign_of_giants_compatible then self.detailcompatibility:SetString(STRINGS.UI.MODSSCREEN.COMPATIBILITY_ROG_ONLY) else self.detailcompatibility:SetString(STRINGS.UI.MODSSCREEN.COMPATIBILITY_NONE) end end if KnownModIndex:HasModConfigurationOptions(modname) then self.modconfigbutton:Show() -- Rebuild controller focus directions if (TheInput:ControllerAttached() and not TheFrontEnd.tracking_mouse) then self.applybutton:SetFocusChangeDir(MOVE_UP, self.modconfigbutton) self.cancelbutton:SetFocusChangeDir(MOVE_UP, self.modconfigbutton) self.modconfigbutton:SetFocusChangeDir(MOVE_LEFT, self.optionspanel) self.modconfigbutton:SetFocusChangeDir(MOVE_RIGHT, self.morebutton) self.modconfigbutton:SetFocusChangeDir(MOVE_DOWN, self.applybutton) end else self.modconfigbutton:Hide() -- Clear out controller focus directions when we hide it if (TheInput:ControllerAttached() and not TheFrontEnd.tracking_mouse) then self.applybutton:SetFocusChangeDir(MOVE_UP, nil) self.cancelbutton:SetFocusChangeDir(MOVE_UP, nil) self.modconfigbutton:ClearFocusDirs() end end self.detailwarning:SetColour(1,1,1,1) local modStatus = self:GetBestModStatus(modname) if modStatus == "WORKING_NORMALLY" then --self.enablespinner:SetSelected(ENABLE) self.detailwarning:SetString(STRINGS.UI.MODSSCREEN.WORKING_NORMALLY) elseif modStatus == "WILL_ENABLE" then --self.enablespinner:SetSelected(ENABLE) self.detailwarning:SetString(STRINGS.UI.MODSSCREEN.WILL_ENABLE) elseif modStatus == "WILL_DISABLE" then --self.enablespinner:SetSelected(DISABLE) self.detailwarning:SetString(STRINGS.UI.MODSSCREEN.WILL_DISABLE) elseif modStatus == "DISABLED_ERROR" then --self.enablespinner:SetSelected(DISABLE) self.detailwarning:SetColour(0.9,0.3,0.3,1) self.detailwarning:SetString(STRINGS.UI.MODSSCREEN.DISABLED_ERROR) elseif modStatus == "DISABLED_OLD" then --self.enablespinner:SetSelected(DISABLE) self.detailwarning:SetColour(0.8,0.8,0.3,1) self.detailwarning:SetString(STRINGS.UI.MODSSCREEN.DISABLED_OLD) elseif modStatus == "DISABLED_MANUAL" then --self.enablespinner:SetSelected(DISABLE) self.detailwarning:SetString(STRINGS.UI.MODSSCREEN.DISABLED_MANUAL) end end function ModsScreen:OnConfirmEnableCurrent(data, restart) local modname = self.modnames[self.currentmod] if data == DISABLE then KnownModIndex:Disable(modname) elseif data == ENABLE then KnownModIndex:Enable(modname) else if KnownModIndex:IsModEnabled(modname) then KnownModIndex:Disable(modname) else KnownModIndex:Enable(modname) end end self:Scroll(0) self:ShowModDetails(self.currentmod) if restart then KnownModIndex:Save() TheSim:Quit() end end function ModsScreen:EnableCurrent(data) local modname = self.modnames[self.currentmod] local modinfo = KnownModIndex:GetModInfo(modname) if modinfo.restart_required then print("RESTART REQUIRED") TheFrontEnd:PushScreen(PopupDialogScreen(STRINGS.UI.MODSSCREEN.RESTART_TITLE, STRINGS.UI.MODSSCREEN.RESTART_REQUIRED, { {text=STRINGS.UI.MODSSCREEN.RESTART, cb = function() self:OnConfirmEnableCurrent(data, true) end }, {text=STRINGS.UI.MODSSCREEN.CANCEL, cb = function() TheFrontEnd:PopScreen() end} })) else self:OnConfirmEnableCurrent(data, false) end end function ModsScreen:ModLinkCurrent() local modname = self.modnames[self.currentmod] local thread = KnownModIndex:GetModInfo(modname).forumthread local url = "" if thread then url = "http://forums.kleientertainment.com/index.php?%s" url = string.format(url, KnownModIndex:GetModInfo(modname).forumthread) else url = "http://forums.kleientertainment.com/index.php?/forum/26-dont-starve-mods-and-tools/" end VisitURL(url) end function ModsScreen:MoreMods() VisitURL("http://forums.kleientertainment.com/files/") end function ModsScreen:Cancel() KnownModIndex:RestoreCachedSaveData() self:UnloadModInfoPrefabs(self.infoprefabs) self.cb(false) end function ModsScreen:Apply() KnownModIndex:Save() self:UnloadModInfoPrefabs(self.infoprefabs) self.cb(true) end function ModsScreen:ConfigureSelectedMod() local modname = self.modnames[self.currentmod] local modinfo = KnownModIndex:GetModInfo(modname) TheFrontEnd:PushScreen(ModConfigurationScreen(modname)) end function ModsScreen:LoadModInfoPrefabs(prefabtable) for i,modname in ipairs(KnownModIndex:GetModNames()) do local info = KnownModIndex:GetModInfo(modname) if info.icon_atlas and info.icon then local atlaspath = "../mods/"..modname.."/"..info.icon_atlas local iconpath = string.gsub(atlaspath, "/[^/]*$", "") .. "/"..info.icon if softresolvefilepath(atlaspath) and softresolvefilepath(iconpath) then local modinfoassets = { Asset("ATLAS", atlaspath), Asset("IMAGE", iconpath), } local prefab = Prefab("modbaseprefabs/MODSCREEN_"..modname, nil, modinfoassets, nil) RegisterPrefabs( prefab ) table.insert(prefabtable, prefab.name) else -- This prevents malformed icon paths from crashing the game. print(string.format("WARNING: icon paths for mod %s are not valid. Got icon_atlas=\"%s\" and icon=\"%s\".\nPlease ensure that these point to valid files in your mod folder, or else comment out those lines from your modinfo.lua.", ModInfoname(modname), info.icon_atlas, info.icon)) info.icon_atlas = nil info.icon = nil end end end print("Loading Mod Info Prefabs") TheSim:LoadPrefabs( prefabtable ) end function ModsScreen:UnloadModInfoPrefabs(prefabtable) print("Unloading Mod Info Prefabs") TheSim:UnloadPrefabs( prefabtable ) for k,v in pairs(prefabtable) do prefabtable[k] = nil end end function ModsScreen:ReloadModInfoPrefabs() print("Reloading Mod Info Prefabs") -- load before unload -- this prevents the refcounts of prefabs from going 1, -- 0, 1 (which triggers a resource unload and crashes). Instead we load first, -- so the refcount goes 1, 2, 1 for existing prefabs so everything stays the -- same. local oldprefabs = self.infoprefabs local newprefabs = {} self:LoadModInfoPrefabs(newprefabs) self:UnloadModInfoPrefabs(oldprefabs) self.infoprefabs = newprefabs end function ModsScreen:GetHelpText() local controller_id = TheInput:GetControllerID() local t = {} -- table.insert(t, TheInput:GetLocalizedControl(controller_id, CONTROL_PAGELEFT) .. " " .. STRINGS.UI.HELP.SCROLLBACK) -- table.insert(t, TheInput:GetLocalizedControl(controller_id, CONTROL_PAGERIGHT) .. " " .. STRINGS.UI.HELP.SCROLLFWD) --table.insert(t, TheInput:GetLocalizedControl(controller_id, CONTROL_FOCUS_LEFT) .. " " .. STRINGS.UI.HELP.NEXTCHARACTER) --table.insert(t, TheInput:GetLocalizedControl(controller_id, CONTROL_FOCUS_RIGHT) .. " " .. STRINGS.UI.HELP.PREVCHARACTER) if table.contains(self.optionwidgets, TheFrontEnd:GetFocusWidget()) then table.insert(t, TheInput:GetLocalizedControl(controller_id, CONTROL_ACCEPT) .. " " .. STRINGS.UI.HELP.TOGGLE) end if not self.no_cancel then table.insert(t, TheInput:GetLocalizedControl(controller_id, CONTROL_CANCEL) .. " " .. STRINGS.UI.HELP.BACK) end return table.concat(t, " ") end return ModsScreen
gpl-2.0
CrazyEddieTK/Zero-K
gamedata/explosions_post.lua
17
1247
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Load CA's effects from ./effects and not ./gamedata/explosions -- local luaFiles = VFS.DirList('effects', '*.lua', '*.tdf') --couldn't be arsed to convert to lua since there is no real benefit for CEG's -Zement/DOT for _, filename in ipairs(luaFiles) do local edEnv = {} edEnv._G = edEnv edEnv.Shared = Shared edEnv.GetFilename = function() return filename end setmetatable(edEnv, { __index = system }) local success, eds = pcall(VFS.Include, filename, edEnv) if (not success) then Spring.Log("explosions_post.lua", "error", 'Error parsing ' .. filename .. ': ' .. eds) elseif (eds == nil) then Spring.Log("explosions_post.lua", "error", 'Missing return table from: ' .. filename) else for edName, ed in pairs(eds) do if ((type(edName) == 'string') and (type(ed) == 'table')) then ed.filename = filename ExplosionDefs[edName] = ed end end end end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
Evengard/UniMod
Libs/luasocket/samples/cddb.lua
56
1415
local socket = require("socket") local http = require("socket.http") if not arg or not arg[1] or not arg[2] then print("luasocket cddb.lua <category> <disc-id> [<server>]") os.exit(1) end local server = arg[3] or "http://freedb.freedb.org/~cddb/cddb.cgi" function parse(body) local lines = string.gfind(body, "(.-)\r\n") local status = lines() local code, message = socket.skip(2, string.find(status, "(%d%d%d) (.*)")) if tonumber(code) ~= 210 then return nil, code, message end local data = {} for l in lines do local c = string.sub(l, 1, 1) if c ~= '#' and c ~= '.' then local key, value = socket.skip(2, string.find(l, "(.-)=(.*)")) value = string.gsub(value, "\\n", "\n") value = string.gsub(value, "\\\\", "\\") value = string.gsub(value, "\\t", "\t") data[key] = value end end return data, code, message end local host = socket.dns.gethostname() local query = "%s?cmd=cddb+read+%s+%s&hello=LuaSocket+%s+LuaSocket+2.0&proto=6" local url = string.format(query, server, arg[1], arg[2], host) local body, headers, code = http.get(url) if code == 200 then local data, code, error = parse(body) if not data then print(error or code) else for i,v in pairs(data) do io.write(i, ': ', v, '\n') end end else print(error) end
lgpl-3.0
ranisalt/forgottenserver
data/actions/scripts/other/bed_modification_kits.lua
13
1647
local beds = { [7904] = {{7811, 7812}, {7813, 7814}}, -- green kit [7905] = {{7819, 7820}, {7821, 7822}}, -- yellow kit [7906] = {{7815, 7816}, {7817, 7818}}, -- red kit [7907] = {{1754, 1755}, {1760, 1761}}, -- removal kit [20252] = {{20197, 20198}, {20199, 20200}} -- canopy kit } local function internalBedTransform(item, targetItem, toPosition, itemArray) targetItem:transform(itemArray[1]) targetItem:getPosition():sendMagicEffect(CONST_ME_POFF) Tile(toPosition):getItemByType(ITEM_TYPE_BED):transform(itemArray[2]) toPosition:sendMagicEffect(CONST_ME_POFF) item:remove() end function onUse(player, item, fromPosition, target, toPosition, isHotkey) local newBed = beds[item:getId()] if not newBed or type(target) ~= "userdata" or not target:isItem() then return false end local tile = Tile(toPosition) if not tile or not tile:getHouse() then return false end local targetItemId = target:getId() if targetItemId == newBed[1][1] or targetItemId == newBed[2][1] then player:sendTextMessage(MESSAGE_STATUS_SMALL, "You already have this bed modification.") return true end for _, bed in pairs(beds) do if bed[1][1] == targetItemId or table.contains({1758, 5502, 18027}, targetItemId) then toPosition:sendMagicEffect(CONST_ME_POFF) toPosition.y = toPosition.y + 1 internalBedTransform(item, target, toPosition, newBed[1]) break elseif bed[2][1] == targetItemId or table.contains({1756, 5500, 18029}, targetItemId) then toPosition:sendMagicEffect(CONST_ME_POFF) toPosition.x = toPosition.x + 1 internalBedTransform(item, target, toPosition, newBed[2]) break end end return true end
gpl-2.0
timroes/awesome
lib/awful/spawn.lua
3
17311
--luacheck: no max line length --------------------------------------------------------------------------- --- Spawning of programs. -- -- This module provides methods to start programs and supports startup -- notifications, which allows for callbacks and applying properties to the -- program after it has been launched. This requires currently that the -- applicaton supports them. -- -- **Rules of thumb when a shell is needed**: -- -- * A shell is required when the commands contain `&&`, `;`, `||`, `&` or -- any other unix shell language syntax -- * When shell variables are defined as part of the command -- * When the command is a shell alias -- -- Note that a shell is **not** a terminal emulator. A terminal emulator is -- something like XTerm, Gnome-terminal or Konsole. A shell is something like -- `bash`, `zsh`, `busybox sh` or `Debian ash`. -- -- If you wish to open a process in a terminal window, check that your terminal -- emulator supports the common `-e` option. If it does, then something like -- this should work: -- -- awful.spawn(terminal.." -e my_command") -- -- Note that some terminals, such as rxvt-unicode (urxvt) support full commands -- using quotes, while other terminal emulators require to use quoting. -- -- **Understanding clients versus PID versus commands versus class**: -- -- A *process* has a *PID* (process identifier). It can have 0, 1 or many -- *window*s. -- -- A *command* if what is used to start *process*(es). It has no direct relation -- with *process*, *client* or *window*. When a command is executed, it will -- usually start a *process* which keeps running until it exits. This however is -- not always the case as some applications use scripts as command and others -- use various single-instance mechanisms (usually client/server) and merge -- with an existing process. -- -- A *client* corresponds to a *window*. It is owned by a process. It can have -- both a parent and one or many children. A *client* has a *class*, an -- *instance*, a *role*, and a *type*. See `client.class`, `client.instance`, -- `client.role` and `client.type` for more information about these properties. -- -- **The startup notification protocol**: -- -- The startup notification protocol is an optional specification implemented -- by X11 applications to bridge the chain of knowledge between the moment a -- program is launched to the moment its window (client) is shown. It can be -- found [on the FreeDesktop.org website](https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/). -- -- Awesome has support for the various events that are part of the protocol, but -- the most useful is the identifier, usually identified by its `SNID` acronym in -- the documentation. It isn't usually necessary to even know it exists, as it -- is all done automatically. However, if more control is required, the -- identifier can be specified by an environment variable called -- `DESKTOP_STARTUP_ID`. For example, let us consider execution of the following -- command: -- -- DESKTOP_STARTUP_ID="something_TIME$(date '+%s')" my_command -- -- This should (if the program correctly implements the protocol) result in -- `c.startup_id` to at least match `something`. -- This identifier can then be used in `awful.rules` to configure the client. -- -- Awesome can automatically set the `DESKTOP_STARTUP_ID` variable. This is used -- by `awful.spawn` to specify additional rules for the startup. For example: -- -- awful.spawn("urxvt -e maxima -name CALCULATOR", { -- floating = true, -- tag = mouse.screen.selected_tag, -- placement = awful.placement.bottom_right, -- }) -- -- This can also be used from the command line: -- -- awesome-client 'awful=require("awful"); -- awful.spawn("urxvt -e maxima -name CALCULATOR", { -- floating = true, -- tag = mouse.screen.selected_tag, -- placement = awful.placement.bottom_right, -- })' -- -- **Getting a command's output**: -- -- First, do **not** use `io.popen` **ever**. It is synchronous. Synchronous -- functions **block everything** until they are done. All visual applications -- lock (as Awesome no longer responds), you will probably lose some keyboard -- and mouse events and will have higher latency when playing games. This is -- also true when reading files synchronously, but this is another topic. -- -- Awesome provides a few ways to get output from commands. One is to use the -- `Gio` libraries directly. This is usually very complicated, but gives a lot -- of control on the command execution. -- -- This modules provides `with_line_callback` and `easy_async` for convenience. -- First, lets add this bash command to `rc.lua`: -- -- local noisy = [[bash -c ' -- for I in $(seq 1 5); do -- date -- echo err >&2 -- sleep 2 -- done -- ']] -- -- It prints a bunch of junk on the standard output (*stdout*) and error -- (*stderr*) streams. This command would block Awesome for 10 seconds if it -- were executed synchronously, but will not block it at all using the -- asynchronous functions. -- -- `with_line_callback` will execute the callbacks every time a new line is -- printed by the command: -- -- awful.spawn.with_line_callback(noisy, { -- stdout = function(line) -- naughty.notify { text = "LINE:"..line } -- end, -- stderr = function(line) -- naughty.notify { text = "ERR:"..line} -- end, -- }) -- -- If only the full output is needed, then `easy_async` is the right choice: -- -- awful.spawn.easy_async(noisy, function(stdout, stderr, reason, exit_code) -- naughty.notify { text = stdout } -- end) -- -- **Default applications**: -- -- If the intent is to open a file/document, then it is recommended to use the -- following standard command. The default application will be selected -- according to the [Shared MIME-info Database](https://specifications.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html) -- specification. The `xdg-utils` package provided by most distributions -- includes the `xdg-open` command: -- -- awful.spawn({"xdg-open", "/path/to/file"}) -- -- Awesome **does not** manage, modify or otherwise influence the database -- for default applications. For information about how to do this, consult the -- [ARCH Linux Wiki](https://wiki.archlinux.org/index.php/default_applications). -- -- If you wish to change how the default applications behave, then consult the -- [Desktop Entry](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html) -- specification. -- -- @author Julien Danjou &lt;julien@danjou.info&gt; -- @author Emmanuel Lepage Vallee &lt;elv1313@gmail.com&gt; -- @copyright 2008 Julien Danjou -- @copyright 2014 Emmanuel Lepage Vallee -- @module awful.spawn --------------------------------------------------------------------------- local capi = { awesome = awesome, mouse = mouse, client = client, } local lgi = require("lgi") local Gio = lgi.Gio local GLib = lgi.GLib local util = require("awful.util") local protected_call = require("gears.protected_call") local spawn = {} local end_of_file do -- API changes, bug fixes and lots of fun. Figure out how a EOF is signalled. local input if not pcall(function() -- No idea when this API changed, but some versions expect a string, -- others a table with some special(?) entries input = Gio.DataInputStream.new(Gio.MemoryInputStream.new_from_data("")) end) then input = Gio.DataInputStream.new(Gio.MemoryInputStream.new_from_data({})) end local line, length = input:read_line() if not line then -- Fixed in 2016: NULL on the C side is transformed to nil in Lua end_of_file = function(arg) return not arg end elseif tostring(line) == "" and #line ~= length then -- "Historic" behaviour for end-of-file: -- - NULL is turned into an empty string -- - The length variable is not initialized -- It's highly unlikely that the uninitialized variable has value zero. -- Use this hack to detect EOF. end_of_file = function(arg1, arg2) return #arg1 ~= arg2 end else assert(tostring(line) == "", "Cannot determine how to detect EOF") -- The above uninitialized variable was fixed and thus length is -- always 0 when line is NULL in C. We cannot tell apart an empty line and -- EOF in this case. require("gears.debug").print_warning("Cannot reliably detect EOF on an " .. "GIOInputStream with this LGI version") end_of_file = function(arg) return tostring(arg) == "" end end end spawn.snid_buffer = {} function spawn.on_snid_callback(c) local entry = spawn.snid_buffer[c.startup_id] if entry then local props = entry[1] local callback = entry[2] c:emit_signal("spawn::completed_with_payload", props, callback) spawn.snid_buffer[c.startup_id] = nil end end function spawn.on_snid_cancel(id) if spawn.snid_buffer[id] then spawn.snid_buffer[id] = nil end end --- Spawn a program, and optionally apply properties and/or run a callback. -- -- Applying properties or running a callback requires the program/client to -- support startup notifications. -- -- See `awful.rules.execute` for more details about the format of `sn_rules`. -- -- @tparam string|table cmd The command. -- @tparam[opt=true] table|boolean sn_rules A table of properties to be applied -- after startup; `false` to disable startup notifications. -- @tparam[opt] function callback A callback function to be run after startup. -- @treturn[1] integer The forked PID. -- @treturn[1] ?string The startup notification ID, if `sn` is not false, or -- a `callback` is provided. -- @treturn[2] string Error message. function spawn.spawn(cmd, sn_rules, callback) if cmd and cmd ~= "" then local enable_sn = (sn_rules ~= false or callback) enable_sn = not not enable_sn -- Force into a boolean. local pid, snid = capi.awesome.spawn(cmd, enable_sn) -- The snid will be nil in case of failure if snid then sn_rules = type(sn_rules) ~= "boolean" and sn_rules or {} spawn.snid_buffer[snid] = { sn_rules, { callback } } end return pid, snid end -- For consistency return "Error: No command to execute" end --- Spawn a program using the shell. -- This calls `cmd` with `$SHELL -c` (via `awful.util.shell`). -- @tparam string cmd The command. function spawn.with_shell(cmd) if cmd and cmd ~= "" then cmd = { util.shell, "-c", cmd } return capi.awesome.spawn(cmd, false) end end --- Spawn a program and asynchronously capture its output line by line. -- @tparam string|table cmd The command. -- @tab callbacks Table containing callbacks that should be invoked on -- various conditions. -- @tparam[opt] function callbacks.stdout Function that is called with each -- line of output on stdout, e.g. `stdout(line)`. -- @tparam[opt] function callbacks.stderr Function that is called with each -- line of output on stderr, e.g. `stderr(line)`. -- @tparam[opt] function callbacks.output_done Function to call when no more -- output is produced. -- @tparam[opt] function callbacks.exit Function to call when the spawned -- process exits. This function gets the exit reason and code as its -- arguments. -- The reason can be "exit" or "signal". -- For "exit", the second argument is the exit code. -- For "signal", the second argument is the signal causing process -- termination. -- @treturn[1] Integer the PID of the forked process. -- @treturn[2] string Error message. function spawn.with_line_callback(cmd, callbacks) local stdout_callback, stderr_callback, done_callback, exit_callback = callbacks.stdout, callbacks.stderr, callbacks.output_done, callbacks.exit local have_stdout, have_stderr = stdout_callback ~= nil, stderr_callback ~= nil local pid, _, stdin, stdout, stderr = capi.awesome.spawn(cmd, false, false, have_stdout, have_stderr, exit_callback) if type(pid) == "string" then -- Error return pid end local done_before = false local function step_done() if have_stdout and have_stderr and not done_before then done_before = true return end if done_callback then done_callback() end end if have_stdout then spawn.read_lines(Gio.UnixInputStream.new(stdout, true), stdout_callback, step_done, true) end if have_stderr then spawn.read_lines(Gio.UnixInputStream.new(stderr, true), stderr_callback, step_done, true) end assert(stdin == nil) return pid end --- Asynchronously spawn a program and capture its output. -- (wraps `spawn.with_line_callback`). -- @tparam string|table cmd The command. -- @tab callback Function with the following arguments -- @tparam string callback.stdout Output on stdout. -- @tparam string callback.stderr Output on stderr. -- @tparam string callback.exitreason Exit reason ("exit" or "signal"). -- @tparam integer callback.exitcode Exit code (exit code or signal number, -- depending on "exitreason"). -- @treturn[1] Integer the PID of the forked process. -- @treturn[2] string Error message. -- @see spawn.with_line_callback function spawn.easy_async(cmd, callback) local stdout = '' local stderr = '' local exitcode, exitreason local function parse_stdout(str) stdout = stdout .. str .. "\n" end local function parse_stderr(str) stderr = stderr .. str .. "\n" end local function done_callback() return callback(stdout, stderr, exitreason, exitcode) end local exit_callback_fired = false local output_done_callback_fired = false local function exit_callback(reason, code) exitcode = code exitreason = reason exit_callback_fired = true if output_done_callback_fired then return done_callback() end end local function output_done_callback() output_done_callback_fired = true if exit_callback_fired then return done_callback() end end return spawn.with_line_callback( cmd, { stdout=parse_stdout, stderr=parse_stderr, exit=exit_callback, output_done=output_done_callback }) end --- Call `spawn.easy_async` with a shell. -- This calls `cmd` with `$SHELL -c` (via `awful.util.shell`). -- @tparam string|table cmd The command. -- @tab callback Function with the following arguments -- @tparam string callback.stdout Output on stdout. -- @tparam string callback.stderr Output on stderr. -- @tparam string callback.exitreason Exit reason ("exit" or "signal"). -- @tparam integer callback.exitcode Exit code (exit code or signal number, -- depending on "exitreason"). -- @treturn[1] Integer the PID of the forked process. -- @treturn[2] string Error message. -- @see spawn.with_line_callback function spawn.easy_async_with_shell(cmd, callback) return spawn.easy_async({ util.shell, "-c", cmd or "" }, callback) end --- Read lines from a Gio input stream -- @tparam Gio.InputStream input_stream The input stream to read from. -- @tparam function line_callback Function that is called with each line -- read, e.g. `line_callback(line_from_stream)`. -- @tparam[opt] function done_callback Function that is called when the -- operation finishes (e.g. due to end of file). -- @tparam[opt=false] boolean close Should the stream be closed after end-of-file? function spawn.read_lines(input_stream, line_callback, done_callback, close) local stream = Gio.DataInputStream.new(input_stream) local function done() if close then stream:close() end if done_callback then protected_call(done_callback) end end local start_read, finish_read start_read = function() stream:read_line_async(GLib.PRIORITY_DEFAULT, nil, finish_read) end finish_read = function(obj, res) local line, length = obj:read_line_finish(res) if type(length) ~= "number" then -- Error print("Error in awful.spawn.read_lines:", tostring(length)) done() elseif end_of_file(line, length) then -- End of file done() else -- Read a line -- This needs tostring() for older lgi versions which returned -- "GLib.Bytes" instead of Lua strings (I guess) protected_call(line_callback, tostring(line)) -- Read the next line start_read() end end start_read() end capi.awesome.connect_signal("spawn::canceled" , spawn.on_snid_cancel ) capi.awesome.connect_signal("spawn::timeout" , spawn.on_snid_cancel ) capi.client.connect_signal ("manage" , spawn.on_snid_callback ) return setmetatable(spawn, { __call = function(_, ...) return spawn.spawn(...) end }) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
czfshine/Don-t-Starve
data/scripts/prefabs/minotaur.lua
1
7717
require "brains/minotaurbrain" require "stategraphs/SGminotaur" local assets= { Asset("ANIM", "anim/rook.zip"), Asset("ANIM", "anim/rook_build.zip"), Asset("ANIM", "anim/rook_rhino.zip"), Asset("SOUND", "sound/chess.fsb"), } local prefabs = { "meat", "minotaurhorn" } local loot = { "meat", "meat", "meat", "meat", "meat", "meat", "meat", "meat", "minotaurhorn", } local SLEEP_DIST_FROMHOME = 20 local SLEEP_DIST_FROMTHREAT = 40 local MAX_CHASEAWAY_DIST = 50 local MAX_TARGET_SHARES = 5 local SHARE_TARGET_DIST = 40 local function ShouldSleep(inst) local homePos = inst.components.knownlocations:GetLocation("home") local myPos = Vector3(inst.Transform:GetWorldPosition() ) if not (homePos and distsq(homePos, myPos) <= SLEEP_DIST_FROMHOME*SLEEP_DIST_FROMHOME) or (inst.components.combat and inst.components.combat.target) or (inst.components.burnable and inst.components.burnable:IsBurning() ) or (inst.components.freezable and inst.components.freezable:IsFrozen() ) then return false end local nearestEnt = GetClosestInstWithTag("character", inst, SLEEP_DIST_FROMTHREAT) return nearestEnt == nil end local function ShouldWake(inst) local homePos = inst.components.knownlocations:GetLocation("home") local myPos = Vector3(inst.Transform:GetWorldPosition() ) if (homePos and distsq(homePos, myPos) > SLEEP_DIST_FROMHOME*SLEEP_DIST_FROMHOME) or (inst.components.combat and inst.components.combat.target) or (inst.components.burnable and inst.components.burnable:IsBurning() ) or (inst.components.freezable and inst.components.freezable:IsFrozen() ) then return true end local nearestEnt = GetClosestInstWithTag("character", inst, SLEEP_DIST_FROMTHREAT) return nearestEnt end local function Retarget(inst) local homePos = inst.components.knownlocations:GetLocation("home") local myPos = Vector3(inst.Transform:GetWorldPosition() ) if (homePos and distsq(homePos, myPos) > 40*40) then return end local newtarget = FindEntity(inst, TUNING.MINOTAUR_TARGET_DIST, function(guy) return (guy:HasTag("character") or guy:HasTag("monster")) and not (inst.components.follower and inst.components.follower.leader == guy) and not guy:HasTag("chess") and inst.components.combat:CanTarget(guy) end) return newtarget end local function KeepTarget(inst, target) if inst.sg and inst.sg:HasStateTag("running") then return true end local homePos = inst.components.knownlocations:GetLocation("home") local myPos = Vector3(inst.Transform:GetWorldPosition() ) return (homePos and distsq(homePos, myPos) < 40*40) end local function OnAttacked(inst, data) local attacker = data and data.attacker if attacker and attacker:HasTag("chess") then return end inst.components.combat:SetTarget(attacker) inst.components.combat:ShareTarget(attacker, SHARE_TARGET_DIST, function(dude) return dude:HasTag("chess") end, MAX_TARGET_SHARES) end local function HitShake() -- :Shake(shakeType, duration, speed, scale) -- TheCamera:Shake("SIDE", 0.2, 0.05, .1) TheCamera:Shake("SIDE", 0.5, 0.05, 0.1) end local function oncollide(inst, other) local v1 = Vector3(inst.Physics:GetVelocity()) --if inst.sg:HasStateTag("busy") or inst.sg:HasStateTag("hit") then -- return --end if other == GetPlayer() then return end if v1:LengthSq() < 42 then return end -- dprint("speed: ", math.sqrt(v1:LengthSq())) HitShake() inst:DoTaskInTime(2*FRAMES, function() if (other and other:HasTag("smashable")) then --other.Physics:SetCollides(false) other.components.health:Kill() elseif other and other.components.health and other.components.health:GetPercent() >= 0 then dprint("----------------HIT!:",other, other.components.health and other.components.health:GetPercent()) SpawnPrefab("collapse_small").Transform:SetPosition(other:GetPosition():Get()) inst.SoundEmitter:PlaySound("dontstarve/creatures/rook/explo") inst.components.combat:DoAttack(other) dprint("_____After HIT") elseif other and other.components.workable and other.components.workable.workleft > 0 then SpawnPrefab("collapse_small").Transform:SetPosition(other:GetPosition():Get()) other.components.workable:Destroy(inst) end end) end local function spawnchest(inst) inst:DoTaskInTime(3, function() inst.SoundEmitter:PlaySound("dontstarve/common/ghost_spawn") local chest = SpawnPrefab("minotaurchest") local pos = inst:GetPosition() chest.Transform:SetPosition(pos.x, 0, pos.z) local fx = SpawnPrefab("statue_transition_2") if fx then fx.Transform:SetPosition(inst:GetPosition():Get()) fx.AnimState:SetScale(1,2,1) end fx = SpawnPrefab("statue_transition") if fx then fx.Transform:SetPosition(inst:GetPosition():Get()) fx.AnimState:SetScale(1,1.5,1) end chest:AddComponent("scenariorunner") chest.components.scenariorunner:SetScript("chest_minotaur") chest.components.scenariorunner:Run() end) end local function MakeMinotaur() local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() local sound = inst.entity:AddSoundEmitter() local shadow = inst.entity:AddDynamicShadow() shadow:SetSize( 5, 3 ) inst.Transform:SetFourFaced() MakeCharacterPhysics(inst, 100, 2.2) inst.Physics:SetCylinder(2.2, 4) inst.Physics:SetCollisionCallback(oncollide) anim:SetBank("rook") anim:SetBuild("rook_rhino") inst:AddComponent("locomotor") inst.components.locomotor.walkspeed = TUNING.MINOTAUR_WALK_SPEED inst.components.locomotor.runspeed = TUNING.MINOTAUR_RUN_SPEED inst:SetStateGraph("SGminotaur") inst:AddTag("monster") inst:AddTag("hostile") inst:AddTag("minotaur") inst:AddTag("epic") local brain = require "brains/minotaurbrain" inst:SetBrain(brain) inst:AddComponent("sleeper") inst.components.sleeper:SetWakeTest(ShouldWake) inst.components.sleeper:SetSleepTest(ShouldSleep) inst.components.sleeper:SetResistance(3) inst:AddComponent("combat") inst.components.combat.hiteffectsymbol = "spring" inst.components.combat:SetAttackPeriod(TUNING.MINOTAUR_ATTACK_PERIOD) inst.components.combat:SetDefaultDamage(TUNING.MINOTAUR_DAMAGE) inst.components.combat:SetRetargetFunction(3, Retarget) inst.components.combat:SetKeepTargetFunction(KeepTarget) inst.components.combat:SetRange(3,4) inst:AddComponent("health") inst.components.health:SetMaxHealth(TUNING.MINOTAUR_HEALTH) inst:ListenForEvent("death", spawnchest) inst:AddComponent("lootdropper") inst.components.lootdropper:SetLoot(loot) inst:AddComponent("inspectable") inst:AddComponent("knownlocations") inst:DoTaskInTime(2*FRAMES, function() inst.components.knownlocations:RememberLocation("home", Vector3(inst.Transform:GetWorldPosition()), true) end) MakeMediumBurnableCharacter(inst, "spring") MakeMediumFreezableCharacter(inst, "spring") inst:ListenForEvent("attacked", OnAttacked) -- inst:AddComponent("debugger") return inst end return Prefab("cave/monsters/minotaur", function() return MakeMinotaur(true) end , assets, prefabs)
gpl-2.0
sigma-random/wireshark
test/lua/gregex.lua
29
8743
-- Tests for GLib Regex functions -- written by Hadriel Kaplan, based on Lrexlib's test suite -- This is a test script for tshark/wireshark. -- This script runs inside tshark/wireshark, so to run it do: -- tshark -r empty.cap -X lua_script:<path_to_testdir>/lua/gregex.lua -X lua_script1:glib -- -- if you have to give addtional paths to find the dependent lua files, -- use the '-X lua_script1:' syntax to add more arguments -- -- available arguments: -- -d<dir> provides path directory for lua include files -- -v verbose mode -- -V very verbose mode -- save args before we do anything else local args = {...} for i,v in ipairs(args) do print(i.." = "..v) end -- save current locale and replace it with C-locale local old_locale = os.setlocale() print("Previous locale was '" .. old_locale .. "', setting it to C-locale now") os.setlocale("C") local function testing(...) print("---- Testing "..tostring(...).." ----") end local count = 0 local function test(name, ...) count = count + 1 io.write("test "..name.."-"..count.."...") if (...) == true then io.write("passed\n") io.flush() else io.write("failed!\n") io.flush() error(name.." test failed!") end end ------------- First test some basic stuff to make sure we're sane ----------- print("Lua version: ".._VERSION) testing("Lrexlib GLib Regex library") local lib = GRegex test("global",_G.GRegex == lib) for name, val in pairs(lib) do print("\t"..name.." = "..type(val)) end test("class",type(lib) == 'table') test("class",type(lib._VERSION) == 'string') test("class",type(lib.find) == 'function') test("class",type(lib.compile_flags) == 'function') test("class",type(lib.match_flags) == 'function') test("class",type(lib.flags) == 'function') test("class",type(lib.gsub) == 'function') test("class",type(lib.gmatch) == 'function') test("class",type(lib.new) == 'function') test("class",type(lib.match) == 'function') test("class",type(lib.split) == 'function') test("class",type(lib.version) == 'function') testing("info and flags") test("typeof",typeof(lib) == 'GRegex') print(lib._VERSION) print("Glib version = "..lib.version()) local function getTSize(t) local c = 0 for k,v in pairs(t) do -- print(k.." = "..v) c = c + 1 end return c end local flags = lib.flags() -- print("size = "..c) -- it's 84 for newer GLib, 61 for older test("flags", getTSize(flags) > 60) test("cflags", getTSize(lib.compile_flags()) > 15) test("eflags", getTSize(lib.match_flags()) > 8) testing("new") local results local function checkFunc(objname,funcname,...) results = { pcall(objname[funcname],...) } if results[1] then return true end -- print("Got this error: '"..tostring(results[2]).."'") return false end test("new", checkFunc(lib,"new",".*")) test("new", checkFunc(lib,"new","")) test("new", checkFunc(lib,"new","(hello|world)")) test("new_err", not checkFunc(lib,"new","*")) test("new_err", not checkFunc(lib,"new")) test("new_err", not checkFunc(lib,"new","(hello|world")) test("new_err", not checkFunc(lib,"new","[0-9")) -- invalid compile flag test("new_err", not checkFunc(lib,"new","[0-9]",flags.PARTIAL)) local val1 = "hello world foo bar" local val2 = "hello wORld FOO bar" local patt = "hello (world) (.*) bar" local rgx = lib.new(patt) local rgx2 = lib.new(patt,flags.CASELESS) testing("typeof") test("typeof",typeof(rgx) == 'GRegex') test("typeof",typeof(rgx2) == 'GRegex') testing("match") test("match", checkFunc(lib,"match", val1,patt, 1, flags.CASELESS) and results[2] == "world" and results[3] == "foo") test("match", checkFunc(lib,"match", val2,patt, 1, flags.CASELESS) and results[2] == "wORld" and results[3] == "FOO") test("match", checkFunc(lib,"match", val1,rgx) and results[2] == "world" and results[3] == "foo") test("match", checkFunc(rgx,"match", rgx,val1) and results[2] == "world" and results[3] == "foo") test("match", checkFunc(rgx2,"match", rgx2,val2, 1) and results[2] == "wORld" and results[3] == "FOO") -- different offset won't match this pattern test("match_err", checkFunc(rgx2,"match", rgx2,val2, 4) and results[2] == nil) -- invalid compile flag test("match_err", not checkFunc(lib,"match", val1,patt, 1, flags.PARTIAL)) -- invalid match flag test("match_err", not checkFunc(rgx,"match", rgx,val1, 1, flags.CASELESS)) testing("find") test("find", checkFunc(lib,"find", val1,patt) and results[2] == 1 and results[3] == val1:len() and results[4] == "world" and results[5] == "foo") test("find", checkFunc(lib,"find", val1,rgx) and results[2] == 1 and results[3] == val1:len() and results[4] == "world" and results[5] == "foo") test("find", checkFunc(rgx,"find", rgx,val1) and results[2] == 1 and results[3] == val1:len() and results[4] == "world" and results[5] == "foo") testing("match") --checkFunc(rgx,"exec", rgx,val1) --print(results[4][3],results[4][4]) test("exec", checkFunc(rgx,"exec", rgx,val1) and results[2] == 1 and results[3] == val1:len() and results[4][1] == 7 and results[4][2] == 11 and results[4][3] == 13 and results[4][4] == 15) print("\n----------------------------------------------------------\n") ------- OK, we're sane, so run all the library's real tests --------- testing("Lrexlib-provided tests") -- we're not using the "real" lib name local GLIBNAME = "GRegex" local isglobal = true do local dir for i = 1, select ("#", ...) do local arg = select (i, ...) --print(arg) if arg:sub(1,2) == "-d" then dir = arg:sub(3) end end dir = dir:gsub("[/\\]+$", "") local path = dir .. "/?.lua;" if package.path:sub(1, #path) ~= path then package.path = path .. package.path end end local luatest = require "luatest" -- returns: number of failures local function test_library (libname, setfile, verbose, really_verbose) if verbose then print (("[lib: %s; file: %s]"):format (libname, setfile)) end local lib = isglobal and _G[libname] or require (libname) local f = require (setfile) local sets = f (libname, isglobal) local n = 0 -- number of failures for _, set in ipairs (sets) do if verbose then print (set.Name or "Unnamed set") end local err = luatest.test_set (set, lib, really_verbose) if verbose then for _,v in ipairs (err) do print ("\nTest " .. v.i) print (" Expected result:\n "..tostring(v)) luatest.print_results (v[1], " ") table.remove(v,1) print ("\n Got:") luatest.print_results (v, " ") end end n = n + #err end if verbose then print "" end return n end local avail_tests = { posix = { lib = "rex_posix", "common_sets", "posix_sets" }, gnu = { lib = "rex_gnu", "common_sets", "emacs_sets", "gnu_sets" }, oniguruma = { lib = "rex_onig", "common_sets", "oniguruma_sets", }, pcre = { lib = "rex_pcre", "common_sets", "pcre_sets", "pcre_sets2", }, glib = { lib = GLIBNAME, "common_sets", "pcre_sets", "pcre_sets2", "glib_sets" }, spencer = { lib = "rex_spencer", "common_sets", "posix_sets", "spencer_sets" }, tre = { lib = "rex_tre", "common_sets", "posix_sets", "spencer_sets", --[["tre_sets"]] }, } do local verbose, really_verbose, tests, nerr = false, false, {}, 0 local dir -- check arguments for i = 1, select ("#", ...) do local arg = select (i, ...) --print(arg) if arg:sub(1,1) == "-" then if arg == "-v" then verbose = true elseif arg == "-V" then verbose = true really_verbose = true elseif arg:sub(1,2) == "-d" then dir = arg:sub(3) end else if avail_tests[arg] then tests[#tests+1] = avail_tests[arg] else error ("invalid argument: [" .. arg .. "]") end end end assert (#tests > 0, "no library specified") -- give priority to libraries located in the specified directory if dir and not isglobal then dir = dir:gsub("[/\\]+$", "") for _, ext in ipairs {"dll", "so", "dylib"} do if package.cpath:match ("%?%." .. ext) then local cpath = dir .. "/?." .. ext .. ";" if package.cpath:sub(1, #cpath) ~= cpath then package.cpath = cpath .. package.cpath end break end end end -- do tests for _, test in ipairs (tests) do package.loaded[test.lib] = nil -- to force-reload the tested library for _, setfile in ipairs (test) do nerr = nerr + test_library (test.lib, setfile, verbose, really_verbose) end end print ("Total number of failures: " .. nerr) assert(nerr == 0, "Test failed!") end print("Resetting locale to: " .. old_locale) os.setlocale(old_locale) print("\n-----------------------------\n") print("All tests passed!\n\n")
gpl-2.0
CrazyEddieTK/Zero-K
scripts/spiderassault.lua
9
5237
include "constants.lua" local base = piece 'base' local torso = piece 'torso' local turret = piece 'turret' local lbarrel = piece 'lbarrel' local lflare = piece 'lflare' local rbarrel = piece 'rbarrel' local rflare = piece 'rflare' local larm = piece 'larm' local rarm = piece 'rarm' local lfrontleg = piece 'lfrontleg' local lfrontleg1 = piece 'lfrontleg1' local rfrontleg = piece 'rfrontleg' local rfrontleg1 = piece 'rfrontleg1' local laftleg = piece 'laftleg' local laftleg1 = piece 'laftleg1' local raftleg = piece 'raftleg' local raftleg1 = piece 'raftleg1' local PACE = 1.4 local SIG_Walk = 1 local SIG_Aim = 2 --constants local PI = math.pi local sa = math.rad(-10) local ma = math.rad(40) local la = math.rad(100) local pause = 440 local forward = 2.2 local backward = 2 local up = 1 local gun = false local smokePiece = {base, barrel} function script.Create() Turn(lfrontleg, y_axis, math.rad(45)) Turn(rfrontleg, y_axis, math.rad(-45)) Turn(laftleg, y_axis, math.rad(-45)) Turn(raftleg, y_axis, math.rad(45)) StartThread(SmokeUnit,smokePiece) end local function RestoreAfterDelay() Sleep(2750) Turn(turret, y_axis, 0, math.rad(90)) WaitForTurn(turret, y_axis) Turn(torso, x_axis, 0, math.rad(90)) end local function Walk() Signal(SIG_Walk) SetSignalMask(SIG_Walk) while (true) do -- Move(base, y_axis, 1.5, 2*up) Turn(lfrontleg, y_axis, 1.5*ma, forward) -- right front forward Turn(lfrontleg, z_axis, -ma/2, up) -- right front up Turn(lfrontleg1, z_axis, -ma/3, up) Turn(laftleg, y_axis, -1.5*ma, backward) -- right back backward Turn(laftleg, z_axis, 0, 6*up) -- right back down Turn(laftleg1, z_axis, 0, up) Turn(rfrontleg, y_axis, sa, backward) -- left front backward Turn(rfrontleg, z_axis, 0, 6*up) -- left front down Turn(rfrontleg1, z_axis, 0, up) Turn(raftleg, y_axis, -sa, forward) -- left back forward Turn(raftleg, z_axis, ma/2, up) -- left back up Turn(raftleg1, z_axis, ma/3, up) Sleep(pause) -- Move(base, y_axis, 0, 4*up) Turn(lfrontleg, y_axis, -sa, backward) -- right front backward Turn(lfrontleg, z_axis, 0, 6*up) -- right front down Turn(lfrontleg1, z_axis, 0, up) Turn(laftleg, y_axis, sa, forward) -- right back forward Turn(laftleg, z_axis, -ma/2, up) -- right back up Turn(laftleg1, z_axis, -ma/3, up) Turn(rfrontleg, y_axis, -1.5*ma, forward) -- left front forward Turn(rfrontleg, z_axis, ma/2, up) -- left front up Turn(rfrontleg1, z_axis, ma/3, up) Turn(raftleg, y_axis, 1.5*ma, backward) -- left back backward Turn(raftleg, z_axis, 0, 6*up) -- left back down Turn(raftleg1, z_axis, 0, up) Sleep(pause) end end local function StopWalk() Signal(SIG_Walk) SetSignalMask(SIG_Walk) Move(base, y_axis, 0, 4*up) Turn(lfrontleg, y_axis, 0) -- right front forward Turn(lfrontleg, z_axis, 0, up) Turn(lfrontleg1, z_axis, 0, up) Turn(laftleg, y_axis, 0) -- right back backward Turn(laftleg, z_axis, 0, up) Turn(laftleg1, z_axis, 0, up) Turn(rfrontleg, y_axis, 0) -- left front backward Turn(rfrontleg, z_axis, 0, up) Turn(rfrontleg1, z_axis, 0, up) Turn(raftleg, y_axis, 0) -- left back forward Turn(raftleg, z_axis, 0, up) Turn(raftleg1, z_axis, 0, up) Turn(lfrontleg, y_axis, math.rad(45), forward) Turn(rfrontleg, y_axis, math.rad(-45), forward) Turn(laftleg, y_axis, math.rad(-45), forward) Turn(raftleg, y_axis, math.rad(45), forward) end function script.StartMoving() StartThread(Walk) end function script.StopMoving() StartThread(StopWalk) end function script.QueryWeapon(num) if gun then return lflare else return rflare end end function script.AimFromWeapon(num) return turret end function script.AimWeapon(num, heading, pitch) Signal(SIG_Aim) SetSignalMask(SIG_Aim) Turn(turret, y_axis, heading, math.rad(180)) -- left-right Turn(torso, x_axis, -pitch, math.rad(270)) --up-down WaitForTurn(turret, y_axis) WaitForTurn(torso, x_axis) StartThread(RestoreAfterDelay) return true end local function recoil() if gun then EmitSfx(lflare, 1024) EmitSfx(lflare, 1025) Move(lbarrel, z_axis, -6) Move(larm, z_axis, -2) Move(lbarrel, z_axis, 0, 3) Move(larm, z_axis, 0, 1) else EmitSfx(rflare, 1024) EmitSfx(rflare, 1025) Move(rbarrel, z_axis, -6) Move(rarm, z_axis, -2) Move(rbarrel, z_axis, 0, 3) Move(rarm, z_axis, 0, 1) end end function script.FireWeapon(num) gun = not gun StartThread(recoil) end function script.BlockShot(num, targetID) if Spring.ValidUnitID(targetID) then local distMult = (Spring.GetUnitSeparation(unitID, targetID) or 0)/350 return GG.OverkillPrevention_CheckBlock(unitID, targetID, 141.1, 30 * distMult, false, false, true) end return false end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= 0.25 then Explode(base, sfxNone) return 1 elseif severity <= 0.50 then Explode(base, sfxNone) Explode(lbarrel, sfxFall + sfxSmoke) Explode(rbarrel, sfxFall + sfxSmoke) return 1 else Explode(base, sfxShatter) Explode(lbarrel, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(rbarrel, sfxFall + sfxSmoke + sfxFire + sfxExplode) return 2 end end
gpl-2.0
blueyed/awesome
lib/wibox/widget/init.lua
2
3025
--------------------------------------------------------------------------- -- @author Uli Schlachter -- @copyright 2010 Uli Schlachter -- @classmod wibox.widget --------------------------------------------------------------------------- local cairo = require("lgi").cairo local hierarchy = require("wibox.hierarchy") local widget = { base = require("wibox.widget.base"); textbox = require("wibox.widget.textbox"); imagebox = require("wibox.widget.imagebox"); background = require("wibox.widget.background"); systray = require("wibox.widget.systray"); textclock = require("wibox.widget.textclock"); progressbar = require("wibox.widget.progressbar"); graph = require("wibox.widget.graph"); checkbox = require("wibox.widget.checkbox"); piechart = require("wibox.widget.piechart"); slider = require("wibox.widget.slider"); calendar = require("wibox.widget.calendar"); } setmetatable(widget, { __call = function(_, args) return widget.base.make_widget_declarative(args) end }) --- Draw a widget directly to a given cairo context. -- This function creates a temporary `wibox.hierarchy` instance and uses that to -- draw the given widget once to the given cairo context. -- @tparam widget wdg A widget to draw -- @tparam cairo_context cr The cairo context to draw the widget on -- @tparam number width The width of the widget -- @tparam number height The height of the widget -- @tparam[opt={dpi=96}] table context The context information to give to the widget. function widget.draw_to_cairo_context(wdg, cr, width, height, context) local function no_op() end context = context or {dpi=96} local h = hierarchy.new(context, wdg, width, height, no_op, no_op, {}) h:draw(context, cr) end --- Create an SVG file showing this widget. -- @tparam widget wdg A widget -- @tparam string path The output file path -- @tparam number width The surface width -- @tparam number height The surface height -- @tparam[opt={dpi=96}] table context The context information to give to the widget. function widget.draw_to_svg_file(wdg, path, width, height, context) local img = cairo.SvgSurface.create(path, width, height) local cr = cairo.Context(img) widget.draw_to_cairo_context(wdg, cr, width, height, context) img:finish() end --- Create a cairo image surface showing this widget. -- @tparam widget wdg A widget -- @tparam number width The surface width -- @tparam number height The surface height -- @param[opt=cairo.Format.ARGB32] format The surface format -- @tparam[opt={dpi=96}] table context The context information to give to the widget. -- @return The cairo surface function widget.draw_to_image_surface(wdg, width, height, format, context) local img = cairo.ImageSurface(format or cairo.Format.ARGB32, width, height) local cr = cairo.Context(img) widget.draw_to_cairo_context(wdg, cr, width, height, context) return img end return widget -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
Jordach/Vox
mods/screwdriver/init.lua
1
2334
local function nextrange(x, max) x = x + 1 if x > max then x = 0 end return x end local ROTATE_FACE = 1 local ROTATE_AXIS = 2 local USES = 200 -- Handles rotation local function screwdriver_handler(itemstack, user, pointed_thing, mode) if pointed_thing.type ~= "node" then return end local pos = pointed_thing.under if minetest.is_protected(pos, user:get_player_name()) then minetest.record_protection_violation(pos, user:get_player_name()) return end local node = minetest.get_node(pos) local ndef = minetest.registered_nodes[node.name] if not ndef or not ndef.paramtype2 == "facedir" or (ndef.drawtype == "nodebox" and not ndef.node_box.type == "fixed") or node.param2 == nil then return end if ndef.can_dig and not ndef.can_dig(pos, user) then return end -- Set param2 local rotationPart = node.param2 % 32 -- get first 4 bits local preservePart = node.param2 - rotationPart local axisdir = math.floor(rotationPart / 4) local rotation = rotationPart - axisdir * 4 if mode == ROTATE_FACE then rotationPart = axisdir * 4 + nextrange(rotation, 3) elseif mode == ROTATE_AXIS then rotationPart = nextrange(axisdir, 5) * 4 end node.param2 = preservePart + rotationPart minetest.swap_node(pos, node) if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535 / (USES - 1)) end return itemstack end -- Screwdriver minetest.register_tool("screwdriver:screwdriver", { description = "Screwdriver (left-click rotates face, right-click rotates axis)", inventory_image = "screwdriver.png", wield_scale = {x=1,y=1,z=3}, on_use = function(itemstack, user, pointed_thing) screwdriver_handler(itemstack, user, pointed_thing, ROTATE_FACE) return itemstack end, on_place = function(itemstack, user, pointed_thing) screwdriver_handler(itemstack, user, pointed_thing, ROTATE_AXIS) return itemstack end, }) minetest.register_craft({ output = "screwdriver:screwdriver", recipe = { {"default:steel_ingot"}, {"group:stick"} } }) minetest.register_alias("screwdriver:screwdriver1", "screwdriver:screwdriver") minetest.register_alias("screwdriver:screwdriver2", "screwdriver:screwdriver") minetest.register_alias("screwdriver:screwdriver3", "screwdriver:screwdriver") minetest.register_alias("screwdriver:screwdriver4", "screwdriver:screwdriver")
lgpl-2.1
AllAboutEE/nodemcu-firmware
app/cjson/lua/cjson/util.lua
170
6837
local json = require "cjson" -- Various common routines used by the Lua CJSON package -- -- Mark Pulford <mark@kyne.com.au> -- Determine with a Lua table can be treated as an array. -- Explicitly returns "not an array" for very sparse arrays. -- Returns: -- -1 Not an array -- 0 Empty table -- >0 Highest index in the array local function is_array(table) local max = 0 local count = 0 for k, v in pairs(table) do if type(k) == "number" then if k > max then max = k end count = count + 1 else return -1 end end if max > count * 2 then return -1 end return max end local serialise_value local function serialise_table(value, indent, depth) local spacing, spacing2, indent2 if indent then spacing = "\n" .. indent spacing2 = spacing .. " " indent2 = indent .. " " else spacing, spacing2, indent2 = " ", " ", false end depth = depth + 1 if depth > 50 then return "Cannot serialise any further: too many nested tables" end local max = is_array(value) local comma = false local fragment = { "{" .. spacing2 } if max > 0 then -- Serialise array for i = 1, max do if comma then table.insert(fragment, "," .. spacing2) end table.insert(fragment, serialise_value(value[i], indent2, depth)) comma = true end elseif max < 0 then -- Serialise table for k, v in pairs(value) do if comma then table.insert(fragment, "," .. spacing2) end table.insert(fragment, ("[%s] = %s"):format(serialise_value(k, indent2, depth), serialise_value(v, indent2, depth))) comma = true end end table.insert(fragment, spacing .. "}") return table.concat(fragment) end function serialise_value(value, indent, depth) if indent == nil then indent = "" end if depth == nil then depth = 0 end if value == json.null then return "json.null" elseif type(value) == "string" then return ("%q"):format(value) elseif type(value) == "nil" or type(value) == "number" or type(value) == "boolean" then return tostring(value) elseif type(value) == "table" then return serialise_table(value, indent, depth) else return "\"<" .. type(value) .. ">\"" end end local function file_load(filename) local file if filename == nil then file = io.stdin else local err file, err = io.open(filename, "rb") if file == nil then error(("Unable to read '%s': %s"):format(filename, err)) end end local data = file:read("*a") if filename ~= nil then file:close() end if data == nil then error("Failed to read " .. filename) end return data end local function file_save(filename, data) local file if filename == nil then file = io.stdout else local err file, err = io.open(filename, "wb") if file == nil then error(("Unable to write '%s': %s"):format(filename, err)) end end file:write(data) if filename ~= nil then file:close() end end local function compare_values(val1, val2) local type1 = type(val1) local type2 = type(val2) if type1 ~= type2 then return false end -- Check for NaN if type1 == "number" and val1 ~= val1 and val2 ~= val2 then return true end if type1 ~= "table" then return val1 == val2 end -- check_keys stores all the keys that must be checked in val2 local check_keys = {} for k, _ in pairs(val1) do check_keys[k] = true end for k, v in pairs(val2) do if not check_keys[k] then return false end if not compare_values(val1[k], val2[k]) then return false end check_keys[k] = nil end for k, _ in pairs(check_keys) do -- Not the same if any keys from val1 were not found in val2 return false end return true end local test_count_pass = 0 local test_count_total = 0 local function run_test_summary() return test_count_pass, test_count_total end local function run_test(testname, func, input, should_work, output) local function status_line(name, status, value) local statusmap = { [true] = ":success", [false] = ":error" } if status ~= nil then name = name .. statusmap[status] end print(("[%s] %s"):format(name, serialise_value(value, false))) end local result = { pcall(func, unpack(input)) } local success = table.remove(result, 1) local correct = false if success == should_work and compare_values(result, output) then correct = true test_count_pass = test_count_pass + 1 end test_count_total = test_count_total + 1 local teststatus = { [true] = "PASS", [false] = "FAIL" } print(("==> Test [%d] %s: %s"):format(test_count_total, testname, teststatus[correct])) status_line("Input", nil, input) if not correct then status_line("Expected", should_work, output) end status_line("Received", success, result) print() return correct, result end local function run_test_group(tests) local function run_helper(name, func, input) if type(name) == "string" and #name > 0 then print("==> " .. name) end -- Not a protected call, these functions should never generate errors. func(unpack(input or {})) print() end for _, v in ipairs(tests) do -- Run the helper if "should_work" is missing if v[4] == nil then run_helper(unpack(v)) else run_test(unpack(v)) end end end -- Run a Lua script in a separate environment local function run_script(script, env) local env = env or {} local func -- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists if _G.setfenv then func = loadstring(script) if func then setfenv(func, env) end else func = load(script, nil, nil, env) end if func == nil then error("Invalid syntax.") end func() return env end -- Export functions return { serialise_value = serialise_value, file_load = file_load, file_save = file_save, compare_values = compare_values, run_test_summary = run_test_summary, run_test = run_test, run_test_group = run_test_group, run_script = run_script } -- vi:ai et sw=4 ts=4:
mit
CrazyEddieTK/Zero-K
gamedata/modularcomms/weapons/aamissile.lua
5
1426
local name = "commweapon_aamissile" local weaponDef = { name = [[AA Missile]], areaOfEffect = 48, canattackground = false, cegTag = [[missiletrailblue]], craterBoost = 1, craterMult = 2, cylinderTargeting = 1, customParams = { slot = [[5]], muzzleEffectFire = [[custom:CRASHMUZZLE]], onlyTargetCategory = [[FIXEDWING GUNSHIP]], light_color = [[0.5 0.6 0.6]], light_radius = 380, }, damage = { default = 12, planes = 120, subs = 6, }, explosionGenerator = [[custom:FLASH2]], fireStarter = 70, flightTime = 3, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 2, model = [[wep_m_fury.s3o]], noSelfDamage = true, range = 950, reloadtime = 1, smokeTrail = true, soundHit = [[weapon/missile/rocket_hit]], soundStart = [[weapon/missile/missile_fire7]], startVelocity = 650, texture2 = [[AAsmoketrail]], tolerance = 9000, tracks = true, turnRate = 63000, turret = true, weaponAcceleration = 141, weaponType = [[MissileLauncher]], weaponVelocity = 850, } return name, weaponDef
gpl-2.0
ranisalt/forgottenserver
data/npc/lib/npcsystem/npchandler.lua
6
21885
-- Advanced NPC System by Jiddo if not NpcHandler then -- Constant talkdelay behaviors. TALKDELAY_NONE = 0 -- No talkdelay. Npc will reply immedeatly. TALKDELAY_ONTHINK = 1 -- Talkdelay handled through the onThink callback function. (Default) TALKDELAY_EVENT = 2 -- Not yet implemented -- Currently applied talkdelay behavior. TALKDELAY_ONTHINK is default. NPCHANDLER_TALKDELAY = TALKDELAY_ONTHINK -- Constant indexes for defining default messages. MESSAGE_GREET = 1 -- When the player greets the npc. MESSAGE_FAREWELL = 2 -- When the player unGreets the npc. MESSAGE_BUY = 3 -- When the npc asks the player if he wants to buy something. MESSAGE_ONBUY = 4 -- When the player successfully buys something via talk. MESSAGE_BOUGHT = 5 -- When the player bought something through the shop window. MESSAGE_SELL = 6 -- When the npc asks the player if he wants to sell something. MESSAGE_ONSELL = 7 -- When the player successfully sells something via talk. MESSAGE_SOLD = 8 -- When the player sold something through the shop window. MESSAGE_MISSINGMONEY = 9 -- When the player does not have enough money. MESSAGE_NEEDMONEY = 10 -- Same as above, used for shop window. MESSAGE_MISSINGITEM = 11 -- When the player is trying to sell an item he does not have. MESSAGE_NEEDITEM = 12 -- Same as above, used for shop window. MESSAGE_NEEDSPACE = 13 -- When the player don't have any space to buy an item MESSAGE_NEEDMORESPACE = 14 -- When the player has some space to buy an item, but not enough space MESSAGE_IDLETIMEOUT = 15 -- When the player has been idle for longer then idleTime allows. MESSAGE_WALKAWAY = 16 -- When the player walks out of the talkRadius of the npc. MESSAGE_DECLINE = 17 -- When the player says no to something. MESSAGE_SENDTRADE = 18 -- When the npc sends the trade window to the player MESSAGE_NOSHOP = 19 -- When the npc's shop is requested but he doesn't have any MESSAGE_ONCLOSESHOP = 20 -- When the player closes the npc's shop window MESSAGE_ALREADYFOCUSED = 21 -- When the player already has the focus of this npc. MESSAGE_WALKAWAY_MALE = 22 -- When a male player walks out of the talkRadius of the npc. MESSAGE_WALKAWAY_FEMALE = 23 -- When a female player walks out of the talkRadius of the npc. -- Constant indexes for callback functions. These are also used for module callback ids. CALLBACK_CREATURE_APPEAR = 1 CALLBACK_CREATURE_DISAPPEAR = 2 CALLBACK_CREATURE_SAY = 3 CALLBACK_ONTHINK = 4 CALLBACK_GREET = 5 CALLBACK_FAREWELL = 6 CALLBACK_MESSAGE_DEFAULT = 7 CALLBACK_PLAYER_ENDTRADE = 8 CALLBACK_PLAYER_CLOSECHANNEL = 9 CALLBACK_ONBUY = 10 CALLBACK_ONSELL = 11 CALLBACK_ONADDFOCUS = 18 CALLBACK_ONRELEASEFOCUS = 19 CALLBACK_ONTRADEREQUEST = 20 -- Addidional module callback ids CALLBACK_MODULE_INIT = 12 CALLBACK_MODULE_RESET = 13 -- Constant strings defining the keywords to replace in the default messages. TAG_PLAYERNAME = "|PLAYERNAME|" TAG_ITEMCOUNT = "|ITEMCOUNT|" TAG_TOTALCOST = "|TOTALCOST|" TAG_ITEMNAME = "|ITEMNAME|" NpcHandler = { keywordHandler = nil, focuses = nil, talkStart = nil, idleTime = 120, talkRadius = 3, talkDelayTime = 1, -- Seconds to delay outgoing messages. talkDelay = nil, callbackFunctions = nil, modules = nil, shopItems = nil, -- They must be here since ShopModule uses 'static' functions eventSay = nil, eventDelayedSay = nil, topic = nil, messages = { -- These are the default replies of all npcs. They can/should be changed individually for each npc. [MESSAGE_GREET] = "Greetings, |PLAYERNAME|.", [MESSAGE_FAREWELL] = "Good bye, |PLAYERNAME|.", [MESSAGE_BUY] = "Do you want to buy |ITEMCOUNT| |ITEMNAME| for |TOTALCOST| gold coins?", [MESSAGE_ONBUY] = "Here you are.", [MESSAGE_BOUGHT] = "Bought |ITEMCOUNT|x |ITEMNAME| for |TOTALCOST| gold.", [MESSAGE_SELL] = "Do you want to sell |ITEMCOUNT| |ITEMNAME| for |TOTALCOST| gold coins?", [MESSAGE_ONSELL] = "Here you are, |TOTALCOST| gold.", [MESSAGE_SOLD] = "Sold |ITEMCOUNT|x |ITEMNAME| for |TOTALCOST| gold.", [MESSAGE_MISSINGMONEY] = "You don't have enough money.", [MESSAGE_NEEDMONEY] = "You don't have enough money.", [MESSAGE_MISSINGITEM] = "You don't have so many.", [MESSAGE_NEEDITEM] = "You do not have this object.", [MESSAGE_NEEDSPACE] = "You do not have enough capacity.", [MESSAGE_NEEDMORESPACE] = "You do not have enough capacity for all items.", [MESSAGE_IDLETIMEOUT] = "Good bye.", [MESSAGE_WALKAWAY] = "Good bye.", [MESSAGE_DECLINE] = "Then not.", [MESSAGE_SENDTRADE] = "Of course, just browse through my wares.", [MESSAGE_NOSHOP] = "Sorry, I'm not offering anything.", [MESSAGE_ONCLOSESHOP] = "Thank you, come back whenever you're in need of something else.", [MESSAGE_ALREADYFOCUSED] = "|PLAYERNAME|, I am already talking to you.", [MESSAGE_WALKAWAY_MALE] = "Good bye.", [MESSAGE_WALKAWAY_FEMALE] = "Good bye." } } -- Creates a new NpcHandler with an empty callbackFunction stack. function NpcHandler:new(keywordHandler) local obj = {} obj.callbackFunctions = {} obj.modules = {} obj.eventSay = {} obj.eventDelayedSay = {} obj.topic = {} obj.focuses = {} obj.talkStart = {} obj.talkDelay = {} obj.keywordHandler = keywordHandler obj.messages = {} obj.shopItems = {} setmetatable(obj.messages, self.messages) self.messages.__index = self.messages setmetatable(obj, self) self.__index = self return obj end -- Re-defines the maximum idle time allowed for a player when talking to this npc. function NpcHandler:setMaxIdleTime(newTime) self.idleTime = newTime end -- Attaches a new keyword handler to this npchandler function NpcHandler:setKeywordHandler(newHandler) self.keywordHandler = newHandler end -- Function used to change the focus of this npc. function NpcHandler:addFocus(newFocus) if self:isFocused(newFocus) then return end self.focuses[#self.focuses + 1] = newFocus self.topic[newFocus] = 0 local callback = self:getCallback(CALLBACK_ONADDFOCUS) if not callback or callback(newFocus) then self:processModuleCallback(CALLBACK_ONADDFOCUS, newFocus) end self:updateFocus() end -- Function used to verify if npc is focused to certain player function NpcHandler:isFocused(focus) for k, v in pairs(self.focuses) do if v == focus then return true end end return false end -- This function should be called on each onThink and makes sure the npc faces the player it is talking to. -- Should also be called whenever a new player is focused. function NpcHandler:updateFocus() for pos, focus in pairs(self.focuses) do if focus then doNpcSetCreatureFocus(focus) return end end doNpcSetCreatureFocus(0) end -- Used when the npc should un-focus the player. function NpcHandler:releaseFocus(focus) if shop_cost[focus] then shop_amount[focus] = nil shop_cost[focus] = nil shop_rlname[focus] = nil shop_itemid[focus] = nil shop_container[focus] = nil shop_npcuid[focus] = nil shop_eventtype[focus] = nil shop_subtype[focus] = nil shop_destination[focus] = nil shop_premium[focus] = nil end if self.eventDelayedSay[focus] then self:cancelNPCTalk(self.eventDelayedSay[focus]) end if not self:isFocused(focus) then return end local pos = nil for k, v in pairs(self.focuses) do if v == focus then pos = k end end self.focuses[pos] = nil self.eventSay[focus] = nil self.eventDelayedSay[focus] = nil self.talkStart[focus] = nil self.topic[focus] = nil local callback = self:getCallback(CALLBACK_ONRELEASEFOCUS) if not callback or callback(focus) then self:processModuleCallback(CALLBACK_ONRELEASEFOCUS, focus) end if Player(focus) then closeShopWindow(focus) --Even if it can not exist, we need to prevent it. self:updateFocus() end end -- Returns the callback function with the specified id or nil if no such callback function exists. function NpcHandler:getCallback(id) local ret = nil if self.callbackFunctions then ret = self.callbackFunctions[id] end return ret end -- Changes the callback function for the given id to callback. function NpcHandler:setCallback(id, callback) if self.callbackFunctions then self.callbackFunctions[id] = callback end end -- Adds a module to this npchandler and inits it. function NpcHandler:addModule(module) if self.modules then self.modules[#self.modules + 1] = module module:init(self) end end -- Calls the callback function represented by id for all modules added to this npchandler with the given arguments. function NpcHandler:processModuleCallback(id, ...) local ret = true for i, module in pairs(self.modules) do local tmpRet = true if id == CALLBACK_CREATURE_APPEAR and module.callbackOnCreatureAppear then tmpRet = module:callbackOnCreatureAppear(...) elseif id == CALLBACK_CREATURE_DISAPPEAR and module.callbackOnCreatureDisappear then tmpRet = module:callbackOnCreatureDisappear(...) elseif id == CALLBACK_CREATURE_SAY and module.callbackOnCreatureSay then tmpRet = module:callbackOnCreatureSay(...) elseif id == CALLBACK_PLAYER_ENDTRADE and module.callbackOnPlayerEndTrade then tmpRet = module:callbackOnPlayerEndTrade(...) elseif id == CALLBACK_PLAYER_CLOSECHANNEL and module.callbackOnPlayerCloseChannel then tmpRet = module:callbackOnPlayerCloseChannel(...) elseif id == CALLBACK_ONBUY and module.callbackOnBuy then tmpRet = module:callbackOnBuy(...) elseif id == CALLBACK_ONSELL and module.callbackOnSell then tmpRet = module:callbackOnSell(...) elseif id == CALLBACK_ONTRADEREQUEST and module.callbackOnTradeRequest then tmpRet = module:callbackOnTradeRequest(...) elseif id == CALLBACK_ONADDFOCUS and module.callbackOnAddFocus then tmpRet = module:callbackOnAddFocus(...) elseif id == CALLBACK_ONRELEASEFOCUS and module.callbackOnReleaseFocus then tmpRet = module:callbackOnReleaseFocus(...) elseif id == CALLBACK_ONTHINK and module.callbackOnThink then tmpRet = module:callbackOnThink(...) elseif id == CALLBACK_GREET and module.callbackOnGreet then tmpRet = module:callbackOnGreet(...) elseif id == CALLBACK_FAREWELL and module.callbackOnFarewell then tmpRet = module:callbackOnFarewell(...) elseif id == CALLBACK_MESSAGE_DEFAULT and module.callbackOnMessageDefault then tmpRet = module:callbackOnMessageDefault(...) elseif id == CALLBACK_MODULE_RESET and module.callbackOnModuleReset then tmpRet = module:callbackOnModuleReset(...) end if not tmpRet then ret = false break end end return ret end -- Returns the message represented by id. function NpcHandler:getMessage(id) local ret = nil if self.messages then ret = self.messages[id] end return ret end -- Changes the default response message with the specified id to newMessage. function NpcHandler:setMessage(id, newMessage) if self.messages then self.messages[id] = newMessage end end -- Translates all message tags found in msg using parseInfo function NpcHandler:parseMessage(msg, parseInfo) local ret = msg for search, replace in pairs(parseInfo) do ret = string.gsub(ret, search, replace) end return ret end -- Makes sure the npc un-focuses the currently focused player function NpcHandler:unGreet(cid) if not self:isFocused(cid) then return end local callback = self:getCallback(CALLBACK_FAREWELL) if not callback or callback(cid) then if self:processModuleCallback(CALLBACK_FAREWELL) then local msg = self:getMessage(MESSAGE_FAREWELL) local player = Player(cid) local playerName = player and player:getName() or -1 local parseInfo = { [TAG_PLAYERNAME] = playerName } self:resetNpc(cid) msg = self:parseMessage(msg, parseInfo) self:say(msg, cid, true) self:releaseFocus(cid) end end end -- Greets a new player. function NpcHandler:greet(cid) if cid ~= 0 then local callback = self:getCallback(CALLBACK_GREET) if not callback or callback(cid) then if self:processModuleCallback(CALLBACK_GREET, cid) then local msg = self:getMessage(MESSAGE_GREET) local player = Player(cid) local playerName = player and player:getName() or -1 local parseInfo = { [TAG_PLAYERNAME] = playerName } msg = self:parseMessage(msg, parseInfo) self:say(msg, cid, true) else return end else return end end self:addFocus(cid) end -- Handles onCreatureAppear events. If you with to handle this yourself, please use the CALLBACK_CREATURE_APPEAR callback. function NpcHandler:onCreatureAppear(creature) local cid = creature:getId() if cid == getNpcCid() and next(self.shopItems) then local npc = Npc() local speechBubble = npc:getSpeechBubble() if speechBubble == SPEECHBUBBLE_QUEST then npc:setSpeechBubble(SPEECHBUBBLE_QUESTTRADER) else npc:setSpeechBubble(SPEECHBUBBLE_TRADE) end end local callback = self:getCallback(CALLBACK_CREATURE_APPEAR) if not callback or callback(cid) then if self:processModuleCallback(CALLBACK_CREATURE_APPEAR, cid) then -- end end end -- Handles onCreatureDisappear events. If you with to handle this yourself, please use the CALLBACK_CREATURE_DISAPPEAR callback. function NpcHandler:onCreatureDisappear(creature) local cid = creature:getId() if getNpcCid() == cid then return end local callback = self:getCallback(CALLBACK_CREATURE_DISAPPEAR) if not callback or callback(cid) then if self:processModuleCallback(CALLBACK_CREATURE_DISAPPEAR, cid) then if self:isFocused(cid) then self:unGreet(cid) end end end end -- Handles onCreatureSay events. If you with to handle this yourself, please use the CALLBACK_CREATURE_SAY callback. function NpcHandler:onCreatureSay(creature, msgtype, msg) local cid = creature:getId() local callback = self:getCallback(CALLBACK_CREATURE_SAY) if not callback or callback(cid, msgtype, msg) then if self:processModuleCallback(CALLBACK_CREATURE_SAY, cid, msgtype, msg) then if not self:isInRange(cid) then return end if self.keywordHandler then if self:isFocused(cid) and msgtype == TALKTYPE_PRIVATE_PN or not self:isFocused(cid) then local ret = self.keywordHandler:processMessage(cid, msg) if not ret then local callback = self:getCallback(CALLBACK_MESSAGE_DEFAULT) if callback and callback(cid, msgtype, msg) then self.talkStart[cid] = os.time() end else self.talkStart[cid] = os.time() end end end end end end -- Handles onPlayerEndTrade events. If you wish to handle this yourself, use the CALLBACK_PLAYER_ENDTRADE callback. function NpcHandler:onPlayerEndTrade(creature) local cid = creature:getId() local callback = self:getCallback(CALLBACK_PLAYER_ENDTRADE) if not callback or callback(cid) then if self:processModuleCallback(CALLBACK_PLAYER_ENDTRADE, cid, msgtype, msg) then if self:isFocused(cid) then local player = Player(cid) local playerName = player and player:getName() or -1 local parseInfo = { [TAG_PLAYERNAME] = playerName } local msg = self:parseMessage(self:getMessage(MESSAGE_ONCLOSESHOP), parseInfo) self:say(msg, cid) end end end end -- Handles onPlayerCloseChannel events. If you wish to handle this yourself, use the CALLBACK_PLAYER_CLOSECHANNEL callback. function NpcHandler:onPlayerCloseChannel(creature) local cid = creature:getId() local callback = self:getCallback(CALLBACK_PLAYER_CLOSECHANNEL) if not callback or callback(cid) then if self:processModuleCallback(CALLBACK_PLAYER_CLOSECHANNEL, cid, msgtype, msg) then if self:isFocused(cid) then self:unGreet(cid) end end end end -- Handles onBuy events. If you wish to handle this yourself, use the CALLBACK_ONBUY callback. function NpcHandler:onBuy(creature, itemid, subType, amount, ignoreCap, inBackpacks) local cid = creature:getId() local callback = self:getCallback(CALLBACK_ONBUY) if not callback or callback(cid, itemid, subType, amount, ignoreCap, inBackpacks) then if self:processModuleCallback(CALLBACK_ONBUY, cid, itemid, subType, amount, ignoreCap, inBackpacks) then -- end end end -- Handles onSell events. If you wish to handle this yourself, use the CALLBACK_ONSELL callback. function NpcHandler:onSell(creature, itemid, subType, amount, ignoreCap, inBackpacks) local cid = creature:getId() local callback = self:getCallback(CALLBACK_ONSELL) if not callback or callback(cid, itemid, subType, amount, ignoreCap, inBackpacks) then if self:processModuleCallback(CALLBACK_ONSELL, cid, itemid, subType, amount, ignoreCap, inBackpacks) then -- end end end -- Handles onTradeRequest events. If you wish to handle this yourself, use the CALLBACK_ONTRADEREQUEST callback. function NpcHandler:onTradeRequest(cid) local callback = self:getCallback(CALLBACK_ONTRADEREQUEST) if not callback or callback(cid) then if self:processModuleCallback(CALLBACK_ONTRADEREQUEST, cid) then return true end end return false end -- Handles onThink events. If you wish to handle this yourself, please use the CALLBACK_ONTHINK callback. function NpcHandler:onThink() local callback = self:getCallback(CALLBACK_ONTHINK) if not callback or callback() then if NPCHANDLER_TALKDELAY == TALKDELAY_ONTHINK then for cid, talkDelay in pairs(self.talkDelay) do if talkDelay.time and talkDelay.message and os.time() >= talkDelay.time then selfSay(talkDelay.message, cid, talkDelay.publicize and true or false) self.talkDelay[cid] = nil end end end if self:processModuleCallback(CALLBACK_ONTHINK) then for pos, focus in pairs(self.focuses) do if focus then if not self:isInRange(focus) then self:onWalkAway(focus) elseif self.talkStart[focus] and (os.time() - self.talkStart[focus]) > self.idleTime then self:unGreet(focus) else self:updateFocus() end end end end end end -- Tries to greet the player with the given cid. function NpcHandler:onGreet(cid) if self:isInRange(cid) then if not self:isFocused(cid) then self:greet(cid) return end end end -- Simply calls the underlying unGreet function. function NpcHandler:onFarewell(cid) self:unGreet(cid) end -- Should be called on this npc's focus if the distance to focus is greater then talkRadius. function NpcHandler:onWalkAway(cid) if self:isFocused(cid) then local callback = self:getCallback(CALLBACK_CREATURE_DISAPPEAR) if not callback or callback(cid) then if self:processModuleCallback(CALLBACK_CREATURE_DISAPPEAR, cid) then local msg = self:getMessage(MESSAGE_WALKAWAY) local player = Player(cid) local playerName = player and player:getName() or -1 local playerSex = player and player:getSex() or 0 local parseInfo = { [TAG_PLAYERNAME] = playerName } local message = self:parseMessage(msg, parseInfo) local msg_male = self:getMessage(MESSAGE_WALKAWAY_MALE) local message_male = self:parseMessage(msg_male, parseInfo) local msg_female = self:getMessage(MESSAGE_WALKAWAY_FEMALE) local message_female = self:parseMessage(msg_female, parseInfo) if message_female ~= message_male then if playerSex == PLAYERSEX_FEMALE then selfSay(message_female) else selfSay(message_male) end elseif message ~= "" then selfSay(message) end self:resetNpc(cid) self:releaseFocus(cid) end end end end -- Returns true if cid is within the talkRadius of this npc. function NpcHandler:isInRange(cid) local distance = Player(cid) and getDistanceTo(cid) or -1 if distance == -1 then return false end return distance <= self.talkRadius end -- Resets the npc into its initial state (in regard of the keywordhandler). -- All modules are also receiving a reset call through their callbackOnModuleReset function. function NpcHandler:resetNpc(cid) if self:processModuleCallback(CALLBACK_MODULE_RESET) then self.keywordHandler:reset(cid) end end function NpcHandler:cancelNPCTalk(events) for aux = 1, #events do stopEvent(events[aux].event) end events = nil end function NpcHandler:doNPCTalkALot(msgs, interval, pcid) if self.eventDelayedSay[pcid] then self:cancelNPCTalk(self.eventDelayedSay[pcid]) end self.eventDelayedSay[pcid] = {} local ret = {} for aux = 1, #msgs do self.eventDelayedSay[pcid][aux] = {} doCreatureSayWithDelay(getNpcCid(), msgs[aux], TALKTYPE_PRIVATE_NP, ((aux - 1) * (interval or 4000)) + 700, self.eventDelayedSay[pcid][aux], pcid) ret[#ret + 1] = self.eventDelayedSay[pcid][aux] end return(ret) end -- Makes the npc represented by this instance of NpcHandler say something. -- This implements the currently set type of talkdelay. -- shallDelay is a boolean value. If it is false, the message is not delayed. Default value is true. function NpcHandler:say(message, focus, publicize, shallDelay, delay) if type(message) == "table" then return self:doNPCTalkALot(message, delay or 6000, focus) end if self.eventDelayedSay[focus] then self:cancelNPCTalk(self.eventDelayedSay[focus]) end local shallDelay = not shallDelay and true or shallDelay if NPCHANDLER_TALKDELAY == TALKDELAY_NONE or not shallDelay then selfSay(message, focus, publicize and true or false) return end stopEvent(self.eventSay[focus]) self.eventSay[focus] = addEvent(function(npcId, message, focusId) local npc = Npc(npcId) if not npc then return end local player = Player(focusId) if player then npc:say(message, TALKTYPE_PRIVATE_NP, false, player, npc:getPosition()) end end, self.talkDelayTime * 1000, Npc():getId(), message, focus) end end
gpl-2.0
gaoch023/OpenRA
lua/stacktraceplus.lua
59
12006
-- tables local _G = _G local string, io, debug, coroutine = string, io, debug, coroutine -- functions local tostring, print, require = tostring, print, require local next, assert = next, assert local pcall, type, pairs, ipairs = pcall, type, pairs, ipairs local error = error assert(debug, "debug table must be available at this point") local io_open = io.open local string_gmatch = string.gmatch local string_sub = string.sub local table_concat = table.concat local _M = { max_tb_output_len = 70 -- controls the maximum length of the 'stringified' table before cutting with ' (more...)' } -- this tables should be weak so the elements in them won't become uncollectable local m_known_tables = { [_G] = "_G (global table)" } local function add_known_module(name, desc) local ok, mod = pcall(require, name) if ok then m_known_tables[mod] = desc end end add_known_module("string", "string module") add_known_module("io", "io module") add_known_module("os", "os module") add_known_module("table", "table module") add_known_module("math", "math module") add_known_module("package", "package module") add_known_module("debug", "debug module") add_known_module("coroutine", "coroutine module") -- lua5.2 add_known_module("bit32", "bit32 module") -- luajit add_known_module("bit", "bit module") add_known_module("jit", "jit module") local m_user_known_tables = {} local m_known_functions = {} for _, name in ipairs{ -- Lua 5.2, 5.1 "assert", "collectgarbage", "dofile", "error", "getmetatable", "ipairs", "load", "loadfile", "next", "pairs", "pcall", "print", "rawequal", "rawget", "rawlen", "rawset", "require", "select", "setmetatable", "tonumber", "tostring", "type", "xpcall", -- Lua 5.1 "gcinfo", "getfenv", "loadstring", "module", "newproxy", "setfenv", "unpack", -- TODO: add table.* etc functions } do if _G[name] then m_known_functions[_G[name]] = name end end local m_user_known_functions = {} local function safe_tostring (value) local ok, err = pcall(tostring, value) if ok then return err else return ("<failed to get printable value>: '%s'"):format(err) end end -- Private: -- Parses a line, looking for possible function definitions (in a very naïve way) -- Returns '(anonymous)' if no function name was found in the line local function ParseLine(line) assert(type(line) == "string") --print(line) local match = line:match("^%s*function%s+(%w+)") if match then --print("+++++++++++++function", match) return match end match = line:match("^%s*local%s+function%s+(%w+)") if match then --print("++++++++++++local", match) return match end match = line:match("^%s*local%s+(%w+)%s+=%s+function") if match then --print("++++++++++++local func", match) return match end match = line:match("%s*function%s*%(") -- this is an anonymous function if match then --print("+++++++++++++function2", match) return "(anonymous)" end return "(anonymous)" end -- Private: -- Tries to guess a function's name when the debug info structure does not have it. -- It parses either the file or the string where the function is defined. -- Returns '?' if the line where the function is defined is not found local function GuessFunctionName(info) --print("guessing function name") if type(info.source) == "string" and info.source:sub(1,1) == "@" then local file, err = io_open(info.source:sub(2), "r") if not file then print("file not found: "..tostring(err)) -- whoops! return "?" end local line for i = 1, info.linedefined do line = file:read("*l") end if not line then print("line not found") -- whoops! return "?" end return ParseLine(line) else local line local lineNumber = 0 for l in string_gmatch(info.source, "([^\n]+)\n-") do lineNumber = lineNumber + 1 if lineNumber == info.linedefined then line = l break end end if not line then print("line not found") -- whoops! return "?" end return ParseLine(line) end end --- -- Dumper instances are used to analyze stacks and collect its information. -- local Dumper = {} Dumper.new = function(thread) local t = { lines = {} } for k,v in pairs(Dumper) do t[k] = v end t.dumping_same_thread = (thread == coroutine.running()) -- if a thread was supplied, bind it to debug.info and debug.get -- we also need to skip this additional level we are introducing in the callstack (only if we are running -- in the same thread we're inspecting) if type(thread) == "thread" then t.getinfo = function(level, what) if t.dumping_same_thread and type(level) == "number" then level = level + 1 end return debug.getinfo(thread, level, what) end t.getlocal = function(level, loc) if t.dumping_same_thread then level = level + 1 end return debug.getlocal(thread, level, loc) end else t.getinfo = debug.getinfo t.getlocal = debug.getlocal end return t end -- helpers for collecting strings to be used when assembling the final trace function Dumper:add (text) self.lines[#self.lines + 1] = text end function Dumper:add_f (fmt, ...) self:add(fmt:format(...)) end function Dumper:concat_lines () return table_concat(self.lines) end --- -- Private: -- Iterates over the local variables of a given function. -- -- @param level The stack level where the function is. -- function Dumper:DumpLocals (level) local prefix = "\t " local i = 1 if self.dumping_same_thread then level = level + 1 end local name, value = self.getlocal(level, i) if not name then return end self:add("\tLocal variables:\r\n") while name do if type(value) == "number" then self:add_f("%s%s = number: %g\r\n", prefix, name, value) elseif type(value) == "boolean" then self:add_f("%s%s = boolean: %s\r\n", prefix, name, tostring(value)) elseif type(value) == "string" then self:add_f("%s%s = string: %q\r\n", prefix, name, value) elseif type(value) == "userdata" then self:add_f("%s%s = %s\r\n", prefix, name, safe_tostring(value)) elseif type(value) == "nil" then self:add_f("%s%s = nil\r\n", prefix, name) elseif type(value) == "table" then if m_known_tables[value] then self:add_f("%s%s = %s\r\n", prefix, name, m_known_tables[value]) elseif m_user_known_tables[value] then self:add_f("%s%s = %s\r\n", prefix, name, m_user_known_tables[value]) else local txt = "{" for k,v in pairs(value) do txt = txt..safe_tostring(k)..":"..safe_tostring(v) if #txt > _M.max_tb_output_len then txt = txt.." (more...)" break end if next(value, k) then txt = txt..", " end end self:add_f("%s%s = %s %s\r\n", prefix, name, safe_tostring(value), txt.."}") end elseif type(value) == "function" then local info = self.getinfo(value, "nS") local fun_name = info.name or m_known_functions[value] or m_user_known_functions[value] if info.what == "C" then self:add_f("%s%s = C %s\r\n", prefix, name, (fun_name and ("function: " .. fun_name) or tostring(value))) else local source = info.short_src if source:sub(2,7) == "string" then source = source:sub(9) end --for k,v in pairs(info) do print(k,v) end fun_name = fun_name or GuessFunctionName(info) self:add_f("%s%s = Lua function '%s' (defined at line %d of chunk %s)\r\n", prefix, name, fun_name, info.linedefined, source) end elseif type(value) == "thread" then self:add_f("%sthread %q = %s\r\n", prefix, name, tostring(value)) end i = i + 1 name, value = self.getlocal(level, i) end end --- -- Public: -- Collects a detailed stack trace, dumping locals, resolving function names when they're not available, etc. -- This function is suitable to be used as an error handler with pcall or xpcall -- -- @param thread An optional thread whose stack is to be inspected (defaul is the current thread) -- @param message An optional error string or object. -- @param level An optional number telling at which level to start the traceback (default is 1) -- -- Returns a string with the stack trace and a string with the original error. -- function _M.stacktrace(thread, message, level) if type(thread) ~= "thread" then -- shift parameters left thread, message, level = nil, thread, message end thread = thread or coroutine.running() level = level or 1 local dumper = Dumper.new(thread) local original_error if type(message) == "table" then dumper:add("an error object {\r\n") local first = true for k,v in pairs(message) do if first then dumper:add(" ") first = false else dumper:add(",\r\n ") end dumper:add(safe_tostring(k)) dumper:add(": ") dumper:add(safe_tostring(v)) end dumper:add("\r\n}") original_error = dumper:concat_lines() elseif type(message) == "string" then dumper:add(message) original_error = message end dumper:add("\r\n") dumper:add[[ Stack Traceback =============== ]] --print(error_message) local level_to_show = level if dumper.dumping_same_thread then level = level + 1 end local info = dumper.getinfo(level, "nSlf") while info do if info.what == "main" then if string_sub(info.source, 1, 1) == "@" then dumper:add_f("(%d) main chunk of file '%s' at line %d\r\n", level_to_show, string_sub(info.source, 2), info.currentline) else dumper:add_f("(%d) main chunk of %s at line %d\r\n", level_to_show, info.short_src, info.currentline) end elseif info.what == "C" then --print(info.namewhat, info.name) --for k,v in pairs(info) do print(k,v, type(v)) end local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name or tostring(info.func) dumper:add_f("(%d) %s C function '%s'\r\n", level_to_show, info.namewhat, function_name) --dumper:add_f("%s%s = C %s\r\n", prefix, name, (m_known_functions[value] and ("function: " .. m_known_functions[value]) or tostring(value))) elseif info.what == "tail" then --print("tail") --for k,v in pairs(info) do print(k,v, type(v)) end--print(info.namewhat, info.name) dumper:add_f("(%d) tail call\r\n", level_to_show) dumper:DumpLocals(level) elseif info.what == "Lua" then local source = info.short_src local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name if source:sub(2, 7) == "string" then source = source:sub(9) end local was_guessed = false if not function_name or function_name == "?" then --for k,v in pairs(info) do print(k,v, type(v)) end function_name = GuessFunctionName(info) was_guessed = true end -- test if we have a file name local function_type = (info.namewhat == "") and "function" or info.namewhat if info.source and info.source:sub(1, 1) == "@" then dumper:add_f("(%d) Lua %s '%s' at file '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") elseif info.source and info.source:sub(1,1) == '#' then dumper:add_f("(%d) Lua %s '%s' at template '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") else dumper:add_f("(%d) Lua %s '%s' at line %d of chunk '%s'\r\n", level_to_show, function_type, function_name, info.currentline, source) end dumper:DumpLocals(level) else dumper:add_f("(%d) unknown frame %s\r\n", level_to_show, info.what) end level = level + 1 level_to_show = level_to_show + 1 info = dumper.getinfo(level, "nSlf") end return dumper:concat_lines(), original_error end -- -- Adds a table to the list of known tables function _M.add_known_table(tab, description) if m_known_tables[tab] then error("Cannot override an already known table") end m_user_known_tables[tab] = description end -- -- Adds a function to the list of known functions function _M.add_known_function(fun, description) if m_known_functions[fun] then error("Cannot override an already known function") end m_user_known_functions[fun] = description end return _M
gpl-3.0
unusualcrow/redead_reloaded
entities/entities/sent_fire/cl_init.lua
1
2490
include("shared.lua") function ENT:Initialize() self.Emitter = ParticleEmitter(self:GetPos()) self.SmokeTime = 0 self.LightTime = 0 self:DoTraces() end function ENT:DoTraces() if self:GetPos() == Vector(0, 0, 0) then return end self.PosTbl = {} for i = -30, 30 do for j = -30, 30 do local trace = {} trace.start = self:GetPos() + Vector(i * 2, j * 2, 10) trace.endpos = trace.start + Vector(0, 0, 200) local tr = util.TraceLine(trace) trace.start = tr.HitPos trace.endpos = trace.start + Vector(0, 0, -2000) local tr2 = util.TraceLine(trace) table.insert(self.PosTbl, { Pos = tr2.HitPos, Scale = ((30 - math.abs(i)) + (30 - math.abs(j))) / 60 }) end end end function ENT:Think() if not self.PosTbl then self:DoTraces() if not self.PosTbl then return end end local tbl for i = 1, 6 do tbl = table.Random(self.PosTbl) local particle = self.Emitter:Add("effects/muzzleflash" .. math.random(1, 4), tbl.Pos + (VectorRand() * 2)) particle:SetVelocity(Vector(0, 0, 80)) particle:SetDieTime(math.Rand(0.2, 0.4) + math.Rand(0.3, 0.6) * tbl.Scale) particle:SetStartAlpha(255) particle:SetEndAlpha(0) particle:SetStartSize(math.random(15, 25) + (math.random(25, 50) * tbl.Scale)) particle:SetEndSize(0) particle:SetRoll(math.random(-180, 180)) particle:SetColor(255, 200, 200) particle:SetGravity(Vector(0, 0, 400 + (tbl.Scale * 100))) end if self.SmokeTime < CurTime() then self.SmokeTime = CurTime() + 0.02 local particle = self.Emitter:Add("particles/smokey", tbl.Pos + (VectorRand() * 2) + Vector(0, 0, 50)) particle:SetVelocity(Vector(0, 0, 30 + tbl.Scale * 10)) particle:SetDieTime(math.Rand(0.5, 1.0) + (tbl.Scale * math.Rand(2.5, 3.5))) particle:SetStartAlpha(50 + tbl.Scale * 75) particle:SetEndAlpha(0) particle:SetStartSize(math.random(10, 20)) particle:SetEndSize(math.random(30, 60) + (math.random(40, 80) * tbl.Scale)) particle:SetRoll(0) particle:SetColor(10, 10, 10) particle:SetGravity(Vector(0, 0, 30)) end if self.LightTime < CurTime() then self.LightTime = CurTime() + 0.05 local dlight = DynamicLight(self:EntIndex()) if dlight then dlight.Pos = self:GetPos() dlight.r = 255 dlight.g = 120 dlight.b = 50 dlight.Brightness = 4 dlight.Decay = 2048 dlight.size = 256 * math.Rand(0.8, 1.2) dlight.DieTime = CurTime() + 1 end end end function ENT:OnRemove() if self.Emitter then self.Emitter:Finish() end end function ENT:Draw() end
mit
CrazyEddieTK/Zero-K
LuaRules/Configs/explosion_spawn_defs.lua
4
1725
-- $Id: explosion_spawn_defs.lua 4050 2009-03-09 02:56:38Z midknight $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --Lists post-processing weapon names and the units to spawn when they go off local spawn_defs = { chicken_blimpy_dodobomb = {name = "chicken_dodo", cost=0, expire=30}, veharty_mine = {name = "wolverine_mine", cost=0, expire=60}, hoverminer_mine = {name = "wolverine_mine", cost=0, expire=60}, zenith_meteor = {name = "asteroid_dead", cost=0, expire=0, feature = true}, zenith_meteor_float = {name = "asteroid_dead", cost=0, expire=0, feature = true}, zenith_meteor_aim = {name = "asteroid_dead", cost=0, expire=0, feature = true}, zenith_meteor_uncontrolled = {name = "asteroid_dead", cost=0, expire=0, feature = true}, chickenflyerqueen_dodobomb = {name = "chicken_dodo", cost=0, expire=30}, chickenflyerqueen_basiliskbomb = {name = "chickenc", cost=0, expire=0}, chickenflyerqueen_tiamatbomb = {name = "chicken_tiamat", cost=0, expire=0}, chickenlandqueen_dodobomb = {name = "chicken_dodo", cost=0, expire=30}, chickenlandqueen_basiliskbomb = {name = "chickenc", cost=0, expire=0}, chickenlandqueen_tiamatbomb = {name = "chicken_tiamat", cost=0, expire=0}, } local shieldCollide = { -- unitDefs as the shield hit callin is setup really strangely veharty_mine = {damage = 220, gadgetDamage = 200}, -- gadgetDamage = damage - weapon default damage -- Weapon name must be used } return spawn_defs, shieldCollide -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
czfshine/Don-t-Starve
data/scripts/components/locomotor.lua
1
21282
Dest = Class(function(self, inst, world_offset) self.inst = inst self.world_offset = world_offset end) local PATHFIND_PERIOD = 1 local PATHFIND_MAX_RANGE = 40 local STATUS_CALCULATING = 0 local STATUS_FOUNDPATH = 1 local STATUS_NOPATH = 2 local NO_ISLAND = 127 local ARRIVE_STEP = .15 function Dest:IsValid() if self.inst then if not self.inst:IsValid() then return false end end return true end function Dest:__tostring() if self.inst then return "Going to Entity: " .. tostring(self.inst) elseif self.world_offset then return "Heading to Point: " .. tostring(self.world_offset) else return "No Dest" end end function Dest:GetPoint() local pt = nil if self.inst and self.inst.components.inventoryitem and self.inst.components.inventoryitem.owner then return self.inst.components.inventoryitem.owner.Transform:GetWorldPosition() elseif self.inst then return self.inst.Transform:GetWorldPosition() elseif self.world_offset then return self.world_offset.x,self.world_offset.y,self.world_offset.z else return 0, 0, 0 end end local LocoMotor = Class(function(self, inst) self.inst = inst self.dest = nil self.atdestfn = nil self.bufferedaction = nil self.arrive_step_dist = ARRIVE_STEP self.arrive_dist = ARRIVE_STEP self.walkspeed = TUNING.WILSON_WALK_SPEED -- 4 self.runspeed = TUNING.WILSON_RUN_SPEED -- 6 self.bonusspeed = 0 self.throttle = 1 self.creep_check_timeout = 0 self.slowmultiplier = 0.6 self.fastmultiplier = 1.3 self.groundspeedmultiplier = 1.0 self.enablegroundspeedmultiplier = true self.isrunning = false self.wasoncreep = false self.triggerscreep = true end) function LocoMotor:StopMoving() self.isrunning = false self.inst.Physics:Stop() end function LocoMotor:SetSlowMultiplier(m) self.slowmultiplier = m end function LocoMotor:SetTriggersCreep(triggers) self.triggerscreep = triggers end function LocoMotor:EnableGroundSpeedMultiplier(enable) self.enablegroundspeedmultiplier = enable if not enable then self.groundspeedmultiplier = 1 end end function LocoMotor:GetWalkSpeed() return (self.walkspeed + self:GetBonusSpeed()) * self:GetSpeedMultiplier() end function LocoMotor:GetRunSpeed() return (self.runspeed + self:GetBonusSpeed()) * self:GetSpeedMultiplier() end function LocoMotor:GetBonusSpeed() return self.bonusspeed end function LocoMotor:GetSpeedMultiplier() local inv_mult = 1.0 if self.inst.components.inventory then for k,v in pairs (self.inst.components.inventory.equipslots) do if v.components.equippable then inv_mult = inv_mult * v.components.equippable:GetWalkSpeedMult() end end end return inv_mult * self.groundspeedmultiplier*self.throttle end function LocoMotor:UpdateGroundSpeedMultiplier() self.groundspeedmultiplier = 1 local ground = GetWorld() local oncreep = ground ~= nil and ground.GroundCreep:OnCreep(self.inst.Transform:GetWorldPosition()) local x,y,z = self.inst.Transform:GetWorldPosition() if oncreep then -- if this ever needs to happen when self.enablegroundspeedmultiplier is set, need to move the check for self.enablegroundspeedmultiplier above if self.triggerscreep and not self.wasoncreep then local triggered = ground.GroundCreep:GetTriggeredCreepSpawners(x, y, z) for _,v in ipairs(triggered) do v:PushEvent("creepactivate", {target = self.inst}) end self.wasoncreep = true end self.groundspeedmultiplier = self.slowmultiplier else self.wasoncreep = false if self.fasteronroad then --print(self.inst, "UpdateGroundSpeedMultiplier check road" ) if RoadManager and RoadManager:IsOnRoad( x,0,z ) then self.groundspeedmultiplier = self.fastmultiplier elseif ground ~= nil then local tile = ground.Map:GetTileAtPoint(x,0,z) if tile and tile == GROUND.ROAD then self.groundspeedmultiplier = self.fastmultiplier end end end end end function LocoMotor:WalkForward() self.isrunning = false self.inst.Physics:SetMotorVel(self:GetWalkSpeed(),0,0) self.inst:StartUpdatingComponent(self) end function LocoMotor:RunForward() self.isrunning = true self.inst.Physics:SetMotorVel(self:GetRunSpeed(),0,0) self.inst:StartUpdatingComponent(self) end function LocoMotor:Clear() --Print(VERBOSITY.DEBUG, "LocoMotor:Clear", self.inst.prefab) self.dest = nil self.atdestfn = nil self.wantstomoveforward = nil self.wantstorun = nil self.bufferedaction = nil --self:ResetPath() end function LocoMotor:ResetPath() --Print(VERBOSITY.DEBUG, "LocoMotor:ResetPath", self.inst.prefab) self:KillPathSearch() self.path = nil end function LocoMotor:KillPathSearch() --Print(VERBOSITY.DEBUG, "LocoMotor:KillPathSearch", self.inst.prefab) if self:WaitingForPathSearch() then GetWorld().Pathfinder:KillSearch(self.path.handle) end end function LocoMotor:SetReachDestinationCallback(fn) self.atdestfn = fn end function LocoMotor:PushAction(bufferedaction, run, try_instant) if not bufferedaction then return end self.throttle = 1 local success, reason = bufferedaction:TestForStart() if not success then self.inst:PushEvent("actionfailed", {action = bufferedaction, reason = reason}) return end self:Clear() if bufferedaction.action == ACTIONS.WALKTO then if bufferedaction.target then self:GoToEntity(bufferedaction.target, bufferedaction, run) elseif bufferedaction.pos then self:GoToPoint(bufferedaction.pos, bufferedaction, run) end elseif bufferedaction.action.instant then self.inst:PushBufferedAction(bufferedaction) else if bufferedaction.target then self:GoToEntity(bufferedaction.target, bufferedaction, run) elseif bufferedaction.pos then self:GoToPoint(bufferedaction.pos, bufferedaction, run) else self.inst:PushBufferedAction(bufferedaction) end end end function LocoMotor:GoToEntity(inst, bufferedaction, run) self.dest = Dest(inst) self.throttle = 1 self:SetBufferedAction(bufferedaction) self.wantstomoveforward = true if bufferedaction and bufferedaction.distance then self.arrive_dist = bufferedaction.distance else self.arrive_dist = ARRIVE_STEP if inst.Physics then self.arrive_dist = self.arrive_dist + ( inst.Physics:GetRadius() or 0) end if self.inst.Physics then self.arrive_dist = self.arrive_dist + (self.inst.Physics:GetRadius() or 0) end end if self.directdrive then if run then self:RunForward() else self:WalkForward() end else self:FindPath() end self.wantstorun = run --self.arrive_step_dist = ARRIVE_STEP self.inst:StartUpdatingComponent(self) end function LocoMotor:GoToPoint(pt, bufferedaction, run) self.dest = Dest(nil, pt) self.throttle = 1 if bufferedaction and bufferedaction.distance then self.arrive_dist = bufferedaction.distance else self.arrive_dist = ARRIVE_STEP end --self.arrive_step_dist = ARRIVE_STEP self.wantstorun = run if self.directdrive then if run then self:RunForward() else self:WalkForward() end else self:FindPath() end self.wantstomoveforward = true self:SetBufferedAction(bufferedaction) self.inst:StartUpdatingComponent(self) end function LocoMotor:SetBufferedAction(act) if self.bufferedaction then self.bufferedaction:Fail() end self.bufferedaction = act end function LocoMotor:Stop() --Print(VERBOSITY.DEBUG, "LocoMotor:Stop", self.inst.prefab) self.isrunning = false self.dest = nil self:ResetPath() self.lastdesttile = nil --self.arrive_step_dist = 0 --self:SetBufferedAction(nil) self.wantstomoveforward = false self.wantstorun = false self:StopMoving() self.inst:PushEvent("locomote") self.inst:StopUpdatingComponent(self) end function LocoMotor:WalkInDirection(direction, should_run) --Print(VERBOSITY.DEBUG, "LocoMotor:WalkInDirection ", self.inst.prefab) self:SetBufferedAction(nil) if not self.inst.sg or self.inst.sg:HasStateTag("canrotate") then self.inst.Transform:SetRotation(direction) end self.wantstomoveforward = true self.wantstorun = should_run self:ResetPath() self.lastdesttile = nil if self.directdrive then self:WalkForward() end self.inst:PushEvent("locomote") self.inst:StartUpdatingComponent(self) end function LocoMotor:RunInDirection(direction, throttle) --Print(VERBOSITY.DEBUG, "LocoMotor:RunInDirection ", self.inst.prefab) self.throttle = throttle or 1 self:SetBufferedAction(nil) self.dest = nil self:ResetPath() self.lastdesttile = nil if not self.inst.sg or self.inst.sg:HasStateTag("canrotate") then self.inst.Transform:SetRotation(direction) end self.wantstomoveforward = true self.wantstorun = true if self.directdrive then self:RunForward() end self.inst:PushEvent("locomote") self.inst:StartUpdatingComponent(self) end function LocoMotor:GetDebugString() local pathtile_x = -1 local pathtile_y = -1 local tile_x = -1 local tile_y = -1 local ground = GetWorld() if ground then pathtile_x, pathtile_y = ground.Pathfinder:GetPathTileIndexFromPoint(self.inst.Transform:GetWorldPosition()) tile_x, tile_y = ground.Map:GetTileCoordsAtPoint(self.inst.Transform:GetWorldPosition()) end local speed = self.wantstorun and "RUN" or "WALK" return string.format("%s [%s] [%s] (%u, %u):(%u, %u) +/-%2.2f", speed, tostring(self.dest), tostring(self.bufferedaction), tile_x, tile_y, pathtile_x, pathtile_y, self.arrive_step_dist or 0) end function LocoMotor:HasDestination() return self.dest ~= nil end function LocoMotor:SetShouldRun(should_run) self.wantstorun = should_run end function LocoMotor:WantsToRun() return self.wantstorun == true end function LocoMotor:WantsToMoveForward() return self.wantstomoveforward == true end function LocoMotor:WaitingForPathSearch() return self.path and self.path.handle end function LocoMotor:OnUpdate(dt) if not self.inst:IsValid() then Print(VERBOSITY.DEBUG, "OnUpdate INVALID", self.inst.prefab) self:ResetPath() self.inst:StopUpdatingComponent(self) return end if self.enablegroundspeedmultiplier then self.creep_check_timeout = self.creep_check_timeout - dt if self.creep_check_timeout < 0 then self:UpdateGroundSpeedMultiplier() self.creep_check_timeout = .5 end end --Print(VERBOSITY.DEBUG, "OnUpdate", self.inst.prefab) if self.dest then --Print(VERBOSITY.DEBUG, " w dest") if not self.dest:IsValid() or (self.bufferedaction and not self.bufferedaction:IsValid()) then self:Clear() return end if self.inst.components.health and self.inst.components.health:IsDead() then self:Clear() return end local destpos_x, destpos_y, destpos_z = self.dest:GetPoint() local mypos_x, mypos_y, mypos_z= self.inst.Transform:GetWorldPosition() local dsq = distsq(destpos_x, destpos_z, mypos_x, mypos_z) local run_dist = self:GetRunSpeed()*dt*.5 if dsq <= math.max(run_dist*run_dist, self.arrive_dist*self.arrive_dist) then --Print(VERBOSITY.DEBUG, "REACH DEST") self.inst:PushEvent("onreachdestination", {target=self.dest.inst, pos=Point(destpos_x, destpos_y, destpos_z)}) if self.atdestfn then self.atdestfn(self.inst) end if self.bufferedaction and self.bufferedaction ~= self.inst.bufferedaction then if self.bufferedaction.target and self.bufferedaction.target.Transform then self.inst:FacePoint(self.bufferedaction.target.Transform:GetWorldPosition()) end self.inst:PushBufferedAction(self.bufferedaction) end self:Stop() self:Clear() else --Print(VERBOSITY.DEBUG, "LOCOMOTING") if self:WaitingForPathSearch() then local pathstatus = GetWorld().Pathfinder:GetSearchStatus(self.path.handle) --Print(VERBOSITY.DEBUG, "HAS PATH SEARCH", pathstatus) if pathstatus ~= STATUS_CALCULATING then --Print(VERBOSITY.DEBUG, "PATH CALCULATION complete", pathstatus) if pathstatus == STATUS_FOUNDPATH then --Print(VERBOSITY.DEBUG, "PATH FOUND") local foundpath = GetWorld().Pathfinder:GetSearchResult(self.path.handle) if foundpath then --Print(VERBOSITY.DEBUG, string.format("PATH %d steps ", #foundpath.steps)) if #foundpath.steps > 2 then self.path.steps = foundpath.steps self.path.currentstep = 2 -- for k,v in ipairs(foundpath.steps) do -- Print(VERBOSITY.DEBUG, string.format("%d, %s", k, tostring(Point(v.x, v.y, v.z)))) -- end else --Print(VERBOSITY.DEBUG, "DISCARDING straight line path") self.path.steps = nil self.path.currentstep = nil end else Print(VERBOSITY.DEBUG, "EMPTY PATH") end else if pathstatus == nil then Print(VERBOSITY.DEBUG, string.format("LOST PATH SEARCH %u. Maybe it timed out?", self.path.handle)) else Print(VERBOSITY.DEBUG, "NO PATH") end end GetWorld().Pathfinder:KillSearch(self.path.handle) self.path.handle = nil end end if not self.inst.sg or self.inst.sg:HasStateTag("canrotate") then --Print(VERBOSITY.DEBUG, "CANROTATE") local facepos_x, facepos_y, facepos_z = destpos_x, destpos_y, destpos_z if self.path and self.path.steps and self.path.currentstep < #self.path.steps then --Print(VERBOSITY.DEBUG, "FOLLOW PATH") local step = self.path.steps[self.path.currentstep] local steppos_x, steppos_y, steppos_z = step.x, step.y, step.z --Print(VERBOSITY.DEBUG, string.format("CURRENT STEP %d/%d - %s", self.path.currentstep, #self.path.steps, tostring(steppos))) local step_distsq = distsq(mypos_x, mypos_z, steppos_x, steppos_z) if step_distsq <= (self.arrive_step_dist)*(self.arrive_step_dist) then self.path.currentstep = self.path.currentstep + 1 if self.path.currentstep < #self.path.steps then step = self.path.steps[self.path.currentstep] steppos_x, steppos_y, steppos_z = step.x, step.y, step.z --Print(VERBOSITY.DEBUG, string.format("NEXT STEP %d/%d - %s", self.path.currentstep, #self.path.steps, tostring(steppos))) else --Print(VERBOSITY.DEBUG, string.format("LAST STEP %s", tostring(destpos))) steppos_x, steppos_y, steppos_z = destpos_x, destpos_y, destpos_z end end facepos_x, facepos_y, facepos_z = steppos_x, steppos_y, steppos_z end local x,y,z = self.inst.Physics:GetMotorVel() if x < 0 then --Print(VERBOSITY.DEBUG, "SET ROT", facepos) local angle = self.inst:GetAngleToPoint(facepos_x, facepos_y, facepos_z) self.inst.Transform:SetRotation(180 + angle) else --Print(VERBOSITY.DEBUG, "FACE PT", facepos) self.inst:FacePoint(facepos_x, facepos_y, facepos_z) end end self.wantstomoveforward = self.wantstomoveforward or not self:WaitingForPathSearch() end end local is_moving = self.inst.sg and self.inst.sg:HasStateTag("moving") local is_running = self.inst.sg and self.inst.sg:HasStateTag("running") local should_locomote = (not is_moving ~= not self.wantstomoveforward) or (is_moving and (not is_running ~= not self.wantstorun)) -- 'not' is being used on this line as a cast-to-boolean operator if not self.inst:IsInLimbo() and should_locomote then self.inst:PushEvent("locomote") elseif not self.wantstomoveforward and not self:WaitingForPathSearch() then self:ResetPath() self.inst:StopUpdatingComponent(self) end local cur_speed = self.inst.Physics:GetMotorSpeed() if cur_speed > 0 then local speed_mult = self:GetSpeedMultiplier() local desired_speed = self.isrunning and self.runspeed or self.walkspeed if self.dest and self.dest:IsValid() then local destpos_x, destpos_y, destpos_z = self.dest:GetPoint() local mypos_x, mypos_y, mypos_z = self.inst.Transform:GetWorldPosition() local dsq = distsq(destpos_x, destpos_z, mypos_x, mypos_z) if dsq <= .25 then speed_mult = math.max(.33, math.sqrt(dsq)) end end self.inst.Physics:SetMotorVel((desired_speed + self.bonusspeed) * speed_mult, 0, 0) end end function LocoMotor:FindPath() --Print(VERBOSITY.DEBUG, "LocoMotor:FindPath", self.inst.prefab) --if self.inst.prefab ~= "wilson" then return end if not self.dest:IsValid() then return end local p0 = Vector3(self.inst.Transform:GetWorldPosition()) local p1 = Vector3(self.dest:GetPoint()) local dist = math.sqrt(distsq(p0, p1)) --Print(VERBOSITY.DEBUG, string.format(" %s -> %s distance %2.2f", tostring(p0), tostring(p1), dist)) -- if dist > PATHFIND_MAX_RANGE then -- Print(VERBOSITY.DEBUG, string.format("TOO FAR to pathfind %2.2f > %2.2f", dist, PATHFIND_MAX_RANGE)) -- return -- end local ground = GetWorld() if ground then --Print(VERBOSITY.DEBUG, "GROUND") local desttile_x, desttile_y = ground.Pathfinder:GetPathTileIndexFromPoint(p1.x, p1.y, p1.z) --Print(VERBOSITY.DEBUG, string.format(" dest tile %d, %d", desttile_x, desttile_y)) if desttile_x and desttile_y and self.lastdesttile then --Print(VERBOSITY.DEBUG, string.format(" last dest tile %d, %d", self.lastdesttile.x, self.lastdesttile.y)) if desttile_x == self.lastdesttile.x and desttile_y == self.lastdesttile.y then --Print(VERBOSITY.DEBUG, "SAME PATH") return end end self.lastdesttile = {x = desttile_x, y = desttile_y} --Print(VERBOSITY.DEBUG, string.format("CHECK LOS for [%s] %s -> %s", self.inst.prefab, tostring(p0), tostring(p1))) local isle0 = ground.Map:GetIslandAtPoint(p0:Get()) local isle1 = ground.Map:GetIslandAtPoint(p1:Get()) --print("Islands: ", isle0, isle1) if isle0 ~= NO_ISLAND and isle1 ~= NO_ISLAND and isle0 ~= isle1 then --print("NO PATH (different islands)", isle0, isle1) self:ResetPath() elseif ground.Pathfinder:IsClear(p0.x, p0.y, p0.z, p1.x, p1.y, p1.z, self.pathcaps) then --print("HAS LOS") self:ResetPath() else --print("NO LOS - PATHFIND") -- while chasing a moving target, the path may get reset frequently before any search completes -- only start a new search if we're not already waiting for the previous one to complete OR -- we already have a completed path we can keep following until new search returns if (self.path and self.path.steps) or not self:WaitingForPathSearch() then self:KillPathSearch() local handle = ground.Pathfinder:SubmitSearch(p0.x, p0.y, p0.z, p1.x, p1.y, p1.z, self.pathcaps) if handle then --Print(VERBOSITY.DEBUG, string.format("PATH handle %d ", handle)) --if we already had a path, just keep following it until we get our new one self.path = self.path or {} self.path.handle = handle else Print(VERBOSITY.DEBUG, "SUBMIT PATH FAILED") end end end end end return LocoMotor
gpl-2.0
omidtarh/fire
plugins/face.lua
641
3073
local https = require("ssl.https") local ltn12 = require "ltn12" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(imageUrl) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?" local parameters = "attribute=gender%2Cage%2Crace" parameters = parameters .. "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" if jsonBody.error ~= nil then if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then response = response .. "The image is too big. Provide a smaller image." elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then response = response .. "Is that a valid url for an image?" else response = response .. jsonBody.error end elseif jsonBody.face == nil or #jsonBody.face == 0 then response = response .. "No faces found" else response = response .. #jsonBody.face .." face(s) found:\n\n" for k,face in pairs(jsonBody.face) do local raceP = "" if face.attribute.race.confidence > 85.0 then raceP = face.attribute.race.value:lower() elseif face.attribute.race.confidence > 50.0 then raceP = "(probably "..face.attribute.race.value:lower()..")" else raceP = "(posibly "..face.attribute.race.value:lower()..")" end if face.attribute.gender.confidence > 85.0 then response = response .. "There is a " else response = response .. "There may be a " end response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " " response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n" end end return response end local function run(msg, matches) --return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg') local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end return parseData(data) end return { description = "Who is in that photo?", usage = { "!face [url]", "!recognise [url]" }, patterns = { "^!face (.*)$", "^!recognise (.*)$" }, run = run }
gpl-2.0
ranisalt/forgottenserver
data/scripts/actions/others/surprise_cube.lua
7
2266
local config = { {chanceFrom = 0, chanceTo = 1450, itemId = 2152, count = 5}, -- platinum coin {chanceFrom = 1451, chanceTo = 2850, itemId = 18421}, -- green crystal fragment {chanceFrom = 2851, chanceTo = 3950, itemId = 18419}, -- cyan crystal fragment {chanceFrom = 3951, chanceTo = 5050, itemId = 18420}, -- red crystal fragment {chanceFrom = 5051, chanceTo = 6050, itemId = 2675, count = 20}, -- orange {chanceFrom = 6051, chanceTo = 6850, itemId = 18413}, -- blue crystal shard {chanceFrom = 6851, chanceTo = 7450, itemId = 18415}, -- green crystal shard {chanceFrom = 7451, chanceTo = 8050, itemId = 2169}, -- time ring {chanceFrom = 8051, chanceTo = 8450, itemId = 2213}, -- dwarven ring {chanceFrom = 8451, chanceTo = 8750, itemId = 2167}, -- energy ring {chanceFrom = 8751, chanceTo = 9050, itemId = 2165}, -- stealth ring {chanceFrom = 9051, chanceTo = 9350, itemId = 7440}, -- mastermind potion {chanceFrom = 9351, chanceTo = 9550, itemId = 2214}, -- ring of healing {chanceFrom = 9551, chanceTo = 9750, itemId = 7439}, -- berserk potion {chanceFrom = 9751, chanceTo = 9850, itemId = 18414}, -- violet crystal shard {chanceFrom = 9851, chanceTo = 9950, itemId = 7443}, -- bullseye potion {chanceFrom = 9951, chanceTo = 9960, itemId = 26145}, -- brown pit demon {chanceFrom = 9961, chanceTo = 9970, itemId = 26146}, -- green pit demon {chanceFrom = 9971, chanceTo = 9980, itemId = 26147}, -- blue pit demon {chanceFrom = 9981, chanceTo = 9990, itemId = 26148}, -- black pit demon {chanceFrom = 9991, chanceTo = 10000, itemId = 26149} -- red pit demon } local surpriseCube = Action() function surpriseCube.onUse(player, item, fromPosition, target, toPosition, isHotkey) local chance = math.random(0, 10000) for i = 1, #config do local randomItem = config[i] if chance >= randomItem.chanceFrom and chance <= randomItem.chanceTo then if randomItem.itemId then local gift = randomItem.itemId local count = randomItem.count or 1 if type(count) == "table" then count = math.random(count[1], count[2]) end player:addItem(gift, count) end item:getPosition():sendMagicEffect(CONST_ME_CRAPS) item:remove(1) return true end end return false end surpriseCube:id(26144) surpriseCube:register()
gpl-2.0
CrazyEddieTK/Zero-K
LuaRules/Gadgets/unit_target_priority.lua
3
14767
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if not gadgetHandler:IsSyncedCode() then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Target Priority", desc = "Controls target priority because the engine seems to be based on random numbers.", author = "Google Frog", date = "September 25 2011", --update: 9 January 2014 license = "GNU GPL, v2 or later", layer = 0, enabled = true, } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local spGetUnitLosState = Spring.GetUnitLosState local spGetUnitDefID = Spring.GetUnitDefID local spGetUnitHealth = Spring.GetUnitHealth local spGetUnitAllyTeam = Spring.GetUnitAllyTeam local spGetTeamInfo = Spring.GetTeamInfo local spGetUnitIsStunned = Spring.GetUnitIsStunned local spGetAllUnits = Spring.GetAllUnits local spGetUnitRulesParam = Spring.GetUnitRulesParam local spGetUnitSeparation = Spring.GetUnitSeparation local spGetGameFrame = Spring.GetGameFrame local targetTable, disarmWeaponTimeDefs, disarmPenaltyDefs, captureWeaponDefs, gravityWeaponDefs, proximityWeaponDefs, velocityPenaltyDefs, radarWobblePenalty, radarDotPenalty, transportMult, highAlphaWeaponDamages, DISARM_BASE, DISARM_ADD, DISARM_ADD_TIME = include("LuaRules/Configs/target_priority_defs.lua") local DISARM_DECAY_FRAMES = 1200 local DISARM_TOTAL = DISARM_BASE + DISARM_ADD local DISARM_TIME_FACTOR = DISARM_DECAY_FRAMES + DISARM_ADD_TIME -- Low return number = more worthwhile target -- This seems to override everything, will need to reimplement emp things, badtargetcats etc... -- Callin occurs every 16 frames --// Values that reset every slow update -- Priority added based on health and capture for non-capture weapons local remNormalPriorityModifier = {} local remUnitHealth = {} -- used for overkill avoidance local remUnitHealthPriority = {} local remSpeed = {} -- Priority added based on health and capture for capture weapons -- The disinction is because capture weapons need to prioritize partially captured things local remCapturePriorityModifer = {} -- UnitDefID of unit carried in a transport. Used to override transporter unitDefID local remTransportiee = {} -- Priority to add based on disabled state. local remStunned = {} local remBuildProgress = {} local remStunAttackers = {} -- Whether the enemy unit is visible. local remVisible = {} -- Remebered mass of the target, negative if it is immune to impulse (nanoframes) local remScaledMass = {} --// Fairly unchanging values local remAllyTeam = {} local remUnitDefID = {} local remStatic = {} -- If there are more than STUN_ATTACKERS_IDLE_REQUIREMENT fire-at-will Racketeers or Cutters -- set targeted on a unit then the extra ones will attack other targets. local STUN_ATTACKERS_IDLE_REQUIREMENT = 3 -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Utility Functions local function GetUnitSpeed(unitID) if not remSpeed[unitID] then local _,_,_,vl = Spring.GetUnitVelocity(unitID) remSpeed[unitID] = vl end return remSpeed[unitID] end local function GetUnitVisibility(unitID, allyTeam) if not (remVisible[allyTeam] and remVisible[allyTeam][unitID]) then if not remVisible[allyTeam] then remVisible[allyTeam] = {} end local visibilityTable = spGetUnitLosState(unitID,allyTeam,false) if visibilityTable then if visibilityTable.los then remVisible[allyTeam][unitID] = 2 -- In LoS elseif visibilityTable.typed then remVisible[allyTeam][unitID] = 1 -- Known type else remVisible[allyTeam][unitID] = 0 end else remVisible[allyTeam][unitID] = 0 end end return remVisible[allyTeam][unitID] end local function GetUnitTransportieeDefID(unitID) if not remTransportiee[unitID] then local carryList = Spring.GetUnitIsTransporting(unitID) local carryID = carryList and carryList[1] if carryID and remUnitDefID[carryID] then remTransportiee[unitID] = remUnitDefID[carryID] else remTransportiee[unitID] = -1 end end return remTransportiee[unitID] end local function GetUnitStunnedOrInBuild(unitID) if not remStunned[unitID] then local bla, stunned, nanoframe = spGetUnitIsStunned(unitID) if stunned then remStunned[unitID] = 1 else local disarmed = (spGetUnitRulesParam(unitID, "disarmed") == 1) local disarmExpected = GG.OverkillPrevention_IsDisarmExpected(unitID) if disarmed or disarmExpected then if disarmExpected then remStunned[unitID] = DISARM_TOTAL else local disarmframe = spGetUnitRulesParam(unitID, "disarmframe") or -1 if disarmframe == -1 then -- Should be impossible to reach this branch. remStunned[unitID] = DISARM_TOTAL else local gameFrame = spGetGameFrame() local frames = disarmframe - gameFrame - DISARM_DECAY_FRAMES remStunned[unitID] = DISARM_BASE + math.max(0, math.min(DISARM_ADD, frames/DISARM_TIME_FACTOR)) end end else remStunned[unitID] = 0 end end if nanoframe or remStunned[unitID] >= 1 then local _, maxHealth, paralyzeDamage, _, buildProgress = spGetUnitHealth(unitID) remBuildProgress[unitID] = buildProgress if remStunned[unitID] >= 1 then -- Long paralysis is a much worse target than one that is almost worn off. local paraFactor = math.min(7.5, (paralyzeDamage/maxHealth)^4) remStunned[unitID] = paraFactor end else remBuildProgress[unitID] = 1 end end return remStunned[unitID], remBuildProgress[unitID] end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Weapon type specific priority modifiers local function GetCaptureWeaponPriorityModifier(unitID) if not remCapturePriorityModifer[unitID] then local stunned, buildProgress = GetUnitStunnedOrInBuild(unitID) local priority = stunned*2 + (15 * (1 - buildProgress)) if buildProgress < 1 then priority = priority + 3 end local overkill = GG.OverkillPrevention_IsDoomed(unitID) if overkill then priority = priority + 60 end --// Get priority modifier for health and capture progress. local armored = Spring.GetUnitArmored(unitID) local hp, maxHP, paralyze, capture = spGetUnitHealth(unitID) if hp and maxHP then priority = priority - (hp/maxHP)*0.1 -- Capture healthy units end if armored then priority = priority + 1 end if capture > 0 then -- Really prioritize partially captured units priority = priority - 6*capture end remCapturePriorityModifer[unitID] = priority end return remCapturePriorityModifer[unitID] end local function GetNormalWeaponPriorityModifier(unitID, attackerWeaponDefID) if not remNormalPriorityModifier[unitID] then local stunned, buildProgress = GetUnitStunnedOrInBuild(unitID) local priority = stunned*2 + (15 * (1 - buildProgress)) if buildProgress < 1 then priority = priority + 3 end local overkill = GG.OverkillPrevention_IsDoomed(unitID) if overkill then priority = priority + 60 end local armored, armor = Spring.GetUnitArmored(unitID) local hp, maxHP, paralyze, capture = spGetUnitHealth(unitID) remUnitHealth[unitID] = hp*((armored and armor and 1/armor) or 1) if hp and maxHP then remUnitHealthPriority[unitID] = hp/maxHP end if armored then priority = priority + 2 end if capture > 0 then -- Deprioritize partially captured units. priority = priority + 0.2*capture end remNormalPriorityModifier[unitID] = priority end local alphaDamage = highAlphaWeaponDamages[attackerWeaponDefID] if alphaDamage and remUnitHealth[unitID] and (remUnitHealth[unitID] < alphaDamage) then return remNormalPriorityModifier[unitID] - 0.2 + 0.2*(alphaDamage - remUnitHealth[unitID])/alphaDamage end return remNormalPriorityModifier[unitID] + (remUnitHealthPriority[unitID] or 0) end local function GetGravityWeaponPriorityModifier(unitID, attackerWeaponDefID) if not remScaledMass[unitID] then local _,_,inbuild = spGetUnitIsStunned(unitID) if inbuild then remScaledMass[unitID] = -1 else -- Glaive = 1.46, Zeus = 5.24, Minotaur = 9.48 remScaledMass[unitID] = 0.02 * UnitDefs[remUnitDefID[unitID]].mass end end if remScaledMass[unitID] > 0 then return remScaledMass[unitID] + GetNormalWeaponPriorityModifier(unitID, attackerWeaponDefID) * 0.3 else return false end end local function GetDisarmWeaponPriorityModifier(unitID, attackerWeaponDefID) local stunned = GetUnitStunnedOrInBuild(unitID) if stunned <= disarmWeaponTimeDefs[attackerWeaponDefID] then return GetNormalWeaponPriorityModifier(unitID, attackerWeaponDefID) end return (disarmPenaltyDefs[attackerWeaponDefID] or 10) + GetNormalWeaponPriorityModifier(unitID, attackerWeaponDefID) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Priority callin local DEF_TARGET_TOO_FAR_PRIORITY = 100000 --usually numbers are around several millions, if target is out of range function gadget:AllowWeaponTarget(unitID, targetID, attackerWeaponNum, attackerWeaponDefID, defPriority) --Spring.Echo("TARGET CHECK") if defPriority > DEF_TARGET_TOO_FAR_PRIORITY then return defPriority --hope engine is not that wrong about the best target outside of the range end if (not targetID) or (not unitID) or (not attackerWeaponDefID) then return true, 25 end local allyTeam = remAllyTeam[unitID] if (not allyTeam) then return true, 25 end if GG.GetUnitTarget(unitID) == targetID then if disarmWeaponTimeDefs[attackerWeaponDefID] then if (remStunAttackers[targetID] or 0) < STUN_ATTACKERS_IDLE_REQUIREMENT then local stunned, buildProgress = GetUnitStunnedOrInBuild(targetID) if stunned ~= 0 then remStunAttackers[targetID] = (remStunAttackers[targetID] or 0) + 1 end return true, 0 -- Maximum priority end else return true, 0 -- Maximum priority end end local lastShotBonus = 0 if GG.OverkillPrevention_GetLastShot(unitID) == targetID then lastShotBonus = -0.3 end local enemyUnitDefID = remUnitDefID[targetID] --// Get Velocity target penalty local velocityAdd = 0 local velocityPenaltyDef = velocityPenaltyDefs[attackerWeaponDefID] if velocityPenaltyDef then local unitSpeed = GetUnitSpeed(targetID) if unitSpeed > velocityPenaltyDef[1] then velocityAdd = velocityPenaltyDef[2] + unitSpeed*velocityPenaltyDef[3] end end --// Radar dot handling. Radar dots are not handled by subsequent areas because a unit which is -- identified but not visible cannot have priority based on health or other status effects. local visiblity = GetUnitVisibility(targetID, allyTeam) if visiblity ~= 2 then local wobbleAdd = (radarDotPenalty[attackerWeaponDefID] or 0) -- Mobile units get a penalty for radar wobble. Identified statics experience no wobble. if radarWobblePenalty[attackerWeaponDefID] and (visibility == 0 or not remStatic[enemyUnitDefID]) then wobbleAdd = radarWobblePenalty[attackerWeaponDefID] end if visiblity == 0 then return true, 25 + wobbleAdd + velocityAdd + lastShotBonus elseif visiblity == 1 then -- If the unit type is accessible then it can be included in the priority calculation. return true, (targetTable[enemyUnitDefID][attackerWeaponDefID] or 5) + wobbleAdd + velocityAdd + 1.5 + lastShotBonus end end --// Get default priority for weapon type vs unit type. Includes transportation local defPrio if transportMult[enemyUnitDefID] then local transportiee = GetUnitTransportieeDefID(targetID) if transportiee then defPrio = targetTable[enemyUnitDefID][attackerWeaponDefID] or 5 else defPrio = (targetTable[transportiee][attackerWeaponDefID] or 5)*transportMult[enemyUnitDefID] end else defPrio = targetTable[enemyUnitDefID][attackerWeaponDefID] or 5 end --// Get priority modifier based on broad weapon type and generic unit status if captureWeaponDefs[attackerWeaponDefID] then defPrio = defPrio + GetCaptureWeaponPriorityModifier(targetID) elseif gravityWeaponDefs[attackerWeaponDefID] then local gravityPriority = GetGravityWeaponPriorityModifier(targetID, attackerWeaponDefID) if not gravityPriority then return false end defPrio = defPrio + gravityPriority elseif disarmWeaponTimeDefs[attackerWeaponDefID] then defPrio = defPrio + GetDisarmWeaponPriorityModifier(targetID, attackerWeaponDefID) else defPrio = defPrio + GetNormalWeaponPriorityModifier(targetID, attackerWeaponDefID) end --// Proximity weapon special handling (heatrays). -- Prioritize nearby units. if proximityWeaponDefs[attackerWeaponDefID] then local unitSeparation = spGetUnitSeparation(unitID,targetID,true) local distAdd = proximityWeaponDefs[attackerWeaponDefID] * (unitSeparation/WeaponDefs[attackerWeaponDefID].range) defPrio = defPrio + distAdd end --Spring.Utilities.UnitEcho(targetID, string.format("%.1f", defPrio)) return true, defPrio + velocityAdd + lastShotBonus -- bigger value have lower priority end function gadget:GameFrame(f) if f%16 == 8 then -- f%16 == 0 happens just before AllowWeaponTarget remNormalPriorityModifier = {} remUnitHealth = {} remUnitHealthPriority = {} remSpeed = {} remCapturePriorityModifer = {} remTransportiee = {} remVisible = {} remScaledMass = {} remStunned = {} remStunAttackers = {} remBuildProgress = {} end end function gadget:UnitCreated(unitID, unitDefID) remUnitDefID[unitID] = unitDefID local allyTeam = spGetUnitAllyTeam(unitID) remAllyTeam[unitID] = allyTeam remStatic[unitID] = (unitDefID and not Spring.Utilities.getMovetype(UnitDefs[unitDefID])) end function gadget:UnitDestroyed(unitID, unitDefID) remUnitDefID[unitID] = nil remStatic[unitID] = nil remAllyTeam[unitID] = nil end function gadget:UnitGiven(unitID, unitDefID, teamID, oldTeamID) local _,_,_,_,_,newAllyTeam = spGetTeamInfo(teamID) remAllyTeam[unitID] = newAllyTeam end function gadget:Initialize() for _, unitID in ipairs(spGetAllUnits()) do local unitDefID = spGetUnitDefID(unitID) gadget:UnitCreated(unitID, unitDefID) end -- Hopefully not all weapon callins will need to be watched -- in some future version. for weaponID,_ in pairs(WeaponDefs) do Script.SetWatchWeapon(weaponID, true) end end
gpl-2.0
alexgrist/NutScript
plugins/saveitems.lua
1
3091
PLUGIN.name = "Save Items" PLUGIN.author = "Chessnut" PLUGIN.description = "Saves items that were dropped." --[[ function PLUGIN:OnSavedItemLoaded(items) for k, v in ipairs(items) do -- do something end end function PLUGIN:ShouldDeleteSavedItems() return true end ]]-- -- as title says. function PLUGIN:LoadData() local items = self:GetData() if (items) then local idRange = {} local info = {} for _, v in ipairs(items) do idRange[#idRange + 1] = v[1] info[v[1]] = {v[2], v[3], v[4]} end if (#idRange > 0) then if (hook.Run("ShouldDeleteSavedItems") == true) then -- don't spawn saved item and just delete them. local query = mysql:Delete("ix_items") query:WhereIn("item_id", idRange) query:Execute() print("Server Deleted Server Items (does not includes Logical Items)") else local query = mysql:Select("ix_items") query:Select("item_id") query:Select("unique_id") query:Select("data") query:WhereIn("item_id", idRange) query:Callback(function(result) if (istable(result)) then local loadedItems = {} local bagInventories = {} for _, v in ipairs(result) do local itemID = tonumber(v.item_id) local data = util.JSONToTable(v.data or "[]") local uniqueID = v.unique_id local itemTable = ix.item.list[uniqueID] if (itemTable and itemID) then local item = ix.item.New(uniqueID, itemID) item.data = data or {} local itemInfo = info[itemID] local position, angles, bMovable = itemInfo[1], itemInfo[2], true if (isbool(itemInfo[3])) then bMovable = itemInfo[3] end local itemEntity = item:Spawn(position, angles) itemEntity.ixItemID = itemID local physicsObject = itemEntity:GetPhysicsObject() if (IsValid(physicsObject)) then physicsObject:EnableMotion(bMovable) end item.invID = 0 loadedItems[#loadedItems + 1] = item if (item.isBag) then local invType = ix.item.inventoryTypes[uniqueID] bagInventories[item:GetData("id")] = {invType.w, invType.h} end end end -- we need to manually restore bag inventories in the world since they don't have a current owner -- that it can automatically restore along with the character when it's loaded if (!table.IsEmpty(bagInventories)) then ix.inventory.Restore(bagInventories) end hook.Run("OnSavedItemLoaded", loadedItems) -- when you have something in the dropped item. end end) query:Execute() end end end end function PLUGIN:SaveData() local items = {} for _, v in ipairs(ents.FindByClass("ix_item")) do if (v.ixItemID and !v.bTemporary) then local physicsObject = v:GetPhysicsObject() local bMovable = nil if (IsValid(physicsObject)) then bMovable = physicsObject:IsMoveable() end items[#items + 1] = { v.ixItemID, v:GetPos(), v:GetAngles(), bMovable } end end self:SetData(items) end
mit
cloudwu/skynet
service/service_provider.lua
3
2423
local skynet = require "skynet" local provider = {} local function new_service(svr, name) local s = {} svr[name] = s s.queue = {} return s end local svr = setmetatable({}, { __index = new_service }) function provider.query(name) local s = svr[name] if s.queue then table.insert(s.queue, skynet.response()) else if s.address then return skynet.ret(skynet.pack(s.address)) else error(s.error) end end end local function boot(addr, name, code, ...) local s = svr[name] skynet.call(addr, "lua", "init", code, ...) local tmp = table.pack( ... ) for i=1,tmp.n do tmp[i] = tostring(tmp[i]) end if tmp.n > 0 then s.init = table.concat(tmp, ",") end s.time = skynet.time() end function provider.launch(name, code, ...) local s = svr[name] if s.address then return skynet.ret(skynet.pack(s.address)) end if s.booting then table.insert(s.queue, skynet.response()) else s.booting = true local err local ok, addr = pcall(skynet.newservice,"service_cell", name) if ok then ok, err = xpcall(boot, debug.traceback, addr, name, code, ...) else err = addr addr = nil end s.booting = nil if ok then s.address = addr for _, resp in ipairs(s.queue) do resp(true, addr) end s.queue = nil skynet.ret(skynet.pack(addr)) else if addr then skynet.send(addr, "debug", "EXIT") end s.error = err for _, resp in ipairs(s.queue) do resp(false) end s.queue = nil error(err) end end end function provider.test(name) local s = svr[name] if s.booting then skynet.ret(skynet.pack(nil, true)) -- booting elseif s.address then skynet.ret(skynet.pack(s.address)) elseif s.error then error(s.error) else skynet.ret() -- nil end end function provider.close(name) local s = svr[name] if not s or s.booting then return skynet.ret(skynet.pack(nil)) end svr[name] = nil skynet.ret(skynet.pack(s.address)) end skynet.start(function() skynet.dispatch("lua", function(session, address, cmd, ...) provider[cmd](...) end) skynet.info_func(function() local info = {} for k,v in pairs(svr) do local status if v.booting then status = "booting" elseif v.queue then status = "waiting(" .. #v.queue .. ")" end info[skynet.address(v.address)] = { init = v.init, name = k, time = os.date("%Y %b %d %T %z",math.floor(v.time)), status = status, } end return info end) end)
mit
alinfrat/robot
plugins/stats.lua
236
3989
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(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/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/"..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' then 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(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(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)",-- Put everything you like :) "^[!/]([Tt]eleseed)"-- Put everything you like :) }, run = run } end
gpl-2.0
andywingo/snabbswitch
lib/ljsyscall/syscall/linux/ffi.lua
18
19305
-- ffi definitions of Linux types local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local abi = require "syscall.abi" local ffi = require "ffi" require "syscall.ffitypes" local arch = require("syscall.linux." .. abi.arch .. ".ffi") -- architecture specific definitions local defs = {} local function append(str) defs[#defs + 1] = str end append [[ typedef uint32_t mode_t; typedef unsigned short int sa_family_t; typedef uint64_t rlim64_t; typedef unsigned long nlink_t; typedef unsigned long ino_t; typedef long time_t; typedef int32_t daddr_t; typedef long blkcnt_t; typedef long blksize_t; typedef int32_t clockid_t; typedef long clock_t; typedef uint32_t off32_t; /* only used for eg mmap2 on Linux */ typedef uint32_t le32; /* this is little endian - not really using it yet */ typedef uint32_t id_t; typedef unsigned int tcflag_t; typedef unsigned int speed_t; typedef int timer_t; typedef uint64_t fsblkcnt_t; typedef uint64_t fsfilcnt_t; /* despite glibc, Linux uses 32 bit dev_t */ typedef uint32_t dev_t; typedef unsigned long aio_context_t; typedef unsigned long nfds_t; // should be a word, but we use 32 bits as bitops are signed 32 bit in LuaJIT at the moment typedef int32_t fd_mask; // again should be a long, and we have wrapped in a struct // TODO ok to wrap Lua types but not syscall? https://github.com/justincormack/ljsyscall/issues/36 // TODO is this size right? check struct cpu_set_t { int32_t val[1024 / (8 * sizeof (int32_t))]; }; typedef int mqd_t; typedef int idtype_t; /* defined as enum */ struct timespec { time_t tv_sec; long tv_nsec; }; // misc typedef void (*sighandler_t) (int); // structs struct timeval { long tv_sec; /* seconds */ long tv_usec; /* microseconds */ }; struct itimerspec { struct timespec it_interval; struct timespec it_value; }; struct itimerval { struct timeval it_interval; struct timeval it_value; }; typedef struct __fsid_t { int __val[2]; } fsid_t; //static const int UTSNAME_LENGTH = 65; struct utsname { char sysname[65]; char nodename[65]; char release[65]; char version[65]; char machine[65]; char domainname[65]; }; struct pollfd { int fd; short int events; short int revents; }; typedef struct { /* based on Linux FD_SETSIZE = 1024, the kernel can do more, so can increase */ fd_mask fds_bits[1024 / (sizeof (fd_mask) * 8)]; } fd_set; struct ucred { pid_t pid; uid_t uid; gid_t gid; }; struct rlimit64 { rlim64_t rlim_cur; rlim64_t rlim_max; }; struct sysinfo { long uptime; unsigned long loads[3]; unsigned long totalram; unsigned long freeram; unsigned long sharedram; unsigned long bufferram; unsigned long totalswap; unsigned long freeswap; unsigned short procs; unsigned short pad; unsigned long totalhigh; unsigned long freehigh; unsigned int mem_unit; char _f[20-2*sizeof(long)-sizeof(int)]; /* TODO ugh, remove calculation */ }; struct timex { unsigned int modes; long int offset; long int freq; long int maxerror; long int esterror; int status; long int constant; long int precision; long int tolerance; struct timeval time; long int tick; long int ppsfreq; long int jitter; int shift; long int stabil; long int jitcnt; long int calcnt; long int errcnt; long int stbcnt; int tai; int :32; int :32; int :32; int :32; int :32; int :32; int :32; int :32; int :32; int :32; int :32; }; typedef union sigval { int sival_int; void *sival_ptr; } sigval_t; struct cmsghdr { size_t cmsg_len; int cmsg_level; int cmsg_type; char cmsg_data[?]; }; struct msghdr { void *msg_name; socklen_t msg_namelen; struct iovec *msg_iov; size_t msg_iovlen; void *msg_control; size_t msg_controllen; int msg_flags; }; struct mmsghdr { struct msghdr msg_hdr; unsigned int msg_len; }; struct sockaddr { sa_family_t sa_family; char sa_data[14]; }; struct sockaddr_storage { sa_family_t ss_family; unsigned long int __ss_align; char __ss_padding[128 - 2 * sizeof(unsigned long int)]; /* total length 128 TODO no calculations */ }; struct sockaddr_in { sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr; unsigned char sin_zero[8]; }; struct sockaddr_in6 { sa_family_t sin6_family; in_port_t sin6_port; uint32_t sin6_flowinfo; struct in6_addr sin6_addr; uint32_t sin6_scope_id; }; struct sockaddr_un { sa_family_t sun_family; char sun_path[108]; }; struct sockaddr_nl { sa_family_t nl_family; unsigned short nl_pad; uint32_t nl_pid; uint32_t nl_groups; }; struct sockaddr_ll { unsigned short sll_family; unsigned short sll_protocol; /* __be16 */ int sll_ifindex; unsigned short sll_hatype; unsigned char sll_pkttype; unsigned char sll_halen; unsigned char sll_addr[8]; }; struct nlmsghdr { uint32_t nlmsg_len; uint16_t nlmsg_type; uint16_t nlmsg_flags; uint32_t nlmsg_seq; uint32_t nlmsg_pid; }; struct rtgenmsg { unsigned char rtgen_family; }; struct ifinfomsg { unsigned char ifi_family; unsigned char __ifi_pad; unsigned short ifi_type; int ifi_index; unsigned ifi_flags; unsigned ifi_change; }; struct rtattr { unsigned short rta_len; unsigned short rta_type; }; struct nlmsgerr { int error; struct nlmsghdr msg; }; struct rtmsg { unsigned char rtm_family; unsigned char rtm_dst_len; unsigned char rtm_src_len; unsigned char rtm_tos; unsigned char rtm_table; unsigned char rtm_protocol; unsigned char rtm_scope; unsigned char rtm_type; unsigned int rtm_flags; }; static const int IFNAMSIZ = 16; struct ifmap { unsigned long mem_start; unsigned long mem_end; unsigned short base_addr; unsigned char irq; unsigned char dma; unsigned char port; }; struct rtnl_link_stats { uint32_t rx_packets; uint32_t tx_packets; uint32_t rx_bytes; uint32_t tx_bytes; uint32_t rx_errors; uint32_t tx_errors; uint32_t rx_dropped; uint32_t tx_dropped; uint32_t multicast; uint32_t collisions; uint32_t rx_length_errors; uint32_t rx_over_errors; uint32_t rx_crc_errors; uint32_t rx_frame_errors; uint32_t rx_fifo_errors; uint32_t rx_missed_errors; uint32_t tx_aborted_errors; uint32_t tx_carrier_errors; uint32_t tx_fifo_errors; uint32_t tx_heartbeat_errors; uint32_t tx_window_errors; uint32_t rx_compressed; uint32_t tx_compressed; }; struct ndmsg { uint8_t ndm_family; uint8_t ndm_pad1; uint16_t ndm_pad2; int32_t ndm_ifindex; uint16_t ndm_state; uint8_t ndm_flags; uint8_t ndm_type; }; struct nda_cacheinfo { uint32_t ndm_confirmed; uint32_t ndm_used; uint32_t ndm_updated; uint32_t ndm_refcnt; }; struct ndt_stats { uint64_t ndts_allocs; uint64_t ndts_destroys; uint64_t ndts_hash_grows; uint64_t ndts_res_failed; uint64_t ndts_lookups; uint64_t ndts_hits; uint64_t ndts_rcv_probes_mcast; uint64_t ndts_rcv_probes_ucast; uint64_t ndts_periodic_gc_runs; uint64_t ndts_forced_gc_runs; }; struct ndtmsg { uint8_t ndtm_family; uint8_t ndtm_pad1; uint16_t ndtm_pad2; }; struct ndt_config { uint16_t ndtc_key_len; uint16_t ndtc_entry_size; uint32_t ndtc_entries; uint32_t ndtc_last_flush; uint32_t ndtc_last_rand; uint32_t ndtc_hash_rnd; uint32_t ndtc_hash_mask; uint32_t ndtc_hash_chain_gc; uint32_t ndtc_proxy_qlen; }; typedef struct { unsigned int clock_rate; unsigned int clock_type; unsigned short loopback; } sync_serial_settings; typedef struct { unsigned int clock_rate; unsigned int clock_type; unsigned short loopback; unsigned int slot_map; } te1_settings; typedef struct { unsigned short encoding; unsigned short parity; } raw_hdlc_proto; typedef struct { unsigned int t391; unsigned int t392; unsigned int n391; unsigned int n392; unsigned int n393; unsigned short lmi; unsigned short dce; } fr_proto; typedef struct { unsigned int dlci; } fr_proto_pvc; typedef struct { unsigned int dlci; char master[IFNAMSIZ]; } fr_proto_pvc_info; typedef struct { unsigned int interval; unsigned int timeout; } cisco_proto; struct if_settings { unsigned int type; unsigned int size; union { raw_hdlc_proto *raw_hdlc; cisco_proto *cisco; fr_proto *fr; fr_proto_pvc *fr_pvc; fr_proto_pvc_info *fr_pvc_info; sync_serial_settings *sync; te1_settings *te1; } ifs_ifsu; }; struct ifreq { union { char ifrn_name[IFNAMSIZ]; } ifr_ifrn; union { struct sockaddr ifru_addr; struct sockaddr ifru_dstaddr; struct sockaddr ifru_broadaddr; struct sockaddr ifru_netmask; struct sockaddr ifru_hwaddr; short ifru_flags; int ifru_ivalue; int ifru_mtu; struct ifmap ifru_map; char ifru_slave[IFNAMSIZ]; char ifru_newname[IFNAMSIZ]; void * ifru_data; struct if_settings ifru_settings; } ifr_ifru; }; struct ifaddrmsg { uint8_t ifa_family; uint8_t ifa_prefixlen; uint8_t ifa_flags; uint8_t ifa_scope; uint32_t ifa_index; }; struct ifa_cacheinfo { uint32_t ifa_prefered; uint32_t ifa_valid; uint32_t cstamp; uint32_t tstamp; }; struct rta_cacheinfo { uint32_t rta_clntref; uint32_t rta_lastuse; uint32_t rta_expires; uint32_t rta_error; uint32_t rta_used; uint32_t rta_id; uint32_t rta_ts; uint32_t rta_tsage; }; struct fdb_entry { uint8_t mac_addr[6]; uint8_t port_no; uint8_t is_local; uint32_t ageing_timer_value; uint8_t port_hi; uint8_t pad0; uint16_t unused; }; struct inotify_event { int wd; uint32_t mask; uint32_t cookie; uint32_t len; char name[?]; }; struct linux_dirent64 { uint64_t d_ino; int64_t d_off; unsigned short d_reclen; unsigned char d_type; char d_name[0]; }; struct flock64 { short int l_type; short int l_whence; off_t l_start; off_t l_len; pid_t l_pid; }; typedef union epoll_data { void *ptr; int fd; uint32_t u32; uint64_t u64; } epoll_data_t; struct signalfd_siginfo { uint32_t ssi_signo; int32_t ssi_errno; int32_t ssi_code; uint32_t ssi_pid; uint32_t ssi_uid; int32_t ssi_fd; uint32_t ssi_tid; uint32_t ssi_band; uint32_t ssi_overrun; uint32_t ssi_trapno; int32_t ssi_status; int32_t ssi_int; uint64_t ssi_ptr; uint64_t ssi_utime; uint64_t ssi_stime; uint64_t ssi_addr; uint8_t __pad[48]; }; struct io_event { uint64_t data; uint64_t obj; int64_t res; int64_t res2; }; struct seccomp_data { int nr; uint32_t arch; uint64_t instruction_pointer; uint64_t args[6]; }; struct sock_filter { uint16_t code; uint8_t jt; uint8_t jf; uint32_t k; }; struct sock_fprog { unsigned short len; struct sock_filter *filter; }; struct mq_attr { long mq_flags, mq_maxmsg, mq_msgsize, mq_curmsgs, __unused[4]; }; struct termios2 { tcflag_t c_iflag; tcflag_t c_oflag; tcflag_t c_cflag; tcflag_t c_lflag; cc_t c_line; cc_t c_cc[19]; speed_t c_ispeed; speed_t c_ospeed; }; struct input_event { struct timeval time; uint16_t type; uint16_t code; int32_t value; }; struct input_id { uint16_t bustype; uint16_t vendor; uint16_t product; uint16_t version; }; struct input_absinfo { int32_t value; int32_t minimum; int32_t maximum; int32_t fuzz; int32_t flat; int32_t resolution; }; struct input_keymap_entry { uint8_t flags; uint8_t len; uint16_t index; uint32_t keycode; uint8_t scancode[32]; }; struct ff_replay { uint16_t length; uint16_t delay; }; struct ff_trigger { uint16_t button; uint16_t interval; }; struct ff_envelope { uint16_t attack_length; uint16_t attack_level; uint16_t fade_length; uint16_t fade_level; }; struct ff_constant_effect { int16_t level; struct ff_envelope envelope; }; struct ff_ramp_effect { int16_t start_level; int16_t end_level; struct ff_envelope envelope; }; struct ff_condition_effect { uint16_t right_saturation; uint16_t left_saturation; int16_t right_coeff; int16_t left_coeff; uint16_t deadband; int16_t center; }; struct ff_periodic_effect { uint16_t waveform; uint16_t period; int16_t magnitude; int16_t offset; uint16_t phase; struct ff_envelope envelope; uint32_t custom_len; int16_t *custom_data; }; struct ff_rumble_effect { uint16_t strong_magnitude; uint16_t weak_magnitude; }; struct ff_effect { uint16_t type; int16_t id; uint16_t direction; struct ff_trigger trigger; struct ff_replay replay; union { struct ff_constant_effect constant; struct ff_ramp_effect ramp; struct ff_periodic_effect periodic; struct ff_condition_effect condition[2]; struct ff_rumble_effect rumble; } u; }; typedef struct { int val[2]; } kernel_fsid_t; /* we define the underlying structs not the pointer typedefs for capabilities */ struct user_cap_header { uint32_t version; int pid; }; struct user_cap_data { uint32_t effective; uint32_t permitted; uint32_t inheritable; }; /* this are overall capabilities structs to put metatables on */ struct cap { uint32_t cap[2]; }; struct capabilities { uint32_t version; int pid; struct cap effective; struct cap permitted; struct cap inheritable; }; struct xt_get_revision { char name[29]; uint8_t revision; }; struct vfs_cap_data { le32 magic_etc; struct { le32 permitted; /* Little endian */ le32 inheritable; /* Little endian */ } data[2]; }; typedef struct { void *ss_sp; int ss_flags; size_t ss_size; } stack_t; struct sched_param { int sched_priority; /* unused after here */ int sched_ss_low_priority; struct timespec sched_ss_repl_period; struct timespec sched_ss_init_budget; int sched_ss_max_repl; }; struct tun_filter { uint16_t flags; uint16_t count; uint8_t addr[0][6]; }; struct tun_pi { uint16_t flags; uint16_t proto; /* __be16 */ }; struct vhost_vring_state { unsigned int index; unsigned int num; }; struct vhost_vring_file { unsigned int index; int fd; }; struct vhost_vring_addr { unsigned int index; unsigned int flags; uint64_t desc_user_addr; uint64_t used_user_addr; uint64_t avail_user_addr; uint64_t log_guest_addr; }; struct vhost_memory_region { uint64_t guest_phys_addr; uint64_t memory_size; uint64_t userspace_addr; uint64_t flags_padding; }; struct vhost_memory { uint32_t nregions; uint32_t padding; struct vhost_memory_region regions[0]; }; struct rusage { struct timeval ru_utime; struct timeval ru_stime; long ru_maxrss; long ru_ixrss; long ru_idrss; long ru_isrss; long ru_minflt; long ru_majflt; long ru_nswap; long ru_inblock; long ru_oublock; long ru_msgsnd; long ru_msgrcv; long ru_nsignals; long ru_nvcsw; long ru_nivcsw; }; ]] append(arch.nsig or [[ static const int _NSIG = 64; ]] ) append(arch.sigset or [[ // again, should be a long static const int _NSIG_BPW = 32; typedef struct { int32_t sig[_NSIG / _NSIG_BPW]; } sigset_t; ]] ) -- both Glibc and Musl have larger termios at least for some architectures; I believe this is correct for kernel append(arch.termios or [[ struct termios { tcflag_t c_iflag; tcflag_t c_oflag; tcflag_t c_cflag; tcflag_t c_lflag; cc_t c_line; cc_t c_cc[19]; }; ]] ) -- Linux struct siginfo padding depends on architecture if abi.abi64 then append [[ static const int SI_MAX_SIZE = 128; static const int SI_PAD_SIZE = (SI_MAX_SIZE / sizeof (int)) - 4; ]] else append [[ static const int SI_MAX_SIZE = 128; static const int SI_PAD_SIZE = (SI_MAX_SIZE / sizeof (int)) - 3; ]] end append(arch.siginfo or [[ typedef struct siginfo { int si_signo; int si_errno; int si_code; union { int _pad[SI_PAD_SIZE]; struct { pid_t si_pid; uid_t si_uid; } kill; struct { int si_tid; int si_overrun; sigval_t si_sigval; } timer; struct { pid_t si_pid; uid_t si_uid; sigval_t si_sigval; } rt; struct { pid_t si_pid; uid_t si_uid; int si_status; clock_t si_utime; clock_t si_stime; } sigchld; struct { void *si_addr; } sigfault; struct { long int si_band; int si_fd; } sigpoll; } _sifields; } siginfo_t; ]] ) -- this is the type used by the rt_sigaction syscall NB have renamed the fields to sa_ append(arch.sigaction or [[ struct k_sigaction { void (*sa_handler)(int); unsigned long sa_flags; void (*sa_restorer)(void); unsigned sa_mask[2]; }; ]] ) -- these could vary be arch but do not yet append [[ static const int sigev_preamble_size = sizeof(int) * 2 + sizeof(sigval_t); static const int sigev_max_size = 64; static const int sigev_pad_size = (sigev_max_size - sigev_preamble_size) / sizeof(int); typedef struct sigevent { sigval_t sigev_value; int sigev_signo; int sigev_notify; union { int _pad[sigev_pad_size]; int _tid; struct { void (*_function)(sigval_t); void *_attribute; } _sigev_thread; } _sigev_un; } sigevent_t; ]] append(arch.ucontext) -- there is no default for ucontext and related types as very machine specific if arch.statfs then append(arch.statfs) else -- Linux struct statfs/statfs64 depends on 64/32 bit if abi.abi64 then append [[ typedef long statfs_word; ]] else append [[ typedef uint32_t statfs_word; ]] end append [[ struct statfs64 { statfs_word f_type; statfs_word f_bsize; uint64_t f_blocks; uint64_t f_bfree; uint64_t f_bavail; uint64_t f_files; uint64_t f_ffree; kernel_fsid_t f_fsid; statfs_word f_namelen; statfs_word f_frsize; statfs_word f_flags; statfs_word f_spare[4]; }; ]] end append(arch.stat) -- epoll packed on x86_64 only (so same as x86) append(arch.epoll or [[ struct epoll_event { uint32_t events; epoll_data_t data; }; ]] ) -- endian dependent if abi.le then append [[ struct iocb { uint64_t aio_data; uint32_t aio_key, aio_reserved1; uint16_t aio_lio_opcode; int16_t aio_reqprio; uint32_t aio_fildes; uint64_t aio_buf; uint64_t aio_nbytes; int64_t aio_offset; uint64_t aio_reserved2; uint32_t aio_flags; uint32_t aio_resfd; }; ]] else append [[ struct iocb { uint64_t aio_data; uint32_t aio_reserved1, aio_key; uint16_t aio_lio_opcode; int16_t aio_reqprio; uint32_t aio_fildes; uint64_t aio_buf; uint64_t aio_nbytes; int64_t aio_offset; uint64_t aio_reserved2; uint32_t aio_flags; uint32_t aio_resfd; }; ]] end -- functions, minimal for Linux as mainly use syscall append [[ long syscall(int number, ...); int gettimeofday(struct timeval *tv, void *tz); int clock_gettime(clockid_t clk_id, struct timespec *tp); void exit(int status); ]] ffi.cdef(table.concat(defs, ""))
apache-2.0
borq79/Cary-Area-Public-Library-Classes
courses/diy_weather_nodemcu/source/nodemcu/weather.lua
1
3505
-- ==================================================================================================================== -- ==================================================================================================================== -- Copyright (c) 2017 Ryan Brock. All rights reserved. -- Licensed under the MIT License. See LICENSE file in the project root for full license information. -- -- This file is run when the NodeMCU boots. -- This will connect to the WiFi and start up the mini HTTP server -- ==================================================================================================================== -- ==================================================================================================================== function trim(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end -- ==================================================================================================================== -- Load the Configuration -- ==================================================================================================================== print("\n-----------------------------------") print(" Starting Weather Station ...") print("-----------------------------------") if file.open("weather.config") then configLine = file.readline() while configLine do configName, configValue = configLine:match("([^,]+)\:([^,]+)") configName = trim(configName) configValue = trim(configValue) print(string.format("Setting [%s] to [%s]", configName, configValue)) _G[configName] = configValue configLine = file.readline() end file.close() end -- ==================================================================================================================== -- Connect to the wifi -- ==================================================================================================================== wifi.setmode(wifi.STATION) station_cfg={} station_cfg.ssid=ssid station_cfg.pwd=wifipassword station_cfg.save=true station_cfg.auto=true connectionStatus = wifi.sta.config(station_cfg) if connectionStatus == true then print(string.format("Successfully Connected to [%s]", ssid)) print("Connected IP Details: ", wifi.sta.getip()) else print(string.format("Failed to connect to [%s]", ssid)) end -- ==================================================================================================================== -- Start the HTTP server -- ==================================================================================================================== srv=net.createServer(net.TCP) srv:listen(80,function(conn) conn:on("receive",function(conn,payload) -- Grab the first line of the HTTP request - ignore the rest path = payload:match("^GET (.+) HTTP/%d.%d\r\n.*") print(string.format("HTTP Request [%s]", path)) if path == "/api/w" then respondApiWeather(conn) else conn:send(string.format("<html><head><title>Weather Station</title></head><body>Hello World</body></html>")) end --conn:send(string.format("<h1> Hello, NodeMcu.</h1>\r\nT=%d.%02d C\r\nT=%d.%02d F\r\nhumidity=%d.%03d%%\r\nADC=%d\r\n", TC, TCD, TF, TFD, H/1000, H%1000, adc.read(0))) --conn:send(string.format("<html><head><title>Weather Station</title></head><body>Hello World</body></html>")) end) end) function respondApiWeather(conn) print("API/Weather Response") conn:send(string.format("{\"t\": 1483314140,\"tf\": 32,\"tc\": 0,\"p\": 23,\"h\": 32.5,\"i\": 345}")) end
mit
tgroshon/canvas-lms
lib/canvas/request_throttle/increment_bucket.lua
43
1169
local cache_key = KEYS[1] local amount = tonumber(ARGV[1]) local current_time = tonumber(ARGV[2]) local outflow = tonumber(ARGV[3]) local maximum = tonumber(ARGV[4]) -- Our modified leaky bucket algorithm is explained in lib/canvas/request_throttle.rb local leak = function(count, last_touched, current_time, outflow) if count > 0 then local timespan = current_time - last_touched local loss = outflow * timespan if loss > 0 then count = count - loss end end return count, last_touched end local count, last_touched = unpack(redis.call('HMGET', cache_key, 'count', 'last_touched')) count = tonumber(count or 0) last_touched = tonumber(last_touched or current_time) count, last_touched = leak(count, last_touched, current_time, outflow) count = count + amount if count > maximum then count = maximum end if count < 0 then count = 0 end redis.call('HMSET', cache_key, 'count', count, 'last_touched', current_time) -- reset expiration to 1 hour from now each time we write redis.call('EXPIRE', cache_key, 3600) -- redis converts lua numbers to ints, so we have to return these as strings return { tostring(count), tostring(current_time) }
agpl-3.0
UristMcEngineer/Michels-Medieval-Mod
mmm/mods/boats/init.lua
1
5588
-- -- Helper functions -- local function is_water(pos) local nn = minetest.get_node(pos).name return minetest.get_item_group(nn, "water") ~= 0 end local function get_sign(i) if i == 0 then return 0 else return i / math.abs(i) end end local function get_velocity(v, yaw, y) local x = -math.sin(yaw) * v local z = math.cos(yaw) * v return {x = x, y = y, z = z} end local function get_v(v) return math.sqrt(v.x ^ 2 + v.z ^ 2) end -- -- Boat entity -- local boat = { physical = true, collisionbox = {-0.5, -0.35, -0.5, 0.5, 0.3, 0.5}, visual = "mesh", mesh = "boat.obj", textures = {"default_wood.png"}, driver = nil, v = 0, last_v = 0, removed = false } function boat.on_rightclick(self, clicker) if not clicker or not clicker:is_player() then return end local name = clicker:get_player_name() if self.driver and clicker == self.driver then self.driver = nil clicker:set_detach() default.player_attached[name] = false default.player_set_animation(clicker, "stand" , 30) local pos = clicker:getpos() pos = {x = pos.x, y = pos.y + 0.2, z = pos.z} minetest.after(0.1, function() clicker:setpos(pos) end) elseif not self.driver then self.driver = clicker clicker:set_attach(self.object, "", {x = 0, y = 11, z = -3}, {x = 0, y = 0, z = 0}) default.player_attached[name] = true minetest.after(0.2, function() default.player_set_animation(clicker, "sit" , 30) end) self.object:setyaw(clicker:get_look_yaw() - math.pi / 2) end end function boat.on_activate(self, staticdata, dtime_s) self.object:set_armor_groups({immortal = 1}) if staticdata then self.v = tonumber(staticdata) end self.last_v = self.v end function boat.get_staticdata(self) return tostring(self.v) end function boat.on_punch(self, puncher, time_from_last_punch, tool_capabilities, direction) if not puncher or not puncher:is_player() or self.removed then return end if self.driver and puncher == self.driver then self.driver = nil puncher:set_detach() default.player_attached[puncher:get_player_name()] = false end if not self.driver then self.removed = true -- delay remove to ensure player is detached minetest.after(0.1, function() self.object:remove() end) if not minetest.setting_getbool("creative_mode") then puncher:get_inventory():add_item("main", "boats:boat") end end end function boat.on_step(self, dtime) self.v = get_v(self.object:getvelocity()) * get_sign(self.v) if self.driver then local ctrl = self.driver:get_player_control() local yaw = self.object:getyaw() if ctrl.up then self.v = self.v + 0.1 elseif ctrl.down then self.v = self.v - 0.1 end if ctrl.left then if self.v < 0 then self.object:setyaw(yaw - (1 + dtime) * 0.03) else self.object:setyaw(yaw + (1 + dtime) * 0.03) end elseif ctrl.right then if self.v < 0 then self.object:setyaw(yaw + (1 + dtime) * 0.03) else self.object:setyaw(yaw - (1 + dtime) * 0.03) end end end local velo = self.object:getvelocity() if self.v == 0 and velo.x == 0 and velo.y == 0 and velo.z == 0 then self.object:setpos(self.object:getpos()) return end local s = get_sign(self.v) self.v = self.v - 0.02 * s if s ~= get_sign(self.v) then self.object:setvelocity({x = 0, y = 0, z = 0}) self.v = 0 return end if math.abs(self.v) > 4.5 then self.v = 4.5 * get_sign(self.v) end local p = self.object:getpos() p.y = p.y - 0.5 local new_velo = {x = 0, y = 0, z = 0} local new_acce = {x = 0, y = 0, z = 0} if not is_water(p) then local nodedef = minetest.registered_nodes[minetest.get_node(p).name] if (not nodedef) or nodedef.walkable then self.v = 0 new_acce = {x = 0, y = 1, z = 0} else new_acce = {x = 0, y = -9.8, z = 0} end new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y) self.object:setpos(self.object:getpos()) else p.y = p.y + 1 if is_water(p) then local y = self.object:getvelocity().y if y >= 4.5 then y = 4.5 elseif y < 0 then new_acce = {x = 0, y = 20, z = 0} else new_acce = {x = 0, y = 5, z = 0} end new_velo = get_velocity(self.v, self.object:getyaw(), y) self.object:setpos(self.object:getpos()) else new_acce = {x = 0, y = 0, z = 0} if math.abs(self.object:getvelocity().y) < 1 then local pos = self.object:getpos() pos.y = math.floor(pos.y) + 0.5 self.object:setpos(pos) new_velo = get_velocity(self.v, self.object:getyaw(), 0) else new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y) self.object:setpos(self.object:getpos()) end end end self.object:setvelocity(new_velo) self.object:setacceleration(new_acce) end minetest.register_entity("boats:boat", boat) minetest.register_craftitem("boats:boat", { description = "Boat", inventory_image = "boat_inventory.png", wield_image = "boat_wield.png", wield_scale = {x = 2, y = 2, z = 1}, liquids_pointable = true, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return end if not is_water(pointed_thing.under) then return end pointed_thing.under.y = pointed_thing.under.y + 0.5 minetest.add_entity(pointed_thing.under, "boats:boat") if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end return itemstack end, }) minetest.register_craft({ output = "boats:boat", recipe = { {"", "", "" }, {"group:wood", "", "group:wood"}, {"group:wood", "group:wood", "group:wood"}, }, })
gpl-3.0
andywingo/snabbswitch
lib/ljsyscall/syscall/linux/nl.lua
18
36273
-- modularize netlink code as it is large and standalone local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local function init(S) local nl = {} -- exports local ffi = require "ffi" local bit = require "syscall.bit" local h = require "syscall.helpers" local util = S.util local types = S.types local c = S.c local htonl = h.htonl local align = h.align local t, pt, s = types.t, types.pt, types.s local adtt = { [c.AF.INET] = t.in_addr, [c.AF.INET6] = t.in6_addr, } local function addrtype(af) local tp = adtt[tonumber(af)] if not tp then error("bad address family") end return tp() end local function mktype(tp, x) if ffi.istype(tp, x) then return x else return tp(x) end end local mt = {} -- metatables local meth = {} -- similar functions for netlink messages local function nlmsg_align(len) return align(len, 4) end local nlmsg_hdrlen = nlmsg_align(s.nlmsghdr) local function nlmsg_length(len) return len + nlmsg_hdrlen end local function nlmsg_ok(msg, len) return len >= nlmsg_hdrlen and msg.nlmsg_len >= nlmsg_hdrlen and msg.nlmsg_len <= len end local function nlmsg_next(msg, buf, len) local inc = nlmsg_align(msg.nlmsg_len) return pt.nlmsghdr(buf + inc), buf + inc, len - inc end local rta_align = nlmsg_align -- also 4 byte align local function rta_length(len) return len + rta_align(s.rtattr) end local function rta_ok(msg, len) return len >= s.rtattr and msg.rta_len >= s.rtattr and msg.rta_len <= len end local function rta_next(msg, buf, len) local inc = rta_align(msg.rta_len) return pt.rtattr(buf + inc), buf + inc, len - inc end local addrlenmap = { -- map interface type to length of hardware address TODO are these always same? [c.ARPHRD.ETHER] = 6, [c.ARPHRD.EETHER] = 6, [c.ARPHRD.LOOPBACK] = 6, } local ifla_decode = { [c.IFLA.IFNAME] = function(ir, buf, len) ir.name = ffi.string(buf) end, [c.IFLA.ADDRESS] = function(ir, buf, len) local addrlen = addrlenmap[ir.type] if (addrlen) then ir.addrlen = addrlen ir.macaddr = t.macaddr() ffi.copy(ir.macaddr, buf, addrlen) end end, [c.IFLA.BROADCAST] = function(ir, buf, len) local addrlen = addrlenmap[ir.type] -- TODO always same if (addrlen) then ir.broadcast = t.macaddr() ffi.copy(ir.broadcast, buf, addrlen) end end, [c.IFLA.MTU] = function(ir, buf, len) local u = pt.uint(buf) ir.mtu = tonumber(u[0]) end, [c.IFLA.LINK] = function(ir, buf, len) local i = pt.int(buf) ir.link = tonumber(i[0]) end, [c.IFLA.QDISC] = function(ir, buf, len) ir.qdisc = ffi.string(buf) end, [c.IFLA.STATS] = function(ir, buf, len) ir.stats = t.rtnl_link_stats() -- despite man page, this is what kernel uses. So only get 32 bit stats here. ffi.copy(ir.stats, buf, s.rtnl_link_stats) end } local ifa_decode = { [c.IFA.ADDRESS] = function(ir, buf, len) ir.addr = addrtype(ir.family) ffi.copy(ir.addr, buf, ffi.sizeof(ir.addr)) end, [c.IFA.LOCAL] = function(ir, buf, len) ir.loc = addrtype(ir.family) ffi.copy(ir.loc, buf, ffi.sizeof(ir.loc)) end, [c.IFA.BROADCAST] = function(ir, buf, len) ir.broadcast = addrtype(ir.family) ffi.copy(ir.broadcast, buf, ffi.sizeof(ir.broadcast)) end, [c.IFA.LABEL] = function(ir, buf, len) ir.label = ffi.string(buf) end, [c.IFA.ANYCAST] = function(ir, buf, len) ir.anycast = addrtype(ir.family) ffi.copy(ir.anycast, buf, ffi.sizeof(ir.anycast)) end, [c.IFA.CACHEINFO] = function(ir, buf, len) ir.cacheinfo = t.ifa_cacheinfo() ffi.copy(ir.cacheinfo, buf, ffi.sizeof(t.ifa_cacheinfo)) end, } local rta_decode = { [c.RTA.DST] = function(ir, buf, len) ir.dst = addrtype(ir.family) ffi.copy(ir.dst, buf, ffi.sizeof(ir.dst)) end, [c.RTA.SRC] = function(ir, buf, len) ir.src = addrtype(ir.family) ffi.copy(ir.src, buf, ffi.sizeof(ir.src)) end, [c.RTA.IIF] = function(ir, buf, len) local i = pt.int(buf) ir.iif = tonumber(i[0]) end, [c.RTA.OIF] = function(ir, buf, len) local i = pt.int(buf) ir.oif = tonumber(i[0]) end, [c.RTA.GATEWAY] = function(ir, buf, len) ir.gateway = addrtype(ir.family) ffi.copy(ir.gateway, buf, ffi.sizeof(ir.gateway)) end, [c.RTA.PRIORITY] = function(ir, buf, len) local i = pt.int(buf) ir.priority = tonumber(i[0]) end, [c.RTA.PREFSRC] = function(ir, buf, len) local i = pt.uint32(buf) ir.prefsrc = tonumber(i[0]) end, [c.RTA.METRICS] = function(ir, buf, len) local i = pt.int(buf) ir.metrics = tonumber(i[0]) end, [c.RTA.TABLE] = function(ir, buf, len) local i = pt.uint32(buf) ir.table = tonumber(i[0]) end, [c.RTA.CACHEINFO] = function(ir, buf, len) ir.cacheinfo = t.rta_cacheinfo() ffi.copy(ir.cacheinfo, buf, s.rta_cacheinfo) end, -- TODO some missing } local nda_decode = { [c.NDA.DST] = function(ir, buf, len) ir.dst = addrtype(ir.family) ffi.copy(ir.dst, buf, ffi.sizeof(ir.dst)) end, [c.NDA.LLADDR] = function(ir, buf, len) ir.lladdr = t.macaddr() ffi.copy(ir.lladdr, buf, s.macaddr) end, [c.NDA.CACHEINFO] = function(ir, buf, len) ir.cacheinfo = t.nda_cacheinfo() ffi.copy(ir.cacheinfo, buf, s.nda_cacheinfo) end, [c.NDA.PROBES] = function(ir, buf, len) -- TODO what is this? 4 bytes end, } local ifflist = {} for k, _ in pairs(c.IFF) do ifflist[#ifflist + 1] = k end mt.iff = { __tostring = function(f) local s = {} for _, k in pairs(ifflist) do if bit.band(f.flags, c.IFF[k]) ~= 0 then s[#s + 1] = k end end return table.concat(s, ' ') end, __index = function(f, k) if c.IFF[k] then return bit.band(f.flags, c.IFF[k]) ~= 0 end end } nl.encapnames = { [c.ARPHRD.ETHER] = "Ethernet", [c.ARPHRD.LOOPBACK] = "Local Loopback", } meth.iflinks = { fn = { refresh = function(i) local j, err = nl.interfaces() if not j then return nil, err end for k, _ in pairs(i) do i[k] = nil end for k, v in pairs(j) do i[k] = v end return i end, }, } mt.iflinks = { __index = function(i, k) if meth.iflinks.fn[k] then return meth.iflinks.fn[k] end end, __tostring = function(is) local s = {} for _, v in ipairs(is) do s[#s + 1] = tostring(v) end return table.concat(s, '\n') end } meth.iflink = { index = { family = function(i) return tonumber(i.ifinfo.ifi_family) end, type = function(i) return tonumber(i.ifinfo.ifi_type) end, typename = function(i) local n = nl.encapnames[i.type] return n or 'unknown ' .. i.type end, index = function(i) return tonumber(i.ifinfo.ifi_index) end, flags = function(i) return setmetatable({flags = tonumber(i.ifinfo.ifi_flags)}, mt.iff) end, change = function(i) return tonumber(i.ifinfo.ifi_change) end, }, fn = { setflags = function(i, flags, change) local ok, err = nl.newlink(i, 0, flags, change or c.IFF.ALL) if not ok then return nil, err end return i:refresh() end, up = function(i) return i:setflags("up", "up") end, down = function(i) return i:setflags("", "up") end, setmtu = function(i, mtu) local ok, err = nl.newlink(i.index, 0, 0, 0, "mtu", mtu) if not ok then return nil, err end return i:refresh() end, setmac = function(i, mac) local ok, err = nl.newlink(i.index, 0, 0, 0, "address", mac) if not ok then return nil, err end return i:refresh() end, address = function(i, address, netmask) -- add address if type(address) == "string" then address, netmask = util.inet_name(address, netmask) end if not address then return nil end local ok, err if ffi.istype(t.in6_addr, address) then ok, err = nl.newaddr(i.index, c.AF.INET6, netmask, "permanent", "local", address) else local broadcast = address:get_mask_bcast(netmask).broadcast ok, err = nl.newaddr(i.index, c.AF.INET, netmask, "permanent", "local", address, "broadcast", broadcast) end if not ok then return nil, err end return i:refresh() end, deladdress = function(i, address, netmask) if type(address) == "string" then address, netmask = util.inet_name(address, netmask) end if not address then return nil end local af if ffi.istype(t.in6_addr, address) then af = c.AF.INET6 else af = c.AF.INET end local ok, err = nl.deladdr(i.index, af, netmask, "local", address) if not ok then return nil, err end return i:refresh() end, delete = function(i) local ok, err = nl.dellink(i.index) if not ok then return nil, err end return true end, move_ns = function(i, ns) -- TODO also support file descriptor form as well as pid local ok, err = nl.newlink(i.index, 0, 0, 0, "net_ns_pid", ns) if not ok then return nil, err end return true -- no longer here so cannot refresh end, rename = function(i, name) local ok, err = nl.newlink(i.index, 0, 0, 0, "ifname", name) if not ok then return nil, err end i.name = name -- refresh not working otherwise as done by name TODO fix so by index return i:refresh() end, refresh = function(i) local j, err = nl.interface(i.name) if not j then return nil, err end for k, _ in pairs(i) do i[k] = nil end for k, v in pairs(j) do i[k] = v end return i end, } } mt.iflink = { __index = function(i, k) if meth.iflink.index[k] then return meth.iflink.index[k](i) end if meth.iflink.fn[k] then return meth.iflink.fn[k] end if k == "inet" or k == "inet6" then return end -- might not be set, as we add it, kernel does not provide if c.ARPHRD[k] then return i.ifinfo.ifi_type == c.ARPHRD[k] end end, __tostring = function(i) local hw = '' if not i.loopback and i.macaddr then hw = ' HWaddr ' .. tostring(i.macaddr) end local s = i.name .. string.rep(' ', 10 - #i.name) .. 'Link encap:' .. i.typename .. hw .. '\n' if i.inet then for a = 1, #i.inet do s = s .. ' ' .. 'inet addr: ' .. tostring(i.inet[a].addr) .. '/' .. i.inet[a].prefixlen .. '\n' end end if i.inet6 then for a = 1, #i.inet6 do s = s .. ' ' .. 'inet6 addr: ' .. tostring(i.inet6[a].addr) .. '/' .. i.inet6[a].prefixlen .. '\n' end end s = s .. ' ' .. tostring(i.flags) .. ' MTU: ' .. i.mtu .. '\n' s = s .. ' ' .. 'RX packets:' .. i.stats.rx_packets .. ' errors:' .. i.stats.rx_errors .. ' dropped:' .. i.stats.rx_dropped .. '\n' s = s .. ' ' .. 'TX packets:' .. i.stats.tx_packets .. ' errors:' .. i.stats.tx_errors .. ' dropped:' .. i.stats.tx_dropped .. '\n' return s end } meth.rtmsg = { index = { family = function(i) return tonumber(i.rtmsg.rtm_family) end, dst_len = function(i) return tonumber(i.rtmsg.rtm_dst_len) end, src_len = function(i) return tonumber(i.rtmsg.rtm_src_len) end, index = function(i) return tonumber(i.oif) end, flags = function(i) return tonumber(i.rtmsg.rtm_flags) end, dest = function(i) return i.dst or addrtype(i.family) end, source = function(i) return i.src or addrtype(i.family) end, gw = function(i) return i.gateway or addrtype(i.family) end, -- might not be set in Lua table, so return nil iif = function() return nil end, oif = function() return nil end, src = function() return nil end, dst = function() return nil end, }, flags = { -- TODO rework so iterates in fixed order. TODO Do not seem to be set, find how to retrieve. [c.RTF.UP] = "U", [c.RTF.GATEWAY] = "G", [c.RTF.HOST] = "H", [c.RTF.REINSTATE] = "R", [c.RTF.DYNAMIC] = "D", [c.RTF.MODIFIED] = "M", [c.RTF.REJECT] = "!", } } mt.rtmsg = { __index = function(i, k) if meth.rtmsg.index[k] then return meth.rtmsg.index[k](i) end -- if S.RTF[k] then return bit.band(i.flags, S.RTF[k]) ~= 0 end -- TODO see above end, __tostring = function(i) -- TODO make more like output of ip route local s = "dst: " .. tostring(i.dest) .. "/" .. i.dst_len .. " gateway: " .. tostring(i.gw) .. " src: " .. tostring(i.source) .. "/" .. i.src_len .. " if: " .. (i.output or i.oif) return s end, } meth.routes = { fn = { match = function(rs, addr, len) -- exact match if type(addr) == "string" then local sl = addr:find("/", 1, true) if sl then len = tonumber(addr:sub(sl + 1)) addr = addr:sub(1, sl - 1) end if rs.family == c.AF.INET6 then addr = t.in6_addr(addr) else addr = t.in_addr(addr) end end local matches = {} for _, v in ipairs(rs) do if len == v.dst_len then if v.family == c.AF.INET then if addr.s_addr == v.dest.s_addr then matches[#matches + 1] = v end else local match = true for i = 0, 15 do if addr.s6_addr[i] ~= v.dest.s6_addr[i] then match = false end end if match then matches[#matches + 1] = v end end end end matches.tp, matches.family = rs.tp, rs.family return setmetatable(matches, mt.routes) end, refresh = function(rs) local nr = nl.routes(rs.family, rs.tp) for k, _ in pairs(rs) do rs[k] = nil end for k, v in pairs(nr) do rs[k] = v end return rs end, } } mt.routes = { __index = function(i, k) if meth.routes.fn[k] then return meth.routes.fn[k] end end, __tostring = function(is) local s = {} for k, v in ipairs(is) do s[#s + 1] = tostring(v) end return table.concat(s, '\n') end, } meth.ifaddr = { index = { family = function(i) return tonumber(i.ifaddr.ifa_family) end, prefixlen = function(i) return tonumber(i.ifaddr.ifa_prefixlen) end, index = function(i) return tonumber(i.ifaddr.ifa_index) end, flags = function(i) return tonumber(i.ifaddr.ifa_flags) end, scope = function(i) return tonumber(i.ifaddr.ifa_scope) end, } } mt.ifaddr = { __index = function(i, k) if meth.ifaddr.index[k] then return meth.ifaddr.index[k](i) end if c.IFA_F[k] then return bit.band(i.ifaddr.ifa_flags, c.IFA_F[k]) ~= 0 end end } -- TODO functions repetitious local function decode_link(buf, len) local iface = pt.ifinfomsg(buf) buf = buf + nlmsg_align(s.ifinfomsg) len = len - nlmsg_align(s.ifinfomsg) local rtattr = pt.rtattr(buf) local ir = setmetatable({ifinfo = t.ifinfomsg()}, mt.iflink) ffi.copy(ir.ifinfo, iface, s.ifinfomsg) while rta_ok(rtattr, len) do if ifla_decode[rtattr.rta_type] then ifla_decode[rtattr.rta_type](ir, buf + rta_length(0), rta_align(rtattr.rta_len) - rta_length(0)) end rtattr, buf, len = rta_next(rtattr, buf, len) end return ir end local function decode_address(buf, len) local addr = pt.ifaddrmsg(buf) buf = buf + nlmsg_align(s.ifaddrmsg) len = len - nlmsg_align(s.ifaddrmsg) local rtattr = pt.rtattr(buf) local ir = setmetatable({ifaddr = t.ifaddrmsg(), addr = {}}, mt.ifaddr) ffi.copy(ir.ifaddr, addr, s.ifaddrmsg) while rta_ok(rtattr, len) do if ifa_decode[rtattr.rta_type] then ifa_decode[rtattr.rta_type](ir, buf + rta_length(0), rta_align(rtattr.rta_len) - rta_length(0)) end rtattr, buf, len = rta_next(rtattr, buf, len) end return ir end local function decode_route(buf, len) local rt = pt.rtmsg(buf) buf = buf + nlmsg_align(s.rtmsg) len = len - nlmsg_align(s.rtmsg) local rtattr = pt.rtattr(buf) local ir = setmetatable({rtmsg = t.rtmsg()}, mt.rtmsg) ffi.copy(ir.rtmsg, rt, s.rtmsg) while rta_ok(rtattr, len) do if rta_decode[rtattr.rta_type] then rta_decode[rtattr.rta_type](ir, buf + rta_length(0), rta_align(rtattr.rta_len) - rta_length(0)) else error("NYI: " .. rtattr.rta_type) end rtattr, buf, len = rta_next(rtattr, buf, len) end return ir end local function decode_neigh(buf, len) local rt = pt.rtmsg(buf) buf = buf + nlmsg_align(s.rtmsg) len = len - nlmsg_align(s.rtmsg) local rtattr = pt.rtattr(buf) local ir = setmetatable({rtmsg = t.rtmsg()}, mt.rtmsg) ffi.copy(ir.rtmsg, rt, s.rtmsg) while rta_ok(rtattr, len) do if nda_decode[rtattr.rta_type] then nda_decode[rtattr.rta_type](ir, buf + rta_length(0), rta_align(rtattr.rta_len) - rta_length(0)) else error("NYI: " .. rtattr.rta_type) end rtattr, buf, len = rta_next(rtattr, buf, len) end return ir end -- TODO other than the first few these could be a table local nlmsg_data_decode = { [c.NLMSG.NOOP] = function(r, buf, len) return r end, [c.NLMSG.ERROR] = function(r, buf, len) local e = pt.nlmsgerr(buf) if e.error ~= 0 then r.error = t.error(-e.error) else r.ack = true end -- error zero is ACK, others negative return r end, [c.NLMSG.DONE] = function(r, buf, len) return r end, [c.NLMSG.OVERRUN] = function(r, buf, len) r.overrun = true return r end, [c.RTM.NEWADDR] = function(r, buf, len) local ir = decode_address(buf, len) ir.op, ir.newaddr, ir.nl = "newaddr", true, c.RTM.NEWADDR r[#r + 1] = ir return r end, [c.RTM.DELADDR] = function(r, buf, len) local ir = decode_address(buf, len) ir.op, ir.deladdr, ir.nl = "delddr", true, c.RTM.DELADDR r[#r + 1] = ir return r end, [c.RTM.GETADDR] = function(r, buf, len) local ir = decode_address(buf, len) ir.op, ir.getaddr, ir.nl = "getaddr", true, c.RTM.GETADDR r[#r + 1] = ir return r end, [c.RTM.NEWLINK] = function(r, buf, len) local ir = decode_link(buf, len) ir.op, ir.newlink, ir.nl = "newlink", true, c.RTM.NEWLINK r[ir.name] = ir r[#r + 1] = ir return r end, [c.RTM.DELLINK] = function(r, buf, len) local ir = decode_link(buf, len) ir.op, ir.dellink, ir.nl = "dellink", true, c.RTM.DELLINK r[ir.name] = ir r[#r + 1] = ir return r end, -- TODO need test that returns these, assume updates do [c.RTM.GETLINK] = function(r, buf, len) local ir = decode_link(buf, len) ir.op, ir.getlink, ir.nl = "getlink", true, c.RTM.GETLINK r[ir.name] = ir r[#r + 1] = ir return r end, [c.RTM.NEWROUTE] = function(r, buf, len) local ir = decode_route(buf, len) ir.op, ir.newroute, ir.nl = "newroute", true, c.RTM.NEWROUTE r[#r + 1] = ir return r end, [c.RTM.DELROUTE] = function(r, buf, len) local ir = decode_route(buf, len) ir.op, ir.delroute, ir.nl = "delroute", true, c.RTM.DELROUTE r[#r + 1] = ir return r end, [c.RTM.GETROUTE] = function(r, buf, len) local ir = decode_route(buf, len) ir.op, ir.getroute, ir.nl = "getroute", true, c.RTM.GETROUTE r[#r + 1] = ir return r end, [c.RTM.NEWNEIGH] = function(r, buf, len) local ir = decode_neigh(buf, len) ir.op, ir.newneigh, ir.nl = "newneigh", true, c.RTM.NEWNEIGH r[#r + 1] = ir return r end, [c.RTM.DELNEIGH] = function(r, buf, len) local ir = decode_neigh(buf, len) ir.op, ir.delneigh, ir.nl = "delneigh", true, c.RTM.DELNEIGH r[#r + 1] = ir return r end, [c.RTM.GETNEIGH] = function(r, buf, len) local ir = decode_neigh(buf, len) ir.op, ir.getneigh, ir.nl = "getneigh", true, c.RTM.GETNEIGH r[#r + 1] = ir return r end, } function nl.read(s, addr, bufsize, untildone) addr = addr or t.sockaddr_nl() -- default to kernel bufsize = bufsize or 8192 local reply = t.buffer(bufsize) local ior = t.iovecs{{reply, bufsize}} local m = t.msghdr{msg_iov = ior.iov, msg_iovlen = #ior, msg_name = addr, msg_namelen = ffi.sizeof(addr)} local done = false -- what should we do if we get a done message but there is some extra buffer? could be next message... local r = {} while not done do local len, err = s:recvmsg(m) if not len then return nil, err end local buffer = reply local msg = pt.nlmsghdr(buffer) while not done and nlmsg_ok(msg, len) do local tp = tonumber(msg.nlmsg_type) if nlmsg_data_decode[tp] then r = nlmsg_data_decode[tp](r, buffer + nlmsg_hdrlen, msg.nlmsg_len - nlmsg_hdrlen) if r.overrun then return S.read(s, addr, bufsize * 2) end -- TODO add test if r.error then return nil, r.error end -- not sure what the errors mean though! if r.ack then done = true end else error("unknown data " .. tp) end if tp == c.NLMSG.DONE then done = true end msg, buffer, len = nlmsg_next(msg, buffer, len) end if not untildone then done = true end end return r end -- TODO share with read side local ifla_msg_types = { ifla = { -- IFLA.UNSPEC [c.IFLA.ADDRESS] = t.macaddr, [c.IFLA.BROADCAST] = t.macaddr, [c.IFLA.IFNAME] = "asciiz", -- TODO IFLA.MAP [c.IFLA.MTU] = t.uint32, [c.IFLA.LINK] = t.uint32, [c.IFLA.MASTER] = t.uint32, [c.IFLA.TXQLEN] = t.uint32, [c.IFLA.WEIGHT] = t.uint32, [c.IFLA.OPERSTATE] = t.uint8, [c.IFLA.LINKMODE] = t.uint8, [c.IFLA.LINKINFO] = {"ifla_info", c.IFLA_INFO}, [c.IFLA.NET_NS_PID] = t.uint32, [c.IFLA.NET_NS_FD] = t.uint32, [c.IFLA.IFALIAS] = "asciiz", --[c.IFLA.VFINFO_LIST] = "nested", --[c.IFLA.VF_PORTS] = "nested", --[c.IFLA.PORT_SELF] = "nested", --[c.IFLA.AF_SPEC] = "nested", }, ifla_info = { [c.IFLA_INFO.KIND] = "ascii", [c.IFLA_INFO.DATA] = "kind", }, ifla_vlan = { [c.IFLA_VLAN.ID] = t.uint16, -- other vlan params }, ifa = { -- IFA.UNSPEC [c.IFA.ADDRESS] = "address", [c.IFA.LOCAL] = "address", [c.IFA.LABEL] = "asciiz", [c.IFA.BROADCAST] = "address", [c.IFA.ANYCAST] = "address", -- IFA.CACHEINFO }, rta = { -- RTA_UNSPEC [c.RTA.DST] = "address", [c.RTA.SRC] = "address", [c.RTA.IIF] = t.uint32, [c.RTA.OIF] = t.uint32, [c.RTA.GATEWAY] = "address", [c.RTA.PRIORITY] = t.uint32, [c.RTA.METRICS] = t.uint32, -- RTA.PREFSRC -- RTA.MULTIPATH -- RTA.PROTOINFO -- RTA.FLOW -- RTA.CACHEINFO }, veth_info = { -- VETH_INFO_UNSPEC [c.VETH_INFO.PEER] = {"ifla", c.IFLA}, }, nda = { [c.NDA.DST] = "address", [c.NDA.LLADDR] = t.macaddr, [c.NDA.CACHEINFO] = t.nda_cacheinfo, -- [c.NDA.PROBES] = , }, } --[[ TODO add static const struct nla_policy ifla_vfinfo_policy[IFLA_VF_INFO_MAX+1] = { [IFLA_VF_INFO] = { .type = NLA_NESTED }, }; static const struct nla_policy ifla_vf_policy[IFLA_VF_MAX+1] = { [IFLA_VF_MAC] = { .type = NLA_BINARY, .len = sizeof(struct ifla_vf_mac) }, [IFLA_VF_VLAN] = { .type = NLA_BINARY, .len = sizeof(struct ifla_vf_vlan) }, [IFLA_VF_TX_RATE] = { .type = NLA_BINARY, .len = sizeof(struct ifla_vf_tx_rate) }, [IFLA_VF_SPOOFCHK] = { .type = NLA_BINARY, .len = sizeof(struct ifla_vf_spoofchk) }, }; static const struct nla_policy ifla_port_policy[IFLA_PORT_MAX+1] = { [IFLA_PORT_VF] = { .type = NLA_U32 }, [IFLA_PORT_PROFILE] = { .type = NLA_STRING, .len = PORT_PROFILE_MAX }, [IFLA_PORT_VSI_TYPE] = { .type = NLA_BINARY, .len = sizeof(struct ifla_port_vsi)}, [IFLA_PORT_INSTANCE_UUID] = { .type = NLA_BINARY, .len = PORT_UUID_MAX }, [IFLA_PORT_HOST_UUID] = { .type = NLA_STRING, .len = PORT_UUID_MAX }, [IFLA_PORT_REQUEST] = { .type = NLA_U8, }, [IFLA_PORT_RESPONSE] = { .type = NLA_U16, }, }; ]] local function ifla_getmsg(args, messages, values, tab, lookup, kind, af) local msg = table.remove(args, 1) local value, len local tp if type(msg) == "table" then -- for nested attributes local nargs = msg len = 0 while #nargs ~= 0 do local nlen nlen, nargs, messages, values, kind = ifla_getmsg(nargs, messages, values, tab, lookup, kind, af) len = len + nlen end return len, args, messages, values, kind end if type(msg) == "cdata" or type(msg) == "userdata" then tp = msg value = table.remove(args, 1) if not value then error("not enough arguments") end value = mktype(tp, value) len = ffi.sizeof(value) messages[#messages + 1] = tp values[#values + 1] = value return len, args, messages, values, kind end local rawmsg = msg msg = lookup[msg] tp = ifla_msg_types[tab][msg] if not tp then error("unknown message type " .. tostring(rawmsg) .. " in " .. tab) end if tp == "kind" then local kinds = { vlan = {"ifla_vlan", c.IFLA_VLAN}, veth = {"veth_info", c.VETH_INFO}, } tp = kinds[kind] end if type(tp) == "table" then value = t.rtattr{rta_type = msg} -- missing rta_len, but have reference and can fix messages[#messages + 1] = t.rtattr values[#values + 1] = value tab, lookup = tp[1], tp[2] len, args, messages, values, kind = ifla_getmsg(args, messages, values, tab, lookup, kind, af) len = nlmsg_align(s.rtattr) + len value.rta_len = len return len, args, messages, values, kind -- recursion base case, just a value, not nested else value = table.remove(args, 1) if not value then error("not enough arguments") end end if tab == "ifla_info" and msg == c.IFLA_INFO.KIND then kind = value end local slen if tp == "asciiz" then -- zero terminated tp = t.buffer(#value + 1) slen = nlmsg_align(s.rtattr) + #value + 1 elseif tp == "ascii" then -- not zero terminated tp = t.buffer(#value) slen = nlmsg_align(s.rtattr) + #value else if tp == "address" then tp = adtt[tonumber(af)] end value = mktype(tp, value) end len = nlmsg_align(s.rtattr) + nlmsg_align(ffi.sizeof(tp)) slen = slen or len messages[#messages + 1] = t.rtattr messages[#messages + 1] = tp values[#values + 1] = t.rtattr{rta_type = msg, rta_len = slen} values[#values + 1] = value return len, args, messages, values, kind end local function ifla_f(tab, lookup, af, ...) local len, kind local messages, values = {t.nlmsghdr}, {false} local args = {...} while #args ~= 0 do len, args, messages, values, kind = ifla_getmsg(args, messages, values, tab, lookup, kind, af) end local len = 0 local offsets = {} local alignment = nlmsg_align(1) for i, tp in ipairs(messages) do local item_alignment = align(ffi.sizeof(tp), alignment) offsets[i] = len len = len + item_alignment end local buf = t.buffer(len) for i = 2, #offsets do -- skip header local value = values[i] if type(value) == "string" then ffi.copy(buf + offsets[i], value) else -- slightly nasty if ffi.istype(t.uint32, value) then value = t.uint32_1(value) end if ffi.istype(t.uint16, value) then value = t.uint16_1(value) end if ffi.istype(t.uint8, value) then value = t.uint8_1(value) end ffi.copy(buf + offsets[i], value, ffi.sizeof(value)) end end return buf, len end local rtpref = { [c.RTM.NEWLINK] = {"ifla", c.IFLA}, [c.RTM.GETLINK] = {"ifla", c.IFLA}, [c.RTM.DELLINK] = {"ifla", c.IFLA}, [c.RTM.NEWADDR] = {"ifa", c.IFA}, [c.RTM.GETADDR] = {"ifa", c.IFA}, [c.RTM.DELADDR] = {"ifa", c.IFA}, [c.RTM.NEWROUTE] = {"rta", c.RTA}, [c.RTM.GETROUTE] = {"rta", c.RTA}, [c.RTM.DELROUTE] = {"rta", c.RTA}, [c.RTM.NEWNEIGH] = {"nda", c.NDA}, [c.RTM.DELNEIGH] = {"nda", c.NDA}, [c.RTM.GETNEIGH] = {"nda", c.NDA}, [c.RTM.NEWNEIGHTBL] = {"ndtpa", c.NDTPA}, [c.RTM.GETNEIGHTBL] = {"ndtpa", c.NDTPA}, [c.RTM.SETNEIGHTBL] = {"ndtpa", c.NDTPA}, } function nl.socket(tp, addr) tp = c.NETLINK[tp] local sock, err = S.socket(c.AF.NETLINK, c.SOCK.RAW, tp) if not sock then return nil, err end if addr then if type(addr) == "table" then addr.type = tp end -- need type to convert group names from string if not ffi.istype(t.sockaddr_nl, addr) then addr = t.sockaddr_nl(addr) end local ok, err = S.bind(sock, addr) if not ok then S.close(sock) return nil, err end end return sock end function nl.write(sock, dest, ntype, flags, af, ...) local a, err = sock:getsockname() -- to get bound address if not a then return nil, err end dest = dest or t.sockaddr_nl() -- kernel destination default local tl = rtpref[ntype] if not tl then error("NYI: ", ntype) end local tab, lookup = tl[1], tl[2] local buf, len = ifla_f(tab, lookup, af, ...) local hdr = pt.nlmsghdr(buf) hdr[0] = {nlmsg_len = len, nlmsg_type = ntype, nlmsg_flags = flags, nlmsg_seq = sock:seq(), nlmsg_pid = a.pid} local ios = t.iovecs{{buf, len}} local m = t.msghdr{msg_iov = ios.iov, msg_iovlen = #ios, msg_name = dest, msg_namelen = s.sockaddr_nl} return sock:sendmsg(m) end -- TODO "route" should be passed in as parameter, test with other netlink types local function nlmsg(ntype, flags, af, ...) ntype = c.RTM[ntype] flags = c.NLM_F[flags] local sock, err = nl.socket("route", {}) -- bind to empty sockaddr_nl, kernel fills address if not sock then return nil, err end local k = t.sockaddr_nl() -- kernel destination local ok, err = nl.write(sock, k, ntype, flags, af, ...) if not ok then sock:close() return nil, err end local r, err = nl.read(sock, k, nil, true) -- true means until get done message if not r then sock:close() return nil, err end local ok, err = sock:close() if not ok then return nil, err end return r end -- TODO do not have all these different arguments for these functions, pass a table for initialization. See also iplink. function nl.newlink(index, flags, iflags, change, ...) if change == 0 then change = c.IFF.NONE end -- 0 should work, but does not flags = c.NLM_F("request", "ack", flags) if type(index) == 'table' then index = index.index end local ifv = {ifi_index = index, ifi_flags = c.IFF[iflags], ifi_change = c.IFF[change]} return nlmsg("newlink", flags, nil, t.ifinfomsg, ifv, ...) end function nl.dellink(index, ...) if type(index) == 'table' then index = index.index end local ifv = {ifi_index = index} return nlmsg("dellink", "request, ack", nil, t.ifinfomsg, ifv, ...) end -- read interfaces and details. function nl.getlink(...) return nlmsg("getlink", "request, dump", nil, t.rtgenmsg, {rtgen_family = c.AF.PACKET}, ...) end -- read routes function nl.getroute(af, tp, tab, prot, scope, ...) local rtm = t.rtmsg{family = af, table = tab, protocol = prot, type = tp, scope = scope} local r, err = nlmsg(c.RTM.GETROUTE, "request, dump", af, t.rtmsg, rtm) if not r then return nil, err end return setmetatable(r, mt.routes) end function nl.routes(af, tp) af = c.AF[af] if not tp then tp = c.RTN.UNICAST end tp = c.RTN[tp] local r, err = nl.getroute(af, tp) if not r then return nil, err end local ifs, err = nl.getlink() if not ifs then return nil, err end local indexmap = {} -- TODO turn into metamethod as used elsewhere for i, v in pairs(ifs) do v.inet, v.inet6 = {}, {} indexmap[v.index] = i end for k, v in ipairs(r) do if ifs[indexmap[v.iif]] then v.input = ifs[indexmap[v.iif]].name end if ifs[indexmap[v.oif]] then v.output = ifs[indexmap[v.oif]].name end if tp > 0 and v.rtmsg.rtm_type ~= tp then r[k] = nil end -- filter unwanted routes end r.family = af r.tp = tp return r end local function preftable(tab, prefix) for k, v in pairs(tab) do if k:sub(1, #prefix) ~= prefix then tab[prefix .. k] = v tab[k] = nil end end return tab end function nl.newroute(flags, rtm, ...) flags = c.NLM_F("request", "ack", flags) rtm = mktype(t.rtmsg, rtm) return nlmsg("newroute", flags, rtm.family, t.rtmsg, rtm, ...) end function nl.delroute(rtm, ...) rtm = mktype(t.rtmsg, rtm) return nlmsg("delroute", "request, ack", rtm.family, t.rtmsg, rtm, ...) end -- read addresses from interface TODO flag cleanup function nl.getaddr(af, ...) local family = c.AF[af] local ifav = {ifa_family = family} return nlmsg("getaddr", "request, root", family, t.ifaddrmsg, ifav, ...) end -- TODO may need ifa_scope function nl.newaddr(index, af, prefixlen, flags, ...) if type(index) == 'table' then index = index.index end local family = c.AF[af] local ifav = {ifa_family = family, ifa_prefixlen = prefixlen or 0, ifa_flags = c.IFA_F[flags], ifa_index = index} --__TODO in __new return nlmsg("newaddr", "request, ack", family, t.ifaddrmsg, ifav, ...) end function nl.deladdr(index, af, prefixlen, ...) if type(index) == 'table' then index = index.index end local family = c.AF[af] local ifav = {ifa_family = family, ifa_prefixlen = prefixlen or 0, ifa_flags = 0, ifa_index = index} return nlmsg("deladdr", "request, ack", family, t.ifaddrmsg, ifav, ...) end function nl.getneigh(index, tab, ...) if type(index) == 'table' then index = index.index end tab.ifindex = index local ndm = t.ndmsg(tab) return nlmsg("getneigh", "request, dump", ndm.family, t.ndmsg, ndm, ...) end function nl.newneigh(index, tab, ...) if type(index) == 'table' then index = index.index end tab.ifindex = index local ndm = t.ndmsg(tab) return nlmsg("newneigh", "request, ack, excl, create", ndm.family, t.ndmsg, ndm, ...) end function nl.delneigh(index, tab, ...) if type(index) == 'table' then index = index.index end tab.ifindex = index local ndm = t.ndmsg(tab) return nlmsg("delneigh", "request, ack", ndm.family, t.ndmsg, ndm, ...) end function nl.interfaces() -- returns with address info too. local ifs, err = nl.getlink() if not ifs then return nil, err end local addr4, err = nl.getaddr(c.AF.INET) if not addr4 then return nil, err end local addr6, err = nl.getaddr(c.AF.INET6) if not addr6 then return nil, err end local indexmap = {} for i, v in pairs(ifs) do v.inet, v.inet6 = {}, {} indexmap[v.index] = i end for i = 1, #addr4 do local v = ifs[indexmap[addr4[i].index]] v.inet[#v.inet + 1] = addr4[i] end for i = 1, #addr6 do local v = ifs[indexmap[addr6[i].index]] v.inet6[#v.inet6 + 1] = addr6[i] end return setmetatable(ifs, mt.iflinks) end function nl.interface(i) -- could optimize just to retrieve info for one local ifs, err = nl.interfaces() if not ifs then return nil, err end return ifs[i] end local link_process_f local link_process = { -- TODO very incomplete. generate? name = function(args, v) return {"ifname", v} end, link = function(args, v) return {"link", v} end, address = function(args, v) return {"address", v} end, type = function(args, v, tab) if v == "vlan" then local id = tab.id if id then tab.id = nil return {"linkinfo", {"kind", "vlan", "data", {"id", id}}} end elseif v == "veth" then local peer = tab.peer tab.peer = nil local peertab = link_process_f(peer) return {"linkinfo", {"kind", "veth", "data", {"peer", {t.ifinfomsg, {}, peertab}}}} end return {"linkinfo", "kind", v} end, } function link_process_f(tab, args) args = args or {} for _, k in ipairs{"link", "name", "type"} do local v = tab[k] if v then if link_process[k] then local a = link_process[k](args, v, tab) for i = 1, #a do args[#args + 1] = a[i] end else error("bad iplink command " .. k) end end end return args end -- TODO better name. even more general, not just newlink. or make this the exposed newlink interface? -- I think this is generally a nicer interface to expose than the ones above, for all functions function nl.iplink(tab) local args = {tab.index or 0, tab.modifier or 0, tab.flags or 0, tab.change or 0} local args = link_process_f(tab, args) return nl.newlink(unpack(args)) end -- TODO iplink may not be appropriate always sort out flags function nl.create_interface(tab) tab.modifier = c.NLM_F.CREATE return nl.iplink(tab) end return nl end return {init = init}
apache-2.0
unusualcrow/redead_reloaded
entities/weapons/rad_itemplacer/shared.lua
1
5283
if SERVER then AddCSLuaFile("shared.lua") SWEP.Weight = 1 SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false end if CLIENT then ClientItemPlacerTbl = {} ClientItemPlacerTbl["teh"] = {} SWEP.DrawAmmo = true SWEP.DrawCrosshair = true SWEP.CSMuzzleFlashes = true SWEP.ViewModelFOV = 74 SWEP.ViewModelFlip = false SWEP.PrintName = "Item Placement Tool" SWEP.Slot = 5 SWEP.Slotpos = 5 function SWEP:DrawWeaponSelection(x, y, wide, tall, alpha) end end SWEP.HoldType = "pistol" SWEP.ViewModel = "models/weapons/v_pistol.mdl" SWEP.WorldModel = "models/weapons/w_pistol.mdl" SWEP.Primary.Swap = Sound("weapons/clipempty_rifle.wav") SWEP.Primary.Sound = Sound("NPC_CombineCamera.Click") SWEP.Primary.Delete1 = Sound("Weapon_StunStick.Melee_Hit") SWEP.Primary.Delete = Sound("Weapon_StunStick.Melee_HitWorld") SWEP.Primary.ClipSize = 1 SWEP.Primary.DefaultClip = 99999 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "pistol" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" SWEP.AmmoType = "Knife" SWEP.ItemTypes = {"info_player_zombie", "info_player_army", "info_lootspawn", "info_npcspawn", "info_evac", "point_radiation"} SWEP.ServersideItems = {"info_player_zombie", "info_player_army", "info_lootspawn", "info_npcspawn", "info_evac", "point_radiation"} SWEP.SharedItems = {} function SWEP:Initialize() if SERVER then self:SetWeaponHoldType(self.HoldType) end end function SWEP:Synch() for k, v in pairs(self.ServersideItems) do local ents = ents.FindByClass(v) local postbl = {} for c, d in pairs(ents) do table.insert(postbl, d:GetPos()) end net.Start("ItemPlacerSynch") net.WriteString(v) net.WriteTable(postbl) net.Send(self.Owner) --local tbl = { Name = v, Ents = postbl } --datastream.StreamToClients( { self.Owner }, "ItemPlacerSynch", tbl ) end end net.Receive("ItemPlacerSynch", function(len) ClientItemPlacerTbl[net.ReadString()] = net.ReadTable() end) --[[function PlacerSynch( handler, id, encoded, decoded ) ClientItemPlacerTbl[ decoded.Name ] = decoded.Ents end datastream.Hook( "ItemPlacerSynch", PlacerSynch )]] function SWEP:Deploy() if SERVER then self:Synch() end self:SendWeaponAnim(ACT_VM_DRAW) return true end function SWEP:Think() if CLIENT then return end if self.Owner:KeyDown(IN_USE) and ((self.NextDel or 0) < CurTime()) then self.NextDel = CurTime() + 1 local tr = util.TraceLine(util.GetPlayerTrace(self.Owner)) local closest local dist = 1000 for k, v in pairs(ents.FindByClass(self.ItemTypes[self:GetNWInt("ItemType", 1)])) do if v:GetPos():Distance(tr.HitPos) < dist then dist = v:GetPos():Distance(tr.HitPos) closest = v end end if IsValid(closest) then closest:Remove() self.Owner:EmitSound(self.Primary.Delete1) self:Synch() end end end function SWEP:Reload() if CLIENT then return end for k, v in pairs(ents.FindByClass(self.ItemTypes[self:GetNWInt("ItemType", 1)])) do v:Remove() end self:Synch() self.Owner:EmitSound(self.Primary.Delete) end function SWEP:Holster() return true end function SWEP:ShootEffects() self.Owner:MuzzleFlash() self.Owner:SetAnimation(PLAYER_ATTACK1) self:SendWeaponAnim(ACT_VM_PRIMARYATTACK) end function SWEP:PlaceItem() local itemtype = self.ItemTypes[self:GetNWInt("ItemType", 1)] local tr = util.TraceLine(util.GetPlayerTrace(self.Owner)) local ent = ents.Create(itemtype) ent:SetPos(tr.HitPos + tr.HitNormal * 5) ent:Spawn() ent.AdminPlaced = true end function SWEP:PrimaryAttack() self:SetNextPrimaryFire(CurTime() + 1) self:EmitSound(self.Primary.Sound, 100, math.random(95, 105)) self:ShootEffects() if SERVER then self:PlaceItem() self:Synch() end end function SWEP:SecondaryAttack() self:SetNextSecondaryFire(CurTime() + 0.5) self:EmitSound(self.Primary.Swap) if SERVER then self:SetNWInt("ItemType", self:GetNWInt("ItemType", 1) + 1) if self:GetNWInt("ItemType", 1) > #self.ItemTypes then self:SetNWInt("ItemType", 1) end end end function SWEP:DrawHUD() draw.SimpleText("PRIMARY FIRE: Place Item SECONDARY FIRE: Change Item Type +USE: Delete Nearest Item Of Current Type RELOAD: Remove All Of Current Item Type", "AmmoFontSmall", ScrW() * 0.5, ScrH() - 120, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) draw.SimpleText("CURRENT ITEM TYPE: " .. self.ItemTypes[self:GetNWInt("ItemType", 1)], "AmmoFontSmall", ScrW() * 0.5, ScrH() - 100, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) for k, v in pairs(self.SharedItems) do for c, d in pairs(ents.FindByClass(v)) do local pos = d:GetPos():ToScreen() if pos.visible then draw.SimpleText(v, "AmmoFontSmall", pos.x, pos.y - 15, Color(80, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) draw.RoundedBox(0, pos.x - 2, pos.y - 2, 4, 4, Color(255, 255, 255)) end end end for k, v in pairs(ClientItemPlacerTbl) do for c, d in pairs(v) do local vec = Vector(d[1], d[2], d[3]) local pos = vec:ToScreen() if pos.visible then draw.SimpleText(k, "AmmoFontSmall", pos.x, pos.y - 15, Color(80, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) draw.RoundedBox(0, pos.x - 2, pos.y - 2, 4, 4, Color(255, 255, 255)) end end end end
mit