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 if (vert_glsl_file != NULL && frag_glsl_file != NULL && geom_glsl_file != NULL)
29 m_shader_program.InitialiseShaders(vert_glsl_file, frag_glsl_file, geom_glsl_file);
30 m_shader_program.Use();
31 glUniform4f(m_shader_program.GetUniformLocation("colour"), 0,0,0,1); //TODO: Allow different colours
38 void ObjectRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
40 // If we don't have anything to render, return.
41 if (first_obj_id == last_obj_id) return;
42 // If there are no objects of this type, return.
43 if (m_indexes.empty()) return;
44 unsigned first_index = 0;
45 while (m_indexes.size() > first_index && m_indexes[first_index] < first_obj_id) first_index ++;
46 unsigned last_index = first_index;
47 while (m_indexes.size() > last_index && m_indexes[last_index] < last_obj_id) last_index ++;
49 m_shader_program.Use();
51 glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(2*first_index*sizeof(uint32_t)));
56 * Default implementation for rendering using CPU
58 void ObjectRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
60 Error("Cannot render objects of type %d on CPU", m_type);
61 //TODO: Render a rect or something instead?
65 * Prepare index buffers for both CPU and GPU rendering to receive indexes (but don't add any yet!)
67 void ObjectRenderer::PrepareBuffers(unsigned max_objects)
69 if (m_buffer_builder != NULL) // We already have a BufferBuilder
71 Fatal("Has been called before, without FinaliseBuffers being called since!");
73 // Empty and reserve the indexes vector (for CPU rendering)
75 m_indexes.reserve(max_objects); //TODO: Can probably make this smaller? Or leave it out? Do we care?
77 // Initialise and resize the ibo (for GPU rendering)
79 m_ibo.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
80 m_ibo.SetType(GraphicsBuffer::BufferTypeIndex);
81 m_ibo.Resize(max_objects * 2 * sizeof(uint32_t));
82 // BufferBuilder is used to construct the ibo
83 m_buffer_builder = new BufferBuilder<uint32_t>(m_ibo.Map(false, true, true), m_ibo.GetSize()); // new matches delete in ObjectRenderer::FinaliseBuffers
88 * Add object index to the buffers for CPU and GPU rendering
90 void ObjectRenderer::AddObjectToBuffers(unsigned index)
92 if (m_buffer_builder == NULL) // No BufferBuilder!
94 Fatal("Called without calling PrepareBuffers");
96 m_buffer_builder->Add(2*index); // ibo for GPU rendering
97 m_buffer_builder->Add(2*index+1);
98 m_indexes.push_back(index); // std::vector of indices for CPU rendering
102 * Finalise the index buffers for CPU and GPU rendering
104 void ObjectRenderer::FinaliseBuffers()
106 if (m_buffer_builder == NULL) // No BufferBuilder!
108 Fatal("Called without calling PrepareBuffers");
110 // For GPU rendering, UnMap the ibo
112 // ... and delete the BufferBuilder used to create it
113 delete m_buffer_builder; // delete matches new in ObjectRenderer::PrepareBuffers
114 m_buffer_builder = NULL;
116 // Nothing is necessary for CPU rendering
123 void RectFilledRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
125 for (unsigned i = 0; i < m_indexes.size(); ++i)
127 if (m_indexes[i] < first_obj_id) continue;
128 if (m_indexes[i] >= last_obj_id) continue;
129 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
130 FloodFillOnCPU(bounds.x+1, bounds.y+1, bounds, target, Colour(0,0,0,1));
132 for (int64_t x = max((int64_t)0, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
134 for (int64_t y = max((int64_t)0, bounds.y); y <= min(bounds.y+bounds.h, target.h-1); ++y)
136 int index = (x+target.w*y)*4;
137 target.pixels[index+0] = 0;
138 target.pixels[index+1] = 0;
139 target.pixels[index+2] = 0;
140 target.pixels[index+3] = 255;
150 void RectOutlineRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
152 //Debug("Render %u outlined rectangles on CPU", m_indexes.size());
153 for (unsigned i = 0; i < m_indexes.size(); ++i)
155 if (m_indexes[i] < first_obj_id) continue;
156 if (m_indexes[i] >= last_obj_id) continue;
157 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
159 // Using bresenham's lines now mainly because I want to see if they work
161 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x+bounds.w, bounds.y, target);
163 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y+bounds.h, bounds.x+bounds.w, bounds.y+bounds.h, target);
165 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x, bounds.y+bounds.h, target);
167 ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y, bounds.x+bounds.w, bounds.y+bounds.h, target);
169 // Diagonal for testing (from bottom left to top right)
170 //ObjectRenderer::RenderLineOnCPU(bounds.x,bounds.y+bounds.h, bounds.x+bounds.w, bounds.y,target, C_BLUE);
171 //ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y+bounds.h, bounds.x, bounds.y, target,C_GREEN);
178 void CircleFilledRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
180 for (unsigned i = 0; i < m_indexes.size(); ++i)
182 if (m_indexes[i] < first_obj_id) continue;
183 if (m_indexes[i] >= last_obj_id) continue;
184 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
185 int64_t centre_x = bounds.x + bounds.w / 2;
186 int64_t centre_y = bounds.y + bounds.h / 2;
188 //Debug("Centre is %d, %d", centre_x, centre_y);
189 //Debug("Bounds are %d,%d,%d,%d", bounds.x, bounds.y, bounds.w, bounds.h);
190 //Debug("Windos is %d,%d", target.w, target.h);
191 for (int64_t x = max((int64_t)0, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
193 for (int64_t y = max((int64_t)0, bounds.y); y <= min(bounds.y + bounds.h, target.h-1); ++y)
195 Real dx(2); dx *= Real(x - centre_x)/Real(bounds.w);
196 Real dy(2); dy *= Real(y - centre_y)/Real(bounds.h);
197 int64_t index = (x+target.w*y)*4;
199 if (dx*dx + dy*dy <= Real(1))
201 target.pixels[index+0] = 0;
202 target.pixels[index+1] = 0;
203 target.pixels[index+2] = 0;
204 target.pixels[index+3] = 255;
211 Rect ObjectRenderer::CPURenderBounds(const Rect & bounds, const View & view, const CPURenderTarget & target)
213 Rect result = view.TransformToViewCoords(bounds);
214 result.x *= Real(target.w);
215 result.y *= Real(target.h);
216 result.w *= Real(target.w);
217 result.h *= Real(target.h);
221 ObjectRenderer::PixelPoint ObjectRenderer::CPUPointLocation(const Vec2 & point, const View & view, const CPURenderTarget & target)
224 Rect result = view.TransformToViewCoords(Rect(point.x, point.y,1,1));
225 int64_t x = Int64(result.x)*target.w;
226 int64_t y = Int64(result.y)*target.h;
227 return PixelPoint(x,y);
231 void BezierRenderer::RenderBezierOnCPU(unsigned i, Objects & objects, const View & view, const CPURenderTarget & target, const Colour & c)
233 const Rect & bounds = objects.bounds[i];
234 PixelBounds pix_bounds(CPURenderBounds(bounds,view,target));
235 Bezier control(objects.beziers[objects.data_indices[i]].ToAbsolute(bounds),CPURenderBounds(Rect(0,0,1,1), view, target));
237 if (view.ShowingBezierBounds())
239 ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x+pix_bounds.w, pix_bounds.y, target, Colour(255,0,0,0));
240 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,255,0,0));
241 ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x, pix_bounds.y+pix_bounds.h, target, Colour(255,0,0,0));
242 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,255,0,0));
245 unsigned blen = target.w;//min(max(2U, (unsigned)Int64(Real(target.w)/view.GetBounds().w)),
246 //min((unsigned)(pix_bounds.w+pix_bounds.h)/4 + 1, 100U));
248 // DeCasteljau Divide the Bezier
249 queue<Bezier> divisions;
250 divisions.push(control);
251 while(divisions.size() < blen)
253 Bezier & current = divisions.front();
254 if (current.GetType() == Bezier::LINE)
259 divisions.push(current.DeCasteljauSubdivideRight(Real(1)/Real(2)));
260 divisions.push(current.DeCasteljauSubdivideLeft(Real(1)/Real(2)));
263 while (divisions.size() > 0)
265 Bezier & current = divisions.front();
266 RenderLineOnCPU(Int64(current.x0), Int64(current.y0), Int64(current.x3), Int64(current.y3), target, c);
273 * Not sure how to apply De'Casteljau, will just use a bunch of Bresnham lines for now.
275 void BezierRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
277 if (view.PerformingShading())
280 //Warn("Rendering Beziers on CPU. Things may explode.");
281 for (unsigned i = 0; i < m_indexes.size(); ++i)
283 if (m_indexes[i] < first_obj_id) continue;
284 if (m_indexes[i] >= last_obj_id) continue;
286 if (view.ShowingBezierType())
288 switch (objects.beziers[objects.data_indices[m_indexes[i]]].GetType())
292 case Bezier::QUADRATIC:
295 case Bezier::SERPENTINE:
311 RenderBezierOnCPU(m_indexes[i], objects, view, target, c);
315 void BezierRenderer::PrepareBezierGPUBuffer(Objects & objects)
317 m_bezier_coeffs.SetType(GraphicsBuffer::BufferTypeTexture);
318 m_bezier_coeffs.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
319 m_bezier_coeffs.Resize(objects.beziers.size()*sizeof(GPUBezierCoeffs));
320 BufferBuilder<GPUBezierCoeffs> builder(m_bezier_coeffs.Map(false, true, true), m_bezier_coeffs.GetSize());
323 for (unsigned i = 0; i < objects.beziers.size(); ++i)
325 const Bezier & bez = objects.beziers[i];
327 GPUBezierCoeffs coeffs = {
328 Float(bez.x0), Float(bez.y0),
329 Float(bez.x1), Float(bez.y1),
330 Float(bez.x2), Float(bez.y2),
331 Float(bez.x3), Float(bez.y3)
335 m_bezier_coeffs.UnMap();
336 glGenTextures(1, &m_bezier_buffer_texture);
337 glBindTexture(GL_TEXTURE_BUFFER, m_bezier_buffer_texture);
338 glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32F, m_bezier_coeffs.GetHandle());
340 m_bezier_ids.SetType(GraphicsBuffer::BufferTypeTexture);
341 m_bezier_ids.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
342 m_bezier_ids.Upload(objects.data_indices.size() * sizeof(uint32_t), &objects.data_indices[0]);
344 glGenTextures(1, &m_bezier_id_buffer_texture);
345 glActiveTexture(GL_TEXTURE1);
346 glBindTexture(GL_TEXTURE_BUFFER, m_bezier_id_buffer_texture);
347 glTexBuffer(GL_TEXTURE_BUFFER, GL_R32I, m_bezier_ids.GetHandle());
348 glActiveTexture(GL_TEXTURE0);
351 void BezierRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
353 if (!m_shader_program.Valid())
354 Warn("Shader is invalid (objects are of type %d)", m_type);
356 // If we don't have anything to render, return.
357 if (first_obj_id == last_obj_id) return;
358 // If there are no objects of this type, return.
359 if (m_indexes.empty()) return;
361 unsigned first_index = 0;
362 while (m_indexes.size() > first_index && m_indexes[first_index] < first_obj_id) first_index ++;
363 unsigned last_index = first_index;
364 while (m_indexes.size() > last_index && m_indexes[last_index] < last_obj_id) last_index ++;
366 m_shader_program.Use();
367 glUniform1i(m_shader_program.GetUniformLocation("bezier_buffer_texture"), 0);
368 glUniform1i(m_shader_program.GetUniformLocation("bezier_id_buffer_texture"), 1);
370 glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(2*first_index*sizeof(uint32_t)));
376 * Render Path (shading)
378 void PathRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
382 for (unsigned i = 0; i < m_indexes.size(); ++i)
384 if (m_indexes[i] < first_obj_id) continue;
385 if (m_indexes[i] >= last_obj_id) continue;
388 Rect bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
389 PixelBounds pix_bounds(bounds);
390 Path & path = objects.paths[objects.data_indices[m_indexes[i]]];
392 if (view.ShowingFillPoints())
395 PixelPoint start(CPUPointLocation((path.m_top+path.m_left+path.m_right+path.m_bottom)/4, view, target));
396 for (unsigned f = 0; f < path.m_fill_points.size(); ++f)
398 PixelPoint end(CPUPointLocation(path.m_fill_points[f], view, target));
399 RenderLineOnCPU(start.first, start.second, end.first, end.second, target, Colour(0,0,255,0));
403 if (!view.PerformingShading())
406 for (unsigned b = path.m_start; b <= path.m_end; ++b)
408 BezierRenderer::RenderBezierOnCPU(b,objects,view,target,path.m_stroke);
411 if (pix_bounds.w*pix_bounds.h > 100)
413 vector<Vec2> & fill_points = path.FillPoints(objects, view);
414 Debug("High resolution; use fill points %u,%u", pix_bounds.w, pix_bounds.h);
415 for (unsigned f = 0; f < fill_points.size(); ++f)
417 PixelPoint fill_point(CPUPointLocation(fill_points[f], view, target));
419 FloodFillOnCPU(fill_point.first, fill_point.second, pix_bounds, target, path.m_fill, path.m_stroke);
424 Debug("Low resolution; use brute force %u,%u",pix_bounds.w, pix_bounds.h);
425 int64_t y_min = max((int64_t)0, pix_bounds.y);
426 int64_t y_max = min(pix_bounds.y+pix_bounds.h, target.h);
427 int64_t x_min = max((int64_t)0, pix_bounds.x);
428 int64_t x_max = min(pix_bounds.x+pix_bounds.w, target.w);
429 for (int64_t y = y_min; y < y_max; ++y)
431 for (int64_t x = x_min; x < x_max; ++x)
433 Rect pb(path.SolveBounds(objects));
434 Vec2 pt(pb.x + (Real(x-pix_bounds.x)/Real(pix_bounds.w))*pb.w,
435 pb.y + (Real(y-pix_bounds.y)/Real(pix_bounds.h))*pb.h);
436 if (path.PointInside(objects, pt))
438 FloodFillOnCPU(x, y, pix_bounds, target, path.m_fill, path.m_stroke);
447 * For debug, save pixels to bitmap
449 void ObjectRenderer::SaveBMP(const CPURenderTarget & target, const char * filename)
451 SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(target.pixels, target.w, target.h, 8*4, target.w*4,
452 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
453 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000
455 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff
456 #endif //SDL_BYTEORDER
459 Fatal("SDL_CreateRGBSurfaceFrom(pixels...) failed - %s", SDL_GetError());
460 if (SDL_SaveBMP(surf, filename) != 0)
461 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
464 SDL_FreeSurface(surf);
470 void ObjectRenderer::RenderLineOnCPU(int64_t x0, int64_t y0, int64_t x1, int64_t y1, const CPURenderTarget & target, const Colour & colour, bool transpose)
472 int64_t dx = x1 - x0;
473 int64_t dy = y1 - y0;
474 bool neg_m = (dy*dx < 0);
478 // If positive slope > 1, just swap x and y
481 RenderLineOnCPU(y0,x0,y1,x1,target,colour,!transpose);
485 int64_t two_dy = 2*dy;
486 int64_t p = two_dy - dx;
487 int64_t two_dxdy = 2*(dy-dx);
488 int64_t x; int64_t y; int64_t x_end;
489 int64_t width = (transpose ? target.h : target.w);
490 int64_t height = (transpose ? target.w : target.h);
507 if (x_end < 0) return;
508 y = (neg_m ? y - (dy*-x)/dx : y + (dy*-x)/dx);
514 if (x > width) return;
518 // TODO: Avoid extra inner conditionals
521 if (x >= 0 && x < width && y >= 0 && y < height)
523 int64_t index = (transpose ? (y + x*target.w)*4 : (x + y*target.w)*4);
524 target.pixels[index+0] = colour.r;
525 target.pixels[index+1] = colour.g;
526 target.pixels[index+2] = colour.b;
527 target.pixels[index+3] = colour.a;
533 if (neg_m) --y; else ++y;
536 } while (++x <= x_end);
540 void ObjectRenderer::FloodFillOnCPU(int64_t x, int64_t y, const PixelBounds & bounds, const CPURenderTarget & target, const Colour & fill, const Colour & stroke)
542 // HACK to prevent overflooding (when the fill points for a path round to the pixel outside the boundary)
543 // (I totally just made that term up...)
544 Colour c = GetColour(target, x+1, y);
545 if (c == fill || c == stroke)
547 c = GetColour(target, x-1, y);
548 if (c == fill || c == stroke)
550 c = GetColour(target, x, y+1);
551 if (c == fill || c == stroke)
553 c = GetColour(target, x, y-1);
554 if (c == fill || c == stroke)
557 // The hack works but now we get underflooding, or, "droughts".
560 queue<PixelPoint > traverse;
561 traverse.push(PixelPoint(x,y));
562 // now with 100% less stack overflows!
563 while (traverse.size() > 0)
565 PixelPoint cur(traverse.front());
567 if (cur.first < 0 || cur.first < bounds.x || cur.first >= bounds.x+bounds.w || cur.first >= target.w ||
568 cur.second < 0 || cur.second < bounds.y || cur.second >= bounds.y+bounds.h || cur.second >= target.h)
570 c = GetColour(target, cur.first, cur.second);
571 if (c == fill || c == stroke)
574 SetColour(target, cur.first, cur.second, fill);
576 //Debug("c is {%u,%u,%u,%u} fill is {%u,%u,%u,%u}, stroke is {%u,%u,%u,%u}",
577 // c.r,c.g,c.b,c.a, fill.r,fill.g,fill.b,fill.a, stroke.r,stroke.g,stroke.b,stroke.a);
579 traverse.push(PixelPoint(cur.first+1, cur.second));
580 traverse.push(PixelPoint(cur.first-1, cur.second));
581 traverse.push(PixelPoint(cur.first, cur.second-1));
582 traverse.push(PixelPoint(cur.first, cur.second+1));