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(const Bezier & relative, const Rect & bounds, 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));
236 Bezier control(relative.ToAbsolute(bounds), Rect(0,0,target.w, target.h));
238 if (view.ShowingBezierBounds())
240 ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x+pix_bounds.w, pix_bounds.y, target, Colour(255,0,0,0));
241 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));
242 ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x, pix_bounds.y+pix_bounds.h, target, Colour(255,0,0,0));
243 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));
246 unsigned blen = pix_bounds.w;//min(max(2U, (unsigned)Int64(Real(target.w)/view.GetBounds().w)),
247 //min((unsigned)(pix_bounds.w+pix_bounds.h)/4 + 1, 100U));
249 // DeCasteljau Divide the Bezier
250 #ifdef BEZIER_CPU_DECASTELJAU
251 queue<Bezier> divisions;
252 divisions.push(control);
253 while(divisions.size() < blen)
255 Bezier & current = divisions.front();
256 //if (current.GetType() == Bezier::LINE)
261 divisions.push(current.DeCasteljauSubdivideRight(Real(1)/Real(2)));
262 divisions.push(current.DeCasteljauSubdivideLeft(Real(1)/Real(2)));
265 while (divisions.size() > 0)
267 Bezier & current = divisions.front();
268 RenderLineOnCPU(Int64(current.x0), Int64(current.y0), Int64(current.x3), Int64(current.y3), target, c);
272 Real invblen(1); invblen /= Real(blen);
277 control.Evaluate(v0.x, v0.y, 0);
278 for (int64_t j = 1; j <= blen; ++j)
280 control.Evaluate(v1.x, v1.y, t);
281 RenderLineOnCPU(v0.x, v0.y, v1.x, v1.y, target);
285 #endif //BEZIER_CPU_DECASTELJAU
290 * Not sure how to apply De'Casteljau, will just use a bunch of Bresnham lines for now.
292 void BezierRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
294 #ifdef TRANSFORM_BEZIERS_TO_PATH
297 if (view.PerformingShading())
300 //Warn("Rendering Beziers on CPU. Things may explode.");
301 for (unsigned i = 0; i < m_indexes.size(); ++i)
303 if (m_indexes[i] < first_obj_id) continue;
304 if (m_indexes[i] >= last_obj_id) continue;
306 if (view.ShowingBezierType())
308 switch (objects.beziers[objects.data_indices[m_indexes[i]]].GetType())
312 case Bezier::QUADRATIC:
315 case Bezier::SERPENTINE:
331 Rect & bounds = objects.bounds[m_indexes[i]];
332 Bezier & bez = objects.beziers[objects.data_indices[m_indexes[i]]];
333 RenderBezierOnCPU(bez, bounds, view, target, c);
337 void BezierRenderer::PrepareBezierGPUBuffer(Objects & objects)
339 m_bezier_coeffs.SetType(GraphicsBuffer::BufferTypeTexture);
340 m_bezier_coeffs.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
341 m_bezier_coeffs.Resize(objects.beziers.size()*sizeof(GPUBezierCoeffs));
342 BufferBuilder<GPUBezierCoeffs> builder(m_bezier_coeffs.Map(false, true, true), m_bezier_coeffs.GetSize());
345 for (unsigned i = 0; i < objects.beziers.size(); ++i)
347 const Bezier & bez = objects.beziers[i];
348 GPUBezierCoeffs coeffs = {
349 Float(bez.x0), Float(bez.y0),
350 Float(bez.x1), Float(bez.y1),
351 Float(bez.x2), Float(bez.y2),
352 Float(bez.x3), Float(bez.y3)
357 m_bezier_coeffs.UnMap();
358 glGenTextures(1, &m_bezier_buffer_texture);
359 glBindTexture(GL_TEXTURE_BUFFER, m_bezier_buffer_texture);
360 glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32F, m_bezier_coeffs.GetHandle());
362 m_bezier_ids.SetType(GraphicsBuffer::BufferTypeTexture);
363 m_bezier_ids.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
364 m_bezier_ids.Upload(objects.data_indices.size() * sizeof(uint32_t), &objects.data_indices[0]);
366 glGenTextures(1, &m_bezier_id_buffer_texture);
367 glActiveTexture(GL_TEXTURE1);
368 glBindTexture(GL_TEXTURE_BUFFER, m_bezier_id_buffer_texture);
369 glTexBuffer(GL_TEXTURE_BUFFER, GL_R32I, m_bezier_ids.GetHandle());
370 glActiveTexture(GL_TEXTURE0);
373 void BezierRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
376 if (!m_shader_program.Valid())
377 Warn("Shader is invalid (objects are of type %d)", m_type);
379 // If we don't have anything to render, return.
380 if (first_obj_id == last_obj_id) return;
381 // If there are no objects of this type, return.
382 if (m_indexes.empty()) return;
384 unsigned first_index = 0;
385 while (m_indexes.size() > first_index && m_indexes[first_index] < first_obj_id) first_index ++;
386 unsigned last_index = first_index;
387 while (m_indexes.size() > last_index && m_indexes[last_index] < last_obj_id) last_index ++;
389 m_shader_program.Use();
390 glUniform1i(m_shader_program.GetUniformLocation("bezier_buffer_texture"), 0);
391 glUniform1i(m_shader_program.GetUniformLocation("bezier_id_buffer_texture"), 1);
393 glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(2*first_index*sizeof(uint32_t)));
399 * Render Path (shading)
401 void PathRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
405 for (unsigned i = 0; i < m_indexes.size(); ++i)
407 if (m_indexes[i] < first_obj_id) continue;
408 if (m_indexes[i] >= last_obj_id) continue;
411 Rect bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
412 PixelBounds pix_bounds(bounds);
413 Path & path = objects.paths[objects.data_indices[m_indexes[i]]];
415 if (view.ShowingFillPoints())
418 PixelPoint start(CPUPointLocation((path.m_top+path.m_left+path.m_right+path.m_bottom)/4, view, target));
419 for (unsigned f = 0; f < path.m_fill_points.size(); ++f)
421 PixelPoint end(CPUPointLocation(path.m_fill_points[f], view, target));
422 RenderLineOnCPU(start.first, start.second, end.first, end.second, target, Colour(0,0,255,0));
426 #ifndef TRANSFORM_BEZIERS_TO_PATH
427 if (!view.PerformingShading())
429 for (unsigned b = path.m_start; b <= path.m_end; ++b)
431 Rect & bbounds = objects.bounds[b];
432 Bezier & bez = objects.beziers[objects.data_indices[b]];
433 BezierRenderer::RenderBezierOnCPU(bez,bbounds,view,target,path.m_stroke);
436 // Outlines still get drawn if using TRANSFORM_BEZIERS_TO_PATH
437 for (unsigned b = path.m_start; b <= path.m_end; ++b)
439 Colour stroke = (view.PerformingShading()) ? path.m_stroke : Colour(0,0,0,255);
440 // bezier's bounds are relative to this object's bounds, convert back to view bounds
441 Rect bbounds = objects.bounds[b];
442 bbounds.x *= objects.bounds[m_indexes[i]].w;
443 bbounds.x += objects.bounds[m_indexes[i]].x;
444 bbounds.y *= objects.bounds[m_indexes[i]].h;
445 bbounds.y += objects.bounds[m_indexes[i]].y;
446 bbounds.w *= objects.bounds[m_indexes[i]].w;
447 bbounds.h *= objects.bounds[m_indexes[i]].h;
448 bbounds = view.TransformToViewCoords(bbounds);
449 //Debug("Bounds: %s", objects.bounds[m_indexes[i]].Str().c_str());
450 //Debug("Relative Bez Bounds: %s", objects.bounds[b].Str().c_str());
451 //Debug("Bez Bounds: %s", bbounds.Str().c_str());
453 Bezier & bez = objects.beziers[objects.data_indices[b]];
455 BezierRenderer::RenderBezierOnCPU(bez,bbounds,view,target, stroke);
457 if (!view.PerformingShading())
462 if (pix_bounds.w*pix_bounds.h > 100)
464 vector<Vec2> & fill_points = path.FillPoints(objects, view);
465 Debug("High resolution; use fill points %u,%u", pix_bounds.w, pix_bounds.h);
466 for (unsigned f = 0; f < fill_points.size(); ++f)
468 PixelPoint fill_point(CPUPointLocation(fill_points[f], view, target));
470 FloodFillOnCPU(fill_point.first, fill_point.second, pix_bounds, target, path.m_fill, path.m_stroke);
475 Debug("Low resolution; use brute force %u,%u",pix_bounds.w, pix_bounds.h);
476 int64_t y_min = max((int64_t)0, pix_bounds.y);
477 int64_t y_max = min(pix_bounds.y+pix_bounds.h, target.h);
478 int64_t x_min = max((int64_t)0, pix_bounds.x);
479 int64_t x_max = min(pix_bounds.x+pix_bounds.w, target.w);
480 for (int64_t y = y_min; y < y_max; ++y)
482 for (int64_t x = x_min; x < x_max; ++x)
484 Rect pb(path.SolveBounds(objects));
485 Vec2 pt(pb.x + (Real(x-pix_bounds.x)/Real(pix_bounds.w))*pb.w,
486 pb.y + (Real(y-pix_bounds.y)/Real(pix_bounds.h))*pb.h);
487 if (path.PointInside(objects, pt))
489 FloodFillOnCPU(x, y, pix_bounds, target, path.m_fill, path.m_stroke);
501 * For debug, save pixels to bitmap
503 void ObjectRenderer::SaveBMP(const CPURenderTarget & target, const char * filename)
505 SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(target.pixels, target.w, target.h, 8*4, target.w*4,
506 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
507 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000
509 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff
510 #endif //SDL_BYTEORDER
513 Fatal("SDL_CreateRGBSurfaceFrom(pixels...) failed - %s", SDL_GetError());
514 if (SDL_SaveBMP(surf, filename) != 0)
515 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
518 SDL_FreeSurface(surf);
527 void ObjectRenderer::RenderLineOnCPU(int64_t x0, int64_t y0, int64_t x1, int64_t y1, const CPURenderTarget & target, const Colour & colour, bool transpose)
529 int64_t dx = x1 - x0;
530 int64_t dy = y1 - y0;
531 bool neg_m = (dy*dx < 0);
535 // If positive slope > 1, just swap x and y
538 RenderLineOnCPU(y0,x0,y1,x1,target,colour,!transpose);
542 int64_t two_dy = 2*dy;
543 int64_t p = two_dy - dx;
544 int64_t two_dxdy = 2*(dy-dx);
545 int64_t x; int64_t y; int64_t x_end;
546 int64_t width = (transpose ? target.h : target.w);
547 int64_t height = (transpose ? target.w : target.h);
564 if (x_end < 0) return;
565 y = (neg_m ? y - (dy*-x)/dx : y + (dy*-x)/dx);
571 if (x > width) return;
575 // TODO: Avoid extra inner conditionals
578 if (x >= 0 && x < width && y >= 0 && y < height)
580 int64_t index = (transpose ? (y + x*target.w)*4 : (x + y*target.w)*4);
581 target.pixels[index+0] = colour.r;
582 target.pixels[index+1] = colour.g;
583 target.pixels[index+2] = colour.b;
584 target.pixels[index+3] = colour.a;
590 if (neg_m) --y; else ++y;
593 } while (++x <= x_end);
597 void ObjectRenderer::FloodFillOnCPU(int64_t x, int64_t y, const PixelBounds & bounds, const CPURenderTarget & target, const Colour & fill, const Colour & stroke)
599 // HACK to prevent overflooding (when the fill points for a path round to the pixel outside the boundary)
600 // (I totally just made that term up...)
601 Colour c = GetColour(target, x+1, y);
602 if (c == fill || c == stroke)
604 c = GetColour(target, x-1, y);
605 if (c == fill || c == stroke)
607 c = GetColour(target, x, y+1);
608 if (c == fill || c == stroke)
610 c = GetColour(target, x, y-1);
611 if (c == fill || c == stroke)
614 // The hack works but now we get underflooding, or, "droughts".
617 queue<PixelPoint > traverse;
618 traverse.push(PixelPoint(x,y));
619 // now with 100% less stack overflows!
620 while (traverse.size() > 0)
622 PixelPoint cur(traverse.front());
624 if (cur.first < 0 || cur.first < bounds.x || cur.first >= bounds.x+bounds.w || cur.first >= target.w ||
625 cur.second < 0 || cur.second < bounds.y || cur.second >= bounds.y+bounds.h || cur.second >= target.h)
627 c = GetColour(target, cur.first, cur.second);
628 if (c == fill || c == stroke)
631 SetColour(target, cur.first, cur.second, fill);
633 //Debug("c is {%u,%u,%u,%u} fill is {%u,%u,%u,%u}, stroke is {%u,%u,%u,%u}",
634 // c.r,c.g,c.b,c.a, fill.r,fill.g,fill.b,fill.a, stroke.r,stroke.g,stroke.b,stroke.a);
636 traverse.push(PixelPoint(cur.first+1, cur.second));
637 traverse.push(PixelPoint(cur.first-1, cur.second));
638 traverse.push(PixelPoint(cur.first, cur.second-1));
639 traverse.push(PixelPoint(cur.first, cur.second+1));