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 * Abhishek Sharma
14 *
15 * Copyright (C) 2004-2008 Authors
16 *
17 * Released under GNU GPL, read the file 'COPYING' for more information
18 */
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24 #include "pov-out.h"
25 #include <inkscape.h>
26 #include <inkscape-version.h>
27 #include <sp-path.h>
28 #include <style.h>
29 #include <display/curve.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 "helper/geom-curves.h"
37 #include <io/sys.h>
39 #include <string>
40 #include <stdio.h>
41 #include <stdarg.h>
44 namespace Inkscape
45 {
46 namespace Extension
47 {
48 namespace Internal
49 {
52 //########################################################################
53 //# M E S S A G E S
54 //########################################################################
56 static void err(const char *fmt, ...)
57 {
58 va_list args;
59 g_log(NULL, G_LOG_LEVEL_WARNING, "Pov-out err: ");
60 va_start(args, fmt);
61 g_logv(NULL, G_LOG_LEVEL_WARNING, fmt, args);
62 va_end(args);
63 g_log(NULL, G_LOG_LEVEL_WARNING, "\n");
64 }
69 //########################################################################
70 //# U T I L I T Y
71 //########################################################################
75 static double
76 effective_opacity(SPItem const *item)
77 {
78 double ret = 1.0;
79 for (SPObject const *obj = item; obj; obj = obj->parent)
80 {
81 SPStyle const *const style = SP_OBJECT_STYLE(obj);
82 g_return_val_if_fail(style, ret);
83 ret *= SP_SCALE24_TO_FLOAT(style->opacity.value);
84 }
85 return ret;
86 }
92 //########################################################################
93 //# OUTPUT FORMATTING
94 //########################################################################
97 /**
98 * We want to control floating output format
99 */
100 static PovOutput::String dstr(double d)
101 {
102 char dbuf[G_ASCII_DTOSTR_BUF_SIZE+1];
103 g_ascii_formatd(dbuf, G_ASCII_DTOSTR_BUF_SIZE,
104 "%.8f", (gdouble)d);
105 PovOutput::String s = dbuf;
106 return s;
107 }
109 #define DSTR(d) (dstr(d).c_str())
112 /**
113 * Output data to the buffer, printf()-style
114 */
115 void PovOutput::out(const char *fmt, ...)
116 {
117 va_list args;
118 va_start(args, fmt);
119 gchar *output = g_strdup_vprintf(fmt, args);
120 va_end(args);
121 outbuf.append(output);
122 g_free(output);
123 }
129 /**
130 * Output a 2d vector
131 */
132 void PovOutput::vec2(double a, double b)
133 {
134 out("<%s, %s>", DSTR(a), DSTR(b));
135 }
139 /**
140 * Output a 3d vector
141 */
142 void PovOutput::vec3(double a, double b, double c)
143 {
144 out("<%s, %s, %s>", DSTR(a), DSTR(b), DSTR(c));
145 }
149 /**
150 * Output a v4d ector
151 */
152 void PovOutput::vec4(double a, double b, double c, double d)
153 {
154 out("<%s, %s, %s, %s>", DSTR(a), DSTR(b), DSTR(c), DSTR(d));
155 }
159 /**
160 * Output an rgbf color vector
161 */
162 void PovOutput::rgbf(double r, double g, double b, double f)
163 {
164 //"rgbf < %1.3f, %1.3f, %1.3f %1.3f>"
165 out("rgbf ");
166 vec4(r, g, b, f);
167 }
171 /**
172 * Output one bezier's start, start-control, end-control, and end nodes
173 */
174 void PovOutput::segment(int segNr,
175 double startX, double startY,
176 double startCtrlX, double startCtrlY,
177 double endCtrlX, double endCtrlY,
178 double endX, double endY)
179 {
180 //" /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>"
181 out(" /*%4d*/ ", segNr);
182 vec2(startX, startY);
183 out(", ");
184 vec2(startCtrlX, startCtrlY);
185 out(", ");
186 vec2(endCtrlX, endCtrlY);
187 out(", ");
188 vec2(endX, endY);
189 }
195 /**
196 * Output the file header
197 */
198 bool PovOutput::doHeader()
199 {
200 time_t tim = time(NULL);
201 out("/*###################################################################\n");
202 out("### This PovRay document was generated by Inkscape\n");
203 out("### http://www.inkscape.org\n");
204 out("### Created: %s", ctime(&tim));
205 out("### Version: %s\n", Inkscape::version_string);
206 out("#####################################################################\n");
207 out("### NOTES:\n");
208 out("### ============\n");
209 out("### POVRay information can be found at\n");
210 out("### http://www.povray.org\n");
211 out("###\n");
212 out("### The 'AllShapes' objects at the bottom are provided as a\n");
213 out("### preview of how the output would look in a trace. However,\n");
214 out("### the main intent of this file is to provide the individual\n");
215 out("### shapes for inclusion in a POV project.\n");
216 out("###\n");
217 out("### For an example of how to use this file, look at\n");
218 out("### share/examples/istest.pov\n");
219 out("###\n");
220 out("### If you have any problems with this output, please see the\n");
221 out("### Inkscape project at http://www.inkscape.org, or visit\n");
222 out("### the #inkscape channel on irc.freenode.net . \n");
223 out("###\n");
224 out("###################################################################*/\n");
225 out("\n\n");
226 out("/*###################################################################\n");
227 out("## Exports in this file\n");
228 out("##==========================\n");
229 out("## Shapes : %d\n", nrShapes);
230 out("## Segments : %d\n", nrSegments);
231 out("## Nodes : %d\n", nrNodes);
232 out("###################################################################*/\n");
233 out("\n\n\n");
234 return true;
235 }
239 /**
240 * Output the file footer
241 */
242 bool PovOutput::doTail()
243 {
244 out("\n\n");
245 out("/*###################################################################\n");
246 out("### E N D F I L E\n");
247 out("###################################################################*/\n");
248 out("\n\n");
249 return true;
250 }
254 /**
255 * Output the curve data to buffer
256 */
257 bool PovOutput::doCurve(SPItem *item, const String &id)
258 {
259 using Geom::X;
260 using Geom::Y;
262 //### Get the Shape
263 if (!SP_IS_SHAPE(item))//Bulia's suggestion. Allow all shapes
264 return true;
266 SPShape *shape = SP_SHAPE(item);
267 SPCurve *curve = shape->curve;
268 if (curve->is_empty())
269 return true;
271 nrShapes++;
273 PovShapeInfo shapeInfo;
274 shapeInfo.id = id;
275 shapeInfo.color = "";
277 //Try to get the fill color of the shape
278 SPStyle *style = SP_OBJECT_STYLE(shape);
279 /* fixme: Handle other fill types, even if this means translating gradients to a single
280 flat colour. */
281 if (style)
282 {
283 if (style->fill.isColor())
284 {
285 // see color.h for how to parse SPColor
286 float rgb[3];
287 sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
288 double const dopacity = ( SP_SCALE24_TO_FLOAT(style->fill_opacity.value)
289 * effective_opacity(shape) );
290 //gchar *str = g_strdup_printf("rgbf < %1.3f, %1.3f, %1.3f %1.3f>",
291 // rgb[0], rgb[1], rgb[2], 1.0 - dopacity);
292 String rgbf = "rgbf <";
293 rgbf.append(dstr(rgb[0])); rgbf.append(", ");
294 rgbf.append(dstr(rgb[1])); rgbf.append(", ");
295 rgbf.append(dstr(rgb[2])); rgbf.append(", ");
296 rgbf.append(dstr(1.0 - dopacity)); rgbf.append(">");
297 shapeInfo.color += rgbf;
298 }
299 }
301 povShapes.push_back(shapeInfo); //passed all tests. save the info
303 // convert the path to only lineto's and cubic curveto's:
304 Geom::Matrix tf = item->i2d_affine();
305 Geom::PathVector pathv = pathv_to_linear_and_cubic_beziers( curve->get_pathvector() * tf );
307 /*
308 * We need to know the number of segments (NR_CURVETOs/LINETOs, including
309 * closing line segment) before we write out segment data. Since we are
310 * going to skip degenerate (zero length) paths, we need to loop over all
311 * subpaths and segments first.
312 */
313 int segmentCount = 0;
314 /**
315 * For all Subpaths in the <path>
316 */
317 for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit)
318 {
319 /**
320 * For all segments in the subpath, including extra closing segment defined by 2geom
321 */
322 for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_closed(); ++cit)
323 {
325 // Skip zero length segments.
326 if( !cit->isDegenerate() ) ++segmentCount;
327 }
328 }
330 out("/*###################################################\n");
331 out("### PRISM: %s\n", id.c_str());
332 out("###################################################*/\n");
333 out("#declare %s = prism {\n", id.c_str());
334 out(" linear_sweep\n");
335 out(" bezier_spline\n");
336 out(" 1.0, //top\n");
337 out(" 0.0, //bottom\n");
338 out(" %d //nr points\n", segmentCount * 4);
339 int segmentNr = 0;
341 nrSegments += segmentCount;
343 /**
344 * at moment of writing, 2geom lacks proper initialization of empty intervals in rect...
345 */
346 Geom::Rect cminmax( pathv.front().initialPoint(), pathv.front().initialPoint() );
349 /**
350 * For all Subpaths in the <path>
351 */
352 for (Geom::PathVector::const_iterator pit = pathv.begin(); pit != pathv.end(); ++pit)
353 {
355 cminmax.expandTo(pit->initialPoint());
357 /**
358 * For all segments in the subpath, including extra closing segment defined by 2geom
359 */
360 for (Geom::Path::const_iterator cit = pit->begin(); cit != pit->end_closed(); ++cit)
361 {
363 // Skip zero length segments
364 if( cit->isDegenerate() )
365 continue;
367 if( is_straight_curve(*cit) )
368 {
369 Geom::Point p0 = cit->initialPoint();
370 Geom::Point p1 = cit->finalPoint();
371 segment(segmentNr++,
372 p0[X], p0[Y], p0[X], p0[Y], p1[X], p1[Y], p1[X], p1[Y] );
373 nrNodes += 8;
374 }
375 else if(Geom::CubicBezier const *cubic = dynamic_cast<Geom::CubicBezier const*>(&*cit))
376 {
377 std::vector<Geom::Point> points = cubic->points();
378 Geom::Point p0 = points[0];
379 Geom::Point p1 = points[1];
380 Geom::Point p2 = points[2];
381 Geom::Point p3 = points[3];
382 segment(segmentNr++,
383 p0[X],p0[Y], p1[X],p1[Y], p2[X],p2[Y], p3[X],p3[Y]);
384 nrNodes += 8;
385 }
386 else
387 {
388 err("logical error, because pathv_to_linear_and_cubic_beziers was used");
389 return false;
390 }
392 if (segmentNr < segmentCount)
393 out(",\n");
394 else
395 out("\n");
396 if (segmentNr > segmentCount)
397 {
398 err("Too many segments");
399 return false;
400 }
402 cminmax.expandTo(cit->finalPoint());
404 }
405 }
407 out("}\n");
409 double cminx = cminmax.min()[X];
410 double cmaxx = cminmax.max()[X];
411 double cminy = cminmax.min()[Y];
412 double cmaxy = cminmax.max()[Y];
414 out("#declare %s_MIN_X = %s;\n", id.c_str(), DSTR(cminx));
415 out("#declare %s_CENTER_X = %s;\n", id.c_str(), DSTR((cmaxx+cminx)/2.0));
416 out("#declare %s_MAX_X = %s;\n", id.c_str(), DSTR(cmaxx));
417 out("#declare %s_WIDTH = %s;\n", id.c_str(), DSTR(cmaxx-cminx));
418 out("#declare %s_MIN_Y = %s;\n", id.c_str(), DSTR(cminy));
419 out("#declare %s_CENTER_Y = %s;\n", id.c_str(), DSTR((cmaxy+cminy)/2.0));
420 out("#declare %s_MAX_Y = %s;\n", id.c_str(), DSTR(cmaxy));
421 out("#declare %s_HEIGHT = %s;\n", id.c_str(), DSTR(cmaxy-cminy));
422 if (shapeInfo.color.length()>0)
423 out("#declare %s_COLOR = %s;\n",
424 id.c_str(), shapeInfo.color.c_str());
425 out("/*###################################################\n");
426 out("### end %s\n", id.c_str());
427 out("###################################################*/\n\n\n\n");
429 if (cminx < minx)
430 minx = cminx;
431 if (cmaxx > maxx)
432 maxx = cmaxx;
433 if (cminy < miny)
434 miny = cminy;
435 if (cmaxy > maxy)
436 maxy = cmaxy;
438 return true;
439 }
441 /**
442 * Descend the svg tree recursively, translating data
443 */
444 bool PovOutput::doTreeRecursive(SPDocument *doc, SPObject *obj)
445 {
447 String id;
448 if (!obj->getId())
449 {
450 char buf[16];
451 sprintf(buf, "id%d", idIndex++);
452 id = buf;
453 }
454 else
455 {
456 id = obj->getId();
457 }
459 if (SP_IS_ITEM(obj))
460 {
461 SPItem *item = SP_ITEM(obj);
462 if (!doCurve(item, id))
463 return false;
464 }
466 /**
467 * Descend into children
468 */
469 for (SPObject *child = obj->firstChild() ; child ; child = child->next)
470 {
471 if (!doTreeRecursive(doc, child))
472 return false;
473 }
475 return true;
476 }
478 /**
479 * Output the curve data to buffer
480 */
481 bool PovOutput::doTree(SPDocument *doc)
482 {
483 double bignum = 1000000.0;
484 minx = bignum;
485 maxx = -bignum;
486 miny = bignum;
487 maxy = -bignum;
489 if (!doTreeRecursive(doc, doc->root))
490 return false;
492 //## Let's make a union of all of the Shapes
493 if (povShapes.size()>0)
494 {
495 String id = "AllShapes";
496 char *pfx = (char *)id.c_str();
497 out("/*###################################################\n");
498 out("### UNION OF ALL SHAPES IN DOCUMENT\n");
499 out("###################################################*/\n");
500 out("\n\n");
501 out("/**\n");
502 out(" * Allow the user to redefine the finish{}\n");
503 out(" * by declaring it before #including this file\n");
504 out(" */\n");
505 out("#ifndef (%s_Finish)\n", pfx);
506 out("#declare %s_Finish = finish {\n", pfx);
507 out(" phong 0.5\n");
508 out(" reflection 0.3\n");
509 out(" specular 0.5\n");
510 out("}\n");
511 out("#end\n");
512 out("\n\n");
513 out("#declare %s = union {\n", id.c_str());
514 for (unsigned i = 0 ; i < povShapes.size() ; i++)
515 {
516 out(" object { %s\n", povShapes[i].id.c_str());
517 out(" texture { \n");
518 if (povShapes[i].color.length()>0)
519 out(" pigment { %s }\n", povShapes[i].color.c_str());
520 else
521 out(" pigment { rgb <0,0,0> }\n");
522 out(" finish { %s_Finish }\n", pfx);
523 out(" } \n");
524 out(" } \n");
525 }
526 out("}\n\n\n\n");
529 double zinc = 0.2 / (double)povShapes.size();
530 out("/*#### Same union, but with Z-diffs (actually Y in pov) ####*/\n");
531 out("\n\n");
532 out("/**\n");
533 out(" * Allow the user to redefine the Z-Increment\n");
534 out(" */\n");
535 out("#ifndef (AllShapes_Z_Increment)\n");
536 out("#declare AllShapes_Z_Increment = %s;\n", DSTR(zinc));
537 out("#end\n");
538 out("\n");
539 out("#declare AllShapes_Z_Scale = 1.0;\n");
540 out("\n\n");
541 out("#declare %s_Z = union {\n", pfx);
543 for (unsigned i = 0 ; i < povShapes.size() ; i++)
544 {
545 out(" object { %s\n", povShapes[i].id.c_str());
546 out(" texture { \n");
547 if (povShapes[i].color.length()>0)
548 out(" pigment { %s }\n", povShapes[i].color.c_str());
549 else
550 out(" pigment { rgb <0,0,0> }\n");
551 out(" finish { %s_Finish }\n", pfx);
552 out(" } \n");
553 out(" scale <1, %s_Z_Scale, 1>\n", pfx);
554 out(" } \n");
555 out("#declare %s_Z_Scale = %s_Z_Scale + %s_Z_Increment;\n\n",
556 pfx, pfx, pfx);
557 }
559 out("}\n");
561 out("#declare %s_MIN_X = %s;\n", pfx, DSTR(minx));
562 out("#declare %s_CENTER_X = %s;\n", pfx, DSTR((maxx+minx)/2.0));
563 out("#declare %s_MAX_X = %s;\n", pfx, DSTR(maxx));
564 out("#declare %s_WIDTH = %s;\n", pfx, DSTR(maxx-minx));
565 out("#declare %s_MIN_Y = %s;\n", pfx, DSTR(miny));
566 out("#declare %s_CENTER_Y = %s;\n", pfx, DSTR((maxy+miny)/2.0));
567 out("#declare %s_MAX_Y = %s;\n", pfx, DSTR(maxy));
568 out("#declare %s_HEIGHT = %s;\n", pfx, DSTR(maxy-miny));
569 out("/*##############################################\n");
570 out("### end %s\n", id.c_str());
571 out("##############################################*/\n");
572 out("\n\n");
573 }
575 return true;
576 }
579 //########################################################################
580 //# M A I N O U T P U T
581 //########################################################################
585 /**
586 * Set values back to initial state
587 */
588 void PovOutput::reset()
589 {
590 nrNodes = 0;
591 nrSegments = 0;
592 nrShapes = 0;
593 idIndex = 0;
594 outbuf.clear();
595 povShapes.clear();
596 }
600 /**
601 * Saves the Shapes of an Inkscape SVG file as PovRay spline definitions
602 */
603 void PovOutput::saveDocument(SPDocument *doc, gchar const *filename_utf8)
604 {
605 reset();
607 //###### SAVE IN POV FORMAT TO BUFFER
608 //# Lets do the curves first, to get the stats
609 if (!doTree(doc))
610 {
611 err("Could not output curves for %s", filename_utf8);
612 return;
613 }
615 String curveBuf = outbuf;
616 outbuf.clear();
618 if (!doHeader())
619 {
620 err("Could not write header for %s", filename_utf8);
621 return;
622 }
624 outbuf.append(curveBuf);
626 if (!doTail())
627 {
628 err("Could not write footer for %s", filename_utf8);
629 return;
630 }
635 //###### WRITE TO FILE
636 Inkscape::IO::dump_fopen_call(filename_utf8, "L");
637 FILE *f = Inkscape::IO::fopen_utf8name(filename_utf8, "w");
638 if (!f)
639 return;
641 for (String::iterator iter = outbuf.begin() ; iter!=outbuf.end(); iter++)
642 {
643 int ch = *iter;
644 fputc(ch, f);
645 }
647 fclose(f);
648 }
653 //########################################################################
654 //# EXTENSION API
655 //########################################################################
659 #include "clear-n_.h"
663 /**
664 * API call to save document
665 */
666 void
667 PovOutput::save(Inkscape::Extension::Output */*mod*/,
668 SPDocument *doc, gchar const *filename_utf8)
669 {
670 /* See comments in JavaFSOutput::save re the name `filename_utf8'. */
671 saveDocument(doc, filename_utf8);
672 }
676 /**
677 * Make sure that we are in the database
678 */
679 bool PovOutput::check (Inkscape::Extension::Extension */*module*/)
680 {
681 /* We don't need a Key
682 if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
683 return FALSE;
684 */
686 return true;
687 }
691 /**
692 * This is the definition of PovRay output. This function just
693 * calls the extension system with the memory allocated XML that
694 * describes the data.
695 */
696 void
697 PovOutput::init()
698 {
699 Inkscape::Extension::build_from_mem(
700 "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
701 "<name>" N_("PovRay Output") "</name>\n"
702 "<id>org.inkscape.output.pov</id>\n"
703 "<output>\n"
704 "<extension>.pov</extension>\n"
705 "<mimetype>text/x-povray-script</mimetype>\n"
706 "<filetypename>" N_("PovRay (*.pov) (paths and shapes only)") "</filetypename>\n"
707 "<filetypetooltip>" N_("PovRay Raytracer File") "</filetypetooltip>\n"
708 "</output>\n"
709 "</inkscape-extension>",
710 new PovOutput());
711 }
717 } // namespace Internal
718 } // namespace Extension
719 } // namespace Inkscape
722 /*
723 Local Variables:
724 mode:c++
725 c-file-style:"stroustrup"
726 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
727 indent-tabs-mode:nil
728 fill-column:99
729 End:
730 */
731 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :