├── .gitignore ├── Circles.png ├── Helpers.cpp ├── Makefile ├── Model.cpp ├── Notes ├── Objective.cpp ├── Packing.png ├── PhiFunc.cpp ├── PhiObj.cpp ├── README.md ├── SpecialPrimitives.nb ├── Struct.cpp ├── Transform.cpp ├── Visualisation.nb ├── XMLInterface.cpp ├── dNLP.cpp ├── examplegen.cpp ├── gQP.cpp ├── main.cpp ├── makeGRB ├── sol.xml ├── test.xml ├── tinyxml2.cpp └── tinyxml2.h /.gitignore: -------------------------------------------------------------------------------- 1 | packer 2 | examplegen 3 | out.xml 4 | *.o 5 | -------------------------------------------------------------------------------- /Circles.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Athlici/Packing/4286683735f823d0ab10b907ba0aadbb08e5692f/Circles.png -------------------------------------------------------------------------------- /Helpers.cpp: -------------------------------------------------------------------------------- 1 | //convert a point in XML into an object 2 | point toPoint(XMLElement* p){ 3 | double x,y; 4 | p->QueryDoubleAttribute("x",&x); 5 | p->QueryDoubleAttribute("y",&y); 6 | return point(x,y); 7 | }; 8 | 9 | //convert a circle in XML into an object 10 | circle toCircle(XMLElement* c,double s=1){ 11 | double r; 12 | c->QueryDoubleAttribute("r",&r); 13 | return circle(toPoint(c),(s*r>0)?r:-r); 14 | } 15 | 16 | //tuple importXML(string filepath){} 17 | //void exportXML(xmlPkg,solution){} 18 | 19 | //construct a parallel line with distance r 20 | tuple moveLine(point p0,point p1,double r){ 21 | double dx = p0.x-p1.x, dy = p0.y-p1.y; 22 | double c = r/sqrt(dx*dx+dy*dy); 23 | return tuple(point(p0.x-dy*c,p0.y+dx*c), 24 | point(p1.x-dy*c,p1.y+dx*c)); 25 | } 26 | 27 | #ifdef IPOPT 28 | //find the bounding circle of an object with Ipopt 29 | circle boundCircMod(SmartPtr app, PhiCompObj* A){ 30 | Objective* obj = new FirstVar(); 31 | vector vars = {var(0,2e19),var(-2e19,2e19),var(-2e19,2e19),var(0,0,true)}; 32 | 33 | Scale f = Scale(0); 34 | RotTrans g = RotTrans(1); 35 | PhiInfObj* C = new PhiCircCompl(circle(point(0,0),1)); 36 | PhiFunc* phi = phiFunc(C,f,A,g); 37 | 38 | double x[] = {1,0,0,0}; 39 | while(phi->eval(x)<0) 40 | x[0]*=2; 41 | 42 | bool newseg; 43 | do{ 44 | SmartPtr nlp = new dNLP(obj,vars,phi->getIneqs(x),x); 45 | app->OptimizeTNLP(nlp); 46 | newseg = (nlp->res[0] < x[0]) && (phi->getIneqs(x) != phi->getIneqs(nlp->res)); 47 | for(int i=0;i<3;i++) x[i] = nlp->res[i]; 48 | }while(newseg); 49 | 50 | return circle(point(x[1],x[2]),x[0]); 51 | } 52 | #endif 53 | 54 | #ifdef GUROBI 55 | //find the bounding circle of an object with GUROBI 56 | circle boundCircMod(GRBEnv env, PhiCompObj* A){ 57 | Objective* obj = new FirstVar(); 58 | vector vars = {var(0,2e19),var(-2e19,2e19),var(-2e19,2e19),var(0,0,true)}; 59 | 60 | Scale f = Scale(0); 61 | RotTrans g = RotTrans(1); 62 | PhiInfObj* C = new PhiCircCompl(circle(point(0,0),1)); 63 | PhiFunc* phi = phiFunc(C,f,A,g); 64 | 65 | double x[] = {1,0,0,0}; 66 | while(phi->eval(x)<0) 67 | x[0]*=2; 68 | 69 | bool newseg; 70 | // do{ 71 | try{ 72 | gQP* nlp = new gQP(env,obj,vars,phi->getIneqs(x)); 73 | nlp->optimize(); 74 | newseg = (nlp->res[0] < x[0]) && (phi->getIneqs(x) != phi->getIneqs(nlp->res)); 75 | for(int i=0;i<3;i++) x[i] = nlp->res[i]; 76 | } catch(GRBException e) { 77 | std::cout << "Error code = " << e.getErrorCode() << std::endl; 78 | std::cout << e.getMessage() << std::endl; 79 | } 80 | // }while(newseg); 81 | 82 | return circle(point(x[1],x[2]),x[0]); 83 | } 84 | #endif 85 | 86 | //pack circles by iteratively placing them in the first free position of a path 87 | vector circlePack(vector cr){ 88 | int n = cr.size(); 89 | vector> chain(n); 90 | chain[0] = {circle(point(-cr[0],0),cr[0]),0}; 91 | chain[1] = {circle(point( cr[1],0),cr[1]),1}; 92 | 93 | for(int i=2;i(chain[j]), c2 = get<0>(chain[(j+1)%i]); 97 | double x1=c1.p.x, y1=c1.p.y, r1=c1.r, x2=c2.p.x, y2=c2.p.y, r2=c2.r, r=cr[i]; 98 | double dx=x1-x2, dy=y1-y2, dr=r1-r2, dx2=dx*dx, dy2=dy*dy, sr=r1+r2+2*r; 99 | double n1 = sqrt((dx2+dy2-dr*dr)*(sr*sr-dx2-dy2)), n2 = dx2+dy2; 100 | point pos = point((x1+x2-(n1*dy+dr*sr*dx)/n2)/2,(y1+y2+(n1*dx-dr*sr*dy)/n2)/2); 101 | 102 | bool placeable = true; 103 | for(int k=0;k(chain[k]); 105 | dx = pos.x-tmp.p.x, dy = pos.y-tmp.p.y, sr = r+tmp.r; 106 | placeable = dx*dx+dy*dy-sr*sr > -1e-8; 107 | } 108 | if(placeable){ 109 | for(int k=i-1;k>j;k--) 110 | chain[k+1]=chain[k]; 111 | chain[j+1] = {circle(pos,r),i}; 112 | unplaced = false; 113 | } 114 | } 115 | } 116 | 117 | vector res(n); 118 | for(int i=0;i tmp = chain[i]; 120 | res[get<1>(tmp)] = get<0>(tmp).p; 121 | } 122 | return res; 123 | } 124 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CXXFLAGS= -std=c++1z -Ofast 2 | 3 | release: main.o tinyxml2.o 4 | g++ $(CXXFLAGS) -lipopt -o packer tinyxml2.o main.o 5 | 6 | debug: main.o tinyxml2.o 7 | g++ $(CXXFLAGS) -ggdb -lipopt -o packer tinyxml2.o main.o 8 | 9 | examplegen: tinyxml2.o 10 | g++ -o examplegen tinyxml2.o examplegen.cpp 11 | 12 | main.o: *.cpp 13 | g++ $(CXXFLAGS) -c main.cpp 14 | 15 | tinyxml2.o: tinyxml2.cpp 16 | g++ $(CXXFLAGS) -c tinyxml2.cpp 17 | 18 | clean: 19 | rm -f *.o packer 20 | -------------------------------------------------------------------------------- /Model.cpp: -------------------------------------------------------------------------------- 1 | //class to store the complete problem 2 | class Model{ 3 | public: 4 | vector vars; //variables 5 | Objective* f; //objective funtion 6 | vector C; //container object (union of primitive objects) 7 | Scale sc = 0; //container modification function TODO: make more general 8 | vector objs; //list of objects that shall be fitted 9 | vector rt; //list of their transformations 10 | 11 | Model() {}; 12 | 13 | //generate the no-fit constraints 14 | PhiFunc* createPhiFunc(){ 15 | int n = objs.size(),m = C.size(); 16 | vector comp(n*(n-1)/2+n*m); 17 | //must lie inside the container 18 | for(int i=0;i> getF() = 0; 16 | }; 17 | 18 | //optimize the value of the first variable, for example for scaling 19 | class FirstVar: public Objective{ 20 | public: 21 | FirstVar(){}; 22 | Number eval(Index n, const Number* x){ 23 | return x[0]; 24 | } 25 | 26 | void grad(Index n, const Number* x, Number* grad){ 27 | grad[0] = 1; 28 | for(int i=1;i> getF(){ 32 | return {{0,1,1}}; 33 | } 34 | 35 | }; 36 | -------------------------------------------------------------------------------- /Packing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Athlici/Packing/4286683735f823d0ab10b907ba0aadbb08e5692f/Packing.png -------------------------------------------------------------------------------- /PhiFunc.cpp: -------------------------------------------------------------------------------- 1 | class PhiFuncPrim; 2 | 3 | tuple moveLine(point,point,double); 4 | 5 | class PhiFunc{ 6 | static double sign(double x){return ((x>=0) ? 1 : -1);} 7 | public: 8 | virtual double eval(const double* x) = 0; 9 | virtual vector getIneqs(const double* x) = 0; 10 | virtual vector getIndices(const double* x) = 0; 11 | virtual vector print(const double* x) = 0; 12 | 13 | static PhiFunc* phiFunc(point,point,RotTrans,point ,RotTrans); 14 | static PhiFunc* phiFunc(point,point,RotTrans,circle,RotTrans); 15 | static PhiFunc* phiFunc(circle,RotTrans,point ,RotTrans); 16 | static PhiFunc* phiFunc(circle,RotTrans,circle,RotTrans); 17 | static PhiFunc* phiFunc(circle,Scale,point ,RotTrans); 18 | static PhiFunc* phiFunc(circle,Scale,circle,RotTrans); 19 | static PhiFunc* phiFunc(point,point,Scale,point ,RotTrans); 20 | static PhiFunc* phiFunc(point,point,Scale,circle,RotTrans); 21 | static PhiFunc* phiFunc(circle,RotTrans,circle,point,RotTrans,double); 22 | static PhiFunc* phiFunc(circle,Scale ,circle,point,RotTrans,double); 23 | }; 24 | 25 | class PhiFuncPrim: public PhiFunc{ 26 | public: 27 | //0->no var, i/-i->(i-1)th var (cos) 28 | //constant -> (0,0), linear -> (0,i), quadratic -> (i,j) 29 | virtual vector> getF() = 0; 30 | virtual void getD1(const double* x,double* res) = 0; 31 | virtual vector getD1ind() = 0; 32 | virtual void getD2(const double* x,double* res) = 0; 33 | virtual vector> getD2ind() = 0; 34 | vector getIneqs (const double* x){return {this};} 35 | vector getIndices (const double* x){return {};} 36 | }; 37 | 38 | class PhiFuncNode: public PhiFunc{ 39 | bool sense; //0 -> max,1 -> min 40 | vector nodes; 41 | 42 | int argmax(const double* x){ 43 | int ind = 0; 44 | double val = nodes[0]->eval(x); 45 | for(int i=1;ieval(x); 47 | if(tmp>val){ 48 | val = tmp; 49 | ind = i; 50 | } 51 | } 52 | return ind; 53 | } 54 | 55 | public: 56 | PhiFuncNode(bool s,vector n) : sense(s),nodes(n) {}; 57 | 58 | double eval(const double* x){ 59 | double res = nodes[0]->eval(x); 60 | for(int i=1;ieval(x); 62 | if(sense ^ (tmp>res)) 63 | res=tmp; 64 | } 65 | return res; 66 | } 67 | 68 | vector getIneqs(const double* x){ 69 | if(sense){ 70 | vector res = {}; 71 | for(int i=0;i tmp = nodes[i]->getIneqs(x); 73 | res.insert(res.end(),tmp.begin(),tmp.end()); 74 | } 75 | return res; 76 | } else 77 | return nodes[argmax(x)]->getIneqs(x); 78 | } 79 | 80 | vector getIndices(const double* x){ 81 | if(sense){ 82 | vector res = {}; 83 | for(int i=0;i tmp = nodes[i]->getIndices(x); 85 | res.insert(res.end(),tmp.begin(),tmp.end()); 86 | } 87 | return res; 88 | } else { 89 | int ind = argmax(x); 90 | vector res = nodes[ind]->getIndices(x); 91 | res.push_back(ind); 92 | return res; 93 | } 94 | } 95 | 96 | vector print(const double* x){ 97 | vector out = {string(sense?"Min":"Max") + "-Node : " + std::to_string(eval(x))}; 98 | for(int i=0;i tmp = nodes[i]->print(x); 100 | out.push_back("-" + tmp[0]); 101 | for(int j=1;j> getF(){ 131 | return {{0,i+1,trs[0]},{0,j+1,trs[1]},{0,j+2,trs[2]},{0,j+3,rot[0]},{0,-j-3,rot[1]},{0,0,o}}; 132 | } 133 | 134 | vector print(const double* x){ 135 | return {"LnScClRt : " + std::to_string(eval(x))}; 136 | } 137 | 138 | void getD1(const double* x,double* res){ 139 | Vector2d g(cos(x[j+2]),-sin(x[j+2])); 140 | res[0] = trs[0]; res[1] = trs[1]; res[2] = trs[2]; 141 | res[3] = rot*g; 142 | } 143 | 144 | vector getD1ind(){ 145 | return {i,j,j+1,j+2}; 146 | } 147 | 148 | void getD2(const double* x,double* res){ 149 | Vector2d g(sin(x[j+2]),cos(x[j+2])); 150 | res[0] = -rot*g; 151 | } 152 | 153 | vector> getD2ind(){ 154 | return {{j+2,j+2}}; 155 | } 156 | }; 157 | 158 | class PhiFuncCcScClRt : public PhiFuncPrim{ 159 | double cd(circle c){ //Circle Distance 160 | return c.r*c.r-c.p.x*c.p.x-c.p.y*c.p.y; 161 | } 162 | Matrix3d A; 163 | double m,b; 164 | int i,j; 165 | 166 | public: 167 | PhiFuncCcScClRt(circle cc,Scale f,circle c,RotTrans g){ 168 | double xc=cc.p.x, yc=cc.p.y, px=c.p.x, py=c.p.y; 169 | A << cd(cc)/2, xc, yc, 170 | px*yc-py*xc, py,-px, 171 | px*xc+py*yc,-px,-py; 172 | A *= 2; m = -2*cc.r*c.r; b = cd(c); 173 | i = f.ind; j = g.ind; 174 | } 175 | 176 | double eval(const double* x){ 177 | RowVector3d f(x[i],sin(x[j+2]),cos(x[j+2])); 178 | Vector3d g(x[i],x[j],x[j+1]); 179 | return f*A*g-g[1]*g[1]-g[2]*g[2]+m*x[i]+b; 180 | } 181 | 182 | vector> getF(){ 183 | return {{ i+1,i+1,A(0,0)},{ i+1,j+1,A(0,1)},{ i+1,j+2,A(0,2)}, 184 | { j+3,i+1,A(1,0)},{ j+3,j+1,A(1,1)},{ j+3,j+2,A(1,2)}, 185 | {-j-3,i+1,A(2,0)},{-j-3,j+1,A(2,1)},{-j-3,j+2,A(2,2)}, 186 | {j+1,j+1,-1},{j+2,j+2,-1},{0,i+1,m},{0,0,b}}; 187 | } 188 | 189 | vector print(const double* x){ 190 | return {"CcScClRt : " + std::to_string(eval(x))}; 191 | } 192 | 193 | vector getD1ind(){ 194 | return {i,j,j+1,j+2}; 195 | } 196 | 197 | void getD1(const double* x,double* res){ 198 | RowVector3d f(x[i],sin(x[j+2]),cos(x[j+2])),fA=f*A; 199 | Vector3d g(x[i],x[j],x[j+1]),Ag=A*g; 200 | res[0] = fA[0]+Ag[0]+m; 201 | res[1] = fA[1]-2*g[1]; 202 | res[2] = fA[2]-2*g[2]; 203 | res[3] = f[2]*Ag[1]-f[1]*Ag[2]; 204 | } 205 | 206 | vector> getD2ind(){ 207 | if(i A; 227 | double b; 228 | int i,j; 229 | 230 | public: 231 | PhiFuncHCcScClRt(circle cc,Scale f,circle c,point p,RotTrans g,double s){ 232 | double ox=cc.p.x, oy=cc.p.y, cx=c.p.x, cy=c.p.y; 233 | A << ox*(cx-p.x)+oy*(cy-p.y),ox*(cy-p.y)+oy*(p.x-cx),p.x-cx,p.y-cy,p.y-cy,cx-p.x; 234 | b = s*(cx*p.y-cy*p.x); A*=s; 235 | i = f.ind; j = g.ind; 236 | } 237 | 238 | double eval(const double* x){ 239 | RowVector3d f(x[i],x[j],x[j+1]); 240 | Vector2d g(sin(x[j+2]),cos(x[j+2])); 241 | return f*A*g+b; 242 | } 243 | 244 | vector> getF(){ 245 | return {{i+1,j+3,A(0,0)},{i+1,-j-3,A(0,1)}, 246 | {j+1,j+3,A(1,0)},{j+1,-j-3,A(1,1)}, 247 | {j+2,j+3,A(2,0)},{j+2,-j-3,A(2,1)},{0,0,b}}; 248 | } 249 | 250 | vector print(const double* x){ 251 | return {"HCcScClRt : " + std::to_string(eval(x))}; 252 | } 253 | 254 | vector getD1ind(){ 255 | return {i,j,j+1,j+2}; 256 | } 257 | 258 | void getD1(const double* x,double* res){ 259 | Vector2d g(sin(x[j+2]),cos(x[j+2])),dg(g[1],-g[0]); 260 | Vector3d Ag=A*g; 261 | RowVector3d f(x[i],x[j],x[j+1]); 262 | res[0] = Ag[0]; res[1] = Ag[1]; res[2] = Ag[2]; 263 | res[3] = f*A*dg; 264 | } 265 | 266 | vector> getD2ind(){ 267 | if(i> getF(){ 298 | return {{i+1,j+3,A(0,0)},{j+1,j+3,-A(0,0)},{i+1,-j-3,A(0,1)},{j+1,-j-3,-A(0,1)}, 299 | {i+2,j+3,A(1,0)},{j+2,j+3,-A(1,0)},{i+2,-j-3,A(1,1)},{j+2,-j-3,-A(1,1)}, 300 | {i+3,j+3,B(0,0)},{i+3,-j-3,B(0,1)},{-i-3,j+3,B(1,0)},{-i-3,-j-3,B(1,1)},{0,0,c}}; 301 | } 302 | 303 | vector print(const double* x){ 304 | return {"RtRtMdfg : " + std::to_string(eval(x)) 305 | + " " + std::to_string(i) + " " + std::to_string(j)}; 306 | } 307 | 308 | vector getD1ind(){ 309 | return {i,i+1,i+2,j,j+1,j+2}; 310 | } 311 | 312 | void getD1(const double* x,double* res){ 313 | RowVector2d f1(sin(x[i+2]),cos(x[i+2])),f1d(f1[1],-f1[0]); 314 | Vector2d f2(sin(x[j+2]),cos(x[j+2])),f2d(f2[1],-f2[0]); 315 | RowVector2d y(x[i]-x[j],x[i+1]-x[j+1]); 316 | Vector2d Af2 = A*f2; 317 | double tmp[] = {Af2[0],Af2[1],f1d*B*f2,-Af2[0],-Af2[1],(y*A+f1*B)*f2d}; 318 | for(int i=0;i<6;i++) res[i] = tmp[i]; 319 | } 320 | 321 | vector> getD2ind(){ 322 | if(i> getF(){ 362 | return {{i+1,i+1,s},{i+1,j+1,-2*s},{j+1,j+1,s},{i+2,i+2,s},{i+2,j+2,-2*s},{j+2,j+2,s}, 363 | {i+1,j+3,R1(0,0)},{j+1,j+3,-R1(0,0)},{i+1,-j-3,R1(0,1)},{j+1,-j-3,-R1(0,1)}, 364 | {i+2,j+3,R1(1,0)},{j+2,j+3,-R1(1,0)},{i+2,-j-3,R1(1,1)},{j+2,-j-3,-R1(1,1)}, 365 | { i+3,i+1,R2(0,0)},{ i+3,j+1,-R2(0,0)},{ i+3,i+2,R2(0,1)},{ i+3,j+2,-R2(0,1)}, 366 | {-i-3,i+1,R2(1,0)},{-i-3,i+1,-R2(1,0)},{-i-3,i+2,R2(1,1)},{-i-3,j+2,-R2(1,1)}, 367 | {i+3,j+3,A(0,0)},{i+3,-j-3,A(0,1)},{-i-3,j+3,A(1,0)},{-i-3,-j-3,A(1,1)},{0,0,b}}; 368 | } 369 | 370 | vector print(const double* x){ 371 | return {"ClRtPtRt : " + std::to_string(eval(x))}; 372 | } 373 | 374 | vector getD1ind(){ 375 | return {i,i+1,i+2,j,j+1,j+2}; 376 | } 377 | 378 | void getD1(const double* x,double* res){ 379 | RowVector2d f1(sin(x[i+2]),cos(x[i+2])),f1d(f1[1],-f1[0]); 380 | Vector2d f2(sin(x[j+2]),cos(x[j+2])),f2d(f2[1],-f2[0]); 381 | Vector2d y(x[i]-x[j],x[i+1]-x[j+1]); 382 | Vector2d dy = 2*s*y+(f1*R1).transpose()+R2*f2; 383 | double tmp[] {dy[0],dy[1],f1d*(R1*y+A*f2),-dy[0],-dy[1],y.dot(R2*f2d)+f1*A*f2d}; 384 | for(int i=0;i<6;i++) res[i] = tmp[i]; 385 | } 386 | 387 | vector> getD2ind(){ 388 | if(i tmp = moveLine(p0,p1,c.r); 423 | return PhiFunc::phiFunc(get<0>(tmp),get<1>(tmp),f,c.p,g); 424 | } 425 | 426 | PhiFunc* PhiFunc::phiFunc(circle c,RotTrans f,point p,RotTrans g){ 427 | return new PhiFuncClRtPtRt(c,f,p,g,sign(c.r)); 428 | } 429 | //If c1<0 then it should be -c1>c2 430 | PhiFunc* PhiFunc::phiFunc(circle c1,RotTrans f,circle c2,RotTrans g){ 431 | return new PhiFuncClRtPtRt(circle(c1.p,c1.r+c2.r),f,c2.p,g,sign(c1.r)); 432 | } 433 | 434 | //OK for scaling, otherwise negative circle radius determines complement 435 | PhiFunc* PhiFunc::phiFunc(circle cc,Scale f,point p,RotTrans g){ 436 | return new PhiFuncCcScClRt(cc,f,circle(p,0),g); 437 | } 438 | 439 | PhiFunc* PhiFunc::phiFunc(circle cc,Scale f,circle c,RotTrans g){ 440 | return new PhiFuncCcScClRt(cc,f,c,g); 441 | } 442 | 443 | PhiFunc* PhiFunc::phiFunc(point p0,point p1,Scale f,point p,RotTrans g){ 444 | return new PhiFuncLnScClRt(p0,p1,f,circle(p,0),g); 445 | } 446 | 447 | PhiFunc* PhiFunc::phiFunc(point p0,point p1,Scale f,circle c,RotTrans g){ 448 | return new PhiFuncLnScClRt(p0,p1,f,c,g); 449 | } 450 | 451 | PhiFunc* PhiFunc::phiFunc(circle cc,RotTrans f,circle pc,point p,RotTrans g,double s){ 452 | Matrix2d A,B; 453 | double ox=cc.p.x, oy=cc.p.y, dx=pc.p.x-p.x, dy=pc.p.y-p.y, c; 454 | A << dx, dy, dy, -dx; 455 | B << ox*dy-oy*dx, -ox*dy-oy*dx, ox*dy+oy*dx, ox*dy-oy*dx; 456 | c = pc.p.x*p.y-pc.p.y*p.x; 457 | A*= s; B*= s; c*= s; 458 | return new PhiFuncRtRtMdfg(A,B,c,f,g); 459 | } 460 | 461 | PhiFunc* PhiFunc::phiFunc(circle cc,Scale f,circle pc,point p,RotTrans g,double s){ 462 | return new PhiFuncHCcScClRt(cc,f,pc,p,g,s); 463 | } 464 | -------------------------------------------------------------------------------- /PhiObj.cpp: -------------------------------------------------------------------------------- 1 | class PhiCircCompl; //Circle Complement 2 | class PhiLineCompl; //Line Complement 3 | class PhiPolygon; //Polygon 4 | class PhiCircSeg; //Circle Segment 5 | class PhiHat; //Hat (Circle Complement Segment) 6 | 7 | class PhiCompObj{ //Composite Objects (includes primitives) 8 | public: 9 | //every object implements a distance function to all other objects 10 | virtual PhiFunc* phiFunc(RotTrans, PhiCompObj*, RotTrans) = 0; 11 | virtual PhiFunc* phiFunc(RotTrans, PhiPolygon*, RotTrans) = 0; 12 | virtual PhiFunc* phiFunc(RotTrans, PhiCircSeg*, RotTrans) = 0; 13 | virtual PhiFunc* phiFunc(RotTrans, PhiHat* , RotTrans) = 0; 14 | virtual PhiFunc* phiFunc(RotTrans, PhiCircCompl*, Scale) = 0; 15 | virtual PhiFunc* phiFunc(RotTrans, PhiLineCompl*, Scale) = 0; 16 | 17 | //helper function to virtually move composite objects 18 | virtual void move(point) = 0; 19 | }; 20 | 21 | class PhiInfObj{ //Infinite Objects 22 | public: 23 | virtual PhiFunc* phiFunc(Scale f, PhiCompObj* B, RotTrans g) = 0; 24 | }; 25 | 26 | class PhiCircCompl: public PhiInfObj{ 27 | public: 28 | circle c; 29 | PhiCircCompl(circle ci) : c(ci) {} 30 | 31 | PhiFunc* phiFunc(Scale f, PhiCompObj* B, RotTrans g){ 32 | return B->phiFunc(g, this, f); 33 | } 34 | }; 35 | 36 | class PhiLineCompl: public PhiInfObj{ 37 | public: 38 | point p0,p1; 39 | PhiLineCompl(point p0i, point p1i) : p0(p0i),p1(p1i) {} 40 | 41 | PhiFunc* phiFunc(Scale f, PhiCompObj* B, RotTrans g){ 42 | return B->phiFunc(g, this, f); 43 | } 44 | }; 45 | 46 | //class PhiLine: public PhiCompObj{}; 47 | 48 | //Union of Composite Objects 49 | class PhiCompNode: public PhiCompObj{ 50 | vector nodes; 51 | public: 52 | PhiCompNode(vector ni) : nodes(ni) {} 53 | 54 | template PhiFunc* phiFuncM(RotTrans f,S* O, T g){ 55 | vector res(nodes.size()); 56 | for(int i=0;iphiFunc(f,O,g); 58 | return new PhiFuncNode(true,res); 59 | } 60 | 61 | PhiFunc* phiFunc(RotTrans f,PhiCompObj* O,RotTrans g){ 62 | return phiFuncM(f,O,g); 63 | } 64 | 65 | PhiFunc* phiFunc(RotTrans f,PhiPolygon* P,RotTrans g){ 66 | return phiFuncM(f,P,g); 67 | } 68 | 69 | PhiFunc* phiFunc(RotTrans f,PhiCircSeg* D,RotTrans g){ 70 | return phiFuncM(f,D,g); 71 | } 72 | 73 | PhiFunc* phiFunc(RotTrans f,PhiHat* H,RotTrans g){ 74 | return phiFuncM(f,H,g); 75 | } 76 | 77 | PhiFunc* phiFunc(RotTrans f,PhiCircCompl* C,Scale g){ 78 | return phiFuncM(f,C,g); 79 | } 80 | 81 | PhiFunc* phiFunc(RotTrans f, PhiLineCompl* L, Scale g){ 82 | return phiFuncM(f,L,g); 83 | } 84 | 85 | void move(point p){ 86 | for(PhiCompObj* obj : nodes) 87 | obj->move(p); 88 | } 89 | }; 90 | 91 | //Polygon (assumed to be convex) 92 | class PhiPolygon: public PhiCompObj{ 93 | public: 94 | vector p; //Counter clockwise enumeration of points 95 | int n; 96 | 97 | PhiPolygon(vector pi) : p(pi),n(pi.size()) {} 98 | 99 | PhiFunc* phiFunc(RotTrans f,PhiCompObj* O, RotTrans g){ 100 | return O->phiFunc(g, this, f); 101 | } 102 | 103 | //a point is outside iff it is to the right of one side 104 | PhiFunc* phiFunc(RotTrans f,point q,RotTrans g){ 105 | vector comp(n); 106 | for(int i=0;i comp(2*n); 114 | vector exts(2*n); 115 | for(int i=0;i tmp = moveLine(p[i],p[(i+1)%n],c.r); 117 | exts[2*i ] = get<0>(tmp); 118 | exts[2*i+1] = get<1>(tmp); 119 | } 120 | for(int i=0;i comp(n); 132 | for(int i=0;in; 140 | vector comp(n+m); 141 | for(int i=0;iphiFunc(g,p[i],p[(i+1)%n],f); 143 | for(int i=0;ip[i],Q->p[(i+1)%m],g); 145 | return new PhiFuncNode(false,comp); 146 | } 147 | 148 | //implemented in the complementary classes 149 | PhiFunc* phiFunc(RotTrans f, PhiCircSeg* C, RotTrans g); 150 | PhiFunc* phiFunc(RotTrans f, PhiHat* H, RotTrans g); 151 | 152 | //no intersection iff no point is contained 153 | PhiFunc* phiFunc(RotTrans g, PhiCircCompl* C, Scale f){ 154 | vector comp(n); 155 | for(int i=0;ic,f,p[i],g); 157 | return new PhiFuncNode(true,comp); 158 | } 159 | 160 | //no intersection iff no point is contained 161 | PhiFunc* phiFunc(RotTrans g, PhiLineCompl* L, Scale f){ 162 | vector comp(n); 163 | for(int i=0;ip0,L->p1,f,p[i],g); 165 | return new PhiFuncNode(true,comp); 166 | } 167 | 168 | void move(point pd){ 169 | for(int i=0;icircCompletion(p0i,p1i,pci.p)})) { 189 | } 190 | 191 | PhiFunc* phiFunc(RotTrans f,PhiCompObj* O, RotTrans g){ 192 | return O->phiFunc(g, this, f); 193 | } 194 | 195 | PhiFunc* phiFunc(RotTrans f,PhiPolygon* P, RotTrans g){ 196 | return P->phiFunc(g, this, f); 197 | } 198 | 199 | PhiFunc* phiFunc(RotTrans f, PhiCircSeg* C, RotTrans g){ 200 | return new PhiFuncNode(false,{ 201 | P.phiFunc(f,C->pc,g),C->P.phiFunc(g,pc,f), 202 | P.phiFunc(f,&C->P,g),PhiFunc::phiFunc(pc,f,C->pc,g)}); 203 | } 204 | 205 | PhiFunc* phiFunc(RotTrans f, PhiHat* H, RotTrans g); 206 | 207 | PhiFunc* phiFunc(RotTrans g, PhiCircCompl* C, RotTrans f){ 208 | vector comp = {PhiFunc::phiFunc(C->c,f,p0,g), 209 | PhiFunc::phiFunc(C->c,f,p1,g)}; 210 | if(C->c.r+pc.r>0) 211 | comp.push_back(new PhiFuncNode(false,{ 212 | PhiFunc::phiFunc(C->c,f,pc,g), 213 | PhiFunc::phiFunc(C->c,f,pc,p0,g, 1), 214 | PhiFunc::phiFunc(C->c,f,pc,p1,g,-1)})); 215 | return new PhiFuncNode(true,comp); 216 | } 217 | 218 | PhiFunc* phiFunc(RotTrans g, PhiCircCompl* C, Scale f){ 219 | return new PhiFuncNode(true,{ 220 | PhiFunc::phiFunc(C->c,f,p0,g), 221 | PhiFunc::phiFunc(C->c,f,p1,g), 222 | new PhiFuncNode(false,{ //TODO add C->pc.r+pc.r>=0 223 | PhiFunc::phiFunc(C->c,f,pc,g), 224 | PhiFunc::phiFunc(C->c,f,pc,p0,g,-1), 225 | PhiFunc::phiFunc(C->c,f,pc,p1,g, 1)})}); 226 | } 227 | 228 | PhiFunc* phiFunc(RotTrans g, PhiLineCompl* L, Scale f){ 229 | return new PhiFuncNode(true,{ 230 | PhiFunc::phiFunc(L->p0,L->p1,f,p0,g), 231 | PhiFunc::phiFunc(L->p0,L->p1,f,p1,g), 232 | new PhiFuncNode(false,{ 233 | PhiFunc::phiFunc(L->p0,L->p1,f,pc,g), 234 | PhiFunc::phiFunc(L->p0,L->p1,f,P.p[2],g)})}); 235 | } 236 | 237 | void move(point pd){ 238 | p0.move(pd);p1.move(pd);pc.move(pd); 239 | P.move(pd); 240 | } 241 | }; 242 | 243 | PhiFunc* PhiPolygon::phiFunc(RotTrans f, PhiCircSeg* C, RotTrans g){ 244 | return new PhiFuncNode(false,{C->P.phiFunc(g,this,f),this->phiFunc(f,C->pc,g)}); 245 | } 246 | 247 | class PhiHat: public PhiCompObj{ 248 | public: 249 | point p0,p1,p2; //Get rid of this? 250 | circle pc; //Radius needs to be negative 251 | PhiPolygon P; 252 | 253 | PhiHat(point p0i,point p1i,point p2i,circle ci) : 254 | p0(p0i),p1(p1i),p2(p2i),pc(ci),P(PhiPolygon({p0i,p1i,p2i})) {} 255 | 256 | PhiHat(point p0i,point p1i,point p2i,double r) : 257 | p0(p0i),p1(p1i),p2(p2i),P(PhiPolygon({p0i,p1i,p2i})) { 258 | double dx = p0.x-p1.x,dy = p0.y-p1.y; 259 | double s = sqrt(4*r*r/(dx*dx+dy*dy)-1); 260 | pc = circle(point((p0.x+p1.x+dy*s)/2,(p0.y+p1.y-dx*s)/2),r); 261 | } 262 | 263 | PhiFunc* phiFunc(RotTrans f,PhiCompObj* O, RotTrans g){ 264 | return O->phiFunc(g, this, f); 265 | } 266 | 267 | PhiFunc* phiFunc(RotTrans f,PhiPolygon* O, RotTrans g){ 268 | return O->phiFunc(g, this, f); 269 | } 270 | 271 | PhiFunc* phiFunc(RotTrans f,PhiCircSeg* O, RotTrans g){ 272 | return O->phiFunc(g, this, f); 273 | } 274 | 275 | PhiFunc* phiFuncG(RotTrans f, PhiPolygon* Q, RotTrans g){ 276 | int m = Q->n; 277 | vector comp(m+2); //P1,P2 not in Q, if q over l then q in C 278 | for(int i=0;ip[i],g), 281 | PhiFunc::phiFunc(pc,f,Q->p[i],g)}); 282 | comp[m ] = Q->phiFunc(g,p0,f); 283 | comp[m+1] = Q->phiFunc(g,p1,f); 284 | return new PhiFuncNode(true,comp); 285 | } 286 | 287 | PhiFunc* phiFuncG(RotTrans f, circle c, RotTrans g){ 288 | return new PhiFuncNode(false,{ 289 | PhiFunc::phiFunc(pc,f,c,g), 290 | PhiFunc::phiFunc(p0,p1,f,c,g), 291 | new PhiFuncNode(true,{ 292 | PhiFunc::phiFunc(get<0>(moveLine(p0,p1,c.r)),get<0>(moveLine(p0,p2,c.r)),f,c.p,g), 293 | PhiFunc::phiFunc(get<1>(moveLine(p2,p1,c.r)),get<1>(moveLine(p0,p1,c.r)),f,c.p,g), 294 | PhiFunc::phiFunc(c,g,p0,f),PhiFunc::phiFunc(c,g,p1,f)})}); 295 | } 296 | 297 | PhiFunc* phiFuncG(RotTrans f, PhiCircSeg* D, RotTrans g){ 298 | return new PhiFuncNode(false,{ 299 | D->P.phiFunc(g,p0,p1,f), 300 | D->phiFunc(g,new PhiCircCompl(pc),f), 301 | phiFuncG(f,D->pc,g), 302 | new PhiFuncNode(true,{ 303 | D->phiFunc(g,new PhiPolygon({p0,p2,point(2*p0.x-p1.x,2*p0.y-p1.y)}),f), 304 | PhiFunc::phiFunc(pc,f,D->p1,g), 305 | PhiFunc::phiFunc(D->p0,D->p1,g,p1,f), 306 | PhiFunc::phiFunc(D->p1,D->p0,g,p0,f)}), 307 | new PhiFuncNode(true,{ 308 | D->phiFunc(g,new PhiPolygon({p1,point(2*p1.x-p0.x,2*p1.y-p0.y),p2}),f), 309 | PhiFunc::phiFunc(pc,f,D->p0,g), 310 | PhiFunc::phiFunc(D->p0,D->p1,g,p0,f), 311 | PhiFunc::phiFunc(D->p1,D->p0,g,p1,f)})}); 312 | } 313 | 314 | PhiFunc* phiFunc(RotTrans f, PhiHat* H, RotTrans g){ 315 | return new PhiFuncNode(false,{ 316 | P.phiFunc(f,H,g),phiFuncG(f,&H->P,g), 317 | new PhiFuncNode(true,{ 318 | PhiFunc::phiFunc(p2,p0,f,H->p1,g), 319 | PhiFunc::phiFunc(H->p2,H->p0,g,p1,f), 320 | PhiFunc::phiFunc(pc,f,H->p0,g), 321 | PhiFunc::phiFunc(H->pc,g,p0,f)}), 322 | new PhiFuncNode(true,{ 323 | PhiFunc::phiFunc(p1,p2,f,H->p0,g), 324 | PhiFunc::phiFunc(H->p1,H->p2,g,p0,f), 325 | PhiFunc::phiFunc(pc,f,H->p1,g), 326 | PhiFunc::phiFunc(H->pc,g,p1,f)})}); 327 | } 328 | 329 | PhiFunc* phiFunc(RotTrans g, PhiCircCompl* C, Scale f){ 330 | return P.phiFunc(g,C,f); 331 | } 332 | 333 | PhiFunc* phiFunc(RotTrans g, PhiLineCompl* L, Scale f){ 334 | return P.phiFunc(g,L,f); 335 | } 336 | 337 | void move(point pd){ 338 | p0.move(pd);p1.move(pd);p2.move(pd);pc.move(pd); 339 | P.move(pd); 340 | } 341 | }; 342 | 343 | PhiFunc* PhiPolygon::phiFunc(RotTrans f, PhiHat* H, RotTrans g){ 344 | return new PhiFuncNode(false,{H->P.phiFunc(g,this,f),H->phiFuncG(g,this,f)}); 345 | } 346 | 347 | PhiFunc* PhiCircSeg::phiFunc(RotTrans f, PhiHat* H, RotTrans g){ 348 | return new PhiFuncNode(false,{H->P.phiFunc(g,this,f),H->phiFuncG(g,this,f)}); 349 | } 350 | 351 | PhiFunc* phiFunc(PhiInfObj* A, Scale f, PhiCompObj* B, RotTrans g){ 352 | return A->phiFunc(f,B,g); 353 | } 354 | 355 | PhiFunc* phiFunc(PhiCompObj* A, RotTrans f, PhiCompObj* B, RotTrans g){ 356 | return A->phiFunc(f,B,g); 357 | } 358 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Overview 2 | -------- 3 | 4 | ![Packing](https://github.com/Athlici/Packing/blob/master/Packing.png) 5 | 6 | Ever needed to arrange irregular objects with rotations and translations into as small a container as possible? 7 | 8 | Worry no more for I have written the code to do just that so you don't have to. 9 | 10 | Given a set of irregular 2D objects this program finds an arrangement such that the size of their container is minimized. This can be useful to optimize material or space usage in cutting and packing applications. 11 | The objects can be unions of convex polygons as well as convex and concave circle segments which are subject to continuous translation and rotations. 12 | The container can currently be a disk subject to scaling. 13 | 14 | This program is at a Proof of Concept stage, but given interest in it I'm willing to assist and extend it. For example the infrastructure to extend this to an intersection of disks and half-spaces for the container or other scenarios and support for different objective functions is either already partially present or can be added easily. 15 | 16 | So, how is this different from these great projects doing packing/nesting: 17 | 18 | * [SVGnest](https://github.com/Jack000/SVGnest) 19 | * [libnest2d](https://github.com/tamasmeszaros/libnest2d) 20 | * [2D-Bin-Packing](https://github.com/mses-bly/2D-Bin-Packing) 21 | 22 | All of them can only handle a discrete (and usually small) number of possible rotations. In return (and through heuristics) they can solve bigger problem instances. 23 | 24 | Installation 25 | ------------ 26 | This project uses [Ipopt](https://projects.coin-or.org/Ipopt) for the actual numerical calculations. As such it and it's dependencies, in particular a sparse matrix library are required (and if that isn't ma57 but mumps change the line in main.cpp). Follow it's guide or pray your distro has a package for it. 27 | 28 | Furthermore it uses the Eigen matrix library, so get that one as well. 29 | 30 | After that building should be as simple as running 31 | 32 | make 33 | 34 | In theory there should be no reason this couldn't run under windows, although getting ipopt to compile there already proves your skills superior to mine. 35 | 36 | Usage 37 | ----- 38 | Data In- and Export is currently implemented via XML files. The test.xml example contains all functions currently implemented and is given as first and only parameter when running the program. The output will be a copy of the input with the parameters of the best solution found added in out.xml. This solution can be visualized with the Mathematica notebook in this repo. 39 | 40 | The defining points of the basic shapes (convex polygon, circle segment, hat) are expected in mathematically positive (counter-clockwise) order with the numbering for the latter two starting at the beginning of the line cutting of a circle. 41 | 42 | TODO: Infographics 43 | 44 | How it works 45 | ------------ 46 | 47 | Given the objects the program builds their distance functions based on and as described in this [paper](https://pdfs.semanticscholar.org/8c7b/92a7379af4c87b4cd5900745d48d62fbd954.pdf). This results in a lot of linear functions in a Min-Max-Tree with the constraint that the result of the tree is non-negative (no overlap). 48 | 49 | Choosing a branch of this tree on which Ipopt can work is done by starting with a heuristic solution which is then successively refined as long as it reaches a new branching of the tree. 50 | 51 | The heuristic I developed for this starts by finding a bounding circle for every object and then stringing these along a chain, inserting a circle at the first position where a circle can fit while touching both its predecessor and successor. 52 | 53 | ![Circles](https://github.com/Athlici/Packing/blob/master/Circles.png) 54 | 55 | Known Bugs 56 | ---------- 57 | 58 | Somehow Ipopt doesn't want to work sometimes (regularly) so no solution is found. Restarting the program usually fixes this. 59 | -------------------------------------------------------------------------------- /Struct.cpp: -------------------------------------------------------------------------------- 1 | struct var{ //variables 2 | var() {}; 3 | var(double lbi,double ubi) : lb(lbi),ub(ubi) {}; 4 | var(double lbi,double ubi,bool radiani) : lb(lbi),ub(ubi),radian(radiani) {}; 5 | double lb,ub; 6 | bool radian=false; 7 | // string name; 8 | }; 9 | 10 | class point{ //points TODO: make Vector2d? 11 | public: 12 | point() {}; 13 | point(double xi,double yi) : x(xi),y(yi) {}; 14 | double x,y; 15 | 16 | void move(point p){ 17 | x+=p.x; y+=p.y; 18 | } 19 | }; 20 | 21 | class circle{ //circles 22 | public: 23 | circle() {}; 24 | circle(point pi,double ri) : p(pi),r(ri) {}; 25 | point p; 26 | double r; 27 | 28 | void move(point pd){ 29 | p.move(pd); 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Transform.cpp: -------------------------------------------------------------------------------- 1 | class Transform{ 2 | // public: 3 | // virtual PhiFunc* phiFunc(PhiCompObj* P, PhiCompObj* Q, Transform* f) = 0; 4 | }; 5 | 6 | //scaling function, only for the container 7 | class Scale: public Transform{ 8 | public: 9 | int ind; 10 | Scale(){}; 11 | Scale(int i) : ind(i) {} 12 | }; 13 | 14 | //class Translate: public Transform{ <- imitated by RotTrans with third variable fixed 0 15 | // public: 16 | // int ind; 17 | // Translate(int i) : ind(i) {} 18 | //}; 19 | 20 | //rotate and then translate 21 | class RotTrans: public Transform{ 22 | public: 23 | int ind; 24 | RotTrans(){}; 25 | RotTrans(int i) : ind(i) {} 26 | }; 27 | -------------------------------------------------------------------------------- /Visualisation.nb: -------------------------------------------------------------------------------- 1 | (* Content-type: application/vnd.wolfram.mathematica *) 2 | 3 | (*** Wolfram Notebook File ***) 4 | (* http://www.wolfram.com/nb *) 5 | 6 | (* CreatedBy='Mathematica 11.1' *) 7 | 8 | (*CacheID: 234*) 9 | (* Internal cache information: 10 | NotebookFileLineBreakTest 11 | NotebookFileLineBreakTest 12 | NotebookDataPosition[ 158, 7] 13 | NotebookDataLength[ 20176, 510] 14 | NotebookOptionsPosition[ 18470, 482] 15 | NotebookOutlinePosition[ 18808, 497] 16 | CellTagsIndexPosition[ 18765, 494] 17 | WindowFrame->Normal*) 18 | 19 | (* Beginning of Notebook Content *) 20 | Notebook[{ 21 | Cell[BoxData[ 22 | RowBox[{ 23 | RowBox[{"toNum", "[", "x_", "]"}], ":=", 24 | RowBox[{"First", "@", 25 | RowBox[{"ImportString", "[", 26 | RowBox[{"x", ",", "\"\\""}], "]"}]}]}]], "Input", 27 | CellChangeTimes->{{3.744658344399028*^9, 3.744658370717238*^9}, { 28 | 3.7446584595111227`*^9, 3.744658463261428*^9}, {3.753166155120841*^9, 29 | 3.75316616044816*^9}},ExpressionUUID->"b3cec433-62aa-4128-9a1b-\ 30 | a26bb0649dea"], 31 | 32 | Cell[BoxData[ 33 | RowBox[{ 34 | RowBox[{"RT", "[", "p_", "]"}], ":=", 35 | RowBox[{ 36 | RowBox[{"{", 37 | RowBox[{"x", ",", "y"}], "}"}], "+", 38 | RowBox[{ 39 | RowBox[{"RotationMatrix", "[", "\[Phi]", "]"}], ".", "p"}]}]}]], "Input", 40 | CellChangeTimes->{{3.7454193700533257`*^9, 41 | 3.745419402431612*^9}},ExpressionUUID->"31945163-dca9-4e9a-8f71-\ 42 | 4e1493017cf3"], 43 | 44 | Cell[BoxData[ 45 | RowBox[{ 46 | RowBox[{ 47 | RowBox[{"Parse", "[", 48 | RowBox[{ 49 | RowBox[{"XMLObject", "[", "\"\\"", "]"}], "[", 50 | RowBox[{ 51 | RowBox[{"{", "}"}], ",", 52 | RowBox[{"XMLElement", "[", 53 | RowBox[{"\"\\"", ",", 54 | RowBox[{"{", "}"}], ",", "l_"}], "]"}], ",", 55 | RowBox[{"{", "}"}]}], "]"}], "]"}], ":=", 56 | RowBox[{"Graphics", "[", 57 | RowBox[{"Join", "@@", 58 | RowBox[{"(", 59 | RowBox[{"Parse", "/@", "l"}], ")"}]}], "]"}]}], ";"}]], "Input", 60 | CellChangeTimes->{{3.745019702844962*^9, 3.745019710724987*^9}, { 61 | 3.74642583787418*^9, 3.746425842809314*^9}, {3.746425904671692*^9, 62 | 3.746425908198731*^9}, {3.75316618272746*^9, 3.753166183366625*^9}, 63 | 3.7531663353522778`*^9, {3.7558781401241426`*^9, 3.755878156022575*^9}, { 64 | 3.75587822510047*^9, 65 | 3.755878229203905*^9}},ExpressionUUID->"a6e1c8dc-e555-480a-ad18-\ 66 | adc3abed7c21"], 67 | 68 | Cell[BoxData[{ 69 | RowBox[{ 70 | RowBox[{ 71 | RowBox[{"Parse", "[", 72 | RowBox[{"XMLElement", "[", 73 | RowBox[{"\"\\"", ",", 74 | RowBox[{"{", 75 | RowBox[{ 76 | RowBox[{"\"\\"", "\[Rule]", "a_"}], ",", 77 | RowBox[{"\"\\"", "\[Rule]", "b_"}], ",", 78 | RowBox[{"\"\\"", "\[Rule]", "c_"}]}], "}"}], ",", 79 | RowBox[{"{", "}"}]}], "]"}], "]"}], ":=", 80 | RowBox[{"{", 81 | RowBox[{ 82 | RowBox[{"x", "\[Rule]", 83 | RowBox[{"toNum", "@", "a"}]}], ",", 84 | RowBox[{"y", "\[Rule]", 85 | RowBox[{"toNum", "@", "b"}]}], ",", 86 | RowBox[{"\[Phi]", "\[Rule]", 87 | RowBox[{"toNum", "@", "c"}]}]}], "}"}]}], 88 | ";"}], "\[IndentingNewLine]", 89 | RowBox[{ 90 | RowBox[{ 91 | RowBox[{"Parse", "[", 92 | RowBox[{"XMLElement", "[", 93 | RowBox[{"\"\\"", ",", 94 | RowBox[{"{", 95 | RowBox[{"\"\\"", "\[Rule]", "a_"}], "}"}], ",", 96 | RowBox[{"{", "}"}]}], "]"}], "]"}], ":=", 97 | RowBox[{"{", 98 | RowBox[{"r", "\[Rule]", 99 | RowBox[{"toNum", "@", "a"}]}], "}"}]}], ";"}]}], "Input", 100 | CellChangeTimes->{{3.744576579782918*^9, 3.7445766310151367`*^9}, { 101 | 3.744576678405624*^9, 3.74457671562317*^9}, 3.7445768504551*^9, { 102 | 3.744577230638856*^9, 3.744577252582581*^9}, {3.744578347373796*^9, 103 | 3.744578353917666*^9}, {3.7445783850057373`*^9, 3.7445784291897087`*^9}, { 104 | 3.7445790433897877`*^9, 3.744579138797763*^9}, {3.744579178621751*^9, 105 | 3.744579209501803*^9}, {3.7446512678817*^9, 3.74465128781361*^9}, { 106 | 3.744651341565668*^9, 3.744651368237503*^9}, {3.744651482118807*^9, 107 | 3.7446515319093723`*^9}, {3.744651604990551*^9, 3.7446516966371603`*^9}, { 108 | 3.74465241600736*^9, 3.7446524203183737`*^9}, 3.7446524834157057`*^9, { 109 | 3.74465260791313*^9, 3.7446526267826443`*^9}, {3.74465367143874*^9, 110 | 3.744653693606522*^9}, {3.7446537291830997`*^9, 3.744653752478644*^9}, { 111 | 3.7446540826389933`*^9, 3.744654112334607*^9}, {3.74465414525618*^9, 112 | 3.744654194662826*^9}, {3.744654244270536*^9, 3.744654311566679*^9}, { 113 | 3.744654353930772*^9, 3.744654438837399*^9}, {3.7446545277410994`*^9, 114 | 3.7446545629323483`*^9}, {3.744657610102234*^9, 3.7446576599901237`*^9}, { 115 | 3.7446580202162027`*^9, 3.7446580505999804`*^9}, {3.7446580862863503`*^9, 116 | 3.744658114773974*^9}, {3.744658317726687*^9, 3.744658331870263*^9}, { 117 | 3.744658376773203*^9, 3.7446583890062933`*^9}, {3.744658771542061*^9, 118 | 3.744658794822733*^9}, {3.7446588655506477`*^9, 3.74465900074973*^9}, { 119 | 3.7558803144683*^9, 120 | 3.75588035118023*^9}},ExpressionUUID->"e3e27ae2-4a8e-445d-874a-\ 121 | e7fb9fc6269c"], 122 | 123 | Cell[BoxData[ 124 | RowBox[{ 125 | RowBox[{ 126 | RowBox[{"Parse", "[", 127 | RowBox[{"XMLElement", "[", 128 | RowBox[{"\"\\"", ",", 129 | RowBox[{"{", "}"}], ",", "l_"}], "]"}], "]"}], ":=", 130 | RowBox[{ 131 | RowBox[{"(", 132 | RowBox[{"Parse", "/@", 133 | RowBox[{"Most", "[", "l", "]"}]}], ")"}], "/.", 134 | RowBox[{"Parse", "[", 135 | RowBox[{"Last", "@", "l"}], "]"}]}]}], ";"}]], "Input", 136 | CellChangeTimes->{{3.74465674640784*^9, 3.744656753342451*^9}, { 137 | 3.744656938285521*^9, 138 | 3.74465695183733*^9}},ExpressionUUID->"968dca91-9a3c-45b6-8af3-\ 139 | 1f6badb5fb5f"], 140 | 141 | Cell[BoxData[ 142 | RowBox[{ 143 | RowBox[{ 144 | RowBox[{"Parse", "[", 145 | RowBox[{"XMLElement", "[", 146 | RowBox[{"\"\\"", ",", 147 | RowBox[{"{", "}"}], ",", "l_"}], "]"}], "]"}], ":=", 148 | RowBox[{"Join", "@@", 149 | RowBox[{"(", 150 | RowBox[{"MapIndexed", "[", 151 | RowBox[{ 152 | RowBox[{ 153 | RowBox[{"{", 154 | RowBox[{ 155 | RowBox[{"ColorData", "[", 156 | RowBox[{"37", ",", 157 | RowBox[{"#2", "[", 158 | RowBox[{"[", "1", "]"}], "]"}]}], "]"}], ",", 159 | RowBox[{"Parse", "[", "#", "]"}]}], "}"}], "&"}], ",", "l"}], "]"}], 160 | ")"}]}]}], ";"}]], "Input", 161 | CellChangeTimes->{{3.744656774973152*^9, 3.744656796197217*^9}, { 162 | 3.745019506796907*^9, 3.7450195113409357`*^9}, {3.7450195917810307`*^9, 163 | 3.745019646141055*^9}},ExpressionUUID->"b92904ae-217f-46f2-a4ca-\ 164 | f8813a022ac2"], 165 | 166 | Cell[BoxData[ 167 | RowBox[{ 168 | RowBox[{ 169 | RowBox[{"Parse", "[", 170 | RowBox[{"XMLElement", "[", 171 | RowBox[{"\"\\"", ",", 172 | RowBox[{"{", "}"}], ",", "l_"}], "]"}], "]"}], ":=", 173 | RowBox[{ 174 | RowBox[{ 175 | RowBox[{"Parse", "@", 176 | RowBox[{"MapAt", "[", 177 | RowBox[{ 178 | RowBox[{"Append", "[", 179 | RowBox[{"Last", "[", "l", "]"}], "]"}], ",", "#", ",", "3"}], 180 | "]"}]}], "&"}], "/@", 181 | RowBox[{"Most", "[", "l", "]"}]}]}], ";"}]], "Input", 182 | CellChangeTimes->{{3.7527906645431013`*^9, 3.752790743539323*^9}, { 183 | 3.7531642524690933`*^9, 3.7531642548852663`*^9}, {3.753164299114747*^9, 184 | 3.7531643033226433`*^9}, {3.753164352032845*^9, 3.75316436852765*^9}, { 185 | 3.753164835143992*^9, 3.753164869310514*^9}, 3.753164917589099*^9, { 186 | 3.753165434114596*^9, 3.753165465880692*^9}, 3.753165572780218*^9, { 187 | 3.7531656575516*^9, 3.753165676261846*^9}, {3.7531657242676487`*^9, 188 | 3.753165726843461*^9}, {3.753166325031721*^9, 189 | 3.753166328304008*^9}},ExpressionUUID->"89c07c05-bd17-481b-ae63-\ 190 | 8246cb43fddf"], 191 | 192 | Cell[BoxData[ 193 | RowBox[{ 194 | RowBox[{ 195 | RowBox[{"Parse", "[", 196 | RowBox[{"XMLElement", "[", 197 | RowBox[{"\"\\"", ",", 198 | RowBox[{"{", "}"}], ",", 199 | RowBox[{"{", "l_", "}"}]}], "]"}], "]"}], ":=", 200 | RowBox[{ 201 | RowBox[{ 202 | RowBox[{"Circle", "[", 203 | RowBox[{"#", ",", 204 | RowBox[{"r", "*", 205 | RowBox[{"Abs", "[", "#2", "]"}]}]}], "]"}], "&"}], "@@", 206 | RowBox[{"Parse", "[", "l", "]"}]}]}], ";"}]], "Input", 207 | CellChangeTimes->{{3.744657280150031*^9, 3.744657280933721*^9}, { 208 | 3.744658398319229*^9, 3.744658411736758*^9}, {3.755876132339872*^9, 209 | 3.755876154627743*^9}, 3.755876704259645*^9, {3.75587724247549*^9, 210 | 3.755877258243699*^9}, {3.755877497475794*^9, 3.7558775006117153`*^9}, 211 | 3.755878197723942*^9, {3.7558784348281813`*^9, 3.7558784476837177`*^9}, { 212 | 3.755880270828129*^9, 3.7558802726038847`*^9}, {3.755880304412401*^9, 213 | 3.7558803056360407`*^9}, {3.7558803592544394`*^9, 214 | 3.755880361644145*^9}},ExpressionUUID->"20a8e235-e155-4aa3-a2a9-\ 215 | a6d943d0081c"], 216 | 217 | Cell[BoxData[ 218 | RowBox[{ 219 | RowBox[{ 220 | RowBox[{"Parse", "[", 221 | RowBox[{"XMLElement", "[", 222 | RowBox[{"\"\\"", ",", 223 | RowBox[{"{", "}"}], ",", "l_"}], "]"}], "]"}], ":=", 224 | RowBox[{"InfiniteLine", "[", 225 | RowBox[{"r", "*", 226 | RowBox[{"(", 227 | RowBox[{"Parse", "/@", "l"}], ")"}]}], "]"}]}], ";"}]], "Input", 228 | CellChangeTimes->{{3.755874500963934*^9, 3.755874504357687*^9}, { 229 | 3.755875325651743*^9, 3.755875331484211*^9}, {3.755877516315927*^9, 230 | 3.755877521899581*^9}, {3.755877707931775*^9, 3.755877715379538*^9}, { 231 | 3.755878451715863*^9, 3.755878456387871*^9}, {3.755878497780031*^9, 232 | 3.755878500795986*^9}},ExpressionUUID->"c79c2c45-ab33-424c-9e26-\ 233 | 501434ad730b"], 234 | 235 | Cell[BoxData[ 236 | RowBox[{ 237 | RowBox[{ 238 | RowBox[{"Parse", "[", 239 | RowBox[{"XMLElement", "[", 240 | RowBox[{"\"\\"", ",", 241 | RowBox[{"{", "}"}], ",", "l_"}], "]"}], "]"}], ":=", 242 | RowBox[{ 243 | RowBox[{"Polygon", "[", 244 | RowBox[{ 245 | RowBox[{"RT", "@*", "Parse"}], "/@", 246 | RowBox[{"Most", "[", "l", "]"}]}], "]"}], "/.", 247 | RowBox[{"Parse", "[", 248 | RowBox[{"Last", "@", "l"}], "]"}]}]}], ";"}]], "Input", 249 | CellChangeTimes->{{3.744656865421698*^9, 3.744656899805694*^9}, { 250 | 3.744656958413817*^9, 3.744656960061599*^9}, {3.74541942492775*^9, 251 | 3.7454194342149467`*^9}},ExpressionUUID->"8f308cc3-b68f-43df-81ec-\ 252 | 2e60c0c2e447"], 253 | 254 | Cell[BoxData[ 255 | RowBox[{ 256 | RowBox[{ 257 | RowBox[{"Parse", "[", 258 | RowBox[{"XMLElement", "[", 259 | RowBox[{"\"\\"", ",", 260 | RowBox[{"{", "}"}], ",", "l_"}], "]"}], "]"}], ":=", 261 | RowBox[{ 262 | RowBox[{ 263 | RowBox[{ 264 | RowBox[{"DiskSegment", "[", 265 | RowBox[{ 266 | RowBox[{"#", "[", 267 | RowBox[{"[", "1", "]"}], "]"}], ",", 268 | RowBox[{"#", "[", 269 | RowBox[{"[", "2", "]"}], "]"}], ",", 270 | RowBox[{ 271 | RowBox[{ 272 | RowBox[{"If", "[", 273 | RowBox[{ 274 | RowBox[{"#", "<", "0", "<", "#2"}], ",", 275 | RowBox[{"{", 276 | RowBox[{"#2", ",", 277 | RowBox[{"#", "+", 278 | RowBox[{"2", "Pi"}]}]}], "}"}], ",", 279 | RowBox[{"{", 280 | RowBox[{"#2", ",", "#"}], "}"}]}], "]"}], "&"}], "@@", 281 | RowBox[{"(", 282 | RowBox[{"ArcTan", "@@@", 283 | RowBox[{"{", 284 | RowBox[{ 285 | RowBox[{"#2", "-", 286 | RowBox[{"#", "[", 287 | RowBox[{"[", "1", "]"}], "]"}]}], ",", 288 | RowBox[{"#3", "-", 289 | RowBox[{"#", "[", 290 | RowBox[{"[", "1", "]"}], "]"}]}]}], "}"}]}], ")"}]}]}], "]"}], 291 | "&"}], "@@", 292 | RowBox[{"(", 293 | RowBox[{ 294 | RowBox[{ 295 | RowBox[{"{", 296 | RowBox[{ 297 | RowBox[{"{", 298 | RowBox[{ 299 | RowBox[{"RT", "[", 300 | RowBox[{"#", "[", 301 | RowBox[{"[", "1", "]"}], "]"}], "]"}], ",", 302 | RowBox[{"#", "[", 303 | RowBox[{"[", "2", "]"}], "]"}]}], "}"}], ",", 304 | RowBox[{"RT", "[", "#2", "]"}], ",", 305 | RowBox[{"RT", "[", "#3", "]"}]}], "}"}], "&"}], "@@", 306 | RowBox[{"(", 307 | RowBox[{"Parse", "/@", 308 | RowBox[{"Most", "[", "l", "]"}]}], ")"}]}], ")"}]}], "/.", 309 | RowBox[{"Parse", "[", 310 | RowBox[{"Last", "@", "l"}], "]"}]}]}], ";"}]], "Input", 311 | CellChangeTimes->{ 312 | 3.745416092151107*^9, {3.745416750562272*^9, 3.745416765460038*^9}, { 313 | 3.745416804364479*^9, 3.7454168697904882`*^9}, {3.745416966796616*^9, 314 | 3.745417005572123*^9}, {3.745418787619381*^9, 3.745418793140394*^9}, { 315 | 3.745419465277749*^9, 3.74541952639748*^9}, {3.745420875685548*^9, 316 | 3.7454208870918694`*^9}, {3.745420954169842*^9, 3.74542095900187*^9}, { 317 | 3.746335161995613*^9, 3.7463351711385736`*^9}, {3.7463352145358953`*^9, 318 | 3.746335221303109*^9}, {3.746335968993472*^9, 3.7463359706976967`*^9}, { 319 | 3.7463360764310913`*^9, 3.746336079006905*^9}, {3.746336153068984*^9, 320 | 3.746336155252225*^9}, {3.746336202331251*^9, 3.7463362072592983`*^9}, { 321 | 3.83094698133506*^9, 3.8309470035277863`*^9}, 3.8309470567595987`*^9, 322 | 3.830976233500329*^9, {3.83097647602361*^9, 3.830976487255122*^9}, { 323 | 3.830976617417194*^9, 3.830976663029593*^9}, 3.83097827112506*^9, { 324 | 3.830978306323575*^9, 3.830978317874596*^9}, {3.830978908982932*^9, 325 | 3.830978974960827*^9}, {3.830979010202029*^9, 326 | 3.830979058962471*^9}},ExpressionUUID->"9b9570ad-005c-421b-931d-\ 327 | 62b84c061a61"], 328 | 329 | Cell[BoxData[ 330 | RowBox[{ 331 | RowBox[{ 332 | RowBox[{"Parse", "[", 333 | RowBox[{"XMLElement", "[", 334 | RowBox[{"\"\\"", ",", 335 | RowBox[{"{", "}"}], ",", "l_"}], "]"}], "]"}], ":=", 336 | RowBox[{ 337 | RowBox[{ 338 | RowBox[{ 339 | RowBox[{"Polygon", "[", 340 | RowBox[{"Join", "[", 341 | RowBox[{ 342 | RowBox[{"Table", "[", 343 | RowBox[{ 344 | RowBox[{ 345 | RowBox[{"#", "[", 346 | RowBox[{"[", "1", "]"}], "]"}], "+", 347 | RowBox[{ 348 | RowBox[{"#", "[", 349 | RowBox[{"[", "2", "]"}], "]"}], 350 | RowBox[{"{", 351 | RowBox[{ 352 | RowBox[{"Cos", "[", "t", "]"}], ",", 353 | RowBox[{"Sin", "[", "t", "]"}]}], "}"}]}]}], ",", 354 | RowBox[{"Evaluate", "[", 355 | RowBox[{ 356 | RowBox[{ 357 | RowBox[{ 358 | RowBox[{ 359 | RowBox[{"{", 360 | RowBox[{"t", ",", "#", ",", "#2", ",", 361 | RowBox[{ 362 | RowBox[{"(", 363 | RowBox[{"#2", "-", "#"}], ")"}], "/", "20"}]}], "}"}], 364 | "&"}], "@@", 365 | RowBox[{"{", 366 | RowBox[{"#2", ",", 367 | RowBox[{"Mod", "[", 368 | RowBox[{"#", ",", 369 | RowBox[{"2", "Pi"}], ",", "#2"}], "]"}]}], "}"}]}], "&"}], 370 | "@@", 371 | RowBox[{"ArcTan", "@@@", 372 | RowBox[{"{", 373 | RowBox[{ 374 | RowBox[{"#2", "-", 375 | RowBox[{"#", "[", 376 | RowBox[{"[", "1", "]"}], "]"}]}], ",", 377 | RowBox[{"#3", "-", 378 | RowBox[{"#", "[", 379 | RowBox[{"[", "1", "]"}], "]"}]}]}], "}"}]}]}], "]"}]}], 380 | "]"}], ",", 381 | RowBox[{"{", "#4", "}"}]}], "]"}], "]"}], "&"}], "@@", 382 | RowBox[{"(", 383 | RowBox[{ 384 | RowBox[{ 385 | RowBox[{"{", 386 | RowBox[{ 387 | RowBox[{"{", 388 | RowBox[{ 389 | RowBox[{"RT", "[", 390 | RowBox[{"#", "[", 391 | RowBox[{"[", "1", "]"}], "]"}], "]"}], ",", 392 | RowBox[{"#", "[", 393 | RowBox[{"[", "2", "]"}], "]"}]}], "}"}], ",", 394 | RowBox[{"RT", "[", "#2", "]"}], ",", 395 | RowBox[{"RT", "[", "#3", "]"}], ",", 396 | RowBox[{"RT", "[", "#4", "]"}]}], "}"}], "&"}], "@@", 397 | RowBox[{"(", 398 | RowBox[{"Parse", "/@", 399 | RowBox[{"Most", "[", "l", "]"}]}], ")"}]}], ")"}]}], "/.", 400 | RowBox[{"Parse", "[", 401 | RowBox[{"Last", "@", "l"}], "]"}]}]}], ";"}]], "Input", 402 | CellChangeTimes->{{3.7446544446959047`*^9, 3.744654449697669*^9}, { 403 | 3.746806017282496*^9, 3.746806032489809*^9}, 3.746806529346933*^9, { 404 | 3.746806960403702*^9, 3.746806971387836*^9}, {3.746807198164693*^9, 405 | 3.746807199364951*^9}, {3.7468072567869987`*^9, 3.746807299041945*^9}, { 406 | 3.746807754531394*^9, 3.746807762586502*^9}, {3.746807833657819*^9, 407 | 3.746807837057362*^9}, {3.7468078940083723`*^9, 3.746807922326065*^9}, { 408 | 3.7468079841329107`*^9, 3.746808025812017*^9}, {3.746808063458498*^9, 409 | 3.746808106528277*^9}, {3.746808230763667*^9, 3.746808231140088*^9}, { 410 | 3.7468082749466543`*^9, 3.746808287147374*^9}, {3.746808328384556*^9, 411 | 3.746808336304339*^9}, {3.746808432477315*^9, 3.746808432885113*^9}, 412 | 3.74680891583525*^9},ExpressionUUID->"d638879a-bef2-4b4f-9aaa-\ 413 | f292731986ed"], 414 | 415 | Cell[BoxData[ 416 | RowBox[{ 417 | RowBox[{ 418 | RowBox[{"Parse", "[", 419 | RowBox[{"XMLElement", "[", 420 | RowBox[{"\"\\"", ",", 421 | RowBox[{"{", 422 | RowBox[{ 423 | RowBox[{"\"\\"", "\[Rule]", "x_"}], ",", 424 | RowBox[{"\"\\"", "\[Rule]", "y_"}]}], "}"}], ",", 425 | RowBox[{"{", "}"}]}], "]"}], "]"}], ":=", 426 | RowBox[{"toNum", "/@", 427 | RowBox[{"{", 428 | RowBox[{"x", ",", "y"}], "}"}]}]}], ";"}]], "Input", 429 | CellChangeTimes->{{3.744658419343116*^9, 430 | 3.74465841980903*^9}},ExpressionUUID->"8a8ce114-ce96-4923-94a6-\ 431 | 67308d510b62"], 432 | 433 | Cell[BoxData[ 434 | RowBox[{ 435 | RowBox[{ 436 | RowBox[{"Parse", "[", 437 | RowBox[{"XMLElement", "[", 438 | RowBox[{"\"\\"", ",", 439 | RowBox[{"{", 440 | RowBox[{ 441 | RowBox[{"\"\\"", "\[Rule]", "x_"}], ",", 442 | RowBox[{"\"\\"", "\[Rule]", "y_"}], ",", 443 | RowBox[{"\"\\"", "\[Rule]", "r_"}]}], "}"}], ",", 444 | RowBox[{"{", "}"}]}], "]"}], "]"}], ":=", 445 | RowBox[{"{", 446 | RowBox[{ 447 | RowBox[{"toNum", "/@", 448 | RowBox[{"{", 449 | RowBox[{"x", ",", "y"}], "}"}]}], ",", 450 | RowBox[{"toNum", "[", "r", "]"}]}], "}"}]}], ";"}]], "Input", 451 | CellChangeTimes->{{3.745417128945691*^9, 452 | 3.745417171141281*^9}},ExpressionUUID->"d93ee2bf-ee38-4112-8e99-\ 453 | 0a87f391d8f4"], 454 | 455 | Cell[BoxData[ 456 | RowBox[{ 457 | RowBox[{"in", "=", 458 | RowBox[{"Import", "[", 459 | RowBox[{ 460 | "\"\\"", "<>", "$UserName", "<>", 461 | "\"\\""}], "]"}]}], 462 | ";"}]], "Input", 463 | CellChangeTimes->{{3.744567935968203*^9, 3.744567990678121*^9}, 464 | 3.744573617239212*^9, {3.7454186823029137`*^9, 3.7454186957816668`*^9}, 465 | 3.746217636303001*^9, 3.7462623971536837`*^9, 3.7463345102534122`*^9, 466 | 3.7463362580804777`*^9, {3.755878175811845*^9, 3.75587817697965*^9}, { 467 | 3.755880209082698*^9, 468 | 3.755880209466502*^9}},ExpressionUUID->"d45c3705-ae09-42d8-a208-\ 469 | dd32ac373b50"], 470 | 471 | Cell[BoxData[ 472 | RowBox[{"Parse", "[", "in", "]"}]], "Input", 473 | CellChangeTimes->{{3.744568950839779*^9, 3.7445689589422903`*^9}, { 474 | 3.744569133958106*^9, 3.74456915533615*^9}, {3.744569211038793*^9, 475 | 3.744569251000249*^9}, {3.7445697880772057`*^9, 3.744569806063519*^9}, { 476 | 3.7445698526819983`*^9, 3.7445699721682253`*^9}, {3.744575618704156*^9, 477 | 3.7445756288707323`*^9}, {3.744576397341713*^9, 3.744576405061852*^9}, { 478 | 3.7446519971159077`*^9, 3.7446519993327007`*^9}, {3.753164193089369*^9, 479 | 3.753164195512341*^9}, {3.755878075461193*^9, 480 | 3.755878076371557*^9}},ExpressionUUID->"1adb8199-b32c-4e99-9aa5-\ 481 | d749108a09eb"] 482 | }, 483 | WindowSize->{956, 1076}, 484 | WindowMargins->{{2, Automatic}, {Automatic, 2}}, 485 | FrontEndVersion->"11.2 for Linux x86 (64-bit) (September 10, 2017)", 486 | StyleDefinitions->"Default.nb" 487 | ] 488 | (* End of Notebook Content *) 489 | 490 | (* Internal cache information *) 491 | (*CellTagsOutline 492 | CellTagsIndex->{} 493 | *) 494 | (*CellTagsIndex 495 | CellTagsIndex->{} 496 | *) 497 | (*NotebookFileOutline 498 | Notebook[{ 499 | Cell[558, 20, 408, 9, 34, "Input",ExpressionUUID->"b3cec433-62aa-4128-9a1b-a26bb0649dea"], 500 | Cell[969, 31, 352, 10, 31, "Input",ExpressionUUID->"31945163-dca9-4e9a-8f71-4e1493017cf3"], 501 | Cell[1324, 43, 899, 22, 34, "Input",ExpressionUUID->"a6e1c8dc-e555-480a-ad18-adc3abed7c21"], 502 | Cell[2226, 67, 2552, 53, 82, "Input",ExpressionUUID->"e3e27ae2-4a8e-445d-874a-e7fb9fc6269c"], 503 | Cell[4781, 122, 567, 16, 34, "Input",ExpressionUUID->"968dca91-9a3c-45b6-8af3-1f6badb5fb5f"], 504 | Cell[5351, 140, 836, 23, 34, "Input",ExpressionUUID->"b92904ae-217f-46f2-a4ca-f8813a022ac2"], 505 | Cell[6190, 165, 1048, 24, 34, "Input",ExpressionUUID->"89c07c05-bd17-481b-ae63-8246cb43fddf"], 506 | Cell[7241, 191, 1023, 23, 34, "Input",ExpressionUUID->"20a8e235-e155-4aa3-a2a9-a6d943d0081c"], 507 | Cell[8267, 216, 703, 16, 34, "Input",ExpressionUUID->"c79c2c45-ab33-424c-9e26-501434ad730b"], 508 | Cell[8973, 234, 654, 17, 31, "Input",ExpressionUUID->"8f308cc3-b68f-43df-81ec-2e60c0c2e447"], 509 | Cell[9630, 253, 2980, 73, 107, "Input",ExpressionUUID->"9b9570ad-005c-421b-931d-62b84c061a61"], 510 | Cell[12613, 328, 3332, 84, 130, "Input",ExpressionUUID->"d638879a-bef2-4b4f-9aaa-f292731986ed"], 511 | Cell[15948, 414, 558, 16, 34, "Input",ExpressionUUID->"8a8ce114-ce96-4923-94a6-67308d510b62"], 512 | Cell[16509, 432, 704, 20, 34, "Input",ExpressionUUID->"d93ee2bf-ee38-4112-8e99-0a87f391d8f4"], 513 | Cell[17216, 454, 617, 14, 34, "Input",ExpressionUUID->"d45c3705-ae09-42d8-a208-dd32ac373b50"], 514 | Cell[17836, 470, 630, 10, 34, "Input",ExpressionUUID->"1adb8199-b32c-4e99-9aa5-d749108a09eb"] 515 | } 516 | ] 517 | *) 518 | 519 | -------------------------------------------------------------------------------- /XMLInterface.cpp: -------------------------------------------------------------------------------- 1 | class XMLInterface{ 2 | XMLDocument doc; 3 | XMLNode* box; 4 | vector objsXML; 5 | 6 | PhiCompObj* parseObj(XMLElement* obj){ 7 | if(!strcmp(obj->Name(),"Union")){ 8 | vector nodes; 9 | for(XMLElement* n=obj->FirstChildElement();n!=nullptr;n=n->NextSiblingElement()) 10 | nodes.push_back(parseObj(n)); 11 | return new PhiCompNode(nodes); 12 | } 13 | if(!strcmp(obj->Name(),"Polygon")){ 14 | vector points; 15 | for(XMLElement* p=obj->FirstChildElement("Point");p!=nullptr;p=p->NextSiblingElement("Point")) 16 | points.push_back(toPoint(p)); 17 | return new PhiPolygon(points); 18 | }if(!strcmp(obj->Name(),"CircSeg")){ //TODO: Check orientation, calculate cx,cy 19 | XMLElement* p0=obj->FirstChildElement("Point"); 20 | XMLElement* p1=p0->NextSiblingElement("Point"); 21 | XMLElement* c=obj->FirstChildElement("Circle"); 22 | return new PhiCircSeg(toPoint(p0),toPoint(p1),toCircle(c)); 23 | }if(!strcmp(obj->Name(),"Hat")){ 24 | XMLElement* p0=obj->FirstChildElement("Point"); 25 | XMLElement* p1=p0->NextSiblingElement("Point"); 26 | XMLElement* p2=p1->NextSiblingElement("Point"); 27 | XMLElement* c=obj->FirstChildElement("Circle"); 28 | return new PhiHat(toPoint(p0),toPoint(p1),toPoint(p2),toCircle(c,-1)); 29 | } 30 | return 0; 31 | } 32 | 33 | PhiInfObj* parseInfObj(XMLElement* obj){ 34 | if(!strcmp(obj->Name(),"CircCompl")){ 35 | XMLElement* c=obj->FirstChildElement("Circle"); 36 | return new PhiCircCompl(toCircle(c)); 37 | } 38 | if(!strcmp(obj->Name(),"LineCompl")){ 39 | XMLElement* p0=obj->FirstChildElement("Point"); 40 | XMLElement* p1=p0->NextSiblingElement("Point"); 41 | return new PhiLineCompl(toPoint(p0),toPoint(p1)); 42 | } 43 | return 0; 44 | } 45 | 46 | public: 47 | XMLInterface() {}; 48 | 49 | bool load(char* path){ 50 | return doc.LoadFile(path); 51 | } 52 | 53 | Model* parse(){ 54 | Model* model = new Model(); 55 | model->f = new FirstVar(); 56 | for(XMLNode* node=doc.FirstChild()->FirstChild();node!=nullptr;node=node->NextSibling()){ 57 | if(!strcmp(node->Value(),"Container")){ 58 | vector infObjs; 59 | for(XMLElement* obj=node->FirstChildElement();obj!=nullptr;obj=obj->NextSiblingElement()) 60 | infObjs.push_back(parseInfObj(obj)); 61 | box = node; 62 | model->sc = Scale(0); 63 | model->vars.push_back(var(0,2e19)); 64 | model->C = infObjs; 65 | } 66 | if(!strcmp(node->Value(),"Objects")){ 67 | for(XMLElement* obj=node->FirstChildElement();obj!=nullptr;obj=obj->NextSiblingElement()){ 68 | objsXML.push_back(obj); 69 | model->rt.push_back(RotTrans(model->vars.size())); 70 | model->vars.push_back(var(-2e19,2e19)); 71 | model->vars.push_back(var(-2e19,2e19)); 72 | #ifdef IPOPT 73 | model->vars.push_back(var(-2*M_PI,2*M_PI)); 74 | #endif 75 | #ifdef GUROBI 76 | model->vars.push_back(var(-2e19,2e19,true)); 77 | #endif 78 | model->objs.push_back(parseObj(obj)); 79 | } 80 | } 81 | } 82 | return model; 83 | } 84 | 85 | bool write(vector sol,vector bc){ 86 | XMLElement* tmp = doc.NewElement("Solution"); 87 | tmp->SetAttribute("r",sol[0]); 88 | box->InsertEndChild(tmp); 89 | for(int i=0;iSetAttribute("x",sol[3*i+1]+c*x-s*y); 93 | tmp->SetAttribute("y",sol[3*i+2]+s*x+c*y); 94 | tmp->SetAttribute("phi",sol[3*i+3]); 95 | objsXML[i]->InsertEndChild(tmp); 96 | } 97 | return doc.SaveFile("out.xml"); 98 | } 99 | }; 100 | -------------------------------------------------------------------------------- /dNLP.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace Ipopt; 4 | 5 | //implements the interface to solve the local optimization problems 6 | class dNLP : public TNLP{ 7 | private: 8 | Objective* f; //objective 9 | vector vars; //variables 10 | vector phix; //constraint functions 11 | const double* x0; //initial values 12 | vector jacl; //number of nonzero jacobians for each phix 13 | vector> hesmap; //indexes of hessian nonzeros for every constraint 14 | vector> hesind; //index to matrix location map for the hessian 15 | 16 | public: 17 | double* res; //array for the solution 18 | 19 | //initialize with the necessary values 20 | dNLP(Objective* fi,vector varsi,vector phixi,const double* x0i) : 21 | f(fi),vars(varsi),phix(phixi),x0(x0i) {}; 22 | 23 | //give Ipopt the required information about the problem 24 | bool get_nlp_info(Index& n, Index& m, Index& njac, Index& nhes, IndexStyleEnum& index_style){ 25 | n = vars.size(); //number of variables 26 | m = phix.size(); //number of constraints 27 | 28 | //store the number of nonzero jacobians of every constraint 29 | jacl.resize(m); 30 | njac = 0; 31 | for(int i=0;igetD1ind().size(); 33 | njac += jacl[i]; 34 | } 35 | 36 | //find all the nonzero hessian entries 37 | int hesnz[n*n] = {0}; 38 | for(int i=0;i> tmp = phix[i]->getD2ind(); 40 | for(int j=0;j(tmp[j])+get<1>(tmp[j])] = 1; 42 | } 43 | //number them and create the inverse map 44 | nhes = 0; 45 | for(int i=0;i0){ 48 | hesnz[i*n+j]=++nhes; 49 | hesind.push_back({i,j}); 50 | } 51 | //for every constraint store the indices of the nonzero hessians 52 | hesmap.resize(m); 53 | for(int i=0;i> tmp = phix[i]->getD2ind(); 55 | hesmap[i].resize(tmp.size()); 56 | for(int j=0;j(tmp[j])+get<1>(tmp[j])]-1; 58 | } 59 | 60 | index_style = TNLP::C_STYLE; 61 | return true; 62 | } 63 | 64 | //set lower and upper bounds for variables, >=0 for constraints 65 | bool get_bounds_info(Index n, Number* xl, Number* xu, Index m, Number* gl, Number* gu){ 66 | for(int i=0;ieval(n,x); 86 | return true; 87 | } 88 | 89 | bool eval_grad_f(Index n, const Number* x, bool newx, Number* gradf){ 90 | f->grad(n,x,gradf); 91 | return true; 92 | } 93 | 94 | bool eval_g(Index n, const Number* x, bool newx, Index m, Number* g){ 95 | //potentially precalc (sin,cos) + manage indices here with even/odd encoding 96 | for(int i=0;ieval(x); 98 | return true; 99 | } 100 | 101 | bool eval_jac_g(Index n, const Number* x, bool newx, Index m, Index njac, 102 | Index* iRow, Index *jCol, Number* values){ 103 | int ind = 0; 104 | //without pointer return indices, otherwise calculate values 105 | if(values == NULL){ 106 | for(int i=0;i tmp = phix[i]->getD1ind(); 108 | for(int j=0;jgetD1(x,&values[ind]); 117 | ind += jacl[i]; 118 | } 119 | } 120 | return true; 121 | } 122 | 123 | bool eval_h(Index n, const Number* x, bool newx, Number sigmaf, Index m, const Number* lambda, 124 | bool newlambda, Index nhes, Index* iRow, Index* jCol, Number* values){ 125 | //TODO add objective hessian (for non-linear objectives) 126 | //without pointer return indices, otherwise calculate values 127 | if(values == NULL){ 128 | for(int i=0;i(hesind[i]); 130 | jCol[i] = get<1>(hesind[i]); 131 | } 132 | } else { 133 | for(int i=0;igetD2(x,val); 139 | for(int j=0;j 2 | #include 3 | 4 | #include "tinyxml2.h" 5 | 6 | using namespace tinyxml2; 7 | using std::to_string; 8 | 9 | int main(int argc, char** argv) { 10 | 11 | XMLDocument xmlDoc; 12 | XMLNode* pBox = xmlDoc.NewElement("Container"); 13 | xmlDoc.InsertFirstChild(pBox); 14 | XMLNode* pObjs = xmlDoc.NewElement("Objects"); 15 | xmlDoc.InsertEndChild(pObjs); 16 | 17 | XMLElement* cc = xmlDoc.NewElement("CircCompl"); 18 | cc->SetAttribute("x",0.0); 19 | cc->SetAttribute("y",0.0); 20 | cc->SetAttribute("r",1.0); 21 | pBox->InsertFirstChild(cc); 22 | 23 | int n=5; 24 | 25 | for(int i=0;iSetAttribute("x",to_string(cos(phi*j)).c_str()); 31 | point->SetAttribute("y",to_string(sin(phi*j)).c_str()); 32 | pol->InsertEndChild(point); 33 | } 34 | pObjs->InsertEndChild(pol); 35 | } 36 | 37 | // double s2 = 1/sqrt(2); 38 | // PhiCompObj* P = new PhiCircSeg(point(-s2,s2),point(s2,s2),circle(point(0,0),1)); 39 | 40 | xmlDoc.SaveFile("test.xml"); 41 | } 42 | -------------------------------------------------------------------------------- /gQP.cpp: -------------------------------------------------------------------------------- 1 | class gQP{ 2 | private: 3 | GRBModel model; 4 | vector vars,vcos; 5 | bool* dual; 6 | int n; 7 | 8 | static int sign(int i){ 9 | return (i!=0?(i>0?1:-1):0); 10 | } 11 | 12 | GRBQuadExpr parseExpr(vector> f){ 13 | GRBQuadExpr expr = GRBQuadExpr(); 14 | expr.clear(); 15 | for(int l=0;l(f[l]),j = get<1>(f[l]); 17 | double d = get<2>(f[l]); 18 | if(d>0.001 || d<-0.001) 19 | switch(3*sign(i)+sign(j)){ 20 | case 4: expr.addTerm(d,vars[ i-1],vars[ j-1]); break; 21 | case 2: expr.addTerm(d,vars[ i-1],vcos[-j-1]); break; 22 | case -2: expr.addTerm(d,vcos[-i-1],vars[ j-1]); break; 23 | case -4: expr.addTerm(d,vcos[-i-1],vcos[-j-1]); break; 24 | case 1: expr.addTerm(d,vars[ j-1]); break; 25 | case -1: expr.addTerm(d,vcos[-j-1]); break; 26 | case 0: expr.addConstant(d); break; 27 | } 28 | 29 | } 30 | 31 | return expr; 32 | } 33 | 34 | public: 35 | double* res; 36 | 37 | gQP(GRBEnv env,Objective* fi,vector varsi,vector phix) : model(GRBModel(env)){ 38 | // model = GRBModel(env); 39 | model.set(GRB_IntParam_NonConvex, 2); 40 | // model.set(GRB_DoubleParam_TimeLimit, 60); 41 | 42 | n = varsi.size(); 43 | vars.resize(n);vcos.resize(n);dual = new bool[n]; 44 | for(int i=0;i 1e19? GRB_INFINITY:varsi[i].ub,0,GRB_CONTINUOUS); 59 | } 60 | 61 | model.setObjective(parseExpr(fi->getF()), GRB_MINIMIZE); 62 | 63 | for(int i=0;igetF()),GRB_GREATER_EQUAL,0); 65 | 66 | #ifdef GLOPTIPOLY 67 | std::cout << "mpol x " << n+n/3 << std::endl; 68 | std::cout << "f = x(1);" << std::endl; 69 | std::cout << "K = ["; std::cout.precision(10); 70 | for(int i=0;i> phi = phix[i]->getF(); 72 | for(int j=0;j(phi[j]),l=get<1>(phi[j]); 74 | if(k!=0) 75 | std::cout << "(" << get<2>(phi[j]) << ")*x(" << (k>0 ? k+(k-2)/3 : 1-k-(k+2)/3) << ")*x(" 76 | << (l>0 ? l+(l-2)/3 : 1-l-(l+2)/3) << ")+"; 77 | else if(l!=0) 78 | std::cout << "(" << get<2>(phi[j]) << ")*x(" << (l>0 ? l+(l-2)/3 : 1-l-(l+2)/3) << ")+"; 79 | else 80 | std::cout << "(" << get<2>(phi[j]) << ")+"; 81 | } 82 | std::cout << "\b>=0,"; 83 | } 84 | for(int i=1;3*i=1,"; 86 | std::cout << "\b];" << std::endl; 87 | std::cout << "P = msdp(min(f),K)" << std::endl; 88 | #endif 89 | } 90 | 91 | void optimize(){ 92 | res = new double[n]; 93 | model.write("test.lp"); 94 | model.optimize(); 95 | std::cout << "{"; 96 | for(int i=0;i 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include "tinyxml2.h" 12 | 13 | #define IPOPT 14 | //#define GUROBI 15 | 16 | #ifdef IPOPT 17 | #include "coin/IpIpoptApplication.hpp" 18 | #endif 19 | 20 | #ifdef GUROBI 21 | #include 22 | #include "gurobi_c++.h" 23 | #endif 24 | 25 | //using std::vector,std::tuple,std::get,std::string; 26 | //using Eigen::Matrix2d,Eigen::Vector2d,Eigen::RowVector2d; 27 | //using Eigen::Matrix3d,Eigen::Vector3d,Eigen::RowVector3d; 28 | using std::vector; 29 | using std::tuple; 30 | using std::get; 31 | using std::string; 32 | using Eigen::Matrix2d; 33 | using Eigen::Vector2d; 34 | using Eigen::RowVector2d; 35 | using Eigen::Matrix3d; 36 | using Eigen::Vector3d; 37 | using Eigen::RowVector3d; 38 | using namespace tinyxml2; 39 | 40 | #include "Struct.cpp" //data structures 41 | #include "Transform.cpp" //object transformations 42 | #include "PhiFunc.cpp" //the distance functions 43 | #include "PhiObj.cpp" //object construction 44 | #include "Objective.cpp" //objective funtions 45 | 46 | #ifdef IPOPT 47 | #include "dNLP.cpp" //Ipopt interface 48 | #endif 49 | #ifdef GUROBI 50 | #include "gQP.cpp" 51 | #endif 52 | 53 | #include "Helpers.cpp" //miscellaneous helper functions 54 | #include "Model.cpp" //the resulting model 55 | #include "XMLInterface.cpp" //im- and export with XML 56 | 57 | const double randperm=100; //number of starting permutations 58 | const double randorient=10; //number of starting orientations 59 | 60 | int main(int argc, char** argv) { 61 | 62 | #ifdef IPOPT 63 | //Ipopt initialization 64 | std::cout << "Initializing IPOPT: "; 65 | SmartPtr app = IpoptApplicationFactory(); 66 | app->Options()->SetIntegerValue("print_level", 2); //verbosity 67 | app->Options()->SetIntegerValue("max_iter", 500); //maximum iteration number 68 | app->Options()->SetNumericValue("tol", 1e-6); //tolerance 69 | // app->Options()->SetStringValue("linear_solver", "ma57"); 70 | app->Options()->SetStringValue("linear_solver", "mumps"); 71 | // app->Options()->SetStringValue("accept_every_trial_step", "yes"); //semi-succesfull workaround for unresolved bug 72 | // app->Options()->SetStringValue("derivative_test", "second-order"); 73 | ApplicationReturnStatus status = app->Initialize(); 74 | if(status == Solve_Succeeded){ 75 | std::cout << "Success \n"; 76 | }else{ 77 | std::cout << "Error! Code " << status << "\n"; 78 | return (int) status; 79 | } 80 | #endif 81 | 82 | #ifdef GUROBI 83 | GRBEnv env = GRBEnv(); 84 | #endif 85 | 86 | //random input initialization 87 | std::default_random_engine randgen(std::chrono::system_clock::now().time_since_epoch().count()); 88 | std::uniform_real_distribution pidist(-M_PI,M_PI); 89 | 90 | //read objects from xml input file 91 | XMLInterface xml; 92 | if(xml.load(argv[1])){ 93 | std::cout << "Error: Couldn't load input file!\n"; 94 | return 1; 95 | } 96 | Model* model = xml.parse(); 97 | int n = model->objs.size(); 98 | 99 | //calculate bounding circles for all objects 100 | vector bc(n); 101 | for(int i=0;iobjs[i]); 103 | model->objs[i]->move(bc[i].p); //move bounding circle center to the origin 104 | } 105 | 106 | //create distance functions for all objects 107 | PhiFunc* phi = model->createPhiFunc(); 108 | // const double testvar[7] = {0,-1.38,1,-2.73,-2.9,-1,0.12}; 109 | // vector out = phi->print(testvar); 110 | // for(int i=0;i> initials(randperm*randorient); 114 | for(int k=0;k perm(n); 116 | vector bcp(n); 117 | for(int i=0;i pts(n),ptsp = circlePack(bcp); 121 | for(int i=0;i x(3*n+1); 126 | x[0]=1; 127 | for(int i=0;ieval(x.data())<-0.001;i++) 135 | x[0]*=2; 136 | initials[randorient*k+l] = x; 137 | } 138 | } 139 | 140 | //iterative solver 141 | Objective* f = model->f; 142 | vector bestsol = initials[0]; 143 | for(int i=0;ieval(n,x); 148 | if(phi->eval(x) < 0.01){ //relaxation 149 | x[0]*=1.03; 150 | for(int j=0;j nlp = new dNLP(f,model->vars,phi->getIneqs(x),x); 157 | status = app->OptimizeTNLP(nlp); 158 | double fv=f->eval(n,nlp->res); 159 | if(status == Solve_Succeeded && fv < prior){ 160 | #endif 161 | #ifdef GUROBI 162 | try{ 163 | gQP* nlp = new gQP(env,f,model->vars,phi->getIneqs(x)); 164 | /*status =*/ nlp->optimize(); 165 | double fv=f->eval(n,nlp->res); 166 | if(fv < prior){ 167 | #endif 168 | if(fv < f->eval(n,bestsol.data()) && phi->eval(nlp->res) > -0.001){ 169 | std::cout << fv << ":"; 170 | for(int j=0;j<3*n+1;j++){ 171 | bestsol[j] = nlp->res[j]; 172 | std::cout << bestsol[j] << ","; 173 | } 174 | std::cout << std::endl; 175 | } 176 | if(phi->getIneqs(x) != phi->getIneqs(nlp->res)){ 177 | notstalled = true; 178 | for(int j=0;j<3*n+1;j++) 179 | x[j] = nlp->res[j]; 180 | } else 181 | notstalled = false; 182 | } else 183 | notstalled = false; 184 | #ifdef GUROBI 185 | } catch(GRBException e) { 186 | std::cout << "Error code = " << e.getErrorCode() << std::endl; 187 | std::cout << e.getMessage() << std::endl; 188 | } 189 | #endif 190 | }while(notstalled); 191 | } 192 | 193 | // vector res = phi->print(x); 194 | // for(int i=0;i 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 172 | 173 | 174 | -------------------------------------------------------------------------------- /tinyxml2.h: -------------------------------------------------------------------------------- 1 | /* 2 | Original code by Lee Thomason (www.grinninglizard.com) 3 | 4 | This software is provided 'as-is', without any express or implied 5 | warranty. In no event will the authors be held liable for any 6 | damages arising from the use of this software. 7 | 8 | Permission is granted to anyone to use this software for any 9 | purpose, including commercial applications, and to alter it and 10 | redistribute it freely, subject to the following restrictions: 11 | 12 | 1. The origin of this software must not be misrepresented; you must 13 | not claim that you wrote the original software. If you use this 14 | software in a product, an acknowledgment in the product documentation 15 | would be appreciated but is not required. 16 | 17 | 2. Altered source versions must be plainly marked as such, and 18 | must not be misrepresented as being the original software. 19 | 20 | 3. This notice may not be removed or altered from any source 21 | distribution. 22 | */ 23 | 24 | #ifndef TINYXML2_INCLUDED 25 | #define TINYXML2_INCLUDED 26 | 27 | #if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) 28 | # include 29 | # include 30 | # include 31 | # include 32 | # include 33 | # if defined(__PS3__) 34 | # include 35 | # endif 36 | #else 37 | # include 38 | # include 39 | # include 40 | # include 41 | # include 42 | #endif 43 | #include 44 | 45 | /* 46 | TODO: intern strings instead of allocation. 47 | */ 48 | /* 49 | gcc: 50 | g++ -Wall -DTINYXML2_DEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe 51 | 52 | Formatting, Artistic Style: 53 | AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h 54 | */ 55 | 56 | #if defined( _DEBUG ) || defined (__DEBUG__) 57 | # ifndef TINYXML2_DEBUG 58 | # define TINYXML2_DEBUG 59 | # endif 60 | #endif 61 | 62 | #ifdef _MSC_VER 63 | # pragma warning(push) 64 | # pragma warning(disable: 4251) 65 | #endif 66 | 67 | #ifdef _WIN32 68 | # ifdef TINYXML2_EXPORT 69 | # define TINYXML2_LIB __declspec(dllexport) 70 | # elif defined(TINYXML2_IMPORT) 71 | # define TINYXML2_LIB __declspec(dllimport) 72 | # else 73 | # define TINYXML2_LIB 74 | # endif 75 | #elif __GNUC__ >= 4 76 | # define TINYXML2_LIB __attribute__((visibility("default"))) 77 | #else 78 | # define TINYXML2_LIB 79 | #endif 80 | 81 | 82 | #if defined(TINYXML2_DEBUG) 83 | # if defined(_MSC_VER) 84 | # // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like 85 | # define TIXMLASSERT( x ) if ( !((void)0,(x))) { __debugbreak(); } 86 | # elif defined (ANDROID_NDK) 87 | # include 88 | # define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } 89 | # else 90 | # include 91 | # define TIXMLASSERT assert 92 | # endif 93 | #else 94 | # define TIXMLASSERT( x ) {} 95 | #endif 96 | 97 | 98 | /* Versioning, past 1.0.14: 99 | http://semver.org/ 100 | */ 101 | static const int TIXML2_MAJOR_VERSION = 6; 102 | static const int TIXML2_MINOR_VERSION = 2; 103 | static const int TIXML2_PATCH_VERSION = 0; 104 | 105 | #define TINYXML2_MAJOR_VERSION 6 106 | #define TINYXML2_MINOR_VERSION 2 107 | #define TINYXML2_PATCH_VERSION 0 108 | 109 | // A fixed element depth limit is problematic. There needs to be a 110 | // limit to avoid a stack overflow. However, that limit varies per 111 | // system, and the capacity of the stack. On the other hand, it's a trivial 112 | // attack that can result from ill, malicious, or even correctly formed XML, 113 | // so there needs to be a limit in place. 114 | static const int TINYXML2_MAX_ELEMENT_DEPTH = 100; 115 | 116 | namespace tinyxml2 117 | { 118 | class XMLDocument; 119 | class XMLElement; 120 | class XMLAttribute; 121 | class XMLComment; 122 | class XMLText; 123 | class XMLDeclaration; 124 | class XMLUnknown; 125 | class XMLPrinter; 126 | 127 | /* 128 | A class that wraps strings. Normally stores the start and end 129 | pointers into the XML file itself, and will apply normalization 130 | and entity translation if actually read. Can also store (and memory 131 | manage) a traditional char[] 132 | */ 133 | class StrPair 134 | { 135 | public: 136 | enum { 137 | NEEDS_ENTITY_PROCESSING = 0x01, 138 | NEEDS_NEWLINE_NORMALIZATION = 0x02, 139 | NEEDS_WHITESPACE_COLLAPSING = 0x04, 140 | 141 | TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, 142 | TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, 143 | ATTRIBUTE_NAME = 0, 144 | ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, 145 | ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, 146 | COMMENT = NEEDS_NEWLINE_NORMALIZATION 147 | }; 148 | 149 | StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {} 150 | ~StrPair(); 151 | 152 | void Set( char* start, char* end, int flags ) { 153 | TIXMLASSERT( start ); 154 | TIXMLASSERT( end ); 155 | Reset(); 156 | _start = start; 157 | _end = end; 158 | _flags = flags | NEEDS_FLUSH; 159 | } 160 | 161 | const char* GetStr(); 162 | 163 | bool Empty() const { 164 | return _start == _end; 165 | } 166 | 167 | void SetInternedStr( const char* str ) { 168 | Reset(); 169 | _start = const_cast(str); 170 | } 171 | 172 | void SetStr( const char* str, int flags=0 ); 173 | 174 | char* ParseText( char* in, const char* endTag, int strFlags, int* curLineNumPtr ); 175 | char* ParseName( char* in ); 176 | 177 | void TransferTo( StrPair* other ); 178 | void Reset(); 179 | 180 | private: 181 | void CollapseWhitespace(); 182 | 183 | enum { 184 | NEEDS_FLUSH = 0x100, 185 | NEEDS_DELETE = 0x200 186 | }; 187 | 188 | int _flags; 189 | char* _start; 190 | char* _end; 191 | 192 | StrPair( const StrPair& other ); // not supported 193 | void operator=( StrPair& other ); // not supported, use TransferTo() 194 | }; 195 | 196 | 197 | /* 198 | A dynamic array of Plain Old Data. Doesn't support constructors, etc. 199 | Has a small initial memory pool, so that low or no usage will not 200 | cause a call to new/delete 201 | */ 202 | template 203 | class DynArray 204 | { 205 | public: 206 | DynArray() : 207 | _mem( _pool ), 208 | _allocated( INITIAL_SIZE ), 209 | _size( 0 ) 210 | { 211 | } 212 | 213 | ~DynArray() { 214 | if ( _mem != _pool ) { 215 | delete [] _mem; 216 | } 217 | } 218 | 219 | void Clear() { 220 | _size = 0; 221 | } 222 | 223 | void Push( T t ) { 224 | TIXMLASSERT( _size < INT_MAX ); 225 | EnsureCapacity( _size+1 ); 226 | _mem[_size] = t; 227 | ++_size; 228 | } 229 | 230 | T* PushArr( int count ) { 231 | TIXMLASSERT( count >= 0 ); 232 | TIXMLASSERT( _size <= INT_MAX - count ); 233 | EnsureCapacity( _size+count ); 234 | T* ret = &_mem[_size]; 235 | _size += count; 236 | return ret; 237 | } 238 | 239 | T Pop() { 240 | TIXMLASSERT( _size > 0 ); 241 | --_size; 242 | return _mem[_size]; 243 | } 244 | 245 | void PopArr( int count ) { 246 | TIXMLASSERT( _size >= count ); 247 | _size -= count; 248 | } 249 | 250 | bool Empty() const { 251 | return _size == 0; 252 | } 253 | 254 | T& operator[](int i) { 255 | TIXMLASSERT( i>= 0 && i < _size ); 256 | return _mem[i]; 257 | } 258 | 259 | const T& operator[](int i) const { 260 | TIXMLASSERT( i>= 0 && i < _size ); 261 | return _mem[i]; 262 | } 263 | 264 | const T& PeekTop() const { 265 | TIXMLASSERT( _size > 0 ); 266 | return _mem[ _size - 1]; 267 | } 268 | 269 | int Size() const { 270 | TIXMLASSERT( _size >= 0 ); 271 | return _size; 272 | } 273 | 274 | int Capacity() const { 275 | TIXMLASSERT( _allocated >= INITIAL_SIZE ); 276 | return _allocated; 277 | } 278 | 279 | void SwapRemove(int i) { 280 | TIXMLASSERT(i >= 0 && i < _size); 281 | TIXMLASSERT(_size > 0); 282 | _mem[i] = _mem[_size - 1]; 283 | --_size; 284 | } 285 | 286 | const T* Mem() const { 287 | TIXMLASSERT( _mem ); 288 | return _mem; 289 | } 290 | 291 | T* Mem() { 292 | TIXMLASSERT( _mem ); 293 | return _mem; 294 | } 295 | 296 | private: 297 | DynArray( const DynArray& ); // not supported 298 | void operator=( const DynArray& ); // not supported 299 | 300 | void EnsureCapacity( int cap ) { 301 | TIXMLASSERT( cap > 0 ); 302 | if ( cap > _allocated ) { 303 | TIXMLASSERT( cap <= INT_MAX / 2 ); 304 | int newAllocated = cap * 2; 305 | T* newMem = new T[newAllocated]; 306 | TIXMLASSERT( newAllocated >= _size ); 307 | memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs 308 | if ( _mem != _pool ) { 309 | delete [] _mem; 310 | } 311 | _mem = newMem; 312 | _allocated = newAllocated; 313 | } 314 | } 315 | 316 | T* _mem; 317 | T _pool[INITIAL_SIZE]; 318 | int _allocated; // objects allocated 319 | int _size; // number objects in use 320 | }; 321 | 322 | 323 | /* 324 | Parent virtual class of a pool for fast allocation 325 | and deallocation of objects. 326 | */ 327 | class MemPool 328 | { 329 | public: 330 | MemPool() {} 331 | virtual ~MemPool() {} 332 | 333 | virtual int ItemSize() const = 0; 334 | virtual void* Alloc() = 0; 335 | virtual void Free( void* ) = 0; 336 | virtual void SetTracked() = 0; 337 | virtual void Clear() = 0; 338 | }; 339 | 340 | 341 | /* 342 | Template child class to create pools of the correct type. 343 | */ 344 | template< int ITEM_SIZE > 345 | class MemPoolT : public MemPool 346 | { 347 | public: 348 | MemPoolT() : _blockPtrs(), _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} 349 | ~MemPoolT() { 350 | Clear(); 351 | } 352 | 353 | void Clear() { 354 | // Delete the blocks. 355 | while( !_blockPtrs.Empty()) { 356 | Block* lastBlock = _blockPtrs.Pop(); 357 | delete lastBlock; 358 | } 359 | _root = 0; 360 | _currentAllocs = 0; 361 | _nAllocs = 0; 362 | _maxAllocs = 0; 363 | _nUntracked = 0; 364 | } 365 | 366 | virtual int ItemSize() const { 367 | return ITEM_SIZE; 368 | } 369 | int CurrentAllocs() const { 370 | return _currentAllocs; 371 | } 372 | 373 | virtual void* Alloc() { 374 | if ( !_root ) { 375 | // Need a new block. 376 | Block* block = new Block(); 377 | _blockPtrs.Push( block ); 378 | 379 | Item* blockItems = block->items; 380 | for( int i = 0; i < ITEMS_PER_BLOCK - 1; ++i ) { 381 | blockItems[i].next = &(blockItems[i + 1]); 382 | } 383 | blockItems[ITEMS_PER_BLOCK - 1].next = 0; 384 | _root = blockItems; 385 | } 386 | Item* const result = _root; 387 | TIXMLASSERT( result != 0 ); 388 | _root = _root->next; 389 | 390 | ++_currentAllocs; 391 | if ( _currentAllocs > _maxAllocs ) { 392 | _maxAllocs = _currentAllocs; 393 | } 394 | ++_nAllocs; 395 | ++_nUntracked; 396 | return result; 397 | } 398 | 399 | virtual void Free( void* mem ) { 400 | if ( !mem ) { 401 | return; 402 | } 403 | --_currentAllocs; 404 | Item* item = static_cast( mem ); 405 | #ifdef TINYXML2_DEBUG 406 | memset( item, 0xfe, sizeof( *item ) ); 407 | #endif 408 | item->next = _root; 409 | _root = item; 410 | } 411 | void Trace( const char* name ) { 412 | printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", 413 | name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs, 414 | ITEM_SIZE, _nAllocs, _blockPtrs.Size() ); 415 | } 416 | 417 | void SetTracked() { 418 | --_nUntracked; 419 | } 420 | 421 | int Untracked() const { 422 | return _nUntracked; 423 | } 424 | 425 | // This number is perf sensitive. 4k seems like a good tradeoff on my machine. 426 | // The test file is large, 170k. 427 | // Release: VS2010 gcc(no opt) 428 | // 1k: 4000 429 | // 2k: 4000 430 | // 4k: 3900 21000 431 | // 16k: 5200 432 | // 32k: 4300 433 | // 64k: 4000 21000 434 | // Declared public because some compilers do not accept to use ITEMS_PER_BLOCK 435 | // in private part if ITEMS_PER_BLOCK is private 436 | enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE }; 437 | 438 | private: 439 | MemPoolT( const MemPoolT& ); // not supported 440 | void operator=( const MemPoolT& ); // not supported 441 | 442 | union Item { 443 | Item* next; 444 | char itemData[ITEM_SIZE]; 445 | }; 446 | struct Block { 447 | Item items[ITEMS_PER_BLOCK]; 448 | }; 449 | DynArray< Block*, 10 > _blockPtrs; 450 | Item* _root; 451 | 452 | int _currentAllocs; 453 | int _nAllocs; 454 | int _maxAllocs; 455 | int _nUntracked; 456 | }; 457 | 458 | 459 | 460 | /** 461 | Implements the interface to the "Visitor pattern" (see the Accept() method.) 462 | If you call the Accept() method, it requires being passed a XMLVisitor 463 | class to handle callbacks. For nodes that contain other nodes (Document, Element) 464 | you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs 465 | are simply called with Visit(). 466 | 467 | If you return 'true' from a Visit method, recursive parsing will continue. If you return 468 | false, no children of this node or its siblings will be visited. 469 | 470 | All flavors of Visit methods have a default implementation that returns 'true' (continue 471 | visiting). You need to only override methods that are interesting to you. 472 | 473 | Generally Accept() is called on the XMLDocument, although all nodes support visiting. 474 | 475 | You should never change the document from a callback. 476 | 477 | @sa XMLNode::Accept() 478 | */ 479 | class TINYXML2_LIB XMLVisitor 480 | { 481 | public: 482 | virtual ~XMLVisitor() {} 483 | 484 | /// Visit a document. 485 | virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { 486 | return true; 487 | } 488 | /// Visit a document. 489 | virtual bool VisitExit( const XMLDocument& /*doc*/ ) { 490 | return true; 491 | } 492 | 493 | /// Visit an element. 494 | virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { 495 | return true; 496 | } 497 | /// Visit an element. 498 | virtual bool VisitExit( const XMLElement& /*element*/ ) { 499 | return true; 500 | } 501 | 502 | /// Visit a declaration. 503 | virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { 504 | return true; 505 | } 506 | /// Visit a text node. 507 | virtual bool Visit( const XMLText& /*text*/ ) { 508 | return true; 509 | } 510 | /// Visit a comment node. 511 | virtual bool Visit( const XMLComment& /*comment*/ ) { 512 | return true; 513 | } 514 | /// Visit an unknown node. 515 | virtual bool Visit( const XMLUnknown& /*unknown*/ ) { 516 | return true; 517 | } 518 | }; 519 | 520 | // WARNING: must match XMLDocument::_errorNames[] 521 | enum XMLError { 522 | XML_SUCCESS = 0, 523 | XML_NO_ATTRIBUTE, 524 | XML_WRONG_ATTRIBUTE_TYPE, 525 | XML_ERROR_FILE_NOT_FOUND, 526 | XML_ERROR_FILE_COULD_NOT_BE_OPENED, 527 | XML_ERROR_FILE_READ_ERROR, 528 | XML_ERROR_PARSING_ELEMENT, 529 | XML_ERROR_PARSING_ATTRIBUTE, 530 | XML_ERROR_PARSING_TEXT, 531 | XML_ERROR_PARSING_CDATA, 532 | XML_ERROR_PARSING_COMMENT, 533 | XML_ERROR_PARSING_DECLARATION, 534 | XML_ERROR_PARSING_UNKNOWN, 535 | XML_ERROR_EMPTY_DOCUMENT, 536 | XML_ERROR_MISMATCHED_ELEMENT, 537 | XML_ERROR_PARSING, 538 | XML_CAN_NOT_CONVERT_TEXT, 539 | XML_NO_TEXT_NODE, 540 | XML_ELEMENT_DEPTH_EXCEEDED, 541 | 542 | XML_ERROR_COUNT 543 | }; 544 | 545 | 546 | /* 547 | Utility functionality. 548 | */ 549 | class TINYXML2_LIB XMLUtil 550 | { 551 | public: 552 | static const char* SkipWhiteSpace( const char* p, int* curLineNumPtr ) { 553 | TIXMLASSERT( p ); 554 | 555 | while( IsWhiteSpace(*p) ) { 556 | if (curLineNumPtr && *p == '\n') { 557 | ++(*curLineNumPtr); 558 | } 559 | ++p; 560 | } 561 | TIXMLASSERT( p ); 562 | return p; 563 | } 564 | static char* SkipWhiteSpace( char* p, int* curLineNumPtr ) { 565 | return const_cast( SkipWhiteSpace( const_cast(p), curLineNumPtr ) ); 566 | } 567 | 568 | // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't 569 | // correct, but simple, and usually works. 570 | static bool IsWhiteSpace( char p ) { 571 | return !IsUTF8Continuation(p) && isspace( static_cast(p) ); 572 | } 573 | 574 | inline static bool IsNameStartChar( unsigned char ch ) { 575 | if ( ch >= 128 ) { 576 | // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() 577 | return true; 578 | } 579 | if ( isalpha( ch ) ) { 580 | return true; 581 | } 582 | return ch == ':' || ch == '_'; 583 | } 584 | 585 | inline static bool IsNameChar( unsigned char ch ) { 586 | return IsNameStartChar( ch ) 587 | || isdigit( ch ) 588 | || ch == '.' 589 | || ch == '-'; 590 | } 591 | 592 | inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) { 593 | if ( p == q ) { 594 | return true; 595 | } 596 | TIXMLASSERT( p ); 597 | TIXMLASSERT( q ); 598 | TIXMLASSERT( nChar >= 0 ); 599 | return strncmp( p, q, nChar ) == 0; 600 | } 601 | 602 | inline static bool IsUTF8Continuation( char p ) { 603 | return ( p & 0x80 ) != 0; 604 | } 605 | 606 | static const char* ReadBOM( const char* p, bool* hasBOM ); 607 | // p is the starting location, 608 | // the UTF-8 value of the entity will be placed in value, and length filled in. 609 | static const char* GetCharacterRef( const char* p, char* value, int* length ); 610 | static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); 611 | 612 | // converts primitive types to strings 613 | static void ToStr( int v, char* buffer, int bufferSize ); 614 | static void ToStr( unsigned v, char* buffer, int bufferSize ); 615 | static void ToStr( bool v, char* buffer, int bufferSize ); 616 | static void ToStr( float v, char* buffer, int bufferSize ); 617 | static void ToStr( double v, char* buffer, int bufferSize ); 618 | static void ToStr(int64_t v, char* buffer, int bufferSize); 619 | 620 | // converts strings to primitive types 621 | static bool ToInt( const char* str, int* value ); 622 | static bool ToUnsigned( const char* str, unsigned* value ); 623 | static bool ToBool( const char* str, bool* value ); 624 | static bool ToFloat( const char* str, float* value ); 625 | static bool ToDouble( const char* str, double* value ); 626 | static bool ToInt64(const char* str, int64_t* value); 627 | 628 | // Changes what is serialized for a boolean value. 629 | // Default to "true" and "false". Shouldn't be changed 630 | // unless you have a special testing or compatibility need. 631 | // Be careful: static, global, & not thread safe. 632 | // Be sure to set static const memory as parameters. 633 | static void SetBoolSerialization(const char* writeTrue, const char* writeFalse); 634 | 635 | private: 636 | static const char* writeBoolTrue; 637 | static const char* writeBoolFalse; 638 | }; 639 | 640 | 641 | /** XMLNode is a base class for every object that is in the 642 | XML Document Object Model (DOM), except XMLAttributes. 643 | Nodes have siblings, a parent, and children which can 644 | be navigated. A node is always in a XMLDocument. 645 | The type of a XMLNode can be queried, and it can 646 | be cast to its more defined type. 647 | 648 | A XMLDocument allocates memory for all its Nodes. 649 | When the XMLDocument gets deleted, all its Nodes 650 | will also be deleted. 651 | 652 | @verbatim 653 | A Document can contain: Element (container or leaf) 654 | Comment (leaf) 655 | Unknown (leaf) 656 | Declaration( leaf ) 657 | 658 | An Element can contain: Element (container or leaf) 659 | Text (leaf) 660 | Attributes (not on tree) 661 | Comment (leaf) 662 | Unknown (leaf) 663 | 664 | @endverbatim 665 | */ 666 | class TINYXML2_LIB XMLNode 667 | { 668 | friend class XMLDocument; 669 | friend class XMLElement; 670 | public: 671 | 672 | /// Get the XMLDocument that owns this XMLNode. 673 | const XMLDocument* GetDocument() const { 674 | TIXMLASSERT( _document ); 675 | return _document; 676 | } 677 | /// Get the XMLDocument that owns this XMLNode. 678 | XMLDocument* GetDocument() { 679 | TIXMLASSERT( _document ); 680 | return _document; 681 | } 682 | 683 | /// Safely cast to an Element, or null. 684 | virtual XMLElement* ToElement() { 685 | return 0; 686 | } 687 | /// Safely cast to Text, or null. 688 | virtual XMLText* ToText() { 689 | return 0; 690 | } 691 | /// Safely cast to a Comment, or null. 692 | virtual XMLComment* ToComment() { 693 | return 0; 694 | } 695 | /// Safely cast to a Document, or null. 696 | virtual XMLDocument* ToDocument() { 697 | return 0; 698 | } 699 | /// Safely cast to a Declaration, or null. 700 | virtual XMLDeclaration* ToDeclaration() { 701 | return 0; 702 | } 703 | /// Safely cast to an Unknown, or null. 704 | virtual XMLUnknown* ToUnknown() { 705 | return 0; 706 | } 707 | 708 | virtual const XMLElement* ToElement() const { 709 | return 0; 710 | } 711 | virtual const XMLText* ToText() const { 712 | return 0; 713 | } 714 | virtual const XMLComment* ToComment() const { 715 | return 0; 716 | } 717 | virtual const XMLDocument* ToDocument() const { 718 | return 0; 719 | } 720 | virtual const XMLDeclaration* ToDeclaration() const { 721 | return 0; 722 | } 723 | virtual const XMLUnknown* ToUnknown() const { 724 | return 0; 725 | } 726 | 727 | /** The meaning of 'value' changes for the specific type. 728 | @verbatim 729 | Document: empty (NULL is returned, not an empty string) 730 | Element: name of the element 731 | Comment: the comment text 732 | Unknown: the tag contents 733 | Text: the text string 734 | @endverbatim 735 | */ 736 | const char* Value() const; 737 | 738 | /** Set the Value of an XML node. 739 | @sa Value() 740 | */ 741 | void SetValue( const char* val, bool staticMem=false ); 742 | 743 | /// Gets the line number the node is in, if the document was parsed from a file. 744 | int GetLineNum() const { return _parseLineNum; } 745 | 746 | /// Get the parent of this node on the DOM. 747 | const XMLNode* Parent() const { 748 | return _parent; 749 | } 750 | 751 | XMLNode* Parent() { 752 | return _parent; 753 | } 754 | 755 | /// Returns true if this node has no children. 756 | bool NoChildren() const { 757 | return !_firstChild; 758 | } 759 | 760 | /// Get the first child node, or null if none exists. 761 | const XMLNode* FirstChild() const { 762 | return _firstChild; 763 | } 764 | 765 | XMLNode* FirstChild() { 766 | return _firstChild; 767 | } 768 | 769 | /** Get the first child element, or optionally the first child 770 | element with the specified name. 771 | */ 772 | const XMLElement* FirstChildElement( const char* name = 0 ) const; 773 | 774 | XMLElement* FirstChildElement( const char* name = 0 ) { 775 | return const_cast(const_cast(this)->FirstChildElement( name )); 776 | } 777 | 778 | /// Get the last child node, or null if none exists. 779 | const XMLNode* LastChild() const { 780 | return _lastChild; 781 | } 782 | 783 | XMLNode* LastChild() { 784 | return _lastChild; 785 | } 786 | 787 | /** Get the last child element or optionally the last child 788 | element with the specified name. 789 | */ 790 | const XMLElement* LastChildElement( const char* name = 0 ) const; 791 | 792 | XMLElement* LastChildElement( const char* name = 0 ) { 793 | return const_cast(const_cast(this)->LastChildElement(name) ); 794 | } 795 | 796 | /// Get the previous (left) sibling node of this node. 797 | const XMLNode* PreviousSibling() const { 798 | return _prev; 799 | } 800 | 801 | XMLNode* PreviousSibling() { 802 | return _prev; 803 | } 804 | 805 | /// Get the previous (left) sibling element of this node, with an optionally supplied name. 806 | const XMLElement* PreviousSiblingElement( const char* name = 0 ) const ; 807 | 808 | XMLElement* PreviousSiblingElement( const char* name = 0 ) { 809 | return const_cast(const_cast(this)->PreviousSiblingElement( name ) ); 810 | } 811 | 812 | /// Get the next (right) sibling node of this node. 813 | const XMLNode* NextSibling() const { 814 | return _next; 815 | } 816 | 817 | XMLNode* NextSibling() { 818 | return _next; 819 | } 820 | 821 | /// Get the next (right) sibling element of this node, with an optionally supplied name. 822 | const XMLElement* NextSiblingElement( const char* name = 0 ) const; 823 | 824 | XMLElement* NextSiblingElement( const char* name = 0 ) { 825 | return const_cast(const_cast(this)->NextSiblingElement( name ) ); 826 | } 827 | 828 | /** 829 | Add a child node as the last (right) child. 830 | If the child node is already part of the document, 831 | it is moved from its old location to the new location. 832 | Returns the addThis argument or 0 if the node does not 833 | belong to the same document. 834 | */ 835 | XMLNode* InsertEndChild( XMLNode* addThis ); 836 | 837 | XMLNode* LinkEndChild( XMLNode* addThis ) { 838 | return InsertEndChild( addThis ); 839 | } 840 | /** 841 | Add a child node as the first (left) child. 842 | If the child node is already part of the document, 843 | it is moved from its old location to the new location. 844 | Returns the addThis argument or 0 if the node does not 845 | belong to the same document. 846 | */ 847 | XMLNode* InsertFirstChild( XMLNode* addThis ); 848 | /** 849 | Add a node after the specified child node. 850 | If the child node is already part of the document, 851 | it is moved from its old location to the new location. 852 | Returns the addThis argument or 0 if the afterThis node 853 | is not a child of this node, or if the node does not 854 | belong to the same document. 855 | */ 856 | XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ); 857 | 858 | /** 859 | Delete all the children of this node. 860 | */ 861 | void DeleteChildren(); 862 | 863 | /** 864 | Delete a child of this node. 865 | */ 866 | void DeleteChild( XMLNode* node ); 867 | 868 | /** 869 | Make a copy of this node, but not its children. 870 | You may pass in a Document pointer that will be 871 | the owner of the new Node. If the 'document' is 872 | null, then the node returned will be allocated 873 | from the current Document. (this->GetDocument()) 874 | 875 | Note: if called on a XMLDocument, this will return null. 876 | */ 877 | virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0; 878 | 879 | /** 880 | Make a copy of this node and all its children. 881 | 882 | If the 'target' is null, then the nodes will 883 | be allocated in the current document. If 'target' 884 | is specified, the memory will be allocated is the 885 | specified XMLDocument. 886 | 887 | NOTE: This is probably not the correct tool to 888 | copy a document, since XMLDocuments can have multiple 889 | top level XMLNodes. You probably want to use 890 | XMLDocument::DeepCopy() 891 | */ 892 | XMLNode* DeepClone( XMLDocument* target ) const; 893 | 894 | /** 895 | Test if 2 nodes are the same, but don't test children. 896 | The 2 nodes do not need to be in the same Document. 897 | 898 | Note: if called on a XMLDocument, this will return false. 899 | */ 900 | virtual bool ShallowEqual( const XMLNode* compare ) const = 0; 901 | 902 | /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the 903 | XML tree will be conditionally visited and the host will be called back 904 | via the XMLVisitor interface. 905 | 906 | This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse 907 | the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this 908 | interface versus any other.) 909 | 910 | The interface has been based on ideas from: 911 | 912 | - http://www.saxproject.org/ 913 | - http://c2.com/cgi/wiki?HierarchicalVisitorPattern 914 | 915 | Which are both good references for "visiting". 916 | 917 | An example of using Accept(): 918 | @verbatim 919 | XMLPrinter printer; 920 | tinyxmlDoc.Accept( &printer ); 921 | const char* xmlcstr = printer.CStr(); 922 | @endverbatim 923 | */ 924 | virtual bool Accept( XMLVisitor* visitor ) const = 0; 925 | 926 | /** 927 | Set user data into the XMLNode. TinyXML-2 in 928 | no way processes or interprets user data. 929 | It is initially 0. 930 | */ 931 | void SetUserData(void* userData) { _userData = userData; } 932 | 933 | /** 934 | Get user data set into the XMLNode. TinyXML-2 in 935 | no way processes or interprets user data. 936 | It is initially 0. 937 | */ 938 | void* GetUserData() const { return _userData; } 939 | 940 | protected: 941 | XMLNode( XMLDocument* ); 942 | virtual ~XMLNode(); 943 | 944 | virtual char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); 945 | 946 | XMLDocument* _document; 947 | XMLNode* _parent; 948 | mutable StrPair _value; 949 | int _parseLineNum; 950 | 951 | XMLNode* _firstChild; 952 | XMLNode* _lastChild; 953 | 954 | XMLNode* _prev; 955 | XMLNode* _next; 956 | 957 | void* _userData; 958 | 959 | private: 960 | MemPool* _memPool; 961 | void Unlink( XMLNode* child ); 962 | static void DeleteNode( XMLNode* node ); 963 | void InsertChildPreamble( XMLNode* insertThis ) const; 964 | const XMLElement* ToElementWithName( const char* name ) const; 965 | 966 | XMLNode( const XMLNode& ); // not supported 967 | XMLNode& operator=( const XMLNode& ); // not supported 968 | }; 969 | 970 | 971 | /** XML text. 972 | 973 | Note that a text node can have child element nodes, for example: 974 | @verbatim 975 | This is bold 976 | @endverbatim 977 | 978 | A text node can have 2 ways to output the next. "normal" output 979 | and CDATA. It will default to the mode it was parsed from the XML file and 980 | you generally want to leave it alone, but you can change the output mode with 981 | SetCData() and query it with CData(). 982 | */ 983 | class TINYXML2_LIB XMLText : public XMLNode 984 | { 985 | friend class XMLDocument; 986 | public: 987 | virtual bool Accept( XMLVisitor* visitor ) const; 988 | 989 | virtual XMLText* ToText() { 990 | return this; 991 | } 992 | virtual const XMLText* ToText() const { 993 | return this; 994 | } 995 | 996 | /// Declare whether this should be CDATA or standard text. 997 | void SetCData( bool isCData ) { 998 | _isCData = isCData; 999 | } 1000 | /// Returns true if this is a CDATA text element. 1001 | bool CData() const { 1002 | return _isCData; 1003 | } 1004 | 1005 | virtual XMLNode* ShallowClone( XMLDocument* document ) const; 1006 | virtual bool ShallowEqual( const XMLNode* compare ) const; 1007 | 1008 | protected: 1009 | XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {} 1010 | virtual ~XMLText() {} 1011 | 1012 | char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); 1013 | 1014 | private: 1015 | bool _isCData; 1016 | 1017 | XMLText( const XMLText& ); // not supported 1018 | XMLText& operator=( const XMLText& ); // not supported 1019 | }; 1020 | 1021 | 1022 | /** An XML Comment. */ 1023 | class TINYXML2_LIB XMLComment : public XMLNode 1024 | { 1025 | friend class XMLDocument; 1026 | public: 1027 | virtual XMLComment* ToComment() { 1028 | return this; 1029 | } 1030 | virtual const XMLComment* ToComment() const { 1031 | return this; 1032 | } 1033 | 1034 | virtual bool Accept( XMLVisitor* visitor ) const; 1035 | 1036 | virtual XMLNode* ShallowClone( XMLDocument* document ) const; 1037 | virtual bool ShallowEqual( const XMLNode* compare ) const; 1038 | 1039 | protected: 1040 | XMLComment( XMLDocument* doc ); 1041 | virtual ~XMLComment(); 1042 | 1043 | char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); 1044 | 1045 | private: 1046 | XMLComment( const XMLComment& ); // not supported 1047 | XMLComment& operator=( const XMLComment& ); // not supported 1048 | }; 1049 | 1050 | 1051 | /** In correct XML the declaration is the first entry in the file. 1052 | @verbatim 1053 | 1054 | @endverbatim 1055 | 1056 | TinyXML-2 will happily read or write files without a declaration, 1057 | however. 1058 | 1059 | The text of the declaration isn't interpreted. It is parsed 1060 | and written as a string. 1061 | */ 1062 | class TINYXML2_LIB XMLDeclaration : public XMLNode 1063 | { 1064 | friend class XMLDocument; 1065 | public: 1066 | virtual XMLDeclaration* ToDeclaration() { 1067 | return this; 1068 | } 1069 | virtual const XMLDeclaration* ToDeclaration() const { 1070 | return this; 1071 | } 1072 | 1073 | virtual bool Accept( XMLVisitor* visitor ) const; 1074 | 1075 | virtual XMLNode* ShallowClone( XMLDocument* document ) const; 1076 | virtual bool ShallowEqual( const XMLNode* compare ) const; 1077 | 1078 | protected: 1079 | XMLDeclaration( XMLDocument* doc ); 1080 | virtual ~XMLDeclaration(); 1081 | 1082 | char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); 1083 | 1084 | private: 1085 | XMLDeclaration( const XMLDeclaration& ); // not supported 1086 | XMLDeclaration& operator=( const XMLDeclaration& ); // not supported 1087 | }; 1088 | 1089 | 1090 | /** Any tag that TinyXML-2 doesn't recognize is saved as an 1091 | unknown. It is a tag of text, but should not be modified. 1092 | It will be written back to the XML, unchanged, when the file 1093 | is saved. 1094 | 1095 | DTD tags get thrown into XMLUnknowns. 1096 | */ 1097 | class TINYXML2_LIB XMLUnknown : public XMLNode 1098 | { 1099 | friend class XMLDocument; 1100 | public: 1101 | virtual XMLUnknown* ToUnknown() { 1102 | return this; 1103 | } 1104 | virtual const XMLUnknown* ToUnknown() const { 1105 | return this; 1106 | } 1107 | 1108 | virtual bool Accept( XMLVisitor* visitor ) const; 1109 | 1110 | virtual XMLNode* ShallowClone( XMLDocument* document ) const; 1111 | virtual bool ShallowEqual( const XMLNode* compare ) const; 1112 | 1113 | protected: 1114 | XMLUnknown( XMLDocument* doc ); 1115 | virtual ~XMLUnknown(); 1116 | 1117 | char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); 1118 | 1119 | private: 1120 | XMLUnknown( const XMLUnknown& ); // not supported 1121 | XMLUnknown& operator=( const XMLUnknown& ); // not supported 1122 | }; 1123 | 1124 | 1125 | 1126 | /** An attribute is a name-value pair. Elements have an arbitrary 1127 | number of attributes, each with a unique name. 1128 | 1129 | @note The attributes are not XMLNodes. You may only query the 1130 | Next() attribute in a list. 1131 | */ 1132 | class TINYXML2_LIB XMLAttribute 1133 | { 1134 | friend class XMLElement; 1135 | public: 1136 | /// The name of the attribute. 1137 | const char* Name() const; 1138 | 1139 | /// The value of the attribute. 1140 | const char* Value() const; 1141 | 1142 | /// Gets the line number the attribute is in, if the document was parsed from a file. 1143 | int GetLineNum() const { return _parseLineNum; } 1144 | 1145 | /// The next attribute in the list. 1146 | const XMLAttribute* Next() const { 1147 | return _next; 1148 | } 1149 | 1150 | /** IntValue interprets the attribute as an integer, and returns the value. 1151 | If the value isn't an integer, 0 will be returned. There is no error checking; 1152 | use QueryIntValue() if you need error checking. 1153 | */ 1154 | int IntValue() const { 1155 | int i = 0; 1156 | QueryIntValue(&i); 1157 | return i; 1158 | } 1159 | 1160 | int64_t Int64Value() const { 1161 | int64_t i = 0; 1162 | QueryInt64Value(&i); 1163 | return i; 1164 | } 1165 | 1166 | /// Query as an unsigned integer. See IntValue() 1167 | unsigned UnsignedValue() const { 1168 | unsigned i=0; 1169 | QueryUnsignedValue( &i ); 1170 | return i; 1171 | } 1172 | /// Query as a boolean. See IntValue() 1173 | bool BoolValue() const { 1174 | bool b=false; 1175 | QueryBoolValue( &b ); 1176 | return b; 1177 | } 1178 | /// Query as a double. See IntValue() 1179 | double DoubleValue() const { 1180 | double d=0; 1181 | QueryDoubleValue( &d ); 1182 | return d; 1183 | } 1184 | /// Query as a float. See IntValue() 1185 | float FloatValue() const { 1186 | float f=0; 1187 | QueryFloatValue( &f ); 1188 | return f; 1189 | } 1190 | 1191 | /** QueryIntValue interprets the attribute as an integer, and returns the value 1192 | in the provided parameter. The function will return XML_SUCCESS on success, 1193 | and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. 1194 | */ 1195 | XMLError QueryIntValue( int* value ) const; 1196 | /// See QueryIntValue 1197 | XMLError QueryUnsignedValue( unsigned int* value ) const; 1198 | /// See QueryIntValue 1199 | XMLError QueryInt64Value(int64_t* value) const; 1200 | /// See QueryIntValue 1201 | XMLError QueryBoolValue( bool* value ) const; 1202 | /// See QueryIntValue 1203 | XMLError QueryDoubleValue( double* value ) const; 1204 | /// See QueryIntValue 1205 | XMLError QueryFloatValue( float* value ) const; 1206 | 1207 | /// Set the attribute to a string value. 1208 | void SetAttribute( const char* value ); 1209 | /// Set the attribute to value. 1210 | void SetAttribute( int value ); 1211 | /// Set the attribute to value. 1212 | void SetAttribute( unsigned value ); 1213 | /// Set the attribute to value. 1214 | void SetAttribute(int64_t value); 1215 | /// Set the attribute to value. 1216 | void SetAttribute( bool value ); 1217 | /// Set the attribute to value. 1218 | void SetAttribute( double value ); 1219 | /// Set the attribute to value. 1220 | void SetAttribute( float value ); 1221 | 1222 | private: 1223 | enum { BUF_SIZE = 200 }; 1224 | 1225 | XMLAttribute() : _name(), _value(),_parseLineNum( 0 ), _next( 0 ), _memPool( 0 ) {} 1226 | virtual ~XMLAttribute() {} 1227 | 1228 | XMLAttribute( const XMLAttribute& ); // not supported 1229 | void operator=( const XMLAttribute& ); // not supported 1230 | void SetName( const char* name ); 1231 | 1232 | char* ParseDeep( char* p, bool processEntities, int* curLineNumPtr ); 1233 | 1234 | mutable StrPair _name; 1235 | mutable StrPair _value; 1236 | int _parseLineNum; 1237 | XMLAttribute* _next; 1238 | MemPool* _memPool; 1239 | }; 1240 | 1241 | 1242 | /** The element is a container class. It has a value, the element name, 1243 | and can contain other elements, text, comments, and unknowns. 1244 | Elements also contain an arbitrary number of attributes. 1245 | */ 1246 | class TINYXML2_LIB XMLElement : public XMLNode 1247 | { 1248 | friend class XMLDocument; 1249 | public: 1250 | /// Get the name of an element (which is the Value() of the node.) 1251 | const char* Name() const { 1252 | return Value(); 1253 | } 1254 | /// Set the name of the element. 1255 | void SetName( const char* str, bool staticMem=false ) { 1256 | SetValue( str, staticMem ); 1257 | } 1258 | 1259 | virtual XMLElement* ToElement() { 1260 | return this; 1261 | } 1262 | virtual const XMLElement* ToElement() const { 1263 | return this; 1264 | } 1265 | virtual bool Accept( XMLVisitor* visitor ) const; 1266 | 1267 | /** Given an attribute name, Attribute() returns the value 1268 | for the attribute of that name, or null if none 1269 | exists. For example: 1270 | 1271 | @verbatim 1272 | const char* value = ele->Attribute( "foo" ); 1273 | @endverbatim 1274 | 1275 | The 'value' parameter is normally null. However, if specified, 1276 | the attribute will only be returned if the 'name' and 'value' 1277 | match. This allow you to write code: 1278 | 1279 | @verbatim 1280 | if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar(); 1281 | @endverbatim 1282 | 1283 | rather than: 1284 | @verbatim 1285 | if ( ele->Attribute( "foo" ) ) { 1286 | if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); 1287 | } 1288 | @endverbatim 1289 | */ 1290 | const char* Attribute( const char* name, const char* value=0 ) const; 1291 | 1292 | /** Given an attribute name, IntAttribute() returns the value 1293 | of the attribute interpreted as an integer. The default 1294 | value will be returned if the attribute isn't present, 1295 | or if there is an error. (For a method with error 1296 | checking, see QueryIntAttribute()). 1297 | */ 1298 | int IntAttribute(const char* name, int defaultValue = 0) const; 1299 | /// See IntAttribute() 1300 | unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const; 1301 | /// See IntAttribute() 1302 | int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const; 1303 | /// See IntAttribute() 1304 | bool BoolAttribute(const char* name, bool defaultValue = false) const; 1305 | /// See IntAttribute() 1306 | double DoubleAttribute(const char* name, double defaultValue = 0) const; 1307 | /// See IntAttribute() 1308 | float FloatAttribute(const char* name, float defaultValue = 0) const; 1309 | 1310 | /** Given an attribute name, QueryIntAttribute() returns 1311 | XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion 1312 | can't be performed, or XML_NO_ATTRIBUTE if the attribute 1313 | doesn't exist. If successful, the result of the conversion 1314 | will be written to 'value'. If not successful, nothing will 1315 | be written to 'value'. This allows you to provide default 1316 | value: 1317 | 1318 | @verbatim 1319 | int value = 10; 1320 | QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 1321 | @endverbatim 1322 | */ 1323 | XMLError QueryIntAttribute( const char* name, int* value ) const { 1324 | const XMLAttribute* a = FindAttribute( name ); 1325 | if ( !a ) { 1326 | return XML_NO_ATTRIBUTE; 1327 | } 1328 | return a->QueryIntValue( value ); 1329 | } 1330 | 1331 | /// See QueryIntAttribute() 1332 | XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const { 1333 | const XMLAttribute* a = FindAttribute( name ); 1334 | if ( !a ) { 1335 | return XML_NO_ATTRIBUTE; 1336 | } 1337 | return a->QueryUnsignedValue( value ); 1338 | } 1339 | 1340 | /// See QueryIntAttribute() 1341 | XMLError QueryInt64Attribute(const char* name, int64_t* value) const { 1342 | const XMLAttribute* a = FindAttribute(name); 1343 | if (!a) { 1344 | return XML_NO_ATTRIBUTE; 1345 | } 1346 | return a->QueryInt64Value(value); 1347 | } 1348 | 1349 | /// See QueryIntAttribute() 1350 | XMLError QueryBoolAttribute( const char* name, bool* value ) const { 1351 | const XMLAttribute* a = FindAttribute( name ); 1352 | if ( !a ) { 1353 | return XML_NO_ATTRIBUTE; 1354 | } 1355 | return a->QueryBoolValue( value ); 1356 | } 1357 | /// See QueryIntAttribute() 1358 | XMLError QueryDoubleAttribute( const char* name, double* value ) const { 1359 | const XMLAttribute* a = FindAttribute( name ); 1360 | if ( !a ) { 1361 | return XML_NO_ATTRIBUTE; 1362 | } 1363 | return a->QueryDoubleValue( value ); 1364 | } 1365 | /// See QueryIntAttribute() 1366 | XMLError QueryFloatAttribute( const char* name, float* value ) const { 1367 | const XMLAttribute* a = FindAttribute( name ); 1368 | if ( !a ) { 1369 | return XML_NO_ATTRIBUTE; 1370 | } 1371 | return a->QueryFloatValue( value ); 1372 | } 1373 | 1374 | /// See QueryIntAttribute() 1375 | XMLError QueryStringAttribute(const char* name, const char** value) const { 1376 | const XMLAttribute* a = FindAttribute(name); 1377 | if (!a) { 1378 | return XML_NO_ATTRIBUTE; 1379 | } 1380 | *value = a->Value(); 1381 | return XML_SUCCESS; 1382 | } 1383 | 1384 | 1385 | 1386 | /** Given an attribute name, QueryAttribute() returns 1387 | XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion 1388 | can't be performed, or XML_NO_ATTRIBUTE if the attribute 1389 | doesn't exist. It is overloaded for the primitive types, 1390 | and is a generally more convenient replacement of 1391 | QueryIntAttribute() and related functions. 1392 | 1393 | If successful, the result of the conversion 1394 | will be written to 'value'. If not successful, nothing will 1395 | be written to 'value'. This allows you to provide default 1396 | value: 1397 | 1398 | @verbatim 1399 | int value = 10; 1400 | QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 1401 | @endverbatim 1402 | */ 1403 | XMLError QueryAttribute( const char* name, int* value ) const { 1404 | return QueryIntAttribute( name, value ); 1405 | } 1406 | 1407 | XMLError QueryAttribute( const char* name, unsigned int* value ) const { 1408 | return QueryUnsignedAttribute( name, value ); 1409 | } 1410 | 1411 | XMLError QueryAttribute(const char* name, int64_t* value) const { 1412 | return QueryInt64Attribute(name, value); 1413 | } 1414 | 1415 | XMLError QueryAttribute( const char* name, bool* value ) const { 1416 | return QueryBoolAttribute( name, value ); 1417 | } 1418 | 1419 | XMLError QueryAttribute( const char* name, double* value ) const { 1420 | return QueryDoubleAttribute( name, value ); 1421 | } 1422 | 1423 | XMLError QueryAttribute( const char* name, float* value ) const { 1424 | return QueryFloatAttribute( name, value ); 1425 | } 1426 | 1427 | /// Sets the named attribute to value. 1428 | void SetAttribute( const char* name, const char* value ) { 1429 | XMLAttribute* a = FindOrCreateAttribute( name ); 1430 | a->SetAttribute( value ); 1431 | } 1432 | /// Sets the named attribute to value. 1433 | void SetAttribute( const char* name, int value ) { 1434 | XMLAttribute* a = FindOrCreateAttribute( name ); 1435 | a->SetAttribute( value ); 1436 | } 1437 | /// Sets the named attribute to value. 1438 | void SetAttribute( const char* name, unsigned value ) { 1439 | XMLAttribute* a = FindOrCreateAttribute( name ); 1440 | a->SetAttribute( value ); 1441 | } 1442 | 1443 | /// Sets the named attribute to value. 1444 | void SetAttribute(const char* name, int64_t value) { 1445 | XMLAttribute* a = FindOrCreateAttribute(name); 1446 | a->SetAttribute(value); 1447 | } 1448 | 1449 | /// Sets the named attribute to value. 1450 | void SetAttribute( const char* name, bool value ) { 1451 | XMLAttribute* a = FindOrCreateAttribute( name ); 1452 | a->SetAttribute( value ); 1453 | } 1454 | /// Sets the named attribute to value. 1455 | void SetAttribute( const char* name, double value ) { 1456 | XMLAttribute* a = FindOrCreateAttribute( name ); 1457 | a->SetAttribute( value ); 1458 | } 1459 | /// Sets the named attribute to value. 1460 | void SetAttribute( const char* name, float value ) { 1461 | XMLAttribute* a = FindOrCreateAttribute( name ); 1462 | a->SetAttribute( value ); 1463 | } 1464 | 1465 | /** 1466 | Delete an attribute. 1467 | */ 1468 | void DeleteAttribute( const char* name ); 1469 | 1470 | /// Return the first attribute in the list. 1471 | const XMLAttribute* FirstAttribute() const { 1472 | return _rootAttribute; 1473 | } 1474 | /// Query a specific attribute in the list. 1475 | const XMLAttribute* FindAttribute( const char* name ) const; 1476 | 1477 | /** Convenience function for easy access to the text inside an element. Although easy 1478 | and concise, GetText() is limited compared to getting the XMLText child 1479 | and accessing it directly. 1480 | 1481 | If the first child of 'this' is a XMLText, the GetText() 1482 | returns the character string of the Text node, else null is returned. 1483 | 1484 | This is a convenient method for getting the text of simple contained text: 1485 | @verbatim 1486 | This is text 1487 | const char* str = fooElement->GetText(); 1488 | @endverbatim 1489 | 1490 | 'str' will be a pointer to "This is text". 1491 | 1492 | Note that this function can be misleading. If the element foo was created from 1493 | this XML: 1494 | @verbatim 1495 | This is text 1496 | @endverbatim 1497 | 1498 | then the value of str would be null. The first child node isn't a text node, it is 1499 | another element. From this XML: 1500 | @verbatim 1501 | This is text 1502 | @endverbatim 1503 | GetText() will return "This is ". 1504 | */ 1505 | const char* GetText() const; 1506 | 1507 | /** Convenience function for easy access to the text inside an element. Although easy 1508 | and concise, SetText() is limited compared to creating an XMLText child 1509 | and mutating it directly. 1510 | 1511 | If the first child of 'this' is a XMLText, SetText() sets its value to 1512 | the given string, otherwise it will create a first child that is an XMLText. 1513 | 1514 | This is a convenient method for setting the text of simple contained text: 1515 | @verbatim 1516 | This is text 1517 | fooElement->SetText( "Hullaballoo!" ); 1518 | Hullaballoo! 1519 | @endverbatim 1520 | 1521 | Note that this function can be misleading. If the element foo was created from 1522 | this XML: 1523 | @verbatim 1524 | This is text 1525 | @endverbatim 1526 | 1527 | then it will not change "This is text", but rather prefix it with a text element: 1528 | @verbatim 1529 | Hullaballoo!This is text 1530 | @endverbatim 1531 | 1532 | For this XML: 1533 | @verbatim 1534 | 1535 | @endverbatim 1536 | SetText() will generate 1537 | @verbatim 1538 | Hullaballoo! 1539 | @endverbatim 1540 | */ 1541 | void SetText( const char* inText ); 1542 | /// Convenience method for setting text inside an element. See SetText() for important limitations. 1543 | void SetText( int value ); 1544 | /// Convenience method for setting text inside an element. See SetText() for important limitations. 1545 | void SetText( unsigned value ); 1546 | /// Convenience method for setting text inside an element. See SetText() for important limitations. 1547 | void SetText(int64_t value); 1548 | /// Convenience method for setting text inside an element. See SetText() for important limitations. 1549 | void SetText( bool value ); 1550 | /// Convenience method for setting text inside an element. See SetText() for important limitations. 1551 | void SetText( double value ); 1552 | /// Convenience method for setting text inside an element. See SetText() for important limitations. 1553 | void SetText( float value ); 1554 | 1555 | /** 1556 | Convenience method to query the value of a child text node. This is probably best 1557 | shown by example. Given you have a document is this form: 1558 | @verbatim 1559 | 1560 | 1 1561 | 1.4 1562 | 1563 | @endverbatim 1564 | 1565 | The QueryIntText() and similar functions provide a safe and easier way to get to the 1566 | "value" of x and y. 1567 | 1568 | @verbatim 1569 | int x = 0; 1570 | float y = 0; // types of x and y are contrived for example 1571 | const XMLElement* xElement = pointElement->FirstChildElement( "x" ); 1572 | const XMLElement* yElement = pointElement->FirstChildElement( "y" ); 1573 | xElement->QueryIntText( &x ); 1574 | yElement->QueryFloatText( &y ); 1575 | @endverbatim 1576 | 1577 | @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted 1578 | to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. 1579 | 1580 | */ 1581 | XMLError QueryIntText( int* ival ) const; 1582 | /// See QueryIntText() 1583 | XMLError QueryUnsignedText( unsigned* uval ) const; 1584 | /// See QueryIntText() 1585 | XMLError QueryInt64Text(int64_t* uval) const; 1586 | /// See QueryIntText() 1587 | XMLError QueryBoolText( bool* bval ) const; 1588 | /// See QueryIntText() 1589 | XMLError QueryDoubleText( double* dval ) const; 1590 | /// See QueryIntText() 1591 | XMLError QueryFloatText( float* fval ) const; 1592 | 1593 | int IntText(int defaultValue = 0) const; 1594 | 1595 | /// See QueryIntText() 1596 | unsigned UnsignedText(unsigned defaultValue = 0) const; 1597 | /// See QueryIntText() 1598 | int64_t Int64Text(int64_t defaultValue = 0) const; 1599 | /// See QueryIntText() 1600 | bool BoolText(bool defaultValue = false) const; 1601 | /// See QueryIntText() 1602 | double DoubleText(double defaultValue = 0) const; 1603 | /// See QueryIntText() 1604 | float FloatText(float defaultValue = 0) const; 1605 | 1606 | // internal: 1607 | enum ElementClosingType { 1608 | OPEN, // 1609 | CLOSED, // 1610 | CLOSING // 1611 | }; 1612 | ElementClosingType ClosingType() const { 1613 | return _closingType; 1614 | } 1615 | virtual XMLNode* ShallowClone( XMLDocument* document ) const; 1616 | virtual bool ShallowEqual( const XMLNode* compare ) const; 1617 | 1618 | protected: 1619 | char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); 1620 | 1621 | private: 1622 | XMLElement( XMLDocument* doc ); 1623 | virtual ~XMLElement(); 1624 | XMLElement( const XMLElement& ); // not supported 1625 | void operator=( const XMLElement& ); // not supported 1626 | 1627 | XMLAttribute* FindOrCreateAttribute( const char* name ); 1628 | char* ParseAttributes( char* p, int* curLineNumPtr ); 1629 | static void DeleteAttribute( XMLAttribute* attribute ); 1630 | XMLAttribute* CreateAttribute(); 1631 | 1632 | enum { BUF_SIZE = 200 }; 1633 | ElementClosingType _closingType; 1634 | // The attribute list is ordered; there is no 'lastAttribute' 1635 | // because the list needs to be scanned for dupes before adding 1636 | // a new attribute. 1637 | XMLAttribute* _rootAttribute; 1638 | }; 1639 | 1640 | 1641 | enum Whitespace { 1642 | PRESERVE_WHITESPACE, 1643 | COLLAPSE_WHITESPACE 1644 | }; 1645 | 1646 | 1647 | /** A Document binds together all the functionality. 1648 | It can be saved, loaded, and printed to the screen. 1649 | All Nodes are connected and allocated to a Document. 1650 | If the Document is deleted, all its Nodes are also deleted. 1651 | */ 1652 | class TINYXML2_LIB XMLDocument : public XMLNode 1653 | { 1654 | friend class XMLElement; 1655 | // Gives access to SetError and Push/PopDepth, but over-access for everything else. 1656 | // Wishing C++ had "internal" scope. 1657 | friend class XMLNode; 1658 | friend class XMLText; 1659 | friend class XMLComment; 1660 | friend class XMLDeclaration; 1661 | friend class XMLUnknown; 1662 | public: 1663 | /// constructor 1664 | XMLDocument( bool processEntities = true, Whitespace whitespaceMode = PRESERVE_WHITESPACE ); 1665 | ~XMLDocument(); 1666 | 1667 | virtual XMLDocument* ToDocument() { 1668 | TIXMLASSERT( this == _document ); 1669 | return this; 1670 | } 1671 | virtual const XMLDocument* ToDocument() const { 1672 | TIXMLASSERT( this == _document ); 1673 | return this; 1674 | } 1675 | 1676 | /** 1677 | Parse an XML file from a character string. 1678 | Returns XML_SUCCESS (0) on success, or 1679 | an errorID. 1680 | 1681 | You may optionally pass in the 'nBytes', which is 1682 | the number of bytes which will be parsed. If not 1683 | specified, TinyXML-2 will assume 'xml' points to a 1684 | null terminated string. 1685 | */ 1686 | XMLError Parse( const char* xml, size_t nBytes=(size_t)(-1) ); 1687 | 1688 | /** 1689 | Load an XML file from disk. 1690 | Returns XML_SUCCESS (0) on success, or 1691 | an errorID. 1692 | */ 1693 | XMLError LoadFile( const char* filename ); 1694 | 1695 | /** 1696 | Load an XML file from disk. You are responsible 1697 | for providing and closing the FILE*. 1698 | 1699 | NOTE: The file should be opened as binary ("rb") 1700 | not text in order for TinyXML-2 to correctly 1701 | do newline normalization. 1702 | 1703 | Returns XML_SUCCESS (0) on success, or 1704 | an errorID. 1705 | */ 1706 | XMLError LoadFile( FILE* ); 1707 | 1708 | /** 1709 | Save the XML file to disk. 1710 | Returns XML_SUCCESS (0) on success, or 1711 | an errorID. 1712 | */ 1713 | XMLError SaveFile( const char* filename, bool compact = false ); 1714 | 1715 | /** 1716 | Save the XML file to disk. You are responsible 1717 | for providing and closing the FILE*. 1718 | 1719 | Returns XML_SUCCESS (0) on success, or 1720 | an errorID. 1721 | */ 1722 | XMLError SaveFile( FILE* fp, bool compact = false ); 1723 | 1724 | bool ProcessEntities() const { 1725 | return _processEntities; 1726 | } 1727 | Whitespace WhitespaceMode() const { 1728 | return _whitespaceMode; 1729 | } 1730 | 1731 | /** 1732 | Returns true if this document has a leading Byte Order Mark of UTF8. 1733 | */ 1734 | bool HasBOM() const { 1735 | return _writeBOM; 1736 | } 1737 | /** Sets whether to write the BOM when writing the file. 1738 | */ 1739 | void SetBOM( bool useBOM ) { 1740 | _writeBOM = useBOM; 1741 | } 1742 | 1743 | /** Return the root element of DOM. Equivalent to FirstChildElement(). 1744 | To get the first node, use FirstChild(). 1745 | */ 1746 | XMLElement* RootElement() { 1747 | return FirstChildElement(); 1748 | } 1749 | const XMLElement* RootElement() const { 1750 | return FirstChildElement(); 1751 | } 1752 | 1753 | /** Print the Document. If the Printer is not provided, it will 1754 | print to stdout. If you provide Printer, this can print to a file: 1755 | @verbatim 1756 | XMLPrinter printer( fp ); 1757 | doc.Print( &printer ); 1758 | @endverbatim 1759 | 1760 | Or you can use a printer to print to memory: 1761 | @verbatim 1762 | XMLPrinter printer; 1763 | doc.Print( &printer ); 1764 | // printer.CStr() has a const char* to the XML 1765 | @endverbatim 1766 | */ 1767 | void Print( XMLPrinter* streamer=0 ) const; 1768 | virtual bool Accept( XMLVisitor* visitor ) const; 1769 | 1770 | /** 1771 | Create a new Element associated with 1772 | this Document. The memory for the Element 1773 | is managed by the Document. 1774 | */ 1775 | XMLElement* NewElement( const char* name ); 1776 | /** 1777 | Create a new Comment associated with 1778 | this Document. The memory for the Comment 1779 | is managed by the Document. 1780 | */ 1781 | XMLComment* NewComment( const char* comment ); 1782 | /** 1783 | Create a new Text associated with 1784 | this Document. The memory for the Text 1785 | is managed by the Document. 1786 | */ 1787 | XMLText* NewText( const char* text ); 1788 | /** 1789 | Create a new Declaration associated with 1790 | this Document. The memory for the object 1791 | is managed by the Document. 1792 | 1793 | If the 'text' param is null, the standard 1794 | declaration is used.: 1795 | @verbatim 1796 | 1797 | @endverbatim 1798 | */ 1799 | XMLDeclaration* NewDeclaration( const char* text=0 ); 1800 | /** 1801 | Create a new Unknown associated with 1802 | this Document. The memory for the object 1803 | is managed by the Document. 1804 | */ 1805 | XMLUnknown* NewUnknown( const char* text ); 1806 | 1807 | /** 1808 | Delete a node associated with this document. 1809 | It will be unlinked from the DOM. 1810 | */ 1811 | void DeleteNode( XMLNode* node ); 1812 | 1813 | void ClearError() { 1814 | SetError(XML_SUCCESS, 0, 0); 1815 | } 1816 | 1817 | /// Return true if there was an error parsing the document. 1818 | bool Error() const { 1819 | return _errorID != XML_SUCCESS; 1820 | } 1821 | /// Return the errorID. 1822 | XMLError ErrorID() const { 1823 | return _errorID; 1824 | } 1825 | const char* ErrorName() const; 1826 | static const char* ErrorIDToName(XMLError errorID); 1827 | 1828 | /** Returns a "long form" error description. A hopefully helpful 1829 | diagnostic with location, line number, and/or additional info. 1830 | */ 1831 | const char* ErrorStr() const; 1832 | 1833 | /// A (trivial) utility function that prints the ErrorStr() to stdout. 1834 | void PrintError() const; 1835 | 1836 | /// Return the line where the error occured, or zero if unknown. 1837 | int ErrorLineNum() const 1838 | { 1839 | return _errorLineNum; 1840 | } 1841 | 1842 | /// Clear the document, resetting it to the initial state. 1843 | void Clear(); 1844 | 1845 | /** 1846 | Copies this document to a target document. 1847 | The target will be completely cleared before the copy. 1848 | If you want to copy a sub-tree, see XMLNode::DeepClone(). 1849 | 1850 | NOTE: that the 'target' must be non-null. 1851 | */ 1852 | void DeepCopy(XMLDocument* target) const; 1853 | 1854 | // internal 1855 | char* Identify( char* p, XMLNode** node ); 1856 | 1857 | // internal 1858 | void MarkInUse(XMLNode*); 1859 | 1860 | virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { 1861 | return 0; 1862 | } 1863 | virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { 1864 | return false; 1865 | } 1866 | 1867 | private: 1868 | XMLDocument( const XMLDocument& ); // not supported 1869 | void operator=( const XMLDocument& ); // not supported 1870 | 1871 | bool _writeBOM; 1872 | bool _processEntities; 1873 | XMLError _errorID; 1874 | Whitespace _whitespaceMode; 1875 | mutable StrPair _errorStr; 1876 | int _errorLineNum; 1877 | char* _charBuffer; 1878 | int _parseCurLineNum; 1879 | int _parsingDepth; 1880 | // Memory tracking does add some overhead. 1881 | // However, the code assumes that you don't 1882 | // have a bunch of unlinked nodes around. 1883 | // Therefore it takes less memory to track 1884 | // in the document vs. a linked list in the XMLNode, 1885 | // and the performance is the same. 1886 | DynArray _unlinked; 1887 | 1888 | MemPoolT< sizeof(XMLElement) > _elementPool; 1889 | MemPoolT< sizeof(XMLAttribute) > _attributePool; 1890 | MemPoolT< sizeof(XMLText) > _textPool; 1891 | MemPoolT< sizeof(XMLComment) > _commentPool; 1892 | 1893 | static const char* _errorNames[XML_ERROR_COUNT]; 1894 | 1895 | void Parse(); 1896 | 1897 | void SetError( XMLError error, int lineNum, const char* format, ... ); 1898 | 1899 | // Something of an obvious security hole, once it was discovered. 1900 | // Either an ill-formed XML or an excessively deep one can overflow 1901 | // the stack. Track stack depth, and error out if needed. 1902 | class DepthTracker { 1903 | public: 1904 | DepthTracker(XMLDocument * document) { 1905 | this->_document = document; 1906 | document->PushDepth(); 1907 | } 1908 | ~DepthTracker() { 1909 | _document->PopDepth(); 1910 | } 1911 | private: 1912 | XMLDocument * _document; 1913 | }; 1914 | void PushDepth(); 1915 | void PopDepth(); 1916 | 1917 | template 1918 | NodeType* CreateUnlinkedNode( MemPoolT& pool ); 1919 | }; 1920 | 1921 | template 1922 | inline NodeType* XMLDocument::CreateUnlinkedNode( MemPoolT& pool ) 1923 | { 1924 | TIXMLASSERT( sizeof( NodeType ) == PoolElementSize ); 1925 | TIXMLASSERT( sizeof( NodeType ) == pool.ItemSize() ); 1926 | NodeType* returnNode = new (pool.Alloc()) NodeType( this ); 1927 | TIXMLASSERT( returnNode ); 1928 | returnNode->_memPool = &pool; 1929 | 1930 | _unlinked.Push(returnNode); 1931 | return returnNode; 1932 | } 1933 | 1934 | /** 1935 | A XMLHandle is a class that wraps a node pointer with null checks; this is 1936 | an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2 1937 | DOM structure. It is a separate utility class. 1938 | 1939 | Take an example: 1940 | @verbatim 1941 | 1942 | 1943 | 1944 | 1945 | 1946 | 1947 | @endverbatim 1948 | 1949 | Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very 1950 | easy to write a *lot* of code that looks like: 1951 | 1952 | @verbatim 1953 | XMLElement* root = document.FirstChildElement( "Document" ); 1954 | if ( root ) 1955 | { 1956 | XMLElement* element = root->FirstChildElement( "Element" ); 1957 | if ( element ) 1958 | { 1959 | XMLElement* child = element->FirstChildElement( "Child" ); 1960 | if ( child ) 1961 | { 1962 | XMLElement* child2 = child->NextSiblingElement( "Child" ); 1963 | if ( child2 ) 1964 | { 1965 | // Finally do something useful. 1966 | @endverbatim 1967 | 1968 | And that doesn't even cover "else" cases. XMLHandle addresses the verbosity 1969 | of such code. A XMLHandle checks for null pointers so it is perfectly safe 1970 | and correct to use: 1971 | 1972 | @verbatim 1973 | XMLHandle docHandle( &document ); 1974 | XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement(); 1975 | if ( child2 ) 1976 | { 1977 | // do something useful 1978 | @endverbatim 1979 | 1980 | Which is MUCH more concise and useful. 1981 | 1982 | It is also safe to copy handles - internally they are nothing more than node pointers. 1983 | @verbatim 1984 | XMLHandle handleCopy = handle; 1985 | @endverbatim 1986 | 1987 | See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects. 1988 | */ 1989 | class TINYXML2_LIB XMLHandle 1990 | { 1991 | public: 1992 | /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. 1993 | XMLHandle( XMLNode* node ) : _node( node ) { 1994 | } 1995 | /// Create a handle from a node. 1996 | XMLHandle( XMLNode& node ) : _node( &node ) { 1997 | } 1998 | /// Copy constructor 1999 | XMLHandle( const XMLHandle& ref ) : _node( ref._node ) { 2000 | } 2001 | /// Assignment 2002 | XMLHandle& operator=( const XMLHandle& ref ) { 2003 | _node = ref._node; 2004 | return *this; 2005 | } 2006 | 2007 | /// Get the first child of this handle. 2008 | XMLHandle FirstChild() { 2009 | return XMLHandle( _node ? _node->FirstChild() : 0 ); 2010 | } 2011 | /// Get the first child element of this handle. 2012 | XMLHandle FirstChildElement( const char* name = 0 ) { 2013 | return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 ); 2014 | } 2015 | /// Get the last child of this handle. 2016 | XMLHandle LastChild() { 2017 | return XMLHandle( _node ? _node->LastChild() : 0 ); 2018 | } 2019 | /// Get the last child element of this handle. 2020 | XMLHandle LastChildElement( const char* name = 0 ) { 2021 | return XMLHandle( _node ? _node->LastChildElement( name ) : 0 ); 2022 | } 2023 | /// Get the previous sibling of this handle. 2024 | XMLHandle PreviousSibling() { 2025 | return XMLHandle( _node ? _node->PreviousSibling() : 0 ); 2026 | } 2027 | /// Get the previous sibling element of this handle. 2028 | XMLHandle PreviousSiblingElement( const char* name = 0 ) { 2029 | return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); 2030 | } 2031 | /// Get the next sibling of this handle. 2032 | XMLHandle NextSibling() { 2033 | return XMLHandle( _node ? _node->NextSibling() : 0 ); 2034 | } 2035 | /// Get the next sibling element of this handle. 2036 | XMLHandle NextSiblingElement( const char* name = 0 ) { 2037 | return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 ); 2038 | } 2039 | 2040 | /// Safe cast to XMLNode. This can return null. 2041 | XMLNode* ToNode() { 2042 | return _node; 2043 | } 2044 | /// Safe cast to XMLElement. This can return null. 2045 | XMLElement* ToElement() { 2046 | return ( _node ? _node->ToElement() : 0 ); 2047 | } 2048 | /// Safe cast to XMLText. This can return null. 2049 | XMLText* ToText() { 2050 | return ( _node ? _node->ToText() : 0 ); 2051 | } 2052 | /// Safe cast to XMLUnknown. This can return null. 2053 | XMLUnknown* ToUnknown() { 2054 | return ( _node ? _node->ToUnknown() : 0 ); 2055 | } 2056 | /// Safe cast to XMLDeclaration. This can return null. 2057 | XMLDeclaration* ToDeclaration() { 2058 | return ( _node ? _node->ToDeclaration() : 0 ); 2059 | } 2060 | 2061 | private: 2062 | XMLNode* _node; 2063 | }; 2064 | 2065 | 2066 | /** 2067 | A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the 2068 | same in all regards, except for the 'const' qualifiers. See XMLHandle for API. 2069 | */ 2070 | class TINYXML2_LIB XMLConstHandle 2071 | { 2072 | public: 2073 | XMLConstHandle( const XMLNode* node ) : _node( node ) { 2074 | } 2075 | XMLConstHandle( const XMLNode& node ) : _node( &node ) { 2076 | } 2077 | XMLConstHandle( const XMLConstHandle& ref ) : _node( ref._node ) { 2078 | } 2079 | 2080 | XMLConstHandle& operator=( const XMLConstHandle& ref ) { 2081 | _node = ref._node; 2082 | return *this; 2083 | } 2084 | 2085 | const XMLConstHandle FirstChild() const { 2086 | return XMLConstHandle( _node ? _node->FirstChild() : 0 ); 2087 | } 2088 | const XMLConstHandle FirstChildElement( const char* name = 0 ) const { 2089 | return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 ); 2090 | } 2091 | const XMLConstHandle LastChild() const { 2092 | return XMLConstHandle( _node ? _node->LastChild() : 0 ); 2093 | } 2094 | const XMLConstHandle LastChildElement( const char* name = 0 ) const { 2095 | return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 ); 2096 | } 2097 | const XMLConstHandle PreviousSibling() const { 2098 | return XMLConstHandle( _node ? _node->PreviousSibling() : 0 ); 2099 | } 2100 | const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const { 2101 | return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); 2102 | } 2103 | const XMLConstHandle NextSibling() const { 2104 | return XMLConstHandle( _node ? _node->NextSibling() : 0 ); 2105 | } 2106 | const XMLConstHandle NextSiblingElement( const char* name = 0 ) const { 2107 | return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 ); 2108 | } 2109 | 2110 | 2111 | const XMLNode* ToNode() const { 2112 | return _node; 2113 | } 2114 | const XMLElement* ToElement() const { 2115 | return ( _node ? _node->ToElement() : 0 ); 2116 | } 2117 | const XMLText* ToText() const { 2118 | return ( _node ? _node->ToText() : 0 ); 2119 | } 2120 | const XMLUnknown* ToUnknown() const { 2121 | return ( _node ? _node->ToUnknown() : 0 ); 2122 | } 2123 | const XMLDeclaration* ToDeclaration() const { 2124 | return ( _node ? _node->ToDeclaration() : 0 ); 2125 | } 2126 | 2127 | private: 2128 | const XMLNode* _node; 2129 | }; 2130 | 2131 | 2132 | /** 2133 | Printing functionality. The XMLPrinter gives you more 2134 | options than the XMLDocument::Print() method. 2135 | 2136 | It can: 2137 | -# Print to memory. 2138 | -# Print to a file you provide. 2139 | -# Print XML without a XMLDocument. 2140 | 2141 | Print to Memory 2142 | 2143 | @verbatim 2144 | XMLPrinter printer; 2145 | doc.Print( &printer ); 2146 | SomeFunction( printer.CStr() ); 2147 | @endverbatim 2148 | 2149 | Print to a File 2150 | 2151 | You provide the file pointer. 2152 | @verbatim 2153 | XMLPrinter printer( fp ); 2154 | doc.Print( &printer ); 2155 | @endverbatim 2156 | 2157 | Print without a XMLDocument 2158 | 2159 | When loading, an XML parser is very useful. However, sometimes 2160 | when saving, it just gets in the way. The code is often set up 2161 | for streaming, and constructing the DOM is just overhead. 2162 | 2163 | The Printer supports the streaming case. The following code 2164 | prints out a trivially simple XML file without ever creating 2165 | an XML document. 2166 | 2167 | @verbatim 2168 | XMLPrinter printer( fp ); 2169 | printer.OpenElement( "foo" ); 2170 | printer.PushAttribute( "foo", "bar" ); 2171 | printer.CloseElement(); 2172 | @endverbatim 2173 | */ 2174 | class TINYXML2_LIB XMLPrinter : public XMLVisitor 2175 | { 2176 | public: 2177 | /** Construct the printer. If the FILE* is specified, 2178 | this will print to the FILE. Else it will print 2179 | to memory, and the result is available in CStr(). 2180 | If 'compact' is set to true, then output is created 2181 | with only required whitespace and newlines. 2182 | */ 2183 | XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 ); 2184 | virtual ~XMLPrinter() {} 2185 | 2186 | /** If streaming, write the BOM and declaration. */ 2187 | void PushHeader( bool writeBOM, bool writeDeclaration ); 2188 | /** If streaming, start writing an element. 2189 | The element must be closed with CloseElement() 2190 | */ 2191 | void OpenElement( const char* name, bool compactMode=false ); 2192 | /// If streaming, add an attribute to an open element. 2193 | void PushAttribute( const char* name, const char* value ); 2194 | void PushAttribute( const char* name, int value ); 2195 | void PushAttribute( const char* name, unsigned value ); 2196 | void PushAttribute(const char* name, int64_t value); 2197 | void PushAttribute( const char* name, bool value ); 2198 | void PushAttribute( const char* name, double value ); 2199 | /// If streaming, close the Element. 2200 | virtual void CloseElement( bool compactMode=false ); 2201 | 2202 | /// Add a text node. 2203 | void PushText( const char* text, bool cdata=false ); 2204 | /// Add a text node from an integer. 2205 | void PushText( int value ); 2206 | /// Add a text node from an unsigned. 2207 | void PushText( unsigned value ); 2208 | /// Add a text node from an unsigned. 2209 | void PushText(int64_t value); 2210 | /// Add a text node from a bool. 2211 | void PushText( bool value ); 2212 | /// Add a text node from a float. 2213 | void PushText( float value ); 2214 | /// Add a text node from a double. 2215 | void PushText( double value ); 2216 | 2217 | /// Add a comment 2218 | void PushComment( const char* comment ); 2219 | 2220 | void PushDeclaration( const char* value ); 2221 | void PushUnknown( const char* value ); 2222 | 2223 | virtual bool VisitEnter( const XMLDocument& /*doc*/ ); 2224 | virtual bool VisitExit( const XMLDocument& /*doc*/ ) { 2225 | return true; 2226 | } 2227 | 2228 | virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ); 2229 | virtual bool VisitExit( const XMLElement& element ); 2230 | 2231 | virtual bool Visit( const XMLText& text ); 2232 | virtual bool Visit( const XMLComment& comment ); 2233 | virtual bool Visit( const XMLDeclaration& declaration ); 2234 | virtual bool Visit( const XMLUnknown& unknown ); 2235 | 2236 | /** 2237 | If in print to memory mode, return a pointer to 2238 | the XML file in memory. 2239 | */ 2240 | const char* CStr() const { 2241 | return _buffer.Mem(); 2242 | } 2243 | /** 2244 | If in print to memory mode, return the size 2245 | of the XML file in memory. (Note the size returned 2246 | includes the terminating null.) 2247 | */ 2248 | int CStrSize() const { 2249 | return _buffer.Size(); 2250 | } 2251 | /** 2252 | If in print to memory mode, reset the buffer to the 2253 | beginning. 2254 | */ 2255 | void ClearBuffer() { 2256 | _buffer.Clear(); 2257 | _buffer.Push(0); 2258 | _firstElement = true; 2259 | } 2260 | 2261 | protected: 2262 | virtual bool CompactMode( const XMLElement& ) { return _compactMode; } 2263 | 2264 | /** Prints out the space before an element. You may override to change 2265 | the space and tabs used. A PrintSpace() override should call Print(). 2266 | */ 2267 | virtual void PrintSpace( int depth ); 2268 | void Print( const char* format, ... ); 2269 | void Write( const char* data, size_t size ); 2270 | inline void Write( const char* data ) { Write( data, strlen( data ) ); } 2271 | void Putc( char ch ); 2272 | 2273 | void SealElementIfJustOpened(); 2274 | bool _elementJustOpened; 2275 | DynArray< const char*, 10 > _stack; 2276 | 2277 | private: 2278 | void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities. 2279 | 2280 | bool _firstElement; 2281 | FILE* _fp; 2282 | int _depth; 2283 | int _textDepth; 2284 | bool _processEntities; 2285 | bool _compactMode; 2286 | 2287 | enum { 2288 | ENTITY_RANGE = 64, 2289 | BUF_SIZE = 200 2290 | }; 2291 | bool _entityFlag[ENTITY_RANGE]; 2292 | bool _restrictedEntityFlag[ENTITY_RANGE]; 2293 | 2294 | DynArray< char, 20 > _buffer; 2295 | 2296 | // Prohibit cloning, intentionally not implemented 2297 | XMLPrinter( const XMLPrinter& ); 2298 | XMLPrinter& operator=( const XMLPrinter& ); 2299 | }; 2300 | 2301 | 2302 | } // tinyxml2 2303 | 2304 | #if defined(_MSC_VER) 2305 | # pragma warning(pop) 2306 | #endif 2307 | 2308 | #endif // TINYXML2_INCLUDED 2309 | --------------------------------------------------------------------------------