Code

Merge and cleanup of GSoC C++-ification project.
[inkscape.git] / src / extension / internal / pov-out.cpp
index bb12e0564cb6641ad21506cc0a2bec60181185d2..a130b692354142786208ac3b1bd8fcfe97aa75bd 100644 (file)
@@ -10,6 +10,7 @@
  *
  * Authors:
  *   Bob Jamison <ishmal@inkscape.org>
+ *   Abhishek Sharma
  *
  * Copyright (C) 2004-2008 Authors
  *
 #endif
 #include "pov-out.h"
 #include <inkscape.h>
-#include <inkscape_version.h>
+#include <inkscape-version.h>
 #include <sp-path.h>
 #include <style.h>
 #include <display/curve.h>
-#include <libnr/n-art-bpath.h>
 #include <extension/system.h>
 #include <2geom/pathvector.h>
 #include <2geom/rect.h>
 #include <2geom/bezier-curve.h>
 #include <2geom/hvlinesegment.h>
 #include "helper/geom.h"
+#include "helper/geom-curves.h"
 #include <io/sys.h>
 
 #include <string>
@@ -48,33 +49,26 @@ namespace Internal
 {
 
 
-
-
 //########################################################################
-//# U T I L I T Y
+//# M E S S A G E S
 //########################################################################
 
-
-
-/**
- * This function searches the Repr tree recursively from the given node,
- * and adds refs to all nodes with the given name, to the result vector
- */
-static void
-findElementsByTagName(std::vector<Inkscape::XML::Node *> &results,
-                      Inkscape::XML::Node *node,
-                      char const *name)
+static void err(const char *fmt, ...)
 {
-    if ( !name || strcmp(node->name(), name) == 0 )
-        results.push_back(node);
+    va_list args;
+    g_log(NULL,  G_LOG_LEVEL_WARNING, "Pov-out err: ");
+    va_start(args, fmt);
+    g_logv(NULL, G_LOG_LEVEL_WARNING, fmt, args);
+    va_end(args);
+    g_log(NULL,  G_LOG_LEVEL_WARNING, "\n");
+}
 
-    for (Inkscape::XML::Node *child = node->firstChild() ; child ;
-              child = child->next())
-        findElementsByTagName( results, child, name );
 
-}
 
 
+//########################################################################
+//# U T I L I T Y
+//########################################################################
 
 
 
@@ -112,7 +106,7 @@ static PovOutput::String dstr(double d)
     return s;
 }
 
-
+#define DSTR(d) (dstr(d).c_str())
 
 
 /**
@@ -137,7 +131,7 @@ void PovOutput::out(const char *fmt, ...)
  */
 void PovOutput::vec2(double a, double b)
 {
-    out("<%s, %s>", dstr(a).c_str(), dstr(b).c_str());
+    out("<%s, %s>", DSTR(a), DSTR(b));
 }
 
 
@@ -147,7 +141,7 @@ void PovOutput::vec2(double a, double b)
  */
 void PovOutput::vec3(double a, double b, double c)
 {
-    out("<%s, %s, %s>", dstr(a).c_str(), dstr(b).c_str(), dstr(c).c_str());
+    out("<%s, %s, %s>", DSTR(a), DSTR(b), DSTR(c));
 }
 
 
@@ -157,8 +151,7 @@ void PovOutput::vec3(double a, double b, double c)
  */
 void PovOutput::vec4(double a, double b, double c, double d)
 {
-    out("<%s, %s, %s, %s>", dstr(a).c_str(), dstr(b).c_str(),
-                dstr(c).c_str(), dstr(d).c_str());
+    out("<%s, %s, %s, %s>", DSTR(a), DSTR(b), DSTR(c), DSTR(d));
 }
 
 
@@ -208,8 +201,8 @@ bool PovOutput::doHeader()
     out("/*###################################################################\n");
     out("### This PovRay document was generated by Inkscape\n");
     out("### http://www.inkscape.org\n");
-    out("### Created: %s", ctime(&tim));
-    out("### Version: %s\n", INKSCAPE_VERSION);
+    out("### Created: %s",   ctime(&tim));
+    out("### Version: %s\n", Inkscape::version_string);
     out("#####################################################################\n");
     out("### NOTES:\n");
     out("### ============\n");
@@ -308,17 +301,31 @@ bool PovOutput::doCurve(SPItem *item, const String &id)
     povShapes.push_back(shapeInfo); //passed all tests.  save the info
 
     // convert the path to only lineto's and cubic curveto's:
-    Geom::Matrix tf = sp_item_i2d_affine(item);
+    Geom::Matrix tf = item->i2d_affine();
     Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers( curve->get_pathvector() * tf );
 
-    //Count the NR_CURVETOs/LINETOs (including closing line segment)
+    /*
+     * We need to know the number of segments (NR_CURVETOs/LINETOs, including
+     * closing line segment) before we write out segment data. Since we are
+     * going to skip degenerate (zero length) paths, we need to loop over all
+     * subpaths and segments first.
+     */
     int segmentCount = 0;
-    for(Geom::PathVector::const_iterator it = pathv.begin(); it != pathv.end(); ++it)
-           {
-        segmentCount += (*it).size();
-        if (it->closed())
-            segmentCount += 1;
+    /**
+     * For all Subpaths in the <path>
+     */
+    for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit)
+    {
+        /**
+         * For all segments in the subpath, including extra closing segment defined by 2geom
+         */
+        for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_closed(); ++cit)
+        {
+
+            // Skip zero length segments.
+            if( !cit->isDegenerate() ) ++segmentCount;
         }
+    }
 
     out("/*###################################################\n");
     out("### PRISM:  %s\n", id.c_str());
@@ -334,28 +341,30 @@ bool PovOutput::doCurve(SPItem *item, const String &id)
     nrSegments += segmentCount;
 
     /**
-     *  at moment of writing, 2geom lacks proper initialization of empty intervals in rect...
-     */     
-    Geom::Rect cminmax( pathv.front().initialPoint(), pathv.front().initialPoint() ); 
-   
-   
+     *   at moment of writing, 2geom lacks proper initialization of empty intervals in rect...
+     */
+    Geom::Rect cminmax( pathv.front().initialPoint(), pathv.front().initialPoint() );
+
+
     /**
      * For all Subpaths in the <path>
-     */             
+     */
     for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit)
         {
 
         cminmax.expandTo(pit->initialPoint());
 
         /**
-         * For all segments in the subpath
-         */                     
+         * For all segments in the subpath, including extra closing segment defined by 2geom
+         */
         for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_closed(); ++cit)
-                   {
+            {
+
+            // Skip zero length segments
+            if( cit->isDegenerate() )
+                continue;
 
-            if( dynamic_cast<Geom::LineSegment const *> (&*cit) ||
-                    dynamic_cast<Geom::HLineSegment const *>(&*cit) ||
-                    dynamic_cast<Geom::VLineSegment const *>(&*cit) )
+            if( is_straight_curve(*cit) )
                 {
                 Geom::Point p0 = cit->initialPoint();
                 Geom::Point p1 = cit->finalPoint();
@@ -364,7 +373,7 @@ bool PovOutput::doCurve(SPItem *item, const String &id)
                 nrNodes += 8;
                 }
             else if(Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const*>(&*cit))
-                           {
+            {
                 std::vector<Geom::Point> points = cubic->points();
                 Geom::Point p0 = points[0];
                 Geom::Point p1 = points[1];
@@ -375,8 +384,8 @@ bool PovOutput::doCurve(SPItem *item, const String &id)
                 nrNodes += 8;
                 }
             else
-                           {
-                g_warning("logical error, because pathv_to_linear_and_cubic_beziers was used");
+            {
+                err("logical error, because pathv_to_linear_and_cubic_beziers was used");
                 return false;
                 }
 
@@ -384,6 +393,11 @@ bool PovOutput::doCurve(SPItem *item, const String &id)
                 out(",\n");
             else
                 out("\n");
+            if (segmentNr > segmentCount)
+                {
+                err("Too many segments");
+                return false;
+                }
 
             cminmax.expandTo(cit->finalPoint());
 
@@ -397,14 +411,14 @@ bool PovOutput::doCurve(SPItem *item, const String &id)
     double cminy = cminmax.min()[Y];
     double cmaxy = cminmax.max()[Y];
 
-    out("#declare %s_MIN_X    = %s;\n", id.c_str(), dstr(cminx).c_str());
-    out("#declare %s_CENTER_X = %s;\n", id.c_str(), dstr((cmaxx+cminx)/2.0).c_str());
-    out("#declare %s_MAX_X    = %s;\n", id.c_str(), dstr(cmaxx).c_str());
-    out("#declare %s_WIDTH    = %s;\n", id.c_str(), dstr(cmaxx-cminx).c_str());
-    out("#declare %s_MIN_Y    = %s;\n", id.c_str(), dstr(cminy).c_str());
-    out("#declare %s_CENTER_Y = %s;\n", id.c_str(), dstr((cmaxy+cminy)/2.0).c_str());
-    out("#declare %s_MAX_Y    = %s;\n", id.c_str(), dstr(cmaxy).c_str());
-    out("#declare %s_HEIGHT   = %s;\n", id.c_str(), dstr(cmaxy-cminy).c_str());
+    out("#declare %s_MIN_X    = %s;\n", id.c_str(), DSTR(cminx));
+    out("#declare %s_CENTER_X = %s;\n", id.c_str(), DSTR((cmaxx+cminx)/2.0));
+    out("#declare %s_MAX_X    = %s;\n", id.c_str(), DSTR(cmaxx));
+    out("#declare %s_WIDTH    = %s;\n", id.c_str(), DSTR(cmaxx-cminx));
+    out("#declare %s_MIN_Y    = %s;\n", id.c_str(), DSTR(cminy));
+    out("#declare %s_CENTER_Y = %s;\n", id.c_str(), DSTR((cmaxy+cminy)/2.0));
+    out("#declare %s_MAX_Y    = %s;\n", id.c_str(), DSTR(cmaxy));
+    out("#declare %s_HEIGHT   = %s;\n", id.c_str(), DSTR(cmaxy-cminy));
     if (shapeInfo.color.length()>0)
         out("#declare %s_COLOR    = %s;\n",
                 id.c_str(), shapeInfo.color.c_str());
@@ -425,32 +439,38 @@ bool PovOutput::doCurve(SPItem *item, const String &id)
 }
 
 /**
- *  Output the curve data to buffer
+ *  Descend the svg tree recursively, translating data
  */
-bool PovOutput::doCurvesRecursive(SPDocument *doc, Inkscape::XML::Node *node)
+bool PovOutput::doTreeRecursive(SPDocument *doc, SPObject *obj)
 {
-    /**
-     * If the object is an Item, try processing it
-     */             
-    char *str  = (char *) node->attribute("id");
-    SPObject *reprobj = doc->getObjectByRepr(node);
-    if (SP_IS_ITEM(reprobj) && str)
+
+    String id;
+    if (!obj->getId())
+        {
+        char buf[16];
+        sprintf(buf, "id%d", idIndex++);
+        id = buf;
+        }
+    else
+        {
+            id = obj->getId();
+        }
+
+    if (SP_IS_ITEM(obj))
         {
-        SPItem *item = SP_ITEM(reprobj);
-        String id = str;
+        SPItem *item = SP_ITEM(obj);
         if (!doCurve(item, id))
             return false;
         }
 
     /**
      * Descend into children
-     */             
-    for (Inkscape::XML::Node *child = node->firstChild() ; child ;
-              child = child->next())
+     */
+    for (SPObject *child = obj->firstChild() ; child ; child = child->next)
         {
-               if (!doCurvesRecursive(doc, child))
-                   return false;
-               }
+            if (!doTreeRecursive(doc, child))
+                return false;
+        }
 
     return true;
 }
@@ -458,7 +478,7 @@ bool PovOutput::doCurvesRecursive(SPDocument *doc, Inkscape::XML::Node *node)
 /**
  *  Output the curve data to buffer
  */
-bool PovOutput::doCurves(SPDocument *doc)
+bool PovOutput::doTree(SPDocument *doc)
 {
     double bignum = 1000000.0;
     minx  =  bignum;
@@ -466,7 +486,7 @@ bool PovOutput::doCurves(SPDocument *doc)
     miny  =  bignum;
     maxy  = -bignum;
 
-    if (!doCurvesRecursive(doc, doc->rroot))
+    if (!doTreeRecursive(doc, doc->root))
         return false;
 
     //## Let's make a union of all of the Shapes
@@ -513,7 +533,7 @@ bool PovOutput::doCurves(SPDocument *doc)
         out(" * Allow the user to redefine the Z-Increment\n");
         out(" */\n");
         out("#ifndef (AllShapes_Z_Increment)\n");
-        out("#declare AllShapes_Z_Increment = %s;\n", dstr(zinc).c_str());
+        out("#declare AllShapes_Z_Increment = %s;\n", DSTR(zinc));
         out("#end\n");
         out("\n");
         out("#declare AllShapes_Z_Scale = 1.0;\n");
@@ -538,14 +558,14 @@ bool PovOutput::doCurves(SPDocument *doc)
 
         out("}\n");
 
-        out("#declare %s_MIN_X    = %s;\n", pfx, dstr(minx).c_str());
-        out("#declare %s_CENTER_X = %s;\n", pfx, dstr((maxx+minx)/2.0).c_str());
-        out("#declare %s_MAX_X    = %s;\n", pfx, dstr(maxx).c_str());
-        out("#declare %s_WIDTH    = %s;\n", pfx, dstr(maxx-minx).c_str());
-        out("#declare %s_MIN_Y    = %s;\n", pfx, dstr(miny).c_str());
-        out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((maxy+miny)/2.0).c_str());
-        out("#declare %s_MAX_Y    = %s;\n", pfx, dstr(maxy).c_str());
-        out("#declare %s_HEIGHT   = %s;\n", pfx, dstr(maxy-miny).c_str());
+        out("#declare %s_MIN_X    = %s;\n", pfx, DSTR(minx));
+        out("#declare %s_CENTER_X = %s;\n", pfx, DSTR((maxx+minx)/2.0));
+        out("#declare %s_MAX_X    = %s;\n", pfx, DSTR(maxx));
+        out("#declare %s_WIDTH    = %s;\n", pfx, DSTR(maxx-minx));
+        out("#declare %s_MIN_Y    = %s;\n", pfx, DSTR(miny));
+        out("#declare %s_CENTER_Y = %s;\n", pfx, DSTR((maxy+miny)/2.0));
+        out("#declare %s_MAX_Y    = %s;\n", pfx, DSTR(maxy));
+        out("#declare %s_HEIGHT   = %s;\n", pfx, DSTR(maxy-miny));
         out("/*##############################################\n");
         out("### end %s\n", id.c_str());
         out("##############################################*/\n");
@@ -570,6 +590,7 @@ void PovOutput::reset()
     nrNodes    = 0;
     nrSegments = 0;
     nrShapes   = 0;
+    idIndex    = 0;
     outbuf.clear();
     povShapes.clear();
 }
@@ -579,24 +600,24 @@ void PovOutput::reset()
 /**
  * Saves the Shapes of an Inkscape SVG file as PovRay spline definitions
  */
-void PovOutput::saveDocument(SPDocument *doc, gchar const *uri)
+void PovOutput::saveDocument(SPDocument *doc, gchar const *filename_utf8)
 {
     reset();
 
     //###### SAVE IN POV FORMAT TO BUFFER
     //# Lets do the curves first, to get the stats
-    if (!doCurves(doc))
+    if (!doTree(doc))
         {
-        g_warning("Could not output curves for %s\n", uri);
+        err("Could not output curves for %s", filename_utf8);
         return;
         }
-        
+
     String curveBuf = outbuf;
     outbuf.clear();
 
     if (!doHeader())
         {
-        g_warning("Could not write header for %s\n", uri);
+        err("Could not write header for %s", filename_utf8);
         return;
         }
 
@@ -604,7 +625,7 @@ void PovOutput::saveDocument(SPDocument *doc, gchar const *uri)
 
     if (!doTail())
         {
-        g_warning("Could not write footer for %s\n", uri);
+        err("Could not write footer for %s", filename_utf8);
         return;
         }
 
@@ -612,8 +633,8 @@ void PovOutput::saveDocument(SPDocument *doc, gchar const *uri)
 
 
     //###### WRITE TO FILE
-    Inkscape::IO::dump_fopen_call(uri, "L");
-    FILE *f = Inkscape::IO::fopen_utf8name(uri, "w");
+    Inkscape::IO::dump_fopen_call(filename_utf8, "L");
+    FILE *f = Inkscape::IO::fopen_utf8name(filename_utf8, "w");
     if (!f)
         return;
 
@@ -643,10 +664,11 @@ void PovOutput::saveDocument(SPDocument *doc, gchar const *uri)
  * API call to save document
 */
 void
-PovOutput::save(Inkscape::Extension::Output *mod,
-                        SPDocument *doc, gchar const *uri)
+PovOutput::save(Inkscape::Extension::Output */*mod*/,
+                        SPDocument *doc, gchar const *filename_utf8)
 {
-    saveDocument(doc, uri);
+    /* See comments in JavaFSOutput::save re the name `filename_utf8'. */
+    saveDocument(doc, filename_utf8);
 }
 
 
@@ -654,7 +676,7 @@ PovOutput::save(Inkscape::Extension::Output *mod,
 /**
  * Make sure that we are in the database
  */
-bool PovOutput::check (Inkscape::Extension::Extension *module)
+bool PovOutput::check (Inkscape::Extension::Extension */*module*/)
 {
     /* We don't need a Key
     if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
@@ -681,7 +703,7 @@ PovOutput::init()
             "<output>\n"
                 "<extension>.pov</extension>\n"
                 "<mimetype>text/x-povray-script</mimetype>\n"
-                "<filetypename>" N_("PovRay (*.pov) (export splines)") "</filetypename>\n"
+                "<filetypename>" N_("PovRay (*.pov) (paths and shapes only)") "</filetypename>\n"
                 "<filetypetooltip>" N_("PovRay Raytracer File") "</filetypetooltip>\n"
             "</output>\n"
         "</inkscape-extension>",
@@ -706,4 +728,4 @@ PovOutput::init()
   fill-column:99
   End:
 */
-// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :
+// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :