The QuadTree is ~72% more amazing.
[ipdf/code.git] / src / view.cpp
1 #include "view.h"
2 #include "bufferbuilder.h"
3 #include "screen.h"
4 #include "gl_core44.h"
5
6 #ifndef CONTROLPANEL_DISABLED
7         #include "controlpanel.h"
8 #endif //CONTROLPANEL_DISABLED
9
10 using namespace IPDF;
11 using namespace std;
12
13 /**
14  * Constructs a view
15  * Allocates memory for ObjectRenderers
16  * @param document - The document to associate the View with
17  * @param bounds - Initial bounds of the View
18  * @param colour - Colour to use for rendering this view. TODO: Make sure this actually works, or just remove it
19  */
20 View::View(Document & document, Screen & screen, const Rect & bounds, const Colour & colour)
21         : m_use_gpu_transform(USE_GPU_TRANSFORM), m_use_gpu_rendering(USE_GPU_RENDERING), m_bounds_dirty(true), m_buffer_dirty(true), 
22                 m_render_dirty(true), m_document(document), m_screen(screen), m_cached_display(), m_bounds(bounds), m_colour(colour), m_bounds_ubo(), 
23                 m_objbounds_vbo(), m_object_renderers(NUMBER_OF_OBJECT_TYPES), m_cpu_rendering_pixels(NULL),
24                 m_perform_shading(USE_SHADING), m_show_bezier_bounds(false), m_show_bezier_type(false),
25                 m_show_fill_points(false), m_show_fill_bounds(false)
26 {
27         Debug("View Created - Bounds => {%s}", m_bounds.Str().c_str());
28
29         screen.SetView(this); // oh dear...
30
31         // Create ObjectRenderers - new's match delete's in View::~View
32         //TODO: Don't forget to put new renderers here or things will be segfaultastic
33         m_object_renderers[RECT_FILLED] = new RectFilledRenderer();
34         m_object_renderers[RECT_OUTLINE] = new RectOutlineRenderer();
35         m_object_renderers[CIRCLE_FILLED] = new CircleFilledRenderer();
36         m_object_renderers[BEZIER] = new BezierRenderer();
37         m_object_renderers[PATH] = new PathRenderer();
38
39         // To add rendering for a new type of object;
40         // 1. Add enum to ObjectType in ipdf.h
41         // 2. Implement class inheriting from ObjectRenderer using that type in objectrenderer.h and objectrenderer.cpp
42         // 3. Add it here
43         // 4. Profit
44
45
46 #ifndef QUADTREE_DISABLED
47         m_quadtree_max_depth = 1;
48         m_current_quadtree_node = document.GetQuadTree().root_id;
49 #endif
50 }
51
52 /**
53  * Destroy a view
54  * Frees memory used by ObjectRenderers
55  */
56 View::~View()
57 {
58         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
59         {
60                 delete m_object_renderers[i]; // delete's match new's in constructor
61         }
62         m_object_renderers.clear();
63         delete [] m_cpu_rendering_pixels;
64 }
65
66 /**
67  * Translate the view
68  * @param x, y - Amount to translate
69  */
70 void View::Translate(Real x, Real y)
71 {
72         x *= m_bounds.w;
73         y *= m_bounds.h;
74         m_bounds.x += x;
75         m_bounds.y += y;
76         //Debug("View Bounds => %s", m_bounds.Str().c_str());
77         if (!m_use_gpu_transform)
78                 m_buffer_dirty = true;
79         m_bounds_dirty = true;
80 }
81
82 /**
83  * Set View bounds
84  * @param bounds - New bounds
85  */
86 void View::SetBounds(const Rect & bounds)
87 {
88         m_bounds.x = bounds.x;
89         m_bounds.y = bounds.y;
90         m_bounds.w = bounds.w;
91         m_bounds.h = bounds.h;
92         if (!m_use_gpu_transform)
93                 m_buffer_dirty = true;
94         m_bounds_dirty = true;
95 }
96
97 /**
98  * Scale the View at a point
99  * @param x, y - Coordinates to scale at (eg: Mouse cursor position)
100  * @param scale_amount - Amount to scale by
101  */
102 void View::ScaleAroundPoint(Real x, Real y, Real scale_amount)
103 {
104         // x and y are coordinates in the window
105         // Convert to local coords.
106         x *= m_bounds.w;
107         y *= m_bounds.h;
108         x += m_bounds.x;
109         y += m_bounds.y;
110         
111         Real top = y - m_bounds.y;
112         Real left = x - m_bounds.x;
113         
114         top *= scale_amount;
115         left *= scale_amount;
116         
117         m_bounds.x = x - left;
118         m_bounds.y = y - top;
119         m_bounds.w *= scale_amount;
120         m_bounds.h *= scale_amount;
121         //Debug("Scale at {%s, %s} by %s View Bounds => %s", x.Str().c_str(), y.Str().c_str(), scale_amount.Str().c_str(), m_bounds.Str().c_str());
122         if (!m_use_gpu_transform)
123                 m_buffer_dirty = true;
124         m_bounds_dirty = true;
125 }
126
127 /**
128  * Transform a point in the document to a point relative to the top left corner of the view
129  * This is the CPU coordinate transform code; used only if the CPU is doing coordinate transforms
130  * @param inp - Input Rect {x,y,w,h} in the document
131  * @returns output Rect {x,y,w,h} in the View
132  */
133 Rect View::TransformToViewCoords(const Rect& inp) const
134 {
135         Rect out;
136         out.x = (inp.x - m_bounds.x) / m_bounds.w;
137         out.y = (inp.y - m_bounds.y) / m_bounds.h;
138         out.w = inp.w / m_bounds.w;
139         out.h = inp.h / m_bounds.h;
140         return out;
141 }
142
143 /**
144  * Render the view
145  * Updates FrameBuffer if the document, object bounds, or view bounds have changed, then Blits it
146  * Otherwise just Blits the cached FrameBuffer
147  * @param width - Width of View to render
148  * @param height - Height of View to render
149  */
150 void View::Render(int width, int height)
151 {
152         glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION,42,-1, "Beginning View::Render()");
153         // View dimensions have changed (ie: Window was resized)
154         int prev_width = m_cached_display.GetWidth();
155         int prev_height = m_cached_display.GetHeight();
156         if (width != prev_width || height != prev_height)
157         {
158                 m_cached_display.Create(width, height);
159                 m_bounds_dirty = true;
160         }
161
162         // View bounds have not changed; blit the FrameBuffer as it is
163         if (!m_bounds_dirty)
164         {
165                 m_cached_display.UnBind();
166                 m_cached_display.Blit();
167                 glPopDebugGroup();
168                 return;
169         }
170         m_cached_display.Bind(); //NOTE: This is redundant; Clear already calls Bind
171         m_cached_display.Clear();
172
173 #ifndef QUADTREE_DISABLED
174         if (m_bounds_dirty)
175         {
176                 if (false && (m_bounds.x > 1.0 || m_bounds.x < 0.0 || m_bounds.y > 1.0 || m_bounds.y < 0.0 || m_bounds.w > 1.0 || m_bounds.h > 1.0))
177                 {
178                         //TODO: Generate a new parent node.
179                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].parent != QUADTREE_EMPTY)
180                         {
181                                 m_bounds = TransformFromQuadChild(m_bounds, m_document.GetQuadTree().nodes[m_current_quadtree_node].child_type);
182                                 m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].parent;
183                         }
184                 }
185                 if (ContainedInQuadChild(m_bounds, QTC_TOP_LEFT))
186                 {
187                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].top_left == QUADTREE_EMPTY)
188                         {
189                                 // We want to reparent into a child node, but none exist. Get the document to create one.
190                                 m_document.GenQuadChild(m_current_quadtree_node, QTC_TOP_LEFT);
191                                 m_render_dirty = true;
192                         }
193                         m_bounds = TransformToQuadChild(m_bounds, QTC_TOP_LEFT);
194                         m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].top_left;
195                 }
196                 if (ContainedInQuadChild(m_bounds, QTC_TOP_RIGHT))
197                 {
198                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].top_right == QUADTREE_EMPTY)
199                         {
200                                 // We want to reparent into a child node, but none exist. Get the document to create one.
201                                 m_document.GenQuadChild(m_current_quadtree_node, QTC_TOP_RIGHT);
202                                 m_render_dirty = true;
203                         }
204                         m_bounds = TransformToQuadChild(m_bounds, QTC_TOP_RIGHT);
205                         m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].top_right;
206                 }
207                 if (ContainedInQuadChild(m_bounds, QTC_BOTTOM_LEFT))
208                 {
209                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_left == QUADTREE_EMPTY)
210                         {
211                                 // We want to reparent into a child node, but none exist. Get the document to create one.
212                                 m_document.GenQuadChild(m_current_quadtree_node, QTC_BOTTOM_LEFT);
213                                 m_render_dirty = true;
214                         }
215                         m_bounds = TransformToQuadChild(m_bounds, QTC_BOTTOM_LEFT);
216                         m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_left;
217                 }
218                 if (ContainedInQuadChild(m_bounds, QTC_BOTTOM_RIGHT))
219                 {
220                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_right == QUADTREE_EMPTY)
221                         {
222                                 // We want to reparent into a child node, but none exist. Get the document to create one.
223                                 m_document.GenQuadChild(m_current_quadtree_node, QTC_BOTTOM_RIGHT);
224                                 m_render_dirty = true;
225                         }
226                         m_bounds = TransformToQuadChild(m_bounds, QTC_BOTTOM_RIGHT);
227                         m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_right;
228                 }
229         }
230         m_screen.DebugFontPrintF("Current View QuadTree Node: %d (objs: %d -> %d)\n", m_current_quadtree_node, m_document.GetQuadTree().nodes[m_current_quadtree_node].object_begin,
231                                 m_document.GetQuadTree().nodes[m_current_quadtree_node].object_end);
232
233         Rect view_top_bounds = m_bounds;
234         QuadTreeIndex tmp = m_current_quadtree_node;
235         while (tmp != -1)
236         {
237                 view_top_bounds = TransformFromQuadChild(view_top_bounds, m_document.GetQuadTree().nodes[tmp].child_type);
238                 tmp = m_document.GetQuadTree().nodes[tmp].parent;
239         }
240         m_screen.DebugFontPrintF("Equivalent View Bounds: %s\n", view_top_bounds.Str().c_str());
241 #endif
242
243         if (!m_use_gpu_rendering)
244         {
245                 // Dynamically resize CPU rendering target pixels if needed
246                 if (m_cpu_rendering_pixels == NULL || width*height > prev_width*prev_height)
247                 {
248                         delete [] m_cpu_rendering_pixels;
249                         m_cpu_rendering_pixels = new uint8_t[width*height*4];
250                         if (m_cpu_rendering_pixels == NULL)
251                                 Fatal("Could not allocate %d*%d*4 = %d bytes for cpu rendered pixels", width, height, width*height*4);
252                 }
253                 // Clear CPU rendering pixels
254                 for (int i = 0; i < width*height*4; ++i)
255                         m_cpu_rendering_pixels[i] = 255;
256         }
257 #ifdef QUADTREE_DISABLED
258         RenderRange(width, height, 0, m_document.ObjectCount());
259 #else
260         RenderQuadtreeNode(width, height, m_current_quadtree_node, m_quadtree_max_depth);
261 #endif
262         if (!m_use_gpu_rendering)
263         {
264                 m_screen.RenderPixels(0,0,width, height, m_cpu_rendering_pixels); //TODO: Make this work :(
265                 // Debug for great victory (do something similar for GPU and compare?)
266                 //ObjectRenderer::SaveBMP({m_cpu_rendering_pixels, width, height}, "cpu_rendering_last_frame.bmp");
267         }
268         m_cached_display.UnBind(); // resets render target to the screen
269         m_cached_display.Blit(); // blit FrameBuffer to screen
270         m_buffer_dirty = false;
271         glPopDebugGroup();
272         
273 #ifndef CONTROLPANEL_DISABLED
274         ControlPanel::Update();
275 #endif //CONTROLPANEL_DISABLED
276         //Debug("Completed Render");
277         
278 }
279
280 #ifndef QUADTREE_DISABLED
281 void View::RenderQuadtreeNode(int width, int height, QuadTreeIndex node, int remaining_depth)
282 {
283         Rect old_bounds = m_bounds;
284         if (node == QUADTREE_EMPTY) return;
285         if (!remaining_depth) return;
286         //Debug("Rendering QT node %d, (objs: %d -- %d)\n", node, m_document.GetQuadTree().nodes[node].object_begin, m_document.GetQuadTree().nodes[node].object_end);
287         m_bounds_dirty = true;
288         RenderRange(width, height, m_document.GetQuadTree().nodes[node].object_begin, m_document.GetQuadTree().nodes[node].object_end);
289
290         m_bounds = TransformToQuadChild(old_bounds, QTC_TOP_LEFT);
291         m_bounds_dirty = true;
292         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].top_left, remaining_depth-1);
293         m_bounds = TransformToQuadChild(old_bounds, QTC_TOP_RIGHT);
294         m_bounds_dirty = true;
295         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].top_right, remaining_depth-1);
296         m_bounds = TransformToQuadChild(old_bounds, QTC_BOTTOM_LEFT);
297         m_bounds_dirty = true;
298         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].bottom_left, remaining_depth-1);
299         m_bounds = TransformToQuadChild(old_bounds, QTC_BOTTOM_RIGHT);
300         m_bounds_dirty = true;
301         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].bottom_right, remaining_depth-1);
302         m_bounds = old_bounds;
303         m_bounds_dirty = true;
304 }
305 #endif
306
307 void View::RenderRange(int width, int height, unsigned first_obj, unsigned last_obj)
308 {
309         glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 43, -1, "View::RenderRange()");
310         if (m_render_dirty) // document has changed
311                 PrepareRender();
312
313         if (m_buffer_dirty || m_bounds_dirty) // object bounds have changed
314                 UpdateObjBoundsVBO(first_obj, last_obj);
315
316         if (m_use_gpu_transform)
317         {
318                 GLfloat glbounds[] = {static_cast<GLfloat>(Float(m_bounds.x)), static_cast<GLfloat>(Float(m_bounds.y)), static_cast<GLfloat>(Float(m_bounds.w)), static_cast<GLfloat>(Float(m_bounds.h)),
319                                         0.0, 0.0, static_cast<GLfloat>(width), static_cast<GLfloat>(height)};
320                 m_bounds_ubo.Upload(sizeof(float)*8, glbounds);
321         }
322         else
323         {
324                 GLfloat glbounds[] = {0.0f, 0.0f, 1.0f, 1.0f,
325                                         0.0f, 0.0f, float(width), float(height)};
326                 m_bounds_ubo.Upload(sizeof(float)*8, glbounds);
327         }
328         m_bounds_dirty = false;
329
330
331         // Render using GPU
332         if (m_use_gpu_rendering) 
333         {
334                 if (m_colour.a < 1.0f)
335                 {
336                         glEnable(GL_BLEND);
337                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
338                 }
339                 m_objbounds_vbo.Bind();
340                 m_bounds_ubo.Bind();
341                 glEnableVertexAttribArray(0);
342                 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
343         
344                 for (unsigned i = 0; i < m_object_renderers.size(); ++i)
345                 {
346                         m_object_renderers[i]->RenderUsingGPU(first_obj, last_obj);
347                 }
348                 
349                 glDisableVertexAttribArray(0);
350                 if (m_colour.a < 1.0f)
351                 {
352                         glDisable(GL_BLEND);
353                 }
354         }
355         else // Rasterise on CPU then blit texture to GPU
356         {
357
358                 for (unsigned i = 0; i < m_object_renderers.size(); ++i)
359                 {
360                         m_object_renderers[i]->RenderUsingCPU(m_document.m_objects, *this, {m_cpu_rendering_pixels, width, height}, first_obj, last_obj);
361                 }
362         }
363         glPopDebugGroup();
364 }
365
366 void View::UpdateObjBoundsVBO(unsigned first_obj, unsigned last_obj)
367 {
368         //m_objbounds_vbo.Invalidate();
369         m_objbounds_vbo.SetType(GraphicsBuffer::BufferTypeVertex);
370         m_objbounds_vbo.SetName("Object Bounds VBO");
371         if (m_use_gpu_transform)
372         {
373                 m_objbounds_vbo.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
374         }
375         else
376         {
377                 m_objbounds_vbo.SetUsage(GraphicsBuffer::BufferUsageDynamicCopy);
378         }
379         m_objbounds_vbo.Resize(m_document.ObjectCount()*sizeof(GPUObjBounds));
380
381         BufferBuilder<GPUObjBounds> obj_bounds_builder(m_objbounds_vbo.MapRange(first_obj*sizeof(GPUObjBounds), (last_obj-first_obj)*sizeof(GPUObjBounds), false, true, true), m_objbounds_vbo.GetSize());
382
383         for (unsigned id = first_obj; id < last_obj; ++id)
384         {
385                 Rect obj_bounds;
386                 if (m_use_gpu_transform)
387                 {
388                         obj_bounds = m_document.m_objects.bounds[id];
389                 }
390                 else
391                 {
392                         obj_bounds = TransformToViewCoords(m_document.m_objects.bounds[id]);
393                 }
394                 GPUObjBounds gpu_bounds = {
395                         (float)Float(obj_bounds.x),
396                         (float)Float(obj_bounds.y),
397                         (float)Float(obj_bounds.x + obj_bounds.w),
398                         (float)Float(obj_bounds.y + obj_bounds.h)
399                 };
400                 obj_bounds_builder.Add(gpu_bounds);
401
402         }
403         m_objbounds_vbo.UnMap();
404 }
405 /**
406  * Prepare the document for rendering
407  * Will be called on View::Render if m_render_dirty is set
408  * (Called at least once, on the first Render)
409  */
410 void View::PrepareRender()
411 {
412         Debug("Recreate buffers with %u objects", m_document.ObjectCount());
413         // Prepare bounds vbo
414         m_bounds_ubo.Invalidate();
415         m_bounds_ubo.SetType(GraphicsBuffer::BufferTypeUniform);
416         m_bounds_ubo.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
417         m_bounds_ubo.SetName("m_bounds_ubo: Screen bounds.");
418         
419         // Instead of having each ObjectRenderer go through the whole document
420         //  we initialise them, go through the document once adding to the appropriate Renderers
421         //  and then finalise them
422         // This will totally be efficient if we have like, a lot of distinct ObjectTypes. Which could totally happen. You never know.
423
424         // Prepare the buffers
425         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
426         {
427                 m_object_renderers[i]->PrepareBuffers(m_document.ObjectCount());
428         }
429
430         // Add objects from Document to buffers
431         for (unsigned id = 0; id < m_document.ObjectCount(); ++id)
432         {
433                 ObjectType type = m_document.m_objects.types[id];
434                 m_object_renderers.at(type)->AddObjectToBuffers(id); // Use at() in case the document is corrupt TODO: Better error handling?
435                 // (Also, Wow I just actually used std::vector::at())
436                 // (Also, I just managed to make it throw an exception because I'm a moron)
437                 //Debug("Object of type %d", type);
438         }
439
440         // Finish the buffers
441         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
442         {
443                 m_object_renderers[i]->FinaliseBuffers();
444         }
445         dynamic_cast<BezierRenderer*>(m_object_renderers[BEZIER])->PrepareBezierGPUBuffer(m_document.m_objects);
446         m_render_dirty = false;
447 }

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