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 <ishmalius@gmail.com>
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 "sp-path.h"
26 #include <style.h>
27 #include "display/curve.h"
28 #include "libnr/n-art-bpath.h"
29 #include "extension/system.h"
31 #include "io/sys.h"
33 #include <string>
34 #include <stdio.h>
35 #include <stdarg.h>
38 namespace Inkscape
39 {
40 namespace Extension
41 {
42 namespace Internal
43 {
48 //########################################################################
49 //# U T I L I T Y
50 //########################################################################
54 /**
55 * This function searches the Repr tree recursively from the given node,
56 * and adds refs to all nodes with the given name, to the result vector
57 */
58 static void
59 findElementsByTagName(std::vector<Inkscape::XML::Node *> &results,
60 Inkscape::XML::Node *node,
61 char const *name)
62 {
63 if ( !name || strcmp(node->name(), name) == 0 )
64 results.push_back(node);
66 for (Inkscape::XML::Node *child = node->firstChild() ; child ;
67 child = child->next())
68 findElementsByTagName( results, child, name );
70 }
76 static double
77 effective_opacity(SPItem const *item)
78 {
79 double ret = 1.0;
80 for (SPObject const *obj = item; obj; obj = obj->parent)
81 {
82 SPStyle const *const style = SP_OBJECT_STYLE(obj);
83 g_return_val_if_fail(style, ret);
84 ret *= SP_SCALE24_TO_FLOAT(style->opacity.value);
85 }
86 return ret;
87 }
93 //########################################################################
94 //# OUTPUT FORMATTING
95 //########################################################################
98 /**
99 * We want to control floating output format
100 */
101 static PovOutput::String dstr(double d)
102 {
103 char dbuf[G_ASCII_DTOSTR_BUF_SIZE+1];
104 g_ascii_formatd(dbuf, G_ASCII_DTOSTR_BUF_SIZE,
105 "%.8f", (gdouble)d);
106 PovOutput::String s = dbuf;
107 return s;
108 }
113 /**
114 * Output data to the buffer, printf()-style
115 */
116 void PovOutput::out(char const *fmt, ...)
117 {
118 va_list args;
119 va_start(args, fmt);
120 gchar *output = g_strdup_vprintf(fmt, args);
121 va_end(args);
122 outbuf.append(output);
123 g_free(output);
124 }
130 /**
131 * Output a 2d vector
132 */
133 void PovOutput::vec2(double a, double b)
134 {
135 out("<");
136 out(dstr(a).c_str());
137 out(", ");
138 out(dstr(b).c_str());
139 out(">");
140 }
144 /**
145 * Output a 3d vector
146 */
147 void PovOutput::vec3(double a, double b, double c)
148 {
149 out("<");
150 out(dstr(a).c_str());
151 out(", ");
152 out(dstr(b).c_str());
153 out(", ");
154 out(dstr(c).c_str());
155 out(">");
156 }
160 /**
161 * Output a v4d ector
162 */
163 void PovOutput::vec4(double a, double b, double c, double d)
164 {
165 out("<");
166 out(dstr(a).c_str());
167 out(", ");
168 out(dstr(b).c_str());
169 out(", ");
170 out(dstr(c).c_str());
171 out(", ");
172 out(dstr(d).c_str());
173 out(">");
174 }
178 /**
179 * Output an rgbf color vector
180 */
181 void PovOutput::rgbf(double r, double g, double b, double f)
182 {
183 //"rgbf < %1.3f, %1.3f, %1.3f %1.3f>"
184 out("rgbf ");
185 vec4(r, g, b, f);
186 }
190 /**
191 * Output one bezier's start, start-control, end-control, and end nodes
192 */
193 void PovOutput::segment(int segNr,
194 double startX, double startY,
195 double startCtrlX, double startCtrlY,
196 double endCtrlX, double endCtrlY,
197 double endX, double endY)
198 {
199 //" /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>"
200 out(" /*%4d*/ ", segNr);
201 vec2(startX, startY);
202 out(", ");
203 vec2(startCtrlX, startCtrlY);
204 out(", ");
205 vec2(endCtrlX, endCtrlY);
206 out(", ");
207 vec2(endX, endY);
208 }
214 /**
215 * Output the file header
216 */
217 void PovOutput::doHeader()
218 {
219 time_t tim = time(NULL);
220 out("/*###################################################################\n");
221 out("### This PovRay document was generated by Inkscape\n");
222 out("### http://www.inkscape.org\n");
223 out("### Created: %s", ctime(&tim));
224 out("### Version: %s\n", VERSION);
225 out("#####################################################################\n");
226 out("### NOTES:\n");
227 out("### ============\n");
228 out("### POVRay information can be found at\n");
229 out("### http://www.povray.org\n");
230 out("###\n");
231 out("### The 'AllShapes' objects at the bottom are provided as a\n");
232 out("### preview of how the output would look in a trace. However,\n");
233 out("### the main intent of this file is to provide the individual\n");
234 out("### shapes for inclusion in a POV project.\n");
235 out("###\n");
236 out("### For an example of how to use this file, look at\n");
237 out("### share/examples/istest.pov\n");
238 out("###\n");
239 out("### If you have any problems with this output, please see the\n");
240 out("### Inkscape project at http://www.inkscape.org, or visit\n");
241 out("### the #inkscape channel on irc.freenode.net . \n");
242 out("###\n");
243 out("###################################################################*/\n");
244 out("\n\n");
245 out("/*###################################################################\n");
246 out("## Exports in this file\n");
247 out("##==========================\n");
248 out("## Shapes : %d\n", nrShapes);
249 out("## Segments : %d\n", nrSegments);
250 out("## Nodes : %d\n", nrNodes);
251 out("###################################################################*/\n");
252 out("\n\n\n");
253 }
257 /**
258 * Output the file footer
259 */
260 void PovOutput::doTail()
261 {
262 out("\n\n");
263 out("/*###################################################################\n");
264 out("### E N D F I L E\n");
265 out("###################################################################*/\n");
266 out("\n\n");
267 }
271 /**
272 * Output the curve data to buffer
273 */
274 void PovOutput::doCurves(SPDocument *doc)
275 {
276 std::vector<Inkscape::XML::Node *>results;
277 //findElementsByTagName(results, SP_ACTIVE_DOCUMENT->rroot, "path");
278 findElementsByTagName(results, SP_ACTIVE_DOCUMENT->rroot, NULL);
279 if (results.size() == 0)
280 return;
282 double bignum = 1000000.0;
283 double minx = bignum;
284 double maxx = -bignum;
285 double miny = bignum;
286 double maxy = -bignum;
288 for (unsigned int indx = 0; indx < results.size() ; indx++)
289 {
290 //### Fetch the object from the repr info
291 Inkscape::XML::Node *rpath = results[indx];
292 char *str = (char *) rpath->attribute("id");
293 if (!str)
294 continue;
296 String id = str;
297 SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(rpath);
298 if (!reprobj)
299 continue;
301 //### Get the transform of the item
302 if (!SP_IS_ITEM(reprobj))
303 continue;
305 SPItem *item = SP_ITEM(reprobj);
306 NR::Matrix tf = sp_item_i2d_affine(item);
308 //### Get the Shape
309 if (!SP_IS_SHAPE(reprobj))//Bulia's suggestion. Allow all shapes
310 continue;
312 SPShape *shape = SP_SHAPE(reprobj);
313 SPCurve *curve = shape->curve;
314 if (sp_curve_empty(curve))
315 continue;
317 nrShapes++;
319 PovShapeInfo shapeInfo;
320 shapeInfo.id = id;
321 shapeInfo.color = "";
323 //Try to get the fill color of the shape
324 SPStyle *style = SP_OBJECT_STYLE(shape);
325 /* fixme: Handle other fill types, even if this means translating gradients to a single
326 flat colour. */
327 if (style && (style->fill.isColor()))
328 {
329 // see color.h for how to parse SPColor
330 float rgb[3];
331 sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
332 double const dopacity = ( SP_SCALE24_TO_FLOAT(style->fill_opacity.value)
333 * effective_opacity(shape) );
334 //gchar *str = g_strdup_printf("rgbf < %1.3f, %1.3f, %1.3f %1.3f>",
335 // rgb[0], rgb[1], rgb[2], 1.0 - dopacity);
336 String rgbf = "rgbf <";
337 rgbf.append(dstr(rgb[0])); rgbf.append(", ");
338 rgbf.append(dstr(rgb[1])); rgbf.append(", ");
339 rgbf.append(dstr(rgb[2])); rgbf.append(", ");
340 rgbf.append(dstr(1.0 - dopacity)); rgbf.append(">");
341 shapeInfo.color += rgbf;
342 }
344 povShapes.push_back(shapeInfo); //passed all tests. save the info
346 int curveLength = SP_CURVE_LENGTH(curve);
348 //Count the NR_CURVETOs/LINETOs
349 int segmentCount=0;
350 NArtBpath *bp = SP_CURVE_BPATH(curve);
351 for (int curveNr=0 ; curveNr<curveLength ; curveNr++, bp++)
352 if (bp->code == NR_CURVETO || bp->code == NR_LINETO)
353 segmentCount++;
355 double cminx = bignum;
356 double cmaxx = -bignum;
357 double cminy = bignum;
358 double cmaxy = -bignum;
359 double lastx = 0.0;
360 double lasty = 0.0;
362 out("/*###################################################\n");
363 out("### PRISM: %s\n", id.c_str());
364 out("###################################################*/\n");
365 out("#declare %s = prism {\n", id.c_str());
366 out(" linear_sweep\n");
367 out(" bezier_spline\n");
368 out(" 1.0, //top\n");
369 out(" 0.0, //bottom\n");
370 out(" %d //nr points\n", segmentCount * 4);
371 int segmentNr = 0;
372 bp = SP_CURVE_BPATH(curve);
374 nrSegments += curveLength;
376 for (int curveNr=0 ; curveNr < curveLength ; curveNr++)
377 {
378 using NR::X;
379 using NR::Y;
380 //transform points. note overloaded '*'
381 NR::Point const p1(bp->c(1) * tf);
382 NR::Point const p2(bp->c(2) * tf);
383 NR::Point const p3(bp->c(3) * tf);
384 double const x1 = p1[X], y1 = p1[Y];
385 double const x2 = p2[X], y2 = p2[Y];
386 double const x3 = p3[X], y3 = p3[Y];
388 switch (bp->code)
389 {
390 case NR_MOVETO:
391 case NR_MOVETO_OPEN:
392 {
393 //fprintf(f, "moveto: %f %f\n", bp->x3, bp->y3);
394 break;
395 }
396 case NR_CURVETO:
397 {
398 //fprintf(f, " /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>",
399 // segmentNr++, lastx, lasty, x1, y1, x2, y2, x3, y3);
400 segment(segmentNr++,
401 lastx, lasty, x1, y1, x2, y2, x3, y3);
402 nrNodes += 8;
404 if (segmentNr < segmentCount)
405 out(",\n");
406 else
407 out("\n");
409 if (lastx < cminx)
410 cminx = lastx;
411 if (lastx > cmaxx)
412 cmaxx = lastx;
413 if (lasty < cminy)
414 cminy = lasty;
415 if (lasty > cmaxy)
416 cmaxy = lasty;
417 break;
418 }
419 case NR_LINETO:
420 {
421 //NOTE: we need to carefully handle line->curve and curve->line
422 // transitions.
423 //fprintf(f, " /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>",
424 // segmentNr++, lastx, lasty, lastx, lasty, x3, y3, x3, y3);
425 segment(segmentNr++,
426 lastx, lasty, lastx, lasty, x3, y3, x3, y3);
427 nrNodes += 8;
429 if (segmentNr < segmentCount)
430 out(",\n");
431 else
432 out("\n");
434 //fprintf(f, "lineto\n");
435 if (lastx < cminx)
436 cminx = lastx;
437 if (lastx > cmaxx)
438 cmaxx = lastx;
439 if (lasty < cminy)
440 cminy = lasty;
441 if (lasty > cmaxy)
442 cmaxy = lasty;
443 break;
444 }
445 case NR_END:
446 {
447 //fprintf(f, "end\n");
448 break;
449 }
450 }
451 lastx = x3;
452 lasty = y3;
453 bp++;
454 }
455 out("}\n");
458 //# prefix for following declarations
459 char *pfx = (char *)id.c_str();
461 out("#declare %s_MIN_X = %s;\n", pfx, dstr(cminx).c_str());
462 out("#declare %s_CENTER_X = %s;\n", pfx, dstr((cmaxx+cminx)/2.0).c_str());
463 out("#declare %s_MAX_X = %s;\n", pfx, dstr(cmaxx).c_str());
464 out("#declare %s_WIDTH = %s;\n", pfx, dstr(cmaxx-cminx).c_str());
465 out("#declare %s_MIN_Y = %s;\n", pfx, dstr(cminy).c_str());
466 out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((cmaxy+cminy)/2.0).c_str());
467 out("#declare %s_MAX_Y = %s;\n", pfx, dstr(cmaxy).c_str());
468 out("#declare %s_HEIGHT = %s;\n", pfx, dstr(cmaxy-cminy).c_str());
469 if (shapeInfo.color.length()>0)
470 out("#declare %s_COLOR = %s;\n",
471 pfx, shapeInfo.color.c_str());
472 out("/*###################################################\n");
473 out("### end %s\n", id.c_str());
474 out("###################################################*/\n\n\n\n");
475 if (cminx < minx)
476 minx = cminx;
477 if (cmaxx > maxx)
478 maxx = cmaxx;
479 if (cminy < miny)
480 miny = cminy;
481 if (cmaxy > maxy)
482 maxy = cmaxy;
484 }//for
488 //## Let's make a union of all of the Shapes
489 if (povShapes.size()>0)
490 {
491 String id = "AllShapes";
492 char *pfx = (char *)id.c_str();
493 out("/*###################################################\n");
494 out("### UNION OF ALL SHAPES IN DOCUMENT\n");
495 out("###################################################*/\n");
496 out("\n\n");
497 out("/**\n");
498 out(" * Allow the user to redefine the finish{}\n");
499 out(" * by declaring it before #including this file\n");
500 out(" */\n");
501 out("#ifndef (%s_Finish)\n", pfx);
502 out("#declare %s_Finish = finish {\n", pfx);
503 out(" phong 0.5\n");
504 out(" reflection 0.3\n");
505 out(" specular 0.5\n");
506 out("}\n");
507 out("#end\n");
508 out("\n\n");
509 out("#declare %s = union {\n", id.c_str());
510 for (unsigned i = 0 ; i < povShapes.size() ; i++)
511 {
512 out(" object { %s\n", povShapes[i].id.c_str());
513 out(" texture { \n");
514 if (povShapes[i].color.length()>0)
515 out(" pigment { %s }\n", povShapes[i].color.c_str());
516 else
517 out(" pigment { rgb <0,0,0> }\n");
518 out(" finish { %s_Finish }\n", pfx);
519 out(" } \n");
520 out(" } \n");
521 }
522 out("}\n\n\n\n");
525 double zinc = 0.2 / (double)povShapes.size();
526 out("/*#### Same union, but with Z-diffs (actually Y in pov) ####*/\n");
527 out("\n\n");
528 out("/**\n");
529 out(" * Allow the user to redefine the Z-Increment\n");
530 out(" */\n");
531 out("#ifndef (AllShapes_Z_Increment)\n");
532 out("#declare AllShapes_Z_Increment = %s;\n", dstr(zinc).c_str());
533 out("#end\n");
534 out("\n");
535 out("#declare AllShapes_Z_Scale = 1.0;\n");
536 out("\n\n");
537 out("#declare %s_Z = union {\n", pfx);
539 for (unsigned i = 0 ; i < povShapes.size() ; i++)
540 {
541 out(" object { %s\n", povShapes[i].id.c_str());
542 out(" texture { \n");
543 if (povShapes[i].color.length()>0)
544 out(" pigment { %s }\n", povShapes[i].color.c_str());
545 else
546 out(" pigment { rgb <0,0,0> }\n");
547 out(" finish { %s_Finish }\n", pfx);
548 out(" } \n");
549 out(" scale <1, %s_Z_Scale, 1>\n", pfx);
550 out(" } \n");
551 out("#declare %s_Z_Scale = %s_Z_Scale + %s_Z_Increment;\n\n",
552 pfx, pfx, pfx);
553 }
555 out("}\n");
557 out("#declare %s_MIN_X = %s;\n", pfx, dstr(minx).c_str());
558 out("#declare %s_CENTER_X = %s;\n", pfx, dstr((maxx+minx)/2.0).c_str());
559 out("#declare %s_MAX_X = %s;\n", pfx, dstr(maxx).c_str());
560 out("#declare %s_WIDTH = %s;\n", pfx, dstr(maxx-minx).c_str());
561 out("#declare %s_MIN_Y = %s;\n", pfx, dstr(miny).c_str());
562 out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((maxy+miny)/2.0).c_str());
563 out("#declare %s_MAX_Y = %s;\n", pfx, dstr(maxy).c_str());
564 out("#declare %s_HEIGHT = %s;\n", pfx, dstr(maxy-miny).c_str());
565 out("/*##############################################\n");
566 out("### end %s\n", id.c_str());
567 out("##############################################*/\n");
568 out("\n\n");
569 }
571 }
576 //########################################################################
577 //# M A I N O U T P U T
578 //########################################################################
582 /**
583 * Set values back to initial state
584 */
585 void PovOutput::reset()
586 {
587 nrNodes = 0;
588 nrSegments = 0;
589 nrShapes = 0;
590 outbuf.clear();
591 povShapes.clear();
592 }
596 /**
597 * Saves the <paths> of an Inkscape SVG file as PovRay spline definitions
598 */
599 void PovOutput::saveDocument(SPDocument *doc, gchar const *uri)
600 {
601 reset();
603 //###### SAVE IN POV FORMAT TO BUFFER
604 //# Lets do the curves first, to get the stats
605 doCurves(doc);
606 String curveBuf = outbuf;
607 outbuf.clear();
609 doHeader();
611 outbuf.append(curveBuf);
613 doTail();
618 //###### WRITE TO FILE
619 Inkscape::IO::dump_fopen_call(uri, "L");
620 FILE *f = Inkscape::IO::fopen_utf8name(uri, "w");
621 if (!f)
622 return;
624 for (String::iterator iter = outbuf.begin() ; iter!=outbuf.end(); iter++)
625 {
626 int ch = *iter;
627 fputc(ch, f);
628 }
630 fclose(f);
631 }
636 //########################################################################
637 //# EXTENSION API
638 //########################################################################
642 #include "clear-n_.h"
646 /**
647 * API call to save document
648 */
649 void
650 PovOutput::save(Inkscape::Extension::Output *mod,
651 SPDocument *doc, gchar const *uri)
652 {
653 saveDocument(doc, uri);
654 }
658 /**
659 * Make sure that we are in the database
660 */
661 bool PovOutput::check (Inkscape::Extension::Extension *module)
662 {
663 /* We don't need a Key
664 if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
665 return FALSE;
666 */
668 return true;
669 }
673 /**
674 * This is the definition of PovRay output. This function just
675 * calls the extension system with the memory allocated XML that
676 * describes the data.
677 */
678 void
679 PovOutput::init()
680 {
681 Inkscape::Extension::build_from_mem(
682 "<inkscape-extension xmlns=\"" INKSCAPE_EXTENSION_URI "\">\n"
683 "<name>" N_("PovRay Output") "</name>\n"
684 "<id>org.inkscape.output.pov</id>\n"
685 "<output>\n"
686 "<extension>.pov</extension>\n"
687 "<mimetype>text/x-povray-script</mimetype>\n"
688 "<filetypename>" N_("PovRay (*.pov) (export splines)") "</filetypename>\n"
689 "<filetypetooltip>" N_("PovRay Raytracer File") "</filetypetooltip>\n"
690 "</output>\n"
691 "</inkscape-extension>",
692 new PovOutput());
693 }
699 } // namespace Internal
700 } // namespace Extension
701 } // namespace Inkscape
704 /*
705 Local Variables:
706 mode:c++
707 c-file-style:"stroustrup"
708 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
709 indent-tabs-mode:nil
710 fill-column:99
711 End:
712 */
713 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :