]> git.tdb.fi Git - libs/gl.git/blob - source/builders/capsule.cpp
Use a placeholder texture when a texture has not been loaded yet
[libs/gl.git] / source / builders / capsule.cpp
1 #define _USE_MATH_DEFINES
2 #include <cmath>
3 #include "capsule.h"
4 #include "primitivebuilder.h"
5
6 using namespace std;
7
8 namespace Msp {
9 namespace GL {
10
11 CapsuleBuilder::CapsuleBuilder(float r, float l, unsigned s, unsigned n):
12         radius(r),
13         length(l),
14         segments(s),
15         rings(n)
16 {
17         if(segments<3)
18                 segments = 3;
19         rings |= 1;
20         if(rings<3)
21                 rings = 3;
22 }
23
24 void CapsuleBuilder::build(PrimitiveBuilder &builder) const
25 {
26         float u_scale = 1.0/segments;
27         float v_scale = 1/(length+radius*M_PI);
28         adjust_texture_scale(u_scale, v_scale, radius*M_PI*2, length+radius*M_PI);
29
30         builder.normal(0, 0, -1);
31         builder.texcoord(0.5, 0);
32         builder.vertex(0, 0, -length/2-radius);
33         for(unsigned i=1; i<rings; ++i)
34         {
35                 float cz = length*(i>rings/2 ? 0.5 : -0.5);
36                 float v = ((i>rings/2 ? i-1 : i)*radius*M_PI/(rings-1)+(i>rings/2 ? length : 0))*v_scale;
37                 float ra = (i>rings/2 ? i-1 : i)*M_PI/(rings-1);
38                 float rc = cos(ra);
39                 float rs = sin(ra);
40                 for(unsigned j=0; j<=segments; ++j)
41                 {
42                         float sa = j*M_PI*2/segments;
43                         float sc = cos(sa);
44                         float ss = sin(sa);
45                         builder.normal(rs*sc, rs*ss, -rc);
46                         if(generate_tan)
47                                 builder.tangent(-ss, sc, 0);
48                         builder.texcoord(j*u_scale, v);
49                         builder.vertex(rs*sc*radius, rs*ss*radius, cz-rc*radius);
50                 }
51         }
52         builder.normal(0, 0, 1);
53         builder.texcoord(0.5, (length+radius*M_PI)*v_scale);
54         builder.vertex(0, 0, length/2+radius);
55
56         for(unsigned i=0; i<segments; ++i)
57         {
58                 builder.begin(TRIANGLE_STRIP);
59                 builder.element(0);
60                 for(unsigned j=0; j+1<rings; ++j)
61                 {
62                         builder.element(1+j*(segments+1)+i+1);
63                         builder.element(1+j*(segments+1)+i);
64                 }
65                 builder.element((segments+1)*(rings-1)+1);
66                 builder.end();
67         }
68 }
69
70 } // namespace GL
71 } // namespace Msp