content
stringlengths 5
1.05M
|
|---|
-- Copyright 2015-2019, Björn Ståhl
-- License: 3-Clause BSD
-- Reference: http://durden.arcan-fe.com
--
-- Description: Global / Persistent configuration management.
-- Deals with key lookup, update hooks and so on. For actual default
-- configuration values, see config.lua
--
local log, fmt = suppl_add_logfn("config");
-- here for the time being, will move with internationalization
LBL_YES = "yes";
LBL_NO = "no";
LBL_FLIP = "toggle";
LBL_BIND_COMBINATION = "Press and hold the desired combination, %s to Cancel";
LBL_BIND_KEYSYM = "Press and hold single key to bind keysym %s, %s to Cancel";
LBL_BIND_COMBINATION_REP = "Press and hold or repeat- press, %s to Cancel";
LBL_UNBIND_COMBINATION = "Press and hold the combination to unbind, %s to Cancel";
LBL_METAGUARD = "Query Rebind in %d keypresses";
LBL_METAGUARD_META = "Rebind (meta keys) in %.2f seconds, %s to Cancel";
LBL_METAGUARD_BASIC = "Rebind (basic keys) in %.2f seconds, %s to Cancel";
LBL_METAGUARD_MENU = "Rebind (global menu) in %.2f seconds, %s to Cancel";
LBL_METAGUARD_TMENU = "Rebind (target menu) in %.2f seconds, %s to Cancel";
HC_PALETTE = {
"\\#efd469",
"\\#43abc9",
"\\#cd594a",
"\\#b5c689",
"\\#f58b4c",
"\\#ed6785",
"\\#d0d0d0",
};
local defaults = system_load("config.lua")();
local listeners = {};
function gconfig_listen(key, id, fun)
if (listeners[key] == nil) then
listeners[key] = {};
end
listeners[key][id] = fun;
end
-- for tools and other plugins to enable their own values
function gconfig_register(key, val)
if (not defaults[key]) then
local v = get_key(key);
if (v ~= nil) then
if (type(val) == "number") then
v = tonumber(v);
elseif (type(val) == "boolean") then
v = v == "true";
end
defaults[key] = v;
else
defaults[key] = val;
end
end
end
function gconfig_set(key, val, force)
if (type(val) ~= type(defaults[key])) then
log(fmt(
"key=%s:kind=error:type_in=%s:type_out=%s:value=%s",
key, type(val), type(defaults[key]), val
));
return;
end
-- lua5.1 timebomb, 5.2 adds to_lstring on args, 5.1 does not, might
-- need to go with a fixup where .format walks ... and tostrings boolean
log(fmt("key=%s:kind=set:new_value=%s", key, tostring(val)));
defaults[key] = val;
if (force) then
store_key(key, tostring(val));
end
if (listeners[key]) then
for k,v in pairs(listeners[key]) do
v(key, val);
end
end
end
function gconfig_get(key)
return defaults[key];
end
--
-- these need special consideration, packing and unpacking so treat
-- them separately
--
gconfig_buttons = {
all = {},
float = {
},
tile = {
},
};
gconfig_statusbar_buttons = {
};
-- for the sake of convenience, : is blocked from being a valid vsym as
-- it is used as a separator elsewhere (suppl_valid_vsymbol)
local function btn_str(v)
return string.format("%s:%s:%s", v.direction, v.label, v.command);
end
local function str_to_btn(dst, v)
local str, rest = string.split_first(v, "=");
local dir, rest = string.split_first(rest, ":");
local key, rest = string.split_first(rest, ":");
local base, cmd = string.split_first(rest, ":");
if (#dir > 0 and #rest > 0 and #key > 0) then
local ind = string.sub(str, 10);
table.insert(dst, {
label = key,
command = cmd,
direction = dir,
ind = tonumber(ind)
});
return true;
end
end
function gconfig_statusbar_rebuild(nosynch)
--double negative, but oh well - save the current state as config
if (not nosynch) then
drop_keys("sbar_btn_%");
drop_keys("sbar_btn_alt_%");
drop_keys("sbar_btn_drag_%");
local keys_out = {};
for i,v in ipairs(gconfig_statusbar_buttons) do
keys_out["sbar_btn_" .. tostring(i)] = btn_str(v);
if (v.alt_command) then
keys_out["sbar_btn_alt_" .. tostring(i)] = v.alt_command;
end
if (v.drag_command) then
keys_out["sbar_btn_drag_" .. tostring(i)] = v.drag_command;
end
end
store_key(keys_out);
end
gconfig_statusbar_buttons = {};
local ofs = 0;
for _,v in ipairs(match_keys("sbar_btn_%")) do
if (str_to_btn(gconfig_statusbar_buttons, v)) then
local ent = gconfig_statusbar_buttons[#gconfig_statusbar_buttons];
if (ent.ind) then
ent.alt_command = get_key("sbar_btn_alt_" .. tostring(ent.ind));
ent.drag_command = get_key("sbar_btn_drag_" .. tostring(ent.ind));
end
end
end
-- will take care of synching against gconfig_statusbar,
-- but only if the tiler itself expose that method (i.e.
-- gconf can be loaded before)
if all_tilers_iter then
for tiler in all_tilers_iter() do
if (tiler.rebuild_statusbar_custom) then
tiler:rebuild_statusbar_custom(gconfig_statusbar_buttons);
end
end
end
end
function gconfig_buttons_rebuild(nosynch)
local keys = {};
-- delete the keys, then rebuild buttons so we use the same code for both
-- update dynamically and for initial load
if (not nosynch) then
drop_keys("tbar_btn_all_%");
drop_keys("tbar_btn_float_%");
drop_keys("tbar_btn_tile_%");
local keys_out = {};
for _, group in ipairs({"all", "float", "tile"}) do
for i,v in ipairs(gconfig_buttons[group]) do
keys_out["tbar_btn_" .. group .. "_" .. tostring(i)] = btn_str(v);
end
end
store_key(keys_out);
end
for _, group in ipairs({"all", "float", "tile"}) do
gconfig_buttons[group] = {};
for _,v in ipairs(match_keys("tbar_btn_" .. group .. "_%")) do
str_to_btn(gconfig_buttons[group], v);
end
end
end
local function gconfig_setup()
for k,vl in pairs(defaults) do
local v = get_key(k);
if (v) then
if (type(vl) == "number") then
defaults[k] = tonumber(v);
-- naive packing for tables (only used with colors currently), just
-- use : as delimiter and split/concat to manage - just sanity check/
-- ignore on count and assume same type.
elseif (type(vl) == "table") then
local lst = string.split(v, ':');
local ok = true;
for i=1,#lst do
if (not vl[i]) then
ok = false;
break;
end
if (type(vl[i]) == "number") then
lst[i] = tonumber(lst[i]);
if (not lst[i]) then
ok = false;
break;
end
elseif (type(vl[i]) == "boolean") then
lst[i] = lst[i] == "true";
end
end
if (ok) then
defaults[k] = lst;
end
elseif (type(vl) == "boolean") then
defaults[k] = v == "true";
else
defaults[k] = v;
end
end
end
-- separate handling for mouse
local ms = mouse_state();
mouse_acceleration(defaults.mouse_factor, defaults.mouse_factor);
ms.autohide = defaults.mouse_autohide;
ms.hover_ticks = defaults.mouse_hovertime;
ms.drag_delta = defaults.mouse_dragdelta;
ms.hide_base = defaults.mouse_hidetime;
for i=1,8 do
ms.btns_bounce[i] = defaults["mouse_debounce_" .. tostring(i)];
end
-- and for the high-contrast palette used for widgets, ...
for _,v in ipairs(match_keys("hc_palette_%")) do
local cl = string.split(v, "=");
local ind = tonumber(string.sub(cl[1], 12));
if ind then
HC_PALETTE[ind] = cl[2];
end
end
-- and for global state of titlebar and statusbar
gconfig_buttons_rebuild(true);
gconfig_statusbar_rebuild(true);
end
local mask_state = false;
function gconfig_mask_temp(state)
mask_state = state;
end
-- shouldn't store all of default overrides in database, just from a
-- filtered subset
function gconfig_shutdown()
local ktbl = {};
for k,v in pairs(defaults) do
if (type(v) ~= "table") then
ktbl[k] = tostring(v);
else
ktbl[k] = table.concat(v, ':');
end
end
if not mask_state then
for i,v in ipairs(match_keys("durden_temp_%")) do
local k = string.split(v, "=")[1];
ktbl[k] = "";
end
end
for i,v in ipairs(HC_PALETTE) do
ktbl["hc_palette_" .. tostring(i)] = v
end
store_key(ktbl);
end
gconfig_setup();
|
-- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
modifier_slark_pounce_lua = class({})
--------------------------------------------------------------------------------
-- Classifications
function modifier_slark_pounce_lua:IsHidden()
return false
end
function modifier_slark_pounce_lua:IsDebuff()
return false
end
function modifier_slark_pounce_lua:IsStunDebuff()
return false
end
function modifier_slark_pounce_lua:IsPurgable()
return true
end
--------------------------------------------------------------------------------
-- Initializations
function modifier_slark_pounce_lua:OnCreated( kv )
self.parent = self:GetParent()
-- references
local speed = self:GetAbility():GetSpecialValueFor( "pounce_speed" )
local distance = self:GetAbility():GetSpecialValueFor( "pounce_distance" )
if self.parent:HasScepter() then
local new_distance = self:GetAbility():GetSpecialValueFor( "pounce_distance_scepter" )
speed = new_distance/distance*speed
distance = new_distance
end
self.radius = self:GetAbility():GetSpecialValueFor( "pounce_radius" )
self.leash_radius = self:GetAbility():GetSpecialValueFor( "leash_radius" )
self.leash_duration = self:GetAbility():GetSpecialValueFor( "leash_duration" )
local duration = distance/speed
local height = 160
if not IsServer() then return end
-- arc
self.arc = self.parent:AddNewModifier(
self.parent, -- player source
self:GetAbility(), -- ability source
"modifier_generic_arc_lua", -- modifier name
{
speed = speed,
duration = duration,
distance = distance,
height = height,
} -- kv
)
self.arc:SetEndCallback(function( interrupted )
-- destroy this modifier when arc ends
if self:IsNull() then return end
self.arc = nil
self:Destroy()
end)
-- set duration
self:SetDuration( duration, true )
-- set inactive
self:GetAbility():SetActivated( false )
-- Start interval
self:StartIntervalThink( 0.1 )
self:OnIntervalThink()
-- play effects
self:PlayEffects()
end
function modifier_slark_pounce_lua:OnRefresh( kv )
end
function modifier_slark_pounce_lua:OnRemoved()
end
function modifier_slark_pounce_lua:OnDestroy()
if not IsServer() then return end
-- set active
self:GetAbility():SetActivated( true )
-- destroy trees upon land
GridNav:DestroyTreesAroundPoint( self.parent:GetOrigin(), 100, false )
-- destroy arc modifier
if self.arc and not self.arc:IsNull() then
self.arc:Destroy()
end
end
--------------------------------------------------------------------------------
-- Status Effects
function modifier_slark_pounce_lua:CheckState()
local state = {
[MODIFIER_STATE_DISARMED] = true,
}
return state
end
--------------------------------------------------------------------------------
-- Interval Effects
function modifier_slark_pounce_lua:OnIntervalThink()
-- find units
local enemies = FindUnitsInRadius(
self.parent:GetTeamNumber(), -- int, your team number
self.parent:GetOrigin(), -- point, center point
nil, -- handle, cacheUnit. (not known)
self.radius, -- float, radius. or use FIND_UNITS_EVERYWHERE
DOTA_UNIT_TARGET_TEAM_ENEMY, -- int, team filter
DOTA_UNIT_TARGET_HERO, -- int, type filter
0, -- int, flag filter
FIND_CLOSEST, -- int, order filter
false -- bool, can grow cache
)
local target
for _,enemy in pairs(enemies) do
if not enemy:IsIllusion() then
target = enemy
break
end
end
if not target then return end
-- add leash
target:AddNewModifier(
self.parent, -- player source
self:GetAbility(), -- ability source
"modifier_slark_pounce_lua_debuff", -- modifier name
{
duration = self.leash_duration,
radius = self.leash_radius,
purgable = false,
} -- kv
)
-- play effects
local sound_cast = "Hero_Slark.Pounce.Impact"
EmitSoundOn( sound_cast, target )
-- destroy
self:Destroy()
end
--------------------------------------------------------------------------------
-- Graphics & Animations
function modifier_slark_pounce_lua:GetEffectName()
return "particles/units/heroes/hero_slark/slark_pounce_trail.vpcf"
end
function modifier_slark_pounce_lua:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
function modifier_slark_pounce_lua:PlayEffects()
-- Get Resources
local particle_cast = "particles/units/heroes/hero_slark/slark_pounce_start.vpcf"
-- Create Particle
local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_ABSORIGIN_FOLLOW, self.parent )
ParticleManager:ReleaseParticleIndex( effect_cast )
end
|
vim.opt.fileencodings = { "utf-8", "iso-2022-jp", "euc-jp", "sjis" }
vim.opt.fileformats = { "unix", "dos", "mac" }
vim.opt.wildmode = { "longest", "full" }
vim.opt.nrformats = { "bin", "hex" }
vim.opt.autochdir = true
vim.opt.breakindent = true
vim.opt.confirm = true
vim.opt.expandtab = true
vim.opt.hidden = true
vim.opt.ignorecase = true
vim.opt.linebreak = true
vim.opt.number = true
vim.opt.showmatch = true
vim.opt.smartcase = true
vim.opt.smartindent = true
vim.opt.splitbelow = true
vim.opt.splitright = true
vim.opt.swapfile = false
vim.opt.scrolloff = 5
vim.opt.shiftwidth = 4
vim.opt.tabstop = 4
vim.opt.history = 200
vim.opt.cmdheight = 2
vim.opt.ttimeoutlen = 100
vim.opt.clipboard = "unnamed"
vim.opt.display = "lastline"
vim.opt.mouse = "a"
vim.opt.viminfofile = "NONE"
|
str = "Hello world"
length = #str
|
local export = {}
local conv = {
--consonants without nukta
["ਸ"] = "s",
["ਹ"] = "h",
["ਕ"] = "k", ["ਖ"] = "kh", ["ਗ"] = "g", ["ਘ"] = "gh", ["ਙ"] = "ṅ",
["ਚ"] = "c", ["ਛ"] = "ch", ["ਜ"] = "j", ["ਝ"] = "jh", ["ਞ"] = "ñ",
["ਟ"] = "ṭ", ["ਠ"] = "ṭh", ["ਡ"] = "ḍ", ["ਢ"] = "ḍh", ["ਣ"] = "ṇ",
["ਤ"] = "t", ["ਥ"] = "th", ["ਦ"] = "d", ["ਧ"] = "dh", ["ਨ"] = "n",
["ਪ"] = "p", ["ਫ"] = "ph", ["ਬ"] = "b", ["ਭ"] = "bh", ["ਮ"] = "m",
["ਯ"] = "y", ["ਰ"] = "r", ["ਲ"] = "l", ["ਵ"] = "v", ["ੜ"] = "ṛ",
--consonants with nukta
["ਸ਼"] = "ś",
["ਖ਼"] = "x",
["ਗ਼"] = "ġ",
["ਜ਼"] = "z",
["ਫ਼"] = "f",
["ਲ਼"] = "ḷ",
["ਕ਼"] = "q",
["ਡ਼"] = "ṛ",
-- vowels
["ਾ"] = "ā",
["ਿ"] = "i", ["ੀ"] = "ī",
["ੁ"] = "u", ["ੂ"] = "ū",
["ੇ"] = "ē", ["ੈ"] = "ai",
["ੋ"] = "o", ["ੌ"] = "au",
-- other diacritics
["ੰ"] = "N", --ṭippi: nasalize
["ਂ"] = "N", --bindi: nasalize
["ੱ"] = "ː", --addak: geminate
["੍"] = "", --halant, supresses the inherent vowel "a"
["ਃ"] = "h", --voiceless "h" sound (tone raiser)
-- independent vowels
["ਅ"] = "a", ["ਆ"] = "ā",
["ਇ"] = "i", ["ਈ"] = "ī",
["ਉ"] = "u", ["ਊ"] = "ū",
["ਏ"] = "ē", ["ਐ"] = "ai",
["ਓ"] = "o", ["ਔ"] = "ō",
-- digits
["੦"] = "0", ["੧"] = "1", ["੨"] = "2", ["੩"] = "3", ["੪"] = "4",
["੫"] = "5", ["੬"] = "6", ["੭"] = "7", ["੮"] = "8", ["੯"] = "9",
}
local nasal_assim = {
["[kg]h?"] = "ṅ",
["[cj]h?"] = "ñ",
["[ṭḍ]h?"] = "ṇ",
["[td]h?"] = "n",
["[pb]h?"] = "m",
["n"] = "n",
["m"] = "m",
["s"] = "n",
}
-- translit any words or phrases
function export.tr(text, lang, sc)
local c = "([ਸਹਕਖਗਘਙਚਛਜਝਞਟਠਡਢਣਤਥਦਧਨਪਫਬਭਮਯਰਲਵੜː]਼?)"
local y = "ਯ"
local v = "([aਾਿੀੁੂੇੈੋੌ੍])"
local virama = "੍"
local n = "([ੰਂ]?)"
local nukta = "([ਸਖਗਜਫਲਕਡ]਼)"
local can_drop = mw.ustring.gsub(c,y,"")
local no_virama = mw.ustring.gsub(v,virama,"")
text = text .. " "
text = mw.ustring.gsub(text,c,"%1a")
text = mw.ustring.gsub(text,"a"..v,"%1")
-- mw.log(text)
text = mw.ustring.gsub(text,v..n..can_drop.."a ","%1%2%3 ") --ending
-- mw.log(text)
text = mw.ustring.gsub(text,v..n..can_drop.."a"..c..v,"%1%2%3%4%5")
-- mw.log(text)
text = mw.ustring.gsub(text,nukta,conv)
text = mw.ustring.gsub(text,".",conv)
for key,val in pairs(nasal_assim) do
text = mw.ustring.gsub(text,"N("..key..")",val.."%1")
end
text = mw.ustring.gsub(text,"([aiuēaioāīū])N ", "%1̃ ")
text = mw.ustring.gsub(text,"(.?)N", "%1̃")
text = mw.ustring.gsub(text,"ː(.)","%1%1")
text = mw.ustring.gsub(text," ?।",".")
text = mw.ustring.gsub(text," $","")
return mw.ustring.toNFC(text)
end
return export
|
l = sexpr(1, 2, 3)
print(l)
assert(is_sexpr(l))
assert(is_sexpr(sexpr(10)))
assert(not is_sexpr(10))
assert(not is_sexpr({}))
|
--[[
Created by DidVaitel (http://steamcommunity.com/profiles/76561198108670811)
]]
gDuel.vgui = gDuel.vgui or {}
surface.CreateFont( 'gDuelFont100', {
font = 'Roboto',
size = 100,
weight = 500
} )
surface.CreateFont( 'gDuelFont20', {
font = 'Roboto',
size = 20,
weight = 500
} )
surface.CreateFont( 'gDuelFont18', {
font = 'Roboto',
size = 18,
weight = 500
} )
surface.CreateFont( 'gDuelFont15', {
font = 'Roboto',
size = 15,
weight = 500
} )
surface.CreateFont( 'gDuelFont14', {
font = 'Roboto',
size = 14,
weight = 500
} )
// Our functions
local blur = Material 'pp/blurscreen'
local Linecolor = Color(255, 255, 255, 100)
// Blur
function gDuel.vgui.DrawBlur( pan, amt )
local x, y = pan:LocalToScreen( 0, 0 )
surface.SetDrawColor( 255, 255, 255 )
surface.SetMaterial( blur )
for i = 1, 3 do
blur:SetFloat( '$blur', ( i / 3 ) * ( amt or 6 ) )
blur:Recompute()
render.UpdateScreenEffectTexture()
surface.DrawTexturedRect( x * -1, y * -1, ScrW(), ScrH() )
end
end
// Line
function gDuel.vgui.DrawLine( x1, y1, x2, y2, clr )
if not clr then clr = Color( 255, 255, 255 ) end
surface.SetDrawColor( clr )
surface.DrawLine( x1, y1, x2, y2 )
end
// Box
function gDuel.vgui.DrawBox( x, y, w, h, clr, out )
if not clr then clr = Color( 15, 15, 15, 200 ) end
surface.SetDrawColor( clr )
surface.DrawRect( x, y, w, h )
if out then
gDuel.vgui.DrawOutlinedBox(x, y, w, h, Color(0, 0, 0, 0))
end
end
// DrawOutlinedBox
function gDuel.vgui.DrawOutlinedBox( x, y, w, h, clr )
if not clr then clr = Color( 15, 15, 15, 200 ) end
//gDuel.vgui.DrawBox( x, y, w, h, clr )
surface.SetDrawColor(Linecolor)
surface.DrawOutlinedRect(x, y, w, h)
end
function gDuel.vgui.txt( str, size, x, y, clr, a1, a2 )
if not a1 then a1 = 0 end
if not a2 then a2 = 0 end
if not clr or clr == nil then clr = Color( 255, 255, 255 ) end
draw.SimpleText( str, 'gDuelFont' .. size, x, y, clr, a1, a2 )
end
function gDuel.vgui.scroll(parent, x, y, w, h, down, ph, items)
local scroll = parent:Add 'DScrollPanel'
scroll:SetSize(w, h)
scroll:SetPos(x, y)
scroll:GetVBar():SetWide(0)
if items then items(scroll) end
return scroll
end
// txt entery
PANEL = {}
function PANEL:Init()
self:SetFont( 'DermaDefault' )
end
function PANEL:Paint( w, h )
gDuel.vgui.DrawOutlinedBox(0, 0, w, h)
self:DrawTextEntryText(color_white, Color( 150, 150, 150, 150 ), color_white )
end
vgui.Register('gTxtEntry', PANEL, 'DTextEntry')
function gDuel.vgui.txtentry(name, parent, x, y, w, h, onchange, secval)
local idText = parent:Add 'gTxtEntry'
idText:SetSize(w, h)
idText:SetPos(x, y)
idText:SetText(name)
idText:SetFont 'gDuelFont18'
function idText:OnChange()
onchange(self, self:GetValue())
end
function idText:OnGetFocus()
if self:GetValue() == name then
self:SetValue ''
end
end
return idText
end
|
#!/usr/bin/env lua
require 'Test.Assertion'
plan(12)
local doc = [[
{
"title": "api",
"version": "v1",
"description": "api for unit test",
"basePath": "/restapi/",
"documentationLink": "http://developers.google.com/discovery",
"resources": {
"test": {
"methods": {
"get": {
"id": "foo.get_info",
"path": "/show",
"httpMethod": "GET",
"parameters": {
"user": {},
"border": {}
}
}
}
}
}
}
]]
require 'Spore.Protocols'.slurp = function ()
return doc
end -- mock
require 'Spore'.new_from_lua = function (t)
return t
end --mock
local m = require 'Spore.GoogleDiscovery'
is_table( m, "Spore.GoogleDiscovery" )
equals( m, package.loaded['Spore.GoogleDiscovery'] )
is_function( m.new_from_discovery )
is_function( m.convert )
local spec = m.new_from_discovery('mock')
equals( spec.name, 'api' )
equals( spec.version, 'v1' )
equals( spec.description, 'api for unit test' )
equals( spec.base_url, 'https://www.googleapis.com/restapi/' )
equals( spec.meta.documentation, 'http://developers.google.com/discovery' )
local meth = spec.methods.get_info
is_table( meth )
equals( meth.path, '/show' )
equals( meth.method, 'GET' )
|
Weapon.PrettyName = "Remington 870"
Weapon.WeaponID = "m9k_remington870"
Weapon.DamageMultiplier = 1.0
Weapon.WeaponType = WEAPON_PRIMARY
|
local style = data.raw['gui-style'].default
style.filterfill_requests = {
type = 'table_style',
parent = 'picker_table'
}
style.filterfill_filters = {
type = 'table_style',
parent = 'picker_table'
}
data:extend {
{
type = 'sprite',
name = 'picker-request-bp',
filename = '__PickerInventoryTools__/graphics/filterfill.png',
priority = 'extra-high',
width = 64,
height = 64,
x = 320,
y = 0
},
{
type = 'sprite',
name = 'picker-request-2x',
filename = '__PickerInventoryTools__/graphics/filterfill.png',
priority = 'extra-high',
width = 64,
height = 64,
x = 384,
y = 0
},
{
type = 'sprite',
name = 'picker-request-5x',
filename = '__PickerInventoryTools__/graphics/filterfill.png',
priority = 'extra-high',
width = 64,
height = 64,
x = 448,
y = 0
},
{
type = 'sprite',
name = 'picker-request-10x',
filename = '__PickerInventoryTools__/graphics/filterfill.png',
priority = 'extra-high',
width = 64,
height = 64,
x = 512,
y = 0
},
{
type = 'sprite',
name = 'picker-request-max',
filename = '__PickerInventoryTools__/graphics/filterfill.png',
priority = 'extra-high',
width = 64,
height = 64,
x = 576,
y = 0
},
{
type = 'sprite',
name = 'picker-request-clear',
filename = '__PickerInventoryTools__/graphics/filterfill.png',
priority = 'extra-high',
width = 64,
height = 64,
x = 256,
y = 0
}
}
data:extend {
{
type = 'sprite',
name = 'picker-filters-all',
filename = '__PickerInventoryTools__/graphics/filterfill.png',
priority = 'extra-high',
width = 64,
height = 64,
x = 0,
y = 0
},
{
type = 'sprite',
name = 'picker-filters-down',
filename = '__PickerInventoryTools__/graphics/filterfill.png',
priority = 'extra-high',
width = 64,
height = 64,
x = 64,
y = 0
},
{
type = 'sprite',
name = 'picker-filters-right',
filename = '__PickerInventoryTools__/graphics/filterfill.png',
priority = 'extra-high',
width = 64,
height = 64,
x = 128,
y = 0
},
{
type = 'sprite',
name = 'picker-filters-set-all',
filename = '__PickerInventoryTools__/graphics/filterfill.png',
priority = 'extra-high',
width = 64,
height = 64,
x = 192,
y = 0
},
{
type = 'sprite',
name = 'picker-filters-clear-all',
filename = '__PickerInventoryTools__/graphics/filterfill.png',
priority = 'extra-high',
width = 64,
height = 64,
x = 256,
y = 0
}
}
|
-- flexdash_ui_button.lua
local white = {1, 1, 1, 1}
local MOUSE_OFF = 1
local MOUSE_HOVER = 2
local MOUSE_DOWN = 3
local mouse_status = MOUSE_OFF
flexdash_lib.num_click_spots = flexdash_lib.num_click_spots + 1
local is_me = flexdash_lib.num_click_spots
defineProperty("button_name", "fd_big_button_down")
defineProperty("width", 48)
defineProperty("height", 48)
local button_image = {}
button_image[MOUSE_OFF] = sasl.gl.loadImage ("ui_assets/"..get(button_name).."_off.png", 0, 0, get(width), get(height))
button_image[MOUSE_HOVER] = sasl.gl.loadImage ("ui_assets/"..get(button_name).."_over.png", 0, 0, get(width), get(height))
button_image[MOUSE_DOWN] = sasl.gl.loadImage ("ui_assets/"..get(button_name).."_click.png", 0, 0, get(width), get(height))
function onMouseMove(component, x, y, button, parentX, parentY)
return true
end
function onMouseDown(component, x, y, button, parentX, parentY)
if flexdash_lib.owns_mousedown == 0 then
flexdash_lib.owns_mousedown = is_me -- only one clicky thing should have control of the mouseUp/mouseHold events or strange things happens
if button == MB_LEFT then
mouse_status = MOUSE_DOWN
end
flexdash_lib.doMouseDown (button, parentX, parentY, get(button_name))
end
return true
end
function onMouseUp(component, x, y, button, parentX, parentY)
mouse_status = MOUSE_HOVER
if flexdash_lib.owns_mousedown == is_me then
if x < 0 or y < 0 or x > get(position)[3] or y > get(position)[4] then
mouse_status = MOUSE_OFF
else
flexdash_lib.doMouseUp (button, parentX, parentY, get(button_name))
end
else
mouse_status = MOUSE_OFF
end
flexdash_lib.owns_mousedown = 0
return true
end
function onMouseHold (component, x, y, button, parentX, parentY)
if flexdash_lib.owns_mousedown == is_me then
flexdash_lib.doMouseHold(button, parentX, parentY, get(button_name))
end
return true
end
function onMouseEnter()
if flexdash_lib.owns_mousedown == is_me then
mouse_status = MOUSE_DOWN
else
mouse_status = MOUSE_HOVER
end
end
function onMouseLeave()
mouse_status = MOUSE_OFF
end
function draw()
sasl.gl.drawTexture ( button_image[mouse_status] , 0, 0, size[1] , size[2], white)
end
|
local BitStruct = {
_width = 1, -- Prototype default width for each field we create
_base = 0, -- Prototype default bit number for each field we create
}
function BitStruct:new(o)
o = o or {}
local newFields = {
_base = o._base or 0,
_width = o._width or 1,
_fields = o._fields or {},
} -- Our new list of fields once all fixups are done
self.__index = self
setmetatable(o, self)
local base = newFields._base -- Bit number that is base of next field we encounter
-- Iterate over requested field descriptors and turn them into real fields.
for k,v in ipairs(o) do
if math.type(v) == 'integer' then
error('BitStruct:new cannot (yet) support integer values')
elseif type(v) == 'boolean' then -- A single bit field
error('BitStruct:new cannot (yet) support boolean values')
elseif type(v) == 'table' then
-- Build a descriptor for a set of fields starting at our current base bit number.
local subTableDesc = {_base = base}
table.move(v, 1, #v, 1, subTableDesc)
-- Recurse to define fields specified in a descriptor that is itself a table.
local subTable = BitStruct:new(subTableDesc)
-- Add the subTable fields to our object being constructed.
for subK, subV in pairs(subTable) do
newFields[#newFields] = subV
end
elseif type(v) == 'string' then
local w = o._parentWidth or 1 -- Parent's width (e.g., dword 32b) or one bit if no parent
o[v] = BitStruct:new{_width=w, _base=base}
base = base + w
elseif type(v) == 'function' then
local w, field = v(k, base)
newFields[#newFields] = field
print("type function returns", w, field)
for wk,wv in pairs(w) do print(" wfield ", wk, wv) end
base = base + w
end
end
-- Update width to span all of the fields we just processed.
o._width = base - o._base
return o
end
-- Create a constructor for a fixed sized word with subfields. This
-- can be used to create functions to make DWORDs, Short, Byte, etc.
-- and subdivide their bits into named fields. The resulting function
-- can then be used to declare the subfields as first class members of
-- the parent BitStruct structure.
--
-- The constructor creates a function to find each of the
-- constructor's child fields to their bit base and width, returning a
-- table with the fields configured this wayt aht can then be handled
-- as a "subTable" as if the table were a member of the list of fields
-- presented to the BitField:new() constructor.
function BitStruct.FixedWordFactory(wordWidth)
return function(fields) -- Creates list of fields in list passed to BitStruct:new()
print("FixedWordFactory factory fields:")
for k,v in pairs(fields) do print(" ", k,v) end
return function(field, base) -- Binds a field to its true base and width as BitField:new() proceeds
print("factory result field", field, " base", base, " wordWidth", wordWidth)
print("factory result fields:")
for k,v in pairs(fields) do
print(" ", k,v)
if (type(v) == 'table') then
for k2,v2 in pairs(v) do
print(" ", k2, v2)
end
end
end
return {
_wordWidth=wordWidth,
}
end
end
end
-- TESTS ################################################################
local dword = BitStruct:FixedWordFactory(32)
local short = BitStruct:FixedWordFactory(16)
local s = BitStruct:new{
twoBit = {14,13},
severalBits = {12,8},
aByte = {7,0},
dword{
byte3={31,24},
byte2={23,16},
byte1={15,8},
byte0={7,0},
},
short{
s1={15,8},
s0={7,0},
},
}
for k,v in pairs(s) do print(k,v) end
return BitStruct
|
--
-- Xbox One XDK tests
-- Copyright Blizzard Entertainment, Inc
--
local p = premake
local suite = test.declare("durango_globals")
local vc2010 = p.vstudio.vc2010
--
-- Setup
--
local wks, prj
function suite.setup()
p.action.set("vs2017")
wks, prj = test.createWorkspace()
end
local function prepare()
kind "WindowedApp"
system "durango"
prj = test.getproject(wks, 1)
vc2010.globals(prj)
end
function suite.onDefaultValues()
prepare()
test.capture [[
<PropertyGroup Label="Globals">
<ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid>
<IgnoreWarnCompileDuplicatedFilename>true</IgnoreWarnCompileDuplicatedFilename>
<LatestTargetPlatformVersion>$([Microsoft.Build.Utilities.ToolLocationHelper]::GetLatestSDKTargetPlatformVersion('Windows', '10.0'))</LatestTargetPlatformVersion>
<WindowsTargetPlatformVersion>$(LatestTargetPlatformVersion)</WindowsTargetPlatformVersion>
<DefaultLanguage>en-US</DefaultLanguage>
<ApplicationEnvironment>title</ApplicationEnvironment>
<TargetRuntime>Native</TargetRuntime>
</PropertyGroup>
]]
end
|
-----------------------------------------------------------------------------------------
-- Decorators
-- Filter
-- Filters the access of it's child node either a specific number of times, or every
-- specific amount of time. By default the node is 'Treated as Inactive' to it's parent
-- when child is Filtered. Unchecking this option will instead return Failure when Filtered.
-----------------------------------------------------------------------------------------
local Filter = bt.Class("Filter",bt.BTDecorator)
bt.Filter = Filter
FilterMode =
{
LimitNumberOfTimes = 0,
CoolDown = 1,
}
Policy =
{
SuccessOrFailure = 0,
SuccessOnly = 1,
FailureOnly = 2,
}
function Filter:ctor()
bt.BTDecorator.ctor(self)
self.name = "Filter"
self.filterMode = FilterMode.CoolDown
self.maxCount = 1
self.coolDownTime = 5
self.inactiveWhenLimited = true
self.policy = Policy.SuccessOrFailure
self.executedCount = 0
self.currentTime = 0
self.cooldownFuncId = 0
end
function Filter:init(jsonData)
if jsonData.filterMode ~= nil then
self.filterMode = FilterMode[jsonData.filterMode]
end
if jsonData.maxCount ~= nil then
self.maxCount = jsonData.maxCount._value
end
if jsonData.coolDownTime ~= nil then
self.coolDownTime = jsonData.coolDownTime._value
end
if jsonData.inactiveWhenLimited ~= nil then
self.inactiveWhenLimited = jsonData.inactiveWhenLimited
end
if jsonData.policy ~= nil then
self.policy = Policy[jsonData.policy]
end
end
function Filter:onExecute(agent,blackboard)
local decoratedConnection = self:getDecoratedConnection()
if decoratedConnection == nil then
return bt.Status.Resting
end
if self.filterMode == FilterMode.CoolDown then
if self.currentTime > 0 then
if self.inactiveWhenLimited then
return bt.Status.Optional
else
return bt.Status.Failure
end
end
self.status = decoratedConnection:execute(agent,blackboard)
if self.status == bt.Status.Success or self.status == bt.Status.Failure then
self.currentTime = self.coolDownTime
self.cooldownFuncId = bt.addLoopFunc(self.coolDown,self)
end
elseif self.filterMode == FilterMode.LimitNumberOfTimes then
if self.executedCount > self.maxCount then
if self.inactiveWhenLimited then
return bt.Status.Optional
else
return bt.Status.Failure
end
end
self.status = decoratedConnection:execute(agent,blackboard)
if (self.status == bt.Status.Success and self.policy == Policy.SuccessOnly) or
(self.status == bt.Status.Failure and self.policy == Policy.FailureOnly) or
((self.status == bt.Status.Success or self.status == bt.Status.Failure)
and self.policy == Policy.SuccessOrFailure) then
self.executedCount = self.executedCount + 1
self:debug(self.executedCount)
end
end
return self.status
end
function Filter:onGraphStarted()
self.executedCount = 0
self.currentTime = 0
end
function Filter:coolDown()
if self.cooldownFuncId then
self.currentTime = self.currentTime - bt.deltaTime
self:debug(string.format( "cooldown:%.2f/%.2f",self.currentTime,self.coolDownTime))
if self.currentTime <= 0 then
self.currentTime = 0
bt.delLoopFunc(self.cooldownFuncId)
self.cooldownFuncId = 0
end
end
end
function Filter:destroy()
if self.cooldownFuncId > 0 then
bt.delLoopFunc(self.cooldownFuncId)
end
end
|
--------------------------------------------------------------------------------
-- State............ : Debug
-- Author........... :
-- Description...... :
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function Steam.Debug_onEnter ( )
--------------------------------------------------------------------------------
log.message ( this.sDebugLabel ( ), "Debug++" )
--Steamworks.ResetAllStats ( true )
--
-- Setup the Achievement HUD
--
hud.newTemplateInstance ( this.getUser ( ), "SteamDebug", "SteamDebug" )
local hList = hud.getComponent ( this.getUser ( ), "SteamDebug.MenuList" )
hud.addListColumn ( hList )
hud.addListColumn ( hList )
hud.addListColumn ( hList )
hud.addListColumn ( hList )
hud.addListColumn ( hList )
hud.addListItem ( hList, "" )
-- ID
hud.setListColumnTextAlignmentAt ( hList, 0, hud.kAlignLeft, hud.kAlignCenter )
hud.setListColumnWidthAt ( hList, 0, 20 )
-- Name
hud.setListColumnTextAlignmentAt ( hList, 1, hud.kAlignLeft, hud.kAlignCenter )
hud.setListColumnWidthAt ( hList, 1, 20 )
-- Description
hud.setListColumnTextAlignmentAt ( hList, 2, hud.kAlignLeft, hud.kAlignCenter )
hud.setListColumnWidthAt ( hList, 2, 40 )
-- Percent
hud.setListColumnTextAlignmentAt ( hList, 3, hud.kAlignCenter, hud.kAlignCenter )
hud.setListColumnWidthAt ( hList, 3, 10 )
-- Achieved
hud.setListColumnTextAlignmentAt ( hList, 4, hud.kAlignCenter, hud.kAlignCenter )
hud.setListColumnWidthAt ( hList, 4, 10 )
-- Create the labels
local hID = this.debugCreateLabel ( "ID", "SteamDebug.ID" )
local hName = this.debugCreateLabel ( "Name", "SteamDebug.Name" )
local hDescription = this.debugCreateLabel ( "Desc.", "SteamDebug.Desc" )
local hPercent = this.debugCreateLabel ( "%", "SteamDebug.Percent" )
local hAchieved = this.debugCreateLabel ( "Achieved", "SteamDebug.Achieved" )
-- Set the labels as the content
hud.setListItemChildAt ( hList, 0, 0, hID )
hud.setListItemChildAt ( hList, 0, 1, hName )
hud.setListItemChildAt ( hList, 0, 2, hDescription )
hud.setListItemChildAt ( hList, 0, 3, hPercent )
hud.setListItemChildAt ( hList, 0, 4, hAchieved )
--
-- Setup the Stats HUD
--
local hStatsList = hud.getComponent ( this.getUser ( ), "SteamDebug.StatList" )
hud.addListColumn ( hStatsList )
hud.addListColumn ( hStatsList )
hud.addListColumn ( hStatsList )
hud.addListColumn ( hStatsList )
hud.addListItem ( hStatsList, "" )
-- Name
hud.setListColumnTextAlignmentAt ( hStatsList, 0, hud.kAlignLeft, hud.kAlignCenter )
hud.setListColumnWidthAt ( hStatsList, 0, 33 )
-- Type
hud.setListColumnTextAlignmentAt ( hStatsList, 1, hud.kAlignLeft, hud.kAlignCenter )
hud.setListColumnWidthAt ( hStatsList, 1, 33 )
-- Value
hud.setListColumnTextAlignmentAt ( hStatsList, 2, hud.kAlignLeft, hud.kAlignCenter )
hud.setListColumnWidthAt ( hStatsList, 2, 33 )
local hStatName = this.debugCreateLabel ( "Name", "SteamDebug.StatName" )
local hStatType = this.debugCreateLabel ( "Type", "SteamDebug.StatType" )
local hStatValue = this.debugCreateLabel ( "Value", "SteamDebug.StatValueH" )
hud.setListItemChildAt ( hStatsList, 0, 0, hStatName )
hud.setListItemChildAt ( hStatsList, 0, 1, hStatType )
hud.setListItemChildAt ( hStatsList, 0, 2, hStatValue )
--
-- Show the player name
--
local hPlayerName = hud.getComponent ( this.getUser ( ), "SteamDebug.PlayerName" )
local sPlayerName = Steamworks.GetLocalPlayerName ( )
hud.setLabelText ( hPlayerName, "Player: "..sPlayerName )
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
|
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
--
-- This file is compatible with Lua 5.3
local class = require("class")
require("kaitaistruct")
local str_decode = require("string_decode")
OpaqueExternalType02Child = class.class(KaitaiStruct)
function OpaqueExternalType02Child:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function OpaqueExternalType02Child:_read()
self.s1 = str_decode.decode(self._io:read_bytes_term(124, false, true, true), "UTF-8")
self.s2 = str_decode.decode(self._io:read_bytes_term(124, false, false, true), "UTF-8")
self.s3 = OpaqueExternalType02Child.OpaqueExternalType02ChildChild(self._io, self, self._root)
end
OpaqueExternalType02Child.property.some_method = {}
function OpaqueExternalType02Child.property.some_method:get()
if self._m_some_method ~= nil then
return self._m_some_method
end
self._m_some_method = true
return self._m_some_method
end
OpaqueExternalType02Child.OpaqueExternalType02ChildChild = class.class(KaitaiStruct)
function OpaqueExternalType02Child.OpaqueExternalType02ChildChild:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function OpaqueExternalType02Child.OpaqueExternalType02ChildChild:_read()
if self._root.some_method then
self.s3 = str_decode.decode(self._io:read_bytes_term(64, true, true, true), "UTF-8")
end
end
|
object_tangible_collection_reward_buddy_painting_01 = object_tangible_collection_reward_shared_buddy_painting_01:new {
}
ObjectTemplates:addTemplate(object_tangible_collection_reward_buddy_painting_01, "object/tangible/collection/reward/buddy_painting_01.iff")
|
local socket = require("socket.core")
local cjson = require("cjson")
local other_port = 8080
local ip = '127.0.0.1'
print('Starting socket')
udp = socket.udp()
udp:setsockname("*", 8088)
local cmd = {command='init', args={num_inputs=2, num_outputs=2, num_genomes=100, allow_recurrent=true}}
udp:sendto(cjson.encode(cmd), ip, other_port)
res_json = udp:receive()
res = cjson.decode(res_json)
cmd = {command='start_gen'}
udp:sendto(cjson.encode(cmd), ip, other_port)
res_json = udp:receive()
res = cjson.decode(res_json)
cmd = {command='get_output', args={genome=0,inputs={0.1,0.3}}}
udp:sendto(cjson.encode(cmd), ip, other_port)
res_json = udp:receive()
res = cjson.decode(res_json)
for i, v in pairs(res['result']) do
print(i, v)
end
|
do class "BasicClassA"
{
m_bBool = false,
m_strString = "Hello World",
m_nNumber = 1,
}
getter "Bool->m_bBool"
getter "String->m_strString"
getter "Number->m_nNumber"
function Initialize( self )
end
function __GC( self )
self.m_bBool = false
end
end
|
--[[
Author: Noya
Date: 16.01.2015.
After the passive is upgraded, it checks all player controled units for the modifiers to update the buff.
Note: To actually apply a synergy buff on every summoned unit as soon they are spawned, you'll need to run a thinker that globally checks your controlled units and applies modifier.
]]
function SynergyLevel( event )
local caster = event.caster
local targets = event.target_entities
local ability = event.ability
-- Unit name contains a part of the unit name, so you can make different levels of the unit and they will still be registered
-- If you change this to "npc_" in the parameter passed, it will affect all self-controlled units
local unit_name = event.unit_name
-- Re-apply modifier_bear_synergy, only check for units that start with the unit_name
for _,unit in pairs(targets) do
print(unit:GetUnitName())
if unit:GetOwner() == caster then
local u = unit:GetUnitName()
local string_contains_unit = string.find( tostring(u) , tostring(unit_name))
if string_contains_unit == 1 then
print("Remove and apply")
unit:RemoveModifierByName("modifier_bear_synergy")
ability:ApplyDataDrivenModifier(caster, unit, "modifier_bear_synergy", {} )
end
end
end
-- Re-apply modifier_true_form on the caster
if caster:HasModifier("modifier_true_form_synergy") then
caster:RemoveModifierByName("modifier_true_form_synergy")
ability:ApplyDataDrivenModifier(caster, caster, "modifier_true_form_synergy", {} )
end
end
|
MDIR = "patch/meta/"
print("Loading execfg.lua...")
dofile(MDIR .. "execfg.lua") -- sets ORIGINAL_EXE and BUILD_PATH
print("Opening database...")
img_open(":memory:")
print("Populating database tables...")
sql_file(MDIR .. "tables.sql")
print("Loading original EXE...")
img_loadexe(ORIGINAL_EXE, true, true, true, false)
print("Loading plan for section 1...")
img_loadplan(1, MDIR .. "1plan.bin")
print("Walking image plan...")
img_walkplan(1)
|
local Class = require('./utils/class')
local logger = require('./utils/logger')
local queue_to_vkscript = require('./utils/queue_to_vkscript')
local set_interval = require('timer').setInterval
local Queue = Class()
--- Create Queue object
-- @param vk (table) - vk object
-- @return Queue object
function Queue:init(vk)
self.vk = vk
self.queue = {} -- {{method, params}, {method, params}}
local interval = 1/(20 * #vk.token)
set_interval(interval*1000, function()
coroutine.wrap(self.send_queue)(self)
end)
end
--- Send queue
function Queue:send_queue()
if #self.queue == 0 then return end
local queue = {}
local waiters = {}
local count = math.min(25, #self.queue)
for i=1, count do
queue[i], waiters[i] = unpack(self.queue[1])
table.remove(self.queue, 1)
end
local res, err = self.vk:request('execute', {code=queue_to_vkscript(queue)})
if not res then
logger:error(err)
return
end
local co_suc, co_err
for i, val in ipairs(res) do
co_suc, co_err = coroutine.resume(waiters[i], val)
if not co_suc then
logger:error(co_err)
end
end
end
--- Make queued vk request
-- @param method (string) vk method to execute
-- @param params (table|nil) table of method args
-- @return data (table|nil) result or nil if error
-- @return error(nil|table) nil or error
function Queue:request(method, params)
table.insert(self.queue, {{method, params}, coroutine.running()})
return coroutine.yield()
end
return Queue
|
--[[
Name: toyota.lua
For: TalosLife
By: TalosLife
]]--
local Car = {}
Car.Make = "Toyota"
Car.Name = "MR2 GT"
Car.UID = "toyota_mr2gt"
Car.Desc = "A drivable Toyota MR2 GT by TheDanishMaster"
Car.Model = "models/tdmcars/toy_mr2gt.mdl"
Car.Script = "scripts/vehicles/TDMCars/mr2gt.txt"
Car.Price = 3000
Car.FuellTank = 70
Car.FuelConsumption = 9
GM.Cars:Register( Car )
local Car = {}
Car.Make = "Toyota"
Car.Name = "Tundra Crewmax"
Car.UID = "toyota_crewmax"
Car.Desc = "A drivable Toyota Tundra Crewmax by TheDanishMaster"
Car.Model = "models/tdmcars/toy_tundra.mdl"
Car.Script = "scripts/vehicles/TDMCars/toytundra.txt"
Car.Price = 30000
Car.FuellTank = 115
Car.FuelConsumption = 8
GM.Cars:Register( Car )
local Car = {}
Car.Make = "Toyota"
Car.Name = "Prius"
Car.UID = "toyota_prius"
Car.Desc = "A drivable Toyota Prius by TheDanishMaster"
Car.Model = "models/tdmcars/prius.mdl"
Car.Script = "scripts/vehicles/TDMCars/prius.txt"
Car.Price = 21000
Car.FuellTank = 53.55
Car.FuelConsumption = 31.25
GM.Cars:Register( Car )
local Car = {}
Car.Make = "Toyota"
Car.Name = "Supra"
Car.UID = "toyota_supra"
Car.Desc = "A drivable Toyota Supra by TheDanishMaster"
Car.Model = "models/tdmcars/supra.mdl"
Car.Script = "scripts/vehicles/TDMCars/supra.txt"
Car.Price = 65000
Car.FuellTank = 60
Car.FuelConsumption = 10.6
GM.Cars:Register( Car )
local Car = {}
Car.Make = "Toyota"
Car.Name = "FJ Cruiser"
Car.UID = "toyota_fjcruiser"
Car.Desc = "A drivable Toyota FJ Cruiser by TheDanishMaster"
Car.Model = "models/tdmcars/toy_fj.mdl"
Car.Script = "scripts/vehicles/TDMCars/toyfj.txt"
Car.Price = 33000
Car.FuellTank = 85.5
Car.FuelConsumption = 11.8
GM.Cars:Register( Car )
local Car = {}
Car.Make = "Toyota"
Car.Name = "RAV4 Sport"
Car.UID = "toyota_rav4sport"
Car.Desc = "A drivable Toyota RAV4 Sport by TheDanishMaster"
Car.Model = "models/tdmcars/toy_rav4.mdl"
Car.Script = "scripts/vehicles/TDMCars/toyrav4.txt"
Car.Price = 25000
Car.FuellTank = 72
Car.FuelConsumption = 15
GM.Cars:Register( Car )
|
slot0 = class("GuildBossMissionFleet", import("...BaseVO"))
slot0.Ctor = function (slot0, slot1)
slot0.id = slot1.fleet_id
slot0.userShips = {}
slot0.commanders = {}
slot0.invaildShips = {}
slot0.invaildCommanders = {}
if slot1.ships then
slot0:Flush(slot1)
end
end
slot0.Flush = function (slot0, slot1)
slot0.userShips = {}
slot0.invaildShips = {}
for slot5, slot6 in ipairs(slot1.ships) do
if slot0:IsVaildShip({
uid = slot6.user_id,
id = slot6.ship_id
}) then
table.insert(slot0.userShips, slot7)
else
table.insert(slot0.invaildShips, slot7)
end
end
slot2 = getProxy(CommanderProxy):getData()
slot3 = {}
for slot7, slot8 in pairs(slot1.commanders) do
if slot2[slot8.id] and slot8.pos then
slot3[slot8.pos] = slot9
else
table.insert(slot0.invaildCommanders, slot8.id)
end
end
slot0:UpdateCommander(slot3)
end
slot0.GetName = function (slot0)
if slot0:IsMainFleet() then
return i18n("ship_formationUI_fleetName11")
else
return i18n("ship_formationUI_fleetName1")
end
end
slot0.ExistMember = function (slot0, slot1)
return getProxy(GuildProxy):getRawData() and slot2:getMemberById(slot1)
end
slot0.IsVaildShip = function (slot0, slot1)
return slot0.ExistMember(slot0, slot1.uid) and function (slot0)
slot1 = getProxy(GuildProxy):getRawData()
if getProxy(PlayerProxy):getRawData().id == slot0.uid then
return getProxy(BayProxy):getShipById(slot0.id) ~= nil
end
return slot1:getMemberById(slot0.uid).GetAssaultFleet(slot3):ExistShip(GuildAssaultFleet.GetVirtualId(slot0.uid, slot0.id))
end(slot1) and not function (slot0)
return pg.ShipFlagMgr.GetInstance():GetShipFlag(slot0.id, "inEvent")
end(slot1)
end
slot0.ExistInvailShips = function (slot0)
if #slot0.invaildShips > 0 then
return true
end
if _.any(slot0.userShips, function (slot0)
return not slot0:IsVaildShip(slot0)
end) then
return true
end
return false
end
slot0.ClearInvaildShip = function (slot0)
slot0.invaildShips = {}
for slot4 = #slot0.userShips, 1, -1 do
if not slot0:IsVaildShip(slot0.userShips[slot4]) then
table.remove(slot0.userShips, slot4)
end
end
end
slot0.GetMyShipIds = function (slot0)
slot1 = {}
slot2 = getProxy(PlayerProxy):getRawData().id
for slot6, slot7 in ipairs(slot0.userShips) do
if slot7.uid == slot2 then
table.insert(slot1, slot7.id)
end
end
return slot1
end
slot0.GetShipIds = function (slot0)
return slot0.userShips
end
slot0.GetShips = function (slot0)
slot1 = getProxy(PlayerProxy):getData()
slot2 = getProxy(GuildProxy):getData()
slot3 = getProxy(BayProxy)
slot4 = {}
for slot8, slot9 in ipairs(slot0.userShips) do
if slot1.id == slot9.uid then
if slot3:getShipById(slot9.id) then
slot10.id = GuildAssaultFleet.GetVirtualId(slot1.id, slot10.id)
table.insert(slot4, {
member = slot1,
ship = GuildBossMissionShip.New(slot10)
})
end
elseif slot2:getMemberById(slot9.uid) and slot10:GetAssaultFleet() and slot2.getMemberById(slot9.uid) and slot10.GetAssaultFleet():GetShipByRealId(slot9.uid, slot9.id) then
table.insert(slot4, {
member = slot10,
ship = GuildBossMissionShip.New(slot12)
})
end
end
return slot4
end
slot0.RemoveAll = function (slot0)
slot0.userShips = {}
end
slot0.IsMainFleet = function (slot0)
return slot0.id == 1
end
slot0.ExistUserShip = function (slot0, slot1)
return _.any(slot0.userShips, function (slot0)
return slot0.uid == slot0
end)
end
slot0.ContainShip = function (slot0, slot1, slot2)
return _.any(slot0.userShips, function (slot0)
return slot0.uid == slot0 and slot0.id ==
end)
end
slot0.RemoveUserShip = function (slot0, slot1, slot2)
for slot6, slot7 in ipairs(slot0.userShips) do
if slot7.uid == slot1 and slot7.id == slot2 then
table.remove(slot0.userShips, slot6)
return slot6
end
end
end
slot0.AddUserShip = function (slot0, slot1, slot2, slot3)
if slot3 then
table.insert(slot0.userShips, slot3, {
uid = slot1,
id = slot2
})
else
table.insert(slot0.userShips, {
uid = slot1,
id = slot2
})
end
end
slot0.GetOtherMemberShipCnt = function (slot0, slot1)
slot2 = 0
for slot6, slot7 in ipairs(slot0.userShips) do
if slot7.uid ~= slot1 then
slot2 = slot2 + 1
end
end
return slot2
end
slot0.ExistSameKindShip = function (slot0, slot1)
for slot6, slot7 in pairs(slot2) do
if slot7.ship:isSameKind(slot1) then
return true
end
end
return false
end
slot0.IsLegal = function (slot0)
slot2 = 0
slot3 = 0
slot4 = 0
slot5 = 0
slot6 = 0
slot7 = 0
slot8 = getProxy(PlayerProxy):getRawData().id
for slot12, slot13 in ipairs(slot1) do
if slot13 and slot13.ship:getTeamType() == TeamType.Main then
slot2 = slot2 + 1
if slot13.member.id == slot8 then
slot5 = slot5 + 1
end
elseif slot13 and slot13.ship:getTeamType() == TeamType.Vanguard then
slot3 = slot3 + 1
if slot13.member.id == slot8 then
slot6 = slot6 + 1
end
elseif slot13 and slot13.ship:getTeamType() == TeamType.Submarine then
slot4 = slot4 + 1
if slot13.member.id == slot8 then
slot7 = slot7 + 1
end
end
if pg.ShipFlagMgr.GetInstance():GetShipFlag(GuildAssaultFleet.GetRealId(slot13.ship.id), "inEvent") then
return false, i18n("guild_boss_formation_exist_event_ship", slot13.ship:getConfig("name"))
end
end
if slot2 > 3 or slot3 > 3 or slot4 > 3 then
return false, i18n("guild_boss_fleet_cnt_invaild")
end
slot10 = nil
slot10 = (slot2 <= 0 or slot3 <= 0 or (slot6 > 0 and slot5 > 0) or i18n("guild_boss_formation_not_exist_self_ship")) and i18n("guild_fleet_is_legal")
if slot0:IsMainFleet() then
return slot2 > 0 and slot3 > 0 and slot9, slot10
else
return true
end
end
slot0.ResortShips = function (slot0, slot1)
function slot2(slot0)
slot1 = GuildAssaultFleet.GetVirtualId(slot0.uid, slot0.id)
for slot5, slot6 in ipairs(slot0) do
if slot1 == slot6.shipId then
return slot5
end
end
return 0
end
table.sort(slot0.userShips, function (slot0, slot1)
return slot0(slot0) < slot0(slot1)
end)
end
slot0.UpdateCommander = function (slot0, slot1)
slot0.commanders = slot1
slot0.skills = {}
slot0:updateCommanderSkills()
end
slot0.ClearCommanders = function (slot0)
for slot4, slot5 in pairs(slot0.commanders) do
slot0:RemoveCommander(slot4)
end
end
slot0.getCommanders = function (slot0)
return slot0.commanders
end
slot0.AddCommander = function (slot0, slot1, slot2)
slot0.commanders[slot1] = slot2
slot0.skills = {}
slot0:updateCommanderSkills()
end
slot0.RemoveCommander = function (slot0, slot1)
slot0.commanders[slot1] = nil
slot0.skills = {}
slot0:updateCommanderSkills()
end
slot0.GetCommanderPos = function (slot0, slot1)
for slot5, slot6 in pairs(slot0.commanders) do
if slot6.id == slot1 then
return slot5
end
end
return false
end
slot0.updateCommanderSkills = function (slot0)
slot1 = #slot0.skills
while slot1 > 0 do
if not slot0:findCommanderBySkillId(slot0.skills[slot1].id) and slot2:GetSystem() == FleetSkill.SystemCommanderNeko then
table.remove(slot0.skills, slot1)
end
slot1 = slot1 - 1
end
for slot6, slot7 in pairs(slot2) do
for slot11, slot12 in ipairs(slot7:getSkills()) do
for slot16, slot17 in ipairs(slot12:getTacticSkill()) do
table.insert(slot0.skills, FleetSkill.New(FleetSkill.SystemCommanderNeko, slot17))
end
end
end
end
slot0.findSkills = function (slot0, slot1)
return _.filter(slot0:getSkills(), function (slot0)
return slot0:GetType() == slot0
end)
end
slot0.findCommanderBySkillId = function (slot0, slot1)
for slot6, slot7 in pairs(slot2) do
if _.any(slot7:getSkills(), function (slot0)
return _.any(slot0:getTacticSkill(), function (slot0)
return slot0 == slot0
end)
end) then
return slot7
end
end
end
slot0.getSkills = function (slot0)
return slot0.skills or {}
end
slot0.getFleetType = function (slot0)
if id == slot0.MAIN_FLEET_ID then
return FleetType.Normal
elseif id == slot0.SUB_FLEET_ID then
return FleetType.Submarine
end
end
slot0.BuildBattleBuffList = function (slot0)
slot1 = {}
slot2, slot3 = FleetSkill.GuildBossTriggerSkill(slot0, FleetSkill.TypeBattleBuff)
if slot2 and #slot2 > 0 then
slot4 = {}
for slot8, slot9 in ipairs(slot2) do
slot4[slot11] = slot4[slot0:findCommanderBySkillId(slot3[slot8].id)] or {}
table.insert(slot4[slot11], slot9)
end
for slot8, slot9 in pairs(slot4) do
table.insert(slot1, {
slot8,
slot9
})
end
end
for slot8, slot9 in pairs(slot4) do
for slot14, slot15 in ipairs(slot10) do
if #slot15:getBuffsAddition() > 0 then
slot17 = nil
for slot21, slot22 in ipairs(slot1) do
if slot22[1] == slot9 then
slot17 = slot22[2]
break
end
end
if not slot17 then
table.insert(slot1, {
slot9,
{}
})
end
for slot21, slot22 in ipairs(slot16) do
table.insert(slot17, slot22)
end
end
end
end
return slot1
end
slot0.ExistCommander = function (slot0, slot1)
for slot6, slot7 in pairs(slot2) do
if slot7.id == slot1 then
return true
end
end
return false
end
slot0.ExistInvaildCommanders = function (slot0)
if #slot0.invaildCommanders > 0 then
return true
end
slot2 = getProxy(CommanderProxy)
for slot6, slot7 in pairs(slot1) do
if not slot2:getCommanderById(slot7.id) then
return true
end
end
return false
end
slot0.RemoveInvaildCommanders = function (slot0)
slot2 = getProxy(CommanderProxy)
for slot6, slot7 in pairs(slot1) do
if not slot2:getCommanderById(slot7.id) then
slot0:RemoveCommander(slot6)
end
end
slot0.invaildCommanders = {}
end
slot0.getCommandersAddition = function (slot0)
slot1 = {}
for slot5, slot6 in pairs(CommanderConst.PROPERTIES) do
slot7 = 0
for slot11, slot12 in pairs(slot0:getCommanders()) do
slot7 = slot7 + slot12:getAbilitysAddition()[slot6]
end
if slot7 > 0 then
table.insert(slot1, {
attrName = slot6,
value = slot7
})
end
end
return slot1
end
slot0.getCommandersTalentDesc = function (slot0)
slot1 = {}
for slot5, slot6 in pairs(slot0:getCommanders()) do
for slot11, slot12 in pairs(slot7) do
if slot1[slot11] then
slot1[slot11].value = slot1[slot11].value + slot12.value
else
slot1[slot11] = {
name = slot11,
value = slot12.value,
type = slot12.type
}
end
end
end
return slot1
end
slot0.ExistAnyCommander = function (slot0)
return table.getCount(slot0:getCommanders()) ~= 0
end
return slot0
|
require'lualine'.setup()
|
onWin = function(W)
W:setMap("res/map/meadows/meadows.tmx", 1060, 1025)
W:addConditionProgress("boss", "BossZeff")
W:unlockAchievement("ACH_KILL_ZEFF")
if (W:isQuestState("zeffs_curse", "started")) then
W:changeQuestState("zeffs_curse", "failed")
end
if (W:isQuestState("hungry_wolf", "started")) then
W:changeQuestState("hungry_wolf", "failed")
end
end
onLose = function(W)
W:setMap("res/map/meadows/meadows.tmx", 1060, 1025)
end
|
object_tangible_loot_creature_loot_collections_fried_icecream_components_naboo_phraig = object_tangible_loot_creature_loot_collections_fried_icecream_components_naboo_shared_phraig:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_fried_icecream_components_naboo_phraig, "object/tangible/loot/creature/loot/collections/fried/icecream/components/naboo/phraig.iff")
|
local ffi = require 'ffi'
local Scalar = require 'libsclr'
local qconsts = require "Q/UTILS/lua/qconsts"
local basetypes = { "I1", "I2", "I4", "I8", "F4", "F8" }
local is_basetype = {}
for _, basetype in ipairs(basetypes) do
is_basetype[basetype] = true
end
local inttypes = { "I1", "I2", "I4", "I8" }
local is_inttype = {}
for _, inttype in ipairs(inttypes) do
is_inttype[inttype] = true
end
return function (
f1,
s1,
optargs
)
local subs = {};
assert(type(f1) == "lVector"); assert(not f1:has_nulls())
assert(type(s1) == "Scalar")
local s1_qtype = s1:qtype()
local f1_qtype = f1:qtype()
assert(is_inttype[f1_qtype]);
local fn = "vsrem" .. "_" .. f1_qtype
if ( s1_qtype ) then fn = fn .. "_" .. s1_qtype end
subs.fn = fn
subs.fn_ispc = fn .. "_ispc"
subs.f1_qtype = f1_qtype
subs.f1_ctype = assert(qconsts.qtypes[f1_qtype].ctype)
subs.cst_f1_as = subs.f1_ctype .. " *"
local f2_qtype
if ( optargs ) then
assert(type(optargs) == "table")
if ( optargs.f2_qtype ) then
f2_qtype = optargs.f2_qtype
assert(is_basetype[f2_qtype]) -- not strong enough
end
end
if ( not f2_qtype ) then
f2_qtype = f1_qtype
end
-- TODO P2 chk_f2_qtype
local f2_ctype = qconsts.qtypes[f2_qtype].ctype
subs.f2_qtype = f2_qtype
subs.f2_ctype = f2_ctype
subs.cst_f2_as = subs.f2_ctype .. " *"
subs.f2_width = qconsts.qtypes[f2_qtype].width
if ( s1_qtype ) then
subs.cargs = s1:to_data()
subs.s1_ctype = qconsts.qtypes[s1_qtype].ctype
subs.cst_cargs = ffi.cast(subs.s1_ctype .. " *", subs.cargs)
else
subs.cst_cargs = ffi.NULL
end
subs.s1_ctype = qconsts.qtypes[s1_qtype].ctype
subs.code = "c = a b; "
subs.tmpl = "OPERATORS/F1S1OPF2/lua/f1s1opf2_sclr.tmpl"
subs.srcdir = "OPERATORS/F1S1OPF2/gen_src/"
subs.incdir = "OPERATORS/F1S1OPF2/gen_inc/"
subs.incs = { "OPERATORS/F1S1OPF2/gen_inc/", "UTILS/inc/" }
subs.libs = { "-lgomp", "-lm" }
-- for ISPC
subs.code_ispc = "c = a b; "
subs.f1_ctype_ispc = qconsts.qtypes[f1_qtype].ispctype
subs.s1_ctype_ispc = qconsts.qtypes[s1_qtype].ispctype
subs.f2_ctype_ispc = qconsts.qtypes[f2_qtype].ispctype
subs.tmpl_ispc = "OPERATORS/F1S1OPF2/lua/f1s1opf2_ispc.tmpl"
return subs
end
|
slot0 = class("ShipDialog")
slot1 = 0.3
slot2 = 2
slot0.Ctor = function (slot0, slot1, slot2)
slot0.dialog = slot1
slot0.label = slot0.dialog.gameObject:GetComponentInChildren(typeof(Text))
slot0.content = slot2
slot0.started = false
end
slot0.loop = function (slot0, slot1, slot2, slot3)
slot0.timer = Timer.New(function ()
slot0:display()
end, slot2 + slot3 * math.random(), slot1)
end
slot0.display = function (slot0)
if slot0.chatOn then
return
end
slot0.chatOn = true
rtf(slot0.dialog).localScale = Vector3.New(0, 0, 1)
slot0.label.text = slot0.content
slot0.label.alignment = (CHAT_POP_STR_LEN < #slot0.content and TextAnchor.MiddleLeft) or TextAnchor.MiddleCenter
LeanTween.scale(rtf(slot0.dialog), Vector3.New(1, 1, 1), slot0):setEase(LeanTweenType.easeOutBack)
LeanTween.scale(rtf(slot0.dialog), Vector3.New(0, 0, 1), slot0):setOnComplete(System.Action(function ()
slot0.chatOn = false
end)).setDelay(slot1, slot0 + LeanTween.scale(rtf(slot0.dialog), Vector3.New(0, 0, 1), slot0).setOnComplete(System.Action(function ()
slot0.chatOn = false
end)).setDelay):setEase(LeanTweenType.easeInBack)
end
slot0.play = function (slot0)
if not slot0.started then
slot0.started = true
slot0.timer:Start()
else
slot0.timer:Resume()
end
end
slot0.pause = function (slot0)
if slot0.started then
slot0.timer:Pause()
end
end
slot0.stop = function (slot0)
slot0.timer:Stop()
slot0.started = false
end
return slot0
|
---------------------------------------------------------------------------------------------------
---replay_menu_page.lua
---author: Karl
---date: 2021.5.11
---desc: implements replay player and replay saver
---------------------------------------------------------------------------------------------------
local MenuPage = require("BHElib.ui.menu.menu_page")
---@class ReplayMenuPage:MenuPage
local M = LuaClass("menu.ReplayMenuPage", MenuPage)
local MultiPageMenuSelector = require("BHElib.ui.selectors.multi_page_menu_selector")
local ShakeEffListingSelector = require("BHElib.ui.selectors.shake_eff_listing_selector")
local MenuConst = require("BHElib.ui.menu.menu_global")
local Coordinates = require("BHElib.unclassified.coordinates_and_screen")
local FS = require("file_system.file_system")
---------------------------------------------------------------------------------------------------
---cache variables and functions
local Vec2 = math.vec2
local Vec4 = math.vec4
local Selectable = ShakeEffListingSelector.Selectable
---------------------------------------------------------------------------------------------------
---name formatting parameters
local STR_REPLAY_PREFIX = "Default_"
local STR_REPLAY_SUFFIX = ".Replay" -- credit to Trackmania replay suffix, hard to come up with a suffix better than ".rpy" myself
---------------------------------------------------------------------------------------------------
local OnSaveReplay -- forward declaration
local function OnLoadReplay()
PlaySound("se:select00", 0.1, 0, true)
end
local function CreateSaveSelectable(display_text, full_path, file_name, i)
local replay_info = {
i = i,
file_name = file_name,
full_path = full_path,
}
local selectable = Selectable(display_text, {
{MenuConst.CHOICE_SPECIFY, "replay_path_for_write", full_path},
{MenuConst.CHOICE_SPECIFY, "replay_info", replay_info},
{MenuConst.CHOICE_EXECUTE, OnSaveReplay},
{MenuConst.CHOICE_CASCADE}, -- let title page do the saving job
})
return selectable
end
local function CreateLoadSelectable(display_text, full_path)
local selectable = Selectable(display_text, {
{MenuConst.CHOICE_SPECIFY, "replay_path_for_read", full_path},
{MenuConst.CHOICE_EXECUTE, OnLoadReplay},
{MenuConst.CHOICE_EXIT} -- let stage scene do the loading job
})
return selectable
end
function OnSaveReplay(menu_manager, menu_page)
local info = menu_manager:queryChoice("replay_info")
local selector = menu_page:getSelector()
selector:setSelectableAtIndex(info.i, CreateSaveSelectable(info.file_name, info.full_path, info.file_name, info.i))
PlaySound("se:extend", 0.1, 0, true)
end
---scan through all replay files in the directory, create an array of options with index specified by the replay file;
---for empty slots, those elements in the array with corresponding index will be filled with empty selectable
---@param max_index number maximum number of items; must be multiple of mod_num
---@param mod_num number number of items must be divisible by mod_num
---@return table, number an array of all selectables and the size of the array
local function CreateAllSelectable(is_saving, replay_file_directory, max_index, mod_num, empty_room_num)
local size = empty_room_num
local ret = {}
local files = FS.getBriefOfFilesInDirectory(replay_file_directory)
for i = 1, #files do
local file = files[i]
local file_name = file.name -- contains the suffix part
if file.isDirectory == false and string.sub(file_name, -#STR_REPLAY_SUFFIX, -1)== STR_REPLAY_SUFFIX
and string.sub(file_name, 1, #STR_REPLAY_PREFIX) == STR_REPLAY_PREFIX then
local number_str = string.sub(file_name, #STR_REPLAY_PREFIX + 1, -#STR_REPLAY_SUFFIX - 1)
local number = tonumber(number_str)
if number and number <= max_index then
local selectable
local full_path = replay_file_directory.."/"..file_name
if is_saving then
selectable = CreateSaveSelectable(file_name, full_path, file_name, number)
else
selectable = CreateLoadSelectable(file_name, full_path)
end
ret[number] = selectable
size = max(number, size) + empty_room_num
end
end
end
size = math.ceil(size / mod_num) * mod_num
size = min(size, max_index)
-- fill out the empty slots
for i = 1, size do
if ret[i] == nil then
if is_saving then
local file_name = STR_REPLAY_PREFIX..tostring(i)..STR_REPLAY_SUFFIX
ret[i] = CreateSaveSelectable(
"--- empty ---",
replay_file_directory.."/"..file_name,
file_name,
i)
else
ret[i] = Selectable("--- empty ---", nil)
end
end
end
return ret, size
end
local function ReplayMenuProcessInput(self)
---@type InputManager
local input = self.selection_input
if input:isAnyKeyJustChanged("escape", false, true) then
self:exit()
else
MultiPageMenuSelector.processInput(self)
end
end
---@param init_focused_index number initial position index of focused selectable
function M.__create(
init_focused_index,
is_saving,
replay_file_directory,
num_selectable_in_page,
num_pages
)
-- create simple menu selector
local width = Coordinates.getResolution()
local ui_scale = Coordinates.getUIScale()
width = width / ui_scale -- convert to "ui" coordinates
local center_x, center_y = Coordinates.getScreenCenterInUI()
local title = "Replay"
if is_saving then
title = "Save Replay"
end
local max_replay_num = num_pages * num_selectable_in_page
local selectable_array, size = CreateAllSelectable(is_saving, replay_file_directory, max_replay_num, num_selectable_in_page, 10)
local selector = MultiPageMenuSelector.shortInit(
init_focused_index,
1,
width * 0.7,
Vec2(center_x, center_y),
selectable_array,
title,
num_selectable_in_page,
size / num_selectable_in_page,
180,
0
)
selector.processInput = ReplayMenuProcessInput
local self = MenuPage.__create(selector)
self.replay_file_directory = replay_file_directory
self.is_saving = is_saving
return self
end
return M
|
function foo(x)
local bar = function(a, b, c)
return a + b + c
end
return bar(
x,
1,
2)
end
|
local es = class(LevelLoadingScreenGuiScript)
LevelLoadingScreenGuiScript = es
function es:init(gui, res, p, layer)
self._gui = gui
if arg.load_level_data.level_data.editor_load then
self._is_editor = true
else
es.super.init(self, gui, res, p, layer)
end
end
function es:update(...)
if self._is_editor then
self:do_editor_stuff()
else
es.super.update(self, ...)
end
end
function es:do_editor_stuff()
if alive(self._gui) and self._gui:workspaces()[1] then
local load = self._gui:workspaces()[1]:panel():child("Load")
if alive(load) then
for _, child in pairs(load:children()) do
local mchild = getmetatable(child)
if mchild == Text then
child:animate(function(o)
if alive(o) then
coroutine.yield()
o:set_text(tostring(o:name()))
end
end)
end
end
end
end
end
|
for i,v in ipairs({
{841,2338.1001,-705.90002,130.89999,1.99811,357.49847,0.08728},
{841,2339.8999,-706.09998,130.89999,4.98779,355.98477,0.34961},
{843,2338.69995,-707.70001,131.5,0,356.75,0},
{839,2334.8999,-706.20001,132.10001,0,0,0},
{833,2338.30005,-704.5,131.3,0,0,46},
{837,2338.8999,-698,131.60001,5.5,0,351.25},
{837,2344.6001,-700.5,131.60001,5.49866,0,319.24939},
{837,2332.8999,-699.20001,131.39999,2.24652,357.49811,28.84436},
{3461,2340.30005,-707.59998,130.3,0,0,0},
{3461,2340.19995,-708.20001,130.3,0,0,0},
{3461,2340.69995,-707.79999,130.3,0,0,0},
{3461,2339.80005,-707.70001,130.2,0,0,0},
{3461,2338.6001,-707.40002,130.2,0,0,0},
{3461,2338,-707.40002,130.2,0,0,0},
{3461,2337.5,-707.29999,130.2,0,0,0},
{3461,2337,-707.29999,130.2,0,0,0},
{3461,2336.5,-707.29999,130.2,0,0,0},
{3461,2335.8999,-707.09998,130.2,0,0,0},
{3461,2335.3999,-707.20001,130.2,0,0,0},
{3461,2338,-707.79999,130.2,0,0,0},
{3461,2338.09961,-707.7998,130.2,0,0,0},
{3461,2336.5,-707.40002,130.2,0,0,0},
{3461,2336.3999,-705.90002,129,0,0,0},
{3461,2335.8999,-705.90002,129,0,0,0},
{3461,2334.69995,-706.09998,129,0,0,0},
{3461,2334.6001,-704.09998,129,0,0,0},
{3461,2335,-706.09998,129,0,0,0},
{3461,2337,-706.5,129,0,0,0},
{3461,2336.8999,-705,129,0,0,0},
{3461,2334.3999,-704.90002,129,0,0,0},
{3461,2335.30005,-704.90002,129,0,0,0},
{3461,2337,-704,129,0,0,0},
{3461,2336.3999,-703.90002,129,0,0,0},
{3461,2338.80005,-705,129.5,0,0,0},
{3461,2339.1001,-705.09998,129.5,0,0,0},
{3461,2337.19995,-703.20001,129.2,0,0,0},
{3461,2338.1001,-704.20001,129.2,0,0,0},
{3461,2338.30005,-704.70001,129.5,0,0,0},
{3461,2339,-706.09998,129.5,0,0,0},
{3461,2337.5,-703.90002,129.2,0,0,0},
{3461,2341,-707.09998,129.2,346.25,0,0},
{3461,2340.3999,-706.90002,129.2,346.24512,0,0},
{1481,2346.09961,-704.09961,131.89999,0,0,229.99879},
{1481,2345.30005,-705,131.89999,0,0,229.99878},
{2100,2350.8999,-701.59998,131,0,0,274},
{2232,2350.69995,-700.5,131.60001,0,0,274},
{2232,2350.8999,-703.09998,131.60001,0,0,273.99902},
{960,2348.7998,-698.5,131.5,358.00049,1.99951,325.31616},
{1543,2348.69995,-697.90002,131.2,0,0,0},
{1543,2348.6001,-698,131.2,0,0,0},
{1543,2348.5,-698.09998,131.2,0,0,0},
{1543,2348.3999,-698.20001,131.2,0,0,0},
{1543,2348.80005,-698,131.2,0,0,0},
{1543,2348.8999,-698.09998,131.2,0,0,0},
{1543,2349,-698.20001,131.2,0,0,0},
{1543,2348.8999,-698.20001,131.2,0,0,0},
{1543,2348.80005,-698.09998,131.2,0,0,0},
{1543,2348.80005,-698.20001,131.2,0,0,0},
{1543,2348.69995,-698.09998,131.2,0,0,0},
{1543,2348.69995,-698.20001,131.2,0,0,0},
{1543,2348.6001,-698.20001,131.2,0,0,0},
{1543,2348.69995,-698.29999,131.2,0,0,0},
{1543,2348.80005,-698.40002,131.2,0,0,0},
{1543,2349,-698.29999,131.2,0,0,0},
{1543,2348.5,-698.40002,131.2,0,0,0},
{1543,2349.19995,-698.40002,131.2,0,0,0},
{1463,2329.8999,-704.79999,130.8,0,0,0},
{1463,2330,-706.09998,130.7,0,0,0},
-- {2806,2346,-704,132.10001,0,0,341.75},
{1255,2345.3999,-710.09998,131.60001,0,0,130},
{1255,2343.19995,-711.90002,131.5,0,0,119.99573},
{1255,2340.5,-713.09998,131.3,358,359.74985,105.98398},
{1643,2339.8999,-689.20001,132,4.75,0,0},
{1641,2336.5,-690.20001,132,4.48901,355.98767,46.31451},
{1640,2342.5,-690.09998,131.89999,4.5,0,0},
{2103,2338,-689.09998,132.10001,3.5,0,14.75},
{1598,2342.69995,-694.59998,131.8,0,0,0},
{2780,2338.6001,-706,124.9,0,0,0},
{3461,2353.80005,-698.59998,132.3,0,0,0},
{3461,2345.69995,-714.40002,131.8,0,0,0},
{3461,2327.69995,-710.40002,131.8,0,0,0},
{3461,2330.1001,-688.59998,133.3,0,0,0},
{960,2347.30005,-697.40002,131.7,358.00049,1.99951,325.31616},
{1484,2347.1001,-696.79999,131.60001,349.84457,32.57159,6.42654},
{1484,2347.19995,-696.90002,131.60001,349.84314,32.56897,6.42151},
{1484,2347.30005,-696.90002,131.60001,349.84314,32.56897,6.42151},
{1484,2347.3999,-697,131.60001,349.84314,32.56897,6.42151},
{1484,2347.6001,-697.09998,131.60001,349.84314,32.56897,6.42151},
{1484,2347.69995,-697.20001,131.60001,349.84314,32.56897,6.42151},
{1484,2347.80005,-697.29999,131.60001,349.84314,32.56897,6.42151},
{1484,2347.69995,-697.40002,131.60001,349.84314,32.56897,6.42151},
{1484,2347.6001,-697.29999,131.60001,349.84314,32.56897,6.42151},
{1484,2347.5,-697.20001,131.60001,349.84314,32.56897,6.42151},
{1484,2347.3999,-697.09998,131.60001,349.84314,32.56897,6.42151},
{1484,2347.19995,-697.09998,131.60001,349.84314,32.56897,6.42151},
{1484,2347.1001,-697,131.60001,349.84314,32.56897,6.42151},
{1484,2346.8999,-697.09998,131.60001,349.84314,32.56897,6.42151},
{1484,2346.89941,-697.09961,131.60001,349.84314,32.56897,6.42151},
{1544,2347.69995,-697.59998,131.39999,0,0,0},
{1544,2347.6001,-697.40002,131.39999,0,0,0},
{1544,2347.3999,-697.29999,131.39999,0,0,0},
{1544,2347.3999,-697.5,131.39999,0,0,0},
{1544,2347.3999,-697.70001,131.39999,0,0,0},
{1544,2347.6001,-697.79999,131.39999,0,0,0},
{1544,2347.3999,-698,131.39999,0,0,0},
{1544,2347.19995,-697.79999,131.39999,0,0,0},
{1544,2346.8999,-697.70001,131.39999,0,0,0},
{1544,2347.19995,-697.5,131.39999,0,0,0},
{1544,2347.19995,-697.29999,131.39999,0,0,0},
{1544,2347,-697.40002,131.39999,0,0,0},
{1543,2338.8999,-689,132,0,0,0},
}) do
local obj = createObject(v[1], v[2], v[3], v[4], v[5], v[6], v[7])
setObjectScale(obj, 1)
setElementDimension(obj, 0)
setElementInterior(obj, 0)
setElementDoubleSided(obj, true)
setElementFrozen(obj,true)
end
|
-- Lexer tokens
local tokens = {
"and", "break", "do", "else", "elseif", "end", "false";
"for", "function", "goto", "if", "in", "local", "nil", "not", "or";
"repeat", "return", "then", "true", "until", "while";
"concat", "dots", "eq", "ge", "le", "ne";
"label", "number", "name", "string";
"eof";
"plus", "minus", "mul", "div", "mod", "pow", "len";
"less", "greater", "assign", "lparen", "rparen", "lcurbrace", "rcurbrace", "lbrace", "rbrace";
"semicolon", "colon", "comma", "dot", "tilde";
}
local reserved = {}
-- 1 = and, 22 = while
for k = 1, 22 do
reserved[tokens[k]] = k
end
-- Convert tokens to numbers
for k = 1, #tokens do
tokens[tokens[k]] = k
end
-- Token names table, we use metatable to fallback to their literal name
local tokennames = setmetatable({
[tokens.concat] = "..",
[tokens.dots] = "...",
[tokens.eq] = "==",
[tokens.ge] = ">=",
[tokens.le] = "<=",
[tokens.ne] = "~=";
[tokens.label] = "::",
[tokens.number] = "<number>",
[tokens.name] = "<name>",
[tokens.string] = "<string>";
[tokens.eof] = "<eof>";
[tokens.plus] = "+",
[tokens.minus] = "-",
[tokens.mul] = "*",
[tokens.div] = "/",
[tokens.mod] = "%",
[tokens.pow] = "^",
[tokens.greater] = ">";
[tokens.less] = "<",
[tokens.lbrace] = "[",
[tokens.rbrace] = "]",
[tokens.lcurbrace] = "{",
[tokens.rcurbrace] = "}",
[tokens.lparen] = "(",
[tokens.rparen] = ")";
[tokens.assign] = "=",
[tokens.dot] = ".",
[tokens.comma] = ",",
[tokens.colon] = ":",
[tokens.semicolon] = ";",
[tokens.len] = "#";
[tokens.tilde] = "~";
}, {
__index = tokens
})
return {
tokens = tokens,
tokennames = tokennames,
reserved = reserved
}
|
--------------- 选房及私人房指令开始 -------------------------
CREATE_PRIVATE_ROOM_REQUEST = 0x114; --用户创建私人房,回复0x1007或者0x1005
ENTER_PRIVATE_ROOM_REQUEST = 0x115; --用户进入私人房,回复0x1007或者0x1005
ROOM_BROADCAST_ROOM_INFO = 0x212; --server向客户端发送房间信息
SEARCH_PRIVATE_ROOM_REQUEST = 0x10e; --用户搜索私人房 --回复0x208
PRIVATE_ROOM_LIST_REPONSE = 0x208; --用户获取私人房列表回复
--------------- 选房及私人房指令结束 -------------------------
|
PlazaMainRightCcsView = class("PlazaMainRightCcsView")
PlazaMainRightCcsView.onCreationComplete = function (slot0)
slot1 = {
[5] = {
cc.p(1282, 602),
cc.p(1282, 500),
cc.p(1282, 396),
cc.p(1282, 295),
cc.p(1282, 193)
},
[4] = {
cc.p(1282, 585),
cc.p(1282, 457),
cc.p(1282, 334),
cc.p(1282, 210)
},
[3] = {
cc.p(1282, 585),
cc.p(1282, 457),
cc.p(1282, 334),
cc.p(1282, 210)
},
[2] = {
cc.p(1282, 585),
cc.p(1282, 457),
cc.p(1282, 334),
cc.p(1282, 210)
}
}
slot0.btnPaiHangBang._spine = sp.SkeletonAnimation:create("gameres/animation/spine/zsbdt_phbeffect/zsbdt_phbeffect.json", "gameres/animation/spine/zsbdt_phbeffect/zsbdt_phbeffect.atlas")
slot0.btnPaiHangBang._spine:setAnimation(0, "animation", true)
slot0.btnPaiHangBang.spine:addChild(slot0.btnPaiHangBang._spine)
slot0._btns = {
slot0.btnKefu,
slot0.btnPaiHangBang,
slot0.btnYingHang,
slot0.btnActivity
}
if IS_SDK_OFFIIAL_VERIFY then
slot0._btns = {
slot0.btnPaiHangBang,
slot0.btnYingHang
}
end
if slot0.btnBackup then
if IS_IOS_IN_HOUSE then
table.insert(slot0._btns, slot0.btnBackup)
end
slot0.btnBackup:setVisible(IS_IOS_IN_HOUSE)
end
for slot5, slot6 in ipairs(slot0._btns) do
slot6:setPosition(slot1[#slot0._btns][slot5])
end
for slot5, slot6 in ipairs(slot0._btns) do
slot6._initX = slot6:getPositionX()
slot6._initScale = slot6:getScale()
DisplayUtil.setVisible(slot6, false)
end
if IS_IOS_VERIFY then
slot0._btnGroups4IosVerify = ComponentsGroup.new(slot0._btns)
slot2 = nil
if IS_IOS_VERIFY_ALL_NO_BANK then
slot2 = {}
slot0.bg:setScaleY(0.3)
else
slot2 = {
slot0.btnYingHang
}
slot0.bg:setScaleY(0.44)
end
slot0._btnGroups4IosVerify:showThese(slot2)
slot0._btns = slot2
end
slot0.btnKefu.datingTishitubiao:setVisible(false)
slot0.model.hasNewEMailCountChangedSignal:add(slot0.onHasNewEMailCount, slot0)
uiMgr:adjustSlimWidth(slot0, UIConfig.ALIGN_RIGHT, -77)
ClassUtil.extends(slot0, BasePlazaTweenComponent, true, 300, nil, nil, nil, 0)
slot0._spineKFMsg = nil
slot0:setKfMsgIconShowing(Hero:getNeed2ShowKfMsg())
end
PlazaMainRightCcsView.setKfMsgIconShowing = function (slot0, slot1)
if slot1 then
if not slot0._spineKFMsg then
slot4 = sp.SkeletonAnimation:create(slot2, slot3)
slot4:setAnimation(0, "animation", true)
slot4:setPosition(8.66, 48.1)
slot0.btnKefu:addChild(slot4)
slot0._spineKFMsg = slot4
end
elseif slot0._spineKFMsg then
slot0._spineKFMsg:removeFromParent()
slot0._spineKFMsg = nil
end
end
PlazaMainRightCcsView.doShow = function (slot0, slot1, slot2)
if slot1 <= 0 then
slot0:setPosition(slot0._toPos)
slot0:onShowComplete()
for slot6, slot7 in ipairs(slot0._btns) do
TweenLite.killTweensOf(slot7)
DisplayUtil.setVisible(slot7, true)
slot7:setScale(slot7._initScale)
end
slot0:setOpacity(255)
else
slot3 = CustomEase.byName("myShakeEase1")
for slot7, slot8 in ipairs(slot0._btns) do
TweenLite.to(slot8, 0.2, {
autoAlpha = 1,
scale = slot8._initScale,
x = slot8._initX,
delay = slot7 * 0.05 + 0.2
})
end
TweenLite.to(slot0, 1, {
alpha = 1,
x = slot0._toPos.x,
y = slot0._toPos.y,
onComplete = handler(slot0, slot0.onShowComplete),
delay = slot2,
ease = slot3
})
end
if NewbieUI then
NewbieUI.plazaLeftBtnRank = slot0.btnPaiHangBang
end
if IS_SDK_OFFIIAL_VERIFY then
slot0.btnActivity:setVisible(false)
slot0.btnKefu:setVisible(false)
end
end
PlazaMainRightCcsView.onShowComplete = function (slot0)
BasePlazaTweenComponent.onShowComplete(slot0)
eventMgr:dispatch(GameEvent.PLAZA_MAIN_RIGHT_SHOW_COMPLETE)
end
PlazaMainRightCcsView.doHide = function (slot0, slot1, slot2)
eventMgr:dispatch(GameEvent.PLAZA_MAIN_LEFT_HIDE_BEGIN)
if slot1 <= 0 then
slot0:setPosition(slot0._fromPos)
for slot6, slot7 in ipairs(slot0._btns) do
TweenLite.killTweensOf(slot7)
DisplayUtil.setVisible(slot7, false)
slot7:setScale(slot7._initScale * 1.3)
end
slot0:onHideComplete()
slot0:setOpacity(0)
else
slot3 = #slot0._btns
for slot7, slot8 in ipairs(slot0._btns) do
TweenLite.to(slot8, 0.1, {
autoAlpha = 0,
scale = slot8._initScale * 1.3,
delay = (slot2 or 0) + (slot3 - slot7) * 0.1
})
end
TweenLite.to(slot0, slot1, {
alpha = 0,
x = slot0._fromPos.x,
y = slot0._fromPos.y,
onComplete = handler(slot0, slot0.onHideComplete),
delay = slot2
})
end
if NewbieUI then
NewbieUI.plazaLeftBtnRank = nil
end
end
PlazaMainRightCcsView.onHasNewEMailCount = function (slot0)
slot0.btnKefu.datingTishitubiao:setVisible(slot0.model:getHasNewEMailCount() > 0)
slot0.btnKefu.datingTishitubiao.txtTS:setString(slot1)
end
PlazaMainRightCcsView.onBtnClick = function (slot0, slot1, slot2)
if slot1 == slot0.btnYingHang then
slot0.controller:openBankModule()
trackMgr:recordTracks(TRACK_HALL_YH)
elseif slot1 == slot0.btnPaiHangBang then
slot0.model:setIsShowingRank(true)
trackMgr:recordTracks(TRACK_HALL_PHB)
elseif slot1 == slot0.btnKefu then
slot0.model:setIsShowingCustomService(true)
slot0:setKfMsgIconShowing(false)
Hero:setNeed2ShowKfMsg(false)
trackMgr:recordTracks(TRACK_HALL_KF)
elseif slot1 == slot0.btnBackup then
slot0.controller:gotoBackup()
elseif slot1 == slot0.btnActivity then
requireModule("ActivityModule")
ProxyActivity:show()
else
tweenMsgMgr:showWhiteMsg("该功能尚未开放!")
end
end
return
|
-------
-- @module bad
local bad = {}
--------
-- inference fails! Have to explicitly
-- declare the function and its arguments
bad['entry'] = function(one)
end
return bad
|
require('stdlib/string')
local Color = require('util/Colors')
local tools = {}
tools.MAX_INT32 = 2147483647
function tools.sortByValue(t)
local keys = {}
for key, _ in pairs(t) do table.insert(keys, key) end
table.sort(keys, function(keyLhs, keyRhs) return t[keyLhs] < t[keyRhs] end)
local r = {}
for _, key in ipairs(keys) do r[key] = t[key] end
return r
end
function tools.FlyingTime(this_tick)
if not global.oarc_timers then global.oarc_timers = {} end
local time = tools.formatTimeMinsSecs(this_tick)
for __, player in pairs(global.oarc_timers) do
FlyingText(time, player.position, {r = 1, g = 0, b = 0}, player.surface)
end
end
function tools.error(player, error_message, play_sound)
error_message = error_message or ''
player.print({'error.msg', error_message})
if play_sound ~= false then
play_sound = play_sound or 'utility/wire_pickup'
if player then player.play_sound {path = play_sound} end
end
end
function tools.success(player, success_message, play_sound)
success_message = success_message or ''
player.print({'success.msg', success_message})
if play_sound ~= false then
play_sound = play_sound or 'utility/confirm'
if player then player.play_sound {path = play_sound} end
end
end
function tools.notify(player, notify_message, play_sound)
notify_message = notify_message or ''
player.print({'notify.msg', notify_message})
if play_sound ~= false then
play_sound = play_sound or 'utility/wire_connect_pole'
if player then player.play_sound {path = play_sound} end
end
end
function tools.formatTimeMinsSecs(ticks)
local seconds = ticks / 60
local minutes = math.floor((seconds) / 60)
local seconds = math.floor(seconds - 60 * minutes)
return string.format("%dm:%02ds", minutes, seconds)
end
-- Useful for displaying game time in mins:secs format
function tools.formatTimeHoursMins(ticks)
local seconds = ticks / 60
local minutes = math.floor((seconds) / 60)
local hours = math.floor((minutes) / 60)
local minutes = math.floor(minutes - 60 * hours)
return string.format("%dh:%02dm", hours, minutes)
end
function tools.get_player(o)
local o_type, p = type(o)
if o_type == 'table' then
p = o
elseif o_type == 'string' or o_type == 'number' then
p = game.players[o]
end
if p and p.valid and p.is_player() then return p end
end
function tools.getMarketBonuses(player)
local player = tools.get_player(player)
if player and global.ocore.markets.player_markets[player.name].stats then
return global.ocore.markets.player_markets[player.name].stats
end
end
function tools.formatMarketBonuses(player)
local player = tools.get_player(player)
if player then
if global.ocore.markets and global.ocore.markets.player_markets and global.ocore.markets.player_markets[player.name] and global.ocore.markets.player_markets[player.name].stats then
local stats = global.ocore.markets.player_markets[player.name].stats
local str = "[color=blue]Bonuses for [/color][color=orange]"..player.name.."[/color][color=blue]:[/color]\n"
for type, item in pairs(stats) do
str = str.."[color=purple]["..type.."][/color]\n"
for name, data in pairs(item) do
if type == "sell-speed" then
str = str.."[color=cyan]-- ["..name.."]:[/color] \t[color=orange]LVL: [/color][color=green]"..data.lvl.."[/color] \t[color=orange]SECONDS: [/color][color=green]"..data.formatted.."%[/color]\n"
else
str = str.."[color=cyan]-- ["..name.."]:[/color] \t[color=orange]LVL: [/color][color=green]"..data.lvl.."[/color] \t[color=orange]BONUS: [/color][color=green]"..data.formatted.."%[/color]\n"
end
end
end
return str
else
return
end
end
end
function matChest()
local player = game.player
local target = player.selected
if target and target.valid then
if target.type == "container" or target.type == "logistic-container" then
material_chest = target
end
end
end
function tools.stockUp()
if material_chest and material_chest.valid then
local chest_inv = material_chest.get_inventory(defines.inventory.chest)
chest_inv.clear()
local list = game.surfaces[GAME_SURFACE_NAME].find_entities_filtered {type = "entity-ghost", force = material_chest.force}
for _, ghost in pairs(list) do
if ghost.ghost_name == "curved-rail" or ghost.ghost_name ==
"straight-rail" then
if chest_inv.can_insert("rail") then
chest_inv.insert {name = "rail", count = 1}
end
else
if chest_inv.can_insert(ghost.ghost_name) then
chest_inv.insert {name = ghost.ghost_name, count = 1}
end
end
end
end
end
function tools.get_player_base_bonuses(player)
local player = player
local t = {
["run_bonus"] = player.character_running_speed_modifier,
["handcraft_bonus"] = player.character_crafting_speed_modifier,
["mining_bonus"] = player.character_mining_speed_modifier,
["reach_bonus"] = player.character_reach_distance_bonus,
["resource_reach_bonus"] = player.character_resource_reach_distance_bonus,
["build_bonus"] = player.character_build_distance_bonus,
["item_drop_bonus"] = player.character_item_drop_distance_bonus,
["loot_pickup_bonus"] = player.character_loot_pickup_distance_bonus,
["inventory_bonus"] = player.character_inventory_slots_bonus,
["trash_bonus"] = player.character_trash_slot_count_bonus,
["bot_speed_bonus"] = player.force.worker_robots_speed_modifier,
["bot_storage_bonus"] = player.force.worker_robots_storage_bonus,
["bot_battery_bonus"] = player.force.worker_robots_battery_modifier
}
return t
end
function tools.floating_text(surface, position, text, color)
color = color or Color.white
return surface.create_entity {
name = 'tutorial-flying-text',
color = color,
text = text,
position = position
}
end
function tools.floating_text_on_player(player, text, color)
tools.floating_text_on_player_offset(player, text, color, 0, -1.5)
end
function tools.floating_text_on_player_offset(player, text, color, x_offset,
y_offset)
player = tools.get_player(player)
if not player or not player.valid then return end
local position = player.position
return tools.floating_text(player.surface, {
x = position.x + x_offset,
y = position.y + y_offset
}, text, color)
end
function tools.protect_entity(entity)
entity.minable = false
entity.destructible = false
end
function tools.link_in_spawn(pos)
local link_in = game.surfaces[GAME_SURFACE_NAME].create_entity {
name = "linked-belt",
position = pos,
force = game.forces["neutral"]
}
link_in.linked_belt_type = "input"
return link_in
end
function tools.link_out_spawn(pos)
local link_out = game.surfaces[GAME_SURFACE_NAME].create_entity {
name = "linked-belt",
position = pos,
force = game.forces["neutral"]
}
link_out.linked_belt_type = "output"
return link_out
end
function tools.link_belts(player, inp, outp)
local player = player
if inp.valid and outp.valid then
inp.connect_linked_belts(outp)
if inp.linked_belt_neighbour == outp then
tools.success(player, "Success")
tools.protect_entity(inp)
tools.protect_entity(outp)
inp = nil
outp = nil
elseif inp.linked_belt_neighbour ~= outp then
tools.error(player, "Couldn't make link")
return
end
else
tools.error(player, "Invalid")
end
end
function tools.make(player, sharedobject, flow)
local player = player
local shared_objects = {
["chest"] = true,
["belt"] = true,
["belts"] = true,
["power"] = true,
["energy"] = true,
["accumulator"] = true
}
local flows = {["in"] = true, ["out"] = true}
if not player.admin then
tools.error(player, "You're not admin!")
return
end
if sharedobject == "link" then
local link_in = global.oarc_players[player.name].link_in or nil
local link_out = global.oarc_players[player.name].link_out or nil
if link_in and link_out then
if link_in == link_out then
tools.notify(
"Last logged input belt is the same as last logged output belt. Specify a new belt with /make mode <in/out>")
return false
else
tools.link_belts(player, link_in, link_out)
end
else
tools.error(player, "Missing a link")
return false
end
elseif sharedobject == "mode" then
local sel = player.selected
if not sel then
tools.error(player, "Place your cursor over the target linked belt.")
return false
end
if sel.name == "linked-belt" then
if flow == "in" then
global.oarc_players[player.name].link_in = sel
local link_in = global.oarc_players[player.name].link_in
if link_in.linked_belt_type == "input" then
tools.notify(
"MODE already set to INPUT. '/make mode output' to link an OUTPUT belt. '/make link' to connect.")
return link_in
else
link_in.linked_belt_type = "input"
tools.notify(
"MODE set to INPUT. '/make mode output' to link an OUTPUT belt. '/make link' to connect.")
return link_in
end
elseif flow == "out" then
global.oarc_players[player.name].link_out = sel
local link_out = global.oarc_players[player.name].link_out
if link_out.linked_belt_type == "output" then
tools.notify(
"MODE already set to OUTPUT. '/make mode input' to link an INPUT belt. '/make link' to connect.")
return link_out
else
link_out.linked_belt_type = "output"
tools.notify(
"MODE set to OUTPUT. '/make mode input' to link an INPUT belt. '/make link' to connect.")
return link_out
end
end
else
tools.error(player, "Not a linked belt type.")
return false
end
elseif sharedobject == "water" then
local pos = GetWoodenChestFromCursor(player)
if pos and (getDistance(pos, player.position) > 2) then
player.surface.set_tiles({[1] = {name = "water", position = pos}})
return true
else
tools.error(player,
"Failed to place waterfill. Don't stand so close!")
return false
end
elseif sharedobject == "combinator" or sharedobject == "combinators" then
local pos = GetWoodenChestFromCursor(player)
if pos and (player.surface.can_place_entity {
name = "constant-combinator",
position = {pos.x, pos.y - 1}
}) and (player.surface.can_place_entity {
name = "constant-combinator",
position = {pos.x, pos.y + 1}
}) then
SharedChestsSpawnCombinators(player, {x = pos.x, y = pos.y - 1},
{x = pos.x, y = pos.y + 1})
return true
end
elseif shared_objects[sharedobject] then
if flows[flow] then
local pos = GetWoodenChestFromCursor(player)
if pos then
if sharedobject == "chest" then
if flow == "in" then
SharedChestsSpawnInput(player, pos)
return true
elseif flow == "out" then
SharedChestsSpawnOutput(player, pos)
return true
end
elseif sharedobject == "belt" or sharedobject == "belts" then
if flow == "in" then
local link_in = tools.link_in_spawn(pos)
global.oarc_players[player.name].link_in = link_in
return link_in
elseif flow == "out" then
local link_out = tools.link_out_spawn(pos)
global.oarc_players[player.name].link_out = link_out
return link_out
end
elseif sharedobject == "power" or sharedobject == "energy" or
sharedobject == "accumulator" then
if flow == "in" then
if (player.surface.can_place_entity {
name = "electric-energy-interface",
position = pos
}) and (player.surface.can_place_entity {
name = "constant-combinator",
position = {x = pos.x + 1, y = pos.y}
}) then
SharedEnergySpawnInput(player, pos)
return true
end
elseif flow == "out" then
if (player.surface.can_place_entity {
name = "electric-energy-interface",
position = pos
}) and (player.surface.can_place_entity {
name = "constant-combinator",
position = {x = pos.x + 1, y = pos.y}
}) then
SharedEnergySpawnOutput(player, pos)
return true
end
end
end
else
return false
end
else
tools.error(player, "Looking for 'in/out'")
return
end
elseif sharedobject == "help" or sharedobject == "h" then
tools.notify(player, "/make <entity/command> <'in' or 'out'>")
tools.notify(player,
"entities: 'belt', 'chest', 'power', 'combinators', 'water'")
tools.notify(player, "commands: 'link', 'mode', 'help'")
else
tools.error(player, "Invalid magic entity.. try /make help")
return
end
end
function tools.run_tests(player, cursor_stack)
local p = player.print
local log = print
local tests = {
parent = {
"[cursor stack]", "[cursor stack]", "[cursor stack]",
"[cursor stack] ", "[player]", "[cursor stack]", "[cursor stack]",
"[cursor stack]", "[cursor stack]", "[cursor stack]",
"[cursor stack]"
},
name = {
"oName:", "valid:", "is_blueprint:", "is_blueprint_book:",
"is_cursor_blueprint:", "[cursor stack] is_module:", "is_tool:",
"[cursor stack] is_mining_tool:", "is_armor:",
"[cursor stack] is_repair_tool:", "is_item_with_label:",
"is_item_with_inventory:", "is_item_with_entity_data:",
"is_upgrade_item:"
},
funcs = {
cursor_stack.object_name, cursor_stack.valid,
cursor_stack.is_blueprint, cursor_stack.is_blueprint_book,
player.is_cursor_blueprint(), cursor_stack.is_module,
cursor_stack.is_tool, cursor_stack.is_mining_tool,
cursor_stack.is_armor, cursor_stack.is_repair_tool,
cursor_stack.is_item_with_label,
cursor_stack.is_item_with_inventory,
cursor_stack.is_item_with_entity_data, cursor_stack.is_upgrade_item
},
truthy = {
parent = "[color=blue]",
name = "[color=green]",
funcs = "[color=orange]",
close = "[/color]"
}
}
for index, test in pairs(tests.funcs) do
if test then
local msg = tests.truthy.parent .. tests.parent[index] ..
tests.truthy.close .. " " .. tests.truthy.name ..
tests.name[index] .. tests.truthy.close .. " " ..
tests.truthy.funcs .. tostring(test) ..
tests.truthy.close
p(msg)
msg = tests.parent[index] .. " " .. tests.name[index] .. " " ..
tostring(test)
log(msg)
end
end
end
function tools.safeTeleport(player, surface, target_pos)
local safe_pos = surface.find_non_colliding_position("character",
target_pos, 15, 1)
if (not safe_pos) then
player.teleport(target_pos, surface)
else
player.teleport(safe_pos, surface)
end
end
function tools.getItem(player, item_name, count)
local items = game.item_prototypes
local player = player
if items[item_name] then
local count = count or items[item_name].stack_size
player.insert {name = item_name, count = count}
else
return
end
end
function tools.round(num, dp)
local mult = 10 ^ (dp or 0)
return math.floor(num * mult + 0.5) / mult
end
function tools.replace(player, e1, e2)
if not player.admin then
player.print("[ERROR] You're not admin!")
return
end
local p, cs, bp_ent_count, bp_tile_count = player.print,
player.cursor_stack, 0, 0
tools.run_tests(player, cs)
if game.entity_prototypes[e1] or game.tile_prototypes[e1] then
local bp, bp_ents, bp_tiles = {}, {}, {}
if not player.is_cursor_blueprint() then
bp_ents = cs.get_blueprint_entities()
bp_tiles = cs.get_blueprint_tiles()
else
bp_ents = player.get_blueprint_entities()
bp_tiles = player.cursor_stack.import_stack(tostring(
player.cursor_stack
.export_stack()))
.get_blueprint_tiles()
end
if game.entity_prototypes[e1] then
p(e1 .. " is an entity prototype.")
for each, ent in pairs(bp_ents) do
if ent.name == e1 then
ent.name = e2
bp_ent_count = bp_ent_count + 1
end
end
elseif game.tile_prototypes[e1] then
p(e1 .. " is a tile prototype.")
for each, tile in pairs(bp_tiles) do
if tile.name == e1 then
tile.name = e2
bp_tile_count = bp_tile_count + 1
end
end
end
cs.clear()
cs.set_stack {name = "blueprint"}
bp = cs
bp.set_blueprint_entities(bp_ents)
bp.set_blueprint_tiles(bp_tiles)
-- bp.clear()
-- bp.
-- if not player.is_cursor_blueprint() then
-- else
-- end
-- bp.clear_blueprint()
end
p("entity replacements: " .. bp_ent_count)
p("tile replacements: " .. bp_tile_count)
-- else
-- player.print("Not a valid blueprint")
end
function tools.getDistance(pos1, pos2)
local pos1 = {x = pos1.x or pos1[1], y = pos1.y or pos1[2]}
local pos2 = {x = pos2.x or pos2[1], y = pos2.y or pos2[2]}
local a = math.abs(pos1.x - pos2.x)
local b = math.abs(pos1.y - pos2.y)
local c = math.sqrt(a ^ 2 + b ^ 2)
return c
end
function tools.getClosest(pos, list)
local x, y = pos.x or pos[1], pos.y or pos[2]
local closest = tools.MAX_INT32
for _, posenum in pairs(list) do
local distance = tools.getDistance(pos, posenum)
if distance < closest then
x, y = posenum.x, posenum.y
closest = distance
end
end
if closest == tools.MAX_INT32 then return end
return {position = {x, y}, distance = closest}
end
return tools
|
local UIManager =
{
Name = "UI",
Type = "System",
Namespace = "C_UI",
Functions =
{
{
Name = "Reload",
Type = "Function",
},
},
Events =
{
{
Name = "UiScaleChanged",
Type = "Event",
LiteralName = "UI_SCALE_CHANGED",
},
},
Tables =
{
},
};
APIDocumentation:AddDocumentationTable(UIManager);
|
require('core.LGML')({
entry = 'src.Game',
debug = true
})
|
--[[
-- Created by Tyler Berry, Aug 14 2017
-- Copyright (c) Firaxis Games
--]]
-- ===========================================================================
-- Base File
-- ===========================================================================
include("WorldTracker");
include("AllianceResearchSupport");
-- ===========================================================================
-- CACHE BASE FUNCTIONS
-- ===========================================================================
BASE_UpdateResearchPanel = UpdateResearchPanel;
BASE_RealizeCurrentResearch = RealizeCurrentResearch;
BASE_ShouldUpdateResearchPanel = ShouldUpdateResearchPanel;
-- ===========================================================================
-- OVERRIDE BASE FUNCTIONS
-- ===========================================================================
function UpdateResearchPanel( isHideResearch:boolean )
CalculateAllianceResearchBonus();
BASE_UpdateResearchPanel(isHideResearch);
end
function RealizeCurrentResearch( playerID:number, kData:table, kControl:table )
BASE_RealizeCurrentResearch(playerID, kData, kControl);
if kControl == nil then
kControl = Controls;
end
local showAllianceIcon = false;
if kData ~= nil then
local techID = GameInfo.Technologies[kData.TechType].Index;
if AllyHasOrIsResearchingTech(techID) then
kControl.AllianceIcon:SetToolTipString(GetAllianceIconToolTip());
kControl.AllianceIcon:SetColor(GetAllianceIconColor());
showAllianceIcon = true;
end
end
kControl.Alliance:SetShow(showAllianceIcon);
end
function ShouldUpdateResearchPanel(ePlayer:number, eTech:number)
return BASE_ShouldUpdateResearchPanel(ePlayer, eTech) or HasMaxLevelResearchAlliance(ePlayer);
end
-- ===========================================================================
function RealizeEmptyMessage()
local crisisData = Game.GetEmergencyManager():GetEmergencyInfoTable(Game.GetLocalPlayer());
local foo = not crisisData;
if (m_hideChat and m_hideCivics and m_hideResearch and next(crisisData) == nil) then
--Controls.EmptyPanel:SetHide(false);
else
--Controls.EmptyPanel:SetHide(true);
end
end
function Initialize()
ContextPtr:LoadNewContext("WorldCrisisTracker", Controls.PanelStack);
Controls.TutorialGoals:SetHide(true);
Controls.PanelStack:CalculateSize();
end
Initialize();
|
resource_manifest_version "44febabe-d386-4d18-afbe-5e627f4af937"
this_is_a_map 'yes'
|
--[[
module:Color
author:DylanYang
time:2021-02-18 16:26:05
]]
local _M = Class("Color")
_M.public.r = nil
_M.public.g = nil
_M.public.b = nil
function _M:ctor(r, g, b)
self.r = r or 0
self.g = g or 0
self.b = b or 0
end
function static:ToString()
return string.format("Color(r: %s, g: %s, b: %s)", self.r, self.g, self.b)
end
--Converts the value of the color channel to the range 0-1
function static:DecimalColor(c)
return c.r / 255, c.g / 255, c.b / 255
end
function static:GetHexadecimal(c)
local cps = {"r", "g", "b"}
local cstr = ""
for i = 1, #cps do
cstr = cstr..string.format("%0x", c[cps[i]])
end
return cstr
end
function static:GetColorByType(c, t)
if t == 1 then
return self:GetHexadecimal(c)
elseif t == 2 then
return string.format("<color=#%s>%s</color>", self:GetHexadecimal(c), "%s")
end
return c
end
return _M
|
-- Copyright (c) 2010-2012 by Robert G. Jakabosky <bobby@sharedrealm.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.
object "ODB" {
c_source [[
typedef git_odb ODB;
]],
constructor "new" {
c_call {"GitError", "err"} "git_odb_new" { "ODB *", "&this" },
},
constructor "open" {
c_call {"GitError", "err"} "git_odb_open"
{ "ODB *", "&this", "const char *", "object_dir" },
},
destructor "free" {
c_method_call "void" "git_odb_free" {}
},
method "add_backend" {
var_in{"ODBBackend *", "backend"},
var_in{"int", "priority"},
var_out{"GitError", "err"},
c_source [[
${err} = git_odb_add_backend(${this}, &(${backend}->backend), ${priority});
ODBBackend_ref(${backend});
]],
},
method "add_alternate" {
var_in{"ODBBackend *", "backend"},
var_in{"int", "priority"},
var_out{"GitError", "err"},
c_source [[
${err} = git_odb_add_alternate(${this}, &(${backend}->backend), ${priority});
ODBBackend_ref(${backend});
]],
},
method "read" {
c_call "GitError" "git_odb_read"
{ "!OdbObject *", "&out>1", "ODB *", "this", "OID", "&id"},
},
method "read_prefix" {
c_call "GitError" "git_odb_read_prefix"
{ "!OdbObject *", "&out>1", "ODB *", "this", "OID", "&short_id", "unsigned int", "len"},
},
method "read_header" {
c_call { "GitError", "err>3" } "git_odb_read_header"
{ "size_t", "&len_p>1", "git_otype", "&(otype)", "ODB *", "this", "OID", "&id"},
c_call { "const char *", "type>2" } "git_object_type2string" { "git_otype", "otype" },
},
method "exists" {
c_method_call { "GitError", "err" } "git_odb_exists" { "OID", "&id" }
},
method "write" {
c_call { "git_otype", "(otype)" } "git_object_string2type" { "const char *", "type<3" },
c_call "GitError" "git_odb_write"
{ "OID", "&id>1", "ODB *", "this<1", "const char *", "data<2", "size_t", "#data",
"git_otype", "otype"},
},
c_function "hash" {
c_call { "GitError", "err" } "git_odb_hash"
{ "OID", "&id>1", "const char *", "data", "size_t", "#data", "git_otype", "otype"}
},
c_function "hashfile" {
c_call { "GitError", "err" } "git_odb_hashfile"
{ "OID", "&id>1", "const char *", "path", "git_otype", "otype"}
},
}
|
---------------------------------------------------------------------------------------------------
-- RC common module
---------------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.mobileHost = "127.0.0.1"
config.defaultProtocolVersion = 2
config.ValidateSchema = false
config.checkAllValidations = true
config.application1.registerAppInterfaceParams.appHMIType = { "REMOTE_CONTROL" }
config.application2.registerAppInterfaceParams.appHMIType = { "REMOTE_CONTROL" }
--[[ Required Shared libraries ]]
local test = require("user_modules/dummy_connecttest")
local commonFunctions = require("user_modules/shared_testcases/commonFunctions")
local commonTestCases = require("user_modules/shared_testcases/commonTestCases")
local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
local json = require("modules/json")
local hmi_values = require("user_modules/hmi_values")
local utils = require('user_modules/utils')
local actions = require("user_modules/sequences/actions")
local apiLoader = require("modules/api_loader")
--[[ Common Variables ]]
local commonRC = {}
commonRC.timeout = 2000
commonRC.minTimeout = 500
commonRC.DEFAULT = "Default"
commonRC.buttons = { climate = "FAN_UP", radio = "VOLUME_UP" }
commonRC.getHMIConnection = actions.getHMIConnection
commonRC.getMobileSession = actions.getMobileSession
commonRC.policyTableUpdate = actions.policyTableUpdate
commonRC.getHMICapabilitiesFromFile = actions.sdl.getHMICapabilitiesFromFile
commonRC.registerApp = actions.registerApp
commonRC.getHMIAppId = actions.getHMIAppId
commonRC.jsonFileToTable = utils.jsonFileToTable
commonRC.tableToJsonFile = utils.tableToJsonFile
commonRC.cloneTable = utils.cloneTable
commonRC.wait = actions.run.wait
commonRC.isTableEqual = utils.isTableEqual
commonRC.getPreloadedPT = actions.sdl.getPreloadedPT
commonRC.getDefaultHMITable = hmi_values.getDefaultHMITable
commonRC.modules = { "RADIO", "CLIMATE" }
commonRC.allModules = { "RADIO", "CLIMATE", "SEAT", "AUDIO", "LIGHT", "HMI_SETTINGS" }
commonRC.newModules = { "AUDIO", "LIGHT", "HMI_SETTINGS" }
commonRC.modulesWithoutSeat = { "RADIO", "CLIMATE", "AUDIO", "LIGHT", "HMI_SETTINGS" }
commonRC.capMap = {
["RADIO"] = "radioControlCapabilities",
["CLIMATE"] = "climateControlCapabilities",
["SEAT"] = "seatControlCapabilities",
["AUDIO"] = "audioControlCapabilities",
["LIGHT"] = "lightControlCapabilities",
["HMI_SETTINGS"] = "hmiSettingsControlCapabilities",
["BUTTONS"] = "buttonCapabilities"
}
commonRC.audioSources = {
"NO_SOURCE_SELECTED",
"CD",
"BLUETOOTH_STEREO_BTST",
"USB",
"USB2",
"LINE_IN",
"IPOD",
"MOBILE_APP",
"AM",
"FM",
"XM",
"DAB"
}
commonRC.LightsNameList = { "FRONT_LEFT_HIGH_BEAM", "FRONT_RIGHT_HIGH_BEAM", "FRONT_LEFT_LOW_BEAM",
"FRONT_RIGHT_LOW_BEAM", "FRONT_LEFT_PARKING_LIGHT", "FRONT_RIGHT_PARKING_LIGHT",
"FRONT_LEFT_FOG_LIGHT", "FRONT_RIGHT_FOG_LIGHT", "FRONT_LEFT_DAYTIME_RUNNING_LIGHT",
"FRONT_RIGHT_DAYTIME_RUNNING_LIGHT", "FRONT_LEFT_TURN_LIGHT", "FRONT_RIGHT_TURN_LIGHT",
"REAR_LEFT_FOG_LIGHT", "REAR_RIGHT_FOG_LIGHT", "REAR_LEFT_TAIL_LIGHT", "REAR_RIGHT_TAIL_LIGHT",
"REAR_LEFT_BRAKE_LIGHT", "REAR_RIGHT_BRAKE_LIGHT", "REAR_LEFT_TURN_LIGHT", "REAR_RIGHT_TURN_LIGHT",
"REAR_REGISTRATION_PLATE_LIGHT", "HIGH_BEAMS", "LOW_BEAMS", "FOG_LIGHTS", "RUNNING_LIGHTS",
"PARKING_LIGHTS", "BRAKE_LIGHTS", "REAR_REVERSING_LIGHTS", "SIDE_MARKER_LIGHTS", "LEFT_TURN_LIGHTS",
"RIGHT_TURN_LIGHTS", "HAZARD_LIGHTS", "AMBIENT_LIGHTS", "OVERHEAD_LIGHTS", "READING_LIGHTS",
"TRUNK_LIGHTS", "EXTERIOR_FRONT_LIGHTS", "EXTERIOR_REAR_LIGHTS", "EXTERIOR_LEFT_LIGHTS",
"EXTERIOR_RIGHT_LIGHTS", "REAR_CARGO_LIGHTS", "REAR_TRUCK_BED_LIGHTS", "REAR_TRAILER_LIGHTS",
"LEFT_SPOT_LIGHTS", "RIGHT_SPOT_LIGHTS", "LEFT_PUDDLE_LIGHTS", "RIGHT_PUDDLE_LIGHTS",
"EXTERIOR_ALL_LIGHTS" }
commonRC.readOnlyLightStatus = { "RAMP_UP", "RAMP_DOWN", "UNKNOWN", "INVALID" }
--[[ Common Functions ]]
function commonRC.registerAppWOPTU(pAppId, self)
return actions.registerAppWOPTU(pAppId)
end
function commonRC.getRCAppConfig(tbl)
if tbl then
local out = commonRC.cloneTable(tbl.policy_table.app_policies.default)
out.moduleType = commonRC.allModules
out.groups = { "Base-4", "RemoteControl" }
out.AppHMIType = { "REMOTE_CONTROL" }
return out
else
return {
keep_context = false,
steal_focus = false,
priority = "NONE",
default_hmi = "NONE",
moduleType = commonRC.allModules,
groups = { "Base-4", "RemoteControl" },
AppHMIType = { "REMOTE_CONTROL" }
}
end
end
function actions.ptu.getAppData(pAppId)
return {
keep_context = false,
steal_focus = false,
priority = "NONE",
default_hmi = "NONE",
groups = { "Base-4", "RemoteControl" },
AppHMIType = actions.getConfigAppParams(pAppId).appHMIType
}
end
local function allowSDL()
commonRC.getHMIConnection():SendNotification("SDL.OnAllowSDLFunctionality", {
allowed = true,
source = "GUI",
device = {
id = utils.getDeviceMAC(),
name = utils.getDeviceName()
}
})
actions.run.wait(500) -- stabilization delay
end
function commonRC.start(pHMIParams)
test:runSDL()
commonFunctions:waitForSDLStart(test)
:Do(function()
test:initHMI(test)
:Do(function()
commonFunctions:userPrint(35, "HMI initialized")
test:initHMI_onReady(pHMIParams)
:Do(function()
commonFunctions:userPrint(35, "HMI is ready")
test:connectMobile()
:Do(function()
commonFunctions:userPrint(35, "Mobile connected")
allowSDL()
end)
end)
end)
end)
end
local function backupPreloadedPT()
local preloadedFile = commonFunctions:read_parameter_from_smart_device_link_ini("PreloadedPT")
commonPreconditions:BackupFile(preloadedFile)
end
local function updatePreloadedPT(pCountOfRCApps)
if not pCountOfRCApps then pCountOfRCApps = 2 end
local preloadedFile = commonPreconditions:GetPathToSDL()
.. commonFunctions:read_parameter_from_smart_device_link_ini("PreloadedPT")
local preloadedTable = commonRC.jsonFileToTable(preloadedFile)
preloadedTable.policy_table.functional_groupings["DataConsent-2"].rpcs = json.null
preloadedTable.policy_table.functional_groupings["RemoteControl"].rpcs.OnRCStatus = {
hmi_levels = { "FULL", "BACKGROUND", "LIMITED", "NONE" }
}
for i = 1, pCountOfRCApps do
local appId = config["application" .. i].registerAppInterfaceParams.fullAppID
preloadedTable.policy_table.app_policies[appId] = commonRC.getRCAppConfig(preloadedTable)
preloadedTable.policy_table.app_policies[appId].AppHMIType = nil
end
commonRC.tableToJsonFile(preloadedTable, preloadedFile)
end
function commonRC.preconditions(isPreloadedUpdate, pCountOfRCApps)
if isPreloadedUpdate == nil then isPreloadedUpdate = true end
actions.preconditions()
if isPreloadedUpdate == true then
backupPreloadedPT()
updatePreloadedPT(pCountOfRCApps)
end
end
local function restorePreloadedPT()
local preloadedFile = commonFunctions:read_parameter_from_smart_device_link_ini("PreloadedPT")
commonPreconditions:RestoreFile(preloadedFile)
end
function commonRC.postconditions()
actions.postconditions()
restorePreloadedPT()
end
function commonRC.unregisterApp(pAppId)
if not pAppId then pAppId = 1 end
local mobSession = commonRC.getMobileSession(pAppId)
local hmiAppId = commonRC.getHMIAppId(pAppId)
commonRC.deleteHMIAppId(pAppId)
local cid = mobSession:SendRPC("UnregisterAppInterface",{})
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered", { appID = hmiAppId, unexpectedDisconnect = false })
mobSession:ExpectResponse(cid, { success = true, resultCode = "SUCCESS"})
end
function commonRC.getModuleControlData(module_type)
local out = { moduleType = module_type }
if module_type == "CLIMATE" then
out.moduleId = "2df6518c-ca8a-4e7c-840a-0eba5c028351"
out.climateControlData = {
fanSpeed = 50,
currentTemperature = {
unit = "FAHRENHEIT",
value = 20.1
},
desiredTemperature = {
unit = "CELSIUS",
value = 10.5
},
acEnable = true,
circulateAirEnable = true,
autoModeEnable = true,
defrostZone = "FRONT",
dualModeEnable = true,
acMaxEnable = true,
ventilationMode = "BOTH",
heatedSteeringWheelEnable = true,
heatedWindshieldEnable = true,
heatedRearWindowEnable = true,
heatedMirrorsEnable = true,
climateEnable = true
}
elseif module_type == "RADIO" then
out.moduleId = "00bd6d93-e093-4bf0-9784-281febe41bed"
out.radioControlData = {
frequencyInteger = 1,
frequencyFraction = 2,
band = "AM",
rdsData = {
PS = "ps",
RT = "rt",
CT = "123456789012345678901234",
PI = "pi",
PTY = 1,
TP = false,
TA = true,
REG = "US"
},
availableHdChannels = {0, 1, 2, 3, 4, 5, 6, 7},
hdChannel = 7,
signalStrength = 5,
signalChangeThreshold = 10,
radioEnable = true,
state = "ACQUIRING",
hdRadioEnable = true,
sisData = {
stationShortName = "Name1",
stationIDNumber = {
countryCode = 100,
fccFacilityId = 100
},
stationLongName = "RadioStationLongName",
stationLocation = {
longitudeDegrees = 0.1,
latitudeDegrees = 0.1,
altitude = 0.1
},
stationMessage = "station message"
}
}
elseif module_type == "SEAT" then
out.moduleId = "a42bf1e0-e02e-4462-912a-7d4230815f73"
out.seatControlData = {
id = "DRIVER",
heatingEnabled = true,
coolingEnabled = true,
heatingLevel = 50,
coolingLevel = 50,
horizontalPosition = 50,
verticalPosition = 50,
frontVerticalPosition = 50,
backVerticalPosition = 50,
backTiltAngle = 50,
headSupportHorizontalPosition = 50,
headSupportVerticalPosition = 50,
massageEnabled = true,
massageMode = {
{
massageZone = "LUMBAR",
massageMode = "HIGH"
},
{
massageZone = "SEAT_CUSHION",
massageMode = "LOW"
}
},
massageCushionFirmness = {
{
cushion = "TOP_LUMBAR",
firmness = 30
},
{
cushion = "BACK_BOLSTERS",
firmness = 60
}
},
memory = {
id = 1,
label = "Label value",
action = "SAVE"
}
}
elseif module_type == "AUDIO" then
out.moduleId = "0876b4be-f1ce-4f5c-86e9-5ca821683a1b"
out.audioControlData = {
source = "AM",
keepContext = false,
volume = 50,
equalizerSettings = {
{
channelId = 10,
channelName = "Channel 1",
channelSetting = 50
}
}
}
elseif module_type == "LIGHT" then
out.moduleId = "f31ef579-743d-41be-a75e-80630d16f4e6"
out.lightControlData = {
lightState = {
{
id = "FRONT_LEFT_HIGH_BEAM",
status = "ON",
density = 0.2,
color = {
red = 50,
green = 150,
blue = 200
}
}
}
}
elseif module_type == "HMI_SETTINGS" then
out.moduleId = "fd68f1ef-95ce-4468-a304-4c864a0e34a1"
out.hmiSettingsControlData = {
displayMode = "DAY",
temperatureUnit = "CELSIUS",
distanceUnit = "KILOMETERS"
}
end
return out
end
function commonRC.getAnotherModuleControlData(module_type)
local out = { moduleType = module_type }
if module_type == "CLIMATE" then
out.moduleId = "2df6518c-ca8a-4e7c-840a-0eba5c028351"
out.climateControlData = {
fanSpeed = 65,
currentTemperature = {
unit = "FAHRENHEIT",
value = 44.3
},
desiredTemperature = {
unit = "CELSIUS",
value = 22.6
},
acEnable = false,
circulateAirEnable = false,
autoModeEnable = true,
defrostZone = "ALL",
dualModeEnable = true,
acMaxEnable = false,
ventilationMode = "UPPER",
climateEnable = false
}
elseif module_type == "RADIO" then
out.moduleId = "00bd6d93-e093-4bf0-9784-281febe41bed"
out.radioControlData = {
frequencyInteger = 1,
frequencyFraction = 2,
band = "AM",
rdsData = {
PS = "ps",
RT = "rt",
CT = "123456789012345678901234",
PI = "pi",
PTY = 2,
TP = false,
TA = true,
REG = "US"
},
availableHDs = 1,
hdChannel = 1,
signalStrength = 5,
signalChangeThreshold = 20,
radioEnable = true,
state = "ACQUIRING",
hdRadioEnable = true,
sisData = {
stationShortName = "Name2",
stationIDNumber = {
countryCode = 200,
fccFacilityId = 200
},
stationLongName = "RadioStationLongName2",
stationLocation = {
longitudeDegrees = 20.1,
latitudeDegrees = 20.1,
altitude = 20.1
},
stationMessage = "station message 2"
}
}
elseif module_type == "SEAT" then
out.moduleId = "a42bf1e0-e02e-4462-912a-7d4230815f73"
out.seatControlData ={
id = "FRONT_PASSENGER",
heatingEnabled = true,
coolingEnabled = false,
heatingLevel = 75,
coolingLevel = 0,
horizontalPosition = 75,
verticalPosition = 75,
frontVerticalPosition = 75,
backVerticalPosition = 75,
backTiltAngle = 75,
headSupportHorizontalPosition = 75,
headSupportVerticalPosition = 75,
massageEnabled = true,
massageMode = {
{
massageZone = "LUMBAR",
massageMode = "OFF"
},
{
massageZone = "SEAT_CUSHION",
massageMode = "HIGH"
}
},
massageCushionFirmness = {
{
cushion = "MIDDLE_LUMBAR",
firmness = 65
},
{
cushion = "SEAT_BOLSTERS",
firmness = 30
}
},
memory = {
id = 2,
label = "Another label value",
action = "RESTORE"
}
}
elseif module_type == "AUDIO" then
out.moduleId = "0876b4be-f1ce-4f5c-86e9-5ca821683a1b"
out.audioControlData = {
source = "USB",
keepContext = true,
volume = 20,
equalizerSettings = {
{
channelId = 20,
channelName = "Channel 2",
channelSetting = 20
}
}
}
elseif module_type == "LIGHT" then
out.moduleId = "f31ef579-743d-41be-a75e-80630d16f4e6"
out.lightControlData = {
lightState = {
{
id = "READING_LIGHTS",
status = "ON",
density = 0.5,
color = {
red = 150,
green = 200,
blue = 250
}
}
}
}
elseif module_type == "HMI_SETTINGS" then
out.moduleId = "fd68f1ef-95ce-4468-a304-4c864a0e34a1"
out.hmiSettingsControlData = {
displayMode = "NIGHT",
temperatureUnit = "FAHRENHEIT",
distanceUnit = "MILES"
}
end
return out
end
function commonRC.getButtonNameByModule(pModuleType)
return commonRC.buttons[string.lower(pModuleType)]
end
function commonRC.getReadOnlyParamsByModule(pModuleType)
local out = { moduleType = pModuleType }
if pModuleType == "CLIMATE" then
out.climateControlData = {
currentTemperature = {
unit = "FAHRENHEIT",
value = 32.6
}
}
elseif pModuleType == "RADIO" then
out.radioControlData = {
rdsData = {
PS = "ps",
RT = "rt",
CT = "123456789012345678901234",
PI = "pi",
PTY = 2,
TP = false,
TA = true,
REG = "US"
},
availableHdChannels = {2, 3, 4},
signalStrength = 4,
signalChangeThreshold = 22,
state = "MULTICAST",
sisData = {
stationShortName = "Name2",
stationIDNumber = {
countryCode = 200,
fccFacilityId = 200
},
stationLongName = "RadioStationLongName2",
stationLocation = {
longitudeDegrees = 20.1,
latitudeDegrees = 20.1,
altitude = 20.1
},
stationMessage = "station message 2"
}
}
elseif pModuleType == "AUDIO" then
out.audioControlData = {
equalizerSettings = { { channelName = "Channel 1" } }
}
end
return out
end
function commonRC.getModuleParams(pModuleData)
if pModuleData.moduleType == "CLIMATE" then
if not pModuleData.climateControlData then
pModuleData.climateControlData = { }
end
return pModuleData.climateControlData
elseif pModuleData.moduleType == "RADIO" then
if not pModuleData.radioControlData then
pModuleData.radioControlData = { }
end
return pModuleData.radioControlData
elseif pModuleData.moduleType == "AUDIO" then
if not pModuleData.audioControlData then
pModuleData.audioControlData = { }
end
return pModuleData.audioControlData
elseif pModuleData.moduleType == "SEAT" then
if not pModuleData.seatControlData then
pModuleData.seatControlData = { }
end
return pModuleData.seatControlData
end
end
function commonRC.getSettableModuleControlData(pModuleType)
local out = commonRC.getModuleControlData(pModuleType)
local params_read_only = commonRC.getModuleParams(commonRC.getReadOnlyParamsByModule(pModuleType))
if params_read_only then
for p_read_only, p_read_only_value in pairs(params_read_only) do
if pModuleType == "AUDIO" then
for sub_read_only_key, sub_read_only_value in pairs(p_read_only_value) do
for sub_read_only_name in pairs(sub_read_only_value) do
commonRC.getModuleParams(out)[p_read_only][sub_read_only_key][sub_read_only_name] = nil
end
end
else
commonRC.getModuleParams(out)[p_read_only] = nil
end
end
end
return out
end
-- RC RPCs structure
local rcRPCs = {
GetInteriorVehicleData = {
appEventName = "GetInteriorVehicleData",
hmiEventName = "RC.GetInteriorVehicleData",
requestParams = function(pModuleType, pSubscribe)
return {
moduleType = pModuleType,
subscribe = pSubscribe
}
end,
hmiRequestParams = function(pModuleType, _, pSubscribe)
return {
moduleType = pModuleType,
moduleId = commonRC.actualInteriorDataStateOnHMI[pModuleType].moduleId,
subscribe = pSubscribe
}
end,
hmiResponseParams = function(pModuleType, pSubscribe)
local GetInteriorVDModuleData = commonRC.actualInteriorDataStateOnHMI[pModuleType]
if GetInteriorVDModuleData.audioControlData then
GetInteriorVDModuleData.audioControlData.keepContext = nil
end
return {
moduleData = GetInteriorVDModuleData,
isSubscribed = pSubscribe
}
end,
responseParams = function(success, resultCode, pModuleType, pSubscribe)
local GetInteriorVDModuleData = commonRC.actualInteriorDataStateOnHMI[pModuleType]
if GetInteriorVDModuleData.audioControlData then
GetInteriorVDModuleData.audioControlData.keepContext = nil
end
return {
success = success,
resultCode = resultCode,
moduleData = GetInteriorVDModuleData,
isSubscribed = pSubscribe
}
end
},
SetInteriorVehicleData = {
appEventName = "SetInteriorVehicleData",
hmiEventName = "RC.SetInteriorVehicleData",
requestParams = function(pModuleType)
local moduleData = commonRC.getSettableModuleControlData(pModuleType)
moduleData.moduleId = nil
return {
moduleData = moduleData
}
end,
hmiRequestParams = function(pModuleType, pAppId)
local moduleData = commonRC.getSettableModuleControlData(pModuleType)
moduleData.moduleId = commonRC.actualInteriorDataStateOnHMI[pModuleType].moduleId
return {
moduleData = moduleData,
appID = commonRC.getHMIAppId(pAppId),
}
end,
hmiResponseParams = function(pModuleType)
local moduleData = commonRC.getSettableModuleControlData(pModuleType)
moduleData.moduleId = commonRC.actualInteriorDataStateOnHMI[pModuleType].moduleId
return {
moduleData = moduleData
}
end,
responseParams = function(success, resultCode, pModuleType)
local moduleData = commonRC.getSettableModuleControlData(pModuleType)
moduleData.moduleId = commonRC.actualInteriorDataStateOnHMI[pModuleType].moduleId
return {
success = success,
resultCode = resultCode,
moduleData = moduleData
}
end
},
ButtonPress = {
appEventName = "ButtonPress",
hmiEventName = "Buttons.ButtonPress",
requestParams = function(pModuleType)
return {
moduleType = pModuleType,
buttonName = commonRC.getButtonNameByModule(pModuleType),
buttonPressMode = "SHORT"
}
end,
hmiRequestParams = function(pModuleType, pAppId)
return {
appID = commonRC.getHMIAppId(pAppId),
moduleType = pModuleType,
buttonName = commonRC.getButtonNameByModule(pModuleType),
buttonPressMode = "SHORT"
}
end,
hmiResponseParams = function()
return {}
end,
responseParams = function(success, resultCode)
return {
success = success,
resultCode = resultCode
}
end
},
GetInteriorVehicleDataConsent = {
hmiEventName = "RC.GetInteriorVehicleDataConsent",
hmiRequestParams = function(pModuleType, pAppId)
return {
appID = commonRC.getHMIAppId(pAppId),
moduleType = pModuleType
}
end,
hmiResponseParams = function(pAllowed)
return {
allowed = {pAllowed}
}
end,
},
OnInteriorVehicleData = {
appEventName = "OnInteriorVehicleData",
hmiEventName = "RC.OnInteriorVehicleData",
hmiResponseParams = function(pModuleType)
local OnInteriorVDModuleData = commonRC.getAnotherModuleControlData(pModuleType)
if OnInteriorVDModuleData.audioControlData then
OnInteriorVDModuleData.audioControlData.keepContext = nil
end
return {
moduleData = OnInteriorVDModuleData
}
end,
responseParams = function(pModuleType)
local OnInteriorVDModuleData = commonRC.getAnotherModuleControlData(pModuleType)
if OnInteriorVDModuleData.audioControlData then
OnInteriorVDModuleData.audioControlData.keepContext = nil
end
return {
moduleData = OnInteriorVDModuleData
}
end
},
OnRemoteControlSettings = {
hmiEventName = "RC.OnRemoteControlSettings",
hmiResponseParams = function(pAllowed, pAccessMode)
return {
allowed = pAllowed,
accessMode = pAccessMode
}
end
}
}
function commonRC.getAppEventName(pRPC)
return rcRPCs[pRPC].appEventName
end
function commonRC.getHMIEventName(pRPC)
return rcRPCs[pRPC].hmiEventName
end
function commonRC.getAppRequestParams(pRPC, ...)
return rcRPCs[pRPC].requestParams(...)
end
function commonRC.getAppResponseParams(pRPC, ...)
return rcRPCs[pRPC].responseParams(...)
end
function commonRC.getHMIRequestParams(pRPC, ...)
return rcRPCs[pRPC].hmiRequestParams(...)
end
function commonRC.getHMIResponseParams(pRPC, ...)
return rcRPCs[pRPC].hmiResponseParams(...)
end
function commonRC.subscribeToModule(pModuleType, pAppId)
local rpc = "GetInteriorVehicleData"
local subscribe = true
local mobSession = commonRC.getMobileSession(pAppId)
local cid = mobSession:SendRPC(commonRC.getAppEventName(rpc), commonRC.getAppRequestParams(rpc, pModuleType, subscribe))
EXPECT_HMICALL(commonRC.getHMIEventName(rpc), commonRC.getHMIRequestParams(rpc, pModuleType, pAppId, subscribe))
:Do(function(_, data)
commonRC.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", commonRC.getHMIResponseParams(rpc, pModuleType, subscribe))
commonRC.setActualInteriorVD(pModuleType, commonRC.getHMIResponseParams(rpc, pModuleType, subscribe).moduleData)
end)
mobSession:ExpectResponse(cid, commonRC.getAppResponseParams(rpc, true, "SUCCESS", pModuleType, subscribe))
:ValidIf(function(_,data)
if "AUDIO" == pModuleType and
nil ~= data.payload.moduleData.audioControlData.keepContext then
return false, "Mobile response GetInteriorVehicleData contains unexpected keepContext parameter"
end
return true
end)
end
function commonRC.unSubscribeToModule(pModuleType, pAppId)
local rpc = "GetInteriorVehicleData"
local subscribe = false
local mobSession = commonRC.getMobileSession(pAppId)
local cid = mobSession:SendRPC(commonRC.getAppEventName(rpc), commonRC.getAppRequestParams(rpc, pModuleType, subscribe))
EXPECT_HMICALL(commonRC.getHMIEventName(rpc), commonRC.getHMIRequestParams(rpc, pModuleType, pAppId, subscribe))
:Do(function(_, data)
commonRC.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", commonRC.getHMIResponseParams(rpc, pModuleType, subscribe))
end)
mobSession:ExpectResponse(cid, commonRC.getAppResponseParams(rpc, true, "SUCCESS", pModuleType, subscribe))
:ValidIf(function(_,data)
if "AUDIO" == pModuleType and
nil ~= data.payload.moduleData.audioControlData.keepContext then
return false, "Mobile response GetInteriorVehicleData contains unexpected keepContext parameter"
end
return true
end)
end
function commonRC.isSubscribed(pModuleType, pAppId)
local mobSession = commonRC.getMobileSession(pAppId)
local rpc = "OnInteriorVehicleData"
commonRC.getHMIConnection():SendNotification(commonRC.getHMIEventName(rpc), commonRC.getHMIResponseParams(rpc, pModuleType))
commonRC.setActualInteriorVD(pModuleType, commonRC.getHMIResponseParams(rpc, pModuleType).moduleData)
mobSession:ExpectNotification(commonRC.getAppEventName(rpc), commonRC.getAppResponseParams(rpc, pModuleType))
:ValidIf(function(_,data)
if "AUDIO" == pModuleType and
nil ~= data.payload.moduleData.audioControlData.keepContext then
return false, "Mobile notification OnInteriorVehicleData contains unexpected keepContext parameter"
end
return true
end)
end
function commonRC.isUnsubscribed(pModuleType, pAppId)
local mobSession = commonRC.getMobileSession(pAppId)
local rpc = "OnInteriorVehicleData"
commonRC.getHMIConnection():SendNotification(commonRC.getHMIEventName(rpc), commonRC.getHMIResponseParams(rpc, pModuleType))
commonRC.setActualInteriorVD(pModuleType, commonRC.getHMIResponseParams(rpc, pModuleType).moduleData)
mobSession:ExpectNotification(commonRC.getAppEventName(rpc), {}):Times(0)
commonTestCases:DelayedExp(commonRC.timeout)
end
function commonRC.defineRAMode(pAllowed, pAccessMode)
local rpc = "OnRemoteControlSettings"
commonRC.getHMIConnection():SendNotification(commonRC.getHMIEventName(rpc), commonRC.getHMIResponseParams(rpc, pAllowed, pAccessMode))
commonTestCases:DelayedExp(commonRC.minTimeout) -- workaround due to issue with SDL -> redundant OnHMIStatus notification is sent
end
function commonRC.rpcDenied(pModuleType, pAppId, pRPC, pResultCode)
local mobSession = commonRC.getMobileSession(pAppId)
local cid = mobSession:SendRPC(commonRC.getAppEventName(pRPC), commonRC.getAppRequestParams(pRPC, pModuleType))
EXPECT_HMICALL(commonRC.getHMIEventName(pRPC), {}):Times(0)
mobSession:ExpectResponse(cid, { success = false, resultCode = pResultCode })
commonTestCases:DelayedExp(commonRC.timeout)
end
function commonRC.rpcDeniedWithCustomParams(pParams, pAppId, pRPC, pResultCode)
local mobSession = commonRC.getMobileSession(pAppId)
local cid = mobSession:SendRPC(commonRC.getAppEventName(pRPC), pParams)
EXPECT_HMICALL(commonRC.getHMIEventName(pRPC), {}):Times(0)
mobSession:ExpectResponse(cid, { success = false, resultCode = pResultCode })
commonTestCases:DelayedExp(commonRC.timeout)
end
function commonRC.rpcAllowed(pModuleType, pAppId, pRPC)
local mobSession = commonRC.getMobileSession(pAppId)
local cid = mobSession:SendRPC(commonRC.getAppEventName(pRPC), commonRC.getAppRequestParams(pRPC, pModuleType))
EXPECT_HMICALL(commonRC.getHMIEventName(pRPC), commonRC.getHMIRequestParams(pRPC, pModuleType, pAppId))
:Do(function(_, data)
commonRC.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", commonRC.getHMIResponseParams(pRPC, pModuleType))
end)
mobSession:ExpectResponse(cid, commonRC.getAppResponseParams(pRPC, true, "SUCCESS", pModuleType))
end
function commonRC.rpcAllowedWithConsent(pModuleType, pAppId, pRPC)
local mobSession = commonRC.getMobileSession(pAppId)
local cid = mobSession:SendRPC(commonRC.getAppEventName(pRPC), commonRC.getAppRequestParams(pRPC, pModuleType))
local consentRPC = "GetInteriorVehicleDataConsent"
EXPECT_HMICALL(commonRC.getHMIEventName(consentRPC), commonRC.getHMIRequestParams(consentRPC, pModuleType, pAppId))
:Do(function(_, data)
commonRC.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", commonRC.getHMIResponseParams(consentRPC, true))
EXPECT_HMICALL(commonRC.getHMIEventName(pRPC), commonRC.getHMIRequestParams(pRPC, pModuleType, pAppId))
:Do(function(_, data2)
commonRC.getHMIConnection():SendResponse(data2.id, data2.method, "SUCCESS", commonRC.getHMIResponseParams(pRPC, pModuleType))
end)
end)
mobSession:ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
end
function commonRC.rpcRejectWithConsent(pModuleType, pAppId, pRPC)
local moduleId = commonRC.actualInteriorDataStateOnHMI[pModuleType].moduleId
local info = "The resource [" .. pModuleType .. ":" .. moduleId ..
"] is in use and the driver disallows this remote control RPC"
local consentRPC = "GetInteriorVehicleDataConsent"
local mobSession = commonRC.getMobileSession(pAppId)
local cid = mobSession:SendRPC(commonRC.getAppEventName(pRPC), commonRC.getAppRequestParams(pRPC, pModuleType))
EXPECT_HMICALL(commonRC.getHMIEventName(consentRPC), commonRC.getHMIRequestParams(consentRPC, pModuleType, pAppId))
:Do(function(_, data)
commonRC.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", commonRC.getHMIResponseParams(consentRPC, false))
EXPECT_HMICALL(commonRC.getHMIEventName(pRPC)):Times(0)
end)
mobSession:ExpectResponse(cid, { success = false, resultCode = "REJECTED", info = info })
commonTestCases:DelayedExp(commonRC.timeout)
end
function commonRC.rpcRejectWithoutConsent(pModuleType, pAppId, pRPC)
local mobSession = commonRC.getMobileSession(pAppId)
local cid = mobSession:SendRPC(commonRC.getAppEventName(pRPC), commonRC.getAppRequestParams(pRPC, pModuleType))
EXPECT_HMICALL(commonRC.getHMIEventName("GetInteriorVehicleDataConsent")):Times(0)
EXPECT_HMICALL(commonRC.getHMIEventName(pRPC)):Times(0)
mobSession:ExpectResponse(cid, { success = false, resultCode = "REJECTED" })
commonTestCases:DelayedExp(commonRC.timeout)
end
function commonRC.rpcButtonPress(pParams, pAppId)
local cid = commonRC.getMobileSession(pAppId):SendRPC("ButtonPress", pParams)
pParams.appID = commonRC.getHMIAppId(pAppId)
EXPECT_HMICALL("Buttons.ButtonPress", pParams)
:Do(function(_, data)
commonRC.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
commonRC.getMobileSession(pAppId):ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
end
function commonRC.buildButtonCapability(name, shortPressAvailable, longPressAvailable, upDownAvailable)
return hmi_values.createButtonCapability(name, shortPressAvailable, longPressAvailable, upDownAvailable)
end
function commonRC.buildHmiRcCapabilities(pCapabilities)
local hmiParams = hmi_values.getDefaultHMITable()
hmiParams.RC.IsReady.params.available = true
local capParams = hmiParams.RC.GetCapabilities.params.remoteControlCapability
for k, v in pairs(commonRC.capMap) do
if pCapabilities[k] then
if pCapabilities[k] ~= commonRC.DEFAULT then
capParams[v] = pCapabilities[k]
end
else
capParams[v] = nil
end
end
return hmiParams
end
function commonRC.backupHMICapabilities()
local hmiCapabilitiesFile = commonFunctions:read_parameter_from_smart_device_link_ini("HMICapabilities")
commonPreconditions:BackupFile(hmiCapabilitiesFile)
end
function commonRC.restoreHMICapabilities()
local hmiCapabilitiesFile = commonFunctions:read_parameter_from_smart_device_link_ini("HMICapabilities")
commonPreconditions:RestoreFile(hmiCapabilitiesFile)
end
function commonRC.getButtonIdByName(pArray, pButtonName)
for id, buttonData in pairs(pArray) do
if buttonData.name == pButtonName then
return id
end
end
end
local function audibleState(pAppId)
if not pAppId then pAppId = 1 end
local appParams = config["application" .. pAppId].registerAppInterfaceParams
local audibleStateValue
if appParams.isMediaApplication == true then
audibleStateValue = "AUDIBLE"
else
audibleStateValue = "NOT_AUDIBLE"
end
return audibleStateValue
end
function commonRC.activateApp(pAppId)
if not pAppId then pAppId = 1 end
local pHMIAppId = commonRC.getHMIAppId(pAppId)
local mobSession = commonRC.getMobileSession(pAppId)
local requestId = test.hmiConnection:SendRequest("SDL.ActivateApp", { appID = pHMIAppId })
EXPECT_HMIRESPONSE(requestId)
mobSession:ExpectNotification("OnHMIStatus", { hmiLevel = "FULL", audioStreamingState = audibleState(pAppId),
systemContext = "MAIN" })
actions.run.wait()
end
function commonRC.getModuleId(pModuleType)
local rcCapabilities = hmi_values.getDefaultHMITable().RC.GetCapabilities.params.remoteControlCapability
if pModuleType == "LIGHT" or pModuleType == "HMI_SETTINGS" then
return rcCapabilities[commonRC.capMap[pModuleType]].moduleInfo.moduleId
else
return rcCapabilities[commonRC.capMap[pModuleType]][1].moduleInfo.moduleId
end
end
local function updateModuleId(pRcCapTbl)
for _, moduleType in pairs(commonRC.allModules) do
local defaultModuleId
if moduleType == "LIGHT" or moduleType == "HMI_SETTINGS" then
defaultModuleId = pRcCapTbl[commonRC.capMap[moduleType]].moduleInfo.moduleId
else
defaultModuleId = pRcCapTbl[commonRC.capMap[moduleType]][1].moduleInfo.moduleId
end
commonRC.actualInteriorDataStateOnHMI[moduleType].moduleId = defaultModuleId
end
end
function commonRC.updateDefaultCapabilities(pDisabledModuleTypes, pIsHmiCapCorrect)
local hmiCapabilitiesFile = commonPreconditions:GetPathToSDL()
.. commonFunctions:read_parameter_from_smart_device_link_ini("HMICapabilities")
local hmiCapTbl = commonRC.jsonFileToTable(hmiCapabilitiesFile)
local rcCapTbl = hmiCapTbl.UI.systemCapabilities.remoteControlCapability
if not pIsHmiCapCorrect then
updateModuleId(rcCapTbl)
end
for _, pDisabledModuleType in pairs(pDisabledModuleTypes) do
local buttonId = commonRC.getButtonIdByName(rcCapTbl.buttonCapabilities,
commonRC.getButtonNameByModule(pDisabledModuleType))
table.remove(rcCapTbl.buttonCapabilities, buttonId)
rcCapTbl[string.lower(pDisabledModuleType) .. "ControlCapabilities"] = nil
end
commonRC.tableToJsonFile(hmiCapTbl.UI.systemCapabilities.remoteControlCapability, "actualState001.json")
commonRC.tableToJsonFile(hmiCapTbl, hmiCapabilitiesFile)
end
commonRC.getHMIAppIds = actions.getHMIAppIds
commonRC.deleteHMIAppId = actions.deleteHMIAppId
commonRC.actualInteriorDataStateOnHMI = {
CLIMATE = commonRC.cloneTable(commonRC.getModuleControlData("CLIMATE")),
RADIO = commonRC.cloneTable(commonRC.getModuleControlData("RADIO")),
SEAT = commonRC.cloneTable(commonRC.getModuleControlData("SEAT")),
AUDIO = commonRC.cloneTable(commonRC.getModuleControlData("AUDIO")),
LIGHT = commonRC.cloneTable(commonRC.getModuleControlData("LIGHT")),
HMI_SETTINGS = commonRC.cloneTable(commonRC.getModuleControlData("HMI_SETTINGS"))
}
updateModuleId(commonRC.getDefaultHMITable().RC.GetCapabilities.params.remoteControlCapability)
function commonRC.setActualInteriorVD(pModuleType, pParams)
local moduleParams
if pModuleType == "CLIMATE" then
moduleParams = "climateControlData"
elseif pModuleType == "RADIO" then
moduleParams = "radioControlData"
elseif pModuleType == "SEAT" then
moduleParams = "seatControlData"
elseif pModuleType == "AUDIO" then
moduleParams = "audioControlData"
elseif pModuleType == "LIGHT" then
moduleParams = "lightControlData"
elseif pModuleType == "HMI_SETTINGS" then
moduleParams = "hmiSettingsControlData"
end
for key, value in pairs(pParams[moduleParams]) do
if type(value) ~= "table" then
if value ~= commonRC.actualInteriorDataStateOnHMI[pModuleType][moduleParams][key] then
commonRC.actualInteriorDataStateOnHMI[pModuleType][moduleParams][key] = value
end
else
if false == commonFunctions:is_table_equal(value, commonRC.actualInteriorDataStateOnHMI[pModuleType][moduleParams][key]) then
commonRC.actualInteriorDataStateOnHMI[pModuleType][moduleParams][key] = value
end
end
end
end
function commonRC.getModuleControlDataForResponse(pModuleType)
local moduleData = commonRC.actualInteriorDataStateOnHMI[pModuleType]
if moduleData.audioControlData then
moduleData.audioControlData.keepContext = nil
end
return moduleData
end
function commonRC.rpcUnsuccessResultCode(pAppId, pRPC, pRequestParams, pResult)
local mobSession = commonRC.getMobileSession(pAppId)
local cid = mobSession:SendRPC(commonRC.getAppEventName(pRPC), pRequestParams)
EXPECT_HMICALL(commonRC.getHMIEventName(pRPC))
:Times(0)
mobSession:ExpectResponse(cid, pResult)
end
local function setSyncMsgVersion()
local mobile = apiLoader.init("data/MOBILE_API.xml")
local schema = mobile.interface[next(mobile.interface)]
local ver = schema.version
for appId = 1, 3 do
local syncMsgVersion = actions.getConfigAppParams(appId).syncMsgVersion
syncMsgVersion.majorVersion = tonumber(ver.majorVersion)
syncMsgVersion.minorVersion = tonumber(ver.minorVersion)
syncMsgVersion.patchVersion = tonumber(ver.patchVersion)
end
end
setSyncMsgVersion()
return commonRC
|
local register_globalstep = minetest.register_globalstep
local get_connected_players = minetest.get_connected_players
local close_formspec = minetest.close_formspec
--[[
this is a combination of https://forum.minetest.net/viewtopic.php?t=24572 and rubenwardy's recommendation
this is an extreme hack, which disables the internal inventory system from being accessible
in cases of lag, players can still unlock their mouse, this is unacceptable
]]--
if (not editor_mode) then
minetest.register_on_joinplayer(function(player)
player:set_inventory_formspec("size[0,0]position[-100,-100]")
end)
register_globalstep(function()
for _, player in pairs(get_connected_players()) do
close_formspec(player:get_player_name(), "")
end
end)
end
|
local function intervalOrder(x,y)
if x[1] == y[1] then return x[2] < y[2] end
return x[1] < y[1]
end
local function tryMerge(x,y)
if x[2] >= y[1] then
return {x[1], math.max(x[2], y[2])}
else
return nil
end
end
local function intervalMerge(intervals)
table.sort(intervals, intervalOrder)
local i=1
while i < #intervals do
local merged = tryMerge(intervals[i], intervals[i+1])
if merged then
table.remove(intervals, i)
table.remove(intervals, i)
table.insert(intervals, i, merged)
else
i = i+1
end
end
return intervals
end
local function solve(data)
local intervals = {}
for interval in js.of(data) do
table.insert(intervals, {interval[0], interval[1]})
end
local answer = js.Array {}
for _,interval in ipairs(intervalMerge(intervals)) do
answer:push(js.Array(interval))
end
return answer
end
return solve
-- local test = {{7,16},{20,26},{1,6},{16,17},{16,20},{17,22},{7,10},{17,22},{4,5},{10,19}}
-- for _,int in ipairs(intervalMerge(test)) do
-- print(unpack(int))
-- end
|
--[[----------------------------------------------------------------------------
MIT License
Copyright (c) 2018 David F. Burns
This file is part of LrSlide.
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.
------------------------------------------------------------------------------]]
require 'strict'
local Debug = require 'Debug'.init()
local Util = require 'Util'
function newReg()
local self = {
stdoutTable = nil
}
--[[
-- parseRegOutput: an internal utility function that parses the output of reg.exe into a table.
--
-- Input expected to be reg.exe's stdout in a table of lines.
-- It expects the output to be in the form:
--
-- HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts
-- Arial (TrueType) REG_SZ arial.ttf
-- <repeat the above line 0..n times>
]]
self.parseRegOutput = function( regOutput )
local results = {}
local pair = {}
for _, line in ipairs( regOutput ) do
line = Util.trim( line )
-- Util.log( 0, 'LINE', line )
if line ~= '' and not Util.stringStarts( line, 'HKEY' ) then
pair = Util.splitString( "%s*REG_SZ%s*" , line )
if #pair > 2 then
Util.log( 0, 'ERROR: reg output not understood:', line )
else
-- Util.log( 0, pair[ 1 ], pair[ 2 ] )
results[ pair[ 1 ] ] = pair[ 2 ]
end
end
end
return results
end
--[[
-- queryValue: returns the data for a given registry value. Nil if it doesn't exist.
--
-- executes the following: reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -v SystemRoot
]]
self.queryValue = function( key, name )
local args = {}
table.insert( args, 'query' )
table.insert( args, '"' .. key .. '"' )
table.insert( args, '-v' )
table.insert( args, name )
local result = self.run( args )
if result ~= 0 then
return nil
end
local resultsTable = self.parseRegOutput( self.stdoutTable )
return resultsTable[ name ]
end
--[[
-- queryKey: returns all name/value pairs under a registry key in a Lua table.
--
-- executes the following: reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"
]]
self.queryKey = function( key )
local args = {}
table.insert( args, 'query' )
table.insert( args, '"' .. key .. '"' )
local result = self.run( args )
if result ~= 0 then
return nil
end
return self.parseRegOutput( self.stdoutTable )
end
--[[
-- run: a raw wrapper around the reg.exe utility.
]]
self.run = function( args, execOptions )
Util.log( 0, "Running reg.exe" )
Util.logpp( 0, args )
execOptions = execOptions or {}
local execResult, stdoutTable, stderrTable = Util.execAndCaptureWithArgs( 'reg', args, execOptions )
Util.log( 2, "The exit status is: " .. tostring( execResult ) );
if execResult ~= 0 then
Util.log( 0, 'ERROR. Failed to run reg.exe. Result code: ' .. execResult )
end
if #stdoutTable > 0 then
-- Util.log( 0, 'STDOUT: ')
-- Util.logpp( 0, stdoutTable )
end
if #stderrTable > 0 then
Util.log( 0, 'STDERR: ')
Util.logpp( 0, stderrTable )
end
self.stdoutTable = stdoutTable
return execResult
end
-- constructor:
return {
run = self.run,
queryValue = self.queryValue,
queryKey = self.queryKey,
}
end
|
-- Blitwizard style checker
-- modified by Roberto Perpuly
-- *----------------------*
-- Some style check options:
c_indent_spaces = 4
c_bracket_on_separate_line = false
c_allow_for_loops = false
lua_indent_spaces = 4
lua_use_semicolon = false
-- End of options.
luakeywords = { "function", "do", "end", "for", "while", "if", "then", "else", "elseif", "or", "and", "break", "return", "local" }
ckeywords = { "else", "const", "char", "int", "long", "struct", "short", "signed", "unsigned", "float", "double", "if", "switch", "case", "return", "continue", "break", "extern", "static" }
args = {...}
styleerror = false
function error_whitespace(file, nr)
styleerror = true
print("Style: line " .. file .. ":" .. nr .. " ends with whitespace(s)")
end
function error_linecommentspace(file, nr, language)
styleerror = true
local linecomment = "//"
if language ~= nil and string.lower(language) == "lua" then
linecomment = "--"
end
print("Style: line " .. file .. ":" .. nr .. " should have a whitespace between " .. linecomment .. " and the comment text following it")
end
function error_linecommentspace2(file, nr, language)
styleerror = true
local linecomment = "//"
if language ~= nil and string.lower(language) == "lua" then
linecomment = "--"
end
print("Style: line " .. file .. ":" .. nr .. " should have a whitespace between " .. linecomment .. " and the code it follows")
end
function error_shortblockcomment(file, nr)
styleerror = true
print("Style: line " .. file .. ":" .. nr .. " has a short block comment, please convert to line comment(s)")
end
function error_bracketnotonseparateline(file, nr)
styleerror = true
print("Style: line " .. file .. ":" .. nr .. " has a bracket on the same line as other code, put it isolated into the next line")
end
function error_bracketonseparateline(file, nr)
styleerror = true
print("Style: line " .. file .. ":" .. nr .. " has an isolated bracket, please put it on the previous line")
end
function error_multiplecommandsonelineafterbracket(file, nr)
styleerror = true
print("Style: line " .. file .. ":" .. nr .. " has multiple commands or statements in a single line, please put everything after { in a new line")
end
function error_multiplecommandsonelineaftersemicolon(file, nr)
styleerror = true
print("Style: line " .. file .. ":" .. nr .. " has multiple commands or statements in a line, please put everything after ; in a new line")
end
function error_expectedwhitespace(file, nr, char, after)
styleerror = true
local beforeafter = "before"
if after then
beforeafter = "after"
end
print("Style: line " .. file .. ":" .. nr .. " should have a whitespace " .. beforeafter .. " " .. char)
end
function error_tabs(file)
styleerror = true
print("Style: file " .. file .. " contains tab characters. Please use space for indentation and \\t for tabs in strings")
end
function checkcommentsandstrings(file, nr, language, line, insideblockcomment, insidestring, blockcommentlength, tabfound)
-- Enable this for debugging:
-- print("checkcommentsandstrings \"" .. line .. "\", " .. tostring(insideblockcomment) .. ", " .. tostring(insidestring) .. ", " .. tostring(blockcommentlength))
if tabfound == nil then
tabfound = false
end
-- check for tab characters:
if string.find(line, "\t", 1, true) ~= nil and not tabfound then
tabfound = true
error_tabs(file)
end
-- Get start position of block comments:
local blockcommentstart = 1/0
if language == "c" then
local v = string.find(line, "/*", 1, true)
if v ~= nil then
blockcommentstart = v
end
elseif language == "lua" then
local v = string.find(line, "--[[", 1, true)
if v ~= nil then
blockcommentstart = v
end
end
-- Get start position of line comments:
local linecommentstart = 1/0
if language == "c" then
local v = string.find(line, "//", 1, true)
if v ~= nil then
linecommentstart = v
end
elseif language == "lua" then
local v = string.find(line, "--", 1, true)
if v ~= nil then
if blockcommentstart > v then -- don't interpret as block comment
linecommentstart = v
end
end
end
-- Get the position of string start:
local linestringstart = string.find(line, "\"", 1, true)
if linestringstart == nil then
linestringstart = 1 / 0
end
-- Skip escaped string starts
while linestringstart > 1 and linestringstart < 1 / 0 do
if string.sub(line, linestringstart - 1, linestringstart - 1) == "\"" then
linestringstart = string.find(line, "\"", linestringstart + 1, true)
if linestringstart == nil then
linestringstart = 1 / 0
end
else
break
end
end
-- Check second string notation type for lua:
if language == "lua" then
local linestringstart2 = string.find(line, "[[", 1, true)
if linestringstart2 ~= nil then
if linestringstart2 < linestringstart then
linestringstart = linestringstart2
end
end
end
-- Now lets go scan for line comments, block comments, strings:
if insideblockcomment == false and insidestring == false then
if linecommentstart < linestringstart
and linecommentstart < blockcommentstart then
-- the line comment takes precedence over strings, block comments
-- check for white space following the line comment
-- if linecommentstart + #"//" <= #line then
-- local nextchar = string.sub(line, linecommentstart + #"//",
-- linecommentstart + #"//")
-- if nextchar ~= " " and nextchar ~= "\t" and
-- (language ~= "c" or nextchar ~= "/") then
-- error_linecommentspace(file, nr, language)
-- end
-- end
-- check if a space is before the line comment:
if linecommentstart > 1 then
local firstchar = string.sub(line, linecommentstart - 1, linecommentstart - 1)
if firstchar ~= " " and firstchar ~= "\t" then
error_linecommentspace2(file, nr, language)
end
end
-- return line up to the comment
if linecommentstart > 1 then
return string.sub(line, 1, linecommentstart-1), false, false, 0, tabfound
else
return "", false, false, 0, tabfound
end
end
if linestringstart < blockcommentstart then
-- string starts before block comment -> check remaining string
local remainingstring = ""
remainingstring,insideblockcomment,insidestring,blockcommentlength = checkcommentsandstrings(file, nr, language, string.sub(line, linestringstart+1), false, true, 0, tabfound)
return string.sub(line, 1, linestringstart) .. remainingstring, insideblockcomment, insidestring, 0, tabfound
end
if blockcommentstart < 1/0 then
-- we got a block comment -> check remaining string
local remainingstring = ""
remainingstring,insideblockcomment,insidestring = checkcommentsandstrings(file, nr, language, string.sub(line, blockcommentstart + #"/*"), true, false, 1, tabfound)
return string.sub(line, 1, blockcommentstart - 1) .. remainingstring, insideblockcomment, insidestring, blockcommentlength, tabfound
end
return line, false, false, 0, tabfound
else
if insidestring ~= false then
local stringend = string.find(line, "\"", 1, true)
-- deal with \" occurances:
if stringend and stringend > 1 then
if line[stringend-1] == "\\" then
-- escaped, -> ignore
local remainingstring = ""
remainingstring,insideblockcomment,insidestring = checkcommentsandstrings(file, nr, language, string.sub(line, stringend), false, true, 0, tabfound)
return string.sub(line, 1, stringend - 1) .. remainingstring, insideblockcomment, insidestring, 0, tabfound
end
end
-- deal with valid " string end:
if stringend ~= nil then
local remainingstring = ""
remainingstring,insideblockcomment,insidestring = checkcommentsandstrings(file, nr, language, string.sub(line, stringend+1), false, false, 0, tabfound)
return string.sub(line, 1, stringend) .. remainingstring, insideblockcomment, insidestring, 0
end
return line, false, true, nil, tabfound
else
local commentend = string.find(line, "*/", 1, true)
if commentend ~= nil then
-- check for short block comments (should be line comments!)
if blockcommentlength <= 2 then
error_shortblockcomment(file, nr)
end
local remainingstring = ""
remainingstring,insideblockcomment,insidestring,blockcommentlength = checkcommentsandstrings(file, nr, language, string.sub(line, commentend + #"*/"), false, false, blockcommentlength, tabfound)
return remainingstring, insideblockcomment, insidestring, blockcommentlength, tabfound
else
return "", true, false, blockcommentlength + 1, tabfound
end
end
end
end
function checkfile(file)
local n = 1
-- variables used for checkcommentsandstrings()
local insideblockcomment = false
local insidestring = false
local blockcommentlength = 0
-- variables used for char per char check
local cpc_insidestring = false
local cpc_bracketcount = 0
local cpc_ininitialiser = false
local tabfound = false
for line in io.lines(file) do
local line_without_comments = ""
-- strip line breaks
while string.ends(line, "\n") or string.ends(line, "\r") do
line = string.sub(line, 1, #line - 1)
end
-- check white space at the end of line
if string.ends(line, " ") then
error_whitespace(file, n)
end
-- check language:
local language = "lua"
-- get line without line comments, block comments
local isolatedline = ""
isolatedline,insideblockcomment,insidestring,blockcommentlength,tabfound = checkcommentsandstrings(file, n, language, line, insideblockcomment, insidestring, blockcommentlength, tabfound)
while string.ends(isolatedline, " ") do
if #isolatedline > 1 then
isolatedline = string.sub(isolatedline, 1, #isolatedline - 1)
else
isolatedline = ""
end
end
-- check if preprocessor line (C)
local cpc_preprocessorline = false
if language == "c" then
local linecopy = isolatedline
while string.starts(linecopy, " ") do
linecopy = string.sub(linecopy, 2)
end
if string.starts(linecopy, "#") then
cpc_preprocessorline = true
end
end
-- evaluate line char per char for () brackets and strings
local i = 1
while i <= #isolatedline do
if cpc_insidestring == false then
if string.sub(isolatedline, i, i) == "\"" then
-- check for " string start
-- make sure it isn't escaped:
local escaped = false
if i > 1 then
if string.sub(isolatedline, i-1, i-1) == "\\" then
escaped = true
end
end
-- unescaped string start:
if escaped == false then
cpc_insidestring = "\""
end
elseif string.sub(isolatedline, i, i) == "(" then
-- Check for opening brackets
cpc_bracketcount = cpc_bracketcount + 1
elseif string.sub(isolatedline, i, i) == ")" then
-- Check for closing brackets
cpc_bracketcount = math.max(0, cpc_bracketcount - 1)
elseif string.sub(isolatedline, i, i) == "=" and cpc_bracketcount == 0 then
-- Assignment line with possible initialiser
-- Make sure it's not an equality check of some sort:
local equality = false
if i > 1 then -- avoid !=, <= and >=, ==
local char = string.sub(isolatedline, i - 1, i - 1)
if char == "!" or char == "<" or char == ">" or char == "=" or char == "^" or char == "~" or char == "|" then
equality = true
end
end
if i < #isolatedline then -- avoid ==
if string.sub(isolatedline, i + 1, i + 1) == "=" then
equality = true
end
end
if equality == false then
-- it wasn't some equality check but a true assignment
cpc_ininitialiser = true
end
elseif (string.sub(isolatedline, i, i) == ";" and cpc_bracketcount == 0) then
-- End of command, terminate our initialiser scope
cpc_ininitialiser = false
elseif ((string.sub(isolatedline, i, i) == "{" and cpc_ininitialiser == false) or (string.sub(isolatedline, i, i) == ";" and cpc_bracketcount == 0)) then
-- Check for opening scopes followed by code
-- or terminatted lines followed by code
-- => multiple commands in one line which is bad
-- Check if there is a command in the followup:
local followedbynonspace = false
local j = i + 1
while j <= #isolatedline do
if string.sub(isolatedline, j, j) ~= " "
and string.sub(isolatedline, j, j) ~= "\t" then
followedbynonspace = true
break
end
j = j + 1
end
if followedbynonspace == true then
if string.sub(isolatedline, i, i) == "{" then
error_multiplecommandsonelineafterbracket(file, n)
else
error_multiplecommandsonelineaftersemicolon(file, n)
end
end
end
else
-- check for end of string
if i + #cpc_insidestring - 1 <= #isolatedline then
if string.sub(isolatedline, i, i + #cpc_insidestring - 1) == cpc_insidestring then
i = i + #cpc_insidestring - 1
cpc_insidestring = false
end
end
end
i = i + 1
end
-- check line for various obvious problems:
if #isolatedline > 0 then
if insidestring == false then
if language == "c" then
-- Check for bracket on separate line
if string.ends(isolatedline, "{") then
if c_bracket_on_separate_line then
-- Bracket SHALL be isolated
local linecopy = isolatedline
while string.starts(linecopy, " ") do
linecopy = string.sub(linecopy, 2)
end
if linecopy ~= "{" then
error_bracketnotonseparateline(file, n)
end
end
end
end
end
end
n = n + 1
end
end
function string.starts(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
function string.ends(String,End)
return End=='' or string.sub(String,-string.len(End))==End
end
|
--Copyright (C) 2009 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
object_creature_player_shared_bothan_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_bothan_female.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/bth_f.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_human_f.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 1,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:bothan",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.72, 0.81},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 5,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 491942670,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_bothan_female, "object/creature/player/shared_bothan_female.iff")
object_creature_player_shared_bothan_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_bothan_male.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/bth_m.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_human_m.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 0,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:bothan",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.75, 0.83},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 5,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 1542946611,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_bothan_male, "object/creature/player/shared_bothan_male.iff")
object_creature_player_shared_human_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_human_female.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/hum_f.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_human_f.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 1,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:human",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.83, 1.08},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 0,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 4294949865,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_human_female, "object/creature/player/shared_human_female.iff")
object_creature_player_shared_human_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_human_male.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/hum_m.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_human_m.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 0,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:human",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.89, 1.11},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 0,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 2937962913,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_human_male, "object/creature/player/shared_human_male.iff")
object_creature_player_shared_ithorian_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_ithorian_female.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/ith_f.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_ithorian_f.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 1,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:ithorian",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.89, 1.03},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 33,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 3017834515,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_ithorian_female, "object/creature/player/shared_ithorian_female.iff")
object_creature_player_shared_ithorian_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_ithorian_male.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/ith_m.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_ithorian_m.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 0,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:ithorian",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.92, 1.06},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 33,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 951764932,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_ithorian_male, "object/creature/player/shared_ithorian_male.iff")
object_creature_player_shared_moncal_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_moncal_female.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/mon_f.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_moncal_f.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 1,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:moncalamari",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.86, 0.94},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 3,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 2553266142,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_moncal_female, "object/creature/player/shared_moncal_female.iff")
object_creature_player_shared_moncal_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_moncal_male.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/mon_m.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_moncal_m.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 0,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:moncalamari",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.89, 1},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 3,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 3116914088,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_moncal_male, "object/creature/player/shared_moncal_male.iff")
object_creature_player_shared_rodian_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_rodian_female.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/rod_f.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_rodian_f.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 1,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:rodian",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.78, 0.92},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 1,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 3261342811,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_rodian_female, "object/creature/player/shared_rodian_female.iff")
object_creature_player_shared_rodian_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_rodian_male.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/rod_m.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_rodian_m.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 0,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:rodian",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.81, 0.94},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 1,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 200920476,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_rodian_male, "object/creature/player/shared_rodian_male.iff")
object_creature_player_shared_sullustan_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_sullustan_female.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/sul_f.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_sullustan_f.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 1,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:sullustan",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.89, 1.03},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 49,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 359871514,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_sullustan_female, "object/creature/player/shared_sullustan_female.iff")
object_creature_player_shared_sullustan_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_sullustan_male.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/sul_m.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_sullustan_m.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 0,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:sullustan",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.92, 1.06},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 49,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 194222500,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_sullustan_male, "object/creature/player/shared_sullustan_male.iff")
object_creature_player_shared_trandoshan_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_trandoshan_female.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/trn_f.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_trandoshan_f.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 1,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:trandoshan",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {1, 1.22},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 2,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 406594758,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_trandoshan_female, "object/creature/player/shared_trandoshan_female.iff")
object_creature_player_shared_trandoshan_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_trandoshan_male.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/trn_m.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_trandoshan_m.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 0,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:trandoshan",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {1.03, 1.25},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 2,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 1355045775,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_trandoshan_male, "object/creature/player/shared_trandoshan_male.iff")
object_creature_player_shared_twilek_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_twilek_female.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/twk_f.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_twilek_f.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 1,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:twilek",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.89, 1.08},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 6,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 2224509660,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_twilek_female, "object/creature/player/shared_twilek_female.iff")
object_creature_player_shared_twilek_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_twilek_male.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/twk_m.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_twilek_m.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 0,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:twilek",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.92, 1.11},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 6,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 4068532859,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_twilek_male, "object/creature/player/shared_twilek_male.iff")
object_creature_player_shared_wookiee_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_wookiee_female.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/wke_f.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_wookiee_f.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {{"/private/index_texture_1", "/shared_owner/index_texture_1"}},
detailedDescription = "",
gameObjectType = 1025,
gender = 1,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:wookiee",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {1.08, 1.25},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 4,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 229336546,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_wookiee_female, "object/creature/player/shared_wookiee_female.iff")
object_creature_player_shared_wookiee_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_wookiee_male.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/wke_m.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_wookiee_m.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {{"/private/index_texture_1", "/shared_owner/index_texture_1"}},
detailedDescription = "",
gameObjectType = 1025,
gender = 0,
locationReservationRadius = 0,
lookAtText = "@:e",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:wookiee",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {1.11, 1.28},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 4,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 90470685,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_wookiee_male, "object/creature/player/shared_wookiee_male.iff")
object_creature_player_shared_zabrak_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_zabrak_female.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/zab_f.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_zabrak_f.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 1,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:zabrak",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.89, 1.03},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 7,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 2850250749,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_zabrak_female, "object/creature/player/shared_zabrak_female.iff")
object_creature_player_shared_zabrak_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_zabrak_male.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
acceleration = {36,12},
animationMapFilename = "all_male.map",
appearanceFilename = "appearance/zab_m.sat",
arrangementDescriptorFilename = "abstract/slot/arrangement/player.iff",
cameraHeight = 0,
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/player/client_shared_player_zabrak_m.cdf",
clientGameObjectType = 1025,
collisionActionBlockFlags = 0,
collisionActionFlags = 255,
collisionActionPassFlags = 0,
collisionHeight = 1.8,
collisionLength = 1.5,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
collisionOffsetX = 0,
collisionOffsetZ = 0,
collisionRadius = 0.5,
containerType = 1,
containerVolumeLimit = 0,
customizationVariableMapping = {},
detailedDescription = "",
gameObjectType = 1025,
gender = 0,
locationReservationRadius = 0,
lookAtText = "",
movementDatatable = "datatables/movement/movement_human.iff",
niche = 1,
noBuildRadius = 0,
objectName = "@species:zabrak",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
postureAlignToTerrain = {0,0,1,0,0,0,0,0,0,0,0,0,0,1,1},
race = 0,
rangedIntCustomizationVariables = {},
scale = {0.92, 1.06},
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slopeModAngle = 26,
slopeModPercent = 0.0125,
slotDescriptorFilename = "abstract/slot/descriptor/player.iff",
snapToTerrain = 1,
socketDestinations = {},
species = 7,
speed = {5.376,1.549},
stepHeight = 0.5,
structureFootprintFileName = "",
surfaceType = 0,
swimHeight = 1,
targetable = 1,
totalCellNumber = 0,
turnRate = {720,720},
useStructureFootprintOutline = 0,
warpTolerance = 17,
waterModPercent = 0.75,
clientObjectCRC = 3791955286,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/creature/base/shared_base_creature.iff", "object/creature/player/base/shared_base_player.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_creature_player_shared_zabrak_male, "object/creature/player/shared_zabrak_male.iff")
--Added Races
--Hutt male
object_creature_player_shared_hutt_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_hutt_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_hutt_male, "object/creature/player/shared_hutt_male.iff")
--Hutt female
object_creature_player_shared_hutt_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_hutt_female.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_hutt_female, "object/creature/player/shared_hutt_female.iff")
--Nautolan male
object_creature_player_shared_nautolan_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_nautolan_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_nautolan_male, "object/creature/player/shared_nautolan_male.iff")
--Togruta female
object_creature_player_shared_togruta_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_togruta_female.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_togruta_female, "object/creature/player/shared_togruta_female.iff")
--Chiss female
object_creature_player_shared_chiss_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_chiss_female.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_chiss_female, "object/creature/player/shared_chiss_female.iff")
--Chiss male
object_creature_player_shared_chiss_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_chiss_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_chiss_male, "object/creature/player/shared_chiss_male.iff")
--Devaronian male
object_creature_player_shared_devaronian_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_devaronian_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_devaronian_male, "object/creature/player/shared_devaronian_male.iff")
--Gran male
object_creature_player_shared_gran_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_gran_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_gran_male, "object/creature/player/shared_gran_male.iff")
--Ishi Tib male
object_creature_player_shared_ishi_tib_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_ishi_tib_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_ishi_tib_male, "object/creature/player/shared_ishi_tib_male.iff")
--Nightsister female
object_creature_player_shared_nightsister_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_nightsister_female.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_nightsister_female, "object/creature/player/shared_nightsister_female.iff")
--Nikto male
object_creature_player_shared_nikto_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_nikto_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_nikto_male, "object/creature/player/shared_nikto_male.iff")
--Quarren male
object_creature_player_shared_quarren_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_quarren_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_quarren_male, "object/creature/player/shared_quarren_male.iff")
--SMC female
object_creature_player_shared_smc_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_smc_female.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_smc_female, "object/creature/player/shared_smc_female.iff")
--Weequay male
object_creature_player_shared_weequay_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_weequay_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_weequay_male, "object/creature/player/shared_weequay_male.iff")
--Aqualish female
object_creature_player_shared_aqualish_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_aqualish_female.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_aqualish_female, "object/creature/player/shared_aqualish_female.iff")
--Aqualish male
object_creature_player_shared_aqualish_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_aqualish_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_aqualish_male, "object/creature/player/shared_aqualish_male.iff")
--Bith female
object_creature_player_shared_bith_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_bith_female.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_bith_female, "object/creature/player/shared_bith_female.iff")
--Bith male
object_creature_player_shared_bith_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_bith_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_bith_male, "object/creature/player/shared_bith_male.iff")
--Gotal male
object_creature_player_shared_gotal_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_gotal_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_gotal_male, "object/creature/player/shared_gotal_male.iff")
--Talz male
object_creature_player_shared_talz_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_talz_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_talz_male, "object/creature/player/shared_talz_male.iff")
--Abyssin male
object_creature_player_shared_abyssin_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_abyssin_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_abyssin_male, "object/creature/player/shared_abyssin_male.iff")
--Arcona male
object_creature_player_shared_arcona_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_arcona_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_arcona_male, "object/creature/player/shared_arcona_male.iff")
--Cerean male
object_creature_player_shared_cerean_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_cerean_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_cerean_male, "object/creature/player/shared_cerean_male.iff")
--Duros male
object_creature_player_shared_duros_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_duros_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_duros_male, "object/creature/player/shared_duros_male.iff")
--Gungan male
object_creature_player_shared_gungan_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_gungan_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_gungan_male, "object/creature/player/shared_gungan_male.iff")
--Iktotchi male
object_creature_player_shared_iktotchi_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_iktotchi_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_iktotchi_male, "object/creature/player/shared_iktotchi_male.iff")
--Jenet male
object_creature_player_shared_jenet_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_jenet_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_jenet_male, "object/creature/player/shared_jenet_male.iff")
--Kel Dor male
object_creature_player_shared_kel_dor_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_kel_dor_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_kel_dor_male, "object/creature/player/shared_kel_dor_male.iff")
--Kubaz male
object_creature_player_shared_kubaz_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_kubaz_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_kubaz_male, "object/creature/player/shared_kubaz_male.iff")
--Sanyassan male
object_creature_player_shared_sanyassan_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_sanyassan_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_sanyassan_male, "object/creature/player/shared_sanyassan_male.iff")
--Sanyassan female
object_creature_player_shared_sanyassan_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_sanyassan_female.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_sanyassan_female, "object/creature/player/shared_sanyassan_female.iff")
--Chadra Fan female
object_creature_player_shared_chadra_fan_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_chadra_fan_female.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_chadra_fan_female, "object/creature/player/shared_chadra_fan_female.iff")
--Chadra Fan male
object_creature_player_shared_chadra_fan_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_chadra_fan_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_chadra_fan_male, "object/creature/player/shared_chadra_fan_male.iff")
--Droid male
object_creature_player_shared_droid_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_droid_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_droid_male, "object/creature/player/shared_droid_male.iff")
--Dug male
object_creature_player_shared_dug_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_dug_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_dug_male, "object/creature/player/shared_dug_male.iff")
--Ewok male
object_creature_player_shared_ewok_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_ewok_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_ewok_male, "object/creature/player/shared_ewok_male.iff")
--Ewok female
object_creature_player_shared_ewok_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_ewok_female.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_ewok_female, "object/creature/player/shared_ewok_female.iff")
--Feeorin male
object_creature_player_shared_feeorin_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_feeorin_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_feeorin_male, "object/creature/player/shared_feeorin_male.iff")
--Geonosian male
object_creature_player_shared_geonosian_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_geonosian_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_geonosian_male, "object/creature/player/shared_geonosian_male.iff")
--Ortolan male
object_creature_player_shared_ortolan_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_ortolan_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_ortolan_male, "object/creature/player/shared_ortolan_male.iff")
--Togorian male
object_creature_player_shared_togorian_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_togorian_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_togorian_male, "object/creature/player/shared_togorian_male.iff")
--Toydarian male
object_creature_player_shared_toydarian_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_toydarian_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_toydarian_male, "object/creature/player/shared_toydarian_male.iff")
--mirialan female
object_creature_player_shared_mirialan_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_mirialan_female.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_mirialan_female, "object/creature/player/shared_mirialan_female.iff")
--mirialan male
object_creature_player_shared_mirialan_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_mirialan_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_mirialan_male, "object/creature/player/shared_mirialan_male.iff")
--zeltron female
object_creature_player_shared_zeltron_female = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_zeltron_female.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_zeltron_female, "object/creature/player/shared_zeltron_female.iff")
--zeltron male
object_creature_player_shared_zeltron_male = SharedCreatureObjectTemplate:new {
clientTemplateFileName = "object/creature/player/shared_zeltron_male.iff"}
ObjectTemplates:addClientTemplate(object_creature_player_shared_zeltron_male, "object/creature/player/shared_zeltron_male.iff")
|
mrequire "game/costumes/costumes"
|
local M = {}
M.config = function()
local status_ok, colorizer = pcall(require, "colorizer")
if not status_ok then
return
end
-- https://github.com/norcalli/nvim-colorizer.lua#customization
local files = { "*" }
local options = {
RGB = true,
RRGGBB = true,
RRGGBBAA = true,
rgb_fn = true,
hsl_fn = true,
css = true,
css_fn = true,
}
colorizer.config(files, options)
end
return M
|
require("libosgLua")
function showInfo(instance)
local c = osgLua.getTypeInfo(instance)
if c then
print("name = ",c.name)
for i,v in ipairs(c.constructors) do
print(string.format("\tconstructor(%2d) %s",i,v))
end
for i,v in ipairs(c.methods) do
print(string.format("\tmethod(%2d) %s",i,v))
end
else
print(instance.." ** not found **")
end
end
osgLua.loadWrapper("osg")
osgLua.loadWrapper("osgText")
osgLua.loadWrapper("osgGA")
osgLua.loadWrapper("osgProducer")
types = osgLua.getTypes()
for t,d in ipairs( types ) do
showInfo(d)
end
|
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')
function ENT:Initialize()
self.BaseClass.Initialize(self)
self:PhysicsInit(SOLID_NONE)
self:SetMoveType(MOVETYPE_NONE)
self:SetSolid(SOLID_NONE)
self.sbenvironment.temperature2 = 0
self.sbenvironment.temperature3 = 0
self:SetNotSolid(true)
self:DrawShadow(false)
if CAF then
self.caf = self.caf or {}
self.caf.custom = self.caf.custom or {}
self.caf.custom.canreceivedamage = false
self.caf.custom.canreceiveheatdamage = false
end
end
function ENT:GetTemperature(ent)
if not ent then return end
local pos = ent:GetPos()
local entpos = ent:GetPos()
local SunAngle = (entpos - pos)
SunAngle:Normalize()
local startpos = (entpos - (SunAngle * 4096))
local trace = {}
trace.start = startpos
trace.endpos = entpos + Vector(0, 0, 30)
local tr = util.TraceLine(trace)
if (tr.Hit) then
if (tr == ent) then
if (ent:IsPlayer()) then
if (ent:Health() > 0) then
ent:TakeDamage(5, 0)
ent:EmitSound("HL2Player.BurnPain")
end
end
end
end
local dist = pos:Distance(self:GetPos())
if dist < self:GetSize() / 6 then
return self.sbenvironment.temperature
elseif dist < self:GetSize() * 1 / 3 then
return self.sbenvironment.temperature2
elseif dist < self:GetSize() * 1 / 2 then
return self.sbenvironment.temperature3
elseif dist < self:GetSize() * 2 / 3 then
return self.sbenvironment.temperature3 / 2
elseif self.sbenvironment.temperature3 / 4 <= 14 then --Check that it isn't colder then Space, else return Space temperature
return 14
end
return self.sbenvironment.temperature3 / 4 --All other checks failed, player is the farest away from the star, but temp is still warmer then space, return that temperature
end
function ENT:GetPriority()
return 2
end
local function SendSunBeam(ent)
for k, ply in pairs(player.GetAll()) do
umsg.Start("AddStar", ply)
--umsg.Entity( ent ) --planet.num
umsg.Short(ent:EntIndex())
umsg.Vector(ent:GetPos()) --planet.num
umsg.Float(ent.sbenvironment.size)
umsg.End()
end
end
function ENT:CreateEnvironment(radius, temp1, temp2, temp3, name)
if radius and type(radius) == "number" then
if radius < 0 then
radius = 0
end
self.sbenvironment.size = radius
end
if temp2 and type(temp2) == "number" then
if temp2 < 0 then
temp2 = 0
end
self.sbenvironment.temperature2 = temp2
end
if temp3 and type(temp3) == "number" then
if temp3 < 0 then
temp3 = 0
end
self.sbenvironment.temperature3 = temp3
end
self.BaseClass.CreateEnvironment(self, 0, 100, temp1, 0, 0, 100, 0, name)
SendSunBeam(self)
end
function ENT:UpdateEnvironment(radius, temp1, temp2, temp3)
if radius and type(radius) == "number" then
self:UpdateSize(self.sbenvironment.size, radius)
end
if temp1 and type(temp1) == "number" then
self.sbenvironment.temperature = temp1
end
if temp2 and type(temp2) == "number" then
self.sbenvironment.temperature2 = temp2
end
if temp3 and type(temp3) == "number" then
self.sbenvironment.temperature3 = temp3
end
SendSunBeam(self)
end
function ENT:IsStar()
return true
end
function ENT:CanTool()
return false
end
function ENT:GravGunPunt()
return false
end
function ENT:GravGunPickupAllowed()
return false
end
function ENT:Remove()
self.BaseClass.Remove(self)
table.remove(TrueSun, self:GetPos())
end
|
local mod = get_mod("rwaon_talents")
-- Hagbane Bow
------------------------------------------------------------------------------
for _, weapon in ipairs{
"shortbow_hagbane_template_1",
} do
local weapon_template = Weapons[weapon]
local action_one = weapon_template.actions.action_one
local action_two = weapon_template.actions.action_two
change_chain_actions(action_one, "default", 1, {
sub_action = "default",
start_time = 0.2, -- 0
action = "action_wield",
input = "action_wield"
})
change_chain_actions(action_one, "shoot_charged", 2, {
sub_action = "default",
start_time = 0.5, -- 0.66
action = "action_wield",
input = "action_wield"
})
weapon_template.dodge_count = 5 --6
end
-- Dot Changes
--[[BuffTemplates.arrow_poison_dot = {
buffs = {
{
duration = 12, -- 3
name = "arrow poison dot",
start_flow_event = "poisoned",
end_flow_event = "poisoned_end",
death_flow_event = "poisoned_death",
remove_buff_func = "remove_dot_damage",
apply_buff_func = "start_dot_damage",
time_between_dot_damages = 2.4, -- 0.6
damage_profile = "poison_direct",
update_func = "apply_dot_damage",
reapply_buff_func = "reapply_dot_damage"
}
}
}
BuffTemplates.aoe_poison_dot = {
buffs = {
{
duration = 6, -- 3
name = "aoe poison dot",
start_flow_event = "poisoned",
end_flow_event = "poisoned_end",
death_flow_event = "poisoned_death",
remove_buff_func = "remove_dot_damage",
apply_buff_func = "start_dot_damage",
time_between_dot_damages = 1.5, -- 0.75
damage_profile = "poison",
update_func = "apply_dot_damage",
reapply_buff_func = "reapply_dot_damage"
}
}
}]]
|
Minigolf.HideDefaultHUDElements = {
CHudHealth = true,
CHudBattery = true,
CHudAmmo = true,
CHudDamageIndicator = true,
CHudWeaponSelection = true,
CHudCrosshair = true
};
hook.Add("HUDShouldDraw", "Minigolf.HideDefaultHUD", function(name)
if(Minigolf.HideDefaultHUDElements[name]) then
return false
end
end);
hook.Add("SpawnMenuEnabled", "Minigolf.DisableSpawnMenu", function()
return false
end)
hook.Add("ContextMenuOpen", "Minigolf.DisableContextMenu", function()
return false
end)
hook.Add("PreDrawHalos", "Minigolf.AddHalosAroundTeamMembers", function()
local teamID = LocalPlayer():Team()
halo.Add(team.GetPlayers(teamID), team.GetColor(teamID), 5, 5, 2, true, true)
end)
-- Override drawing the death notices
function GM:DrawDeathNotice(x, y)
end
|
local M = {}
local random = math.random
-- Tile bitmask references.
-- NB! Tiles with more than one variant are listed in tables.
local frame = {
[0] = 1,
[1] = 1,
[2] = 35,
[3] = 35,
[4] = 1,
[5] = 1,
[6] = 35,
[7] = 35,
[8] = 47,
[9] = 47,
[10] = 33,
[11] = 49,
[12] = 47,
[13] = 47,
[14] = 33,
[15] = 49,
[16] = 2,
[17] = 2,
[18] = 43,
[19] = 43,
[20] = 2,
[21] = 2,
[22] = 48,
[23] = 48,
[24] = 40,
[25] = 40,
[26] = 46,
[27] = 45,
[28] = 40,
[29] = 40,
[30] = 44,
[31] = 25,
[32] = 1,
[33] = 1,
[34] = 35,
[35] = 35,
[36] = 1,
[37] = 1,
[38] = 35,
[39] = 35,
[40] = 47,
[41] = 47,
[42] = 33,
[43] = 49,
[44] = 47,
[45] = 47,
[46] = 33,
[47] = 49,
[48] = 2,
[49] = 2,
[50] = 43,
[51] = 43,
[52] = 2,
[53] = 2,
[54] = 48,
[55] = 48,
[56] = 40,
[57] = 40,
[58] = 46,
[59] = 45,
[60] = 40,
[61] = 40,
[62] = 44,
[63] = 25,
[64] = 8,
[65] = 8,
[66] = 34,
[67] = 34,
[68] = 8,
[69] = 8,
[70] = 34,
[71] = 34,
[72] = 7,
[73] = 7,
[74] = 28,
[75] = 21,
[76] = 7,
[77] = 7,
[78] = 28,
[79] = 21,
[80] = 32,
[81] = 32,
[82] = 15,
[83] = 15,
[84] = 32,
[85] = 32,
[86] = 36,
[87] = 36,
[88] = 3,
[89] = 3,
[90] = 39,
[91] = 27,
[92] = 3,
[93] = 3,
[94] = 16,
[95] = 26,
[96] = 8,
[97] = 8,
[98] = 34,
[99] = 34,
[100] = 8,
[101] = 8,
[102] = 34,
[103] = 34,
[104] = 42,
[105] = 42,
[106] = 14,
[107] = 31,
[108] = 42,
[109] = 42,
[110] = 14,
[111] = 31,
[112] = 32,
[113] = 32,
[114] = 15,
[115] = 15,
[116] = 32,
[117] = 32,
[118] = 36,
[119] = 36,
[120] = 6,
[121] = 6,
[122] = 10,
[123] = 38,
[124] = 6,
[125] = 6,
[126] = 24,
[127] = 20,
[128] = 1,
[129] = 1,
[130] = 35,
[131] = 35,
[132] = 1,
[133] = 1,
[134] = 35,
[135] = 35,
[136] = 47,
[137] = 47,
[138] = 33,
[139] = 49,
[140] = 47,
[141] = 47,
[142] = 33,
[143] = 49,
[144] = 2,
[145] = 2,
[146] = 43,
[147] = 43,
[148] = 2,
[149] = 2,
[150] = 48,
[151] = 48,
[152] = 40,
[153] = 40,
[154] = 46,
[155] = 45,
[156] = 40,
[157] = 40,
[158] = 44,
[159] = 25,
[160] = 1,
[161] = 1,
[162] = 35,
[163] = 35,
[164] = 1,
[165] = 1,
[166] = 35,
[167] = 35,
[168] = 47,
[169] = 47,
[170] = 33,
[171] = 49,
[172] = 47,
[173] = 47,
[174] = 33,
[175] = 49,
[176] = 2,
[177] = 2,
[178] = 43,
[179] = 43,
[180] = 2,
[181] = 2,
[182] = 48,
[183] = 48,
[184] = 40,
[185] = 40,
[186] = 46,
[187] = 45,
[188] = 40,
[189] = 40,
[190] = 44,
[191] = 25,
[192] = 8,
[193] = 8,
[194] = 34,
[195] = 34,
[196] = 8,
[197] = 8,
[198] = 34,
[199] = 34,
[200] = 7,
[201] = 7,
[202] = 28,
[203] = 21,
[204] = 7,
[205] = 7,
[206] = 28,
[207] = 21,
[208] = 9,
[209] = 9,
[210] = 22,
[211] = 22,
[212] = 9,
[213] = 9,
[214] = 29,
[215] = 29,
[216] = 4,
[217] = 4,
[218] = 41,
[219] = 17,
[220] = 4,
[221] = 4,
[222] = 11,
[223] = 37,
[224] = 8,
[225] = 8,
[226] = 34,
[227] = 34,
[228] = 8,
[229] = 8,
[230] = 34,
[231] = 34,
[232] = 42,
[233] = 42,
[234] = 14,
[235] = 31,
[236] = 42,
[237] = 42,
[238] = 14,
[239] = 31,
[240] = 9,
[241] = 9,
[242] = 22,
[243] = 22,
[244] = 9,
[245] = 9,
[246] = 29,
[247] = 29,
[248] = 5,
[249] = 5,
[250] = 23,
[251] = 13,
[252] = 5,
[253] = 5,
[254] = 18,
[255] = { 12, 19, 30 },
}
-- Basic parameters and references required by the module.
local map, maxRows, maxColumns
function M.init( m, r, c )
map, maxRows, maxColumns = m, r, c
end
-- Calculate a bitmask value for a given cell and retrieves the corresponding frame id.
function M.getFrameID( row, column, currentFrame )
-- Prevent modifying the outer edges of the game map.
if row > 0 and row < maxRows+1 and column > 0 and column < maxColumns+1 then
local bitmask = 0
if map[row-1][column-1] ~= 0 then
bitmask = bitmask + 1
end
if map[row-1][column] ~= 0 then
bitmask = bitmask + 2
end
if map[row-1][column+1] ~= 0 then
bitmask = bitmask + 4
end
if map[row][column-1] ~= 0 then
bitmask = bitmask + 8
end
if map[row][column+1] ~= 0 then
bitmask = bitmask + 16
end
if map[row+1][column-1] ~= 0 then
bitmask = bitmask + 32
end
if map[row+1][column] ~= 0 then
bitmask = bitmask + 64
end
if map[row+1][column+1] ~= 0 then
bitmask = bitmask + 128
end
local id = frame[bitmask]
if type( id ) == "table" then
-- If the game is trying to update an existing tile,
-- then don't return the same frame id to the game.
local t = frame[bitmask][random(1,#id)]
if currentFrame then
while t == currentFrame do
t = frame[bitmask][random(1,#id)]
end
end
id = t
end
return id, bitmask
end
end
return M
|
--------------------------------
-- @module AssetsManagerEx
-- @extend Ref
-- @parent_module cc
---@class cc.AssetsManagerEx:cc.Ref
local AssetsManagerEx = {}
cc.AssetsManagerEx = AssetsManagerEx
--------------------------------
--- @brief Gets the current update state.
---@return number
function AssetsManagerEx:getState()
end
--------------------------------
--- @brief Function for retrieving the max concurrent task count
---@return number
function AssetsManagerEx:getMaxConcurrentTask()
end
--------------------------------
--- @brief Check out if there is a new version of manifest.
--- You may use this method before updating, then let user determine whether
--- he wants to update resources.
---@return cc.AssetsManagerEx
function AssetsManagerEx:checkUpdate()
end
--------------------------------
--- @brief Set the verification function for checking whether downloaded asset is correct, e.g. using md5 verification
--- param callback The verify callback function
---@param callback fun(arg0:std::string&,arg1:cc.ManifestAsset):boolean
---@return cc.AssetsManagerEx
function AssetsManagerEx:setVerifyCallback(callback)
end
--------------------------------
--- @brief Gets storage path.
---@return string
function AssetsManagerEx:getStoragePath()
end
--------------------------------
--- @brief Update with the current local manifest.
---@return cc.AssetsManagerEx
function AssetsManagerEx:update()
end
--------------------------------
--- @brief Set the handle function for comparing manifests versions
--- param handle The compare function
---@param handle fun(arg0:std::string&,arg1:std::string&):number
---@return cc.AssetsManagerEx
function AssetsManagerEx:setVersionCompareHandle(handle)
end
--------------------------------
--- @brief Function for setting the max concurrent task count
---@param max number
---@return cc.AssetsManagerEx
function AssetsManagerEx:setMaxConcurrentTask(max)
end
--------------------------------
--- @brief Function for retrieving the local manifest object
---@return cc.Manifest
function AssetsManagerEx:getLocalManifest()
end
--------------------------------
--- @brief Function for retrieving the remote manifest object
---@return cc.Manifest
function AssetsManagerEx:getRemoteManifest()
end
--------------------------------
--- @brief Reupdate all failed assets under the current AssetsManagerEx context
---@return cc.AssetsManagerEx
function AssetsManagerEx:downloadFailedAssets()
end
--------------------------------
--- @brief Create function for creating a new AssetsManagerEx
--- param manifestUrl The url for the local manifest file
--- param storagePath The storage path for downloaded assets
--- warning The cached manifest in your storage path have higher priority and will be searched first,
--- only if it doesn't exist, AssetsManagerEx will use the given manifestUrl.
---@param manifestUrl string
---@param storagePath string
---@return cc.AssetsManagerEx
function AssetsManagerEx:create(manifestUrl, storagePath)
end
--------------------------------
---
---@param manifestUrl string
---@param storagePath string
---@return cc.AssetsManagerEx
function AssetsManagerEx:AssetsManagerEx(manifestUrl, storagePath)
end
return nil
|
local fn = vim.fn
local execute = vim.api.nvim_command
local function packer_init()
local install_path = fn.stdpath("data") .. "/site/pack/packer/start/packer.nvim"
if fn.empty(fn.glob(install_path)) > 0 then
execute("!git clone https://github.com/wbthomason/packer.nvim " .. install_path)
end
vim.cmd("packadd! packer.nvim")
vim.cmd("autocmd BufWritePost plugins.lua PackerCompile")
end
packer_init()
-- general
require("config.autocmd").setup()
require("config").setup()
require("plugins").setup()
require("config.keymappings").setup()
-- ext
require("ext").setup()
-- lsp config
require("lsp").setup()
require("ext.cmp").setup()
-- code formatter
require("ext.formatters").setup()
-- lsp server
require("lsp.bash").setup()
require("lsp.cc").setup()
require("lsp.cmake").setup()
require("lsp.css").setup()
require("lsp.docker").setup()
require("lsp.go").setup()
require("lsp.html").setup()
require("lsp.python").setup()
require("lsp.rust").setup()
require("lsp.tsserver").setup()
require("lsp.vim").setup()
require("lsp.vue").setup()
require("lsp.yaml").setup()
require("lsp.sql").setup()
require("lsp.tex").setup()
require("lsp.lua").setup()
require("lsp.tailwindcss").setup()
require("lsp.emmet").setup()
require("lsp.solidity").setup()
-- debugger
require("debugger").setup()
|
local PersonInfo = class('PersonInfo', TextPanel)
return PersonInfo
|
--[[
This script has only been used by me to make JCR6
able to package all different kind of Bubble engines
into a JCR6 file that the Bubble_Builder can use to
tie the correct engine to the Bubble projects
Please note that some variables may need to be changed
if you intend to use this yourself.
]]
local sprintf = string.format
bubbledir = "E:/Projects/Applications/VisualStudio/Bubble"
output = bubbledir.."/Build/bin/Release/Engines.jcr"
JLS.SetJCR6OutputFile(output)
AddComment("Bubble","Contains all Bubble engines. The builder uses this file to link the correct engine to each project")
function Plus(scandir,name)
print("/n/nEngine: "..name)
d = GetDir(scandir)
for _,f in ipairs(d) do
print("Adding: "..f.." to "..name)
Add(sprintf("%s/%s",scandir,f),sprintf("Engine_bin/%s/%s",name,f),{ Author="Jeroen P. Broks", Notes="GPL3", Storage='lzma' })
end
end
Plus(bubbledir.."/CLI/bin/Release","CLI")
Plus(bubbledir.."/MonoGame/src/bin/DesktopGL/AnyCPU/Release","MonoGame")
--Plus(bubbledir.."/NALA/bin/DesktopGL/AnyCPU/Release","NALA")
Plus(bubbledir.."/NALA/DirectX/NALA_DX/bin/Windows/x86/Release","NALA")
|
LIBRARY.Name = "Notifications"
LIBRARY.Author = "IZED"
local rpc = import("libs/rpc")
local utils = import("libs/utils")
local event = import("libs/event")
local cfg = import("config/notifications")
local counter = 0
local delayedCounter = 0
local list = {}
local yPos = 0
local function ThrowHint( options )
if not options then options = {} end
local color = options.color or Color(255, 255, 255)
local text = options.text or ""
local _counter = counter
if list[_counter] then list[_counter]:Remove() list[_counter] = nil end
local hint = vgui.Create("DPanel")
if options.big then
hint:SetPos( ScrW()*0.5 - utils.TextWidth("SoulMission80", text)*0.5,ScrH() * 0.2 + yPos )
hint:SetSize(utils.TextWidth("SoulMission80", text), utils.TextHeight("SoulMission80", text))
else
hint:SetPos( ScrW() - utils.TextWidth(cfg.Font, text) - 20,ScrH() / 8 * 6 + yPos )
hint:SetSize(utils.TextWidth(cfg.Font, text), utils.TextHeight(cfg.Font, text))
end
hint:SetDrawBackground(false)
local label = vgui.Create( "ZOutlinedLabel", hint )
label:SetPos( 0,0 )
label:SetText( text )
if big then
label:SetFont( "SoulMission80" )
else
label:SetFont( cfg.Font )
end
label:SetColor( color )
list[_counter] = {
hint = hint,
text = text,
color = color,
big = options.big
}
if options.chat then
chat.AddText(color, text )
else
MsgC(color, text, "\n")
end
local th = utils.TextHeight(cfg.Font, "I")
if options.big then
th = utils.TextHeight("SoulMission60", "I")
end
if yPos == 0 then
yPos = th
elseif yPos == th then
yPos = 2 * th
elseif yPos == 2 * th then
yPos = 3 * th
elseif yPos == 3 * th then
yPos = 4 * th
elseif yPos == 4 * th then
yPos = 5 * th
else
yPos = 0
end
timer.Create("Notification:".._counter, options.duration or 4, 1, function()
list[_counter].moveLeft = true
end)
counter = _counter
surface.PlaySound( "ambient/water/drip"..math.random(1, 4)..".wav" )
end
event.Observe("Tick"):subscribe(function()
for k,v in pairs(list) do
if v.hint and v.text and v.moveLeft then
local x,y = v.hint:GetPos()
v.hint:SetPos(x-5,y)
if x <= ScrW() - utils.TextWidth(cfg.Font, v.text) - 50 then
v.moveLeft = false
v.moveRight = true
end
elseif v.hint and v.text and v.moveRight then
local x,y = v.hint:GetPos()
if list[k].big then
v.hint:SetPos(x+80,y)
else
v.hint:SetPos(x+50,y)
end
if x >= ScrW() then
list[k].hint:Remove()
list[k].hint = nil
list[k] = nil
end
end
end
end)
COMPONENT.Create = function(options)
utils.PrintTable(options)
timer.Create( "DelayedHint:" .. delayedCounter, delay or 0, 1, function()
ThrowHint(options)
end)
delayedCounter = delayedCounter + 1
end
rpc.Observe("notifications.Create"):subscribe(COMPONENT.Create)
|
-- only alter this file if it's named "custom.recipes.lua"
-- alter the recipes as you please and delete / comment out
-- the recipes you don't want to be available in the game
-- the original versions are in "default/recipes.lua"
return {
["tpad:tpad"] = {
{'group:wood', 'default:bronze_ingot', 'group:wood'},
{'default:bronze_ingot', 'group:wood', 'default:bronze_ingot'},
{'group:wood', 'default:bronze_ingot', 'group:wood'},
},
}
|
test = require 'u-test'
common = require 'common'
local function VerifySuccess(hr)
SetCheckHR(1)
if hr ~= 0 then
test.equal(hr, 0)
print("Failure. hr=" .. hr)
test.stopTest()
end
return true
end
function AchievementsManager_Handler()
print("AchievementsManager_Handler")
StartAchievementsManagerDoWorkLoop()
XblAchievementsManagerAddLocalUser()
end
function OnXblAchievementsManagerDoWork_LocalUserAddedEvent()
print("OnXblAchievementsManagerDoWork_LocalUserAddedEvent")
handle, hr = XblAchievementsManagerGetAchievement("1")
VerifySuccess(hr)
count, hr = XblAchievementsManagerResultGetAchievements(handle)
VerifySuccess(hr)
XblAchievementsManagerResultCloseHandle(handle)
handle, hr = XblAchievementsManagerGetAchievements()
VerifySuccess(hr)
count, hr = XblAchievementsManagerResultGetAchievements(handle)
if count ~= 2 then
test.equal(hr, 0);
print("Failure. Number of achievements found (" .. count .. ") different from expected (2). hr=" .. hr)
test.stopTest()
end
VerifySuccess(hr)
XblAchievementsManagerResultCloseHandle(handle)
handle, hr = XblAchievementsManagerGetAchievements()
VerifySuccess(hr)
count, hr = XblAchievementsManagerResultGetAchievements()
VerifySuccess(hr)
XblAchievementsManagerResultCloseHandle(handle)
handle, hr = XblAchievementsManagerGetAchievementsByState()
VerifySuccess(hr)
count, hr = XblAchievementsManagerResultGetAchievements()
VerifySuccess(hr)
XblAchievementsManagerResultCloseHandle(handle)
XblAchievementsManagerRemoveLocalUser()
StopAchievementsManagerDoWorkLoop()
test.stopTest()
end
function OnXblAchievementsManagerDoWork_AchievementProgressUpdatedEvent()
print("OnXblAchievementsManagerDoWork_AchievementProgressUpdatedEvent")
end
function OnXblAchievementsManagerDoWork_AchievementUnlockedEvent()
print("OnXblAchievementsManagerDoWork_AchievementUnlockedEvent")
end
test.isbvt = true
test.TestAchievementsManager = function()
common.init(AchievementsManager_Handler)
end
|
raceRoot = Element("race-root", "raceRoot")
local races = {}
local raceDimension = 0
-- Возможные состояния гонки
local RaceState = {
waiting = "waiting",
running = "running",
ended = "ended"
}
setTimer(function ()
for id, race in pairs(races) do
local racePlayers = race:getPlayers()
if not racePlayers or #racePlayers == 0 then
race:destroy()
end
end
end, 60 * 1000 * 5, 0)
local function isRaceState(state)
if not state then return false end
return not not RaceState[state]
end
function getPlayerRace(player)
if player.parent.type == "race" then
return races[player.parent.id]
end
end
function getRaceByElement(element)
if not isElement(element) then
outputDebugString("getRaceByElement: bad race element '" .. tostring(element) .. "'")
return false
end
if element.type ~= "race" then
outputDebugString("getRaceByElement: bad race element '" .. tostring(element.type) .. "'")
return false
end
return races[element.id]
end
-- Удалить игрока при уничтожении автомобиля
addEventHandler("onElementDestroy", root, function ()
if source.type ~= "vehicle" then return end
local player = source.controller
if not isElement(player) then return end
local race = getPlayerRace(player)
if not race then return end
race:removePlayer(player)
end)
-- Запретить выход игроков, находящихся в гонке, из автомобиля
addEventHandler("onVehicleStartExit", root, function (player)
local race = getPlayerRace(player)
if not race then return end
cancelEvent()
end)
addEventHandler("onResourceStart", resourceRoot, function ()
for i, player in ipairs(getElementsByType("player")) do
if player:getData("activeUI") == "raceUI" then
player:setData("activeUI", false)
if player.vehicle then
player.vehicle.dimension = 0
end
player.dimension = 0
end
end
end)
---------------------------------------------------------------
----------------------- Создание гонки ------------------------
---------------------------------------------------------------
addEvent("Race.clientFinished", true)
addEvent("Race.clientLeave", true)
addEvent("Race.clientReady", true)
local RACE_LOG_SERVER = true
local RACE_LOG_DEBUG = true
local RACE_LOG_FORMAT = "Race [%s]: %s"
-- Режиы гонок
local raceGamemodes = {
sprint = Sprint,
drift = Drift,
-- drag = Drag,
-- circle = Circle,
duel = Duel
}
local RACE_SETTINGS = {
separateDimension = false,
gamemode = "sprint",
duration = 300
}
local RACE_MAP = {
checkpoints = {},
objects = {},
spawnpoints = {}
}
Race = newclass "Race"
function Race:init(settings, map)
-- Создать element гонки и добавить в таблицу гонок
local id = raceRoot:getChildrenCount() + 1
self.element = Element("race", "race_" .. tostring(id))
self.element.parent = raceRoot
races[self.element.id] = self
-- Инициализация состояния гонки, загрузка настроек и карты
self.state = ""
self.settings = exports.dpUtils:extendTable(settings, RACE_SETTINGS)
self.map = exports.dpUtils:extendTable(map, RACE_MAP)
self.element:setData("Race.settings", self.settings)
-- Выбор уникального dimension'а в зависимости от настроек
if self.settings.separateDimension then
self.dimension = 12000 + raceDimension
else
self.dimension = 0
end
raceDimension = raceDimension + 1
if raceDimension > 13000 then
raceDimension = 0
end
-- Маркер финиша
local x, y, z = unpack(self.map.checkpoints[#self.map.checkpoints])
if x and y and z then
self.finishMarker = createMarker(x, y, z - 1, "cylinder", 7, 0, 0, 0, 0)
self.finishMarker.dimension = self.dimension
self.finishMarker.parent = self.element
end
-- Корректное удаление игрока из гонки при выходе с сервера
local this = self
addEventHandler("onPlayerQuit", self.element, function ()
this:removePlayer(source)
end)
-- Удалить игрока при взрыве автомобиля
addEventHandler("onVehicleExplode", self.element, function ()
local player = vehicle:getData("Race.player")
this:removePlayer(player)
end)
addEventHandler("onPlayerVehicleExit", self.element, function ()
outputDebugString("Vehicle exit")
this:removePlayer(source)
end)
addEventHandler("Race.clientLeave", resourceRoot, function ()
if client.parent == this.element then
this:removePlayer(client)
end
end)
addEventHandler("Race.clientFinished", self.element, function ()
if client.parent == this.element then
this:playerFinish(client)
end
end)
addEventHandler("Race.clientReady", self.element, function ()
if client.parent == this.element then
this:playerReady(client)
end
end)
self:setState(RaceState.waiting)
self.allPlayers = {}
self.totalPlayersCount = 0
self.readyPlayers = {}
local gamemodeClass = raceGamemodes[self.settings.gamemode]
if not gamemodeClass then
self:log("Failed to create race. Gamemode '" .. tostring(self.settings.gamemode) .. "' does not exist")
self:destroy()
return false
end
self.gamemode = gamemodeClass(self)
self:log("Race created. Race ID: '" .. tostring(self.element.id) .. "'")
end
function Race:destroy()
-- Гонка уже удалена
if not isElement(self.element) then
self:log("Failed to destroy race. It's already destroyed.")
return false
end
if self.isBeingDestroyed then
self:log("Failed to destroy race. It's being destroyed.")
return false
end
self.gamemode:raceDestroyed()
self.isBeingDestroyed = true
triggerEvent("dpRaceManager.raceDestroyed", self.element)
-- Принудительно финишировать гонку
if self:getState() == RaceState.running then
self:finish()
end
-- Удалить всех игроков из гонки
for _, player in ipairs(self:getPlayers()) do
self:removePlayer(player)
end
if isElement(self.finishMarker) then
destroyElement(self.finishMarker)
end
-- Удалить таймеры
if isTimer(self.durationTimer) then
killTimer(self.durationTimer)
end
if isTimer(self.countdownTimer) then
killTimer(self.countdownTimer)
end
if isTimer(self.waitingTimer) then
killTimer(self.waitingTimer)
end
-- Удалить саму гонку
races[self.element.id] = nil
if destroyElement(self.element) then
self:log("Race destroyed")
else
self:log("Failed to destroy race")
end
self.isBeingDestroyed = false
self.totalPlayersCount = 0
end
---------------------------------------------------------------
----------------------- Состояние гонки -----------------------
---------------------------------------------------------------
function Race:setState(state)
if not check("Race:setState", "state", "string", state) then return false end
if not isRaceState(state) then
self:log("Failed to change race state. '" .. tostring(state) .."' is not a valid race state.")
return false
end
self.state = state
self.element:setData("Race.state", state)
triggerClientEvent(self.element, "Race.stateChanged", self.element, self.state)
return true
end
function Race:getState()
return self.state
end
---------------------------------------------------------------
----------------------- Игроки в гонке ------------------------
---------------------------------------------------------------
function Race:addPlayer(player)
if not check("Race:addPlayer", "player", "player", player) then return false end
if not player:getData("_id") then
self:log("Failed to add player. Player is not logged in")
return false
end
-- Игрок не должен находиться в гонке
if player.parent.type == "race" then
self:log("Failed to add player. Player is in other race")
return false
end
-- Игрок должен быть в автомобиле
if not player.vehicle then
self:log("Failed to add player. Player must be in a vehicle")
return false
end
-- Игрок должен быть за рулем
if player.vehicle.controller ~= player then
self:log("Failed to add player. Player must driving the vehicle")
return false
end
-- В автомобиле должен быть только один игрок
if exports.dpUtils:getVehicleOccupantsCount(player.vehicle) > 1 then
self:log("Failed to add player. Player must be the only vehicle occupant")
return false
end
player.vehicle.dimension = self.dimension
toggleAllControls(player, false)
local race = self
player.vehicle.frozen = true
setTimer(function ()
if not race.element then
return
end
player.vehicle.frozen = false
end, 1500, 1)
setTimer(function ()
toggleAllControls(player, true)
if not race.element then
return
end
player.vehicle.frozen = true
end, 3000, 1)
player.vehicle:setData("Race.player", player)
player.vehicle.parent = player
player.parent = self.element
player.dimension = self.dimension
player:setData("Race.vehicle", player.vehicle)
triggerClientEvent(player, "Race.addedToRace", self.element, self.settings, self.map)
triggerClientEvent(self.element, "Race.playerAdded", player)
self.gamemode:spawnPlayer(player)
self.allPlayers = self:getPlayers()
self:log("Player added: '" .. tostring(player.name) .. "'")
self.totalPlayersCount = #self.allPlayers
return true
end
function Race:removePlayer(player)
if not check("Race:removePlayer", "player", "player", player) then return false end
if not isElement(self.element) then
self:log("Failed to remove player. Race is destroyed")
return false
end
-- Игрок должен находиться в этой гонке
if player.parent.id ~= self.element.id then
self:log("Failed to remove player. Player is not in this race")
return false
end
-- На момент удаления игрок может быть не в машине
local vehicle = player.vehicle
if not vehicle then
vehicle = player:getData("Race.vehicle")
end
if isElement(vehicle) then
vehicle.dimension = 0
vehicle.frozen = false
vehicle:removeData("Race.player")
vehicle.parent = root
end
player.parent = root
player.dimension = 0
player:removeData("Race.finished")
player:setData("activeUI", false)
if not self.isBeingDestroyed then
self.gamemode:playerRemoved(player)
end
if self.element and isElement(self.element) then
triggerClientEvent(player, "Race.removedFromRace", resourceRoot)
triggerClientEvent(self.element, "Race.playerRemoved", player)
self:log("Player removed: '" .. tostring(player.name) .. "'")
end
-- Удалить гонку при удалении всех игроков
if self:getState() ~= RaceState.waiting and #self:getPlayers() == 0 then
self:destroy()
end
return true
end
function Race:getPlayers()
if not isElement(self.element) then
return {}
end
return self.element:getChildren("player")
end
function Race:getAllPlayers()
if type(self.allPlayers) ~= "table" then
return {}
else
return self.allPlayers
end
end
function Race:getFinishedPlayers()
return self.gamemode:getFinishedPlayers()
end
function Race:getTotalPlayersCount()
return self.totalPlayersCount
end
---------------------------------------------------------------
----------------------- Геймплей гонки ------------------------
---------------------------------------------------------------
local COUNTDOWN_DELAY = 3000
local WAITING_DELAY = 15000
-- Запуск гонки, ожидание игроков и т. д.
function Race:launch()
-- Гонка не должна быть запущена
if self:getState() ~= RaceState.waiting then
self:log("Failed to launch race. It's already running or ended")
return false
end
if #self.readyPlayers >= #self:getPlayers() then
self:log("All players ready before start")
self:preStart()
else
self.waitingTimer = setTimer(function() self:preStart(true) end, WAITING_DELAY, 1)
end
return true
end
function Race:playerReady(player)
if self:isPlayerReady(player) then
return false
end
table.insert(self.readyPlayers, player)
self:log("Player ready " .. tostring(player.name))
if isTimer(self.waitingTimer) and #self.readyPlayers >= #self:getPlayers() then
self:log("All players are ready")
self:preStart()
end
end
function Race:isPlayerReady(player)
for i, p in ipairs(self.readyPlayers) do
if player == p then
return true
end
end
return false
end
-- Запуск отсчёта
function Race:preStart(kickNotReady)
if isTimer(self.waitingTimer) then
killTimer(self.waitingTimer)
end
for i, p in ipairs(self:getPlayers()) do
if not self:isPlayerReady(p) then
self:removePlayer(p)
self:log("Player not ready " .. tostring(p.name))
end
end
triggerClientEvent(self.element, "Race.launch", self.element)
self.countdownTimer = setTimer(function() self:start() end, COUNTDOWN_DELAY, 1)
self:log("Starting race...")
end
-- Старт гонки
function Race:start()
-- Гонка не должна быть запущена
if self:getState() ~= RaceState.waiting then
self:log("Failed to start race. It's already running or ended")
return false
end
-- Гонка не должна быть без игроков
if #self:getPlayers() == 0 then
self:log("Failed to start race. No players in race")
self:destroy()
return false
end
-- Не был запущен countdown
if not isTimer(self.countdownTimer) then
self:log("Race must be started with Race:launch()")
return false
end
killTimer(self.countdownTimer)
self:setState(RaceState.running)
self:setTimeLeft(self.settings.duration)
triggerClientEvent(self.element, "Race.start", self.element)
for _, player in ipairs(self:getPlayers()) do
player.vehicle.frozen = false
end
self.allPlayers = self:getPlayers()
self.totalPlayersCount = #self.allPlayers
self.gamemode:raceStarted()
self:log("Race started")
return true
end
-- Завершение гонки
function Race:finish(timeout)
-- Гонка должна быть запущена
if self:getState() ~= RaceState.running then
self:log("Failed to finish race. Race is not running")
return false
end
self:setState(RaceState.ended)
triggerClientEvent(self.element, "Race.finish", self.element)
self.gamemode:raceFinished(timeout)
self:log("Race finished")
return true
end
function Race:playerFinish(player)
if not check("Race:playerFinish", "player", "player", player) then return false end
-- Игрок должен находиться в этой гонке
if player.parent.id ~= self.element.id then
self:log("Failed to finish player. Player is not in this race")
return false
end
return self.gamemode:playerFinished(player)
end
-- Время в секундах
function Race:setTimeLeft(time)
if self:getState() ~= RaceState.running then
self:log("Failed to set time left. Race is not running")
return false
end
if type(time) ~= "number" then
self:log("Failed to set time left. Time must be number")
return false
end
if isTimer(self.durationTimer) then
killTimer(self.durationTimer)
end
self.durationTimer = setTimer(function() self:finish(true) end, math.max(50, math.floor(time * 1000)), 1)
triggerClientEvent(self.element, "Race.updateTimeLeft", self.element, time)
return true
end
-- Время в секундах
function Race:getTimeLeft()
if not isTimer(self.durationTimer) then
return false
end
local timeLeft = getTimerDetails(self.durationTimer)
return timeLeft / 1000
end
---------------------------------------------------------------
--------------------------- Прочее ----------------------------
---------------------------------------------------------------
function Race:log(message)
local id = "destroyed"
if isElement(self.element) then
id = self.element.id
end
local outputString = string.format(RACE_LOG_FORMAT, id, tostring(message))
if RACE_LOG_SERVER then
outputServerLog(outputString)
end
if RACE_LOG_DEBUG then
outputDebugString(outputString)
end
return true
end
|
AddCSLuaFile()
ENT.Base = "bw_base_explosive"
ENT.PrintName = "C4 Explosive"
ENT.Model = "models/weapons/w_c4_planted.mdl"
ENT.ExplodeTime = 20
ENT.ExplodeRadius = 200
ENT.DefuseTime = 10
ENT.ShowTimer = true
ENT.OnlyPlantWorld = false
ENT.UsePlant = false
|
-- https://github.com/premake/premake-core/issues/1559
premake.override(premake.vstudio.vc2010, "targetFramework", function(oldfn, prj)
if prj.clr == "NetCore" then
local action = premake.action.current()
local tools = string.format(' ToolsVersion="%s"', action.vstudio.toolsVersion)
local framework = prj.dotnetframework or action.vstudio.targetFramework or "4.0"
premake.w('<TargetFramework>%s</TargetFramework>', framework)
else
oldfn(prj)
end
end)
-- https://github.com/premake/premake-core/issues/1549
premake.override(premake.vstudio.cs2005.elements, "projectProperties", function(base, cfg)
local calls = base(cfg);
table.insert(calls, function(cfg)
if cfg.clr == "Unsafe" then
premake.w('<AllowUnsafeBlocks>true</AllowUnsafeBlocks>')
end
end)
return calls;
end)
|
local MAJOR, MINOR = "Olivine:Luassert:Stub-1.0", 1
-- Get a reference to the package information if any
local APkg = Apollo.GetPackage(MAJOR)
-- If there was an older version loaded we need to see if this is newer
if APkg and (APkg.nVersion or 0) >= MINOR then
return
end
-------------------------------------------------------------------------------
--- Olivine-Labs stub
-------------------------------------------------------------------------------
local util
local spy
-- Set a reference to the actual package or create an empty table
local stub = APkg and APkg.tPackage or {}
local stubfunc = function() end
function stub.new(object, key, func)
if object == nil and key == nil then
-- called without arguments, create a 'blank' stub
object = {}
key = ""
end
assert(type(object) == "table" and key ~= nil, "stub.new(): Can only create stub on a table key, call with 2 params; table, key")
assert(object[key] == nil or util.callable(object[key]), "stub.new(): The element for which to create a stub must either be callable, or be nil")
local old_elem = object[key] -- keep existing element (might be nil!)
object[key] = type(func) == "function" and func or stubfunc -- set the stubfunction
local s = spy.on(object, key) -- create a spy on top of the stub function
local spy_revert = s.revert -- keep created revert function
s.revert = function(self) -- wrap revert function to restore original element
if not self.reverted then
spy_revert(self)
object[key] = old_elem
self.reverted = true
end
return old_elem
end
return s
end
function stub.is_stub(object)
return spy.is_spy(object) and object.callback == stubfunc
end
local function set_stub(state)
end
stub = setmetatable( stub, {
__call = function(self, ...)
-- stub originally was a function only. Now that it is a module table
-- the __call method is required for backward compatibility
-- NOTE: this deviates from spy, which has no __call method
return stub.new(...)
end })
function stub:OnLoad()
util = Apollo.GetPackage("Olivine:Luassert:Util-1.0").tPackage
spy = Apollo.GetPackage("Olivine:Luassert:Spy-1.0").tPackage
assert:register("modifier", "stub", set_stub)
end
Apollo.RegisterPackage(stub, MAJOR, MINOR, {"Lib:Assert-1.0"})
|
#!/usr/local/bin/lua
---------------------------------------------------------------------
-- LuaSOAP test file.
-- $Id: test.lua,v 1.3 2004/03/24 19:27:38 tomas Exp $
---------------------------------------------------------------------
require"lxp/lom"
require"soap"
function table.equal (t1, t2)
assert (type(t1) == type(t2), string.format ("%s (%s) ~= %s (%s)", type(t1),
tostring(t1), type(t2), tostring(t2)))
for i, v1 in pairs (t1) do
local v2 = t2[i]
local tv1 = type(v1)
if tv1 == "table" then
local ok, err = table.equal (v1, v2)
if not ok then
return false, err
end
elseif v1 ~= v2 then
return false, string.format ("%s ~= %s", tostring(v1), tostring(v2))
end
end
return true
end
local tests = {
{
namespace = "Some-URI",
method = "GetLastTradePrice",
entries = { { tag = "symbol", "DEF" }, },
header = {
tag = "t:Transaction",
attr = { "xmlns:t", "SOAP-ENV:mustUnderstand",
["xmlns:t"] = "some-URI",
["SOAP-ENV:mustUnderstand"] = 1,
},
5,
},
xml = [[
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Header>
<t:Transaction xmlns:t="some-URI" SOAP-ENV:mustUnderstand="1">
5
</t:Transaction>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<m:GetLastTradePrice xmlns:m="Some-URI">
<symbol>DEF</symbol>
</m:GetLastTradePrice>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>]]
},
{
namespace = "Some-URI",
method = "GetLastTradePriceDetailed",
entries = {
{ tag = "Symbol", "DEF" },
{ tag = "Company", "DEF Corp" },
{ tag = "Price", 34.1 },
},
xml = [[
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<m:GetLastTradePriceDetailed xmlns:m="Some-URI">
<Symbol>DEF</Symbol>
<Company>DEF Corp</Company>
<Price>34.1</Price>
</m:GetLastTradePriceDetailed>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>]]
},
{
namespace = "Some-URI",
method = "GetLastTradePriceResponse",
entries = {
{ tag = "Price", 34.5 },
},
header = {
tag = "t:Transaction",
attr = { "xmlns:t", "xsi:type", "mustUnderstand",
["xmlns:t"] = "some-URI",
["xsi:type"] = "xsd:int",
["mustUnderstand"] = 1,
},
5,
},
xml = [[
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Header>
<t:Transaction xmlns:t="some-URI" xsi:type="xsd:int" mustUnderstand="1">
5
</t:Transaction>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<m:GetLastTradePriceResponse xmlns:m="Some-URI">
<Price>34.5</Price>
</m:GetLastTradePriceResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>]]
},
{
namespace = "Some-URI",
method = "GetLastTradePriceResponse",
entries = {
{
tag = "PriceAndVolume",
{ tag = "LastTradePrice", 34.5, },
{ tag = "DayVolume", 10000, },
}
},
xml = [[
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<m:GetLastTradePriceResponse xmlns:m="Some-URI">
<PriceAndVolume>
<LastTradePrice>
34.5
</LastTradePrice>
<DayVolume>
10000
</DayVolume>
</PriceAndVolume>
</m:GetLastTradePriceResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>]]
},
{
namespace = nil,
method = "SOAP-ENV:Fault",
entries = {
{ tag = "faultcode", "SOAP-ENV:MustUnderstand", },
{ tag = "faultstring", "SOAP Must Understand Error", },
},
xml = [[
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:MustUnderstand</faultcode>
<faultstring>SOAP Must Understand Error</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>]]
},
{
namespace = nil,
method = "SOAP-ENV:Fault",
entries = {
{ tag = "faultcode", "SOAP-ENV:Server", },
{ tag = "faultstring", "Server Error", },
{
tag = "detail",
{
tag = "e:myfaultdetails",
attr = { "xmlns:e", ["xmlns:e"] = "Some-URI", },
{ tag = "message", "My application didn't work", },
{ tag = "errorcode", 1001, },
},
},
},
xml = [[
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring>Server Error</faultstring>
<detail>
<e:myfaultdetails xmlns:e="Some-URI">
<message>
My application didn't work
</message>
<errorcode>
1001
</errorcode>
</e:myfaultdetails>
</detail>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>]]
},
}
for i, t in ipairs(tests) do
local s = soap.encode (t.namespace, t.method, t.entries, t.header)
s = string.gsub (s, "[\n\r\t]", "")
local ds = assert (lom.parse ([[<?xml version="1.0" encoding="ISO-8859-1"?>]]..s))
t.xml = string.gsub (t.xml, "[\n\r\t]", "")
local dx = assert (lom.parse ([[<?xml version="1.0" encoding="ISO-8859-1"?>]]..t.xml))
print (table.equal (ds, dx))
end
|
local function giveExercise()
local num1 = math.random(0, 100)
local num2 = math.random(0, 100)
io.write(string.format("%d + %d = ", num1, num2))
local userNum = io.read("n")
if userNum == (num1 + num2) and type(userNum) == "number" then
print("Spravne")
elseif userNum ~= (num1 + num2) and type(userNum) == "number" then
print("Spatne")
else
print("Spatne zadana hodnota")
end
end
giveExercise()
|
local firePlaces = {
{-1817.96, 142.17, 15.1},
{-1817.96, 142.17, 15.1},
{-2885.11, 460.5, 4.91},
{-1985.94, 369.42, 35.21},
{-1756.07, 931.96, 24.74},
{-1575.65, 1207.31, 7.59},
{-1552.45, 386.15, 7.18},
{-1527.6357421875,-404.1904296875,7.078125},
{-1738.0205078125,103.244140625,3.5546875},
{-1984.5517578125,368.8173828125,35.231113433838},
{-2527.19921875,567.8203125,14.4609375},
{-2656.09765625,608.9365234375,14.453125},
{-2821.255859375,1304.837890625,7.1015625},
}
local fireElements = {}
local fireObjects = {2021, 2022, 2023}
local isFireFighterRunning = false
local blip = nil
local screenW, screenH = guiGetScreenSize()
local firesLeft = 0
function loadFireObjects()
local fire = engineLoadDFF("fire.dff", 0)
engineReplaceModel(fire, 2021)
local fire_large = engineLoadDFF("fire_large.dff", 0)
engineReplaceModel(fire_large, 2023)
local fire_med = engineLoadDFF("fire_med.dff", 0)
engineReplaceModel(fire_med, 2022)
end
function unloadFireObjects()
for i, v in ipairs(fireObjects) do
engineRestoreModel(v)
end
end
local timesHit = {}
function destroyFire(fire)
if (isElement(fire) and fireElements[fire]) then
destroyElement(fire)
fireElements[fire] = nil
triggerServerEvent("AURfire.reward", localPlayer)
firesLeft = firesLeft - 1
exports.AURstickynote:displayText("AURfire", "text", firesLeft.." "..(firesLeft > 1 and "fires" or "fire") .." left")
if (firesLeft == 0) then
startFire()
end
end
end
function hitFire(w, ammo, clipAmmo, hX, hY, hZ, hitEl)
if (not isFireFighterRunning) then
removeEventHandler("onClientPlayerWeaponFire", localPlayer, hitFire)
end
if (w ~= 42) then
return false
end
if (not hitEl or not isElement(hitEl)) then
return false
end
if (getElementType(hitEl) ~= "object") then
return false
end
if (not fireElements[hitEl]) then
return false
end
if (not timesHit[hitEl]) then
timesHit[hitEl] = 1
else
timesHit[hitEl] = timesHit[hitEl] + 1
end
if (timesHit[hitEl] == 25) then
destroyFire(hitEl)
timesHit[hitEl] = nil
end
end
function startFire()
isFireFighterRunning = true
unloadFireObjects()
loadFireObjects()
firesLeft = 0
if (isElement(blip)) then
destroyElement(blip)
end
for i, v in pairs(fireElements) do
if (isElement(i)) then
destroyElement(i)
end
end
local randomPlace = firePlaces[math.random(#firePlaces)]
local x, y, z = unpack(randomPlace)
local zoneName = getZoneName(x, y, z, false)
blip = createBlip(x, y, z, 20)
exports.NGCdxmsg:createNewDxMessage("A fire broke out at "..zoneName.."! Go there and extinguish the fire!", 255, 0, 0)
for i=1, 10 do
local z = z - 0.5
if (getGroundPosition(x, y, z) ~= getGroundPosition(x, y, z + 15)) then
z = getGroundPosition(x, y, z + 5)
end
fireElements[createObject(fireObjects[math.random(#fireObjects)], x + i, y, z)] = true
end
for i=1, 10 do
local z = z - 0.5
if (getGroundPosition(x, y, z) ~= getGroundPosition(x, y, z + 15)) then
z = getGroundPosition(x, y, z + 5)
end
fireElements[createObject(fireObjects[math.random(#fireObjects)], x, y + i, z)] = true
end
for i=1, 10 do
local z = z - 0.5
if (getGroundPosition(x, y, z) ~= getGroundPosition(x, y, z + 15)) then
z = getGroundPosition(x, y, z + 5)
end
fireElements[createObject(fireObjects[math.random(#fireObjects)], x - i, y, z)] = true
end
for i=1, 10 do
local z = z - 0.5
if (getGroundPosition(x, y, z) ~= getGroundPosition(x, y, z + 15)) then
z = getGroundPosition(x, y, z + 5)
end
fireElements[createObject(fireObjects[math.random(#fireObjects)], x, y - i, z)] = true
end
for i=1, 10 do
local z = z - 0.5
if (getGroundPosition(x, y, z) ~= getGroundPosition(x, y, z + 15)) then
z = getGroundPosition(x, y, z + 5)
end
fireElements[createObject(fireObjects[math.random(#fireObjects)], x - i, y - i, z)] = true
end
for i=1, 10 do
local z = z - 0.5
if (getGroundPosition(x, y, z) ~= getGroundPosition(x, y, z + 15)) then
z = getGroundPosition(x, y, z + 5)
end
fireElements[createObject(fireObjects[math.random(#fireObjects)], x + i, y + i, z)] = true
end
for i=1, 10 do
local z = z - 0.5
if (getGroundPosition(x, y, z) ~= getGroundPosition(x, y, z + 15)) then
z = getGroundPosition(x, y, z + 5)
end
fireElements[createObject(fireObjects[math.random(#fireObjects)], x + i, y - i, z)] = true
end
for i=1, 10 do
local z = z - 0.5
if (getGroundPosition(x, y, z) ~= getGroundPosition(x, y, z + 15)) then
z = getGroundPosition(x, y, z + 5)
end
fireElements[createObject(fireObjects[math.random(#fireObjects)], x - i, y + i, z)] = true
end
for i, v in pairs(fireElements) do
setElementAlpha(i, 255)
firesLeft = firesLeft + 1
end
exports.AURstickynote:displayText("AURfire", "text", firesLeft.." "..(firesLeft > 1 and "fires" or "fire") .." left")
end
function stopFire()
if (not isFireFighterRunning) then
return
end
isFireFighterRunning = false
unloadFireObjects()
for i, v in pairs(fireElements) do
destroyElement(i)
end
fireElements = {}
if (isElement(blip)) then
destroyElement(blip)
end
blip = nil
end
function loadOnStart()
if (getElementData(localPlayer, "Occupation") == "Firefighter") then
startFire()
addEventHandler("onClientPlayerWeaponFire", localPlayer, hitFire)
addEventHandler("onClientRender", root, dxFires)
end
end
addEventHandler("onClientResourceStart", resourceRoot, loadOnStart)
function onElementDataChange(dataName, oldValue)
if (dataName == "Occupation" and getElementData(localPlayer, dataName) == "Firefighter") then
startFire()
addEventHandler("onClientPlayerWeaponFire", localPlayer, hitFire)
elseif (dataName == "Occupation" and isFireFighterRunning) then
removeEventHandler("onClientPlayerWeaponFire", localPlayer, hitFire)
exports.AURstickynote:displayText("AURfire", "text", false)
stopFire()
end
end
addEventHandler("onClientElementDataChange", localPlayer, onElementDataChange, false)
function toggleFirefighter()
if (getElementData(localPlayer, "Occupation") == "Firefighter") then
exports.CSGranks:openPanel()
end
end
bindKey("F5", "down", toggleFirefighter)
|
AddCommand("p-spawn", function(player)
if DISABLE_COMMANDE then return end
local x,y,z = GetPlayerLocation(player)
Spawn(x,y,z)
end)
AddCommand("p-fly", function(player)
if DISABLE_COMMANDE then return end
local x,y,z = GetPlayerLocation(player)
SetPlayerLocation(player, x, y, z + 40000)
end)
AddCommand("p", function(player)
if DISABLE_COMMANDE then return end
SetParachutePlayer(player, true)
end)
|
add_subdirs("deps/malog/src")
add_subdirs("src")
add_subdirs("examples")
|
local base_util = require("__core__/lualib/util")
local small_ruins = {require("ruins/small-fluid-burner"), require("ruins/small-reinforced-windturbines"), require("ruins/small-sentinel-outpost")}
local medium_ruins = {require("ruins/medium-creep-biomass"), require("ruins/medium-fuel-plant"), require("ruins/medium-tree-greenhouse")}
local large_ruin = require("ruins/large-matter-plant")
local function make_ruin_set()
-- Get the base ruin set of the AbandonedRuins mod. This creates a copy of that ruin set.
local base_ruins = remote.call("AbandonedRuins", "get_ruin_set", "base")
-- Add the custom Krastorio2 ruins to the existing ruins.
for _, ruin in pairs(small_ruins) do
table.insert(base_ruins.small, ruin)
end
for _, ruin in pairs(medium_ruins) do
table.insert(base_ruins.medium, ruin)
end
table.insert(base_ruins.large, large_ruin)
if settings.startup["kr-more-realistic-weapon"].value then
-- With the weapon overhaul, turrets use the krastorio2 ammo instead of base game ammo.
-- So, replace those spawned items within the ruins.
replace_item_name_in_all_ruins(base_ruins, "firearm-magazine", "rifle-magazine")
replace_item_name_in_all_ruins(base_ruins, "piercing-rounds-magazine", "armor-piercing-rifle-magazine")
end
if settings.startup["kr-rebalance-vehicles&fuels"].value then
-- With the fuel overhaul, vehicles use the krastorio2 fuel instead of base game solid fuel.
-- So, replace those spawned items within the ruins.
replace_item_name_in_all_ruins(base_ruins, "solid-fuel", "fuel")
end
-- Provide the extended and modified ruin set as the "krastorio2" set.
remote.call("AbandonedRuins", "add_ruin_set", "krastorio2", base_ruins.small, base_ruins.medium, base_ruins.large)
end
-- The ruin set is created always when the game is loaded, since the ruin sets are not save/loaded by AbandonedRuins.
-- Since this is using on_load, we must be sure that it always produces the same result for everyone.
-- Luckily, it's okay to do ruin changes based on a startup setting here since those cannot change during the game.
script.on_init(make_ruin_set)
script.on_load(make_ruin_set)
function replace_item_name_in_all_ruins(ruin_set, value, replacement)
for _, ruin in pairs(ruin_set.small) do
replace_item_name(ruin, value, replacement)
end
for _, ruin in pairs(ruin_set.medium) do
replace_item_name(ruin, value, replacement)
end
for _, ruin in pairs(ruin_set.large) do
replace_item_name(ruin, value, replacement)
end
end
function replace_item_name(ruin, name, replacement)
if not (ruin.entities and next(ruin.entities) ~= nil) then return end
for _, entity in pairs(ruin.entities) do
if entity[3] and entity[3].items then
local items = base_util.copy(entity[3].items)
for item, count in pairs(items) do
if item == name then
entity[3].items[replacement] = count
entity[3].items[name] = nil
end
end
end
end
end
|
game:service("TeleportService"):Teleport(IDHERE)
|
local Prop = {}
Prop.Name = "Book Store"
Prop.Government = true
Prop.Doors = {
Vector( 2236.000000, 2798.000000, -13355.687500 ),
Vector( 2236.000000, 2706.000000, -13355.687500 ),
}
GM.Property:Register( Prop )
|
-----------------------------------
-- Area: Wajaom Woodlands
-- ZNM: Gotoh Zha the Redolent
-----------------------------------
mixins =
{
require("scripts/mixins/job_special"),
require("scripts/mixins/rage")
}
require("scripts/globals/status")
-----------------------------------
-- Detailed Notes & Todos
-- (please remove these if you handle any)
-- 1. Find out if stats (INT, MND, MAB..)
-- actually change when it switches mode on retail.
-- 2. Correct mobskill use behavior:
-- Will always do Groundburst after Warm-Up,
-- will never use Groundburst without a preceding Warm-Up.
-- will not attempt any other TP attacks until Groundburst finished
-- (either landed or failed from lack of targets, resetting his TP)
-- 3. Firespit can land over 1500 dmg during rage.
-- If rage is reset/removed its 2hrs are also reset.
-- 4. This NM also shows some insight into retail mob 2hrs/1hrs:
-- they actually have the same cooldown as players and only
-- time, respawn, or rage loss will reset them.
-- 6. Speaking of those two functions..
-- We have no data on the weapon break chance, went with 10% on both for now.
-- Do crit ws hits count differently than regular ws hits on retail?
-- Should onCriticalHit count WS crit hits if regular WS hits do not count?
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(tpz.mobMod.IDLE_DESPAWN, 300)
end
function onMobSpawn(mob)
tpz.mix.jobSpecial.config(mob, {
specials =
{
{id = tpz.jsa.MANAFONT, hpp = math.random(66, 95)},
{id = tpz.jsa.BENEDICTION, hpp = 0},
},
})
mob:setLocalVar("[rage]timer", 3600) -- 60 minutes
mob:setSpellList(296) -- Set BLM spell list
end
function onMobFight(mob, target)
if mob:AnimationSub() == 1 and mob:getLocalVar("jobChanged") == 0 then
mob:setLocalVar("jobChanged", 1)
mob:setSpellList(297) -- Set WHM spell list.
-- set new JSA parameters
tpz.mix.jobSpecial.config(mob, {
specials =
{
{id = tpz.jsa.MANAFONT, hpp = 0},
{id = tpz.jsa.BENEDICTION, hpp = math.random(25, 50)},
},
})
end
end
function onCriticalHit(mob)
local RND = math.random(1, 100)
if mob:AnimationSub() == 0 and RND <= 10 then
mob:AnimationSub(1)
end
end
function onWeaponskillHit(mob, attacker, weaponskill)
local RND = math.random(1, 100)
if mob:AnimationSub() == 0 and RND <= 10 then
mob:AnimationSub(1)
end
return 0
end
function onMobDeath(mob, killer)
end
|
local strnew = CS.ZX.Core.StringNew
local M = setmetatable({
}, {__index = function(t, k)
local id = strnew(k)
t[k] = id
return id
end})
return M
|
--[[
LuiExtended
License: The MIT License (MIT)
--]]
local zo_strformat = zo_strformat
local changelogMessages = {
"|cFFA500LuiExtended Version 6.2.2|r",
"",
"|cFFFF00Known Issues:|r",
"[*] Due to API changes with Major/Minor effects the Bar Highlight component of Combat Info may have some issues tracking Major/Minor debuffs applied onto a target. In some cases they won't start tracking until you mouse off and back on to the target. This is due to some issues with the API that I hope are addressed in the future (although it may not technically qualify as a bug).",
"",
"|cFFFF00General:|r",
"[*] Updated icons & tooltips for the new sets and Alliance War skill line consumables introduced in this update.",
"",
"|cFFFF00Buffs & Debuffs:|r",
"[*] You can now independently control the alignment and sorting direction of each buff or debuff container. The new settings mirror the previous default settings, you may need to readjust some of these settings if you had modified them before.",
"[*] You can now independently control the Horizontal/Vertical orientation of the Long Term Buffs, Prominent Buffs, and Prominent Debuffs container. The new settings mirror the previous default settings, you may need to readjust some of these settings if you had modified them before.",
"[*] Added a new Alignment & Sorting Options submenu for the changes above to make changing these settings easier.",
"[*] Removed the display of Cyrodiil Home/Enemy/Edge Keep bonus buffs - these took up too much space and the functions used to determine/display them were inefficient.",
"[*] The toggle option for Cyrodiil buffs now only applies to Cyrodiil Scroll bonuses. Emperorship Alliance Bonus & Blessing of War will now always display (Note: The toggle setting for Battle Spirit is separate and remains unchanged).",
"[*] The options for Consolidating Major/Minor effects has been removed due to API changes to Major/Minor effect handling.",
"[*] Custom icons for Major/Minor effects from Potions/Poisons have been removed due to API Changes and the menu option for toggling these icons has been removed (Note: The option to toggle the default icons for Major/Minor Slayer/Aegis remains).",
"",
"|cFFFF00Combat Info:|r",
"- Removed the \"Highlight Secondary Id\" option from Bar Highlight settings. This applied to all of about 2 or 3 abilities before (The magicka regen buff for Honor the Dead for example) that now always display when Highlight is enabled.",
"",
}
-- Hide toggle called by the menu or xml button
function LUIE.ToggleChangelog(option)
LUIE_Changelog:ClearAnchors()
LUIE_Changelog:SetAnchor(CENTER, GuiRoot, CENTER, 0, -120 )
LUIE_Changelog:SetHidden(option)
end
-- Called on initialize
function LUIE.ChangelogScreen()
-- concat messages into one string
local changelog = table.concat(changelogMessages, "\n")
-- If text start with '*' replace it with bullet texture
changelog = string.gsub(changelog, "%[%*%]", "|t12:12:EsoUI/Art/Miscellaneous/bullet.dds|t")
-- Set the window title
LUIE_Changelog_Title:SetText(zo_strformat("<<1>> Changelog", LUIE.name))
-- Set the about string
LUIE_Changelog_About:SetText(zo_strformat("v<<1>> by <<2>>", LUIE.version, LUIE.author))
-- Set the changelog text
LUIE_Changelog_Text:SetText(changelog)
-- Display the changelog if version number < current version
if (LUIESV.Default[GetDisplayName()]['$AccountWide'].WelcomeVersion ~= LUIE.version) then
LUIE_Changelog:SetHidden(false)
end
-- Set version to current version
LUIESV.Default[GetDisplayName()]['$AccountWide'].WelcomeVersion = LUIE.version
end
|
data:extend(
{
{
type = "item",
name = "plutonium-239",
icon = "__Clowns-Nuclear__/graphics/icons/plutonium-239.png",
icon_size = 32,
subgroup = "clowns-nuclear-isotopes",
order = "c",
stack_size = 50
},
{
type = "ammo",
name = "thermonuclear-bomb",
icon = "__Clowns-Nuclear__/graphics/icons/thermonuclear-bomb.png",
icon_size = 32,
ammo_type =
{
range_modifier = 5,
cooldown_modifier = 10,
target_type = "position",
category = "rocket",
action =
{
type = "direct",
action_delivery =
{
type = "projectile",
projectile = "thermonuclear-rocket",
starting_speed = 0.02,
source_effects =
{
type = "create-entity",
entity_name = "explosion-hit"
}
}
}
},
subgroup = "ammo",
order = "d[rocket-launcher]-c[thermonuclear-bomb]",
stack_size = 1,
},
}
)
if settings.startup["artillery-shells"].value == true then
data:extend(
{
{
type = "ammo",
name = "artillery-shell-nuclear",
icons =
{
{
icon = "__base__/graphics/icons/artillery-shell.png",
icon_size=64,
},
{
icon = "__base__/graphics/icons/atomic-bomb.png",
scale = 0.4,
shift = {-10, -10},
},
},
icon_size = 32,
ammo_type =
{
category = "artillery-shell",
target_type = "position",
action =
{
type = "direct",
action_delivery =
{
type = "artillery",
projectile = "artillery-projectile-nuclear",
starting_speed = 1,
direction_deviation = 0,
range_deviation = 0,
source_effects =
{
type = "create-explosion",
entity_name = "artillery-cannon-muzzle-flash"
}
}
}
},
subgroup = "ammo",
order = "d[explosive-cannon-shell]-d[artillery]2",
stack_size = 3
},
{
type = "ammo",
name = "artillery-shell-thermonuclear",
icons =
{
{
icon = "__base__/graphics/icons/artillery-shell.png",
icon_size=64,
},
{
icon = "__Clowns-Nuclear__/graphics/icons/thermonuclear-bomb.png",
scale = 0.4,
shift = {-10, -10},
},
},
icon_size = 32,
ammo_type =
{
category = "artillery-shell",
target_type = "position",
action =
{
type = "direct",
action_delivery =
{
type = "artillery",
projectile = "artillery-projectile-thermonuclear",
starting_speed = 1,
direction_deviation = 0,
range_deviation = 0,
source_effects =
{
type = "create-explosion",
entity_name = "artillery-cannon-muzzle-flash"
}
}
}
},
subgroup = "ammo",
order = "d[explosive-cannon-shell]-d[artillery]2",
stack_size = 1
},
}
)
end
|
-- NOTE: This needs update acccording to potions.lua!
local config = {
removeOnUse = "no",
usableOnTarget = "yes", -- can be used on target? (fe. healing friend)
range = -1,
realAnimation = "no", -- make text effect visible only for players in range 1x1
flask = 7636,
splash = 41
}
config.removeOnUse = getBooleanFromString(config.removeOnUse)
config.usableOnTarget = getBooleanFromString(config.usableOnTarget)
config.realAnimation = getBooleanFromString(config.realAnimation)
local combat = createCombatObject()
setCombatParam(combat, COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE)
setCombatParam(combat, COMBAT_PARAM_TARGETCASTERORTOPMOST, true)
setCombatParam(combat, COMBAT_PARAM_AGGRESSIVE, false)
setCombatParam(combat, COMBAT_PARAM_DISPEL, CONDITION_POISON)
function onUse(cid, item, fromPosition, itemEx, toPosition)
if(not isPlayer(itemEx.uid) or (not config.usableOnTarget and cid ~= itemEx.uid)) then
if(config.splash < 1) then
return true
end
if(toPosition.x == CONTAINER_POSITION) then
toPosition = getThingPosition(item.uid)
end
doDecayItem(doCreateItem(POOL, config.splash, toPosition))
doRemoveItem(item.uid, 1)
if(not config.flask or config.removeOnUse) then
return true
end
if(fromPosition.x ~= CONTAINER_POSITION) then
doCreateItem(config.flask, fromPosition)
else
doPlayerAddItem(cid, config.flask, 1)
end
return true
end
if(config.range > 0 and cid ~= itemEx.uid and getDistanceBetween(getCreaturePosition(cid), getCreaturePosition(itemEx.uid)) > config.range) then
return true
end
if(not doCombat(cid, combat, numberToVariant(itemEx.uid))) then
return true
end
doSendMagicEffect(getThingPosition(itemEx.uid), CONST_ME_MAGIC_BLUE)
if(not config.realAnimation) then
doCreatureSay(itemEx.uid, "Aaaah...", TALKTYPE_ORANGE_1)
else
for i, tid in ipairs(getSpectators(getThingPosition(itemEx.uid), 1, 1)) do
if(isPlayer(tid)) then
doCreatureSay(itemEx.uid, "Aaaah...", TALKTYPE_ORANGE_1, false, tid)
end
end
end
doRemoveItem(item.uid, 1)
if(not config.flask or config.removeOnUse) then
return true
end
if(fromPosition.x ~= CONTAINER_POSITION) then
doCreateItem(config.flask, fromPosition)
else
doPlayerAddItem(cid, config.flask, 1)
end
return true
end
|
S1 = State()
S2 = State()
code = [[
id = ...
for i = 1, 10000 do
print("id: " .. id .. ", val: " .. i)
end
]]
T1 = thread(S1, code, 1)
T2 = thread(S2, code, 2)
T1:wait()
T2:wait()
|
g = love.graphics --so instead of typing love.graphics.blahblahblah every time,
k = love.keyboard --you can simply write g.blahblahblah! Yay!
function love.load()
-- frame size declaration
width = g.getWidth()
height = g.getHeight()
-- ball properties
ballx, bally = width/2 , height/2
ballxvelocity, ballyvelocity = -1 , 1
-- paddle properties
paddle1, paddle2 = height/2, height/2
-- sound file
wallhit = love.audio.newSource("sounds/wallhit.ogg", "static")
paddlehit = love.audio.newSource("sounds/paddlehit.ogg", "static")
lose = love.audio.newSource("sounds/win.ogg", "static")
-- score
score1, score2 = 0 , 0
end
function love.draw()
-- drawing the ball
g.ellipse( "fill", ballx, bally, 10, 10 )
-- drawing the paddles
g.rectangle("fill", 15,paddle1, 10,60)
g.rectangle("fill", width-15,paddle2, 10,60)
-- draw the score
g.print(score1, (width/2)-30, 30)
g.print(score2, (width/2)+30, 30)
end
function love.update(dt)
-- ball direction
ballx = ballx + ballxvelocity
bally = bally + ballyvelocity
collider()
paddlecontrol()
end
function collider()
if bally > height or bally < 0 then
ballyvelocity = ballyvelocity * -1
wallhit:play()
end
-- print(bally, paddle1)
-- verbose conditionals for collision that affirm my interest in learning the physics library
if ballx >15 and ballx <25 and bally > paddle1 and bally < paddle1 + 60 then
ballxvelocity = ballxvelocity * -1
paddlehit:play()
end
if ballx >width-25 and ballx <width-15 and bally > paddle2 and bally < paddle2 + 60 then
ballxvelocity = ballxvelocity * -1
paddlehit:play()
end
-- off screen detection
if ballx < 0 then
lose:play()
ballx = width/2
bally = height/2
score2 = score2 + 1
end
if ballx > width then
lose:play()
ballx = width/2
bally = height/2
score1 = score1 + 1
end
end
function paddlecontrol()
if k.isDown("w") then
paddle1 = paddle1 - 3
end
if k.isDown("s") then
paddle1 = paddle1 + 3
end
if k.isDown("up") then
paddle2 = paddle2 - 3
end
if k.isDown("down") then
paddle2 = paddle2 + 3
end
end
|
function PlayerEquipment:use_trip_mine_mx()
local ray = self:valid_look_at_placement()
if ray then
managers.statistics:use_trip_mine()
local sensor_upgrade = managers.player:has_category_upgrade("trip_mine", "sensor_toggle")
-- if Network:is_client() then
-- managers.network:session():send_to_host("place_trip_mine", ray.position, ray.normal, sensor_upgrade)
-- else
local rot = Rotation(ray.normal, math.UP)
local unit = TripMineBase.spawn(ray.position, rot, sensor_upgrade, managers.network:session():local_peer():id(), true)
unit:base():set_active(true, self._unit)
-- end
return true
end
return false
end
|
login_autoVerifyFailed_title=[[手机号自动验证未成功]]
login_autoVerifyFailed_reasonText=[[]]
login_autoVerifyFailed_tryAgainBtnText=[[再试一次]]
login_autoVerifyFailed_fillByHandBtnText=[[手动填写]]
|
-- import
local PhysicsShape = require 'candy.physics.2D.PhysicsShape'
local ComponentModule = require 'candy.Component'
local Component = ComponentModule.Component
-- module
local PhysicsTriggerModule = {}
local function _triggerCollisionHandler ( phase, fixA, fixB, arb )
local bodyA = fixA:getBody ()
local ownerA = bodyA.component
local bodyB = fixB:getBody ()
local ownerB = bodyB.component
if phase == MOAIBox2DArbiter.BEGIN then
if ownerA.onCollisionEnter then
ownerA:onCollisionEnter ( ownerB, fixA, fixB )
end
elseif ownerA.onCollisionExit then
ownerA:onCollisionExit ( ownerB, fixA, fixB )
end
end
---@class TriggerObjectBase : Component
local TriggerObjectBase = CLASS: TriggerObjectBase ( Component )
:MODEL {
Field ( "enterMessage" ):string (),
Field ( "exitMessage" ):string ()
}
function TriggerObjectBase:__init ()
self.enterMessage = "collision.enter"
self.exitMessage = "collision.exit"
end
function TriggerObjectBase:onAttach ( ent )
local body = self:createBody ()
self.body = body
body:setSleepingAllowed ( false )
local prop = ent:getProp ()
body:setAttrLink ( MOAIProp.ATTR_X_LOC, prop, MOAIProp.ATTR_WORLD_X_LOC )
body:setAttrLink ( MOAIProp.ATTR_Y_LOC, prop, MOAIProp.ATTR_WORLD_Y_LOC )
body.component = self
body:forceUpdate ()
self:updateCollisionShape ()
end
function TriggerObjectBase:onDetach ()
local body = self.body
body:clearAttrLink ( MOAIProp.ATTR_X_LOC )
body:clearAttrLink ( MOAIProp.ATTR_Y_LOC )
body:destroy ()
end
function TriggerObjectBase:onStart ()
self.active = true
end
function TriggerObjectBase:createBody ()
local world = self:getScene ():getBox2DWorld ()
local body = world:addBody ( MOAIBox2DBody.DYNAMIC )
body:setGravityScale ( 0 )
return body
end
function TriggerObjectBase:updateCollisionShape ()
local body = self.body
if not body then
return
end
if self.shape then
self.shape:destroy ()
end
local shape = body:addCircle ( 0, 0, self.radius )
self.shape = shape
self.shape:setSensor ( true )
self:setupCollisionCallback ( self.shape )
end
function TriggerObjectBase:setupCollisionCallback ( shape )
shape.component = self
shape:setCollisionHandler ( _triggerCollisionHandler, MOAIBox2DArbiter.BEGIN + MOAIBox2DArbiter.END )
end
function TriggerObjectBase:onCollisionEnter ( target )
if not self.active then
return
end
local msg = self.enterMessage or "collision.enter"
self._entity:tell ( msg, target )
end
function TriggerObjectBase:onCollisionExit ( target )
if not self.active then
return
end
local msg = self.exitMessage or "collision.exit"
self._entity:tell ( msg, target )
end
---@class TriggerObject : TriggerObjectBase
local TriggerObject = CLASS: TriggerObject ( TriggerObjectBase )
:MODEL {
"----",
Field ( "radius" ):range ( 0 ):set ( "setRadius" )
}
ComponentModule.registerComponent ( "TriggerObject", TriggerObject )
function TriggerObject:__init ()
self.radius = 50
end
function TriggerObject:setRadius ( r )
self.radius = r
self:updateCollisionShape ()
end
function TriggerObject:createBody ()
local world = self:getScene ():getBox2DWorld ()
local body = world:addBody ( MOAIBox2DBody.DYNAMIC )
body:setGravityScale ( 0 )
return body
end
PhysicsTriggerModule.TriggerObjectBase = TriggerObjectBase
PhysicsTriggerModule.TriggerObject = TriggerObject
return PhysicsTriggerModule
|
local _M = require 'resty.resolver.http'
describe('resty.resolver.http', function()
describe('.new', function()
it('initializes client', function()
local client = _M.new()
assert.truthy(client)
end)
end)
describe(':connect', function()
it('resolves localhost', function()
local client = _M.new()
client:set_timeout(1000)
client.resolver.cache:save({ { address = '127.0.0.1', name = 'unknown.', ttl = 1800 } })
assert(client:connect('unknown', 1984))
assert.equal('unknown', client.host)
assert.equal(1984, client.port)
end)
end)
end)
|
local plainLayouter = {}
plainLayouter.__mt = {__index = plainLayouter}
function plainLayouter:new(space)
local self = setmetatable({},self.__mt)
return self
end
function plainLayouter:begin()
self.drawQueue = {}
end
function plainLayouter:finish(draw)
if draw then
for i=#self.drawQueue,1,-1 do
self.drawQueue[i]()
end
end
end
function plainLayouter:eval(block)
self.startx,self.starty = self.x,self.y
block()
end
function plainLayouter:layout(x,y,w,h,pw,ph,draw)
return x,y,w,h
end
return plainLayouter
|
require('plugins.sniprun.settings')
|
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
local function greetCallback(cid)
local player = Player(cid)
if player:getCondition(CONDITION_POISON) then
player:sendTextMessage(MESSAGE_STATUS_WARNING, "Venture the path of decay!")
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
player:teleportTo(Position(33396, 32836, 14))
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
return false
else
npcHandler:say("Begone! Hissssss! You bear not the mark of the cobra!", cid)
return false
end
return true
end
npcHandler:setCallback(CALLBACK_GREET, greetCallback)
npcHandler:addModule(FocusModule:new())
|
local Model = require("lib.model")
local UserLog = Model:new('user_logs')
return UserLog
|
local snap = require('snap')
local config = require('snap.config')
local file = config.file:with({ reverse = true, suffix = ' »', layout = snap.get('layout').center })
local vimgrep = config.vimgrep:with({ limit = 50000, suffix = ' »' })
-- local args = {"--hidden", "--iglob", "!**/.git/*", "--iglob", "!**/.baks/*", "--iglob", "!**/.langservers/*", "--iglob", "!**/.undo/*", "--iglob", "!**/.session/*", "--iglob", "!**/coc/**","--ignore-case", "--follow",}
local args = {
'--follow',
'--hidden',
'-g',
'!{.backup,.swap,.langservers,.session,.undo,.git,node_modules,vendor,.cache,.vscode-server,.Desktop,.Documents,classes,.DS_STORE}/*',
}
snap.maps({
{
'<leader>s',
file({
try = {
snap.get('producer.git.file').args({ '--cached', '--others', '--exclude-standard' }),
snap.get('producer.ripgrep.file').args({
'--follow',
'--hidden',
'-g',
'!{.backup,.swap,.langservers,.session,.undo,.git,node_modules,vendor,.cache,.vscode-server,.Desktop,.Documents,classes,.DS_STORE}/*',
}),
},
prompt = 'Files',
}),
},
{ '<Leader>f', vimgrep({ prompt = 'Grep' }), { command = 'grep' } },
{ '<Leader>S', file({ producer = 'vim.oldfile', prompt = 'History' }), { command = 'history' } },
{ '<Leader>b', file({ producer = 'vim.buffer', prompt = 'Buffers' }), { command = 'buffers' } },
{
'<Leader>ds',
file({
args = args,
try = {
snap.get('consumer.combine')(
snap.get('producer.ripgrep.file').args({}, '/Users/admin/.config/nvim'),
snap.get('producer.ripgrep.file').args({}, '/Users/admin/.config/zsh')
),
},
prompt = 'Search Dotfiles',
}),
{ command = 'search dotfiles' },
},
{
'<Leader>df',
vimgrep({
args = args,
try = {
snap.get('consumer.combine')(
snap.get('producer.ripgrep.vimgrep').args({}, '/Users/admin/.config/*')
-- snap.get'producer.ripgrep.vimgrep'.args({}, "/Users/admin/.config/zsh")
),
},
prompt = 'Grep Dotfiles',
}),
{ command = 'grep dotfiles' },
},
})
|
--
-- Copyright (c) 2007, Trent Gamblin
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- -- Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- -- Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- -- Neither the name of the <organization> nor the
-- names of its contributors may be used to endorse or promote products
-- derived from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY <copyright holder> ``AS IS'' AND ANY
-- EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
function start()
startMusic("village.ogg")
portal = Object:new{number=2, x=16, y=64, width=16, base_height=8}
girl = Object:new{number=3, x=96, y=144, width=14, base_height=7, anim_set="girl2", move_type=MOVE_WANDER, rest=2000}
makeCharacter(3)
end
function stop()
end
function update(step)
girl:move(step)
end
function activate(activator, activated)
if (activated == 3) then
n = randint(3)
if (n == 1) then
doDialogue("Girl: And on his farm he had a cow, E I E I O...$")
elseif (n == 2) then
doDialogue("Girl: With a moo moo here and a moo moo there...$")
else
doDialogue("Girl: Here a moo, there a moo, everywhere a moo moo...$")
end
end
end
function collide(obj1, obj2)
if ((obj1 == 2) or (obj2 == 2)) then
fadeOut()
setObjectPosition(1, 16, 80)
setObjectDirection(1, DIRECTION_SOUTH)
startArea("farmershome1")
fadeIn()
end
end
|
--- 物品基类
--- @module ItemBase
-- @copyright Lilith Games, Avatar Team
-- @author Dead Ratman
local ItemBase = class('ItemBase')
function ItemBase:initialize(_baseData, _derivedData)
----print('ItemBase:initialize()')
self.baseData = _baseData
self.typeConfig = Config.ItemType[_baseData.Type]
self.derivedData = _derivedData
self.equipObj = nil
end
--放入背包
function ItemBase:PutIntoBag()
NetUtil.Fire_C('GetItemEvent', localPlayer, self.baseData.ItemID)
end
--从背包里扔掉
function ItemBase:ThrowOutOfBag()
NetUtil.Fire_C('RemoveItemEvent', localPlayer, self.baseData.ItemID)
end
--在背包中使用
function ItemBase:UseInBag()
end
--拿在手中使用
function ItemBase:UseInHand()
SoundUtil.Play3DSE(localPlayer.Position, self.baseData.UseSoundID)
NetUtil.Fire_C('CUseItemEvent', localPlayer, self.baseData.ItemID)
NetUtil.Fire_S('SUseItemEvent', localPlayer, self.baseData.ItemID)
end
--装备
function ItemBase:Equip()
NetUtil.Fire_C('UnequipCurEquipmentEvent', localPlayer)
wait(0.1)
Data.Player.curEquipmentID = self.baseData.ItemID
NetUtil.Fire_C('RemoveItemEvent', localPlayer, self.baseData.ItemID)
NetUtil.Fire_C('FsmTriggerEvent', localPlayer, 'TakeOutItemState')
GuiControl:UpdateUseBtnIcon(self.baseData.UseBtnIcon)
invoke(
function()
NetUtil.Fire_C('CTakeOutItemEvent', localPlayer, self.baseData.ItemID)
NetUtil.Fire_S('STakeOutItemEvent', localPlayer, self.baseData.ItemID)
local node1, node2 = string.match(self.derivedData.ParentNode, '([%w_]+).([%w_]+)')
------print(node1, node1)
local pNode = localPlayer.Avatar[node1][node2]
self.equipObj =
world:CreateInstance(
self.derivedData.ModelName,
self.derivedData.ModelName .. 'Instance',
pNode,
pNode.Position + self.derivedData.Offset,
pNode.Rotation + self.derivedData.Angle
)
self.equipObj.LocalPosition = self.derivedData.Offset
self.equipObj.LocalRotation = self.derivedData.Angle
self:ChangeNameColor()
GuiControl:UpdateTakeOffBtn()
end,
self.baseData.TakeOutTime
)
end
--取下装备
function ItemBase:Unequip()
Data.Player.curEquipmentID = 0
local effect = world:CreateInstance('UnequipEffect', 'UnequipEffect', self.equipObj.Parent, self.equipObj.Position)
SoundUtil.Play2DSE(localPlayer.UserId, 34)
invoke(
function()
self.equipObj:Destroy()
wait(.3)
effect:Destroy()
self:ChangeNameColor()
end,
0.2
)
NetUtil.Fire_C('FsmTriggerEvent', localPlayer, 'IdleState')
--wait(self.baseData.TakeOutTime)
Data.Player.bag[self.baseData.ItemID].count = Data.Player.bag[self.baseData.ItemID].count + 1
GuiControl:UpdateTakeOffBtn()
GuiControl:UpdateUseBtnIcon()
end
function ItemBase:ChangeNameColor()
NotReplicate(
function()
if Data.Player.curEquipmentID == 0 then
for k, v in pairs(world:FindPlayers()) do
if v ~= localPlayer and v.NameGui.NameBarTxt2.Color ~= Color(255, 255, 255, 255) then
v.NameGui.NameBarTxt2.Color = Color(255, 255, 255, 255)
end
end
else
for k, v in pairs(world:FindPlayers()) do
if v ~= localPlayer and v.NameGui.NameBarTxt2.Color ~= Color(255, 0, 0, 255) then
v.NameGui.NameBarTxt2.Color = Color(255, 0, 0, 255)
end
end
end
end
)
end
function ItemBase:Update(dt)
self:ChangeNameColor()
end
return ItemBase
|
-- Run: lua example.lua
require "lunit-globalized"
local simple = lunit.create_testcase( "simple" )
function simple.test_success()
assert_true( true, "This test never fails.")
end
function simple.test_failure()
assert_true( "Hello World!", "This test always fails!")
end
local enhanced = lunit.create_testcase( "enhanced" )
local foobar = nil
function enhanced.setup()
foobar = "Hello World"
end
function enhanced.teardown()
foobar = nil
end
function enhanced.test1()
assert_equal("Hello World", foobar)
foobar = string.sub(foobar, 1, 5)
assert_equal("Hello", foobar)
end
function enhanced.test2()
assert_equal("Hello World", foobar)
foobar = string.sub(foobar, -5)
assert_equal("World", foobar)
end
lunit.main(...)
|
local json = require('json')
local timer = require('timer')
local miniz = require('miniz')
local websocket = require('coro-websocket')
local Emitter = require('utils/Emitter')
local Mutex = require('utils/Mutex')
local Stopwatch = require('utils/Stopwatch')
local EventHandler = require('client/EventHandler')
local constants = require('constants')
local enums = require('enums')
local logLevel = enums.logLevel
local inflate = miniz.inflate
local min, max, random = math.min, math.max, math.random
local encode, decode, null = json.encode, json.decode, json.null
local ws_parseUrl, ws_connect = websocket.parseUrl, websocket.connect
local format = string.format
local sleep = timer.sleep
local setInterval, clearInterval = timer.setInterval, timer.clearInterval
local concat = table.concat
local wrap = coroutine.wrap
local ID_DELAY = constants.ID_DELAY
local GATEWAY_VERSION = constants.GATEWAY_VERSION
local GATEWAY_DELAY = constants.GATEWAY_DELAY
local DISPATCH = 0
local HEARTBEAT = 1
local IDENTIFY = 2
local STATUS_UPDATE = 3
local VOICE_STATE_UPDATE = 4
-- local VOICE_SERVER_PING = 5 -- TODO
local RESUME = 6
local RECONNECT = 7
local REQUEST_GUILD_MEMBERS = 8
local INVALID_SESSION = 9
local HELLO = 10
local HEARTBEAT_ACK = 11
local GUILD_SYNC = 12
local TEXT = 1
local BINARY = 2
local CLOSE = 8
local ignore = {
['CALL_DELETE'] = true,
['CHANNEL_PINS_ACK'] = true,
['GUILD_INTEGRATIONS_UPDATE'] = true,
['MESSAGE_ACK'] = true,
['PRESENCES_REPLACE'] = true,
['USER_SETTINGS_UPDATE'] = true,
}
local Shard = require('class')('Shard', Emitter)
function Shard:__init(id, client)
Emitter.__init(self)
self._id = id
self._client = client
self._mutex = Mutex()
self._sw = Stopwatch()
self._backoff = 1000
end
for name in pairs(logLevel) do
Shard[name] = function(self, fmt, ...)
local client = self._client
return client[name](client, format('Shard %i : %s', self._id, fmt), ...)
end
end
function Shard:__tostring()
return format('Shard: %i', self._id)
end
local function connect(url)
local options = assert(ws_parseUrl(url))
options.pathname = format('/?v=%i&encoding=json', GATEWAY_VERSION)
return assert(ws_connect(options))
end
local function getReconnectTime(self, n, m)
return self._backoff * (n + random() * (m - n))
end
local function incrementReconnectTime(self)
self._backoff = min(self._backoff * 2, 30000)
end
local function decrementReconnectTime(self)
self._backoff = max(self._backoff / 2, 1000)
end
function Shard:connect(url, token)
local success, res, read, write = pcall(connect, url)
if success then
self._read = read
self._write = write
self._reconnect = nil
self:info('Connected to %s', url)
self:handlePayloads(token)
self:info('Disconnected')
else
self:error('Could not connect to %s (%s)', url, res) -- TODO: get new url?
end
if self._reconnect then
self:info('Reconnecting...')
return self:connect(url, token)
elseif self._reconnect == nil and self._client._options.autoReconnect then
local backoff = getReconnectTime(self, 0.9, 1.1)
incrementReconnectTime(self)
self:info('Reconnecting after %i ms...', backoff)
sleep(backoff)
return self:connect(url, token)
end
end
function Shard:disconnect(reconnect)
if not self._write then return end
self._reconnect = not not reconnect
self:stopHeartbeat()
self._write()
self._read = nil
self._write = nil
end
function Shard:handlePayloads(token)
local client = self._client
for message in self._read do
local opcode = message.opcode
local payload = message.payload
if opcode == BINARY then
payload = inflate(payload, 1)
elseif opcode == CLOSE then
local code, i = ('>H'):unpack(payload)
local msg = #payload > i and payload:sub(i) or 'Connection closed'
self:warning('%i - %s', code, msg)
break
end
client:emit('raw', payload)
payload = decode(payload, 1, null)
local s = payload.s
local t = payload.t
local d = payload.d
local op = payload.op
if t ~= null then
self:debug('WebSocket OP %s : %s : %s', op, t, s)
else
self:debug('WebSocket OP %s', op)
end
if op == DISPATCH then
self._seq = s
if not ignore[t] then
EventHandler[t](d, client, self)
end
elseif op == HEARTBEAT then
self:heartbeat()
elseif op == RECONNECT then
self:warning('Discord has requested a reconnection')
self:disconnect(true)
elseif op == INVALID_SESSION then
if payload.d and self._session_id then
self:info('Session invalidated, resuming...')
self:resume(token)
else
self:info('Session invalidated, re-identifying...')
sleep(random(1000, 5000))
self:identify(token)
end
elseif op == HELLO then
self:info('Received HELLO (%s)', concat(d._trace, ', '))
self:startHeartbeat(d.heartbeat_interval)
if self._session_id then
self:resume(token)
else
self:identify(token)
end
elseif op == HEARTBEAT_ACK then
self._waiting = nil
client:emit('heartbeat', self._id, self._sw.milliseconds)
elseif op then
self:warning('Unhandled WebSocket payload OP %i', op)
end
end
end
local function loop(self)
if self._waiting then
self._waiting = nil
self:warning('Previous heartbeat not acknowledged')
return wrap(self.disconnect)(self, true)
end
decrementReconnectTime(self)
wrap(self.heartbeat)(self)
end
function Shard:startHeartbeat(interval)
if self._heartbeat then
clearInterval(self._heartbeat)
end
self._heartbeat = setInterval(interval, loop, self)
end
function Shard:stopHeartbeat()
if self._heartbeat then
clearInterval(self._heartbeat)
end
self._heartbeat = nil
end
function Shard:identifyWait()
if self:waitFor('READY', 1.5 * ID_DELAY) then
return sleep(ID_DELAY)
end
end
local function send(self, op, d)
if not self._write then
return false, 'Not connected to gateway'
end
self._mutex:lock()
local success, err = self._write {opcode = TEXT, payload = encode {op = op, d = d}}
self._mutex:unlockAfter(GATEWAY_DELAY)
return success, err
end
function Shard:heartbeat()
self._sw:reset()
self._waiting = true
return send(self, HEARTBEAT, self._seq or json.null)
end
function Shard:identify(token)
local client = self._client
local mutex = client._mutex
local options = client._options
mutex:lock()
wrap(function()
self:identifyWait()
mutex:unlock()
end)()
self._seq = nil
self._session_id = nil
self._ready = false
self._loading = {guilds = {}, chunks = {}, syncs = {}}
return send(self, IDENTIFY, {
token = token,
properties = {
['$os'] = jit.os,
['$browser'] = 'Discordia',
['$device'] = 'Discordia',
['$referrer'] = '',
['$referring_domain'] = '',
},
compress = options.compress,
large_threshold = options.largeThreshold,
shard = {self._id, client._total_shard_count},
presence = next(client._presence) and client._presence,
})
end
function Shard:resume(token)
return send(self, RESUME, {
token = token,
session_id = self._session_id,
seq = self._seq
})
end
function Shard:requestGuildMembers(id)
return send(self, REQUEST_GUILD_MEMBERS, {
guild_id = id,
query = '',
limit = 0,
})
end
function Shard:updateStatus(presence)
return send(self, STATUS_UPDATE, presence)
end
function Shard:updateVoice(guild_id, channel_id, self_mute, self_deaf)
return send(self, VOICE_STATE_UPDATE, {
guild_id = guild_id,
channel_id = channel_id or null,
self_mute = self_mute or false,
self_deaf = self_deaf or false,
})
end
function Shard:syncGuilds(ids)
return send(self, GUILD_SYNC, ids)
end
return Shard
|
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937'
description '[Grievance] Loading Screen'
version '1.3.0'
loadscreen 'ui/index.html'
files {
'ui/index.html',
'ui/normalize.min.css',
'ui/main.css',
'ui/main.js',
'ui/bg.jpg',
'ui/logo.png',
-- Theme: Autumn
-- 'ui/main-autumn.css',
-- 'ui/bg-autumn.jpg'
}
|
--this is incredibly hacky
local CollectionService = game:GetService("CollectionService")
return function(Sunshine, entity)
local water = entity.water
local model = entity.model
local transform = entity.transform
local collider = entity.collider
if water and collider and model and transform then
local character
Sunshine:update(function()
local touchedEntity
for _,hitEntity in pairs(collider.hitEntities) do
if hitEntity and hitEntity.hydrophobic and hitEntity.health then
hitEntity.health.health = 0
elseif hitEntity and hitEntity.character and hitEntity.character.controllable
then
character = hitEntity
character.character.swimming = true
touchedEntity = true
end
end
if character and not touchedEntity then
character.character.swimming = false
character = nil
end
for _,p in pairs(model.model:GetDescendants()) do
if CollectionService:HasTag(p, "forcefield") then
p.Size = Vector3.new(transform.size.X,0.05,transform.size.Z)
p.CFrame = CFrame.new(transform.cFrame.Position + Vector3.new(0,transform.size.Y/2,0))
end
end
end, entity)
end
end
|
return
{
HOOK_PLAYER_RIGHT_CLICKING_ENTITY =
{
CalledWhen = "A player has right-clicked an entity. Plugins may override / refuse.",
DefaultFnName = "OnPlayerRightClickingEntity", -- also used as pagename
Desc = [[
This hook is called when the {{cPlayer|player}} right-clicks an {{cEntity|entity}}. Plugins may
override the default behavior or even cancel the default processing.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has right-clicked the entity" },
{ Name = "Entity", Type = "{{cEntity}} descendant", Notes = "The entity that has been right-clicked" },
},
Returns = [[
If the functino returns false or no value, Cuberite calls other plugins' callbacks and finally does
the default processing for the right-click. If the function returns true, no other callbacks are
called and the default processing is skipped.
]],
}, -- HOOK_PLAYER_RIGHT_CLICKING_ENTITY
}
|
--[[
Copyright © 2013-2015, Giuliano Riccio
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of findAll nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Giuliano Riccio BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]
_addon.name = 'findAll'
_addon.author = 'Zohno'
_addon.version = '1.20150105'
_addon.commands = {'findall'}
require('chat')
require('lists')
require('logger')
require('sets')
require('tables')
require('strings')
json = require('json')
file = require('files')
slips = require('slips')
config = require('config')
texts = require('texts')
res = require('resources')
defaults = {}
defaults.Track = ''
defaults.Tracker = {}
settings = config.load(defaults)
tracker = texts.new(settings.Track, settings.Tracker, settings)
do
config.register(settings, function(settings)
tracker:text(settings.Track)
tracker:visible(settings.Track ~= '' and windower.ffxi.get_info().logged_in)
end)
local bag_ids = res.bags:rekey('english'):key_map(string.lower):map(table.get-{'id'})
local variable_cache = S{}
tracker:register_event('reload', function()
for variable in tracker:it() do
local bag_name, search = variable:match('(.*):(.*)')
local bag = bag_name == 'all' and 'all' or bag_ids[bag_name:lower()]
if not bag and bag_name ~= 'all' then
warning('Unknown bag: %s':format(bag_name))
else
if not S{'$freespace', '$usedspace', '$maxspace'}:contains(search:lower()) then
local items = S(res.items:name(windower.wc_match-{search})) + S(res.items:name_log(windower.wc_match-{search}))
if items:empty() then
warning('No items matching "%s" found.':format(search))
else
variable_cache:add({
name = variable,
bag = bag,
type = 'item',
ids = items:map(table.get-{'id'}),
search = search,
})
end
else
variable_cache:add({
name = variable,
bag = bag,
type = 'info',
search = search,
})
end
end
end
end)
do
local update = T{}
local search_bag = function(bag, ids)
return bag:filter(function(item)
return type(item) == 'table' and ids:contains(item.id)
end):reduce(function(acc, item)
return type(item) == 'table' and item.count + acc or acc
end, 0)
end
local last_check = 0
windower.register_event('prerender', function()
if os.clock() - last_check < 0.25 then
return
end
last_check = os.clock()
local items = T{}
for variable in variable_cache:it() do
if variable.type == 'info' then
local info
if variable.bag == 'all' then
info = {
max = 0,
count = 0
}
for bag_info in T(windower.ffxi.get_bag_info()):it() do
info.max = info.max + bag_info.max
info.count = info.count + bag_info.count
end
else
info = windower.ffxi.get_bag_info(variable.bag)
end
update[variable.name] =
variable.search == '$freespace' and (info.max - info.count)
or variable.search == '$usedspace' and info.count
or variable.search == '$maxspace' and info.max
or nil
elseif variable.type == 'item' then
if variable.bag == 'all' then
for id in bag_ids:it() do
if not items[id] then
items[id] = T(windower.ffxi.get_items(id))
end
end
else
if not items[variable.bag] then
items[variable.bag] = T(windower.ffxi.get_items(variable.bag))
end
end
update[variable.name] = variable.bag ~= 'all' and search_bag(items[variable.bag], variable.ids) or items:reduce(function(acc, bag)
return acc + search_bag(bag, variable.ids)
end, 0)
end
end
if not update:empty() then
tracker:update(update)
end
end)
end
end
zone_search = true
first_pass = true
time_out_offset = 0
next_sequence_offset = 0
item_names = T{}
global_storages = T{}
storages_path = 'data/storages.json'
storages_order = L{'temporary', 'inventory', 'wardrobe', 'safe', 'storage', 'locker', 'satchel', 'sack', 'case'}
storage_slips_order = L{'slip 01', 'slip 02', 'slip 03', 'slip 04', 'slip 05', 'slip 06', 'slip 07', 'slip 08', 'slip 09', 'slip 10', 'slip 11', 'slip 12', 'slip 13', 'slip 14', 'slip 15', 'slip 16', 'slip 17', 'slip 18', 'slip 19', 'slip 20', 'slip 21'}
merged_storages_orders = L{}:extend(storages_order):extend(storage_slips_order)
function search(query, export)
update()
if query:length() == 0 then
return
end
local character_set = S{}
local character_filter = S{}
local terms = ''
for _, query_element in ipairs(query) do
local char = query_element:match('^([:!]%a+)$')
if char then
if char:sub(1, 1) == '!' then
character_filter:add(char:sub(2):lower():gsub("^%l", string.upper))
else
character_set:add(char:sub(2):lower():gsub("^%l", string.upper))
end
else
terms = query_element
end
end
if character_set:length() == 0 and terms == '' then
return
end
local new_item_ids = S{}
for character_name, storages in pairs(global_storages) do
for storage_name, storage in pairs(storages) do
if storage_name ~= 'gil' then
for id, quantity in pairs(storage) do
id = tostring(id)
if item_names[id] == nil then
new_item_ids:add(tostring(id))
end
end
end
end
end
for id,_ in pairs(new_item_ids) do
local item = res.items[tonumber(id)]
if item then
item_names[id] = {
['name'] = item.name,
['long_name'] = item.name_log
}
end
end
local results_items = S{}
local terms_pattern = ''
if terms ~= '' then
terms_pattern = terms:escape():gsub('%a', function(char) return string.format("[%s%s]", char:lower(), char:upper()) end)
end
for id, names in pairs(item_names) do
if terms_pattern == '' or item_names[id].name:find(terms_pattern)
or item_names[id].long_name:find(terms_pattern)
then
results_items:add(id)
end
end
log('Searching: '..query:concat(' '))
local no_results = true
local sorted_names = global_storages:keyset():sort()
:reverse()
if windower.ffxi.get_info().logged_in then
sorted_names = sorted_names:append(sorted_names:remove(sorted_names:find(windower.ffxi.get_player().name)))
:reverse()
end
local export_file
if export ~= nil then
export_file = io.open(windower.addon_path..'data/'..export, 'w')
if export_file == nil then
error('The file "'..export..'" cannot be created.')
else
export_file:write('"char";"storage";"item";"quantity"\n')
end
end
local total_quantity = 0
for _, character_name in ipairs(sorted_names) do
if (character_set:length() == 0 or character_set:contains(character_name)) and not character_filter:contains(character_name) then
local storages = global_storages[character_name]
for _, storage_name in ipairs(merged_storages_orders) do
local results = L{}
if storage_name~= 'gil' and storages[storage_name] ~= nil then
for id, quantity in pairs(storages[storage_name]) do
if results_items:contains(id) then
if terms_pattern ~= '' then
total_quantity = total_quantity + quantity
results:append(
(character_name..'/'..storage_name..':'):color(259)..' '..
item_names[id].name:gsub('('..terms_pattern..')', ('%1'):color(258))..
(item_names[id].name:match(terms_pattern) and '' or ' ['..item_names[id].long_name:gsub('('..terms_pattern..')', ('%1'):color(258))..']')..
(quantity > 1 and ' '..('('..quantity..')'):color(259) or '')
)
else
results:append(
(character_name..'/'..storage_name..':'):color(259)..' '..item_names[id].name..
(quantity > 1 and ' '..('('..quantity..')'):color(259) or '')
)
end
if export_file ~= nil then
export_file:write('"'..character_name..'";"'..storage_name..'";"'..item_names[id].name..'";"'..quantity..'"\n')
end
no_results = false
end
end
results:sort()
for i, result in ipairs(results) do
log(result)
end
end
end
end
end
if total_quantity > 0 then
log('Total: ' .. total_quantity)
end
if export_file ~= nil then
export_file:close()
log('The results have been saved to "'..export..'"')
end
if no_results then
if terms ~= '' then
if character_set:length() == 0 and character_filter:length() == 0 then
log('You have no items that match \''..terms..'\'.')
else
log('You have no items that match \''..terms..'\' on the specified characters.')
end
else
log('You have no items on the specified characters.')
end
end
end
function get_storages()
local items = windower.ffxi.get_items()
local storages = {}
if not items then
return false
end
storages.gil = items.gil
for _, storage_name in ipairs(storages_order) do
storages[storage_name] = T{}
for _, data in ipairs(items[storage_name]) do
if type(data) == 'table' then
if data.id ~= 0 then
local id = tostring(data.id)
storages[storage_name][id] = (storages[storage_name][id] or 0) + data.count
end
end
end
end
local slip_storages = slips.get_player_items()
for _, slip_id in ipairs(slips.storages) do
local slip_name = 'slip '..tostring(slips.get_slip_number_by_id(slip_id)):lpad('0', 2)
storages[slip_name] = T{}
for _, id in ipairs(slip_storages[slip_id]) do
storages[slip_name][tostring(id)] = 1
end
end
return storages
end
function update()
if not windower.ffxi.get_info().logged_in then
print('You have to be logged in to use this addon.')
return false
end
if zone_search == false then
notice('findAll has not detected a fully loaded inventory yet.')
return false
end
local player_name = windower.ffxi.get_player().name
local storages_file = file.new(storages_path)
if not storages_file:exists() then
storages_file:create()
end
global_storages = json.read(storages_file)
if global_storages == nil then
global_storages = T{}
end
local temp_storages = get_storages()
if temp_storages then
global_storages[player_name] = temp_storages
else
return false
end
-- build json string
local characters_json = L{}
for character_name, storages in pairs(global_storages) do
local storages_json = L{}
for storage_name, storage in pairs(storages) do
if storage_name == 'gil' then
storages_json:append('"'..storage_name..'":'..storage)
elseif storage_name ~= 'temporary' then
local items_json = L{}
for id, quantity in pairs(storage) do
items_json:append('"'..id..'":'..quantity)
end
storages_json:append('"'..storage_name..'":{'..items_json:concat(',')..'}')
end
end
characters_json:append('"'..character_name..'":{'..storages_json:concat(',')..'}')
end
storages_file:write('{'..characters_json:concat(',\n')..'}')
collectgarbage()
return true
end
windower.register_event('load', update:cond(function() return windower.ffxi.get_info().logged_in end))
windower.register_event('incoming chunk', function(id,original,modified,injected,blocked)
local seq = original:byte(4)*256+original:byte(3)
if (next_sequence and seq + next_sequence_offset >= next_sequence) or (time_out and seq + time_out_offset >= time_out) then
zone_search = true
update()
next_sequence = nil
time_out = nil
sequence_offset = 0
end
if id == 0x00A then -- First packet of a new zone
zone_search = false
time_out = seq+33
if time_out < time_out%0x100 then
time_out_offset = 256
end
-- elseif id == 0x01D then
-- This packet indicates that the temporary item structure should be copied over to
-- the real item structure, accessed with get_items(). Thus we wait one packet and
-- then trigger an update.
-- zone_search = true
-- next_sequence = seq+128
-- if next_sequence < next_sequence%0x100 then
-- next_sequence_offset = 256
-- end
elseif (id == 0x1E or id == 0x1F or id == 0x20) and zone_search then
-- Inventory Finished packets aren't sent for trades and such, so this is more
-- of a catch-all approach. There is a subtantial delay to avoid spam writing.
next_sequence = seq+128
if next_sequence < next_sequence%0x100 then
next_sequence_offset = 256
end
end
end)
windower.register_event('ipc message', function(str)
if str == 'findAll update' then
update()
end
end)
handle_command = function(...)
if first_pass then
first_pass = false
windower.send_ipc_message('findAll update')
windower.send_command('wait 0.05;findall '..table.concat({...},' '))
else
first_pass = true
local params = L{...}
local query = L{}
local export = nil
-- convert command line params (SJIS) to UTF-8
for i, elm in ipairs(params) do
params[i] = windower.from_shift_jis(elm)
end
while params:length() > 0 and params[1]:match('^[:!]%a+$') do
query:append(params:remove(1))
end
if params:length() > 0 then
export = params[params:length()]:match('^--export=(.+)$') or params[params:length()]:match('^-e(.+)$')
if export ~= nil then
export = export:gsub('%.csv$', '')..'.csv'
params:remove(params:length())
if export:match('['..('\\/:*?"<>|'):escape()..']') then
export = nil
error('The filename cannot contain any of the following characters: \\ / : * ? " < > |')
end
end
query:append(params:concat(' '))
end
search(query, export)
end
end
windower.register_event('unhandled command', function(command, ...)
if command:lower() == 'find' then
local me = windower.ffxi.get_mob_by_target('me')
if me then
handle_command(':%s':format(me.name), ...)
else
handle_command(...)
end
end
end)
windower.register_event('addon command', handle_command)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.