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

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