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

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