Python script for plotting data using Gnuplot
[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 using namespace IPDF;
7 using namespace std;
8
9 /**
10  * Constructs a view
11  * Allocates memory for ObjectRenderers
12  * @param document - The document to associate the View with
13  * @param bounds - Initial bounds of the View
14  * @param colour - Colour to use for rendering this view. TODO: Make sure this actually works, or just remove it
15  */
16 View::View(Document & document, Screen & screen, const Rect & bounds, const Colour & colour)
17         : m_use_gpu_transform(USE_GPU_TRANSFORM), m_use_gpu_rendering(USE_GPU_RENDERING), m_bounds_dirty(true), m_buffer_dirty(true), 
18                 m_render_dirty(true), m_document(document), m_screen(screen), m_cached_display(), m_bounds(bounds), m_colour(colour), m_bounds_ubo(), 
19                 m_objbounds_vbo(), m_object_renderers(NUMBER_OF_OBJECT_TYPES), m_cpu_rendering_pixels(NULL)
20 {
21         Debug("View Created - Bounds => {%s}", m_bounds.Str().c_str());
22
23         // Create ObjectRenderers - new's match delete's in View::~View
24         // Ok, look, this may seem disgusting, but go look at View::PrepareRender before you murder me
25         m_object_renderers[RECT_FILLED] = new RectFilledRenderer();
26         m_object_renderers[RECT_OUTLINE] = new RectOutlineRenderer();
27         m_object_renderers[CIRCLE_FILLED] = new CircleFilledRenderer();
28
29         // To add rendering for a new type of object;
30         // 1. Add enum to ObjectType in ipdf.h
31         // 2. Implement class inheriting from ObjectRenderer using that type in objectrenderer.h and objectrenderer.cpp
32         // 3. Add it here
33         // 4. Profit
34 }
35
36 /**
37  * Destroy a view
38  * Frees memory used by ObjectRenderers
39  */
40 View::~View()
41 {
42         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
43         {
44                 delete m_object_renderers[i];
45         }
46         m_object_renderers.clear();
47         delete [] m_cpu_rendering_pixels;
48 }
49
50 /**
51  * Translate the view
52  * @param x, y - Amount to translate
53  */
54 void View::Translate(Real x, Real y)
55 {
56         x *= m_bounds.w;
57         y *= m_bounds.h;
58         m_bounds.x += x;
59         m_bounds.y += y;
60         Debug("View Bounds => %s", m_bounds.Str().c_str());
61         if (!m_use_gpu_transform)
62                 m_buffer_dirty = true;
63         m_bounds_dirty = true;
64 }
65
66 /**
67  * Scale the View at a point
68  * @param x, y - Coordinates to scale at (eg: Mouse cursor position)
69  * @param scale_amount - Amount to scale by
70  */
71 void View::ScaleAroundPoint(Real x, Real y, Real scale_amount)
72 {
73         // x and y are coordinates in the window
74         // Convert to local coords.
75         x *= m_bounds.w;
76         y *= m_bounds.h;
77         x += m_bounds.x;
78         y += m_bounds.y;
79         
80         Real top = y - m_bounds.y;
81         Real left = x - m_bounds.x;
82         
83         top *= scale_amount;
84         left *= scale_amount;
85         
86         m_bounds.x = x - left;
87         m_bounds.y = y - top;
88         m_bounds.w *= scale_amount;
89         m_bounds.h *= scale_amount;
90         Debug("View Bounds => %s", m_bounds.Str().c_str());
91         if (!m_use_gpu_transform)
92                 m_buffer_dirty = true;
93         m_bounds_dirty = true;
94 }
95
96 /**
97  * Transform a point in the document to a point relative to the top left corner of the view
98  * This is the CPU coordinate transform code; used only if the CPU is doing coordinate transforms
99  * @param inp - Input Rect {x,y,w,h} in the document
100  * @returns output Rect {x,y,w,h} in the View
101  */
102 Rect View::TransformToViewCoords(const Rect& inp) const
103 {
104         Rect out;
105         out.x = (inp.x - m_bounds.x) / m_bounds.w;
106         out.y = (inp.y - m_bounds.y) / m_bounds.h;
107         out.w = inp.w / m_bounds.w;
108         out.h = inp.h / m_bounds.h;
109         return out;
110 }
111
112 /**
113  * Render the view
114  * Updates FrameBuffer if the document, object bounds, or view bounds have changed, then Blits it
115  * Otherwise just Blits the cached FrameBuffer
116  * @param width - Width of View to render
117  * @param height - Height of View to render
118  */
119 void View::Render(int width, int height)
120 {
121         // View dimensions have changed (ie: Window was resized)
122         int prev_width = m_cached_display.GetWidth();
123         int prev_height = m_cached_display.GetHeight();
124         if (width != prev_width || height != prev_height)
125         {
126                 m_cached_display.Create(width, height);
127                 m_bounds_dirty = true;
128         }
129
130         // View bounds have not changed; blit the FrameBuffer as it is
131         if (!m_bounds_dirty)
132         {
133                 m_cached_display.UnBind();
134                 m_cached_display.Blit();
135                 return;
136         }
137
138         // Bind FrameBuffer for rendering, and clear it
139
140
141         if (m_render_dirty) // document has changed
142                 PrepareRender();
143
144         if (m_buffer_dirty) // object bounds have changed
145                 UpdateObjBoundsVBO();
146
147         if (m_use_gpu_transform)
148         {
149                 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))};
150                 m_bounds_ubo.Upload(sizeof(float)*4, glbounds);
151         }
152         else
153         {
154                 GLfloat glbounds[] = {0.0f, 0.0f, 1.0f, 1.0f};
155                 m_bounds_ubo.Upload(sizeof(float)*4, glbounds);
156         }
157         m_bounds_dirty = false;
158
159         m_cached_display.Bind(); //NOTE: This is redundant; Clear already calls Bind
160         m_cached_display.Clear();
161
162
163         // Render using GPU
164         if (m_use_gpu_rendering) 
165         {
166                 if (m_colour.a < 1.0f)
167                 {
168                         glEnable(GL_BLEND);
169                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
170                 }
171                 m_objbounds_vbo.Bind();
172                 m_bounds_ubo.Bind();
173                 glEnableVertexAttribArray(0);
174                 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
175         
176                 for (unsigned i = 0; i < m_object_renderers.size(); ++i)
177                 {
178                         m_object_renderers[i]->RenderUsingGPU();
179                 }
180                 
181                 glDisableVertexAttribArray(0);
182                 if (m_colour.a < 1.0f)
183                 {
184                         glDisable(GL_BLEND);
185                 }
186         }
187         else // Rasterise on CPU then blit texture to GPU
188         {
189                 // Dynamically resize CPU rendering target pixels if needed
190                 if (m_cpu_rendering_pixels == NULL || width*height > prev_width*prev_height)
191                 {
192                         delete [] m_cpu_rendering_pixels;
193                         m_cpu_rendering_pixels = new uint8_t[width*height*4];
194                         if (m_cpu_rendering_pixels == NULL)
195                                 Fatal("Could not allocate %d*%d*4 = %d bytes for cpu rendered pixels", width, height, width*height*4);
196                 }
197                 // Clear CPU rendering pixels
198                 for (int i = 0; i < width*height*4; ++i)
199                         m_cpu_rendering_pixels[i] = 255;
200
201                 for (unsigned i = 0; i < m_object_renderers.size(); ++i)
202                 {
203                         m_object_renderers[i]->RenderUsingCPU(m_document.m_objects, *this, {m_cpu_rendering_pixels, width, height});
204                 }
205                 m_screen.RenderPixels(0,0,width, height, m_cpu_rendering_pixels); //TODO: Make this work :(
206                 // Debug for great victory (do something similar for GPU and compare?)
207                 ObjectRenderer::SaveBMP({m_cpu_rendering_pixels, width, height}, "cpu_rendering_last_frame.bmp");
208         }
209         m_cached_display.UnBind(); // resets render target to the screen
210         m_cached_display.Blit(); // blit FrameBuffer to screen
211 }
212
213 void View::UpdateObjBoundsVBO()
214 {
215         Debug("Called");
216         m_objbounds_vbo.Invalidate();
217         m_objbounds_vbo.SetType(GraphicsBuffer::BufferTypeVertex);
218         if (m_use_gpu_transform)
219         {
220                 m_objbounds_vbo.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
221         }
222         else
223         {
224                 m_objbounds_vbo.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
225         }
226         m_objbounds_vbo.Resize(m_document.ObjectCount()*sizeof(GPUObjBounds));
227
228         BufferBuilder<GPUObjBounds> obj_bounds_builder(m_objbounds_vbo.Map(false, true, true), m_objbounds_vbo.GetSize());
229
230         for (unsigned id = 0; id < m_document.ObjectCount(); ++id)
231         {
232                 Rect obj_bounds;
233                 if (m_use_gpu_transform)
234                 {
235                         obj_bounds = m_document.m_objects.bounds[id];
236                 }
237                 else
238                 {
239                         obj_bounds = TransformToViewCoords(m_document.m_objects.bounds[id]);
240                 }
241                 GPUObjBounds gpu_bounds = {
242                         (float)Float(obj_bounds.x),
243                         (float)Float(obj_bounds.y),
244                         (float)Float(obj_bounds.x + obj_bounds.w),
245                         (float)Float(obj_bounds.y + obj_bounds.h)
246                 };
247                 obj_bounds_builder.Add(gpu_bounds);
248
249         }
250         m_objbounds_vbo.UnMap();
251         m_buffer_dirty = false;
252 }
253 /**
254  * Prepare the document for rendering
255  * Will be called on View::Render if m_render_dirty is set
256  * (Called at least once, on the first Render)
257  */
258 void View::PrepareRender()
259 {
260         // Prepare bounds vbo
261         m_bounds_ubo.SetType(GraphicsBuffer::BufferTypeUniform);
262         m_bounds_ubo.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
263         
264         // Instead of having each ObjectRenderer go through the whole document
265         //  we initialise them, go through the document once adding to the appropriate Renderers
266         //  and then finalise them
267         // This will totally be efficient if we have like, a lot of distinct ObjectTypes. Which could totally happen. You never know.
268
269         // Prepare the buffers
270         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
271         {
272                 m_object_renderers[i]->PrepareBuffers(m_document.ObjectCount());
273         }
274
275         // Add objects from Document to buffers
276         for (unsigned id = 0; id < m_document.ObjectCount(); ++id)
277         {
278                 ObjectType type = m_document.m_objects.types[id];
279                 m_object_renderers.at(type)->AddObjectToBuffers(id); // Use at() in case the document is corrupt TODO: Better error handling?
280                 // (Also, Wow I just actually used std::vector::at())
281         }
282
283         // Finish the buffers
284         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
285         {
286                 m_object_renderers[i]->FinaliseBuffers();
287         }       
288         m_render_dirty = false;
289 }

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