Careful, you may have to shade your eyes
[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 #include <vector>
9 #include <queue>
10
11 using namespace std;
12
13 namespace IPDF
14 {
15
16 /**
17  * ObjectRenderer constructor
18  * Note we cannot compile the shaders in the ShaderProgram constructor
19  *  because the Screen class needs to initialise GL first and it has a
20  *      ShaderProgram member
21  */
22 ObjectRenderer::ObjectRenderer(const ObjectType & type, 
23                 const char * vert_glsl_file, const char * frag_glsl_file, const char * geom_glsl_file)
24                 : m_type(type), m_shader_program(), m_indexes(), m_buffer_builder(NULL)
25 {
26         m_shader_program.InitialiseShaders(vert_glsl_file, frag_glsl_file, geom_glsl_file);
27         m_shader_program.Use();
28         glUniform4f(m_shader_program.GetUniformLocation("colour"), 0,0,0,1); //TODO: Allow different colours
29 }
30
31 /**
32  * Render using GPU
33  */
34 void ObjectRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
35 {
36         // If we don't have anything to render, return.
37         if (first_obj_id == last_obj_id) return;
38         // If there are no objects of this type, return.
39         if (m_indexes.empty()) return;
40         unsigned first_index = 0;
41         while (m_indexes.size() > first_index && m_indexes[first_index] < first_obj_id) first_index ++;
42         unsigned last_index = first_index;
43         while (m_indexes.size() > last_index && m_indexes[last_index] < last_obj_id) last_index ++;
44
45         m_shader_program.Use();
46         m_ibo.Bind();
47         glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(2*first_index*sizeof(uint32_t)));
48 }
49
50
51 /**
52  * Default implementation for rendering using CPU
53  */
54 void ObjectRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
55 {
56         Error("Cannot render objects of type %d on CPU", m_type);
57         //TODO: Render a rect or something instead?
58 }
59
60 /**
61  * Prepare index buffers for both CPU and GPU rendering to receive indexes (but don't add any yet!)
62  */
63 void ObjectRenderer::PrepareBuffers(unsigned max_objects)
64 {
65         if (m_buffer_builder != NULL) // We already have a BufferBuilder
66         {
67                 Fatal("Has been called before, without FinaliseBuffers being called since!");
68         }
69         // Empty and reserve the indexes vector (for CPU rendering)
70         m_indexes.clear();
71         m_indexes.reserve(max_objects); //TODO: Can probably make this smaller? Or leave it out? Do we care?
72
73         // Initialise and resize the ibo (for GPU rendering)
74         m_ibo.Invalidate();
75         m_ibo.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
76         m_ibo.SetType(GraphicsBuffer::BufferTypeIndex);
77         m_ibo.Resize(max_objects * 2 * sizeof(uint32_t));
78         // BufferBuilder is used to construct the ibo
79         m_buffer_builder = new BufferBuilder<uint32_t>(m_ibo.Map(false, true, true), m_ibo.GetSize()); // new matches delete in ObjectRenderer::FinaliseBuffers
80
81 }
82
83 /**
84  * Add object index to the buffers for CPU and GPU rendering
85  */
86 void ObjectRenderer::AddObjectToBuffers(unsigned index)
87 {
88         if (m_buffer_builder == NULL) // No BufferBuilder!
89         {
90                 Fatal("Called without calling PrepareBuffers");
91         }
92         m_buffer_builder->Add(2*index); // ibo for GPU rendering
93         m_buffer_builder->Add(2*index+1);
94         m_indexes.push_back(index); // std::vector of indices for CPU rendering
95 }
96
97 /**
98  * Finalise the index buffers for CPU and GPU rendering
99  */
100 void ObjectRenderer::FinaliseBuffers()
101 {
102         if (m_buffer_builder == NULL) // No BufferBuilder!
103         {
104                 Fatal("Called without calling PrepareBuffers");
105         }
106         // For GPU rendering, UnMap the ibo
107         m_ibo.UnMap();
108         // ... and delete the BufferBuilder used to create it
109         delete m_buffer_builder; // delete matches new in ObjectRenderer::PrepareBuffers
110         m_buffer_builder = NULL;
111         
112         // Nothing is necessary for CPU rendering
113 }
114
115
116 /**
117  * Rectangle (filled)
118  */
119 void RectFilledRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
120 {
121         for (unsigned i = 0; i < m_indexes.size(); ++i)
122         {
123                 if (m_indexes[i] < first_obj_id) continue;
124                 if (m_indexes[i] >= last_obj_id) continue;
125                 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
126                 FloodFillOnCPU(bounds.x+1, bounds.y+1, bounds, target, Colour(0,0,0,1));
127                 /*
128                 for (int64_t x = max((int64_t)0, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
129                 {
130                         for (int64_t y = max((int64_t)0, bounds.y); y <= min(bounds.y+bounds.h, target.h-1); ++y)
131                         {
132                                 int index = (x+target.w*y)*4;
133                                 target.pixels[index+0] = 0;
134                                 target.pixels[index+1] = 0;
135                                 target.pixels[index+2] = 0;
136                                 target.pixels[index+3] = 255;
137                         }
138                 }
139                 */
140         }
141 }
142
143 /**
144  * Rectangle (outine)
145  */
146 void RectOutlineRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
147 {
148         //Debug("Render %u outlined rectangles on CPU", m_indexes.size());
149         for (unsigned i = 0; i < m_indexes.size(); ++i)
150         {
151                 if (m_indexes[i] < first_obj_id) continue;
152                 if (m_indexes[i] >= last_obj_id) continue;
153                 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
154                 
155                 // Using bresenham's lines now mainly because I want to see if they work
156                 // top
157                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x+bounds.w, bounds.y, target);
158                 // bottom
159                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y+bounds.h, bounds.x+bounds.w, bounds.y+bounds.h, target);
160                 // left
161                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x, bounds.y+bounds.h, target);
162                 // right
163                 ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y, bounds.x+bounds.w, bounds.y+bounds.h, target);
164
165                 // Diagonal for testing (from bottom left to top right)
166                 //ObjectRenderer::RenderLineOnCPU(bounds.x,bounds.y+bounds.h, bounds.x+bounds.w, bounds.y,target, C_BLUE);
167                 //ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y+bounds.h, bounds.x, bounds.y, target,C_GREEN);
168         }
169 }
170
171 /**
172  * Circle (filled)
173  */
174 void CircleFilledRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
175 {
176         for (unsigned i = 0; i < m_indexes.size(); ++i)
177         {
178                 if (m_indexes[i] < first_obj_id) continue;
179                 if (m_indexes[i] >= last_obj_id) continue;
180                 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
181                 int64_t centre_x = bounds.x + bounds.w / 2;
182                 int64_t centre_y = bounds.y + bounds.h / 2;
183                 
184                 //Debug("Centre is %d, %d", centre_x, centre_y);
185                 //Debug("Bounds are %d,%d,%d,%d", bounds.x, bounds.y, bounds.w, bounds.h);
186                 //Debug("Windos is %d,%d", target.w, target.h);
187                 for (int64_t x = max((int64_t)0, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
188                 {
189                         for (int64_t y = max((int64_t)0, bounds.y); y <= min(bounds.y + bounds.h, target.h-1); ++y)
190                         {
191                                 Real dx(2); dx *= Real(x - centre_x)/Real(bounds.w);
192                                 Real dy(2); dy *= Real(y - centre_y)/Real(bounds.h);
193                                 int64_t index = (x+target.w*y)*4;
194                                 
195                                 if (dx*dx + dy*dy <= Real(1))
196                                 {
197                                         target.pixels[index+0] = 0;
198                                         target.pixels[index+1] = 0;
199                                         target.pixels[index+2] = 0;
200                                         target.pixels[index+3] = 255;
201                                 }
202                         }
203                 }
204         }
205 }
206
207 Rect ObjectRenderer::CPURenderBounds(const Rect & bounds, const View & view, const CPURenderTarget & target)
208 {
209         Rect result = view.TransformToViewCoords(bounds);
210         result.x *= Real(target.w);
211         result.y *= Real(target.h);
212         result.w *= Real(target.w);
213         result.h *= Real(target.h);
214         return result;
215 }
216
217 ObjectRenderer::PixelPoint ObjectRenderer::CPUPointLocation(const Vec2 & point, const View & view, const CPURenderTarget & target)
218 {
219         // hack...
220         Rect result = view.TransformToViewCoords(Rect(point.x, point.y,1,1));
221         int64_t x = result.x*target.w;
222         int64_t y = result.y*target.h;
223         return PixelPoint(x,y);
224 }
225         
226
227 /**
228  * Bezier curve
229  * Not sure how to apply De'Casteljau, will just use a bunch of Bresnham lines for now.
230  */
231 void BezierRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
232 {
233         //Warn("Rendering Beziers on CPU. Things may explode.");
234         for (unsigned i = 0; i < m_indexes.size(); ++i)
235         {
236                 if (m_indexes[i] < first_obj_id) continue;
237                 if (m_indexes[i] >= last_obj_id) continue;
238                 const Rect & bounds = objects.bounds[m_indexes[i]];
239                 PixelBounds pix_bounds(CPURenderBounds(bounds,view,target));
240
241                 Bezier control(objects.beziers[objects.data_indices[m_indexes[i]]].ToAbsolute(bounds),CPURenderBounds(Rect(0,0,1,1), view, target));
242                 //Debug("%s -> %s via %s", objects.beziers[objects.data_indices[m_indexes[i]]].Str().c_str(), control.Str().c_str(), bounds.Str().c_str());
243                 // Draw a rectangle around the bezier for debugging the bounds rectangle calculations
244                 if (view.ShowingObjectBounds())
245                 {
246                         ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x+pix_bounds.w, pix_bounds.y, target, Colour(1,0,0,1));
247                         ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y+pix_bounds.h, pix_bounds.x+pix_bounds.w, pix_bounds.y+pix_bounds.h, target, Colour(0,1,0,1));
248                         ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x, pix_bounds.y+pix_bounds.h, target, Colour(1,0,0,1));
249                         ObjectRenderer::RenderLineOnCPU(pix_bounds.x+pix_bounds.w, pix_bounds.y, pix_bounds.x+pix_bounds.w, pix_bounds.y+pix_bounds.h, target, Colour(0,1,0,1));
250                 }
251                 // Draw lines between the control points for debugging
252                 //ObjectRenderer::RenderLineOnCPU((int64_t)control.x0, (int64_t)control.y0, (int64_t)control.x1, (int64_t)control.y1,target);
253                 //ObjectRenderer::RenderLineOnCPU((int64_t)control.x1, (int64_t)control.y1, (int64_t)control.x2, (int64_t)control.y2,target);
254                                                                                 
255
256                 
257                 Real x[2]; Real y[2];
258                 control.Evaluate(x[0], y[0], Real(0));
259                 //Debug("target is (%lu, %lu)", target.w, target.h);
260                 int64_t blen = min(max((int64_t)2, (int64_t)(target.w/view.GetBounds().w)), (int64_t)100);
261                 
262                 Real invblen(1); invblen /= blen;
263                 //Debug("Using %li lines, inverse %f", blen, Double(invblen));
264                 for (int64_t j = 1; j <= blen; ++j)
265                 {
266                         control.Evaluate(x[j % 2],y[j % 2], invblen*j);
267                         ObjectRenderer::RenderLineOnCPU((int64_t)Double(x[0]),(int64_t)Double(y[0]), (int64_t)Double(x[1]),(int64_t)Double(y[1]), target, Colour(0,0,0,!view.PerformingShading()));
268                 }
269                 
270                 /*
271                 Real u(0);
272                 while (u < Real(1))
273                 {
274                         u += Real(1e-6);
275                         Real x; Real y; control.Evaluate(x,y,u);
276                         int64_t index = ((int64_t)x + (int64_t)y*target.w)*4;
277                         if (index >= 0 && index < 4*(target.w*target.h))
278                         {
279                                 target.pixels[index+0] = 0;
280                                 target.pixels[index+1] = 0;
281                                 target.pixels[index+2] = 0;
282                                 target.pixels[index+3] = 255;
283                         }       
284                 }
285                 */
286                 
287         }
288 }
289
290 void BezierRenderer::PrepareBezierGPUBuffer(const Objects& objects)
291 {
292         m_bezier_coeffs.SetType(GraphicsBuffer::BufferTypeTexture);
293         m_bezier_coeffs.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
294         m_bezier_coeffs.Resize(objects.beziers.size()*sizeof(GPUBezierCoeffs));
295         BufferBuilder<GPUBezierCoeffs> builder(m_bezier_coeffs.Map(false, true, true), m_bezier_coeffs.GetSize());
296
297
298         for (unsigned i = 0; i < objects.beziers.size(); ++i)
299         {
300                 const Bezier & bez = objects.beziers[i];
301                 
302                 GPUBezierCoeffs coeffs = {
303                         Float(bez.x0), Float(bez.y0),
304                         Float(bez.x1), Float(bez.y1),
305                         Float(bez.x2), Float(bez.y2),
306                         Float(bez.x3), Float(bez.y3)
307                         };
308                 builder.Add(coeffs);
309         }
310         m_bezier_coeffs.UnMap();
311         glGenTextures(1, &m_bezier_buffer_texture);
312         glBindTexture(GL_TEXTURE_BUFFER, m_bezier_buffer_texture);
313         glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32F, m_bezier_coeffs.GetHandle());
314
315         m_bezier_ids.SetType(GraphicsBuffer::BufferTypeTexture);
316         m_bezier_ids.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
317         m_bezier_ids.Upload(objects.data_indices.size() * sizeof(uint32_t), &objects.data_indices[0]);
318         
319         glGenTextures(1, &m_bezier_id_buffer_texture);
320         glActiveTexture(GL_TEXTURE1);
321         glBindTexture(GL_TEXTURE_BUFFER, m_bezier_id_buffer_texture);
322         glTexBuffer(GL_TEXTURE_BUFFER, GL_R32I, m_bezier_ids.GetHandle());
323         glActiveTexture(GL_TEXTURE0);
324 }
325
326 void BezierRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
327 {
328         if (!m_shader_program.Valid())
329                 Warn("Shader is invalid (objects are of type %d)", m_type);
330
331         // If we don't have anything to render, return.
332         if (first_obj_id == last_obj_id) return;
333         // If there are no objects of this type, return.
334         if (m_indexes.empty()) return;
335
336         unsigned first_index = 0;
337         while (m_indexes.size() > first_index && m_indexes[first_index] < first_obj_id) first_index ++;
338         unsigned last_index = first_index;
339         while (m_indexes.size() > last_index && m_indexes[last_index] < last_obj_id) last_index ++;
340
341         m_shader_program.Use();
342         glUniform1i(m_shader_program.GetUniformLocation("bezier_buffer_texture"), 0);
343         glUniform1i(m_shader_program.GetUniformLocation("bezier_id_buffer_texture"), 1);
344         m_ibo.Bind();
345         glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(2*first_index*sizeof(uint32_t)));
346 }
347
348
349
350 /**
351  * Render Path (shading)
352  */
353 void PathRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
354 {
355         if (!view.ShowingObjectBounds() && !view.PerformingShading())
356                 return;
357                 
358         for (unsigned i = 0; i < m_indexes.size(); ++i)
359         {
360                 if (m_indexes[i] < first_obj_id) continue;
361                 if (m_indexes[i] >= last_obj_id) continue;
362                 
363                 
364                 Rect bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
365                 PixelBounds pix_bounds(bounds);
366                 const Path & path = objects.paths[objects.data_indices[m_indexes[i]]];
367                 if (path.m_fill.a == 0 || !view.PerformingShading())
368                         continue;
369                 
370                 for (unsigned f = 0; f < path.m_fill_points.size(); ++f)
371                 {
372                         PixelPoint fill_point(CPUPointLocation(path.m_fill_points[f], view, target));
373                         FloodFillOnCPU(fill_point.first, fill_point.second, pix_bounds, target, path.m_fill);
374                 }
375                 
376                 /*if (true)//(view.ShowingObjectBounds())
377                 {
378                         
379                         PixelPoint start(CPUPointLocation((path.m_top+path.m_left+path.m_right+path.m_bottom)/4, view, target));
380                         for (unsigned f = 0; f < path.m_fill_points.size(); ++f)
381                         {
382                                 PixelPoint end(CPUPointLocation(path.m_fill_points[f], view, target));
383                                 RenderLineOnCPU(start.first, start.second, end.first, end.second, target, Colour(0,0,1,1));
384                         }
385                 }
386                 */
387         
388         }       
389 }
390
391 /**
392  * For debug, save pixels to bitmap
393  */
394 void ObjectRenderer::SaveBMP(const CPURenderTarget & target, const char * filename)
395 {
396         SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(target.pixels, target.w, target.h, 8*4, target.w*4,
397         #if SDL_BYTEORDER == SDL_LIL_ENDIAN
398                 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000
399         #else
400                 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff
401         #endif //SDL_BYTEORDER  
402         );      
403         if (surf == NULL)
404                 Fatal("SDL_CreateRGBSurfaceFrom(pixels...) failed - %s", SDL_GetError());
405         if (SDL_SaveBMP(surf, filename) != 0)
406                 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
407
408         // Cleanup
409         SDL_FreeSurface(surf);
410 }
411
412 /**
413  * Bresenham's lines
414  */
415 void ObjectRenderer::RenderLineOnCPU(int64_t x0, int64_t y0, int64_t x1, int64_t y1, const CPURenderTarget & target, const Colour & colour, bool transpose)
416 {
417         int64_t dx = x1 - x0;
418         int64_t dy = y1 - y0;
419         bool neg_m = (dy*dx < 0);
420         dy = abs(dy);
421         dx = abs(dx);
422
423         // If positive slope > 1, just swap x and y
424         if (dy > dx)
425         {
426                 RenderLineOnCPU(y0,x0,y1,x1,target,colour,!transpose);
427                 return;
428         }
429
430         int64_t two_dy = 2*dy;
431         int64_t p = two_dy - dx;
432         int64_t two_dxdy = 2*(dy-dx);
433         int64_t x; int64_t y; int64_t x_end;
434         int64_t width = (transpose ? target.h : target.w);
435         int64_t height = (transpose ? target.w : target.h);
436
437         uint8_t rgba[4];
438         rgba[0] = 255*colour.r;
439         rgba[1] = 255*colour.g;
440         rgba[2] = 255*colour.b;
441         rgba[3] = 255*colour.a;
442
443         if (x0 > x1)
444         {
445                 x = x1;
446                 y = y1;
447                 x_end = x0;
448         }
449         else
450         {
451                 x = x0;
452                 y = y0;
453                 x_end = x1;
454         }
455
456         if (x < 0)
457         {
458                 if (x_end < 0) return;
459                 y = (neg_m ? y - (dy*-x)/dx : y + (dy*-x)/dx);
460                 x = 0;
461         }
462         
463         if (x_end > width)
464         {
465                 if (x > width) return;
466                 x_end = width-1;
467         }
468
469         // TODO: Avoid extra inner conditionals
470         do
471         {       
472                 if (x >= 0 && x < width && y >= 0 && y < height)
473                 {
474                         int64_t index = (transpose ? (y + x*target.w)*4 : (x + y*target.w)*4);
475                         for (int i = 0; i < 4; ++i)
476                                 target.pixels[index+i] = rgba[i];
477                 }
478                 if (p < 0)
479                         p += two_dy;
480                 else
481                 {
482                         if (neg_m) --y; else ++y;
483                         p += two_dxdy;
484                 }
485         } while (++x <= x_end);
486 }
487
488 void ObjectRenderer::FloodFillOnCPU(int64_t x, int64_t y, const PixelBounds & bounds, const CPURenderTarget & target, const Colour & fill)
489 {
490         if (fill == Colour(1,1,1,1))
491                 return;
492         queue<PixelPoint > traverse;
493         traverse.push(PixelPoint(x,y));
494         // now with 100% less stack overflows!
495         while (traverse.size() > 0)
496         {
497                 PixelPoint cur(traverse.front());
498                 traverse.pop();
499                 if (cur.first < 0 || cur.first < bounds.x || cur.first >= bounds.x+bounds.w || cur.first >= target.w ||
500                         cur.second < 0 || cur.second < bounds.y || cur.second >= bounds.y+bounds.h || cur.second >= target.h)
501                         continue;
502                 if (GetColour(target, cur.first, cur.second) != Colour(1,1,1,1))
503                         continue;
504                 SetColour(target, cur.first, cur.second, fill);
505                 
506
507                 traverse.push(PixelPoint(cur.first+1, cur.second));
508                 traverse.push(PixelPoint(cur.first-1, cur.second));
509                 traverse.push(PixelPoint(cur.first, cur.second-1));
510                 traverse.push(PixelPoint(cur.first, cur.second+1)); 
511         }
512 }
513
514 }

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