Code

Improved version reporting. Add SVN revision and custom status to
[inkscape.git] / src / extension / internal / pov-out.cpp
1 /*
2  * A simple utility for exporting Inkscape svg Shapes as PovRay bezier
3  * prisms.  Note that this is output-only, and would thus seem to be
4  * better placed as an 'export' rather than 'output'.  However, Export
5  * handles all or partial documents, while this outputs ALL shapes in
6  * the current SVG document.
7  *
8  *  For information on the PovRay file format, see:
9  *      http://www.povray.org
10  *
11  * Authors:
12  *   Bob Jamison <ishmal@inkscape.org>
13  *
14  * Copyright (C) 2004-2008 Authors
15  *
16  * Released under GNU GPL, read the file 'COPYING' for more information
17  */
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23 #include "pov-out.h"
24 #include <inkscape.h>
25 #include <inkscape-version.h>
26 #include <sp-path.h>
27 #include <style.h>
28 #include <display/curve.h>
29 #include <extension/system.h>
30 #include <2geom/pathvector.h>
31 #include <2geom/rect.h>
32 #include <2geom/bezier-curve.h>
33 #include <2geom/hvlinesegment.h>
34 #include "helper/geom.h"
35 #include "helper/geom-curves.h"
36 #include <io/sys.h>
38 #include <string>
39 #include <stdio.h>
40 #include <stdarg.h>
43 namespace Inkscape
44 {
45 namespace Extension
46 {
47 namespace Internal
48 {
51 //########################################################################
52 //# M E S S A G E S
53 //########################################################################
55 static void err(const char *fmt, ...)
56 {
57     va_list args;
58     g_log(NULL,  G_LOG_LEVEL_WARNING, "Pov-out err: ");
59     va_start(args, fmt);
60     g_logv(NULL, G_LOG_LEVEL_WARNING, fmt, args);
61     va_end(args);
62     g_log(NULL,  G_LOG_LEVEL_WARNING, "\n");
63 }
68 //########################################################################
69 //# U T I L I T Y
70 //########################################################################
74 static double
75 effective_opacity(SPItem const *item)
76 {
77     double ret = 1.0;
78     for (SPObject const *obj = item; obj; obj = obj->parent)
79         {
80         SPStyle const *const style = SP_OBJECT_STYLE(obj);
81         g_return_val_if_fail(style, ret);
82         ret *= SP_SCALE24_TO_FLOAT(style->opacity.value);
83         }
84     return ret;
85 }
91 //########################################################################
92 //# OUTPUT FORMATTING
93 //########################################################################
96 /**
97  * We want to control floating output format
98  */
99 static PovOutput::String dstr(double d)
101     char dbuf[G_ASCII_DTOSTR_BUF_SIZE+1];
102     g_ascii_formatd(dbuf, G_ASCII_DTOSTR_BUF_SIZE,
103                   "%.8f", (gdouble)d);
104     PovOutput::String s = dbuf;
105     return s;
108 #define DSTR(d) (dstr(d).c_str())
111 /**
112  *  Output data to the buffer, printf()-style
113  */
114 void PovOutput::out(const char *fmt, ...)
116     va_list args;
117     va_start(args, fmt);
118     gchar *output = g_strdup_vprintf(fmt, args);
119     va_end(args);
120     outbuf.append(output);
121     g_free(output);
128 /**
129  *  Output a 2d vector
130  */
131 void PovOutput::vec2(double a, double b)
133     out("<%s, %s>", DSTR(a), DSTR(b));
138 /**
139  * Output a 3d vector
140  */
141 void PovOutput::vec3(double a, double b, double c)
143     out("<%s, %s, %s>", DSTR(a), DSTR(b), DSTR(c));
148 /**
149  *  Output a v4d ector
150  */
151 void PovOutput::vec4(double a, double b, double c, double d)
153     out("<%s, %s, %s, %s>", DSTR(a), DSTR(b), DSTR(c), DSTR(d));
158 /**
159  *  Output an rgbf color vector
160  */
161 void PovOutput::rgbf(double r, double g, double b, double f)
163     //"rgbf < %1.3f, %1.3f, %1.3f %1.3f>"
164     out("rgbf ");
165     vec4(r, g, b, f);
170 /**
171  *  Output one bezier's start, start-control, end-control, and end nodes
172  */
173 void PovOutput::segment(int segNr,
174                         double startX,     double startY,
175                         double startCtrlX, double startCtrlY,
176                         double endCtrlX,   double endCtrlY,
177                         double endX,       double endY)
179     //"    /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>"
180     out("    /*%4d*/ ", segNr);
181     vec2(startX,     startY);
182     out(", ");
183     vec2(startCtrlX, startCtrlY);
184     out(", ");
185     vec2(endCtrlX,   endCtrlY);
186     out(", ");
187     vec2(endX,       endY);
194 /**
195  * Output the file header
196  */
197 bool PovOutput::doHeader()
199     time_t tim = time(NULL);
200     out("/*###################################################################\n");
201     out("### This PovRay document was generated by Inkscape\n");
202     out("### http://www.inkscape.org\n");
203     out("### Created: %s",   ctime(&tim));
204     out("### Version: %s\n", Inkscape::version_string);
205     out("#####################################################################\n");
206     out("### NOTES:\n");
207     out("### ============\n");
208     out("### POVRay information can be found at\n");
209     out("### http://www.povray.org\n");
210     out("###\n");
211     out("### The 'AllShapes' objects at the bottom are provided as a\n");
212     out("### preview of how the output would look in a trace.  However,\n");
213     out("### the main intent of this file is to provide the individual\n");
214     out("### shapes for inclusion in a POV project.\n");
215     out("###\n");
216     out("### For an example of how to use this file, look at\n");
217     out("### share/examples/istest.pov\n");
218     out("###\n");
219     out("### If you have any problems with this output, please see the\n");
220     out("### Inkscape project at http://www.inkscape.org, or visit\n");
221     out("### the #inkscape channel on irc.freenode.net . \n");
222     out("###\n");
223     out("###################################################################*/\n");
224     out("\n\n");
225     out("/*###################################################################\n");
226     out("##   Exports in this file\n");
227     out("##==========================\n");
228     out("##    Shapes   : %d\n", nrShapes);
229     out("##    Segments : %d\n", nrSegments);
230     out("##    Nodes    : %d\n", nrNodes);
231     out("###################################################################*/\n");
232     out("\n\n\n");
233     return true;
238 /**
239  *  Output the file footer
240  */
241 bool PovOutput::doTail()
243     out("\n\n");
244     out("/*###################################################################\n");
245     out("### E N D    F I L E\n");
246     out("###################################################################*/\n");
247     out("\n\n");
248     return true;
253 /**
254  *  Output the curve data to buffer
255  */
256 bool PovOutput::doCurve(SPItem *item, const String &id)
258     using Geom::X;
259     using Geom::Y;
261     //### Get the Shape
262     if (!SP_IS_SHAPE(item))//Bulia's suggestion.  Allow all shapes
263         return true;
265     SPShape *shape = SP_SHAPE(item);
266     SPCurve *curve = shape->curve;
267     if (curve->is_empty())
268         return true;
270     nrShapes++;
272     PovShapeInfo shapeInfo;
273     shapeInfo.id    = id;
274     shapeInfo.color = "";
276     //Try to get the fill color of the shape
277     SPStyle *style = SP_OBJECT_STYLE(shape);
278     /* fixme: Handle other fill types, even if this means translating gradients to a single
279            flat colour. */
280     if (style)
281         {
282         if (style->fill.isColor())
283             {
284             // see color.h for how to parse SPColor
285             float rgb[3];
286             sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
287             double const dopacity = ( SP_SCALE24_TO_FLOAT(style->fill_opacity.value)
288                                       * effective_opacity(shape) );
289             //gchar *str = g_strdup_printf("rgbf < %1.3f, %1.3f, %1.3f %1.3f>",
290             //                             rgb[0], rgb[1], rgb[2], 1.0 - dopacity);
291             String rgbf = "rgbf <";
292             rgbf.append(dstr(rgb[0]));         rgbf.append(", ");
293             rgbf.append(dstr(rgb[1]));         rgbf.append(", ");
294             rgbf.append(dstr(rgb[2]));         rgbf.append(", ");
295             rgbf.append(dstr(1.0 - dopacity)); rgbf.append(">");
296             shapeInfo.color += rgbf;
297             }
298         }
300     povShapes.push_back(shapeInfo); //passed all tests.  save the info
302     // convert the path to only lineto's and cubic curveto's:
303     Geom::Matrix tf = sp_item_i2d_affine(item);
304     Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers( curve->get_pathvector() * tf );
306     //Count the NR_CURVETOs/LINETOs (including closing line segment)
307     int segmentCount = 0;
308     for(Geom::PathVector::const_iterator it = pathv.begin(); it != pathv.end(); ++it)
309             {
310         segmentCount += (*it).size();
311         if (it->closed())
312             segmentCount += 1;
313         }
315     out("/*###################################################\n");
316     out("### PRISM:  %s\n", id.c_str());
317     out("###################################################*/\n");
318     out("#declare %s = prism {\n", id.c_str());
319     out("    linear_sweep\n");
320     out("    bezier_spline\n");
321     out("    1.0, //top\n");
322     out("    0.0, //bottom\n");
323     out("    %d //nr points\n", segmentCount * 4);
324     int segmentNr = 0;
326     nrSegments += segmentCount;
328     /**
329      *   at moment of writing, 2geom lacks proper initialization of empty intervals in rect...
330      */     
331     Geom::Rect cminmax( pathv.front().initialPoint(), pathv.front().initialPoint() ); 
332    
333    
334     /**
335      * For all Subpaths in the <path>
336      */      
337     for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit)
338         {
340         cminmax.expandTo(pit->initialPoint());
342         /**
343          * For all segments in the subpath
344          */                      
345         for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_closed(); ++cit)
346                     {
348             if( is_straight_curve(*cit) )
349                 {
350                 Geom::Point p0 = cit->initialPoint();
351                 Geom::Point p1 = cit->finalPoint();
352                 segment(segmentNr++,
353                         p0[X], p0[Y], p0[X], p0[Y], p1[X], p1[Y], p1[X], p1[Y] );
354                 nrNodes += 8;
355                 }
356             else if(Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const*>(&*cit))
357                             {
358                 std::vector<Geom::Point> points = cubic->points();
359                 Geom::Point p0 = points[0];
360                 Geom::Point p1 = points[1];
361                 Geom::Point p2 = points[2];
362                 Geom::Point p3 = points[3];
363                 segment(segmentNr++,
364                             p0[X],p0[Y], p1[X],p1[Y], p2[X],p2[Y], p3[X],p3[Y]);
365                 nrNodes += 8;
366                 }
367             else
368                             {
369                 err("logical error, because pathv_to_linear_and_cubic_beziers was used");
370                 return false;
371                 }
373             if (segmentNr < segmentCount)
374                 out(",\n");
375             else
376                 out("\n");
378             cminmax.expandTo(cit->finalPoint());
380             }
381         }
383     out("}\n");
385     double cminx = cminmax.min()[X];
386     double cmaxx = cminmax.max()[X];
387     double cminy = cminmax.min()[Y];
388     double cmaxy = cminmax.max()[Y];
390     out("#declare %s_MIN_X    = %s;\n", id.c_str(), DSTR(cminx));
391     out("#declare %s_CENTER_X = %s;\n", id.c_str(), DSTR((cmaxx+cminx)/2.0));
392     out("#declare %s_MAX_X    = %s;\n", id.c_str(), DSTR(cmaxx));
393     out("#declare %s_WIDTH    = %s;\n", id.c_str(), DSTR(cmaxx-cminx));
394     out("#declare %s_MIN_Y    = %s;\n", id.c_str(), DSTR(cminy));
395     out("#declare %s_CENTER_Y = %s;\n", id.c_str(), DSTR((cmaxy+cminy)/2.0));
396     out("#declare %s_MAX_Y    = %s;\n", id.c_str(), DSTR(cmaxy));
397     out("#declare %s_HEIGHT   = %s;\n", id.c_str(), DSTR(cmaxy-cminy));
398     if (shapeInfo.color.length()>0)
399         out("#declare %s_COLOR    = %s;\n",
400                 id.c_str(), shapeInfo.color.c_str());
401     out("/*###################################################\n");
402     out("### end %s\n", id.c_str());
403     out("###################################################*/\n\n\n\n");
405     if (cminx < minx)
406         minx = cminx;
407     if (cmaxx > maxx)
408         maxx = cmaxx;
409     if (cminy < miny)
410         miny = cminy;
411     if (cmaxy > maxy)
412         maxy = cmaxy;
414     return true;
417 /**
418  *  Descend the svg tree recursively, translating data
419  */
420 bool PovOutput::doTreeRecursive(SPDocument *doc, SPObject *obj)
423     String id;
424     if (!obj->id)
425         {
426         char buf[16];
427         sprintf(buf, "id%d", idIndex++);
428         id = buf;
429         }
430     else
431         {
432         id = obj->id;
433         }
435     if (SP_IS_ITEM(obj))
436         {
437         SPItem *item = SP_ITEM(obj);
438         if (!doCurve(item, id))
439             return false;
440         }
442     /**
443      * Descend into children
444      */
445     for (SPObject *child = obj->firstChild() ; child ; child = child->next)
446         {
447                 if (!doTreeRecursive(doc, child))
448                     return false;
449                 }
451     return true;
454 /**
455  *  Output the curve data to buffer
456  */
457 bool PovOutput::doTree(SPDocument *doc)
459     double bignum = 1000000.0;
460     minx  =  bignum;
461     maxx  = -bignum;
462     miny  =  bignum;
463     maxy  = -bignum;
465     if (!doTreeRecursive(doc, doc->root))
466         return false;
468     //## Let's make a union of all of the Shapes
469     if (povShapes.size()>0)
470         {
471         String id = "AllShapes";
472         char *pfx = (char *)id.c_str();
473         out("/*###################################################\n");
474         out("### UNION OF ALL SHAPES IN DOCUMENT\n");
475         out("###################################################*/\n");
476         out("\n\n");
477         out("/**\n");
478         out(" * Allow the user to redefine the finish{}\n");
479         out(" * by declaring it before #including this file\n");
480         out(" */\n");
481         out("#ifndef (%s_Finish)\n", pfx);
482         out("#declare %s_Finish = finish {\n", pfx);
483         out("    phong 0.5\n");
484         out("    reflection 0.3\n");
485         out("    specular 0.5\n");
486         out("}\n");
487         out("#end\n");
488         out("\n\n");
489         out("#declare %s = union {\n", id.c_str());
490         for (unsigned i = 0 ; i < povShapes.size() ; i++)
491             {
492             out("    object { %s\n", povShapes[i].id.c_str());
493             out("        texture { \n");
494             if (povShapes[i].color.length()>0)
495                 out("            pigment { %s }\n", povShapes[i].color.c_str());
496             else
497                 out("            pigment { rgb <0,0,0> }\n");
498             out("            finish { %s_Finish }\n", pfx);
499             out("            } \n");
500             out("        } \n");
501             }
502         out("}\n\n\n\n");
505         double zinc   = 0.2 / (double)povShapes.size();
506         out("/*#### Same union, but with Z-diffs (actually Y in pov) ####*/\n");
507         out("\n\n");
508         out("/**\n");
509         out(" * Allow the user to redefine the Z-Increment\n");
510         out(" */\n");
511         out("#ifndef (AllShapes_Z_Increment)\n");
512         out("#declare AllShapes_Z_Increment = %s;\n", DSTR(zinc));
513         out("#end\n");
514         out("\n");
515         out("#declare AllShapes_Z_Scale = 1.0;\n");
516         out("\n\n");
517         out("#declare %s_Z = union {\n", pfx);
519         for (unsigned i = 0 ; i < povShapes.size() ; i++)
520             {
521             out("    object { %s\n", povShapes[i].id.c_str());
522             out("        texture { \n");
523             if (povShapes[i].color.length()>0)
524                 out("            pigment { %s }\n", povShapes[i].color.c_str());
525             else
526                 out("            pigment { rgb <0,0,0> }\n");
527             out("            finish { %s_Finish }\n", pfx);
528             out("            } \n");
529             out("        scale <1, %s_Z_Scale, 1>\n", pfx);
530             out("        } \n");
531             out("#declare %s_Z_Scale = %s_Z_Scale + %s_Z_Increment;\n\n",
532                     pfx, pfx, pfx);
533             }
535         out("}\n");
537         out("#declare %s_MIN_X    = %s;\n", pfx, DSTR(minx));
538         out("#declare %s_CENTER_X = %s;\n", pfx, DSTR((maxx+minx)/2.0));
539         out("#declare %s_MAX_X    = %s;\n", pfx, DSTR(maxx));
540         out("#declare %s_WIDTH    = %s;\n", pfx, DSTR(maxx-minx));
541         out("#declare %s_MIN_Y    = %s;\n", pfx, DSTR(miny));
542         out("#declare %s_CENTER_Y = %s;\n", pfx, DSTR((maxy+miny)/2.0));
543         out("#declare %s_MAX_Y    = %s;\n", pfx, DSTR(maxy));
544         out("#declare %s_HEIGHT   = %s;\n", pfx, DSTR(maxy-miny));
545         out("/*##############################################\n");
546         out("### end %s\n", id.c_str());
547         out("##############################################*/\n");
548         out("\n\n");
549         }
551     return true;
555 //########################################################################
556 //# M A I N    O U T P U T
557 //########################################################################
561 /**
562  *  Set values back to initial state
563  */
564 void PovOutput::reset()
566     nrNodes    = 0;
567     nrSegments = 0;
568     nrShapes   = 0;
569     idIndex    = 0;
570     outbuf.clear();
571     povShapes.clear();
576 /**
577  * Saves the Shapes of an Inkscape SVG file as PovRay spline definitions
578  */
579 void PovOutput::saveDocument(SPDocument *doc, gchar const *uri)
581     reset();
583     //###### SAVE IN POV FORMAT TO BUFFER
584     //# Lets do the curves first, to get the stats
585     if (!doTree(doc))
586         {
587         err("Could not output curves for %s", uri);
588         return;
589         }
590         
591     String curveBuf = outbuf;
592     outbuf.clear();
594     if (!doHeader())
595         {
596         err("Could not write header for %s", uri);
597         return;
598         }
600     outbuf.append(curveBuf);
602     if (!doTail())
603         {
604         err("Could not write footer for %s", uri);
605         return;
606         }
611     //###### WRITE TO FILE
612     Inkscape::IO::dump_fopen_call(uri, "L");
613     FILE *f = Inkscape::IO::fopen_utf8name(uri, "w");
614     if (!f)
615         return;
617     for (String::iterator iter = outbuf.begin() ; iter!=outbuf.end(); iter++)
618         {
619         int ch = *iter;
620         fputc(ch, f);
621         }
623     fclose(f);
629 //########################################################################
630 //# EXTENSION API
631 //########################################################################
635 #include "clear-n_.h"
639 /**
640  * API call to save document
641 */
642 void
643 PovOutput::save(Inkscape::Extension::Output */*mod*/,
644                         SPDocument *doc, gchar const *uri)
646     saveDocument(doc, uri);
651 /**
652  * Make sure that we are in the database
653  */
654 bool PovOutput::check (Inkscape::Extension::Extension */*module*/)
656     /* We don't need a Key
657     if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
658         return FALSE;
659     */
661     return true;
666 /**
667  * This is the definition of PovRay output.  This function just
668  * calls the extension system with the memory allocated XML that
669  * describes the data.
670 */
671 void
672 PovOutput::init()
674     Inkscape::Extension::build_from_mem(
675         "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
676             "<name>" N_("PovRay Output") "</name>\n"
677             "<id>org.inkscape.output.pov</id>\n"
678             "<output>\n"
679                 "<extension>.pov</extension>\n"
680                 "<mimetype>text/x-povray-script</mimetype>\n"
681                 "<filetypename>" N_("PovRay (*.pov) (export splines)") "</filetypename>\n"
682                 "<filetypetooltip>" N_("PovRay Raytracer File") "</filetypetooltip>\n"
683             "</output>\n"
684         "</inkscape-extension>",
685         new PovOutput());
692 }  // namespace Internal
693 }  // namespace Extension
694 }  // namespace Inkscape
697 /*
698   Local Variables:
699   mode:c++
700   c-file-style:"stroustrup"
701   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
702   indent-tabs-mode:nil
703   fill-column:99
704   End:
705 */
706 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :