More moronic bugs
[ipdf/code.git] / src / objectrenderer.cpp
1 /**
2  * @file objectrenderer.cpp
3  * @brief Implements ObjectRenderer and derived classes
4  */
5
6 #include "objectrenderer.h"
7 #include "view.h"
8
9 using namespace std;
10
11 namespace IPDF
12 {
13
14 /**
15  * ObjectRenderer constructor
16  * Note we cannot compile the shaders in the ShaderProgram constructor
17  *  because the Screen class needs to initialise GL first and it has a
18  *      ShaderProgram member
19  */
20 ObjectRenderer::ObjectRenderer(const ObjectType & type, 
21                 const char * vert_glsl_file, const char * frag_glsl_file, const char * geom_glsl_file)
22                 : m_type(type), m_shader_program(), m_indexes(), m_buffer_builder(NULL)
23 {
24         m_shader_program.InitialiseShaders(vert_glsl_file, frag_glsl_file, geom_glsl_file);
25         m_shader_program.Use();
26         glUniform4f(m_shader_program.GetUniformLocation("colour"), 0,0,0,1); //TODO: Allow different colours
27 }
28
29 /**
30  * Render using GPU
31  */
32 void ObjectRenderer::RenderUsingGPU()
33 {
34         if (!m_shader_program.Valid())
35                 Warn("Shader is invalid (objects are of type %d)", m_type);
36         m_shader_program.Use();
37         m_ibo.Bind();
38         glDrawElements(GL_LINES, m_indexes.size()*2, GL_UNSIGNED_INT, 0);
39 }
40
41
42 /**
43  * Default implementation for rendering using CPU
44  */
45 void ObjectRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target)
46 {
47         Error("Cannot render objects of type %d on CPU", m_type);
48         //TODO: Render a rect or something instead?
49 }
50
51 /**
52  * Prepare index buffers for both CPU and GPU rendering to receive indexes (but don't add any yet!)
53  */
54 void ObjectRenderer::PrepareBuffers(unsigned max_objects)
55 {
56         if (m_buffer_builder != NULL) // We already have a BufferBuilder
57         {
58                 Fatal("Has been called before, without FinaliseBuffers being called since!");
59         }
60         // Empty and reserve the indexes vector (for CPU rendering)
61         m_indexes.clear();
62         m_indexes.reserve(max_objects); //TODO: Can probably make this smaller? Or leave it out? Do we care?
63
64         // Initialise and resize the ibo (for GPU rendering)
65         m_ibo.Invalidate();
66         m_ibo.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
67         m_ibo.SetType(GraphicsBuffer::BufferTypeIndex);
68         m_ibo.Resize(max_objects * 2 * sizeof(uint32_t));
69         // BufferBuilder is used to construct the ibo
70         m_buffer_builder = new BufferBuilder<uint32_t>(m_ibo.Map(false, true, true), m_ibo.GetSize()); // new matches delete in ObjectRenderer::FinaliseBuffers
71
72 }
73
74 /**
75  * Add object index to the buffers for CPU and GPU rendering
76  */
77 void ObjectRenderer::AddObjectToBuffers(unsigned index)
78 {
79         if (m_buffer_builder == NULL) // No BufferBuilder!
80         {
81                 Fatal("Called without calling PrepareBuffers");
82         }
83         m_buffer_builder->Add(2*index); // ibo for GPU rendering
84         m_buffer_builder->Add(2*index+1);
85         m_indexes.push_back(index); // std::vector of indices for CPU rendering
86 }
87
88 /**
89  * Finalise the index buffers for CPU and GPU rendering
90  */
91 void ObjectRenderer::FinaliseBuffers()
92 {
93         if (m_buffer_builder == NULL) // No BufferBuilder!
94         {
95                 Fatal("Called without calling PrepareBuffers");
96         }
97         // For GPU rendering, UnMap the ibo
98         m_ibo.UnMap();
99         // ... and delete the BufferBuilder used to create it
100         delete m_buffer_builder; // delete matches new in ObjectRenderer::PrepareBuffers
101         m_buffer_builder = NULL;
102         
103         // Nothing is necessary for CPU rendering
104 }
105
106
107 /**
108  * Rectangle (filled)
109  */
110 void RectFilledRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target)
111 {
112         for (unsigned i = 0; i < m_indexes.size(); ++i)
113         {
114                 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
115                 for (int64_t x = max(0L, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
116                 {
117                         for (int64_t y = max(0L, bounds.y); y <= min(bounds.y+bounds.h, target.h-1); ++y)
118                         {
119                                 int index = (x+target.w*y)*4;
120                                 target.pixels[index+0] = 0;
121                                 target.pixels[index+1] = 0;
122                                 target.pixels[index+2] = 0;
123                                 target.pixels[index+3] = 255;
124                         }
125                 }
126         }
127 }
128
129 /**
130  * Rectangle (outine)
131  */
132 void RectOutlineRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target)
133 {
134         //Debug("Render %u outlined rectangles on CPU", m_indexes.size());
135         for (unsigned i = 0; i < m_indexes.size(); ++i)
136         {
137                 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
138                 
139                 // Using bresenham's lines now mainly because I want to see if they work
140                 // top
141                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x+bounds.w, bounds.y, target);
142                 // bottom
143                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y+bounds.h, bounds.x+bounds.w, bounds.y+bounds.h, target);
144                 // left
145                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x, bounds.y+bounds.h, target);
146                 // right
147                 ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y, bounds.x+bounds.w, bounds.y+bounds.h, target);
148
149                 // Diagonal for testing (from bottom left to top right)
150                 //ObjectRenderer::RenderLineOnCPU(bounds.x,bounds.y+bounds.h, bounds.x+bounds.w, bounds.y,target, C_BLUE);
151                 //ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y+bounds.h, bounds.x, bounds.y, target,C_GREEN);
152         }
153 }
154
155 /**
156  * Circle (filled)
157  */
158 void CircleFilledRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target)
159 {
160         for (unsigned i = 0; i < m_indexes.size(); ++i)
161         {
162                 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
163                 int64_t centre_x = bounds.x + bounds.w / 2;
164                 int64_t centre_y = bounds.y + bounds.h / 2;
165                 
166                 //Debug("Centre is %d, %d", centre_x, centre_y);
167                 //Debug("Bounds are %d,%d,%d,%d", bounds.x, bounds.y, bounds.w, bounds.h);
168                 //Debug("Windos is %d,%d", target.w, target.h);
169                 for (int64_t x = max(0L, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
170                 {
171                         for (int64_t y = max(0L, bounds.y); y <= min(bounds.y + bounds.h, target.h-1); ++y)
172                         {
173                                 double dx = 2.0*(double)(x - centre_x)/(double)(bounds.w);
174                                 double dy = 2.0*(double)(y - centre_y)/(double)(bounds.h);
175                                 int64_t index = (x+target.w*y)*4;
176                                 
177                                 if (dx*dx + dy*dy <= 1.0)
178                                 {
179                                         target.pixels[index+0] = 0;
180                                         target.pixels[index+1] = 0;
181                                         target.pixels[index+2] = 0;
182                                         target.pixels[index+3] = 255;
183
184                                 }
185                         }
186                 }
187         }
188 }
189
190 Rect ObjectRenderer::CPURenderBounds(const Rect & bounds, const View & view, const CPURenderTarget & target)
191 {
192         Rect result = view.TransformToViewCoords(bounds);
193         result.x *= Real(target.w);
194         result.y *= Real(target.h);
195         result.w *= Real(target.w);
196         result.h *= Real(target.h);
197         return result;
198 }
199         
200
201 /**
202  * Bezier curve
203  * Not sure how to apply De'Casteljau, will just use a bunch of Bresnham lines for now.
204  */
205 void BezierRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target)
206 {
207         //Warn("Rendering Beziers on CPU. Things may explode.");
208         for (unsigned i = 0; i < m_indexes.size(); ++i)
209         {
210                 Rect bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
211                 PixelBounds pix_bounds(bounds);
212
213
214                 Bezier control(objects.beziers[objects.data_indices[m_indexes[i]]], bounds);
215                 //Debug("%s -> %s via %s", objects.beziers[objects.data_indices[m_indexes[i]]].Str().c_str(), control.Str().c_str(), bounds.Str().c_str());
216                 // Draw a rectangle around the bezier for debugging the coord transforms
217                 //ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x+pix_bounds.w, pix_bounds.y, target);
218                 //ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y+pix_bounds.h, pix_bounds.x+pix_bounds.w, pix_bounds.y+pix_bounds.h, target);
219                 //ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x, pix_bounds.y+pix_bounds.h, target);
220                 //ObjectRenderer::RenderLineOnCPU(pix_bounds.x+pix_bounds.w, pix_bounds.y, pix_bounds.x+pix_bounds.w, pix_bounds.y+pix_bounds.h, target);
221         
222                 // Draw lines between the control points for debugging
223                 //ObjectRenderer::RenderLineOnCPU((int64_t)control.x0, (int64_t)control.y0, (int64_t)control.x1, (int64_t)control.y1,target);
224                 //ObjectRenderer::RenderLineOnCPU((int64_t)control.x1, (int64_t)control.y1, (int64_t)control.x2, (int64_t)control.y2,target);
225                                                                                 
226
227                 
228                 Real x[2]; Real y[2];
229                 control.Evaluate(x[0], y[0], Real(0));
230                 int64_t blen = max(2L, min(100L, pix_bounds.w));
231                 Real invblen(1); invblen /= blen;
232                 Debug("Using %li lines, inverse %f", blen, Double(invblen));
233                 for (int64_t j = 1; j <= blen; ++j)
234                 {
235                         control.Evaluate(x[j % 2],y[j % 2], invblen*j);
236                         ObjectRenderer::RenderLineOnCPU((int64_t)Double(x[0]),(int64_t)Double(y[0]), (int64_t)Double(x[1]),(int64_t)Double(y[1]), target);
237                 }
238                 
239                 /*
240                 Real u(0);
241                 while (u < Real(1))
242                 {
243                         u += Real(1e-6);
244                         Real x; Real y; control.Evaluate(x,y,u);
245                         int64_t index = ((int64_t)x + (int64_t)y*target.w)*4;
246                         if (index >= 0 && index < 4*(target.w*target.h))
247                         {
248                                 target.pixels[index+0] = 0;
249                                 target.pixels[index+1] = 0;
250                                 target.pixels[index+2] = 0;
251                                 target.pixels[index+3] = 255;
252                         }       
253                 }
254                 */
255                 
256         }
257 }
258
259 void BezierRenderer::PrepareBezierGPUBuffer(const Objects& objects)
260 {
261         m_bezier_coeffs.SetType(GraphicsBuffer::BufferTypeTexture);
262         m_bezier_coeffs.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
263         m_bezier_coeffs.Resize(objects.beziers.size()*sizeof(GPUBezierCoeffs));
264         BufferBuilder<GPUBezierCoeffs> builder(m_bezier_coeffs.Map(false, true, true), m_bezier_coeffs.GetSize());
265
266         for (auto bez : objects.beziers)
267         {
268                 GPUBezierCoeffs coeffs = {
269                         Float(bez.x0), Float(bez.y0),
270                         Float(bez.x1 - bez.x0), Float(bez.y1 - bez.y0),
271                         Float(bez.x2 - bez.x0), Float(bez.y2 - bez.y0)
272                         };
273                 builder.Add(coeffs);
274         }
275         m_bezier_coeffs.UnMap();
276         glGenTextures(1, &m_bezier_buffer_texture);
277         glBindTexture(GL_TEXTURE_BUFFER, m_bezier_buffer_texture);
278         glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32F, m_bezier_coeffs.GetHandle());
279
280         m_bezier_ids.SetType(GraphicsBuffer::BufferTypeTexture);
281         m_bezier_ids.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
282         m_bezier_ids.Upload(objects.data_indices.size() * sizeof(uint32_t), &objects.data_indices[0]);
283         
284         glGenTextures(1, &m_bezier_id_buffer_texture);
285         glActiveTexture(GL_TEXTURE1);
286         glBindTexture(GL_TEXTURE_BUFFER, m_bezier_id_buffer_texture);
287         glTexBuffer(GL_TEXTURE_BUFFER, GL_R32I, m_bezier_ids.GetHandle());
288         glActiveTexture(GL_TEXTURE0);
289 }
290
291 void BezierRenderer::RenderUsingGPU()
292 {
293         if (!m_shader_program.Valid())
294                 Warn("Shader is invalid (objects are of type %d)", m_type);
295         m_shader_program.Use();
296         glUniform1i(m_shader_program.GetUniformLocation("bezier_buffer_texture"), 0);
297         glUniform1i(m_shader_program.GetUniformLocation("bezier_id_buffer_texture"), 1);
298         m_ibo.Bind();
299         glDrawElements(GL_LINES, m_indexes.size()*2, GL_UNSIGNED_INT, 0);
300 }
301
302 /**
303  * For debug, save pixels to bitmap
304  */
305 void ObjectRenderer::SaveBMP(const CPURenderTarget & target, const char * filename)
306 {
307         SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(target.pixels, target.w, target.h, 8*4, target.w*4,
308         #if SDL_BYTEORDER == SDL_LIL_ENDIAN
309                 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000
310         #else
311                 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff
312         #endif //SDL_BYTEORDER  
313         );      
314         if (surf == NULL)
315                 Fatal("SDL_CreateRGBSurfaceFrom(pixels...) failed - %s", SDL_GetError());
316         if (SDL_SaveBMP(surf, filename) != 0)
317                 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
318
319         // Cleanup
320         SDL_FreeSurface(surf);
321 }
322
323 /**
324  * Bresenham's lines
325  */
326 void ObjectRenderer::RenderLineOnCPU(int64_t x0, int64_t y0, int64_t x1, int64_t y1, const CPURenderTarget & target, const Colour & colour, bool transpose)
327 {
328         int64_t dx = x1 - x0;
329         int64_t dy = y1 - y0;
330         bool neg_m = (dy*dx < 0);
331         dy = abs(dy);
332         dx = abs(dx);
333
334         // If positive slope > 1, just swap x and y
335         if (dy > dx)
336         {
337                 RenderLineOnCPU(y0,x0,y1,x1,target,colour,!transpose);
338                 return;
339         }
340
341         int64_t two_dy = 2*dy;
342         int64_t p = two_dy - dx;
343         int64_t two_dxdy = 2*(dy-dx);
344         int64_t x; int64_t y; int64_t x_end;
345         int64_t width = (transpose ? target.h : target.w);
346         int64_t height = (transpose ? target.w : target.h);
347
348         uint8_t rgba[4];
349         rgba[0] = 255*colour.r;
350         rgba[1] = 255*colour.g;
351         rgba[2] = 255*colour.b;
352         rgba[3] = 255*colour.a;
353
354         if (x0 > x1)
355         {
356                 x = x1;
357                 y = y1;
358                 x_end = x0;
359         }
360         else
361         {
362                 x = x0;
363                 y = y0;
364                 x_end = x1;
365         }
366
367         if (x < 0)
368         {
369                 if (x_end < 0) return;
370                 y = (neg_m ? y - (dy*-x)/dx : y + (dy*-x)/dx);
371                 x = 0;
372         }
373         
374         if (x_end > width)
375         {
376                 if (x > width) return;
377                 x_end = width-1;
378         }
379
380         // TODO: Avoid extra inner conditionals
381         do
382         {
383                 if (x >= 0 && x < width && y >= 0 && y < height)
384                 {
385                         int64_t index = (transpose ? (y + x*target.w)*4 : (x + y*target.w)*4);
386                         for (int i = 0; i < 4; ++i)
387                                 target.pixels[index+i] = rgba[i];
388                 }
389                 
390                 if (p < 0)
391                         p += two_dy;
392                 else
393                 {
394                         if (neg_m) --y; else ++y;
395                         p += two_dxdy;
396                 }
397         } while (++x < x_end);
398 }
399
400 }

UCC git Repository :: git.ucc.asn.au