Code

do calligraphic draw opacity correctly
[inkscape.git] / src / dyna-draw-context.cpp
1 #define __SP_DYNA_DRAW_CONTEXT_C__
3 /*
4  * Handwriting-like drawing mode
5  *
6  * Authors:
7  *   Mitsuru Oka <oka326@parkcity.ne.jp>
8  *   Lauris Kaplinski <lauris@kaplinski.com>
9  *   bulia byak <buliabyak@users.sf.net>
10  *
11  * The original dynadraw code:
12  *   Paul Haeberli <paul@sgi.com>
13  *
14  * Copyright (C) 1998 The Free Software Foundation
15  * Copyright (C) 1999-2005 authors
16  * Copyright (C) 2001-2002 Ximian, Inc.
17  *
18  * Released under GNU GPL, read the file 'COPYING' for more information
19  */
21 #define noDYNA_DRAW_VERBOSE
23 #include "config.h"
25 #include <gtk/gtk.h>
26 #include <gdk/gdkkeysyms.h>
28 #include "svg/svg.h"
29 #include "display/canvas-bpath.h"
30 #include "display/bezier-utils.h"
32 #include "macros.h"
33 #include "document.h"
34 #include "selection.h"
35 #include "desktop.h"
36 #include "desktop-events.h"
37 #include "desktop-handles.h"
38 #include "desktop-affine.h"
39 #include "desktop-style.h"
40 #include "message-context.h"
41 #include "pixmaps/cursor-calligraphy.xpm"
42 #include "dyna-draw-context.h"
43 #include "libnr/n-art-bpath.h"
44 #include "libnr/nr-path.h"
45 #include "xml/repr.h"
46 #include "context-fns.h"
47 #include "sp-item.h"
48 #include "inkscape.h"
49 #include "color.h"
51 #define DDC_RED_RGBA 0xff0000ff
53 #define SAMPLE_TIMEOUT 10
54 #define TOLERANCE_LINE 1.0
55 #define TOLERANCE_CALLIGRAPHIC 3.0
56 #define DYNA_EPSILON 1.0e-6
58 #define DYNA_MIN_WIDTH 1.0e-6
60 #define DRAG_MIN 0.0
61 #define DRAG_DEFAULT 1.0
62 #define DRAG_MAX 1.0
64 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
65 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
66 static void sp_dyna_draw_context_dispose(GObject *object);
68 static void sp_dyna_draw_context_setup(SPEventContext *ec);
69 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
70 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
72 static void clear_current(SPDynaDrawContext *dc);
73 static void set_to_accumulated(SPDynaDrawContext *dc);
74 static void accumulate_calligraphic(SPDynaDrawContext *dc);
76 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
77 static void fit_and_split_calligraphics(SPDynaDrawContext *ddc, gboolean release);
79 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
80 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
81 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
82 static void draw_temporary_box(SPDynaDrawContext *dc);
85 static SPEventContextClass *parent_class;
87 GtkType
88 sp_dyna_draw_context_get_type(void)
89 {
90     static GType type = 0;
91     if (!type) {
92         GTypeInfo info = {
93             sizeof(SPDynaDrawContextClass),
94             NULL, NULL,
95             (GClassInitFunc) sp_dyna_draw_context_class_init,
96             NULL, NULL,
97             sizeof(SPDynaDrawContext),
98             4,
99             (GInstanceInitFunc) sp_dyna_draw_context_init,
100             NULL,   /* value_table */
101         };
102         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
103     }
104     return type;
107 static void
108 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
110     GObjectClass *object_class = (GObjectClass *) klass;
111     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
113     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
115     object_class->dispose = sp_dyna_draw_context_dispose;
117     event_context_class->setup = sp_dyna_draw_context_setup;
118     event_context_class->set = sp_dyna_draw_context_set;
119     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
122 static void
123 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
125     SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
127     event_context->cursor_shape = cursor_calligraphy_xpm;
128     event_context->hot_x = 4;
129     event_context->hot_y = 4;
131     ddc->accumulated = NULL;
132     ddc->segments = NULL;
133     ddc->currentcurve = NULL;
134     ddc->currentshape = NULL;
135     ddc->npoints = 0;
136     ddc->cal1 = NULL;
137     ddc->cal2 = NULL;
138     ddc->repr = NULL;
140     /* DynaDraw values */
141     ddc->cur = NR::Point(0,0);
142     ddc->last = NR::Point(0,0);
143     ddc->vel = NR::Point(0,0);
144     ddc->acc = NR::Point(0,0);
145     ddc->ang = NR::Point(0,0);
146     ddc->del = NR::Point(0,0);
148     /* attributes */
149     ddc->dragging = FALSE;
151     ddc->mass = 0.3;
152     ddc->drag = DRAG_DEFAULT;
153     ddc->angle = 30.0;
154     ddc->width = 0.2;
156     ddc->vel_thin = 0.1;
157     ddc->flatness = 0.9;
159     ddc->abs_width = false;
160     ddc->keep_selected = true;
163 static void
164 sp_dyna_draw_context_dispose(GObject *object)
166     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
168     if (ddc->accumulated) {
169         ddc->accumulated = sp_curve_unref(ddc->accumulated);
170     }
172     while (ddc->segments) {
173         gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
174         ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
175     }
177     if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
178     if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
179     if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
181     if (ddc->currentshape) {
182         gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
183         ddc->currentshape = NULL;
184     }
186     if (ddc->_message_context) {
187         delete ddc->_message_context;
188     }
190     G_OBJECT_CLASS(parent_class)->dispose(object);
193 static void
194 sp_dyna_draw_context_setup(SPEventContext *ec)
196     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
198     if (((SPEventContextClass *) parent_class)->setup)
199         ((SPEventContextClass *) parent_class)->setup(ec);
201     ddc->accumulated = sp_curve_new_sized(32);
202     ddc->currentcurve = sp_curve_new_sized(4);
204     ddc->cal1 = sp_curve_new_sized(32);
205     ddc->cal2 = sp_curve_new_sized(32);
207     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
208     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
209     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
210     /* fixme: Cannot we cascade it to root more clearly? */
211     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
213     sp_event_context_read(ec, "mass");
214     sp_event_context_read(ec, "drag");
215     sp_event_context_read(ec, "angle");
216     sp_event_context_read(ec, "width");
217     sp_event_context_read(ec, "thinning");
218     sp_event_context_read(ec, "tremor");
219     sp_event_context_read(ec, "flatness");
220     sp_event_context_read(ec, "usepressure");
221     sp_event_context_read(ec, "usetilt");
222     sp_event_context_read(ec, "abs_width");
223     sp_event_context_read(ec, "keep_selected");
225     ddc->is_drawing = false;
227     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
230 static void
231 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
233     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
235     if (!strcmp(key, "mass")) {
236         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
237         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
238     } else if (!strcmp(key, "drag")) {
239         double const dval = ( val ? g_ascii_strtod (val, NULL) : DRAG_DEFAULT );
240         ddc->drag = CLAMP(dval, DRAG_MIN, DRAG_MAX);
241     } else if (!strcmp(key, "angle")) {
242         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
243         ddc->angle = CLAMP (dval, -90, 90);
244     } else if (!strcmp(key, "width")) {
245         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
246         ddc->width = CLAMP(dval, -1000.0, 1000.0);
247     } else if (!strcmp(key, "thinning")) {
248         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
249         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
250     } else if (!strcmp(key, "tremor")) {
251         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
252         ddc->tremor = CLAMP(dval, 0.0, 1.0);
253     } else if (!strcmp(key, "flatness")) {
254         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
255         ddc->flatness = CLAMP(dval, 0, 1.0);
256     } else if (!strcmp(key, "usepressure")) {
257         ddc->usepressure = (val && strcmp(val, "0"));
258     } else if (!strcmp(key, "usetilt")) {
259         ddc->usetilt = (val && strcmp(val, "0"));
260     } else if (!strcmp(key, "abs_width")) {
261         ddc->abs_width = (val && strcmp(val, "0"));
262     } else if (!strcmp(key, "keep_selected")) {
263         ddc->keep_selected = (val && strcmp(val, "0"));
264     }
266     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
269 static double
270 flerp(double f0, double f1, double p)
272     return f0 + ( f1 - f0 ) * p;
275 /* Get normalized point */
276 static NR::Point
277 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
279     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
280     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
281     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
284 /* Get view point */
285 static NR::Point
286 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
288     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
289     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
290     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
293 static void
294 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
296     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
297     dc->vel = NR::Point(0,0);
298     dc->acc = NR::Point(0,0);
299     dc->ang = NR::Point(0,0);
300     dc->del = NR::Point(0,0);
303 static void
304 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
306     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
307         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
308     else
309         dc->pressure = DDC_DEFAULT_PRESSURE;
311     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
312         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
313     else
314         dc->xtilt = DDC_DEFAULT_TILT;
316     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
317         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
318     else
319         dc->ytilt = DDC_DEFAULT_TILT;
323 static gboolean
324 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
326     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
328     /* Calculate mass and drag */
329     double const mass = flerp(1.0, 160.0, dc->mass);
330     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
332     /* Calculate force and acceleration */
333     NR::Point force = n - dc->cur;
334     if ( NR::L2(force) < DYNA_EPSILON ) {
335         return FALSE;
336     }
338     dc->acc = force / mass;
340     /* Calculate new velocity */
341     dc->vel += dc->acc;
343     /* Calculate angle of drawing tool */
345     double a1;
346     if (dc->usetilt) {
347         // 1a. calculate nib angle from input device tilt:
348         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
350         if (length > 0) {
351             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
352             a1 = atan2(ang1);
353         }
354         else
355             a1 = 0.0;
356     }
357     else {
358         // 1b. fixed dc->angle (absolutely flat nib):
359         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
360         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
361         a1 = atan2(ang1);
362     }
364     // 2. perpendicular to dc->vel (absolutely non-flat nib):
365     gdouble const mag_vel = NR::L2(dc->vel);
366     if ( mag_vel < DYNA_EPSILON ) {
367         return FALSE;
368     }
369     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
371     // 3. Average them using flatness parameter:
372     // calculate angles
373     double a2 = atan2(ang2);
374     // flip a2 to force it to be in the same half-circle as a1
375     bool flipped = false;
376     if (fabs (a2-a1) > 0.5*M_PI) {
377         a2 += M_PI;
378         flipped = true;
379     }
380     // normalize a2
381     if (a2 > M_PI)
382         a2 -= 2*M_PI;
383     if (a2 < -M_PI)
384         a2 += 2*M_PI;
385     // find the flatness-weighted bisector angle, unflip if a2 was flipped
386     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
387     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
388     // convert to point
389     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
391     /* Apply drag */
392     dc->vel *= 1.0 - drag;
394     /* Update position */
395     dc->last = dc->cur;
396     dc->cur += dc->vel;
398     return TRUE;
401 static void
402 sp_dyna_draw_brush(SPDynaDrawContext *dc)
404     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
406     // How much velocity thins strokestyle
407     double vel_thin = flerp (0, 160, dc->vel_thin);
409     // Influence of pressure on thickness
410     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
412     double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
414     double tremble_left = 0, tremble_right = 0;
415     if (dc->tremor > 0) {
416         // obtain two normally distributed random variables, using polar Box-Muller transform
417         double x1, x2, w, y1, y2;
418         do {
419             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
420             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
421             w = x1 * x1 + x2 * x2;
422         } while ( w >= 1.0 );
423         w = sqrt( (-2.0 * log( w ) ) / w );
424         y1 = x1 * w;
425         y2 = x2 * w;
427         // deflect both left and right edges randomly and independently, so that:
428         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
429         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
430         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
431         // comparatively smooth and slow ones excessively jittery
432         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
433         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
434     }
436     if ( width < 0.02 * dc->width ) {
437         width = 0.02 * dc->width;
438     }
440     double dezoomify_factor = 0.05 * 1000;
441     if (!dc->abs_width) {
442         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
443     }
445     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
446     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
448     NR::Point abs_middle = sp_dyna_draw_get_vpoint(dc, dc->cur);
450     dc->point1[dc->npoints] = abs_middle + del_left;
451     dc->point2[dc->npoints] = abs_middle - del_right;
453     dc->del = 0.5*(del_left + del_right);
455     dc->npoints++;
458 void
459 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
461     desktop->setToolboxAdjustmentValue (id, value);
464 gint
465 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
466                                   GdkEvent *event)
468     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
469     SPDesktop *desktop = event_context->desktop;
471     gint ret = FALSE;
473     switch (event->type) {
474     case GDK_BUTTON_PRESS:
475         if ( event->button.button == 1 ) {
477             SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
479             if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
480                 return TRUE;
481             }
483             NR::Point const button_w(event->button.x,
484                                      event->button.y);
485             NR::Point const button_dt(desktop->w2d(button_w));
486             sp_dyna_draw_reset(dc, button_dt);
487             sp_dyna_draw_extinput(dc, event);
488             sp_dyna_draw_apply(dc, button_dt);
489             sp_curve_reset(dc->accumulated);
490             if (dc->repr) {
491                 dc->repr = NULL;
492             }
494             /* initialize first point */
495             dc->npoints = 0;
497             sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
498                                 ( GDK_KEY_PRESS_MASK |
499                                   GDK_BUTTON_RELEASE_MASK |
500                                   GDK_POINTER_MOTION_MASK |
501                                   GDK_BUTTON_PRESS_MASK ),
502                                 NULL,
503                                 event->button.time);
505             ret = TRUE;
507             dc->is_drawing = true;
508         }
509         break;
510     case GDK_MOTION_NOTIFY:
511         if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
512             dc->dragging = TRUE;
514             NR::Point const motion_w(event->motion.x,
515                                      event->motion.y);
516             NR::Point const motion_dt(desktop->w2d(motion_w));
518             sp_dyna_draw_extinput(dc, event);
519             if (!sp_dyna_draw_apply(dc, motion_dt)) {
520                 ret = TRUE;
521                 break;
522             }
524             if ( dc->cur != dc->last ) {
525                 sp_dyna_draw_brush(dc);
526                 g_assert( dc->npoints > 0 );
527                 fit_and_split(dc, FALSE);
528             }
529             ret = TRUE;
530         }
531         break;
533     case GDK_BUTTON_RELEASE:
534         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
535         dc->is_drawing = false;
536         if ( dc->dragging && event->button.button == 1 ) {
537             dc->dragging = FALSE;
539             /* Remove all temporary line segments */
540             while (dc->segments) {
541                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
542                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
543             }
544             /* Create object */
545             fit_and_split(dc, TRUE);
546             accumulate_calligraphic(dc);
547             set_to_accumulated(dc); /* temporal implementation */
548             /* reset accumulated curve */
549             sp_curve_reset(dc->accumulated);
550             clear_current(dc);
551             if (dc->repr) {
552                 dc->repr = NULL;
553             }
554             ret = TRUE;
555         }
556         break;
557     case GDK_KEY_PRESS:
558         switch (get_group0_keyval (&event->key)) {
559         case GDK_Up:
560         case GDK_KP_Up:
561             if (!MOD__CTRL_ONLY) {
562                 dc->angle += 5.0;
563                 if (dc->angle > 90.0)
564                     dc->angle = 90.0;
565                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
566                 ret = TRUE;
567             }
568             break;
569         case GDK_Down:
570         case GDK_KP_Down:
571             if (!MOD__CTRL_ONLY) {
572                 dc->angle -= 5.0;
573                 if (dc->angle < -90.0)
574                     dc->angle = -90.0;
575                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
576                 ret = TRUE;
577             }
578             break;
579         case GDK_Right:
580         case GDK_KP_Right:
581             if (!MOD__CTRL_ONLY) {
582                 dc->width += 0.01;
583                 if (dc->width > 1.0)
584                     dc->width = 1.0;
585                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
586                 ret = TRUE;
587             }
588             break;
589         case GDK_Left:
590         case GDK_KP_Left:
591             if (!MOD__CTRL_ONLY) {
592                 dc->width -= 0.01;
593                 if (dc->width < 0.01)
594                     dc->width = 0.01;
595                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
596                 ret = TRUE;
597             }
598             break;
599         case GDK_x:
600         case GDK_X:
601             if (MOD__ALT_ONLY) {
602                 desktop->setToolboxFocusTo ("altx-calligraphy");
603                 ret = TRUE;
604             }
605             break;
606         case GDK_Escape:
607             sp_desktop_selection(desktop)->clear();
608             break;
610         default:
611             break;
612         }
613     default:
614         break;
615     }
617     if (!ret) {
618         if (((SPEventContextClass *) parent_class)->root_handler) {
619             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
620         }
621     }
623     return ret;
627 static void
628 clear_current(SPDynaDrawContext *dc)
630     /* reset bpath */
631     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
632     /* reset curve */
633     sp_curve_reset(dc->currentcurve);
634     sp_curve_reset(dc->cal1);
635     sp_curve_reset(dc->cal2);
636     /* reset points */
637     dc->npoints = 0;
640 static void
641 set_to_accumulated(SPDynaDrawContext *dc)
643     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
645     if (!sp_curve_empty(dc->accumulated)) {
646         NArtBpath *abp;
647         gchar *str;
649         if (!dc->repr) {
650             /* Create object */
651             Inkscape::XML::Node *repr = sp_repr_new("svg:path");
653             /* Set style */
654             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
656             dc->repr = repr;
658             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
659             Inkscape::GC::release(dc->repr);
660             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
661             item->updateRepr();
662             if (dc->keep_selected)
663                 sp_desktop_selection(desktop)->set(dc->repr);
664         }
665         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
666         str = sp_svg_write_path(abp);
667         g_assert( str != NULL );
668         nr_free(abp);
669         dc->repr->setAttribute("d", str);
670         g_free(str);
671     } else {
672         if (dc->repr) {
673             sp_repr_unparent(dc->repr);
674         }
675         dc->repr = NULL;
676     }
678     sp_document_done(sp_desktop_document(desktop));
681 static void
682 accumulate_calligraphic(SPDynaDrawContext *dc)
684     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
685         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
686         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
687         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
688         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
689         sp_curve_closepath(dc->accumulated);
691         sp_curve_unref(rev_cal2);
693         sp_curve_reset(dc->cal1);
694         sp_curve_reset(dc->cal2);
695     }
698 static void
699 fit_and_split(SPDynaDrawContext *dc,
700               gboolean release)
702     fit_and_split_calligraphics(dc, release);
705 static double square(double const x)
707     return x * x;
710 static void
711 fit_and_split_calligraphics(SPDynaDrawContext *dc, gboolean release)
713     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
715 #ifdef DYNA_DRAW_VERBOSE
716     g_print("[F&S:R=%c]", release?'T':'F');
717 #endif
719     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
720         return; // just clicked
722     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
723 #define BEZIER_SIZE       4
724 #define BEZIER_MAX_BEZIERS  8
725 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
727 #ifdef DYNA_DRAW_VERBOSE
728         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
729                 dc->npoints, release ? "TRUE" : "FALSE");
730 #endif
732         /* Current calligraphic */
733         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
734             /* dc->npoints > 0 */
735             /* g_print("calligraphics(1|2) reset\n"); */
736             sp_curve_reset(dc->cal1);
737             sp_curve_reset(dc->cal2);
739             sp_curve_moveto(dc->cal1, dc->point1[0]);
740             sp_curve_moveto(dc->cal2, dc->point2[0]);
741         }
743         NR::Point b1[BEZIER_MAX_LENGTH];
744         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
745                                                tolerance_sq, BEZIER_MAX_BEZIERS);
746         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
748         NR::Point b2[BEZIER_MAX_LENGTH];
749         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
750                                                tolerance_sq, BEZIER_MAX_BEZIERS);
751         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
753         if ( nb1 != -1 && nb2 != -1 ) {
754             /* Fit and draw and reset state */
755 #ifdef DYNA_DRAW_VERBOSE
756             g_print("nb1:%d nb2:%d\n", nb1, nb2);
757 #endif
758             /* CanvasShape */
759             if (! release) {
760                 sp_curve_reset(dc->currentcurve);
761                 sp_curve_moveto(dc->currentcurve, b1[0]);
762                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
763                     sp_curve_curveto(dc->currentcurve, bp1[1],
764                                      bp1[2], bp1[3]);
765                 }
766                 sp_curve_lineto(dc->currentcurve,
767                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
768                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
769                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
770                 }
771                 sp_curve_closepath(dc->currentcurve);
772                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
773             }
775             /* Current calligraphic */
776             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
777                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
778             }
779             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
780                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
781             }
782         } else {
783             /* fixme: ??? */
784 #ifdef DYNA_DRAW_VERBOSE
785             g_print("[fit_and_split_calligraphics] failed to fit-cubic.\n");
786 #endif
787             draw_temporary_box(dc);
789             for (gint i = 1; i < dc->npoints; i++) {
790                 sp_curve_lineto(dc->cal1, dc->point1[i]);
791             }
792             for (gint i = 1; i < dc->npoints; i++) {
793                 sp_curve_lineto(dc->cal2, dc->point2[i]);
794             }
795         }
797         /* Fit and draw and copy last point */
798 #ifdef DYNA_DRAW_VERBOSE
799         g_print("[%d]Yup\n", dc->npoints);
800 #endif
801         if (!release) {
802             g_assert(!sp_curve_empty(dc->currentcurve));
804             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
805                                                    SP_TYPE_CANVAS_BPATH,
806                                                    NULL);
807             SPCurve *curve = sp_curve_copy(dc->currentcurve);
808             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
809             sp_curve_unref(curve);
811             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
812             double opacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
813             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity)), SP_WIND_RULE_EVENODD);
814             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
815             /* fixme: Cannot we cascade it to root more clearly? */
816             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
818             dc->segments = g_slist_prepend(dc->segments, cbp);
819         }
821         dc->point1[0] = dc->point1[dc->npoints - 1];
822         dc->point2[0] = dc->point2[dc->npoints - 1];
823         dc->npoints = 1;
824     } else {
825         draw_temporary_box(dc);
826     }
829 static void
830 draw_temporary_box(SPDynaDrawContext *dc)
832     sp_curve_reset(dc->currentcurve);
833     sp_curve_moveto(dc->currentcurve, dc->point1[0]);
834     for (gint i = 1; i < dc->npoints; i++) {
835         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
836     }
837     for (gint i = dc->npoints-1; i >= 0; i--) {
838         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
839     }
840     sp_curve_closepath(dc->currentcurve);
841     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
844 /*
845   Local Variables:
846   mode:c++
847   c-file-style:"stroustrup"
848   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
849   indent-tabs-mode:nil
850   fill-column:99
851   End:
852 */
853 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :