• Useful Code Snippets
    232 replies, posted
How To Live Update DListView and Override Paint [code]myglobal = myglobal or { } net.Receieve("dlistview_update", function(len) local tbl = net.ReadTable() if myglobal.panel and myglobal.panel:IsVisible() then myglobal:FillList( end end) function myglobal:FillList(frame) if frame == nil then frame = self.OurList end frame:Clear() for k, v in pairs(tbl) do ---- This is the tbl you are updating the data with local line = frame:AddLine( v[1] ) end local wBatt = 0 frame.Paint = function( self, w, h ) ------- If you are doing paint overrides, you do that stuff here// draw.RoundedBoxEx( 8, 0, 0, w, h, Color( 36, 36, 36, 255 ), false, false, true, true) wBatt = w end for k, v in pairs( frame.Lines ) do v.Paint = function() draw.SimpleText( v:GetValue(1), "your_font", wBatt/2, 0, Color(255, 255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) end end end local PANEL = { } function PANEL:Init() self.Frame = vgui.Create("DFrame"); self.Frame:SetSize( 400, 200 ); self.Frame:Center() self.Frame:SetTitle(" Updating List View "); self.Frame:SetScreenLock(true); self.Frame:SetDraggable(false); self.Frame:ShowCloseButton(false); self.Frame:MakePopup(); self.List = vgui.Create( "DListView", self.Frame ) self.List:SetMultiSelect( false ) self.List:Dock( FILL ) myglobal:FillList(self.List) myglobal.panel = self.Frame myglobal.OurList = self.List end[/code]
I found those in some of my old files someone might find it useful, do whatever with it Disable opening the spawn menu [code]hook.Add("SpawnMenuOpen", "DisallowSpawnMenu", function() if !(LocalPlayer():IsAdmin() or LocalPlayer():IsSuperAdmin()) then return false end end)[/code] Disable opening the context menu [code]hook.Add("ContextMenuOpen", "DisallowContextMenu", function() if !(LocalPlayer():IsAdmin() or LocalPlayer():IsSuperAdmin()) then return false end end)[/code]
Does that actually disable it or just hide it? They could probably still use stuff like gm_spawn.
[QUOTE=SirFrancisB;51669627]Does that actually disable it or just hide it? They could probably still use stuff like gm_spawn.[/QUOTE] No it doesnt but this will: [code]local allowed_groups = { ["superadmin"] = true, ["admin"] = false -- Add groups like: -- ["groupname"] = true -- Note: Last entry doesn't need comma } if (SERVER) then local spawn_hooks = {"Effect", "NPC", "Object", "Prop", "Ragdoll", "SENT", "SWEP", "Vehicle"} for k, v in pairs(spawn_hooks) do hook.Add("PlayerSpawn" .. v, "Prevent_Spawn" .. v, function(ply) if (not allowed_groups[ply:GetUserGroup()]) then return false end end) end else hook.Add("SpawnMenuOpen", "Prevent_SpawnMenu", function() if (not allowed_groups[LocalPlayer():GetUserGroup()]) then return false end end) hook.Add("ContextMenuOpen", "Prevent_ContextMenu", function() if (not allowed_groups[LocalPlayer():GetUserGroup()]) then return false end end) end[/code]
I found the existing 2D3D interaction libraries to be pretty confusing so using examples from others i made my own simplified one. [LUA] local Interactive2D3D = {} Interactive2D3D.IsVisible = function(self) return (self.Visible or false) end Interactive2D3D.Start = function(self, vPos, aRot, vScale) if !vPos or !aRot then return false end self.Valid = true local plpostoscreenx = vPos.x - LocalPlayer():GetShootPos().x local plpostoscreeny = vPos.y - LocalPlayer():GetShootPos().y local plpostoscreen = math.sqrt( plpostoscreenx^2+plpostoscreeny^2 ) local dist1 = 1/( math.cos( math.rad( EyeAngles().y ) ) ) * plpostoscreen local distfull = 1/( math.cos( math.rad( EyeAngles().p ) ) ) * dist1 local trace = {} trace.start = LocalPlayer():GetShootPos() trace.endpos = LocalPlayer():GetAimVector() * distfull + trace.start trace.filter = LocalPlayer() local tr = util.TraceLine( trace ) if tr.Entity and IsValid(tr.Entity) then self.Visible = false return false end self.Visible = true local test = trace.endpos local vWorldPos=test-vPos; vWorldPos:Rotate( Angle( 0, -aRot.y, 0 ) ); vWorldPos:Rotate( Angle( -aRot.p, 0, 0 ) ); vWorldPos:Rotate( Angle( 0, 0, -aRot.r ) ); self.EyeHitx = (vWorldPos.x/(vScale or 1)) self.EyeHity = ((-vWorldPos.y)/(vScale or 1)) return true end Interactive2D3D.Finish = function(self) if !self:IsVisible() then return false end return self:Remove() end Interactive2D3D.Use = function(self, Name) if !self:IsVisible() then return false end if !Name and self.Buttons then for _,v in pairs(self.Buttons) do if self:Use(v.Name) then if (v.LastClick or 0) < CurTime() then if v.DoClick then self:Remove(v.Name) v:DoClick() v.LastClick = CurTime()+0.1 return v.Name end end break end end else if !self.Buttons or !self.Buttons[Name] then return false end return self.Buttons[Name]:IsHovered() end end hook.Add( "KeyPress", "Interactive2D3DKeyPress", function( _, key ) if ( key == IN_USE ) then Interactive2D3D:Use() end end ) Interactive2D3D.Remove = function(self, Name) if Name and self.Buttons and self.Buttons[Name] then self.Buttons[Name] = nil else self.Buttons = {} self.Visible = false self.Valid = false end return true end Interactive2D3D.MakeButton = function(self, x, y, w, h , Name) if !Name or !self.Valid then return false end self.Buttons = self.Buttons or {} if self.Buttons[Name] then if self:IsVisible() and self.EyeHitx and self.EyeHity then if (self.EyeHitx < w-(x*-1)) and (self.EyeHitx > x) and (self.EyeHity < h-(y*-1)) and (self.EyeHity > y) then if !self.Buttons[Name].Hovered then self.Buttons[Name].Hovered = true end else if self.Buttons[Name].Hovered then self.Buttons[Name].Hovered = false end end if self.Buttons[Name].Paint then self.Buttons[Name]:Paint(x, y, w, h) end end return self.Buttons[Name] end local Button = {} Button.Name = Name Button.Hovered = false Button.IsHovered = function(this) return this.Hovered or false end Button.Remove = function(this) return self:Remove(this.Name) or false end Button.Pos = {x = (x or 0), y = (y or 0), w = (w or 0), h = (h or 0)} Button.GetPos = function(this) return this.Pos or {} end self.Buttons[Name] = Button return Button end [/LUA] You can find the [URL="https://gist.github.com/mattkrins/9983ea8ebca71d85a8c643bdadaab442"]latest version[/URL] and example usage on my Gist.
[QUOTE=101kl;51708734]I found the existing 2D3D interaction libraries to be pretty confusing so using examples from others i made my own simplified one. [LUA] local Interactive2D3D = {} Interactive2D3D.IsVisible = function(self) return (self.Visible or false) end Interactive2D3D.Start = function(self, vPos, aRot, vScale) if !vPos or !aRot then return false end self.Valid = true local plpostoscreenx = vPos.x - LocalPlayer():GetShootPos().x local plpostoscreeny = vPos.y - LocalPlayer():GetShootPos().y local plpostoscreen = math.sqrt( plpostoscreenx^2+plpostoscreeny^2 ) local dist1 = 1/( math.cos( math.rad( EyeAngles().y ) ) ) * plpostoscreen local distfull = 1/( math.cos( math.rad( EyeAngles().p ) ) ) * dist1 local trace = {} trace.start = LocalPlayer():GetShootPos() trace.endpos = LocalPlayer():GetAimVector() * distfull + trace.start trace.filter = LocalPlayer() local tr = util.TraceLine( trace ) if tr.Entity and IsValid(tr.Entity) then self.Visible = false return false end self.Visible = true local test = trace.endpos local vWorldPos=test-vPos; vWorldPos:Rotate( Angle( 0, -aRot.y, 0 ) ); vWorldPos:Rotate( Angle( -aRot.p, 0, 0 ) ); vWorldPos:Rotate( Angle( 0, 0, -aRot.r ) ); self.EyeHitx = (vWorldPos.x/(vScale or 1)) self.EyeHity = ((-vWorldPos.y)/(vScale or 1)) return true end Interactive2D3D.Finish = function(self) if !self:IsVisible() then return false end return self:Remove() end Interactive2D3D.Use = function(self, Name) if !self:IsVisible() then return false end if !Name and self.Buttons then for _,v in pairs(self.Buttons) do if self:Use(v.Name) then if (v.LastClick or 0) < CurTime() then if v.DoClick then self:Remove(v.Name) v:DoClick() v.LastClick = CurTime()+0.1 return v.Name end end break end end else if !self.Buttons or !self.Buttons[Name] then return false end return self.Buttons[Name]:IsHovered() end end hook.Add( "KeyPress", "Interactive2D3DKeyPress", function( _, key ) if ( key == IN_USE ) then Interactive2D3D:Use() end end ) Interactive2D3D.Remove = function(self, Name) if Name and self.Buttons and self.Buttons[Name] then self.Buttons[Name] = nil else self.Buttons = {} self.Visible = false self.Valid = false end return true end Interactive2D3D.MakeButton = function(self, x, y, w, h , Name) if !Name or !self.Valid then return false end self.Buttons = self.Buttons or {} if self.Buttons[Name] then if self:IsVisible() and self.EyeHitx and self.EyeHity then if (self.EyeHitx < w-(x*-1)) and (self.EyeHitx > x) and (self.EyeHity < h-(y*-1)) and (self.EyeHity > y) then if !self.Buttons[Name].Hovered then self.Buttons[Name].Hovered = true end else if self.Buttons[Name].Hovered then self.Buttons[Name].Hovered = false end end if self.Buttons[Name].Paint then self.Buttons[Name]:Paint(x, y, w, h) end end return self.Buttons[Name] end local Button = {} Button.Name = Name Button.Hovered = false Button.IsHovered = function(this) return this.Hovered or false end Button.Remove = function(this) return self:Remove(this.Name) or false end Button.Pos = {x = (x or 0), y = (y or 0), w = (w or 0), h = (h or 0)} Button.GetPos = function(this) return this.Pos or {} end self.Buttons[Name] = Button return Button end [/LUA] You can find the [URL="https://gist.github.com/mattkrins/9983ea8ebca71d85a8c643bdadaab442"]latest version[/URL] and example usage on my Gist.[/QUOTE] thank you! completely removes all keys functionality in my gamemode :)
[QUOTE=StickmanJohn;51713737]thank you! completely removes all keys functionality in my gamemode :)[/QUOTE] No idea how you managed that; this code doesn't override the Use function, it only hooks into it: [LUA]hook.Add( "KeyPress", "Interactive2D3DKeyPress", function( _, key ) if ( key == IN_USE ) then Interactive2D3D:Use() end end )[/LUA]
[QUOTE=101kl;51718908]No idea how you managed that; this code doesn't override the Use function, it only hooks into it: [LUA]hook.Add( "KeyPress", "Interactive2D3DKeyPress", function( _, key ) if ( key == IN_USE ) then Interactive2D3D:Use() end end )[/LUA][/QUOTE] by keys i mean my swep keys
[QUOTE=StickmanJohn;51721411]by keys i mean my swep keys[/QUOTE] But you were talking about your gamemode?
[QUOTE=StickmanJohn;51721411]by keys i mean my swep keys[/QUOTE] And it doesn't touch anything to do with SWEPS. My code works perfectly fine and should not conflict with anything. You have broken your gamemode/sweps. Not me.
IMO a better way to make circles, in derma, or really any shape. [LUA]local meta = FindMetaTable( "Panel" ) function meta:SetVertices( verts ) self.vertices = {} local radiusW = self:GetWide() / 2 local radiusH = self:GetTall() / 2 self.vertices[ #self.vertices + 1 ] = { x = radiusW, y = radiusH } for i = 0, verts do local a = math.rad( i / verts * -360 ) self.vertices[ #self.vertices + 1 ] = { x = radiusW + math.sin( a ) * radiusW, y = radiusH + math.cos( a ) * radiusH } end self.vertices[ #self.vertices + 1 ] = { x = radiusW, y = radiusH } self:SetPaintedManually( true ) self.vParent = vgui.Create( "Panel", self:GetParent() ) self.vParent:SetPos( self:GetPos() ) self.vParent:SetSize( self:GetSize() ) self.vParent.vChild = self function self.vParent:Paint() if !self.vChild or !IsValid( self.vChild ) then return end render.ClearStencil() render.SetStencilEnable( true ) render.SetStencilWriteMask( 1 ) render.SetStencilTestMask( 1 ) render.SetStencilFailOperation( STENCILOPERATION_REPLACE ) render.SetStencilCompareFunction( STENCILCOMPARISONFUNCTION_EQUAL ) render.SetStencilReferenceValue( 1 ) draw.NoTexture() surface.SetDrawColor( color_white ) surface.DrawPoly( self.vChild.vertices ) render.SetStencilFailOperation( STENCILOPERATION_ZERO ) render.SetStencilCompareFunction( STENCILCOMPARISONFUNCTION_EQUAL ) render.SetStencilReferenceValue( 1 ) self.vChild:PaintManual() render.SetStencilEnable( false ) end end[/LUA] Example of usage: [LUA]local DPanel = vgui.Create( "DPanel" ) DPanel:SetSize( 100, 100 ) DPanel:SetVertices( 6 )[/LUA] That would create a hexagon at the top left of the screen.
Why are you creating a new panel? Just detour paint on self
[QUOTE=Klaes4Zaugen;51771006]Why are you creating a new panel? Just detour paint on self[/QUOTE] If you use PaintManual then paint wont be called.
[QUOTE=101kl;51722387]And it doesn't touch anything to do with SWEPS. My code works perfectly fine and should not conflict with anything. You have broken your gamemode/sweps. Not me.[/QUOTE] i meant the functionality, there is no point having keys now when i just use this :P
Get the velocity a player will have if they fall X units, and vice versa: [code]local cv_gravity = GetConVar( "sv_gravity" ) function util.SpeedToFallHeight( fallSpeed ) return fallSpeed * fallSpeed / (2 * cv_gravity:GetInt()) end function util.FallHeightToSpeed( fallHeight ) return math.sqrt( cv_gravity:GetInt() * 2 * fallHeight ) end[/code] (Taken from [url]https://github.com/LestaD/SourceEngine2007/blob/master/se2007/game/shared/cstrike/cs_gamemovement.cpp#L676[/url])
Serverside chat.AddText [lua]AddCSLuaFile() if SERVER then util.AddNetworkString( "sendTeamText" ) else net.Receive( "sendTeamText", function() chat.AddText( unpack(net.ReadTable()) ) end ) return end chat = {} function chat.AddText( ... ) net.Start( "sendTeamText" ) net.WriteTable( {...} ) net.Broadcast() net.Send()-- send to player using net.Send() end[/lua] Do something after a set amount of time - uses utime [lua] local meta = FindMetaTable("Player") delayMins = 2 -- Amount of time to perform action after in minutes function meta:GenericTimerStart() timer.Create("GenericTimer-" .. tostring(self:UniqueID()), 10, 0, function() if not ( self and IsValid( self ) ) then return end utimeAddToTeam( self ) end ) end hook.Add( "PlayerInitialSpawn", "GenericTimerStart", GenericTimerStart ) function meta:GenericTimerEnd() local uid = tostring(self:UniqueID()) if timer.Exists("GenericTimer-" .. uid)) then timer.Stop("GenericTimer-" .. uid)) timer.Destroy("GenericTimer-" .. uid)) end end hook.Add( "PlayerDisconnected", "GenericTimerEnd", GenericTimerEnd ) function meta:utimeAddToTeam() local plyMins = math.floor( ( self:GetUTime() + CurTime() - self:GetUTimeStart() )/60) local uid = tostring(self:UniqueID()) if plyMins >= delayMins then Msg( "Replace this with your action" ) end if not timer.Exists("GenericTimer-" .. uid) then timer.Create("GenericTimer-" .. uid), 10, 0, function() if not ( self and IsValid( self ) ) then return end utimeAddToTeam( self ) end ) end end[/lua]
Draws vertical rectangles, health bars, armor bars etc. The bgcolor is a background Color, make it the same if you wish to not have a background. [CODE]function DrawVerticalRect(font, xpos, ypos, w, h, equation, color, bgcolor, title, value) draw.SimpleText( title, font, xpos + (w / 2), ypos - h - 18, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP) surface.SetDrawColor(bgcolor) surface.DrawRect(xpos, ypos - h, w , h ) surface.SetDrawColor(Color(color.r, color.g, color.b, 20)) surface.DrawRect(xpos + 2, ypos - h + 2, w - 4, h - 4 ) surface.SetDrawColor(color) surface.DrawRect(xpos + 2, ypos - ( h * equation) + 2, w - 4 , h * equation - 4) draw.SimpleText( value, font, xpos + (w / 2), h + 27, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) end[/CODE] Example use: [CODE] local w = ScrW() local h = ScrH() DrawVerticalRect("HungerGames_24", w / 2 - 10, h - 20, BarW, 60, math.Clamp(v:Health(), 0, 100) / v:GetMaxHealth() or 0, Color(209,15,47,255), Color(70,70,70,255), "HP", v:Health())[/CODE] Output: [IMG]https://i.gyazo.com/7bd5a718e432edd7e73d7a93600b25d9.png[/IMG]
[QUOTE=dannyf127;51879572]Draws verticle rectangles, health bars, armor bars etc. The bgcolor is a background Color, make it the same if you wish to not have a background. [/QUOTE] Hey, this is pretty cool, I can actually see myself using more than 2 things on here from now on!
[URL="https://github.com/XxLMM13xXgaming/lmm_guis"]Heres[/URL] a GUI lib i started it has just one GUI right now however i will add some more throughout time! If you would like to add your own just make a pull request or something! Heres some pics: Main Frame [IMG]https://camo.githubusercontent.com/8e644b93beab4678bc735552e70f7faae83607d0/687474703a2f2f692e696d6775722e636f6d2f364631766a79542e706e67[/IMG] Frame when close BTN is hovered [IMG]https://camo.githubusercontent.com/5f752165e3bf84101d24fb7e0718d7c721797e62/687474703a2f2f692e696d6775722e636f6d2f686245377832572e706e67[/IMG] Frame when test BTN is hovered [IMG]https://camo.githubusercontent.com/d7e7e682844db513d6d1bfc41d8e23f52a9338f9/687474703a2f2f692e696d6775722e636f6d2f6977326f626f512e706e67[/IMG]
[QUOTE=XxLMM13xXx;51879630][URL="https://github.com/XxLMM13xXgaming/lmm_guis"]Heres[/URL] a GUI lib i started it has just one GUI right now however i will add some more throughout time! If you would like to add your own just make a pull request or something![/QUOTE] Pictures would be awesome.
[QUOTE=VeXan;51879657]Pictures would be awesome.[/QUOTE] Well there are some on the git page but heres a few... Main Frame [IMG]https://camo.githubusercontent.com/8e644b93beab4678bc735552e70f7faae83607d0/687474703a2f2f692e696d6775722e636f6d2f364631766a79542e706e67[/IMG] Frame when close BTN is hovered [IMG]https://camo.githubusercontent.com/5f752165e3bf84101d24fb7e0718d7c721797e62/687474703a2f2f692e696d6775722e636f6d2f686245377832572e706e67[/IMG] Frame when test BTN is hovered [IMG]https://camo.githubusercontent.com/d7e7e682844db513d6d1bfc41d8e23f52a9338f9/687474703a2f2f692e696d6775722e636f6d2f6977326f626f512e706e67[/IMG] Also edited my last post
Not a code snippet, but I found this in the vphysics interface and it is the first proper explanation of Source units/directions I've seen: [code]// ------------------------------------------------------------------------------------ // UNITS: // ------------------------------------------------------------------------------------ // NOTE: Coordinates are in HL units. 1 unit == 1 inch. X is east (forward), Y is north (left), Z is up (up) // QAngle are pitch (around y), Yaw (around Z), Roll (around X) // AngularImpulse are exponetial maps (an axis in HL units scaled by a "twist" angle in degrees) // They can be transformed like normals/covectors and added linearly // mass is kg, volume is in^3, acceleration is in/s^2, velocity is in/s // density is kg/m^3 (water ~= 998) // preferably, these would be in kg/in^3, but the range of those numbers makes them not very human readable // having water be about 1000 is really convenient for data entry. // Since volume is in in^3 and density is in kg/m^3: // density = (mass / volume) * CUBIC_METERS_PER_CUBIC_INCH // Force is applied using impulses (kg*in/s) // Torque is applied using impulses (kg*degrees/s) // ------------------------------------------------------------------------------------[/code] On topic, here's a formula that will find force from troy grains and feet/sec. This is really useful for accurate bullet impulse. [code]-- 1 grain = exactly 64.79891 milligrams -- 0.00006479891 kilo -- 12 inches = 1 ft -- 12 * 0.00006479891 = 0.00077758692 -- Returns kg*in/s function math.GrainFeetForce(flGrains, flFtPerSec, flExaggeration --[[= 1]]) return flGrains * flFtPerSec * 0.00077758692 * (flExaggeration or 1) end[/code]
[QUOTE=code_gs;51880734][code]// units[/code][/QUOTE] Inches make me sad :(
Why are you working on kilos and then inches Edit: Nvm, is valve's fault
[QUOTE=Sanxy;51879400]Serverside chat.AddText [lua]AddCSLuaFile() if SERVER then util.AddNetworkString( "sendTeamText" ) else net.Receive( "sendTeamText", function() chat.AddText( unpack(net.ReadTable()) ) end ) return end chat = {} function chat.AddText( ... ) net.Start( "sendTeamText" ) net.WriteTable( {...} ) net.Broadcast() net.Send()-- send to player using net.Send() end[/lua] [/QUOTE] Here is one that works for both console and chat. With broadcasting possible. [url]https://github.com/CenturiesGaming/custom_stuff/blob/master/lua/autorun/colored_chat_message.lua[/url]
[QUOTE=andreblue;51883667]Here is one that works for both console and chat. With broadcasting possible. [url]https://github.com/CenturiesGaming/custom_stuff/blob/master/lua/autorun/colored_chat_message.lua[/url][/QUOTE] Just a note here: Any color < 151 will not render in srcds.exe
[QUOTE=Derek_SM;51884150]Just a note here: Any color < 151 will not render in srcds.exe[/QUOTE] Serverside or clientside? And in the console or the chat?
[QUOTE=andreblue;51885500]Serverside or clientside? And in the console or the chat?[/QUOTE] The server. srcds = source dedicated server
[QUOTE=dannyf127;51879572][CODE]function DrawVerticleRect[/CODE][/QUOTE] VERTI[B]CAL[/B] DAMMIT
[QUOTE=MPan1;51885638]VERTI[B]CAL[/B] DAMMIT[/QUOTE] ok.
Sorry, you need to Log In to post a reply to this thread.