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

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