content
stringlengths 5
1.05M
|
---|
require 'common'
local zone_30 = {}
--------------------------------------------------
-- Map Callbacks
--------------------------------------------------
function zone_30.Init(zone)
DEBUG.EnableDbgCoro() --Enable debugging this coroutine
PrintInfo("=>> Init_zone_30")
end
function zone_30.Rescued(zone, name, mail)
COMMON.Rescued(zone, name, mail)
end
function zone_30.EnterSegment(zone, rescuing, segmentID, mapID)
if rescuing ~= true then
COMMON.BeginDungeon(zone.ID, segmentID, mapID)
end
end
function zone_30.ExitSegment(zone, result, rescue, segmentID, mapID)
DEBUG.EnableDbgCoro() --Enable debugging this coroutine
PrintInfo("=>> ExitSegment_zone_30 result "..tostring(result).." segment "..tostring(segmentID))
--first check for rescue flag; if we're in rescue mode then take a different path
COMMON.ExitDungeonMissionCheck(zone.ID, segmentID)
if rescue == true then
COMMON.EndRescue(zone, result, segmentID)
elseif result ~= RogueEssence.Data.GameProgress.ResultType.Cleared then
COMMON.EndDungeonDay(result, SV.checkpoint.Zone, SV.checkpoint.Segment, SV.checkpoint.Map, SV.checkpoint.Entry)
else
if segmentID == 0 then
if GAME:InRogueMode() then
COMMON.EndDungeonDay(result, 1,-1,1,0)
else
GAME:EnterZone(30, -1, 0, 0)
end
else
PrintInfo("No exit procedure found!")
COMMON.EndDungeonDay(result, SV.checkpoint.Zone, SV.checkpoint.Segment, SV.checkpoint.Map, SV.checkpoint.Entry)
end
end
end
return zone_30
|
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
keywordHandler:addKeyword({'offer'}, StdModule.say, {npcHandler = npcHandler, text = "Well, I sell freshly caught fish. You like some? Of course, you can buy more than one at once. *grin* Just ask me for a {trade}."})
keywordHandler:addKeyword({'buy'}, StdModule.say, {npcHandler = npcHandler, text = "Well, I sell freshly caught fish. You like some? Of course, you can buy more than one at once. *grin* Just ask me for a {trade}."})
keywordHandler:addKeyword({'fish'}, StdModule.say, {npcHandler = npcHandler, text = "Well, I sell freshly caught fish. You like some? Of course, you can buy more than one at once. *grin* Just ask me for a {trade}."})
keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, text = "My name is Bruno."})
keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, text = "My job is to catch fish and to sell them here."})
keywordHandler:addKeyword({'marlene'}, StdModule.say, {npcHandler = npcHandler, text = "Ah yes, my lovely wife. God forgive her, but she can't stop talking. So my work is a great rest for my poor ears. *laughs loudly*"})
keywordHandler:addKeyword({'graubart'}, StdModule.say, {npcHandler = npcHandler, text = "I like this old salt. I learned much from him. Whatever. You like some fish? *grin*"})
npcHandler:setMessage(MESSAGE_GREET, "Ahoi, |PLAYERNAME|. You want to buy some fresh fish?")
npcHandler:setMessage(MESSAGE_FAREWELL, "Good bye and come again!")
npcHandler:setMessage(MESSAGE_SENDTRADE, "Buy all the fish you want. It's fresh and healthy, promised.")
npcHandler:addModule(FocusModule:new())
|
-- << init_state.lua
local wesnoth = wesnoth
local addon = creepwars
local ipairs = ipairs
local is_ai_array = addon.is_ai_array
local on_event = wesnoth.require("lua/on_event.lua")
-- kill auto-generated AI leaders (not guards)
for _, unit in ipairs(wesnoth.get_units { canrecruit = true }) do
if is_ai_array[unit.side] and unit.max_moves > 1 then
wesnoth.wml_actions.kill {
id = unit.id,
fire_event = false,
animate = false,
}
end
end
for _, guard in ipairs(addon.guards_pos) do
local unit = {
side = guard.side,
type = "Elvish Marshal",
name = "Guard",
max_moves = 0,
max_hitpoints = 60 * creepwars.guard_health_percentage / 100,
max_experience = 100000,
random_traits = false,
canrecruit = true,
{ "defense", { castle = 50, } },
}
wesnoth.put_unit(unit, guard.x, guard.y)
end
for _, side in ipairs(wesnoth.sides) do
side.recruit = {}
end
on_event("start", function()
for _, team in ipairs(addon.team_array) do
local active = addon.array_filter(team, function(s)
return #wesnoth.get_units { canrecruit = true, side = s.side } > 0
end)
for _, side in ipairs(team) do
side.gold = side.gold * (6 - #active) / 2
end
end
end)
-- >>
|
local a=module('_core','libs/Tunnel')local b=module('_core','libs/Proxy')APICKF=b.getInterface('API')cAPI=a.getInterface('cAPI')Citizen.CreateThread(function()while true do Citizen.Wait(5*60*1000)collectgarbage("count")collectgarbage("collect")end end)RegisterNetEvent("hoppe:return:item")AddEventHandler("hoppe:return:item",function(c)local d=source;local e=APICKF.getUserFromSource(d)if e then local f=e:getCharacter()if f then local g=parseInt(f.id)print("item returned")f:addItem(c,1)end end end)RegisterCommand('e',function(source,h,i)TriggerClientEvent("emotes:cancelevent",source,h[1])end)RegisterNetEvent("hoppe:e2:anim")AddEventHandler("hoppe:e2:anim",function(j,k)local d=source;local e=APICKF.getUserFromSource(d)if e then local f=e:getCharacter()if f then if f:hasGroup("admin")then TriggerClientEvent("hoppe:e2:anim",k,j)end end end end)RegisterServerEvent("tryclean")AddEventHandler("tryclean",function(l)TriggerClientEvent("syncclean",-1,l)end) |
--[[
定时器Proxy,用于处理游戏中需要定时操作的逻辑
提供了添加和移除定时器的接口
--]]
local TimerProxy = class("TimerProxy")
local TAG = "<TimerProxy | "
local _scheduler = cc.Director:getInstance():getScheduler()
local TIMER_STATUS = {
INIT = "timer_init";
DELAY = "timer_delay";
RUNNING = "timer_running";
FINISH = "timer_finished";
}
function TimerProxy:ctor()
-- body
self._timers = {}
local timer_init_, timer_delay_, timer_running_; --[[, timer_finish_--]]
timer_init_ = function (timer, dt)
-- body
if timer.delay then
timer._status = TIMER_STATUS.DELAY
timer._elapseDelay = timer.delay
return timer_delay_(timer, dt)
end
timer._status = TIMER_STATUS.RUNNING
timer._elapse = timer.interval
return timer_running_(timer, dt)
end
timer_delay_ = function (timer, dt)
-- body
timer._elapseDelay = timer._elapseDelay - dt
if timer._elapseDelay > 0.0 then
return
end
timer._status = TIMER_STATUS.RUNNING
timer._elapse = timer.interval
-- timer_running_(timer, dt)
end
timer_running_ = function (timer, dt)
-- body
timer._elapse = timer._elapse - dt
if timer._elapse > 0.0 then
return
end
timer._elapse = timer.interval
timer._usedTimes = timer._usedTimes + 1
if timer.callback then
timer.callback(timer.tag)
end
if timer._usedTimes >= timer.times then
timer._status = TIMER_STATUS.FINISH
-- return timer_finish_(timer, dt)
end
end
--[[
timer_finish_ = function (timer, dt)
-- body
if self._timers[timer.tag] then
self._timers[timer.tag] = nil
end
end
--]]
local function timer_validate_()
-- body
for k, v in pairs(self._timers) do
if v._status == TIMER_STATUS.FINISH then
self._timers[k] = nil
end
end
end
local function timer_update_(timer, dt)
-- body
if timer._status == TIMER_STATUS.INIT then
return timer_init_(timer, dt)
end
if timer._status == TIMER_STATUS.DELAY then
return timer_delay_(timer, dt)
end
if timer._status == TIMER_STATUS.RUNNING then
return timer_running_(timer, dt)
end
if timer._status == TIMER_STATUS.FINISH then
-- nothing to do
-- return timer_finish_(timer, dt)
return
end
print(TAG .. "Timer_update_ - timer status error.")
end
local function scheduleUpdate_(dt)
-- body
for _, v in pairs(self._timers) do
-- print(TAG .. "scheduleUpdate_ - called." .. dt)
timer_update_(v, dt)
end
timer_validate_()
end
self._schedulerEntry = _scheduler:scheduleScriptFunc(scheduleUpdate_, 0.0, false)
end
--[[
添加定时器
timerTag - 定时器标识,建议使用字符串进行标识
callback - 定时器回调函数
interval - 定时器间隔时间,默认(不填时)为0.0的间隔,即一帧执行一次
times - 定时器重复定数,0次为无效定时器,负数次则为无限重复定时器,默认(不填时)为1次
delay - 延时多长时间开始定时,默认(不填时)为立即开始
--]]
function TimerProxy:addTimer(timerTag, callback, interval, times, delay)
-- body
assert(timerTag, "timerTag is error.")
assert(type(callback) == "function", "Timer callback error.")
if self._timers[timerTag] then
print(TAG .. "addTimer - timerTag is existed.")
return false
end
interval = interval or 0.0
interval = tonumber(interval)
if interval < 0.0 then
interval = 0.0
end
times = times or 1
times = math.ceil(tonumber(times))
if times == 0 then
print(TAG .. "addTimer - times error with 0")
return
end
if times < 0 then
times = math.huge
end
delay = delay or false
if delay ~= false then
delay = tonumber(delay)
if delay < 0.0 then
delay = false
end
end
self._timers[timerTag] = {
tag = timerTag;
interval = interval;
times = times;
callback = callback;
delay = delay;
_status = TIMER_STATUS.INIT;
_elapse = 0;
_usedTimes = 0;
_elapseDelay = 0;
}
return true
end
--[[
移除指定的定时器
timerTag - 调用addTimer时传入的timerTag值
--]]
function TimerProxy:removeTimer(timerTag)
-- body
if self._timers[timerTag] then
self._timers[timerTag] = nil
end
end
--[[
查询指定的定时器是否有效
timerTag - 调用addTimer时传入的timerTag值
--]]
function TimerProxy:hasTimer(timerTag)
-- body
if self._timers[timerTag] then
return true
end
return false
end
function TimerProxy:finalizer()
-- body
_scheduler:unscheduleScriptEntry(self._schedulerEntry)
end
cc.exports.TimerProxy = cc.exports.TimerProxy or TimerProxy:create()
return cc.exports.TimerProxy |
name = "Leveling: Route 6 (near Vermilion)"
author = "Liquid"
description = [[This script will train the first pokémon of your team.
It will also try to capture shinies by throwing pokéballs.
Start anywhere between Vermilion City and Route 6.]]
local team = require "teamlib"
local maxLv = 100
local listVermilion_1 = "36-22,36-19,38-19,38-11,43-11,43-0"
local listVermilion_2 = "43-11,38-11,38-22,27-21"
local list_1_1 = "27-53,27-45,36-45,36-31,13-30,13-23,26-23,26-21,34-21,34-25,34-45,23-45,23-50,19-50,19-52,0-52"
local list_1_2 = "19-53,23-50,23-45,36-45,36-31,13-30,13-23,26-23,26-21,34-21,34-25,34-45,23-45,23-50,19-50,19-52,0-52"
local list_2 = "57-32,57-34,53-34,53-35,52-35,52-36,43-36,43-30,42-30,42-26,32-19,32-28,42-27,42-36,52-36,55-33,60-33"
function onStart()
return team.onStart(maxLv)
end
function onPathAction()
while not isTeamSortedByLevelAscending() and getOption(4) do
return sortTeamByLevelAscending()
end
if team.isTrainingOver(maxLv) and not team.isSearching() then
return logout("Complete training! Stop the bot.")
end
if team.useLeftovers() then
return
end
if getUsablePokemonCount() > 1
and (getPokemonLevel(team.getLowestIndexOfUsablePokemon()) < maxLv
or team.isSearching())
then
x = getPlayerX()
y = getPlayerY()
if getMapName() == "Pokecenter Vermilion" then
moveToCell(9,22)
elseif getMapName() == "Vermilion City" then
moveToListCell(listVermilion_1)
elseif getMapName() == "Route 6" then
if x == 0 and y == 53 then
moveToListCell(list_1_2)
else
moveToListCell(list_1_1)
end
elseif getMapName() == "Vermilion City Graveyard" then
moveToListCell(list_2)
elseif getMapName() == "Prof. Antibans Classroom" then
return team.antibanclassroom()
end
else
if getMapName() == "Vermilion City Graveyard" then
moveToCell(60,33)
elseif getMapName() == "Route 6" then
moveToCell(23,61)
elseif getMapName() == "Vermilion City" then
moveToListCell(listVermilion_2)
elseif getMapName() == "Pokecenter Vermilion" then
usePokecenter()
elseif getMapName() == "Prof. Antibans Classroom" then
return team.antibanclassroom()
end
end
end
function onBattleAction()
return team.onBattleFighting()
end
function onStop()
return team.onStop()
end
function onBattleMessage(message)
return team.onBattleMessage(message)
end
function onDialogMessage(message)
return team.onAntibanDialogMessage(message)
end
function onSystemMessage(message)
return team.onSystemMessage(message)
end |
-- (c) 2009-2011 John MacFarlane. Released under MIT license.
-- See the file LICENSE in the source for details.
--- Provides access to all lunamark writers without preloading
-- them. Writer modules are loaded only when needed.
--
-- local writers = require("lunamark.writer")
-- local htmlwriter = writers.html -- html writer loaded now
-- local myformat = 'latex'
-- local mywriter = writers[myformat] -- latex writer loaded now
local G = {}
setmetatable(G,{ __index = function(t,name)
local mod = require("lunamark.writer." .. name)
rawset(t,name,mod)
return t[name]
end })
return G
|
local version = luajava.bindClass("android.os.Build").VERSION.SDK_INT;
local function autotheme()
local h=tonumber(os.date("%H"))
--h=0
if version >= 21 then
if h<=6 or h>=22 then
return (android.R.style.Theme_Material)
else
return (android.R.style.Theme_Material_Light)
end
else
if h<=6 or h>=22 then
return (android.R.style.Theme_Holo)
else
return (android.R.style.Theme_Holo_Light)
end
end
end
return autotheme
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:26' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
INFAMY_METER_WIDTH = 256
INFAMY_METER_HEIGHT = 128
INFAMY_METER_KEYBOARD_BAR_OFFSET_X = 14
INFAMY_METER_KEYBOARD_BAR_OFFSET_Y = 15
INFAMY_METER_GAMEPAD_BAR_OFFSET = 10
local INFAMY_METER_UPDATE_DELAY_SECONDS = 1
-- Forces the bar to be at least 3% full, in order to make it visible even at one or two bounty
local MIN_BAR_PERCENTAGE = 0.03
local UPDATE_TYPE_TICK = 0
local UPDATE_TYPE_EVENT = 1
local INFAMY_METER_SLOW_FADE_TIME = 1400 -- in milliseconds
local INFAMY_METER_SLOW_FADE_DELAY = 600 -- in milliseconds
local INFAMY_METER_FADE_TIME = 200 -- in milliseconds
local GREY_DAGGER_ICON = "EsoUI/Art/HUD/infamy_dagger-grey.dds"
local RED_DAGGER_ICON = "EsoUI/Art/HUD/infamy_dagger-red.dds"
local DAGGER_ICON_CUTOUT = "EsoUI/Art/HUD/infamy_dagger-cutout.dds"
local RED_EYE_ICON = "EsoUI/Art/HUD/trespassing_eye-red.dds"
local EYE_ICON_CUTOUT = "EsoUI/Art/HUD/trespassing_eye-cutout.dds"
local ZO_HUDInfamyMeter = ZO_Object:Subclass()
function ZO_HUDInfamyMeter:New(...)
local object = ZO_Object.New(self)
object:Initialize(...)
return object
end
function ZO_HUDInfamyMeter:UpdateInfamyMeterState(infamy, bounty, isKOS, isTrespassing)
self.infamyMeterState.infamy = infamy or GetInfamy()
self.infamyMeterState.bounty = bounty or GetBounty()
if isKOS ~= nil then
self.infamyMeterState.isKOS = isKOS
else
self.infamyMeterState.isKOS = IsKillOnSight()
end
if isTrespassing ~= nil then
self.infamyMeterState.isTrespassing = isTrespassing
else
self.infamyMeterState.isTrespassing = IsTrespassing()
end
end
function ZO_HUDInfamyMeter:GetOldInfamyMeterState()
return self.infamyMeterState.infamy, self.infamyMeterState.bounty, self.infamyMeterState.isKOS, self.infamyMeterState.isTrespassing
end
function ZO_HUDInfamyMeter:Initialize(control)
-- Initialize state
self.nextUpdateTime = 0
self.hiddenExternalRequest = false
self.meterTotal = GetInfamyMeterSize()
self.infamyMeterState = {}
self:UpdateInfamyMeterState(0, 0, false, false)
self.isInGamepadMode = IsInGamepadPreferredMode()
self.currencyOptions =
{
showTooltips = true,
customTooltip = SI_STATS_BOUNTY_LABEL,
font = self.isInGamepadMode and "ZoFontGamepadHeaderDataValue" or "ZoFontGameLargeBold",
overrideTexture = self.isInGamepadMode and ZO_Currency_GetGamepadCurrencyIcon(CURT_MONEY) or nil,
iconSide = RIGHT,
isGamepad = self.isInGamepadMode
}
-- Set up controls
ApplyTemplateToControl(control, self.isInGamepadMode and "ZO_HUDInfamyMeter_GamepadTemplate" or "ZO_HUDInfamyMeter_KeyboardTemplate")
self.control = control
self.meterFrame = control:GetNamedChild("Frame")
self.infamyBar = control:GetNamedChild("InfamyBar")
self.bountyBar = control:GetNamedChild("BountyBar")
self.centerIconAnimatingTexture = control:GetNamedChild("CenterIconAnimatingTexture")
self.centerIconPersistentTexture = control:GetNamedChild("CenterIconPersistentTexture")
self.bountyLabel = control:GetNamedChild("BountyDisplay")
-- Set up fade in/out animations
self.fadeAnim = ZO_AlphaAnimation:New(control)
self.fadeAnim:SetMinMaxAlpha(0.0, 1.0)
-- Initialize bar states and animations
self.infamyBar.easeAnimation = ANIMATION_MANAGER:CreateTimelineFromVirtual("ZO_HUDInfamyMeterEasing")
self.infamyBar.startPercent = 0
self.infamyBar.endPercent = self.infamyMeterState.infamy / self.meterTotal
self.bountyBar.easeAnimation = ANIMATION_MANAGER:CreateTimelineFromVirtual("ZO_HUDInfamyMeterEasing")
self.bountyBar.startPercent = 0
self.bountyBar.endPercent = self.infamyMeterState.bounty / self.meterTotal
-- Initialize Center Icon and its animations
self.centerIconCutoutInAnimation = ANIMATION_MANAGER:CreateTimelineFromVirtual("ZO_HUDInfamyMeterCenterIconCutoutIn")
self.centerIconCutoutInAnimation:GetAnimation(1):SetAnimatedControl(self.centerIconAnimatingTexture)
self.centerIconCutoutInAnimation:GetAnimation(2):SetAnimatedControl(self.centerIconAnimatingTexture)
self.centerIconCutoutInAnimation:GetAnimation(3):SetAnimatedControl(self.centerIconAnimatingTexture)
self.centerIconCutoutInAnimation:GetAnimation(4):SetAnimatedControl(self.centerIconPersistentTexture)
self.centerIconScaleOutAnimation = ANIMATION_MANAGER:CreateTimelineFromVirtual("ZO_HUDInfamyMeterCenterIconScaleOut")
self.centerIconScaleOutAnimation:GetAnimation(1):SetAnimatedControl(self.centerIconAnimatingTexture)
self.centerIconScaleOutAnimation:GetAnimation(2):SetAnimatedControl(self.centerIconAnimatingTexture)
self.centerIconScaleOutAnimation:GetAnimation(3):SetAnimatedControl(self.centerIconPersistentTexture)
-- Register for events
control:RegisterForEvent(EVENT_JUSTICE_INFAMY_UPDATED, function()
if self:ShouldProcessUpdateEvent() then
self:OnInfamyUpdated(UPDATE_TYPE_EVENT)
end
end)
control:RegisterForEvent(EVENT_LEVEL_UPDATE, function()
if self:ShouldProcessUpdateEvent() then
self:OnInfamyUpdated(UPDATE_TYPE_EVENT)
end
end)
control:RegisterForEvent(EVENT_PLAYER_ACTIVATED, function()
if IsInJusticeEnabledZone() then
if self:ShouldProcessUpdateEvent() then
self:OnInfamyUpdated(UPDATE_TYPE_EVENT)
end
else
self.control:SetHidden(true)
self.control:SetAlpha(0)
end
end)
end
function ZO_HUDInfamyMeter:ShouldProcessUpdateEvent()
local infamy = GetInfamy()
local isTrespassing = IsTrespassing()
return IsInJusticeEnabledZone()
and not self.hiddenExternalRequest
and ((infamy ~= 0 and infamy ~= self.infamyMeterState.infamy) or isTrespassing ~= self.infamyMeterState.isTrespassing)
end
function ZO_HUDInfamyMeter:Update(time)
if self.nextUpdateTime <= time and not self.hiddenExternalRequest and IsInJusticeEnabledZone() then
self.nextUpdateTime = time + INFAMY_METER_UPDATE_DELAY_SECONDS
self:OnInfamyUpdated(UPDATE_TYPE_TICK)
end
end
function ZO_HUDInfamyMeter:OnInfamyUpdated(updateType)
local oldInfamy, oldBounty, wasKOS, wasTrespassing = self:GetOldInfamyMeterState()
self:UpdateInfamyMeterState()
local gamepadModeSwitchUpdate = IsInGamepadPreferredMode() ~= self.isInGamepadMode
if oldInfamy ~= self.infamyMeterState.infamy or updateType == UPDATE_TYPE_EVENT or gamepadModeSwitchUpdate then
-- Update frame and bars if we're switching between PC and console mode
if IsInGamepadPreferredMode() and not self.isInGamepadMode then
self.currencyOptions.font = "ZoFontGamepadHeaderDataValue"
self.currencyOptions.isGamepad = true
ApplyTemplateToControl(self.control, "ZO_HUDInfamyMeter_GamepadTemplate")
self.isInGamepadMode = true
elseif not IsInGamepadPreferredMode() and self.isInGamepadMode then
self.currencyOptions.font = "ZoFontGameLargeBold"
self.currencyOptions.isGamepad = false
self.currencyOptions.iconSize = nil
ApplyTemplateToControl(self.control, "ZO_HUDInfamyMeter_KeyboardTemplate")
self.isInGamepadMode = false
end
-- Hide or show meter
if self.infamyMeterState.infamy == 0 then
self.fadeAnim:FadeOut(INFAMY_METER_SLOW_FADE_DELAY, INFAMY_METER_SLOW_FADE_TIME, ZO_ALPHA_ANIMATION_OPTION_FORCE_ALPHA, function() self.control:SetHidden(true) end)
else
self.fadeAnim:FadeIn(0, INFAMY_METER_FADE_TIME, ZO_ALPHA_ANIMATION_OPTION_USE_CURRENT_ALPHA)
end
-- Update bars
self:UpdateBar(self.infamyBar, self.infamyMeterState.infamy, updateType)
self:UpdateBar(self.bountyBar, self.infamyMeterState.bounty, updateType)
-- Update trespassing/KOS icon
self:AnimateCenterIcon(wasKOS, wasTrespassing)
-- Update label
ZO_CurrencyControl_SetSimpleCurrency(self.bountyLabel, CURT_MONEY, GetFullBountyPayoffAmount(), self.currencyOptions, CURRENCY_SHOW_ALL, true)
-- Fire center-screen announcement if we updated below a threshold
local infamyLevel = GetInfamyLevel(self.infamyMeterState.infamy)
local oldInfamyLevel = GetInfamyLevel(oldInfamy)
local messageParams
-- Fire CSA
if self.infamyMeterState.isTrespassing ~= wasTrespassing then
local sound, primaryMessage, secondaryMessage
messageParams = CENTER_SCREEN_ANNOUNCE:CreateMessageParams(CSA_CATEGORY_LARGE_TEXT)
if wasTrespassing then
messageParams:SetCSAType(CENTER_SCREEN_ANNOUNCE_TYPE_JUSTICE_NO_LONGER_KOS)
sound = SOUNDS.JUSTICE_NO_LONGER_KOS
primaryMessage = zo_strformat(SI_JUSTICE_NO_LONGER_TRESPASSING_PRIMARY)
secondaryMessage = zo_strformat(SI_JUSTICE_NO_LONGER_TRESPASSING_SECONDARY)
if self.infamyMeterState.bounty > 0 then
TriggerTutorial(TUTORIAL_TRIGGER_TRESPASS_SUBZONE_EXITED_WITH_BOUNTY)
end
else
messageParams:SetCSAType(CENTER_SCREEN_ANNOUNCE_TYPE_JUSTICE_NOW_KOS)
TriggerTutorial(TUTORIAL_TRIGGER_TRESPASS_SUBZONE_ENTERED)
sound = SOUNDS.JUSTICE_NOW_KOS
primaryMessage = zo_strformat(SI_JUSTICE_NOW_TRESPASSING_PRIMARY)
secondaryMessage = zo_strformat(SI_JUSTICE_NOW_TRESPASSING_SECONDARY)
end
messageParams:SetText(primaryMessage, secondaryMessage)
messageParams:SetSound(sound)
elseif infamyLevel ~= oldInfamyLevel then
local sound, primaryMessage, secondaryMessage, icon
messageParams = CENTER_SCREEN_ANNOUNCE:CreateMessageParams(CSA_CATEGORY_LARGE_TEXT)
if oldInfamyLevel == INFAMY_THRESHOLD_FUGITIVE then
messageParams:SetCSAType(CENTER_SCREEN_ANNOUNCE_TYPE_JUSTICE_NO_LONGER_KOS)
sound = SOUNDS.JUSTICE_NO_LONGER_KOS
primaryMessage = zo_strformat(SI_JUSTICE_INFAMY_LEVEL_CHANGED, GetString("SI_INFAMYTHRESHOLDSTYPE", infamyLevel))
secondaryMessage = zo_strformat(SI_JUSTICE_NO_LONGER_KOS)
icon = "EsoUI/Art/Stats/infamy_KOS_icon-Notification.dds"
elseif infamyLevel == INFAMY_THRESHOLD_FUGITIVE then
messageParams:SetCSAType(CENTER_SCREEN_ANNOUNCE_TYPE_JUSTICE_NOW_KOS)
TriggerTutorial(TUTORIAL_TRIGGER_FUGITIVE_REACHED)
sound = SOUNDS.JUSTICE_NOW_KOS
primaryMessage = zo_strformat(SI_JUSTICE_NOW_FUGITIVE)
secondaryMessage = zo_strformat(SI_JUSTICE_NOW_KOS)
icon = "EsoUI/Art/Stats/infamy_KOS_icon-Notification.dds"
else
messageParams:SetCSAType(CENTER_SCREEN_ANNOUNCE_TYPE_JUSTICE_INFAMY_CHANGED)
if infamyLevel == INFAMY_THRESHOLD_DISREPUTABLE then
TriggerTutorial(TUTORIAL_TRIGGER_DISREPUTABLE_REACHED)
elseif infamyLevel == INFAMY_THRESHOLD_NOTORIOUS then
TriggerTutorial(TUTORIAL_TRIGGER_NOTORIOUS_REACHED)
end
primaryMessage = zo_strformat(SI_JUSTICE_INFAMY_LEVEL_CHANGED, GetString("SI_INFAMYTHRESHOLDSTYPE", infamyLevel))
sound = SOUNDS.JUSTICE_STATE_CHANGED
end
messageParams:SetText(primaryMessage, secondaryMessage)
messageParams:SetIconData(icon)
messageParams:SetSound(sound)
messageParams:MarkSuppressIconFrame()
end
if messageParams then
CENTER_SCREEN_ANNOUNCE:AddMessageWithParams(messageParams)
end
end
end
function ZO_HUDInfamyMeter:AnimateCenterIcon(wasKOS, wasTrespassing)
if self.infamyMeterState.isTrespassing then
if not wasTrespassing then
self.centerIconAnimatingTexture:SetTexture(EYE_ICON_CUTOUT)
self.centerIconPersistentTexture:SetTexture(RED_EYE_ICON)
self.centerIconPersistentTexture:SetAlpha(0)
self.centerIconCutoutInAnimation:PlayFromStart()
end
elseif self.infamyMeterState.isKOS then
if wasTrespassing then
self.centerIconAnimatingTexture:SetTexture(RED_EYE_ICON)
self.centerIconPersistentTexture:SetTexture(RED_DAGGER_ICON)
self.centerIconScaleOutAnimation:PlayFromStart()
elseif not wasKOS then
self.centerIconAnimatingTexture:SetTexture(DAGGER_ICON_CUTOUT)
self.centerIconPersistentTexture:SetTexture(RED_DAGGER_ICON)
self.centerIconPersistentTexture:SetAlpha(0)
self.centerIconCutoutInAnimation:PlayFromStart()
end
else
if wasTrespassing or wasKOS then
self.centerIconAnimatingTexture:SetTexture(self.centerIconPersistentTexture:GetTextureFileName())
self.centerIconPersistentTexture:SetTexture(GREY_DAGGER_ICON)
self.centerIconScaleOutAnimation:PlayFromStart()
end
end
end
function ZO_HUDInfamyMeter:UpdateBar(bar, newValue, updateType)
if not bar.easeAnimation:IsPlaying() or updateType == UPDATE_TYPE_EVENT then
-- Update Values
bar.startPercent = bar.endPercent
bar.endPercent = newValue / self.meterTotal
-- Manually set bar to its start percentage
-- (we do this in case the bar has become out-of-date since it was last animated, for example by being hidden or paused)
self:SetBarValue(bar, bar.startPercent)
-- Start the animation
bar.easeAnimation:PlayFromStart()
end
end
function ZO_HUDInfamyMeter:AnimateMeter(progress)
local infamyFillPercentage = zo_min((progress * (self.infamyBar.endPercent - self.infamyBar.startPercent)) + self.infamyBar.startPercent, 1)
local bountyFillPercentage = zo_min((progress * (self.bountyBar.endPercent - self.bountyBar.startPercent)) + self.bountyBar.startPercent, 1)
local infamyMinPercentage = self.infamyMeterState.infamy ~= 0 and MIN_BAR_PERCENTAGE or 0
local bountyMinPercentage = self.infamyMeterState.bounty ~= 0 and MIN_BAR_PERCENTAGE or 0
self:SetBarValue(self.infamyBar, zo_max(infamyFillPercentage, infamyMinPercentage))
self:SetBarValue(self.bountyBar, zo_max(bountyFillPercentage, bountyMinPercentage))
end
function ZO_HUDInfamyMeter:SetBarValue(bar, percentFilled)
local NO_LEADING_EDGE = false
bar:StartFixedCooldown(percentFilled, CD_TYPE_RADIAL, CD_TIME_TYPE_TIME_REMAINING, NO_LEADING_EDGE) -- CD_TIME_TYPE_TIME_REMAINING causes clockwise scroll
end
function ZO_HUDInfamyMeter:RequestHidden(hidden)
if hidden ~= self.hiddenExternalRequest then
if hidden then
self.fadeAnim:FadeOut(0, INFAMY_METER_FADE_TIME, ZO_ALPHA_ANIMATION_OPTION_USE_CURRENT_ALPHA, function() self.control:SetHidden(true) end, ZO_ALPHA_ANIMATION_OPTION_USE_CURRENT_SHOWN)
elseif IsInJusticeEnabledZone() and (GetInfamy() ~= 0 or self.infamyMeterState.infamy ~= 0) then
self.fadeAnim:FadeIn(0, INFAMY_METER_FADE_TIME, ZO_ALPHA_ANIMATION_OPTION_USE_CURRENT_ALPHA)
end
self.hiddenExternalRequest = hidden
end
end
function ZO_HUDInfamyMeter_Initialize(control)
HUD_INFAMY_METER = ZO_HUDInfamyMeter:New(control)
end
function ZO_HUDInfamyMeter_Update(time)
HUD_INFAMY_METER:Update(time)
end
function ZO_HUDInfamyMeter_AnimateMeter(progress)
if HUD_INFAMY_METER then
HUD_INFAMY_METER:AnimateMeter(progress)
end
end |
require 'rnn'
function build_network(inputSize, hiddenSize, outputSize)
-- I0: The model architecture needs more work, why does having a linear layer as per
-- the example in (http://arxiv.org/abs/1511.07889) cause a "size mismatch, m1: [10 x 512], m2: [10 x 512]" error?
-- I1: add in a dropout layer
rnn = nn.Sequential()
--:add(nn.Sequencer(nn.Linear(inputSize, hiddenSize)))
:add(nn.Sequencer(nn.LSTM(hiddenSize, hiddenSize)))
:add(nn.Sequencer(nn.LSTM(hiddenSize, hiddenSize)))
:add(nn.Sequencer(nn.Linear(hiddenSize, outputSize)))
:add(nn.Sequencer(nn.LogSoftMax()))
-- I1: Adding this line makes the loss oscillate a lot more during training, when according to
-- http://arxiv.org/abs/1409.2329 this should *help* model performance
--rnn:getParameters():uniform(-0.1, 0.1)
return rnn
end
-- Keep the input layer small so the model trains / converges quickly while training
local inputSize = 10
-- Most models seem to use 512 LSTM units in the hidden layers, so let's stick with this
local hiddenSize = 512
-- We want the network to classify the inputs using a one-hot representation of the outputs
local outputSize = 3
local rnn = build_network(inputSize, hiddenSize, outputSize)
--artificially small batchSize again for easy training
local batchSize=5
--and the same for dataset size
local dsSize=batchSize*2
inputs = {}
-- Build up our inputs and targets
-- I2, add code so that if --cuda supplied, these become CudaTensors
-- using the opt.XXX and 'require cunn'
-- I3 - replace this random data set with something more meaningful / learnable
-- and with a realistic testing and validation set
for i = 1, dsSize do
table.insert(inputs, torch.randn(inputSize,hiddenSize))
end
-- *3 to get 3 sample labels..
-- I4: do these dims have to be like this as the Sequencer thinks it's doing a batch..
-- Intuitively I expected targets to be more like this commented-out line, but then we get
-- "bad argument #2 to '?' (out of range at..."
-- targets = torch.ceil(torch.rand(outputSize,dsSize)*3)
-- Same as I1 above (add :cuda()).
targets = torch.ceil(torch.rand(inputSize,hiddenSize)*3)
-- Decorate the regular nn Criterion with a SequencerCriterion as this simplifies training quite a bit
seqC = nn.SequencerCriterion(nn.ClassNLLCriterion())
local count = 0
local numEpochs=100
local start = torch.tic()
--Now let's train our network on the small, fake dataset we generated earlier
while numEpochs ~= 0 do
rnn:training()
count = count + 1
out = rnn:forward(inputs)
err = seqC:forward(out, targets)
gradOut = seqC:backward(out, targets)
rnn:backward(inputs, gradOut)
if count % batchSize == 0 then
local currT = torch.toc(start)
print('loss', err .. ' in ', currT .. ' s')
--TODO, make this configurable / reduce over time as the model converges
rnn:updateParameters(0.05)
-- I5: Are these steps necessary? Seem to make no difference to convergence if called or not
-- Perhaps they are being called by
rnn:zeroGradParameters()
rnn:forget()
start = torch.tic()
end
-- I6: Make this configurable based on the convergence, so we keep going for bigger, more complex models until they are trained
-- to an acceptable accuracy
-- Also add in code to save out the model file to disk for evaluation / usage externally periodically
if count % dsSize == 0 then
numEpochs = numEpochs - 1
end
end |
-- Copyright 2011 Manuel Munz <freifunk at somakoma dot de>
-- Licensed to the public under the Apache License 2.0.
module("luci.tools.olsr", package.seeall)
function etx_color(etx)
local color = "#bb3333"
if etx == 0 then
color = "#bb3333"
elseif etx < 2 then
color = "#00cc00"
elseif etx < 4 then
color = "#ffcb05"
elseif etx < 10 then
color = "#ff6600"
end
return color
end
function snr_color(snr)
local color = "#bb3333"
if snr == 0 then
color = "#bb3333"
elseif snr > 30 then
color = "#00cc00"
elseif snr > 20 then
color = "#ffcb05"
elseif snr > 5 then
color = "#ff6600"
end
return color
end
|
function test.test(callback, signalType, times, interval)
checkArg(1, callback, "function")
checkArg(2, signalType, "string", "nil")
checkArg(3, times, "number", "nil")
checkArg(4, interval, "number", "nil")
local ID = math.random(1, 0x7FFFFFFF)
while handlers[ID] do
ID = math.random(1, 0x7FFFFFFF)
end
handlers[ID] = {
signalType = signalType,
callback = callback,
times = times or math.huge,
interval = interval,
nextTriggerTime = interval and (computer.uptime() + interval) or nil
}
return ID
end |
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Replication = {}
function ReadOnlyTable(table)
return setmetatable(table, {
__index = function()
return "The metatable is locked"
end;
__newindex = function()
return "The metatable is locked"
end;
})
end
function Replication.ClassifyModuleScriptType(Module, Ancestor)
if Ancestor then
local FirstParent = Module:FindFirstAncestorWhichIsA("ModuleScript")
if FirstParent and FirstParent:IsDescendantOf(Ancestor) then
return Replication.ScriptType.SubModule
end
end
local Parent = Module.Parent
while Parent and Parent ~= Ancestor do
local ParentName = Parent.Name
if ParentName == "Server" then
return Replication.ScriptType.Server
elseif ParentName == "Client" then
return Replication.ScriptType.Client
end
Parent = Parent.Parent
end
return Replication.ScriptType.Shared
end
function Replication.ReparentModulesByScriptType(Map, Type, Parent)
assert(type(Map) == "table")
assert(type(Type) == "string")
assert(typeof(Parent) == "Instance")
for _, Module in pairs(Map[Type]) do
Module.Parent = Parent
end
end
function Replication.GetMapForParent(Parent)
assert(typeof(Parent) == "Instance")
local Map = {
[Replication.ScriptType.Shared] = {};
[Replication.ScriptType.Client] = {};
[Replication.ScriptType.Server] = {};
[Replication.ScriptType.SubModule] = {};
}
for _, Descendant in pairs(Parent:GetDescendants()) do
if Descendant:IsA("ModuleScript") then
local ScriptType = Replication.ClassifyModuleScriptType(Descendant, Parent)
table.insert(Map[ScriptType], Descendant)
end
end
return Map
end
function Replication.MergeModuleIntoLookupTable(Module, Lookup)
if Lookup[Module.Name] then
warn("Duplicate of ", Module.Name, " found, using first one found")
else
Lookup[Module.Name] = Module
end
end
function Replication.MergeMapIntoLookupTable(Lookup, Map, AcceptedModes)
for _, ScriptType in pairs(AcceptedModes) do
for _, Module in pairs(Map[ScriptType]) do
Replication.MergeModuleIntoLookupTable(Module, Lookup)
end
end
end
Replication.ScriptType = ReadOnlyTable({
Shared = "Shared";
Client = "Client";
Server = "Server";
SubModule = "SubModule";
})
function Replication.IsInTable(table, Value)
assert(type(table) == "table")
assert(Value, "Must pass in a value to check for")
for _, Entry in pairs(table) do
if Entry == Value then
return true
end
end
return false
end
function Replication.CreateReplicationFolder(Name)
assert(type(Name) == "string")
local CheckReplicated = ReplicatedStorage:FindFirstChild(Name)
if CheckReplicated and CheckReplicated:IsA("Folder") then
local Children = CheckReplicated:GetChildren()
if #Children > 1 then
error(string.format([[A folder with the same name as %s was found, and has Children within it.\n
Will not procceed with replication process as this will interfere.]], Name))
else
return CheckReplicated
end
end
local ReplicationFolder = Instance.new("Folder")
ReplicationFolder.Name = Name
ReplicationFolder.Parent = ReplicatedStorage
return ReplicationFolder
end
return Replication |
-- if execution is slow, perform a maximum of 4 simultaneous updates in order to keep the fixrate
local MAX_SKIP_FRAMES = 4
local function loop(Time)
local accumulator = 0.0
local lastStepTime = 0.0
return function (newTime, stepName, beforeUpdateFn, updateFn)
local dtFixed = Time.DeltaFixed
local stepTime = newTime - lastStepTime
if stepTime > 0.25 then
stepTime = 0.25
end
lastStepTime = newTime
Time.Now = newTime
-- 1000/30/1000 = 0.03333333333333333
accumulator = accumulator + stepTime
--[[
Adjusting the framerate, the world must run on the same frequency,
this ensures determinism in the execution of the scripts
Each system in "transform" step is executed at a predetermined frequency (in Hz).
Ex. If the game is running on the client at 30FPS but a system needs to be run at
120Hz or 240Hz, this logic will ensure that this frequency is reached
@see https://gafferongames.com/post/fix_your_timestep/
@see https://gameprogrammingpatterns.com/game-loop.html
@see https://bell0bytes.eu/the-game-loop/
]]
if stepName == "process" then
if accumulator >= dtFixed then
Time.Interpolation = 1
beforeUpdateFn(Time)
local nLoops = 0
while (accumulator >= dtFixed and nLoops < MAX_SKIP_FRAMES) do
updateFn(Time)
nLoops = nLoops + 1
Time.Process = Time.Process + dtFixed
accumulator = accumulator - dtFixed
end
end
else
Time.Interpolation = math.min(math.max(accumulator/dtFixed, 0), 1)
beforeUpdateFn(Time)
updateFn(Time)
end
end
end
local Timer = {}
Timer.__index = Timer
function Timer.New(frequency)
local Time = {
Now = 0,
-- The time at the beginning of this frame. The world receives the current time at the beginning
-- of each frame, with the value increasing per frame.
Frame = 0,
Process = 0, -- The time the latest process step has started.
Delta = 0, -- The completion time in seconds since the last frame.
DeltaFixed = 0,
-- INTERPOLATION: The proportion of time since the previous transform relative to processDeltaTime
Interpolation = 0
}
local timer = setmetatable({
-- Public, visible by systems
Time = Time,
Frequency = 0,
_update = loop(Time)
}, Timer)
timer:SetFrequency(frequency)
return timer
end
--[[
Changes the frequency of execution of the "process" step
@param frequency {number}
]]
function Timer:SetFrequency(frequency)
-- frequency: number,
-- The maximum times per second this system should be updated. Defaults 30
if frequency == nil then
frequency = 30
end
local safeFrequency = math.floor(math.abs(frequency)/2)*2
if safeFrequency < 2 then
safeFrequency = 2
end
if frequency ~= safeFrequency then
frequency = safeFrequency
end
self.Frequency = frequency
self.Time.DeltaFixed = 1000/frequency/1000
end
function Timer:Update(now, step, beforeUpdate, update)
self._update(now, step, beforeUpdate, update)
end
return Timer
|
--[[
Copyright (c) 2011-2015 chukong-incc.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
include('cocos2d/Cocos2d.lua')
include('cocos2d/Cocos2dConstants.lua')
-- include('cocos2d/functions.lua')
-- opengl
include('cocos2d/Opengl.lua')
include('cocos2d/OpenglConstants.lua')
-- audio
-- include('cocosdenshion/AudioEngine.lua')
-- cocosstudio
-- if nil ~= ccs then
-- include('cocostudio/CocoStudio.lua')
-- end
-- ui
if nil ~= ccui then
include('ui/GuiConstants.lua')
include('ui/experimentalUIConstants.lua')
end
-- extensions
include('extension/ExtensionConstants.lua')
-- network
include('network/NetworkConstants.lua')
-- Spine
if nil ~= sp then
include('spine/SpineConstants.lua')
end
-- include('cocos2d/deprecated.lua')
include('cocos2d/DrawPrimitives.lua')
-- Lua extensions
include('cocos2d/bitExtend.lua')
-- CCLuaEngine
-- include('cocos2d/DeprecatedCocos2dClass.lua')
-- include('cocos2d/DeprecatedCocos2dEnum.lua')
-- include('cocos2d/DeprecatedCocos2dFunc.lua')
-- include('cocos2d/DeprecatedOpenglEnum.lua')
-- register_cocostudio_module
-- if nil ~= ccs then
-- include('cocostudio/DeprecatedCocoStudioClass.lua')
-- include('cocostudio/DeprecatedCocoStudioFunc.lua')
-- end
-- register_cocosbuilder_module
-- include('cocosbuilder/DeprecatedCocosBuilderClass.lua')
-- register_cocosdenshion_module
-- include('cocosdenshion/DeprecatedCocosDenshionClass.lua')
-- include('cocosdenshion/DeprecatedCocosDenshionFunc.lua')
-- register_extension_module
-- include('extension/DeprecatedExtensionClass.lua')
-- include('extension/DeprecatedExtensionEnum.lua')
-- include('extension/DeprecatedExtensionFunc.lua')
-- register_network_module
-- include('network/DeprecatedNetworkClass.lua')
-- include('network/DeprecatedNetworkEnum.lua')
-- include('network/DeprecatedNetworkFunc.lua')
-- register_ui_moudle
-- if nil ~= ccui then
-- include('ui/DeprecatedUIEnum.lua')
-- include('ui/DeprecatedUIFunc.lua')
-- end
-- cocosbuilder
-- include('cocosbuilder/CCBReaderLoad.lua')
-- physics3d
include('physics3d/physics3d-constants.lua')
-- if CC_USE_FRAMEWORK then
-- include('framework/init.lua')
-- end
|
-- Specify input and output paths:
OUTPUT_FILE = "build/rst/index.rst"
INPUT_FILE = "build/xml/index.xml"
FRAME_FILE = "index.rst.in"
-- Usually, Doxygen-based documentation has a main page (created with
-- the \mainpage directive). If that's the case, force-include
-- the contents of 'page_index.rst' into 'index.rst':
INTRO_FILE = "page_index.rst"
-- If your documentation uses \verbatim directives for code snippets
-- you can convert those to reStructuredText C++ code-blocks:
VERBATIM_TO_CODE_BLOCK = "c++"
-- Asterisks, pipes and trailing underscores have special meaning in
-- reStructuredText. If they appear in Doxy-comments anywhere except
-- for code-blocks, they must be escaped:
ESCAPE_ASTERISKS = true
ESCAPE_PIPES = true
ESCAPE_TRAILING_UNDERSCORES = true |
local AddonName, AddonTable = ...
AddonTable.eternalpalace = {
-- Abyssal Commander Sivara
168359, -- abyssal-commanders-mantle
168276, -- claw-of-the-myrmidon
168386, -- gauntlets-of-overflowing-chill
168345, -- helm-of-the-inexorable-tide
168361, -- naga-centaurs-shellplate
168387, -- palace-sentinel-vambraces
168901, -- royal-scaleguards-battleaxe
168390, -- sabatons-of-the-stalwart
168903, -- scepter-of-the-azshari
168371, -- seawrath-legwraps
168273, -- shiver-venom-crossbow
168306, -- shiver-venom-lance
168905, -- shiver-venom-relic
168341, -- siren-mystics-vestments
168818, -- sivaras-slitherblade
168477, -- tidebinders-driftglobe
168377, -- tideblood-bracers
168384, -- wavespine-clutch
-- Blackwater Behemoth
168376, -- anglerfish-feelers
168343, -- blackwater-shimmerscale-vest
168900, -- divers-folly
168373, -- eelskin-flippers
168397, -- fang-of-the-behemoth
168342, -- fathom-feeders-mantle
168389, -- fleetwreckers-greaves
168353, -- hood-of-lightless-depths
169304, -- leviathans-lure
169312, -- luminous-jellyweed
168383, -- pelagos-predators-legguards
168379, -- ship-swallowers-belt
168385, -- slipstreamers-saltwalkers
168362, -- trench-tyrants-shoulderplates
168885, -- undercove-crushers
-- Radiance of Azshara
168355, -- servitors-heartguard
168382, -- arcanamental-bindings
168378, -- leggings-of-the-stormborn
169313, -- phial-of-the-arcane-tempest
168360, -- warhelm-of-dread-waters
168380, -- ancient-tempest-striders
168374, -- belt-of-blind-devotion
168475, -- bulwark-of-the-seaborn-avatar
168375, -- gloves-of-unshackled-arcana
168381, -- grips-of-the-scaled-arcanist
168336, -- handmaidens-cowl-of-sacrifice
168478, -- monstrositys-shipbreaker
168372, -- sea-sculptors-cuffs
168348, -- shoulderpads-of-frothing-rage
168388, -- storm-tempered-girdle
-- Lady Ashvane
169305, -- aquipotent-nautilus
169311, -- ashvanes-razor-coral
168367, -- barnacle-crusted-breastplate
169310, -- bloodthirsty-urchin
168889, -- boralus-nobles-seal
168877, -- coralshell-warboots
168883, -- cultured-pearl-armbands
168904, -- current-weavers-gavel
168347, -- helm-of-hideous-transformation
168876, -- priscillas-fishnets
168335, -- robes-of-sunken-nobility
168354, -- shoulderguards-of-crushing-depths
168870, -- tanglekelp-waistwrap
-- Orgozoa
168604, -- drape-of-the-hatcher
169319, -- dribbling-inkpod
168339, -- incubators-bellcap
168872, -- cephalopods-sash
168875, -- formcrafters-pants
168346, -- tidal-drifters-shoulders
168897, -- tentacle-crusher
168352, -- scalemail-of-unnatural-selection
168365, -- greathelm-of-the-tender
169309, -- zoatroid-egg-sac
168476, -- great-reef-barrier
168893, -- hatchery-scraper
168894, -- squidhunter-speargun
168274, -- aqua-pulse-trident
168899, -- orgozoas-paralytic-barb
-- The Queen's Court
168338, -- amice-of-the-reef-witch
168879, -- ardent-worshippers-boots
168892, -- court-dagger-of-sentencing
169316, -- deferred-sentence
169315, -- edicts-of-the-faithless
168886, -- hands-of-the-fanatic
168881, -- naga-executors-armguards
168898, -- pashmars-finial
168364, -- pauldrons-of-fanatical-might
168890, -- ring-of-the-highborne-courtier
168357, -- silivazs-skullguard
168896, -- stormtamers-orb
168350, -- tunic-of-the-sycophant
-- Za'qul, Harbinger of Ny'alotha
168391, -- cloak-of-ill-tidings
169306, -- zaquls-portal-key
169307, -- vision-of-demise
168349, -- shroud-of-unmooring-whispers
168363, -- dark-passengers-breastplate
168884, -- bindings-of-the-herald
168337, -- vestments-of-creeping-terror
168882, -- shackles-of-dissonance
169588, -- gardbrace-of-fractured-reality
169308, -- chain-of-suffering
168301, -- sever-edge-of-madness
168902, -- dreams-end
-- Queen Azshara
168275, -- anu-azshara-staff-of-the-eternal
169694, -- aqueous-reliquary
169314, -- azsharas-font-of-power
168871, -- beloved-monarchs-waistwrap
168874, -- cherished-empresss-leggings
168891, -- cursed-lovers-ring
168869, -- eternity-keepers-greatbelt
168887, -- gloves-of-incomparable-beauty
168888, -- handguards-of-the-highest-born
168880, -- slippers-of-the-sorceress-queen
168873, -- tide-goddesss-wargreaves
168878, -- vethans-icewalkers
}
|
class = require 'middleclass'
push = require 'push'
binser = require 'binser'
-- Seed RNG
math.randomseed(os.time())
-- Make upscaling look pixelated instead of blurry
love.graphics.setDefaultFilter('nearest', 'nearest')
require 'Util'
require 'Constants'
require 'Game'
require 'Skill'
require 'Menu'
require 'Sprite'
require 'Player'
require 'Map'
require 'Battle'
require 'Chapter'
-- Register classes so they're serializable
-- Don't serialize Music, preloaded
-- Don't serialize Sound, preloaded
-- Don't serialize Animation, only referenced by graphics preload
-- Don't serialize Scene, can only save when current_scene is nil
binser.register(Scaling)
binser.register(Buff)
binser.register(Effect)
binser.register(Skill)
binser.register(MenuItem)
binser.register(Menu)
binser.register(Sprite)
binser.register(Player)
binser.register(Map)
binser.register(GridSpace)
binser.register(Battle)
binser.register(Chapter)
-- Initialize window and launch game
function love.load()
-- Set up a screen with the virtual width and height
local WINDOW_WIDTH, WINDOW_HEIGHT = love.window.getDesktopDimensions()
push:setupScreen(
VIRTUAL_WIDTH,
VIRTUAL_HEIGHT,
1280,
720,
{ fullscreen = false, resizable = true }
)
love.window.setTitle('Abelon')
-- Font used by LOVE's text engine
local font_file = 'graphics/fonts/' .. FONT .. '.ttf'
love.graphics.setFont(love.graphics.newFont(font_file, FONT_SIZE))
-- Storing keypresses
love.keyboard.keysPressed = {}
love.keyboard.keysReleased = {}
-- Go!
game = Game:new()
end
-- Resize game window
function love.resize(w, h)
push:resize(w, h)
end
-- Collect a keypress on this frame
function love.keyboard.wasPressed(key)
return love.keyboard.keysPressed[key]
end
-- Record a keypress on this frame
function love.keypressed(key)
love.keyboard.keysPressed[key] = true
end
-- Update each frame, dt is seconds since last frame
function love.update(dt)
dt = math.min(dt, 1 / 60)
-- dt = dt / 2 -- DEBUG
-- Update everything in the game
game:update(dt)
-- reset all keys pressed and released this frame
love.keyboard.keysPressed = {}
love.keyboard.keysReleased = {}
end
-- Render game to screen each frame using virtual resolution from push
function love.draw()
push:apply('start')
game:render()
push:apply('end')
end
|
local QuestConfig = utils.class();
local auto_accept_quest_list = {}
local npc_quest_list = {};
local npc_submit_list = {} ---交任务的npc
local npc_status_funcList = {}
local mutex_id_list = {} --互斥Id任务分组
local AutoAcceptNextIdList = {} --自动接下一任务id
local CityContuctId = {41, 42, 43, 44}
local ActivityBountyId = {51, 52, 53, 54}
local _cityContuctInfo = nil;
function QuestConfig:_init_(row, advance)
self.id = row.id;
self.type = row.type;
self.day7_type = row.day7_type;
self.guide_type = row.is_fuben_quest;
self.depend = {fight = 0, quest = 0, level = 0};
self.condition = {};
self.time = {from=0, to=0xffffffff, period = 0xffffffff, duration = 0xffffffff};
self.count_limit = 0;
self.auto_accept = false;
self.only_accept_by_other_activity = true;
if advance then
self.desc = row.desc1;
self.auto_accept = (row.auto_accept ~= 0)
self.autoAcceptType = row.auto_accept
self.only_accept_by_other_activity = (row.only_accept_by_other_activity ~= 0)
self.depend.fight = row.depend_fight_id;
self.depend.quest = row.depend_quest_id;
self.depend.level = row.depend_level;
table.insert(self.condition, {type=row.event_type1, id=row.event_id1, count=row.event_count1})
table.insert(self.condition, {type=row.event_type2, id=row.event_id2, count=row.event_count2})
self.time.from = row.begin_time;
if row.end_time > 0 then
self.time.to = row.end_time;
end
if row.period > 0 then
self.time.period = row.period;
else
self.time.period = self.time.to - self.time.from;
end
if row.duration > 0 then
self.time.duration = row.duration;
else
self.time.duration = self.time.period;
end
self.count_limit = row.count;
end
self.consume = {}
self.reward = {}
if row.consume_type1 ~= 0 then
if row.consume_need_reset1 == 0 then row.consume_need_reset1 = 1 end
table.insert(self.consume, {type=row.consume_type1,id=row.consume_id1,value=row.consume_value1,need_reset=row.consume_need_reset1})
end
if row.consume_type2 ~= 0 then
if row.consume_need_reset2 == 0 then row.consume_need_reset2 = 1 end
table.insert(self.consume, {type=row.consume_type2,id=row.consume_id2,value=row.consume_value2,need_reset=row.consume_need_reset2})
end
for i = 1, 3 do
if row["reward_type"..i] ~= 0 then
local _type = row["reward_type"..i]
local _id = row["reward_id"..i]
local _value = row["reward_value"..i]
local _item = utils.ItemHelper.Get(_type, _id)
if _item then
if _type == utils.ItemHelper.TYPE.ITEM then
if _item.is_show ~= 0 then
table.insert(self.reward, {type = _type, id = _id, value = _value})
end
else
table.insert(self.reward, {type = _type, id = _id, value = _value})
end
end
end
end
self.raw = row;
if self.auto_accept and self.depend.query == 0 then
auto_accept_quest_list[self.id] = self;
end
end
function QuestConfig:_getter_(k)
return self.raw[k]
end
-- config --
local questConfig = nil;
local acceptSideQuestList = {}
local submitSideQuestList = {}
local questConfigByType = {};
local questConfigType = {};
local questConfigByGuideType = {};
local questConfigByMemory = {};
local function GetQuestConfig(id, stage)
if questConfig == nil then
questConfig = {}
DATABASE.ForEach("advance_quest", function(row)
local cfg_row = QuestConfig(row, true);
--修改 建设 任务,交任务Npc
local cfg = setmetatable({cfg = cfg_row}, {__index = function(t, k)
if k ~= "npc_id" then
return cfg_row[k]
else
--建设城市任务
if CityContuctId[1]==cfg_row.type or CityContuctId[2]==cfg_row.type or CityContuctId[3]==cfg_row.type or CityContuctId[4]==cfg_row.type then
if cfg_row.npc_id ~= 0 then
return cfg_row.npc_id
--没有任务 交付Npc 找建设城市指定Npc
else
local cityQuestFinishNpc = nil
local questOwenerCityType = _cityContuctInfo and _cityContuctInfo.current_city
if questOwenerCityType then
local ActivityConfig = require "config.activityConfig"
local _city_cfg = ActivityConfig.GetCityConfig(nil,questOwenerCityType)
if _city_cfg and _city_cfg.donate_npc_id then
cityQuestFinishNpc = _city_cfg.donate_npc_id
end
end
return cityQuestFinishNpc
end
else
return cfg_row.npc_id
end
end
end})
if questConfig[cfg.id] == nil then
if cfg.accept_npc_id and cfg.accept_npc_id ~= 0 then
npc_quest_list[cfg.accept_npc_id] = npc_quest_list[cfg.accept_npc_id] or {}
table.insert(npc_quest_list[cfg.accept_npc_id], cfg);
end
if cfg.npc_id and cfg.npc_id ~= 0 then
npc_submit_list[cfg.npc_id] = npc_submit_list[cfg.npc_id] or {}
table.insert(npc_submit_list[cfg.npc_id], cfg);
end
if cfg.mutex_id and cfg.mutex_id ~= 0 then
mutex_id_list[cfg.mutex_id] = mutex_id_list[cfg.mutex_id] or {}
table.insert(mutex_id_list[cfg.mutex_id], cfg);
end
if cfg.autoAcceptType == 4 or cfg.autoAcceptType == 5 or cfg.type == 20 then
table.insert(acceptSideQuestList, cfg);
end
if cfg.autoAcceptType == 5 or cfg.autoAcceptType == 8 then
table.insert(submitSideQuestList, cfg)
end
if cfg.type and cfg.type ~= 0 then
if questConfigType[cfg.type] == nil then questConfigType[cfg.type] = {} end
if cfg.type == 100 then
if questConfigByType[cfg.type] == nil then
questConfigByType[cfg.type] = {};
end
local day = tonumber(cfg.desc1);
if questConfigByType[cfg.type][day] == nil then
questConfigByType[cfg.type][day] = {};
end
if questConfigByType[cfg.type][day][cfg.day7_type] == nil then
questConfigByType[cfg.type][day][cfg.day7_type] = {};
end
table.insert(questConfigByType[cfg.type][day][cfg.day7_type], cfg);
end
table.insert(questConfigType[cfg.type], cfg)
end
if cfg.guide_type and cfg.guide_type ~= 0 then
if questConfigByGuideType[cfg.guide_type] == nil then
questConfigByGuideType[cfg.guide_type] = {};
end
table.insert(questConfigByGuideType[cfg.guide_type], cfg);
end
if cfg.memory_chapter and cfg.memory_chapter ~= 0 then
if questConfigByMemory[cfg.memory_chapter] == nil then
questConfigByMemory[cfg.memory_chapter] = {};
end
if questConfigByMemory[cfg.memory_chapter][cfg.memory_stage] == nil then
questConfigByMemory[cfg.memory_chapter][cfg.memory_stage] = {};
end
table.insert(questConfigByMemory[cfg.memory_chapter][cfg.memory_stage], cfg);
end
questConfig[cfg.id] = setmetatable({{}}, {__index = function(t, k)
return questConfig[cfg.id][1][k]
end});
end
questConfig[cfg.id][cfg.stage] = cfg;
end)
end
if stage then
return questConfig[id][stage];
end
if id then
return questConfig[id];
end
return questConfig;
end
local questChapter = nil
local questChapterGroup = nil
local function GetChapter(id)
if not questChapter or not questChapterGroup then
questChapter = {}
questChapterGroup = {}
DATABASE.ForEach("xiaobai_mainstory", function(row, idx)
questChapter[row.quest_id] = row.group
questChapterGroup[row.group] = questChapterGroup[row.group] or {}
table.insert(questChapterGroup[row.group], row.quest_id)
end)
end
if not id then
return questChapterGroup
end
return questChapter[id]
end
local gotoWhereConfig = nil;
local function GetGoWhereConfig(gid)
if gotoWhereConfig == nil then
gotoWhereConfig = LoadDatabaseWithKey("7day_go_where", "gid");
end
return gotoWhereConfig[gid]
end
local quest_delayConfig = nil;
local function GetQuestDelayConfig(gid)
if quest_delayConfig == nil then
quest_delayConfig = LoadDatabaseWithKey("7day_delay", "quest_id");
end
return quest_delayConfig[gid]
end
local function GetRewardConfig(id)
local cfg = GetQuestConfig(id);
return cfg and cfg.reward;
end
local questSequenceCfg = nil
local function GetQuestSequenceCfg(questType)
if not questSequenceCfg then
questSequenceCfg = LoadDatabaseWithKey("quest_sequence", "quest_type")
end
return questSequenceCfg[questType]
end
local function GetQuestConfigByType(type,time,desc)
GetQuestConfig()
if desc then
return questConfigByType[type][time][desc];
end
if time then
return questConfigByType[type][time];
end
if type then
return questConfigByType[type];
end
end
local function GetQuestConfigByGuideType(type)
GetQuestConfig()
if type then
return questConfigByGuideType[type];
end
return questConfigByGuideType;
end
local function GetQuestConfigByMemory(chapter, stage)
GetQuestConfig()
if stage then
return questConfigByMemory[chapter][stage];
end
return questConfigByMemory[chapter];
end
local function CreateObject(name, pos)
pos = pos or {}
local prefab = SGK.ResourcesManager.Load(name)
if not prefab then
print("load prefab failed", name)
return;
end
local o = UnityEngine.GameObject.Instantiate(prefab);
o.transform.position = Vector3(pos[1] or 0, pos[2] or 0, pos[3] or 0);
end
local eventHandle = nil;
local function GetQuestEnv(quest)
if not quest.script then
return {}
end
if not quest._env then
if quest.script == nil or quest.script == "" or quest.script == "0" or quest.script == 0 then
quest._env = {};
return quest._env;
end
local script = quest.script;
if script == "guide/bounty/eventHandle.lua" then
if eventHandle == nil then
eventHandle = setmetatable({
CreateObject = CreateObject,
EnterMap = module.EncounterFightModule.GUIDE.EnterMap,
Interact = module.EncounterFightModule.GUIDE.Interact,
GetCurrentMapName = module.EncounterFightModule.GUIDE.GetCurrentMapName,
GetCurrentMapID = module.EncounterFightModule.GUIDE.GetCurrentMapID,
}, {__index=_G, __newindex=function(t,k,v)
ERROR_LOG('canot set global in eventHandle.lua', k, debug.traceback());
rawset(t, k, v);
end})
assert(loadfile(script, 'bt', eventHandle))();
-- setmetatable(eventHandle, nil);
end
quest._env = {
OnEnterMap = eventHandle.OnEnterMap,
Guide = eventHandle.Guide,
OnAccept = eventHandle.OnAccept,
}
else
local env = setmetatable({
CreateObject = CreateObject,
EnterMap = module.EncounterFightModule.GUIDE.EnterMap,
Interact = module.EncounterFightModule.GUIDE.Interact,
GetCurrentMapName = module.EncounterFightModule.GUIDE.GetCurrentMapName,
GetCurrentMapID = module.EncounterFightModule.GUIDE.GetCurrentMapID,
}, {__index=_G})
ERROR_LOG("GetQuestEnv", quest.id, quest.name, quest.status)
local func = loadfile(script, 'bt', env)
if func then func(); end
quest._env = env;
end
end
return quest._env;
end
local function callQuestScript(quest, name, ...)
local env = GetQuestEnv(quest);
if rawget(env, name) then
coroutine.resume(coroutine.create(env[name]), quest, ...);
return true;
end
end
local function startQuestScript(quest)
if isNil(quest.script) then
return ;
end
if quest.status ~= 0 then
return ;
end
if quest.events then
return;
end
local env = GetQuestEnv(quest);
quest.events = {}
if callQuestScript(quest, "OnEnterMap", SceneStack.MapId(), SceneStack.CurrentSceneName()) then
quest.events["MAP_SCENE_READY"] = function(event, name)
if quest.status == 0 then
env.OnEnterMap(quest, SceneStack.MapId(), name);
end
end;
utils.EventManager.getInstance():addListener("MAP_SCENE_READY", quest.events["MAP_SCENE_READY"]);
end
end
local function cancelQusetScript(quest)
if quest then
for k, v in pairs(quest.events or {}) do
utils.EventManager.getInstance():removeListener(k, v);
end
quest.events = nil
end
end
local function doQuestAcceptScrpt(quest)
callQuestScript(quest, "OnAccept");
end
local function startQuestGuideScript(quest, acceptable)
local teamInfo = module.TeamModule.GetTeamInfo();
if not (teamInfo.group == 0 or module.playerModule.Get().id == teamInfo.leader.pid) then
showDlgError(nil,"你正在队伍中,无法进行该操作")
return
end
if quest.status == 0 or acceptable == true then
for i = 1, 2 do
if quest.condition then
if quest.condition[i].type == 1 then
if quest.condition[i].id == 1 then
if module.HeroModule.GetManager():Get(11000).level < quest.condition[i].count then
if quest.type == 10 then
LoadStory(tonumber(tostring(quest.id).."1"), function()
utils.MapHelper.OpSelectMap()
end)
return
else
showDlgError(nil, "等级不足")
return
end
end
end
end
end
end
coroutine.resume(coroutine.create(function()
callQuestScript(quest, "Guide")
end));
end
end
-- quest --
local Quest = utils.class()
local function addGiveItem(quest, needTip)
if quest.cfg and quest.cfg.give_id and quest.cfg.give_id ~= 0 and quest.cfg.give_value and quest.cfg.give_value ~= 0 then
if quest.status == 0 then
if module.ItemModule.GetItemCount(quest.cfg.give_id) == 0 then
module.ItemModule.UpItemData({quest.cfg.give_id, quest.cfg.give_value, quest.uuid}, needTip)
end
end
end
end
local function RemoveQuestItem(quest)
if quest and quest.status ~= 0 and quest.cfg.give_id and quest.cfg.give_id ~= 0 and quest.cfg.give_value and quest.cfg.give_value ~= 0 then
if module.ItemModule.GetItemCount(quest.cfg.give_id) > 0 then
module.ItemModule.RemoveQuestItem(quest.cfg.give_id)
end
end
end
function Quest:Init(data, register)
local cfg = GetQuestConfig(data[2]);
if not cfg then
return nil;
end
self.uuid = data[1];
self.id = data[2];
self.status = data[3];
self.records = {data[4], data[5]}
self.finishCount = data[6]
self.accept_time = data[9]
self.finish_time = data[10]
self.cfg = cfg;
self.stageFlag = 1;
if data[11] then
for i=1,30 do
if (data[11] & (1 << (i - 1))) == 0 then
if self.cfg[i] then
self.stageFlag = i;
elseif i ~= 1 then
self.stageFlag = i - 1;
end
break;
end
end
end
self.reward = GetRewardConfig(self.id) or {}
cancelQusetScript(self);
addGiveItem(self, register)
--startQuestGuideScript(self);
-- print("Quset:Init", self.uuid, self.id, self.cfg.name, self.status);
return self;
end
function Quest:_getter_(k)
return self.cfg[self.stageFlag][k];
end
-- quest list --
local quest_list = nil;
local waiting_thread = {};
local quest_by_type_and_status_cache = {};
local function QueryQuestList(first)
utils.NetworkService.Send(76, {nil, 1})
if first then
if coroutine.isyieldable() and waiting_thread then
waiting_thread[#waiting_thread+1] = coroutine.running();
return coroutine.yield();
end
end
end
local function GetQuestList(type, status)
local already_have_data = true;
if quest_list == nil then
quest_list = {}
quest_by_type_and_status_cache = {}
utils.NetworkService.Send(76, {nil, 1})
end
if not type and not status then
return quest_list
end
local cache_status = status or -1;
local cache_type = type or -1;
if not quest_by_type_and_status_cache[cache_type] then
quest_by_type_and_status_cache[cache_type] = {}
end
if quest_by_type_and_status_cache[cache_type][cache_status] then
return quest_by_type_and_status_cache[cache_type][cache_status];
end
local list = {};
for _, quest in pairs(quest_list) do
if type == nil or quest.type == type then
if status == nil or quest.status == status then
table.insert(list, quest);
end
end
end
quest_by_type_and_status_cache[cache_type][cache_status] = list;
return list;
end
local function GetQuest(uuid)
return GetQuestList()[uuid];
end
local _questNs = {}
local _quest_update_status_info = {};
local function CheckQuestServerRequestStatus(uuid)
if _quest_update_status_info[uuid] and os.time() - _quest_update_status_info[uuid].time < 3 then
--print('quest waiting for server respond', uuid);
return false;
end
return true;
end
local function RecordQuestServerRequestStatus(uuid, sn)
_questNs[sn] = uuid;
if coroutine.isyieldable() then
_quest_update_status_info[uuid] = { time = os.time(), co = coroutine.running() }
return coroutine.yield();
else
_quest_update_status_info[uuid] = { time = os.time() }
end
end
local function CleanQuestServerRequestStatus(sn, result)
local uuid = _questNs[sn]
if not uuid then
return;
end
_questNs[sn] = nil;
local info = _quest_update_status_info[uuid]
_quest_update_status_info[uuid] = nil;
if info and info.co then
assert(coroutine.resume(info.co, result == 0));
end
end
local function SetQuestStatus(uuid, status, nextId, stage)
-- print("设置任务状态", uuid, status, nextId, stage, debug.traceback())
stage = stage or 0;
local quest = GetQuest(uuid)
if quest == nil and status ~= 0 then
return false;
end
if quest and quest.uuid < 0 then
quest:SetStatus(status);
else
if not CheckQuestServerRequestStatus(uuid) then
return false;
end
local _sn = utils.NetworkService.Send(78, {nil, uuid, status, nextId, stage})
RecordQuestServerRequestStatus(uuid, _sn);
return true
end
end
local quest_index = 0;
local function RegisterQuest(quest)
-- ERROR_LOG("RegisterQuest", debug.traceback())
quest_list = quest_list or {}
quest_by_type_and_status_cache = {}
local doAccept = false;
if not quest.uuid then
quest_index = quest_index - 1;
quest.uuid = quest_index
quest.id = quest_index
doAccept = true;
end
quest_list[quest.uuid] = quest
if quest.status == 0 then
startQuestScript(quest);
end
if doAccept and quest.status == 0 then
doQuestAcceptScrpt(quest);
end
--startQuestGuideScript(quest);
if not quest.accept_time then
quest.accept_time = module.Time.now()
end
if quest.is_show_on_task then
utils.EventManager.getInstance():dispatch("QUEST_LIST_CHANGE", quest);
end
utils.EventManager.getInstance():dispatch("QUEST_INFO_CHANGE");
return quest.uuid;
end
local function RemoveQuest(uuid)
--ERROR_LOG(uuid..debug.traceback())
if uuid < 0 then
local quest = quest_list[uuid];
if quest and quest.bountyType then --试炼任务
module.BountyModule.Cancel(quest.bountyType)
end
quest_list[uuid] = nil;
quest_by_type_and_status_cache = {}
cancelQusetScript(quest);
RemoveQuestItem(quest)
utils.EventManager.getInstance():dispatch("QUEST_INFO_CHANGE");
end
end
local SnArr = {}
local function CityContuctAcceptQuest(type)
ERROR_LOG('CityContuctAcceptQuest', type, debug.traceback())
local sn = utils.NetworkService.Send(11041, {nil, type});
SnArr[sn] = type
end
local function CityContuctCancelQuest(uuid)
if not CheckQuestServerRequestStatus(uuid or "city_contruct") then
return;
end
local sn = utils.NetworkService.Send(11043, {nil, uuid});
RecordQuestServerRequestStatus(uuid or "city_contruct", sn);
end
local function CityContuctSubmitQuest(uuid)
if not CheckQuestServerRequestStatus(uuid or "city_contruct") then
return;
end
local sn = utils.NetworkService.Send(11045, {nil, uuid});
RecordQuestServerRequestStatus(uuid or "city_contruct", sn);
end
local function CanAcceptQuest(id, showError)
local cfg = GetQuestConfig(id);
if not cfg then
if showError then showDlgError(nil, "任务不存在"); end
return;
end
if cfg.type == 1 then
return true;
end
-- print("任务信息", sprinttb(cfg))
if cfg.depend.quest ~= 0 then
local dq = GetQuest(cfg.depend.quest);
if dq == nil or dq.status ~= 1 then
if showError then showDlgError(nil, "前置任务未完成"); end
return;
end
end
if cfg.depend.fight ~= 0 then
local info = module.fightModule.GetFightInfo(cfg.depend.fight)
if not info or not info:IsPassed() then
if showError then showDlgError(nil, "依赖副本未完成"); end
return;
end
end
if cfg.mode~=0 and not utils.SGKTools.CheckPlayerMode(cfg.mode) then
if showError then showDlgError(nil, "形象不符合任务要求") end
return false
end
if cfg.mutex_id~=0 and mutex_id_list[cfg.mutex_id] and mutex_id_list[cfg.mutex_id] ~= {} then--互斥任务不可重复领取
local _reject=false
for i=1,#mutex_id_list[cfg.mutex_id] do
local _id=mutex_id_list[cfg.mutex_id][i].id
local quest = GetQuest(_id);
if quest and quest.status == 0 then
_reject=true
break
end
end
if _reject then
if showError then showDlgError(nil, "任务已领取"); end
return false;
end
end
if module.HeroModule.GetManager():Get(11000) and module.HeroModule.GetManager():Get(11000).level < cfg.depend.level then
if showError then showDlgError(nil, "未达到任务领取等级"); end
return false;
end
local function IsAcceptConsume(flag)
flag = flag or 0;
return (flag & 0x24) ~= 0
end
for _, consume in ipairs(cfg.consume) do
if consume.type ~= 0 and IsAcceptConsume(consume.need_reset) then
local item = utils.ItemHelper.Get(consume.type, consume.id);
if item.count < consume.value then
if showError then showDlgError(nil, item.name .. '数量不足'); end
return false;
end
end
end
local quest = GetQuest(id);
if quest and cfg.count_limit ~= 0 and quest.finishCount >= cfg.count_limit then
if showError then showDlgError(nil, cfg.count_limit == 1 and "任务已经完成" or "任务已经达到最大可完成次数"); end
return false;
end
if cfg.begin_time > 0 and cfg.end_time > 0 and cfg.period > 0 then
local begin_time, end_time = cfg.begin_time, cfg.end_time;
if cfg.relative_to_born == 1 then
begin_time = module.playerModule.GetCreateTime() + ((cfg.begin_time - 1) * 86400)
end_time = module.playerModule.GetCreateTime() + ((cfg.end_time - 1) * 86400) - 1
end
local period, duration = cfg.period, cfg.duration;
local now = module.Time.now();
if now < begin_time then
if showError then showDlgError(nil, "任务还未开启"); end
return false
end
if now >= end_time then
if showError then showDlgError(nil, "任务已结束"); end
return false
end
if period ~= 0 then
local period_count = math.floor((now - begin_time) / period);
local start_time = begin_time+period_count * period;
if now - start_time >= duration then
if showError then showDlgError(nil, "任务不在开启时间内"); end
return false
end
end
end
---判断是否需要刷新
if quest and cfg.begin_time >= 0 and cfg.end_time >= 0 and cfg.period >= 0 and cfg.relative_to_born == 0 then
local total_pass = module.Time.now() - cfg.begin_time
local period_pass = total_pass - math.floor(total_pass / cfg.period) * cfg.period
local period_begin = module.Time.now() - period_pass;
if quest.accept_time < period_begin then
return true
end
end
---开服任务 判断是否在开服任务活动时间中
---relative_to_born为1的
--[[
if cfg.type == 100 or cfg.type == 97 or cfg.relative_to_born == 1 then
local _beginTime = module.playerModule.GetCreateTime() + ((cfg.begin_time - 1) * 86400)
local _endTime = module.playerModule.GetCreateTime() + ((cfg.end_time - 1) * 86400) - 1
local now = module.Time.now();
if (now < _beginTime) or (now >= _endTime) then
if showError then showDlgError(nil, "任务不在开启时间内"); end
return false
end
end
--]]
--庄园任务
if cfg.type == 14 or cfg.type == 23 then
if not module.ManorRandomQuestNPCModule.QuestAcceptable(cfg.id) then
return false;
end
end
if quest and quest.status == 0 then
if showError then showDlgError(nil, "任务已领取"); end
return false;
end
return true;
end
local function IsSumitConsume(flag)
return (flag == nil) or (flag == 0) or ((flag&0x41) ~= 0)
end
local function GetQuestEndTime(quest)
local _endTime = 0;
if quest.relative_to_born == 1 then
_endTime = module.playerModule.GetCreateTime() + ((quest.end_time - 1) * 86400) - 1;
else
local total_pass = module.Time.now() - quest.time.from;
local period_pass = total_pass % quest.time.period;
local period_end = module.Time.now() - period_pass + quest.time.duration;
_endTime = math.min(period_end, quest.time.to);
end
return _endTime;
end
local function CanSubmitQuest(uuid, showError)
local quest = GetQuest(uuid);
if not quest then
--print('quest', uuid, "not exists");
if showError then
showDlgError(nil, "任务不存在");
end
return;
end
if quest.status and quest.status ~= 0 then
if showError then
showDlgError(nil, "任务不处于已接未完成状态");
end
return false, 6;
end
for i, _ in ipairs(quest.condition or {}) do
if quest.condition[i].type == 1 then
if quest.condition[i].id == 1 then
local level = module.HeroModule.GetManager():Get(11000).level;
if level < quest.condition[i].count then
if showError then
showDlgError(nil, "没有达到完成任务所需等级");
end
return false, 1, level, i;
end
end
elseif quest.condition[i].type == 34 then --拥有角色X个
local _endTime = GetQuestEndTime(quest);
if quest.condition[i].id == 1 then
local count = module.HeroModule.GetHeroCount(_endTime);
if count < quest.condition[i].count then
if showError then
showDlgError(nil, "角色数量不足");
end
return false, 3, count, i;
end
end
elseif quest.condition[i].type == 37 then --拥有护符装备
local _endTime = GetQuestEndTime(quest);
if quest.condition[i].id == 1 then --护符
local count = module.equipmentModule.EquipCount(_endTime);
if count < quest.condition[i].count then
if showError then
showDlgError(nil, "护符数量不足");
end
return false, 4, count, i;
end
elseif quest.condition[i].id == 2 then --铭文
local count = module.equipmentModule.InscripCount(_endTime);
if count < quest.condition[i].count then
if showError then
showDlgError(nil, "铭文数量不足");
end
return false, 5, count, i;
end
end
elseif (quest.condition[i].type == 2 or quest.condition[i].type == 3) and quest.condition[i].count > quest.records[i] then --type 为 2 和 3 则需要战斗
if showError then
showDlgError(nil, "任务所需战斗未完成");
end
return false, 2, quest.records[i], i;
elseif quest.condition[i].type == 60 then --在线时长任务
local _time = module.playerModule.Get().loginTime
if quest.records[i] == 0 then
_time = quest.accept_time
end
local needTime = _time + (quest.condition[i].count - quest.records[i]) - module.Time.now();
if needTime > 0 then
if showError then
showDlgError(nil, "未到时间");
end
return false, 8, needTime, i;
end
elseif quest.condition[i].type == 65 then --主角穿戴某种品质的护符(装备)X个
local _count = module.EquipHelp.GetQualityCount(11000, 0, quest.condition[i].id)
if _count < quest.condition[i].count then
if showError then
showDlgError(nil, "主角穿戴某种品质的护符不足");
end
return false, 9, _count, i;
end
elseif quest.condition[i].type == 66 then --主角穿戴某种品质的铭文(守护)X个
local _count = module.EquipHelp.GetQualityCount(11000, 1, quest.condition[i].id)
if _count < quest.condition[i].count then
if showError then
showDlgError(nil, "主角穿戴某种品质的铭文不足");
end
return false, 10, _count, i;
end
elseif quest.condition[i].type == 68 then --穿了几件套装
if quest.condition[i].id ~= 0 then
local _count = module.EquipHelp.GetSuitCount(quest.condition[i].id, 0)
local _flag = false
for k,v in pairs(_count) do
if v >= quest.condition[i].count then
_flag = true
break
end
end
if not _flag then
if showError then
showDlgError(nil, "穿戴几件套装");
end
return false, 11, _count, i;
end
end
elseif quest.condition[i].type == 62 then --拥有某个等级的英雄X个
local _endTime = GetQuestEndTime(quest);
local count = module.HeroModule.GetHeroCount(_endTime, quest.condition[i].id);
if count < quest.condition[i].count then
if showError then
showDlgError(nil, "角色数量不足");
end
return false, 12, count, i;
end
elseif quest.condition[i].type == 63 then --拥有某个品质护符(装备)X个
local _endTime = GetQuestEndTime(quest);
local count = module.equipmentModule.EquipCount(_endTime, quest.condition[i].id);
if count < quest.condition[i].count then
if showError then
showDlgError(nil, "护符数量不足");
end
return false, 13, count, i;
end
elseif quest.condition[i].type == 64 then --拥有某个品质铭文(守护)X个
local _endTime = GetQuestEndTime(quest);
local count = module.equipmentModule.InscripCount(_endTime, quest.condition[i].id);
if count < quest.condition[i].count then
if showError then
showDlgError(nil, "铭文数量不足");
end
return false, 14, count, i;
end
elseif quest.condition[i].type == 71 then --拥有道具X个
local _count = module.ItemModule.GetItemCount(quest.condition[i].id)
if _count < quest.condition[i].count then
if showError then
showDlgError(nil, "道具数量不足");
end
return false, 15, _count, i;
end
elseif quest.condition[i].type == 72 then --阶数X
local _hero = module.HeroModule.GetManager():Get(quest.condition[i].id)
if _hero then
if _hero.stage < quest.condition[i].count then
if showError then
showDlgError(nil, "阶数不足");
end
return false, 16, _hero.stage, i;
end
else
return false, 16;
end
elseif quest.condition[i].type == 74 then --武器星数
local _hero = module.HeroModule.GetManager():Get(quest.condition[i].id)
if _hero then
if _hero.star < quest.condition[i].count then
if showError then
showDlgError(nil, "武器星数不足");
end
return false, 17, _hero.star, i;
end
else
return false, 17
end
elseif quest.condition[i].type == 81 then --X个角色加了Y个技能点的任务
local _heroList = module.HeroModule.GetManager():GetAll()
local _count = 0
for k,v in pairs(_heroList or {}) do
if module.HeroHelper.GetTalentCount(v.id) >= quest.condition[i].id then
_count = _count + 1
end
end
if _count < quest.condition[i].count then
return false, 18, _count, i;
end
elseif quest.condition[i].type == 82 then --X护符进阶Y阶的任务
local _count = module.EquipHelp.GetAdvCount(quest.condition[i].id)
if _count < quest.condition[i].count then
if showError then
showDlgError(nil, "数量不足")
end
return false, 19, _count, i;
end
elseif quest.condition[i].type == 83 then --拥有Y件套套装效果数量X
local _heroList = module.HeroModule.GetManager():GetAll()
local _count = 0
for p,v in pairs(_heroList) do
local _suit = module.HeroModule.GetManager():GetEquipSuit(v.id)
if _suit and _suit[0] then
for k,v in pairs(_suit[0]) do
if #v.IdxList >= quest.condition[i].id then
_count = _count + 1
break
end
end
end
end
if _count < quest.condition[i].count then
return false, 20, _count, i;
end
elseif quest.condition[i].type == 91 then
local _list = utils.ItemHelper.GetList(utils.ItemHelper.TYPE.ITEM, quest.condition[i].id)
local _count = 0
for i,v in ipairs(_list) do
_count = _count + module.ItemModule.GetItemCount(v.id)
end
if _count < quest.condition[i].count then
return false, 21, _count, i;
end
elseif quest.condition[i].type == 98 then
local _info = module.fightModule.GetFightInfo(quest.condition[i].id)
local _count = 0
if _info then
for i = 1, 3 do
if module.fightModule.GetOpenStar(_info.star, i) ~= 0 then
_count = _count + 1
end
end
end
if _count < quest.condition[i].count then
return false, 22, _count, i;
end
elseif quest.condition[i].type == 100 then
local _info = module.fightModule.GetFightInfo(quest.condition[i].id)
if not _info:IsPassed() then
return false, 23, 0, i;
end
elseif quest.condition[i].type == 101 then
local starPoint = module.playerModule.Get().starPoint or 0;
if starPoint < quest.condition[i].count then
if showError then
showDlgError(nil, "任务所需未完成");
end
return false, 24, starPoint, i;
end
elseif quest.condition[i].type == 102 then --装备升级次数
local _endTime = GetQuestEndTime(quest)
local count = module.equipmentModule.EquipLevelCount(_endTime, quest.condition[i].id);
if count < quest.condition[i].count then
if showError then
showDlgError(nil, "装备升级数不足");
end
return false, 25, count, i;
end
elseif quest.condition[i].type == 110 then --特定角色达到多少级
local manager = module.HeroModule.GetManager()
local hero = manager:Get(quest.condition[i].id) or {level = -1}
if hero.level < quest.condition[i].count then
if showError then
local cfg = module.HeroModule.GetConfig(quest.condition[i].id);
showDlgError(nil, string.format("%s等级没有达到%d", cfg and cfg.name or '角色', quest.condition[i].count));
end
return false, 26, hero.level, i;
end
elseif quest.condition[i].type == 112 then --完成某个任务
local quest = GetQuest(quest.condition[i].id);
if quest == nil or quest.status ~= 1 then
if showError then
showDlgError(nil, "任务未完成");
end
return false, 27, 0, i;
end
elseif quest.condition[i].count > quest.records[i] then
if showError then
showDlgError(nil, "任务所需未完成");
end
return false, 7, quest.records[i], i;
end
end
for _, consume in ipairs(quest.consume or {}) do
if consume.type ~= 0 and IsSumitConsume(consume.need_reset) then
local item = utils.ItemHelper.Get(consume.type, consume.id) or {count = 0}
if item.count < consume.value then
if showError then
print("item", item.name, "not enough");
showDlgError(nil, item.name .. '数量不足');
end
return false, 3;
end
end
end
return true;
end
local function GetQuestSubmitItemList(uuid)
local quest = GetQuestConfig(uuid)
local list = {}
for _, consume in ipairs(quest.consume) do
if consume.type ~= 0 and IsSumitConsume(consume.need_reset) then
print("---------------",consume.need_reset)
table.insert(list, consume)
end
end
if #list > 0 then
return list;
end
end
local function AcceptQuest(id)
if not CanAcceptQuest(id) then
--print("quest can't accept")
return;
end
-- print("接任务", id);
return SetQuestStatus(id, 0);
end
---登录成功接取注册日常活动任务
local function AcceptActivityQuest()
local _count = 0
if not questConfig then
GetQuestConfig(1)
end
for k,v in pairs(questConfig) do
--[[
if v.type == 20 or v.type == 100 or v.type == 30 then
if AcceptQuest(v.id) then
_count = _count + 1
end
end
--]]
end
return _count
end
local function FinishQuest(uuid, data, stage)
local quest = GetQuest(uuid);
if not quest then
--print('quest', uuid, "not exists");
return;
end
stage = stage or quest.stageFlag
-- if data and data.nextId then
-- AutoAcceptNextIdList[uuid] = data.nextId
-- end
for i,v in ipairs(CityContuctId) do
if quest.type == v then
return CityContuctSubmitQuest(uuid);
end
end
if not CanSubmitQuest(uuid) then
local case1,case2=CanSubmitQuest(uuid)
--print("quest can't submit",case2);
return;
end
data = data or {nextId = 0}
-- print("完成任务", uuid, debug.traceback());
--任务栏可见的任务增加奖励确认弹窗
if quest.is_show_on_task and quest.is_show_on_task == 0 and quest.reward and next(quest.reward) then
utils.SGKTools.ShowTaskItem(quest,function ()
if quest.reward and next(quest.reward) then
local _tab = {}
for i=1,#quest.reward do
table.insert(_tab,{quest.reward[i].type,quest.reward[i].id,quest.reward[i].value})
end
DispatchEvent("ADD_FILTER_REWARDS",_tab)
end
SetQuestStatus(uuid, 1, data.nextId, stage)
end)
else
SetQuestStatus(uuid, 1, data.nextId, stage)
end
end
local BountyId = 2
local function CancelQuest(uuid)
if uuid == nil or type(uuid) ~= "number" then
ERROR_LOG('remove quest failed, uuid is nil')
return;
end
if uuid < 0 then
RemoveQuest(uuid)
else
local quest = quest_list[uuid]
for i,v in ipairs(CityContuctId) do
if quest and quest.type == v then
return CityContuctCancelQuest(uuid);
end
end
if quest and quest.type == BountyId then
return module.BountyModule.Cancel()
end
SetQuestStatus(uuid, 2);
end
end
local function SendSevenDayEmail(addEmail)
local TipCfg = require "config.TipConfig"
for day,v in pairs(addEmail) do
local list = {};
-- list.id = "sevenDay"..day;
-- list.type = 101;
list.title = TipCfg.GetAssistDescConfig(61005).info;
list.status = 2;
list.time = module.playerModule.GetCreateTime() + ((v[1].end_time - 1) * 86400)
list.attachment_count = 1;
list.attachment_opened = 0;
local reward = {}
for _,questCfg in ipairs(v) do
local quest = GetQuest(questCfg.id);
-- local _reward = GetRewardConfig(questCfg.id);
-- ERROR_LOG("奖励", sprinttb(quest.reward))
for _,item in ipairs(quest.reward) do
if reward[item.id] then
reward[item.id].value = reward[item.id].value + item.value;
else
reward[item.id] = {};
reward[item.id].type = item.type;
reward[item.id].id = item.id;
reward[item.id].value = item.value;
end
end
end
local items = {};
items.content = TipCfg.GetAssistDescConfig(61005 + day).info;
items.id = 0;
items.item = {};
for _,item in pairs(reward) do
local info = {};
info[1] = item.type;
info[2] = item.id;
info[3] = item.value;
table.insert(items.item, info);
end
list.content = items;
list.fun = function (id,type,data)
if type == 1 then --打开邮件
elseif type == 2 then --领取邮件
for _,questCfg in ipairs(v) do
print("完成任务",questCfg.id, questCfg.name)
FinishQuest(questCfg.id);
end
module.MailModule.SetAttachment_opened(id,1);
elseif type == 3 then --删除邮件
for _,questCfg in ipairs(v) do
local quest = GetQuest(questCfg.id);
if quest and quest.status == 0 then
print(quest.name.."未完成")
return;
end
end
module.MailModule.DelMail(id)
end
end
-- for _,questCfg in ipairs(v) do
-- ERROR_LOG("可完成", questCfg.id, questCfg.name)
-- end
-- ERROR_LOG("添加邮件", sprinttb(list))
-- module.MailModule.SetManager(list, true);
end
end
local checkDelayQuest = false;
local function GetSevenDayOpen()
local allQuest = GetQuestConfigByType(100);
if checkDelayQuest then
for i,v in ipairs(allQuest or {}) do
for _,j in pairs(v) do
for _,k in ipairs(j) do
local _endTime = module.playerModule.GetCreateTime() + ((k.end_time - 1) * 86400) - 1
if module.Time.now() > _endTime then
-- ERROR_LOG("超时", k.end_time, module.playerModule.GetCreateTime(), module.Time.now(), _endTime)
return false;
else
return true;
end
end
end
end
else
checkDelayQuest = true;
local isopen = true;
local addEmail = {};
for day,v in ipairs(allQuest or {}) do
for _,j in pairs(v) do
for _,k in ipairs(j) do
local _endTime = module.playerModule.GetCreateTime() + ((k.end_time - 1) * 86400) - 1
if module.Time.now() > _endTime then
local delay_config = GetQuestDelayConfig(k.id);
if delay_config and module.Time.now() < _endTime + delay_config.delay_time then
local quest = GetQuest(k.id);
if quest and quest.status == 0 and quest.consume_id1 == 0 then
local submit = CanSubmitQuest(k.id);
if submit then
-- ERROR_LOG(k.name.."可以延时提交");
-- FinishQuest(k.id);
if addEmail[day] == nil then
addEmail[day] = {};
end
table.insert(addEmail[day], k);
-- else
-- ERROR_LOG(k.name.."未完成");
end
-- elseif quest == nil then
-- ERROR_LOG(k.name.."不存在");
-- elseif quest.status ~= 0 then
-- ERROR_LOG(k.name.."已完成");
end
end
if isopen then
isopen = false;
end
end
end
end
end
SendSevenDayEmail(addEmail)
return isopen;
end
end
local OldUuid = nil
local function GetOldUuid()
return OldUuid
end
local function SetOldUuid(Uuid)
OldUuid = Uuid
end
local NpcStatus = {
Finish = 1, --可完成
Accept = 2, --可接
UnAccept = 3, --不可交
}
local NpcStatusSortIndex = {
[5] = 1,
[1] = 2,
[2] = 3,
[8] = 4,
[7] = 5,
[3] = 6,
[4] = 7,
[10] = 8,
[11] = 9,
}
local function getNpcStatus(npcId, func)
GetQuestConfig(0)
if not quest_list then
table.insert(npc_status_funcList, {npcId = npcId, func = func})
return nil
end
local list = npc_quest_list[npcId] or {}
local _subList = npc_submit_list[npcId] or {}
local _acceptTab = {}
local _subTab = {}
local _unSubTab = {}
for i,v in ipairs(list) do
if CanAcceptQuest(v.id) then
table.insert(_acceptTab, v)
end
end
for i,v in ipairs(_subList) do
if CanSubmitQuest(v.id) then
table.insert(_subTab, v)
elseif GetQuest(v.id) and GetQuest(v.id).status == 0 then
table.insert(_unSubTab, v)
end
end
if #_subTab >= 1 then
table.sort(_subTab, function(a, b)
return (NpcStatusSortIndex[a.type] or 1) > (NpcStatusSortIndex[b.type] or 1)
end)
if func then
func(NpcStatus.Finish, _subTab[1].is_show_on_task)
return
end
return {status = NpcStatus.Finish, type = _subTab[1].is_show_on_task}
end
if #_acceptTab >= 1 then
table.sort(_acceptTab, function(a, b)
return (NpcStatusSortIndex[a.type] or 1) > (NpcStatusSortIndex[b.type] or 1)
end)
if func then
func(NpcStatus.Accept, _acceptTab[1].is_show_on_task)
return
end
return {stauts = NpcStatus.Accept, type = _acceptTab[1].is_show_on_task}
end
if #_unSubTab >= 1 then
table.sort(_unSubTab, function(a, b)
return (NpcStatusSortIndex[a.type] or 1) > (NpcStatusSortIndex[b.type] or 1)
end)
if func then
func(NpcStatus.UnAccept, _unSubTab[1].is_show_on_task)
return
end
return {stauts = NpcStatus.UnAccept, type = _unSubTab[1].is_show_on_task}
end
func()
return nil
end
local function notifyNpcStatusChange()
for i,v in ipairs(npc_status_funcList) do
if v.npcId and v.func then
getNpcStatus(v.npcId, v.func)
end
end
npc_status_funcList = {}
end
local otherQuestTab = {}
local function UpdateOtherQuest(data,pid)
if data and pid then
local uuid = data[1];
local id = data[2];
local status = data[3];
local records = {data[4], data[5]}
local finishCount = data[6]
local accept_time = data[9]
local finish_time = data[10]
otherQuestTab[pid] = otherQuestTab[pid] or {}
otherQuestTab[pid][id] = otherQuestTab[pid][id] or {}
otherQuestTab[pid][id].uuid = uuid
otherQuestTab[pid][id].id = id
otherQuestTab[pid][id].status = status;
otherQuestTab[pid][id].records = records
otherQuestTab[pid][id].finishCount = finishCount
otherQuestTab[pid][id].accept_time = accept_time
otherQuestTab[pid][id].finish_time = finish_time
otherQuestTab[pid][id].lastQueryTime = module.Time.now()
end
end
-- network event --
utils.EventManager.getInstance():addListener("server_respond_77", function(event, cmd, data)
if data[2] ~= 0 then
--print("query quest failed", data[2])
local _last_waiting_thread = waiting_thread or {};
waiting_thread = nil;
for _, co in ipairs(_last_waiting_thread) do
coroutine.resume(co, {});
end
return;
end
local sn = data[1]
if SnArr[sn] then
-- ERROR_LOG("server_respond_77",sprinttb(data))
if data[3] and next(data[3])~=nil then
UpdateOtherQuest(data[3][1],SnArr[sn].pid)
if SnArr[sn].func then
SnArr[sn].func()
else
DispatchEvent("COOPERAQUEST_INFO_CHANGE",{SnArr[sn].quest_id,module.playerModule.GetSelfID()})
end
end
SnArr[sn] = nil
else
quest_list = quest_list or {}
quest_by_type_and_status_cache = {}
for k, v in pairs(quest_list) do
if k > 0 then
quest_list[k] = nil;
end
end
for _, v in ipairs(data[3]) do
local quest = Quest():Init(v);
if quest then
quest_list[quest.uuid] = quest;
if quest.status == 0 then
startQuestScript(quest)
end
end
end
notifyNpcStatusChange()
utils.EventManager.getInstance():dispatch("QUEST_INFO_CHANGE");
local _last_waiting_thread = waiting_thread;
waiting_thread = nil;
for _, co in ipairs(_last_waiting_thread or {}) do
coroutine.resume(co, quest_list);
end
end
end);
utils.EventManager.getInstance():addListener("server_respond_79", function(event, cmd, data)
local sn, result = data[1], data[2];
CleanQuestServerRequestStatus(sn, result);
end)
local have_quest_change = false;
utils.EventManager.getInstance():addListener("server_notify_56", function(event, cmd, data)
-- print("server_notify_56", unpack(data));
local uuid = data[1];
quest_list = quest_list or {};
quest_by_type_and_status_cache = {}
local oldStatus = quest_list[uuid] and quest_list[uuid].status;
local quest = quest_list[uuid] or Quest();
if not quest:Init(data, true) then
return;
end
if quest.id == 0 then
quest_list[uuid] = nil;
else
quest_list[uuid] = quest;
startQuestScript(quest);
end
if quest.status == 0 and oldStatus ~= quest.status then
doQuestAcceptScrpt(quest);
end
RemoveQuestItem(quest)
if quest.status == 1 and quest.is_show_on_task == 0 then
--utils.EventManager.getInstance():dispatch("QUEST_FINISH");
if quest.show_reward ~= 0 then
--完成任务提示
-- GetFinishQuest()
end
end
if quest.status == 1 then
DispatchEvent("LOCAL_HERO_QUEST_FINISH", {questId = quest.id})
end
if quest.status ~= 0 then
module.EncounterFightModule.RemoveFightDataByType("quest_" .. quest.id);
end
utils.EventManager.getInstance():dispatch("QUEST_INFO_CHANGE", quest);
have_quest_change = true;
if quest.is_show_on_task then
utils.EventManager.getInstance():dispatch("QUEST_LIST_CHANGE", quest);
end
if quest.status == 1 and (quest.type == 31 or quest.type == 32) then
utils.EventManager.getInstance():dispatch("LOCAL_ACHIEVEMENT_CHANGE", {quest_id = quest.id})
end
end);
utils.EventManager.getInstance():addListener("server_notify_end", function(event, cmd, data)
if have_quest_change then
have_quest_change = false
utils.EventManager.getInstance():dispatch("AFTER_QUEST_INFO_CHANGE");
end
end)
utils.EventManager.getInstance():addListener("server_notify_58", function(event, cmd, data)
local quest_id = data[1];
local rewards = {};
for k, v in ipairs(data) do
if k ~= 1 then
table.insert(rewards, {type=v[1],id=v[2],value=v[3],uuid=v[4] or 0})
end
end
local cfg = GetQuestConfig(quest_id);
if cfg and cfg.is_show_on_task then
utils.EventManager.getInstance():dispatch("QUEST_FINISH_REWARD", cfg, rewards);
end
end);
local lastQueryTime=0
local function CityContuctInfo(reset,flag)
--flag --查询本地不查服务器
if flag then
return _cityContuctInfo;
end
local need_send_request = false;
if lastQueryTime+20<module.Time.now() or reset or _cityContuctInfo == nil then
need_send_request = true;
end
_cityContuctInfo = _cityContuctInfo or {today_count = 0, round_index = 0, current_city = 0, boss = {}};
if need_send_request then
utils.NetworkService.Send(11049)
lastQueryTime=module.Time.now()
end
return _cityContuctInfo;
end
local function CityContructFightBoss(id)
utils.NetworkService.Send(11047, {nil, id})
end
local canAcceptList = {}
local function findActivityQuest(typeId)
for k,v in pairs(quest_list) do
if v.type and v.type == typeId and v.status == 0 then
return true
end
end
return false
end
local function findActivityQuestByQuestType(v)
if v.quest_type ~= "0" then
local _questType = StringSplit(v.quest_type, "|")
for i,p in ipairs(CityContuctId) do
if p == v.id then
for i,v in ipairs(_questType) do
local _list = GetQuestList(tonumber(p), 0)
if _list and #_list > 0 then
return false
end
end
end
end
for i,p in ipairs(ActivityBountyId) do
if p == v.id then
local _list = module.QuestModule.GetList()
for i,t in ipairs(_questType) do
for k,d in pairs(_list) do
if d.bountyId == tonumber(t) and d.status == 0 then
return false
end
end
end
end
end
end
return true
end
local function activityQuestDependId(_cfg)
if _cfg.depend_quest_id and _cfg.depend_quest_id ~= 0 then
local _questCfg = GetQuest(_cfg.depend_quest_id)
if not _questCfg or (_questCfg and _questCfg.status ~= 1) then
return false
end
end
return true
end
---活动构成成任务结构
local function addCanAcceptActivityQuest(tab)
local activityConfig = require "config.activityConfig"
for k,v in pairs(activityConfig.GetActivity()) do
if v.activity_type == 1 then
if findActivityQuestByQuestType(v) and not findActivityQuest(v.id) and activityQuestDependId(v) then
local _cfg = activityConfig.GetActivity(v.id)
if _cfg and _cfg.lv_limit <= module.HeroModule.GetManager():Get(11000).level then
local _questCfg = {}
_questCfg.name = _cfg.name
_questCfg.type = _cfg.id
_questCfg.desc = _cfg.des
_questCfg.desc2 = _cfg.des2
_questCfg.script = "guide/bounty/activityQuest.lua"
_questCfg.npc_id = _cfg.findnpcname
_questCfg.map_id = _cfg.gotowhere
_questCfg.icon = _cfg.icon
_questCfg.reward = {}
for i = 1, 3 do
if _cfg["reward_id"..i] ~= 0 then
local _temp = {}
_temp.type = _cfg["reward_type"..i]
_temp.id = _cfg["reward_id"..i]
_temp.value = _cfg["reward_value"..i] or 0
local _item = utils.ItemHelper.Get(_temp.type, _temp.id)
if _item and _item.is_show ~= 0 then
table.insert(_questCfg.reward, _temp)
end
end
end
table.insert(tab, _questCfg)
end
end
end
end
end
local function GetCanAccept()
if not questConfig then
GetQuestConfig(1)
end
canAcceptList = {}
for k,v in pairs(questConfig) do
if CanAcceptQuest(k) and (v.type == 10 or v.type == 11 or v.type == 12) then
table.insert(canAcceptList, v)
end
end
--插入活动
addCanAcceptActivityQuest(canAcceptList)
return canAcceptList
end
utils.EventManager.getInstance():addListener("server_respond_11042", function(event, cmd, data)
local sn, result = data[1], data[2];
if result == 0 then
if SnArr[sn] then
utils.EventManager.getInstance():dispatch("CITY_CONTUCT_ACCEPT_SUCCEED",SnArr[sn]);
SnArr[sn] = nil
end
_cityContuctInfo.current_city = data[4];
else
if SnArr[sn] then
utils.EventManager.getInstance():dispatch("CITY_CONTUCT_ACCEPT_FAILD",SnArr[sn]);
SnArr[sn] = nil
end
end
end);
utils.EventManager.getInstance():addListener("server_respond_11050", function(event, cmd, data)
--ERROR_LOG("server_respond_11050",sprinttb(data))
if data[2] ~= 0 then
print("query city contuct info failed")
return;
end
_cityContuctInfo = {boss = {}};
_cityContuctInfo.round_index = data[3];
_cityContuctInfo.today_count = data[4];
_cityContuctInfo.current_city = data[6];
for _, v in ipairs(data[5] or {}) do
_cityContuctInfo.boss[v[1]] = { id = v[1], exp = v[2], quest_group = v[3],lastSetTime=v[4] }
end
print("_cityContuctInfo", _cityContuctInfo.round_index, _cityContuctInfo.today_count);
utils.EventManager.getInstance():dispatch("CITY_CONTRUCT_INFO_CHANGE");
end);
utils.EventManager.getInstance():addListener("server_respond_11044", function(event, cmd, data)
local sn, result = data[1], data[2];
if result ~= 0 then
print("query city contuct info failed")
else
_cityContuctInfo = _cityContuctInfo or {};
_cityContuctInfo.round_index = data[3];
_cityContuctInfo.today_count = data[4];
_cityContuctInfo.current_city = 0;
-- print("_cityContuctInfo", _cityContuctInfo.round_index, _cityContuctInfo.today_count);
utils.EventManager.getInstance():dispatch("CITY_CONTRUCT_INFO_CHANGE",sn);
end
CleanQuestServerRequestStatus(sn, result)
end)
utils.EventManager.getInstance():addListener("server_respond_11046", function(event, cmd, data)
local sn, result = data[1], data[2];
if result ~= 0 then
print("query city contuct info failed")
else
_cityContuctInfo = _cityContuctInfo or {};
_cityContuctInfo.round_index = data[3];
_cityContuctInfo.today_count = data[4];
print("_cityContuctInfo", _cityContuctInfo.round_index, _cityContuctInfo.today_count);
utils.EventManager.getInstance():dispatch("CITY_CONTRUCT_INFO_CHANGE");
end
CleanQuestServerRequestStatus(sn, result)
end)
utils.EventManager.getInstance():addListener("LOCAL_RECONNECTION", function(event, data)
coroutine.resume(coroutine.create(function()
QueryQuestList(true)
end))
end)
local function GetQuestConfigByMutexId(mutexId)
if questConfig == nil then
GetQuestConfig()
end
return mutex_id_list[mutexId]
end
local function GetQuestConfigByNPC(npc, only_can_accept)
GetQuestConfig(0);
local list = npc_quest_list[npc] or {}
if not only_can_accept then
return list;
end
local t = {}
for _, v in ipairs(list) do
if CanAcceptQuest(v.id) and v.only_accept_by_other_activity == 0 then
table.insert(canAcceptList, v)
end
table.insert(t, v);
end
return t;
end
local function GetRedPointState(full)
local allQuest = GetQuestConfigByType(100);
local nowDay = math.ceil((module.Time.now() - module.playerModule.GetCreateTime()) / 86400);
if full then
local pointState = {};
for day,v in ipairs(allQuest) do
if pointState[day] == nil then
pointState[day] = {};
end
for type,k in pairs(v) do
local state = false;
if nowDay >= day then
for _,j in ipairs(k) do
if CanSubmitQuest(j.id) and j.day7_type ~= 2 then
local quest = GetQuest(j.id);
-- ERROR_LOG("任务可以提交", quest.name);
state = true;
break;
end
end
end
pointState[day][type] = state;
end
end
return pointState;
else
for day,v in ipairs(allQuest or {}) do --天
if nowDay >= day then
for _,k in pairs(v) do --类别
for _,j in ipairs(k) do --任务
if CanSubmitQuest(j.id) and j.day7_type ~= 2 then
local quest = GetQuest(j.id);
-- ERROR_LOG("任务可以提交", quest.name);
return true;
end
end
end
end
end
return false
end
end
local function getOtherRecords(quest, idx)
local i = idx or 1
if quest.condition[i].type == 1 then
if quest.condition[i].id == 1 then
return module.HeroModule.GetManager():Get(11000).level
end
elseif quest.condition[i].type == 34 then
local _endTime = GetQuestEndTime(quest);
if quest.condition[i].id == 1 then
return module.HeroModule.GetHeroCount(_endTime)
end
elseif quest.condition[i].type == 37 then
local _endTime = GetQuestEndTime(quest);
if quest.condition[i].id == 1 then
return module.equipmentModule.EquipCount(_endTime)
elseif quest.condition[i].id == 2 then
return module.equipmentModule.InscripCount(_endTime)
end
elseif quest.condition[i].type == 62 then
local _endTime = GetQuestEndTime(quest);
return module.HeroModule.GetHeroCount(_endTime, quest.condition[i].id)
elseif quest.condition[i].type == 63 then
local _endTime = GetQuestEndTime(quest);
return module.HeroModule.EquipCount(_endTime, quest.condition[i].id)
elseif quest.condition[i].type == 64 then
local _endTime = GetQuestEndTime(quest);
return module.HeroModule.InscripCount(_endTime, quest.condition[i].id)
elseif quest.condition[i].type == 71 then
return module.ItemModule.GetItemCount(quest.condition[i].id)
elseif quest.condition[i].type == 72 then
local _hero = module.HeroModule.GetManager():Get(quest.condition[i].id)
_hero = _hero or {stage = 0}
return _hero.stage
elseif quest.condition[i].type == 74 then
local _hero = module.HeroModule.GetManager():Get(quest.condition[i].id)
_hero = _hero or {star = 0}
return _hero.star
elseif quest.condition[i].type == 91 then
local _list = utils.ItemHelper.GetList(utils.ItemHelper.TYPE.ITEM, quest.condition[i].id)
local _count = 0
for i,v in ipairs(_list) do
_count = _count + module.ItemModule.GetItemCount(v.id)
end
return _count
elseif quest.condition[i].type == 98 then
local _info = module.fightModule.GetFightInfo(quest.condition[i].id)
local _count = 0
if _info then
for i = 1, 3 do
if module.fightModule.GetOpenStar(_info.star, i) ~= 0 then
_count = _count + 1
end
end
end
if _count > 1 then
_count = 1
end
return _count
elseif quest.condition[i].type == 100 then
local _info = module.fightModule.GetFightInfo(quest.condition[i].id)
if _info:IsPassed() then
return 1
end
return 0
elseif quest.condition[i].type == 101 then
return (module.playerModule.Get().starPoint or 0)
elseif quest.condition[i].type == 102 then
local _endTime = GetQuestEndTime(quest)
local _count = module.equipmentModule.EquipLevelCount(_endTime, quest.condition[i].id)
return _count
else
return quest.records[i]
end
end
local function GetConfigType(type)
return questConfigType[type] or {}
end
local acceptSideQuestCo = nil;
local needAccept = false;
local function AcceptSideQuest()
GetQuestConfig()
if acceptSideQuestCo then
needAccept = true;
return;
end
needAccept = false;
acceptSideQuestCo = coroutine.create(function()
for i,v in ipairs(acceptSideQuestList) do
if CanAcceptQuest(v.id) then
local data = utils.NetworkService.SyncRequest(78, {nil, v.id, 0})
if data[2] ~= 0 then
print("自动接", v.id, v.name, sprinttb(v.consume), sprinttb(data));
end
end
end
for i,v in ipairs(submitSideQuestList) do
if CanSubmitQuest(v.id) then
local quest = GetQuest(v.id);
local data = utils.NetworkService.SyncRequest(78, {nil, v.id, 1, 0, quest.stageFlag})
if data[2] ~= 0 then
print("自动交", v.id, v.name, quest.stageFlag, sprinttb(data), debug.traceback());
end
end
end
acceptSideQuestCo = nil;
if needAccept then
AcceptSideQuest();
end
end)
coroutine.resume(acceptSideQuestCo);
end
utils.EventManager.getInstance():addListener("AFTER_QUEST_INFO_CHANGE", function(event, data)
if SceneStack.MapId() ~= 0 then
AcceptSideQuest()
end
end)
utils.EventManager.getInstance():addListener("EQUIPMENT_INFO_CHANGE", function(event, data)
if SceneStack.MapId() ~= 0 then
AcceptSideQuest()
end
end)
utils.EventManager.getInstance():addListener("ShowActorLvUp", function(event, data)
if SceneStack.MapId() ~= 0 then
AcceptSideQuest()
end
end)
utils.EventManager.getInstance():addListener("ITEM_INFO_CHANGE", function(event, data)
if SceneStack.MapId() ~= 0 then
AcceptSideQuest()
end
end)
local function checkChangeNameQuest()
local _quest = GetQuest(101081)
if _quest and _quest.status == 0 then
local _count = module.ItemModule.GetItemCount(90115)
if utils.SGKTools.matchingName(module.playerModule.Get().name) ~= "陆水银" then
FinishQuest(101081)
end
end
end
local function GetOtherQuest(pid,quest_id,CoopQuest_id,refresh,func)
if not refresh and otherQuestTab[pid] and otherQuestTab[pid][quest_id] and otherQuestTab[pid][quest_id].lastQueryTime+15>= module.Time.now() then
if otherQuestTab[pid][quest_id].status == 0 or otherQuestTab[pid][quest_id].status == 1 then
if func then
func()
else
return otherQuestTab[pid][quest_id]
end
end
else
local sn = utils.NetworkService.Send(76, {nil, 0,0,pid,quest_id})
SnArr[sn] = {quest_id = CoopQuest_id,pid = pid,func = func}
end
end
return {
GetList = GetQuestList,
Get = GetQuest,
GetCfg = GetQuestConfig,
GetCfgByType = GetQuestConfigByType,
GetConfigType = GetConfigType,
GetQuestConfigByNPC = GetQuestConfigByNPC,
GetQuestConfigByGuideType = GetQuestConfigByGuideType,
GetQuestConfigByMemory = GetQuestConfigByMemory,
GetGoWhereConfig = GetGoWhereConfig,
GetQuestSequenceCfg = GetQuestSequenceCfg,
GetQuestSubmitItemList = GetQuestSubmitItemList,
GetCfgByMutexId=GetQuestConfigByMutexId,--获取相同互斥ID的任务
Accept = AcceptQuest,
Finish = FinishQuest,
Submit = FinishQuest,
Cancel = CancelQuest,
CanAccept = CanAcceptQuest,
CanSubmit = CanSubmitQuest,
CityContuctInfo = CityContuctInfo,
CityContuctAcceptQuest = CityContuctAcceptQuest,
CityContuctCancelQuest = CityContuctCancelQuest,
CityContuctSubmitQuest = CityContuctSubmitQuest,
CityContructFightBoss = CityContructFightBoss,
RegisterQuest = RegisterQuest,
RemoveQuest = RemoveQuest,
GetCanAccept = GetCanAccept,
StartQuestGuideScript = startQuestGuideScript,
GetOldUuid = GetOldUuid,
SetOldUuid = SetOldUuid,
GetNpcStatus = getNpcStatus,
GetRedPointState = GetRedPointState,
GetOtherRecords = getOtherRecords,
GetSevenDayOpen = GetSevenDayOpen,
AcceptActivityQuest = AcceptActivityQuest,
QueryQuestList = QueryQuestList,
AcceptSideQuest = AcceptSideQuest,
GetChapter = GetChapter,
NotifyNpcStatusChange = notifyNpcStatusChange,
callQuestScript = callQuestScript,
CheckChangeNameQuest = checkChangeNameQuest,
AutoAcceptNextIdList = AutoAcceptNextIdList,
GetOtherQuest = GetOtherQuest,
}
|
data:extend(
{
{
type = "item",
name = "uranium-fuel",
icon = "__Engineersvsenvironmentalist__/graphics/icons/ore/uraninite.png",
flags = {"goes-to-main-inventory"},
fuel_category = "chemical", fuel_value = "400PJ",
subgroup = "fuel-processing",
order = "c[solid-fuel]",
stack_size = 50
},
{
type = "item",
name = "enriched-uranium",
icon = "__Engineersvsenvironmentalist__/graphics/icons/ore/uraninite.png",
flags = {"goes-to-main-inventory"},
fuel_category = "chemical", fuel_value = "2EJ",
subgroup = "fuel-processing",
order = "c[solid-fuel]",
stack_size = 50
},
{
type = "item",
name = "highly-enriched-uranium",
icon = "__Engineersvsenvironmentalist__/graphics/icons/ore/uraninite.png",
flags = {"goes-to-main-inventory"},
fuel_category = "chemical", fuel_value = "8EJ",
subgroup = "fuel-processing",
order = "c[solid-fuel]",
stack_size = 50
},
{
type = "item",
name = "uranium-dust",
icon = "__Engineersvsenvironmentalist__/graphics/icons/ore/uraninite.png",
flags = {"goes-to-main-inventory"},
subgroup = "fuel-processing",
order = "c[solid-fuel]",
stack_size = 100000
},
{
type = "recipe",
name = "uranium-fuel-2",
category = "chemistry",
energy_required = 30000,
ingredients =
{
{type="item", name="uranium-dust", amount=50000},
{type="fluid", name="hydrogen-fluoride", amount=10},
},
results=
{
{type="item", name="uranium-fuel", amount=1}
},
icon = "__Engineersvsenvironmentalist__/graphics/icons/ore/uraninite.png",
subgroup = "fuel-processing",
enabled = false,
order = "uranium"
},
{
type = "recipe",
name = "uranium-fuel",
category = "chemistry",
energy_required = 30000,
ingredients =
{
{type="item", name="uraninite", amount=1},
{type="fluid", name="hydrogen-fluoride", amount=10},
},
results=
{
{type="item", name="uranium-fuel", amount=1}
},
icon = "__Engineersvsenvironmentalist__/graphics/icons/ore/uraninite.png",
subgroup = "fuel-processing",
enabled = false,
order = "uranium"
},
{
type = "recipe",
name = "uranium-fuel",
category = "chemistry",
energy_required = 30000,
ingredients =
{
{type="item", name="uraninite", amount=1},
{type="fluid", name="hydrogen-fluoride", amount=10},
},
results=
{
{type="item", name="uranium-fuel", amount=1}
},
icon = "__Engineersvsenvironmentalist__/graphics/icons/ore/uraninite.png",
subgroup = "fuel-processing",
enabled = false,
order = "uranium"
},
{
type = "recipe",
name = "enriched-uranium",
category = "chemistry",
energy_required = 40000,
ingredients =
{
{type="item", name="uranium-fuel", amount=5},
{type="fluid", name="hydrogen-fluoride", amount=100},
},
results=
{
{type="item", name="enriched-uranium", amount=1}
},
icon = "__Engineersvsenvironmentalist__/graphics/icons/ore/uraninite.png",
subgroup = "fuel-processing",
enabled = false,
order = "uranium"
},
{
type = "recipe",
name = "highly-enriched-uranium",
category = "chemistry",
energy_required = 40000,
ingredients =
{
{type="item", name="enriched-uranium", amount=4},
{type="fluid", name="hydrogen-fluoride", amount=1000},
},
results=
{
{type="item", name="highly-enriched-uranium", amount=1}
},
icon = "__Engineersvsenvironmentalist__/graphics/icons/ore/uraninite.png",
subgroup = "fuel-processing",
enabled = false,
order = "uranium"
},
}
)
|
-- Copyright (C) Yichun Zhang (agentzh)
local base = require "resty.core.base"
base.allows_subsystem('http')
local ffi = require "ffi"
local C = ffi.C
local ffi_str = ffi.string
local getfenv = getfenv
local error = error
local errmsg = base.get_errmsg_ptr()
local get_string_buf = base.get_string_buf
local FFI_ERROR = base.FFI_ERROR
ffi.cdef[[
int ngx_http_lua_ffi_ssl_set_serialized_session(ngx_http_request_t *r,
const unsigned char *buf, int len, char **err);
int ngx_http_lua_ffi_ssl_get_serialized_session(ngx_http_request_t *r,
char *buf, char **err);
int ngx_http_lua_ffi_ssl_get_session_id(ngx_http_request_t *r,
char *buf, char **err);
int ngx_http_lua_ffi_ssl_get_serialized_session_size(ngx_http_request_t *r,
char **err);
int ngx_http_lua_ffi_ssl_get_session_id_size(ngx_http_request_t *r,
char **err);
]]
local _M = { version = base.version }
-- return session, err
function _M.get_serialized_session()
local r = getfenv(0).__ngx_req
if not r then
error("no request found")
end
local len = C.ngx_http_lua_ffi_ssl_get_serialized_session_size(r, errmsg)
if len < 0 then
return nil, ffi_str(errmsg[0])
end
if len > 4096 then
return nil, "session too big to serialize"
end
local buf = get_string_buf(len)
local rc = C.ngx_http_lua_ffi_ssl_get_serialized_session(r, buf, errmsg)
if rc == FFI_ERROR then
return nil, ffi_str(errmsg[0])
end
return ffi_str(buf, len)
end
-- return session_id, err
function _M.get_session_id()
local r = getfenv(0).__ngx_req
if not r then
error("no request found")
end
local len = C.ngx_http_lua_ffi_ssl_get_session_id_size(r, errmsg)
if len < 0 then
return nil, ffi_str(errmsg[0])
end
local buf = get_string_buf(len)
local rc = C.ngx_http_lua_ffi_ssl_get_session_id(r, buf, errmsg)
if rc == FFI_ERROR then
return nil, ffi_str(errmsg[0])
end
return ffi_str(buf, len)
end
-- return ok, err
function _M.set_serialized_session(sess)
local r = getfenv(0).__ngx_req
if not r then
error("no request found")
end
local rc = C.ngx_http_lua_ffi_ssl_set_serialized_session(r, sess, #sess,
errmsg)
if rc == FFI_ERROR then
return nil, ffi_str(errmsg[0])
end
return true
end
return _M
|
dependencies = {}
files = {"init.lua", "receiver.lua", "sender_export.lua"}
exposed = {"receiver.lua"}
function init() print("Version 1.0") end
return {
dependencies = dependencies,
files = files,
exposed = exposed,
init = init
}
|
require "common.p8declares"
function OnPropertyChanged(sProperty)
local propertyValue = Properties[sProperty]
if (LOG ~= nil and type(LOG) == "table") then
LogTrace("OnPropertyChanged(" .. sProperty .. ") changed to: " .. Properties[sProperty])
end
-- Remove any spaces (trim the property)
local trimmedProperty = string.gsub(sProperty, " ", "")
local status = true
local err = ""
if (ON_PROPERTY_CHANGED[sProperty] ~= nil and type(ON_PROPERTY_CHANGED[sProperty]) == "function") then
status, err = pcall(ON_PROPERTY_CHANGED[sProperty], propertyValue)
elseif (ON_PROPERTY_CHANGED[trimmedProperty] ~= nil and type(ON_PROPERTY_CHANGED[trimmedProperty]) == "function") then
status, err = pcall(ON_PROPERTY_CHANGED[trimmedProperty], propertyValue)
end
if (not status) then
LogError("LUA_ERROR: " .. err)
end
end
function UpdateProperty(propertyName, propertyValue)
if (Properties[propertyName] ~= nil) then
C4:UpdateProperty(propertyName, propertyValue)
end
end |
function solveTheta(lat)
local t = lat/2;
local dt = 0
for i=1,20 do
--repeat
dt = -(t + sin(t)*cos(t) + 2*sin(t) - (2+pi*0.5)*sin(lat))/(2*cos(t)*(1+cos(t)))
t = t+dt
--until dt < 0.001
end
return t
end
function get_max_x(y,lat)
if y ~= lasty then
local t = solveTheta(abs(lat))
maxx = 2/sqrt(pi*(4+pi))*pi*(1+cos(t))
lasty = y
end
return maxx
end
function lens_inverse(x,y)
local t = asin(y/2*sqrt((4+pi)/pi))
local lat = asin((t+sin(t)*cos(t)+2*sin(t))/(2+pi*0.5))
local lon = sqrt(pi*(4+pi))*x/(2*(1+cos(t)))
if abs(y) > maxy or abs(x) > get_max_x(y,lat) then
return nil
end
return latlon_to_ray(lat,lon)
end
function lens_forward(x,y,z)
local lat,lon = ray_to_latlon(x,y,z)
local t = solveTheta(lat)
local x = 2/sqrt(pi*(4+pi))*lon*(1+cos(t))
local y = 2*sqrt(pi/(4+pi))*sin(t)
return x,y
end
local t = solveTheta(pi*0.5)
maxy = 2*sqrt(pi/(4+pi))*sin(t)
max_fov = 360
max_vfov = 180
t = solveTheta(0)
lens_width = 2/sqrt(pi*(4+pi))*pi*(1+cos(t))*2
lens_height = 2*maxy
onload = "f_contain"
|
local doors = {
{x= 191009.0, y= 206329.0, z= 1320.0, h= -90.0, x2= 191012.0, y2= 206707.0, z2= 1322.0, h2=90.0}, -- Comico back entrance
{x= 189357.0, y= 208903.0, z= 1311.0, h= 90.0, x2= 189370.0, y2= 208488.0, z2= 1322.0, h2=-90.0}, -- Comico main entrance
{x= 191238.0, y= 207037.0, z= 1322.0, h= 180.0, x2= 191238.0, y2= 207037.0, z2= 2423.0, h2=180.0}, -- Ascenceur comico
{x= 171636.0, y= 195417.0, z= 584.0, h= -90.0, x2= 170138.0, y2= 194165.0, z2= 1396.0, h2=180.0}, -- Prefecture 1
}
local text3d = {}
AddEvent("OnPackageStart", function()
for k,v in pairs(doors) do
text3d[k] = {}
text3d[k]["enter"] = CreateText3D("[E]", 17, v.x, v.y, v.z + 100, 0.0, 0.0, 0.0)
text3d[k]["exit"] = CreateText3D("[E]", 17, v.x2, v.y2, v.z2 + 100, 0.0, 0.0, 0.0)
end
end)
AddEvent("OnPackageStop", function()
for k,v in pairs(text3d) do
DestroyText3D(v.enter)
DestroyText3D(v.exit)
end
end)
AddEvent("OnPlayerSpawn", function(player)
CallRemoteEvent(player, "SendDoors", doors)
end)
AddRemoteEvent("OnPlayerUseDoors", function(player, id, exit)
local tp = doors[id]
if tp ~= nil then
if not exit then
SetPlayerLocation(player, tp.x2, tp.y2, tp.z2)
SetPlayerHeading(player, tp.h2)
else
SetPlayerLocation(player, tp.x, tp.y, tp.z)
SetPlayerHeading(player, tp.h)
end
end
end) |
function test_async_post()
print "Async post test"
local function OnLoad (data)
if data ~= "" then print ("Data received") end
System.Application.Exit (0)
end
local callback = Common.File.CreateAsyncLoadHandler (OnLoad)
local FILE_NAME = "http://untgames.com"
local result = Common.File.AsyncPostString (FILE_NAME, "post_string", callback)
print ("Test completed")
end
function test ()
test_async_post ()
end
|
local itemKey = ARGV[1]
local vector = ARGV[2]
-- Retrieve all the tripple where the item is the subject.
local SPOTrippleList = redis.call('ZRANGEBYLEX', itemKey, '[SPO:'.. vector ..':', '[SPO:'.. vector ..'\xff')
-- Retrieve all the tripple where the item is the object.
local OPSTrippleList = redis.call('ZRANGEBYLEX', itemKey, '[OPS:'.. vector ..':', '[OPS:'.. vector ..'\xff')
redis.log(redis.LOG_DEBUG, string.format("Nucleus: Retrieved %s relationship(s) for vector %s.", table.getn(SPOTrippleList) + table.getn(OPSTrippleList), vector));
-- Splits a tripple into a table
local function splitTripple (tripple)
local splittedTripple = {}
local index = 1
for vector in string.gmatch(tripple, "([^:]+)") do
splittedTripple[index] = vector
index = index + 1
end
return splittedTripple
end
-- Archive a tripple
local function archiveTripple(itemKey, subject, predicate, object)
redis.call('ZREM', itemKey, 'SPO:'..subject..':'..predicate..':'..object)
redis.call('ZREM', itemKey, 'SOP:'..subject..':'..object..':'..predicate)
redis.call('ZREM', itemKey, 'OPS:'..object..':'..predicate..':'..subject)
redis.call('ZREM', itemKey, 'OSP:'..object..':'..subject..':'..predicate)
redis.call('ZREM', itemKey, 'PSO:'..predicate..':'..subject..':'..object)
redis.call('ZREM', itemKey, 'POS:'..predicate..':'..object..':'..subject)
redis.call('ZADD', itemKey, 0, '*SPO:'..subject..':'..predicate..':'..object)
redis.call('ZADD', itemKey, 0, '*SOP:'..subject..':'..object..':'..predicate)
redis.call('ZADD', itemKey, 0, '*OPS:'..object..':'..predicate..':'..subject)
redis.call('ZADD', itemKey, 0, '*OSP:'..object..':'..subject..':'..predicate)
redis.call('ZADD', itemKey, 0, '*PSO:'..predicate..':'..subject..':'..object)
redis.call('ZADD', itemKey, 0, '*POS:'..predicate..':'..object..':'..subject)
redis.log(redis.LOG_DEBUG, string.format("Nucleus: Archived the relationship between %s, %s and %s.", subject, predicate, object));
end
for index, tripple in pairs(SPOTrippleList) do
local splittedTripple = splitTripple(tripple)
local subject = vector
local predicate = splittedTripple[3]
local object = splittedTripple[4]
archiveTripple(itemKey, subject, predicate, object)
end
for index, tripple in pairs(OPSTrippleList) do
local splittedTripple = splitTripple(tripple)
local subject = splittedTripple[4]
local predicate = splittedTripple[3]
local object = vector
if predicate ~= "is-authored-by" then
archiveTripple(itemKey, subject, predicate, object)
end
end
return { SPOTrippleList, OPSTrippleList } |
--[[
█▀▀█ █▀▀█ █▀▀█ ░░▀ █▀▀ █▀▀ ▀▀█▀▀ ▀▀█ █▀▀ █▀▀█ █▀▀█
█░░█ █▄▄▀ █░░█ ░░█ █▀▀ █░░ ░░█░░ ▄▀░ █▀▀ █▄▄▀ █░░█
█▀▀▀ ▀░▀▀ ▀▀▀▀ █▄█ ▀▀▀ ▀▀▀ ░░▀░░ ▀▀▀ ▀▀▀ ▀░▀▀ ▀▀▀▀
SCRIPT CREADO POR ByBlackDeath
DISCORD DEl CREADOR: ByBlackDeath#5528
]]--
X.OpenGetMenu = function(id)
local elements = {}
ESX.TriggerServerCallback('reborn_jobs:getWarehouse', function(warehouse)
X.LastShop = warehouse
table.insert(elements, {value = "wood" , valueLabel = Local.wood , material = X.LastShop.materials.wood, maxMaterial = X.LastShop.maxMaterials.wood, label = "<span style='color: orange;'>Madera</span><b> : "..X.LastShop.materials.wood.."/"..X.LastShop.maxMaterials.wood.."</b>"})
table.insert(elements, {value = "food" , valueLabel = Local.food , material = X.LastShop.materials.food, maxMaterial = X.LastShop.maxMaterials.food, label = "<span style='color: green;'>Comida</span><b> : "..X.LastShop.materials.food.."/"..X.LastShop.maxMaterials.food.."</b>"})
table.insert(elements, {value = "mine" , valueLabel = Local.mine , material = X.LastShop.materials.mine, maxMaterial = X.LastShop.maxMaterials.mine, label = "<span style='color: yellow;'>Minerales</span><b> : "..X.LastShop.materials.mine.."/"..X.LastShop.maxMaterials.mine.."</b>"})
table.insert(elements, {value = "water", valueLabel = Local.water, material = X.LastShop.materials.water, maxMaterial = X.LastShop.maxMaterials.water, label = "<span style='color: cyan;'>Agua</span><b> : "..X.LastShop.materials.water.."/"..X.LastShop.maxMaterials.water.."</b>"})
table.insert(elements, {value = "infoTrucks", label = Local.infoTrucks})
table.insert(elements, {value = "infoVans", label = Local.infoVans})
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'warehouse', {
title = Local.warehouse,
align = 'top-left',
elements = elements
}, function(data, menu)
if data.current.value == "infoTrucks" then
ESX.ShowNotification(Local.haveToBuy)
local msg = "Camiones: "
for k,v in pairs(Config.AvaliableTrucks) do
if k % 2 == 0 then
msg = msg.."~g~"..v.." "
else
msg = msg.."~o~"..v.." "
end
end
ESX.ShowNotification(msg)
elseif data.current.value == "infoVans" then
ESX.ShowNotification(Local.haveToBuy)
local msg = "Furgonetas: "
for k,v in pairs(Config.AvaliableVans) do
if k % 2 == 0 then
msg = msg.."~g~"..v.." "
else
msg = msg.."~o~"..v.." "
end
end
ESX.ShowNotification(msg)
elseif data.current.value then
X.Material = data.current.value
X.ActualWarehouse = X.LastShop.storeName
X.OpenOptionMenu()
end
end,
function(data, menu)
isMenuOpened = false
menu.close()
end
)
end, id)
end
X.OpenGetCharge = function()
ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'warehouse_charge',
{
title = Local.load..X.Material.." ("..Local.maxCharge..Config.MaxWeight[X.Option].." "..Local.tons..")",
}, function(data, menu)
local parameter = data.value
local tons = tonumber(parameter)
if X.Option == 'truck' then
if X.IsAValidTruck() then
ESX.TriggerServerCallback('reborn_jobs:getWarehouse', function(warehouse)
if tons > 0 and tons < Config.MaxWeight[X.Option] then
if warehouse.materials[X.Material] >= tons then
ESX.Game.SpawnVehicle(Config.TrailersModels[X.Material].go, X.LastShop.spawnCharge, X.LastShop.spawnCharge.h, function(vehicle)
local plate = X.GenerateUniquePlate()
SetVehicleNumberPlateText(vehicle, plate)
TriggerServerEvent('reborn_jobs:addTrailer', X.Trim(GetVehicleNumberPlateText(vehicle)), tons)
TriggerServerEvent('reborn_jobs:removeMaterial', X.LastShop.storeName, X.Material, tons)
X.GoToNextStep()
end)
else
ESX.ShowNotification(Local.notenough)
end
else
ESX.ShowNotification(Local.invalidAumont)
end
end, X.ActualWarehouse)
else
ESX.ShowNotification(Local.notTruckAllowed)
end
elseif X.Option == 'van' then
if X.IsAValidVan() then
ESX.TriggerServerCallback('reborn_jobs:getWarehouse', function(warehouse)
if tons > 0 and tons <= Config.MaxWeight[X.Option] then
if warehouse.materials[X.Material] >= tons then
X.Tons = tons
TriggerServerEvent('reborn_jobs:removeMaterial', X.LastShop.storeName, X.Material, X.Tons)
ESX.ShowNotification(Local.goToCharge)
X.GoToNextStep()
else
ESX.ShowNotification(Local.notenough)
end
else
ESX.ShowNotification(Local.invalidAumont)
end
end, X.ActualWarehouse)
else
ESX.ShowNotification(Local.notTruckAllowed)
end
end
menu.close()
end, function(data, menu)
menu.close()
end)
end
X.OpenOptionMenu = function()
local elements = {}
table.insert(elements, {value = "truck", label = Local.loadTruck})
table.insert(elements, {value = "van", label = Local.loadVan})
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'warehouse_load', {
title = Local.warehouse,
align = 'top-left',
elements = elements
}, function(data2, menu2)
if data2.current.value then
X.IsSelecting = true
X.Option = data2.current.value
ESX.ShowNotification(Local.youSelect..Local[X.Material].."~w~ "..Local.inLabel.." ~o~"..X.ActualWarehouse.."~w~. "..Local.youNeed.." ~y~"..Local[X.Option])
ESX.UI.Menu.CloseAll()
end
end,
function(data2, menu2)
menu2.close()
end
)
end
X.CancelCharging = function()
X.Material = nil
X.ActualWarehouse = nil
X.Option = nil
X.IsSelecting = false
end
X.ExistsPlate = function(trailers, plate)
for k,v in pairs(trailers) do
if v.plate == plate then
return true
end
end
return false
end
X.GoToNextStep = function()
if X.Option == 'truck' then
X.IsSelecting = false
X.IsCarrying = true
elseif X.Option == 'van' then
X.IsSelecting = false
X.IsChargingBox = true
end
end
X.GenerateUniquePlate = function()
local plate = nil
ESX.TriggerServerCallback('reborn_jobs:getTrailers', function(trailers)
local intentOfPlate = "TRC "..math.random(100, 999)
while X.ExistsPlate(trailers, intentOfPlate) == true do
intentOfPlate = "TRC "..math.random(100, 999)
end
plate = intentOfPlate
end)
while plate == nil do
Wait(0)
end
return plate
end |
-- Natural Selection 2 Competitive Mod
-- Source located at - https://github.com/xToken/CompMod
-- lua\CompMod\Mixins\OrdersMixin\server.lua
-- - Dragon
local oldOrdersMixinOnUpdate = OrdersMixin.OnUpdate
function OrdersMixin:OnUpdate(deltaTime)
oldOrdersMixinOnUpdate(self, deltaTime)
local currentOrder = self:GetCurrentOrder()
if currentOrder and (self.lastInvalidOrderCheck or 0) + 1 < Shared.GetTime() then
local orderType = currentOrder:GetType()
if orderType == kTechId.Attack then
local orderTarget = Shared.GetEntity(currentOrder:GetParam())
if orderTarget and (orderTarget:isa("Player") and not orderTarget:GetIsSighted()) then
-- Targeted player that is no longer visible, clear
self:ClearOrders()
end
elseif orderType == kTechId.Defend then
local orderTarget = Shared.GetEntity(currentOrder:GetParam())
if orderTarget and GetAreEnemies(self, orderTarget) then
-- We cant defend enemies...
self:ClearOrders()
end
end
self.lastInvalidOrderCheck = Shared.GetTime()
end
end |
return function(center, surface) --small smelting station
local ce = function(params)
params.raise_built = true
return surface.create_entity(params)
end
local fN = game.forces.neutral
local direct = defines.direction
ce{name = "stone-furnace", position = {center.x-2, center.y-2}, force = fN}
local chest = ce{name = "wooden-chest", position = {center.x, center.y-1}, force = fN}
if chest then
chest.insert{name = "coal", count = math.random(1, 10)}
chest.insert{name = "iron-ore", count = math.random(1, 40)}
end
end
|
--获取随机整数
math.random = jass.GetRandomInt
--求距离
function math.distance(x1, y1, x2, y2)
local x = x1 - x2
local y = y1 - y2
return math.sqrt(x * x + y * y)
end
--
function math.less(x, y)
return x < y
end
function math.more(x, y)
return x > y
end
--计算2个角度之间的夹角
function math.angle(r1, r2)
local r = (r1 - r2) % 360
if r > 0 then
if r > 180 then
return 360 - r
else
return r
end
else
if r < - 180 then
return 360 + r
else
return - r
end
end
end
--弧度去死吧
local deg = math.deg(1)
local rad = math.rad(1)
--正弦
local sin = math.sin
function math.sin(r)
return sin(r * rad)
end
--余弦
local cos = math.cos
function math.cos(r)
return cos(r * rad)
end
--正切
local tan = math.tan
function math.tan(r)
return tan(r * rad)
end
--反正弦
local asin = math.asin
function math.asin(v)
return asin(v) * deg
end
--反余弦
local acos = math.acos
function math.acos(v)
return acos(v) * deg
end
--反正切
local atan = math.atan2
function math.atan(v1, v2)
return atan(v1, v2) * deg
end
math.atan2 = math.atan |
local E, L, V, P, G = unpack(ElvUI); --Inport: Engine, Locales, PrivateDB, ProfileDB, GlobalDB, Localize Underscore
local M = E:GetModule('MiscEnh')
-- Based on ElvUI_TransparentMovers by: Dandruff @ Whisperwind
function M:UpdateMoverTransparancy()
local mover
for name, _ in pairs(E.CreatedMovers) do
mover = _G[name]
if mover then
mover:SetAlpha(E.db.general.movertransparancy)
end
end
end
function M:LoadMoverTransparancy()
-- hook create function for movers created after this method has run
hooksecurefunc(E, 'CreateMover', function(self, parent)
parent.mover:SetAlpha(E.db.general.movertransparancy)
end)
-- update transparancy of all created movers
self:UpdateMoverTransparancy()
end |
local CorePackages = game:GetService("CorePackages")
local Roact = require(CorePackages.Roact)
local Constants = require(script.Parent.Parent.Constants)
local FONT = Constants.Font.MainWindowHeader
local TEXT_SIZE = Constants.DefaultFontSize.MainWindowHeader
local TEXT_COLOR = Constants.Color.Text
local function HeaderButton(props)
local text = props.text
local size = props.size
local pos = props.pos
local sortfunction = props.sortfunction
return Roact.createElement("TextButton", {
Text = text,
TextSize = TEXT_SIZE,
TextColor3 = TEXT_COLOR,
Font = FONT,
TextXAlignment = Enum.TextXAlignment.Left,
Size = size,
Position = pos,
BackgroundTransparency = 1,
[Roact.Event.Activated] = function()
if sortfunction then
sortfunction(text)
end
end,
})
end
return HeaderButton |
local Block
local Line
if game then
local pluginModel = script.Parent.Parent.Parent.Parent
Block = require(pluginModel.com.blacksheepherd.code.Block)
Line = require(pluginModel.com.blacksheepherd.code.Line)
else
Block = require("com.blacksheepherd.code.Block")
Line = require("com.blacksheepherd.code.Line")
end
local FunctionBlock
do
local _parent_0 = Block
local _base_0 = {
BeforeRender = function(self)
return tostring(self._indent) .. tostring(self._name) .. " = function(" .. tostring(self._parameters) .. ")"
end,
AfterRender = function(self)
return tostring(self._indent) .. "end"
end,
AddLineIfNotAdded = function(self, lineString)
if not (self._addedLines[lineString]) then
self._addedLines[lineString] = true
return self:AddChild(Line(lineString))
end
end
}
_base_0.__index = _base_0
setmetatable(_base_0, _parent_0.__base)
local _class_0 = setmetatable({
__init = function(self, name, parameters)
_parent_0.__init(self)
self._name = name
self._parameters = parameters
self._addedLines = { }
end,
__base = _base_0,
__name = "FunctionBlock",
__parent = _parent_0
}, {
__index = function(cls, name)
local val = rawget(_base_0, name)
if val == nil then
return _parent_0[name]
else
return val
end
end,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
if _parent_0.__inherited then
_parent_0.__inherited(_parent_0, _class_0)
end
FunctionBlock = _class_0
end
return FunctionBlock
|
mmCreateView("t1", "MpiClusterView", "::t1::mcview")
mmCreateModule("SimpleClusterClient", "::mcc")
mmCreateModule("MpiProvider", "::mpi")
mmCreateCall("SimpleClusterClientViewRegistration", "::t1::mcview::register", "::mcc::registerView")
mmCreateCall("MpiCall", "::t1::mcview::requestMpi", "::mpi::provideMpi")
|
--- An output stream that writes to a file.
--
-- @module FileOutputStream
-- @author sci4me
-- @license MIT
-- @copyright Scitoshi Nakayobro 2021
local class = require "middleclass"
local OutputStream = require "iostream.OutputStream"
local char = string.char
local FileOutputStream = class("FileOutputStream", OutputStream)
function FileOutputStream:initialize(path)
self.fh = io.open(path, "wb")
end
function FileOutputStream:writeU8(x)
if type(x) ~= "number" then error("expected number, got " .. type(x)) end
if x < 0 or x > 255 or (x % 1 ~= 0) then error("expected an unsigned byte, got " .. tostring(x)) end
self.fh:write(char(x))
end
function FileOutputStream:flush()
self.fh:flush()
end
function FileOutputStream:close()
self.fh:close()
end
return FileOutputStream |
--[[ Copyright (c) 2019 robot256 (MIT License)
* Project: Multiple Unit Train Control
* File: checkModuleMatching.lua
* Description: Checks if a pair of locos are RET modular type, and if the module configurations match.
* Returns true if they are not modular locos.
--]]
local moduleTypes = nil
local function isRelevantModule(name)
if moduleTypes == nil then
moduleTypes = {}
game.print("MUTC is Caching RET module types")
-- Cache table of allowable modules
if game.technology_prototypes["ret-modular-locomotives"] then
for _,effect in pairs(game.technology_prototypes["ret-modular-locomotives"].effects) do
if effect.type == "unlock-recipe" and game.equipment_prototypes[effect.recipe] then
moduleTypes[effect.recipe] = true
--game.print("Cached module type " .. effect.recipe)
end
end
end
end
if moduleTypes[name] then
return true
else
return false
end
end
function checkModuleMatching(loco1, loco2)
-- Given a pair of locos that have same type and are in the right spot in the train to be a pair
-- Check if they have modular locomotive grids
if loco1.grid and loco1.grid.prototype.name=="modular-locomotive-grid" then
-- Read grid contents of both locos
local gridOne = loco1.grid.get_contents()
local gridTwo = loco2.grid.get_contents()
local matched = true
for k,v in pairs(gridOne) do
if isRelevantModule(k) and not(gridTwo[k] and gridTwo[k]==v) then
matched = false
break
end
end
if matched then
for k,v in pairs(gridTwo) do
if isRelevantModule(k) and not(gridOne[k] and gridOne[k]==v) then
matched = false
break
end
end
end
return matched
else
-- Not a modular locomotive, always able to replace
return true
end
end
return checkModuleMatching
|
--[[
joli-lune
small framework for love2d
MIT License (see licence file)
]]
local Render = require "src.renderer"
local lg = love.graphics
local ShapeRenderer = Render:extend(Render)
local shapefunc = {
rect = lg.rectangle,
circ = lg.circle,
poly = lg.polygon,
line = lg.line
}
local getArgs = {
rect = function(mode, x, y, arg1, arg2)
return mode, x, y, arg1, arg2
end,
circ = function(mode, x, y, arg1, arg2)
return mode, x, y, arg1
end,
poly = function(mode, x, y, arg1, arg2)
return mode, arg1
end,
line = function(mode, x, y, arg1, arg2)
return {arg1[1]+x,arg1[2]+y,arg1[3]+x,arg1[4]+y}
end,
}
function ShapeRenderer:__tostring()
return "shaperenderer"
end
function ShapeRenderer:new(game, type, color, mode, arg1, arg2)
ShapeRenderer.super.new(self)
self.game = game
self.rendertype = "shape"
self.type = type
self.mode = mode or "fill"
self.arg1 = arg1
self.arg2 = arg2
self.tint = color
self.linestyle = "rough"
if type == "line" then
--self.linestyle = self.mode or "rough"
end
end
function ShapeRenderer:draw(position, x, y, z, r, sx, sy,ox,oy)
ShapeRenderer.super.draw(self)
x, y = self:getPosition(x,y,ox,oy)
if self.clip then
lg.setScissor(position.x+self.clip.x,position.y+self.clip.y,self.clip.width,self.clip.height)
end
lg.push()
lg.scale(sx,sy)
lg.rotate(r)
lg.setLineStyle(self.linestyle)
shapefunc[self.type](getArgs[self.type](self.mode, x, y, self.arg1, self.arg2))
lg.pop()
if self.tint then
lg.setColor(1,1,1,1)
end
if self.clip then
lg.setScissor()
end
if self.shader then
lg.setShader()
end
end
function ShapeRenderer:debugLayout(ui)
ShapeRenderer.super.debugLayout(self,ui)
ui:layoutRow('dynamic', 20, 1)
ui:label("Type : "..self.type)
ui:label("Mode : "..self.mode)
if self.type == "rect" then
ui:layoutRow('dynamic', 20, 2)
self.arg1 = ui:property("Width", 0, self.arg1, 10000000, 1, 1)
self.arg2 = ui:property("Height", 0, self.arg2, 10000000, 1, 1)
end
if self.type == "circ" then
ui:layoutRow('dynamic', 20, 1)
self.arg1 = ui:property("Radius", -10000000, self.arg1, 10000000, 1, 1)
end
end
return ShapeRenderer |
local tArgs = {...}
if tArgs[1] == nil then
print("Please type a url.")
local url = read()
local file = http.get(url)
print("What would you like to download it as?")
local filename = read()
local f = fs.open(filename, "w")
f.write(file.readAll)
f.close()
f = fs.open(filename, "r")
print("showing the file...")
print(f.readAll())
while true do
print("Is this correct? [Y/n]")
local event, key = os.pullEvent( "key" ) -- limit os.pullEvent to the 'key' event
if key == keys.y then
print( "Downloaded "..filename.." from "..url.."." )
break
else
print("retrying...")
dofile("download")
end
end
else
if (tArgs[2] == "as") and (tArgs[3] ~= nil) then
local file = http.get(tArgs[1])
local f = fs.open(tArgs[3], "w")
f.write(file.readAll)
f.close()
f = fs.open(tArgs[3], "r")
print("showing the file...")
print(f.readAll())
while true do
print("Is this correct? [Y/n]")
local event, key = os.pullEvent( "key" ) -- limit os.pullEvent to the 'key' event
if key == keys.y then
print( "Downloaded "..filename.." from "..url.."." )
break
else
print("retrying...")
dofile("download")
end
end
end
end
|
--[[
MTA Role Play (mta-rp.pl)
Autorzy poniższego kodu:
- Patryk Adamowicz <[email protected]>
Discord: PatrykAdam#1293
Link do githuba: https://github.com/PatrykAdam/mtarp
--]]
local screenX, screenY = guiGetScreenSize()
local scaleX, scaleY = math.max(0.6, (screenX / 1920)), math.max(0.6, (screenY / 1080))
local notify = {}
notify.waiting = {}
notify.W, notify.H = 344 * scaleX, 104 * scaleX
notify.font = dxCreateFont( "assets/Lato-Regular.ttf", 11 * scaleX )
notify.noLimit = {}
function addNotify(message, time)
if not time then
time = (dxGetTextWidth( message, 1.0, "default" )/100) * 1000
if time < 2000 then
time = 2000
end
end
if string.len(message) > 51 then
if #notify.noLimit == 2 then table.remove(notify.noLimit, 2) end
local message, space = exports.sarp_main:wordBreak(message, 405 * scaleX, false, 1.0, notify.font)
table.insert(notify.noLimit, {
time = time,
state = 0,
height = (space + 1) * dxGetFontHeight( 1.0, notify.font ),
message = message
})
if #notify.noLimit == 1 then
addEventHandler( "onClientRender", root, notify.noLimitRender)
end
else
if #notify.waiting > 10 then table.remove(notify.waiting, 10) end
table.insert(notify.waiting, {
time = time,
state = 0,
message = exports.sarp_main:wordBreak(message, 210 * scaleX, false, 1.0, notify.font)
})
if #notify.waiting == 1 then
addEventHandler( "onClientRender", root, notify.onRender)
end
end
end
addEvent("addNotify", true)
addEventHandler( "addNotify", root, addNotify )
function notify.onRender()
for i = 1, 3 do
local current = notify.waiting[i]
if current then
local X, alpha
if current.state == 0 then
if not current.startTick then
current.startTick = getTickCount()
local sound = playSound( "assets/sound.mp3" )
setSoundVolume( sound, 0.5 )
end
local progress = (getTickCount() - current.startTick) / 500
X, alpha = interpolateBetween( screenX + notify.W, 0, 0,
screenX - notify.W, 255, 0,
progress, "Linear" )
if progress > 1 then
current.startTick = getTickCount()
current.state = 1
end
elseif current.state == 1 then
X = screenX - notify.W
alpha = 255
if getTickCount() - current.startTick >= current.time then
current.startTick = getTickCount()
current.state = 2
end
elseif current.state == 2 then
local progress = (getTickCount() - current.startTick) / 500
X, alpha = interpolateBetween( screenX - notify.W, 255, 0,
screenX + notify.W, 0, 0,
progress, "Linear" )
if progress > 1 then
table.remove(notify.waiting, i)
if #notify.waiting == 0 then
removeEventHandler( "onClientRender", root, notify.onRender)
end
end
end
dxDrawImage( X, 70 * scaleX + (90 * scaleX)*i, notify.W, notify.H, "assets/notificationGUI.png", 0, 0, 0, tocolor(255, 255, 255, alpha) )
dxDrawText( current.message, X + 95 * scaleX, 70 * scaleX + (90 * scaleX)*i + 10 * scaleX, 0, 85 * scaleX + (90 * scaleX)*i + 85 * scaleX, tocolor(211, 211, 211, alpha), 1.0, notify.font, "left", "center", false, false, false, true )
end
end
end
function notify.noLimitRender()
local current = notify.noLimit[1]
local alpha
if current then
if current.state == 0 then
if not current.startTick then
current.startTick = getTickCount()
end
local progress = (getTickCount() - current.startTick) / 500
alpha = interpolateBetween( 0, 0, 0,
255, 0, 0,
progress, "Linear" )
if progress > 1 then
current.startTick = getTickCount()
current.state = 1
end
elseif current.state == 1 then
alpha = 255
if getTickCount() - current.startTick >= current.time then
current.startTick = getTickCount()
current.state = 2
end
elseif current.state == 2 then
local progress = (getTickCount() - current.startTick) / 500
alpha = interpolateBetween( 255, 0, 0,
0, 0, 0,
progress, "Linear" )
if progress > 1 then
table.remove(notify.noLimit, 1)
if #notify.noLimit == 0 then
removeEventHandler( "onClientRender", root, notify.noLimitRender)
end
end
end
local Y = getElementData(localPlayer, "radar:gtaV") and screenY - 340 * scaleX or screenY - 250
dxDrawRectangle( 28 * scaleX, Y - current.height, 421.7 * scaleX, current.height + 10 * scaleY, tocolor(0, 0, 0, 180, alpha) )
dxDrawText( current.message, 35 * scaleX, Y - current.height + 5 * scaleY, 0, Y + 5 * scaleY, tocolor(211, 211, 211, alpha), 1.0, notify.font, "left", "center", false, false, false, true )
end
end
|
function create_refinery(args)
local refinery = table.deepcopy(data.raw["assembling-machine"]["oil-refinery-mk3"])
refinery.name = args.name
refinery.icon = "__built-in-beacons-fe-plus__/graphics/icons/" .. args.name .. ".png"
refinery.icon_size = 64
refinery.icon_mipmaps = nil
refinery.minable.result = args.name
refinery.module_specification.module_slots = 8
refinery.crafting_speed = args.crafting_speed
refinery.energy_usage = args.energy_usage
refinery.energy_source = { type = "electric", usage_priority = "secondary-input", emissions_per_minute = args.emissions_per_minute, drain = "9.8MW" }
refinery.allowed_effects = {"productivity","pollution"}
for _, direction in pairs({"north", "east", "south", "west"}) do
refinery.animation[direction].layers[1].filename = "__built-in-beacons-fe-plus__/graphics/entity/beaconed-fe-oil-refinery/" .. args.name .. "/oil-refinery.png"
refinery.animation[direction].layers[1].hr_version.filename = "__built-in-beacons-fe-plus__/graphics/entity/beaconed-fe-oil-refinery/" .. args.name .. "/hr-oil-refinery.png"
end
local result,ingredients
if settings.startup["upgradeable-recipes"].value then
ingredients = args.upgradeable_ingredients
result = args.upgradeable_result
else
ingredients = args.ingredients
result = args.result
end
data:extend({
{
type = "item",
name = args.name,
icon = refinery.icon,
icon_size = refinery.icon_size,
subgroup = "fb-fluids",
order = args.item_order,
place_result = args.name,
stack_size = 50
},
{
type = "recipe",
name = args.name,
icon = refinery.icon,
icon_size = refinery.icon_size,
subgroup = "fb-fluids",
order = args.item_order,
enabled = false,
ingredients = ingredients,
results = result
}
})
data:extend({refinery})
end
|
function LGP.GenerateHash()
return ""
end
function LGP:SendEntityCode(Player)
local UploadSpeed = LGP.UploadSpeed:GetInt()
local Script = util.Compress(self.Script)
local Parts = {}
for i = 1, math.ceil(#Script / UploadSpeed) do
table.insert(Parts, Script:sub(i * UploadSpeed, (i + 1) * UploadSpeed - 1))
end
local Hash = LGP.GenerateHash()
net.Start("lgp_start_sending")
net.WriteEntity(self)
net.WriteString(Hash)
net.Send(Player)
local Delay = 0
for i, Part in pairs(Parts) do
timer.Simple(Delay,
function ()
if Player:IsValid() then
net.Start("lgp_receive_script")
net.WriteEntity(self)
net.WriteString(Hash)
net.WriteInt(i)
net.WriteInt(#Parts)
net.WriteString(Part)
net.Send(Player)
end
end
)
Delay = Delay + 0.2
end
return Delay
end
function LGP:SendEntityCodeBroadcast(Entity)
local UploadSpeed = LGP.UploadSpeed:GetInt()
local Script = util.Compress(self.Script)
local Parts = {}
for i = 1, math.ceil(#Script / UploadSpeed) do
table.insert(Parts, Script:sub(i * UploadSpeed, (i + 1) * UploadSpeed - 1))
end
local Hash = LGP.GenerateHash()
net.Start("lgp_start_sending")
net.WriteEntity(self)
net.WriteString(Hash)
net.Broadcast()
local Delay = 0
for i, Part in pairs(Parts) do
timer.Simple(Delay,
function ()
if Player:IsValid() then
net.Start("lgp_receive_script")
net.WriteEntity(self)
net.WriteString(Hash)
net.WriteInt(i)
net.WriteInt(#Parts)
net.WriteString(Part)
net.Broadcast()
end
end
)
Delay = Delay + 0.2
end
return Delay
end |
--! file: Base class for a character in a game.
Character = Object:extend()
function Character:new(x, y, speed, imageDir)
self.x = x
self.y = y
self.speed = speed
self.sprite = love.graphics.newImage(imageDir)
self.width = self.sprite:getWidth()
self.height = self.sprite:getHeight()
end
function Character:update(dt)
local window_width = love.graphics.getWidth()
if 0 > self.x then
self.x = 0
elseif window_width < (self.x + self.width) then
self.x = window_width - self.width
end
end
function Character:draw()
love.graphics.draw(self.sprite, self.x, self.y)
end
|
local zmq = require "lzmq"
local ztimer = require "lzmq.timer"
IS_WINDOWS = package.config:sub(1,1) == "\\"
zassert = zmq.assert
function sleep(sec)
ztimer.sleep(sec * 1000)
end
function s_sleep(msec)
ztimer.sleep(msec)
end
function printf(fmt, ...)
return io.write((string.format(fmt, ...)))
end
function fprintf(file, fmt, ...)
return file:write((string.format(fmt, ...)))
end
function sprintf(fmt, ...)
return (string.format(fmt, ...))
end
function randof(n)
if type(n) == 'number' then
return math.random(1, n) - 1
end
return n[math.random(1, #n)]
end
function getchar()
io.read(1)
end
function s_dump_str(str)
-- Dump the message as text or binary
local function is_text(data)
for i=1, #data do
local c = data:byte(i)
if (c < 32 or c > 127) then
return false
end
end
return true
end
local result = sprintf("[%03d] ", #str)
if is_text(str) then
result = result .. str
else
for i=1, #str do
result = result .. sprintf("%02X", str:byte(i))
end
end
return result
end
function s_dump_msg(msg)
print("----------------------------------------")
-- Process all parts of the message
for _, data in ipairs(msg) do
print(s_dump_str(data))
end
end
function s_dump(socket)
local msg = socket:recv_all()
s_dump_msg(msg)
end
function s_unwrap(msg)
local frame = table.remove(msg, 1)
if msg[1] and (#msg[1]==0) then
table.remove(msg, 1)
end
return frame
end
function s_wrap(msg, frame)
table.insert(msg, 1, "")
table.insert(msg, 1, frame)
return msg
end
|
local uv = require("uv")
local SOCK = "/tmp/echo.sock"
local client = uv.new_pipe(false)
client:connect(SOCK, function (err)
assert(not err, err)
client:read_start(function (err, chunk)
assert(not err, err)
if chunk then
print(chunk)
else
client:close()
end
end)
client:write("Hello ")
client:write("world!")
end)
print("CTRL-C to break")
uv.run("default")
uv.loop_close()
|
#!/usr/bin/lua
local fs = require "nixio.fs"
local function scrape()
for metrics in fs.glob("/var/prometheus/*.prom") do
output(get_contents(metrics), '\n')
end
end
return { scrape = scrape }
|
utils = require('utils')
function with_temp_ref(...)
local args = {...}
local dtype = 'int32_t'
if type(args[1]) == 'string' then
dtype = table.remove(args, 1)
end
local count = 1
if type(args[1]) == 'number' then
count = table.remove(args, 1)
end
local func = table.remove(args, 1)
assert(type(func) == 'function')
dfhack.with_temp_object(df.new(dtype, count), func, table.unpack(args))
end
function test.zero_initialize()
with_temp_ref(function(x)
expect.eq(x.value, 0)
end)
end
function test.zero_initialize_array()
with_temp_ref(2, function(x)
expect.eq(x:_displace(1).value, 0)
end)
end
function test.displace_zero()
with_temp_ref(function(x)
expect.eq(x, x:_displace(0))
end)
end
function test.displace_nonzero()
with_temp_ref(2, function(x)
expect.ne(x, x:_displace(1))
expect.eq(utils.addressof(x) + x:sizeof(), utils.addressof(x:_displace(1)))
end)
end
function test.displace_negative()
with_temp_ref(2, function(x)
expect.true_(x:_displace(1):_displace(-1).value)
end)
end
function test.index_read()
with_temp_ref(function(x)
expect.eq(x.value, x[0])
end)
end
function test.index_write()
with_temp_ref(function(x)
x[0] = 1
expect.eq(x.value, 1)
expect.eq(x[0], 1)
x.value = 2
expect.eq(x.value, 2)
expect.eq(x[0], 2)
end)
end
function test.index_write_multi()
local len = 3
with_temp_ref(len, function(x)
for i = 0, len - 1 do
x[i] = i * i
end
for i = 0, len - 1 do
expect.eq(x[i], i * i)
end
end)
end
function test.index_read_negative()
with_temp_ref(function(x)
expect.error_match(function()
expect.true_(x:_displace(1)[-1])
end, 'negative index')
end)
end
function test.index_write_negative()
with_temp_ref(function(x)
expect.error_match(function()
x:_displace(1)[-1] = 7
end, 'negative index')
end)
end
|
local BenchmarkBpClass = Inherit(CppObjectBase)
function BenchmarkBpClass:Start()
collectgarbage("stop")
self.m_TestResult = {}
-- GlueFunc
a_("************Start UObject Type Bench****************")
self:TestBPReflection()
self:TestGlueFunction()
-- do return end
a_("************Start Struct Type Bench****************")
local StructTypeIns = TestGlueEx.New()
self.TestGlueFunction(StructTypeIns)
a_("************Start BpStruct Type Bench****************")
local BpStructTypeIns = FTestGlueExBp.New()
BenchmarkBpClass.TestReadWrite(BpStructTypeIns, "ReadWriteInt", 1)
BenchmarkBpClass.TestReadWrite(BpStructTypeIns, "ReadWriteVector", FVector.New(1,2,3))
self.TestGlueFunction(BpStructTypeIns)
a_("************Start common struct Bench****************")
self:CommonStructBench(TestGlueEx)
self:TestDynamicMultiCast()
collectgarbage("restart")
end
local CallCountForBench = 10000
local NsTimeFactor = 1000000000/CallCountForBench
local function Clock()
return FPlatformTime.Seconds() * NsTimeFactor
end
function BenchmarkBpClass:TestBPReflection( )
self:TestFunc("TestCallFunc_0param")
self:TestFunc("TestCallFunc_1param_int", 1)
self:TestFunc("TestCallFunc_1param_int_ref", 1)
self:TestFunc("TestCallFunc_1param_FVector", FVector.New(1,2,3))
self:TestFunc("TestCallFunc_1param_FVector_ref", FVector.New(1,2,3))
self:TestFunc("TestCallFunc_3param", i, self, FVector.New(1,2,3))
self:TestFunc("TestCallFunc_Ret_int")
self:TestFunc("TestCallFunc_Ret_FVector" )
self:TestReadWrite("ReadWriteInt", 1)
self:TestReadWrite("ReadWriteVector", FVector.New(1,2,3))
end
function BenchmarkBpClass:TestGlueFunction( )
BenchmarkBpClass.TestFunc(self, "Glue_TestCallFunc_0param")
BenchmarkBpClass.TestFunc(self, "Glue_TestCallFunc_1param_int", 1)
BenchmarkBpClass.TestFunc(self, "Glue_TestCallFunc_1param_int_ref", 1)
BenchmarkBpClass.TestFunc(self, "Glue_TestCallFunc_1param_FVector", FVector.New(1,2,3))
BenchmarkBpClass.TestFunc(self, "Glue_TestCallFunc_1param_FVector_ref", FVector.New(1,2,3))
BenchmarkBpClass.TestFunc(self, "Glue_TestCallFunc_3param", i, self, FVector.New(1,2,3))
BenchmarkBpClass.TestFunc(self, "Glue_TestCallFunc_Ret_int")
BenchmarkBpClass.TestFunc(self, "Glue_TestCallFunc_Ret_FVector" )
BenchmarkBpClass.TestReadWrite(self, "Glue_ReadWriteInt", 1)
BenchmarkBpClass.TestReadWrite(self, "Glue_ReadWriteVector", FVector.New(1,2,3))
local cppins = self._cppinstance_ or self
local meta = getmetatable(cppins)
a_("static self part1 ")
BenchmarkBpClass.TestReadWrite(self, "Glue_StaticReadWriteInt", 1)
BenchmarkBpClass.TestReadWrite(self, "Glue_StaticReadWriteVector", FVector.New(1,2,3))
a_("static meta part2 ")
BenchmarkBpClass.TestReadWrite(meta, "Glue_StaticReadWriteInt", 1, true)
BenchmarkBpClass.TestReadWrite(meta, "Glue_StaticReadWriteVector", FVector.New(1,2,3), true)
a_("****static end****")
end
function BenchmarkBpClass:TestDynamicMultiCast()
local CallCount = CallCountForBench
local function f()
end
self.BenchDelegate_2Param:Add(InsCallBack(f, self))
local t = Clock()
self:Call_BenchDelegate_2Param(CallCount)
local t1 = Clock()
self.BenchDelegate_2Param:RemoveAll()
self.BenchDelegate_2Param:Add(f)
local t2 = Clock()
self:Call_BenchDelegate_2Param(CallCount)
local t3 = Clock()
a_(string.format("BenchDelegate_2Param %.2f %.2f", t1-t, t3-t2))
end
function BenchmarkBpClass:TestFunc(FuncName, ...)
-- self.m_TestResult[FuncName] = self.m_TestResult[FuncName] or {}
local TestResult = ""
local TestCount = CallCountForBench
local cppins = self._cppinstance_ or self
local TestFunc = self[FuncName]
local t = Clock()
for i = 1, TestCount do
-- local tt = Clock()
self[FuncName](self, ...)
-- add = add + Clock()-tt
end
local t1 = Clock()
for i = 1, TestCount do
cppins[FuncName](cppins, ...)
end
local t2 = Clock()
for i = 1, TestCount do
TestFunc(cppins, ...)
end
local t3 = Clock()
a_(string.format(FuncName..": %.2f %.2f %.2f", t1-t, t2-t1, t3-t2))
end
function BenchmarkBpClass:TestReadWrite(PropertyName, Data, bIsStatic)
bIsStatic = bIsStatic or false
local TestCount = CallCountForBench
local cppins = self._cppinstance_ or self
local readfunc = self["LuaGet_"..PropertyName]
local writefunc = self["LuaSet_"..PropertyName]
local t = Clock()
for i = 1, TestCount do
local x = self[PropertyName]
end
local t1 = Clock()
for i = 1, TestCount do
local x = cppins[PropertyName]
end
local t2 = Clock()
if readfunc then
if not bIsStatic then
for i = 1, TestCount do
local x = readfunc(self)
end
else
-- for i = 1, TestCount do
-- local x = readfunc(nil)
-- end
end
end
local t3 = Clock()
a_(string.format(PropertyName.." Read: %.2f %.2f %.2f", t1-t, t2-t1, t3-t2))
local t4 = Clock()
for i = 1, TestCount do
self[PropertyName] = Data
end
local t5 = Clock()
for i = 1, TestCount do
cppins[PropertyName] = Data
end
local t6 = Clock()
if writefunc then
if not bIsStatic then
for i = 1, TestCount do
writefunc(self, nil, Data)
end
else
-- for i = 1, TestCount do
-- writefunc(nil, nil, Data)
-- end
end
end
local t7 = Clock()
a_(string.format(PropertyName.." Write: %.2f %.2f %.2f", t5-t4, t6-t5, t7-t6))
end
function BenchmarkBpClass:CommonStructBench(TheClass)
local TestCount = CallCountForBench
local t = Clock()
for i = 1, TestCount do
TheClass.New()
end
local t1 = Clock()
for i = 1, TestCount do
TheClass.Temp()
end
local t2 = Clock()
a_(string.format(" New And Temp: %.2f %.2f ", t1-t, t2-t1))
end
return BenchmarkBpClass |
--[[
NPCAttack - Server
by: standardcombo
v0.9.1
Works in conjunction with NPCAIServer. The separation of the two scripts makes it
easier to design diverse kinds of enemies.
--]]
-- Component dependencies
local MODULE = require( script:GetCustomProperty("ModuleManager") )
require ( script:GetCustomProperty("DestructibleManager") )
function DESTRUCTIBLE_MANAGER() return MODULE.Get("standardcombo.NPCKit.DestructibleManager") end
function COMBAT() return MODULE.Get("standardcombo.Combat.Wrap") end
function PLAYER_HOMING_TARGETS() return MODULE.Get("standardcombo.Combat.PlayerHomingTargets") end
function CROSS_CONTEXT_CALLER() return MODULE.Get("standardcombo.Utils.CrossContextCaller") end
function LOOT_DROP_FACTORY() return MODULE.Get_Optional("standardcombo.NPCKit.LootDropFactory") end
local ROOT = script:GetCustomProperty("Root"):WaitForObject()
local DAMAGE_TO_PLAYERS = script:GetCustomProperty("DamageToPlayers") or 1
local DAMAGE_TO_NPCS = script:GetCustomProperty("DamageToNPCs") or 1
local PROJECTILE_BODY = script:GetCustomProperty("ProjectileBody")
local MUZZLE_FLASH_VFX = script:GetCustomProperty("MuzzleFlash")
local IMPACT_SURFACE_VFX = script:GetCustomProperty("ImpactSurface")
local IMPACT_CHARACTER_VFX = script:GetCustomProperty("ImpactCharacter")
local PROJECTILE_LIFESPAN = script:GetCustomProperty("ProjectileLifeSpan") or 10
local PROJECTILE_SPEED = script:GetCustomProperty("ProjectileSpeed") or 4000
local PROJECTILE_GRAVITY = script:GetCustomProperty("ProjectileGravity") or 1
local IS_PROJECTILE_HOMING = script:GetCustomProperty("ProjectileHoming")
local HOMING_DRAG = script:GetCustomProperty("HomingDrag") or 7
local HOMING_ACCELERATION = script:GetCustomProperty("HomingAcceleration") or 15000
local REWARD_RESOURCE_TYPE = ROOT:GetCustomProperty("RewardResourceType")
local REWARD_RESOURCE_AMOUNT = ROOT:GetCustomProperty("RewardResourceAmount")
local LOOT_ID = ROOT:GetCustomProperty("LootId")
local attackCooldown = 2
local cooldownRemaining = 0
local projectileImpactListener = nil
function GetTeam()
return ROOT:GetCustomProperty("Team")
end
function GetObjectTeam(object)
if object.team ~= nil then
return object.team
end
local templateRoot = object:FindTemplateRoot()
if templateRoot then
return templateRoot:GetCustomProperty("Team")
end
return nil
end
function Attack(target)
if target:IsA("Player") and PLAYER_HOMING_TARGETS() then
target = PLAYER_HOMING_TARGETS().GetTargetForPlayer(target)
end
local startPos = script:GetWorldPosition()
local rotation = script:GetWorldRotation()
local direction = rotation * Vector3.FORWARD
if not IS_PROJECTILE_HOMING then
local v = target:GetWorldPosition() - startPos
direction = v:GetNormalized() + 200 * Vector3.UP * v.size * PROJECTILE_GRAVITY / PROJECTILE_SPEED / PROJECTILE_SPEED
end
CROSS_CONTEXT_CALLER().Call(function()
local projectile = Projectile.Spawn(PROJECTILE_BODY, startPos, direction)
projectile.lifeSpan = PROJECTILE_LIFESPAN
projectile.speed = PROJECTILE_SPEED
projectile.gravityScale = PROJECTILE_GRAVITY
if IS_PROJECTILE_HOMING then
projectile.homingTarget = target
projectile.drag = HOMING_DRAG
projectile.homingAcceleration = HOMING_ACCELERATION
end
projectile.piercesRemaining = 999
projectileImpactListener = projectile.impactEvent:Connect(OnProjectileImpact)
end)
SpawnAsset(MUZZLE_FLASH_VFX, startPos, rotation)
end
function OnProjectileImpact(projectile, other, hitResult)
local myTeam = GetTeam()
local impactTeam = GetObjectTeam(other)
if (impactTeam ~= 0 and myTeam == impactTeam) then return end
CleanupProjectileListener()
local pos = hitResult:GetImpactPosition()
local rot = projectile:GetWorldTransform():GetRotation()
local damageAmount = 0
if other:IsA("Player") then
damageAmount = DAMAGE_TO_PLAYERS
SpawnAsset(IMPACT_CHARACTER_VFX, pos, rot)
else
damageAmount = DAMAGE_TO_NPCS
SpawnAsset(IMPACT_SURFACE_VFX, pos, hitResult:GetTransform():GetRotation())
end
local dmg = Damage.New(damageAmount)
dmg:SetHitResult(hitResult)
dmg.reason = DamageReason.COMBAT
COMBAT().ApplyDamage(other, dmg, script, pos, rot)
projectile:Destroy()
end
function CleanupProjectileListener()
if projectileImpactListener then
projectileImpactListener:Disconnect()
projectileImpactListener = nil
end
end
function SpawnAsset(template, pos, rot)
if not template then return end
CROSS_CONTEXT_CALLER().Call(function()
local spawnedVfx = World.SpawnAsset(template, {position = pos, rotation = rot})
if spawnedVfx and spawnedVfx.lifeSpan <= 0 then
spawnedVfx.lifeSpan = 1.5
end
end)
end
function OnDestroyed(obj)
--print("OnDestroyed()")
CleanupProjectileListener()
end
ROOT.destroyEvent:Connect(OnDestroyed)
-- Damage / destructible
local id = DESTRUCTIBLE_MANAGER().Register(script)
ROOT:SetNetworkedCustomProperty("ObjectId", id)
function ApplyDamage(dmg, source, position, rotation)
local amount = dmg.amount
if (amount ~= 0) then
local prevHealth = GetHealth()
local newHealth = prevHealth - amount
SetHealth(newHealth)
local hitResult = dmg:GetHitResult()
-- Determine best value for impact position
local impactPosition
if not position and hitResult and hitResult:GetImpactPosition() ~= Vector3.ZERO then
impactPosition = hitResult:GetImpactPosition()
elseif position then
impactPosition = position
else
impactPosition = script:GetWorldPosition()
end
-- Determine best value for impact rotation
local impactRotation = Rotation.New()
if hitResult then
impactRotation = hitResult:GetTransform():GetRotation()
elseif rotation then
impactRotation = rotation
end
-- Source position
local sourcePosition = nil
if Object.IsValid(source) then
sourcePosition = source:GetWorldPosition()
end
-- Effects
local spawnedVfx = nil
if (newHealth <= 0 and DESTROY_FX) then
SpawnAsset(DESTROY_FX, impactPosition, impactRotation)
elseif DAMAGE_FX then
SpawnAsset(DAMAGE_FX, impactPosition, impactRotation)
end
-- Events
Events.Broadcast("ObjectDamaged", id, prevHealth, amount, impactPosition, impactRotation, source)
Events.BroadcastToAllPlayers("ObjectDamaged", id, prevHealth, amount, impactPosition, impactRotation)
if (newHealth <= 0) then
Events.Broadcast("ObjectDestroyed", id)
Events.BroadcastToAllPlayers("ObjectDestroyed", id)
DropRewards(source)
end
--print(ROOT.name .. " Health = " .. newHealth)
end
end
function GetHealth()
return ROOT:GetCustomProperty("CurrentHealth")
end
function SetHealth(value)
ROOT:SetNetworkedCustomProperty("CurrentHealth", value)
end
function DropRewards(killer)
-- Give resources
if REWARD_RESOURCE_TYPE
and Object.IsValid(killer)
and killer:IsA("Player") then
killer:AddResource(REWARD_RESOURCE_TYPE, REWARD_RESOURCE_AMOUNT)
end
-- Drop loot
if LOOT_DROP_FACTORY() then
local pos = script:GetWorldPosition()
LOOT_DROP_FACTORY().Drop(LOOT_ID, pos)
end
end
|
---------------------------------------------------------------------------------------------
--ATF version: 2.2
--Created date: 03/Nov/2015
--Author: Ta Thanh Dong
---------------------------------------------------------------------------------------------
Test = require('connecttest')
require('cardinalities')
local events = require('events')
local mobile_session = require('mobile_session')
---------------------------------------------------------------------------------------------
-----------------------------Required Shared Libraries---------------------------------------
---------------------------------------------------------------------------------------------
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonTestCases = require('user_modules/shared_testcases/commonTestCases')
local SDLConfig = require('user_modules/shared_testcases/SmartDeviceLinkConfigurations')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
require('user_modules/AppTypes')
---------------------------------------------------------------------------------------------
-------------------------------------------Preconditions-------------------------------------
---------------------------------------------------------------------------------------------
commonSteps:DeleteLogsFileAndPolicyTable()
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("Preconditions")
--1. Activate application
commonSteps:ActivationApp(_, "Preconditions_ActivationApp_1")
--2. Get appID Value on HMI side
--Get_HMI_AppID("Get_HMI_AppID_1")
--3. Update policy table
local PermissionLinesForBase4 =
[[ "OnExitApplication": {
"hmi_levels": [
"BACKGROUND",
"FULL",
"LIMITED",
"NONE"
]
},
"GetDTCs": {
"hmi_levels": [
"BACKGROUND",
"FULL",
"LIMITED",
"NONE"
]
},
"AddCommand": {
"hmi_levels": [
"BACKGROUND",
"FULL",
"LIMITED",
"NONE"
]
},
"OnCommand": {
"hmi_levels": [
"BACKGROUND",
"FULL",
"LIMITED",
"NONE"
]
},]]
local PermissionLinesForGroup1 = nil
local PermissionLinesForApplication = nil
--TODO: PT is blocked by ATF defect APPLINK-19188
--local PTName = testCasesForPolicyTable:createPolicyTableFile(PermissionLinesForBase4, PermissionLinesForGroup1, PermissionLinesForApplication, {"OnExitApplication", "GetDTCs", "AddCommand", "OnCommand"})
local PTName = testCasesForPolicyTable:createPolicyTableFile_temp(PermissionLinesForBase4, PermissionLinesForGroup1, PermissionLinesForApplication, {"OnExitApplication", "GetDTCs", "AddCommand", "OnCommand"})
--testCasesForPolicyTable:updatePolicy(PTName)
testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt(PTName)
----------------------------------------------------------------------------------------------
--PART1: Common test cases for OnExitApplication requirements:
--SDLAQ-CRS-885: OnExitApplication(USER_EXIT) moves the app to NONE
--SDLAQ-CRS-888: DRIVER_DISTRACTION_VIOLATION
--SDLAQ-CRS-3100: OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION, appID)
----------------------------------------------------------------------------------------------
local function part1()
APIName = "OnExitApplication" -- set API name
Apps = {}
Apps[1] = {}
Apps[1].storagePath = config.pathToSDL .. SDLConfig:GetValue("AppStorageFolder") .. "/"..config.application1.registerAppInterfaceParams.fullAppID.. "_" .. config.deviceMAC.. "/"
Apps[1].appName = config.application1.registerAppInterfaceParams.appName
if commonFunctions:isMediaApp() then
AudioStreamingState = "AUDIBLE"
else
AudioStreamingState = "NOT_AUDIBLE"
end
local function Get_HMI_AppID(TestCaseName)
if TestCaseName == nil then
TestCaseName = Get_HMI_AppID
end
Test[TestCaseName] = function(self)
Apps[1].appID = self.applications[Apps[1].appName]
end
end
local function Open_UIMenu(TestCaseName)
Test[TestCaseName] = function(self)
--hmi side: send OnSystemContext
self.hmiConnection:SendNotification("UI.OnSystemContext", {systemContext = "MENU"})
--mobile side: expected OnHMIStatus
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MENU", hmiLevel = "FULL", audioStreamingState = AudioStreamingState})
end
end
local function Select_OnExitApplication_USER_EXIT(TestCaseName)
Test[TestCaseName] = function(self)
--hmi side: send OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "USER_EXIT", appID = Apps[1].appID})
--mobile side: expected OnHMIStatus (NONE, NOT_AUDIBLE) notification
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MENU", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"})
end
end
local function Select_OnExitApplication_DRIVER_DISTRACTION_VIOLATION(TestCaseName)
Test[TestCaseName] = function(self)
--hmi side: send OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "DRIVER_DISTRACTION_VIOLATION", appID = Apps[1].appID})
--mobile side: expected OnHMIStatus (NONE, NOT_AUDIBLE) notification
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MENU", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"})
end
end
local function Close_UIMenu(TestCaseName)
Test[TestCaseName] = function(self)
--hmi side: send OnSystemContext
self.hmiConnection:SendNotification("UI.OnSystemContext", {systemContext = "MAIN", appID = Apps[1].appID})
--mobile side: expected OnHMIStatus
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MAIN", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"})
end
end
local function Open_VRMenu(TestCaseName)
Test[TestCaseName] = function(self)
commonTestCases:DelayedExp(1000)
--hmi side: send OnSystemContext
self.hmiConnection:SendNotification("VR.Started")
self.hmiConnection:SendNotification("UI.OnSystemContext", {systemContext = "VRSESSION"})
--mobile side: SDL does not send OnHMIStatus to NONE hmi level app
EXPECT_NOTIFICATION("OnHMIStatus", {})
:Times(0)
end
end
local function Select_VRSynonym(TestCaseName)
Test[TestCaseName] = function(self)
local cid = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = Apps[1].appID})
self.hmiConnection:SendNotification("UI.OnSystemContext", {systemContext = "MAIN"})
EXPECT_HMIRESPONSE(cid)
--mobile side: expected OnHMIStatus
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = "NOT_AUDIBLE"})
end
end
local function Close_VRMenu(TestCaseName)
Test[TestCaseName] = function(self)
self.hmiConnection:SendNotification("VR.Stopped")
--mobile side: expected OnHMIStatus
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = AudioStreamingState})
end
end
local function OnExitApplication_reason_UNAUTHORIZED_TRANSPORT_REGISTRATION()
function Test:Precondition_AddCommand_1()
--mobile side: sending AddCommand request
local cid = self.mobileSession:SendRPC("AddCommand",
{
cmdID = 1,
menuParams =
{
menuName ="Command1_onMenu1"
},
vrCommands =
{
"Command1_OnVR",
"Command2_OnVR"
}
})
--hmi side: expect UI.AddCommand request
EXPECT_HMICALL("UI.AddCommand",
{
cmdID = 1,
menuParams =
{
menuName ="Command1_onMenu1"
}
})
:Do(function(_,data)
--hmi side: sending UI.AddCommand response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--hmi side: expect VR.AddCommand request
EXPECT_HMICALL("VR.AddCommand",
{
cmdID = 1,
type = "Command",
vrCommands =
{
"Command1_OnVR",
"Command2_OnVR"
}
})
:Do(function(_,data)
--hmi side: sending VR.AddCommand response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--mobile side: expect AddCommand response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
--mobile side: expect OnHashChange notification
EXPECT_NOTIFICATION("OnHashChange")
end
function Test:OnExitApplication_reason_UNAUTHORIZED_TRANSPORT_REGISTRATION()
commonTestCases:DelayedExp(1000)
--mobile side: sending the request
local cid = self.mobileSession:SendRPC("GetDTCs", {ecuName = 2, dtcMask = 3})
--hmi side: expect VehicleInfo.GetDTCs request
EXPECT_HMICALL("VehicleInfo.GetDTCs", {ecuName = 2, dtcMask = 3})
:Do(function(_,data)
--hmi side: send OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION", appID = Apps[1].appID})
local ID = data.id
function to_run()
--hmi side: sending response
self.hmiConnection:SendResponse(ID, data.method, "SUCCESS", {ecuHeader = 2, dtc = {"line 0","line 1","line 2"}})
end
RUN_AFTER(to_run, 2000)
end)
--mobile side: expected OnAppInterfaceUnregistered notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
--hmi side: expected BasicCommunication.OnAppUnregistered
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", {appID = Apps[1].appID, unexpectedDisconnect = false})
--mobile side: expect the response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", ecuHeader = 2, dtc = {"line 0","line 1","line 2"}})
:Times(0)
end
function Test:OnCommand_IsIgnoredAfterSDLReceved_OnExitApplication_reason_UNAUTHORIZED_TRANSPORT_REGISTRATION()
commonTestCases:DelayedExp(1000)
--hmi side: sending UI.OnCommand notification after SDL receved OnExitApplication with reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION"
self.hmiConnection:SendNotification("UI.OnCommand", {cmdID = 1, appID = Apps[1].appID})
--mobile side: OnCommand notification is ignored
EXPECT_NOTIFICATION("OnCommand", {cmdID = cmdIDValue, triggerSource= "MENU"})
:Times(0)
end
end
-----------------------------------------------------------------------------------------------
-------------------------------------------TEST BLOCK I----------------------------------------
--------------------------------Check normal cases of Mobile request---------------------------
-----------------------------------------------------------------------------------------------
--Not Applicable
----------------------------------------------------------------------------------------------
-----------------------------------------TEST BLOCK II----------------------------------------
-----------------------------Check special cases of Mobile request----------------------------
----------------------------------------------------------------------------------------------
--Not Applicable
-----------------------------------------------------------------------------------------------
-------------------------------------------TEST BLOCK III--------------------------------------
----------------------------------Check normal cases of HMI notification-----------------------
-----------------------------------------------------------------------------------------------
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("Test suite: Check normal cases of HMI notification")
local function TCs_verify_normal_cases()
--TCs_verify_normal_cases.1: verify OnExitApplication with reason = USER_EXIT
-----------------------------------------------------------------------------------------------
--Requirement id in JAMA or JIRA:
--SDLAQ-CRS-885: OnExitApplication(USER_EXIT) moves the app to NONE
--Verification criteria:
--1. HMI->SDL: BasicCommunication.OnExitApplication(USER_EXIT, appID)
--2. SDL -> app: OnHMIStatus (NONE, NOT_AUDIBLE)
Open_UIMenu("Open_UIMenu_1")
Select_OnExitApplication_USER_EXIT("Select_OnExitApplication_USER_EXIT_1")
Close_UIMenu("Close_UIMenu_1")
--PostCondition
commonSteps:ActivationApp(_, "ActivationApp_2")
--TCs_verify_normal_cases.2: verify OnExitApplication with reason = DRIVER_DISTRACTION_VIOLATION
-----------------------------------------------------------------------------------------------
--Requirement id in JAMA or JIRA:
--SDLAQ-CRS-888: DRIVER_DISTRACTION_VIOLATION
--Verification criteria:
--1. HMI->SDL: BasicCommunication.OnExitApplication(DRIVER_DISTRACTION_VIOLATION, appID)
--2. SDL -> app: OnHMIStatus (NONE, NOT_AUDIBLE)
Open_UIMenu("Open_UIMenu_2")
Select_OnExitApplication_DRIVER_DISTRACTION_VIOLATION("Select_OnExitApplication_DRIVER_DISTRACTION_VIOLATION_1")
Close_UIMenu("Close_UIMenu_2")
--PostCondition
commonSteps:ActivationApp(_, "ActivationApp_3")
--TCs_verify_normal_cases.3: verify OnExitApplication with reason = UNAUTHORIZED_TRANSPORT_REGISTRATION
-----------------------------------------------------------------------------------------------
--Requirement id in JAMA or JIRA:
--SDLAQ-CRS-3100: OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION, appID)
--Verification criteria:
--1. In case SDL receives OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION, appID_1) notification from HMI SDL must:
--1.1. - unregister application with appID_1 via OnAppInterfaceUnregistered(APP_UNATHORIZED) notification
--1.2.- clear its internal information about app's non-responded RPCs,
--1.3. - ignore all responses and notifications from HMI associated with appID_1
--HMI expected behavior:
--1. In case device connected over BT and navigation application with appID_1 is running on this device HMI is expected:
--1.1. - to ignore all requests from SDL associated with this appID_1
--1.2. - to reject registration for this navigation application with appID_1 via OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION, appID_1) notification
OnExitApplication_reason_UNAUTHORIZED_TRANSPORT_REGISTRATION()
--PostCondition
commonSteps:RegisterAppInterface("RegisterAppInterface1")
commonSteps:RegisterAppInterface("RegisterAppInterface1")
--1. Activate application
commonSteps:ActivationApp(_, "ActivationApp_4")
--2. Get appID Value on HMI side
Get_HMI_AppID("Get_HMI_AppID_2")
--TCs_verify_normal_cases.4: Verify invalid cases of reason parameter
-----------------------------------------------------------------------------------------------
--1. IsMissed
--2. IsEmtpy
--3. NonExist
--4. WrongDataType
local InvalidValues = { {value = nil, name = "IsMissed"},
{value = "", name = "IsEmtpy"},
{value = "ANY", name = "NonExist"},
{value = 123, name = "WrongDataType"}}
for i = 1, #InvalidValues do
Test["OnExitApplication_reason_" .. InvalidValues[i].name .."_IsIgnored"] = function(self)
commonTestCases:DelayedExp(1000)
--hmi side: send OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = InvalidValues[i].value, appID = Apps[1].appID})
--mobile side: expected OnHMIStatus (NONE, NOT_AUDIBLE) notification
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MAIN", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"})
:Times(0)
--mobile side: expected OnAppInterfaceUnregistered notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
:Times(0)
--hmi side: expected BasicCommunication.OnAppUnregistered
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", {appID = Apps[1].appID, unexpectedDisconnect = false})
:Times(0)
end
end
--TCs_verify_normal_cases.5: Verify invalid cases of appID parameter
-----------------------------------------------------------------------------------------------
--1. IsMissed
--2. IsEmtpy
--3. NonExist
--4. WrongDataType
local InvalidValues = { {value = nil, name = "IsMissed"},
{value = "", name = "IsEmtpy"},
{value = "ANY", name = "NonExist"},
{value = 123, name = "WrongDataType"}}
local reasons = { {value = "USER_EXIT", name = "USER_EXIT"},
{value = "DRIVER_DISTRACTION_VIOLATION", name = "DRIVER_DISTRACTION_VIOLATION"},
{value = "UNAUTHORIZED_TRANSPORT_REGISTRATION", name = "UNAUTHORIZED_TRANSPORT_REGISTRATION"}}
for i = 1, #reasons do
for j = 1, #InvalidValues do
Test["OnExitApplication_reason_"..reasons[i].name .."_appID_" .. InvalidValues[j].name .."_IsIgnored"] = function(self)
commonTestCases:DelayedExp(1000)
--hmi side: send OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = reasons[i].value, appID = InvalidValues[j].value})
--mobile side: expected OnHMIStatus (NONE, NOT_AUDIBLE) notification
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MAIN", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"})
:Times(0)
--mobile side: expected OnAppInterfaceUnregistered notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
:Times(0)
--hmi side: expected BasicCommunication.OnAppUnregistered
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", {appID = Apps[1].appID, unexpectedDisconnect = false})
:Times(0)
end
end
end
end
TCs_verify_normal_cases()
----------------------------------------------------------------------------------------------
-----------------------------------------TEST BLOCK IV----------------------------------------
----------------------------Check special cases of HMI notification---------------------------
----------------------------------------------------------------------------------------------
--Requirement id in JAMA or JIRA:
--APPLINK-14765: SDL must cut off the fake parameters from requests, responses and notifications received from HMI
-----------------------------------------------------------------------------------------------
--List of test cases for special cases of HMI notification:
--1. InvalidJsonSyntax
--2. InvalidStructure
--3. FakeParams
--4. FakeParameterIsFromAnotherAPI
--5. MissedmandatoryParameters
--6. MissedAllPArameters
--7. SeveralNotifications with the same values
--8. SeveralNotifications with different values
----------------------------------------------------------------------------------------------
local function SpecialResponseChecks()
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("Test suite: Check special cases of HMI notification")
--SpecialResponseChecks.1. Verify OnExitApplication with invalid Json syntax
----------------------------------------------------------------------------------------------
function Test:OnExitApplication_InvalidJsonSyntax()
commonTestCases:DelayedExp(1000)
--hmi side: send OnExitApplication
--self.hmiConnection:Send('{"jsonrpc":"2.0","method":"BasicCommunication.OnExitApplication","params":{"reason":"USER_EXIT","appID":'..Apps[1].appID..'}}')
self.hmiConnection:Send('{"jsonrpc";"2.0","method":"BasicCommunication.OnExitApplication","params":{"reason":"USER_EXIT","appID":'..Apps[1].appID..'}}')
EXPECT_NOTIFICATION("OnHMIStatus")
:Times(0)
end
--SpecialResponseChecks.2. Verify OnExitApplication with invalid structure
----------------------------------------------------------------------------------------------
function Test:OnExitApplication_InvalidStructure()
commonTestCases:DelayedExp(1000)
--hmi side: send OnExitApplication
--method is moved into params parameter
--self.hmiConnection:Send('{"jsonrpc":"2.0","method":"BasicCommunication.OnExitApplication","params":{"reason":"USER_EXIT","appID":'..Apps[1].appID..'}}')
self.hmiConnection:Send('{"jsonrpc";"2.0","params":{"method":"BasicCommunication.OnExitApplication","reason":"USER_EXIT","appID":'..Apps[1].appID..'}}')
EXPECT_NOTIFICATION("OnExitApplication")
:Times(0)
end
--SpecialResponseChecks.3. Verify OnExitApplication with FakeParams
----------------------------------------------------------------------------------------------
function Test:OnExitApplication_FakeParams()
--hmi side: send OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "USER_EXIT", appID = Apps[1].appID, fake = 123})
--mobile side: expected OnHMIStatus (NONE, NOT_AUDIBLE) notification
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MAIN", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"})
:ValidIf(function(_,data)
if data.payload.fake then
print(" SDL forwards fake parameter to mobile ")
return false
else
return true
end
end)
end
--PostCondition
commonSteps:ActivationApp(_, "ActivationApp_5")
--SpecialResponseChecks.4. Verify OnExitApplication with FakeParameterIsFromAnotherAPI
function Test:OnExitApplication_FakeParameterIsFromAnotherAPI()
--hmi side: send OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "USER_EXIT", appID = Apps[1].appID, sliderPosition = 123})
--mobile side: expected OnHMIStatus (NONE, NOT_AUDIBLE) notification
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MAIN", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"})
:ValidIf(function(_,data)
if data.payload.sliderPosition then
print(" SDL forwards fake parameter to mobile ")
return false
else
return true
end
end)
end
--PostCondition
commonSteps:ActivationApp(_, "ActivationApp_6")
--SpecialResponseChecks.5. Verify OnExitApplication misses mandatory parameter
----------------------------------------------------------------------------------------------
--It is covered when verifying each parameter
--SpecialResponseChecks.6. Verify OnExitApplication MissedAllPArameters
----------------------------------------------------------------------------------------------
function Test:OnExitApplication_AllParameters_AreMissed()
commonTestCases:DelayedExp(1000)
--hmi side: send OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication",{})
--mobile side: expected OnHMIStatus (NONE, NOT_AUDIBLE) notification
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MAIN", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"})
:Times(0)
--mobile side: expected OnAppInterfaceUnregistered notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
:Times(0)
--hmi side: expected BasicCommunication.OnAppUnregistered
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", {appID = Apps[1].appID, unexpectedDisconnect = false})
:Times(0)
end
--SpecialResponseChecks.7. Verify OnExitApplication with SeveralNotifications_WithTheSameValues
----------------------------------------------------------------------------------------------
function Test:OnExitApplication_SeveralNotifications_WithTheSameValues()
--hmi side: send OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "USER_EXIT", appID = Apps[1].appID})
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "USER_EXIT", appID = Apps[1].appID})
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "USER_EXIT", appID = Apps[1].appID})
--mobile side: expected OnHMIStatus (NONE, NOT_AUDIBLE) notification
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MAIN", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"})
:Times(1)
end
--PostCondition
commonSteps:ActivationApp(_, "ActivationApp_7")
--SpecialResponseChecks.8. Verify OnExitApplication with SeveralNotifications_WithDifferentValues
----------------------------------------------------------------------------------------------
function Test:OnExitApplication_SeveralNotifications_WithDifferentValues()
--hmi side: send OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "USER_EXIT", appID = Apps[1].appID})
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "DRIVER_DISTRACTION_VIOLATION", appID = Apps[1].appID})
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION", appID = Apps[1].appID})
--mobile side: expected OnHMIStatus (NONE, NOT_AUDIBLE) notification
EXPECT_NOTIFICATION("OnHMIStatus", {systemContext = "MAIN", hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE"})
--mobile side: expected OnAppInterfaceUnregistered notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
--hmi side: expected BasicCommunication.OnAppUnregistered
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", {appID = Apps[1].appID, unexpectedDisconnect = false})
end
--PostCondition
commonSteps:RegisterAppInterface("RegisterAppInterface2")
--1. Activate application
commonSteps:ActivationApp(_, "ActivationApp_8")
--2. Get appID Value on HMI side
Get_HMI_AppID("Get_HMI_AppID_3")
end
SpecialResponseChecks()
-----------------------------------------------------------------------------------------------
-------------------------------------------TEST BLOCK V----------------------------------------
-------------------------------------Checks All Result Codes-----------------------------------
-----------------------------------------------------------------------------------------------
--Description: Check all resultCodes
--Not Applicable
----------------------------------------------------------------------------------------------
-----------------------------------------TEST BLOCK VI----------------------------------------
-------------------------Sequence with emulating of user's action(s)--------------------------
----------------------------------------------------------------------------------------------
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("Test suite: Sequence with emulating of user's action(s)")
local function SequenceCheck()
--Requirement id in JAMA or JIRA: SDLAQ-TC-312: TC_OnExitApplication_01
--Verification criteria:
-- Checking changing of HMI level to NONE and audioStreaming State to NOT_AUDIBLE after Exit App from In-App menu and possibility to activate this app again. Checked two reason of exit application ("DRIVER_DISTRACTION_VIOLATION" and "USER_EXIT").
--It is covered by TC_OnExitApplication_04
----------------------------------------------------------------------------------------------
--Requirement id in JAMA or JIRA: SDLAQ-TC-313: TC_OnExitApplication_02
--Verification criteria:
--1. Checking processing of RPC requests after Exit App from In-App menu (According policy table). Checked two reason of exit application ("DRIVER_DISTRACTION_VIOLATION" and "USER_EXIT").
local function TC_OnExitApplication_02()
Open_UIMenu("Open_UIMenu_02_1")
Select_OnExitApplication_USER_EXIT("Select_OnExitApplication_USER_EXIT_02")
Close_UIMenu("Close_UIMenu_02_1")
local function Alert_inNoneHmiLevel_Disallowed(TestCaseName)
Test[TestCaseName] = function(self)
--mobile side: Alert request
local CorIdAlert = self.mobileSession:SendRPC("Alert",
{
alertText1 = "alertText1",
ttsChunks =
{
{
text = "TTSChunk",
type = "TEXT",
},
},
duration = 3000,
softButtons =
{
{
type = "TEXT",
text = "BUTTON1",
softButtonID = 1171,
systemAction = "DEFAULT_ACTION",
},
},
})
--mobile side: Alert response
EXPECT_RESPONSE(CorIdAlert, { success = false, resultCode = "DISALLOWED" })
end
end
Alert_inNoneHmiLevel_Disallowed("Alert_inNoneHmiLevel_Disallowed_02_1")
--PostCondition
commonSteps:ActivationApp(_, "ActivationApp_9")
----------------------------------------------------------------------------------------------
Open_UIMenu("Open_UIMenu_02_2")
Select_OnExitApplication_DRIVER_DISTRACTION_VIOLATION("Select_OnExitApplication_DRIVER_DISTRACTION_VIOLATION_02")
Close_UIMenu("Close_UIMenu_02_2")
Alert_inNoneHmiLevel_Disallowed("Alert_inNoneHmiLevel_Disallowed_02_2")
--PostCondition
commonSteps:ActivationApp(_, "ActivationApp_10")
end
TC_OnExitApplication_02()
----------------------------------------------------------------------------------------------
--Requirement id in JAMA or JIRA: SDLAQ-TC-314: TC_OnExitApplication_03
--Verification criteria:
--1. Checking possibility activating app after Exit App from In-App menu via VR synonym of application. Checked two reason of exit application ("DRIVER_DISTRACTION_VIOLATION" and "USER_EXIT").
local function TC_OnExitApplication_03()
--Exit application
Open_UIMenu("Open_UIMenu_03_1")
Select_OnExitApplication_USER_EXIT("Select_OnExitApplication_USER_EXIT_03")
Close_UIMenu("Close_UIMenu_03_1")
--Activate application via VR menu
Open_VRMenu("Open_UIMenu_03_1")
Select_VRSynonym("Select_VRSynonym_To_ActivateApp_03_1")
Close_VRMenu("Close_VRMenu_1")
--Exit application
Open_UIMenu("Open_UIMenu_03_2")
Select_OnExitApplication_DRIVER_DISTRACTION_VIOLATION("Select_OnExitApplication_DRIVER_DISTRACTION_VIOLATION_03")
Close_UIMenu("Close_UIMenu_03_2")
--Activate application via VR menu
Open_VRMenu("Open_UIMenu_03_3")
Select_VRSynonym("Select_VRSynonym_To_ActivateApp_03_2")
Close_VRMenu("Close_VRMenu_3")
end
TC_OnExitApplication_03()
----------------------------------------------------------------------------------------------
--Requirement id in JAMA or JIRA: SDLAQ-TC-347: TC_OnExitApplication_04
--Verification criteria:
--1. Check that core handle OnExitApplication notification from HMI. Checked two reason of exit application ("DRIVER_DISTRACTION_VIOLATION" and "USER_EXIT").
local function TC_OnExitApplication_04()
--Exit application
Open_UIMenu("Open_UIMenu_04_1")
Select_OnExitApplication_USER_EXIT("Select_OnExitApplication_USER_EXIT_04")
Close_UIMenu("Close_UIMenu_04_1")
commonSteps:ActivationApp(_, "ActivationApp_11")
--Exit application
Open_UIMenu("Open_UIMenu_04_2")
Select_OnExitApplication_DRIVER_DISTRACTION_VIOLATION("Select_OnExitApplication_DRIVER_DISTRACTION_VIOLATION_04")
Close_UIMenu("Close_UIMenu_04_2")
end
TC_OnExitApplication_04()
----------------------------------------------------------------------------------------------
end
SequenceCheck()
----------------------------------------------------------------------------------------------
-----------------------------------------TEST BLOCK VII---------------------------------------
--------------------------------------Different HMIStatus-------------------------------------
----------------------------------------------------------------------------------------------
--Description: Check different HMIStatus
--Not Applicable
end
part1()
----------------------------------------------------------------------------------------------
--PART2: Specific script for requirement:
--SDLAQ-CRS-885: OnExitApplication(USER_EXIT) moves the app to NONE
----------------------------------------------------------------------------------------------
--Note: This part is the same as previous revision (no change).
local function part2()
local application1 =
{
registerAppInterfaceParams =
{
syncMsgVersion =
{
majorVersion = 3,
minorVersion = 0
},
appName = "Test Application",
isMediaApplication = true,
languageDesired = 'EN-US',
hmiDisplayLanguageDesired = 'EN-US',
appHMIType = { "NAVIGATION"},
appID = "8675308",
deviceInfo =
{
os = "Android",
carrier = "Megafon",
firmwareRev = "Name: Linux, Version: 3.4.0-perf",
osVersion = "4.4.2",
maxNumberRFCOMMPorts = 1
}
}
}
local application2 =
{
registerAppInterfaceParams =
{
syncMsgVersion =
{
majorVersion = 3,
minorVersion = 0
},
appName = "Test Application2",
isMediaApplication = true,
languageDesired = 'EN-US',
hmiDisplayLanguageDesired = 'EN-US',
appHMIType = { "NAVIGATION" },
appID = "8675310",
deviceInfo =
{
os = "Android",
carrier = "Megafon",
firmwareRev = "Name: Linux, Version: 3.4.0-perf",
osVersion = "4.4.2",
maxNumberRFCOMMPorts = 1
}
}
}
local function AppRegistration(self, session, params)
local CorIdRegister = session:SendRPC("RegisterAppInterface", params)
--hmi side: expect BasicCommunication.OnAppRegistered request
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered")
:Do(function(_,data)
self.applications[data.params.application.appName] = data.params.application.appID
end)
--mobile side: expect response
session:ExpectResponse(CorIdRegister, { success = true, resultCode = "SUCCESS" })
session:ExpectNotification("OnHMIStatus",{hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"})
end
local function DelayedExp(time)
local event = events.Event()
event.matches = function(self, e) return self == e end
EXPECT_EVENT(event, "Delayed event")
:Timeout(time + 1000)
RUN_AFTER(function()
RAISE_EVENT(event, event)
end, time)
end
local function ActivationApp(self, appID, session)
--hmi side: sending SDL.ActivateApp request
local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = appID})
EXPECT_HMIRESPONSE(RequestId)
:Do(function(_,data)
if
data.result.isSDLAllowed ~= true then
local RequestId = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}})
--hmi side: expect SDL.GetUserFriendlyMessage message response
--TODO: Update after resolving APPLINK-16094 EXPECT_HMIRESPONSE(RequestId,{result = {code = 0, method = "SDL.GetUserFriendlyMessage"}})
EXPECT_HMIRESPONSE(RequestId)
:Do(function(_,data)
--hmi side: send request SDL.OnAllowSDLFunctionality
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}})
--hmi side: expect BasicCommunication.ActivateApp request
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_,data)
--hmi side: sending BasicCommunication.ActivateApp response
self.hmiConnection:SendResponse(data.id,"BasicCommunication.ActivateApp", "SUCCESS", {})
end)
:Times(2)
end)
end
end)
--mobile side: expect notification
session:ExpectNotification("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"})
end
---------------------------------------------------------------------------------------------
--Description: TC checks unregistration of app by SDL after receiving BasicCommunication.OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION).
function Test:Case_OnExitApplicationAfterRegistration()
--hmi side: send request BasicCommunication.OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION", appID = self.applications["Test Application"]})
--mobile side: expect onAppInterfaceUnregistered notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
--hmi side: expect BasicCommunication.OnAppUnregistered
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", { appID = self.applications["Test Application"], unexpectedDisconnect = false})
DelayedExp(2000)
end
---------------------------------------------------------------------------------------------
--Description: TC checks unregistration of app by SDL after receiving BasicCommunication.OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION) during processing API, SDL does not resends messages to mobile side after unregistration.
function Test:Precondition_RegisterAppSession()
AppRegistration(self, self.mobileSession, application1.registerAppInterfaceParams)
end
function Test:Precondition_ActivateApp()
ActivationApp(self, self.applications["Test Application"], self.mobileSession)
end
function Test:Case_OnExitApplicationduringProcessingAPI()
--mobile side: sending Speak request
local cid = self.mobileSession:SendRPC("Speak",
{
ttsChunks =
{
{
text = "Speak text",
type = "TEXT"
}
}
})
--hmi side: TTS.Speak request
EXPECT_HMICALL("TTS.Speak",
{
ttsChunks =
{
{
text = "Speak text",
type = "TEXT"
}
}
})
:Do(function(_,data)
function to_run()
--hmi side: sending TTS.Speak response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end
RUN_AFTER(to_run,2000)
--hmi side: send request BasicCommunication.OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION", appID = self.applications["Test Application"]})
--mobile side: expect onAppInterfaceUnregistered notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
:Do(function(_,data)
EXPECT_NOTIFICATION("OnHMIStatus", {})
:Times(0)
self.hmiConnection:SendNotification("UI.OnSystemContext",{ appID = self.applications["Test Application"], systemContext = "HMI_OBSCURED" })
self.hmiConnection:SendNotification("UI.OnSystemContext",{ appID = self.applications["Test Application"], systemContext = "MENU" })
self.hmiConnection:SendNotification("UI.OnSystemContext",{ appID = self.applications["Test Application"], systemContext = "MAIN" })
DelayedExp(4000)
end)
--hmi side: expect BasicCommunication.OnAppUnregistered
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", { appID = self.applications["Test Application"], unexpectedDisconnect = false})
end)
end
---------------------------------------------------------------------------------------------
--Description: TC checks unregistration of app by SDL after receiving BasicCommunication.OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION) during Streamings.
function Test:Precondition_RegisterAppSession()
AppRegistration(self, self.mobileSession, application1.registerAppInterfaceParams)
end
function Test:Precondition_ActivateApp()
ActivationApp(self, self.applications["Test Application"], self.mobileSession)
end
function Test:Precondition_StartAudioVideoService()
self.mobileSession:StartService(11)
:Do(function()
print ("\27[32m Video service is started \27[0m ")
end)
self.mobileSession:StartService(10)
:Do(function()
print ("\27[32m Audio service is started \27[0m ")
end)
end
function Test:Precondition_StartAudioVidoeStreaming()
self.mobileSession:StartStreaming(11,"files/Wildlife.wmv")
self.mobileSession:StartStreaming(10,"files/Kalimba.mp3")
end
function Test:Case_OnExitApplicationduringProcessingStremings()
--hmi side: send request BasicCommunication.OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION", appID = self.applications["Test Application"]})
--mobile side: expect onAppInterfaceUnregistered notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
:Do(function(_,data)
DelayedExp(4000)
end)
--hmi side: expect BasicCommunication.OnAppUnregistered
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", { appID = self.applications["Test Application"], unexpectedDisconnect = false})
end
function Test:Postcondition_StopStreamings()
local function StopVideo()
print(" \27[32m Stopping video streaming \27[0m ")
self.mobileSession:StopStreaming("files/Wildlife.wmv")
self.mobileSession:Send(
{
frameType = 0,
serviceType = 11,
frameInfo = 4,
sessionId = self.mobileSession.sessionId
})
end
local function StopAudio()
print(" \27[32m Stopping audio streaming \27[0m ")
self.mobileSession:StopStreaming("files/Kalimba.mp3")
self.mobileSession:Send(
{
frameType = 0,
serviceType = 10,
frameInfo = 4,
sessionId = self.mobileSession.sessionId
})
end
RUN_AFTER(StopVideo, 2000)
RUN_AFTER(StopAudio, 2500)
local event = events.Event()
event.matches = function(_, data)
return data.frameType == 0 and
(data.serviceType == 11 or
data.serviceType == 10) and
data.sessionId == self.mobileSession.sessionId and
(data.frameInfo == 5 or -- End Service ACK
data.frameInfo == 6) -- End Service NACK
end
self.mobileSession:ExpectEvent(event, "EndService ACK")
:Timeout(60000)
:Times(2)
:ValidIf(function(s, data)
if data.frameInfo == 5 then return true
else return false, "EndService NACK received" end
end)
end
---------------------------------------------------------------------------------------------
--Description: TC checks unregistration of app by SDL after receiving BasicCommunication.OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION) and response APPLICATION_NOT_REGISTERED to request after OnAppInterfaceUnregistered(APP_UNAUTHORIZED) notification.
function Test:Precondition_RegisterAppSession()
AppRegistration(self, self.mobileSession, application1.registerAppInterfaceParams)
DelayedExp(1000)
end
function Test:Precondition_ActivateApp()
ActivationApp(self, self.applications["Test Application"], self.mobileSession)
end
function Test:Case_RequestsAfterOnExitApplication()
commonTestCases:DelayedExp(2000)
--hmi side: send request BasicCommunication.OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION", appID = self.applications["Test Application"]})
--mobile side: expect onAppInterfaceUnregistered notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
:Do(function(_,data)
--mobile side: sending Speak request
local cid = self.mobileSession:SendRPC("Speak",
{
ttsChunks =
{
{
text = "Speak text",
type = "TEXT"
}
}
})
--hmi side: TTS.Speak request
EXPECT_HMICALL("TTS.Speak")
:Times(0)
--mobile side: expect Speak response
EXPECT_RESPONSE(cid, {resultCode = "APPLICATION_NOT_REGISTERED"})
end)
--hmi side: expect BasicCommunication.OnAppUnregistered
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", { appID = self.applications["Test Application"], unexpectedDisconnect = false})
end
---------------------------------------------------------------------------------------------
--Description: TC checks unregistration of corresponding app by SDL after receiving BasicCommunication.OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION) in case 2 apps are registered.
function Test:Precondition_StartSession2()
-- Connected expectation
self.mobileSession2 = mobile_session.MobileSession(
self,
self.mobileConnection,
application1.registerAppInterfaceParams)
end
function Test:Precondition_RegisterAppFirstSession()
AppRegistration(self, self.mobileSession, application1.registerAppInterfaceParams)
end
function Test:Precondition_RegisterAppSecondSession()
self.mobileSession2:StartService(7)
:Do(function(_,data)
AppRegistration(self, self.mobileSession2, application2.registerAppInterfaceParams)
end)
end
function Test:Precondition_ActivateApp()
ActivationApp(self, self.applications["Test Application2"], self.mobileSession2)
end
function Test:Case_OnExitApplicationForOneApp()
--hmi side: send request BasicCommunication.OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION", appID = self.applications["Test Application"]})
--mobile side: expect onAppInterfaceUnregistered notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
:Do(function(_,data)
--mobile side: sending Speak request in first session
local cidFirstSession = self.mobileSession:SendRPC("Speak",
{
ttsChunks =
{
{
text = "Speak text in first session",
type = "TEXT"
}
}
})
--mobile side: Speak response in first session
EXPECT_RESPONSE(cidFirstSession, {resultCode = "APPLICATION_NOT_REGISTERED", success = false})
--mobile side: sending Speak request in second session
local cidSecondSession = self.mobileSession2:SendRPC("Speak",
{
ttsChunks =
{
{
text = "Speak text in second session",
type = "TEXT"
}
}
})
--hmi side: TTS.Speak request
EXPECT_HMICALL("TTS.Speak",
{
ttsChunks =
{
{
text = "Speak text in second session",
type = "TEXT"
}
}
})
:Do(function(_,data)
--hmi side: sending TTS.Speak response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--mobile side: Speak response in second session
self.mobileSession2:ExpectResponse(cidSecondSession,{resultCode = "SUCCESS", success = true})
end)
--hmi side: expect BasicCommunication.OnAppUnregistered
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", { appID = self.applications["Test Application"], unexpectedDisconnect = false})
end
---------------------------------------------------------------------------------------------
--Description: TC checks absence of unregistration by SDL after receiving BasicCommunication.OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION) without appId.
function Test:Precondition_RegisterAppFirstSession()
AppRegistration(self, self.mobileSession, application1.registerAppInterfaceParams)
end
function Test:Case_OnExitApplicationWithoutAppId()
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION"})
EXPECT_ANY_SESSION_NOTIFICATION("OnAppInterfaceUnregistered")
:Times(0)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered")
:Times(0)
DelayedExp(3000)
end
---------------------------------------------------------------------------------------------
--Description: TC checks absence of unregistration by SDL after receiving BasicCommunication.OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION) with appId of not registered app.
function Test:Case_OnExitApplicationWithNotExistentAppID()
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION", appID = 1111})
EXPECT_ANY_SESSION_NOTIFICATION("OnAppInterfaceUnregistered")
:Times(0)
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered")
:Times(0)
DelayedExp(3000)
end
---------------------------------------------------------------------------------------------
--Description: TC checks unregistration by SDL after receiving BasicCommunication.OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION) of 2 registered apps.
function Test:Case_OnExitApplicationToTwoRegisteredApps()
--hmi side: send request BasicCommunication.OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION", appID = self.applications["Test Application"]})
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION", appID = self.applications["Test Application2"]})
--mobile side: expect onAppInterfaceUnregistered notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
self.mobileSession2:ExpectNotification("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
--hmi side: expect BasicCommunication.OnAppUnregistered
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered",
{ appID = self.applications["Test Application"], unexpectedDisconnect = false},
{ appID = self.applications["Test Application2"], unexpectedDisconnect = false})
:Times(2)
DelayedExp(1000)
end
---------------------------------------------------------------------------------------------
--Description: TC checks unregistration by SDL after receiving BasicCommunication.OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION) in limited.
function Test:Precondition_RegisterApp()
AppRegistration(self, self.mobileSession, application1.registerAppInterfaceParams)
end
function Test:Precondition_ActivateApp()
ActivationApp(self, self.applications["Test Application"], self.mobileSession)
end
function Test:Case_OnExitApplicationInLimited()
--hmi side: sending BasicCommunication.OnExitApplication notification
self.hmiConnection:SendNotification("BasicCommunication.OnAppDeactivated", {appID = self.applications["Test Application"], reason = "GENERAL"})
EXPECT_NOTIFICATION("OnHMIStatus",
{ systemContext = "MAIN", hmiLevel = "LIMITED", audioStreamingState = "AUDIBLE"})
:Do(function(_,data)
--hmi side: send request BasicCommunication.OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION", appID = self.applications["Test Application"]})
--mobile side: expect onAppInterfaceUnregistered notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
--hmi side: expect BasicCommunication.OnAppUnregistered
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", { appID = self.applications["Test Application"], unexpectedDisconnect = false})
end)
end
---------------------------------------------------------------------------------------------
--Description: TC checks unregistration by SDL after receiving BasicCommunication.OnExitApplication(UNAUTHORIZED_TRANSPORT_REGISTRATION) in background.
function Test:Precondition_RegisterAppFirstSession()
AppRegistration(self, self.mobileSession, application1.registerAppInterfaceParams)
end
function Test:Precondition_RegisterAppSecondSession()
AppRegistration(self, self.mobileSession2, application2.registerAppInterfaceParams)
end
function Test:Precondition_ActivateAppFirstApp()
ActivationApp(self, self.applications["Test Application"], self.mobileSession)
end
function Test:Precondition_ActivateAppSendApp()
local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications["Test Application2"]})
EXPECT_HMIRESPONSE(RequestId)
:Do(function(_,data)
if
data.result.isSDLAllowed ~= true then
local RequestId = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}})
--hmi side: expect SDL.GetUserFriendlyMessage message response
EXPECT_HMIRESPONSE(RequestId,{result = {code = 0, method = "SDL.GetUserFriendlyMessage"}})
:Do(function(_,data)
--hmi side: send request SDL.OnAllowSDLFunctionality
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}})
--hmi side: expect BasicCommunication.ActivateApp request
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_,data)
--hmi side: sending BasicCommunication.ActivateApp response
self.hmiConnection:SendResponse(data.id,"BasicCommunication.ActivateApp", "SUCCESS", {})
end)
:Times(2)
end)
end
end)
--mobile side: expect notification
self.mobileSession2:ExpectNotification("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"})
EXPECT_NOTIFICATION("OnHMIStatus",
{ systemContext = "MAIN", hmiLevel = "BACKGROUND", audioStreamingState = "NOT_AUDIBLE"})
end
function Test:Case_OnExitApplicationInBackground()
--hmi side: send request BasicCommunication.OnExitApplication
self.hmiConnection:SendNotification("BasicCommunication.OnExitApplication", {reason = "UNAUTHORIZED_TRANSPORT_REGISTRATION", appID = self.applications["Test Application"]})
--mobile side: expect onAppInterfaceUnregistered notification
EXPECT_NOTIFICATION("OnAppInterfaceUnregistered", {reason = "APP_UNAUTHORIZED"})
--hmi side: expect BasicCommunication.OnAppUnregistered
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", { appID = self.applications["Test Application"], unexpectedDisconnect = false})
end
end
part2()
---------------------------------------------------------------------------------------------
-------------------------------------------Post-conditions-----------------------------
---------------------------------------------------------------------------------------------
--Postcondition: restore sdl_preloaded_pt.json
testCasesForPolicyTable:Restore_preloaded_pt()
return Test
|
util.AddNetworkString("OCRP_UpdateInventory")
util.AddNetworkString("OCRP_UpdateSkills")
function PMETA:UnCompileString( t, to_uncompile_string )
local ExplodedStr = string.Explode( ";", to_uncompile_string )
if t == "inv" then
for k, v in pairs(ExplodedStr) do
local ExplodedSecond = string.Explode( ".", v )
if GAMEMODE.OCRP_Items[ExplodedSecond[1]] != nil then
if tonumber(ExplodedSecond[2]) >= 1 then
if ExplodedSecond[1] != "item_ammo_cop" then
self:GiveItem(ExplodedSecond[1],tonumber(ExplodedSecond[2]),"LOAD")
end
end
end
end
net.Start("OCRP_UpdateInventory")
net.WriteTable(self.OCRPData["Inventory"])
net.Send(self)
elseif t == "itembank" then
for k, v in pairs(ExplodedStr) do
local ExplodedSecond = string.Explode( ".", v )
if GAMEMODE.OCRP_Items[ExplodedSecond[1]] != nil then
if tonumber(ExplodedSecond[2]) >= 1 then
self.OCRPData["ItemBank"].WeightData.Cur = self.OCRPData["ItemBank"].WeightData.Cur + GAMEMODE.OCRP_Items[ExplodedSecond[1]].Weight
self.OCRPData["ItemBank"][ExplodedSecond[1]] = tonumber(ExplodedSecond[2])
end
end
end
elseif t == "car" then
for k, v in pairs(ExplodedStr) do
local ExplodedSecond = string.Explode( ".", v )
if GAMEMODE.OCRP_Cars[ExplodedSecond[1]] != nil then
if !ExplodedSecond[3] then
ExplodedSecond[3] = false
end
table.insert(self.OCRPData["Cars"], {car = ExplodedSecond[1], skin = tonumber(ExplodedSecond[2]), hydros = ExplodedSecond[3], underglow = ExplodedSecond[4], Nitrous = ExplodedSecond[5], headlights = ExplodedSecond[6]})
if ExplodedSecond[7] ~= "nil" then
self.GasSave[ExplodedSecond[1]] = tonumber(ExplodedSecond[7])
self:SetNWInt("Gas_" .. ExplodedSecond[1], tonumber(ExplodedSecond[7]))
end
if ExplodedSecond[8] ~= "nil" then
self.HealthSave[ExplodedSecond[1]] = tonumber(ExplodedSecond[8])
self:SetNWInt("Health_" .. ExplodedSecond[1], tonumber(ExplodedSecond[8]))
end
end
end
SendCarsClient( self )
elseif t == "skill" then
for k, v in pairs(ExplodedStr) do
local ExplodedSecond = string.Explode( ".", v )
if GAMEMODE.OCRP_Skills[ExplodedSecond[1]] != nil then
self.OCRPData["Skills"][ExplodedSecond[1]] = tonumber(ExplodedSecond[2])
if GAMEMODE.OCRP_Skills[ExplodedSecond[1]].Function then
GAMEMODE.OCRP_Skills[ExplodedSecond[1]].Function( self, ExplodedSecond[1] )
end
end
end
self:UpdateAllSkills()
elseif t == "wardrobe" then
for k, v in pairs(ExplodedStr) do
if v == "" then continue end
if table.HasValue(self.OCRPData["Wardrobe"], v) then continue end
table.insert(self.OCRPData["Wardrobe"], tonumber(v))
end
self:SendWardrobeUpdate()
elseif t == "storage" then
local given = false
local held = false
local restored = {}
for k, v in pairs(ExplodedStr) do
local ExplodedSecond = string.Explode( ".", v )
if ExplodedSecond and ExplodedSecond[1] then
if GAMEMODE.OCRP_Items[ExplodedSecond[1]] != nil then
if tonumber(ExplodedSecond[2]) >= 1 then
local i = 1
while i <= tonumber(ExplodedSecond[2]) do
if self:HasRoom(ExplodedSecond[1], 1) and not self:ExceedsMax(ExplodedSecond[1], 1) then
given = true
self:UnStoreItem(ExplodedSecond[1], 1)
self:GiveItem(ExplodedSecond[1],1,"LOAD")
restored[ExplodedSecond[1]] = (restored[ExplodedSecond[1]] or 0) + 1
else
held = true
self:StoreItem(ExplodedSecond[1], 1)
end
i = i + 1
end
end
end
end
end
for k,v in pairs(restored) do
SV_PrintToAdmin(self, "RESTORE-ITEM", "was given back " .. tostring(v) .. " of " .. k .. " from last disconnect.")
end
if given == true then
self:Hint("You have been given back some dropped items you left when you last disconnected.")
end
if held == true then
self:Hint("Some items were not given back to you because you do not have enough room or they exceed your max for that item!")
self:Hint("Make room and reconnect to get your items back.")
end
net.Start("OCRP_UpdateInventory")
net.WriteTable(self.OCRPData["Inventory"])
net.Send(self)
--runOCRPQuery("UPDATE `ocrp_users` SET `storage` = 'None' WHERE `STEAM_ID` = '".. self:SteamID() .."'")
elseif t == "blacklist" then
self.OCRPData["Blacklists"] = {}
for k,v in pairs(ExplodedStr) do
self.OCRPData["Blacklists"][k] = true
end
elseif t == "buddies" then
self.OCRPData["Buddies"] = self.OCRPData["Buddies"] or {}
for k,v in pairs(ExplodedStr) do
table.insert(self.OCRPData["Buddies"], v)
end
net.Start("OCRP_UpdateBuddies")
net.WriteTable(self.OCRPData["Buddies"])
net.Send(self)
end
end
function PMETA:CompileString( t )
local Compiled = ""
if t == "inv" then
for item, amt in pairs(self.OCRPData["Inventory"]) do
if item != "WeightData" && !GAMEMODE.OCRP_Items[item].DoesntSave then
Compiled = Compiled ..item.."."..tostring(amt)..";"
end
end
elseif t == "itembank" then
for item, amt in pairs(self.OCRPData["ItemBank"]) do
if item != "WeightData" && !GAMEMODE.OCRP_Items[item].DoesntSave then
Compiled = Compiled ..item.."."..tostring(amt)..";"
end
end
elseif t == "car" then
for _, d in pairs(self.OCRPData["Cars"]) do
d.underglow = d.underglow or "none"
d.Nitrous = d.Nitrous or false
d.headlights = d.headlights or "none"
Compiled = Compiled ..d.car.."."..tostring(d.skin).."."..tostring(d.hydros).."." .. tostring(d.underglow) .. "." .. tostring(d.Nitrous) .. "." ..
tostring(d.headlights) .. "." .. tostring(self.GasSave[d.car]) .. "." .. tostring(self.HealthSave[d.car]) .. ";"
end
elseif t == "skill" then
for skill, level in pairs(self.OCRPData["Skills"]) do
Compiled = Compiled ..skill.."."..tostring(level)..";"
end
elseif t == "wardrobe" then
local added = {}
for _, d in pairs(self.OCRPData["Wardrobe"]) do
if d == "" then continue end
if table.HasValue(added, d) then continue end
Compiled = Compiled .. d .. ";"
table.insert(added, d)
end
elseif t == "storage" then
for item, amt in pairs(self.OCRPData["Storage"] or {}) do
if !GAMEMODE.OCRP_Items[item].DoesntSave then
Compiled = Compiled ..item.."."..tostring(amt)..";"
end
end
elseif t == "blacklist" then
if self.OCRPData["Blacklists"] then
for k,v in pairs(self.OCRPData["Blacklists"]) do
if v == true then
if tonumber(k) > 1 then
Compiled = Compiled .. k .. ";"
end
end
end
end
elseif t == "warnings" then
for _,warning in pairs(self.OCRPData["Warnings"]) do
Compiled = Compiled ..warning.admin.."."..warning.reason.."." .. warning.Date .. ";"
end
elseif t == "buddies" then
for _,buddy in pairs(self.OCRPData["Buddies"]) do
if type(buddy) == "string" and string.len(buddy) > 0 then
Compiled = Compiled .. buddy .. ";"
end
end
end
return Compiled
end |
-- make table, grouping all data for the same item
-- input is 2 columns (item, data)
local A
while 1 do
local l=io.read()
if l==nil then break end
local _,_,a,b=string.find(l,'"?([_%w]+)"?%s*(.*)$')
if a~=A then A=a io.write("\n",a,":") end
io.write(" ",b)
end
io.write("\n")
|
-- see: https://github.com/openresty/lua-nginx-module#nginx-api-for-lua
local RDB = get_RDB()
-- must be before any content
local hdrs = ngx.req.get_headers()
-- remove port number from hostname
local vhost = get_vhostname()
-- map request to a redis key
local rkey = vhost .. '|' .. (ngx.var.uri or '/')
-- look it up (expecting a hash)
local values, err = RDB:hgetall(rkey)
if err or #values == 0 then
-- internal redirect to fastCGI. extend in nginx conf file.
return ngx.exec('/__F__/' .. vhost)
end
-- tracking
-- RDB:hincrby(rkey, '_hits', 1)
-- redis.lua code returns the redis list aka array as
-- a list of values. Need them to be name/value pairs
values = RDB:array_to_hash(values)
local content, content_hash = 'EMPTY', nil
for name, val in pairs(values) do
--LOG("n=" .. (name or 'nil') .. " v=" .. (val or 'nil'))
if name == '_content' then
-- this key holds the HTML or image data itself (raw)
content = val
ngx.header['X-CFC-Hit'] = 'm'
elseif name == '_hash' then
content_hash = val
ngx.header['X-CFC-Hit'] = 'd'
elseif name == '_status' then
-- control response status
ngx.status = val
elseif name == '_redirect' then
-- we need ngx to handle complexity of relative urls and so on.
return ngx.redirect('//' .. hdrs.host .. val, values._code or 302)
elseif name == '_refresh' then
-- use the value to update the key's timeout so stays in cache on read usage
RDB:expire(val)
elseif string.sub(name, 1,1) == '_' then
-- ignore
else
-- everything else is a header line
ngx.header[name] = val
end
end
if content_hash then
-- do internal redirect, and serve as a static file.
-- LOG(rkey .. ' => /__S__/' .. content_hash)
return ngx.exec('/__S__/' .. content_hash)
else
-- send it directly
ngx.print(content)
end
|
--[[-------------------------------------------------------------------------
API for adding new
- tilesets
- corporations
- islands
request api:
==============
local path = mod_loader.mods[modApi.currentMod].scriptPath
local islandApi = require(path .."replaceIsland/api")
-----------------
-- Method List
-----------------
islandApi:GetVersion()
======================
returns the version of this library (not the highest version initialized)
islandApi:GetHighestVersion()
=============================
returns the highest version of this library.
since mods are initialized sequentially,
this function cannot be sure of the highest version until after init.
it will be up to date when when islands are initialized however.
islandApi:IsIsland(id)
======================
returns true if island with id is one of the 4 islands selected.
island order is determined after all mods has been initialized.
islandApi:GetIsland(id)
=======================
returns the corp index used for island id.
island order is determined after all mods has been initialized. but before they load.
any code requiring island order at game init can be called from your island's init function.
islandApi:AddTileset(tileset)
=============================
adds a tileset that can be set to an island.
tileset is a table with the following fields:
field | type | description
---------------------+--------------------+------------------------------------------------------------
id | string | an identifier that should be unique among tilesets. (req)
path | string | the file path within mod for tiles. (req)
tiles | table | a table for setting the locations of tiles.
| | default locations are used for tiles without one.
rainchance | number | percentage chance of rain.
GetRainchance | function() | function version of rainChance.
environmentChance | table | percentage chance of turning plain tiles to another tile.
getEnvironmentChance | function(tileType) | function version of environmentChance.
---------------------+--------------------+------------------------------------------------------------
example:
----------
local sandLoc = Point(-28,1)
{
id = "my_unique_tileset_id",
path = "img/my_first_tileset/",
tiles = {
"building_sheet", -- default location for "building_sheet" will be used.
"ground_0", -- default location for "ground_0" will be used.
sand_0 = sandLoc, -- custom location used instead.
sand_1 = sandLoc,
},
rainChance = 30, -- percentage chance of rain.
getRainChance = function() -- alternatively use a function to set rainchance.
return 30
end,
environmentChance = { -- percentage chance of turning plain tile to other tile.
[TERRAIN_ACID] = 0,
[TERRAIN_FOREST] = 14,
[TERRAIN_SAND] = 3,
[TERRAIN_ICE] = 0,
},
getEnvironmentChance = function(tileType) -- alternatively use a function to set environmentChance.
if tileType == TERRAIN_FOREST then
return 30
end
return 0
end
}
islandApi:AddCorp(corporation)
==============================
adds a corporation that can be set to an island.
corporation is a table with the following fields:
(most of the fields are required)
field | type | description
---------------------+------------------+----------------------------------------------------------------------
id | string | an identifier that should be unique among corporations. (req)
path | string | the file path within mod for corporation assets. (req)
CEO_Name | string | name of CEO
CEO_Personality | string | personality id for dialog for CEO.
Name | string | display name for corporation.
Bark_Name | string | shorthand(?) display name for corporation.
Tileset | string | id of tileset used for missions.
Environment | string | display name for environment.
Description | string | displayed description of corporation.
Pilot | string | id of pilot used by corporate units in missions.
PowAssets | table of strings | ids of building assets for random Power Objectives in missions.
TechAssets | table of strings | ids of building assets for random Core Objectives in missions.
RepAssets | table of strings | ids of building assets for random Reputation Objectives in missions.
Missions_High | table of strings | ids of high threat level missions given by corporation.
Missions_Low | table of strings | ids of low threat level missions given by corporation.
Color | string | color for something(?)
Music | table of strings | paths to music in missions.
Map | table of strings | paths to music on island overview.
---------------------+------------------+----------------------------------------------------------------------
example:
----------
local corp = Corp_Default:new{
id = "my_unique_corporation_id",
path = "img/my_first_corp/",
}
-- or a more or less complete template --
local corp = {
id = "my_unique_corporation_id",
path = "img/my_first_corp/",
CEO_Name = "Mr. Business",
CEO_Personality = "Personality_CEO",
Name = "Pepsi Co",
Bark_Name = "Pepsi",
Tileset = "grass",
Environment = "Wacky Weather",
Description = "This is my first corporation",
Pilot = "Pilot_Archive",
PowAssets = {
"Str_Power",
"Str_Nimbus",
"Str_Battery",
"Str_Power"
},
TechAssets = {
"Str_Robotics",
"Str_Research"
},
RepAssets = {
"Str_Bar",
"Str_Clinic"
},
Missions_High = {
"Mission_Volatile",
"Mission_Train",
"Mission_Force"
},
Missions_Low = {
"Mission_Survive",
"Mission_Wind"
},
Bosses = {
"Mission_BlobBoss",
"Mission_SpiderBoss",
"Mission_BeetleBoss",
"Mission_HornetBoss",
"Mission_FireflyBoss",
"Mission_ScorpionBoss",
"Mission_JellyBoss",
},
Color = GL_Color(200,25,25),
Music = { "/music/grass/combat_delta", "/music/grass/combat_gamma"},
Map = { "/music/grass/map" }
}
islandApi:AddIsland(island)
===========================
adds a new island to the arrange island screen.
island is a table with the following fields:
field | type | description
---------------------+---------------------+------------------------------------------------------------------
id | string | an identifier that should be unique among islands. (req)
path | string | the file path within mod for island assets. (req)
corp | string | id of corporation used for island.
shift | Point | an offset between 1x and 3x version of island images.
magic | Point | an offset for mouse detection of sectors on 3x island.
data | table of RegionInfo | list of sectors made with RegionInfo(p1, p2, i1)
network | tbl of tbl of ints | table of network connections between sectors.
init | function | init func called to init islands after all mods has been inited.
startIsland | function | wip
leaveIsland | function | wip
---------------------+---------------------+------------------------------------------------------------------
example:
----------
local island = {
id = "my_unique_island_id",
path = "img/my_first_island/",
corp = "Corp_Grass",
-- an offset to translate between 1x and ~3x zoom level of island.
shift = Point(10,15),
-- offsets the mouse detection sections on zoomed in island.
magic = Point(135,82),
-- RegionInfo(x, y, z)
-- x: offset of section.
-- y: offset of text from center of section.
-- z: threat level? not sure.
data = {
RegionInfo(Point(61,47) - off, Point(20,0), 300),
RegionInfo(Point(69,152) - off, Point(0,-40), 100),
RegionInfo(Point(106,186) - off, Point(0,-25), 100),
RegionInfo(Point(180,67) - off, Point(0,0), 300),
RegionInfo(Point(304,83) - off, Point(0,-50), 100),
RegionInfo(Point(262,143) - off, Point(0,-30), 100),
RegionInfo(Point(247,186) - off, Point(10,-10), 300),
RegionInfo(Point(357,186) - off, Point(-10,-20), 100)
},
-- describes which sections are connected to which other sections.
network = {
{1,3},
{0,2,3},
{1,3,6},
{0,1,2,4,5},
{3,5},
{3,4,6,7},
{2,5,7},
{5,6}
},
init = function(self)
-- custom init code for island.
end,
-- ideas for functions that are currently not implemented.
-- may add them if a use case comes up.
load = function(self, options, version)
startIsland = function(self) end -- use currentTileset.lua's hook for loading tileset instead.
leaveIsland = function(self) end -- use currentTileset.lua's hook for loading tileset instead.
}
islandApi:UnlockRst()
=====================
unlocks RST, so the island can be swapped out.
]]---------------------------------------------------------------------------
local path = mod_loader.mods[modApi.currentMod].resourcePath
local init = require(path .."scripts/replaceIsland/init")
local this = {}
local function file_exists(name)
local f = io.open(name, "r")
if f then io.close(f) return true else return false end
end
local waterLoc = Point(-28,1)
local mountainLoc = Point(-28,-21)
local buildingTileLoc = Point(-28,-15)
local forestLoc = Point(-25,5)
local lavaLoc = Point(-27,2)
local sandLoc = Point(-28,1)
local tileLoc = {
acid_0 = waterLoc,
acid_1 = waterLoc,
acid_2 = waterLoc,
acid_3 = waterLoc,
building_1_tile = buildingTileLoc,
building_2_tile = buildingTileLoc,
building_3_tile = buildingTileLoc,
forest_0 = forestLoc,
forest_0_front = forestLoc,
ice = waterLoc,
ice_1 = waterLoc,
ice_1_crack = waterLoc,
ice_2 = waterLoc,
ice_2_crack = waterLoc,
lava_0 = lavaLoc,
lava_1 = lavaLoc,
mountain = mountainloc,
mountain_0 = mountainLoc,
mountain_0_broken = mountainLoc,
mountain_1 = mountainLoc,
mountain_2 = mountainLoc,
sand_0 = sandLoc,
sand_1 = sandLoc,
sand_0_front = sandLoc,
sand_1_front = sandLoc,
water = waterLoc,
water_0 = waterLoc,
water_1 = waterLoc,
water_2 = waterLoc,
water_3 = waterLoc,
}
function this:GetVersion()
return init.version
end
function this:GetHighestVersion()
return init.mostRecent.version
end
function this:IsIsland(id)
return self:GetIsland(id) and true
end
function this:GetIsland(id)
local ret = list_indexof(lmn_replace_island.islandOrder, id)
return ret > 0 and ret or nil
end
function this:AddTileset(tileset)
assert(type(tileset) == 'table')
assert(type(tileset.id) == 'string') -- TODO: check for collision with other added tilesets?
assert(type(tileset.path) == 'string')
local m = lmn_replace_island
local path = path .. tileset.path
assert(not m.tilesets[tileset.id], "Attempted to add a tileset with the same id as another.")
m.tilesets[tileset.id] = tileset
tileset.getEnvironmentChance = tileset.getEnvironmentChance or function(tileType, ...) return tileset.environmentChance and tileset.environmentChance[tileType] or 0 end
tileset.getRainChance = tileset.getRainChance or function(...) return tileset.rainChance or 0 end
assert(type(tileset.getEnvironmentChance) == 'function')
assert(type(tileset.getRainChance) == 'function')
if file_exists(path .."env.png") then
modApi:appendAsset("img/strategy/corp/".. tileset.id .."_env.png", path .."env.png")
else
modApi:copyAsset("img/combat/tiles_grass/ground_0.png" ,"img/strategy/corp/".. tileset.id .."_env.png")
end
if type(tileset.tiles) ~= 'table' then return end
for i, loc in pairs(tileset.tiles) do
local tile = i
if type(tile) == 'number' then
assert(type(loc) == 'string')
tile = loc
loc = tileLoc[tile]
end
local resourcePath = "combat/tiles_".. tileset.id .."/".. tile ..".png"
local file = path .. tile ..".png"
Location[resourcePath] = loc
if file_exists(file) then
modApi:appendAsset("img/".. resourcePath, file)
end
end
end
function this:AddCorp(corp)
assert(type(corp) == 'table')
assert(type(corp.id) == 'string')
assert(type(corp.path) == 'string')
local m = lmn_replace_island
local path = path .. corp.path
assert(not m.corps[corp.id], "Attempted to add a corporation with the same id as another.")
m.corps[corp.id] = Corp_Default:new(corp)
local file = path .."ceo.png"
if file_exists(file) then
corp.CEO_Image = corp.id ..".png"
modApi:appendAsset("img/portraits/ceo/".. corp.id ..".png", file)
elseif not file_exists("img/portraits/ceo/".. corp.CEO_Image) then
corp.CEO_Image = "ceo_portrait.png"
end
local file1 = path .."office.png"
local file2 = path .."office_small.png"
if file_exists(file1) and file_exists(file2) then
corp.Office = corp.id
modApi:appendAsset("img/ui/corps/".. corp.id .."_small.png", file2)
modApi:appendAsset("img/ui/corps/".. corp.id ..".png", file1)
elseif
not file_exists("img/ui/corps/".. corp.Office .."_small.png") or
not file_exists("img/ui/corps/".. corp.Office ..".png")
then
corp.Office = "archive"
end
end
function this:AddIsland(island)
assert(type(island) == 'table')
assert(type(island.id) == 'string')
assert(type(island.path) == 'string')
island.corp = island.corp or "Corp_Grass"
local m = lmn_replace_island
local path = path .. island.path
island.resourcePath = "img/islands/".. island.id
assert(not m.islands[island.id], "Attempted to add an island with the same id as another.")
m.islands[island.id] = island
modApi:appendAsset(island.resourcePath .."/island.png", path .."island.png")
modApi:appendAsset(island.resourcePath .."/island1x.png", path .."island1x.png")
modApi:appendAsset(island.resourcePath .."/island1x_out.png", path .."island1x_out.png")
for x = 0, 7 do
modApi:appendAsset(island.resourcePath .."/island_".. x ..".png", path .."/sections/island_".. x ..".png")
modApi:appendAsset(island.resourcePath .."/island_".. x .."_OL.png", path .."/sections/island_".. x .."_OL.png")
end
end
function this:UnlockRst()
local m = lmn_replace_island
m.unlockRst = true
end
return this |
-- Mite interpreter
-- (c) Reuben Thomas 2000
return {
writes = "Mite interpreter",
output =
[[/* Interpreter output */
typedef struct {
Word ret;
} runW_Output;
]],
prelude = [[
typedef void runW_State;
#define returnWith(r) \
out->ret = r; \
return out
#define checkDiv(d) \
if (d == 0) \
returnWith (ExcDivByZero)
#define checkShift(s) \
if (s > WORD_BIT) \
returnWith (ExcBadShift)
#define P R->ptr
#define setP(x) \
P = (Byte *)(x); checkP
#define checkP \
if (P > R->end || P < R->img) \
returnWith (ExcBadP)
#define setS(x) \
S = (Word *)(x); checkS
#define checkS \
if (S > stkEnd || S < stk) \
returnWith (ExcBadS)
/* TODO: Use a linked list of stack frames; setS will unwind it */
#define stackExtend \
returnWith (ExcBadS)
#define extendS \
if (S == stk) \
stackExtend
#define REGS 8
static void *
runW_writerNew (void)
{
return NULL;
}]],
resolve = nil,
macros = "",
inst = {
Inst {"lab", ""},
Inst {"mov", "r[o1] = r[o2]"},
Inst {"movi", "r[o1] = objR_getNum (R, &o2)"},
Inst {"ldl", "r[o1] = inp->labAddr[LABEL_D][o2]"},
Inst {"ld", "if (r[o2] & WORD_MASK) returnWith (ExcBadAddress); " ..
"r[o1] = *(SWord *)r[o2]"},
Inst {"st", "if (r[o2] & WORD_MASK) returnWith (ExcBadAddress); " ..
"*(SWord *)r[o1] = r[o2]"},
Inst {"gets", "r[o1] = (SWord)S"},
Inst {"sets", "setS (r[o1])"},
Inst {"pop", "r[o1] = *S; setS (S + 1)"},
Inst {"push", "extendS; setS (S - 1); *S = r[o1]"},
Inst {"add", "r[o1] = r[o2] + r[o3]"},
Inst {"sub", "r[o1] = r[o2] - r[o3]"},
Inst {"mul", "r[o1] = r[o2] * r[o3]"},
Inst {"div", "checkDiv ((Word)r[o3]); " ..
"r[o1] = (Word)r[o2] / (Word)r[o3]"},
Inst {"rem", "checkDiv ((Word)r[o3]); " ..
"r[o1] = (Word)r[o2] % (Word)r[o3]"},
Inst {"and", "r[o1] = r[o2] & r[o3]"},
Inst {"or", "r[o1] = r[o2] | r[o3]"},
Inst {"xor", "r[o1] = r[o2] ^ r[o3]"},
Inst {"sl", "checkShift ((Word)r[o3]); " ..
"r[o1] = r[o2] << r[o3]"},
Inst {"srl", "checkShift ((Word)r[o3]); " ..
"r[o1] = (Word)r[o2] >> r[o3]"},
Inst {"sra", "checkShift ((Word)r[o3]); " ..
"r[o1] = r[o2] >> r[o3]"},
Inst {"teq", "r[o1] = r[o2] == r[o3]"},
Inst {"tlt", "r[o1] = r[o2] < r[o3]"},
Inst {"tltu", "r[o1] = (Word)r[o2] < (Word)r[o3]"},
Inst {"b", "setP (o1)"},
Inst {"br", "setP (r[o1])"},
Inst {"bf", "if (!r[o1]) setP (o2)"},
Inst {"bt", "if (r[o1]) setP (o2)"},
Inst {"call", "extendS; setS (S - 1); *S = (SWord)P; " ..
"setP (o1 + 1)"},
Inst {"callr", "extendS; setS (S - 1); *S = (SWord)P; " ..
"setP (o1 + 1)"},
Inst {"ret", "if (S == stkEnd) returnWith (ExcRet); " ..
"setP (*S); setS (S + 1)"},
Inst {"calln", "(*(void (*)(void))(*(SWord *)r[o1]))()"},
Inst {"lit", ""},
Inst {"litl", ""},
Inst {"space", ""},
},
trans = Translator {
[[SWord r[REGS], o1, o2, o3;
Word *S, *stk, *stkEnd, stkSize = 1024;
]], -- decls
[[stk = new (stkSize * WORD_BYTE);
stkEnd = S = stk + stkSize;]], -- init
"", -- update
"", -- finish
},
}
|
local old_ST_init = SkillTreeTweakData.init
function SkillTreeTweakData:init(tweak_data)
old_ST_init(self, tweak_data)
local function digest(value)
return Application:digest_value(value, true)
end
self.tier_unlocks = {
digest(0),
digest(0),
digest(0),
digest(0)
}
end |
local MP = minetest.get_modpath("eco_mapgen")
eco_mapgen.register_biome({
name = "ice",
match = {
temperature = 0,
humidity = 20,
min_height = 8
},
flat = MP .. "/schematics/base/grass_flat",
slope_upper = MP .. "/schematics/base/grass_slope_upper",
slope_lower = MP .. "/schematics/base/grass_slope_lower",
slope_inner_upper = MP .."/schematics/base/grass_slope_inner_corner_upper",
slope_inner_lower = MP .."/schematics/base/grass_slope_inner_corner_lower",
slope_outer_upper = MP .."/schematics/base/grass_slope_outer_corner_upper",
slope_outer_lower = MP .."/schematics/base/grass_slope_outer_corner_lower",
replace = {
["default:dirt_with_grass"] = "default:ice",
["eco_stairsplus:slope_dirt_with_grass"] = "moreblocks:slope_ice",
["eco_stairsplus:slope_dirt_with_grass_inner_cut"] = "moreblocks:slope_ice_inner_cut",
["eco_stairsplus:slope_dirt_with_grass_outer_cut"] = "moreblocks:slope_ice_outer_cut"
}
})
|
function Client_PresentConfigureUI(rootParent)
rootParentobj = rootParent;
Conditionsrequiredforwinit = Mod.Settings.Conditionsrequiredforwin;
if(Conditionsrequiredforwinit == nil)then
Conditionsrequiredforwinit = 1;
end
Capturedterritoriesinit = Mod.Settings.Capturedterritories;
if(Capturedterritoriesinit == nil)then
Capturedterritoriesinit = 0;
end
Lostterritoriesinit = Mod.Settings.Lostterritories;
if(Lostterritoriesinit == nil)then
Lostterritoriesinit = 0;
end
Ownedterritoriesinit = Mod.Settings.Ownedterritories;
if(Ownedterritoriesinit == nil)then
Ownedterritoriesinit = 0;
end
Capturedbonusesinit = Mod.Settings.Capturedbonuses;
if(Capturedbonusesinit == nil)then
Capturedbonusesinit = 0;
end
Lostbonusesinit = Mod.Settings.Lostbonuses;
if(Lostbonusesinit == nil)then
Lostbonusesinit = 0;
end
Ownedbonusesinit = Mod.Settings.Ownedbonuses;
if(Ownedbonusesinit == nil)then
Ownedbonusesinit = 0;
end
Killedarmiesinit = Mod.Settings.Killedarmies;
if(Killedarmiesinit == nil)then
Killedarmiesinit = 0;
end
Lostarmiesinit = Mod.Settings.Lostarmies;
if(Lostarmiesinit == nil)then
Lostarmiesinit = 0;
end
Ownedarmiesinit = Mod.Settings.Ownedarmies;
if(Ownedarmiesinit == nil)then
Ownedarmiesinit = 0;
end
Eleminateaisinit = Mod.Settings.Eleminateais;
if(Eleminateaisinit == nil)then
Eleminateaisinit = 0;
end
Eleminateplayersinit = Mod.Settings.Eleminateplayers;
if(Eleminateplayersinit == nil)then
Eleminateplayersinit = 0;
end
Eleminateaisandplayersinit = Mod.Settings.Eleminateaisandplayers;
if(Eleminateaisandplayersinit == nil)then
Eleminateaisandplayersinit = 0;
end
terrconditioninit = Mod.Settings.terrcondition
if(terrconditioninit == nil)then
terrconditioninit = {};
end
ShowUI();
end
function ShowUI()
hotzlist = {};
local num = 0;
local conditionnumber = 14;
while(num <= conditionnumber)do
hotzlist[num] = UI.CreateHorizontalLayoutGroup(rootParentobj);
num = num + 1;
end
UI.CreateLabel(hotzlist[0]).SetText('To disable a condition, set it to 0(except territory conditions, they are disabled through the remove button)');
UI.CreateLabel(hotzlist[1]).SetText('Conditions required for win');
inputConditionsrequiredforwin = UI.CreateNumberInputField(hotzlist[1]).SetSliderMinValue(1).SetSliderMaxValue(11).SetValue(Conditionsrequiredforwinit);
UI.CreateLabel(hotzlist[2]).SetText('Captured this many territories');
inputCapturedterritories = UI.CreateNumberInputField(hotzlist[2]).SetSliderMinValue(0).SetSliderMaxValue(1000).SetValue(Capturedterritoriesinit);
UI.CreateLabel(hotzlist[3]).SetText('Lost this many territories');
inputLostterritories = UI.CreateNumberInputField(hotzlist[3]).SetSliderMinValue(0).SetSliderMaxValue(1000).SetValue(Lostterritoriesinit);
UI.CreateLabel(hotzlist[4]).SetText('Owns this many territories');
inputOwnedterritories = UI.CreateNumberInputField(hotzlist[4]).SetSliderMinValue(0).SetSliderMaxValue(1000).SetValue(Ownedterritoriesinit);
UI.CreateLabel(hotzlist[5]).SetText('Captured this many bonuses');
inputCapturedbonuses = UI.CreateNumberInputField(hotzlist[5]).SetSliderMinValue(0).SetSliderMaxValue(100).SetValue(Capturedbonusesinit);
UI.CreateLabel(hotzlist[6]).SetText('Lost this many bonuses');
inputLostbonuses = UI.CreateNumberInputField(hotzlist[6]).SetSliderMinValue(0).SetSliderMaxValue(100).SetValue(Lostbonusesinit);
UI.CreateLabel(hotzlist[7]).SetText('Owns this many bonuses');
inputOwnedbonuses = UI.CreateNumberInputField(hotzlist[7]).SetSliderMinValue(0).SetSliderMaxValue(100).SetValue(Ownedbonusesinit);
UI.CreateLabel(hotzlist[8]).SetText('Killed this many armies');
inputKilledarmies = UI.CreateNumberInputField(hotzlist[8]).SetSliderMinValue(0).SetSliderMaxValue(1000).SetValue(Killedarmiesinit);
UI.CreateLabel(hotzlist[9]).SetText('Lost this many armies');
inputLostarmies = UI.CreateNumberInputField(hotzlist[9]).SetSliderMinValue(0).SetSliderMaxValue(1000).SetValue(Lostarmiesinit);
UI.CreateLabel(hotzlist[10]).SetText('Owns this many armies');
inputOwnedarmies = UI.CreateNumberInputField(hotzlist[10]).SetSliderMinValue(0).SetSliderMaxValue(1000).SetValue(Ownedarmiesinit);
UI.CreateLabel(hotzlist[11]).SetText("Eleminated this many ais(players turned into ai don't count)");
inputEleminateais = UI.CreateNumberInputField(hotzlist[11]).SetSliderMinValue(0).SetSliderMaxValue(39).SetValue(Eleminateaisinit);
UI.CreateLabel(hotzlist[12]).SetText('Eliminated this many players');
inputEleminateplayers = UI.CreateNumberInputField(hotzlist[12]).SetSliderMinValue(0).SetSliderMaxValue(39).SetValue(Eleminateplayersinit);
UI.CreateLabel(hotzlist[13]).SetText('Eliminated this many AIs and players');
inputEleminateaisandplayers = UI.CreateNumberInputField(hotzlist[13]).SetSliderMinValue(0).SetSliderMaxValue(39).SetValue(Eleminateaisandplayersinit);
inputterrcondition = {};
for _,terrcondition in pairs(terrconditioninit)do
inputterrcondition[tablelength(inputterrcondition)] = {};
local num = tablelength(inputterrcondition)-1;
inputterrcondition[num].horz = UI.CreateHorizontalLayoutGroup(rootParentobj);
inputterrcondition[num].Terrname = UI.CreateTextInputField(inputterrcondition[num].horz).SetPlaceholderText('Enter territory name').SetText(terrcondition.Terrname).SetPreferredWidth(200).SetPreferredHeight(30);
UI.CreateLabel(inputterrcondition[num].horz).SetText("must be hold for");
inputterrcondition[num].Turnnum = UI.CreateNumberInputField(inputterrcondition[num].horz).SetSliderMinValue(0).SetSliderMaxValue(10).SetValue(terrcondition.Turnnum);
UI.CreateLabel(inputterrcondition[num].horz).SetText("Turns");
UI.CreateButton(inputterrcondition[num].horz).SetText('Remove condition').SetOnClick(function()
UI.Destroy(inputterrcondition[num].horz);
inputterrcondition[num].Terrname = nil;
end);
end
horz = UI.CreateHorizontalLayoutGroup(rootParentobj);
knopf = UI.CreateButton(horz).SetText('new territory condition').SetOnClick(newTerritoryCondition);
end
function newTerritoryCondition()
UI.Destroy(horz);
inputterrcondition[tablelength(inputterrcondition)] = {};
local num = tablelength(inputterrcondition)-1;
inputterrcondition[num].horz = UI.CreateHorizontalLayoutGroup(rootParentobj);
inputterrcondition[num].Terrname = UI.CreateTextInputField(inputterrcondition[num].horz).SetPlaceholderText('Enter territory name').SetText("").SetPreferredWidth(200).SetPreferredHeight(30);
UI.CreateLabel(inputterrcondition[num].horz).SetText("must be hold for");
inputterrcondition[num].Turnnum = UI.CreateNumberInputField(inputterrcondition[num].horz).SetSliderMinValue(0).SetSliderMaxValue(10).SetValue(0);
UI.CreateLabel(inputterrcondition[num].horz).SetText("Turns");
UI.CreateButton(inputterrcondition[num].horz).SetText('Remove condition').SetOnClick(function()
UI.Destroy(inputterrcondition[num].horz);
inputterrcondition[num].Terrname = nil;
end);
horz = UI.CreateHorizontalLayoutGroup(rootParentobj);
knopf = UI.CreateButton(horz).SetText('new territory condition').SetOnClick(newTerritoryCondition);
end
function tablelength(arr)
local num = 0;
for _,elem in pairs(arr)do
num = num + 1;
end
return num;
end
|
return {
summary = 'Different data types for samples in a Sound.',
description = 'Sounds can store audio samples as 16 bit integers or 32 bit floats.',
values = {
{
name = 'f32',
description = '32 bit floating point samples (between -1.0 and 1.0).'
},
{
name = 'i16',
description = '16 bit integer samples (between -32768 and 32767).'
}
}
}
|
b = BinooAPI
-- enable debug log
-- NOTE: wont catch messages from this same script immediately, should run this in a script before the main script
b:DebugMode(true)
|
#!/usr/bin/env lua
local ui = require "tek.ui"
local Widget = ui.Widget
local Group = ui.Group
local CheckMark = ui.CheckMark
local RadioButton = ui.RadioButton
local floor = math.floor
local Region = require "tek.lib.region"
local L = ui.getLocale("tekui-demo", "schulze-mueller.de")
local RadioImage1 = ui.getStockImage("radiobutton")
local RadioImage2 = ui.getStockImage("radiobutton", 2)
local BitMapImage1 = ui.loadImage(ui.ProgDir .. "/graphics/world.ppm")
local BitMapImage2 = ui.loadImage(ui.ProgDir .. "/graphics/locale_alpha.png")
or ui.loadImage(ui.ProgDir .. "/graphics/locale.ppm")
local FileImage = ui.getStockImage("file")
-------------------------------------------------------------------------------
-- Create demo window:
-------------------------------------------------------------------------------
local window = ui.Window:new
{
Status = "hide",
Id = "graphics-window",
Title = L.GRAPHICS_TITLE,
Width = "fill",
Height = "fill",
HideOnEscape = true,
SizeButton = true,
Children =
{
Group:new
{
Orientation = "vertical",
Legend = L.GRAPHICS_CHECKMARKS,
Style = "height: fill",
Children =
{
CheckMark:new { Text = "xx-small", Style = "font: ui-xx-small" },
CheckMark:new { Text = "x-small", Style = "font: ui-x-small" },
CheckMark:new { Text = "small", Style = "font: ui-small" },
CheckMark:new { Text = "main", Style = "font: ui-main",
Selected = true },
CheckMark:new { Text = "large", Style = "font: ui-large" },
CheckMark:new { Text = "x-large", Style = "font: ui-x-large" },
CheckMark:new { Text = "xx-large", Style = "font: ui-xx-large" },
}
},
Group:new
{
Orientation = "vertical",
Legend = L.GRAPHICS_RADIOBUTTONS,
Style = "height: fill",
Children =
{
RadioButton:new { Text = "xx-small", Style = "font: ui-xx-small" },
RadioButton:new { Text = "x-small", Style = "font: ui-x-small" },
RadioButton:new { Text = "small", Style = "font: ui-small" },
RadioButton:new { Text = "main", Style = "font: ui-main",
Selected = true },
RadioButton:new { Text = "large", Style = "font: ui-large" },
RadioButton:new { Text = "x-large", Style = "font: ui-x-large" },
RadioButton:new { Text = "xx-large", Style = "font: ui-xx-large" },
}
},
Group:new
{
Orientation = "vertical",
Legend = L.GRAPHICS_BITMAPS,
Style = "height: fill",
Children =
{
ui.ImageWidget:new
{
Mode = "inert",
Class = "button",
Image = BitMapImage2,
Style = "background-color: gradient(0,0,#238,0,100,#aaf); padding: 4",
},
ui.ImageWidget:new
{
Style = "background-color: #fff",
Image = BitMapImage1
}
}
},
Group:new
{
Orientation = "vertical",
Legend = L.GRAPHICS_BACKGROUND,
Style = "height: fill",
Children =
{
ui.Group:new
{
Style = [[
height: fill;
background-color: url(bin/graphics/world.ppm);
]],
Children =
{
ui.ImageWidget:new
{
Height = "fill",
Mode = "button",
Style = [[
background-color: transparent;
margin: 10;
padding: 4;
border-width: 10;
border-focus-width: 6;
min-width: 60;
]],
Image = FileImage
},
}
}
}
}
}
}
-------------------------------------------------------------------------------
-- Started stand-alone or as part of the demo?
-------------------------------------------------------------------------------
if ui.ProgName:match("^demo_") then
local app = ui.Application:new()
ui.Application.connect(window)
app:addMember(window)
window:setValue("Status", "show")
app:run()
else
return
{
Window = window,
Name = L.GRAPHICS_TITLE,
Description = L.GRAPHICS_DESCRIPTION,
}
end
|
-- oUF_SimpleConfig: target
-- zork, 2016
-----------------------------
-- Variables
-----------------------------
local A, L = ...
-----------------------------
-- Target Config
-----------------------------
L.C.target = {
enabled = true,
size = {272,26},
point = {"LEFT",UIParent,"CENTER",213,-273},
scale = 1*L.C.globalscale,
--fader via OnShow
fader = {
fadeInAlpha = 1,
fadeInDuration = 0.3,
fadeInSmooth = "OUT",
fadeOutAlpha = 0,
fadeOutDuration = 0.9,
fadeOutSmooth = "OUT",
fadeOutDelay = 0,
trigger = "OnShow",
},
--healthbar
healthbar = {
--health and absorb bar cannot be disabled, they match the size of the frame
colorTapping = true,
colorDisconnected = true,
colorClass = true,
colorReaction = true,
colorHealth = true,
colorThreat = true,
colorThreatInvers = true,
name = {
enabled = true,
points = {
{"TOPLEFT",2,10},
{"TOPRIGHT",-2,10},
},
size = 16,
tag = "[oUF_SimpleConfig:classification][difficulty][name]|r",
},
health = {
enabled = true,
point = {"RIGHT",-2,0},
size = 15,
tag = "[oUF_Simple:health]",
},
debuffHighlight = false,
},
--powerbar
powerbar = {
enabled = true,
size = {272,5},
point = {"TOP","BOTTOM",0,-4}, --if no relativeTo is given the frame base will be the relativeTo reference
colorPower = true,
},
--leader
leader = {
enabled = true,
size = {18,18},
point = {"BOTTOMRIGHT","TOPRIGHT",0,-6},
},
--raidmark
raidmark = {
enabled = true,
size = {18,18},
point = {"CENTER","TOP",0,4},
},
--castbar
castbar = {
enabled = true,
size = {267,28},
point = {"CENTER",UIParent,"BOTTOM",-16,225},
name = {
enabled = true,
points = {
{"LEFT",2,0},
{"RIGHT",-2,0},
},
--font = STANDARD_TEXT_FONT,
size = 16,
--outline = "",--OUTLINE",
--align = "CENTER",
--noshadow = true,
},
icon = {
enabled = true,
size = {26,26},
point = {"LEFT","RIGHT",6,0},
},
},
buffs = {
enabled = true,
point = {"BOTTOMRIGHT","TOPRIGHT",0,15},
num = 32,
cols = 4,
size = 30,
spacing = 4,
initialAnchor = "BOTTOMRIGHT",
growthX = "LEFT",
growthY = "UP",
disableCooldown = false,
},
debuffs = {
enabled = true,
point = {"BOTTOMLEFT","TOPLEFT",0,15},
num = 40,
cols = 4,
size = 30,
spacing = 8,
initialAnchor = "BOTTOMLEFT",
growthX = "RIGHT",
growthY = "UP",
disableCooldown = false,
filter = "PLAYER",
},
}
|
--[[
desc: Duelist, a system of duelist management.
author: Musoucrow
since: 2018-6-6
alter: 2019-9-27
]]--
local _CONFIG = require("config")
local _DIRECTOR = require("director")
local _SOUND = require("lib.sound")
local _MAP = require("map.init")
local _FACTORY = require("actor.factory")
local _RESMGR = require("actor.resmgr")
local _ASPECT = require("actor.service.aspect")
local _STATE = require("actor.service.state")
local _EFFECT = require("actor.service.effect")
local _BATTLE = require("actor.service.battle")
local _DUELIST = require("actor.service.duelist")
local _MOTION = require("actor.service.motion")
local _BUFF = require("actor.service.buff")
local _Color = require("graphics.drawunit.color")
local _Base = require("actor.system.base")
---@class Actor.System.Duelist : Actor.System
local _Duelist = require("core.class")(_Base)
local _overKillSoundData = _RESMGR.GetSoundData("overKill")
local _killEffectData = _RESMGR.GetInstanceData("effect/lastStrike")
local _namedColor = _Color.New(130, 255, 130, 255)
local _bossColor = _Color.New(255, 100, 255, 255)
local _inKill = false
local _bossRate = 0.1
local _bossScale = 1.3
local _inTime = 700
local _outTime = 300
local _meta = {__mode = 'v'}
local _iconPool = {}
setmetatable(_iconPool, _meta)
---@param e Actor.Entity
local function _BossBeaten(e)
if (not _inKill and e.attributes.hp <= 0) then
_BATTLE.Hitstop(e.attacker, e.identity, _outTime)
_DIRECTOR.SetRate(_bossRate, _inTime, "inOutQuad")
_MAP.camera:SetScale(_bossScale, _bossScale, _inTime, "inOutQuad")
local h = _ASPECT.GetPart(e.aspect):GetHeight()
local pos = e.transform.position
local param = {
x = pos.x,
y = pos.y,
z = pos.z - math.floor(h * 0.5)
}
_FACTORY.New(_killEffectData, param)
e.battle.deadProcess = 1
_inKill = true
end
end
function _Duelist:Ctor(upperEvent)
_Base.Ctor(self, upperEvent, {
duelist = true,
battle = true,
states = true,
attributes = true
}, "duelist")
_MAP.AddLoadListener(self, self.OnClean)
end
function _Duelist:OnEnter(entity)
if (entity.duelist.rank == 2) then
entity.battle.beatenCaller:AddListener(entity, _BossBeaten)
end
end
---@param entity Actor.Entity
function _Duelist:OnInit(entity)
if (_DUELIST.IsPartner(entity.battle, entity.duelist) and _CONFIG.user.player ~= entity) then
_DUELIST.SetAura(entity, "partner")
elseif (entity.duelist.rank == 2) then
_DUELIST.SetAura(entity, "boss")
elseif (entity.duelist.rank == 1) then
_DUELIST.SetAura(entity, "named")
end
entity.duelist.icon = _DUELIST.GetIcon(entity.aspect, _iconPool, entity.duelist.iconShift.x, entity.duelist.iconShift.y, 24, 24)
end
function _Duelist:OnClean(data)
local x = data.init.x
local y = data.init.y
local direction = data.init.direction
for n=1, self._list:GetLength() do
local e = self._list:Get(n) ---@type Actor.Entity
if (e.identity.canCross) then
e.transform.position:Set(x, y, 0)
e.transform.positionTick = true
if (direction) then
e.transform.direction = direction
e.transform.scaleTick = true
end
_STATE.Reset(e.states)
end
end
end
function _Duelist:Update(dt)
if (_inKill and not _DIRECTOR.IsTweening()) then
_DIRECTOR.SetRate(1, _outTime, "inOutQuad")
_MAP.camera:SetScale(1, 1, _outTime, "inOutQuad")
_SOUND.Play(_overKillSoundData)
_inKill = false
end
for n=1, self._list:GetLength() do
local e = self._list:Get(n) ---@type Actor.Entity
if (not e.identity.isPaused and e.battle.deadProcess > 0) then
if (e.duelist.rank == 2) then
local camp = e.battle.camp
for m=1, self._list:GetLength() do
local ee = self._list:Get(m) ---@type Actor.Entity
if ((ee.battle.camp == camp or ee.duelist.isEnemy) and ee.duelist.rank < 2) then
ee.battle.deadProcess = 1
end
end
end
end
end
end
return _Duelist |
package.path = package.path .. ";./lib/tui/?/init.lua;./lib/tui/?.lua;./lib/utf8_simple/?.lua"
local sirocco = require "sirocco"
local Prompt = sirocco.prompt
local List = sirocco.list
-- Clear whole screen for demo
-- io.write("\27[2J\27[1;1H")
List {
prompt = ("A long prompt that should wrap"):rep(10),
required = true,
items = {
{
value = "Hello",
label = "Hello"
},
{
value = "Bonjour",
label = "Bonjour"
},
{
value = "Ciao",
label = "Ciao"
},
},
}:ask()
Prompt {
prompt = ("A long prompt that should wrap"):rep(10) .. "\n❱ ",
placeholder = "A simple answer",
required = true
}:ask()
Prompt {
prompt = "A simple question\n❱ ",
placeholder = "A simple answer",
}:ask()
|
class("GoBackCommand", pm.SimpleCommand).execute = function (slot0, slot1)
slot2 = slot1:getBody()
slot3 = slot1:getType() or 1
if getProxy(ContextProxy).getContextCount(slot4) > 1 then
slot5 = slot4:popContext()
slot6 = nil
for slot10 = 1, slot3, 1 do
if slot4:getContextCount() > 0 then
slot6 = slot4:popContext()
else
print("could not pop more context")
break
end
end
slot6:extendData(slot2)
slot0:sendNotification(GAME.LOAD_SCENE, {
prevContext = slot5,
context = slot6
})
else
print("no more context in the stack")
end
end
return class("GoBackCommand", pm.SimpleCommand)
|
-- The following tags are used to categorize certain tests in this file:
-- - #v5.1: test applies to Lua versions 5.1 and older.
-- - #v5.2: test applies to Lua versions 5.2 and newer.
-- - #jit: test applies to Lua JIT versions 2.0 and newer.
-- Tagged tests can be skipped via the --exclude-tags argument to busted.
describe('contract module,', function()
insulate('check()/__call()', function()
local contract = require('contract')
--since contract.__call() is an alias for contract.check(), all of the following tests apply for both. To simplify our test code, we will create a local function that calls both of these with the same arguments. Note that this function will not work for the implicit arg lookup tests - those will need to define a different calling function.
local function check(input, ...)
contract.check(input, ...)
contract(input, ...)
end
--testing types against contract with number
it('accepts number args for number contracts', function()
assert.has_no.errors(function() check("n", 1) end)
end)
it('rejects string args for number contracts', function()
assert.has.errors(function() check("n", "") end)
end)
it('rejects bool true for number contracts', function()
assert.has.errors(function() check("n", true) end)
end)
it('rejects table args for number contracts', function()
assert.has.errors(function() check("n", {}) end)
end)
it('rejects function args for number contracts', function()
assert.has.errors(function() check("n", function() end) end)
end)
it('rejects thread args for number contracts', function()
assert.has.errors(function() check("n", coroutine.create(function() end)) end)
end)
it('rejects userdata args for number contracts', function()
pending()
end)
--alternate string representations for number type
it('allows "num" in contract string', function()
assert.has_no.errors(function() check("num", 1) end)
end)
it('allows "number" in contract string', function()
assert.has_no.errors(function() check("number", 1) end)
end)
--testing types against contract with string
it('rejects number args for string contracts', function()
assert.has.errors(function() check("s", 1) end)
end)
it('accepts string args for string contracts', function()
assert.has_no.errors(function() check("s", "") end)
end)
it('rejects bool true for string contracts', function()
assert.has.errors(function() check("s", true) end)
end)
it('rejects table args for string contracts', function()
assert.has.errors(function() check("s", {}) end)
end)
it('rejects function args for string contracts', function()
assert.has.errors(function() check("s", function() end) end)
end)
it('rejects thread args for string contracts', function()
assert.has.errors(function() check("s", coroutine.create(function() end)) end)
end)
it('rejects userdata args for string contracts', function()
pending()
end)
--alternate string representations for string type
it('allows "str" in contract string', function()
assert.has_no.errors(function() check("str", "") end)
end)
it('allows "string" in contract string', function()
assert.has_no.errors(function() check("string", "") end)
end)
--testing types against contract with bool
it('rejects number args for bool contracts', function()
assert.has.errors(function() check("b", 1) end)
end)
it('rejects string args for bool contracts', function()
assert.has.errors(function() check("b", "") end)
end)
it('accepts bool true for bool contracts', function()
assert.has_no.errors(function() check("b", true) end)
end)
it('rejects table args for bool contracts', function()
assert.has.errors(function() check("b", {}) end)
end)
it('rejects function args for bool contracts', function()
assert.has.errors(function() check("b", function() end) end)
end)
it('rejects thread args for bool contracts', function()
assert.has.errors(function() check("b", coroutine.create(function() end)) end)
end)
it('rejects userdata args for bool contracts', function()
pending()
end)
--alternate string representations for bool type
it('allows "bool" in contract string', function()
assert.has_no.errors(function() check("bool", true) end)
end)
it('allows "boolean" in contract string', function()
assert.has_no.errors(function() check("boolean", true) end)
end)
--testing types against contract with table
it('rejects number args for table contracts', function()
assert.has.errors(function() check("t", 1) end)
end)
it('rejects string args for table contracts', function()
assert.has.errors(function() check("t", "") end)
end)
it('rejects bool true for table contracts', function()
assert.has.errors(function() check("t", true) end)
end)
it('accepts table args for table contracts', function()
assert.has_no.errors(function() check("t", {}) end)
end)
it('rejects function args for table contracts', function()
assert.has.errors(function() check("t", function() end) end)
end)
it('rejects thread args for table contracts', function()
assert.has.errors(function() check("t", coroutine.create(function() end)) end)
end)
it('rejects userdata args for table contracts', function()
pending()
end)
--alternate string representations for table type
it('allows "tbl" in contract string', function()
assert.has_no.errors(function() check("tbl", {}) end)
end)
it('allows "table" in contract string', function()
assert.has_no.errors(function() check("table", {}) end)
end)
--testing types against contract with function
it('rejects number args for function contracts', function()
assert.has.errors(function() check("f", 1) end)
end)
it('rejects string args for function contracts', function()
assert.has.errors(function() check("f", "") end)
end)
it('rejects bool true for function contracts', function()
assert.has.errors(function() check("f", true) end)
end)
it('rejects table args for function contracts', function()
assert.has.errors(function() check("f", {}) end)
end)
it('accepts function args for function contracts', function()
assert.has_no.errors(function() check("f", function() end) end)
end)
it('rejects thread args for function contracts', function()
assert.has.errors(function() check("f", coroutine.create(function() end)) end)
end)
it('rejects userdata args for function contracts', function()
pending()
end)
--alternate string representations for function type
it('allows "fnc" in contract string', function()
assert.has_no.errors(function() check("fnc", function() end) end)
end)
it('allows "func" in contract string', function()
assert.has_no.errors(function() check("func", function() end) end)
end)
it('allows "function" in contract string', function()
assert.has_no.errors(function() check("function", function() end) end)
end)
--testing types against contract with thread
it('rejects number args for thread contracts', function()
assert.has.errors(function() check("th", 1) end)
end)
it('rejects string args for thread contracts', function()
assert.has.errors(function() check("th", "") end)
end)
it('rejects bool true for thread contracts', function()
assert.has.errors(function() check("th", true) end)
end)
it('rejects table args for thread contracts', function()
assert.has.errors(function() check("th", {}) end)
end)
it('rejects function args for thread contracts', function()
assert.has.errors(function() check("th", function() end) end)
end)
it('accept thread args for thread contracts', function()
assert.has_no.errors(function() check("th", coroutine.create(function() end)) end)
end)
it('rejects userdata args for thread contracts', function()
pending()
end)
--alternate string representations for thread type
it('allows "thread" in contract string', function()
assert.has_no.errors(function() check("thread", coroutine.create(function() end)) end)
end)
--testing types against contract with userdata
it('rejects number args for userdata contracts', function()
pending()
end)
it('rejects string args for userdata contracts', function()
pending()
end)
it('rejects bool true for userdata contracts', function()
pending()
end)
it('rejects table args for userdata contracts', function()
pending()
end)
it('rejects function args for userdata contracts', function()
pending()
end)
it('rejects thread args for userdata contracts', function()
pending()
end)
it('accepts userdata args for userdata contracts', function()
pending()
end)
--alternate string representations for userdata type
it('allows "usr" in contract string', function()
pending()
end)
it('allows "user" in contract string', function()
pending()
end)
it('allows "userdata" in contract string', function()
pending()
end)
--testing types against contract with "any"
it('accepts number args for "any" contracts', function()
assert.has_no.errors(function() contract('a', 1) end)
end)
it('accepts string args for "any" contracts', function()
assert.has_no.errors(function() check("a", "") end)
end)
it('accepts bool true for "any" contracts', function()
assert.has_no.errors(function() check("a", true) end)
end)
it('accepts table args for "any" contracts', function()
assert.has_no.errors(function() check("a", {}) end)
end)
it('accepts function args for "any" contracts', function()
assert.has_no.errors(function() check("a", function() end) end)
end)
it('accepts thread args for "any" contracts', function()
assert.has_no.errors(function() check("a", coroutine.create(function() end)) end)
end)
it('accepts userdata args for "any" contracts', function()
pending()
end)
--alternate string representations for "any" type
it('allows "any" in contract string', function()
assert.has_no.errors(function() contract('any', 1) end)
end)
--handling required args
it('accepts a matching required arg', function()
assert.has_no.errors(function() check('rn', 1) end)
end)
it('rejects a non-matching required arg', function()
assert.has.errors(function() check('rn', 'one') end)
end)
it('accepts multiple matching required args', function()
assert.has_no.errors(function() check('rn,rs', 1, "two") end)
end)
it('rejects a missing required arg', function()
assert.has.errors(function() check('rn,rs', 1) end)
end)
it('rejects an explicit nil for a required arg', function()
assert.has.errors(function() check('rn', nil) end)
end)
--handling empty contracts
it('accepts an empty string contract', function()
assert.has_no.errors(function() check('', nil) end)
end)
it('accepts an empty string contract and no args', function()
assert.has_no.errors(function() check('') end)
end)
it('accepts an explicit nil for contract', function()
assert.has_no.errors(function() check(nil, nil) end)
end)
it('accepts an explicit nil contract and no args', function()
assert.has_no.errors(function() check(nil) end)
end)
it('accepts nothing for contract', function()
assert.has_no.errors(function() check() end)
end)
it('accepts additional args beyond those in the contract', function()
assert.has_no.errors(function() check('rn', 1, 'two', 3) end)
end)
--handling optional args
it('accepts a missing optional arg', function()
assert.has_no.errors(function() check('rn,n', 1) end)
end)
it('accepts a matching optional arg', function()
assert.has_no.errors(function() check('n', 1) end)
end)
it('accepts an explicit nil for an optional arg', function()
assert.has_no.errors(function() check('n', nil) end)
end)
it('rejects a non-matching optional arg', function()
assert.has.errors(function() check('n', 'one') end)
end)
it('handles explicit nils between other args', function()
assert.has_no.errors(function() check('n,n,n', 1, nil, 3) end)
end)
it('handles explicit nils between required args', function()
assert.has_no.errors(function() check('rn,n,rn', 1, nil, 3) end)
end)
--implicit arg lookup
it('accepts correct args looked up implicitly from the calling function', function()
assert.has_no.errors(function()
local f = function(a,b)
contract.check('rn,rs')
contract('rn,rs')
end
f(1, 'two')
end)
end)
it('rejects incorrect args looked up implicitly from the calling function', function()
assert.has.errors(function()
local f = function(a,b)
contract.check('rn,rs')
contract('rn,rs')
end
f(1, 2)
end)
end)
it('errors when trying to lookup an arg named "arg" implicitly from the calling function', function()
assert.has.errors(function()
local f = function(arg)
contract.check('n')
contract('n')
end
f(1)
end)
end)
--handling varargs
it('accepts matching varargs passed explicitly', function()
assert.has_no.errors(function()
local f = function(...)
contract.check('n,n', ...)
contract('n,n', ...)
end
f(1, 2)
end)
end)
it('rejects non-matching varargs passed explicitly', function()
assert.has.errors(function()
local f = function(...)
contract.check('n,n', ...)
contract('n,n', ...)
end
f('one', 'two')
end)
end)
it('accepts explicit nils for optional varargs when passed explicitly', function()
assert.has_no.errors(function()
local f = function(...)
contract.check('n', ...)
contract('n', ...)
end
f(nil)
end)
end)
it('accepts missing varargs with at least one passed explicitly', function()
assert.has_no.errors(function()
local f = function(...)
contract.check('rn,n', ...)
contract('rn,n', ...)
end
f(1)
end)
end)
it('errors when trying to lookup varargs implicitly from the calling function #v5.1', function()
assert.has.errors(function()
local f = function(...)
contract.check('rn,rs')
contract('rn,rs')
end
f(1, 'two')
end)
end)
it('accepts varargs looked up implicitly from the calling function #v5.2 #jit', function()
assert.has_no.errors(function()
local f = function(...)
contract.check('rn,rs')
contract('rn,rs')
end
f(1, 'two')
end)
end)
it('accepts missing varargs for optional args when looked up implicitly from the calling function #v5.2 #jit', function()
assert.has_no.errors(function()
local f = function(...)
contract.check('n')
contract('n')
end
f()
end)
end)
it('errors if passing no args #v5.1', function()
assert.has.errors(function()
local f = function()
contract.check('n')
contract('n')
end
f()
end)
end)
it('accepts no args for contract with only optional arg rules #v5.2 #jit', function()
assert.has_no.errors(function()
local f = function()
contract.check('n')
contract('n')
end
f()
end)
end)
--handling multi-type rules in contracts
it('accepts args that match either of the types in a required multi-type rule', function()
assert.has_no.errors(function() check('rn|s,rn|s', 1, 'two') end)
end)
it('rejects args that match none of the types in a required multi-type rule', function()
assert.has.errors(function() check('rn|s', true) end)
end)
it('accepts args that match either of the types in an optional multi-type rule', function()
assert.has_no.errors(function() check('n|s,n|s', 1, 'two') end)
end)
it('rejects args that match none of the types in an optional multi-type rule', function()
assert.has.errors(function() check('n|s', true) end)
end)
it('contracts are not case-sensitive', function()
assert.has_no.errors(function() check('rn,rN,Rn,RN', 1, 2, 3, 4) end)
end)
--handling whitespace
it('ignores leading whitespace in contract', function()
assert.has_no.errors(function() check('\n\r\t rn', 1) end)
end)
it('ignores trailing whitespace in contract', function()
assert.has_no.errors(function() check('rn \n\r\t', 1) end)
end)
it('ignores whitespace between characters in contract', function()
assert.has_no.errors(function() check('r \n\r\t n', 1) end)
end)
it('raises error for invalid characters in a contract', function()
assert.has.errors(function() check('rxxxxxn', 1) end)
end)
it('raises error for invalid characters following a valid contract string', function()
assert.has.errors(function() check('nxxxxx', 1) end)
end)
it('passes successive calls for same contract and same args', function()
assert.has_no.errors(function()
check('rn', 1)
check('rn', 1)
end)
end)
end)
insulate('off()', function()
local contract = require('contract')
it('disables contract checking', function()
contract.off()
assert.has_no.errors(function() contract('rn', 'one') end)
end)
end)
insulate('on()', function()
local contract = require('contract')
it('enables contract checking', function()
contract.on()
assert.has_no.errors(function() contract('rn', 1) end)
assert.has.errors(function() contract('rn', 'one') end)
end)
end)
insulate('isOn()', function()
local contract = require('contract')
it('returns true when module is enabled', function()
contract.on()
assert.is.equal(true, contract.isOn())
end)
it('returns false when module is disabled', function()
contract.off()
assert.is.equal(false, contract.isOn())
end)
end)
insulate('toggle()', function()
local contract = require('contract')
it('switches module from off to on', function()
contract.off()
contract.toggle()
assert.is.equal(true, contract.isOn())
end)
it('switches module from on to off', function()
contract.on()
contract.toggle()
assert.is.equal(false, contract.isOn())
end)
end)
insulate('clearCache()', function()
local contract = require('contract')
it('runs without error', function()
assert.has_no.errors(function() contract.clearCache() end)
end)
end)
end) |
-- ======= Copyright (c) 2003-2011, Unknown Worlds Entertainment, Inc. All rights reserved. =======
--
-- lua\MapEntityLoader.lua
--
-- Created by: Brian Cronin ([email protected])
--
-- ========= For more information, visit us at http://www.unknownworlds.com =====================
local function hue2rgb(p, q, t)
if t < 0 then t = t + 1 end
if t > 1 then t = t - 1 end
if t < 1/6 then return p + (q - p) * 6 * t end
if t < 1/2 then return q end
if t < 2/3 then return p + (q - p) * (2/3 - t) * 6 end
return p
end
local function rgb_to_hsl(r, g, b)
--r, g, b = r/255, g/255, b/255
local min = math.min(r, g, b)
local max = math.max(r, g, b)
local delta = max - min
local h, s, l = 0, 0, ((min+max)/2)
if l > 0 and l < 0.5 then s = delta/(max+min) end
if l >= 0.5 and l < 1 then s = delta/(2-max-min) end
if delta > 0 then
if max == r and max ~= g then h = h + (g-b)/delta end
if max == g and max ~= b then h = h + 2 + (b-r)/delta end
if max == b and max ~= r then h = h + 4 + (r-g)/delta end
h = h / 6;
end
if h < 0 then h = h + 1 end
if h > 1 then h = h - 1 end
return h * 360, s, l
end
local function _h2rgb(m1, m2, h)
if h<0 then h = h+1 end
if h>1 then h = h-1 end
if h*6<1 then
return m1+(m2-m1)*h*6
elseif h*2<1 then
return m2
elseif h*3<2 then
return m1+(m2-m1)*(2/3-h)*6
else
return m1
end
end
local function hsl_to_rgb(h, s, L)
h = h/360
local m1, m2
if L<=0.5 then
m2 = L*(s+1)
else
m2 = L+s-L*s
end
m1 = L*2-m2
return _h2rgb(m1, m2, h+1/3), _h2rgb(m1, m2, h), _h2rgb(m1, m2, h-1/3)
end
local function _col_amp(color)
if not color then
return
end
local r = color.r
local g = color.g
local b = color.b
-- lower how green everyhing will be
g = math.pow(g , 1.05)
local h, s, l = rgb_to_hsl(r, g, b)
if s > 1.0 then
Print("saturation out of range, undefined behaviour: %s", s)
s = 1.0
end
-- bring luminosity closer to center, since we can increase intensity. l=0.5 is strongest
--local old_l = l
--l = Clamp(0.5 * math.pow(2.0 * l, 3.0) + 0.5, 0, 1)
--l = Clamp(((0.5 * math.pow(2.0 * l - 1, 3.0) + 0.4) + l) / 2.0, 0, 1)
--Print("%s vs %s", old_l, l)
-- increase saturation
if (s > 0) then
s = Clamp(math.pow(s, 0.95), 0,1.0)
end
-- convert back to rgb
r, g, b = hsl_to_rgb(h, s, l)
return Color(r, g, b, color.a)
end
local function _col_reduce(color)
if not color then
return
end
local r = color.r
local g = color.g
local b = color.b
-- lower how green everyhing will be
g = math.pow(g , 1.05)
local h, s, l = rgb_to_hsl(r, g, b)
if s > 1.0 then
Print("saturation out of range, undefined behaviour: %s", s)
s = 1.0
end
-- bring luminosity closer to center, since we can increase intensity. l=0.5 is strongest
--local old_l = l
--l = Clamp(0.5 * math.pow(2.0 * l, 3.0) + 0.5, 0, 1)
--l = Clamp(((0.5 * math.pow(2.0 * l - 1, 3.0) + 0.4) + l) / 2.0, 0, 1)
--Print("%s vs %s", old_l, l)
-- decrease saturation
if (s > 0) then
s = Clamp(math.pow(s, 2.0), 0,1.0)
end
-- convert back to rgb
r, g, b = hsl_to_rgb(h, s, l)
return Color(r, g, b, color.a)
end
local function ClientOnly()
return Client ~= nil
end
local function ServerOnly()
return Server ~= nil
end
local function ClientAndServerAndPredict()
return Client or Server or Predict
end
function LoadEntityFromValues(entity, values, initOnly)
entity:SetOrigin(values.origin)
entity:SetAngles(values.angles)
-- Copy all of the key values as fields on the entity.
for key, value in pairs(values) do
if key ~= "origin" and key ~= "angles" then
entity[key] = value
end
end
if not initOnly then
if entity.OnLoad then
entity:OnLoad()
end
end
if entity.OnInitialized then
entity:OnInitialized()
end
end
local function LoadLight(className, groupName, values)
if not values.modified then
values.modified = true
--[[
-- boost the saturation
if values.color_dir_right then
values.color_dir_right = _col_amp(values.color_dir_right )
values.color_dir_left = _col_amp(values.color_dir_left )
values.color_dir_up = _col_amp(values.color_dir_up )
values.color_dir_down = _col_amp(values.color_dir_down )
values.color_dir_forward = _col_amp(values.color_dir_forward )
values.color_dir_backward = _col_amp(values.color_dir_backward)
end
if values.color then
values.color = _col_amp(values.color )
end
--]]
-- boost ambient light intensity if low
if not values.color_dir_right and values.intensity and values.intensity > 0 then
-- disabled because we now have a shader doing something similar
--[[
local i = values.intensity
local ideal = 5.0
i = i / ideal
if i > 1.0 then
i = i + 1 / i
else
i = 2 * - math.pow(i - 1, 2) + 2
end
values.intensity = i * ideal
--]]
if values.color then
if className == "light_spot" then
values.color = _col_reduce(values.color)
else
values.color = _col_amp(values.color)
end
end
end
-- widen all the lights if we can, since they are all so bloody narrow
-- nevermind, maps suck and have no light bleed protection
if values.outerAngle then
--values.outerAngle = values.outerAngle * 1.2
end
end
if Client.lightList == nil then
Client.lightList = { }
end
if Client.lowLightList == nil then
Client.lowLightList = { }
end
if Client.originalLights == nil then
Client.originalLights = { }
end
if Client.fullyLoaded == nil then --Game hasnt loaded yet, so build light data tables.
if groupName == "Low Lights" then
table.insert(Client.lowLightList, {className = className, groupName = groupName, values = values})
else
table.insert(Client.originalLights, {className = className, groupName = groupName, values = values})
end
else
local renderLight = Client.CreateRenderLight()
local coords = values.angles:GetCoords(values.origin)
if values.specular == nil then
values.specular = true
end
if className == "light_spot" then
renderLight:SetType(RenderLight.Type_Spot)
renderLight:SetOuterCone(values.outerAngle)
renderLight:SetInnerCone(values.innerAngle)
renderLight:SetCastsShadows(values.casts_shadows)
renderLight:SetSpecular(values.specular)
if values.gobo_texture ~= nil then
renderLight:SetGoboTexture(values.gobo_texture)
end
if values.shadow_fade_rate ~= nil then
renderLight:SetShadowFadeRate(values.shadow_fade_rate)
end
elseif className == "light_point" then
renderLight:SetType(RenderLight.Type_Point)
renderLight:SetCastsShadows(values.casts_shadows)
renderLight:SetSpecular(values.specular)
if values.shadow_fade_rate ~= nil then
renderLight:SetShadowFadeRate(values.shadow_fade_rate)
end
elseif className == "light_ambient" then
renderLight:SetType(RenderLight.Type_AmbientVolume)
renderLight:SetDirectionalColor(RenderLight.Direction_Right, (values.color_dir_right))
renderLight:SetDirectionalColor(RenderLight.Direction_Left, (values.color_dir_left))
renderLight:SetDirectionalColor(RenderLight.Direction_Up, (values.color_dir_up))
renderLight:SetDirectionalColor(RenderLight.Direction_Down, (values.color_dir_down))
renderLight:SetDirectionalColor(RenderLight.Direction_Forward, (values.color_dir_forward))
renderLight:SetDirectionalColor(RenderLight.Direction_Backward, (values.color_dir_backward))
end
renderLight:SetCoords(coords)
renderLight:SetRadius(values.distance)
renderLight:SetIntensity(values.intensity)
renderLight:SetColor(values.color)
renderLight:SetGroup(groupName)
renderLight.ignorePowergrid = values.ignorePowergrid
local atmosphericDensity = tonumber(values.atmospheric_density)
-- Backwards compatibility
if values.atmospheric then
atmosphericDensity = 1.0
end
if atmosphericDensity ~= nil then
local atmoModifier = Client.GetOptionFloat("graphics/atmospheric-density", 1.0)
renderLight:SetAtmosphericDensity( atmosphericDensity * atmoModifier )
end
-- Save original values so we can alter and restore lights
renderLight.originalIntensity = values.intensity
renderLight.originalColor = values.color
renderLight.originalCoords = Coords(coords)
-- added by creepier atmos
renderLight.originalRadius = values.distance
renderLight.originalSpecular = values.specular
renderLight.originalAtmosphericDensity = atmosphericDensity
if (className == "light_ambient") then
renderLight.originalRight = values.color_dir_right
renderLight.originalLeft = values.color_dir_left
renderLight.originalUp = values.color_dir_up
renderLight.originalDown = values.color_dir_down
renderLight.originalForward = values.color_dir_forward
renderLight.originalBackward = values.color_dir_backward
end
renderLight.className = className
renderLight.groupName = groupName
renderLight.values = values
table.insert(Client.lightList, renderLight)
return true
end
end
local function LoadBillboard(className, groupName, values)
local renderBillboard = Client.CreateRenderBillboard()
renderBillboard:SetOrigin(values.origin)
renderBillboard:SetGroup(groupName)
renderBillboard:SetMaterial(values.material)
renderBillboard:SetSize(values.size)
if Client.billboardList == nil then
Client.billboardList = { }
end
table.insert(Client.billboardList, renderBillboard)
return true
end
local function LoadDecal(className, groupName, values)
local renderDecal = Client.CreateRenderDecal()
if values.material == "" then
Shared.Message(string.format("Warning: Missing or invalid decal at: %s!", ToString(values.origin)))
return
end
local coords = values.angles:GetCoords(values.origin)
renderDecal:SetCoords(coords)
--renderDecal:SetGroup(groupName)
renderDecal:SetMaterial(values.material)
renderDecal:SetExtents(values.extents)
if Client.decalList == nil then
Client.decalList = { }
end
table.insert(Client.decalList, renderDecal)
return true
end
local lightProps = set {
"models/props/eclipse/eclipse_main_area_a_light.model",
"models/props/eclipse/eclipse_gate_area_screen.model",
"models/props/eclipse/eclipse_hallway_03_corner_up.model",
"models/props/eclipse/eclipse_hallway_02_corner_up.model",
"models/props/eclipse/eclipse_hallway_01_corner_up.model",
"models/props/eclipse/eclipse_ceilingmods_D_05_lamp.model",
"models/props/eclipse/eclipse_ceilingmods_d_05_lamp.model",
"models/props/eclipse/eclipse_ceilingmods01_03_lamp.model",
"models/props/eclipse/eclipse_hallway_04_lamp.model",
"models/props/eclipse/eclipse_details01_04.model",
"models/props/eclipse/eclipse_modular_section_n_02.model",
"models/props/descent/descent_energytower_ring.model",
"models/props/descent/descent_ceilinglight_01.model",
"models/props/descent/descent_hallway_01_light.model",
"models/props/descent/descent_doorway_01_var.model",
"models/props/descent/descent_doorway_02_open.model",
"models/props/descent/descent_doorway_03_double_closed.model",
"models/props/descent/descent_doorway_03_double_open.model",
"models/props/descent/descent_ceilingpanels_02_tile2.model",
"models/props/descent/descent_energyflow_ring_01.model",
"models/props/descent/descent_lightpanels_01a.model",
"models/props/descent/descent_lightpanels_01b.model",
"models/props/descent/descent_hallway_01_light.model",
"models/props/descent/descent_tram_ceiling_light_01.model",
"models/props/descent/descent_pillar_04.model",
"models/props/descent/descent_doorway_01.model",
"models/props/descent/descent_ribwalls_01_str1.model",
"models/props/descent/descent_ribwalls_01_str2.model",
"models/props/descent/descent_ribwalls_01_str3.model",
"models/props/descent/descent_ribwalls_01_str4.model",
"models/props/descent/descent_ribwalls_01_str5.model",
"models/props/descent/descent_ribwalls_01_crn_in.model",
"models/props/descent/descent_ribwalls_01_crn_out.model",
"models/props/discovery/discovery_light_01.model",
"models/props/refinery/refinery_small_light_01.model",
"models/props/refinery/refinery_elevator1_platform.model",
"models/props/refinery/mining_light_01.model",
"models/props/refinery/mining_light_02.model",
"models/props/refinery/refinery_floodlight_01.model",
"models/props/refinery/docking_clerical_light.model",
"models/props/summit/summit_container_01_top.model",
"models/props/veil/veil_archwall.model",
"models/props/biodome/biodome_pillar_04_pillar1.model"
}
local function LoadStaticProp(className, groupName, values)
if values.model == "" or values.model == nil then
Shared.Message(string.format("Warning: Missing or invalid prop at: %s!", ToString(values.origin)))
return
end
local physicsModel
local coords = values.angles:GetCoords(values.origin)
coords.xAxis = coords.xAxis * values.scale.x
coords.yAxis = coords.yAxis * values.scale.y
coords.zAxis = coords.zAxis * values.scale.z
local renderModelCommAlpha = GetAndCheckValue(values.commAlpha, 0, 1, "commAlpha", 1, true)
local blocksPlacement = groupName == kCommanderInvisibleGroupName or
groupName == kCommanderInvisibleVentsGroupName or
groupName == kCommanderNoBuildGroupName or
( gSeasonalCommanderInvisibleGroupName and groupName == gSeasonalCommanderInvisibleGroupName )
-- Test against false so that the default is true
if values.collidable ~= false then
-- Create the physical representation of the prop.
physicsModel = Shared.CreatePhysicsModel(values.model, false, coords, nil)
physicsModel:SetPhysicsType(CollisionObject.Static)
-- Make it not block selection and structure placement (GetCommanderPickTarget)
if renderModelCommAlpha < 1 or blocksPlacement then
physicsModel:SetGroup(PhysicsGroup.CommanderPropsGroup)
end
-- NOTE that CollisionGeometryGroup is also filtered by commander alpha stuff
if string.find(values.model, "models/props/tram/tram_railing") or
string.find(values.model, "models/props/refining/refining_railing") or
string.find(values.model, "models/props/refinery/mining_rails") then
physicsModel:SetGroup(PhysicsGroup.CollisionGeometryGroup)
end
end
-- Only create Pathing objects if we are told too
if values.pathInclude and not Pathing.GetLevelHasPathingMesh() then
Pathing.CreatePathingObject(values.model, coords, values.pathWalkable or false)
end
if Client then
-- Create the visual representation of the prop.
-- All static props can be instanced.
local renderModel = Client.CreateRenderModel(RenderScene.Zone_Default)
renderModel:SetModel(values.model)
if values.castsShadows ~= nil then
renderModel:SetCastsShadows(values.castsShadows)
end
renderModel:SetCoords(coords)
renderModel:SetGroup(groupName)
renderModel.commAlpha = renderModelCommAlpha
renderModel.model = values.model
table.insert(Client.propList, {renderModel, physicsModel})
if string.find(values.model, "models/props/generic/lights/") or
string.find(values.model, "models/props/biodome/biodome_lights") or
string.find(values.model, "models/props/descent/descent_wallmods") or
string.find(values.model, "models/props/eclipse/eclipse_wallmod") or
lightProps[values.model] then
renderModel:InstanceMaterials()
renderModel:SetMaterialParameter("emissiveMod", 1)
renderModel:SetIsStatic(true)
renderModel:SetIsInstanced(true)
if not Client.lightPropList then
Client.lightPropList = { }
end
table.insert(Client.lightPropList, renderModel)
else
renderModel:SetIsStatic(true)
renderModel:SetIsInstanced(true)
end
end
return true
end
local function LoadSoundEffect(className, groupName, values)
local soundEffect = Server.CreateEntity(className)
Log("Loading "..className)
if soundEffect then
soundEffect:SetMapEntity()
soundEffect:SetOrigin(values.origin)
soundEffect:SetAngles(values.angles)
Shared.PrecacheSound(values.eventName)
soundEffect:SetAsset(values.eventName)
-- make maps way quieter
soundEffect:SetVolume(0.1)
if values.listenChannel then
soundEffect:SetListenChannel(values.listenChannel)
end
if values.startsOnMessage and string.len(values.startsOnMessage) > 0 then
soundEffect:RegisterSignalListener(function() soundEffect:Start() end, values.startsOnMessage)
end
return true
end
return false
end
local function LoadReflectionProbe(className, groupName, values)
local renderReflectionProbe = Client.CreateRenderReflectionProbe()
if values.strength == nil then
values.strength = 1
end
renderReflectionProbe:SetOrigin(values.origin)
renderReflectionProbe:SetGroup(groupName)
renderReflectionProbe:SetRadius(values.distance)
renderReflectionProbe:SetStrength(values.strength)
if Client.reflectionProbeList == nil then
Client.reflectionProbeList = { }
end
renderReflectionProbe.className = className
renderReflectionProbe.groupName = groupName
renderReflectionProbe.values = values
table.insert(Client.reflectionProbeList, renderReflectionProbe)
if values.__editorData ~= nil then
cubemap = values.__editorData.reflection_probe_cubemap
end
if cubemap ~= nil and cubemap:GetSize() > 0 then
renderReflectionProbe:SetCubeMapRaw( values.__editorData.reflection_probe_cubemap )
end
return true
end
local loadTypes = { }
loadTypes["light_spot"] = { LoadAllowed = ClientOnly, LoadFunction = LoadLight }
loadTypes["light_point"] = { LoadAllowed = ClientOnly, LoadFunction = LoadLight }
loadTypes["light_ambient"] = { LoadAllowed = ClientOnly, LoadFunction = LoadLight }
loadTypes["prop_static"] = { LoadAllowed = ClientAndServerAndPredict, LoadFunction = LoadStaticProp }
loadTypes["sound_effect"] = { LoadAllowed = ServerOnly, LoadFunction = LoadSoundEffect }
loadTypes["billboard"] = { LoadAllowed = ClientOnly, LoadFunction = LoadBillboard }
loadTypes["decal"] = { LoadAllowed = ClientOnly, LoadFunction = LoadDecal }
loadTypes["reflection_probe"] = { LoadAllowed = ClientOnly, LoadFunction = LoadReflectionProbe }
--
-- This will load common map entities for the Client, Server, or both.
-- Call LoadMapEntity() with the map name of the entity and the map values
-- and it will be loaded. Returns true on success.
--
function LoadMapEntity(className, groupName, values)
local loadData = loadTypes[className]
if loadData and loadData.LoadAllowed() and IsGroupActiveInSeason(groupName, GetSeason()) then
return loadData.LoadFunction(className, groupName, values)
end
return false
end |
includeFile("custom_content/tangible/content/eow/final_data_disk.lua")
includeFile("custom_content/tangible/content/eow/final_data_disk_rebel.lua")
|
local Renderer = dtrequire("systems.render.Renderer")
local PhysicsComponent = dtrequire("components.Physics")
local PhysicsOverlayRenderer = Renderer:subtype("droptune.editor.PhysicsOverlayRenderer")
do
PhysicsOverlayRenderer.filter = PhysicsComponent.filter
function PhysicsOverlayRenderer:init()
self.drawBoundingBoxes = true
self.drawColliders = true
self.drawTransforms = true
end
function PhysicsOverlayRenderer:draw(pipeline)
local drawBoundingBoxes = self.drawBoundingBoxes
local drawColliders = self.drawColliders
local drawTransforms = self.drawTransforms
local scaledLineWidth = 1 / pipeline.camera:getScale()
pipeline:transformed(function(l, t, w, h)
for _, e in ipairs(self.entities) do
local body = e[PhysicsComponent].body
local fixtures = body:getFixtures()
if drawBoundingBoxes then
for _, fixture in ipairs(fixtures) do
love.graphics.setColor(1, 1, 0)
love.graphics.setLineWidth(scaledLineWidth)
for i = 1, fixture:getShape():getChildCount() do
local l, t, r, b = fixture:getLocalBoundingBox(i)
love.graphics.rectangle("line", l, t, r-l, b-t)
end
end
end
love.graphics.push()
love.graphics.translate(body:getWorldCenter())
love.graphics.rotate(body:getAngle())
if drawTransforms then
love.graphics.setColor(1, 0, 0)
love.graphics.push()
love.graphics.setLineWidth(1)
love.graphics.scale(1 / pipeline.camera:getScale())
local size = 16
love.graphics.line(0, size, 0, 0, size, 0)
love.graphics.line(-size * 0.125, size * 0.75, 0, size, size * 0.125, size * 0.75)
love.graphics.pop()
end
local cx, cy = body:getLocalCenter()
love.graphics.translate(-cx, -cy)
for _, fixture in ipairs(fixtures) do
local shape = fixture:getShape()
if drawColliders then
love.graphics.setColor(1, 0, 0)
love.graphics.setLineWidth(scaledLineWidth)
local shapetype = shape:getType()
if shapetype == "circle" then
local x, y = shape:getPoint()
local r = shape:getRadius()
love.graphics.circle("line", x, y, r)
elseif shapetype == "polygon" then
love.graphics.polygon("line", shape:getPoints())
elseif shapetype == "chain" or shapetype == "edge" then
love.graphics.line(shape:getPoints())
end
end
end
love.graphics.pop()
end
end)
end
end
return PhysicsOverlayRenderer |
local skynet = require("skynet")
local sharedata = require "skynet.sharedata"
local json = require("cjson")
local codecache = require "skynet.codecache"
local TAG = "ConfigServer"
local ConfigServer = {}
function ConfigServer:init(pGameCode)
-- Log.d(TAG, "11111111111111121212121")
self.m_pGoldRoomConfigTable = {}
-- 配置
self.m_pAnnouncementConfig = nil
self.m_pShareActivityConfig = nil
self.m_pAuditConfig = nil
self.m_redisClientsMgr = require("utils/redisClientsMgr")
self.m_redisClientsMgr:init()
self.m_pServerConfig = require(onGetServerConfigFile(pGameCode))
self.m_pHallServiceMgr = skynet.localname(".HallServiceMgr")
-- self.m_pGameConfigFilePath = self.m_pServerConfig.iOtherConfigPath
-- 初始化userInfoRedis
self.m_redisClientsMgr:addRedisClient(DefineType.REDIS_ACTIVITY, self.m_pServerConfig.iGameIpPortConfig.iActivityRedisConfig)
-- 启动定时器查看配置
self.m_pScheduleMgr = require("utils/schedulerMgr")
self.m_pScheduleMgr:init()
local pCallback = self.onRefreshConfig
self.m_pGetAnnouncementTimer = self.m_pScheduleMgr:register(pCallback, 30 * 60 * 1000, -1, 10 * 1000, self)
self:onRefreshConfig()
end
function ConfigServer:onUpdatePlaytypeConfig(pPlaytypeConfig)
-- 去掉一部分的数据
pPlaytypeConfig.iGameRoundPath = nil
pPlaytypeConfig.iGameRulePath = nil
pPlaytypeConfig.iGameUserCardMap = nil
self.m_pPlaytypeConfig = pPlaytypeConfig
end
function ConfigServer:onRefreshConfig()
local pOtherConfigFile = self.m_pServerConfig.iOtherConfigPath
-- Log.dump(TAG, self.m_pServerConfig, "self.m_pServerConfig")
Log.d(TAG, "pOtherConfigFile = [%s]", pOtherConfigFile)
package.loaded[pOtherConfigFile] = nil
codecache.clear()
self.m_pOtherConfig = require(pOtherConfigFile)
Log.dump(TAG, self.m_pOtherConfig, "self.m_pOtherConfig")
end
------------------- socket --------------------
function ConfigServer:ClientUserGetConfig(pAgent, reqest)
-- Log.dump(TAG, reqest, "reqest")
if reqest.iConfigName and reqest.iParamData and self[reqest.iConfigName] then
return self[reqest.iConfigName](self, reqest.iConfigName, pAgent, reqest.iParamData)
end
end
function ConfigServer:GetFriendRoomConfig(pConfigname, pAgent, data)
data = data and json.decode(data) or {}
if not data or not data.iGameCode then
return
end
if self.m_pPlaytypeConfig then
local name = "ServerUserGetConfig"
local info = {}
info.iConfigName = pConfigname
info.iConfigData = json.encode(self.m_pPlaytypeConfig)
skynet.call(self.m_pHallServiceMgr, "lua", "onSendPackage", pAgent, name, info)
end
end
function ConfigServer:SetShareActivityData(pConfigname, pAgent, data)
data = data and json.decode(data) or {}
if not data or not data.iGameCode or not data.iUserId then
return
end
if not self.m_pOtherConfig or not self.m_pOtherConfig.iShareConfig then
return
end
Log.dump(TAG, self.m_pOtherConfig.iShareConfig, "self.m_pOtherConfig.iShareConfig")
local pOneDayReward = self.m_pOtherConfig.iShareConfig.iOneDayReward or 1
local pUserId = data.iUserId
local pKey = string.format("Share_Count_UserId_%d", pUserId)
local pRet = self:onExecuteRedisCmd(DefineType.REDIS_ACTIVITY, "HMGET", pKey, "continue", "getCount", "isFirst", "lastTime")
local pDataTime = onGetNowDataLastTime(os.date("*t", os.time()))
if isTable(pRet) then
-- 如果不是连续的
pRet[1] = tonumber(pRet[1]) and tonumber(pRet[1]) + 1 or 1
pRet[2] = tonumber(pRet[2]) and tonumber(pRet[2]) + pOneDayReward or pOneDayReward
if pRet[4] then
local pOldDate = os.date("%x", tonumber(pRet[4]))
local pNewDate = os.date("%x", os.time())
-- 计算上次签到的最后时间
if pOldDate == pNewDate then
local pMsg = "您今天已经分享领过奖励了,本次分享没有钻石奖励。"
self:onServerUserShowHints(pUserId, 0 , pMsg)
return
else
-- 如果不是连续天
if os.time() - tonumber(pRet[4]) > 24 * 60 * 60 then
pRet[1] = 1
pRet[2] = pOneDayReward
end
end
end
local pData = {}
pData.iUserId = pUserId
pData.RoomCardNum = pOneDayReward
local pTable = not pRet[3] and self.m_pOtherConfig.iShareConfig.iFirstConfig or self.m_pOtherConfig.iShareConfig.iNormalConfig
if pRet[1] >= 5 then
pRet[1] = 0
pRet[3] = 1
pRet[2] = 0
pData.RoomCardNum = pData.RoomCardNum + pTable.iRewardTable.RoomCardNum
local pRet = self:onExecuteRedisCmd(DefineType.REDIS_ACTIVITY, "HMSET", pKey, "isFirst", pRet[3])
end
local pRet = self:onExecuteRedisCmd(DefineType.REDIS_ACTIVITY, "HMSET", pKey, "continue", pRet[1], "getCount", pRet[2], "lastTime", pDataTime)
self:onDealShareRewardTable(pAgent, pConfigname, pData)
end
end
function ConfigServer:onServerUserShowHints(pUserId, pType, pMsg)
local pAgent = skynet.call(self.m_pHallServiceMgr, "lua", "onGetAgentByUserId", pUserId)
if not pAgent then return end
local name = "ServerUserShowHints"
local info = {}
info.iShowType = pType
info.iShowMsg = pMsg
skynet.call(self.m_pHallServiceMgr, "lua", "onSendPackage", pAgent, name, info)
end
function ConfigServer:onDealShareRewardTable(pAgent, pConfigname, data)
if not data or not data.iUserId then return end
if data.RoomCardNum then
local info = {
iUserId = data.iUserId,
iRoomCardNum = data.RoomCardNum,
}
local pHallServer = skynet.call(self.m_pHallServiceMgr, "lua", "onGetHallServerByUserId", info.iUserId)
if pHallServer then
local pRet = skynet.call(pHallServer, "lua", "onUpdateUserRoomCard", info)
end
self:onSendConfigData(pAgent, pConfigname, data)
end
end
function ConfigServer:GetShareActivityConfig(pConfigname, pAgent, data)
data = data and json.decode(data) or {}
if not data or not data.iGameCode or not data.iUserId then
return
end
if not self.m_pOtherConfig or not self.m_pOtherConfig.iShareConfig then
return
end
local pUserId = data.iUserId
-- 加上自己的信息
local pKey = string.format("Share_Count_UserId_%d", pUserId)
local pRet = self:onExecuteRedisCmd(DefineType.REDIS_ACTIVITY, "HMGET", pKey, "continue", "getCount", "isFirst", "lastTime")
if isTable(pRet) and pRet[3] then
self.m_pOtherConfig.iShareConfig.iNormalConfig.iContinueNum = tonumber(pRet[1]) or 0
self.m_pOtherConfig.iShareConfig.iNormalConfig.iGetCount = tonumber(pRet[2]) or 0
self.m_pOtherConfig.iShareConfig.iNormalConfig.iIsFirst = 0
self.m_pOtherConfig.iShareConfig.iNormalConfig.iTodayReward = 0
if pRet[4] then
local pOldDate = os.date("%x", tonumber(pRet[4]))
local pNewDate = os.date("%x", os.time())
-- 计算上次签到的最后时间
if pOldDate == pNewDate then
self.m_pOtherConfig.iShareConfig.iNormalConfig.iTodayReward = 1
else
-- 如果不是连续天
if os.time() - tonumber(pRet[4]) > 24 * 60 * 60 then
self.m_pOtherConfig.iShareConfig.iNormalConfig.iContinueNum = 0
self.m_pOtherConfig.iShareConfig.iNormalConfig.iGetCount = 0
local pRet = self:onExecuteRedisCmd(DefineType.REDIS_ACTIVITY, "HMSET", pKey, "continue", 0, "getCount", 0)
end
end
end
self:onSendConfigData(pAgent, pConfigname, self.m_pOtherConfig.iShareConfig.iNormalConfig)
elseif isTable(pRet) then
self.m_pOtherConfig.iShareConfig.iFirstConfig.iContinueNum = pRet[1] or 0
self.m_pOtherConfig.iShareConfig.iFirstConfig.iGetCount = pRet[2] or 0
self.m_pOtherConfig.iShareConfig.iFirstConfig.iIsFirst = 1
self.m_pOtherConfig.iShareConfig.iFirstConfig.iTodayReward = 0
if pRet[4] then
local pOldDate = os.date("%x", tonumber(pRet[4]))
local pNewDate = os.date("%x", os.time())
-- 计算上次签到的最后时间
if pOldDate == pNewDate then
self.m_pOtherConfig.iShareConfig.iFirstConfig.iTodayReward = 1
else
-- 如果不是连续天
if os.time() - tonumber(pRet[4]) > 24 * 60 * 60 then
self.m_pOtherConfig.iShareConfig.iFirstConfig.iContinueNum = 0
self.m_pOtherConfig.iShareConfig.iFirstConfig.iGetCount = 0
local pRet = self:onExecuteRedisCmd(DefineType.REDIS_ACTIVITY, "HMSET", pKey, "continue", 0, "getCount", 0)
end
end
end
self:onSendConfigData(pAgent, pConfigname, self.m_pOtherConfig.iShareConfig.iFirstConfig)
end
end
function ConfigServer:GetAuditConfig(pConfigname, pAgent, data)
data = data and json.decode(data) or {}
if not data or not data.iVersion then
return
end
local pVersion = nil
local pOpen = 0
data.iPlatform = tonumber(data.iPlatform) or DefineType.PLATFORM_IOS
if self.m_pOtherConfig and self.m_pOtherConfig.iAuditConfig then
if DefineType.PLATFORM_IOS == tonumber(data.iPlatform) then
pVersion = self.m_pOtherConfig.iAuditConfig.iIosVersion
elseif DefineType.PLATFORM_ANDROID == tonumber(data.iPlatform) then
pVersion = self.m_pOtherConfig.iAuditConfig.iAndroidVersion
elseif DefineType.PLATFORM_WINDOWS == tonumber(data.iPlatform) then
pVersion = self.m_pOtherConfig.iAuditConfig.iWindowsVersion
elseif DefineType.PLATFORM_MAC == tonumber(data.iPlatform) then
pVersion = self.m_pOtherConfig.iAuditConfig.iMacVersion
end
if pVersion and pVersion <= data.iVersion then
pOpen = 1
end
end
local pConfigData = {}
pConfigData.iOpen = pOpen
self:onSendConfigData(pAgent, pConfigname, pConfigData)
end
function ConfigServer:onSendConfigData(pAgent, pConfigname, pConfigData)
local name = "ServerUserGetConfig"
local info = {}
info.iConfigName = pConfigname
info.iConfigData = json.encode(pConfigData)
skynet.call(self.m_pHallServiceMgr, "lua", "onSendPackage", pAgent, name, info)
end
----------------------------------- redis ---------------------------------
function ConfigServer:onExecuteRedisCmd(redis, cmd, ...)
local pFmt = ""
local arg = {...}
for i = 1, #arg do
pFmt = pFmt.."%s "
end
local pStr = string.format(pFmt, ...)
Log.d(TAG, "onExecuteRedisCmd %s %s %s", redis, cmd, pStr)
if self.m_redisClientsMgr[cmd] then
local pRetRedis = self.m_redisClientsMgr[cmd](self.m_redisClientsMgr, redis, ...)
if pRetRedis and type(pRetRedis) == "table" then
Log.dump(TAG, pRetRedis, "pRetRedis")
else
Log.d(TAG, "pRetRedis[%s]", pRetRedis)
end
return pRetRedis
else
Log.e(TAG, "unknow cmd[%s]", cmd)
return -1
end
end
return ConfigServer |
-- benchmark instantiation/destruction
-- params: <n> [destructor]
--- n: number of instantiations
--- "destructor": add a destructor if passed
-- lib
package.path = ";src/?.lua;"..package.path
local Luaoop = require("Luaoop")
class = Luaoop.class
local n, destruct = tonumber(arg[1]) or 1e6, arg[2] == "destructor"
local Entity = class("Entity")
function Entity:__construct(id)
self.id = id
end
if destruct then
function Entity:__destruct()
end
end
print("n:", n)
print("destructor:", destruct)
print()
print("instantiate entities:", n)
local ent
for i=1,n do
ent = Entity(i)
end
print("last ent_id:", ent.id)
print("GC count:", collectgarbage("count"))
|
function removeFromPluginRepresentation()
end
function updatePluginRepresentation()
end
function ext_getItemData_pricing()
local c=readInfo()
local obj={}
obj.name=sim.getObjectName(model)
obj.type='conveyor'
obj.conveyorType='default'
obj.brVersion=0
obj.length=c.length*1000 -- in mm here
obj.width=c.width*1000 -- in mm here
return obj
end
function setShapeSize(h,x,y,z)
local r,mmin=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_x)
local r,mmax=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_x)
local sx=mmax-mmin
local r,mmin=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_y)
local r,mmax=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_y)
local sy=mmax-mmin
local r,mmin=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_z)
local r,mmax=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_z)
local sz=mmax-mmin
sim.scaleObject(h,x/sx,y/sy,z/sz)
end
function getDefaultInfoForNonExistingFields(info)
if not info['version'] then
info['version']=_MODELVERSION_
end
if not info['subtype'] then
info['subtype']='A'
end
if not info['velocity'] then
info['velocity']=0.1
end
if not info['acceleration'] then
info['acceleration']=0.01
end
if not info['length'] then
info['length']=1
end
if not info['width'] then
info['width']=0.3
end
if not info['height'] then
info['height']=0.1
end
if not info['borderHeight'] then
info['borderHeight']=0.2
end
if not info['bitCoded'] then
info['bitCoded']=1+2+4+8
end
if not info['wallThickness'] then
info['wallThickness']=0.005
end
if not info['stopRequests'] then
info['stopRequests']={}
end
end
function readInfo()
local data=sim.readCustomDataBlock(model,simBWF.modelTags.CONVEYOR)
if data then
data=sim.unpackTable(data)
else
data={}
end
getDefaultInfoForNonExistingFields(data)
return data
end
function writeInfo(data)
if data then
sim.writeCustomDataBlock(model,simBWF.modelTags.CONVEYOR,sim.packTable(data))
else
sim.writeCustomDataBlock(model,simBWF.modelTags.CONVEYOR,'')
end
end
function setColor(red,green,blue,spec)
sim.setShapeColor(middleParts[2],nil,sim.colorcomponent_ambient_diffuse,{red,green,blue})
sim.setShapeColor(middleParts[2],nil,sim.colorcomponent_specular,{spec,spec,spec})
sim.setShapeColor(endParts[1],nil,sim.colorcomponent_ambient_diffuse,{red,green,blue})
sim.setShapeColor(endParts[1],nil,sim.colorcomponent_specular,{spec,spec,spec})
sim.setShapeColor(endParts[2],nil,sim.colorcomponent_ambient_diffuse,{red,green,blue})
sim.setShapeColor(endParts[2],nil,sim.colorcomponent_specular,{spec,spec,spec})
end
function getColor()
local r,rgb=sim.getShapeColor(middleParts[2],nil,sim.colorcomponent_ambient_diffuse)
local r,spec=sim.getShapeColor(middleParts[2],nil,sim.colorcomponent_specular)
return rgb[1],rgb[2],rgb[3],(spec[1]+spec[2]+spec[3])/3
end
function updateConveyor()
local conf=readInfo()
local length=conf['length']
local width=conf['width']
local height=conf['height']
local borderHeight=conf['borderHeight']
local bitCoded=conf['bitCoded']
local wt=conf['wallThickness']
local re=sim.boolAnd32(bitCoded,16)==0
---[[
sim.setObjectPosition(rotJoints[1],model,{0,-length*0.5,-height*0.5})
sim.setObjectPosition(rotJoints[2],model,{0,length*0.5,-height*0.5})
setShapeSize(middleParts[1],width,length,height)
setShapeSize(middleParts[2],width,length,0.001)
setShapeSize(middleParts[3],width,length,height)
sim.setObjectPosition(middleParts[1],model,{0,0,-height*0.5})
sim.setObjectPosition(middleParts[2],model,{0,0,-0.0005})
sim.setObjectPosition(middleParts[3],model,{0,0,-height*0.5})
setShapeSize(endParts[1],width,0.083148*height/0.2,0.044443*height/0.2)
sim.setObjectPosition(endParts[1],model,{0,-length*0.5-0.5*0.083148*height/0.2,-0.044443*height*0.5/0.2})
setShapeSize(endParts[2],width,0.083148*height/0.2,0.044443*height/0.2)
sim.setObjectPosition(endParts[2],model,{0,length*0.5+0.5*0.083148*height/0.2,-0.044443*height*0.5/0.2})
setShapeSize(endParts[3],width,height*0.5,height)
sim.setObjectPosition(endParts[3],model,{0,-length*0.5-0.25*height,-height*0.5})
setShapeSize(endParts[4],width,height*0.5,height)
sim.setObjectPosition(endParts[4],model,{0,length*0.5+0.25*height,-height*0.5})
for i=5,6,1 do
setShapeSize(endParts[i],height,height,width)
end
setShapeSize(sides[1],wt,length,height+2*borderHeight)
setShapeSize(sides[2],wt,length,height+2*borderHeight)
setShapeSize(sides[4],width+2*wt,height*0.5+1*borderHeight,height+2*borderHeight)
setShapeSize(sides[3],width+2*wt,height*0.5+1*borderHeight,height+2*borderHeight)
sim.setObjectPosition(sides[4],model,{0,-(length+height*0.5+borderHeight)*0.5,-height*0.5})
sim.setObjectPosition(sides[3],model,{0,(length+height*0.5+borderHeight)*0.5,-height*0.5})
sim.setObjectPosition(sides[1],model,{-(width+wt)*0.5,0,-height*0.5})
sim.setObjectPosition(sides[2],model,{(width+wt)*0.5,0,-height*0.5})
if re then
sim.setObjectInt32Parameter(endParts[1],sim.objintparam_visibility_layer,1)
sim.setObjectInt32Parameter(endParts[2],sim.objintparam_visibility_layer,1)
sim.setObjectInt32Parameter(endParts[3],sim.objintparam_visibility_layer,1)
sim.setObjectInt32Parameter(endParts[4],sim.objintparam_visibility_layer,1)
sim.setObjectInt32Parameter(endParts[5],sim.objintparam_visibility_layer,256)
sim.setObjectInt32Parameter(endParts[6],sim.objintparam_visibility_layer,256)
sim.setObjectInt32Parameter(endParts[5],sim.shapeintparam_respondable,1)
sim.setObjectInt32Parameter(endParts[6],sim.shapeintparam_respondable,1)
else
sim.setObjectInt32Parameter(endParts[1],sim.objintparam_visibility_layer,0)
sim.setObjectInt32Parameter(endParts[2],sim.objintparam_visibility_layer,0)
sim.setObjectInt32Parameter(endParts[3],sim.objintparam_visibility_layer,0)
sim.setObjectInt32Parameter(endParts[4],sim.objintparam_visibility_layer,0)
sim.setObjectInt32Parameter(endParts[5],sim.objintparam_visibility_layer,0)
sim.setObjectInt32Parameter(endParts[6],sim.objintparam_visibility_layer,0)
sim.setObjectInt32Parameter(endParts[5],sim.shapeintparam_respondable,0)
sim.setObjectInt32Parameter(endParts[6],sim.shapeintparam_respondable,0)
end
if sim.boolAnd32(bitCoded,1)~=0 then
sim.setObjectInt32Parameter(sides[1],sim.objintparam_visibility_layer,0)
sim.setObjectInt32Parameter(sides[1],sim.shapeintparam_respondable,0)
sim.setObjectSpecialProperty(sides[1],0)
sim.setObjectProperty(sides[1],sim.objectproperty_dontshowasinsidemodel)
else
sim.setObjectInt32Parameter(sides[1],sim.objintparam_visibility_layer,1+256)
sim.setObjectInt32Parameter(sides[1],sim.shapeintparam_respondable,1)
sim.setObjectSpecialProperty(sides[1],sim.objectspecialproperty_collidable+sim.objectspecialproperty_measurable+sim.objectspecialproperty_detectable_all+sim.objectspecialproperty_renderable)
sim.setObjectProperty(sides[1],sim.objectproperty_selectable+sim.objectproperty_selectmodelbaseinstead)
end
if sim.boolAnd32(bitCoded,2)~=0 then
sim.setObjectInt32Parameter(sides[2],sim.objintparam_visibility_layer,0)
sim.setObjectInt32Parameter(sides[2],sim.shapeintparam_respondable,0)
sim.setObjectSpecialProperty(sides[2],0)
sim.setObjectProperty(sides[2],sim.objectproperty_dontshowasinsidemodel)
else
sim.setObjectInt32Parameter(sides[2],sim.objintparam_visibility_layer,1+256)
sim.setObjectInt32Parameter(sides[2],sim.shapeintparam_respondable,1)
sim.setObjectSpecialProperty(sides[2],sim.objectspecialproperty_collidable+sim.objectspecialproperty_measurable+sim.objectspecialproperty_detectable_all+sim.objectspecialproperty_renderable)
sim.setObjectProperty(sides[2],sim.objectproperty_selectable+sim.objectproperty_selectmodelbaseinstead)
end
if sim.boolAnd32(bitCoded,4)~=0 or (not re) then
sim.setObjectInt32Parameter(sides[3],sim.objintparam_visibility_layer,0)
sim.setObjectInt32Parameter(sides[3],sim.shapeintparam_respondable,0)
sim.setObjectSpecialProperty(sides[3],0)
sim.setObjectProperty(sides[3],sim.objectproperty_dontshowasinsidemodel)
else
sim.setObjectInt32Parameter(sides[3],sim.objintparam_visibility_layer,1+256)
sim.setObjectInt32Parameter(sides[3],sim.shapeintparam_respondable,1)
sim.setObjectSpecialProperty(sides[3],sim.objectspecialproperty_collidable+sim.objectspecialproperty_measurable+sim.objectspecialproperty_detectable_all+sim.objectspecialproperty_renderable)
sim.setObjectProperty(sides[3],sim.objectproperty_selectable+sim.objectproperty_selectmodelbaseinstead)
end
if sim.boolAnd32(bitCoded,8)~=0 or (not re) then
sim.setObjectInt32Parameter(sides[4],sim.objintparam_visibility_layer,0)
sim.setObjectInt32Parameter(sides[4],sim.shapeintparam_respondable,0)
sim.setObjectSpecialProperty(sides[4],0)
sim.setObjectProperty(sides[4],sim.objectproperty_dontshowasinsidemodel)
else
sim.setObjectInt32Parameter(sides[4],sim.objintparam_visibility_layer,1+256)
sim.setObjectInt32Parameter(sides[4],sim.shapeintparam_respondable,1)
sim.setObjectSpecialProperty(sides[4],sim.objectspecialproperty_collidable+sim.objectspecialproperty_measurable+sim.objectspecialproperty_detectable_all+sim.objectspecialproperty_renderable)
sim.setObjectProperty(sides[4],sim.objectproperty_selectable+sim.objectproperty_selectmodelbaseinstead)
end
if sim.boolAnd32(bitCoded,32)==0 then
local textureID=sim.getShapeTextureId(textureHolder)
sim.setShapeTexture(middleParts[2],textureID,sim.texturemap_plane,12,{0.04,0.04})
sim.setShapeTexture(endParts[1],textureID,sim.texturemap_plane,12,{0.04,0.04})
sim.setShapeTexture(endParts[2],textureID,sim.texturemap_plane,12,{0.04,0.04})
else
sim.setShapeTexture(middleParts[2],-1,sim.texturemap_plane,12,{0.04,0.04})
sim.setShapeTexture(endParts[1],-1,sim.texturemap_plane,12,{0.04,0.04})
sim.setShapeTexture(endParts[2],-1,sim.texturemap_plane,12,{0.04,0.04})
end
--]]
end
function getAvailableSensors()
local l=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0)
local retL={}
for i=1,#l,1 do
local data=sim.readCustomDataBlock(l[i],'XYZ_BINARYSENSOR_INFO')
if data then
retL[#retL+1]={sim.getObjectName(l[i]),l[i]}
end
end
return retL
end
function getAvailableMasterConveyors()
local l=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0)
local retL={}
for i=1,#l,1 do
if l[i]~=model then
local data=sim.readCustomDataBlock(l[i],simBWF.modelTags.CONVEYOR)
if data then
retL[#retL+1]={sim.getObjectName(l[i]),l[i]}
end
end
end
return retL
end
function lengthChange(ui,id,newVal)
local conf=readInfo()
local l=tonumber(newVal)
if l then
l=l*0.001
if l<0.01 then l=0.01 end
if l>5 then l=5 end
if l~=conf['length'] then
simBWF.markUndoPoint()
conf['length']=l
writeInfo(conf)
updateConveyor()
end
end
simUI.setEditValue(ui,2,simBWF.format("%.0f",conf['length']/0.001),true)
end
function widthChange(ui,id,newVal)
local conf=readInfo()
local w=tonumber(newVal)
if w then
w=w*0.001
if w<0.01 then w=0.01 end
if w>2 then w=2 end
if w~=conf['width'] then
simBWF.markUndoPoint()
conf['width']=w
writeInfo(conf)
updateConveyor()
end
end
simUI.setEditValue(ui,4,simBWF.format("%.0f",conf['width']/0.001),true)
end
function heightChange(ui,id,newVal)
local conf=readInfo()
local w=tonumber(newVal)
if w then
w=w*0.001
if w<0.01 then w=0.01 end
if w>1 then w=1 end
if w~=conf['height'] then
simBWF.markUndoPoint()
conf['height']=w
writeInfo(conf)
updateConveyor()
end
end
simUI.setEditValue(ui,20,simBWF.format("%.0f",conf['height']/0.001),true)
end
function borderHeightChange(ui,id,newVal)
local conf=readInfo()
local w=tonumber(newVal)
if w then
w=w*0.001
if w<0.005 then w=0.005 end
if w>0.2 then w=0.2 end
if w~=conf['borderHeight'] then
simBWF.markUndoPoint()
conf['borderHeight']=w
writeInfo(conf)
updateConveyor()
end
end
simUI.setEditValue(ui,21,simBWF.format("%.0f",conf['borderHeight']/0.001),true)
end
function wallThicknessChange(ui,id,newVal)
local conf=readInfo()
local w=tonumber(newVal)
if w then
w=w*0.001
if w<0.001 then w=0.001 end
if w>0.02 then w=0.02 end
if w~=conf['wallThickness'] then
simBWF.markUndoPoint()
conf['wallThickness']=w
writeInfo(conf)
updateConveyor()
end
end
simUI.setEditValue(ui,26,simBWF.format("%.0f",conf['wallThickness']/0.001),true)
end
function leftSideOpenClicked(ui,id,newVal)
local conf=readInfo()
conf['bitCoded']=sim.boolOr32(conf['bitCoded'],1)
if newVal==0 then
conf['bitCoded']=conf['bitCoded']-1
end
simBWF.markUndoPoint()
writeInfo(conf)
updateConveyor()
end
function rightSideOpenClicked(ui,id,newVal)
local conf=readInfo()
conf['bitCoded']=sim.boolOr32(conf['bitCoded'],2)
if newVal==0 then
conf['bitCoded']=conf['bitCoded']-2
end
simBWF.markUndoPoint()
writeInfo(conf)
updateConveyor()
end
function frontSideOpenClicked(ui,id,newVal)
local conf=readInfo()
conf['bitCoded']=sim.boolOr32(conf['bitCoded'],4)
if newVal==0 then
conf['bitCoded']=conf['bitCoded']-4
end
simBWF.markUndoPoint()
writeInfo(conf)
updateConveyor()
end
function backSideOpenClicked(ui,id,newVal)
local conf=readInfo()
conf['bitCoded']=sim.boolOr32(conf['bitCoded'],8)
if newVal==0 then
conf['bitCoded']=conf['bitCoded']-8
end
simBWF.markUndoPoint()
writeInfo(conf)
updateConveyor()
end
function triggerStopChange_callback(ui,id,newIndex)
local sens=comboStopTrigger[newIndex+1][2]
simBWF.setReferencedObjectHandle(model,1,sens)
if simBWF.getReferencedObjectHandle(model,2)==sens then
simBWF.setReferencedObjectHandle(model,2,-1)
end
simBWF.markUndoPoint()
updateStartStopTriggerComboboxes()
end
function triggerStartChange_callback(ui,id,newIndex)
local sens=comboStartTrigger[newIndex+1][2]
simBWF.setReferencedObjectHandle(model,2,sens)
if simBWF.getReferencedObjectHandle(model,1)==sens then
simBWF.setReferencedObjectHandle(model,1,-1)
end
simBWF.markUndoPoint()
updateStartStopTriggerComboboxes()
end
function masterChange_callback(ui,id,newIndex)
local sens=comboMaster[newIndex+1][2]
simBWF.setReferencedObjectHandle(model,3,sens) -- master
updateMasterCombobox()
updateEnabledDisabledItems()
simBWF.markUndoPoint()
end
function updateStartStopTriggerComboboxes()
local c=readInfo()
local loc=getAvailableSensors()
comboStopTrigger=simBWF.populateCombobox(ui,100,loc,{},simBWF.getObjectNameOrNone(simBWF.getReferencedObjectHandle(model,1)),true,{{simBWF.NONE_TEXT,-1}})
comboStartTrigger=simBWF.populateCombobox(ui,101,loc,{},simBWF.getObjectNameOrNone(simBWF.getReferencedObjectHandle(model,2)),true,{{simBWF.NONE_TEXT,-1}})
end
function updateMasterCombobox()
local c=readInfo()
local loc=getAvailableMasterConveyors()
comboMaster=simBWF.populateCombobox(ui,102,loc,{},simBWF.getObjectNameOrNone(simBWF.getReferencedObjectHandle(model,3)),true,{{simBWF.NONE_TEXT,-1}})
end
function updateEnabledDisabledItems()
if ui then
local c=readInfo()
local re=sim.boolAnd32(c['bitCoded'],16)==0
local simStopped=sim.getSimulationState()==sim.simulation_stopped
simUI.setEnabled(ui,2,simStopped,true)
simUI.setEnabled(ui,4,simStopped,true)
simUI.setEnabled(ui,5,simStopped,true)
simUI.setEnabled(ui,6,simStopped,true)
simUI.setEnabled(ui,7,simStopped,true)
simUI.setEnabled(ui,8,simStopped,true)
simUI.setEnabled(ui,20,simStopped,true)
simUI.setEnabled(ui,21,simStopped,true)
simUI.setEnabled(ui,22,simStopped,true)
simUI.setEnabled(ui,23,simStopped,true)
simUI.setEnabled(ui,24,simStopped and re,true)
simUI.setEnabled(ui,25,simStopped and re,true)
simUI.setEnabled(ui,26,simStopped,true)
simUI.setEnabled(ui,27,simStopped,true)
simUI.setEnabled(ui,28,simStopped,true)
simUI.setEnabled(ui,1000,simBWF.getReferencedObjectHandle(model,3)==-1,true) -- enable
simUI.setEnabled(ui,10,simBWF.getReferencedObjectHandle(model,3)==-1,true) -- vel
simUI.setEnabled(ui,12,simBWF.getReferencedObjectHandle(model,3)==-1,true) -- accel
simUI.setEnabled(ui,100,simStopped,true) -- stop trigger
simUI.setEnabled(ui,101,simStopped,true) -- restart trigger
simUI.setEnabled(ui,102,simStopped,true) -- master
end
end
function roundedEndsClicked(ui,id,newVal)
local conf=readInfo()
conf['bitCoded']=sim.boolOr32(conf['bitCoded'],16)
if newVal~=0 then
conf['bitCoded']=conf['bitCoded']-16
end
writeInfo(conf)
simBWF.markUndoPoint()
updateConveyor()
updateEnabledDisabledItems()
end
function texturedClicked(ui,id,newVal)
local conf=readInfo()
conf['bitCoded']=sim.boolOr32(conf['bitCoded'],32)
if newVal~=0 then
conf['bitCoded']=conf['bitCoded']-32
end
writeInfo(conf)
simBWF.markUndoPoint()
updateConveyor()
end
function enabledClicked(ui,id,newVal)
local conf=readInfo()
conf['bitCoded']=sim.boolOr32(conf['bitCoded'],64)
if newVal==0 then
conf['bitCoded']=conf['bitCoded']-64
end
writeInfo(conf)
simBWF.markUndoPoint()
end
function redChange(ui,id,newVal)
simBWF.markUndoPoint()
local r,g,b,s=getColor()
setColor(newVal/100,g,b,s)
end
function greenChange(ui,id,newVal)
simBWF.markUndoPoint()
local r,g,b,s=getColor()
setColor(r,newVal/100,b,s)
end
function blueChange(ui,id,newVal)
simBWF.markUndoPoint()
local r,g,b,s=getColor()
setColor(r,g,newVal/100,s)
end
function specularChange(ui,id,newVal)
simBWF.markUndoPoint()
local r,g,b,s=getColor()
setColor(r,g,b,newVal/100)
end
function speedChange(ui,id,newVal)
local c=readInfo()
local v=tonumber(newVal)
if v then
v=v*0.001
if v<-0.5 then v=-0.5 end
if v>0.5 then v=0.5 end
if v~=c['velocity'] then
simBWF.markUndoPoint()
c['velocity']=v
writeInfo(c)
end
end
simUI.setEditValue(ui,10,simBWF.format("%.0f",c['velocity']/0.001),true)
end
function accelerationChange(ui,id,newVal)
local c=readInfo()
local v=tonumber(newVal)
if v then
v=v*0.001
if v<0.001 then v=0.001 end
if v>1 then v=1 end
if v~=c['acceleration'] then
simBWF.markUndoPoint()
c['acceleration']=v
writeInfo(c)
end
end
simUI.setEditValue(ui,12,simBWF.format("%.0f",c['acceleration']/0.001),true)
end
function createDlg()
if (not ui) and simBWF.canOpenPropertyDialog() then
local xml = [[
<tabs id="77">
<tab title="General" layout="form">
<label text="Enabled"/>
<checkbox text="" on-change="enabledClicked" id="1000"/>
<label text="Speed (mm/s)"/>
<edit on-editing-finished="speedChange" id="10"/>
<label text="Acceleration (mm/s^2)"/>
<edit on-editing-finished="accelerationChange" id="12"/>
<label text="Master conveyor"/>
<combobox id="102" on-change="masterChange_callback">
</combobox>
<label text="Stop on trigger"/>
<combobox id="100" on-change="triggerStopChange_callback">
</combobox>
<label text="Restart on trigger"/>
<combobox id="101" on-change="triggerStartChange_callback">
</combobox>
<label text="" style="* {margin-left: 150px;}"/>
<label text="" style="* {margin-left: 150px;}"/>
</tab>
<tab title="Dimensions" layout="form">
<label text="Length (mm)"/>
<edit on-editing-finished="lengthChange" id="2"/>
<label text="Width (mm)"/>
<edit on-editing-finished="widthChange" id="4"/>
<label text="Height (mm)"/>
<edit on-editing-finished="heightChange" id="20"/>
<label text="Border height (mm)"/>
<edit on-editing-finished="borderHeightChange" id="21"/>
<label text="Wall thickness (mm)"/>
<edit on-editing-finished="wallThicknessChange" id="26"/>
</tab>
<tab title="Color" layout="form">
<label text="Red"/>
<hslider minimum="0" maximum="100" on-change="redChange" id="5"/>
<label text="Green"/>
<hslider minimum="0" maximum="100" on-change="greenChange" id="6"/>
<label text="Blue"/>
<hslider minimum="0" maximum="100" on-change="blueChange" id="7"/>
<label text="Specular"/>
<hslider minimum="0" maximum="100" on-change="specularChange" id="8"/>
</tab>
<tab title="More" layout="form">
<label text="Textured"/>
<checkbox text="" on-change="texturedClicked" id="28"/>
<label text="Left side open"/>
<checkbox text="" on-change="leftSideOpenClicked" id="22"/>
<label text="Right side open"/>
<checkbox text="" on-change="rightSideOpenClicked" id="23"/>
<label text="Rounded ends"/>
<checkbox text="" on-change="roundedEndsClicked" id="27"/>
<label text="Front side open"/>
<checkbox text="" on-change="frontSideOpenClicked" id="24"/>
<label text="Back side open"/>
<checkbox text="" on-change="backSideOpenClicked" id="25"/>
</tab>
</tabs>
]]
ui=simBWF.createCustomUi(xml,simBWF.getUiTitleNameFromModel(model,_MODELVERSION_,_CODEVERSION_),previousDlgPos--[[,closeable,onCloseFunction,modal,resizable,activate,additionalUiAttribute--]])
local red,green,blue,spec=getColor()
local config=readInfo()
simUI.setEditValue(ui,2,simBWF.format("%.0f",config['length']/0.001),true)
simUI.setEditValue(ui,4,simBWF.format("%.0f",config['width']/0.001),true)
simUI.setEditValue(ui,20,simBWF.format("%.0f",config['height']/0.001),true)
simUI.setEditValue(ui,21,simBWF.format("%.0f",config['borderHeight']/0.001),true)
simUI.setEditValue(ui,26,simBWF.format("%.0f",config['wallThickness']/0.001),true)
simUI.setCheckboxValue(ui,22,(sim.boolAnd32(config['bitCoded'],1)~=0) and 2 or 0,true)
simUI.setCheckboxValue(ui,23,(sim.boolAnd32(config['bitCoded'],2)~=0) and 2 or 0,true)
simUI.setCheckboxValue(ui,24,(sim.boolAnd32(config['bitCoded'],4)~=0) and 2 or 0,true)
simUI.setCheckboxValue(ui,25,(sim.boolAnd32(config['bitCoded'],8)~=0) and 2 or 0,true)
simUI.setCheckboxValue(ui,27,(sim.boolAnd32(config['bitCoded'],16)==0) and 2 or 0,true)
simUI.setCheckboxValue(ui,28,(sim.boolAnd32(config['bitCoded'],32)==0) and 2 or 0,true)
simUI.setCheckboxValue(ui,1000,(sim.boolAnd32(config['bitCoded'],64)~=0) and 2 or 0,true)
simUI.setEditValue(ui,10,simBWF.format("%.0f",config['velocity']/0.001),true)
simUI.setEditValue(ui,12,simBWF.format("%.0f",config['acceleration']/0.001),true)
-- simUI.setEditValue(ui,14,simBWF.format("%.0f",config[3]/0.001),true)
simUI.setSliderValue(ui,5,red*100,true)
simUI.setSliderValue(ui,6,green*100,true)
simUI.setSliderValue(ui,7,blue*100,true)
simUI.setSliderValue(ui,8,spec*100,true)
updateStartStopTriggerComboboxes()
updateMasterCombobox()
updateEnabledDisabledItems()
simUI.setCurrentTab(ui,77,dlgMainTabIndex,true)
--]]
end
end
function showDlg()
if not ui then
createDlg()
end
end
function removeDlg()
if ui then
local x,y=simUI.getPosition(ui)
previousDlgPos={x,y}
dlgMainTabIndex=simUI.getCurrentTab(ui,77)
simUI.destroy(ui)
ui=nil
end
end
function sysCall_init()
dlgMainTabIndex=0
model=sim.getObjectAssociatedWithScript(sim.handle_self)
_MODELVERSION_=0
_CODEVERSION_=0
local _info=readInfo()
simBWF.checkIfCodeAndModelMatch(model,_CODEVERSION_,_info['version'])
-- Following for backward compatibility:
if _info['stopTrigger'] then
simBWF.setReferencedObjectHandle(model,1,sim.getObjectHandle_noErrorNoSuffixAdjustment(_info['stopTrigger']))
_info['stopTrigger']=nil
end
if _info['startTrigger'] then
simBWF.setReferencedObjectHandle(model,2,sim.getObjectHandle_noErrorNoSuffixAdjustment(_info['startTrigger']))
_info['startTrigger']=nil
end
if _info['masterConveyor'] then
simBWF.setReferencedObjectHandle(model,3,sim.getObjectHandle_noErrorNoSuffixAdjustment(_info['masterConveyor']))
_info['masterConveyor']=nil
end
----------------------------------------
writeInfo(_info)
rotJoints={}
rotJoints[1]=sim.getObjectHandle('genericConveyorTypeA_jointB')
rotJoints[2]=sim.getObjectHandle('genericConveyorTypeA_jointC')
middleParts={}
middleParts[1]=sim.getObjectHandle('genericConveyorTypeA_sides')
middleParts[2]=sim.getObjectHandle('genericConveyorTypeA_textureA')
middleParts[3]=sim.getObjectHandle('genericConveyorTypeA_forwarderA')
endParts={}
endParts[1]=sim.getObjectHandle('genericConveyorTypeA_textureB')
endParts[2]=sim.getObjectHandle('genericConveyorTypeA_textureC')
endParts[3]=sim.getObjectHandle('genericConveyorTypeA_B')
endParts[4]=sim.getObjectHandle('genericConveyorTypeA_C')
endParts[5]=sim.getObjectHandle('genericConveyorTypeA_forwarderB')
endParts[6]=sim.getObjectHandle('genericConveyorTypeA_forwarderC')
sides={}
sides[1]=sim.getObjectHandle('genericConveyorTypeA_leftSide')
sides[2]=sim.getObjectHandle('genericConveyorTypeA_rightSide')
sides[3]=sim.getObjectHandle('genericConveyorTypeA_frontSide')
sides[4]=sim.getObjectHandle('genericConveyorTypeA_backSide')
textureHolder=sim.getObjectHandle('genericConveyorTypeA_textureHolder')
updatePluginRepresentation()
previousDlgPos,algoDlgSize,algoDlgPos,distributionDlgSize,distributionDlgPos,previousDlg1Pos=simBWF.readSessionPersistentObjectData(model,"dlgPosAndSize")
end
showOrHideUiIfNeeded=function()
local s=sim.getObjectSelection()
if s and #s>=1 and s[#s]==model then
showDlg()
else
removeDlg()
end
end
function sysCall_nonSimulation()
showOrHideUiIfNeeded()
end
function sysCall_sensing()
if simJustStarted then
updateEnabledDisabledItems()
end
simJustStarted=nil
showOrHideUiIfNeeded()
end
function sysCall_suspend()
showOrHideUiIfNeeded()
end
function sysCall_afterSimulation()
updateEnabledDisabledItems()
local conf=readInfo()
conf['encoderDistance']=0
conf['stopRequests']={}
writeInfo(conf)
end
function sysCall_beforeSimulation()
simJustStarted=true
end
function sysCall_beforeInstanceSwitch()
removeDlg()
removeFromPluginRepresentation()
end
function sysCall_afterInstanceSwitch()
updatePluginRepresentation()
end
function sysCall_cleanup()
removeDlg()
removeFromPluginRepresentation()
simBWF.writeSessionPersistentObjectData(model,"dlgPosAndSize",previousDlgPos,algoDlgSize,algoDlgPos,distributionDlgSize,distributionDlgPos,previousDlg1Pos)
end |
-- ... c.lua
|
require('packer').use({
'https://github.com/nvim-treesitter/nvim-treesitter',
run = ':TSUpdate',
config = function()
-- Enable Tree-sitter-based code folding.
vim.o.foldmethod = 'expr'
vim.o.foldexpr = 'nvim_treesitter#foldexpr()'
-- Enable Tree-sitter-based syntax highlighting.
require('nvim-treesitter.configs').setup({highlight = {enable = true}})
end
})
|
object_mobile_dressed_echo_base_darth_vader = object_mobile_shared_dressed_echo_base_darth_vader:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_echo_base_darth_vader, "object/mobile/dressed_echo_base_darth_vader.iff")
|
project "UI"
language "C#"
kind "SharedLib"
files { "../src/ui/**.cs", "../src/ui/**.glsl", "../src/ui/data/**.png"}
links { "System", "System.Drawing", "OpenTK", "Util", "Graphics", "Engine" }
location "ui"
vpaths { ["*"] = "../src/ui" }
|
-- require('feline').setup()
|
--
--
-- UTF-8 file
--
-- We are using this as the base list of NPC names, so we do not look at the locale
-- to determine whether we should abandon further processing.
local G = Grail.npc.name
local _, release, _, interface = GetBuildInfo()
release = tonumber(release)
interface = tonumber(interface)
if release >= 0 then
G[-1920895]='NukeMe -1920895'
G[-1910895]='NukeMe -1910895'
G[-1900895]='NukeMe -1900895'
G[-1410864]='NukeMe -1410864'
G[-1370896]='NukeMe -1370896'
G[-1360896]='NukeMe -1360896'
G[-1100863]='NukeMe -1100863'
G[-1080942]='NukeMe -1080942'
G[-910680]='NukeMe -910680'
G[-890680]='NukeMe -890680'
G[-890630]='NukeMe -890630'
G[-880630]='NukeMe -880630'
G[-780634]='NukeMe -780634'
G[-770650]='NukeMe -770650'
G[-770641]='NukeMe -770641'
G[-760641]='NukeMe -760641'
G[-750641]='NukeMe -750641'
G[-610646]='NukeMe -610646'
G[0]='Self'
G[1]=ADVENTURE_JOURNAL
G[130809]='NukeMe 130809'
G[500022]='Candy Bucket'
G[500024]="Anson's Crate"
G[500025]="Edgar's Crate"
G[500032]='Image of Nozdormu'
G[562180]='Klaxxi Warrior'
G[562295]='Omnia Mage'
G[562378]='Omnia Priest'
G[563195]='Blackguard Brewmaster'
G[563196]='Blackguard Battlemaster'
G[563197]='Blackguard Stalwart'
G[563622]='Wu Kao Rogue'
G[563623]='Wu Kao Assassin'
G[563624]='Wu Kao Hawkmaster'
G[565558]='Huojin Monk'
G[600000]='Moss-Covered Chest'
G[600001]='Sturdy Chest'
G[600002]='Smoldering Chest'
G[702446]='NukeMe 702446'
G[1000033]='Locked Chest'
G[1000034]='Old Jug'
G[1000035]="Captain's Footlocker"
G[1000036]='Broken Barrel'
G[1000055]='A half-eaten body'
G[1000056]="Rolf's corpse"
G[1000061]='A Weathered Grave'
G[1000068]='Wanted Poster'
G[1000256]='Wanted!'
G[1000259]='Half-buried Barrel'
G[1000261]='Damaged Crate'
G[1002059]='A Dwarven Corpse'
G[1002076]='Bubbling Cauldron'
G[1002083]='Bloodsail Correspondence'
G[1002688]='Keystone'
G[1002701]='Iridescent Shards'
G[1002702]='Stone of Inner Binding'
G[1002713]='Wanted Board'
G[1002908]='Sealed Supply Crate'
G[1003972]='WANTED'
G[1004141]='Control Console'
G[1006751]='Strange Fruited Plant'
G[1006752]='Strange Fronded Plant'
G[1007510]='Sprouted Frond'
G[1007923]="Denalan's Planter"
G[1020985]='Loose Dirt'
G[1020992]='Black Shield'
G[1021042]='Theramore Guard Badge'
G[1024776]="Yuriv's Tombstone"
G[1035251]="Karnitol's Chest"
G[1035591]='Fishing Bobber'
G[1112948]="Intrepid's Locked Strongbox"
G[1131474]='The Discs of Norgannon'
G[1138492]='Shards of Myzrael'
G[1142151]='Sealed Barrel'
G[1142195]='Woodpaw Battle Map'
G[1142487]='The Sparklematic 5200'
G[1151286]='Kaldorei Tome of Summoning'
G[1152097]="Belnistrasz's Brazier"
G[1161521]='Research Equipment'
G[1161526]='Crate of Foodstuffs'
G[1164869]='Spectral Chalice'
G[1164955]='Northern Crystal Pylon'
G[1164956]='Western Crystal Pylon'
G[1164957]='Eastern Crystal Pylon'
G[1176091]='Deadwood Cauldron'
G[1176392]='Scourge Cauldron'
G[1177544]="Joseph's Chest"
G[1179485]='Broken Trap'
G[1179517]="Treasure of the Shen'dralar"
G[1179551]="Hydraxis' Coffer"
G[1179697]='Arena Treasure Chest'
G[1179880]="Drakkisath's Brand"
G[1180025]='Mysterious Eastvale Haystack'
G[1180055]='Mysterious Wailing Caverns Chest'
G[1180056]='Mysterious Tree Stump'
G[1180366]='Battered Tackle Box'
G[1180448]='Wanted Poster: Deathclasp'
G[1180503]='Sandy Cookbook'
G[1180715]='Holly Preserver'
G[1180743]='Carefully Wrapped Present'
G[1180746]='Gently Shaken Gift'
G[1180747]='Gaily Wrapped Present'
G[1180748]='Ticking Present'
G[1180793]='Festive Gift'
G[1180918]='Wanted: Thaelis the Hungerer'
G[1181011]="Magister Duskwither's Journal"
G[1181150]='Dusty Journal'
G[1181153]="Wanted Poster: Kel'gash the Wicked"
G[1181748]='Blood Crystal'
G[1181756]='Battered Ancient Book'
G[1181758]='Mound of Dirt'
G[1182032]="Galaen's Journal"
G[1182392]='Garadar Bulletin Board'
G[1182393]='Telaar Bulletin Board'
G[1182549]='Fel Orc Plans'
G[1182947]='The Codex of Blood'
G[1183770]="B'naar Control Console"
G[1183877]='Ethereal Transporter Control Panel'
G[1184300]='Necromantic Focus'
G[1184825]="Lashh'an Tome"
G[1185126]='Crystal Prison'
G[1185165]='Legion Communicator'
G[1186585]='Dragonskin Scroll'
G[1186887]="Large Jack-o'-Lantern"
G[1187236]='Winter Veil Gift'
G[1187273]='Suspicious Hoofprint'
G[1187559]='Horde Bonfire'
G[1187564]='Alliance Bonfire'
G[1187565]='Elder Atkanok'
G[1187851]='Cultist Shrine'
G[1187905]='Massive Glowing Egg'
G[1188085]='Plagued Grain'
G[1188261]='Battered Journal'
G[1188364]='Wrecked Crab Trap'
G[1188365]='Heart of the Ancients'
G[1188419]="Elder Mana'loa"
G[1188667]='Amberseed'
G[1189311]='Flesh-bound Tome'
G[1189989]='Dark Iron Mole Machine Wreckage'
G[1190535]="Zim'Abwa"
G[1190602]="Zim'Torga"
G[1190657]="Zim'Rhuk"
G[1190768]='Timeworn Coffer'
G[1190777]="Artruis's Phylactery"
G[1190917]='Abandoned Mail'
G[1190936]='Plague Cauldron'
G[1191760]="Inventor's Library Console"
G[1191761]='Prototype Console'
G[1191766]='Orders From Drakuru'
G[1192060]="Fjorn's Anvil"
G[1192072]='Harpoon Crate'
G[1192078]="Hodir's Horn"
G[1192079]="Hodir's Spear"
G[1192080]="Hodir's Helm"
G[1192524]='Arngrim the Insatiable'
G[1192833]="Bridenbrad's Possessions"
G[1193195]='Pulsing Crystal'
G[1193400]='Saronite Bomb Stack'
G[1193905]="Alexstrasza's Gift"
G[1194105]='Buzzbox 413'
G[1194122]='Buzzbox 723'
G[1194378]="Stolen Explorers' League Document"
G[1194555]='Archivum Console'
G[1194714]='Disgusting Workbench'
G[1195134]='The Bomb'
G[1195431]='Headquarters Radio'
G[1195433]='Ancient Tablets'
G[1195435]='Weapons Cabinet'
G[1195438]='Cup of Elune'
G[1195445]='Ancient Vortex Runestone'
G[1195497]="Elune's Brazier"
G[1195517]="Elune's Handmaiden"
G[1195600]='Smouldering Stone'
G[1195642]='Naga Power Stone'
G[1195676]='Secret Lab Squawkbox'
G[1196393]='Broken Relic'
G[1196394]='Crate of Mandrake Essence'
G[1196832]='Upper Scrying Stone'
G[1196833]='Lower Scrying Stone'
G[1201578]='Wrenchmen Recruitment Poster'
G[1201742]='Runeforge'
G[1202135]="Dadanga's Grave"
G[1202264]="Ringo's Sack"
G[1202335]="Paxton's Field Cannon"
G[1202407]="Sandscraper's Chest"
G[1202474]='Antediluvean Chest'
G[1202598]='Big Nasty Plunger'
G[1202613]='Platform Control Panel'
G[1202697]='Eye of Twilight'
G[1202701]='Outhouse Hideout'
G[1202706]='Twilight Cauldron'
G[1202712]='The Twilight Apocrypha'
G[1202714]='Enormous Skull'
G[1202759]='Sunken Horde Chest'
G[1202859]='Half-buried Footlocker'
G[1202871]='Sunken Crate'
G[1202916]='Sandy Mound'
G[1202975]='Submerged Outhouse'
G[1203128]='Broken Bottle'
G[1203134]='Empty Pedestal'
G[1203140]='Broken Prong'
G[1203186]='STAY OUT!'
G[1203207]='Codex of Shadows'
G[1203301]='Naga Tridents'
G[1203305]='Crucible of Nazsharin'
G[1203395]='Alliance S.E.A.L. Equipment'
G[1203733]='Bounty Board'
G[1203734]='Westfall Deed'
G[1204050]='Foebreaker Blueprints'
G[1204274]="Captain's Log"
G[1204351]='Ettin Control Orb'
G[1204406]='Half-Buried Bottle'
G[1204450]="Captain Stillwater's Charts"
G[1204578]='Barrel of Doublerum'
G[1204817]='Lightforged Rod'
G[1204824]='Lightforged Arch'
G[1204825]='Lightforged Crest'
G[1204959]='Gigantic Painite Cluster'
G[1205134]="Forgemaster's Log"
G[1205143]='Abandoned Outhouse'
G[1205198]='Pile of Explosives'
G[1205207]="Maziel's Journal"
G[1205258]='Broken Weapons Crate'
G[1205266]='Elaborate Disc'
G[1205350]='Horde Communication Panel'
G[1205540]='Decrepit Skeleton'
G[1205874]='Sand-Covered Hieroglyphs'
G[1205875]="Crusader's Flare"
G[1206109]="Warchief's Command Board"
G[1206111]="Hero's Call Board"
G[1206293]='A. I. D.A. Terminal'
G[1206335]='Stone Slab'
G[1206336]='Marble Slab'
G[1206374]='Trove of the Watchers'
G[1206504]="Rhea's Final Note"
G[1206585]='Totem of Ruumbo'
G[1206944]='Shovel'
G[1207104]='Master Control Pump'
G[1207125]='Crate of Left Over Supplies'
G[1207179]='Winterfall Cauldron'
G[1207291]='Echo Three'
G[1207303]='Adventure Board'
G[1207359]='Pure Twilight Egg'
G[1207406]='Strange Fountain'
G[1207407]='Broken Pillar'
G[1207408]='Magical Brazier'
G[1207409]="Tol'vir Grave"
G[1207410]='Large Stone Obelisk'
G[1207411]='Dwarven Bone Pile'
G[1207412]='Stone Tablet'
G[1208184]='Earthen Ring Bonfire'
G[1208420]='Treasure Chest'
G[1208535]='Dried Acorn'
G[1208549]='Voodoo Pile'
G[1208825]='Shrine of the Ancestors'
G[1209072]='Stolen Crate'
G[1209673]='Jade Tiger Pillar'
G[1209845]='Mouthwatering Brew'
G[1211316]="The Commander's Cache"
G[1211754]='Curious Text'
G[1212181]='Ancient Statue'
G[1212389]='Scroll of Auspice'
G[1213767]='Hidden Treasure'
G[1213770]='Stolen Sprite Treasure'
G[1213771]='Statue of Xuen'
G[1213793]="Rikktik's Tiny Chest"
G[1214062]='Glowing Amber'
G[1214218]='Clutter'
G[1214438]='Ancient Mogu Tablet'
G[1214562]='Sha-Haunted Crystal'
G[1214871]='Shattered Destroyer'
G[1215705]='Tillers Shrine'
G[1215844]='Flagpole'
G[1216274]='Signal Fire'
G[1216609]='Flare Launcher'
G[1216837]="Wrathion's Jewel Chest"
G[1217848]='Midsummer Bonfire'
G[1218072]='Head of the Keymaster'
G[1218077]='Base of the Chamberlain'
G[1218750]='Work Orders'
G[1218765]='Empty Crate'
G[1218808]='Cache of Ancient Treasures'
G[1220641]='Thunderlord Cache'
G[1220832]='Sunken Treasure'
G[1220901]='Gleaming Treasure Chest'
G[1220902]='Rope-Bound Treasure Chest'
G[1220903]='Gleaming Crane Statue'
G[1220986]="Blackguard's Jetsam"
G[1221036]='Gleaming Treasure Satchel'
G[1221376]='Old Sign Fragment'
G[1221413]='Lin Family Scroll'
G[1221617]='Skull-Covered Chest'
G[1221670]='Moss-Covered Chest'
G[1222684]='Glinting Sand'
G[1223084]='Moss-Covered Chest'
G[1223087]='Moss-Covered Chest'
G[1223088]='Moss-Covered Chest'
G[1223090]='Moss-Covered Chest'
G[1223101]='Moss-Covered Chest'
G[1223107]='Moss-Covered Chest'
G[1223533]='Peaceful Offering'
G[1224217]='Dusty Chest'
G[1224305]="Chaincrafter's Anvil"
G[1224306]='Broken Chains'
G[1224392]="Slave's Stash"
G[1224613]="Spectator's Chest"
G[1224616]='Obsidian Petroglyph'
G[1224623]='Wiggling Egg'
G[1224633]='Iron Horde Supplies'
G[1224686]="Devourer's Gutstone"
G[1224713]='Cragmaul Cache'
G[1224750]='Hanging Satchel'
G[1224753]='Scaly Rylak Egg'
G[1224754]='Waterlogged Chest'
G[1224755]='Iron Horde Tribute'
G[1224756]="Alchemist's Satchel"
G[1224770]='Shadowmoon Exile Treasure'
G[1224780]='Shadowmoon Sacrificial Dagger'
G[1224781]='Rotting Basket'
G[1224783]='False-Bottomed Jar'
G[1224784]="Vindicator's Cache"
G[1224785]='Demonic Cache'
G[1225596]='Prickly Nopal'
G[1225726]='Iron Shredder Decommission Orders'
G[1225778]="Barum's Notes"
G[1226831]="Astrologer's Box"
G[1226854]='Armored Elekk Tusk'
G[1226861]="Ronokk's Belongings"
G[1226862]='Giant Moonwillow Cone'
G[1226865]='Cargo of the Raven Queen'
G[1226888]='Aruunem Berry Bush'
G[1226955]="Arena Master's War Horn"
G[1226976]="Deceptia's Smoldering Boots"
G[1226983]="Crag-Leaper's Cache"
G[1226987]='Ricky'
G[1226990]='Supply Dump'
G[1226993]="Survivalist's Cache"
G[1226994]='Grimfrost Treasure'
G[1226996]='Goren Leftovers'
G[1227067]='Forge'
G[1227069]='Hastily Written Note'
G[1227134]='Iron Horde Cargo Shipment'
G[1227504]='Barbed Thunderlord Spear'
G[1227527]='Lightbearer'
G[1227587]="Yuuri's Gift"
G[1227654]='Viperlash'
G[1227737]='Shadow Council Communicator'
G[1227743]='Fantastic Fish'
G[1227793]="Aarko's Family Treasure"
G[1227806]='Battle-Worn Frostwolf Banner'
G[1227859]='Hope'
G[1227951]="Rook's Tacklebox"
G[1227953]='Jug of Aged Ironwine'
G[1227954]='Luminous Shell'
G[1227955]='Amethyl Crystal'
G[1227956]="Foreman's Lunchbox"
G[1227996]='Curious Deathweb Egg'
G[1227998]="Ockbar's Pack"
G[1228012]='Charred Sword'
G[1228013]="Farmer's Bounty"
G[1228014]='Relic of Aruuna'
G[1228015]='Iron Box'
G[1228016]='Barrel of Fish'
G[1228017]='Draenei Weapons'
G[1228018]="Soulbinder's Reliquary"
G[1228019]='Webbed Sac'
G[1228020]='Relic of Telmor'
G[1228021]="Treasure of Ango'rosh"
G[1228022]='Light of the Sea'
G[1228023]='Bonechewer Remnants'
G[1228024]='Aruuna Mining Cart'
G[1228025]="Keluu's Belongings"
G[1228026]='Pure Crystal Dust'
G[1228483]='Rusted Lockbox'
G[1228493]='True Iron Deposit'
G[1228563]='Blackrock Deposit'
G[1228570]="Ketya's Stash"
G[1228571]='Frostweed'
G[1228572]='Fireweed'
G[1228573]='Gorgrond Flytrap'
G[1228574]='Starflower'
G[1228575]='Nagrand Arrowbloom'
G[1228576]='Talador Orchid'
G[1228991]='Frostblossom'
G[1229314]='Goblin Mind Control Device'
G[1229328]='Bloodmaul Frostbender'
G[1229330]='Mysterious Ring'
G[1229331]='A Mystical Hat'
G[1229333]='Mysterious Boots'
G[1229344]='Buried Timewarped Staff'
G[1229354]='Bright Coin'
G[1229367]='Frozen Orc Skeleton'
G[1229640]='Frostwolf Cold-Singer'
G[1230252]='Burning Pearl'
G[1230401]='Spider'
G[1230402]='Lucky Coin'
G[1230424]='Snow-Covered Strongbox'
G[1230425]='Gnawed Bone'
G[1230611]='Pale Loot Sack'
G[1230643]='Teroclaw Nest'
G[1230664]='The Crystal Blade of Torvath'
G[1230665]='Drafting Table'
G[1230820]='Snapdragon'
G[1230865]='List of Ingredients'
G[1230880]='Drudgeboat Salvage'
G[1230881]='Drudgeboat Salvage'
G[1230882]='Gold-O-Matic 9000'
G[1230909]='Forgotten Supplies'
G[1230933]='Defense Pylon Central Control Console'
G[1231069]='Strange Looking Dagger'
G[1231100]='Icevine'
G[1231103]='Raided Loot'
G[1231183]='Place Eye of Anzu'
G[1231184]='Offering Bowl'
G[1231644]='Horned Skull'
G[1231769]='Glowing Mushroom'
G[1231901]='Ogre Scrolls'
G[1231903]="Razzlebeard's Report"
G[1231918]="Laanda's Scroll"
G[1232024]='Warsong Attack Plans'
G[1232066]='Sunken Treasure'
G[1232067]='Stolen Treasure'
G[1232100]='Nagrand Cherry'
G[1232169]="Varasha's Egg"
G[1232353]="Overseer's Chair"
G[1232360]='Cannonball'
G[1232397]='Bulletin Board'
G[1232458]="Nizzix's Chest"
G[1232489]='Weapon Loader'
G[1232492]='Doomshot'
G[1232494]='Mushroom-Covered Chest'
G[1232571]='Goblin Pack'
G[1232582]="Ashes of A'kumbo"
G[1232583]='Carved Drinking Horn'
G[1232586]="Rovo's Dagger"
G[1232587]="Uzko's Knickknacks"
G[1232588]="Greka's Urn"
G[1232589]="Veema's Herb Bag"
G[1232590]='Void-Infused Crystal'
G[1232591]="Beloved's Offering"
G[1232592]='Swamplighter Hive'
G[1232596]='Ancestral Greataxe'
G[1232597]='Goblin Pack'
G[1232598]='Steamwheedle Glider Pilot'
G[1232599]='Warsong Spoils'
G[1232621]='Strange Spore'
G[1232624]="Mikkal's Chest"
G[1232986]='Tormmok'
G[1232989]='Basket of Arakkoa Goods'
G[1233005]='Bloodmaul Cache'
G[1233032]="Mountain Climber's Pack"
G[1233034]='Steamwheedle Supplies'
G[1233044]='Fungus-Covered Chest'
G[1233048]='Brilliant Dreampetal'
G[1233052]='Steamwheedle Supplies'
G[1233079]='Appropriated Warsong Supplies'
G[1233101]='Sunken Fishing boat'
G[1233103]='Warsong Lockbox'
G[1233113]='Warsong Spear'
G[1233117]='Frostweed'
G[1233126]='Shadowmoon Treasure'
G[1233132]='Freshwater Clam'
G[1233134]='Golden Kaliri Egg'
G[1233135]='Warsong Cache'
G[1233137]='Burning Blade Cache'
G[1233139]='Ancient Titan Chest'
G[1233149]='Laughing Skull Cache'
G[1233206]='Abandoned Cargo'
G[1233218]="Adventurer's Pack"
G[1233229]='Shadow Council Tome of Curses'
G[1233241]='Glowing Cave Mushroom'
G[1233263]='Shamanstone'
G[1233291]='Command Board'
G[1233296]='Ancient Ogre Hoard Jar'
G[1233350]='Warsong Command Brief'
G[1233391]='Weaponization Orders'
G[1233452]='A Pile of Dirt'
G[1233455]='Aged Stone Container'
G[1233457]='Crushed Adventurer'
G[1233492]='Elemental Offering'
G[1233499]="Adventurer's Sack"
G[1233501]='Mysterious Petrified Pod'
G[1233504]='Remains of Grimnir Ashpick'
G[1233505]='Unknown Petrified Egg'
G[1233507]='Forgotten Ogre Cache'
G[1233511]="Adventurer's Pack"
G[1233513]='Forgotten Skull Cache'
G[1233520]='Remains of Explorer Engineer Toldirk Ashlamp'
G[1233521]='Lazy Warsong Scout'
G[1233522]='Obsidian Crystal Formation'
G[1233523]='Mysterious Petrified Pod'
G[1233524]='Unknown Petrified Egg'
G[1233525]='Botani Essence Seed'
G[1233526]='Ancient Titan Chest'
G[1233532]='Bone-Carved Dagger'
G[1233549]='Genedar Debris'
G[1233550]='Unknown Petrified Egg'
G[1233551]='Breezestrider Talbuk'
G[1233552]='Aged Stone Container'
G[1233558]='Mysterious Petrified Pod'
G[1233559]='Forgotten Skull Cache'
G[1233560]="Fragment of Oshu'gun"
G[1233561]='Tormmok'
G[1233593]='Polished Saberon Skull'
G[1233598]='Elemental Shackles'
G[1233611]='Highmaul Sledge'
G[1233613]='Telaar Defender Shield'
G[1233618]='Ogre Beads'
G[1233623]='Clumsy Adventurer'
G[1233626]="Grizzlemaw's Bonepile"
G[1233641]='Watertight Bag'
G[1233642]="Abu'Gar's Favorite Lure"
G[1233645]='Warsong Helm'
G[1233649]="Gambler's Purse"
G[1233650]='Mangled Adventurer'
G[1233651]='Lost Pendant'
G[1233658]='Impaled Adventurer'
G[1233697]='Saberon Stash'
G[1233715]="Goldtoe's Plunder"
G[1233768]='Pale Elixir'
G[1233773]='Bag of Herbs'
G[1233792]='Pile of Rubble'
G[1233917]='Do Not Touch'
G[1233973]='Bounty of the Elements'
G[1233975]="Rooby's Roo"
G[1234054]='Warm Goren Egg'
G[1234105]='Arakkoa Archaeology Find'
G[1234106]='Ogre Archaeology Find'
G[1234147]='Lost Outcast'
G[1234154]='Misplaced Scrolls'
G[1234155]='Relics of the Outcasts'
G[1234157]='Fractured Sunstone'
G[1234159]='Lost Herb Satchel'
G[1234243]='Overly Gaudy Note'
G[1234432]='Ogron Plunder'
G[1234446]='Relics of the Outcasts'
G[1234449]='Relics of the Outcasts'
G[1234451]='Relics of the Outcasts'
G[1234456]='Shattered Hand Lockbox'
G[1234458]='Shattered Hand Cache'
G[1234461]='Toxicfang Venom'
G[1234471]='Spray-O-Matic 5000 XT'
G[1234472]="Sailor Zazzuk's 180-Proof Rum"
G[1234473]='Campaign Contributions'
G[1234474]='Saberon Stash'
G[1234618]='Gift of Anzu'
G[1234704]='Elixir of Shadow Sight'
G[1234740]='Orcish Signaling Horn'
G[1234746]='Cultist Statue'
G[1235073]='Offering to the Raven Mother'
G[1235091]='Lost Ring'
G[1235095]='Misplaced Scroll'
G[1235097]="Ephial's Dark Grimoire"
G[1235103]='Garrison Supplies'
G[1235104]='Sun-Touched Cache'
G[1235127]='Mysterious Petrified Pod'
G[1235129]='Enriched Seeds'
G[1235135]='Smuggled Apexis Artifacts'
G[1235141]='Iron Horde Explosives'
G[1235143]='Arakkoa Outcast'
G[1235168]='Arakkoa Outcast'
G[1235172]="Outcast's Belongings"
G[1235282]='Sethekk Ritual Brew'
G[1235289]="Garrison Workman's Hammer"
G[1235299]="Coinbender's Payment"
G[1235300]='Mysterious Mushrooms'
G[1235307]='Waterlogged Satchel'
G[1235310]='Shredder Parts'
G[1235313]='Abandoned Mining Pick'
G[1235365]="Admiral Taylor's Coffer"
G[1235859]="Brokor's Sack"
G[1235860]='Orc Skeleton'
G[1235869]='Canyon Boulderbreaker'
G[1235881]='Petrified Rylak Egg'
G[1236092]='Stashed Emergency Rucksack'
G[1236096]='Remains of Balldir Deeprock'
G[1236099]='Suntouched Spear'
G[1236138]='Iron Supply Chest'
G[1236139]='Explorer Canister'
G[1236140]='Goren Tunnel'
G[1236141]='Discarded Pack'
G[1236147]="Vindicator's Hammer"
G[1236149]='Seagull'
G[1236158]="Sniper's Crossbow"
G[1236169]='Harvestable Precious Crystal'
G[1236170]='Remains of Balik Orecrusher'
G[1236178]='Evermorn Supply Cache'
G[1236206]='War Planning Map'
G[1236258]='Unknown Petrified Egg'
G[1236259]='Mysterious Petrified Pod'
G[1236260]='Mysterious Petrified Pod'
G[1236264]='Forgotten Skull Cache'
G[1236265]='Aged Stone Container'
G[1236266]='Unknown Petrified Egg'
G[1236267]='Ancient Titan Chest'
G[1236483]='Gift of the Ancients'
G[1236610]="Spirit's Gift"
G[1236633]="Smuggler's Cache"
G[1236693]='Iron Horde Munitions'
G[1236715]='Odd Skull'
G[1236755]='Dusty Lockbox'
G[1236931]="Giants' Stash of Weapons"
G[1236935]='Burning Blade Cache'
G[1237016]="Wanted: Kuu'rat"
G[1237021]="Wanted: Kliaa's Stinger"
G[1237227]='Highmaul Reliquary'
G[1237263]='Stolen Goods'
G[1237453]='Unearthed Reliquary'
G[1237511]='Strange Spore'
G[1237705]="Boneseer's Cauldron"
G[1237790]="Prophet Velen's Memorial"
G[1237821]="Bladefury's Orders"
G[1237946]='Spirit Coffer'
G[1238940]='Academy Bookshelf'
G[1239067]='War Mill Work Order'
G[1239120]="Okuna Longtusk's Pack"
G[1239194]="Norana's Cache"
G[1239328]="Captain's Foot Locker"
G[1239341]='Tidestone Shard'
G[1239768]="Gutrek's Blade"
G[1239771]="Gutrek's Hilt"
G[1239772]="Gutrek's Pommel"
G[1239791]='Relic Hunting Notes'
G[1239803]='Leyscar Scuttler'
G[1239821]='Research Notes'
G[1239889]='Precision Blasting Powder'
G[1239890]='Detonators'
G[1239902]='Tanaan Planning Map'
G[1239923]="Gronnsbane's Haft"
G[1239924]="Gronnsbane's Weight"
G[1239971]='Medical Supplies'
G[1239977]='Steamcap Mushrooms'
G[1240003]='Strange Sapphire'
G[1240016]="Artificer's Journal"
G[1240033]='Dim Ley Crystal'
G[1240267]='Cracked Ley Crystal'
G[1240289]='Weathered Axe'
G[1240317]="Iskar's Tome of Shadows"
G[1240346]='Olive Sprig'
G[1240354]='Genuinely Unguarded Treasure'
G[1240543]="Stolen Captain's Chest"
G[1240547]='Orc Skull'
G[1240552]='Tidestone Core'
G[1240570]='Eye Holder'
G[1240575]='Laz-Tron Disc Reader'
G[1240577]="The Blade of Kra'nak"
G[1240580]='Jewel of Hellfire'
G[1240608]='Small Treasure Chest'
G[1240609]='Stoneblood Ravager'
G[1240616]='Frozen Supplies'
G[1240617]="Lost Sentinel's Pouch"
G[1240625]="High Priestess' Reliquary"
G[1240637]='Glimmering Treasure Chest'
G[1240638]='Disputed Treasure'
G[1240639]='Sneaky Snake'
G[1240643]='Treasure Chest'
G[1240649]='Small Treasure Chest'
G[1240655]='Glimmering Treasure Chest'
G[1240657]='Small Treasure Chest'
G[1240855]='Tome of Secrets'
G[1241128]='Unguarded Thistleleaf Treasure'
G[1241216]='Treasure Chest'
G[1241267]='Small Treasure Chest'
G[1241275]='Skyfire Medical Supplies'
G[1241433]='Forgotten Sack'
G[1241434]='Lodged Hunting Spear'
G[1241449]='Blackfang Island Cache'
G[1241450]='Crystallized Fel Spike'
G[1241504]='Polished Crystal'
G[1241521]="Snake Charmer's Flute"
G[1241522]='The Perfect Blossom'
G[1241524]='Pale Removal Equipment'
G[1241533]="Forgotten Champion's Blade"
G[1241557]='Small Treasure Chest'
G[1241560]='Bleeding Hollow Warchest'
G[1241561]='Jewel of the Fallen Star'
G[1241563]='Tormmok'
G[1241565]='Looted Bleeding Hollow Treasure'
G[1241566]='Rune Etched Femur'
G[1241599]='Strange Fruit'
G[1241600]='Discarded Helm'
G[1241601]="Scout's Belongings"
G[1241602]='Forgotten Iron Horde Supplies'
G[1241605]='Crystallized Essence of the Elements'
G[1241641]='Foxflower'
G[1241656]='Overgrown Relic'
G[1241657]='Jeweled Arakkoa Effigy'
G[1241664]='"Borrowed" Enchanted Spyglass'
G[1241666]='Mysterious Corrupted Obelisk'
G[1241671]='Forgotten Shard of the Cipher'
G[1241674]='Skull of the Mad Chief'
G[1241680]='Small Treasure Chest'
G[1241692]='Axe of the Weeping Wolf'
G[1241699]='Spoils of War'
G[1241712]="Ironbeard's Treasure"
G[1241713]='The Eye of Grannok'
G[1241714]='Stashed Iron Sea Booty'
G[1241717]='Glimmering Treasure Chest'
G[1241726]='Leystone Deposit'
G[1241742]='Leorajh'
G[1241743]='Felslate Deposit'
G[1241745]='Leorajh'
G[1241760]='Sacrificial Blade'
G[1241764]='Bleeding Hollow Looter'
G[1241775]='Brazier of Awakening'
G[1241835]='Bleeding Hollow Mushroom Stash'
G[1241841]='Looted Mystical Staff'
G[1241847]="The Commander's Shield"
G[1241848]='Dazzling Rod'
G[1241866]='Soulthorn'
G[1241870]="Ashildir's Bones"
G[1242249]='Partially Mined Apexis Crystal'
G[1242350]='Treasure Chest'
G[1242633]="Tanithria's Silkweave"
G[1242638]="Tanithria's Red Dye"
G[1242639]="Tanithria's Green Dye"
G[1242645]='Mezzkrast'
G[1242649]='Fel-Tainted Apexis Formation'
G[1242657]="Lyndras' Runic Catgut"
G[1242665]='Addie Fizzlebog'
G[1243334]='Withered Herb'
G[1243402]="Navarrogg's Cage"
G[1243639]='Siphoning Crystal'
G[1243688]='Treasure Chest'
G[1243690]='Bejeweled Egg'
G[1243693]="Dead Man's Chest"
G[1243698]='Glimmering Treasure Chest'
G[1243700]='Forsaken Battle Plans'
G[1243796]='Suspiciously Glowing Chest'
G[1243798]='Bax Freeseeker'
G[1243822]="Yotnar's Right Foot"
G[1243836]="Yotnar's Head"
G[1243852]='Radiating Apexis Shard'
G[1243860]='Gleaming Draenic Chest'
G[1243938]='Naval Equipment Blueprint: Blast Furnace'
G[1243953]='Twisted Root'
G[1244446]="Ram'Pag"
G[1244466]='Fel Portal'
G[1244473]='Thunder Totem Stolen Goods'
G[1244555]='Mysterious Dust'
G[1244559]="Helya's Altar"
G[1244628]="Taurson's Prize"
G[1244694]='Small Treasure Chest'
G[1244708]="Watcher's Journal"
G[1244774]='Aethril'
G[1244775]='Dreamleaf'
G[1244776]='Dreamleaf'
G[1244777]='Fjarnskaggl'
G[1244778]='Starlight Rose'
G[1244786]='Felwort'
G[1244829]='The Tangled Beard'
G[1244830]='Herblore of the Ancients'
G[1244912]='Small Treasure Chest'
G[1244923]='Lever'
G[1244928]='Glimmering Treasure Chest'
G[1244983]='Dirty Pocketwatch'
G[1245126]='Crystallized Ancient Mana'
G[1245245]='Vengeful Warglaive'
G[1245328]='Enchanted Scroll'
G[1245479]='Battered Chest'
G[1245507]='Supply Cache'
G[1245524]='Treasure Chest'
G[1245525]='Small Treasure Chest'
G[1245527]='Treasure Chest'
G[1245541]='Small Treasure Chest'
G[1245543]='Treasure Chest'
G[1245551]='Small Treasure Chest'
G[1245554]='Small Treasure Chest'
G[1245555]='Small Treasure Chest'
G[1245581]='Magic Broom'
G[1245688]='Shattered Burial Urn'
G[1245887]='Driftwood'
G[1245941]='Warp Cache'
G[1246037]='Mezzkrast'
G[1246205]='Quilen'
G[1246254]='Dusty Coffer'
G[1246463]="Hammer of Khaz'goroth"
G[1246465]='Tidestone of Golganneth'
G[1246522]='Fel Reaver Arm'
G[1246524]='Small Treasure Chest'
G[1246664]='Test Kitchen Results'
G[1246703]='Magical Manifest of the Moon'
G[1246710]="Nomi's Silver Mackerel"
G[1246713]='Place Telemancy Beacon'
G[1246804]='Highmountain Tauren Archaeology Find'
G[1246811]='Highborne Archaeology Find'
G[1246812]='Demonic Archaeology Find'
G[1247023]='Shadowbloom'
G[1247398]='Felsoul Keyring'
G[1247605]='Flourishing Aethril'
G[1247607]='Flourishing Fjarnskaggl'
G[1247694]="Kel'danath's Knapsack"
G[1248000]='Felwort'
G[1248001]='Savage Felbat'
G[1248002]='Felwort'
G[1248003]='Felwort'
G[1248005]='Felwort'
G[1248006]='Felwort'
G[1248007]='Felwort'
G[1248008]='Felwort'
G[1248009]='Felwort'
G[1248010]='Felwort'
G[1248011]='Felwort'
G[1248027]='Brambly Fjarnskaggl'
G[1248080]='Needle Coral'
G[1248091]="Lyndras' Threading Needles"
G[1248093]='Box of Bear Fur'
G[1248407]="Kel'danath's Manaflask"
G[1248534]='Tears of Elune'
G[1248554]='Nightborne Artifact Cache'
G[1248781]='Spotted Gloomcap'
G[1249000]='Ripe Pumpkin'
G[1249021]='Silgryn'
G[1249422]='Timeworn Jar'
G[1249514]="Dreamer's Tear"
G[1249524]='Egg of Gangamesh'
G[1249742]='Freshly Dug Grave'
G[1249827]='Highmountain Shoulderpad'
G[1249890]="Tigrid's Arkhana"
G[1250080]='Quilen'
G[1250084]='Hatecoil Riptail'
G[1250088]='Weeping Banshee'
G[1250090]='Azsuna Mana Wyrm'
G[1250104]='Hatecoil Spitespeaker'
G[1250107]='Mojodishu'
G[1250109]='Treasure Chest'
G[1250267]='Felsurge Egg'
G[1250373]='Encyclopedia Azsunica (K-M)'
G[1250383]='Moonshade Relic'
G[1250413]="Oren's Prized Possessions"
G[1250536]='Intact Greatstag Antler'
G[1250541]='Treasure Chest'
G[1250548]="Hammer of Khaz'goroth"
G[1250612]="Snaggle's Note"
G[1250903]='Large Ceremonial Drum'
G[1250904]='Medium Ceremonial Drum'
G[1250987]='Quilen'
G[1250990]='Crate of Ancient Relics'
G[1251032]='Armoire'
G[1251124]='Spiritwalker Ebonhorn'
G[1251191]='Ancient Bones'
G[1251416]='Ancient Mana Chunk'
G[1251425]='Moist Grizzlecomb'
G[1251571]='Ashilvara, Verse 1'
G[1251668]='Treasure Chest'
G[1251669]='Treasure Chest'
G[1251719]='Small Treasure Chest'
G[1251737]='Treasure Chest'
G[1251745]='Treasure Chest'
G[1251746]='Treasure Chest'
G[1251747]='Treasure Chest'
G[1251749]='Treasure Chest'
G[1251751]='Treasure Chest'
G[1251753]='Treasure Chest'
G[1251754]='Glimmering Treasure Chest'
G[1251755]='Glimmering Treasure Chest'
G[1251756]='Glimmering Treasure Chest'
G[1251757]='Glimmering Treasure Chest'
G[1251758]='Glimmering Treasure Chest'
G[1251759]='Glimmering Treasure Chest'
G[1251764]='Thankrit'
G[1251792]='Small Treasure Chest'
G[1251820]='Nether Ray'
G[1251851]='Small Treasure Chest'
G[1251870]="The Sixtriggers' Premium Stash"
G[1251954]='Small Treasure Chest'
G[1251991]='The Aegis of Aggramar'
G[1252184]='Requisitioned Seal of Fate'
G[1252258]='Leyline Feed'
G[1252408]='Ancient Mana Shard'
G[1252447]='Shimmering Ancient Mana Cluster'
G[1252448]='Shimmering Ancient Mana Cluster'
G[1252449]='Shimmering Ancient Mana Cluster'
G[1252450]='Shimmering Ancient Mana Cluster'
G[1252772]='Ancient Mana Chunk'
G[1252774]='Ancient Mana Crystal'
G[1252778]='Enslaving Infernal'
G[1252802]='Small Treasure Chest'
G[1252803]='Small Treasure Chest'
G[1252805]='Treasure Chest'
G[1252812]='Treasure Chest'
G[1252813]='Small Treasure Chest'
G[1252814]='Unpowered Telemancy Beacon'
G[1252819]='Small Treasure Chest'
G[1252820]='Small Treasure Chest'
G[1252821]='Treasure Chest'
G[1252822]='Glimmering Treasure Chest'
G[1252824]='Treasure Chest'
G[1252831]='Glimmering Treasure Chest'
G[1252832]='Small Treasure Chest'
G[1252833]='Treasure Chest'
G[1252834]='Small Treasure Chest'
G[1252837]='Treasure Chest'
G[1252838]='Treasure Chest'
G[1252839]='Small Treasure Chest'
G[1252840]='Small Treasure Chest'
G[1252841]='Small Treasure Chest'
G[1252842]='Treasure Chest'
G[1252844]='Treasure Chest'
G[1252850]='Small Treasure Chest'
G[1252860]='Small Treasure Chest'
G[1252884]='Chronarch Defender'
G[1253081]="Fruit of the Arcan'dor"
G[1253280]='Leystone Seam'
G[1253957]='Treasure Chest'
G[1254008]="Kyrtos's Research Notes"
G[1254023]='Arcane Power Unit'
G[1254128]='Treasure Chest'
G[1255341]="Llorian's Supplies"
G[1255828]='Small Treasure Chest'
G[1255829]='Small Treasure Chest'
G[1257289]='Elven Treasure Chest'
G[1257290]='Highmountain Clan Chest'
G[1257291]='Nightborne Treasure Chest'
G[1257393]='Treasure Chest'
G[1257545]='Treasure Chest'
G[1257546]='Treasure Chest'
G[1257978]='Treasure Chest'
G[1258968]="Hymdall's Cache"
G[1258979]='Fel-Ravaged Tome'
G[1260247]='Ancient Mana Chunk'
G[1260248]='Ancient Mana Shard'
G[1260249]='Ancient Mana Shard'
G[1260494]='Twice-Fortified Arcwine'
G[1260498]='Leypetal Blossom'
G[1260526]='Spoils'
G[1265435]='Doodad_7sr_hubmanatree_seedholder001'
G[1266032]='Nightborne Arms Cache'
G[1266291]='Fel Crystal'
G[1266619]='A Mysterious Note'
G[1267655]='Ravaged Supplies'
G[1267768]='Unearthed Antiquities'
G[1268534]='Curious Wyrmtongue Cache'
G[1268541]='Curious Wyrmtongue Cache'
G[1268545]='Curious Wyrmtongue Cache'
G[1268559]='Curious Wyrmtongue Cache'
G[1268564]='Curious Wyrmtongue Cache'
G[1268568]='Curious Wyrmtongue Cache'
G[1268571]='Curious Wyrmtongue Cache'
G[1268765]='Disturbed Mud'
G[1269056]='Small Treasure Chest'
G[1269065]='Small Treasure Chest'
G[1269068]='Small Treasure Chest'
G[1269075]='Small Treasure Chest'
G[1269080]='Small Treasure Chest'
G[1269278]='Fel-Encrusted Herb'
G[1269887]='Fel-Encrusted Herb Cluster'
G[1270917]='Glenbrook Register'
G[1271124]="Light's Judgment"
G[1271227]='Hidden Wyrmtongue Cache'
G[1271554]='Veiled Wyrmtongue Chest'
G[1271648]="Stolen Idol of Krag'wa"
G[1271668]='Cache of Acuity'
G[1271669]='Cache of Wit'
G[1271670]='Cache of Guile'
G[1271849]='Eredar War Supplies'
G[1271850]='Eredar War Supplies'
G[1271979]='Hearthsteed'
G[1272010]='Crystallized Memory'
G[1272179]="Mayor's Bulletin"
G[1272422]="Gentle's Spellbook"
G[1272455]='Eredar War Supplies'
G[1272456]='Eredar War Supplies'
G[1272562]='Waves of Power'
G[1272633]='Cursed Chest'
G[1272741]='Used Vial'
G[1272770]='Eredar War Supplies'
G[1272771]='Eredar War Supplies'
G[1272782]='Astral Glory'
G[1273052]='Fel-Encrusted Herb'
G[1273053]='Fel-Encrusted Herb Cluster'
G[1273274]='Congealed Void Crystal'
G[1273301]='Ancient Eredar Cache'
G[1273407]='High Exarch Turalyon'
G[1273412]='Ancient Eredar Cache'
G[1273414]='Ancient Eredar Cache'
G[1273439]='Ancient Eredar Cache'
G[1273443]='Void-Seeped Cache'
G[1273523]='Legion War Supplies'
G[1273524]='Legion War Supplies'
G[1273527]='Felfang Basilisk'
G[1273528]='Legion War Supplies'
G[1273533]='Legion War Supplies'
G[1273535]='Legion War Supplies'
G[1273814]='Bladed Charm'
G[1273833]="Heart of Nhal'athoth"
G[1275099]='Saurolisk Egg'
G[1276226]='Void-Tinged Chest'
G[1276228]="Desperate Eredar's Cache"
G[1276230]="Doomseeker's Treasure"
G[1276254]="Beginner's Guide to Archaeology"
G[1276487]='Intact Mudfish'
G[1276488]='Azerite Cannonball'
G[1276513]='Intact Mudfish'
G[1276515]='Fishing Rod'
G[1276616]='Magic Broom'
G[1276617]='Storm Silver Deposit'
G[1276618]='Platinum Deposit'
G[1276619]='Monelite Seam'
G[1276621]='Rich Monelite Deposit'
G[1276622]='Rich Storm Silver Deposit'
G[1276623]="Warlord's Deathwheel"
G[1276735]='Offerings of the Chosen'
G[1276837]='Recipe Rock'
G[1277199]='Weatherd Job List'
G[1277323]='Tome of Silver and Ash'
G[1277336]='Treasure Chest'
G[1277348]='Hati'
G[1277373]='Glimmering Seaweed'
G[1277459]='Pig Effigy'
G[1277561]="Warlord's Cache"
G[1277637]='Void-Seeped Cache'
G[1277715]='Cursed Nazmani Chest'
G[1277885]="Wunja's Trove"
G[1278252]='Job Flyer'
G[1278313]='Sternly Worded Letter'
G[1278342]='Pristine Phylactery'
G[1278436]='Shipwrecked Chest'
G[1278437]='Offering to Bwonsamdi'
G[1278456]='Treasure Chest'
G[1278459]='Treasure Chest'
G[1278460]='Treasure Chest'
G[1278461]='Treasure Chest'
G[1278462]='Treasure Chest'
G[1278585]='Cursed Effigy'
G[1278669]='Fallhaven Ledger'
G[1278694]='Treasure Chest'
G[1278713]='Treasure Chest'
G[1278716]='Treasure Chest'
G[1278793]='Treasure Chest'
G[1278808]='Gryphon Nest'
G[1279042]="Smuggler's Stash"
G[1279253]="Lucky Horace's Lucky Chest"
G[1279260]='"Cleverly" Disguised Chest'
G[1279299]='Venomous Seal'
G[1279325]='Treasure Chest'
G[1279337]='Heartsbane Grimoire'
G[1279366]='Treasure Chest'
G[1279367]='Treasure Chest'
G[1279378]='Treasure Chest'
G[1279379]='Treasure Chest'
G[1279388]="Lucille's Pack"
G[1279609]='Spoils of Pandaria'
G[1279689]='Lost Nazmani Treasure'
G[1279705]='Offering Vessel'
G[1279750]='Hay Covered Chest'
G[1280347]="Scroll of Fate's Hand"
G[1280480]='Titan Keeper Data Core'
G[1280504]='Swallowed Chest'
G[1280522]='Partially-Digested Treasure'
G[1280576]='Encased Scroll'
G[1280619]='Old Ironbound Chest'
G[1280727]='Charred Note'
G[1280736]='Bee Hive'
G[1280948]='Legion Outhouse'
G[1280951]='Ashvane Spoils'
G[1281092]="Witch Doctor's Hoard"
G[1281137]='Assorted Salvage'
G[1281176]="Jani's Stash"
G[1281230]='Formal Invitation'
G[1281305]='Slagshot Slammer'
G[1281348]='Crumbling Letter'
G[1281379]='Aromatic Onion'
G[1281387]='Blasting Powder'
G[1281388]="Jani's Stash"
G[1281390]="Jani's Stash"
G[1281397]='Cutwater Treasure Chest'
G[1281494]='Frosty Treasure Chest'
G[1281551]='Help Wanted Poster'
G[1281646]='Honey Vat'
G[1281647]='Posted Notice'
G[1281655]='Gift of the Brokenhearted'
G[1281673]="Corlain Citizen's Journal"
G[1281718]='HELP WANTED'
G[1281898]="Dazar's Forgotten Chest"
G[1281903]='Treasure Chest'
G[1282153]='Sunken Strongbox'
G[1282389]='Forgotten Bones'
G[1282432]='Rug'
G[1282448]='Wanted Poster'
G[1282457]='Unfinished Brambleguard Totem'
G[1282478]='Empty Crate'
G[1282662]="Assassin's Orders"
G[1282666]='Urn of Agussu'
G[1282721]='Treasure Chest'
G[1282722]='Treasure Chest'
G[1284448]="Hidden Scholar's Chest"
G[1284454]="Da White Shark's Bounty"
G[1284455]="The Exile's Lament"
G[1286016]="Ship's Log"
G[1286953]='Rod of Tides'
G[1287189]='Wanted: Dangerous Beasts'
G[1287228]='Wanted: Dark Chronicler'
G[1287232]='Scouting Report'
G[1287239]="Grayal's Last Offering"
G[1287304]="Lost Explorer's Bounty"
G[1287318]='Sandfury Reserve'
G[1287320]='Stranded Cache'
G[1287324]="Excavator's Greed"
G[1287326]="Zem'lan's Buried Treasure"
G[1287327]='Scouting Report'
G[1287463]='Old Ship Part'
G[1287958]='Bulletin Board'
G[1288157]="WANTED: Yarsel'ghun"
G[1288167]="Marie's Package"
G[1288214]='Wanted Poster'
G[1288475]='Firelands Slag'
G[1288596]='Cache of Secrets'
G[1288622]='WANTED: Sister Lilias'
G[1288641]="WANTED: Gryphon 'Nappers"
G[1288646]='Prickly Pear'
G[1289310]='WANTED: Living Earthguard'
G[1289313]='WANTED: The Hornet'
G[1289317]='Seaweed'
G[1289361]='WANTED: Quartermaster Ssylis'
G[1289365]='Wanted Poster'
G[1289647]='Weathered Treasure Chest'
G[1290138]='Bot Buster Bomb'
G[1290419]='Wanted Poster'
G[1290537]='Help Wanted'
G[1290725]="Riches of Tor'nowa"
G[1290765]='Large Pile of Gold'
G[1290770]='Treasure Chest'
G[1290820]='River Carnations'
G[1290993]='Irontide Loot'
G[1292408]='Mountain of Bacon'
G[1292523]='Wanted Poster'
G[1292673]='A Damp Scroll'
G[1292674]='A Damp Scroll'
G[1292675]='A Damp Scroll'
G[1292676]='A Damp Scroll'
G[1292677]='A Damp Scroll'
G[1292686]='Ominous Altar'
G[1292783]='Zandalari Water Jugs'
G[1293349]='Discarded Lunchbox'
G[1293350]='Carved Wooden Chest'
G[1293568]='Wanted Poster'
G[1293852]='Buried Treasure Chest'
G[1293880]='Buried Treasure Chest'
G[1293881]='Buried Treasure Chest'
G[1293884]='Buried Treasure Chest'
G[1293962]='Precarious Noble Cache'
G[1293964]="Forgotten Smuggler's Stash"
G[1293965]='Scrimshaw Cache'
G[1293985]='Wanted: War Gore'
G[1294173]='Venture Co. Supply Chest'
G[1294174]='Forgotten Chest'
G[1294316]='Lost Offerings of Kimbul'
G[1294317]='Deadwood Chest'
G[1294319]='Sandsunken Treasure'
G[1296574]="Ian's Empty Bottle"
G[1296583]="Navarro's Flask"
G[1296584]="Zach's Canteen"
G[1297071]='Tiny Coin Purse'
G[1297492]='Bulletin Board'
G[1297825]='Web-Covered Chest'
G[1297828]="Merchant's Chest"
G[1297878]='Hexed Chest'
G[1297879]='Bespelled Chest'
G[1297880]='Ensorcelled Chest'
G[1297881]='Enchanted Chest'
G[1297891]='Runebound Cache'
G[1297892]='Runebound Chest'
G[1297893]='Runebound Coffer'
G[1298920]='Stolen Thornspeaker Cache'
G[1303039]='Curious Grain Sack'
end
if release >= 28153 then
G[-1800895]='NukeMe -1800895'
G[-1240896]='NukeMe -1240896'
G[-1020942]='NukeMe -1020942'
G[-970942]='NukeMe -970942'
G[-740641]='NukeMe -740641'
G[134310]='NukeMe 134310'
G[1293119]='Seaweed'
end
-- End of localized NPC names
|
local Logger = require("utils.logger")
require("utils.helpers")
local ChassisDealer = require("screenplays.space.chassis_dealer")
chassis_dealer_conv_handler = conv_handler:new {}
function chassis_dealer_conv_handler:runScreenHandlers(pConvTemplate, pPlayer, pNpc, selectedOption, pConvScreen)
local screen = LuaConversationScreen(pConvScreen)
local screenID = screen:getScreenID()
if (screenID == "chassis_dealer_buy_chassis") then
local suiManager = LuaSuiManager()
local options = ChassisDealer:getValidBlueprints(pPlayer)
if (#options <= 0) then
pConvScreen = screen:cloneScreen()
local clonedConversation = LuaConversationScreen(pConvScreen)
clonedConversation:setDialogTextTO("@chassis_npc:no_deeds")
return pConvScreen
end
suiManager:sendListBox(pPlayer, pPlayer, "@chassis_npc:buy_ship_title", "@chassis_npc:buy_ship_prompt", 2, "@cancel", "", "@ok", "chassis_dealer_conv_handler", "purchaseChassisConfirmation", 32, options)
elseif (screenID == "chassis_dealer_sell_components") then
-- TODO: Get looted components...
pConvScreen = screen:cloneScreen()
local clonedConversation = LuaConversationScreen(pConvScreen)
clonedConversation:setDialogTextTO("@conversation/chassis_npc:s_3310c404")
return pConvScreen
end
return pConvScreen
end
function chassis_dealer_conv_handler:purchaseChassisConfirmation(pPlayer, pSui, eventIndex, arg0)
local cancelPressed = (eventIndex == 1)
if (cancelPressed) then
return
end
local pInventory = SceneObject(pPlayer):getSlottedObject("inventory")
local suiManager = LuaSuiManager()
local selection = arg0 + 1
-- TODO CHECKS: Too many ships, no money, too many POB ships, inventory full.
local possibleBlueprints = ChassisDealer:getValidBlueprints(pPlayer)
local selectedBluePrint = possibleBlueprints[selection][1]
local path = ChassisDealer:getPathByName(selectedBluePrint)
if (path == nil or pInventory == nil) then
CreatureObject(pPlayer):sendSystemMessage("@chassis_npc:failed")
else
local pBlueprint = getContainerObjectByTemplate(pInventory, path, true)
suiManager:sendMessageBox(pBlueprint, pPlayer, "@chassis_npc:confirm_transaction", "@chassis_npc:can_use", "@chassis_npc:btn_buy", "chassis_dealer_conv_handler", "purchaseChassis")
end
-- TODO: Add in certs...
end
function chassis_dealer_conv_handler:purchaseChassis(pPlayer, pSui, eventIndex, arg0)
local cancelPressed = (eventIndex == 1)
if (pPlayer == nil or pSui == nil or cancelPressed) then
return
end
local pInventory = SceneObject(pPlayer):getSlottedObject("inventory")
if (pInventory == nil) then
return
end
local suiBox = LuaSuiBox(pSui)
local pUsingObject = suiBox:getUsingObject()
if (pUsingObject == nil) then
return
end
local deedPath = SceneObject(pUsingObject):getTemplateObjectPath()
local chassis = ChassisDealer:getChassisFromBlueprint(deedPath)
if (chassis ~= nil) then
local pChassis = giveItem(pInventory, chassis, -1)
if (pChassis ~= nil) then
SceneObject(pChassis):sendTo(pPlayer)
CreatureObject(pPlayer):sendSystemMessage("@chassis_npc:bought_chassis")
end
SceneObject(pUsingObject):destroyObjectFromWorld()
SceneObject(pUsingObject):destroyObjectFromDatabase()
end
end
|
fx_version 'bodacious'
game 'gta5'
client_script "client-side/*"
server_script "server-side/*" |
Locales ['pl'] = {
['press_button'] = "Naciśnij ~INPUT_CONTEXT~, aby zakupić lub sprawdzić swoje ubezpieczenie",
['ins_time'] = "~g~Twoje ubezpieczenie %s jest ważne do %s",
['buy_ins'] = "Zakup ubezpieczenia %s",
['3_days'] = "3 dni (5000$)",
['7_days'] = "7 dni (10000$)",
['14_days'] = "14 dni (20000$)",
['31_days'] = "31 dni (40000$)",
['insurance'] = "Ubezpieczenie %s",
['not_enought'] = "~r~Nie masz wystarczającej ilości pieniędzy!",
['bought_ins'] = "~g~Zakupiono ubezpieczenie %s na %s dni"
}
|
function Devour( keys )
local caster = keys.caster
local target = keys.target
local ability = keys.ability
local modifier = keys.modifier
ability:ApplyDataDrivenModifier(caster, caster, "modifier_doom_bringer_devour_arena", nil)
caster:SetModifierStackCount("modifier_doom_bringer_devour_arena", caster, target:GetMaxHealth() * ability:GetLevelSpecialValueFor("stolen_health_pct", ability:GetLevel() - 1) * 0.01)
caster:CalculateStatBonus(true)
local gold = math.max(ability:GetLevelSpecialValueFor("min_bonus_gold", ability:GetLevel() - 1), ((target:GetMinimumGoldBounty() + target:GetMaximumGoldBounty()) / 2) * ability:GetLevelSpecialValueFor("bonus_gold_pct", ability:GetLevel() - 1) * 0.01)
Gold:AddGoldWithMessage(caster, gold)
target:SetMinimumGoldBounty(0)
target:SetMaximumGoldBounty(0)
target:Kill(ability, caster)
--[[
local devour_table = {} --TODO
if devour_table[target:GetUnitName()] then
local ability1 = "doom_bringer_empty1"
local ability2 = "doom_bringer_empty2"
if ability.DevourAbilities then
ability1 = ability.DevourAbilities[1]
ability2 = ability.DevourAbilities[2]
end
local creep1 = target:GetAbilityByIndex(0)
local creep2 = target:GetAbilityByIndex(1)
if creep1 then
ability.DevourAbilities[1] = creep1:GetAbilityName()
local caster1 = ReplaceAbilities(caster, ability1, ability.DevourAbilities[1], false, false)
caster1:SetLevel(creep1:GetLevel())
else
ReplaceAbilities(caster, ability.DevourAbilities[1], "doom_bringer_empty1", false, false)
ability.DevourAbilities[1] = nil
end
if creep2 then
ability.DevourAbilities[2] = creep2:GetAbilityName()
local caster2 = ReplaceAbilities(caster, ability1, ability.DevourAbilities[2], false, false)
caster2:SetLevel(creep2:GetLevel())
else
ReplaceAbilities(caster, ability.DevourAbilities[2], "doom_bringer_empty2", false, false)
ability.DevourAbilities[2] = nil
end
end]]
end
|
--[[
Copyright (c) 2022, Vsevolod Stakhov <[email protected]>
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 argparse = require "argparse"
-- Define command line options
local parser = argparse()
:name "rspamadm template"
:description "Apply jinja templates for strings/files"
:help_description_margin(30)
parser:argument "file"
:description "File to process"
:argname "<file>"
:args "*"
parser:flag "-n --no-vars"
:description "Don't add Rspamd internal variables"
parser:option "-e --env"
:description "Load additional environment vars from specific file (name=value)"
:argname "<filename>"
:count "*"
parser:option "-l --lua-env"
:description "Load additional environment vars from specific file (lua source)"
:argname "<filename>"
:count "*"
parser:mutex(
parser:option "-s --suffix"
:description "Store files with the new suffix"
:argname "<suffix>",
parser:flag "-i --inplace"
:description "Replace input file(s)"
)
local lua_util = require "lua_util"
local function set_env(opts, env)
if opts.env then
for _,fname in ipairs(opts.env) do
for kv in assert(io.open(fname)):lines() do
if not kv:match('%s*#.*') then
local k,v = kv:match('([^=%s]+)%s*=%s*(.+)')
if k and v then
env[k] = v
else
io.write(string.format('invalid env line in %s: %s\n', fname, kv))
end
end
end
end
end
if opts.lua_env then
for _,fname in ipairs(opts.env) do
local ret,res_or_err = pcall(loadfile(fname))
if not ret then
io.write(string.format('cannot load %s: %s\n', fname, res_or_err))
else
if type(res_or_err) == 'table' then
for k,v in pairs(res_or_err) do
env[k] = lua_util.deepcopy(v)
end
else
io.write(string.format('cannot load %s: not a table\n', fname))
end
end
end
end
end
local function read_file(file)
local content
if file == '-' then
content = io.read("*all")
else
local f = assert(io.open(file, "rb"))
content = f:read("*all")
f:close()
end
return content
end
local function handler(args)
local opts = parser:parse(args)
local env = {}
set_env(opts, env)
if not opts.file or #opts.file == 0 then opts.file = {'-'} end
for _,fname in ipairs(opts.file) do
local content = read_file(fname)
local res = lua_util.jinja_template(content, env, opts.no_vars)
if opts.inplace then
local nfile = string.format('%s.new', fname)
local out = assert(io.open(nfile, 'w'))
out:write(content)
out:close()
os.rename(nfile, fname)
elseif opts.suffix then
local nfile = string.format('%s.%s', opts.suffix)
local out = assert(io.open(nfile, 'w'))
out:write(content)
out:close()
else
io.write(res)
end
end
end
return {
handler = handler,
description = parser._description,
name = 'template'
} |
resource_manifest_version "44febabe-d386-4d18-afbe-5e627f4af937"
server_scripts {
"ac_s.lua",
}
client_scripts {
"ac_c.lua",
} |
-- spec script. should NOT be bundled with final game.
-- for lib/list.lua
--
require( "spec.spec_helper" )
List = require( 'list' )
describe( "List", function()
describe( "#new", function()
context( "when no initial values specified", function()
it( "sets first to 0", function()
local q = List:new()
assert.is.equal( 0, q.first )
end)
it( "sets last to -1", function()
local q = List:new()
assert.is.equal( -1, q.last )
end)
end)
context( "when initial items specified", function()
local items = { 'foo', 'bar', 3, 'qux' }
it( "sets first to 0", function()
local q = List:new( unpack( items ) )
assert.is.equal( 0, q.first )
end)
it( "sets last to length minus 1", function()
local q = List:new( unpack( items ) )
assert.is.equal( #items - 1, q.last )
end)
it( "is initialized with those items", function()
local q = List:new( unpack( items ) )
local r1 = q[ q.first ]
local r2 = q[ q.last ]
assert.is.same( 'foo', r1 )
assert.is.same( 'qux', r2 )
end)
end)
end)
describe( "#push", function()
context( "when pushing a nil", function()
local q = List:new( 'foo', 'bar' )
local old_first = q.first
local old_last = q.last
it( "doesn't change .first", function()
q:push( nil )
assert.is_equal( old_first, q.first )
end)
it( "doesn't change .last", function()
q:push( nil )
assert.is_equal( old_last, q.last )
end)
end)
context( "when pushing an integer", function()
local q = List:new()
local item = 12
it( "increments last", function()
q:push( item )
assert.is.equal( 0, q.last )
end)
it( "adds it to the end of the list", function()
local expected = item
q:push( item )
local result = q[ q.last ]
assert.is.same( expected, result )
end)
end)
context( "when pushing a table", function()
local q = List:new()
local item = { foo = 'bar', [9] = 'ok' }
it( "increments last", function()
q:push( item )
assert.is.equal( 0, q.last )
end)
it( "adds it to the end of the list", function()
local expected = item
q:push( item )
local result = q[ q.last ]
assert.is.same( expected, result )
end)
end)
end)
describe( "#pop", function()
context( "when list is empty", function()
local q = List:new()
local old_first = q.first
local old_last = q.last
it( "returns nil", function()
local result = q:pop()
assert.is_nil( result )
end)
it( "doesn't change .first", function()
q:pop()
assert.is_equal( old_first, q.first )
end)
it( "doesn't change .last", function()
q:pop()
assert.is_equal( old_last, q.last )
end)
end)
context( "when list has multiple items", function()
it( "pops entries correctly", function()
local q = List:new( 12, 'asd', 43 )
local expected = 43
local result = q:pop()
assert.is.same( expected, result )
end)
it( "updates .first", function()
local q = List:new( 12, 'asd', 43 )
q:pop()
assert.is_equal( 0, q.first )
end)
it( "updates .last", function()
local q = List:new( 12, 'asd', 43 )
q:pop()
assert.is_equal( 1, q.last )
end)
end)
end)
describe( "#shift", function()
context( "when list is empty", function()
local q = List:new()
local old_first = q.first
local old_last = q.last
it( "returns nil", function()
local result = q:shift()
assert.is_nil( result )
end)
it( "doesn't change .first", function()
q:shift()
assert.is_equal( old_first, q.first )
end)
it( "doesn't change .last", function()
q:shift()
assert.is_equal( old_last, q.last )
end)
end)
context( "when list has multiple items", function()
it( "returns the first value", function()
local q = List:new( 12, 'asd', 43, 7 )
local expected = 12
local result = q:shift()
assert.is.same( expected, result )
end)
it( "updates .first", function()
local q = List:new( 12, 'asd', 43, 7 )
local old_first = q.first
q:shift()
assert.is_equal( old_first + 1, q.first )
end)
it( "doesn't change .last", function()
local q = List:new( 12, 'asd', 43, 7 )
local old_last = q.last
q:shift()
assert.is_equal( old_last, q.last )
end)
end)
end)
describe( "#unshift", function()
context( "when list is empty", function()
local q = List:new()
it( "places the item at the start of the list", function()
local expected = 'asd'
q:unshift( 'asd' )
local result = q[ q.first ]
assert.is.same( expected, result )
end)
end)
context( "when list has items", function()
local q = List:new( 12, 'foo' )
it( "places the item at the start of the list", function()
local expected = 'asd'
q:unshift( 'asd' )
local result = q[ q.first ]
assert.is.same( expected, result )
end)
it( "doesn't change last", function()
local expected = 'foo'
q:unshift( 'asd' )
local result = q[ q.last ]
assert.is.same( expected, result )
end)
end)
end)
describe( "#length", function()
context( "when list is empty", function()
local q = List:new()
it( "returns 0", function()
local result = q:length()
assert.is.equal( 0, result )
end)
end)
context( "when list is short", function()
local q = List:new( 'foo', 'bar', 'baz' )
it( "counts a short list correctly", function()
local result = q:length()
assert.is.same( 3, result )
end)
end)
context( "when list has been modified", function()
local q = List:new()
for _ = 1, 20 do
q:push( 'foo' )
end
for _ = 1, 3 do
q:shift()
q:pop()
end
q:push( 'bar' )
it( "returns the expected length", function()
local expected = 15
local result = q:length()
assert.is.same( expected, result )
end)
end)
end)
describe( "#isEmpty", function()
context( "when list is empty", function()
local q = List:new()
it( "returns true", function()
local result = q:isEmpty()
assert.is_true( result )
end)
end)
context( "when list is non-empty", function()
local q = List:new( 4, 2, 7 )
it( "returns false", function()
local result = q:isEmpty()
assert.is_false( result )
end)
end)
context( "when list has been emptied", function()
local q = List:new()
q:push( 'foo' )
q:push( 'bar' )
q:pop()
q:pop()
it( "returns true", function()
local result = q:isEmpty()
assert.is_true( result )
end)
end)
end)
describe( "#get", function()
context( "when list is empty", function()
local q = List:new()
it( "returns nil", function()
local result = q:get()
assert.is_nil( result )
end)
end)
context( "when list is not empty", function()
local q = List:new( 'foo', 'bar', 'baz' )
context( "when index is 0", function()
local index = 0
it( "returns nil", function()
assert.is_nil( q:get( index ) )
end)
end)
context( "when index is beyond the end of the list", function()
local index = 200
it( "returns nil", function()
assert.is_nil( q:get( index ) )
end)
end)
context( "when index is within the list", function()
local index = 2
it( "returns the value from that list position", function()
local expected = "bar"
assert.is_equal( expected, q:get( index ) )
end)
end)
end)
end)
describe( "#entries", function()
context( "when list is empty", function()
local q = List:new()
it( "returns an empty array", function()
assert.are_same( {}, q:entries() )
end)
end)
context( "when list has content", function()
context( "when list hasn't been modified", function()
local q = List:new( "foo", "bar", "baz" )
it( "returns an empty array", function()
assert.are_same( { "foo", "bar", "baz" }, q:entries() )
end)
end)
context( "when list has been modified", function()
local q = List:new( "foo", "bar", "baz" )
it( "still returns the full list", function()
q:shift()
q:push( "qux" )
assert.are_same( { "bar", "baz", "qux" }, q:entries() )
end)
end)
end)
end)
end)
|
--鉄獣の戦線
--
--Script by JustFish
function c101102052.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--disable spsummon
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetRange(LOCATION_SZONE)
e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetTargetRange(1,0)
e2:SetTarget(c101102052.splimit)
c:RegisterEffect(e2)
--search
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(101102052,0))
e3:SetCategory(CATEGORY_SEARCH+CATEGORY_TOHAND)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_SZONE)
e3:SetCountLimit(1,101102052)
e3:SetCost(c101102052.srcost)
e3:SetTarget(c101102052.srtg)
e3:SetOperation(c101102052.srop)
c:RegisterEffect(e3)
--attacklimit
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(101102052,1))
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetProperty(EFFECT_FLAG_DELAY)
e4:SetCode(EVENT_DESTROYED)
e4:SetCondition(c101102052.limcon)
e4:SetOperation(c101102052.limop)
c:RegisterEffect(e4)
end
function c101102052.splimit(e,c)
return c:IsLocation(LOCATION_EXTRA) and not c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST)
end
function c101102052.cfilter(c,tp)
return c:IsType(TYPE_MONSTER) and c:IsAbleToGraveAsCost()
and Duel.IsExistingMatchingCard(c101102052.srfilter,tp,LOCATION_DECK,0,1,nil,c:GetOriginalRace())
end
function c101102052.srfilter(c,race)
return c:IsSetCard(0x24f) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand() and c:GetOriginalRace()~=race
end
function c101102052.srcost(e,tp,eg,ep,ev,re,r,rp,chk)
e:SetLabel(100)
return true
end
function c101102052.srtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
if e:GetLabel()~=100 then return false end
e:SetLabel(0)
return Duel.IsExistingMatchingCard(c101102052.cfilter,tp,LOCATION_HAND+LOCATION_MZONE,0,1,nil,tp)
end
local g=Duel.SelectMatchingCard(tp,c101102052.cfilter,tp,LOCATION_HAND+LOCATION_MZONE,0,1,1,nil,tp)
e:SetLabel(g:GetFirst():GetOriginalRace())
Duel.SendtoGrave(g,REASON_COST)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c101102052.srop(e,tp,eg,ep,ev,re,r,rp)
local race=e:GetLabel()
if race==0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c101102052.srfilter,tp,LOCATION_DECK,0,1,1,nil,race)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
function c101102052.limcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return rp==1-tp and c:IsReason(REASON_EFFECT) and c:GetPreviousControler()==tp and c:IsPreviousLocation(LOCATION_SZONE)
and Duel.GetTurnPlayer()==1-tp and aux.bpcon()
end
function c101102052.limop(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_ATTACK_ANNOUNCE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(0,1)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
|
--------------------------------------------------------------------------------
local _ = require 'cherry.libs.underscore'
local Text = {}
-- displayCounter --> counter
--------------------------------------------------------------------------------
function Text.embossed(options)
local _text =
display.newEmbossedText(
{
parent = options.parent,
text = options.text,
x = options.x,
y = options.y,
align = options.align or 'center',
width = options.width,
height = options.height,
font = options.font,
fontSize = options.fontSize
}
)
local color =
options.color or
{
highlight = {r = 1, g = 1, b = 1},
shadow = {r = 0.3, g = 0.3, b = 0.3}
}
_text:setEmbossColor(color)
return _text
end
function Text.simple(options)
if (options.parent == nil) then
return nil
end
if (options.text == nil) then
return nil
end
local _text =
display.newText(
{
parent = options.parent,
text = options.text,
x = options.x,
y = options.y,
align = options.align or 'center',
width = options.width,
font = options.font,
fontSize = options.fontSize
}
)
_text:setFillColor(options.color)
return _text
end
function Text.curve(options)
local curvedText = display.newGroup()
local circleSize = options.curveSize or 250
local step = options.fontSize * (0.33 / #options.text)
for i = 1, #options.text do
local angleDegrees = (i - (#options.text + 1.5) / 2) * step - 90
local angleRadians = math.rad(angleDegrees)
local color = {
highlight = {r = 0.2, g = 0.2, b = 0.2},
shadow = {r = 0.2, g = 0.2, b = 0.2}
}
local sprite =
Text.embossed(
{
parent = curvedText,
text = options.text:sub(i, i),
x = 0,
y = 0,
font = options.font,
fontSize = 65,
color = color
}
)
sprite.x = options.x + math.cos(angleRadians) * circleSize
sprite.y = options.y + math.sin(angleRadians) * circleSize
sprite.rotation = 90 + angleDegrees -- or maybe minus this or plus 90...
end
options.parent:insert(curvedText)
return curvedText
end
--------------------------------------------------------
function Text.counter(numToReach, writer, anchorX, anchorY, x, next, nextMillis)
writer.currentDisplay = writer.currentDisplay or 0
writer.x = x
writer.anchorX = anchorX
writer.anchorY = anchorY
timer.performWithDelay(
25,
function()
local ratio = (4 * numToReach) / (numToReach - writer.currentDisplay)
local toAdd = math.floor(numToReach / ratio)
if (toAdd == 0) then
toAdd = 1
end
writer.currentDisplay = math.round(writer.currentDisplay + toAdd)
if (writer.currentDisplay >= numToReach) then
writer.currentDisplay = math.round(numToReach)
writer.text = writer.currentDisplay
if (next) then
next()
end
else
nextMillis = 100 / (numToReach - writer.currentDisplay)
Text.counter(numToReach, writer, anchorX, anchorY, x, next, nextMillis)
end
end
)
end
--------------------------------------------------------------------------------
function Text.appearFromSides(leftMessage, rightMessage, options)
options =
_.defaults(
options,
{
y = display.contentHeight * 0.25,
color = 'ffffff',
fontSize = 45
}
)
local leftText =
display.newText(
{
parent = options.parent,
text = leftMessage,
x = -display.contentWidth * 0.5,
y = options.y,
font = _G.FONTS.default,
fontSize = options.fontSize,
color = options.color
}
)
local rightText =
display.newText(
{
parent = options.parent,
text = rightMessage,
x = display.contentWidth * 1.5,
y = options.y,
font = _G.FONTS.default,
fontSize = options.fontSize,
color = options.color
}
)
leftText.anchorX = 1
rightText.anchorX = 0
local widthDiff = (rightText.width - leftText.width) * 0.5
local center = display.contentWidth * 0.5 - widthDiff
transition.to(
leftText,
{
time = 600,
x = center - 10,
transition = easing.outBack,
onComplete = function()
transition.to(
leftText,
{
delay = options.delay or 750,
time = 750,
alpha = 0,
onComplete = function()
display.remove(leftText)
end
}
)
end
}
)
transition.to(
rightText,
{
time = 600,
x = center + 10,
transition = easing.outBack,
onComplete = function()
transition.to(
rightText,
{
delay = options.delay or 750,
time = 750,
alpha = 0,
onComplete = function()
display.remove(rightText)
end
}
)
end
}
)
end
--------------------------------------------------------------------------------
return Text
|
---@module fimbul.v35.spell_template
local spell_template = {}
function spell_template:new(y)
local neu = y or {}
setmetatable(neu, self)
self.__index = self
neu.templatetype = "spell"
return neu
end
return spell_template
|
tmr.alarm(0, 1000, 0, function()
dofile("wifi-connect.lua");
dofile("water-tank.lua");
end)
|
--[[
********************************************************************************
Project owner: RageQuit community
Project name: GTW-RPG
Developers: Mr_Moose
Source code: https://github.com/404rq/GTW-RPG/
Bugtracker: https://discuss.404rq.com/t/issues
Suggestions: https://discuss.404rq.com/t/development
Version: Open source
License: BSD 2-Clause
Status: Stable release
********************************************************************************
]]--
local timer = nil
local text = ""
local text2 = ""
local messages = { }
local r,g,b = 255,255,255
local isColorCoded = false
function hpm(message, red, green, blue, colorCoded)
if colorCoded == nil then
colorCoded = false
end
text = message
r = red
g = green
b = blue
isColorCoded = colorCoded
-- Fix the ability to set the same
-- message twice with anti spam included
if isTimer( timer ) then
killTimer( timer )
end
timer = setTimer( function() text = "" end, 10000, 1 )
-- Play notification sound
playSound("sound/beep.mp3")
end
addEvent("GTWhelp.onTextAdd", true)
addEventHandler("GTWhelp.onTextAdd", root, hpm)
addEventHandler("onClientRender", root, function( )
local tick = getTickCount ( )
local sx,sy = guiGetScreenSize ( )
if ( text ~= text2 and text ~= "" ) then
table.insert ( messages, { text, true, tick + 7000, 170, r, g, b, isColorCoded })
end
text2 = text
if ( #messages > 7 ) then
table.remove ( messages, 1 )
end
for index, data in ipairs ( messages ) do
local v1 = data[1]
local v2 = data[2]
local v3 = data[3]
local v4 = data[4]
local v5 = data[5]
local v6 = data[6]
local v7 = data[7]
local v8 = data[8]
dxDrawRectangle( sx/2 - 100, sy-((-101)+(index*100)), 200, 100, tocolor( 0, 0, 0, v4 ) )
dxDrawText( v1, sx/2, (-100)+(index*46), sx/2, 0, tocolor( v5, v6, v7, v4+75 ), 0.7, "bankgothic", "center", "center", false, true, false, v8 )
if ( tick >= v3 ) then
messages[index][4] = v4-2
if ( v4 <= 1 ) then
table.remove ( messages, index )
end
end
end
end)
|
local M = {}
local levels = vim.log.levels
local uv = vim.loop
-- vim.notify wrappers
M.notify = {}
M.notify.info = function(message)
vim.notify(message, levels.INFO, { title = "workspaces.nvim" })
end
M.notify.warn = function(message)
vim.notify(message, levels.WARN, { title = "workspaces.nvim" })
end
M.notify.err = function(message)
vim.notify(message, levels.ERROR, { title = "workspaces.nvim" })
end
-- system dependent path separator from plenary.nvim
M.path = {}
M.path.sep = (function()
if jit then
local os = string.lower(jit.os)
if os == "linux" or os == "osx" or os == "bsd" then
return "/"
else
return "\\"
end
else
return package.config:sub(1, 1)
end
end)()
M.path.basename = function(path_str)
-- remove ending /
if string.sub(path_str, #path_str, #path_str) == M.path.sep then
path_str = string.sub(path_str, 1, #path_str - 1)
end
local parts = vim.split(path_str, M.path.sep)
return parts[#parts]
end
-- read a file into a string (synchronous)
M.file = {}
M.file.read = function(path)
local fd = uv.fs_open(path, "r", 438)
if not fd then return nil end
local stat = assert(uv.fs_fstat(fd))
local data = assert(uv.fs_read(fd, stat.size, 0))
assert(uv.fs_close(fd))
return data
end
-- write a string to a file (synchronous)
M.file.write = function(path, data)
local fd = assert(uv.fs_open(path, "w", 438))
assert(uv.fs_write(fd, data, 0))
end
return M
|
project "lua_gl"
language "C"
files { "luagl/src/**.cpp" , "luagl/src/**.c" , "luagl/src/**.h" , "luagl/include/**.h" ,}
-- "freeglut/src/**.cpp" , "freeglut/src/**.c" , "freeglut/src/**.h" , "freeglut/include/**.h" }
excludes{ "src/Interpreter.c" , }
links { "lib_lua" }
--defines "FREEGLUT_STATIC"
if WINDOWS then
links { "opengl32" , "glu32" }
links "gdi32"
links "winmm"
-- defines "FREEGLUT_LIB_PRAGMAS=0"
-- defines ""
else -- nix
links { "GL" }--, "GLU" }
defines "HAVE_FCNTL_H=1"
end
includedirs { ".", "luagl/src" , "luagl/include" }--, "freeglut/src" , "freeglut/include" , "freeglut/include/GL" }
KIND{kind="lua",name="gl",luaopen="luagl"}
|
function findRotation(x1,y1,x2,y2)
local t = -math.deg(math.atan2(x2-x1,y2-y1))
if t < 0 then t = t + 360 end
return t
end
function getPointFromDistanceRotation(x, y, dist, angle)
local a = math.rad(90 - angle);
local dx = math.cos(a) * dist;
local dy = math.sin(a) * dist;
return x+dx, y+dy;
end
function dm (...)
return exports.mtatr_hud:dm (...);
end
function tocomma (...)
return exports.mtatr_utils:comma_value (...);
end |
data:extend({
-- Startup
{
type = "double-setting",
name = "Noxys_Swimming-swimming-speed",
setting_type = "startup",
minimum_value = 0.01,
default_value = 0.35,
maximum_value = 10,
order = "a"
},
{
type = "double-setting",
name = "Noxys_Swimming-swimming-deep-speed",
setting_type = "startup",
minimum_value = 0.01,
default_value = 0.25,
maximum_value = 10,
order = "b"
},
{
type = "bool-setting",
name = "Noxys_Swimming-is-deep-swimmable",
setting_type = "startup",
default_value = true,
order = "c"
},
-- Global
-- Per user
})
|
Config = {}
Config.DrawDistance = 100.0
Config.JobName = "salvage"
Config.PlatePrefix = "OCEANMAN"
Config.Locale = 'fr'
Config.Vehicles = {
Truck = {
Spawner = 1,
Label = 'dinghy',
Hash = "dinghy",
Livery = 0,
Trailer = "none"
}
}
Config.Zones = {
Cloakroom = {
Pos = {x = -733.85, y = -1344.20, z = 1.5},
Size = {x = 0.5, y = 0.5, z = 0.5},
Color = {r = 11, g = 203, b = 159},
Type = 0,
hint = _U('prompt_locker')
},
VehicleSpawner = {
Pos = {x = -739.57, y = -1327.92, z = 1.59},
Size = {x = 0.5, y = 0.5, z = 0.5},
Color = {r = 11, g = 203, b = 159},
Type = 0,
hint = _U('prompt_vehicle')
},
VehicleSpawnPoint = {
Pos = {x = -734.10, y = -1332.54, z = -0.47},
Size = {x = 3.0, y = 3.0, z = 1.0},
Type = -1,
Heading = 25.48
},
VehicleDeleter = {
Pos = {x = -725.70, y = -1327.52, z = -1.5},
Size = {x = 3.0, y = 3.0, z = 3.0},
Color = {r = 255, g = 0, b = 0},
Type = 1,
hint = _U('prompt_vehicledeleter')
},
Vente = {
Pos = {x = -744.78, y = -1333.81, z = 1.59},
Size = {x = 0.5, y = 0.5, z = 0.5},
Color = {r = 11, g = 203, b = 159},
Type = 0,
hint = _U('prompt_cashout'),
ItemTime = 500,
ItemDb_name = "contrat",
ItemName = "Facture",
ItemMax = 25,
ItemAdd = 5,
ItemRemove = 1,
ItemRequires = "contrat",
ItemRequires_name = "Facture",
ItemDrop = 100,
ItemPrice = 3
}
}
Config.Pool = {
{ [ 'x' ] = 3173.85 , [ 'y' ] = -320.13 , [ 'z' ] = -20.95 },
{ [ 'x' ] = 3150.14 , [ 'y' ] = -330.64 , [ 'z' ] = -25.97 },
{ [ 'x' ] = 3194.99 , [ 'y' ] = -377.61 , [ 'z' ] = -32.84 },
{ [ 'x' ] = 3186.74 , [ 'y' ] = -392.79 , [ 'z' ] = -16.49 },
{ [ 'x' ] = 3250.91 , [ 'y' ] = -420.44 , [ 'z' ] = -76.98 },
{ [ 'x' ] = 3298.15 , [ 'y' ] = -408.64 , [ 'z' ] = -123.01 },
{ [ 'x' ] = 3268.59 , [ 'y' ] = -448.53 , [ 'z' ] = -88.45 },
{ [ 'x' ] = -881.99 , [ 'y' ] = 6629.61 , [ 'z' ] = -28.15 },
{ [ 'x' ] = -898.67 , [ 'y' ] = 6647.94 , [ 'z' ] = -27.73 },
{ [ 'x' ] = -914.51 , [ 'y' ] = 6665.64 , [ 'z' ] = -34.94 },
{ [ 'x' ] = -998.27 , [ 'y' ] = 6704.22 , [ 'z' ] = -43.61 },
{ [ 'x' ] = -1014.71 , [ 'y' ] = 6533.14 , [ 'z' ] = -28.61 },
{ [ 'x' ] = -2838.83 , [ 'y' ] = -434.26 , [ 'z' ] = -29.88 },
{ [ 'x' ] = -2845.55 , [ 'y' ] = -468.42 , [ 'z' ] = -31.61 },
{ [ 'x' ] = -3400.83 , [ 'y' ] = 3716.78 , [ 'z' ] = -82.17 },
{ [ 'x' ] = -3398.58 , [ 'y' ] = 3721.22 , [ 'z' ] = -79.82 },
{ [ 'x' ] = -3171.79 , [ 'y' ] = 3935.58 , [ 'z' ] = -38.00 },
{ [ 'x' ] = -3182.40 , [ 'y' ] = 3040.81 , [ 'z' ] = -36.93 },
{ [ 'x' ] = -3177.65 , [ 'y' ] = 3045.22 , [ 'z' ] = -39.48 },
{ [ 'x' ] = 3158.31 , [ 'y' ] = -262.12 , [ 'z' ] = -26.62 },
{ [ 'x' ] = -3593.77 , [ 'y' ] = 1974.05 , [ 'z' ] = -154.30 },
{ [ 'x' ] = -3609.98 , [ 'y' ] = 565.97 , [ 'z' ] = -75.04 },
{ [ 'x' ] = -2012.06 , [ 'y' ] = -1245.47, [ 'z' ] = -123.79 },
{ [ 'x' ] = 1620.58 , [ 'y' ] = -3642.92, [ 'z' ] = -75.50 },
{ [ 'x' ] = 4167.95 , [ 'y' ] = 3710.74 , [ 'z' ] = -31.37 },
{ [ 'x' ] = 3158.31 , [ 'y' ] = -262.12 , [ 'z' ] = -26.62 },
{ [ 'x' ] = 4236.41 , [ 'y' ] = 3597.14 , [ 'z' ] = -45.25 },
{ [ 'x' ] = 3791.98 , [ 'y' ] = 3659.84 , [ 'z' ] = -17.15 },
{ [ 'x' ] = 1632.19 , [ 'y' ] = -3561.86, [ 'z' ] = -78.48 },
{ [ 'x' ] = 3158.31 , [ 'y' ] = -262.12 , [ 'z' ] = -26.62 },
{ [ 'x' ] = -2845.55 , [ 'y' ] = -468.42 , [ 'z' ] = -31.61 },
{ [ 'x' ] = -1014.71 , [ 'y' ] = 6533.14 , [ 'z' ] = -28.61 }
}
for i=1, #Config.Pool, 1 do
Config.Zones['Pool' .. i] = {
Pos = Config.Pool[i],
Size = {x = 1.5, y = 1.5, z = 1.0},
Color = {r = 204, g = 204, b = 0},
Type = -1
}
end
Config.Uniforms = {
job_wear = {
male = {
['tshirt_1'] = 68, ['tshirt_2'] = 0,
['torso_1'] = 243, ['torso_2'] = 5,
['decals_1'] = 0, ['decals_2'] = 0,
--add the Scuba mask and set the glasses (small) mask to -1 ad off)
['mask_1'] = 36, ['mask_2'] = 0,
['arms'] = 8,
['pants_1'] = 94, ['pants_2'] = 0,
['shoes_1'] = 67, ['shoes_2'] = 0,
['glasses_1'] = -1, ['glasses_2'] = 0,
['helmet_1'] = -1, ['helmet_2'] = 0,
['chain_1'] = 0, ['chain_2'] = 0,
['ears_1'] = -1, ['ears_2'] = 0
},
female = {
['tshirt_1'] = 1, ['tshirt_2'] = 0,
['torso_1'] = 251, ['torso_2'] = 5,
['decals_1'] = 0, ['decals_2'] = 0,
['mask_1'] = 36, ['mask_2'] = 0,
['arms'] = 6,
['pants_1'] = 97, ['pants_2'] = 5,
['shoes_1'] = 70, ['shoes_2'] = 0,
['glasses_1'] = -1, ['glasses_2'] = 0,
['helmet_1'] = -1, ['helmet_2'] = 0,
['chain_1'] = 0, ['chain_2'] = 0,
['ears_1'] = -1, ['ears_2'] = 0
}
}
}
|
ITEM.name = "Harmonica"
ITEM.description = "A playable harmonica."
ITEM.longdesc = "A free reed wind instrument that is used throughout the Zone in which it is featured in many musical genres. The instrument appears to have around 10 holes which the user would blow into to produce a sound. Some STALKERS have mastered the Harmonica and use it over a Guitar for their instrument choice, mostly due to how easy it is to carry around."
ITEM.model = "models/lostsignalproject/items/misc/harmonica.mdl"
ITEM.width = 1
ITEM.height = 1
ITEM.price = 400
ITEM.img = ix.util.GetMaterial("vgui/hud/harmonica.png")
ITEM.sounds = {
Sound("stalkersound/harmonica/harmonica_1.ogg"),
Sound("stalkersound/harmonica/harmonica_2.ogg"),
Sound("stalkersound/harmonica/harmonica_3.ogg"),
Sound("stalkersound/harmonica/harmonica_4.ogg"),
Sound("stalkersound/harmonica/harmonica_5.ogg")
}
ITEM.functions.use = { -- sorry, for name order.
name = "Play",
icon = "icon16/stalker/sell.png",
OnRun = function(item)
if(item:GetData("cooldown", 0) < os.time()) then
local soundplay = table.Random(item.sounds)
item.player:EmitSound(soundplay, 50, 100, 0.5)
ix.chat.Send(item.player, "iteminternal", "puts their "..item.name.." to their mouths and plays a tune.", false)
item:SetData("cooldown", os.time() + 15 )
end
return false
end,
OnCanRun = function(item)
return (!IsValid(item.entity)) and item.invID == item:GetOwner():GetCharacter():GetInventory():GetID()
end
}
|
module(...)
local specification = [=====[
--[[
int, int2, int3, int4
float, float2, float3, float4
float2x2, float3x3, float4x4
bool, bool2, bool3, bool4
strin
--]]
local keywords = {
"void",
"attribute", "const", "uniform", "varying",
"break", "continue", "do", "for", "while",
"if", "else",
"void", "true", "false",
"return",
"string",
"bool", "bool2", "bool3", "bool4",
"int", "int2", "int3", "int4",
"float", "float2", "float3", "float4",
"float2x2", "float3x3", "float4x4",
"pixel1", "pixel2", "pixel3", "pixel4",
"image1", "image2", "image3", "image4",
"region",
"kernel", "languageVersion", "parameter",
"dependent", "input", "output",
}
local identifier_ignore = {}
local operators = {
left_op = "<<",
right_op = ">>",
inc_op = "++",
dec_op = "--",
le_op = "<=",
ge_op = ">=",
eq_op = "==",
ne_op = "!=",
and_op = "&&",
or_op = "||",
xor_op = "^^",
mul_assign = "*=",
div_assign = "/=",
add_assign = "+=",
mod_assign = "%=",
left_assign = "<<=",
right_assign = ">>=",
and_assign = "&=",
xor_assign = "^=",
or_assign = "|=",
sub_assign = "-=",
left_paren = "(",
right_paren = ")",
left_bracket = "[",
right_bracket = "]",
left_brace = "{",
right_brace = "}",
dot = ".",
comma = ",",
colon = ":",
equal = "=",
semicolon = ";",
bang = "!",
dash = "-",
tilde = "~",
plus = "+",
star = "*",
slash = "/",
percent = "%",
left_angle = "<",
right_angle = ">",
vertical_bar = "|",
caret = "^",
ampersand = "&",
question = "?",
}
for i, kw in ipairs(keywords) do
Token(
P(kw), kw:upper(), kw:len()
)
end
for name, op in pairs(operators) do
Token(
P(op), name:upper(),
op:len()
)
end
local keyword_map = {}
for i, kw in ipairs(keywords) do
keyword_map[kw] = true
end
for i, kw in ipairs(identifier_ignore) do
keyword_map[kw] = nil
end
--------------------------------------------------------
--- Variable Tokens
nondigit = P"_" + R"az" + R"AZ"
--------------------------
--- Numerical Tokens
-- digits
octal_digit = R"07"
hexadecimal_digit = R("09", "af", "AF")
nonzero_digit = R"19"
digit = P"0" + nonzero_digit
-- constants
decimal_constant = nonzero_digit * (nonzero_digit + digit)^0
octal_constant = P"0" * (
octal_digit +
LexErr(decimal_constant+nondigit, "invalid octal constant")
)^0
hexadecimal_constant = (P"0x" + P"0X") *
(
hexadecimal_digit +
LexErr(nondigit, "invalid hexadecimal constant")
)^1
INTCONSTANT = Token(
hexadecimal_constant + octal_constant + decimal_constant ,
"INTCONSTANT",
MAX_PRIORITY-1
)
-- float annotations
digit_sequence = digit^1
exponent_part = ((S"eE" * P"-")^-1 + S"eE"^-1) * digit_sequence
sign = S"-+"
floating_suffix = S"fF"
fractional_constant = digit_sequence * P"." * digit_sequence^-1 +
P"." * digit_sequence
FLOATCONSTANT = Token(
(
fractional_constant * exponent_part^-1 +
digit_sequence * exponent_part
) *
floating_suffix^-1,
"FLOATCONSTANT",
MAX_PRIORITY
)
endline = S"\n\r"
STRINGCONSTANT = Token(
P[["]] * (P[[\"]]+(1 - (endline + P[["]])))^0 * (P[["]] + LexErr(P(1), [[string missing closing "]])),
"STRINGCONSTANT",
MAX_PRIORITY
)
IDENTIFIER = Token(
Cmt(
C(nondigit * (nondigit + digit)^0),
function(s, i, a)
return not keyword_map[a]
end),
"IDENTIFIER",
MAX_PRIORITY
)
tokens = {IDENTIFIER = true, INTCONSTANT = true, FLOATCONSTANT = true}
for i, kw in ipairs(keywords) do
tokens[kw:upper()] = true
end
for name, op in pairs(operators) do
tokens[name:upper()] = true
end
-- variable_identifier:
-- IDENTIFIER
variable_identifier = Rule(V"IDENTIFIER", "variable_identifier")
-- primary_expression:
-- variable_identifier
-- INTCONSTANT
-- FLOATCONSTANT
-- LEFT_PAREN expression RIGHT_PAREN
primary_expression = Rule(
V"variable_identifier" +
V"FLOATCONSTANT" +
V"INTCONSTANT" +
V"TRUE" + V"FALSE" +
V"LEFT_PAREN" * V"function_arguments"^-1 * V"RIGHT_PAREN"
,
"primary_expression"
)
local function_constructor =
V"BOOL" + V"BOOL2" + V"BOOL3" + V"BOOL4" +
V"INT" + V"INT2" + V"INT3" + V"INT4" +
V"FLOAT" + V"FLOAT2" + V"FLOAT3" + V"FLOAT4" +
V"FLOAT2X2" + V"FLOAT3X3" + V"FLOAT4X4" +
V"PIXEL1" + V"PIXEL2" + V"PIXEL3" + V"PIXEL4" +
V"REGION"
-- postfix_expression:
-- primary_expression
-- postfix_expression LEFT_BRACKET integer_expression RIGHT_BRACKET
-- function_call
-- postfix_expression DOT FIELD_SELECTION
-- postfix_expression INC_OP
-- postfix_expression DEC_OP
postfix_expression = Rule(
V"primary_expression" * (
V"LEFT_BRACKET" * V"integer_expression" * V"RIGHT_BRACKET" +
V"function_call" +
V"DOT" * V"IDENTIFIER" +
V"INC_OP" +
V"DEC_OP"
)^0 +
function_constructor * V"function_call",
"postfix_expression"
)
-- integer_expression:
-- expression
integer_expression = --Rule(V"expression", "integer_expression")
Rule(V"INTCONSTANT", "integer_expression")
-- function_call:
-- function_call_or_method
function_call = Rule(
V"LEFT_PAREN" *
V"function_arguments"^-1 *
V"RIGHT_PAREN",
"function_call"
)
-- function_arguments:
-- function_call_header VOID
-- function_call_header
function_arguments = Rule(
V"VOID" +
V"conditional_expression" * (V"COMMA" * V"conditional_expression")^0,
"function_arguments"
)
-- unary_expression:
-- postfix_expression
-- INC_OP unary_expression
-- DEC_OP unary_expression
-- unary_operator unary_expression
unary_expression = Rule(
V"postfix_expression" +
V"INC_OP" * V"unary_expression" +
V"DEC_OP" * V"unary_expression" +
V"unary_operator" * V"unary_expression",
"unary_expression"
)
-- unary_operator:
-- PLUS
-- DASH
-- BANG
-- TILDE // reserved
unary_operator = Rule(V"PLUS" + V"DASH" + V"BANG", "unary_operator")
-- multiplicative_expression:
-- unary_expression
-- multiplicative_expression STAR unary_expression
-- multiplicative_expression SLASH unary_expression
-- multiplicative_expression PERCENT unary_expression // reserved
multiplicative_expression = Rule(
V"unary_expression" * (
V"STAR" * V"unary_expression" +
V"SLASH" * V"unary_expression"
)^0,
"multiplicative_expression"
)
-- additive_expression:
-- multiplicative_expression
-- additive_expression PLUS multiplicative_expression
-- additive_expression DASH multiplicative_expression
additive_expression = Rule(
V"multiplicative_expression" * (
V"PLUS" * V"multiplicative_expression" +
V"DASH" * V"multiplicative_expression"
)^0,
"additive_expression"
)
-- shift_expression:
-- additive_expression
-- shift_expression LEFT_OP additive_expression // reserved
-- shift_expression RIGHT_OP additive_expression // reserved
shift_expression = Rule(V"additive_expression", "shift_expression")
-- relational_expression:
-- shift_expression
-- relational_expression LEFT_ANGLE shift_expression
-- relational_expression RIGHT_ANGLE shift_expression
-- relational_expression LE_OP shift_expression
-- relational_expression GE_OP shift_expression
relational_expression = Rule(
V"shift_expression" * (
V"LEFT_ANGLE" * V"shift_expression" +
V"RIGHT_ANGLE" * V"shift_expression" +
V"LE_OP" * V"shift_expression" +
V"GE_OP" * V"shift_expression"
)^0,
"relational_expression"
)
-- equality_expression:
-- relational_expression
-- equality_expression EQ_OP relational_expression
-- equality_expression NE_OP relational_expression
equality_expression = Rule(
V"relational_expression" * (
V"EQ_OP" * V"relational_expression" +
V"NE_OP" * V"relational_expression"
)^0,
"equality_expression"
)
-- and_expression:
-- equality_expression
-- and_expression AMPERSAND equality_expression // reserved
and_expression = Rule(V"equality_expression", "and_expression")
-- exclusive_or_expression:
-- and_expression
-- exclusive_or_expression CARET and_expression // reserved
exclusive_or_expression = Rule(V"and_expression", "exclusive_or_expression")
-- inclusive_or_expression:
-- exclusive_or_expression
-- inclusive_or_expression VERTICAL_BAR exclusive_or_expression // reserved
inclusive_or_expression = Rule(V"exclusive_or_expression", "inclusive_or_expression")
-- logical_and_expression:
-- inclusive_or_expression
-- logical_and_expression AND_OP inclusive_or_expression
logical_and_expression = Rule(
V"inclusive_or_expression" * (
V"AND_OP" * V"inclusive_or_expression"
)^0,
"logical_and_expression"
)
-- logical_xor_expression:
-- logical_and_expression
-- logical_xor_expression XOR_OP logical_and_expression
logical_xor_expression = Rule(
V"logical_and_expression" * (
V"XOR_OP" * V"logical_and_expression"
)^0,
"logical_xor_expression"
)
-- logical_or_expression:
-- logical_xor_expression
-- logical_or_expression OR_OP logical_xor_expression
logical_or_expression = Rule(
V"logical_xor_expression" * (
V"OR_OP" * V"logical_xor_expression"
)^0,
"logical_or_expression"
)
-- conditional_expression:
-- logical_or_expression
-- logical_or_expression QUESTION expression COLON assignment_expression
conditional_expression = Rule(
V"logical_or_expression" * (
V"QUESTION" * V"expression" * V"COLON" * V"assignment_expression"
)^0,
"conditional_expression"
)
-- assignment_expression:
-- conditional_expression
-- unary_expression assignment_operator assignment_expression
assignment_expression = Rule(
V"postfix_expression" * V"assignment_operator" * V"assignment_expression" +
V"conditional_expression",
"assignment_expression"
)
-- assignment_operator:
-- EQUAL
-- MUL_ASSIGN
-- DIV_ASSIGN
-- MOD_ASSIGN // reserved
-- ADD_ASSIGN
-- SUB_ASSIGN
-- LEFT_ASSIGN // reserved
-- RIGHT_ASSIGN // reserved
-- AND_ASSIGN // reserved
-- XOR_ASSIGN // reserved
-- OR_ASSIGN // reserved
assignment_operator = Rule(
V"EQUAL" + V"MUL_ASSIGN" + V"DIV_ASSIGN" + V"ADD_ASSIGN" + V"SUB_ASSIGN",
"assignment_operator"
)
-- expression:
-- assignment_expression
-- expression COMMA assignment_expression
expression = Rule(
V"assignment_expression" * (
V"COMMA" * V"assignment_expression"
)^0,
"expression"
)
-- constant_expression:
-- conditional_expression
constant_expression = Rule(
V"conditional_expression",
"constant_expression"
)
-- declaration:
-- function_prototype SEMICOLON
-- init_declarator_list SEMICOLON
declaration = Rule(
V"function_prototype" +
V"single_declaration", -- +
--V"init_declarator_list",
"declaration"
)
-- function_prototype:
-- function_declarator RIGHT_PAREN
function_prototype = Rule(
V"fully_specified_type" *
V"IDENTIFIER" *
V"LEFT_PAREN" *
V"function_parameter_list"^-1 *
V"RIGHT_PAREN",
"function_prototype"
)
function_parameter_list = Rule(
V"parameter_declaration" * (V"COMMA" * V"parameter_declaration")^0,
"function_parameter_list"
)
function_parameter = Rule(
V"VOID" +
V"parameter_declaration",
"function_parameter"
)
-- parameter_declaration:
-- type_qualifier parameter_qualifier parameter_declarator
-- parameter_qualifier parameter_declarator
-- type_qualifier parameter_qualifier parameter_type_specifier
-- parameter_qualifier parameter_type_specifier
parameter_declaration = Rule(
V"fully_specified_type" * V"IDENTIFIER" * (
V"LEFT_BRACKET" * V"constant_expression" * V"RIGHT_BRACKET"
)^-1,
"parameter_declaration"
)
-- parameter_type_specifier:
-- type_specifier
parameter_type_specifier = Rule(V"type_specifier", "parameter_type_specifier")
-- init_declarator_list:
-- single_declaration
init_declarator_list = Rule(
V"fully_specified_type" * V"IDENTIFIER" * (V"COMMA" * V"IDENTIFIER")^0,
"init_declarator_list"
)
-- single_declaration:
-- fully_specified_type
-- fully_specified_type IDENTIFIER
-- fully_specified_type IDENTIFIER EQUAL initializer
single_declaration = Rule(
V"fully_specified_type" * V"IDENTIFIER" *
(
V"COMMA" * V"IDENTIFIER" * (V"COMMA" * V"IDENTIFIER")^0 +
(V"EQUAL" * V"initializer")^-1
)
,
"single_declaration"
)
-- fully_specified_type:
-- type_specifier
-- type_qualifier type_specifier
fully_specified_type = Rule(
V"type_qualifier"^-1 * V"type_specifier",
"fully_specified_type"
)
-- type_qualifier:
-- CONST
-- ATTRIBUTE // Vertex only.
-- VARYING
-- UNIFORM
type_qualifier = Rule(V"CONST" + V"ATTRIBUTE" + V"VARYING" + V"UNIFORM", "type_qualifier")
-- type_specifier:
-- type_specifier_nonarray
type_specifier = Rule(
V"type_specifier_nonarray",
"type_specifier"
)
-- type_specifier_nonarray:
-- VOID
-- FLOAT
-- VEC2
-- VEC3
-- VEC4
-- MAT2
-- MAT3
-- MAT4
-- SAMPLER2D
-- SAMPLER2DRECT
-- TYPE_NAME
type_specifier_nonarray = Rule(
V"VOID" +
V"BOOL" + V"BOOL2" + V"BOOL3" + "BOOL4" +
V"INT" + V"INT2" + V"INT3" + "INT4" +
V"FLOAT" + V"FLOAT2" + V"FLOAT3" + "FLOAT4" +
V"FLOAT2X2" + V"FLOAT3X3" + V"FLOAT4X4" +
V"PIXEL1" + V"PIXEL2" + V"PIXEL3" + V"PIXEL4" +
V"REGION",
"type_specifier_nonarray"
)
-- initializer:
-- assignment_expression
initializer = Rule(V"assignment_expression", "initializer")
-- declaration_statement:
-- declaration
declaration_statement = Rule(V"declaration" * V"SEMICOLON", "declaration_statement")
-- statement:
-- compound_statement
-- simple_statement
-- // Grammar Note: No labeled statements; 'goto' is not supported.
statement = Rule(V"compound_statement" + V"simple_statement", "statement")
-- simple_statement:
-- declaration_statement
-- expression_statement
-- selection_statement
-- iteration_statement
-- jump_statement
simple_statement = Rule(
V"declaration_statement" + V"expression_statement" +
V"selection_statement" + V"iteration_statement" +
V"jump_statement",
"simple_statement"
)
-- compound_statement:
-- LEFT_BRACE RIGHT_BRACE
-- LEFT_BRACE statement_list RIGHT_BRACE
compound_statement = Rule(
V"LEFT_BRACE" * V"RIGHT_BRACE" +
V"LEFT_BRACE" * V"statement_list" * V"RIGHT_BRACE",
"compound_statement"
)
-- statement_list:
-- statement
-- statement_list statement
statement_list = Rule(V"statement"^1, "statement_list")
-- expression_statement:
-- SEMICOLON
-- expression SEMICOLON
expression_statement = Rule(
V"SEMICOLON" +
V"expression" * V"SEMICOLON",
"expression_statement"
)
-- selection_statement:
-- IF LEFT_PAREN expression RIGHT_PAREN selection_rest_statement
selection_statement = Rule(
V"IF" * V"LEFT_PAREN" * V"expression" *
V"RIGHT_PAREN" *
V"selection_rest_statement",
"selection_statement"
)
-- selection_rest_statement:
-- statement ELSE statement
-- statement
-- // Grammar Note: No 'switch'. Switch statements not supported.
selection_rest_statement = Rule(
V"statement" * (V"ELSE" * V"statement")^-1,
"selection_rest_statement"
)
-- condition:
-- expression
-- fully_specified_type IDENTIFIER EQUAL initializer
condition = Rule(
V"expression" +
V"fully_specified_type" * V"IDENTIFIER" * V"EQUAL" *
V"initializer",
"condition"
)
-- iteration_statement:
-- WHILE LEFT_PAREN condition RIGHT_PAREN statement_no_new_scope
-- DO statement WHILE LEFT_PAREN expression RIGHT_PAREN SEMICOLON
-- FOR LEFT_PAREN for_init_statement for_rest_statement RIGHT_PAREN statement_no_new_scope
iteration_statement = Rule(
V"WHILE" * V"LEFT_PAREN" * V"condition" *
V"RIGHT_PAREN" *
V"statement" +
V"DO" * V"statement" * V"WHILE" * V"LEFT_PAREN" *
V"expression" *
V"RIGHT_PAREN" *
V"SEMICOLON" +
V"FOR" * V"LEFT_PAREN" * V"for_init_statement" *
V"for_rest_statement" *
V"RIGHT_PAREN" *
V"statement"
,
"iteration_statement"
)
-- for_init_statement:
-- expression_statement
-- declaration_statement
for_init_statement = Rule(
V"declaration_statement" + V"expression_statement",
"for_init_statement"
)
-- conditionopt:
-- condition
-- /* empty */
conditionopt = Rule(V"condition" + P(-1), "conditionopt")
-- for_rest_statement:
-- conditionopt SEMICOLON
-- conditionopt SEMICOLON expression
for_rest_statement = Rule(
V"conditionopt" * V"SEMICOLON" * V"expression"^-1,
"for_rest_statement"
)
-- jump_statement:
-- CONTINUE SEMICOLON
-- BREAK SEMICOLON
-- RETURN SEMICOLON
-- RETURN expression SEMICOLON
-- DISCARD SEMICOLON // Fragment shader only.
-- // Grammar Note: No 'goto'. Gotos are not supported.
jump_statement = Rule(
(
V"CONTINUE" +
V"BREAK" +
V"RETURN" * V"expression" +
V"RETURN"
) * V"SEMICOLON",
"jump_statement"
)
-- translation_unit:
-- external_declaration
-- translation_unit external_declaration
translation_unit = Rule((V"kernel_declaration" + V"function_definition")^1, "translation_unit")
-- function_definition:
-- function_prototype compound_statement_no_new_scope
function_definition = Rule(
V"function_prototype" *
V"compound_statement",
"function_definition"
)
value = Rule(
function_constructor * V"function_call" +
V"STRINGCONSTANT" + V"DASH" * (V"FLOATCONSTANT" + V"INTCONSTANT") +
V"FLOATCONSTANT" + V"INTCONSTANT" +
V"TRUE" + V"FALSE",
"value"
)
name_value = Rule(
V"IDENTIFIER" * V"COLON" * V"value" * V"SEMICOLON",
"name_value"
)
metadata = Rule(
V"LEFT_ANGLE" * V"name_value"^0 * V"RIGHT_ANGLE",
"metadata"
)
kernel_metadata = Rule(
V"KERNEL" * V"IDENTIFIER" * V"metadata",
"kernel_metadata"
)
language_version_statement = Rule(
V"LEFT_ANGLE" * V"LANGUAGEVERSION" * V"COLON" * V"value" * V"SEMICOLON" * V"RIGHT_ANGLE",
"language_version_statement"
)
parameter = Rule(
V"PARAMETER" * V"type_specifier_nonarray" * V"IDENTIFIER" *
V"metadata"^-1,
"parameter"
)
dependent = Rule(
V"DEPENDENT" * V"type_specifier_nonarray" * V"IDENTIFIER" * (V"COMMA" * V"IDENTIFIER")^0,
"dependent"
)
input = Rule(
V"INPUT" * (V"IMAGE1" + V"IMAGE2" + V"IMAGE3" + V"IMAGE4") * V"IDENTIFIER",
"input"
)
output = Rule(
V"OUTPUT" * (V"PIXEL1" + V"PIXEL2" + V"PIXEL3" + V"PIXEL4") * V"IDENTIFIER",
"output"
)
kernel_declaration = Rule(
(V"dependent" + V"parameter" + V"input" + V"output") * V"SEMICOLON",
"kernel_declaration"
)
pbk = Rule(
V"language_version_statement" *
V"kernel_metadata" *
V"LEFT_BRACE" *
V"translation_unit" *
V"RIGHT_BRACE",
"pbk"
)
single_line_comment = Comment(P"//"*(1 - S"\n\r")^0, "single_line_comment")
multi_line_comment = Comment(P"/*"*(1 - P"*/")^0*P"*/", "multi_line_comment")
]=====]
function get_specification()
return specification
end |
local diagnostic, fn, lsp = vim.diagnostic, vim.fn, vim.lsp
local fmt = string.format
local function get_diagnostic(prefix, severity)
local count
if fn.has('nvim-0.6') == 0 then
count = lsp.diagnostic.get_count(0, severity)
else
local severities = {
['Warning'] = diagnostic.severity.WARN,
['Error'] = diagnostic.severity.ERROR,
}
count = #diagnostic.get(0, {severity=severities[severity]})
end
if count < 1 then
return ''
end
return fmt('%s:%d', prefix, count)
end
local function get_error()
return get_diagnostic('E', 'Error')
end
local function get_warning()
return get_diagnostic('W', 'Warning')
end
return {
get_error = get_error,
get_warning = get_warning,
}
|
--[[--------------------
# four <a href="https://travis-ci.org/lubyk/four"><img src="https://travis-ci.org/lubyk/four.png" alt="Build Status"></a>
Lightweight OpenGL rendering engine for providing a basic abstraction layer
for compositional GLSL shader programming and rendering.
<html><a href="https://github.com/lubyk/four"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_green_007200.png" alt="Fork me on GitHub"></a></html>
*MIT license* © Daniel C. Bünzli, Gaspard Bucher 2014.
## Installation
With [luarocks](http://luarocks.org):
$ luarocks install four
For a gentle introduction to the library, please have a look at the
[tutorials](tutorial.four.html).
--]]--------------------
local lub = require 'lub'
local lib = lub.Autoload 'four'
-- Current version respecting [semantic versioning](http://semver.org).
lib.VERSION = '1.0.0'
lib.DEPENDS = { -- doc
-- Compatible with LuaJIT (uses ffi for OpenGL bindings).
"lua >= 5.1, < 5.3",
-- Uses [Lubyk base library](http://doc.lubyk.org/lub.html)
'lub >= 1.0.3, < 2',
-- Uses [Lubyk networking and realtime](http://doc.lubyk.org/lens.html)
'lens >= 1.0.0, < 2',
-- Uses [Lubyk simple UI](http://doc.lubyk.org/lui.html)
'lui >= 1.0.0, < 2',
}
-- nodoc
lib.DESCRIPTION = {
summary = "",
detailed = [[
]],
homepage = "http://doc.lubyk.org/four.html",
author = "Daniel C. Bünzli, Gaspard Bucher",
license = "MIT",
}
-- nodoc
lib.BUILD = {
github = 'lubyk',
pure_lua = true,
}
-- Enable crash on error debugging.
--
-- WARN: This has a *HUGE* performance cost and should only be called during
-- development.
function lib.debug()
require('four.RendererGL32').debug()
end
return lib
|
local _=function(event)
log("pickup event:"..Inspect(event))
--[[example:
]]--
assert(Session.isServer)
local entity=Entity.find(event.entityName,event.entityId,event.entityLogin)
-- problem: broadcasted delete will return later
-- solution1: do not broadcast deletion to caller
-- generic: broadcast from Entity.delete
-- problem: server can reject deletion
-- sol: handle delete event on serv, respond to deletion on caller
-- way to respond to event? direct command?
if not entity then
log("warn: pickup: no entity")
return
end
local responseEvent=Event.new()
responseEvent.code="pickup_ok"
responseEvent.entityName=entity.entity
responseEvent.entityId=entity.id
responseEvent.entityLogin=entity.login
responseEvent.actorLogin=event.login
-- default target: all
end
return _ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.