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-2007 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 //########################################################################
97 static const char *formatDouble(gchar *sbuffer, double d)
98 {
99 return (const char *)g_ascii_formatd(sbuffer,
100 G_ASCII_DTOSTR_BUF_SIZE, "%.8g", (gdouble)d);
102 }
105 /**
106 * Not-threadsafe version
107 */
108 static char _dstr_buf[G_ASCII_DTOSTR_BUF_SIZE+1];
110 static const char *dstr(double d)
111 {
112 return formatDouble(_dstr_buf, d);
113 }
120 /**
121 * Output data to the buffer, printf()-style
122 */
123 void PovOutput::out(char *fmt, ...)
124 {
125 va_list args;
126 va_start(args, fmt);
127 g_vsnprintf(fmtbuf, 4096, fmt, args);
128 va_end(args);
129 outbuf.append(fmtbuf);
130 }
138 /**
139 * Output a 3d vector
140 */
141 void PovOutput::vec2(double a, double b)
142 {
143 outbuf.append("<");
144 outbuf.append(dstr(a));
145 outbuf.append(", ");
146 outbuf.append(dstr(b));
147 outbuf.append(">");
148 }
152 /**
153 * Output a 3d vector
154 */
155 void PovOutput::vec3(double a, double b, double c)
156 {
157 outbuf.append("<");
158 outbuf.append(dstr(a));
159 outbuf.append(", ");
160 outbuf.append(dstr(b));
161 outbuf.append(", ");
162 outbuf.append(dstr(c));
163 outbuf.append(">");
164 }
168 /**
169 * Output a v4d ector
170 */
171 void PovOutput::vec4(double a, double b, double c, double d)
172 {
173 outbuf.append("<");
174 outbuf.append(dstr(a));
175 outbuf.append(", ");
176 outbuf.append(dstr(b));
177 outbuf.append(", ");
178 outbuf.append(dstr(c));
179 outbuf.append(", ");
180 outbuf.append(dstr(d));
181 outbuf.append(">");
182 }
185 /**
186 * Output an rgbf color vector
187 */
188 void PovOutput::rgbf(double r, double g, double b, double f)
189 {
190 //"rgbf < %1.3f, %1.3f, %1.3f %1.3f>"
191 outbuf.append("rgbf ");
192 vec4(r, g, b, f);
193 }
197 /**
198 * Output one bezier's start, start-control, end-control, and end nodes
199 */
200 void PovOutput::segment(int segNr, double a0, double a1,
201 double b0, double b1,
202 double c0, double c1,
203 double d0, double d1)
204 {
205 //" /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>"
206 char buf[32];
207 snprintf(buf, 31, " /*%4d*/ ", segNr);
208 outbuf.append(buf);
209 vec2(a0, a1);
210 outbuf.append(", ");
211 vec2(b0, b1);
212 outbuf.append(", ");
213 vec2(c0, c1);
214 outbuf.append(", ");
215 vec2(d0, d1);
216 }
222 /**
223 * Output the file header
224 */
225 void PovOutput::doHeader()
226 {
227 time_t tim = time(NULL);
228 out("/*###################################################################\n");
229 out("### This PovRay document was generated by Inkscape\n");
230 out("### http://www.inkscape.org\n");
231 out("### Created: %s", ctime(&tim));
232 out("### Version: %s\n", VERSION);
233 out("#####################################################################\n");
234 out("### NOTES:\n");
235 out("### ============\n");
236 out("### POVRay information can be found at\n");
237 out("### http://www.povray.org\n");
238 out("###\n");
239 out("### The 'AllShapes' objects at the bottom are provided as a\n");
240 out("### preview of how the output would look in a trace. However,\n");
241 out("### the main intent of this file is to provide the individual\n");
242 out("### shapes for inclusion in a POV project.\n");
243 out("###\n");
244 out("### For an example of how to use this file, look at\n");
245 out("### share/examples/istest.pov\n");
246 out("###################################################################*/\n");
247 out("\n\n");
248 out("/*###################################################################\n");
249 out("## Exports in this file\n");
250 out("##==========================\n");
251 out("## Shapes : %d\n", nrShapes);
252 out("## Segments : %d\n", nrSegments);
253 out("## Nodes : %d\n", nrNodes);
254 out("###################################################################*/\n");
255 out("\n\n\n");
256 }
260 /**
261 * Output the file footer
262 */
263 void PovOutput::doTail()
264 {
265 out("\n\n");
266 out("/*###################################################################\n");
267 out("### E N D F I L E\n");
268 out("###################################################################*/\n");
269 out("\n\n");
270 }
274 /**
275 * Output the curve data to buffer
276 */
277 void PovOutput::doCurves(SPDocument *doc)
278 {
279 std::vector<Inkscape::XML::Node *>results;
280 //findElementsByTagName(results, SP_ACTIVE_DOCUMENT->rroot, "path");
281 findElementsByTagName(results, SP_ACTIVE_DOCUMENT->rroot, NULL);
282 if (results.size() == 0)
283 return;
285 double bignum = 1000000.0;
286 double minx = bignum;
287 double maxx = -bignum;
288 double miny = bignum;
289 double maxy = -bignum;
291 for (unsigned int indx = 0; indx < results.size() ; indx++)
292 {
293 //### Fetch the object from the repr info
294 Inkscape::XML::Node *rpath = results[indx];
295 char *str = (char *) rpath->attribute("id");
296 if (!str)
297 continue;
299 String id = str;
300 SPObject *reprobj = SP_ACTIVE_DOCUMENT->getObjectByRepr(rpath);
301 if (!reprobj)
302 continue;
304 //### Get the transform of the item
305 if (!SP_IS_ITEM(reprobj))
306 continue;
308 SPItem *item = SP_ITEM(reprobj);
309 NR::Matrix tf = sp_item_i2d_affine(item);
311 //### Get the Shape
312 if (!SP_IS_SHAPE(reprobj))//Bulia's suggestion. Allow all shapes
313 continue;
315 SPShape *shape = SP_SHAPE(reprobj);
316 SPCurve *curve = shape->curve;
317 if (sp_curve_empty(curve))
318 continue;
320 nrShapes++;
322 PovShapeInfo shapeInfo;
323 shapeInfo.id = id;
324 shapeInfo.color = "";
326 //Try to get the fill color of the shape
327 SPStyle *style = SP_OBJECT_STYLE(shape);
328 /* fixme: Handle other fill types, even if this means translating gradients to a single
329 flat colour. */
330 if (style && (style->fill.type == SP_PAINT_TYPE_COLOR))
331 {
332 // see color.h for how to parse SPColor
333 float rgb[3];
334 sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
335 double const dopacity = ( SP_SCALE24_TO_FLOAT(style->fill_opacity.value)
336 * effective_opacity(shape) );
337 //gchar *str = g_strdup_printf("rgbf < %1.3f, %1.3f, %1.3f %1.3f>",
338 // rgb[0], rgb[1], rgb[2], 1.0 - dopacity);
339 String rgbf = "rgbf <";
340 rgbf.append(dstr(rgb[0])); rgbf.append(", ");
341 rgbf.append(dstr(rgb[1])); rgbf.append(", ");
342 rgbf.append(dstr(rgb[2])); rgbf.append(", ");
343 rgbf.append(dstr(1.0 - dopacity)); rgbf.append(">");
344 shapeInfo.color += rgbf;
345 }
347 povShapes.push_back(shapeInfo); //passed all tests. save the info
349 int curveLength = SP_CURVE_LENGTH(curve);
351 //Count the NR_CURVETOs/LINETOs
352 int segmentCount=0;
353 NArtBpath *bp = SP_CURVE_BPATH(curve);
354 for (int curveNr=0 ; curveNr<curveLength ; curveNr++, bp++)
355 if (bp->code == NR_CURVETO || bp->code == NR_LINETO)
356 segmentCount++;
358 double cminx = bignum;
359 double cmaxx = -bignum;
360 double cminy = bignum;
361 double cmaxy = -bignum;
362 double lastx = 0.0;
363 double lasty = 0.0;
365 out("/*###################################################\n");
366 out("### PRISM: %s\n", id.c_str());
367 out("###################################################*/\n");
368 out("#declare %s = prism {\n", id.c_str());
369 out(" linear_sweep\n");
370 out(" bezier_spline\n");
371 out(" 1.0, //top\n");
372 out(" 0.0, //bottom\n");
373 out(" %d //nr points\n", segmentCount * 4);
374 int segmentNr = 0;
375 bp = SP_CURVE_BPATH(curve);
377 nrSegments += curveLength;
379 for (int curveNr=0 ; curveNr < curveLength ; curveNr++)
380 {
381 using NR::X;
382 using NR::Y;
383 NR::Point const p1(bp->c(1) * tf);
384 NR::Point const p2(bp->c(2) * tf);
385 NR::Point const p3(bp->c(3) * tf);
386 double const x1 = p1[X], y1 = p1[Y];
387 double const x2 = p2[X], y2 = p2[Y];
388 double const x3 = p3[X], y3 = p3[Y];
390 switch (bp->code)
391 {
392 case NR_MOVETO:
393 case NR_MOVETO_OPEN:
394 {
395 //fprintf(f, "moveto: %f %f\n", bp->x3, bp->y3);
396 break;
397 }
398 case NR_CURVETO:
399 {
400 //fprintf(f, " /*%4d*/ <%f, %f>, <%f, %f>, <%f,%f>, <%f,%f>",
401 // segmentNr++, lastx, lasty, x1, y1, x2, y2, x3, y3);
402 segment(segmentNr++,
403 lastx, lasty, x1, y1, x2, y2, x3, y3);
404 nrNodes += 8;
406 if (segmentNr < segmentCount)
407 out(",\n");
408 else
409 out("\n");
411 if (lastx < cminx)
412 cminx = lastx;
413 if (lastx > cmaxx)
414 cmaxx = lastx;
415 if (lasty < cminy)
416 cminy = lasty;
417 if (lasty > cmaxy)
418 cmaxy = lasty;
419 break;
420 }
421 case NR_LINETO:
422 {
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 char *pfx = (char *)id.c_str();
460 out("#declare %s_MIN_X = %s;\n", pfx, dstr(cminx));
461 out("#declare %s_CENTER_X = %s;\n", pfx, dstr((cmaxx+cminx)/2.0));
462 out("#declare %s_MAX_X = %s;\n", pfx, dstr(cmaxx));
463 out("#declare %s_WIDTH = %s;\n", pfx, dstr(cmaxx-cminx));
464 out("#declare %s_MIN_Y = %s;\n", pfx, dstr(cminy));
465 out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((cmaxy+cminy)/2.0));
466 out("#declare %s_MAX_Y = %s;\n", pfx, dstr(cmaxy));
467 out("#declare %s_HEIGHT = %s;\n", pfx, dstr(cmaxy-cminy));
468 if (shapeInfo.color.length()>0)
469 out("#declare %s_COLOR = %s;\n",
470 pfx, shapeInfo.color.c_str());
471 out("/*###################################################\n");
472 out("### end %s\n", id.c_str());
473 out("###################################################*/\n\n\n\n");
474 if (cminx < minx)
475 minx = cminx;
476 if (cmaxx > maxx)
477 maxx = cmaxx;
478 if (cminy < miny)
479 miny = cminy;
480 if (cmaxy > maxy)
481 maxy = cmaxy;
483 }//for
487 //## Let's make a union of all of the Shapes
488 if (povShapes.size()>0)
489 {
490 String id = "AllShapes";
491 char *pfx = (char *)id.c_str();
492 out("/*###################################################\n");
493 out("### UNION OF ALL SHAPES IN DOCUMENT\n");
494 out("###################################################*/\n");
495 out("\n\n");
496 out("/**\n");
497 out(" * Allow the user to redefine the finish{}\n");
498 out(" * by declaring it before #including this file\n");
499 out(" */\n");
500 out("#ifndef (%s_Finish)\n", pfx);
501 out("#declare %s_Finish = finish {\n", pfx);
502 out(" phong 0.5\n");
503 out(" reflection 0.3\n");
504 out(" specular 0.5\n");
505 out("}\n");
506 out("#end\n");
507 out("\n\n");
508 out("#declare %s = union {\n", id.c_str());
509 for (unsigned i = 0 ; i < povShapes.size() ; i++)
510 {
511 out(" object { %s\n", povShapes[i].id.c_str());
512 out(" texture { \n");
513 if (povShapes[i].color.length()>0)
514 out(" pigment { %s }\n", povShapes[i].color.c_str());
515 else
516 out(" pigment { rgb <0,0,0> }\n");
517 out(" finish { %s_Finish }\n", pfx);
518 out(" } \n");
519 out(" } \n");
520 }
521 out("}\n\n\n\n");
524 double zinc = 0.2 / (double)povShapes.size();
525 out("/*#### Same union, but with Z-diffs (actually Y in pov) ####*/\n");
526 out("\n\n");
527 out("/**\n");
528 out(" * Allow the user to redefine the Z-Increment\n");
529 out(" */\n");
530 out("#ifndef (AllShapes_Z_Increment)\n");
531 out("#declare AllShapes_Z_Increment = %s;\n", dstr(zinc));
532 out("#end\n");
533 out("\n");
534 out("#declare AllShapes_Z_Scale = 1.0;\n");
535 out("\n\n");
536 out("#declare %s_Z = union {\n", pfx);
538 for (unsigned i = 0 ; i < povShapes.size() ; i++)
539 {
540 out(" object { %s\n", povShapes[i].id.c_str());
541 out(" texture { \n");
542 if (povShapes[i].color.length()>0)
543 out(" pigment { %s }\n", povShapes[i].color.c_str());
544 else
545 out(" pigment { rgb <0,0,0> }\n");
546 out(" finish { %s_Finish }\n", pfx);
547 out(" } \n");
548 out(" scale <1, %s_Z_Scale, 1>\n", pfx);
549 out(" } \n");
550 out("#declare %s_Z_Scale = %s_Z_Scale + %s_Z_Increment;\n\n",
551 pfx, pfx, pfx);
552 }
554 out("}\n");
556 out("#declare %s_MIN_X = %s;\n", pfx, dstr(minx));
557 out("#declare %s_CENTER_X = %s;\n", pfx, dstr((maxx+minx)/2.0));
558 out("#declare %s_MAX_X = %s;\n", pfx, dstr(maxx));
559 out("#declare %s_WIDTH = %s;\n", pfx, dstr(maxx-minx));
560 out("#declare %s_MIN_Y = %s;\n", pfx, dstr(miny));
561 out("#declare %s_CENTER_Y = %s;\n", pfx, dstr((maxy+miny)/2.0));
562 out("#declare %s_MAX_Y = %s;\n", pfx, dstr(maxy));
563 out("#declare %s_HEIGHT = %s;\n", pfx, dstr(maxy-miny));
564 out("/*##############################################\n");
565 out("### end %s\n", id.c_str());
566 out("##############################################*/\n");
567 out("\n\n");
568 }
570 }
575 //########################################################################
576 //# M A I N O U T P U T
577 //########################################################################
581 /**
582 * Set values back to initial state
583 */
584 void PovOutput::reset()
585 {
586 nrNodes = 0;
587 nrSegments = 0;
588 nrShapes = 0;
589 outbuf.clear();
590 povShapes.clear();
591 }
595 /**
596 * Saves the <paths> of an Inkscape SVG file as PovRay spline definitions
597 */
598 void PovOutput::saveDocument(SPDocument *doc, gchar const *uri)
599 {
600 reset();
602 //###### SAVE IN POV FORMAT TO BUFFER
603 //# Lets do the curves first, to get the stats
604 doCurves(doc);
605 String curveBuf = outbuf;
606 outbuf.clear();
608 doHeader();
610 outbuf.append(curveBuf);
612 doTail();
617 //###### WRITE TO FILE
618 Inkscape::IO::dump_fopen_call(uri, "L");
619 FILE *f = Inkscape::IO::fopen_utf8name(uri, "w");
620 if (!f)
621 return;
623 for (String::iterator iter = outbuf.begin() ; iter!=outbuf.end(); iter++)
624 {
625 int ch = *iter;
626 fputc(ch, f);
627 }
629 fclose(f);
630 }
635 //########################################################################
636 //# EXTENSION API
637 //########################################################################
641 #include "clear-n_.h"
645 /**
646 * API call to save document
647 */
648 void
649 PovOutput::save(Inkscape::Extension::Output *mod,
650 SPDocument *doc, gchar const *uri)
651 {
652 saveDocument(doc, uri);
653 }
657 /**
658 * Make sure that we are in the database
659 */
660 bool PovOutput::check (Inkscape::Extension::Extension *module)
661 {
662 /* We don't need a Key
663 if (NULL == Inkscape::Extension::db.get(SP_MODULE_KEY_OUTPUT_POV))
664 return FALSE;
665 */
667 return true;
668 }
672 /**
673 * This is the definition of PovRay output. This function just
674 * calls the extension system with the memory allocated XML that
675 * describes the data.
676 */
677 void
678 PovOutput::init()
679 {
680 Inkscape::Extension::build_from_mem(
681 "<inkscape-extension>\n"
682 "<name>" N_("PovRay Output") "</name>\n"
683 "<id>org.inkscape.output.pov</id>\n"
684 "<output>\n"
685 "<extension>.pov</extension>\n"
686 "<mimetype>text/x-povray-script</mimetype>\n"
687 "<filetypename>" N_("PovRay (*.pov) (export splines)") "</filetypename>\n"
688 "<filetypetooltip>" N_("PovRay Raytracer File") "</filetypetooltip>\n"
689 "</output>\n"
690 "</inkscape-extension>",
691 new PovOutput());
692 }
698 } // namespace Internal
699 } // namespace Extension
700 } // namespace Inkscape
703 /*
704 Local Variables:
705 mode:c++
706 c-file-style:"stroustrup"
707 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
708 indent-tabs-mode:nil
709 fill-column:99
710 End:
711 */
712 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :