1 #define __SP_SPIRAL_C__
3 /** \file
4 * <sodipodi:spiral> implementation
5 */
6 /*
7 * Authors:
8 * Mitsuru Oka <oka326@parkcity.ne.jp>
9 * Lauris Kaplinski <lauris@kaplinski.com>
10 *
11 * Copyright (C) 1999-2002 Lauris Kaplinski
12 * Copyright (C) 2000-2001 Ximian, Inc.
13 *
14 * Released under GNU GPL, read the file 'COPYING' for more information
15 */
17 #include "config.h"
20 #include "svg/svg.h"
21 #include "attributes.h"
22 #include "display/bezier-utils.h"
23 #include "display/curve.h"
24 #include <glibmm/i18n.h>
25 #include "xml/repr.h"
27 #include "sp-spiral.h"
29 static void sp_spiral_class_init (SPSpiralClass *klass);
30 static void sp_spiral_init (SPSpiral *spiral);
32 static void sp_spiral_build (SPObject * object, SPDocument * document, Inkscape::XML::Node * repr);
33 static Inkscape::XML::Node *sp_spiral_write (SPObject *object, Inkscape::XML::Node *repr, guint flags);
34 static void sp_spiral_set (SPObject *object, unsigned int key, const gchar *value);
35 static void sp_spiral_update (SPObject *object, SPCtx *ctx, guint flags);
37 static gchar * sp_spiral_description (SPItem * item);
38 static void sp_spiral_snappoints(SPItem const *item, SnapPointsIter p);
39 static void sp_spiral_set_shape (SPShape *shape);
41 static NR::Point sp_spiral_get_tangent (SPSpiral const *spiral, gdouble t);
43 static SPShapeClass *parent_class;
45 /**
46 * Register SPSpiral class and return its type number.
47 */
48 GType
49 sp_spiral_get_type (void)
50 {
51 static GType spiral_type = 0;
53 if (!spiral_type) {
54 GTypeInfo spiral_info = {
55 sizeof (SPSpiralClass),
56 NULL, /* base_init */
57 NULL, /* base_finalize */
58 (GClassInitFunc) sp_spiral_class_init,
59 NULL, /* class_finalize */
60 NULL, /* class_data */
61 sizeof (SPSpiral),
62 16, /* n_preallocs */
63 (GInstanceInitFunc) sp_spiral_init,
64 NULL, /* value_table */
65 };
66 spiral_type = g_type_register_static (SP_TYPE_SHAPE, "SPSpiral", &spiral_info, (GTypeFlags)0);
67 }
68 return spiral_type;
69 }
71 /**
72 * SPSpiral vtable initialization.
73 */
74 static void
75 sp_spiral_class_init (SPSpiralClass *klass)
76 {
77 GObjectClass * gobject_class;
78 SPObjectClass * sp_object_class;
79 SPItemClass * item_class;
80 SPShapeClass *shape_class;
82 gobject_class = (GObjectClass *) klass;
83 sp_object_class = (SPObjectClass *) klass;
84 item_class = (SPItemClass *) klass;
85 shape_class = (SPShapeClass *) klass;
87 parent_class = (SPShapeClass *)g_type_class_ref (SP_TYPE_SHAPE);
89 sp_object_class->build = sp_spiral_build;
90 sp_object_class->write = sp_spiral_write;
91 sp_object_class->set = sp_spiral_set;
92 sp_object_class->update = sp_spiral_update;
94 item_class->description = sp_spiral_description;
95 item_class->snappoints = sp_spiral_snappoints;
97 shape_class->set_shape = sp_spiral_set_shape;
98 }
100 /**
101 * Callback for SPSpiral object initialization.
102 */
103 static void
104 sp_spiral_init (SPSpiral * spiral)
105 {
106 spiral->cx = 0.0;
107 spiral->cy = 0.0;
108 spiral->exp = 1.0;
109 spiral->revo = 3.0;
110 spiral->rad = 1.0;
111 spiral->arg = 0.0;
112 spiral->t0 = 0.0;
113 }
115 /**
116 * Virtual build: set spiral properties from corresponding repr.
117 */
118 static void
119 sp_spiral_build (SPObject * object, SPDocument * document, Inkscape::XML::Node * repr)
120 {
121 if (((SPObjectClass *) parent_class)->build)
122 ((SPObjectClass *) parent_class)->build (object, document, repr);
124 sp_object_read_attr (object, "sodipodi:cx");
125 sp_object_read_attr (object, "sodipodi:cy");
126 sp_object_read_attr (object, "sodipodi:expansion");
127 sp_object_read_attr (object, "sodipodi:revolution");
128 sp_object_read_attr (object, "sodipodi:radius");
129 sp_object_read_attr (object, "sodipodi:argument");
130 sp_object_read_attr (object, "sodipodi:t0");
131 }
133 /**
134 * Virtual write: write spiral attributes to corresponding repr.
135 */
136 static Inkscape::XML::Node *
137 sp_spiral_write (SPObject *object, Inkscape::XML::Node *repr, guint flags)
138 {
139 SPSpiral *spiral = SP_SPIRAL (object);
141 if ((flags & SP_OBJECT_WRITE_BUILD) && !repr) {
142 repr = sp_repr_new ("svg:path");
143 }
145 if (flags & SP_OBJECT_WRITE_EXT) {
146 /* Fixme: we may replace these attributes by
147 * sodipodi:spiral="cx cy exp revo rad arg t0"
148 */
149 repr->setAttribute("sodipodi:type", "spiral");
150 sp_repr_set_svg_double(repr, "sodipodi:cx", spiral->cx);
151 sp_repr_set_svg_double(repr, "sodipodi:cy", spiral->cy);
152 sp_repr_set_svg_double(repr, "sodipodi:expansion", spiral->exp);
153 sp_repr_set_svg_double(repr, "sodipodi:revolution", spiral->revo);
154 sp_repr_set_svg_double(repr, "sodipodi:radius", spiral->rad);
155 sp_repr_set_svg_double(repr, "sodipodi:argument", spiral->arg);
156 sp_repr_set_svg_double(repr, "sodipodi:t0", spiral->t0);
157 }
159 // make sure the curve is rebuilt with all up-to-date parameters
160 sp_spiral_set_shape ((SPShape *) spiral);
162 //Duplicate the path
163 SPCurve *curve = ((SPShape *) spiral)->curve;
164 //Nulls might be possible if this called iteratively
165 if ( !curve ) {
166 //g_warning("sp_spiral_write(): No path to copy\n");
167 return NULL;
168 }
169 NArtBpath *bpath = SP_CURVE_BPATH(curve);
170 if ( !bpath ) {
171 //g_warning("sp_spiral_write(): No path to copy\n");
172 return NULL;
173 }
174 char *d = sp_svg_write_path ( bpath );
175 repr->setAttribute("d", d);
176 g_free (d);
178 if (((SPObjectClass *) (parent_class))->write)
179 ((SPObjectClass *) (parent_class))->write (object, repr, flags | SP_SHAPE_WRITE_PATH);
181 return repr;
182 }
184 /**
185 * Virtual set: change spiral object attribute.
186 */
187 static void
188 sp_spiral_set (SPObject *object, unsigned int key, const gchar *value)
189 {
190 SPSpiral *spiral;
191 SPShape *shape;
193 spiral = SP_SPIRAL (object);
194 shape = SP_SHAPE (object);
196 /// \todo fixme: we should really collect updates
197 switch (key) {
198 case SP_ATTR_SODIPODI_CX:
199 if (!sp_svg_length_read_computed_absolute (value, &spiral->cx)) {
200 spiral->cx = 0.0;
201 }
202 object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
203 break;
204 case SP_ATTR_SODIPODI_CY:
205 if (!sp_svg_length_read_computed_absolute (value, &spiral->cy)) {
206 spiral->cy = 0.0;
207 }
208 object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
209 break;
210 case SP_ATTR_SODIPODI_EXPANSION:
211 if (value) {
212 /** \todo
213 * FIXME: check that value looks like a (finite)
214 * number. Create a routine that uses strtod, and
215 * accepts a default value (if strtod finds an error).
216 * N.B. atof/sscanf/strtod consider "nan" and "inf"
217 * to be valid numbers.
218 */
219 spiral->exp = g_ascii_strtod (value, NULL);
220 spiral->exp = CLAMP (spiral->exp, 0.0, 1000.0);
221 } else {
222 spiral->exp = 1.0;
223 }
224 object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
225 break;
226 case SP_ATTR_SODIPODI_REVOLUTION:
227 if (value) {
228 spiral->revo = g_ascii_strtod (value, NULL);
229 spiral->revo = CLAMP (spiral->revo, 0.05, 1024.0);
230 } else {
231 spiral->revo = 3.0;
232 }
233 object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
234 break;
235 case SP_ATTR_SODIPODI_RADIUS:
236 if (!sp_svg_length_read_computed_absolute (value, &spiral->rad)) {
237 spiral->rad = MAX (spiral->rad, 0.001);
238 }
239 object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
240 break;
241 case SP_ATTR_SODIPODI_ARGUMENT:
242 if (value) {
243 spiral->arg = g_ascii_strtod (value, NULL);
244 /** \todo
245 * FIXME: We still need some bounds on arg, for
246 * numerical reasons. E.g., we don't want inf or NaN,
247 * nor near-infinite numbers. I'm inclined to take
248 * modulo 2*pi. If so, then change the knot editors,
249 * which use atan2 - revo*2*pi, which typically
250 * results in very negative arg.
251 */
252 } else {
253 spiral->arg = 0.0;
254 }
255 object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
256 break;
257 case SP_ATTR_SODIPODI_T0:
258 if (value) {
259 spiral->t0 = g_ascii_strtod (value, NULL);
260 spiral->t0 = CLAMP (spiral->t0, 0.0, 0.999);
261 /** \todo
262 * Have shared constants for the allowable bounds for
263 * attributes. There was a bug here where we used -1.0
264 * as the minimum (which leads to NaN via, e.g.,
265 * pow(-1.0, 0.5); see sp_spiral_get_xy for
266 * requirements.
267 */
268 } else {
269 spiral->t0 = 0.0;
270 }
271 object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
272 break;
273 default:
274 if (((SPObjectClass *) parent_class)->set)
275 ((SPObjectClass *) parent_class)->set (object, key, value);
276 break;
277 }
278 }
280 /**
281 * Virtual update callback.
282 */
283 static void
284 sp_spiral_update (SPObject *object, SPCtx *ctx, guint flags)
285 {
286 if (flags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG | SP_OBJECT_VIEWPORT_MODIFIED_FLAG)) {
287 sp_shape_set_shape ((SPShape *) object);
288 }
290 if (((SPObjectClass *) parent_class)->update)
291 ((SPObjectClass *) parent_class)->update (object, ctx, flags);
292 }
294 /**
295 * Return textual description of spiral.
296 */
297 static gchar *
298 sp_spiral_description (SPItem * item)
299 {
300 // TRANSLATORS: since turn count isn't an integer, please adjust the
301 // string as needed to deal with an localized plural forms.
302 return g_strdup_printf (_("<b>Spiral</b> with %3f turns"), SP_SPIRAL(item)->revo);
303 }
306 /**
307 * Fit beziers together to spiral and draw it.
308 *
309 * \pre dstep \> 0.
310 * \pre is_unit_vector(*hat1).
311 * \post is_unit_vector(*hat2).
312 **/
313 static void
314 sp_spiral_fit_and_draw (SPSpiral const *spiral,
315 SPCurve *c,
316 double dstep,
317 NR::Point darray[],
318 NR::Point const &hat1,
319 NR::Point &hat2,
320 double *t)
321 {
322 #define BEZIER_SIZE 4
323 #define FITTING_MAX_BEZIERS 4
324 #define BEZIER_LENGTH (BEZIER_SIZE * FITTING_MAX_BEZIERS)
325 g_assert (dstep > 0);
326 g_assert (is_unit_vector (hat1));
328 NR::Point bezier[BEZIER_LENGTH];
329 double d;
330 int depth, i;
332 for (d = *t, i = 0; i <= SAMPLE_SIZE; d += dstep, i++) {
333 darray[i] = sp_spiral_get_xy(spiral, d);
335 /* Avoid useless adjacent dups. (Otherwise we can have all of darray filled with
336 the same value, which upsets chord_length_parameterize.) */
337 if ((i != 0)
338 && (darray[i] == darray[i - 1])
339 && (d < 1.0)) {
340 i--;
341 d += dstep;
342 /** We mustn't increase dstep for subsequent values of
343 * i: for large spiral.exp values, rate of growth
344 * increases very rapidly.
345 */
346 /** \todo
347 * Get the function itself to decide what value of d
348 * to use next: ensure that we move at least 0.25 *
349 * stroke width, for example. The derivative (as used
350 * for get_tangent before normalization) would be
351 * useful for estimating the appropriate d value. Or
352 * perhaps just start with a small dstep and scale by
353 * some small number until we move >= 0.25 *
354 * stroke_width. Must revert to the original dstep
355 * value for next iteration to avoid the problem
356 * mentioned above.
357 */
358 }
359 }
361 double const next_t = d - 2 * dstep;
362 /* == t + (SAMPLE_SIZE - 1) * dstep, in absence of dups. */
364 hat2 = -sp_spiral_get_tangent (spiral, next_t);
366 /** \todo
367 * We should use better algorithm to specify maximum error.
368 */
369 depth = sp_bezier_fit_cubic_full (bezier, NULL, darray, SAMPLE_SIZE,
370 hat1, hat2,
371 SPIRAL_TOLERANCE*SPIRAL_TOLERANCE,
372 FITTING_MAX_BEZIERS);
373 g_assert(depth * BEZIER_SIZE <= gint(G_N_ELEMENTS(bezier)));
374 #ifdef SPIRAL_DEBUG
375 if (*t == spiral->t0 || *t == 1.0)
376 g_print ("[%s] depth=%d, dstep=%g, t0=%g, t=%g, arg=%g\n",
377 debug_state, depth, dstep, spiral->t0, *t, spiral->arg);
378 #endif
379 if (depth != -1) {
380 for (i = 0; i < 4*depth; i += 4) {
381 sp_curve_curveto (c,
382 bezier[i + 1],
383 bezier[i + 2],
384 bezier[i + 3]);
385 }
386 } else {
387 #ifdef SPIRAL_VERBOSE
388 g_print ("cant_fit_cubic: t=%g\n", *t);
389 #endif
390 for (i = 1; i < SAMPLE_SIZE; i++)
391 sp_curve_lineto (c, darray[i]);
392 }
393 *t = next_t;
394 g_assert (is_unit_vector (hat2));
395 }
397 static void
398 sp_spiral_set_shape (SPShape *shape)
399 {
400 NR::Point darray[SAMPLE_SIZE + 1];
401 double t;
403 SPSpiral *spiral = SP_SPIRAL(shape);
405 SP_OBJECT (spiral)->requestModified(SP_OBJECT_MODIFIED_FLAG);
407 SPCurve *c = sp_curve_new ();
409 #ifdef SPIRAL_VERBOSE
410 g_print ("cx=%g, cy=%g, exp=%g, revo=%g, rad=%g, arg=%g, t0=%g\n",
411 spiral->cx,
412 spiral->cy,
413 spiral->exp,
414 spiral->revo,
415 spiral->rad,
416 spiral->arg,
417 spiral->t0);
418 #endif
420 /* Initial moveto. */
421 sp_curve_moveto(c, sp_spiral_get_xy(spiral, spiral->t0));
423 double const tstep = SAMPLE_STEP / spiral->revo;
424 double const dstep = tstep / (SAMPLE_SIZE - 1);
426 NR::Point hat1 = sp_spiral_get_tangent (spiral, spiral->t0);
427 NR::Point hat2;
428 for (t = spiral->t0; t < (1.0 - tstep);) {
429 sp_spiral_fit_and_draw (spiral, c, dstep, darray, hat1, hat2, &t);
431 hat1 = -hat2;
432 }
433 if ((1.0 - t) > SP_EPSILON)
434 sp_spiral_fit_and_draw (spiral, c, (1.0 - t)/(SAMPLE_SIZE - 1.0),
435 darray, hat1, hat2, &t);
437 sp_shape_set_curve_insync ((SPShape *) spiral, c, TRUE);
438 sp_curve_unref (c);
439 }
441 /**
442 * Set spiral properties and update display.
443 */
444 void
445 sp_spiral_position_set (SPSpiral *spiral,
446 gdouble cx,
447 gdouble cy,
448 gdouble exp,
449 gdouble revo,
450 gdouble rad,
451 gdouble arg,
452 gdouble t0)
453 {
454 g_return_if_fail (spiral != NULL);
455 g_return_if_fail (SP_IS_SPIRAL (spiral));
457 /** \todo
458 * Consider applying CLAMP or adding in-bounds assertions for
459 * some of these parameters.
460 */
461 spiral->cx = cx;
462 spiral->cy = cy;
463 spiral->exp = exp;
464 spiral->revo = revo;
465 spiral->rad = MAX (rad, 0.001);
466 spiral->arg = arg;
467 spiral->t0 = CLAMP(t0, 0.0, 0.999);
469 ((SPObject *)spiral)->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
470 }
472 /**
473 * Virtual snappoints callback.
474 */
475 static void sp_spiral_snappoints(SPItem const *item, SnapPointsIter p)
476 {
477 if (((SPItemClass *) parent_class)->snappoints) {
478 ((SPItemClass *) parent_class)->snappoints (item, p);
479 }
480 }
482 /**
483 * Return one of the points on the spiral.
484 *
485 * \param t specifies how far along the spiral.
486 * \pre \a t in [0.0, 2.03]. (It doesn't make sense for t to be much more
487 * than 1.0, though some callers go slightly beyond 1.0 for curve-fitting
488 * purposes.)
489 */
490 NR::Point sp_spiral_get_xy (SPSpiral const *spiral, gdouble t)
491 {
492 g_assert (spiral != NULL);
493 g_assert (SP_IS_SPIRAL(spiral));
494 g_assert (spiral->exp >= 0.0);
495 /* Otherwise we get NaN for t==0. */
496 g_assert (spiral->exp <= 1000.0);
497 /* Anything much more results in infinities. Even allowing 1000 is somewhat overkill. */
498 g_assert (t >= 0.0);
499 /* Any callers passing -ve t will have a bug for non-integral values of exp. */
501 double const rad = spiral->rad * pow(t, (double) spiral->exp);
502 double const arg = 2.0 * M_PI * spiral->revo * t + spiral->arg;
504 return NR::Point(rad * cos (arg) + spiral->cx,
505 rad * sin (arg) + spiral->cy);
506 }
509 /**
510 * Returns the derivative of sp_spiral_get_xy with respect to t,
511 * scaled to a unit vector.
512 *
513 * \pre spiral != 0.
514 * \pre 0 \<= t.
515 * \pre p != NULL.
516 * \post is_unit_vector(*p).
517 */
518 static NR::Point
519 sp_spiral_get_tangent (SPSpiral const *spiral, gdouble t)
520 {
521 NR::Point ret(1.0, 0.0);
522 g_return_val_if_fail (( ( spiral != NULL )
523 && SP_IS_SPIRAL(spiral) ),
524 ret);
525 g_assert (t >= 0.0);
526 g_assert (spiral->exp >= 0.0);
527 /* See above for comments on these assertions. */
529 double const t_scaled = 2.0 * M_PI * spiral->revo * t;
530 double const arg = t_scaled + spiral->arg;
531 double const s = sin (arg);
532 double const c = cos (arg);
534 if (spiral->exp == 0.0) {
535 ret = NR::Point(-s, c);
536 } else if (t_scaled == 0.0) {
537 ret = NR::Point(c, s);
538 } else {
539 NR::Point unrotated(spiral->exp, t_scaled);
540 double const s_len = L2 (unrotated);
541 g_assert (s_len != 0);
542 /** \todo
543 * Check that this isn't being too hopeful of the hypot
544 * function. E.g. test with numbers around 2**-1070
545 * (denormalized numbers), preferably on a few different
546 * platforms. However, njh says that the usual implementation
547 * does handle both very big and very small numbers.
548 */
549 unrotated /= s_len;
551 /* ret = spiral->exp * (c, s) + t_scaled * (-s, c);
552 alternatively ret = (spiral->exp, t_scaled) * (( c, s),
553 (-s, c)).*/
554 ret = NR::Point(dot(unrotated, NR::Point(c, -s)),
555 dot(unrotated, NR::Point(s, c)));
556 /* ret should already be approximately normalized: the
557 matrix ((c, -s), (s, c)) is orthogonal (it just
558 rotates by arg), and unrotated has been normalized,
559 so ret is already of unit length other than numerical
560 error in the above matrix multiplication. */
562 /** \todo
563 * I haven't checked how important it is for ret to be very
564 * near unit length; we could get rid of the below.
565 */
567 ret.normalize();
568 /* Proof that ret length is non-zero: see above. (Should be near 1.) */
569 }
571 g_assert (is_unit_vector (ret));
572 return ret;
573 }
575 /**
576 * Compute rad and/or arg for point on spiral.
577 */
578 void
579 sp_spiral_get_polar (SPSpiral const *spiral, gdouble t, gdouble *rad, gdouble *arg)
580 {
581 g_return_if_fail (spiral != NULL);
582 g_return_if_fail (SP_IS_SPIRAL(spiral));
584 if (rad)
585 *rad = spiral->rad * pow(t, (double) spiral->exp);
586 if (arg)
587 *arg = 2.0 * M_PI * spiral->revo * t + spiral->arg;
588 }
590 /**
591 * Return true if spiral has properties that make it invalid.
592 */
593 bool
594 sp_spiral_is_invalid (SPSpiral const *spiral)
595 {
596 gdouble rad;
598 sp_spiral_get_polar (spiral, 0.0, &rad, NULL);
599 if (rad < 0.0 || rad > SP_HUGE) {
600 g_print ("rad(t=0)=%g\n", rad);
601 return TRUE;
602 }
603 sp_spiral_get_polar (spiral, 1.0, &rad, NULL);
604 if (rad < 0.0 || rad > SP_HUGE) {
605 g_print ("rad(t=1)=%g\n", rad);
606 return TRUE;
607 }
608 return FALSE;
609 }
611 /*
612 Local Variables:
613 mode:c++
614 c-file-style:"stroustrup"
615 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
616 indent-tabs-mode:nil
617 fill-column:99
618 End:
619 */
620 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :