Torus in OpenB3D

Post your FreeBASIC source, examples, tips and tricks here. Please don’t post code without including an explanation.
Post Reply
angros47
Posts: 2362
Joined: Jun 21, 2005 19:04

Torus in OpenB3D

Post by angros47 »

This is a simple porting of this code https://www.songho.ca/opengl/gl_torus.html

Code: Select all

#include "openb3d.bi"
screen 18,  32, , &h10002 

	
Graphics3d 640,480,32,1,1

function CreateTorus(majorRadius as single, minorRadius as single, sectorCount as integer, sideCount as integer, parent as any ptr=0) as any ptr

	const PI=3.1415926535897
	dim mesh as any ptr=CreateMesh(parent)
	dim surf as any ptr=CreateSurface(mesh)

	dim as single x, y, z, xz                              ' vertex position
	dim as single s, t                                     ' texCoord

	dim as single sectorStep = 2 * PI / sectorCount
	dim as single sideStep = 2 * PI / sideCount
	dim as single sectorAngle, sideAngle

	for i as integer = 0 to sideCount
		' start the tube side from the inside where sideAngle = pi
		sideAngle = PI + i * sideStep              ' starting from -pi to pi
		xz = minorRadius * cos(sideAngle)          ' r * cos(u)
		y = minorRadius * sin(sideAngle)           ' r * sin(u)

		' add (sectorCount+1) vertices per side
		' the first and last vertices have same position and normal,
		' but different tex coords
		for j as integer = 0 to sectorCount
			sectorAngle = j * sectorStep           ' starting from 0 to 2pi

			' tmp x and y to compute normal vector
			x = xz * cos(sectorAngle)
			z = xz * sin(sectorAngle)

			' shift x & z, and vertex position
			x += majorRadius * cos(sectorAngle)   ' (R + r * cos(u)) * cos(v)
			z += majorRadius * sin(sectorAngle)   ' (R + r * cos(u)) * sin(v)

			' vertex tex coord between [0, 1]
			s = cast(single, j) / sectorCount
			t = cast(single, i) / sideCount
			AddVertex (surf, x, y, z, s, t)
		next
	next

	dim as unsigned integer k1, k2
	for i as integer = 0 to sideCount-1
		k1 = i * (sectorCount + 1)     ' beginning of current side
		k2 = k1 + sectorCount + 1      ' beginning of next side

		for j as integer = 1 to sectorCount
			' 2 triangles per sector
			AddTriangle(surf, k1, k2, k1+1)
			AddTriangle(surf, k1+1, k2, k2+1)
			k1+=1: k2+=1
		next
	next
	UpdateNormals(mesh)
	return mesh
end function
It doesn't include the part that creates the normals because OpenB3D can calculate them on its own. It is possible to set the diameters, and the number of segments. The torus obtained can be processed further with MeshCSG to create more complex geometry.
Post Reply