6 #include "stb_truetype.h"
11 //TODO: Make this work for variable sized Reals
13 // Loads an std::vector<T> of size num_elements from a file.
15 static void LoadStructVector(FILE *src_file, size_t num_elems, std::vector<T>& dest)
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);
24 // Saves an std::vector<T> to a file. Size must be saves separately.
26 static void SaveStructVector(FILE *dst_file, std::vector<T>& src)
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());
34 static void WriteChunkHeader(FILE *dst_file, DocChunkTypes type, uint32_t size)
37 written = fwrite(&type, sizeof(type), 1, dst_file);
39 Fatal("Could not write Chunk header! (ID)");
40 written = fwrite(&size, sizeof(size), 1, dst_file);
42 Fatal("Could not write Chunk header (size)!");
45 static bool ReadChunkHeader(FILE *src_file, DocChunkTypes& type, uint32_t& size)
47 if (fread(&type, sizeof(DocChunkTypes), 1, src_file) != 1)
49 if (fread(&size, sizeof(uint32_t), 1, src_file) != 1)
54 void Document::Save(const string & filename)
56 Debug("Saving document to file \"%s\"...", filename.c_str());
57 FILE * file = fopen(filename.c_str(), "w");
59 Fatal("Couldn't open file \"%s\" - %s", filename.c_str(), strerror(errno));
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);
66 Fatal("Failed to write number of objects!");
68 Debug("Object types...");
69 WriteChunkHeader(file, CT_OBJTYPES, m_objects.types.size() * sizeof(ObjectType));
70 SaveStructVector<ObjectType>(file, m_objects.types);
72 Debug("Object bounds...");
73 WriteChunkHeader(file, CT_OBJBOUNDS, m_objects.bounds.size() * sizeof(Rect));
74 SaveStructVector<Rect>(file, m_objects.bounds);
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);
80 Debug("Bezier data...");
81 WriteChunkHeader(file, CT_OBJBEZIERS, m_objects.beziers.size() * sizeof(uint8_t));
82 SaveStructVector<Bezier>(file, m_objects.beziers);
84 int err = fclose(file);
86 Fatal("Failed to close file \"%s\" - %s", filename.c_str(), strerror(err));
88 Debug("Successfully saved %u objects to \"%s\"", ObjectCount(), filename.c_str());
91 #ifndef QUADTREE_DISABLED
93 void Document::GenBaseQuadtree()
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);
101 QuadTreeIndex Document::GenQuadChild(QuadTreeIndex parent, QuadTreeNodeChildren type)
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});
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)
109 if (ContainedInQuadChild(m_objects.bounds[i], type))
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]);
117 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
121 m_quadtree.nodes[parent].top_left = new_index;
124 m_quadtree.nodes[parent].top_right = new_index;
126 case QTC_BOTTOM_LEFT:
127 m_quadtree.nodes[parent].bottom_left = new_index;
129 case QTC_BOTTOM_RIGHT:
130 m_quadtree.nodes[parent].bottom_right = new_index;
133 Fatal("Tried to add a QuadTree child of invalid type!");
138 // Reparent a quadtree node, making it the "type" child of a new node.
139 QuadTreeIndex Document::GenQuadParent(QuadTreeIndex child, QuadTreeNodeChildren type)
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});
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)
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]);
152 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
156 m_quadtree.nodes[new_index].top_left = child;
159 m_quadtree.nodes[new_index].top_right = child;
161 case QTC_BOTTOM_LEFT:
162 m_quadtree.nodes[new_index].bottom_left = child;
164 case QTC_BOTTOM_RIGHT:
165 m_quadtree.nodes[new_index].bottom_right = child;
168 Fatal("Tried to add a QuadTree child of invalid type!");
175 void Document::Load(const string & filename)
177 m_objects.bounds.clear();
181 Debug("Loaded empty document.");
184 Debug("Loading document from file \"%s\"", filename.c_str());
185 FILE * file = fopen(filename.c_str(), "r");
187 Fatal("Couldn't open file \"%s\"", filename.c_str(), strerror(errno));
191 DocChunkTypes chunk_type;
193 while (ReadChunkHeader(file, chunk_type, chunk_size))
198 read = fread(&m_count, sizeof(m_count), 1, file);
200 Fatal("Failed to read number of objects!");
201 Debug("Number of objects: %u", ObjectCount());
204 Debug("Object types...");
205 LoadStructVector<ObjectType>(file, chunk_size/sizeof(ObjectType), m_objects.types);
208 Debug("Object bounds...");
209 LoadStructVector<Rect>(file, chunk_size/sizeof(Rect), m_objects.bounds);
212 Debug("Object data indices...");
213 LoadStructVector<unsigned>(file, chunk_size/sizeof(unsigned), m_objects.data_indices);
216 Debug("Bezier data...");
217 LoadStructVector<Bezier>(file, chunk_size/sizeof(Bezier), m_objects.beziers);
221 Debug("Successfully loaded %u objects from \"%s\"", ObjectCount(), filename.c_str());
222 #ifndef QUADTREE_DISABLED
223 if (m_quadtree.root_id == QUADTREE_EMPTY)
230 void Document::Add(ObjectType type, const Rect & bounds, unsigned data_index)
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?
238 unsigned Document::AddBezierData(const Bezier & bezier)
240 m_objects.beziers.push_back(bezier);
241 return m_objects.beziers.size()-1;
245 void Document::DebugDumpObjects()
247 Debug("Objects for Document %p are:", this);
248 for (unsigned id = 0; id < ObjectCount(); ++id)
250 Debug("%u. \tType: %u\tBounds: %s", id, m_objects.types[id], m_objects.bounds[id].Str().c_str());
254 bool Document::operator==(const Document & equ) const
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);
263 #include "../contrib/pugixml-1.4/src/pugixml.hpp"
264 #include "../contrib/pugixml-1.4/src/pugixml.cpp"
267 * Load an SVG into a rectangle
269 void Document::LoadSVG(const string & filename, const Rect & bounds)
271 using namespace pugi;
273 xml_document doc_xml;
274 ifstream input(filename.c_str(), ios_base::in);
275 xml_parse_result result = doc_xml.load(input);
278 Fatal("Couldn't load \"%s\" - %s", filename.c_str(), result.description());
280 Debug("Loaded XML - %s", result.description());
284 // Combine all SVG tags into one thing because lazy
285 for (xml_node svg : doc_xml.children("svg"))
287 Real width = svg.attribute("width").as_float() * bounds.w;
288 Real height = svg.attribute("width").as_float() * bounds.h;
293 const char * attrib_names[] = {"x", "y", "width", "height"};
294 for (pugi::xml_node rect : svg.children("rect"))
296 for (size_t i = 0; i < 4; ++i)
297 coords[i] = rect.attribute(attrib_names[i]).as_float();
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");
305 for (pugi::xml_node circle : svg.children("circle"))
307 Real cx = circle.attribute("cx").as_float();
308 Real cy = circle.attribute("cy").as_float();
309 Real r = circle.attribute("r").as_float();
311 Real x = (cx - r)/width + bounds.x;
312 Real y = (cy - r)/height + bounds.y;
317 Add(CIRCLE_FILLED, rect,0);
318 Debug("Added Circle %s", rect.Str().c_str());
323 for (pugi::xml_node path : svg.children("path"))
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));
339 // Behold my amazing tokenizing abilities
340 static string & GetToken(const string & d, string & token, unsigned & i)
343 while (i < d.size() && iswspace(d[i]))
350 if (d[i] == ',' || (isalpha(d[i]) && d[i] != 'e') || iswspace(d[i]))
352 if (token.size() == 0 && !iswspace(d[i]))
360 Debug("Got token \"%s\"", token.c_str());
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)
369 Real x[4] = {0,0,0,0};
370 Real y[4] = {0,0,0,0};
383 while (i < d.size() && GetToken(d, token, i).size() > 0)
385 if (isalpha(token[0]))
394 bool relative = islower(command[0]);
396 if (command == "m" || command == "M")
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;
403 x[0] = (relative) ? x[0] + dx : dx;
404 y[0] = (relative) ? y[0] + dy : dy;
408 Debug("mmoveto %f,%f", Float(x[0]),Float(y[0]));
409 command = (command == "m") ? "l" : "L";
411 else if (command == "c" || command == "C" || command == "q" || command == "Q")
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;
418 x[1] = (relative) ? x[0] + dx : dx;
419 y[1] = (relative) ? y[0] + dy : dy;
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;
425 x[2] = (relative) ? x[0] + dx : dx;
426 y[2] = (relative) ? y[0] + dy : dy;
428 if (command != "q" && command != "Q")
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;
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);
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);
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]));
458 else if (command == "l" || command == "L")
460 Debug("Construct lineto command");
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;
466 x[1] = (relative) ? x[0] + dx : dx;
467 y[1] = (relative) ? y[0] + dy : dy;
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);
478 Debug("[%u] lineto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
484 else if (command == "z" || command == "Z")
486 Debug("Construct returnto command");
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);
497 Debug("[%u] returnto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
505 Warn("Unrecognised command \"%s\", set to \"m\"", command.c_str());
519 void Document::AddFontGlyphAtPoint(stbtt_fontinfo *font, int character, Real scale, Real x, Real y)
521 int glyph_index = stbtt_FindGlyphIndex(font, character);
523 // Check if there is actully a glyph to render.
524 if (stbtt_IsGlyphEmpty(font, glyph_index))
529 stbtt_vertex *instructions;
530 int num_instructions = stbtt_GetGlyphShape(font, glyph_index, &instructions);
532 Real current_x(0), current_y(0);
534 for (int i = 0; i < num_instructions; ++i)
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);
546 unsigned bezier_index;
547 switch(instructions[i].type)
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);
557 // Quadratic Bezier To:
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);
570 stbtt_FreeShape(font, instructions);