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 {
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)
107 {
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;
113 }
118 /**
119 * Output data to the buffer, printf()-style
120 */
121 void PovOutput::out(const char *fmt, ...)
122 {
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);
129 }
135 /**
136 * Output a 2d vector
137 */
138 void PovOutput::vec2(double a, double b)
139 {
140 out("<%s, %s>", dstr(a).c_str(), dstr(b).c_str());
141 }
145 /**
146 * Output a 3d vector
147 */
148 void PovOutput::vec3(double a, double b, double c)
149 {
150 out("<%s, %s, %s>", dstr(a).c_str(), dstr(b).c_str(), dstr(c).c_str());
151 }
155 /**
156 * Output a v4d ector
157 */
158 void PovOutput::vec4(double a, double b, double c, double d)
159 {
160 out("<%s, %s, %s, %s>", dstr(a).c_str(), dstr(b).c_str(),
161 dstr(c).c_str(), dstr(d).c_str());
162 }
166 /**
167 * Output an rgbf color vector
168 */
169 void PovOutput::rgbf(double r, double g, double b, double f)
170 {
171 //"rgbf < %1.3f, %1.3f, %1.3f %1.3f>"
172 out("rgbf ");
173 vec4(r, g, b, f);
174 }
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)
186 {
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);
196 }
202 /**
203 * Output the file header
204 */
205 bool PovOutput::doHeader()
206 {
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");
241 return true;
242 }
246 /**
247 * Output the file footer
248 */
249 bool PovOutput::doTail()
250 {
251 out("\n\n");
252 out("/*###################################################################\n");
253 out("### E N D F I L E\n");
254 out("###################################################################*/\n");
255 out("\n\n");
256 return true;
257 }
261 /**
262 * Output the curve data to buffer
263 */
264 bool PovOutput::doCurve(SPItem *item, const String &id)
265 {
266 using Geom::X;
267 using Geom::Y;
269 //### Get the Shape
270 if (!SP_IS_SHAPE(item))//Bulia's suggestion. Allow all shapes
271 return true;
273 SPShape *shape = SP_SHAPE(item);
274 SPCurve *curve = shape->curve;
275 if (curve->is_empty())
276 return true;
278 nrShapes++;
280 PovShapeInfo shapeInfo;
281 shapeInfo.id = id;
282 shapeInfo.color = "";
284 //Try to get the fill color of the shape
285 SPStyle *style = SP_OBJECT_STYLE(shape);
286 /* fixme: Handle other fill types, even if this means translating gradients to a single
287 flat colour. */
288 if (style)
289 {
290 if (style->fill.isColor())
291 {
292 // see color.h for how to parse SPColor
293 float rgb[3];
294 sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
295 double const dopacity = ( SP_SCALE24_TO_FLOAT(style->fill_opacity.value)
296 * effective_opacity(shape) );
297 //gchar *str = g_strdup_printf("rgbf < %1.3f, %1.3f, %1.3f %1.3f>",
298 // rgb[0], rgb[1], rgb[2], 1.0 - dopacity);
299 String rgbf = "rgbf <";
300 rgbf.append(dstr(rgb[0])); rgbf.append(", ");
301 rgbf.append(dstr(rgb[1])); rgbf.append(", ");
302 rgbf.append(dstr(rgb[2])); rgbf.append(", ");
303 rgbf.append(dstr(1.0 - dopacity)); rgbf.append(">");
304 shapeInfo.color += rgbf;
305 }
306 }
308 povShapes.push_back(shapeInfo); //passed all tests. save the info
310 // convert the path to only lineto's and cubic curveto's:
311 Geom::Matrix tf = sp_item_i2d_affine(item);
312 Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers( curve->get_pathvector() * tf );
314 //Count the NR_CURVETOs/LINETOs (including closing line segment)
315 int segmentCount = 0;
316 for(Geom::PathVector::const_iterator it = pathv.begin(); it != pathv.end(); ++it)
317 {
318 segmentCount += (*it).size();
319 if (it->closed())
320 segmentCount += 1;
321 }
323 out("/*###################################################\n");
324 out("### PRISM: %s\n", id.c_str());
325 out("###################################################*/\n");
326 out("#declare %s = prism {\n", id.c_str());
327 out(" linear_sweep\n");
328 out(" bezier_spline\n");
329 out(" 1.0, //top\n");
330 out(" 0.0, //bottom\n");
331 out(" %d //nr points\n", segmentCount * 4);
332 int segmentNr = 0;
334 nrSegments += segmentCount;
336 /**
337 * at moment of writing, 2geom lacks proper initialization of empty intervals in rect...
338 */
339 Geom::Rect cminmax( pathv.front().initialPoint(), pathv.front().initialPoint() );
342 /**
343 * For all Subpaths in the <path>
344 */
345 for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit)
346 {
348 cminmax.expandTo(pit->initialPoint());
350 /**
351 * For all segments in the subpath
352 */
353 for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_closed(); ++cit)
354 {
356 if( is_straight_curve(*cit) )
357 {
358 Geom::Point p0 = cit->initialPoint();
359 Geom::Point p1 = cit->finalPoint();
360 segment(segmentNr++,
361 p0[X], p0[Y], p0[X], p0[Y], p1[X], p1[Y], p1[X], p1[Y] );
362 nrNodes += 8;
363 }
364 else if(Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const*>(&*cit))
365 {
366 std::vector<Geom::Point> points = cubic->points();
367 Geom::Point p0 = points[0];
368 Geom::Point p1 = points[1];
369 Geom::Point p2 = points[2];
370 Geom::Point p3 = points[3];
371 segment(segmentNr++,
372 p0[X],p0[Y], p1[X],p1[Y], p2[X],p2[Y], p3[X],p3[Y]);
373 nrNodes += 8;
374 }
375 else
376 {
377 g_warning("logical error, because pathv_to_linear_and_cubic_beziers was used");
378 return false;
379 }
381 if (segmentNr < segmentCount)
382 out(",\n");
383 else
384 out("\n");
386 cminmax.expandTo(cit->finalPoint());
388 }
389 }
391 out("}\n");
393 double cminx = cminmax.min()[X];
394 double cmaxx = cminmax.max()[X];
395 double cminy = cminmax.min()[Y];
396 double cmaxy = cminmax.max()[Y];
398 out("#declare %s_MIN_X = %s;\n", id.c_str(), dstr(cminx).c_str());
399 out("#declare %s_CENTER_X = %s;\n", id.c_str(), dstr((cmaxx+cminx)/2.0).c_str());
400 out("#declare %s_MAX_X = %s;\n", id.c_str(), dstr(cmaxx).c_str());
401 out("#declare %s_WIDTH = %s;\n", id.c_str(), dstr(cmaxx-cminx).c_str());
402 out("#declare %s_MIN_Y = %s;\n", id.c_str(), dstr(cminy).c_str());
403 out("#declare %s_CENTER_Y = %s;\n", id.c_str(), dstr((cmaxy+cminy)/2.0).c_str());
404 out("#declare %s_MAX_Y = %s;\n", id.c_str(), dstr(cmaxy).c_str());
405 out("#declare %s_HEIGHT = %s;\n", id.c_str(), dstr(cmaxy-cminy).c_str());
406 if (shapeInfo.color.length()>0)
407 out("#declare %s_COLOR = %s;\n",
408 id.c_str(), shapeInfo.color.c_str());
409 out("/*###################################################\n");
410 out("### end %s\n", id.c_str());
411 out("###################################################*/\n\n\n\n");
413 if (cminx < minx)
414 minx = cminx;
415 if (cmaxx > maxx)
416 maxx = cmaxx;
417 if (cminy < miny)
418 miny = cminy;
419 if (cmaxy > maxy)
420 maxy = cmaxy;
422 return true;
423 }
425 /**
426 * Output the curve data to buffer
427 */
428 bool PovOutput::doCurvesRecursive(SPDocument *doc, Inkscape::XML::Node *node)
429 {
430 /**
431 * If the object is an Item, try processing it
432 */
433 char *str = (char *) node->attribute("id");
434 SPObject *reprobj = doc->getObjectByRepr(node);
435 if (SP_IS_ITEM(reprobj) && str)
436 {
437 SPItem *item = SP_ITEM(reprobj);
438 String id = str;
439 if (!doCurve(item, id))
440 return false;
441 }
443 /**
444 * Descend into children
445 */
446 for (Inkscape::XML::Node *child = node->firstChild() ; child ;
447 child = child->next())
448 {
449 if (!doCurvesRecursive(doc, child))
450 return false;
451 }
453 return true;
454 }
456 /**
457 * Output the curve data to buffer
458 */
459 bool PovOutput::doCurves(SPDocument *doc)
460 {
461 double bignum = 1000000.0;
462 minx = bignum;
463 maxx = -bignum;
464 miny = bignum;
465 maxy = -bignum;
467 if (!doCurvesRecursive(doc, doc->rroot))
468 return false;
470 //## Let's make a union of all of the Shapes
471 if (povShapes.size()>0)
472 {
473 String id = "AllShapes";
474 char *pfx = (char *)id.c_str();
475 out("/*###################################################\n");
476 out("### UNION OF ALL SHAPES IN DOCUMENT\n");
477 out("###################################################*/\n");
478 out("\n\n");
479 out("/**\n");
480 out(" * Allow the user to redefine the finish{}\n");
481 out(" * by declaring it before #including this file\n");
482 out(" */\n");
483 out("#ifndef (%s_Finish)\n", pfx);
484 out("#declare %s_Finish = finish {\n", pfx);
485 out(" phong 0.5\n");
486 out(" reflection 0.3\n");
487 out(" specular 0.5\n");
488 out("}\n");
489 out("#end\n");
490 out("\n\n");
491 out("#declare %s = union {\n", id.c_str());
492 for (unsigned i = 0 ; i < povShapes.size() ; i++)
493 {
494 out(" object { %s\n", povShapes[i].id.c_str());
495 out(" texture { \n");
496 if (povShapes[i].color.length()>0)
497 out(" pigment { %s }\n", povShapes[i].color.c_str());
498 else
499 out(" pigment { rgb <0,0,0> }\n");
500 out(" finish { %s_Finish }\n", pfx);
501 out(" } \n");
502 out(" } \n");
503 }
504 out("}\n\n\n\n");
507 double zinc = 0.2 / (double)povShapes.size();
508 out("/*#### Same union, but with Z-diffs (actually Y in pov) ####*/\n");
509 out("\n\n");
510 out("/**\n");
511 out(" * Allow the user to redefine the Z-Increment\n");
512 out(" */\n");
513 out("#ifndef (AllShapes_Z_Increment)\n");
514 out("#declare AllShapes_Z_Increment = %s;\n", dstr(zinc).c_str());
515 out("#end\n");
516 out("\n");
517 out("#declare AllShapes_Z_Scale = 1.0;\n");
518 out("\n\n");
519 out("#declare %s_Z = union {\n", pfx);
521 for (unsigned i = 0 ; i < povShapes.size() ; i++)
522 {
523 out(" object { %s\n", povShapes[i].id.c_str());
524 out(" texture { \n");
525 if (povShapes[i].color.length()>0)
526 out(" pigment { %s }\n", povShapes[i].color.c_str());
527 else
528 out(" pigment { rgb <0,0,0> }\n");
529 out(" finish { %s_Finish }\n", pfx);
530 out(" } \n");
531 out(" scale <1, %s_Z_Scale, 1>\n", pfx);
532 out(" } \n");
533 out("#declare %s_Z_Scale = %s_Z_Scale + %s_Z_Increment;\n\n",
534 pfx, pfx, pfx);
535 }
537 out("}\n");
539 out("#declare %s_MIN_X = %s;\n", pfx, dstr(minx).c_str());
540 out("#declare %s_CENTER_X = %s;\n", pfx, dstr((maxx+minx)/2.0).c_str());
541 out("#declare %s_MAX_X = %s;\n", pfx, dstr(maxx).c_str());
542 out("#declare %s_WIDTH = %s;\n", pfx, dstr(maxx-minx).c_str());
543 out("#declare %s_MIN_Y = %s;\n", pfx, dstr(miny).c_str());
544 out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((maxy+miny)/2.0).c_str());
545 out("#declare %s_MAX_Y = %s;\n", pfx, dstr(maxy).c_str());
546 out("#declare %s_HEIGHT = %s;\n", pfx, dstr(maxy-miny).c_str());
547 out("/*##############################################\n");
548 out("### end %s\n", id.c_str());
549 out("##############################################*/\n");
550 out("\n\n");
551 }
553 return true;
554 }
557 //########################################################################
558 //# M A I N O U T P U T
559 //########################################################################
563 /**
564 * Set values back to initial state
565 */
566 void PovOutput::reset()
567 {
568 nrNodes = 0;
569 nrSegments = 0;
570 nrShapes = 0;
571 outbuf.clear();
572 povShapes.clear();
573 }
577 /**
578 * Saves the Shapes of an Inkscape SVG file as PovRay spline definitions
579 */
580 void PovOutput::saveDocument(SPDocument *doc, gchar const *uri)
581 {
582 reset();
584 //###### SAVE IN POV FORMAT TO BUFFER
585 //# Lets do the curves first, to get the stats
586 if (!doCurves(doc))
587 {
588 g_warning("Could not output curves for %s\n", uri);
589 return;
590 }
592 String curveBuf = outbuf;
593 outbuf.clear();
595 if (!doHeader())
596 {
597 g_warning("Could not write header for %s\n", uri);
598 return;
599 }
601 outbuf.append(curveBuf);
603 if (!doTail())
604 {
605 g_warning("Could not write footer for %s\n", uri);
606 return;
607 }
612 //###### WRITE TO FILE
613 Inkscape::IO::dump_fopen_call(uri, "L");
614 FILE *f = Inkscape::IO::fopen_utf8name(uri, "w");
615 if (!f)
616 return;
618 for (String::iterator iter = outbuf.begin() ; iter!=outbuf.end(); iter++)
619 {
620 int ch = *iter;
621 fputc(ch, f);
622 }
624 fclose(f);
625 }
630 //########################################################################
631 //# EXTENSION API
632 //########################################################################
636 #include "clear-n_.h"
640 /**
641 * API call to save document
642 */
643 void
644 PovOutput::save(Inkscape::Extension::Output *mod,
645 SPDocument *doc, gchar const *uri)
646 {
647 saveDocument(doc, uri);
648 }
652 /**
653 * Make sure that we are in the database
654 */
655 bool PovOutput::check (Inkscape::Extension::Extension *module)
656 {
657 /* We don't need a Key
658 if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
659 return FALSE;
660 */
662 return true;
663 }
667 /**
668 * This is the definition of PovRay output. This function just
669 * calls the extension system with the memory allocated XML that
670 * describes the data.
671 */
672 void
673 PovOutput::init()
674 {
675 Inkscape::Extension::build_from_mem(
676 "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
677 "<name>" N_("PovRay Output") "</name>\n"
678 "<id>org.inkscape.output.pov</id>\n"
679 "<output>\n"
680 "<extension>.pov</extension>\n"
681 "<mimetype>text/x-povray-script</mimetype>\n"
682 "<filetypename>" N_("PovRay (*.pov) (export splines)") "</filetypename>\n"
683 "<filetypetooltip>" N_("PovRay Raytracer File") "</filetypetooltip>\n"
684 "</output>\n"
685 "</inkscape-extension>",
686 new PovOutput());
687 }
693 } // namespace Internal
694 } // namespace Extension
695 } // namespace Inkscape
698 /*
699 Local Variables:
700 mode:c++
701 c-file-style:"stroustrup"
702 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
703 indent-tabs-mode:nil
704 fill-column:99
705 End:
706 */
707 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :