2 * @file objectrenderer.cpp
3 * @brief Implements ObjectRenderer and derived classes
6 #include "objectrenderer.h"
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
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)
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
34 void ObjectRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
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 ++;
45 m_shader_program.Use();
47 glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(2*first_index*sizeof(uint32_t)));
52 * Default implementation for rendering using CPU
54 void ObjectRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
56 Error("Cannot render objects of type %d on CPU", m_type);
57 //TODO: Render a rect or something instead?
61 * Prepare index buffers for both CPU and GPU rendering to receive indexes (but don't add any yet!)
63 void ObjectRenderer::PrepareBuffers(unsigned max_objects)
65 if (m_buffer_builder != NULL) // We already have a BufferBuilder
67 Fatal("Has been called before, without FinaliseBuffers being called since!");
69 // Empty and reserve the indexes vector (for CPU rendering)
71 m_indexes.reserve(max_objects); //TODO: Can probably make this smaller? Or leave it out? Do we care?
73 // Initialise and resize the ibo (for GPU rendering)
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
84 * Add object index to the buffers for CPU and GPU rendering
86 void ObjectRenderer::AddObjectToBuffers(unsigned index)
88 if (m_buffer_builder == NULL) // No BufferBuilder!
90 Fatal("Called without calling PrepareBuffers");
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
98 * Finalise the index buffers for CPU and GPU rendering
100 void ObjectRenderer::FinaliseBuffers()
102 if (m_buffer_builder == NULL) // No BufferBuilder!
104 Fatal("Called without calling PrepareBuffers");
106 // For GPU rendering, UnMap the ibo
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;
112 // Nothing is necessary for CPU rendering
119 void RectFilledRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
121 for (unsigned i = 0; i < m_indexes.size(); ++i)
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));
128 for (int64_t x = max((int64_t)0, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
130 for (int64_t y = max((int64_t)0, bounds.y); y <= min(bounds.y+bounds.h, target.h-1); ++y)
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;
146 void RectOutlineRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
148 //Debug("Render %u outlined rectangles on CPU", m_indexes.size());
149 for (unsigned i = 0; i < m_indexes.size(); ++i)
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));
155 // Using bresenham's lines now mainly because I want to see if they work
157 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x+bounds.w, bounds.y, target);
159 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y+bounds.h, bounds.x+bounds.w, bounds.y+bounds.h, target);
161 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x, bounds.y+bounds.h, target);
163 ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y, bounds.x+bounds.w, bounds.y+bounds.h, target);
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);
174 void CircleFilledRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
176 for (unsigned i = 0; i < m_indexes.size(); ++i)
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;
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)
189 for (int64_t y = max((int64_t)0, bounds.y); y <= min(bounds.y + bounds.h, target.h-1); ++y)
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;
195 if (dx*dx + dy*dy <= Real(1))
197 target.pixels[index+0] = 0;
198 target.pixels[index+1] = 0;
199 target.pixels[index+2] = 0;
200 target.pixels[index+3] = 255;
207 Rect ObjectRenderer::CPURenderBounds(const Rect & bounds, const View & view, const CPURenderTarget & target)
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);
217 ObjectRenderer::PixelPoint ObjectRenderer::CPUPointLocation(const Vec2 & point, const View & view, const CPURenderTarget & target)
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);
229 * Not sure how to apply De'Casteljau, will just use a bunch of Bresnham lines for now.
231 void BezierRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
233 //Warn("Rendering Beziers on CPU. Things may explode.");
234 for (unsigned i = 0; i < m_indexes.size(); ++i)
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));
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())
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));
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);
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);
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)
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()));
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))
279 target.pixels[index+0] = 0;
280 target.pixels[index+1] = 0;
281 target.pixels[index+2] = 0;
282 target.pixels[index+3] = 255;
290 void BezierRenderer::PrepareBezierGPUBuffer(const Objects& objects)
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());
298 for (unsigned i = 0; i < objects.beziers.size(); ++i)
300 const Bezier & bez = objects.beziers[i];
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)
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());
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]);
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);
326 void BezierRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
328 if (!m_shader_program.Valid())
329 Warn("Shader is invalid (objects are of type %d)", m_type);
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;
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 ++;
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);
345 glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(2*first_index*sizeof(uint32_t)));
351 * Render Path (shading)
353 void PathRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
355 if (!view.ShowingObjectBounds() && !view.PerformingShading())
358 for (unsigned i = 0; i < m_indexes.size(); ++i)
360 if (m_indexes[i] < first_obj_id) continue;
361 if (m_indexes[i] >= last_obj_id) continue;
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())
370 for (unsigned f = 0; f < path.m_fill_points.size(); ++f)
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);
376 /*if (true)//(view.ShowingObjectBounds())
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)
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));
392 * For debug, save pixels to bitmap
394 void ObjectRenderer::SaveBMP(const CPURenderTarget & target, const char * filename)
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
400 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff
401 #endif //SDL_BYTEORDER
404 Fatal("SDL_CreateRGBSurfaceFrom(pixels...) failed - %s", SDL_GetError());
405 if (SDL_SaveBMP(surf, filename) != 0)
406 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
409 SDL_FreeSurface(surf);
415 void ObjectRenderer::RenderLineOnCPU(int64_t x0, int64_t y0, int64_t x1, int64_t y1, const CPURenderTarget & target, const Colour & colour, bool transpose)
417 int64_t dx = x1 - x0;
418 int64_t dy = y1 - y0;
419 bool neg_m = (dy*dx < 0);
423 // If positive slope > 1, just swap x and y
426 RenderLineOnCPU(y0,x0,y1,x1,target,colour,!transpose);
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);
438 rgba[0] = 255*colour.r;
439 rgba[1] = 255*colour.g;
440 rgba[2] = 255*colour.b;
441 rgba[3] = 255*colour.a;
458 if (x_end < 0) return;
459 y = (neg_m ? y - (dy*-x)/dx : y + (dy*-x)/dx);
465 if (x > width) return;
469 // TODO: Avoid extra inner conditionals
472 if (x >= 0 && x < width && y >= 0 && y < height)
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];
482 if (neg_m) --y; else ++y;
485 } while (++x <= x_end);
488 void ObjectRenderer::FloodFillOnCPU(int64_t x, int64_t y, const PixelBounds & bounds, const CPURenderTarget & target, const Colour & fill)
490 if (fill == Colour(1,1,1,1))
492 queue<PixelPoint > traverse;
493 traverse.push(PixelPoint(x,y));
494 // now with 100% less stack overflows!
495 while (traverse.size() > 0)
497 PixelPoint cur(traverse.front());
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)
502 if (GetColour(target, cur.first, cur.second) != Colour(1,1,1,1))
504 SetColour(target, cur.first, cur.second, fill);
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));