]> git.tdb.fi Git - libs/gl.git/blob - source/capsule.cpp
9ea19326c7075cde8468097f3c6cdfd942a0e116
[libs/gl.git] / source / capsule.cpp
1 /* $Id$
2
3 This file is part of libmspgl
4 Copyright © 2011  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <cmath>
9 #include "capsule.h"
10 #include "primitivebuilder.h"
11
12 using namespace std;
13
14 namespace Msp {
15 namespace GL {
16
17 CapsuleBuilder::CapsuleBuilder(float r, float l, unsigned s, unsigned n):
18         radius(r),
19         length(l),
20         segments(s),
21         rings(n)
22 {
23         if(segments<3)
24                 segments = 3;
25         rings |= 1;
26         if(rings<3)
27                 rings = 3;
28 }
29
30 void CapsuleBuilder::build(PrimitiveBuilder &builder) const
31 {
32         float u_scale = 1.0/segments;
33         float v_scale = 1/(length+radius*M_PI);
34         adjust_texture_scale(u_scale, v_scale, radius*M_PI*2, length+radius*M_PI);
35
36         builder.normal(0, 0, -1);
37         builder.texcoord(0.5, 0);
38         builder.vertex(0, 0, -length/2-radius);
39         for(unsigned i=1; i<rings; ++i)
40         {
41                 float cz = length*(i>rings/2 ? 0.5 : -0.5);
42                 float v = ((i>rings/2 ? i-1 : i)*radius*M_PI/(rings-1)+(i>rings/2 ? length : 0))*v_scale;
43                 float ra = (i>rings/2 ? i-1 : i)*M_PI/(rings-1);
44                 float rc = cos(ra);
45                 float rs = sin(ra);
46                 for(unsigned j=0; j<=segments; ++j)
47                 {
48                         float sa = j*M_PI*2/segments;
49                         float sc = cos(sa);
50                         float ss = sin(sa);
51                         builder.normal(rs*sc, rs*ss, -rc);
52                         if(tangent_attr>=0)
53                                 builder.attrib(tangent_attr, -ss, sc, 0);
54                         if(binormal_attr>=0)
55                                 builder.attrib(binormal_attr, rc*sc, rc*ss, rs);
56                         builder.texcoord(j*u_scale, v);
57                         builder.vertex(rs*sc*radius, rs*ss*radius, cz-rc*radius);
58                 }
59         }
60         builder.normal(0, 0, 1);
61         builder.texcoord(0.5, (length+radius*M_PI)*v_scale);
62         builder.vertex(0, 0, length/2+radius);
63
64         for(unsigned i=0; i<segments; ++i)
65         {
66                 builder.begin(GL::TRIANGLE_STRIP);
67                 builder.element(0);
68                 for(unsigned j=0; j+1<rings; ++j)
69                 {
70                         builder.element(1+j*(segments+1)+i+1);
71                         builder.element(1+j*(segments+1)+i);
72                 }
73                 builder.element((segments+1)*(rings-1)+1);
74                 builder.end();
75         }
76 }
77
78 } // namespace GL
79 } // namespace Msp