a4b20d08f091ecaa4585377343a9f97f7fccf9af
[ipdf/code.git] / src / document.cpp
1 #include "document.h"
2 #include "bezier.h"
3 #include <cstdio>
4 #include <fstream>
5
6 #include "stb_truetype.h"
7
8 using namespace IPDF;
9 using namespace std;
10
11 //TODO: Make this work for variable sized Reals
12
13 // Loads an std::vector<T> of size num_elements from a file.
14 template<typename T>
15 static void LoadStructVector(FILE *src_file, size_t num_elems, std::vector<T>& dest)
16 {
17         size_t structsread = 0;
18         dest.resize(num_elems);
19         structsread = fread(dest.data(), sizeof(T), num_elems, src_file);
20         if (structsread != num_elems)
21                 Fatal("Only read %u structs (expected %u)!", structsread, num_elems);
22 }
23
24 // Saves an std::vector<T> to a file. Size must be saves separately.
25 template<typename T>
26 static void SaveStructVector(FILE *dst_file, std::vector<T>& src)
27 {
28         size_t written = 0;
29         written = fwrite(src.data(), sizeof(T), src.size(), dst_file);
30         if (written != src.size())
31                 Fatal("Only wrote %u structs (expected %u)!", written, src.size());
32 }
33
34 static void WriteChunkHeader(FILE *dst_file, DocChunkTypes type, uint32_t size)
35 {
36         size_t written = 0;
37         written = fwrite(&type, sizeof(type), 1, dst_file);
38         if (written != 1)
39                 Fatal("Could not write Chunk header! (ID)");
40         written = fwrite(&size, sizeof(size), 1, dst_file);
41         if (written != 1)
42                 Fatal("Could not write Chunk header (size)!");
43 }
44
45 static bool ReadChunkHeader(FILE *src_file, DocChunkTypes& type, uint32_t& size)
46 {
47         if (fread(&type, sizeof(DocChunkTypes), 1, src_file) != 1)
48                 return false;
49         if (fread(&size, sizeof(uint32_t), 1, src_file) != 1)
50                 return false;
51         return true;
52 }
53
54 void Document::Save(const string & filename)
55 {
56         Debug("Saving document to file \"%s\"...", filename.c_str());
57         FILE * file = fopen(filename.c_str(), "w");
58         if (file == NULL)
59                 Fatal("Couldn't open file \"%s\" - %s", filename.c_str(), strerror(errno));
60
61         size_t written;
62         Debug("Number of objects (%u)...", ObjectCount());
63         WriteChunkHeader(file, CT_NUMOBJS, sizeof(m_count));
64         written = fwrite(&m_count, sizeof(m_count), 1, file);
65         if (written != 1)
66                 Fatal("Failed to write number of objects!");
67
68         Debug("Object types...");
69         WriteChunkHeader(file, CT_OBJTYPES, m_objects.types.size() * sizeof(ObjectType));
70         SaveStructVector<ObjectType>(file, m_objects.types);
71
72         Debug("Object bounds...");
73         WriteChunkHeader(file, CT_OBJBOUNDS, m_objects.bounds.size() * sizeof(Rect));
74         SaveStructVector<Rect>(file, m_objects.bounds);
75
76         Debug("Object data indices...");
77         WriteChunkHeader(file, CT_OBJINDICES, m_objects.data_indices.size() * sizeof(unsigned));
78         SaveStructVector<unsigned>(file, m_objects.data_indices);
79         
80         Debug("Bezier data...");
81         WriteChunkHeader(file, CT_OBJBEZIERS, m_objects.beziers.size() * sizeof(uint8_t));
82         SaveStructVector<Bezier>(file, m_objects.beziers);
83
84         int err = fclose(file);
85         if (err != 0)
86                 Fatal("Failed to close file \"%s\" - %s", filename.c_str(), strerror(err));
87
88         Debug("Successfully saved %u objects to \"%s\"", ObjectCount(), filename.c_str());
89 }
90
91 #ifndef QUADTREE_DISABLED
92
93 void Document::GenBaseQuadtree()
94 {
95         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QTC_UNKNOWN, 0, ObjectCount()});
96         m_quadtree.root_id = 0;
97         GenQuadChild(0, QTC_TOP_LEFT);
98         GenQuadParent(0, QTC_BOTTOM_RIGHT);
99 }
100
101 QuadTreeIndex Document::GenQuadChild(QuadTreeIndex parent, QuadTreeNodeChildren type)
102 {
103         QuadTreeIndex new_index = m_quadtree.nodes.size();
104         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, parent, type, 0, 0});
105
106         m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
107         for (unsigned i = m_quadtree.nodes[parent].object_begin; i < m_quadtree.nodes[parent].object_end; ++i)
108         {
109                 if (ContainedInQuadChild(m_objects.bounds[i], type))
110                 {
111                         m_objects.bounds.push_back(TransformToQuadChild(m_objects.bounds[i], type));
112                         m_objects.types.push_back(m_objects.types[i]);
113                         m_objects.data_indices.push_back(m_objects.data_indices[i]);
114                         m_count++;
115                 }
116         }
117         m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
118         switch (type)
119         {
120                 case QTC_TOP_LEFT:
121                         m_quadtree.nodes[parent].top_left = new_index;
122                         break;
123                 case QTC_TOP_RIGHT:
124                         m_quadtree.nodes[parent].top_right = new_index;
125                         break;
126                 case QTC_BOTTOM_LEFT:
127                         m_quadtree.nodes[parent].bottom_left = new_index;
128                         break;
129                 case QTC_BOTTOM_RIGHT:
130                         m_quadtree.nodes[parent].bottom_right = new_index;
131                         break;
132                 default:
133                         Fatal("Tried to add a QuadTree child of invalid type!");
134         }
135         return new_index;
136 }
137
138 // Reparent a quadtree node, making it the "type" child of a new node.
139 QuadTreeIndex Document::GenQuadParent(QuadTreeIndex child, QuadTreeNodeChildren type)
140 {
141         QuadTreeIndex new_index = m_quadtree.nodes.size();
142         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, -1, QTC_UNKNOWN, 0, 0});
143
144         m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
145         for (unsigned i = m_quadtree.nodes[child].object_begin; i < m_quadtree.nodes[child].object_end; ++i)
146         {
147                 m_objects.bounds.push_back(TransformFromQuadChild(m_objects.bounds[i], type));
148                 m_objects.types.push_back(m_objects.types[i]);
149                 m_objects.data_indices.push_back(m_objects.data_indices[i]);
150                 m_count++;
151         }
152         m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
153         switch (type)
154         {
155                 case QTC_TOP_LEFT:
156                         m_quadtree.nodes[new_index].top_left = child;
157                         break;
158                 case QTC_TOP_RIGHT:
159                         m_quadtree.nodes[new_index].top_right = child;
160                         break;
161                 case QTC_BOTTOM_LEFT:
162                         m_quadtree.nodes[new_index].bottom_left = child;
163                         break;
164                 case QTC_BOTTOM_RIGHT:
165                         m_quadtree.nodes[new_index].bottom_right = child;
166                         break;
167                 default:
168                         Fatal("Tried to add a QuadTree child of invalid type!");
169         }
170         return new_index;
171 }
172
173 #endif
174
175 void Document::Load(const string & filename)
176 {
177         m_objects.bounds.clear();
178         m_count = 0;
179         if (filename == "")
180         {
181                 Debug("Loaded empty document.");
182                 return;
183         }
184         Debug("Loading document from file \"%s\"", filename.c_str());
185         FILE * file = fopen(filename.c_str(), "r");
186         if (file == NULL)
187                 Fatal("Couldn't open file \"%s\"", filename.c_str(), strerror(errno));
188
189         size_t read;
190
191         DocChunkTypes chunk_type;
192         uint32_t chunk_size;
193         while (ReadChunkHeader(file, chunk_type, chunk_size))
194         {
195                 switch(chunk_type)
196                 {
197                 case CT_NUMOBJS:
198                         read = fread(&m_count, sizeof(m_count), 1, file);
199                         if (read != 1)
200                                 Fatal("Failed to read number of objects!");
201                         Debug("Number of objects: %u", ObjectCount());
202                         break;
203                 case CT_OBJTYPES:
204                         Debug("Object types...");
205                         LoadStructVector<ObjectType>(file, chunk_size/sizeof(ObjectType), m_objects.types);
206                         break;
207                 case CT_OBJBOUNDS:
208                         Debug("Object bounds...");
209                         LoadStructVector<Rect>(file, chunk_size/sizeof(Rect), m_objects.bounds);
210                         break;
211                 case CT_OBJINDICES:
212                         Debug("Object data indices...");
213                         LoadStructVector<unsigned>(file, chunk_size/sizeof(unsigned), m_objects.data_indices);
214                         break;
215                 case CT_OBJBEZIERS:
216                         Debug("Bezier data...");
217                         LoadStructVector<Bezier>(file, chunk_size/sizeof(Bezier), m_objects.beziers);
218                         break;
219                 }
220         }
221         Debug("Successfully loaded %u objects from \"%s\"", ObjectCount(), filename.c_str());
222 #ifndef QUADTREE_DISABLED
223         if (m_quadtree.root_id == QUADTREE_EMPTY)
224         {
225                 GenBaseQuadtree();
226         }
227 #endif
228 }
229
230 void Document::Add(ObjectType type, const Rect & bounds, unsigned data_index)
231 {
232         m_objects.types.push_back(type);
233         m_objects.bounds.push_back(bounds);
234         m_objects.data_indices.push_back(data_index);
235         ++m_count; // Why can't we just use the size of types or something?
236 }
237
238 unsigned Document::AddBezierData(const Bezier & bezier)
239 {
240         m_objects.beziers.push_back(bezier);
241         return m_objects.beziers.size()-1;
242 }
243
244
245 void Document::DebugDumpObjects()
246 {
247         Debug("Objects for Document %p are:", this);
248         for (unsigned id = 0; id < ObjectCount(); ++id)
249         {
250                 Debug("%u. \tType: %u\tBounds: %s", id, m_objects.types[id], m_objects.bounds[id].Str().c_str());
251         }
252 }
253
254 bool Document::operator==(const Document & equ) const
255 {
256         return (ObjectCount() == equ.ObjectCount() 
257                 && memcmp(m_objects.bounds.data(), equ.m_objects.bounds.data(), ObjectCount() * sizeof(Rect)) == 0
258                 && memcmp(m_objects.data_indices.data(), equ.m_objects.data_indices.data(), ObjectCount() * sizeof(unsigned)) == 0
259                 && memcmp(m_objects.beziers.data(), equ.m_objects.beziers.data(), m_objects.beziers.size() * sizeof(Bezier)) == 0);
260 }
261
262
263 #include "../contrib/pugixml-1.4/src/pugixml.hpp"
264 #include "../contrib/pugixml-1.4/src/pugixml.cpp"
265
266 /**
267  * Load an SVG into a rectangle
268  */
269 void Document::LoadSVG(const string & filename, const Rect & bounds)
270 {
271         using namespace pugi;
272         
273         xml_document doc_xml;
274         ifstream input(filename.c_str(), ios_base::in);
275         xml_parse_result result = doc_xml.load(input);
276         
277         if (!result)
278                 Fatal("Couldn't load \"%s\" - %s", filename.c_str(), result.description());
279                 
280         Debug("Loaded XML - %s", result.description());
281         
282         input.close();
283
284         // Combine all SVG tags into one thing because lazy
285         for (xml_node svg : doc_xml.children("svg"))
286         {
287                 Real width = svg.attribute("width").as_float() * bounds.w;
288                 Real height = svg.attribute("width").as_float() * bounds.h;
289                 
290                 
291                 // Rectangles
292                 Real coords[4];
293                 const char * attrib_names[] = {"x", "y", "width", "height"};
294                 for (pugi::xml_node rect : svg.children("rect"))
295                 {
296                         for (size_t i = 0; i < 4; ++i)
297                                 coords[i] = rect.attribute(attrib_names[i]).as_float();
298                         
299                         bool outline = !(rect.attribute("fill"));
300                         Add(outline?RECT_OUTLINE:RECT_FILLED, Rect(coords[0]/width + bounds.x, coords[1]/height + bounds.y, coords[2]/width, coords[3]/height),0);
301                         Debug("Added rectangle");
302                 }               
303                 
304                 // Circles
305                 for (pugi::xml_node circle : svg.children("circle"))
306                 {
307                         Real cx = circle.attribute("cx").as_float();
308                         Real cy = circle.attribute("cy").as_float();
309                         Real r = circle.attribute("r").as_float();
310                         
311                         Real x = (cx - r)/width + bounds.x; 
312                         Real y = (cy - r)/height + bounds.y; 
313                         Real w = 2*r/width; 
314                         Real h = 2*r/height;
315                         
316                         Rect rect(x,y,w,h);
317                         Add(CIRCLE_FILLED, rect,0);
318                         Debug("Added Circle %s", rect.Str().c_str());
319
320                 }               
321                 
322                 // paths
323                 for (pugi::xml_node path : svg.children("path"))
324                 {
325                         
326                         string d = path.attribute("d").as_string();
327                         Debug("Path data attribute is \"%s\"", d.c_str());
328                         AddPathFromString(d, Rect(bounds.x,bounds.y,width,height));
329                         
330                 }
331         }
332         
333         //Fatal("Done");
334         
335         
336
337 }
338
339 // Behold my amazing tokenizing abilities
340 static string & GetToken(const string & d, string & token, unsigned & i)
341 {
342         token.clear();
343         while (i < d.size() && iswspace(d[i]))
344         {
345                 ++i;
346         }
347         
348         while (i < d.size())
349         {
350                 if (d[i] == ',' || (isalpha(d[i]) && d[i] != 'e') || iswspace(d[i]))
351                 {
352                         if (token.size() == 0 && !iswspace(d[i]))
353                         {
354                                 token += d[i++];
355                         }
356                         break;  
357                 }
358                 token += d[i++];
359         }
360         Debug("Got token \"%s\"", token.c_str());
361         return token;
362 }
363
364
365 // Fear the wrath of the tokenizing svg data
366 // Seriously this isn't really very DOM-like at all is it?
367 void Document::AddPathFromString(const string & d, const Rect & bounds)
368 {
369         Real x[4] = {0,0,0,0};
370         Real y[4] = {0,0,0,0};
371         
372         string token("");
373         string command("m");
374         
375         Real x0(0);
376         Real y0(0);
377         
378         unsigned i = 0;
379         unsigned prev_i = 0;
380         
381         bool start = false;
382         
383         while (i < d.size() && GetToken(d, token, i).size() > 0)
384         {
385                 if (isalpha(token[0]))
386                         command = token;
387                 else
388                 {
389                         i = prev_i; // hax
390                         if(command == "")
391                                 command = "L";
392                 }
393                 
394                 bool relative = islower(command[0]);
395                         
396                 if (command == "m" || command == "M")
397                 {
398                         Debug("Construct moveto command");
399                         Real dx = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.w;
400                         assert(GetToken(d,token,i) == ",");
401                         Real dy = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.h;
402                         
403                         x[0] = (relative) ? x[0] + dx : dx;
404                         y[0] = (relative) ? y[0] + dy : dy;
405                         
406
407                         
408                         Debug("mmoveto %f,%f", Float(x[0]),Float(y[0]));
409                         command = (command == "m") ? "l" : "L";
410                 }
411                 else if (command == "c" || command == "C" || command == "q" || command == "Q")
412                 {
413                         Debug("Construct curveto command");
414                         Real dx = strtod(GetToken(d,token,i).c_str(),NULL)/bounds.w;
415                         assert(GetToken(d,token,i) == ",");
416                         Real dy = strtod(GetToken(d,token,i).c_str(),NULL)/bounds.h;
417                         
418                         x[1] = (relative) ? x[0] + dx : dx;
419                         y[1] = (relative) ? y[0] + dy : dy;
420                         
421                         dx = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.w;
422                         assert(GetToken(d,token,i) == ",");
423                         dy = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.h;
424                         
425                         x[2] = (relative) ? x[0] + dx : dx;
426                         y[2] = (relative) ? y[0] + dy : dy;
427                         
428                         if (command != "q" && command != "Q")
429                         {
430                                 dx = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.w;
431                                 assert(GetToken(d,token,i) == ",");
432                                 dy = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.h;
433                                 x[3] = (relative) ? x[0] + dx : dx;
434                                 y[3] = (relative) ? y[0] + dy : dy;
435                         }
436                         else
437                         {
438                                 x[3] = x[2];
439                                 y[3] = y[2];
440                                 Real old_x1(x[1]), old_y1(y[1]);
441                                 x[1] = x[0] + Real(2) * (old_x1 - x[0])/ Real(3);
442                                 y[1] = y[0] + Real(2) * (old_y1 - y[0])/ Real(3);
443                                 x[2] = x[3] + Real(2) * (old_x1 - x[3])/ Real(3);
444                                 y[2] = y[3] + Real(2) * (old_y1 - y[3])/ Real(3);
445                         }
446                         
447                         unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
448                         Add(BEZIER,Rect(0,0,1,1),index);
449                         
450                         
451                         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]));
452                         
453                         x[0] = x[3];
454                         y[0] = y[3];
455
456                         
457                 }
458                 else if (command == "l" || command == "L")
459                 {
460                         Debug("Construct lineto command");
461                 
462                         Real dx = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.w;
463                         assert(GetToken(d,token,i) == ",");
464                         Real dy = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.h;
465                         
466                         x[1] = (relative) ? x[0] + dx : dx;
467                         y[1] = (relative) ? y[0] + dy : dy;
468                         
469                         x[2] = x[1];
470                         y[2] = y[1];
471                         
472                         x[3] = x[1];
473                         y[3] = y[1];
474
475                         unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
476                         Add(BEZIER,Rect(0,0,1,1),index);
477                         
478                         Debug("[%u] lineto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
479                         
480                         x[0] = x[3];
481                         y[0] = y[3];
482
483                 }
484                 else if (command == "z" || command == "Z")
485                 {
486                         Debug("Construct returnto command");
487                         x[1] = x0;
488                         y[1] = y0;
489                         x[2] = x0;
490                         y[2] = y0;
491                         x[3] = x0;
492                         y[3] = y0;
493                         
494                         unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
495                         Add(BEZIER,Rect(0,0,1,1),index);
496                         
497                         Debug("[%u] returnto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
498                         
499                         x[0] = x[3];
500                         y[0] = y[3];
501                         command = "m";
502                 }
503                 else
504                 {
505                         Warn("Unrecognised command \"%s\", set to \"m\"", command.c_str());
506                         command = "m";
507                 }
508                 
509                 if (!start)
510                 {
511                         x0 = x[0];
512                         y0 = y[0];
513                         start = true;
514                 }
515                 prev_i = i;
516         }
517 }
518
519 void Document::AddFontGlyphAtPoint(stbtt_fontinfo *font, int character, Real scale, Real x, Real y)
520 {
521         int glyph_index = stbtt_FindGlyphIndex(font, character);
522
523         // Check if there is actully a glyph to render.
524         if (stbtt_IsGlyphEmpty(font, glyph_index))
525         {
526                 return;
527         }
528
529         stbtt_vertex *instructions;
530         int num_instructions = stbtt_GetGlyphShape(font, glyph_index, &instructions);
531
532         Real current_x(0), current_y(0);
533
534         for (int i = 0; i < num_instructions; ++i)
535         {
536                 // TTF uses 16-bit signed ints for coordinates:
537                 // with the y-axis inverted compared to us.
538                 // Convert and scale any data.
539                 Real inst_x = Real(instructions[i].x)*scale;
540                 Real inst_y = Real(instructions[i].y)*-scale;
541                 Real inst_cx = Real(instructions[i].cx)*scale;
542                 Real inst_cy = Real(instructions[i].cy)*-scale;
543                 Real old_x(current_x), old_y(current_y);
544                 current_x = inst_x;
545                 current_y = inst_y;
546                 unsigned bezier_index;
547                 switch(instructions[i].type)
548                 {
549                 // Move To
550                 case STBTT_vmove:
551                         break;
552                 // Line To
553                 case STBTT_vline:
554                         bezier_index = AddBezierData(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));
555                         Add(BEZIER,Rect(0,0,1,1),bezier_index);
556                         break;
557                 // Quadratic Bezier To:
558                 case STBTT_vcurve:
559                         // Quadratic -> Cubic:
560                         // - Endpoints are the same.
561                         // - cubic1 = quad0+(2/3)*(quad1-quad0)
562                         // - cubic2 = quad2+(2/3)*(quad1-quad2)
563                         bezier_index = AddBezierData(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,
564                                                 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));
565                         Add(BEZIER,Rect(0,0,1,1),bezier_index);
566                         break;
567                 }
568         }
569
570         stbtt_FreeShape(font, instructions);
571 }

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