My eyes, they burn! Also runs faster, slightly less buggy.
[ipdf/code.git] / src / document.cpp
1 #include "document.h"
2 #include "bezier.h"
3 #include "profiler.h"
4 #include <cstdio>
5 #include <fstream>
6
7 #include "../contrib/pugixml-1.4/src/pugixml.cpp"
8 #include "transformationtype.h"
9
10 #include "stb_truetype.h"
11
12 using namespace IPDF;
13 using namespace std;
14
15 //TODO: Make this work for variable sized Reals
16
17 // Loads an std::vector<T> of size num_elements from a file.
18 template<typename T>
19 static void LoadStructVector(FILE *src_file, size_t num_elems, std::vector<T>& dest)
20 {
21         size_t structsread = 0;
22         dest.resize(num_elems);
23         structsread = fread(dest.data(), sizeof(T), num_elems, src_file);
24         if (structsread != num_elems)
25                 Fatal("Only read %u structs (expected %u)!", structsread, num_elems);
26 }
27
28 // Saves an std::vector<T> to a file. Size must be saves separately.
29 template<typename T>
30 static void SaveStructVector(FILE *dst_file, std::vector<T>& src)
31 {
32         size_t written = 0;
33         written = fwrite(src.data(), sizeof(T), src.size(), dst_file);
34         if (written != src.size())
35                 Fatal("Only wrote %u structs (expected %u)!", written, src.size());
36 }
37
38 static void WriteChunkHeader(FILE *dst_file, DocChunkTypes type, uint32_t size)
39 {
40         size_t written = 0;
41         written = fwrite(&type, sizeof(type), 1, dst_file);
42         if (written != 1)
43                 Fatal("Could not write Chunk header! (ID)");
44         written = fwrite(&size, sizeof(size), 1, dst_file);
45         if (written != 1)
46                 Fatal("Could not write Chunk header (size)!");
47 }
48
49 static bool ReadChunkHeader(FILE *src_file, DocChunkTypes& type, uint32_t& size)
50 {
51         if (fread(&type, sizeof(DocChunkTypes), 1, src_file) != 1)
52                 return false;
53         if (fread(&size, sizeof(uint32_t), 1, src_file) != 1)
54                 return false;
55         return true;
56 }
57
58 void Document::Save(const string & filename)
59 {
60         Debug("Saving document to file \"%s\"...", filename.c_str());
61         FILE * file = fopen(filename.c_str(), "w");
62         if (file == NULL)
63                 Fatal("Couldn't open file \"%s\" - %s", filename.c_str(), strerror(errno));
64
65         size_t written;
66         Debug("Number of objects (%u)...", ObjectCount());
67         WriteChunkHeader(file, CT_NUMOBJS, sizeof(m_count));
68         written = fwrite(&m_count, sizeof(m_count), 1, file);
69         if (written != 1)
70                 Fatal("Failed to write number of objects!");
71
72         Debug("Object types...");
73         WriteChunkHeader(file, CT_OBJTYPES, m_objects.types.size() * sizeof(ObjectType));
74         SaveStructVector<ObjectType>(file, m_objects.types);
75
76         Debug("Object bounds...");
77         WriteChunkHeader(file, CT_OBJBOUNDS, m_objects.bounds.size() * sizeof(Rect));
78         SaveStructVector<Rect>(file, m_objects.bounds);
79
80         Debug("Object data indices...");
81         WriteChunkHeader(file, CT_OBJINDICES, m_objects.data_indices.size() * sizeof(unsigned));
82         SaveStructVector<unsigned>(file, m_objects.data_indices);
83         
84         Debug("Bezier data...");
85         WriteChunkHeader(file, CT_OBJBEZIERS, m_objects.beziers.size() * sizeof(uint8_t));
86         SaveStructVector<Bezier>(file, m_objects.beziers);
87
88         int err = fclose(file);
89         if (err != 0)
90                 Fatal("Failed to close file \"%s\" - %s", filename.c_str(), strerror(err));
91
92         Debug("Successfully saved %u objects to \"%s\"", ObjectCount(), filename.c_str());
93 }
94
95 #ifndef QUADTREE_DISABLED
96
97 void Document::GenBaseQuadtree()
98 {
99         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QTC_UNKNOWN, 0, ObjectCount(), -1});
100         m_quadtree.root_id = 0;
101 }
102
103 int Document::ClipObjectToQuadChild(int object_id, QuadTreeNodeChildren type)
104 {
105         PROFILE_SCOPE("Document::ClipObjectToQuadChild");
106         switch (m_objects.types[object_id])
107         {
108         case RECT_FILLED:
109         case RECT_OUTLINE:
110         case PATH:
111                 {
112                 Rect obj_bounds = TransformToQuadChild(m_objects.bounds[object_id], type);
113                 if (obj_bounds.x < 0)
114                 {
115                         obj_bounds.w += obj_bounds.x;
116                         obj_bounds.x = 0;
117                 }
118                 if (obj_bounds.y < 0)
119                 {
120                         obj_bounds.h += obj_bounds.y;
121                         obj_bounds.y = 0;
122                 }
123                 if (obj_bounds.x + obj_bounds.w > 1)
124                 {
125                         obj_bounds.w += (1 - (obj_bounds.x + obj_bounds.w));
126                 }
127                 if (obj_bounds.y + obj_bounds.h > 1)
128                 {
129                         obj_bounds.h += (1 - (obj_bounds.y + obj_bounds.h));
130                 }
131                 m_objects.bounds.push_back(obj_bounds);
132                 m_objects.types.push_back(m_objects.types[object_id]);
133                 m_objects.data_indices.push_back(m_objects.data_indices[object_id]);
134                 return 1;
135                 }
136         case BEZIER:
137                 {
138                 // If we're entirely within the quadtree node, no clipping need occur.
139                 if (ContainedInQuadChild(m_objects.bounds[object_id], type))
140                 {
141                         m_objects.bounds.push_back(TransformToQuadChild(m_objects.bounds[object_id], type));
142                         m_objects.types.push_back(m_objects.types[object_id]);
143                         m_objects.data_indices.push_back(m_objects.data_indices[object_id]);
144                         return 1;
145                 }
146                 Rect clip_bezier_bounds = TransformRectCoordinates(m_objects.bounds[object_id], TransformFromQuadChild(Rect{0,0,1,1}, type)); 
147                 std::vector<Bezier> new_curves = m_objects.beziers[m_objects.data_indices[object_id]].ClipToRectangle(clip_bezier_bounds);
148                 for (size_t i = 0; i < new_curves.size(); ++i)
149                 {
150                         Rect new_bounds = TransformToQuadChild(m_objects.bounds[object_id], type);
151                         Bezier new_curve_data = new_curves[i].ToAbsolute(TransformToQuadChild(m_objects.bounds[object_id],type));
152                         new_bounds = new_curve_data.SolveBounds();
153                         Debug("New bounds: %s", new_bounds.Str().c_str());
154                         new_curve_data = new_curve_data.ToRelative(new_bounds);
155                         unsigned index = AddBezierData(new_curve_data);
156                         m_objects.bounds.push_back(new_bounds);
157                         m_objects.types.push_back(BEZIER);
158                         m_objects.data_indices.push_back(index);
159                 }
160                 return new_curves.size();
161                 }
162         default:
163                 Debug("Adding %s -> %s", m_objects.bounds[object_id].Str().c_str(), TransformToQuadChild(m_objects.bounds[object_id], type).Str().c_str());
164                 m_objects.bounds.push_back(TransformToQuadChild(m_objects.bounds[object_id], type));
165                 m_objects.types.push_back(m_objects.types[object_id]);
166                 m_objects.data_indices.push_back(m_objects.data_indices[object_id]);
167                 return 1;
168         }
169         return 0;
170 }
171 QuadTreeIndex Document::GenQuadChild(QuadTreeIndex parent, QuadTreeNodeChildren type)
172 {
173         PROFILE_SCOPE("Document::GenQuadChild()");
174         QuadTreeIndex new_index = m_quadtree.nodes.size();
175         Debug("-------------- Generating Quadtree Node %d (parent %d, type %d) ----------------------", new_index, parent, type);
176         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, parent, type, 0, 0, -1, true});
177
178         m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
179         for (QuadTreeIndex overlay = parent; overlay != -1; overlay = m_quadtree.nodes[overlay].next_overlay)
180         {
181                 for (unsigned i = m_quadtree.nodes[overlay].object_begin; i < m_quadtree.nodes[overlay].object_end; ++i)
182                 {
183                         if (IntersectsQuadChild(m_objects.bounds[i], type))
184                         {
185                                 m_count += ClipObjectToQuadChild(i, type);
186                         }
187                 }
188         }
189         m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
190         // No objects are dirty.
191         m_quadtree.nodes[new_index].object_dirty = m_objects.bounds.size();
192         switch (type)
193         {
194                 case QTC_TOP_LEFT:
195                         m_quadtree.nodes[parent].top_left = new_index;
196                         break;
197                 case QTC_TOP_RIGHT:
198                         m_quadtree.nodes[parent].top_right = new_index;
199                         break;
200                 case QTC_BOTTOM_LEFT:
201                         m_quadtree.nodes[parent].bottom_left = new_index;
202                         break;
203                 case QTC_BOTTOM_RIGHT:
204                         m_quadtree.nodes[parent].bottom_right = new_index;
205                         break;
206                 default:
207                         Fatal("Tried to add a QuadTree child of invalid type!");
208         }
209         m_document_dirty = true;
210         return new_index;
211 }
212
213 void Document::OverlayQuadChildren(QuadTreeIndex orig_parent, QuadTreeIndex parent, QuadTreeNodeChildren type)
214 {
215         PROFILE_SCOPE("Document::OverlayQuadChildren()");
216         QuadTreeIndex new_index = m_quadtree.nodes.size();
217         Debug("-------------- Generating Quadtree Node %d (orig %d parent %d, type %d) ----------------------", new_index, orig_parent, parent, type);
218         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, orig_parent, type, 0, 0, -1, true});
219
220         m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
221         for (unsigned i = m_quadtree.nodes[parent].object_dirty; i < m_quadtree.nodes[parent].object_end; ++i)
222         {
223                 if (IntersectsQuadChild(m_objects.bounds[i], type))
224                 {
225                         m_count += ClipObjectToQuadChild(i, type);
226                 }
227         }
228         m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
229         QuadTreeIndex orig_node = -1;
230         switch (type)
231         {
232                 case QTC_TOP_LEFT:
233                         orig_node = m_quadtree.nodes[orig_parent].top_left;
234                         break;
235                 case QTC_TOP_RIGHT:
236                         orig_node = m_quadtree.nodes[orig_parent].top_right;
237                         break;
238                 case QTC_BOTTOM_LEFT:
239                         orig_node = m_quadtree.nodes[orig_parent].bottom_left;
240                         break;
241                 case QTC_BOTTOM_RIGHT:
242                         orig_node = m_quadtree.nodes[orig_parent].bottom_right;
243                         break;
244                 default:
245                         Fatal("Tried to overlay a QuadTree child of invalid type!");
246         }
247         if (orig_node == -1)
248                 Fatal("Tried to overlay a QuadTree child that didn't exist!");
249
250         // Add us to the node's overlay linked list.
251         QuadTreeIndex prev_overlay = orig_node;
252         while (m_quadtree.nodes[prev_overlay].next_overlay != -1) prev_overlay = m_quadtree.nodes[prev_overlay].next_overlay;
253         Debug("- Original node %d, Previous overlay %d, new overlay %d", orig_node, prev_overlay, new_index);
254         m_quadtree.nodes[prev_overlay].next_overlay = new_index;
255
256         // Recurse into any extant children.
257         if (m_quadtree.nodes[orig_node].top_left != -1)
258                 OverlayQuadChildren(orig_node, new_index, QTC_TOP_LEFT);
259         if (m_quadtree.nodes[orig_node].top_right != -1)
260                 OverlayQuadChildren(orig_node, new_index, QTC_TOP_RIGHT);
261         if (m_quadtree.nodes[orig_node].bottom_left != -1)
262                 OverlayQuadChildren(orig_node, new_index, QTC_BOTTOM_LEFT);
263         if (m_quadtree.nodes[orig_node].bottom_right != -1)
264                 OverlayQuadChildren(orig_node, new_index, QTC_BOTTOM_RIGHT);
265
266         m_quadtree.nodes[new_index].object_dirty = m_quadtree.nodes[new_index].object_end;
267         m_quadtree.nodes[new_index].next_overlay = -1;
268         m_document_dirty = true;
269 }
270
271 void Document::OverlayQuadParent(QuadTreeIndex orig_child, QuadTreeIndex child, QuadTreeNodeChildren type)
272 {
273         PROFILE_SCOPE("Document::OverlayQuadParent()");
274         QuadTreeIndex new_index = m_quadtree.nodes.size();
275         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, -1, QTC_UNKNOWN, 0, 0, -1, true});
276
277         m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
278         m_quadtree.nodes[new_index].object_dirty = m_objects.bounds.size();
279         for (QuadTreeIndex overlay = child; overlay != -1; overlay = m_quadtree.nodes[overlay].next_overlay)
280         {
281                 for (unsigned i = m_quadtree.nodes[overlay].object_begin; i < m_quadtree.nodes[overlay].object_end; ++i)
282                 {
283                         Rect new_bounds = TransformFromQuadChild(m_objects.bounds[i], type);
284                         // If the object is too small to be seen, discard it.
285                         if (!new_bounds.w || !new_bounds.h) continue;
286                         m_objects.bounds.push_back(new_bounds);
287                         m_objects.types.push_back(m_objects.types[i]);
288                         m_objects.data_indices.push_back(m_objects.data_indices[i]);
289                         m_count++;
290                 }
291         }
292         m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
293         QuadTreeIndex orig_node = m_quadtree.nodes[orig_child].parent;
294         if (orig_node == -1)
295                 Fatal("Tried to overlay a QuadTree child that didn't exist!");
296
297         // Add us to the node's overlay linked list.
298         QuadTreeIndex prev_overlay = orig_node;
299         while (m_quadtree.nodes[prev_overlay].next_overlay != -1) prev_overlay = m_quadtree.nodes[prev_overlay].next_overlay;
300         m_quadtree.nodes[prev_overlay].next_overlay = new_index;
301         Debug("OverlayQuadParent(%d, %d, %d) = %d", orig_child, child, type, new_index);
302
303         // Recurse into any extant parent.
304         if (m_quadtree.nodes[orig_node].parent != -1)
305                 OverlayQuadParent(orig_node, new_index, m_quadtree.nodes[orig_node].child_type);
306
307         m_quadtree.nodes[new_index].object_dirty = m_quadtree.nodes[new_index].object_end;
308         m_quadtree.nodes[new_index].next_overlay = -1;
309         m_document_dirty = true;
310 }
311
312 void Document::PropagateQuadChanges(QuadTreeIndex node)
313 {
314         for(QuadTreeIndex overlay = node; overlay != -1; overlay = m_quadtree.nodes[overlay].next_overlay)
315         {
316                 // We don't care about clean overlays.
317                 if (m_quadtree.nodes[overlay].object_dirty == m_quadtree.nodes[overlay].object_end) continue;
318                 // Recurse into our parent, should we have any.
319                 if (m_quadtree.nodes[node].parent != -1)
320                         OverlayQuadParent(node, overlay, m_quadtree.nodes[node].child_type);
321                 // Recurse into any extant children.
322                 if (m_quadtree.nodes[node].top_left != -1)
323                         OverlayQuadChildren(node, overlay, QTC_TOP_LEFT);
324                 if (m_quadtree.nodes[node].top_right != -1)
325                         OverlayQuadChildren(node, overlay, QTC_TOP_RIGHT);
326                 if (m_quadtree.nodes[node].bottom_left != -1)
327                         OverlayQuadChildren(node, overlay, QTC_BOTTOM_LEFT);
328                 if (m_quadtree.nodes[node].bottom_right != -1)
329                         OverlayQuadChildren(node, overlay, QTC_BOTTOM_RIGHT);
330
331                 m_quadtree.nodes[overlay].object_dirty = m_quadtree.nodes[overlay].object_end;
332         }
333 }
334
335 // Reparent a quadtree node, making it the "type" child of a new node.
336 QuadTreeIndex Document::GenQuadParent(QuadTreeIndex child, QuadTreeNodeChildren type)
337 {
338         QuadTreeIndex new_index = m_quadtree.nodes.size();
339         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, -1, QTC_UNKNOWN, 0, 0, -1, true});
340
341         m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
342         for (QuadTreeIndex overlay = child; overlay != -1; overlay = m_quadtree.nodes[overlay].next_overlay)
343         {
344                 for (unsigned i = m_quadtree.nodes[overlay].object_begin; i < m_quadtree.nodes[overlay].object_end; ++i)
345                 {
346                         Rect new_bounds = TransformFromQuadChild(m_objects.bounds[i], type);
347                         // If the object is too small to be seen, discard it.
348                         if (!new_bounds.w || !new_bounds.h) continue;
349                         m_objects.bounds.push_back(new_bounds);
350                         m_objects.types.push_back(m_objects.types[i]);
351                         m_objects.data_indices.push_back(m_objects.data_indices[i]);
352                         m_count++;
353                 }
354         }
355         m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
356         m_quadtree.nodes[new_index].object_dirty = m_objects.bounds.size();
357         switch (type)
358         {
359                 case QTC_TOP_LEFT:
360                         m_quadtree.nodes[new_index].top_left = child;
361                         break;
362                 case QTC_TOP_RIGHT:
363                         m_quadtree.nodes[new_index].top_right = child;
364                         break;
365                 case QTC_BOTTOM_LEFT:
366                         m_quadtree.nodes[new_index].bottom_left = child;
367                         break;
368                 case QTC_BOTTOM_RIGHT:
369                         m_quadtree.nodes[new_index].bottom_right = child;
370                         break;
371                 default:
372                         Fatal("Tried to add a QuadTree child of invalid type!");
373         }
374         return new_index;
375         m_document_dirty = true;
376 }
377
378 #endif
379
380 void Document::Load(const string & filename)
381 {
382         m_objects.bounds.clear();
383         m_count = 0;
384         if (filename == "")
385         {
386                 Debug("Loaded empty document.");
387                 return;
388         }
389         Debug("Loading document from file \"%s\"", filename.c_str());
390         FILE * file = fopen(filename.c_str(), "r");
391         if (file == NULL)
392                 Fatal("Couldn't open file \"%s\"", filename.c_str(), strerror(errno));
393
394         size_t read;
395
396         DocChunkTypes chunk_type;
397         uint32_t chunk_size;
398         while (ReadChunkHeader(file, chunk_type, chunk_size))
399         {
400                 switch(chunk_type)
401                 {
402                 case CT_NUMOBJS:
403                         read = fread(&m_count, sizeof(m_count), 1, file);
404                         if (read != 1)
405                                 Fatal("Failed to read number of objects!");
406                         Debug("Number of objects: %u", ObjectCount());
407                         break;
408                 case CT_OBJTYPES:
409                         Debug("Object types...");
410                         LoadStructVector<ObjectType>(file, chunk_size/sizeof(ObjectType), m_objects.types);
411                         break;
412                 case CT_OBJBOUNDS:
413                         Debug("Object bounds...");
414                         LoadStructVector<Rect>(file, chunk_size/sizeof(Rect), m_objects.bounds);
415                         break;
416                 case CT_OBJINDICES:
417                         Debug("Object data indices...");
418                         LoadStructVector<unsigned>(file, chunk_size/sizeof(unsigned), m_objects.data_indices);
419                         break;
420                 case CT_OBJBEZIERS:
421                         Debug("Bezier data...");
422                         LoadStructVector<Bezier>(file, chunk_size/sizeof(Bezier), m_objects.beziers);
423                         break;
424                         
425                 case CT_OBJPATHS:
426                         Debug("Path data...");
427                         Warn("Not handled because lazy");
428                         break;
429                 }
430         }
431         Debug("Successfully loaded %u objects from \"%s\"", ObjectCount(), filename.c_str());
432 #ifndef QUADTREE_DISABLED
433         if (m_quadtree.root_id == QUADTREE_EMPTY)
434         {
435                 GenBaseQuadtree();
436         }
437 #endif
438 }
439
440 unsigned Document::AddPath(unsigned start_index, unsigned end_index, const Colour & fill, const Colour & stroke)
441 {
442         Path path(m_objects, start_index, end_index, fill, stroke);
443         unsigned data_index = AddPathData(path);
444         Rect bounds = path.SolveBounds(m_objects);
445         unsigned result = Add(PATH, bounds,data_index);
446         m_objects.paths[data_index].m_index = result;
447         //Debug("Added path %u -> %u (%u objects) colour {%u,%u,%u,%u}, stroke {%u,%u,%u,%u}", start_index, end_index, (end_index - start_index), fill.r, fill.g, fill.b, fill.a, stroke.r, stroke.g, stroke.b, stroke.a);
448         return result;
449 }
450
451 /**
452  * Add a Bezier using Absolute coords
453  */
454 unsigned Document::AddBezier(const Bezier & bezier)
455 {
456         Rect bounds = bezier.SolveBounds();
457         Bezier data = bezier.ToRelative(bounds); // Relative
458         if (data.ToAbsolute(bounds) != bezier)
459         {
460                 Warn("%s != %s", data.ToAbsolute(bounds).Str().c_str(),
461                         bezier.Str().c_str());
462                 Warn("ToAbsolute on ToRelative does not give original Bezier");
463         }
464         unsigned index = AddBezierData(data);
465         return Add(BEZIER, bounds, index);
466 }
467 // Adds an object to the Document, clipping it to m_clip_rect.
468 // Helper function called by Document::Add()
469 int Document::AddClip(ObjectType type, const Rect& bounds, unsigned data_index, const Rect& clip_rect)
470 {
471         PROFILE_SCOPE("Document::AddAndClip");
472         switch (type)
473         {
474         case RECT_FILLED:
475         case RECT_OUTLINE:
476         case PATH:
477                 {
478                 Rect obj_bounds = clip_rect.Clip(bounds);
479                 m_objects.bounds.push_back(obj_bounds);
480                 m_objects.types.push_back(type);
481                 m_objects.data_indices.push_back(data_index);
482                 return 1;
483                 }
484         case BEZIER:
485                 {
486                 // If we're entirely within the clipping rect, no clipping need occur.
487                 if (clip_rect.Contains(bounds))
488                 {
489                         m_objects.bounds.push_back(bounds);
490                         m_objects.types.push_back(type);
491                         m_objects.data_indices.push_back(data_index);
492                         return 1;
493                 }
494                 Rect clip_bezier_bounds = TransformRectCoordinates(bounds, clip_rect); 
495                 std::vector<Bezier> new_curves = m_objects.beziers[data_index].ClipToRectangle(clip_bezier_bounds);
496                 for (size_t i = 0; i < new_curves.size(); ++i)
497                 {
498                         Bezier new_curve_data = new_curves[i].ToAbsolute(bounds);
499                         Rect new_bounds = new_curve_data.SolveBounds();
500                         new_curve_data = new_curve_data.ToRelative(new_bounds);
501                         unsigned index = AddBezierData(new_curve_data);
502                         m_objects.bounds.push_back(new_bounds);
503                         m_objects.types.push_back(BEZIER);
504                         m_objects.data_indices.push_back(index);
505                 }
506                 return new_curves.size();
507                 }
508         default:
509                 m_objects.bounds.push_back(bounds);
510                 m_objects.types.push_back(type);
511                 m_objects.data_indices.push_back(data_index);
512                 return 1;
513         }
514         return 0;
515 }
516
517 unsigned Document::Add(ObjectType type, const Rect & bounds, unsigned data_index, QuadTreeIndex qti)
518 {
519         PROFILE_SCOPE("Document::Add");
520         Rect new_bounds = bounds;
521 #ifndef QUADTREE_DISABLED
522         int num_added = 1;
523         if (qti == -1) qti = m_current_insert_node;
524         if (qti != -1)
525         {
526                 // Move the object to the quadtree node it should be in.
527                 m_quadtree.GetCanonicalCoords(qti, new_bounds.x, new_bounds.y, this);
528                 Rect cliprect = Rect(0,0,1,1);
529                 num_added = AddClip(type, new_bounds, data_index, cliprect);
530         }
531         else
532 #endif
533         {
534                 m_objects.types.push_back(type);
535                 m_objects.bounds.push_back(new_bounds);
536                 m_objects.data_indices.push_back(data_index);
537         }
538         m_document_dirty = true;
539 #ifndef QUADTREE_DISABLED
540         if (qti != -1)
541         {
542                 QuadTreeIndex new_qti = qti;
543                 while (m_quadtree.nodes[new_qti].next_overlay != -1)
544                 {
545                         if (m_count == m_quadtree.nodes[new_qti].object_end+1)
546                         {
547                                 m_quadtree.nodes[new_qti].object_end += num_added;
548                                 m_quadtree.nodes[new_qti].render_dirty = true;
549                                 new_qti = -1;
550                                 break;
551                         }
552                         new_qti = m_quadtree.nodes[new_qti].next_overlay;
553                 }
554                 if (new_qti != -1)
555                 {
556                         QuadTreeIndex overlay = m_quadtree.nodes.size();
557                         Debug("Adding new overlay, nqti = %d, overlay = %d", new_qti, overlay);
558                         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, -1, QTC_UNKNOWN, 0, 0, -1});
559                         m_quadtree.nodes[overlay].object_begin = m_count;
560                         // All objects are dirty.
561                         m_quadtree.nodes[overlay].object_dirty = m_count;
562                         m_quadtree.nodes[overlay].object_end = m_count+num_added;
563                         m_quadtree.nodes[overlay].next_overlay = -1;
564                         m_quadtree.nodes[overlay].render_dirty = true;
565                         m_quadtree.nodes[new_qti].next_overlay = overlay;
566                         new_qti = overlay;
567                 }
568         }
569         m_count += num_added;
570         return m_count-num_added;
571 #else // words fail me (still not amused)
572         return (m_count++);
573 #endif
574         
575 }
576
577 unsigned Document::AddBezierData(const Bezier & bezier)
578 {
579         m_objects.beziers.push_back(bezier);
580         return m_objects.beziers.size()-1;
581 }
582
583 unsigned Document::AddPathData(const Path & path)
584 {
585         m_objects.paths.push_back(path);
586         return m_objects.paths.size()-1;
587 }
588
589 void Document::DebugDumpObjects()
590 {
591         Debug("Objects for Document %p are:", this);
592         for (unsigned id = 0; id < ObjectCount(); ++id)
593         {
594                 Debug("%u. \tType: %u\tBounds: %s", id, m_objects.types[id], m_objects.bounds[id].Str().c_str());
595         }
596 }
597
598 bool Document::operator==(const Document & equ) const
599 {
600         return (ObjectCount() == equ.ObjectCount() 
601                 && memcmp(m_objects.bounds.data(), equ.m_objects.bounds.data(), ObjectCount() * sizeof(Rect)) == 0
602                 && memcmp(m_objects.data_indices.data(), equ.m_objects.data_indices.data(), ObjectCount() * sizeof(unsigned)) == 0
603                 && memcmp(m_objects.beziers.data(), equ.m_objects.beziers.data(), m_objects.beziers.size() * sizeof(Bezier)) == 0);
604 }
605
606
607
608 // Behold my amazing tokenizing abilities
609 static string & GetToken(const string & d, string & token, unsigned & i, const string & delims = "()[],{}<>;:=")
610 {
611         token.clear();
612         while (i < d.size() && iswspace(d[i]))
613         {
614                 ++i;
615         }
616         
617         while (i < d.size())
618         {
619                 if (iswspace(d[i]) || strchr(delims.c_str(),d[i]) != NULL)
620                 {
621                         if (token.size() == 0 && !iswspace(d[i]))
622                         {
623                                 token += d[i++];
624                         }
625                         break;  
626                 }
627                 token += d[i++];
628         }
629         //Debug("Got token \"%s\"", token.c_str());
630         return token;
631 }
632
633 static void GetXYPair(const string & d, Real & x, Real & y, unsigned & i,const string & delims = "()[],{}<>;:=")
634 {
635         string token("");
636         while (GetToken(d, token, i, delims) == ",");
637         x = RealFromStr(token);
638         if (GetToken(d, token, i, delims) != ",")
639         {
640                 Fatal("Expected \",\" seperating x,y pair");
641         }
642         y = RealFromStr(GetToken(d,token,i,delims));
643 }
644
645 static bool GetKeyValuePair(const string & d, string & key, string & value, unsigned & i, const string & delims = "()[],{}<>;:=")
646 {
647         key = "";
648         string token;
649         while (GetToken(d, token, i, delims) == ":" || token == ";");
650         key = token;
651         if (GetToken(d, token, i, delims) != ":")
652         {
653                 Error("Expected \":\" seperating key:value pair");
654                 return false;
655         }
656         value = "";
657         GetToken(d, value, i, delims);
658         return true;
659 }
660
661 static void TransformXYPair(Real & x, Real & y, const SVGMatrix & transform)
662 {
663         Real x0(x);
664         x = transform.a * x + transform.c * y + transform.e;
665         y = transform.b * x0 + transform.d * y + transform.f;
666 }
667
668 void Document::ParseSVGTransform(const string & s, SVGMatrix & transform)
669 {
670         //Debug("Parsing transform %s", s.c_str());
671         string token;
672         string command;
673         unsigned i = 0;
674         
675         while (i < s.size())
676         {
677                 GetToken(s, command, i);
678                 if (command == "," || command == "" || command == ":")
679                 {
680                         if (i < s.size())
681                                 GetToken(s, command, i);
682                         else
683                                 return;
684                 }
685                 //Debug("Token is \"%s\"", command.c_str());
686         
687                 SVGMatrix delta = {1,0,0,0,1,0};
688         
689         
690                 assert(GetToken(s,token, i) == "(");
691                 if (command == "translate")
692                 {
693                         GetXYPair(s, delta.e, delta.f, i);
694                         assert(GetToken(s,token, i) == ")");    
695                 }
696                 else if (command == "matrix")
697                 {
698                         GetXYPair(s, delta.a, delta.b,i);
699                         GetXYPair(s, delta.c, delta.d,i);
700                         GetXYPair(s, delta.e, delta.f,i);
701                         assert(GetToken(s,token, i) == ")");    
702                 }
703                 else if (command == "scale")
704                 {
705                         delta.a = RealFromStr(GetToken(s,token,i));
706                         GetToken(s, token, i);
707                         if (token == ",")
708                         {
709                                 delta.d = RealFromStr(GetToken(s,token,i));
710                                 assert(GetToken(s, token, i) == ")");
711                         }
712                         else
713                         {
714                                 delta.d = delta.a;
715                                 assert(token == ")");
716                         }
717                         
718                 }
719                 else
720                 {
721                         Warn("Unrecognised transform \"%s\", using identity", command.c_str());
722                 }
723         
724                 //Debug("Old transform is {%f,%f,%f,%f,%f,%f}", transform.a, transform.b, transform.c, transform.d,transform.e,transform.f);
725                 //Debug("Delta transform is {%f,%f,%f,%f,%f,%f}", delta.a, delta.b, delta.c, delta.d,delta.e,delta.f);
726         
727                 SVGMatrix old(transform);
728                 transform.a = old.a * delta.a + old.c * delta.b;
729                 transform.c = old.a * delta.c + old.c * delta.d;
730                 transform.e = old.a * delta.e + old.c * delta.f + old.e;
731         
732                 transform.b = old.b * delta.a + old.d * delta.b;
733                 transform.d = old.b * delta.c + old.d * delta.d;
734                 transform.f = old.b * delta.e + old.d * delta.f + old.f;
735         
736                 //Debug("New transform is {%f,%f,%f,%f,%f,%f}", transform.a, transform.b, transform.c, transform.d,transform.e,transform.f);
737         }
738 }
739
740 inline Colour ParseColourString(const string & colour_str)
741 {
742         Colour c(0,0,0,0);
743         if (colour_str == "red")
744                 c = {255,0,0,255};
745         else if (colour_str == "blue")
746                 c = {0,0,255,255};
747         else if (colour_str == "green")
748                 c = {0,255,0,255};
749         else if (colour_str == "black")
750                 c = {0,0,0,255};
751         else if (colour_str == "white")
752                 c = {255,255,255,255};
753         else if (colour_str.size() == 7 && colour_str[0] == '#')
754         {
755                 //Debug("Parse colour string: \"%s\"", colour_str.c_str());
756                 char comp[3] = {colour_str[1], colour_str[2], '\0'};
757                 c.r = strtoul(comp, NULL, 16);
758                 comp[0] = colour_str[3]; comp[1] = colour_str[4];
759                 c.g = strtoul(comp, NULL, 16);
760                 comp[0] = colour_str[5]; comp[1] = colour_str[6];
761                 c.b = strtoul(comp, NULL, 16);
762                 c.a = 255;
763                 //Debug("Colour is: %u, %u, %u, %u", c.r, c.g, c.b, c.a);
764         }
765         return c;
766 }
767
768 void Document::ParseSVGNode(pugi::xml_node & root, SVGMatrix & parent_transform)
769 {
770         //Debug("Parse node <%s>", root.name());
771
772         
773         // Centre the SVGs
774         if (strcmp(root.name(),"svg") == 0)
775         {
776                 Real ww = RealFromStr(root.attribute("width").as_string());
777                 Real hh = RealFromStr(root.attribute("height").as_string());
778                 parent_transform.e -= parent_transform.a * ww/Real(2);
779                 parent_transform.f -= parent_transform.d * hh/Real(2);
780         }
781         
782         for (pugi::xml_node child = root.first_child(); child; child = child.next_sibling())
783         {
784                 SVGMatrix transform(parent_transform);  
785                 pugi::xml_attribute attrib_trans = child.attribute("transform");
786                 if (!attrib_trans.empty())
787                 {
788                         ParseSVGTransform(attrib_trans.as_string(), transform);
789                 }
790                 
791                 
792                 
793                 if (strcmp(child.name(), "svg") == 0 || strcmp(child.name(),"g") == 0
794                         || strcmp(child.name(), "group") == 0)
795                 {
796                         
797                         ParseSVGNode(child, transform);
798                         continue;
799                 }
800                 else if (strcmp(child.name(), "path") == 0)
801                 {
802                         string d = child.attribute("d").as_string();
803                         //Debug("Path data attribute is \"%s\"", d.c_str());
804                         bool closed = false;
805                         pair<unsigned, unsigned> range = ParseSVGPathData(d, transform, closed);
806                         if (true && range.first < m_count && range.second < m_count)//(closed)
807                         {
808                                 
809                                 string colour_str("");
810                                 map<string, string> style;
811                                 if (child.attribute("style"))
812                                 {
813                                         ParseSVGStyleData(child.attribute("style").as_string(), style);
814                                 }
815                                 
816                                 // Determine shading colour
817                                 if (child.attribute("fill"))
818                                 {
819                                         colour_str = child.attribute("fill").as_string();
820                                 }
821                                 else if (style.find("fill") != style.end())
822                                 {
823                                         colour_str = style["fill"];
824                                 }
825                                 Colour fill = ParseColourString(colour_str);
826                                 Colour stroke = fill;
827                         
828                                 if (child.attribute("stroke"))
829                                 {
830                                         colour_str = child.attribute("stroke").as_string();
831                                         stroke = ParseColourString(colour_str);
832                                 }
833                                 else if (style.find("stroke") != style.end())
834                                 {
835                                         colour_str = style["stroke"];
836                                         stroke = ParseColourString(colour_str);
837                                 }
838                                 
839                                 
840                                 // Determin shading alpha
841                                 if (child.attribute("fill-opacity"))
842                                 {
843                                         fill.a = 255*child.attribute("fill-opacity").as_float();
844                                 }
845                                 else if (style.find("fill-opacity") != style.end())
846                                 {
847                                         fill.a = 255*strtod(style["fill-opacity"].c_str(), NULL);
848                                 }
849                                 if (child.attribute("stroke-opacity"))
850                                 {
851                                         stroke.a = 255*child.attribute("stroke-opacity").as_float();
852                                 }
853                                 else if (style.find("stroke-opacity") != style.end())
854                                 {
855                                         stroke.a = 255*strtod(style["stroke-opacity"].c_str(), NULL);
856                                 }
857                                 AddPath(range.first, range.second, fill, stroke);
858                         }
859                         
860                 }
861                 else if (strcmp(child.name(), "line") == 0)
862                 {
863                         Real x0(child.attribute("x1").as_float());
864                         Real y0(child.attribute("y1").as_float());
865                         Real x1(child.attribute("x2").as_float());
866                         Real y1(child.attribute("y2").as_float());
867                         TransformXYPair(x0,y0,transform);
868                         TransformXYPair(x1,y1,transform);
869                         AddBezier(Bezier(x0,y0,x1,y1,x1,y1,x1,y1));
870                 }
871                 else if (strcmp(child.name(), "rect") == 0)
872                 {
873                         Real coords[4];
874                         const char * attrib_names[] = {"x", "y", "width", "height"};
875                         for (size_t i = 0; i < 4; ++i)
876                                 coords[i] = child.attribute(attrib_names[i]).as_float();
877                         
878                         Real x2(coords[0]+coords[2]);
879                         Real y2(coords[1]+coords[3]);
880                         TransformXYPair(coords[0],coords[1],transform); // x, y, transform
881                         TransformXYPair(x2,y2,transform);
882                         coords[2] = x2 - coords[0];
883                         coords[3] = y2 - coords[1];
884                         
885                         bool outline = !(child.attribute("fill") && strcmp(child.attribute("fill").as_string(),"none") != 0);
886                         Add(outline?RECT_OUTLINE:RECT_FILLED, Rect(coords[0], coords[1], coords[2], coords[3]),0);
887                 }
888                 else if (strcmp(child.name(), "circle") == 0)
889                 {
890                         Real cx = child.attribute("cx").as_float();
891                         Real cy = child.attribute("cy").as_float();
892                         Real r = child.attribute("r").as_float();
893                         
894                         Real x = (cx - r);
895                         Real y = (cy - r);
896                         TransformXYPair(x,y,transform);
897                         Real w = Real(2)*r*transform.a; // width scales
898                         Real h = Real(2)*r*transform.d; // height scales
899                         
900                         
901                         Rect rect(x,y,w,h);
902                         Add(CIRCLE_FILLED, rect,0);
903                         Debug("Added Circle %s", rect.Str().c_str());                   
904                 }
905                 else if (strcmp(child.name(), "text") == 0)
906                 {
907                         Real x = child.attribute("x").as_float();
908                         Real y = child.attribute("y").as_float();
909                         TransformXYPair(x,y,transform);
910                         Debug("Add text \"%s\"", child.child_value());
911                         AddText(child.child_value(), 0.05, x, y);
912                 }
913         }
914 }
915
916 void Document::ParseSVGStyleData(const string & style, map<string, string> & results)
917 {
918         unsigned i = 0;
919         string key;
920         string value;
921         while (i < style.size() && GetKeyValuePair(style, key, value, i))
922         {
923                 results[key] = value;
924         }
925 }
926
927 /**
928  * Parse an SVG string into a rectangle
929  */
930 void Document::ParseSVG(const string & input, const Rect & bounds)
931 {
932         using namespace pugi;
933         
934         xml_document doc_xml;
935         xml_parse_result result = doc_xml.load(input.c_str());
936         
937         if (!result)
938                 Error("Couldn't parse SVG input - %s", result.description());
939                 
940         Debug("Loaded XML - %s", result.description());
941         SVGMatrix transform = {bounds.w, 0,bounds.x, 0,bounds.h,bounds.y};
942         ParseSVGNode(doc_xml, transform);
943 }
944
945 /**
946  * Load an SVG into a rectangle
947  */
948 void Document::LoadSVG(const string & filename, const Rect & bounds)
949 {
950         using namespace pugi;
951         
952         xml_document doc_xml;
953         ifstream input(filename.c_str(), ios_base::in);
954         xml_parse_result result = doc_xml.load(input);
955         
956         if (!result)
957                 Error("Couldn't load \"%s\" - %s", filename.c_str(), result.description());
958                 
959         Debug("Loaded XML from \"%s\" - %s", filename.c_str(), result.description());
960         
961         input.close();
962                                                 // a c e, b d f
963         SVGMatrix transform = {bounds.w,0 ,bounds.x, 0,bounds.h,bounds.y};
964         ParseSVGNode(doc_xml, transform);
965 }
966
967
968
969 // Fear the wrath of the tokenizing svg data
970 // Seriously this isn't really very DOM-like at all is it?
971 pair<unsigned, unsigned> Document::ParseSVGPathData(const string & d, const SVGMatrix & transform, bool & closed)
972 {
973         closed = false;
974         Real x[4] = {0,0,0,0};
975         Real y[4] = {0,0,0,0};
976         
977         string token("");
978         string command("m");
979         
980         Real x0(0);
981         Real y0(0);
982         
983         unsigned i = 0;
984         unsigned prev_i = 0;
985         
986         bool start = false;
987         
988
989         static string delims("()[],{}<>;:=LlHhVvmMqQzZcC");
990
991         pair<unsigned, unsigned> range(m_count, m_count);
992         
993         while (i < d.size() && GetToken(d, token, i, delims).size() > 0)
994         {
995                 if (isalpha(token[0]))
996                         command = token;
997                 else
998                 {
999                         i = prev_i; // hax
1000                         if(command == "")
1001                                 command = "L";
1002                 }
1003                 
1004                 bool relative = islower(command[0]);
1005                         
1006                 if (command == "m" || command == "M")
1007                 {
1008                         //Debug("Construct moveto command");
1009                         Real dx = RealFromStr(GetToken(d,token,i,delims));
1010                         assert(GetToken(d,token,i,delims) == ",");
1011                         Real dy = RealFromStr(GetToken(d,token,i,delims));
1012                         
1013                         x[0] = (relative) ? x[0] + dx : dx;
1014                         y[0] = (relative) ? y[0] + dy : dy;
1015                         
1016                         x0 = x[0];
1017                         y0 = y[0];
1018                         //Debug("mmoveto %f,%f", Float(x[0]),Float(y[0]));
1019                         command = (command == "m") ? "l" : "L";
1020                 }
1021                 else if (command == "c" || command == "C" || command == "q" || command == "Q")
1022                 {
1023                         //Debug("Construct curveto command");
1024                         Real dx = RealFromStr(GetToken(d,token,i,delims));
1025                         assert(GetToken(d,token,i,delims) == ",");
1026                         Real dy = RealFromStr(GetToken(d,token,i,delims));
1027                         
1028                         x[1] = (relative) ? x[0] + dx : dx;
1029                         y[1] = (relative) ? y[0] + dy : dy;
1030                         
1031                         dx = RealFromStr(GetToken(d,token,i,delims));
1032                         assert(GetToken(d,token,i,delims) == ",");
1033                         dy = RealFromStr(GetToken(d,token,i,delims));
1034                         
1035                         x[2] = (relative) ? x[0] + dx : dx;
1036                         y[2] = (relative) ? y[0] + dy : dy;
1037                         
1038                         if (command != "q" && command != "Q")
1039                         {
1040                                 dx = RealFromStr(GetToken(d,token,i,delims));
1041                                 assert(GetToken(d,token,i,delims) == ",");
1042                                 dy = RealFromStr(GetToken(d,token,i,delims));
1043                                 x[3] = (relative) ? x[0] + dx : dx;
1044                                 y[3] = (relative) ? y[0] + dy : dy;
1045                         }
1046                         else
1047                         {
1048                                 x[3] = x[2];
1049                                 y[3] = y[2];
1050                                 Real old_x1(x[1]), old_y1(y[1]);
1051                                 x[1] = x[0] + Real(2) * (old_x1 - x[0])/ Real(3);
1052                                 y[1] = y[0] + Real(2) * (old_y1 - y[0])/ Real(3);
1053                                 x[2] = x[3] + Real(2) * (old_x1 - x[3])/ Real(3);
1054                                 y[2] = y[3] + Real(2) * (old_y1 - y[3])/ Real(3);
1055                         }
1056                         
1057                         Real x3(x[3]);
1058                         Real y3(y[3]);
1059                         for (int j = 0; j < 4; ++j)
1060                                 TransformXYPair(x[j],y[j], transform);
1061
1062                         range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
1063                         
1064                         //Debug("[%u] curveto %f,%f %f,%f %f,%f", index, Float(x[1]),Float(y[1]),Float(x[2]),Float(y[2]),Float(x[3]),Float(y[3]));
1065                         
1066                         x[0] = x3;
1067                         y[0] = y3;
1068
1069                         
1070                 }
1071                 else if (command == "l" || command == "L" || command == "h" || command == "H" || command == "v" || command == "V")
1072                 {
1073                         //Debug("Construct lineto command, relative %d", relative);
1074                 
1075                         Real dx = RealFromStr(GetToken(d,token,i,delims));
1076                         Real dy = 0;
1077                         if (command == "l" || command == "L")
1078                         {
1079                                 assert(GetToken(d,token,i,delims) == ",");
1080                                 dy = RealFromStr(GetToken(d,token,i,delims));
1081                         }
1082                         else if (command == "v" || command == "V")
1083                         {
1084                                 swap(dx,dy);
1085                         }
1086                         
1087                         x[1] = (relative) ? x[0] + dx : dx;
1088                         y[1] = (relative) ? y[0] + dy : dy;
1089                         if (command == "v" || command == "V")
1090                         {
1091                                 x[1] = x[0];
1092                         }
1093                         else if (command == "h" || command == "H")
1094                         {
1095                                 y[1] = y[0];
1096                         }
1097                         
1098                         Real x1(x[1]);
1099                         Real y1(y[1]);
1100                         
1101                         TransformXYPair(x[0],y[0],transform);
1102                         TransformXYPair(x[1],y[1],transform);
1103
1104
1105                         range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[1],y[1],x[1],y[1]));
1106                         
1107                         //Debug("[%u] lineto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
1108                         
1109                         x[0] = x1;
1110                         y[0] = y1;
1111
1112                 }
1113                 else if (command == "z" || command == "Z")
1114                 {
1115                         //Debug("Construct returnto command");
1116                         x[1] = x0;
1117                         y[1] = y0;
1118                         x[2] = x0;
1119                         y[2] = y0;
1120                         x[3] = x0;
1121                         y[3] = y0;
1122                         
1123                         Real x3(x[3]);
1124                         Real y3(y[3]);
1125                         for (int j = 0; j < 4; ++j)
1126                                 TransformXYPair(x[j],y[j], transform);
1127
1128                         range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
1129                         //Debug("[%u] returnto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
1130                         
1131                         x[0] = x3;
1132                         y[0] = y3;
1133                         command = "m";
1134                         closed = true;
1135                 }
1136                 else
1137                 {
1138                         Warn("Unrecognised command \"%s\", set to \"m\"", command.c_str());
1139                         command = "m";
1140                 }
1141                 
1142                 if (!start)
1143                 {
1144                         x0 = x[0];
1145                         y0 = y[0];
1146                         start = true;
1147                 }
1148                 prev_i = i;
1149         }
1150         return range;
1151 }
1152
1153 void Document::SetFont(const string & font_filename)
1154 {
1155         if (m_font_data != NULL)
1156         {
1157                 free(m_font_data);
1158         }
1159         
1160         FILE *font_file = fopen(font_filename.c_str(), "rb");
1161         fseek(font_file, 0, SEEK_END);
1162         size_t font_file_size = ftell(font_file);
1163         fseek(font_file, 0, SEEK_SET);
1164         m_font_data = (unsigned char*)malloc(font_file_size);
1165         size_t read = fread(m_font_data, 1, font_file_size, font_file);
1166         if (read != font_file_size)
1167         {
1168                 Fatal("Failed to read font data from \"%s\" - Read %u bytes expected %u - %s", font_filename.c_str(), read, font_file_size, strerror(errno));
1169         }
1170         fclose(font_file);
1171         stbtt_InitFont(&m_font, m_font_data, 0);
1172 }
1173
1174 void Document::AddText(const string & text, Real scale, Real x, Real y)
1175 {
1176         if (m_font_data == NULL)
1177         {
1178                 Warn("No font loaded");
1179                 return;
1180         }
1181                 
1182         Real x0(x);
1183         //Real y0(y);
1184         int ascent = 0, descent = 0, line_gap = 0;
1185         stbtt_GetFontVMetrics(&m_font, &ascent, &descent, &line_gap);
1186         Real font_scale = scale;
1187         font_scale /= Real(ascent - descent);
1188         Real y_advance = Real(font_scale) * Real(ascent - descent + line_gap);
1189         for (unsigned i = 0; i < text.size(); ++i)
1190         {
1191                 if (text[i] == '\n')
1192                 {
1193                         y += y_advance;
1194                         x = x0;
1195                 }
1196                 if (!isprint(text[i]))
1197                         continue;
1198                         
1199                 int advance_width = 0, left_side_bearing = 0, kerning = 0;
1200                 stbtt_GetCodepointHMetrics(&m_font, text[i], &advance_width, &left_side_bearing);
1201                 if (i >= 1)
1202                 {
1203                         kerning = stbtt_GetCodepointKernAdvance(&m_font, text[i-1], text[i]);
1204                 }
1205                 x += font_scale * Real(kerning);
1206                 AddFontGlyphAtPoint(&m_font, text[i], font_scale, x, y);
1207                 x += font_scale * Real(advance_width);
1208         }
1209 }
1210
1211 void Document::AddFontGlyphAtPoint(stbtt_fontinfo *font, int character, Real scale, Real x, Real y)
1212 {
1213         int glyph_index = stbtt_FindGlyphIndex(font, character);
1214
1215         // Check if there is actully a glyph to render.
1216         if (stbtt_IsGlyphEmpty(font, glyph_index))
1217         {
1218                 return;
1219         }
1220
1221         stbtt_vertex *instructions;
1222         int num_instructions = stbtt_GetGlyphShape(font, glyph_index, &instructions);
1223
1224         Real current_x(0), current_y(0);
1225         unsigned start_index = m_count;
1226         unsigned end_index = m_count;
1227         for (int i = 0; i < num_instructions; ++i)
1228         {
1229                 // TTF uses 16-bit signed ints for coordinates:
1230                 // with the y-axis inverted compared to us.
1231                 // Convert and scale any data.
1232                 Real inst_x = Real(instructions[i].x)*scale;
1233                 Real inst_y = Real(instructions[i].y)*-scale;
1234                 Real inst_cx = Real(instructions[i].cx)*scale;
1235                 Real inst_cy = Real(instructions[i].cy)*-scale;
1236                 Real old_x(current_x), old_y(current_y);
1237                 current_x = inst_x;
1238                 current_y = inst_y;
1239                 
1240                 switch(instructions[i].type)
1241                 {
1242                 // Move To
1243                 case STBTT_vmove:
1244                         break;
1245                 // Line To
1246                 case STBTT_vline:
1247                         end_index = AddBezier(Bezier(old_x + x, old_y + y, old_x + x, old_y + y, current_x + x, current_y + y, current_x + x, current_y + y));
1248                         break;
1249                 // Quadratic Bezier To:
1250                 case STBTT_vcurve:
1251                         // Quadratic -> Cubic:
1252                         // - Endpoints are the same.
1253                         // - cubic1 = quad0+(2/3)*(quad1-quad0)
1254                         // - cubic2 = quad2+(2/3)*(quad1-quad2)
1255                         end_index = AddBezier(Bezier(old_x + x, old_y + y, old_x + Real(2)*(inst_cx-old_x)/Real(3) + x, old_y + Real(2)*(inst_cy-old_y)/Real(3) + y,
1256                                                 current_x + Real(2)*(inst_cx-current_x)/Real(3) + x, current_y + Real(2)*(inst_cy-current_y)/Real(3) + y, current_x + x, current_y + y));
1257                         break;
1258                 }
1259         }
1260         
1261         if (start_index < m_count && end_index < m_count)
1262         {
1263                 AddPath(start_index, end_index);
1264         }
1265         //Debug("Added Glyph \"%c\" at %f %f, scale %f", (char)character, Float(x), Float(y), Float(scale));
1266
1267         stbtt_FreeShape(font, instructions);
1268 }
1269
1270 void Document::TransformObjectBounds(const SVGMatrix & transform, ObjectType type)
1271 {
1272         #ifdef TRANSFORM_BEZIERS_TO_PATH
1273                 for (unsigned i = 0; i < m_objects.paths.size(); ++i)
1274                 {
1275                         Path & p = m_objects.paths[i];
1276                         p.m_bounds.x = transform.a * p.m_bounds.x + transform.e;
1277                         p.m_bounds.y = transform.d * p.m_bounds.y + transform.f;
1278                         p.m_bounds.w *= transform.a;
1279                         p.m_bounds.h *= transform.d;
1280                 }
1281                 return;
1282         #endif          
1283         
1284         for (unsigned i = 0; i < m_count; ++i)
1285         {
1286                 if (type == NUMBER_OF_OBJECT_TYPES || m_objects.types[i] == type)
1287                 {
1288                         TransformXYPair(m_objects.bounds[i].x, m_objects.bounds[i].y, transform);
1289                         m_objects.bounds[i].w *= transform.a;
1290                         m_objects.bounds[i].h *= transform.d;
1291                 }
1292         }
1293 }
1294
1295 void Document::TranslateObjects(const Real & dx, const Real & dy, ObjectType type)
1296 {
1297         #ifdef TRANSFORM_BEZIERS_TO_PATH
1298         for (unsigned i = 0; i < m_objects.paths.size(); ++i)
1299         {
1300                 Path & p = m_objects.paths[i];
1301                 p.m_bounds.x += dx;
1302                 p.m_bounds.y += dy;
1303         }
1304         return;
1305         #endif
1306
1307         for (unsigned i = 0; i < m_count; ++i)
1308         {
1309                 if (type == NUMBER_OF_OBJECT_TYPES || m_objects.types[i] == type)
1310                 {
1311                         m_objects.bounds[i].x += dx;
1312                         m_objects.bounds[i].y += dy;
1313                 }
1314         }
1315 }
1316
1317 void Document::ScaleObjectsAboutPoint(const Real & x, const Real & y, const Real & scale_amount, ObjectType type)
1318 {
1319         #ifdef TRANSFORM_BEZIERS_TO_PATH
1320                 for (unsigned i = 0; i < m_objects.paths.size(); ++i)
1321                 {
1322                         Path & p = m_objects.paths[i];
1323                         p.m_bounds.w /= scale_amount;
1324                         p.m_bounds.h /= scale_amount;
1325                         p.m_bounds.x -= x;
1326                         p.m_bounds.x /= scale_amount;
1327                         p.m_bounds.x += x;
1328                         p.m_bounds.y -= y;
1329                         p.m_bounds.y /= scale_amount;
1330                         p.m_bounds.y += y;
1331                 }
1332                 return;
1333         #endif
1334         
1335         for (unsigned i = 0; i < m_count; ++i)
1336         {
1337                 if (type != NUMBER_OF_OBJECT_TYPES && m_objects.types[i] != type)
1338                         continue;
1339                 
1340                 m_objects.bounds[i].w /= scale_amount;
1341                 m_objects.bounds[i].h /= scale_amount;
1342                 //m_objects.bounds[i].x = x + (m_objects.bounds[i].x-x)/scale_amount;
1343                 //m_objects.bounds[i].y = y + (m_objects.bounds[i].y-x)/scale_amount;
1344                 m_objects.bounds[i].x -= x;
1345                 m_objects.bounds[i].x /= scale_amount;
1346                 m_objects.bounds[i].x += x;
1347                 
1348                 m_objects.bounds[i].y -= y;
1349                 m_objects.bounds[i].y /= scale_amount;
1350                 m_objects.bounds[i].y += y;
1351         }
1352
1353 }
1354
1355

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