/******************************************************************************* * Copyright (c) 2012, 2013 Association for Decentralized Information Management in * Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.g3d.shape; import java.util.ArrayList; import java.util.List; import javax.vecmath.AxisAngle4d; import javax.vecmath.Vector3d; import org.simantics.g3d.math.MathTools; public class Sphere { public static Mesh create(double radius, int s, int p) { if (s < 3 || p < 3 || radius < MathTools.NEAR_ZERO) throw new IllegalArgumentException(); List vertices = new ArrayList((s-2)*p + 2); List normals = new ArrayList(vertices.size()); List indices = new ArrayList(((s-3)*p*2 + p * 2)*3); Vector3d v = new Vector3d(0.0,-radius,0.0); Vector3d vp = new Vector3d(); for (int ip = 0; ip < p; ip++) { if (ip == 0) { vertices.add(new Vector3d(0.0,-radius,0.0)); } else if (ip == p - 1) { vertices.add(new Vector3d(0.0, radius,0.0)); int off = 1 + (ip-2)*s; for (int is = 0; is < s; is++) { indices.add(vertices.size() - 1); indices.add(is+off); if (is < s -1) indices.add(is+off+1); else indices.add(off); } } else { AxisAngle4d aa = new AxisAngle4d(1, 0, 0, ((double)ip/(double)(p-1))*Math.PI); MathTools.rotate(MathTools.getQuat(aa), v, vp); for (int is = 0; is < s; is++) { aa = new AxisAngle4d(0, 1, 0, ((double)is/(double)s)*Math.PI*2); Vector3d vs = new Vector3d(); MathTools.rotate(MathTools.getQuat(aa), vp, vs); vertices.add(vs); } if (ip == 1) { for (int is = 0; is < s; is++) { indices.add(0); if (is < s -1) indices.add(is+2); else indices.add(1); indices.add(is+1); } } else { int off = 1 + (ip-1)*s; for (int is = 0; is < s-1; is++) { indices.add(off + is - s); indices.add(off + is+1); indices.add(off + is); indices.add(off + is - s); indices.add(off + is + 1 - s); indices.add(off + is + 1); } indices.add(off - 1); indices.add(off); indices.add(off + s - 1); indices.add(off -1); indices.add(off - s); indices.add(off); } } } for (int i = 0; i < vertices.size(); i++) { Vector3d n = new Vector3d(vertices.get(i)); n.normalize(); normals.add(n); } return Mesh.create(vertices,normals,indices); } public static void main(String arg[]) { Mesh s1 = create(1.0, 3, 3); Mesh s2 = create(1.0, 4, 4); System.out.println("debug " + s1 + " " + s2); } }