Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

procedurally generate a sphere mesh

Tags:

mesh

3d

i am looking for an algorithm ( in pseudo code) that generates the 3d coordinates of a sphere mesh like this:

alt text

the number of horizontal and lateral slices should be configurable

like image 461
clamp Avatar asked Nov 02 '10 20:11

clamp


People also ask

How do you make a sphere in OpenGL?

In order to draw the surface of a sphere in OpenGL, you must triangulate adjacent vertices to form polygons. It is possible to use a single triangle strip to render the whole sphere. However, if the shared vertices have different normals or texture coordinates, then a single triangle strip cannot be used.


2 Answers

If there are M lines of latitude (horizontal) and N lines of longitude (vertical), then put dots at

(x, y, z) = (sin(Pi * m/M) cos(2Pi * n/N), sin(Pi * m/M) sin(2Pi * n/N), cos(Pi * m/M))

for each m in { 0, ..., M } and n in { 0, ..., N-1 } and draw the line segments between the dots, accordingly.

edit: maybe adjust M by 1 or 2 as required, because you should decide whether or not to count "latitude lines" at the poles

like image 55
Jonathan Avatar answered Oct 04 '22 04:10

Jonathan


This is a working C# code for the above answer:

using UnityEngine;  [RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] public class ProcSphere : MonoBehaviour {      private Mesh mesh;     private Vector3[] vertices;      public int horizontalLines, verticalLines;     public int radius;      private void Awake()     {         GetComponent<MeshFilter>().mesh = mesh = new Mesh();         mesh.name = "sphere";         vertices = new Vector3[horizontalLines * verticalLines];         int index = 0;         for (int m = 0; m < horizontalLines; m++)         {             for (int n = 0; n < verticalLines - 1; n++)             {                 float x = Mathf.Sin(Mathf.PI * m/horizontalLines) * Mathf.Cos(2 * Mathf.PI * n/verticalLines);                 float y = Mathf.Sin(Mathf.PI * m/horizontalLines) * Mathf.Sin(2 * Mathf.PI * n/verticalLines);                 float z = Mathf.Cos(Mathf.PI * m / horizontalLines);                 vertices[index++] = new Vector3(x, y, z) * radius;             }         }         mesh.vertices = vertices;     }      private void OnDrawGizmos()     {         if (vertices == null) {             return;         }         for (int i = 0; i < vertices.Length; i++) {             Gizmos.color = Color.black;             Gizmos.DrawSphere(transform.TransformPoint(vertices[i]), 0.1f);         }     } } 
like image 31
yshahak Avatar answered Oct 04 '22 03:10

yshahak