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

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