hexsha
stringlengths
40
40
size
int64
5
129k
content
stringlengths
5
129k
avg_line_length
float64
4
98.3
max_line_length
int64
5
660
alphanum_fraction
float64
0.25
0.98
10ac7a23eb2a746d9b1bdc530517601f1f49f761
24,870
-- -- Copyright (C) 2017-2019 DBot -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. class PPM2.NetworkChangeState new: (key = '', keyValid = '', newValue, obj, len = 24, ply = NULL) => @key = key @keyValid = keyValid @oldValue = obj[key] @newValue = newValue @ply = ply @time = CurTimeL() @rtime = RealTimeL() @stime = SysTime() @obj = obj @objID = obj.netID @len = len @rlen = len - 24 -- ID - 16 bits, variable id - 8 bits @cantApply = false @networkChange = true GetPlayer: => @ply ChangedByClient: => not @networkChange or IsValid(@ply) ChangedByPlayer: => not @networkChange or IsValid(@ply) ChangedByServer: => not @networkChange or not IsValid(@ply) GetKey: => @keyValid GetVariable: => @keyValid GetVar: => @keyValid GetKeyInternal: => @key GetVariableInternal: => @key GetVarInternal: => @key GetNewValue: => @newValue GetValue: => @newValue GetCantApply: => @cantApply SetCantApply: (val) => @cantApply = val NewValue: => @newValue GetOldValue: => @oldValue OldValue: => @oldValue CurTime: => @time GetCurTime: => @time GetReceiveTime: => @time GetReceiveStamp: => @time RealTimeL: => @rtime GetRealTimeL: => @rtime SysTime: => @stime GetSysTime: => @stime GetObject: => @obj GetNWObject: => @obj GetNetworkedObject: => @obj GetLength: => @rlen GetRealLength: => @len ChangedByNetwork: => @networkChange Revert: => @obj[@key] = @oldValue if not @cantApply Apply: => @obj[@key] = @newValue if not @cantApply do nullify = -> ProtectedCall -> for _, ent in ipairs ents.GetAll() ent.__PPM2_PonyData\Remove() if ent.__PPM2_PonyData for _, ent in ipairs ents.GetAll() ent.__PPM2_PonyData = nil nullify() timer.Simple 0, -> timer.Simple 0, -> timer.Simple 0, nullify hook.Add 'InitPostEntity', 'PPM2.FixSingleplayer', nullify wUInt = (def = 0, size = 8) -> return (arg = def) -> net.WriteUInt(arg, size) wInt = (def = 0, size = 8) -> return (arg = def) -> net.WriteInt(arg, size) rUInt = (size = 8, min = 0, max = 255) -> return -> math.Clamp(net.ReadUInt(size), min, max) rInt = (size = 8, min = -128, max = 127) -> return -> math.Clamp(net.ReadInt(size), min, max) rFloat = (min = 0, max = 255) -> return -> math.Clamp(net.ReadFloat(), min, max) wFloat = net.WriteFloat rBool = net.ReadBool wBool = net.WriteBool rColor = net.ReadColor wColor = net.WriteColor rString = net.ReadString wString = net.WriteString class NetworkedPonyData extends PPM2.ModifierBase @AddNetworkVar = (getName = 'Var', readFunc = (->), writeFunc = (->), defValue, onSet = ((val) => val), networkByDefault = true) => defFunc = defValue defFunc = (-> defValue) if type(defValue) ~= 'function' strName = "_NW_#{getName}" @NW_NextVarID += 1 id = @NW_NextVarID tab = {:strName, :readFunc, :getName, :writeFunc, :defValue, :defFunc, :id, :onSet} table.insert(@NW_Vars, tab) @NW_VarsTable[id] = tab @__base[strName] = defFunc() @__base["Get#{getName}"] = => @[strName] @__base["Set#{getName}"] = (val = defFunc(), networkNow = networkByDefault) => oldVal = @[strName] nevVal = onSet(@, val) @[strName] = nevVal state = PPM2.NetworkChangeState(strName, getName, nevVal, @) state.networkChange = false @SetLocalChange(state) return unless networkNow and @NETWORKED and (CLIENT and @ent == LocalPlayer() or SERVER) net.Start(@@NW_Modify) net.WriteUInt(@GetNetworkID(), 16) net.WriteUInt(id, 16) writeFunc(nevVal) net.SendToServer() if CLIENT net.Broadcast() if SERVER @NetworkVar = (...) => @AddNetworkVar(...) @GetSet = (fname, fvalue) => @__base["Get#{fname}"] = => @[fvalue] @__base["Set#{fname}"] = (fnewValue = @[fvalue]) => oldVal = @[fvalue] @[fvalue] = fnewValue state = PPM2.NetworkChangeState(fvalue, fname, fnewValue, @) state.networkChange = false @SetLocalChange(state) @NW_WAIT = {} if CLIENT hook.Add 'OnEntityCreated', 'PPM2.NW_WAIT', (ent) -> timer.Simple 0, -> return if not IsValid(ent) dirty = false entid = ent\EntIndex() ttl = RealTimeL() for controller in *@NW_WAIT if controller.removed controller.isNWWaiting = false dirty = true elseif controller.waitEntID == entid controller.isNWWaiting = false controller.ent = ent controller.modelCached = ent\GetModel() controller\SetupEntity(ent) --print('FOUND', ent) dirty = true elseif controller.waitTTL < ttl dirty = true controller.isNWWaiting = false if dirty @NW_WAIT = [controller for controller in *@NW_WAIT when controller.isNWWaiting] hook.Add 'NotifyShouldTransmit', 'PPM2.NW_WAIT', (ent, should) -> timer.Simple 0, -> return if not IsValid(ent) dirty = false entid = ent\EntIndex() ttl = RealTimeL() for controller in *@NW_WAIT if controller.removed controller.isNWWaiting = false dirty = true elseif controller.waitEntID == entid controller.isNWWaiting = false controller.ent = ent controller.modelCached = ent\GetModel() controller\SetupEntity(ent) --print('FOUND', ent) dirty = true elseif controller.waitTTL < ttl dirty = true controller.isNWWaiting = false if dirty @NW_WAIT = [controller for controller in *@NW_WAIT when controller.isNWWaiting] @OnNetworkedCreated = (ply = NULL, len = 0, nwobj) => if CLIENT netID = net.ReadUInt16() entid = net.ReadUInt16() obj = @NW_Objects[netID] or @(netID, entid) obj.NETWORKED = true obj.CREATED_BY_SERVER = true obj.NETWORKED_PREDICT = true obj\ReadNetworkData() else ply[@NW_CooldownTimer] = ply[@NW_CooldownTimer] or 0 ply[@NW_CooldownTimerCount] = ply[@NW_CooldownTimerCount] or 0 if ply[@NW_CooldownTimer] < RealTimeL() ply[@NW_CooldownTimerCount] = 1 ply[@NW_CooldownTimer] = RealTimeL() + 10 else ply[@NW_CooldownTimerCount] += 1 if ply[@NW_CooldownTimerCount] >= 3 ply[@NW_CooldownMessage] = ply[@NW_CooldownMessage] or 0 if ply[@NW_CooldownMessage] < RealTimeL() PPM2.Message 'Player ', ply, " is creating #{@__name} too quickly!" ply[@NW_CooldownMessage] = RealTimeL() + 1 return waitID = net.ReadUInt16() obj = @(nil, ply) obj.NETWORKED_PREDICT = true obj\ReadNetworkData() obj\Create() timer.Simple 0.5, -> return if not IsValid(ply) net.Start(@NW_ReceiveID) net.WriteUInt(waitID, 16) net.WriteUInt(obj.netID, 16) net.Send(ply) @OnNetworkedModify = (ply = NULL, len = 0) => id = net.ReadUInt16() obj = @NW_Objects[id] unless obj return if CLIENT net.Start(@NW_Rejected) net.WriteUInt(id, 16) net.Send(ply) return if IsValid(ply) and obj.ent ~= ply error('Invalid realm for player being specified. If you are running on your own net.* library, check up your code') if CLIENT net.Start(@NW_Rejected) net.WriteUInt(id, 16) net.Send(ply) return varID = net.ReadUInt16() varData = @NW_VarsTable[varID] return unless varData {:strName, :getName, :readFunc, :writeFunc, :onSet} = varData newVal = onSet(obj, readFunc()) return if newVal == obj["Get#{getName}"](obj) state = PPM2.NetworkChangeState(strName, getName, newVal, obj, len, ply) state\Apply() obj\NetworkDataChanges(state) if SERVER net.Start(@NW_Modify) net.WriteUInt(id, 16) net.WriteUInt(varID, 16) writeFunc(newVal) net.SendOmit(ply) @OnNetworkedDelete = (ply = NULL, len = 0) => id = net.ReadUInt16() obj = @NW_Objects[id] return unless obj obj\Remove(true) @ReadNetworkData = => output = {strName, {getName, readFunc()} for _, {:getName, :strName, :readFunc} in ipairs @NW_Vars} return output @RenderTasks = {} @CheckTasks = {} @NW_Vars = {} @NW_VarsTable = {} @NW_Objects = {} @O_Slots = {} if CLIENT @NW_Waiting = {} @NW_WaitID = -1 @NW_NextVarID = -1 @NW_Create = 'PPM2.NW.Created' @NW_Modify = 'PPM2.NW.Modified' @NW_Broadcast = 'PPM2.NW.ModifiedBroadcast' @NW_Remove = 'PPM2.NW.Removed' @NW_Rejected = 'PPM2.NW.Rejected' @NW_ReceiveID = 'PPM2.NW.ReceiveID' @NW_CooldownTimerCount = 'ppm2_NW_CooldownTimerCount' @NW_CooldownTimer = 'ppm2_NW_CooldownTimer' @NW_CooldownMessage = 'ppm2_NW_CooldownMessage' @NW_NextObjectID = 0 @NW_NextObjectID_CL = 0x60000 if SERVER net.pool(@NW_Create) net.pool(@NW_Modify) net.pool(@NW_Remove) net.pool(@NW_ReceiveID) net.pool(@NW_Rejected) net.pool(@NW_Broadcast) net.Receive @NW_Create, (len = 0, ply = NULL, obj) -> @OnNetworkedCreated(ply, len, obj) net.Receive @NW_Modify, (len = 0, ply = NULL, obj) -> @OnNetworkedModify(ply, len, obj) net.Receive @NW_Remove, (len = 0, ply = NULL, obj) -> @OnNetworkedDelete(ply, len, obj) net.Receive @NW_ReceiveID, (len = 0, ply = NULL) -> return if SERVER waitID = net.ReadUInt16() netID = net.ReadUInt16() obj = @NW_Waiting[waitID] @NW_Waiting[waitID] = nil return unless obj obj.NETWORKED = true @NW_Objects[obj.netID] = nil obj.netID = netID obj.waitID = nil @NW_Objects[netID] = obj net.Receive @NW_Rejected, (len = 0, ply = NULL) -> return if SERVER netID = net.ReadUInt16() obj = @NW_Objects[netID] return unless obj return if obj.__LastReject and obj.__LastReject > RealTimeL() obj.__LastReject = RealTimeL() + 3 obj.NETWORKED = false obj\Create() net.Receive @NW_Broadcast, (len = 0, ply = NULL) -> return if SERVER netID = net.ReadUInt16() obj = @NW_Objects[netID] return unless obj obj\ReadNetworkData(len, ply) @GetSet('UpperManeModel', 'm_upperManeModel') @GetSet('LowerManeModel', 'm_lowerManeModel') @GetSet('TailModel', 'm_tailModel') @GetSet('SocksModel', 'm_socksModel') @GetSet('NewSocksModel', 'm_newSocksModel') @NetworkVar('Fly', rBool, wBool, false) @NetworkVar('DisableTask', rBool, wBool, false) @NetworkVar('UseFlexLerp', rBool, wBool, true) @NetworkVar('FlexLerpMultiplier', rFloat(0, 10), wFloat, 1) @SetupModifiers: => for key, value in pairs PPM2.PonyDataRegistry if value.modifiers @RegisterModifier(value.getFunc, 0, 0) @SetModifierMinMaxFinal(value.getFunc, value.min, value.max) if value.min or value.max @SetupLerpTables(value.getFunc) strName = '_NW_' .. value.getFunc funcLerp = 'Calculate' .. value.getFunc @__base['Get' .. value.getFunc] = => @[funcLerp](@, @[strName]) for key, value in pairs PPM2.PonyDataRegistry @NetworkVar(value.getFunc, value.read, value.write, value.default) new: (netID, ent) => super() @m_upperManeModel = Entity(-1) @m_lowerManeModel = Entity(-1) @m_tailModel = Entity(-1) @m_socksModel = Entity(-1) @m_newSocksModel = Entity(-1) @recomputeTextures = true @isValid = true @removed = false @valid = true @NETWORKED = false @NETWORKED_PREDICT = false @[data.strName] = data.defFunc() for _, data in ipairs @@NW_Vars when data.defFunc if SERVER @netID = @@NW_NextObjectID @@NW_NextObjectID += 1 else netID = -1 if netID == nil @netID = netID @@NW_Objects[@netID] = @ if CLIENT for i = 1, 1024 if not @@O_Slots[i] @slotID = i @@O_Slots[i] = @ break if not @slotID error('dafuq? No empty slots are available') @isNWWaiting = false if type(ent) == 'number' entid = ent @waitEntID = entid ent = Entity(entid) --print(ent, entid) if not IsValid(ent) @isNWWaiting = true @waitTTL = RealTimeL() + 60 table.insert(@@NW_WAIT, @) PPM2.LMessage('message.ppm2.debug.race_condition') --print('WAITING ON ', entid) return return if not IsValid(ent) @ent = ent @modelCached = ent\GetModel() if IsValid(ent) @SetupEntity(ent) GetEntity: => @ent IsValid: => @isValid GetModel: => @modelCached EntIndex: => @entID ObjectSlot: => @slotID GetObjectSlot: => @slotID Clone: (target = @ent) => copy = @@(nil, target) @ApplyDataToObject(copy) return copy SetupEntity: (ent) => if ent.__PPM2_PonyData return if ent.__PPM2_PonyData\GetOwner() and IsValid(ent.__PPM2_PonyData\GetOwner()) and ent.__PPM2_PonyData\GetOwner() ~= @GetOwner() ent.__PPM2_PonyData\Remove() if ent.__PPM2_PonyData.Remove and ent.__PPM2_PonyData ~= @ ent.__PPM2_PonyData = @ @entTable = @ent\GetTable() return unless IsValid(ent) @modelCached = ent\GetModel() ent\PPMBonesModifier() @flightController = PPM2.PonyflyController(@) @entID = ent\EntIndex() @lastLerpThink = RealTimeL() @ModelChanges(@modelCached, @modelCached) @Reset() timer.Simple(0, -> @GetRenderController()\CompileTextures() if @GetRenderController()) if CLIENT PPM2.DebugPrint('Ponydata ', @, ' was updated to use for ', @ent) @@RenderTasks = [task for i, task in pairs @@NW_Objects when task\IsValid() and IsValid(task.ent) and not task.ent\IsPlayer() and not task\GetDisableTask()] @@CheckTasks = [task for i, task in pairs @@NW_Objects when task\IsValid() and IsValid(task.ent) and not task\GetDisableTask()] ModelChanges: (old = @ent\GetModel(), new = old) => @modelCached = new @SetFly(false) if SERVER timer.Simple 0.5, -> return unless IsValid(@ent) @Reset() GenericDataChange: (state) => hook.Run 'PPM2_PonyDataChanges', @ent, @, state if state\GetKey() == 'Fly' and @flightController @flightController\Switch(state\GetValue()) if state\GetKey() == 'DisableTask' @@RenderTasks = [task for i, task in pairs @@NW_Objects when task\IsValid() and IsValid(task.ent) and not task.ent\IsPlayer() and not task\GetDisableTask()] @@CheckTasks = [task for i, task in pairs @@NW_Objects when task\IsValid() and IsValid(task.ent) and not task\GetDisableTask()] @GetSizeController()\DataChanges(state) if @ent and @GetBodygroupController() @GetBodygroupController()\DataChanges(state) if @ent and @GetBodygroupController() @GetWeightController()\DataChanges(state) if @ent and @GetWeightController() if CLIENT and @ent @GetRenderController()\DataChanges(state) if @GetRenderController() ResetScale: => if scale = @GetSizeController() scale\ResetScale() ModifyScale: => if scale = @GetSizeController() scale\ModifyScale() Reset: => if scale = @GetSizeController() scale\Reset() if CLIENT @GetWeightController()\Reset() if @GetWeightController() and @GetWeightController().Reset @GetRenderController()\Reset() if @GetRenderController() and @GetRenderController().Reset @GetBodygroupController()\Reset() if @GetBodygroupController() and @GetBodygroupController().Reset GetHoofstepVolume: => return 0.8 if @ShouldMuffleHoosteps() return 1 ShouldMuffleHoosteps: => return @GetSocksAsModel() or @GetSocksAsNewModel() PlayerRespawn: => return if not IsValid(@ent) @entTable.__cachedIsPony = @ent\IsPony() if not @entTable.__cachedIsPony return if @alreadyCalledRespawn @alreadyCalledRespawn = true @alreadyCalledDeath = true else @alreadyCalledRespawn = false @alreadyCalledDeath = false @ApplyBodygroups(CLIENT, true) @SetFly(false) if SERVER @ent\PPMBonesModifier() if scale = @GetSizeController() scale\PlayerRespawn() if weight = @GetWeightController() weight\PlayerRespawn() if CLIENT @deathRagdollMerged = false @GetRenderController()\PlayerRespawn() if @GetRenderController() @GetBodygroupController()\MergeModels(@ent) if IsValid(@ent) and @GetBodygroupController().MergeModels PlayerDeath: => return if not IsValid(@ent) if @ent.__ppmBonesModifiers @ent.__ppmBonesModifiers\Remove() @entTable.__cachedIsPony = @ent\IsPony() if not @entTable.__cachedIsPony return if @alreadyCalledDeath @alreadyCalledDeath = true else @alreadyCalledDeath = false @SetFly(false) if SERVER if scale = @GetSizeController() scale\PlayerDeath() if weight = @GetWeightController() weight\PlayerDeath() if CLIENT @DoRagdollMerge() @GetRenderController()\PlayerDeath() if @GetRenderController() DoRagdollMerge: => return if @deathRagdollMerged bgController = @GetBodygroupController() rag = @ent\GetRagdollEntity() if not bgController.MergeModels @deathRagdollMerged = true elseif IsValid(rag) @deathRagdollMerged = true bgController\MergeModels(rag) ApplyBodygroups: (updateModels = CLIENT) => @GetBodygroupController()\ApplyBodygroups(updateModels) if @ent SetLocalChange: (state) => @GenericDataChange(state) NetworkDataChanges: (state) => @GenericDataChange(state) SlowUpdate: => @GetBodygroupController()\SlowUpdate() if @GetBodygroupController() @GetWeightController()\SlowUpdate() if @GetWeightController() if scale = @GetSizeController() scale\SlowUpdate() Think: => RenderScreenspaceEffects: => time = RealTimeL() delta = time - @lastLerpThink @lastLerpThink = time if @isValid and IsValid(@ent) for _, change in ipairs @TriggerLerpAll(delta * 5) state = PPM2.NetworkChangeState('_NW_' .. change[1], change[1], change[2] + @['_NW_' .. change[1]], @) state\SetCantApply(true) @GenericDataChange(state) GetFlightController: => @flightController GetRenderController: => return if SERVER return @renderController if not @isValid if not @renderController or @modelCached ~= @modelRender @modelRender = @modelCached cls = PPM2.GetRenderController(@modelCached) if @renderController and cls == @renderController.__class @renderController.ent = @ent PPM2.DebugPrint('Skipping render controller recreation for ', @ent, ' as part of ', @) return @renderController @renderController\Remove() if @renderController @renderController = cls(@) @renderController.ent = @ent return @renderController GetWeightController: => return @weightController if not @isValid if not @weightController or @modelCached ~= @modelWeight @modelCached = @modelCached or @ent\GetModel() @modelWeight = @modelCached cls = PPM2.GetPonyWeightController(@modelCached) if @weightController and cls == @weightController.__class @weightController.ent = @ent PPM2.DebugPrint('Skipping weight controller recreation for ', @ent, ' as part of ', @) return @weightController @weightController\Remove() if @weightController @weightController = cls(@) @weightController.ent = @ent return @weightController GetSizeController: => return @scaleController if not @isValid if not @scaleController or @modelCached ~= @modelScale @modelCached = @modelCached or @ent\GetModel() @modelScale = @modelCached cls = PPM2.GetSizeController(@modelCached) if @scaleController and cls == @scaleController.__class @scaleController.ent = @ent PPM2.DebugPrint('Skipping size controller recreation for ', @ent, ' as part of ', @) return @scaleController @scaleController\Remove() if @scaleController @scaleController = cls(@) @scaleController.ent = @ent return @scaleController GetScaleController: => @GetSizeController() GetBodygroupController: => return @bodygroups if not @isValid if not @bodygroups or @modelBodygroups ~= @modelCached @modelCached = @modelCached or @ent\GetModel() @modelBodygroups = @modelCached cls = PPM2.GetBodygroupController(@modelCached) if @bodygroups and cls == @bodygroups.__class @bodygroups.ent = @ent PPM2.DebugPrint('Skipping bodygroup controller recreation for ', @ent, ' as part of ', @) return @bodygroups @bodygroups\Remove() if @bodygroups @bodygroups = cls(@) @bodygroups.ent = @ent return @bodygroups Remove: (byClient = false) => @removed = true @@NW_Objects[@netID] = nil if SERVER or @NETWORKED @@O_Slots[@slotID] = nil if @slotID @isValid = false @ent = @GetEntity() if not IsValid(@ent) @entTable.__PPM2_PonyData = nil if IsValid(@ent) and @ent.__PPM2_PonyData == @ @GetWeightController()\Remove() if @GetWeightController() if CLIENT @GetRenderController()\Remove() if @GetRenderController() if IsValid(@ent) and @ent.__ppm2_task_hit @entTable.__ppm2_task_hit = false @ent\SetNoDraw(false) @GetBodygroupController()\Remove() if @GetBodygroupController() @GetSizeController()\Remove() if @GetSizeController() @flightController\Switch(false) if @flightController @@RenderTasks = [task for i, task in pairs @@NW_Objects when task\IsValid() and IsValid(task.ent) and not task.ent\IsPlayer() and not task\GetDisableTask()] @@CheckTasks = [task for i, task in pairs @@NW_Objects when task\IsValid() and IsValid(task.ent) and not task\GetDisableTask()] __tostring: => "[#{@@__name}:#{@netID}|#{@ent}]" GetOwner: => @ent IsNetworked: => @NETWORKED IsGoingToNetwork: => @NETWORKED_PREDICT SetIsGoingToNetwork: (val = @NETWORKED) => @NETWORKED_PREDICT = val IsLocal: => @isLocal IsLocalObject: => @isLocal GetNetworkID: => @netID NetworkID: => @netID NetID: => @netID ComputeMagicColor: => color = @GetHornMagicColor() if not @GetSeparateMagicColor() if not @GetSeparateEyes() color = @GetEyeIrisTop()\Lerp(0.5, @GetEyeIrisBottom()) else lerpLeft = @GetEyeIrisTopLeft()\Lerp(0.5, @GetEyeIrisBottomLeft()) lerpRight = @GetEyeIrisTopRight()\Lerp(0.5, @GetEyeIrisBottomRight()) color = lerpLeft\Lerp(0.5, lerpRight) return color ReadNetworkData: (len = 24, ply = NULL, silent = false, applyEntities = true) => data = @@ReadNetworkData() validPly = IsValid(ply) states = [PPM2.NetworkChangeState(key, keyValid, newVal, @, len, ply) for key, {keyValid, newVal} in pairs data] for _, state in ipairs states if not validPly or applyEntities or not isentity(state\GetValue()) state\Apply() @NetworkDataChanges(state) unless silent NetworkedIterable: (grabEntities = true) => data = [{getName, @[strName]} for _, {:strName, :getName} in ipairs @@NW_Vars when grabEntities or not isentity(@[strName])] return data ApplyDataToObject: (target, applyEntities = false) => target["Set#{key}"](target, value) for {key, value} in *@NetworkedIterable(applyEntities) when target["Set#{key}"] return target WriteNetworkData: => writeFunc(@[strName]) for _, {:strName, :writeFunc} in ipairs @@NW_Vars ReBroadcast: => return false if not @NETWORKED return false if CLIENT net.Start(@@NW_Broadcast) net.WriteUInt16(@netID) @WriteNetworkData() net.Broadcast() return true Create: => return if @NETWORKED return if CLIENT and @CREATED_BY_SERVER -- wtf @NETWORKED = true if SERVER @NETWORKED_PREDICT = true if SERVER net.Start(@@NW_Create) net.WriteUInt16(@netID) net.WriteEntity(@ent) @WriteNetworkData() filter = RecipientFilter() filter\AddAllPlayers() filter\RemovePlayer(@ent) if IsValid(@ent) and @ent\IsPlayer() net.Send(filter) else @@NW_WaitID += 1 @waitID = @@NW_WaitID net.Start(@@NW_Create) before = net.BytesWritten() net.WriteUInt16(@waitID) @WriteNetworkData() after = net.BytesWritten() net.SendToServer() @@NW_Waiting[@waitID] = @ return after - before NetworkTo: (targets = {}) => net.Start(@@NW_Create) net.WriteUInt16(@netID) net.WriteEntity(@ent) @WriteNetworkData() net.Send(targets) PPM2.NetworkedPonyData = NetworkedPonyData if CLIENT net.Receive 'PPM2.NotifyDisconnect', -> netID = net.ReadUInt16() data = NetworkedPonyData.NW_Objects[netID] return if not data data\Remove() net.Receive 'PPM2.PonyDataRemove', -> netID = net.ReadUInt16() data = NetworkedPonyData.NW_Objects[netID] return if not data data\Remove() else hook.Add 'PlayerJoinTeam', 'PPM2.TeamWaypoint', (ply, new) -> ply.__ppm2_modified_jump = false hook.Add 'OnPlayerChangedTeam', 'PPM2.TeamWaypoint', (ply, old, new) -> ply.__ppm2_modified_jump = false entMeta = FindMetaTable('Entity') entMeta.GetPonyData = => self2 = @ self = entMeta.GetTable(@) return if not @ if @__PPM2_PonyData and @__PPM2_PonyData.ent ~= self2 @__PPM2_PonyData.ent = self2 @__PPM2_PonyData\SetupEntity(self2) if CLIENT return @__PPM2_PonyData
31.322418
159
0.694733
14829ec86ca05e4f85a6536d5e993fa892f64e5d
1,077
[ { name: "Ether" address: "0x0000000000000000000000000000000000000000" symbol: "ETH" } { name: "Rinkebits" address: "0x8a75f985d5316b1a98bc11fe5364abbad55e1c7a" symbol: "RINK" } { name: "EOS" address: "0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0" symbol: "EOS" } { name: "TenXPay" address: "0xB97048628DB6B661D4C2aA833e95Dbe1A905B280" symbol: "PAY" } { name: "Golem" address: "0xa74476443119A942dE498590Fe1f2454d7D4aC0d" symbol: "GNT" } { name: "Salt" address: "0x4156D3342D5c385a87D264F90653733592000581" symbol: "SALT" } { name: "Basic Attention Token" address: "0x0D8775F648430679A709E98d2b0Cb6250d2887EF" symbol: "BAT" } { name: "Metal" address: "0xF433089366899D83a9f26A773D59ec7eCF30355e" symbol: "MTL" } { name: "Veritaseum" address: "0x8f3470A7388c05eE4e7AF3d01D8C722b0FF52374" symbol: "VERI" } { name: "ICONOMI" address: "0x888666CA69E0f178DED6D75b5726Cee99A87D698" symbol: "ICN" } ]
20.320755
58
0.647168
8df3b538a7c2d23d94bb91ba398c98fbba0f9de9
3,200
import concat from table unpack = unpack or table.unpack type = type moon = is_object: (value) -> -- is a moonscript object type(value) == "table" and value.__class is_a: (thing, t) -> return false unless type(thing) == "table" cls = thing.__class while cls if cls == t return true cls = cls.__parent false type: (value) -> -- the moonscript object class base_type = type value if base_type == "table" cls = value.__class return cls if cls base_type -- convet position in text to line number pos_to_line = (str, pos) -> line = 1 for _ in str\sub(1, pos)\gmatch("\n") line += 1 line trim = (str) -> str\match "^%s*(.-)%s*$" get_line = (str, line_num) -> -- todo: this returns an extra blank line at the end for line in str\gmatch "([^\n]*)\n?" return line if line_num == 1 line_num -= 1 get_closest_line = (str, line_num) -> line = get_line str, line_num if (not line or trim(line) == "") and line_num > 1 get_closest_line(str, line_num - 1) else line, line_num reversed = (seq) -> coroutine.wrap -> for i=#seq,1,-1 coroutine.yield i, seq[i] split = (str, delim) -> return {} if str == "" str ..= delim [m for m in str\gmatch("(.-)"..delim)] dump = (what) -> seen = {} _dump = (what, depth=0) -> t = type what if t == "string" '"'..what..'"\n' elseif t == "table" if seen[what] return "recursion("..tostring(what) ..")...\n" seen[what] = true depth += 1 lines = for k,v in pairs what (" ")\rep(depth*4).."["..tostring(k).."] = ".._dump(v, depth) seen[what] = false "{\n" .. concat(lines) .. (" ")\rep((depth - 1)*4) .. "}\n" else tostring(what).."\n" _dump what debug_posmap = (posmap, moon_code, lua_code) -> tuples = [{k, v} for k, v in pairs posmap] table.sort tuples, (a, b) -> a[1] < b[1] lines = for pair in *tuples lua_line, pos = unpack pair moon_line = pos_to_line moon_code, pos lua_text = get_line lua_code, lua_line moon_text = get_closest_line moon_code, moon_line "#{pos}\t #{lua_line}:[ #{trim lua_text} ] >> #{moon_line}:[ #{trim moon_text} ]" concat(lines, "\n") setfenv = setfenv or (fn, env) -> local name i = 1 while true name = debug.getupvalue fn, i break if not name or name == "_ENV" i += 1 if name debug.upvaluejoin fn, i, (-> env), 1 fn getfenv = getfenv or (fn) -> i = 1 while true name, val = debug.getupvalue fn, i break unless name return val if name == "_ENV" i += 1 nil -- moves the last argument to the front if it's a table, or returns empty table -- inserted to the front of args get_options = (...) -> count = select "#", ... opts = select count, ... if type(opts) == "table" opts, unpack {...}, nil, count - 1 else {}, ... safe_module = (name, tbl) -> setmetatable tbl, { __index: (key) => error "Attempted to import non-existent `#{key}` from #{name}" } { :moon, :pos_to_line, :get_closest_line, :get_line, :reversed, :trim, :split, :dump, :debug_posmap, :getfenv, :setfenv, :get_options, :unpack, :safe_module }
22.377622
85
0.58
b097d7e5c1e739d441b9bc2ed9796fe7db08dd48
2,288
path = (...)\gsub("[^%.]*$", "") view = require "view" pf = require "pathfun" PFM = require "pathfun.master" colours = require path .. "colours" global = require "global" import Vec2 from PFM M = {} nav = pf.Navigation() path = {} local current_poly local source, target draw_nav = -> love.graphics.setColor(colours.contour) for p in *nav.polygons if p.hidden then continue for i = 1, p.n if not p.connections[i] or p.connections[i].polygon.hidden A, B = p\get_edge(i) love.graphics.line(A.x, A.y, B.x, B.y) love.graphics.setColor(1,1,1) M.draw = () -> view\set() for pmap in *global.pmaps pmap.decomposition\draw(true) if not pmap.hidden draw_nav() for i = 1, #path - 1 A, B = path[i], path[i + 1] love.graphics.line(A.x, A.y, B.x, B.y) if target love.graphics.circle("fill", target.x, target.y, 2) if source love.graphics.circle("fill", source.x, source.y, 2) view\unset() love.graphics.setColor(1,1,1) M.mousemoved = (x, y) -> target = Vec2(view\get_coordinates(x, y)) if not source target = nav\_is_point_inside(target) and target or nav\_closest_boundary_point(target) return target = current_poly\is_point_inside_connected(target) and target or current_poly\closest_boundary_point_connected(target) if source and target path = nav\_shortest_path(source, target) M.mousepressed = (x, y, button) -> X, Y = view\get_coordinates(x, y) switch button when 2 source = Vec2(X, Y) current_poly = nav\_is_point_inside(source) if not current_poly source, current_poly = nav\_closest_boundary_point(source) path = {} target = nil M.keypressed = (key) -> M.mousereleased = -> nil M.set_visibility = (name, bool) -> for p in *(nav.name_groups[name] or {}) p.hidden = not bool source, target = nil path = {} M.clear = -> nav = pf.Navigation([pmap.decomposition.items for pmap in *global.pmaps]) for pmap in *global.pmaps if name = pmap.name M.set_visibility(name, not pmap.hidden) nav\initialize() source, target = nil path = {} return M
26.604651
95
0.604895
4e86a155ca0a511a6619225ffe7837c3c67bc19e
33,952
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) Buffer = require 'aullar.buffer' require 'ljglibs.cdefs.glib' ffi = require 'ffi' append = table.insert describe 'Buffer', -> describe '.text', -> it 'is a string representation of the contents', -> b = Buffer '' assert.equals '', b.text b = Buffer 'hello' assert.equals 'hello', b.text it 'setting it replaces the text completely with the new specified text', -> b = Buffer 'hello' b.text = 'brave new world' assert.equals 'brave new world', tostring b it 'sets the text as one undo', -> b = Buffer 'hello' b.text = 'brave new world' b\undo! assert.equals 'hello', b.text it 'errors out when setting for a read-only buffer', -> b = Buffer '1234567' b.read_only = true assert.raises 'read%-only', -> b.text = 'NO' describe '.multibyte', -> it 'returns true if the buffer contains multibyte characters', -> assert.is_false Buffer('vanilla').multibyte assert.is_true Buffer('HƏllo').multibyte it 'is updated whenever text is inserted', -> b = Buffer 'vanilla' b\insert 1, 'Bačon' assert.is_true b.multibyte it 'is updated whenever text is deleted', -> b = Buffer 'Bačon' start_p, end_p = b\byte_offset(3), b\byte_offset(4) b\delete start_p, end_p - start_p assert.is_false b.multibyte describe 'lines([start_line, end_line])', -> all_lines = (b) -> [ffi.string(l.ptr, l.size) for l in b\lines 1] context 'with no parameters passed', -> it 'returns a generator for all available lines in the buffer', -> b = Buffer 'line 1\nline 2\nline 3' assert.same { 'line 1', 'line 2', 'line 3', }, all_lines(b) it 'considers an empty last line as a line', -> b = Buffer 'line 1\n' assert.same { 'line 1', '', }, all_lines(b) it 'considers an empty buffer as having one line', -> b = Buffer '' assert.same { '', }, all_lines(b) it 'handles different types of line breaks', -> b = Buffer 'line 1\nline 2\r\nline 3\r' assert.same { 'line 1', 'line 2', 'line 3', '', }, all_lines(b) it 'is not confused by CR line breaks at the gap boundaries', -> b = Buffer 'line 1\r\nline 2' b.text_buffer\move_gap_to 7 assert.same { 'line 1', '', 'line 2' }, all_lines(b) b = Buffer 'line 1\n\nline 2' b.text_buffer\move_gap_to 7 assert.same { 'line 1', '', 'line 2' }, all_lines(b) it 'is not confused by multiple consecutive line breaks', -> b = Buffer 'line 1\n\nline 2' b\delete 8, 1 b\delete 7, 1 b\insert 7, '\n' assert.same { 'line 1', 'line 2', }, all_lines(b) it 'handles various gap positions automatically', -> b = Buffer 'line 1\nline 2' b.text_buffer\move_gap_to 0 assert.same { 'line 1', 'line 2' }, all_lines(b) b\insert 3, 'x' assert.same { 'lixne 1', 'line 2' }, all_lines(b) b\insert 9, 'air' assert.same { 'lixne 1', 'airline 2' }, all_lines(b) b\delete 3, 1 assert.same { 'line 1', 'airline 2' }, all_lines(b) b\delete 8, 3 assert.same { 'line 1', 'line 2' }, all_lines(b) it 'provides useful information about the line', -> b = Buffer 'line 1\nline 2' gen = b\lines! line = gen! assert.equals 1, line.nr assert.equals 6, line.size assert.equals 7, line.full_size assert.equals 1, line.start_offset assert.equals 7, line.end_offset assert.equals 'line 1', line.text assert.is_true line.has_eol line = gen! assert.equals 2, line.nr assert.equals 6, line.size assert.equals 6, line.full_size assert.equals 8, line.start_offset assert.equals 13, line.end_offset assert.equals 'line 2', line.text assert.is_false line.has_eol it 'correctly return line sizes given multi-byte line breaks', -> b = Buffer 'line 1\r\nline 2' gen = b\lines! line = gen! assert.equals 6, line.size assert.equals 8, line.full_size assert.is_true line.has_eol line = gen! assert.equals 6, line.size assert.equals 6, line.full_size describe 'pair_match_forward(offset, closing [, end_offset])', -> it 'returns the offset of the closing pair character', -> b = Buffer '1[34]6' assert.equals 5, b\pair_match_forward 2, ']' it 'handles nested pairs', -> b = Buffer '1[3[56]8]0' assert.equals 9, b\pair_match_forward 2, ']' it 'accounts for the gap', -> b = Buffer '1[3[56]8]0' gap_buffer = b.text_buffer for gap_pos = 1, 10 gap_buffer\move_gap_to gap_pos - 1 assert.equals 9, b\pair_match_forward 2, ']' it 'returns nil if no match was found', -> b = Buffer '1[3' assert.is_nil b\pair_match_forward 2, ']' it 'stops the search at <end_offset>', -> b = Buffer '1[34]6' assert.equals 5, b\pair_match_forward 2, ']', 6 assert.equals 5, b\pair_match_forward 2, ']', 5 assert.is_nil b\pair_match_forward 2, ']', 4 it 'match braces with identical style only', -> b = Buffer '1[3]5]7' b.styling.at = spy.new (pos) => styles = {nil, 'operator', nil, 'string', nil, 'operator'} return styles[pos] assert.equal 6, b\pair_match_forward 2, ']' describe 'pair_match_backward(offset, opening [, end_offset])', -> it 'returns the offset of the closing preceeding pair character', -> b = Buffer '1[34]6' assert.equals 2, b\pair_match_backward 5, '[' it 'handles nested pairs', -> b = Buffer '1[3[56]8]0' assert.equals 2, b\pair_match_backward 9, '[' it 'accounts for the gap', -> b = Buffer '1[3[56]8]0' gap_buffer = b.text_buffer for gap_pos = 1, 10 gap_buffer\move_gap_to gap_pos - 1 assert.equals 2, b\pair_match_backward 9, '[' it 'returns nil if no match was found', -> b = Buffer '12]4' assert.is_nil b\pair_match_backward 3, '[' it 'stops the search at <end_offset>', -> b = Buffer '1[34]6' assert.equals 2, b\pair_match_backward 5, '[', 1 assert.equals 2, b\pair_match_backward 5, '[', 2 assert.is_nil b\pair_match_backward 5, '[', 3 describe 'markers', -> local buffer, markers before_each -> buffer = Buffer '123456789' markers = buffer.markers it 'updates markers with inserts', -> markers\add { {name: 'test', start_offset: 2, end_offset: 4} } buffer\insert 1, '!' assert.same {}, markers\at 2 assert.same { name: 'test', start_offset: 3, end_offset: 5 }, markers\at(3)[1] buffer\insert 4, '!' assert.same { name: 'test', start_offset: 3, end_offset: 6 }, markers\at(3)[1] it 'updates markers with deletes', -> markers\add { {name: 'test', start_offset: 2, end_offset: 5} } buffer\delete 1, 1 assert.same {}, markers\at 5 assert.same { name: 'test', start_offset: 1, end_offset: 4 }, markers\at(1)[1] buffer\delete 2, 1 assert.same { name: 'test', start_offset: 1, end_offset: 3 }, markers\at(1)[1] buffer\delete 1, 2 assert.same {}, markers\at 1 describe 'get_line(nr)', -> it 'returns line information for the specified line', -> b = Buffer 'line 1\nline 2' line = b\get_line 2 assert.equals 2, line.nr assert.equals 6, line.size assert.equals 6, line.full_size assert.equals 8, line.start_offset assert.equals 13, line.end_offset assert.equals 'line 2', line.text it 'return nil for an out-of-bounds line', -> b = Buffer 'line 1\nline 2' assert.is_nil b\get_line 0 assert.is_nil b\get_line 3 it 'returns an empty first line for an empty buffer', -> b = Buffer '' line = b\get_line 1 assert.not_nil line assert.equals 0, line.size it 'works fine with a last empty line', -> b = Buffer '123\n' line = b\get_line 2 assert.is_not_nil line assert.equals 2, line.nr assert.equals '', line.text assert.equals 5, line.start_offset assert.equals 5, line.end_offset describe 'get_line_at_offset(offset)', -> it 'returns line information for the line at the specified offset', -> b = Buffer 'line 1\nline 2' line = b\get_line_at_offset 8 assert.equals 2, line.nr assert.equals 6, line.size assert.equals 8, line.start_offset assert.equals 13, line.end_offset it 'handles boundaries correctly', -> b = Buffer '123456\n\n901234' assert.is_nil b\get_line_at_offset -1 assert.is_nil b\get_line_at_offset 0 assert.equals 1, b\get_line_at_offset(1).nr assert.equals 1, b\get_line_at_offset(7).nr assert.equals 2, b\get_line_at_offset(8).nr assert.equals 3, b\get_line_at_offset(9).nr assert.equals 3, b\get_line_at_offset(14).nr assert.equals 3, b\get_line_at_offset(15).nr assert.is_nil b\get_line_at_offset(16) it 'returns an empty first line for an empty buffer', -> b = Buffer '' line = b\get_line_at_offset 1 assert.not_nil line assert.equals 0, line.size it 'works fine with a last empty line', -> b = Buffer '123\n' assert.is_not_nil b\get_line_at_offset(5) assert.equals 2, b\get_line_at_offset(5).nr describe '.nr_lines', -> it 'is the number lines in the buffer', -> b = Buffer 'line 1\nline 2' assert.equals 2, b.nr_lines b\insert 3, '\n\n' assert.equals 4, b.nr_lines b\insert b.size + 1, '\n' assert.equals 5, b.nr_lines b\delete 3, 1 assert.equals 4, b.nr_lines it 'is 1 for an empty string', -> b = Buffer '' assert.equals 1, b.nr_lines describe 'get_ptr(offset, size)', -> it 'returns a pointer to a char buffer starting at offset, valid for <size> bytes', -> b = Buffer '123456789' assert.equals '3456', ffi.string(b\get_ptr(3, 4), 4) it 'handles boundary conditions', -> b = Buffer '123' assert.equals '123', ffi.string(b\get_ptr(1, 3), 3) assert.equals '1', ffi.string(b\get_ptr(1, 1), 1) assert.equals '3', ffi.string(b\get_ptr(3, 1), 1) it 'raises errors for illegal values of offset and size', -> b = Buffer '123' assert.raises 'Illegal', -> b\get_ptr -1, 2 assert.raises 'Illegal', -> b\get_ptr 1, 4 assert.raises 'Illegal', -> b\get_ptr 3, 2 it 'returns a read-only pointer', -> b = Buffer '123' ptr = b\get_ptr 1, 1 assert.raises 'constant', -> ptr[0] = 88 it 'returns a "empty" pointer when size is zero', -> b = Buffer '' ptr = b\get_ptr 1, 0 assert.equals 0, ptr[0] describe 'sub(start_index [, end_index])', -> it 'returns a string for the given inclusive range', -> b = Buffer '123456789' assert.equals '234', b\sub(2, 4) b\delete 4, 1 assert.equals '678', b\sub(5, 7) b\insert 4, 'X' assert.equals '123X56789', b\sub(1, 9) it 'omitting end_index retrieves the contents until the end', -> b = Buffer '12345' assert.equals '2345', b\sub(2) assert.equals '5', b\sub(5) it 'specifying an end_index greater than size retrieves the contents until the end', -> b = Buffer '12345' assert.equals '2345', b\sub(2, 6) assert.equals '45', b\sub(4, 10) it 'specifying an start_index greater than size return an empty string', -> b = Buffer '12345' assert.equals '', b\sub(6, 6) assert.equals '', b\sub(6, 10) assert.equals '', b\sub(10, 12) it 'works fine with a last empty line', -> b = Buffer '123\n' assert.equals 2, b.nr_lines assert.equals '123\n', b\sub b\get_line(1).start_offset, b\get_line(2).end_offset describe 'insert(offset, text, size)', -> it 'inserts the given text at the specified position', -> b = Buffer 'hello world' b\insert 7, 'brave ' assert.equals 'hello brave world', tostring(b) it 'automatically extends the buffer as needed', -> b = Buffer 'hello world' big_text = string.rep 'x', 5000 b\insert 7, big_text assert.equals "hello #{big_text}world", tostring(b) it 'handles insertion at the end of the buffer (i.e. appending)', -> b = Buffer '' b\insert 1, 'hello\n' assert.equals 'hello\n', tostring(b) assert.equals 'hello', b\get_line(1).text b\insert b.size + 1, 'world' assert.equals 'hello\nworld', tostring(b) assert.equals 'world', b\get_line(2).text it 'invalidates any previous line information', -> b = Buffer '\n456\n789' line_text_ptr = b\get_line(3).ptr b\insert 1, '123' assert.not_equals line_text_ptr, b\get_line(3).ptr it 'updates the styling to keep the existing styling', -> b = Buffer '123\n567' b.styling\set 1, 7, 'keyword' b\insert 5, 'XX' assert.same { 1, 'keyword', 5, 7, 'keyword', 10 }, b.styling\get(1, 9) it 'errors out for a read-only buffer', -> b = Buffer '1234567' b.read_only = true assert.raises 'read%-only', -> b\insert 2, 'xx' describe 'delete(offset, count)', -> it 'deletes <count> bytes from <offset>', -> b = Buffer 'goodbye world' b\delete 5, 3 -- random access delete assert.equals 'good world', tostring(b) it 'handles boundary conditions', -> b = Buffer '123' b\delete 1, 3 assert.equals '', tostring(b) b.text = '123' b\delete 3, 1 assert.equals '12', tostring(b) it 'invalidates any previous line information', -> b = Buffer '123\n456\n789' line_text_ptr = b\get_line(3).ptr b\delete 1, 1 assert.not_equals line_text_ptr, b\get_line(3).ptr it 'updates the styling to keep the existing styling', -> b = Buffer '123\n567' b.styling\set 1, 3, 'keyword' b.styling\set 5, 7, 'string' b\delete 3, 3 assert.same { 1, 'keyword', 3, 3, 'string', 5 }, b.styling\get(1, 4) it 'errors out for a read-only buffer', -> b = Buffer '1234567' b.read_only = true assert.raises 'read%-only', -> b\delete 2, 1 describe 'replace(offset, count, replacement, replacement_size)', -> it 'replaces the specified number of characters with the replacement', -> b = Buffer '12 456 890' b\replace 1, 2, 'oh' b\replace 4, 3, 'hai' b\replace 8, 3, 'cat' assert.equals 'oh hai cat', b.text describe 'char_offset(byte_offset)', -> it 'returns the char_offset for the given byte_offset', -> b = Buffer 'äåö' for p in *{ {1, 1}, {3, 2}, {5, 3}, {7, 4}, } assert.equal p[2], b\char_offset p[1] describe 'byte_offset(char_offset)', -> it 'returns byte offsets for all character offsets passed as parameters', -> b = Buffer 'äåö' for p in *{ {1, 1}, {3, 2}, {5, 3}, {7, 4}, } assert.equal p[1], b\byte_offset p[2] describe '.length', -> it 'is the number of code points in the buffer', -> b = Buffer '' assert.equal 0, b.length b.text = '123' assert.equal 3, b.length b.text = 'äåö' assert.equal 3, b.length it 'updates automatically with modification', -> b = Buffer string.rep('äåö', 100) assert.equal 300, b.length for _ = 1, 40 cur_length = b.length pos = math.floor math.random(b.size - 10) insert_pos = b\byte_offset(b\char_offset(pos)) b\insert insert_pos, 'äåö' assert.equal cur_length + 3, b.length b\delete insert_pos, 2 -- delete 'ä' assert.equal cur_length + 2, b.length describe 'undo', -> it 'undoes the last operation', -> b = Buffer 'hello' b\delete 1, 1 b\undo! assert.equal 'hello', b.text it 'sets .part_of_revision for modification notifications', -> b = Buffer 'hello' flags = {} b\insert 1, 'x' b\delete 1, 1 b\add_listener { on_inserted: (_, buffer, args) -> append(flags, args.part_of_revision or 'fail') on_deleted: (_, buffer, args) -> append(flags, args.part_of_revision or 'fail') } b\undo! b\undo! assert.equal 'hello', b.text assert.same {true, true}, flags it 'errors out for a read-only buffer', -> b = Buffer '1234567' b\insert 2, 'foo' b.read_only = true assert.raises 'read%-only', -> b\undo! describe 'change(offset, count, f)', -> local buffer, notified, notified_styled, notified_markers before_each -> buffer = Buffer '' notified = nil l = { on_changed: (_, args) => notified = args on_styled: (_, args) => notified_styled = args on_markers_changed: (_, args) => notified_markers = args } buffer\add_listener l it 'invokes <f>, grouping all modification as one revision', -> buffer.text = '123456789' buffer\change 3, 3, (b) -> -- change '345' b\delete 4, 2 -- remove 45 b\insert 3, 'XY' assert.equal '12XY36789', buffer.text assert.equal 3, notified.offset assert.equal 3, notified.size assert.equal 'XY3', notified.text assert.equal '345', notified.prev_text buffer\undo! assert.equal '123456789', buffer.text it 'returns the return value of <f> as its own return value', -> buffer.text = '12345' ret = buffer\change 1, 3, -> 'zed' assert.equals 'zed', ret it 'provides a consistent state during the changes', -> jit.off! buffer.text = '123456789' assert.equal '123456789', buffer\get_line(1).text assert.equal 1, buffer.nr_lines buffer\change 3, 3, (b) -> -- change '345' b\delete 4, 2 -- remove 45 assert.equal '1236789', b\get_line(1).text b\insert 4, 'xy' assert.equal '123xy6789', b\get_line_at_offset(1).text b\insert 4, '\n\n' assert.equal 3, b.nr_lines it 'supports growing changes', -> buffer.text = '123456789' buffer\change 3, 3, (b) -> -- change '345' b\delete 4, 1 -- remove 4 b\insert 4, 'four' b\delete 7, 1 -- remove 'r' assert.equal '123fou56789', buffer.text assert.equal 3, notified.offset assert.equal 5, notified.size assert.equal '3fou5', notified.text assert.equal '345', notified.prev_text buffer\undo! assert.equal '123456789', buffer.text it 'supports appending changes', -> buffer.text = '1234' buffer\change 1, buffer.size, (b) -> b.text = '' b\insert 1, 'xxxx' b\insert 5, 'y' assert.equal 'xxxxy', buffer.text assert.equal 1, notified.offset assert.equal 5, notified.size assert.equal 'xxxxy', notified.text assert.equal '1234', notified.prev_text buffer\undo! assert.equal '1234', buffer.text it 'supports shrinking changes', -> buffer.text = '123456789' buffer\change 1, 4, (b) -> -- change '1234' b\delete 1, 3 -- remove 123 b\insert 1, 'X' assert.equal 'X456789', buffer.text assert.equal 1, notified.offset assert.equal 4, notified.size assert.equal 'X4', notified.text assert.equal '1234', notified.prev_text buffer\undo! assert.equal '123456789', buffer.text it 'supports changing from nothing to something', -> buffer.text = '123456789' buffer\change 3, 0, (b) -> -- change right before '3' b\insert 3, 'XYZ' b\delete 5, 1 assert.equal '12XY3456789', buffer.text assert.equal 3, notified.offset assert.equal 2, notified.size assert.equal 'XY', notified.text assert.equal '', notified.prev_text buffer\undo! assert.equal '123456789', buffer.text it 'supports changing from nothing to nothing', -> buffer.text = '123456789' buffer\change 3, 0, (b) -> -- change right before '3' b\insert 3, 'X' b\delete 3, 1 assert.equal '123456789', buffer.text assert.is_nil notified it 'supports changing from something to nothing', -> buffer.text = '123456789' buffer\change 3, 3, (b) -> -- change '345' b\delete 3, 3 assert.equal '126789', buffer.text assert.equal 3, notified.offset assert.equal 3, notified.size assert.equal '', notified.text assert.equal '345', notified.prev_text buffer\undo! assert.equal '123456789', buffer.text it 'collapses marker notification into one notification', -> buffer.text = '123456789' markers = buffer.markers buffer\change 1, 9, (b) -> markers\add { {name: 'first', start_offset: 2, end_offset: 4} } markers\add { {name: 'second', start_offset: 6, end_offset: 8} } assert.same { start_offset: 2, end_offset: 8 }, notified_markers describe 'styling notifications', -> describe 'when coupled with modifications', -> it 'collapses styling notifications in the change event', -> buffer.text = '123456789' buffer\change 3, 3, (b) -> -- change '345' b.styling\set 3, 4, 'string' b.styling\set 5, 6, 'keyword' b\delete 3, 3 assert.is_nil notified_styled assert.same { start_line: 1, end_line: 1, invalidated: true }, notified.styled it 'expands the styled range to cover all modified lines as needed', -> buffer.text = '12\n456\n890' buffer\change 1, 10, (b) -> b\delete 1, 1 b.styling\set 4, 5, 'string' b\delete 9, 1 assert.is_nil notified_styled assert.same { start_line: 1, end_line: 3, invalidated: true }, notified.styled describe 'when only styling changes are present', -> it 'fires a single on_styled notification', -> buffer.text = '12\n456\n890' buffer\change 1, 10, (b) -> b.styling\set 4, 5, 'string' b.styling\set 9, 10, 'keyword' assert.is_nil notified assert.same { start_line: 2, end_line: 3, invalidated: false }, notified_styled it 'bubbles up any errors in <f>', -> buffer.text = 'hello' assert.raises 'BOOM', -> buffer\change 1, 3, -> error 'BOOM' describe 'recursive changes', -> it 'is reentrant', -> buffer.text = '123456789' buffer\change 3, 3, (b) -> -- change '345' b\delete 4, 2 -- remove 45 b\change 3, 1, -> b\delete 3, 1 -- remove 3 b\insert 3, 'XY' assert.equal '12XY6789', buffer.text buffer\undo! assert.equal '123456789', buffer.text it 'handles border cases', -> buffer.text = '123' buffer\change 1, 3, (b) -> -- change all -- all these should work b\change 3, 1, -> nil b\change 2, 2, -> nil b\change 1, 3, -> nil -- insert one, to push the actual roof up b\change 1, 1, -> b\insert 1, 'X' -- and these should work b\change 4, 1, -> nil b\change 3, 2, -> nil b\change 1, 4, -> nil it 'is a no-op when no changes were made', -> buffer.text = 'hello' buffer\change 1, 3, -> nil assert.is_nil notified it 'raises an error for recursive out of range changes', -> buffer.text = '123456789' assert.raises "range", -> buffer\change 3, 3, (b) -> b\change(2, 1, ->) assert.raises "range", -> buffer\change 3, 3, (b) -> b\change(4, 3, ->) assert.raises "range", -> buffer\change 3, 3, (b) -> b\change(4, 3, ->) it 'raises an error for out-of-scope modifications', -> buffer.text = '123456789' assert.raises "range", -> buffer\change 3, 3, (b) -> b\insert 2, 'x' assert.raises "range", -> buffer\change 3, 3, (b) -> b\insert 7, 'x' describe '.can_undo', -> it 'returns true if there are any revisions to undo in the buffer', -> b = Buffer 'hello' assert.is_false b.can_undo b\insert 1, 'hola ' assert.is_true b.can_undo describe 'as_one_undo(f)', -> it 'invokes <f>, grouping all modification as one undo', -> b = Buffer 'hello' b\as_one_undo -> b\insert 6, ' world' b\delete 1, 5 b\insert 1, 'cruel' assert.equal 'cruel world', b.text b\undo! assert.equal 'hello', b.text it 'bubbles up any errors in <f>', -> b = Buffer 'hello' assert.raises 'BOOM', -> b\as_one_undo -> error 'BOOM' describe 'redo', -> it 'redoes the last undone operation', -> b = Buffer 'hello' b\delete 1, 1 b\undo! b\redo! assert.equal 'ello', b.text it 'sets .part_of_revision for modification notifications', -> b = Buffer '' b\insert 1, 'x' b\insert 1, 'y' b\undo! b\undo! flags = {} b\add_listener { on_inserted: (_, buffer, args) -> append(flags, args.part_of_revision or 'fail') on_deleted: (_, buffer, args) -> append(flags, args.part_of_revision or 'fail') } b\redo! b\redo! assert.same {true, true}, flags describe '.collect_revisions', -> it 'causes revisions to be skipped when false', -> b = Buffer '' b.collect_revisions = false b\insert 1, 'x' assert.is_false b.can_undo describe 'refresh_styling_at(line_nr, to_line [, opts])', -> local b, mode before_each -> b = Buffer '' mode = {} b.mode = mode context 'and <offset> is not part of a block', -> it 'refreshes only the current line', -> b.text = '123\n56\n89\n' b.lexer = spy.new -> { 1, 'operator', 2 } b.styling\apply 1, { 1, 'keyword', 4, 5, 'string', 7, 8, 'string', 9, } b\refresh_styling_at 2, 3 assert.spy(b.lexer).was_called_with '56\n' assert.same { 1, 'operator', 2 }, b.styling\get(5, 7) it 'falls back to a full lexing if newly lexed line is part of a block', -> b.text = '123\n56\n' lexers = { spy.new -> { 1, 'string', 5 }, spy.new -> { 1, 'string', 7 }, } call_count = 1 b.lexer = (text) -> l = lexers[call_count] assert.is_not_nil l call_count += 1 l(text) b\refresh_styling_at 1, 3 assert.spy(lexers[1]).was_called_with '123\n' assert.spy(lexers[2]).was_called_with '123\n56\n' assert.same { 1, 'string', 7 }, b.styling\get(1, 7) context 'and <offset> is at the last line of a block', -> it 'starts from the first non-block line', -> b.text = '123\n56\n89\n' b.lexer = spy.new -> { 1, 'operator', 6 } b.styling\apply 1, { 1, 'keyword', 4, 5, 'string', 10, -- block of line 2 & 3 } b\refresh_styling_at 3, 4 assert.spy(b.lexer).was_called_with '56\n89\n' assert.same { 1, 'operator', 4 }, b.styling\get(5, 7) assert.same { 1, 'operator', 3 }, b.styling\get(8, 10) context 'and <offset> is at a line within a block', -> it 'only lexes up to the current line if the new styling ends in the same block style', -> b.text = '123\n56\n89\n' b.lexer = spy.new -> { 1, 'my_block', 8 } b.styling\set 1, 10, 'my_block' res = b\refresh_styling_at 2, 3 assert.spy(b.lexer).was_called(1) assert.spy(b.lexer).was_called_with '123\n56\n' assert.same { start_line: 2, end_line: 2, invalidated: false }, res it 'lexes the full range if the new styling indicates a block change', -> b.text = '123\n56\n89\n' b.lexer = spy.new -> { 1, 'operator', 2 } b.styling\set 1, 10, 'my_block' res = b\refresh_styling_at 2, 3 assert.spy(b.lexer).was_called(2) assert.spy(b.lexer).was_called_with '123\n56\n' assert.spy(b.lexer).was_called_with '123\n56\n89\n' assert.same { start_line: 2, end_line: 3, invalidated: true }, res it 'returns the styled range', -> b.text = '123\n56\n89\n' b.lexer = spy.new -> { 1, 'operator', 2 } res = b\refresh_styling_at 1, 3 assert.same { start_line: 1, end_line: 1, invalidated: false }, res context 'when opts.force_full is set', -> it 'always lexes the full range', -> b.text = '123\n56\n89\n' b.lexer = spy.new -> { 1, 'operator', 2 } res = b\refresh_styling_at 1, 3, force_full: true assert.spy(b.lexer).was_called_with '123\n56\n89\n' assert.same { start_line: 1, end_line: 3, invalidated: true }, res context 'notifications', -> it 'fires the on_styled notification', -> listener = on_styled: spy.new -> b\add_listener listener b.text = '123\n56\n89\n' b.lexer = -> { 1, 'operator', 2 } b\refresh_styling_at 1, 3, force_full: true assert.spy(listener.on_styled).was_called 1 assert.spy(listener.on_styled).was_called_with listener, b, { start_line: 1, end_line: 3, invalidated: true } it 'sets the start offset from the first affected line regardless of the lexing', -> b.text = '123\n56\n89\n' b.lexer = spy.new -> { 1, 'string', 7 } b.styling\set 1, 6, 'string' -- block from 1st to 2nd line res = b\refresh_styling_at 2, 3 assert.spy(b.lexer).was_called_with '123\n56\n' -- both lines b.lexer due to block -- but only the second line is effectively restyled assert.same { start_line: 2, end_line: 2, invalidated: false }, res it 'supresses the on_styled notification if opts.no_notify is set', -> listener = on_styled: spy.new -> b\add_listener listener b.text = '123\n56\n89\n' b.lexer = -> { 1, 'operator', 2 } b\refresh_styling_at 1, 3, force_full: true, no_notify: true assert.spy(listener.on_styled).was_not_called! context 'when lexing the full range', -> before_each -> b.text = '123\n56\n89\n' b.styling\set 1, 10, 'keyword' it 'invalidates all subsequent styling', -> b.lexer = -> { 1, 'operator', 2 } b\refresh_styling_at 1, 2, force_full: true assert.same {}, b.styling\get(8, 10) it 'sets the styling last_pos_styled to the last line styled', -> b.lexer = -> { 1, 'operator', 2 } b\refresh_styling_at 1, 2, force_full: true assert.equals 7, b.styling.last_pos_styled b\refresh_styling_at 1, 3, force_full: true assert.equals 10, b.styling.last_pos_styled context 'meta methods', -> it 'tostring returns a lua string representation of the buffer', -> b = Buffer 'hello world' assert.equals 'hello world', tostring b context 'notifications', -> describe 'on_inserted', -> it 'is fired upon insertions to all interested listeners', -> l1 = on_inserted: spy.new -> nil l2 = on_inserted: spy.new -> nil b = Buffer 'hello' b\add_listener l1 b\add_listener l2 b\insert 3, 'xx' args = { offset: 3, text: 'xx', size: 2, invalidate_offset: 3, revision: b.revisions.entries[1] part_of_revision: false, lines_changed: false } assert.spy(l1.on_inserted).was_called_with l1, b, args assert.spy(l2.on_inserted).was_called_with l2, b, args describe 'on_deleted', -> it 'is fired upon deletions to listeners', -> l1 = on_deleted: spy.new -> nil b = Buffer 'hello' b\add_listener l1 b\delete 3, 2 assert.spy(l1.on_deleted).was_called_with l1, b, { offset: 3, text: 'll', size: 2, invalidate_offset: 3, revision: b.revisions.entries[1], part_of_revision: false, lines_changed: false } describe 'on_changed', -> it 'is fired upon changes to listeners', -> l1 = on_changed: spy.new -> nil b = Buffer 'hello' b\add_listener l1 b\change 2, 2, -> b\delete 2, 1 b\insert 2, 'X' assert.spy(l1.on_changed).was_called_with l1, b, { offset: 2, text: 'Xl', prev_text: 'el', size: 2, invalidate_offset: 2, revision: b.revisions.entries[1], part_of_revision: false, lines_changed: false, changes: { {type: 'deleted', offset: 2, size: 1}, {type: 'inserted', offset: 2, size: 1}, } } it 'fires on_styled notifications for styling changes outside of lexing', -> b = Buffer '12\n45' l = on_styled: spy.new -> nil b\add_listener l b.styling\set 1, 5, 'string' assert.spy(l.on_styled).was_called_with l, b, { start_line: 1, end_line: 2, invalidated: false } context 'resource management', -> it 'buffers are collected properly', -> b = Buffer 'foobar' l = on_styled: spy.new -> nil b\add_listener l buffers = setmetatable { b }, __mode: 'v' b = nil collect_memory! assert.is_nil buffers[1]
31.407956
96
0.578994
143290ad64f63f35a3c9ad864d30959f02838f22
51
-- The handler for / msgpage "Hello, Moonscript!"
12.75
28
0.686275
a5b9314166431c7ca8dbdf9b3f8fc46ff19e5ae9
4,943
require "tests/init" tx = ulx.TableX -- Save us typing ux = ulx.UtilX describe "Test Utilities", (using nil) -> it "Round() compliance", (using nil) -> assert.equal(41, ux.Round(41.41)) assert.equal(42, ux.Round(41.50, 0)) assert.equal(41, ux.Round(41.499999999999, 0)) assert.equal(410, ux.Round(414, -1)) assert.equal(41.41, ux.Round(41.4099, 2)) return it "CheckArg() basic compliance", (using nil) -> assert.True(ux.CheckArg("test", 1, "number", 41)) assert.True(ux.CheckArg("test", 2, "string", "41")) assert.True(ux.CheckArg("test", 3, "table", {})) assert.True(ux.CheckArg("test", 4, "function", (() ->))) assert.True(ux.CheckArg("test", 5, "boolean", true)) assert.True(ux.CheckArg("test", 6, "boolean", false)) assert.True(ux.CheckArg("test", 7, "nil", nil)) assert.True(ux.CheckArg("test", 8, ux, ux)) assert.True(ux.CheckArg("test", 9, ux, ux!)) assert.True(ux.CheckArg("test", 10, tx, tx)) assert.error(-> ux.CheckArg("test", 11, ux, tx)) assert.error(-> ux.CheckArg("test", 12, ux, tx!)) return it "CheckArg() corner cases", (using nil) -> assert.True(ux.CheckArg()) assert.True(ux.CheckArg("test")) assert.True(ux.CheckArg("test", 3)) assert.True(ux.CheckArg("test", 4, "function", (() ->))) assert.True(ux.CheckArg(nil, 5, "boolean", true)) assert.True(ux.CheckArg("test", nil, "boolean", false)) assert.True(ux.CheckArg("test", 7, nil, "41")) assert.True(ux.CheckArg(nil, nil, ux, ux)) assert.True(ux.CheckArg(nil, nil, nil, ux!)) assert.True(ux.CheckArg(nil, 10, nil, tx)) assert.error(-> ux.CheckArg("test", 11, ux, nil)) assert.error(-> ux.CheckArg(nil, 12, "string", nil)) assert.error(-> ux.CheckArg("test", nil, "string", 42)) assert.error(-> ux.CheckArg(nil, nil, "table", true)) return it "CheckArgs() compliance", (using nil) -> assert.True(ux.CheckArgs("test", {{"boolean", true}, {"string", "41"}})) assert.True(ux.CheckArgs("test", {{"number", 41}, {"string", "41"}, {"table", {}}, {"function", (() ->)}, {"boolean", true}, {"boolean", false}, {"nil", nil}, {ux, ux}, {ux, ux!}, {tx, tx}})) assert.error(-> ux.CheckArgs("test", {{ux, tx}})) assert.error(-> ux.CheckArgs("test", {{ux, tx!}})) return it "TimeStringToNumber() compliance", (using nil) -> assert.equal 41, ux.TimeStringToNumber(41), ux.TimeStringToNumber("41"), ux.TimeStringToNumber("41s"), ux.TimeStringToNumber("41 second"), ux.TimeStringToNumber("41 seconds") assert.equal 41*60, ux.TimeStringToNumber("41 m"), ux.TimeStringToNumber("41minute") assert.equal 39*60, ux.TimeStringToNumber("41m -3m 1m"), ux.TimeStringToNumber("41minute - 3minute 1 m") assert.equal 41*60*60, ux.TimeStringToNumber("41h"), ux.TimeStringToNumber("41 hours ") assert.equal 41*60*60 - 7*60, ux.TimeStringToNumber("41h -7m"), ux.TimeStringToNumber("41 hours -7 minutes") assert.equal 41*60*60*24, ux.TimeStringToNumber("41 d"), ux.TimeStringToNumber(" 41 day") assert.equal 41*60*60*24*7, ux.TimeStringToNumber("41 w"), ux.TimeStringToNumber("41weeks") assert.equal 41.5*60*60*24*7 - 11*60*60, ux.TimeStringToNumber("41.5 w - 11h"), ux.TimeStringToNumber("41.5weeks -11hours") assert.equal 3214991, ux.TimeStringToNumber("1M7d5h3m11s"), ux.TimeStringToNumber("1M 7d 5h 3m 11"), ux.TimeStringToNumber(" 1M 7d 5h 3m 11"), ux.TimeStringToNumber("1M 7d 5h 3m 11 "), ux.TimeStringToNumber("1M, 7d, 5h, 3m 11s"), ux.TimeStringToNumber("1M, 7d, 5h, 3m 11s "), ux.TimeStringToNumber("1 month 7 days, 5h 3minute, 11 seconds"), ux.TimeStringToNumber(" 1 month 7 days, 5h 3minute, 11 seconds ") assert.equal 60*60*24*365 - 6*60*60, ux.TimeStringToNumber("1 year - 6 hours") assert.equal 60*60*24*365 - 6.5*60*60 + 5*60, ux.TimeStringToNumber("1 year - 6.5 hours + 5 minutes") assert.equal 60*60*24*365 - 6*60*60 + 2*60, ux.TimeStringToNumber("1 year - 6 hours + 5 minutes - 3 minutes"), ux.TimeStringToNumber("1 year - 6 hours + 5 minutes - 3 minutes", "minute")*60*60, ux.TimeStringToNumber("1 year - 6 hours + 5 minutes - 3 minutes", "hour")*60*60 assert.equal 30, ux.TimeStringToNumber("31m-1", "minute"), ux.TimeStringToNumber("0.5h", "minute") return it "Explode() compliance", (using nil) -> assert.same {"This", "is", "a", "sentence"}, ux.Explode(" ", "This is a sentence") return it "SplitArgs() compliance", (using nil) -> assert.same {'This', 'is', 'a', 'Cool sentence to', 'make', 'split up'}, ux.SplitArgs('This is a "Cool sentence to" make "split up"') return
35.307143
85
0.598422
30042af0de241ea810d4efe61091cf4c402caf38
4,677
glib = require 'ljglibs.glib' {:activities, :config} = howl {:File} = howl.io {:icon, :StyledText} = howl.ui {:Matcher} = howl.util append = table.insert separator = File.separator howl.config.define name: 'file_icons' description: 'Whether file and directory icons are displayed' scope: 'global' type_of: 'boolean' default: true get_cwd = -> buffer = howl.app.editor and howl.app.editor.buffer directory = buffer and (buffer.file and buffer.file.parent or buffer.directory) return directory or File glib.get_current_dir! should_hide = (file) -> extensions = config.hidden_file_extensions return false unless extensions file_ext = file.extension for ext in *extensions if file_ext == ext return true return false display_name = (file, is_directory, base_directory) -> if file == base_directory return StyledText(".#{separator}", 'directory') rel_path = file\relative_to_parent(base_directory) if is_directory return StyledText(rel_path .. separator, 'directory') else return StyledText(rel_path, 'filename') display_icon = (is_directory) -> is_directory and icon.get('directory', 'directory') or icon.get('file', 'filename') get_dir_and_leftover = (path) -> if not path or path.is_blank or not File.is_absolute path directory = File.home_dir if not path or path.is_blank return directory, '' else path = tostring directory / path path = File.expand_path path root_marker = separator .. separator pos = path\rfind root_marker if pos path = path\sub pos + 1 unmatched = '' local closest_dir while not path.is_empty pos = path\rfind(separator) if pos unmatched = path\sub(pos + 1) .. unmatched path = path\sub 1, pos closest_dir = File path break if closest_dir.is_directory path = path\sub 1, -2 unmatched = separator .. unmatched break unless pos if closest_dir return closest_dir, unmatched return File(glib.get_current_dir!).root_dir, path file_matcher = (files, directory, allow_new=false) -> children = {} hidden_by_config = {} for file in *files is_directory = file.is_directory name = display_name(file, is_directory, directory) if should_hide file hidden_by_config[file.basename] = { StyledText(tostring(name), 'comment'), StyledText('[hidden]', 'comment'), :file name: tostring(name) :is_directory, } else append children, { name :file :is_directory, name: tostring(name) is_hidden: file.is_hidden } table.sort children, (f1, f2) -> d1, d2 = f1.is_directory, f2.is_directory h1, h2 = f1.is_hidden, f2.is_hidden return false if h1 and not h2 return true if h2 and not h1 return true if d1 and not d2 return false if d2 and not d1 f1.name < f2.name matcher = Matcher children return (text) -> hidden_exact_match = hidden_by_config[text] if hidden_exact_match append children, hidden_exact_match hidden_by_config[text] = nil matcher = Matcher children matches = moon.copy matcher(text) if config.file_icons for item in *matches unless item.has_icon append item, 1, display_icon(item.is_directory) item.has_icon = true if not text or text.is_blank or not allow_new return matches for item in *matches if item.name == text or item.name == text..separator return matches append matches, { text, StyledText('[New]', 'keyword') file: directory / text name: text is_new: true } if config.file_icons append matches[#matches], 1, icon.get('file-new', 'filename') return matches subtree_paths_matcher = (paths, directory, opts = {}) -> loader = -> with_icons = config.file_icons dir_icon = icon.get('directory', 'directory') file_icon = icon.get('file', 'filename') has_directories = not opts.only_files items = for i = 1, #paths activities.yield! if i % 1000 == 0 path = paths[i] is_directory = has_directories and path\ends_with(separator) d_name = StyledText(path, is_directory and 'directory' or 'filename') if with_icons used_icon = is_directory and dir_icon or file_icon { used_icon, d_name, :directory, :path } else { d_name, :directory, :path } Matcher(items, reverse: true) activities.run { title: "Loading paths from '#{directory}'" status: -> "Preparing #{#paths} paths for selection.." }, loader { :file_matcher, :get_cwd, :get_dir_and_leftover, :subtree_paths_matcher, }
25.697802
85
0.663887
d6c6b6f1eea9942dcb2110ec88902c0bf0ce35ce
3,099
export ^ class SoundManager new:() => @currentMusic = nil @bgm= {} @bgm.barAmbiance = love.audio.newSource("res/bgm/Jazz_Street_Trio_-_caught_sleeping.ogg", "stream") @bgm.barAmbiance\setLooping(true) @bgm.quietPlace = love.audio.newSource("res/bgm/WwoollfF_-_Saxy_Kenny__WwoollfF__cm_.ogg", "stream") @bgm.quietPlace\setLooping(true) @bgm.poker = love.audio.newSource("res/bgm/Jahzzar_-_Poker.ogg", "stream") @bgm.poker\setLooping(true) -- typewriter sounds @typeSounds: { love.audio.newSource("res/sfx/typewriter/edited/type01.ogg", "static") love.audio.newSource("res/sfx/typewriter/edited/type02.ogg", "static") love.audio.newSource("res/sfx/typewriter/edited/type03.ogg", "static") love.audio.newSource("res/sfx/typewriter/edited/type04.ogg", "static") love.audio.newSource("res/sfx/typewriter/edited/type05.ogg", "static") } @pullbackSounds: { love.audio.newSource("res/sfx/typewriter/edited/pullback01.ogg", "static") love.audio.newSource("res/sfx/typewriter/edited/pullback02.ogg", "static") } @bellSounds: { love.audio.newSource("res/sfx/typewriter/edited/bell01.ogg", "static") love.audio.newSource("res/sfx/typewriter/edited/bell02.ogg", "static") } -- generic slap sound @slapSounds: { love.audio.newSource("res/sfx/slap/117347__stereostereo__10-slap-real.ogg", "static") love.audio.newSource("res/sfx/slap/73535__macinino__door-slamming_slowed_faded.ogg", "static") } -- censored word sound @bubbleSounds: { love.audio.newSource("res/sfx/bubbles/192501__murraysortz__bubbles-quick.ogg", "static") love.audio.newSource("res/sfx/bubbles/261597__kwahmah-02__bubbles2.ogg", "static") love.audio.newSource("res/sfx/bubbles/104946__glaneur-de-sons__bubble-7.ogg", "static") } @popSounds: { love.audio.newSource("res/sfx/dialog/244654__greenvwbeetle__pop-2.ogg", "static") love.audio.newSource("res/sfx/dialog/244654__greenvwbeetle__pop-2_slow.ogg", "static") } @playOneOf: (soundArray) => index = math.random(#soundArray) if soundArray[index]\isPlaying() soundArray[index]\rewind() else soundArray[index]\play() playPop:(index)=> -- for pop only : no rewind if not @@popSounds[index]\isPlaying() @@popSounds[index]\play() playSlap:(index)=> if @@slapSounds[index]\isPlaying() @@slapSounds[index]\rewind() else @@slapSounds[index]\play() playAnyType:()=> @@playOneOf(@@typeSounds) playAnyBell:()=> @@playOneOf(@@bellSounds) playAnyPullBack:()=> @@playOneOf(@@pullbackSounds) playAnyBubble:()=> @@playOneOf(@@bubbleSounds) playMusic:(name)=> @stopMusic() if @bgm[name] @currentMusic=@bgm[name] @currentMusic\play() stopMusic:() => if @currentMusic @currentMusic\stop()
34.433333
108
0.632139
20e5346b0445fbf7bf3adfbdce99fae646f1ca1c
3,472
import Buffer, app, completion from howl require 'howl.completion.in_buffer_completer' require 'howl.variables.core_variables' describe 'InBufferCompleter', -> describe 'complete()', -> local buffer, lines factory = completion.in_buffer.factory complete_at = (pos) -> context = buffer\context_at pos completer = factory buffer, context completer\complete context before_each -> buffer = Buffer {} lines = buffer.lines it 'returns completions for local matches in the buffer', -> buffer.text = [[ Hello there some symbol (foo) { if yike { say_it = 'blarg' s } } other sion (arg) { saphire = 'that too' } ]] comps = complete_at buffer.lines[5].end_pos table.sort comps assert.same { 'saphire', 'say_it', 'sion', 'some', 'symbol' }, comps it 'does not include the token being completed itself', -> buffer.text = [[ text te noice test ]] assert.same { 'text', 'test' }, complete_at lines[2].end_pos - 1 assert.same { 'test' }, complete_at 3 it 'favours matches close to the current position', -> buffer.text = [[ two twitter tw other and other twice twitter ]] assert.same { 'twitter', 'two', 'twice' }, complete_at lines[3].end_pos it 'offers "smart" completions after the local ones', -> buffer.text = [[ two twitter _fatwa tw the_water ]] assert.same { 'twitter', 'two', 'the_water', '_fatwa' }, complete_at lines[4].end_pos it 'works with unicode', -> buffer.text = [[ hellö häst h ]] assert.same { 'häst', 'hellö' }, complete_at lines[3].end_pos it 'detects existing words using the word_pattern variable', -> buffer.text = [[ *foo*/-bar eat.food. * oo ]] buffer.config.word_pattern = '[^/%s.]+' assert.same { '*foo*' }, complete_at lines[3].end_pos context '(multiple buffers)', -> local buffer2, buffer3 before_each -> close_all_buffers! buffer2 = Buffer buffer.mode buffer2.text = 'foo\n' app\add_buffer buffer2, false buffer2.last_shown = 123 buffer3 = Buffer buffer.mode buffer3.text = 'fabulous\n' buffer3.last_shown = 12 app\add_buffer buffer3, false after_each -> app\close_buffer buffer2, true app\close_buffer buffer3, true it 'searches up to <config.inbuffer_completion_max_buffers> other buffers', -> buffer.text = 'fry\nf' comps = complete_at buffer.lines[2].end_pos table.sort comps assert.same { 'fabulous', 'foo', 'fry' }, comps buffer.config.inbuffer_completion_max_buffers = 2 comps = complete_at buffer.lines[2].end_pos table.sort comps assert.same { 'foo', 'fry' }, comps it 'prefers closer matches', -> buffer.text = 'fry\nf' comps = complete_at buffer.lines[2].end_pos assert.same { 'fry', 'foo', 'fabulous' }, comps it 'skips buffers with a different mode if <config.inbuffer_completion_same_mode_only> is true', -> buffer.config.inbuffer_completion_same_mode_only = true buffer2.mode = {} buffer.text = 'fry\nf' comps = complete_at buffer.lines[2].end_pos assert.same { 'fry', 'fabulous' }, comps buffer.config.inbuffer_completion_same_mode_only = false comps = complete_at buffer.lines[2].end_pos assert.same { 'fry', 'foo', 'fabulous' }, comps
26.105263
105
0.627016
3d397d6cd5d26c012f1f2a9b6a66bc641868cfd1
159
local * ffi = assert require "ffi" ffi.cdef [[ struct cell { int value; bool open, flag; }; ]] ffi.typeof "struct cell"
12.230769
26
0.503145
f783f0f3a9f9db26302e8ad401d8305ae705c356
1,536
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) flair = require 'aullar.flair' {:define_class} = require 'aullar.util' flair.define 'current-line', { type: flair.RECTANGLE, background: '#8294ab', background_alpha: 0.2, width: 'full', } flair.define 'current-line-overlay', { type: flair.SANDWICH, foreground: '#a3a3a3' } CurrentLineMarker = { new: (@view) => draw_before: (x, y, display_line, cr, clip, col) => @_offset = 1 @_height = display_line.height current_flair = flair.get 'current-line' if display_line.is_wrapped if @view.config.view_line_wrap_navigation == 'visual' @_offset = display_line.lines\at(col).line_start @_height = nil -- defaults to visual line current_flair.height = @_height flair.draw current_flair, display_line, @_offset, @_offset, x, y, cr draw_after: (x, y, display_line, cr, clip, col) => block = display_line.block overlay_flair = flair.get 'current-line-overlay' if block overlay_flair.width = block.width overlay_flair.height = @_height flair.draw overlay_flair, display_line, @_offset, @_offset, x, y, cr else overlay_flair.width = nil overlay_flair.height = nil bg_ranges = display_line.background_ranges return unless #bg_ranges > 0 for range in *bg_ranges flair.draw overlay_flair, display_line, range.start_offset, range.end_offset, x, y, cr } define_class CurrentLineMarker
28.444444
94
0.690755
3f147f2ca7a36e0521f01db269ea3bb17a4e3626
284
M = {} name = "run" U = require "umolflowFramework" TK = require("PackageToolkit") case = TK.test.case M[name] = -> fn = U.task.run case fn, {((i)-> i), 3}, {{1,2,3}}, "task.run case 1" case fn, {((i)-> i), 3, "1 2"}, {{1,2}}, "task.run case 2" return true return M
21.846154
62
0.53169
3691ba71b103fb6dedac5e081cca8c04f31ea430
1,112
-- ltypekit | 23.11.2018 -- By daelvn -- util functions color = (require "ansicolors") or ((x) -> x\gsub "%b{}","") warn = (s) -> print color "%{yellow}[WARN] #{s}" panic = (s) -> print color "%{red}[ERROR] #{s}" traceback = (s) => infot = {} for i=1,4 do infot[i] = debug.getinfo i print color "%{red}[ERROR] #{s}" print color "%{white} In function: %{yellow}#{infot[3].name}%{white}" print color " Signature: %{green}'#{@signature or "???"}'" print color " Stack traceback:" print color " %{red}#{infot[1].name}%{white} in #{infot[1].source} at line #{infot[1].currentline}" print color " %{red}#{infot[2].name}%{white} in #{infot[2].source} at line #{infot[2].currentline}" print color " %{red}#{infot[3].name}%{white} in #{infot[3].source} at line #{infot[3].currentline}" print color " %{red}#{infot[4].name}%{white} in #{infot[4].source} at line #{infot[4].currentline}" die = (s) => traceback @, s error! contains = (t, value) -> for val in *t do if val == value then return true {:warn, :panic, :die, :contains}
39.714286
110
0.569245
90f984e12ae1e8565c2795bd212e358e914d70e1
605
import Widget from require "lapis.html" class Layout extends Widget content: => html_5 -> head -> title "Just a chill room" link rel: "stylesheet", type: "text/css", href: "/static/semantic.min.css" style -> raw [[ body > .ui.container { margin-top: 3em; } ]] body -> @content_for "inner" script type: "text/javascript", src: "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js" script type: "text/javascript", src: "/static/semantic.min.js" @content_for "script_post"
31.842105
118
0.578512
9d5c7a8ffa48c995ee9af84baa0e5ce1e654d8e7
2,181
export script_name = 'JumpScroll' export script_description = 'Save/load subtitle grid scrollbar position (MSWindows only)' ok, ffi = pcall require, 'ffi' return if not ok or jit.os != 'Windows' ffi.cdef[[ uintptr_t GetForegroundWindow(); uintptr_t SendMessageA(uintptr_t hWnd, uintptr_t Msg, uintptr_t wParam, uintptr_t lParam); uintptr_t FindWindowExA(uintptr_t hWndParent, uintptr_t hWndChildAfter, uintptr_t lpszClass, uintptr_t lpszWindow); ]] jumpscroll_max = 3 jumpscroll = [nil for i=1,jumpscroll_max] h = nil msgs = {WM_VSCROLL:0x0115, SBM_SETPOS:0xE0, SBM_GETPOS:0xE1, SB_THUMBPOSITION:4, SB_ENDSCROLL:8, SB_SETTEXT:0x401} get_handle = -> if not h h = {} h.App = ffi.C.GetForegroundWindow! h.Statusbar = ffi.C.FindWindowExA h.App, 0, ffi.cast('uintptr_t','msctls_statusbar32'), 0 h.Container = ffi.C.FindWindowExA h.App, 0, ffi.cast('uintptr_t','wxWindowNR'), 0 h.SubsGrid = ffi.C.FindWindowExA h.Container, 0, 0, 0 h.Scrollbar = ffi.C.FindWindowExA h.SubsGrid, 0, 0, 0 h.App != 0 update_statusbar = (i, saved=true) -> if h.Statusbar ffi.C.SendMessageA h.Statusbar, msgs.SB_SETTEXT, 0, ffi.cast 'uintptr_t', ('JumpScroll #%d: %s position %d')\format i, saved and 'saved' or 'scrolled to', jumpscroll[i] save_scroll_pos = (i) -> return unless get_handle! jumpscroll[i] = tonumber ffi.C.SendMessageA h.Scrollbar, msgs.SBM_GETPOS, 0, 0 update_statusbar i load_scroll_pos = (i) -> return unless jumpscroll[i] and get_handle! ffi.C.SendMessageA h.SubsGrid, msgs.WM_VSCROLL, msgs.SB_THUMBPOSITION, h.Scrollbar ffi.C.SendMessageA h.Scrollbar, msgs.SBM_SETPOS, jumpscroll[i], 0 ffi.C.SendMessageA h.SubsGrid, msgs.WM_VSCROLL, msgs.SB_ENDSCROLL, h.Scrollbar update_statusbar i, false for i=1,jumpscroll_max aegisub.register_macro script_name..'/save/'..i, 'Remember subtitle grid scrollbar position as #'..i, -> save_scroll_pos i for i=1,jumpscroll_max aegisub.register_macro script_name..'/load/'..i, 'Scroll to subtitle grid scrollbar position previously saved in #'..i, -> load_scroll_pos i
38.263158
115
0.701972
d0311e57552cef6c81bc1a96a549c92a0b12548e
411
-- TDD style suite = describe test = it dashes = require 'dashes' suite 'Dash replacement', -> test 'with no n-dashes', -> line = "But what about the moving--" res = "But what about the moving—" assert.equals (dashes.mdash line), res test 'with n-dashes', -> line = "B-- But what about the moving---" res = "B– But what about the moving—" assert.equals (dashes.ndash line), res
25.6875
45
0.627737
d6214d5db497342ab5cf4c69e7d8ad8ce19857e4
510
import java from smaug Gdx = java.require "com.badlogic.gdx.Gdx" SmaugVM = java.require "smaug.SmaugVM" get_clipboard = -> Gdx.app\getClipboard!\getContents! set_clipboard = (v) -> Gdx.app\getClipboard!\setContents v get_os = -> SmaugVM.util\get_OS! get_memory = -> Gdx.app\getJavaHeap! open_url = (url) -> Gdx.net\openURI url vibrate = (ms) -> Gdx.input\vibrate ms quit = -> Gdx.app\exit! { :get_clipboard :get_os :get_memory :open_url :set_clipboard :vibrate :quit }
14.166667
45
0.67451
f0738415524f2d2dfce6b48c7ab7ad28730a6c8e
11,398
logger = require "lapis.logging" url = require "socket.url" session = require "lapis.session" import Router from require "lapis.router" import html_writer from require "lapis.html" import parse_cookie_string, to_json, build_url, auto_table from require "lapis.util" json = require "cjson" local capture_errors, capture_errors_json, respond_to set_and_truthy = (val, default=true) -> return default if val == nil val run_before_filter = (filter, r) -> _write = r.write written = false r.write = (...) -> written = true _write ... filter r r.write = nil written class Request new: (@app, @req, @res) => @buffer = {} -- output buffer @params = {} @options = {} @cookies = auto_table -> parse_cookie_string @req.headers.cookie @session = session.lazy_session @ add_params: (params, name) => self[name] = params for k,v in pairs params -- expand nested[param][keys] if front = k\match "^([^%[]+)%[" curr = @params for match in k\gmatch "%[(.-)%]" new = curr[front] if new == nil new = {} curr[front] = new curr = new front = match curr[front] = v else @params[k] = v -- render the request into the response -- do this last render: (opts=false) => @options = opts if opts session.write_session @ @write_cookies! if @options.status @res.status = @options.status if obj = @options.json @res.headers["Content-type"] = "application/json" @res.content = to_json obj return if ct = @options.content_type @res.headers["Content-type"] = ct if not @res.headers["Content-type"] @res.headers["Content-type"] = "text/html" if redirect_url = @options.redirect_to if redirect_url\match "^/" redirect_url = @build_url redirect_url @res\add_header "Location", redirect_url @res.status or= 302 has_layout = @app.layout and set_and_truthy(@options.layout, true) @layout_opts = if has_layout { inner: nil } widget = @options.render widget = @route_name if widget == true if widget if type(widget) == "string" widget = require "#{@app.views_prefix}.#{widget}" view = widget @options.locals @layout_opts.view_widget = view if @layout_opts view\include_helper @ @write view if has_layout inner = @buffer @buffer = {} layout_path = @options.layout layout_cls = if type(layout_path) == "string" require "#{@app.views_prefix}.#{layout_path}" else @app.layout @layout_opts.inner or= -> raw inner layout = layout_cls @layout_opts layout\include_helper @ layout\render @buffer if next @buffer content = table.concat @buffer @res.content = if @res.content @res.content .. content else content html: (fn) => html_writer fn url_for: (first, ...) => if type(first) == "table" @app.router\url_for first\url_params @, ... else @app.router\url_for first, ... -- @build_url! --> http://example.com:8080 -- @build_url "hello_world" --> http://example.com:8080/hello_world -- @build_url "hello_world?color=blue" --> http://example.com:8080/hello_world?color=blue -- @build_url "cats", host: "leafo.net", port: 2000 --> http://leafo.net:2000/cats -- Where example.com is the host of the request, and 8080 is current port build_url: (path, options) => return path if path and path\match "^%a+:" parsed = { k,v for k,v in pairs @req.parsed_url } parsed.query = nil if path _path, query = path\match("^(.-)%?(.*)$") path = _path or path parsed.query = query parsed.path = path if parsed.port == "80" parsed.port = nil if options for k,v in pairs options parsed[k] = v build_url parsed write: (...) => for thing in *{...} t = type(thing) -- is it callable? if t == "table" mt = getmetatable(thing) if mt and mt.__call t = "function" switch t when "string" table.insert @buffer, thing when "table" -- see if there are options for k,v in pairs thing if type(k) == "string" @options[k] = v else @write v when "function" @write thing @buffer when "nil" nil -- ignore else error "Don't know how to write: (#{t}) #{thing}" write_cookies: => return unless next @cookies extra = @app.cookie_attributes if extra extra = "; " .. table.concat @app.cookie_attributes, "; " for k,v in pairs @cookies cookie = "#{url.escape k}=#{url.escape v}; Path=/; HttpOnly" cookie ..= extra if extra @res\add_header "Set-cookie", cookie class Application Request: Request layout: require"lapis.views.layout" error_page: require"lapis.views.error" -- find action for named route in this application @find_action: (name) => @_named_route_cache or= {} route = @_named_route_cache[name] -- update the cache unless route for app_route in pairs @__base if type(app_route) == "table" app_route_name = next app_route @_named_route_cache[app_route_name] = app_route route = app_route if app_route_name == name route and @[route], route views_prefix: "views" new: => @build_router! enable: (feature) => fn = require "lapis.features.#{feature}" fn @ match: (route_name, path, handler) => if handler == nil handler = path path = route_name route_name = nil key = if route_name {[route_name]: path} else path @[key] = handler @router = nil handler for meth in *{"get", "post", "delete", "put"} upper_meth = meth\upper! @__base[meth] = (route_name, path, handler) => if handler == nil handler = path path = route_name route_name = nil @responders or= {} existing = @responders[route_name or path] tbl = { [upper_meth]: handler } if existing setmetatable tbl, __index: (key) => existing if key\match "%u" responder = respond_to tbl @responders[route_name or path] = responder @match route_name, path, responder build_router: => @router = Router! @router.default_route = => false add_route = (path, handler) -> t = type path if t == "table" or t == "string" and path\match "^/" @router\add_route path, @wrap_handler handler add_routes = (cls) -> for path, handler in pairs cls.__base add_route path, handler for path, handler in pairs @ add_route path, handler if parent = cls.__parent add_routes parent add_routes @@ wrap_handler: (handler) => (params, path, name, r) -> with r .route_name = name \add_params r.req.params_get, "GET" \add_params r.req.params_post, "POST" \add_params params, "url_params" if @before_filters for filter in *@before_filters return r if run_before_filter filter, r \write handler r dispatch: (req, res) => local err, trace, r success = xpcall (-> r = @.Request self, req, res unless @router\resolve req.parsed_url.path, r -- run default route if nothing matched handler = @wrap_handler self.default_route handler {}, nil, "default_route", r r\render! logger.request r), (_err) -> err = _err trace = debug.traceback "", 2 unless success self.handle_error r, err, trace res serve: => -- TODO: alias to lapis.serve @before_filter: (fn) => @__base.before_filters or= {} table.insert @before_filters, fn -- copies all actions into this application, preserves before filters -- @include other_app, path: "/hello", name: "hello_" @include: (other_app, opts, into=@__base) => if type(other_app) == "string" other_app = require other_app path_prefix = opts and opts.path or other_app.path name_prefix = opts and opts.name or other_app.name for path, action in pairs other_app.__base t = type path if t == "table" if path_prefix name = next path path[name] = path_prefix .. path[name] if name_prefix name = next path path[name_prefix .. name] = path[name] path[name] = nil elseif t == "string" and path\match "^/" if path_prefix path = path_prefix .. path else continue if before_filters = other_app.before_filters fn = action action = (r) -> for filter in *before_filters return if run_before_filter filter, r fn r into[path] = action -- Callbacks -- run with Request as self, instead of application default_route: => -- strip trailing / if @req.parsed_url.path\match "./$" stripped = @req.parsed_url.path\match "^(.+)/+$" redirect_to: @build_url(stripped, query: @req.parsed_url.query), status: 301 else @app.handle_404 @ handle_404: => error "Failed to find route: #{@req.cmd_url}" handle_error: (err, trace, [email protected]_page) => r = @app.Request self, @req, @res r\write { status: 500 layout: false content_type: "text/html" error_page { status: 500, :err, :trace } } r\render! logger.request r r respond_to = do default_head = -> layout: false -- render nothing (tbl) -> tbl.HEAD = default_head unless tbl.HEAD out = => fn = tbl[@req.cmd_mth] if fn if before = tbl.before return if run_before_filter before, @ fn @ else error "don't know how to respond to #{@req.cmd_mth}" if error_response = tbl.on_error out = capture_errors out, error_response out, tbl default_error_response = -> { render: true } capture_errors = (fn, error_response=default_error_response) -> if type(fn) == "table" error_response = fn.on_error or error_response fn = fn[1] (...) => co = coroutine.create fn out = { coroutine.resume co, @ } unless out[1] -- error error debug.traceback co, out[2] -- { status, "error", error_msgs } if coroutine.status(co) == "suspended" if out[2] == "error" @errors = out[3] error_response @ else -- yield to someone else error "Unknown yield" else unpack out, 2 capture_errors_json = (fn) -> capture_errors fn, => { json: { errors: @errors } } yield_error = (msg) -> coroutine.yield "error", {msg} assert_error = (thing, msg, ...) -> yield_error msg unless thing thing, msg, ... json_params = (fn) -> (...) => if content_type = @req.headers["content-type"] -- Header often ends with ;UTF-8 if string.find content_type\lower!, "application/json", nil, true local obj pcall -> obj, err = json.decode ngx.req.get_body_data! @add_params obj, "json" if obj fn @, ... { :Request, :Application, :respond_to :capture_errors, :capture_errors_json :json_params, :assert_error, :yield_error }
24.724512
91
0.592911
8f4ce508778592ccfb72f9b33dbc992eca5d8449
4,882
import runner from require "lapis.cmd.cqueues" import SpecServer from require "lapis.spec.server" server = SpecServer runner describe "server", -> setup -> server\load_test_server { app_class: "spec_cqueues.s1.app" } teardown -> server\close_test_server! it "should request basic page", -> status, res, headers = server\request "/" assert.same 200, status assert.same [[<!DOCTYPE HTML><html lang="en"><head><title>Lapis Page</title></head><body>Welcome to Lapis 1.7.0</body></html>]], res assert.same { content_type: "text/html" connection: "close" }, headers it "should request json page", -> status, res, headers = server\request "/world", { expect: "json" } assert.same 200, status assert.same { success: true }, res assert.same { content_type: "application/json" connection: "close" }, headers describe "params", -> it "dumps query params", -> status, res, headers = server\request "/dump-params?color=blue&color=green&height[oops]=9", { expect: "json" } assert.same 200, status assert.same { color: "green" height: { oops: "9" } }, res it "dumps post params", -> status, res, headers = server\request "/dump-params", { expect: "json" post: { color: "blue" "height[oops]": "9" } } assert.same 200, status assert.same { color: "blue" height: { oops: "9" } }, res it "dumps json params", -> status, res, headers = server\request "/dump-params", { expect: "json" method: "POST" headers: { "content-type": "application/json" } data: '{"thing": 1234}' } assert.same 200, status -- this route isn't json aware assert.same {}, res status, res, headers = server\request "/dump-json-params", { expect: "json" method: "POST" headers: { "content-type": "application/json" } data: '{"thing": 1234}' } assert.same { thing: 1234 }, res describe "csrf", -> import escape from require "lapis.util" import decode_with_secret from require "lapis.util.encoding" it "should get a csrf token", -> import parse_cookie_string from require "lapis.util" status, res, headers = server\request "/form", { expect: "json" } assert.same 200, status assert.truthy res.csrf_token assert.truthy headers.set_cookie cookies = parse_cookie_string headers.set_cookie assert.truthy cookies.lapis_session_token it "should get a csrf token from existing token", -> random_text = "hello world" status, res, headers = server\request "/form", { expect: "json" headers: { "Cookie": "lapis_session_token=#{escape random_text}" } } token = res.csrf_token assert.same { k: "hello world" }, decode_with_secret token it "rejects missing csrf token", -> random_text = "hello world" status, res, headers = server\request "/form", { expect: "json" post: { } headers: { "Cookie": "lapis_session_token=#{escape random_text}" } } assert.same { errors: { "missing csrf token" } }, res it "rejects invalid csrf token", -> random_text = "hello world" status, res, headers = server\request "/form", { expect: "json" post: { csrf_token: "hello world" } headers: { "Cookie": "lapis_session_token=#{escape random_text}" } } assert.same { errors: { "csrf: invalid format" } }, res csrf = require "lapis.csrf" token = csrf.generate_token { cookies: {} } status, res, headers = server\request "/form", { expect: "json" post: { csrf_token: token } headers: { "Cookie": "lapis_session_token=#{escape random_text}" } } assert.same { errors: { "csrf: token mismatch" } }, res it "accepts csrf token", -> status, res, headers = server\request "/form", { expect: "json" headers: {} } import parse_cookie_string from require "lapis.util" cookies = parse_cookie_string headers.set_cookie status, res, headers = server\request "/form", { expect: "json" post: { csrf_token: res.csrf_token } headers: { "Cookie": "lapis_session_token=#{escape cookies.lapis_session_token}" } } assert.same {success: true}, res assert.nil res.headers
23.358852
136
0.547522
af08e88adbb4880b1e7250c14923ded446dddb69
1,197
Dorothy! PopupPanelView = require "View.Control.Basic.PopupPanel" -- [signals] -- "Show",-> -- "Hide",-> -- [params] -- width,height Class PopupPanelView, __init:(args)=> @scrollArea\setupMenuScroll @menu @closeBtn\slot "Tapped",-> @hide! CCDirector.currentScene\addChild @,editor.topMost thread -> @show! show:=> @perform CCSequence { CCShow! oOpacity 0.3,0.6,oEase.OutQuad } @closeBtn.scaleX = 0 @closeBtn.scaleY = 0 @closeBtn\perform oScale 0.3,1,1,oEase.OutBack @panel.opacity = 0 @panel.scaleX = 0 @panel.scaleY = 0 @panel\perform CCSequence { CCSpawn { oOpacity 0.3,1,oEase.OutQuad oScale 0.3,1,1,oEase.OutBack } CCCall -> @scrollArea.touchEnabled = true @menu.enabled = true @opMenu.enabled = true @emit "Show" } hide:=> @scrollArea.touchEnabled = false @menu.enabled = false @opMenu.enabled = false @closeBtn\perform oScale 0.3,0,0,oEase.InBack @panel\perform CCSpawn { oOpacity 0.3,0,oEase.OutQuad oScale 0.3,0,0,oEase.InBack } @perform CCSequence { oOpacity 0.3,0,oEase.OutQuad CCCall -> @emit "Hide" @parent\removeChild @ }
22.166667
57
0.630744
551b03e5c719f69a29cb91466b03605a47bc5a90
195
define = require'classy'.define define 'Event', -> instance initialize: (type, data={}) => @type = type for k, v in pairs data continue if k == 'type' @[k] = v
19.5
34
0.528205
fee8e4b7d1554e5c03809053939ec7e166bcf6e1
6,460
-- Copyright 2013-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) pairs = pairs howl.util.lpeg_lexer -> c = capture ruby_pairs = { '(': ')' '{': '}' '[': ']' } capture_pair_as = (name) -> any [ (P(p1) * Cg(Cc(p2), name)) for p1, p2 in pairs ruby_pairs ] keyword = c 'keyword', -B'.' * word { 'BEGIN', 'END', 'alias', 'and', 'begin', 'break', 'case' 'class', 'def', 'defined?', 'do', 'else', 'elsif', 'end', 'ensure', 'false', 'for', 'if', 'in', 'module', 'next', 'nil', 'not', 'or', 'redo', 'rescue', 'retry', 'return', 'self', 'super', 'then', 'true', 'undef', 'unless', 'until', 'when', 'while', 'yield', '__FILE__', '__LINE__' } special = c 'special', word { 'private', 'protected', 'public' } embedded_doc = sequence { c('whitespace', eol), c('keyword', '=begin') * #space, c('comment', scan_until(eol * '=end')), c('whitespace', eol), c('keyword', '=end') * #space } comment = c 'comment', P'#' * scan_until(eol) operator = c 'operator', S'+-*/%!~&\\^=<>;:,.(){}[]|?' ident = (alpha + '_')^1 * (alpha + digit + S'_?!')^0 symbol = c 'symbol', any { -B(':') * P':' * S'@$'^-1 * (ident + S'+-/*'), ident * ':' * #(-P(':')) } identifier = c 'identifier', ident member = c 'member', P'@' * P'@'^-1 * ident^1 global = c 'global', P'$' * (ident^1 + S"/_?$`'" + R'09') constant = c 'constant', upper^1 * (upper + digit + '_')^0 * -(#lower) type_p = upper^1 * (alpha + digit + '_')^0 type = c 'type', type_p fdecl = c('keyword', 'def') * c('whitespace', space^1) * c('fdecl', complement(any(space, '('))^1) type_def = sequence { c('keyword', any('class', 'module')), c('whitespace', blank^1), c('type_def', type_p), sequence({ c('operator', '::'), c('type_def', type_p) })^0 } -- numbers hex_digit_run = xdigit^1 * (P'_' * xdigit^1)^0 hexadecimal_number = P'0' * S'xX' * hex_digit_run^1 * (P'.' * hex_digit_run^1)^0 * (S'pP' * S'-+'^0 * xdigit^1)^0 oct_digit_run = R'07'^1 * (P'_' * R'07'^1)^0 octal_number = P'0' * S'oO'^-1 * oct_digit_run^1 binary_digit_run = S'01'^1 * (P'_' * S'01'^1)^0 binary_number = P'0' * S'bB'^-1 * binary_digit_run^1 digit_run = digit^1 * (P'_' * digit^1)^0 float = digit_run^1 * '.' * digit_run^1 integer = digit_run^1 char = P'?' * (P'\\' * alpha * '-')^0 * alpha number = c 'number', any { octal_number, hexadecimal_number, binary_number, char, (float + integer) * (S'eE' * P('-')^0 * digit^1)^0 } del_style = 'operator' sq_string = any { c('string', span("'", "'", '\\')), c(del_style, '%q' * capture_pair_as('sq_del')) * c('string', scan_until_capture('sq_del', '\\')) * c(del_style, 1), c(del_style, '%q') * paired(1, '\\', del_style, 'string'), } P { 'all' all: any { number, symbol, V'string', V'regex', comment, V'wordlist', embedded_doc, V'heredoc', operator, fdecl, type_def, member, keyword, special, constant, type, global, identifier } string: sq_string + V'dq_string' interpolation_base: any { number, symbol, V'string', V'regex', V'wordlist', operator, member, keyword, constant, type, global, identifier } interpolation_block: c('operator', '{') * (-P'}' * (V'interpolation_base' + 1))^0 * c('operator', '}') interpolation: c('operator', '#') * any( V'interpolation_block', member, global ) dq_string_start: any { c('string', Cg(S'"`', 'del')), c(del_style, P'%' * any { S'Qx' * any { capture_pair_as('del'), Cg(P(1), 'del') }, capture_pair_as('del'), }) } dq_string_end: any { c('string', S'"`'), c(del_style, match_back('del')), } dq_string_chunk: c('string', scan_until_capture('del', '\\', '#')) * any { V'dq_string_end', V'interpolation' * V'dq_string_chunk', (c('string', '#') * V'dq_string_chunk')^-1 } dq_string: V'dq_string_start' * V('dq_string_chunk') * V('dq_string_end')^0 regex_start: any { sequence { #(P'/' * complement(eol + '/')^0 * '/'), c('regex', Cg('/', 're_del')), }, c(del_style, P'%r' * any { capture_pair_as 're_del', Cg(P(1), 're_del') }) } regex_end: any { c('regex', '/'), c(del_style, match_back('re_del')), } regex_chunk: c('regex', scan_until_capture('re_del', '\\', '#', '\n')) * any { V'regex_end', V'interpolation' * V'regex_chunk', (c('regex', '#') * V'regex_chunk')^-1 } regex_modifiers: c 'special', lower^0 regex_continuation: -#sequence { blank^0, any { digit, #alpha * -any('or', 'and', 'unless', 'if', 'then') } } regex: V'regex_start' * V('regex_chunk') * V'regex_modifiers' * V'regex_continuation' heredoc_end: c('string', eol) * S(' \t')^0 * c('constant', match_back('hd_del')) heredoc_chunk: c('string', scan_until(V'heredoc_end' + '#', '\\')) * any { V'interpolation' * V'heredoc_chunk', (c('string', '#') * V'heredoc_chunk')^-1 } heredoc_tail: match_until eol, V'all' + c('whitespace', S(' \t')^1) + c('default', 1) heredoc_sq: c('constant', P"'" * Cg(scan_until("'"), 'hd_del') * P"'") * V'heredoc_tail' * c('string', scan_until(V'heredoc_end')) heredoc_dq: c('constant', S'`"' * Cg(scan_until(S'`"'), 'hd_del') * S'`"') * V'heredoc_tail' * V'heredoc_chunk' heredoc_bare: c('constant', Cg(scan_until(space + S',.'), 'hd_del')) * V'heredoc_tail' * V('heredoc_chunk') heredoc: sequence { -B(':'), c('operator', '<<'), #complement(space), c('constant', S'-~')^-1, any(V'heredoc_sq', V'heredoc_dq', V'heredoc_bare'), V('heredoc_end')^0, Cg('', 'hd_del') -- cancel out any outside (stacked) heredocs } wordlist_start: c del_style, '%w' * any { capture_pair_as 'wl_del', Cg(P(1), 'wl_del'), } wordlist_end: c del_style, match_back('wl_del') wordlist_chunk: -match_back('wl_del') * any { c('whitespace', S(' \t')^1), c('string', complement(S(' \t') + match_back('wl_del'))^1), } wordlist: V'wordlist_start' * V('wordlist_chunk')^0 * V'wordlist_end' }
29.907407
134
0.524768
0043e462a400422358e5ca4acd6caad738e6c798
1,194
load_line_table = (chunk_name) -> import to_lua from require "moonscript.base" return unless chunk_name\match "^@" fname = chunk_name\sub 2 file = assert io.open fname code = file\read "*a" file\close! c, ltable = to_lua code return nil, ltable unless c line_tables = require "moonscript.line_tables" line_tables[chunk_name] = ltable true (options) -> busted = require "busted" handler = require("busted.outputHandlers.utfTerminal") options local spec_name coverage = require "moonscript.cmd.coverage" cov = coverage.CodeCoverage! busted.subscribe { "test", "start" }, (context) -> cov\start! busted.subscribe { "test", "end" }, -> cov\stop! busted.subscribe { "suite", "end" }, (context) -> line_counts = {} for chunk_name, counts in pairs cov.line_counts continue unless chunk_name\match("^@$./") or chunk_name\match "@[^/]" continue if chunk_name\match "^@spec/" if chunk_name\match "%.lua$" chunk_name = chunk_name\gsub "lua$", "moon" continue unless load_line_table chunk_name line_counts[chunk_name] = counts cov.line_counts = line_counts cov\format_results! handler
22.961538
75
0.670854
97a5f3cf6c67c78e6aa6b8ed1ebc2877c79c0297
21,579
export script_name = "Shake It" export script_description = "Lets you add a shaking effect to fbf typesets with configurable constraints." export script_version = "0.2.0" export script_author = "line0" export script_namespace = "l0.ShakeIt" DependencyControl = require "l0.DependencyControl" depCtrl = DependencyControl { feed: "https://raw.githubusercontent.com/TypesettingTools/line0-Aegisub-Scripts/master/DependencyControl.json", { {"a-mo.LineCollection", version: "1.3.0", url: "https://github.com/TypesettingTools/Aegisub-Motion", feed: "https://raw.githubusercontent.com/TypesettingTools/Aegisub-Motion/DepCtrl/DependencyControl.json"}, {"l0.ASSFoundation", version:"0.4.3", url: "https://github.com/TypesettingTools/ASSFoundation", feed: "https://raw.githubusercontent.com/TypesettingTools/ASSFoundation/master/DependencyControl.json"}, {"l0.Functional", version: "0.5.0", url: "https://github.com/TypesettingTools/Functional", feed: "https://raw.githubusercontent.com/TypesettingTools/Functional/master/DependencyControl.json"}, {"a-mo.ConfigHandler", version: "1.1.4", url: "https://github.com/TypesettingTools/Aegisub-Motion", feed: "https://raw.githubusercontent.com/TypesettingTools/Aegisub-Motion/DepCtrl/DependencyControl.json"}, } } LineCollection, ASS, Functional, ConfigHandler = depCtrl\requireModules! {:list, :math, :string, :table, :unicode, :util, :re } = Functional logger = depCtrl\getLogger! -- Enums used in dialog signChangeModes1D = { Any: "Allow Any" Force: "Force" Prevent: "Prevent" } signChangeModes2D = { Any: "Any number" Either: "At least one" One: "Exactly one" } tagShakeTargets = { LineBegin: "Beginning of every line" ExistingTags: "Every existing override tag" TagSections: "Every tag section" } dialogs = { shakePosition: { { class: "label", label: "Shaking Offset Limits (relative to original position): ", x: 0, y: 0, width: 10, height: 1, }, offXMin: { class: "floatedit", value: 0, min: 0, step:1, config: true x: 0, y: 1, width: 3, height: 1 }, { class: "label", label: "< x <", x: 3, y: 1, width: 3, height: 1 }, offXMax: { class: "floatedit", value: 10, min: 0, step: 1, config: true x: 6, y: 1, width: 4, height: 1, }, offYMin: { class: "floatedit", value: 0, min: 0, step: 1, config: true x: 0, y: 2, width: 3, height: 1 }, { class: "label", label: "< y <", x: 3, y: 2, width: 3, height: 1 }, offYMax: { class: "floatedit", x: 6, y: 2, width: 4, height: 1, config: true value: 10, min: 0, step: 1 }, { class: "label", label: "", x: 0, y: 3, width: 10, height: 1 }, groupLines: { class: "checkbox", label: "Group lines by:", value: true, config: true x: 0, y: 4, width: 1, height: 1 }, groupLinesField: { class: "dropdown", items: {"start_time", "end_time", "layer", "effect", "actor"}, value: 'start_time', config: true x: 1, y: 4, width: 1, height: 1 }, { class: "label", label: "Shake interval: every", x: 0, y: 5, width: 1, height: 1 }, interval: { class:"intedit", value: 1, min: 1, config: true x: 1, y: 5, width: 1, height: 1 }, { class: "label", label: "line group(s)", x: 2, y: 5, width: 1, height: 1 }, { class: "label", label: "Angle between subsequent line group offsets:", x: 0, y: 6, width: 10, height: 1 }, { class: "label", label: "Min:", x: 0, y: 7, width: 1, height: 1 }, angleMin: { class: "floatedit", value: 0, min: 0, max: 180, step: 1, config: true x: 1, y: 7, width: 2, height: 1 }, { class: "label", label: "� Max:", x: 3, y: 7, width: 3, height: 1 }, angleMax: { class: "floatedit", value: 180, min: 0, max: 180, step: 1, config: true x: 6, y: 7, width: 2, height: 1, }, { class: "label", label: "�", x: 8, y: 7, width: 2, height: 1 }, { class: "label", label: "", x: 0, y: 8, width: 10, height: 1 }, { class: "label", label: "Constraints:", x: 0, y: 9, width: 10, height: 1 }, signChangeX: { class: "dropdown", items: table.values(signChangeModes1D), value: signChangeModes1D.Any, config: true x: 0, y: 10, width: 2, height: 1 }, { class: "label", label: "sign change for X offsets of subsequent line groups.", x: 2, y: 10, width: 5, height: 1 }, signChangeY: { class: "dropdown", items: table.values(signChangeModes1D), value: signChangeModes1D.Any, config: true x: 0, y: 11, width: 2, height: 1 }, { class: "label", label: "sign change for Y offsets of subsequent line groups.", x: 2, y: 11, width: 5, height: 1 }, signChangeCmb: { class: "dropdown", items: table.values(signChangeModes2D), value: signChangeModes2D.Any, config: true x: 0, y: 12, width: 2, height: 1 }, { class: "label", x: 2, y: 12, width: 5, height: 1 label: "of the X and Y offsets must change sign between subsequent line groups.", }, { class: "label", label: "", x: 0, y: 13, width: 10, height: 1 }, { class: "label", label: "Random Number Generation", x: 0, y: 14, width: 10, height: 1 }, { class: "label", label: "Seed:", x: 0, y: 15, width: 1, height: 1 }, seed: { class:"intedit", value: os.time!, x: 1, y: 15, width: 2, height: 1 }, repeatPattern: { class: "checkbox", label: "Repeat pattern every", value: false, config: true, x: 0, y: 16, width: 1, height: 1 }, repeatInterval: { class:"intedit", value: 12, config: true, x: 1, y: 16, width: 1, height: 1 }, { class: "label", label: "line group(s)", x: 2, y: 16, width: 1, height: 1 }, }, shakeScalarTag: { { class: "label", label: "Shaking Targets:", x: 0, y: 0, width: 6, height: 1 }, { class: "label", label: "Tag:", x: 0, y: 1, width: 1, height: 1 }, tag: { class: "dropdown", items: table.pluck table.filter(ASS.tagMap, (tag) -> tag.type == ASS.Number and not tag.props.global), "overrideName", value: "\\frz", config: true, x: 1, y: 1, width: 1, height: 1 }, LineBegin: { class: "checkbox", label: tagShakeTargets.LineBegin, value: true, config: true, x: 0, y: 2, width: 6, height: 1 }, ExistingTags: { class: "checkbox", label: tagShakeTargets.ExistingTags, value: false, config: true, x: 0, y: 3, width: 6, height: 1 }, TagSections: { class: "checkbox", label: tagShakeTargets.TagSections, value: false, config: true x: 0, y: 4, width: 6, height: 1 }, { class: "label", label: "", x: 0, y: 5, width: 6, height: 1 }, { class: "label", label: "Shake offset limits (relative to original tag value): ", x: 0, y: 6, width: 6, height: 1, }, absoluteOffsetMin: { class: "floatedit", value: 0, min: 0, step:1, config: true, x: 0, y: 7, width: 2, height: 1 }, { class: "label", label: "< value <", x: 2, y: 7, width: 1, height: 1 }, absoluteOffsetMax: { class: "floatedit", value: 10, min: 0, step: 1, config: true x: 3, y: 7, width: 2, height: 1, }, { class: "label", label: "", x: 0, y: 8, width: 6, height: 1 }, groupLines: { class: "checkbox", label: "Group lines by:", value: true, config: true, x: 0, y: 9, width: 1, height: 1 }, groupLinesField: { class: "dropdown", items: {"start_time", "end_time", "layer", "effect", "actor"}, value: 'start_time', config: true, x: 1, y: 9, width: 1, height: 1 }, { class: "label", label: "Shake interval: every", x: 0, y: 10, width: 1, height: 1 }, interval: { class: "intedit", value: 1, min: 1, config: true, x: 1, y: 10, width: 1, height: 1 }, { class: "label", label: "line group(s)", x: 2, y: 10, width: 1, height: 1 }, { class: "label", label: "Offset difference range between subsequent line groups:", x: 0, y: 11, width: 6, height: 1 }, { class: "label", label: "Min:", x: 0, y: 12, width: 1, height: 1 }, groupOffsetMin: { class: "floatedit", value: 0, min: 0, step: 1, config: true, x: 1, y: 12, width: 2, height: 1 }, { class: "label", label: " Max:", x: 3, y: 12, width: 1, height: 1 }, groupOffsetMax: { class: "floatedit", value: 10, min: 0, step: 1, config: true x: 4, y: 12, width: 2, height: 1, }, { class: "label", label: "", x: 0, y: 13, width: 6, height: 1 }, { class: "label", label: "Shake offset constraints between subsequent line groups:", x: 0, y: 14, width: 6, height: 1 }, signChange: { class: "dropdown", items: table.values(signChangeModes1D), value: signChangeModes1D.Any, config: true, x: 0, y: 15, width: 2, height: 1 }, { class: "label", label: "sign change for tag offsets of subsequent lines.", x: 2, y: 15, width: 4, height: 1 }, { class: "label", label: "", x: 0, y: 16, width: 6, height: 1 }, { class: "label", label: "", x: 0, y: 17, width: 6, height: 1 }, { class: "label", label: "Random Number Generation", x: 0, y: 18, width: 10, height: 1 }, { class: "label", label: "Seed:", x: 0, y: 19, width: 1, height: 1 }, seed: { class:"intedit", value: os.time!, x: 1, y: 19, width: 2, height: 1 }, repeatPattern: { class: "checkbox", label: "Repeat pattern every", value: false, config: true, x: 0, y: 20, width: 1, height: 1 }, repeatInterval: { class:"intedit", value: 12, config: true, x: 1, y: 20, width: 1, height: 1 }, { class: "label", label: "line group(s)", x: 2, y: 20, width: 1, height: 1 }, } } hasLineRotation = (line) -> styleTags = line\getDefaultTags nil, false return true unless styleTags.tags.angle\equal 0 line\modTags {"angle", "angle_x", "angle_y"}, (tag) -> true groupLines = (lines, field, interval = 1) -> -- collect selected lines and group if desired groups = if field table.values list.groupBy(lines.lines, field), (grpA, grpB) -> grpA[1][field] < grpB[1][field] else [{line} for line in *lines] -- group fbf lines to get longer shake interval if interval > 1 groups = [list.join unpack group for group in *list.chunk groups, interval] return groups applyPositionShake = (lines, groups, offsets) -> aegisub.progress.task "Shaking..." groupCount = #groups for i, group in ipairs groups aegisub.progress.set 20 + 80 * (i-1) / groupCount aegisub.cancel! if aegisub.progress.is_cancelled! for line in *group data = ASS\parse line pos, align, org = data\getPosition! modifiedTags = {pos} if pos.class == ASS.Tag.Move pos\add offsets[i][1], offsets[i][2], offsets[i][1], offsets[i][2] else pos\add offsets[i][1], offsets[i][2] if hasLineRotation data modifiedTags[2] = org org\add offsets[i][1], offsets[i][2] data\replaceTags modifiedTags data\commit! lines\replaceLines! collectTags = (lines, groups, tagName, targets) -> maxTagCountPerLine = 0 groupCount = #groups tagsByGroupAndLine = for i, group in ipairs groups aegisub.progress.set 10 + 50 * (i-1) / groupCount aegisub.cancel! if aegisub.progress.is_cancelled! for line in *group tags = {} ass = line.ASS or ASS\parse line if targets.LineBegin -- get the tag section right at line begin, create one if it doesn't exist section = if #ass.sections > 0 and ass.sections[1].instanceOf[ASS.Section.Tag] ass.sections[1] else ass\insertSections(ASS.Section.Tag!, 1)[1] -- get the last matching override tag in that section, create one from style default if it doesn't exist tags[#tags+1] = section\getTags(tagName, -1, -1, true)[1] or section\insertDefaultTags tagName if targets.ExistingTags list.joinInto tags, ass\getTags tagName if targets.TagSections ass\callback (section,_,i) -> tags[#tags+1] = section\getTags(tagName, -1, -1, true)[1] or section\insertTags( section\getEffectiveTags(true).tags[tagName]), ASS.Section.Tag -- deduplicate tags we matched multiple times tags = table.keys list.makeSet tags -- sort tags by order of appearance in the line table.sort tags, (a, b) -> aSectionPosition = list.indexOf a.parent.parent.sections, a.parent bSectionPosition = list.indexOf b.parent.parent.sections, b.parent if aSectionPosition == bSectionPosition return list.indexOf(a.parent.tags, a) < list.indexOf b.parent.tags, b return aSectionPosition < bSectionPosition maxTagCountPerLine = math.max maxTagCountPerLine, #tags tags return tagsByGroupAndLine, maxTagCountPerLine getSingleSign = (mode, offPrev) -> ref = switch mode when signChangeModes1D.Prevent then offPrev when signChangeModes1D.Force then -offPrev else math.random! - 0.5 return math.sign ref, true makePositionOffsetGenerator = (res) -> shakeRadius = math.vector2.distance 0, 0, res.offXMax, res.offYMax offXPrev, offYPrev, offX, offY = 0, 0 -- allow user to replay a previous shake math.randomseed res.seed return (constrainAngle = true, rollLimit = 5000) -> for i = 1, rollLimit -- check if X sign change is subject to combined X/Y constraints xSign = if res.signChangeCmb == signChangeModes2D.One and res.signChangeY == signChangeModes1D.Force math.sign offXPrev, true elseif res.signChangeCmb == signChangeModes2D.Either and res.signChangeY == signChangeModes1D.Prevent math.sign -offXPrev, true -- otherwise use X-only constraints else getSingleSign res.signChangeX, offXPrev -- generate a new horizontal offset with the desired sign offX = xSign * math.randomFloat res.offXMin, res.offXMax xSignChanged = offX * offXPrev < 0 -- check if Y sign change is subject to combined X/Y constraints ySign = if res.signChangeCmb == signChangeModes2D.Either and not xSignChanged math.sign -offYPrev, true elseif res.signChangeCmb == signChangeModes2D.One and xSignChanged math.sign offYPrev, true -- otherwise use Y-only constraints else getSingleSign res.signChangeY, offYPrev -- generate a new vertical offset with the desired sign offY = ySign * math.randomFloat res.offYMin, res.offYMax -- scale the current and previous offset vectors to the shake radius offXNorm, offYNorm = math.vector2.normalize offX, offY, shakeRadius offXPrevNorm, offYPrevNorm = math.vector2.normalize offXPrev, offYPrev, shakeRadius -- get the angle difference on the circle around the origin distance = math.vector2.distance offXPrevNorm, offYPrevNorm, offXNorm, offYNorm angle = math.degrees math.acos (2*shakeRadius^2 - distance^2) / (2 * shakeRadius^2) -- and check if is within the user-specified constraints if not constrainAngle or angle >= res.angleMin and angle <= res.angleMax offXPrev, offYPrev = offX, offY return {offX, offY} -- give up after so many rolls, because we're to lazy to actually do our maths -- and factor the constraints in when pulling our random numbers logger\error "Couldn't find offset that satifies chosen angle constraints (Min: #{res.angleMin}�, Max: #{res.angleMax}� for group #{i}. Aborting." makeSimpleOffset = (prev, min, max, signChangeMode = signChangeModes1D.Any, minDiff = 0, maxDiff = math.huge, rollLimit = 5000) -> for i = 1, rollLimit sign = getSingleSign signChangeMode, prev off = sign * math.randomFloat min, max diffToPrev = math.abs off-prev if diffToPrev <= maxDiff and diffToPrev >= minDiff return off logger\error "Couldn't find offset that satifies constraints Min=#{minDiff} <= #{prev} <= Max=#{maxDiff}." makeMultiOffsetGenerator = (res, count) -> -- this makes all initial offsets start with the same sign if sign change is enforced -- TODO: maybe offer an option to start with a random sign for every value offPrev = [0 for _ = 1, count] -- allow user to replay a previous shake math.randomseed res.seed return (applyConstraints = true, rollLimit) -> minPrevDiff, maxPrevDiff = if applyConstraints res.groupOffsetMin, res.groupOffsetMax else 0, math.huge offPrev = for i = 1, count makeSimpleOffset offPrev[i], res.absoluteOffsetMin, res.absoluteOffsetMax, res.signChange, minPrevDiff, maxPrevDiff, rollLimit return offPrev calculateOffsets = (seriesCount, generator, seed, repeatInterval = math.huge, startProgress = 0, endProgress = 100) -> offsets = {} for i = 0, seriesCount - 1 aegisub.progress.set startProgress + (endProgress-startProgress) * i / seriesCount aegsiub.cancel! if aegisub.progress.is_cancelled! offsets[1 + i] = if i < repeatInterval generator i != 0 else offsets[1 + i%repeatInterval] return offsets showDialog = (macro) -> options = ConfigHandler dialogs, depCtrl.configFile, false, script_version, depCtrl.configDir options\read! options\updateInterface macro btn, res = aegisub.dialog.display dialogs[macro] if btn options\updateConfiguration res, macro options\write! return res shakePosition = (sub, sel) -> res = showDialog "shakePosition" return aegisub.cancel! unless res -- fix up some user errors if res.offXMax < res.offXMin res.offXMin, res.offXMax = res.offXMax, res.offXMin if res.offYMax < res.offYMin res.offYMin, res.offYMax = res.offYMax, res.offYMin if res.angleMax < res.angleMin res.angleMin, res.angleMax = res.angleMax, res.angleMin -- check for conflicting constraints err = {"You have provided conflicting constraints: "} if res.signChangeX == signChangeModes1D.Force and res.signChangeY == signChangeModes1D.Force if res.angleMax < 90 err[#err+1] = "Forced sign inversion for X and Y offsets require a maxium angle of at least 90�." if res.signChangeCmb == signChangeModes2D.One err[#err+1] = "Can't limit signs to only one of the X and Y offsets because sign changes are separately enforced for both." elseif res.signChangeX == signChangeModes1D.Prevent and res.signChangeY == signChangeModes1D.Prevent if res.angleMin > 90 err[#err+1] = "Can't prevent sign inversion for X and Y offsets when the minimum angle is larger than 90�." if res.signChangeCmb == signChangeModes2D.Either err[#err+1] = "Can't change signs of either X or Y offsets because they are prevented for both." logger\assert #err == 1, table.concat err, "\n" lines = LineCollection sub, sel aegisub.progress.task "Grouping lines..." groups = groupLines lines, res.groupLines and res.groupLinesField or nil, res.interval aegisub.progress.set 10 aegisub.cancel! if aegisub.progress.is_cancelled! aegisub.progress.task "Rolling dice..." -- generate offsets for every line group, but don't apply them immediately in case the generator fails offsets = calculateOffsets #groups, makePositionOffsetGenerator(res), res.seed, res.repeatPattern and res.repeatInterval or math.huge, 10, 20 -- apply the position offsets to all line groups aegisub.progress.task "Applying shake..." applyPositionShake lines, groups, offsets shakeScalarTag = (sub, sel) -> res = showDialog "shakeScalarTag" return aegisub.cancel! unless res -- fix up some user errors if res.absoluteOffsetMax < res.absoluteOffsetMin res.absoluteOffsetMin, res.absoluteOffsetMax = res.absoluteOffsetMax, res.absoluteOffsetMin if res.groupOffsetMax < res.groupOffsetMin res.groupOffsetMin, res.groupOffsetMax = res.groupOffsetMax, res.groupOffsetMin lines = LineCollection sub, sel aegisub.progress.task "Grouping lines..." groups = groupLines lines, res.groupLines and res.groupLinesField or nil, res.interval groupCount = #groups aegisub.progress.set 10 aegisub.progress.task "Collecting tags..." tagsByGroupAndLine, offsetCount = collectTags lines, groups, ASS.tagNames[res.tag][1], res aegisub.progress.task "Rolling dice..." offsets = calculateOffsets #groups, makeMultiOffsetGenerator(res, offsetCount), res.seed, res.repeatPattern and res.repeatInterval or math.huge, 60, 70 aegisub.progress.task "Applying shake..." for g, group in ipairs groups aegisub.progress.set 70 + 30 * (g-1) / groupCount aegisub.cancel! if aegisub.progress.is_cancelled! for tagsByLine in *tagsByGroupAndLine[g] -- TODO: support tags w/ > 1 parameter tag\add offsets[g][t] for t, tag in ipairs tagsByLine line.ASS\commit! for line in *group lines\replaceLines! depCtrl\registerMacros { {"Shake Position", "Applies randomized offsets to line positioning.", shakePosition}, {"Shake Scalar Tag", "Applies randomized offsets to a specified scalar override tag.", shakeScalarTag}, }
33.982677
150
0.629316
b4fe5a8b24b382135fe55978f15b9446954e67d0
3,018
import Router from require "lapis.router" describe "basic route matching", -> local r handler = (...) -> { ... } before_each -> r = Router! r\add_route "/hello", handler r\add_route "/hello/:name", handler r\add_route "/hello/:name/world", handler r\add_route "/static/*", handler r\add_route "/x/:color/:height/*", handler r.default_route = -> "failed to find route" it "should match static route", -> out = r\resolve "/hello" assert.same out, { {}, "/hello" } it "should match param route", -> out = r\resolve "/hello/world2323" assert.same out, { { name: "world2323" }, "/hello/:name" } it "should match param route", -> out = r\resolve "/hello/the-parameter/world" assert.same out, { { name: "the-parameter" }, "/hello/:name/world" } it "should match splat", -> out = r\resolve "/static/hello/world/343434/foo%20bar.png" assert.same out, { { splat: 'hello/world/343434/foo%20bar.png' } "/static/*" } it "should match all", -> out = r\resolve "/x/greenthing/123px/ahhhhwwwhwhh.txt" assert.same out, { { splat: 'ahhhhwwwhwhh.txt' height: '123px' color: 'greenthing' } "/x/:color/:height/*" } it "should match nothing", -> assert.same r\resolve("/what-the-heck"), "failed to find route" it "should match nothing", -> assert.same r\resolve("/hello//world"), "failed to find route" describe "named routes", -> local r handler = (...) -> { ... } before_each -> r = Router! r\add_route { homepage: "/home" }, handler r\add_route { profile: "/profile/:name" }, handler r\add_route { profile_settings: "/profile/:name/settings" }, handler r\add_route { game: "/game/:user_slug/:game_slug" }, handler r\add_route { splatted: "/page/:slug/*" }, handler r.default_route = -> "failed to find route" it "should match", -> out = r\resolve "/home" assert.same out, { {}, "/home", "homepage" } it "should generate correct url", -> url = r\url_for "homepage" assert.same url, "/home" it "should generate correct url", -> url = r\url_for "profile", name: "adam" assert.same url, "/profile/adam" it "should generate correct url", -> url = r\url_for "game", user_slug: "leafo", game_slug: "x-moon" assert.same url, "/game/leafo/x-moon" -- TODO: this is incorrect it "should generate correct url", -> url = r\url_for "splatted", slug: "cool", splat: "hello" assert.same url, "/page/cool/*" it "should create param from object", -> user = { url_key: (route_name, param_name) => assert.same route_name, "profile_settings" assert.same param_name, "name" "adam" } url = r\url_for "profile_settings", name: user assert.same url, "/profile/adam/settings" it "should not build url", -> assert.has_error (-> r\url_for "fake_url", name: user), "Missing route named fake_url"
26.707965
72
0.597416
1e2d42b562043eb612bf19d8b495d1019e8f894c
3,172
PRIVMSG: '^%pupper (.+)$': (source, destination, arg) => say arg\upper! '^%plower (.+)$': (source, destination, arg) => say ivar2.util.utf8.lower(arg) '^%preverse (.+)$': (source, destination, arg) => say arg\reverse! '^%plen (.+)$': (source, destination, arg) => say tostring(arg\len!) '^%pnicks$': (source, destination) => chan = ivar2.channels[destination] or ivar2.channels[destination\lower!] say table.concat([ivar2.util.nonickalert(chan.nicks, n) for n,k in pairs(chan.nicks)], ' ') '^%prandom (.+)$': (source, destination, arg) => words = [word for word in arg\gmatch('%S+')] say words[math.random(1, #words)] '^%pbold (.+)$': (source, destination, arg) => say ivar2.util.bold(arg) '^%punderline (.+)$': (source, destination, arg) => say ivar2.util.underline(arg) '^%pitalic (.+)$': (source, destination, arg) => say ivar2.util.italic(arg) '^%pinvert (.+)$': (source, destination, arg) => say ivar2.util.reverse(arg) '^%ptrim (.+)$': (source, destination, arg) => say ivar2.util.trim(arg) '^%pcolor ([0-9]+) (.+)$': (source, destination, color, arg) => say ivar2.util.color(arg, color) '^%pfirst (.+)$': (source, destination, arg) => say ivar2.util.split(arg, '%s')[1] '^%psplit (.-) (.*)$': (source, destination, arg, args) => say table.concat(ivar2.util.split(args, arg), ' ') '^%preplace (.-) (.-) (.*)$': (source, destination, pat, repl, arg) => new, n = string.gsub(arg, pat, repl) say(new) '^%pnocolor (.*)$': (source, destination, arg) => say ivar2.util.stripformatting(arg) '^%pstutter (.*)$': (source, destination, arg) => -- Stutter by anders from luabot s_senpai = 0.65 say arg\gsub("(%a[%w%p]+)", (w) -> if math.random! >= s_senpai return (w\sub(1, 1).."-")\rep(math.random(1, 3))..w else return w) '^%prot13 (.+)$': (source, destination, arg) => say ivar2.util.rot13(arg) '^%phex (.+)$': (source, destination, arg) => say arg\gsub '.', (b) -> ('%02x ')\format(b\byte!) '^%prtl (.+)$': (source, destination, arg) => say '‮'..arg '^%pltr (.+)$': (source, destination, arg) => say '‎'..arg '^%pemote (.+)$': (source, destination, arg) => @Action destination, arg 'botsnack': => replies = { 'Nom nom nom.' 'Ooooh' 'Yummi!' 'Delightful.' 'That makes me happy' 'How kind!' 'Sweet.' "Sorry, but I can't handle more right now." "*burp*" "Ah.. Hiccup!" } reply replies[math.random #replies] "#{ivar2.config.nick}.?%?": => replies = { "Sorry, but I tried my best" "I am not fully sentient yet, but I'm learning every day" "Please, I tried my best." "That was what my very best, just for you" "Maybe another time" "Sorry, not feeling so good" "Oof." "Whoopsie." "Just give me some time, I will get it eventually" "ಠ_ಠ" "( ͡° ͜ʖ ͡°) " } reply replies[math.random #replies] --'^%prepeat (%d+) (.*)$': (source, destination, nr, command) => -- for i=1, nr -- @DispatchCommand 'PRIVMSG', command, source, destination
36.045455
95
0.553909
9385a63833d9bb2b1d5c39feaab7fb90112fea38
510
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import app, interact from howl class ReadText run: (@finish, opts = {}) => with app.window.command_line .prompt = opts.prompt or '' .title = opts.title keymap: ctrl_m: => self.finish app.window.command_line.text ctrl_g: => self.finish! interact.register name: 'read_text' description: 'Read free form text entered by user' factory: ReadText
22.173913
79
0.686275
ea6a2857b726be405c3eaac5426eed698e77b7c5
3,172
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) {:Attribute} = require 'ljglibs.pango' ffi = require 'ffi' C = ffi.C {:max, :min, :abs} = math {:define_class} = require 'aullar.util' flair = require 'aullar.flair' flair.define 'selection', { type: flair.RECTANGLE, background: '#a3d5da', background_alpha: 0.6 } flair.define 'selection-overlay', { type: flair.RECTANGLE, background: '#c3e5ea', background_alpha: 0.4, } Selection = { new: (@view) => @_anchor = nil @_end_pos = nil properties: { is_empty: => (@_anchor == nil) or (@_anchor == @_end_pos) anchor: { get: => @_anchor set: (anchor) => return if anchor == @_anchor error "Can't set anchor when selection is empty", 2 if @is_empty @_anchor = anchor @view\refresh_display @range! @_notify_change! } end_pos: { get: => @_end_pos set: (end_pos) => return if end_pos == @_end_pos error "Can't set end_pos when selection is empty", 2 if @is_empty @_end_pos = end_pos @view\refresh_display @range! @_notify_change! } } set: (anchor, end_pos) => return if anchor == @_anchor and end_pos == @_end_pos @clear! unless @is_empty @_anchor = anchor @_end_pos = end_pos @view\refresh_display @range! @_notify_change! extend: (from_pos, to_pos) => if @is_empty @set from_pos, to_pos else @view\refresh_display min(to_pos, @_end_pos), max(to_pos, @_end_pos) @_end_pos = to_pos @_notify_change! clear: => return unless @_anchor and @_end_pos @view\refresh_display @range! @_anchor, @_end_pos = nil, nil @_notify_change! range: => min(@_anchor, @_end_pos), max(@_anchor, @_end_pos) affects_line: (line) => return false if @is_empty start, stop = @range! if start >= line.start_offset return start <= line.end_offset stop >= line.start_offset draw: (x, y, cr, display_line, line) => start_x, width = x, display_line.width - @view.base_x start, stop = @range! start_col, end_col = 1, line.size + 1 if start > line.start_offset -- sel starts on line start_col = (start - line.start_offset) + 1 if stop < line.end_offset -- sel ends on line end_col = (stop - line.start_offset) + 1 flair.draw 'selection', display_line, start_col, end_col, x, y, cr draw_overlay: (x, y, cr, display_line, line) => bg_ranges = display_line.background_ranges return unless #bg_ranges > 0 start, stop = @range! start_col = (start - line.start_offset) + 1 end_col = (stop - line.start_offset) + 1 for range in *bg_ranges break if range.start_offset > end_col if range.end_offset > start_col start_o = max start_col, range.start_offset end_o = min end_col, range.end_offset flair.draw 'selection-overlay', display_line, start_o, end_o, x, y, cr _notify_change: => if @listener and @listener.on_selection_changed @listener.on_selection_changed @listener, self } define_class Selection
25.376
79
0.638398
17f2152c0387d217a25284d88df19b0658cad261
566
export modinfo = { type: "command" desc: "Seieki" alias: {"seieki"} func: getDoPlayersFunction (v) -> while true s = CreateInstance"Part"{ Parent: v.Character[ConfigSystem("Get", "Ero-mei")] BrickColor: BrickColor.new("White") Size: Vector3.new(0.5,0.5,0.5) TopSurface: 0 BottomSurface: 0 Shape: 0 CFrame: CFrame.new(v.Character[ConfigSystem("Get", "Ero-mei")].Main.Position+Vector3.new(0,1,0)) } dm = CreateInstance"SpecialMesh"{ MeshType: "Sphere" Parent: s Scale: Vector3.new(0.1,0.1,0.1) } wait(0.5) }
25.727273
100
0.636042
73dda3a47d2a22b3f833c6a0fdfdee20f0e9c601
784
import Corpus from require 'moongrahams' describe 'corpus', -> it 'should have 5 tokens', -> corpus = Corpus! corpus\processTextLine 'one two three four five 6 7' assert.are.same 5, corpus.count it 'should have 4 tokens and 2 records of the token "this"', -> corpus = Corpus! corpus\processTextLine 'this is where this ends' assert.are.same 4, corpus.count assert.are.same 2, corpus.tokens['this'] it 'should have 7 tokens', -> corpus = Corpus! Corpus.TokenPattern = '([a-zA-Z0-9]%w+)%W*' corpus\processTextLine 'one two three four five 6 7' Corpus.TokenPattern = '([a-zA-Z]%w+)%W*' assert.are.same 5, corpus.count it 'is case sensitive', -> corpus = Corpus! corpus\processTextLine 'hi HI hi, hello heLLo' assert.are.same 4, corpus.count
23.058824
64
0.683673
20fe88078944b87bc7d67c0204569ade146c7527
7,395
-- Copyright (C) 2018-2020 DBotThePony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. import DPP2 from _G import Menus from DPP2 Menus.SecondaryMenu = => return if not IsValid(@) Menus.QCheckBox(@, 'no_tool_player') Menus.QCheckBox(@, 'no_tool_player_admin') Menus.QCheckBox(@, 'rl_enable') Menus.QCheckBox(@, 'bl_enable') Menus.QCheckBox(@, 'excl_enable') Menus.QCheckBox(@, 'no_host_limits') Menus.QCheckBox(@, 'limits_lists_enabled') Menus.QCheckBox(@, 'no_rope_world') Menus.QCheckBox(@, 'draw_owner') Menus.QCheckBox(@, 'simple_owner') Menus.QCheckBox(@, 'entity_name') Menus.QCheckBox(@, 'entity_info') Menus.QCheckBox(@, 'allow_damage_npc') Menus.QCheckBox(@, 'allow_damage_vehicle') Menus.QCheckBox(@, 'upforgrabs') Menus.QSlider(@, 'upforgrabs_timer', 1, 600) Menus.QCheckBox(@, 'autocleanup') Menus.QSlider(@, 'autocleanup_timer', 1, 900) Menus.QCheckBox(@, 'autofreeze') Menus.QCheckBox(@, 'autoghost') Menus.LoggingMenu = => return if not IsValid(@) Menus.QCheckBox(@, 'log') Menus.QCheckBox(@, 'log_echo') Menus.QCheckBox(@, 'log_echo_clients') Menus.QCheckBox(@, 'log_write') Menus.QCheckBox(@, 'log_spawns') Menus.QCheckBox(@, 'log_toolgun') Menus.QCheckBox(@, 'log_tranfer') Menus.AntispamMenu = => return if not IsValid(@) Menus.QCheckBox(@, 'antispam') Menus.QCheckBox(@, 'antispam_alt_dupes') Menus.QCheckBox(@, 'antispam_ignore_admins') @Help('gui.dpp2.help.antispam_ignore_admins') Menus.QCheckBox(@, 'antispam_unfreeze') Menus.QSlider(@, 'antispam_unfreeze_div', 0.01, 10, 2) Menus.QCheckBox(@, 'antispam_collisions') Menus.QCheckBox(@, 'antispam_spam') Menus.QSlider(@, 'antispam_spam_threshold', 0.1, 50, 2) Menus.QSlider(@, 'antispam_spam_threshold2', 0.1, 50, 2) Menus.QSlider(@, 'antispam_spam_cooldown', 0.1, 10, 3) Menus.QSlider(@, 'antispam_vol_aabb_div', 1, 10000) Menus.QCheckBox(@, 'antispam_spam_vol') Menus.QCheckBox(@, 'antispam_spam_aabb') Menus.QSlider(@, 'antispam_spam_vol_threshold', 1, 1000000000) Menus.QSlider(@, 'antispam_spam_vol_threshold2', 1, 1000000000) Menus.QSlider(@, 'antispam_spam_vol_cooldown', 1, 1000000000) @Help('') Menus.QCheckBox(@, 'antispam_ghost_by_size') Menus.QSlider(@, 'antispam_ghost_size', 1, 1000000) Menus.QCheckBox(@, 'antispam_ghost_aabb') Menus.QSlider(@, 'antispam_ghost_aabb_size', 1, 10000000) @Help('') Menus.QCheckBox(@, 'antispam_block_by_size') Menus.QSlider(@, 'antispam_block_size', 1, 1000000) Menus.QCheckBox(@, 'antispam_block_aabb') Menus.QSlider(@, 'antispam_block_aabb_size', 1, 10000000) Menus.AntipropkillMenu = => return if not IsValid(@) Menus.QCheckBox(@, 'apropkill') Menus.QCheckBox(@, 'apropkill_damage') Menus.QCheckBox(@, 'apropkill_damage_nworld') Menus.QCheckBox(@, 'apropkill_damage_nveh') Menus.QCheckBox(@, 'apropkill_trap') Menus.QCheckBox(@, 'apropkill_push') Menus.QCheckBox(@, 'apropkill_surf') Menus.QCheckBox(@, 'apropkill_throw') Menus.QCheckBox(@, 'apropkill_punt') Menus.PrimaryMenu = => return if not IsValid(@) Menus.QCheckBox(@, 'protection') for name in *{'physgun', 'gravgun', 'toolgun', 'use', 'pickup', 'damage', 'vehicle', 'drive'} with spoiler = vgui.Create('DCollapsibleCategory', @) \Dock(TOP) \DockMargin(5, 5, 5, 5) \SetLabel('gui.dpp2.toolmenu.names.' .. name) \SetExpanded(false) canvas = vgui.Create('EditablePanel', spoiler) \SetContents(canvas) dostuff = (a) -> a\SetParent(canvas) a\DockMargin(0, 5, 0, 5) dostuff(Menus.QCheckBox(@, name .. '_protection')) dostuff(Menus.QCheckBox(@, name .. '_touch_any')) dostuff(Menus.QCheckBox(@, name .. '_no_world')) dostuff(Menus.QCheckBox(@, name .. '_no_world_admin')) dostuff(Menus.QCheckBox(@, name .. '_no_map')) dostuff(Menus.QCheckBox(@, name .. '_no_map_admin')) Menus.ClientProtectionModulesMenu = => return if not IsValid(@) @CheckBox('gui.dpp2.cvars.cl_protection', 'dpp2_cl_protection') for name in *{'physgun', 'gravgun', 'toolgun', 'use', 'pickup', 'damage', 'vehicle', 'drive'} with spoiler = vgui.Create('DCollapsibleCategory', @) \Dock(TOP) \DockMargin(5, 5, 5, 5) \SetLabel('gui.dpp2.toolmenu.names.' .. name) \SetExpanded(false) canvas = vgui.Create('EditablePanel', spoiler) \SetContents(canvas) dostuff = (a) -> a\SetParent(canvas) a\DockMargin(0, 5, 0, 5) dostuff(@CheckBox('gui.dpp2.cvars.' .. 'cl_' .. name .. '_protection', 'dpp2_cl_' .. name .. '_protection')) dostuff(@CheckBox('gui.dpp2.cvars.' .. 'cl_' .. name .. '_no_other', 'dpp2_cl_' .. name .. '_no_other')) dostuff(@CheckBox('gui.dpp2.cvars.' .. 'cl_' .. name .. '_no_players', 'dpp2_cl_' .. name .. '_no_players')) dostuff(@CheckBox('gui.dpp2.cvars.' .. 'cl_' .. name .. '_no_world', 'dpp2_cl_' .. name .. '_no_world')) dostuff(@CheckBox('gui.dpp2.cvars.' .. 'cl_' .. name .. '_no_map', 'dpp2_cl_' .. name .. '_no_map')) Menus.ClientMenu = => return if not IsValid(@) @CheckBox('gui.dpp2.cvars.cl_draw_owner', 'dpp2_cl_draw_owner') @CheckBox('gui.dpp2.cvars.cl_simple_owner', 'dpp2_cl_simple_owner') @CheckBox('gui.dpp2.cvars.cl_entity_name', 'dpp2_cl_entity_name') @CheckBox('gui.dpp2.cvars.cl_entity_info', 'dpp2_cl_entity_info') @CheckBox('gui.dpp2.cvars.cl_no_contraptions', 'dpp2_cl_no_contraptions') @CheckBox('gui.dpp2.cvars.cl_draw_contraption_aabb', 'dpp2_cl_draw_contraption_aabb') @Help('') @CheckBox('gui.dpp2.cvars.cl_no_players', 'dpp2_cl_no_players') @CheckBox('gui.dpp2.cvars.cl_no_func', 'dpp2_cl_no_func') @CheckBox('gui.dpp2.cvars.cl_no_map', 'dpp2_cl_no_map') @CheckBox('gui.dpp2.cvars.cl_no_world', 'dpp2_cl_no_world') @Help('') @CheckBox('gui.dpp2.cvars.cl_ownership_in_vehicle', 'dpp2_cl_ownership_in_vehicle') @CheckBox('gui.dpp2.cvars.cl_ownership_in_vehicle_always', 'dpp2_cl_ownership_in_vehicle_always') @Help('') @CheckBox('gui.dpp2.cvars.cl_notify' .. a, 'dpp2_cl_notify' .. a) for a in *{'', '_generic', '_error', '_hint', '_undo', '_cleanup', '_sound'} @NumSlider('gui.dpp2.cvars.cl_notify_timemul', 'dpp2_cl_notify_timemul', 0, 10, 2) @Help('') @CheckBox('gui.dpp2.cvars.cl_properties' .. a, 'dpp2_cl_properties' .. a) for a in *{'', '_regular', '_admin', '_restrictions'} @Help('') @CheckBox('gui.dpp2.cvars.cl_physgun_undo', 'dpp2_cl_physgun_undo') @CheckBox('gui.dpp2.cvars.cl_physgun_undo_custom', 'dpp2_cl_physgun_undo_custom') @Help('gui.dpp2.undo.physgun_help')
41.544944
143
0.717106
d36b816872b2a096a760a41a5dcabf73a8e40fd5
213
-- typekit.parser.error -- Error reporting for the parser import style from require "ansikit.style" parserError = (msg) -> print style "%{bold red}typekit (parser) $%{notBold} #{msg}" error! { :parserError }
23.666667
62
0.694836
198b8560ed3a106db403365c77eeaaec0fd7cfa9
2,704
-- load everything we need import loadfile from require 'moonscript.base' import Context, DepGraph, Executor from require 'moonbuild' Variable = (require 'moonbuild')['core.Variable'] import parseargs from (require 'moonbuild')['_cmd.common'] argparse = require 'argparse' import sort, concat from table import exit from os -- parse the arguments parser = with argparse "moonbuild", "A build system in moonscript" \option '-b --buildfile', "Build file to use", 'Build.moon' \option '-j --parallel', "Sets the number of parallel tasks, 'y' to run as many as we have cores", '1' \flag '-l --list', "List the targets", false \flag '-V --list-variables', "List the variables", false \flag '-q --quiet', "Don't print targets as they are being built", false \flag '-f --force', "Always rebuild every target", false \flag '-v --verbose', "Be verbose", false (\option '-u --unset', "Unsets a variable")\count '*' (\option '-s --set', "Sets a variable")\args(2)\count '*' (\option '-S --set-list', "Sets a variable to a list")\args(2)\count '*' (\argument 'targets', "Targets to build")\args '*' \add_complete! args = parser\parse! overrides = {} for unset in *args.unset overrides[unset] = Variable.NIL for set in *args.set overrides[set[1]] = set[2] for set in *args.set_list overrides[set[1]] = parseargs set[2] args.parallel = args.parallel == 'y' and 'y' or ((tonumber args.parallel) or error "Invalid argument for -j: #{args.parallel}") error "Invalid argument for -j: #{args.parallel}" if args.parallel != 'y' and (args.parallel<1 or args.parallel%1 != 0) print "Parsed CLI args" if args.verbose -- load the buildfile ctx = Context! ctx\load (loadfile args.buildfile), overrides print "Loaded buildfile" if args.verbose -- handle -l and -V if args.list print "Public targets" targets, n = {}, 1 for t in *ctx.targets if t.public targets[n], n = t.name, n+1 sort targets print concat targets, ", " print! exit 0 unless args.list_variables if args.list_variables print "Public variables" vars, n = {}, 1 for k, v in pairs ctx.variables if v.public vars[n], n = k, n+1 sort vars print concat vars, ", " print! exit 0 -- initialize the buildfile further ctx\init! print "Initialized buildfile" if args.verbose -- create the DAG targets = #args.targets==0 and ctx.defaulttargets or args.targets dag = DepGraph ctx, targets print "Created dependancy graph" if args.verbose -- execute the build nparallel = args.parallel == 'y' and Executor\getmaxparallel! or args.parallel print "Building with #{nparallel} max parallel process#{nparallel>1 and "es" or ""}" if args.verbose executor = Executor dag, nparallel executor\execute args print "Finished" if args.verbose
33.382716
127
0.704512
5b427e25481e5bbe35de57f6fa274ba8f69947bc
325
intcode = require 'intcode' vectors = { {'1,0,0,0,99', '2,0,0,0,99'} {'2,3,0,3,99', '2,3,0,6,99'} {'2,4,4,5,99,0', '2,4,4,5,99,9801'} {'1,1,1,4,99,5,6,0,99', '30,1,1,4,2,5,6,0,99'} } for i, {src, dst} in ipairs vectors describe "test vector ##{i}", -> it "should pass", -> assert.same intcode(src), dst
23.214286
48
0.523077
8fefc77b461d46595af69917663196063222dea9
5,737
import render_html, Widget from require "lapis.html" render_widget = (w) -> buffer = {} w buffer table.concat buffer describe "lapis.html", -> it "should render html", -> output = render_html -> b "what is going on?" div -> pre class: "cool", -> span "hello world" text capture -> div "this is captured" link rel: "icon" -- , type: "image/png", href: "dad"-- can't have multiple because of hash ordering raw "<div>raw test</div>" text "<div>raw test</div>" html_5 -> div "what is going on there?" assert.same [[<b>what is going on?</b><div><pre class="cool"><span>hello world</span></pre></div>&lt;div&gt;this is captured&lt;/div&gt;<link rel="icon"/><div>raw test</div>&lt;div&gt;raw test&lt;/div&gt;<!DOCTYPE HTML><html lang="en"><div>what is going on there?</div></html>]], output it "should render more html", -> output = render_html -> element "leaf", {"hello"}, "world" element "leaf", "one", "two", "three" element "leaf", {hello: "world", "a"}, { no: "show", "b", "c" } leaf {"hello"}, "world" leaf "one", "two", "three" leaf {hello: "world", "a"}, { no: "show", "b", "c" } assert.same [[<leaf>helloworld</leaf><leaf>onetwothree</leaf><leaf hello="world">abc</leaf><leaf>helloworld</leaf><leaf>onetwothree</leaf><leaf hello="world">abc</leaf>]], output -- attributes are unordered so we don't check output (for now) it "should render multiple attributes", -> render_html -> link rel: "icon", type: "image/png", href: "dad" pre id: "hello", class: "things", style: [[border: image("http://leafo.net")]] it "should capture", -> local capture_out output = render_html -> text "hello" capture_out = capture -> div "This is the capture" text "world" assert.same "helloworld", output assert.same "<div>This is the capture</div>", capture_out it "should render the widget", -> class TestWidget extends Widget content: => div class: "hello", @message @content_for "inner" input = render_widget TestWidget message: "Hello World!", inner: -> b "Stay Safe" assert.same input, [[<div class="hello">Hello World!</div><b>Stay Safe</b>]] it "should render widget with inheritance", -> class BaseWidget extends Widget value: 100 another_value: => 200 content: => div class: "base_widget", -> @inner! inner: => error "implement me" class TestWidget extends BaseWidget inner: => text "Widget speaking, value: #{@value}, another_value: #{@another_value!}" input = render_widget TestWidget! assert.same input, [[<div class="base_widget">Widget speaking, value: 100, another_value: 200</div>]] it "should include widget helper", -> class Test extends Widget content: => div "What's up! #{@hello!}" w = Test! w\include_helper { id: 10 hello: => "id: #{@id}" } input = render_widget w assert.same input, [[<div>What&#039;s up! id: 10</div>]] it "helper should pass to sub widget", -> class Fancy extends Widget content: => text @cool_message! text @thing class Test extends Widget content: => first -> widget Fancy @ second -> widget Fancy! w = Test thing: "THING" w\include_helper { cool_message: => "so-cool" } assert.same [[<first>so-coolTHING</first><second>so-cool</second>]], render_widget w it "helpers should resolve correctly ", -> class Base extends Widget one: 1 two: 2 three: 3 class Sub extends Base two: 20 three: 30 four: 40 content: => text @one text @two text @three text @four text @five w = Sub! w\include_helper { one: 100 two: 200 four: 400 five: 500 } buff = {} w\render buff assert.same {"1", "20", "30", "40", "500"}, buff it "should include methods from mixin", -> class TestMixin thing: -> div class: "the_thing", -> text "hello world" class SomeWidget extends Widget @include TestMixin content: => div class: "outer", -> @thing! assert.same [[<div class="outer"><div class="the_thing">hello world</div></div>]], render_widget SomeWidget! it "should set layout opt", -> class TheWidget extends Widget content: => @content_for "title", -> div "hello world" @content_for "another", "yeah" widget = TheWidget! helper = { layout_opts: {} } widget\include_helper helper out = render_widget widget assert.same { another: "yeah", title: "<div>hello world</div>" }, helper.layout_opts it "should render content for", -> class TheLayout extends Widget content: => assert.truthy @has_content_for "title" assert.truthy @has_content_for "inner" assert.truthy @has_content_for "footer" assert.falsy @has_content_for "hello" div class: "title", -> @content_for "title" @content_for "inner" @content_for "footer" class TheWidget extends Widget content: => @content_for "title", -> div "hello world" @content_for "footer", "The's footer" div "what the heck?" layout_opts = {} inner = {} view = TheWidget! view\include_helper { :layout_opts } view inner layout_opts.inner = -> raw inner assert.same [[<div class="title"><div>hello world</div></div><div>what the heck?</div>The&#039;s footer]], render_widget TheLayout layout_opts
26.560185
290
0.587938
42a642ee671371b6ae0104a52e008004c5d2d293
6,515
-- Copyright (c) 2005-2010, Niels Martin Hansen, Rodrigo Braz Monteiro -- Copyright (c) 2013, Thomas Goyne <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. error = error pairs = pairs select = select sformat = string.format tonumber = tonumber type = type check = require 'aegisub.argcheck' local * -- Make a shallow copy of a table copy = check'table' (tbl) -> {k, v for k, v in pairs tbl} -- Make a deep copy of a table -- Retains equality of table references inside the copy and handles self-referencing structures deep_copy = check'table' (tbl) -> seen = {} copy = (val) -> return val if type(val) != 'table' return seen[val] if seen[val] seen[val] = val {k, copy(v) for k, v in pairs val} copy tbl -- Generates ASS hexadecimal string from R, G, B integer components, in &HBBGGRR& format ass_color = (r, g, b) -> sformat "&H%02X%02X%02X&", b, g, r -- Format an alpha-string for \Xa style overrides ass_alpha = (a) -> sformat "&H%02X&", a -- Format an ABGR string for use in style definitions (these don't end with & either) ass_style_color = (r, g, b, a) -> sformat "&H%02X%02X%02X%02X", a, b, g, r -- Extract colour components of an ASS colour extract_color = check'string' (s) -> local a, b, g, r -- Try a style first a, b, g, r = s\match '&H(%x%x)(%x%x)(%x%x)(%x%x)' if a then return tonumber(r, 16), tonumber(g, 16), tonumber(b, 16), tonumber(a, 16) -- Then a colour override b, g, r = s\match '&H(%x%x)(%x%x)(%x%x)&' if b then return tonumber(r, 16), tonumber(g, 16), tonumber(b, 16), 0 -- Then an alpha override a = s\match '&H(%x%x)&' if a then return 0, 0, 0, tonumber(a, 16) -- Ok how about HTML format then? r, g, b, a = s\match '#(%x%x)(%x?%x?)(%x?%x?)(%x?%x?)' if r then return tonumber(r, 16), tonumber(g, 16) or 0, tonumber(b, 16) or 0, tonumber(a, 16) or 0 -- Create an alpha override code from a style definition colour code alpha_from_style = check'string' (scolor) -> ass_alpha select 4, extract_color scolor -- Create an colour override code from a style definition colour code color_from_style = check'string' (scolor) -> r, g, b = extract_color scolor ass_color r or 0, g or 0, b or 0 -- Converts HSV (Hue, Saturation, Value) to RGB HSV_to_RGB = (H, S, V) -> r, g, b = 0, 0, 0 -- Saturation is zero, make grey if S == 0 r = clamp(V*255, 0, 255) g = r b = r -- Else, calculate color else -- Calculate subvalues H = math.abs(H) % 360 -- Put H in range [0, 360) Hi = math.floor(H/60) f = H/60.0 - Hi p = V*(1-S) q = V*(1-f*S) t = V*(1-(1-f)*S) -- Do math based on hue index if Hi == 0 r = V*255.0 g = t*255.0 b = p*255.0 elseif Hi == 1 r = q*255.0 g = V*255.0 b = p*255.0 elseif Hi == 2 r = p*255.0 g = V*255.0 b = t*255.0 elseif Hi == 3 r = p*255.0 g = q*255.0 b = V*255.0 elseif Hi == 4 r = t*255.0 g = p*255.0 b = V*255.0 elseif Hi == 5 r = V*255.0 g = p*255.0 b = q*255.0 else error "math.floor(H % 360 / 60) should be [0, 6), is #{Hi}?" return r, g, b -- Convert HSL (Hue, Saturation, Luminance) to RGB -- Contributed by Gundamn HSL_to_RGB = (H, S, L) -> local r, g, b -- Make sure input is in range H = math.abs(H) % 360 S = clamp(S, 0, 1) L = clamp(L, 0, 1) if S == 0 -- Simple case if saturation is 0, all grey r = L g = L b = L else -- More common case, saturated colour Q = if L < 0.5 L * (1.0 + S) else L + S - (L * S) P = 2.0 * L - Q Hk = H / 360 local Tr, Tg, Tb if Hk < 1/3 Tr = Hk + 1/3 Tg = Hk Tb = Hk + 2/3 elseif Hk > 2/3 Tr = Hk - 2/3 Tg = Hk Tb = Hk - 1/3 else Tr = Hk + 1/3 Tg = Hk Tb = Hk - 1/3 get_component = (T) -> if T < 1/6 P + ((Q - P) * 6.0 * T) elseif 1/6 <= T and T < 1/2 Q elseif 1/2 <= T and T < 2/3 P + ((Q - P) * (2/3 - T) * 6.0) else P r = get_component(Tr) g = get_component(Tg) b = get_component(Tb) return math.floor(r*255+0.5), math.floor(g*255+0.5), math.floor(b*255+0.5) -- Removes spaces at the start and end of string trim = (s) -> s\gsub '^%s*(.-)%s*$', '%1' -- Get the 'head' and 'tail' of a string, treating it as a sequence of words separated by one or more space-characters headtail = (s) -> a, b, head, tail = s\find '(.-)%s+(.*)' if a then head, tail else s, '' -- Iterator function for headtail words = (s) -> -> return if s == '' head, tail = headtail s s = tail head -- Clamp a number value to a range clamp = (val, min, max) -> if val < min then min elseif val > max then max else val -- Interpolate between two numbers interpolate = (pct, min, max) -> if pct <= 0 then min elseif pct >= 1 then max else pct * (max - min) + min -- Interpolate between two colour values, given in either style definition or style override format -- Return in style override format interpolate_color = (pct, first, last) -> r1, g1, b1 = extract_color first r2, g2, b2 = extract_color last r, g, b = interpolate(pct, r1, r2), interpolate(pct, g1, g2), interpolate(pct, b1, b2) ass_color r, g, b -- Interpolate between two alpha values, given either in style override or as part as a style definition colour -- Return in style override format interpolate_alpha = (pct, first, last) -> ass_alpha interpolate pct, select(4, extract_color first), select(4, extract_color last) { :copy, :deep_copy, :ass_color, :ass_alpha, :ass_style_color, :extract_color, :alpha_from_style, :color_from_style, :HSV_to_RGB, :HSL_to_RGB, :trim, :headtail, :words, :clamp, :interpolate, :interpolate_color, :interpolate_alpha }
28.955556
118
0.607828
8874fa8c8d0840f4aaa5830898e72c2f175c79d2
1,904
export class Entity new: => @x = 0 @y = 0 @layer = 0 @visible = true @active = true @scene = nil @graphic = nil @components = Locker! sceneAdded: (scene) => @scene = scene @components\lock! for _, component in ipairs @components.values component\added(@) @components\unlock! sceneRemoved: => @scene = nil @components\lock! for _, component in ipairs @components.values component\removed! @components\unlock! sceneEnter: => sceneLeave: => beforeUpdate: => @components\lock! for _, component in ipairs @components.values component\beforeUpdate! @components\unlock! update: (dt) => if (@graphic != nil) @graphic\update(dt) @components\lock! for _, component in ipairs @components.values component\update(dt) @components\unlock! lateUpdate: => @components\lock! for _, component in ipairs @components.values component\lateUpdate! @components\unlock! draw: => if (@graphic != nil) @graphic\draw(@x, @y) @components\lock! for _, component in ipairs @components.values component\draw! @components\unlock! addComponent: (component) => @components\add(component) if (@scene != nil) component\added(@) return component removeComponent: (component) => if (@components\remove(component)) component\removed(@) removeSelf: => @scene\removeEntity(@) toString: => "#{@@__name}, scene: #{if @scene == nil then "nil" else @scene.__class.__name}"
21.885057
92
0.510504
39d3d8c13980d541780ebbf060a2f05a062a3483
6,530
url = require "socket.url" lapis_config = require "lapis.config" session = require "lapis.session" import html_writer from require "lapis.html" import increment_perf from require "lapis.nginx.context" import parse_cookie_string, to_json, build_url, auto_table from require "lapis.util" import insert from table get_time = (config) -> if ngx ngx.update_time! ngx.now! elseif config.server == "cqueues" require("cqueues").monotime! class Request @__inherited: (child) => -- add inheritance to support methods if support = rawget child, "support" return if getmetatable support setmetatable support, { __index: @support } -- these are like methods but we don't put them on the request object so they -- don't take up names that someone might use @support: { default_url_params: => parsed = { k,v for k,v in pairs @req.parsed_url } parsed.query = nil parsed load_cookies: => @cookies = auto_table -> cookie = @req.headers.cookie if type(cookie) == "table" out = {} for str in *cookie for k,v in pairs parse_cookie_string str out[k] = v out else parse_cookie_string cookie load_session: => @session = session.lazy_session @ -- write what is in @options and @buffer into the output -- this is called once, and done last render: => @@support.write_session @ @@support.write_cookies @ if @options.status @res.status = @options.status if @options.headers for k,v in pairs @options.headers @res\add_header k, v if obj = @options.json @res.headers["Content-Type"] = @options.content_type or "application/json" @res.content = to_json obj return if ct = @options.content_type @res.headers["Content-Type"] = ct if not @res.headers["Content-Type"] @res.headers["Content-Type"] = "text/html" if redirect_url = @options.redirect_to if redirect_url\match "^/" redirect_url = @build_url redirect_url @res\add_header "Location", redirect_url @res.status or= 302 return layout = if @options.layout != nil @options.layout else @app.layout @layout_opts = if layout { _content_for_inner: nil } widget = @options.render widget = @route_name if widget == true config = lapis_config.get! if widget if type(widget) == "string" widget = require "#{@app.views_prefix}.#{widget}" start_time = if config.measure_performance get_time config view = widget @options.locals @layout_opts.view_widget = view if @layout_opts view\include_helper @ @write view if start_time t = get_time config increment_perf "view_time", t - start_time if layout inner = @buffer @buffer = {} layout_cls = if type(layout) == "string" require "#{@app.views_prefix}.#{layout}" else layout start_time = if config.measure_performance get_time config @layout_opts._content_for_inner or= -> raw inner layout = layout_cls @layout_opts layout\include_helper @ layout\render @buffer if start_time t = get_time config increment_perf "layout_time", t - start_time if next @buffer content = table.concat @buffer @res.content = if @res.content @res.content .. content else content write_session: session.write_session write_cookies: => return unless next @cookies for k,v in pairs @cookies cookie = "#{url.escape k}=#{url.escape v}" if extra = @app.cookie_attributes @, k, v cookie ..= "; " .. extra @res\add_header "Set-Cookie", cookie add_params: (params, name) => @[name] = params for k,v in pairs params -- expand nested[param][keys] front = k\match "^([^%[]+)%[" if type(k) == "string" if front curr = @params for match in k\gmatch "%[(.-)%]" new = curr[front] if type(new) != "table" new = {} curr[front] = new curr = new front = match curr[front] = v else @params[k] = v } new: (@app, @req, @res) => @buffer = {} -- output buffer @params = {} @options = {} @@support.load_cookies @ @@support.load_session @ flow: (flow) => key = "_flow_#{flow}" unless @[key] @[key] = require("#{@app.flows_prefix}.#{flow}") @ @[key] html: (fn) => html_writer fn url_for: (first, ...) => if type(first) == "table" @app.router\url_for first\url_params @, ... else @app.router\url_for first, ... -- @build_url! --> http://example.com:8080 -- @build_url "hello_world" --> http://example.com:8080/hello_world -- @build_url "hello_world?color=blue" --> http://example.com:8080/hello_world?color=blue -- @build_url "cats", host: "leafo.net", port: 2000 --> http://leafo.net:2000/cats -- Where example.com is the host of the request, and 8080 is current port build_url: (path, options) => return path if path and (path\match("^%a+:") or path\match "^//") parsed = @@support.default_url_params @ if path _path, query = path\match("^(.-)%?(.*)$") path = _path or path parsed.query = query parsed.path = path scheme = parsed.scheme or "http" if scheme == "http" and (parsed.port == "80" or parsed.port == 80) parsed.port = nil if scheme == "https" and (parsed.port == "443" or parsed.port == 443) parsed.port = nil if options for k,v in pairs options parsed[k] = v build_url parsed write: (thing, ...) => t = type(thing) -- is it callable? if t == "table" mt = getmetatable(thing) if mt and mt.__call t = "function" switch t when "string" insert @buffer, thing when "table" -- see if there are options for k,v in pairs thing if type(k) == "string" @options[k] = v else @write v when "function" @write thing @buffer when "nil" nil -- ignore else error "Don't know how to write: (#{t}) #{thing}" @write ... if ...
25.40856
91
0.569832
829c16390f0fae9c493167f9d2bc3a9495a742f2
98,362
-- -- Copyright (C) 2017-2020 DBotThePony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. -- Texture indexes (-1) -- 1 = models/ppm2/base/eye_l -- 2 = models/ppm2/base/eye_r -- 3 = models/ppm2/base/body -- 4 = models/ppm2/base/horn -- 5 = models/ppm2/base/wings -- 6 = models/ppm2/base/hair_color_1 -- 7 = models/ppm2/base/hair_color_2 -- 8 = models/ppm2/base/tail_color_1 -- 9 = models/ppm2/base/tail_color_2 -- 10 = models/ppm2/base/cmark -- 11 = models/ppm2/base/eyelashes PPM2.CacheManager = DLib.CacheManager('ppm2_cache', 1024 * 0x00100000, 'vtf') PPM2.CacheManager\AddCommands() PPM2.CacheManager\SetConVar() developer = ConVar('developer') grind_down_color = (r, g, b, a) -> return "#{math.round(r.r * 0.12156862745098)}_#{math.round(r.g * 0.24705882352941)}-#{math.round(r.b * 0.12156862745098)}_#{math.round(r.a * 0.12156862745098)}" if IsColor(r) return "#{math.round(r * 0.12156862745098)}_#{math.round(g * 0.24705882352941)}_#{math.round(b * 0.12156862745098)}_#{math.round((a or 255) * 0.12156862745098)}" PPM2.IsValidURL = (url) -> print(debug.traceback()) if not isstring(url) url ~= '' and url\find('^https?://') and url or false PPM2.BuildURLHTML = (url, width, height) -> url = url\Replace('%', '%25')\Replace(' ', '%20')\Replace('"', '%22')\Replace("'", '%27')\Replace('#', '%23')\Replace('<', '%3C')\Replace('=', '%3D')\Replace('>', '%3E') return "<html> <head> <style> html, body { background: transparent; margin: 0; padding: 0; overflow: hidden; } #mainimage { max-width: #{width}; height: auto; width: 100%; margin: 0; padding: 0; max-height: #{height}; } #imgdiv { width: #{width}; height: #{height}; overflow: hidden; margin: 0; padding: 0; text-align: center; } </style> <script> window.onload = function() { var img = document.getElementById('mainimage'); if (img.naturalWidth < img.naturalHeight) { img.style.setProperty('height', '100%'); img.style.setProperty('width', 'auto'); } img.style.setProperty('margin-top', (#{height} - img.height) / 2); setInterval(function() { console.log('FRAME'); }, 50); }; </script> </head> <body> <div id='imgdiv'> <img src='#{url}' id='mainimage' /> </div> </body> </html>" PPM2.HTML_MATERIAL_QUEUE = PPM2.HTML_MATERIAL_QUEUE or {} PPM2.URL_MATERIAL_CACHE = PPM2.URL_MATERIAL_CACHE or {} PPM2.ALREADY_DOWNLOADING = PPM2.ALREADY_DOWNLOADING or {} PPM2.FAILED_TO_DOWNLOAD = PPM2.FAILED_TO_DOWNLOAD or {} PPM2.TEXTURE_TASKS = PPM2.TEXTURE_TASKS or {} PPM2.TEXTURE_TASKS_EDITOR = PPM2.TEXTURE_TASKS_EDITOR or {} coroutine_yield = coroutine.yield coroutine_resume = coroutine.resume coroutine_status = coroutine.status PPM2.MAX_TASKS = 0 PPM2.COMPLETED_TASKS = 0 PPM2.LAST_TASK = 0 PPM2.TextureCompileWorker = -> while true name, task = next(PPM2.TEXTURE_TASKS) if not name coroutine_yield() if not next(PPM2.TEXTURE_TASKS_EDITOR) DLib.Util.PopProgress('ppm2_busy') if PPM2.LAST_TASK < SysTime() PPM2.MAX_TASKS = 0 PPM2.COMPLETED_TASKS = 0 else PPM2.TEXTURE_TASKS[name] = nil PPM2.TEXTURE_TASK_CURRENT = name DLib.Util.PushProgress('ppm2_busy', DLib.I18n.Localize('gui.ppm2.busy'), PPM2.COMPLETED_TASKS / PPM2.MAX_TASKS) task[1](task[2], false, task[3], task[4]) if IsValid(task[2]) task[2].texture_tasks -= 1 task[2]._once = true PPM2.COMPLETED_TASKS += 1 PPM2.LAST_TASK = SysTime() + 5 DLib.Util.PushProgress('ppm2_busy', DLib.I18n.Localize('gui.ppm2.busy'), PPM2.COMPLETED_TASKS / PPM2.MAX_TASKS) if not next(PPM2.TEXTURE_TASKS) DLib.Util.PopProgress('ppm2_busy') PPM2.TEXTURE_TASK_CURRENT = nil PPM2.TextureCompileThread = PPM2.TextureCompileThread or coroutine.create(PPM2.TextureCompileWorker) null_texrure = GetRenderTarget('ppm2__null', 4, 4) render.PushRenderTarget(null_texrure) render.Clear(0, 0, 0, 0, true, true) render.PopRenderTarget() PPM2.URLThreadWorker = -> while true if not PPM2.HTML_MATERIAL_QUEUE[1] coroutine_yield() else data = table.remove(PPM2.HTML_MATERIAL_QUEUE, 1) panel = vgui.Create('DHTML') panel\SetVisible(false) panel\SetSize(data.width, data.height) panel\SetHTML(PPM2.BuildURLHTML(data.url, data.width, data.height)) panel\Refresh() frame = 0 panel.ConsoleMessage = (pnl, msg) -> if msg == 'FRAME' frame += 1 systime = SysTime() + 16 timeout = false while panel\IsLoading() or frame < 20 if systime <= SysTime() timeout = true panel\Remove() if IsValid(panel) newMat = CreateMaterial("PPM2_URLMaterial_Failed_#{data.hash}", 'UnlitGeneric', { '$basetexture': 'null' '$ignorez': 1 '$vertexcolor': 1 '$vertexalpha': 1 '$nolod': 1 '$translucent': 1 }) newMat\SetTexture('$basetexture', null_texrure) PPM2.FAILED_TO_DOWNLOAD[data.index] = { texture: newMat\GetTexture('$basetexture') material: newMat index: data.index hash: data.hash } PPM2.ALREADY_DOWNLOADING[data.index] = nil for resolve in *data.resolve resolve(newMat\GetTexture('$basetexture'), newMat) break coroutine_yield() if not timeout panel\UpdateHTMLTexture() htmlmat = panel\GetHTMLMaterial() systime = SysTime() + 1 while not htmlmat and systime <= SysTime() htmlmat = panel\GetHTMLMaterial() if htmlmat rt, mat = PPM2.PonyTextureController\LockRenderTarget(data.width, data.height, 0, 0, 0, 0) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) surface.SetDrawColor(255, 255, 255) surface.SetMaterial(htmlmat) surface.DrawTexturedRect(0, 0, data.width, data.height) render.PopFilterMag() render.PopFilterMin() vtf = DLib.VTF.Create(2, data.width, data.height, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGBA8888 or IMAGE_FORMAT_DXT5, { fill: Color(0, 0, 0, 0) flags: TEXTUREFLAGS_CLAMPS\bor(TEXTUREFLAGS_CLAMPT) }) vtf\CaptureRenderTargetCoroutine() if select('#', render.ReadPixel(0, 0)) == 3 PPM2.PonyTextureController\_CaptureAlphaClosure(data.width, mat, vtf) else PPM2.PonyTextureController\ReleaseRenderTarget(data.width, data.height) path = '../data/' .. PPM2.CacheManager\Set(data.index, vtf\ToString()) newMat = CreateMaterial("PPM2_URLMaterial_#{data.hash}", 'UnlitGeneric', { '$basetexture': '../data/' .. path '$ignorez': 1 '$vertexcolor': 1 '$vertexalpha': 1 '$nolod': 1 }) newMat\SetTexture('$basetexture', '../data/' .. path) newMat\GetTexture('$basetexture')\Download() PPM2.URL_MATERIAL_CACHE[data.index] = { texture: newMat\GetTexture('$basetexture') material: newMat index: data.index hash: data.hash } PPM2.ALREADY_DOWNLOADING[data.index] = nil for resolve in *data.resolve resolve(newMat\GetTexture('$basetexture'), newMat) else newMat = CreateMaterial("PPM2_URLMaterial_Failed_#{data.hash}", 'UnlitGeneric', { '$basetexture': 'null' '$ignorez': 1 '$vertexcolor': 1 '$vertexalpha': 1 '$nolod': 1 '$translucent': 1 }) PPM2.FAILED_TO_DOWNLOAD[data.index] = { texture: newMat\GetTexture('$basetexture') material: newMat index: data.index hash: data.hash } PPM2.ALREADY_DOWNLOADING[data.index] = nil for resolve in *data.resolve resolve(newMat\GetTexture('$basetexture'), newMat) coroutine_yield() panel\Remove() if IsValid(panel) PPM2.URLThread = PPM2.URLThread or coroutine.create(PPM2.URLThreadWorker) PPM2.GetURLMaterial = (url, width = 512, height = 512) -> assert(isstring(url) and url\trim() ~= '', 'Must specify valid URL', 2) index = url .. '__' .. width .. '_' .. height .. '_clamp' index ..= '_rgba8888' if PPM2.NO_COMPRESSION\GetBool() if data = PPM2.FAILED_TO_DOWNLOAD[index] return DLib.Promise (resolve) -> resolve(data.texture, data.material) if data = PPM2.URL_MATERIAL_CACHE[index] return DLib.Promise (resolve) -> resolve(data.texture, data.material) if data = PPM2.ALREADY_DOWNLOADING[index] return DLib.Promise (resolve) -> table.insert(data.resolve, resolve) if getcache = PPM2.CacheManager\HasGet(index) return DLib.Promise (resolve) -> hash = DLib.Util.QuickSHA1(index) newMat = CreateMaterial("PPM2_URLMaterial_#{hash}", 'UnlitGeneric', { '$basetexture': '../data/' .. getcache '$ignorez': 1 '$vertexcolor': 1 '$vertexalpha': 1 '$nolod': 1 }) newMat\SetTexture('$basetexture', '../data/' .. getcache) newMat\GetTexture('$basetexture')\Download() if developer\GetBool() PPM2.URL_MATERIAL_CACHE[index] = { texture: newMat\GetTexture('$basetexture') material: newMat index: index :hash } resolve(newMat\GetTexture('$basetexture'), newMat) return DLib.Promise (resolve) -> data = { :url :width :height :index hash: DLib.Util.QuickSHA1(index) resolve: {resolve} } PPM2.ALREADY_DOWNLOADING[index] = data table.insert(PPM2.HTML_MATERIAL_QUEUE, data) hook.Add 'Think', 'PPM2 Material Tasks', -> status, err = coroutine_resume(PPM2.URLThread) if not status PPM2.URLThread = coroutine.create(PPM2.URLThreadWorker) error(err) status, err = coroutine_resume(PPM2.TextureCompileThread) if not status table.Empty(PPM2.PonyTextureController.LOCKED_RENDERTARGETS) PPM2.TextureCompileThread = coroutine.create(PPM2.TextureCompileWorker) error('Texture task thread failed: ' .. err) for name, {thread, self, lock, release} in pairs(PPM2.TEXTURE_TASKS_EDITOR) if coroutine_status(thread) == 'dead' PPM2.TEXTURE_TASKS_EDITOR[name] = nil self.texture_tasks -= 1 PPM2.COMPLETED_TASKS += 1 DLib.Util.PushProgress('ppm2_busy', DLib.I18n.Localize('gui.ppm2.busy'), PPM2.COMPLETED_TASKS / PPM2.MAX_TASKS) else status, err = coroutine_resume(thread, self, true, lock, release) if not status PPM2.TEXTURE_TASKS_EDITOR[name] = nil self.texture_tasks -= 1 PPM2.COMPLETED_TASKS += 1 error(name .. ' editor texture task failed: ' .. err) hook.Add 'InvalidateMaterialCache', 'PPM2.WebTexturesCache', -> PPM2.HTML_MATERIAL_QUEUE = {} PPM2.URL_MATERIAL_CACHE = {} PPM2.ALREADY_DOWNLOADING = {} PPM2.FAILED_TO_DOWNLOAD = {} table.Empty(PPM2.PonyTextureController.LOCKED_RENDERTARGETS) table.Empty(PPM2.PonyTextureController.LOCKED_RENDERTARGETS_MASK) PPM2.URLThread = coroutine.create(PPM2.URLThreadWorker) PPM2.TextureCompileThread = coroutine.create(PPM2.TextureCompileWorker) null_texrure = GetRenderTarget('ppm2__null', 4, 4) render.PushRenderTarget(null_texrure) render.Clear(0, 0, 0, 0, true, true) render.PopRenderTarget() PPM2.TextureTableHash = (input) -> hash = DLib.Util.SHA1() hash\Update('post intel fix') hash\Update('post sampling fix') hash\Update('rgba8888') if PPM2.NO_COMPRESSION\GetBool() hash\Update(' ' .. tostring(value) .. ' ') for value in *input return hash\Digest() DrawTexturedRectRotated = (x = 0, y = 0, width = 0, height = 0, rotation = 0) -> surface.DrawTexturedRectRotated(x + width / 2, y + height / 2, width, height, rotation) GetMat = (matIn) -> return matIn if not isstring(matIn) return Material(matIn, 'smooth'), nil LOCKED_RENDERTARGETS = PPM2.PonyTextureController and PPM2.PonyTextureController.LOCKED_RENDERTARGETS class PPM2.PonyTextureController extends PPM2.ControllerChildren @AVALIABLE_CONTROLLERS = {} @MODELS = {'models/ppm/player_default_base.mdl', 'models/ppm/player_default_base_nj.mdl', 'models/cppm/player_default_base.mdl', 'models/cppm/player_default_base_nj.mdl'} @HAIR_MATERIAL_COLOR = PPM2.MaterialsRegistry.HAIR_MATERIAL_COLOR @TAIL_MATERIAL_COLOR = PPM2.MaterialsRegistry.TAIL_MATERIAL_COLOR @WINGS_MATERIAL_COLOR = PPM2.MaterialsRegistry.WINGS_MATERIAL_COLOR @HORN_MATERIAL_COLOR = PPM2.MaterialsRegistry.HORN_MATERIAL_COLOR @BODY_MATERIAL = PPM2.MaterialsRegistry.BODY_MATERIAL @HORN_DETAIL_COLOR = PPM2.MaterialsRegistry.HORN_DETAIL_COLOR @EYE_OVAL = PPM2.MaterialsRegistry.EYE_OVAL @EYE_OVALS = PPM2.MaterialsRegistry.EYE_OVALS @EYE_GRAD = PPM2.MaterialsRegistry.EYE_GRAD @EYE_EFFECT = PPM2.MaterialsRegistry.EYE_EFFECT @EYE_LINE_L_1 = PPM2.MaterialsRegistry.EYE_LINE_L_1 @EYE_LINE_R_1 = PPM2.MaterialsRegistry.EYE_LINE_R_1 @EYE_LINE_L_2 = PPM2.MaterialsRegistry.EYE_LINE_L_2 @EYE_LINE_R_2 = PPM2.MaterialsRegistry.EYE_LINE_R_2 @PONY_SOCKS = PPM2.MaterialsRegistry.PONY_SOCKS @MAT_INDEX_EYE_LEFT = 0 @MAT_INDEX_EYE_RIGHT = 1 @MAT_INDEX_BODY = 2 @MAT_INDEX_HORN = 3 @MAT_INDEX_WINGS = 4 @MAT_INDEX_HAIR_COLOR1 = 5 @MAT_INDEX_HAIR_COLOR2 = 6 @MAT_INDEX_TAIL_COLOR1 = 7 @MAT_INDEX_TAIL_COLOR2 = 8 @MAT_INDEX_CMARK = 9 @MAT_INDEX_EYELASHES = 10 @NEXT_GENERATED_ID = 100000 @BODY_UPDATE_TRIGGER = {} @MANE_UPDATE_TRIGGER = {'ManeType': true, 'ManeTypeLower': true} @TAIL_UPDATE_TRIGGER = {'TailType': true} @EYE_UPDATE_TRIGGER = {'SeparateEyes': true, 'IrisSizeInternal': true} @PHONG_UPDATE_TRIGGER = { 'SeparateHornPhong': true 'SeparateWingsPhong': true 'SeparateManePhong': true 'SeparateTailPhong': true } @CLOTHES_UPDATE_HEAD = { 'HeadClothes': true 'HeadClothesUseColor': true } @CLOTHES_UPDATE_NECK = { 'NeckClothes': true 'NeckClothesUseColor': true } @CLOTHES_UPDATE_BODY = { 'BodyClothes': true 'BodyClothesUseColor': true } @CLOTHES_UPDATE_EYES = { 'EyeClothes': true 'EyeClothesUseColor': true } for i = 1, PPM2.MAX_CLOTHES_COLORS @CLOTHES_UPDATE_HEAD["HeadClothesColor#{i}"] = true @CLOTHES_UPDATE_NECK["NeckClothesColor#{i}"] = true @CLOTHES_UPDATE_BODY["BodyClothesColor#{i}"] = true @CLOTHES_UPDATE_EYES["EyeClothesColor#{i}"] = true for i = 1, PPM2.MAX_CLOTHES_URLS @CLOTHES_UPDATE_HEAD["HeadClothesURL#{i}"] = true @CLOTHES_UPDATE_NECK["NeckClothesURL#{i}"] = true @CLOTHES_UPDATE_BODY["BodyClothesURL#{i}"] = true @CLOTHES_UPDATE_EYES["EyeClothesURL#{i}"] = true for _, ttype in ipairs {'Body', 'Horn', 'Wings', 'BatWingsSkin', 'Socks', 'Mane', 'Tail', 'UpperMane', 'LowerMane', 'LEye', 'REye', 'BEyes', 'Eyelashes'} @PHONG_UPDATE_TRIGGER[ttype .. 'PhongExponent'] = true @PHONG_UPDATE_TRIGGER[ttype .. 'PhongBoost'] = true @PHONG_UPDATE_TRIGGER[ttype .. 'PhongTint'] = true @PHONG_UPDATE_TRIGGER[ttype .. 'PhongFront'] = true @PHONG_UPDATE_TRIGGER[ttype .. 'PhongMiddle'] = true @PHONG_UPDATE_TRIGGER[ttype .. 'PhongSliding'] = true @PHONG_UPDATE_TRIGGER[ttype .. 'Lightwarp'] = true @PHONG_UPDATE_TRIGGER[ttype .. 'LightwarpURL'] = true for _, publicName in ipairs {'', 'Left', 'Right'} @EYE_UPDATE_TRIGGER["EyeReflectionType#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeType#{publicName}"] = true @EYE_UPDATE_TRIGGER["HoleWidth#{publicName}"] = true @EYE_UPDATE_TRIGGER["IrisSize#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeLines#{publicName}"] = true @EYE_UPDATE_TRIGGER["HoleSize#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeBackground#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeIrisTop#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeIrisBottom#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeIrisLine1#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeIrisLine2#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeHole#{publicName}"] = true @EYE_UPDATE_TRIGGER["DerpEyesStrength#{publicName}"] = true @EYE_UPDATE_TRIGGER["DerpEyes#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeReflection#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeEffect#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeURL#{publicName}"] = true @EYE_UPDATE_TRIGGER["IrisWidth#{publicName}"] = true @EYE_UPDATE_TRIGGER["IrisHeight#{publicName}"] = true @EYE_UPDATE_TRIGGER["HoleHeight#{publicName}"] = true @EYE_UPDATE_TRIGGER["HoleShiftX#{publicName}"] = true @EYE_UPDATE_TRIGGER["HoleShiftY#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeRotation#{publicName}"] = true @EYE_UPDATE_TRIGGER["PonySize"] = true @EYE_UPDATE_TRIGGER["EyeRefract#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeCornerA#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeLineDirection#{publicName}"] = true @EYE_UPDATE_TRIGGER["EyeGlossyStrength#{publicName}"] = true @EYE_UPDATE_TRIGGER["LEyeLightwarp"] = true @EYE_UPDATE_TRIGGER["REyeLightwarp"] = true @EYE_UPDATE_TRIGGER["LEyeLightwarpURL"] = true @EYE_UPDATE_TRIGGER["REyeLightwarpURL"] = true @EYE_UPDATE_TRIGGER["BEyesLightwarp"] = true @EYE_UPDATE_TRIGGER["BEyesLightwarpURL"] = true for i = 1, 6 @MANE_UPDATE_TRIGGER["ManeColor#{i}"] = true @MANE_UPDATE_TRIGGER["ManeDetailColor#{i}"] = true @MANE_UPDATE_TRIGGER["ManeURLColor#{i}"] = true @MANE_UPDATE_TRIGGER["ManeURL#{i}"] = true @MANE_UPDATE_TRIGGER["TailURL#{i}"] = true @MANE_UPDATE_TRIGGER["TailURLColor#{i}"] = true @TAIL_UPDATE_TRIGGER["TailColor#{i}"] = true @TAIL_UPDATE_TRIGGER["TailDetailColor#{i}"] = true for i = 1, PPM2.MAX_BODY_DETAILS @BODY_UPDATE_TRIGGER["BodyDetail#{i}"] = true @BODY_UPDATE_TRIGGER["BodyDetailColor#{i}"] = true @BODY_UPDATE_TRIGGER["BodyDetailURLColor#{i}"] = true @BODY_UPDATE_TRIGGER["BodyDetailURL#{i}"] = true @BODY_UPDATE_TRIGGER["BodyDetailGlow#{i}"] = true @BODY_UPDATE_TRIGGER["BodyDetailGlowStrength#{i}"] = true @BODY_UPDATE_TRIGGER["BodyDetailFirst#{i}"] = true @BODY_UPDATE_TRIGGER["BodyDetailURLFirst#{i}"] = true for i = 1, PPM2.MAX_TATTOOS @BODY_UPDATE_TRIGGER["TattooType#{i}"] = true @BODY_UPDATE_TRIGGER["TattooPosX#{i}"] = true @BODY_UPDATE_TRIGGER["TattooPosY#{i}"] = true @BODY_UPDATE_TRIGGER["TattooRotate#{i}"] = true @BODY_UPDATE_TRIGGER["TattooScaleX#{i}"] = true @BODY_UPDATE_TRIGGER["TattooScaleY#{i}"] = true @BODY_UPDATE_TRIGGER["TattooColor#{i}"] = true @BODY_UPDATE_TRIGGER["TattooGlow#{i}"] = true @BODY_UPDATE_TRIGGER["TattooGlowStrength#{i}"] = true @BODY_UPDATE_TRIGGER["TattooOverDetail#{i}"] = true @GetCacheH = (hash) => path = PPM2.CacheManager\HasGetHash(hash) return if not path return '../data/' .. path @SetCacheH = (hash, value) => '../data/' .. PPM2.CacheManager\SetHash(hash, value) @LOCKED_RENDERTARGETS = LOCKED_RENDERTARGETS or {} @LOCKED_RENDERTARGETS_MASK = LOCKED_RENDERTARGETS_MASK or {} SelectLockFuncs: => if PPM2.NO_ENCODING\GetBool() return true, @LockRenderTargetHungry, @ReleaseRenderTargetHungry if @GrabData('IsEditor') return true, @LockRenderTargetEditor, @ReleaseRenderTargetEditor return false, @LockRenderTarget, @ReleaseRenderTarget LockRenderTargetHungry: (name, width, height, r = 0, g = 0, b = 0, a = 255) => index = string.format('ppm2_rt_%s_%s_%d_%d', @GetID(), name, width, height) rt = GetRenderTarget(index, width, height) render.PushRenderTarget(rt) render.Clear(r, g, b, a, true, true) cam.Start2D() surface.SetDrawColor(r, g, b, a) mat = CreateMaterial(index .. '_m', 'UnlitGeneric', { '$basetexture': '!' .. index, '$translucent': '1', }) mat\SetTexture('$basetexture', rt) return rt, mat ReleaseRenderTargetHungry: (name, width, height, no_pop = false) => index = string.format('ppm2_rt_%s_%s_%d_%d', @GetID(), name, width, height) if not no_pop cam.End2D() render.PopRenderTarget() return GetRenderTarget(index, width, height) LockRenderTargetEditor: (name, width, height, r = 0, g = 0, b = 0, a = 255) => index = string.format('PPM2_editor_%s_%d_%d', name, width, height) rt = GetRenderTarget(index, width, height) render.PushRenderTarget(rt) render.Clear(r, g, b, a, true, true) cam.Start2D() surface.SetDrawColor(r, g, b, a) mat = CreateMaterial(index .. 'a', 'UnlitGeneric', { '$basetexture': '!' .. index, '$translucent': '1', }) mat\SetTexture('$basetexture', rt) return rt, mat ReleaseRenderTargetEditor: (name, width, height, no_pop = false) => index = string.format('PPM2_editor_%s_%d_%d', name, width, height) if not no_pop cam.End2D() render.PopRenderTarget() return GetRenderTarget(index, width, height) LockRenderTarget: (name, ...) => @@LockRenderTarget(...) @LockRenderTarget = (width, height, r = 0, g = 0, b = 0, a = 255) => index = string.format('PPM2_buffer_%d_%d', width, height) while @LOCKED_RENDERTARGETS[index] coroutine_yield() @LOCKED_RENDERTARGETS[index] = true rt = GetRenderTarget(index, width, height) render.PushRenderTarget(rt) render.Clear(r, g, b, a, true, true) cam.Start2D() surface.SetDrawColor(r, g, b, a) surface.DrawRect(0, 0, width + 1, height + 1) mat = CreateMaterial(index .. 'a', 'UnlitGeneric', { '$basetexture': '!' .. index, '$translucent': '1', }) mat\SetTexture('$basetexture', rt) return rt, mat ReleaseRenderTarget: (name, ...) => @@ReleaseRenderTarget(...) @ReleaseRenderTarget = (width, height, no_pop = false) => index = string.format('PPM2_buffer_%d_%d', width, height) @LOCKED_RENDERTARGETS[index] = false if not no_pop cam.End2D() render.PopRenderTarget() return GetRenderTarget(index, width, height) LockRenderTargetMask: (name, ...) => @@LockRenderTargetMask(...) @LockRenderTargetMask = (width, height) => index = string.format('PPM2_mask_%d_%d', width, height) while @LOCKED_RENDERTARGETS_MASK[index] coroutine_yield() @LOCKED_RENDERTARGETS_MASK[index] = true index2 = string.format('PPM2_mask2_%d_%d', width, height) rt1, rt2 = GetRenderTarget(index, width, height), GetRenderTarget(index2, width, height) mat1, mat2 = CreateMaterial(index .. 'b', 'UnlitGeneric', { '$basetexture': '!' .. index, '$translucent': '1', }), CreateMaterial(index2 .. 'b', 'UnlitGeneric', { '$basetexture': '!' .. index2, '$translucent': '1', }) mat1\SetTexture('$basetexture', rt1) mat2\SetTexture('$basetexture', rt2) return rt1, rt2, mat1, mat2 ReleaseRenderTargetMask: (name, ...) => @@ReleaseRenderTargetMask(...) @ReleaseRenderTargetMask = (width, height) => index = string.format('PPM2_mask_%d_%d', width, height) index2 = string.format('PPM2_mask2_%d_%d', width, height) @LOCKED_RENDERTARGETS_MASK[index] = false return GetRenderTarget(index, width, height), GetRenderTarget(index2, width, height) new: (controller, compile = true) => super(controller\GetData()) @isValid = true @cachedENT = @GetEntity() @id = @GetEntity()\EntIndex() @load_tickets = {} if @id == -1 @clientsideID = true @id = @@NEXT_GENERATED_ID @@NEXT_GENERATED_ID += 1 @texture_tasks = 0 @compiled = false @lastMaterialUpdate = 0 @lastMaterialUpdateEnt = NULL @delayCompilation = {} @processing_first = true @CompileTextures() if compile hook.Add('InvalidateMaterialCache', @, @InvalidateMaterialCache, 100) HasActiveTasks: => @texture_tasks > 0 CreateRenderTask: (func = '', ...) => index = string.format('%p%s', @, func) isRenderTarget, lock, release = @SelectLockFuncs() if isRenderTarget return if PPM2.TEXTURE_TASKS_EDITOR[index] thread = coroutine.create(@[func]) PPM2.TEXTURE_TASKS_EDITOR[index] = {thread, @, lock, release} @texture_tasks += 1 PPM2.MAX_TASKS += 1 PPM2.LAST_TASK = SysTime() + 5 else return if PPM2.TEXTURE_TASKS[index] PPM2.TEXTURE_TASKS[index] = {@[func], @, lock, release} @texture_tasks += 1 PPM2.MAX_TASKS += 1 PPM2.LAST_TASK = SysTime() + 5 if not PPM2.TEXTURE_TASK_CURRENT and @_once coroutine.resume(PPM2.TextureCompileThread) DataChanges: (state) => return unless @isValid return if not @GetEntity() key = state\GetKey() if key\find('Separate') and key\find('Phong') @UpdatePhongData() return switch key when 'BodyColor' @CreateRenderTask('CompileBody') @CreateRenderTask('CompileWings') @CreateRenderTask('CompileHorn') when 'EyelashesColor' @CreateRenderTask('CompileEyelashes') when 'BodyBumpStrength', 'Socks', 'Bodysuit', 'LipsColor', 'NoseColor', 'LipsColorInherit', 'NoseColorInherit', 'EyebrowsColor', 'GlowingEyebrows', 'EyebrowsGlowStrength' @CreateRenderTask('CompileBody') when 'CMark', 'CMarkType', 'CMarkURL', 'CMarkColor', 'CMarkSize' @CreateRenderTask('CompileCMark') when 'SocksColor', 'SocksTextureURL', 'SocksTexture', 'SocksDetailColor1', 'SocksDetailColor2', 'SocksDetailColor3', 'SocksDetailColor4', 'SocksDetailColor5', 'SocksDetailColor6' @CreateRenderTask('CompileSocks') when 'NewSocksColor1', 'NewSocksColor2', 'NewSocksColor3', 'NewSocksTextureURL' @CreateRenderTask('CompileNewSocks') when 'HornURL1', 'SeparateHorn', 'HornColor', 'HornURL2', 'HornURL3', 'HornURLColor1', 'HornURLColor2', 'HornURLColor3', 'UseHornDetail', 'HornGlow', 'HornGlowSrength', 'HornDetailColor' @CreateRenderTask('CompileHorn') when 'WingsURL1', 'WingsURL2', 'WingsURL3', 'WingsURLColor1', 'WingsURLColor2', 'WingsURLColor3', 'SeparateWings', 'WingsColor' @CreateRenderTask('CompileWings') else if @@MANE_UPDATE_TRIGGER[key] @CreateRenderTask('CompileHair') elseif @@TAIL_UPDATE_TRIGGER[key] @CreateRenderTask('CompileTail') elseif @@EYE_UPDATE_TRIGGER[key] @CreateRenderTask('CompileLeftEye') @CreateRenderTask('CompileRightEye') elseif @@BODY_UPDATE_TRIGGER[key] @CreateRenderTask('CompileBody') elseif @@PHONG_UPDATE_TRIGGER[key] @UpdatePhongData() elseif @@CLOTHES_UPDATE_HEAD[key] @CreateRenderTask('CompileHeadClothes') elseif @@CLOTHES_UPDATE_EYES[key] @CreateRenderTask('CompileEyeClothes') elseif @@CLOTHES_UPDATE_NECK[key] @CreateRenderTask('CompileNeckClothes') elseif @@CLOTHES_UPDATE_BODY[key] @CreateRenderTask('CompileBodyClothes') PutTicket: (name) => @load_tickets[name] = (@load_tickets[name] or 0) + 1 return @load_tickets[name] CheckTicket: (name, value) => return @load_tickets[name] == value InvalidateMaterialCache: => timer.Simple 0, -> @CompileTextures() Remove: => @isValid = false @ResetTextures() IsValid: => @isValid and @GetData()\IsValid() GetID: => return @GetObjectSlot() if @GetObjectSlot() return @id if @clientsideID if @GetEntity() ~= @cachedENT @cachedENT = @GetEntity() @id = @GetEntity()\EntIndex() if @id == -1 @id = @@NEXT_GENERATED_ID @@NEXT_GENERATED_ID += 1 @CompileTextures() if @compiled return @id GetBody: => @BodyMaterial GetBodyName: => @BodyMaterialName GetSocks: => @SocksMaterial GetSocksName: => @SocksMaterialName GetNewSocks: => @NewSocksColor1, @NewSocksColor2, @NewSocksBase GetNewSocksName: => @NewSocksColor1Name, @NewSocksColor2Name, @NewSocksBaseName GetCMark: => @CMarkTexture GetCMarkName: => @CMarkTextureName GetGUICMark: => @CMarkTextureGUI GetGUICMarkName: => @CMarkTextureGUIName GetCMarkGUI: => @CMarkTextureGUI GetCMarkGUIName: => @CMarkTextureGUIName GetHair: (index = 1) => if index == 2 return @HairColor2Material else return @HairColor1Material GetHairName: (index = 1) => if index == 2 return @HairColor2MaterialName else return @HairColor1MaterialName GetMane: (index = 1) => if index == 2 return @HairColor2Material else return @HairColor1Material GetManeName: (index = 1) => if index == 2 return @HairColor2MaterialName else return @HairColor1MaterialName GetTail: (index = 1) => if index == 2 return @TailColor2Material else return @TailColor1Material GetTailName: (index = 1) => if index == 2 return @TailColor2MaterialName else return @TailColor1MaterialName GetEye: (left = false) => if left return @EyeMaterialL else return @EyeMaterialR GetEyeName: (left = false) => if left return @EyeMaterialLName else return @EyeMaterialRName GetHorn: => @HornMaterial GetHornName: => @HornMaterialName GetWings: => @WingsMaterial GetWingsName: => @WingsMaterialName CompileTextures: => return if not @GetData()\IsValid() @CreateRenderTask('CompileBody') @CreateRenderTask('CompileHair') @CreateRenderTask('CompileTail') @CreateRenderTask('CompileHorn') @CreateRenderTask('CompileWings') @CreateRenderTask('CompileCMark') @CreateRenderTask('CompileSocks') @CreateRenderTask('CompileNewSocks') @CreateRenderTask('CompileEyelashes') @CreateRenderTask('CompileLeftEye') @CreateRenderTask('CompileRightEye') @CreateRenderTask('CompileBodyClothes') @CreateRenderTask('CompileNeckClothes') @CreateRenderTask('CompileHeadClothes') @CreateRenderTask('CompileEyeClothes') @compiled = true PreDraw: (ent = @GetEntity(), drawingNewTask = false) => --return unless @compiled return unless @isValid if @lastMaterialUpdate < RealTimeL() or @lastMaterialUpdateEnt ~= ent @lastMaterialUpdateEnt = ent @lastMaterialUpdate = RealTimeL() + 1 ent\SetSubMaterial(@@MAT_INDEX_EYE_LEFT, @GetEyeName(true)) ent\SetSubMaterial(@@MAT_INDEX_EYE_RIGHT, @GetEyeName(false)) ent\SetSubMaterial(@@MAT_INDEX_BODY, @GetBodyName()) ent\SetSubMaterial(@@MAT_INDEX_HORN, @GetHornName()) ent\SetSubMaterial(@@MAT_INDEX_WINGS, @GetWingsName()) ent\SetSubMaterial(@@MAT_INDEX_HAIR_COLOR1, @GetHairName(1)) ent\SetSubMaterial(@@MAT_INDEX_HAIR_COLOR2, @GetHairName(2)) ent\SetSubMaterial(@@MAT_INDEX_TAIL_COLOR1, @GetTailName(1)) ent\SetSubMaterial(@@MAT_INDEX_TAIL_COLOR2, @GetTailName(2)) ent\SetSubMaterial(@@MAT_INDEX_CMARK, @GetCMarkName()) ent\SetSubMaterial(@@MAT_INDEX_EYELASHES, @EyelashesName) if drawingNewTask render.MaterialOverrideByIndex(@@MAT_INDEX_EYE_LEFT, @GetEye(true)) render.MaterialOverrideByIndex(@@MAT_INDEX_EYE_RIGHT, @GetEye(false)) render.MaterialOverrideByIndex(@@MAT_INDEX_BODY, @GetBody()) render.MaterialOverrideByIndex(@@MAT_INDEX_HORN, @GetHorn()) render.MaterialOverrideByIndex(@@MAT_INDEX_WINGS, @GetWings()) render.MaterialOverrideByIndex(@@MAT_INDEX_HAIR_COLOR1, @GetHair(1)) render.MaterialOverrideByIndex(@@MAT_INDEX_HAIR_COLOR2, @GetHair(2)) render.MaterialOverrideByIndex(@@MAT_INDEX_TAIL_COLOR1, @GetTail(1)) render.MaterialOverrideByIndex(@@MAT_INDEX_TAIL_COLOR2, @GetTail(2)) render.MaterialOverrideByIndex(@@MAT_INDEX_CMARK, @GetCMark()) render.MaterialOverrideByIndex(@@MAT_INDEX_EYELASHES, @Eyelashes) PostDraw: (ent = @GetEntity(), drawingNewTask = false) => --return unless @compiled return unless @isValid return unless drawingNewTask render.MaterialOverrideByIndex(@@MAT_INDEX_EYE_LEFT) render.MaterialOverrideByIndex(@@MAT_INDEX_EYE_RIGHT) render.MaterialOverrideByIndex(@@MAT_INDEX_BODY) render.MaterialOverrideByIndex(@@MAT_INDEX_HORN) render.MaterialOverrideByIndex(@@MAT_INDEX_WINGS) render.MaterialOverrideByIndex(@@MAT_INDEX_HAIR_COLOR1) render.MaterialOverrideByIndex(@@MAT_INDEX_HAIR_COLOR2) render.MaterialOverrideByIndex(@@MAT_INDEX_TAIL_COLOR1) render.MaterialOverrideByIndex(@@MAT_INDEX_TAIL_COLOR2) render.MaterialOverrideByIndex(@@MAT_INDEX_CMARK) ResetTextures: (ent = @GetEntity()) => return if not IsValid(ent) @lastMaterialUpdateEnt = NULL @lastMaterialUpdate = 0 ent\SetSubMaterial(@@MAT_INDEX_EYE_LEFT) ent\SetSubMaterial(@@MAT_INDEX_EYE_RIGHT) ent\SetSubMaterial(@@MAT_INDEX_BODY) ent\SetSubMaterial(@@MAT_INDEX_HORN) ent\SetSubMaterial(@@MAT_INDEX_WINGS) ent\SetSubMaterial(@@MAT_INDEX_HAIR_COLOR1) ent\SetSubMaterial(@@MAT_INDEX_HAIR_COLOR2) ent\SetSubMaterial(@@MAT_INDEX_TAIL_COLOR1) ent\SetSubMaterial(@@MAT_INDEX_TAIL_COLOR2) ent\SetSubMaterial(@@MAT_INDEX_CMARK) ent\SetSubMaterial(@@MAT_INDEX_EYELASHES) PreDrawLegs: (ent = @GetEntity()) => --return unless @compiled return unless @isValid render.MaterialOverrideByIndex(@@MAT_INDEX_BODY, @GetBody()) render.MaterialOverrideByIndex(@@MAT_INDEX_HORN, @GetHorn()) render.MaterialOverrideByIndex(@@MAT_INDEX_WINGS, @GetWings()) render.MaterialOverrideByIndex(@@MAT_INDEX_CMARK, @GetCMark()) PostDrawLegs: (ent = @GetEntity()) => --return unless @compiled return unless @isValid render.MaterialOverrideByIndex(@@MAT_INDEX_BODY) render.MaterialOverrideByIndex(@@MAT_INDEX_HORN) render.MaterialOverrideByIndex(@@MAT_INDEX_WINGS) render.MaterialOverrideByIndex(@@MAT_INDEX_CMARK) @MAT_INDEX_SOCKS = 0 UpdateSocks: (ent = @GetEntity(), socksEnt) => return unless @isValid socksEnt\SetSubMaterial(@@MAT_INDEX_SOCKS, @GetSocksName()) UpdateNewSocks: (ent = @GetEntity(), socksEnt) => return unless @isValid socksEnt\SetSubMaterial(0, @NewSocksColor2Name) socksEnt\SetSubMaterial(1, @NewSocksColor1Name) socksEnt\SetSubMaterial(2, @NewSocksBaseName) UpdateNewHorn: (ent = @GetEntity(), hornEnt) => return unless @isValid hornEnt\SetSubMaterial(0, @HornMaterialName1) hornEnt\SetSubMaterial(1, @HornMaterialName2) UpdateClothes: (ent = @GetEntity(), clothesEnt) => return unless @isValid if @NeckClothes_Index if @NeckClothes_MatName clothesEnt\SetSubMaterial(@NeckClothes_Index[index], @NeckClothes_MatName[index]) for index = 1, @NeckClothes_Index.size else clothesEnt\SetSubMaterial(index, '') for index in *@NeckClothes_Index if @EyeClothes_Index if @EyeClothes_MatName clothesEnt\SetSubMaterial(@EyeClothes_Index[index], @EyeClothes_MatName[index]) for index = 1, @EyeClothes_Index.size else clothesEnt\SetSubMaterial(index, '') for index in *@EyeClothes_Index if @HeadClothes_Index if @HeadClothes_MatName clothesEnt\SetSubMaterial(@HeadClothes_Index[index], @HeadClothes_MatName[index]) for index = 1, @HeadClothes_Index.size else clothesEnt\SetSubMaterial(index, '') for index in *@HeadClothes_Index if @BodyClothes_Index if @BodyClothes_MatName clothesEnt\SetSubMaterial(@BodyClothes_Index[index], @BodyClothes_MatName[index]) for index = 1, @BodyClothes_Index.size else clothesEnt\SetSubMaterial(index, '') for index in *@BodyClothes_Index @clothesModel = clothesEnt @QUAD_SIZE_EYES = 512 @QUAD_SIZE_SOCKS = 512 @QUAD_SIZE_CLOTHES_BODY = 1024 @QUAD_SIZE_CLOTHES_HEAD = 512 @QUAD_SIZE_CLOTHES_NECK = 512 @QUAD_SIZE_CLOTHES_EYES = 256 @QUAD_SIZE_CMARK = 512 @QUAD_SIZE_CONST = 512 @QUAD_SIZE_WING = 64 @QUAD_SIZE_HORN = 512 @QUAD_SIZE_HAIR = 512 @QUAD_SIZE_TAIL = 512 @QUAD_SIZE_BODY = 2048 @TATTOO_DEF_SIZE = 128 DrawTattoo: (index = 1, drawingGlow = false, texSize = (PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) + 1) * @@QUAD_SIZE_BODY) => mat = PPM2.MaterialsRegistry.TATTOOS[@GrabData("TattooType#{index}")] return if not mat X, Y = @GrabData("TattooPosX#{index}"), @GrabData("TattooPosY#{index}") TattooRotate = @GrabData("TattooRotate#{index}") TattooScaleX = @GrabData("TattooScaleX#{index}") TattooScaleY = @GrabData("TattooScaleY#{index}") if not drawingGlow {:r, :g, :b} = @GrabData("TattooColor#{index}") surface.SetDrawColor(r, g, b) else if @GrabData("TattooGlow#{index}") surface.SetDrawColor(255, 255, 255, 255 * @GrabData("TattooGlowStrength#{index}")) else surface.SetDrawColor(0, 0, 0) surface.SetMaterial(mat) tSize = @@TATTOO_DEF_SIZE * (PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) + 1) sizeX, sizeY = tSize * TattooScaleX, tSize * TattooScaleY surface.DrawTexturedRectRotated((X * texSize / 2) / 100 + texSize / 2, -(Y * texSize / 2) / 100 + texSize / 2, sizeX, sizeY, TattooRotate) ApplyPhongData: (matTarget, prefix = 'Body', lightwarpsOnly = false, noBump = false) => return if not matTarget PhongExponent = @GrabData(prefix .. 'PhongExponent') PhongBoost = @GrabData(prefix .. 'PhongBoost') PhongTint = @GrabData(prefix .. 'PhongTint') PhongFront = @GrabData(prefix .. 'PhongFront') PhongMiddle = @GrabData(prefix .. 'PhongMiddle') Lightwarp = @GrabData(prefix .. 'Lightwarp') LightwarpURL = PPM2.IsValidURL(@GrabData(prefix .. 'LightwarpURL')) BumpmapURL = PPM2.IsValidURL(@GrabData(prefix .. 'BumpmapURL')) PhongSliding = @GrabData(prefix .. 'PhongSliding') {:r, :g, :b} = PhongTint r /= 255 g /= 255 b /= 255 PhongTint = Vector(r, g, b) PhongFresnel = Vector(PhongFront, PhongMiddle, PhongSliding) if not lightwarpsOnly with matTarget \SetFloat('$phongexponent', PhongExponent) \SetFloat('$phongboost', PhongBoost) \SetVector('$phongtint', PhongTint) \SetVector('$phongfresnelranges', PhongFresnel) if LightwarpURL ticket = @PutTicket(prefix .. '_phong') PPM2.GetURLMaterial(LightwarpURL, 256, 16)\Then (tex, mat) -> return if not @CheckTicket(prefix .. '_phong', ticket) matTarget\SetTexture('$lightwarptexture', tex) else myTex = PPM2.AvaliableLightwarpsPaths[Lightwarp] or PPM2.AvaliableLightwarpsPaths[1] matTarget\SetTexture('$lightwarptexture', myTex) if not noBump if BumpmapURL ticket = @PutTicket(prefix .. '_bump') PPM2.GetURLMaterial(BumpmapURL, matTarget\Width(), matTarget\Height())\Then (tex, mat) -> return if not @CheckTicket(prefix .. '_bump', ticket) matTarget\SetTexture('$bumpmap', tex) else matTarget\SetUndefined('$bumpmap') GetBodyPhongMaterials: (output = {}) => table.insert(output, {@BodyMaterial, false, false}) if @BodyMaterial table.insert(output, {@HornMaterial, false, true}) if @HornMaterial and not @GrabData('SeparateHornPhong') table.insert(output, {@HornMaterial1, false, true}) if @HornMaterial1 and not @GrabData('SeparateHornPhong') table.insert(output, {@HornMaterial2, false, true}) if @HornMaterial2 and not @GrabData('SeparateHornPhong') table.insert(output, {@WingsMaterial, false, false}) if @WingsMaterial and not @GrabData('SeparateWingsPhong') table.insert(output, {@Eyelashes, false, false}) if @Eyelashes and not @GrabData('SeparateEyelashesPhong') if not @GrabData('SeparateManePhong') table.insert(output, {@HairColor1Material, false, false}) if @HairColor1Material table.insert(output, {@HairColor2Material, false, false}) if @HairColor2Material if not @GrabData('SeparateTailPhong') table.insert(output, {@TailColor1Material, false, false}) if @TailColor1Material table.insert(output, {@TailColor2Material, false, false}) if @TailColor2Material UpdatePhongData: => proceed = {} @GetBodyPhongMaterials(proceed) for _, mat in ipairs proceed @ApplyPhongData(mat[1], 'Body', mat[2], mat[3], mat[4]) if @GrabData('SeparateHornPhong') @ApplyPhongData(@HornMaterial, 'Horn', false, true) if @HornMaterial @ApplyPhongData(@HornMaterial1, 'Horn', false, true) if @HornMaterial1 @ApplyPhongData(@HornMaterial2, 'Horn', false, true) if @HornMaterial2 if @GrabData('SeparateEyelashesPhong') and @Eyelashes @ApplyPhongData(@Eyelashes, 'Eyelashes', false, true) if @GrabData('SeparateWingsPhong') and @WingsMaterial @ApplyPhongData(@WingsMaterial, 'Wings') @ApplyPhongData(@SocksMaterial, 'Socks') if @SocksMaterial @ApplyPhongData(@NewSocksColor1, 'Socks') if @NewSocksColor1 @ApplyPhongData(@NewSocksColor2, 'Socks') if @NewSocksColor2 @ApplyPhongData(@NewSocksBase, 'Socks') if @NewSocksBase if @GrabData('SeparateManePhong') @ApplyPhongData(@HairColor1Material, 'Mane') @ApplyPhongData(@HairColor2Material, 'Mane') if @GrabData('SeparateTailPhong') @ApplyPhongData(@TailColor1Material, 'Tail') @ApplyPhongData(@TailColor2Material, 'Tail') if @GrabData('SeparateEyes') @ApplyPhongData(@EyeMaterialL, 'LEye', true) @ApplyPhongData(@EyeMaterialR, 'REye', true) else @ApplyPhongData(@EyeMaterialL, 'BEyes', true) @ApplyPhongData(@EyeMaterialR, 'BEyes', true) CompileBody: (isRenderTarget, lock, release) => return unless @isValid textureData = { 'name': "PPM2_#{@GetID()}_Body" 'shader': 'VertexLitGeneric' 'data': { '$basetexture': 'models/ppm2/base/body' '$lightwarptexture': 'models/ppm2/base/lightwrap' '$halflambert': '1' '$selfillum': '1' '$selfillummask': 'null' '$bumpmap': 'null-bumpmap' '$color': '{255 255 255}' '$color2': '{255 255 255}' '$model': '1' '$phong': '1' '$phongexponent': '3' '$phongboost': '0.15' '$phongtint': '[1 .95 .95]' '$phongfresnelranges': '[0.5 6 10]' '$rimlight': '1' '$rimlightexponent': '2' '$rimlightboost': '1' } } hash = { 'body' grind_down_color(@GrabData('BodyColor')) @GrabData('LipsColorInherit') @GrabData('LipsColorInherit') and grind_down_color(@GrabData('LipsColor')) @GrabData('NoseColorInherit') @GrabData('NoseColorInherit') and grind_down_color(@GrabData('NoseColor')) @GrabData('Socks') @GrabData('Bodysuit') @GrabData('EyebrowsColor') PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) } for i = 1, PPM2.MAX_BODY_DETAILS table.insert(hash, PPM2.IsValidURL(@GrabData("BodyDetailURL#{i}"))) table.insert(hash, @GrabData("BodyDetailFirst#{i}")) table.insert(hash, @GrabData("BodyDetail#{i}")) table.insert(hash, grind_down_color(@GrabData("BodyDetailColor#{i}"))) for i = 1, PPM2.MAX_TATTOOS table.insert(hash, @GrabData("TattooType#{i}")) table.insert(hash, @GrabData("TattooOverDetail#{i}")) table.insert(hash, @GrabData("TattooPosX#{i}")) table.insert(hash, @GrabData("TattooRotate#{i}")) table.insert(hash, @GrabData("TattooScaleX#{i}")) table.insert(hash, @GrabData("TattooScaleY#{i}")) table.insert(hash, grind_down_color(@GrabData("TattooColor#{i}"))) hash = PPM2.TextureTableHash(hash) texSize = (PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) + 1) * @@QUAD_SIZE_BODY @BodyMaterialName = "!#{textureData.name\lower()}" @BodyMaterial = CreateMaterial(textureData.name, textureData.shader, textureData.data) if getcache = @@GetCacheH(hash) @BodyMaterial\SetTexture('$basetexture', getcache) @BodyMaterial\GetTexture('$basetexture')\Download() if developer\GetBool() else urlTextures = {} for i = 1, PPM2.MAX_BODY_DETAILS if geturl = PPM2.IsValidURL(@GrabData("BodyDetailURL#{i}")) urlTextures[i] = select(2, PPM2.GetURLMaterial(geturl, texSize, texSize)\Await()) return unless @isValid @UpdatePhongData() {:r, :g, :b} = @GrabData('BodyColor') lock(@, 'body', texSize, texSize, r, g, b) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) for i = 1, PPM2.MAX_BODY_DETAILS if @GrabData('BodyDetailFirst' .. i) if mat = PPM2.MaterialsRegistry.BODY_DETAILS[@GrabData("BodyDetail#{i}")] surface.SetDrawColor(@GrabData("BodyDetailColor#{i}")) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) surface.SetDrawColor(255, 255, 255) for i, mat in pairs urlTextures if @GrabData('BodyDetailURLFirst' .. i) surface.SetDrawColor(@GrabData("BodyDetailURLColor#{i}")) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) surface.SetDrawColor(@GrabData('EyebrowsColor')) surface.SetMaterial(PPM2.MaterialsRegistry.EYEBROWS) surface.DrawTexturedRect(0, 0, texSize, texSize) if not @GrabData('LipsColorInherit') surface.SetDrawColor(@GrabData('LipsColor')) else {:r, :g, :b} = @GrabData('BodyColor') r, g, b = math.max(r - 30, 0), math.max(g - 30, 0), math.max(b - 30, 0) surface.SetDrawColor(r, g, b) surface.SetMaterial(PPM2.MaterialsRegistry.LIPS) surface.DrawTexturedRect(0, 0, texSize, texSize) if not @GrabData('NoseColorInherit') surface.SetDrawColor(@GrabData('NoseColor')) else {:r, :g, :b} = @GrabData('BodyColor') r, g, b = math.max(r - 30, 0), math.max(g - 30, 0), math.max(b - 30, 0) surface.SetDrawColor(r, g, b) surface.SetMaterial(PPM2.MaterialsRegistry.NOSE) surface.DrawTexturedRect(0, 0, texSize, texSize) @DrawTattoo(i) for i = 1, PPM2.MAX_TATTOOS when @GrabData("TattooOverDetail#{i}") for i = 1, PPM2.MAX_BODY_DETAILS if not @GrabData('BodyDetailFirst' .. i) if mat = PPM2.MaterialsRegistry.BODY_DETAILS[@GrabData("BodyDetail#{i}")] surface.SetDrawColor(@GrabData("BodyDetailColor#{i}")) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) surface.SetDrawColor(255, 255, 255) for i, mat in pairs urlTextures if not @GrabData('BodyDetailURLFirst' .. i) surface.SetDrawColor(@GrabData("BodyDetailURLColor#{i}")) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) @DrawTattoo(i) for i = 1, PPM2.MAX_TATTOOS when @GrabData("TattooOverDetail#{i}") if suit = PPM2.MaterialsRegistry.SUITS[@GrabData('Bodysuit')] surface.SetDrawColor(255, 255, 255) surface.SetMaterial(suit) surface.DrawTexturedRect(0, 0, texSize, texSize) if @GrabData('Socks') surface.SetDrawColor(255, 255, 255) surface.SetMaterial(@@PONY_SOCKS) surface.DrawTexturedRect(0, 0, texSize, texSize) render.PopFilterMag() render.PopFilterMin() if isRenderTarget @BodyMaterial\SetTexture('$basetexture', release(@, 'body', texSize, texSize)) else vtf = DLib.VTF.Create(2, texSize, texSize, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGB888 or IMAGE_FORMAT_DXT1, {fill: Color(), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'body', texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash, vtf\ToString()) @BodyMaterial\SetTexture('$basetexture', path) @BodyMaterial\GetTexture('$basetexture')\Download() texSize = texSize / 2 hash_bump = PPM2.TextureTableHash({ 'body bump' math.floor(@GrabData('BodyBumpStrength') * 255) PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) }) if getcache = @@GetCacheH(hash_bump) @BodyMaterial\SetTexture('$bumpmap', getcache) @BodyMaterial\GetTexture('$bumpmap')\Download() if developer\GetBool() else lock(@, 'body_bump', texSize, texSize, 127, 127, 255) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) surface.SetDrawColor(255, 255, 255, @GrabData('BodyBumpStrength') * 255) surface.SetMaterial(PPM2.MaterialsRegistry.BODY_BUMP) surface.DrawTexturedRect(0, 0, texSize, texSize) render.PopFilterMag() render.PopFilterMin() if isRenderTarget @BodyMaterial\SetTexture('$bumpmap', release(@, 'body_bump', texSize, texSize)) else vtf = DLib.VTF.Create(2, texSize, texSize, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGB888 or IMAGE_FORMAT_DXT1, {fill: Color(), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'body_bump', texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash_bump, vtf\ToString()) @BodyMaterial\SetTexture('$bumpmap', path) @BodyMaterial\GetTexture('$bumpmap')\Download() hash_glow = { 'body illum i8' @GrabData('GlowingEyebrows') math.floor(@GrabData('EyebrowsGlowStrength') * 255) PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) } for i = 1, PPM2.MAX_BODY_DETAILS table.insert(hash_glow, @GrabData("BodyDetail#{i}")) table.insert(hash_glow, math.floor(@GrabData("BodyDetailGlowStrength#{i}") * 255)) table.insert(hash_glow, @GrabData("BodyDetailGlow#{i}")) for i = 1, PPM2.MAX_TATTOOS table.insert(hash_glow, math.floor(@GrabData("TattooGlowStrength#{i}") * 255)) table.insert(hash_glow, @GrabData("TattooGlow#{i}")) table.insert(hash_glow, @GrabData("TattooType#{i}")) table.insert(hash_glow, @GrabData("TattooOverDetail#{i}")) table.insert(hash_glow, @GrabData("TattooPosX#{i}")) table.insert(hash_glow, @GrabData("TattooRotate#{i}")) table.insert(hash_glow, @GrabData("TattooScaleX#{i}")) table.insert(hash_glow, @GrabData("TattooScaleY#{i}")) hash_glow = PPM2.TextureTableHash(hash_glow) if getcache = @@GetCacheH(hash_glow) @BodyMaterial\SetTexture('$selfillummask', getcache) @BodyMaterial\GetTexture('$selfillummask')\Download() if developer\GetBool() else lock(@, 'body_illum', texSize, texSize) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) surface.SetDrawColor(255, 255, 255) if @GrabData('GlowingEyebrows') surface.SetDrawColor(255, 255, 255, 255 * @GrabData('EyebrowsGlowStrength')) surface.SetMaterial(PPM2.MaterialsRegistry.EYEBROWS) surface.DrawTexturedRect(0, 0, texSize, texSize) for i = 1, PPM2.MAX_TATTOOS if not @GrabData("TattooOverDetail#{i}") @DrawTattoo(i, true) for i = 1, PPM2.MAX_BODY_DETAILS if mat = PPM2.MaterialsRegistry.BODY_DETAILS[@GrabData("BodyDetail#{i}")] alpha = @GrabData("BodyDetailGlowStrength#{i}") if @GetData()["GetBodyDetailGlow#{i}"](@GetData()) surface.SetDrawColor(255, 255, 255, alpha * 255) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) else surface.SetDrawColor(0, 0, 0, alpha * 255) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) for i = 1, PPM2.MAX_TATTOOS if @GrabData("TattooOverDetail#{i}") @DrawTattoo(i, true) render.PopFilterMag() render.PopFilterMin() if isRenderTarget @BodyMaterial\SetTexture('$selfillummask', release(@, 'body_illum', texSize, texSize)) else vtf = DLib.VTF.Create(2, texSize, texSize, IMAGE_FORMAT_I8, {fill: Color(), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'body_illum', texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash_glow, vtf\ToString()) @BodyMaterial\SetTexture('$selfillummask', path) @BodyMaterial\GetTexture('$selfillummask')\Download() @BUMP_COLOR = Color(127, 127, 255) CompileHorn: (isRenderTarget, lock, release) => return unless @isValid textureData = { 'name': "PPM2_#{@GetID()}_Horn" 'shader': 'VertexLitGeneric' 'data': { '$basetexture': 'models/ppm2/base/horn' '$bumpmap': 'models/ppm2/base/horn_normal' '$selfillum': '1' '$selfillummask': 'null' '$rimlight': '1' '$rimlightexponent': '2' '$rimlightboost': '1' '$model': '1' '$phong': '1' '$phongexponent': '3' '$phongboost': '0.05' '$phongtint': '[1 .95 .95]' '$phongfresnelranges': '[0.5 6 10]' '$alpha': '1' '$color': '[1 1 1]' '$color2': '[1 1 1]' } } textureData_New1 = { 'name': "PPM2_#{@GetID()}_Horn1" 'shader': 'VertexLitGeneric' 'data': { '$basetexture': 'models/debug/debugwhite' '$selfillum': '0' '$rimlight': '1' '$rimlightexponent': '2' '$rimlightboost': '1' '$model': '1' '$phong': '1' '$phongexponent': '3' '$phongboost': '0.05' '$phongtint': '[1 .95 .95]' '$phongfresnelranges': '[0.5 6 10]' '$alpha': '1' '$color': '[1 1 1]' '$color2': '[1 1 1]' } } textureData_New2 = { 'name': "PPM2_#{@GetID()}_Horn2" 'shader': 'VertexLitGeneric' 'data': { '$basetexture': 'models/debug/debugwhite' '$selfillum': '1' '$selfillummask': 'null' '$rimlight': '1' '$rimlightexponent': '2' '$rimlightboost': '1' '$model': '1' '$phong': '1' '$phongexponent': '3' '$phongboost': '0.05' '$phongtint': '[1 .95 .95]' '$phongfresnelranges': '[0.5 6 10]' '$alpha': '1' '$color': '[1 1 1]' '$color2': '[1 1 1]' } } texSize = (PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) + 1) * @@QUAD_SIZE_HORN @HornMaterialName = "!#{textureData.name\lower()}" @HornMaterialName1 = "!#{textureData_New1.name\lower()}" @HornMaterialName2 = "!#{textureData_New2.name\lower()}" @HornMaterial = CreateMaterial(textureData.name, textureData.shader, textureData.data) @HornMaterial1 = CreateMaterial(textureData_New1.name, textureData_New1.shader, textureData_New1.data) @HornMaterial2 = CreateMaterial(textureData_New2.name, textureData_New2.shader, textureData_New2.data) @UpdatePhongData() {:r, :g, :b} = @GrabData('BodyColor') {:r, :g, :b} = @GrabData('HornColor') if @GrabData('SeparateHorn') hash = PPM2.TextureTableHash({ 'horn' grind_down_color(r, g, b) grind_down_color(@GrabData('HornDetailColor')) @GrabData('HornURLColor1') @GrabData('HornURLColor2') @GrabData('HornURLColor3') PPM2.IsValidURL(@GrabData('HornURL1')) PPM2.IsValidURL(@GrabData('HornURL2')) PPM2.IsValidURL(@GrabData('HornURL3')) PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) }) @HornMaterial1\SetVector('$color2', Vector(r / 255, g / 255, b / 255)) do local r, g, b {:r, :g, :b} = @GrabData('HornDetailColor') @HornMaterial2\SetVector('$color2', Vector(r / 255, g / 255, b / 255)) if getcache = @@GetCacheH(hash) @HornMaterial\SetTexture('$basetexture', getcache) @HornMaterial\GetTexture('$basetexture')\Download() if developer\GetBool() else urlTextures = {} for i = 1, 3 if geturl = PPM2.IsValidURL(@GrabData("HornURL#{i}")) urlTextures[i] = select(2, PPM2.GetURLMaterial(geturl, texSize, texSize)\Await()) return unless @isValid lock(@, 'horn', texSize, texSize, r, g, b) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) {:r, :g, :b} = @GrabData('HornDetailColor') surface.SetDrawColor(r, g, b) surface.SetMaterial(@@HORN_DETAIL_COLOR) surface.DrawTexturedRect(0, 0, texSize, texSize) for i, mat in pairs urlTextures {:r, :g, :b, :a} = @GrabData("HornURLColor#{i}") surface.SetDrawColor(r, g, b, a) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) render.PopFilterMag() render.PopFilterMin() if isRenderTarget @HornMaterial\SetTexture('$basetexture', release(@, 'horn', texSize, texSize)) else vtf = DLib.VTF.Create(2, texSize, texSize, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGB888 or IMAGE_FORMAT_DXT1, {fill: Color(), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'horn', texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash, vtf\ToString()) @HornMaterial\SetTexture('$basetexture', path) @HornMaterial\GetTexture('$basetexture')\Download() hash = PPM2.TextureTableHash({ 'horn illum i8' @GrabData('HornGlow') math.floor(@GrabData('HornGlowSrength') * 255) PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) }) if getcache = @@GetCacheH(hash) @HornMaterial\SetTexture('$selfillummask', getcache) @HornMaterial\GetTexture('$selfillummask')\Download() if developer\GetBool() else lock(@, 'horn_illum', texSize, texSize) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) if @GrabData('HornGlow') @HornMaterial2\SetTexture('$selfillummask', 'models/debug/debugwhite') surface.SetDrawColor(255, 255, 255, @GrabData('HornGlowSrength') * 255) surface.SetMaterial(@@HORN_DETAIL_COLOR) surface.DrawTexturedRect(0, 0, texSize, texSize) else @HornMaterial2\SetTexture('$selfillummask', null_texrure) render.PopFilterMag() render.PopFilterMin() if isRenderTarget @HornMaterial\SetTexture('$selfillummask', release(@, 'horn_illum', texSize, texSize)) else vtf = DLib.VTF.Create(2, texSize, texSize, IMAGE_FORMAT_I8, {fill: Color(0, 0, 0), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'horn_illum', texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash, vtf\ToString()) @HornMaterial\SetTexture('$selfillummask', path) @HornMaterial\GetTexture('$selfillummask')\Download() hash = PPM2.TextureTableHash({ 'horn bump' @GrabData('HornDetailColor').a PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) }) if getcache = @@GetCacheH(hash) @HornMaterial\SetTexture('$bumpmap', getcache) @HornMaterial\GetTexture('$bumpmap')\Download() if developer\GetBool() else lock(@, 'horn_bump', texSize, texSize, 127, 127, 255) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) surface.SetDrawColor(255, 255, 255, @GrabData('HornDetailColor').a) surface.SetMaterial(PPM2.MaterialsRegistry.HORN_DETAIL_BUMP) surface.DrawTexturedRect(0, 0, texSize, texSize) render.PopFilterMag() render.PopFilterMin() if isRenderTarget @HornMaterial\SetTexture('$bumpmap', release(@, 'horn_bump', texSize, texSize)) else vtf = DLib.VTF.Create(2, texSize, texSize, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGB888 or IMAGE_FORMAT_DXT1, {fill: Color(127, 127, 255), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'horn_bump', texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash, vtf\ToString()) @HornMaterial\SetTexture('$bumpmap', path) @HornMaterial\GetTexture('$bumpmap')\Download() CompileClothPart: (iName, matregistry, indexregistry, rtsize, opaque = true, isRenderTarget, lock, release) => return unless @isValid data = { '$basetexture': 'models/debug/debugwhite' '$phong': '1' '$phongexponent': '20' '$phongboost': '.1' '$phongfresnelranges': '[.3 1 8]' '$halflambert': '1' '$lightwarptexture': 'models/ppm/clothes/lightwarp' '$rimlight': '1' '$rimlightexponent': '2' '$rimlightboost': '1' '$color': '[1 1 1]' '$color2': '[1 1 1]' } if not opaque data['$alpha'] = '1' data['$translucent'] = '1' clothes = @GrabData(iName .. 'Clothes') return if not matregistry[clothes] or not indexregistry[clothes] @[iName .. 'Clothes_Index'] = indexregistry[clothes] urls = {} for i = 1, PPM2.MAX_CLOTHES_URLS if url = PPM2.IsValidURL(@GrabData(iName .. 'ClothesURL' .. i)) urls[i] = select(1, PPM2.GetURLMaterial(url)\Await()) return unless @isValid colored = @GrabData(iName .. 'ClothesUseColor') if not colored and table.Count(urls) == 0 @[iName .. 'Clothes_Mat'] = nil @[iName .. 'Clothes_MatName'] = nil @UpdateClothes(nil, @clothesModel) if IsValid(@clothesModel) return if matregistry[clothes].size == 0 name = "PPM2_#{@GetID()}_Clothes_#{iName}_1" mat = CreateMaterial(name, 'VertexLitGeneric', data) @[iName .. 'Clothes_Mat'] = {mat} @[iName .. 'Clothes_MatName'] = {"!#{name}"} if urls[1] mat\SetVector('$color2', Vector(1, 1, 1)) mat\SetTexture('$basetexture', urls[1]) @UpdateClothes(nil, @clothesModel) if IsValid(@clothesModel) elseif colored mat\SetTexture('$basetexture', 'models/debug/debugwhite') col = @GrabData("#{iName}ClothesColor1") mat\SetVector('$color2', col\ToVector()) if opaque mat\SetFloat('$alpha', 1) mat\SetInt('$translucent', 0) else mat\SetFloat('$alpha', col.a / 255) mat\SetInt('$translucent', 1) @UpdateClothes(nil, @clothesModel) if IsValid(@clothesModel) return @[iName .. 'Clothes_Mat'] = {} tab1 = @[iName .. 'Clothes_Mat'] @[iName .. 'Clothes_MatName'] = {} tab2 = @[iName .. 'Clothes_MatName'] nextindex = 1 for matIndex = 1, matregistry[clothes].size name = "PPM2_#{@GetID()}_Clothes_#{iName}_#{matIndex}" mat = CreateMaterial(name, 'VertexLitGeneric', data) tab1[matIndex] = mat tab2[matIndex] = "!#{name}" if urls[matIndex] mat\SetVector('$color2', Vector(1, 1, 1)) mat\SetTexture('$basetexture', urls[matIndex]) @UpdateClothes(nil, @clothesModel) if IsValid(@clothesModel) elseif colored and matregistry[clothes][matIndex].size == 0 mat\SetTexture('$basetexture', 'models/debug/debugwhite') col = @GrabData("#{iName}ClothesColor#{nextindex}") nextindex += 1 mat\SetVector('$color2', col\ToVector()) if opaque mat\SetFloat('$alpha', 1) mat\SetInt('$translucent', 0) else mat\SetFloat('$alpha', col.a / 255) mat\SetInt('$translucent', 1) elseif colored rtsize = rtsize mat\SetVector('$color2', Vector(1, 1, 1)) {:r, :g, :b, :a} = @GrabData("#{iName}ClothesColor#{nextindex}") if opaque mat\SetFloat('$alpha', 1) mat\SetInt('$translucent', 0) else mat\SetFloat('$alpha', a / 255) mat\SetInt('$translucent', 1) hash = { 'cloth part' opaque iName clothes PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) } for i = 1, PPM2.MAX_CLOTHES_COLORS table.insert(hash, grind_down_color(@GrabData(iName .. 'ClothesColor' .. i))) hash = PPM2.TextureTableHash(hash) if getcache = @@GetCacheH(hash) mat\SetTexture('$basetexture', getcache) mat\GetTexture('$basetexture')\Download() if developer\GetBool() else lock(@, 'cloth_' .. iName, rtsize, rtsize, r, g, b) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) for i2 = 1, matregistry[clothes][matIndex].size texture = matregistry[clothes][matIndex][i2] if not isnumber(texture) surface.SetMaterial(texture) surface.SetDrawColor(@GrabData("#{iName}ClothesColor#{nextindex}")) nextindex += 1 surface.DrawTexturedRect(0, 0, rtsize, rtsize) render.PopFilterMag() render.PopFilterMin() if isRenderTarget mat\SetTexture('$basetexture', release(@, 'cloth_' .. iName, rtsize, rtsize)) else vtf = DLib.VTF.Create(2, rtsize, rtsize, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGB888 or IMAGE_FORMAT_DXT1, {fill: Color(r, g, b), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'cloth_' .. iName, rtsize, rtsize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash, vtf\ToString()) mat\SetTexture('$basetexture', path) mat\GetTexture('$basetexture')\Download() else tab1[matIndex] = nil tab2[matIndex] = nil @UpdateClothes(nil, @clothesModel) if IsValid(@clothesModel) CompileHeadClothes: (isRenderTarget, lock, release) => @CompileClothPart('Head', PPM2.MaterialsRegistry.HEAD_CLOTHES, PPM2.MaterialsRegistry.HEAD_CLOTHES_INDEX, @@QUAD_SIZE_CLOTHES_HEAD, true, isRenderTarget, lock, release) CompileBodyClothes: (isRenderTarget, lock, release) => @CompileClothPart('Body', PPM2.MaterialsRegistry.BODY_CLOTHES, PPM2.MaterialsRegistry.BODY_CLOTHES_INDEX, @@QUAD_SIZE_CLOTHES_BODY, true, isRenderTarget, lock, release) CompileNeckClothes: (isRenderTarget, lock, release) => @CompileClothPart('Neck', PPM2.MaterialsRegistry.NECK_CLOTHES, PPM2.MaterialsRegistry.NECK_CLOTHES_INDEX, @@QUAD_SIZE_CLOTHES_NECK, true, isRenderTarget, lock, release) CompileEyeClothes: (isRenderTarget, lock, release) => @CompileClothPart('Eye', PPM2.MaterialsRegistry.EYE_CLOTHES, PPM2.MaterialsRegistry.EYE_CLOTHES_INDEX, @@QUAD_SIZE_CLOTHES_EYES, false, isRenderTarget, lock, release) CompileNewSocks: (isRenderTarget, lock, release) => return unless @isValid data = { '$basetexture': 'models/debug/debugwhite' '$model': '1' '$ambientocclusion': '1' '$lightwarptexture': 'models/ppm2/base/lightwrap' '$phong': '1' '$phongexponent': '6' '$phongboost': '0.1' '$phongtint': '[1 .95 .95]' '$phongfresnelranges': '[1 5 10]' '$rimlight': '1' '$rimlightexponent': '2' '$rimlightboost': '1' '$color': '[1 1 1]' '$color2': '[1 1 1]' '$cloakPassEnabled': '1' } textureColor1 = { 'name': "PPM2_#{@GetID()}_NewSocks_Color1" 'shader': 'VertexLitGeneric' 'data': data } textureColor2 = { 'name': "PPM2_#{@GetID()}_NewSocks_Color2" 'shader': 'VertexLitGeneric' 'data': data } textureBase = { 'name': "PPM2_#{@GetID()}_NewSocks_Base" 'shader': 'VertexLitGeneric' 'data': data } @NewSocksColor1Name = '!' .. textureColor1.name\lower() @NewSocksColor2Name = '!' .. textureColor2.name\lower() @NewSocksBaseName = '!' .. textureBase.name\lower() @NewSocksColor1 = CreateMaterial(textureColor1.name, textureColor1.shader, textureColor1.data) @NewSocksColor2 = CreateMaterial(textureColor2.name, textureColor2.shader, textureColor2.data) @NewSocksBase = CreateMaterial(textureBase.name, textureBase.shader, textureBase.data) texSize = (PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) + 1) * @@QUAD_SIZE_SOCKS @UpdatePhongData() if url = PPM2.IsValidURL(@GrabData('NewSocksTextureURL')) texture = PPM2.GetURLMaterial(url, texSize, texSize)\Await() return unless @isValid for _, tex in ipairs {@NewSocksColor1, @NewSocksColor2, @NewSocksBase} tex\SetVector('$color2', Vector(1, 1, 1)) tex\SetTexture('$basetexture', texture) return {:r, :g, :b} = @GrabData('NewSocksColor1') @NewSocksColor1\SetVector('$color2', Vector(r / 255, g / 255, b / 255)) @NewSocksColor1\SetTexture('$basetexture', 'models/debug/debugwhite') {:r, :g, :b} = @GrabData('NewSocksColor2') @NewSocksColor2\SetVector('$color2', Vector(r / 255, g / 255, b / 255)) @NewSocksColor2\SetTexture('$basetexture', 'models/debug/debugwhite') {:r, :g, :b} = @GrabData('NewSocksColor3') @NewSocksBase\SetVector('$color2', Vector(r / 255, g / 255, b / 255)) @NewSocksBase\SetTexture('$basetexture', 'models/debug/debugwhite') CompileEyelashes: (isRenderTarget, lock, release) => return unless @isValid textureData = { 'name': "PPM2_#{@GetID()}_Eyelashes" 'shader': 'VertexLitGeneric' 'data': { '$basetexture': 'models/debug/debugwhite' '$model': '1' '$ambientocclusion': '1' '$lightwarptexture': 'models/ppm2/base/lightwrap' '$phong': '1' '$phongexponent': '6' '$phongboost': '0.1' '$phongtint': '[1 .95 .95]' '$phongfresnelranges': '[1 5 10]' '$rimlight': '1' '$rimlightexponent': '1' '$rimlightboost': '0.5' '$color': '[1 1 1]' '$color2': '[1 1 1]' '$cloakPassEnabled': '1' } } @EyelashesName = '!' .. textureData.name\lower() @Eyelashes = CreateMaterial(textureData.name, textureData.shader, textureData.data) @UpdatePhongData() {:r, :g, :b} = @GrabData('EyelashesColor') @Eyelashes\SetVector('$color', Vector(r / 255, g / 255, b / 255)) @Eyelashes\SetVector('$color2', Vector(r / 255, g / 255, b / 255)) CompileSocks: (isRenderTarget, lock, release) => return unless @isValid textureData = { 'name': "PPM2_#{@GetID()}_Socks" 'shader': 'VertexLitGeneric' 'data': { '$basetexture': 'models/props_pony/ppm/ppm_socks/socks_striped' '$model': '1' '$ambientocclusion': '1' '$lightwarptexture': 'models/ppm2/base/lightwrap' '$phong': '1' '$phongexponent': '6' '$phongboost': '0.1' '$phongtint': '[1 .95 .95]' '$phongfresnelranges': '[1 5 10]' '$rimlight': '1' '$rimlightexponent': '2' '$rimlightboost': '1' '$color': '[1 1 1]' '$color2': '[1 1 1]' '$cloakPassEnabled': '1' } } @SocksMaterialName = "!#{textureData.name\lower()}" @SocksMaterial = CreateMaterial(textureData.name, textureData.shader, textureData.data) @UpdatePhongData() texSize = (PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) + 1) * @@QUAD_SIZE_SOCKS {:r, :g, :b} = @GrabData('SocksColor') @SocksMaterial\SetFloat('$alpha', 1) if url = PPM2.IsValidURL(@GrabData('SocksTextureURL')) texture = PPM2.GetURLMaterial(url, texSize, texSize)\Await() return unless @isValid @SocksMaterial\SetVector('$color', Vector(r / 255, g / 255, b / 255)) @SocksMaterial\SetVector('$color2', Vector(r / 255, g / 255, b / 255)) @SocksMaterial\SetTexture('$basetexture', texture) else @SocksMaterial\SetVector('$color', Vector(1, 1, 1)) @SocksMaterial\SetVector('$color2', Vector(1, 1, 1)) hash = { 'socks' @GrabData('SocksTexture') grind_down_color(@GrabData('SocksDetailColor1')) grind_down_color(@GrabData('SocksDetailColor2')) grind_down_color(@GrabData('SocksDetailColor3')) grind_down_color(@GrabData('SocksDetailColor4')) grind_down_color(@GrabData('SocksDetailColor5')) grind_down_color(@GrabData('SocksDetailColor6')) PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) } hash = PPM2.TextureTableHash(hash) if getcache = @@GetCacheH(hash) @SocksMaterial\SetTexture('$basetexture', getcache) @SocksMaterial\GetTexture('$basetexture')\Download() if developer\GetBool() else lock(@, 'sock', texSize, texSize, r, g, b) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) socksType = @GrabData('SocksTexture') surface.SetMaterial(PPM2.MaterialsRegistry.SOCKS_MATERIALS[socksType] or PPM2.MaterialsRegistry.SOCKS_MATERIALS[1]) surface.DrawTexturedRect(0, 0, texSize, texSize) if details = PPM2.MaterialsRegistry.SOCKS_DETAILS[socksType] for i = 1, details.size {:r, :g, :b} = @GrabData('SocksDetailColor' .. i) surface.SetDrawColor(r, g, b) surface.SetMaterial(details[i]) surface.DrawTexturedRect(0, 0, texSize, texSize) render.PopFilterMag() render.PopFilterMin() if isRenderTarget @SocksMaterial\SetTexture('$basetexture', release(@, 'sock', texSize, texSize)) else vtf = DLib.VTF.Create(2, texSize, texSize, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGB888 or IMAGE_FORMAT_DXT1, {fill: Color(r, g, b), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'sock', texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash, vtf\ToString()) @SocksMaterial\SetTexture('$basetexture', path) @SocksMaterial\GetTexture('$basetexture')\Download() CompileWings: (isRenderTarget, lock, release) => return unless @isValid textureData = { 'name': "PPM2_#{@GetID()}_Wings" 'shader': 'VertexLitGeneric' 'data': { '$basetexture': 'models/debug/debugwhite' '$model': '1' '$phong': '1' '$phongexponent': '3' '$phongboost': '0.05' '$phongtint': '[1 .95 .95]' '$phongfresnelranges': '[0.5 6 10]' '$alpha': '1' '$color': '[1 1 1]' '$color2': '[1 1 1]' '$rimlight': '1' '$rimlightexponent': '2' '$rimlightboost': '1' } } texSize = (PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) + 1) * @@QUAD_SIZE_WING @WingsMaterialName = "!#{textureData.name\lower()}" @WingsMaterial = CreateMaterial(textureData.name, textureData.shader, textureData.data) @UpdatePhongData() {:r, :g, :b} = @GrabData('BodyColor') {:r, :g, :b} = @GrabData('WingsColor') if @GrabData('SeparateWings') hash = { 'wings', grind_down_color(r, g, b) PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) } for i = 1, 3 table.insert(hash, PPM2.IsValidURL(@GrabData("WingsURL#{i}"))) table.insert(hash, @GrabData("WingsURLColor#{i}")) hash = PPM2.TextureTableHash(hash) if getcache = @@GetCacheH(hash) @WingsMaterial\SetTexture('$basetexture', getcache) @WingsMaterial\GetTexture('$basetexture')\Download() if developer\GetBool() else urlTextures = {} for i = 1, 3 if url = PPM2.IsValidURL(@GrabData("WingsURL#{i}")) urlTextures[i] = select(2, PPM2.GetURLMaterial(url, texSize, texSize)\Await()) return unless @isValid lock(@, 'wings', texSize, texSize, r, g, b) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) surface.SetMaterial(@@WINGS_MATERIAL_COLOR) surface.DrawTexturedRect(0, 0, texSize, texSize) for i, mat in pairs urlTextures {:r, :g, :b, :a} = @GrabData("WingsURLColor#{i}") surface.SetDrawColor(r, g, b, a) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) render.PopFilterMag() render.PopFilterMin() if isRenderTarget @WingsMaterial\SetTexture('$basetexture', release(@, 'wings', texSize, texSize)) else vtf = DLib.VTF.Create(2, texSize, texSize, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGB888 or IMAGE_FORMAT_DXT1, {fill: Color(r, g, b), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'wings', texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash, vtf\ToString()) @WingsMaterial\SetTexture('$basetexture', path) @WingsMaterial\GetTexture('$basetexture')\Download() GetManeType: => @GrabData('ManeType') GetManeTypeLower: => @GrabData('ManeTypeLower') GetTailType: => @GrabData('TailType') CompileHair: (isRenderTarget, lock, release) => return unless @isValid textureFirst = { 'name': "PPM2_#{@GetID()}_Mane_1" 'shader': 'VertexLitGeneric' 'data': { '$basetexture': 'models/debug/debugwhite' '$lightwarptexture': 'models/ppm2/base/lightwrap' '$halflambert': '1' '$model': '1' '$phong': '1' '$phongexponent': '6' '$phongboost': '0.05' '$phongtint': '[1 .95 .95]' '$phongfresnelranges': '[0.5 6 10]' '$rimlight': '1' '$rimlightexponent': '2' '$rimlightboost': '1' '$color': '[1 1 1]' '$color2': '[1 1 1]' } } textureSecond = { 'name': "PPM2_#{@GetID()}_Mane_2" 'shader': 'VertexLitGeneric' 'data': {k, v for k, v in pairs textureFirst.data} } @HairColor1MaterialName = "!#{textureFirst.name\lower()}" @HairColor2MaterialName = "!#{textureSecond.name\lower()}" @HairColor1Material = CreateMaterial(textureFirst.name, textureFirst.shader, textureFirst.data) @HairColor2Material = CreateMaterial(textureSecond.name, textureSecond.shader, textureSecond.data) texSize = (PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) + 1) * @@QUAD_SIZE_HAIR hash = { 'mane 1', @GetManeType() grind_down_color(@GrabData('ManeColor1')) PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) } for i = 1, 6 table.insert(hash, PPM2.IsValidURL(@GrabData("ManeURL#{i}"))) table.insert(hash, grind_down_color(@GrabData("ManeURLColor#{i}"))) table.insert(hash, grind_down_color(@GrabData("ManeDetailColor#{i}"))) hash = PPM2.TextureTableHash(hash) if getcache = @@GetCacheH(hash) @HairColor1Material\SetTexture('$basetexture', getcache) @HairColor1Material\GetTexture('$basetexture')\Download() if developer\GetBool() else urlTextures = {} for i = 1, 6 if url = PPM2.IsValidURL(@GrabData("ManeURL#{i}")) urlTextures[i] = select(2, PPM2.GetURLMaterial(url, texSize, texSize)\Await()) return unless @isValid {:r, :g, :b} = @GrabData('ManeColor1') lock(@, 'hair_1_color', texSize, texSize, r, g, b) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) if registry = PPM2.MaterialsRegistry.UPPER_MANE_DETAILS[@GetManeType()] -- using moonscripts iterator will call index metamethods while iterating for i2 = 1, registry.size mat = registry[i2] {:r, :g, :b, :a} = @GrabData("ManeDetailColor#{i2}") surface.SetDrawColor(r, g, b, a) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) for i, mat in pairs urlTextures surface.SetDrawColor(@GrabData("ManeURLColor#{i}")) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) render.PopFilterMag() render.PopFilterMin() if isRenderTarget @HairColor1Material\SetTexture('$basetexture', release(@, 'hair_1_color', texSize, texSize)) else vtf = DLib.VTF.Create(2, texSize, texSize, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGB888 or IMAGE_FORMAT_DXT1, {fill: Color(r, g, b), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'hair_1_color', texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash, vtf\ToString()) @HairColor1Material\SetTexture('$basetexture', path) @HairColor1Material\GetTexture('$basetexture')\Download() hash = { 'mane 2', @GetManeTypeLower() grind_down_color(@GrabData('ManeColor2')) PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) } for i = 1, 6 table.insert(hash, @GrabData("ManeURL#{i}")) table.insert(hash, grind_down_color(@GrabData("ManeURLColor#{i}"))) table.insert(hash, grind_down_color(@GrabData("ManeDetailColor#{i}"))) hash = PPM2.TextureTableHash(hash) if getcache = @@GetCacheH(hash) @HairColor2Material\SetTexture('$basetexture', getcache) @HairColor2Material\GetTexture('$basetexture')\Download() if developer\GetBool() else urlTextures = {} for i = 1, 6 if url = PPM2.IsValidURL(@GrabData("ManeURL#{i}")) urlTextures[i] = select(2, PPM2.GetURLMaterial(url, texSize, texSize)\Await()) return unless @isValid {:r, :g, :b} = @GrabData('ManeColor2') lock(@, 'hair_2_color', texSize, texSize, r, g, b) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) if registry = PPM2.MaterialsRegistry.LOWER_MANE_DETAILS[@GetManeTypeLower()] i = 1 for i2 = 1, registry.size mat = registry[i2] surface.SetDrawColor(@GrabData("ManeDetailColor#{i}")) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) i += 1 for i, mat in pairs urlTextures surface.SetDrawColor(@GrabData("ManeURLColor#{i}")) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) render.PopFilterMag() render.PopFilterMin() if isRenderTarget @HairColor2Material\SetTexture('$basetexture', release(@, 'hair_2_color', texSize, texSize)) else vtf = DLib.VTF.Create(2, texSize, texSize, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGB888 or IMAGE_FORMAT_DXT1, {fill: Color(r, g, b), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'hair_2_color', texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash, vtf\ToString()) @HairColor2Material\SetTexture('$basetexture', path) @HairColor2Material\GetTexture('$basetexture')\Download() CompileTail: (isRenderTarget, lock, release) => return unless @isValid textureFirst = { 'name': "PPM2_#{@GetID()}_Tail_1" 'shader': 'VertexLitGeneric' 'data': { '$basetexture': 'models/debug/debugwhite' '$lightwarptexture': 'models/ppm2/base/lightwrap' '$halflambert': '1' '$model': '1' '$phong': '1' '$phongexponent': '6' '$phongboost': '0.05' '$phongtint': '[1 .95 .95]' '$phongfresnelranges': '[0.5 6 10]' '$rimlight': '1' '$rimlightexponent': '2' '$rimlightboost': '1' '$color': '[1 1 1]' '$color2': '[1 1 1]' } } textureSecond = { 'name': "PPM2_#{@GetID()}_Tail_2" 'shader': 'VertexLitGeneric' 'data': {k, v for k, v in pairs textureFirst.data} } @TailColor1MaterialName = "!#{textureFirst.name\lower()}" @TailColor2MaterialName = "!#{textureSecond.name\lower()}" @TailColor1Material = CreateMaterial(textureFirst.name, textureFirst.shader, textureFirst.data) @TailColor2Material = CreateMaterial(textureSecond.name, textureSecond.shader, textureSecond.data) texSize = (PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) + 1) * @@QUAD_SIZE_TAIL hash = { 'tail 1', @GetTailType() grind_down_color(@GrabData('TailColor1')) PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) } for i = 1, 6 table.insert(hash, PPM2.IsValidURL(@GrabData("TailURL#{i}"))) table.insert(hash, grind_down_color(@GrabData("TailDetailColor#{i}"))) table.insert(hash, grind_down_color(@GrabData("TailURLColor#{i}"))) hash = PPM2.TextureTableHash(hash) if getcache = @@GetCacheH(hash) @TailColor1Material\SetTexture('$basetexture', getcache) @TailColor1Material\GetTexture('$basetexture')\Download() if developer\GetBool() else urlTextures = {} for i = 1, 6 if url = PPM2.IsValidURL(@GrabData("TailURL#{i}")) urlTextures[i] = select(2, PPM2.GetURLMaterial(url, texSize, texSize)\Await()) return unless @isValid {:r, :g, :b} = @GrabData('TailColor1') lock(@, 'tail_1_color', texSize, texSize, r, g, b) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) if registry = PPM2.MaterialsRegistry.TAIL_DETAILS[@GetTailType()] i = 1 for i2 = 1, registry.size mat = registry[i2] surface.SetMaterial(mat) surface.SetDrawColor(@GrabData("TailDetailColor#{i}")) surface.DrawTexturedRect(0, 0, texSize, texSize) i += 1 for i, mat in pairs urlTextures surface.SetDrawColor(@GrabData("TailURLColor#{i}")) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) render.PopFilterMag() render.PopFilterMin() if isRenderTarget @TailColor1Material\SetTexture('$basetexture', release(@, 'tail_1_color', texSize, texSize)) else vtf = DLib.VTF.Create(2, texSize, texSize, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGB888 or IMAGE_FORMAT_DXT1, {fill: Color(r, g, b), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'tail_1_color', texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash, vtf\ToString()) @TailColor1Material\SetTexture('$basetexture', path) @TailColor1Material\GetTexture('$basetexture')\Download() hash = { 'tail 2', @GetTailType() grind_down_color(@GrabData('TailColor2')) PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) } for i = 1, 6 table.insert(hash, PPM2.IsValidURL(@GrabData("TailURL#{i}"))) table.insert(hash, grind_down_color(@GrabData("TailDetailColor#{i}"))) table.insert(hash, grind_down_color(@GrabData("TailURLColor#{i}"))) hash = PPM2.TextureTableHash(hash) if getcache = @@GetCacheH(hash) @TailColor2Material\SetTexture('$basetexture', getcache) @TailColor2Material\GetTexture('$basetexture')\Download() else urlTextures = {} for i = 1, 6 if url = PPM2.IsValidURL(@GrabData("TailURL#{i}")) urlTextures[i] = select(2, PPM2.GetURLMaterial(url, texSize, texSize)\Await()) return unless @isValid {:r, :g, :b} = @GrabData('TailColor2') lock(@, 'tail_2_color', texSize, texSize, r, g, b) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) if registry = PPM2.MaterialsRegistry.TAIL_DETAILS[@GetTailType()] i = 1 for i2 = 1, registry.size mat = registry[i2] surface.SetMaterial(mat) surface.SetDrawColor(@GrabData("TailDetailColor#{i}")) surface.DrawTexturedRect(0, 0, texSize, texSize) i += 1 for i, mat in pairs urlTextures surface.SetDrawColor(@GrabData("TailURLColor#{i}")) surface.SetMaterial(mat) surface.DrawTexturedRect(0, 0, texSize, texSize) render.PopFilterMag() render.PopFilterMin() if isRenderTarget @TailColor2Material\SetTexture('$basetexture', release(@, 'tail_2_color', texSize, texSize)) else vtf = DLib.VTF.Create(2, texSize, texSize, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGB888 or IMAGE_FORMAT_DXT1, {fill: Color(r, g, b), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'tail_2_color', texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash, vtf\ToString()) @TailColor2Material\SetTexture('$basetexture', path) @TailColor2Material\GetTexture('$basetexture')\Download() @REFLECT_RENDER_SIZE = 64 @GetReflectionsScale: => val = REAL_TIME_EYE_REFLECTIONS_SIZE\GetInt() return @REFLECT_RENDER_SIZE if val % 2 ~= 0 return val CompileLeftEye: (isRenderTarget, lock, release) => @CompileEye(true, isRenderTarget, lock, release) CompileRightEye: (isRenderTarget, lock, release) => @CompileEye(false, isRenderTarget, lock, release) CompileEye: (left = false, isRenderTarget, lock, release) => return unless @isValid prefix = left and 'l' or 'r' prefixUpper = left and 'L' or 'R' prefixUpperR = left and 'R' or 'L' separated = @GrabData('SeparateEyes') prefixData = '' prefixData = left and 'Left' or 'Right' if separated EyeRefract = @GrabData("EyeRefract#{prefixData}") EyeCornerA = @GrabData("EyeCornerA#{prefixData}") EyeType = @GrabData("EyeType#{prefixData}") EyeBackground = @GrabData("EyeBackground#{prefixData}") EyeHole = @GrabData("EyeHole#{prefixData}") HoleWidth = @GrabData("HoleWidth#{prefixData}") IrisSize = @GrabData("IrisSize#{prefixData}") * (EyeRefract and .38 or .75) EyeIris1 = @GrabData("EyeIrisTop#{prefixData}") EyeIris2 = @GrabData("EyeIrisBottom#{prefixData}") EyeIrisLine1 = @GrabData("EyeIrisLine1#{prefixData}") EyeIrisLine2 = @GrabData("EyeIrisLine2#{prefixData}") EyeLines = @GrabData("EyeLines#{prefixData}") HoleSize = @GrabData("HoleSize#{prefixData}") EyeReflection = @GrabData("EyeReflection#{prefixData}") EyeReflectionType = @GrabData("EyeReflectionType#{prefixData}") EyeEffect = @GrabData("EyeEffect#{prefixData}") DerpEyes = @GrabData("DerpEyes#{prefixData}") DerpEyesStrength = @GrabData("DerpEyesStrength#{prefixData}") EyeURL = @GrabData("EyeURL#{prefixData}") IrisWidth = @GrabData("IrisWidth#{prefixData}") IrisHeight = @GrabData("IrisHeight#{prefixData}") HoleHeight = @GrabData("HoleHeight#{prefixData}") HoleShiftX = @GrabData("HoleShiftX#{prefixData}") HoleShiftY = @GrabData("HoleShiftY#{prefixData}") EyeRotation = @GrabData("EyeRotation#{prefixData}") EyeLineDirection = @GrabData("EyeLineDirection#{prefixData}") EyeGlossyStrength = @GrabData("EyeGlossyStrength#{prefixData}") PonySize = @GrabData('PonySize') IrisSizeInternal = @GrabData('IrisSizeInternal') PonySize = 1 if IsValid(@GetEntity()) and @GetEntity()\IsRagdoll() texSize = (PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) + 1) * @@QUAD_SIZE_EYES shiftX, shiftY = (1 - IrisWidth) * texSize / 2, (1 - IrisHeight) * texSize / 2 shiftY += DerpEyesStrength * .15 * texSize if DerpEyes and left shiftY -= DerpEyesStrength * .15 * texSize if DerpEyes and not left textureData = { 'name': "PPM2_#{@GetID()}_#{EyeRefract and 'EyeRefract' or 'Eyes'}_#{prefix}3" 'shader': EyeRefract and 'EyeRefract' or 'Eyes' 'data': { '$iris': 'models/ppm2/base/face/p_base' '$irisframe': '0' '$ambientoccltexture': 'models/ppm2/eyes/eye_extra' '$envmap': 'models/ppm2/eyes/eye_reflection' '$corneatexture': 'models/ppm2/eyes/eye_cornea_oval' '$lightwarptexture': 'models/ppm2/clothes/lightwarp' '$ambientocclcolor': '[0.3 0.3 0.3]' '$dilation': '0.5' '$glossiness': tostring(EyeGlossyStrength) '$parallaxstrength': '0.5' '$corneabumpstrength': '0.02' '$halflambert': '1' '$nodecal': '1' '$eyeorigin': '[0 0 0]' '$irisu': '[0 1 0 0]' '$irisv': '[0 0 1 0]' '$entityorigin': '1.0' } } @["EyeMaterial#{prefixUpper}Name"] = "!#{textureData.name\lower()}" createdMaterial = CreateMaterial(textureData.name, textureData.shader, textureData.data) @["EyeMaterial#{prefixUpper}"] = createdMaterial @UpdatePhongData() if IrisSizeInternal\abs() <= 0.02 createdMaterial\SetInt('$irisframe', 0) elseif IrisSizeInternal > 0 createdMaterial\SetInt('$irisframe', math.clamp(IrisSizeInternal\progression(0, 0.2) * 4 + 2, 2, 6)\round() - 1) else createdMaterial\SetInt('$irisframe', math.clamp((1 - IrisSizeInternal\progression(-0.5, 0)) * 13 + 7, 7, 20)\round() - 1) createdMaterial\SetFloat('$glossiness', EyeGlossyStrength) IrisPos = texSize / 2 - texSize * IrisSize * PonySize / 2 IrisQuadSize = texSize * IrisSize * PonySize HoleQuadSize = texSize * IrisSize * HoleSize * PonySize HolePos = texSize / 2 holeX = HoleQuadSize * HoleWidth / 2 holeY = texSize * (IrisSize * HoleSize * HoleHeight * PonySize) / 2 calcHoleX = HolePos - holeX + holeX * HoleShiftX + shiftX calcHoleY = HolePos - holeY + holeY * HoleShiftY + shiftY {:r, :g, :b} = EyeBackground if EyeRefract if EyeCornerA hash = PPM2.TextureTableHash({ 'eye cornera', PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) IrisPos + shiftX - texSize / 16, IrisPos + shiftY - texSize / 16, IrisQuadSize * IrisWidth * 1.5, IrisQuadSize * IrisHeight * 1.5, EyeRotation }) if getcache = @@GetCacheH(hash) createdMaterial\SetTexture('$corneatexture', getcache) createdMaterial\GetTexture('$corneatexture')\Download() if developer\GetBool() else lock(@, 'eye_cornera', texSize, texSize) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) surface.SetMaterial(PPM2.MaterialsRegistry.EYE_CORNERA_OVAL) surface.SetDrawColor(255, 255, 255) DrawTexturedRectRotated(IrisPos + shiftX - texSize / 16, IrisPos + shiftY - texSize / 16, IrisQuadSize * IrisWidth * 1.5, IrisQuadSize * IrisHeight * 1.5, EyeRotation) if isRenderTarget createdMaterial\SetTexture('$corneatexture', release(@, 'eye_cornera', texSize, texSize)) else vtf = DLib.VTF.Create(2, texSize, texSize, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGB888 or IMAGE_FORMAT_DXT1, {fill: Color(r, g, b), mipmap_count: -2}) vtf\CaptureRenderTargetCoroutine() release(@, 'eye_cornera', texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash, vtf\ToString()) createdMaterial\SetTexture('$corneatexture', path) createdMaterial\SetTexture('$corneatexture')\Download() else createdMaterial\SetTexture('$corneatexture', null_texrure) if url = PPM2.IsValidURL(EyeURL) texture = PPM2.GetURLMaterial(url, texSize, texSize)\Await() return unless @isValid createdMaterial\SetTexture('$iris', texture) return hash = PPM2.TextureTableHash({ 'eye frames' prefixUpper EyeType grind_down_color(EyeBackground) grind_down_color(EyeHole) HoleWidth * 100 math.round(IrisSize * 100) grind_down_color(EyeIris1) grind_down_color(EyeIris2) EyeLines and grind_down_color(EyeIrisLine1) or '-' EyeLines and grind_down_color(EyeIrisLine2) or '-' math.round(HoleSize * 100) math.round(EyeGlossyStrength * 100) grind_down_color(EyeReflection) EyeReflectionType EyeEffect DerpEyes math.round(DerpEyesStrength * 100) EyeURL math.round(IrisWidth * 100) math.round(IrisHeight * 100) math.round(HoleHeight * 100) math.round(HoleShiftX) math.round(HoleShiftY) math.round(EyeRotation) EyeLineDirection math.round(PonySize * 100) PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) }) if getcache = @@GetCacheH(hash) createdMaterial\SetTexture('$iris', getcache) createdMaterial\GetTexture('$iris')\Download() if developer\GetBool() else {:r, :g, :b, :a} = EyeBackground lock(@, 'eye_' .. prefixUpper, texSize, texSize, r, g, b) _IrisSize = IrisSize render_frame = (mult = 1) -> IrisSize = _IrisSize * mult IrisPos = texSize / 2 - texSize * IrisSize * PonySize / 2 IrisQuadSize = texSize * IrisSize * PonySize HoleQuadSize = texSize * IrisSize * HoleSize * PonySize HolePos = texSize / 2 holeX = HoleQuadSize * HoleWidth / 2 holeY = texSize * (IrisSize * HoleSize * HoleHeight * PonySize) / 2 calcHoleX = HolePos - holeX + holeX * HoleShiftX + shiftX calcHoleY = HolePos - holeY + holeY * HoleShiftY + shiftY render.Clear(r, g, b, 255, true, true) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) surface.SetDrawColor(EyeIris1) surface.SetMaterial(@@EYE_OVALS[EyeType] or @EYE_OVAL) DrawTexturedRectRotated(IrisPos + shiftX, IrisPos + shiftY, IrisQuadSize * IrisWidth, IrisQuadSize * IrisHeight, EyeRotation) surface.SetDrawColor(EyeIris2) surface.SetMaterial(@@EYE_GRAD) DrawTexturedRectRotated(IrisPos + shiftX, IrisPos + shiftY, IrisQuadSize * IrisWidth, IrisQuadSize * IrisHeight, EyeRotation) if EyeLines lprefix = prefixUpper lprefix = prefixUpperR if not EyeLineDirection surface.SetDrawColor(EyeIrisLine1) surface.SetMaterial(@@["EYE_LINE_#{lprefix}_1"]) DrawTexturedRectRotated(IrisPos + shiftX, IrisPos + shiftY, IrisQuadSize * IrisWidth, IrisQuadSize * IrisHeight, EyeRotation) surface.SetDrawColor(EyeIrisLine2) surface.SetMaterial(@@["EYE_LINE_#{lprefix}_2"]) DrawTexturedRectRotated(IrisPos + shiftX, IrisPos + shiftY, IrisQuadSize * IrisWidth, IrisQuadSize * IrisHeight, EyeRotation) surface.SetDrawColor(EyeHole) surface.SetMaterial(@@EYE_OVALS[EyeType] or @EYE_OVAL) DrawTexturedRectRotated(calcHoleX, calcHoleY, HoleQuadSize * HoleWidth * IrisWidth, HoleQuadSize * HoleHeight * IrisHeight, EyeRotation) surface.SetDrawColor(EyeEffect) surface.SetMaterial(@@EYE_EFFECT) DrawTexturedRectRotated(IrisPos + shiftX, IrisPos + shiftY, IrisQuadSize * IrisWidth, IrisQuadSize * IrisHeight, EyeRotation) surface.SetDrawColor(EyeReflection) surface.SetMaterial(PPM2.MaterialsRegistry.EYE_REFLECTIONS[EyeReflectionType]) DrawTexturedRectRotated(IrisPos + shiftX, IrisPos + shiftY, IrisQuadSize * IrisWidth, IrisQuadSize * IrisHeight, EyeRotation) render.PopFilterMag() render.PopFilterMin() if isRenderTarget render_frame() createdMaterial\SetTexture('$iris', release(@, 'eye_' .. prefixUpper, texSize, texSize)) else -- 1 - base frame -- 2 - 6 - enlarge -- 7 - 20 - shrink vtf = DLib.VTF.Create(2, texSize, texSize, PPM2.NO_COMPRESSION\GetBool() and IMAGE_FORMAT_RGB888 or IMAGE_FORMAT_DXT1, {fill: Color(r, g, b), mipmap_count: -2, frames: 20}) for i, mult in ipairs({1, 1.04, 1.08, 1.12, 1.16, 1.20, 1, 0.96153846153846, 0.92307692307692, 0.88461538461538, 0.84615384615385, 0.80769230769231, 0.76923076923077, 0.73076923076923, 0.69230769230769, 0.65384615384615, 0.61538461538462, 0.57692307692308, 0.53846153846154, 0.5}) render_frame(mult) vtf\CaptureRenderTargetCoroutine({frame: i}) release(@, 'eye_' .. prefixUpper, texSize, texSize) vtf\AutoGenerateMips(false) path = @@SetCacheH(hash, vtf\ToString()) createdMaterial\SetTexture('$iris', path) createdMaterial\GetTexture('$iris')\Download() _CaptureAlphaClosure: (...) => @@_CaptureAlphaClosure(...) @_CaptureAlphaClosure: (texSize, mat, vtf) => rt1, rt2, mat1, mat2 = @LockRenderTargetMask(texSize, texSize) surface.SetDrawColor(255, 255, 255) -- capture alpha render.PushRenderTarget(rt1) render.Clear(255, 255, 255, 0, true, true) cam.Start2D() render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) render.OverrideBlend(true, BLEND_DST_COLOR, BLEND_DST_COLOR, BLENDFUNC_ADD, BLEND_SRC_ALPHA, BLEND_DST_ALPHA, BLENDFUNC_ADD) surface.SetMaterial(mat) surface.DrawTexturedRectUV(0, 0, texSize - 1, texSize - 1, -0.016129032258065, -0.016129032258065, 1.0161290322581, 1.0161290322581) render.OverrideBlend(false) render.PopFilterMag() render.PopFilterMin() cam.End2D() render.PopRenderTarget() @ReleaseRenderTarget(texSize, texSize, true) -- compute alpha render.PushRenderTarget(rt2) render.Clear(0, 0, 0, 255, true, true) cam.Start2D() render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) surface.SetMaterial(mat1) surface.DrawTexturedRectUV(0, 0, texSize - 1, texSize - 1, -0.016129032258065, -0.016129032258065, 1.0161290322581, 1.0161290322581) render.PopFilterMag() render.PopFilterMin() cam.End2D() PPM2.LATEST_MASK_ = mat1 PPM2.LATEST_MASK = mat2 vtf\CaptureRenderTargetAsAlphaCoroutine() render.PopRenderTarget() @ReleaseRenderTargetMask(texSize, texSize) CompileCMark: (isRenderTarget, lock, release) => return unless @isValid textureData = { 'name': "PPM2_#{@GetID()}_CMark" 'shader': 'VertexLitGeneric' 'data': { '$basetexture': '__error' '$translucent': '1' '$vertexalpha': '1' -- this is required for DXT3/DXT5 textures '$lightwarptexture': 'models/ppm2/base/lightwrap' } } textureDataGUI = { 'name': "PPM2_#{@GetID()}_CMark_GUI" 'shader': 'UnlitGeneric' 'data': { '$basetexture': '__error' '$vertexalpha': '1' -- this is required for DXT3/DXT5 textures '$lightwarptexture': 'models/ppm2/base/lightwrap' } } @CMarkTextureName = "!#{textureData.name\lower()}" @CMarkTexture = CreateMaterial(textureData.name, textureData.shader, textureData.data) @CMarkTextureGUIName = "!#{textureDataGUI.name\lower()}" @CMarkTextureGUI = CreateMaterial(textureDataGUI.name, textureDataGUI.shader, textureDataGUI.data) unless @GrabData('CMark') @CMarkTexture\SetTexture('$basetexture', null_texrure) @CMarkTextureGUI\SetTexture('$basetexture', null_texrure) return URL = @GrabData('CMarkURL') size = 1 / @GrabData('CMarkSize') texSize = (PPM2.USE_HIGHRES_TEXTURES\GetInt()\Clamp(0, 1) + 1) * @@QUAD_SIZE_CMARK matrix = Matrix() matrix\Translate(Vector(0.5, 0.5)) matrix\Scale(Vector(size, size)) matrix\Translate(Vector(-0.5, -0.5)) @CMarkTexture\SetMatrix('$basetexturetransform', matrix) @CMarkTextureGUI\SetMatrix('$basetexturetransform', matrix) CMarkColor = @GrabData('CMarkColor') @CMarkTexture\SetVector('$color2', CMarkColor\ToVector()) @CMarkTextureGUI\SetVector('$color2', CMarkColor\ToVector()) if url = PPM2.IsValidURL(URL) texture = PPM2.GetURLMaterial(url, texSize, texSize)\Await() return unless @isValid @CMarkTexture\SetTexture('$basetexture', texture) @CMarkTextureGUI\SetTexture('$basetexture', texture) return if mark = PPM2.MaterialsRegistry.CUTIEMARKS[@GrabData('CMarkType')] @CMarkTexture\SetTexture('$basetexture', mark\GetTexture('$basetexture')) @CMarkTextureGUI\SetTexture('$basetexture', mark\GetTexture('$basetexture')) else @CMarkTexture\SetTexture('$basetexture', null_texrure) @CMarkTextureGUI\SetTexture('$basetexture', null_texrure) PPM2.GetTextureController = (model = 'models/ppm/player_default_base.mdl') -> PPM2.PonyTextureController.AVALIABLE_CONTROLLERS[model\lower()] or PPM2.PonyTextureController
34.260536
284
0.696031
0143949ee564aa65bba5308130a2cb99118b398b
2,104
require 'howl.completion.api_completer' import Buffer from howl import completion from howl import DefaultMode from howl.modes match = require 'luassert.match' describe 'api_completer', -> factory = completion.api.factory describe 'complete()', -> api = { keyword: {}, function: {}, sub: { foo: {} bar: {} zed: { frob: {} other: {} } } } local buffer, mode complete_at = (pos) -> context = buffer\context_at pos completer = factory buffer, context comps = completer\complete context table.sort comps comps before_each -> mode = DefaultMode! mode.api = api mode.completers = { 'api' } buffer = Buffer mode it 'returns global completions when no prefix is found', -> buffer.text = ' k\nfun' comps = complete_at buffer.lines[1].start_pos assert.same { 'function', 'keyword', 'sub' }, comps assert.same { 'function' }, complete_at buffer.lines[2].end_pos it 'returns authoritive scoped completions when appropriate', -> buffer.text = 'sub.zed:f' assert.same { 'bar', 'foo', 'zed', authoritive: true }, complete_at 5 assert.same { 'zed', authoritive: true }, complete_at 6 assert.same { 'frob', 'other', authoritive: true }, complete_at 9 it 'returns an empty set for non-matched prefixes', -> buffer.text = 'well so.sub' assert.same { }, complete_at 5 assert.same { }, complete_at 8 assert.same { }, complete_at buffer.length + 1 context 'when mode provides a .resolve_type() method', -> it 'is invoked with (mode, context)', -> mode.resolve_type = spy.new -> nil buffer.text = 'lookie' complete_at 5 assert.spy(mode.resolve_type).was_called_with match.is_ref(mode), buffer\context_at 5 it 'the returned (path, part) is used for looking up completions', -> mode.resolve_type = -> 'sub', {'sub'} buffer.text = 'look.' assert.same { 'bar', 'foo', 'zed', authoritive: true }, complete_at 6
30.492754
93
0.607414
0984afbce8b68624a8d33207edb815b1f4bbf31b
33,677
export RUN_TESTS = false if RUN_TESTS print('Running tests') utility = nil json = nil Game = nil export LOCALIZATION = nil export STATE = { -- Always available INITIALIZED: false PATHS: { RESOURCES: nil DOWNLOADFILE: nil GAMES: 'games.json' } ROOT_CONFIG: nil SETTINGS: {} NUM_SLOTS: 0 SCROLL_INDEX: 1 SCROLL_STEP: 1 LEFT_CLICK_ACTION: 1 PLATFORM_NAMES: {} PLATFORM_RUNNING_STATUS: {} GAMES: {} REVEALING_DELAY: 0 SKIN_VISIBLE: true SKIN_ANIMATION_PLAYING: false -- Volatile PLATFORM_ENABLED_STATUS: nil PLATFORM_QUEUE: nil BANNER_QUEUE: nil GAME_BEING_MODIFIED: nil } export COMPONENTS = { STATUS: nil SETTINGS: nil LIBRARY: nil } export log = (...) -> print(...) if STATE.LOGGING == true downloadFile = (url, path, finishCallback, errorCallback) -> log('Attempting to download file:', url, path, finishCallback, errorCallback) assert(type(url) == 'string', 'main.init.downloadFile') assert(type(path) == 'string', 'main.init.downloadFile') assert(type(finishCallback) == 'string', 'main.init.downloadFile') assert(type(errorCallback) == 'string', 'main.init.downloadFile') SKIN\Bang(('[!SetOption "Downloader" "URL" "%s"]')\format(url)) SKIN\Bang(('[!SetOption "Downloader" "DownloadFile" "%s"]')\format(path)) SKIN\Bang(('[!SetOption "Downloader" "FinishAction" "[!CommandMeasure Script %s()]"]')\format(finishCallback)) SKIN\Bang(('[!SetOption "Downloader" "OnConnectErrorAction" "[!CommandMeasure Script %s()]"]')\format(errorCallback)) SKIN\Bang(('[!SetOption "Downloader" "OnRegExpErrorAction" "[!CommandMeasure Script %s()]"]')\format(errorCallback)) SKIN\Bang(('[!SetOption "Downloader" "OnDownloadErrorAction" "[!CommandMeasure Script %s()]"]')\format(errorCallback)) SKIN\Bang('[!SetOption "Downloader" "UpdateDivider" "63"]') SKIN\Bang('[!SetOption "Downloader" "Disabled" "0"]') SKIN\Bang('[!UpdateMeasure "Downloader"]') stopDownloader = () -> log('Stopping downloader') SKIN\Bang('[!SetOption "Downloader" "UpdateDivider" "-1"]') SKIN\Bang('[!SetOption "Downloader" "Disabled" "1"]') SKIN\Bang('[!UpdateMeasure "Downloader"]') downloadBanner = (game) -> log('Downloading a banner for', game\getTitle()) assert(game ~= nil, 'main.init.downloadBanner') assert(game.__class == Game, 'main.init.downloadBanner') bannerPath = game\getBanner()\reverse()\match('^([^%.]+%.[^\\]+)')\reverse() downloadFile(game\getBannerURL(), bannerPath, 'OnBannerDownloadFinished', 'OnBannerDownloadError') export setUpdateDivider = (value) -> assert(type(value) == 'number' and value % 1 == 0 and value ~= 0, 'main.init.setUpdateDivider') SKIN\Bang(('[!SetOption "Script" "UpdateDivider" "%d"]')\format(value)) SKIN\Bang('[!UpdateMeasure "Script"]') startDetectingPlatformGames = () -> COMPONENTS.STATUS\show(LOCALIZATION\get('main_status_detecting_platform_games', 'Detecting %s games')\format(STATE.PLATFORM_QUEUE[1]\getName())) switch STATE.PLATFORM_QUEUE[1]\getPlatformID() when ENUMS.PLATFORM_IDS.SHORTCUTS log('Starting to detect Windows shortcuts') utility.runCommand(STATE.PLATFORM_QUEUE[1]\parseShortcuts()) when ENUMS.PLATFORM_IDS.STEAM url, path, finishCallback, errorCallback = STATE.PLATFORM_QUEUE[1]\downloadCommunityProfile() if url ~= nil log('Attempting to download and parse the Steam community profile') downloadFile(url, path, finishCallback, errorCallback) else log('Starting to detect Steam games') STATE.PLATFORM_QUEUE[1]\getLibraries() if STATE.PLATFORM_QUEUE[1]\hasLibrariesToParse() utility.runCommand(STATE.PLATFORM_QUEUE[1]\getACFs()) else OnFinishedDetectingPlatformGames() when ENUMS.PLATFORM_IDS.STEAM_SHORTCUTS log('Starting to detect non-Steam game shortcuts added to Steam') games = STATE.PLATFORM_QUEUE[1]\generateGames() OnFinishedDetectingPlatformGames() when ENUMS.PLATFORM_IDS.BATTLENET log('Starting to detect Blizzard Battle.net games') if STATE.PLATFORM_QUEUE[1]\hasUnprocessedPaths() utility.runCommand(STATE.PLATFORM_QUEUE[1]\identifyFolders()) else OnFinishedDetectingPlatformGames() when ENUMS.PLATFORM_IDS.GOG_GALAXY log('Starting to detect GOG Galaxy games') utility.runCommand(STATE.PLATFORM_QUEUE[1]\dumpDatabases()) else assert(nil, 'main.init.startDetectingPlatformGames') detectGames = () -> COMPONENTS.STATUS\show(LOCALIZATION\get('main_status_detecting_games', 'Detecting games')) platforms = [Platform(COMPONENTS.SETTINGS) for Platform in *require('main.platforms')] log('Num platforms:', #platforms) COMPONENTS.PROCESS\registerPlatforms(platforms) STATE.PLATFORM_ENABLED_STATUS = {} STATE.PLATFORM_QUEUE = {} for platform in *platforms enabled = platform\isEnabled() platform\validate() if enabled platformID = platform\getPlatformID() STATE.PLATFORM_NAMES[platformID] = platform\getName() STATE.PLATFORM_ENABLED_STATUS[platformID] = enabled STATE.PLATFORM_RUNNING_STATUS[platformID] = false if platform\getPlatformProcess() ~= nil table.insert(STATE.PLATFORM_QUEUE, platform) if enabled log(' ' .. STATE.PLATFORM_NAMES[platformID] .. ' = ' .. tostring(enabled)) assert(#STATE.PLATFORM_QUEUE > 0, 'There are no enabled platforms.') STATE.BANNER_QUEUE = {} startDetectingPlatformGames() startDownloadingBanner = () -> while #STATE.BANNER_QUEUE > 0 -- Remove games, which have previously failed to have their banners downloaded if io.fileExists((STATE.BANNER_QUEUE[1]\getBanner()\gsub('%..+', '%.failedToDownload'))) table.remove(STATE.BANNER_QUEUE, 1) continue break if #STATE.BANNER_QUEUE > 0 log('Starting to download a banner') COMPONENTS.STATUS\show(LOCALIZATION\get('main_status_n_banners_to_download', '%d banners left to download')\format(#STATE.BANNER_QUEUE)) downloadBanner(STATE.BANNER_QUEUE[1]) else STATE.BANNER_QUEUE = nil OnFinishedDownloadingBanners() updateSlots = () -> success, err = pcall( () -> if STATE.SCROLL_INDEX < 1 STATE.SCROLL_INDEX = 1 elseif STATE.SCROLL_INDEX > #STATE.GAMES - STATE.NUM_SLOTS + 1 if #STATE.GAMES > STATE.NUM_SLOTS STATE.SCROLL_INDEX = #STATE.GAMES - STATE.NUM_SLOTS + 1 else STATE.SCROLL_INDEX = 1 if COMPONENTS.SLOTS\populate(STATE.GAMES, STATE.SCROLL_INDEX) COMPONENTS.ANIMATIONS\resetSlots() COMPONENTS.SLOTS\update() else SKIN\Bang(('[!SetOption "Slot1Text" "Text" "%s"]')\format(LOCALIZATION\get('main_no_games', 'No games to show'))) COMPONENTS.ANIMATIONS\resetSlots() COMPONENTS.SLOTS\update() ) COMPONENTS.STATUS\show(err, true) unless success onInitialized = () -> COMPONENTS.STATUS\hide() COMPONENTS.LIBRARY\finalize(STATE.PLATFORM_ENABLED_STATUS) STATE.PLATFORM_ENABLED_STATUS = nil COMPONENTS.LIBRARY\save() COMPONENTS.LIBRARY\sort(COMPONENTS.SETTINGS\getSorting()) STATE.GAMES = COMPONENTS.LIBRARY\get() updateSlots() STATE.INITIALIZED = true animationType = COMPONENTS.SETTINGS\getSkinSlideAnimation() if animationType ~= ENUMS.SKIN_ANIMATIONS.NONE COMPONENTS.ANIMATIONS\pushSkinSlide(animationType, false) setUpdateDivider(1) COMPONENTS.PROCESS\update() log('Skin initialized') additionalEnums = () -> ENUMS.LEFT_CLICK_ACTIONS = { LAUNCH_GAME: 1 HIDE_GAME: 2 UNHIDE_GAME: 3 REMOVE_GAME: 4 } export Initialize = () -> STATE.PATHS.RESOURCES = SKIN\GetVariable('@') STATE.PATHS.DOWNLOADFILE = SKIN\GetVariable('CURRENTPATH') .. 'DownloadFile\\' STATE.ROOT_CONFIG = SKIN\GetVariable('ROOTCONFIG') dofile(('%s%s')\format(STATE.PATHS.RESOURCES, 'lib\\rainmeter_helpers.lua')) COMPONENTS.STATUS = require('shared.status')() success, err = pcall( () -> require('shared.enums') additionalEnums() Game = require('main.game') utility = require('shared.utility') utility.createJSONHelpers() json = require('lib.json') COMPONENTS.SETTINGS = require('shared.settings')() STATE.LOGGING = COMPONENTS.SETTINGS\getLogging() STATE.SCROLL_STEP = COMPONENTS.SETTINGS\getScrollStep() log('Initializing skin') export LOCALIZATION = require('shared.localization')(COMPONENTS.SETTINGS) COMPONENTS.STATUS\show(LOCALIZATION\get('status_initializing', 'Initializing')) SKIN\Bang(('[!SetVariable "ContextTitleSettings" "%s"]')\format(LOCALIZATION\get('main_context_title_settings', 'Settings'))) SKIN\Bang(('[!SetVariable "ContextTitleOpenShortcutsFolder" "%s"]')\format(LOCALIZATION\get('main_context_title_open_shortcuts_folder', 'Open shortcuts folder'))) SKIN\Bang(('[!SetVariable "ContextTitleExecuteStoppingBangs" "%s"]')\format(LOCALIZATION\get('main_context_title_execute_stopping_bangs', 'Execute stopping bangs'))) SKIN\Bang(('[!SetVariable "ContextTitleHideGamesStatus" "%s"]')\format(LOCALIZATION\get('main_context_title_start_hiding_games', 'Start hiding games'))) SKIN\Bang(('[!SetVariable "ContextTitleUnhideGameStatus" "%s"]')\format(LOCALIZATION\get('main_context_title_start_unhiding_games', 'Start unhiding games'))) SKIN\Bang(('[!SetVariable "ContextTitleRemoveGamesStatus" "%s"]')\format(LOCALIZATION\get('main_context_title_start_removing_games', 'Start removing games'))) COMPONENTS.TOOLBAR = require('main.toolbar')(COMPONENTS.SETTINGS) COMPONENTS.TOOLBAR\hide() COMPONENTS.ANIMATIONS = require('main.animations')() STATE.NUM_SLOTS = COMPONENTS.SETTINGS\getLayoutRows() * COMPONENTS.SETTINGS\getLayoutColumns() COMPONENTS.SLOTS = require('main.slots')(COMPONENTS.SETTINGS) COMPONENTS.LIBRARY = require('shared.library')(COMPONENTS.SETTINGS) COMPONENTS.PROCESS = require('main.process')() detectGames() ) COMPONENTS.STATUS\show(err, true) unless success export Update = () -> return unless STATE.INITIALIZED success, err = pcall( () -> if STATE.SKIN_ANIMATION_PLAYING COMPONENTS.ANIMATIONS\play() elseif STATE.REVEALING_DELAY >= 0 and not STATE.SKIN_VISIBLE STATE.REVEALING_DELAY -= 17 if STATE.REVEALING_DELAY < 0 COMPONENTS.ANIMATIONS\pushSkinSlide(COMPONENTS.SETTINGS\getSkinSlideAnimation(), true) else COMPONENTS.ANIMATIONS\play() if STATE.SCROLL_INDEX_UPDATED == false updateSlots() STATE.SCROLL_INDEX_UPDATED = true ) unless success COMPONENTS.STATUS\show(err, true) setUpdateDivider(-1) -- Process monitoring export UpdateProcess = (running) -> return unless STATE.INITIALIZED success, err = pcall( () -> COMPONENTS.PROCESS\update(running == 1) ) COMPONENTS.STATUS\show(err, true) unless success export UpdatePlatformProcesses = () -> return unless STATE.INITIALIZED success, err = pcall( () -> STATE.PLATFORM_RUNNING_STATUS = COMPONENTS.PROCESS\updatePlatforms() ) COMPONENTS.STATUS\show(err, true) unless success export GameProcessStarted = (game) -> return unless STATE.INITIALIZED success, err = pcall( () -> log('Game started') return ) COMPONENTS.STATUS\show(err, true) unless success export GameProcessTerminated = (game) -> return unless STATE.INITIALIZED success, err = pcall( () -> duration = COMPONENTS.PROCESS\getDuration() / 3600 log(game\getTitle(), 'was played for', duration, 'hours') game\incrementHoursPlayed(duration) COMPONENTS.LIBRARY\save() platformID = game\getPlatformID() if COMPONENTS.SETTINGS\getBangsEnabled() unless game\getIgnoresOtherBangs() SKIN\Bang(bang) for bang in *COMPONENTS.SETTINGS\getGlobalStoppingBangs() platformBangs = switch platformID when ENUMS.PLATFORM_IDS.SHORTCUTS COMPONENTS.SETTINGS\getShortcutsStoppingBangs() when ENUMS.PLATFORM_IDS.STEAM, ENUMS.PLATFORM_IDS.STEAM_SHORTCUTS COMPONENTS.SETTINGS\getSteamStoppingBangs() when ENUMS.PLATFORM_IDS.BATTLENET COMPONENTS.SETTINGS\getBattlenetStoppingBangs() when ENUMS.PLATFORM_IDS.GOG_GALAXY COMPONENTS.SETTINGS\getGOGGalaxyStoppingBangs() else assert(nil, 'Encountered an unsupported platform ID when executing platform-specific stopping bangs.') SKIN\Bang(bang) for bang in *platformBangs SKIN\Bang(bang) for bang in *game\getStoppingBangs() switch platformID when ENUMS.PLATFORM_IDS.GOG_GALAXY if COMPONENTS.SETTINGS\getGOGGalaxyIndirectLaunch() SKIN\Bang('["#@#windowless.vbs" "#@#main\\platforms\\gog_galaxy\\closeClient.bat"]') SKIN\Bang('[!ShowFade]') if COMPONENTS.SETTINGS\getHideSkin() ) COMPONENTS.STATUS\show(err, true) unless success export ManuallyTerminateGameProcess = () -> success, err = pcall( () -> COMPONENTS.PROCESS\stopMonitoring() ) COMPONENTS.STATUS\show(err, true) unless success -- Skin events export Unload = () -> success, err = pcall( () -> log('Unloading skin') COMPONENTS.LIBRARY\save() COMPONENTS.SETTINGS\save() ) COMPONENTS.STATUS\show(err, true) unless success export OnMouseOver = () -> return unless STATE.INITIALIZED success, err = pcall( () -> setUpdateDivider(1) ) COMPONENTS.STATUS\show(err, true) unless success otherWindowsActive = () -> rootConfigName = STATE.ROOT_CONFIG configs = utility.getConfigs([('%s\\%s')\format(rootConfigName, name) for name in *{'Search', 'Sort', 'Filter', 'Game'}]) for config in *configs if config\isActive() return true return false export OnMouseLeave = () -> return unless STATE.INITIALIZED success, err = pcall( () -> COMPONENTS.ANIMATIONS\resetSlots() animationType = COMPONENTS.SETTINGS\getSkinSlideAnimation() if STATE.SKIN_VISIBLE and animationType ~= ENUMS.SKIN_ANIMATIONS.NONE and not otherWindowsActive() if COMPONENTS.ANIMATIONS\pushSkinSlide(animationType, false) return setUpdateDivider(-1) ) COMPONENTS.STATUS\show(err, true) unless success export OnMouseLeaveEnabler = () -> return unless STATE.INITIALIZED return if STATE.SKIN_VISIBLE success, err = pcall( () -> STATE.REVEALING_DELAY = COMPONENTS.SETTINGS\getSkinRevealingDelay() setUpdateDivider(-1) ) COMPONENTS.STATUS\show(err, true) unless success -- Toolbar export OnMouseOverToolbar = () -> return unless STATE.INITIALIZED return unless STATE.SKIN_VISIBLE return if STATE.SKIN_ANIMATION_PLAYING success, err = pcall( () -> COMPONENTS.TOOLBAR\show() COMPONENTS.SLOTS\unfocus() COMPONENTS.SLOTS\leave() COMPONENTS.ANIMATIONS\resetSlots() COMPONENTS.ANIMATIONS\cancelAnimations() ) COMPONENTS.STATUS\show(err, true) unless success export OnMouseLeaveToolbar = () -> return unless STATE.INITIALIZED return unless STATE.SKIN_VISIBLE return if STATE.SKIN_ANIMATION_PLAYING success, err = pcall( () -> COMPONENTS.TOOLBAR\hide() COMPONENTS.SLOTS\focus() COMPONENTS.SLOTS\hover() ) COMPONENTS.STATUS\show(err, true) unless success -- Toolbar -> Searching export OnToolbarSearch = (stack) -> return unless STATE.INITIALIZED STATE.STACK_NEXT_FILTER = stack log('OnToolbarSearch', stack) SKIN\Bang('[!ActivateConfig "#ROOTCONFIG#\\Search"]') export HandshakeSearch = () -> return unless STATE.INITIALIZED success, err = pcall( () -> SKIN\Bang(('[!CommandMeasure "Script" "Handshake(%s)" "#ROOTCONFIG#\\Search"]')\format(tostring(STATE.STACK_NEXT_FILTER))) ) COMPONENTS.STATUS\show(err, true) unless success export Search = (str, stack) -> return unless STATE.INITIALIZED success, err = pcall( () -> log('Searching for:', str) games = if stack then STATE.GAMES else nil COMPONENTS.LIBRARY\filter(ENUMS.FILTER_TYPES.TITLE, {input: str, :games, :stack}) STATE.GAMES = COMPONENTS.LIBRARY\get() STATE.SCROLL_INDEX = 1 updateSlots() ) COMPONENTS.STATUS\show(err, true) unless success export OnToolbarResetGames = () -> return unless STATE.INITIALIZED success, err = pcall( () -> STATE.GAMES = COMPONENTS.LIBRARY\get() STATE.SCROLL_INDEX = 1 updateSlots() ) COMPONENTS.STATUS\show(err, true) unless success -- Toolbar -> Sorting export OnToolbarSort = (quick) -> return unless STATE.INITIALIZED success, err = pcall( () -> log('OnToolbarSort') if quick sortingType = COMPONENTS.SETTINGS\getSorting() + 1 sortingType = 1 if sortingType >= ENUMS.SORTING_TYPES.MAX return Sort(sortingType) configName = ('%s\\Sort')\format(STATE.ROOT_CONFIG) config = utility.getConfig(configName) if config ~= nil and config\isActive() return SKIN\Bang(('[!DeactivateConfig "%s"]')\format(configName)) SKIN\Bang(('[!ActivateConfig "%s"]')\format(configName)) ) COMPONENTS.STATUS\show(err, true) unless success export OnToolbarReverseOrder = () -> return unless STATE.INITIALIZED success, err = pcall( () -> log('Reversing order of games') table.reverse(STATE.GAMES) updateSlots() ) COMPONENTS.STATUS\show(err, true) unless success export HandshakeSort = () -> return unless STATE.INITIALIZED success, err = pcall( () -> SKIN\Bang(('[!CommandMeasure "Script" "Handshake(%d)" "#ROOTCONFIG#\\Sort"]')\format(COMPONENTS.SETTINGS\getSorting())) ) COMPONENTS.STATUS\show(err, true) unless success export Sort = (sortingType) -> return unless STATE.INITIALIZED success, err = pcall( () -> COMPONENTS.SETTINGS\setSorting(sortingType) COMPONENTS.LIBRARY\sort(sortingType, STATE.GAMES) STATE.SCROLL_INDEX = 1 updateSlots() ) COMPONENTS.STATUS\show(err, true) unless success -- Toolbar -> Filtering export OnToolbarFilter = (stack) -> return unless STATE.INITIALIZED success, err = pcall( () -> STATE.STACK_NEXT_FILTER = stack configName = ('%s\\Filter')\format(STATE.ROOT_CONFIG) config = utility.getConfig(configName) if config ~= nil and config\isActive() return HandshakeFilter() SKIN\Bang(('[!ActivateConfig "%s"]')\format(configName)) ) COMPONENTS.STATUS\show(err, true) unless success export HandshakeFilter = () -> return unless STATE.INITIALIZED success, err = pcall( () -> stack = tostring(STATE.STACK_NEXT_FILTER) appliedFilters = '[]' if STATE.STACK_NEXT_FILTER appliedFilters = json.encode(COMPONENTS.LIBRARY\getFilterStack())\gsub('"', '|') SKIN\Bang(('[!CommandMeasure "Script" "Handshake(%s, \'%s\')" "#ROOTCONFIG#\\Filter"]')\format(stack, appliedFilters)) ) COMPONENTS.STATUS\show(err, true) unless success export Filter = (filterType, stack, arguments) -> return unless STATE.INITIALIZED success, err = pcall( () -> log('Filter', filterType, type(filterType), stack, type(stack), arguments) arguments = arguments\gsub('|', '"') arguments = json.decode(arguments) arguments.games = if stack then STATE.GAMES else nil arguments.stack = stack COMPONENTS.LIBRARY\filter(filterType, arguments) STATE.GAMES = COMPONENTS.LIBRARY\get() STATE.SCROLL_INDEX = 1 updateSlots() ) COMPONENTS.STATUS\show(err, true) unless success -- Slots launchGame = (game) -> if game\isInstalled() == true game\setLastPlayed(os.time()) COMPONENTS.LIBRARY\sort(COMPONENTS.SETTINGS\getSorting()) COMPONENTS.LIBRARY\save() STATE.GAMES = COMPONENTS.LIBRARY\get() STATE.SCROLL_INDEX = 1 updateSlots() COMPONENTS.PROCESS\monitor(game) if COMPONENTS.SETTINGS\getBangsEnabled() unless game\getIgnoresOtherBangs() SKIN\Bang(bang) for bang in *COMPONENTS.SETTINGS\getGlobalStartingBangs() platformBangs = switch game\getPlatformID() when ENUMS.PLATFORM_IDS.SHORTCUTS COMPONENTS.SETTINGS\getShortcutsStartingBangs() when ENUMS.PLATFORM_IDS.STEAM, ENUMS.PLATFORM_IDS.STEAM_SHORTCUTS COMPONENTS.SETTINGS\getSteamStartingBangs() when ENUMS.PLATFORM_IDS.BATTLENET COMPONENTS.SETTINGS\getBattlenetStartingBangs() when ENUMS.PLATFORM_IDS.GOG_GALAXY COMPONENTS.SETTINGS\getGOGGalaxyStartingBangs() else assert(nil, 'Encountered an unsupported platform ID when executing platform-specific starting bangs.') SKIN\Bang(bang) for bang in *platformBangs SKIN\Bang(bang) for bang in *game\getStartingBangs() SKIN\Bang(('[%s]')\format(game\getPath())) SKIN\Bang('[!HideFade]') if COMPONENTS.SETTINGS\getHideSkin() elseif game\getPlatformID() == ENUMS.PLATFORM_IDS.STEAM game\setLastPlayed(os.time()) game\setInstalled(true) COMPONENTS.LIBRARY\sort(COMPONENTS.SETTINGS\getSorting()) COMPONENTS.LIBRARY\save() STATE.GAMES = COMPONENTS.LIBRARY\get() STATE.SCROLL_INDEX = 1 updateSlots() SKIN\Bang(('[%s]')\format(game\getPath())) hideGame = (game) -> return if game\isVisible() == false game\setVisible(false) COMPONENTS.LIBRARY\save() i = table.find(STATE.GAMES, game) table.remove(STATE.GAMES, i) if #STATE.GAMES == 0 COMPONENTS.LIBRARY\filter(ENUMS.FILTER_TYPES.NONE) STATE.GAMES = COMPONENTS.LIBRARY\get() STATE.SCROLL_INDEX = 1 ToggleHideGames() updateSlots() unhideGame = (game) -> return if game\isVisible() == true game\setVisible(true) COMPONENTS.LIBRARY\save() i = table.find(STATE.GAMES, game) table.remove(STATE.GAMES, i) if #STATE.GAMES == 0 COMPONENTS.LIBRARY\filter(ENUMS.FILTER_TYPES.NONE) STATE.GAMES = COMPONENTS.LIBRARY\get() STATE.SCROLL_INDEX = 1 ToggleUnhideGames() updateSlots() removeGame = (game) -> i = table.find(STATE.GAMES, game) table.remove(STATE.GAMES, i) COMPONENTS.LIBRARY\remove(game) i = table.find(STATE.GAMES, game) table.remove(STATE.GAMES, i) if #STATE.GAMES == 0 COMPONENTS.LIBRARY\filter(ENUMS.FILTER_TYPES.NONE) STATE.GAMES = COMPONENTS.LIBRARY\get() STATE.SCROLL_INDEX = 1 ToggleRemoveGames() updateSlots() export OnLeftClickSlot = (index) -> return unless STATE.INITIALIZED return if STATE.SKIN_ANIMATION_PLAYING return if index < 1 or index > STATE.NUM_SLOTS success, err = pcall( () -> game = COMPONENTS.SLOTS\leftClick(index) return unless game action = switch STATE.LEFT_CLICK_ACTION when ENUMS.LEFT_CLICK_ACTIONS.LAUNCH_GAME then launchGame when ENUMS.LEFT_CLICK_ACTIONS.HIDE_GAME then hideGame when ENUMS.LEFT_CLICK_ACTIONS.UNHIDE_GAME then unhideGame when ENUMS.LEFT_CLICK_ACTIONS.REMOVE_GAME then removeGame else assert(nil, 'main.init.OnLeftClickSlot') animationType = COMPONENTS.SETTINGS\getSlotsClickAnimation() unless COMPONENTS.ANIMATIONS\pushSlotClick(index, animationType, action, game) action(game) ) COMPONENTS.STATUS\show(err, true) unless success export OnMiddleClickSlot = (index) -> return unless STATE.INITIALIZED return if STATE.SKIN_ANIMATION_PLAYING return if index < 1 or index > STATE.NUM_SLOTS success, err = pcall( () -> log('OnMiddleClickSlot', index) game = COMPONENTS.SLOTS\middleClick(index) return if game == nil configName = ('%s\\Game')\format(STATE.ROOT_CONFIG) if STATE.GAME_BEING_MODIFIED ~= nil and game == STATE.GAME_BEING_MODIFIED STATE.GAME_BEING_MODIFIED = nil return SKIN\Bang(('[!DeactivateConfig "%s"]')\format(configName)) STATE.GAME_BEING_MODIFIED = game config = utility.getConfig(configName) if config == nil or not config\isActive() SKIN\Bang(('[!ActivateConfig "%s"]')\format(configName)) else HandshakeGame() ) COMPONENTS.STATUS\show(err, true) unless success export HandshakeGame = () -> return unless STATE.INITIALIZED success, err = pcall( () -> log('HandshakeGame') gameID = STATE.GAME_BEING_MODIFIED\getGameID() STATE.GAME_BEING_MODIFIED = nil assert(gameID ~= nil, 'main.init.HandshakeGame') SKIN\Bang(('[!CommandMeasure "Script" "Handshake(%d)" "#ROOTCONFIG#\\Game"]')\format(gameID)) ) COMPONENTS.STATUS\show(err, true) unless success export UpdateGame = (gameID) -> return unless STATE.INITIALIZED success, err = pcall( () -> log('UpdateGame') if gameID ~= nil games = io.readJSON(STATE.PATHS.GAMES) games = games.games game = games[gameID] -- gameID should also be the index of the game since the games table in games.json should be sorted according to the gameIDs. if game == nil or game.gameID ~= gameID game = nil for args in *games if args.gameID == gameID game = args break assert(game ~= nil, 'main.init.UpdateGame') COMPONENTS.LIBRARY\update(Game(game)) ) COMPONENTS.STATUS\show(err, true) unless success export OnHoverSlot = (index) -> return unless STATE.INITIALIZED return if STATE.SKIN_ANIMATION_PLAYING return if index < 1 or index > STATE.NUM_SLOTS success, err = pcall( () -> COMPONENTS.SLOTS\hover(index) ) COMPONENTS.STATUS\show(err, true) unless success export OnLeaveSlot = (index) -> return unless STATE.INITIALIZED return if STATE.SKIN_ANIMATION_PLAYING return if index < 1 or index > STATE.NUM_SLOTS success, err = pcall( () -> COMPONENTS.SLOTS\leave(index) ) COMPONENTS.STATUS\show(err, true) unless success export OnScrollSlots = (direction) -> return unless STATE.INITIALIZED return if STATE.SKIN_ANIMATION_PLAYING success, err = pcall( () -> index = STATE.SCROLL_INDEX + direction * STATE.SCROLL_STEP if index < 1 return elseif index > #STATE.GAMES - STATE.NUM_SLOTS + 1 return STATE.SCROLL_INDEX = index log(('Scroll index is now %d')\format(STATE.SCROLL_INDEX)) STATE.SCROLL_INDEX_UPDATED = false ) COMPONENTS.STATUS\show(err, true) unless success -- Game detection export OnFinishedDetectingPlatformGames = () -> success, err = pcall( () -> log('Finished detecting platform\'s games') platform = table.remove(STATE.PLATFORM_QUEUE, 1) games = platform\getGames() log(('Found %d %s games')\format(#games, platform\getName())) COMPONENTS.LIBRARY\add(games) for game in *games if game\getBannerURL() ~= nil if game\getBanner() == nil game\setBannerURL(nil) else table.insert(STATE.BANNER_QUEUE, game) if #STATE.PLATFORM_QUEUE > 0 return startDetectingPlatformGames() STATE.PLATFORM_QUEUE = nil log(('%d banners to download')\format(#STATE.BANNER_QUEUE)) if #STATE.BANNER_QUEUE > 0 return startDownloadingBanner() onInitialized() ) COMPONENTS.STATUS\show(err, true) unless success -- Game detection -> Windows shortcuts export OnParsedShortcuts = () -> success, err = pcall( () -> unless STATE.PLATFORM_QUEUE[1]\hasParsedShortcuts() return utility.runLastCommand() log('Parsed Windows shortcuts') output = '' path = STATE.PLATFORM_QUEUE[1]\getOutputPath() if io.fileExists(path) output = io.readFile(path) STATE.PLATFORM_QUEUE[1]\generateGames(output) OnFinishedDetectingPlatformGames() ) COMPONENTS.STATUS\show(err, true) unless success -- Game detection -> Steam export OnCommunityProfileDownloaded = () -> success, err = pcall( () -> log('Successfully downloaded Steam community profile') stopDownloader() downloadedPath = STATE.PLATFORM_QUEUE[1]\getDownloadedCommunityProfilePath() cachedPath = STATE.PLATFORM_QUEUE[1]\getCachedCommunityProfilePath() os.rename(downloadedPath, cachedPath) profile = '' if io.fileExists(cachedPath, false) profile = io.readFile(cachedPath, false) STATE.PLATFORM_QUEUE[1]\parseCommunityProfile(profile) STATE.PLATFORM_QUEUE[1]\getLibraries() if STATE.PLATFORM_QUEUE[1]\hasLibrariesToParse() return utility.runCommand(STATE.PLATFORM_QUEUE[1]\getACFs()) OnFinishedDetectingPlatformGames() ) COMPONENTS.STATUS\show(err, true) unless success export OnCommunityProfileDownloadFailed = () -> success, err = pcall( () -> log('Failed to download Steam community profile') stopDownloader() STATE.PLATFORM_QUEUE[1]\getLibraries() if STATE.PLATFORM_QUEUE[1]\hasLibrariesToParse() return utility.runCommand(STATE.PLATFORM_QUEUE[1]\getACFs()) OnFinishedDetectingPlatformGames() ) COMPONENTS.STATUS\show(err, true) unless success export OnGotACFs = () -> success, err = pcall( () -> unless STATE.PLATFORM_QUEUE[1]\hasGottenACFs() return utility.runLastCommand() log('Dumped list of Steam appmanifests') STATE.PLATFORM_QUEUE[1]\generateGames() if STATE.PLATFORM_QUEUE[1]\hasLibrariesToParse() return utility.runCommand(STATE.PLATFORM_QUEUE[1]\getACFs()) STATE.PLATFORM_QUEUE[1]\generateShortcuts() OnFinishedDetectingPlatformGames() ) COMPONENTS.STATUS\show(err, true) unless success -- Game detection -> Blizzard Battle.Net export OnIdentifiedBattlenetFolders = () -> success, err = pcall( () -> unless STATE.PLATFORM_QUEUE[1]\hasProcessedPath() return utility.runLastCommand() log('Dumped list of folders in a Blizzard Battle.net folder') STATE.PLATFORM_QUEUE[1]\generateGames(io.readFile(io.joinPaths(STATE.PLATFORM_QUEUE[1]\getCachePath(), 'output.txt'))) if STATE.PLATFORM_QUEUE[1]\hasUnprocessedPaths() return utility.runCommand(STATE.PLATFORM_QUEUE[1]\identifyFolders()) OnFinishedDetectingPlatformGames() ) COMPONENTS.STATUS\show(err, true) unless success -- Game detection -> GOG Galaxy export OnDumpedDBs = () -> success, err = pcall( () -> unless STATE.PLATFORM_QUEUE[1]\hasDumpedDatabases() return utility.runLastCommand() log('Dumped GOG Galaxy databases') cachePath = STATE.PLATFORM_QUEUE[1]\getCachePath() index = io.readFile(io.joinPaths(cachePath, 'index.txt')) galaxy = io.readFile(io.joinPaths(cachePath, 'galaxy.txt')) STATE.PLATFORM_QUEUE[1]\generateGames(index, galaxy) OnFinishedDetectingPlatformGames() ) COMPONENTS.STATUS\show(err, true) unless success -- Banner downloading export OnBannerDownloadFinished = () -> success, err = pcall( () -> log('Successfully downloaded a banner') downloadedPath = io.joinPaths(STATE.PATHS.DOWNLOADFILE, SKIN\GetMeasure('Downloader')\GetOption('DownloadFile')) game = table.remove(STATE.BANNER_QUEUE, 1) bannerPath = io.joinPaths(STATE.PATHS.RESOURCES, game\getBanner()) os.rename(downloadedPath, bannerPath) game\setBannerURL(nil) game\setExpectedBanner(nil) startDownloadingBanner() ) COMPONENTS.STATUS\show(err, true) unless success export OnBannerDownloadError = () -> success, err = pcall( () -> log('Failed to download a banner') game = table.remove(STATE.BANNER_QUEUE, 1) io.writeFile(game\getBanner()\gsub('%..+', '%.failedToDownload'), '') game\setBanner(nil) game\setBannerURL(nil) startDownloadingBanner() ) COMPONENTS.STATUS\show(err, true) unless success export OnFinishedDownloadingBanners = () -> success, err = pcall( () -> log('Finished downloading banners') stopDownloader() onInitialized() ) COMPONENTS.STATUS\show(err, true) unless success -- Context title action export ToggleHideGames = () -> success, err = pcall( () -> if STATE.LEFT_CLICK_ACTION == ENUMS.LEFT_CLICK_ACTIONS.HIDE_GAME SKIN\Bang(('[!SetVariable "ContextTitleHideGamesStatus" "%s"]')\format(LOCALIZATION\get('main_context_title_start_hiding_games', 'Start hiding games'))) STATE.LEFT_CLICK_ACTION = ENUMS.LEFT_CLICK_ACTIONS.LAUNCH_GAME return elseif STATE.LEFT_CLICK_ACTION == ENUMS.LEFT_CLICK_ACTIONS.UNHIDE_GAME ToggleUnhideGames() elseif STATE.LEFT_CLICK_ACTION == ENUMS.LEFT_CLICK_ACTIONS.REMOVE_GAME ToggleRemoveGames() COMPONENTS.LIBRARY\filter(ENUMS.FILTER_TYPES.HIDDEN, {state: false, stack: true, games: STATE.GAMES}) games = COMPONENTS.LIBRARY\get() if #games == 0 COMPONENTS.LIBRARY\filter(ENUMS.FILTER_TYPES.HIDDEN, {state: false}) games = COMPONENTS.LIBRARY\get() if #games == 0 return else STATE.GAMES = games STATE.SCROLL_INDEX = 1 updateSlots() else STATE.GAMES = games updateSlots() SKIN\Bang(('[!SetVariable "ContextTitleHideGamesStatus" "%s"]')\format(LOCALIZATION\get('main_context_title_stop_hiding_games', 'Stop hiding games'))) STATE.LEFT_CLICK_ACTION = ENUMS.LEFT_CLICK_ACTIONS.HIDE_GAME ) COMPONENTS.STATUS\show(err, true) unless success export ToggleUnhideGames = () -> success, err = pcall( () -> if STATE.LEFT_CLICK_ACTION == ENUMS.LEFT_CLICK_ACTIONS.UNHIDE_GAME SKIN\Bang(('[!SetVariable "ContextTitleUnhideGameStatus" "%s"]')\format(LOCALIZATION\get('main_context_title_start_unhiding_games', 'Start unhiding games'))) STATE.LEFT_CLICK_ACTION = ENUMS.LEFT_CLICK_ACTIONS.LAUNCH_GAME return elseif STATE.LEFT_CLICK_ACTION == ENUMS.LEFT_CLICK_ACTIONS.HIDE_GAME ToggleHideGames() elseif STATE.LEFT_CLICK_ACTION == ENUMS.LEFT_CLICK_ACTIONS.REMOVE_GAME ToggleRemoveGames() COMPONENTS.LIBRARY\filter(ENUMS.FILTER_TYPES.HIDDEN, {state: true, stack: true, games: STATE.GAMES}) games = COMPONENTS.LIBRARY\get() if #games == 0 COMPONENTS.LIBRARY\filter(ENUMS.FILTER_TYPES.HIDDEN, {state: true}) games = COMPONENTS.LIBRARY\get() if #games == 0 return else STATE.GAMES = games STATE.SCROLL_INDEX = 1 updateSlots() else STATE.GAMES = games updateSlots() SKIN\Bang(('[!SetVariable "ContextTitleUnhideGameStatus" "%s"]')\format(LOCALIZATION\get('main_context_title_stop_unhiding_games', 'Stop unhiding games'))) STATE.LEFT_CLICK_ACTION = ENUMS.LEFT_CLICK_ACTIONS.UNHIDE_GAME ) COMPONENTS.STATUS\show(err, true) unless success export ToggleRemoveGames = () -> success, err = pcall( () -> if STATE.LEFT_CLICK_ACTION == ENUMS.LEFT_CLICK_ACTIONS.REMOVE_GAME SKIN\Bang(('[!SetVariable "ContextTitleRemoveGamesStatus" "%s"]')\format(LOCALIZATION\get('main_context_title_start_removing_games', 'Start removing games'))) STATE.LEFT_CLICK_ACTION = ENUMS.LEFT_CLICK_ACTIONS.LAUNCH_GAME return elseif STATE.LEFT_CLICK_ACTION == ENUMS.LEFT_CLICK_ACTIONS.HIDE_GAME ToggleHideGames() elseif STATE.LEFT_CLICK_ACTION == ENUMS.LEFT_CLICK_ACTIONS.UNHIDE_GAME ToggleUnhideGames() if #STATE.GAMES == 0 COMPONENTS.LIBRARY\filter(ENUMS.FILTER_TYPES.NONE) STATE.GAMES = COMPONENTS.LIBRARY\get() STATE.SCROLL_INDEX = 1 updateSlots() return if #STATE.GAMES == 0 SKIN\Bang(('[!SetVariable "ContextTitleRemoveGamesStatus" "%s"]')\format(LOCALIZATION\get('main_context_title_stop_removing_games', 'Stop removing games'))) STATE.LEFT_CLICK_ACTION = ENUMS.LEFT_CLICK_ACTIONS.REMOVE_GAME ) COMPONENTS.STATUS\show(err, true) unless success
35.788523
168
0.733052
66109c1186c4cd196e099053250515e76ebbe3c7
80
a = 'b' c = d (a b) c d import c from d (a b) c d (c d) a b a, b = c, d (d a) c
8.888889
15
0.4375
dceedff774f0dea982abced7a8c22848ee5f11ac
616
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) mode = howl.mode local lexers { comment_syntax: '//' auto_pairs: { '(': ')' '[': ']' '{': '}' '"': '"' "'": "'" } lexer: (text, buffer, opts) -> lexers or= bundle_load('php_lexer') lexer = opts and opts.sub_lexing and lexers.php if not lexer and buffer buf_start = buffer\sub 1, 30 if buf_start\match '^%s*<%?' lexer = lexers.php else lexer = lexers.embedded_php lexer or= lexers.embedded_php lexer text }
19.870968
79
0.582792
ff1c7cccffcedb0dd44d60172ab847ce3b6dc3cb
5,954
utils = require("utils") print(utils) import simpleIdGeneratorFactory, applyMeta, getMeta from utils idGenerator = simpleIdGeneratorFactory() DijkstraSearch = nil AstarSearch = nil class Path new: (nodes, cost) => @nodes = nodes @cost = cost getCost: () => @cost getNodes: () => @nodes Node, Edge = nil, nil AddPositionMeta = (node, vec) -> applyMeta(node, { position: vec }) GetPositionMeta = (node) -> return getMeta(node, "position") class Graph new: (nodes={}) => @nodes = nodes -- memoized paths @paths = {} @heurisitcsFunc = () -> 0 findPath: (start, goal, algo=DijkstraSearch, cache=true) => -- find the shortest path if cache and @paths[start\getId()] and @paths[start\getId()][goal\getId()] return @paths[start\getId()][goal\getId()] path = algo(start, goal, @nodes, @heurisitcsFunc) if not @paths[start\getId()] @paths[start\getId()] = {} if not @paths[goal\getId()] @paths[goal\getId()] = {} @paths[start\getId()][goal\getId()] = path @paths[goal\getId()][start\getId()] = Path(table.reverse(path\getNodes()), path\getCost()) return path addNodes: (nodes) => for i, v in ipairs(nodes) table.insert(@nodes, v) setHeuristicsFunction: (func) => @heurisitcsFunc = func getAllNodes: () => @nodes clone: () => nodes = {} edges = {} for i, v in ipairs(@nodes) node = v\clone() nodes[v\getId()] = node for j, edge in ipairs(v\getEdges()) nedge = edge\clone() if not edges[nedge] edges[nedge] = {} connections = edge\getNodes() table.insert(edges[nedge], [n for _, n in ipairs(connections)]) for i, v in ipairs(edges) n1 = nodes[v[1]] n2 = nodes[v[2]] i\connect(n1, n2) return Graph(nodes) class Edge new: (weight) => @weight = weight @connected = false @nodes = {} @id = idGenerator() connect: (n1, n2) => if not @connected n1\addEdge(@) n2\addEdge(@) table.insert(@nodes, n1) table.insert(@nodes, n2) @connected = true getWeight: () => @weight getNodes: () => @nodes getId: () => @id clone: () => return Edge(@weight) class Node new: (weight) => @weight = weight @edges = {} @id = idGenerator() getWeight: () => @weight addEdge: (edge) => table.insert(@edges, edge) getEdges: () => @edges setWeight: (weight) => @weight = weight addWeight: (weight) => @weight += weight getNeighbors: () => nodes = {} for edge in *@edges enodes = edge\getNodes() for node in *enodes if node\getId() ~= @getId() nodes[node] = edge\getWeight() + node\getWeight() return nodes getId: () => @id clone: () => return Node(@weight) DijkstraSearch = (start, goal, nodes) -> if start\getId() == goal\getId() return Path({start}, 0) visitedNodes = {} distances = {node, math.huge for node in *nodes} distances[start] = 0 path = {} queue = {start} while #queue > 0 mdist = math.huge currentNode = nil currentIndex = 1 for i, node in ipairs(queue) if distances[node] < mdist mdist = distances[node] currentIndex = i currentNode = table.remove(queue, currentIndex) if currentNode == goal break for neighbor, cost in pairs(currentNode\getNeighbors()) if not visitedNodes[neighbor] tcost = distances[currentNode] + cost if tcost < distances[neighbor] distances[neighbor] = tcost path[neighbor] = currentNode table.insert(queue, neighbor) visitedNodes[currentNode] = true finalPath = {} u = goal if path[u] while u table.insert(finalPath, u) u = path[u] return Path(table.reverse(finalPath), distances[goal]) -- todo implement heurisitc cost estimate AstarSearch = (start, goal, nodes, heurisitcsFunc) -> closedSet = {} openMap = {[start]: true} openSet = {start} path = {} gScore = {node, math.huge for node in *nodes} gScore[start] = 0 fScore = {node, math.huge for node in *nodes} fScore[start] = heurisitcsFunc(start, goal) while #openSet > 0 currentIndex = 1 minf = math.huge for i, node in ipairs(openSet) if fScore[node] <= minf minf = fScore[node] currentIndex = i currentNode = table.remove(openSet, currentIndex) closedSet[currentNode] = true openMap[currentNode] = nil -- TODO: FIX for neighbor, cost in pairs(currentNode\getNeighbors()) if not closedSet[neighbor] tgScore = gScore[currentNode] + cost if not openMap[neighbor] openMap[neighbor] = true table.insert(openSet, neighbor) else if tgScore >= gScore[neighbor] continue path[neighbor] = currentNode gScore[neighbor] = tgScore fScore[neighbor] = gScore[neighbor] + heurisitcsFunc(neighbor, goal) finalPath = {} u = goal if path[u] while u table.insert(finalPath, u) u = path[u] return Path(table.reverse(finalPath), gScore[goal]) createDistanceHeuristics = (nodeMap) -> distanceMap = {} for node, pos in pairs(nodeMap) distanceMap[node] = {} for node2, pos2 in pairs(nodeMap) dist = Distance2D(pos, pos2) distanceMap[node][node2] = dist return (a, b) -> return distanceMap[a][b] return { :Graph, :Node, :Edge, :DijkstraSearch, :AstarSearch, :createDistanceHeuristics, :AddPositionMeta, :GetPositionMeta }
21.729927
95
0.561135
6a7a4b324880642c0e0ec17ff60b7ad808c76d17
1,597
-- This is the base class for all pieces, contains most common functions -- -- Every piece has some variables - 'player_id' (either 0 or 1), -- the position (0-based), 'is_royal' boolean value, shows if the piece -- is critical and shouldn't be eaten no way (as the King in vanilla chess) -- the path to image, built as 'assets/'..image..'.png' if provided -- -- To create a new piece type you should extend this class, like: -- export class Pawn extends Piece ... -- Look at examples in this folder around -- -- You can copy the "dummy.moon" file and write your own piece logic export class Piece -- Each piece has its own global and local values @is_royal: false @image: "" new: => @player_id = 0 @pos = {0, 0} -- Setters set_pos: (pos_x, pos_y) => @pos = {pos_x, pos_y} set_player_id: (id) => @player_id = id set_piece_class: (piece_class) => @__class = piece_class -- Change the piece class - like if it was -- a pawn which went to the border -- Getters get_pos: => @pos get_player_id: => @player_id is_royal: => @is_royal get_image: (image) => @image get_name: => -- Returns the class name as a string @__class.__name get_class: => -- Returns a pointer to the class table @__class -- The functions to be overriden in child classes get_possible_moves: (board) => -- 'board' represented as a table, -- containing all pieces -- Return nothing
28.517857
75
0.596744
f5f886c369f38be1f55e92e5649805448eceae62
672
verifyOwner = (src) -> for _,mask in pairs(ivar2.config.owners) if src.mask\match(mask) return true verifyChannelOwner = (src, destination) -> channel = ivar2.config.channels[destination] if type(channel) == 'table' and type(channel.owners) == 'table' for _,mask in pairs(channel.owners) if src.mask\match(mask) return true JOIN: { (source, destination, arg) => if verifyOwner source @Log 'info', 'Automatically OPing owner' @Mode destination, "+o #{source.nick}" elseif verifyChannelOwner source, destination @Log 'info', 'Automatically OPing channel owner' @Mode destination, "+o #{source.nick}" }
28
65
0.662202
2d6300afbac134166623e9cce5c475950a6f9136
612
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import app, interact from howl class ReadText run: (@finish, opts = {}) => with app.window.command_line .prompt = opts.prompt or '' .title = opts.title @opts = moon.copy opts keymap: enter: => self.finish app.window.command_line.text escape: => self.finish! handle_back: => if @opts.cancel_on_back self.finish back: true interact.register name: 'read_text' description: 'Read free form text entered by user' factory: ReadText
21.857143
79
0.676471
7ba9f7b6d2e94596fc762b9e9742f763210f95fd
4,353
-- Copyright 2019 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) {:ListWidget, :List} = howl.ui {:Matcher} = howl.util class ConsoleView new: (@console) => init: (@command_line, opts={}) => @list = List nil, never_shrink: true, on_selection_change: (selection) -> @list_widget = ListWidget @list if opts.max_height @list_widget.max_height_request = opts.max_height @command_line\add_widget 'completer', @list_widget @list_widget\hide! on_text_changed: => if @history_showing -- filter history @list\update @command_line.text else -- refresh command list @_refresh! keymap: enter: => if @history_showing -- we only set the command line text @history_showing = false @_hide_list! item = @list.selection if item.text @command_line.text = item.text elseif type(item) == 'table' @command_line.text = tostring item[1] else @command_line.text = tostring item return local status, response if @list_widget.showing status, response = pcall -> @console\select @command_line.text, @list.selection, @completion_opts else status, response = pcall -> @console\run @command_line.text if status @_hide_list! return if @_handle_response response else @_handle_error response escape: => if @history_showing -- just close list and cancel history_showing @_hide_list! @history_showing = false return if @list_widget.showing @_hide_list! else @command_line\finish! backspace: => return false unless @command_line.text.is_empty and @console.back status, response = pcall -> @console\back! if status if response return if @_handle_response response else @_refresh! else @_handle_error response tab: => if not @list_widget.showing and @completion_opts @_show_completions! binding_for: ['cursor-up']: => if @list_widget.showing @list\select_prev! else @_show_history! ['cursor-down']: => @list\select_next! if @list_widget.showing ['cursor-page-up']: => @list\prev_page! if @list_widget.showing ['cursor-page-down']: => @list\next_page! if @list_widget.showing _refresh: => with @command_line.notification \clear! \hide! text = @command_line.text -- update title and prompt if @console.display_title @command_line.title = @console\display_title! else @command_line.title = nil @command_line.prompt = @console\display_prompt! -- handle parsing, if available if @console.parse status, response = pcall -> @console\parse text if status if response if @_handle_response response return else @_handle_error response -- show completions, if available @completion_opts = @console.complete and @console\complete text if @completion_opts if @list_widget.showing or @completion_opts.auto_show @_show_completions @completion_opts else @_hide_list! else @_hide_list! _show_completions: => @list_widget\show! @list.matcher = Matcher @completion_opts.completions @list.reverse = false if @completion_opts.columns @list.columns = @completion_opts.columns @list\update @completion_opts.match_text _show_history: => if @console.get_history history_items = @console\get_history! return unless history_items @list_widget\show! @list.matcher = Matcher history_items, preserve_order: true @list.reverse = true @list\update '' @history_showing = true _hide_list: => @list_widget\hide! _handle_response: (r) => if r.text @command_line.text = r.text @_refresh! if r.error @_handle_error r.error if r.result @command_line\finish r.result return true if r.cancel @command_line\finish! return true _handle_error: (msg) => log.error msg @command_line.notification\error msg @command_line.notification\show!
25.017241
105
0.628992
24bff3ca1e78aa7998602a362c649b7266116b7e
43
handle("/", -> print "Hello, Moonscript!")
21.5
42
0.604651
4c09fa91200ed39a5243400d226958e677a29444
4,316
export ^ helper = require("helper") class GridView new: (@grid, @w, @h) => @cellBaseSize = 20 @offsetX = 0 @offsetY = 0 @offset_speed = 100 @scale = 1 -- final cell size will be @cellBaseSize * @scale pixels @scaleMax = 10 @scaleMin = 0.5 @run_aliveColor = {178, 34, 34} -- aka 'firebrick' @run_deadColor = {255, 215, 0} -- aka 'gold 1' @run_gridColor = {218, 165, 32} -- aka 'goldenrod' @pause_aliveColor = {139, 26, 26} -- aka 'firebrick 4' @pause_deadColor = {70, 130, 80} -- aka 'steelblue' @pause_gridColor = {176,196,222} -- aka 'lightsteelblue' @gridWidth = 1 cellSize: => @cellBaseSize * @scale aliveColor: => @run_aliveColor if @grid.running else @pause_aliveColor deadColor: => @run_deadColor if @grid.running else @pause_deadColor gridColor: => @run_gridColor if @grid.running else @pause_gridColor setScale: (str) => switch str when "up" @scale += 0.1 when "down" @scale -= 0.1 else @scale = tonumber str @scale = math.min(@scale, @scaleMax) @scale = math.max(@scale, @scaleMin) update: (dt) => if love.keyboard.isDown "right" @offsetX -= @offset_speed * dt if love.keyboard.isDown "left" @offsetX += @offset_speed * dt if love.keyboard.isDown "down" @offsetY -= @offset_speed * dt if love.keyboard.isDown "up" @offsetY += @offset_speed * dt @cleanOffsetValues! draw: => @drawBackground! @drawCells! @drawLines! drawBackground: => w = love.graphics.getWidth! h = love.graphics.getHeight! love.graphics.setColor @deadColor() love.graphics.rectangle "fill", 0, 0, w, h drawCells: => love.graphics.push! love.graphics.translate @offsetX, @offsetY top_left_x, top_left_y = @translateCoord 0, 0 numCol = @w / @cellSize! + 1 numRow = @h / @cellSize! + 1 for i = top_left_x, top_left_x + numCol for j = top_left_y, top_left_y + numRow cell_i = helper.modulo_lua(i, @grid.size) cell_j = helper.modulo_lua(j, @grid.size) cell_grid_offset_x = math.floor((i - 1) / @grid.size) cell_grid_offset_y = math.floor((j - 1) / @grid.size) @drawCell cell_i, cell_j, cell_grid_offset_x, cell_grid_offset_y @drawCell 2, 2, 0, 0 love.graphics.pop! drawLines: => love.graphics.setColor @gridColor() love.graphics.setLineWidth @gridWidth * @scale oX = @offsetX % @cellSize! oY = @offsetY % @cellSize! vertCnt = math.ceil wScr! / @cellSize! for i=1, vertCnt lineX = (i - 1) * @cellSize! + oX love.graphics.line lineX, 0, lineX, hScr! horizCnt = math.ceil hScr! / @cellSize! for i=1, horizCnt lineY = (i - 1) * @cellSize! + oY love.graphics.line 0, lineY, wScr!, lineY drawCell: (i, j, grid_offX = 0, grid_offY = 0) => -- offset indicate that the cell is seen in 'another' iteration -- of the grid because of the infinite looping @grid\checkCoordinates i, j cell_x = (i - 1 + grid_offX * @grid.size) * @cellSize! cell_y = (j - 1 + grid_offY * @grid.size) * @cellSize! if @grid\is_alive i, j love.graphics.setColor @aliveColor() love.graphics.rectangle "fill", cell_x, cell_y, @cellSize!, @cellSize! love.graphics.setColor {0, 0, 0} cleanOffsetValues: => @offsetX %= @grid.size * @cellSize! @offsetY %= @grid.size * @cellSize! translateCoord: (x, y, inGrid=false) => -- translate x,y coordinates in the window into cell coordinates -- if inGrid : always returns a coordinate in the grid (using modulos) i = math.floor((x - @offsetX) / @cellSize!) + 1 j = math.floor((y - @offsetY) / @cellSize!) + 1 if inGrid i = helper.modulo_lua i, @grid.size j = helper.modulo_lua j, @grid.size return i, j
34.253968
80
0.549815
f77652a2e618dd8e1dd93efe934fe77c83d27b99
1,570
M = {} import escape_pattern from require "lapis.util" M.log = (msg) -> ngx.log ngx.NOTICE, inspect(msg) M.log_err = (msg) -> ngx.log ngx.ERR, inspect(msg) M.split = (str, delim using nil) -> str ..= delim [part for part in str\gmatch "(.-)" .. escape_pattern delim] M.strip = (str, pattern = '%s') -> sub = "^" .. pattern .. "*(.-)" .. pattern .. "*$" return string.gsub(str, sub, "%1") M.trim = (str) -> return M.strip(str, '%s') M.replace = (str, what, sub) -> what = string.gsub(what, "[%(%)%.%+%-%*%?%[%]%^%$%%]", "%%%1") -- escape pattern sub = string.gsub(sub, "[%%]", "%%%%") -- escape replacement return string.gsub(str, what, sub) M.set = (list) -> set = {} for _, l in ipairs(list) do set[l] = true return set -- define response function M.response = (t) -> -- close redis connection redis.finish(t['redis']) if t['redis'] -- setup defaults response = status: 500, json: { message: "Unknown failure" } response['status'] = t['status'] if t['status'] response['json']['message'] = t['msg'] if t['msg'] response['json']['data'] = t['data'] if t['data'] -- if a msg wasn't given and the status code is successful (ie 200's), assume msg is "OK" response['json']['message'] = "OK" if t['msg'] == nil and response['status'] < 300 response['json']['message'] = "Entry does not exist" if t['msg'] == nil and response['status'] == 404 -- log if theres a failure library.log_err(response) if response['status'] >= 300 return response return M
29.074074
105
0.568153
c6f9cceb3dfa5526c51b5cb0939575514e506730
414
-- Copyright 2013-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) class YAMLMode new: => @lexer = bundle_load('yaml_lexer') default_config: use_tabs: false comment_syntax: '#' indentation: { more_after: { ':%s*$', '[>|]%s*$' } } auto_pairs: { '(': ')' '[': ']' '{': '}' '"': '"' "'": "'" }
15.333333
79
0.509662
67201a2aed1f2caf878e9fb5abc2d1a0ce4d489b
439
-- vim: ts=2 sw=2 et : -- Place for random code experiment. moon=require("moon") p=moon.p f = => _f = (last) => if last==@ then return else last+1 _f, @, 0 print x for x in f 10 csv = (f) -> stream = io.input(f) => if s = io.read() [tonumber(x) or x for x in s\gsub("([\t\r ]*|--.*)","")\gmatch("([^,]+)")] else io.close(stream) and nil print(#x) for x in csv "it.moon" when #x>0 23,18,20,11,22 --asdas
17.56
80
0.530752
92a1ea9a58ebf70e3d4382b3120524f780786634
321
mode_reg = name: 'markdown' extensions: {'md', 'markdown'} create: -> bundle_load('markdown_mode') howl.mode.register mode_reg unload = -> howl.mode.unregister 'markdown' return { info: author: 'Copyright 2013-2015 The Howl Developers', description: 'Markdown support', license: 'MIT', :unload }
18.882353
54
0.679128
1c1fdf162fbc49090a3eaad122c2a500d065e97e
14,012
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import TaskRunner from howl.util import app, command, interact from howl import highlight, markup, NotificationWidget from howl.ui append = table.insert highlight.define_default 'replace_strikeout', { type: highlight.SANDWICH, color: '#f0f0f0' } parse_replacement = (text, marker) -> target, replacement = text\match("([^#{marker}]+)#{marker}(.*)") if target return target, replacement return text default_find = (buffer, target, init) -> init = buffer\byte_offset init text = buffer.text -> start_pos, end_pos = text\find target, init, true if not start_pos return init = end_pos + 1 return { start_pos: buffer\char_offset(start_pos), end_pos: buffer\char_offset(end_pos) } class Replacement run: (@finish, opts={}) => @command_line = app.window.command_line with opts.editor @text = .buffer.text @line_at_top = .line_at_top @orig_cursor_pos = .cursor.pos -- @preview_buffer holds replaced text @preview_buffer = app\new_buffer opts.editor.buffer.mode @preview_buffer.title = opts.preview_title or 'Preview Replacements' @preview_buffer.text = @text @preview_buffer.data.is_preview = true -- @buffer always holds original text @buffer = howl.Buffer! @buffer.collect_revisions = false @buffer.text = @text @start_pos = opts.editor.active_chunk.start_pos or 1 @end_pos = opts.editor.active_chunk.end_pos or @buffer.length @runner = TaskRunner! self.find = opts.find or default_find self.replace = opts.replace or (match, replacement) -> replacement self.replacer_help = opts.help @command_line.title = opts.title or 'Replace' @orig_buffer = app.editor.buffer app.editor.buffer = @preview_buffer app.editor.line_at_top = @line_at_top @caption_widget = NotificationWidget! @command_line\add_widget 'caption_widget', @caption_widget @selected_idx = nil @num_matches = 0 @num_replacements = 0 @matches = {} @replacements = {} @replacements_applied = {} @strikeouts = {} @excluded = {} @num_excluded = 0 @adjusted_positions = {} replace_command = (opts.replace_command or '') .. (@command_line\pop_spillover! or '') if replace_command.is_empty replace_command = '/' @command_line\write replace_command @on_update replace_command _restore_return: (result) => @runner\cancel_all! app.editor.buffer = @orig_buffer app\close_buffer @preview_buffer, true self.finish result true on_update: (text) => return if not text or text.is_empty marker = text[1] target, replacement = parse_replacement text\usub(2), marker refresh_matches = (target != @target) or (@replacement and not replacement) refresh_replacement = refresh_matches or (replacement != @replacement) @target = target @replacement = replacement if refresh_matches @_reload_matches! if refresh_replacement @_reload_replacements! _reload_matches: => @runner\cancel_all! @runner\run 'reload-matches', (yield) -> if @num_replacements > 0 @preview_buffer.text = @text app.editor.line_at_top = @line_at_top @matches = {} @num_matches = 0 @replacements = {} @num_replacements = 0 @replacements_applied = {} @adjusted_positions = {} @excluded = {} @selected_idx = nil preview_start = 1 if @target and not @target.is_empty batch_start = @start_pos find = self.find for found_match in find @buffer, @target, @start_pos, @end_pos if found_match.end_pos > @end_pos break append @matches, found_match @num_matches += 1 if (not @selected_idx) and (found_match.start_pos >= @orig_cursor_pos) @selected_idx = @num_matches if found_match.start_pos - batch_start > 64 * 1024 batch_start = found_match.start_pos @_preview_replacements preview_start @_update_caption false, true preview_start = @num_matches + 1 if yield! return if not @selected_idx and @num_matches > 0 @selected_idx = 1 @_preview_replacements preview_start @_update_caption! _reload_replacements: => @runner\cancel 'submit' @runner\cancel 'reload-replacements' @runner\run 'reload-replacements', (yield) -> @replacements = {} @num_replacements = 0 return unless @replacement batch_start = @start_pos preview_start = 1 replace = self.replace replacement = @replacement for found_match in *@matches append @replacements, replace found_match, replacement @num_replacements += 1 if found_match.start_pos - batch_start > 64 * 1024 batch_start = found_match.start_pos @_preview_replacements preview_start @_update_caption true, false preview_start = @num_replacements + 1 if yield! return @_preview_replacements preview_start @_update_caption! _update_caption: (match_finished=true, replace_finished=true) => morem = match_finished and '' or '+' morer = replace_finished and '' or '+' local msg if @num_replacements == 0 and @num_excluded == 0 msg = "Found #{@num_matches}#{morem} matches." else numr = math.max(0, @num_replacements - @num_excluded) msg = "Replacing #{numr}#{morer} of #{@num_matches}#{morem} matches." @caption_widget\notify 'comment', msg _preview_replacements: (start_idx=1, strikeout_removals=true) => adjust = 0 if @adjusted_positions[start_idx] and @matches[start_idx] adjust = @adjusted_positions[start_idx] - @matches[start_idx].start_pos matches = @matches replacements = @replacements pending = {} for i = start_idx, @num_matches match = matches[i] match_len = match.end_pos - match.start_pos + 1 replacement = replacements[i] currently_applied = @replacements_applied[i] preview_pos = @adjusted_positions[i] @adjusted_positions[i] = match.start_pos + adjust if not replacement or @excluded[i] if currently_applied append pending, first: preview_pos last: preview_pos + currently_applied.ulen - 1 text: @buffer\chunk(match.start_pos, match.end_pos).text @replacements_applied[i] = nil @strikeouts[i] = nil else if currently_applied != replacement len = currently_applied and currently_applied.ulen or match_len if replacement.is_empty and strikeout_removals replacement = @buffer\chunk(match.start_pos, match.end_pos).text @strikeouts[i] = true else @strikeouts[i] = nil append pending, first: preview_pos last: preview_pos + len - 1 text: replacement @replacements_applied[i] = replacement adjust += replacement.ulen - match_len if #pending > 0 first = pending[1].first last = pending[#pending].last substituted = {} for i, p in ipairs pending nextp = pending[i+1] append substituted, p.text if nextp append substituted, @preview_buffer\sub p.last + 1, nextp.first - 1 app.editor\with_position_restored -> @preview_buffer\chunk(first, last).text = table.concat substituted @_preview_highlights! _preview_highlights: => if @matches[@selected_idx] app.editor\ensure_visible @adjusted_positions[@selected_idx] or @matches[@selected_idx].start_pos else app.editor.line_at_top = @line_at_top first_visible = @preview_buffer.lines[math.max(1, app.editor.line_at_top - 5)].start_pos last_visible = @preview_buffer.lines[math.min(#@preview_buffer.lines, app.editor.line_at_bottom + 10)].end_pos @_clear_highlights! return unless @num_matches > 0 -- skip until visible section local visible_start for i = 1, @num_matches match = @matches[i] preview_position = @adjusted_positions[i] or match.start_pos if preview_position >= first_visible visible_start = i break -- highlight visible section only return unless visible_start for i = visible_start, @num_matches match = @matches[i] preview_position = @adjusted_positions[i] or match.start_pos if preview_position > last_visible break hlt = @selected_idx == i and 'search' or 'search_secondary' len = @replacements_applied[i] and @replacements_applied[i].ulen or match.end_pos - match.start_pos + 1 if @strikeouts[i] @_highlight_match 'replace_strikeout', preview_position, len else @_highlight_match hlt, preview_position, len _clear_highlights: (start_idx=1) => highlight.remove_all 'search', @preview_buffer highlight.remove_all 'search_secondary', @preview_buffer highlight.remove_all 'replace_strikeout', @preview_buffer _highlight_match: (name, pos, len) => highlight.apply name, @preview_buffer, pos, len _toggle_current: => newval = not @excluded[@selected_idx] @excluded[@selected_idx] = newval @num_excluded += newval and 1 or -1 @_preview_replacements @selected_idx @_update_caption! _switch_to: (cmd) => captured_text = @command_line.text @command_line\run_after_finish -> app.editor.selection\select @start_pos, @end_pos command.run cmd .. ' ' .. captured_text @_restore_return! keymap: escape: => @_restore_return! alt_enter: => @_toggle_current! enter: => @runner\run 'submit', -> cursor_pos = @selected_idx and @matches[@selected_idx] and @matches[@selected_idx].start_pos result = num_replaced: @num_replacements - @num_excluded target: @target replacement: @replacement line_at_top: app.editor.line_at_top :cursor_pos if result.num_replaced > 0 @_preview_replacements 1, false result.text = @preview_buffer.text @_restore_return result ctrl_r: => @_switch_to 'buffer-replace-regex' binding_for: ["cursor-down"]: => return unless (@num_matches > 0) and @selected_idx if @selected_idx == @num_matches @selected_idx = 1 else @selected_idx += 1 @_preview_highlights! ["cursor-up"]: => return unless (@num_matches > 0) and @selected_idx if @selected_idx == 1 @selected_idx = @num_matches else @selected_idx -= 1 @_preview_highlights! ['editor-scroll-up']: -> app.editor\scroll_up! ['editor-scroll-down']: -> app.editor\scroll_down! ['buffer-replace']: => @_switch_to 'buffer-replace' ['buffer-replace-regex']: => @_switch_to 'buffer-replace-regex' help: => help = { { heading: "Syntax '/match/replacement'" text: markup.howl "Replaces occurences of <string>'match'</> with <string>'replacement'</>. If match text contains <string>'/'</>, a different separator can be specified by replacing the first character with the desired separator." } { key: 'up' action: 'Select previous match' } { key: 'down' action: 'Select next match' } { key: 'alt_enter' action: 'Toggle replacement for currently selected match' } { key: 'ctrl_r' action: 'Switch to buffer-replace-regex' } { key_for: 'buffer-replace' action: 'Switch to buffer-replace' } { key: 'enter' action: 'Apply replacements' } } if @replacer_help for item in *@replacer_help append help, item return help interact.register name: 'get_replacement' description: 'Return text with user specified replacements applied' factory: Replacement interact.register name: 'get_replacement_regex' description: 'Return text with user specified regex based replacements applied' handler: (opts) -> opts = moon.copy opts with opts .find = (buffer, target, start_pos=1, end_pos=buffer.length) -> ok, rex = pcall -> r('()' .. target .. '()') if not target or target.is_blank or not ok return -> line = buffer.lines\at_pos start_pos offset = start_pos - line.start_pos text = line.text\usub offset + 1 if line.end_pos > end_pos text = text\usub 1, end_pos - line.end_pos matcher = rex\gmatch text return -> while line result = table.pack matcher! if #result> 0 captures = {} for i=1, result.n - 2 append captures, result[i+1] return { start_pos: line.start_pos + offset + result[1] - 1 end_pos: line.start_pos + offset + result[result.n] - 2 :captures } else line = line.next return unless line text = line.text if line.end_pos > end_pos text = text\usub 1, end_pos - line.end_pos matcher = rex\gmatch text offset = 0 .replace = (match, replacement) -> if replacement result = replacement\gsub '(\\%d+)', (ref) -> ref_idx = tonumber(ref\sub(2)) if ref_idx > 0 return match.captures[ref_idx] or '' return '' return result .help = { { text: markup.howl "Here <string>'match'</> is a PCRE regular expression and <string>'replacement'</> is text which may contain backreferences such as <string>'\\1'</string>" } } interact.get_replacement opts
30.660832
115
0.633457
5ddb05a723416d80b0c71c5416a654f8effa7232
34
require "lapis.db.model.relations"
34
34
0.823529
caa10c430df58c5e68b6cbdc9dcc7500fe6b60ac
511
describe "build", -> build = require('shipwright').build before_each -> vim = {} _G.vim = mock(vim) it "propagates load errors", -> assert.errors(-> build("fake_file")) assert.errors(-> build("spec/build/malformed_build_file.lua")) it "runs a build file with an injected context", -> -- build_file.lua also performs work, checking that a prescribed set of -- functions are availible inside it. assert.no.errors(-> build("spec/build/build_file.lua"))
26.894737
75
0.639922
3363e7c83e5f1b0532361a311add007980d4812f
574
import Widget from require "lapis.html" class IndexView extends Widget content: => h1 -> text "Welcome to this basic Luminary example and Lapis #{require "lapis.version"}!" color,msg = if @is_valid_env "#00FF00", "Looks like you're in the 'development' environment! You should see the Luminary toggle button attached to the right of this window." else "#FF0000", "Luminary is disabled outside of the 'development' environment. The Luminary toggle button shouldn't be shown here." h3 style: "color:#{color};", -> text msg
33.764706
152
0.686411
3c8d583c8d663bad904782108ceff5c759ac710c
1,361
-- Implementation of the AS3 Point. The API interface was used for function -- names, but the code is original work. class Point new: (x = 0, y = 0) => -- Add the clone mixin clone = require "LunoPunk.utils.mixins.clone" clone @ @x, @y = x, y -- The length of the line from (0, 0) to the point length: => math.sqrt @x^2 + @y^2 -- Add two points together add: (p) => Point @x + p.x, @y + p.y __add: (p) => @add p -- Copies point data from p to this Point copyFrom: (p) => @x, @y = p.x, p.y -- The distance between two points distance: (p1, p2) -> math.sqrt (p1.x - p2.x)^2 + (p1.y - p2.y)^2 -- determine if two points are equal equals: (p) => @x == p.x and @y == p.y -- determines a point between two points -- TODO -- interpolate: (p1, p2) => -- scales the line between (0,0) and current point to a set length normalize: (length) => l = @length! return if l == 0 @x = length * @x / l @y = length * @y / l -- offsets the point by an amount offset: (dx, dy) => @x += dx @y += dy -- Converts polar coordinates to a new point -- TODO -- polar: (length, angle) -> -- set the point to a new value set: (x, y) => @x, @y = x, y -- Subtracts p from this point to create a new Point subtract: (p) => Point @x - p.x, @y - p.y toString: => string.format "(%f, %f)", @x, @y __tostring: => @toString! { :Point }
23.465517
75
0.587068
dc20491fed74e310418c2a5deba738936f5da192
12,819
-- The 'shortest_path' and 'string_pull' functions are based on C++ code from the Godot Engine. -- Original copyright reported below: --------------------------------------------------------------------------- -- navigation_2d.cpp -- --------------------------------------------------------------------------- -- This file is part of: -- -- GODOT ENGINE -- -- https://godotengine.org -- --------------------------------------------------------------------------- -- Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. -- -- Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). -- -- -- -- Permission is hereby granted, free of charge, to any person obtaining -- -- a copy of this software and associated documentation files (the -- -- "Software"), to deal in the Software without restriction, including -- -- without limitation the rights to use, copy, modify, merge, publish, -- -- distribute, sublicense, and/or sell copies of the Software, and to -- -- permit persons to whom the Software is furnished to do so, subject to -- -- the following conditions: -- -- -- -- The above copyright notice and this permission notice shall be -- -- included in all copies or substantial portions of the Software. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.-- -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- --------------------------------------------------------------------------- path = (...)\gsub("[^%.]*$", "") M = require(path .. 'master') import CyclicList, Set, SymmetricMatrix, Vec2 from M import wedge from Vec2 import round from M.math geometry = require(path .. 'geometry') import bounding_box, centroid, closest_edge_point, is_point_in_triangle from geometry local * ConvexPolygon = M.class { __init: (vertices, name, hidden) => -- vertices is a list of Vec2 assert(#vertices > 2, "A polygon must have a least 3 points.", 2) @vertices = CyclicList(vertices) @name = name @hidden = hidden @n = #vertices @min, @max = bounding_box(vertices) @centroid = centroid(vertices) @connections = [false for i = 1, @n] len: => @n ipairs: => ipairs(@vertices.items) __index: (key) => @vertices[key] get_edge: (i) => @vertices[i], @vertices[i + 1] get_connection: (i) => -- if edge i is connected to another polygon return the polygon + edge_idx it is connected to. c = @connections[i] if c and not c.polygon.hidden return c.polygon, c.edge is_point_inside: (P) => unless P.x < @min.x or P.y < @min.y or P.x > @max.x or P.y > @max.y for i = 2, @n - 1 if is_point_in_triangle(P, @vertices[1], @vertices[i], @vertices[i + 1]) then return true return false is_point_inside_connected: (P, visited={}) => visited[self] = true if @is_point_inside(P) return self for t in *@connections if t and not t.polygon.hidden and not visited[t.polygon] if poly = t.polygon\is_point_inside_connected(P, visited) return poly return nil closest_edge_point: (P, edge_idx) => A, B = @get_edge(edge_idx) return closest_edge_point(P, A, B) closest_boundary_point_connected: (P, visited={}) => visited[self] = true local C, poly d = math.huge for i = 1, @n if not @connections[i] or @connections[i].polygon.hidden tmp_C = @closest_edge_point(P, i) tmp_d = (P - tmp_C)\lenS() if tmp_d < d d = tmp_d C = tmp_C poly = self else neighbour = @connections[i].polygon if not visited[neighbour] tmp_C, tmp_poly, tmp_d = neighbour\closest_boundary_point_connected(P, visited) if tmp_d < d d = tmp_d C = tmp_C poly = tmp_poly return C, poly, d } Navigation = M.class { __init: (pmaps={}) => -- pmaps is a table of lists of convex decompositions. Each convex decomposition is a list -- of convex polygons, represented by a list of pairs of coordinates. Each pmap can optionally have -- a "name" field (a string), which will be used to toggle the pmap visibility, and a "hidden" field -- (boolean) which will determine if it is initially visible. vertices, vertex_idxs, polygons, name_groups = {}, {n:0}, {}, {} for pmap in *pmaps name_group = pmap.name and {} name_groups[pmap.name] = name_group if pmap.name for poly in *pmap tmp = {} for v in *poly x, y = unpack(v) label = tostring(x) .. ';' .. tostring(y) if not vertices[label] v = Vec2(x, y) vertices[label] = v vertex_idxs.n += 1 vertex_idxs[v] = vertex_idxs.n tmp[#tmp + 1] = vertices[label] cp = ConvexPolygon(tmp, pmap.name, pmap.hidden) polygons[#polygons + 1] = cp name_group[#name_group + 1] = cp if name_group @polygons = polygons @vertex_idxs = vertex_idxs @name_groups = name_groups set_visibility: (name, bool) => for p in *(@name_groups[name] or {}) p.hidden = not bool toggle_visibility: (name) => for p in *(@name_groups[name] or {}) p.hidden = not p.hidden initialize: => @initialized = true edges_matrix = SymmetricMatrix(@vertex_idxs.n) for k, p in ipairs(@polygons) for i = 1, p.n A, B = p\get_edge(i) A_idx, B_idx = @vertex_idxs[A], @vertex_idxs[B] if not edges_matrix[A_idx][B_idx] edges_matrix[A_idx][B_idx] = {} t = edges_matrix[A_idx][B_idx] t[#t + 1] = {edge:i, polygon:p} for i = 1, @vertex_idxs.n for j = i + 1, @vertex_idxs.n if t = edges_matrix[i][j] A, B = unpack(t) A.polygon.connections[A.edge] = B or false B.polygon.connections[B.edge] = A if B _is_point_inside: (P) => @initialize() if not @initialized visited = {} for poly in *@polygons if not visited[poly] and not poly.hidden if p = poly\is_point_inside_connected(P, visited) then return p _closest_boundary_point: (P) => @initialize() if not @initialized d = math.huge local C, piece, poly for p in *@polygons unless p.hidden for i = 1, p.n if not p.connections[i] or p.connections[i].polygon.hidden tmp_C = p\closest_edge_point(P, i) tmp_d = (P - tmp_C)\lenS() if tmp_d < d d = tmp_d C = tmp_C poly = p return C, poly _shortest_path: (A, B) => @initialize() if not @initialized if @n == 0 return {} -- work with integer coordinates A, B = round(A), round(B) local node_A, node_B -- find piece and node cointaining A, or closest alternative node_A = @_is_point_inside(A) if not node_A A, node_A = @_closest_boundary_point(A) A = round(A) -- find node containing B, or closest alternative (only within nodes connected to 'node_A') node_B = node_A\is_point_inside_connected(B) if not node_B B, node_B = node_A\closest_boundary_point_connected(B) B = round(B) if node_A == node_B return {A, B} found_path = false for p in *@polygons p.prev_edge = nil polylist = Set() node_B.entry = B node_B.distance = 0 polylist\add(node_B) while not found_path if polylist\size() == 0 break local least_cost_poly least_cost = math.huge for p in polylist\iterator() cost = p ~= node_B and p.distance + (p.centroid - A)\len() or 0 if cost < least_cost least_cost_poly = p least_cost = cost p = least_cost_poly for i = 1, p.n q, c_edge = p\get_connection(i) if q entry = p\closest_edge_point(p.entry, i) distance = p.distance + (p.entry - entry)\len() if q.prev_edge if q.distance > distance q.prev_edge = c_edge q.distance = distance q.entry = entry else q.prev_edge = c_edge q.distance = distance q.entry = entry polylist\add(q) if q == node_A found = true break if found_path break polylist\remove(p) -- string pulling to optimise the path portals = {{A, A}} p = node_A while p ~= node_B and p.prev_edge C, D = p\get_edge(p.prev_edge) L, R = unpack(portals[#portals]) sign = orientation(C, L, D) sign = sign == 0 and orientation(C, R, D) or sign portals[#portals + 1] = sign > 0 and {C, D} or {D, C} p = p\get_connection(p.prev_edge) portals[#portals + 1] = {B, B} return string_pull(portals) is_point_inside: (x, y) => return not not @_is_point_inside(Vec2(x, y)) closest_boundary_point: (x, y) => P = @_closest_boundary_point(Vec2(x, y)) return P.x, P.y shortest_path: (x1, y1, x2, y2) => path = @_shortest_path(Vec2(x1, y1), Vec2(x2, y2)) return [{v.x, v.y} for v in *path] } M.Navigation = Navigation string_pull = (portals) -> portal_left, portal_right = unpack(portals[1]) l_idx, r_idx = 1, 1 apex = portal_left path = {apex} i = 1 while i < #portals i += 1 left, right = unpack(portals[i]) skip = false -- update right if orientation(portal_right, apex, right) <= 0 if apex == portal_right or orientation(portal_left, apex, right) > 0 -- tighten the funnel portal_right = right r_idx = i else if path[#path] ~= portal_left path[#path + 1] = portal_left apex = portal_left portal_right = apex r_idx = l_idx i = l_idx skip = true -- update left if not skip and orientation(portal_left, apex, left) >= 0 if apex == portal_left or orientation(portal_right, apex, left) < 0 -- tighten the funnel portal_left = left l_idx = i else if path[#path] ~= portal_right path[#path + 1] = portal_right apex = portal_right portal_left = apex l_idx = r_idx i = r_idx A = portals[#portals][1] if path[#path] ~= A or #path == 1 path[#path + 1] = A return path orientation = (L, P, R) -> -- positive if L is to the left of P and R is to the right wedge(R - P, L - P)
37.049133
108
0.490756
0d975544984cfabba1ac3169069f9744c8c1e725
543
-- Apply a function a list of values -- and return the results as a list TK = require "PackageToolkit" M = {} tail = (TK.module.import ..., '../_lists/_tail').tail head = (TK.module.import ..., '../_lists/_head').head append = (TK.module.import ..., '../_lists/_append').append M.map = (f, list) -> aux = (f, list, accum) -> if #list == 0 return accum else return aux f, (tail list), (append accum, (f (head list))) return {} if (type list) != "table" return aux f, list, {} return M
31.941176
70
0.563536
f2e84ec8eee8ecad3952f68987a460973f7cc5a7
9,310
-- Copyright 2016 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import app, command, dispatch from howl import theme from howl.ui import File from howl.io import get_cwd from howl.util.paths Gdk = require 'ljglibs.gdk' args = {...} unless #args >= 1 print 'Usage: screen-shooter <out-dir> [theme] [screenshot]' print ' theme - A specific theme, or "all" to generate a specific screenshot for all themes' print ' screenshot - A specific screenshot to generate' os.exit(1) out_dir = File.tmpdir! image_dir = File args[1] project_dir = out_dir\join('howl') examples_dir = out_dir\join('examples') source_project = get_cwd! howl.sys.env['HOME'] = out_dir.path File.home_dir = out_dir wait_for = (seconds) -> parking = dispatch.park 'wait' howl.timer.after seconds, -> dispatch.resume parking dispatch.wait parking wait_a_bit = -> wait_for 0.2 snapshot = (name, dir, opts) -> parking = dispatch.park 'shot' howl.timer.after (opts.wait_before or 0.5), -> pb = app.window\get_screenshot with_overlays: opts.with_overlays pb\save dir\join("#{name}.png").path, 'png', {} thumbnail = pb\scale_simple 314, 144, Gdk.INTERP_HYPER thumbnail\save dir\join("#{name}_tn.png").path, 'png', {} wait_for (opts.wait_after) or 0.5 app.window.command_line\abort_all! dispatch.resume parking opts.run! dispatch.wait parking for buffer in *app.buffers app\close_buffer buffer, true for _ = 1, #app.window.views - 1 command.view_close! log.info '' open_files = (filepaths) -> for path in *filepaths app\open_file project_dir\join(path) wait_a_bit! -- allow lexing screenshots = { { name: 'file-open' -> command.run "open #{project_dir}/re" } { name: 'completion-types' with_overlays: true -> app\open_file examples_dir / 'test.rb' app.editor.cursor\move_to line: 4, column: 7 command.editor_complete! } { name: 'project-open' -> app\open_file project_dir / 'lib/howl/application.moon' command.run 'project-open prsp' } { name: 'switch-buffer' -> open_files { 'lib/howl/application.moon' 'site/source/doc/index.haml' 'lib/howl/command.moon' } command.run 'switch-buffer' } { name: 'buffer-structure' -> open_files { 'lib/howl/regex.moon' } app.editor.cursor.line = 17 command.run 'buffer-structure' } { name: 'buffer-search-forward' -> open_files { 'lib/howl/ustring.moon' } app.editor.line_at_top = 137 app.editor.cursor.line = 140 command.run 'buffer-search-forward tex' } { name: 'buffer-grep' -> open_files { 'lib/howl/dispatch.moon' } dispatch.launch -> command.run 'buffer-grep resume' app.editor.line_at_top = 8 } { name: 'buffer-replace' -> open_files { 'lib/howl/application.moon' } with app.editor.searcher \forward_to 'showing' \commit! app.editor.line_at_top = math.max(app.editor.cursor.line - 2, 1) command.run 'buffer-replace /showing/' } { name: 'buffer-replace-regex' -> open_files { 'lib/howl/application.moon' } command.run 'buffer-replace-regex /\\w+\\s*=\\s*require(.+)/' } { name: 'buffer-modes' -> command.run 'buffer-mode' } { name: 'buffer-inspect' with_overlays: true -> app\open_file examples_dir / 'faulty.moon' app.editor.cursor\move_to line: 12 command.run 'buffer-inspect' command.run 'cursor-goto-inspection' } { name: 'clipboard' -> howl.clipboard.clear! howl.clipboard.push 'http://howl.io/' howl.clipboard.push 'howl.clipboard.push "text"' howl.clipboard.push 'abc def' wait_a_bit! command.run 'editor-paste..' } { name: 'show-doc' with_overlays: true -> open_files { 'lib/howl/application.moon' } app.editor.cursor.pos = app.editor.buffer\find('table.sort') + 6 app.editor.line_at_top = app.editor.cursor.line - 2 command.show_doc_at_cursor! } { name: 'multi-views' -> open_files { 'lib/howl/application.moon', 'lib/howl/bundle.moon', 'lib/howl/command.moon', } command.view_new_above! command.view_new_left_of! } { name: 'lots-of-views' wait_before: 2 -> open_files { 'lib/howl/application.moon', 'lib/howl/bundle.moon', 'lib/howl/command.moon', 'lib/howl/regex.moon', 'lib/howl/ustring.moon', 'lib/howl/chunk.moon', } app.editor.line_at_top = 4 command.view_new_right_of! app.editor.line_at_top = 10 command.view_new_below! wait_a_bit! app.editor.line_at_top = 10 command.view_new_right_of! wait_a_bit! app.editor.line_at_top = 10 command.view_new_below! wait_a_bit! app.editor.line_at_top = 10 wait_a_bit! } { name: 'exec-prompt' -> open_files { 'lib/howl/keymap.moon' } app.editor.line_at_top = 10 command.run 'exec ./' } { name: 'whole-word-search' -> open_files { 'lib/howl/ustring.moon' } pos = app.editor.buffer\find 'pattern' line = app.editor.buffer.lines\at_pos pos app.editor.cursor.pos = pos app.editor.line_at_top = line.nr command.run 'buffer-search-word-forward' } { name: 'concurrent-commands' wait_before: 3 wait_after: 1 -> open_files { 'lib/howl/application.moon' } command.exec project_dir, 'while true; do echo "foo"; sleep 1; done' command.exec source_project, './bin/howl-spec' command.run 'switch-buffer' } { name: 'commands' -> howl.interact.select_command title: 'Command', prompt: ':' } { name: 'configuration' -> command.run 'set' } { name: 'configuration-help' -> command.run 'set indent=' } { name: 'command-line-help' with_overlays: true -> open_files { 'lib/howl/application.moon' 'site/source/doc/index.haml' 'lib/howl/command.moon' } dispatch.launch -> command.run 'switch-buffer' app.window.command_line\show_help! } { name: 'project-file-search' wait_before: 3 wait_after: 1 -> open_files { 'lib/howl/ustring.moon' } pos = app.editor.buffer\find 'append' line = app.editor.buffer.lines\at_pos pos app.editor.cursor.pos = pos app.editor.line_at_top = line.nr command.run 'project-file-search' } } take_snapshots = (theme_name, to_dir, only) -> for _, def in ipairs screenshots if only and only != def.name continue if def.with_overlays and not only print " = #{def.name} (external).." out, err, p = howl.io.Process.execute "#{howl.sys.env.SNAPSHOT_CMD} '#{image_dir}' '#{theme_name}' '#{def.name}'" if not p.successful print ">> External snapshot failed!" print out if #out > 0 print err os.exit(p.exit_status) else print " = #{def.name}.." snapshot "#{def.name}", to_dir, { wait_before: def.wait_before, wait_after: def.wait_after, with_overlays: def.with_overlays, run: def[1] } get_theme = (name) -> for t_name in pairs theme.all if t_name\lower!\find name\lower! return t_name setup_example_files = -> example_files = { 'test.rb': 'class Foo attr_accessor :maardvark, :banana aa end ' 'faulty.moon': "mod = require 'mod' {:insert} = table first_func = (x) -> m = mod.foo 'x' oops_shadow = (mod) -> mod\\gmatch '.*(%w+).*' oops_shadow('mymod') " } examples_dir\mkdir_p! for filename, contents in pairs example_files file = examples_dir / filename file.contents = contents run = (theme_name, only) -> print "- Generating screenshots in '#{image_dir}' (tmp dir '#{out_dir}').." image_dir\mkdir_p! unless image_dir.is_directory print "- Setting up test project.." _, err, p = howl.io.Process.execute "git clone --shared '#{source_project}' '#{project_dir}'" unless p.successful error err print "- Setting up example files.." setup_example_files! local for_themes if theme_name and theme_name != 'all' for_themes = { get_theme theme_name } if #for_themes == 0 available_themes = table.concat [n for n in pairs theme.all], '\n' print "Unknown theme '#{theme_name}'\nAvailable themes:\n\n#{available_themes}" os.exit(1) else for_themes = [n for n in pairs theme.all] print "- Taking screenshots.." app.window\resize 1048, 480 for cur_theme in *for_themes howl.config.theme = cur_theme wait_a_bit! ss_dir = image_dir\join((cur_theme\lower!\gsub('%s', '-'))) ss_dir\mkdir_p! unless ss_dir.exists print " * #{cur_theme}.." take_snapshots cur_theme, ss_dir, only howl.signal.connect 'app-ready', -> log.info '' status, ret = pcall run, args[2], args[3] out_dir\rm_r! unless status print ret os.exit(1) log.info 'All done!' os.exit(0) howl.config.cursor_blink_interval = 0 howl.config.font_size = 10 app.args = {app.args[0]} app\run!
23.159204
119
0.622234
d55cfea959570f6f7a4a970eafbfd79d45607bf7
2,176
import NewExpr,NewExprVal,ExprIndex,ExprToString,AddItem from require "Data.API.Expression" for item in *{ { Name:"Plus" Text:"Plus +" Type:"Number" MultiLine:false TypeIgnore:false Group:"Operation" Desc:"Number [Number] + [Number]." CodeOnly:false ToCode:=> "( #{ @[2] } + #{ @[3] } )" Create:NewExpr "Number","Number" Args:false __index:ExprIndex __tostring:ExprToString } { Name:"Minus" Text:"Minus -" Type:"Number" MultiLine:false TypeIgnore:false Group:"Operation" Desc:"Number [Number] - [Number]." CodeOnly:false ToCode:=> "( #{ @[2] } - #{ @[3] } )" Create:NewExpr "Number","Number" Args:false __index:ExprIndex __tostring:ExprToString } { Name:"Multiply" Text:"Multiply *" Type:"Number" MultiLine:false TypeIgnore:false Group:"Operation" Desc:"Number [Number] * [Number]." CodeOnly:false ToCode:=> "( #{ @[2] } * #{ @[3] } )" Create:NewExpr "Number","Number" Args:false __index:ExprIndex __tostring:ExprToString } { Name:"Divide" Text:"Divide /" Type:"Number" MultiLine:false TypeIgnore:false Group:"Operation" Desc:"Number [Number] / [Number]." CodeOnly:false ToCode:=> "( #{ @[2] } / #{ @[3] } )" Create:NewExpr "Number","Number" Args:false __index:ExprIndex __tostring:ExprToString } { Name:"Power" Text:"Power ^" Type:"Number" MultiLine:false TypeIgnore:false Group:"Operation" Desc:"Number [Number] ^ [Number]." CodeOnly:false ToCode:=> "( #{ @[2] } ^ #{ @[3] } )" Create:NewExpr "Number","Number" Args:false __index:ExprIndex __tostring:ExprToString } { Name:"Module" Text:"Module %" Type:"Number" MultiLine:false TypeIgnore:false Group:"Operation" Desc:"Number [Number] % [Number]." CodeOnly:false ToCode:=> "( #{ @[2] } % #{ @[3] } )" Create:NewExpr "Number","Number" Args:false __index:ExprIndex __tostring:ExprToString } { Name:"Number" Text:"Number" Type:"Number" MultiLine:false TypeIgnore:false Group:"Number" Desc:"Raw number." CodeOnly:true ToCode:=> "#{ @[2] }" Create:NewExprVal 0 Args:false __index:ExprIndex __tostring:ExprToString } } AddItem item
19.603604
91
0.638327
b3905d39065326e36a6a83459ba5ffcf247a08b2
20,522
import Postgres from require "kpgmoon" unpack = table.unpack or unpack HOST = "127.0.0.1" USER = "postgres" DB = "pgmoon_test" describe "kpgmoon with server", -> for socket_type in *{"luasocket", "cqueues"} describe "socket(#{socket_type})", -> local pg setup -> os.execute "dropdb --if-exists -U '#{USER}' '#{DB}'" os.execute "createdb -U postgres '#{DB}'" pg = Postgres { database: DB user: USER host: HOST :socket_type } assert pg\connect! it "creates and drop table", -> res = assert pg\query [[ create table hello_world ( id serial not null, name text, count integer not null default 0, primary key (id) ) ]] assert.same true, res res = assert pg\query [[ drop table hello_world ]] assert.same true, res it "settimeout()", -> timeout_pg = Postgres { host: "10.0.0.1" :socket_type } timeout_pg\settimeout 1000 ok, err = timeout_pg\connect! assert.is_nil ok errors = { "timeout": true "Connection timed out": true } assert.true errors[err] it "tries to connect with SSL", -> -- we expect a server with ssl = off ssl_pg = Postgres { database: DB user: USER host: HOST ssl: true :socket_type } finally -> ssl_pg\disconnect! assert ssl_pg\connect! it "requires SSL", -> ssl_pg = Postgres { database: DB user: USER host: HOST ssl: true ssl_required: true :socket_type } status, err = ssl_pg\connect! assert.falsy status assert.same [[the server does not support SSL connections]], err describe "with table", -> before_each -> assert pg\query [[ create table hello_world ( id serial not null, name text, count integer not null default 0, flag boolean default TRUE, primary key (id) ) ]] after_each -> assert pg\query [[ drop table hello_world ]] it "inserts a row", -> res = assert pg\query [[ insert into "hello_world" ("name", "count") values ('hi', 100) ]] assert.same { affected_rows: 1 }, res it "inserts a row with return value", -> res = assert pg\query [[ insert into "hello_world" ("name", "count") values ('hi', 100) returning "id" ]] assert.same { affected_rows: 1 { id: 1 } }, res it "selects from empty table", -> res = assert pg\query [[select * from hello_world limit 2]] assert.same {}, res it "deletes nothing", -> res = assert pg\query [[delete from hello_world]] assert.same { affected_rows: 0 }, res it "update no rows", -> res = assert pg\query [[update "hello_world" SET "name" = 'blahblah']] assert.same { affected_rows: 0 }, res describe "with rows", -> before_each -> for i=1,10 assert pg\query [[ insert into "hello_world" ("name", "count") values (']] .. "thing_#{i}" .. [[', ]] .. i .. [[) ]] it "select some rows", -> res = assert pg\query [[ select * from hello_world ]] assert.same "table", type(res) assert.same 10, #res it "update rows", -> res = assert pg\query [[ update "hello_world" SET "name" = 'blahblah' ]] assert.same { affected_rows: 10 }, res assert.same "blahblah", unpack((pg\query "select name from hello_world limit 1")).name it "delete a row", -> res = assert pg\query [[ delete from "hello_world" where id = 1 ]] assert.same { affected_rows: 1 }, res assert.same nil, unpack((pg\query "select * from hello_world where id = 1")) or nil it "truncate table", -> res = assert pg\query "truncate hello_world" assert.same true, res it "make many select queries", -> for i=1,20 assert pg\query [[update "hello_world" SET "name" = 'blahblah' where id = ]] .. i assert pg\query [[ select * from hello_world ]] -- single call, multiple queries describe "multi-queries #multi", -> it "gets two results", -> res, num_queries = assert pg\query [[ select id, flag from hello_world order by id asc limit 2; select id, flag from hello_world order by id asc limit 2 offset 2; ]] assert.same 2, num_queries assert.same { { { id: 1, flag: true } { id: 2, flag: true } } { { id: 3, flag: true } { id: 4, flag: true } } }, res it "gets three results", -> res, num_queries = assert pg\query [[ select id, flag from hello_world order by id asc limit 2; select id, flag from hello_world order by id asc limit 2 offset 2; select id, flag from hello_world order by id asc limit 2 offset 4; ]] assert.same 3, num_queries assert.same { { { id: 1, flag: true } { id: 2, flag: true } } { { id: 3, flag: true } { id: 4, flag: true } } { { id: 5, flag: true } { id: 6, flag: true } } }, res it "does multiple updates", -> res, num_queries = assert pg\query [[ update hello_world set flag = false where id = 3; update hello_world set flag = true; ]] assert.same 2, num_queries assert.same { { affected_rows: 1 } { affected_rows: 10 } }, res it "does mix update and select", -> res, num_queries = assert pg\query [[ update hello_world set flag = false where id = 3; select id, flag from hello_world where id = 3 ]] assert.same 2, num_queries assert.same { { affected_rows: 1 } { { id: 3, flag: false } } }, res it "returns partial result on error", -> res, err, partial, num_queries = pg\query [[ select id, flag from hello_world order by id asc limit 1; select id, flag from jello_world limit 1; ]] assert.same { err: [[ERROR: relation "jello_world" does not exist (112)]] num_queries: 1 partial: { { id: 1, flag: true } } }, { :res, :err, :partial, :num_queries } it "deserializes types correctly", -> assert pg\query [[ create table types_test ( id serial not null, name text default 'hello', subname varchar default 'world', count integer default 100, flag boolean default false, count2 double precision default 1.2, bytes bytea default E'\\x68656c6c6f5c20776f726c6427', config json default '{"hello": "world", "arr": [1,2,3], "nested": {"foo": "bar"}}', bconfig jsonb default '{"hello": "world", "arr": [1,2,3], "nested": {"foo": "bar"}}', uuids uuid[] default ARRAY['00000000-0000-0000-0000-000000000000']::uuid[], primary key (id) ) ]] assert pg\query [[ insert into types_test (name) values ('hello') ]] res = assert pg\query [[ select * from types_test order by id asc limit 1 ]] assert.same { { id: 1 name: "hello" subname: "world" count: 100 flag: false count2: 1.2 bytes: 'hello\\ world\'' config: { hello: "world", arr: {1,2,3}, nested: {foo: "bar"} } bconfig: { hello: "world", arr: {1,2,3}, nested: {foo: "bar"} } uuids: {'00000000-0000-0000-0000-000000000000'} } }, res assert pg\query [[ drop table types_test ]] describe "hstore", -> import encode_hstore, decode_hstore from require "kpgmoon.hstore" describe "encoding", -> it "encodes hstore type", -> t = { foo: "bar" } enc = encode_hstore t assert.same [['"foo"=>"bar"']], enc it "encodes multiple pairs", -> t = { foo: "bar", abc: "123" } enc = encode_hstore t results = {'\'"foo"=>"bar", "abc"=>"123"\'', '\'"abc"=>"123", "foo"=>"bar"\''} assert(enc == results[1] or enc == results[2]) it "escapes", -> t = { foo: "bar's" } enc = encode_hstore t assert.same [['"foo"=>"bar''s"']], enc describe "decoding", -> it "decodes hstore into a table", -> s = '"foo"=>"bar"' dec = decode_hstore s assert.same {foo: 'bar'}, dec it "decodes hstore with multiple parts", -> s = '"foo"=>"bar", "1-a"=>"anything at all"' assert.same { foo: "bar" "1-a": "anything at all" }, decode_hstore s it "decodes hstore with embedded quote", -> assert.same { hello: 'wo"rld' }, decode_hstore [["hello"=>"wo\"rld"]] describe "serializing", -> before_each -> assert pg\query [[ CREATE EXTENSION hstore; create table hstore_test ( id serial primary key, h hstore ) ]] pg\setup_hstore! after_each -> assert pg\query [[ DROP TABLE hstore_test; DROP EXTENSION hstore; ]] it "serializes correctly", -> assert pg\query "INSERT INTO hstore_test (h) VALUES (#{encode_hstore {foo: 'bar'}});" res = assert pg\query "SELECT * FROM hstore_test;" assert.same {foo: 'bar'}, res[1].h it "serializes NULL as string", -> assert pg\query "INSERT INTO hstore_test (h) VALUES (#{encode_hstore {foo: 'NULL'}});" res = assert pg\query "SELECT * FROM hstore_test;" assert.same 'NULL', res[1].h.foo it "serializes multiple pairs", -> assert pg\query "INSERT INTO hstore_test (h) VALUES (#{encode_hstore {abc: '123', foo: 'bar'}});" res = assert pg\query "SELECT * FROM hstore_test;" assert.same {abc: '123', foo: 'bar'}, res[1].h describe "json", -> import encode_json, decode_json from require "kpgmoon.json" it "encodes json type", -> t = { hello: "world" } enc = encode_json t assert.same [['{"hello":"world"}']], enc t = { foo: "some 'string'" } enc = encode_json t assert.same [['{"foo":"some ''string''"}']], enc it "encodes json type with custom escaping", -> escape = (v) -> "`#{v}`" t = { hello: "world" } enc = encode_json t, escape assert.same [[`{"hello":"world"}`]], enc it "serialize correctly", -> assert pg\query [[ create table json_test ( id serial not null, config json, primary key (id) ) ]] assert pg\query "insert into json_test (config) values (#{encode_json {foo: "some 'string'"}})" res = assert pg\query [[select * from json_test where id = 1]] assert.same { foo: "some 'string'" }, res[1].config assert pg\query "insert into json_test (config) values (#{encode_json {foo: "some \"string\""}})" res = assert pg\query [[select * from json_test where id = 2]] assert.same { foo: "some \"string\"" }, res[1].config assert pg\query [[ drop table json_test ]] describe "arrays", -> import decode_array, encode_array from require "kpgmoon.arrays" it "converts table to array", -> import PostgresArray from require "kpgmoon.arrays" array = PostgresArray {1,2,3} assert.same {1,2,3}, array assert PostgresArray.__base == getmetatable array it "encodes array value", -> assert.same "ARRAY[1,2,3]", encode_array {1,2,3} assert.same "ARRAY['hello','world']", encode_array {"hello", "world"} assert.same "ARRAY[[4,5],[6,7]]", encode_array {{4,5}, {6,7}} it "decodes empty array value", -> assert.same {}, decode_array "{}" import PostgresArray from require "kpgmoon.arrays" assert PostgresArray.__base == getmetatable decode_array "{}" it "decodes numeric array", -> assert.same {1}, decode_array "{1}", tonumber assert.same {1, 3}, decode_array "{1,3}", tonumber assert.same {5.3}, decode_array "{5.3}", tonumber assert.same {1.2, 1.4}, decode_array "{1.2,1.4}", tonumber it "decodes multi-dimensional numeric array", -> assert.same {{1}}, decode_array "{{1}}", tonumber assert.same {{1,2,3},{4,5,6}}, decode_array "{{1,2,3},{4,5,6}}", tonumber it "decodes literal array", -> assert.same {"hello"}, decode_array "{hello}" assert.same {"hello", "world"}, decode_array "{hello,world}" it "decodes multi-dimensional literal array", -> assert.same {{"hello"}}, decode_array "{{hello}}" assert.same {{"hello", "world"}, {"foo", "bar"}}, decode_array "{{hello,world},{foo,bar}}" it "decodes string array", -> assert.same {"hello world"}, decode_array [[{"hello world"}]] it "decodes multi-dimensional string array", -> assert.same {{"hello world"}, {"yes"}}, decode_array [[{{"hello world"},{"yes"}}]] it "decodes string escape sequences", -> assert.same {[[hello \ " yeah]]}, decode_array [[{"hello \\ \" yeah"}]] it "fails to decode invalid array syntax", -> assert.has_error -> decode_array [[{1, 2, 3}]] it "decodes literal starting with numbers array", -> assert.same {"1one"}, decode_array "{1one}" assert.same {"1one", "2two"}, decode_array "{1one,2two}" it "decodes json array result", -> res = pg\query "select array(select row_to_json(t) from (values (1,'hello'), (2, 'world')) as t(id, name)) as items" assert.same { { items: { { id: 1, name: "hello" } { id: 2, name: "world" } } } }, res it "decodes jsonb array result", -> assert.same { { items: { { id: 442, name: "itch" } { id: 99, name: "zone" } } } }, pg\query "select array(select row_to_json(t)::jsonb from (values (442,'itch'), (99, 'zone')) as t(id, name)) as items" describe "with table", -> before_each -> pg\query "drop table if exists arrays_test" it "loads integer arrays from table", -> assert pg\query "create table arrays_test ( a integer[], b int2[], c int8[], d numeric[], e float4[], f float8[] )" num_cols = 6 assert pg\query "insert into arrays_test values (#{"'{1,2,3}',"\rep(num_cols)\sub 1, -2})" assert pg\query "insert into arrays_test values (#{"'{9,5,1}',"\rep(num_cols)\sub 1, -2})" assert.same { { a: {1,2,3} b: {1,2,3} c: {1,2,3} d: {1,2,3} e: {1,2,3} f: {1,2,3} } { a: {9,5,1} b: {9,5,1} c: {9,5,1} d: {9,5,1} e: {9,5,1} f: {9,5,1} } }, (pg\query "select * from arrays_test") it "loads string arrays from table", -> assert pg\query "create table arrays_test ( a text[], b varchar[], c char(3)[] )" num_cols = 3 assert pg\query "insert into arrays_test values (#{"'{one,two}',"\rep(num_cols)\sub 1, -2})" assert pg\query "insert into arrays_test values (#{"'{1,2,3}',"\rep(num_cols)\sub 1, -2})" assert.same { { a: {"one", "two"} b: {"one", "two"} c: {"one", "two"} } { a: {"1", "2", "3"} b: {"1", "2", "3"} c: {"1 ", "2 ", "3 "} } }, (pg\query "select * from arrays_test") it "loads string arrays from table", -> assert pg\query "create table arrays_test (ids boolean[])" assert pg\query "insert into arrays_test (ids) values ('{t,f}')" assert pg\query "insert into arrays_test (ids) values ('{{t,t},{t,f},{f,f}}')" assert.same { { ids: {true, false} } { ids: { {true, true} {true, false} {false, false} } } }, (pg\query "select * from arrays_test") it "converts null", -> pg.convert_null = true res = assert pg\query "select null the_null" assert pg.NULL == res[1].the_null it "converts to custom null", -> pg.convert_null = true n = {"hello"} pg.NULL = n res = assert pg\query "select null the_null" assert n == res[1].the_null it "encodes bytea type", -> n = { { bytea: "encoded' string\\" } } enc = pg\encode_bytea n[1].bytea res = assert pg\query "select #{enc}::bytea" assert.same n, res it "returns error message", -> status, err = pg\query "select * from blahlbhabhabh" assert.falsy status assert.same [[ERROR: relation "blahlbhabhabh" does not exist (15)]], err it "allows a query after getting an error", -> status, err = pg\query "select * from blahlbhabhabh" assert.falsy status res = pg\query "select 1" assert.truthy res it "errors when connecting with invalid server", -> pg2 = Postgres { database: "doesnotexist" :socket_type } status, err = pg2\connect! assert.falsy status assert.same [[FATAL: database "doesnotexist" does not exist]], err teardown -> pg\disconnect! os.execute "dropdb -U postgres '#{DB}'" describe "kpgmoon without server", -> escape_ident = { { "dad", '"dad"' } { "select", '"select"' } { 'love"fish', '"love""fish"' } } escape_literal = { { 3434, "3434" } { 34.342, "34.342" } { "cat's soft fur", "'cat''s soft fur'" } { true, "TRUE" } } local pg before_each -> pg = Postgres! for {ident, expected} in *escape_ident it "escapes identifier '#{ident}'", -> assert.same expected, pg\escape_identifier ident for {lit, expected} in *escape_literal it "escapes literal '#{lit}'", -> assert.same expected, pg\escape_literal lit
31.18845
131
0.475636
74d38ba42eda339b2ab220ff44850982708dd687
545
import Widget from require "lapis.html" class List extends Widget content: => element "table", -> tr -> td -> text "id" td -> text "name" td -> text "email" td -> text "admin" td -> text "created" td -> text "updated" for _, user in pairs @list tr -> td -> text user.id td -> text user.name td -> text user.email td -> text tostring user.admin td -> text tostring user.created td -> text tostring user.updated
25.952381
42
0.506422
360e15f9b72ded56bbaad2188547a6a4f861e0f2
2,987
return (ASS, ASSFInst, yutilsMissingMsg, createASSClass, Functional, LineCollection, Line, logger, SubInspector, Yutils) -> {:list, :math, :string, :table, :unicode, :util, :re } = Functional msgs = { checkValue: { mustBePositive: "%s must be a positive number, got %d." mustBeInteger: "%s must be an integer, got %s." mustBeInRange: "%s must be in range %d - %d, got %s." } cmp: { badOperand: "operand #%d must be a number or an object of (or based on) the %s class, got a %s." } } Number = createASSClass "Number", ASS.Tag.Base, {"value"}, {"number"}, {base: 10, precision: 3, scale: 1} Number.new = (args) => if type(args) == "number" @value = args else @value = @getArgs(args, 0, true)[1] @readProps args @checkValue! @value %= @__tag.mod if @__tag.mod @value *= @__tag.scale if @__tag.scale != 1 return @ Number.checkValue = => @typeCheck{@value} tag = @__tag if tag.range and (@value < tag.range[1] or @value > tag.range[2]) logger\error msgs.checkValue.mustBeInRange, @typeName, tag.range[1], tag.range[2], @value logger\error msgs.checkValue.mustBePositive, @typeName, @value if tag.positive and @value < 0 logger\error msgs.checkValue.mustBeInteger, @typeName, @value if tag.integer and not math.isInt @value Number.getTagParams = (_, precision = @__tag.precision) => val = @value @checkValue! val %= @__tag.mod if @__tag.mod val /= @__tag.scale if @__tag.scale != 1 return math.round val, precision Number.cmp = (a, mode, b) -> aType, bType = type(a), type b if aType == "table" and (a.compatible[Number] or a.baseClasses[Number]) a = a.value elseif aType !="number" logger\error msgs.cmp.badOperand, 1, Number.typeName, ASS\instanceOf(a) and a.typeName or type a if bType == "table" and (b.compatible[Number] or b.baseClasses[Number]) b = b.value elseif bType !="number" logger\error msgs.cmp.badOperand, 2, Number.typeName, ASS\instanceOf(b) and b.typeName or type b return switch mode when "<" then a < b when ">" then a > b when "<=" then a <= b when ">=" then a >= b Number.lerp = (a, b, t) -> c = a\copy! c.value = a.value + (b.value - a.value) * t return c Number.modEq = (val, div) => (@%div)\equal val Number.__lt = (a, b) -> Number.cmp a, "<", b Number.__le = (a, b) -> Number.cmp a, "<=", b Number.__add = (a, b) -> type(a) == "table" and a\copy!\add(b) or b\copy!\add a Number.__sub = (a, b) -> type(a) == "table" and a\copy!\sub(b) or Number(a)\sub b Number.__mul = (a, b) -> type(a) == "table" and a\copy!\mul(b) or b\copy!\mul a Number.__div = (a, b) -> type(a) == "table" and a\copy!\div(b) or Number(a)\div b Number.__mod = (a, b) -> type(a) == "table" and a\copy!\mod(b) or Number(a)\mod b Number.__pow = (a, b) -> type(a) == "table" and a\copy!\pow(b) or Number(a)\pow b return Number
35.987952
123
0.602611
c91e0519ecc1037b4fa855d4c54c9ccd9116c7e5
148
ShapeType = smaug.java.require "com.badlogic.gdx.graphics.glutils.ShapeRenderer$ShapeType" { "line": ShapeType.Line "fill": ShapeType.Filled }
21.142857
90
0.756757
7052557e56b6aaa067ded749e72ae84e92f0bfec
2,586
round = math.round :define = require 'classy' insert: append = table :exec = require "process" command = require 'command' define 'PulseAudio', -> vol_cmd = (sink, val) -> "pacmd set-sink-volume #{sink} #{val}" mute_cmd = (sink, val) -> "pacmd set-sink-mute #{sink} #{val}" parse_list_sinks = (str) -> lines = str\split "\n" sinks = {} for idx, line in ipairs lines if index = line\match 'index: (%d+)' current = line\match('*%s+index') and true or false name = lines[idx+1] name = name\gsub 'name: ', '' name = name\gsub '[<>]', '' name = name\trim! sink = :current, :name, :index append sinks, sink sinks parse_list_sink_inputs = (str) -> lines = str\split "\n" inputs = {} for idx, line in ipairs lines if index = line\match 'index: (%d+)' sink = lines[idx+4] input = :sink, :index append inputs, input inputs static list_sinks: => -- using synchronous built-in here since this -- is intended to be used in a setup context -- and so the coroutine/event system isn't -- yet initialized reader = io.popen "pacmd list-sinks" out = reader\read '*a' parse_list_sinks out properties is_current: => out = command "pacmd list-sinks" return false unless out sink_list = parse_list_sinks out for sink in *sink_list if sink.name == @name return sink.current volume: get: => out = command "pacmd dump" return unless out for sink, value in out\gmatch 'set%-sink%-volume ([^%s]+) (0x%x+)' if sink == @name return tonumber(value) / 65536 set: (val) => val = 1 if val > 1 val = 0 if val < 0 vol = round val * 65536 exec vol_cmd(@name, vol) mute:=> out = command "pacmd dump" return unless out for sink, value in out\gmatch 'set%-sink%-mute ([^%s]+) (%a+)' if sink == @name return value == "yes" instance -- name should be name of a sink this will control -- so list_sinks is a good way of doing that initialize: (sink) => @name = sink.name @index = sink.index toggle_mute: => val = @mute and 0 or 1 exec mute_cmd(@name, val) make_current: => exec "pacmd set-default-sink #{@name}" out = command "pacmd list-sink-inputs" return unless out inputs = parse_list_sink_inputs out exec "pacmd move-sink-input #{input.index} #{@index}" for input in *inputs
27.806452
80
0.568832
45a569b40eda4ee542b07dc54d07648446a4d546
776
use_test_env = (env_name="test") -> import setup, teardown from require "busted" env = require "lapis.environment" setup -> env.push env_name teardown -> env.pop! use_test_server = -> import setup, teardown from require "busted" import load_test_server, close_test_server from require "lapis.spec.server" setup -> load_test_server! teardown -> close_test_server! assert_no_queries = (fn=error"missing function") -> assert = require "luassert" db = require "lapis.db" old_query = db.get_raw_query! query_log = {} db.set_raw_query (...) -> table.insert query_log, (...) old_query ... res, err = pcall fn db.set_raw_query old_query assert res, err assert.same {}, query_log {:use_test_env, :use_test_server, :assert_no_queries}
23.515152
77
0.704897
b7ca566e4021d5025a4d08d2a29dc7f82dec481d
6,689
import type, tostring, pairs, select from _G import concat from table import FALSE NULL TRUE build_helpers format_date is_raw raw from require "lapis.db.base" local conn, logger local * BACKENDS = { -- the raw backend is a debug backend that lets you specify the function that -- handles the query raw: (fn) -> fn luasql: -> config = require("lapis.config").get! mysql_config = assert config.mysql, "missing mysql configuration" luasql = require("luasql.mysql").mysql! conn = assert luasql\connect mysql_config.database, mysql_config.user, mysql_config.password (q) -> logger.query q if logger cur = assert conn\execute q has_rows = type(cur) != "number" result = { affected_rows: has_rows and cur\numrows! or cur last_auto_id: conn\getlastautoid! } if has_rows colnames = cur\getcolnames! coltypes = cur\getcoltypes! assert #colnames == #coltypes name2type = {} for i = 1, #colnames do colname = colnames[i] coltype = coltypes[i] name2type[colname] = coltype while true if row = cur\fetch {}, "a" for colname, value in pairs(row) coltype = name2type[colname] if coltype == 'number(1)' value = if value == '1' then true else false elseif coltype\match 'number' value = tonumber(value) row[colname] = value table.insert result, row else break result resty_mysql: -> import after_dispatch, increment_perf from require "lapis.nginx.context" config = require("lapis.config").get! mysql_config = assert config.mysql, "missing mysql configuration for resty_mysql" host = mysql_config.host or "127.0.0.1" port = mysql_config.port or 3306 path = mysql_config.path database = assert mysql_config.database, "`database` missing from config for resty_mysql" user = assert mysql_config.user, "`user` missing from config for resty_mysql" password = mysql_config.password ssl = mysql_config.ssl ssl_verify = mysql_config.ssl_verify timeout = mysql_config.timeout or 10000 -- 10 seconds max_idle_timeout = mysql_config.max_idle_timeout or 10000 -- 10 seconds pool_size = mysql_config.pool_size or 100 mysql = require "resty.mysql" (q) -> logger.query q if logger db = ngx and ngx.ctx.resty_mysql_db unless db db, err = assert mysql\new() db\set_timeout(timeout) options = { :database, :user, :password, :ssl, :ssl_verify } if path options.path = path else options.host = host options.port = port assert db\connect options if ngx ngx.ctx.resty_mysql_db = db after_dispatch -> db\set_keepalive(max_idle_timeout, pool_size) start_time = if ngx and config.measure_performance ngx.update_time! ngx.now! res, err, errcode, sqlstate = assert db\query q local result if err == 'again' result = {res} while err == 'again' res, err, errcode, sqlstate = assert db\read_result! table.insert result, res else result = res if start_time ngx.update_time! increment_perf "db_time", ngx.now! - start_time increment_perf "db_count", 1 result } set_backend = (name, ...) -> backend = BACKENDS[name] unless backend error "Failed to find MySQL backend: #{name}" raw_query = backend ... set_raw_query = (fn) -> raw_query = fn get_raw_query = -> raw_query escape_literal = (val) -> switch type val when "number" return tostring val when "string" if conn return "'#{conn\escape val}'" else if ngx return ngx.quote_sql_str(val) else connect! return escape_literal val when "boolean" return val and "TRUE" or "FALSE" when "table" return "NULL" if val == NULL return val[1] if is_raw val error "unknown table passed to `escape_literal`" error "don't know how to escape value: #{val}" escape_identifier = (ident) -> return ident[1] if is_raw ident ident = tostring ident '`' .. (ident\gsub '`', '``') .. '`' init_logger = -> config = require("lapis.config").get! logger = if ngx or os.getenv("LAPIS_SHOW_QUERIES") or config.show_queries require "lapis.logging" init_db = -> config = require("lapis.config").get! backend = config.mysql and config.mysql.backend unless backend backend = if ngx "resty_mysql" else "luasql" set_backend backend connect = -> init_logger! init_db! -- replaces raw_query to default backend raw_query = (...) -> connect! raw_query ... interpolate_query, encode_values, encode_assigns, encode_clause = build_helpers escape_literal, escape_identifier append_all = (t, ...) -> for i=1, select "#", ... t[#t + 1] = select i, ... add_cond = (buffer, cond, ...) -> append_all buffer, " WHERE " switch type cond when "table" encode_clause cond, buffer when "string" append_all buffer, interpolate_query cond, ... query = (str, ...) -> if select("#", ...) > 0 str = interpolate_query str, ... raw_query str _select = (str, ...) -> query "SELECT " .. str, ... _insert = (tbl, values, ...) -> if values._timestamp values._timestamp = nil time = format_date! values.created_at or= time values.updated_at or= time buff = { "INSERT INTO " escape_identifier(tbl) " " } encode_values values, buff raw_query concat buff _update = (table, values, cond, ...) -> if values._timestamp values._timestamp = nil values.updated_at or= format_date! buff = { "UPDATE " escape_identifier(table) " SET " } encode_assigns values, buff if cond add_cond buff, cond, ... raw_query concat buff _delete = (table, cond, ...) -> buff = { "DELETE FROM " escape_identifier(table) } if cond add_cond buff, cond, ... raw_query concat buff _truncate = (table) -> raw_query "TRUNCATE " .. escape_identifier table -- To be implemented -- { -- :parse_clause -- -- } { :connect :raw, :is_raw, :NULL, :TRUE, :FALSE, :encode_values :encode_assigns :encode_clause :interpolate_query :query :escape_literal :escape_identifier :format_date :init_logger :set_backend :set_raw_query :get_raw_query select: _select insert: _insert update: _update delete: _delete truncate: _truncate }
22.674576
113
0.621618
7b2de89672603e5221f652f6b228ae87e0e66f41
126
Loader = require('vendor/hug/lib/loader') Loader((key) -> file = _.kebabCase(key) return require("lib/entities/#{file}") )
18
41
0.674603
d9dbb1e304e8326073c51823e10115bfcbb6bd20
1,469
import log, signal from howl import ActionBuffer from howl.ui append = table.insert class JournalBuffer extends ActionBuffer new: => super! @read_only = true @title = 'Howl Journal' @entry_sizes = {} @_appended = self\append_entry @_trimmed = self\trim signal.connect 'log-entry-appended', @_appended signal.connect 'log-trimmed', @_trimmed for entry in *log.entries @append_entry entry modify: (f) => @read_only = false f! @read_only = true @modified = false append_entry: (entry) => level = entry.level message = entry.message .. '\n' append @entry_sizes, message\count '\n' @modify -> editor = howl.app.editor at_end_of_file = editor and editor.cursor.at_end_of_file level = 'error' if level == 'traceback' @append message, level editor.cursor\eof! if at_end_of_file if howl.app.editor and howl.app.editor.buffer == @ howl.app.editor.cursor\eof! trim: (options) => size = options.size assert size <= #@entry_sizes nlines = 0 to_remove = #@entry_sizes - size for _=1,to_remove nlines += table.remove @entry_sizes, 1 @modify -> @lines\delete 1, nlines signal.connect 'buffer-closed', (params) -> {:buffer} = params return if typeof(buffer) != 'JournalBuffer' signal.disconnect 'log-entry-appended', buffer._appended signal.disconnect 'log-trimmed', buffer._trimmed return JournalBuffer
22.953125
62
0.656909
bcf6511b3449e8e632650668686a62cfa67bcca5
487
Gtk = require 'ljglibs.gtk' describe 'Box', -> local box before_each -> box = Gtk.Box! describe '(child properties)', -> it 'supports r/w property access through properties_for(child)', -> box2 = Gtk.Box! box\add box2 p = box\properties_for box2 assert.is_false p.expand assert.equal Gtk.PACK_START, p.pack_type p.expand = true p.pack_type = Gtk.PACK_END assert.is_true p.expand assert.equal Gtk.PACK_END, p.pack_type
23.190476
71
0.646817
d555bdd3b064d68bfd7bfd8c56dc1e3d12c4667b
5,932
return (ASS, ASSFInst, yutilsMissingMsg, createASSClass, Functional, LineCollection, Line, logger, SubInspector, Yutils) -> {:list, :math, :string, :table, :unicode, :util, :re } = Functional class Drawing msgs = { parse: { invalidQuirksMode: "Invalid quirks mode '%s'" badOrdinate: "expected ordinate, got '%s'" wrongOrdinateCount: "incorrect number of ordinates for command '%s': expected %d, got %d" cantParse: "Error: failed to parse drawing near '%s' (%s)." unsupportedCommand: "Error: Unsupported drawing Command '%s'." } } local cmdMap, cmdSet, Close, Draw, Move, Contour, Bezier @getContours = (str, parent, splitContours = true) => unless cmdMap -- import often accessed information into local scope cmdMap, cmdSet = ASS.Draw.commandMapping, ASS.Draw.commands Close, Move, Contour, Bezier = ASS.Draw.Close, ASS.Draw.Move, ASS.Draw.Contour, ASS.Draw.Bezier -- split drawing command string cmdParts = string.split string.trim(str), "%s+", nil, false -- TODO: check possible optimization by using simple split and no trimming here and skipping empty stuff later on instead cmdPartCnt = #cmdParts i, junk, prevCmdType = 1 contours, c = {}, 1 contour, d = {}, 1 while i <= cmdPartCnt cmd, cmdType = cmdParts[i], cmdMap[cmdParts[i]] -- move command creates a new contour if cmdType == Move and i > 1 and splitContours contours[c] = Contour contour contours[c].parent = parent contour, d, c = {}, 1, c+1 -- close command closes a contour if cmdType == Close contour[d] = Close! -- There are two ways for a new drawing command to start -- (a) a new command is explicitely denoted by its identifier m, l, b, etc -- (b) a new command of the same type as the previous command implicitely starts -- once coordinates in addition to those consumed by the previous command are encountered elseif cmdType or prevCmdType and cmd\find "^[%-%d%.]+$" if cmdType prevCmdType = cmdType else i -= 1 prmCnt = prevCmdType.__defProps.ords p, prms, skippedOrdCnt = 1, {}, 0 while p <= prmCnt prm = cmdParts[p+i] if prms[p-skippedOrdCnt] = tonumber prm p += 1 continue -- process ordinates that failed to cast to a number -- either the command or the the drawing is truncated if not prm or prm\match "^[bclmnps]$" unless ASS.config.fixDrawings reason = msgs.parse.wrongOrdinateCount\format prevCmdType.typeName, prmCnt, p-1 near = table.concat cmdParts, " ", math.max(i+p-10,1), i+p logger\error msgs.parse.cantParse, near, reason -- we can fix this if required, but need to -- give back any subsequent drawing commands prmCnt = prm and p - 1 or p break -- the ordinate is either malformed or has trailing junk elseif not ASS.config.fixDrawings near = table.concat cmdParts, " ", math.max(i+p-10,1), i+p logger\error msgs.parse.cantParse, near, msgs.parse.badOrdinate\format prm ord, fragment = prm\match "^([%-%d%.]*)(.*)$" switch ASS.config.quirks when ASS.Quirks.VSFilter -- xy-vsfilter accepts and draws an ordinate with junk at the end, -- but will skip any following drawing commands in the drawing section. if ord prms[p-skippedOrdCnt] = tonumber ord fragment = prm unless prms[p-skippedOrdCnt] -- move the junk into a comment section and stop parsing further drawing commands junk or= ASS.Section.Comment fragment junk\append list.slice(cmdParts, i+p+1), " " i = cmdPartCnt + 1 -- fast forward to end of the outer loop break when ASS.Quirks.libass -- libass only draws y ordinates with trailing junk but discards x ordinates. -- However, it will recover once it hits valid commands again. junk or= ASS.Section.Comment! if not ord or p % 2 == 1 -- move broken x parameter into a comment section junk\append prm, " " -- make sure to read another parameter for this command -- to replace the one we just gave up skippedOrdCnt, prmCnt += 1 else -- move junk trailing the y ordinate into a comment section prms[p-skippedOrdCnt] = tonumber ord if not prms[p-skippedOrdCnt] junk\append prm, " " skippedOrdCnt, prmCnt += 1 else junk\append fragment, " " p += 1 else logger\error msgs.parse.invalidQuirksMode, tostring ASS.config.quirks -- set the marker for skipping input/type checking in the drawing command constructors prms.__raw = true -- only create the command if the required number of ordinates have been specified if #prms == prevCmdType.__defProps.ords -- use the superfast internal constructor if available contour[d] = if prevCmdType.__defNew prevCmdType.__defNew prms else prevCmdType prms i += prmCnt -- TODO: also check for ordinates ending w/ junk here and apply quirks algo else logger\error msgs.parse.unsupportedCommand, cmdParts[i] i += 1 d += 1 if d > 0 contours[c] = Contour contour contours[c].parent = parent return contours, junk
42.371429
187
0.584626
9d4c49aa40c5f54660d759856cc647bb8aa82cf1
2,059
html = require "lapis.html" markdown = require "markdown" -- lib/lazuli/luarocks install markdown config = require"lapis.config".get! import getDoMsuffix, formatDate, getAge, blankifyLinks, stripHtml, abbrCaps from require "utils" class ProfileShow extends html.Widget content: => if false and config.envmode == "development" pre style: "background: rgba(0,0,0,0.8); padding: 1em; margin: 1em;",-> code -> text require"moonscript.util".dump @profiledata with @profiledata section id:"profile_summary", class: "pure-g", -> h1 class: "pure-u-1", -> text \get_user!.username span class: "shortInfo", -> if .birthday and @acls.birthday_y text getAge .birthday if .gender and @acls.gender text abbrCaps .gender if .orientation and @acls.orientation text " " .. abbrCaps .orientation if .preferred_role and @acls.preferred_role text " " .. .preferred_role if .gender and @acls.gender div class: "pure-u-1-3", "Gender:" div class: "pure-u-2-3", .gender\lower! if .birthday if @acls.birthday_y div class: "pure-u-1-3", "Age:" div class: "pure-u-2-3", getAge .birthday if @acls.birthday_dm or @acls.birthday_y div class: "pure-u-1-3", "Birthday:" div class: "pure-u-2-3", formatDate .birthday, @acls.birthday_dm, @acls.birthday_y if .orientation and @acls.orientation div class: "pure-u-1-3", "Orientation:" div class: "pure-u-2-3", .orientation\lower! if .preferred_role and @acls.preferred_role div class: "pure-u-1-3", "Preferred role:" div class: "pure-u-2-3", .preferred_role if .about and @acls.about section id:"profile_about", class: "pure-g", -> h1 class: "pure-u-1" ,"About me" unless .about\sub(1,2)=="# " div class: "pure-u-1", -> raw blankifyLinks markdown stripHtml .about
42.895833
96
0.592035
aa333285fe492122437dc4969dbe9c0ae75d4c73
1,468
import type, tostring, pairs, select from _G import NULL, TRUE, FALSE, raw, is_raw, format_date from require "lapis.db.base" local conn local * backends = { luasql: -> config = require("lapis.config").get! mysql_config = assert config.mysql, "missing mysql configuration" luasql = require("luasql.mysql").mysql! conn = assert luasql\connect mysql_config.database, mysql_config.user escape_literal = (q) -> conn\escape q raw_query = (q) -> cur = assert conn\execute q result = { affected_rows: cur\numrows! } while true if row = cur\fetch {}, "a" table.insert result, row else break result } set_backend = (name="default", ...) -> assert(backends[name]) ... escape_literal = (val) -> assert(conn)\escape val escape_identifier = (ident) -> return ident if is_raw ident ident = tostring ident '`' .. (ident\gsub '`', '``') .. '`' raw_query = (...) -> config = require("lapis.config").get! set_backend "luasql" raw_query ... -- To be implemented -- { -- :query, -- :escape_identifier -- :encode_values -- :encode_assigns -- :encode_clause -- :interpolate_query -- :parse_clause -- :format_date -- -- select: _select -- insert: _insert -- update: _update -- delete: _delete -- truncate: _truncate -- } { :raw, :is_raw, :NULL, :TRUE, :FALSE, :escape_literal :set_backend :raw_query :format_date }
18.820513
79
0.61376
34f0e74b90fda24f7b05801c17052c743a4d709a
11,558
import app, config, signal from howl describe 'config', -> before_each -> config.reset! app.editor = nil describe 'define(options)', -> it 'raises an error if name is missing', -> assert.raises 'name', -> config.define {} it 'raises an error if the description option is missing', -> assert.raises 'description', -> config.define name: 'foo' describe '.definitions', -> it 'is a table of the current definitions, keyed by name', -> var = name: 'foo', description: 'foo variable' config.define var assert.equal type(config.definitions), 'table' assert.same var, config.definitions.foo it 'writing directly to it raises an error', -> assert.has_error -> config.definitions.frob = 'crazy' describe 'set(name, value)', -> it 'sets <name> globally to <value>', -> var = name: 'foo', description: 'foo variable' config.define var config.set 'foo', 2 assert.equal config.get('foo'), 2 it 'an error is raised if <name> is not defined', -> assert.raises 'Undefined', -> config.set 'que', 'si' it 'setting a value of nil clears the value', -> var = name: 'foo', description: 'foo variable' config.define var config.set 'foo', 'bar' config.set 'foo', nil assert.is_nil config.foo describe 'get(name)', -> before_each -> config.define name: 'var', description: 'test variable' it 'returns the global value of <name>', -> config.set 'var', 'hello' assert.equal config.get('var'), 'hello' context 'when a default is provided', -> before_each -> config.define name: 'with_default', description: 'test', default: 123 it 'the default value is returned if no value has been set', -> assert.equal config.get('with_default'), 123 it 'if a value has been set it takes precedence', -> config.set 'with_default', 'foo' assert.equal config.get('with_default'), 'foo' it 'reset clears all set values, but keeps the definitions', -> config.define name: 'var', description: 'test' config.set 'var', 'set' config.reset! assert.is_not_nil config.definitions['var'] assert.is_nil config.get 'var' it 'global variables can be set and get directly on config', -> config.define name: 'direct', description: 'test', default: 123 assert.equal config.direct, 123 config.direct = 'bar' assert.equal config.direct, 'bar' assert.equal config.get('direct'), 'bar' context 'when a validate function is provided', -> it 'is called with the value to be set whenever the variable is set', -> validate = spy.new -> true config.define name: 'validated', description: 'test', :validate config.set 'validated', 'my_value' assert.spy(validate).was_called_with 'my_value' it 'an error is raised if the function returns false for to-be set value', -> config.define name: 'validated', description: 'test', validate: -> false assert.error -> config.set 'validated', 'foo' config.define name: 'validated', description: 'test', validate: -> nil assert.no_error -> config.set 'validated', 'foo' config.define name: 'validated', description: 'test', validate: -> true assert.no_error -> config.set 'validated', 'foo' it 'an error is not raised if the function returns truish for to-be set value', -> config.define name: 'validated', description: 'test', validate: -> true config.set 'validated', 'foo' assert.equal config.get('validated'), 'foo' config.define name: 'validated', description: 'test', validate: -> 2 config.set 'validated', 'foo2' assert.equal config.get('validated'), 'foo2' it 'the function is not called when clearing a value by setting it to nil', -> validate = Spy! config.define name: 'validated', description: 'test', :validate config.set 'validated', nil assert.is_false validate.called context 'when a convert function is provided', -> it 'is called with the value to be set and the return value is used instead', -> config.define name: 'converted', description: 'test', convert: -> 'wanted' config.set 'converted', 'requested' assert.equal config.converted, 'wanted' context 'when options is provided', -> before_each -> config.define name: 'with_options' description: 'test' options: { 'one', 'two' } it 'an error is raised if the to-be set value is not a valid option', -> assert.raises 'option', -> config.set 'with_options', 'three' it 'an error is not raised if the to-be set value is a valid option', -> config.set 'with_options', 'one' it 'options can be a function returning a table', -> config.define name: 'with_options_func', description: 'test', options: -> { 'one', 'two' } assert.raises 'option', -> config.set 'with_options_func', 'three' config.set 'with_options_func', 'one' it 'options can be a table of tables containg values and descriptions', -> options = { { 'one', 'description for one' } { 'two', 'description for two' } } config.define name: 'with_options_desc', description: 'test', :options assert.raises 'option', -> config.set 'with_options_desc', 'three' config.set 'with_options_desc', 'one' context 'when scope is provided', -> it 'raises an error if it is not "local" or "global"', -> assert.raises 'scope', -> config.define name: 'bla', description: 'foo', scope: 'blarg' context 'with local scope for a variable', -> it 'an error is raised when trying to set the global value of the variable', -> config.define name: 'local', description: 'test', scope: 'local' assert.error -> config.set 'local', 'foo' context 'when type_of is provided', -> it 'raises an error if the type is not recognized', -> assert.raises 'type', -> config.define name: 'bla', description: 'foo', type_of: 'blarg' context 'and is "boolean"', -> def = nil before_each -> config.define name: 'bool', description: 'foo', type_of: 'boolean' def = config.definitions.bool it 'options are {true, false}', -> assert.same def.options, { true, false } it 'convert handles boolean types and "true" and "false"', -> assert.equal def.convert(true), true assert.equal def.convert(false), false assert.equal def.convert('true'), true assert.equal def.convert('false'), false assert.equal def.convert('blargh'), 'blargh' it 'converts to boolean upon assignment', -> config.bool = 'false' assert.equal config.bool, false context 'and is "number"', -> def = nil before_each -> config.define name: 'number', description: 'foo', type_of: 'number' def = config.definitions.number it 'convert handles numbers and string numbers', -> assert.equal def.convert(1), 1 assert.equal def.convert('1'), 1 assert.equal def.convert(0.5), 0.5 assert.equal def.convert('0.5'), 0.5 assert.equal def.convert('blargh'), 'blargh' it 'validate returns true for numbers only', -> assert.is_true def.validate 1 assert.is_true def.validate 1.2 assert.is_false def.validate '1' assert.is_false def.validate 'blargh' it 'converts to number upon assignment', -> config.number = '1' assert.equal config.number, 1 context 'and is "string_list"', -> def = nil before_each -> config.define name: 'string_list', description: 'foo', type_of: 'string_list' def = config.definitions.string_list describe 'convert', -> it 'leaves string tables alone', -> orig = { 'hi', 'there' } assert.same orig, def.convert orig it 'converts values in other tables as necessary', -> orig = { 1, 2 } assert.same { '1', '2', }, def.convert orig it 'converts simple values into a table', -> assert.same { '1' }, def.convert '1' assert.same { '1' }, def.convert 1 it 'converts a blank string into an empty table', -> assert.same {}, def.convert '' assert.same {}, def.convert ' ' it 'converts a comma separated string into a list of values', -> assert.same { '1', '2' }, def.convert '1,2' assert.same { '1', '2' }, def.convert ' 1 , 2 ' it 'validate returns true for table values', -> assert.is_true def.validate {} assert.is_false def.validate '1' assert.is_false def.validate 23 context 'watching', -> before_each -> config.define name: 'trigger', description: 'watchable' it 'watch(name, function) register a watcher for <name>', -> assert.not_error -> config.watch 'foo', -> true it 'set invokes watchers with <name>, <value> and false', -> callback = Spy! config.watch 'trigger', callback config.set 'trigger', 'value' assert.same callback.called_with, { 'trigger', 'value', false } it 'define(..) invokes watchers with <name>, <default-value> and false', -> callback = spy.new -> config.watch 'undefined', callback config.define name: 'undefined', description: 'springs into life', default: 123 assert.spy(callback).was_called_with 'undefined', 123, false context 'when a callback raises an error', -> before_each -> config.watch 'trigger', -> error 'oh noes' it 'other callbacks are still invoked', -> callback = Spy! config.watch 'trigger', callback config.set 'trigger', 'value' assert.is_true callback.called it 'an error is logged', -> config.set 'trigger', 'value' assert.match log.last_error.message, 'watcher' describe 'proxy', -> config.define name: 'my_var', description: 'base', type_of: 'number' local proxy before_each -> config.my_var = 123 proxy = config.local_proxy! it 'returns a table with access to all previously defined variables', -> assert.equal 123, proxy.my_var it 'changing a variable changes it locally only', -> proxy.my_var = 321 assert.equal 321, proxy.my_var assert.equal 123, config.my_var it 'assignments are still validated and converted as usual', -> assert.has_error -> proxy.my_var = 'not a number' proxy.my_var = '111' assert.equal 111, proxy.my_var it 'an error is raised if trying to set a variable with global scope', -> config.define name: 'global', description: 'global', scope: 'global' assert.has_error -> proxy.global = 'illegal' it 'an error is raised if the variable is not defined', -> assert.raises 'Undefined', -> proxy.que = 'si' it 'setting a value to nil clears the value', -> proxy.my_var = 666 proxy.my_var = nil assert.equal 123, proxy.my_var it 'setting a variable via a proxy invokes watchers with <name>, <value> and true', -> callback = spy.new -> config.watch 'my_var', callback proxy.my_var = 333 assert.spy(callback).was.called_with, { 'my_var', 333, true } it 'can be chained to another proxy to create a lookup chain', -> config.my_var = 222 base_proxy = config.local_proxy! proxy.chain_to base_proxy assert.equal 222, proxy.my_var base_proxy.my_var = 333 assert.equal 333, proxy.my_var assert.equal 222, config.my_var
37.895082
94
0.630645
a87cc2501c206ef74230cec95183d5cce987aef9
591
colors = require 'ansicolors' round = math.round time_calc = (start, finish) -> round finish - start, 3 { info: (msg, info) -> print colors("[ %{dim}#{msg}%{reset} ]") success: (msg, info) -> msg = colors("[ %{green}SUCCEEDED") :start_at, success_at: end_at = info print msg .. colors "%{white} in #{time_calc(start_at, end_at)} seconds%{reset} ]" print '' fail: (msg, info) -> msg = colors("[ %{red}FAILED (#{msg})") :start_at, fail_at: end_at = info print msg .. colors "%{white} in #{time_calc(start_at, end_at)} seconds%{reset} ]" print '' }
28.142857
86
0.593909
8ff1e4d76f8cf15cedaed94538acc972290fc27d
1,415
import decode, encode from require "lunajson" import request from require "ssl.https" import sink from require "ltn12" import source from require "ltn12" -- _ _ _ -- | | | | ___| |_ _____ __ ___ _ __ -- | |_| |/ _ | __|_ | '_ \ / _ | '__| -- | _ | __| |_ / /| | | | __| | -- |_| |_|\___|\__/___|_| |_|\___|_| -- API_URI = "https://api.hetzner.cloud/v1" class Hetzner new: (api_key) => @api_key = api_key _request: (connection={}) => body = {} connection.sink = sink.table body connection.headers or= {} connection.headers.authorization = "Bearer #{@api_key}" success, code, headers = request connection if success if code ~= 200 return nil, "status code #{code} returned\n#{table.concat body}", { :success :code :headers body: decode table.concat body } else return { :success :code :headers body: decode table.concat body } else return nil, "request failed\n#{code}" get: (uri_tail) => @_request url: "#{API_URI}/#{uri_tail}" post: (uri_tail, body) => body = encode body @_request url: "#{API_URI}/#{uri_tail}" method: "POST" source: source.string body headers: ["content-type"]: "application/json" ["content-length"]: #body servers: => (assert @get("servers")).body.servers new_server: (json) => @post "servers", json {:Hetzner}
22.109375
71
0.580919
4c8be519a7d3b92f25f68381aa70173fa68a1395
329
export class ParticleSystem new: => @emitters = Group! @lookup = {} register: (name, emitter) => @emitters\add emitter @lookup[name] = emitter emit: (name, x, y, amount) => @lookup[name]\emit x, y, amount stream: (name, x, y, amount) => @lookup[name]\stream x, y, amount stop: (name) => @lookup[name]\stop!
19.352941
35
0.617021
13852ec722c334c6e4115753f222f331435d3af8
12,200
-- -- Copyright (C) 2017-2020 DBotThePony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. class ExpressionSequence extends PPM2.SequenceBase new: (controller, data) => super(controller, data) { 'flexSequence': @flexSequence 'bonesSequence': @bonesSequence 'bones': @bonesNames 'flexes': @flexNames } = data @knownBonesSequences = {} @controller = controller @flexStates = {} @bonesNames = @bonesNames or {} @bonesFuncsPos = ['SetModifier' .. boneName .. 'Position' for _, boneName in ipairs @bonesNames] @bonesFuncsScale = ['SetModifier' .. boneName .. 'Scale' for _, boneName in ipairs @bonesNames] @bonesFuncsAngles = ['SetModifier' .. boneName .. 'Angles' for _, boneName in ipairs @bonesNames] @ponydata = @controller.renderController\GetData() @ponydataID = @ponydata\GetModifierID(@name .. '_emote') @RestartChildren() @Launch() GetController: => @controller SetControllerModifier: (name = '', val) => @ponydata['SetModifier' .. name](@ponydata, @ponydataID, val) RestartChildren: => if @flexSequence if flexController = @controller.renderController\GetFlexController() @flexController = flexController if type(@flexSequence) == 'table' for _, seq in ipairs @flexSequence flexController\StartSequence(seq, @time)\SetInfinite(@GetInfinite()) else flexController\StartSequence(@flexSequence, @time)\SetInfinite(@GetInfinite()) if @flexNames @flexStates = [{flexController\GetFlexState(flex), flexController\GetFlexState(flex)\GetModifierID(@name .. '_emote')} for _, flex in ipairs @flexNames] @knownBonesSequences = {} if bones = @GetEntity()\PPMBonesModifier() @bonesController = bones if @bonesSequence if type(@bonesSequence) == 'table' for _, seq in ipairs @bonesSequence bones\StartSequence(seq, @time)\SetInfinite(@GetInfinite()) table.insert(@knownBonesSequences, seq) else bones\StartSequence(@bonesSequence, @time)\SetInfinite(@GetInfinite()) table.insert(@knownBonesSequences, @bonesSequence) @bonesModifierID = bones\GetModifierID(@name .. '_emote') PlayBonesSequence: (name, time = @time) => return PPM2.Message('Bones controller not found for sequence ', @, '! This is a bug. ', @controller) if not @bonesController table.insert(@knownBonesSequences, name) return @bonesController\StartSequence(name, time) Think: (delta = 0) => return false if not IsValid(@GetEntity()) super(delta) Stop: => super() @ponydata\ResetModifiers(@name .. '_emote') if @flexController if @flexSequence if type(@flexSequence) == 'table' for _, id in ipairs @flexSequence @flexController\EndSequence(id) else @flexController\EndSequence(@flexSequence) flex\ResetModifiers(id) for _, {flex, id} in ipairs @flexStates if @bonesController for _, id in ipairs @knownBonesSequences @bonesController\EndSequence(id) SetBonePosition: (id = 1, val = Vector(0, 0, 0)) => @controller[@bonesFuncsPos[id]] and @controller[@bonesFuncsPos[id]](@controller, @bonesModifierID, val) SetBoneScale: (id = 1, val = 0) => @controller[@bonesFuncsScale[id]] and @controller[@bonesFuncsScale[id]](@controller, @bonesModifierID, val) SetBoneAngles: (id = 1, val = Angles(0, 0, 0)) => @controller[@bonesFuncsAngles[id]] and @controller[@bonesFuncsAngles[id]](@controller, @bonesModifierID, val) SetFlexWeight: (id = 1, val = 0) => @flexStates[id] and @flexStates[id][1](@flexStates[id][1], @flexStates[id][2], val) PPM2.ExpressionSequence = ExpressionSequence class PPM2.PonyExpressionsController extends PPM2.ControllerChildren @AVALIABLE_CONTROLLERS = {} @MODELS = {'models/ppm/player_default_base_new.mdl', 'models/ppm/player_default_base_new_nj.mdl'} @SEQUENCES = { { 'name': 'sad' 'flexSequence': {'sad'} 'bonesSequence': {'floppy_ears'} 'autostart': false 'repeat': false 'time': 5 'reset': => 'func': (delta, timeOfAnim) => } { 'name': 'sorry' 'flexSequence': 'sorry' 'bonesSequence': {'floppy_ears'} 'autostart': false 'repeat': false 'time': 8 } { 'name': 'scrunch' 'flexSequence': 'scrunch' 'autostart': false 'repeat': false 'time': 6 } { 'name': 'gulp' 'flexSequence': 'gulp' 'autostart': false 'repeat': false 'time': 2 } { 'name': 'blahblah' 'flexSequence': 'blahblah' 'autostart': false 'repeat': false 'time': 3 } { 'name': 'wink_left' 'flexSequence': 'wink_left' 'bonesSequence': 'forward_left' 'autostart': false 'repeat': false 'time': 2 } { 'name': 'wink_right' 'flexSequence': 'wink_right' 'bonesSequence': 'forward_right' 'autostart': false 'repeat': false 'time': 2 } { 'name': 'happy_eyes' 'flexSequence': 'happy_eyes' 'autostart': false 'repeat': false 'time': 3 } { 'name': 'happy_grin' 'flexSequence': 'happy_grin' 'autostart': false 'repeat': false 'time': 3 } { 'name': 'duck' 'flexSequence': 'duck' 'autostart': false 'repeat': false 'time': 3 } { 'name': 'duck_insanity' 'flexSequence': 'duck_insanity' 'autostart': false 'repeat': false 'time': 3 } { 'name': 'duck_quack' 'flexSequence': 'duck_quack' 'flexSequence': 'duck_quack' 'autostart': false 'repeat': false 'time': 5 } { 'name': 'hurt' 'flexSequence': 'hurt' 'bonesSequence': 'floppy_ears_weak' 'autostart': false 'repeat': false 'time': 4 'reset': => @SetControllerModifier('IrisSizeInternal', -0.3) } { 'name': 'kill_grin' 'flexSequence': 'kill_grin' 'autostart': false 'repeat': false 'time': 8 } { 'name': 'greeny' 'flexSequence': 'greeny' 'autostart': false 'repeat': false 'time': 2 } { 'name': 'big_grin' 'flexSequence': 'big_grin' 'autostart': false 'repeat': false 'time': 3 } { 'name': 'o3o' 'flexSequence': 'o3o' 'autostart': false 'repeat': false 'time': 3 } { 'name': 'xd' 'flexSequence': 'xd' 'autostart': false 'repeat': false 'time': 3 } { 'name': 'tongue' 'flexSequence': 'tongue' 'autostart': false 'repeat': false 'time': 3 } { 'name': 'angry_tongue' 'flexSequence': 'angry_tongue' 'bonesSequence': 'forward_ears' 'autostart': false 'repeat': false 'time': 6 } { 'name': 'pffff' 'flexSequence': 'pffff' 'bonesSequence': 'forward_ears' 'autostart': false 'repeat': false 'time': 6 } { 'name': 'cat' 'flexSequence': 'cat' 'autostart': false 'repeat': false 'time': 5 } { 'name': 'talk' 'flexSequence': 'talk' 'autostart': false 'repeat': false 'time': 1.25 } { 'name': 'ooo' 'flexSequence': 'ooo' 'bonesSequence': 'neck_flopping_backward' 'autostart': false 'repeat': false 'time': 2 } { 'name': 'anger' 'flexSequence': 'anger' 'bonesSequence': 'forward_ears' 'autostart': false 'repeat': false 'time': 4 'reset': => @SetControllerModifier('IrisSizeInternal', -0.2) } { 'name': 'ugh' 'flexSequence': 'ugh' 'autostart': false 'repeat': false 'time': 5 'reset': => } { 'name': 'lips_licking' 'flexSequence': 'lips_lick' 'autostart': false 'repeat': false 'time': 5 'reset': => } { 'name': 'lips_licking_suggestive' 'bonesSequence': 'floppy_ears_weak' 'flexSequence': {'lips_lick', 'face_smirk', 'suggestive_eyes'} 'autostart': false 'repeat': false 'time': 4 'reset': => } { 'name': 'suggestive_eyes' 'flexSequence': {'suggestive_eyes'} 'autostart': false 'repeat': false 'time': 4 'reset': => } { 'name': 'suggestive' 'bonesSequence': 'floppy_ears_weak' 'flexSequence': {'suggestive_eyes', 'tongue_pullout', 'suggestive_open'} 'autostart': false 'repeat': false 'time': 4 'reset': => } { 'name': 'suggestive_wo' 'bonesSequence': 'floppy_ears_weak' 'flexSequence': {'suggestive_eyes', 'suggestive_open_anim'} 'autostart': false 'repeat': false 'time': 4 'reset': => } { 'name': 'wild' 'bonesSequence': 'neck_backward' 'autostart': false 'repeat': false 'time': 3 'reset': => @SetControllerModifier('IrisSizeInternal', -0.5) @PlayBonesSequence(math.random(1, 100) > 50 and 'neck_left' or 'neck_right') } { 'name': 'owo_alternative' 'flexSequence': 'owo_alternative' 'autostart': false 'repeat': false 'time': 8 'reset': => @SetControllerModifier('IrisSizeInternal', math.Rand(0.1, 0.3)) } { 'name': 'licking' 'bonesSequence': 'neck_twitch_fast' 'flexSequence': 'tongue_pullout_twitch_fast' 'autostart': false 'repeat': false 'time': 6 } } @SequenceObject = ExpressionSequence new: (controller) => super(controller) @renderController = controller @Hook('PPM2_HurtAnimation', @PPM2_HurtAnimation) @Hook('PPM2_KillAnimation', @PPM2_KillAnimation) @Hook('PPM2_AngerAnimation', @PPM2_AngerAnimation) @Hook('PPM2_EmoteAnimation', @PPM2_EmoteAnimation) @Hook('OnPlayerChat', @OnPlayerChat) @ResetSequences() PPM2_HurtAnimation: (ply = NULL) => return if ply ~= @GetEntity() @RestartSequence('hurt') @EndSequence('kill_grin') PPM2_KillAnimation: (ply = NULL) => return if ply ~= @GetEntity() @RestartSequence('kill_grin') @EndSequence('anger') PPM2_AngerAnimation: (ply = NULL) => return if ply ~= @GetEntity() @EndSequence('kill_grin') @RestartSequence('anger') OnPlayerChat: (ply = NULL, text = '', teamOnly = false, isDead = false) => return if ply ~= @GetEntity() or teamOnly or isDead text = text\lower() switch text when 'o', ':o', 'о', 'О', ':о', ':О' @RestartSequence('ooo') when ':3', ':з' @RestartSequence('cat') when ':d' @RestartSequence('big_grin') when 'xd', 'exdi' @RestartSequence('xd') when ':p' @RestartSequence('tongue') when '>:p', '>:р', '>:Р' @RestartSequence('angry_tongue') when ':р', ':Р' @RestartSequence('tongue') when ':c', 'o3o', 'oops', ':С', ':с', '(', ':(' @RestartSequence('sad') when 'sorry' @RestartSequence('sorry') when 'okay mate', 'okay, mate' @RestartSequence('wink_left') else if text\find('hehehe') or text\find('hahaha') @RestartSequence('greeny') elseif text\find('^pff+') @RestartSequence('pffff') elseif text\find('^blah blah') @RestartSequence('blahblah') else @RestartSequence('talk') PPM2_EmoteAnimation: (ply = NULL, emote = '', time, isEndless = false, shouldStop = false) => return if ply ~= @GetEntity() for _, {:sequence} in ipairs PPM2.AVALIABLE_EMOTES if shouldStop or sequence ~= emote @EndSequence(sequence) if not shouldStop seqPlay = @RestartSequence(emote, time) if not seqPlay PPM2.Message("Unknown Emote - #{emote}!") print(seqPlay, @isValid) print(debug.traceback()) return seqPlay\SetInfinite(isEndless) seqPlay\RestartChildren() DataChanges: (state) => PPM2.GetPonyExpressionsController = (...) -> PPM2.PonyExpressionsController\SelectController(...)
24.596774
160
0.646475
dd059908a37a6d6ad319018149c424f9af3c59df
265
import Model from require "lapis.db.model" export class Users extends Model @timestamp: true write_session: (r) => r.session.user = @id r.session.name = @name read_session: (r) => if r.session.user return @find id: r.session.user nil
18.928571
42
0.65283
ed8b2c5d02e2a3f2d12d788e03206afc6bfe1a80
4,538
-- -- Copyright (C) 2017-2019 DBot -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. ALLOW_ONLY_RAGDOLLS = CreateConVar('ppm2_sv_edit_ragdolls_only', '0', {FCVAR_NOTIFY, FCVAR_REPLICATED}, 'Allow to edit only ragdolls') DISALLOW_PLAYERS = CreateConVar('ppm2_sv_edit_no_players', '1', {FCVAR_NOTIFY, FCVAR_REPLICATED}, 'When unrestricted edit allowed, do not allow to edit players.') genericEditFilter = (ent = NULL, ply = NULL) => return false if not IsValid(ent) return false if not IsValid(ply) return false if not ent\IsPony() return false if ALLOW_ONLY_RAGDOLLS\GetBool() and ent\GetClass() ~= 'prop_ragdoll' return false if DISALLOW_PLAYERS\GetBool() and ent\IsPlayer() return false if not ply\GetPonyData() return false if not hook.Run('CanProperty', ply, 'ponydata', ent) return false if not hook.Run('CanTool', ply, {Entity: ent, HitPos: ent\GetPos(), HitNormal: Vector()}, 'ponydata') return true applyPonyData = { MenuLabel: 'Apply pony data...' Order: 2500 MenuIcon: 'icon16/user.png' MenuOpen: (menu, ent = NULL, tr) => return if not IsValid(ent) with menu\AddSubMenu() \AddOption 'Use Local data', -> net.Start('PPM2.RagdollEdit') net.WriteEntity(ent) net.WriteBool(true) net.SendToServer() \AddSpacer() for _, fil in ipairs PPM2.PonyDataInstance\FindFiles() \AddOption "Use '#{fil}' data", -> net.Start('PPM2.RagdollEdit') net.WriteEntity(ent) net.WriteBool(false) data = PPM2.PonyDataInstance(fil, nil, true, true, false) data\WriteNetworkData() net.SendToServer() Filter: genericEditFilter Action: (ent = NULL) => } ponyDataFlexEnable = { MenuLabel: 'Enable flexes' Order: 2501 MenuIcon: 'icon16/emoticon_smile.png' MenuOpen: (menu, ent = NULL, tr) => Filter: (ent = NULL, ply = NULL) => return false if not genericEditFilter(@, ent, ply) return false if not ent\GetPonyData() return false if not ent\GetPonyData()\GetNoFlex() return true Action: (ent = NULL) => return if not IsValid(ent) net.Start 'PPM2.RagdollEditFlex' net.WriteEntity(ent) net.WriteBool(false) net.SendToServer() } ponyDataFlexDisable = { MenuLabel: 'Disable flexes' Order: 2501 MenuIcon: 'icon16/emoticon_unhappy.png' MenuOpen: (menu, ent = NULL, tr) => Filter: (ent = NULL, ply = NULL) => return false if not genericEditFilter(@, ent, ply) return false if not ent\GetPonyData() return false if ent\GetPonyData()\GetNoFlex() return true Action: (ent = NULL) => return if not IsValid(ent) net.Start 'PPM2.RagdollEditFlex' net.WriteEntity(ent) net.WriteBool(true) net.SendToServer() } playEmote = { MenuLabel: 'Play pony emote' Order: 2502 MenuIcon: 'icon16/emoticon_wink.png' MenuOpen: (menu, ent = NULL, tr) => return if not IsValid(ent) with menu\AddSubMenu() for _, {:name, :sequence, :id, :time} in ipairs PPM2.AVALIABLE_EMOTES \AddOption "Play '#{name}' emote", -> net.Start('PPM2.RagdollEditEmote') net.WriteEntity(ent) net.WriteUInt(id, 8) net.SendToServer() hook.Call('PPM2_EmoteAnimation', nil, ent, sequence, time) Filter: (ent = NULL, ply = NULL) => return false if not genericEditFilter(@, ent, ply) return false if not ent\GetPonyData() return false if ent\GetPonyData()\GetNoFlex() return true Action: (ent = NULL) => } properties.Add('ppm2.applyponydata', applyPonyData) properties.Add('ppm2.enableflex', ponyDataFlexEnable) properties.Add('ppm2.disableflex', ponyDataFlexDisable) properties.Add('ppm2.playemote', playEmote)
35.453125
162
0.721463
1ac6d4da120743eb754b1013b0597751da661cc5
13,988
socket = require "kpgmoon.socket" import insert from table import rshift, lshift, band from require "bit" unpack = table.unpack or unpack VERSION = "1.8.1" _len = (thing, t=type(thing)) -> switch t when "string" #thing when "table" l = 0 for inner in *thing inner_t = type inner if inner_t == "string" l += #inner else l += _len inner, inner_t l else error "don't know how to calculate length of #{t}" _debug_msg = (str) -> require("moon").dump [p for p in str\gmatch "[^%z]+"] flipped = (t) -> keys = [k for k in pairs t] for key in *keys t[t[key]] = key t MSG_TYPE = flipped { status: "S" auth: "R" backend_key: "K" ready_for_query: "Z" query: "Q" notice: "N" notification: "A" password: "p" row_description: "T" data_row: "D" command_complete: "C" error: "E" } ERROR_TYPES = flipped { severity: "S" code: "C" message: "M" position: "P" detail: "D" schema: "s" table: "t" constraint: "n" } PG_TYPES = { [16]: "boolean" [17]: "bytea" [20]: "number" -- int8 [21]: "number" -- int2 [23]: "number" -- int4 [700]: "number" -- float4 [701]: "number" -- float8 [1700]: "number" -- numeric [114]: "json" -- json [3802]: "json" -- jsonb -- arrays [1000]: "array_boolean" -- bool array [1005]: "array_number" -- int2 array [1007]: "array_number" -- int4 array [1016]: "array_number" -- int8 array [1021]: "array_number" -- float4 array [1022]: "array_number" -- float8 array [1231]: "array_number" -- numeric array [1009]: "array_string" -- text array [1015]: "array_string" -- varchar array [1002]: "array_string" -- char array [1014]: "array_string" -- bpchar array [2951]: "array_string" -- uuid array [199]: "array_json" -- json array [3807]: "array_json" -- jsonb array } NULL = "\0" tobool = (str) -> str == "t" class Postgres convert_null: false NULL: {"NULL"} :PG_TYPES user: "postgres" host: "127.0.0.1" port: "5432" ssl: false -- custom types supplementing PG_TYPES type_deserializers: { json: (val, name) => import decode_json from require "kpgmoon.json" decode_json val bytea: (val, name) => @decode_bytea val array_boolean: (val, name) => import decode_array from require "kpgmoon.arrays" decode_array val, tobool array_number: (val, name) => import decode_array from require "kpgmoon.arrays" decode_array val, tonumber array_string: (val, name) => import decode_array from require "kpgmoon.arrays" decode_array val array_json: (val, name) => import decode_array from require "kpgmoon.arrays" import decode_json from require "kpgmoon.json" decode_array val, decode_json hstore: (val, name) => import decode_hstore from require "kpgmoon.hstore" decode_hstore val } set_type_oid: (oid, name) => unless rawget(@, "PG_TYPES") @PG_TYPES = {k,v for k,v in pairs @PG_TYPES} @PG_TYPES[assert tonumber oid] = name setup_hstore: => res = unpack @query "SELECT oid FROM pg_type WHERE typname = 'hstore'" assert res, "hstore oid not found" @set_type_oid tonumber(res.oid), "hstore" new: (opts) => @sock, @sock_type = socket.new opts and opts.socket_type if opts @user = opts.user @host = opts.host @database = opts.database @port = opts.port @password = opts.password @ssl = opts.ssl @ssl_verify = opts.ssl_verify @ssl_required = opts.ssl_required @pool_name = opts.pool @luasec_opts = { key: opts.key cert: opts.cert cafile: opts.cafile } connect: => opts = if @sock_type == "nginx" { pool: @pool_name or "#{@host}:#{@port}:#{@database}" } ok, err = @sock\connect @host, @port, opts return nil, err unless ok if @sock\getreusedtimes! == 0 if @ssl success, err = @send_ssl_message! return nil, err unless success success, err = @send_startup_message! return nil, err unless success success, err = @auth! return nil, err unless success success, err = @wait_until_ready! return nil, err unless success true settimeout: (...) => @sock\settimeout ... disconnect: => sock = @sock @sock = nil sock\close! keepalive: (...) => sock = @sock @sock = nil sock\setkeepalive ... auth: => t, msg = @receive_message! return nil, msg unless t unless MSG_TYPE.auth == t @disconnect! if MSG_TYPE.error == t return nil, @parse_error msg error "unexpected message during auth: #{t}" auth_type = @decode_int msg, 4 switch auth_type when 0 -- trust true when 3 -- cleartext password @cleartext_auth msg when 5 -- md5 password @md5_auth msg else error "don't know how to auth: #{auth_type}" cleartext_auth: (msg) => assert @password, "missing password, required for connect" @send_message MSG_TYPE.password, { @password NULL } @check_auth! md5_auth: (msg) => import md5 from require "kpgmoon.crypto" salt = msg\sub 5, 8 assert @password, "missing password, required for connect" @send_message MSG_TYPE.password, { "md5" md5 md5(@password .. @user) .. salt NULL } @check_auth! check_auth: => t, msg = @receive_message! return nil, msg unless t switch t when MSG_TYPE.error nil, @parse_error msg when MSG_TYPE.auth true else error "unknown response from auth" query: (q) => @post q local row_desc, data_rows, command_complete, err_msg local result, notifications num_queries = 0 while true t, msg = @receive_message! return nil, msg unless t switch t when MSG_TYPE.data_row data_rows or= {} insert data_rows, msg when MSG_TYPE.row_description row_desc = msg when MSG_TYPE.error err_msg = msg when MSG_TYPE.command_complete command_complete = msg next_result = @format_query_result row_desc, data_rows, command_complete num_queries += 1 if num_queries == 1 result = next_result elseif num_queries == 2 result = { result, next_result } else insert result, next_result row_desc, data_rows, command_complete = nil when MSG_TYPE.ready_for_query break when MSG_TYPE.notification notifications = {} unless notifications insert notifications, @parse_notification(msg) -- when MSG_TYPE.notice -- TODO: do something with notices else if ngx then ngx.log(ngx.ERR, "received unhandled MSG_TYPE: ", tostring(t), " (msg: ", tostring(msg), ")") if err_msg if ngx then ngx.log(ngx.DEBUG, "returning err_msg") return nil, @parse_error(err_msg), result, num_queries, notifications if ngx then ngx.log(ngx.DEBUG, "returning result, num_queries") result, num_queries, notifications post: (q) => @send_message MSG_TYPE.query, {q, NULL} wait_for_notification: => while true t, msg = @receive_message! return nil, msg unless t switch t when MSG_TYPE.notification return @parse_notification(msg) format_query_result: (row_desc, data_rows, command_complete) => local command, affected_rows if command_complete command = command_complete\match "^%w+" affected_rows = tonumber command_complete\match "%d+%z$" if row_desc return {} unless data_rows fields = @parse_row_desc row_desc num_rows = #data_rows for i=1,num_rows data_rows[i] = @parse_data_row data_rows[i], fields if affected_rows and command != "SELECT" data_rows.affected_rows = affected_rows return data_rows if affected_rows { :affected_rows } else true parse_error: (err_msg) => local severity, message, detail, position error_data = {} offset = 1 while offset <= #err_msg t = err_msg\sub offset, offset str = err_msg\match "[^%z]+", offset + 1 break unless str offset += 2 + #str if field = ERROR_TYPES[t] error_data[field] = str switch t when ERROR_TYPES.severity severity = str when ERROR_TYPES.message message = str when ERROR_TYPES.position position = str when ERROR_TYPES.detail detail = str msg = "#{severity}: #{message}" if position msg = "#{msg} (#{position})" if detail msg = "#{msg}\n#{detail}" msg, error_data parse_row_desc: (row_desc) => num_fields = @decode_int row_desc\sub(1,2) offset = 3 fields = for i=1,num_fields name = row_desc\match "[^%z]+", offset offset += #name + 1 -- 4: object id of table -- 2: attribute number of column (4) -- 4: object id of data type (6) data_type = @decode_int row_desc\sub offset + 6, offset + 6 + 3 data_type = @PG_TYPES[data_type] or "string" -- 2: data type size (10) -- 4: type modifier (12) -- 2: format code (16) -- we only know how to handle text format = @decode_int row_desc\sub offset + 16, offset + 16 + 1 assert 0 == format, "don't know how to handle format" offset += 18 {name, data_type} fields parse_data_row: (data_row, fields) => -- 2: number of values num_fields = @decode_int data_row\sub(1,2) out = {} offset = 3 for i=1,num_fields field = fields[i] continue unless field {field_name, field_type} = field -- 4: length of value len = @decode_int data_row\sub offset, offset + 3 offset += 4 if len < 0 out[field_name] = @NULL if @convert_null continue value = data_row\sub offset, offset + len - 1 offset += len switch field_type when "number" value = tonumber value when "boolean" value = value == "t" when "string" nil else if fn = @type_deserializers[field_type] value = fn @, value, field_type out[field_name] = value out parse_notification: (msg) => pid = @decode_int msg\sub 1, 4 offset = 4 channel, payload = msg\match "^([^%z]+)%z([^%z]*)%z$", offset + 1 unless channel error "parse_notification: failed to parse notification" { operation: "notification" pid: pid channel: channel payload: payload } wait_until_ready: => while true t, msg = @receive_message! return nil, msg unless t if MSG_TYPE.error == t @disconnect! return nil, @parse_error(msg) break if MSG_TYPE.ready_for_query == t true receive_message: => t, err = @sock\receive 1 unless t @disconnect! return nil, "receive_message: failed to get type: #{err}" len, err = @sock\receive 4 unless len @disconnect! return nil, "receive_message: failed to get len: #{err}" len = @decode_int len len -= 4 msg = @sock\receive len t, msg send_startup_message: => assert @user, "missing user for connect" assert @database, "missing database for connect" data = { @encode_int 196608 "user", NULL @user, NULL "database", NULL @database, NULL NULL } @sock\send { @encode_int _len(data) + 4 data } send_ssl_message: => success, err = @sock\send { @encode_int 8, @encode_int 80877103 } return nil, err unless success t, err = @sock\receive 1 return nil, err unless t if t == MSG_TYPE.status if @sock_type == "nginx" @sock\sslhandshake false, nil, @ssl_verify else @sock\sslhandshake @ssl_verify, @luasec_opts elseif t == MSG_TYPE.error or @ssl_required @disconnect! nil, "the server does not support SSL connections" else true -- no SSL support, but not required by client send_message: (t, data, len=nil) => len = _len data if len == nil len += 4 -- includes the length of the length integer @sock\send { t @encode_int len data } decode_int: (str, bytes=#str) => switch bytes when 4 d, c, b, a = str\byte 1, 4 a + lshift(b, 8) + lshift(c, 16) + lshift(d, 24) when 2 b, a = str\byte 1, 2 a + lshift(b, 8) else error "don't know how to decode #{bytes} byte(s)" -- create big endian binary string of number encode_int: (n, bytes=4) => switch bytes when 4 a = band n, 0xff b = band rshift(n, 8), 0xff c = band rshift(n, 16), 0xff d = band rshift(n, 24), 0xff string.char d, c, b, a else error "don't know how to encode #{bytes} byte(s)" decode_bytea: (str) => if str\sub(1, 2) == '\\x' str\sub(3)\gsub '..', (hex) -> string.char tonumber hex, 16 else str\gsub '\\(%d%d%d)', (oct) -> string.char tonumber oct, 8 encode_bytea: (str) => string.format "E'\\\\x%s'", str\gsub '.', (byte) -> string.format '%02x', string.byte byte escape_identifier: (ident) => '"' .. (tostring(ident)\gsub '"', '""') .. '"' escape_literal: (val) => switch type val when "number" return tostring val when "string" return "'#{(val\gsub "'", "''")}'" when "boolean" return val and "TRUE" or "FALSE" error "don't know how to escape value: #{val}" __tostring: => "<Postgres socket: #{@sock}>" { :Postgres, new: Postgres, :VERSION }
23.082508
82
0.5835
c7d56772d2bebca605af5df4dcc8ef20576a6c40
484
log = require 'log' class Date new: => @sec = 0 @usec = 0 @now: => ret = Date() sntp.sync "stdtime.gov.hk", => ret.sec, ret.usec = rtctime.get() return ret -- retrun milli seconds for current date - adate __sub: (adate) => return (@sec - adate.sec) * 1000 + (@usec - adate.usec) / 1000 __tostring: => tm = rtctime.epoch2cal @sec return "#{tm['year']}.#{tm['mon']}.#{tm['day']} #{tm['hour']}:#{tm['min']}:#{tm['sec']}" return Date
21.043478
92
0.53719
19bbe733bd4e702a3518569befad928b61a00fb9
38,383
-- Copyright (C) 2018-2020 DBotThePony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -- of the Software, and to permit persons to whom the Software is furnished to do so, -- subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies -- or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE -- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. gui.dpp2.access.status.contraption = 'Конструкция' gui.dpp2.access.status.contraption_ext = 'Конструкция <%d>' gui.dpp2.access.status.map = 'Карта' gui.dpp2.access.status.world = 'Без владельца' gui.dpp2.access.status.friend = 'Не является другом владельца' gui.dpp2.access.status.invalident = 'Неверная сущность' gui.dpp2.access.status.disabled = 'Защита отключена' gui.dpp2.access.status.ownerdisabled = 'Защита для владельца отключена' gui.dpp2.access.status.yoursettings = 'Ваши настройки' gui.dpp2.access.status.toolgun_player = 'Невозможно использовать Инструмент на игроке' gui.dpp2.access.status.model_blacklist = 'Модель в черном списке' gui.dpp2.access.status.toolgun_mode_blocked = 'Использование этого Инструмента ограничено' gui.dpp2.access.status.toolgun_mode_excluded = 'Использование этого Инструмента разрешено' gui.dpp2.access.status.lock_self = 'Ваш собственный блок' gui.dpp2.access.status.lock_other = 'Блок остальных' gui.dpp2.access.status.no_surf = 'Анти-сёрф' gui.dpp2.access.status.damage_allowed = 'Урон разрешён' message.dpp2.owning.owned = 'Теперь вы являетесь владельцем этой сущности' message.dpp2.owning.owned_contraption = 'Теперь вы являетесь владельцем этой конструкции' message.dpp2.notice.upforgrabs = 'Сущности %s теперь доступны для забора!' message.dpp2.notice.cleanup = 'Сущности %s были удалены.' message.dpp2.warn.trap = 'Ваша сущность, возможно, застряла в другом игроке. Взаимодействие с сущностью снимет статус призрака!' message.dpp2.warn.collisions = 'Ваша сущность, возможно, застряла в другой сущности. Взаимодействие с сущностью снимет статус призрака!' message.dpp2.restriction.spawn = 'Сущность %q ограничена для вашей пользовательской группы' message.dpp2.restriction.e2fn = 'DPP/2: Expression 2 функция %q ограничена для вашей пользовательской группы' gui.dpp2.chosepnl.buttons.to_chosen = 'Выбрать >' gui.dpp2.chosepnl.buttons.to_available = '< Убрать' gui.dpp2.chosepnl.column.available = 'Доступно' gui.dpp2.chosepnl.column.chosen = 'Выбрано' gui.dpp2.chosepnl.add.add = 'Добавить' gui.dpp2.chosepnl.add.entry = 'Добавить собственный вариант' gui.dpp2.restriction.is_whitelist = 'Список групп работает как белый список' gui.dpp2.restriction.edit_title = 'Редактирование ограничения %q' gui.dpp2.restriction.edit_multi_title = 'Редактирование нескольких ограничений' gui.dpp2.cvars.protection = 'Главный рубильник защиты' gui.dpp2.cvars.autocleanup = 'Удалять сущности игроков по таймеру' gui.dpp2.cvars.autocleanup_timer = 'Таймер удаления' gui.dpp2.cvars.autofreeze = 'Замораживать физические сущности' gui.dpp2.cvars.autoghost = 'Делать призраком вместо заморозки' message.dpp2.notice.frozen = 'Сущности %s теперь заморожены!' gui.dpp2.cvars.upforgrabs = 'Включить таймер для забора' gui.dpp2.cvars.upforgrabs_timer = 'Время до забора' gui.dpp2.cvars.no_tool_player = 'Запретить использовать Инструмент на игроках' gui.dpp2.cvars.no_tool_player_admin = 'Запретить использовать Инструмент на игроках как администратор' for {modeID, modeName} in *{{'physgun', 'Физпушка'}, {'toolgun', 'Инструмент'}, {'drive', 'Управление сущностями'}, {'damage', 'Урон'}, {'pickup', 'Подбор'}, {'use', 'Использование'}, {'vehicle', 'Транспортные средства'}, {'gravgun', 'Гравипушка'}} gui.dpp2.cvars[modeID .. '_protection'] = string.format('Включить модуль защиты %q', modeName) gui.dpp2.cvars[modeID .. '_touch_any'] = string.format('%s: Администраторы могут использовать все', modeName) gui.dpp2.cvars[modeID .. '_no_world'] = string.format('%s: Запретить игрокам использовать сущности без владельца', modeName) gui.dpp2.cvars[modeID .. '_no_world_admin'] = string.format('%s: Запретить администраторам использовать сущности без владельца', modeName) gui.dpp2.cvars[modeID .. '_no_map'] = string.format('%s: Запретить игрокам использовать сущности карты', modeName) gui.dpp2.cvars[modeID .. '_no_map_admin'] = string.format('%s: Запретить администраторам использовать сущности карты', modeName) gui.dpp2.cvars['el_' .. modeID .. '_enable'] = string.format('Включить список исключений для %q', modeName) gui.dpp2.cvars['bl_' .. modeID .. '_enable'] = string.format('Включить чёрный список для %q', modeName) gui.dpp2.cvars['bl_' .. modeID .. '_whitelist'] = string.format('Чёрный список %q работает как белый список', modeName) gui.dpp2.cvars['bl_' .. modeID .. '_admin_bypass'] = string.format('Чёрный список %q не распространяется на администраторов', modeName) gui.dpp2.cvars['rl_' .. modeID .. '_enable'] = string.format('Включить список ограничений для %q', modeName) gui.dpp2.cvars['rl_' .. modeID .. '_invert'] = string.format('Инвентировать список ограничений для %q', modeName) gui.dpp2.cvars['rl_' .. modeID .. '_invert_all'] = string.format('Полностью инвентировать список ограничений для %q', modeName) gui.dpp2.cvars['cl_' .. modeID .. '_protection'] = string.format('Включить модуль защиты %q для моих сущностей', modeName) gui.dpp2.cvars['cl_' .. modeID .. '_no_other'] = string.format('%s: Запретить использовать сущности других игроков', modeName) gui.dpp2.cvars['cl_' .. modeID .. '_no_world'] = string.format('%s: Запретить использовать сущности без владельца', modeName) gui.dpp2.cvars['cl_' .. modeID .. '_no_map'] = string.format('%s: Запретить использовать сущности карты', modeName) gui.dpp2.cvars['cl_' .. modeID .. '_no_players'] = string.format('%s: Я не хочу действовать на игроков', modeName) gui.dpp2.buddystatus[modeID] = 'Товарищ в ' .. modeName gui.dpp2.toolmenu.restrictions[modeID] = 'Ограничения ' .. modeName gui.dpp2.toolmenu.blacklist[modeID] = 'Чёрный список ' .. modeName gui.dpp2.toolmenu.exclusions[modeID] = 'Исключения ' .. modeName gui.dpp2.toolmenu.names[modeID] = modeName gui.dpp2.property.lock_self[modeID] = 'Заблокировать использование ' .. modeName gui.dpp2.property.unlock_self[modeID] = 'Разрешить использование ' .. modeName gui.dpp2.property.lock_others[modeID] = gui.dpp2.property.lock_self[modeID] gui.dpp2.property.unlock_others[modeID] = gui.dpp2.property.unlock_self[modeID] command.dpp2.lock_self[modeID] = 'Использование #E в модуле ' .. modeName .. ' успешно заблокировано' command.dpp2.unlock_self[modeID] = 'Использование #E в модуле ' .. modeName .. ' успешно разблокировано' command.dpp2.lock_others[modeID] = 'Использование #E в модуле ' .. modeName .. ' для остальных успешно заблокировано' command.dpp2.unlock_others[modeID] = 'Использование #E в модуле ' .. modeName .. ' для остальных успешно разблокировано' command.dpp2.blacklist.added[modeID] = '#E добавил %s в чёрный список ' .. modeName command.dpp2.blacklist.removed[modeID] = '#E удалил %s из чёрного списка ' .. modeName command.dpp2.exclist.added[modeID] = '#E добавил %s из списка исключений ' .. modeName command.dpp2.exclist.removed[modeID] = '#E удалил %s из списка исключений ' .. modeName gui.dpp2.menu['add_to_' .. modeID .. '_blacklist'] = 'Добавить в чёрный список ' .. modeName gui.dpp2.menu['remove_from_' .. modeID .. '_blacklist'] = 'Удалить из чёрного списка ' .. modeName gui.dpp2.menu['add_to_' .. modeID .. '_exclist'] = 'Добавить в список исключений ' .. modeName gui.dpp2.menu['remove_from_' .. modeID .. '_exclist'] = 'Удалить из списка исключений' .. modeName gui.dpp2.menu['add_to_' .. modeID .. '_restrictions'] = 'Добавить в список ограничений ' .. modeName .. '...' gui.dpp2.menu['edit_in_' .. modeID .. '_restrictions'] = 'Редактировать в списке ограничений ' .. modeName gui.dpp2.menu['remove_from_' .. modeID .. '_restrictions'] = 'Удалить из списка ограничений ' .. modeName gui.dpp2.menu['add_to_' .. modeID .. '_limits'] = 'Добавить в список лимитов ' .. modeName .. '...' gui.dpp2.menu['edit_in_' .. modeID .. '_limits'] = 'Редактировать с списке лимитов ' .. modeName gui.dpp2.menu['remove_from_' .. modeID .. '_limits'] = 'Удалить из списка лимитов ' .. modeName gui.dpp2.disable_protection[modeID] = 'Отключить модуль защиты ' .. modeName command.dpp2.rlists.added[modeID] = '#E добавил %q в список ограничений ' .. modeName .. ' с флажком белого списка на %s' command.dpp2.rlists.added_ext[modeID] = '#E добавил %q в список ограничений ' .. modeName .. ' с группами %q и с флажком белого списка на %s' command.dpp2.rlists.updated[modeID] = '#E изменил %q в ' .. modeName .. ' с группами %q и с флажком белого списка на %s' command.dpp2.rlists.removed[modeID] = '#E удалил %q из списка ограничений ' .. modeName command.dpp2.enabled_for[modeID] = '#E включил модуль защиты ' .. modeName .. ' для #E' command.dpp2.disabled_for[modeID] = '#E отключил модуль защиты ' .. modeName .. ' для #E' command.dpp2.already_disabled_for[modeID] = 'Модуль защиты ' .. modeName .. ' для #E уже отключен!' command.dpp2.already_enabled_for[modeID] = 'Модуль защиты ' .. modeName .. ' для #E уже включен!' gui.dpp2.access.status['ownerdisabled_' .. modeID] = 'Защита ' .. modeName .. ' для владельца отключена' gui.dpp2.access.status[modeID .. '_exclusion'] = 'Сущность находится в списке исключений' gui.dpp2.sharing['share_' .. modeID] = 'Поделится в ' .. modeName command.dpp2.rlists.added.model = '#E добавил %q в список ограничения моделей с флажком белого списка на %s' command.dpp2.rlists.added_ext.model = '#E добавил %q в список ограничения моделей с группами %q и с флажком белого списка на %s' command.dpp2.rlists.updated.model = '#E изменил %q в списке ограничения моделей с группами %q и с флажком белого списка на %s' command.dpp2.rlists.removed.model = '#E удалил %q из списка ограничения моделей' command.dpp2.rlists.added.e2fn = '#E добавил %q в список ограничений Expression 2 Function с флажком белого списка на %s' command.dpp2.rlists.added_ext.e2fn = '#E добавил %q в список ограничений Expression 2 Function с группами %q и с флажком белого списка на %s' command.dpp2.rlists.updated.e2fn = '#E изменил %q в список ограничений Expression 2 Function с группами %q и с флажком белого списка на %s' command.dpp2.rlists.removed.e2fn = '#E удалил %q из списка ограничений Expression 2 Function' gui.dpp2.cvars.rl_e2fn_enable = 'Включить список ограничений Expression 2' gui.dpp2.cvars.rl_e2fn_invert = 'Список ограничений Expression 2 инвертирован' gui.dpp2.cvars.rl_e2fn_invert_all = 'Список ограничений Expression 2 полностью инвертирован' do modeID = 'model' gui.dpp2.menu['add_to_' .. modeID .. '_limits'] = 'Добавить в список лимитов моделей...' gui.dpp2.menu['edit_in_' .. modeID .. '_limits'] = 'Редактировать в списке лимитов моделей' gui.dpp2.menu['remove_from_' .. modeID .. '_limits'] = 'Удалить из списка лимитов моделей' gui.dpp2.cvars.rl_enable = 'Включить списки ограничений' gui.dpp2.cvars.bl_enable = 'Включить чёрные списки' gui.dpp2.cvars.excl_enable = 'Включить списки исключений' gui.dpp2.model_blacklist.window_title = 'Визуальный чёрный список моделей' gui.dpp2.model_exclusions.window_title = 'Визуальный список моделей-исключений' gui.dpp2.model_restrictions.window_title = 'Визуальный список ограниченных моделей' gui.dpp2.model_limits.window_title = 'Визуальный список лимитов моделей' gui.dpp2.access.status.model_exclusion = 'Модель в списке исключений' for {modeID, modeName} in *{{'model', 'Модель'}, {'toolgun_mode', 'Инструмент'}, {'class_spawn', 'Сущность'}} gui.dpp2.cvars['el_' .. modeID .. '_enable'] = string.format('Включить список исключений %q', modeName) gui.dpp2.cvars['bl_' .. modeID .. '_enable'] = string.format('Включить чёрный список %q', modeName) gui.dpp2.cvars['bl_' .. modeID .. '_whitelist'] = string.format('Чёрный список %q работает как белый список', modeName) gui.dpp2.cvars['bl_' .. modeID .. '_admin_bypass'] = string.format('Чёрный список %q не распространяется на администраторов', modeName) gui.dpp2.cvars['rl_' .. modeID .. '_enable'] = string.format('Включить список ограничений %q', modeName) gui.dpp2.cvars['rl_' .. modeID .. '_invert'] = string.format('Список ограничений %q инвертирован', modeName) gui.dpp2.cvars['rl_' .. modeID .. '_invert_all'] = string.format('Список ограничений %q полностью инвертирован', modeName) gui.dpp2.menu['add_to_' .. modeID .. '_blacklist'] = 'Добавить в чёрный список ' .. modeName gui.dpp2.menu['remove_from_' .. modeID .. '_blacklist'] = 'Удалить из чёрного списка ' .. modeName gui.dpp2.menu['add_to_' .. modeID .. '_exclist'] = 'Добавить в список исключений ' .. modeName gui.dpp2.menu['remove_from_' .. modeID .. '_exclist'] = 'Удалить из списка исключений ' .. modeName gui.dpp2.menu['add_to_' .. modeID .. '_restrictions'] = 'Добавить в список ограничений ' .. modeName gui.dpp2.menu['edit_in_' .. modeID .. '_restrictions'] = 'Редактировать в списке ограничений ' .. modeName gui.dpp2.menu['remove_from_' .. modeID .. '_restrictions'] = 'Удалить из списка ограничений ' .. modeName gui.dpp2.cvars.no_rope_world = 'Запретить создавать верёвки на мире' gui.dpp2.cvars.log = 'Главный рубильник журнала' gui.dpp2.cvars.log_echo = 'Выводить журнал в консоли сервера' gui.dpp2.cvars.log_echo_clients = 'Выводить журнал в консоли администраторов' gui.dpp2.cvars.log_spawns = 'Записывать в журнал создания сущностей' gui.dpp2.cvars.log_toolgun = 'Записывать в журнал использование Инструмента' gui.dpp2.cvars.log_tranfer = 'Записывать в журнал передачу сущностей' gui.dpp2.cvars.log_write = 'Записывать журнал на диск' gui.dpp2.cvars.physgun_undo = 'Включить историю отмены физпушки' gui.dpp2.cvars.cl_physgun_undo = 'Включить историю отмены физпушки' gui.dpp2.cvars.cl_physgun_undo_custom = 'Использовать отдельную историю для физпушки' gui.dpp2.cvars.allow_damage_npc = 'Всегда разрешать наносить урон НИПам' gui.dpp2.cvars.allow_damage_vehicle = 'Всегда разрешать наносить урон транспортным средствам' gui.dpp2.cvars.cl_protection = 'Главный рубильник клиентской защиты' gui.dpp2.cvars.cl_draw_contraption_aabb = 'Отрисовывать линии вокруг AABB конструкций (может сильно сказаться на производительности)' gui.dpp2.cvars.cl_draw_owner = 'Отображать панель владельца' gui.dpp2.cvars.cl_simple_owner = 'Простая панель владельца (стиль FPP)' gui.dpp2.cvars.cl_entity_name = 'Отображать имена сущностей' gui.dpp2.cvars.cl_entity_info = 'Отображать информацию сущностей' gui.dpp2.cvars.cl_no_contraptions = 'Использовать упрощённую обработку конструкций. Может сильно улучшить производительность с большими конструкциями.' gui.dpp2.cvars.cl_no_players = 'Не отображать панель владельца на других игроках' gui.dpp2.cvars.cl_no_func = 'Не отображать панель владельца на сущностях дверей и func_' gui.dpp2.cvars.cl_no_map = 'Не отображать панель владельца на сущностях во владении карты' gui.dpp2.cvars.cl_no_world = 'Не отображать панель владельца на сущностях без владельца' gui.dpp2.cvars.cl_ownership_in_vehicle = 'Отображать панель владельца будучи находясь в транспортном средстве' gui.dpp2.cvars.cl_ownership_in_vehicle_always = 'Всегда отображать панель владельца будучи находясь в транспортном средстве' gui.dpp2.cvars.cl_notify = 'Отображать уведомления на экране' gui.dpp2.cvars.cl_notify_generic = 'Отображать общие уведомления на экране' gui.dpp2.cvars.cl_notify_error = 'Отображать уведомления об ошибках на экране' gui.dpp2.cvars.cl_notify_hint = 'Отображать подсказки на экране' gui.dpp2.cvars.cl_notify_undo = 'Отображать уведомления об отмене на экране' gui.dpp2.cvars.cl_notify_cleanup = 'Отображать уведомления об очистке на экране' gui.dpp2.cvars.cl_notify_sound = 'Проигрывать звук на уведомлениях' gui.dpp2.cvars.cl_notify_timemul = 'Множитель времени показа уведомлений' gui.dpp2.cvars.cl_properties = 'Отображать DPP/2 в контекстном меню сущностей' gui.dpp2.cvars.cl_properties_regular = 'Отображать общие свойства в контекстном меню сущностей' gui.dpp2.cvars.cl_properties_admin = 'Отображать административные свойства в контекстном меню сущностей' gui.dpp2.cvars.cl_properties_restrictions = 'Отображать ограничивающие свойства в контекстном меню сущностей' gui.dpp2.cvars.draw_owner = 'Серверное переопределение: Отображать панель владельца' gui.dpp2.cvars.simple_owner = 'Серверное переопределение: Простая панель владельца (стиль FPP)' gui.dpp2.cvars.entity_name = 'Серверное переопределение: Отображать имена сущностей' gui.dpp2.cvars.entity_info = 'Серверное переопределение: Отображать информацию сущностей' gui.dpp2.cvars.apropkill = 'Анти пропкилл' gui.dpp2.cvars.apropkill_damage = 'Предотвращать урон от давки' gui.dpp2.cvars.apropkill_damage_nworld = 'Игнорировать давку от сущностей без владельца' gui.dpp2.cvars.apropkill_damage_nveh = 'Игнорировать давку от транспортных средств' gui.dpp2.cvars.apropkill_trap = 'Препятствовать захват игроков сущностями' gui.dpp2.cvars.apropkill_push = 'Препятствовать толканию сущностями игроков' gui.dpp2.cvars.apropkill_throw = 'Препятствовать киданию сущностей физпушкой' gui.dpp2.cvars.apropkill_punt = 'Препятствовать киданию сущностей гравипушкой' gui.dpp2.cvars.apropkill_surf = 'Препятствовать сёрфу на сущностях\n(требует "помощи" со стороны других модификаций,\nтаких как DSit)' gui.dpp2.cvars.antispam = 'Рубильник антиспама' gui.dpp2.cvars.antispam_alt_dupes = 'Альтернативный вариант антиспама для advdupe(2). Данная настройка может ослабить антиспам защиту от гриферов, использующих advdupe(2).' gui.dpp2.cvars.antispam_ignore_admins = 'Антиспам игнорирует администрацию' gui.dpp2.help.antispam_ignore_admins = 'Имейте ввиду, что игнорирование администрации\nможет негативно сказаться на настройке антиспама\nдля обычных игроков в следствие неполного тестирования настроек.' gui.dpp2.cvars.antispam_unfreeze = 'Антиспам разморозки' gui.dpp2.cvars.antispam_unfreeze_div = 'Множитель времени антиспама разморозки' gui.dpp2.cvars.antispam_collisions = 'Препятствовать созданию сущности внутри другой сущности' gui.dpp2.cvars.antispam_spam = 'Препятствовать спаму' gui.dpp2.cvars.antispam_spam_threshold = 'Предел создания сущности как призрака при спаме' gui.dpp2.cvars.antispam_spam_threshold2 = 'Предел удаления сущности при спаме' gui.dpp2.cvars.antispam_spam_cooldown = 'Скорость сброса счётчика спама' gui.dpp2.cvars.antispam_vol_aabb_div = 'Делитель размера AABB' gui.dpp2.cvars.antispam_spam_vol = 'Антиспам на основе объема' gui.dpp2.cvars.antispam_spam_aabb = 'Антиспам на основе размера AABB' gui.dpp2.cvars.antispam_spam_vol_threshold = 'Лимит по объему спама перед созданием как призрак' gui.dpp2.cvars.antispam_spam_vol_threshold2 = 'Лимит по объему спама перед удалением' gui.dpp2.cvars.antispam_spam_vol_cooldown = 'Скорость сброса счётчика объема' gui.dpp2.cvars.antispam_ghost_by_size = 'Создавать сущности как призрак при определенном объеме' gui.dpp2.cvars.antispam_ghost_size = 'Предел объема' gui.dpp2.cvars.antispam_ghost_aabb = 'Создавать сущности как призрак при определенном размере AABB' gui.dpp2.cvars.antispam_ghost_aabb_size = 'Предел размера AABB' gui.dpp2.cvars.antispam_block_by_size = 'Автоматически добавлять в чёрный список при определенном объеме' gui.dpp2.cvars.antispam_block_size = 'Предел объема' gui.dpp2.cvars.antispam_block_aabb = 'Автоматически добавлять в чёрный список при определенном размере AABB' gui.dpp2.cvars.antispam_block_aabb_size = 'Предел размера AABB' message.dpp2.antispam.hint_ghosted = '%d сущностей были созданы как призраки из-за спама' message.dpp2.antispam.hint_removed = '%d сущностей были удалены из-за спама' message.dpp2.antispam.hint_unfreeze_antispam = 'Антиспам разморозки. Попробуйте снова через #.2f секунд' message.dpp2.antispam.hint_disallowed = 'Действие запрещено по причине спама' message.dpp2.antispam.hint_ghosted_single = 'Сущность была создана как призрак из-за спама' message.dpp2.antispam.hint_removed_single = 'Сущность была удалена из-за спама' message.dpp2.antispam.hint_ghosted_big = '%d сущностей были созданы как призраки из-за их размера. Коснитесь их для убора статуса призрака!' message.dpp2.antispam.hint_ghosted_big_single = 'Сущность была создана как призрак из-за их размера. Коснитесь для убора статуса призрака!' command.dpp2.generic.invalid_side = 'Эта команда не может быть выполнена в данном контексте.' command.dpp2.generic.notarget = 'Неверная цель команды!' command.dpp2.generic.no_bots = 'Эта команда не может работать с ботами' command.dpp2.generic.noaccess = 'Вы не можете выполнять данную команду (причина: %s)' command.dpp2.generic.noaccess_check = 'Вы не можете выполнять данную команду на данной цели (причина: %s)' command.dpp2.generic.invalid_time = 'Вы обязаны указать срок блокировки' command.dpp2.cleanup = '#E удалил все сущности #E' command.dpp2.cleanup_plain = '#E cудалил все сущности %s<%s/%s>' command.dpp2.cleardecals = '#E очистил декали' command.dpp2.cleanupgibs = '#E удалил мусорные сущности. #d сущностей было удалено' command.dpp2.cleanupnpcs = '#E удалил всех НИПов #E' command.dpp2.cleanupnpcs_plain = '#E удалил всех НИПов %s<%s/%s>' command.dpp2.cleanupallnpcs = '#E удалил всех НИПов во владении игроков' command.dpp2.cleanupall = '#E удалил все сущности во владении игроков' command.dpp2.cleanupvehicles = '#E удалил все транспортные средства #E' command.dpp2.cleanupvehicles_plain = '#E удалил все транспортные средства %s<%s/%s>' command.dpp2.cleanupallvehicles = '#E удалил все транспортные средства во владении игроков' command.dpp2.freezephys = '#E заморозил все сущности #E' command.dpp2.freezephysall = '#E заморозил все сущности во владении игроков' command.dpp2.freezephyspanic = '#E заморозил все сущности' command.dpp2.cleanupdisconnected = '#E удалил все сущности отключившихся игроков' command.dpp2.ban = '#E запретил игроку #E создавать сущности на срок %s' command.dpp2.indefinitely = 'Неопределённый срок' command.dpp2.permanent_ban = '#E запретил игроку #E создавать сущности на неопределённый срок' command.dpp2.already_banned = 'Цель уже имеет блокировку на создание сущностей на неопределённый срок' command.dpp2.unban.not_banned = 'Цель не имеет блокировки на создание сущностей' command.dpp2.unban.unbanned = '#E разрешил игроку #E создавать сущности' command.dpp2.unban.do_unban = 'Запретить' command.dpp2.hint.none = '<никто>' command.dpp2.hint.player = '<игрок>' command.dpp2.hint.share.not_own_contraption = '<у вас нет сущностей во владении в данной конструкции>' command.dpp2.hint.share.nothing_shared = '<нет сущностей которыми вы поделились>' command.dpp2.hint.share.nothing_to_share = '<нечем делиться>' command.dpp2.hint.share.not_owned = '<не является владельцем>' command.dpp2.transfer.none = 'У вас нет сущностей которые вы могли бы передать.' command.dpp2.transfer.already_ply = 'Вы уже выставили #E как преемника на владение вашими сущностями!' command.dpp2.transfer.none_ply = 'У вас уже нет преемника на владение сущностями!' command.dpp2.transfered = '#E передал права на свои сущности игроку #E' command.dpp2.transferfallback = 'Игрок #E успешно выставлен как преемник прав на ваши сущности' command.dpp2.transferunfallback = 'Преемник успешно убран' message.dpp2.transfer.as_fallback = '%s<%s> передал #d сущностей игроку #E как преемник' message.dpp2.transfer.no_more_fallback = 'Ваш преемник отключился от сервера!' command.dpp2.transferent.notarget = 'Указана неверная сущность' command.dpp2.transfercontraption.notarget = 'Указана неверная конструкция' command.dpp2.transferent.not_owner = 'Вы не являетесь владельцем данной сущности!' command.dpp2.transfercontraption.not_owner = 'Вы не владеете ни одной сущностью в данной конструкции!' command.dpp2.transferent.success = 'Успешно передал #E игроку #E' command.dpp2.transfertoworldent.success = 'Успешно убрал владельца #E' command.dpp2.transfercontraption.success = 'Успешно передал #d сущностей игроку #E' command.dpp2.transfertoworld.success = 'Успешно убрал владельца у #d сущностей' gui.dpp2.property.transferent = 'Передать права на данную сущность...' gui.dpp2.property.transfertoworldent = 'Убрать владельца у данной сущности' gui.dpp2.property.transfercontraption = 'Передалть права на данную конструкцию...' gui.dpp2.property.transfertoworldcontraption = 'Убрать владельца у данной конструкции' gui.dpp2.property.banning = 'DPP/2 бан...' gui.dpp2.property.restrictions = 'Ограничения DPP/2' gui.dpp2.property.lock_self.top = 'Запретить мне...' gui.dpp2.property.unlock_self.top = 'Разрешить мне...' gui.dpp2.property.lock_others.top = 'Запретить другим...' gui.dpp2.property.unlock_others.top = 'Разрешить другим...' message.dpp2.property.transferent.nolongervalid = 'Сущность более не является действительной' message.dpp2.property.transferent.noplayer = 'Целевой игрок отключился от сервера' message.dpp2.property.transfercontraption.nolongervalid = 'Конструкция более не является действительной' message.dpp2.blacklist.model_blocked = 'Модель %s находится в чёрном списке' message.dpp2.blacklist.model_restricted = 'Модель %s ограничена для вашей группы' message.dpp2.blacklist.models_blocked = '#d сущностей были удалены из-за их нахождения в чёрном или ограничивающем списке' message.dpp2.spawn.banned = 'Вам запрещено создавать сущности' message.dpp2.spawn.banned_for = 'Вам запрещено создавать сущности в течение следующих %s' command.dpp2.lists.arg_empty = 'Вы не предоставили аргумент' command.dpp2.lists.group_empty = 'Вы не указали имя группы!' command.dpp2.lists.limit_empty = 'Значение лимита неверно' command.dpp2.lists.already_in = 'Целевой список уже имеет данный элемент!' command.dpp2.lists.already_not = 'Целевой список не имеет данного элемента!' command.dpp2.blacklist.added.model = '#E добавил %s в чёрный список моделей' command.dpp2.blacklist.removed.model = '#E удалил %s из чёрного списка моделей' command.dpp2.exclist.added.model = '#E добавил %s в список исключений моделей' command.dpp2.exclist.removed.model = '#E удалил %s из списка исключений моделей' command.dpp2.exclist.added.toolgun_mode = '#E добавил %s в список исключений инструментов' command.dpp2.exclist.removed.toolgun_mode = '#E удалил %s из списка исключений инструментов' message.dpp2.log.spawn.generic = '#E создал #E' message.dpp2.log.spawn.tried_generic = '#E #C попытался #C создать #E' message.dpp2.log.spawn.tried_plain = '#E #C попытался #C to создать %q' message.dpp2.log.spawn.giveswep = '#E выдал себе #C%s' message.dpp2.log.spawn.giveswep_valid = '#E выдал себе #E' message.dpp2.log.spawn.prop = '#E создал #E [%s]' message.dpp2.log.in_next = 'Журналирование продолжено в %s' message.dpp2.log.transfer.world = '#E убрал владельца сущности #E' message.dpp2.log.transfer.other = '#E передал права на сущность #E к игроку #E' message.dpp2.log.toolgun.regular = '#E использовал инструмент %s на #E' message.dpp2.log.toolgun.property = '#E использовал свойство %s на #E' message.dpp2.log.toolgun.world = '#E использовал инструмент %s на мире' command.dpp2.rlists.added.toolgun_mode = '#E добавил %q to в список ограничений инструментов и с флажком белого списка на %s' command.dpp2.rlists.added_ext.toolgun_mode = '#E добавил %q в список ограничений инструментов с группами %q и с флажком белого списка на %s' command.dpp2.rlists.updated.toolgun_mode = '#E изменил %q в списке ограничений инструментов с группами %q и с флажком белого списка на %s' command.dpp2.rlists.removed.toolgun_mode = '#E удалил %q из списка ограничений инструментов' command.dpp2.rlists.added.class_spawn = '#E добавил %q в список ограничений сущностей с флажком белого списка на %s' command.dpp2.rlists.updated.class_spawn = '#E изменил %q в списке ограничений сущностей с группами %q и с флажком белого списка на %s' command.dpp2.rlists.added_ext.class_spawn = '#E добавил %q в список ограничений сущностей с группами %q и с флажком белого списка на %s' command.dpp2.rlists.removed.class_spawn = '#E удалил %q из списка ограничений сущностей' gui.dpp2.toolcategory.main = 'Основные настройки' gui.dpp2.toolcategory.client = 'Клиентские настройки' gui.dpp2.toolcategory.restriction = 'Списки ограничений' gui.dpp2.toolcategory.blacklist = 'Чёрные списки' gui.dpp2.toolcategory.player = 'Утилиты' gui.dpp2.toolcategory.limits = 'Лимиты' gui.dpp2.toolcategory.exclusions = 'Исключения' gui.dpp2.toolmenu.select_tool = 'Выбрать данный инструмент' gui.dpp2.toolmenu.select_tool2 = 'Достать данный инструмент' gui.dpp2.toolmenu.playermode = 'Защита игроков' gui.dpp2.toolmenu.client_protection = 'Настройки защиты' gui.dpp2.toolmenu.client_settings = 'Общие настройки' gui.dpp2.toolmenu.client_commands = 'Утилиты' gui.dpp2.toolmenu.transfer = 'Передача владения' gui.dpp2.toolmenu.transfer_fallback = 'Преемники' gui.dpp2.toolmenu.primary = 'Основные настройки' gui.dpp2.toolmenu.secondary = 'Вторичные настройки' gui.dpp2.toolmenu.antipropkill = 'Анти-пропкилл' gui.dpp2.toolmenu.antispam = 'Антиспам' gui.dpp2.toolmenu.cleanup = 'Очистка' gui.dpp2.toolmenu.utils = 'Утилиты' gui.dpp2.toolmenu.logging = 'Журналирование' gui.dpp2.toolmenu.restrictions.toolgun_mode = 'Ограничения инструментов (сущности)' gui.dpp2.toolmenu.restrictions.class_spawn = 'Ограничения сущностей' gui.dpp2.toolmenu.restrictions.model = 'Ограничения моделей' gui.dpp2.toolmenu.restrictions.e2fn = 'Ограничения Expression 2' gui.dpp2.toolmenu.exclusions.model = 'Исключения моделей' gui.dpp2.toolmenu.exclusions.toolgun_mode = 'Ограничения режимов инструментов' gui.dpp2.toolmenu.limits.sbox = 'Лимиты песочницы' gui.dpp2.toolmenu.limits.entity = 'Лимиты сущностей' gui.dpp2.toolmenu.limits.model = 'Лимиты моделей' gui.dpp2.toolmenu.playerutil.clear = '%s: удалить сущности' gui.dpp2.toolmenu.playerutil.freezephys = 'З' gui.dpp2.toolmenu.playerutil.freezephys_tip = 'Заморозить сущности данного игрока' gui.dpp2.toolmenu.playerutil.freezephysall = 'Заморозить сущности во владении игроков' gui.dpp2.toolmenu.playerutil.freezephyspanic = 'Заморозить ВСЕ сущности' gui.dpp2.toolmenu.playerutil.clear_all = 'Удалить сущности во владении игроков' gui.dpp2.toolmenu.playerutil.clear_npcs = 'Удалить НИПов во владении игроков' gui.dpp2.toolmenu.playerutil.clear_vehicles = 'Удалить транспортные средства во владении игроков' gui.dpp2.toolmenu.playerutil.clear_disconnected = 'Удалить сущности отключившихся игроков' gui.dpp2.toolmenu.blacklist.model = 'Чёрный список моделей' gui.dpp2.toolmenu.util.cleardecals = 'Очистить декали' gui.dpp2.toolmenu.util.cleanupgibs = 'Удалить мусор' gui.dpp2.restriction_lists.view.classname = 'Имя класса' gui.dpp2.restriction_lists.view.groups = 'Группы' gui.dpp2.restriction_lists.view.iswhitelist = 'Белый список' gui.dpp2.restriction_lists.add_new = 'Добавить...' gui.dpp2.menus.add = 'Добавить новую запись...' gui.dpp2.menus.query.title = 'Добавить новую запись' gui.dpp2.menus.query.subtitle = 'Пожалуйста, введите имя класса нового (или существующего) ограничения' gui.dpp2.menus.edit = 'Изменить...' gui.dpp2.menus.remove = 'Удалить' gui.dpp2.menus.remove2 = 'Подтвердить' gui.dpp2.menus.copy_classname = 'Копировать имя класса' gui.dpp2.menus.copy_groups = 'Копировать группы' gui.dpp2.menus.copy_group = 'Копировать группу' gui.dpp2.menus.copy_limit = 'Копировать лимит' gui.dpp2.property.copymodel = 'Копировать модель' gui.dpp2.property.copyangles = 'Копировать угол' gui.dpp2.property.copyvector = 'Копировать позицию' gui.dpp2.property.copyclassname = 'Копировать имя класса' command.dpp2.setvar.none = 'Не указана консольная переменная' command.dpp2.setvar.invalid = 'Консольная переменная не принадлежит DPP/2: %s' command.dpp2.setvar.no_arg = 'Не указано новое значение' command.dpp2.setvar.changed = '#E изменил значение переменной dpp2_%s' gui.dpp2.sharing.window_title = 'Поделиться' gui.dpp2.property.share = 'Поделиться...' gui.dpp2.property.share_all = 'Поделиться полностью' gui.dpp2.property.un_share_all = 'Более не делиться полностью' gui.dpp2.property.share_contraption = 'Поделиться конструкцией...' command.dpp2.sharing.no_target = 'Не указана цель для общего доступа' command.dpp2.sharing.no_mode = 'Не указан режим для общего доступа' command.dpp2.sharing.invalid_mode = 'Указан неверный режим для общего доступа' command.dpp2.sharing.invalid_entity = 'Указана неверная сущность для общего доступа' command.dpp2.sharing.invalid_contraption = 'Указана неверная конструкция для общего доступа' command.dpp2.sharing.not_owner = 'Вы не можете открыть общий доступ к сущности, которой не владеете' command.dpp2.sharing.already_shared = 'Сущность уже имеет общий доступ в данном режиме' command.dpp2.sharing.shared = '#E теперь имеет общий доступ в режиме %s' command.dpp2.sharing.shared_contraption = 'Все внутри конструкции %d теперь имеет общий доступ в режиме %s' command.dpp2.sharing.already_not_shared = 'Сущность уже не имеет общего доступа в данном режиме' command.dpp2.sharing.un_shared = '#E более не имеет общего доступа в режиме %s' command.dpp2.sharing.un_shared_contraption = 'Все внутри конструкции %d более не имеет общего доступа в режиме %s' command.dpp2.sharing.cooldown = 'Команда на перезарядке, попробуйте снова через #.2f секунд' gui.dpp2.cvars.no_host_limits = 'Для хоста слушающего сервера или одиночной игры лимитов нет' gui.dpp2.cvars.sbox_limits_enabled = 'Включить переопределения лимитов песочницы' gui.dpp2.cvars.sbox_limits_inclusive = 'Список лимитов песочницы исключающий' gui.dpp2.cvars.entity_limits_enabled = 'Включить лимиты на сущности' gui.dpp2.cvars.entity_limits_inclusive = 'Список лимитов на сущности исключающий' gui.dpp2.cvars.model_limits_enabled = 'Включить лимиты на модели' gui.dpp2.cvars.model_limits_inclusive = 'Список лимитов на модели исключающий' gui.dpp2.cvars.limits_lists_enabled = 'Включить списки лимитов' command.dpp2.limit_lists.added.sbox = '#E добавил лимит песочницы %q для группы %s как #d' command.dpp2.limit_lists.removed.sbox = '#E удалил лимит песочницы %q для группы %s' command.dpp2.limit_lists.modified.sbox = '#E изменил лимит песочницы %q для группы %s на #d' command.dpp2.limit_lists.added.entity = '#E добавил лимит сущностей %q для группы %s as #d' command.dpp2.limit_lists.removed.entity = '#E удалил лимит сущностей %q для группы %s' command.dpp2.limit_lists.modified.entity = '#E изменил лимит сущностей %q для группы %s на #d' command.dpp2.limit_lists.added.model = '#E добавил лимит моделей %q для группы %s как #d' command.dpp2.limit_lists.removed.model = '#E удалил лимит моделей %q для группы %s' command.dpp2.limit_lists.modified.model = '#E изменил лимит моделей %q для группы %s на #d' gui.dpp2.limit_lists.view.classname = 'Имя класса' gui.dpp2.limit_lists.view.group = 'Группа' gui.dpp2.limit_lists.view.limit = 'Лимит' gui.dpp2.limit.edit_title = 'Редактирование лимитов для %s' message.dpp2.limit.spawn = 'Вы достигнули лимита %s!' message.dpp2.inspect.invalid_entity = 'Трассировка не нашала ни одной сущности' message.dpp2.inspect.check_console = 'Проверьте свою консоль для результатов осмотра' message.dpp2.inspect.clientside = '-- ВЫВОД КЛИЕНТА --' message.dpp2.inspect.serverside = '-- ВЫВОД СЕРВЕРА --' message.dpp2.inspect.footer = '--------------------------------------' message.dpp2.inspect.result.class = 'Имя класса: %s' message.dpp2.inspect.result.position = 'Позиция в мире: Vector(#f, #f, #f)' message.dpp2.inspect.result.angles = 'Угол в мире: Angle(#f, #f, #f)' message.dpp2.inspect.result.eye_angles = '"Глазной" угол в мире: Angle(#f, #f, #f)' message.dpp2.inspect.result.table_size = 'Размер таблицы: #d' message.dpp2.inspect.result.health = 'Здоровье: #d' message.dpp2.inspect.result.max_health = 'Максимум здоровья: #d' message.dpp2.inspect.result.owner_entity = 'Владелец: #E' message.dpp2.inspect.result.owner_steamid = 'SteamID владельца: %s' message.dpp2.inspect.result.owner_nickname = 'Nickname владельца: %s' message.dpp2.inspect.result.owner_uniqueid = 'UniqueID владельца: %s' message.dpp2.inspect.result.unowned = 'Сущность не имеет владельца' message.dpp2.inspect.result.model = 'Модель: %s' message.dpp2.inspect.result.skin = 'Скин: %s' message.dpp2.inspect.result.bodygroup_count = 'Количество бадигрупов: #d' gui.dpp2.property.arm_creator = 'Достать инструмент создания' gui.dpp2.undo.physgun = 'Отменено действие физпушки' gui.dpp2.undo.physgun_help = 'Для отмены действия физпушки используйте консольную команду dpp2_undo_physgun' gui.dpp2.undo.physgun_nothing = 'Нечего отменять' message.dpp2.autoblacklist.added_volume = 'Модель %q была автоматически добавилена в чёрный список на основе объема' message.dpp2.autoblacklist.added_aabb = 'Модель %q была автоматически добавилена в чёрный список на основе размера AABB' message.dpp2.import.dpp_friends = 'Импортировано #d записей из списка друзей DPP.' message.dpp2.import.fpp_friends = 'Импортировано #d записей из списка друзей FPP.' message.dpp2.import.no_fpp_table = 'FPP не содержит друзей' message.dpp2.import.button_dpp_friends = 'Импортировать DPP друзей' message.dpp2.import.button_fpp_friends = 'Импортировать FPP друзей' message.dpp2.error.empty_constraint = 'Entity:GetConstrainedEntities() вернул неверные сущности?!' gui.dpp2.toolmenu.playertransfer = 'Передать все к игроку %s' gui.dpp2.toolmenu.playertransferfallback = 'Отметить игрока %s как преемника' gui.dpp2.property.cleanup = 'Удалить сущности владельца' gui.dpp2.property.cleanupnpcs = 'Удалить НИПов владельца' gui.dpp2.property.cleanupvehicles = 'Удалить транспортные средства владельца' gui.dpp2.cvars.model_restrict_props = 'Список ограничения моделей распространяется только на prop_*' gui.dpp2.cvars.model_blacklist_props = 'Чёрный список моделей распространяется только на prop_*' gui.dpp2.cvars.model_exclusion_props = 'Список исключений моделей распространяется только на prop_*'
64.078464
248
0.78144
6456d23655b3fb72c70c7efaee1596ea24ee50f4
32
require 'telnet' require 'http'
10.666667
16
0.75
d7043ae7e805e6f23393663f88f6b98b7b102b44
5,432
max = math.max min = math.min pointOnLine = (p, q, r) -> return (q.x <= max(p.x, r.x)) and (q.x >= min(p.x, r.x) ) and (q.z <= max(p.z, r.z)) and (q.z >= min(p.z, r.z)) vectorOrinetation = (p, q, r) -> val = ((q.z - p.z) * (r.x - q.x)) - ((q.x - p.x) * (r.z - q.z)) if (val == 0) return 0 if (val > 0) return 1 return 2 doVectorsIntersect = (p1, q1, p2, q2) -> o1 = vectorOrinetation(p1, q1, p2) o2 = vectorOrinetation(p1, q1, q2) o3 = vectorOrinetation(p2, q2, p1) o4 = vectorOrinetation(p2, q2, q1) if (o1 ~= o2 and o3 ~= o4) return true if(o1 == 0 and pointOnLine(p1, p2, q1)) return true if(o2 == 0 and pointOnLine(p1, q2, q1)) return true if(o3 == 0 and pointOnLine(p2, p1, q2)) return true if(o4 == 0 and pointOnLine(p2, p1, q2)) return true return false pointOfIntersection = (p1, p2, q1, q2) -> if doVectorsIntersect(p1, p2, q1, q2) v1 = p2 - p1 v2 = q2 - q1 a1 = (v1.z/v1.x) c1 = p1.z - a1*p1.x a2 = (v2.z/v2.x) c2 = q1.z - a2*q1.x if a1 >= math.huge and a2 >= math.huge return (p1 + q1 + p2 + q2) / 4 if a1 >= math.huge return SetVector(p1.x, 0, a2*p1.x + c2) if a2 >= math.huge return SetVector(q1.x, 0, a1*q1.x + c1) x = (c2 - c1)/(a1 - a2) return SetVector(x, 0, a1*x + c1) -- checks if two vector paths intersects doVectorPathsIntersect = (p1, p2) -> if #p1 <= 0 or #p2 <= 0 return false for i=2, #p1 v1 = p1[i-1] v2 = p1[i] for j=2, #p2 v3 = p2[j-1] v4 = p2[j] if doVectorsIntersect(v1, v2, v3, v4) return true return false -- returns all the points of intersection between to vector paths pointsOfPathIntersection = (p1, p2) -> if doVectorPathsIntersect(p1, p2) ret = {} for i=2, #p1 v1 = p1[i-1] v2 = p1[i] for j=2, #p2 v3 = p2[j-1] v4 = p2[j] intersection = pointOfIntersection(v1,v2,v3,v4) if intersection table.insert(ret, intersection) return ret -- checks if a point is inside a vector path getWindingNumber = (path, v1) -> intersections = pointsOfPathIntersection(path, {v1 , SetVector(math.huge, 0, v1.z)}) if intersections return #intersections return 0 isInisdeVectorPath = (path, v1) -> return getWindingNumber(path, v1) % 2 ~= 0 local2Global = (v,t) -> up = SetVector(t.up_x, t.up_y, t.up_z) front = SetVector(t.front_x, t.front_y, t.front_z) right = SetVector(t.right_x, t.right_y, t.right_z) return v.x * front + v.y * up + v.z * right safeDiv = (a,b) -> if a == 0 return 0 if b == 0 return math.hugh return a/b safeDivV = (v1,v2) -> return SetVector(safeDiv(v1.x,v2.x), safeDiv(v1.y,v2.y), safeDiv(v1.z, v2.z)) global2Local = (v,t) -> up = SetVector(t.up_x, t.up_y, t.up_z) front = SetVector(t.front_x, t.front_y, t.front_z) right = SetVector(t.right_x, t.right_y, t.right_z) return SetVector(DotProduct(v, front), DotProduct(v, up), DotProduct(v, right)) class Area new: (routineFactory) => @areaSubjects = { all: Subject.create() } @type = t @path = path @handles = {} @enabled = false --Calculate center and radius @_bounding() --register everyone that is inside -- create routine that keeps area updated if routineFactory @routineFactory = routineFactory @enable() enable: () => if @_enabled return @_enabled = true for v in ObjectsInRange(@radius+50,@center) if IsInsideArea(@path,v) @handles[v] = true if @routineFactory @subscription = routineFactory()\subscribe(@\update) disable: () => @_enabled = false if @subscription @subscription\unsubscribe() getPath: () => @path getCenter: () => @center getObjects: () => return [i for i,v in pairs(@handles)] getRadius: () => @radius _bounding: () => error("Not implemented") update: () => all = {i,1 for i,v in pairs(@handles)} for v in ObjectsInRange(@radius+50,@center) all[v] = 1 for v,_ in pairs(all) do if IsInsideArea(@path,v) if @handles[v] == nil @nextObject(v,true) @handles[v] = true else if @handles[v] @nextObject(v,false) @handles[v] = nil nextObject: (handle,inside) => @areaSubjects.all\onNext(@,handle,inside) if(@areaSubjects[handle]) @areaSubjects[handle]\onNext(@,handle,inside) onChange: (handle) => if(handle) @areaSubjects[handle] = @areaSubjects[handle] or Subject.create() return @areaSubjects[handle] return @areaSubjects.all save: () => return @handles load: (...) => @handles = ... class PolyArea extends Area new: (...) => super(...) _bounding: () => center = GetCenterOfPath(@path) radius = 0 for i,v in ipairs(GetPathPoints(@path)) do radius = math.max(radius,Length(v-center)) @center = center @radius = radius return { :pointOfIntersection, :doVectorsIntersect, :doVectorPathsIntersect, :pointsOfPathIntersection, :local2Global, :global2Local, :Area, :PolyArea }
22.446281
114
0.557069
eb5339d4adee89e189436ab23378c2976c558746
1,875
--------------------------------------------------------------------------- -- Environment ------------------------------------------------------------ --------------------------------------------------------------------------- import pcall from _G import run from require 'shell' import open, read, close from io import configdir from require 'hs' import byte, find, sub from string { sigcheck:T } = require 'typecheck' import imageFromPath from require 'hs.image' --------------------------------------------------------------------------- -- Implementation --------------------------------------------------------- --------------------------------------------------------------------------- ASSETS_DIR = configdir .. '/assets' path = (name) -> ASSETS_DIR .. '/' .. name load = (p, arg) -> p = ASSETS_DIR .. '/' .. p unless byte(p) == 47 -- '^/' sub4 = sub p, -4 sub5 = sub p, -5 -- If the requested asset is an image. if sub4 == '.jpg' or sub4 == '.png' or sub4 == '.gif' or sub4 == '.ico' or sub4 == '.bmp' or sub5 == '.jpeg' or sub5 == '.icns' -- load asset as an hs.image object. success, result = pcall imageFromPath, p error 'Failed to load image at path: ' .. p unless success result\size arg, true if arg return result elseif sub4 == '.lua' or sub5 == '.moon' -- If the requested asset is a lua/moon configuraion file. success, result = pcall dofile, p return success and result or nil else -- If the requested asset is a text file. output, success = run 'file', p if success and find output, 'text' handle = open p, 'r' content = read handle, '*a' close handle return content return p setmetatable { assetsdir: ASSETS_DIR path: T 'string', path load: T 'string', load }, { __index: T '?, string', (f) => path f __call: T '?, string', (f, a) => load f, a }
34.090909
76
0.478933
71b5eb947d865447eab9b2c85dfe4fdd74083173
2,007
-- for running stuff in parallel coroutine = require("coroutine") local * co_create = coroutine.create co_yield = coroutine.yield co_running = coroutine.running co_resume = coroutine.resume co_status = coroutine.status unpack = table.unpack list = (args, limit) -> -- check args fn_list = args for i=1, #fn_list if type(fn_list[i]) ~= "function" then return 0, "arg must #{i} be function" num = #fn_list limit = num unless limit ~= nil and limit > num results = {} tasks = {} context = { remain_count: num error_count: 0 results: {} caller_coroutine: co_running! exec_count: 0 } -- create our threads for i=1, num -- create async handler tasks[i] = co_create( (index, fn) -> -- print 'starting ' .. index ok, result = pcall fn -- use pcall to handle error -- print 'ending ' .. index -- pack result context.results[index] = { ok: ok result: result } -- decrement running threads count context.remain_count -= 1 -- finally, exit if no remaining thread if context.remain_count == 0 -- resume caller thread if it's not dead if co_status(context.caller_coroutine) ~= 'dead' co_resume(context.caller_coroutine) ) -- loop while any task is suspended or limit has not reached while true -- now execute any suspended task for i=1, num task = tasks[i] if co_status(task) == 'suspended' then co_resume(task, i, fn_list[i]) -- this prevent infinit loop based on limit context.exec_count += 1 -- we've reached our limit, get out if context.remain_count <= 0 or context.exec_count > limit -- make sure we're not waiting for it externally context.remain_count = 0 break -- externally, make sure to wait for all threads to finish -- if we somehow got here by excessive inner thread yields if context.remain_count > 0 co_yield! context.results { :list }
24.777778
75
0.634778
55a16a78e1df44ca40590651998d67c859daacd0
245
hello = "hello" world = "world" (using nil) -> hello = 3223 (a using nil) -> hello = 3223 a = 323 (a,b,c using a,b,c) -> a,b,c = 1,2,3 world = 12321 (a,e,f using a,b,c, hello) -> a,b,c = 1,2,3 hello = 12321 world = "yeah"
11.136364
29
0.518367
567aa4c96ff8024d67949dffa4f1b8c5119f9798
1,119
-- Copyright 2014-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) ffi = require 'ffi' require 'ljglibs.cdefs.pango' core = require 'ljglibs.core' C, ffi_gc, ffi_cast = ffi.C, ffi.gc, ffi.cast attr_t = ffi.typeof 'PangoAttribute *' to_attr = (o) -> ffi_cast attr_t, o core.define 'PangoAttrIterator', { next: => C.pango_attr_iterator_next(@) != 0 range: => vals = ffi.new 'gint[2]' C.pango_attr_iterator_range @, vals, vals + 1 tonumber(vals[0]), tonumber(vals[1]) get: (type) => v = C.pango_attr_iterator_get @, type v != nil and v or nil } core.define 'PangoAttrList', { properties: { iterator: => ffi_gc C.pango_attr_list_get_iterator(@), C.pango_attr_iterator_destroy } new: -> ffi.gc C.pango_attr_list_new!, C.pango_attr_list_unref insert: (attr) => C.pango_attr_list_insert @, to_attr ffi_gc(attr, nil) insert_before: (attr) => C.pango_attr_list_insert_before @, to_attr ffi_gc(attr, nil) change: (attr) => C.pango_attr_list_change @, to_attr ffi_gc(attr, nil) }, (t, ...) -> t.new ...
24.866667
88
0.675603
371bedca2ec0de7d4ac1e830d29da6992c82a394
9,272
import PATHS from require "ZF.2D.paths" import PATH from require "ZF.2D.path" import SEGMENT from require "ZF.2D.segment" import POINT from require "ZF.2D.point" class SHAPE extends PATHS version: "1.1.2" -- @param shape string || SHAPE -- @param close boolean new: (shape, close = true) => -- checks if the value is a number, otherwise it returns an invalid error isNumber = (v) -> if v = tonumber v return v else error "unknown shape" @paths, @l, @t, @r, @b = {}, math.huge, math.huge, -math.huge, -math.huge if type(shape) == "string" -- indexes all values that are different from a space i, data = 1, [s for s in shape\gmatch "%S+"] while i <= #data switch data[i] when "m" -- creates a new path layer @push PATH! -- skip to the next letter i += 2 when "l" j = 1 while tonumber(data[i + j]) != nil last = @paths[#@paths] path, p0 = last.path, POINT! if #path == 0 and data[i - 3] == "m" p0.x = isNumber data[i - 2] p0.y = isNumber data[i - 1] else segment = path[#path].segment p0 = POINT segment[#segment] -- creates the new line points and -- checks if they are really a number p1 = POINT! p1.x = isNumber data[i + j + 0] p1.y = isNumber data[i + j + 1] -- adds the line to the path last\push SEGMENT p0, p1 j += 2 -- skip to the next letter i += j - 1 when "b" j = 1 while tonumber(data[i + j]) != nil last = @paths[#@paths] path, p0 = last.path, POINT! if #path == 0 and data[i - 3] == "m" p0.x = isNumber data[i - 2] p0.y = isNumber data[i - 1] else segment = path[#path].segment p0 = POINT segment[#segment] -- creates the new bezier points and -- checks if they are really a number p1, p2, p3 = POINT!, POINT!, POINT! p1.x = isNumber data[i + j + 0] p1.y = isNumber data[i + j + 1] p2.x = isNumber data[i + j + 2] p2.y = isNumber data[i + j + 3] p3.x = isNumber data[i + j + 4] p3.y = isNumber data[i + j + 5] -- adds the bezier to the path last\push SEGMENT p0, p1, p2, p3 j += 6 -- skip to the next letter i += j - 1 else -- if the (command | letter) is other than "m", "l" and "b", that shape is unknown error "unknown shape" i += 1 elseif type(shape) == "table" and rawget shape, "paths" for key, value in pairs shape\copy! @[key] = value -- removes invalid path i = 1 while i <= #@paths path = @paths[i].path if #path == 0 table.remove @paths, i i -= 1 i += 1 -- checks whether to close or open the shape if close == true or close == "close" @close! elseif close == "open" @open! -- sets the bounding box @setBoudingBox! -- sets the position the paths will be -- @param an integer -- @param mode string -- @param px number -- @param py number -- @return SHAPE setPosition: (an = 7, mode = "tcp", px = 0, py = 0) => {:w, :h} = @ switch an when 1 switch mode when "tcp" then @move px, py - h when "ucp" then @move -px, -py + h when 2 switch mode when "tcp" then @move px - w / 2, py - h when "ucp" then @move -px + w / 2, -py + h when 3 switch mode when "tcp" then @move px - w, py - h when "ucp" then @move -px + w, -py + h when 4 switch mode when "tcp" then @move px, py - h / 2 when "ucp" then @move -px, -py + h / 2 when 5 switch mode when "tcp" then @move px - w / 2, py - h / 2 when "ucp" then @move -px + w / 2, -py + h / 2 when 6 switch mode when "tcp" then @move px - w, py - h / 2 when "ucp" then @move -px + w, -py + h / 2 when 7 switch mode when "tcp" then @move px, py when "ucp" then @move -px, -py when 8 switch mode when "tcp" then @move px - w / 2, py when "ucp" then @move -px + w / 2, -py when 9 switch mode when "tcp" then @move px - w, py when "ucp" then @move -px + w, -py return @ -- transforms the points from perspective tags [fax, fay...] -- https://github.com/Alendt/Aegisub-Scripts/blob/0e897aeaab4eb11855cd1d83474616ef06307268/macros/alen.Shapery.moon#L3787 -- @param line table -- @param data table -- @return SHAPE expand: (line, data) => pf = (sx = 100, sy = 100, p = 1) -> assert p > 0 and p == floor p if p == 1 sx / 100, sy / 100 else p -= 1 sx /= 2 sy /= 2 pf sx, sy, p with data .p = .p == "text" and 1 or .p frx = pi / 180 * .frx fry = pi / 180 * .fry frz = pi / 180 * line.styleref.angle sx, cx = -sin(frx), cos(frx) sy, cy = sin(fry), cos(fry) sz, cz = -sin(frz), cos(frz) xscale, yscale = pf line.styleref.scale_x, line.styleref.scale_y, .p fax = .fax * xscale / yscale fay = .fay * yscale / xscale x1 = {1, fax, .pos[1] - .org[1]} y1 = {fay, 1, .pos[2] - .org[2]} x2, y2 = {}, {} for i = 1, 3 x2[i] = x1[i] * cz - y1[i] * sz y2[i] = x1[i] * sz + y1[i] * cz y3, z3 = {}, {} for i = 1, 3 y3[i] = y2[i] * cx z3[i] = y2[i] * sx x4, z4 = {}, {} for i = 1, 3 x4[i] = x2[i] * cy - z3[i] * sy z4[i] = x2[i] * sy + z3[i] * cy dist = 312.5 z4[3] += dist offs_x = .org[1] - .pos[1] offs_y = .org[2] - .pos[2] matrix = [{} for i = 1, 3] for i = 1, 3 matrix[1][i] = z4[i] * offs_x + x4[i] * dist matrix[2][i] = z4[i] * offs_y + y3[i] * dist matrix[3][i] = z4[i] @filter (x, y) -> v = [(matrix[m][1] * x * xscale) + (matrix[m][2] * y * yscale) + matrix[m][3] for m = 1, 3] w = 1 / max v[3], 0.1 return v[1] * w, v[2] * w return @ -- distorts a shape into a clip -- http://www.planetclegg.com/projects/WarpingTextToSplines.html -- @param an integer -- @param clip string || SHAPE -- @param mode string -- @param leng integer -- @param offset number -- @return SHAPE inClip: (an = 7, clip, mode = "left", leng, offset = 0) => mode = mode\lower! @toOrigin! if type(clip) != "table" clip = SHAPE clip, false leng or= clip\length! size = leng - @w @ = @flatten nil, nil, 2 @filter (x, y) -> y = switch an when 7, 8, 9 then y - @h when 4, 5, 6 then y - @h / 2 -- when 1, 2, 3 then y x = switch mode when 1, "left" then x + offset when 2, "center" then x + offset + size / 2 when 3, "right" then x - offset + size -- gets normal tangent tan, pnt, t = clip\getNormal x / leng, true -- reescale tangent tan.x = pnt.x + y * tan.x tan.y = pnt.y + y * tan.y return tan return @ {:SHAPE}
36.940239
125
0.385677
c2e6a1edaa4f347c034e6eee5c968920f7972b7e
8,272
import concat from table import type, tostring, pairs, select from _G local raw_query, raw_disconnect local logger import FALSE NULL TRUE build_helpers format_date is_raw raw is_list list is_encodable from require "lapis.db.base" array = (t) -> import PostgresArray from require "pgmoon.arrays" PostgresArray t is_array = (v) -> import PostgresArray from require "pgmoon.arrays" getmetatable(v) == PostgresArray.__base _is_encodable = (item) -> return true if is_encodable item return true if is_array item false local gettime BACKENDS = { -- the raw backend is a debug backend that lets you specify the function that -- handles the query raw: (fn) -> fn pgmoon: -> import after_dispatch, increment_perf, set_perf from require "lapis.nginx.context" config = require("lapis.config").get! pg_config = assert config.postgres, "missing postgres configuration" local pgmoon_conn _query = (str) -> pgmoon = ngx and ngx.ctx.pgmoon or pgmoon_conn unless pgmoon import Postgres from require "pgmoon" pgmoon = Postgres pg_config assert pgmoon\connect! if ngx ngx.ctx.pgmoon = pgmoon after_dispatch -> pgmoon\keepalive! else pgmoon_conn = pgmoon start_time = if config.measure_performance if reused = ngx and pgmoon.sock\getreusedtimes! set_perf "pgmoon_conn", reused > 0 and "reuse" or"new" unless gettime gettime = require("socket").gettime gettime! res, err = pgmoon\query str if start_time dt = gettime! - start_time increment_perf "db_time", dt increment_perf "db_count", 1 logger.query "(#{"%.2f"\format dt * 1000}ms) #{str}" if logger else logger.query str if logger if not res and err error "#{str}\n#{err}" res _disconnect = -> return unless pgmoon_conn pgmoon_conn\disconnect! pgmoon_conn = nil true _query, _disconnect } set_backend = (name, ...) -> backend = BACKENDS[name] unless backend error "Failed to find PostgreSQL backend: #{name}" raw_query, raw_disconnect = backend ... set_raw_query = (fn) -> raw_query = fn get_raw_query = -> raw_query init_logger = -> config = require("lapis.config").get! logger = if ngx or os.getenv("LAPIS_SHOW_QUERIES") or config.show_queries require "lapis.logging" init_db = -> config = require("lapis.config").get! backend = config.postgres and config.postgres.backend unless backend backend = "pgmoon" set_backend backend escape_identifier = (ident) -> return ident[1] if is_raw ident if is_list ident escaped_items = [escape_identifier item for item in *ident[1]] assert escaped_items[1], "can't flatten empty list" return "(#{concat escaped_items, ", "})" ident = tostring ident '"' .. (ident\gsub '"', '""') .. '"' escape_literal = (val) -> switch type val when "number" return tostring val when "string" return "'#{(val\gsub "'", "''")}'" when "boolean" return val and "TRUE" or "FALSE" when "table" return "NULL" if val == NULL if is_list val escaped_items = [escape_literal item for item in *val[1]] assert escaped_items[1], "can't flatten empty list" return "(#{concat escaped_items, ", "})" if is_array val import encode_array from require "pgmoon.arrays" return encode_array val, escape_literal return val[1] if is_raw val error "unknown table passed to `escape_literal`" error "don't know how to escape value: #{val}" interpolate_query, encode_values, encode_assigns, encode_clause = build_helpers escape_literal, escape_identifier append_all = (t, ...) -> for i=1, select "#", ... t[#t + 1] = select i, ... connect = -> init_logger! init_db! -- replaces raw_query to default backend disconnect = -> assert raw_disconnect, "no active connection" raw_disconnect! -- this default implementation is replaced when the connection is established raw_query = (...) -> connect! raw_query ... query = (str, ...) -> if select("#", ...) > 0 str = interpolate_query str, ... raw_query str _select = (str, ...) -> query "SELECT " .. str, ... add_returning = (buff, first, cur, following, ...) -> return unless cur if first append_all buff, " RETURNING " append_all buff, escape_identifier cur if following append_all buff, ", " add_returning buff, false, following, ... _insert = (tbl, values, ...) -> buff = { "INSERT INTO " escape_identifier(tbl) " " } encode_values values, buff if ... add_returning buff, true, ... raw_query concat buff add_cond = (buffer, cond, ...) -> append_all buffer, " WHERE " switch type cond when "table" encode_clause cond, buffer when "string" append_all buffer, interpolate_query cond, ... _update = (table, values, cond, ...) -> buff = { "UPDATE " escape_identifier(table) " SET " } encode_assigns values, buff if cond add_cond buff, cond, ... if type(cond) == "table" add_returning buff, true, ... raw_query concat buff _delete = (table, cond, ...) -> buff = { "DELETE FROM " escape_identifier(table) } if cond add_cond buff, cond, ... raw_query concat buff -- truncate many tables _truncate = (...) -> tables = concat [escape_identifier t for t in *{...}], ", " raw_query "TRUNCATE " .. tables .. " RESTART IDENTITY" parse_clause = do local grammar make_grammar = -> basic_keywords = {"where", "having", "limit", "offset"} import P, R, C, S, Cmt, Ct, Cg, V from require "lpeg" alpha = R("az", "AZ", "__") alpha_num = alpha + R("09") white = S" \t\r\n"^0 some_white = S" \t\r\n"^1 word = alpha_num^1 single_string = P"'" * (P"''" + (P(1) - P"'"))^0 * P"'" double_string = P'"' * (P'""' + (P(1) - P'"'))^0 * P'"' strings = single_string + double_string -- case insensitive word ci = (str) -> import S from require "lpeg" local p for c in str\gmatch "." char = S"#{c\lower!}#{c\upper!}" p = if p p * char else char p * -alpha_num balanced_parens = P { P"(" * (V(1) + strings + (P(1) - ")"))^0 * P")" } order_by = ci"order" * some_white * ci"by" / "order" group_by = ci"group" * some_white * ci"by" / "group" keyword = order_by + group_by for k in *basic_keywords part = ci(k) / k keyword += part keyword = keyword * white clause_content = (balanced_parens + strings + (word + P(1) - keyword))^1 outer_join_type = (ci"left" + ci"right" + ci"full") * (white * ci"outer")^-1 join_type = (ci"natural" * white)^-1 * ((ci"inner" + outer_join_type) * white)^-1 start_join = join_type * ci"join" join_body = (balanced_parens + strings + (P(1) - start_join - keyword))^1 join_tuple = Ct C(start_join) * C(join_body) joins = (#start_join * Ct join_tuple^1) / (joins) -> {"join", joins} clause = Ct (keyword * C clause_content) grammar = white * Ct joins^-1 * clause^0 (clause) -> return {} if clause == "" make_grammar! unless grammar parsed = if tuples = grammar\match clause { unpack t for t in *tuples } if not parsed or (not next(parsed) and not clause\match "^%s*$") return nil, "failed to parse clause: `#{clause}`" parsed encode_case = (exp, t, on_else) -> buff = { "CASE ", exp } for k,v in pairs t append_all buff, "\nWHEN ", escape_literal(k), " THEN ", escape_literal(v) if on_else != nil append_all buff, "\nELSE ", escape_literal on_else append_all buff, "\nEND" concat buff { :connect :disconnect :query, :raw, :is_raw, :list, :is_list, :array, :is_array, :NULL, :TRUE, :FALSE, :escape_literal, :escape_identifier, :encode_values, :encode_assigns, :encode_clause, :interpolate_query, :parse_clause, :format_date, :encode_case :init_logger :set_backend :set_raw_query :get_raw_query select: _select insert: _insert update: _update delete: _delete truncate: _truncate is_encodable: _is_encodable }
23.301408
113
0.623308
a8242228ed111798703aa565f1098cce0d4d620a
523
{ 1, 2 } { 1, 2 } { 1, 2 } {1,2} { 1,2 } { something 1,2, 4,5,6, 3,4,5 } { a 1,2,3, 4,5,6 1,2,3 } { b 1,2,3, 4,5,6 1,2,3, 1,2,3 } { 1,2,3 } { c 1,2,3, } hello 1,2,3,4, 1,2,3,4,4,5 x 1, 2, 3, 4, 5, 6 hello 1,2,3, world 4,5,6, 5,6,7,8 hello 1,2,3, world 4,5,6, 5,6,7,8, 9,9 { hello 1,2, 3,4, 5, 6 } x = { hello 1,2,3,4, 5,6,7 1,2,3,4 } if hello 1,2,3, world, world print "hello" if hello 1,2,3, world, world print "hello"
6.22619
17
0.399618
888a105f2daff2f691484eafb8960a785a067f28
24,686
lfs = require "lfs" DownloadManager = require "DM.DownloadManager" PreciseTimer = require "PT.PreciseTimer" UpdateFeed = require "l0.DependencyControl.UpdateFeed" fileOps = require "l0.DependencyControl.FileOps" Logger = require "l0.DependencyControl.Logger" Common = require "l0.DependencyControl.Common" ModuleLoader = require "l0.DependencyControl.ModuleLoader" DependencyControl = nil class UpdaterBase extends Common @logger = Logger fileBaseName: "DependencyControl.Updater" msgs = { updateError: { [0]: "Couldn't %s %s '%s' because of a paradox: module not found but updater says up-to-date (%s)" [1]: "Couldn't %s %s '%s' because the updater is disabled." [2]: "Skipping %s of %s '%s': namespace '%s' doesn't conform to rules." [3]: "Skipping %s of unmanaged %s '%s'." [4]: "No remaining feed available to %s %s '%s' from." [6]: "The %s of %s '%s' failed because no suitable package could be found %s." [5]: "Skipped %s of %s '%s': Another update initiated by %s is already running." [7]: "Skipped %s of %s '%s': An internet connection is currently not available." [10]: "Skipped %s of %s '%s': the update task is already running." [15]: "Couldn't %s %s '%s' because its requirements could not be satisfied:" [30]: "Couldn't %s %s '%s': failed to create temporary download directory %s" [35]: "Aborted %s of %s '%s' because the feed contained a missing or malformed SHA-1 hash for file %s." [50]: "Couldn't finish %s of %s '%s' because some files couldn't be moved to their target location:\n" [55]: "%s of %s '%s' succeeded, couldn't be located by the module loader." [56]: "%s of %s '%s' succeeded, but an error occured while loading the module:\n%s" [57]: "%s of %s '%s' succeeded, but it's missing a version record." [58]: "%s of unmanaged %s '%s' succeeded, but an error occured while creating a DependencyControl record: %s" [100]: "Error (%d) in component %s during %s of %s '%s':\n— %s" } updaterErrorComponent: {"DownloadManager (adding download)", "DownloadManager"} } getUpdaterErrorMsg: (code, name, scriptType, isInstall, detailMsg) => if code <= -100 -- Generic downstream error return msgs.updateError[100]\format -code, msgs.updaterErrorComponent[math.floor(-code/100)], @@terms.isInstall[isInstall], @@terms.scriptType.singular[scriptType], name, detailMsg else -- Updater error: return msgs.updateError[-code]\format @@terms.isInstall[isInstall], @@terms.scriptType.singular[scriptType], name, detailMsg class UpdateTask extends UpdaterBase dlm = DownloadManager! msgs = { checkFeed: { downloadFailed: "Failed to download feed: %s" noData: "The feed doesn't have any update information for %s '%s'." badChannel: "The specified update channel '%s' wasn't present in the feed." invalidVersion: "The feed contains an invalid version record for %s '%s' (channel: %s): %s." unsupportedPlatform: "No download available for your platform '%s' (channel: %s)." noFiles: "No files available to download for your platform '%s' (channel: %s)." } run: { starting: "Starting %s of %s '%s'... " fetching: "Trying to %sfetch missing %s '%s'..." feedCandidates: "Trying %d candidate feeds (%s mode)..." feedTrying: "Checking feed %d/%d (%s)..." upToDate: "The %s '%s' is up-to-date (v%s)." alreadyUpdated: "%s v%s has already been installed." noFeedAvailExt: "(required: %s; installed: %s; available: %s)" noUpdate: "Feed has no new update." skippedOptional: "Skipped %s of optional dependency '%s': %s" optionalNoFeed: "No feed available to download module from." optionalNoUpdate: "No suitable download could be found %s." } performUpdate: { updateReqs: "Checking requirements..." updateReady: "Update ready. Using temporary directory '%s'." fileUnchanged: "Skipped unchanged file '%s'." fileAddDownload: "Added Download %s ==> '%s'." filesDownloading: "Downloading %d files..." movingFiles: "Downloads complete. Now moving files to Aegisub automation directory '%s'..." movedFile: "Moved '%s' ==> '%s'." moveFileFailed: "Failed to move '%s' ==> '%s': %s" updSuccess: "%s of %s '%s' (v%s) complete." reloadNotice: "Please rescan your autoload directory for the changes to take effect." unknownType: "Skipping file '%s': unknown type '%s'." } refreshRecord: { unsetVirtual: "Update initated by another macro already fetched %s '%s', switching to update mode." otherUpdate: "Update initated by another macro already updated %s '%s' to v%s." } } new: (@record, targetVersion = 0, @addFeeds, @exhaustive, @channel, @optional, @updater) => DependencyControl or= require "l0.DependencyControl" assert @record.__class == DependencyControl, "First parameter must be a #{DependencyControl.__name} object." @logger = @updater.logger @triedFeeds = {} @status = nil @targetVersion = DependencyControl\parseVersion targetVersion -- set UpdateFeed settings @feedConfig = { downloadPath: aegisub.decode_path "?user/feedDump/" dumpExpanded: true } if @updater.config.c.dumpFeeds return nil, -1 unless @updater.config.c.updaterEnabled -- TODO: check if this even works return nil, -2 unless @record\validateNamespace! set: (targetVersion, @addFeeds, @exhaustive, @channel, @optional) => @targetVersion = DependencyControl\parseVersion targetVersion return @ checkFeed: (feedUrl) => -- get feed contents feed = UpdateFeed feedUrl, false, nil, @feedConfig, @logger unless feed.data -- no cached data available, perform download success, err = feed\fetch! unless success return nil, msgs.checkFeed.downloadFailed\format err -- select our script and update channel updateRecord = feed\getScript @record.namespace, @record.scriptType, @record.config, false unless updateRecord return nil, msgs.checkFeed.noData\format @@terms.scriptType.singular[@record.scriptType], @record.name success, currentChannel = updateRecord\setChannel @channel unless success return nil, msgs.checkFeed.badChannel\format currentChannel -- check if an update is available and satisfies our requirements res, version = @record\checkVersion updateRecord.version if res == nil return nil, msgs.checkFeed.invalidVersion\format @@terms.scriptType.singular[@record.scriptType], @record.name, currentChannel, tostring updateRecord.version elseif res or @targetVersion > version return false, nil, version -- check if our platform is supported/files are available to download res, platform = updateRecord\checkPlatform! unless res return nil, msgs.checkFeed.unsupportedPlatform\format platform, currentChannel if #updateRecord.files == 0 return nil, msgs.checkFeed.noFiles\format platform, currentChannel return true, updateRecord, version run: (waitLock, exhaustive = @updater.config.c.tryAllFeeds or @@exhaustive) => logUpdateError = (code, extErr, virtual = @virtual) -> if code < 0 @logger\log @getUpdaterErrorMsg code, @record.name, @record.scriptType, virtual, extErr return code, extErr with @record do @logger\log msgs.run.starting, @@terms.isInstall[.virtual], @@terms.scriptType.singular[.scriptType], .name -- don't perform update of a script when another one is already running for the same script return logUpdateError -10 if @running -- check if the script was already updated if @updated and not exhaustive and @record\checkVersion @targetVersion @logger\log msgs.run.alreadyUpdated, @record.name, DependencyControl\getVersionString @record.version return 2 -- build feed list userFeed, haveFeeds, feeds = @record.config.c.userFeed, {}, {} if userFeed and not @triedFeeds[userFeed] feeds[1] = userFeed else unless @triedFeeds[@record.feed] or haveFeeds[@record.feed] feeds[1] = @record.feed for feed in *@addFeeds unless @triedFeeds[feed] or haveFeeds[feed] feeds[#feeds+1] = feed haveFeeds[feed] = true for feed in *@updater.config.c.extraFeeds unless @triedFeeds[feed] or haveFeeds[feed] feeds[#feeds+1] = feed haveFeeds[feed] = true if #feeds == 0 if @optional @logger\log msgs.run.skippedOptional, @record.name, @@terms.isInstall[@record.virtual], msgs.run.optionalNoFeed return 3 return logUpdateError -4 -- check internet connection return logUpdateError -7 unless dlm\isInternetConnected! -- get a lock on the updater success, otherHost = @updater\getLock waitLock return logUpdateError -5, otherHost unless success -- check feeds for update until we find and update or run out of feeds to check -- normal mode: check feeds until an update matching the required version is found -- exhaustive mode: check all feeds for updates and pick the highest version @logger\log msgs.run.feedCandidates, #feeds, exhaustive and "exhaustive" or "normal" @logger.indent += 1 maxVer, updateRecord = 0 for i, feed in ipairs feeds @logger\log msgs.run.feedTrying, i, #feeds, feed res, rec, version = @checkFeed feed @triedFeeds[feed] = true if res == nil @logger\log rec elseif version > maxVer maxVer = version if res updateRecord = rec break unless exhaustive else @logger\trace msgs.run.noUpdate else @logger\trace msgs.run.noUpdate @logger.indent -= 1 local code, res wasVirtual = @record.virtual unless updateRecord -- for a script to be marked up-to-date it has to installed on the user's system -- and the version must at least be that returned by at least one feed if maxVer>0 and not @record.virtual and @targetVersion <= @record.version @logger\log msgs.run.upToDate, @@terms.scriptType.singular[@record.scriptType], @record.name, DependencyControl\getVersionString @record.version return 0 res = msgs.run.noFeedAvailExt\format @targetVersion == 0 and "any" or DependencyControl\getVersionString(@targetVersion), @record.virtual and "no" or DependencyControl\getVersionString(@record.version), maxVer<1 and "none" or DependencyControl\getVersionString maxVer if @optional @logger\log msgs.run.skippedOptional, @record.name, @@terms.isInstall[@record.virtual], msgs.run.optionalNoUpdate\format res return 3 return logUpdateError -6, res code, res = @performUpdate updateRecord return logUpdateError code, res, wasVirtual performUpdate: (update) => finish = (...) -> @running = false if @record.virtual or @record.recordType == @@RecordType.Unmanaged ModuleLoader.removeDummyRef @record return ... -- don't perform update of a script when another one is already running for the same script return finish -10 if @running @running = true -- set a dummy ref (which hasn't yet been set for virtual and unmanaged modules) -- and record version to allow resolving circular dependencies if @record.virtual or @record.recordType == @@RecordType.Unmanaged ModuleLoader.createDummyRef @record @record\setVersion update.version -- try to load required modules first to see if all dependencies are satisfied -- this may trigger more updates reqs = update.requiredModules if reqs and #reqs > 0 @logger\log msgs.performUpdate.updateReqs @logger.indent += 1 success, err = ModuleLoader.loadModules @record, reqs, {@record.feed} @logger.indent -= 1 unless success @logger.indent += 1 @logger\log err @logger.indent -= 1 return finish -15, err -- since circular dependencies are possible, our task may have completed in the meantime -- so check again if we still need to update return finish 2 if @updated and @record\checkVersion update.version -- download updated scripts to temp directory -- check hashes before download, only update changed files tmpDir = aegisub.decode_path "?temp/l0.#{DependencyControl.__name}_#{'%04X'\format math.random 0, 16^4-1}" res, dir = fileOps.mkdir tmpDir return finish -30, "#{tmpDir} (#{dir})" if res == nil @logger\log msgs.performUpdate.updateReady, tmpDir scriptSubDir = @record.namespace scriptSubDir = scriptSubDir\gsub "%.","/" if @record.scriptType == @@ScriptType.Module dlm\clear! for file in *update.files file.type or= "script" baseName = scriptSubDir .. file.name tmpName, prettyName = "#{tmpDir}/#{file.type}/#{baseName}", baseName switch file.type when "script" file.fullName = "#{@record.automationDir}/#{baseName}" when "test" file.fullName = "#{@record.testDir}/#{baseName}" prettyName ..= " (Unit Test)" else file.unknown = true @logger\log msgs.performUpdate.unknownType, file.name, file.type continue continue if file.delete unless type(file.sha1)=="string" and #file.sha1 == 40 and tonumber(file.sha1, 16) return finish -35, "#{prettyName} (#{tostring(file.sha1)\lower!})" if dlm\checkFileSHA1 file.fullName, file.sha1 @logger\trace msgs.performUpdate.fileUnchanged, prettyName continue dl, err = dlm\addDownload file.url, tmpName, file.sha1 return finish -140, err unless dl dl.targetFile = file.fullName @logger\trace msgs.performUpdate.fileAddDownload, file.url, prettyName dlm\waitForFinish (progress) -> @logger\progress progress, msgs.performUpdate.filesDownloading, #dlm.downloads return true @logger\progress! if #dlm.failedDownloads>0 err = @logger\format ["#{dl.url}: #{dl.error}" for dl in *dlm.failedDownloads], 1 return finish -245, err -- move files to their destination directory and clean up @logger\log msgs.performUpdate.movingFiles, @record.automationDir moveErrors = {} @logger.indent += 1 for dl in *dlm.downloads res, err = fileOps.move dl.outfile, dl.targetFile, true -- don't immediately error out if moving of a single file failed -- try to move as many files as possible and let the user handle the rest if res @logger\trace msgs.performUpdate.movedFile, dl.outfile, dl.targetFile else @logger\log msgs.performUpdate.moveFileFailed, dl.outfile, dl.targetFile, err moveErrors[#moveErrors+1] = err @logger.indent -= 1 if #moveErrors>0 return finish -50, @logger\format moveErrors, 1 else lfs.rmdir tmpDir os.remove file.fullName for file in *update.files when file.delete and not file.unknown -- Nuke old module refs and reload oldVer, wasVirtual = @record.version, @record.virtual -- Update complete, refresh module information/configuration if @record.scriptType == @@ScriptType.Module ref = ModuleLoader.loadModule @record, @record, false, true unless ref if @record._error return finish -56, @logger\format @record._error, 1 else return finish -55 -- get a fresh version record if type(ref.version) == "table" and ref.version.__class.__name == DependencyControl.__name @record = ref.version else -- look for any compatible non-DepCtrl version records and create an unmanaged record return finish -57 unless ref.version success, rec = pcall DependencyControl, { moduleName: @record.moduleName, version: ref.version, recordType: @@RecordType.Unmanaged, name: @record.name } return finish -58, rec unless success @record = rec @ref = ref else with @record .name, .version, .virtual = @record.name, DependencyControl\parseVersion update.version @record\writeConfig! @updated = true @logger\log msgs.performUpdate.updSuccess, @@terms.capitalize(@@terms.isInstall[wasVirtual]), @@terms.scriptType.singular[@record.scriptType], @record.name, DependencyControl\getVersionString @record.version -- Diplay changelog @logger\log update\getChangelog @record, (DependencyControl\parseVersion oldVer) + 1 @logger\log msgs.performUpdate.reloadNotice -- TODO: check handling of private module copies (need extra return value?) return finish 1, DependencyControl\getVersionString @record.version refreshRecord: => with @record wasVirtual, oldVersion = .virtual, .version \loadConfig true if wasVirtual and not .virtual or .version > oldVersion @updated = true @ref = ModuleLoader.loadModule @record, @record, false, true if .scriptType == @@ScriptType.Module if wasVirtual @logger\log msgs.refreshRecord.unsetVirtual, @@terms.scriptType.singular[.scriptType], .name else @logger\log msgs.refreshRecord.otherUpdate, @@terms.scriptType.singular[.scriptType], .name, DependencyControl\getVersionString @record.version class Updater extends UpdaterBase msgs = { getLock: { orphaned: "Ignoring orphaned in-progress update started by %s." waitFinished: "Waited %d seconds." abortWait: "Timeout reached after %d seconds." waiting: "Waiting for update intiated by %s to finish..." } require: { macroPassed: "%s is not a module." upToDate: "Tried to require an update for up-to-date module '%s'." } scheduleUpdate: { updaterDisabled: "Skipping update check for %s (Updater disabled)." runningUpdate: "Running scheduled update for %s '%s'..." } } new: (@host = script_namespace, @config, @logger = @@logger) => @tasks = {scriptType, {} for _, scriptType in pairs @@ScriptType when "number" == type scriptType} addTask: (record, targetVersion, addFeeds = {}, exhaustive, channel, optional) => DependencyControl or= require "l0.DependencyControl" if record.__class != DependencyControl depRec = {saveRecordToConfig: false, readGlobalScriptVars: false} depRec[k] = v for k, v in pairs record record = DependencyControl depRec task = @tasks[record.scriptType][record.namespace] if task return task\set targetVersion, addFeeds, exhaustive, channel, optional else task, err = UpdateTask record, targetVersion, addFeeds, exhaustive, channel, optional, @ @tasks[record.scriptType][record.namespace] = task return task, err require: (record, ...) => @logger\assert record.scriptType == @@ScriptType.Module, msgs.require, record.name or record.namespace @logger\log "%s module '%s'...", record.virtual and "Installing required" or "Updating outdated", record.name task, code = @addTask record, ... code, res = task\run true if task if code == 0 and not task.updated -- usually we know in advance if a module is up to date so there's no reason to block other updaters -- but we'll make sure to handle this case gracefully, anyway @logger\debug msgs.require.upToDate, task.record.name or task.record.namespace return ModuleLoader.loadModule task.record, task.record.namespace elseif code >= 0 return task.ref else -- pass on update errors return nil, code, res scheduleUpdate: (record) => unless @config.c.updaterEnabled @logger\trace msgs.scheduleUpdate.updaterDisabled, record.name or record.namespace return -1 -- no regular updates for non-existing or unmanaged modules if record.virtual or record.recordType == @@RecordType.Unmanaged return -3 -- the update interval has not yet been passed since the last update check if record.config.c.lastUpdateCheck and (record.config.c.lastUpdateCheck + @config.c.updateInterval > os.time!) return false record.config.c.lastUpdateCheck = os.time! record.config\write! task = @addTask record -- no need to check for errors, because we've already accounted for those case @logger\trace msgs.scheduleUpdate.runningUpdate, @@terms.scriptType.singular[record.scriptType], record.name return task\run! getLock: (doWait, waitTimeout = @config.c.updateWaitTimeout) => return true if @hasLock @config\load! running, didWait = @config.c.updaterRunning if running and running.host != @host if running.time + @config.c.updateOrphanTimeout < os.time! @logger\log msgs.getLock.orphaned, running.host elseif doWait @logger\log msgs.getLock.waiting, running.host timeout, didWait = waitTimeout, true while running and timeout > 0 PreciseTimer.sleep 1000 timeout -= 1 @config\load! running = @config.c.updaterRunning @logger\log timeout <= 0 and msgs.getLock.abortWait or msgs.getLock.waitFinished, waitTimeout - timeout else return false, running.host -- register the running update in the config file to prevent collisions -- with other scripts trying to update the same modules -- TODO: store this flag in the db @config.c.updaterRunning = host: @host, time: os.time! @config\write! @hasLock = true -- reload important module version information from configuration -- because another updater instance might have updated them in the meantime if didWait task\refreshRecord! for _,task in pairs @tasks[@@ScriptType.Module] return true releaseLock: => return false unless @hasLock @hasLock = false @config.c.updaterRunning = false @config\write!
47.110687
133
0.601434
f1e2867dcf242c88bd8a31bb9f8a30743ed3a49c
15,797
import Postgres from require "pgmoon-mashape" HOST = "127.0.0.1" USER = "postgres" DB = "pgmoon_test" describe "pgmoon-mashape with server", -> local pg setup -> os.execute "dropdb --if-exists -U '#{USER}' '#{DB}'" os.execute "createdb -U postgres '#{DB}'" pg = Postgres { database: DB user: USER host: HOST } assert pg\connect! it "creates and drop table", -> res = assert pg\query [[ create table hello_world ( id serial not null, name text, count integer not null default 0, primary key (id) ) ]] assert.same true, res res = assert pg\query [[ drop table hello_world ]] assert.same true, res it "tries to connect with SSL", -> -- we expect a server with ssl = off ssl_pg = Postgres { database: DB user: USER host: HOST ssl: true } finally -> ssl_pg\disconnect! assert ssl_pg\connect! it "requires SSL", -> ssl_pg = Postgres { database: DB user: USER host: HOST ssl: true ssl_required: true } status, err = ssl_pg\connect! assert.falsy status assert.same [[the server does not support SSL connections]], err describe "with table", -> before_each -> assert pg\query [[ create table hello_world ( id serial not null, name text, count integer not null default 0, flag boolean default TRUE, primary key (id) ) ]] after_each -> assert pg\query [[ drop table hello_world ]] it "inserts a row", -> res = assert pg\query [[ insert into "hello_world" ("name", "count") values ('hi', 100) ]] assert.same { affected_rows: 1 }, res it "inserts a row with return value", -> res = assert pg\query [[ insert into "hello_world" ("name", "count") values ('hi', 100) returning "id" ]] assert.same { affected_rows: 1 { id: 1 } }, res it "selects from empty table", -> res = assert pg\query [[select * from hello_world limit 2]] assert.same {}, res it "deletes nothing", -> res = assert pg\query [[delete from hello_world]] assert.same { affected_rows: 0 }, res it "update no rows", -> res = assert pg\query [[update "hello_world" SET "name" = 'blahblah']] assert.same { affected_rows: 0 }, res describe "with rows", -> before_each -> for i=1,10 assert pg\query [[ insert into "hello_world" ("name", "count") values (']] .. "thing_#{i}" .. [[', ]] .. i .. [[) ]] it "select some rows", -> res = assert pg\query [[ select * from hello_world ]] assert.same "table", type(res) assert.same 10, #res it "update rows", -> res = assert pg\query [[ update "hello_world" SET "name" = 'blahblah' ]] assert.same { affected_rows: 10 }, res assert.same "blahblah", unpack((pg\query "select name from hello_world limit 1")).name it "delete a row", -> res = assert pg\query [[ delete from "hello_world" where id = 1 ]] assert.same { affected_rows: 1 }, res assert.same nil, unpack((pg\query "select * from hello_world where id = 1")) or nil it "truncate table", -> res = assert pg\query "truncate hello_world" assert.same true, res it "make many select queries", -> for i=1,20 assert pg\query [[update "hello_world" SET "name" = 'blahblah' where id = ]] .. i assert pg\query [[ select * from hello_world ]] -- single call, multiple queries describe "multi-queries #multi", -> it "gets two results", -> res, num_queries = assert pg\query [[ select id, flag from hello_world order by id asc limit 2; select id, flag from hello_world order by id asc limit 2 offset 2; ]] assert.same 2, num_queries assert.same { { { id: 1, flag: true } { id: 2, flag: true } } { { id: 3, flag: true } { id: 4, flag: true } } }, res it "gets three results", -> res, num_queries = assert pg\query [[ select id, flag from hello_world order by id asc limit 2; select id, flag from hello_world order by id asc limit 2 offset 2; select id, flag from hello_world order by id asc limit 2 offset 4; ]] assert.same 3, num_queries assert.same { { { id: 1, flag: true } { id: 2, flag: true } } { { id: 3, flag: true } { id: 4, flag: true } } { { id: 5, flag: true } { id: 6, flag: true } } }, res it "does multiple updates", -> res, num_queries = assert pg\query [[ update hello_world set flag = false where id = 3; update hello_world set flag = true; ]] assert.same 2, num_queries assert.same { { affected_rows: 1 } { affected_rows: 10 } }, res it "does mix update and select", -> res, num_queries = assert pg\query [[ update hello_world set flag = false where id = 3; select id, flag from hello_world where id = 3 ]] assert.same 2, num_queries assert.same { { affected_rows: 1 } { { id: 3, flag: false } } }, res it "returns partial result on error", -> res, err, partial, num_queries = pg\query [[ select id, flag from hello_world order by id asc limit 1; select id, flag from jello_world limit 1; ]] assert.same { err: [[ERROR: relation "jello_world" does not exist (104)]] num_queries: 1 partial: { { id: 1, flag: true } } }, { :res, :err, :partial, :num_queries } it "deserializes types correctly", -> assert pg\query [[ create table types_test ( id serial not null, name text default 'hello', subname varchar default 'world', count integer default 100, flag boolean default false, count2 double precision default 1.2, bytes bytea default E'\\x68656c6c6f5c20776f726c6427', config json default '{"hello": "world", "arr": [1,2,3], "nested": {"foo": "bar"}}', bconfig jsonb default '{"hello": "world", "arr": [1,2,3], "nested": {"foo": "bar"}}', uuids uuid[] default ARRAY['00000000-0000-0000-0000-000000000000']::uuid[], primary key (id) ) ]] assert pg\query [[ insert into types_test (name) values ('hello') ]] res = assert pg\query [[ select * from types_test order by id asc limit 1 ]] assert.same { { id: 1 name: "hello" subname: "world" count: 100 flag: false count2: 1.2 bytes: 'hello\\ world\'' config: { hello: "world", arr: {1,2,3}, nested: {foo: "bar"} } bconfig: { hello: "world", arr: {1,2,3}, nested: {foo: "bar"} } uuids: {'00000000-0000-0000-0000-000000000000'} } }, res assert pg\query [[ drop table types_test ]] describe "json", -> import encode_json, decode_json from require "pgmoon-mashape.json" it "encodes json type", -> t = { hello: "world" } enc = encode_json t assert.same [['{"hello":"world"}']], enc t = { foo: "some 'string'" } enc = encode_json t assert.same [['{"foo":"some ''string''"}']], enc it "encodes json type with custom escaping", -> escape = (v) -> "`#{v}`" t = { hello: "world" } enc = encode_json t, escape assert.same [[`{"hello":"world"}`]], enc it "serialize correctly", -> assert pg\query [[ create table json_test ( id serial not null, config json, primary key (id) ) ]] assert pg\query "insert into json_test (config) values (#{encode_json {foo: "some 'string'"}})" res = assert pg\query [[select * from json_test where id = 1]] assert.same { foo: "some 'string'" }, res[1].config assert pg\query "insert into json_test (config) values (#{encode_json {foo: "some \"string\""}})" res = assert pg\query [[select * from json_test where id = 2]] assert.same { foo: "some \"string\"" }, res[1].config assert pg\query [[ drop table json_test ]] describe "arrays", -> import decode_array, encode_array from require "pgmoon-mashape.arrays" it "converts table to array", -> import PostgresArray from require "pgmoon-mashape.arrays" array = PostgresArray {1,2,3} assert.same {1,2,3}, array assert PostgresArray.__base == getmetatable array it "encodes array value", -> assert.same "ARRAY[1,2,3]", encode_array {1,2,3} assert.same "ARRAY['hello','world']", encode_array {"hello", "world"} assert.same "ARRAY[[4,5],[6,7]]", encode_array {{4,5}, {6,7}} it "decodes empty array value", -> assert.same {}, decode_array "{}" import PostgresArray from require "pgmoon-mashape.arrays" assert PostgresArray.__base == getmetatable decode_array "{}" it "decodes numeric array", -> assert.same {1}, decode_array "{1}", tonumber assert.same {1, 3}, decode_array "{1,3}", tonumber assert.same {5.3}, decode_array "{5.3}", tonumber assert.same {1.2, 1.4}, decode_array "{1.2,1.4}", tonumber it "decodes multi-dimensional numeric array", -> assert.same {{1}}, decode_array "{{1}}", tonumber assert.same {{1,2,3},{4,5,6}}, decode_array "{{1,2,3},{4,5,6}}", tonumber it "decodes literal array", -> assert.same {"hello"}, decode_array "{hello}" assert.same {"hello", "world"}, decode_array "{hello,world}" it "decodes multi-dimensional literal array", -> assert.same {{"hello"}}, decode_array "{{hello}}" assert.same {{"hello", "world"}, {"foo", "bar"}}, decode_array "{{hello,world},{foo,bar}}" it "decodes string array", -> assert.same {"hello world"}, decode_array [[{"hello world"}]] it "decodes multi-dimensional string array", -> assert.same {{"hello world"}, {"yes"}}, decode_array [[{{"hello world"},{"yes"}}]] it "decodes string escape sequences", -> assert.same {[[hello \ " yeah]]}, decode_array [[{"hello \\ \" yeah"}]] it "fails to decode invalid array syntax", -> assert.has_error -> decode_array [[{1, 2, 3}]] it "decodes literal starting with numbers array", -> assert.same {"1one"}, decode_array "{1one}" assert.same {"1one", "2two"}, decode_array "{1one,2two}" it "decodes json array result", -> res = pg\query "select array(select row_to_json(t) from (values (1,'hello'), (2, 'world')) as t(id, name)) as items" assert.same { { items: { { id: 1, name: "hello" } { id: 2, name: "world" } } } }, res it "decodes jsonb array result", -> assert.same { { items: { { id: 442, name: "itch" } { id: 99, name: "zone" } } } }, pg\query "select array(select row_to_json(t)::jsonb from (values (442,'itch'), (99, 'zone')) as t(id, name)) as items" describe "with table", -> before_each -> pg\query "drop table if exists arrays_test" it "loads integer arrays from table", -> assert pg\query "create table arrays_test ( a integer[], b int2[], c int8[], d numeric[], e float4[], f float8[] )" num_cols = 6 assert pg\query "insert into arrays_test values (#{"'{1,2,3}',"\rep(num_cols)\sub 1, -2})" assert pg\query "insert into arrays_test values (#{"'{9,5,1}',"\rep(num_cols)\sub 1, -2})" assert.same { { a: {1,2,3} b: {1,2,3} c: {1,2,3} d: {1,2,3} e: {1,2,3} f: {1,2,3} } { a: {9,5,1} b: {9,5,1} c: {9,5,1} d: {9,5,1} e: {9,5,1} f: {9,5,1} } }, (pg\query "select * from arrays_test") it "loads string arrays from table", -> assert pg\query "create table arrays_test ( a text[], b varchar[], c char(3)[] )" num_cols = 3 assert pg\query "insert into arrays_test values (#{"'{one,two}',"\rep(num_cols)\sub 1, -2})" assert pg\query "insert into arrays_test values (#{"'{1,2,3}',"\rep(num_cols)\sub 1, -2})" assert.same { { a: {"one", "two"} b: {"one", "two"} c: {"one", "two"} } { a: {"1", "2", "3"} b: {"1", "2", "3"} c: {"1 ", "2 ", "3 "} } }, (pg\query "select * from arrays_test") it "loads string arrays from table", -> assert pg\query "create table arrays_test (ids boolean[])" assert pg\query "insert into arrays_test (ids) values ('{t,f}')" assert pg\query "insert into arrays_test (ids) values ('{{t,t},{t,f},{f,f}}')" assert.same { { ids: {true, false} } { ids: { {true, true} {true, false} {false, false} } } }, (pg\query "select * from arrays_test") it "converts null", -> pg.convert_null = true res = assert pg\query "select null the_null" assert pg.NULL == res[1].the_null it "converts to custom null", -> pg.convert_null = true n = {"hello"} pg.NULL = n res = assert pg\query "select null the_null" assert n == res[1].the_null it "encodes bytea type", -> n = { { bytea: "encoded' string\\" } } enc = pg\encode_bytea n[1].bytea res = assert pg\query "select #{enc}::bytea" assert.same n, res it "returns error message", -> status, err = pg\query "select * from blahlbhabhabh" assert.falsy status assert.same [[ERROR: relation "blahlbhabhabh" does not exist (15)]], err it "allows a query after getting an error", -> status, err = pg\query "select * from blahlbhabhabh" assert.falsy status res = pg\query "select 1" assert.truthy res it "errors when connecting with invalid server", -> pg2 = Postgres { database: "doesnotexist" } status, err = pg2\connect! assert.falsy status assert.same [[FATAL: database "doesnotexist" does not exist]], err teardown -> pg\disconnect! os.execute "dropdb -U postgres '#{DB}'" describe "pgmoon-mashape without server", -> escape_ident = { { "dad", '"dad"' } { "select", '"select"' } { 'love"fish', '"love""fish"' } } escape_literal = { { 3434, "3434" } { 34.342, "34.342" } { "cat's soft fur", "'cat''s soft fur'" } { true, "TRUE" } } local pg before_each -> pg = Postgres! for {ident, expected} in *escape_ident it "escapes identifier '#{ident}'", -> assert.same expected, pg\escape_identifier ident for {lit, expected} in *escape_literal it "escapes literal '#{lit}'", -> assert.same expected, pg\escape_literal lit
28.208929
127
0.526113
a61df7498c9e1a7992523e0ae3abd670296fffe1
7,399
-- Copyright 2012-2015 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) import config, mode from howl import formatting from howl.editing import style from howl.ui append = table.insert {:huge, :max, :min} = math is_comment = (line, comment_prefix) -> line\umatch r"^\\s*#{r.escape comment_prefix}" class DefaultMode completers: { 'in_buffer' } word_pattern: r'\\b[\\pL_][\\pL\\d_]*\\b' code_blocks: {} indent: (editor) => indent_level = editor.buffer.config.indent dont_indent_styles = comment: true, string: true buffer = editor.buffer current_line = editor.current_line editor\transform_active_lines (lines) -> comment_prefix = @_comment_pair! local prev_line for line in *lines continue if line.is_blank and line.nr != current_line.nr local indent prev_line or= line.previous_non_blank if comment_prefix and prev_line and is_comment(prev_line, comment_prefix) indent = prev_line.indentation else line_start_style = style.at_pos buffer, line.start_pos continue if dont_indent_styles[line_start_style] indent = @indent_for line, indent_level line.indentation = indent if indent != line.indentation prev_line = line with editor.cursor if .line != current_line.nr or .column < (current_line.indentation + 1) \move_to line: current_line.nr, column: current_line.indentation + 1 comment: (editor) => prefix, suffix = @_comment_pair! return unless prefix prefix ..= ' ' suffix = ' ' .. suffix unless suffix.is_empty buffer, cursor = editor.buffer, editor.cursor current_column = cursor.column tab_expansion = string.rep ' ', buffer.config.tab_width editor\transform_active_lines (lines) -> min_indent = huge for l in *lines unless l.is_blank min_indent = min(min_indent, l.indentation) for line in *lines unless line.is_blank text = line\gsub '\t', tab_expansion new_text = text\usub(1, min_indent) .. prefix .. text\usub(min_indent + 1) .. suffix if buffer.config.use_tabs new_text = new_text\gsub(tab_expansion, '\t') line.text = new_text cursor.column = current_column + #prefix unless current_column == 1 uncomment: (editor) => prefix, suffix = @_comment_pair! return unless prefix cursor = editor.cursor pattern = r"()#{r.escape prefix}\\s?().*?()\\s?#{r.escape suffix}()$" current_column = cursor.column cur_line = editor.current_line cursor_delta = nil editor\transform_active_lines (lines) -> for line in *lines pfx_start, middle_start, sfx_start, trail_start = line\umatch pattern if pfx_start head = line\usub 1, pfx_start - 1 middle = line\usub middle_start, sfx_start - 1 trail = line\usub trail_start line.text = head .. middle .. trail cursor_delta = middle_start - pfx_start if line == cur_line if cursor_delta cursor.column = max 1, current_column - cursor_delta toggle_comment: (editor) => prefix, _ = @_comment_pair! return unless prefix pattern = r"^\\s*#{r.escape prefix}.*" all_active_lines_commented = true for line in *editor.active_lines if not line\umatch(pattern) and not line.is_blank all_active_lines_commented = false break if all_active_lines_commented @uncomment editor else @comment editor structure: (editor) => buffer = editor.buffer buf_indent = buffer.config.indent threshold = buffer.config.indentation_structure_threshold line_levels = {} lines = {} cur_line = nil max_level = 0 for line in *editor.buffer.lines unless line.is_blank indentation = line.indentation if cur_line and indentation > cur_line.indentation unless cur_line\match '%a' prev = cur_line.previous cur_line = prev if prev and prev.indentation == cur_line.indentation if cur_line and cur_line\match '%a' level = cur_line.indentation / buf_indent max_level = max level, max_level line_levels[level] = 1 + (line_levels[level] or 0) append lines, { line: cur_line, :level } cur_line = line cut_off = 0 count = 0 for i = 0, max_level level_count = line_levels[i] if level_count cut_off = i count += level_count break if count >= threshold [l.line for l in *lines when l.level <= cut_off] resolve_type: (context) => pfx = context.prefix parts = {} leading = pfx\umatch r'((?:\\w+[.:])*\\w+)[.:]\\w*$' parts = [p for p in leading\gmatch '%w+'] if leading leading, parts on_insert_at_cursor: (args, editor) => if args.text == editor.buffer.eol buffer = editor.buffer if buffer.config.auto_format for code_block in * (@code_blocks.multiline or {}) return true if formatting.ensure_block editor, table.unpack code_block cur_line = editor.current_line prev_line = cur_line.previous_non_blank cur_line.indentation = prev_line.indentation if prev_line @indent editor true indent_for: (line, indent_level) => prev_line = line.previous_non_blank if prev_line spec = @indentation or {} dedent_delta = -indent_level if @patterns_match line.text, spec.less_for indent_delta = indent_level if @patterns_match prev_line.text, spec.more_after indent_delta = indent_level if not indent_delta and @patterns_match line.text, spec.more_for same_delta = 0 if @patterns_match prev_line.text, spec.same_after if indent_delta or dedent_delta or same_delta delta = (dedent_delta or 0) + (indent_delta or 0) + (same_delta or 0) new = prev_line.indentation + delta if new < prev_line.indentation and line.indentation <= new return line.indentation unless spec.less_for.authoritive return new -- unwarranted indents if spec.more_after and spec.more_after.authoritive != false and line.indentation > prev_line.indentation return prev_line.indentation if spec.less_for and spec.less_for.authoritive != false and line.indentation < prev_line.indentation return prev_line.indentation return prev_line.indentation if line.is_blank alignment_adjustment = line.indentation % indent_level line.indentation + alignment_adjustment patterns_match: (text, patterns) => return false unless patterns for p in *patterns neg_match = nil if typeof(p) == 'table' p, neg_match = p[1], p[2] match = text\umatch p if match and (not neg_match or not text\umatch neg_match) return true false _comment_pair: => return unless @comment_syntax prefix, suffix = @comment_syntax, '' if type(@comment_syntax) == 'table' {prefix, suffix} = @comment_syntax prefix, suffix -- Config variables with config .define name: 'indentation_structure_threshold' description: 'The indentation structure parsing will stop once this number of lines has been collected' default: 10 type_of: 'number' mode.register name: 'default', create: DefaultMode DefaultMode
30.829167
110
0.664684
14ecb2b6b698897bbaf3ccb8f065c3fcb8786f13
343
-- Copyright 2017 The Howl Developers -- License: MIT (see LICENSE.md at the top-level directory of the distribution) { lexer: bundle_load('dart_lexer') comment_syntax: '//' auto_pairs: { '(': ')' '[': ']' '{': '}' '"': '"' "'": "'" } indentation: more_after: { '=>%s*$', '[[{(]%s*$', } }
14.913043
79
0.478134