Mostly features added to DebugScript
[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 #include <vector>
9 #include <queue>
10 #include <stack>
11
12 using namespace std;
13
14 namespace IPDF
15 {
16
17 /**
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
22  */
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)
26 {
27         if (vert_glsl_file != NULL && frag_glsl_file != NULL && geom_glsl_file != NULL)
28         {
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
32         }
33 }
34
35 /**
36  * Render using GPU
37  */
38 void ObjectRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
39 {
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 ++;
48
49         m_shader_program.Use();
50         m_ibo.Bind();
51         glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(2*first_index*sizeof(uint32_t)));
52 }
53
54
55 /**
56  * Default implementation for rendering using CPU
57  */
58 void ObjectRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
59 {
60         Error("Cannot render objects of type %d on CPU", m_type);
61         //TODO: Render a rect or something instead?
62 }
63
64 /**
65  * Prepare index buffers for both CPU and GPU rendering to receive indexes (but don't add any yet!)
66  */
67 void ObjectRenderer::PrepareBuffers(unsigned max_objects)
68 {
69         if (m_buffer_builder != NULL) // We already have a BufferBuilder
70         {
71                 Fatal("Has been called before, without FinaliseBuffers being called since!");
72         }
73         // Empty and reserve the indexes vector (for CPU rendering)
74         m_indexes.clear();
75         m_indexes.reserve(max_objects); //TODO: Can probably make this smaller? Or leave it out? Do we care?
76
77         // Initialise and resize the ibo (for GPU rendering)
78         m_ibo.Invalidate();
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
84
85 }
86
87 /**
88  * Add object index to the buffers for CPU and GPU rendering
89  */
90 void ObjectRenderer::AddObjectToBuffers(unsigned index)
91 {
92         if (m_buffer_builder == NULL) // No BufferBuilder!
93         {
94                 Fatal("Called without calling PrepareBuffers");
95         }
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
99 }
100
101 /**
102  * Finalise the index buffers for CPU and GPU rendering
103  */
104 void ObjectRenderer::FinaliseBuffers()
105 {
106         if (m_buffer_builder == NULL) // No BufferBuilder!
107         {
108                 Fatal("Called without calling PrepareBuffers");
109         }
110         // For GPU rendering, UnMap the ibo
111         m_ibo.UnMap();
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;
115         
116         // Nothing is necessary for CPU rendering
117 }
118
119
120 /**
121  * Rectangle (filled)
122  */
123 void RectFilledRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
124 {
125         for (unsigned i = 0; i < m_indexes.size(); ++i)
126         {
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));
131                 /*
132                 for (int64_t x = max((int64_t)0, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
133                 {
134                         for (int64_t y = max((int64_t)0, bounds.y); y <= min(bounds.y+bounds.h, target.h-1); ++y)
135                         {
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;
141                         }
142                 }
143                 */
144         }
145 }
146
147 /**
148  * Rectangle (outine)
149  */
150 void RectOutlineRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
151 {
152         //Debug("Render %u outlined rectangles on CPU", m_indexes.size());
153         for (unsigned i = 0; i < m_indexes.size(); ++i)
154         {
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));
158                 
159                 // Using bresenham's lines now mainly because I want to see if they work
160                 // top
161                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x+bounds.w, bounds.y, target);
162                 // bottom
163                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y+bounds.h, bounds.x+bounds.w, bounds.y+bounds.h, target);
164                 // left
165                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x, bounds.y+bounds.h, target);
166                 // right
167                 ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y, bounds.x+bounds.w, bounds.y+bounds.h, target);
168
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);
172         }
173 }
174
175 /**
176  * Circle (filled)
177  */
178 void CircleFilledRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
179 {
180         for (unsigned i = 0; i < m_indexes.size(); ++i)
181         {
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;
187                 
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)
192                 {
193                         for (int64_t y = max((int64_t)0, bounds.y); y <= min(bounds.y + bounds.h, target.h-1); ++y)
194                         {
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;
198                                 
199                                 if (dx*dx + dy*dy <= Real(1))
200                                 {
201                                         target.pixels[index+0] = 0;
202                                         target.pixels[index+1] = 0;
203                                         target.pixels[index+2] = 0;
204                                         target.pixels[index+3] = 255;
205                                 }
206                         }
207                 }
208         }
209 }
210
211 Rect ObjectRenderer::CPURenderBounds(const Rect & bounds, const View & view, const CPURenderTarget & target)
212 {
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);
218         return result;
219 }
220
221 ObjectRenderer::PixelPoint ObjectRenderer::CPUPointLocation(const Vec2 & point, const View & view, const CPURenderTarget & target)
222 {
223         // hack...
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);
228 }
229         
230         
231 void BezierRenderer::RenderBezierOnCPU(const Bezier & relative, const Rect & bounds, const View & view, const CPURenderTarget & target, const Colour & c)
232 {
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)); 
237
238         if (view.ShowingBezierBounds())
239         {
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));
244         }
245         
246         int64_t blen =  min((int64_t)50,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));
248                 
249                 // DeCasteljau Divide the Bezier
250         #ifdef BEZIER_CPU_DECASTELJAU
251         queue<Bezier> divisions;
252         divisions.push(control);
253         while(divisions.size() < (uint64_t)(blen))
254         {
255                 Bezier & current = divisions.front();
256                 //if (current.GetType() == Bezier::LINE)
257                 //{
258                 //      --blen;
259                 //      continue;
260                 //}
261                 divisions.push(current.DeCasteljauSubdivideRight(Real(1)/Real(2)));     
262                 divisions.push(current.DeCasteljauSubdivideLeft(Real(1)/Real(2)));
263                 divisions.pop();
264         }
265         while (divisions.size() > 0)
266         {
267                 Bezier & current = divisions.front();
268                 RenderLineOnCPU(Int64(current.x0), Int64(current.y0), Int64(current.x3), Int64(current.y3), target, c);
269                 divisions.pop();
270         }               
271         #else
272                 Real invblen(1); invblen /= Real(blen);
273                 
274                 Real t(invblen);
275                 Vec2 v0;
276                 Vec2 v1;
277                 control.Evaluate(v0.x, v0.y, 0);
278                 for (int64_t j = 1; j <= blen; ++j)
279                 {
280                         control.Evaluate(v1.x, v1.y, t);
281                         RenderLineOnCPU(v0.x, v0.y, v1.x, v1.y, target);
282                         t += invblen;
283                         v0 = v1;
284                 }
285         #endif //BEZIER_CPU_DECASTELJAU
286 }
287
288 /**
289  * Bezier curve
290  * Not sure how to apply De'Casteljau, will just use a bunch of Bresnham lines for now.
291  */
292 void BezierRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
293 {
294         #ifdef TRANSFORM_BEZIERS_TO_PATH
295                 return;
296         #endif
297         if (view.PerformingShading())
298                 return;
299                 
300         //Warn("Rendering Beziers on CPU. Things may explode.");
301         for (unsigned i = 0; i < m_indexes.size(); ++i)
302         {
303                 if (m_indexes[i] < first_obj_id) continue;
304                 if (m_indexes[i] >= last_obj_id) continue;
305                 Colour c(0,0,0,255);
306                 if (view.ShowingBezierType())
307                 {
308                         switch (objects.beziers[objects.data_indices[m_indexes[i]]].GetType())
309                         {
310                                 case Bezier::LINE:
311                                         break;
312                                 case Bezier::QUADRATIC:
313                                         c.b = 255;
314                                         break;
315                                 case Bezier::SERPENTINE:
316                                         c.r = 255;
317                                         break;
318                                 case Bezier::CUSP:
319                                         c.g = 255;
320                                         break;
321                                 case Bezier::LOOP:
322                                         c.r = 128;
323                                         c.b = 128;
324                                         break;
325                                 default:
326                                         c.r = 128;
327                                         c.g = 128;
328                                         break;
329                         }
330                 }
331                 Rect bounds = view.TransformToViewCoords(objects.bounds[m_indexes[i]]);
332                 Bezier & bez = objects.beziers[objects.data_indices[m_indexes[i]]];
333                 RenderBezierOnCPU(bez, bounds, view, target, c);
334         }
335 }
336
337 void BezierRenderer::PrepareBezierGPUBuffer(Objects & objects)
338 {
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());
343
344         
345         for (unsigned i = 0; i < objects.beziers.size(); ++i)
346         {
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)
353                         };
354                 builder.Add(coeffs);
355         }
356         
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());
361
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]);
365         
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);
371 }
372
373 void BezierRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
374 {
375
376         if (!m_shader_program.Valid())
377                 Warn("Shader is invalid (objects are of type %d)", m_type);
378
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;
383
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 ++;
388
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);
392         m_ibo.Bind();
393         
394         // To antialias the line... causes SIGFPE because why would anything make sense
395         //glEnable(GL_BLEND);
396         //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
397         //glEnable(GL_LINE_SMOOTH);
398         //glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
399         glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(2*first_index*sizeof(uint32_t)));
400 }
401
402
403
404 /**
405  * Render Path (shading)
406  */
407 void PathRenderer::RenderUsingCPU(Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
408 {
409
410                 
411         for (unsigned i = 0; i < m_indexes.size(); ++i)
412         {
413                 if (m_indexes[i] < first_obj_id) continue;
414                 if (m_indexes[i] >= last_obj_id) continue;
415                 
416                 
417         
418                 Path & path = objects.paths[objects.data_indices[m_indexes[i]]];
419                 Rect bounds(CPURenderBounds(path.GetBounds(objects), view, target));
420                 PixelBounds pix_bounds(bounds);
421                 
422                 if (view.ShowingFillPoints())
423                 {
424                         
425                         PixelPoint start(CPUPointLocation((path.m_top+path.m_left+path.m_right+path.m_bottom)/4, view, target));
426                         for (unsigned f = 0; f < path.m_fill_points.size(); ++f)
427                         {
428                                 PixelPoint end(CPUPointLocation(path.m_fill_points[f], view, target));
429                                 RenderLineOnCPU(start.first, start.second, end.first, end.second, target, Colour(0,0,255,0));
430                         }
431                 }
432                 
433                 #ifndef TRANSFORM_BEZIERS_TO_PATH
434                 if (!view.PerformingShading())
435                         continue;
436                 for (unsigned b = path.m_start; b <= path.m_end; ++b)
437                 {
438                         Rect bbounds = view.TransformToViewCoords(objects.bounds[b]);
439                         Bezier & bez = objects.beziers[objects.data_indices[b]];
440                         BezierRenderer::RenderBezierOnCPU(bez,bbounds,view,target,path.m_stroke);
441                 }
442                 #else
443                 // Outlines still get drawn if using TRANSFORM_BEZIERS_TO_PATH
444                 for (unsigned b = path.m_start; b <= path.m_end; ++b)
445                 {
446                         Colour stroke = (view.PerformingShading()) ? path.m_stroke : Colour(0,0,0,255);
447                         // bezier's bounds are relative to this object's bounds, convert back to view bounds
448                         Rect bbounds = objects.bounds[b];
449                         bbounds.x *= objects.bounds[m_indexes[i]].w;
450                         bbounds.x += objects.bounds[m_indexes[i]].x;
451                         bbounds.y *= objects.bounds[m_indexes[i]].h;
452                         bbounds.y += objects.bounds[m_indexes[i]].y;
453                         bbounds.w *= objects.bounds[m_indexes[i]].w;
454                         bbounds.h *= objects.bounds[m_indexes[i]].h;
455                         bbounds = view.TransformToViewCoords(bbounds);
456                         //Debug("Bounds: %s", objects.bounds[m_indexes[i]].Str().c_str());
457                         //Debug("Relative Bez Bounds: %s", objects.bounds[b].Str().c_str());
458                         //Debug("Bez Bounds: %s", bbounds.Str().c_str());
459                         
460                         Bezier & bez = objects.beziers[objects.data_indices[b]];
461                         
462                         BezierRenderer::RenderBezierOnCPU(bez,bbounds,view,target, stroke);
463                 }
464                 if (!view.PerformingShading())
465                         continue;
466                 #endif
467                 
468                 
469                 if (pix_bounds.w*pix_bounds.h > 100)
470                 {
471                         vector<Vec2> & fill_points = path.FillPoints(objects, view);
472                         Debug("High resolution; use fill points %u,%u", pix_bounds.w, pix_bounds.h);
473                         for (unsigned f = 0; f < fill_points.size(); ++f)
474                         {
475                                 PixelPoint fill_point(CPUPointLocation(fill_points[f], view, target));
476                                 
477                                 FloodFillOnCPU(fill_point.first, fill_point.second, pix_bounds, target, path.m_fill, path.m_stroke);
478                         }
479                 }
480                 else
481                 {
482                         Debug("Low resolution; use brute force %u,%u",pix_bounds.w, pix_bounds.h);
483                         int64_t y_min = max((int64_t)0, pix_bounds.y);
484                         int64_t y_max = min(pix_bounds.y+pix_bounds.h, target.h);
485                         int64_t x_min = max((int64_t)0, pix_bounds.x);
486                         int64_t x_max = min(pix_bounds.x+pix_bounds.w, target.w);
487                         for (int64_t y = y_min; y < y_max; ++y)
488                         {
489                                 for (int64_t x = x_min; x < x_max; ++x)
490                                 {
491                                         Rect pb(path.SolveBounds(objects));
492                                         Vec2 pt(pb.x + (Real(x-pix_bounds.x)/Real(pix_bounds.w))*pb.w, 
493                                                         pb.y + (Real(y-pix_bounds.y)/Real(pix_bounds.h))*pb.h);
494                                         if (path.PointInside(objects, pt))
495                                         {
496                                                 FloodFillOnCPU(x, y, pix_bounds, target, path.m_fill, path.m_stroke);
497                                         }
498                                 }
499                         }
500                 }
501         }       
502 }
503
504
505
506
507 /**
508  * For debug, save pixels to bitmap
509  */
510 void ObjectRenderer::SaveBMP(const CPURenderTarget & target, const char * filename)
511 {
512         SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(target.pixels, target.w, target.h, 8*4, target.w*4,
513         #if SDL_BYTEORDER == SDL_LIL_ENDIAN
514                 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000
515         #else
516                 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff
517         #endif //SDL_BYTEORDER  
518         );      
519         if (surf == NULL)
520                 Fatal("SDL_CreateRGBSurfaceFrom(pixels...) failed - %s", SDL_GetError());
521         if (SDL_SaveBMP(surf, filename) != 0)
522                 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
523
524         // Cleanup
525         SDL_FreeSurface(surf);
526 }
527
528
529
530
531 /**
532  * Bresenham's lines
533  */
534 void ObjectRenderer::RenderLineOnCPU(int64_t x0, int64_t y0, int64_t x1, int64_t y1, const CPURenderTarget & target, const Colour & colour, bool transpose)
535 {
536         int64_t dx = x1 - x0;
537         int64_t dy = y1 - y0;
538         bool neg_m = (dy*dx < 0);
539         dy = abs(dy);
540         dx = abs(dx);
541
542         // If positive slope > 1, just swap x and y
543         if (dy > dx)
544         {
545                 RenderLineOnCPU(y0,x0,y1,x1,target,colour,!transpose);
546                 return;
547         }
548
549         int64_t two_dy = 2*dy;
550         int64_t p = two_dy - dx;
551         int64_t two_dxdy = 2*(dy-dx);
552         int64_t x; int64_t y; int64_t x_end;
553         int64_t width = (transpose ? target.h : target.w);
554         int64_t height = (transpose ? target.w : target.h);
555
556         if (x0 > x1)
557         {
558                 x = x1;
559                 y = y1;
560                 x_end = x0;
561         }
562         else
563         {
564                 x = x0;
565                 y = y0;
566                 x_end = x1;
567         }
568
569         if (x < 0)
570         {
571                 if (x_end < 0) return;
572                 y = (neg_m ? y - (dy*-x)/dx : y + (dy*-x)/dx);
573                 x = 0;
574         }
575         
576         if (x_end > width)
577         {
578                 if (x > width) return;
579                 x_end = width-1;
580         }
581
582         // TODO: Avoid extra inner conditionals
583         do
584         {       
585                 if (x >= 0 && x < width && y >= 0 && y < height)
586                 {
587                         int64_t index = (transpose ? (y + x*target.w)*4 : (x + y*target.w)*4);
588                         target.pixels[index+0] = colour.r;
589                         target.pixels[index+1] = colour.g;
590                         target.pixels[index+2] = colour.b;
591                         target.pixels[index+3] = colour.a;
592                 }
593                 if (p < 0)
594                         p += two_dy;
595                 else
596                 {
597                         if (neg_m) --y; else ++y;
598                         p += two_dxdy;
599                 }
600         } while (++x <= x_end);
601 }
602
603
604 void ObjectRenderer::FloodFillOnCPU(int64_t x, int64_t y, const PixelBounds & bounds, const CPURenderTarget & target, const Colour & fill, const Colour & stroke)
605 {
606         // HACK to prevent overflooding (when the fill points for a path round to the pixel outside the boundary)
607         // (I totally just made that term up...)
608         Colour c = GetColour(target, x+1, y);
609         if (c == fill || c == stroke)
610                 return;
611         c = GetColour(target, x-1, y);
612         if (c == fill || c == stroke)
613                 return;
614         c = GetColour(target, x, y+1);
615         if (c == fill || c == stroke)
616                 return;
617         c = GetColour(target, x, y-1);
618         if (c == fill || c == stroke)
619                 return;
620                 
621         // The hack works but now we get underflooding, or, "droughts".
622         
623                 
624         queue<PixelPoint > traverse;
625         traverse.push(PixelPoint(x,y));
626         // now with 100% less stack overflows!
627         while (traverse.size() > 0)
628         {
629                 PixelPoint cur(traverse.front());
630                 traverse.pop();
631                 if (cur.first < 0 || cur.first < bounds.x || cur.first >= bounds.x+bounds.w || cur.first >= target.w ||
632                         cur.second < 0 || cur.second < bounds.y || cur.second >= bounds.y+bounds.h || cur.second >= target.h)
633                         continue;
634                 c = GetColour(target, cur.first, cur.second);
635                 if (c == fill || c == stroke)
636                         continue;
637
638                 SetColour(target, cur.first, cur.second, fill);
639                 
640                 //Debug("c is {%u,%u,%u,%u} fill is {%u,%u,%u,%u}, stroke is {%u,%u,%u,%u}",
641                 //      c.r,c.g,c.b,c.a, fill.r,fill.g,fill.b,fill.a, stroke.r,stroke.g,stroke.b,stroke.a);
642
643                 traverse.push(PixelPoint(cur.first+1, cur.second));
644                 traverse.push(PixelPoint(cur.first-1, cur.second));
645                 traverse.push(PixelPoint(cur.first, cur.second-1));
646                 traverse.push(PixelPoint(cur.first, cur.second+1)); 
647         }
648 }
649
650 ObjectRenderer::PixelBounds::PixelBounds(const Rect & bounds)
651 {
652         x = Int64(Double(bounds.x));
653         y = Int64(Double(bounds.y));
654         w = Int64(Double(bounds.w));
655         h = Int64(Double(bounds.h));
656 }
657
658 }

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