Code

update to 2geom rev. 1507
[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 <libnr/n-art-bpath.h>
30 #include <extension/system.h>
31 #include <2geom/pathvector.h>
32 #include <2geom/rect.h>
33 #include <2geom/bezier-curve.h>
34 #include <2geom/hvlinesegment.h>
35 #include "helper/geom.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 {
53 //########################################################################
54 //# U T I L I T Y
55 //########################################################################
59 /**
60  * This function searches the Repr tree recursively from the given node,
61  * and adds refs to all nodes with the given name, to the result vector
62  */
63 static void
64 findElementsByTagName(std::vector<Inkscape::XML::Node *> &results,
65                       Inkscape::XML::Node *node,
66                       char const *name)
67 {
68     if ( !name || strcmp(node->name(), name) == 0 )
69         results.push_back(node);
71     for (Inkscape::XML::Node *child = node->firstChild() ; child ;
72               child = child->next())
73         findElementsByTagName( results, child, name );
75 }
81 static double
82 effective_opacity(SPItem const *item)
83 {
84     double ret = 1.0;
85     for (SPObject const *obj = item; obj; obj = obj->parent)
86         {
87         SPStyle const *const style = SP_OBJECT_STYLE(obj);
88         g_return_val_if_fail(style, ret);
89         ret *= SP_SCALE24_TO_FLOAT(style->opacity.value);
90         }
91     return ret;
92 }
98 //########################################################################
99 //# OUTPUT FORMATTING
100 //########################################################################
103 /**
104  * We want to control floating output format
105  */
106 static PovOutput::String dstr(double d)
108     char dbuf[G_ASCII_DTOSTR_BUF_SIZE+1];
109     g_ascii_formatd(dbuf, G_ASCII_DTOSTR_BUF_SIZE,
110                   "%.8f", (gdouble)d);
111     PovOutput::String s = dbuf;
112     return s;
118 /**
119  *  Output data to the buffer, printf()-style
120  */
121 void PovOutput::out(const char *fmt, ...)
123     va_list args;
124     va_start(args, fmt);
125     gchar *output = g_strdup_vprintf(fmt, args);
126     va_end(args);
127     outbuf.append(output);
128     g_free(output);
135 /**
136  *  Output a 2d vector
137  */
138 void PovOutput::vec2(double a, double b)
140     out("<%s, %s>", dstr(a).c_str(), dstr(b).c_str());
145 /**
146  * Output a 3d vector
147  */
148 void PovOutput::vec3(double a, double b, double c)
150     out("<%s, %s, %s>", dstr(a).c_str(), dstr(b).c_str(), dstr(c).c_str());
155 /**
156  *  Output a v4d ector
157  */
158 void PovOutput::vec4(double a, double b, double c, double d)
160     out("<%s, %s, %s, %s>", dstr(a).c_str(), dstr(b).c_str(),
161                  dstr(c).c_str(), dstr(d).c_str());
166 /**
167  *  Output an rgbf color vector
168  */
169 void PovOutput::rgbf(double r, double g, double b, double f)
171     //"rgbf < %1.3f, %1.3f, %1.3f %1.3f>"
172     out("rgbf ");
173     vec4(r, g, b, f);
178 /**
179  *  Output one bezier's start, start-control, end-control, and end nodes
180  */
181 void PovOutput::segment(int segNr,
182                         double startX,     double startY,
183                         double startCtrlX, double startCtrlY,
184                         double endCtrlX,   double endCtrlY,
185                         double endX,       double endY)
187     //"    /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>"
188     out("    /*%4d*/ ", segNr);
189     vec2(startX,     startY);
190     out(", ");
191     vec2(startCtrlX, startCtrlY);
192     out(", ");
193     vec2(endCtrlX,   endCtrlY);
194     out(", ");
195     vec2(endX,       endY);
202 /**
203  * Output the file header
204  */
205 void PovOutput::doHeader()
207     time_t tim = time(NULL);
208     out("/*###################################################################\n");
209     out("### This PovRay document was generated by Inkscape\n");
210     out("### http://www.inkscape.org\n");
211     out("### Created: %s", ctime(&tim));
212     out("### Version: %s\n", INKSCAPE_VERSION);
213     out("#####################################################################\n");
214     out("### NOTES:\n");
215     out("### ============\n");
216     out("### POVRay information can be found at\n");
217     out("### http://www.povray.org\n");
218     out("###\n");
219     out("### The 'AllShapes' objects at the bottom are provided as a\n");
220     out("### preview of how the output would look in a trace.  However,\n");
221     out("### the main intent of this file is to provide the individual\n");
222     out("### shapes for inclusion in a POV project.\n");
223     out("###\n");
224     out("### For an example of how to use this file, look at\n");
225     out("### share/examples/istest.pov\n");
226     out("###\n");
227     out("### If you have any problems with this output, please see the\n");
228     out("### Inkscape project at http://www.inkscape.org, or visit\n");
229     out("### the #inkscape channel on irc.freenode.net . \n");
230     out("###\n");
231     out("###################################################################*/\n");
232     out("\n\n");
233     out("/*###################################################################\n");
234     out("##   Exports in this file\n");
235     out("##==========================\n");
236     out("##    Shapes   : %d\n", nrShapes);
237     out("##    Segments : %d\n", nrSegments);
238     out("##    Nodes    : %d\n", nrNodes);
239     out("###################################################################*/\n");
240     out("\n\n\n");
245 /**
246  *  Output the file footer
247  */
248 void PovOutput::doTail()
250     out("\n\n");
251     out("/*###################################################################\n");
252     out("### E N D    F I L E\n");
253     out("###################################################################*/\n");
254     out("\n\n");
259 /**
260  *  Output the curve data to buffer
261  */
262 void PovOutput::doCurves(SPDocument *doc)
264     using Geom::X;
265     using Geom::Y;
267     std::vector<Inkscape::XML::Node *>results;
268     //findElementsByTagName(results, SP_ACTIVE_DOCUMENT->rroot, "path");
269     findElementsByTagName(results, SP_ACTIVE_DOCUMENT->rroot, NULL);
270     if (results.size() == 0)
271         return;
273     double bignum = 1000000.0;
274     double minx  =  bignum;
275     double maxx  = -bignum;
276     double miny  =  bignum;
277     double maxy  = -bignum;
279     for (unsigned int indx = 0; indx < results.size() ; indx++)
280         {
281         //### Fetch the object from the repr info
282         Inkscape::XML::Node *rpath = results[indx];
283         char *str  = (char *) rpath->attribute("id");
284         if (!str)
285             continue;
287         String id = str;
288         SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(rpath);
289         if (!reprobj)
290             continue;
292         //### Get the transform of the item
293         if (!SP_IS_ITEM(reprobj))
294             continue;
296         SPItem *item = SP_ITEM(reprobj);
297         Geom::Matrix tf = sp_item_i2d_affine(item);
299         //### Get the Shape
300         if (!SP_IS_SHAPE(reprobj))//Bulia's suggestion.  Allow all shapes
301             continue;
303         SPShape *shape = SP_SHAPE(reprobj);
304         SPCurve *curve = shape->curve;
305         if (curve->is_empty())
306             continue;
307             
308         nrShapes++;
310         PovShapeInfo shapeInfo;
311         shapeInfo.id    = id;
312         shapeInfo.color = "";
314         //Try to get the fill color of the shape
315         SPStyle *style = SP_OBJECT_STYLE(shape);
316         /* fixme: Handle other fill types, even if this means translating gradients to a single
317            flat colour. */
318         if (style && (style->fill.isColor()))
319             {
320             // see color.h for how to parse SPColor
321             float rgb[3];
322             sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
323             double const dopacity = ( SP_SCALE24_TO_FLOAT(style->fill_opacity.value)
324                                       * effective_opacity(shape) );
325             //gchar *str = g_strdup_printf("rgbf < %1.3f, %1.3f, %1.3f %1.3f>",
326             //                             rgb[0], rgb[1], rgb[2], 1.0 - dopacity);
327             String rgbf = "rgbf <";
328             rgbf.append(dstr(rgb[0]));         rgbf.append(", ");
329             rgbf.append(dstr(rgb[1]));         rgbf.append(", ");
330             rgbf.append(dstr(rgb[2]));         rgbf.append(", ");
331             rgbf.append(dstr(1.0 - dopacity)); rgbf.append(">");
332             shapeInfo.color += rgbf;
333             }
335         povShapes.push_back(shapeInfo); //passed all tests.  save the info
337         // convert the path to only lineto's and cubic curveto's:
338         Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers( curve->get_pathvector() * tf );
340         //Count the NR_CURVETOs/LINETOs (including closing line segment)
341         guint segmentCount = 0;
342         for(Geom::PathVector::const_iterator it = pathv.begin(); it != pathv.end(); ++it) {
343             segmentCount += (*it).size();
344             if (it->closed())
345                 segmentCount += 1;
346         }
348         out("/*###################################################\n");
349         out("### PRISM:  %s\n", id.c_str());
350         out("###################################################*/\n");
351         out("#declare %s = prism {\n", id.c_str());
352         out("    linear_sweep\n");
353         out("    bezier_spline\n");
354         out("    1.0, //top\n");
355         out("    0.0, //bottom\n");
356         out("    %d //nr points\n", segmentCount * 4);
357         int segmentNr = 0;
359         nrSegments += segmentCount;
361         Geom::Rect cminmax( pathv.front().initialPoint(), pathv.front().initialPoint() );  // at moment of writing, 2geom lacks proper initialization of empty intervals in rect...
362         for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit) {
364             cminmax.expandTo(pit->initialPoint());
366             for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_closed(); ++cit) {
368                 if( dynamic_cast<Geom::LineSegment const *> (&*cit) ||
369                     dynamic_cast<Geom::HLineSegment const *>(&*cit) ||
370                     dynamic_cast<Geom::VLineSegment const *>(&*cit) )
371                 {
372                     segment(segmentNr++,
373                             cit->initialPoint()[X], cit->initialPoint()[Y], cit->initialPoint()[X], cit->initialPoint()[Y],
374                             cit->finalPoint()[X], cit->finalPoint()[Y], cit->finalPoint()[X], cit->finalPoint()[Y] );
375                     nrNodes += 8;
376                 }
377                 else if(Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const*>(&*cit)) {
378                     std::vector<Geom::Point> points = cubic->points();
379                     segment(segmentNr++,
380                             points[0][X],points[0][Y], points[1][X],points[1][Y], points[2][X],points[2][Y], points[3][X],points[3][Y]);
381                     nrNodes += 8;
382                 }
383                 else {
384                     g_error ("logical error, because pathv_to_linear_and_cubic_beziers was used");
385                 }
387                 if (segmentNr <= segmentCount)
388                     out(",\n");
389                 else
390                     out("\n");
392                 cminmax.expandTo(cit->finalPoint());
394             }
395         }
397         out("}\n");
399         double cminx = cminmax.min()[X];
400         double cmaxx = cminmax.max()[X];
401         double cminy = cminmax.min()[Y];
402         double cmaxy = cminmax.max()[Y];
403                      
404         //# prefix for following declarations
405         char *pfx = (char *)id.c_str();
407         out("#declare %s_MIN_X    = %s;\n", pfx, dstr(cminx).c_str());
408         out("#declare %s_CENTER_X = %s;\n", pfx, dstr((cmaxx+cminx)/2.0).c_str());
409         out("#declare %s_MAX_X    = %s;\n", pfx, dstr(cmaxx).c_str());
410         out("#declare %s_WIDTH    = %s;\n", pfx, dstr(cmaxx-cminx).c_str());
411         out("#declare %s_MIN_Y    = %s;\n", pfx, dstr(cminy).c_str());
412         out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((cmaxy+cminy)/2.0).c_str());
413         out("#declare %s_MAX_Y    = %s;\n", pfx, dstr(cmaxy).c_str());
414         out("#declare %s_HEIGHT   = %s;\n", pfx, dstr(cmaxy-cminy).c_str());
415         if (shapeInfo.color.length()>0)
416             out("#declare %s_COLOR    = %s;\n",
417                     pfx, shapeInfo.color.c_str());
418         out("/*###################################################\n");
419         out("### end %s\n", id.c_str());
420         out("###################################################*/\n\n\n\n");
421         if (cminx < minx)
422             minx = cminx;
423         if (cmaxx > maxx)
424             maxx = cmaxx;
425         if (cminy < miny)
426             miny = cminy;
427         if (cmaxy > maxy)
428             maxy = cmaxy;
430         }//for
434     //## Let's make a union of all of the Shapes
435     if (povShapes.size()>0)
436         {
437         String id = "AllShapes";
438         char *pfx = (char *)id.c_str();
439         out("/*###################################################\n");
440         out("### UNION OF ALL SHAPES IN DOCUMENT\n");
441         out("###################################################*/\n");
442         out("\n\n");
443         out("/**\n");
444         out(" * Allow the user to redefine the finish{}\n");
445         out(" * by declaring it before #including this file\n");
446         out(" */\n");
447         out("#ifndef (%s_Finish)\n", pfx);
448         out("#declare %s_Finish = finish {\n", pfx);
449         out("    phong 0.5\n");
450         out("    reflection 0.3\n");
451         out("    specular 0.5\n");
452         out("}\n");
453         out("#end\n");
454         out("\n\n");
455         out("#declare %s = union {\n", id.c_str());
456         for (unsigned i = 0 ; i < povShapes.size() ; i++)
457             {
458             out("    object { %s\n", povShapes[i].id.c_str());
459             out("        texture { \n");
460             if (povShapes[i].color.length()>0)
461                 out("            pigment { %s }\n", povShapes[i].color.c_str());
462             else
463                 out("            pigment { rgb <0,0,0> }\n");
464             out("            finish { %s_Finish }\n", pfx);
465             out("            } \n");
466             out("        } \n");
467             }
468         out("}\n\n\n\n");
471         double zinc   = 0.2 / (double)povShapes.size();
472         out("/*#### Same union, but with Z-diffs (actually Y in pov) ####*/\n");
473         out("\n\n");
474         out("/**\n");
475         out(" * Allow the user to redefine the Z-Increment\n");
476         out(" */\n");
477         out("#ifndef (AllShapes_Z_Increment)\n");
478         out("#declare AllShapes_Z_Increment = %s;\n", dstr(zinc).c_str());
479         out("#end\n");
480         out("\n");
481         out("#declare AllShapes_Z_Scale = 1.0;\n");
482         out("\n\n");
483         out("#declare %s_Z = union {\n", pfx);
485         for (unsigned i = 0 ; i < povShapes.size() ; i++)
486             {
487             out("    object { %s\n", povShapes[i].id.c_str());
488             out("        texture { \n");
489             if (povShapes[i].color.length()>0)
490                 out("            pigment { %s }\n", povShapes[i].color.c_str());
491             else
492                 out("            pigment { rgb <0,0,0> }\n");
493             out("            finish { %s_Finish }\n", pfx);
494             out("            } \n");
495             out("        scale <1, %s_Z_Scale, 1>\n", pfx);
496             out("        } \n");
497             out("#declare %s_Z_Scale = %s_Z_Scale + %s_Z_Increment;\n\n",
498                     pfx, pfx, pfx);
499             }
501         out("}\n");
503         out("#declare %s_MIN_X    = %s;\n", pfx, dstr(minx).c_str());
504         out("#declare %s_CENTER_X = %s;\n", pfx, dstr((maxx+minx)/2.0).c_str());
505         out("#declare %s_MAX_X    = %s;\n", pfx, dstr(maxx).c_str());
506         out("#declare %s_WIDTH    = %s;\n", pfx, dstr(maxx-minx).c_str());
507         out("#declare %s_MIN_Y    = %s;\n", pfx, dstr(miny).c_str());
508         out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((maxy+miny)/2.0).c_str());
509         out("#declare %s_MAX_Y    = %s;\n", pfx, dstr(maxy).c_str());
510         out("#declare %s_HEIGHT   = %s;\n", pfx, dstr(maxy-miny).c_str());
511         out("/*##############################################\n");
512         out("### end %s\n", id.c_str());
513         out("##############################################*/\n");
514         out("\n\n");
515         }
522 //########################################################################
523 //# M A I N    O U T P U T
524 //########################################################################
528 /**
529  *  Set values back to initial state
530  */
531 void PovOutput::reset()
533     nrNodes    = 0;
534     nrSegments = 0;
535     nrShapes   = 0;
536     outbuf.clear();
537     povShapes.clear();
542 /**
543  * Saves the <paths> of an Inkscape SVG file as PovRay spline definitions
544  */
545 void PovOutput::saveDocument(SPDocument *doc, gchar const *uri)
547     reset();
549     //###### SAVE IN POV FORMAT TO BUFFER
550     //# Lets do the curves first, to get the stats
551     doCurves(doc);
552     String curveBuf = outbuf;
553     outbuf.clear();
555     doHeader();
556     
557     outbuf.append(curveBuf);
558     
559     doTail();
564     //###### WRITE TO FILE
565     Inkscape::IO::dump_fopen_call(uri, "L");
566     FILE *f = Inkscape::IO::fopen_utf8name(uri, "w");
567     if (!f)
568         return;
570     for (String::iterator iter = outbuf.begin() ; iter!=outbuf.end(); iter++)
571         {
572         int ch = *iter;
573         fputc(ch, f);
574         }
575         
576     fclose(f);
582 //########################################################################
583 //# EXTENSION API
584 //########################################################################
588 #include "clear-n_.h"
592 /**
593  * API call to save document
594 */
595 void
596 PovOutput::save(Inkscape::Extension::Output *mod,
597                         SPDocument *doc, gchar const *uri)
599     saveDocument(doc, uri);
604 /**
605  * Make sure that we are in the database
606  */
607 bool PovOutput::check (Inkscape::Extension::Extension *module)
609     /* We don't need a Key
610     if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
611         return FALSE;
612     */
614     return true;
619 /**
620  * This is the definition of PovRay output.  This function just
621  * calls the extension system with the memory allocated XML that
622  * describes the data.
623 */
624 void
625 PovOutput::init()
627     Inkscape::Extension::build_from_mem(
628         "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
629             "<name>" N_("PovRay Output") "</name>\n"
630             "<id>org.inkscape.output.pov</id>\n"
631             "<output>\n"
632                 "<extension>.pov</extension>\n"
633                 "<mimetype>text/x-povray-script</mimetype>\n"
634                 "<filetypename>" N_("PovRay (*.pov) (export splines)") "</filetypename>\n"
635                 "<filetypetooltip>" N_("PovRay Raytracer File") "</filetypetooltip>\n"
636             "</output>\n"
637         "</inkscape-extension>",
638         new PovOutput());
645 }  // namespace Internal
646 }  // namespace Extension
647 }  // namespace Inkscape
650 /*
651   Local Variables:
652   mode:c++
653   c-file-style:"stroustrup"
654   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
655   indent-tabs-mode:nil
656   fill-column:99
657   End:
658 */
659 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :