[bb] CreateCubeSphere() function by Flanker [ 6 months ago ]

Started by BlitzBot, June 29, 2017, 00:28:43

Previous topic - Next topic

BlitzBot

Title : CreateCubeSphere() function
Author : Flanker
Posted : 6 months ago

Description : Just a function to create a "cubesphere" mesh, with proper UVs for a cubemap set of textures. It has 6 surfaces, one for each cube face :



You can set a number of subdivisions, from 1 to 180, and choose beetween 2 geometry modes. Mode 0 is just a normalisation while Mode 1 (default) limits the deformation near edges :



I put it here before it gets lost in the depth of my hard drive...


Code :
Code: blitzbasic
Function CreateCubeSphere(segments#=16,mode=1)
	
	mesh = CreateMesh()
	
	For s = 1 To 6
		
		surf = CreateSurface(mesh)
		
		For y = 0 To segments
			For x = 0 To segments
				
				Select s
					Case 1
						vx# = x-segments/2 : vy# = segments/2 : vz# = segments/2-y
					Case 2
						vx = x-segments/2 : vy = segments/2-y : vz = -segments/2
					Case 3
						vx = x-segments/2 : vy = -segments/2 : vz = y-segments/2
					Case 4
						vx = -segments/2 : vy = segments/2-y : vz = segments/2-x
					Case 5
						vx = segments/2 : vy = segments/2-y : vz = x-segments/2
					Case 6
						vx = segments/2-x : vy = segments/2-y : vz = segments/2
				End Select
				
				If mode = 0
					magnitude# = Sqr( vx*vx + vy*vy + vz*vz )
					vertX# = vx/magnitude : vertY# = vy/magnitude : vertZ# = vz/magnitude
				Else
					vx = vx/segments*2 : vy = vy/segments*2 : vz = vz/segments*2
					vertX = vx * Sqr( 1.0 - (vy*vy)/2 - (vz*vz)/2 + ((vy*vy)*(vz*vz)/3) )
					vertY = vy * Sqr( 1.0 - (vz*vz)/2 - (vx*vx)/2 + ((vz*vz)*(vx*vx)/3) )
					vertZ = vz * Sqr( 1.0 - (vx*vx)/2 - (vy*vy)/2 + ((vx*vx)*(vy*vy)/3) )
				EndIf
				
				vertex = AddVertex(surf,vertX,vertY,vertZ,x/segments,y/segments)
				VertexNormal(surf,vertex,vertX,vertY,vertZ)
				
			Next
		Next
		
		For y = 0 To segments-1
			For x = 0 To segments-1
				AddTriangle(surf,y*(segments+1)+x,y*(segments+1)+x+1,y*(segments+1)+x+segments+2)
				AddTriangle(surf,y*(segments+1)+x,y*(segments+1)+x+segments+2,y*(segments+1)+x+segments+1)
			Next
		Next
		
	Next
	
	Return mesh
	
End Function


Comments :


Rick Nasher(Posted 6 months ago)

 Very cool!


BlitzSupport(Posted 6 months ago)

 This is awesome, thanks for posting it!


Krischan(Posted 6 months ago)

 Very, very nice and much shorter than <a href="codearcs836a.html?code=2539" target="_blank">my current solution</a>. As this kind of cube/sphere is the best solution to create planets check out my <a href="codearcs6dbf.html?code=3193" target="_blank">Cubemap to Spheremap conversion</a> if you don't know it already.


Flanker(Posted 6 months ago)

 @KrischanI knew there were already "cubesphere" codes in the code archives, but I didn't see that yours already included the same formula to limit the deformations.