forked from xeolabs/scenejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sphere.js
82 lines (69 loc) · 2.89 KB
/
sphere.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
SceneJS.Plugins.addPlugin(
"geometry", // Node type
"sphere",
new (function() {
this.getSource = function () {
var publish;
return {
subscribe:function (fn) {
publish = fn;
},
configure:function (cfg) {
publish(build(cfg));
}
};
};
function build(cfg) {
// Thanks awfully to: http://learningwebgl.com/cookbook/index.php/How_to_draw_a_sphere
var latitudeBands = cfg.latitudeBands || 30;
var longitudeBands = cfg.longitudeBands || 30;
var radius = cfg.radius || 2;
var positions = [];
var normals = [];
var uvs = [];
for (var latNumber = 0; latNumber <= latitudeBands; latNumber++) {
var theta = latNumber * Math.PI / latitudeBands;
var sinTheta = Math.sin(theta);
var cosTheta = Math.cos(theta);
for (var longNumber = 0; longNumber <= longitudeBands; longNumber++) {
var phi = longNumber * 2 * Math.PI / longitudeBands;
var sinPhi = Math.sin(phi);
var cosPhi = Math.cos(phi);
var x = cosPhi * sinTheta;
var y = cosTheta;
var z = sinPhi * sinTheta;
var u = 1- (longNumber / longitudeBands);
var v = latNumber / latitudeBands;
normals.push(x);
normals.push(y);
normals.push(z);
uvs.push(u);
uvs.push(v);
positions.push(radius * x);
positions.push(radius * y);
positions.push(radius * z);
}
}
var indices = [];
for (var latNumber = 0; latNumber < latitudeBands; latNumber++) {
for (var longNumber = 0; longNumber < longitudeBands; longNumber++) {
var first = (latNumber * (longitudeBands + 1)) + longNumber;
var second = first + longitudeBands + 1;
indices.push(first);
indices.push(second);
indices.push(first + 1);
indices.push(second);
indices.push(second + 1);
indices.push(first + 1);
}
}
return {
primitive:cfg.wire ? "lines" : "triangles",
coreId : "sphere_" + (cfg.wire ? "wire" : "_solid") + radius + "_" + longitudeBands + "_" + latitudeBands,
positions : new Float32Array(positions),
normals: new Float32Array(normals),
uv : new Float32Array(uvs),
indices : new Uint16Array(indices)
};
}
})());