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

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