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

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