repo_name
stringlengths
6
78
path
stringlengths
4
206
copies
stringclasses
281 values
size
stringlengths
4
7
content
stringlengths
625
1.05M
license
stringclasses
15 values
SalvationDevelopment/Salvation-Scripts-Production
c30741334.lua
7
1452
--熱血指導王ジャイアントレーナー function c30741334.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,nil,8,3) c:EnableReviveLimit() --draw local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DRAW+CATEGORY_DAMAGE) e1:SetDescription(aux.Stringid(30741334,0)) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(3,30741334) e1:SetCost(c30741334.cost) e1:SetTarget(c30741334.target) e1:SetOperation(c30741334.operation) c:RegisterEffect(e1) end function c30741334.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetCurrentPhase()==PHASE_MAIN1 and e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_BP) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH) e1:SetTargetRange(1,0) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) end function c30741334.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c30741334.operation(e,tp,eg,ep,ev,re,r,rp,chk) local ct=Duel.Draw(tp,1,REASON_EFFECT) if ct==0 then return end local dc=Duel.GetOperatedGroup():GetFirst() Duel.ConfirmCards(1-tp,dc) if dc:IsType(TYPE_MONSTER) then Duel.Damage(1-tp,800,REASON_EFFECT) end Duel.ShuffleHand(tp) end
gpl-2.0
smartdevicelink/sdl_atf_test_scripts
test_scripts/Resumption/InteriorVehicleData/021_InteriorVD_resumption_in_3rd_ignition_cycle.lua
1
2716
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0188-get-interior-data-resumption.md -- -- Description: SDL resumes interior vehicle data in 3rd ignition cycle -- -- Precondition: -- 1. HMI and SDL are started -- 2. Mobile app with REMOTE_CONTROL hmi type is registered and activated -- 3. App is subscribed to moduleType_1 via GetInteriorVehicleData(moduleType_1) -- -- Sequence: -- 1. Two IGN_OFF and IGN_ON cycles are performed -- 2. App starts registration with actual hashId after IGN_ON in 3rd ignition cycle -- SDL does: -- - a. send RC.GetInteriorVehicleData(subscribe=true, moduleType_1, default moduleId) to HMI during resumption data -- 3. HMI sends successful RC.GetInteriorVehicleData(moduleType_1, isSubscribed = true) response to SDL -- SDL does: -- - a. respond RAI(success=true, result code = SUCCESS) to mobile app -- - b. update hashId after successful resumption --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local common = require('test_scripts/Resumption/InteriorVehicleData/commonResumptionsInteriorVD') --[[ Local Variables ]] local moduleType = common.modules[1] local default = nil local appSessionId = 1 --[[ Local Functions ]] local function checkResumptionData() local defaultModuleNumber = 1 local modulesCount = 1 local expectedModules = { { moduleType = moduleType, subscribe = true, moduleId = common.getModuleId(moduleType, defaultModuleNumber) } } common.checkResumptionData(modulesCount, expectedModules, true) end --[[ Scenario ]] common.Title("Preconditions") common.Step("Clean environment", common.preconditions) common.Step("Start SDL, HMI, connect Mobile, start Session", common.start) common.Step("App registration", common.registerAppWOPTU) common.Step("App activation", common.activateApp) common.Step("Add interiorVD subscription", common.GetInteriorVehicleData, { moduleType, default, common.IVDataSubscribeAction.subscribe }) common.Title("Test") common.Step("Ignition off", common.ignitionOff) common.Step("Start SDL, HMI, connect Mobile, start Session", common.start) common.Step("Ignition off", common.ignitionOff) common.Step("Start SDL, HMI, connect Mobile, start Session", common.start) common.Step("Re-register App resumption data", common.reRegisterApp, { appSessionId, checkResumptionData, common.resumptionFullHMILevel }) common.Step("Check subscription with OnInteriorVD", common.onInteriorVD, { moduleType }) common.Title("Postconditions") common.Step("Stop SDL", common.postconditions)
bsd-3-clause
DeinFreund/Zero-K-Infrastructure
MissionEditor/MissionEditor2/MissionBase/LuaRules/Gadgets/mission_runner.lua
2
66867
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Mission Runner", desc = "Runs missions built with the mission editor", author = "quantum", date = "Sept 03, 2008", license = "GPL v2 or later", layer = 0, enabled = true -- loaded by default? } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if not VFS.FileExists("mission.lua") then return end local callInList = { -- events forwarded to unsynced "UnitFinished", } VFS.Include("savetable.lua") local magic = "--mt\r\n" local SAVE_FILE = "Gadgets/mission_runner.lua" -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- SYNCED -- if (gadgetHandler:IsSyncedCode()) then -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- VFS.Include("LuaRules/Configs/mission_config.lua") local mission = VFS.Include("mission.lua") local triggers = mission.triggers -- array local allTriggers = {unpack(triggers)} -- we'll never remove triggers from here, so the indices will stay correct local unitGroups = {} -- key: unitID, value: group set (an array of strings) local cheatingWasEnabled = false local scores = {} local gameStarted = false local currCutsceneID local currCutsceneIsSkippable local events = {} -- key: frame, value: event array local counters = {} -- key: name, value: count local countdowns = {} -- key: name, value: frame local displayedCountdowns = {} -- key: name local lastFinishedUnits = {} -- key: teamID, value: unitID local allowTransfer = false local factoryExpectedUnits = {} -- key: factoryID, value: {unitDefID, groups: group set} local repeatFactoryGroups = {} -- key: factoryID, value: group set local ghosts = {} -- key: incrementing index, value: unit details -- TODO local objectives = {} -- [index] = {id, title, description, color, unitsOrPositions = {}} -- important: widget must be able to access on demand local persistentMessages = {} --[index] = {} -- ditto local unitsWithObjectives = {} local wantUpdateDisabledUnits = false _G.displayedCountdowns = displayedCountdowns _G.lastFinishedUnits = lastFinishedUnits _G.factoryExpectedUnits = factoryExpectedUnits _G.repeatFactoryGroups = repeatFactoryGroups _G.objectives = objectives _G.persistentMessages = persistentMessages for _, counter in ipairs(mission.counters) do counters[counter] = 0 end local shiftOptsTable = {"shift"} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function TakeRandomI(t) return t[math.random(#t)] end local function CopyTable(original) -- Warning: circular table references lead to an infinite loop. local copy = {} for k, v in pairs(original) do if (type(v) == "table") then copy[k] = CopyTable(v) else copy[k] = v end end return copy end local function ArrayToSet(array) local set = {} for i=1, #array do set[array[i]] = true end return set end local function DoSetsIntersect(set1, set2) for key in pairs(set1) do if set2[key] then return true end end return false end local function MergeSets(set1, set2) local result = {} for key in pairs(set1) do result[key] = true end for key in pairs(set2) do result[key] = true end return result end -- overrules the transfer prohibition local function SpecialTransferUnit(...) local oldAllowTransferState = allowTransfer allowTransfer = true Spring.TransferUnit(...) allowTransfer = oldAllowTransferState end local function FindFirstLogic(logicType) for _, trigger in ipairs(triggers) do for _, logicItem in ipairs(trigger.logic) do if logicItem.logicType == logicType then return logicItem, trigger end end end end local function FindAllLogic(logicType) local logicItems = {} for _, trigger in ipairs(triggers) do for _, logicItem in ipairs(trigger.logic) do if logicItem.logicType == logicType then --logicItems[logicItem] = trigger -- we'll want to iterate this table using pairs, so just to be safe don't use table keys logicItems[#logicItems+1] = {logicItem, trigger} end end end return logicItems end local function ArraysHaveIntersection(array1, array2) for _, item1 in ipairs(array1) do for _, item2 in ipairs(array2) do if item1 == item2 then return true end end end return false end local function RemoveTrigger(trigger) for i=1, #triggers do if triggers[i] == trigger then table.remove(triggers, i) break end end end local function ArrayContains(array, item) for i=1, #array do if item == array[i] then return true end end return false end local function StartsWith(s, startString) return string.sub(s, 1, #startString) == startString end local function CountTableElements(t) local count = 0 for _ in pairs(t) do count = count + 1 end return count end local function GetUnitsInRegion(region, teamID) local regionUnits = {} if Spring.GetTeamInfo(teamID) then for i=1, #region.areas do local area = region.areas[i] local areaUnits if area.category == "cylinder" then areaUnits = Spring.GetUnitsInCylinder(area.x, area.y, area.r, teamID) elseif area.category == "rectangle" then areaUnits = Spring.GetUnitsInRectangle(area.x, area.y, area.x + area.width, area.y + area.height, teamID) else error "area category not supported" end for _, unitID in ipairs(areaUnits) do regionUnits[unitID] = true end end end return regionUnits end local function IsUnitInRegion(unitID, region) local x, y, z = Spring.GetUnitPosition(unitID) for i=1,#region.areas do local area = region.areas[i] if area.category == "cylinder" then local dist = ( (x - area.x)^2 + (z - area.y)^2 )^0.5 if dist <= area.r then return true end elseif area.category == "rectangle" then local rx1, rx2, rz1, rz2 = area.x, area.x + area.width, area.y, area.y + area.height if x >= rx1 and x <= rx2 and z >= rz1 and z <= rz2 then return true end else error "area category not supported" end end return false end local function GetRegionsUnitIsIn(unitID) local regions = {} local ret = false for i=1,#mission.regions do local region = mission.regions[i] if IsUnitInRegion(unitID, region) then regions[#region + 1] = region ret = true end end if ret then return regions else return nil end end local function FindUnitsInGroup(searchGroup) local results = {} if StartsWith(searchGroup, "Units in ") then for i=1,#mission.regions do local region = mission.regions[i] for playerIndex=1, #mission.players do local player = mission.players[playerIndex] if searchGroup == string.format("Units in %s (%s)", region.name, player) then local teamID = playerIndex - 1 return GetUnitsInRegion(region, teamID) end end end elseif StartsWith(searchGroup, "Latest Factory Built Unit (") then for playerIndex=1, #mission.players do local player = mission.players[playerIndex] if searchGroup == "Latest Factory Built Unit ("..player..")" then local teamID = playerIndex - 1 if lastFinishedUnits[teamID] then results[lastFinishedUnits[teamID]] = true end end end return results elseif StartsWith(searchGroup, "Any Unit (") then for playerIndex=1, #mission.players do local player = mission.players[playerIndex] if searchGroup == "Any Unit ("..player..")" then local teamID = playerIndex - 1 local units = Spring.GetTeamUnits(teamID) local ret = {} for i=1,#units do ret[units[i]] = true end return ret end end end -- static group for unitID, groups in pairs(unitGroups) do if groups[searchGroup] then results[unitID] = true end end return results end -- returns first unitID it finds in a group local function FindUnitInGroup(searchGroup) local results = FindUnitsInGroup(searchGroup) for unitID in pairs(results) do return unitID end end local function FindUnitsInGroups(searchGroups) local results = {} for searchGroup in pairs(searchGroups) do results = MergeSets(results, FindUnitsInGroup(searchGroup)) end return results end local function IsUnitInGroup(unitID, group) return unitGroups[unitID] and unitGroups[unitID][group] end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local disabledUnitDefIDs = {} -- [team] = {[unitDefID1] = true, [unitDefID2] = true, ...} local selectedUnitConditionGroups = {} local unitIsVisibleConditionGroups = {} do local teams = Spring.GetTeamList() for _, trigger in pairs(triggers) do trigger.occurrences = trigger.occurrences or 0 if trigger.maxOccurrences < 0 then trigger.maxOccurrences = math.huge elseif trigger.maxOccurrences == 0 then RemoveTrigger(trigger) end end for i,logic in pairs(FindAllLogic"TimeCondition") do local condition = logic[1] condition.args.period = condition.args.frames end for i,logic in pairs(FindAllLogic"UnitCreatedCondition") do local condition = logic[1] condition.args.unitDefIDs = {} for _, unitName in ipairs(condition.args.units) do condition.args.unitDefIDs[UnitDefNames[unitName].id] = true end end for i,logic in pairs(FindAllLogic"UnitFinishedCondition") do local condition = logic[1] condition.args.unitDefIDs = {} for _, unitName in ipairs(condition.args.units) do condition.args.unitDefIDs[UnitDefNames[unitName].id] = true end end for i,logic in pairs(FindAllLogic"UnitFinishedInFactoryCondition") do local condition = logic[1] condition.args.unitDefIDs = {} for _, unitName in ipairs(condition.args.units) do condition.args.unitDefIDs[UnitDefNames[unitName].id] = true end end for i=1,#teams do local teamID = teams[i] disabledUnitDefIDs[teamID] = {} for _, disabledUnitName in ipairs(mission.disabledUnits) do disabledUnitDefIDs[teamID][UnitDefNames[disabledUnitName].id] = true end end for i,logic in pairs(FindAllLogic("UnitSelectedCondition")) do local condition = logic[1] selectedUnitConditionGroups = MergeSets(selectedUnitConditionGroups, condition.args.groups) end for i,logic in pairs(FindAllLogic("UnitIsVisibleCondition")) do local condition = logic[1] unitIsVisibleConditionGroups = MergeSets(unitIsVisibleConditionGroups, condition.args.groups) end end local function AddUnitGroup(unitID, group) unitGroups[unitID][group] = true if selectedUnitConditionGroups[group] then Spring.SetUnitRulesParam(unitID, "notifyselect", 1) end if unitIsVisibleConditionGroups[group] then Spring.SetUnitRulesParam(unitID, "notifyvisible", 1) end end local function AddUnitGroups(unitID, groups) for group in pairs(groups) do AddUnitGroup(unitID, group) end end local function RemoveUnitGroup(unitID, group) unitGroups[unitID][group] = nil if selectedUnitConditionGroups[group] then Spring.SetUnitRulesParam(unitID, "notifyselect", 0) end if unitIsVisibleConditionGroups[group] then Spring.SetUnitRulesParam(unitID, "notifyvisible", 0) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- actually defined in a bit local function ExecuteTrigger() end local function UnsyncedEventFunc(action) action.args.logicType = action.logicType _G.missionEventArgs = action.args SendToUnsynced("MissionEvent") _G.missionEventArgs = nil end local actionsTable = { CustomAction = function(action) if action.name == "my custom action name" then -- fill in your custom actions end end, CustomAction2 = function(action) if action.args.synced then local func, err = loadstring(action.args.codeStr) if err then error("Failed to load custom action: ".. action.args.codeStr) return end func() else action.args.logicType = action.logicType _G.missionEventArgs = action.args SendToUnsynced"MissionEvent" _G.missionEventArgs = nil end end, DestroyUnitsAction = function(action) for unitID in pairs(FindUnitsInGroup(action.args.group)) do Spring.DestroyUnit(unitID, true, not action.args.explode) end for i=#ghosts,1,-1 do local ghost = ghosts[i] for group in pairs(ghost.groups) do if (group == action.args.group) then SendToUnsynced("GhostRemovedEvent", i) table.remove(ghosts, i) break end end end end, ExecuteTriggersAction = function(action) for _, triggerIndex in ipairs(action.args.triggers) do ExecuteTrigger(allTriggers[triggerIndex]) end end, ExecuteRandomTriggerAction = function(action) local triggerIndex = TakeRandomI(action.args.triggers) ExecuteTrigger(allTriggers[triggerIndex]) end, AllowUnitTransfersAction = function(action) allowTransfer = true GG.mission.allowTransfer = true end, TransferUnitsAction = function(action) for unitID in pairs(FindUnitsInGroup(action.args.group)) do SpecialTransferUnit(unitID, action.args.player, false) end end, ModifyResourcesAction = function(action) local teamID = action.args.player if Spring.GetTeamInfo(teamID) then if action.args.category == "metal" then if action.args.amount > 0 then Spring.AddTeamResource(teamID, "metal", action.args.amount) else Spring.UseTeamResource(teamID, "metal", -action.args.amount) end elseif action.args.category == "energy" then if action.args.amount > 0 then Spring.AddTeamResource(teamID, "energy", action.args.amount) else Spring.UseTeamResource(teamID, "energy", -action.args.amount) end elseif action.args.category == "energy storage" then local _, currentStorage = Spring.GetTeamResources(teamID, "energy") Spring.SetTeamResource(teamID, "es", currentStorage + action.args.amount) elseif action.args.category == "metal storage" then local _, currentStorage = Spring.GetTeamResources(teamID, "metal") Spring.SetTeamResource(teamID, "ms", currentStorage + action.args.amount) end end end, ModifyUnitHealthAction = function(action) for unitID in pairs(FindUnitsInGroup(action.args.group)) do Spring.AddUnitDamage(unitID, action.args.damage, 0, -1, -6) -- weaponID -6 since -1 to -5 are used by engine for various things and ZK does UnitPreDamaged on them end end, MakeUnitsAlwaysVisibleAction = function(action) for unitID in pairs(FindUnitsInGroup(action.args.group)) do Spring.SetUnitAlwaysVisible(unitID, action.args.value) end end, MakeUnitsNeutralAction = function(action) for unitID in pairs(FindUnitsInGroup(action.args.group)) do Spring.SetUnitNeutral(unitID, action.args.value) end end, ModifyCounterAction = function(action) local counter = action.args.counter local value = action.args.value local n = counters[counter] if action.args.action == "Increase" then counters[counter] = n + value elseif action.args.action == "Reduce" then counters[counter] = n - value elseif action.args.action == "Set" then counters[counter] = value elseif action.args.action == "Multiply" then counters[counter] = n * value end for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "CounterModifiedCondition" then local c = condition.args.condition local v = condition.args.value local n = counters[condition.args.counter] if (c == "=" and n == v) or (c == "<" and n < v) or (c == ">" and n > v) or (c == "<=" and n <= v) or (c == ">=" and n >= v) or (c == "!=" and n ~= v) then ExecuteTrigger(trigger) break end end end end end, DisplayCountersAction = function(action) for counter, value in pairs(counters) do Spring.Echo(string.format("Counter %s: %f", counter, value)) end end, ModifyScoreAction = function(action) for _, teamID in ipairs(action.args.players) do if Spring.GetTeamInfo(teamID) then local score = scores[teamID] or 0 if action.args.action == "Increase Score" then score = score + action.args.value elseif action.args.action == "Reduce Score" then score = score - action.args.value elseif action.args.action == "Set Score" then score = action.args.value elseif action.args.action == "Multiply Score" then score = score * action.args.value end scores[teamID] = score Spring.SetTeamRulesParam(teamID, "score", score) end end end, EnableTriggersAction = function(action) for _, triggerIndex in ipairs(action.args.triggers) do allTriggers[triggerIndex].enabled = true end end, DisableTriggersAction = function(action) for _, triggerIndex in ipairs(action.args.triggers) do allTriggers[triggerIndex].enabled = false end end, StartCountdownAction = function(action) local expiry = Spring.GetGameFrame() + action.args.frames countdowns[action.args.countdown] = expiry if action.args.display then displayedCountdowns[action.args.countdown] = true Spring.SetGameRulesParam("countdown:"..action.args.countdown, expiry) end end, CancelCountdownAction = function(action) countdowns[action.args.countdown] = nil displayedCountdowns[action.args.countdown] = nil Spring.SetGameRulesParam("countdown:"..action.args.countdown, "-1") end, ModifyCountdownAction = function(action) if countdowns[action.args.countdown] then local newExpiry if action.args.action == "Extend" then newExpiry = countdowns[action.args.countdown] + action.args.frames elseif action.args.action == "Anticipate" then newExpiry = countdowns[action.args.countdown] - action.args.frames else error"countdown modify mode not supported" end if newExpiry < Spring.GetGameFrame() then -- execute immediatly countdowns[action.args.countdown] = nil displayedCountdowns[action.args.countdown] = nil Spring.SetGameRulesParam("countdown:"..action.args.countdown, "-1") for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "CountdownEndedCondition" and condition.args.countdown == action.args.countdown then ExecuteTrigger(trigger) break end end end else -- change expiry time countdowns[action.args.countdown] = newExpiry if displayedCountdowns[action.args.countdown] then Spring.SetGameRulesParam("countdown:"..action.args.countdown, newExpiry) end end end -- todo: execute trigger if countdown has expired! print Spring.Echo end, CreateUnitsAction = function(action, createdUnits) local gameframe = Spring.GetGameFrame() for _, unit in ipairs(action.args.units) do if Spring.GetTeamInfo(unit.player) then local ud = UnitDefNames[unit.unitDefName] local isBuilding = ud.isBuilding or ud.isFactory or not ud.canMove local cardinalHeading = "n" if unit.heading > 45 and unit.heading <= 135 then cardinalHeading = "e" elseif unit.heading > 135 and unit.heading <= 225 then cardinalHeading = "s" elseif unit.heading > 225 and unit.heading <= 315 then cardinalHeading = "w" end if unit.isGhost then for group in pairs(unit.groups) do unit[#unit + 1] = group end unit.cardinalHeading = cardinalHeading unit.isBuilding = isBuilding local ghostID = #ghosts+1 ghosts[ghostID] = unit _G.ghostEventArgs = unit SendToUnsynced("GhostEvent", ghostID) _G.ghostEventArgs = nil else -- ZK mex placement if ud.customParams.ismex and GG.metalSpots then local function GetClosestMetalSpot(x, z) local bestSpot local bestDist = math.huge local bestIndex for i = 1, #GG.metalSpots do local spot = GG.metalSpots[i] local dx, dz = x - spot.x, z - spot.z local dist = dx*dx + dz*dz if dist < bestDist then bestSpot = spot bestDist = dist bestIndex = i end end return bestSpot end local bestSpot = GetClosestMetalSpot(unit.x, unit.y ) unit.x, unit.y = bestSpot.x, bestSpot.z end local unitID, drop local height = Spring.GetGroundHeight(unit.x, unit.y) if GG.DropUnit and (action.args.useOrbitalDrop) then drop = true unitID = GG.DropUnit(unit.unitDefName, unit.x, height, unit.y, cardinalHeading, unit.player) else unitID = Spring.CreateUnit(unit.unitDefName, unit.x, height, unit.y, cardinalHeading, unit.player) end if action.args.ceg and action.args.ceg ~= '' then Spring.SpawnCEG(action.args.ceg, unit.x, height, unit.y, 0, 1, 0) end if unitID then if not isBuilding then if unit.heading ~= 0 then local heading = (unit.heading - 180)/360 * 2 * math.pi if drop and gameframe > 1 then --Spring.MoveCtrl.SetRotation(unitID, 0, heading, 0) Spring.SetUnitRotation(unitID, 0, heading, 0) else Spring.SetUnitRotation(unitID, 0, heading, 0) end end end createdUnits[unitID] = true if unit.groups and next(unit.groups) then AddUnitGroups(unitID, unit.groups) end end end end end end, ConsoleMessageAction = function(action) Spring.SendMessage(action.args.message) end, DefeatAction = function(action) local aiAllyTeams = {} local playerAllyTeams = {} local teams = Spring.GetTeamList() local gaiaTeam = Spring.GetGaiaTeamID() for i=1,#teams do local team = teams[i] local _, _, _, isAI, _, allyTeam = Spring.GetTeamInfo(team) if (gaiaTeam == team) then -- do nothing elseif not isAI then playerAllyTeams[allyTeam] = true end end for i=1,#teams do local team = teams[i] local _, spectator, _, isAI, _, allyTeam = Spring.GetTeamInfo(team) if (gaiaTeam == team) then -- do nothing elseif isAI and not playerAllyTeams[allyTeam] then aiAllyTeams[#aiAllyTeams+1] = allyTeam else Spring.KillTeam(team) end end Spring.GameOver(aiAllyTeams) end, VictoryAction = function(action) local humanAllyTeams = {} local teams = Spring.GetTeamList() local gaiaTeam = Spring.GetGaiaTeamID() for i=1,#teams do local unitTeam = teams[i] local _, _, _, isAI, _, allyTeam = Spring.GetTeamInfo(unitTeam) if (gaiaTeam == team) then -- do nothing elseif not isAI then humanAllyTeams[#humanAllyTeams+1] = allyTeam end end Spring.GameOver(humanAllyTeams) end, LockUnitsAction = function(action) local teams = action.args.players or {} if CountTableElements(teams) == 0 then teams = Spring.GetTeamList() end for _, disabledUnitName in ipairs(action.args.units) do local disabledUnit = UnitDefNames[disabledUnitName] if disabledUnit then for _,teamID in pairs(teams) do disabledUnitDefIDs[teamID][disabledUnit.id] = true end end end wantUpdateDisabledUnits = true end, UnlockUnitsAction = function(action) local teams = action.args.players or {} if CountTableElements(teams) == 0 then teams = Spring.GetTeamList() end for _, disabledUnitName in ipairs(action.args.units) do local disabledUnit = UnitDefNames[disabledUnitName] if disabledUnit then for _,teamID in pairs(teams) do disabledUnitDefIDs[teamID][disabledUnit.id] = nil end end end wantUpdateDisabledUnits = true end, GiveOrdersAction = function(action, createdUnits) local orderedUnits if not next(action.args.groups) then orderedUnits = createdUnits else orderedUnits = FindUnitsInGroups(action.args.groups) end for unitID in pairs(orderedUnits) do for i, order in ipairs(action.args.orders) do -- bug workaround: the table needs to be copied before it's used in GiveOrderToUnit local x, y, z = order.args[1], order.args[2], order.args[3] if y == 0 then y = Spring.GetGroundHeight(x, z) end local options if i == 1 and (not action.args.queue) then options = 0 else options = shiftOptsTable end Spring.GiveOrderToUnit(unitID, CMD[order.orderType], {x, y, z}, options) end end end, GiveTargetedOrdersAction = function(action, createdUnits) local orderedUnits if not next(action.args.groups) then orderedUnits = createdUnits else orderedUnits = FindUnitsInGroups(action.args.groups) end for unitID in pairs(orderedUnits) do for i, order in ipairs(action.args.orders) do local targets = FindUnitsInGroups(action.args.targetGroups) local target for unitID in pairs(targets) do target = unitID break end local options if i == 1 and (not action.args.queue) then options = 0 else options = shiftOptsTable end Spring.GiveOrderToUnit(unitID, CMD[order.orderType], {target}, options) end end end, GiveFactoryOrdersAction = function(action, createdUnits) local orderedUnits if not next(action.args.factoryGroups) then orderedUnits = createdUnits else orderedUnits = FindUnitsInGroups(action.args.factoryGroups) end for factoryID in pairs(orderedUnits) do local factoryDef = UnitDefs[Spring.GetUnitDefID(factoryID)] local hasBeenGivenOrders = false for _, unitDefName in ipairs(action.args.buildOrders) do local unitDef = UnitDefNames[unitDefName] if ArrayContains(factoryDef.buildOptions, unitDef.id) then Spring.GiveOrderToUnit(factoryID, -unitDef.id, {}, {}) hasBeenGivenOrders = true if next(action.args.builtUnitsGroups) then factoryExpectedUnits[factoryID] = factoryExpectedUnits[factoryID] or {} table.insert(factoryExpectedUnits[factoryID], {unitDefID = unitDef.id, groups = CopyTable(action.args.builtUnitsGroups)}) end end end if hasBeenGivenOrders and action.args.repeatOrders then Spring.GiveOrderToUnit(factoryID, CMD.REPEAT, {1}, {}) repeatFactoryGroups[factoryID] = CopyTable(action.args.builtUnitsGroups) end end end, SendScoreAction = function(action) if not (cheatingWasEnabled) then SendToUnsynced("ScoreEvent") end end, SetCameraUnitTargetAction = function(action) for unitID, groups in pairs(unitGroups) do if groups[action.args.group] then local _,_,_,x,_,y = Spring.GetUnitPosition(unitID, true) local args = { x = x, y = y, logicType = "SetCameraPointTargetAction", } _G.missionEventArgs = args SendToUnsynced("MissionEvent") _G.missionEventArgs = nil break end end end, BeautyShotAction = function(action) for unitID, groups in pairs(unitGroups) do if groups[action.args.group] then local _,_,_,x,y,z = Spring.GetUnitPosition(unitID, true) action.args.x = x action.args.y = y action.args.z = z action.args.unitID = unitID UnsyncedEventFunc(action) break end end end, GuiMessagePersistentAction = function(action) persistentMessages[#persistentMessages+1] = {message = action.args.message, height = action.args.height, width = action.args.width, fontSize = action.args.fontSize, image = action.args.image, imageFromArchive = action.args.imageFromArchive} UnsyncedEventFunc(action) end, AddObjectiveAction = function(action) objectives[#objectives+1] = {id = action.args.id, title = action.args.title, description = action.args.description, status = "Incomplete", unitsOrPositions = {}} UnsyncedEventFunc(action) end, ModifyObjectiveAction = function(action) for i=1,#objectives do local obj = objectives[i] if obj.id == action.args.id then local title = action.args.title if title and title ~= '' then obj.title = title end local description = action.args.description if description and description ~= '' then obj.description = description end obj.status = action.args.status or obj.status break end end UnsyncedEventFunc(action) end, AddUnitsToObjectiveAction = function(action) for i=1,#objectives do local obj = objectives[i] if obj.id == action.args.id then local groupName = action.args.group local units = FindUnitsInGroup(groupName) for unitID in pairs(units) do obj.unitsOrPositions[#obj.unitsOrPositions + 1] = unitID unitsWithObjectives[unitID] = true end action.args.units = units break end end UnsyncedEventFunc(action) end, AddPointToObjectiveAction = function(action) for i=1,#objectives do local obj = objectives[i] if obj.id == action.args.id then obj.unitsOrPositions[#obj.unitsOrPositions + 1] = {action.args.x, action.args.y} break end end UnsyncedEventFunc(action) end, EnterCutsceneAction = function(action) currCutsceneID = action.args.id currCutsceneIsSkippable = action.args.skippable UnsyncedEventFunc(action) end, LeaveCutsceneAction = function(action) currCutsceneID = nil currCutsceneIsSkippable = false UnsyncedEventFunc(action) end, StopCutsceneActionsAction = function(action) local toKillID = action.args.cutsceneID local anyCutscene = (toKillID == "Any Cutscene") local currentCutscene = (toKillID == "Current Cutscene") for frame, eventsAtFrame in pairs(events) do for i=#eventsAtFrame,1,-1 do -- work backwards so we don't mess up the indexes ahead of us when removing table entries local event = eventsAtFrame[i] if anyCutscene or (event.cutsceneID == toKillID) or (currentCutscene and (event.cutsceneID == currCutsceneID)) then table.remove(eventsAtFrame, i) end end end end, } local unsyncedActions = { PauseAction = true, MarkerPointAction = true, SetCameraPointTargetAction = true, SetCameraPosDirAction = true, SaveCameraStateAction = true, RestoreCameraStateAction = true, ShakeCameraAction = true, GuiMessageAction = true, --GuiMessagePersistentAction = true, HideGuiMessagePersistentAction = true, ConvoMessageAction = true, ClearConvoMessageQueueAction = true, AddObjectiveAction = true, ModifyObjectiveAction = true, AddUnitsToObjectiveAction = true, AddPointToObjectiveAction = true, SoundAction = true, MusicAction = true, MusicLoopAction = true, StopMusicAction = true, SunriseAction = true, SunsetAction = true, EnterCutsceneAction = true, LeaveCutsceneAction = true, FadeOutAction = true, FadeInAction = true, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function UpdateDisabledUnits(unitID, teamID) local unitDefID = Spring.GetUnitDefID(unitID) local buildOpts = UnitDefs[unitDefID].buildOptions for i=1,#buildOpts do local buildID = buildOpts[i] local cmdDescID = Spring.FindUnitCmdDesc(unitID, -buildID) if cmdDescID then Spring.EditUnitCmdDesc(unitID, cmdDescID, {disabled = disabledUnitDefIDs[teamID][buildID] or false}) end end end local function UpdateAllDisabledUnits() local units = Spring.GetAllUnits() for i=1,#units do local unitID = units[i] local teamID = Spring.GetUnitTeam(unitID) UpdateDisabledUnits(unitID, teamID) end end local function AddEvent(frame, funcName, args, cutsceneID) events[frame] = events[frame] or {} table.insert(events[frame], {funcName = funcName, args = args, cutsceneID = cutsceneID}) end local function RunEvents(frame) if events[frame] then for _, Event in ipairs(events[frame]) do local func = actionsTable[Event.funcName] if (not func) and unsyncedActions[Event.funcName] then func = UnsyncedEventFunc end func(unpack(Event.args)) -- run event end end events[frame] = nil end local function CustomConditionMet(name) for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "CustomCondition" and trigger.name == name then ExecuteTrigger(trigger) break end end end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- ExecuteTrigger = function(trigger, frame) if not trigger.enabled then return end if math.random() < trigger.probability then if trigger.maxOccurrences == trigger.occurrences then RemoveTrigger(trigger) -- the trigger is no longer needed return end local createdUnits = {} local cutsceneID local frame = frame or (Spring.GetGameFrame() + 1) -- events will take place at this frame for i=1,#trigger.logic do local action = trigger.logic[i] local args = {action, createdUnits, action.logicType} local funcName = action.logicType if action.logicType == "WaitAction" then frame = frame + action.args.frames elseif action.logicType == "EnterCutsceneAction" then cutsceneID = action.args.id elseif action.logicType == "LeaveCutsceneAction" then cutsceneID = nil end if actionsTable[funcName] or unsyncedActions[funcName] then AddEvent(frame, funcName, args, cutsceneID) -- schedule event end end end trigger.occurrences = trigger.occurrences + 1 if trigger.maxOccurrences == trigger.occurrences then RemoveTrigger(trigger) -- the trigger is no longer needed end end local function ExecuteTriggerByName(name, frame) local triggers = GG.mission.triggers for i=1,#triggers do local trigger = triggers[i] if trigger and trigger.name == name then ExecuteTrigger(trigger, frame) --break end end end local function SetTriggerEnabledByName(name, enabled) local triggers = GG.mission.triggers for i=1,#triggers do local trigger = triggers[i] if trigger and trigger.name == name then trigger.enabled = enabled end end end local function CheckUnitsEnteredGroups(unitID, condition) if not next(condition.args.groups) then return true end -- no group selected: any unit is ok if not unitGroups[unitID] then return false end -- group is required but unit has no group if DoSetsIntersect(condition.args.groups, unitGroups[unitID]) then return true end -- unit has one of the required groups return false end local function CheckUnitsEnteredPlayer(unitID, condition) if not condition.args.players[1] then return true end -- no player is required: any is ok return ArrayContains(condition.args.players, Spring.GetUnitTeam(unitID)) -- unit is is owned by one of the selected players end local function CheckUnitsEntered(units, condition) local count = 0 for _, unitID in ipairs(units) do if CheckUnitsEnteredGroups(unitID, condition) and CheckUnitsEnteredPlayer(unitID, condition) then count = count + 1 end end return count >= condition.args.number end local function SendMissionVariables(tbl) if not (tbl and type(tbl) == "table") then Spring.Log(gadget:GetInfo().name, "error", "Invalid argument for SendMissionVariables") return end local str = "" for k,v in pairs(tbl) do str = str .. k .. "=" .. v .. ";" end local str64 = "MISSIONVARS: " .. GG.Base64Encode(str) print(str64) Spring.Echo(str64) end local function SetAllyTeamLongName(allyTeamID, name) Spring.SetGameRulesParam("allyteam_long_name_" .. allyTeamID, name) end local function SetAllyTeamShortName(allyTeamID, name) Spring.SetGameRulesParam("allyteam_short_name_" .. allyTeamID, name) end local function SendObjectivesToUnsynced() _G.objectives = objectives SendToUnsynced("SendMissionObjectives") end local function SendPersistentMessagesToUnsynced() _G.persistentMessages = persistentMessages SendToUnsynced("SendMissionPersistentMessages") end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:UnitDamaged(unitID, unitDefID, unitTeam, damage, paralyzer, weaponID, attackerID, attackerDefID, attackerTeam) local toExecute = {} for triggerIndex=1, #triggers do local trigger = triggers[triggerIndex] for conditionIndex=1, #trigger.logic do local condition = trigger.logic[conditionIndex] if condition.logicType == "UnitDamagedCondition" and --not paralyzer and (Spring.GetUnitHealth(unitID) < condition.args.value) and (condition.args.anyAttacker or FindUnitsInGroup(condition.args.attackerGroup)[attackerID]) and (condition.args.anyVictim or FindUnitsInGroup(condition.args.victimGroup)[unitID]) then toExecute[#toExecute + 1] = trigger break end end end -- do it this way to avoid the problem when you remove elements from a table while still iterating over it for i=1,#toExecute do ExecuteTrigger(toExecute[i]) end end function gadget:AllowUnitTransfer(unitID, unitDefID, oldTeam, newTeam, capture) return capture or allowTransfer end function gadget:GamePreload() for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "GamePreloadCondition" then ExecuteTrigger(trigger, -1) end end end RunEvents(-1) end function gadget:GameFrame(n) if not gameStarted then for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "GameStartedCondition" then ExecuteTrigger(trigger, n) end end end if mission.debug then Spring.SendCommands("setmaxspeed 100") end for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "PlayerJoinedCondition" then local players = Spring.GetPlayerList(condition.args.playerNumber, true) if players[1] then ExecuteTrigger(trigger) break end end end end gameStarted = true end RunEvents(n) for countdown, expiry in pairs(countdowns) do if n == expiry then countdowns[countdown] = nil displayedCountdowns[countdown] = nil for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "CountdownEndedCondition" and condition.args.countdown == countdown then ExecuteTrigger(trigger) break end end end end for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "CountdownTickCondition" and condition.args.countdown == countdown and (expiry - n) % condition.args.frames == 0 then ExecuteTrigger(trigger) break end if condition.logicType == "TimeLeftInCountdownCondition" and condition.args.countdown == countdown and (expiry - n) < condition.args.frames then ExecuteTrigger(trigger) break end end end end for _, trigger in pairs(triggers) do for _, condition in ipairs(trigger.logic) do local args = condition.args if condition.logicType == "TimeCondition" and args.frames == n then args.frames = n + args.period ExecuteTrigger(trigger) break end end end for _, trigger in pairs(triggers) do for _, condition in ipairs(trigger.logic) do local args = condition.args if condition.logicType == "TimerCondition" and args.frames == n then ExecuteTrigger(trigger) break end end end if Spring.IsCheatingEnabled() then if not cheatingWasEnabled then cheatingWasEnabled = true GG.mission.cheatingWasEnabled = true Spring.Echo "The score will not be saved." end end if (n+3)%30 == 0 then for _, trigger in pairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "UnitsAreInAreaCondition" then local areas = condition.args.areas for _, area in ipairs(areas) do local units if area.category == "cylinder" then units = Spring.GetUnitsInCylinder(area.x, area.y, area.r) elseif area.category == "rectangle" then units = Spring.GetUnitsInRectangle(area.x, area.y, area.x + area.width, area.y + area.height) else error "area category not supported" end if CheckUnitsEntered(units, condition) then ExecuteTrigger(trigger) break end end end end end end if wantUpdateDisabledUnits then UpdateAllDisabledUnits() wantUpdateDisabledUnits = false end end function gadget:GameOver() for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "GameEndedCondition" then ExecuteTrigger(trigger) break end end end end function gadget:TeamDied(teamID) for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "PlayerDiedCondition" and condition.args.playerNumber == teamID then ExecuteTrigger(trigger) break end end end end function gadget:UnitDestroyed(unitID, unitDefID, unitTeam) for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "UnitDestroyedCondition" then -- check if the unit is in a region the trigger is watching for groupName in pairs(condition.args.groups) do if FindUnitsInGroup(groupName)[unitID] then ExecuteTrigger(trigger) break end end end end end unitGroups[unitID] = nil factoryExpectedUnits[unitID] = nil repeatFactoryGroups[unitID] = nil if unitsWithObjectives[unitID] then for i=1, #objectives do local obj = objectives[i] for j=#obj.unitsOrPositions, 1, -1 do unitOrPos = obj.unitsOrPositions[j] if unitOrPos == unitID then table.remove(obj.unitsOrPositions, j) end end end unitsWithObjectives[unitID] = nil end end function gadget:UnitFromFactory(unitID, unitDefID, unitTeam, factID, factDefID, userOrders) lastFinishedUnits[unitTeam] = unitID -- assign groups if repeatFactoryGroups[factID] then for group in pairs(repeatFactoryGroups[factID]) do AddUnitGroup(unitID, group) end elseif factoryExpectedUnits[factID] then if factoryExpectedUnits[factID][1].unitDefID == unitDefID then for group in pairs(factoryExpectedUnits[factID][1].groups) do AddUnitGroup(unitID, group) end table.remove(factoryExpectedUnits[factID], 1) end end for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "UnitFinishedInFactoryCondition" and (condition.args.unitDefIDs[unitDefID] or not condition.args.units[1]) then if not next(condition.args.players) or ArrayContains(condition.args.players, unitTeam) then ExecuteTrigger(trigger) break end end end end end function gadget:UnitFinished(unitID, unitDefID, unitTeam) for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "UnitFinishedCondition" and (condition.args.unitDefIDs[unitDefID] or not condition.args.units[1]) then if not next(condition.args.players) or ArrayContains(condition.args.players, unitTeam) then ExecuteTrigger(trigger) break end end end end end function gadget:UnitCreated(unitID, unitDefID, unitTeam) unitGroups[unitID] = unitGroups[unitID] or {} for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "UnitCreatedCondition" and (condition.args.unitDefIDs[unitDefID] or not condition.args.units[1]) then if not next(condition.args.players) or ArrayContains(condition.args.players, unitTeam) then ExecuteTrigger(trigger) break end end end end UpdateDisabledUnits(unitID, unitTeam) end function gadget:UnitTaken(unitID, unitDefID, oldTeam, newTeam) UpdateDisabledUnits(unitID, newTeam) end -- ZK custom functions function gadget:AllowCommand_GetWantedCommand() return true end function gadget:AllowCommand_GetWantedUnitDefID() return true end function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions, cmdTag, synced) --if isInCutscene and (not synced) then -- return false --end -- prevent widgets from building disabled units if disabledUnitDefIDs[teamID][-cmdID] then local luaAI = Spring.GetTeamLuaAI(teamID) or '' return (luaAI ~= '') and EXEMPT_AI_FROM_UNIT_LOCK end return true end local function Deserialize(text) local f, err = loadstring(text) if not f then Spring.Echo("error while deserializing (compiling): "..tostring(err)) return end setfenv(f, {}) -- sandbox for security and cheat prevention local success, arg = pcall(f) if not success then Spring.Echo("error while deserializing (calling): "..tostring(arg)) return end return arg end function gadget:RecvLuaMsg(msg, player) local _, _, _, teamID = Spring.GetPlayerInfo(player) if StartsWith(msg, magic) then local args = Deserialize(msg) if args.type == "notifyGhostBuilt" then for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "UnitBuiltOnGhostCondition" then if teamID == args.teamID and not next(condition.args.groups) or DoSetsIntersect(condition.args.groups, args.groups) then for group in pairs(args.groups) do AddUnitGroup(args.unitID, group) end ExecuteTrigger(trigger) break end end end end end elseif StartsWith(msg, "notifyselect ") then local unitID = tonumber(string.match(msg, "%d+")) for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "UnitSelectedCondition" then if not next(condition.args.players) or ArrayContains(condition.args.players, teamID) then for groupName in pairs(condition.args.groups) do if FindUnitsInGroup(groupName)[unitID] then ExecuteTrigger(trigger) break end end end end end end elseif StartsWith(msg, "notifyvisible ") then local unitID = tonumber(string.match(msg, "%d+")) for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do if condition.logicType == "UnitIsVisibleCondition" then if not next(condition.args.players) or ArrayContains(condition.args.players, teamID) then for groupName in pairs(condition.args.groups) do if FindUnitsInGroup(groupName)[unitID] then ExecuteTrigger(trigger) break end end end end end end elseif StartsWith(msg, "sendMissionObjectives") then SendObjectivesToUnsynced() elseif StartsWith(msg, "sendMissionPersistentMessages") then SendPersistentMessagesToUnsynced() elseif StartsWith(msg, "skipCutscene") then if currCutsceneID and currCutsceneIsSkippable then for _, trigger in ipairs(triggers) do for _, condition in ipairs(trigger.logic) do local conditionCutsceneID = condition.args.cutsceneID if condition.logicType == "CutsceneSkippedCondition" and ((conditionCutsceneID == currCutsceneID) or (conditionCutsceneID == "Any Cutscene") or (conditionCutsceneID == "Current Cutscene")) then ExecuteTrigger(trigger) end end end end end end -- function gadget:AllowResourceTransfer() -- return false -- end local function MakeGGTable() GG.mission = { scores = scores, counters = counters, countdowns = countdowns, unitGroups = unitGroups, triggers = triggers, allTriggers = allTriggers, objectives = objectives, persistentMessages = persistentMessages, cheatingWasEnabled = cheatingWasEnabled, allowTransfer = allowTransfer, GetUnitsInRegion = GetUnitsInRegion, IsUnitInRegion = IsUnitInRegion, FindUnitsInGroup = FindUnitsInGroup, FindUnitInGroup = FindUnitInGroup, FindUnitsInGroups = FindUnitsInGroups, IsUnitInGroup = IsUnitInGroup, AddUnitGroup = AddUnitGroup, RemoveUnitGroup = RemoveUnitGroup, RunEvents = RunEvents, ExecuteTrigger = ExecuteTrigger, ExecuteTriggerByName = ExecuteTriggerByName, SetTriggerEnabledByName = SetTriggerEnabledByName, SendMissionVariables = SendMissionVariables, SetAllyTeamLongName = SetAllyTeamLongName, SetAllyTeamShortName = SetAllyTeamShortName, } _G.mission = GG.mission _G.mission.events = events end function gadget:Initialize() MakeGGTable() -- Set up the forwarding calls to the unsynced part of the gadget. -- This does not overwrite the calls in the synced part. local SendToUnsynced = SendToUnsynced for _, callIn in pairs(callInList) do local fun = gadget[callIn] if (fun ~= nil) then gadget[callIn] = function(self, ...) SendToUnsynced(callIn, ...) return fun(self, ...) end else gadget[callIn] = function(self, ...) SendToUnsynced(callIn, ...) end end gadgetHandler:UpdateCallIn(callIn) end -- ZK allyteam name API (defaults) local allyTeamsNamed = {} local teams = Spring.GetTeamList() for i=0,#teams do local teamID, leader, _, isAITeam, _, allyTeamID = Spring.GetTeamInfo(i) if leader and (not allyTeamsNamed[allyTeamID]) then local name if isAITeam then name = select(2, Spring.GetAIInfo(teamID)) else name = Spring.GetPlayerInfo(leader) end if name then Spring.SetGameRulesParam("allyteam_long_name_"..allyTeamID, name) Spring.SetGameRulesParam("allyteam_short_name_"..allyTeamID, name) allyTeamsNamed[allyTeamID] = true end end end end function gadget:UnitEnteredLos(unitID, unitTeam, allyTeam, unitDefID) for i=1,#triggers do for j=1,#triggers[i].logic do local condition = triggers[i].logic[j] if condition.logicType == "UnitEnteredLOSCondition" then if not next(condition.args.alliances) or ArrayContains(condition.args.alliances, allyTeam) then for groupName in pairs(condition.args.groups) do if FindUnitsInGroup(groupName)[unitID] then ExecuteTrigger(triggers[i]) break end end end end end end end local function LoadAllTriggers(current, loaded) for triggerIndex, data in pairs(loaded) do current[triggerIndex].enabled = data.enabled current[triggerIndex].occurrences = data.occurrences end end local function LoadTriggers(current, loaded) local newTriggers = {} for triggerIndex,data in pairs(loaded) do for _,data2 in pairs(current) do if data2.name == data.name then data2.enabled = data.enabled data2.occurences = data.occurences newTriggers[triggerIndex] = data2 break end end end return newTriggers end function gadget:Load(zip) if not GG.SaveLoad then Spring.Log(gadget:GetInfo().name, LOG.WARNING, "Save/Load API not found") return end local data = GG.SaveLoad.ReadFile(zip, "Mission Runner", SAVE_FILE) if data then scores = data.scores counters = data.counters countdowns = data.countdowns displayedCountdowns = data.displayedCountdowns unitGroups = GG.SaveLoad.GetNewUnitIDKeys(data.unitGroups) repeatFactoryGroups = GG.SaveLoad.GetNewUnitIDKeys(data.repeatFactoryGroups) factoryExpectedUnits = GG.SaveLoad.GetNewUnitIDKeys(data.factoryExpectedUnits) objectives = data.objectives persistentMessages = data.persistentMessages cheatingWasEnabled = data.cheatingWasEnabled allowTransfer = data.allowTransfer --triggers = data.triggers --allTriggers = data.allTriggers triggers = LoadTriggers(triggers, data.triggers) LoadAllTriggers(allTriggers, data.allTriggers) lastFinishedUnits = GG.SaveLoad.GetNewUnitIDValues(data.lastFinishedUnits) -- reset events gameframes local eventsTemp = {} local savedFrame = GG.SaveLoad.GetSavedGameFrame() for frame, eventsThatFrame in pairs(data.events) do eventsTemp[frame - savedFrame] = eventsThatFrame end events = eventsTemp -- update object references MakeGGTable() end gameStarted = true -- TODO transmit ghosts as well end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- UNSYNCED -- else -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- need this because SYNCED.tables are merely proxies, not real tables local function MakeRealTable(proxy) local proxyLocal = proxy local ret = {} for i,v in spairs(proxyLocal) do if type(v) == "table" then ret[i] = MakeRealTable(v) else ret[i] = v end end return ret end function WrapToLuaUI() if Script.LuaUI("MissionEvent") then local missionEventArgs = {} local missionEventArgsSynced = SYNCED.missionEventArgs for k, v in spairs(missionEventArgsSynced) do missionEventArgs[k] = v end Script.LuaUI.MissionEvent(missionEventArgs) end end local ghosts = {} local cardinalHeadings = {s = 0, w = 90, n = 180, e = 270} function GhostEvent(_, ghostID) local ghost= {} local ghostSynced = SYNCED.ghostEventArgs for k, v in spairs(ghostSynced) do ghost[k] = v end ghosts[ghostID] = ghost local _, _, _, teamID = Spring.GetPlayerInfo(ghost.player) ghost.unitDefID = UnitDefNames[ghost.unitDefName].id ghost.teamID = teamID if ghost.isBuilding then local ch = ghost.cardinalHeading or "n" ghost.heading = cardinalHeadings[ch] or ghost.heading end end function GhostRemovedEvent(_,ghostID) table.remove(ghosts, ghostID) end local startTime = Spring.GetTimer() function gadget:DrawWorld() for ghostID, ghost in pairs(ghosts) do gl.PushMatrix() gl.LoadIdentity() local t = Spring.DiffTimers(Spring.GetTimer(), startTime) local alpha = (math.sin(t*6)+1)/6+1/3 -- pulse gl.Color(0.7, 0.7, 1, alpha) gl.Translate(ghost.x, Spring.GetGroundHeight(ghost.x, ghost.y), ghost.y) gl.Rotate(ghost.heading, 0, 1, 0) gl.DepthTest(true) gl.UnitShape(ghost.unitDefID, ghost.teamID, false, false, false) gl.PopMatrix() end end function getDistance(x1, z1, x2, z2) local x, z = x2 - x1, z2- z1 return (x*x + z*z)^0.5 end function gadget:UnitFinished(unitID, unitDefID, unitTeam) local x, y, z = Spring.GetUnitPosition(unitID) for ghostID, ghost in pairs(ghosts) do if unitDefID == ghost.unitDefID and getDistance(x, z, ghost.x, ghost.y) < 100 then -- ghost.y is no typo local groups = {} for i=1, #ghost do groups[ghost[i]] = true end local args = { type = "notifyGhostBuilt", unitID = unitID, groups = groups, teamID = ghost.teamID, } Spring.SendLuaRulesMsg(magic..table.show(args)) ghosts[ghostID] = nil break end end end function ScoreEvent() local teamID = Spring.GetLocalTeamID() local score = Spring.GetTeamRulesParam(teamID, "score") or 0 if score then local scoreStr = "SCORE: "..GG.Base64Encode(tostring(Spring.GetGameFrame()).."/"..tostring(math.floor(score))) print(scoreStr) Spring.Echo(scoreStr) end end function SendMissionObjectives() if Script.LuaUI("MissionObjectivesFromSynced") then local objectives = MakeRealTable(SYNCED.objectives) Script.LuaUI.MissionObjectivesFromSynced(objectives) end end function SendMissionPersistentMessages() if Script.LuaUI("MissionPersistentMessagesFromSynced") then local persistentMessages = MakeRealTable(SYNCED.persistentMessages) Script.LuaUI.MissionPersistentMessagesFromSynced(persistentMessages) end end local function SaveTriggers(triggersToSave) local output = {} for triggerIndex, data in pairs(triggersToSave) do output[triggerIndex] = { name = data.name, enabled = data.enabled, occurrences = data.occurrences } end return output end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:Initialize() gadgetHandler:AddSyncAction('MissionEvent', WrapToLuaUI) gadgetHandler:AddSyncAction('GhostEvent', GhostEvent) gadgetHandler:AddSyncAction('GhostRemovedEvent', GhostRemovedEvent) gadgetHandler:AddSyncAction('ScoreEvent', ScoreEvent) gadgetHandler:AddSyncAction('SendMissionObjectives', SendMissionObjectives) gadgetHandler:AddSyncAction('SendMissionPersistentMessages', SendMissionPersistentMessages) for _,callIn in pairs(callInList) do local fun = gadget[callIn] gadgetHandler:AddSyncAction(callIn, fun) end end function gadget:Shutdown() gadgetHandler:RemoveSyncAction('MissionEvent') gadgetHandler:RemoveSyncAction('GhostEvent') gadgetHandler:RemoveSyncAction('GhostRemovedEvent') gadgetHandler:RemoveSyncAction('ScoreEvent') gadgetHandler:RemoveSyncAction('SendMissionObjectives') gadgetHandler:RemoveSyncAction('SendMissionPersistentMessages') end function gadget:Save(zip) if not GG.SaveLoad then Spring.Log(gadget:GetInfo().name, LOG.WARNING, "Save/Load API not found") return end local toSave = MakeRealTable(SYNCED.mission) toSave.displayedCountdowns = MakeRealTable(SYNCED.displayedCountdowns) toSave.factoryExpectedUnits = MakeRealTable(SYNCED.factoryExpectedUnits) toSave.repeatFactoryGroups = MakeRealTable(SYNCED.repeatFactoryGroups) toSave.lastFinishedUnits = MakeRealTable(SYNCED.repeatFactoryGroups) -- clean up triggers table -- I think the only thing that needs saving is name (to identify non-allTriggers), -- whether a trigger is enabled or not, and occurrence count toSave.triggers = SaveTriggers(toSave.triggers) toSave.allTriggers = SaveTriggers(toSave.allTriggers) GG.SaveLoad.WriteSaveData(zip, SAVE_FILE, toSave) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- end
gpl-3.0
smartdevicelink/sdl_atf_test_scripts
test_scripts/RC/InteriorVehicleData_cache/038_OnInteriorVD_one_parameter.lua
1
3326
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0178-GetInteriorVehicleData.md -- User story: TBD -- Use case: TBD -- -- Requirement summary: TBD -- -- Description: -- In case -- 1. Mobile app1 is subscribed to module_1 -- 2. HMI sends OnInteriorVD with one param changing for module_1 -- 3. Mobile app1 sends GetInteriorVD(module_1, without subscribe parameter) request -- SDL must -- 1. not send GetInteriorVD request to HMI -- 2. send GetinteriorVD response to mobile app1 with actual data --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('test_scripts/RC/InteriorVehicleData_cache/common_interiorVDcache') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false local OnInteriorVDparams = { CLIMATE = { fanSpeed = 30 }, RADIO = { frequencyFraction = 3 }, SEAT = { id = "FRONT_PASSENGER" }, LIGHT = { lightState = { { id = "FRONT_RIGHT_HIGH_BEAM", status = "ON" } } }, AUDIO = { source = "FM" }, HMI_SETTINGS = { displayMode = "NIGHT" } } local function getModuleData(module_type, pParams) local out = { moduleType = module_type } if module_type == "CLIMATE" then out.climateControlData = pParams elseif module_type == "RADIO" then out.radioControlData = pParams elseif module_type == "SEAT" then out.seatControlData = pParams elseif module_type == "AUDIO" then out.audioControlData = pParams elseif module_type == "LIGHT" then out.lightControlData = pParams elseif module_type == "HMI_SETTINGS" then out.hmiSettingsControlData = pParams end return out end local function setActualInteriorVD(pInitialParams, pUpdatedParams) local moduleType = pInitialParams.moduleType if moduleType == "LIGHT" then local mergedParams = common.cloneTable(pInitialParams) mergedParams.lightControlData.lightState[2] = pUpdatedParams.lightControlData.lightState[1] common.setActualInteriorVD(moduleType, { lightControlData = mergedParams.lightControlData }) end end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("Register app1", common.registerAppWOPTU, { 1 }) runner.Step("Activate app1", common.activateApp, { 1 }) runner.Title("Test") for _, mod in pairs(common.modules) do local initialParams = common.cloneTable(common.actualInteriorDataStateOnHMI[mod]) local updatedParams = getModuleData(mod, OnInteriorVDparams[mod]) runner.Step("App1 GetInteriorVehicleData with subscribe=true " .. mod, common.GetInteriorVehicleData, { mod, true, true, 1 }) runner.Step("App1 OnInteriorVehicleData for " .. mod, common.OnInteriorVD, { mod, true, 1, updatedParams }) runner.Step("Set HMI data state for " .. mod .. " module", setActualInteriorVD, { initialParams, updatedParams }) runner.Step("App1 GetInteriorVehicleData without subscribe " .. mod, common.GetInteriorVehicleData, { mod, nil, false, 1 }) end runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
bsd-3-clause
ddumont/darkstar
scripts/globals/effects/saber_dance.lua
32
1693
----------------------------------- -- -- EFFECT_SABER_DANCE -- ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) local saberDanceMerits = target:getMerit(MERIT_SABER_DANCE); if (saberDanceMerits>5) then target:addMod(MOD_SAMBA_PDURATION, (saberDanceMerits -5)); end -- Does not stack with warrior Double Attack trait, so disable it if (target:hasTrait(15)) then --TRAIT_DOUBLE_ATTACK target:delMod(MOD_DOUBLE_ATTACK, 10); end target:addMod(MOD_DOUBLE_ATTACK,effect:getPower()); target:delStatusEffect(EFFECT_FAN_DANCE); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) local power = effect:getPower(); local decayby = 0; -- Double attack rate decays until 20% then stays there if (power > 20) then decayby = 3; effect:setPower(power-decayby); target:delMod(MOD_DOUBLE_ATTACK,decayby); end end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) local saberDanceMerits = target:getMerit(MERIT_SABER_DANCE); if (saberDanceMerits>1) then target:delMod(MOD_SAMBA_PDURATION, (saberDanceMerits -5)); end if (target:hasTrait(15)) then --TRAIT_DOUBLE_ATTACK -- put Double Attack trait back on. target:addMod(MOD_DOUBLE_ATTACK, 10); end target:delMod(MOD_DOUBLE_ATTACK,effect:getPower()); end;
gpl-3.0
Squeakz/darkstar
scripts/globals/effects/saber_dance.lua
32
1693
----------------------------------- -- -- EFFECT_SABER_DANCE -- ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) local saberDanceMerits = target:getMerit(MERIT_SABER_DANCE); if (saberDanceMerits>5) then target:addMod(MOD_SAMBA_PDURATION, (saberDanceMerits -5)); end -- Does not stack with warrior Double Attack trait, so disable it if (target:hasTrait(15)) then --TRAIT_DOUBLE_ATTACK target:delMod(MOD_DOUBLE_ATTACK, 10); end target:addMod(MOD_DOUBLE_ATTACK,effect:getPower()); target:delStatusEffect(EFFECT_FAN_DANCE); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) local power = effect:getPower(); local decayby = 0; -- Double attack rate decays until 20% then stays there if (power > 20) then decayby = 3; effect:setPower(power-decayby); target:delMod(MOD_DOUBLE_ATTACK,decayby); end end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) local saberDanceMerits = target:getMerit(MERIT_SABER_DANCE); if (saberDanceMerits>1) then target:delMod(MOD_SAMBA_PDURATION, (saberDanceMerits -5)); end if (target:hasTrait(15)) then --TRAIT_DOUBLE_ATTACK -- put Double Attack trait back on. target:addMod(MOD_DOUBLE_ATTACK, 10); end target:delMod(MOD_DOUBLE_ATTACK,effect:getPower()); end;
gpl-3.0
legatvs/libquvi-scripts
share/media/myspass.lua
3
2960
-- libquvi-scripts -- Copyright (C) 2013 Toni Gundogdu <legatvs@gmail.com> -- Copyright (C) 2012 Guido Leisker <guido@guido-leisker.de> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This program is free software: you can redistribute it and/or -- modify it under the terms of the GNU Affero General Public -- License as published by the Free Software Foundation, either -- version 3 of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General -- Public License along with this program. If not, see -- <http://www.gnu.org/licenses/>. -- local MySpass = {} -- Utility functions unique to this script -- Identify the media script. function ident(qargs) return { can_parse_url = MySpass.can_parse_url(qargs), domains = table.concat({'myspass.de'}, ',') } end -- Parse the media properties. function parse(qargs) -- Make mandatory: the media ID is needed to fetch the data XML. qargs.id = qargs.input_url:match("(%d+)/?$") or error("no match: media ID") local t = { 'http://www.myspass.de/myspass/includes/apps/video', '/getvideometadataxml.php?id=', qargs.id } local c = quvi.http.fetch(table.concat(t)).data local P = require 'lxp.lom' local L = require 'quvi/lxph' local x = P.parse(c) qargs.thumb_url = L.find_first_tag(x, 'imagePreview')[1] qargs.duration_ms = MySpass.to_duration_ms(L, x) qargs.streams = MySpass.iter_streams(L, x) qargs.title = MySpass.to_title(L, x) return qargs end -- -- Utility functions -- function MySpass.can_parse_url(qargs) local U = require 'socket.url' local t = U.parse(qargs.input_url) if t and t.scheme and t.scheme:lower():match('^http$') and t.host and t.host:lower():match('myspass%.de$') -- Expect all URLs ending with digits to be videos. and t.path and t.path:lower():match('^/myspass/.-/%d+/?$') then return true else return false end end function MySpass.iter_streams(L, x) local u = L.find_first_tag(x, 'url_flv')[1] local S = require 'quvi/stream' return {S.stream_new(u)} end function MySpass.to_duration_ms(L, x) local m,s = L.find_first_tag(x, 'duration')[1]:match('(%d+)%:(%d+)') m = tonumber(((m or ''):gsub('%a',''))) or 0 m = tonumber(((s or ''):gsub('%a',''))) or 0 return (m*60000) + (s*1000) end function MySpass.to_title(L, x) local t = { L.find_first_tag(x, 'format')[1], string.format('s%02de%02d -', L.find_first_tag(x, 'season')[1], L.find_first_tag(x, 'episode')[1]), L.find_first_tag(x, 'title')[1] } return table.concat(t, ' ') end -- vim: set ts=2 sw=2 tw=72 expandtab:
agpl-3.0
ddumont/darkstar
scripts/zones/West_Ronfaure/npcs/Aaveleon.lua
14
1533
----------------------------------- -- Area: West Ronfaure -- NPC: Aaveleon -- Involved in Quest: A Sentry's Peril -- @pos -431 -45 343 100 ----------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/West_Ronfaure/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,A_SENTRY_S_PERIL) == QUEST_ACCEPTED) then if (trade:hasItemQty(600,1) and trade:getItemCount() == 1) then player:startEvent(0x0064); else player:startEvent(118); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0065); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0064) then player:tradeComplete(); player:addItem(601); player:messageSpecial(ITEM_OBTAINED,601); end end;
gpl-3.0
albmarvil/The-Eternal-Sorrow
Exes/media/LUA/Managers/DropManager.lua
2
19447
Drop = { --INFO Y FUNCIONES GENERALES DEL DROP: Inicialización, tabla de drop general (GDD) y función DropObjectByType Contenedores = { ChestT1 = { --Cofres normales o de Tier 1 ---Se usan tablas sin claves para que se iteren siempre de la misma forma pesos = { {name = "Nada", peso = 0}, --Esto sirve para indicar que no debe caer nada {name = "Almas", peso = 2}, --En los primeros cofres es raro que necesite vida, quiero abrir cofres para habilidades {name = "Dinero", peso = 2}, {name = "Habilidad1", peso = 55}, {name = "Habilidad2", peso = 15}, {name = "Habilidad3", peso = 0}, {name = "Potenciador", peso = 7}, {name = "Arma1", peso = 5}, {name = "Arma2", peso = 1}, {name = "Arma3", peso = 0}, }, rangoPotenciadores = {min = 5, max = 7}, rangoAlmas = {min = 25, max = 50}, --son porcentajes rangoDineroBase = {min = 1000, max = 2000}, rangoDinero_function = function (sala) local min = math.floor(0.5 * sala * sala + sala + 1000) local max = math.floor(0.5 * sala * sala + sala + 2000) return min, max end, }, ChestT2 = { --Cofres medios o de Tier 2 pesos = { {name = "Nada", peso = 0}, {name = "Almas", peso = 5}, --Dado que salen dos cosas, un poco mas de probabilidad que el anterior {name = "Dinero", peso = 3}, {name = "Habilidad1", peso = 10}, {name = "Habilidad2", peso = 45}, {name = "Habilidad3", peso = 5}, {name = "Potenciador", peso = 7}, {name = "Arma1", peso = 3}, {name = "Arma2", peso = 3}, {name = "Arma3", peso = 1}, }, rangoPotenciadores = {min = 5, max = 7}, rangoAlmas = {min = 50, max = 75}, --son porcentajes rangoDineroBase = {min = 2500, max = 5000}, rangoDinero_function = function (sala) local min = math.floor(0.5 * sala * sala + sala + 2500) local max = math.floor(0.5 * sala * sala + sala + 5000) return min, max end, }, ChestT3 = { --Cofres grandes o de Tier 3 pesos = { {name = "Nada", peso = 0}, {name = "Almas", peso = 8}, --Dado que salen tres cosas, un poco mas de probabilidad que el anterior {name = "Dinero", peso = 4}, {name = "Habilidad1", peso = 10}, {name = "Habilidad2", peso = 20}, --2 {name = "Habilidad3", peso = 40}, --3 {name = "Potenciador", peso = 7}, {name = "Arma1", peso = 0}, {name = "Arma2", peso = 1}, {name = "Arma3", peso = 10}, }, rangoPotenciadores = {min = 1, max = 8}, rangoAlmas = {min = 75, max = 100}, --son porcentajes rangoDineroBase = {min = 5000, max = 10000}, rangoDinero_function = function (sala) local min = math.floor(sala * sala + 9 * sala + 5000) local max = math.floor(sala * sala + 9 * sala + 10000) return min, max end, }, brokenObject = { --Cofres normales o de Tier 1 ---Se usan tablas sin claves para que se iteren siempre de la misma forma pesos = { {name = "Nada", peso = 80}, --Esto sirve para indicar que no debe caer nada {name = "Almas", peso = 5}, {name = "Dinero", peso = 10}, {name = "Habilidad1", peso = 2}, {name = "Habilidad2", peso = 0}, {name = "Habilidad3", peso = 0}, {name = "Potenciador", peso = 3}, {name = "Arma1", peso = 0}, {name = "Arma2", peso = 0}, {name = "Arma3", peso = 0}, }, rangoPotenciadores = {min = 1, max = 1}, rangoAlmas = {min = 1, max = 10}, --son porcentajes rangoDineroBase = {min = 10, max = 50}, rangoDinero_function = function (sala) local min = math.floor(1.5 * sala * sala + sala + 10) local max = math.floor(1.5 * sala * sala + sala + 50) return min, max end, }, brokenObjectsNoTile = { ---Se usan tablas sin claves para que se iteren siempre de la misma forma pesos = { {name = "Nada", peso = 0}, --Esto sirve para indicar que no debe caer nada {name = "Almas", peso = 40}, {name = "Dinero", peso = 55}, {name = "Habilidad1", peso = 5}, {name = "Habilidad2", peso = 0}, {name = "Habilidad3", peso = 0}, {name = "Potenciador", peso = 5}, {name = "Arma1", peso = 1}, {name = "Arma2", peso = 0}, {name = "Arma3", peso = 0}, }, rangoPotenciadores = {min = 1, max = 3}, rangoAlmas = {min = 15, max = 25}, --son porcentajes rangoDineroBase = {min = 75, max = 150}, rangoDinero_function = function (sala) local min = math.floor(1.5 * sala * sala + sala + 75) local max = math.floor(1.5 * sala * sala + sala + 150) return min, max end, }, }, Init = function () --Esta inicialización sirve para rellenar los vectores de acumulación una vez en el juego Cofres.Init() --inicializamos las armas Armas.Init() --inicializamos los potenciadores --***OJO estamos fijando el nº máximo de potenciadores diferentes que puede haber en la partida Potenciadores.Init(24) --inicializamos las habilidades Habilidades.Init() --Acumulamos la tabla de probabilidades de cada contenedor del juego -- Y aprovechamos para inicializar los valores rangoDinero a partir de los valores básicos for k,v in pairs(Drop.Contenedores) do local totalWeight = 0 local acum = {} for key,value in pairs(v.pesos) do if value.peso > 0 then --si el peso es nulo, no lo meto en el vector de acumulación totalWeight = totalWeight + value.peso acum[key] = {name = value.name, peso = totalWeight} end end v.rangoDinero = {min = v.rangoDineroBase.min, max = v.rangoDineroBase.max} v.acum = acum v.totalWeight = totalWeight end end, --Multiplicador para controlar rápidamente la cantidad de dinero que puede contener un contenedor MultiplicadorDinero = 1, --Esta funcion actualiza el rango de dinero que puede tener un contenedor --Esta función debería depender del numero de salas en la que estamos. --Se hace uso de la funcion de cada contenedor (la de los cofres son calcadas a la del precio de los cofres) ActualizaDineroContenedores = function (numSalas) for k,v in pairs(Drop.Contenedores) do if type(v) == "table" then --solo actualizamos aquellos que tengan funciones de actualización if v["rangoDinero_function"] ~= nil then local min, max = v.rangoDinero_function(numSalas) v.rangoDinero.min = min v.rangoDinero.max = max -- Log.Debug("Min: "..min) -- Log.Debug("Max: "..max) end end end end, --INFO Y FUNCIONES RELATIVAS A LOS PUNTOS DE INTERES puntosInteres = {}, numPuntosInteres = 0, CreateObjects = function() --Al entrar en una nueva sala, actualizamos la información de los contenedores --Por ejemplo actualizamos el dinero que pueden soltar los diferentes tipos de contenedores --Este dato depende del numero de salas que llevemos Drop.ActualizaDineroContenedores(GameMgr.salas_totales) --limpiamos valores de los puntos de interes de la sala anterior Drop.numPuntosInteres = 0 Drop.puntosInteres = {} local puntos = getInterestingPoints() --guardamos los puntos en lua para no acceder a C++ if puntos ~= nil then for i = 0, puntos:size()-1, 1 do local aux_tabla = {peso = puntos:at(i):weight(), pos = puntos:at(i):pos(), pesoAcum = 0} Drop.puntosInteres[i+1] = aux_tabla Drop.numPuntosInteres = Drop.numPuntosInteres + 1 end end if Drop.numPuntosInteres > 0 then --Elegimos los cofres sobre la info de los ptos de interes Cofres.CreateChests() if FuncionesMapList.currentMap ~= "HabitacionTesoro" then --En la habitacion del tesoro no creamos trampas --Elegimos las trampas sobre la info restante de ptos de interes FuncionesTrampas.crearTrampas() end --Eelegimos de los puntos de interes que queden puntos para spawnear los objetos rompibles FuncionesObjRompibles.crearObjetosRompibles() end end, DropObjectByType = function (tipo, posicion) if tipo:find("Arma") ~= nil then --estamos ante un arma if tipo:find("1") ~= nil then --Arma Tier1 Armas.CreateArma(1, posicion) --Esto devuelve un arma aleatoria del tier indicado elseif tipo:find("2") ~= nil then --Arma Tier2 Armas.CreateArma(2, posicion) elseif tipo:find("3") ~= nil then --Arma Tier3 Armas.CreateArma(3, posicion) end elseif tipo:find("Habilidad") ~= nil then --estamos ante una habilidad if tipo:find("1") ~= nil then --Habilidad Tier1 Habilidades.CreateHabilidad(1, posicion) --Esto devuelve una Habilidad aleatoria del tier indicado elseif tipo:find("2") ~= nil then --Habilidad Tier2 Habilidades.CreateHabilidad(2, posicion) elseif tipo:find("3") ~= nil then --Habilidad Tier3 Habilidades.CreateHabilidad(3, posicion) end end end, } --CALLBACK LLAMADO CUANDO MATAMOS A UN JEFE function Drop.JefeMuerto() --Drop del resto de objetos: Habilidades, armas, ALMAS, POTENCIADORES end --CALLBACK LLAMADO CUANDO ROMPEMOS UN OBJETO function Drop.ObjetoRompible(positionObjeto) -- Log.Debug("Se ha roto un objeto rompible") --cogemos los valores de la tabla que necesitamos local tablaObjAcum = Drop.Contenedores.brokenObject.acum local totalWeight = Drop.Contenedores.brokenObject.totalWeight local tablaObj = Drop.Contenedores.brokenObject --sacamos un número aleatorio del peso local rnd = Random(totalWeight) --buscamos el drop que tenemos que sacar del objeto rompible for k,v in pairs(tablaObjAcum) do if v.peso >= rnd then -- Log.Debug("Tengo que sacar algo de: "..v.name) if v.name == "Potenciador" then --averiguamos cuantos potenciadore sacamos a la vez local numPotenciadores = RandomRange(tablaObj.rangoPotenciadores.min, tablaObj.rangoPotenciadores.max) -- Log.Debug("Saco "..numPotenciadores.." potenciadores") --se le pasa la posicion, un radio donde apareceran los potenciadores y el nº de potenciadores a instanciar Potenciadores.CreatePotenciador(positionObjeto, 10, 30, numPotenciadores) elseif v.name == "Almas" then --averiguamos la cantidad de almas que sacamos local cantidadAlmas = RandomRange(tablaObj.rangoAlmas.min, tablaObj.rangoAlmas.max) -- Log.Debug("Saco "..cantidadAlmas.." almas del cofre") Almas.CreateCantidadAlmas( positionObjeto, 10, 30, cantidadAlmas, 1) --por ahora le indicamos la granularidad a machete elseif v.name == "Dinero" then --averiguamos la cantidad de dinero que sacamos local cantidadDinero = RandomRange(tablaObj.rangoDinero.min, tablaObj.rangoDinero.max) -- Log.Debug("Saco "..cantidadDinero.." dinero del cofre") --Como queremos conseguir una lluvia de monedas al abrir un cofre, le damos una granularidad alta -- Por ejemplo: granularidad =10, usaremos 10 veces más monedas que el mínimo de cambio aproximador -- La granularidad tmb depende de la cantidad soltada y de los tipos de monedas disponibles Dinero.CreateCantidadDinero( positionObjeto, cantidadDinero, 1, 5) else local entityType = Drop.DropObjectByType(v.name, positionObjeto) end break end end end --CALLBACK LLAMADO CUANDO ROMPEMOS UN OBJETO function Drop.brokenObjectsNoTile(positionObjeto) -- Log.Debug("Se ha roto un objeto rompible") --cogemos los valores de la tabla que necesitamos local tablaObjAcum = Drop.Contenedores.brokenObjectsNoTile.acum local totalWeight = Drop.Contenedores.brokenObjectsNoTile.totalWeight local tablaObj = Drop.Contenedores.brokenObjectsNoTile --sacamos un número aleatorio del peso local rnd = Random(totalWeight) --buscamos el drop que tenemos que sacar del objeto rompible for k,v in pairs(tablaObjAcum) do if v.peso >= rnd then -- Log.Debug("Tengo que sacar algo de: "..v.name) if v.name == "Potenciador" then --averiguamos cuantos potenciadore sacamos a la vez local numPotenciadores = RandomRange(tablaObj.rangoPotenciadores.min, tablaObj.rangoPotenciadores.max) -- Log.Debug("Saco "..numPotenciadores.." potenciadores") --se le pasa la posicion, un radio donde apareceran los potenciadores y el nº de potenciadores a instanciar Potenciadores.CreatePotenciador(positionObjeto, 10, 30, numPotenciadores) elseif v.name == "Almas" then --averiguamos la cantidad de almas que sacamos local cantidadAlmas = RandomRange(tablaObj.rangoAlmas.min, tablaObj.rangoAlmas.max) -- Log.Debug("Saco "..cantidadAlmas.." almas del cofre") Almas.CreateCantidadAlmas( positionObjeto, 10, 30, cantidadAlmas, 1) --por ahora le indicamos la granularidad a machete elseif v.name == "Dinero" then --averiguamos la cantidad de dinero que sacamos local cantidadDinero = RandomRange(tablaObj.rangoDinero.min, tablaObj.rangoDinero.max) -- Log.Debug("Saco "..cantidadDinero.." dinero del cofre") --Como queremos conseguir una lluvia de monedas al abrir un cofre, le damos una granularidad alta -- Por ejemplo: granularidad =10, usaremos 10 veces más monedas que el mínimo de cambio aproximador -- La granularidad tmb depende de la cantidad soltada y de los tipos de monedas disponibles Dinero.CreateCantidadDinero( positionObjeto, cantidadDinero, 1, 5) else local entityType = Drop.DropObjectByType(v.name, positionObjeto) end break end end end --CALLBACK QUE EJECUTAREMOS CUANDO SE ABRA UN TESORO function Drop.CofreAbierto(nivelCofre, posicionCofre) -- Log.Debug("Se ha abierto un cofre de nivel: "..nivelCofre.." - En la posicion: "..posicionCofre.x..", "..posicionCofre.y) -- local posSpawn = posicionCofre -- posSpawn.z = 0 --seteamos la z a 0 para spawnear los elementos posicionCofre.z = 0 local tablaCofreAcum = nil local tablaCofre = nil local totalWeight = 0 local numHabilidades = nivelCofre if nivelCofre == 1 then tablaCofreAcum = Drop.Contenedores.ChestT1.acum tablaCofre = Drop.Contenedores.ChestT1 totalWeight = Drop.Contenedores.ChestT1.totalWeight elseif nivelCofre == 2 then tablaCofreAcum = Drop.Contenedores.ChestT2.acum tablaCofre = Drop.Contenedores.ChestT2 totalWeight = Drop.Contenedores.ChestT2.totalWeight elseif nivelCofre == 3 then tablaCofreAcum = Drop.Contenedores.ChestT3.acum tablaCofre = Drop.Contenedores.ChestT3 totalWeight = Drop.Contenedores.ChestT3.totalWeight end -- local rnd = math.random(totalWeight) local rnd = Random(totalWeight) -- Log.Debug("Drop.CofreAbierto (tipo drop) RND: "..rnd) for k,v in pairs(tablaCofreAcum) do if v.peso >= rnd then -- Log.Debug("Tengo que sacar algo de: "..v.name) -- v.name = "Habilidad3" if v.name == "Potenciador" then --averiguamos cuantos potenciadore sacamos a la vez -- local numPotenciadores = math.random(tablaCofre.rangoPotenciadores.min, tablaCofre.rangoPotenciadores.max) local numPotenciadores = RandomRange(tablaCofre.rangoPotenciadores.min, tablaCofre.rangoPotenciadores.max) -- Log.Debug("Drop.CofreAbierto (potenciadores) RND: "..numPotenciadores) -- Log.Debug("Saco "..numPotenciadores.." potenciadores") --se le pasa la posicion, un radio donde apareceran los potenciadores y el nº de potenciadores a instanciar Potenciadores.CreatePotenciador(posicionCofre, 15, 40, numPotenciadores) elseif v.name == "Almas" then --averiguamos la cantidad de almas que sacamos -- local cantidadAlmas = math.random(tablaCofre.rangoAlmas.min, tablaCofre.rangoAlmas.max) local cantidadAlmas = RandomRange(tablaCofre.rangoAlmas.min, tablaCofre.rangoAlmas.max) -- Log.Debug("Drop.CofreAbierto (almas) RND: "..cantidadAlmas) -- Log.Debug("Saco "..cantidadAlmas.." almas del cofre") Almas.CreateCantidadAlmas( posicionCofre, 15, 40, cantidadAlmas, 1) --por ahora le indicamos la granularidad a machete elseif v.name == "Dinero" then --averiguamos la cantidad de dinero que sacamos -- local cantidadDinero = math.random(tablaCofre.rangoDinero.min, tablaCofre.rangoDinero.max) local cantidadDinero = RandomRange(tablaCofre.rangoDinero.min, tablaCofre.rangoDinero.max) -- Log.Debug("Drop.CofreAbierto (dinero) RND: "..cantidadDinero) -- Log.Debug("Saco "..cantidadDinero.." dinero del cofre") --Como queremos conseguir una lluvia de monedas al abrir un cofre, le damos una granularidad alta -- Por ejemplo: granularidad =10, usaremos 10 veces más monedas que el mínimo de cambio aproximador -- La granularidad tmb depende de la cantidad soltada y de los tipos de monedas disponibles Dinero.CreateCantidadDinero( posicionCofre, cantidadDinero, 2, 50) elseif v.name == "Habilidad1" or v.name == "Habilidad2" or v.name == "Habilidad3" then local offset = -20 for i=1,numHabilidades do posicionCofre.x = posicionCofre.x + offset local entityType = Drop.DropObjectByType(v.name, posicionCofre) offset = offset + 20 end else local entityType = Drop.DropObjectByType(v.name, posicionCofre) end break end end end --CALLBACK QUE EJECUTAREMOS CUANDO SE MUERA UN ENEMIGO function Drop.EnemyDie(typeEnemy, nivelEnemy, positionEnemy) local radioAltar = true if RetoMgr.retoLoaded == "RetoAltar.lua" then radioAltar = Reto.distance end if EventoAvalancha.hordaInvocada == false and radioAltar then --Solo dropeamos cuando matamos a enemigos que no son del reto local tablaContendorAcum = Drop.Contenedores[typeEnemy].acum local tablaContenedor = Drop.Contenedores[typeEnemy] local totalWeight = Drop.Contenedores[typeEnemy].totalWeight -- local rnd = math.random(totalWeight) local rnd = Random(totalWeight) -- Log.Debug("Drop.CofreAbierto (tipo drop) RND: "..rnd) --Si estamos en el reto del altar calculamos si el enemigo ha muerto en su radio --Calculamos la cantidad de dinero que debemos dropear -- local minDinero, maxDinero = tablaContenedor.CrecimientoDinero(nivelEnemy) local minDinero = tablaContenedor.rangoDineroBase.min local maxDinero = tablaContenedor.rangoDineroBase.max local cantDinero = RandomRange(minDinero, maxDinero) Dinero.CreateCantidadDinero( positionEnemy, cantDinero, 1, 1) for k,v in pairs(tablaContendorAcum) do if v.peso >= rnd then -- Log.Debug("Tengo que sacar algo de: "..v.name) --Debug -- v.name = "Arma1" if v.name == "Potenciador" then --averiguamos cuantos potenciadore sacamos a la vez -- local numPotenciadores = math.random(tablaCofre.rangoPotenciadores.min, tablaCofre.rangoPotenciadores.max) local numPotenciadores = RandomRange(tablaContenedor.rangoPotenciadores.min, tablaContenedor.rangoPotenciadores.max) -- Log.Debug("Drop.CofreAbierto (potenciadores) RND: "..numPotenciadores) -- Log.Debug("Saco "..numPotenciadores.." potenciadores") --se le pasa la posicion, un radio donde apareceran los potenciadores y el nº de potenciadores a instanciar Potenciadores.CreatePotenciador(positionEnemy, 0, 30, numPotenciadores) elseif v.name == "Almas" then --averiguamos la cantidad de almas que sacamos -- local cantidadAlmas = math.random(tablaCofre.rangoAlmas.min, tablaCofre.rangoAlmas.max) local cantidadAlmas = RandomRange(tablaContenedor.rangoAlmas.min, tablaContenedor.rangoAlmas.max) -- Log.Debug("Drop.CofreAbierto (almas) RND: "..cantidadAlmas) -- Log.Debug("Saco "..cantidadAlmas.." almas del cofre") Almas.CreateCantidadAlmas( positionEnemy, 0, 30, cantidadAlmas, 1) --por ahora le indicamos la granularidad a machete else local entityType = Drop.DropObjectByType(v.name, positionEnemy) end break end end end end
apache-2.0
jomanmuk/vlc-2.1
share/lua/playlist/mpora.lua
97
2565
--[[ $Id$ Copyright © 2009 the VideoLAN team Authors: Konstantin Pavlov (thresh@videolan.org) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "video%.mpora%.com/watch/" ) end -- Parse function. function parse() p = {} while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "meta name=\"title\"" ) then _,_,name = string.find( line, "content=\"(.*)\" />" ) end if string.match( line, "image_src" ) then _,_,arturl = string.find( line, "image_src\" href=\"(.*)\" />" ) end if string.match( line, "video_src" ) then _,_,video = string.find( line, 'href="http://video%.mpora%.com/ep/(.*)%.swf" />' ) end end if not name or not arturl or not video then return nil end -- Try and get URL for SD video. sd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/") if not sd then return nil end page = sd:read( 65653 ) sdurl = string.match( page, "url=\"(.*)\" />") page = nil table.insert( p, { path = sdurl; name = name; arturl = arturl; } ) -- Try and check if HD video is available. checkhd = vlc.stream("http://api.mpora.com/tv/player/load/vid/"..video.."/platform/video/domain/video.mpora.com/" ) if not checkhd then return nil end page = checkhd:read( 65653 ) hashd = tonumber( string.match( page, "<has_hd>(%d)</has_hd>" ) ) page = nil if hashd then hd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/hd/true/") page = hd:read( 65653 ) hdurl = string.match( page, "url=\"(.*)\" />") table.insert( p, { path = hdurl; name = name.." (HD)"; arturl = arturl; } ) end return p end
lgpl-2.1
jlcvp/otxserver
data/monster/quests/svargrond_arena/warlord/deathbringer.lua
2
2935
local mType = Game.createMonsterType("Deathbringer") local monster = {} monster.description = "Deathbringer" monster.experience = 5100 monster.outfit = { lookType = 231, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.health = 8440 monster.maxHealth = 8440 monster.race = "undead" monster.corpse = 7349 monster.speed = 300 monster.manaCost = 0 monster.changeTarget = { interval = 0, chance = 0 } monster.strategiesTarget = { nearest = 70, health = 10, damage = 10, random = 10, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = false, illusionable = false, canPushItems = true, canPushCreatures = false, staticAttackChance = 95, targetDistance = 1, runHealth = 0, healthHidden = false, isBlockable = false, canWalkOnEnergy = false, canWalkOnFire = false, canWalkOnPoison = false } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, {text = "YOU FOOLS WILL PAY!", yell = true}, {text = "YOU ALL WILL DIE!!", yell = true}, {text = "DEATH, DESTRUCTION!", yell = true}, {text = "I will eat your soul!", yell = false} } monster.loot = { } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -465}, {name ="combat", interval = 1000, chance = 10, type = COMBAT_FIREDAMAGE, minDamage = -80, maxDamage = -120, range = 7, radius = 4, shootEffect = CONST_ANI_FIRE, target = true}, {name ="combat", interval = 3000, chance = 17, type = COMBAT_FIREDAMAGE, minDamage = -300, maxDamage = -450, length = 8, spread = 3, effect = CONST_ME_FIREAREA, target = false}, {name ="combat", interval = 2000, chance = 12, type = COMBAT_EARTHDAMAGE, minDamage = -300, maxDamage = -450, length = 8, spread = 3, effect = CONST_ME_POISONAREA, target = false}, {name ="combat", interval = 2000, chance = 10, type = COMBAT_LIFEDRAIN, minDamage = -80, maxDamage = -100, radius = 6, effect = CONST_ME_POFF, target = false}, {name ="combat", interval = 3000, chance = 25, type = COMBAT_LIFEDRAIN, minDamage = -80, maxDamage = -150, range = 7, effect = CONST_ME_MAGIC_RED, target = false} } monster.defenses = { defense = 15, armor = 15 } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 10}, {type = COMBAT_EARTHDAMAGE, percent = 100}, {type = COMBAT_FIREDAMAGE, percent = 100}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 100}, {type = COMBAT_HOLYDAMAGE , percent = -15}, {type = COMBAT_DEATHDAMAGE , percent = 100} } monster.immunities = { {type = "paralyze", condition = false}, {type = "outfit", condition = true}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType:register(monster)
gpl-2.0
Squeakz/darkstar
scripts/zones/GM_Home/npcs/Trader.lua
32
1090
----------------------------------- -- Area: GM Home -- NPC: Trader -- Type: Debug NPC for testing trades. ----------------------------------- package.loaded["scripts/zones/GM_Home/TextIDs"] = nil; ----------------------------------- require("scripts/zones/GM_Home/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(4096,1) and trade:getItemCount() == 1) then player:startEvent(126); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(127); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
lemonkit/VisualCocos
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/Twirl.lua
8
3896
-------------------------------- -- @module Twirl -- @extend Grid3DAction -- @parent_module cc -------------------------------- -- brief Set the amplitude rate of the effect.<br> -- param amplitudeRate The value of amplitude rate will be set. -- @function [parent=#Twirl] setAmplitudeRate -- @param self -- @param #float amplitudeRate -- @return Twirl#Twirl self (return value: cc.Twirl) -------------------------------- -- brief Initializes the action with center position, number of twirls, amplitude, a grid size and duration.<br> -- param duration Specify the duration of the Twirl action. It's a value in seconds.<br> -- param gridSize Specify the size of the grid.<br> -- param position Specify the center position of the twirl action.<br> -- param twirls Specify the twirls count of the Twirl action.<br> -- param amplitude Specify the amplitude of the Twirl action.<br> -- return If the initialization success, return true; otherwise, return false. -- @function [parent=#Twirl] initWithDuration -- @param self -- @param #float duration -- @param #size_table gridSize -- @param #vec2_table position -- @param #unsigned int twirls -- @param #float amplitude -- @return bool#bool ret (return value: bool) -------------------------------- -- brief Get the amplitude rate of the effect.<br> -- return Return the amplitude rate of the effect. -- @function [parent=#Twirl] getAmplitudeRate -- @param self -- @return float#float ret (return value: float) -------------------------------- -- brief Set the amplitude to the effect.<br> -- param amplitude The value of amplitude will be set. -- @function [parent=#Twirl] setAmplitude -- @param self -- @param #float amplitude -- @return Twirl#Twirl self (return value: cc.Twirl) -------------------------------- -- brief Get the amplitude of the effect.<br> -- return Return the amplitude of the effect. -- @function [parent=#Twirl] getAmplitude -- @param self -- @return float#float ret (return value: float) -------------------------------- -- brief Set the center position of twirl action.<br> -- param position The center position of twirl action will be set. -- @function [parent=#Twirl] setPosition -- @param self -- @param #vec2_table position -- @return Twirl#Twirl self (return value: cc.Twirl) -------------------------------- -- brief Get the center position of twirl action.<br> -- return The center position of twirl action. -- @function [parent=#Twirl] getPosition -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- brief Create the action with center position, number of twirls, amplitude, a grid size and duration.<br> -- param duration Specify the duration of the Twirl action. It's a value in seconds.<br> -- param gridSize Specify the size of the grid.<br> -- param position Specify the center position of the twirl action.<br> -- param twirls Specify the twirls count of the Twirl action.<br> -- param amplitude Specify the amplitude of the Twirl action.<br> -- return If the creation success, return a pointer of Twirl action; otherwise, return nil. -- @function [parent=#Twirl] create -- @param self -- @param #float duration -- @param #size_table gridSize -- @param #vec2_table position -- @param #unsigned int twirls -- @param #float amplitude -- @return Twirl#Twirl ret (return value: cc.Twirl) -------------------------------- -- -- @function [parent=#Twirl] clone -- @param self -- @return Twirl#Twirl ret (return value: cc.Twirl) -------------------------------- -- -- @function [parent=#Twirl] update -- @param self -- @param #float time -- @return Twirl#Twirl self (return value: cc.Twirl) -------------------------------- -- -- @function [parent=#Twirl] Twirl -- @param self -- @return Twirl#Twirl self (return value: cc.Twirl) return nil
mit
8devices/luci
protocols/relay/luasrc/model/network/proto_relay.lua
9
3435
--[[ LuCI - Network model - relay protocol extension Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local netmod = luci.model.network local device = luci.util.class(netmod.interface) netmod:register_pattern_virtual("^relay-%w") local proto = netmod:register_protocol("relay") function proto.get_i18n(self) return luci.i18n.translate("Relay bridge") end function proto.ifname(self) return "relay-" .. self.sid end function proto.opkg_package(self) return "relayd" end function proto.is_installed(self) return nixio.fs.access("/lib/network/relay.sh") end function proto.is_floating(self) return true end function proto.is_virtual(self) return true end function proto.get_interface(self) return device(self.sid, self) end function proto.get_interfaces(self) if not self.ifaces then local ifs = { } local _, net, dev for net in luci.util.imatch(self:_get("network")) do net = netmod:get_network(net) if net then dev = net:get_interface() if dev then ifs[dev:name()] = dev end end end for dev in luci.util.imatch(self:_get("ifname")) do dev = netmod:get_interface(dev) if dev then ifs[dev:name()] = dev end end self.ifaces = { } for _, dev in luci.util.kspairs(ifs) do self.ifaces[#self.ifaces+1] = dev end end return self.ifaces end function proto.uptime(self) local net local upt = 0 for net in luci.util.imatch(self:_get("network")) do net = netmod:get_network(net) if net then upt = math.max(upt, net:uptime()) end end return upt end function device.__init__(self, ifname, network) self.ifname = ifname self.network = network end function device.type(self) return "tunnel" end function device.is_up(self) if self.network then local _, dev for _, dev in ipairs(self.network:get_interfaces()) do if not dev:is_up() then return false end end return true end return false end function device._stat(self, what) local v = 0 if self.network then local _, dev for _, dev in ipairs(self.network:get_interfaces()) do v = v + dev[what](dev) end end return v end function device.rx_bytes(self) return self:_stat("rx_bytes") end function device.tx_bytes(self) return self:_stat("tx_bytes") end function device.rx_packets(self) return self:_stat("rx_packets") end function device.tx_packets(self) return self:_stat("tx_packets") end function device.mac(self) if self.network then local _, dev for _, dev in ipairs(self.network:get_interfaces()) do return dev:mac() end end end function device.ipaddrs(self) local addrs = { } if self.network then addrs[1] = luci.ip.IPv4(self.network:_get("ipaddr")) end return addrs end function device.ip6addrs(self) return { } end function device.shortname(self) return "%s %q" % { luci.i18n.translate("Relay"), self.ifname } end function device.get_type_i18n(self) return luci.i18n.translate("Relay Bridge") end
apache-2.0
roysc/awesome
lib/awful/menu.lua
2
21526
-------------------------------------------------------------------------------- --- A menu for awful -- -- @author Damien Leone &lt;damien.leone@gmail.com&gt; -- @author Julien Danjou &lt;julien@danjou.info&gt; -- @author dodo -- @copyright 2008, 2011 Damien Leone, Julien Danjou, dodo -- @release @AWESOME_VERSION@ -- @module awful.menu -------------------------------------------------------------------------------- local wibox = require("wibox") local button = require("awful.button") local util = require("awful.util") local tags = require("awful.tag") local keygrabber = require("awful.keygrabber") local beautiful = require("beautiful") local object = require("gears.object") local surface = require("gears.surface") local cairo = require("lgi").cairo local setmetatable = setmetatable local tonumber = tonumber local string = string local ipairs = ipairs local pairs = pairs local pcall = pcall local print = print local table = table local type = type local math = math local capi = { screen = screen, mouse = mouse, client = client } local screen = require("awful.screen") local menu = { mt = {} } local table_update = function (t, set) for k, v in pairs(set) do t[k] = v end return t end local table_merge = function (t, set) for _, v in ipairs(set) do table.insert(t, v) end end --- Key bindings for menu navigation. -- Keys are: up, down, exec, enter, back, close. Value are table with a list of valid -- keys for the action, i.e. menu_keys.up = { "j", "k" } will bind 'j' and 'k' -- key to up action. This is common to all created menu. -- @class table -- @name menu_keys menu.menu_keys = { up = { "Up", "k" }, down = { "Down", "j" }, back = { "Left", "h" }, exec = { "Return" }, enter = { "Right", "l" }, close = { "Escape" } } local function load_theme(a, b) a = a or {} b = b or {} local ret = {} local fallback = beautiful.get() if a.reset then b = fallback end if a == "reset" then a = fallback end ret.border = a.border_color or b.menu_border_color or b.border_normal or fallback.menu_border_color or fallback.border_normal ret.border_width= a.border_width or b.menu_border_width or b.border_width or fallback.menu_border_width or fallback.border_width or 0 ret.fg_focus = a.fg_focus or b.menu_fg_focus or b.fg_focus or fallback.menu_fg_focus or fallback.fg_focus ret.bg_focus = a.bg_focus or b.menu_bg_focus or b.bg_focus or fallback.menu_bg_focus or fallback.bg_focus ret.fg_normal = a.fg_normal or b.menu_fg_normal or b.fg_normal or fallback.menu_fg_normal or fallback.fg_normal ret.bg_normal = a.bg_normal or b.menu_bg_normal or b.bg_normal or fallback.menu_bg_normal or fallback.bg_normal ret.submenu_icon= a.submenu_icon or b.menu_submenu_icon or b.submenu_icon or fallback.menu_submenu_icon or fallback.submenu_icon ret.submenu = a.submenu or b.menu_submenu or b.submenu or fallback.menu_submenu or fallback.submenu or "▶" ret.height = a.height or b.menu_height or b.height or fallback.menu_height or 16 ret.width = a.width or b.menu_width or b.width or fallback.menu_width or 100 ret.font = a.font or b.font or fallback.font for _, prop in ipairs({"width", "height", "menu_width"}) do if type(ret[prop]) ~= "number" then ret[prop] = tonumber(ret[prop]) end end return ret end local function item_position(_menu, child) local in_dir, other, a, b = 0, 0, "height", "width" local dir = _menu.layout.dir or "y" if dir == "x" then a, b = b, a end local in_dir, other = 0, _menu[b] local num = util.table.hasitem(_menu.child, child) if num then for i = 0, num - 1 do local item = _menu.items[i] if item then other = math.max(other, item[b]) in_dir = in_dir + item[a] end end end local w, h = other, in_dir if dir == "x" then w, h = h, w end return w, h end local function set_coords(_menu, screen_idx, m_coords) local s_geometry = capi.screen[screen_idx].workarea local screen_w = s_geometry.x + s_geometry.width local screen_h = s_geometry.y + s_geometry.height _menu.width = _menu.wibox.width _menu.height = _menu.wibox.height _menu.x = _menu.wibox.x _menu.y = _menu.wibox.y if _menu.parent then local w, h = item_position(_menu.parent, _menu) w = w + _menu.parent.theme.border_width _menu.y = _menu.parent.y + h + _menu.height > screen_h and screen_h - _menu.height or _menu.parent.y + h _menu.x = _menu.parent.x + w + _menu.width > screen_w and _menu.parent.x - _menu.width or _menu.parent.x + w else if m_coords == nil then m_coords = capi.mouse.coords() m_coords.x = m_coords.x + 1 m_coords.y = m_coords.y + 1 end _menu.y = m_coords.y < s_geometry.y and s_geometry.y or m_coords.y _menu.x = m_coords.x < s_geometry.x and s_geometry.x or m_coords.x _menu.y = _menu.y + _menu.height > screen_h and screen_h - _menu.height or _menu.y _menu.x = _menu.x + _menu.width > screen_w and screen_w - _menu.width or _menu.x end _menu.wibox.x = _menu.x _menu.wibox.y = _menu.y end local function set_size(_menu) local in_dir, other, a, b = 0, 0, "height", "width" local dir = _menu.layout.dir or "y" if dir == "x" then a, b = b, a end for _, item in ipairs(_menu.items) do other = math.max(other, item[b]) in_dir = in_dir + item[a] end _menu[a], _menu[b] = in_dir, other if in_dir > 0 and other > 0 then _menu.wibox[a] = in_dir _menu.wibox[b] = other return true end return false end local function check_access_key(_menu, key) for i, item in ipairs(_menu.items) do if item.akey == key then _menu:item_enter(i) _menu:exec(i, { exec = true }) return end end if _menu.parent then check_access_key(_menu.parent, key) end end local function grabber(_menu, mod, key, event) if event ~= "press" then return end local sel = _menu.sel or 0 if util.table.hasitem(menu.menu_keys.up, key) then local sel_new = sel-1 < 1 and #_menu.items or sel-1 _menu:item_enter(sel_new) elseif util.table.hasitem(menu.menu_keys.down, key) then local sel_new = sel+1 > #_menu.items and 1 or sel+1 _menu:item_enter(sel_new) elseif sel > 0 and util.table.hasitem(menu.menu_keys.enter, key) then _menu:exec(sel) elseif sel > 0 and util.table.hasitem(menu.menu_keys.exec, key) then _menu:exec(sel, { exec = true }) elseif util.table.hasitem(menu.menu_keys.back, key) then _menu:hide() elseif util.table.hasitem(menu.menu_keys.close, key) then menu.get_root(_menu):hide() else check_access_key(_menu, key) end end function menu:exec(num, opts) opts = opts or {} local item = self.items[num] if not item then return end local cmd = item.cmd if type(cmd) == "table" then local action = cmd.cmd if #cmd == 0 then if opts.exec and action and type(action) == "function" then action() end return end if not self.child[num] then self.child[num] = menu.new(cmd, self) end local can_invoke_action = opts.exec and action and type(action) == "function" and (not opts.mouse or (opts.mouse and (self.auto_expand or (self.active_child == self.child[num] and self.active_child.wibox.visible)))) if can_invoke_action then local visible = action(self.child[num], item) if not visible then menu.get_root(self):hide() return else self.child[num]:update() end end if self.active_child and self.active_child ~= self.child[num] then self.active_child:hide() end self.active_child = self.child[num] if not self.active_child.visible then self.active_child:show() end elseif type(cmd) == "string" then menu.get_root(self):hide() util.spawn(cmd) elseif type(cmd) == "function" then local visible, action = cmd(item, self) if not visible then menu.get_root(self):hide() else self:update() if self.items[num] then self:item_enter(num, opts) end end if action and type(action) == "function" then action() end end end function menu:item_enter(num, opts) opts = opts or {} local item = self.items[num] if num == nil or self.sel == num or not item then return elseif self.sel then self:item_leave(self.sel) end --print("sel", num, menu.sel, item.theme.bg_focus) item._background:set_fg(item.theme.fg_focus) item._background:set_bg(item.theme.bg_focus) self.sel = num if self.auto_expand and opts.hover then if self.active_child then self.active_child:hide() self.active_child = nil end if type(item.cmd) == "table" then self:exec(num, opts) end end end function menu:item_leave(num) --print("leave", num) local item = self.items[num] if item then item._background:set_fg(item.theme.fg_normal) item._background:set_bg(item.theme.bg_normal) end end --- Show a menu. -- @param args The arguments -- @param args.coords Menu position defaulting to mouse.coords() function menu:show(args) args = args or {} local coords = args.coords or nil local screen_index = screen.focused() if not set_size(self) then return end set_coords(self, screen_index, coords) keygrabber.run(self._keygrabber) self.wibox.visible = true end --- Hide a menu popup. function menu:hide() -- Remove items from screen for i = 1, #self.items do self:item_leave(i) end if self.active_child then self.active_child:hide() self.active_child = nil end self.sel = nil keygrabber.stop(self._keygrabber) self.wibox.visible = false end --- Toggle menu visibility. -- @param args The arguments -- @param args.coords Menu position {x,y} function menu:toggle(args) if self.wibox.visible then self:hide() else self:show(args) end end --- Update menu content function menu:update() if self.wibox.visible then self:show({ coords = { x = self.x, y = self.y } }) end end --- Get the elder parent so for example when you kill -- it, it will destroy the whole family. function menu:get_root() return self.parent and menu.get_root(self.parent) or self end --- Add a new menu entry. -- args.* params needed for the menu entry constructor. -- @param args The item params -- @param args.new (Default: awful.menu.entry) The menu entry constructor. -- @param[opt] args.theme The menu entry theme. -- @param[opt] index The index where the new entry will inserted. function menu:add(args, index) if not args then return end local theme = load_theme(args.theme or {}, self.theme) args.theme = theme args.new = args.new or menu.entry local success, item = pcall(args.new, self, args) if not success then print("Error while creating menu entry: " .. item) return end if not item.widget then print("Error while checking menu entry: no property widget found.") return end item.parent = self item.theme = item.theme or theme item.width = item.width or theme.width item.height = item.height or theme.height wibox.widget.base.check_widget(item.widget) item._background = wibox.widget.background() item._background:set_widget(item.widget) item._background:set_fg(item.theme.fg_normal) item._background:set_bg(item.theme.bg_normal) -- Create bindings item._background:buttons(util.table.join( button({}, 3, function () self:hide() end), button({}, 1, function () local num = util.table.hasitem(self.items, item) self:item_enter(num, { mouse = true }) self:exec(num, { exec = true, mouse = true }) end ))) item._mouse = function () local num = util.table.hasitem(self.items, item) self:item_enter(num, { hover = true, moue = true }) end item.widget:connect_signal("mouse::enter", item._mouse) if index then self.layout:reset() table.insert(self.items, index, item) for _, i in ipairs(self.items) do self.layout:add(i._background) end else table.insert(self.items, item) self.layout:add(item._background) end if self.wibox then set_size(self) end return item end --- Delete menu entry at given position -- @param num The position in the table of the menu entry to be deleted; can be also the menu entry itself function menu:delete(num) if type(num) == "table" then num = util.table.hasitem(self.items, num) end local item = self.items[num] if not item then return end item.widget:disconnect_signal("mouse::enter", item._mouse) item.widget.visible = false table.remove(self.items, num) if self.sel == num then self:item_leave(self.sel) self.sel = nil end self.layout:reset() for _, i in ipairs(self.items) do self.layout:add(i._background) end if self.child[num] then self.child[num]:hide() if self.active_child == self.child[num] then self.active_child = nil end table.remove(self.child, num) end if self.wibox then set_size(self) end end -------------------------------------------------------------------------------- --- Build a popup menu with running clients and shows it. -- @param args Menu table, see new() function for more informations -- @param item_args Table that will be merged into each item, see new() for more -- informations. -- @return The menu. function menu.clients(args, item_args) local cls = capi.client.get() local cls_t = {} for k, c in pairs(cls) do cls_t[#cls_t + 1] = { c.name or "", function () if not c:isvisible() then tags.viewmore(c:tags(), c.screen) end c:emit_signal("request::activate", "menu.clients", {raise=true}) end, c.icon } if item_args then if type(item_args) == "function" then table_merge(cls_t[#cls_t], item_args(c)) else table_merge(cls_t[#cls_t], item_args) end end end args = args or {} args.items = args.items or {} table_merge(args.items, cls_t) local m = menu.new(args) m:show(args) return m end -------------------------------------------------------------------------------- --- Default awful.menu.entry constructor -- @param parent The parent menu -- @param args the item params -- @return table with 'widget', 'cmd', 'akey' and all the properties the user wants to change function menu.entry(parent, args) args = args or {} args.text = args[1] or args.text or "" args.cmd = args[2] or args.cmd args.icon = args[3] or args.icon local ret = {} -- Create the item label widget local label = wibox.widget.textbox() local key = '' label:set_font(args.theme.font) label:set_markup(string.gsub( util.escape(args.text), "&amp;(%w)", function (l) key = string.lower(l) return "<u>" .. l .. "</u>" end, 1)) -- Set icon if needed local icon, iconbox local margin = wibox.layout.margin() margin:set_widget(label) if args.icon then icon = surface.load(args.icon) end if icon then local iw = icon:get_width() local ih = icon:get_height() if iw > args.theme.width or ih > args.theme.height then local w, h if ((args.theme.height / ih) * iw) > args.theme.width then w, h = args.theme.height, (args.theme.height / iw) * ih else w, h = (args.theme.height / ih) * iw, args.theme.height end -- We need to scale the image to size w x h local img = cairo.ImageSurface(cairo.Format.ARGB32, w, h) local cr = cairo.Context(img) cr:scale(w / iw, h / ih) cr:set_source_surface(icon, 0, 0) cr:paint() icon = img end iconbox = wibox.widget.imagebox() if iconbox:set_image(icon) then margin:set_left(2) else iconbox = nil end end if not iconbox then margin:set_left(args.theme.height + 2) end -- Create the submenu icon widget local submenu if type(args.cmd) == "table" then if args.theme.submenu_icon then submenu = wibox.widget.imagebox() submenu:set_image(surface.load(args.theme.submenu_icon)) else submenu = wibox.widget.textbox() submenu:set_font(args.theme.font) submenu:set_text(args.theme.submenu) end end -- Add widgets to the wibox local left = wibox.layout.fixed.horizontal() if iconbox then left:add(iconbox) end -- This contains the label left:add(margin) local layout = wibox.layout.align.horizontal() layout:set_left(left) if submenu then layout:set_right(submenu) end return table_update(ret, { label = label, sep = submenu, icon = iconbox, widget = layout, cmd = args.cmd, akey = key, }) end -------------------------------------------------------------------------------- --- Create a menu popup. -- @param args Table containing the menu informations. -- -- * Key items: Table containing the displayed items. Each element is a table by default (when element 'new' is awful.menu.entry) containing: item name, triggered action, submenu table or function, item icon (optional). -- * Keys theme.[fg|bg]_[focus|normal], theme.border_color, theme.border_width, theme.submenu_icon, theme.height and theme.width override the default display for your menu and/or of your menu entry, each of them are optional. -- * Key auto_expand controls the submenu auto expand behaviour by setting it to true (default) or false. -- -- @param parent Specify the parent menu if we want to open a submenu, this value should never be set by the user. -- @usage -- The following function builds and shows a menu of clients that match -- -- a particular rule. -- -- Bound to a key, it can be used to select from dozens of terminals open on -- -- several tags. -- -- When using @{rules.match_any} instead of @{rules.match}, -- -- a menu of clients with different classes could be build. -- -- function terminal_menu () -- terms = {} -- for i, c in pairs(client.get()) do -- if awful.rules.match(c, {class = "URxvt"}) then -- terms[i] = -- {c.name, -- function() -- awful.tag.viewonly(c.first_tag) -- client.focus = c -- end, -- c.icon -- } -- end -- end -- awful.menu(terms):show() -- end function menu.new(args, parent) args = args or {} args.layout = args.layout or wibox.layout.flex.vertical local _menu = table_update(object(), { item_enter = menu.item_enter, item_leave = menu.item_leave, get_root = menu.get_root, delete = menu.delete, update = menu.update, toggle = menu.toggle, hide = menu.hide, show = menu.show, exec = menu.exec, add = menu.add, child = {}, items = {}, parent = parent, layout = args.layout(), theme = load_theme(args.theme or {}, parent and parent.theme) }) if parent then _menu.auto_expand = parent.auto_expand elseif args.auto_expand ~= nil then _menu.auto_expand = args.auto_expand else _menu.auto_expand = true end -- Create items for i, v in ipairs(args) do _menu:add(v) end if args.items then for i, v in pairs(args.items) do _menu:add(v) end end _menu._keygrabber = function (...) grabber(_menu, ...) end _menu.wibox = wibox({ ontop = true, fg = _menu.theme.fg_normal, bg = _menu.theme.bg_normal, border_color = _menu.theme.border, border_width = _menu.theme.border_width, type = "popup_menu" }) _menu.wibox.visible = false _menu.wibox:set_widget(_menu.layout) set_size(_menu) _menu.x = _menu.wibox.x _menu.y = _menu.wibox.y return _menu end function menu.mt:__call(...) return menu.new(...) end return setmetatable(menu, menu.mt) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
cservan/OpenNMT_scores_0.2.0
onmt/utils/Memory.lua
1
1719
local Memory = {} --[[ Optimize memory usage of Neural Machine Translation. Parameters: * `model` - a table containing encoder and decoder * `criterion` - a single target criterion object * `batch` - a Batch object * `verbose` - produce output or not Example: local model = {} model.encoder = onmt.Models.buildEncoder(...) model.decoder = onmt.Models.buildDecoder(...) Memory.optimize(model, criterion, batch, verbose) ]] function Memory.optimize(model, criterion, batch, verbose) if verbose then _G.logger:info('Preparing memory optimization...') end -- Prepare memory optimization local memoryOptimizer = onmt.utils.MemoryOptimizer.new({model.encoder, model.decoder}) -- Batch of one single word since we optimize the first clone. local realSizes = { sourceLength = batch.sourceLength, targetLength = batch.targetLength } batch.sourceLength = 1 batch.targetLength = 1 -- Initialize all intermediate tensors with a first batch. local encStates, context = model.encoder:forward(batch) local decOutputs = model.decoder:forward(batch, encStates, context) decOutputs = onmt.utils.Tensor.recursiveClone(decOutputs) local encGradStatesOut, gradContext, _ = model.decoder:backward(batch, decOutputs, criterion) model.encoder:backward(batch, encGradStatesOut, gradContext) -- mark shared tensors local sharedSize, totSize = memoryOptimizer:optimize() if verbose then _G.logger:info(' * sharing %d%% of output/gradInput tensors memory between clones', (sharedSize / totSize)*100) end -- Restore batch to be transparent for the calling code. batch.sourceLength = realSizes.sourceLength batch.targetLength = realSizes.targetLength end return Memory
mit
ddumont/darkstar
scripts/zones/Tavnazian_Safehold/Zone.lua
12
3369
----------------------------------- -- -- Zone: Tavnazian_Safehold (26) -- ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) zone:registerRegion(1, -5, -24, 18, 5, -20, 27); zone:registerRegion(2, 104, -42, -88, 113, -38, -77); end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(27.971,-14.068,43.735,66); end if (player:getCurrentMission(COP) == AN_INVITATION_WEST) then if (player:getVar("PromathiaStatus") == 1) then cs = 0x0065; end elseif (player:getCurrentMission(COP) == SHELTERING_DOUBT and player:getVar("PromathiaStatus") == 0) then cs = 0x006B; elseif (player:getCurrentMission(COP) == CHAINS_AND_BONDS and player:getVar("PromathiaStatus") == 1) then cs = 0x0072; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { [1] = function (x) if (player:getCurrentMission(COP) == AN_ETERNAL_MELODY and player:getVar("PromathiaStatus") == 2) then player:startEvent(0x0069); end end, [2] = function (x) if (player:getCurrentMission(COP) == SLANDEROUS_UTTERINGS and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x0070); end end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0065) then player:completeMission(COP,AN_INVITATION_WEST); player:addMission(COP,THE_LOST_CITY); player:setVar("PromathiaStatus",0); elseif (csid == 0x0069) then player:setVar("PromathiaStatus",0); player:completeMission(COP,AN_ETERNAL_MELODY); player:addMission(COP,ANCIENT_VOWS); elseif (csid == 0x006B) then player:setVar("PromathiaStatus",1); elseif (csid == 0x0070) then player:setVar("PromathiaStatus",1); elseif (csid == 0x0072) then player:setVar("PromathiaStatus",2); end end;
gpl-3.0
ddumont/darkstar
scripts/zones/Abyssea-Uleguerand/npcs/qm1.lua
14
1392
----------------------------------- -- Zone: Abyssea-Uleguerand -- NPC: qm1 (???) -- Spawns Ironclad Triturator -- @pos ? ? ? 253 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3245,1) and trade:hasItemQty(3251,1) and trade:getItemCount() == 2) then -- Player has all the required items. if (GetMobAction(17813925) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17813925):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3245, 3251); -- Inform player what items they need. end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
smartdevicelink/sdl_atf_test_scripts
test_scripts/WebEngine/007_SetAppProperties_with_invalid_parameters.lua
1
3239
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0240-sdl-js-pwa.md -- -- Description: -- Verify that the SDL responds with success:false, "INVALID_DATA" on request with invalid parameters type -- -- Precondition: -- 1. SDL and HMI are started -- -- Sequence: -- 1. HMI sends BC.SetAppProperties request with invalid parameters type -- a. SDL sends response with success:false, "INVALID_DATA" to HMI -- 2. HMI sends BC.GetAppProperties request with wrong policyAppID to SDL -- a. SDL sends response with success:false, "DATA_NOT_AVAILABLE" to HMI -- 3. HMI sends BC.SetAppProperties request with application properties of the policyAppID to SDL -- a. SDL sends successful response to HMI -- 4. HMI sends BC.SetAppProperties request with invalid parameters type -- a. SDL sends response with success:false, "INVALID_DATA" to HMI -- 5. HMI sends BC.GetAppProperties request with policyAppID to SDL -- a. SDL sends successful response with application properties of the policyAppID to HMI --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local common = require('test_scripts/WebEngine/commonWebEngine') --[[ Local Variables ]] local invalidAppPropType = { -- value type is updated to string instead of array nicknames = "Test Web Application invalidType", -- value type is updated to integer instead of string policyAppID = 5, -- value type is updated to string instead of boolean enabled = "false", -- value type is updated to integer instead of string authToken = 12345, -- value type is updated to integer instead of string transportType = 123, -- value type is updated to array instead of individual value ("BOTH", "CLOUD", "MOBILE") hybridAppPreference = {"CLOUD", "MOBILE"}, -- value type is updated to integer instead of string endpoint = 8080 } -- [[ Scenario ]] common.Title("Preconditions") common.Step("Clean environment", common.preconditions) common.Step("Start SDL, HMI, connect regular mobile, start Session", common.start) common.Title("Test") for parameter, value in pairs(invalidAppPropType) do common.Step("SetAppProperties request: invalid parameter type " .. parameter .. " with ".. tostring(value), common.errorRPCprocessingUpdate, { "SetAppProperties", common.resultCode.INVALID_DATA, parameter, value }) common.Step("GetAppProperties request: with policyAppID", common.errorRPCprocessing, { "GetAppProperties", common.resultCode.DATA_NOT_AVAILABLE }) end common.Step("SetAppProperties request for policyAppID", common.setAppProperties, { common.defaultAppProperties }) for parameter, value in pairs(invalidAppPropType) do common.Step("SetAppProperties request: invalid parameter type " .. parameter .. " with ".. tostring(value), common.errorRPCprocessingUpdate, { "SetAppProperties", common.resultCode.INVALID_DATA, parameter, value }) common.Step("GetAppProperties request: with policyAppID", common.getAppProperties, { common.defaultAppProperties }) end common.Title("Postconditions") common.Step("Stop SDL", common.postconditions)
bsd-3-clause
Squeakz/darkstar
scripts/globals/spells/bluemagic/radiant_breath.lua
25
2259
----------------------------------------- -- Spell: Radiant Breath -- Deals light damage to enemies within a fan-shaped area of effect originating from the caster. Additional effect: Slow and Silence. -- Spell cost: 116 MP -- Monster Type: Wyverns -- Spell Type: Magical (Light) -- Blue Magic Points: 4 -- Stat Bonus: CHR+1, HP+5 -- Level: 54 -- Casting Time: 5.25 seconds -- Recast Time: 33.75 seconds -- Magic Bursts on: Transfixion, Fusion, Light -- Combos: None ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage local multi = 2.90; if (caster:hasStatusEffect(EFFECT_AZURE_LORE)) then multi = multi + 0.50; end params.multiplier = multi; params.tMultiplier = 1.5; params.duppercap = 69; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0; damage = BlueMagicalSpell(caster, target, spell, params, MND_BASED); damage = BlueFinalAdjustments(caster, target, spell, damage, params); local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0); if (damage > 0 and resist > 0.3) then local typeEffect = EFFECT_SLOW; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,35,0,getBlueEffectDuration(caster,resist,typeEffect)); end if (damage > 0 and resist > 0.3) then local typeEffect = EFFECT_SILENCE; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,25,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
Squeakz/darkstar
scripts/zones/Attohwa_Chasm/mobs/Sargas.lua
4
2114
----------------------------------- -- Area: Attohwa Chasm -- NM: Sargas ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); mob:setMobMod(MOBMOD_AUTO_SPIKES,mob:getShortID()); mob:addStatusEffect(EFFECT_SHOCK_SPIKES,50,0,0); mob:getStatusEffect(EFFECT_SHOCK_SPIKES):setFlag(32); end; ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(mob,target,damage) -- Guestimating 2 in 3 chance to stun on melee. if ((math.random(1,100) >= 66) or (target:hasStatusEffect(EFFECT_STUN) == true)) then return 0,0,0; else local duration = math.random(5,15); target:addStatusEffect(EFFECT_STUN,5,0,duration); return SUBEFFECT_STUN,0,EFFECT_STUN; end end; ----------------------------------- -- onSpikesDamage ----------------------------------- function onSpikesDamage(mob,target,damage) local INT_diff = mob:getStat(MOD_INT) - target:getStat(MOD_INT); if (INT_diff > 20) then INT_diff = 20 + ((INT_diff - 20)*0.5); -- INT above 20 is half as effective. end local dmg = ((damage+INT_diff)*0.5); -- INT adjustment and base damage averaged together. local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(mob, ELE_THUNDER, target, dmg, params); dmg = dmg * applyResistanceAddEffect(mob,target,ELE_THUNDER,0); dmg = adjustForTarget(target,dmg,ELE_THUNDER); dmg = finalMagicNonSpellAdjustments(mob,target,ELE_THUNDER,dmg); if (dmg < 0) then dmg = 0; end return SUBEFFECT_SHOCK_SPIKES,44,dmg; end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) -- UpdateNMSpawnPoint(mob:getID()); mob:setRespawnTime(math.random((7200),(10800))); -- 2 to 3 hrs end;
gpl-3.0
Squeakz/darkstar
scripts/globals/items/plate_of_sea_spray_risotto.lua
18
1627
----------------------------------------- -- ID: 4268 -- Item: plate_of_sea_spray_risotto -- Food Effect: 4Hrs, All Races ----------------------------------------- -- HP 45 -- Dexterity 6 -- Agility 3 -- Mind -4 -- HP Recovered While Healing 1 -- Accuracy % 6 (cap 20) ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4343); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 45); target:addMod(MOD_DEX, 6); target:addMod(MOD_AGI, 3); target:addMod(MOD_MND, -4); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_FOOD_ACCP, 6); target:addMod(MOD_FOOD_ACC_CAP, 20); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 45); target:delMod(MOD_DEX, 6); target:delMod(MOD_AGI, 3); target:delMod(MOD_MND, -4); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_FOOD_ACCP, 6); target:delMod(MOD_FOOD_ACC_CAP, 20); end;
gpl-3.0
smartdevicelink/sdl_atf_test_scripts
test_scripts/AppServices/RPCPassThrough/011_UnknownRpc_Unsupported_Request.lua
1
3950
--------------------------------------------------------------------------------------------------- -- Precondition: -- 1) app1 and app2 are registered on SDL. -- 2) AppServiceProvider permissions(with NAVIGATION AppService permissions to handle rpc FutureRequest) are assigned for <app1ID> -- 3) allow_unknown_rpc_passthrough is set to true for <app2ID> -- 4) app1 sends a PublishAppService (with {serviceType=NAVIGATION, handledRPC=FutureRequest} in the manifest) -- -- Steps: -- 1) app2 sends a FutureRequest request to core -- -- Expected: -- 1) Core forwards the request to app1 -- 2) app1 responds to Core with { success = false, resultCode = "UNSUPPORTED_REQUEST", info = "Request CANNOT be handled by app services" } -- 3) Core sees that the original request function ID is unknown and sends {success = true, resultCode = "UNSUPPORTED_REQUEST"} to app2 --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('test_scripts/AppServices/commonAppServices') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local variables ]] local rpcRequest = { name = "FutureRequest", hmi_name = "FutureInterface.FutureRequest", func_id = 956, params = { futureParam = 50, futureParam2 = { 50 }, futureParam3 = "StringValue" }, hmi_params = { futureParam = 50, futureParam2 = { 50 }, futureParam3 = "StringValue" } } local unsupportedResponse = { success = false, resultCode = "UNSUPPORTED_REQUEST" } local manifest = { serviceName = config.application1.registerAppInterfaceParams.appName, serviceType = "NAVIGATION", handledRPCs = { rpcRequest.func_id }, allowAppConsumers = true, rpcSpecVersion = config.application1.registerAppInterfaceParams.syncMsgVersion, navigationServiceManifest = {} } local rpcResponse = { params = unsupportedResponse } --[[ Local functions ]] local function PTUfunc(tbl) --Add permissions for app1 local pt_entry = common.getAppServiceProducerConfig(1) pt_entry.app_services.NAVIGATION = { handled_rpcs = {{function_id = rpcRequest.func_id}} } tbl.policy_table.app_policies[common.getConfigAppParams(1).fullAppID] = pt_entry --Add permissions for app2 pt_entry = common.getAppDataForPTU(2) pt_entry.groups = { "Base-4" } pt_entry.allow_unknown_rpc_passthrough = true tbl.policy_table.app_policies[common.getConfigAppParams(2).fullAppID] = pt_entry end local function RPCPassThruTest() local providerMobileSession = common.getMobileSession(1) local mobileSession = common.getMobileSession(2) local cid = mobileSession:SendRPC(rpcRequest.func_id, rpcRequest.params) providerMobileSession:ExpectRequest(rpcRequest.func_id, rpcRequest.params):Do(function(_, data) providerMobileSession:SendResponse(rpcRequest.func_id, data.rpcCorrelationId, unsupportedResponse) end) --Core will NOT attempt to process message EXPECT_HMICALL(rpcRequest.hmi_name, rpcRequest.hmi_params):Times(0) --Core will respond with UNSUPPORTED_REQUEST because the RPC is unknown mobileSession:ExpectResponse(cid, rpcResponse.params) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("RAI App 1", common.registerApp) runner.Step("Activate App 1", common.activateApp) runner.Step("PTU", common.policyTableUpdate, { PTUfunc }) runner.Step("PublishAppService", common.publishMobileAppService, { manifest, 1 }) runner.Step("RAI App 2", common.registerAppWOPTU, { 2 }) runner.Step("Activate App 2", common.activateApp, { 2 }) runner.Title("Test") runner.Step("RPCPassThroughTest_UNSUPPORTED", RPCPassThruTest) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
bsd-3-clause
Squeakz/darkstar
scripts/zones/Port_Windurst/npcs/Odilia.lua
13
1044
----------------------------------- -- Area: Port Windurst -- NPC: Odilia -- Type: Standard NPC -- @zone: 240 -- @pos 78.801 -6 118.653 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0121); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Squeakz/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Dynamis_Lord.lua
23
2056
----------------------------------- -- Area: Dynamis Xarcabard -- NM: Dynamis_Lord -- -- In OLD Dynamis, he is spawned by killing 15 Kindred NMs.. -- ..NOT by killing Ying and Yang. -- -- In Neo Dynamis, he is spawned by trading -- a Shrouded Bijou to the ??? in front of Castle Zvahl. ----------------------------------- require("scripts/globals/status"); require("scripts/globals/titles"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) local YingID = 17330183; local YangID = 17330184; if (mob:getBattleTime() % 90 == 0 and mob:getBattleTime() >= 90) then if (GetMobAction(YingID) == ACTION_NONE and GetMobAction(YangID) == ACTION_NONE) then GetMobByID(YingID):setSpawn(-414.282,-44,20.427); -- These come from DL's spawn point when he spawns them. GetMobByID(YangID):setSpawn(-414.282,-44,20.427); SpawnMob(YingID):updateEnmity(target); -- Respawn the dragons after 90sec SpawnMob(YangID):updateEnmity(target); end end if (GetMobAction(YingID) == ACTION_ROAMING) then -- ensure that it's always going after someone, can't kite it away! GetMobByID(YingID):updateEnmity(target); end if (GetMobAction(YangID) == ACTION_ROAMING) then GetMobByID(YangID):updateEnmity(target); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) local npc = GetNPCByID(17330781); -- ID of the '???' target. player:addTitle(LIFTER_OF_SHADOWS); npc:setPos(mob:getXPos(),mob:getYPos(),mob:getZPos()); npc:setStatus(0); -- Spawn the '???' DespawnMob(17330183); -- despawn dragons DespawnMob(17330184); end;
gpl-3.0
jlcvp/otxserver
data/lib/core/storages.lua
2
2002
Storage = { -- General storages isTraining = 30000, NpcExhaust = 30001, RentedHorseTimer = 30015, -- Promotion Storage cannot be changed, it is set in source code Promotion = 30018, combatProtectionStorage = 30023, Factions = 30024, blockMovementStorage = 30025, FamiliarSummon = 30026, TrainerRoom = 30027, NpcSpawn = 30028, ExerciseDummyExhaust = 30029, StrawberryCupcake = 30032, StoreExaust = 30051, LemonCupcake = 30052, BlueberryCupcake = 30053, FamiliarSummonEvent10 = 30054, FamiliarSummonEvent60 = 30055, FreeQuests = 30057, PremiumAccount = 30058, --[[ Old storages Over time, this will be dropped and replaced by the table above ]] Grimvale = { -- Reserved storage from 50380 - 50399 SilverVein = 50380, WereHelmetEnchant = 50381 }, OutfitQuest = { -- Reserved storage from 50960 - 51039 -- Until all outfit quests are completed DefaultStart = 50960, Ref = 50961, -- Golden Outfit GoldenOutfit = 51015, }, AdventurersGuild = { -- Reserved storage from 52130 - 52159 Stone = 52130, }, } GlobalStorage = { ExpBoost = 65004, XpDisplayMode = 65006, OberonEventTime = 65009, ScarlettEtzelEventTime = 65011, CobraBastionFlask = 65012, KeysUpdate = 40000, -- Reserved storage from 40000 - 40000 } -- Values extraction function local function extractValues(tab, ret) if type(tab) == "number" then table.insert(ret, tab) else for _, v in pairs(tab) do extractValues(v, ret) end end end local extraction = {} extractValues(Storage, extraction) -- Call function table.sort(extraction) -- Sort the table -- The choice of sorting is due to the fact that sorting is very cheap O (n log2 (n)) -- And then we can simply compare one by one the elements finding duplicates in O(n) -- Scroll through the extracted table for duplicates if #extraction > 1 then for i = 1, #extraction - 1 do if extraction[i] == extraction[i+1] then Spdlog.warn(string.format("Duplicate storage value found: %d", extraction[i])) end end end
gpl-2.0
ddumont/darkstar
scripts/globals/items/serving_of_mont_blanc.lua
12
1483
----------------------------------------- -- ID: 5557 -- Item: Serving of Mont Blanc -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +8 -- MP +10 -- Intelligence +1 -- HP Recoverd while healing 1 -- MP Recovered while healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5557); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 8); target:addMod(MOD_MP, 10); target:addMod(MOD_INT, 1); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 8); target:delMod(MOD_MP, 10); target:delMod(MOD_INT, 1); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
jlcvp/otxserver
data/monster/mammals/bear.lua
2
2631
local mType = Game.createMonsterType("Bear") local monster = {} monster.description = "a bear" monster.experience = 23 monster.outfit = { lookType = 16, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.raceId = 16 monster.Bestiary = { class = "Mammal", race = BESTY_RACE_MAMMAL, toKill = 500, FirstUnlock = 25, SecondUnlock = 250, CharmsPoints = 15, Stars = 2, Occurrence = 0, Locations = "Several spawns near Kazordoon, Femor Hills, north of Thais, near the White Flower Temple, \z Rookgaard Bear Cave, Bear Room Quest in Rookgaard, Rookgaard Bear Mountain, South of Villa Scapula, \z Ferngrims Gate, North of Carlin, Fields of Glory, Edron Troll Cave, south of Venore, Desert Dungeon, \z first floor of the Orc Fort mountain and west of Outlaw Camp." } monster.health = 80 monster.maxHealth = 80 monster.race = "blood" monster.corpse = 5975 monster.speed = 156 monster.manaCost = 300 monster.changeTarget = { interval = 4000, chance = 0 } monster.strategiesTarget = { nearest = 100, } monster.flags = { summonable = true, attackable = true, hostile = true, convinceable = true, pushable = false, rewardBoss = false, illusionable = true, canPushItems = false, canPushCreatures = false, staticAttackChance = 90, targetDistance = 1, runHealth = 15, healthHidden = false, isBlockable = false, canWalkOnEnergy = false, canWalkOnFire = false, canWalkOnPoison = false } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, {text = "Grrrr", yell = false}, {text = "Groar", yell = false} } monster.loot = { {name = "meat", chance = 39750, maxCount = 4}, {name = "ham", chance = 20000, maxCount = 3}, {name = "bear paw", chance = 2000}, {name = "honeycomb", chance = 460} } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -25} } monster.defenses = { defense = 10, armor = 10 } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 0}, {type = COMBAT_EARTHDAMAGE, percent = 0}, {type = COMBAT_FIREDAMAGE, percent = 0}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = -10}, {type = COMBAT_HOLYDAMAGE , percent = 10}, {type = COMBAT_DEATHDAMAGE , percent = -5} } monster.immunities = { {type = "paralyze", condition = false}, {type = "outfit", condition = false}, {type = "invisible", condition = false}, {type = "bleed", condition = false} } mType:register(monster)
gpl-2.0
ddumont/darkstar
scripts/globals/items/bowl_of_seafood_stew.lua
12
1463
----------------------------------------- -- ID: 4561 -- Item: Bowl of Seafood Stew -- Food Effect: 180Min, All Races ----------------------------------------- -- Health 20 -- Dexterity 1 -- Vitality 5 -- Defense % 25 -- Defense Cap 120 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4561); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_DEX, 1); target:addMod(MOD_VIT, 5); target:addMod(MOD_FOOD_DEFP, 25); target:addMod(MOD_FOOD_DEF_CAP, 120); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_DEX, 1); target:delMod(MOD_VIT, 5); target:delMod(MOD_FOOD_DEFP, 25); target:delMod(MOD_FOOD_DEF_CAP, 120); end;
gpl-3.0
ddumont/darkstar
scripts/zones/Giddeus/npcs/Laa_Mozi.lua
14
2157
----------------------------------- -- Area: Giddeus -- NPC: Laa Mozi -- Involved in Mission 1-3 -- @pos -22 0 148 145 ----------------------------------- package.loaded["scripts/zones/Giddeus/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/zones/Giddeus/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(WINDURST) == THE_PRICE_OF_PEACE) then if (player:hasKeyItem(FOOD_OFFERINGS)) then -- We have the offerings player:startEvent(0x002d); else if (player:getVar("laa_talk") == 1) then -- npc: You want your offering back? player:startEvent(0x002e); elseif (player:getVar("laa_talk") == 2) then -- npc: You'll have to crawl back to treasure chamber, etc player:startEvent(0x002f); else -- We don't have the offerings yet or anymore player:startEvent(0x0030); end end else player:startEvent(0x0030); end end ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x002d) then player:delKeyItem(FOOD_OFFERINGS); player:setVar("laa_talk",1); if (player:hasKeyItem(DRINK_OFFERINGS) == false) then player:setVar("MissionStatus",2); end elseif (csid == 0x002e) then player:setVar("laa_talk",2); end end;
gpl-3.0
jchuang1977/luci-1
applications/luci-app-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
10
5915
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Copyright 2012 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.luci_statistics.luci_statistics", package.seeall) function index() require("nixio.fs") require("luci.util") require("luci.statistics.datatree") -- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path function _entry( path, ... ) local file = path[5] or path[4] if nixio.fs.access( "/usr/lib/collectd/" .. file .. ".so" ) then entry( path, ... ) end end local labels = { s_output = _("Output plugins"), s_system = _("System plugins"), s_network = _("Network plugins"), conntrack = _("Conntrack"), cpu = _("Processor"), csv = _("CSV Output"), df = _("Disk Space Usage"), disk = _("Disk Usage"), dns = _("DNS"), email = _("Email"), entropy = _("Entropy"), exec = _("Exec"), interface = _("Interfaces"), iptables = _("Firewall"), irq = _("Interrupts"), iwinfo = _("Wireless"), load = _("System Load"), memory = _("Memory"), netlink = _("Netlink"), network = _("Network"), nut = _("UPS"), olsrd = _("OLSRd"), ping = _("Ping"), processes = _("Processes"), rrdtool = _("RRDTool"), splash_leases = _("Splash Leases"), tcpconns = _("TCP Connections"), unixsock = _("UnixSock"), uptime = _("Uptime") } -- our collectd menu local collectd_menu = { output = { "csv", "network", "rrdtool", "unixsock" }, system = { "cpu", "df", "disk", "email", "entropy", "exec", "irq", "load", "memory", "nut", "processes", "uptime" }, network = { "conntrack", "dns", "interface", "iptables", "netlink", "olsrd", "ping", "splash_leases", "tcpconns", "iwinfo" } } -- create toplevel menu nodes local st = entry({"admin", "statistics"}, template("admin_statistics/index"), _("Statistics"), 80) st.index = true entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _("Collectd"), 10).subindex = true -- populate collectd plugin menu local index = 1 for section, plugins in luci.util.kspairs( collectd_menu ) do local e = entry( { "admin", "statistics", "collectd", section }, firstchild(), labels["s_"..section], index * 10 ) e.index = true for j, plugin in luci.util.vspairs( plugins ) do _entry( { "admin", "statistics", "collectd", section, plugin }, cbi("luci_statistics/" .. plugin ), labels[plugin], j * 10 ) end index = index + 1 end -- output views local page = entry( { "admin", "statistics", "graph" }, template("admin_statistics/index"), _("Graphs"), 80) page.setuser = "nobody" page.setgroup = "nogroup" local vars = luci.http.formvalue(nil, true) local span = vars.timespan or nil local host = vars.host or nil -- get rrd data tree local tree = luci.statistics.datatree.Instance(host) local _, plugin, idx for _, plugin, idx in luci.util.vspairs( tree:plugins() ) do -- get plugin instances local instances = tree:plugin_instances( plugin ) -- plugin menu entry entry( { "admin", "statistics", "graph", plugin }, call("statistics_render"), labels[plugin], idx ).query = { timespan = span , host = host } -- if more then one instance is found then generate submenu if #instances > 1 then local _, inst, idx2 for _, inst, idx2 in luci.util.vspairs(instances) do -- instance menu entry entry( { "admin", "statistics", "graph", plugin, inst }, call("statistics_render"), inst, idx2 ).query = { timespan = span , host = host } end end end end function statistics_render() require("luci.statistics.rrdtool") require("luci.template") require("luci.model.uci") local vars = luci.http.formvalue() local req = luci.dispatcher.context.request local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true ) local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1] local host = vars.host or uci:get( "luci_statistics", "collectd", "Hostname" ) or luci.sys.hostname() local opts = { host = vars.host } local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ), opts ) local hosts = graph.tree:host_instances() local is_index = false local i, p, inst, idx -- deliver image if vars.img then local l12 = require "luci.ltn12" local png = io.open(graph.opts.imgpath .. "/" .. vars.img:gsub("%.+", "."), "r") if png then luci.http.prepare_content("image/png") l12.pump.all(l12.source.file(png), luci.http.write) end return end local plugin, instances local images = { } -- find requested plugin and instance for i, p in ipairs( luci.dispatcher.context.path ) do if luci.dispatcher.context.path[i] == "graph" then plugin = luci.dispatcher.context.path[i+1] instances = { luci.dispatcher.context.path[i+2] } end end -- no instance requested, find all instances if #instances == 0 then --instances = { graph.tree:plugin_instances( plugin )[1] } instances = graph.tree:plugin_instances( plugin ) is_index = true -- index instance requested elseif instances[1] == "-" then instances[1] = "" is_index = true end -- render graphs for i, inst in luci.util.vspairs( instances ) do for i, img in luci.util.vspairs( graph:render( plugin, inst, is_index ) ) do table.insert( images, graph:strippngpath( img ) ) images[images[#images]] = inst end end luci.template.render( "public_statistics/graph", { images = images, plugin = plugin, timespans = spans, current_timespan = span, hosts = hosts, current_host = host, is_index = is_index } ) end
apache-2.0
Squeakz/darkstar
scripts/zones/Bastok_Markets/npcs/Marin.lua
13
1136
----------------------------------- -- Area: Bastok Markets -- NPC: Marin -- Type: Quest Giver -- @zone: 235 -- @pos -340.060 -11.003 -148.181 -- -- Auto-Script: Requires Verification. Verified standard dialog is also "All By Myself" repeatable quest. - thrydwolf 12/18/2011 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0169); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Squeakz/darkstar
scripts/zones/Lufaise_Meadows/npcs/Ghost_Talker_IM.lua
13
3327
----------------------------------- -- Area: Lufaise Meadows -- NPC: Ghost Talker, I.M. -- Border Conquest Guards -- @pos 414.659 0.905 -52.417 24 ----------------------------------- package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Lufaise_Meadows/TextIDs"); local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = TAVNAZIANARCH; local csid = 0x7ff8; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
ddumont/darkstar
scripts/zones/Bastok_Mines/TextIDs.lua
5
6501
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- Come back after sorting your inventory. FULL_INVENTORY_AFTER_TRADE = 6383; -- Try trading again after sorting your inventory. ITEM_OBTAINED = 6385; -- Obtained: <<<Unknown Parameter (Type: 80) 1>>><<<Possible Special Code: 01>>><<<Possible Special Code: 05>>> GIL_OBTAINED = 6386; -- Obtained <<<Numeric Parameter 0>>> gil. NOT_HAVE_ENOUGH_GIL = 6390; -- You do not have enough gil. KEYITEM_OBTAINED = 6388; -- Obtained key item: <<<Unknown Parameter (Type: 80) 1>>> HOMEPOINT_SET = 6476; -- Home point set! ALCHEMY_SUPPORT = 7048; -- Your Multiple Choice (Parameter 1)[fishing/woodworking/smithing/goldsmithing/clothcraft/leatherworking/bonecraft/alchemy/cooking] skills went up GUILD_TERMINATE_CONTRACT = 7062; -- You have terminated your trading contract with the Multiple Choice (Parameter 1)[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild and formed a new one with the Multiple Choice (Parameter 0)[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild GUILD_NEW_CONTRACT = 7070; -- You have formed a new trading contract with the Multiple Choice (Parameter 0)[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild NO_MORE_GP_ELIGIBLE = 7077; -- You are not eligible to receive guild points at this time. GP_OBTAINED = 7082; -- Obtained: ?Numeric Parameter 0? guild points. NOT_HAVE_ENOUGH_GP = 7083; -- You do not have enough guild points. FISHING_MESSAGE_OFFSET = 10794; -- You can't fish here. -- Conquest System CONQUEST = 11105; --You've earned conquest points! -- Mission Dialogs YOU_ACCEPT_THE_MISSION = 6505; -- You have accepted the mission. ORIGINAL_MISSION_OFFSET = 6510; -- You can consult the ission section of the main menu to review your objectives. Speed and efficiency are your priorities. Dismissed. EXTENDED_MISSION_OFFSET = 11608; -- Go to Ore Street and talk to Medicine Eagle. He says he was there when the commotion started. -- Dynamis dialogs YOU_CANNOT_ENTER_DYNAMIS = 11718; -- You cannot enter Dynamis PLAYERS_HAVE_NOT_REACHED_LEVEL = 11720; -- Players who have not reached levelare prohibited from entering Dynamis. UNUSUAL_ARRANGEMENT_PEBBLES = 11731; -- There is an unusual arrangement of pebbles here. -- Dialog Texts HEMEWMEW_DIALOG = 7055; -- I have been appointed by the Guildworkers' Union to manage the trading of manufactured crafts and the exchange of guild points. VIRNAGE_DIALOG_1 = 10976; -- They stayed in a citadel on the Sauromugue Champaign. The paint may be there still! VIRNAGE_DIALOG_2 = 10982; -- Hand my letter to Eperdur in the San d'Oria Cathedral to claim your reward. THE_GATE_IS_LOCKED = 12153; -- The gate is locked. -- Harvest Festival TRICK_OR_TREAT = 11680; -- Trick or treat... THANK_YOU_TREAT = 11681; -- And now for your treat... HERE_TAKE_THIS = 11682; -- Here, take this... IF_YOU_WEAR_THIS = 11683; -- If you put this on and walk around, something...unexpected might happen... THANK_YOU = 11681; -- Thank you... -- Shop Texts FAUSTIN_CLOSED_DIALOG = 10773; -- I'm trying to start a business selling goods from Ronfaure, RODELLIEUX_CLOSED_DIALOG = 10774; -- I'm trying to start a business selling goods from Fauregandi, MILLE_CLOSED_DIALOG = 10775; -- I'm trying to start a business selling goods from Norvallen, TIBELDA_CLOSED_DIALOG = 10776; -- I'm trying to start a business selling goods from Valdeaunia, GALDEO_CLOSED_DIALOG = 10777; -- I'm trying to start a business selling goods from Li'Telor, DEEGIS_SHOP_DIALOG = 10894; -- The only things an adventurer needs are courage and a good suit of armor! Welcome to Deegis's Armour! ZEMEDARS_SHOP_DIALOG = 10895; -- Everything in our store is top-grade and Galka-made! What're you lookin' for? BOYTZ_SHOP_DIALOG = 10896; -- Welcome to Boytz's Knickknacks. GELZERIO_SHOP_DIALOG = 10897; -- ...Yes? GRISELDA_SHOP_DIALOG = 10898; -- Good of you to drop by the Bat's Lair Inn! Why don't you try some of our specialty plates? NEIGEPANCE_SHOP_DIALOG = 10899; -- Hello there. A well-fed chocobo is a happy chocobo! FAUSTIN_OPEN_DIALOG = 10900; -- Hello there! Might I interest you specialty goods from Ronfaure? MILLE_OPEN_DIALOG = 10901; -- Hello there! Might I interest you specialty goods from Norvallen? RODELLIEUX_OPEN_DIALOG = 10902; -- Hello there! Might I interest you specialty goods from Fauregandi? TIBELDA_OPEN_DIALOG = 10903; -- Goods of all varieties, imported directly from the northern land of Valdeaunia! MAYMUNAH_SHOP_DIALOG = 10904; -- Welcome to the Alchemists' Guild! Looking for something specific? ODOBA_SHOP_DIALOG = 10905; -- Welcome to the Alchemists' Guild. How may I help you? GALDEO_OPEN_DIALOG = 11465; -- Come! Take a look at all the wonderful goods from Li'Telor. AULAVIA_OPEN_DIALOG = 11466; -- May I interest you in some specialty goods from Vollbow? AULAVIA_CLOSED_DIALOG = 11467; -- I'm trying to start a business selling goods from Vollbow, PROUDBEARD_SHOP_DIALOG = 11636; -- Would you be interested in a nice suit of adventurer-issue armor? Be careful when you buy, though. We offer no refunds. EMALIVEULAUX_COP_NOT_COMPLETED = 12234; -- I'd like to start my own business someday, but I just haven't found anything that truly interests me. EMALIVEULAUX_OPEN_DIALOG = 12235; -- Rare Tavnazian imports! Get them before they're gone! EMALIVEULAUX_CLOSED_DIALOG = 12236; -- I'd love to sell you goods imported from the island of Tavnazia, but with the area under foreign control, I can't secure my trade routes... -- Weather Dialog MARIADOK_DIALOG = 6737; -- Your fate rides on the changing winds of Vana'diel. I can give you insight on the local weather. -- Standard NPC Dialog ITEM_DELIVERY_DIALOG = 10429; -- Need something sent to a friend's house? Sending items to your own house? You've come to the right place! -- conquest Base CONQUEST_BASE = 6578; -- Tallying conquest results...
gpl-3.0
smartdevicelink/sdl_atf_test_scripts
test_scripts/API/VehicleData/VehicleDataVersioning/007_VD_parameter_DB_app_version_equal_to_parameter_version.lua
1
2253
--------------------------------------------------------------------------------------------------- -- Description: The app is able to retrieve the parameter in case app version is equal parameter version, -- parameter is listed in DB -- In case: -- 1. App is registered with syncMsgVersion=5.5 -- 2. Parameter has since=5.5 DB -- 3. App requests GetVehicleData(<Parameter>) -- SDL does: -- a. process the request successful --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('test_scripts/API/VehicleData/VehicleDataVersioning/common') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false config.application1.registerAppInterfaceParams.syncMsgVersion.majorVersion = 5 config.application1.registerAppInterfaceParams.syncMsgVersion.minorVersion = 5 config.ValidateSchema = false --[[ Local Functions ]] local function ptuFunc(pTbl) pTbl.policy_table.vehicle_data = {} pTbl.policy_table.vehicle_data.schema_version = "00.00.01" pTbl.policy_table.vehicle_data.schema_items = { { name = "custom_vd_item1_integer", type = "Integer", key = "OEM_REF_INT", array = false, mandatory = false, minvalue = 0, maxvalue = 100, since = "5.5.0" } } pTbl.policy_table.functional_groupings.NewTestCaseGroup = common.cloneTable(pTbl.policy_table.functional_groupings["Emergency-1"]) pTbl.policy_table.functional_groupings.NewTestCaseGroup.rpcs.GetVehicleData.parameters = { "custom_vd_item1_integer" } pTbl.policy_table.app_policies[common.getConfigAppParams(1).fullAppID].groups = { "Base-4", "NewTestCaseGroup" } end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("RAI", common.registerApp) runner.Step("PTU", common.policyTableUpdate, { ptuFunc }) runner.Step("Activate App", common.activateApp) runner.Title("Test") runner.Step("RPC GetVehicleData", common.processGetVDwithCustomDataSuccess) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts
test_scripts/CloudAppRPCs/013_Same_app_name_mobile_app_Unregistered.lua
1
5209
--------------------------------------------------------------------------------------------------- -- Precondition: -- 1) Application with <appID> is registered on SDL. -- 2) Specific permissions are assigned for <appID> with SetCloudAppProperties -- 3) Application defines 2 cloud apps in PT by sending SetCloudAppProperties RPC requests: -- - AppA (hybridAppPreference=CLOUD) -- - AppB (hybridAppPreference=BOTH) -- -- Steps: -- 1) Mobile AppA is registered successfully -- 2) Cloud AppA is trying to register -- SDL does: -- - register cloud AppA successfully -- - unregister mobile AppA successfully -- 3) Mobile AppB is registered successfully -- 4) Cloud AppB is trying to register -- SDL does: -- - register cloud AppB successfully -- - not unregister mobile AppB --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('test_scripts/CloudAppRPCs/commonCloudAppRPCs') local utils = require("user_modules/utils") --[[ Conditions to scik test ]] if config.defaultMobileAdapterType == "WS" or config.defaultMobileAdapterType == "WSS" then runner.skipTest("Test is not applicable for WS/WSS connection") end --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local Functions ]] local hmiAppIDMap = {} local function setHybridApp(pAppId, pAppNameCode, pHybridAppPreference) local params = { properties = { nicknames = { "HybridApp" .. pAppNameCode }, appID = "000000" .. pAppId, enabled = true, authToken = "ABCD12345" .. pAppId, cloudTransportType = "WSS", hybridAppPreference = pHybridAppPreference, endpoint = "ws://127.0.0.1:808" .. pAppId .. "/" } } local cid = common.getMobileSession():SendRPC("SetCloudAppProperties", params) common.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" }) common.getHMIConnection():ExpectRequest("BasicCommunication.UpdateAppList"):Do(function(_,data) local apps = data.params.applications for i,v in ipairs(apps) do if v.appName == "HybridApp" .. pAppNameCode then print('Setting HMI App ID '.. pAppNameCode) hmiAppIDMap[pAppId] = v.appID -- end end end) end local function PTUfunc(tbl) tbl.policy_table.app_policies[common.getConfigAppParams(1).fullAppID] = common.getCloudAppStoreConfig(1); end local function connectMobDevice() local conId = 2 local deviceInfo = { host = "1.0.0.1", port = config.mobilePort } utils.addNetworkInterface(conId, deviceInfo.host) common.mobile.createConnection(conId, deviceInfo.host, deviceInfo.port) common.mobile.connect(conId) :Do(function() common.mobile.allowSDL(conId) end) end local function deleteMobDevices() utils.deleteNetworkInterface(2) end local function registerApp(pAppId, pConId, pAppNameCode, pActivateCloudApp, pUnregAppId) if (pActivateCloudApp) then common.getHMIConnection():SendRequest("SDL.ActivateApp", {appID = hmiAppIDMap[pAppId]}) end local session = common.getMobileSession(pAppId, pConId) session:StartService(7) :Do(function() local params = utils.cloneTable(common.app.getParams()) params.appName = "HybridApp" .. pAppNameCode params.appID = "000" .. pAppId params.fullAppID = "000000" .. pAppId local cid = session:SendRPC("RegisterAppInterface", params) session:ExpectResponse(cid, { success = true, resultCode = "SUCCESS" }) session:ExpectNotification("OnPermissionsChange") session:ExpectNotification("OnHMIStatus"):Times(pActivateCloudApp == true and 2 or 1) common.getHMIConnection():ExpectNotification("BasicCommunication.OnAppRegistered") :Do(function(_, d) common.setHMIAppId(d.params.application.appID, pAppId) end) end) local occurrences = 0 if pUnregAppId then occurrences = 1 end common.getHMIConnection():ExpectNotification("BasicCommunication.OnAppUnregistered", { appID = common.getHMIAppId(pUnregAppId), unexpectedDisconnect = false }) :Times(occurrences) utils.wait(2000) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("RAI", common.registerApp) runner.Step("PTU", common.policyTableUpdate, { PTUfunc }) runner.Step("Activate App", common.activateApp) runner.Step("Add additional connection", connectMobDevice) runner.Step("Define Hybrid App A in PT as CLOUD", setHybridApp, { 2, "A", "CLOUD" }) runner.Step("Define Hybrid App B in PT as BOTH", setHybridApp, { 3, "B", "BOTH" }) runner.Title("Test") runner.Step("Register Mobile App A SUCCESS", registerApp, { 4, 1, "A" }) runner.Step("Register Cloud App A SUCCESS, Unregister Mobile App A", registerApp, { 2, 2, "A", true, 4 }) runner.Step("Register Mobile App B SUCCESS", registerApp, { 5, 1, "B" }) runner.Step("Register Cloud App B SUCCESS", registerApp, { 3, 2, "B", true}) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions) runner.Step("Remove additional connection", deleteMobDevices)
bsd-3-clause
kennethlombardi/moai-graphics
engine/resources/lua/ManagerGameLoop.lua
1
2666
local function preInitialize() -- require managers to perform singleton initialization require("ConfigurationManager"); require("UserDataManager"); require("MessageManager"); require("SimulationManager"); require("WindowManager"); require("ResourceManager"); require("LayerManager"); require("SceneManager"); require("SoundManager"); require("InputManager"); require("GameVariables"); print("PreInitialized"); end local done = false; local function onQuit(payload) done = true; end local function initialize() require("SimulationManager"):setLeakTrackingEnabled(true); require("SimulationManager"):setHistogramEnabled(true); -- require("SceneManager"):addSceneFromFile('assignment5-OctreeScene.lua'); -- require("SceneManager"):addSceneFromFile('assignment2-BoundingVolumesScene.lua'); require("SceneManager"):addSceneFromFile('cs350TestScene.lua'); -- simulation state -- MOAIGfxDevice.setClearDepth(true); MOAIGfxDevice.getFrameBuffer ():setClearDepth ( true ) require("MessageManager"):listen("QUIT", onQuit); require("MessageManager"):send("GAME_INITIALIZED") print("Initialized"); end local function preShutdown() --require("LayerManager"):getLayerByName("pickleFile0.lua"):serializeToFile("pickleFileDiff0.lua"); --require("LayerManager"):serializeLayerToFile(require("LayerManager"):getLayerIndexByName("pickleFile1.lua"), "pickleFileDiff1.lua"); end local function shutdown() require("LayerManager"):shutdown(); require("ResourceManager"):shutdown(); require("WindowManager"):shutdown(); require("SoundManager"):shutdown(); require("SceneManager"):shutdown(); require("ShapesLibrary"):shutdown(); require("GameVariables"):shutdown(); require("ConfigurationManager"):shutdown(); require("UserDataManager"):shutdown(); require("SimulationManager"):forceGarbageCollection(); require("SimulationManager"):reportLeaks(); require("SimulationManager"):forceGarbageCollection(); require("SimulationManager"):reportHistogram(); require("SimulationManager"):shutdown(); end local function update(dt) require("MessageManager"):update(dt); require("InputManager"):update(dt); require("LayerManager"):update(dt); require("SceneManager"):update(dt); require("SoundManager"):update(dt); require("SimulationManager"):update(dt); end function gamesLoop () preInitialize(); initialize(); while not done do update(require("SimulationManager"):getStep()); coroutine.yield() end preShutdown(); shutdown(); os.exit(); end return gamesLoop;
mit
ddumont/darkstar
scripts/zones/Selbina/npcs/Catus.lua
17
1067
----------------------------------- -- Area: Selbina -- NPC: Catus -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getZPos() < -28.750) then player:startEvent(0x00dc); else player:startEvent(0x00e5); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
imashkan/IMHAUL
plugins/anti-flood.lua
281
2422
local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds local TIME_CHECK = 5 local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, function (data, success, result) if success ~= 1 then local text = 'I can\'t kick '..data.user..' but should be kicked' send_msg(data.chat, '', ok_cb, nil) end end, {chat=chat, user=user}) end local function run (msg, matches) if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' else local chat = msg.to.id local hash = 'anti-flood:enabled:'..chat if matches[1] == 'enable' then redis:set(hash, true) return 'Anti-flood enabled on chat' end if matches[1] == 'disable' then redis:del(hash) return 'Anti-flood disabled on chat' end end end local function pre_process (msg) -- Ignore service msg if msg.service then print('Service message') return msg end local hash_enable = 'anti-flood:enabled:'..msg.to.id local enabled = redis:get(hash_enable) if enabled then print('anti-flood enabled') -- Check flood if msg.from.type == 'user' then -- Increase the number of messages from the user on the chat local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then local receiver = get_receiver(msg) local user = msg.from.id local text = 'User '..user..' is flooding' local chat = msg.to.id send_msg(receiver, text, ok_cb, nil) if msg.to.type ~= 'chat' then print("Flood in not a chat group!") elseif user == tostring(our_id) then print('I won\'t kick myself') elseif is_sudo(msg) then print('I won\'t kick an admin!') else -- Ban user -- TODO: Check on this plugin bans local bhash = 'banned:'..msg.to.id..':'..msg.from.id redis:set(bhash, true) kick_user(user, chat) end msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end end return msg end return { description = 'Plugin to kick flooders from group.', usage = {}, patterns = { '^!antiflood (enable)$', '^!antiflood (disable)$' }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
ddumont/darkstar
scripts/globals/spells/absorb-tp.lua
25
1446
-------------------------------------- -- Spell: Absorb-TP -- Steals an enemy's TP. -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local cap = 1200 local dmg = math.random(100, 1200); --get resist multiplier (1x if no resist) local resist = applyResistance(caster, spell, target, caster:getStat(MOD_INT)-target:getStat(MOD_INT), DARK_MAGIC_SKILL, 1.0); --get the resisted damage dmg = dmg * resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster, spell, target, dmg); --add in target adjustment dmg = adjustForTarget(target, dmg, spell:getElement()); --add in final adjustments if (resist <= 0.125) then spell:setMsg(85); dmg = 0 else spell:setMsg(454); dmg = dmg * ((100 + caster:getMod(MOD_AUGMENTS_ABSORB)) / 100) if ((target:getTP()) < dmg) then dmg = target:getTP(); end if (dmg > cap) then dmg = cap; end -- drain caster:addTP(dmg); target:addTP(-dmg); end return dmg; end;
gpl-3.0
jlcvp/otxserver
data/monster/quests/grave_danger/risen_soldier.lua
2
2105
local mType = Game.createMonsterType("Risen Soldier") local monster = {} monster.description = "an Risen Soldier" monster.experience = 0 monster.outfit = { lookType = 306, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.health = 20000 monster.maxHealth = 20000 monster.race = "undead" monster.corpse = 0 monster.speed = 220 monster.manaCost = 0 monster.changeTarget = { interval = 4000, chance = 10 } monster.strategiesTarget = { nearest = 100, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = false, illusionable = false, canPushItems = true, canPushCreatures = true, staticAttackChance = 90, targetDistance = 1, runHealth = 0, healthHidden = false, isBlockable = false, canWalkOnEnergy = false, canWalkOnFire = false, canWalkOnPoison = false } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, } monster.loot = { } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -450}, {name ="combat", interval = 2000, chance = 20, type = COMBAT_PHYSICALDAMAGE, minDamage = 0, maxDamage = -435, range = 7, shootEffect = CONST_ANI_WHIRLWINDSWORD, target = false} } monster.defenses = { defense = 45, armor = 45, {name ="invisible", interval = 2000, chance = 15, effect = CONST_ME_MAGIC_BLUE} } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 20}, {type = COMBAT_EARTHDAMAGE, percent = -10}, {type = COMBAT_FIREDAMAGE, percent = 80}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 0}, {type = COMBAT_HOLYDAMAGE , percent = 10}, {type = COMBAT_DEATHDAMAGE , percent = -5} } monster.immunities = { {type = "paralyze", condition = false}, {type = "outfit", condition = false}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType:register(monster)
gpl-2.0
Squeakz/darkstar
scripts/zones/Northern_San_dOria/npcs/Coullene.lua
13
1581
----------------------------------- -- Area: Northern San d'Oria -- NPC: Coullene -- Type: Involved in Quest (Flyers for Regine) -- @zone: 231 -- @pos 146.420 0.000 127.601 -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) ==QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeCoulene") == 0) then player:messageSpecial(COULLENE_DIALOG); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradeCoulene",1); player:messageSpecial(FLYER_ACCEPTED); player:tradeComplete(); elseif (player:getVar("tradeCoulene") ==1) then player:messageSpecial(FLYER_ALREADY); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,COULLENE_DIALOG); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
premake/premake-monodevelop
tests/test_sln.lua
2
1137
--- -- monodevelop/tests/test_sln.lua -- Automated test suite for MonoDevelop workspace generation. -- Copyright (c) 2011-2015 Manu Evans and the Premake project --- local suite = test.declare("monodevelop_workspace") local monodevelop = premake.modules.monodevelop --------------------------------------------------------------------------- -- Setup/Teardown --------------------------------------------------------------------------- local wks, prj, cfg function suite.setup() _ACTION = "monodevelop" premake.indent(" ") wks = workspace "MyWorkspace" configurations { "Debug", "Release" } kind "ConsoleApp" end function suite.slnProj() project "MyProject" premake.vstudio.sln2005.reorderProjects(wks) premake.vstudio.sln2005.projects(wks) test.capture [[ Project("{2857B73E-F847-4B02-9238-064979017E93}") = "MyProject", "MyProject.cproj", "{42B5DBC6-AE1F-903D-F75D-41E363076E92}" EndProject ]] end function suite.monoDevelopProperties() project "MyProject" monodevelop.MonoDevelopProperties(wks) test.capture [[ GlobalSection(MonoDevelopProperties) = preSolution EndGlobalSection ]] end
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts
test_scripts/Protocol/Enable_OEM_exclusive_apps_support/013_VehicleTypeData_RAI_4th_protocol.lua
1
1820
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0293-vehicle-type-filter.md --------------------------------------------------------------------------------------------------- -- Description: Check that SDL is able to provide all vehicle type data in RAI response in case the app is registered -- via 4th protocol -- -- Steps: -- 1. HMI provides all vehicle type data in BC.GetSystemInfo(ccpu_version, systemHardwareVersion) -- and VI.GetVehicleType(make, model, modelYear, trim) responses -- 2. App requests RAI via 4th protocol -- SDL does: -- - Provide the vehicle type info with all parameter values received from HMI in RAI response to the app -- except systemHardwareVersion --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local common = require("test_scripts/Protocol/commonProtocol") --[[ Test Configuration ]] config.defaultProtocolVersion = 4 -- Set 4 protocol as default for script --[[ Local Variables ]] local hmiCap = common.setHMIcap(common.vehicleTypeInfoParams.default) --[[ Local Functions ]] local function registerApp(responseExpectedData) local session = common.createSession() session:StartService(7) :Do(function() common.registerAppEx(responseExpectedData) end) end --[[ Scenario ]] common.Title("Preconditions") common.Step("Clean environment", common.preconditions) common.Step("Start SDL, HMI, connect Mobile, start Session", common.start, { hmiCap }) common.Title("Test") common.Step("Vehicle type data in RAI", registerApp, { common.vehicleTypeInfoParams.default }) common.Title("Postconditions") common.Step("Stop SDL", common.postconditions)
bsd-3-clause
vorbi123/testt
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
smartdevicelink/sdl_atf_test_scripts
test_scripts/MobileProjection/Phase2/011_single_app_video_streaming.lua
1
2867
--------------------------------------------------------------------------------------------------- -- Issue: https://github.com/smartdevicelink/sdl_core/issues/2129 --------------------------------------------------------------------------------------------------- -- Description: -- In case: -- 1) There is a mobile app which is video source -- 2) And this app starts Video streaming -- 3) And this app stops Video streaming -- SDL must: -- 1) Not send 'OnHMIStatus' when Video streaming is started or stopped --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local common = require('test_scripts/MobileProjection/Phase2/common') local runner = require('user_modules/script_runner') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false config.defaultProtocolVersion = 3 --[[ Local Variables ]] local testCases = { [001] = { t = "PROJECTION", m = false } } --[[ Local Functions ]] local function activateApp() local requestId = common.getHMIConnection():SendRequest("SDL.ActivateApp", { appID = common.getHMIAppId() }) common.getHMIConnection():ExpectResponse(requestId) common.getMobileSession():ExpectNotification("OnHMIStatus", { hmiLevel = "FULL", systemContext = "MAIN", audioStreamingState = "NOT_AUDIBLE", videoStreamingState = "STREAMABLE" }) end local function appStartVideoStreaming() common.getMobileSession():StartService(11) :Do(function() common.getHMIConnection():ExpectRequest("Navigation.StartStream") :Do(function(_, data) common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {}) common.getMobileSession():StartStreaming(11, "files/MP3_1140kb.mp3") common.getHMIConnection():ExpectNotification("Navigation.OnVideoDataStreaming", { available = true }) end) end) common.getMobileSession():ExpectNotification("OnHMIStatus") :Times(0) end local function appStopStreaming() common.getMobileSession():StopStreaming("files/MP3_1140kb.mp3") common.getMobileSession():ExpectNotification("OnHMIStatus") :Times(0) end --[[ Scenario ]] for n, tc in common.spairs(testCases) do runner.Title("TC[" .. string.format("%03d", n) .. "]: " .. "[hmiType:" .. tc.t .. ", isMedia:" .. tostring(tc.m) .. "]") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("Set App Config", common.setAppConfig, { 1, tc.t, tc.m }) runner.Step("Register App", common.registerApp, { 1 }) runner.Step("Activate App", activateApp) runner.Step("App starts Video streaming", appStartVideoStreaming) runner.Step("App stops streaming", appStopStreaming) runner.Step("Clean sessions", common.cleanSessions) runner.Step("Stop SDL", common.postconditions) end
bsd-3-clause
vladon/omim
3party/osrm/osrm-backend/profiles/bicycle.lua
59
12992
require("lib/access") require("lib/maxspeed") -- Begin of globals barrier_whitelist = { [""] = true, ["cycle_barrier"] = true, ["bollard"] = true, ["entrance"] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true, ["no"] = true } access_tag_whitelist = { ["yes"] = true, ["permissive"] = true, ["designated"] = true } access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true } access_tag_restricted = { ["destination"] = true, ["delivery"] = true } access_tags_hierachy = { "bicycle", "vehicle", "access" } cycleway_tags = {["track"]=true,["lane"]=true,["opposite"]=true,["opposite_lane"]=true,["opposite_track"]=true,["share_busway"]=true,["sharrow"]=true,["shared"]=true } service_tag_restricted = { ["parking_aisle"] = true } restriction_exception_tags = { "bicycle", "vehicle", "access" } default_speed = 15 walking_speed = 6 bicycle_speeds = { ["cycleway"] = default_speed, ["primary"] = default_speed, ["primary_link"] = default_speed, ["secondary"] = default_speed, ["secondary_link"] = default_speed, ["tertiary"] = default_speed, ["tertiary_link"] = default_speed, ["residential"] = default_speed, ["unclassified"] = default_speed, ["living_street"] = default_speed, ["road"] = default_speed, ["service"] = default_speed, ["track"] = 12, ["path"] = 12 --["footway"] = 12, --["pedestrian"] = 12, } pedestrian_speeds = { ["footway"] = walking_speed, ["pedestrian"] = walking_speed, ["steps"] = 2 } railway_speeds = { ["train"] = 10, ["railway"] = 10, ["subway"] = 10, ["light_rail"] = 10, ["monorail"] = 10, ["tram"] = 10 } platform_speeds = { ["platform"] = walking_speed } amenity_speeds = { ["parking"] = 10, ["parking_entrance"] = 10 } man_made_speeds = { ["pier"] = walking_speed } route_speeds = { ["ferry"] = 5 } bridge_speeds = { ["movable"] = 5 } surface_speeds = { ["asphalt"] = default_speed, ["cobblestone:flattened"] = 10, ["paving_stones"] = 10, ["compacted"] = 10, ["cobblestone"] = 6, ["unpaved"] = 6, ["fine_gravel"] = 6, ["gravel"] = 6, ["fine_gravel"] = 6, ["pebbelstone"] = 6, ["ground"] = 6, ["dirt"] = 6, ["earth"] = 6, ["grass"] = 6, ["mud"] = 3, ["sand"] = 3 } take_minimum_of_speeds = true obey_oneway = true obey_bollards = false use_restrictions = true ignore_areas = true -- future feature traffic_signal_penalty = 5 u_turn_penalty = 20 use_turn_restrictions = false turn_penalty = 60 turn_bias = 1.4 --modes mode_normal = 1 mode_pushing = 2 mode_ferry = 3 mode_train = 4 mode_movable_bridge = 5 local function parse_maxspeed(source) if not source then return 0 end local n = tonumber(source:match("%d*")) if not n then n = 0 end if string.match(source, "mph") or string.match(source, "mp/h") then n = (n*1609)/1000; end return n end function get_exceptions(vector) for i,v in ipairs(restriction_exception_tags) do vector:Add(v) end end function node_function (node, result) local barrier = node:get_value_by_key("barrier") local access = Access.find_access_tag(node, access_tags_hierachy) local traffic_signal = node:get_value_by_key("highway") -- flag node if it carries a traffic light if traffic_signal and traffic_signal == "traffic_signals" then result.traffic_lights = true end -- parse access and barrier tags if access and access ~= "" then if access_tag_blacklist[access] then result.barrier = true else result.barrier = false end elseif barrier and barrier ~= "" then if barrier_whitelist[barrier] then result.barrier = false else result.barrier = true end end end function way_function (way, result) -- initial routability check, filters out buildings, boundaries, etc local highway = way:get_value_by_key("highway") local route = way:get_value_by_key("route") local man_made = way:get_value_by_key("man_made") local railway = way:get_value_by_key("railway") local amenity = way:get_value_by_key("amenity") local public_transport = way:get_value_by_key("public_transport") local bridge = way:get_value_by_key("bridge") if (not highway or highway == '') and (not route or route == '') and (not railway or railway=='') and (not amenity or amenity=='') and (not man_made or man_made=='') and (not public_transport or public_transport=='') and (not bridge or bridge=='') then return end -- don't route on ways or railways that are still under construction if highway=='construction' or railway=='construction' then return end -- access local access = Access.find_access_tag(way, access_tags_hierachy) if access and access_tag_blacklist[access] then return end -- other tags local name = way:get_value_by_key("name") local ref = way:get_value_by_key("ref") local junction = way:get_value_by_key("junction") local maxspeed = parse_maxspeed(way:get_value_by_key ( "maxspeed") ) local maxspeed_forward = parse_maxspeed(way:get_value_by_key( "maxspeed:forward")) local maxspeed_backward = parse_maxspeed(way:get_value_by_key( "maxspeed:backward")) local barrier = way:get_value_by_key("barrier") local oneway = way:get_value_by_key("oneway") local onewayClass = way:get_value_by_key("oneway:bicycle") local cycleway = way:get_value_by_key("cycleway") local cycleway_left = way:get_value_by_key("cycleway:left") local cycleway_right = way:get_value_by_key("cycleway:right") local duration = way:get_value_by_key("duration") local service = way:get_value_by_key("service") local area = way:get_value_by_key("area") local foot = way:get_value_by_key("foot") local surface = way:get_value_by_key("surface") local bicycle = way:get_value_by_key("bicycle") -- name if ref and "" ~= ref and name and "" ~= name then result.name = name .. ' / ' .. ref elseif ref and "" ~= ref then result.name = ref elseif name and "" ~= name then result.name = name elseif highway then -- if no name exists, use way type -- this encoding scheme is excepted to be a temporary solution result.name = "{highway:"..highway.."}" end -- roundabout handling if junction and "roundabout" == junction then result.roundabout = true; end -- speed local bridge_speed = bridge_speeds[bridge] if (bridge_speed and bridge_speed > 0) then highway = bridge; if duration and durationIsValid(duration) then result.duration = math.max( parseDuration(duration), 1 ); end result.forward_mode = mode_movable_bridge result.backward_mode = mode_movable_bridge result.forward_speed = bridge_speed result.backward_speed = bridge_speed elseif route_speeds[route] then -- ferries (doesn't cover routes tagged using relations) result.forward_mode = mode_ferry result.backward_mode = mode_ferry result.ignore_in_grid = true if duration and durationIsValid(duration) then result.duration = math.max( 1, parseDuration(duration) ) else result.forward_speed = route_speeds[route] result.backward_speed = route_speeds[route] end elseif railway and platform_speeds[railway] then -- railway platforms (old tagging scheme) result.forward_speed = platform_speeds[railway] result.backward_speed = platform_speeds[railway] elseif platform_speeds[public_transport] then -- public_transport platforms (new tagging platform) result.forward_speed = platform_speeds[public_transport] result.backward_speed = platform_speeds[public_transport] elseif railway and railway_speeds[railway] then result.forward_mode = mode_train result.backward_mode = mode_train -- railways if access and access_tag_whitelist[access] then result.forward_speed = railway_speeds[railway] result.backward_speed = railway_speeds[railway] end elseif amenity and amenity_speeds[amenity] then -- parking areas result.forward_speed = amenity_speeds[amenity] result.backward_speed = amenity_speeds[amenity] elseif bicycle_speeds[highway] then -- regular ways result.forward_speed = bicycle_speeds[highway] result.backward_speed = bicycle_speeds[highway] elseif access and access_tag_whitelist[access] then -- unknown way, but valid access tag result.forward_speed = default_speed result.backward_speed = default_speed else -- biking not allowed, maybe we can push our bike? -- essentially requires pedestrian profiling, for example foot=no mean we can't push a bike if foot ~= 'no' and junction ~= "roundabout" then if pedestrian_speeds[highway] then -- pedestrian-only ways and areas result.forward_speed = pedestrian_speeds[highway] result.backward_speed = pedestrian_speeds[highway] result.forward_mode = mode_pushing result.backward_mode = mode_pushing elseif man_made and man_made_speeds[man_made] then -- man made structures result.forward_speed = man_made_speeds[man_made] result.backward_speed = man_made_speeds[man_made] result.forward_mode = mode_pushing result.backward_mode = mode_pushing elseif foot == 'yes' then result.forward_speed = walking_speed result.backward_speed = walking_speed result.forward_mode = mode_pushing result.backward_mode = mode_pushing elseif foot_forward == 'yes' then result.forward_speed = walking_speed result.forward_mode = mode_pushing result.backward_mode = 0 elseif foot_backward == 'yes' then result.forward_speed = walking_speed result.forward_mode = 0 result.backward_mode = mode_pushing end end end -- direction local impliedOneway = false if junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then impliedOneway = true end if onewayClass == "yes" or onewayClass == "1" or onewayClass == "true" then result.backward_mode = 0 elseif onewayClass == "no" or onewayClass == "0" or onewayClass == "false" then -- prevent implied oneway elseif onewayClass == "-1" then result.forward_mode = 0 elseif oneway == "no" or oneway == "0" or oneway == "false" then -- prevent implied oneway elseif cycleway and string.find(cycleway, "opposite") == 1 then if impliedOneway then result.forward_mode = 0 result.backward_mode = mode_normal result.backward_speed = bicycle_speeds["cycleway"] end elseif cycleway_left and cycleway_tags[cycleway_left] and cycleway_right and cycleway_tags[cycleway_right] then -- prevent implied elseif cycleway_left and cycleway_tags[cycleway_left] then if impliedOneway then result.forward_mode = 0 result.backward_mode = mode_normal result.backward_speed = bicycle_speeds["cycleway"] end elseif cycleway_right and cycleway_tags[cycleway_right] then if impliedOneway then result.forward_mode = mode_normal result.backward_speed = bicycle_speeds["cycleway"] result.backward_mode = 0 end elseif oneway == "-1" then result.forward_mode = 0 elseif oneway == "yes" or oneway == "1" or oneway == "true" or impliedOneway then result.backward_mode = 0 end -- pushing bikes if bicycle_speeds[highway] or pedestrian_speeds[highway] then if foot ~= "no" and junction ~= "roundabout" then if result.backward_mode == 0 then result.backward_speed = walking_speed result.backward_mode = mode_pushing elseif result.forward_mode == 0 then result.forward_speed = walking_speed result.forward_mode = mode_pushing end end end -- cycleways if cycleway and cycleway_tags[cycleway] then result.forward_speed = bicycle_speeds["cycleway"] elseif cycleway_left and cycleway_tags[cycleway_left] then result.forward_speed = bicycle_speeds["cycleway"] elseif cycleway_right and cycleway_tags[cycleway_right] then result.forward_speed = bicycle_speeds["cycleway"] end -- dismount if bicycle == "dismount" then result.forward_mode = mode_pushing result.backward_mode = mode_pushing result.forward_speed = walking_speed result.backward_speed = walking_speed end -- surfaces if surface then surface_speed = surface_speeds[surface] if surface_speed then if result.forward_speed > 0 then result.forward_speed = surface_speed end if result.backward_speed > 0 then result.backward_speed = surface_speed end end end -- maxspeed MaxSpeed.limit( result, maxspeed, maxspeed_forward, maxspeed_backward ) end function turn_function (angle) -- compute turn penalty as angle^2, with a left/right bias k = turn_penalty/(90.0*90.0) if angle>=0 then return angle*angle*k/turn_bias else return angle*angle*k*turn_bias end end
apache-2.0
AwrmawnTg-Cli/Uzzbot
plugins/banhammer.lua
294
10470
local function is_user_whitelisted(id) local hash = 'whitelist:user#id'..id local white = redis:get(hash) or false return white end local function is_chat_whitelisted(id) local hash = 'whitelist:chat#id'..id local white = redis:get(hash) or false return white end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function superban_user(user_id, chat_id) -- Save to redis local hash = 'superbanned:'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function is_super_banned(user_id) local hash = 'superbanned:'..user_id local superbanned = redis:get(hash) return superbanned or false end local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local user_id = msg.from.id local chat_id = msg.to.id local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, chat_id) if superbanned then print('SuperBanned user talking!') superban_user(user_id, chat_id) msg.text = '' end if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end -- WHITELIST local hash = 'whitelist:enabled' local whitelist = redis:get(hash) local issudo = is_sudo(msg) -- Allow all sudo users even if whitelist is allowed if whitelist and not issudo then print('Whitelist enabled and not sudo') -- Check if user or chat is whitelisted local allowed = is_user_whitelisted(msg.from.id) if not allowed then print('User '..msg.from.id..' not whitelisted') if msg.to.type == 'chat' then allowed = is_chat_whitelisted(msg.to.id) if not allowed then print ('Chat '..msg.to.id..' not whitelisted') else print ('Chat '..msg.to.id..' whitelisted :)') end end else print('User '..msg.from.id..' allowed :)') end if not allowed then msg.text = '' end else print('Whitelist not enabled or is sudo') end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'superban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!') return superban_user(member_id, chat_id) elseif get_cmd == 'whitelist user' then local hash = 'whitelist:user#id'..member_id redis:set(hash, true) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted') elseif get_cmd == 'whitelist delete user' then local hash = 'whitelist:user#id'..member_id redis:del(hash) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist') end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1] == 'kickme' then kick_user(msg.from.id, msg.to.id) end if not is_momod(msg) then return nil end local receiver = get_receiver(msg) if matches[4] then get_cmd = matches[1]..' '..matches[2]..' '..matches[3] elseif matches[3] then get_cmd = matches[1]..' '..matches[2] else get_cmd = matches[1] end if matches[1] == 'ban' then local user_id = matches[3] local chat_id = msg.to.id if msg.to.type == 'chat' then if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then ban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end else return 'This isn\'t a chat group' end end if matches[1] == 'superban' and is_admin(msg) then local user_id = matches[3] local chat_id = msg.to.id if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then superban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' globally banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'superbanned:'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if matches[1] == 'whitelist' then if matches[2] == 'enable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:set(hash, true) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then if string.match(matches[4], '^%d+$') then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' else local member = string.gsub(matches[4], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'delete' and matches[3] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:del(hash) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist' end end end return { description = "Plugin to manage bans, kicks and white/black lists.", usage = { user = "!kickme : Exit from group", moderator = { "!whitelist <enable>/<disable> : Enable or disable whitelist mode", "!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled", "!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled", "!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled", "!whitelist delete user <user_id> : Remove user from whitelist", "!whitelist delete chat : Remove chat from whitelist", "!ban user <user_id> : Kick user from chat and kicks it if joins chat again", "!ban user <username> : Kick user from chat and kicks it if joins chat again", "!ban delete <user_id> : Unban user", "!kick <user_id> : Kick user from chat group by id", "!kick <username> : Kick user from chat group by username", }, admin = { "!superban user <user_id> : Kick user from all chat and kicks it if joins again", "!superban user <username> : Kick user from all chat and kicks it if joins again", "!superban delete <user_id> : Unban user", }, }, patterns = { "^!(whitelist) (enable)$", "^!(whitelist) (disable)$", "^!(whitelist) (user) (.*)$", "^!(whitelist) (chat)$", "^!(whitelist) (delete) (user) (.*)$", "^!(whitelist) (delete) (chat)$", "^!(ban) (user) (.*)$", "^!(ban) (delete) (.*)$", "^!(superban) (user) (.*)$", "^!(superban) (delete) (.*)$", "^!(kick) (.*)$", "^!(kickme)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
Planimeter/grid-sdk
engine/client/gui/console/textboxautocompleteitemgroup.lua
1
1212
--=========== Copyright © 2019, Planimeter, All rights reserved. ===========-- -- -- Purpose: Console Text Box Autocomplete Item Group class -- --==========================================================================-- class "gui.console.textboxautocompleteitemgroup" ( "gui.textboxautocompleteitemgroup" ) local textboxautocompleteitemgroup = gui.console.textboxautocompleteitemgroup function textboxautocompleteitemgroup:textboxautocompleteitemgroup( parent, name ) gui.textboxautocompleteitemgroup.textboxautocompleteitemgroup( self, parent, name ) end function textboxautocompleteitemgroup:invalidateLayout() local itemWidth = 0 local font = self:getScheme( "font" ) local maxWidth = 0 local listItems = self:getItems() if ( listItems ) then local y = 1 local padding = 18 for _, listItem in ipairs( listItems ) do listItem:setX( 1 ) listItem:setY( y ) itemWidth = font:getWidth( listItem:getText() ) + 2 * padding if ( itemWidth > maxWidth ) then maxWidth = itemWidth end y = y + listItem:getHeight() end self:setWidth( maxWidth + 2 ) for _, listItem in ipairs( listItems ) do listItem:setWidth( maxWidth ) end end self:updatePos() end
mit
Grisu118/Scripts
misc/AddMoney.lua
1
1673
-- Fügt stündlich einen Betrag auf das Konto des Spielers hinzu. -- -- @author Grisu118 -- @date 03/12/2013 -- @version 1.0 -- @Descripion: Readme you can find there: https://github.com/Grisu118/Scripts -- @web: http://grisu118.ch or http://vertexdezign.de -- Copyright (C) Grisu118, All Rights Reserved. -- free for noncommerical-usage AddMoney = {}; function AddMoney.prerequisitesPresent(specializations) print "AddMoney by Grisu118 loaded, special thanks to Sven777b"; return true; end; function AddMoney:load(xmlFile) self.incomePerHour = 0; local difficultyMultiplier = 2 ^ (3 - g_currentMission.missionStats.difficulty); --4 2 1 self.incomePerHour = difficultyMultiplier * Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.incomePerHour"), 100); g_currentMission.environment:addHourChangeListener(self); self.hourChanged = SpecializationUtil.callSpecializationsFunction("hourChanged") end; function AddMoney:delete() g_currentMission.environment:removeHourChangeListener(self); end; function AddMoney:getSaveAttributesAndNodes(nodeIdent) end; function AddMoney:loadFromAttributesAndNodes(xmlFile, key, resetVehicles) end; function AddMoney:readStream(streamId, connection) end; function AddMoney:writeStream(streamId, connection) end; function AddMoney:mouseEvent(posX, posY, isDown, isUp, button) end; function AddMoney:keyEvent(unicode, sym, modifier, isDown) end; function AddMoney:update(dt) end; function AddMoney:updateTick(dt) end; function AddMoney:hourChanged() if self.isServer then g_currentMission:addSharedMoney(self.incomePerHour, "other"); end; end; function AddMoney:draw() end;
apache-2.0
ddumont/darkstar
scripts/zones/Bastok_Mines/npcs/Gregory.lua
14
1045
----------------------------------- -- Area: Bastok Mines -- NPC: Gregory -- Type: ENM -- @zone 234 -- @pos 51.530 -1 -83.940 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0100); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
ddumont/darkstar
scripts/zones/Temenos/bcnms/Temenos_Western_Tower.lua
35
1096
----------------------------------- -- Area: Temenos -- Name: ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[Temenos_W_Tower]UniqueID",GenerateLimbusKey()); HideArmouryCrates(GetInstanceRegion(1298),TEMENOS); HideTemenosDoor(GetInstanceRegion(1298)); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("limbusbitmap",0); player:setVar("characterLimbusKey",GetServerVariable("[Temenos_W_Tower]UniqueID")); player:setVar("LimbusID",1298); player:delKeyItem(COSMOCLEANSE); player:delKeyItem(WHITE_CARD); end; -- Leaving by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then player:setPos(580,-1.5,4.452,192); ResetPlayerLimbusVariable(player) end end;
gpl-3.0
ddumont/darkstar
scripts/zones/Bastok_Mines/npcs/Rodellieux.lua
17
1433
----------------------------------- -- Area: Bastok_Mines -- NPC: Rodellieux -- Only sells when Bastok controlls Fauregandi Region ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(FAUREGANDI); if (RegionOwner ~= NATION_BASTOK) then player:showText(npc,RODELLIEUX_CLOSED_DIALOG); else player:showText(npc,RODELLIEUX_OPEN_DIALOG); stock = { 0x11db, 90, --Beaugreens 0x110b, 39, --Faerie Apple 0x02b3, 54 --Maple Log } showShop(player,BASTOK,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
ddumont/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Travonce.lua
14
1060
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Travonce -- Type: Standard NPC -- @zone 26 -- @pos -89.068 -14.367 -0.030 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00d2); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Squeakz/darkstar
scripts/globals/weaponskills/raging_fists.lua
11
1405
----------------------------------- -- Raging Fists -- Hand-to-Hand weapon skill -- Skill Level: 125 -- Delivers a fivefold attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Thunder Gorget. -- Aligned with the Thunder Belt. -- Element: None -- Modifiers: STR:30% ; DEX:30% -- 100%TP 200%TP 300%TP -- 1.00 4.6 9 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; params.numHits = 5; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2; params.str_wsc = 0.2; params.dex_wsc = 0.2; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp200 = 4.6; params.ftp300 = 9 params.str_wsc = 0.3; params.dex_wsc = 0.3; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
ddumont/darkstar
scripts/globals/items/balik_sis.lua
12
1663
----------------------------------------- -- ID: 5600 -- Item: Balik Sis -- Food Effect: 30Min, All Races ----------------------------------------- -- Dexterity 4 -- Mind -2 -- Attack % 13 -- Attack Cap 65 -- Ranged ACC 1 -- Ranged ATT % 13 -- Ranged ATT Cap 65 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5600); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 4); target:addMod(MOD_MND, -2); target:addMod(MOD_FOOD_ATTP, 13); target:addMod(MOD_FOOD_ATT_CAP, 65); target:addMod(MOD_RACC, 1); target:addMod(MOD_FOOD_RATTP, 13); target:addMod(MOD_FOOD_RATT_CAP, 65); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 4); target:delMod(MOD_MND, -2); target:delMod(MOD_FOOD_ATTP, 13); target:delMod(MOD_FOOD_ATT_CAP, 65); target:delMod(MOD_RACC, 1); target:delMod(MOD_FOOD_RATTP, 13); target:delMod(MOD_FOOD_RATT_CAP, 65); end;
gpl-3.0
ShaPOC/iamlimitless.nl-portfolio
munchy-in-lua/src/main.lua
1
1391
--[[ -- @package Monster Munchies -- @author Jimmy Aupperlee <jimmy@moustachegames.net> -- @copyright 2014 Jimmy Aupperlee -- @license http://moustachegames.net/code-license -- @version 0.1.0 -- @since File available since Release 0.1.0 --]] -- ------------------------------------------------------------ -- ROOT path -- ------------------------------------------------------------ -- Get the root of this file, which is the project root! -- Warning, this variable will have an ending forward slash! -- So don't add an extra forward slash when using it! _G.ROOT = MOAIFileSystem:getAbsoluteDirectoryPath( "./" ) -- ------------------------------------------------------------ -- The random seed! -- ------------------------------------------------------------ -- This very important little seed makes sure the game is -- different every time math.randomseed(os.time()) -- ------------------------------------------------------------ -- Set package path to ROOT -- ------------------------------------------------------------ -- We want the p ackage path to always be in the root no matter -- where we compile from. package.path = package.path .. ";" .. _G.ROOT -- ------------------------------------------------------------ -- And finally, we start the system! -- ------------------------------------------------------------ require "System/Bootstrap/start"
lgpl-3.0
smartdevicelink/sdl_atf_test_scripts
test_scripts/Defects/7_1/885_ShowConstantTBT.lua
1
3454
--------------------------------------------------------------------------------------------------- -- Issue: https://github.com/SmartDeviceLink/sdl_core/issues/885, -- https://github.com/smartdevicelink/sdl_core/issues/3829 --------------------------------------------------------------------------------------------------- -- Description: Check that SDL does not stop processing softButton events once a response is received for the RPC. -- 'ShowConstantTBT' scenario. -- -- Steps: -- 1. App is registered and activated -- 2. App sends 'ShowConstantTBT' RPC with soft buttons -- SDL does: -- - transfer request to HMI -- 3. HMI sends 'OnButtonEvent' and 'OnButtonPress' notifications -- SDL does: -- - transfer notifications to the App -- 4. HMI provides a response for 'ShowConstantTBT' -- SDL does: -- - transfer response to the App -- 5. HMI sends 'OnButtonEvent' and 'OnButtonPress' notifications -- SDL does: -- - transfer notifications to the App --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('user_modules/sequences/actions') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local Variables ]] local btn = { id = 4, name = "CUSTOM_BUTTON" } local params = { navigationText1 = "navigationText1", softButtons = { { type = "TEXT", softButtonID = 4, text = "text" } } } --[[ Local Functions ]] local function sendOnButtonEvents() common.getHMIConnection():SendNotification("Buttons.OnButtonEvent", { name = btn.name, mode = "BUTTONDOWN", customButtonID = btn.id, appID = common.getHMIAppId() }) common.getHMIConnection():SendNotification("Buttons.OnButtonPress", { name = btn.name, mode = "SHORT", customButtonID = btn.id, appID = common.getHMIAppId() }) end local function showConstantTBT() local cid = common.getMobileSession():SendRPC("ShowConstantTBT", params) common.getMobileSession():ExpectNotification("OnButtonEvent", { buttonName = btn.name, buttonEventMode = "BUTTONDOWN", customButtonID = btn.id }) :Times(2) common.getMobileSession():ExpectNotification("OnButtonPress", { buttonName = btn.name, buttonPressMode = "SHORT", customButtonID = btn.id }) :Times(2) common.getHMIConnection():ExpectRequest("Navigation.ShowConstantTBT") :Do(function(_, data) common.run.runAfter(function() sendOnButtonEvents() end, 500) common.run.runAfter(function() common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {}) end, 1000) end) common.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" }) :Do(function() sendOnButtonEvents() end) end local function pTUpdateFunc(tbl) tbl.policy_table.app_policies[common.app.getParams().fullAppID].groups = { "Base-4", "Navigation-1" } end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("Register App", common.registerApp) runner.Step("Update ptu", common.policyTableUpdate, { pTUpdateFunc }) runner.Step("Activate App", common.activateApp) runner.Title("Test") runner.Step("ShowConstantTBT with soft buttons", showConstantTBT) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
bsd-3-clause
ddumont/darkstar
scripts/zones/Hall_of_Transference/npcs/_0e3.lua
14
1358
----------------------------------- -- Area: Hall of Transference -- NPC: Large Apparatus (Left) - Holla -- @pos -239 -1 290 14 ----------------------------------- package.loaded["scripts/zones/Hall_of_Transference/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Hall_of_Transference/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") == 1) then player:startEvent(0x00A0); else player:messageSpecial(NO_RESPONSE_OFFSET); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00A0) then player:setPos(92.033, 0, 80.380, 255, 16); -- To Promyvion Holla {R} end end;
gpl-3.0
ddumont/darkstar
scripts/globals/weaponskills/guillotine.lua
18
1964
----------------------------------- -- Guillotine -- Scythe weapon skill -- Skill level: 200 -- Delivers a four-hit attack. Duration varies with TP. -- Modifiers: STR:25% ; MND:25% -- 100%TP 200%TP 300%TP -- 0.875 0.875 0.875 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 4; -- ftp damage mods (for Damage Varies with TP; lines are calculated in the function params.ftp100 = 0.875; params.ftp200 = 0.875; params.ftp300 = 0.875; -- wscs are in % so 0.2=20% params.str_wsc = 0.25; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.25; params.chr_wsc = 0.0; -- critical mods, again in % (ONLY USE FOR critICAL HIT VARIES WITH TP) params.crit100 = 0.0; params.crit200=0.0; params.crit300=0.0; params.canCrit = false; -- accuracy mods (ONLY USE FOR accURACY VARIES WITH TP) , should be the params.acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp. params.acc100 = 0; params.acc200=0; params.acc300=0; -- attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default. params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.3; params.mnd_wsc = 0.5; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (damage > 0) then local duration = (tp/1000 * 30) + 30; if (target:hasStatusEffect(EFFECT_SILENCE) == false) then target:addStatusEffect(EFFECT_SILENCE, 1, 0, duration); end end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Squeakz/darkstar
scripts/globals/weaponskills/shining_strike.lua
11
1313
----------------------------------- -- Shining Strike -- Club weapon skill -- Skill level: 5 -- Deals light elemental damage to enemy. Damage varies with TP. -- Aligned with the Thunder Gorget. -- Aligned with the Thunder Belt. -- Element: None -- Modifiers: STR:40% ; MND:40% -- 100%TP 200%TP 300%TP -- 1.625 3 4.625 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; params.ftp100 = 1; params.ftp200 = 1.75; params.ftp300 = 2.5; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.2; params.chr_wsc = 0.0; params.ele = ELE_LIGHT; params.skill = SKILL_CLB; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 1.625; params.ftp200 = 3; params.ftp300 = 4.625; params.str_wsc = 0.4; params.mnd_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Squeakz/darkstar
scripts/zones/Selbina/npcs/Sleeping_Lizard.lua
13
1059
----------------------------------- -- Area: Selbina -- NPC: Sleeping Lizard -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getZPos() < -28.750) then player:startEvent(0x00d5); else player:startEvent(0x00e5); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
ddumont/darkstar
scripts/zones/The_Shrine_of_RuAvitau/npcs/qm2.lua
14
1568
----------------------------------- -- Area: The Shrine of Ru'Avitau -- NPC: ??? (Spawn Kirin) -- @pos -81 32 2 178 ----------------------------------- package.loaded["scripts/zones/The_Shrine_of_RuAvitau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Shrine_of_RuAvitau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Validate traded items are all needed seals and ensure Kirin is not alive if (GetMobAction(17506670) == 0 and trade:hasItemQty(1404, 1) and trade:hasItemQty(1405, 1) and trade:hasItemQty(1406, 1) and trade:hasItemQty(1407, 1) and trade:getItemCount() == 4) then -- Complete the trade.. player:tradeComplete(); -- Spawn Kirin.. local mob = SpawnMob(17506670, 180); player:showText(npc, KIRIN_OFFSET); mob:updateClaim(player); npc:setStatus(STATUS_DISAPPEAR); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0064); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
smartdevicelink/sdl_atf_test_scripts
test_scripts/RC/MultipleModules/InteriorVehicleData/SetInteriorVehicleData/002_moduleId_exists_but_does_not_match_to_the_ControlData.lua
1
2296
--------------------------------------------------------------------------------------------------- -- Proposal: -- https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0221-multiple-modules.md -- Description: -- Mobile App sent "SetInteriorVehicleData" request containing incorrect value of "moduleId" to the SDL. -- SDL should decline this request answering with (resultCode = "UNSUPPORTED_RESOURCE"). -- -- Preconditions: -- 1) SDL and HMI are started -- 2) HMI sent all modules capabilities to the SDL -- 3) Mobile is connected to the SDL -- 4) App is registered and activated -- -- Steps: -- 1) App sends "SetInteriorVehicleData"(moduleType = "LIGHT", moduleId = "incorrect_value", lightControlData) request -- to the SDL -- Check: -- SDL does NOT resend "RC.SetInteriorVehicleData" request to the HMI -- SDL responds with "SetInteriorVehicleData"(success = false, resultCode = "UNSUPPORTED_RESOURCE") to the App --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require("test_scripts/RC/MultipleModules/commonRCMulModules") --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local Variables ]] local rcCapabilities = { LIGHT = common.DEFAULT } local requestModuleData = { moduleType = "LIGHT", moduleId = "incorrect_value", lightControlData = { lightState = { { id = "FRONT_LEFT_HIGH_BEAM", status = "OFF"} } } } --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Build default actual module state", common.initHmiDataState, { rcCapabilities }) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start, { rcCapabilities }) runner.Step("RAI", common.registerApp) runner.Step("PTU", common.customModulesPTU, { "LIGHT" }) runner.Step("Activate App", common.activateApp) runner.Title("Test") runner.Step("Send SetInteriorVehicleData rpc for LIGHT module with incorrect moduleId", common.rpcReject,{"LIGHT", "incorrect_value", 1, "SetInteriorVehicleData", requestModuleData, "UNSUPPORTED_RESOURCE"}) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
bsd-3-clause
ddumont/darkstar
scripts/zones/Selbina/npcs/Vuntar.lua
14
3323
----------------------------------- -- Area: Selbina -- NPC: Vuntar -- Starts and Finishes Quest: Cargo (R) -- @pos 7 -2 -15 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(OTHER_AREAS,CARGO) ~= QUEST_AVAILABLE) then realday = tonumber(os.date("%j")); -- %M for next minute, %j for next real day starttime = player:getVar("VuntarCanBuyItem_date"); if (realday ~= starttime) then if (trade:hasItemQty(4529,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then player:startEvent(0x0034,1); -- Can Buy rolanberry (881 ce) elseif (trade:hasItemQty(4530,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then player:startEvent(0x0034,2); -- Can Buy rolanberry (874 ce) elseif (trade:hasItemQty(4531,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then player:startEvent(0x0034,3); -- Can Buy rolanberry (864 ce) end else player:startEvent(0x046e,4365); -- Can't buy rolanberrys end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getMainLvl() >= 20 and player:getQuestStatus(OTHER_AREAS,CARGO) == QUEST_AVAILABLE) then player:startEvent(0x0032,4365); -- Start quest "Cargo" elseif (player:getMainLvl() < 20) then player:startEvent(0x0035); -- Dialog for low level or low fame else player:startEvent(0x0033,4365); -- During & after completed quest "Cargo" end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0032) then player:addQuest(OTHER_AREAS,CARGO); elseif (csid == 0x0034) then player:setVar("VuntarCanBuyItem_date", os.date("%j")); -- %M for next minute, %j for next real day if (player:getQuestStatus(OTHER_AREAS,CARGO) == QUEST_ACCEPTED) then player:completeQuest(OTHER_AREAS,CARGO); player:addFame(OTHER_AREAS,30); end if (option == 1) then player:addGil(800); player:messageSpecial(GIL_OBTAINED,800); player:tradeComplete(); elseif (option == 2) then player:addGil(2000); player:messageSpecial(GIL_OBTAINED,2000); player:tradeComplete(); elseif (option == 3) then player:addGil(3000); player:messageSpecial(GIL_OBTAINED,3000); player:tradeComplete(); end end end;
gpl-3.0
Squeakz/darkstar
scripts/zones/East_Ronfaure/npcs/Signpost.lua
13
2313
----------------------------------- -- Area: East Ronfaure -- NPC: Signpost -- Involved in Quest: To Cure a Cough -- @pos 257 -45 212 101 ----------------------------------- package.loaded["scripts/zones/East_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/East_Ronfaure/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local X = player:getXPos(); local Z = player:getZPos(); if ((X > 251.6 and X < 263.6) and (Z < 219.7 and Z > 207.7)) then if (player:hasKeyItem(SCROLL_OF_TREASURE) == true) then player:startEvent(20); player:delKeyItem(SCROLL_OF_TREASURE); player:addGil(GIL_RATE*3000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000); else player:startEvent(5); end elseif ((X > 434.9 and X < 446.9) and (Z < 148.4 and Z > 136.4)) then player:startEvent(3); elseif ((X > 652.2 and X < 664.2) and (Z < 311.5 and Z > 299.5)) then player:startEvent(7); elseif ((X > 459.2 and X < 471.2) and (Z < -167.4 and Z > -179.4)) then player:startEvent(9); elseif ((X > 532 and X < 544) and (Z < -378.2 and Z > -390.2)) then player:startEvent(11); elseif ((X > 273.1 and X < 285.1) and (Z < -251.6 and Z > -263.6)) then player:startEvent(13); elseif ((X > 290.5 and X < 302.5) and (Z < -451.1 and Z > -463.1)) then player:startEvent(15); elseif ((X > 225.1 and X < 237.1) and (Z < 68.6 and Z > 56.6)) then player:startEvent(17); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --print("CSID: %u",csid); --print("RESULT: %u",option); end;
gpl-3.0
ddumont/darkstar
scripts/zones/Norg/npcs/Sohyon.lua
14
1029
----------------------------------- -- Area: Norg -- NPC: Sohyon -- Type: Standard NPC -- @zone 252 -- @pos 47.286 -7.282 13.873 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00d4); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
elverion/rom-bot
devtools/UltimateMailMod/Inbox/MailViewer.lua
1
9723
-- ################### -- ## ## -- ## Mail Viewer ## -- ## ## -- ################### function UMMMailViewerTemplate_OnLoad(this) this.priv_ParentFrameName = nil; this.priv_ViewIndex = 0; this.priv_Attachments = {}; this.ClearAttachments = function(self) self.priv_Attachments = {}; end; this.AddAttachment = function(self, type, icon, count) local newItem = {}; newItem.Type = string.lower(type); newItem.Icon = icon; newItem.Count = count; newItem.Link = link; table.insert(self.priv_Attachments, newItem); end; this.ShowAttachments = function(self, CODAmount) if (CODAmount) then getglobal(self:GetName().."FooterAttachmentLabel"):SetText("|cff"..UMMColor.Yellow..UMM_VIEWER_ATTACHMENTCOD.."|r"); else getglobal(self:GetName().."FooterAttachmentLabel"):SetText("|cff"..UMMColor.White..UMM_VIEWER_ATTACHED.."|r"); end getglobal(self:GetName().."FooterAttachmentLabel"):Show(); local previous = getglobal(self:GetName().."FooterAttachmentLabel"); for a = 1, 2 do local button = getglobal(self:GetName().."FooterAttachment"..a); button:Hide(); end local moneyFrame = getglobal(self:GetName().."FooterMoneyFrame"); moneyFrame:Hide(); local diamondFrame = getglobal(self:GetName().."FooterDiamondFrame"); diamondFrame:Hide(); local codCheck = getglobal(self:GetName().."FooterAcceptCODCheck"); codCheck:Hide(); local goldAttached = false; local goldValue = 0; local diamondsAttached = false; local diamondValue = 0; for a = 1, table.getn(self.priv_Attachments) do local button = getglobal(self:GetName().."FooterAttachment"..a); SetItemButtonTexture(button, self.priv_Attachments[a].Icon); if (self.priv_Attachments[a].Type == "item") then SetItemButtonCount(button, self.priv_Attachments[a].Count); else SetItemButtonCount(button, 0); end if (self.priv_Attachments[a].Type == "gold") then goldAttached = true; goldValue = self.priv_Attachments[a].Count; elseif (self.priv_Attachments[a].Type == "diamond") then diamondsAttached = true; diamondValue = self.priv_Attachments[a].Count; end button:ClearAllAnchors(); button:SetAnchor("LEFT", "RIGHT", previous:GetName(), 10, 0); button:Show(); previous = button; end if (goldAttached == true) then moneyFrame:ClearAllAnchors(); moneyFrame:SetAnchor("LEFT", "RIGHT", previous:GetName(), 10, 0); moneyFrame:SetAmount(goldValue, "gold"); elseif (diamondsAttached == true) then diamondFrame:ClearAllAnchors(); diamondFrame:SetAnchor("LEFT", "RIGHT", previous:GetName(), 10, 0); diamondFrame:SetAmount(diamondValue, "diamond"); elseif CODAmount and (CODAmount > 0) then moneyFrame:ClearAllAnchors(); moneyFrame:SetAnchor("LEFT", "RIGHT", previous:GetName(), 10, 10); moneyFrame:SetAmount(CODAmount); codCheck:ClearAllAnchors(); codCheck:SetAnchor("LEFT", "RIGHT", previous:GetName(), 0, -10); getglobal(codCheck:GetName().."Label"):SetText("|cff"..UMMColor.White..UMM_VIEWER_ATTACHMENTACCEPT.."|r"); codCheck:SetChecked(nil); codCheck:Show(); end getglobal(self:GetName().."Footer"):Show(); end; this.Display = function(self, parentFrame, mailIndex, mailObject) if (mailObject ~= nil) then self.priv_ViewIndex = mailIndex; self.priv_ParentFrameName = parentFrame; getglobal(self:GetName().."BodyFrameInput"):ClearFocus(); getglobal(self:GetName().."HeaderAuthor"):SetText("|cff"..UMMFriends:GetColor(mailObject.Author)..mailObject.Author.."|r"); getglobal(self:GetName().."HeaderSubject"):SetText("|cff"..UMMColor.White..mailObject.Subject.."|r"); getglobal(self:GetName().."BodyFrameInput"):SetText(mailObject.Body); local bodyText, texture, isTakeable, isInvoice = GetInboxText(mailIndex); UMMMailManager:InboxRefresh(); UMMMailManager.Mails[self.priv_ViewIndex].Tagged = true; getglobal(self:GetName().."BodyFrameInput"):SetText(bodyText); if (mailObject.CanReply == true) then getglobal(self:GetName().."Reply"):Enable(); else getglobal(self:GetName().."Reply"):Disable(); end if (mailObject.CODAmount + mailObject.AttachedMoney + mailObject.AttachedItems + mailObject.AttachedDiamonds > 0) then if (mailObject.WasReturned == true) then getglobal(self:GetName().."Return"):Disable(); else if (mailObject.CanReply == true) then getglobal(self:GetName().."Return"):Enable(); else getglobal(self:GetName().."Return"):Disable(); end end getglobal(self:GetName().."Delete"):Disable(); getglobal(self:GetName().."FooterAcceptCODCheck"):Hide(); self:ClearAttachments(); if (mailObject.CODAmount > 0) then -- C.O.D. mails local name, itemTexture, count = GetInboxItem(mailIndex, 1); self:AddAttachment("Item", itemTexture, count); self:ShowAttachments(mailObject.CODAmount); else if (mailObject.AttachedItems > 0 and mailObject.AttachedMoney > 0) then -- Gold & Item local name, itemTexture, count, link = GetInboxItem(mailIndex, 1); self:AddAttachment("Item", itemTexture, count); self:AddAttachment("Gold", "interface/icons/coin_03", mailObject.AttachedMoney); self:ShowAttachments(); elseif (mailObject.AttachedItems > 0) then -- Item local name, itemTexture, count, link = GetInboxItem(mailIndex, 1); self:AddAttachment("Item", itemTexture, count); self:ShowAttachments(); elseif (mailObject.AttachedMoney > 0) then -- Money self:AddAttachment("Gold", "interface/icons/coin_03", mailObject.AttachedMoney); self:ShowAttachments(); elseif (mailObject.AttachedDiamonds > 0) then -- Diamonds self:AddAttachment("Diamond", "interface/icons/crystal_01", mailObject.AttachedDiamonds); self:ShowAttachments(); end end else getglobal(self:GetName().."Footer"):Hide(); getglobal(self:GetName().."Return"):Disable(); getglobal(self:GetName().."Delete"):Enable(); end self:Show(); else self:Hide(); end end; this.AttachmentOnEnter = function(self, this) GameTooltip:SetOwner(this, "ANCHOR_RIGHT") GameTooltip:SetInboxItem(self.priv_ViewIndex) GameTooltip:Show() end this.AttachmentOnClick = function(self, this) local acceptCOD = false; if (UMMMailManager.Mails[self.priv_ViewIndex].CODAmount > 0) then if (getglobal(self:GetName().."FooterAcceptCODCheck"):IsChecked()) then acceptCOD = true; end end if (UMMMailManager:GetAttachments(self.priv_ViewIndex, acceptCOD, self:GetName())) then getglobal(self:GetName().."Reply"):Disable(); getglobal(self:GetName().."Return"):Disable(); getglobal(self:GetName().."Delete"):Disable(); getglobal(self:GetName().."Close"):Disable(); else -- COD not accepted - message already shown end end; this.AttachmentOnLeave = function(self, this) GameTooltip:Hide() end this.RefreshViewer = function(self) -- Refresh after attachment action ... local mailObject = UMMMailManager.Mails[self.priv_ViewIndex] local parentName = self.priv_ParentFrameName local mailIndex = self.priv_ViewIndex self:Display(parentName, mailIndex, mailObject) getglobal(self:GetName().."Close"):Enable() end this.SignalViewerClosed = function(self) self:ClearAttachments() getglobal(self:GetName().."BodyFrameInput"):ClearFocus() getglobal(self.priv_ParentFrameName):ViewerClosed(); self.priv_ParentFrameName = nil; end; this.ButtonClick = function(self, action) if (string.lower(action) == "reply") then UMMMailManager:ReplyToMail(self.priv_ViewIndex); self:Hide(); elseif (string.lower(action) == "return") then if (UMMMailManager:ReturnMail(self.priv_ViewIndex)) then self:Hide(); end elseif (string.lower(action) == "delete") then if (UMMMailManager:DeleteMail(self.priv_ViewIndex)) then self:Hide(); end elseif (string.lower(action) == "close") then self:Hide(); end end; this.InitView = function(self) getglobal(self:GetName().."HeaderAuthorLabel"):SetText("|cff"..UMMColor.Grey..UMM_VIEWER_LABEL_FROM.."|r"); getglobal(self:GetName().."HeaderSubjectLabel"):SetText("|cff"..UMMColor.Grey..UMM_VIEWER_LABEL_SUBJECT.."|r"); getglobal(self:GetName().."Reply"):SetText(UMM_VIEWER_BUTTON_REPLY); getglobal(self:GetName().."Return"):SetText(UMM_VIEWER_BUTTON_RETURN); getglobal(self:GetName().."Delete"):SetText(UMM_VIEWER_BUTTON_DELETE); getglobal(self:GetName().."Close"):SetText(UMM_VIEWER_BUTTON_CLOSE); getglobal(self:GetName().."FooterAttachmentLabel"):SetText("|cff"..UMMColor.White..UMM_VIEWER_ATTACHED.."|r"); getglobal(self:GetName().."FooterAcceptCODCheckLabel"):SetText("|cff"..UMMColor.White..UMM_VIEWER_ATTACHMENTACCEPT.."|r"); -- Disable the buttons except Close getglobal(self:GetName().."Reply"):Disable(); getglobal(self:GetName().."Return"):Disable(); getglobal(self:GetName().."Delete"):Disable(); getglobal(self:GetName().."Footer"):Hide(); end; this:InitView(); end function UMMMailViewerTemplate_OnHide(this) this:SignalViewerClosed(); end
mit
smartdevicelink/sdl_atf_test_scripts
test_scripts/Protocol/NACKReason/017_SetVideoConfig_error_response_Video_Service_NACK.lua
1
2518
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0308-protocol-nak-reason.md -- -- Description: SDL provides reason information in NACK message -- in case NACK received because HMI responds with erroneous result code to Navigation.SetVideoConfig request -- -- Precondition: -- 1. SDL and HMI are started -- 2. Mobile app is registered with 'NAVIGATION' HMI type and with 5 protocol -- 3. Mobile app is activated -- -- Steps: -- 1. Mobile app requests the opening of Video service -- SDL does: -- - send Navigation.SetVideoConfig request to HMI -- 2. HMI responds with erroneous result code to Navigation.SetVideoConfig request -- SDL does: -- - respond with NACK to StartService request because HMI responds with erroneous result code -- to Navigation.SetVideoConfig request -- - provide reason information in NACK message --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local common = require("test_scripts/Protocol/commonProtocol") --[[ Local Variables ]] local videoServiceParams = { reqParams = { height = { type = common.bsonType.INT32, value = 350 }, width = { type = common.bsonType.INT32, value = 800 }, videoProtocol = { type = common.bsonType.STRING, value = "RAW" }, videoCodec = { type = common.bsonType.STRING, value = "H264" }, }, nackParams = { reason = { type = common.bsonType.STRING, value = "Received SetVideoConfig failure response" } } } --[[ Local Functions ]] local function setVideoConfig() common.getHMIConnection():ExpectRequest("Navigation.SetVideoConfig") :Do(function(_, data) common.getHMIConnection():SendError(data.id, data.method, "REJECTED", "Request is rejected" ) end) end --[[ Scenario ]] common.Title("Preconditions") common.Step("Clean environment", common.preconditions) common.Step("Start SDL, HMI, connect Mobile, start Session", common.start) common.Step("Register App", common.registerAppUpdatedProtocolVersion) common.Step("Activate App", common.activateApp) common.Title("Test") common.Step("Start Video Service, erroneous SetVideoConfig response, NACK", common.startServiceUnprotectedNACK, { 1, common.serviceType.VIDEO, videoServiceParams.reqParams, videoServiceParams.nackParams, setVideoConfig }) common.Title("Postconditions") common.Step("Stop SDL", common.postconditions)
bsd-3-clause
Squeakz/darkstar
scripts/zones/Meriphataud_Mountains/npcs/Mushosho.lua
13
1915
----------------------------------- -- Area: Meriphataud Mountains -- NPC: Mushosho -- Type: Outpost Vendor -- @pos -290 16 415 119 ----------------------------------- package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); require("scripts/zones/Meriphataud_Mountains/TextIDs"); local region = ARAGONEU; local csid = 0x7ff4; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local owner = GetRegionOwner(region); local arg1 = getArg1(owner,player); if (owner == player:getNation()) then nation = 1; elseif (arg1 < 1792) then nation = 2; else nation = 0; end player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP()); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if (option == 1) then ShowOPVendorShop(player); elseif (option == 2) then if (player:delGil(OP_TeleFee(player,region))) then toHomeNation(player); end elseif (option == 6) then player:delCP(OP_TeleFee(player,region)); toHomeNation(player); end end;
gpl-3.0
ddumont/darkstar
scripts/zones/PsoXja/npcs/_09a.lua
14
2875
----------------------------------- -- Area: Pso'Xja -- NPC: _09a (Stone Gate) -- Notes: Spawns Gargoyle when triggered -- @pos 261.600 -1.925 -50.000 9 ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if ((trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1 and player:getMainJob() == JOBS.THF) then local X=player:getXPos(); if (npc:getAnimation() == 9) then if (X <= 261) then if (GetMobAction(16814091) == 0) then local Rand = math.random(1,2); -- estimated 50% success as per the wiki if (Rand == 1) then -- Spawn Gargoyle player:messageSpecial(DISCOVER_DISARM_FAIL + 0x8000, 0, 0, 0, 0, true); SpawnMob(16814091):updateClaim(player); -- Gargoyle else player:messageSpecial(DISCOVER_DISARM_SUCCESS + 0x8000, 0, 0, 0, 0, true); npc:openDoor(30); end player:tradeComplete(); else player:messageSpecial(DOOR_LOCKED); end end end end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local X=player:getXPos(); if (npc:getAnimation() == 9) then if (X <= 261) then if (GetMobAction(16814091) == 0) then local Rand = math.random(1,10); if (Rand <=9) then -- Spawn Gargoyle player:messageSpecial(TRAP_ACTIVATED + 0x8000, 0, 0, 0, 0, true); SpawnMob(16814091):updateClaim(player); -- Gargoyle else player:messageSpecial(TRAP_FAILS + 0x8000, 0, 0, 0, 0, true); npc:openDoor(30); end else player:messageSpecial(DOOR_LOCKED); end elseif (X >= 262) then player:startEvent(0x001A); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x001A and option == 1) then player:setPos(260,-0.25,-20,254,111); end end;
gpl-3.0
ddumont/darkstar
scripts/zones/Port_Bastok/npcs/Tete.lua
17
1303
----------------------------------- -- Area: Port Bastok -- NPC: Tete -- Continues Quest: The Wisdom Of Elders ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ------------------------------------ require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(BASTOK,THE_WISDOM_OF_ELDERS) == QUEST_ACCEPTED) then player:startEvent(0x00af); else player:startEvent(0x0023); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00af) then player:setVar("TheWisdomVar",2); end end;
gpl-3.0
smartdevicelink/sdl_atf_test_scripts
test_scripts/SDL5_0/FullAppID/002_PTU_full_app_ID_false.lua
1
1845
--------------------------------------------------------------------------------------------- -- Script verifies that a PT snapshot contains the correct full_app_id_supported flag -- Supports PROPRIETARY --------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local actions = require("user_modules/sequences/actions") local common = require("test_scripts/SDL5_0/FullAppID/common") local full_app_id_supported = "false" -- This is the id in the policy table common.policy_app_id = config.application1.registerAppInterfaceParams.fullAppID -- copy the fullAppID field to appID and remove full app id config.application1.registerAppInterfaceParams.appID = config.application1.registerAppInterfaceParams.fullAppID config.application1.registerAppInterfaceParams.fullAppID = nil runner.Title("Preconditions " .. full_app_id_supported) -- Stop SDL if process is still running, delete local policy table and log files runner.Step("Clean environment", common.preconditions) runner.Step("Set UseFullAppID to true", actions.setSDLIniParameter, {"UseFullAppID", full_app_id_supported}) -- Start SDL and HMI, establish connection between SDL and HMI, open mobile connection via TCP runner.Step("Start SDL, HMI, connect Mobile", common.start) -- Pring in terminal build options(RC status and policy slow) runner.Step("SDL Configuration", common.printSDLConfig) runner.Title("Test " .. full_app_id_supported) -- create mobile session, register application, perform PTU wit PT runner.Step("RAI, PTU", common.raiPTU) -- Check that PTU is performed successful runner.Step("Check Status", common.checkPTUStatus) runner.Title("Postconditions " .. full_app_id_supported) runner.Step("Restore ini and stop SDL", common.postconditions)
bsd-3-clause
Squeakz/darkstar
scripts/zones/Bastok_Mines/npcs/Explorer_Moogle.lua
13
1711
----------------------------------- -- Area: Bastok Mines -- NPC: Explorer Moogle -- ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/teleports"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) accept = 0; event = 0x0249; if (player:getGil() < 300) then accept = 1; end if (player:getMainLvl() < EXPLORER_MOOGLE_LEVELCAP) then event = event + 1; end player:startEvent(event,player:getZoneID(),0,accept); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); local price = 300; if (csid == 0x0249) then if (option == 1 and player:delGil(price)) then toExplorerMoogle(player,231); elseif (option == 2 and player:delGil(price)) then toExplorerMoogle(player,234); elseif (option == 3 and player:delGil(price)) then toExplorerMoogle(player,240); elseif (option == 4 and player:delGil(price)) then toExplorerMoogle(player,248); elseif (option == 5 and player:delGil(price)) then toExplorerMoogle(player,249); end end end;
gpl-3.0
Squeakz/darkstar
scripts/globals/items/sis_kebabi.lua
18
1650
----------------------------------------- -- ID: 5598 -- Item: sis_kebabi -- Food Effect: 30Min, All Races ----------------------------------------- -- Strength 6 -- Vitality -2 -- Intelligence -2 -- Attack % 20 -- Attack Cap 70 -- Ranged ATT % 20 -- Ranged ATT Cap 70 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5598); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 6); target:addMod(MOD_VIT, -2); target:addMod(MOD_INT, -2); target:addMod(MOD_FOOD_ATTP, 20); target:addMod(MOD_FOOD_ATT_CAP, 70); target:addMod(MOD_FOOD_RATTP, 20); target:addMod(MOD_FOOD_RATT_CAP, 70); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 6); target:delMod(MOD_VIT, -2); target:delMod(MOD_INT, -2); target:delMod(MOD_FOOD_ATTP, 20); target:delMod(MOD_FOOD_ATT_CAP, 70); target:delMod(MOD_FOOD_RATTP, 20); target:delMod(MOD_FOOD_RATT_CAP, 70); end;
gpl-3.0
ddumont/darkstar
scripts/globals/items/bijou_glace.lua
12
1326
----------------------------------------- -- ID: 4269 -- Item: Bijou Glace -- Food Effect: 240Min, All Races ----------------------------------------- -- Magic % 13 -- Magic Cap 90 -- Magic Regen While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4269); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 13); target:addMod(MOD_FOOD_MP_CAP, 90); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP, 13); target:delMod(MOD_FOOD_MP_CAP, 90); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
ddumont/darkstar
scripts/globals/weaponskills/double_thrust.lua
26
1348
----------------------------------- -- Double Thrust -- Polearm weapon skill -- Skill Level: 5 -- Delivers a two-hit attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Light Gorget. -- Aligned with the Light Belt. -- Element: None -- Modifiers: STR:30% -- 100%TP 200%TP 300%TP -- 1.00 1.50 2.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 2; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.dex_wsc = 0.3; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Adirelle/oUF
elements/assistantindicator.lua
7
2432
--[[ # Element: Assistant Indicator Toggles the visibility of an indicator based on the unit's raid assistant status. ## Widget AssistantIndicator - Any UI widget. ## Notes A default texture will be applied if the widget is a Texture and doesn't have a texture or a color set. ## Examples -- Position and size local AssistantIndicator = self:CreateTexture(nil, 'OVERLAY') AssistantIndicator:SetSize(16, 16) AssistantIndicator:SetPoint('TOP', self) -- Register it with oUF self.AssistantIndicator = AssistantIndicator --]] local _, ns = ... local oUF = ns.oUF local function Update(self, event) local element = self.AssistantIndicator local unit = self.unit --[[ Callback: AssistantIndicator:PreUpdate() Called before the element has been updated. * self - the AssistantIndicator element --]] if(element.PreUpdate) then element:PreUpdate() end local isAssistant = UnitInRaid(unit) and UnitIsGroupAssistant(unit) and not UnitIsGroupLeader(unit) if(isAssistant) then element:Show() else element:Hide() end --[[ Callback: AssistantIndicator:PostUpdate(isAssistant) Called after the element has been updated. * self - the AssistantIndicator element * isAssistant - indicates whether the unit is a raid assistant (boolean) --]] if(element.PostUpdate) then return element:PostUpdate(isAssistant) end end local function Path(self, ...) --[[ Override: AssistantIndicator.Override(self, event, ...) Used to completely override the element's update process. * self - the parent object * event - the event triggering the update (string) * ... - the arguments accompanying the event (string) --]] return (self.AssistantIndicator.Override or Update) (self, ...) end local function ForceUpdate(element) return Path(element.__owner, 'ForceUpdate') end local function Enable(self) local element = self.AssistantIndicator if(element) then element.__owner = self element.ForceUpdate = ForceUpdate self:RegisterEvent('GROUP_ROSTER_UPDATE', Path, true) if(element:IsObjectType('Texture') and not element:GetTexture()) then element:SetTexture([[Interface\GroupFrame\UI-Group-AssistantIcon]]) end return true end end local function Disable(self) local element = self.AssistantIndicator if(element) then element:Hide() self:UnregisterEvent('GROUP_ROSTER_UPDATE', Path) end end oUF:AddElement('AssistantIndicator', Path, Enable, Disable)
mit
Squeakz/darkstar
scripts/zones/Eastern_Altepa_Desert/mobs/Cactrot_Rapido.lua
4
13314
----------------------------------- -- Area: Eastern Altepa Desert -- NM: Cactrot Rapido ----------------------------------- require("scripts/globals/titles"); local path = { -45.214237, 0.059482, -204.244873, -46.114422, 0.104212, -203.765884, -47.013275, 0.149004, -203.285812, -47.911877, 0.193759, -202.805313, -58.443733, 0.767810, -197.319977, -61.495697, 0.477824, -195.851227, -64.869675, 0.109868, -194.287720, -75.073441, 0.254733, -189.665695, -81.320366, 0.495319, -186.993607, -91.067123, 0.288822, -183.020676, -97.377228, -0.392546, -180.579071, -99.247047, -0.895448, -179.936798, -100.800270, -1.393698, -179.434647, -102.352448, -1.900111, -178.961166, -103.899933, -2.504567, -178.528854, -105.126732, -3.031813, -178.190872, -106.367256, -3.527977, -177.907257, -107.613914, -4.023795, -177.639709, -108.867058, -4.500517, -177.388947, -110.153046, -4.924853, -177.183960, -111.440956, -5.322861, -177.007553, -112.735832, -5.956526, -176.851334, -114.710777, -5.139105, -176.495575, -116.667969, -4.440962, -176.081223, -117.885887, -3.910276, -175.532532, -119.009041, -3.591512, -174.816345, -120.015816, -3.243386, -173.936310, -120.987274, -2.875988, -173.018311, -121.980667, -2.569070, -172.122421, -122.732048, -2.157357, -171.448853, -125.173172, -0.957143, -169.194305, -125.936897, -0.534065, -168.118042, -126.509903, -0.232718, -167.291153, -127.278130, 0.155391, -166.201279, -128.056259, 0.507568, -165.116730, -128.636505, 0.869508, -164.300949, -136.568512, 3.083321, -153.014694, -136.977478, 3.211246, -152.089355, -137.378784, 3.349919, -151.163742, -137.792618, 3.493883, -150.238480, -138.222778, 3.588699, -149.317413, -139.789780, 4.143739, -145.951996, -140.113312, 4.375872, -144.993851, -140.287079, 4.543484, -143.998215, -140.466980, 4.650395, -142.999802, -140.650879, 4.757523, -142.002258, -140.834824, 4.864695, -141.004730, -141.029587, 4.938367, -140.006378, -141.407669, 5.135919, -138.010376, -141.643478, 5.328803, -136.341202, -141.718018, 5.393569, -135.328995, -141.813690, 5.423491, -134.313965, -141.928970, 5.490732, -132.961258, -142.095245, 5.603091, -130.931778, -142.253555, 5.573742, -129.240341, -142.852249, 5.496122, -123.503990, -143.283661, 5.484383, -119.451439, -143.331360, 5.500263, -118.093521, -143.367279, 5.357600, -117.080986, -143.595398, 4.682551, -114.444756, -143.761444, 4.288168, -113.153831, -143.944153, 3.851855, -111.863541, -144.114670, 3.081480, -110.600967, -144.374863, 2.389771, -109.383690, -144.561234, 1.352810, -107.876305, -144.406784, 0.635471, -106.733185, -144.221008, -0.194526, -105.556168, -143.877808, -0.956815, -104.450096, -143.333038, -1.686279, -103.367638, -142.964157, -2.185963, -102.417923, -142.580856, -1.692963, -101.476410, -142.176361, -1.494776, -100.551079, -141.584686, -1.078624, -99.351585, -141.150131, -0.753439, -98.444046, -140.304092, -0.076350, -96.605209, -138.948074, 0.686977, -93.901413, -138.008743, 1.152010, -92.116440, -136.429688, 1.963583, -89.143188, -134.031357, 2.365622, -84.672249, -133.287766, 2.253940, -83.149849, -131.816559, 1.901823, -80.109253, -129.684540, 1.223290, -75.525696, -126.872261, 0.516513, -69.392265, -124.933060, 0.570506, -65.425987, -122.093231, 0.971921, -59.642326, -121.642838, 0.935626, -58.728325, -109.254097, -0.174285, -33.826805, -107.579643, -0.704243, -30.530849, -104.290489, -2.292845, -24.004328, -103.340012, -2.798456, -22.273823, -101.417862, -3.851769, -18.828547, -97.400208, -5.963912, -11.658532, -96.157463, -6.415525, -9.279702, -94.492889, -7.087772, -6.000663, -87.445793, -8.721937, 8.182076, -82.627701, -10.710227, 17.341963, -78.738350, -12.969520, 24.556398, -77.843742, -12.820852, 24.081251, -76.622406, -12.841505, 24.162075, -75.760681, -13.003385, 24.680101, -74.814415, -13.116152, 25.040958, -73.821739, -13.185088, 25.261553, -72.808220, -13.145959, 25.357367, -71.794624, -13.038998, 25.335396, -70.787224, -12.916903, 25.232685, -69.777863, -12.797923, 25.146303, -68.767639, -12.701465, 25.068045, -67.753258, -12.639880, 24.988928, -66.398720, -12.608677, 24.871193, -63.693352, -12.663887, 24.614614, -61.332371, -12.802485, 24.348162, -50.877781, -13.008631, 23.174417, -49.525688, -12.897259, 23.080366, -44.121357, -12.405771, 22.702574, -41.750877, -12.331022, 22.526335, -31.591017, -12.228968, 21.767466, -30.574598, -12.240875, 21.682938, -28.892553, -12.373736, 21.497755, -26.193161, -12.326892, 21.279018, -25.180489, -12.211316, 21.241808, -23.829905, -12.058004, 21.196482, -18.073771, -11.557770, 20.988880, -15.020272, -11.416804, 20.876867, -10.272671, -11.514080, 20.625463, -5.530938, -11.567481, 20.363932, -2.144115, -11.611256, 20.183678, 1.250314, -11.545613, 20.013973, 4.980156, -11.624237, 19.813007, 6.658255, -11.886693, 19.655684, 7.651558, -12.083179, 19.533247, 8.947555, -12.524771, 19.332045, 10.214692, -12.953741, 19.087330, 11.502657, -13.320731, 18.860584, 12.780280, -13.754982, 18.569122, 14.030073, -14.196076, 18.227663, 15.295671, -14.636890, 17.897783, 16.523689, -15.021481, 17.490923, 18.113350, -15.462179, 17.026085, 19.330448, -16.081728, 16.884964, 20.436007, -16.775909, 16.924559, 21.711395, -17.273441, 16.566978, 23.008286, -17.863113, 16.240875, 25.600761, -16.349407, 15.708939, 27.885015, -14.547360, 15.286979, 29.175026, -13.795184, 15.093222, 31.474035, -12.003471, 14.741585, 32.733868, -11.282872, 14.418842, 34.007584, -10.686451, 14.024928, 35.271973, -10.187914, 13.686438, 36.557934, -9.658462, 13.328313, 38.519291, -9.480738, 12.813184, 42.436985, -9.212695, 11.718233, 43.381554, -9.141721, 11.339855, 44.327057, -9.046030, 10.973053, 45.586422, -8.833047, 10.505932, 53.230701, -8.530454, 7.711083, 55.138641, -8.453061, 6.993709, 59.573353, -7.617370, 5.394830, 69.459343, -7.685488, 1.939287, 72.022415, -7.802935, 1.038878, 72.933075, -7.848290, 0.582272, 73.840149, -7.893467, 0.117998, 74.749786, -7.938770, -0.341271, 75.661224, -7.972084, -0.797652, 76.574295, -7.968478, -1.252196, 83.864113, -7.963341, -4.913532, 85.353340, -7.848778, -5.726798, 92.465195, -7.863905, -9.688751, 93.283051, -7.853431, -10.298190, 94.106422, -7.894407, -10.898237, 94.932503, -7.953709, -11.493578, 95.759720, -8.025735, -12.087400, 102.684669, -8.555371, -16.980604, 103.452599, -8.716061, -17.633831, 104.192497, -8.917103, -18.314260, 105.165489, -9.238935, -19.207094, 106.146698, -9.576337, -20.094185, 107.875641, -10.310707, -21.564810, 110.510101, -11.774194, -23.772697, 112.850891, -11.348615, -25.616978, 113.918427, -10.971118, -26.418327, 114.921410, -10.609308, -27.303473, 115.544731, -10.389357, -28.099230, 116.108887, -10.155023, -28.928883, 116.677101, -9.907154, -29.764107, 117.259628, -9.660060, -30.577936, 117.841934, -9.415455, -31.403658, 118.628448, -9.101988, -32.489857, 119.226006, -8.906536, -33.291828, 121.370842, -8.177029, -36.269379, 121.892303, -8.089925, -37.141682, 122.419975, -8.003403, -38.010284, 123.126312, -8.000000, -39.172443, 124.321335, -7.985068, -41.228336, 124.715233, -7.965429, -42.168995, 125.117836, -7.945378, -43.105942, 125.524841, -7.925108, -44.041027, 125.932388, -7.857445, -44.973671, 126.477409, -7.837416, -46.216499, 128.163406, -7.896171, -50.290894, 128.435196, -7.838074, -51.272820, 128.713623, -7.837389, -52.253597, 129.000900, -7.732649, -53.228714, 129.289841, -7.648998, -54.203396, 129.763367, -7.580074, -56.180931, 129.849594, -7.588713, -57.197235, 129.947464, -7.598557, -58.212494, 130.050140, -7.608885, -59.227268, 130.154587, -7.632762, -60.241852, 130.148819, -7.683857, -61.259670, 129.995834, -7.740675, -62.266739, 129.800461, -7.810890, -63.265373, 129.614334, -7.882718, -64.265656, 129.431046, -7.955023, -65.266464, 129.248032, -8.027370, -66.267303, 128.941101, -8.148669, -67.934982, 128.592590, -8.226739, -69.244926, 128.169174, -8.255370, -70.171631, 127.624290, -8.259485, -71.033081, 127.052391, -8.258126, -71.877647, 126.489380, -8.258752, -72.728165, 125.929886, -8.260109, -73.581032, 125.371674, -8.261738, -74.434708, 124.246277, -8.290220, -76.135551, 123.706482, -8.174309, -76.993515, 122.960106, -8.099961, -78.127975, 121.970772, -8.000000, -79.504745, 121.232613, -8.000000, -80.207413, 120.399490, -8.000000, -80.794556, 119.492821, -8.000000, -81.260330, 118.549973, -8.000000, -81.649460, 117.614258, -8.000000, -82.055428, 116.680702, -8.000000, -82.466354, 115.746910, -8.000000, -82.876801, 114.813171, -7.956547, -83.285782, 113.566681, -7.910290, -83.827690, 111.362625, -7.895653, -84.719353, 110.370857, -7.837558, -84.951813, 109.379196, -7.779317, -85.183273, 108.389091, -7.722087, -85.421638, 107.398117, -7.713781, -85.657982, 106.404572, -7.742430, -85.887161, 100.443123, -7.914205, -87.261345, 78.931618, -9.066314, -92.160812, 78.006859, -9.174266, -92.574493, 77.191170, -9.243567, -93.175354, 76.518112, -9.365136, -93.929840, 75.956619, -9.517926, -94.767433, 75.396698, -9.684797, -95.603516, 74.836777, -9.851719, -96.439613, 74.276855, -10.018639, -97.275703, 73.716927, -10.185554, -98.111778, 73.157005, -10.352473, -98.947868, 72.037186, -10.691887, -100.619995, 65.185234, -12.325055, -110.974182, 64.502304, -12.210523, -112.137856, 63.758068, -12.309777, -113.272629, 60.121979, -12.452700, -119.008751, 57.324074, -12.271764, -123.665543, 54.016415, -11.951966, -129.203384, 51.480064, -12.026159, -133.225754, 50.535629, -12.216867, -134.627289, 49.575897, -12.556334, -136.002838, 48.761570, -12.911916, -137.027985, 47.980934, -13.217538, -138.086014, 45.906788, -14.359197, -140.978027, 45.197201, -13.630539, -142.093567, 44.498314, -12.896272, -143.199234, 43.958618, -12.095625, -144.064774, 42.670326, -11.275743, -146.004883, 36.821983, -8.478559, -154.982544, 33.769165, -7.889951, -159.845291, 28.914276, -7.639688, -167.631866, 22.451923, -4.734315, -177.783630, 20.719790, -3.657952, -180.643219, 20.171061, -3.421347, -181.483154, 19.586971, -3.203986, -182.310669, 18.478239, -2.926458, -182.771957, 17.234682, -2.637700, -182.976196, 16.290546, -2.427790, -183.316666, 15.309304, -2.271078, -183.548950, 14.327208, -2.134478, -183.788116, 13.344822, -1.998021, -184.026215, 12.361718, -1.863053, -184.263077, 8.079593, -1.926340, -185.327988, 2.468133, -1.674941, -186.621872, 0.478332, -1.519862, -187.029205, -5.183570, -1.168827, -188.135437, -10.524970, -0.787942, -189.075882, -11.111217, -0.629007, -189.894958, -12.298127, -0.580679, -190.385666, -13.245046, -0.599274, -190.750412, -14.188004, -0.496885, -191.123428, -15.131532, -0.387342, -191.495163, -16.076939, -0.359143, -191.862503, -18.904144, 0.286367, -192.923462, -19.298399, 0.512927, -193.844086, -20.236032, 0.637131, -194.226257, -21.165127, 0.763740, -194.627731, -22.089966, 0.795228, -195.051437, -23.013824, 0.792700, -195.483749, -23.938154, 0.790050, -195.915085, -25.589787, 0.636639, -196.951553, -26.508005, 0.544279, -197.385910, -27.422697, 0.452274, -197.827805, -28.337297, 0.380589, -198.272293, -29.254520, 0.334919, -198.716125, -31.397188, 0.228204, -199.746597, -36.625172, 0.000000, -202.187897, -37.873020, 0.000000, -202.493210, -39.119324, 0.000000, -203.037552, -40.370975, 0.000000, -203.569611 }; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) onMobRoam(mob); end; ----------------------------------- -- onPath Action ----------------------------------- function onPath(mob) pathfind.patrol(mob, path, PATHFLAG_RUN); end; ----------------------------------- -- onMobRoam Action ----------------------------------- function onMobRoam(mob) -- move to start position if not moving if (mob:isFollowingPath() == false) then mob:pathThrough(pathfind.first(path), PATHFLAG_RUN); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) player:addTitle(CACTROT_DESACELERADOR); -- Set Cactrot Rapido's spawnpoint and respawn time (24-72 hours) UpdateNMSpawnPoint(mob:getID()); mob:setRespawnTime(math.random(86400,259200)); end;
gpl-3.0
Squeakz/darkstar
scripts/zones/South_Gustaberg/npcs/Stone_Monument.lua
13
1276
----------------------------------- -- Area: South Gustaberg -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos 520.064 -5.881 -738.356 107 ----------------------------------- package.loaded["scripts/zones/South_Gustaberg/TextIDs"] = nil; ----------------------------------- require("scripts/zones/South_Gustaberg/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x00040); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
ddumont/darkstar
scripts/zones/Buburimu_Peninsula/npcs/Signpost.lua
13
1438
----------------------------------- -- Area: Buburimu Peninsula -- NPC: Signpost ----------------------------------- package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Buburimu_Peninsula/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getID() == 17261165) then player:messageSpecial(SIGN_5); elseif (npc:getID() == 17261166) then player:messageSpecial(SIGN_4); elseif (npc:getID() == 17261167) then player:messageSpecial(SIGN_3); elseif (npc:getID() == 17261168) then player:messageSpecial(SIGN_2); elseif (npc:getID() == 17261169) or (npc:getID() == 17261170) or (npc:getID() == 17261171) then player:messageSpecial(SIGN_1); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --print("CSID: %u",csid); --print("RESULT: %u",option); end;
gpl-3.0
Squeakz/darkstar
scripts/globals/items/serving_of_salmon_eggs.lua
18
1325
----------------------------------------- -- ID: 5217 -- Item: serving_of_salmon_eggs -- Food Effect: 5Min, All Races ----------------------------------------- -- Health 6 -- Magic 6 -- Dexterity 2 -- Mind -3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5217); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 6); target:addMod(MOD_MP, 6); target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 6); target:delMod(MOD_MP, 6); target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -3); end;
gpl-3.0
coreyfarrell/testsuite
asttest/self-tests/proclib_perror/test.lua
5
1684
-- test proclib's ablity to detect missing and non-executable files real_print = print function print(msg) printed = true if msg ~= expected_msg then print = real_print fail("expected perror to print '" .. tostring(expected_msg) .. "' but got '" .. msg .. "' instead") end end function expect(msg) printed = false expected_msg = msg end function check() if not printed then print = real_print fail("expected perror to print '" .. tostring(expected_msg) .. "' but got nothing instead") end expected_msg = nil printed = false end function test_crash() real_print("testing crash") expect("process crashed (core dumped)") proc.perror(nil, "core") check() end function test_timeout() real_print("testing a timeout") expect(nil) local p = proc.exec("sleep", "1") proc.perror(p:wait(1)) end function test_error_1() real_print("testing an error (1)") expect("error running process") proc.perror(nil, "error") check() end function test_error_2() real_print("testing an error (2)") expect("error running process (error)") proc.perror(nil, "error", "error", 1) check() end function test_signal_1() real_print("testing a signal (1)") expect("process terminated by signal 0") proc.perror(nil, 0) check() end function test_signal_2() real_print("testing a signal (2)") expect("process terminated by signal 15") local p = proc.exec("sleep", "1") proc.perror(p:term()) check() end function test_unknown() real_print("testing an unknown error (2)") expect("error running process (unknown)") proc.perror(nil, "unknown") check() end test_crash() test_timeout() test_error_1() test_error_2() test_signal_1() test_signal_2() test_unknown()
gpl-2.0
ddumont/darkstar
scripts/zones/Abyssea-Misareaux/npcs/qm13.lua
14
1548
----------------------------------- -- Zone: Abyssea-Misareaux -- NPC: qm13 (???) -- Spawns Cirein-Croin -- @pos ? ? ? 216 ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/status"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --[[ if (GetMobAction(17662481) == ACTION_NONE) then -- NM not already spawned from this if (player:hasKeyItem(GLISTENING_OROBON_LIVER) and player:hasKeyItem(DOFFED_POROGGO_HAT)) then player:startEvent(1021, GLISTENING_OROBON_LIVER, DOFFED_POROGGO_HAT); -- Ask if player wants to use KIs else player:startEvent(1020, GLISTENING_OROBON_LIVER, DOFFED_POROGGO_HAT); -- Do not ask, because player is missing at least 1. end end ]] end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 1021 and option == 1) then SpawnMob(17662481):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:delKeyItem(GLISTENING_OROBON_LIVER); player:delKeyItem(DOFFED_POROGGO_HAT); end end;
gpl-3.0
ddumont/darkstar
scripts/globals/mobskills/Stormwind.lua
30
2237
--------------------------------------------- -- Stormwind -- -- Description: Creates a whirlwind that deals Wind damage to targets in an area of effect. -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: Unknown radial -- Notes: --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- -- onMobSkillCheck --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; --------------------------------------------- -- onMobWeaponSkill --------------------------------------------- function onMobWeaponSkill(target, mob, skill) local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_WIND,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS); if (mob:getName() == "Kreutzet") then if (mob:actionQueueAbility() == true) then if (mob:getLocalVar("Stormwind") == 0) then mob:setLocalVar("Stormwind", 1); dmgmod = 1.25; info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_WIND,dmgmod,TP_NO_EFFECT); dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS); elseif (mob:getLocalVar("Stormwind") == 1) then mob:setLocalVar("Stormwind", 0); dmgmod = 1.6; info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_WIND,dmgmod,TP_NO_EFFECT); dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS); end elseif (mob:actionQueueAbility() == false) then for i = 0, 1 do -- Stormwind 3 times per use. Gets stronger each use. -- TODO: Should be some sort of delay here between ws's.. mob:useMobAbility(926); mob:setLocalVar("Stormwind", 0); end end end target:delHP(dmg); return dmg; end;
gpl-3.0
smartdevicelink/sdl_atf_test_scripts
test_scripts/SDL5_0/TTSChunks/002_SetGlobalProperties.lua
1
3314
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0014-adding-audio-file-playback-to-ttschunk.md -- User story:TBD -- Use case:TBD -- -- Requirement summary: -- TBD -- -- Description: -- In case: -- 1) HMI provides ‘FILE’ item in ‘speechCapabilities’ parameter of ‘TTS.GetCapabilities’ response -- 2) New app registers and send SetGlobalProperties with ‘FILE’ item in ‘helpPrompt’, ‘timeoutPrompt’ parameters -- SDL does: -- 1) Send TTS.SetGlobalProperties request to HMI with ‘FILE’ item in ‘helpPrompt’, ‘timeoutPrompt’ parameters --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('test_scripts/SDL5_0/TTSChunks/common') --[[ Local Variables ]] local putFileParams = { requestParams = { syncFileName = 'pathToFile1', fileType = "GRAPHIC_PNG", persistentFile = false, systemFile = false }, filePath = "files/icon.png" } local putFileParams2 = { requestParams = { syncFileName = 'pathToFile2', fileType = "GRAPHIC_PNG", persistentFile = false, systemFile = false }, filePath = "files/icon.png" } local params = { helpPrompt = { { type = common.type, text = "pathToFile1" } }, timeoutPrompt = { { type = common.type, text = "pathToFile2" } } } local hmiParams = { helpPrompt = { { type = common.type, text = common.getPathToFileInStorage("pathToFile1") } }, timeoutPrompt = { { type = common.type, text = common.getPathToFileInStorage("pathToFile2") } } } --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local Functions ]] local function sendSetGlobalProperties_FILE_NOT_FOUND() local corId = common.getMobileSession():SendRPC("SetGlobalProperties", params) common.getMobileSession():ExpectResponse(corId, { success = false, resultCode = "FILE_NOT_FOUND" }) end local function sendSetGlobalProperties_SUCCESS() local corId = common.getMobileSession():SendRPC("SetGlobalProperties", params) common.getHMIConnection():ExpectRequest("TTS.SetGlobalProperties", { helpPrompt = hmiParams.helpPrompt, timeoutPrompt = hmiParams.timeoutPrompt }) :Do(function(_, data) common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {}) end) common.getMobileSession():ExpectResponse(corId, { success = true, resultCode = "SUCCESS" }) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, init HMI, connect Mobile", common.start) runner.Step("Register App", common.registerApp) runner.Step("Activate App", common.activateApp) runner.Title("Test") runner.Step("Send SetGlobalProperties FILE_NOT_FOUND response", sendSetGlobalProperties_FILE_NOT_FOUND) runner.Step("Upload first icon file", common.putFile, { putFileParams }) runner.Step("Upload second icon file", common.putFile, { putFileParams2 }) runner.Step("Send SetGlobalProperties SUCCESS response", sendSetGlobalProperties_SUCCESS) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
bsd-3-clause
ddumont/darkstar
scripts/globals/conquest.lua
8
46974
----------------------------------- -- -- Functions for Conquest system -- ----------------------------------- require("scripts/globals/common"); require("scripts/globals/missions"); ----------------------------------- -- convenience constants ----------------------------------- NATION_SANDORIA = 0; NATION_BASTOK = 1; NATION_WINDURST = 2; BEASTMEN = 3; OTHER = 4; RONFAURE = 0; ZULKHEIM = 1; NORVALLEN = 2; GUSTABERG = 3; DERFLAND = 4; SARUTABARUTA = 5; KOLSHUSHU = 6; ARAGONEU = 7; FAUREGANDI = 8; VALDEAUNIA = 9; QUFIMISLAND = 10; LITELOR = 11; KUZOTZ = 12; VOLLBOW = 13; ELSHIMOLOWLANDS = 14; ELSHIMOUPLANDS = 15; TULIA = 16; MOVALPOLOS = 17; TAVNAZIANARCH = 18; CONQUEST_TALLY_START = 0; CONQUEST_TALLY_END = 1; CONQUEST_UPDATE = 2; nationAlly = 3; ----------------------------------- -- San d'Oria inventory -- {Option,CP,Item} ----------------------------------- SandInv = {0x80A1,0x000A,0x1055,0x80A0,0x0007,0x1056,0x80A3,0x2328,0x3CB5, 0x80A2,0x09C4,0x3CB6,0x80A5,0x01F4,0x3D91,0x80A6,0x03E8,0x3D92, 0x80A7,0x07D0,0x3D93,0x8002,0x03E8,0x30DE,0x8003,0x03E8,0x31D1, 0x8004,0x03E8,0x32CC,0x8006,0x03E8,0x3596,0x8001,0x03E8,0x40A0, 0x8005,0x03E8,0x4133,0x8000,0x03E8,0x430F,0x8011,0x07D0,0x3156, 0x8012,0x07D0,0x3252,0x8014,0x07D0,0x32F5,0x8010,0x07D0,0x41D4, 0x8013,0x07D0,0x43D7,0x8022,0x0FA0,0x308F,0x8023,0x0FA0,0x318F, 0x8024,0x0FA0,0x328F,0x8021,0x0FA0,0x3330,0x8027,0x0FA0,0x34B7, 0x8025,0x0FA0,0x4168,0x8020,0x0FA0,0x41CC,0x8026,0x0FA0,0x42FE, 0x8034,0x1F40,0x3030,0x8031,0x1F40,0x310F,0x8032,0x1F40,0x320F, 0x8033,0x1F40,0x3597,0x8030,0x1F40,0x40D9,0x8042,0x3E80,0x3018, 0x8043,0x3E80,0x3019,0x8046,0x3E80,0x318E,0x8047,0x3E80,0x328E, 0x8045,0x3E80,0x3331,0x8044,0x3E80,0x3333,0x8048,0x3E80,0x33A4, 0x8049,0x3E80,0x3598,0x8041,0x3E80,0x40BB,0x8040,0x3E80,0x41D3, 0x8056,0x5DC0,0x3021,0x8052,0x5DC0,0x308E,0x8054,0x5DC0,0x310E, 0x8055,0x5DC0,0x320E,0x8051,0x5DC0,0x3332,0x8050,0x5DC0,0x350C, 0x8053,0x5DC0,0x359A,0x8058,0x5DC0,0x40D7,0x8059,0x5DC0,0x41A5, 0x8057,0x5DC0,0x42AB,0x8062,0x7D00,0x34F5,0x8061,0x7D00,0x41F6, 0x8060,0x7D00,0x4932,0x8072,0x9C40,0x3354,0x8070,0x9C40,0x36BD, 0x8071,0x9C40,0x36BE,0x8083,0xBB80,0x41FD,0x8080,0xBB80,0x4239, 0x8082,0xBB80,0x4432,0x8081,0xBB80,0x460E,0x8090,0xDAC0,0x385C, 0x80A4,0x1388,0x44AF,0x80A8,0x1388,0x6F7C}; ----------------------------------- -- Bastok inventory -- {Option,CP,Item} ----------------------------------- BastInv = {0x80A1,0x000A,0x1055,0x80A0,0x0007,0x1056,0x80A3,0x2328,0x3CB5, 0x80A2,0x09C4,0x3CB6,0x80A5,0x01F4,0x3D91,0x80A6,0x03E8,0x3D92, 0x80A7,0x07D0,0x3D93,0x8003,0x03E8,0x30DD,0x8004,0x03E8,0x31D0, 0x8005,0x03E8,0x32CB,0x8000,0x03E8,0x4031,0x8002,0x03E8,0x4108, 0x8007,0x03E8,0x418C,0x8006,0x03E8,0x42E8,0x8001,0x03E8,0x4347, 0x8014,0x07D0,0x3031,0x8011,0x07D0,0x3155,0x8012,0x07D0,0x3251, 0x8013,0x07D0,0x4169,0x8010,0x07D0,0x4298,0x8022,0x0FA0,0x3096, 0x8023,0x0FA0,0x3116,0x8024,0x0FA0,0x3196,0x8025,0x0FA0,0x3216, 0x8026,0x0FA0,0x3296,0x8021,0x0FA0,0x332A,0x8029,0x0FA0,0x34B9, 0x8028,0x0FA0,0x3606,0x8020,0x0FA0,0x4148,0x8027,0x0FA0,0x41A6, 0x8031,0x1F40,0x3086,0x8032,0x1F40,0x3186,0x8033,0x1F40,0x3286, 0x8034,0x1F40,0x3599,0x8030,0x1F40,0x4084,0x8035,0x1F40,0x4383, 0x8042,0x3E80,0x3106,0x8043,0x3E80,0x3206,0x8041,0x3E80,0x332B, 0x8040,0x3E80,0x4091,0x8044,0x3E80,0x42E9,0x8045,0x3E80,0x4365, 0x8053,0x5DC0,0x3010,0x8055,0x5DC0,0x3308,0x8050,0x5DC0,0x332C, 0x8051,0x5DC0,0x350E,0x8052,0x5DC0,0x40AD,0x8054,0x5DC0,0x42FF, 0x8062,0x7D00,0x34F6,0x8060,0x7D00,0x3E55,0x8061,0x7D00,0x458F, 0x8072,0x9C40,0x3355,0x8071,0x9C40,0x3638,0x8070,0x9C40,0x36BF, 0x8080,0xBB80,0x419F,0x8081,0xBB80,0x4431,0x8083,0xBB80,0x44F7, 0x8082,0xBB80,0x4714,0x8090,0xDAC0,0x385D,0x80A4,0x1388,0x44B0, 0x80A8,0x1388,0x6F7C}; ----------------------------------- -- Windurst inventory -- {Option,CP,Item} ----------------------------------- WindInv = {0x80A1,0x000A,0x1055,0x8044,0x3E80,0x31BE,0x8025,0x0FA0,0x32B6, 0x80A0,0x0007,0x1056,0x8045,0x3E80,0x323E,0x8027,0x0FA0,0x33A5, 0x80A3,0x2328,0x3CB5,0x8046,0x3E80,0x32BE,0x8028,0x0FA0,0x34B8, 0x80A2,0x09C4,0x3CB6,0x8041,0x3E80,0x332E,0x8026,0x0FA0,0x416B, 0x80A5,0x01F4,0x3D91,0x8047,0x3E80,0x41AA,0x8020,0x0FA0,0x4188, 0x80A6,0x03E8,0x3D92,0x8048,0x3E80,0x4136,0x8033,0x1F40,0x3146, 0x80A7,0x07D0,0x3D93,0x8040,0x3E80,0x42BA,0x8034,0x1F40,0x31C7, 0x8003,0x03E8,0x3273,0x8050,0x5DC0,0x332F,0x8035,0x1F40,0x3246, 0x8002,0x03E8,0x403A,0x8051,0x5DC0,0x350D,0x8036,0x1F40,0x32C6, 0x8001,0x03E8,0x4284,0x8053,0x5DC0,0x41A8,0x8032,0x1F40,0x332D, 0x8004,0x03E8,0x42EA,0x8054,0x5DC0,0x41A9,0x8030,0x1F40,0x404F, 0x8000,0x03E8,0x4307,0x8052,0x5DC0,0x42C6,0x8038,0x1F40,0x411D, 0x8011,0x07D0,0x30C4,0x8061,0x7D00,0x304B,0x8037,0x1F40,0x41A7, 0x8012,0x07D0,0x316D,0x8062,0x7D00,0x34F7,0x8031,0x1F40,0x4382, 0x8013,0x07D0,0x31AF,0x8060,0x7D00,0x3E56,0x8042,0x3E80,0x30BE, 0x8014,0x07D0,0x3237,0x8072,0x9C40,0x3356,0x8043,0x3E80,0x313E, 0x8015,0x07D0,0x32AF,0x8070,0x9C40,0x36C0,0x80A4,0x1388,0x44B1, 0x8016,0x07D0,0x416A,0x8071,0x9C40,0x36C1,0x8024,0x0FA0,0x3236, 0x8017,0x07D0,0x4222,0x8082,0xBB80,0x4464,0x8090,0xDAC0,0x385E, 0x8010,0x07D0,0x42CF,0x8081,0xBB80,0x447A,0x8023,0x0FA0,0x31B6, 0x8021,0x0FA0,0x30B6,0x8083,0xBB80,0x44D1,0x8080,0xBB80,0x46E1, 0x8022,0x0FA0,0x3136,0x80A8,0x1388,0x6F7C}; ----------------------------------- -- Crystal Donate Array -- Conquest Point Required for recharged the ring + charge -- CP Reward for Supply Quest -- TP Fees ----------------------------------- DonateCrys = {4096,4097,4098,4099,4100,4101,4102,4103,4238,4239,4240,4241,4242,4243,4244,4245}; XpRing = {350,700,600}; RingCharg = {7,7,3}; supplyReward = {10,30,40,10,40,10,40,40,70,50,60,40,70,70,70,70,70,70,70}; tpFees = { 100, 100, 150, 100, 150, 100, 100, 150, 350, 400, 150, 250, 300, 500, 250, 350, 500, 0, 300 } ---------------------------------------------------------------- -- function tradeConquestGuard() ----------------------------------------------------------------- function tradeConquestGuard(player,npc,trade,guardnation,guardtype) -- Nation: -- NATION_SANDORIA, NATION_BASTOK, NATION_WINDURST, OTHER(Jeuno) -- Type: 1: city, 2: foreign, 3: outpost, 4: border local myCP = player:getCP(); local item = trade:getItemId(); local AddPoints = 0; if (player:getNation() == guardnation or guardnation == OTHER) then if (guardtype ~= 3 and guardtype ~= 4) then -- all guard can trade crystal except outpost and border. if (item >= 4096 and item <= 4103 or item >= 4238 and item <= 4245) then for Crystal = 1,#DonateCrys,1 do local tcount = trade:getItemQty(DonateCrys[Crystal]) if (tcount > 0 and trade:hasItemQty(DonateCrys[Crystal],tcount)) then if (player:getRank() == 1) then player:showText(npc,CONQUEST - 7); break; elseif (player:getRankPoints() == 4000) then player:showText(npc,CONQUEST + 43); break; elseif (DonateCrys[Crystal] == 4102 or DonateCrys[Crystal] == 4103 or DonateCrys[Crystal] == 4244 or DonateCrys[Crystal] == 4245) then AddPoints = AddPoints + tcount * math.floor(4000 / (player:getRank() * 12 - 16)); else AddPoints = AddPoints + tcount * math.floor(4000 / (player:getRank() * 12 - 12)); end end end if (player:getRank() ~= 1 and player:getRankPoints() < 4000) then if (AddPoints + player:getRankPoints() >= 4000) then newpoint = (AddPoints + player:getRankPoints()) - 4000; player:addCP(newpoint); player:setRankPoints(4000); player:showText(npc,CONQUEST + 44); else --printf("point: %u",AddPoints); player:addRankPoints(AddPoints); player:showText(npc,CONQUEST + 45); end player:tradeComplete(); end end end if (item >= 15761 and item <= 15763) then -- All guard can recharge ring - I can't read number of charge atm if (trade:hasItemQty(item,1) and trade:getItemCount() == 1 and player:getVar("CONQUEST_RING_RECHARGE") < os.time() and (ALLOW_MULTIPLE_EXP_RINGS == 1 or checkConquestRing(player) < 2)) then if (myCP >= XpRing[item - 15760]) then player:delCP(XpRing[item - 15760]); player:tradeComplete(); player:addItem(item); player:setVar("CONQUEST_RING_RECHARGE",getConquestTally()); player:showText(npc,CONQUEST + 58,item,XpRing[item - 15760],RingCharg[(item - 15760)]); else player:showText(npc,CONQUEST + 55,item,XpRing[item - 15760]); end else -- TODO: Verify that message is retail correct. -- This gives feedback on a failure at least, and is grouped with the recharge messages. Confident enough for a commit. player:showText(npc,CONQUEST+56,item); -- "Please be aware that you can only purchase or recharge <item> once during the period between each conquest results tally. end end end end; ------------------------------------------------------------------------- -- function suppliesFresh(player) [NEED COMMAND] 0: delete old supply after weekly conquest tally ------------------------------------------------------------------------- function supplyRunFresh(player) local fresh = player:getVar("supplyQuest_fresh"); local started = player:getVar("supplyQuest_started"); local region = player:getVar("supplyQuest_region"); if ((fresh <= os.time() and (region > 0 or player:hasKeyItem(75))) or started <= 400) then -- Legacy support to remove supplies from the old system, otherwise they'd never go away. return 0; else return 1; end; end; ---------------------------------------------------------------- -- function getArg1(player) ----------------------------------------------------------------- windurst_bastok_ally = 0; sandy_windurst_ally = 0; sandy_bastok_ally = 0; function getArg1(guardnation,player) local pNation = player:getNation(); local output = 0; local signet = 0; if (guardnation == NATION_WINDURST) then output = 33; elseif (guardnation == NATION_SANDORIA) then output = 1; elseif (guardnation == NATION_BASTOK) then output = 17; end if (guardnation == pNation) then signet = 0; elseif (pNation == NATION_WINDURST) then if (guardnation == NATION_BASTOK and windurst_bastok_ally == 1) or (guardnation == NATION_SANDORIA and sandy_windurst_ally == 1) then signet = 1; else signet = 7; end elseif (pNation == NATION_BASTOK) then if (guardnation == NATION_WINDURST and windurst_bastok_ally == 1) or (guardnation == NATION_SANDORIA and sandy_bastok_ally == 1) then signet = 2; else signet = 7; end elseif (pNation == NATION_SANDORIA) then if (guardnation == NATION_WINDURST and sandy_windurst_ally == 1) or (guardnation == NATION_BASTOK and sandy_bastok_ally == 1) then signet = 4; else signet = 7; end end if (guardnation == OTHER) then output = (pNation * 16) + (3 * 256) + 65537; else output = output + 256 * signet; end return output; end; ------------------------------------------------ -- function getExForceAvailable(guardnation,player) Expeditionary Force Menu [NOT IMPLEMENTED] ------------------------------------------------ function getExForceAvailable(guardnation,player) return 0; end; ------------------------------------------------ -- function conquest_ranking() computes part of argument 3 for gate guard events. -- it represents the conquest standing of the 3 nations. Verified. ------------------------------------------------ function conquestRanking() return getNationRank(NATION_SANDORIA) + 4 * getNationRank(NATION_BASTOK) + 16 * getNationRank(NATION_WINDURST); end; ---------------------------------------------------------------- -- function getSupplyAvailable(nation,player) produces the supply quest mask for the nation based on the current conquest standings. ---------------------------------------------------------------- function getSupplyAvailable(nation,player) local mask = 2130706463; if (player:getVar("supplyQuest_started") == vanaDay()) then mask = 4294967295; -- Need to wait 1 vanadiel day end for nb = 0,15 do if (player:hasKeyItem(getSupplyKey(nb))) then mask = -1; -- if you have supply run already activated end end if (player:hasKeyItem(getSupplyKey(18))) then -- we need to skip 16 and 17 for now mask = -1; end if (mask ~= -1 and mask ~= 4294967295) then for i = 0,18 do if (GetRegionOwner(i) ~= nation or i == 16 or (i == 18 and player:hasCompletedMission(COP,DARKNESS_NAMED) == false)) then mask = mask + 2^(i + 5); end end end return mask; end; ---------------------------------------------------------------- -- function getArg6(player) computes argument 6 for gate guard events. This number encodes a player's rank and nationality: -- bits 1-4 encode the rank of the player (verified that bit 4 is part of the rank number so ranks could have gone up to 31.) -- bits 5-6 seem to encode the citizenship as below. This part needs more testing and verification. ----------------------------------------------------------------- function getArg6(player) local output = player:getRank(); local nation = player:getNation(); if (nation == NATION_SANDORIA) then return output; elseif (nation == NATION_BASTOK) then return output + 32; elseif (nation == NATION_WINDURST) then return output + 64; end end; ------------------------------------------------ -- function getRewardExForce(guardnation,player) Expeditionary Force Reward [NOT IMPLEMENTED] ------------------------------------------------ function getRewardExForce(guardnation,player) return 0; end; ------------------------------------------------ -- function getKeySupply(region) ------------------------------------------------ function getSupplyKey(region) if (region <= 9) then return 75 + region; elseif (region == 10) then return 124; elseif (region <= 13) then return 74 + region; elseif (region <= 15) then return 248 + region; elseif (region == 18) then return 620; end end; ----------------------------------------------------------------- -- giltosetHP(player) returns the amount of gil it costs a player to set a homepoint at a foreign outpost/border guard. ----------------------------------------------------------------- function giltosetHP(guardnation,player) local rank = player:getRank(); if (getArg1(guardnation,player) < 0x700) then -- determine ifplayer is in same or allied nation as guard HPgil = 0; else if (rank <= 5) then HPgil = 100 * 2^(rank - 1); else HPgil = 800 * rank - 2400; end end return HPgil; end; ----------------------------------------------------------------- -- function hasOutpost(player, region) returns 1 ifthe player has the outpost of the indicated region under current allegiance. ----------------------------------------------------------------- function hasOutpost(player, region) local nation = player:getNation() local bit = {}; if (nation == NATION_BASTOK) then supply_quests = player:getNationTeleport(NATION_BASTOK); elseif (nation == NATION_SANDORIA) then supply_quests = player:getNationTeleport(NATION_SANDORIA); elseif (nation == NATION_WINDURST) then supply_quests = player:getNationTeleport(NATION_WINDURST); end; for i = 23,5,-1 do twop = 2^i if (supply_quests >= twop) then bit[i]=1; supply_quests = supply_quests - twop; else bit[i]=0; end; --printf("bit %u: %u \n",i,bit[i]); end; return bit[region]; end; ----------------------------------------------------------------- -- function OP_TeleFee(player,region) ----------------------------------------------------------------- function OP_TeleFee(player,region) if (hasOutpost(player, region+5) == 1) then if (GetRegionOwner(region) == player:getNation()) then return tpFees[region + 1]; else return tpFees[region + 1] * 3; end else return 0; end end; ----------------------------------------------------------------- -- Teleport Outpost > Nation ----------------------------------------------------------------- function toHomeNation(player) if (player:getNation() == NATION_BASTOK) then player:setPos(89, 0 , -66, 0, 234); elseif (player:getNation() == NATION_SANDORIA) then player:setPos(49, -1 , 29, 164, 231); else player:setPos(193, -12 , 220, 64, 240); end end; ----------------------------------------------------------------- -- function getTeleAvailable(nation) ----------------------------------------------------------------- function getTeleAvailable(nation) local mask = 2145386527; for i = 5,23 do if (GetRegionOwner(i - 5) ~= nation) then mask = mask + 2^i; end; end return mask; end; --------------------------------- -- Teleport Nation > Outpost --------------------------------- function toOutpost(player,option) -- Coordinates marked {R} have been obtained by packet capture from retail. Don't change them. -- Ronfaure if (option == 5) then player:setPos(-437.688, -20.255, -219.227, 124, 100); -- {R} -- Zulkheim elseif (option == 6) then player:setPos(148.231, -7.975 , 93.479, 154, 103); -- {R} -- Norvallen elseif (option == 7) then player:setPos(62.030, 0.463, -2.025, 67, 104); -- {R} -- Gustaberg elseif (option == 8) then player:setPos(-580.161, 39.578, 62.68, 89, 106); -- {R} -- Derfland elseif (option == 9) then player:setPos(465.820, 23.625, 423.164, 29, 109); -- {R} -- Sarutabaruta elseif (option == 10) then player:setPos(-17.921, -13.335, 318.156, 254, 115); -- {R} -- Kolshushu elseif (option == 11) then player:setPos(-480.237, -30.943, 58.079, 62, 118); -- {R} -- Aragoneu elseif (option == 12) then player:setPos(-297.047, 16.988, 418.026, 225, 119); -- {R} -- Fauregandi elseif (option == 13) then player:setPos(-18.690, -60.048, -109.243, 100, 111); -- {R} -- Valdeaunia elseif (option == 14) then player:setPos(211.210, -24.016, -207.338, 160, 112); -- {R} -- Qufim Island elseif (option == 15) then player:setPos(-243.049, -19.983, 306.712, 71, 126); -- {R} -- Li'Telor elseif (option == 16) then player:setPos(-37.669, 0.419, -141.216, 69, 121); -- {R} -- Kuzotz elseif (option == 17) then player:setPos(-249.983, 7.965, -252.976, 122, 114); -- {R} -- Vollbow elseif (option == 18) then player:setPos(-176.360, 7.624, -63.580, 122, 113); -- {R} -- Elshimo Lowlands elseif (option == 19) then player:setPos(-240.860, -0.031, -388.434, 64, 123); -- {R} -- Elshimo Uplands elseif (option == 20) then player:setPos(207.821, -0.128, -86.623, 159, 124); -- {R} -- Tu'Lia ?! elseif (option == 21) then player:setPos(4, -54, -600, 192, 130); -- Dummied out? -- Tavnazia elseif (option == 23) then player:setPos(-535.861, -7.149, -53.628, 122, 24); -- {R} end; end; ----------------------------------- -- Expeditionary Force -- {Option,Quest,Zone,MenuMask,MinimumLevel,KeyItem} NOT USED ----------------------------------- EXFORCE = {0x20006,ZULK_EF,0x67,0x000040,0x14,ZULKHEIM_EF_INSIGNIA, 0x20007,NORV_EF,0x68,0x000080,0x19,NORVALLEN_EF_INSIGNIA, 0x20009,DERF_EF,0x6D,0x000200,0x19,DERFLAND_EF_INSIGNIA, 0x2000B,KOLS_EF,0x76,0x000800,0x14,KOLSHUSHU_EF_INSIGNIA, 0x2000C,ARAG_EF,0x77,0x001000,0x19,ARAGONEU_EF_INSIGNIA, 0x2000D,FAUR_EF,0x6F,0x002000,0x23,FAUREGANDI_EF_INSIGNIA, 0x2000E,VALD_EF,0x70,0x004000,0x28,VALDEAUNIA_EF_INSIGNIA, 0x2000F,QUFI_EF,0x7E,0x008000,0x19,QUFIM_EF_INSIGNIA, 0x20010,LITE_EF,0x79,0x010000,0x23,LITELOR_EF_INSIGNIA, 0x20011,KUZO_EF,0x72,0x020000,0x28,KUZOTZ_EF_INSIGNIA, 0x20012,VOLL_EF,0x71,0x040000,0x41,VOLLBOW_EF_INSIGNIA, 0x20013,ELLO_EF,0x7B,0x080000,0x23,ELSHIMO_LOWLANDS_EF_INSIGNIA, 0x20014,ELUP_EF,0x7C,0x100000,0x2D,ELSHIMO_UPLANDS_EF_INSIGNIA}; --------------------------------- -- --------------------------------- function getRegionalConquestOverseers(region) switch (region): caseof { --------------------------------- [RONFAURE] = function (x) -- West Ronfaure (100) --------------------------------- --print("RONFAURE"); local Doladepaiton = 17187525; npc = { -- Doladepaiton,NATION_SANDORIA, -- Doladepaiton, R.K. Doladepaiton+7,NATION_SANDORIA, -- Ballie, R.K. Doladepaiton+3,NATION_SANDORIA, -- Flag Doladepaiton+11,NATION_SANDORIA, -- Flag -- Doladepaiton+1,NATION_BASTOK, -- Yoshihiro, I.M. Doladepaiton+8,NATION_BASTOK, -- Molting Moth, I.M. Doladepaiton+4,NATION_BASTOK, -- Flag Doladepaiton+13,NATION_BASTOK, -- Flag -- Doladepaiton+2,NATION_WINDURST, -- Kyanta-Pakyanta, W.W. Doladepaiton+9,NATION_WINDURST, -- Tottoto, W.W. Doladepaiton+5,NATION_WINDURST, -- Flag Doladepaiton+13,NATION_WINDURST, -- Flag -- Doladepaiton+6,BEASTMEN, -- Flag Doladepaiton+14,BEASTMEN, -- Flag -- Doladepaiton+10,OTHER, -- Harvetour } end, --------------------------------- [ZULKHEIM] = function (x) -- Valkurm_Dunes (103) --------------------------------- --print("ZULKHEIM"); local Quanteilleron = 17199709; npc = { -- Quanteilleron,NATION_SANDORIA, -- Quanteilleron, R.K. Quanteilleron+7,NATION_SANDORIA, -- Prunilla, R.K. Quanteilleron+3,NATION_SANDORIA, -- flag Quanteilleron+11,NATION_SANDORIA, -- flag -- Quanteilleron+1,NATION_BASTOK, -- Tsunashige, I.M. Quanteilleron+8,NATION_BASTOK, -- Fighting Ant, I.M. Quanteilleron+4,NATION_BASTOK, -- flag Quanteilleron+12,NATION_BASTOK, -- flag -- Quanteilleron+2,NATION_WINDURST, -- Nyata-Mobuta, W.W. Quanteilleron+9,NATION_WINDURST, -- Tebubu, W.W. Quanteilleron+5,NATION_WINDURST, -- flag Quanteilleron+13,NATION_WINDURST, -- flag -- Quanteilleron+6,BEASTMEN, -- flag Quanteilleron+14,BEASTMEN, -- flag -- Quanteilleron+10,OTHER, -- Medicine Axe } end, --------------------------------- [NORVALLEN] = function (x) -- Jugner_Forest (104) --------------------------------- --print("NORVALLEN"); local Chaplion = 17203848; npc = { -- Chaplion,NATION_SANDORIA, -- Chaplion, R.K. Chaplion+7,NATION_SANDORIA, -- Taumiale, R.K. Chaplion+3,NATION_SANDORIA, -- flag Chaplion+11,NATION_SANDORIA, -- flag -- Chaplion+1,NATION_BASTOK, -- Takamoto, I.M. Chaplion+8,NATION_BASTOK, -- Pure Heart, I.M. Chaplion+4,NATION_BASTOK, -- flag Chaplion+12,NATION_BASTOK, -- flag -- Chaplion+2,NATION_WINDURST, -- Bubchu-Bibinchu, W.W. Chaplion+9,NATION_WINDURST, -- Geruru, W.W. Chaplion+5,NATION_WINDURST, -- flag Chaplion+13,NATION_WINDURST, -- flag -- Chaplion+6,BEASTMEN, -- flag Chaplion+14,BEASTMEN, -- flag -- Chaplion+10,OTHER, -- Mionie } end, --------------------------------- [GUSTABERG] = function (x) -- North_Gustaberg (106) --------------------------------- --print("GUSTABERG"); local Ennigreaud = 17212060; npc = { -- Ennigreaud,NATION_SANDORIA, -- Ennigreaud, R.K. Ennigreaud+7,NATION_SANDORIA, -- Quellebie, R.K. Ennigreaud+3,NATION_SANDORIA, -- flag Ennigreaud+11,NATION_SANDORIA, -- flag -- Ennigreaud+1,NATION_BASTOK, -- Shigezane, I.M. Ennigreaud+8,NATION_BASTOK, -- Heavy Fog, I.M. Ennigreaud+4,NATION_BASTOK, -- flag Ennigreaud+12,NATION_BASTOK, -- flag -- Ennigreaud+2,NATION_WINDURST, -- Kuuwari-Aori, W.W. Ennigreaud+9,NATION_WINDURST, -- Butsutsu, W.W. Ennigreaud+5,NATION_WINDURST, -- flag Ennigreaud+13,NATION_WINDURST, -- flag -- Ennigreaud+6,BEASTMEN, -- flag Ennigreaud+14,BEASTMEN, -- flag -- Ennigreaud+10,OTHER, -- Kuleo } end, --------------------------------- [DERFLAND] = function (x) -- Pashhow_Marshlands (109) --------------------------------- --print("DERFLAND"); local Mesachedeau = 17224326; npc = { -- Mesachedeau,NATION_SANDORIA, -- Mesachedeau, R.K. Mesachedeau+7,NATION_SANDORIA, -- Ioupie, R.K. Mesachedeau+3,NATION_SANDORIA, -- flag Mesachedeau+11,NATION_SANDORIA, -- flag -- Mesachedeau+1,NATION_BASTOK, -- Souun, I.M. Mesachedeau+8,NATION_BASTOK, -- Sharp Tooth, I.M. Mesachedeau+4,NATION_BASTOK, -- flag Mesachedeau+12,NATION_BASTOK, -- flag -- Mesachedeau+2,NATION_WINDURST, -- Mokto-Lankto, W.W. Mesachedeau+9,NATION_WINDURST, -- Shikoko, W.W. Mesachedeau+5,NATION_WINDURST, -- flag Mesachedeau+13,NATION_WINDURST, -- flag -- Mesachedeau+6,BEASTMEN, -- flag Mesachedeau+14,BEASTMEN, -- flag -- Mesachedeau+10,OTHER, -- Tahmasp } end, --------------------------------- [SARUTABARUTA] = function (x) -- West_Sarutabaruta (115) --------------------------------- --print("SARUTABARUTA"); local Naguipeillont = 17248825; npc = { -- Naguipeillont,NATION_SANDORIA, -- Naguipeillont, R.K. Naguipeillont+7,NATION_SANDORIA, -- Banege, R.K. Naguipeillont+3,NATION_SANDORIA, -- flag Naguipeillont+11,NATION_SANDORIA, -- flag -- Naguipeillont+1,NATION_BASTOK, -- Ryokei, I.M. Naguipeillont+8,NATION_BASTOK, -- Slow Axe, I.M. Naguipeillont+4,NATION_BASTOK, -- flag Naguipeillont+12,NATION_BASTOK, -- flag -- Naguipeillont+2,NATION_WINDURST, -- Roshina-Kuleshuna, W.W. Naguipeillont+9,NATION_WINDURST, -- Darumomo, W.W. Naguipeillont+5,NATION_WINDURST, -- flag Naguipeillont+13,NATION_WINDURST, -- flag -- Naguipeillont+6,BEASTMEN, -- flag Naguipeillont+14,BEASTMEN, -- flag -- Naguipeillont+10,OTHER, -- Mahien-Uhien } end, --------------------------------- [KOLSHUSHU] = function (x) -- Buburimu_Peninsula (118) --------------------------------- --print("KOLSHUSHU"); local Bonbavour = 17261143; npc = { -- Bonbavour,NATION_SANDORIA, -- Bonbavour, R.K. Bonbavour+7,NATION_SANDORIA, -- Craigine, R.K. Bonbavour+3,NATION_SANDORIA, -- flag Bonbavour+11,NATION_SANDORIA, -- flag -- Bonbavour+1,NATION_BASTOK, -- Ishin, I.M. Bonbavour+8,NATION_BASTOK, -- Wise Turtle, I.M. Bonbavour+4,NATION_BASTOK, -- flag Bonbavour+12,NATION_BASTOK, -- flag -- Bonbavour+2,NATION_WINDURST, -- Ganemu-Punnemu, W.W. Bonbavour+9,NATION_WINDURST, -- Mashasha, W.W. Bonbavour+5,NATION_WINDURST, -- flag Bonbavour+13,NATION_WINDURST, -- flag -- Bonbavour+6,BEASTMEN, -- flag Bonbavour+14,BEASTMEN, -- flag -- Bonbavour+10,OTHER, -- Lobho Ukipturi } end, --------------------------------- [ARAGONEU] = function (x) -- Meriphataud_Mountains (119) --------------------------------- --print("ARAGONEU"); local Chegourt = 17265271; npc = { -- Chegourt,NATION_SANDORIA, -- Chegourt, R.K. Chegourt+7,NATION_SANDORIA, -- Buliame, R.K. Chegourt+3,NATION_SANDORIA, -- flag Chegourt+11,NATION_SANDORIA, -- flag -- Chegourt+1,NATION_BASTOK, -- Akane, I.M. Chegourt+8,NATION_BASTOK, -- Three Steps, I.M. Chegourt+4,NATION_BASTOK, -- flag Chegourt+12,NATION_BASTOK, -- flag -- Chegourt+2,NATION_WINDURST, -- Donmo-Boronmo, W.W. Chegourt+9,NATION_WINDURST, -- Daruru, W.W. Chegourt+5,NATION_WINDURST, -- flag Chegourt+13,NATION_WINDURST, -- flag -- Chegourt+6,BEASTMEN, -- flag Chegourt+14,BEASTMEN, -- flag -- Chegourt+10,OTHER, -- Mushosho } end, --------------------------------- [FAUREGANDI] = function (x) -- Beaucedine_Glacier (111) --------------------------------- --print("FAUREGANDI"); local Parledaire = 17232209; npc = { -- Parledaire,NATION_SANDORIA, -- Parledaire, R.K. Parledaire+7,NATION_SANDORIA, -- Leaufetie, R.K. Parledaire+3,NATION_SANDORIA, -- flag Parledaire+11,NATION_SANDORIA, -- flag -- Parledaire+1,NATION_BASTOK, -- Akane, I.M. Parledaire+8,NATION_BASTOK, -- Rattling Rain, I.M. Parledaire+4,NATION_BASTOK, -- flag Parledaire+12,NATION_BASTOK, -- flag -- Parledaire+2,NATION_WINDURST, -- Ryunchi-Pauchi, W.W. Parledaire+9,NATION_WINDURST, -- Chopapa, W.W. Parledaire+5,NATION_WINDURST, -- flag Parledaire+13,NATION_WINDURST, -- flag -- Parledaire+6,BEASTMEN, -- flag Parledaire+14,BEASTMEN, -- flag -- Parledaire+10,OTHER, -- Gueriette } end, --------------------------------- [VALDEAUNIA] = function (x) -- Xarcabard (112) --------------------------------- --print("VALDEAUNIA"); local Jeantelas = 17236290; npc = { -- Jeantelas,NATION_SANDORIA, -- Jeantelas, R.K. Jeantelas+7,NATION_SANDORIA, -- Pilcha, R.K. Jeantelas+3,NATION_SANDORIA, -- flag Jeantelas+11,NATION_SANDORIA, -- flag -- Jeantelas+1,NATION_BASTOK, -- Kaya, I.M. Jeantelas+8,NATION_BASTOK, -- Heavy Bear, I.M. Jeantelas+4,NATION_BASTOK, -- flag Jeantelas+12,NATION_BASTOK, -- flag -- Jeantelas+2,NATION_WINDURST, -- Magumo-Yagimo, W.W. Jeantelas+9,NATION_WINDURST, -- Tememe, W.W. Jeantelas+5,NATION_WINDURST, -- flag Jeantelas+13,NATION_WINDURST, -- flag -- Jeantelas+6,BEASTMEN, -- flag Jeantelas+14,BEASTMEN, -- flag -- Jeantelas+10,OTHER, -- Pelogrant } end, --------------------------------- [QUFIMISLAND] = function (x) -- Qufim_Island (126) --------------------------------- --print("QUFIMISLAND"); local Pitoire = 17293716; npc = { -- Pitoire,NATION_SANDORIA, -- Pitoire, R.K. Pitoire+7,NATION_SANDORIA, -- Matica, R.K. Pitoire+3,NATION_SANDORIA, -- flag Pitoire+11,NATION_SANDORIA, -- flag -- Pitoire+1,NATION_BASTOK, -- Sasa, I.M. Pitoire+8,NATION_BASTOK, -- Singing Blade, I.M. Pitoire+4,NATION_BASTOK, -- flag Pitoire+12,NATION_BASTOK, -- flag -- Pitoire+2,NATION_WINDURST, -- Tsonga-Hoponga, W.W. Pitoire+9,NATION_WINDURST, -- Numumu, W.W. Pitoire+5,NATION_WINDURST, -- flag Pitoire+13,NATION_WINDURST, -- flag -- Pitoire+6,BEASTMEN, -- flag Pitoire+14,BEASTMEN, -- flag -- Pitoire+10,OTHER, -- Jiwon } end, --------------------------------- [LITELOR] = function (x) -- The_Sanctuary_of_ZiTah (121) --------------------------------- --print("LITELOR"); local Credaurion = 17273365; npc = { -- Credaurion,NATION_SANDORIA, -- Credaurion, R.K. Credaurion+7,NATION_SANDORIA, -- Limion, R.K. Credaurion+3,NATION_SANDORIA, -- flag Credaurion+11,NATION_SANDORIA, -- flag -- Credaurion+1,NATION_BASTOK, -- Calliope, I.M. Credaurion+8,NATION_BASTOK, -- Dedden, I.M. Credaurion+4,NATION_BASTOK, -- flag Credaurion+12,NATION_BASTOK, -- flag -- Credaurion+2,NATION_WINDURST, -- Ajimo-Majimo, W.W. Credaurion+9,NATION_WINDURST, -- Ochocho, W.W. Credaurion+5,NATION_WINDURST, -- flag Credaurion+13,NATION_WINDURST, -- flag -- Credaurion+6,BEASTMEN, -- flag Credaurion+14,BEASTMEN, -- flag -- Credaurion+10,OTHER, -- Kasim } end, --------------------------------- [KUZOTZ] = function (x) -- Eastern_Altepa_Desert (114) --------------------------------- --print("KUZOTZ"); local Eaulevisat = 17244627; npc = { -- Eaulevisat,NATION_SANDORIA, -- Eaulevisat, R.K. Eaulevisat+7,NATION_SANDORIA, -- Laimeve, R.K. Eaulevisat+3,NATION_SANDORIA, -- flag Eaulevisat+11,NATION_SANDORIA, -- flag -- Eaulevisat+1,NATION_BASTOK, -- Lindgard, I.M. Eaulevisat+8,NATION_BASTOK, -- Daborn, I.M. Eaulevisat+4,NATION_BASTOK, -- flag Eaulevisat+12,NATION_BASTOK, -- flag -- Eaulevisat+2,NATION_WINDURST, -- Variko-Njariko, W.W. Eaulevisat+9,NATION_WINDURST, -- Sahgygy, W.W. Eaulevisat+5,NATION_WINDURST, -- flag Eaulevisat+13,NATION_WINDURST, -- flag -- Eaulevisat+6,BEASTMEN, -- flag Eaulevisat+14,BEASTMEN, -- flag -- Eaulevisat+10,OTHER, -- Sowande } end, --------------------------------- [VOLLBOW] = function (x) -- Cape_Teriggan (113) --------------------------------- --print("VOLLBOW"); local Salimardi = 17240472; npc = { -- Salimardi,NATION_SANDORIA, -- Salimardi, R.K. Salimardi+7,NATION_SANDORIA, -- Paise, R.K. Salimardi+3,NATION_SANDORIA, -- flag Salimardi+11,NATION_SANDORIA, -- flag -- Salimardi+1,NATION_BASTOK, -- Sarmistha, I.M. Salimardi+8,NATION_BASTOK, -- Dultwa, I.M. Salimardi+4,NATION_BASTOK, -- flag Salimardi+12,NATION_BASTOK, -- flag -- Salimardi+2,NATION_WINDURST, -- Voranbo-Natanbo, W.W. Salimardi+9,NATION_WINDURST, -- Orukeke, W.W. Salimardi+5,NATION_WINDURST, -- flag Salimardi+13,NATION_WINDURST, -- flag -- Salimardi+6,BEASTMEN, -- flag Salimardi+14,BEASTMEN, -- flag -- Salimardi+10,OTHER, -- Bright Moon } end, --------------------------------- [ELSHIMOLOWLANDS] = function (x) -- Yuhtunga_Jungle (123) --------------------------------- --print("ELSHIMOLOWLANDS"); local Zorchorevi = 17281600; npc = { -- Zorchorevi,NATION_SANDORIA, -- Zorchorevi, R.K. Zorchorevi+7,NATION_SANDORIA, -- Mupia, R.K. Zorchorevi+3,NATION_SANDORIA, -- flag Zorchorevi+11,NATION_SANDORIA, -- flag -- Zorchorevi+1,NATION_BASTOK, -- Mahol, I.M. Zorchorevi+8,NATION_BASTOK, -- Bammiro, I.M. Zorchorevi+4,NATION_BASTOK, -- flag Zorchorevi+12,NATION_BASTOK, -- flag -- Zorchorevi+2,NATION_WINDURST, -- Uphra-Kophra, W.W. Zorchorevi+9,NATION_WINDURST, -- Richacha, W.W. Zorchorevi+5,NATION_WINDURST, -- flag Zorchorevi+13,NATION_WINDURST, -- flag -- Zorchorevi+6,BEASTMEN, -- flag Zorchorevi+14,BEASTMEN, -- flag -- Zorchorevi+10,OTHER, -- Robino-Mobino } end, --------------------------------- [ELSHIMOUPLANDS] = function (x) -- Yhoator_Jungle (124) --------------------------------- --print("ELSHIMOUPLANDS"); local Ilieumort = 17285650; npc ={ -- Ilieumort,NATION_SANDORIA, -- Ilieumort, R.K. Ilieumort+7,NATION_SANDORIA, -- Emila, R.K. Ilieumort+3,NATION_SANDORIA, -- flag Ilieumort+11,NATION_SANDORIA, -- flag -- Ilieumort+1,NATION_BASTOK, -- Mintoo, I.M. Ilieumort+8,NATION_BASTOK, -- Guddal, I.M. Ilieumort+4,NATION_BASTOK, -- flag Ilieumort+12,NATION_BASTOK, -- flag -- Ilieumort+2,NATION_WINDURST, -- Etaj-Pohtaj, W.W. Ilieumort+9,NATION_WINDURST, -- Ghantata, W.W. Ilieumort+5,NATION_WINDURST, -- flag Ilieumort+13,NATION_WINDURST, -- flag -- Ilieumort+6,BEASTMEN, -- flag Ilieumort+14,BEASTMEN, -- flag -- Ilieumort+10,OTHER, -- Mugha Dovajaiho } end, --------------------------------- [TULIA] = function (x) -- RuAun_Gardens (130) --------------------------------- --print("TULIA"); local RuAun_Banner = 17310080; npc = { -- RuAun_Banner,NATION_SANDORIA, -- flag -- RuAun_Banner+1,NATION_BASTOK, -- flag -- RuAun_Banner+2,NATION_WINDURST, -- flag -- RuAun_Banner+3,BEASTMEN, -- flag } end, --------------------------------- [MOVALPOLOS] = function (x) -- Oldton_Movalpolos --------------------------------- --print("MOVALPOLOS"); local Oldton_Banner_Offset = 16822509; npc = { -- Oldton_Banner_Offset,NATION_SANDORIA, -- flag -- Oldton_Banner_Offset+1,NATION_BASTOK, -- flag -- Oldton_Banner_Offset+2,NATION_WINDURST, -- flag -- Oldton_Banner_Offset+3,BEASTMEN, -- flag } end, --------------------------------- [TAVNAZIANARCH] = function (x) -- Lufaise_Meadows --------------------------------- --print("TAVNAZIA"); local Jemmoquel = 16875865; npc = { -- Jemmoquel,NATION_SANDORIA, -- Jemmoquel, R.K. Jemmoquel+7,NATION_SANDORIA, -- Chilaumme, R.K. Jemmoquel+3,NATION_SANDORIA, -- flag Jemmoquel+11,NATION_SANDORIA, -- flag -- Jemmoquel+1,NATION_BASTOK, -- Yoram, I.M. Jemmoquel+8,NATION_BASTOK, -- Ghost Talker, I.M. Jemmoquel+4,NATION_BASTOK, -- flag Jemmoquel+12,NATION_BASTOK, -- flag -- Jemmoquel+2,NATION_WINDURST, -- Teldo-Moroldo, W.W. Jemmoquel+9,NATION_WINDURST, -- Cotete, W.W. Jemmoquel+5,NATION_WINDURST, -- flag Jemmoquel+13,NATION_WINDURST, -- flag -- Jemmoquel+6,BEASTMEN, -- flag Jemmoquel+14,BEASTMEN, -- flag -- Jemmoquel+10,OTHER, -- Jersey } end, } return npc; end; ----------------------------------- -- ----------------------------------- function SetRegionalConquestOverseers(region) local npclist = getRegionalConquestOverseers(region); local nation = GetRegionOwner(region); for i = 1, #npclist, 2 do local npc = GetNPCByID(npclist[i]); if (npc ~= nil) then if (npclist[i+1] == nation) then npc:setStatus(0); else npc:setStatus(2); end if (npclist[i+1] == OTHER) then if (nation ~= BEASTMEN) then npc:setStatus(0); else npc:setStatus(2); end end end end end; ----------------------------------- -- checkConquestRing ----------------------------------- function checkConquestRing(player) local count = 0; -- If not enabled by admin, do a count on Chariot, Empress, and Emperor Band if (ALLOW_MULTIPLE_EXP_RINGS ~= 1) then for i=15761,15763 do if (player:hasItem(i) == true) then count = count + 1; end end end -- One exp ring purchasable per conquest tally if (BYPASS_EXP_RING_ONE_PER_WEEK ~= 1 and player:getVar("CONQUEST_RING_TIMER") > os.time()) then count = 3; end return count; end; ----------------------------------- -- conquestUpdate ----------------------------------- function conquestUpdate(zone, player, updateType, messageBase) local ranking = getConquestBalance(); if (updateType == CONQUEST_TALLY_START) then player:messageText(player, messageBase, 5); elseif (updateType == CONQUEST_TALLY_END) then --Tallying conquest results... player:messageText(player, messageBase+1, 5); -- This region is currently under x control. local owner = GetRegionOwner(zone:getRegionID()); if (owner <= 3) then player:messageText(player, messageBase+2+owner, 5); else player:messageText(player, messageBase+6, 5); end local offset = 0; if (bit.band(ranking, 0x03) == 0x01) then offset = offset + 7; -- 7 if (bit.band(ranking, 0x30) == 0x10) then offset = offset + 1; -- 8 if (bit.band(ranking, 0x0C) == 0x0C) then offset = offset + 1; -- 9 end elseif (bit.band(ranking, 0x0C) == 0x08) then offset = offset + 3; -- 10 if (bit.band(ranking, 0x30) == 0x30) then offset = offset + 1; -- 11 end elseif (bit.band(ranking, 0x0C) == 0x04) then offset = offset + 6; -- 13 end elseif (bit.band(ranking, 0x0C) == 0x04) then offset = offset + 15; -- 15 if (bit.band(ranking, 0x30) == 0x02) then offset = offset + 3; -- 18 if (bit.band(ranking, 0x03) == 0x03) then offset = offset + 1; -- 19 end elseif (bit.band(ranking, 0x30) == 0x10) then offset = offset + 6; -- 21 end elseif (bit.band(ranking, 0x30) == 0x10) then offset = offset + 23; -- 23 if (bit.band(ranking, 0x0C) == 0x08) then offset = offset + 3; -- 26 if (bit.band(ranking, 0x30) == 0x30) then offset = offset + 1; -- 27 end end end -- Global balance of power: player:messageText(player, messageBase+offset, 5); if (isConquestAlliance()) then -- have formed an alliance. if (bit.band(ranking, 0x03) == 0x01) then player:messageText(player, messageBase+50, 5); elseif (bit.band(ranking, 0x0C) == 0x04) then player:messageText(player, messageBase+51, 5); elseif (bit.band(ranking, 0x30) == 0x10) then player:messageText(player, messageBase+52, 5); end end elseif (updateType == CONQUEST_UPDATE) then -- Conquest update: This region is currently under x control. local owner = GetRegionOwner(zone:getRegionID()); if (owner <= 3) then player:messageText(player, messageBase+32+owner, 5); else player:messageText(player, messageBase+31, 5); end local influence = GetRegionInfluence(zone:getRegionID()); if (influence >= 64) then -- The beastmen are on the rise. player:messageText(player, messageBase+37, 5); elseif (influence == 0) then -- All three nations are at a deadlock. player:messageText(player, messageBase+36, 5); else local sandoria = bit.band(influence, 0x03); local bastok = bit.rshift(bit.band(influence, 0x0C),2); local windurst = bit.rshift(bit.band(influence, 0x30),4); -- Regional influence: San d'Oria player:messageText(player, messageBase+41 - sandoria, 5); -- Bastok player:messageText(player, messageBase+45 - bastok, 5); -- Windurst player:messageText(player, messageBase+49 - windurst, 5); end if (isConquestAlliance()) then --are currently allied. if (bit.band(ranking, 0x03) == 0x01) then player:messageText(player, messageBase+53, 5); elseif (bit.band(ranking, 0x0C) == 0x04) then player:messageText(player, messageBase+54, 5); elseif (bit.band(ranking, 0x30) == 0x10) then player:messageText(player, messageBase+55, 5); end end end end;
gpl-3.0
ddumont/darkstar
scripts/zones/Western_Adoulin/npcs/Marjoirelle.lua
14
1308
----------------------------------- -- Area: Western Adoulin -- NPC: Majoirelle -- Type: Standard NPC and Quest NPC -- Involved With Quest: 'Order Up' -- @zone 256 -- @pos 127 4 -81 ----------------------------------- require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Order_Up = player:getQuestStatus(ADOULIN, ORDER_UP); local Order_Marjoirelle = player:getMaskBit(player:getVar("Order_Up_NPCs"), 8); if ((Order_Up == QUEST_ACCEPTED) and (not Order_Marjoirelle)) then -- Progresses Quest: 'Order Up' player:startEvent(0x0044); else -- Standard Dialogue player:startEvent(0x021A); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x0044) then -- Progresses Quest: 'Order Up' player:setMaskBit("Order_Up_NPCs", 8, true); end end;
gpl-3.0
ddumont/darkstar
scripts/globals/items/bibiki_slug.lua
12
1424
----------------------------------------- -- ID: 5122 -- Item: Bibiki Slug -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -5 -- Vitality 4 -- defense % 16 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5122); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, -5); target:addMod(MOD_VIT, 4); target:addMod(MOD_DEFP, 16); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, -5); target:delMod(MOD_VIT, 4); target:delMod(MOD_DEFP, 16); end;
gpl-3.0
roysc/awesome
lib/beautiful/xresources.lua
2
2592
---------------------------------------------------------------------------- --- Library for getting xrdb data. -- -- @author Yauhen Kirylau &lt;yawghen@gmail.com&gt; -- @copyright 2015 Yauhen Kirylau -- @release @AWESOME_VERSION@ -- @module beautiful.xresources ---------------------------------------------------------------------------- -- Grab environment local print = print local awesome = awesome local xresources = {} local fallback = { --black color0 = '#000000', color8 = '#465457', --red color1 = '#cb1578', color9 = '#dc5e86', --green color2 = '#8ecb15', color10 = '#9edc60', --yellow color3 = '#cb9a15', color11 = '#dcb65e', --blue color4 = '#6f15cb', color12 = '#7e5edc', --purple color5 = '#cb15c9', color13 = '#b75edc', --cyan color6 = '#15b4cb', color14 = '#5edcb4', --white color7 = '#888a85', color15 = '#ffffff', -- background = '#0e0021', foreground = '#bcbcbc', } --- Get current base colorscheme from xrdb. -- @treturn table Color table with keys 'background', 'foreground' and 'color0'..'color15' function xresources.get_current_theme() local keys = { 'background', 'foreground' } for i=0,15 do table.insert(keys, "color"..i) end local colors = {} for _, key in ipairs(keys) do colors[key] = awesome.xrdb_get_value("", key) if not colors[key] then print("W: beautiful: can't get colorscheme from xrdb (using fallback).") return fallback end end return colors end local dpi_per_screen = {} --- Get global or per-screen DPI value falling back to xrdb. -- @tparam[opt=focused] integer s The screen. -- @treturn number DPI value. function xresources.get_dpi(s) if dpi_per_screen[s] then return dpi_per_screen[s] end if not xresources.dpi then xresources.dpi = tonumber(awesome.xrdb_get_value("", "Xft.dpi") or 96) end return xresources.dpi end --- Set DPI for a given screen (defaults to global). -- @tparam number dpi DPI value. -- @tparam[opt] integer s Screen. function xresources.set_dpi(dpi, s) if not s then xresources.dpi = dpi else dpi_per_screen[s] = dpi end end --- Compute resulting size applying current DPI value (optionally per screen). -- @tparam number size Size -- @tparam[opt] integer s The screen. -- @treturn integer Resulting size (using `math.ceil`). function xresources.apply_dpi(size, s) return math.ceil(size/96*xresources.get_dpi(s)) end return xresources -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
smartdevicelink/sdl_atf_test_scripts
test_scripts/Policies/Validation_of_PolicyTables/267_ATF_pt_update_validation_rules_required_parameters_type.lua
1
14588
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] At least one required param has invalid type -- -- Check SDL behavior in case required parameter ith invalid type in received PTU -- 1. Used preconditions: -- Do not start default SDL -- Prepare PTU file with with one required field with invalid type -- Start SDL -- InitHMI register MobileApp -- Perform PT update -- -- 2. Performed steps: -- Check LocalPT changes -- -- Expected result: -- SDL must invalidate this received PolicyTableUpdated and log corresponding error internally --------------------------------------------------------------------------------------------- require('user_modules/script_runner').isTestApplicable({ { extendedPolicy = { "EXTERNAL_PROPRIETARY" } } }) --[[ Required Shared libraries ]] local json = require("modules/json") local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local commonSteps = require ('user_modules/shared_testcases/commonSteps') local testCasesForPolicySDLErrorsStops = require ('user_modules/shared_testcases/testCasesForPolicySDLErrorsStops') local utils = require ('user_modules/utils') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --[[ General configuration parameters ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') config.defaultProtocolVersion = 2 --[[ Local Variables ]] --local basePtuFile = "files/ptu.json" local ptuAppRegistered = "files/ptu_app.json" local PRELOADED_PT_FILE_NAME = "sdl_preloaded_pt.json" local HMIAppId local TESTED_DATA = { preloaded = { policy_table = { module_config = { exchange_after_x_ignition_cycles = 200 } } }, update = { policy_table = { module_config = { exchange_after_x_ignition_cycles = "string" } } } } local TestData = { path = config.pathToSDL .. "TestData", isExist = false, init = function(self) if not self.isExist then os.execute("mkdir ".. self.path) os.execute("echo 'List test data files files:' > " .. self.path .. "/index.txt") self.isExist = true end end, store = function(self, message, pathToFile, fileName) if self.isExist then local dataToWrite = message if pathToFile and fileName then os.execute(table.concat({"cp ", pathToFile, " ", self.path, "/", fileName})) dataToWrite = table.concat({dataToWrite, " File: ", fileName}) end dataToWrite = dataToWrite .. "\n" local file = io.open(self.path .. "/index.txt", "a+") file:write(dataToWrite) file:close() end end, delete = function(self) if self.isExist then os.execute("rm -r -f " .. self.path) self.isExist = false end end, info = function(self) if self.isExist then commonFunctions:userPrint(35, "All test data generated by this test were stored to folder: " .. self.path) else commonFunctions:userPrint(35, "No test data were stored" ) end end } --[[ Local Functions ]] -- local function addApplicationToPTJsonFile(basicFile, newPtFile, appName, app) -- local pt = io.open(basicFile, "r") -- if pt == nil then -- error("PTU file not found") -- end -- local ptString = pt:read("*all") -- pt:close() -- local ptTable = json.decode(ptString) -- ptTable["policy_table"]["app_policies"][appName] = app -- -- Workaround. null value in lua table == not existing value. But in json file it has to be -- ptTable["policy_table"]["functional_groupings"]["DataConsent-2"]["rpcs"] = "tobedeletedinjsonfile" -- local ptJson = json.encode(ptTable) -- ptJson = string.gsub(ptJson, "\"tobedeletedinjsonfile\"", "null") -- local newPtu = io.open(newPtFile, "w") -- newPtu:write(ptJson) -- newPtu:close() -- end local function activateAppInSpecificLevel(self, HMIAppID, hmi_level) local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = HMIAppID, level = hmi_level}) --hmi side: expect SDL.ActivateApp response EXPECT_HMIRESPONSE(RequestId) :Do(function(_,data) --In case when app is not allowed, it is needed to allow app if data.result.isSDLAllowed ~= true then --hmi side: sending SDL.GetUserFriendlyMessage request RequestId = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}}) EXPECT_HMIRESPONSE(RequestId) :Do(function(_,_) --hmi side: send request SDL.OnAllowSDLFunctionality self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = utils.getDeviceMAC(), name = utils.getDeviceName()}}) --hmi side: expect BasicCommunication.ActivateApp request EXPECT_HMICALL("BasicCommunication.ActivateApp") :Do(function(_,data2) --hmi side: sending BasicCommunication.ActivateApp response self.hmiConnection:SendResponse(data2.id,"BasicCommunication.ActivateApp", "SUCCESS", {}) end) -- :Times() end) EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = hmi_level, systemContext = "MAIN" }) end end) end function Test:updatePolicyInDifferentSessions(_, appName, mobileSession) local iappID = self.applications[appName] local requestId = self.hmiConnection:SendRequest("SDL.GetPolicyConfigurationData", { policyType = "module_config", property = "endpoints" }) EXPECT_HMIRESPONSE(requestId) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"} ) mobileSession:ExpectNotification("OnSystemRequest", { requestType = "PROPRIETARY" }) :Do(function(_,_) local CorIdSystemRequest = mobileSession:SendRPC("SystemRequest", { fileName = "PolicyTableUpdate", requestType = "PROPRIETARY", appID = iappID }, "files/jsons/Policies/PTU_ValidationRules/PTU_invalid_required.json") local systemRequestId EXPECT_HMICALL("BasicCommunication.SystemRequest") :Do(function(_,_data1) systemRequestId = _data1.id self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate", { policyfile = "/tmp/fs/mp/images/ivsu_cache/PolicyTableUpdate"} ) local function to_run() self.hmiConnection:SendResponse(systemRequestId,"BasicCommunication.SystemRequest", "SUCCESS", {}) end RUN_AFTER(to_run, 500) end) mobileSession:ExpectResponse(CorIdSystemRequest, { success = true, resultCode = "SUCCESS"}) end) end) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}) end local function constructPathToDatabase() if commonSteps:file_exists(config.pathToSDL .. "storage/policy.sqlite") then return config.pathToSDL .. "storage/policy.sqlite" elseif commonSteps:file_exists(config.pathToSDL .. "policy.sqlite") then return config.pathToSDL .. "policy.sqlite" else commonFunctions:userPrint(31, "policy.sqlite is not found" ) return nil end end local function executeSqliteQuery(rawQueryString, dbFilePath) if not dbFilePath then return nil end local queryExecutionResult = {} local queryString = table.concat({"sqlite3 ", dbFilePath, " '", rawQueryString, "'"}) local file = io.popen(queryString, 'r') if file then local index = 1 for line in file:lines() do queryExecutionResult[index] = line index = index + 1 end file:close() return queryExecutionResult else return nil end end local function isValuesCorrect(actualValues, expectedValues) if #actualValues ~= #expectedValues then return false end local tmpExpectedValues = {} for i = 1, #expectedValues do tmpExpectedValues[i] = expectedValues[i] end local isFound for j = 1, #actualValues do isFound = false for key, value in pairs(tmpExpectedValues) do if value == actualValues[j] then isFound = true tmpExpectedValues[key] = nil break end end if not isFound then return false end end if next(tmpExpectedValues) then return false end return true end function Test.checkLocalPT(checkTable) local expectedLocalPtValues local queryString local actualLocalPtValues local comparationResult local isTestPass = true for _, check in pairs(checkTable) do expectedLocalPtValues = check.expectedValues queryString = check.query actualLocalPtValues = executeSqliteQuery(queryString, constructPathToDatabase()) if actualLocalPtValues then comparationResult = isValuesCorrect(actualLocalPtValues, expectedLocalPtValues) if not comparationResult then TestData:store(table.concat({"Test ", queryString, " failed: SDL has wrong values in LocalPT"})) TestData:store("ExpectedLocalPtValues") commonFunctions:userPrint(31, table.concat({"Test ", queryString, " failed: SDL has wrong values in LocalPT"})) commonFunctions:userPrint(35, "ExpectedLocalPtValues") for _, values in pairs(expectedLocalPtValues) do TestData:store(values) print(values) end TestData:store("ActualLocalPtValues") commonFunctions:userPrint(35, "ActualLocalPtValues") for _, values in pairs(actualLocalPtValues) do TestData:store(values) print(values) end isTestPass = false end else TestData:store("Test failed: Can't get data from LocalPT") commonFunctions:userPrint(31, "Test failed: Can't get data from LocalPT") isTestPass = false end end return isTestPass end -- local function prepareJsonPTU(name, newPTUfile) -- local json_app = [[ { -- "keep_context": false, -- "steal_focus": false, -- "priority": "NONE", -- "default_hmi": "NONE", -- "groups": [ -- "Location-1" -- ], -- "RequestType":[ -- "TRAFFIC_MESSAGE_CHANNEL", -- "PROPRIETARY", -- "HTTP", -- "QUERY_APPS" -- ] -- }]] -- local app = json.decode(json_app) -- -- ToDo (aderiabin): This function must be replaced by call -- -- testCasesForPolicyTable:AddApplicationToPTJsonFile(basePtuFile, newPTUfile, name, app) -- -- after merge of pull request #227 -- addApplicationToPTJsonFile(basePtuFile, newPTUfile, name, app) -- end function Test.backupPreloadedPT(backupPrefix) os.execute(table.concat({"cp ", config.pathToSDL, PRELOADED_PT_FILE_NAME, " ", config.pathToSDL, backupPrefix, PRELOADED_PT_FILE_NAME})) end function Test.restorePreloadedPT(backupPrefix) os.execute(table.concat({"mv ", config.pathToSDL, backupPrefix, PRELOADED_PT_FILE_NAME, " ", config.pathToSDL, PRELOADED_PT_FILE_NAME})) end local function updateJSON(pathToFile, updaters) local file = io.open(pathToFile, "r") local json_data = file:read("*a") file:close() local data = json.decode(json_data) if data then for _, updateFunc in pairs(updaters) do updateFunc(data) end -- Workaround. null value in lua table == not existing value. But in json file it has to be data.policy_table.functional_groupings["DataConsent-2"].rpcs = "tobedeletedinjsonfile" local dataToWrite = json.encode(data) dataToWrite = string.gsub(dataToWrite, "\"tobedeletedinjsonfile\"", "null") file = io.open(pathToFile, "w") file:write(dataToWrite) file:close() end end function Test.preparePreloadedPT() local preloadedUpdaters = { function(data) data.policy_table.module_config.exchange_after_x_ignition_cycles = TESTED_DATA.preloaded.policy_table.module_config.exchange_after_x_ignition_cycles end } updateJSON(config.pathToSDL .. PRELOADED_PT_FILE_NAME, preloadedUpdaters) end function Test.preparePTUpdate() local PTUpdaters = { function(data) data.policy_table.module_config.exchange_after_x_ignition_cycles = TESTED_DATA.update.policy_table.module_config.exchange_after_x_ignition_cycles end } updateJSON(ptuAppRegistered, PTUpdaters) end --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_ActivateAppInFULL() HMIAppId = self.applications[config.application1.registerAppInterfaceParams.appName] activateAppInSpecificLevel(self,HMIAppId,"FULL") TestData:store("Store LocalPT before PTU", constructPathToDatabase(), "beforePTU_policy.sqlite" ) EXPECT_HMICALL("BasicCommunication.PolicyUpdate") :Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}, {status = "UPDATING"}):Times(2) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:UpdatePolicy_ExpectOnAppPermissionChangedWithAppID() -- ToDo (aderiabin): This function must be replaced by call -- testCasesForPolicyTable:updatePolicyInDifferentSessions(Test, ptuAppRegistered, -- config.application1.registerAppInterfaceParams.appName, -- self.mobileSession) -- after merge of pull request #227 self:updatePolicyInDifferentSessions(ptuAppRegistered, config.application1.registerAppInterfaceParams.appName, self.mobileSession) end function Test:TestStep_CheckSDLLogError() local is_test_fail = false local result = testCasesForPolicySDLErrorsStops.ReadSpecificMessage("policy_table.policy_table.module_config.notifications_per_minute_by_priority%[\"EMERGENCY\"%]: value initialized incorrectly") if(result == false) then commonFunctions:printError("Error: message 'policy_table.policy_table.module_config.notifications_per_minute_by_priority[\"EMERGENCY\"]: value initialized incorrectly' is not observed in smartDeviceLink.log.") is_test_fail = true end result = testCasesForPolicySDLErrorsStops.ReadSpecificMessage("policy_table.policy_table.module_config.exchange_after_x_ignition_cycles: value initialized incorrectly") if(result == false) then commonFunctions.printError("Error: message 'policy_table.policy_table.module_config.exchange_after_x_ignition_cycles: value initialized incorrectly' is not observed in smartDeviceLink.log.") is_test_fail = true end if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop() StopSDL() end return Test
bsd-3-clause
xdemolish/darkstar
scripts/globals/abilities/pets/fire_ii.lua
5
1159
--------------------------------------------------- -- Fire 2 --------------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); require("/scripts/globals/magic"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill) local spell = getSpell(145); --calculate raw damage local dmg = calculateMagicDamage(133,1,pet,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false); --get resist multiplier (1x if no resist) local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, ELE_FIRE); --get the resisted damage dmg = dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = mobAddBonuses(pet,spell,target,dmg, 1); --add on TP bonuses local tp = pet:getTP(); if tp < 100 then tp = 100; end dmg = dmg * tp / 100; --add in final adjustments dmg = finalMagicAdjustments(pet,target,spell,dmg); return dmg; end
gpl-3.0
xdemolish/darkstar
scripts/zones/Cloister_of_Tremors/bcnms/trial_by_earth.lua
13
1775
----------------------------------- -- Area: Cloister of Tremors -- BCNM: Trial by Earth -- @pos -539 1 -493 209 ----------------------------------- package.loaded["scripts/zones/Cloister_of_Tremors/TextIDs"] = nil; ------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Cloister_of_Tremors/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if(player:hasCompleteQuest(BASTOK,TRIAL_BY_EARTH)) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); end elseif(leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if(csid == 0x7d01) then player:delKeyItem(TUNING_FORK_OF_EARTH); player:addKeyItem(WHISPER_OF_TREMORS); player:messageSpecial(KEYITEM_OBTAINED,WHISPER_OF_TREMORS); end end;
gpl-3.0
lighter-cd/premake4-mobile
tests/actions/vstudio/vc2010/test_files.lua
31
1551
-- -- tests/actions/vstudio/vc2010/test_files.lua -- Validate generation of files block in Visual Studio 2010 C/C++ projects. -- Copyright (c) 2011 Jason Perkins and the Premake project -- T.vstudio_vs2010_files = { } local suite = T.vstudio_vs2010_files local vc2010 = premake.vstudio.vc2010 -- -- Setup -- local sln, prj function suite.setup() sln = test.createsolution() end local function prepare() premake.bake.buildconfigs() prj = premake.solution.getproject(sln, 1) sln.vstudio_configs = premake.vstudio.buildconfigs(sln) vc2010.files(prj) end -- -- Test file groups -- function suite.SimpleHeaderFile() files { "include/hello.h" } prepare() test.capture [[ <ItemGroup> <ClInclude Include="include\hello.h" /> </ItemGroup> ]] end function suite.SimpleSourceFile() files { "hello.c" } prepare() test.capture [[ <ItemGroup> <ClCompile Include="hello.c"> </ClCompile> </ItemGroup> ]] end function suite.SimpleNoneFile() files { "docs/hello.txt" } prepare() test.capture [[ <ItemGroup> <None Include="docs\hello.txt" /> </ItemGroup> ]] end function suite.SimpleResourceFile() files { "resources/hello.rc" } prepare() test.capture [[ <ItemGroup> <ResourceCompile Include="resources\hello.rc" /> </ItemGroup> ]] end -- -- Test path handling -- function suite.MultipleFolderLevels() files { "src/greetings/hello.c" } prepare() test.capture [[ <ItemGroup> <ClCompile Include="src\greetings\hello.c"> </ClCompile> </ItemGroup> ]] end
mit
hsiaoyi/Melo
cocos2d/cocos/scripting/lua-bindings/script/cocos2d/DeprecatedOpenglEnum.lua
148
11934
-- This is the DeprecatedEnum DeprecatedClass = {} or DeprecatedClass _G.GL_RENDERBUFFER_INTERNAL_FORMAT = gl.RENDERBUFFER_INTERNAL_FORMAT _G.GL_LINE_WIDTH = gl.LINE_WIDTH _G.GL_CONSTANT_ALPHA = gl.CONSTANT_ALPHA _G.GL_BLEND_SRC_ALPHA = gl.BLEND_SRC_ALPHA _G.GL_GREEN_BITS = gl.GREEN_BITS _G.GL_STENCIL_REF = gl.STENCIL_REF _G.GL_ONE_MINUS_SRC_ALPHA = gl.ONE_MINUS_SRC_ALPHA _G.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE _G.GL_CCW = gl.CCW _G.GL_MAX_TEXTURE_IMAGE_UNITS = gl.MAX_TEXTURE_IMAGE_UNITS _G.GL_BACK = gl.BACK _G.GL_ACTIVE_ATTRIBUTES = gl.ACTIVE_ATTRIBUTES _G.GL_TEXTURE_CUBE_MAP_POSITIVE_X = gl.TEXTURE_CUBE_MAP_POSITIVE_X _G.GL_STENCIL_BACK_VALUE_MASK = gl.STENCIL_BACK_VALUE_MASK _G.GL_TEXTURE_CUBE_MAP_POSITIVE_Z = gl.TEXTURE_CUBE_MAP_POSITIVE_Z _G.GL_ONE = gl.ONE _G.GL_TRUE = gl.TRUE _G.GL_TEXTURE12 = gl.TEXTURE12 _G.GL_LINK_STATUS = gl.LINK_STATUS _G.GL_BLEND = gl.BLEND _G.GL_LESS = gl.LESS _G.GL_TEXTURE16 = gl.TEXTURE16 _G.GL_BOOL_VEC2 = gl.BOOL_VEC2 _G.GL_KEEP = gl.KEEP _G.GL_DST_COLOR = gl.DST_COLOR _G.GL_VERTEX_ATTRIB_ARRAY_ENABLED = gl.VERTEX_ATTRIB_ARRAY_ENABLED _G.GL_EXTENSIONS = gl.EXTENSIONS _G.GL_FRONT = gl.FRONT _G.GL_DST_ALPHA = gl.DST_ALPHA _G.GL_ATTACHED_SHADERS = gl.ATTACHED_SHADERS _G.GL_STENCIL_BACK_FUNC = gl.STENCIL_BACK_FUNC _G.GL_ONE_MINUS_DST_COLOR = gl.ONE_MINUS_DST_COLOR _G.GL_BLEND_EQUATION = gl.BLEND_EQUATION _G.GL_RENDERBUFFER_DEPTH_SIZE = gl.RENDERBUFFER_DEPTH_SIZE _G.GL_PACK_ALIGNMENT = gl.PACK_ALIGNMENT _G.GL_VENDOR = gl.VENDOR _G.GL_NEAREST_MIPMAP_LINEAR = gl.NEAREST_MIPMAP_LINEAR _G.GL_TEXTURE_CUBE_MAP_POSITIVE_Y = gl.TEXTURE_CUBE_MAP_POSITIVE_Y _G.GL_NEAREST = gl.NEAREST _G.GL_RENDERBUFFER_WIDTH = gl.RENDERBUFFER_WIDTH _G.GL_ARRAY_BUFFER_BINDING = gl.ARRAY_BUFFER_BINDING _G.GL_ARRAY_BUFFER = gl.ARRAY_BUFFER _G.GL_LEQUAL = gl.LEQUAL _G.GL_VERSION = gl.VERSION _G.GL_COLOR_CLEAR_VALUE = gl.COLOR_CLEAR_VALUE _G.GL_RENDERER = gl.RENDERER _G.GL_STENCIL_BACK_PASS_DEPTH_PASS = gl.STENCIL_BACK_PASS_DEPTH_PASS _G.GL_STENCIL_BACK_PASS_DEPTH_FAIL = gl.STENCIL_BACK_PASS_DEPTH_FAIL _G.GL_STENCIL_BACK_WRITEMASK = gl.STENCIL_BACK_WRITEMASK _G.GL_BOOL = gl.BOOL _G.GL_VIEWPORT = gl.VIEWPORT _G.GL_FRAGMENT_SHADER = gl.FRAGMENT_SHADER _G.GL_LUMINANCE = gl.LUMINANCE _G.GL_DECR_WRAP = gl.DECR_WRAP _G.GL_FUNC_ADD = gl.FUNC_ADD _G.GL_ONE_MINUS_DST_ALPHA = gl.ONE_MINUS_DST_ALPHA _G.GL_OUT_OF_MEMORY = gl.OUT_OF_MEMORY _G.GL_BOOL_VEC4 = gl.BOOL_VEC4 _G.GL_POLYGON_OFFSET_FACTOR = gl.POLYGON_OFFSET_FACTOR _G.GL_STATIC_DRAW = gl.STATIC_DRAW _G.GL_DITHER = gl.DITHER _G.GL_TEXTURE31 = gl.TEXTURE31 _G.GL_TEXTURE30 = gl.TEXTURE30 _G.GL_UNSIGNED_BYTE = gl.UNSIGNED_BYTE _G.GL_DEPTH_COMPONENT16 = gl.DEPTH_COMPONENT16 _G.GL_TEXTURE23 = gl.TEXTURE23 _G.GL_DEPTH_TEST = gl.DEPTH_TEST _G.GL_STENCIL_PASS_DEPTH_FAIL = gl.STENCIL_PASS_DEPTH_FAIL _G.GL_BOOL_VEC3 = gl.BOOL_VEC3 _G.GL_POLYGON_OFFSET_UNITS = gl.POLYGON_OFFSET_UNITS _G.GL_TEXTURE_BINDING_2D = gl.TEXTURE_BINDING_2D _G.GL_TEXTURE21 = gl.TEXTURE21 _G.GL_UNPACK_ALIGNMENT = gl.UNPACK_ALIGNMENT _G.GL_DONT_CARE = gl.DONT_CARE _G.GL_BUFFER_SIZE = gl.BUFFER_SIZE _G.GL_FLOAT_MAT3 = gl.FLOAT_MAT3 _G.GL_UNSIGNED_SHORT_5_6_5 = gl.UNSIGNED_SHORT_5_6_5 _G.GL_INT_VEC2 = gl.INT_VEC2 _G.GL_UNSIGNED_SHORT_4_4_4_4 = gl.UNSIGNED_SHORT_4_4_4_4 _G.GL_NONE = gl.NONE _G.GL_BLEND_DST_ALPHA = gl.BLEND_DST_ALPHA _G.GL_VERTEX_ATTRIB_ARRAY_SIZE = gl.VERTEX_ATTRIB_ARRAY_SIZE _G.GL_SRC_COLOR = gl.SRC_COLOR _G.GL_COMPRESSED_TEXTURE_FORMATS = gl.COMPRESSED_TEXTURE_FORMATS _G.GL_STENCIL_ATTACHMENT = gl.STENCIL_ATTACHMENT _G.GL_MAX_VERTEX_ATTRIBS = gl.MAX_VERTEX_ATTRIBS _G.GL_NUM_COMPRESSED_TEXTURE_FORMATS = gl.NUM_COMPRESSED_TEXTURE_FORMATS _G.GL_BLEND_EQUATION_RGB = gl.BLEND_EQUATION_RGB _G.GL_TEXTURE = gl.TEXTURE _G.GL_LINEAR_MIPMAP_LINEAR = gl.LINEAR_MIPMAP_LINEAR _G.GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING _G.GL_CURRENT_PROGRAM = gl.CURRENT_PROGRAM _G.GL_COLOR_BUFFER_BIT = gl.COLOR_BUFFER_BIT _G.GL_TEXTURE20 = gl.TEXTURE20 _G.GL_ACTIVE_ATTRIBUTE_MAX_LENGTH = gl.ACTIVE_ATTRIBUTE_MAX_LENGTH _G.GL_TEXTURE28 = gl.TEXTURE28 _G.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE _G.GL_TEXTURE22 = gl.TEXTURE22 _G.GL_ELEMENT_ARRAY_BUFFER_BINDING = gl.ELEMENT_ARRAY_BUFFER_BINDING _G.GL_STREAM_DRAW = gl.STREAM_DRAW _G.GL_SCISSOR_BOX = gl.SCISSOR_BOX _G.GL_TEXTURE26 = gl.TEXTURE26 _G.GL_TEXTURE27 = gl.TEXTURE27 _G.GL_TEXTURE24 = gl.TEXTURE24 _G.GL_TEXTURE25 = gl.TEXTURE25 _G.GL_NO_ERROR = gl.NO_ERROR _G.GL_TEXTURE29 = gl.TEXTURE29 _G.GL_FLOAT_MAT4 = gl.FLOAT_MAT4 _G.GL_VERTEX_ATTRIB_ARRAY_NORMALIZED = gl.VERTEX_ATTRIB_ARRAY_NORMALIZED _G.GL_SAMPLE_COVERAGE_INVERT = gl.SAMPLE_COVERAGE_INVERT _G.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL _G.GL_FLOAT_VEC3 = gl.FLOAT_VEC3 _G.GL_STENCIL_CLEAR_VALUE = gl.STENCIL_CLEAR_VALUE _G.GL_UNSIGNED_SHORT_5_5_5_1 = gl.UNSIGNED_SHORT_5_5_5_1 _G.GL_ACTIVE_UNIFORMS = gl.ACTIVE_UNIFORMS _G.GL_INVALID_OPERATION = gl.INVALID_OPERATION _G.GL_DEPTH_ATTACHMENT = gl.DEPTH_ATTACHMENT _G.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS _G.GL_FRAMEBUFFER_COMPLETE = gl.FRAMEBUFFER_COMPLETE _G.GL_ONE_MINUS_CONSTANT_COLOR = gl.ONE_MINUS_CONSTANT_COLOR _G.GL_TEXTURE2 = gl.TEXTURE2 _G.GL_TEXTURE1 = gl.TEXTURE1 _G.GL_GEQUAL = gl.GEQUAL _G.GL_TEXTURE7 = gl.TEXTURE7 _G.GL_TEXTURE6 = gl.TEXTURE6 _G.GL_TEXTURE5 = gl.TEXTURE5 _G.GL_TEXTURE4 = gl.TEXTURE4 _G.GL_GENERATE_MIPMAP_HINT = gl.GENERATE_MIPMAP_HINT _G.GL_ONE_MINUS_SRC_COLOR = gl.ONE_MINUS_SRC_COLOR _G.GL_TEXTURE9 = gl.TEXTURE9 _G.GL_STENCIL_TEST = gl.STENCIL_TEST _G.GL_COLOR_WRITEMASK = gl.COLOR_WRITEMASK _G.GL_DEPTH_COMPONENT = gl.DEPTH_COMPONENT _G.GL_STENCIL_INDEX8 = gl.STENCIL_INDEX8 _G.GL_VERTEX_ATTRIB_ARRAY_TYPE = gl.VERTEX_ATTRIB_ARRAY_TYPE _G.GL_FLOAT_VEC2 = gl.FLOAT_VEC2 _G.GL_BLUE_BITS = gl.BLUE_BITS _G.GL_VERTEX_SHADER = gl.VERTEX_SHADER _G.GL_SUBPIXEL_BITS = gl.SUBPIXEL_BITS _G.GL_STENCIL_WRITEMASK = gl.STENCIL_WRITEMASK _G.GL_FLOAT_VEC4 = gl.FLOAT_VEC4 _G.GL_TEXTURE17 = gl.TEXTURE17 _G.GL_ONE_MINUS_CONSTANT_ALPHA = gl.ONE_MINUS_CONSTANT_ALPHA _G.GL_TEXTURE15 = gl.TEXTURE15 _G.GL_TEXTURE14 = gl.TEXTURE14 _G.GL_TEXTURE13 = gl.TEXTURE13 _G.GL_SAMPLES = gl.SAMPLES _G.GL_TEXTURE11 = gl.TEXTURE11 _G.GL_TEXTURE10 = gl.TEXTURE10 _G.GL_FUNC_SUBTRACT = gl.FUNC_SUBTRACT _G.GL_STENCIL_BUFFER_BIT = gl.STENCIL_BUFFER_BIT _G.GL_TEXTURE19 = gl.TEXTURE19 _G.GL_TEXTURE18 = gl.TEXTURE18 _G.GL_NEAREST_MIPMAP_NEAREST = gl.NEAREST_MIPMAP_NEAREST _G.GL_SHORT = gl.SHORT _G.GL_RENDERBUFFER_BINDING = gl.RENDERBUFFER_BINDING _G.GL_REPEAT = gl.REPEAT _G.GL_TEXTURE_MIN_FILTER = gl.TEXTURE_MIN_FILTER _G.GL_RED_BITS = gl.RED_BITS _G.GL_FRONT_FACE = gl.FRONT_FACE _G.GL_BLEND_COLOR = gl.BLEND_COLOR _G.GL_MIRRORED_REPEAT = gl.MIRRORED_REPEAT _G.GL_INT_VEC4 = gl.INT_VEC4 _G.GL_MAX_CUBE_MAP_TEXTURE_SIZE = gl.MAX_CUBE_MAP_TEXTURE_SIZE _G.GL_RENDERBUFFER_BLUE_SIZE = gl.RENDERBUFFER_BLUE_SIZE _G.GL_SAMPLE_COVERAGE = gl.SAMPLE_COVERAGE _G.GL_SRC_ALPHA = gl.SRC_ALPHA _G.GL_FUNC_REVERSE_SUBTRACT = gl.FUNC_REVERSE_SUBTRACT _G.GL_DEPTH_WRITEMASK = gl.DEPTH_WRITEMASK _G.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT _G.GL_POLYGON_OFFSET_FILL = gl.POLYGON_OFFSET_FILL _G.GL_STENCIL_FUNC = gl.STENCIL_FUNC _G.GL_REPLACE = gl.REPLACE _G.GL_LUMINANCE_ALPHA = gl.LUMINANCE_ALPHA _G.GL_DEPTH_RANGE = gl.DEPTH_RANGE _G.GL_FASTEST = gl.FASTEST _G.GL_STENCIL_FAIL = gl.STENCIL_FAIL _G.GL_UNSIGNED_SHORT = gl.UNSIGNED_SHORT _G.GL_RENDERBUFFER_HEIGHT = gl.RENDERBUFFER_HEIGHT _G.GL_STENCIL_BACK_FAIL = gl.STENCIL_BACK_FAIL _G.GL_BLEND_SRC_RGB = gl.BLEND_SRC_RGB _G.GL_TEXTURE3 = gl.TEXTURE3 _G.GL_RENDERBUFFER = gl.RENDERBUFFER _G.GL_RGB5_A1 = gl.RGB5_A1 _G.GL_RENDERBUFFER_ALPHA_SIZE = gl.RENDERBUFFER_ALPHA_SIZE _G.GL_RENDERBUFFER_STENCIL_SIZE = gl.RENDERBUFFER_STENCIL_SIZE _G.GL_NOTEQUAL = gl.NOTEQUAL _G.GL_BLEND_DST_RGB = gl.BLEND_DST_RGB _G.GL_FRONT_AND_BACK = gl.FRONT_AND_BACK _G.GL_TEXTURE_BINDING_CUBE_MAP = gl.TEXTURE_BINDING_CUBE_MAP _G.GL_MAX_RENDERBUFFER_SIZE = gl.MAX_RENDERBUFFER_SIZE _G.GL_ZERO = gl.ZERO _G.GL_TEXTURE0 = gl.TEXTURE0 _G.GL_SAMPLE_ALPHA_TO_COVERAGE = gl.SAMPLE_ALPHA_TO_COVERAGE _G.GL_BUFFER_USAGE = gl.BUFFER_USAGE _G.GL_ACTIVE_TEXTURE = gl.ACTIVE_TEXTURE _G.GL_BYTE = gl.BYTE _G.GL_CW = gl.CW _G.GL_DYNAMIC_DRAW = gl.DYNAMIC_DRAW _G.GL_RENDERBUFFER_RED_SIZE = gl.RENDERBUFFER_RED_SIZE _G.GL_FALSE = gl.FALSE _G.GL_GREATER = gl.GREATER _G.GL_RGBA4 = gl.RGBA4 _G.GL_VALIDATE_STATUS = gl.VALIDATE_STATUS _G.GL_STENCIL_BITS = gl.STENCIL_BITS _G.GL_RGB = gl.RGB _G.GL_INT = gl.INT _G.GL_DEPTH_FUNC = gl.DEPTH_FUNC _G.GL_SAMPLER_2D = gl.SAMPLER_2D _G.GL_NICEST = gl.NICEST _G.GL_MAX_VIEWPORT_DIMS = gl.MAX_VIEWPORT_DIMS _G.GL_CULL_FACE = gl.CULL_FACE _G.GL_INT_VEC3 = gl.INT_VEC3 _G.GL_ALIASED_POINT_SIZE_RANGE = gl.ALIASED_POINT_SIZE_RANGE _G.GL_INVALID_ENUM = gl.INVALID_ENUM _G.GL_INVERT = gl.INVERT _G.GL_CULL_FACE_MODE = gl.CULL_FACE_MODE _G.GL_TEXTURE8 = gl.TEXTURE8 _G.GL_VERTEX_ATTRIB_ARRAY_POINTER = gl.VERTEX_ATTRIB_ARRAY_POINTER _G.GL_TEXTURE_WRAP_S = gl.TEXTURE_WRAP_S _G.GL_VERTEX_ATTRIB_ARRAY_STRIDE = gl.VERTEX_ATTRIB_ARRAY_STRIDE _G.GL_LINES = gl.LINES _G.GL_EQUAL = gl.EQUAL _G.GL_LINE_LOOP = gl.LINE_LOOP _G.GL_TEXTURE_WRAP_T = gl.TEXTURE_WRAP_T _G.GL_DEPTH_BUFFER_BIT = gl.DEPTH_BUFFER_BIT _G.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS _G.GL_SHADER_TYPE = gl.SHADER_TYPE _G.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = gl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME _G.GL_TEXTURE_CUBE_MAP_NEGATIVE_X = gl.TEXTURE_CUBE_MAP_NEGATIVE_X _G.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y = gl.TEXTURE_CUBE_MAP_NEGATIVE_Y _G.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z = gl.TEXTURE_CUBE_MAP_NEGATIVE_Z _G.GL_DECR = gl.DECR _G.GL_DELETE_STATUS = gl.DELETE_STATUS _G.GL_DEPTH_BITS = gl.DEPTH_BITS _G.GL_INCR = gl.INCR _G.GL_SAMPLE_COVERAGE_VALUE = gl.SAMPLE_COVERAGE_VALUE _G.GL_ALPHA_BITS = gl.ALPHA_BITS _G.GL_FLOAT_MAT2 = gl.FLOAT_MAT2 _G.GL_LINE_STRIP = gl.LINE_STRIP _G.GL_SHADER_SOURCE_LENGTH = gl.SHADER_SOURCE_LENGTH _G.GL_INVALID_VALUE = gl.INVALID_VALUE _G.GL_NEVER = gl.NEVER _G.GL_INCR_WRAP = gl.INCR_WRAP _G.GL_BLEND_EQUATION_ALPHA = gl.BLEND_EQUATION_ALPHA _G.GL_TEXTURE_MAG_FILTER = gl.TEXTURE_MAG_FILTER _G.GL_POINTS = gl.POINTS _G.GL_COLOR_ATTACHMENT0 = gl.COLOR_ATTACHMENT0 _G.GL_RGBA = gl.RGBA _G.GL_SRC_ALPHA_SATURATE = gl.SRC_ALPHA_SATURATE _G.GL_SAMPLER_CUBE = gl.SAMPLER_CUBE _G.GL_FRAMEBUFFER = gl.FRAMEBUFFER _G.GL_TEXTURE_CUBE_MAP = gl.TEXTURE_CUBE_MAP _G.GL_SAMPLE_BUFFERS = gl.SAMPLE_BUFFERS _G.GL_LINEAR = gl.LINEAR _G.GL_LINEAR_MIPMAP_NEAREST = gl.LINEAR_MIPMAP_NEAREST _G.GL_ACTIVE_UNIFORM_MAX_LENGTH = gl.ACTIVE_UNIFORM_MAX_LENGTH _G.GL_STENCIL_BACK_REF = gl.STENCIL_BACK_REF _G.GL_ELEMENT_ARRAY_BUFFER = gl.ELEMENT_ARRAY_BUFFER _G.GL_CLAMP_TO_EDGE = gl.CLAMP_TO_EDGE _G.GL_TRIANGLE_STRIP = gl.TRIANGLE_STRIP _G.GL_CONSTANT_COLOR = gl.CONSTANT_COLOR _G.GL_COMPILE_STATUS = gl.COMPILE_STATUS _G.GL_RENDERBUFFER_GREEN_SIZE = gl.RENDERBUFFER_GREEN_SIZE _G.GL_UNSIGNED_INT = gl.UNSIGNED_INT _G.GL_DEPTH_CLEAR_VALUE = gl.DEPTH_CLEAR_VALUE _G.GL_ALIASED_LINE_WIDTH_RANGE = gl.ALIASED_LINE_WIDTH_RANGE _G.GL_SHADING_LANGUAGE_VERSION = gl.SHADING_LANGUAGE_VERSION _G.GL_FRAMEBUFFER_UNSUPPORTED = gl.FRAMEBUFFER_UNSUPPORTED _G.GL_INFO_LOG_LENGTH = gl.INFO_LOG_LENGTH _G.GL_STENCIL_PASS_DEPTH_PASS = gl.STENCIL_PASS_DEPTH_PASS _G.GL_STENCIL_VALUE_MASK = gl.STENCIL_VALUE_MASK _G.GL_ALWAYS = gl.ALWAYS _G.GL_MAX_TEXTURE_SIZE = gl.MAX_TEXTURE_SIZE _G.GL_FLOAT = gl.FLOAT _G.GL_FRAMEBUFFER_BINDING = gl.FRAMEBUFFER_BINDING _G.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT _G.GL_TRIANGLE_FAN = gl.TRIANGLE_FAN _G.GL_INVALID_FRAMEBUFFER_OPERATION = gl.INVALID_FRAMEBUFFER_OPERATION _G.GL_TEXTURE_2D = gl.TEXTURE_2D _G.GL_ALPHA = gl.ALPHA _G.GL_CURRENT_VERTEX_ATTRIB = gl.CURRENT_VERTEX_ATTRIB _G.GL_SCISSOR_TEST = gl.SCISSOR_TEST _G.GL_TRIANGLES = gl.TRIANGLES
apache-2.0
yylangchen/Sample_Lua
frameworks/cocos2d-x/templates/lua-template-runtime/src/GameScene.lua
5
6484
local GameScene = class("GameScene",function() return cc.Scene:create() end) function GameScene.create() local scene = GameScene.new() scene:addChild(scene:createLayerFarm()) scene:addChild(scene:createLayerMenu()) return scene end function GameScene:ctor() self.visibleSize = cc.Director:getInstance():getVisibleSize() self.origin = cc.Director:getInstance():getVisibleOrigin() self.schedulerID = nil end function GameScene:playBgMusic() local bgMusicPath = cc.FileUtils:getInstance():fullPathForFilename("background.mp3") cc.SimpleAudioEngine:getInstance():playMusic(bgMusicPath, true) local effectPath = cc.FileUtils:getInstance():fullPathForFilename("effect1.wav") cc.SimpleAudioEngine:getInstance():preloadEffect(effectPath) end function GameScene:creatDog() local frameWidth = 105 local frameHeight = 95 -- create dog animate local textureDog = cc.Director:getInstance():getTextureCache():addImage("dog.png") local rect = cc.rect(0, 0, frameWidth, frameHeight) local frame0 = cc.SpriteFrame:createWithTexture(textureDog, rect) rect = cc.rect(frameWidth, 0, frameWidth, frameHeight) local frame1 = cc.SpriteFrame:createWithTexture(textureDog, rect) local spriteDog = cc.Sprite:createWithSpriteFrame(frame0) spriteDog:setPosition(self.origin.x, self.origin.y + self.visibleSize.height / 4 * 3) spriteDog.isPaused = false local animation = cc.Animation:createWithSpriteFrames({frame0,frame1}, 0.5) local animate = cc.Animate:create(animation); spriteDog:runAction(cc.RepeatForever:create(animate)) -- moving dog at every frame local function tick() if spriteDog.isPaused then return end local x, y = spriteDog:getPosition() if x > self.origin.x + self.visibleSize.width then x = self.origin.x else x = x + 1 end spriteDog:setPositionX(x) end self.schedulerID = cc.Director:getInstance():getScheduler():scheduleScriptFunc(tick, 0, false) return spriteDog end -- create farm function GameScene:createLayerFarm() local layerFarm = cc.Layer:create() -- add in farm background local bg = cc.Sprite:create("farm.jpg") bg:setPosition(self.origin.x + self.visibleSize.width / 2 + 80, self.origin.y + self.visibleSize.height / 2) layerFarm:addChild(bg) -- add land sprite for i = 0, 3 do for j = 0, 1 do local spriteLand = cc.Sprite:create("land.png") spriteLand:setPosition(200 + j * 180 - i % 2 * 90, 10 + i * 95 / 2) layerFarm:addChild(spriteLand) end end -- add crop local frameCrop = cc.SpriteFrame:create("crop.png", cc.rect(0, 0, 105, 95)) for i = 0, 3 do for j = 0, 1 do local spriteCrop = cc.Sprite:createWithSpriteFrame(frameCrop); spriteCrop:setPosition(210 + j * 180 - i % 2 * 90, 40 + i * 95 / 2) layerFarm:addChild(spriteCrop) end end -- add moving dog local spriteDog = self:creatDog() layerFarm:addChild(spriteDog) -- handing touch events local touchBeginPoint = nil local function onTouchBegan(touch, event) local location = touch:getLocation() --cclog("onTouchBegan: %0.2f, %0.2f", location.x, location.y) touchBeginPoint = {x = location.x, y = location.y} spriteDog.isPaused = true -- CCTOUCHBEGAN event must return true return true end local function onTouchMoved(touch, event) local location = touch:getLocation() --cclog("onTouchMoved: %0.2f, %0.2f", location.x, location.y) if touchBeginPoint then local cx, cy = layerFarm:getPosition() layerFarm:setPosition(cx + location.x - touchBeginPoint.x, cy + location.y - touchBeginPoint.y) touchBeginPoint = {x = location.x, y = location.y} end end local function onTouchEnded(touch, event) local location = touch:getLocation() --cclog("onTouchEnded: %0.2f, %0.2f", location.x, location.y) touchBeginPoint = nil spriteDog.isPaused = false end local listener = cc.EventListenerTouchOneByOne:create() listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN ) listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED ) listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED ) local eventDispatcher = layerFarm:getEventDispatcher() eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layerFarm) local function onNodeEvent(event) if "exit" == event then cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self.schedulerID) end end layerFarm:registerScriptHandler(onNodeEvent) return layerFarm end -- create menu function GameScene:createLayerMenu() local layerMenu = cc.Layer:create() local menuPopup, menuTools, effectID local function menuCallbackClosePopup() -- stop test sound effect cc.SimpleAudioEngine:getInstance():stopEffect(effectID) menuPopup:setVisible(false) end local function menuCallbackOpenPopup() -- loop test sound effect local effectPath = cc.FileUtils:getInstance():fullPathForFilename("effect1.wav") effectID = cc.SimpleAudioEngine:getInstance():playEffect(effectPath) menuPopup:setVisible(true) end -- add a popup menu local menuPopupItem = cc.MenuItemImage:create("menu2.png", "menu2.png") menuPopupItem:setPosition(0, 0) menuPopupItem:registerScriptTapHandler(menuCallbackClosePopup) menuPopup = cc.Menu:create(menuPopupItem) menuPopup:setPosition(self.origin.x + self.visibleSize.width / 2, self.origin.y + self.visibleSize.height / 2) menuPopup:setVisible(false) layerMenu:addChild(menuPopup) -- add the left-bottom "tools" menu to invoke menuPopup local menuToolsItem = cc.MenuItemImage:create("menu1.png", "menu1.png") menuToolsItem:setPosition(0, 0) menuToolsItem:registerScriptTapHandler(menuCallbackOpenPopup) menuTools = cc.Menu:create(menuToolsItem) local itemWidth = menuToolsItem:getContentSize().width local itemHeight = menuToolsItem:getContentSize().height menuTools:setPosition(self.origin.x + itemWidth/2, self.origin.y + itemHeight/2) layerMenu:addChild(menuTools) return layerMenu end return GameScene
mit
MockbaTheBorg/GTALuaF
Lua/globals/offsets.lua
1
11092
-- Offsets for b1180 -- Instance offsets DRAW_HANDLER = 0x0048 ENTITY_VISIBLE = 0x002C ENTITY_MAX_HEALTH = 0x02A0 PED_MONEY = 0x15d4 PED_TYPE = 0x10A8 VEHICLE_DIRT_LEVEL = 0x0968 VEHICLE_MAX_NUMBER_OF_PASSENGERS = 0x0bb0 VEHICLE_WINDOWS_TINT = 0x03FE -- Memory offsets TEXT_COLOUR = LoadAddr() + 0x1c93e10 TEXT_SCALE1 = LoadAddr() + 0x1c93e14 TEXT_SCALE2 = LoadAddr() + 0x1c93e18 TEXT_WRAP1 = LoadAddr() + 0x1c93e1c TEXT_WRAP2 = LoadAddr() + 0x1c93e20 TEXT_FONT = LoadAddr() + 0x1c93e24 TEXT_JUSTIFICATION = LoadAddr() + 0x1c93e2c TEXT_LEADING = TEXT_JUSTIFICATION + 1 TEXT_DROP_SHADOW = LoadAddr() + 0x1c93e2e TEXT_OUTLINE = LoadAddr() + 0x1c93e2f CLOCK_WEEKDAY = LoadAddr() + 0x1c21198 CLOCK_DAY = LoadAddr() + 0x1c2119c CLOCK_MONTH = LoadAddr() + 0x1c211a0 CLOCK_YEAR = LoadAddr() + 0x1c211a4 CLOCK_HOURS = LoadAddr() + 0x1c211a8 CLOCK_MINUTES = LoadAddr() + 0x1c211ac CLOCK_SECONDS = LoadAddr() + 0x1c211b0 CLOCK_PAUSE = LoadAddr() + 0x235f923 MILLISECONDS_PER_GAME_MINUTE = LoadAddr() + 0x235f944 HUD_WANTED_STARS = LoadAddr() + 0x1fa9238 HUD_CASH = LoadAddr() + 0x1fa9328 HUD_MP_CASH = LoadAddr() + 0x1fa93a0 HUD_MP_MESSAGE = LoadAddr() + 0x1fa9418 HUD_VEHICLE_NAME = LoadAddr() + 0x1fa9490 HUD_AREA_NAME = LoadAddr() + 0x1fa9508 HUD_STREET_NAME = LoadAddr() + 0x1fa95f8 HUD_HELP_TEXT = LoadAddr() + 0x1fa9670 HUD_FLOATING_HELP_TEXT_1 = LoadAddr() + 0x1fa96e8 HUD_FLOATING_HELP_TEXT_2 = LoadAddr() + 0x1fa9760 HUD_RETICLE = LoadAddr() + 0x1fa9850 HUD_SUBTITLE_TEXT = LoadAddr() + 0x1fa98c8 MAX_3D_Z = LoadAddr() + 0x18a85e8 SCREEN_X = LoadAddr() + 0x20bd19c SCREEN_Y = LoadAddr() + 0x20bd1a4 -- Game Functions GET_ENTITY_INSTANCE = LoadAddr() + 0x0a20e64 GET_OBJECT_INSTANCE = LoadAddr() + 0x09f0328 GET_PED_INSTANCE = LoadAddr() + 0x0156fc8 GET_VEHICLE_INSTANCE = LoadAddr() + 0x09f0390 -- Native Functions ADD_BLIP_TO_ENTITY = LoadAddr() + 0x0a243d0 ADD_TEXT_COMPONENT_SUBSTRING_PLAYER_NAME = LoadAddr() + 0x09f45dc BEGIN_TEXT_COMMAND_DISPLAY_TEXT = LoadAddr() + 0x0a39574 COS = LoadAddr() + 0x14fe72c CREATE_VEHICLE = LoadAddr() + 0x0cdbdec DECOR_EXIST_ON = LoadAddr() + 0x0a5caa8 DECOR_GET_INT = LoadAddr() + 0x0a5db04 DELETE_ENTITY = LoadAddr() + 0x0a3c408 DELETE_OBJECT = LoadAddr() + 0x0c8bf6c DELETE_PED = LoadAddr() + 0x0c8bffc DELETE_VEHICLE = LoadAddr() + 0x0cdc2f8 DISABLE_CONTROL_ACTION = LoadAddr() + 0x0c8c500 DISPLAY_ONSCREEN_KEYBOARD = LoadAddr() + 0x0a3c9f4 DOES_ENTITY_EXIST = LoadAddr() + 0x0a3cf28 DOES_EXTRA_EXIST = LoadAddr() + 0x0cdce88 DRAW_BOX = LoadAddr() + 0x0a3e7e0 DRAW_LINE = LoadAddr() + 0x0a3e8bc DRAW_NOTIFICATION = LoadAddr() + 0x09fbdd0 DRAW_POLY = LoadAddr() + 0x0a3e998 END_TEXT_COMMAND_DISPLAY_TEXT = LoadAddr() + 0x0a3fd84 EXPLODE_PED_HEAD = LoadAddr() + 0x0c8d2f8 EXPLODE_VEHICLE = LoadAddr() + 0x0cdda18 FREEZE_ENTITY_POSITION = LoadAddr() + 0x0a40eb0 GET_BLIP_FROM_ENTITY = LoadAddr() + 0x0a5d2d0 GET_CAM_COORD = LoadAddr() + 0x0a412c8 GET_CAM_ROT = LoadAddr() + 0x0a414b4 GET_DISPLAY_NAME_FROM_VEHICLE_MODEL = LoadAddr() + 0x0cde748 GET_ENTITY_BONE_INDEX_BY_NAME = LoadAddr() + 0x0a427cc GET_ENTITY_COORDS = LoadAddr() + 0x0a42c0c GET_ENTITY_FORWARD_X = LoadAddr() + 0x0a42cf0 GET_ENTITY_FORWARD_Y = LoadAddr() + 0x0a42d38 GET_ENTITY_HEADING = LoadAddr() + 0x0a42d80 GET_ENTITY_HEALTH = LoadAddr() + 0x0a42f24 GET_ENTITY_MATRIX = LoadAddr() + 0x0a434d0 GET_ENTITY_MAX_HEALTH = LoadAddr() + 0x0a435b8 GET_ENTITY_MODEL = LoadAddr() + 0x0a435dc GET_ENTITY_VELOCITY = LoadAddr() + 0x0a43e94 GET_GAMEPLAY_CAM_COORD = LoadAddr() + 0x0a45794 GET_GAMEPLAY_CAM_ROT = LoadAddr() + 0x0a457bc GET_GROUND_COORDINATES_WHILE_IN_AIR = LoadAddr() + 0x0a440d4 GET_GROUND_Z_FOR_3D_COORD = LoadAddr() + 0x0a443fc GET_HASH_KEY = LoadAddr() + 0x1229300 GET_LABEL_TEXT = LoadAddr() + 0x0a45fc4 GET_MODEL_DIMENSIONS = LoadAddr() + 0x0a44e6c GET_NEAREST_PLAYER_TO_ENTITY = LoadAddr() + 0x0a44fcc GET_ONSCREEN_KEYBOARD_RESULT = LoadAddr() + 0x07b38c0 GET_PED_ARMOUR = LoadAddr() + 0x0c90cd4 GET_PED_GROUP_INDEX = LoadAddr() + 0x0c91414 GET_PED_IN_VEHICLE_SEAT = LoadAddr() + 0x0cdfe20 GET_PED_NEARBY_PEDS = LoadAddr() + 0x0c8ff78 GET_PED_NEARBY_VEHICLES = LoadAddr() + 0x0c90044 GET_PLAYER_NAME = LoadAddr() + 0x0caf748 GET_PLAYER_PED = LoadAddr() + 0x0c91d5c GET_RENDERING_CAM = LoadAddr() + 0x0a459bc GET_SCREEN_COORD_FROM_WORLD_COORD = LoadAddr() + 0x0a45b10 GET_SHAPE_TEST_RESULT = LoadAddr() + 0x0ce090c GET_VEHICLE_CLASS = LoadAddr() + 0x0ce0ec8 GET_VEHICLE_COLOURS = LoadAddr() + 0x0ce11b4 GET_VEHICLE_EXTRA_COLOURS = LoadAddr() + 0x0ce14b0 GET_VEHICLE_NUMBER_OF_PASSENGERS = LoadAddr() + 0x0cdea04 GET_VEHICLE_NUMBER_PLATE_TEXT = LoadAddr() + 0x0ce2140 GET_VEHICLE_NUMBER_PLATE_TYPE = LoadAddr() + 0x0ce2164 GET_VEHICLE_PED_IS_IN = LoadAddr() + 0x0c9314c GET_VEHICLE_WINDOWS_TINT = LoadAddr() + 0x0ce2444 GET_WORLD_POSITION_OF_ENTITY_BONE = LoadAddr() + 0x0a462d0 GIVE_DELAYED_WEAPON_TO_PED = LoadAddr() + 0x0ce2e84 GIVE_WEAPON_COMPONENT_TO_PED = LoadAddr() + 0x0ce30b8 GIVE_WEAPON_TO_PED = LoadAddr() + 0x0ce32b4 HAS_ANIM_DICT_LOADED = LoadAddr() + 0x0d05d04 HAS_MODEL_LOADED = LoadAddr() + 0x0d05e38 HAS_WEAPON_ASSET_LOADED = LoadAddr() + 0x0d06224 IS_ENTITY_AN_OBJECT = LoadAddr() + 0x0a480dc IS_ENTITY_A_MISSION_ENTITY = LoadAddr() + 0x0a48064 IS_ENTITY_A_PED = LoadAddr() + 0x0a48094 IS_ENTITY_A_VEHICLE = LoadAddr() + 0x0a480b8 IS_ENTITY_DEAD = LoadAddr() + 0x0a4854c IS_HUD_ELEMENT_BEING_DISPLAYED = LoadAddr() + 0x01bd904 IS_HELP_MESSAGE_BEING_DISPLAYED = LoadAddr() + 0x0d17218 IS_PAUSE_MENU_ACTIVE = LoadAddr() + 0x01bc0c4 IS_PED_IN_ANY_VEHICLE = LoadAddr() + 0x0c964d0 IS_THIS_MODEL_A_BICYCLE = LoadAddr() + 0x0ce51ec IS_THIS_MODEL_A_BIKE = LoadAddr() + 0x0ce5234 IS_THIS_MODEL_A_BOAT = LoadAddr() + 0x0ce5280 IS_THIS_MODEL_A_CAR = LoadAddr() + 0x0ce52c8 IS_THIS_MODEL_A_HELI = LoadAddr() + 0x0ce5310 IS_THIS_MODEL_A_PLANE = LoadAddr() + 0x0ce53e8 IS_THIS_MODEL_A_QUADBIKE = LoadAddr() + 0x0ce5430 IS_THIS_MODEL_A_TRAIN = LoadAddr() + 0x0ce5480 IS_VEHICLE_EXTRA_TURNED_ON = LoadAddr() + 0x0ce5b78 IS_VEHICLE_ON_ALL_WHEELS = LoadAddr() + 0x0ce5cd4 IS_VEHICLE_SIREN_ON = LoadAddr() + 0x0ce5f1c IS_VEHICLE_STUCK_ON_ROOF = LoadAddr() + 0x0ce601c NETWORK_HASH_FROM_PLAYER_HANDLE = LoadAddr() + 0x0c9eb78 NETWORK_HAS_CONTROL_OF_ENTITY = LoadAddr() + 0x0c9e750 NETWORK_IS_HOST = LoadAddr() + 0x0fce570 NETWORK_IS_SESSION_STARTED = LoadAddr() + 0x0fcfca8 NETWORK_REQUEST_CONTROL_OF_ENTITY = LoadAddr() + 0x0ca06a8 PLAYER_ID = LoadAddr() + 0x0c91c2c REMOVE_ALL_PED_WEAPONS = LoadAddr() + 0x0ced55c REMOVE_ANIM_DICT = LoadAddr() + 0x0d073bc REMOVE_WEAPON_FROM_PED = LoadAddr() + 0x0cedb08 REQUEST_ANIM_DICT = LoadAddr() + 0x0d077d0 REQUEST_IPL = LoadAddr() + 0x0d078e4 REQUEST_MODEL = LoadAddr() + 0x0cedb6c REQUEST_WEAPON_ASSET = LoadAddr() + 0x0d07d70 SET_ENTITY_AS_MISSION_ENTITY = LoadAddr() + 0x0a50c18 SET_ENTITY_AS_NO_LONGER_NEEDED = LoadAddr() + 0x0a50ef4 SET_ENTITY_COLLISION = LoadAddr() + 0x0a5f99c SET_ENTITY_COORDS = LoadAddr() + 0x0a51164 SET_ENTITY_HEADING = LoadAddr() + 0x0a5175c SET_ENTITY_HEALTH = LoadAddr() + 0x0a51984 SET_ENTITY_INVINCIBLE = LoadAddr() + 0x0a51d68 SET_ENTITY_MAX_HEALTH = LoadAddr() + 0x3cf59f4 SET_ENTITY_VELOCITY = LoadAddr() + 0x0a52520 SET_ENTITY_VISIBLE = LoadAddr() + 0x0a52570 SET_MODEL_AS_NO_LONGER_NEEDED = LoadAddr() + 0x0ce7db4 SET_NOTIFICATION_TEXT_ENTRY = LoadAddr() + 0x09f57a0 SET_PED_ARMOUR = LoadAddr() + 0x0ca66fc SET_PED_AS_GROUP_MEMBER = LoadAddr() + 0x0ca6970 SET_PED_CAN_BE_KNOCKED_OFF_VEHICLE = LoadAddr() + 0x0ca6c38 SET_PED_CAN_BE_TARGETED = LoadAddr() + 0x0ca6d14 SET_PED_CAN_RAGDOLL = LoadAddr() + 0x0ca70a8 SET_PED_CAN_SWITCH_WEAPON = LoadAddr() + 0x0ca71b8 SET_PED_COMPONENT_VARIATION = LoadAddr() + 0x0ca73d0 SET_PED_DECORATION = LoadAddr() + 0x0c87a2c SET_PED_EYE_COLOUR = LoadAddr() + 0x079417c SET_PED_FACE_FEATURE = LoadAddr() + 0x0ca88c8 SET_PED_HAIR_COLOUR = LoadAddr() + 0x0ca80f0 SET_PED_HEAD_BLEND_DATA = LoadAddr() + 0x0ca8124 SET_PED_HEAD_OVERLAY = LoadAddr() + 0x0ca81f4 SET_PED_HEAD_OVERLAY_COLOUR = LoadAddr() + 0x0ca824c SET_PED_INTO_VEHICLE = LoadAddr() + 0x0ca85e8 SET_PED_MONEY = LoadAddr() + 0x0ca89dc SET_PED_PROP_INDEX = LoadAddr() + 0x0ca905c SET_PLAYER_INVINCIBLE = LoadAddr() + 0x0caaad0 SET_PLAYER_MODEL = LoadAddr() + 0x0c899a0 SET_PLAYER_WANTED_LEVEL = LoadAddr() + 0x0c880f8 SET_VEHICLE_COLOURS = LoadAddr() + 0x0cf2644 SET_VEHICLE_CUSTOM_PRIMARY_COLOUR = LoadAddr() + 0x0cf413c SET_VEHICLE_CUSTOM_SECONDARY_COLOUR = LoadAddr() + 0x0cf43b4 SET_VEHICLE_DASHBOARD_COLOUR = LoadAddr() + 0x0cf3530 SET_VEHICLE_DIRT_LEVEL = LoadAddr() + 0x0cf2a9c SET_VEHICLE_ENGINE_ON = LoadAddr() + 0x0cf3330 SET_VEHICLE_EXTRA = LoadAddr() + 0x0d02fc8 SET_VEHICLE_EXTRA_COLOURS = LoadAddr() + 0x0cf3574 SET_VEHICLE_FIXED = LoadAddr() + 0x0cf35d8 SET_VEHICLE_INTERIOR_COLOUR = LoadAddr() + 0x0cf34ec SET_VEHICLE_NEON_LIGHTS_COLOUR = LoadAddr() + 0x0cf3e70 SET_VEHICLE_NEON_LIGHT_ENABLED = LoadAddr() + 0x0cf3f08 SET_VEHICLE_NUMBER_PLATE_TEXT = LoadAddr() + 0x0cf3f9c SET_VEHICLE_NUMBER_PLATE_TYPE = LoadAddr() + 0x08ad58c SET_VEHICLE_ON_GROUND_PROPERLY = LoadAddr() + 0x0cf3fc8 SET_VEHICLE_RADIO_STATION = LoadAddr() + 0x0a54c44 SHOOT_SINGLE_BULLET_BETWEEN_COORDS = LoadAddr() + 0x0a40414 SHOW_HUD_COMPONENT_THIS_FRAME = LoadAddr() + 0x01f38a4 SIN = LoadAddr() + 0x14fe8b8 START_ENTITY_FIRE = LoadAddr() + 0x0a570e4 START_SHAPE_TEST_RAY = LoadAddr() + 0x0cf5598 STOP_ENTITY_FIRE = LoadAddr() + 0x0a57f54 UPDATE_ONSCREEN_KEYBOARD = LoadAddr() + 0x07cc534
mit
xdemolish/darkstar
scripts/zones/Northern_San_dOria/npcs/Bertenont.lua
19
1660
----------------------------------- -- Area: Northern San d'Oria -- NPC: Bertenont -- Involved in Quest: Lure of the Wildcat (San d'Oria) -- @pos -165 0.1 226 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if(trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatSandy = player:getVar("WildcatSandy"); if(player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,9) == false) then player:startEvent(0x0329); else player:showText(npc,BERTENONT_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if(csid == 0x0329) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",9,true); end end;
gpl-3.0
lukego/snabb
lib/ljsyscall/syscall/linux/c.lua
10
40227
-- This sets up the table of C functions -- this should be generated ideally, as it is the ABI spec --[[ Note a fair number are being deprecated, see include/uapi/asm-generic/unistd.h under __ARCH_WANT_SYSCALL_NO_AT, __ARCH_WANT_SYSCALL_NO_FLAGS, and __ARCH_WANT_SYSCALL_DEPRECATED Some of these we already don't use, but some we do, eg use open not openat etc. ]] local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string, select = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string, select local abi = require "syscall.abi" local ffi = require "ffi" local bit = require "syscall.bit" require "syscall.linux.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 h = require "syscall.helpers" local err64 = h.err64 local errpointer = h.errpointer local i6432, u6432 = bit.i6432, bit.u6432 local arg64, arg64u if abi.le then arg64 = function(val) local v2, v1 = i6432(val) return v1, v2 end arg64u = function(val) local v2, v1 = u6432(val) return v1, v2 end else arg64 = function(val) return i6432(val) end arg64u = function(val) return u6432(val) end end -- _llseek very odd, preadv local function llarg64u(val) return u6432(val) end local function llarg64(val) return i6432(val) end local C = {} local nr = require("syscall.linux.nr") local zeropad = nr.zeropad local sys = nr.SYS local socketcalls = nr.socketcalls local u64 = ffi.typeof("uint64_t") -- TODO could make these return errno here, also are these best casts? local syscall_long = ffi.C.syscall -- returns long local function syscall(...) return tonumber(syscall_long(...)) end -- int is default as most common local function syscall_uint(...) return uint(syscall_long(...)) end local function syscall_void(...) return void(syscall_long(...)) end local function syscall_off(...) return u64(syscall_long(...)) end -- off_t local longstype = ffi.typeof("long[?]") local function longs(...) local n = select('#', ...) local ll = ffi.new(longstype, n) for i = 1, n do ll[i - 1] = ffi.cast(long, select(i, ...)) end return ll end -- now for the system calls -- use 64 bit fileops on 32 bit always. As may be missing will use syscalls directly if abi.abi32 then if zeropad then function C.truncate(path, length) local len1, len2 = arg64u(length) return syscall(sys.truncate64, path, int(0), long(len1), long(len2)) end function C.ftruncate(fd, length) local len1, len2 = arg64u(length) return syscall(sys.ftruncate64, int(fd), int(0), long(len1), long(len2)) end function C.readahead(fd, offset, count) local off1, off2 = arg64u(offset) return syscall(sys.readahead, int(fd), int(0), long(off1), long(off2), ulong(count)) end function C.pread(fd, buf, size, offset) local off1, off2 = arg64(offset) return syscall_long(sys.pread64, int(fd), void(buf), ulong(size), int(0), long(off1), long(off2)) end function C.pwrite(fd, buf, size, offset) local off1, off2 = arg64(offset) return syscall_long(sys.pwrite64, int(fd), void(buf), ulong(size), int(0), long(off1), long(off2)) end else function C.truncate(path, length) local len1, len2 = arg64u(length) return syscall(sys.truncate64, path, long(len1), long(len2)) end function C.ftruncate(fd, length) local len1, len2 = arg64u(length) return syscall(sys.ftruncate64, int(fd), long(len1), long(len2)) end function C.readahead(fd, offset, count) local off1, off2 = arg64u(offset) return syscall(sys.readahead, int(fd), long(off1), long(off2), ulong(count)) end function C.pread(fd, buf, size, offset) local off1, off2 = arg64(offset) return syscall_long(sys.pread64, int(fd), void(buf), ulong(size), long(off1), long(off2)) end function C.pwrite(fd, buf, size, offset) local off1, off2 = arg64(offset) return syscall_long(sys.pwrite64, int(fd), void(buf), ulong(size), long(off1), long(off2)) end end -- note statfs,fstatfs pass size of struct on 32 bit only function C.statfs(path, buf) return syscall(sys.statfs64, void(path), uint(ffi.sizeof(buf)), void(buf)) end function C.fstatfs(fd, buf) return syscall(sys.fstatfs64, int(fd), uint(ffi.sizeof(buf)), void(buf)) end -- Note very odd split 64 bit arguments even on 64 bit platform. function C.preadv(fd, iov, iovcnt, offset) local off1, off2 = llarg64(offset) return syscall_long(sys.preadv, int(fd), void(iov), int(iovcnt), long(off2), long(off1)) end function C.pwritev(fd, iov, iovcnt, offset) local off1, off2 = llarg64(offset) return syscall_long(sys.pwritev, int(fd), void(iov), int(iovcnt), long(off2), long(off1)) end -- lseek is a mess in 32 bit, use _llseek syscall to get clean result. -- TODO move this to syscall.lua local off1 = ffi.typeof("uint64_t[1]") function C.lseek(fd, offset, whence) local result = off1() local off1, off2 = llarg64(offset) local ret = syscall(sys._llseek, int(fd), long(off1), long(off2), void(result), uint(whence)) if ret == -1 then return err64 end return result[0] end function C.sendfile(outfd, infd, offset, count) return syscall_long(sys.sendfile64, int(outfd), int(infd), void(offset), ulong(count)) end -- on 32 bit systems mmap uses off_t so we cannot tell what ABI is. Use underlying mmap2 syscall function C.mmap(addr, length, prot, flags, fd, offset) local pgoffset = bit.rshift(offset, 12) return syscall_void(sys.mmap2, void(addr), ulong(length), int(prot), int(flags), int(fd), uint(pgoffset)) end else -- 64 bit function C.truncate(path, length) return syscall(sys.truncate, void(path), ulong(length)) end function C.ftruncate(fd, length) return syscall(sys.ftruncate, int(fd), ulong(length)) end function C.readahead(fd, offset, count) return syscall(sys.readahead, int(fd), ulong(offset), ulong(count)) end function C.pread(fd, buf, count, offset) return syscall_long(sys.pread64, int(fd), void(buf), ulong(count), ulong(offset)) end function C.pwrite(fd, buf, count, offset) return syscall_long(sys.pwrite64, int(fd), void(buf), ulong(count), ulong(offset)) end function C.statfs(path, buf) return syscall(sys.statfs, void(path), void(buf)) end function C.fstatfs(fd, buf) return syscall(sys.fstatfs, int(fd), void(buf)) end function C.preadv(fd, iov, iovcnt, offset) return syscall_long(sys.preadv, int(fd), void(iov), long(iovcnt), ulong(offset)) end function C.pwritev(fd, iov, iovcnt, offset) return syscall_long(sys.pwritev, int(fd), void(iov), long(iovcnt), ulong(offset)) end function C.lseek(fd, offset, whence) return syscall_off(sys.lseek, int(fd), ulong(offset), int(whence)) end function C.sendfile(outfd, infd, offset, count) return syscall_long(sys.sendfile, int(outfd), int(infd), void(offset), ulong(count)) end function C.mmap(addr, length, prot, flags, fd, offset) return syscall_void(sys.mmap, void(addr), ulong(length), int(prot), int(flags), int(fd), ulong(offset)) end end -- glibc caches pid, but this fails to work eg after clone(). function C.getpid() return syscall(sys.getpid) end -- underlying syscalls function C.exit_group(status) return syscall(sys.exit_group, int(status)) end -- void return really function C.exit(status) return syscall(sys.exit, int(status)) end -- void return really C._exit = C.exit_group -- standard method -- clone interface provided is not same as system one, and is less convenient function C.clone(flags, signal, stack, ptid, tls, ctid) return syscall(sys.clone, int(flags), void(stack), void(ptid), void(tls), void(ctid)) -- technically long end -- getdents is not provided by glibc. Musl has weak alias so not visible. function C.getdents(fd, buf, size) return syscall(sys.getdents64, int(fd), buf, uint(size)) end -- glibc has request as an unsigned long, kernel is unsigned int, other libcs are int, so use syscall directly function C.ioctl(fd, request, arg) return syscall(sys.ioctl, int(fd), uint(request), void(arg)) end -- getcwd in libc may allocate memory and has inconsistent return value, so use syscall function C.getcwd(buf, size) return syscall(sys.getcwd, void(buf), ulong(size)) end -- nice in libc may or may not return old value, syscall never does; however nice syscall may not exist if sys.nice then function C.nice(inc) return syscall(sys.nice, int(inc)) end end -- avoid having to set errno by calling getpriority directly and adjusting return values function C.getpriority(which, who) return syscall(sys.getpriority, int(which), int(who)) end -- uClibc only provides a version of eventfd without flags, and we cannot detect this function C.eventfd(initval, flags) return syscall(sys.eventfd2, uint(initval), int(flags)) end -- Musl always returns ENOSYS for these function C.sched_getscheduler(pid) return syscall(sys.sched_getscheduler, int(pid)) end function C.sched_setscheduler(pid, policy, param) return syscall(sys.sched_setscheduler, int(pid), int(policy), void(param)) end local sys_fadvise64 = sys.fadvise64_64 or sys.fadvise64 if abi.abi64 then if sys.stat then function C.stat(path, buf) return syscall(sys.stat, path, void(buf)) end end if sys.lstat then function C.lstat(path, buf) return syscall(sys.lstat, path, void(buf)) end end function C.fstat(fd, buf) return syscall(sys.fstat, int(fd), void(buf)) end function C.fstatat(fd, path, buf, flags) return syscall(sys.fstatat, int(fd), path, void(buf), int(flags)) end function C.fadvise64(fd, offset, len, advise) return syscall(sys_fadvise64, int(fd), ulong(offset), ulong(len), int(advise)) end function C.fallocate(fd, mode, offset, len) return syscall(sys.fallocate, int(fd), uint(mode), ulong(offset), ulong(len)) end else function C.stat(path, buf) return syscall(sys.stat64, path, void(buf)) end function C.lstat(path, buf) return syscall(sys.lstat64, path, void(buf)) end function C.fstat(fd, buf) return syscall(sys.fstat64, int(fd), void(buf)) end function C.fstatat(fd, path, buf, flags) return syscall(sys.fstatat64, int(fd), path, void(buf), int(flags)) end if zeropad then function C.fadvise64(fd, offset, len, advise) local off1, off2 = arg64u(offset) local len1, len2 = arg64u(len) return syscall(sys_fadvise64, int(fd), 0, uint(off1), uint(off2), uint(len1), uint(len2), int(advise)) end else function C.fadvise64(fd, offset, len, advise) local off1, off2 = arg64u(offset) local len1, len2 = arg64u(len) return syscall(sys_fadvise64, int(fd), uint(off1), uint(off2), uint(len1), uint(len2), int(advise)) end end function C.fallocate(fd, mode, offset, len) local off1, off2 = arg64u(offset) local len1, len2 = arg64u(len) return syscall(sys.fallocate, int(fd), uint(mode), uint(off1), uint(off2), uint(len1), uint(len2)) end end -- native Linux aio not generally supported by libc, only posix API function C.io_setup(nr_events, ctx) return syscall(sys.io_setup, uint(nr_events), void(ctx)) end function C.io_destroy(ctx) return syscall(sys.io_destroy, ulong(ctx)) end function C.io_cancel(ctx, iocb, result) return syscall(sys.io_cancel, ulong(ctx), void(iocb), void(result)) end function C.io_getevents(ctx, min, nr, events, timeout) return syscall(sys.io_getevents, ulong(ctx), long(min), long(nr), void(events), void(timeout)) end function C.io_submit(ctx, iocb, nr) return syscall(sys.io_submit, ulong(ctx), long(nr), void(iocb)) end -- mq functions in -rt for glibc, plus syscalls differ slightly function C.mq_open(name, flags, mode, attr) return syscall(sys.mq_open, void(name), int(flags), uint(mode), void(attr)) end function C.mq_unlink(name) return syscall(sys.mq_unlink, void(name)) end function C.mq_getsetattr(mqd, new, old) return syscall(sys.mq_getsetattr, int(mqd), void(new), void(old)) end function C.mq_timedsend(mqd, msg_ptr, msg_len, msg_prio, abs_timeout) return syscall(sys.mq_timedsend, int(mqd), void(msg_ptr), ulong(msg_len), uint(msg_prio), void(abs_timeout)) end function C.mq_timedreceive(mqd, msg_ptr, msg_len, msg_prio, abs_timeout) return syscall(sys.mq_timedreceive, int(mqd), void(msg_ptr), ulong(msg_len), void(msg_prio), void(abs_timeout)) end if sys.mknod then function C.mknod(pathname, mode, dev) return syscall(sys.mknod, pathname, uint(mode), uint(dev)) end end function C.mknodat(fd, pathname, mode, dev) return syscall(sys.mknodat, int(fd), pathname, uint(mode), uint(dev)) end -- pivot_root is not provided by glibc, is provided by Musl function C.pivot_root(new_root, put_old) return syscall(sys.pivot_root, new_root, put_old) end -- setns not in some glibc versions function C.setns(fd, nstype) return syscall(sys.setns, int(fd), int(nstype)) end -- prlimit64 not in my ARM glibc function C.prlimit64(pid, resource, new_limit, old_limit) return syscall(sys.prlimit64, int(pid), int(resource), void(new_limit), void(old_limit)) end -- sched_setaffinity and sched_getaffinity not in Musl at the moment, use syscalls. Could test instead. function C.sched_getaffinity(pid, len, mask) return syscall(sys.sched_getaffinity, int(pid), uint(len), void(mask)) end function C.sched_setaffinity(pid, len, mask) return syscall(sys.sched_setaffinity, int(pid), uint(len), void(mask)) end -- sched_setparam and sched_getparam in Musl return ENOSYS, probably as they work on threads not processes. function C.sched_getparam(pid, param) return syscall(sys.sched_getparam, int(pid), void(param)) end function C.sched_setparam(pid, param) return syscall(sys.sched_setparam, int(pid), void(param)) end -- in librt for glibc but use syscalls instead of loading another library function C.clock_nanosleep(clk_id, flags, req, rem) return syscall(sys.clock_nanosleep, int(clk_id), int(flags), void(req), void(rem)) end function C.clock_getres(clk_id, ts) return syscall(sys.clock_getres, int(clk_id), void(ts)) end function C.clock_settime(clk_id, ts) return syscall(sys.clock_settime, int(clk_id), void(ts)) end -- glibc will not call this with a null path, which is needed to implement futimens in Linux function C.utimensat(fd, path, times, flags) return syscall(sys.utimensat, int(fd), void(path), void(times), int(flags)) end -- not in Android Bionic function C.linkat(olddirfd, oldpath, newdirfd, newpath, flags) return syscall(sys.linkat, int(olddirfd), void(oldpath), int(newdirfd), void(newpath), int(flags)) end function C.symlinkat(oldpath, newdirfd, newpath) return syscall(sys.symlinkat, void(oldpath), int(newdirfd), void(newpath)) end function C.readlinkat(dirfd, pathname, buf, bufsiz) return syscall(sys.readlinkat, int(dirfd), void(pathname), void(buf), ulong(bufsiz)) end function C.inotify_init1(flags) return syscall(sys.inotify_init1, int(flags)) end function C.adjtimex(buf) return syscall(sys.adjtimex, void(buf)) end function C.epoll_create1(flags) return syscall(sys.epoll_create1, int(flags)) end if sys.epoll_wait then function C.epoll_wait(epfd, events, maxevents, timeout) return syscall(sys.epoll_wait, int(epfd), void(events), int(maxevents), int(timeout)) end end function C.swapon(path, swapflags) return syscall(sys.swapon, void(path), int(swapflags)) end function C.swapoff(path) return syscall(sys.swapoff, void(path)) end function C.timerfd_create(clockid, flags) return syscall(sys.timerfd_create, int(clockid), int(flags)) end function C.timerfd_settime(fd, flags, new_value, old_value) return syscall(sys.timerfd_settime, int(fd), int(flags), void(new_value), void(old_value)) end function C.timerfd_gettime(fd, curr_value) return syscall(sys.timerfd_gettime, int(fd), void(curr_value)) end function C.splice(fd_in, off_in, fd_out, off_out, len, flags) return syscall(sys.splice, int(fd_in), void(off_in), int(fd_out), void(off_out), ulong(len), uint(flags)) end function C.tee(src, dest, len, flags) return syscall(sys.tee, int(src), int(dest), ulong(len), uint(flags)) end function C.vmsplice(fd, iovec, cnt, flags) return syscall(sys.vmsplice, int(fd), void(iovec), ulong(cnt), uint(flags)) end -- TODO note that I think these may be incorrect on 32 bit platforms, and strace is buggy if sys.sync_file_range then if abi.abi64 then function C.sync_file_range(fd, pos, len, flags) return syscall(sys.sync_file_range, int(fd), long(pos), long(len), uint(flags)) end else if zeropad then -- only on mips function C.sync_file_range(fd, pos, len, flags) local pos1, pos2 = arg64(pos) local len1, len2 = arg64(len) -- TODO these args appear to be reversed but is this mistaken/endianness/also true elsewhere? strace broken... return syscall(sys.sync_file_range, int(fd), 0, long(pos2), long(pos1), long(len2), long(len1), uint(flags)) end else function C.sync_file_range(fd, pos, len, flags) local pos1, pos2 = arg64(pos) local len1, len2 = arg64(len) return syscall(sys.sync_file_range, int(fd), long(pos1), long(pos2), long(len1), long(len2), uint(flags)) end end end elseif sys.sync_file_range2 then -- only on 32 bit platforms function C.sync_file_range(fd, pos, len, flags) local pos1, pos2 = arg64(pos) local len1, len2 = arg64(len) return syscall(sys.sync_file_range2, int(fd), uint(flags), long(pos1), long(pos2), long(len1), long(len2)) end end -- TODO this should be got from somewhere more generic -- started moving into linux/syscall.lua som explicit (see signalfd) but needs some more cleanups local sigset_size = 8 if abi.arch == "mips" or abi.arch == "mipsel" then sigset_size = 16 end local function sigmasksize(sigmask) local size = 0 if sigmask then size = sigset_size end return ulong(size) end function C.epoll_pwait(epfd, events, maxevents, timeout, sigmask) return syscall(sys.epoll_pwait, int(epfd), void(events), int(maxevents), int(timeout), void(sigmask), sigmasksize(sigmask)) end function C.ppoll(fds, nfds, timeout_ts, sigmask) return syscall(sys.ppoll, void(fds), ulong(nfds), void(timeout_ts), void(sigmask), sigmasksize(sigmask)) end function C.signalfd(fd, mask, size, flags) return syscall(sys.signalfd4, int(fd), void(mask), ulong(size), int(flags)) end -- adding more function C.dup(oldfd) return syscall(sys.dup, int(oldfd)) end if sys.dup2 then function C.dup2(oldfd, newfd) return syscall(sys.dup2, int(oldfd), int(newfd)) end end function C.dup3(oldfd, newfd, flags) return syscall(sys.dup3, int(oldfd), int(newfd), int(flags)) end if sys.chmod then function C.chmod(path, mode) return syscall(sys.chmod, void(path), uint(mode)) end end function C.fchmod(fd, mode) return syscall(sys.fchmod, int(fd), uint(mode)) end function C.umask(mode) return syscall(sys.umask, uint(mode)) end if sys.access then function C.access(path, mode) return syscall(sys.access, void(path), uint(mode)) end end function C.getppid() return syscall(sys.getppid) end function C.getuid() return syscall(sys.getuid) end function C.geteuid() return syscall(sys.geteuid) end function C.getgid() return syscall(sys.getgid) end function C.getegid() return syscall(sys.getegid) end function C.getresuid(ruid, euid, suid) return syscall(sys.getresuid, void(ruid), void(euid), void(suid)) end function C.getresgid(rgid, egid, sgid) return syscall(sys.getresgid, void(rgid), void(egid), void(sgid)) end function C.setuid(id) return syscall(sys.setuid, uint(id)) end function C.setgid(id) return syscall(sys.setgid, uint(id)) end function C.setresuid(ruid, euid, suid) return syscall(sys.setresuid, uint(ruid), uint(euid), uint(suid)) end function C.setresgid(rgid, egid, sgid) return syscall(sys.setresgid, uint(rgid), uint(egid), uint(sgid)) end function C.setreuid(uid, euid) return syscall(sys.setreuid, uint(uid), uint(euid)) end function C.setregid(gid, egid) return syscall(sys.setregid, uint(gid), uint(egid)) end function C.flock(fd, operation) return syscall(sys.flock, int(fd), int(operation)) end function C.getrusage(who, usage) return syscall(sys.getrusage, int(who), void(usage)) end if sys.rmdir then function C.rmdir(path) return syscall(sys.rmdir, void(path)) end end function C.chdir(path) return syscall(sys.chdir, void(path)) end function C.fchdir(fd) return syscall(sys.fchdir, int(fd)) end if sys.chown then function C.chown(path, owner, group) return syscall(sys.chown, void(path), uint(owner), uint(group)) end end function C.fchown(fd, owner, group) return syscall(sys.fchown, int(fd), uint(owner), uint(group)) end function C.lchown(path, owner, group) return syscall(sys.lchown, void(path), uint(owner), uint(group)) end if sys.open then function C.open(pathname, flags, mode) return syscall(sys.open, void(pathname), int(flags), uint(mode)) end end function C.openat(dirfd, pathname, flags, mode) return syscall(sys.openat, int(dirfd), void(pathname), int(flags), uint(mode)) end if sys.creat then function C.creat(pathname, mode) return syscall(sys.creat, void(pathname), uint(mode)) end end function C.close(fd) return syscall(sys.close, int(fd)) end function C.read(fd, buf, count) return syscall_long(sys.read, int(fd), void(buf), ulong(count)) end function C.write(fd, buf, count) return syscall_long(sys.write, int(fd), void(buf), ulong(count)) end function C.readv(fd, iov, iovcnt) return syscall_long(sys.readv, int(fd), void(iov), long(iovcnt)) end function C.writev(fd, iov, iovcnt) return syscall_long(sys.writev, int(fd), void(iov), long(iovcnt)) end if sys.readlink then function C.readlink(path, buf, bufsiz) return syscall_long(sys.readlink, void(path), void(buf), ulong(bufsiz)) end end if sys.rename then function C.rename(oldpath, newpath) return syscall(sys.rename, void(oldpath), void(newpath)) end end function C.renameat(olddirfd, oldpath, newdirfd, newpath) return syscall(sys.renameat, int(olddirfd), void(oldpath), int(newdirfd), void(newpath)) end if sys.renameat2 then function C.renameat2(olddirfd, oldpath, newdirfd, newpath, flags) return syscall(sys.renameat2, int(olddirfd), void(oldpath), int(newdirfd), void(newpath), int(flags)) end end if sys.unlink then function C.unlink(pathname) return syscall(sys.unlink, void(pathname)) end end function C.unlinkat(dirfd, pathname, flags) return syscall(sys.unlinkat, int(dirfd), void(pathname), int(flags)) end function C.prctl(option, arg2, arg3, arg4, arg5) return syscall(sys.prctl, int(option), ulong(arg2), ulong(arg3), ulong(arg4), ulong(arg5)) end if abi.arch ~= "mips" and abi.arch ~= "mipsel" and sys.pipe then -- mips uses old style dual register return calling convention that we cannot use function C.pipe(pipefd) return syscall(sys.pipe, void(pipefd)) end end function C.pipe2(pipefd, flags) return syscall(sys.pipe2, void(pipefd), int(flags)) end function C.pause() return syscall(sys.pause) end function C.remap_file_pages(addr, size, prot, pgoff, flags) return syscall(sys.remap_file_pages, void(addr), ulong(size), int(prot), long(pgoff), int(flags)) end if sys.fork then function C.fork() return syscall(sys.fork) end end function C.kill(pid, sig) return syscall(sys.kill, int(pid), int(sig)) end if sys.mkdir then function C.mkdir(pathname, mode) return syscall(sys.mkdir, void(pathname), uint(mode)) end end function C.fsync(fd) return syscall(sys.fsync, int(fd)) end function C.fdatasync(fd) return syscall(sys.fdatasync, int(fd)) end function C.sync() return syscall(sys.sync) end function C.syncfs(fd) return syscall(sys.syncfs, int(fd)) end if sys.link then function C.link(oldpath, newpath) return syscall(sys.link, void(oldpath), void(newpath)) end end if sys.symlink then function C.symlink(oldpath, newpath) return syscall(sys.symlink, void(oldpath), void(newpath)) end end function C.epoll_ctl(epfd, op, fd, event) return syscall(sys.epoll_ctl, int(epfd), int(op), int(fd), void(event)) end function C.uname(buf) return syscall(sys.uname, void(buf)) end function C.getsid(pid) return syscall(sys.getsid, int(pid)) end function C.getpgid(pid) return syscall(sys.getpgid, int(pid)) end function C.setpgid(pid, pgid) return syscall(sys.setpgid, int(pid), int(pgid)) end if sys.getpgrp then function C.getpgrp() return syscall(sys.getpgrp) end end function C.setsid() return syscall(sys.setsid) end function C.chroot(path) return syscall(sys.chroot, void(path)) end function C.mount(source, target, filesystemtype, mountflags, data) return syscall(sys.mount, void(source), void(target), void(filesystemtype), ulong(mountflags), void(data)) end function C.umount(target) return syscall(sys.umount, void(target)) end function C.umount2(target, flags) return syscall(sys.umount2, void(target), int(flags)) end function C.listxattr(path, list, size) return syscall_long(sys.listxattr, void(path), void(list), ulong(size)) end function C.llistxattr(path, list, size) return syscall_long(sys.llistxattr, void(path), void(list), ulong(size)) end function C.flistxattr(fd, list, size) return syscall_long(sys.flistxattr, int(fd), void(list), ulong(size)) end function C.setxattr(path, name, value, size, flags) return syscall(sys.setxattr, void(path), void(name), void(value), ulong(size), int(flags)) end function C.lsetxattr(path, name, value, size, flags) return syscall(sys.lsetxattr, void(path), void(name), void(value), ulong(size), int(flags)) end function C.fsetxattr(fd, name, value, size, flags) return syscall(sys.fsetxattr, int(fd), void(name), void(value), ulong(size), int(flags)) end function C.getxattr(path, name, value, size) return syscall_long(sys.getxattr, void(path), void(name), void(value), ulong(size)) end function C.lgetxattr(path, name, value, size) return syscall_long(sys.lgetxattr, void(path), void(name), void(value), ulong(size)) end function C.fgetxattr(fd, name, value, size) return syscall_long(sys.fgetxattr, int(fd), void(name), void(value), ulong(size)) end function C.removexattr(path, name) return syscall(sys.removexattr, void(path), void(name)) end function C.lremovexattr(path, name) return syscall(sys.lremovexattr, void(path), void(name)) end function C.fremovexattr(fd, name) return syscall(sys.fremovexattr, int(fd), void(name)) end function C.inotify_add_watch(fd, pathname, mask) return syscall(sys.inotify_add_watch, int(fd), void(pathname), uint(mask)) end function C.inotify_rm_watch(fd, wd) return syscall(sys.inotify_rm_watch, int(fd), int(wd)) end function C.unshare(flags) return syscall(sys.unshare, int(flags)) end function C.reboot(magic, magic2, cmd) return syscall(sys.reboot, int(magic), int(magic2), int(cmd)) end function C.sethostname(name, len) return syscall(sys.sethostname, void(name), ulong(len)) end function C.setdomainname(name, len) return syscall(sys.setdomainname, void(name), ulong(len)) end function C.getitimer(which, curr_value) return syscall(sys.getitimer, int(which), void(curr_value)) end function C.setitimer(which, new_value, old_value) return syscall(sys.setitimer, int(which), void(new_value), void(old_value)) end function C.sched_yield() return syscall(sys.sched_yield) end function C.acct(filename) return syscall(sys.acct, void(filename)) end function C.munmap(addr, length) return syscall(sys.munmap, void(addr), ulong(length)) end function C.faccessat(dirfd, path, mode, flags) return syscall(sys.faccessat, int(dirfd), void(path), uint(mode), int(flags)) end function C.fchmodat(dirfd, path, mode, flags) return syscall(sys.fchmodat, int(dirfd), void(path), uint(mode), int(flags)) end function C.mkdirat(dirfd, pathname, mode) return syscall(sys.mkdirat, int(dirfd), void(pathname), uint(mode)) end function C.fchownat(dirfd, pathname, owner, group, flags) return syscall(sys.fchownat, int(dirfd), void(pathname), uint(owner), uint(group), int(flags)) end function C.setpriority(which, who, prio) return syscall(sys.setpriority, int(which), int(who), int(prio)) end function C.sched_get_priority_min(policy) return syscall(sys.sched_get_priority_min, int(policy)) end function C.sched_get_priority_max(policy) return syscall(sys.sched_get_priority_max, int(policy)) end function C.sched_rr_get_interval(pid, tp) return syscall(sys.sched_rr_get_interval, int(pid), void(tp)) end if sys.poll then function C.poll(fds, nfds, timeout) return syscall(sys.poll, void(fds), int(nfds), int(timeout)) end end function C.msync(addr, length, flags) return syscall(sys.msync, void(addr), ulong(length), int(flags)) end function C.madvise(addr, length, advice) return syscall(sys.madvise, void(addr), ulong(length), int(advice)) end function C.mlock(addr, len) return syscall(sys.mlock, void(addr), ulong(len)) end function C.munlock(addr, len) return syscall(sys.munlock, void(addr), ulong(len)) end function C.mlockall(flags) return syscall(sys.mlockall, int(flags)) end function C.munlockall() return syscall(sys.munlockall) end function C.capget(hdrp, datap) return syscall(sys.capget, void(hdrp), void(datap)) end function C.capset(hdrp, datap) return syscall(sys.capset, void(hdrp), void(datap)) end function C.sysinfo(info) return syscall(sys.sysinfo, void(info)) end function C.execve(filename, argv, envp) return syscall(sys.execve, void(filename), void(argv), void(envp)) end function C.getgroups(size, list) return syscall(sys.getgroups, int(size), void(list)) end function C.setgroups(size, list) return syscall(sys.setgroups, int(size), void(list)) end function C.klogctl(tp, bufp, len) return syscall(sys.syslog, int(tp), void(bufp), int(len)) end function C.sigprocmask(how, set, oldset) return syscall(sys.rt_sigprocmask, int(how), void(set), void(oldset), sigmasksize(set or oldset)) end function C.sigpending(set) return syscall(sys.rt_sigpending, void(set), sigmasksize(set)) end function C.mremap(old_address, old_size, new_size, flags, new_address) return syscall_void(sys.mremap, void(old_address), ulong(old_size), ulong(new_size), int(flags), void(new_address)) end function C.nanosleep(req, rem) return syscall(sys.nanosleep, void(req), void(rem)) end function C.wait4(pid, status, options, rusage) return syscall(sys.wait4, int(pid), void(status), int(options), void(rusage)) end function C.waitid(idtype, id, infop, options, rusage) return syscall(sys.waitid, int(idtype), uint(id), void(infop), int(options), void(rusage)) end function C.settimeofday(tv, tz) return syscall(sys.settimeofday, void(tv), void(tz)) end function C.timer_create(clockid, sevp, timerid) return syscall(sys.timer_create, int(clockid), void(sevp), void(timerid)) end function C.timer_settime(timerid, flags, new_value, old_value) return syscall(sys.timer_settime, int(timerid), int(flags), void(new_value), void(old_value)) end function C.timer_gettime(timerid, curr_value) return syscall(sys.timer_gettime, int(timerid), void(curr_value)) end function C.timer_delete(timerid) return syscall(sys.timer_delete, int(timerid)) end function C.timer_getoverrun(timerid) return syscall(sys.timer_getoverrun, int(timerid)) end -- only on some architectures if sys.waitpid then function C.waitpid(pid, status, options) return syscall(sys.waitpid, int(pid), void(status), int(options)) end end -- fcntl needs a cast as last argument may be int or pointer local fcntl = sys.fcntl64 or sys.fcntl function C.fcntl(fd, cmd, arg) return syscall(fcntl, int(fd), int(cmd), ffi.cast(long, arg)) end function C.pselect(nfds, readfds, writefds, exceptfds, timeout, sigmask) local size = 0 if sigmask then size = sigset_size end local data = longs(void(sigmask), size) return syscall(sys.pselect6, int(nfds), void(readfds), void(writefds), void(exceptfds), void(timeout), void(data)) end -- need _newselect syscall on some platforms local sysselect = sys._newselect or sys.select if sysselect then function C.select(nfds, readfds, writefds, exceptfds, timeout) return syscall(sysselect, int(nfds), void(readfds), void(writefds), void(exceptfds), void(timeout)) end end -- missing on some platforms eg ARM if sys.alarm then function C.alarm(seconds) return syscall(sys.alarm, uint(seconds)) end end -- new system calls, may be missing TODO fix so is not if sys.getrandom then function C.getrandom(buf, count, flags) return syscall(sys.getrandom, void(buf), uint(count), uint(flags)) end end if sys.memfd_create then function C.memfd_create(name, flags) return syscall(sys.memfd_create, void(name), uint(flags)) end end -- kernel sigaction structures actually rather different in Linux from libc ones function C.sigaction(signum, act, oldact) return syscall(sys.rt_sigaction, int(signum), void(act), void(oldact), ulong(sigset_size)) -- size is size of sigset field end -- in VDSO for many archs, so use ffi for speed; TODO read VDSO to find functions there, needs elf reader if pcall(function(k) return ffi.C[k] end, "clock_gettime") then C.clock_gettime = ffi.C.clock_gettime else function C.clock_gettime(clk_id, ts) return syscall(sys.clock_gettime, int(clk_id), void(ts)) end end C.gettimeofday = ffi.C.gettimeofday --function C.gettimeofday(tv, tz) return syscall(sys.gettimeofday, void(tv), void(tz)) end -- glibc does not provide getcpu; it is however VDSO function C.getcpu(cpu, node, tcache) return syscall(sys.getcpu, void(node), void(node), void(tcache)) end -- time is VDSO but not really performance critical; does not exist for some architectures if sys.time then function C.time(t) return syscall(sys.time, void(t)) end end -- socketcalls if not sys.socketcall then function C.socket(domain, tp, protocol) return syscall(sys.socket, int(domain), int(tp), int(protocol)) end function C.bind(sockfd, addr, addrlen) return syscall(sys.bind, int(sockfd), void(addr), uint(addrlen)) end function C.connect(sockfd, addr, addrlen) return syscall(sys.connect, int(sockfd), void(addr), uint(addrlen)) end function C.listen(sockfd, backlog) return syscall(sys.listen, int(sockfd), int(backlog)) end function C.accept(sockfd, addr, addrlen) return syscall(sys.accept, int(sockfd), void(addr), void(addrlen)) end function C.getsockname(sockfd, addr, addrlen) return syscall(sys.getsockname, int(sockfd), void(addr), void(addrlen)) end function C.getpeername(sockfd, addr, addrlen) return syscall(sys.getpeername, int(sockfd), void(addr), void(addrlen)) end function C.socketpair(domain, tp, protocol, sv) return syscall(sys.socketpair, int(domain), int(tp), int(protocol), void(sv)) end function C.send(sockfd, buf, len, flags) return syscall_long(sys.send, int(sockfd), void(buf), ulong(len), int(flags)) end function C.recv(sockfd, buf, len, flags) return syscall_long(sys.recv, int(sockfd), void(buf), ulong(len), int(flags)) end function C.sendto(sockfd, buf, len, flags, dest_addr, addrlen) return syscall_long(sys.sendto, int(sockfd), void(buf), ulong(len), int(flags), void(dest_addr), uint(addrlen)) end function C.recvfrom(sockfd, buf, len, flags, src_addr, addrlen) return syscall_long(sys.recvfrom, int(sockfd), void(buf), ulong(len), int(flags), void(src_addr), void(addrlen)) end function C.shutdown(sockfd, how) return syscall(sys.shutdown, int(sockfd), int(how)) end function C.setsockopt(sockfd, level, optname, optval, optlen) return syscall(sys.setsockopt, int(sockfd), int(level), int(optname), void(optval), uint(optlen)) end function C.getsockopt(sockfd, level, optname, optval, optlen) return syscall(sys.getsockopt, int(sockfd), int(level), int(optname), void(optval), void(optlen)) end function C.sendmsg(sockfd, msg, flags) return syscall_long(sys.sendmsg, int(sockfd), void(msg), int(flags)) end function C.recvmsg(sockfd, msg, flags) return syscall_long(sys.recvmsg, int(sockfd), void(msg), int(flags)) end function C.accept4(sockfd, addr, addrlen, flags) return syscall(sys.accept4, int(sockfd), void(addr), void(addrlen), int(flags)) end function C.recvmmsg(sockfd, msgvec, vlen, flags, timeout) return syscall(sys.recvmmsg, int(sockfd), void(msgvec), uint(vlen), int(flags), void(timeout)) end function C.sendmmsg(sockfd, msgvec, vlen, flags) return syscall(sys.sendmmsg, int(sockfd), void(msgvec), uint(vlen), int(flags)) end else function C.socket(domain, tp, protocol) local args = longs(domain, tp, protocol) return syscall(sys.socketcall, int(socketcalls.SOCKET), void(args)) end function C.bind(sockfd, addr, addrlen) local args = longs(sockfd, void(addr), addrlen) return syscall(sys.socketcall, int(socketcalls.BIND), void(args)) end function C.connect(sockfd, addr, addrlen) local args = longs(sockfd, void(addr), addrlen) return syscall(sys.socketcall, int(socketcalls.CONNECT), void(args)) end function C.listen(sockfd, backlog) local args = longs(sockfd, backlog) return syscall(sys.socketcall, int(socketcalls.LISTEN), void(args)) end function C.accept(sockfd, addr, addrlen) local args = longs(sockfd, void(addr), void(addrlen)) return syscall(sys.socketcall, int(socketcalls.ACCEPT), void(args)) end function C.getsockname(sockfd, addr, addrlen) local args = longs(sockfd, void(addr), void(addrlen)) return syscall(sys.socketcall, int(socketcalls.GETSOCKNAME), void(args)) end function C.getpeername(sockfd, addr, addrlen) local args = longs(sockfd, void(addr), void(addrlen)) return syscall(sys.socketcall, int(socketcalls.GETPEERNAME), void(args)) end function C.socketpair(domain, tp, protocol, sv) local args = longs(domain, tp, protocol, void(sv)) return syscall(sys.socketcall, int(socketcalls.SOCKETPAIR), void(args)) end function C.send(sockfd, buf, len, flags) local args = longs(sockfd, void(buf), len, flags) return syscall_long(sys.socketcall, int(socketcalls.SEND), void(args)) end function C.recv(sockfd, buf, len, flags) local args = longs(sockfd, void(buf), len, flags) return syscall_long(sys.socketcall, int(socketcalls.RECV), void(args)) end function C.sendto(sockfd, buf, len, flags, dest_addr, addrlen) local args = longs(sockfd, void(buf), len, flags, void(dest_addr), addrlen) return syscall_long(sys.socketcall, int(socketcalls.SENDTO), void(args)) end function C.recvfrom(sockfd, buf, len, flags, src_addr, addrlen) local args = longs(sockfd, void(buf), len, flags, void(src_addr), void(addrlen)) return syscall_long(sys.socketcall, int(socketcalls.RECVFROM), void(args)) end function C.shutdown(sockfd, how) local args = longs(sockfd, how) return syscall(sys.socketcall, int(socketcalls.SHUTDOWN), void(args)) end function C.setsockopt(sockfd, level, optname, optval, optlen) local args = longs(sockfd, level, optname, void(optval), optlen) return syscall(sys.socketcall, int(socketcalls.SETSOCKOPT), void(args)) end function C.getsockopt(sockfd, level, optname, optval, optlen) local args = longs(sockfd, level, optname, void(optval), void(optlen)) return syscall(sys.socketcall, int(socketcalls.GETSOCKOPT), void(args)) end function C.sendmsg(sockfd, msg, flags) local args = longs(sockfd, void(msg), flags) return syscall_long(sys.socketcall, int(socketcalls.SENDMSG), void(args)) end function C.recvmsg(sockfd, msg, flags) local args = longs(sockfd, void(msg), flags) return syscall_long(sys.socketcall, int(socketcalls.RECVMSG), void(args)) end function C.accept4(sockfd, addr, addrlen, flags) local args = longs(sockfd, void(addr), void(addrlen), flags) return syscall(sys.socketcall, int(socketcalls.ACCEPT4), void(args)) end function C.recvmmsg(sockfd, msgvec, vlen, flags, timeout) local args = longs(sockfd, void(msgvec), vlen, flags, void(timeout)) return syscall(sys.socketcall, int(socketcalls.RECVMMSG), void(args)) end function C.sendmmsg(sockfd, msgvec, vlen, flags) local args = longs(sockfd, void(msgvec), vlen, flags) return syscall(sys.socketcall, int(socketcalls.SENDMMSG), void(args)) end end return C
apache-2.0
hsiaoyi/Melo
cocos2d/cocos/scripting/lua-bindings/auto/api/PositionFrame.lua
18
1745
-------------------------------- -- @module PositionFrame -- @extend Frame -- @parent_module ccs -------------------------------- -- -- @function [parent=#PositionFrame] getX -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#PositionFrame] getY -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#PositionFrame] setPosition -- @param self -- @param #vec2_table position -- @return PositionFrame#PositionFrame self (return value: ccs.PositionFrame) -------------------------------- -- -- @function [parent=#PositionFrame] setX -- @param self -- @param #float x -- @return PositionFrame#PositionFrame self (return value: ccs.PositionFrame) -------------------------------- -- -- @function [parent=#PositionFrame] setY -- @param self -- @param #float y -- @return PositionFrame#PositionFrame self (return value: ccs.PositionFrame) -------------------------------- -- -- @function [parent=#PositionFrame] getPosition -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- -- @function [parent=#PositionFrame] create -- @param self -- @return PositionFrame#PositionFrame ret (return value: ccs.PositionFrame) -------------------------------- -- -- @function [parent=#PositionFrame] clone -- @param self -- @return Frame#Frame ret (return value: ccs.Frame) -------------------------------- -- -- @function [parent=#PositionFrame] PositionFrame -- @param self -- @return PositionFrame#PositionFrame self (return value: ccs.PositionFrame) return nil
apache-2.0