c97aa56ee3cc0c7355d66232d54a680889d7e8a3
[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, 1, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QTC_UNKNOWN, 0, 1});
94         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QTC_UNKNOWN, 1, ObjectCount()});
95         m_quadtree.root_id = 0;
96 }
97
98 QuadTreeIndex Document::GenQuadNode(QuadTreeIndex parent, QuadTreeNodeChildren type)
99 {
100         QuadTreeIndex new_index = m_quadtree.nodes.size();
101         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, parent, type, 0, 0});
102
103         m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
104         for (unsigned i = m_quadtree.nodes[parent].object_begin; i < m_quadtree.nodes[parent].object_end; ++i)
105         {
106                 if (ContainedInQuadChild(m_objects.bounds[i], type))
107                 {
108                         m_objects.bounds.push_back(TransformToQuadChild(m_objects.bounds[i], type));
109                         m_objects.types.push_back(m_objects.types[i]);
110                         m_objects.data_indices.push_back(m_objects.data_indices[i]);
111                 }
112         }
113         m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
114         switch (type)
115         {
116                 case QTC_TOP_LEFT:
117                         m_quadtree.nodes[parent].top_left = new_index;
118                         break;
119                 case QTC_TOP_RIGHT:
120                         m_quadtree.nodes[parent].top_right = new_index;
121                         break;
122                 case QTC_BOTTOM_LEFT:
123                         m_quadtree.nodes[parent].bottom_left = new_index;
124                         break;
125                 case QTC_BOTTOM_RIGHT:
126                         m_quadtree.nodes[parent].bottom_right = new_index;
127                         break;
128                 default:
129                         Fatal("Tried to add a QuadTree child of invalid type!");
130         }
131         return new_index;
132 }
133
134 #endif
135
136 void Document::Load(const string & filename)
137 {
138         m_objects.bounds.clear();
139         m_count = 0;
140         if (filename == "")
141         {
142                 Debug("Loaded empty document.");
143                 return;
144         }
145         Debug("Loading document from file \"%s\"", filename.c_str());
146         FILE * file = fopen(filename.c_str(), "r");
147         if (file == NULL)
148                 Fatal("Couldn't open file \"%s\"", filename.c_str(), strerror(errno));
149
150         size_t read;
151
152         DocChunkTypes chunk_type;
153         uint32_t chunk_size;
154         while (ReadChunkHeader(file, chunk_type, chunk_size))
155         {
156                 switch(chunk_type)
157                 {
158                 case CT_NUMOBJS:
159                         read = fread(&m_count, sizeof(m_count), 1, file);
160                         if (read != 1)
161                                 Fatal("Failed to read number of objects!");
162                         Debug("Number of objects: %u", ObjectCount());
163                         break;
164                 case CT_OBJTYPES:
165                         Debug("Object types...");
166                         LoadStructVector<ObjectType>(file, chunk_size/sizeof(ObjectType), m_objects.types);
167                         break;
168                 case CT_OBJBOUNDS:
169                         Debug("Object bounds...");
170                         LoadStructVector<Rect>(file, chunk_size/sizeof(Rect), m_objects.bounds);
171                         break;
172                 case CT_OBJINDICES:
173                         Debug("Object data indices...");
174                         LoadStructVector<unsigned>(file, chunk_size/sizeof(unsigned), m_objects.data_indices);
175                         break;
176                 case CT_OBJBEZIERS:
177                         Debug("Bezier data...");
178                         LoadStructVector<Bezier>(file, chunk_size/sizeof(Bezier), m_objects.beziers);
179                         break;
180                 }
181         }
182         Debug("Successfully loaded %u objects from \"%s\"", ObjectCount(), filename.c_str());
183 #ifndef QUADTREE_DISABLED
184         if (m_quadtree.root_id == QUADTREE_EMPTY)
185         {
186                 GenBaseQuadtree();
187         }
188 #endif
189 }
190
191 void Document::Add(ObjectType type, const Rect & bounds, unsigned data_index)
192 {
193         m_objects.types.push_back(type);
194         m_objects.bounds.push_back(bounds);
195         m_objects.data_indices.push_back(data_index);
196         ++m_count; // Why can't we just use the size of types or something?
197 }
198
199 unsigned Document::AddBezierData(const Bezier & bezier)
200 {
201         m_objects.beziers.push_back(bezier);
202         return m_objects.beziers.size()-1;
203 }
204
205
206 void Document::DebugDumpObjects()
207 {
208         Debug("Objects for Document %p are:", this);
209         for (unsigned id = 0; id < ObjectCount(); ++id)
210         {
211                 Debug("%u. \tType: %u\tBounds: %s", id, m_objects.types[id], m_objects.bounds[id].Str().c_str());
212         }
213 }
214
215 bool Document::operator==(const Document & equ) const
216 {
217         return (ObjectCount() == equ.ObjectCount() 
218                 && memcmp(m_objects.bounds.data(), equ.m_objects.bounds.data(), ObjectCount() * sizeof(Rect)) == 0
219                 && memcmp(m_objects.data_indices.data(), equ.m_objects.data_indices.data(), ObjectCount() * sizeof(unsigned)) == 0
220                 && memcmp(m_objects.beziers.data(), equ.m_objects.beziers.data(), m_objects.beziers.size() * sizeof(Bezier)) == 0);
221 }
222
223
224 #include "../contrib/pugixml-1.4/src/pugixml.hpp"
225 #include "../contrib/pugixml-1.4/src/pugixml.cpp"
226
227 void Document::LoadSVG(const string & filename, const Rect & bounds)
228 {
229         using namespace pugi;
230         
231         xml_document doc_xml;
232         ifstream input(filename.c_str(), ios_base::in);
233         xml_parse_result result = doc_xml.load(input);
234         
235         if (!result)
236                 Fatal("Couldn't load \"%s\" - %s", filename.c_str(), result.description());
237                 
238         Debug("Loaded XML - %s", result.description());
239         
240         input.close();
241
242         // Combine all SVG tags into one thing because lazy
243         for (xml_node svg : doc_xml.children("svg"))
244         {
245                 Real width = svg.attribute("width").as_float() * bounds.w;
246                 Real height = svg.attribute("width").as_float() * bounds.h;
247                 
248                 
249                 // Rectangles
250                 Real coords[4];
251                 const char * attrib_names[] = {"x", "y", "width", "height"};
252                 for (pugi::xml_node rect : svg.children("rect"))
253                 {
254                         for (size_t i = 0; i < 4; ++i)
255                                 coords[i] = rect.attribute(attrib_names[i]).as_float();
256                         
257                         bool outline = !(rect.attribute("fill"));
258                         Add(outline?RECT_OUTLINE:RECT_FILLED, Rect(coords[0]/width + bounds.x, coords[1]/height + bounds.y, coords[2]/width, coords[3]/height),0);
259                         Debug("Added rectangle");
260                 }               
261                 
262                 // Circles
263                 for (pugi::xml_node circle : svg.children("circle"))
264                 {
265                         Real cx = circle.attribute("cx").as_float();
266                         Real cy = circle.attribute("cy").as_float();
267                         Real r = circle.attribute("r").as_float();
268                         
269                         Real x = (cx - r)/width + bounds.x; 
270                         Real y = (cy - r)/height + bounds.y; 
271                         Real w = 2*r/width; 
272                         Real h = 2*r/height;
273                         
274                         Rect rect(x,y,w,h);
275                         Add(CIRCLE_FILLED, rect,0);
276                         Debug("Added Circle %s", rect.Str().c_str());
277
278                 }               
279                 
280                 // paths
281                 for (pugi::xml_node path : svg.children("path"))
282                 {
283                         
284                         string d = path.attribute("d").as_string();
285                         Debug("Path data attribute is \"%s\"", d.c_str());
286                         AddPathFromString(d, Rect(bounds.x,bounds.y,width,height));
287                         
288                 }
289         }
290         
291         //Fatal("Done");
292         
293         
294
295 }
296
297 // Behold my amazing tokenizing abilities
298 static string & GetToken(const string & d, string & token, unsigned & i)
299 {
300         token.clear();
301         while (i < d.size() && iswspace(d[i]))
302         {
303                 ++i;
304         }
305         
306         while (i < d.size())
307         {
308                 if (d[i] == ',' || isalpha(d[i]) || iswspace(d[i]))
309                 {
310                         if (token.size() == 0 && !iswspace(d[i]))
311                         {
312                                 token += d[i++];
313                         }
314                         break;  
315                 }
316                 token += d[i++];
317         }
318         Debug("Got token \"%s\"", token.c_str());
319         return token;
320 }
321
322
323 // Fear the wrath of the tokenizing svg data
324 // Seriously this isn't really very DOM-like at all is it?
325 void Document::AddPathFromString(const string & d, const Rect & bounds)
326 {
327         Real x[3] = {0,0,0};
328         Real y[3] = {0,0,0};
329         
330         string token("");
331         string command("m");
332         
333         unsigned i = 0;
334         unsigned prev_i = 0;
335         Real x0;
336         Real y0;
337         bool started = false;
338         while (i < d.size() && GetToken(d, token, i).size() > 0)
339         {
340                 if (isalpha(token[0]))
341                         command = token;
342                 else
343                 {
344                         i = prev_i; // hax
345                         if(command == "")
346                                 command = "l";
347                 }
348                         
349                 if (command == "m")
350                 {
351                         Debug("Construct moveto command");
352                         x[0] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.w;
353                         assert(GetToken(d,token,i) == ",");
354                         y[0] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.h;
355                         if (!started)
356                         {
357                                 x0 = x[0];
358                                 y0 = y[0];
359                                 started = true;
360                         }
361                         Debug("mmoveto %f,%f", Float(x[0]),Float(y[0]));
362                         command = "l";
363                 }
364                 else if (command == "c")
365                 {
366                         Debug("Construct curveto command");
367                         x[0] = strtod(GetToken(d,token,i).c_str(),NULL)/bounds.w;
368                         assert(GetToken(d,token,i) == ",");
369                         y[0] = strtod(GetToken(d,token,i).c_str(),NULL)/bounds.h;
370                         
371                         x[1] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.w;
372                         assert(GetToken(d,token,i) == ",");
373                         y[1] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.h;
374                         
375                         x[2] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.w;
376                         assert(GetToken(d,token,i) == ",");
377                         y[2] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.h;
378                         
379                         unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2]));
380                         Add(BEZIER,bounds,index);
381                         
382                         
383                         Debug("[%u] curveto %f,%f %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]),Float(x[2]),Float(y[2]));
384                         
385                         x[0] = x[2];
386                         y[0] = y[2];
387
388                         
389                 }
390                 else if (command == "l")
391                 {
392                         Debug("Construct lineto command");
393                 
394                         x[1] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.w;
395                         assert(GetToken(d,token,i) == ",");
396                         y[1] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.h;
397                         
398                         x[2] = x[1];
399                         y[2] = y[1];
400                         
401                         unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2]));
402                         Add(BEZIER,bounds,index);
403                         
404                         Debug("[%u] lineto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
405                         
406                         x[0] = x[2];
407                         y[0] = y[2];
408
409                 }
410                 else if (command == "z")
411                 {
412                         Debug("Construct returnto command");
413                         x[1] = x0;
414                         y[1] = y0;
415                         x[2] = x0;
416                         y[2] = y0;
417                         
418                         unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2]));
419                         Add(BEZIER,bounds,index);
420                         
421                         Debug("[%u] returnto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
422                         
423                         x[0] = x[2];
424                         y[0] = y[2];
425                         command = "m";
426                 }
427                 else
428                 {
429                         Warn("Unrecognised command \"%s\", set to \"m\"", command.c_str());
430                         command = "m";
431                 }
432                 prev_i = i;
433         }
434 }

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