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

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