content
stringlengths 5
1.05M
|
---|
local spell = {}
spell = {}
spell["numericaltype"] = [[Absolute Value]]
spell["element"] = [[Almighty]]
spell["cost"] = 99
spell["desc"] = [[I'll show you my true power!
Empties HP and SP to near-null but deals massive damage to the enemy *CHAOS ONLY*]]
spell["numberofhits"] = 5
spell["conditional"] = [[if battle.end REMOVE Chaos FROM party]]
spell["hitchance"] = 100
spell["target"] = [[All Enemy]]
spell["passive"] = false
--a function: statuschance
spell["name"] = [[Chaos!]]
--a function: status
spell["targetattribute"] = [[HP]]
spell["numericalvalue"] = 9999999
spell["costtype"] = [[HP/SP(%)]]
function spell.activate()
state.context.cost(spell.costtype, spell.cost)
state.context.attack(spell, nil, state.battle.participants[state.battle.open])
end
return spell
|
util.AddNetworkString("OCRP_UpdateLootingTable")
sound.Add( {
name = "OCRP_LootingSound",
channel = CHAN_BODY,
volume = .1,
pitch = {95, 110},
sound = "physics/body/body_medium_scrape_rough_loop1.wav"
} )
function PMETA:LootItem(item)
self:StopSound("OCRP_LootingSound")
local target = self.LootingEntity
if not target or not target:IsValid() or not target.Lootable then return end
if not target.player or not target.player:IsValid() or target.player:Alive() then return end
if not self:HasSkill("skill_loot", GAMEMODE.OCRP_Items[item].LootData.Level) then return end
if not target.player:HasItem(item, 1) then return end
local chance = math.random(1,2)
if chance == 2 then self:Hint("Looting failed.") return end
target.player:RemoveItem(item, 1)
local DropedEnt = nil
if item == "item_radio" then
DropedEnt = ents.Create("ocrp_radio")
else
DropedEnt = ents.Create("item_base")
end
DropedEnt:SetNWString("Class", item)
DropedEnt:SetNWInt("Owner",self:EntIndex())
DropedEnt.Amount = 1
DropedEnt:SetPos(target:GetPos() + Vector(0,0,30))
DropedEnt:SetAngles(Angle(0,self:EyeAngles().y ,0))
DropedEnt:Spawn()
if DropedEnt:GetPhysicsObject():IsValid() then
DropedEnt:GetPhysicsObject():ApplyForceCenter(self:GetAimVector() * 120)
end
self:StoreItem(item, 1)
SV_PrintToAdmin(self, "LOOT-ITEM", "looted 1 " .. item .. " from " .. target.player:Nick() .. "'s body.")
self:Hint("Successfully looted 1 " .. GAMEMODE.OCRP_Items[item].Name)
net.Start("OCRP_UpdateLootingTable")
net.WriteTable(target.player.OCRPData["Inventory"])
net.Send(self)
end
net.Receive("OCRP_LootItem", function(len, ply)
ply.NextLoot = ply.NextLoot or CurTime()
if CurTime() < ply.NextLoot then return end
local item = net.ReadString()
ply.NextLoot = CurTime() + (GAMEMODE.OCRP_Items[item].LootData.Time or 2)
ply:LootItem(item)
end)
net.Receive("OCRP_BeginLooting", function(len, ply)
ply:EmitSound("OCRP_LootingSound", 40, 100)
end)
|
#!../../bin/exe/lua
-- setup some default search paths,
require("apps").default_paths()
local pack=require("wetgenes.pack")
local wstr=require("wetgenes.string")
local wwin=require("wetgenes.win")
local posix=require("posix")
--find device in /proc/bus/input/devices ?
local fp=assert(posix.open("/dev/input/event12", posix.O_NONBLOCK + posix.O_RDONLY ))
local hist={}
local deadzone=24
while true do
wwin.sleep(0.0001)
-- local pkt=posix.read(fp,16) -- 32bit
local pkt=posix.read(fp,24) -- 64bit hax
--print(pkt)
if pkt then
local Isecs,Imicros,Itype,Icode,Ivalue
if #pkt==24 then
Isecs=pack.read(pkt,"u32",0)
Imicros=pack.read(pkt,"u32",8)
Itype=pack.read(pkt,"u16",16)
Icode=pack.read(pkt,"u16",18)
Ivalue=pack.read(pkt,"u16",20)
elseif #pkt==16 then
Isecs=pack.read(pkt,"u32",0)
Imicros=pack.read(pkt,"u32",4)
Itype=pack.read(pkt,"u16",8)
Icode=pack.read(pkt,"u16",10)
Ivalue=pack.read(pkt,"u16",12)
end
if Itype==3 then
if Ivalue>128-deadzone and Ivalue<128+deadzone then Ivalue=128 end
end
local key=Itype..":"..Icode
local v=hist[key]
if v and (v ~= Ivalue) then v=false end
if not v then -- *new* values only, ignore most junk packets
hist[key]=Ivalue
local Itime=Isecs+(Imicros/1000000)
print(Itime,Itype,Icode,Ivalue)
end
end
--[[
struct input_event {
struct timeval time;
unsigned short type;
unsigned short code;
unsigned int value;
};
]]
end
|
module('love.audio')
function getActiveSourceCount() end
function getDistanceModel() end
function getDopplerScale() end
function getSourceCount() end
function getOrientation() end
function getPosition() end
function getVelocity() end
function getVolume() end
function newSource() end
function pause() end
function play() end
function resume() end
function rewind() end
function setDistanceModel() end
function setDopplerScale() end
function setOrientation() end
function setPosition() end
function setVelocity() end
function setVolume() end
function stop() end
|
function filterSubSections(txt)
if txt == '' then
return ''
else
return '<div id="subsections">\n<h3>Subsections</h3>\n' .. txt .. '\n</div>'
end
end
|
vim.cmd([[
augroup auto_read
autocmd!
autocmd FocusGained,BufEnter,CursorHold,CursorHoldI *
\ if mode() == 'n' && getcmdwintype() == '' | checktime | endif
autocmd FileChangedShellPost * echohl WarningMsg
\ | echo "File changed on disk. Buffer reloaded!" | echohl None
augroup END
function TwoSpacesSoftTabs()
set tabstop=2
set shiftwidth=2
set softtabstop=2
set expandtab
endfunction
function EightSpacesHardTabs()
set tabstop=8
set shiftwidth=8
set softtabstop=8
set noexpandtab
endfunction
function EightSpacesSoftTabs()
set tabstop=8
set shiftwidth=4
set softtabstop=8
set expandtab
endfunction
function FourSpacesSoftTabs()
set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab
endfunction
function FourSpacesHardTabs()
set tabstop=4
set shiftwidth=4
set softtabstop=4
set noexpandtab
endfunction
function OpenSystemFile()
call system(join('open', expand('%:p'), ' '))
endfunction
" =============================================================================
" Set filetypes for some extensions
" =============================================================================
augroup FILETYPE_SETTINGS
autocmd!
autocmd BufRead *.plot set filetype=gnuplot
autocmd BufRead *.md set filetype=markdown
autocmd BufRead *.lds set filetype=ld
autocmd BufRead *.rb set filetype=ruby
autocmd BufRead *.tex set filetype=tex
autocmd BufRead *.trm set filetype=c
autocmd BufRead *.xlsx.axlsx set filetype=ruby
autocmd BufRead *.h,*.c,*.cc,*.cpp,*.C,*.ino set filetype=c
autocmd BufRead *.tex,*.sty set filetype=tex
autocmd BufRead *.yml,*.yaml,Sakefile set filetype=yaml
autocmd BufRead CHANGELOG setlocal filetype=text
autocmd BufRead *.pl set filetype=prolog
autocmd BufRead *.tex set filetype=tex
autocmd BufWrite *.tex call CompileAndLoad()
autocmd BufReadPost *.jpg call OpenSystemFile()
autocmd BufReadPost *.png call OpenSystemFile()
autocmd BufReadPost *.gif call OpenSystemFile()
autocmd BufReadPost *.pdf call OpenSystemFile()
augroup END
augroup FILE_SPACINGS
autocmd!
autocmd FileType c call FourSpacesSoftTabs()
autocmd FileType java call TwoSpacesSoftTabs()
autocmd FileType python call FourSpacesSoftTabs()
autocmd FileType tex call FourSpacesSoftTabs()
autocmd FileType sh call FourSpacesHardTabs()
autocmd FileType perl call EightSpacesHardTabs()
autocmd FileType html call TwoSpacesSoftTabs()
autocmd FileType haskell call TwoSpacesSoftTabs()
autocmd FileType scheme call TwoSpacesSoftTabs()
autocmd FileType yacc call FourSpacesHardTabs()
augroup END
augroup FILE_LEADERS
autocmd!
autocmd FileType tex let maplocalleader = "\<Space>"
augroup END
]])
|
--[[
[{
"pos": {
"x": 100,
"y": 200,
"z": 300
},
"name": "",
"push": false,
"pull": true,
"radius": 120
}]
--]]
local jumppoints = {}
local old_calculate_power = jumpdrive.calculate_power
jumpdrive.calculate_power = function(radius, distance, sourcePos, targetPos)
for _, jumppoint in ipairs(jumppoints) do
-- check pull distance
local pos_distance = vector.distance(targetPos, jumppoint.pos)
if jumppoint.push then
-- check push distance
pos_distance = vector.distance(sourcePos, jumppoint.pos)
end
if pos_distance < jumppoint.radius then
return 0
end
end
return old_calculate_power(radius, distance, sourcePos, targetPos)
end
local load_data = function()
local path = minetest.get_worldpath().."/jumppoints.json";
local file = io.open( path, "r" );
if( file ) then
local data = file:read("*all");
local jp = minetest.parse_json(data);
file:close();
if jp then
jumppoints = jp
local count = 0
for _, jumppoint in ipairs(jumppoints) do
print("[pandorabox_custom] jumppoints '" .. jumppoint.name .. "', pos: " ..
minetest.pos_to_string(jumppoint.pos) .. ", radius: " .. jumppoint.radius)
count = count + 1
end
print("[pandorabox_custom] Loaded " .. count .. " jumppoints")
else
return false
end
else
print("[pandorabox_custom] Error: Savefile '" .. path .. "' not found.")
end
return true
end
load_data()
minetest.register_chatcommand("jumppoints_reload", {
description = "reload jumppoints.json",
privs = { server = true },
func = function(name, param)
if load_data() then
return true, "reload successful"
else
return true, "error, could not load jumppoints.json"
end
end
})
|
---@module PlayerAnimation 枪械模块:玩家的动画控制类
---@copyright Lilith Games, Avatar Team
---@author Sharif Ma
local PlayerAnimation = class('PlayerAnimation')
---PlayerAnimation类的构造函数
---@param _gun GunBase
function PlayerAnimation:initialize(_gun)
self.gun = _gun
self.id = _gun.animationId
self.player = _gun.character
---玩家的右肩骨骼点
self.bone_R_UpperArm = _gun.character.Avatar.Bone_R_UpperArm
---动画配置初始化
GunBase.static.utility:InitGunAnimationConfig(self)
---设置动画的播放层级
self.player.Avatar:SetBlendSubtree(Enum.BodyPart.UpperBody, self.animationTree)
self.shoulderRayMinDistance = GunConfig.GlobalConfig.ShoulderRayMinDistance
---当前是否处于不可射击状态
self.noShootingState = false
end
function PlayerAnimation:Update(_dt)
---奔跑状态下进行持枪状态,站立状态下进行瞄准
if self.player.State == Enum.CharacterState.Walk or self.noShootingState then
self.player:StopAim()
else
self.player:Aim(world.CurrentCamera.Rotation.x * -1, 2)
end
---是否靠近一个东西导致不可开枪检测
if self.bone_R_UpperArm then
local raycastResults =
Physics:RaycastAll(
self.bone_R_UpperArm.Position,
self.bone_R_UpperArm.Position + self.player.Forward * self.shoulderRayMinDistance,
false
)
local state = false
for k, v in pairs(raycastResults.HitObjectAll) do
if v.Block and not ParentPlayer(v) and v.CollisionGroup ~= 10 then
---前方有阻挡
state = true
end
end
self.noShootingState = state
end
end
function PlayerAnimation:FixUpdate(_dt)
end
---装备武器的动作
function PlayerAnimation:EquipWeapon()
if self.equip and #self.equip > 0 then
local speed = self.equip[2] and tonumber(self.equip[2]) or 1
self.player.Avatar:PlayAnimation(self.equip[1], self.animationTree, 1, 0, true, false, speed)
else
self.player:Equip(1)
end
end
---换子弹的动作
function PlayerAnimation:MagazineLoadStarted()
if self.magazineLoadStarted and #self.magazineLoadStarted > 0 then
local speed = self.magazineLoadStarted[2] and tonumber(self.magazineLoadStarted[2]) or 1
self.player.Avatar:PlayAnimation(self.magazineLoadStarted[1], self.animationTree, 1, 0, true, false, speed)
else
self.player:Reload(1)
end
end
---拉枪栓结束
function PlayerAnimation:PumpStopped()
if self.pumpStopped and #self.pumpStopped > 0 then
local speed = self.pumpStopped[2] and tonumber(self.pumpStopped[2]) or 1
self.player.Avatar:PlayAnimation(self.pumpStopped[1], self.animationTree, 1, 0, true, false, speed)
else
end
end
---开火动作
function PlayerAnimation:Fired()
if self.noShootingState then
return
end
if self.fired and #self.fired > 0 then
local speed = self.fired[2] and tonumber(self.fired[2]) or 1
self.player.Avatar:PlayAnimation(self.fired[1], self.animationTree, 1, 0, true, false, speed)
else
self.player:Attack(1, 1)
end
end
---空仓动作
function PlayerAnimation:EmptyFire()
if self.emptyFire and #self.emptyFire > 0 then
local speed = self.emptyFire[2] and tonumber(self.emptyFire[2]) or 1
self.player.Avatar:PlayAnimation(self.emptyFire[1], self.animationTree, 1, 0, true, false, speed)
else
end
end
---拉枪栓动作
function PlayerAnimation:PumpStarted()
if self.pumpStarted and #self.pumpStarted > 0 then
local speed = self.pumpStarted[2] and tonumber(self.pumpStarted[2]) or 1
self.player.Avatar:PlayAnimation(self.pumpStarted[1], self.animationTree, 1, 0, true, false, speed)
else
end
end
---开火后
function PlayerAnimation:FireStopped()
if self.fireStopped and #self.fireStopped > 0 then
local speed = self.fireStopped[2] and tonumber(self.fireStopped[2]) or 1
self.player.Avatar:PlayAnimation(self.fireStopped[1], self.animationTree, 1, 0, true, false, speed)
else
end
end
function PlayerAnimation:Destructor()
ClearTable(self)
self = nil
end
return PlayerAnimation
|
object_building_mustafar_particle_must_lava_fire = object_building_mustafar_particle_shared_must_lava_fire:new {
}
ObjectTemplates:addTemplate(object_building_mustafar_particle_must_lava_fire, "object/building/mustafar/particle/must_lava_fire.iff")
|
--[[
TPB (Transaction Parameter Block) structure: encode the options for creating transactions
encode(tpb_options_t) -> TPB encoded string.
USAGE:
- pass the encoded TPB to to isc_start_multiple() to start a transaction.
- table reservation options occupy the array part of tpb_options_t, one numerical index
for each table that you want to reserve. the format for reserving a table is
{table_reservation_mode_code, table_reservation_lock_code, table_name}. example:
{'isc_tpb_shared','isc_tpb_lock_read','MYTABLE'}
]]
module(...,require 'fbclient.module')
local pb = require 'fbclient.pb'
local codes = {
-- access mode: read | write
isc_tpb_read = 8, --true: read only access
isc_tpb_write = 9, --true: read/write access
-- isolation level: consistency | concurrency | (read_commited + (rec_version | no_rec_version))
isc_tpb_consistency = 1, --true: repeatable reads but locks the tables from updating by other transactions
isc_tpb_concurrency = 2, --true: repeatable reads without locking: gets the best out of MVCC
isc_tpb_read_committed = 15, --true: see commited changes from other transactions
isc_tpb_rec_version = 17, --true: pending updates don't block reads; use along isc_tpb_read_committed
isc_tpb_no_rec_version = 18, --true: pending updates do block reads; use along isc_tpb_read_committed
-- lock resolution: wait | nowait
isc_tpb_wait = 6, --true: in case of deadlock, wait for isc_tpb_lock_timeout seconds before breaking
isc_tpb_nowait = 7, --true: in case of deadlock, break immediately
isc_tpb_lock_timeout = 21, --number: use this timeout instead of server's configured default; fb 2.0+
-- other options:
--isc_tpb_verb_time = 12, --?: intended for support timing of constraints. not used yet
--isc_tpb_commit_time = 13, --?: intended for support timing of constraints. not used yet
isc_tpb_ignore_limbo = 14, --true: ignore records made by limbo transactions
isc_tpb_autocommit = 16, --true: commit after each statement
isc_tpb_restart_requests = 19, --true: automatically restart requests in a new transaction after failure
isc_tpb_no_auto_undo = 20, --true: refrain from keeping the log used to undo changes in the event of a rollback
}
local table_reservation_mode_codes = {
isc_tpb_shared = 3,
isc_tpb_protected = 4,
isc_tpb_exclusive = 5,
}
local table_reservation_lock_codes = {
isc_tpb_lock_read = 10,
isc_tpb_lock_write = 11,
}
-- parameter: {'isc_tpb_ shared/protected/exclusive', 'isc_tpb_lock_ read/write', <table_name>}
-- note: the reason for creating this special encoder is because this is an array of sequences of options.
local function encode_table_reservation(t)
local mode_opt = assert(table_reservation_mode_codes[t[1]], 'table reservation mode string expected at index 1')
local lock_opt = assert(table_reservation_lock_codes[t[2]], 'table reservation lock string expected at index 2')
local table_name = assert(t[3], 'table name expected at index 3')
--NOTE: the IB6 Api Guide is wrong about this sequence (see CORE-1416)
return struct.pack('BBc0B',lock_opt,#table_name,table_name,mode_opt)
end
local encoders = {
isc_tpb_read = pb.encode_none,
isc_tpb_write = pb.encode_none,
isc_tpb_consistency = pb.encode_none,
isc_tpb_concurrency = pb.encode_none,
isc_tpb_read_committed = pb.encode_none,
isc_tpb_rec_version = pb.encode_none,
isc_tpb_no_rec_version = pb.encode_none,
isc_tpb_wait = pb.encode_none,
isc_tpb_nowait = pb.encode_none,
isc_tpb_lock_timeout = pb.encode_uint,
--isc_tpb_verb_time = nil,
--isc_tpb_commit_time = nil,
isc_tpb_ignore_limbo = pb.encode_none,
isc_tpb_autocommit = pb.encode_none,
isc_tpb_restart_requests= pb.encode_none,
isc_tpb_no_auto_undo = pb.encode_none,
}
-- in addition to encoding the options in the codes table, we encode the array part of opts, which
-- is used for table reservation.
function encode(opts)
-- encode table reservation options, if any
local res_opts = ''
if opts then
for i,v in ipairs(opts) do
res_opts = res_opts..encode_table_reservation(v)
end
end
-- encode normal options and glue them with table reservation options
return pb.encode('TPB', '\3', opts, codes, encoders)..res_opts
end
|
--[[
Title: Draw
Our client-side draw functions
]]
--[[
Function: csayDraw
Draws a csay text on the screen.
Parameters:
msg - The message to draw.
color - *(Optional, defaults to 255, 255, 255, 255)* The color of the text
duration - *(Optional, defaults to 5)* The length of the text
fade - *(Optional, defaults to 0.5)* The length of fade time
Revisions:
v2.10 - Added fade parameter
]]
function ULib.csayDraw( msg, color, duration, fade )
color = color or Color( 255, 255, 255, 255 )
duration = duration or 5
fade = fade or 0.5
local start = CurTime()
local function drawToScreen()
local alpha = 255
local dtime = CurTime() - start
if dtime > duration then -- Our time has come :'(
hook.Remove( "HUDPaint", "CSayHelperDraw" )
return
end
if fade - dtime > 0 then -- beginning fade
alpha = (fade - dtime) / fade -- 0 to 1
alpha = 1 - alpha -- Reverse
alpha = alpha * 255
end
if duration - dtime < fade then -- ending fade
alpha = (duration - dtime) / fade -- 0 to 1
alpha = alpha * 255
end
color.a = alpha
draw.DrawText( msg, "TargetID", ScrW() * 0.5, ScrH() * 0.25, color, TEXT_ALIGN_CENTER )
end
hook.Add( "HUDPaint", "CSayHelperDraw", drawToScreen )
end
|
---@type table<string,TagTooltipData>
UI.Tooltip.TagTooltips = {}
UI.Tooltip.HasTagTooltipData = false
---@class TagTooltipData
---@field Title TranslatedString
---@field Description TranslatedString
local TagTooltips = UI.Tooltip.TagTooltips
---@type TranslatedString
local ts = Classes.TranslatedString
local chaosDamagePattern = "<font color=\"#C80030\">([%d-%s]+)</font>"
---@param character EclCharacter
---@param status EclStatus
---@param tooltip TooltipData
local function OnStatusTooltip(character, status, tooltip)
if Features.ReplaceTooltipPlaceholders or Features.FixChaosDamageDisplay or Features.TooltipGrammarHelper then
for i,element in pairs(tooltip:GetElements("StatusDescription")) do
if element ~= nil then
if Features.ReplaceTooltipPlaceholders then
element.Label = GameHelpers.Tooltip.ReplacePlaceholders(element.Label, character)
end
if Features.TooltipGrammarHelper then
element.Label = string.gsub(element.Label, "a 8", "an 8")
local startPos,endPos = string.find(element.Label , "a <font.->8")
if startPos then
local text = string.sub(element.Label, startPos, endPos)
element.Label = string.gsub(element.Label, text, text:gsub("a ", "an "))
end
end
if Features.FixChaosDamageDisplay and not Data.EngineStatus[status.StatusId] then
local statusType = Ext.StatGetAttribute(status.StatusId, "StatusType")
local descParams = Ext.StatGetAttribute(status.StatusId, "DescriptionParams")
if statusType == "DAMAGE"
and not StringHelpers.IsNullOrEmpty(descParams)
and string.find(descParams, "Damage")
and not string.find(element.Label:lower(), LocalizedText.DamageTypeHandles.Chaos.Text.Value)
then
local startPos,endPos,damage = string.find(element.Label, chaosDamagePattern)
if damage ~= nil then
damage = string.gsub(damage, "%s+", "")
local removeText = string.sub(element.Label, startPos, endPos):gsub("%-", "%%-")
element.Label = string.gsub(element.Label, removeText, GameHelpers.GetDamageText("Chaos", damage))
end
end
end
end
end
end
end
local FarOutManFixSkillTypes = {
Cone = "Range",
Zone = "Range",
}
---@param character EclCharacter
---@param skill string
---@param tooltip TooltipData
local function OnSkillTooltip(character, skill, tooltip)
if Vars.DebugMode and SharedData.RegionData.LevelType == LEVELTYPE.CHARACTER_CREATION then
print(skill, Common.Dump(Ext.StatGetAttribute(skill, "MemorizationRequirements")))
end
--print(Ext.JsonStringify(tooltip.Data))
if Features.TooltipGrammarHelper then
-- This fixes the double spaces from removing the "tag" part of Requires tag
for i,element in pairs(tooltip:GetElements("SkillRequiredEquipment")) do
element.Label = string.gsub(element.Label, "%s+", " ")
end
end
if Features.FixRifleWeaponRequirement then
local requirement = Ext.StatGetAttribute(skill, "Requirement")
if requirement == "RifleWeapon" then
local skillRequirements = tooltip:GetElements("SkillRequiredEquipment")
local addRifleText = true
if skillRequirements ~= nil and #skillRequirements > 0 then
for i,element in pairs(skillRequirements) do
if string.find(element.Label, LocalizedText.SkillTooltip.RifleWeapon.Value) then
addRifleText = false
break
end
end
end
if addRifleText then
local hasRequirement = character.Stats.MainWeapon ~= nil and character.Stats.MainWeapon.WeaponType == "Rifle"
local text = LocalizedText.SkillTooltip.SkillRequiredEquipment:ReplacePlaceholders(LocalizedText.SkillTooltip.RifleWeapon.Value)
tooltip:AppendElement({
Type="SkillRequiredEquipment",
RequirementMet = hasRequirement,
Label = text
})
end
end
end
if Features.ReplaceTooltipPlaceholders
or (Features.FixChaosDamageDisplay or Features.FixCorrosiveMagicDamageDisplay)
or Features.TooltipGrammarHelper then
for i,element in pairs(tooltip:GetElements("SkillDescription")) do
if element ~= nil then
if Features.TooltipGrammarHelper == true then
element.Label = string.gsub(element.Label, "a 8", "an 8")
local startPos,endPos = string.find(element.Label , "a <font.->8")
if startPos then
local text = string.sub(element.Label, startPos, endPos)
element.Label = string.gsub(element.Label, text, text:gsub("a ", "an "))
end
end
if Features.FixChaosDamageDisplay == true and not string.find(element.Label:lower(), LocalizedText.DamageTypeHandles.Chaos.Text.Value) then
local startPos,endPos,damage = string.find(element.Label, chaosDamagePattern)
if damage ~= nil then
damage = string.gsub(damage, "%s+", "")
local removeText = string.sub(element.Label, startPos, endPos):gsub("%-", "%%-")
element.Label = string.gsub(element.Label, removeText, GameHelpers.GetDamageText("Chaos", damage))
end
end
if Features.FixCorrosiveMagicDamageDisplay == true then
local status,err = xpcall(function()
local lowerLabel = string.lower(element.Label)
local damageText = ""
if string.find(lowerLabel, LocalizedText.DamageTypeHandles.Corrosive.Text.Value) then
damageText = LocalizedText.DamageTypeHandles.Corrosive.Text.Value
elseif string.find(lowerLabel, LocalizedText.DamageTypeHandles.Magic.Text.Value) then
damageText = LocalizedText.DamageTypeHandles.Magic.Text.Value
end
if damageText ~= "" then
local startPos,endPos = string.find(lowerLabel, "destroy <font.->[%d-]+ "..damageText..".-</font> on")
if startPos and endPos then
local str = string.sub(element.Label, startPos, endPos)
local replacement = string.gsub(str, "Destroy","Deal"):gsub("destroy","deal"):gsub(" on"," to")
element.Label = replacement..string.sub(element.Label, endPos+1)
end
end
return true
end, debug.traceback)
if not status then
Ext.PrintError(err)
end
end
if Features.ReplaceTooltipPlaceholders == true then
element.Label = GameHelpers.Tooltip.ReplacePlaceholders(element.Label, character)
end
end
end
end
if Features.FixFarOutManSkillRangeTooltip and (character ~= nil and character.Stats ~= nil and character.Stats.TALENT_FaroutDude == true) then
local skillType = Ext.StatGetAttribute(skill, "SkillType")
local rangeAttribute = FarOutManFixSkillTypes[skillType]
if rangeAttribute ~= nil then
local element = tooltip:GetElement("SkillRange")
if element ~= nil then
local range = Ext.StatGetAttribute(skill, rangeAttribute)
element.Value = tostring(range).."m"
end
end
end
end
--- @param skill StatEntrySkillData
--- @param character StatCharacter
--- @param isFromItem boolean
--- @param param string
local function SkillGetDescriptionParam(skill, character, isFromItem, param1, param2)
if Features.ReplaceTooltipPlaceholders then
if param1 == "ExtraData" then
local value = Ext.ExtraData[param2]
if value ~= nil then
if value == math.floor(value) then
return string.format("%i", math.floor(value))
else
if value <= 1.0 and value >= 0.0 then
-- Percentage display
value = value * 100
return string.format("%i", math.floor(value))
else
return tostring(value)
end
end
end
end
end
end
Ext.RegisterListener("SkillGetDescriptionParam", SkillGetDescriptionParam)
---@param status EsvStatus
---@param statusSource StatCharacter
---@param target StatCharacter
---@param param1 string
---@param param2 string
---@param param3 string
local function StatusGetDescriptionParam(status, statusSource, target, param1, param2, param3)
if Features.StatusParamSkillDamage then
if param1 == "Skill" and param2 ~= nil then
if param3 == "Damage" then
local success,result = xpcall(function()
local skillSource = statusSource or target
local damageSkillProps = GameHelpers.Ext.CreateSkillTable(param2)
local damageRange = Game.Math.GetSkillDamageRange(skillSource, damageSkillProps)
if damageRange ~= nil then
local damageTexts = {}
local totalDamageTypes = 0
for damageType,damage in pairs(damageRange) do
local min = damage.Min or damage[1]
local max = damage.Max or damage[2]
if min > 0 or max > 0 then
if max == min then
table.insert(damageTexts, GameHelpers.GetDamageText(damageType, string.format("%i", max)))
else
table.insert(damageTexts, GameHelpers.GetDamageText(damageType, string.format("%i-%i", min, max)))
end
end
totalDamageTypes = totalDamageTypes + 1
end
if totalDamageTypes > 0 then
if totalDamageTypes > 1 then
return StringHelpers.Join(", ", damageTexts)
else
return damageTexts[1]
end
end
end
end, debug.traceback)
if not success then
Ext.PrintError(result)
else
return result
end
elseif param3 == "ExplodeRadius" then
return tostring(Ext.StatGetAttribute(param2, param3))
end
end
end
if Features.ReplaceTooltipPlaceholders then
if param1 == "ExtraData" then
local value = Ext.ExtraData[param2]
if value ~= nil then
if value == math.floor(value) then
return string.format("%i", math.floor(value))
else
if value <= 1.0 and value >= 0.0 then
-- Percentage display
value = value * 100
return string.format("%i", math.floor(value))
else
return tostring(value)
end
end
end
end
end
end
Ext.RegisterListener("StatusGetDescriptionParam", StatusGetDescriptionParam)
---@param character EclCharacter
---@param stat string
---@param tooltip TooltipData
local function OnStatTooltip(character, stat, tooltip)
end
local tooltipSwf = {
"Public/Game/GUI/LSClasses.swf",
"Public/Game/GUI/tooltip.swf",
"Public/Game/GUI/tooltipHelper.swf",
"Public/Game/GUI/tooltipHelper_kb.swf",
}
local function ApplyLeading(tooltip_mc, element, amount)
local val = 0
if element then
if amount == 0 or amount == nil then
amount = tooltip_mc.m_Leading * 0.5
end
local heightPadding = 0
if element.heightOverride then
heightPadding = element.heightOverride / amount
else
heightPadding = element.height / amount
end
heightPadding = Ext.Round(heightPadding)
if heightPadding <= 0 then
heightPadding = 1
end
element.heightOverride = heightPadding * amount
end
end
local function RepositionElements(tooltip_mc)
--tooltip_mc.list.sortOnce("orderId",16,false)
local leading = tooltip_mc.m_Leading * 0.5;
local index = 0
local element = nil
local lastElement = nil
while index < tooltip_mc.list.length do
element = tooltip_mc.list.content_array[index]
if element.list then
element.list.positionElements()
end
if element == tooltip_mc.equipHeader then
element.updateHeight()
else
if element.needsSubSection then
if element.heightOverride == 0 or element.heightOverride == nil then
element.heightOverride = element.height
end
--element.heightOverride = element.heightOverride + leading;
element.heightOverride = element.heightOverride + leading
if lastElement and not lastElement.needsSubSection then
if lastElement.heightOverride == 0 or lastElement.heightOverride == nil then
lastElement.heightOverride = lastElement.height
end
--lastElement.heightOverride = lastElement.heightOverride + leading;
lastElement.heightOverride = lastElement.heightOverride + leading
end
end
--tooltip_mc.applyLeading(element)
ApplyLeading(tooltip_mc, element)
end
lastElement = element
index = index + 1
end
--tooltip_mc.repositionElements()
tooltip_mc.list.positionElements()
tooltip_mc.resetBackground()
end
local lastItem = nil
local function AddTags(tooltip_mc)
if lastItem == nil then
return
end
if UI.Tooltip.HasTagTooltipData then
local text = ""
for tag,data in pairs(TagTooltips) do
if lastItem:HasTag(tag) then
local tagName = ""
if data.Title == nil then
tagName = Ext.GetTranslatedStringFromKey(tag)
else
tagName = data.Title.Value
end
local tagDesc = ""
if data.Description == nil then
tagDesc = Ext.GetTranslatedStringFromKey(tag.."_Description")
else
tagDesc = data.Description.Value
end
tagName = GameHelpers.Tooltip.ReplacePlaceholders(tagName)
tagDesc = GameHelpers.Tooltip.ReplacePlaceholders(tagDesc)
if text ~= "" then
text = text .. "<br>"
end
text = text .. string.format("%s<br>%s", tagName, tagDesc)
end
end
if text ~= "" then
local group = tooltip_mc.addGroup(15)
if group ~= nil then
group.orderId = 0;
group.addDescription(text)
--group.addWhiteSpace(0,0)
else
Ext.PrintError("[LeaderLib:TooltipHandler:AddTags] Failed to create group.")
end
end
end
lastItem = nil
end
local replaceText = {}
local function FormatTagText(content_array, group, isControllerMode)
local updatedText = false
for i=0,#content_array,1 do
local element = content_array[i]
if element ~= nil then
local b,result = xpcall(function()
if element.label_txt ~= nil then
local searchText = StringHelpers.Trim(element.label_txt.htmlText):gsub("[\r\n]", "")
local tag = replaceText[searchText]
local data = TagTooltips[tag]
if data ~= nil then
local finalText = ""
local tagName = ""
if data.Title == nil then
tagName = Ext.GetTranslatedStringFromKey(tag)
else
tagName = data.Title.Value
end
local tagDesc = ""
if data.Description == nil then
tagDesc = Ext.GetTranslatedStringFromKey(tag.."_Description")
else
tagDesc = data.Description.Value
end
if tagName ~= "" then
tagName = GameHelpers.Tooltip.ReplacePlaceholders(tagName)
finalText = tagName
end
if tagDesc ~= "" then
tagDesc = GameHelpers.Tooltip.ReplacePlaceholders(tagDesc)
if finalText ~= "" then
finalText = finalText .. "<br>"
end
finalText = finalText .. tagDesc
end
if finalText ~= "" then
element.label_txt.htmlText = finalText
updatedText = true
end
--print(string.format("[%s] htmlText(%s) finalText(%s)", group.name, element.label_txt.htmlText, finalText))
end
-- if Vars.DebugMode then
-- PrintDebug(string.format("(%s) label_txt.htmlText(%s) color(%s)", group.groupID, element.label_txt.htmlText, element.label_txt.textColor))
-- end
end
return true
end, debug.traceback)
if not b then
Ext.PrintError("[LeaderLib:FormatTagText] Error:")
Ext.PrintError(result)
end
end
end
if updatedText and group ~= nil then
group.iconId = 16
group.setupHeader()
end
end
UI.FormatArrayTagText = FormatTagText
local function FormatTagTooltip(ui, tooltip_mc, ...)
local length = #tooltip_mc.list.content_array
if length > 0 then
for i=0,length,1 do
local group = tooltip_mc.list.content_array[i]
if group ~= nil then
--print(string.format("[%i] groupID(%i) orderId(%s) icon(%s) list(%s)", i, group.groupID or -1, group.orderId or -1, group.iconId, group.list))
if group.list ~= nil then
FormatTagText(group.list.content_array, group, false)
end
end
end
end
end
local function OnTooltipPositioned(ui, ...)
if UI.Tooltip.HasTagTooltipData or #UIListeners.OnTooltipPositioned > 0 then
local root = ui:GetRoot()
if root ~= nil then
local tooltips = {}
if root.formatTooltip ~= nil then
tooltips[#tooltips+1] = root.formatTooltip.tooltip_mc
end
if root.compareTooltip ~= nil then
tooltips[#tooltips+1] = root.compareTooltip.tooltip_mc
end
if root.offhandTooltip ~= nil then
tooltips[#tooltips+1] = root.offhandTooltip.tooltip_mc
end
if #tooltips > 0 then
for i,tooltip_mc in pairs(tooltips) do
if Features.FormatTagElementTooltips then
FormatTagTooltip(ui, tooltip_mc)
end
InvokeListenerCallbacks(UIListeners.OnTooltipPositioned, ui, tooltip_mc, false, lastItem, ...)
end
end
end
end
end
---RootTemplate -> Skill -> Enabled
---@type table<string,table<string,boolean>>
local skillBookAssociatedSkills = {}
---@param item EclItem
---@param tooltip TooltipData
local function OnItemTooltip(item, tooltip)
if tooltip == nil then
return
end
if item ~= nil then
--print(item.StatsId, Ext.JsonStringify(item.WorldPos), Ext.JsonStringify(tooltip.Data))
lastItem = item
local character = Client:GetCharacter()
if character ~= nil then
if Features.FixItemAPCost == true then
local apElement = tooltip:GetElement("ItemUseAPCost")
if apElement ~= nil then
local ap = apElement.Value
if ap > 0 then
for i,status in pairs(character:GetStatuses()) do
if not Data.EngineStatus[status] then
local potion = Ext.StatGetAttribute(status, "StatsId")
if potion ~= nil and potion ~= "" then
local apCostBoost = Ext.StatGetAttribute(potion, "APCostBoost")
if apCostBoost ~= nil and apCostBoost ~= 0 then
ap = math.max(0, ap + apCostBoost)
end
end
end
end
apElement.Value = ap
end
end
end
if item.RootTemplate ~= nil and not StringHelpers.IsNullOrEmpty(item.RootTemplate.Id) then
local skillBookSkillDisplayName = GameHelpers.Tooltip.GetElementAttribute(tooltip:GetElement("SkillbookSkill"), "Value")
if not StringHelpers.IsNullOrEmpty(skillBookSkillDisplayName) then
local savedSkills = skillBookAssociatedSkills[item.RootTemplate.Id]
if savedSkills == nil then
local tooltipIcon = GameHelpers.Tooltip.GetElementAttribute(tooltip:GetElement("SkillIcon"), "Label")
local tooltipSkillDescription = GameHelpers.Tooltip.GetElementAttribute(tooltip:GetElement("SkillDescription"), "Label")
for i,skill in pairs(Ext.GetStatEntries("SkillData")) do
local icon = Ext.StatGetAttribute(skill, "Icon")
if tooltipIcon == icon then
local displayName = GameHelpers.GetStringKeyText(Ext.StatGetAttribute(skill, "DisplayName"))
local description = GameHelpers.GetStringKeyText(Ext.StatGetAttribute(skill, "Description"))
if displayName == skillBookSkillDisplayName and description == tooltipSkillDescription then
if skillBookAssociatedSkills[item.RootTemplate.Id] == nil then
skillBookAssociatedSkills[item.RootTemplate.Id] = {}
savedSkills = skillBookAssociatedSkills[item.RootTemplate.Id]
end
skillBookAssociatedSkills[item.RootTemplate.Id][skill] = true
end
end
end
end
if savedSkills ~= nil then
for skill,b in pairs(savedSkills) do
if b then
OnSkillTooltip(character, skill, tooltip)
end
end
end
end
end
end
if Features.ResistancePenetration == true then
-- Resistance Penetration display
if item:HasTag("LeaderLib_HasResistancePenetration") then
local tagsCheck = {}
for _,damageType in Data.DamageTypes:Get() do
local tags = Data.ResistancePenetrationTags[damageType]
if tags ~= nil then
local totalResPen = 0
for i,tagEntry in pairs(tags) do
if item:HasTag(tagEntry.Tag) then
totalResPen = totalResPen + tagEntry.Amount
tagsCheck[#tagsCheck+1] = tagEntry.Tag
end
end
if totalResPen > 0 then
local tString = LocalizedText.ItemBoosts.ResistancePenetration
local resistanceText = GameHelpers.GetResistanceNameFromDamageType(damageType)
local result = tString:ReplacePlaceholders(GameHelpers.GetResistanceNameFromDamageType(damageType))
--PrintDebug(tString.Value, resistanceText, totalResPen, result)
local element = {
Type = "ResistanceBoost",
Label = result,
Value = totalResPen,
}
tooltip:AppendElement(element)
end
end
end
--print("ResPen tags:", Ext.JsonStringify(tagsCheck))
end
end
if UI.Tooltip.HasTagTooltipData then
for tag,data in pairs(TagTooltips) do
if item:HasTag(tag) then
local finalText = ""
local tagName = ""
local tagDesc = ""
if data.Title == nil then
tagName = Ext.GetTranslatedStringFromKey(tag)
else
tagName = data.Title.Value
end
if data.Description == nil then
tagDesc = Ext.GetTranslatedStringFromKey(tag.."_Description")
else
tagDesc = data.Description.Value
end
if tagName ~= "" then
tagName = GameHelpers.Tooltip.ReplacePlaceholders(tagName)
finalText = tagName
end
if tagDesc ~= "" then
tagDesc = GameHelpers.Tooltip.ReplacePlaceholders(tagDesc)
if finalText ~= "" then
finalText = finalText .. "<br>"
end
finalText = finalText .. tagDesc
end
if finalText ~= "" then
tooltip:AppendElement({
Type="StatsTalentsBoost",
Label=finalText
})
local searchText = finalText:gsub("<font.->", ""):gsub("</font>", ""):gsub("<br>", "")
replaceText[searchText] = tag
end
end
end
end
if Features.TooltipGrammarHelper then
local requirements = tooltip:GetElements("ItemRequirement")
if requirements ~= nil then
for i,element in pairs(requirements) do
element.Label = string.gsub(element.Label, "%s+", " ")
end
end
end
if item:HasTag("LeaderLib_AutoLevel") then
local element = tooltip:GetElement("ItemDescription")
if element ~= nil and not string.find(string.lower(element.Label), "automatically level") then
if not StringHelpers.IsNullOrEmpty(element.Label) then
element.Label = element.Label .. "<br>" .. LocalizedText.Tooltip.AutoLevel.Value
else
element.Label = LocalizedText.Tooltip.AutoLevel.Value
end
end
end
if Features.ReduceTooltipSize then
--print(Ext.JsonStringify(tooltip.Data))
local elements = tooltip:GetElements("ExtraProperties")
if elements ~= nil and #elements > 0 then
for i,v in pairs(elements) do
if StringHelpers.IsNullOrEmpty(StringHelpers.Trim(v.Label)) then
elements[i] = nil
tooltip:RemoveElement(v)
end
end
local result = GameHelpers.Tooltip.CondensePropertiesText(tooltip, elements)
if result ~= nil then
local combined = {
Type = "ExtraProperties",
Label = result
}
tooltip:AppendElement(combined)
end
end
end
end
end
local debugTooltipCalls = {
"tooltipClicked",
"tooltipOut",
"tooltipOver",
"showItemTooltip",
"showTooltip",
"hideTooltip",
"setTooltipSize",
}
Ext.RegisterListener("SessionLoaded", function()
Game.Tooltip.RegisterListener("Item", nil, OnItemTooltip)
Game.Tooltip.RegisterListener("Skill", nil, OnSkillTooltip)
Game.Tooltip.RegisterListener("Status", nil, OnStatusTooltip)
Game.Tooltip.RegisterListener("Stat", nil, OnStatTooltip)
---@param ui UIObject
-- Ext.RegisterUITypeInvokeListener(44, "updateTooltips", function(ui, method, ...)
-- print(ui:GetTypeId(), method, Common.Dump{...})
-- end)
-- Ext.RegisterUITypeInvokeListener(44, "showTooltipLong", function(ui, method, ...)
-- print(ui:GetTypeId(), method, Common.Dump{...})
-- end)
Ext.RegisterUITypeInvokeListener(44, "addTooltip", function(ui, method, text, xPos, yPos, ...)
for i,callback in pairs(UIListeners.OnWorldTooltip) do
local status,err = xpcall(callback, debug.traceback, ui, text, xPos, yPos, ...)
if not status then
Ext.PrintError("[LeaderLib:OnWorldTooltip] Error invoking callback:")
Ext.PrintError(err)
end
end
end, "After")
-- Ext.RegisterUITypeInvokeListener(44, "addFormattedTooltip", function(ui, method, ...)
-- print(ui:GetTypeId(), method, Common.Dump{...})
-- end)
-- for i,v in pairs(debugTooltipCalls) do
-- Ext.RegisterUINameCall(v, function(ui, call, ...)
-- print(ui:GetTypeId(), call, Common.Dump{...})
-- end)
-- end
Ext.RegisterUINameInvokeListener("showFormattedTooltipAfterPos", function(ui, ...)
OnTooltipPositioned(ui, ...)
end)
-- Ext.RegisterUITypeCall(104, "showTooltip", function (ui, call, mcType, doubleHandle, ...)
-- end)
-- Ext.RegisterUITypeInvokeListener(Data.UIType.examine, "update", function(ui, method)
-- print(ui:GetTypeId(), method)
-- local main = ui:GetRoot()
-- local array = main.addStats_array
-- if main ~= nil and array ~= nil then
-- for i=0,#array do
-- print(i, array[i])
-- end
-- end
-- end)
-- Ext.RegisterUITypeInvokeListener(Data.UIType.examine, "updateStatusses", function(ui, method)
-- local main = ui:GetRoot()
-- local array = main.status_array
-- if main ~= nil and array ~= nil then
-- local handleDouble = array[0]
-- if handleDouble ~= nil then
-- local character = Ext.GetCharacter(Ext.DoubleToHandle(handleDouble))
-- if character ~= nil then
-- print(character.MyGuid, handleDouble)
-- end
-- end
-- for i=0,#array do
-- print(i, array[i])
-- end
-- end
-- end)
-- Ext.RegisterUITypeInvokeListener(Data.UIType.contextMenu, "updateButtons", function(ui, method)
-- print(ui:GetTypeId(), method)
-- local main = ui:GetRoot()
-- if main ~= nil and main.buttonArr ~= nil then
-- for i=0,#main.buttonArr do
-- print(i, main.buttonArr[i])
-- end
-- end
-- end)
-- Ext.RegisterUITypeCall(Data.UIType.contextMenu, "buttonPressed", function(ui, ...)
-- print(Common.Dump({...}))
-- end)
end)
local function EnableTooltipOverride()
--Ext.AddPathOverride("Public/Game/GUI/tooltip.swf", "Public/LeaderLib_543d653f-446c-43d8-8916-54670ce24dd9/GUI/tooltip.swf")
Ext.AddPathOverride("Public/Game/GUI/LSClasses.swf", "Public/LeaderLib_543d653f-446c-43d8-8916-54670ce24dd9/GUI/LSClasses_Fixed.swf")
--Ext.AddPathOverride("Public/Game/GUI/tooltipHelper_kb.swf", "Public/LeaderLib_543d653f-446c-43d8-8916-54670ce24dd9/GUI/tooltipHelper_kb_Fixed.swf")
Ext.Print("[LeaderLib] Enabled tooltip override.")
end
if UI == nil then
UI = {}
end
---Registers a tag to display on item tooltips.
---@param tag string
---@param title TranslatedString
---@param description TranslatedString
function UI.RegisterItemTooltipTag(tag, title, description)
local data = {}
if title ~= nil then
data.Title = title
end
if description ~= nil then
data.Description = description
end
TagTooltips[tag] = data
UI.Tooltip.HasTagTooltipData = true
end
-- Ext.RegisterListener("ModuleLoading", EnableTooltipOverride)
-- Ext.RegisterListener("ModuleLoadStarted", EnableTooltipOverride)
-- Ext.RegisterListener("ModuleResume", EnableTooltipOverride)
-- Ext.RegisterListener("SessionLoading", EnableTooltipOverride)
-- Ext.RegisterListener("SessionLoaded", EnableTooltipOverride) |
---@type cohashf
local cohashf = require "colibc.hashf"
return cohashf |
local ReplicatedStorage = game:GetService("ReplicatedStorage")
require(ReplicatedStorage.Shared)
print("Client") |
local M = {}
-- M.UPDATE_MODE_DEFAULT = hash("DEFAULT")
-- M.UPDATE_MODE_LATE = hash("LATE")
-- M.UPDATE_MODE_MANUAL = hash("MANUAL")
local hyper_fmath = require("hyper_trails.fmath")
local hyper_geometry = require("hyper_trails.geometry")
--
-- Helper functions for trail_maker.script
--
-- 'self' is trail_maker.script instance
--
local EMPTY_TABLE = {}
local VECTOR3_EMPTY = vmath.vector3()
local VECTOR3_ONE = vmath.vector3(1)
-- Based on https://forum.defold.com/t/delay-when-using-draw-line-in-update/68695/2
function M.queue_late_update()
physics.raycast_async(VECTOR3_EMPTY, VECTOR3_ONE, EMPTY_TABLE)
end
function M.create_texture(self)
self._tex_buffer = buffer.create(self._tex_w * self._tex_h, {
{
name = hash("rgba"),
type = buffer.VALUE_TYPE_UINT8,
count = 4
}
})
self._tex_stream = buffer.get_stream(self._tex_buffer, hash("rgba"))
end
function M.draw_trail(self)
M.encode_data_to_texture(self)
M.update_uv_opts(self)
M.update_texture(self)
end
function M.encode_data_to_texture(self)
local p = vmath.vector3()
for i = self._data_w, 1, -1 do
local d = self._data[i]
M.write_vectors(self, i, p + d.v_1, p + d.v_2)
M.write_tint(self, i, d.tint)
p = p + d.dpos
end
end
function M.fade_tail(self, dt, data_arr, data_from)
local m = math.min(data_from + self.fade_tail_alpha - 1, self._data_w)
local j = 0
for i = data_from, m do
local w = j / (m - data_from)
if data_arr[i].tint.w > w then
data_arr[i].tint.w = w
end
j = j + 1
end
end
function M.follow_position(self, dt)
local data_arr = self._data
local new_pos = M.get_position(self)
local diff_pos = self._last_pos - new_pos
self._last_pos = new_pos
local prev_point, head_point = M.get_head_data_points(self)
local new_point = nil
local add_new_point = true
if self.segment_length_min > 0 then
if head_point.dlength < self.segment_length_min then
diff_pos = diff_pos + head_point.dpos
add_new_point = false
new_point = head_point
head_point = prev_point
end
end
if add_new_point then
new_point = data_arr[1]
-- shift data array in left direction by one position
for i = 1, self._data_w - 1 do
data_arr[i] = data_arr[i + 1]
end
end
for i = 1, self._data_w do
data_arr[i].lifetime = data_arr[i].lifetime + dt
end
new_point.dpos = diff_pos
new_point.dlength = vmath.length(diff_pos)
new_point.angle = M.make_angle(diff_pos)
new_point.tint = vmath.vector4(self.trail_tint_color)
new_point.width = self.trail_width
new_point.lifetime = 0
new_point.prev = head_point
M.make_vectors_from_angle(self, new_point)
data_arr[self._data_w] = new_point
M.split_segments_by_length(self)
local data_limit = self._data_w
if self.points_limit > 0 then
data_limit = self.points_limit
end
local data_from = self._data_w - data_limit + 1
if self.shrink_length_per_sec > 0 then
M.shrink_length(self, dt, data_arr, data_from)
end
if self.fade_tail_alpha > 0 then
M.fade_tail(self, dt, data_arr, data_from)
end
if self.shrink_tail_width then
M.shrink_width(self, dt, data_from, data_arr, data_limit)
end
if data_from > 1 then
M.pull_not_used_points(self, data_arr, data_from)
end
end
function M.get_head_data_points(self)
return self._data[self._data_w - 1], self._data[self._data_w]
end
function M.get_position(self)
if self.use_world_position then
local pos = go.get_world_position()
local scale = go.get_world_scale()
pos.x = pos.x / scale.x
pos.y = pos.y / scale.y
return pos
else
return go.get_position()
end
end
function M.init_data_points(self)
self._data = {}
for i = 1, self._data_w do
local tint = vmath.vector4(self.trail_tint_color)
tint.w = 0
self._data[i] = {
dpos = vmath.vector3(), -- vector3, difference between this and previous point
dlength = 0, -- length of dpos
angle = 0, -- radians
tint = tint, -- vector4
width = self.trail_width, -- trail width
lifetime = 0, -- used for fading
prev = self._data[i - 1] -- link to the previous point
}
M.make_vectors_from_angle(self, self._data[i])
end
end
function M.init_props(self)
assert(bit.band(self.points_count, (self.points_count - 1)) == 0, "Points count should be 16, 32, 64 (power of two).")
if self.points_limit > self.points_count then
self.points_limit = self.points_count
end
end
function M.init_vars(self)
self._tex_h = 8
self._tex_w = self.points_count
self._tex_w4 = self._tex_w * 4 -- optimization, see write_vectors
self._data_w = self.points_count
self._resource_path = go.get(self.trail_model_url, "texture0")
self._tex_header = {
width = self._tex_w,
height = self._tex_h,
type = resource.TEXTURE_TYPE_2D,
format = resource.TEXTURE_FORMAT_RGBA,
num_mip_maps = 1
}
model.set_constant(self.trail_model_url, "tex_size", vmath.vector4(self._tex_w, self._tex_h, 0, 0))
self._last_pos = M.get_position(self)
end
function M.make_angle(diff_pos)
return math.atan2(-diff_pos.y, -diff_pos.x)
end
function M.make_vectors_from_angle(self, row)
local a = row.angle - math.pi / 2
local w = row.width / 2
row.v_1 = vmath.vector3(math.cos(a) * w, math.sin(a) * w, 0)
row.v_2 = vmath.vector3(math.cos(a + math.pi) * w, math.sin(a + math.pi) * w, 0)
-- Trying to prevent crossing the points
-- TEMPORARILY DISABLED
-- if row.prev ~= nil and row.prev.v_1 ~= nil then
-- local prev = row.prev
-- local intersects = hyper_geometry.lines_intersects(row.v_1, prev.v_1 + row.dpos, row.v_2, prev.v_2 + row.dpos, false)
-- if intersects then
-- local v = row.v_2
-- row.v_2 = row.v_1
-- row.v_1 = v
-- end
-- end
end
function M.pull_not_used_points(self, data_arr, data_from)
local last_point = data_arr[data_from]
last_point.dpos.x = 0
last_point.dpos.y = 0
for i = 1, data_from - 1 do
local d = data_arr[i]
d.dpos.x = 0
d.dpos.y = 0
d.dlength = 0
d.width = 0
d.tint.w = 0
M.make_vectors_from_angle(self, d)
end
end
function M.shrink_length(self, dt, data_arr, data_from)
local to_shrink = self.shrink_length_per_sec * dt
for i = data_from + 1, self._data_w - 1 do
local d = data_arr[i]
if d.dlength ~= 0 then
if d.dlength > to_shrink then
d.dlength = d.dlength - to_shrink
d.dpos = vmath.normalize(d.dpos) * d.dlength
break
else
to_shrink = to_shrink - d.dlength
d.dpos.x = 0
d.dpos.y = 0
d.dlength = 0
end
end
end
end
function M.shrink_width(self, dt, data_from, data_arr, data_limit)
local j = 1
for i = data_from, self._data_w do
data_arr[i].width = self.trail_width * (j / data_limit)
M.make_vectors_from_angle(self, data_arr[i])
j = j + 1
end
end
function M.split_segments_by_length(self)
if not (self.segment_length_max > 0) then
return
end
local data_arr = self._data
local _, head_point = M.get_head_data_points(self)
while head_point.dlength > self.segment_length_max do
local next_dlength = head_point.dlength - self.segment_length_max
local normal = vmath.normalize(head_point.dpos)
head_point.dlength = self.segment_length_max
head_point.dpos = normal * head_point.dlength
local new_point = data_arr[1]
-- shift data array in left direction by one position
for i = 1, self._data_w - 1 do
data_arr[i] = data_arr[i + 1]
end
new_point.dpos = normal * next_dlength
new_point.dlength = next_dlength
new_point.angle = M.make_angle(new_point.dpos)
new_point.tint = vmath.vector4(self.trail_tint_color)
new_point.width = self.trail_width
new_point.lifetime = 0
new_point.prev = head_point
M.make_vectors_from_angle(self, new_point)
data_arr[self._data_w] = new_point
_, head_point = M.get_head_data_points(self)
end
end
function M.update_texture(self)
resource.set_texture(self._resource_path, self._tex_header, self._tex_buffer)
-- DO NOT REMOVE
-- if write_texture then
-- print("Write data.png")
-- local rgba = buffer.get_bytes(self._tex_buffer, hash("rgba"))
-- local bytes = png.encode_rgba(rgba, self._tex_w, self._tex_h)
-- local f = io.open("hyper_trails/textures/data/texture.png", "wb")
-- f:write(bytes)
-- f:flush()
-- f:close()
-- -- + flip vertical!
-- write_texture = false
-- end
end
function on_input(self, action_id, action)
if action_id == hash("profile") and action.pressed then
msg.post("@system:", "toggle_profile")
elseif action_id == hash("physics") and action.pressed then
msg.post("@system:", "toggle_physics_debug")
end
end
function M.update_uv_opts(self)
if self.texture_tiling then
model.set_constant(self.trail_model_url, "uv_opts", vmath.vector4(1, 0, 1, 0))
else
local count = self.points_count
local offset = 0
if self.points_limit > 0 then
count = self.points_limit
offset = -(self.points_count - self.points_limit)
end
model.set_constant(self.trail_model_url, "uv_opts", vmath.vector4(0, 1, count, offset))
end
end
function M.write_tint(self, p_x, tint)
local s = self._tex_stream
local p_y = 5
local i = (p_y - 1) * self._tex_w4 + (p_x - 1) * 4 + 1
s[i + 0] = tint.x * 255
s[i + 1] = tint.y * 255
s[i + 2] = tint.z * 255
s[i + 3] = tint.w * 255
end
function M.write_vectors(self, p_x, v_1, v_2)
local s = self._tex_stream
local w4 = self._tex_w4
local i = (p_x - 1) * 4 + 1
hyper_fmath.encode_rgba_float_to_buffer(v_1.x, s, i)
i = i + w4 -- next line
hyper_fmath.encode_rgba_float_to_buffer(v_1.y, s, i)
i = i + w4 -- next line
hyper_fmath.encode_rgba_float_to_buffer(v_2.x, s, i)
i = i + w4 -- next line
hyper_fmath.encode_rgba_float_to_buffer(v_2.y, s, i)
end
return M |
AddCSLuaFile()
Profiler = Profiler or {}
function Profiler:PlayerAllowedToProfile(ply, action)
//Override this using functions from your favourite admin
return true
end
function Profiler:ShallowCopy(tbl)
local copy = {}
for k,v in pairs(tbl) do
copy[k] = v
end
return copy
end
PROFILER_DOMAIN_PREFIX = PROFILER_DOMAIN_PREFIX or "asset://garrysmod/addons/gmod-prof/html/"
include("networking/sh_init.lua")
include("hooks/sh_init.lua") |
--[[
Copyright 2017-2018 "Kovus" <[email protected]>
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
death_marker.lua - Create a death marker at player death location.
@usage require('modules/common/deathmarker')
--]] local deathmarkers = {}
function deathmarkers.init(event)
local player = game.players[event.player_index]
if not global.death_markers then
global.death_markers = {counters = {}, markers = {}, lines = {}}
end
global.death_markers.lines[player.name] = {}
end
local function removeCorpseTag(entity)
local player = game.players[entity.character_corpse_player_index]
if not player then return end
local tick = entity.character_corpse_tick_of_death
local position = entity.position
local markers = global.death_markers.markers
for idx = 1, #markers do
local entry = markers[idx]
if entry and entry.player_index == player.index and entry.death_tick ==
tick then
if entry.tag and entry.tag.valid then
for i, line in pairs(global.death_markers.lines[player.name]) do
if line.corpse and line.corpse == entity then
rendering.destroy(line.line)
table.remove(global.death_markers.lines[player.name], i)
end
end
if player.connected then
player.print({'death_marker.removed', entry.tag.text})
end
entry.tag.destroy()
end
table.remove(markers, idx)
return
end
end
end
function deathmarkers.playerRespawned(event)
local plidx = event.player_index
local player = game.players[plidx]
local position = player.position
local surface = player.surface
local lines = global.death_markers.lines[player.name]
for i, line in pairs(lines) do
local corpse = surface.find_entity("character-corpse",
line.corpse_position)
if corpse and corpse.type == "character-corpse" then
local newline = rendering.draw_line {
surface = player.surface,
from = player.character,
to = corpse,
players = {player.index},
color = {r = 1, g = 0, b = 0},
width = 3.2,
gap_length = 5,
dash_length = 8,
time_to_live = 60 * 60 * 5
}
line = newline
else
table.remove(lines, i)
end
end
end
function deathmarkers.playerDied(event)
local plidx = event.player_index
local player = game.players[plidx]
local position = player.position
local surface = player.surface
local force = player.force
local counters = global.death_markers.counters
if counters[plidx] then
counters[plidx] = counters[plidx] + 1
else
counters[plidx] = 1
end
-- cannot localize the marker text, as it's a map entity common to all
-- players, and not a gui element or player-based output message.
local text = table.concat({'RIP ', player.name, ' (', counters[plidx], ')'})
local tag = force.add_chart_tag(surface, {
position = position,
text = text,
icon = {type = 'item', name = 'power-armor-mk2'}
})
table.insert(global.death_markers.markers,
{tag = tag, player_index = plidx, death_tick = event.tick})
table.insert(global.death_markers.lines[player.name],
{corpse_position = position, line = {}})
for index, cplayer in pairs(player.force.connected_players) do
if cplayer.surface == surface then
cplayer.print({
'death_marker.message', player.name, text, position.x,
position.y
})
end
end
end
function deathmarkers.corpseExpired(event) removeCorpseTag(event.corpse) end
function deathmarkers.onMined(event)
if event.entity.valid and event.entity.name == 'character-corpse' then
removeCorpseTag(event.entity)
end
end
return deathmarkers
|
-- tiled Plugin template
-- Use this as a template to extend a tiled object with functionality
local M = {}
local function newSlice(options)
local slice = {}
options = options or {}
local filename = options.filename
local border = options.border or 32
local top = options.top or border
local left = options.left or border
local right = options.right or border
local bottom = options.bottom or border
local width = options.textureWidth or 256
local height = options.textureHeight or 256
-- Image Sheet needs to be set like this...
-- +----+-----+-----+
-- | 1 | 2 | 3 |
-- +----+-----+-----+
-- | 4 | 5 | 6 |
-- +----+-----+-----+
-- | 7 | 8 | 9 |
-- +----+-----+-----+
local sheetOptions =
{
sheetContentWidth = width, -- width of original 1x size of entire sheet
sheetContentHeight = height, -- height of original 1x size of entire sheet
frames =
{ -- frame 1, upper left corner
{ x = 0,
y = 0,
width = left,
height = top,
}, -- frame 2, top
{ x = left,
y = 0,
width = width - left - right,
height = top,
},-- frame 3, upper right corner
{ x = width - right,
y = 0,
width = right,
height = top,
}, -- frame 4, middle left
{ x = 0,
y = top,
width = left,
height = height - top - bottom,
},-- frame 5, center
{ x = left,
y = top,
width = width - left - right,
height = height - top - bottom,
}, -- frame 6, middle right
{ x = width - right,
y = top,
width = right,
height = height - top - bottom,
},-- frame 7, bottom left corner
{ x = 0,
y = height - bottom,
width = left,
height = bottom,
},-- frame 8, bottom
{ x = left,
y = height - bottom,
width = width - left - right,
height = bottom,
},-- frame 9, bottom right corner
{ x = width - right,
y = height - bottom,
width = right,
height = bottom,
},
}
}
slice.top = top
slice.left = left
slice.right = right
slice.bottom = bottom
slice.width = width
slice.height = height
slice.sheetOptions = sheetOptions
slice.sheet = graphics.newImageSheet( filename, sheetOptions )
function slice:render(options)
local sliceGroup = display.newGroup()
options = options or {}
local x = options.x or 0
local y = options.y or 0
local width = options.width or 512
local height = options.height or 512
-- Guide image (debug only)
-- local guide = display.newRect(x,y,width,height)
-- guide.alpha = 0.2
local topLeft = display.newImageRect(sliceGroup, self.sheet, 1, self.left, self.top )
topLeft.anchorX, topLeft.anchorY = 0,0
topLeft.x, topLeft.y = x, y
local top = display.newImageRect(sliceGroup, self.sheet, 2, width - self.left - self.right, self.top )
top.anchorX, top.anchorY = 0,0
top.x, top.y = x + self.left, y
local topRight = display.newImageRect(sliceGroup, self.sheet, 3, self.right, self.top )
topRight.anchorX, topRight.anchorY = 0,0
topRight.x, topRight.y = x + width - self.right, y
local left = display.newImageRect(sliceGroup, self.sheet, 4, self.left, height - self.top - self.bottom )
left.anchorX, left.anchorY = 0,0
left.x, left.y = x, y + self.top
local middle = display.newImageRect(sliceGroup, self.sheet, 5, width - self.left - self.right, height - self.top - self.bottom )
middle.anchorX, middle.anchorY = 0,0
middle.x, middle.y = x + self.left, y + self.top
local right = display.newImageRect(sliceGroup, self.sheet, 6, self.right, height - self.top - self.bottom )
right.anchorX, right.anchorY = 0,0
right.x, right.y = x + width - self.right, y + self.top
local bottomLeft = display.newImageRect(sliceGroup, self.sheet, 7, self.left, self.bottom )
bottomLeft.anchorX, bottomLeft.anchorY = 0,0
bottomLeft.x, bottomLeft.y = x, y + height - self.bottom
local bottom = display.newImageRect(sliceGroup, self.sheet, 8, width - self.left - self.right, self.bottom )
bottom.anchorX, bottom.anchorY = 0,0
bottom.x, bottom.y = x + self.left, y + height - self.bottom
local bottomRight = display.newImageRect(sliceGroup, self.sheet, 9, self.right, self.bottom )
bottomRight.anchorX, bottomRight.anchorY = 0,0
bottomRight.x, bottomRight.y = x + width - self.right, y + height - self.bottom
for i = sliceGroup.numChildren, 1, -1 do
sliceGroup[i]:translate(-width/2, -height/2)
end
return sliceGroup
end
return slice
end
function M.new(instance)
if not instance then error("ERROR: Expected display object") end
if not instance.filename then error("ERROR: Expected display object with filename parameter") end
instance.alpha = 0.2
local panel = newSlice({ border = instance.border or 32, textureWidth = instance.textureWidth, textureHeight = instance.textureHeight, filename = instance.filename, left = instance.left, right = instance.right, top = instance.top, bottom = instance.bottom })
local parent,x,y,w,h = instance.parent, instance.x, instance.y, instance.width * instance.xScale, instance.height * instance.yScale
display.remove(instance)
instance = panel:render( { width = w, height = h } )
parent:insert(instance)
instance.x, instance.y = x,y
return instance
end
return M |
-- luacheck: new globals ngx
-- Add path for openresty modules:
package.path = "/usr/local/openresty/lualib/?.lua;" .. package.path
package.cpath = "/usr/local/openresty/lualib/?.so;" .. package.cpath
describe ("resty-redis-mapper", function ()
local Redis, redis
before_each (function ()
Redis = require "resty.redis"
redis = Redis:new ()
assert (redis:connect ("redis", 6379))
redis:flushall ()
end)
after_each (function ()
redis:close ()
end)
it ("can perform # commits per second", function ()
assert.are.equal (redis:dbsize (), 0)
local Module = require "resty-redis-mapper"
local i = 0
local start = os.time ()
repeat
local module = Module {
host = "redis",
}
local Type = module / "type"
local _ = Type {}
module ()
i = i + 1
until os.time () - start >= 5
print ("Can perform " .. tostring (i/5) .. " commits per second.")
end)
it ("can run the example of the documentation", function ()
-- Import the module:
local Rrm = require "resty-redis-mapper"
-- Instantiate the module with a specific configuration:
local rrm = Rrm {
host = "redis",
port = 6379,
}
-- There are some other configuration fields.
-- Create a data type named "type":
local Type = rrm / "type"
-- The type name defines the type of objects.
-- It must be unique within the application.
-- Feel free to add any method to the type,
-- but do **not** change `__index` and `__newindex`,
-- as they are implemented by `resty-redis-mapper`.
function Type:do_something ()
self.value = 42
end
-- A default `__tostring` is defined, but it can be overwritten safely:
function Type:__tostring ()
return tostring (self.value)
end
-- Create an object of type `Type`,
-- and get its unique identifier as second result:
local object, id_object = Type {}
-- Update the object as a standard Lua table,
-- even creating references to objects within:
object.myself = object
object.t = {
a = 1,
b = true,
}
object:do_something ()
assert (tostring (object) == "42", tostring (object))
-- Warning: all data put within a table is copied,
-- except references to objects.
-- This differs from the semantics of tables in the Lua language.
-- Commit all changes done since the module instantiation:
rrm ()
-- If the commit fails, an error is throws.
-- There is thus no need to wrap commit within an `assert`.
-- The module instance becomes unusable after commit,
-- in order to prevent inconsistencies:
assert (not pcall (function ()
local _ = Type {}
end))
-- If you need to perform other changes,
-- create a new instance of the module.
rrm = Rrm { host = "redis", port = 6379 }
-- The type must be registered again,
-- because it is defined per instance of the module:
Type = rrm / "type"
-- This statement does not load the methods defined earlier.
-- In practice, users can create a function that registers all types,
-- and their associated methods.
-- And the object previously created can be loaded using its identifier:
object = rrm [id_object]
assert (object.myself == object)
assert (object.t.a == 1)
assert (object.t.b == true)
-- `resty-redis-mapper` uses transactions.
-- If an object has been modified by something else
-- between its loading and commit time, the commit fails:
object.c = "c"
do
local o_rrm = Rrm { host = "redis", port = 6379 }
local _ = o_rrm / "type"
local o_object = o_rrm [id_object]
o_object.c = nil
o_rrm ()
end
-- This following commit fails,
-- because the object has been modified in the block above.
-- The local copy is thus in a inconsistent state with the reference.
rrm ()
-- Each commit is transactional:
-- either everything is updated, or nothing.
-- `resty-redis-mapper` allows to concurrently read objects.
-- There can also be one write to an object, that is read.
rrm = Rrm { host = "redis", port = 6379 }
Type = rrm / "type"
object = rrm [id_object]
object.c = "c"
do
local o_rrm = Rrm { host = "redis", port = 6379 }
local _ = o_rrm / "type"
local _ = o_rrm [id_object]
o_rrm ()
end
-- This following commit is successful,
-- because the object has been modified by only one instance
-- of the module.
rrm ()
-- It is possible to delete an object using the usual Lua notation:
rrm = Rrm { host = "redis", port = 6379 }
Type = rrm / "type"
object = rrm [id_object]
rrm [object] = nil
-- rrm [id_object] = nil works as well
rrm ()
end)
end)
|
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- CLASS DECLARATION --------------------------------------------------------
local _DK = {};
_DK.__index = _DK;
local DirtyKeys = {}; --[RequestUUID,KQK] -> DocRoot
function _DK.SetDirty(self, kqk, data)
local ruuid = ngx.var.RequestUUID;
if (DirtyKeys[ruuid] == nil) then
DirtyKeys[ruuid] = {};
end
if (DirtyKeys[ruuid][kqk] == nil) then
LT('Replication:SetDirty: R: ' .. ruuid .. ' K: ' .. kqk);
DirtyKeys[ruuid][kqk] = data.__root;
return true;
end
return false;
end
function _DK.UnsetDirty(self, kqk)
local ruuid = ngx.var.RequestUUID;
LT('DirtyKeys:UnsetDirty: R: ' .. ruuid .. ' K: ' .. kqk);
DirtyKeys[ruuid][kqk] = nil;
end
function _DK.GetDirtyKeys(self, ruuid)
return DirtyKeys[ruuid];
end
function _DK.DropDirtyKeys(self, ruuid)
DirtyKeys[ruuid] = nil;
end
return _DK;
|
local Snowflake = require('containers/abstract/Snowflake')
local Resolver = require('client/Resolver')
local ArrayIterable = require('iterables/ArrayIterable')
local json = require('json')
local format = string.format
local Emoji, get = require('class')('Emoji', Snowflake)
function Emoji:__init(data, parent)
Snowflake.__init(self, data, parent)
self.client._emoji_map[self._id] = parent
return self:_loadMore(data)
end
function Emoji:_load(data)
Snowflake._load(self, data)
return self:_loadMore(data)
end
function Emoji:_loadMore(data)
if data.roles then
local roles = #data.roles > 0 and data.roles or nil
if self._roles then
self._roles._array = roles
else
self._roles_raw = roles
end
end
end
function Emoji:_modify(payload)
local data, err = self.client._api:modifyGuildEmoji(self._parent._id, self._id, payload)
if data then
self:_load(data)
return true
else
return false, err
end
end
function Emoji:setName(name)
return self:_modify({name = name or json.null})
end
function Emoji:setRoles(roles)
roles = Resolver.roleIds(roles)
return self:_modify({roles = roles or json.null})
end
function Emoji:delete()
local data, err = self.client._api:deleteGuildEmoji(self._parent._id, self._id)
if data then
local cache = self._parent._emojis
if cache then
cache:_delete(self._id)
end
return true
else
return false, err
end
end
function Emoji:hasRole(id)
id = Resolver.roleId(id)
local roles = self._roles and self._roles._array or self._roles_raw
if roles then
for _, v in ipairs(roles) do
if v == id then
return true
end
end
end
return false
end
function get.name(self)
return self._name
end
function get.guild(self)
return self._parent
end
function get.mentionString(self)
local fmt = self._animated and '<a:%s>' or '<:%s>'
return format(fmt, self.hash)
end
function get.url(self)
local ext = self._animated and 'gif' or 'png'
return format('https://cdn.discordapp.com/emojis/%s.%s', self._id, ext)
end
function get.managed(self)
return self._managed
end
function get.requireColons(self)
return self._require_colons
end
function get.hash(self)
return self._name .. ':' .. self._id
end
function get.animated(self)
return self._animated
end
function get.roles(self)
if not self._roles then
local roles = self._parent._roles
self._roles = ArrayIterable(self._roles_raw, function(id)
return roles:get(id)
end)
self._roles_raw = nil
end
return self._roles
end
return Emoji
|
--------------------------------------------------------------------------------
-- Handler.......... : onLessDown
-- Author........... :
-- Description...... :
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function JPSpriteSample.onLessDown ( bDown )
--------------------------------------------------------------------------------
this.bLessDown ( bDown )
if ( bDown )
then
this.decreaseStep ( )
this.postEvent ( 0.5, "onDecreaseStep" )
end
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
|
lu = require('luaunit')
lua_react = require('lua_react')
function component1(props)
return {
type="flow",
children={
{type="label", text=props.text},
{type="textfield", value=props.value},
{type="button", text="ok"}
}
}
end
function component2(props)
return {
type="flow",
children={
component1({text="t1", value="11"}),
component1({text="t2", value="22"}),
component1({text="t3", value="33"}),
}
}
end
function test11(a)
lua_react.
lu.assertEquals(2,2)
end
function test1(a)
lu.assertEquals(2,2)
end
function test2(a)
lu.assertEquals(2,2)
end
os.exit( lu.LuaUnit.run() )
|
return {
-- generic generator, from sequential list of layers:
sequence = function(layers, layer2params)
return function(params, input)
for i,layer in ipairs(layers) do
local paramsi = layer2params[i]
if paramsi then
input = layer(params[paramsi], input)
else
input = layer(input)
end
end
return input
end
end
}
|
-- color manipulation functions.
function rgb_to_hsv(r, g, b)
-- scale.
r, g, b = r / 255, g / 255, b / 255
local max, min = math.max(r, g, b), math.min(r, g, b)
local h = 0
local s = 0
local v = max
local d = max - min
if max ~= 0 then
s = d / max
end
if max ~= min then
if max == r then
h = (g - b) / d
if g < b then h = h + 6 end
elseif max == g then h = (b - r) / d + 2
elseif max == b then h = (r - g) / d + 4
end
h = h / 6
end
return h, s, v
end
function hsv_to_rgb(h, s, v)
local r, g, b
local i = math.floor(h * 6);
local f = h * 6 - i;
local p = v * (1 - s);
local q = v * (1 - f * s);
local t = v * (1 - (1 - f) * s);
i = i % 6
if i == 0 then r, g, b = v, t, p
elseif i == 1 then r, g, b = q, v, p
elseif i == 2 then r, g, b = p, v, t
elseif i == 3 then r, g, b = p, q, v
elseif i == 4 then r, g, b = t, p, v
elseif i == 5 then r, g, b = v, p, q
end
return r * 255, g * 255, b * 255
end
function rgb_to_hsl(r, g, b)
r, g, b = r / 255, g / 255, b / 255
local max, min = math.max(r, g, b), math.min(r, g, b)
local h = 0
local s = 0
local l = (max + min) / 2
local d = max - min
if max ~= min then
if l > 0.5 then s = d / (2 - max - min) else s = d / (max + min) end
if max == r then
h = (g - b) / d
if g < b then h = h + 6 end
elseif max == g then h = (b - r) / d + 2
elseif max == b then h = (r - g) / d + 4
end
h = h / 6
end
return h, s, l
end
function hsl_to_rgb(h, s, l)
local r, g, b = l, l, l
if s ~= 0 then
function hue2rgb(p, q, t)
if t < 0 then t = t + 1 end
if t > 1 then t = t - 1 end
if t < 1/6 then return p + (q - p) * 6 * t end
if t < 1/2 then return q end
if t < 2/3 then return p + (q - p) * (2/3 - t) * 6 end
return p
end
local q
if l < 0.5 then q = l * (1 + s) else q = l + s - l * s end
local p = 2 * l - q
r = hue2rgb(p, q, h + 1/3)
g = hue2rgb(p, q, h)
b = hue2rgb(p, q, h - 1/3)
end
return r * 255, g * 255, b * 255
end
return {
rgb_to_hsv = rgb_to_hsv,
hsv_to_rgb = hsv_to_rgb,
rgb_to_hsl = rgb_to_hsl,
hsl_to_rgb = hsl_to_rgb
}
|
local component = require("component")
local color = require("color")
local image = require("image")
local buffer = require("doubleBuffering")
local GUI = require("GUI")
local MineOSCore = require("MineOSCore")
--------------------------------------------------------------------------------------------------------------------
if not component.isAvailable("geolyzer") then
GUI.alert("This program requires a geolyzer to work!"); return
end
if not component.isAvailable("hologram") then
GUI.alert("This program requires a hologram projector to work!"); return
end
component.gpu.setResolution(component.gpu.maxResolution())
buffer.flush()
local bufferWidth, bufferHeight = buffer.getResolution()
local resourcesDirectory = MineOSCore.getCurrentScriptDirectory()
local earthImage = image.load(resourcesDirectory .. "Earth.pic")
local onScreenDataXOffset, onScreenDataYOffset = math.floor(bufferWidth / 2), bufferHeight
local onProjectorDataYOffset = 0
local scanResult = {horizontalRange = 0, verticalRange = 0}
local mainContainer = GUI.fullScreenContainer()
--------------------------------------------------------------------------------------------------------------------
local function getOpenGLValidColorChannels(cykaColor)
local r, g, b = color.integerToRGB(cykaColor)
return r / 255, g / 255, b / 255
end
local function createCube(x, y, z, cykaColor, isVisThrObj)
local cube = component.glasses.addCube3D()
cube.set3DPos(x, y, z)
cube.setVisibleThroughObjects(isVisThrObj)
cube.setColor(getOpenGLValidColorChannels(cykaColor))
cube.setAlpha(0.23)
return cube
end
local function glassesCreateCube(x, y, z, cykaColor, text)
local cube = createCube(x, y, z, cykaColor, true)
cube.setVisibleThroughObjects(true)
local floatingText = component.glasses.addFloatingText()
floatingText.set3DPos(x + 0.5, y + 0.5, z + 0.5)
floatingText.setColor(1, 1, 1)
floatingText.setAlpha(0.6)
floatingText.setText(text)
floatingText.setScale(0.015)
end
local function createDick(x, y, z, chance, isVisThrObj)
if component.isAvailable("glasses") and math.random(1, 100) <= chance then
createCube(x, y, z, 0xFFFFFF, isVisThrObj)
createCube(x + 1, y, z, 0xFFFFFF, isVisThrObj)
createCube(x + 2, y, z, 0xFFFFFF, isVisThrObj)
createCube(x + 1, y + 1, z, 0xFFFFFF, isVisThrObj)
createCube(x + 1, y + 2, z, 0xFFFFFF, isVisThrObj)
createCube(x + 1, y + 3, z, 0xFFFFFF, isVisThrObj)
createCube(x + 1, y + 5, z, 0xFF8888, isVisThrObj)
end
end
local function progressReport(value, text)
local width = 40
local x, y = math.floor(bufferWidth / 2 - width / 2), math.floor(bufferHeight / 2)
GUI.progressBar(x, y, width, 0x00B6FF, 0xFFFFFF, 0xEEEEEE, value, true, true, text, "%"):draw()
buffer.drawChanges()
end
local function updateData(onScreen, onProjector, onGlasses)
local glassesAvailable = component.isAvailable("glasses")
if onScreen then buffer.clear(0xEEEEEE) end
if onProjector then component.hologram.clear() end
if onGlasses and glassesAvailable then component.glasses.removeAll() end
local min, max = tonumber(mainContainer.minimumHardnessTextBox.text), tonumber(mainContainer.maximumHardnessTextBox.text)
if min and max then
local horizontalRange, verticalRange = math.floor(mainContainer.horizontalScanRangeSlider.value), math.floor(mainContainer.verticalScanRangeSlider.value)
for x = -horizontalRange, horizontalRange do
for z = -horizontalRange, horizontalRange do
for y = 32 - verticalRange, 32 + verticalRange do
if scanResult[x] and scanResult[x][z] and scanResult[x][z][y] and scanResult[x][z][y] >= min and scanResult[x][z][y] <= max then
if onScreen then
buffer.semiPixelSet(onScreenDataXOffset + x, onScreenDataYOffset + 32 - y, 0x454545)
end
if onProjector and mainContainer.projectorUpdateSwitch.state then
component.hologram.set(horizontalRange + x, math.floor(mainContainer.projectorYOffsetSlider.value) + y - 32, horizontalRange + z, 1)
end
if onGlasses and mainContainer.glassesUpdateSwitch.state and glassesAvailable then
glassesCreateCube(x, y - 32, z, mainContainer.glassesOreColorButton.colors.default.background, "Hardness: " .. string.format("%.2f", scanResult[x][z][y]))
os.sleep(0)
end
end
end
end
end
end
end
local oldDraw = mainContainer.draw
mainContainer.draw = function()
updateData(true, false, false)
oldDraw(mainContainer)
end
local panelWidth = 30
local panelX = bufferWidth - panelWidth + 1
local buttonX, objectY = panelX + 2, 2
local buttonWidth = panelWidth - 4
mainContainer:addChild(GUI.panel(panelX, 1, panelWidth, bufferHeight, 0x444444))
mainContainer.planetImage = mainContainer:addChild(GUI.image(buttonX, objectY, earthImage))
objectY = objectY + mainContainer.planetImage.image[2] + 1
mainContainer:addChild(GUI.label(buttonX, objectY, buttonWidth, 1, 0xFFFFFF, "GeoScan v2.0")):setAlignment(GUI.ALIGNMENT_HORIZONTAL_CENTER, GUI.ALIGNMENT_VERTICAL_TOP)
objectY = objectY + 2
mainContainer.horizontalScanRangeSlider = mainContainer:addChild(GUI.slider(buttonX, objectY, buttonWidth, 0xFFDB80, 0x000000, 0xFFDB40, 0xBBBBBB, 4, 24, 16, false, "Horizontal scan range: "))
mainContainer.horizontalScanRangeSlider.roundValues = true
objectY = objectY + 3
mainContainer.verticalScanRangeSlider = mainContainer:addChild(GUI.slider(buttonX, objectY, buttonWidth, 0xFFDB80, 0x000000, 0xFFDB40, 0xBBBBBB, 4, 32, 16, false, "Vertical show range: "))
mainContainer.verticalScanRangeSlider.roundValues = true
objectY = objectY + 4
mainContainer:addChild(GUI.label(buttonX, objectY, buttonWidth, 1, 0xFFFFFF, "Rendering properties")):setAlignment(GUI.ALIGNMENT_HORIZONTAL_CENTER, GUI.ALIGNMENT_VERTICAL_TOP)
objectY = objectY + 2
mainContainer.minimumHardnessTextBox = mainContainer:addChild(GUI.input(buttonX, objectY, 12, 3, 0x262626, 0xBBBBBB, 0xBBBBBB, 0x262626, 0xFFFFFF, tostring(2.7), nil, true))
mainContainer.maximumHardnessTextBox = mainContainer:addChild(GUI.input(buttonX + 14, objectY, 12, 3, 0x262626, 0xBBBBBB, 0xBBBBBB, 0x262626, 0xFFFFFF, tostring(10), nil, true))
objectY = objectY + 3
mainContainer:addChild(GUI.label(buttonX, objectY, buttonWidth, 1, 0xBBBBBB, "Hardness min Hardness max")):setAlignment(GUI.ALIGNMENT_HORIZONTAL_CENTER, GUI.ALIGNMENT_VERTICAL_TOP)
objectY = objectY + 2
mainContainer.projectorScaleSlider = mainContainer:addChild(GUI.slider(buttonX, objectY, buttonWidth, 0xFFDB80, 0x000000, 0xFFDB40, 0xBBBBBB, 0.33, 3, component.hologram.getScale(), false, "Projection scale: "))
mainContainer.projectorScaleSlider.onValueChanged = function()
component.hologram.setScale(mainContainer.projectorScaleSlider.value)
end
objectY = objectY + 3
mainContainer.projectorYOffsetSlider = mainContainer:addChild(GUI.slider(buttonX, objectY, buttonWidth, 0xFFDB80, 0x000000, 0xFFDB40, 0xBBBBBB, 0, 64, 4, false, "Projection Y offset: "))
mainContainer.projectorYOffsetSlider.roundValues = true
objectY = objectY + 3
local function setButtonColorFromPalette(button)
local selectedColor = GUI.palette(math.floor(mainContainer.width / 2 - 35), math.floor(mainContainer.height / 2 - 12), button.colors.default.background):show()
if selectedColor then button.colors.default.background = selectedColor end
mainContainer:drawOnScreen()
end
local function updateProjectorColors()
component.hologram.setPaletteColor(1, mainContainer.color1Button.colors.default.background)
end
local color1, color2, color3 = component.hologram.getPaletteColor(1), component.hologram.getPaletteColor(2), component.hologram.getPaletteColor(3)
mainContainer.color1Button = mainContainer:addChild(GUI.button(buttonX, objectY, buttonWidth, 1, color1, 0xBBBBBB, 0xEEEEEE, 0x262626, "Projector color")); objectY = objectY + 1
mainContainer.color1Button.onTouch = function()
setButtonColorFromPalette(mainContainer.color1Button)
updateProjectorColors()
end
mainContainer.glassesOreColorButton = mainContainer:addChild(GUI.button(buttonX, objectY, buttonWidth, 1, 0x0044FF, 0xBBBBBB, 0xEEEEEE, 0x262626, "Glasses ore color"))
mainContainer.glassesOreColorButton.onTouch = function()
setButtonColorFromPalette(mainContainer.glassesOreColorButton)
end
objectY = objectY + 2
mainContainer:addChild(GUI.label(buttonX, objectY, buttonWidth, 1, 0xBBBBBB, "Projector update:"))
mainContainer.projectorUpdateSwitch = mainContainer:addChild(GUI.switch(bufferWidth - 8, objectY, 7, 0xFFDB40, 0xAAAAAA, 0xFFFFFF, true))
objectY = objectY + 2
mainContainer:addChild(GUI.label(buttonX, objectY, buttonWidth, 1, 0xBBBBBB, "Glasses update:"))
mainContainer.glassesUpdateSwitch = mainContainer:addChild(GUI.switch(bufferWidth - 8, objectY, 7, 0xFFDB40, 0xAAAAAA, 0xFFFFFF, true))
objectY = objectY + 2
mainContainer:addChild(GUI.button(bufferWidth, 1, 1, 1, nil, 0xEEEEEE, nil, 0xFF2222, "X")).onTouch = function()
mainContainer:stopEventHandling()
createDick(math.random(-48, 48), math.random(1, 32), math.random(-48, 48), 100, true)
end
mainContainer:addChild(GUI.button(panelX, bufferHeight - 5, panelWidth, 3, 0x353535, 0xEEEEEE, 0xAAAAAA, 0x262626, "Update")).onTouch = function()
updateData(false, true, true)
end
mainContainer.scanButton = mainContainer:addChild(GUI.button(panelX, bufferHeight - 2, panelWidth, 3, 0x262626, 0xEEEEEE, 0xAAAAAA, 0x262626, "Scan"))
mainContainer.scanButton.onTouch = function()
scanResult = {}
local horizontalRange, verticalRange = math.floor(mainContainer.horizontalScanRangeSlider.value), math.floor(mainContainer.verticalScanRangeSlider.value)
local total, current = (horizontalRange * 2 + 1) ^ 2, 0
buffer.clear(0x0, 0.48)
for x = -horizontalRange, horizontalRange do
scanResult[x] = {}
for z = -horizontalRange, horizontalRange do
scanResult[x][z] = component.geolyzer.scan(x, z)
current = current + 1
progressReport(math.ceil(current / total * 100), "Scan progress: ")
buffer.drawChanges()
end
end
mainContainer:drawOnScreen()
updateData(false, true, true)
end
--------------------------------------------------------------------------------------------------------------------
buffer.clear(0x0)
mainContainer:drawOnScreen()
mainContainer:startEventHandling()
|
--------------------------------------------------
local action = _ACTION
local options = _OPTIONS
local cfg = premake.config
--------------------------------------------------
if action == "clean" then
os.rmdir("build")
os.exit(1)
end
--------------------------------------------------
if action == "gmake2" then
if nil == options["cc"] then
print("Choose a C/C++ compiler set.")
os.exit(1)
end
end
--------------------------------------------------
workspace "gui-sdk"
location( "build/project/" .. _ACTION )
characterset "MBCS"
staticruntime "On"
omitframepointer "On"
--------------------------------------------------
configurations { "Debug", "Release" }
filter { "configurations:Debug" }
defines { "DEBUG" }
symbols "On"
filter { "configurations:Release" }
defines { "NDEBUG" }
optimize "On"
--------------------------------------------------
filter {"system:windows"}
platforms { "x64" }
defines { "TARGET_OS_WINDOWS", "WIN32_LEAN_AND_MEAN" }
entrypoint "mainCRTStartup"
filter {"system:linux"}
platforms { "x64", "arm32", "arm64" }
defines { "TARGET_OS_LINUX" }
filter {"platforms:arm*"}
defines { "TARGET_OS_LINUX_ARM" }
--------------------------------------------------
filter {"platforms:x64"}
architecture "x86_64"
filter {"platforms:arm32"}
architecture "arm"
--gccprefix "armv7a-linux-gnueabihf-"
filter {"platforms:arm64"}
architecture "aarch64"
--gccprefix "aarch64-linux-gnueabi-"
--------------------------------------------------
group "libs"
include "libs/glfw"
include "libs/imgui"
include "libs/ofx"
group ""
include("main/premake5.lua")
--------------------------------------------------
|
-- hide join/enter messages for custom chat channels?
CSU_HideJoinEnter = true
-- hide all system messages that contains one of the following substrings
CSU_HideSystemContains = {
["Autobroadcast"] = true,
}
-- enable anti spam feature?
CSU_MuteSpam = true
-- use anti spam per user? (true recommended)
CSU_MuteSpam_PerUser = true
-- max spam messages to appear in each channel
CSU_MuteSpam_MaxCount = {
CHAT_MSG_SAY = 1,
CHAT_MSG_CHANNEL = 1,
CHAT_MSG_PARTY = 2,
CHAT_MSG_RAID = 3,
CHAT_MSG_YELL = 1,
CHAT_MSG_WHISPER = 1,
CHAT_MSG_EMOTE = 1,
CHAT_MSG_TEXT_EMOTE = 1,
}
-- max mute duration of spam
CSU_MuteSpam_Duration = {
CHAT_MSG_RAID = 1.0,
CHAT_MSG_PARTY = 2.0,
CHAT_MSG_SAY = 5.0,
CHAT_MSG_CHANNEL = 5.0,
CHAT_MSG_YELL = 5.0,
CHAT_MSG_WHISPER = 5.0,
CHAT_MSG_EMOTE = 5.0,
CHAT_MSG_TEXT_EMOTE = 5.0,
}
-- cleanup interval, just leave it to 1 minute
CSU_Cleanup_Interval = 60
|
resource_manifest_version '05cfa83c-a124-4cfa-a768-c24a5811d8f9'
client_script "@NativeUI/NativeUI.lua"
client_script "MenuExample.lua" |
return {
scenario = {
obtain_stone = {
fool = "愚者の魔石を手に入れた!",
king = "覇者の魔石を手に入れた!",
sage = "賢者の魔石を手に入れた!"
},
three_years_later = "三年の月日が経ち、あなたは再びノースティリスに降り立った。",
}
}
|
-- mdotengine - conf file
function love.conf(t)
t.window.title = "mdotengine"
t.window.icon = "lib/sprite/logo.png"
t.console = true
t.window.fullscreen = false
t.window.width = 600
t.window.height = 600
t.window.vsync = false
t.window.resizable = false
t.modules.joystick = false
t.modules.physics = false
end |
local hudLines = {}
function hudLines:update(dt) end
function hudLines:draw()
love.graphics.line(love.graphics.getWidth() / 2 - 150, 0,
love.graphics.getWidth() / 2 - 150,
love.graphics.getHeight())
love.graphics.line(love.graphics.getWidth() / 2 + 150, 0,
love.graphics.getWidth() / 2 + 150,
love.graphics.getHeight())
love.graphics.line(love.graphics.getWidth() / 2 - 150, 0,
love.graphics.getWidth() / 2 + 150, 0)
love.graphics.line(love.graphics.getWidth() / 2 - 150,
love.graphics.getHeight(),
love.graphics.getWidth() / 2 + 150,
love.graphics.getHeight())
if GameVars.second then
love.graphics.line(love.graphics.getWidth() / 2 - 650, 0,
love.graphics.getWidth() / 2 - 650,
love.graphics.getHeight())
love.graphics.line(love.graphics.getWidth() / 2 - 350, 0,
love.graphics.getWidth() / 2 - 350,
love.graphics.getHeight())
end
end
return hudLines
|
local feature = require('fur.feature')
local lsp = feature:new('lsp')
lsp.source = 'lua/features/lsp.lua'
lsp.plugins = {
'neovim/nvim-lspconfig',
{
'folke/trouble.nvim',
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require('trouble').setup({})
end,
}, -- lsp signature
}
lsp.setup = function()
-- local signs = { Error = "", Warning = "", Hint = "", Information = "" }
local signs = { Error = '✗', Warning = '‼', Information = '!', Hint = '!' } -- also used by "nvim.trouble"
for sign, text in pairs(signs) do
local hl = 'LspDiagnosticsSign' .. sign
vim.fn.sign_define(hl, { text = text, texthl = hl, linehl = '', numhl = '' })
end
end
lsp.mappings = {
{ 'n', '<leader>xx', '<cmd>TroubleToggle<cr>', { silent = true } },
-- { "n", "<leader>xw", "<cmd>Trouble lsp_workspace_diagnostics<cr>", { silent = true } },
-- { "n", "<leader>xd", "<cmd>Trouble lsp_document_diagnostics<cr>", { silent = true } },
{ 'n', '<leader>xl', '<cmd>Trouble loclist<cr>', { silent = true } },
{ 'n', '<leader>xq', '<cmd>Trouble quickfix<cr>', { silent = true } },
}
local lspui_ext = feature:new('lspui_ext')
lspui_ext.plugins = {
{
'ray-x/lsp_signature.nvim',
config = function()
require('lib.lsp').add_on_attach(function(_, _)
require('lsp_signature').on_attach({ bind = true, handler_opts = { border = 'none' } })
end)
end,
},
{
'RishabhRD/nvim-lsputils',
requires = { { 'RishabhRD/popfix' } },
config = function()
vim.lsp.handlers['textDocument/codeAction'] = require('lsputil.codeAction').code_action_handler
vim.lsp.handlers['textDocument/references'] = require('lsputil.locations').references_handler
vim.lsp.handlers['textDocument/definition'] = require('lsputil.locations').definition_handler
vim.lsp.handlers['textDocument/declaration'] = require('lsputil.locations').declaration_handler
vim.lsp.handlers['textDocument/typeDefinition'] = require('lsputil.locations').typeDefinition_handler
vim.lsp.handlers['textDocument/implementation'] = require('lsputil.locations').implementation_handler
vim.lsp.handlers['textDocument/documentSymbol'] = require('lsputil.symbols').document_handler
vim.lsp.handlers['workspace/symbol'] = require('lsputil.symbols').workspace_handler
end,
},
}
lsp.children = { lspui_ext }
return lsp
|
-- Various home electronics
local S = homedecor.gettext
homedecor.register("speaker", {
description = S("Large Stereo Speaker"),
mesh="homedecor_speaker_large.obj",
tiles = {
"homedecor_speaker_sides.png",
"homedecor_speaker_front.png"
},
groups = { snappy = 3 },
sounds = default.node_sound_wood_defaults(),
on_punch = function(pos, node, puncher, pointed_thing)
minetest.set_node(pos, {name = "homedecor:speaker_open", param2 = node.param2})
end
})
homedecor.register("speaker_open", {
description = S("Large Stereo Speaker, open front"),
mesh="homedecor_speaker_large_open.obj",
tiles = {
"homedecor_speaker_sides.png",
"homedecor_speaker_driver.png",
"homedecor_speaker_open_front.png",
"homedecor_generic_metal_black.png"
},
groups = { snappy = 3, not_in_creative_inventory=1 },
sounds = default.node_sound_wood_defaults(),
on_punch = function(pos, node, puncher, pointed_thing)
minetest.set_node(pos, {name = "homedecor:speaker", param2 = node.param2})
end
})
local spk_cbox = {
type = "fixed",
fixed = { -3/16, -8/16, 1/16, 3/16, -2/16, 7/16 }
}
homedecor.register("speaker_small", {
description = S("Small Surround Speaker"),
mesh="homedecor_speaker_small.obj",
tiles = {
"homedecor_speaker_sides.png",
"homedecor_speaker_front.png"
},
selection_box = spk_cbox,
walkable = false,
groups = { snappy = 3 },
sounds = default.node_sound_wood_defaults(),
})
homedecor.register("stereo", {
description = S("Stereo Receiver"),
tiles = { 'homedecor_stereo_top.png',
'homedecor_stereo_bottom.png',
'homedecor_stereo_left.png^[transformFX',
'homedecor_stereo_left.png',
'homedecor_stereo_back.png',
'homedecor_stereo_front.png'},
groups = { snappy = 3 },
sounds = default.node_sound_wood_defaults(),
})
homedecor.register("projection_screen", {
description = S("Projection Screen Material"),
drawtype = 'signlike',
tiles = { 'homedecor_projection_screen.png' },
wield_image = 'homedecor_projection_screen_inv.png',
inventory_image = 'homedecor_projection_screen_inv.png',
walkable = false,
groups = { snappy = 3 },
sounds = default.node_sound_leaves_defaults(),
paramtype2 = 'wallmounted',
selection_box = {
type = "wallmounted",
--wall_side = = <default>
},
})
homedecor.register("television", {
description = S("Small CRT Television"),
tiles = { 'homedecor_television_top.png',
'homedecor_television_bottom.png',
'homedecor_television_left.png^[transformFX',
'homedecor_television_left.png',
'homedecor_television_back.png',
{ name="homedecor_television_front_animated.png",
animation={
type="vertical_frames",
aspect_w=16,
aspect_h=16,
length=80.0
}
}
},
light_source = default.LIGHT_MAX - 1,
groups = { snappy = 3 },
sounds = default.node_sound_wood_defaults(),
})
homedecor.register("dvd_vcr", {
description = S("DVD and VCR"),
tiles = {
"homedecor_dvdvcr_top.png",
"homedecor_dvdvcr_bottom.png",
"homedecor_dvdvcr_sides.png",
"homedecor_dvdvcr_sides.png^[transformFX",
"homedecor_dvdvcr_back.png",
"homedecor_dvdvcr_front.png",
},
inventory_image = "homedecor_dvdvcr_inv.png",
node_box = {
type = "fixed",
fixed = {
{-0.3125, -0.5, -0.25, 0.3125, -0.375, 0.1875},
{-0.25, -0.5, -0.25, 0.25, -0.1875, 0.125},
}
},
groups = { snappy = 3 },
sounds = default.node_sound_wood_defaults(),
})
local tel_cbox = {
type = "fixed",
fixed = { -0.25, -0.5, -0.1875, 0.25, -0.21, 0.15 }
}
homedecor.register("telephone", {
mesh = "homedecor_telephone.obj",
tiles = {
"homedecor_telephone_dial.png",
"homedecor_telephone_base.png",
"homedecor_telephone_handset.png",
"homedecor_telephone_cord.png",
},
inventory_image = "homedecor_telephone_inv.png",
description = "Telephone",
groups = {snappy=3},
selection_box = tel_cbox,
walkable = false,
sounds = default.node_sound_wood_defaults(),
})
minetest.register_abm({
nodenames = "homedecor:telephone",
label = "sfx",
interval = 30,
chance = 15,
action = function(pos, node)
minetest.sound_play("homedecor_telephone_ringing", {
pos = pos,
gain = 1.0,
max_hear_distance = 5
})
end
})
|
for _, player in pairs(game.Players:GetChildren()) do
if player.Name ~= game.Players.LocalPlayer.Name then
workspace.Remote.Damage:FireServer(workspace[player.Name].Humanoid, 0)
end
end
wait(6)
for _, corpse in pairs(workspace:GetChildren()) do
if corpse.Name == "Corpse" then
corpse:MoveTo(workspace[game.Players.LocalPlayer.Name].Torso.Position + Vector3.new(math.random(-10,10),0,math.random(-10,10)))
end
end |
if not Utils:IsInGameState() then
do return end
end
if not Network:is_server() then
UT.showMessage("host only", UT.colors.error)
do return end
end
local amountOfAlivePlayers = managers.network:session():amount_of_alive_players()
managers.network:session():send_to_peers("mission_ended", true, amountOfAlivePlayers)
game_state_machine:change_state_by_name("victoryscreen", {num_winners = amountOfAlivePlayers, personal_win = true}) |
--Custom specialization for planters / seeders that put down chemical
--Fixes the double fertilizing bug and allows herbicide to work
--Almost entirely a copy of the default FertilizingSowingMachine
HerbicidalSpec = {}
function HerbicidalSpec.initSpecialization()
print("HerbicidalSpec.initSpecialization()!")
HerbicidalSpec.spec_sowingMachine =g_specializationManager:getSpecializationByName("sowingMachine")
HerbicidalSpec.spec_sprayer =g_specializationManager:getSpecializationByName("sprayer")
end
function HerbicidalSpec.prerequisitesPresent(specializations)
return SpecializationUtil.hasSpecialization(SowingMachine, specializations) and SpecializationUtil.hasSpecialization(Sprayer, specializations)
end
function HerbicidalSpec.registerOverwrittenFunctions(vehicleType)
SpecializationUtil.registerOverwrittenFunction(vehicleType, "processSowingMachineArea", HerbicidalSpec.processSowingMachineArea)
SpecializationUtil.registerOverwrittenFunction(vehicleType, "getUseSprayerAIRequirements", HerbicidalSpec.getUseSprayerAIRequirements)
SpecializationUtil.registerOverwrittenFunction(vehicleType, "getAreEffectsVisible", HerbicidalSpec.getAreEffectsVisible)
end
function HerbicidalSpec.registerEventListeners(vehicleType)
SpecializationUtil.registerEventListener(vehicleType, "onLoad", HerbicidalSpec)
end
function HerbicidalSpec:onLoad(savegame)
self.needsSetIsTurnedOn = Utils.getNoNil(getXMLBool(self.xmlFile, "vehicle.herbicidalSowingMachine#needsSetIsTurnedOn"), false)
self.spec_sprayer.needsToBeFilledToTurnOn = false
self.spec_sprayer.useSpeedLimit = false
end
function HerbicidalSpec:processSowingMachineArea(superFunc, workArea, dt)
local spec = self
local specSowingMachine = self.spec_sowingMachine
local specSpray = self.spec_sprayer
local sprayerParams = specSpray.workAreaParameters
local sowingParams = specSowingMachine.workAreaParameters
local changedArea, totalArea
self.spec_sowingMachine.isWorking = self:getLastSpeed() > 0.5
if not sowingParams.isActive then
return 0, 0
end
if not self:getIsAIActive() or not g_currentMission.missionInfo.helperBuySeeds then
if sowingParams.seedsVehicle == nil then
if self:getIsAIActive() then
local rootVehicle = self:getRootVehicle()
rootVehicle:stopAIVehicle(AIVehicle.STOP_REASON_OUT_OF_FILL)
end
return 0, 0
end
end
-- stop the sowing machine if the fertilizer tank was filled and got empty
-- do not stop if the tank was all the time empty
if not g_currentMission.missionInfo.helperBuyFertilizer then
if self:getIsAIActive() then
if sprayerParams.sprayFillType == nil or sprayerParams.sprayFillType == FillType.UNKNOWN then
if sprayerParams.lastAIHasSprayed ~= nil then
local rootVehicle = self:getRootVehicle()
rootVehicle:stopAIVehicle(AIVehicle.STOP_REASON_OUT_OF_FILL)
sprayerParams.lastAIHasSprayed = nil
end
else
sprayerParams.lastAIHasSprayed = true
end
end
end
if not sowingParams.canFruitBePlanted then
return 0, 0
end
-- we need to use fertilizer as spraying type because fertilizer is the final blocking value
local sprayTypeIndex = SprayType.FERTILIZER
if sprayerParams.sprayFillLevel <= 0 or (spec.needsSetIsTurnedOn and not self:getIsTurnedOn()) then
sprayTypeIndex = nil
end
local startX,_,startZ = getWorldTranslation(workArea.start)
local widthX,_,widthZ = getWorldTranslation(workArea.width)
local heightX,_,heightZ = getWorldTranslation(workArea.height)
if not specSowingMachine.useDirectPlanting then
changedArea, totalArea = FSDensityMapUtil.updateSowingArea(sowingParams.seedsFruitType, startX, startZ, widthX, widthZ, heightX, heightZ, sowingParams.angle, nil, sprayTypeIndex)
else
changedArea, totalArea = FSDensityMapUtil.updateDirectSowingArea(sowingParams.seedsFruitType, startX, startZ, widthX, widthZ, heightX, heightZ, sowingParams.angle, nil, sprayTypeIndex)
end
self.spec_sowingMachine.isProcessing = self.spec_sowingMachine.isWorking
sowingParams.lastChangedArea = sowingParams.lastChangedArea + changedArea
sowingParams.lastStatsArea = sowingParams.lastStatsArea + changedArea
sowingParams.lastTotalArea = sowingParams.lastTotalArea + totalArea
-- remove tireTracks
FSDensityMapUtil.eraseTireTrack(startX, startZ, widthX, widthZ, heightX, heightZ)
self:updateMissionSowingWarning(startX, startZ)
return changedArea, totalArea
end
function HerbicidalSpec:getUseSprayerAIRequirements(superFunc)
return false
end
function HerbicidalSpec:getAreEffectsVisible(superFunc)
return superFunc(self) and self:getFillUnitFillType(self:getSprayerFillUnitIndex()) ~= FillType.UNKNOWN
end |
local json_encode = require('cjson.safe').encode
local parse_accept_header = require('httoolsp.headers').parse_accept_header
local render_to_string = require('app.views.helpers').render_to_string
local ngx_say = ngx.say
local ngx_exit = ngx.exit
local ngx_req = ngx.req
local ngx_header = ngx.header
local ngx_HTTP_OK = ngx.HTTP_OK
local REASONS = {
[400] = 'Bad Request',
[403] = 'Forbidden',
[404] = 'Not Found',
[405] = 'Method Not Allowed',
[413] = 'Payload Too Large',
[411] = 'Length Required',
[500] = 'Internal Server Error',
[501] = 'Not Implemented',
[502] = 'Bad Gateway',
}
local MEDIA_TYPES = {
'text/html',
'application/json',
'text/plain',
}
local DEFAULT_MEDIA_TYPE = MEDIA_TYPES[1]
local error_page_cache = {}
local error_handler = function()
local args = ngx_req.get_uri_args()
local status = tonumber(args.status or ngx.status)
ngx.status = status
local description = args.description
local content_type
local accept_header = ngx_req.get_headers()['accept']
if type(accept_header) == 'table' then
accept_header = accept_header[1]
end
if accept_header then
content_type = parse_accept_header(accept_header):negotiate(MEDIA_TYPES)
end
if not content_type then
content_type = DEFAULT_MEDIA_TYPE
end
ngx_header['content-type'] = content_type
if content_type == 'text/plain' then
ngx_say('ERROR: ', description or status)
return ngx_exit(ngx_HTTP_OK)
elseif content_type == 'application/json' then
ngx_say(json_encode{
error_code = status,
error_description = description,
})
return ngx_exit(ngx_HTTP_OK)
else
-- do not cache error pages with arbitrary descriptions
local cacheable = not description
if cacheable then
local cached = error_page_cache[status]
if cached then
ngx_say(cached)
return ngx_exit(ngx_HTTP_OK)
end
end
local content = render_to_string('web/error.html', {
title = status,
status = status,
reason = REASONS[status],
description = description,
})
if cacheable then
error_page_cache[status] = content
end
ngx_say(content)
return ngx_exit(ngx_HTTP_OK)
end
end
return {
REASONS = REASONS,
error_handler = error_handler,
}
|
QznnbHallCcsView = class("QznnbHallCcsView")
QznnbHallCcsView.onCreationComplete = function (slot0)
ClassUtil.extends(slot0, BaseGameHallCcsView, true)
BaseGameHallCcsView.onCreationComplete(slot0, "common/QznnbHallItem.csb", 50, 100, 100, 50)
ClassUtil.extends(slot0, BaseGameAniamtionView, true, {
{
fromAlpha = 0,
node = slot0.layerList,
fromPos = cc.p(0, -50)
}
})
end
QznnbHallCcsView.onHide = function (slot0)
BaseGameAniamtionView.onHide(slot0)
BaseGameHallCcsView.onHide(slot0)
end
QznnbHallCcsView.onShow = function (slot0)
slot0.model:setIsShowingRoomTxt(true)
slot0.model:setIsShowingBtnBack(true)
slot0.model:setIsShowingBtnHelp(true)
slot0.model:setIsShowingLogo(false)
slot0.model:setIsShowingPlayerInfo(false)
slot0.model:setIsShowingMainScore(false)
slot0.model:setIsShowingQuickStart(true)
BaseGameAniamtionView.onShow(slot0)
BaseGameHallCcsView.onShow(slot0)
end
QznnbHallCcsView.onBtnClick = function (slot0, slot1, slot2)
return
end
QznnbHallCcsView.destroy = function (slot0)
BaseGameAniamtionView.destroy(slot0)
BaseGameHallCcsView.destroy(slot0)
end
return
|
local item_width = THEME:GetMetric("OptionRow","ItemsStartX") + scale( SCREEN_WIDTH, 960, 1280, SCREEN_RIGHT-300 + 30, SCREEN_RIGHT-20 + 30)
return Def.ActorFrame{
Def.Quad{
OnCommand=cmd(x,223;zoomto,item_width,35;diffuse,{0,0,0,0.6}; fadeleft,0.2;faderight,0.2;);
};
Def.Sprite{
OnCommand=function(self)
(cmd(x,223;diffuse,{1,1,1,0}; fadeleft,0.1;faderight,0.1;))(self)
local isFocus = self:GetParent():GetParent():GetParent():HasFocus( GAMESTATE:GetMasterPlayerNumber() )
if isFocus then
self:playcommand("GainFocus")
end
end;
--cmd(x,223;y,-34.5/2;zoomto,0, 0;diffuse,{1,1,1,1}; fadeleft,0.1;faderight,0.1;);
GainFocusCommand=function(self)
self:Load(THEME:GetPathG("OptionRow","FG"))
if self:GetParent():GetParent():GetParent():HasFocus( PLAYER_1 ) then
self:diffuseleftedge(PlayerColor(PLAYER_1))
else
self:diffuseleftedge({1,1,1,0})
end
if self:GetParent():GetParent():GetParent():HasFocus( PLAYER_2 ) then
self:diffuserightedge(PlayerColor(PLAYER_2))
else
self:diffuserightedge({1,1,1,0})
end
self:stoptweening():decelerate(0.2):diffusealpha(0.7)
end;
LoseFocusCommand=cmd(stoptweening;decelerate,0.2;diffusealpha,0);
};
Def.Quad{
OnCommand=function(self)
(cmd(x,223;y,-34.5/2;zoomto,0, 0;diffuse,{1,1,1,1}; fadeleft,0.1;faderight,0.1;))(self)
local isFocus = self:GetParent():GetParent():GetParent():HasFocus( GAMESTATE:GetMasterPlayerNumber() )
if isFocus then
self:playcommand("GainFocus")
end
end;
--cmd(x,223;y,-34.5/2;zoomto,0, 0;diffuse,{1,1,1,1}; fadeleft,0.1;faderight,0.1;);
GainFocusCommand=cmd(stoptweening;decelerate,0.2;zoomto,item_width, 2);
LoseFocusCommand=cmd(stoptweening;decelerate,0.2;zoomto,0 ,0);
};
Def.Quad{
OnCommand=function(self)
(cmd(x,223;y,34.5/2;zoomto,0, 0;diffuse,{1,1,1,1}; fadeleft,0.1;faderight,0.1;))(self)
local isFocus = self:GetParent():GetParent():GetParent():HasFocus( GAMESTATE:GetMasterPlayerNumber() )
if isFocus then
self:playcommand("GainFocus")
end
end;
GainFocusCommand=cmd(stoptweening;decelerate,0.2;zoomto,item_width, 2);
LoseFocusCommand=cmd(stoptweening;decelerate,0.2;zoomto,0, 0);
};
}; |
lpc=game.Players.LocalPlayer.Character
m=Instance.new("Model",lpc)
m.Name=lpc.Name.."'s Protector"
p=Instance.new("Part",m)
p.Name="Head"
p.Size=Vector3.new(2,2,2)
b=Instance.new("BodyPosition",p)
b.maxForce = Vector3.new()*math.huge
p.Shape="Ball"
p.TopSurface,p.BottomSurface="Smooth","Smooth"
p.BrickColor=BrickColor.new("Bright red")
p.Transparency=0.5
h=Instance.new("Humanoid",m)
h.Health,h.MaxHealth=0,0
p.Touched:connect(function(h)
if h.Parent:findFirstChild("Humanoid") then
if h.Parent.Name~=game.Players.LocalPlayer.Name then
s=Instance.new("StringValue",h.Parent.Humanoid)
s.Name="creator"
s.Value=lpc.Name
h:BreakJoints()
end
end
end)
track = false
function trail(obj,s,t,lt,color,fade)
coroutine.resume(coroutine.create(function()
while track do
old = obj.Position
wait()
new = obj.Position
-- mag = (old-new).magnitude
dist = (old+new)/2
local ray = Instance.new("Part",lpc)
ray.TopSurface,ray.BottomSurface = 0,0
ray.Anchored = true
ray.formFactor = "Custom"
ray.CanCollide = false
ray.Color = obj.Color
ray.Transparency = .5
ray.Size = Vector3.new(2,2,2)
ray.Shape = "Ball"
ray.CFrame = CFrame.new(dist,old)*CFrame.Angles(math.pi/2,0,0)
if fade ~= nil then
delay(lt,function()
for i = t,1,fade do wait() ray.Transparency = i end ray:Remove() end)
else
game:GetService("Debris"):AddItem(ray,lt)
end
if color ~= nil then ray.BrickColor = BrickColor.new(color) end
end
end)) end
track = true trail(p,.5,.5,1)
coroutine.resume(coroutine.create(function()
while wait() do
r = 10
for i = 1,360,5 do
wait()
b.position=lpc.Torso.Position + Vector3.new(math.cos(math.rad(i))*r,math.sin(i*50),math.sin(math.rad(i))*r)
end
end
end))
function Cht(m,s)
pcall(function()
if m=="on/" then
p.Touched:connect(function(h)
if h.Parent:findFirstChild("Humanoid") then
if h.Parent.Name~=game.Players.LocalPlayer.Name then
s=Instance.new("StringValue",h.Parent.Humanoid)
s.Name="creator"
s.Value=lpc.Name
h:BreakJoints()
end
end
end)
end
if m=="off/" then
p.Touched:connect(function() end)
end
if m=="protect/" then
lpc.Humanoid.MaxHealth=1/0
p.BrickColor=BrickColor.new("Navy blue")
Instance.new("ForceField",lpc)
end
if m=="kill/" then
p.BrickColor=BrickColor.new("New Yeller")
lpc:BreakJoints()
end
if m=="reset/" then
m=Instance.new("Model",Workspace)
m.Name=lpc.Name
x=Instance.new("Humanoid",m)
h=Instance.new("Part",m)
h.Name="Head"
t=Instance.new("Part",m)
t.Name="Torso"
t.Anchored=true
h.Anchored=true
t.Transparency=1
h.Transparency=1
game.Players.LocalPlayer.Character=m
lpc:remove()
end
end)
end
game.Players.LocalPlayer.Chatted:connect(function(m) Cht(m,lpc.Parent) end)
|
local ffi = require('ffi')
local C = ffi.C
local errors = require("levee.errors")
local _ = {}
_.stat = require("levee._.syscalls").stat
local buflen = C.SP_PATH_MAX * 4
local buf = ffi.cast("char *", C.malloc(buflen))
local ranges = ffi.new("SpRange16 [2]")
local procname = false
local procname_err, procname_val
local cwd = ffi.string(C.getcwd(buf, buflen))
function _.cwd(s)
if s then
s = _.join(cwd, s)
local rc = C.chdir(s)
if rc < 0 then return errors.get(ffi.errno()) end
cwd = s
end
return nil, cwd
end
function _.abs(s)
return _.join(cwd, s)
end
function _.real(s)
local p = C.realpath(s, buf)
if p == nil then return errors.get(ffi.errno()) end
return nil, ffi.string(p)
end
function _.pop(s, n)
local rng = ranges[0]
rng.off = 0
rng.len = #s
C.sp_path_pop(s, rng, n or 1)
return s:sub(rng.off+1, rng.off+rng.len)
end
function _.split(s, n)
local a, b = ranges[0], ranges[1]
C.sp_path_split(a, b, s, #s, n or 1)
return
s:sub(a.off+1, a.off+a.len),
s:sub(b.off+1, b.off+b.len)
end
function _.splitext(s)
local a, b = ranges[0], ranges[1]
C.sp_path_splitext(a, b, s, #s)
return
s:sub(a.off+1, a.off+a.len),
s:sub(b.off+1, b.off+b.len)
end
function _.join(s, ...)
local n = #s
C.memcpy(buf, s, n)
buf[n] = 0
for i, p in ipairs({...}) do
n = C.sp_path_join(buf, buflen, buf, n, p, #p, 0)
if n < 0 then return "" end
buf[n] = 0
end
n = C.sp_path_clean(buf, n, 0)
return ffi.string(buf, n)
end
function _.clean(s)
C.memcpy(buf, s, #s)
buf[#s] = 0
local n = C.sp_path_clean(buf, #s, 0)
return ffi.string(buf, n)
end
function _.match(s, m)
return C.sp_path_match(s, m)
end
function _.dirname(s, n)
local a, b = ranges[0], ranges[1]
C.sp_path_split(a, b, s, #s, n or 1)
return s:sub(a.off+1, a.off+a.len)
end
function _.basename(s, n)
local a, b = ranges[0], ranges[1]
C.sp_path_split(a, b, s, #s, n or 1)
return s:sub(b.off+1, b.off+b.len)
end
function _.procname()
if not procname then
local n = C.sp_path_proc(buf, buflen)
if n < 0 then
procname_err = errors.get(n)
else
procname_val = ffi.string(buf, n)
end
procname = true
end
return procname_err, procname_val
end
function _.envname(s)
local n = C.sp_path_env(s, buf, buflen)
if n < 0 then return errors.get(n) end
return nil, ffi.string(buf, n)
end
function _.exists(name)
local ffi = require("ffi")
local C = ffi.C
local rc = C.access(name, C.F_OK)
return rc ~= -1
end
function _.walk(path, depth)
local err, dir = _.Dir(path, depth)
if err then return function() end end
return function()
local rc = C.sp_dir_next(dir)
if rc > 0 then return dir end
dir:close()
end
end
--
-- Path
local Path_mt = {}
Path_mt.__index = Path_mt
function Path_mt:__tostring()
return self._path
end
function Path_mt:__concat(s)
return tostring(self) .. tostring(s)
end
function Path_mt:exists()
return _.exists(self._path)
end
function Path_mt:remove(recurse)
local __, __, rc = os.execute(("rm %s%s 2>/dev/null"):format(
recurse and "-r " or "", self))
return rc == 0
end
function Path_mt:stat()
local err, stat = _.stat(self._path)
return stat
end
function Path_mt:is_dir()
local err, stat = _.stat(self._path)
if not stat then return end
return stat:is_dir()
end
function Path_mt:walk(depth)
return _.walk(self._path, depth)
end
function Path_mt:cwd()
local err, cwd = _.cwd(self._path)
if err then err:exit() end
return cwd
end
function Path_mt:write(s)
local fh = io.open(self._path, "w")
fh:write(s)
fh:close()
end
function Path_mt:__call(rel)
return setmetatable({_path=_.join(self._path, rel)}, Path_mt)
end
local Path_constructor = {}
Path_constructor.__index = Path_constructor
function Path_constructor:__call(path)
return setmetatable({_path=_.abs(path)}, Path_mt)
end
function Path_constructor:tmpdir()
local path = os.tmpname()
os.remove(path)
os.execute("mkdir " .. path)
return setmetatable({_path=_.abs(path)}, Path_mt)
end
_.Path = setmetatable({}, Path_constructor)
--
-- Dir
local Dir_mt = {}
Dir_mt.__index = Dir_mt
function Dir_mt:__tostring()
return "levee._.Dir: " .. self:pathname()
end
-- don't descend into the directory on the subsequent `next`
function Dir_mt:skip()
C.sp_dir_skip(self)
end
-- follow into a symlink when calling the subsequent `next`
function Dir_mt:follow()
C.sp_dir_follow(self)
end
function Dir_mt:type()
return C.sp_dir_type(self)
end
function Dir_mt:is_reg()
return C.sp_dir_type(self) == C.SP_PATH_REG
end
function Dir_mt:is_dir()
return C.sp_dir_type(self) == C.SP_PATH_DIR
end
function Dir_mt:stat()
local src = C.sp_dir_stat(self)
if src == nil then return errors.get(-ffi.errno()) end
local dst = ffi.new("SpStat")
C.memcpy(dst, src, ffi.sizeof(dst))
return nil, dst
end
function Dir_mt:pathname()
return ffi.string(self.path, self.pathlen)
end
function Dir_mt:dirname()
return ffi.string(self.path, self.dirlen)
end
function Dir_mt:basename()
return ffi.string(self.path + self.dirlen + 1, self.pathlen - self.dirlen - 1)
end
function Dir_mt:close()
C.sp_dir_close(self)
end
function Dir_mt:using_fd(fd)
for i=0,self.cur-1 do
if fd == C.dirfd(self.stack[i]) then
return true
end
end
return false
end
local Dir_ct = ffi.metatype("SpDir", Dir_mt)
function _.Dir(path, depth)
local dir = Dir_ct()
local rc = C.sp_dir_open(dir, path, depth or 255)
if rc < 0 then return errors.get(rc) end
return nil, ffi.gc(dir, C.sp_dir_close)
end
return _
|
local function lol(gfx)
local items = newItemList()
items:add(newEItem('goal',37,15,gfx))
items:add(newEItem('score',33,15,gfx))
items:add(newEItem('score',31,21,gfx))
items:add(newEItem('score',27,21,gfx))
items:add(newEItem('score',41,20,gfx))
items:add(newEItem('button',36,20,gfx))
items:add(newEItem('buttblock',40,21,gfx))
items:add(newEItem('buttblock',41,21,gfx))
items:add(newEItem('buttblock',42,21,gfx))
items:add(newEItem('buttblock',24,15,gfx))
items:add(newEItem('buttblock',25,15,gfx))
items:add(newEItem('buttblock',26,15,gfx))
items:add(newEItem('buttblock',36,16,gfx))
items:add(newEItem('buttblock',37,16,gfx))
items:add(newEItem('buttblock',38,16,gfx))
items:add(newEItem('buttblock',30,22,gfx))
items:add(newEItem('buttblock',31,22,gfx))
items:add(newEItem('buttblock',32,22,gfx))
items:add(newEItem('spawn',21,13,gfx))
local decs = {}
local nmys = {}
nmys[1] = {6, 21, 17}
nmys[2] = {6, 22, 17}
nmys[3] = {6, 23, 17}
nmys[4] = {6, 24, 17}
nmys[5] = {6, 25, 17}
nmys[6] = {6, 26, 17}
nmys[7] = {6, 27, 24}
nmys[8] = {6, 28, 24}
nmys[9] = {6, 29, 24}
nmys[10] = {6, 30, 24}
nmys[11] = {6, 31, 24}
nmys[12] = {6, 32, 24}
nmys[13] = {6, 37, 23}
nmys[14] = {6, 38, 23}
nmys[15] = {6, 39, 23}
nmys[16] = {6, 41, 23}
nmys[17] = {6, 40, 23}
nmys[18] = {6, 42, 23}
nmys[19] = {6, 38, 18}
nmys[20] = {6, 37, 18}
nmys[21] = {6, 36, 18}
nmys[22] = {6, 35, 18}
nmys[23] = {6, 34, 18}
nmys[24] = {6, 33, 18}
local lvl = {}
lvl[1] = {}
lvl[2] = {}
lvl[3] = {}
lvl[4] = {}
lvl[5] = {}
lvl[6] = {}
lvl[7] = {}
lvl[8] = {}
lvl[9] = {}
lvl[10] = {}
lvl[11] = {}
lvl[12] = {}
lvl[13] = {}
lvl[14] = {}
lvl[15] = {}
lvl[16] = {}
lvl[17] = {}
lvl[18] = {}
lvl[19] = {}
lvl[19][14] = 1
lvl[19][15] = 4
lvl[19][16] = 7
lvl[20] = {}
lvl[20][14] = 2
lvl[20][15] = 5
lvl[20][16] = 8
lvl[21] = {}
lvl[21][14] = 2
lvl[21][15] = 5
lvl[21][16] = 8
lvl[22] = {}
lvl[22][12] = 1
lvl[22][13] = 4
lvl[22][14] = 42
lvl[22][15] = 5
lvl[22][16] = 8
lvl[23] = {}
lvl[23][12] = 2
lvl[23][13] = 5
lvl[23][14] = 5
lvl[23][15] = 5
lvl[23][16] = 8
lvl[24] = {}
lvl[24][12] = 3
lvl[24][13] = 6
lvl[24][14] = 6
lvl[24][15] = 6
lvl[24][16] = 9
lvl[25] = {}
lvl[25][21] = 1
lvl[25][22] = 4
lvl[25][23] = 7
lvl[26] = {}
lvl[26][21] = 2
lvl[26][22] = 5
lvl[26][23] = 8
lvl[27] = {}
lvl[27][21] = 2
lvl[27][22] = 5
lvl[27][23] = 8
lvl[28] = {}
lvl[28][18] = 1
lvl[28][19] = 14
lvl[28][20] = 4
lvl[28][21] = 42
lvl[28][22] = 5
lvl[28][23] = 8
lvl[29] = {}
lvl[29][18] = 2
lvl[29][19] = 5
lvl[29][20] = 5
lvl[29][21] = 5
lvl[29][22] = 5
lvl[29][23] = 8
lvl[30] = {}
lvl[30][18] = 3
lvl[30][19] = 36
lvl[30][20] = 6
lvl[30][21] = 6
lvl[30][22] = 6
lvl[30][23] = 9
lvl[31] = {}
lvl[31][15] = 1
lvl[31][16] = 4
lvl[31][17] = 7
lvl[32] = {}
lvl[32][15] = 2
lvl[32][16] = 5
lvl[32][17] = 8
lvl[33] = {}
lvl[33][15] = 2
lvl[33][16] = 5
lvl[33][17] = 8
lvl[34] = {}
lvl[34][12] = 1
lvl[34][13] = 14
lvl[34][14] = 4
lvl[34][15] = 42
lvl[34][16] = 5
lvl[34][17] = 8
lvl[35] = {}
lvl[35][12] = 2
lvl[35][13] = 5
lvl[35][14] = 5
lvl[35][15] = 5
lvl[35][16] = 5
lvl[35][17] = 8
lvl[35][20] = 1
lvl[35][21] = 4
lvl[35][22] = 7
lvl[36] = {}
lvl[36][12] = 3
lvl[36][13] = 36
lvl[36][14] = 6
lvl[36][15] = 6
lvl[36][16] = 6
lvl[36][17] = 9
lvl[36][20] = 2
lvl[36][21] = 5
lvl[36][22] = 8
lvl[37] = {}
lvl[37][20] = 2
lvl[37][21] = 5
lvl[37][22] = 8
lvl[38] = {}
lvl[38][18] = 1
lvl[38][19] = 4
lvl[38][20] = 42
lvl[38][21] = 5
lvl[38][22] = 8
lvl[39] = {}
lvl[39][18] = 2
lvl[39][19] = 5
lvl[39][20] = 5
lvl[39][21] = 5
lvl[39][22] = 8
lvl[40] = {}
lvl[40][18] = 3
lvl[40][19] = 6
lvl[40][20] = 6
lvl[40][21] = 6
lvl[40][22] = 9
lvl[41] = {}
lvl[42] = {}
lvl[43] = {}
lvl[44] = {}
lvl[45] = {}
lvl[46] = {}
lvl[47] = {}
lvl[48] = {}
lvl[49] = {}
lvl[50] = {}
lvl[51] = {}
lvl[52] = {}
lvl[53] = {}
lvl[54] = {}
lvl[55] = {}
lvl[56] = {}
lvl[57] = {}
lvl[58] = {}
lvl[59] = {}
lvl[60] = {}
lvl[61] = {}
lvl[62] = {}
lvl[63] = {}
lvl[64] = {}
lvl[65] = {}
lvl[66] = {}
lvl[67] = {}
lvl[68] = {}
lvl[69] = {}
lvl[70] = {}
lvl[71] = {}
lvl[72] = {}
lvl[73] = {}
lvl[74] = {}
lvl[75] = {}
lvl[76] = {}
lvl[77] = {}
lvl[78] = {}
lvl[79] = {}
lvl[80] = {}
lvl[81] = {}
lvl[82] = {}
lvl[83] = {}
lvl[84] = {}
lvl[85] = {}
lvl[86] = {}
lvl[87] = {}
lvl[88] = {}
lvl[89] = {}
lvl[90] = {}
lvl[91] = {}
lvl[92] = {}
lvl[93] = {}
lvl[94] = {}
lvl[95] = {}
lvl[96] = {}
lvl[97] = {}
lvl[98] = {}
lvl[99] = {}
lvl[100] = {}
return lvl,items,decs,nmys
end
return lol |
object_static_particle_pt_smoke_small_optimized = object_static_particle_shared_pt_smoke_small_optimized:new {
}
ObjectTemplates:addTemplate(object_static_particle_pt_smoke_small_optimized, "object/static/particle/pt_smoke_small_optimized.iff")
|
local util = require "navigator.util"
local log = util.log
local lsphelper = require "navigator.lspwrapper"
local gui = require "navigator.gui"
local lsp = require "navigator.lspwrapper"
local trace = require"navigator.util".trace
-- local log = util.log
-- local partial = util.partial
-- local cwd = vim.fn.getcwd(0)
-- local lsphelper = require "navigator.lspwrapper"
local locations_to_items = lsphelper.locations_to_items
-- vim.api.nvim_set_option("navtator_options", {width = 90, height = 60, location = require "navigator.location".center})
-- local options = vim.g.navtator_options or {width = 60, height = 40, location = location.center}
local function ref_hdlr(err, api, locations, num, bufnr)
local opts = {}
-- log("arg1", arg1)
-- log(api)
trace(locations)
-- log("num", num)
-- log("bfnr", bufnr)
if err ~= nil then
print('ref callback error, lsp may not ready', err)
return
end
if type(locations) ~= 'table' then
log(api)
log(locations)
log("num", num)
log("bfnr", bufnr)
error(locations)
end
if locations == nil or vim.tbl_isempty(locations) then
print "References not found"
return
end
local items, width = locations_to_items(locations)
local ft = vim.api.nvim_buf_get_option(bufnr, "ft")
local wwidth = vim.api.nvim_get_option("columns")
width = math.min(width + 30, 120, math.floor(wwidth * 0.8))
gui.new_list_view({
items = items,
ft = ft,
width = width,
api = "Reference",
enable_preview_edit = true
})
end
local async_reference_request = function()
local ref_params = vim.lsp.util.make_position_params()
ref_params.context = {includeDeclaration = true}
lsp.call_async("textDocument/references", ref_params, ref_hdlr) -- return asyncresult, canceller
-- lsp.call_async("textDocument/definition", ref_params, ref_hdlr) -- return asyncresult, canceller
end
return {reference_handler = ref_hdlr, show_reference = async_reference_request}
|
local tip = 0
function onCreate()
--Iterate over all notes
for i = 0, getProperty('unspawnNotes.length')-1 do
if getPropertyFromGroup('unspawnNotes', i, 'noteType') == 'Ink Note' then --Check if the note on the chart is a Bullet Note
setPropertyFromGroup('unspawnNotes', i, 'texture', 'INK_assets'); --Change texture
setPropertyFromGroup('unspawnNotes', i, 'noteSplashDisabled', false);
setPropertyFromGroup('unspawnNotes', i, 'noteSplashTexture', 'inkSplashes');
if getPropertyFromGroup('unspawnNotes', i, 'mustPress') == true then --Lets Opponent's instakill notes get ignored
setPropertyFromGroup('unspawnNotes', i, 'ignoreNote', true); --Miss has no penalties
else
setPropertyFromGroup('unspawnNotes', i, 'ignoreNote', true);
end
end
end
end
function noteMiss(id, direction, noteType, isSustainNote)
end
function goodNoteHit(id, direction, noteType, isSustainNote)
if noteType == 'Ink Note' then
tip = tip + 1
if tip == 1 then
makeLuaSprite('exe', 'Damage01', 0, 0)
setScrollFactor('exe', 0, 0);
scaleObject('exe', 1, 1);
setLuaSpriteCamera('exe', 'hud');
addLuaSprite('exe', true);
playSound('inked', 0.5);
runTimer('ink', 5)
elseif tip == 2 then
makeLuaSprite('exe', 'Damage02', 0, 0)
setScrollFactor('exe', 0, 0);
scaleObject('exe', 1, 1);
setLuaSpriteCamera('exe', 'hud');
addLuaSprite('exe', true);
playSound('inked', 0.5);
runTimer('ink', 5)
elseif tip == 3 then
makeLuaSprite('exe', 'Damage03', 0, 0)
setScrollFactor('exe', 0, 0);
scaleObject('exe', 1, 1);
setLuaSpriteCamera('exe', 'hud');
addLuaSprite('exe', true);
playSound('inked', 0.5);
runTimer('ink', 5)
elseif tip == 4 then
makeLuaSprite('exe', 'Damage04', 0, 0)
setScrollFactor('exe', 0, 0);
scaleObject('exe', 1, 1);
setLuaSpriteCamera('exe', 'hud');
addLuaSprite('exe', true);
playSound('inked', 0.5);
runTimer('ink', 5)
else
--nada
playSound('inked', 0.5);
runTimer('ink', 5)
end
--setProperty('health', -1);
end
end
function onTimerCompleted(tag, loops, loopsLeft)
-- A loop from a timer you called has been completed, value "tag" is it's tag
-- loops = how many loops it will have done when it ends completely
-- loopsLeft = how many are remaining
if loopsLeft >= 1 then
tip = 0
setProperty('health', getProperty('health')-0.001);
end
if tag == 'ink' then
tip = 0;
end
end |
local rspamd_util = require "rspamd_util"
local lua_util = require "lua_util"
local opts = {}
local argparse = require "argparse"
local parser = argparse()
:name "rspamadm confighelp"
:description "Shows help for the specified configuration options"
:help_description_margin(32)
parser:flag "--no-ips"
:description "No IPs stats"
parser:flag "--no-keys"
:description "No keys stats"
parser:flag "--short"
:description "Short output mode"
parser:flag "-n --number"
:description "Disable numbers humanization"
parser:option "-s --sort"
:description "Sort order"
:convert {
matched = "matched",
errors = "errors",
ip = "ip"
}
local function add_data(target, src)
for k,v in pairs(src) do
if k ~= 'ips' then
if target[k] then
target[k] = target[k] + v
else
target[k] = v
end
else
if not target['ips'] then target['ips'] = {} end
-- Iterate over IPs
for ip,st in pairs(v) do
if not target['ips'][ip] then target['ips'][ip] = {} end
add_data(target['ips'][ip], st)
end
end
end
end
local function print_num(num)
if opts['n'] or opts['number'] then
return tostring(num)
else
return rspamd_util.humanize_number(num)
end
end
local function print_stat(st, tabs)
if st['checked'] then
print(string.format('%sChecked: %s', tabs, print_num(st['checked'])))
end
if st['matched'] then
print(string.format('%sMatched: %s', tabs, print_num(st['matched'])))
end
if st['errors'] then
print(string.format('%sErrors: %s', tabs, print_num(st['errors'])))
end
if st['added'] then
print(string.format('%sAdded: %s', tabs, print_num(st['added'])))
end
if st['deleted'] then
print(string.format('%sDeleted: %s', tabs, print_num(st['deleted'])))
end
end
-- Sort by checked
local function sort_ips(tbl, sort_opts)
local res = {}
for k,v in pairs(tbl) do
table.insert(res, {ip = k, data = v})
end
local function sort_order(elt)
local key = 'checked'
local _res = 0
if sort_opts['sort'] then
if sort_opts['sort'] == 'matched' then
key = 'matched'
elseif sort_opts['sort'] == 'errors' then
key = 'errors'
elseif sort_opts['sort'] == 'ip' then
return elt['ip']
end
end
if elt['data'][key] then
_res = elt['data'][key]
end
return _res
end
table.sort(res, function(a, b)
return sort_order(a) > sort_order(b)
end)
return res
end
local function add_result(dst, src, k)
if type(src) == 'table' then
if type(dst) == 'number' then
-- Convert dst to table
dst = {dst}
elseif type(dst) == 'nil' then
dst = {}
end
for i,v in ipairs(src) do
if dst[i] and k ~= 'fuzzy_stored' then
dst[i] = dst[i] + v
else
dst[i] = v
end
end
else
if type(dst) == 'table' then
if k ~= 'fuzzy_stored' then
dst[1] = dst[1] + src
else
dst[1] = src
end
else
if dst and k ~= 'fuzzy_stored' then
dst = dst + src
else
dst = src
end
end
end
return dst
end
local function print_result(r)
local function num_to_epoch(num)
if num == 1 then
return 'v0.6'
elseif num == 2 then
return 'v0.8'
elseif num == 3 then
return 'v0.9'
elseif num == 4 then
return 'v1.0+'
elseif num == 5 then
return 'v1.7+'
end
return '???'
end
if type(r) == 'table' then
local res = {}
for i,num in ipairs(r) do
res[i] = string.format('(%s: %s)', num_to_epoch(i), print_num(num))
end
return table.concat(res, ', ')
end
return print_num(r)
end
return function(args, res)
local res_ips = {}
local res_databases = {}
local wrk = res['workers']
opts = parser:parse(args)
if wrk then
for _,pr in pairs(wrk) do
-- processes cycle
if pr['data'] then
local id = pr['id']
if id then
local res_db = res_databases[id]
if not res_db then
res_db = {
keys = {}
}
res_databases[id] = res_db
end
-- General stats
for k,v in pairs(pr['data']) do
if k ~= 'keys' and k ~= 'errors_ips' then
res_db[k] = add_result(res_db[k], v, k)
elseif k == 'errors_ips' then
-- Errors ips
if not res_db['errors_ips'] then
res_db['errors_ips'] = {}
end
for ip,nerrors in pairs(v) do
if not res_db['errors_ips'][ip] then
res_db['errors_ips'][ip] = nerrors
else
res_db['errors_ips'][ip] = nerrors + res_db['errors_ips'][ip]
end
end
end
end
if pr['data']['keys'] then
local res_keys = res_db['keys']
if not res_keys then
res_keys = {}
res_db['keys'] = res_keys
end
-- Go through keys in input
for k,elts in pairs(pr['data']['keys']) do
-- keys cycle
if not res_keys[k] then
res_keys[k] = {}
end
add_data(res_keys[k], elts)
if elts['ips'] then
for ip,v in pairs(elts['ips']) do
if not res_ips[ip] then
res_ips[ip] = {}
end
add_data(res_ips[ip], v)
end
end
end
end
end
end
end
end
-- General stats
for db,st in pairs(res_databases) do
print(string.format('Statistics for storage %s', db))
for k,v in pairs(st) do
if k ~= 'keys' and k ~= 'errors_ips' then
print(string.format('%s: %s', k, print_result(v)))
end
end
print('')
local res_keys = st['keys']
if res_keys and not opts['no-keys'] and not opts['short'] then
print('Keys statistics:')
for k,_st in pairs(res_keys) do
print(string.format('Key id: %s', k))
print_stat(_st, '\t')
if _st['ips'] and not opts['no-ips'] then
print('')
print('\tIPs stat:')
local sorted_ips = sort_ips(_st['ips'], opts)
for _,v in ipairs(sorted_ips) do
print(string.format('\t%s', v['ip']))
print_stat(v['data'], '\t\t')
print('')
end
end
print('')
end
end
if st['errors_ips'] and not opts['no-ips'] and not opts['short'] then
print('')
print('Errors IPs statistics:')
local ip_stat = st['errors_ips']
local ips = lua_util.keys(ip_stat)
-- Reverse sort by number of errors
table.sort(ips, function(a, b)
return ip_stat[a] > ip_stat[b]
end)
for _, ip in ipairs(ips) do
print(string.format('%s: %s', ip, print_result(ip_stat[ip])))
end
print('')
end
end
if not opts['no-ips'] and not opts['short'] then
print('')
print('IPs statistics:')
local sorted_ips = sort_ips(res_ips, opts)
for _, v in ipairs(sorted_ips) do
print(string.format('%s', v['ip']))
print_stat(v['data'], '\t')
print('')
end
end
end
|
------------------------------------------------------------------
--
-- Author: Alexey Melnichuk <[email protected]>
--
-- Copyright (C) 2016 Alexey Melnichuk <[email protected]>
--
-- Licensed according to the included 'LICENSE' document
--
-- This file is part of lua-EventEmitter library.
--
------------------------------------------------------------------
local function split_first(str, sep, plain)
local e, e2 = string.find(str, sep, nil, plain)
if e then
return string.sub(str, 1, e - 1), string.sub(str, e2 + 1)
end
return str
end
local function slit_first_self_test()
local s1, s2 = split_first("ab|cd", "|", true)
assert(s1 == "ab")
assert(s2 == "cd")
local s1, s2 = split_first("|abcd", "|", true)
assert(s1 == "")
assert(s2 == "abcd")
local s1, s2 = split_first("abcd|", "|", true)
assert(s1 == "abcd")
assert(s2 == "")
local s1, s2 = split_first("abcd", "|", true)
assert(s1 == "abcd")
assert(s2 == nil)
end
local function class(base)
local t = base and setmetatable({}, base) or {}
t.__index = t
t.__class = t
t.__base = base
function t.new(...)
local o = setmetatable({}, t)
if o.__init then
if t == ... then -- we call as Class:new()
return o:__init(select(2, ...))
else -- we call as Class.new()
return o:__init(...)
end
end
return o
end
return t
end
local function class_self_test()
local A = class()
function A:__init(a, b)
assert(a == 1)
assert(b == 2)
end
A:new(1, 2)
A.new(1, 2)
local B = class(A)
function B:__init(a,b,c)
assert(self.__base == A)
A.__init(B, a, b)
assert(c == 3)
end
B:new(1, 2, 3)
B.new(1, 2, 3)
end
local function clone(t, o)
o = o or {}
for k, v in pairs(t) do
o[k] = v
end
return o
end
local function self_test()
slit_first_self_test()
class_self_test()
end
return {
clone = clone;
class = class;
split_first = split_first;
self_test = self_test;
}
|
local RGBColor = {}
RGBColor.__index = RGBColor
function RGBColor.new(r, g, b, a)
local self = setmetatable({}, RGBColor)
self.r = r
self.g = g
self.b = b
self.a = a
return self
end
function RGBColor:toTable()
return {self.r, self.g, self.b, self.a}
end
return RGBColor |
local ttt = 0
local current = 0
local color = function (val)
love.graphics.setColor(255,255,255,255*((7-val)/7)*0.7)
end
local circles = {
function (s)
love.graphics.circle("fill",18*s/2,8*s/2,2*s)
love.graphics.circle("line",18*s/2,8*s/2,2*s)
end,
function (s)
love.graphics.circle("fill",33*s/2,15*s/2,2*s)
love.graphics.circle("line",33*s/2,15*s/2,2*s)
end,
function (s)
love.graphics.circle("fill",36*s/2,31*s/2,2*s)
love.graphics.circle("line",36*s/2,31*s/2,2*s)
end,
function (s)
love.graphics.circle("fill",26*s/2,43*s/2,2*s)
love.graphics.circle("line",26*s/2,43*s/2,2*s)
end,
function (s)
love.graphics.circle("fill",10*s/2,43*s/2,2*s)
love.graphics.circle("line",10*s/2,43*s/2,2*s)
end,
function (s)
love.graphics.circle("fill",0*s/2,31*s/2,2*s)
love.graphics.circle("line",0*s/2,31*s/2,2*s)
end,
function (s)
love.graphics.circle("fill",4*s/2,15*s/2,2*s)
love.graphics.circle("line",4*s/2,15*s/2,2*s)
end,
}
local f = {
update = function (dt)
ttt = ttt + dt
current = math.floor(ttt * 7)
end,
draw = function (x,y)
love.graphics.push()
love.graphics.translate(x,y)
for i = 1, 7 do
color((current + i) % 7)
circles[i](1.4)
end
love.graphics.pop()
end
}
return f |
describe("matrix", function()
local cml = require("luacml")
--local eps = 1e-5
local testfmt = "(%s)"
local classes_2x2 =
{
matrix22 = cml.matrix22,
matrix22_r = cml.matrix22_r,
matrix22_c = cml.matrix22_c,
}
local classes_3x3 =
{
matrix33 = cml.matrix33,
matrix33_r = cml.matrix33_r,
matrix33_c = cml.matrix33_c,
}
local classes_4x4 =
{
matrix44 = cml.matrix44,
matrix44_r = cml.matrix44_r,
matrix44_c = cml.matrix44_c,
}
describe("constructor", function()
for name, ctor in pairs(classes_2x2) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
describe("default", function()
it(testname, function()
local input, expected = ctor(), {1,0,0,1}
assert.same(expected, input:totable())
end)
end)
describe("with 4 floats", function()
it(testname, function()
local input, expected = ctor(1,2,3,4), {1,2,3,4}
assert.same(expected, input:totable())
end)
end)
describe("with array of 4 floats", function()
it(testname, function()
local input, expected = ctor{1,2,3,4}, {1,2,3,4}
assert.same(expected, input:totable())
end)
end)
describe("with matrix", function()
it(testname, function()
local A = ctor(1,2,3,4)
local input, expected = ctor(A), {1,2,3,4}
assert.same(expected, input:totable())
end)
end)
end
for name, ctor in pairs(classes_3x3) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
describe("default", function()
it(testname, function()
local input, expected = ctor(), {1,0,0,0,1,0,0,0,1}
assert.same(expected, input:totable())
end)
end)
describe("with 9 floats", function()
it(testname, function()
local input, expected = ctor(1,2,3,4,5,6,7,8,9), {1,2,3,4,5,6,7,8,9}
assert.same(expected, input:totable())
end)
end)
describe("with array of 9 floats", function()
it(testname, function()
local input, expected = ctor{1,2,3,4,5,6,7,8,9}, {1,2,3,4,5,6,7,8,9}
assert.same(expected, input:totable())
end)
end)
describe("with matrix", function()
it(testname, function()
local A = ctor(1,2,3,4,5,6,7,8,9)
local input, expected = ctor(A), {1,2,3,4,5,6,7,8,9}
assert.same(expected, input:totable())
end)
end)
end
for name, ctor in pairs(classes_4x4) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
describe("default", function()
it(testname, function()
local input, expected = ctor(), {1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1}
assert.same(expected, input:totable())
end)
end)
describe("with 16 floats", function()
it(testname, function()
local input, expected = ctor(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16), {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
assert.same(expected, input:totable())
end)
end)
describe("with array of 16 floats", function()
it(testname, function()
local input, expected = ctor{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}, {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
assert.same(expected, input:totable())
end)
end)
describe("with matrix", function()
it(testname, function()
local A = ctor(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)
local input, expected = ctor(A), {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
assert.same(expected, input:totable())
end)
end)
end
-- Test 3x2 matrix
do
local name = "matrix32_r"
local ctor = cml.matrix32_r
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
describe("default", function()
it(testname, function()
local input = ctor()
local expected =
{
1,0,
0,1,
0,0,
}
assert.same(expected, input:totable())
end)
end)
describe("with 6 floats", function()
it(testname, function()
local input = ctor(11,12,21,22,31,32)
local expected =
{
11,12,
21,22,
31,32,
}
assert.same(expected, input:totable())
end)
end)
describe("with array of 6 floats", function()
it(testname, function()
local input = ctor{11,12,21,22,31,32}
local expected =
{
11,12,
21,22,
31,32,
}
assert.same(expected, input:totable())
end)
end)
describe("with matrix", function()
it(testname, function()
local A = ctor(11,12,21,22,31,32)
local input = ctor(A)
local expected =
{
11,12,
21,22,
31,32,
}
assert.same(expected, input:totable())
end)
end)
end
-- Test 2x3 matrix
do
local name = "matrix23_c"
local ctor = cml.matrix23_c
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
describe("default", function()
it(testname, function()
local input = ctor()
local expected =
{
1,0,0,
0,1,0,
}
assert.same(expected, input:totable())
end)
end)
describe("with 6 floats", function()
it(testname, function()
local input = ctor(11,12,13,21,22,23)
local expected =
{
11,12,13,
21,22,23,
}
assert.same(expected, input:totable())
end)
end)
describe("with array of 6 floats", function()
it(testname, function()
local input = ctor{11,12,13,21,22,23}
local expected =
{
11,12,13,
21,22,23,
}
assert.same(expected, input:totable())
end)
end)
describe("with matrix", function()
it(testname, function()
local A = ctor(11,12,13,21,22,23)
local input = ctor(A)
local expected =
{
11,12,13,
21,22,23,
}
assert.same(expected, input:totable())
end)
end)
end
-- Test 4x3 matrix
do
local name = "matrix43_r"
local ctor = cml.matrix43_r
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
describe("default", function()
it(testname, function()
local input = ctor()
local expected =
{
1,0,0,
0,1,0,
0,0,1,
0,0,0,
}
assert.same(expected, input:totable())
end)
end)
describe("with 6 floats", function()
it(testname, function()
local input = ctor(11,12,13,21,22,23,31,32,33,41,42,43)
local expected =
{
11,12,13,
21,22,23,
31,32,33,
41,42,43,
}
assert.same(expected, input:totable())
end)
end)
describe("with array of 6 floats", function()
it(testname, function()
local input = ctor{11,12,13,21,22,23,31,32,33,41,42,43}
local expected =
{
11,12,13,
21,22,23,
31,32,33,
41,42,43,
}
assert.same(expected, input:totable())
end)
end)
describe("with matrix", function()
it(testname, function()
local A = ctor(11,12,13,21,22,23,31,32,33,41,42,43)
local input = ctor(A)
local expected =
{
11,12,13,
21,22,23,
31,32,33,
41,42,43,
}
assert.same(expected, input:totable())
end)
end)
end
-- Test 3x4 matrix
do
local name = "matrix34_c"
local ctor = cml.matrix34_c
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
describe("default", function()
it(testname, function()
local input = ctor()
local expected =
{
1,0,0,0,
0,1,0,0,
0,0,1,0,
}
assert.same(expected, input:totable())
end)
end)
describe("with 6 floats", function()
it(testname, function()
local input = ctor(11,12,13,14,21,22,23,24,31,32,33,34)
local expected =
{
11,12,13,14,
21,22,23,24,
31,32,33,34,
}
assert.same(expected, input:totable())
end)
end)
describe("with array of 6 floats", function()
it(testname, function()
local input = ctor{11,12,13,14,21,22,23,24,31,32,33,34}
local expected =
{
11,12,13,14,
21,22,23,24,
31,32,33,34,
}
assert.same(expected, input:totable())
end)
end)
describe("with matrix", function()
it(testname, function()
local A = ctor(11,12,13,14,21,22,23,24,31,32,33,34)
local input = ctor(A)
local expected =
{
11,12,13,14,
21,22,23,24,
31,32,33,34,
}
assert.same(expected, input:totable())
end)
end)
end
end)
describe("index", function()
-- Test 2x2 matrices
for name, ctor in pairs(classes_2x2) do
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4}
local input = {11,22,33,44}
local expected =
{
[1] = 11, [2] = 22,
[3] = 33, [4] = 44
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
describe("with string", function()
local keys = {"m11","m12","m21","m22"}
local input = {11,22,33,44}
local expected =
{
m11 = 11, m12 = 22,
m21 = 33, m22 = 44
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
end
-- Test 3x3 matrices
for name, ctor in pairs(classes_3x3) do
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4,5,6,7,8,9}
local input = {11,22,33,44,55,66,77,88,99}
local expected =
{
[1] = 11, [2] = 22, [3] = 33,
[4] = 44, [5] = 55, [6] = 66,
[7] = 77, [8] = 88, [9] = 99,
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
describe("with string", function()
local keys = {"m11","m12","m13","m21","m22","m23","m31","m32","m33"}
local input = {11,22,33,44,55,66,77,88,99}
local expected =
{
m11 = 11, m12 = 22, m13 = 33,
m21 = 44, m22 = 55, m23 = 66,
m31 = 77, m32 = 88, m33 = 99,
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
end
-- Test 4x4 matrices
for name, ctor in pairs(classes_4x4) do
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
local input = {11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44}
local expected =
{
11, 12, 13, 14,
21, 22, 23, 24,
31, 32, 33, 34,
41, 42, 43, 44,
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
describe("with string", function()
local keys =
{
"m11","m12","m13","m14",
"m21","m22","m23","m24",
"m31","m32","m33","m34",
"m41","m42","m43","m44",
}
local input = {11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44}
local expected =
{
m11 = 11, m12 = 12, m13 = 13, m14 = 14,
m21 = 21, m22 = 22, m23 = 23, m24 = 24,
m31 = 31, m32 = 32, m33 = 33, m34 = 34,
m41 = 41, m42 = 42, m43 = 43, m44 = 44,
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
end
-- Test 3x2 matrices
do
local name, ctor = "matrix32_r", cml.matrix32_r
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4,5,6}
local input = {11,12,21,22,31,32}
local expected =
{
11, 12,
21, 22,
31, 32,
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
describe("with string", function()
local keys =
{
"m11","m12",
"m21","m22",
"m31","m32",
}
local input = {11,12,21,22,31,32}
local expected =
{
m11 = 11, m12 = 12,
m21 = 21, m22 = 22,
m31 = 31, m32 = 32,
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
end
-- Test 2x3 matrices
do
local name, ctor = "matrix23_c", cml.matrix23_c
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4,5,6}
local input = {11,12,13,21,22,23}
local expected =
{
11, 12, 13,
21, 22, 23,
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
describe("with string", function()
local keys =
{
"m11","m12","m13",
"m21","m22","m23",
}
local input = {11,12,13,21,22,23}
local expected =
{
m11 = 11, m12 = 12, m13 = 13,
m21 = 21, m22 = 22, m23 = 23,
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
end
-- Test 4x3 matrices
do
local name, ctor = "matrix43_r", cml.matrix43_r
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4,5,6,7,8,9,10,11,12}
local input = {11,12,13,21,22,23,31,32,33,41,42,43}
local expected =
{
11, 12, 13,
21, 22, 23,
31, 32, 33,
41, 42, 43,
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
describe("with string", function()
local keys =
{
"m11","m12","m13",
"m21","m22","m23",
"m31","m32","m33",
"m41","m42","m43",
}
local input = {11,12,13,21,22,23,31,32,33,41,42,43}
local expected =
{
m11 = 11, m12 = 12, m13 = 13,
m21 = 21, m22 = 22, m23 = 23,
m31 = 31, m32 = 32, m33 = 33,
m41 = 41, m42 = 42, m43 = 43,
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
end
-- Test 3x4 matrices
do
local name, ctor = "matrix34_c", cml.matrix34_c
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4,5,6,7,8,9,10,11,12}
local input = {11,12,13,14,21,22,23,24,31,32,33,34}
local expected =
{
11,12,13,14,
21,22,23,24,
31,32,33,34,
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
describe("with string", function()
local keys =
{
"m11","m12","m13","m14",
"m21","m22","m23","m24",
"m31","m32","m33","m34",
}
local input = {11,12,13,14,21,22,23,24,31,32,33,34}
local expected =
{
m11 = 11, m12 = 12, m13 = 13, m14 = 14,
m21 = 21, m22 = 22, m23 = 23, m24 = 24,
m31 = 31, m32 = 32, m33 = 33, m34 = 34,
}
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
assert.same(expected[k], obj[k])
end)
end)
end
end)
end
end)
describe("newindex", function()
-- Test 2x2 matrices
for name, ctor in pairs(classes_2x2) do
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4,}
local input = {11,12,21,22,}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
describe("with string", function()
local keys = {"m11","m12","m21","m22"}
local input = {11,12,21,22,}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
end
-- Test 3x3 matrices
for name, ctor in pairs(classes_3x3) do
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4,5,6,7,8,9,}
local input = {11,12,13,21,22,23,31,32,33}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
describe("with string", function()
local keys = {"m11","m12","m13","m21","m22","m23","m31","m32","m33"}
local input = {11,12,13,21,22,23,31,32,33}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
end
-- Test 4x4 matrices
for name, ctor in pairs(classes_4x4) do
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
local input = {11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
describe("with string", function()
local keys =
{
"m11","m12","m13","m14",
"m21","m22","m23","m24",
"m31","m32","m33","m34",
"m41","m42","m43","m44",
}
local input = {11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
end
-- Test 3x2 matrices
do
local name, ctor = "matrix32_r", cml.matrix32_r
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4,5,6}
local input = {11,12,21,22,31,32}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
describe("with string", function()
local keys =
{
"m11","m12",
"m21","m22",
"m31","m32",
}
local input = {11,12,21,22,31,32}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
end
-- Test 2x3 matrices
do
local name, ctor = "matrix23_c", cml.matrix23_c
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4,5,6}
local input = {11,12,13,21,22,23}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
describe("with string", function()
local keys =
{
"m11","m12","m13",
"m21","m22","m23",
}
local input = {11,12,13,21,22,23}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
end
-- Test 4x3 matrices
do
local name, ctor = "matrix43_r", cml.matrix43_r
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4,5,6,7,8,9,10,11,12}
local input = {11,12,13,21,22,23,31,32,33,41,42,43}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
describe("with string", function()
local keys =
{
"m11","m12","m13",
"m21","m22","m23",
"m31","m32","m33",
"m41","m42","m43",
}
local input = {11,12,13,21,22,23,31,32,33,41,42,43}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
end
-- Test 3x4 matrices
do
local name, ctor = "matrix34_c", cml.matrix34_c
local testname = testfmt:format(name)
describe("with integer", function()
local keys = {1,2,3,4,5,6,7,8,9,10,11,12}
local input = {11,12,13,14,21,22,23,24,31,32,33,34}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
describe("with string", function()
local keys =
{
"m11","m12","m13","m14",
"m21","m22","m23","m24",
"m31","m32","m33","m34",
}
local input = {11,12,13,14,21,22,23,24,31,32,33,34}
local expected = 100
for _, k in ipairs(keys) do
describe(tostring(k), function()
it(testname, function()
local obj = ctor(input)
assert.is_userdata(obj)
obj[k] = 100
assert.same(expected, obj[k])
end)
end)
end
end)
end
end)
describe("set", function()
-- Test 2x2 matrices
for name, ctor in pairs(classes_2x2) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,21,22}
local expected = {1,2,3,4}
describe("by table", function()
it(testname, function()
local obj = ctor(input)
obj:set({1,2,3,4})
assert.same(expected, obj:totable())
end)
end)
describe("by numbers", function()
it(testname, function()
local obj = ctor(input)
obj:set(1,2,3,4)
assert.same(expected, obj:totable())
end)
end)
describe("by matrix", function()
it(testname, function()
local obj = ctor(input)
obj:set(ctor(1,2,3,4))
assert.same(expected, obj:totable())
end)
end)
end
-- Test 3x3 matrices
for name, ctor in pairs(classes_3x3) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,13,21,22,23,31,32,33}
local expected = {1,2,3,4,5,6,7,8,9}
describe("by table", function()
it(testname, function()
local obj = ctor(input)
obj:set({1,2,3,4,5,6,7,8,9})
assert.same(expected, obj:totable())
end)
end)
describe("by numbers", function()
it(testname, function()
local obj = ctor(input)
obj:set(1,2,3,4,5,6,7,8,9)
assert.same(expected, obj:totable())
end)
end)
describe("by matrix", function()
it(testname, function()
local obj = ctor(input)
obj:set(ctor(1,2,3,4,5,6,7,8,9))
assert.same(expected, obj:totable())
end)
end)
end
-- Test 4x4 matrices
for name, ctor in pairs(classes_4x4) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44}
local expected = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
describe("by table", function()
it(testname, function()
local obj = ctor(input)
obj:set({1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16})
assert.same(expected, obj:totable())
end)
end)
describe("by numbers", function()
it(testname, function()
local obj = ctor(input)
obj:set(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)
assert.same(expected, obj:totable())
end)
end)
describe("by matrix", function()
it(testname, function()
local obj = ctor(input)
obj:set(ctor(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16))
assert.same(expected, obj:totable())
end)
end)
end
-- Test 2x3 matrices
do
local name, ctor = "matrix23_c", cml.matrix23_c
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,13,21,22,23}
local expected = {1,2,3,4,5,6}
describe("by table", function()
it(testname, function()
local obj = ctor(input)
obj:set({1,2,3,4,5,6})
assert.same(expected, obj:totable())
end)
end)
describe("by numbers", function()
it(testname, function()
local obj = ctor(input)
obj:set(1,2,3,4,5,6)
assert.same(expected, obj:totable())
end)
end)
describe("by matrix", function()
it(testname, function()
local obj = ctor(input)
obj:set(ctor(1,2,3,4,5,6))
assert.same(expected, obj:totable())
end)
end)
end
-- Test 3x2 matrices
do
local name, ctor = "matrix32_r", cml.matrix32_r
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,21,22,31,32}
local expected = {1,2,3,4,5,6}
describe("by table", function()
it(testname, function()
local obj = ctor(input)
obj:set({1,2,3,4,5,6})
assert.same(expected, obj:totable())
end)
end)
describe("by numbers", function()
it(testname, function()
local obj = ctor(input)
obj:set(1,2,3,4,5,6)
assert.same(expected, obj:totable())
end)
end)
describe("by matrix", function()
it(testname, function()
local obj = ctor(input)
obj:set(ctor(1,2,3,4,5,6))
assert.same(expected, obj:totable())
end)
end)
end
-- Test 3x4 matrices
do
local name, ctor = "matrix34_c", cml.matrix34_c
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,13,14,21,22,23,24,31,32,33,34}
local expected = {1,2,3,4,5,6,7,8,9,10,11,12}
describe("by table", function()
it(testname, function()
local obj = ctor(input)
obj:set({1,2,3,4,5,6,7,8,9,10,11,12})
assert.same(expected, obj:totable())
end)
end)
describe("by numbers", function()
it(testname, function()
local obj = ctor(input)
obj:set(1,2,3,4,5,6,7,8,9,10,11,12)
assert.same(expected, obj:totable())
end)
end)
describe("by matrix", function()
it(testname, function()
local obj = ctor(input)
obj:set(ctor(1,2,3,4,5,6,7,8,9,10,11,12))
assert.same(expected, obj:totable())
end)
end)
end
-- Test 4x3 matrices
do
local name, ctor = "matrix43_r", cml.matrix43_r
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,13,21,22,23,31,32,33,41,42,43}
local expected = {1,2,3,4,5,6,7,8,9,10,11,12}
describe("by table", function()
it(testname, function()
local obj = ctor(input)
obj:set({1,2,3,4,5,6,7,8,9,10,11,12})
assert.same(expected, obj:totable())
end)
end)
describe("by numbers", function()
it(testname, function()
local obj = ctor(input)
obj:set(1,2,3,4,5,6,7,8,9,10,11,12)
assert.same(expected, obj:totable())
end)
end)
describe("by matrix", function()
it(testname, function()
local obj = ctor(input)
obj:set(ctor(1,2,3,4,5,6,7,8,9,10,11,12))
assert.same(expected, obj:totable())
end)
end)
end
end)
describe("zero", function()
-- Test 2x2 matrices
for name, ctor in pairs(classes_2x2) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,21,22}
local expected = {0,0,0,0}
it(testname, function()
local obj = ctor(input)
obj:zero()
assert.same(expected, obj:totable())
end)
end
-- Test 3x3 matrices
for name, ctor in pairs(classes_3x3) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,13,21,22,23,31,32,33}
local expected = {0,0,0,0,0,0,0,0,0}
it(testname, function()
local obj = ctor(input)
obj:zero()
assert.same(expected, obj:totable())
end)
end
-- Test 4x4 matrices
for name, ctor in pairs(classes_4x4) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44}
local expected = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
it(testname, function()
local obj = ctor(input)
obj:zero()
assert.same(expected, obj:totable())
end)
end
-- Test 2x3 matrices
do
local name, ctor = "matrix23_c", cml.matrix23_c
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,13,21,22,23}
local expected = {0,0,0,0,0,0}
it(testname, function()
local obj = ctor(input)
obj:zero()
assert.same(expected, obj:totable())
end)
end
-- Test 3x2 matrices
do
local name, ctor = "matrix32_r", cml.matrix32_r
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,21,22,31,32}
local expected = {0,0,0,0,0,0}
it(testname, function()
local obj = ctor(input)
obj:zero()
assert.same(expected, obj:totable())
end)
end
-- Test 3x4 matrices
do
local name, ctor = "matrix34_c", cml.matrix34_c
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,13,14,21,22,23,24,31,32,33,34}
local expected = {0,0,0,0,0,0,0,0,0,0,0,0}
it(testname, function()
local obj = ctor(input)
obj:zero()
assert.same(expected, obj:totable())
end)
end
-- Test 4x3 matrices
do
local name, ctor = "matrix43_r", cml.matrix43_r
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input = {11,12,13,21,22,23,31,32,33,41,42,43}
local expected = {0,0,0,0,0,0,0,0,0,0,0,0}
it(testname, function()
local obj = ctor(input)
obj:zero()
assert.same(expected, obj:totable())
end)
end
end)
describe("identity", function()
-- Test 2x2 matrices
for name, ctor in pairs(classes_2x2) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input =
{
11,12,
21,22,
}
local expected =
{
1,0,
0,1,
}
it(testname, function()
local obj = ctor(input)
obj:identity()
assert.same(expected, obj:totable())
end)
end
-- Test 3x3 matrices
for name, ctor in pairs(classes_3x3) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input =
{
11,12,13,
21,22,23,
31,32,33,
}
local expected =
{
1,0,0,
0,1,0,
0,0,1,
}
it(testname, function()
local obj = ctor(input)
obj:identity()
assert.same(expected, obj:totable())
end)
end
-- Test 4x4 matrices
for name, ctor in pairs(classes_4x4) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input =
{
11,12,13,14,
21,22,23,24,
31,32,33,34,
41,42,43,44,
}
local expected =
{
1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1,
}
it(testname, function()
local obj = ctor(input)
obj:identity()
assert.same(expected, obj:totable())
end)
end
-- Test 2x3 matrices
do
local name, ctor = "matrix23_c", cml.matrix23_c
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input =
{
11,12,13,
21,22,23,
}
local expected =
{
1,0,0,
0,1,0,
}
it(testname, function()
local obj = ctor(input)
obj:identity()
assert.same(expected, obj:totable())
end)
end
-- Test 3x2 matrices
do
local name, ctor = "matrix32_r", cml.matrix32_r
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input =
{
11,12,
21,22,
31,32,
}
local expected =
{
1,0,
0,1,
0,0,
}
it(testname, function()
local obj = ctor(input)
obj:identity()
assert.same(expected, obj:totable())
end)
end
-- Test 3x4 matrices
do
local name, ctor = "matrix34_c", cml.matrix34_c
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input =
{
11,12,13,14,
21,22,23,24,
31,32,33,34,
}
local expected =
{
1,0,0,0,
0,1,0,0,
0,0,1,0,
}
it(testname, function()
local obj = ctor(input)
obj:identity()
assert.same(expected, obj:totable())
end)
end
-- Test 4x3 matrices
do
local name, ctor = "matrix43_r", cml.matrix43_r
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input =
{
11,12,13,
21,22,23,
31,32,33,
41,42,43,
}
local expected =
{
1,0,0,
0,1,0,
0,0,1,
0,0,0,
}
it(testname, function()
local obj = ctor(input)
obj:identity()
assert.same(expected, obj:totable())
end)
end
end)
describe("transpose", function()
-- Test 2x2 matrices
for name, ctor in pairs(classes_2x2) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input =
{
11,12,
21,22,
}
local expected =
{
11,21,
12,22,
}
it(testname, function()
local obj = ctor(input)
obj:transpose()
assert.same(expected, obj:totable())
end)
end
-- Test 3x3 matrices
for name, ctor in pairs(classes_3x3) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input =
{
11,12,13,
21,22,23,
31,32,33,
}
local expected =
{
11,21,31,
12,22,32,
13,23,33,
}
it(testname, function()
local obj = ctor(input)
obj:transpose()
assert.same(expected, obj:totable())
end)
end
-- Test 4x4 matrices
for name, ctor in pairs(classes_4x4) do
local testname = testfmt:format(name)
assert.is_table(ctor)
assert.is_function((getmetatable(ctor) or {}).__call)
local input =
{
11,12,13,14,
21,22,23,24,
31,32,33,34,
41,42,43,44,
}
local expected =
{
11,21,31,41,
12,22,32,42,
13,23,33,43,
14,24,34,44,
}
it(testname, function()
local obj = ctor(input)
obj:transpose()
assert.same(expected, obj:totable())
end)
end
end)
end)
|
--MODIFIERS
---------------------------------------------------------------------------
hyper = {"cmd", "alt", "ctrl"}
hypershift = {"cmd", "alt", "ctrl", "shift"}
-- windows management
-- hypershift + E,S,F,C
-- Custom Application Launcher Key
leader = hs.hotkey.modal.new(hypershift, "a")
function leader:entered() hs.alert'Entered mode' end
function leader:exited() hs.alert'Exited mode' end
leader:bind('', 'escape', function() leader:exit() end)
leader:bind("", "G", "Chrome", function()
hs.application.launchOrFocus("Google Chrome")
leader:exit()
end)
leader:bind("", "C", "Chrome", function()
hs.application.launchOrFocus("Google Chrome")
leader:exit()
end)
leader:bind("", "S", "Spotify", function()
hs.application.launchOrFocus("Spotify")
leader:exit()
end)
leader:bind("", "V", "Docker Desktop", function()
hs.application.launchOrFocus("Visual Studio Code")
leader:exit()
end)
leader:bind("", "D", "Docker Desktop", function()
hs.application.launchOrFocus("Docker Desktop")
leader:exit()
end)
leader:bind("", "I", "iTerm", function()
hs.application.launchOrFocus("Iterm")
leader:exit()
end)
leader:bind("", "T", "iTerm", function()
hs.application.launchOrFocus("Iterm")
leader:exit()
end)
leader:bind("", "N", "Notes", function()
hs.application.launchOrFocus("Notes")
leader:exit()
end)
leader:bind("", "V", "Notes", function()
hs.application.launchOrFocus("Notes")
leader:exit()
end)
leader:bind("", "R", "Reminders", function()
hs.application.launchOrFocus("Reminders")
leader:exit()
end)
-- right click and inspect
-- quickly open inspect - dev tools
hs.hotkey.bind(hypershift, "t", function()
keys = ""
output = "inspect"
local ptMouse = hs.mouse.getAbsolutePosition()
local types = hs.eventtap.event.types
hs.eventtap.event.newMouseEvent(types.rightMouseDown, ptMouse, keys):post()
hs.eventtap.event.newMouseEvent(types.rightMouseUp, ptMouse, keys):post()
hs.timer.doAfter(.1, function()
hs.eventtap.keyStroke({},"i")
hs.eventtap.keyStroke({},"n")
hs.eventtap.keyStroke({},"return")
end)
end)
scrollAmount = 1
-- Scroll down 1 pixel
hs.hotkey.bind(hypershift, "j", function()
print(scrollAmount)
hs.eventtap.event.newScrollEvent({0,(-1 * scrollAmount)},{},'pixel'):post()
end)
-- Scroll up 1 pixel
hs.hotkey.bind(hypershift, "k", function()
print(scrollAmount)
hs.eventtap.event.newScrollEvent({0,(1 * scrollAmount)},{},'pixel'):post()
end)
-- Scroll amount +1
-- add one pixel from the scrollAmount
hs.hotkey.bind(hyper, "j", function()
scrollAmount = scrollAmount - 1
print(scrollAmount)
end)
-- Scroll amount -1
-- remove one pixel from the scrollAmount
hs.hotkey.bind(hyper, "k", function()
scrollAmount = scrollAmount + 1
print(scrollAmount)
end)
-- HOTKEYS
---------------------------------------------------------------------------
-- apply window layout for current monitor configuration
hs.hotkey.bind(hypershift, "y", function()
applyWindowLayout()
end)
-- SCREENS
---------------------------------------------------------------------------
--
-- push window one screen left
hs.hotkey.bind(hypershift, "x", function()
moveWindowToScreen("left")
end)
-- push window one screen right
hs.hotkey.bind(hypershift, "v", function()
moveWindowToScreen("right")
end)
-- CURSOR
---------------------------------------------------------------------------
-- push window one screen right
hs.hotkey.bind(hypershift, "d", function()
moveCursorToScreen()
end)
-- SPACES
---------------------------------------------------------------------------
-- create new space
hs.hotkey.bind(hypershift, "i", function()
hs.alert.show("creating new space")
spaces.createSpace()
end)
-- -- focus one space left
-- hs.hotkey.bind(hypershift, "w", function()
-- moveOneSpace("1")
-- end)
-- -- focus one space right
-- hs.hotkey.bind(hypershift, "r", function()
-- moveOneSpace("2")
-- end)
-- move focused widow one space left
hs.hotkey.bind(hypershift, "h", function()
moveWindowOneSpace("1")
end)
-- move focused widow one space right
hs.hotkey.bind(hypershift, "l", function()
moveWindowOneSpace("2")
end)
-- -- activate mission control
-- hs.hotkey.bind(hypershift, "b", function()
-- activateMissionControl()
-- end)
-- Other
---------------------------------------------------------------------------
-- -- display window hints
-- hs.hotkey.bind(hypershift, "a", function()
-- hs.hints.windowHints()
-- end)
-- draw crosshair
hs.hotkey.bind(hypershift, "z", function()
updateCrosshairs()
end)
-- remove crosshair
hs.hotkey.bind(hyper, "z", function()
clearCrosshairs()
end)
-- chrome fuzzy search tabs
hs.hotkey.bind(hyper,"space", function()
tabSwitcher()
end)
-- xScope bindings
hs.hotkey.bind(hypershift, "4", function()
hs.execute('hammerscope 21', true)
end)
hs.hotkey.bind(hypershift, "7", function()
hs.execute('hammerscope', true)
end) |
local HttpService = import("./HttpService")
describe("instances.HttpService", function()
it("should instantiate", function()
local instance = HttpService:new()
assert.not_nil(instance)
end)
it("should json encode properly", function()
local instance = HttpService:new()
assert.equal(instance:JSONEncode({ 1, true }), "[1,true]")
end)
it("should json decode properly", function()
local instance = HttpService:new()
assert.are.same(instance:JSONDecode("[1,true]"), { 1, true })
end)
end) |
local obj = {}
obj.name = "carnation"
obj.version = "0.1"
obj.author = "Luna <[email protected]>"
obj.license = "Unlicense"
obj.config_url = nil
obj.screen_dimensions = nil
local function calcAngles(pos)
local screenWidth = obj.screen_dimensions[1]
local screenHeight = obj.screen_dimensions[2]
local inX = pos.x / screenWidth
local inY = pos.y / screenHeight
local absX = inX
local absY = 1.0 - inY
local mX = absX * 60.0
local mY = absY * 60.0
local resX = mX - 30.0
local resY = mY - 30.0
return {x=resX, y=resY}
end
function obj:_send_msg(msg)
hs.socket.udp.new():send(msg, obj.config_url, 6699)
end
function obj:start()
hs.alert.show('hello')
if not obj.config_url then
hs.alert.show('fucked up: no url')
return
end
if not obj.screen_dimensions then
hs.alert.show('fucked up: no screen')
return
end
-- keep watcher as global to prevent it from being gc'd away
obj.__watcher = hs.eventtap.new({hs.eventtap.event.types.mouseMoved}, function (event)
local pos = hs.mouse.absolutePosition()
local angle = calcAngles(pos)
local string = "!angles "..angle.x.." "..angle.y
obj:_send_msg(string)
end):start()
-- animation example, do cmd+ctrl+z to do ParamAngleZ animation
obj.__funny_state = {toggle = false, num = 0, op = 'plus'}
obj.__funny_timer = hs.timer.doEvery(0.006, function()
if not obj.__funny_state.toggle then
return
end
-- to animate angleZ, we have both the number we're currenly on
-- and the operation we're supossed to do on each tick
-- the animation also happens beyond the bounds of angleZ, so there's a little
-- bit of a holding time between each angleZ edge (-30 and 30), that makes
-- the animation feel more fluid and not mechanical
-- values beyond 30 here determine the holding bounds of each edge
if obj.__funny_state.num >= 40 and obj.__funny_state.op == 'plus' then
obj.__funny_state.op = 'minus'
elseif obj.__funny_state.num <= -40 and obj.__funny_state.op == 'minus' then
obj.__funny_state.op = 'plus'
end
-- '1' here is the amount angleZ will change per tick
if obj.__funny_state.op == 'plus' then
obj.__funny_state.num = obj.__funny_state.num + 1
else
obj.__funny_state.num = obj.__funny_state.num - 1
end
if obj.__funny_state.num >= -30 and obj.__funny_state.num <= 30 then
obj:_send_msg("set ParamAngleZ "..obj.__funny_state.num)
end
end)
hs.hotkey.bind({"cmd", "ctrl"}, "z", function()
obj.__funny_state.toggle = not obj.__funny_state.toggle
if obj.__funny_state.toggle then
hs.alert.show('doing funnies')
else
hs.alert.show('stopping funnies')
obj:_send_msg("set ParamAngleZ 0")
end
end)
end
return obj
|
--[[-----------------------------------------------------------------------------
* Infected Wars, an open source Garry's Mod game-mode.
*
* Infected Wars is the work of multiple authors,
* a full list can be found in CONTRIBUTORS.md.
* For more information, visit https://github.com/JarnoVgr/InfectedWars
*
* Infected Wars is free software: you can redistribute it and/or modify
* it under the terms of the MIT License.
*
* A full copy of the MIT License can be found in LICENSE.txt.
-----------------------------------------------------------------------------]]
SWEP.Base = "iw_base_dummy"
SWEP.HoldType = "pistol"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.ViewModel = "models/weapons/v_toolgun.mdl"
SWEP.WorldModel = "models/weapons/w_toolgun.mdl"
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.Sound = Sound("items/medshot4.wav")
SWEP.Primary.Recoil = 1
SWEP.Primary.Unrecoil = 1
SWEP.Primary.Damage = 1
SWEP.Primary.NumShots = 1
SWEP.Primary.ClipSize = -1
SWEP.Primary.Delay = 0.25
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "none"
SWEP.Primary.Cone = 0
SWEP.Primary.ConeMoving = 0
SWEP.Primary.ConeCrouching = 0
if CLIENT then
/*SWEP.PlayerModelBones = {}
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Upperarm"] = "Bip01_L_Upperarm"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Forearm"] = "Bip01_L_Forearm"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Hand"] = "Bip01_L_Hand"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger4"] = "Bip01_L_Finger4"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger41"] = "Bip01_L_Finger41"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger42"] = "Bip01_L_Finger42"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger3"] = "Bip01_L_Finger3"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger31"] = "Bip01_L_Finger31"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger32"] = "Bip01_L_Finger32"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger2"] = "Bip01_L_Finger2"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger21"] = "Bip01_L_Finger21"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger22"] = "Bip01_L_Finger22"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger1"] = "Bip01_L_Finger1"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger11"] = "Bip01_L_Finger11"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger12"] = "Bip01_L_Finger12"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger0"] = "Bip01_L_Finger0"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger01"] = "Bip01_L_Finger01"
SWEP.PlayerModelBones["ValveBiped.Bip01_L_Finger02"] = "Bip01_L_Finger02"
//SWEP.PlayerModelBones["ValveBiped.Bip01_R_Forearm"] = "Arm"
//SWEP.PlayerModelBones["ValveBiped.Bip01_R_Hand"] = "Hand"
SWEP.OverrideAngle = {}
//SWEP.OverrideAngle["Arm"] = Angle(-90,0,90)
SWEP.OverrideAngle["Bip01_L_Forearm"] = Angle(0,0,0)
SWEP.OverrideAngle["Bip01_L_Hand"] = Angle(0,0,0)
SWEP.OverrideTranslation = {}
SWEP.OverrideTranslation["Bip01_L_Forearm"] = Vector(3,0,0)
*/
end
--SWEP.IronSightsPos = Vector(-4.5, -9.6, 3.1)
--SWEP.IronSightsAng = Vector(1.1, 0.6, -3.3)
SWEP.Drain = 2
SWEP.HealDistance = 80
local restoretimer = 0
function SWEP:OnInitialize()
self.HealTime = 0
self.HealSound = CreateSound(self.Weapon,"items/medcharge4.wav")
self.EmptySound = Sound("items/medshotno1.wav")
end
function SWEP:FindPlayer( dis )
local trace = self.Owner:TraceLine(dis)
if trace.HitNonWorld then
local target = trace.Entity
if target:IsPlayer() then
return target
end
end
return
end
function SWEP:HealStart()
self.Primary.Automatic = true
self.Weapon:EmitSound(self.Primary.Sound)
if SERVER then
self.HealSound:Play()
end
end
function SWEP:HealStop()
self.HealTime = CurTime()+self.Primary.Delay*2 -- prohibits heal button smashing
self.Primary.Automatic = false
self.Weapon:EmitSound(self.EmptySound)
if SERVER then
self.HealSound:Stop()
end
end
SWEP.target = nil
SWEP.healstack = 0
function SWEP:PrimaryAttack()
local ply = self.Owner
if (ply.EquipedSuit == "suppliesboosterpack") then
self.Weapon:SetNextPrimaryFire(CurTime() + (self.Primary.Delay*0.666))
else
self.Weapon:SetNextPrimaryFire(CurTime() + self.Primary.Delay)
end
if not self:CanPrimaryAttack() then return end
self.target = self.target or self:FindPlayer(self.HealDistance)
if self.target ~= nil and self.target:IsValid() and self.target:Team() == self.Owner:Team()
and self.target:GetPos():Distance(self.Owner:GetShootPos()) < self.HealDistance*1.5 and self.target:Alive() then
if self.target:Health() < self.target:GetMaximumHealth() then -- and if it doesn't have full hp
local prevhp = self.target:Health()
self.target:SetHealth(math.min(self.target:Health()+2,self.target:GetMaximumHealth()))
local drain = self.Drain
if ply:HasBought("efficientexchange") then
drain = drain * 0.7
end
ply:SetSuitPower(ply:SuitPower()-drain)
if CLIENT then -- Emit some nice looking particles...
local pos = self.target:GetPos()+Vector(0,0,50)
self:EmitHealParticles( pos )
end
if SERVER then
self:UpdateHealScore( self.target, prevhp )
end
elseif self.Primary.Automatic then
if CLIENT then
self.Owner:PrintMessage(HUD_PRINTTALK,"Target player is full")
end
self:HealStop()
end
else
self.target = nil
self:HealStop()
end
if CLIENT then
//self.Weapon:SetNetworkedFloat("LastShootTime", CurTime())
end
end
local fired = false
function SWEP:OnThink()
local ply = self.Owner
if ply:KeyPressed(IN_ATTACK) and self:CanPrimaryAttack() then
local target = self:FindPlayer(self.HealDistance)
if target ~= nil then
if target:Health() < target:GetMaximumHealth() then
self:HealStart()
elseif self.Primary.Automatic then
if CLIENT then
self.Owner:PrintMessage(HUD_PRINTTALK,"Target player is full")
end
self:HealStop()
end
else
self:HealStop()
end
end
if ply:KeyReleased(IN_ATTACK) and SERVER then
self.Primary.Automatic = true
self.HealSound:Stop()
end
end
function SWEP:CanPrimaryAttack()
local ply = self.Owner
if ply:SuitPower() <= self.Drain and self.HealTime < CurTime() then
self.Weapon:EmitSound(self.EmptySound)
return false
end
return true
end
function SWEP:SecondaryAttack()
end
|
local g = vim.g
local api = vim.api
local option = api.nvim_buf_get_option
local function buf_only()
local del_non_modifiable = g.bufonly_delete_non_modifiable or false
local cur = api.nvim_get_current_buf()
local deleted, modified = 0, 0
for _, n in ipairs(api.nvim_list_bufs()) do
-- If the iter buffer is modified one, then don't do anything
if option(n, 'modified') then
modified = modified + 1
-- iter is not equal to current buffer
-- iter is modifiable or del_non_modifiable == true
-- `modifiable` check is needed as it will prevent closing file tree ie. NERD_tree
elseif n ~= cur and (option(n, 'modifiable') or del_non_modifiable) then
api.nvim_buf_delete(n, {})
deleted = deleted + 1
end
end
print('BufOnly: '..deleted..' deleted buffer(s), '..modified..' modified buffer(s)')
end
return {
buf_only = buf_only
}
|
oldInteract = interact
function interact(args)
oldInteract(args)
local interactAction = config.getParameter("interactAction")
if interactAction then
local data = config.getParameter("interactData", {})
if type(data) == "string" then
data = root.assetJson(data)
end
return { interactAction, data }
end
end |
class "UIPalette" {
extends "UIObject",
static {
shader = love.graphics.newShader([[
vec4 effect( vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords ){
return ( color + vec4( (1-texture_coords.x) * (1-vec3(color)),1) ) * vec4( (1-texture_coords.y) * vec3(1,1,1), 1 );
}
]])
},
new = function (self, x,y, width,height, colorHueAlias,colorSaturationAlias,colorValueAlias)
UIObject.instanceMethods.new(self, x,y, width,height)
self.colorHueAlias = colorHueAlias
self.colorSaturation = colorSaturationAlias
self.colorValue = colorValueAlias
self.canvas = nil
end,
update = function (self, dt, transform)
self.transform = transform
if self.isClicking then
self.colorSaturation = (
( love.mouse.getX() - select(1, self.transform:transformPoint(self.x,0)) )
/ ( select(1, self.transform:transformPoint(self.width,0)) - select(1, self.transform:transformPoint(0,0)) )
)
self.colorSaturation = math.clamp(self.colorSaturation, 0,1)
self.colorValue = 1 - (
( love.mouse.getY() - select(2, self.transform:transformPoint(0,self.y)))
/ ( select(2, self.transform:transformPoint(0,self.height)) - select(2, self.transform:transformPoint(0,0)) )
)
self.colorValue = math.clamp(self.colorValue, 0,1)
end
end,
draw = function (self)
-- Draw the box
local boxX, boxY = self.transform:transformPoint(self.x, self.y)
local boxX2, boxY2 = self.transform:transformPoint(self.x+self.width, self.y+self.height)
local boxWidth = boxX2 - boxX
local boxHeight = boxY2 - boxY
if not self.canvas then
self.canvas = love.graphics.newCanvas(boxWidth, boxHeight)
end
local previousShader = love.graphics.getShader()
love.graphics.setShader(UIPalette.shader)
love.graphics.setColor(vivid.HSVtoRGB(self.colorHueAlias,1,1,1))
love.graphics.draw(self.canvas, boxX,boxY)
love.graphics.setShader(previousShader)
-- Draw the cursor
local cursorX = boxX + self.colorSaturation * boxWidth
local cursorY = boxY + (1-self.colorValue) * boxHeight
love.graphics.setLineWidth(boxHeight/100)
love.graphics.setColor(0,0,0,1)
love.graphics.circle("line", cursorX,cursorY,boxHeight/60)
love.graphics.setColor(0,0,0,1)
love.graphics.circle("line", cursorX,cursorY,boxHeight/40)
love.graphics.setColor(1,1,1,1)
love.graphics.circle("line", cursorX,cursorY,boxHeight/50)
end,
mouseMoved = function (self, x, y, dx, dy, istouch)
UIObject.instanceMethods.mouseMoved(self, x, y, dx, dy, istouch)
end,
mousePressed = function (self, mouseX, mouseY, button, istouch, presses)
if self:getIsInside() and button == 1 then
self.isClicking = true
end
end,
mouseReleased = function (self, mouseX, mouseY, istouch, presses)
self.isClicking = false
end,
resize = function (self, w, h)
self.canvas = nil
end,
} |
local assert = assert
local ipairs = ipairs
--[[-------------------------------------------------------------------------
math.sum
---------------------------------------------------------------------------]]
function math.sum( ... )
local sum = 0
for num, int in ipairs({...}) do
sum = sum + int
end
return sum
end
--[[-------------------------------------------------------------------------
math.striving_for
---------------------------------------------------------------------------]]
function math.striving_for( value, valueTo, delay )
return value + (valueTo - value) / delay
end
--[[-------------------------------------------------------------------------
Bezier Curve
---------------------------------------------------------------------------]]
function math.bezier_linear( vec1, vec2, t )
return vec1 + ( vec2 - vec1 ) * ( t / 100 )
end
do
local linear = math.bezier_linear
function math.bezier( vec1, vec2, vec3, t )
return linear( linear( vec1, vec2, t ), linear( vec2, vec3, t ), t )
end
end
--[[-------------------------------------------------------------------------
math.average - For number arguments
---------------------------------------------------------------------------]]
do
local select = select
function math.average( ... )
local amount = select( "#", ... )
assert(amount > 1, "At least two numbers are required!")
local total = 0
for i = 1, amount do
total = total + select(i, ...)
end
return total / amount
end
end
--[[-------------------------------------------------------------------------
math.average - For lists
---------------------------------------------------------------------------]]
function math.averageList( tbl )
local sum = 0
for num, number in ipairs( tbl ) do
sum = sum + number
end
return sum / #tbl
end
--[[-------------------------------------------------------------------------
math.average - For tables
---------------------------------------------------------------------------]]
function math.averageTable( tbl )
local sum, counter = 0
for num, number in pairs( tbl ) do
counter = counter + 1
sum = sum + number
end
return sum / counter
end
--[[-------------------------------------------------------------------------
Angle improvements
---------------------------------------------------------------------------]]
local math_floor = math.floor
local math_abs = math.abs
do
local ANGLE = FindMetaTable("Angle")
function ANGLE:Floor()
self[1] = math_floor(self[1])
self[2] = math_floor(self[2])
self[3] = math_floor(self[3])
return self
end
function ANGLE:abs()
self[1] = math_abs(self[1])
self[2] = math_abs(self[2])
self[3] = math_abs(self[3])
return self
end
end
--[[-------------------------------------------------------------------------
Vector improvements
---------------------------------------------------------------------------]]
local math_max = math.max
do
local VECTOR = FindMetaTable("Vector")
function VECTOR:Middle( vec )
if isvector( vec ) then
return ( self + vec ) / 2
else
return ( self[1] + self[2] + self[3] ) / 3
end
end
function VECTOR:Diameter( maxs )
return math_max( maxs[1] + math_abs( self[1] ), maxs[2] + math_abs( self[2] ), maxs[3] + math_abs( self[3] ) )
end
function VECTOR:InBox( vec1, vec2 )
return self[1] >= vec1[1] and self[1] <= vec2[1] and self[2] >= vec1[2] and self[2] <= vec2[2] and self[3] >= vec1[3] and self[3] <= vec2[3]
end
do
local math_Round = math.Round
function VECTOR:Round( dec )
return Vector( math_Round( self[1], dec or 0 ), math_Round( self[2], dec or 0 ), math_Round( self[3], dec or 0 ) )
end
end
function VECTOR:Floor()
self[1] = math_floor( self[1] )
self[2] = math_floor( self[2] )
self[3] = math_floor( self[3] )
return self
end
function VECTOR:Abs()
self[1] = math_abs( self[1] )
self[2] = math_abs( self[2] )
self[3] = math_abs( self[3] )
return self
end
end
--[[-------------------------------------------------------------------------
ents.FindInBoxRotated( global pos, ang, mins, maxs )
---------------------------------------------------------------------------]]
do
local ents_FindInSphere = ents.FindInSphere
local WorldToLocal = WorldToLocal
local table_insert = table.insert
function ents.FindInBoxRotated(pos, ang, mins, maxs)
local result = {}
for num, ent in ipairs( ents_FindInSphere( pos, mins:Diameter( maxs ) ) ) do
if WorldToLocal( ent:GetPos(), ent:GetAngles(), pos, ang ):WithinAABox( mins, maxs ) then
table_insert( result, ent )
end
end
return result
end
end |
--- PlayerStates class.
-- @classmod invokation.combos.PlayerStates
local class = require("pl.class")
local M = class()
--- Constructor.
function M:_init()
self.states = {}
end
--- Index metamethod.
-- @tparam CDOTAPlayer player Player
-- @treturn table Player state
function M:__index(player)
local id = player:GetPlayerID()
if self.states[id] == nil then
self.states[id] = {}
end
return self.states[id]
end
return M
|
if Lib_GPI == nil then
Lib_GPI = {}
end
if Lib_GPI.ToolBox==nil or Lib_GPI.ToolBox_Ver<101 then
Lib_GPI.ToolBox_Ver=101
function Lib_GPI.ToolBox()
local lib={}
function lib.Merge(t1,t2)
for i,v in pairs(t2) do
t1[i]=v
end
return t1
end
function lib.iMerge(t1,t2)
for i,v in ipairs(t2) do
if tContains(t1,v)==false then
tinsert(t1,v)
end
end
return t1
end
function lib.Combine(t,sep)
if type(t)~="table" then return "" end
if sep == nil then sep =" " end
local ret=""
for i,v in ipairs(t) do
ret=ret..sep..v
end
return string.sub(ret,2)
end
function lib.Split(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={}
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
if tContains(t, str)==false then
table.insert(t, str)
end
end
return t
end
lib._DataBrocker=false
function lib:AddDataBrocker(icon,onClick,onTooltipShow,tocName,text)
if LibStub ~= nil and self._DataBrocker ~= true then
local Launcher = LibStub('LibDataBroker-1.1')
if Launcher ~= nil then
self._DataBrocker=true
Launcher:NewDataObject(tocName, {
type = "launcher",
icon = icon,
OnClick = onClick,
OnTooltipShow = onTooltipShow,
tocname = tocName,
label = text,
})
end
end
end
return lib
end
end |
MissionHint = {
type = "Sound",
Properties = {
Hints = {
sndHint1="",
sndHint2="",
sndHint3="",
sndHint4="",
sndHint5="",
sndHint6="",
sndHint7="",
sndHint8="",
sndHint9="",
sndHint10="",
},
sndSkipAcknowledge="",
iAllowedToSkip=3,
fVolume=1.0,
bLoop=0, -- Loop sound.
bOnce=0,
bEnabled=1,
bScaleDownVolumes=1,
},
skipped=0,
HintCount = 1,
SkipCount = 0,
Editor={
Model="Editor/Objects/Sound.cgf",
},
}
function MissionHint:OnSave(props)
props.HintCount = self.HintCount
end
function MissionHint:OnLoad(props)
self:OnReset();
self.HintCount = props.HintCount
end
----------------------------------------------------------------------------------------
function MissionHint:OnPropertyChange()
if (self.soundName ~= self.Properties.sndSource or self.soundid == nil or self.Properties.bLoop ~= self.loop) then
--if (self.started==1) then
-- self:Play();
--end
self.loop = self.Properties.bLoop;
end
self:OnReset();
if (self.soundid ~= nil) then
if (self.Properties.bLoop~=0) then
Sound.SetSoundLoop(self.soundid,1);
else
Sound.SetSoundLoop(self.soundid,0);
end;
Sound.SetSoundVolume(self.soundid,self.Properties.iVolume);
--Sound.SetSoundProperties(self.sound,self.Properties.fFadeValue);
end;
end
----------------------------------------------------------------------------------------
function MissionHint:OnReset()
-- Set basic sound params.
--System.LogToConsole("Reset SP");
--System.LogToConsole("self.Properties.bPlay:"..self.Properties.bPlay..", self.started:"..self.started);
--System.LogToConsole("Resetting now");
self.SkipCount = 0;
self.HintCount = 1;
self.skipped = 0;
self:StopSound();
--self.sound = nil;
self.soundid = nil;
self:ActivateOutput( "Done",false );
Sound.SetGroupScale(SOUNDSCALE_MISSIONHINT, 1.0);
end
----------------------------------------------------------------------------------------
MissionHint["Server"] = {
OnInit= function (self)
self:Activate(0);
self.started = 0;
end,
OnShutDown= function (self)
end,
}
----------------------------------------------------------------------------------------
MissionHint["Client"] = {
----------------------------------------------------------------------------------------
OnInit = function(self)
self:Activate(0);
--System.LogToConsole("OnInit");
self.started = 0;
self.loop = self.Properties.bLoop;
self.soundName = "";
self:ActivateOutput( "Done",false );
if (self.Properties.bPlay==1) then
self:Play();
end
end,
----------------------------------------------------------------------------------------
OnTimer= function(self)
if (self.soundid) then
if ((not Sound.IsPlaying(self.soundid)) or (g_localActor:IsDead())) then
--System.Log("sound stopped - sound scale to normal");
Sound.StopSound(self.soundid)
self.soundid = nil;
Sound.SetGroupScale(SOUNDSCALE_MISSIONHINT, 1.0);
else
-- Sound still playing.
-- set another timer.
self:SetTimer(0, 1000);
end
end
end,
----------------------------------------------------------------------------------------
OnShutDown = function(self)
self:StopSound();
end,
----------------------------------------------------------------------------------------
OnSoundDone = function(self)
self:ActivateOutput( "Done",true );
--System.LogToConsole("Done sound"..self.Properties.soundName);
end,
}
----------------------------------------------------------------------------------------
function MissionHint:Play()
--System.LogToConsole("\005 Now playing with "..self.SkipCount.." skip and "..self.HintCount.." hint");
System.Log("Now playing with "..self.SkipCount.." skip and "..self.HintCount.." hint");
if ((self.Properties.bEnabled == 0 ) or (self.skipped == 1) ) then
do return end;
end
if(self.soundid~=nil and Sound.IsPlaying(self.soundid) )then
Sound.StopSound(self.soundid);
Sound.SetGroupScale(SOUNDSCALE_MISSIONHINT, 1.0);
self.SkipCount = self.SkipCount+1;
end
--System.Log("Now playing 2 ");
self.soundid = nil;
if (self.SkipCount > self.Properties.iAllowedToSkip) then
if (sndSkipAcknowledge ~= "") then
self.skipped = 1;
--self.soundid = Sound.LoadSound(self.Properties.sndSkipAcknowledge);
self.soundName = self.Properties.sndSkipAcknowledge;
--System.Log("Now playing 3 "..self.soundName);
end
else
if (self.soundid == nil) then
self:LoadSnd();
--if (self.soundid == nil) then
--return;
--end;
end
end
local sndFlags = SOUND_2D;
--sndFlags = bor(sndFlags, SOUND_LOOP);
if (self.Properties.bLoop~=0) then
sndFlags = bor(sndFlags, SOUND_LOOP);
--Sound.SetSoundLoop(self.soundid,1);
--else
--Sound.SetSoundLoop(self.soundid,0);
end;
--Sound.SetSoundVolume(self.soundid,self.Properties.iVolume);
self:SetTimer(0, 1000);
--Game:PlaySubtitle(self.soundid);
--System.Log("Try to play 4 "..self.soundName);
self.soundid = self:PlaySoundEvent(self.soundName, g_Vectors.v000, g_Vectors.v010, sndFlags, SOUND_SEMANTIC_DIALOG);
--System.Log("Now playing 4 "..self.soundid);
--Sound.PlaySound(self.sound);
--Sound.PlaySoundFadeUnderwater(self.sound);
--System.LogToConsole( "Play Sound" );
if (self.Properties.bScaleDownVolumes==1) then
Sound.SetGroupScale(SOUNDSCALE_MISSIONHINT, SOUND_VOLUMESCALEMISSIONHINT);
end
end
----------------------------------------------------------------------------------------
function MissionHint:StopSound()
if (self.Properties.bEnabled == 0 ) then
do return end;
end
-- if (self.soundid ~= nil and Sound.IsPlaying(self.soundid) ) then
if (self.soundid ~= nil ) then
Sound.StopSound(self.soundid);
--System.LogToConsole( "Stop Sound" );
self.soundid = nil;
end
self.started = 0;
end
----------------------------------------------------------------------------------------
function MissionHint:LoadSnd()
if (self.Properties.Hints["sndHint"..self.HintCount] ~= "") then
--self.sound = Sound.LoadSound(self.Properties.Hints["sndHint"..self.HintCount]);
self.soundName = self.Properties.Hints["sndHint"..self.HintCount];
self.HintCount = self.HintCount + 1;
end
--self.soundName = self.Properties.Hints["sndHint"..self.HintCount];
--System.Log("Now playing Count: "..self.soundName );
end
-------------------------------------------------------------------------------
-- Stop Event
-------------------------------------------------------------------------------
function MissionHint:Event_Stop( sender )
self:StopSound();
--BroadcastEvent( self,"Stop" );
end
function MissionHint:Event_Play( sender )
self:Play();
--BroadcastEvent( self,"bPlay" );
end
function MissionHint:Event_Enable( sender )
self.Properties.bEnabled = true;
--BroadcastEvent( self,"Enable" );
self:OnPropertyChange();
end
function MissionHint:Event_Disable( sender )
self.Properties.bEnabled = false;
--BroadcastEvent( self,"Disable" );
self:OnPropertyChange();
end
MissionHint.FlowEvents =
{
Inputs =
{
Play = { MissionHint.Event_Play, "bool" },
Stop = { MissionHint.Event_Stop, "bool" },
Enable = { MissionHint.Event_Enable, "bool" },
Disable = { MissionHint.Event_Disable, "bool" },
},
Outputs =
{
Done = "bool",
},
}
|
-- CCDIKController
-- Dthecoolest
-- December 27, 2020
local Debris = game:GetService("Debris") -- for debugging
local RunService = game:GetService("RunService")
local TweenService = game:GetService("TweenService")
local VectorUtil = require(script.VectorUtil)
local Maid = require(script.Maid)
--Axis angle version still here for testing purposes
local function fromToRotation(u, v, axis)
local dot = u:Dot(v)
if dot > 0.99999 then
-- situation 1
return CFrame.new()
elseif dot < -0.99999 then
-- situation 2
return CFrame.fromAxisAngle(axis, math.pi)
end
-- situation 3
return CFrame.fromAxisAngle(u:Cross(v), math.acos(dot) * 0.8)
end
--Quaternion rotation version from Egomoose
--The cooler version (⌐□_□)
local function getRotationBetween(u, v, axis)
local dot, uxv = u:Dot(v), u:Cross(v)
if dot < -0.99999 then
return CFrame.fromAxisAngle(axis, math.pi)
end
return CFrame.new(0, 0, 0, uxv.x, uxv.y, uxv.z, 1 + dot)
end
--[[
Amount is in radians
rotate vector around an axis
]]
local function rotateVectorAround(v, amount, axis)
return CFrame.fromAxisAngle(axis, amount):VectorToWorldSpace(v)
end
local CFNEW = CFrame.new
local CFLOOKAT = CFrame.lookAt
local ZEROVEC = Vector3.new()
local DOWNVECTOR = Vector3.new(0, -1, 0)
--local motor6d = Instance.new("Motor6D")
--Dictionary of how to setup the axis constraints
local hipJoint = Instance.new("Motor6D")
local kneeJoint = Instance.new("Motor6D")
local constraintsTemplate = {
[kneeJoint] = {
["ConstraintType"] = "Hinge",
["UpperAngle"] = 45, -- same as HingeConstraint [-180,180] degrees
["LowerAngle"] = -45,
["AxisAttachment"] = nil, --Automatically tries to find first child an attachment with the part0Motor6dName..AxisAttachment
["JointAttachment"] = nil,
},
[hipJoint] = {
["ConstraintType"] = "BallSocketConstraint",
["UpperAngle"] = 45, -- same as BallSocketConstraint [-180,180] degrees
["TwistLimitsEnabled"] = false, -- yep same as roblox constraints
["TwistUpperAngle"] = 45,
["TwistLowerAngle"] = -45,
["AxisAttachment"] = nil, --Automatically tries to find first child during .new() setup but you can manually input it
["JointAttachment"] = nil,
},
}
local CCDIKController = {}
CCDIKController.__index = CCDIKController
function CCDIKController.new(Motor6DTable, Constraints)
local self = setmetatable({}, CCDIKController)
self.Maid = Maid.new()
self.Motor6DTable = Motor6DTable
--resets the rotation of the Motor6D automatically
--Prevents C0 orientated models like R6 from spinning wildly
--Not needed anymore, was due to C0 and C1 orientations not being 0
--Fixed with new C0 formula
-- for i, motor6D in pairs(Motor6DTable) do
--local newC1Orientation = motor6D.C1 * motor6D.C0:Inverse()
--newC1Orientation -= newC1Orientation.Position
--motor6D.C0 = CFrame.new() + motor6D.C0.Position
--motor6D.C1 = newC1Orientation + motor6D.C1.Position
-- end
self.Constraints = Constraints
self.JointInfo, self.JointAxisInfo = self:SetupJoints() -- Creates instances make sure to clean up via :Destroy()
self.EndEffector = Motor6DTable[#Motor6DTable].Part1:FindFirstChild("EndEffector")
if not self.EndEffector then
local endEffector = Instance.new("Attachment")
endEffector.Name = "EndEffector"
endEffector.Parent = Motor6DTable[#Motor6DTable].Part1
self.EndEffector = endEffector
self.Maid:GiveTask(endEffector)
end
self.DebugMode = false
self.LerpMode = true
self.LerpAlpha = 0.9
self.ConstantLerpSpeed = true
self.AngularSpeed = math.rad(90)
self.FootOrientationSystem = false
self.FootRaycastParams = RaycastParams.new()
self.RaycastLengthDown = 50
self._RayResultTable = {}
--additional feature
self.UseLastMotor = false
return self
end
--[[
Sets up the attachments to find the Motor6D joints position in world space, also tries to find the constraint axis
]]
function CCDIKController:SetupJoints()
local joints = {}
local jointAxisInfo = {}
for _, motor in pairs(self.Motor6DTable) do
--In order to find the joint in world terms and index it fast, only thing that needs to be destroyed
local attachment = Instance.new("Attachment")
attachment.CFrame = motor.C0
attachment.Name = "JointPosition"
attachment.Parent = motor.Part0
joints[motor] = attachment
self.Maid:GiveTask(attachment)
if self.Constraints then
local motorConstraints = self.Constraints[motor]
if motorConstraints then
--If it doesn't already have an axis attachment, find one,
if not motorConstraints.AxisAttachment then
local AxisAttachment = motor.Part0:FindFirstChild(motor.Part0.Name .. "AxisAttachment")
motorConstraints["AxisAttachment"] = AxisAttachment
elseif typeof(motorConstraints.AxisAttachment) == "string" then
local AxisAttachment = motor.Part0:FindFirstChild(
motorConstraints.AxisAttachment .. "AxisAttachment"
)
motorConstraints["AxisAttachment"] = AxisAttachment
end
--same here for joint attachment
if not motorConstraints.JointAttachment then
local JointAttachment = motor.Part1:FindFirstChild(motor.Part0.Name .. "JointAttachment")
motorConstraints["JointAttachment"] = JointAttachment
elseif typeof(motorConstraints.JointAttachment) == "string" then
local JointAttachment = motor.Part1:FindFirstChild(
motorConstraints.JointAttachment .. "JointAttachment"
)
motorConstraints["JointAttachment"] = JointAttachment
end
end
end
end
--self.JointInfo = joints
--self.JointAxisInfo = jointAxisInfo
return joints, jointAxisInfo
end
--[[
Adds constraints settings from Roblox constraint instances already inside the model.
]]
function CCDIKController:GetConstraints()
if not self.Constraints then -- construct the constraint table if none
self.Constraints = {}
end
for _, motor in pairs(self.Motor6DTable) do
local motorPart0: Part
motorPart0 = motor.Part0
local hingeConstraint = motorPart0:FindFirstChildWhichIsA("HingeConstraint")
local ballSocketConstraint = motorPart0:FindFirstChildWhichIsA("BallSocketConstraint")
if hingeConstraint then
self.Constraints[motor] = {
["ConstraintType"] = "Hinge",
["UpperAngle"] = hingeConstraint.UpperAngle, -- same as HingeConstraint [-180,180] degrees
["LowerAngle"] = hingeConstraint.LowerAngle,
["AxisAttachment"] = hingeConstraint.Attachment0,
["JointAttachment"] = hingeConstraint.Attachment1,
}
elseif ballSocketConstraint then
self.Constraints[motor] = {
["ConstraintType"] = "BallSocketConstraint",
["UpperAngle"] = ballSocketConstraint.UpperAngle, -- same as BallSocketConstraint [-180,180] degrees
["TwistLimitsEnabled"] = ballSocketConstraint.TwistLimitsEnabled, -- still have no idea how to do
["TwistUpperAngle"] = ballSocketConstraint.TwistUpperAngle, -- so yeah no twist limits for now
["TwistLowerAngle"] = ballSocketConstraint.TwistLowerAngle,
["AxisAttachment"] = ballSocketConstraint.Attachment0, --Automatically tries to find first child during .new() setup but you can manually input it
["JointAttachment"] = ballSocketConstraint.Attachment1,
}
end
end
end
--[[--------------------------------------------------------
Same as GetConstraints except uses :FindFirstChild() to find the roblox constraint and sets settings accordingly
]]
function CCDIKController:GetConstraintsFromMotor(motor: Motor6D, constraintName: string)
if not self.Constraints then -- construct the constraint table if none
self.Constraints = {}
end
local constraint = motor.Part0:FindFirstChild(constraintName)
if constraint:IsA("HingeConstraint") then
self.Constraints[motor] = {
["ConstraintType"] = "Hinge",
["UpperAngle"] = constraint.UpperAngle, -- same as HingeConstraint [-180,180] degrees
["LowerAngle"] = constraint.LowerAngle,
["AxisAttachment"] = constraint.Attachment0,
["JointAttachment"] = constraint.Attachment1,
}
elseif constraint:IsA("BallSocketConstraint") then
self.Constraints[motor] = {
["ConstraintType"] = "BallSocketConstraint",
["UpperAngle"] = constraint.UpperAngle, -- same as BallSocketConstraint [-180,180] degrees
["TwistLimitsEnabled"] = constraint.TwistLimitsEnabled, -- still have no idea how to do
["TwistUpperAngle"] = constraint.TwistUpperAngle, -- so yeah no twist limits for now
["TwistLowerAngle"] = constraint.TwistLowerAngle,
["AxisAttachment"] = constraint.Attachment0, --Automatically tries to find first child during .new() setup but you can manually input it
["JointAttachment"] = constraint.Attachment1,
}
end
end
--[[
Internal function for CCDIK Iteration step
]]
function CCDIKController:_CCDIKIterateFoot(step)
local constraints = self.Constraints
local motor6DTable = self.Motor6DTable
local footJoint = motor6DTable[#motor6DTable]
footJoint.C0 *= footJoint.Transform
self:OrientFootMotorToFloor(footJoint, step)
footJoint.Transform = CFNEW()
if constraints then
local jointConstraintInfo = constraints[footJoint]
if jointConstraintInfo then
if jointConstraintInfo.ConstraintType == "Hinge" then
self:RotateToHingeAxis(footJoint, jointConstraintInfo)
end
if jointConstraintInfo.ConstraintType == "BallSocketConstraint" then
self:RotateToBallSocketConstraintAxis(footJoint, jointConstraintInfo)
end
end
end
end
--[[
Performs one iteration of the CCDIK step regardless of the end condition
]]
function CCDIKController:_CCDIKIterateStep(goalPosition, step)
local constraints = self.Constraints
local useLastMotor = self.UseLastMotor and 1 or 0 --Makes it so that it iterates the only one motor in the table
for i = #self.Motor6DTable - 1 + useLastMotor, 1, -1 do
local currentJoint = self.Motor6DTable[i]
currentJoint.C0 *= currentJoint.Transform -- apply animations to C0
self:RotateFromEffectorToGoal(currentJoint, goalPosition, step)
currentJoint.Transform = CFNEW()
if constraints then
local jointConstraintInfo = constraints[currentJoint]
if jointConstraintInfo then
if jointConstraintInfo.ConstraintType == "Hinge" then
self:RotateToHingeAxis(currentJoint, jointConstraintInfo)
end
if jointConstraintInfo.ConstraintType == "BallSocketConstraint" then
self:RotateToBallSocketConstraintAxis(currentJoint, jointConstraintInfo)
end
end
end
end
end
--[[------------------------------
Iterates only if goalPosition is not yet reached
]]
function CCDIKController:CCDIKIterateOnce(goalPosition, tolerance, step)
local endEffectorPosition = self.EndEffector.WorldPosition
local distanceToGoal = endEffectorPosition - goalPosition
local tolerance = tolerance or 1
if distanceToGoal.Magnitude > tolerance then
self:_CCDIKIterateStep(goalPosition, step)
end
--Always attempt to orientate foot to floor
if self.FootOrientationSystem then
self:_CCDIKIterateFoot(step)
end
end
function CCDIKController:CCDIKIterateOnceDebug(goalPosition, tolerance, step)
-- local endEffectorPosition = self.EndEffector.WorldPosition
-- local distanceToGoal = endEffectorPosition-goalPosition
-- local tolerance = tolerance or 0
self:_CCDIKIterateStep(goalPosition, step)
--Always attempt to orientate foot to floor
--not for the debug mode
-- if self.FootOrientationSystem then
-- self:_CCDIKIterateFoot(step)
-- end
end
-- Same as Iterate once but in a while loop
function CCDIKController:CCDIKIterateUntil(goalPosition, tolerance, maxBreakCount, step)
local maxBreakCount = maxBreakCount or 10
local currentIterationCount = 0
local endEffectorPosition = self.EndEffector.WorldPosition
local distanceToGoal = endEffectorPosition - goalPosition
local tolerance = tolerance or 1
while distanceToGoal.Magnitude > tolerance and maxBreakCount >= currentIterationCount do
currentIterationCount += 1
self:_CCDIKIterateStep(goalPosition, step)
if self.FootOrientationSystem then
self:_CCDIKIterateFoot(step)
end
end
end
local function worldCFrameToC0ObjectSpace(motor6DJoint, worldCFrame)
local part1CF = motor6DJoint.Part1.CFrame
local c1Store = motor6DJoint.C1
local c0Store = motor6DJoint.C0
local relativeToPart1 = c0Store * c1Store:Inverse() * part1CF:Inverse() * worldCFrame * c1Store
relativeToPart1 -= relativeToPart1.Position
local goalC0CFrame = relativeToPart1 + c0Store.Position
return goalC0CFrame
end
local function calculateGoalFromToC0CFrame(motor6DJoint, u, v, axis)
local rotationCFrame = fromToRotation(u, v, axis)
local part1CF = motor6DJoint.Part1.CFrame
local c1Store = motor6DJoint.C1
local c0Store = motor6DJoint.C0
--calculate goal world CFrame
local goalWorldCFrame = rotationCFrame * part1CF
--do the New C1 Inversing
local relativeToPart1 = c0Store * c1Store:Inverse() * part1CF:Inverse() * goalWorldCFrame * c1Store
--maintain original C0 position
relativeToPart1 -= relativeToPart1.Position
local goalC0CFrame = relativeToPart1 + c0Store.Position
-- local goalC0CFrame = relativeToPart1
return goalC0CFrame
end
function CCDIKController.rotateJointFromTo(motor6DJoint, u, v, axis)
local goalC0CFrame = calculateGoalFromToC0CFrame(motor6DJoint, u, v, axis)
motor6DJoint.C0 = goalC0CFrame
end
local tweenInfo = TweenInfo.new(0.1)
function CCDIKController.rotateJointFromToTween(motor6DJoint, u, v, axis)
print("Tweeen")
--alternative calculation method
local goalC0CFrame = calculateGoalFromToC0CFrame(motor6DJoint, u, v, axis)
local tween = TweenService:Create(motor6DJoint, tweenInfo, { C0 = goalC0CFrame })
tween:Play()
tween.Completed:Wait()
end
--Controls the primary CCDIK Method but instead of going fully towards the goal it lerps slowly towards it instead
function CCDIKController:rotateJointFromToWithLerp(motor6DJoint: Motor6D, u, v, axis, step)
--print("Rotateting")
local goalC0CFrame = calculateGoalFromToC0CFrame(motor6DJoint, u, v, axis)
local lerpAlpha = self.LerpAlpha
local currentC0 = motor6DJoint.C0
if step and self.ConstantLerpSpeed then
local angularDistance = VectorUtil.AngleBetween(currentC0.LookVector, goalC0CFrame.LookVector)
local estimatedTime = self.AngularSpeed / angularDistance
lerpAlpha = math.min(step * estimatedTime, 1)
end
motor6DJoint.C0 = currentC0:Lerp(goalC0CFrame, lerpAlpha)
end
--[[------------------------------
Primary joint movement method which performs the CCDIK algorithm of rotating a joint from end effector to goal
]]
function CCDIKController:RotateFromEffectorToGoal(motor6d: Motor6D, goalPosition, step)
local motor6dPart0 = motor6d.Part0
local part0CF = motor6dPart0.CFrame
local jointWorldPosition = self.JointInfo[motor6d].WorldPosition
--local jointWorldPosition = (motor6d.Part0.CFrame*motor6d.C0).Position
--Faster to use attachments
local endEffectorPosition = self.EndEffector.WorldPosition
local directionToEffector = (endEffectorPosition - jointWorldPosition).Unit
local directionToGoal = (goalPosition - jointWorldPosition).Unit
if self.DebugMode then
self.VisualizeVector(jointWorldPosition, endEffectorPosition - jointWorldPosition, BrickColor.Blue())
self.VisualizeVector(jointWorldPosition, goalPosition - jointWorldPosition, BrickColor.Red())
self.rotateJointFromToTween(motor6d, directionToEffector, directionToGoal, part0CF.UpVector)
return --skip the rest since debug mode lol
end
if self.LerpMode ~= true then
self.rotateJointFromTo(motor6d, directionToEffector, directionToGoal, part0CF.RightVector)
else
self:rotateJointFromToWithLerp(motor6d, directionToEffector, directionToGoal, part0CF.RightVector, step)
end
end
--[[---------------------------------------------------------
This function constraints the rotation of the part1 to the hinge axis of the part0, then also does local EulerAngle constraints
Dictionary to setup the constraint information:
[motor6d] = {
["ConstraintType"] = "Hinge";
["UpperAngle"] = 45; -- same as HingeConstraint [-180,180] degrees
["LowerAngle"] = -45;
["AxisAttachment"] = nil; --Automatically tries to find first child during .new() setup but you can manually input it
["JointAttachment"] = nil;
};
]]
function CCDIKController:RotateToHingeAxis(motor6d: Motor6D, jointConstraintInfo)
local motor6dPart0 = motor6d.Part0
local part0CF = motor6dPart0.CFrame
local axisAttachment = jointConstraintInfo.AxisAttachment
local jointAttachment = jointConstraintInfo.JointAttachment
local hingeAxis = axisAttachment.WorldAxis
local currentHingeAxis = jointAttachment.WorldAxis
--Enforce hinge axis, has to be instantaneous
self.rotateJointFromTo(motor6d, currentHingeAxis, hingeAxis, part0CF.RightVector)
--Then enforce hinge constraints
local axisCFrame = axisAttachment.WorldCFrame
local jointCFrame = jointAttachment.WorldCFrame
local upperAngle = jointConstraintInfo.UpperAngle or 180
local lowerAngle = jointConstraintInfo.LowerAngle or -180
local localCFrame: CFrame
localCFrame = axisCFrame:ToObjectSpace(jointCFrame)
local x, _, _ = localCFrame:ToEulerAnglesXYZ()
--print(math.round(math.deg(x)),math.round(math.deg(y)),math.round(math.deg(z))) -- yep x is the rotation
local constrainedX = math.clamp(math.deg(x), lowerAngle, upperAngle)
constrainedX = math.rad(constrainedX)
local constrainedJointCFrame = CFrame.fromEulerAnglesXYZ(constrainedX, 0, 0)
local newWorldJointCFrame = axisCFrame:ToWorldSpace(constrainedJointCFrame)
local newPart1CFrame = newWorldJointCFrame * jointAttachment.CFrame:Inverse() -- Uhh only works with attachments
-- local goalCFRotation = motor6d.Part0.CFrame:Inverse() * newPart1CFrame
-- goalCFRotation = goalCFRotation - goalCFRotation.Position
local goalCFRotation = worldCFrameToC0ObjectSpace(motor6d, newPart1CFrame)
motor6d.C0 = goalCFRotation
end
--[[---------------------------------------------------------
This function constraints the rotation of the part1 to the hinge axis of the part0, then also does local EulerAngle constraints
Dictionary to setup the constraint information:
[motor6d] = {
["ConstraintType"] = "BallSocketConstraint";
["UpperAngle"] = 45; -- same as BallSocketConstraint [-180,180] degrees
["TwistLimitsEnabled"] = ; -- still have no idea how to do
["TwistUpperAngle"] = -45;--
["TwistLowerAngle"] = -45;
["AxisAttachment"] = nil; --Automatically tries to find first child during .new() setup but you can manually input it
["JointAttachment"] = nil;
};
]]
local function twistSwing(cf, direction)
local axis, theta = cf:ToAxisAngle()
local w, v = math.cos(theta / 2), math.sin(theta / 2) * axis
local proj = v:Dot(direction) * direction
local twist = CFrame.new(cf.x, cf.y, cf.z, proj.x, proj.y, proj.z, w)
local swing = twist:Inverse() * cf
return swing, twist
end
function CCDIKController:RotateToBallSocketConstraintAxis(motor6d, jointConstraintInfo)
local motor6dPart0 = motor6d.Part0
local part0CF = motor6dPart0.CFrame
local axisAttachment = jointConstraintInfo.AxisAttachment
local jointAttachment = jointConstraintInfo.JointAttachment
local centerAxis = axisAttachment.WorldAxis
local currentCenterAxis = jointAttachment.WorldAxis
local angleDifference = VectorUtil.AngleBetween(currentCenterAxis, centerAxis)
local constraintUpperAngle = math.rad(jointConstraintInfo.UpperAngle) or math.rad(45)
--out of bounds constrain it to world axis of the socket
if angleDifference > constraintUpperAngle then
local axis = currentCenterAxis:Cross(centerAxis)
local angleDifference = angleDifference - constraintUpperAngle
local newCenterAxisWithinBounds = rotateVectorAround(currentCenterAxis, angleDifference, axis)
self.rotateJointFromTo(motor6d, currentCenterAxis, newCenterAxisWithinBounds, part0CF.RightVector)
end
--Now enforce twist limits
if jointConstraintInfo.TwistLimitsEnabled then
local axisCFrame = axisAttachment.WorldCFrame
local currentJointCFrame = jointAttachment.WorldCFrame
local twistSwingAxis = axisAttachment.WorldAxis
local jointRelativeCFrame = axisCFrame:ToObjectSpace(currentJointCFrame)
local swing, twist = twistSwing(jointRelativeCFrame, twistSwingAxis)
local axis, angle = twist:ToAxisAngle()
local axisSign = math.sign(axis:Dot(twistSwingAxis))
axis, angle = axisSign * axis, axisSign * angle --make the signs relative to twist axis
angle = math.deg(angle)
local upperAngle = jointConstraintInfo.TwistUpperAngle
local lowerAngle = jointConstraintInfo.TwistLowerAngle
local notConstrained = false
if angle > upperAngle then
angle = upperAngle
elseif angle < lowerAngle then
angle = lowerAngle
else
notConstrained = true
end
if not notConstrained then
angle = math.rad(angle)
local newTwist = CFrame.fromAxisAngle(axis, angle)
local newConstraintedRelativeCFrame = newTwist * swing
local newJointWorldCFrame = axisCFrame * newConstraintedRelativeCFrame
local part1CF = newJointWorldCFrame * jointAttachment.CFrame:Inverse()
-- local goalCF = motor6d.Part0.CFrame:Inverse() * part1CF -- old to object space method
local goalCF = worldCFrameToC0ObjectSpace(motor6d, part1CF)
motor6d.C0 = goalCF
end
end
end
--[[
Finds the attachments in the part1 foot and the raycasting params the system uses
]]
function CCDIKController:SetupFoot(attachmentNameTable: table, raycastParams)
local motor6DTable = self.Motor6DTable
local footJoint = motor6DTable[#motor6DTable]
local footPart = footJoint.Part1
local footAttachmentTable = {}
for i, attachmentName in pairs(attachmentNameTable) do
footAttachmentTable[i] = footPart:FindFirstChild(attachmentName)
end
self.FootAttachmentTable = footAttachmentTable
self.FootRaycastParams = raycastParams
self.FootOrientationSystem = true
end
function CCDIKController:OrientFootMotorToFloor(motor6d: Motor6D, step)
local attachmentTable = self.FootAttachmentTable
local lengthToFloor = self.RaycastLengthDown
local rayResultTable = self._RayResultTable
local raycastParams = self.FootRaycastParams
for i = 1, 3 do
local attachment = attachmentTable[i]
local rayOrigin = attachment.WorldPosition
local rayDown = -attachment.WorldCFrame.UpVector * lengthToFloor
rayResultTable[i] = workspace:Raycast(rayOrigin, rayDown, raycastParams)
end
local raycastNilCheck = (rayResultTable[1] and rayResultTable[2] and rayResultTable[3]) == nil
local footCFrame = self.EndEffector.WorldCFrame
local newUpVector = raycastNilCheck and footCFrame.UpVector
or (rayResultTable[2].Position - rayResultTable[1].Position):Cross(
rayResultTable[3].Position - rayResultTable[1].Position
).Unit
local currentFootUpVector = footCFrame.UpVector
--fixes the ? foot inverting issue
if raycastNilCheck == false then
self:rotateJointFromToWithLerp(motor6d, currentFootUpVector, newUpVector, footCFrame.UpVector, step)
end
--Then enforce constraints
local constraints = self.Constraints
if constraints then
local jointConstraintInfo = constraints[motor6d]
if jointConstraintInfo then
if jointConstraintInfo.ConstraintType == "Hinge" then
self:RotateToHingeAxis(motor6d, jointConstraintInfo)
end
if jointConstraintInfo.ConstraintType == "BallSocketConstraint" then
self:RotateToBallSocketConstraintAxis(motor6d, jointConstraintInfo)
end
end
end
end
function CCDIKController:InitDragDebug()
local lastPart1 = self.Motor6DTable[#self.Motor6DTable].Part1
self.LerpMode = false
local dragMe = Instance.new("Part")
dragMe.CanCollide = false
dragMe.Anchored = true
dragMe.Size = Vector3.new(1, 1, 1)
dragMe.BrickColor = BrickColor.random()
dragMe.Position = lastPart1.Position
dragMe.Name = "DragMe!: " .. lastPart1.Name
dragMe.Parent = workspace
RunService.Heartbeat:Connect(function()
self:CCDIKIterateOnce(dragMe.Position)
end)
end
function CCDIKController:InitTweenDragDebug()
local lastPart1 = self.Motor6DTable[#self.Motor6DTable].Part1
self.DebugMode = true
--self.JointInfo[motor6d].WorldPosition
for i = 1, #self.Motor6DTable - 1 do
print("test")
local motor1 = self.Motor6DTable[i]
local motor2 = self.Motor6DTable[i + 1]
local t1 = self.JointInfo[motor1].WorldPosition
local t2 = self.JointInfo[motor2].WorldPosition
local position = t1
local direction = t2 - t1
local wedgePart = Instance.new("WedgePart")
wedgePart.Size = Vector3.new(0.1, 0.1, direction.Magnitude)
wedgePart.CFrame = CFLOOKAT(position, position + direction) * CFrame.new(0, 0, -direction.Magnitude / 2)
wedgePart.CanCollide = false
local weldConstraint = Instance.new("WeldConstraint")
weldConstraint.Part0 = wedgePart
weldConstraint.Part1 = motor2.Parent
weldConstraint.Parent = motor2.Parent
wedgePart.Parent = workspace
wedgePart.Name = "I am a limb vector"
end
for i, Motor in pairs(self.Motor6DTable) do
Motor.Part1.Transparency = 0.75
Motor.Part0.Transparency = 0.75
end
local dragMe = Instance.new("Part")
dragMe.CanCollide = false
dragMe.Anchored = true
dragMe.Size = Vector3.new(1, 1, 1)
dragMe.BrickColor = BrickColor.random()
dragMe.Position = lastPart1.Position
dragMe.Name = "DragMe!: " .. lastPart1.Name
dragMe.Parent = workspace
spawn(function()
while true do
wait() --eh
self:CCDIKIterateOnceDebug(dragMe.Position)
end
end)
end
--[[---------------------------------------------------------
Reverse Humanoid:BuildRigFromAttachments
Finds Motor6D's and places where the joints are located as attachments
Usefull for creating HingeConstraints and BallSocketConstraints to visualize and orientate the attachments
Pretty necessary in fact to create the attachment axis and decide the upper angle or lower angle
]]
function commandBarSetupJoints(model)
local modelDescendants = model:GetDescendants()
for _, motor6D in pairs(modelDescendants) do
if motor6D:IsA("Motor6D") then
--In order to find the joint in world terms
local Part0Name = motor6D.Part0.Name
local AxisAttachment = Instance.new("Attachment")
AxisAttachment.CFrame = motor6D.C0
AxisAttachment.Name = Part0Name .. "AxisAttachment"
AxisAttachment.Parent = motor6D.Part0
local JointAttachment = Instance.new("Attachment")
JointAttachment.CFrame = motor6D.C1
JointAttachment.Name = Part0Name .. "JointAttachment"
JointAttachment.Parent = motor6D.Part1
end
end
end
--Same as the above function but follow RigAttachment naming rule
function commandBarSetupRigAttachments(model)
local modelDescendants = model:GetDescendants()
for _, motor6D in pairs(modelDescendants) do
if motor6D:IsA("Motor6D") then
--In order to find the joint in world terms
local motor6DName = motor6D.Name
local AxisAttachment = Instance.new("Attachment")
AxisAttachment.CFrame = motor6D.C0
AxisAttachment.Name = motor6DName .. "RigAttachment"
AxisAttachment.Parent = motor6D.Part0
local JointAttachment = Instance.new("Attachment")
JointAttachment.CFrame = motor6D.C1
JointAttachment.Name = motor6DName .. "RigAttachment"
JointAttachment.Parent = motor6D.Part1
end
end
end
--[[
Utility function spawning a wedge part to visualize a vector in world space
]]
function CCDIKController.VisualizeVector(position, direction, brickColor)
local wedgePart = Instance.new("WedgePart")
wedgePart.Size = Vector3.new(0.1, 0.1, direction.Magnitude)
wedgePart.CFrame = CFLOOKAT(position, position + direction) * CFrame.new(0, 0, -direction.Magnitude / 2)
wedgePart.Anchored = true
wedgePart.CanCollide = false
wedgePart.BrickColor = brickColor or BrickColor.random()
wedgePart.Parent = workspace
Debris:AddItem(wedgePart, 0.75)
end
--[[
Do cleaning destroys all the instances made by this object
]]
function CCDIKController:Destroy()
self.Maid:DoCleaning()
self = nil
end
return CCDIKController
|
local a = 1; -- A comment
--[[ A multiline
comment that takes a lot
of space :)
]] |
local Modules = game:GetService("Players").LocalPlayer.PlayerGui.AvatarEditorInGame.Modules
local Roact = require(Modules.Packages.Roact)
local UIBlox = require(Modules.Packages.UIBlox)
local ImageSetButton = UIBlox.Core.ImageSet.Button
local withStyle = UIBlox.Style.withStyle
local Images = UIBlox.App.ImageSet.Images
local CloseViewButton = Roact.PureComponent:extend("CloseViewButton")
local IMAGE = Images["icons/actions/previewShrink"]
local IMAGE_SIZE = Vector2.new(36, 36)
local IMAGE_PADDING = Vector2.new(12, 12)
function CloseViewButton:render()
return withStyle(function(stylePalette)
local theme = stylePalette.Theme
return Roact.createElement(ImageSetButton, {
AnchorPoint = Vector2.new(1, 1),
BackgroundTransparency = 1,
Position = UDim2.new(1, -IMAGE_PADDING.X, 1, -IMAGE_PADDING.Y),
Size = UDim2.new(0, IMAGE_SIZE.X, 0, IMAGE_SIZE.Y),
Image = IMAGE,
ImageColor3 = theme.IconEmphasis.Color,
ImageTransparency = theme.IconEmphasis.Transparency,
[Roact.Event.Activated] = self.props.onActivated,
})
end)
end
return CloseViewButton
|
local utils = require("utils")
local drawableSpriteStruct = require("structs.drawable_sprite")
local jautils = require("mods").requireFromPlugin("libraries.jautils")
local customKevin = {}
local fillColor = jautils.getColor("62222b")
customKevin.name = "FrostHelper/SlowCrushBlock"
customKevin.depth = -9000
jautils.createPlacementsPreserveOrder(customKevin, "horizontal", {
{ "width", 16 },
{ "height", 16 },
{ "directory", "objects/FrostHelper/slowcrushblock/" },
{ "chillout", false },
{ "crushSpeed", 120.0 },
{ "returnSpeed", 60.0 },
{ "returnAcceleration", 160.0 },
{ "crushAcceleration", 250.0 },
{ "axes", "horizontal" }
})
jautils.addPlacement(customKevin, "vertical", {
{ "axes", "vertical"}
})
jautils.addPlacement(customKevin, "both", {
{ "axes", "both" }
})
local axesToBlockIndex = {
none = "0",
horizontal = "1",
vertical = "2",
both = "3",
}
function customKevin.sprite(room, entity)
local sprites = { jautils.getFilledRectangleSprite({x=entity.x + 2, y=entity.y + 2, width = entity.width - 4, height = entity.height - 4}, fillColor) }
for _, value in ipairs(jautils.getCustomBlockSprites(entity, "directory", "block0" .. axesToBlockIndex[entity.axes or "none"], "objects/FrostHelper/slowcrushblock/block00")) do
table.insert(sprites, value)
end
local giant = entity.height >= 48 and entity.width >= 48 and entity.chillout
table.insert(sprites, drawableSpriteStruct.fromTexture(giant and "objects/crushblock/giant_block00" or "objects/crushblock/idle_face", entity):setPosition(entity.x + (entity.width / 2), entity.y + (entity.height / 2)))
return sprites
end
function customKevin.selection(room, entity)
return utils.rectangle(entity.x, entity.y, entity.width, entity.height)
end
return customKevin |
--[[
Description: Dummy initializer to avoid dependency resolution errors on client or server
Author: Sceleratis
Date: 1/9/2022
--]]
--// Initializer functions
return {
Init = function(Root, Packages)
end;
}
|
local constants = require "kong.constants"
local kong_session = require "kong.plugins.session.session"
local kong = kong
local _M = {}
local function load_consumer(consumer_id)
local result, err = kong.db.consumers:select { id = consumer_id }
if not result then
return nil, err
end
return result
end
local function authenticate(consumer, credential_id, groups)
local set_header = kong.service.request.set_header
local clear_header = kong.service.request.clear_header
set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
if consumer.custom_id then
set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
else
clear_header(constants.HEADERS.CONSUMER_CUSTOM_ID)
end
if consumer.username then
set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
else
clear_header(constants.HEADERS.CONSUMER_USERNAME)
end
if groups then
set_header(constants.HEADERS.AUTHENTICATED_GROUPS, table.concat(groups, ", "))
ngx.ctx.authenticated_groups = groups
else
clear_header(constants.HEADERS.AUTHENTICATED_GROUPS)
end
if credential_id then
local credential = {id = credential_id or consumer.id, consumer_id = consumer.id}
set_header(constants.HEADERS.ANONYMOUS, true)
kong.client.authenticate(consumer, credential)
return
end
kong.client.authenticate(consumer, nil)
end
function _M.execute(conf)
local s = kong_session.open_session(conf)
if not s.present then
kong.log.debug("session not present")
return
end
-- check if incoming request is trying to logout
if kong_session.logout(conf) then
kong.log.debug("session logging out")
s:destroy()
return kong.response.exit(200)
end
local cid, credential, groups = kong_session.retrieve_session_data(s)
local consumer_cache_key = kong.db.consumers:cache_key(cid)
local consumer, err = kong.cache:get(consumer_cache_key, nil,
load_consumer, cid)
if err then
kong.log.err("could not load consumer: ", err)
return
end
-- destroy sessions with invalid consumer_id
if not consumer then
kong.log.debug("failed to find consumer, destroying session")
return s:destroy()
end
s:start()
authenticate(consumer, credential, groups)
kong.ctx.shared.authenticated_session = s
end
return _M
|
PluginInit = {
pluginID = "at.homebrew.lrdavinci",
}
|
local handler = require 'kong.plugins.signalfx.handler'
local helpers = require "spec.helpers"
local cjson = require "cjson"
local tostr = require 'pl.pretty'.write
local fmt = string.format
for _, strategy in helpers.each_strategy() do
describe(fmt("Aggregation (%s)", strategy), function()
local proxy_client, admin_client
local service_one, route_one
local service_two, route_two
setup(function()
local bp = helpers.get_db_utils(strategy)
service_one = bp.services:insert({})
route_one = bp.routes:insert({
hosts = { "myhost" },
service = service_one
})
assert(bp.plugins:insert {
name = "signalfx",
route_id = route_one.id,
})
service_two = bp.services:insert({})
route_two = bp.routes:insert({
hosts = { "myotherhost" },
service = service_two
})
assert(bp.plugins:insert {
name = "signalfx",
config = { aggregate_by_http_method = false },
route_id = route_two.id,
})
assert(helpers.start_kong({
path = os.getenv("PATH"),
lua_package_path = os.getenv("LUA_PATH"),
database = strategy,
nginx_conf = "/opt/kong-plugin-signalfx/spec/custom_nginx.template",
plugins = "signalfx"
}))
proxy_client = helpers.proxy_client()
admin_client = helpers.admin_client()
end)
teardown(function()
if proxy_client then proxy_client:close() end
if admin_client then admin_client:close() end
helpers.stop_kong()
end)
it("Aggregates as expected with http method", function()
for i=1, 1000 do
local res = assert(proxy_client:send {
method = "GET",
headers = {
["Host"] = "myhost",
}
})
assert.res_status(200, res)
end
ngx.sleep(1)
local res = assert(admin_client:send {
method = "GET",
path = "/signalfx",
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.same(json.database, {database_reachable = true})
assert.is_number(json.server.connections_accepted)
assert.is_number(json.server.connections_active)
assert.is_number(json.server.connections_handled)
assert.is_number(json.server.connections_reading)
assert.is_number(json.server.connections_waiting)
assert.is_number(json.server.connections_writing)
assert.is_number(json.server.total_requests)
local hdler = handler()
local expected_message = { service = service_one, route = route_one, request = { method = 'GET' } }
local expected_key = hdler:get_context_key(expected_message, { aggregate_by_http_method = true }):sub(6)
local metric_val_string = json.signalfx[expected_key]
assert.is_string(metric_val_string)
local request_count, _, _, _, _, _, statuses = hdler:decode_metrics(metric_val_string)
assert.is_equal(request_count, 1000)
assert.is_equal(statuses["200"].count, 1000)
end)
it("Aggregates as expected without http method", function()
for i=1, 1000 do
local res = assert(proxy_client:send {
method = "GET",
headers = {
["Host"] = "myotherhost",
}
})
assert.res_status(200, res)
end
ngx.sleep(1)
local res = assert(admin_client:send {
method = "GET",
path = "/signalfx",
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.same(json.database, {database_reachable = true})
assert.is_number(json.server.connections_accepted)
assert.is_number(json.server.connections_active)
assert.is_number(json.server.connections_handled)
assert.is_number(json.server.connections_reading)
assert.is_number(json.server.connections_waiting)
assert.is_number(json.server.connections_writing)
assert.is_number(json.server.total_requests)
local hdler = handler()
local expected_message = { service = service_two, route = route_two, request = {} }
local expected_key = hdler:get_context_key(expected_message, { aggregate_by_http_method = false }):sub(6)
local metric_val_string = json.signalfx[expected_key]
assert.is_string(metric_val_string)
local request_count, _, _, _, _, _, statuses = hdler:decode_metrics(metric_val_string)
assert.is_equal(request_count, 1000)
assert.is_equal(statuses["200"].count, 1000)
end)
end)
end
|
Locales['fr'] = {
['you_paid'] = 'vous avez payé ~g~$%s~s~',
['go_next_point'] = 'Allez vers le prochain passage !',
['in_town_speed'] = 'Entrée en ville, attention à votre vitesse ! Vitesse limite : ~y~',
['next_point_speed'] = 'Allez vers le prochain passage ! Vitesse limite : ~y~',
['stop_for_ped'] = 'Faite rapidement un ~r~stop~s~ pour le piéton qui ~y~traverse',
['good_lets_cont'] = '~g~Bien!~s~ continuons!',
['stop_look_left'] = 'Marquer rapidement un ~r~stop~s~ et regardez à votre ~y~gauche~s~. Vitesse limite : ~y~',
['good_turn_right'] = '~g~Bien!~s~ prenez à ~y~droite~s~ et suivez votre file',
['watch_traffic_lightson'] = 'Observez le feu rouge, puis allez tout droit',
['stop_for_passing'] = 'Marquez le stop pour laisser passer les véhicules !',
['hway_time'] = 'Il est temps d\'aller sur la rocade, prenez la deuxième sortie ! Vitesse limite : ~y~',
['go_end'] = 'Retournons en ville, prenez la première sortie',
['gratz_stay_alert'] = 'Bravo, restez vigiliant! Retournons à l auto-école',
['passed_test'] = 'Vous avez ~g~réussi~s~ le test',
['failed_test'] = 'Vous avez ~r~raté~s~ le test',
['theory_test'] = 'Examen du code',
['road_test_car'] = 'Examen de conduite voiture',
['road_test_bike'] = 'Examen de conduite moto',
['road_test_truck'] = 'Examen de conduite camion',
['driving_school'] = 'Ecole de conduite',
['press_open_menu'] = 'Appuyez sur ~INPUT_CONTEXT~ pour ~b~ouvrir le menu',
['driving_school_blip'] = 'Auto-école',
['driving_test_complete'] = 'Test de conduite terminé',
['driving_too_fast'] = 'Vous roulez trop vite, vitesse limite: ~y~%s~s~ km/h!',
['errors'] = 'Erreurs : ~r~%s~s~/%s',
['you_damaged_veh'] = 'Vous avez endommagé votre véhicule',
['yourpoor'] = 'Vous n\'avez pas assez d\'argent',
}
|
class "ZombiesTeamManager"
local g_Logger = require("__shared/Logger")
function ZombiesTeamManager:__init()
self.m_PlayerKilledEvent = Events:Subscribe("Player:Killed", self, self.OnPlayerKilled)
--self.m_PlayerRespawnEvent = Events:Subscribe("Player:Respawn", self, self.OnPlayerRespawn)
self.m_IsInGameChangedEvent = Events:Subscribe("Logic:IsInGameChanged", self, self.OnIsInGameChanged)
self.m_InitTeamsEvent = Events:Subscribe("TeamManager:InitTeams", self, self.OnInitTeams)
self.m_SelectZombieEvent = Events:Subscribe("TeamManager:SelectZombie", self, self.OnSelectZombies)
self.m_IsInGame = false
end
-- Event for getting when IsInGame is changed
function ZombiesTeamManager:OnIsInGameChanged(p_IsInGame)
self.m_IsInGame = p_IsInGame
end
function ZombiesTeamManager:OnInitTeams()
self:InitTeams()
end
function ZombiesTeamManager:OnSelectZombies()
self:SelectZombie()
end
-- Event when a player gets killed
function ZombiesTeamManager:OnPlayerKilled(p_Victom, p_Inflictor, p_Position, p_Weapon, p_RoadKill, p_HeadShot, p_VictomInReviveState)
-- Check to see if we are in game, if not skip the anouncing of messages
if self.m_IsInGame ~= true then
return
end
-- Ensure the attacker and victom are valid
if p_Victom == nil then
return
end
if p_Inflictor == nil then
return
end
s_VictomTeam = p_Victom.teamId
s_AttackerTeam = p_Inflictor.teamId
-- Send a debug message each time a zombie gets killed by a human
if s_VictomTeam == TeamId.Team2 and s_AttackerTeam == TeamId.Team1 then
g_Logger:Write("Zombie " .. p_Victom.name .. " was killed!")
ChatManager:SendMessage("Zombie " .. p_Victom.name .. " was killed!")
end
-- If a human gets killed via a zombie, infect the player
if s_VictomTeam == TeamId.Team1 and s_AttackerTeam == TeamId.Team2 then
self:InfectPlayer(p_Victom)
end
end
-- This should only be called on player killed
function ZombiesTeamManager:InfectPlayer(p_Player)
-- Ensure that our player is valid
if p_Player == nil then
return
end
-- Change the players team
p_Player.teamId = TeamId.Team2
-- Send out notification to all players
ChatManager:SendMessage("Human " .. p_Player.name .. " has been infected!")
end
-- Event for when players spawn/respawn
function ZombiesTeamManager:OnPlayerRespawn(p_Player)
-- if p_Player == nil then
-- return
-- end
-- local s_PlayerTeam = p_Player.teamId
-- -- If the player that spawned is on the zombies team, give them extra health
-- if s_PlayerTeam == TeamId.Team2 then
-- local s_Soldier = p_Player.soldier
-- if s_Soldier == nil then
-- return
-- end
-- s_Soldier.maxHealth = 200
-- --s_Soldier.physicsEnabled = false
-- end
end
-- This function goes through and moves all players to the human side (Team1)
function ZombiesTeamManager:InitTeams()
-- Get all of the players
s_Players = PlayerManager:GetPlayers()
for s_Index, s_Player in ipairs(s_Players) do
-- If we are not on the human team kill
if s_Player.teamId ~= TeamId.Team1 then
-- Attempt to kill the player
if s_Player.alive ~= true then
goto continue
end
if s_Player.soldier ~= nil then
print("init kill")
s_Player.soldier:Kill(false)
end
::continue::
-- Set the player to the human team
s_Player.teamId = TeamId.Team1
end
end
end
function ZombiesTeamManager:SelectZombie()
s_PlayerCount = PlayerManager:GetPlayerCount()
if s_PlayerCount == 0 then
return
end
s_SelectedIndex = math.random(0, s_PlayerCount - 1)
--print("select 1")
s_Players = PlayerManager:GetPlayers()
--print("select 2")
for s_Index, s_Player in ipairs(s_Players) do
-- If we do not have our lucky winner, skip
if s_Index ~= s_SelectedIndex then
goto zcontinue
end
-- If the player is already dead, just change the team
if s_Player.alive ~= true then
goto changeteams
end
-- Get the soldier if they are alive
s_Soldier = s_Player.soldier
if s_Soldier ~= nil then
print("killing player " .. s_Player.name .. " to become zombie")
s_Soldier:Kill(false)
end
::changeteams::
-- Switch the team to zombies
s_Player.teamId = TeamId.Team2
-- Echo out our message
ChatManager:SendMessage("WATCH OUT " .. s_Player.name .. " IS THE NEW ZOMBIE! RUN!")
::zcontinue::
end
end
return ZombiesTeamManager |
addEvent("saveKilometer",true)
addEventHandler("saveKilometer",getRootElement(),saveKilometer)
addEvent("loadVehiclesKilometer",true)
addEventHandler("loadVehiclesKilometer",getRootElement(),loadVehiclesKilometer) |
-- Zorks round texture animation testmod
local function createme(h,tex,circle,x,y,size,dur,degree)
local t = h:CreateTexture(nil,"BACKGROUND",nil,-8)
t:SetPoint("CENTER",x,y)
t:SetSize(size,size)
t:SetBlendMode("ADD")
if circle then
SetPortraitToTexture(t, "Interface\\AddOns\\rGalaxy\\"..tex)
else
t:SetTexture("Interface\\AddOns\\rGalaxy\\"..tex)
end
if dur then
local ag = t:CreateAnimationGroup()
local anim = ag:CreateAnimation("Rotation")
anim:SetDegrees(degree)
anim:SetDuration(dur)
ag:Play()
ag:SetLooping("REPEAT")
end
return t
end
local h = CreateFrame("Frame",nil,UIParent)
h:SetPoint("CENTER",0,0)
h:SetSize(64,64)
local a = createme(h,"bob",true,70,70,128)
local b = createme(h,"bob",false,-70,70,128)
local c = createme(h,"bob",true,70,-70,128,15,360)
local d = createme(h,"bob",false,-70,-70,128,15,360)
local e = createme(h,"bob",true,70,-140,128,15,-360)
local f = createme(h,"bob",false,-70,-140,128,15,-360)
local g = createme(h,"galaxy",true,210,70,128,15,360) |
object_tangible_loot_creature_loot_collections_broken_lightsaber_hilt_003 = object_tangible_loot_creature_loot_collections_shared_broken_lightsaber_hilt_003:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_broken_lightsaber_hilt_003, "object/tangible/loot/creature/loot/collections/broken_lightsaber_hilt_003.iff")
|
local replicatedStorage = game:GetService("ReplicatedStorage")
local Events = replicatedStorage.Events
local eventModule = require(script.EventModule)
Events.playerEvent.OnServerEvent:Connect(function(player, Type)
if Type == "Archway" then
eventModule.Archway(player)
end
if Type == "VoidSphere" then
eventModule.Void(player)
end
if Type == "FireBall" then
eventModule.FireBall(player)
end
if Type == "JumpKick" then
eventModule.JumpKick(player)
end
end) |
local npcConfig = require "config.npcConfig"
local ItemModule = require "module.ItemModule"
local IconFrameHelper = require "utils.IconFrameHelper"
local playerModule = require "module.playerModule"
local QuestModule = require "module.QuestModule"
local NpcChatMoudle = require "module.NpcChatMoudle"
local UserDefault = require "utils.UserDefault"
local View = {}
function View:Start(data)
self.view = SGK.UIReference.Setup(self.gameObject);
local init_obj = CS.UnityEngine.GameObject.Instantiate(SGK.ResourcesManager.Load("prefabs/base/CurrencyChat.prefab"), self.view.transform)
self.rewardQuest_topic_id=nil
self.friendCfg=data.data
local relation = StringSplit(self.friendCfg.quest_up,"|")
self.firstStageQuest = tonumber(relation[2])
self.npcCfg=data.npcCfg
self:initData()
print("zoe npcChat",self.firstStageQuest,sprinttb(relation))
self:loadChatRecord(true)
self:reappearChat(self.view.chat.ScrollView.Viewport.Content.ChatObj.gameObject,self.view.chat.ScrollView.Viewport.Content.transform)
self:init()
--NpcChatMoudle.GetNpcRelation(self.npcCfg.npc_id)
end
function View:initData()
self.npcTopicCfg = npcConfig.GetnpcTopic()
self.npcDialogCfg = npcConfig.GetnpcDialog()
self.relation_value = ItemModule.GetItemCount(self.friendCfg.arguments_item_id)
end
function View:loadChatRecord(bool)
local allNPC_Chat_Record = UserDefault.Load("NPC_Chat_Record",true)
--UserDefault.Clear()
if not allNPC_Chat_Record[self.npcCfg.npc_id] then
allNPC_Chat_Record[self.npcCfg.npc_id]={}
--print("zoe111111111")
UserDefault.Save()
end
self.NPC_Chat_Record = allNPC_Chat_Record[self.npcCfg.npc_id]
--print("zoe查看记录长度",#self.NPC_Chat_Record)
if #self.NPC_Chat_Record > 0 then
print("zoe查看记录",sprinttb(self.NPC_Chat_Record))
end
if bool then
if #self.NPC_Chat_Record == 0 or self.NPC_Chat_Record[#self.NPC_Chat_Record].isOver then
self.view.chooseItem.gameObject:SetActive(true)
self.view.chatItem.gameObject:SetActive(false)
else
self.view.chooseItem.gameObject:SetActive(false)
self.view.chatItem.gameObject:SetActive(true)
end
end
end
function View:reappearChat(tempObj,trans)
for i=1,#self.NPC_Chat_Record do
--print("2222222",i,sprinttb(self.NPC_Chat_Record[i]))
if self.NPC_Chat_Record[i].right then
local obj=SGK.UIReference.Setup(CS.UnityEngine.GameObject.Instantiate(tempObj,trans))
obj.Right.Content.bg.desc[CS.InlineText].text = self.npcDialogCfg[self.NPC_Chat_Record[i].storyId]["reply"..self.NPC_Chat_Record[i].replyId]
--IconFrameHelper.Hero({pid = playerModule.Get().id},obj.Right.icon)
--print("PLayer",sprinttb(module.playerModule.Get()))
obj.Right.icon.transform.localScale=UnityEngine.Vector3(0.8,0.8,1)
IconFrameHelper.Create(obj.Right.icon,{pid = playerModule.GetSelfID()})
obj.Right.name[UI.Text].text=playerModule.Get().name
obj.Right.gameObject:SetActive(true)
obj.gameObject:SetActive(true)
end
if self.NPC_Chat_Record[i].left then
local obj=SGK.UIReference.Setup(CS.UnityEngine.GameObject.Instantiate(tempObj,trans))
obj.Left.Content.bg.desc[CS.InlineText].text = self.npcDialogCfg[self.NPC_Chat_Record[i].storyId].text
local npc_cfg = self.npcCfg
obj.Left.icon[UI.Image]:LoadSprite("icon/"..npc_cfg.icon)
obj.Left.icon.transform.localScale=UnityEngine.Vector3(1.05,1.05,1)
obj.Left.name[UI.Text].text=npc_cfg.name
obj.Left.gameObject:SetActive(true)
obj.gameObject:SetActive(true)
end
if i == #self.NPC_Chat_Record then
if self.NPC_Chat_Record[i].left then
self.rewardQuest_topic_id = self.NPC_Chat_Record[i].rewardId
self:UpPlayerItem(self.NPC_Chat_Record[i].storyId)
end
if self.NPC_Chat_Record[i].right then
for i=1,3 do
self.view.chatItem["item"..i].gameObject:SetActive(false)
self.view.chatItem["item"..i][UnityEngine.CanvasGroup].alpha=0
end
local next_story_id = self.npcDialogCfg[self.NPC_Chat_Record[i].storyId]["reply_npc"..self.NPC_Chat_Record[i].replyId]
self.rewardQuest_topic_id = self.NPC_Chat_Record[i].rewardId
if next_story_id == 0 then
self:finishChat()
else
self.view.top.status[UI.Text].text="对方正在输入中..."
self.view.chatItem["item4"].gameObject:SetActive(true)
self.view.chatItem["item4"][UnityEngine.CanvasGroup]:DOFade(1,0.4):SetDelay(0.1):OnComplete(function ()
self.view.chatItem["item4"][UnityEngine.CanvasGroup]:DOFade(1,0.1):SetDelay(1.7):OnComplete(function ()
self:UpNpcDialog(tempObj,next_story_id)
end)
end)
end
end
end
end
end
function View:init()
self.view = SGK.UIReference.Setup(self.gameObject);
self.view.top.status[UI.Text].text=self.npcCfg.name
for i=1,4 do
local _npcTopicCfg = self.npcTopicCfg[self.npcCfg.npc_id][i]
local last_npcTopicCfg = self.npcTopicCfg[self.npcCfg.npc_id][i-1]
--print(i,sprinttb(_npcTopicCfg))
local npcTopicCfg = nil
-- for k,v in pairs(_npcTopicCfg) do
-- if not module.QuestModule.Get(v.reward_quest) or module.QuestModule.Get(v.reward_quest).status == 0 then
-- npcTopicCfg = v
-- break
-- end
-- end
-- local checkFlag = true
-- if not npcTopicCfg or npcTopicCfg.story_begin == 0 then
-- checkFlag = false
npcTopicCfg = self.npcTopicCfg[self.npcCfg.npc_id][i][1]
-- end
--print(i,sprinttb(npcTopicCfg))
local _view=self.view.chooseItem["item"..i]
_view.Text[UI.Text].text=npcTopicCfg.topic
local onClickFlag = true
if self.relation_value >= npcTopicCfg.condition then
if last_npcTopicCfg and #last_npcTopicCfg > 0 and QuestModule.Get(last_npcTopicCfg[#last_npcTopicCfg].reward_quest) and QuestModule.Get(last_npcTopicCfg[#last_npcTopicCfg].reward_quest).status == 1 then
_view.mask.gameObject:SetActive(false)
else
if i ~= 1 then
_view.mask.Text[UI.Text].text="<color=#FFC300FF>上个话题未完成</color>"
_view.mask.gameObject:SetActive(true)
onClickFlag =false
end
end
if onClickFlag then
CS.UGUIClickEventListener.Get(self.view.chooseItem["item"..i].gameObject).onClick = function ()
if #_npcTopicCfg > 0 and _npcTopicCfg[1].story_begin ~= 0 then
-- self.rewardQuest_topic_id = npcTopicCfg.reward_quest
-- self.view.chooseItem.gameObject:SetActive(false)
-- self:UpPlayerDialog(self.view.chat.ScrollView.Viewport.Content.ChatObj.gameObject,npcTopicCfg.story_begin,1)
-- self.view.chatItem.gameObject:SetActive(true)
self.view.chooseItem.gameObject:SetActive(false)
self:UpLittleTopic(_npcTopicCfg)
self.view.littleTopic.gameObject:SetActive(true)
else
showDlgError(nil,"暂未开放")
end
end
end
else
--_view.Text.gameObject:SetActive(false)
_view.mask.Text[UI.Text].text="<color=#FFFFFFFF>好感度"..npcTopicCfg.condition.."解锁</color>"
_view.mask.gameObject:SetActive(true)
end
end
local stageNum = module.ItemModule.GetItemCount(self.friendCfg.stage_item)
local relation = StringSplit(self.friendCfg.qinmi_max,"|")
local relation_desc = StringSplit(self.friendCfg.qinmi_name,"|")
local relation_value = ItemModule.GetItemCount(self.friendCfg.arguments_item_id)
self.view.top.friendship[CS.UGUISpriteSelector].index = stageNum
local relation_Next_value = relation[stageNum+2] or "max"
if relation_Next_value == "max" then
self.view.top.value[UI.Text].text = relation_Next_value
self.view.top.Scrollbar[UI.Scrollbar].size = 1
else
self.view.top.value[UI.Text].text = relation_value.."/"..tonumber(relation_Next_value)
if relation_value > tonumber(relation_Next_value) then
self.view.top.Scrollbar[UI.Scrollbar].size = 1
else
self.view.top.Scrollbar[UI.Scrollbar].size = relation_value/math.floor(relation_Next_value)
end
end
end
function View:UpLittleTopic(_npcTopicCfg)
CS.UGUIClickEventListener.Get(self.view.littleTopic.back.gameObject).onClick = function ()
self.view.chooseItem.gameObject:SetActive(true)
self.view.littleTopic.gameObject:SetActive(false)
end
--print("xxxxxxxxx",sprinttb(_npcTopicCfg))
self.view.littleTopic.ScrollView[CS.UIMultiScroller].RefreshIconCallback = function (go,idx)
local obj = CS.SGK.UIReference.Setup(go)
local onClickFlag = true
local npcTopicCfg = _npcTopicCfg[(idx+1)]
local LastNpcTopicCfg = _npcTopicCfg[(idx)]
obj.Text[UI.Text].text = _npcTopicCfg[(idx+1)].topic_small
--print(sprinttb(QuestModule.Get(npcTopicCfg.reward_quest)))
if LastNpcTopicCfg and QuestModule.Get(LastNpcTopicCfg.reward_quest) and QuestModule.Get(LastNpcTopicCfg.reward_quest).status == 1 then
if QuestModule.Get(npcTopicCfg.reward_quest) and QuestModule.Get(npcTopicCfg.reward_quest).status == 1 then
obj.mask:SetActive(true)
obj.mask.read:SetActive(true)
obj.mask.Text:SetActive(false)
else
obj.mask:SetActive(false)
end
else
if idx == 0 then
if QuestModule.Get(npcTopicCfg.reward_quest) and QuestModule.Get(npcTopicCfg.reward_quest).status == 1 then
obj.mask:SetActive(true)
obj.mask.read:SetActive(true)
obj.mask.Text:SetActive(false)
else
obj.mask:SetActive(false)
end
else
obj.mask:SetActive(true)
obj.mask.read:SetActive(false)
obj.mask.Text:SetActive(true)
onClickFlag = false
end
end
if onClickFlag then
CS.UGUIClickEventListener.Get(obj.gameObject).onClick = function ()
if not QuestModule.Get(npcTopicCfg.reward_quest) or QuestModule.Get(npcTopicCfg.reward_quest).status == 0 then
self.rewardQuest_topic_id = npcTopicCfg.reward_quest
self.view.littleTopic.gameObject:SetActive(false)
self:UpPlayerDialog(self.view.chat.ScrollView.Viewport.Content.ChatObj.gameObject,npcTopicCfg.story_begin,1)
self.view.chatItem.gameObject:SetActive(true)
else
self:MoveToTopic(npcTopicCfg.story_begin)
end
end
end
obj.gameObject:SetActive(true)
end
self.view.littleTopic.ScrollView[CS.UIMultiScroller].DataCount = #_npcTopicCfg
end
function View:MoveToTopic(story_id)
self:loadChatRecord()
local index = 0
for i=1,#self.NPC_Chat_Record do
if self.NPC_Chat_Record[i].storyId == story_id then
index = i
break
end
end
local height = self.view.chat.ScrollView.Viewport.Content[UnityEngine.RectTransform].sizeDelta.y
local targetHeight = self.view.chat.ScrollView.Viewport.Content.gameObject.transform:GetChild(index):GetComponent(typeof(UnityEngine.RectTransform)).anchoredPosition.y
local viewHight = self.view.chat.ScrollView.Viewport[UnityEngine.RectTransform].rect.size.y
self.view.chat.ScrollView.Viewport.Content.transform:DOLocalMoveY(viewHight - height - targetHeight, 0.3)
--local value = (height - math.abs(targetHeight))/height
--local _value = self.view.chat.ScrollView.ScrollbarVertical[CS.UnityEngine.UI.Scrollbar].value
-- for i=1,10 do
-- SGK.Action.DelayTime.Create(0.015*i):OnComplete(function()
-- self.view.chat.ScrollView.ScrollbarVertical[CS.UnityEngine.UI.Scrollbar].value = (value/10)*i
-- end)
-- end
end
--IconFrameHelper.UpdateHero({pid = pid,sex = _PlayerData.Sex,headFrame = _PlayerData.HeadFrame},PLayerIcon)
function View:UpPlayerDialog(tempObj,story_id,reply_id,desc,role_id)
local obj=SGK.UIReference.Setup(CS.UnityEngine.GameObject.Instantiate(tempObj,self.view.chat.ScrollView.Viewport.Content.transform))
local next_story_id = nil
if reply_id ~= nil then
--print("zoe npcChat",sprinttb(self.npcDialogCfg[story_id]))
obj.Right.Content.bg.desc[CS.InlineText].text = self.npcDialogCfg[story_id]["reply"..reply_id]
next_story_id = self.npcDialogCfg[story_id]["reply_npc"..reply_id]
end
obj.Right.icon.transform.localScale=UnityEngine.Vector3(0.8,0.8,1)
IconFrameHelper.Create(obj.Right.icon,{pid = playerModule.GetSelfID()})
obj.Right.name[UI.Text].text=playerModule.Get().name
obj.Right.gameObject:SetActive(true)
obj.gameObject:SetActive(true)
self.view.chat.ScrollView.ScrollbarVertical[CS.UnityEngine.UI.Scrollbar].value = 0
for i=1,3 do
self.view.chatItem["item"..i].gameObject:SetActive(false)
self.view.chatItem["item"..i][UnityEngine.CanvasGroup].alpha=0
end
self.NPC_Chat_Record[#self.NPC_Chat_Record+1]={storyId = story_id,left = false,right = true,replyId = reply_id,isOver = false,rewardId = self.rewardQuest_topic_id}
UserDefault.Save()
if next_story_id == 0 then
self:finishChat()
else
self.view.top.status[UI.Text].text="对方正在输入中..."
self.view.chatItem["item4"].gameObject:SetActive(true)
self.view.chatItem["item4"][UnityEngine.CanvasGroup]:DOFade(1,0.4):SetDelay(0.1):OnComplete(function ()
self.view.chatItem["item4"][UnityEngine.CanvasGroup]:DOFade(1,0.1):SetDelay(1.7):OnComplete(function ()
self:UpNpcDialog(tempObj,next_story_id)
end)
end)
end
-- coroutine.resume(coroutine.create(function()
-- Sleep(2.0)
-- self:UpNpcDialog(tempObj,next_story_id)
-- end))
end
function View:UpNpcDialog(tempObj,story_id,role_id)
self.view.top.status[UI.Text].text=self.npcCfg.name
self.view.chatItem["item4"].gameObject:SetActive(false)
self.view.chatItem["item4"][UnityEngine.CanvasGroup].alpha=0
local obj=SGK.UIReference.Setup(CS.UnityEngine.GameObject.Instantiate(tempObj,self.view.chat.ScrollView.Viewport.Content.transform))
obj.Left.Content.bg.desc[CS.InlineText].text = self.npcDialogCfg[story_id].text
local npc_cfg = self.npcCfg
obj.Left.icon[UI.Image]:LoadSprite("icon/"..npc_cfg.icon)
obj.Left.icon.transform.localScale=UnityEngine.Vector3(1.05,1.05,1)
obj.Left.name[UI.Text].text=npc_cfg.name
obj.Left.gameObject:SetActive(true)
obj.gameObject:SetActive(true)
self.view.chat.ScrollView.ScrollbarVertical[CS.UnityEngine.UI.Scrollbar].value = 0
self.NPC_Chat_Record[#self.NPC_Chat_Record+1]={storyId = story_id,left = true,right = false,replyId = 0,isOver = false,rewardId = self.rewardQuest_topic_id}
UserDefault.Save()
self:UpPlayerItem(story_id)
end
function View:UpPlayerItem(story_id)
--print("zoezoe",self.rewardQuest_topic_id,sprinttb(self.npcDialogCfg[story_id]))
local CompaleCount = 0
for i=1,3 do
if self.npcDialogCfg[story_id]["reply"..i] ~= "" then
self.view.chatItem["item"..i].Text[UI.Text].text =self.npcDialogCfg[story_id]["reply"..i]
CS.UGUIClickEventListener.Get(self.view.chatItem["item"..i].gameObject).onClick = function ()
self:UpPlayerDialog(self.view.chat.ScrollView.Viewport.Content.ChatObj.gameObject,story_id,i)
end
self.view.chatItem["item"..i].gameObject:SetActive(true)
else
self.view.chatItem["item"..i].gameObject:SetActive(false)
CompaleCount=CompaleCount+1
end
end
if CompaleCount == 0 then
for i=1,3 do
self.view.chatItem["item"..i][UnityEngine.RectTransform].sizeDelta=UnityEngine.Vector2(687.1,93)
self.view.chatItem["item"..i][UnityEngine.CanvasGroup]:DOFade(1,0.5):SetDelay(0.2)
end
elseif CompaleCount == 1 then
for i=1,2 do
self.view.chatItem["item"..i][UnityEngine.RectTransform].sizeDelta=UnityEngine.Vector2(687.1,113)
self.view.chatItem["item"..i][UnityEngine.CanvasGroup]:DOFade(1,0.5):SetDelay(0.2)
end
elseif CompaleCount == 2 then
self.view.chatItem["item"..1][UnityEngine.RectTransform].sizeDelta=UnityEngine.Vector2(687.1,128)
self.view.chatItem["item"..1][UnityEngine.CanvasGroup]:DOFade(1,0.5):SetDelay(0.2)
elseif CompaleCount == 3 then
self:finishChat()
end
end
function View:finishChat()
if not self.NPC_Chat_Record[#self.NPC_Chat_Record].isOver then
--print("zoezoe",self.rewardQuest_topic_id)
QuestModule.Accept(self.rewardQuest_topic_id)
if QuestModule.Get(self.rewardQuest_topic_id) and QuestModule.Get(self.rewardQuest_topic_id).status == 0 then
QuestModule.Finish(self.rewardQuest_topic_id)
end
self.NPC_Chat_Record[#self.NPC_Chat_Record].isOver = true
UserDefault.Save()
--QuestModule.Finish(self.npcTopicCfg[self.npcCfg.npc_id][self.rewardQuest_topic_id].reward_quest)
--showDlgError(nil, "对话完成")
end
end
-- function View:Update()
-- print(self.view.chat.ScrollView.Viewport.Content.gameObject.transform:GetChild(13).position)
-- end
function View:OnDestory()
--print("zoe npcChat界面destory")
end
function View:listEvent()
return {
"QUEST_INFO_CHANGE",
}
end
function View:onEvent(event,data)
if event == "QUEST_INFO_CHANGE" then
print("zoe npcChat QUEST_INFO_CHANGE",sprinttb(data))
if data.id == self.rewardQuest_topic_id then
if data.status == 1 then
self:initData()
self:loadChatRecord(true)
self:init()
else
QuestModule.Finish(self.rewardQuest_topic_id)
end
end
if data and data.id == self.firstStageQuest then
if data.status == 1 then
self:initData()
self:init()
end
end
end
end
return View; |
addEventHandler("onClientResourceStart",resourceRoot,
function ()
triggerServerEvent("removeText",localPlayer)
end
)
|
----------------------------------------------------------------
-- Copyright (c) 2012 Klei Entertainment Inc.
-- All Rights Reserved.
-- SPY SOCIETY.
----------------------------------------------------------------
local array = include( "modules/array" )
local util = include( "modules/util" )
local simdefs = include( "sim/simdefs" )
local simquery = include( "sim/simquery" )
----------------------------------------------------------------
-- Level script
local level_events =
{
EV_UI_INITIALIZED = 1,
EV_UNIT_SELECTED = 2,
EV_HUD_MAINFRAME_TOGGLE= 4,
EV_HUD_CLICK_BUTTON = 6,
EV_CLOSE_SHOP_UI = 8,
EV_CLOSE_LOOT_UI = 9,
EV_FINAL_ROOM_INTERRUPT = 10,
EV_TALKING_HEAD_CLOSED = 11,
}
local script_hook = class()
function script_hook:init( script, name, hookFn, noSkip )
self.script = script
self.name = name
self.noSkip = noSkip
self.waitEvents = {}
self.waitTriggers = {}
self.hookFn = hookFn -- Merely for later identification
self.thread = coroutine.create( hookFn )
end
function script_hook:addHook( hookFn, noSkip, ... )
self.hookCount = (self.hookCount or 0) + 1
local name = string.format( "%s [%d]", self.name, self.hookCount )
return self.script:addHook( name, hookFn, noSkip, ... )
end
function script_hook:removeHook( hookFn )
for i, hook in ipairs( self.script.hooks ) do
if hook.hookFn == hookFn then
self.script:removeHook( hook )
break
end
end
end
function script_hook:removeAllHooks( exceptHook )
if exceptHook then
array.removeElement( self.script.hooks, exceptHook )
end
while #self.script.hooks > 0 do
self.script:removeHook( self.script.hooks[1] )
end
if exceptHook then
table.insert( self.script.hooks, exceptHook )
end
end
function script_hook:queue( event )
self.script:queue( event )
end
function script_hook:clearQueue( skip )
self.script:clearQueue( skip )
end
function script_hook:checkpoint()
self.script.sim:dispatchEvent( simdefs.EV_CHECKPOINT )
local retryCount = self.script.sim:getTags().retries
if retryCount > 0 then
-- Retrying checkpoint, automatically insert a fadeIn event.
self:queue( { type="fadeIn" } )
self:waitFrames( 60 )
end
self.script.sim:getTags().retries = 0
-- Return retryCount in case script cares to handle it as a special case.
return retryCount
end
function script_hook:restore()
self:queue( { type="restoreCheckpoint" } )
-- Once a restore is pushed, lock any changes so it can't be undone inadvertantly.
self.script.lockQueue = true
end
function script_hook:waitFrames( frameCount )
-- This is a BLOCKING delay.
assert( type(frameCount) == "number" )
self.script.sim:dispatchEvent( simdefs.EV_WAIT_DELAY, frameCount )
end
function script_hook:waitFor( ... )
-- Clear old waits.
for triggerType, v in pairs( self.waitTriggers ) do
self.script.sim:removeTrigger( triggerType, self )
end
self.waitEvents = { ... }
self.waitTriggers = { }
if #self.waitEvents > 0 then
for _, waitEv in ipairs( self.waitEvents ) do
if waitEv.action then
self.waitTriggers[ simdefs.TRG_ACTION ] = waitEv.priority or 0
elseif waitEv.trigger then
self.waitTriggers[ waitEv.trigger ] = waitEv.priority or 0
elseif waitEv.uiEvent then
self.waitTriggers[ simdefs.TRG_UI_ACTION ] = waitEv.priority or 0
else
assert( false, util.stringize( waitEv ))
end
end
-- Add hook as handler to requisite wait triggers (a post-step because we need to avoid dupes)
for triggerType, priority in pairs( self.waitTriggers ) do
local trigger = self.script.sim:addTrigger( triggerType, self )
if priority ~= 0 then
trigger.priority = priority
end
end
-- When this hook is triggered by the UI event in question we will resume.
return coroutine.yield()
end
end
function script_hook:onTrigger( sim, triggerType, triggerData )
--simlog( simdefs.LOG_TUTORIAL, "onTrigger( %d ) == %s", triggerType, util.stringize( triggerData, 1 ))
local abort = nil
for _, waitEv in ipairs( self.waitEvents ) do
if triggerType == simdefs.TRG_ACTION then
if (waitEv.action == triggerData.ClassType or waitEv.action == "") and waitEv.pre == triggerData.pre then
if waitEv.fn == nil then
abort = (self:resumeHook( waitEv, triggerData ) == false)
break
else
local result = { waitEv.fn( sim, unpack(triggerData) ) }
if result[1] then
abort = (self:resumeHook( waitEv, unpack( result )) == false)
break
end
end
end
elseif triggerType == simdefs.TRG_UI_ACTION and waitEv.uiEvent == triggerData.uiEvent then
self:resumeHook( waitEv, triggerData.eventData )
elseif triggerType == waitEv.trigger then
if waitEv.fn == nil then
abort = (self:resumeHook( waitEv, triggerData ) == false)
break
else
local result = { waitEv.fn( sim, triggerData ) }
if result[1] then
abort = (self:resumeHook( waitEv, unpack( result )) == false)
break
end
end
end
end
if triggerData and abort then
triggerData.abort = true -- It's up to the trigger source to handle what this means.
end
end
function script_hook:resumeHook( ... )
self:waitFor( nil )
local args = { ... }
local ok, result
repeat
ok, result = coroutine.resume( self.thread, unpack(args) )
assert( ok, tostring(result) .. "\n" .. tostring(debug.traceback( self.thread ) ))
if self.thread == nil then
break -- Resuming actually caused us to be destroyed() already.
elseif coroutine.status( self.thread ) == "dead" then
self.script:removeHook( self )
return result -- if result == false, the hook wants the sim to 'abort' whatever it is currently doing.
elseif result then
-- If there's a return value, it's a simevent simply needing to be dispatched from the main sim coroutine.
args = { self.script.sim:dispatchEvent( result.eventType, result.eventData ) }
end
until not ok or result == nil
end
function script_hook:onScriptEvent( game, eventType, eventData )
--simlog( simdefs.LOG_TUTORIAL, "onScriptEvent( %d ) == %s", eventType, util.stringize( eventData, 1 ))
for i, waitEv in ipairs( self.waitEvents ) do
if waitEv.uiEvent == eventType and (waitEv.fn == nil or waitEv.fn( self.script.sim, eventData )) then
-- This is the UI event we're waiting for! Encapsulate this in a trigger action, which will resume the hook.
game:doAction( "triggerAction", simdefs.TRG_UI_ACTION, { uiEvent = eventType, eventData = eventData } )
break
end
end
end
function script_hook:destroy()
self:waitFor()
self.thread = nil
end
-----------------------------------------------------------------------------------------------
--
local script_mgr = class()
function script_mgr:init( sim )
self.sim = sim
self.hooks = {}
self.scriptEvents = {}
self.eventQueue = {}
self.scripts = {}
end
function script_mgr:loadScript( filename, ... )
local res, script = pcall( reinclude, filename )
if res then
table.insert( self.scripts, script( self, self.sim, ... ))
else
simlog( "LEVEL SCRIPT: '%s'\n%s", filename, script )
end
end
function script_mgr:destroy()
self.scripts = nil
self:clearSpeech()
while #self.hooks > 0 do
self:removeHook( self.hooks[1] )
end
end
function script_mgr:queue( event )
if self.lockQueue then
return
end
assert( event )
table.insert( self.eventQueue, event )
end
function script_mgr:clearQueue( skip )
if self.lockQueue then
return
end
util.tclear( self.eventQueue )
if skip then
-- In addition to clearing the queue, this skips/aborts whatever is currently being processed.
self.sim:dispatchEvent( simdefs.EV_CLEAR_QUEUE )
end
end
function script_mgr:getQueue()
return self.eventQueue
end
function script_mgr:queueScriptEvent( eventType, eventData )
assert( eventType )
table.insert( self.scriptEvents, eventType )
table.insert( self.scriptEvents, eventData or false ) -- false is just a dummy value so that this remains an array without nil entries
end
function script_mgr:dispatchScriptEvents( game )
assert( not game:isReplaying() )
while #self.scriptEvents > 0 do
local eventType = table.remove( self.scriptEvents, 1 )
local eventData = table.remove( self.scriptEvents, 1 )
for _, hook in ipairs( self.hooks ) do
hook:onScriptEvent( game, eventType, eventData )
end
end
end
function script_mgr:addHook( name, hookFn, noSkip, ... )
local hook = script_hook( self, name, hookFn, noSkip )
table.insert( self.hooks, hook )
hook:resumeHook( hook, self.sim, ... )
return hook
end
function script_mgr:removeHook( hook )
hook:destroy()
array.removeElement( self.hooks, hook )
end
----------------------------------------------------------------
-- Level loader
local function loadLevel( params )
local filename = "sim/"..params.levelFile
local lvldata = include( filename )
assert(lvldata)
package.loaded[ filename ] = nil -- Do not cache this lua file.
if lvldata.onLoad then
lvldata:onLoad( params )
end
return lvldata
end
return util.extend( level_events )
{
script_hook = script_hook,
script_mgr = script_mgr,
loadLevel = loadLevel,
}
|
-- ===== ===== ===== ===== =====
-- Copyright (c) 2017 Lukas Grünwald
-- License MIT License
-- ===== ===== ===== ===== =====
require( "pgbase" )
require( "pgdebug" )
require( "pgevents" )
require( "pgcommands" )
require( "pgbasedefinitions" )
require( "pgstatemachine" )
require( "pgstorymode" )
require( "pgspawnunits" )
-- libraries:
require( "libErrorFunctions" )
require( "libDebugFunctions" )
require( "libPGGenericFunctionLibrary" )
-- new classes:
require( "cGalacticConquest" )
function Definitions()
StoryModeEvents = { InitialiseGalacticConquestEvent = InitialiseGalacticConquest }
-- Kad 24/06/2017 14:04:31 - Required globals:
cGCThread_EvaluateOwner = nil
cGCThread_EvaluateOwner_TimeStamp = nil
cGCThread_RefreshGUI = nil
cGCThread_RefreshGUI_TimeStamp = nil
cGCThread_FiscalUpdate = nil
cGCThread_FiscalUpdate_TimeStamp = nil
cGCThread_EvaluateFleets = nil
cGCThread_EvaluateFleets_TimeStamp = nil
cGCThread_ServeEvents = { }
cGCThread_ServeEvents_TimeStamp = { }
cGCThread_ThreadListener = nil
cGCThread_ThreadListener_TimeStamp = nil
GalacticConquest = nil
end
function InitialiseGalacticConquest( message )
if message == OnEnter then
GalacticConquest = cGalacticConquest.New( "SANDBOX_EQUAL_FOOTING" )
GalacticConquest:Initialise()
StartGalacticConquest()
-- DEBUGGING: Unnecessary code below:
-- GalacticConquest:FlashCapitalPlanets()
GalacticConquest:RegisterEvent( "EVENT_TYPE_SPAWNUNITS", { ReinforceStructID = "SPAWN_THRAWN", ReinforcePositionTable = { FindPlanet( "Coruscant" ), }, OwnerObject = Find_Player( "Empire" ) } )
GalacticConquest:RegisterEvent( "EVENT_TYPE_SPAWNUNITS", { ReinforceStructID = "TEST_STRUCT", ReinforcePositionTable = { FindPlanet( "Coruscant" ), FindPlanet( "Kuat" ) }, OwnerObject = Find_Player( "Empire" ), Timer = 85, } )
GalacticConquest:FlashCapitalPlanets()
local thrawnRef = Find_First_Object( "Admonitor_Star_Destroyer" )
local trawnType = GalacticConquest.ObjectManager:GetCGameObjectTypeByReference( Find_First_Object( "Admonitor_Star_Destroyer" ) )
GalacticConquest:RegisterEvent( "EVENT_TYPE_DIPLSTARTDIPLOMATICMISSION", { GameObjectTypeLUAObject = thrawnType, GameObjectReference = thrawnRef, PlanetLUAObject = GalacticConquest.Planets["Coruscant"], Timer = 28, } )
GalacticConquest:RegisterEvent( "EVENT_TYPE_PDORBITALBOMBARDMENTBEGIN", { TargetPlanet = GalacticConquest.Planets["Coruscant"], BombardingFaction = GalacticConquest.Planets["Coruscant"]:GetOwner(), Timer = 10, } )
local cPln = GalacticConquest.Planets["Coruscant"]:GetPlanetInReach( GalacticConquest.Planets["Coruscant"]:GetOwner() )
cPln:AddPlanetHighlight( "FINAL_PLANET" )
Sleep( 5.0 )
cPln:Destroy()
Sleep( 5.0 )
cPln:RemovePlanetHighlight( "FINAL_PLANET" )
-- GalacticConquest:FlashCapitalPlanets()
-- local DiplVal = GalacticConquest.Planets["Coruscant"]:GetDiplomaticRating()
-- local DipValRaw = GalacticConquest.Planets["Coruscant"]:GetCurrentDiplomaticInfluenceOwnerRaw()
-- debugFactionRawMilitaryStrength( DipValRaw, DiplVal )
-- GalacticConquest:RegisterEvent( "EVENT_TYPE_DIPLTURNPLANET", { PlanetLUAObject = GalacticConquest.Planets["Kuat"], FactionLUAObjectNewOwner = GalacticConquest.Factions["Rebel_Alliance"], Timer = 180 } )
-- Sleep(1.0)
-- DiplVal = GalacticConquest.Planets["Coruscant"]:GetDiplomaticRating()
-- DipValRaw = GalacticConquest.Planets["Coruscant"]:GetCurrentDiplomaticInfluenceOwnerRaw()
-- debugFactionRawMilitaryStrength( DipValRaw, DiplVal )
-- Sleep(1.0)
-- DiplVal = GalacticConquest.Planets["Coruscant"]:GetDiplomaticRating()
-- DipValRaw = GalacticConquest.Planets["Coruscant"]:GetCurrentDiplomaticInfluenceOwnerRaw()
-- debugFactionRawMilitaryStrength( DipValRaw, DiplVal )
-- Sleep(1.0)
-- DiplVal = GalacticConquest.Planets["Coruscant"]:GetDiplomaticRating()
-- DipValRaw = GalacticConquest.Planets["Coruscant"]:GetCurrentDiplomaticInfluenceOwnerRaw()
-- debugFactionRawMilitaryStrength( DipValRaw, DiplVal )
-- Sleep(1.0)
-- DiplVal = GalacticConquest.Planets["Coruscant"]:GetDiplomaticRating()
-- DipValRaw = GalacticConquest.Planets["Coruscant"]:GetCurrentDiplomaticInfluenceOwnerRaw()
-- debugFactionRawMilitaryStrength( DipValRaw, DiplVal )
-- Sleep(1.0)
-- Sleep(1.0)
-- GalacticConquest.Planets["Coruscant"]:TakeDamage( 8765 )
-- GalacticConquest:HighlightAllEmpirePlanets()
-- GalacticConquest:HighlightAllRebelPlanets()
-- GalacticConquest:HighlightAllUnderworldPlanets()
elseif message == OnUpdate then
elseif message == OnExit then
end
end
-- ========= ========= MAIN LOOP THREADING ========== ==========
--- Starts the GC framework in a multi-threaded environment.
-- @see cGCThreaded_EvaluateOwner
-- @see cGCThreaded_RefreshGUI
-- @see cGCThreaded_EvaluateFleets
-- @see cGCThreaded_ServeEvents
function StartGalacticConquest( )
local OwnerTick = require( "configGlobalSettings" ).gSetting_Eval_OwnerTick
local GUIRefreshTick = require( "configGlobalSettings" ).gSetting_Eval_GUIEventTick
local MaintenanceTick = require( "configGlobalSettings" ).gSetting_Global_FiscalCycle
local FleetTick = require( "configGlobalSettings" ).gSetting_Eval_FleetsTick
local EventTick = require( "configGlobalSettings" ).gSetting_EventHandlerTick
cGCThread_EvaluateOwner = Create_Thread( "cGCThreaded_EvaluateOwner", OwnerTick )
cGCThread_RefreshGUI = Create_Thread( "cGCThreaded_RefreshGUI", GUIRefreshTick )
cGCThread_FiscalUpdate = Create_Thread( "cGCThreaded_FiscalUpdate", MaintenanceTick )
cGCThread_EvaluateFleets = Create_Thread( "cGCThreaded_EvaluateFleets", FleetTick )
-- Kad 24/06/2017 14:00:54 - Creates EventHandler worker threads. They don't know about each other and the GalacticConquest keeps them completely decoupled.
local evtHndCnt = require( "configGlobalSettings").gSetting_Global_EventHandlerCount
for i = 1, evtHndCnt, 1 do
local tab = { EventTick, i }
if i > 1 then
Sleep( EventTick/evtHndCnt )
end
cGCThread_ServeEvents[i] = Create_Thread( "cGCThreaded_ServeEvents", tab )
end
local ThreadWatchdogTick = require( "configGlobalSettings" ).gSetting_Global_ThreadWatchdogTick
cGCThread_ThreadListener = Create_Thread( "cGCThreaded_ThreadListener", ThreadWatchdogTick )
end
--- Starts the owner evaluation loop.
function cGCThreaded_EvaluateOwner( newOwnerTick )
while true do
cGCThread_EvaluateOwner_TimeStamp = GetCurrentTime()
GalacticConquest:EvaluatePlanetsContested()
GalacticConquest:EvaluatePlanetOwners()
GalacticConquest:EvaluatePlanetBuildings()
Sleep( newOwnerTick )
end
end
--- Starts the fleet evaluation loop.
function cGCThreaded_EvaluateFleets( newFleetsTick )
while true do
GalacticConquest:EvaluateGalacticFleets()
Sleep( newFleetsTick )
end
end
--- Starts the selected planet evaluation.
function cGCThreaded_RefreshGUI( newSelectTick )
local guiHandler = GalacticConquest.GUIHandler
while true do
cGCThread_RefreshGUI = GetCurrentTime()
guiHandler:UpdateSelectedPlanet()
guiHandler:ProcessGUI()
Sleep( newSelectTick )
end
end
--- Starts the first event handler.
function cGCThreaded_ServeEvents( table )
local newEvtTick = table[1]
local handlerIndex = table[2]
local evtHandler = GalacticConquest.EventHandler[handlerIndex]
while true do
cGCThread_ServeEvents_TimeStamp[handlerIndex] = GetCurrentTime()
evtHandler:ServeEvents()
Sleep( newEvtTick )
end
end
--- Starts the Unit maintenance cycle.
-- Fetches the required gSettings each time; which allows for enabling/disabling the maintenance on-the-fly. (Hopefully...)
function cGCThreaded_FiscalUpdate( newEventTick )
Sleep( 0.5 ) -- Kad 23/06/2017 12:51:29 - In case of some other message that also deems itself important enough.
GalacticConquest:UpdateTimedHolochronLogs() -- Kad 23/06/2017 12:50:35 - Run once at the beginning, to initialize the holochron.
Sleep( newEventTick - 1.0 )
while true do
cGCThread_FiscalUpdate_TimeStamp = GetCurrentTime()
local PlayerMaintenance = require( "configGlobalSettings" ).gSetting_Feat_MaintenancePC
local AIMaintenance = require( "configGlobalSettings" ).gSetting_Feat_MaintenanceAI
GalacticConquest:MaintenanceCycle( PlayerMaintenance, AIMaintenance )
GalacticConquest:UpdateTimedHolochronLogs()
Sleep( newEventTick )
end
end
--- If a thread crashes, we'll restart it.
-- TODO: Fix this piece of sh*t. It's still not correctly re-spawning all workers.
function cGCThreaded_ThreadListener( newEventTick )
local maxTimeOutMult = require( "configGlobalSettings" ).gSetting_Global_ThreadWatchdogTimeoutMult
local OwnerTick = require( "configGlobalSettings" ).gSetting_Eval_OwnerTick
local GUIRefreshTick = require( "configGlobalSettings" ).gSetting_Eval_GUIEventTick
local MaintenanceTick = require( "configGlobalSettings" ).gSetting_Global_FiscalCycle
local FleetTick = require( "configGlobalSettings" ).gSetting_Eval_FleetsTick
local EventTick = require( "configGlobalSettings" ).gSetting_EventHandlerTick
while true do
local CurrTime = GetCurrentTime()
if CurrTime - cGCThread_EvaluateOwner_TimeStamp > maxTimeOutMult * OwnerTick then
ThrowThreadCrashedError( "TEXT_LUA_OBJECT_TYPE_THREAD_OWNEREVAL" )
cGCThread_EvaluateOwner = Create_Thread( "cGCThreaded_EvaluateOwner", OwnerTick )
end
CurrTime = GetCurrentTime()
if CurrTime - cGCThread_RefreshGUI_TimeStamp > maxTimeOutMult * GUIRefreshTick then
ThrowThreadCrashedError( "TEXT_LUA_OBJECT_TYPE_THREAD_GUI" )
cGCThread_RefreshGUI = Create_Thread( "cGCThreaded_RefreshGUI", GUIRefreshTick )
end
CurrTime = GetCurrentTime()
if CurrTime - cGCThread_FiscalUpdate_TimeStamp > maxTimeOutMult * MaintenanceTick then
ThrowThreadCrashedError( "TEXT_LUA_OBJECT_TYPE_THREAD_GUI" )
cGCThread_RefreshGUI = Create_Thread( "cGCThreaded_RefreshGUI", GUIRefreshTick )
end
CurrTime = GetCurrentTime()
if CurrTime - cGCThread_EvaluateFleets_TimeStamp > maxTimeOutMult * FleetTick then
ThrowThreadCrashedError( "TEXT_LUA_OBJECT_TYPE_THREAD_FLEETS" )
cGCThread_EvaluateFleets = Create_Thread( "cGCThreaded_EvaluateFleets", FleetTick )
end
for i, timeStamp in pairs( cGCThread_ServeEvents_TimeStamp ) do
CurrTime = GetCurrentTime()
if CurrTime - timeStamp > maxTimeOutMult * EventTick then
ThrowThreadCrashedError( "TEXT_LUA_OBJECT_TYPE_THREAD_EVTHANDLER" )
cGCThread_ServeEvents[i] = Create_Thread( "cGCThreaded_ServeEvents", { i, EventTick } )
end
end
Sleep( newEventTick )
end
end
|
-- stable sorting of string keys
-- keys corresponding to optional values are sorted first
-- after this, keys are sorted alphabetically
local function stableKeys(data)
local keys = {}
for key in pairs(data) do
table.insert(keys, key)
end
table.sort(keys, function(key0, key1)
local opt0 = data[key0].default ~= nil
local opt1 = data[key1].default ~= nil
if opt0 ~= opt1 then
return opt0
end
return key0 < key1
end)
return keys
end
return stableKeys
|
local iconwidth = 25;
local dragging = false;
local typename = "dice";
local sourcenode = nil;
local entries = {};
local descriptionwidget = nil;
local shadowwidget = nil;
local dieboxidentity = nil;
function onInit()
DieBoxManager.registerControl(self);
registerMenuItem("Clear dice", "erase", 4);
end
function onDragStart(button, x, y, draginfo)
dragging = false;
return onDrag(button, x, y, draginfo);
end
function onDrag(button, x, y, draginfo)
if table.getn(entries) > 0 then
if not dragging then
if table.getn(getDice()) > 0 then
draginfo.setType(typename);
draginfo.setDescription(getDescription());
draginfo.setDieList(getDice());
draginfo.setDatabaseNode(sourcenode);
dragging = true;
if PreferenceManager.getValue("interface_cleardicepoolondrag") then
resetAll();
end
return true;
end
end
end
end
function onDragEnd(draginfo)
dragging = false;
end
function onDrop(x, y, draginfo)
if PreferenceManager.getValue("interface_cleardicepoolondrag") then
Debug.console("Campaign Option interface_cleardicepoolondrag set");
end
if not dragging then
-- Dice
if draginfo.isType("dice") then
local dielist = draginfo.getDieList();
if dielist then
setDescription(draginfo.getDescription());
for k, v in pairs(dielist) do
addDie(v.type);
end
end
end
-- Chit
if draginfo.isType("chit") then
if draginfo.getCustomData() == "lightside" then
-- Upgrade PC dice or downgrade NPC dice.
if User.isHost() then
DieBoxUpgradeDowngradeButtonPress("dieboxupgradedifficulty");
else
DieBoxUpgradeDowngradeButtonPress("dieboxupgradeability");
end
elseif draginfo.getCustomData() == "darkside" then
-- Downgrade PC dice or upgrade NPC dice.
Debug.console("TODO: Darkside destiny token code.");
if User.isHost() then
DieBoxUpgradeDowngradeButtonPress("dieboxupgradeability");
else
--DieBoxUpgradeDowngradeButtonPress("dieboxupgradeability");
end
end
-- WFRP3
--if draginfo.getCustomData() == "fortune" then
-- addDie("dFortune");
--elseif draginfo.getCustomData() == "corruption" then
-- addDie("dChallenge");
--end
end
-- Action
if draginfo.isType("action") then
local dielist = draginfo.getDieList();
if dielist then
if PreferenceManager.getValue("interface_cleardicepoolondrag") then
resetAll();
end
setType(draginfo.getType());
setDescription(draginfo.getDescription());
setSourcenode(draginfo.getDatabaseNode());
for k, v in pairs(dielist) do
addDie(v.type);
end
end
end
-- Characteristic
if draginfo.isType("characteristic") then
local dielist = draginfo.getDieList();
if dielist then
if PreferenceManager.getValue("interface_cleardicepoolondrag") then
resetAll();
end
setType(draginfo.getType());
setDescription(draginfo.getDescription());
setSourcenode(draginfo.getDatabaseNode());
for k, v in pairs(dielist) do
addDie(v.type);
end
end
end
-- Skill
if draginfo.isType("skill") then
local dielist = draginfo.getDieList();
if dielist then
if PreferenceManager.getValue("interface_cleardicepoolondrag") then
resetAll();
end
setType(draginfo.getType());
setDescription(draginfo.getDescription());
setSourcenode(draginfo.getDatabaseNode());
for k, v in pairs(dielist) do
addDie(v.type);
end
end
end
-- Specialisation
if draginfo.isType("specialisation") then
local dielist = draginfo.getDieList();
if dielist then
if PreferenceManager.getValue("interface_cleardicepoolondrag") then
resetAll();
end
setType(draginfo.getType());
setDescription(draginfo.getDescription());
setSourcenode(draginfo.getDatabaseNode());
for k, v in pairs(dielist) do
addDie(v.type);
end
end
end
-- Shortcut
if draginfo.isType("shortcut") then
local class, recordname = draginfo.getShortcutData();
-- skill
if class == "skill" then
local dice = {};
local modifiers = {};
local recordnode = DB.findNode(recordname);
if recordnode then
if PreferenceManager.getValue("interface_cleardicepoolondrag") then
resetAll();
end
setType("skill");
local namenode = recordnode.getChild("name");
if namenode then
setDescription(namenode.getValue());
end
setSourcenode(recordnode);
DicePoolManager.addSkillDice(recordnode, dice, modifiers);
addDice(dice);
addDice(modifiers);
end
end
-- actions
if class == "blessing" or class == "melee" or class == "ranged" or class == "social" or class == "spell" or class == "support" then
local dice = {};
local modifiers = {};
local recordnode = DB.findNode(recordname);
if recordnode then
if PreferenceManager.getValue("interface_cleardicepoolondrag") then
resetAll();
end
setType("action");
local namenode = recordnode.getChild("name");
if namenode then
setDescription(namenode.getValue());
end
setSourcenode(recordnode);
DicePoolManager.addActionDice(recordnode, dice, modifiers);
addDice(dice);
addDice(modifiers);
end
end
-- specialisation
if class == "specialisation" then
local dice = {};
local modifiers = {};
local recordnode = DB.findNode(recordname);
if recordnode then
if PreferenceManager.getValue("interface_cleardicepoolondrag") then
resetAll();
end
setType("specialisation");
local namenode = recordnode.getChild("name");
if namenode then
setDescription(namenode.getValue());
end
setSourcenode(recordnode);
DicePoolManager.addSpecialisationDice(recordnode, dice, modifiers);
addDice(dice);
addDice(modifiers);
end
end
end
-- and return true
return true;
end
end
function addDice(dice)
if dice then
for k, v in ipairs(dice) do
addDie(v);
end
end
end
function addDie(type)
local entry = {};
entry.type = type;
entry.icon = addBitmapWidget(type .. "icon");
table.insert(entries, entry);
updateIcons();
end
function removeDie(index)
local dice = {};
for i = 1, #entries do
if i ~= index then
table.insert(dice, entries[i].type);
end
end
resetEntries();
addDice(dice);
if #entries == 0 then
resetAll();
end
end
function findDieOfType(dietype)
for k, v in pairs(getDice()) do
if v == dietype then
return k;
end
end
return 0;
end
function replaceDie(dielistindex, dietype)
local entry = {};
entry.type = dietype;
entry.icon = addBitmapWidget(dietype .. "icon");
table.insert(entries, dielistindex, entry);
removeDie(dielistindex + 1);
updateIcons();
end
function updateIcons()
if table.getn(entries) > 0 then
local position = 0 - (iconwidth * (table.getn(entries) - 1)) / 2;
for k, v in ipairs(entries) do
if v.type then
v.icon.setPosition("", position, 0);
position = position + iconwidth;
end
end
end
if shadowwidget then
shadowwidget.bringToFront();
end
if descriptionwidget then
descriptionwidget.bringToFront();
end
-- Update any remote clients viewing this diebox. Only send GM info if reveal is on.
if User.isHost() then
if not ChatManager.gmDieHide() then
DieBoxManager.sendPlayerDicepool(getDice(), getDescription());
end
else
DieBoxManager.sendPlayerDicepool(getDice(), getDescription());
end
end
function resetEntries()
if table.getn(entries) > 0 then
for k, v in ipairs(entries) do
v.icon.destroy();
end
entries = {};
end
end
function getDice()
local dielist = {};
for k, v in ipairs(entries) do
if v.type then
table.insert(dielist, v.type);
end
end
return dielist;
end
function setDice(dielist)
resetEntries();
--for k, v in ipairs(dielist) do
addDice(dielist);
--end
end
function onDoubleClick(x, y)
if table.getn(entries) > 0 then
local controlwidth, controlheight = getSize();
-- calculate the x position relative to the entries
local entrieswidth = table.getn(entries) * iconwidth;
x = x - ((controlwidth - entrieswidth) / 2 );
-- determine if the x value falls into the entries
if x > 0 and x < entrieswidth then
local index = math.floor(x / iconwidth) + 1;
removeDie(index);
end
end
end
function onMenuSelection(...)
resetAll();
end
function setDescription(description)
if description and description ~= "" then
if descriptionwidget then
descriptionwidget.setText(description);
else
descriptionwidget = addTextWidget("hotkey", description);
end
if shadowwidget then
shadowwidget.setText(description);
else
shadowwidget = addTextWidget("chatfont", description);
end
descriptionwidget.setPosition("",0,0);
shadowwidget.setPosition("",1,1);
end
end
function resetDescription()
if descriptionwidget then
descriptionwidget.destroy();
descriptionwidget = nil;
end
if shadowwidget then
shadowwidget.destroy();
shadowwidget = nil;
end
end
function getDescription()
if descriptionwidget then
return descriptionwidget.getText();
end
return "";
end
function resetAll()
resetType();
resetDescription();
resetSourcenode();
resetEntries();
resetIdentity();
-- Update any remote clients viewing this diebox
DieBoxManager.sendPlayerDicepool(getDice(), getDescription());
end
function setType(type)
typename = type;
end
function resetType()
typename = "dice";
end
function setSourcenode(node)
sourcenode = node;
end
function resetSourcenode()
sourcenode = nil;
end
function setIdentity(actoridentity)
dieboxidentity = actoridentity;
end
function resetIdentity()
dieboxidentity = nil;
end
function onDieboxButtonPress()
local sourcenodename = "";
-- type
--local type = "dice";
local type = typename;
-- description
local description = getDescription();
-- modifier
local modifier = "0";
-- source node name
if sourcenode then
sourcenodename = sourcenode.getNodeName();
end
-- gm only
--local gmonly = PreferenceManager.getValue("interface_gmonly");
local gmonly = ChatManager.gmDieHide();
-- build the dice table
local dice = getDice();
-- verify the identity - use the user if no identity has been set via setIdentity
msgidentity = dieboxidentity;
if msgidentity == "" then
msgidentity = msguser;
end
-- throw the dice
ChatManager.throwDice(type, dice, modifier, description, {sourcenodename, msgidentity, gmonly});
resetAll();
end
function DieBoxUpgradeDowngradeButtonPress(controlname)
--Debug.console("diebox.lua: DieBoxUpgradeDowngradeButtonPress(). Controlname = " .. controlname);
local dietoreplace = "";
local dietochangeto = "";
local keepupgrading = false;
if controlname == "dieboxupgradedifficulty" then
dietoreplace = "dDifficulty";
dietochangeto = "dChallenge";
keepupgrading = true;
elseif controlname == "dieboxdowngradechallenge" then
dietoreplace = "dChallenge";
dietochangeto = "dDifficulty";
elseif controlname == "dieboxupgradeability" then
dietoreplace = "dAbility";
dietochangeto = "dProficiency";
keepupgrading = true;
elseif controlname == "dieboxdowngradeproficiency" then
dietoreplace = "dProficiency";
dietochangeto = "dAbility";
end
--Debug.console("diebox.lua: DieBoxUpgradeDowngradeButtonPress(). Looking to replace " .. dietoreplace .. ", with " .. dietochangeto);
local dietoreplaceindex = findDieOfType(dietoreplace);
if dietoreplaceindex > 0 then
replaceDie(dietoreplaceindex, dietochangeto);
elseif keepupgrading then
-- No more dice found to upgrade, but this is an upagrade process that can keep going! Add another die.
addDie(dietoreplace);
end
end
function onHiddenButtonPress(control)
Debug.console("diebox.lua: onHiddenButtonPress. Button state = " .. control.getValue());
if control.getValue() == 0 then
DieBoxManager.readDicepool();
ChatManager.gmRevealDieRolls(true);
elseif control.getValue() == 1 then
DieBoxManager.sendPlayerDicepool({}, "");
ChatManager.gmRevealDieRolls(false);
end
end
|
CMD.name = 'SetFaction'
CMD.description = 'command.setfaction.description'
CMD.syntax = 'command.setfaction.syntax'
CMD.permission = 'assistant'
CMD.category = 'permission.categories.character_management'
CMD.arguments = 2
CMD.player_arg = 1
CMD.aliases = { 'plytransfer', 'charsetfaction', 'chartransfer' }
function CMD:get_description()
local factions = {}
for k, v in pairs(Factions.all()) do
table.insert(factions, k)
end
return t(self.description, { factions = table.concat(factions, ', ') })
end
function CMD:on_run(player, targets, name, strict)
local faction_table = Factions.find(name, (strict and true) or false)
if faction_table then
self:notify_staff('command.setfaction.message', {
player = get_player_name(player),
target = util.player_list_to_string(targets),
faction = faction_table.name
})
for k, v in ipairs(targets) do
v:set_faction(faction_table.faction_id)
v:notify('notification.faction_changed', { faction = faction_table.name }, faction_table.color)
end
else
player:notify('error.faction.invalid', { faction = name })
end
end
|
local item = require("../item")
local image = require("../image")
return {
name = "Get more rats",
amount = 5,
weight = 0.5,
condition = function (state)
return state.coins >= 5 and state.ratLevel >= 1
end,
description = "The sketchy trenchcoat man returns. For only $5, you may get 4 more rats to sell.",
heads = {
effectDescription = "+4 rats",
effect = function (state)
for i = 1,4 do
table.insert(state.items, item.rat)
end
return {
description = "The man hands you 4 rats. Now go and sell these rats",
image = image.rat4,
}
end
},
tails = {
effectDescription = "+1 rat (50%) ??? (50%)",
effect = function (state)
local p = love.math.random()
if p < 0.5 then
table.insert(state.items, item.rat)
return {
description = [[The man hands you 4 rats... but only 1 of them is real! You try to demand your money back, but he's already gone...]],
image = image.rat,
}
else
if state.ratLevel == 1 then
state.ratLevel = 2
return {
description = [[The man approaches you closer and whispers, "how would you like to join the rat gang?" You agree, and graduate to a level 2 rat dealer!]],
image = image.dealer
}
else
for i = 1,4 do
table.insert(state.items, item.rat)
end
return {
description = [[The man looks at you. "I thought you've moved up from dealing rats..?" He says as he hands you 4 rats anyway.]],
image = image.rat4,
}
end
end
end
},
beg = {
effectDescription = "-5 hp",
effect = function (state)
state.hp = state.hp - 5
return {
description = [[You stare at the man, unanswering. Suddenly a rat jumps out of his trenchcoat and bites you. You lose 5 hp.]],
image = image.ratAngry,
}
end
}
}
|
local t = require( "taptest" )
local ltrim = require( "ltrim" )
t( ltrim( "" ), "" )
t( ltrim( " " ), "" )
t( ltrim( " " ), "" )
t( ltrim( "a" ), "a" )
t( ltrim( " a" ), "a" )
t( ltrim( "a " ), "a " )
t( ltrim( " a " ), "a " )
t( ltrim( " a " ), "a " )
t( ltrim( " ab cd " ), "ab cd " )
t( ltrim( " \t\r\n\f\va\00b \r\t\n\f\v" ), "a\00b \r\t\n\f\v" )
t()
|
--[[ This is the module system - see README.md for discussion. ]]
local Module = {}
--[[ Creates a module of the given name.
Arguments:
* `name` - string; the full name of the module.
Returns: a new Module object; the created module.
Example:
local M = classic.module(...)
M:class("ClassA")
M:class("ClassB")
M:submodule("utils")
return M
]]
function Module:_init(name)
classic._notify(classic.events.MODULE_INIT, name)
rawset(self, '_name', name)
rawset(self, '_submodules', {})
rawset(self, '_classes', {})
rawset(self, '_moduleFunctions', {})
package.loaded[name] = self
end
--[[ Return this module's fully-qualified name as a string. ]]
function Module:name()
return self._name
end
--[[ Declares that this module contains a submodule with the given name.
Arguments:
* `name` - name of the submodule being declared.
]]
function Module:submodule(name)
if name == nil then
error("Submodule name is missing.", 2)
end
if type(name) ~= 'string' then
error("Submodule name must be a string.", 2)
end
if self._submodules[name] ~= nil then
error("Already declared submodule " .. name .. ".", 2)
end
classic._notify(classic.events.MODULE_DECLARE_SUBMODULE, self, name)
self._submodules[name] = true
end
--[[ Declare that this module contains a class with the given name.
Arguments:
* `name` - name of the class being declared.
]]
function Module:class(name)
if name == nil then
error("Class name is missing.", 2)
end
if type(name) ~= 'string' then
error("Class name must be a string.", 2)
end
if self._classes[name] ~= nil then
error("Already declared class " .. name .. ".", 2)
end
classic._notify(classic.events.MODULE_DECLARE_CLASS, self, name)
self._classes[name] = true
end
--[[ Declare that this module contains a function with the given name.
Arguments:
* `name` - name of the function being declared.
]]
function Module:moduleFunction(name)
if name == nil then
error("Function name is missing.", 2)
end
if type(name) ~= 'string' then
error("Function name must be a string.", 2)
end
if self._moduleFunctions[name] ~= nil then
error("Already declared module function " .. name .. ".", 2)
end
classic._notify(classic.events.MODULE_DECLARE_FUNCTION, self, name)
self._moduleFunctions[name] = true
end
--[[ This creates an iterator like pairs(), but which looks up each key in a
separate object.
Arguments:
* `obj` - object in which to look up keys.
* `tbl` - table from which to draw the keys.
Returns: Lua iterator over `(name, obj[name])` for each name in the keys of
`tbl`.
]]
local function keyLookupIterator(obj, tbl)
local iter = pairs(tbl)
local _, name
return function()
name, _ = iter(tbl, name)
if name then
return name, obj[name]
end
end
end
--[[ Returns an iterator over submodules of the given module.
The iterator will yield pairs of (name, submodule).
]]
function Module:submodules()
return keyLookupIterator(self, self._submodules)
end
--[[ Returns an iterator over classes in the module.
The iterator will yield pairs of (name, submodule).
]]
function Module:classes()
return keyLookupIterator(self, self._classes)
end
--[[ Returns an iterator over functions in the module.
The iterator will yield pairs of (name, function).
]]
function Module:functions()
return keyLookupIterator(self, self._moduleFunctions)
end
--[[ Lists the contents of this module.
This is a shortcut for classic.list(); see that function for details.
]]
function Module:list()
assert(self ~= nil, "Module:list() needs to be called with a ':', not a '.'!")
classic.list(self)
end
--[[ This is where we define the metamethods for Module objects.
In particular, we have special handling for indexing into a module.
]]
local Metamodule = {}
--[[ This handles looking things up in the module object.
There are several types of data that can live in a module: submodules, classes,
functions, and other data. In the first three cases, we allow them to be loaded
lazily, which can be convenient for large modules that have a lot of
dependencies.
]]
function Metamodule.__index(self, key)
if Module[key] then
return Module[key]
end
local submodules = assert(rawget(self, "_submodules"), "missing _submodules")
local classes = assert(rawget(self, "_classes"), "missing _classes")
local functions = assert(rawget(self, "_moduleFunctions"),
"missing _moduleFunctions")
if submodules[key] then
local submodule = require(self._name .. "." .. key)
if not classic.isModule(submodule) then
error(tostring(key) .. " is not a module", 2)
end
rawset(self, key, submodule)
return submodule
end
if classes[key] then
local class = classic.getClass(self._name .. "." .. key)
rawset(self, key, class)
return class
end
if functions[key] then
local func = require(self._name .. "." .. key)
if not type(func) == 'function' then
error(self._name .. "." .. tostring(key) .. " is not a function", 2)
end
rawset(self, key, func)
return func
end
error("Module " .. self._name .. " does not contain '" .. key .. "'.", 2)
end
--[[ This allows setting of functions and data in the module.
Functions are name-checked and noted in the _moduleFunctions table; other data
are allowed to pass freely.
]]
function Metamodule.__newindex(self, key, value)
if Module[key] then
error("Member name '" .. key .. "' clashes with the general classic module"
.. " function of the same name.", 2)
end
if self._moduleFunctions[key] then
error("Overwriting function " .. key .. " in module " .. self._name, 2)
end
if self._submodules[key] then
error("Overwriting submodule " .. key .. " in module " .. self._name, 2)
end
if self._classes[key] then
error("Overwriting class " .. key .. " in module " .. self._name, 2)
end
if type(value) == 'function' then
if key == nil then
error("Function name should not be nil!", 2)
end
self._moduleFunctions[key] = value
end
rawset(self, key, value)
end
--[[ String representation of the module object. ]]
function Metamodule.__tostring(self)
return "classic.module<" .. self._name .. ">"
end
--[[ This is a flag marking the object as being a classic module object, which
can then later be used for checking whether or not something is one. ]]
Metamodule.classicModule = true
--[[ We can create a new module object by calling
local my_module = Module(name)
But users should create modules via classic.module().
]]
setmetatable(Module, {
__call = function(self, namespace)
local module = {}
setmetatable(module, Metamodule)
module:_init(namespace)
return module
end
})
return Module
|
{
color0=0x113077,
color1=0xaaaaaa,
color2=0,
name="F2",
faction=8,
blueprints={
{data={name="F2_0",author="F2_0_0",color0=0x113077,color1=0xaaaaaa,
wgroup={0, 0, 2, 0}}, blocks={
{800,{0,0},0},
{834,{4.9992,15},1.5708},
{834,{4.9992,-15},-1.5708},
{855,{18.7492,10},-1.5708},
{855,{18.7492,-10},1.5708},
{815,{21.6658,28.3333},2.3562},
{815,{21.6658,-28.3333},-2.3562},
{855,{-0.0008,28.75},0},
{855,{-0.0008,-28.75},0},
{837,{24.8567,10},2.3562},
{801,{9.9992,29.9999},1.5708},
{801,{9.9992,-29.9999},-1.5708},
{834,{-5.0008,42.5},-1.5708},
{834,{-5.0008,-42.5},1.5708},
{801,{-10.0008,57.5},3.1416},
{801,{-10.0008,-57.5},3.1416},
{801,{9.9992,39.9999},3.1416},
{801,{9.9992,-39.9999},3.1416},
{801,{10,0},0},
{801,{19.9992,39.9999},-1.5708},
{801,{19.9992,-39.9999},1.5708},
{844,{37.0746,20.0044},0},
{844,{37.0746,-20.0044},0},
{834,{59.1456,15.0044},1.5708},
{834,{59.1456,-15.0044},-1.5708},
{801,{-0.0008,57.5},0},
{801,{-0.0008,-57.5},0},
{834,{-25.0008,42.5},-1.5708},
{834,{-25.0008,-42.5},1.5708},
{801,{-40.0008,37.5},0},
{801,{-40.0008,-37.5},0},
{832,{-40.0008,27.5},-1.5708},
{832,{-40.0008,-27.5},1.5708},
{849,{-30.0008,22.5},-1.5708},
{849,{-30.0008,-22.5},1.5708},
{837,{18.3322,48.3329},0},
{801,{-20.0008,57.5},-1.5708},
{801,{-20.0008,-57.5},1.5708},
{801,{9.9992,49.9999},3.1416},
{801,{9.9992,-49.9999},3.1416},
{803,{-35.9588,47.5},0},
{803,{-35.9588,-47.5},0},
{806,{-10.0008,90.216},-1.5708},
{806,{-10.0008,-90.216},1.5708},
{805,{21.767,51.7677},-2.3562},
{805,{21.767,-51.7677},2.3562},
{803,{-42.9588,27.5},0},
{803,{-42.9588,-27.5},0},
{803,{-10.0008,118.89},-1.5708},
{803,{-10.0008,-118.89},1.5708},
{804,{-38.5238,47.5},0},
{804,{-38.5238,-47.5},0},
{803,{-10.0008,120.806},-1.5708},
{803,{-10.0008,-120.806},1.5708},
{803,{24.2121,54.2128},-2.3562},
{803,{24.2121,-54.2128},2.3562},
{805,{26.6573,56.658},-2.3562},
{805,{26.6573,-56.658},2.3562},
{805,{-10.0008,124.264},-1.5708},
{805,{-10.0008,-124.264},1.5708},
{804,{-41.7378,47.5},0},
{804,{-41.7378,-47.5},0},
{803,{-44.3028,47.5},0},
{803,{-44.3028,-47.5},0},
{803,{29.1024,59.1031},-2.3562},
{803,{29.1024,-59.1031},2.3562},
{803,{-46.2188,47.5},0},
{803,{-46.2188,-47.5},0},
{803,{-44.8748,27.5},0},
{803,{-44.8748,-27.5},0},
{806,{-10.0008,154.48},-1.5708},
{806,{-10.0008,-154.48},1.5708},
{806,{-10.0008,209.912},-1.5708},
{806,{-10.0008,-209.912},1.5708},
{803,{30.4572,60.4579},-2.3562},
{803,{30.4572,-60.4579},2.3562},
{805,{32.9024,62.9031},-2.3562},
{805,{32.9024,-62.9031},2.3562}}},
{data={name="F2_1",author="F2_1_1",color0=0x113077,color1=0xaaaaaa,
wgroup={0, 0, 2, 0}}, blocks={
{800,{0,0},0},
{879,{3.5355,16.0355},3.1416},
{879,{3.5355,-16.0355},3.1416},
{835,{-8.75,0},-1.5708},
{829,{8.5355,11.0455},0},
{829,{8.5355,-11.0455},0},
{856,{-13.9645,21.0255},0},
{856,{-13.9645,-21.0255},0},
{856,{-23.9545,51.0255},3.1416},
{856,{-23.9545,-51.0255},3.1416},
{850,{-38.9645,16.0355},1.5708},
{850,{-38.9645,-16.0355},-1.5708},
{881,{3.1165,61.0155},-0.7854},
{881,{3.1165,-61.0155},0.7854},
{827,{-51.9459,13.7907},-2.8198},
{828,{-51.9459,-13.7907},2.8198},
{846,{-41.4545,41.0355},1.5708},
{846,{-41.4545,-41.0355},-1.5708},
{802,{3.1165,75.444},-2.3562},
{829,{-46.4545,36.0355},3.1416},
{829,{-46.4545,-36.0355},3.1416},
{834,{-58.9545,41.0355},0},
{834,{-58.9545,-41.0355},0},
{889,{-68.9545,28.5355},-1.5708},
{889,{-68.9545,-28.5355},1.5708},
{801,{10.1875,80.1575},2.3562},
{801,{10.1875,-80.1575},-2.3562},
{834,{21.0355,16.0455},-1.5708},
{834,{21.0355,-16.0455},1.5708},
{834,{-68.9545,61.0355},0},
{834,{-68.9545,-61.0355},0},
{844,{27.2585,61.0155},-0.7854},
{844,{27.2585,-61.0155},0.7854},
{801,{27.2585,43.9445},0},
{801,{27.2585,-43.9445},0},
{834,{-58.9545,81.0355},1.5708},
{834,{-58.9545,-81.0355},-1.5708},
{856,{54.3295,71.0055},3.1416},
{856,{54.3295,-71.0055},3.1416},
{850,{79.3295,76.0055},1.5708},
{850,{79.3295,-76.0055},-1.5708},
{890,{-103.0965,51.0355},2.3562},
{890,{-103.0965,-51.0355},-2.3562},
{840,{99.3295,71.0055},0},
{840,{99.3295,-71.0055},0},
{828,{12.8305,48.9445},1.5708},
{827,{12.8305,-48.9445},-1.5708},
{840,{-0.4191,90.7642},2.3562},
{840,{-0.4191,-90.7642},-2.3562},
{862,{42.2584,38.9546},2.3562},
{862,{42.2584,-38.9546},-2.3562},
{856,{68.4689,33.952},0.7854},
{856,{68.4689,-33.952},-0.7854},
{805,{-125.4708,35.7323},0.7854},
{805,{-125.4708,-35.7323},-0.7854},
{805,{4.1772,95.3604},-2.3562},
{805,{4.1772,-95.3604},2.3562},
{805,{-46.4545,76.0355},3.1416},
{805,{-46.4545,-76.0355},3.1416},
{804,{-70.5615,76.0355},0},
{804,{-70.5615,-76.0355},0},
{805,{-33.9645,3.5355},1.5708},
{805,{-33.9645,-3.5355},-1.5708},
{804,{99.3295,65.3985},1.5708},
{804,{99.3295,-65.3985},-1.5708},
{803,{-53.9545,91.9935},-1.5708},
{803,{-53.9545,-91.9935},1.5708},
{804,{7.0812,98.2644},-2.3562},
{804,{7.0812,-98.2644},2.3562},
{804,{-81.3537,36.3638},2.3562},
{804,{-81.3537,-36.3638},-2.3562},
{804,{-6.5553,70.6873},-0.7854},
{804,{-6.5553,-70.6873},0.7854},
{803,{-13.458,0},0},
{803,{-127.9159,33.2872},0.7854},
{803,{-127.9159,-33.2872},-0.7854},
{806,{-53.9545,120.6675},-1.5708},
{806,{-53.9545,-120.6675},1.5708},
{804,{-53.9545,149.9905},-1.5708},
{804,{-53.9545,-149.9905},1.5708},
{804,{74.3295,64.3985},1.5708},
{804,{74.3295,-64.3985},-1.5708},
{804,{-53.9545,153.2045},-1.5708},
{804,{-53.9545,-153.2045},1.5708},
{805,{9.9853,101.1685},-2.3562},
{805,{9.9853,-101.1685},2.3562},
{806,{74.3295,113.7215},-1.5708},
{806,{74.3295,-113.7215},1.5708},
{803,{74.3295,142.3955},-1.5708},
{803,{74.3295,-142.3955},1.5708},
{804,{30.6515,33.9546},0},
{804,{30.6515,-33.9546},0},
{803,{-8.369,72.501},-0.7854},
{803,{-8.369,-72.501},0.7854},
{804,{74.3295,144.9605},-1.5708},
{804,{74.3295,-144.9605},1.5708},
{805,{74.3295,149.0675},-1.5708},
{805,{74.3295,-149.0675},1.5708},
{806,{74.3295,179.2835},-1.5708},
{806,{74.3295,-179.2835},1.5708},
{804,{80.2118,22.2091},2.3562},
{804,{80.2118,-22.2091},-2.3562},
{804,{54.3295,54.3985},1.5708},
{804,{54.3295,-54.3985},-1.5708},
{806,{-136.2302,91.2403},-0.7854},
{806,{-136.2302,-91.2403},0.7854},
{803,{-129.2707,31.9324},0.7854},
{803,{-129.2707,-31.9324},-0.7854},
{805,{26.0355,3.5455},1.5708},
{805,{26.0355,-3.5455},-1.5708},
{805,{-157.5961,112.6062},-0.7854},
{805,{-157.5961,-112.6062},0.7854},
{803,{-130.6255,30.5776},0.7854},
{803,{-130.6255,-30.5776},-0.7854},
{804,{-10.1827,74.3147},-0.7854},
{804,{-10.1827,-74.3147},0.7854},
{804,{99.3295,62.1845},1.5708},
{804,{99.3295,-62.1845},-1.5708},
{803,{-160.0412,115.0513},-0.7854},
{803,{-160.0412,-115.0513},0.7854},
{804,{44.3395,54.3985},1.5708},
{804,{44.3395,-54.3985},-1.5708},
{803,{82.0255,20.3954},2.3562},
{803,{82.0255,-20.3954},-2.3562},
{804,{-132.4392,28.7639},0.7854},
{804,{-132.4392,-28.7639},-0.7854},
{805,{-53.9545,157.3115},-1.5708},
{805,{-53.9545,-157.3115},1.5708},
{804,{-53.9545,161.4185},-1.5708},
{804,{-53.9545,-161.4185},1.5708},
{804,{-53.9545,164.6325},-1.5708},
{804,{-53.9545,-164.6325},1.5708},
{804,{-161.8549,116.865},-0.7854},
{804,{-161.8549,-116.865},0.7854},
{804,{-164.1275,119.1376},-0.7854},
{804,{-164.1275,-119.1376},0.7854},
{803,{14.4005,75.9446},2.3562},
{803,{14.4005,-75.9446},-2.3562},
{803,{-165.9412,120.9513},-0.7854},
{803,{-165.9412,-120.9513},0.7854},
{803,{74.3295,207.9575},-1.5708},
{803,{74.3295,-207.9575},1.5708},
{805,{-168.3864,123.3965},-0.7854},
{805,{-168.3864,-123.3965},0.7854},
{805,{74.3295,211.4155},-1.5708},
{805,{74.3295,-211.4155},1.5708},
{803,{21.3005,43.9445},0},
{803,{21.3005,-43.9445},0},
{805,{-171.9219,126.932},-0.7854},
{805,{-171.9219,-126.932},0.7854},
{805,{99.3295,58.0775},1.5708},
{805,{99.3295,-58.0775},-1.5708},
{804,{37.7225,80.9955},0},
{804,{37.7225,-80.9955},0},
{803,{-42.9965,76.0355},3.1416},
{803,{-42.9965,-76.0355},3.1416},
{804,{-134.7118,26.4913},0.7854},
{804,{-134.7118,-26.4913},-0.7854},
{805,{-175.4574,130.4675},-0.7854},
{805,{-175.4574,-130.4675},0.7854},
{805,{74.3295,216.4155},-1.5708},
{805,{74.3295,-216.4155},1.5708},
{803,{-177.9025,132.9126},-0.7854},
{803,{-177.9025,-132.9126},0.7854},
{805,{-180.3477,135.3578},-0.7854},
{805,{-180.3477,-135.3578},0.7854},
{805,{74.3295,221.4155},-1.5708},
{805,{74.3295,-221.4155},1.5708},
{804,{-183.2517,138.2618},-0.7854},
{804,{-183.2517,-138.2618},0.7854},
{804,{99.3295,53.9705},1.5708},
{804,{99.3295,-53.9705},-1.5708},
{804,{-185.5243,140.5344},-0.7854},
{804,{-185.5243,-140.5344},0.7854},
{805,{-188.4284,143.4385},-0.7854},
{805,{-188.4284,-143.4385},0.7854},
{804,{-191.3324,146.3425},-0.7854},
{804,{-191.3324,-146.3425},0.7854},
{803,{74.3295,224.8735},-1.5708},
{803,{74.3295,-224.8735},1.5708},
{803,{74.3295,226.7895},-1.5708},
{803,{74.3295,-226.7895},1.5708},
{805,{-194.2365,149.2466},-0.7854},
{805,{-194.2365,-149.2466},0.7854},
{804,{-197.1405,152.1506},-0.7854},
{804,{-197.1405,-152.1506},0.7854},
{804,{-88.4248,72.7784},-2.3562},
{804,{-88.4248,-72.7784},2.3562},
{803,{-198.9542,153.9643},-0.7854},
{803,{-198.9542,-153.9643},0.7854},
{805,{-201.3994,156.4095},-0.7854},
{805,{-201.3994,-156.4095},0.7854},
{804,{-33.9445,67.6325},-1.5708},
{804,{-33.9445,-67.6325},1.5708},
{806,{-222.7653,177.7754},-0.7854},
{806,{-222.7653,-177.7754},0.7854},
{804,{74.3295,229.3545},-1.5708},
{804,{74.3295,-229.3545},1.5708},
{805,{-244.1312,199.1413},-0.7854},
{805,{-244.1312,-199.1413},0.7854},
{805,{99.3295,49.8635},1.5708},
{805,{99.3295,-49.8635},-1.5708},
{805,{-247.6667,202.6768},-0.7854},
{805,{-247.6667,-202.6768},0.7854},
{805,{74.3295,233.4615},-1.5708},
{805,{74.3295,-233.4615},1.5708},
{806,{74.3295,263.6775},-1.5708},
{806,{74.3295,-263.6775},1.5708},
{806,{-269.0326,224.0427},-0.7854},
{806,{-269.0326,-224.0427},0.7854},
{803,{83.3803,19.0406},2.3562},
{803,{83.3803,-19.0406},-2.3562},
{803,{-69.9125,36.0355},0},
{803,{-69.9125,-36.0355},0},
{805,{-41.4545,61.0155},0},
{805,{-41.4545,-61.0155},0},
{804,{-136.9844,24.2187},0.7854},
{804,{-136.9844,-24.2187},-0.7854},
{804,{-289.767,244.7771},-0.7854},
{804,{-289.767,-244.7771},0.7854},
{805,{13.5208,104.704},-2.3562},
{805,{13.5208,-104.704},2.3562},
{806,{74.3295,319.1095},-1.5708},
{806,{74.3295,-319.1095},1.5708},
{805,{99.3295,44.8635},1.5708},
{805,{99.3295,-44.8635},-1.5708},
{805,{-53.9545,168.7395},-1.5708},
{805,{-53.9545,-168.7395},1.5708},
{804,{74.3295,348.4325},-1.5708},
{804,{74.3295,-348.4325},1.5708},
{803,{74.3295,350.9975},-1.5708},
{803,{74.3295,-350.9975},1.5708},
{803,{-33.9645,26.9935},-1.5708},
{803,{-33.9645,-26.9935},1.5708},
{804,{74.3295,353.5625},-1.5708},
{804,{74.3295,-353.5625},1.5708},
{805,{-292.6711,247.6812},-0.7854},
{805,{-292.6711,-247.6812},0.7854},
{803,{74.3295,356.1275},-1.5708},
{803,{74.3295,-356.1275},1.5708},
{806,{-314.037,269.0471},-0.7854},
{806,{-314.037,-269.0471},0.7854},
{805,{-335.4029,290.413},-0.7854},
{805,{-335.4029,-290.413},0.7854},
{805,{-338.9384,293.9485},-0.7854},
{805,{-338.9384,-293.9485},0.7854},
{803,{99.3295,41.4055},1.5708},
{803,{99.3295,-41.4055},-1.5708},
{805,{-53.9545,173.7395},-1.5708},
{805,{-53.9545,-173.7395},1.5708},
{805,{-342.4739,297.484},-0.7854},
{805,{-342.4739,-297.484},0.7854},
{805,{74.3295,359.5855},-1.5708},
{805,{74.3295,-359.5855},1.5708},
{805,{-346.0094,301.0195},-0.7854},
{805,{-346.0094,-301.0195},0.7854},
{804,{74.3295,363.6925},-1.5708},
{804,{74.3295,-363.6925},1.5708},
{803,{-15.374,0},0},
{804,{-348.9134,303.9235},-0.7854},
{804,{-348.9134,-303.9235},0.7854}}},
{data={name="F2_remainder",author="F2_remainder_2",color0=0x113077,color1=0xaaaaaa,
wgroup={0, 0, 2, 0}}, blocks={
{800,{0,0},0},
{841,{-5.0008,15},-1.5708},
{841,{-5.0008,-15},1.5708},
{805,{-17.5008,20},0},
{805,{-17.5008,-20},0},
{803,{-20.9588,20},0},
{803,{-20.9588,-20},0},
{803,{-22.8748,20},0},
{803,{-22.8748,-20},0},
{804,{-0.0008,26.607},-1.5708},
{804,{-0.0008,-26.607},1.5708},
{803,{-10.0008,25.958},-1.5708},
{803,{-10.0008,-25.958},1.5708},
{805,{-0.0008,30.714},-1.5708},
{805,{-0.0008,-30.714},1.5708}}}}} |
local util = require("spec.util")
describe("config type checking", function()
it("should error out when config.include is not a {string}", function()
util.run_mock_project(finally, {
dir_structure = {
["tlconfig.lua"] = [[return { include = "*.tl" }]],
["foo.tl"] = [[print "a"]],
},
cmd = "build",
generated_files = {},
popen = {
status = nil,
exit = "exit",
code = 1,
},
cmd_output = "Error loading config: Expected include to be a {string}, got string\n",
})
end)
it("should error out when config.source_dir is not a string", function()
util.run_mock_project(finally, {
dir_structure = {
["tlconfig.lua"] = [[return { source_dir = true }]],
["foo.tl"] = [[print "a"]],
},
cmd = "build",
generated_files = {},
popen = {
status = nil,
exit = "exit",
code = 1,
},
cmd_output = "Error loading config: Expected source_dir to be a string, got boolean\n",
})
end)
end)
|
--
-- It looks just like AE2's Molecular Assembler, and has the same function too.
--
local cluster_devices = assert(yatm.cluster.devices)
local cluster_energy = assert(yatm.cluster.energy)
local Energy = assert(yatm.energy)
local assembler_yatm_network = {
kind = "machine",
groups = {
dscs_assembler_module = 1,
energy_consumer = 1,
item_consumer = 1,
item_producer = 1,
machine_worker = 1,
},
default_state = "off",
states = {
conflict = "yatm_dscs:assembler_error",
error = "yatm_dscs:assembler_error",
off = "yatm_dscs:assembler_off",
on = "yatm_dscs:assembler_on",
},
energy = {
capacity = 4000,
startup_threshold = 200,
network_charge_bandwidth = 100,
passive_lost = 0, -- assemblers won't passively start losing energy
},
}
local function refresh_infotext(pos, node)
local meta = minetest.get_meta(pos)
local infotext =
"Assembler\n" ..
cluster_devices:get_node_infotext(pos) .. "\n" ..
cluster_energy:get_node_infotext(pos) .. " [" .. Energy.meta_to_infotext(meta, yatm.devices.ENERGY_BUFFER_KEY) .. "]\n"
meta:set_string("infotext", infotext)
end
function assembler_yatm_network:work(ctx)
return 0
end
local assembler_node_box = {
type = "fixed",
fixed = {
{-0.4375, -0.4375, -0.4375, 0.4375, 0.4375, 0.4375}, -- NodeBox1
{-0.5, -0.5, -0.5, -0.375, 0.5, -0.375}, -- NodeBox2
{0.375, -0.5, -0.5, 0.5, 0.5, -0.375}, -- NodeBox3
{-0.5, -0.5, 0.375, -0.375, 0.5, 0.5}, -- NodeBox4
{0.375, -0.5, 0.375, 0.5, 0.5, 0.5}, -- NodeBox5
{-0.375, 0.375, 0.375, 0.375, 0.5, 0.5}, -- NodeBox6
{-0.375, 0.375, -0.5, 0.375, 0.5, -0.375}, -- NodeBox7
{-0.5, 0.375, -0.5, -0.375, 0.5, 0.5}, -- NodeBox8
{0.375, 0.375, -0.5, 0.5, 0.5, 0.5}, -- NodeBox9
{-0.5, -0.5, -0.5, 0.5, -0.375, -0.375}, -- NodeBox10
{-0.5, -0.5, 0.375, 0.5, -0.375, 0.5}, -- NodeBox11
{-0.5, -0.5, -0.5, -0.375, -0.375, 0.5}, -- NodeBox12
{0.375, -0.5, -0.5, 0.5, -0.375, 0.5}, -- NodeBox13
}
}
local assembler_selection_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},
},
}
local groups = {
cracky = 1,
yatm_dscs_device = 1,
yatm_data_device = 1,
yatm_network_device = 1,
yatm_energy_device = 1,
}
local assembler_data_interface = {}
function assembler_data_interface.on_load(self, pos, node)
end
function assembler_data_interface.receive_pdu(self, pos, node, dir, port, value)
--
end
yatm.devices.register_stateful_network_device({
basename = "yatm_dscs:assembler",
codex_entry_id = "yatm_dscs:assembler",
description = "Item Assembler",
groups = groups,
drop = assembler_yatm_network.states.off,
use_texture_alpha = "opaque",
tiles = {
"yatm_assembler_side.off.png",
},
use_texture_alpha = "clip",
drawtype = "nodebox",
node_box = assembler_node_box,
selection_box = assembler_selection_box,
paramtype = "light",
paramtype2 = "facedir",
yatm_network = assembler_yatm_network,
data_network_device = {
type = "device",
},
data_interface = assembler_data_interface,
refresh_infotext = refresh_infotext,
}, {
on = {
tiles = {{
name = "yatm_assembler_side.on.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1.0
},
}},
},
error = {
tiles = {"yatm_assembler_side.error.png"},
}
})
|
local PANEL = {}
AccessorFunc( PANEL, "m_Material", "Material" )
AccessorFunc( PANEL, "m_Color", "Color" )
AccessorFunc( PANEL, "m_Rotation", "Rotation" )
AccessorFunc( PANEL, "m_Handle", "Handle" )
function PANEL:Init()
self:SetColor( Color( 255, 255, 255, 255 ) )
self:SetRotation( 0 )
self:SetHandle( Vector(0.5, 0.5, 0) )
self:SetMouseInputEnabled( false )
self:SetKeyboardInputEnabled( false )
self:NoClipping( true )
end
function PANEL:Paint()
local Mat = self.m_Material
if ( !Mat ) then return true end
surface.SetMaterial( Mat )
surface.SetDrawColor( self.m_Color.r, self.m_Color.g, self.m_Color.b, self.m_Color.a )
local w, h = self:GetSize()
local x, y = 0, 0
surface.DrawTexturedRectRotated( x, y, w, h, self.m_Rotation )
return true
end
function PANEL:GenerateExample( ClassName, PropertySheet, Width, Height )
local ctrl = vgui.Create( ClassName )
ctrl:SetMaterial( Material( "brick/brick_model" ) )
ctrl:SetSize( 200, 200 )
PropertySheet:AddSheet( ClassName, ctrl, nil, true, true )
end
derma.DefineControl( "DSprite", "A sprite", PANEL, "DPanel" )
-- Convenience function
function CreateSprite( mat )
local sprite = vgui.Create( "DSprite" )
sprite:SetMaterial( mat )
return sprite
end
|
local source = ...
if _VERSION == "Lua 5.1" then
load = loadstring
end
assert(load("return " .. source, '=(EVAL)'))
|
function exporttable(t)
local s = "table =\n{\n"
for row, r in ipairs(t) do
s = s .. "\t{"
for column, v in ipairs(r) do
s = s .. v .. ","
end
s = s .. "},\n"
end
s = s .. "}"
return s
end
function savetable(f)
love.filesystem.write("save" .. f .. ".bly", exporttable(table))
end
function loadtable(f)
if not love.filesystem.exists("save" .. f .. ".bly") then return end
love.filesystem.include("save" .. f .. ".bly")
end
function loadsave(f)
if savemode == "save" then
savetable(f)
elseif savemode == "load" then
loadtable(f)
end
end
function load()
love.filesystem.require("tables/nice.lua") -- start table
love.filesystem.require("notes/sfxr.lua") -- music notes
-- colors...
darkGrey = love.graphics.newColor(51,51,51)
text = love.graphics.newColor(200,200,200)
white = love.graphics.newColor(255,255,255)
lightGrey = love.graphics.newColor(100,100,100)
grey = love.graphics.newColor(68,68,68)
love.graphics.setBackgroundColor(darkGrey)
curRow = 1 -- currently played row
dtSum = 0 -- dtSum counts time
dtLimit = .25 -- dtLimit controls speed
love.audio.setChannels(16) -- cannels! yay! I bet this won't work!
love.audio.setVolume(.3) -- games have too loud a volume always :(
volume = .3 -- since there seems to be no getVolume()
cursorX = 0 -- cursor x position
cursorY = 0 -- cursor y position
cursorField = {} -- the field currently 'inhabited' by the cursor
help = false -- controls help showing
helpUsed = false -- controls help help showing
love.graphics.setFont(love.default_font)
savemode = ""
end
function update(dt)
dtSum = dtSum + dt -- stack the time
cursorField = updateCursorField()
if dtSum > dtLimit then -- if enough time is stacked...
dtSum = dtSum - dtLimit -- 'clear' dtSum
for i, v in pairs(table) do -- for each column in table...
if v[curRow] > 0 then -- if the row's volume is > 0...
notes[i]:setVolume(v[curRow]) -- apply current row's volume
love.audio.play(notes[i]) -- play it
end
end
if curRow == 16 then curRow = 1 else curRow = curRow + 1 end -- next row
end
end
function draw()
for i, v in pairs(table) do -- for each column in table...
for j, w in pairs(v) do -- for each row in table...
if j == curRow or (cursorField[1] == i and cursorField[2] == j) then -- if current row is played or cursor is in field...
love.graphics.setColor(lightGrey) -- set color to background rectangle light grey
else
love.graphics.setColor(grey) -- set color to background rectangle grey
end
love.graphics.rectangle(0, 32*(j-1)+8, 32*(i-1)+8, 24, 24) -- draw background rectangle
if w > 0 then-- if field is > 0...
love.graphics.setColor(white) -- set color to foreground rectangle white
love.graphics.rectangle(0, 32*(j-1)+8, 32*(i-1)+8+24-24*w, 24, 24*w) -- draw note rectangle
end
end
end
-- help and help help drawing
love.graphics.setColor(text) -- set color to help text black
if helpUsed == false then love.graphics.draw("help/hide this: hold H", 16, 26) end -- draw help help the first 4 seconds
if help then love.graphics.draw("enable/disable: Mouse Button (Left)\nincrease/decrease: Mouse Wheel Up/Down\nclear: Backspace\nmaster volume: +/-\nquit: Q, Esc\nsave/load to ./love/belly: s/l",16,26) end
if savemode ~= "" then love.graphics.draw("press function key to save (F1-F12) to that slot", 16, 26) end
end
function updateCursorField()
cursorField = {} -- set to nil, in case we find nothing
cursorX = love.mouse.getX() -- update cursor x value
cursorY = love.mouse.getY() -- update cursor y value
for i, v in pairs(table) do -- for each column.
if cursorY >= 32*(i-1)+8 and cursorY <= 32*i then -- if cursor y position is in the column...
for j, w in pairs(v) do -- for each row
if cursorX >= 32*(j-1)+8 and cursorX <= 32*j then -- if cursor x position is in the row...
return {i, j}
end
end
end
end
return {} -- the 'currently hovered field' if there is none
end
function mousepressed(x,y,button)
if cursorField[1] ~= nil then -- if there is a 'currently hovered field'
local a, b = cursorField[1], cursorField[2] -- less type = good
if button == love.mouse_left then -- on left click...
if table[a][b] > 0 then -- if field is active...
table[a][b] = 0 -- disable it
else
table[a][b] = 1 -- enable it 100%
end
elseif button == love.mouse_wheelup then -- on wheel up...
if table[a][b] < 1 then -- if field is less than 100% active...
table[a][b] = table[a][b] + .25 -- add a quarter of power to it
end
elseif button == love.mouse_wheeldown then -- on wheel down...
if table[a][b] > 0 then -- if field is active...
table[a][b] = table[a][b] - .25 -- reduce it's power by 1/4
end
end
end
end
function keypressed(key)
if key == love.key_escape or key == love.key_q then
love.system.exit()
elseif key == love.key_backspace then
love.filesystem.include("tables/empty.lua")
elseif key == love.key_h then
help = true
helpUsed = true
elseif (key == love.key_plus or key == love.key_kp_plus) and volume < .91 then
volume = volume + .1
love.audio.setVolume(volume)
print(volume)
elseif (key == love.key_minus or key == love.key_kp_minus) and volume > 0.01 then
volume = volume - .1
love.audio.setVolume(volume)
print(volume)
elseif key == love.key_f1 then
loadsave(1)
savemode = ""
elseif key == love.key_f2 then
loadsave(2)
savemode = ""
elseif key == love.key_f3 then
loadsave(3)
savemode = ""
elseif key == love.key_f4 then
loadsave(4)
savemode = ""
elseif key == love.key_f5 then
loadsave(5)
savemode = ""
elseif key == love.key_f6 then
loadsave(6)
savemode = ""
elseif key == love.key_f7 then
loadsave(7)
savemode = ""
elseif key == love.key_f8 then
loadsave(8)
savemode = ""
elseif key == love.key_f9 then
loadsave(9)
savemode = ""
elseif key == love.key_f10 then
loadsave(10)
savemode = ""
elseif key == love.key_f11 then
loadsave(11)
savemode = ""
elseif key == love.key_f12 then
loadsave(12)
savemode = ""
else
savemode = ""
end
if key == love.key_l then
helpUsed = true
savemode = "load"
elseif key == love.key_s then
helpUsed = true
savemode = "save"
end
end
function keyreleased(key)
if key == love.key_h then
help = false
end
end
|
local ICloneable = require("api.ICloneable")
local I18N = require("api.I18N")
--- @classmod DateTime
local DateTime = class.class("DateTime", ICloneable)
--- @function DateTime:new
--- @tparam[opt] int year
--- @tparam[opt] int month
--- @tparam[opt] int day
--- @tparam[opt] int hour
--- @tparam[opt] int minute
--- @tparam[opt] int second
function DateTime:init(year, month, day, hour, minute, second)
self.year = year or 0
self.month = month or 0
self.day = day or 0
self.hour = hour or 0
self.minute = minute or 0
self.second = second or 0
end
--- Returns the date in hours. Used in various places for time
--- tracking purposes.
---
--- @treturn int
function DateTime:hours()
return self.hour
+ self.day * 24
+ self.month * 24 * 30
+ self.year * 24 * 30 * 12
end
--- @tparam int hours
--- @treturn DateTime
function DateTime:from_hours(hours)
hours = math.max(hours, 0)
local hour = hours % 24
local day = math.floor(hours / 24) % 31
local month = math.floor(hours / 24 / 30) % 12
local year = math.floor(hours / 24 / 30 / 12)
return DateTime:new(year, month, day, hour, 0, 0)
end
function DateTime:__tostring()
return string.format("%d/%d/%d %02d:%02d:%02d", self.year, self.month, self.day, self.hour, self.minute, self.second)
end
function DateTime:format_localized(with_hour)
local text = I18N.get("ui.date", self.year, self.month, self.day)
if with_hour then
text = text .. I18N.space() .. I18N.get("ui.date_hour", self.hour)
end
return text
end
-- TODO figure out a generalized cloning mechanism for class instances
function DateTime:clone()
return DateTime:new(self.year, self.month, self.day, self.hour, self.minute, self.second)
end
return DateTime
|
return {
summary = 'Attach attributes from another Mesh onto this one.',
description = [[
Attaches attributes from another Mesh onto this one. This can be used to share vertex data
across multiple meshes without duplicating the data, and can also be used for instanced
rendering by using the `divisor` parameter.
]],
arguments = {
mesh = {
type = 'Mesh',
description = 'The Mesh to attach attributes from.'
},
divisor = {
type = 'number',
default = '0',
description = 'The attribute divisor for all attached attributes.'
},
attributes = {
type = 'table',
description = 'A table of attribute names to attach from the other Mesh.'
},
['...'] = {
type = 'string',
description = 'The names of attributes to attach from the other Mesh.'
}
},
returns = {},
variants = {
{
description = 'Attach all attributes from the other mesh.',
arguments = { 'mesh', 'divisor' },
returns = {}
},
{
arguments = { 'mesh', 'divisor', '...' },
returns = {}
},
{
arguments = { 'mesh', 'divisor', 'attributes' },
returns = {}
}
},
notes = [[
The attribute divisor is a number used to control how the attribute data relates to instancing.
If 0, then the attribute data is considered "per vertex", and each vertex will get the next
element of the attribute's data. If the divisor 1 or more, then the attribute data is
considered "per instance", and every N instances will get the next element of the attribute
data.
To prevent cycles, it is not possible to attach attributes onto a Mesh that already has
attributes attached to a different Mesh.
]],
related = {
'Mesh:detachAttributes',
'Mesh:drawInstanced'
}
}
|
-- this bit of code modifies the default chests and furnaces to be compatible
-- with pipeworks.
minetest.override_item("default:furnace", {
tiles = {
"default_furnace_top.png^pipeworks_tube_connection_stony.png",
"default_furnace_bottom.png^pipeworks_tube_connection_stony.png",
"default_furnace_side.png^pipeworks_tube_connection_stony.png",
"default_furnace_side.png^pipeworks_tube_connection_stony.png",
"default_furnace_side.png^pipeworks_tube_connection_stony.png",
"default_furnace_front.png"
},
groups = {cracky = 2, tubedevice = 1, tubedevice_receiver = 1},
tube = {
insert_object = function(pos, node, stack, direction)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
local timer = minetest.get_node_timer(pos)
if not timer:is_started() then
timer:start(1.0)
end
if direction.y == 1 then
return inv:add_item("fuel",stack)
else
return inv:add_item("src",stack)
end
end,
can_insert = function(pos,node,stack,direction)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
if direction.y == 1 then
return inv:room_for_item("fuel", stack)
else
return inv:room_for_item("src", stack)
end
end,
input_inventory = "dst",
connect_sides = {left = 1, right = 1, back = 1, front = 1, bottom = 1, top = 1}
},
})
minetest.override_item("default:furnace_active", {
tiles = {
"default_furnace_top.png^pipeworks_tube_connection_stony.png",
"default_furnace_bottom.png^pipeworks_tube_connection_stony.png",
"default_furnace_side.png^pipeworks_tube_connection_stony.png",
"default_furnace_side.png^pipeworks_tube_connection_stony.png",
"default_furnace_side.png^pipeworks_tube_connection_stony.png",
{
image = "default_furnace_front_active.png",
backface_culling = false,
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1.5
},
}
},
groups = {cracky = 2, tubedevice = 1, tubedevice_receiver = 1, not_in_creative_inventory = 1},
tube = {
insert_object = function(pos,node,stack,direction)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
local timer = minetest.get_node_timer(pos)
if not timer:is_started() then
timer:start(1.0)
end
if direction.y == 1 then
return inv:add_item("fuel", stack)
else
return inv:add_item("src", stack)
end
end,
can_insert = function(pos, node, stack, direction)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
if direction.y == 1 then
return inv:room_for_item("fuel", stack)
else
return inv:room_for_item("src", stack)
end
end,
input_inventory = "dst",
connect_sides = {left = 1, right = 1, back = 1, front = 1, bottom = 1, top = 1}
},
})
minetest.override_item("default:chest", {
tiles = {
"default_chest_top.png^pipeworks_tube_connection_wooden.png",
"default_chest_top.png^pipeworks_tube_connection_wooden.png",
"default_chest_side.png^pipeworks_tube_connection_wooden.png",
"default_chest_side.png^pipeworks_tube_connection_wooden.png",
"default_chest_side.png^pipeworks_tube_connection_wooden.png",
"default_chest_front.png"
},
groups = {choppy = 2, oddly_breakable_by_hand = 2, tubedevice = 1, tubedevice_receiver = 1},
tube = {
insert_object = function(pos, node, stack, direction)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
return inv:add_item("main", stack)
end,
can_insert = function(pos, node, stack, direction)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
return inv:room_for_item("main", stack)
end,
input_inventory = "main",
connect_sides = {left = 1, right = 1, back = 1, front = 1, bottom = 1, top = 1}
},
})
minetest.override_item("default:chest_locked", {
tiles = {
"default_chest_top.png^pipeworks_tube_connection_wooden.png",
"default_chest_top.png^pipeworks_tube_connection_wooden.png",
"default_chest_side.png^pipeworks_tube_connection_wooden.png",
"default_chest_side.png^pipeworks_tube_connection_wooden.png",
"default_chest_side.png^pipeworks_tube_connection_wooden.png",
"default_chest_lock.png"
},
groups = {choppy = 2, oddly_breakable_by_hand = 2, tubedevice = 1, tubedevice_receiver = 1},
tube = {
insert_object = function(pos, node, stack, direction)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
return inv:add_item("main", stack)
end,
can_insert = function(pos, node, stack, direction)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
return inv:room_for_item("main", stack)
end,
connect_sides = {left = 1, right = 1, back = 1, front = 1, bottom = 1, top = 1}
},
})
|
-- Here is an example of the most common used configuration functions
-- For more in-depth use of premake, refer to the online documentation:
-- https://github.com/premake/premake-core/wiki
-- Add additional defines:
-- defines { "DEFINE1", "DEFINE2" }
-- Remove existing defines:
-- undefines { "DEFINE1", "DEFINE2" }
-- Add files to the project:
-- files { "foo/**.cpp", "foo/**.h", "bar/file.lua" }
-- Remove files to the project:
-- removefiles { "foo/**.h", "bar/file.lua" }
-- Add include directories:
-- includedirs { "foo/", "bar/" }
-- Remove include directories:
-- removeincludedirs { "foo/", "bar/" }
-- Link libraries:
-- links { "libname", "lib2" }
-- Remove libraries:
-- removelinks { "libname", "lib2" }
-- Add libraries directory
-- libdirs { "foo/", "bar/" }
-- Remove libraries directory
-- removelibdirs { "foo/", "bar/" }
local enchantedForest = "./"
include(enchantedForest .. "Premake/EnchantedForestProject")
solution "EnchantedForest"
platforms { "Win32", "x64" }
configurations { "Debug", "Debug Optimized", "Release", "Final" }
startproject "VacuumApp"
filter "action:vs2015"
location ("Project/VisualStudio2015/")
objdir("Project/VisualStudio2015/Obj/%{cfg.buildcfg}_%{cfg.platform}_%{prj.name}")
filter {}
includeEnchantedForest(enchantedForest)
-- projects
EnchantedForestProject("EnchantedForestApp", enchantedForest)
targetname ( "EnchantedForest" )
-- //////////// COMMON SETTINGS ////////////
defines {
"ENCHANTEDFOREST"
}
|
kode = kode or {}
local encode, decode
local ok
if ENVIRONMENT__ == "product" then
ok = pcall(function()
local cjson = require "cjson"
encode = cjson.encode
decode = cjson.decode
end)
end
if not ok then
local simplejson = require "kode.helpers.simplejson"
encode = simplejson.encode
decode = simplejson.decode
end
kode.json = {}
function kode.json.encode(tbl)
local ok, result = pcall(encode, tbl)
if ok then return result end
error("json encode failed")
end
function kode.json.decode(str)
local ok, result = pcall(decode, str)
if ok then return result end
error("json decode failed")
end |
-- bot.lua
-- Use this with `bin/telegram-cli -s bot.lua`
-- 2 seconds between commands (say, `!ping`) should be enough to avoid botloops
-- Of course the other bot could wait 2 seconds between pings, but...
TIMEOUT = 2
-- We shouldn't reply as much if we are busy.
BUSY_TIMEOUT = 10
BUSY_REPLIES = {
["Question"] = "Answer"
}
GENERIC_BUSY_REPLY = "I am currently busy - try again later :)"
DEFAULT_CHAT = nil -- (chat|channel)#id<ID>
DEFAULT_SHOO = nil -- @<USERNAME>
DEFAULT_SPAM = "/start"
LOG_MESSAGES = true
LOG_FILE = "log"
RUN_CRON_EVERY = 60.0
started = false
logfile = nil
our_id = 0
blacklist = {}
in_timeout = {}
busy = false
ignore_commands = false
-- Dispatch tables [command] -> function (peer, params, message)
own_commands = {}
commands = {}
-- Use `register_command` or `register_own_command` with `(command, func)`
-- to add commands to the tables.
function ok_cb(extra, success, result)
end
function should_we_not_reply(msg)
-- Given a telegram message `msg` this checks whether the sender of the
-- message has been blacklisted or is in timeout. If neither applies this
-- updated the *last time replied to* of the user in the `in_timeout` table
-- and returns false.
from = msg.from.peer_type .. "#id" .. msg.from.peer_id
-- Ignore blacklisted users
if blacklist[from] then
return true
end
-- Ignore users in timeout
local timeout = TIMEOUT
if busy then
-- We have a different timeout when we are busy - we don't want to
-- reply with ten messages to people talking with us in private.
-- I wonder if this is really necessary.
timeout = BUSY_TIMEOUT
end
if (in_timeout[from] ~= nil) and (msg.date - in_timeout[from]) < timeout then
return true
end
-- Update last message replied to time
in_timeout[from] = msg.date
return false
end
function user_string(peer)
-- Given a telegram peer `peer` it returns a string containing a textual
-- representation of the peer, according to the following format
-- specification.
--
-- ## Format Specification
--
-- ```bnf
-- <TYPE> "#id" <ID> " - " <NAME>
--
-- <NAME> := ["@" <USERNAME> " - "] <FIRST_NAME> [" " <LAST_NAME>]
-- | <TITLE>
-- <TYPE> := "user" | "group" | "channel"
-- ```
local result = ""
result = result .. peer.peer_type .. "#id" .. peer.peer_id .. " - "
if peer.peer_type == "user" then
if peer.username then
result = result .. "@" .. peer.username .. " - "
end
result = result .. peer.first_name
if peer.last_name then
result = result .. " " .. peer.last_name
end
else
result = result .. peer.title
end
return result
end
function describe_message(msg)
-- Given a telegram message `msg` it returns a string containing a textual
-- representation of the message, according to the following format
-- specification.
--
-- ## Format specification
--
-- ```bnf
-- "[" <DATE> "] [" <FROM:USER> "] [" <TO:USER> "]" <MESSAGE:MESS>
--
-- <DATE> := <YEAR> "-" <MONTH> "-" <DAY> " " <HOUR> ":" <MINUTES> ":" <SECONDS>
-- <USER> := <PEER_TYPE> "#id" <PEER_ID> " - " <PEER_NAME:NAME>
-- <NAME> := ["@" <PEER_USERNAME> " - "] <PEER_FIRST_NAME> [<PEER_LAST_NAME>]
-- | <PEER_TITLE>
-- <MESS> := ": " <MESSAGE_TEXT>
-- | " [media: " <MESSAGE_MEDIA_TYPE> "]"
-- | "[" <MESSAGE_ACTION_TYPE> [": " <MESSAGE_ACTION_USER:USER>] "]"
-- <PEER_TYPE> := "user" | "group" | "channel"
-- ```
local now = os.date("[%Y-%m-%d %H:%M:%S]", msg.date)
local result = now .. " [" .. user_string(msg.from) .. "] [" .. user_string(msg.to) .. "]"
if msg.text then
result = result .. ": " .. msg.text
end
if msg.media then
result = result .. " [media: " .. msg.media.type .. "]"
end
if msg.action then
result = result .. " [" .. msg.action.type
if msg.action.user then
result = result .. ": " .. user_string(msg.action.user)
end
result = result .. "]"
end
return result
end
function log_message(msg)
-- Given a telegram message `msg` it appends to `logfile` the textual
-- representation of `msg` returned by `describe_message`, plus a newline.
logfile:write(describe_message(msg) .. "\n")
end
function register_command(command, func)
commands[command] = func
end
function register_own_command(command, func)
own_commands[command] = func
end
function handle_our_own_message(msg)
-- Given an outbound telegram message `msg` this handles the commands
-- exclusive to ourselves.
local peer = msg.to.peer_type .. "#id" .. msg.to.peer_id
-- This is "bugged" - it doesn't handle accented letters in commands
-- Also, I don't really understand how Lua patterns work :-/
local command, params = msg.text:match("^(!%a*)%s?(.*)$")
if command then
if own_commands[command] then
own_commands[command](peer, params, msg)
end
end
end
function to_whom_should_we_reply(msg)
-- Given a telegram message `msg` it returns whether this is a private
-- chat and the id of the peer we should reply to.
if (msg.to.peer_id == our_id) then
-- This is a private chat - `from` holds the sender, `to` our id
-- Don't reply to ourselves, that'd be silly.
return true, msg.from.peer_type .. "#id" .. msg.from.peer_id
else
-- The message was sent to a group - reply in the group
return false, msg.to.peer_type .. "#id" .. msg.to.peer_id
end
end
function handle_busy(msg, peer)
-- Given a telegram message `msg` and a peer id `peer` (which will always
-- be an user id), this replies with either a generic busy reply or with
-- a reply taken from the `BUSY_REPLIES` table according to the message
-- received.
if busy_replies[msg.text] then
-- Oh-ho! We matched the message with something from the table!
send_msg(peer, BUSY_REPLIES[msg.text], ok_cb, false)
else
-- Generic bot-ty reply which makes us looks like bots
send_msg(peer, GENERIC_BUSY_REPLY, ok_cb, false)
end
end
function on_msg_receive(msg)
if not started then
return
end
-- Log the message to file
if LOG_MESSAGES then
log_message(msg)
end
-- Handle outbound messages
if msg.out then
handle_our_own_message(msg)
return
end
-- Ignore blacklisted users or users in timeout
if should_we_not_reply(msg) then
return
end
local is_private_chat, peer = to_whom_should_we_reply(msg)
if busy then
if is_private_chat then
-- If somebody messages us in a private chat when we are busy,
-- autoresponder FTW.
handle_busy(msg, peer)
end
return
end
if ignore_commands then
return
end
-- See `handle_our_own_message`
local command, params = msg.text:match("^(!%a*)%s?(.*)$")
if command then
if commands[command] then
commands[command](peer, params, msg)
end
end
end
function on_our_id (id)
our_id = id
end
function on_user_update(user, what)
end
function on_chat_update(chat, what)
end
function on_secret_chat_update(chat, what)
end
function on_get_difference_end()
end
function cron()
-- Insert here the code to run every `RUN_CRON_EVERY` seconds.
postpone(cron, false, RUN_CRON_EVERY)
end
function on_binlog_replay_end()
if LOG_MESSAGES then
logfile = assert(io.open(LOG_FILE, "a"))
end
postpone(cron, false, RUN_CRON_EVERY)
started = true
print("We are online.")
end
-------------------------------------------------------------------------------
-- Own commands
-- Says "Sciò" to somebody. Extremely silly.
register_own_command("!shoo", function(peer, params, msg)
if #params == 0 then
params = DEFAULT_SHOO
end
send_msg(peer, params, ok_cb, false)
postpone(function ()
send_msg(peer, "Sciò", ok_cb, false)
end, false, 2.0)
end)
-- Spams a message 10 times - silly, prone to abuse and prolly badly written.
register_own_command("!spam", function(peer, params, msg)
if #params == 0 or params:match("!spam") then
params = DEFAULT_SPAM
end
for i=1,10 do
postpone(function ()
if not ignore_commands then
send_msg(peer, params, ok_cb, False)
end
end, false, i)
end
end)
--[[
-- Old, spammy version of the command - use this coupled with !spam (!spam)* to
-- absolutely flood a chat with messages.
-- No, this wasn't really what I wanted.
register_own_command("!spam", function(peer, params, msg)
if #params == 0 then
params = DEFAULT_SPAM
end
for i=1,10 do
postpone(function ()
send_msg(peer, params, ok_cb, False)
end, false, i)
end
end)
]]
-- Ignore commands - global.
register_own_command("!shtap", function(peer, params, msg)
ignore_commands = true
end)
-- Accept commands again - global.
register_own_command("!go_for_it", function(peer, params, msg)
ignore_commands = false
end)
-- Sets `busy` to true - the bot will ignore commands and reply to private
-- messages with strings from the busy messages table.
register_own_command("!busy", function(peer, params, msg)
busy = true
end)
-- Sets `busy` to false - the bot will now reply to messages and stop replying
-- to private messages.
register_own_command("!free", function(peer, params, msg)
busy = false
end)
-- Self-destructing messages
-- Doesn't work with private chats or normal groups
-- Didn't test it on supergroups
--[[register_own_command("!sd", function(peer, params, msg)
postpone(function ()
delete_msg(msg.id, ok_cb, false)
end, false, 5.0)
end)]]
-------------------------------------------------------------------------------
-- Commands accessible by other users
-- Take care with these, as they are very prone to abuse
-- Reply to `!ping` with `pong` - yes, silly and prone to abuse
register_command("!ping", function (peer, params, msg)
send_msg(peer, "pong", ok_cb, false)
end)
|
local pnode = cat.require"module/game/scene/node/position_node"
local image = cat.class("image",pnode){
assets_name = nil,
}
function image:__init__(path,x,y,r,sx,sy)
pnode.__init__(self,x,y)
self.assets_name = path
self.r = r or 0
self.sx = sx or 1
self.sy = sy or 1
end
function image:draw()
cat.graphics.draw(self.assets_name,self.position.x,self.position.y,self.r,self.sx,self.sy)
end
return image
|
-- init.lua --
-- Global Variables (Modify for your network)
ssid = "strawberrybush"
pass = ""
-- Configure Wireless Internet
wifi.setmode(wifi.STATION)
-- print('set mode=STATION (mode='..wifi.getmode()..')\n')
-- print('MAC Address: ',wifi.sta.getmac())
-- print('Chip ID: ',node.chipid())
-- print('Heap Size: ',node.heap(),'\n')
-- wifi config start
wifi.sta.config(ssid,pass)
-- wifi config end
-- Run the main file
dofile("main.lua")
|