Sphere.hx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package h3d.prim;
  2. import h3d.col.Point;
  3. class Sphere extends Polygon {
  4. var ray : Float;
  5. var segsH : Int;
  6. var segsW : Int;
  7. // Use 1 for a full sphere, 0.5 for a half sphere
  8. var portion : Float;
  9. public function new( ray = 1., segsW = 8, segsH = 6, portion = 1. ) {
  10. this.ray = ray;
  11. this.segsH = segsH;
  12. this.segsW = segsW;
  13. this.portion = portion;
  14. var dp = Math.PI * 2 / segsW;
  15. var pts = [], idx = new hxd.IndexBuffer();
  16. for( y in 0...segsH+1 ) {
  17. var t = (y / segsH) * Math.PI * portion;
  18. var st = Math.sin(t);
  19. var pz = Math.cos(t);
  20. var p = 0.;
  21. for( x in 0...segsW+1 ) {
  22. var px = st * Math.cos(p);
  23. var py = st * Math.sin(p);
  24. pts.push(new Point(px * ray, py * ray, pz * ray));
  25. p += dp;
  26. }
  27. }
  28. for( y in 0...segsH ) {
  29. for( x in 0...segsW ) {
  30. inline function vertice(x, y) return x + y * (segsW + 1);
  31. var v1 = vertice(x + 1, y);
  32. var v2 = vertice(x, y);
  33. var v3 = vertice(x, y + 1);
  34. var v4 = vertice(x + 1, y + 1);
  35. if( y != 0 ) {
  36. idx.push(v1);
  37. idx.push(v2);
  38. idx.push(v4);
  39. }
  40. if( y != segsH - 1 || portion != 1. ) {
  41. idx.push(v2);
  42. idx.push(v3);
  43. idx.push(v4);
  44. }
  45. }
  46. }
  47. super(pts, idx);
  48. }
  49. override public function getCollider() : h3d.col.Collider {
  50. return new h3d.col.Sphere(translatedX, translatedY, translatedZ, ray * scaled);
  51. }
  52. override function addNormals() {
  53. normals = points;
  54. }
  55. override function addUVs() {
  56. uvs = [];
  57. for( y in 0...segsH + 1 )
  58. for( x in 0...segsW + 1 )
  59. uvs.push(new UV(1 - x / segsW, y / segsH));
  60. }
  61. public static function defaultUnitSphere() {
  62. var engine = h3d.Engine.getCurrent();
  63. var s : Sphere = @:privateAccess engine.resCache.get(Sphere);
  64. if( s != null )
  65. return s;
  66. s = new h3d.prim.Sphere(1, 16, 16);
  67. s.addNormals();
  68. s.addUVs();
  69. @:privateAccess engine.resCache.set(Sphere, s);
  70. return s;
  71. }
  72. }