2 * @file objectrenderer.cpp
3 * @brief Implements ObjectRenderer and derived classes
6 #include "objectrenderer.h"
18 * ObjectRenderer constructor
19 * Note we cannot compile the shaders in the ShaderProgram constructor
20 * because the Screen class needs to initialise GL first and it has a
21 * ShaderProgram member
23 ObjectRenderer::ObjectRenderer(const ObjectType & type,
24 const char * vert_glsl_file, const char * frag_glsl_file, const char * geom_glsl_file)
25 : m_type(type), m_shader_program(), m_indexes(), m_buffer_builder(NULL)
27 m_shader_program.InitialiseShaders(vert_glsl_file, frag_glsl_file, geom_glsl_file);
28 m_shader_program.Use();
29 glUniform4f(m_shader_program.GetUniformLocation("colour"), 0,0,0,1); //TODO: Allow different colours
35 void ObjectRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
37 // If we don't have anything to render, return.
38 if (first_obj_id == last_obj_id) return;
39 // If there are no objects of this type, return.
40 if (m_indexes.empty()) return;
41 unsigned first_index = 0;
42 while (m_indexes.size() > first_index && m_indexes[first_index] < first_obj_id) first_index ++;
43 unsigned last_index = first_index;
44 while (m_indexes.size() > last_index && m_indexes[last_index] < last_obj_id) last_index ++;
46 m_shader_program.Use();
48 glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(2*first_index*sizeof(uint32_t)));
53 * Default implementation for rendering using CPU
55 void ObjectRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
57 Error("Cannot render objects of type %d on CPU", m_type);
58 //TODO: Render a rect or something instead?
62 * Prepare index buffers for both CPU and GPU rendering to receive indexes (but don't add any yet!)
64 void ObjectRenderer::PrepareBuffers(unsigned max_objects)
66 if (m_buffer_builder != NULL) // We already have a BufferBuilder
68 Fatal("Has been called before, without FinaliseBuffers being called since!");
70 // Empty and reserve the indexes vector (for CPU rendering)
72 m_indexes.reserve(max_objects); //TODO: Can probably make this smaller? Or leave it out? Do we care?
74 // Initialise and resize the ibo (for GPU rendering)
76 m_ibo.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
77 m_ibo.SetType(GraphicsBuffer::BufferTypeIndex);
78 m_ibo.Resize(max_objects * 2 * sizeof(uint32_t));
79 // BufferBuilder is used to construct the ibo
80 m_buffer_builder = new BufferBuilder<uint32_t>(m_ibo.Map(false, true, true), m_ibo.GetSize()); // new matches delete in ObjectRenderer::FinaliseBuffers
85 * Add object index to the buffers for CPU and GPU rendering
87 void ObjectRenderer::AddObjectToBuffers(unsigned index)
89 if (m_buffer_builder == NULL) // No BufferBuilder!
91 Fatal("Called without calling PrepareBuffers");
93 m_buffer_builder->Add(2*index); // ibo for GPU rendering
94 m_buffer_builder->Add(2*index+1);
95 m_indexes.push_back(index); // std::vector of indices for CPU rendering
99 * Finalise the index buffers for CPU and GPU rendering
101 void ObjectRenderer::FinaliseBuffers()
103 if (m_buffer_builder == NULL) // No BufferBuilder!
105 Fatal("Called without calling PrepareBuffers");
107 // For GPU rendering, UnMap the ibo
109 // ... and delete the BufferBuilder used to create it
110 delete m_buffer_builder; // delete matches new in ObjectRenderer::PrepareBuffers
111 m_buffer_builder = NULL;
113 // Nothing is necessary for CPU rendering
120 void RectFilledRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
122 for (unsigned i = 0; i < m_indexes.size(); ++i)
124 if (m_indexes[i] < first_obj_id) continue;
125 if (m_indexes[i] >= last_obj_id) continue;
126 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
127 FloodFillOnCPU(bounds.x+1, bounds.y+1, bounds, target, Colour(0,0,0,1));
129 for (int64_t x = max((int64_t)0, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
131 for (int64_t y = max((int64_t)0, bounds.y); y <= min(bounds.y+bounds.h, target.h-1); ++y)
133 int index = (x+target.w*y)*4;
134 target.pixels[index+0] = 0;
135 target.pixels[index+1] = 0;
136 target.pixels[index+2] = 0;
137 target.pixels[index+3] = 255;
147 void RectOutlineRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
149 //Debug("Render %u outlined rectangles on CPU", m_indexes.size());
150 for (unsigned i = 0; i < m_indexes.size(); ++i)
152 if (m_indexes[i] < first_obj_id) continue;
153 if (m_indexes[i] >= last_obj_id) continue;
154 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
156 // Using bresenham's lines now mainly because I want to see if they work
158 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x+bounds.w, bounds.y, target);
160 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y+bounds.h, bounds.x+bounds.w, bounds.y+bounds.h, target);
162 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x, bounds.y+bounds.h, target);
164 ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y, bounds.x+bounds.w, bounds.y+bounds.h, target);
166 // Diagonal for testing (from bottom left to top right)
167 //ObjectRenderer::RenderLineOnCPU(bounds.x,bounds.y+bounds.h, bounds.x+bounds.w, bounds.y,target, C_BLUE);
168 //ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y+bounds.h, bounds.x, bounds.y, target,C_GREEN);
175 void CircleFilledRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
177 for (unsigned i = 0; i < m_indexes.size(); ++i)
179 if (m_indexes[i] < first_obj_id) continue;
180 if (m_indexes[i] >= last_obj_id) continue;
181 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
182 int64_t centre_x = bounds.x + bounds.w / 2;
183 int64_t centre_y = bounds.y + bounds.h / 2;
185 //Debug("Centre is %d, %d", centre_x, centre_y);
186 //Debug("Bounds are %d,%d,%d,%d", bounds.x, bounds.y, bounds.w, bounds.h);
187 //Debug("Windos is %d,%d", target.w, target.h);
188 for (int64_t x = max((int64_t)0, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
190 for (int64_t y = max((int64_t)0, bounds.y); y <= min(bounds.y + bounds.h, target.h-1); ++y)
192 Real dx(2); dx *= Real(x - centre_x)/Real(bounds.w);
193 Real dy(2); dy *= Real(y - centre_y)/Real(bounds.h);
194 int64_t index = (x+target.w*y)*4;
196 if (dx*dx + dy*dy <= Real(1))
198 target.pixels[index+0] = 0;
199 target.pixels[index+1] = 0;
200 target.pixels[index+2] = 0;
201 target.pixels[index+3] = 255;
208 Rect ObjectRenderer::CPURenderBounds(const Rect & bounds, const View & view, const CPURenderTarget & target)
210 Rect result = view.TransformToViewCoords(bounds);
211 result.x *= Real(target.w);
212 result.y *= Real(target.h);
213 result.w *= Real(target.w);
214 result.h *= Real(target.h);
218 ObjectRenderer::PixelPoint ObjectRenderer::CPUPointLocation(const Vec2 & point, const View & view, const CPURenderTarget & target)
221 Rect result = view.TransformToViewCoords(Rect(point.x, point.y,1,1));
222 int64_t x = result.x*target.w;
223 int64_t y = result.y*target.h;
224 return PixelPoint(x,y);
230 * Not sure how to apply De'Casteljau, will just use a bunch of Bresnham lines for now.
232 void BezierRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
234 //Warn("Rendering Beziers on CPU. Things may explode.");
235 for (unsigned i = 0; i < m_indexes.size(); ++i)
237 if (m_indexes[i] < first_obj_id) continue;
238 if (m_indexes[i] >= last_obj_id) continue;
239 const Rect & bounds = objects.bounds[m_indexes[i]];
240 PixelBounds pix_bounds(CPURenderBounds(bounds,view,target));
242 Bezier control(objects.beziers[objects.data_indices[m_indexes[i]]].ToAbsolute(bounds),CPURenderBounds(Rect(0,0,1,1), view, target));
243 //Debug("%s -> %s via %s", objects.beziers[objects.data_indices[m_indexes[i]]].Str().c_str(), control.Str().c_str(), bounds.Str().c_str());
244 // Draw a rectangle around the bezier for debugging the bounds rectangle calculations
245 if (view.ShowingObjectBounds())
247 ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x+pix_bounds.w, pix_bounds.y, target, Colour(1,0,0,1));
248 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));
249 ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x, pix_bounds.y+pix_bounds.h, target, Colour(1,0,0,1));
250 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));
252 // Draw lines between the control points for debugging
253 //ObjectRenderer::RenderLineOnCPU((int64_t)control.x0, (int64_t)control.y0, (int64_t)control.x1, (int64_t)control.y1,target);
254 //ObjectRenderer::RenderLineOnCPU((int64_t)control.x1, (int64_t)control.y1, (int64_t)control.x2, (int64_t)control.y2,target);
259 unsigned blen = min(max(2U, (unsigned)(target.w/view.GetBounds().w)), min((unsigned)(pix_bounds.w+pix_bounds.h)/4 + 1, 100U));
261 // DeCasteljau Divide the Bezier
262 queue<Bezier> divisions;
263 divisions.push(control);
264 while(divisions.size() < blen)
266 Bezier & current = divisions.front();
267 if (current.GetType() == Bezier::LINE)
272 divisions.push(current.DeCasteljauSubdivideRight(Real(1)/Real(2)));
273 divisions.push(current.DeCasteljauSubdivideLeft(Real(1)/Real(2)));
276 //Debug("divisions %u", divisions.size());
278 while (divisions.size() > 0)
280 Bezier & current = divisions.front();
281 RenderLineOnCPU(current.x0, current.y0, current.x3, current.y3, target, Colour(0,0,0,!view.PerformingShading()));
285 /* Draw the Bezier by sampling
286 Real invblen(1); invblen /= blen;
290 control.Evaluate(v0.x, v0.y, 0);
291 for (int64_t j = 1; j <= blen; ++j)
293 control.Evaluate(v1.x, v1.y, t);
295 ObjectRenderer::RenderLineOnCPU(v0.x, v0.y, v1.x, v1.y, target, Colour(0,0,0,!view.PerformingShading()));
296 //ObjectRenderer::SetColour(target, x[0], y[0], Colour(1,0,0,1));
297 //ObjectRenderer::SetColour(target, x[1], y[1], Colour(0,0,1,1));
305 void BezierRenderer::PrepareBezierGPUBuffer(const Objects& objects)
307 m_bezier_coeffs.SetType(GraphicsBuffer::BufferTypeTexture);
308 m_bezier_coeffs.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
309 m_bezier_coeffs.Resize(objects.beziers.size()*sizeof(GPUBezierCoeffs));
310 BufferBuilder<GPUBezierCoeffs> builder(m_bezier_coeffs.Map(false, true, true), m_bezier_coeffs.GetSize());
313 for (unsigned i = 0; i < objects.beziers.size(); ++i)
315 const Bezier & bez = objects.beziers[i];
317 GPUBezierCoeffs coeffs = {
318 Float(bez.x0), Float(bez.y0),
319 Float(bez.x1), Float(bez.y1),
320 Float(bez.x2), Float(bez.y2),
321 Float(bez.x3), Float(bez.y3)
325 m_bezier_coeffs.UnMap();
326 glGenTextures(1, &m_bezier_buffer_texture);
327 glBindTexture(GL_TEXTURE_BUFFER, m_bezier_buffer_texture);
328 glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32F, m_bezier_coeffs.GetHandle());
330 m_bezier_ids.SetType(GraphicsBuffer::BufferTypeTexture);
331 m_bezier_ids.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
332 m_bezier_ids.Upload(objects.data_indices.size() * sizeof(uint32_t), &objects.data_indices[0]);
334 glGenTextures(1, &m_bezier_id_buffer_texture);
335 glActiveTexture(GL_TEXTURE1);
336 glBindTexture(GL_TEXTURE_BUFFER, m_bezier_id_buffer_texture);
337 glTexBuffer(GL_TEXTURE_BUFFER, GL_R32I, m_bezier_ids.GetHandle());
338 glActiveTexture(GL_TEXTURE0);
341 void BezierRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
343 if (!m_shader_program.Valid())
344 Warn("Shader is invalid (objects are of type %d)", m_type);
346 // If we don't have anything to render, return.
347 if (first_obj_id == last_obj_id) return;
348 // If there are no objects of this type, return.
349 if (m_indexes.empty()) return;
351 unsigned first_index = 0;
352 while (m_indexes.size() > first_index && m_indexes[first_index] < first_obj_id) first_index ++;
353 unsigned last_index = first_index;
354 while (m_indexes.size() > last_index && m_indexes[last_index] < last_obj_id) last_index ++;
356 m_shader_program.Use();
357 glUniform1i(m_shader_program.GetUniformLocation("bezier_buffer_texture"), 0);
358 glUniform1i(m_shader_program.GetUniformLocation("bezier_id_buffer_texture"), 1);
360 glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(2*first_index*sizeof(uint32_t)));
366 * Render Path (shading)
368 void PathRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
370 if (!view.ShowingObjectBounds() && !view.PerformingShading())
373 for (unsigned i = 0; i < m_indexes.size(); ++i)
375 if (m_indexes[i] < first_obj_id) continue;
376 if (m_indexes[i] >= last_obj_id) continue;
379 Rect bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
380 PixelBounds pix_bounds(bounds);
381 const Path & path = objects.paths[objects.data_indices[m_indexes[i]]];
382 if (path.m_fill.a == 0 || !view.PerformingShading())
385 for (unsigned f = 0; f < path.m_fill_points.size(); ++f)
387 PixelPoint fill_point(CPUPointLocation(path.m_fill_points[f], view, target));
388 FloodFillOnCPU(fill_point.first, fill_point.second, pix_bounds, target, path.m_fill);
391 /*if (true)//(view.ShowingObjectBounds())
394 PixelPoint start(CPUPointLocation((path.m_top+path.m_left+path.m_right+path.m_bottom)/4, view, target));
395 for (unsigned f = 0; f < path.m_fill_points.size(); ++f)
397 PixelPoint end(CPUPointLocation(path.m_fill_points[f], view, target));
398 RenderLineOnCPU(start.first, start.second, end.first, end.second, target, Colour(0,0,1,1));
407 * For debug, save pixels to bitmap
409 void ObjectRenderer::SaveBMP(const CPURenderTarget & target, const char * filename)
411 SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(target.pixels, target.w, target.h, 8*4, target.w*4,
412 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
413 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000
415 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff
416 #endif //SDL_BYTEORDER
419 Fatal("SDL_CreateRGBSurfaceFrom(pixels...) failed - %s", SDL_GetError());
420 if (SDL_SaveBMP(surf, filename) != 0)
421 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
424 SDL_FreeSurface(surf);
430 void ObjectRenderer::RenderLineOnCPU(int64_t x0, int64_t y0, int64_t x1, int64_t y1, const CPURenderTarget & target, const Colour & colour, bool transpose)
432 int64_t dx = x1 - x0;
433 int64_t dy = y1 - y0;
434 bool neg_m = (dy*dx < 0);
438 // If positive slope > 1, just swap x and y
441 RenderLineOnCPU(y0,x0,y1,x1,target,colour,!transpose);
445 int64_t two_dy = 2*dy;
446 int64_t p = two_dy - dx;
447 int64_t two_dxdy = 2*(dy-dx);
448 int64_t x; int64_t y; int64_t x_end;
449 int64_t width = (transpose ? target.h : target.w);
450 int64_t height = (transpose ? target.w : target.h);
453 rgba[0] = 255*colour.r;
454 rgba[1] = 255*colour.g;
455 rgba[2] = 255*colour.b;
456 rgba[3] = 255*colour.a;
473 if (x_end < 0) return;
474 y = (neg_m ? y - (dy*-x)/dx : y + (dy*-x)/dx);
480 if (x > width) return;
484 // TODO: Avoid extra inner conditionals
487 if (x >= 0 && x < width && y >= 0 && y < height)
489 int64_t index = (transpose ? (y + x*target.w)*4 : (x + y*target.w)*4);
490 for (int i = 0; i < 4; ++i)
491 target.pixels[index+i] = rgba[i];
497 if (neg_m) --y; else ++y;
500 } while (++x <= x_end);
503 void ObjectRenderer::FloodFillOnCPU(int64_t x, int64_t y, const PixelBounds & bounds, const CPURenderTarget & target, const Colour & fill)
505 if (fill == Colour(1,1,1,1))
507 queue<PixelPoint > traverse;
508 traverse.push(PixelPoint(x,y));
509 // now with 100% less stack overflows!
510 while (traverse.size() > 0)
512 PixelPoint cur(traverse.front());
514 if (cur.first < 0 || cur.first < bounds.x || cur.first >= bounds.x+bounds.w || cur.first >= target.w ||
515 cur.second < 0 || cur.second < bounds.y || cur.second >= bounds.y+bounds.h || cur.second >= target.h)
517 if (GetColour(target, cur.first, cur.second) != Colour(1,1,1,1))
519 SetColour(target, cur.first, cur.second, fill);
522 traverse.push(PixelPoint(cur.first+1, cur.second));
523 traverse.push(PixelPoint(cur.first-1, cur.second));
524 traverse.push(PixelPoint(cur.first, cur.second-1));
525 traverse.push(PixelPoint(cur.first, cur.second+1));