[ create a new paste ] login | about

Link: http://codepad.org/PtEcWdQQ    [ raw code | output | fork ]

Lua, pasted on Mar 2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
--[[
	Filename:	"smartwelder.lua".
	Author(s):	"Duncan Stead, TheBlackShadowOfGod (GMod 13)".
--]]

TOOL.Category		= "Constraints"
TOOL.Name			= "#Weld - Smart"
TOOL.Command		= nil
TOOL.ConfigName		= ""
TOOL.busy           =false

--the default smartweld settings
TOOL.ClientConVar["radius"]=128
TOOL.ClientConVar["nocollideradius"]=128
TOOL.ClientConVar["maxweldspp"]=3
TOOL.ClientConVar["randomwelds"]=1
TOOL.ClientConVar["nocollide"]=1
TOOL.ClientConVar["unfreeze"]=1
TOOL.ClientConVar["autofreeze"]=0
TOOL.ClientConVar["refreshwelds"]=1
TOOL.ClientConVar["weldstrength"]=0


-- edit these variables to customise your install

--when welding over time, weldtime is the gap between successive welds/nocollides
WELDTIME=0.01
--notifygap is the multiple of which the player will be informed of the smartweld progress (ie. weld 50, 100, 150 placed)
NOTIFYGAP=50
--slowmode is welding over time.  Turning this off will make smart welder perform the weld in one go, making it more likely to crash with big contraptions
SLOWMODE=true
--if you have this on, the script will attempt to follow Conna's prop protection scheme
USEPROPPROTECTION=false

if CLIENT then
	language.Add( "Tool.smartwelder.name", "Smart Welder" )
	language.Add( "Tool.smartwelder.desc", "Automatically welds selected props" )
	language.Add( "Tool.smartwelder.0", "Select props with left click (hold use key to auto-select). Smart-weld with right click (hold use to weld to one prop). Reload clears selection." )

	language.Add( "Undone_smartweld", "Undone Smart Weld" )
end


function TOOL:LeftClick( trace )

	if !self.busy then
		if self.props==nil then
			self.props={}
		end

		for a,v in ipairs(self.props) do
			if !v.ent:IsValid() then
				table.remove(self.props,a)
			end
		end
		
		if !trace.HitPos then return false end
		if trace.Entity:IsPlayer() then return false end

		if SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone )  then return false end
		if CLIENT  then return true end

		// Get client's CVars
		local ply = self:GetOwner()

		local radius=self:GetClientNumber("radius")
		local nocollideradius=self:GetClientNumber("nocollideradius")
		local randomwelds = self:GetClientNumber("randomwelds")
		local smartnocollide = self:GetClientNumber("nocollide") == 1
		local weldsperprop = self:GetClientNumber("maxweldspp")

		if trace.Entity:IsValid() && trace.Entity:GetPhysicsObject():IsValid() then
			if ply:KeyDown(IN_USE)||ply:KeyDown(IN_SPEED) then
				local selectedcount=self:Autoselect(trace.Entity,radius)
				if selectedcount>1 then
					self:GetOwner():PrintMessage(HUD_PRINTCENTER,selectedcount.." props auto-selected")
				end
			else
				self:ChooseEnt(trace.Entity)
			end
		end
	return true
	else
	return false
	end
end

function TOOL:Autoselect(ent,radius)
	local counted=0
	if ent:IsValid() && ent:GetPhysicsObject():IsValid() && !ent:IsPlayer() then
		if !self:IsSelected(ent) then
			if self:IsPropOwner(self:GetOwner(),ent) then
				--add to list, try adding everything near it to list
				self:SelectEnt(ent,false)
				counted=1
				local close_ents = ents.FindInSphere( ent:GetPos(), radius )

	for i,v in ipairs(close_ents) do
	if v!=ent then
	counted=counted+self:Autoselect(v,radius)
	end
	end
	end
	end
	end
	return counted
end

function TOOL:IsSelected(ent)

    	 local selected=-1
       for i,v in ipairs(self.props) do
           if v.ent==ent then
		   selected=i
		   break
		   end
	   end
	   
	   if selected==-1 then
	        return false
		else
		    return true
	   end

end

--Based on a function by Conna
function TOOL:IsPropOwner(ply, ent)

	if USEPROPPROTECTION then
	for k, v in pairs(g_SBoxObjects) do
		for b, j in pairs(v) do
			for _, e in pairs(j) do
				if e == ent then
					if k == ply:UniqueID() then
						return true
					end
				end
			end
		end
	end

	for k, v in pairs(GAMEMODE.CameraList) do
		for b, j in pairs(v) do
			if j == ent then
				if k == ply:UniqueID() then
					return true
				end
			end
		end
	end
	return false
	else
	return true
	end
end

function TOOL:ChooseEnt(ent)

		  if self:IsPropOwner(self:GetOwner(),ent) then
		  
	         local selected=-1
	       for i,v in ipairs(self.props) do
	           if v.ent==ent then
			   selected=i
			   break
			   end
		   end
	         if selected==-1 then
		       local r,g,b,a = ent:GetColor();
			   table.insert(self.props,{ent=ent,r=r,g=g,b=b,a=a})
			   ent:SetColor(0,255,0,255)
		   else
			   ent:SetColor(self.props[selected].r,self.props[selected].g,self.props[selected].b,self.props[selected].a)
			   table.remove(self.props,selected)
		   end
	   end
end




function TOOL:DeselectEnt(ent)

         if self:IsPropOwner(self:GetOwner(),ent) then
         local selected=-1
       for i,v in ipairs(self.props) do
           if v.ent==ent then
		   selected=i
		   break
		   end
	   end
         if selected==-1 then

	   else
       	   ent:SetColor(self.props[selected].r,self.props[selected].g,self.props[selected].b,self.props[selected].a)
		   table.remove(self.props,selected)
	   end
	   end
end



function TOOL:SelectEnt(ent)

   if self:IsPropOwner(self:GetOwner(),ent) then
    local r,g,b,a = ent:GetColor();
	table.insert(self.props,{ent=ent,r=r,g=g,b=b,a=a})
	ent:SetColor(0,255,0,255)
   end

end

function TOOL:WeldingFinished(unfreeze, weldcount, holdinguse, proptable,ply)
		 undo.SetPlayer( ply )
			undo.Finish()

			--if set to auto unfreeze
			if unfreeze then

				 for a,v in ipairs(proptable) do
				     if v.ent:IsValid() then
						 local entphys=v.ent:GetPhysicsObject()
						 if entphys:IsValid() then
						        entphys:EnableMotion(true)
						        entphys:Wake()
						 end
					 end
				 end

			end
			


			if holdinguse then
			    if weldcount!=1 then
      				self:GetOwner():PrintMessage(HUD_PRINTCENTER,"Weld to prop complete! "..weldcount.." welds placed")
		    	else
      			self:GetOwner():PrintMessage(HUD_PRINTCENTER,"Weld to prop complete! "..weldcount.." weld placed")
		    	end

			else

				if weldcount!=1 then
			    self:GetOwner():PrintMessage(HUD_PRINTCENTER,"Smart-weld complete! "..weldcount.." welds placed")
			    else
			    self:GetOwner():PrintMessage(HUD_PRINTCENTER,"Smart-weld complete! "..weldcount.." weld placed")
			    end
		    end
		    
		    --deselect
		    self.busy=false
		    self:ResetSelection()
end

function TOOL:WeldEnts(ent1, ent2, bone1, bone2, weldstrength, smartnocollide, weldcount)

         if ent1:IsValid() and ent2:IsValid() then
	         local const = constraint.Weld( ent1, ent2, bone1, bone2, weldstrength, smartnocollide )
			 undo.AddEntity( const )

			 if (weldcount+1)%NOTIFYGAP==0 then

			 		self:GetOwner():PrintMessage(HUD_PRINTCENTER,"Weld "..(weldcount+1).." placed")

			 end
		 end

end

function TOOL:NoCollideEnts(ent1, ent2,bone1,bone2,nocollidecount)

   if ent1:IsValid() and ent2:IsValid() then
	   local nocoll=constraint.NoCollide(ent1,ent2,bone1,bone2)
	   --setup their undo
	   undo.AddEntity(nocoll)

	   if (nocollidecount+1)%NOTIFYGAP==0 then
	   		self:GetOwner():PrintMessage(HUD_PRINTCENTER,"Nocollide "..(nocollidecount+1).." placed")
	   end
   
   end
end

function TOOL:RightClick( trace )
	if self.busy then
	
	else
	
	local ply = self:GetOwner()
	local randomwelds = self:GetClientNumber("randomwelds")
	local smartnocollide = self:GetClientNumber("nocollide") == 1
	local autofreeze = self:GetClientNumber("autofreeze") == 1
	local unfreeze = self:GetClientNumber("unfreeze") == 1
	local refreshwelds = self:GetClientNumber("refreshwelds") == 1
	local weldsperprop = self:GetClientNumber("maxweldspp")
	local nocollideradius=self:GetClientNumber("nocollideradius")
	local weldstrength=self:GetClientNumber("weldstrength")
	
	if self.props!=nil then
	
		for a,v in ipairs(self.props) do
			if !v.ent:IsValid() then
				table.remove(self.props,a)
			end
		end
		
		if #self.props>1 then
		
		
		    self.busy=true
		    --prefreeze
		    
			if autofreeze then

				 for a,v in ipairs(self.props) do
					 local entphys=v.ent:GetPhysicsObject()
					 if entphys:IsValid() then
					        entphys:EnableMotion(false)
					        entphys:Sleep()
					 end
				 end

			end
		
		    if refreshwelds then
			    --get rid of old contraints
			    for a,v in ipairs(self.props) do

			    	local constrs = constraint.FindConstraints( v.ent, "Weld" )

			    	--for every weld, see if it is welded to a selected prop, in which case remove it
					for b,w in ipairs(constrs) do

					    for c,p in ipairs(self.props) do

	                        if w.Entity[2].Entity==p.ent then
								  if p.ent==v.ent then

								  else

								      --remove the weld
									  w.Constraint:Remove()
								  end

	                        end

					    end


					end

			    end
		    
		    end
		
		
		
		
	        undo.Create("smartweld")

			local welds={}
			for a,v in ipairs(self.props) do
				welds[a]={}
			end

			local weldcount=0
			local holdinguse=false

            if ply:KeyDown(IN_USE)||ply:KeyDown(IN_SPEED) then
                if !trace.HitPos then return false end
				if trace.Entity:IsPlayer() then return false end

				if SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone )  then return false end

				if CLIENT  then return true end
				
				if trace.Entity:IsValid() && trace.Entity:GetPhysicsObject():IsValid() then
				
				   local weldtarget=trace.Entity
				   holdinguse=true
				   self:DeselectEnt(trace.Entity)
				   
				   for a,v in ipairs(self.props) do
				   
				       if v.ent==weldtarget then
				       
				       else
				       
				   
					       local const = constraint.Weld( v.ent, weldtarget, 0, 0, weldstrength, smartnocollide )
					       undo.AddEntity( const )

					       weldcount=weldcount+1
				       
				       end

				   end
				
				end
				
				
            else
            
				for a,v in ipairs(self.props) do
				    for x=1,weldsperprop do
					    local closestdistance=99999999
					    local closestprop=-1
					    for b,w in ipairs(self.props) do
							if a!=b then
									 local linked=false
									 for i,val in ipairs(welds[a]) do
									 	 if val==b then
									 	 			linked=true
									 				break
										end
									 end

									 if !linked then

									 			 local distance=(v.ent:GetPos()-w.ent:GetPos()):Length()
									             if distance<closestdistance then
									             	closestdistance=distance
									             	closestprop=b
									             end
									 end
							end
					    end

					    if closestprop!=-1 then
					    
					    	--weld to this prop and add to weld list
					    	if SLOWMODE then
										 timer.Simple(WELDTIME*weldcount, function() self.WeldEnts ( self, v.ent, self.props[closestprop].ent, 0, 0, weldstrength, smartnocollide, weldcount) end )
							else
							    self:WeldEnts(v.ent,self.props[closestprop].ent,0, 0, weldstrength, smartnocollide, weldcount)
							end

							weldcount=weldcount+1
							table.insert(welds[a],closestprop)
							table.insert(welds[closestprop],a)
						else
							break
					    end

				    end


				end

				for a,v in ipairs(self.props) do
				    for x=1,randomwelds do

				    	--randomly pick a prop

				    	if #self.props>1 then

							local b=math.random(#self.props)

							if b!=a then

								--test if it has been welded to already
								local linked=false
								 for i,val in ipairs(welds[a]) do
								 	 if val==b then
								 	 			linked=true
								 				break
									end
								 end

		                         --if not, weld to it
								 if !linked then
								 
								       if SLOWMODE then
										 timer.Simple(WELDTIME*weldcount, function() self.WeldEnts (self, v.ent,self.props[b].ent,0, 0, weldstrength, smartnocollide,weldcount) end )
										else
										    self:WeldEnts(v.ent,self.props[closestprop].ent,0, 0, weldstrength, smartnocollide,weldcount)
										end

						    		weldcount=weldcount+1
								 	table.insert(welds[a],b)
								 	table.insert(welds[b],a)
								 end

							 end

				    	end

				    end
				end
				
			end
			
			local nocollidecount=0
			for a,v in ipairs(self.props) do
			
				for b,w in ipairs(self.props) do
					if a!=b then
						 local linked=false
						 for i,val in ipairs(welds[a]) do
						 	 if val==b then
						 	 			linked=true
						 				break
							end
						 end

						 if !linked || !smartnocollide then

					 			 local distance=(v.ent:GetPos()-w.ent:GetPos()):Length()
					             if distance<nocollideradius then
					             
					             		--nocollide the ents together
					             		
					             		if SLOWMODE then
										 timer.Simple(WELDTIME*(nocollidecount+weldcount), function() self.NoCollideEnts ( self, v.ent,w.ent,0, 0,nocollidecount ) end )
										else
										    self:NoCollideEnts(v.ent,w.ent,0, 0,nocollidecount)
										end
										nocollidecount=nocollidecount+1

					             
					             end
					    end
					end
				end
			end
			
			if refreshwelds then
				self:GetOwner():PrintMessage(HUD_PRINTCENTER,"Refreshed Smart-weld running...")
			else
				self:GetOwner():PrintMessage(HUD_PRINTCENTER,"Smart-weld running...")
			end
            

            
            if SLOWMODE then
			 timer.Simple(WELDTIME*(weldcount+nocollidecount), function() self.WeldingFinished ( self,unfreeze,weldcount, holdinguse, self.props,ply ) end )
			else
       			self:WeldingFinished(unfreeze,weldcount,holdinguse, self.props,ply)
			end
	    
	    end
	end
	
	end
	
end

function TOOL:ResetSelection()

		 local ply=self:GetOwner()
		 
		 local propscleared=false
		   --clear the selection
		   if self.props==nil then
			      self.props={}
			end
			for a,v in ipairs(self.props) do
					if !v.ent:IsValid() then
						table.remove(self.props,a)
					end
			end
			
			if #self.props>0 then
			   for a,v in ipairs(self.props) do
			       if v.ent:IsValid() then
			       	 v.ent:SetColor(v.r,v.g,v.b,v.a)
			       end
				end
				propscleared=true
				
		   end
		   
		   self.props={}
		   return propscleared

end

function TOOL:Reload( trace )

		 if !self.busy then
		 local cleared=self:ResetSelection()
		 
		 if cleared then
		 	self:GetOwner():PrintMessage(HUD_PRINTCENTER,"Selection cleared!")
		 end
		 end
         

end

function TOOL.BuildCPanel(cp)

    cp:AddControl( "Header", { Text = "#Tool.smartwelder.name", Description	= "#Tool.smartwelder.desc" }  )



    cp:AddControl( "Slider", { Label = "Auto-select Radius:", Description = "The autoselecting radius (hold use and left click to autoselect)",Type = "float", Min = "0", Max = "1000", Command = "smartwelder_radius" } )
    cp:AddControl( "Slider", { Label = "Auto-Nocollide Radius:", Description = "Each prop will nocollide with any props within its radius (set to 0 to disable auto-nocolliding)",Type = "float", Min = "0", Max = "1000", Command = "smartwelder_nocollideradius" } )
    cp:AddControl( "Slider", { Label = "Max welds per prop:", Description = "How many welds each prop will make to its nearest neighbours",Type = "integer", Min = "0", Max = "10", Command = "smartwelder_maxweldspp" } )
    cp:AddControl( "Slider", { Label = "Stability welds per prop:", Description = "How many welds each prop will make to random neighbours to increase stability",Type = "integer", Min = "0", Max = "10", Command = "smartwelder_randomwelds" } )
	cp:AddControl( "Slider", { Label = "Weld forcelimit:", Description = "The strength of the welds created. Use 0 for unbreakable welds.",Type = "float", Min = "0", Max = "10000", Command = "smartwelder_weldstrength" } )
	
	cp:AddControl( "Checkbox", { Label = "No collide:", Description = "Whether pairs of props should be nocollided when welded", Command = "smartwelder_nocollide" } )
	cp:AddControl( "Checkbox", { Label = "Auto freeze:", Description = "Whether all selected props should be frozen before the weld (Warning! Very slow!)", Command = "smartwelder_autofreeze" } )
	cp:AddControl( "Checkbox", { Label = "Auto unfreeze:", Description = "Whether all selected props should be unfrozen after the weld", Command = "smartwelder_unfreeze" } )
	cp:AddControl( "Checkbox", { Label = "Refresh welds:", Description = "Removes old welds inside the selection before smart welding", Command = "smartwelder_refreshwelds" } )


end


Output:
1
line 46: unexpected symbol near '!'


Create a new paste based on this one


Comments: