Code

Refactoring begining
[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  *   MenTaLguY <mental@rydia.net>
11  *
12  * The original dynadraw code:
13  *   Paul Haeberli <paul@sgi.com>
14  *
15  * Copyright (C) 1998 The Free Software Foundation
16  * Copyright (C) 1999-2005 authors
17  * Copyright (C) 2001-2002 Ximian, Inc.
18  * Copyright (C) 2005-2007 bulia byak
19  * Copyright (C) 2006 MenTaLguY
20  *
21  * Released under GNU GPL, read the file 'COPYING' for more information
22  */
24 #define noDYNA_DRAW_VERBOSE
26 #include "config.h"
28 #include <gtk/gtk.h>
29 #include <gdk/gdkkeysyms.h>
30 #include <glibmm/i18n.h>
31 #include <string>
32 #include <cstring>
33 #include <numeric>
35 #include "svg/svg.h"
36 #include "display/canvas-bpath.h"
37 #include "display/bezier-utils.h"
38 #include "display/curve.h"
39 #include <glib/gmem.h>
40 #include "macros.h"
41 #include "document.h"
42 #include "selection.h"
43 #include "desktop.h"
44 #include "desktop-events.h"
45 #include "desktop-handles.h"
46 #include "desktop-affine.h"
47 #include "desktop-style.h"
48 #include "message-context.h"
49 #include "prefs-utils.h"
50 #include "pixmaps/cursor-calligraphy.xpm"
51 #include "libnr/n-art-bpath.h"
52 #include "libnr/nr-path.h"
53 #include "libnr/nr-matrix-ops.h"
54 #include "libnr/nr-scale-translate-ops.h"
55 #include "xml/repr.h"
56 #include "context-fns.h"
57 #include "sp-item.h"
58 #include "inkscape.h"
59 #include "color.h"
60 #include "splivarot.h"
61 #include "sp-item-group.h"
62 #include "sp-shape.h"
63 #include "sp-path.h"
64 #include "sp-text.h"
65 #include "display/canvas-bpath.h"
66 #include "display/canvas-arena.h"
67 #include "livarot/Shape.h"
68 #include "isnan.h"
70 #include "dyna-draw-context.h"
72 #define DDC_RED_RGBA 0xff0000ff
74 #define TOLERANCE_CALLIGRAPHIC 0.1
76 #define DYNA_EPSILON 0.5e-6
77 #define DYNA_EPSILON_START 0.5e-2
78 #define DYNA_VEL_START 1e-5
80 #define DYNA_MIN_WIDTH 1.0e-6
82 #define DRAG_MIN 0.0
83 #define DRAG_DEFAULT 1.0
84 #define DRAG_MAX 1.0
86 // FIXME: move it to some shared file to be reused by both calligraphy and dropper
87 #define C1 0.552
88 static NArtBpath const hatch_area_circle[] = {
89     { NR_MOVETO, 0, 0, 0, 0, -1, 0 },
90     { NR_CURVETO, -1, C1, -C1, 1, 0, 1 },
91     { NR_CURVETO, C1, 1, 1, C1, 1, 0 },
92     { NR_CURVETO, 1, -C1, C1, -1, 0, -1 },
93     { NR_CURVETO, -C1, -1, -1, -C1, -1, 0 },
94     { NR_END, 0, 0, 0, 0, 0, 0 }
95 };
96 #undef C1
99 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
100 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
101 static void sp_dyna_draw_context_dispose(GObject *object);
103 static void sp_dyna_draw_context_setup(SPEventContext *ec);
104 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
105 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
107 static void clear_current(SPDynaDrawContext *dc);
108 static void set_to_accumulated(SPDynaDrawContext *dc, bool unionize);
109 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
110 static void accumulate_calligraphic(SPDynaDrawContext *dc);
112 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
114 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
115 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
116 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
117 static void draw_temporary_box(SPDynaDrawContext *dc);
120 static SPEventContextClass *parent_class;
122 GType sp_dyna_draw_context_get_type(void)
124     static GType type = 0;
125     if (!type) {
126         GTypeInfo info = {
127             sizeof(SPDynaDrawContextClass),
128             0, // base_init
129             0, // base_finalize
130             (GClassInitFunc)sp_dyna_draw_context_class_init,
131             0, // class_finalize
132             0, // class_data
133             sizeof(SPDynaDrawContext),
134             0, // n_preallocs
135             (GInstanceInitFunc)sp_dyna_draw_context_init,
136             0 // value_table
137         };
138         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, static_cast<GTypeFlags>(0));
139     }
140     return type;
143 static void
144 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
146     GObjectClass *object_class = (GObjectClass *) klass;
147     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
149     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
151     object_class->dispose = sp_dyna_draw_context_dispose;
153     event_context_class->setup = sp_dyna_draw_context_setup;
154     event_context_class->set = sp_dyna_draw_context_set;
155     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
158 static void
159 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
161     SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
163     event_context->cursor_shape = cursor_calligraphy_xpm;
164     event_context->hot_x = 4;
165     event_context->hot_y = 4;
167     ddc->accumulated = NULL;
168     ddc->segments = NULL;
169     ddc->currentcurve = NULL;
170     ddc->currentshape = NULL;
171     ddc->npoints = 0;
172     ddc->cal1 = NULL;
173     ddc->cal2 = NULL;
174     ddc->repr = NULL;
176     /* DynaDraw values */
177     ddc->cur = NR::Point(0,0);
178     ddc->last = NR::Point(0,0);
179     ddc->vel = NR::Point(0,0);
180     ddc->vel_max = 0;
181     ddc->acc = NR::Point(0,0);
182     ddc->ang = NR::Point(0,0);
183     ddc->del = NR::Point(0,0);
185     /* attributes */
186     ddc->dragging = FALSE;
188     ddc->mass = 0.3;
189     ddc->drag = DRAG_DEFAULT;
190     ddc->angle = 30.0;
191     ddc->width = 0.2;
192     ddc->pressure = DDC_DEFAULT_PRESSURE;
194     ddc->vel_thin = 0.1;
195     ddc->flatness = 0.9;
196     ddc->cap_rounding = 0.0;
198     ddc->abs_width = false;
199     ddc->keep_selected = true;
201     ddc->hatch_spacing = 0;
202     ddc->hatch_spacing_step = 0;
203     new (&ddc->hatch_pointer_past) std::list<double>();
204     new (&ddc->hatch_nearest_past) std::list<double>();
205     ddc->hatch_last_nearest = NR::Point(0,0);
206     ddc->hatch_last_pointer = NR::Point(0,0);
207     ddc->hatch_vector_accumulated = NR::Point(0,0);
208     ddc->hatch_escaped = false;
209     ddc->hatch_area = NULL;
210     ddc->hatch_item = NULL;
211     ddc->hatch_livarot_path = NULL;
213     ddc->trace_bg = false;
216 static void
217 sp_dyna_draw_context_dispose(GObject *object)
219     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
221     if (ddc->hatch_area) {
222         gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
223         ddc->hatch_area = NULL;
224     }
226     if (ddc->accumulated) {
227         ddc->accumulated = ddc->accumulated->unref();
228     }
230     while (ddc->segments) {
231         gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
232         ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
233     }
235     if (ddc->currentcurve) ddc->currentcurve = ddc->currentcurve->unref();
236     if (ddc->cal1) ddc->cal1 = ddc->cal1->unref();
237     if (ddc->cal2) ddc->cal2 = ddc->cal2->unref();
239     if (ddc->currentshape) {
240         gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
241         ddc->currentshape = NULL;
242     }
244     if (ddc->_message_context) {
245         delete ddc->_message_context;
246     }
248     G_OBJECT_CLASS(parent_class)->dispose(object);
250     ddc->hatch_pointer_past.~list();
251     ddc->hatch_nearest_past.~list();
254 static void
255 sp_dyna_draw_context_setup(SPEventContext *ec)
257     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
259     if (((SPEventContextClass *) parent_class)->setup)
260         ((SPEventContextClass *) parent_class)->setup(ec);
262     ddc->accumulated = new SPCurve(32);
263     ddc->currentcurve = new SPCurve(4);
265     ddc->cal1 = new SPCurve(32);
266     ddc->cal2 = new SPCurve(32);
268     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
269     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
270     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
271     /* fixme: Cannot we cascade it to root more clearly? */
272     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
274     {
275         SPCurve *c = SPCurve::new_from_foreign_bpath(hatch_area_circle);
276         ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
277         c->unref();
278         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
279         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
280         sp_canvas_item_hide(ddc->hatch_area);
281     }
283     sp_event_context_read(ec, "mass");
284     sp_event_context_read(ec, "wiggle");
285     sp_event_context_read(ec, "angle");
286     sp_event_context_read(ec, "width");
287     sp_event_context_read(ec, "thinning");
288     sp_event_context_read(ec, "tremor");
289     sp_event_context_read(ec, "flatness");
290     sp_event_context_read(ec, "tracebackground");
291     sp_event_context_read(ec, "usepressure");
292     sp_event_context_read(ec, "usetilt");
293     sp_event_context_read(ec, "abs_width");
294     sp_event_context_read(ec, "keep_selected");
295     sp_event_context_read(ec, "cap_rounding");
297     ddc->is_drawing = false;
299     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
301     if (prefs_get_int_attribute("tools.calligraphic", "selcue", 0) != 0) {
302         ec->enableSelectionCue();
303     }
306 static void
307 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
309     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
311     if (!strcmp(key, "mass")) {
312         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
313         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
314     } else if (!strcmp(key, "wiggle")) {
315         double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
316         ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
317     } else if (!strcmp(key, "angle")) {
318         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
319         ddc->angle = CLAMP (dval, -90, 90);
320     } else if (!strcmp(key, "width")) {
321         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
322         ddc->width = CLAMP(dval, -1000.0, 1000.0);
323     } else if (!strcmp(key, "thinning")) {
324         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
325         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
326     } else if (!strcmp(key, "tremor")) {
327         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
328         ddc->tremor = CLAMP(dval, 0.0, 1.0);
329     } else if (!strcmp(key, "flatness")) {
330         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
331         ddc->flatness = CLAMP(dval, 0, 1.0);
332     } else if (!strcmp(key, "tracebackground")) {
333         ddc->trace_bg = (val && strcmp(val, "0"));
334     } else if (!strcmp(key, "usepressure")) {
335         ddc->usepressure = (val && strcmp(val, "0"));
336     } else if (!strcmp(key, "usetilt")) {
337         ddc->usetilt = (val && strcmp(val, "0"));
338     } else if (!strcmp(key, "abs_width")) {
339         ddc->abs_width = (val && strcmp(val, "0"));
340     } else if (!strcmp(key, "keep_selected")) {
341         ddc->keep_selected = (val && strcmp(val, "0"));
342     } else if (!strcmp(key, "cap_rounding")) {
343         ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
344     }
346     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
349 static double
350 flerp(double f0, double f1, double p)
352     return f0 + ( f1 - f0 ) * p;
355 /* Get normalized point */
356 static NR::Point
357 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
359     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
360     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
361     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
364 /* Get view point */
365 static NR::Point
366 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
368     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
369     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
370     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
373 static void
374 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
376     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
377     dc->vel = NR::Point(0,0);
378     dc->vel_max = 0;
379     dc->acc = NR::Point(0,0);
380     dc->ang = NR::Point(0,0);
381     dc->del = NR::Point(0,0);
384 static void
385 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
387     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
388         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
389     else
390         dc->pressure = DDC_DEFAULT_PRESSURE;
392     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
393         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
394     else
395         dc->xtilt = DDC_DEFAULT_TILT;
397     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
398         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
399     else
400         dc->ytilt = DDC_DEFAULT_TILT;
404 static gboolean
405 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
407     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
409     /* Calculate mass and drag */
410     double const mass = flerp(1.0, 160.0, dc->mass);
411     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
413     /* Calculate force and acceleration */
414     NR::Point force = n - dc->cur;
416     // If force is below the absolute threshold DYNA_EPSILON,
417     // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
418     // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
419     // discard this move. 
420     // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
421     // especially bothersome at the start of the stroke where we don't yet have the inertia to
422     // smooth them out.
423     if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
424         return FALSE;
425     }
427     dc->acc = force / mass;
429     /* Calculate new velocity */
430     dc->vel += dc->acc;
432     if (NR::L2(dc->vel) > dc->vel_max)
433         dc->vel_max = NR::L2(dc->vel);
435     /* Calculate angle of drawing tool */
437     double a1;
438     if (dc->usetilt) {
439         // 1a. calculate nib angle from input device tilt:
440         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
442         if (length > 0) {
443             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
444             a1 = atan2(ang1);
445         }
446         else
447             a1 = 0.0;
448     }
449     else {
450         // 1b. fixed dc->angle (absolutely flat nib):
451         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
452         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
453         a1 = atan2(ang1);
454     }
456     // 2. perpendicular to dc->vel (absolutely non-flat nib):
457     gdouble const mag_vel = NR::L2(dc->vel);
458     if ( mag_vel < DYNA_EPSILON ) {
459         return FALSE;
460     }
461     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
463     // 3. Average them using flatness parameter:
464     // calculate angles
465     double a2 = atan2(ang2);
466     // flip a2 to force it to be in the same half-circle as a1
467     bool flipped = false;
468     if (fabs (a2-a1) > 0.5*M_PI) {
469         a2 += M_PI;
470         flipped = true;
471     }
472     // normalize a2
473     if (a2 > M_PI)
474         a2 -= 2*M_PI;
475     if (a2 < -M_PI)
476         a2 += 2*M_PI;
477     // find the flatness-weighted bisector angle, unflip if a2 was flipped
478     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
479     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
481     // Try to detect a sudden flip when the new angle differs too much from the previous for the
482     // current velocity; in that case discard this move
483     double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
484     if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
485         return FALSE;
486     }
488     // convert to point
489     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
491 //    g_print ("force %g  acc %g  vel_max %g  vel %g  a1 %g  a2 %g  new_ang %g\n", NR::L2(force), NR::L2(dc->acc), dc->vel_max, NR::L2(dc->vel), a1, a2, new_ang);
493     /* Apply drag */
494     dc->vel *= 1.0 - drag;
496     /* Update position */
497     dc->last = dc->cur;
498     dc->cur += dc->vel;
500     return TRUE;
503 static void
504 sp_dyna_draw_brush(SPDynaDrawContext *dc)
506     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
508     // How much velocity thins strokestyle
509     double vel_thin = flerp (0, 160, dc->vel_thin);
511     // Influence of pressure on thickness
512     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
514     // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
515     // drag)
516     NR::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
517     NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush); 
519     double trace_thick = 1;
520     if (dc->trace_bg) {
521         // pick single pixel
522         NRPixBlock pb;
523         int x = (int) floor(brush_w[NR::X]);
524         int y = (int) floor(brush_w[NR::Y]);
525         nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
526         sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
527         const unsigned char *s = NR_PIXBLOCK_PX(&pb);
528         double R = s[0] / 255.0;
529         double G = s[1] / 255.0;
530         double B = s[2] / 255.0;
531         double A = s[3] / 255.0;
532         double max = MAX (MAX (R, G), B);
533         double min = MIN (MIN (R, G), B);
534         double L = A * (max + min)/2 + (1 - A); // blend with white bg
535         trace_thick = 1 - L;
536         //g_print ("L %g thick %g\n", L, trace_thick);
537     }
539     double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
541     double tremble_left = 0, tremble_right = 0;
542     if (dc->tremor > 0) {
543         // obtain two normally distributed random variables, using polar Box-Muller transform
544         double x1, x2, w, y1, y2;
545         do {
546             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
547             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
548             w = x1 * x1 + x2 * x2;
549         } while ( w >= 1.0 );
550         w = sqrt( (-2.0 * log( w ) ) / w );
551         y1 = x1 * w;
552         y2 = x2 * w;
554         // deflect both left and right edges randomly and independently, so that:
555         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
556         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
557         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
558         // comparatively smooth and slow ones excessively jittery
559         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
560         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
561     }
563     if ( width < 0.02 * dc->width ) {
564         width = 0.02 * dc->width;
565     }
567     double dezoomify_factor = 0.05 * 1000;
568     if (!dc->abs_width) {
569         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
570     }
572     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
573     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
575     dc->point1[dc->npoints] = brush + del_left;
576     dc->point2[dc->npoints] = brush - del_right;
578     dc->del = 0.5*(del_left + del_right);
580     dc->npoints++;
583 void
584 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
586     desktop->setToolboxAdjustmentValue (id, value);
589 static void
590 calligraphic_cancel(SPDynaDrawContext *dc)
592     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
593     dc->dragging = FALSE;
594     dc->is_drawing = false;
595     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
596             /* Remove all temporary line segments */
597             while (dc->segments) {
598                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
599                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
600             }
601             /* reset accumulated curve */
602             dc->accumulated->reset();
603             clear_current(dc);
604             if (dc->repr) {
605                 dc->repr = NULL;
606             }
610 gint
611 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
612                                   GdkEvent *event)
614     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
615     SPDesktop *desktop = event_context->desktop;
617     gint ret = FALSE;
619     switch (event->type) {
620         case GDK_BUTTON_PRESS:
621             if (event->button.button == 1 && !event_context->space_panning) {
623                 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
625                 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
626                     return TRUE;
627                 }
629                 NR::Point const button_w(event->button.x,
630                                          event->button.y);
631                 NR::Point const button_dt(desktop->w2d(button_w));
632                 sp_dyna_draw_reset(dc, button_dt);
633                 sp_dyna_draw_extinput(dc, event);
634                 sp_dyna_draw_apply(dc, button_dt);
635                 dc->accumulated->reset();
636                 if (dc->repr) {
637                     dc->repr = NULL;
638                 }
640                 /* initialize first point */
641                 dc->npoints = 0;
643                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
644                                     ( GDK_KEY_PRESS_MASK |
645                                       GDK_BUTTON_RELEASE_MASK |
646                                       GDK_POINTER_MOTION_MASK |
647                                       GDK_BUTTON_PRESS_MASK ),
648                                     NULL,
649                                     event->button.time);
651                 ret = TRUE;
653                 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
654                 dc->is_drawing = true;
655             }
656             break;
657         case GDK_MOTION_NOTIFY:
658         {
659             NR::Point const motion_w(event->motion.x,
660                                      event->motion.y);
661             NR::Point motion_dt(desktop->w2d(motion_w));
662             sp_dyna_draw_extinput(dc, event);
664             dc->_message_context->clear();
666             // for hatching:
667             double hatch_dist = 0;
668             NR::Point hatch_unit_vector(0,0);
669             NR::Point nearest(0,0);
670             NR::Point pointer(0,0);
671             NR::Matrix motion_to_curve(NR::identity());
673             if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
675                 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
676                 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
677                     // One item selected, and it's a path;
678                     // let's try to track it as a guide
680                     if (selected != dc->hatch_item) {
681                         dc->hatch_item = selected;
682                         if (dc->hatch_livarot_path)
683                             delete dc->hatch_livarot_path;
684                         dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
685                         dc->hatch_livarot_path->ConvertWithBackData(0.01);
686                     }
688                     // calculate pointer point in the guide item's coords
689                     motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
690                     pointer = motion_dt * motion_to_curve;
692                     // calculate the nearest point on the guide path
693                     NR::Maybe<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
694                     nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
697                     // distance from pointer to nearest
698                     hatch_dist = NR::L2(pointer - nearest);
699                     // unit-length vector
700                     hatch_unit_vector = (pointer - nearest)/hatch_dist;
702                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
703                 } else {
704                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
705                 }
706             } 
708             if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
709                 dc->dragging = TRUE;
711                 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
713 #define SPEED_ELEMENTS 12
714 #define SPEED_MIN 0.12
715 #define SPEED_NORMAL 0.65
717                     // speed is the movement of the nearest point along the guide path, divided by
718                     // the movement of the pointer at the same period; it is averaged for the last
719                     // SPEED_ELEMENTS motion events.  Normally, as you track the guide path, speed
720                     // is about 1, i.e. the nearest point on the path is moved by about the same
721                     // distance as the pointer. If the speed starts to decrease, we are losing
722                     // contact with the guide; if it drops below SPEED_MIN, we are on our own and
723                     // not attracted to guide anymore. Most often this happens when you have
724                     // tracked to the end of a guide calligraphic stroke and keep moving
725                     // further. We try to handle this situation gracefully: not stick with the
726                     // guide forever but let go of it smoothly and without sharp jerks (non-zero
727                     // mass recommended; with zero mass, jerks are still quite noticeable).
729                     double speed = 1;
730                     if (NR::L2(dc->hatch_last_nearest) != 0) {
731                         // the distance nearest moved since the last motion event
732                         double nearest_moved = NR::L2(nearest - dc->hatch_last_nearest);
733                         // the distance pointer moved since the last motion event
734                         double pointer_moved = NR::L2(pointer - dc->hatch_last_pointer);
735                         // store them in stacks limited to SPEED_ELEMENTS
736                         dc->hatch_nearest_past.push_front(nearest_moved);
737                         if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
738                             dc->hatch_nearest_past.pop_back();
739                         dc->hatch_pointer_past.push_front(pointer_moved);
740                         if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
741                             dc->hatch_pointer_past.pop_back();
743                         // If the stacks are full,
744                         if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
745                             // calculate the sums of all stored movements
746                             double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
747                             double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
748                             // and divide to get the speed
749                             speed = nearest_sum/pointer_sum;
750                             //g_print ("nearest sum %g  pointer_sum %g  speed %g\n", nearest_sum, pointer_sum, speed);
751                         }
752                     }
754                     if (   dc->hatch_escaped  // already escaped, do not reattach
755                         || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
756                         || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
757                         ) {
758                         // We are NOT attracted to the guide!
760                         //g_print ("\nlast_nearest %g %g   nearest %g %g  pointer %g %g  pos %d %g\n", dc->last_nearest[NR::X], dc->last_nearest[NR::Y], nearest[NR::X], nearest[NR::Y], pointer[NR::X], pointer[NR::Y], position->piece, position->t);
762                         // Remember hatch_escaped so we don't get
763                         // attracted again until the end of this stroke
764                         dc->hatch_escaped = true;
766                     } else {
768                         // Calculate angle cosine of this vector-to-guide and all past vectors
769                         // summed, to detect if we accidentally flipped to the other side of the
770                         // guide
771                         double dot = NR::dot (pointer - nearest, dc->hatch_vector_accumulated);
772                         dot /= NR::L2(pointer - nearest) * NR::L2(dc->hatch_vector_accumulated);
774                         if (dc->hatch_spacing != 0) { // spacing was already set
775                             double target;
776                             if (speed > SPEED_NORMAL) {
777                                 // all ok, strictly obey the spacing
778                                 target = dc->hatch_spacing;
779                             } else {
780                                 // looks like we're starting to lose speed,
781                                 // so _gradually_ let go attraction to prevent jerks
782                                 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;                            
783                             }
784                             if (!isNaN(dot) && dot < -0.5) {// flip
785                                 target = -target;
786                             }
788                             // This is the track pointer that we will use instead of the real one
789                             NR::Point new_pointer = nearest + target * hatch_unit_vector;
791                             // some limited feedback: allow persistent pulling to slightly change
792                             // the spacing
793                             dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
795                             // return it to the desktop coords
796                             motion_dt = new_pointer * motion_to_curve.inverse();
798                         } else {
799                             // this is the first motion event, set the dist 
800                             dc->hatch_spacing = hatch_dist;
801                         }
803                         // remember last points
804                         dc->hatch_last_pointer = pointer;
805                         dc->hatch_last_nearest = nearest;
806                         dc->hatch_vector_accumulated += (pointer - nearest);
807                     }
809                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
811                 } else {
812                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
813                 }
815                 if (!sp_dyna_draw_apply(dc, motion_dt)) {
816                     ret = TRUE;
817                     break;
818                 }
820                 if ( dc->cur != dc->last ) {
821                     sp_dyna_draw_brush(dc);
822                     g_assert( dc->npoints > 0 );
823                     fit_and_split(dc, FALSE);
824                 }
825                 ret = TRUE;
826             }
828             // Draw the hatching circle if necessary
829             if (event->motion.state & GDK_CONTROL_MASK) { 
830                 if (dc->hatch_spacing == 0 && hatch_dist != 0) { 
831                     // Haven't set spacing yet: gray, center free, update radius live
832                     NR::Point c = desktop->w2d(motion_w);
833                     NR::Matrix const sm (NR::scale(hatch_dist, hatch_dist) * NR::translate(c));
834                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
835                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
836                     sp_canvas_item_show(dc->hatch_area);
837                 } else if (dc->dragging && !dc->hatch_escaped) {
838                     // Tracking: green, center snapped, fixed radius
839                     NR::Point c = motion_dt;
840                     NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
841                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
842                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
843                     sp_canvas_item_show(dc->hatch_area);
844                 } else if (dc->dragging && dc->hatch_escaped) {
845                     // Tracking escaped: red, center free, fixed radius
846                     NR::Point c = desktop->w2d(motion_w);
847                     NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
849                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
850                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
851                     sp_canvas_item_show(dc->hatch_area);
852                 } else {
853                     // Not drawing but spacing set: gray, center snapped, fixed radius
854                     NR::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
855                     if (!isNaN(c[NR::X]) && !isNaN(c[NR::Y])) {
856                         NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
857                         sp_canvas_item_affine_absolute(dc->hatch_area, sm);
858                         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
859                         sp_canvas_item_show(dc->hatch_area);
860                     }
861                 }
862             } else {
863                 sp_canvas_item_hide(dc->hatch_area);
864             }
865         }
866         break;
869     case GDK_BUTTON_RELEASE:
870     {
871         NR::Point const motion_w(event->button.x, event->button.y);
872         NR::Point const motion_dt(desktop->w2d(motion_w));
874         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
875         sp_canvas_end_forced_full_redraws(desktop->canvas);
876         dc->is_drawing = false;
878         if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
879             dc->dragging = FALSE;
881             sp_dyna_draw_apply(dc, motion_dt);
883             /* Remove all temporary line segments */
884             while (dc->segments) {
885                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
886                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
887             }
889             /* Create object */
890             fit_and_split(dc, TRUE);
891             accumulate_calligraphic(dc);
892             set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
894             /* reset accumulated curve */
895             dc->accumulated->reset();
897             clear_current(dc);
898             if (dc->repr) {
899                 dc->repr = NULL;
900             }
902             if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
903             if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
904             dc->hatch_last_nearest = NR::Point(0,0);
905             dc->hatch_last_pointer = NR::Point(0,0);
906             dc->hatch_vector_accumulated = NR::Point(0,0);
907             dc->hatch_escaped = false;
908             dc->hatch_item = NULL;
909             dc->hatch_livarot_path = NULL;
911             if (dc->hatch_spacing != 0 && !dc->keep_selected) { 
912                 // we do not select the newly drawn path, so increase spacing by step
913                 if (dc->hatch_spacing_step == 0) {
914                     dc->hatch_spacing_step = dc->hatch_spacing;
915                 }
916                 dc->hatch_spacing += dc->hatch_spacing_step;
917             }
919             dc->_message_context->clear();
920             ret = TRUE;
921         }
922         break;
923     }
925     case GDK_KEY_PRESS:
926         switch (get_group0_keyval (&event->key)) {
927         case GDK_Up:
928         case GDK_KP_Up:
929             if (!MOD__CTRL_ONLY) {
930                 dc->angle += 5.0;
931                 if (dc->angle > 90.0)
932                     dc->angle = 90.0;
933                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
934                 ret = TRUE;
935             }
936             break;
937         case GDK_Down:
938         case GDK_KP_Down:
939             if (!MOD__CTRL_ONLY) {
940                 dc->angle -= 5.0;
941                 if (dc->angle < -90.0)
942                     dc->angle = -90.0;
943                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
944                 ret = TRUE;
945             }
946             break;
947         case GDK_Right:
948         case GDK_KP_Right:
949             if (!MOD__CTRL_ONLY) {
950                 dc->width += 0.01;
951                 if (dc->width > 1.0)
952                     dc->width = 1.0;
953                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
954                 ret = TRUE;
955             }
956             break;
957         case GDK_Left:
958         case GDK_KP_Left:
959             if (!MOD__CTRL_ONLY) {
960                 dc->width -= 0.01;
961                 if (dc->width < 0.01)
962                     dc->width = 0.01;
963                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
964                 ret = TRUE;
965             }
966             break;
967         case GDK_Home:
968         case GDK_KP_Home:
969             dc->width = 0.01;
970             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
971             ret = TRUE;
972             break;
973         case GDK_End:
974         case GDK_KP_End:
975             dc->width = 1.0;
976             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
977             ret = TRUE;
978             break;
979         case GDK_x:
980         case GDK_X:
981             if (MOD__ALT_ONLY) {
982                 desktop->setToolboxFocusTo ("altx-calligraphy");
983                 ret = TRUE;
984             }
985             break;
986         case GDK_Escape:
987             if (dc->is_drawing) {
988                 // if drawing, cancel, otherwise pass it up for deselecting
989                 calligraphic_cancel (dc);
990                 ret = TRUE;
991             }
992             break;
993         case GDK_z:
994         case GDK_Z:
995             if (MOD__CTRL_ONLY && dc->is_drawing) {
996                 // if drawing, cancel, otherwise pass it up for undo
997                 calligraphic_cancel (dc);
998                 ret = TRUE;
999             }
1000             break;
1001         default:
1002             break;
1003         }
1004         break;
1006     case GDK_KEY_RELEASE:
1007         switch (get_group0_keyval(&event->key)) {
1008             case GDK_Control_L:
1009             case GDK_Control_R:
1010                 dc->_message_context->clear();
1011                 dc->hatch_spacing = 0;
1012                 dc->hatch_spacing_step = 0;
1013                 break;
1014             default:
1015                 break;
1016         }
1018     default:
1019         break;
1020     }
1022     if (!ret) {
1023         if (((SPEventContextClass *) parent_class)->root_handler) {
1024             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1025         }
1026     }
1028     return ret;
1032 static void
1033 clear_current(SPDynaDrawContext *dc)
1035     /* reset bpath */
1036     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
1037     /* reset curve */
1038     dc->currentcurve->reset();
1039     dc->cal1->reset();
1040     dc->cal2->reset();
1041     /* reset points */
1042     dc->npoints = 0;
1045 static void
1046 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
1048     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1050     if (!dc->accumulated->is_empty()) {
1051         NArtBpath *abp;
1052         gchar *str;
1054         if (!dc->repr) {
1055             /* Create object */
1056             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1057             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1059             /* Set style */
1060             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
1062             dc->repr = repr;
1064             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1065             Inkscape::GC::release(dc->repr);
1066             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
1067             item->updateRepr();
1068         }
1069         abp = nr_artpath_affine(dc->accumulated->first_bpath(), sp_desktop_dt2root_affine(desktop));
1070         str = sp_svg_write_path(abp);
1071         g_assert( str != NULL );
1072         g_free(abp);
1073         dc->repr->setAttribute("d", str);
1074         g_free(str);
1076         if (unionize) {
1077             sp_desktop_selection(desktop)->add(dc->repr);
1078             sp_selected_path_union_skip_undo();
1079         } else {
1080             if (dc->keep_selected) {
1081                 sp_desktop_selection(desktop)->set(dc->repr);
1082             } 
1083         }
1085     } else {
1086         if (dc->repr) {
1087             sp_repr_unparent(dc->repr);
1088         }
1089         dc->repr = NULL;
1090     }
1092     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC, 
1093                      _("Draw calligraphic stroke"));
1096 static void
1097 add_cap(SPCurve *curve,
1098         NR::Point const &pre, NR::Point const &from,
1099         NR::Point const &to, NR::Point const &post,
1100         double rounding)
1102     NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
1103     double mag = NR::L2(vel);
1105     NR::Point v_in = from - pre;
1106     double mag_in = NR::L2(v_in);
1107     if ( mag_in > DYNA_EPSILON ) {
1108         v_in = mag * v_in / mag_in;
1109     } else {
1110         v_in = NR::Point(0, 0);
1111     }
1113     NR::Point v_out = to - post;
1114     double mag_out = NR::L2(v_out);
1115     if ( mag_out > DYNA_EPSILON ) {
1116         v_out = mag * v_out / mag_out;
1117     } else {
1118         v_out = NR::Point(0, 0);
1119     }
1121     if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
1122         curve->curveto(from + v_in, to + v_out, to);
1123     }
1126 static void
1127 accumulate_calligraphic(SPDynaDrawContext *dc)
1129     if ( !dc->cal1->is_empty() && !dc->cal2->is_empty() ) {
1130         dc->accumulated->reset(); /*  Is this required ?? */
1131         SPCurve *rev_cal2 = dc->cal2->create_reverse();
1133         g_assert(dc->cal1->_end > 1);
1134         g_assert(rev_cal2->_end > 1);
1135         g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
1136         g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
1137         g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
1138         g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
1139         g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->_end-1)->code == NR_CURVETO);
1140         g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->_end-1)->code == NR_CURVETO);
1142         dc->accumulated->append(dc->cal1, FALSE);
1144         add_cap(dc->accumulated, SP_CURVE_SEGMENT(dc->cal1, dc->cal1->_end-1)->c(2), SP_CURVE_SEGMENT(dc->cal1, dc->cal1->_end-1)->c(3), SP_CURVE_SEGMENT(rev_cal2, 0)->c(3), SP_CURVE_SEGMENT(rev_cal2, 1)->c(1), dc->cap_rounding);
1146         dc->accumulated->append(rev_cal2, TRUE);
1148         add_cap(dc->accumulated, SP_CURVE_SEGMENT(rev_cal2, rev_cal2->_end-1)->c(2), SP_CURVE_SEGMENT(rev_cal2, rev_cal2->_end-1)->c(3), SP_CURVE_SEGMENT(dc->cal1, 0)->c(3), SP_CURVE_SEGMENT(dc->cal1, 1)->c(1), dc->cap_rounding);
1150         dc->accumulated->closepath();
1152         rev_cal2->unref();
1154         dc->cal1->reset();
1155         dc->cal2->reset();
1156     }
1159 static double square(double const x)
1161     return x * x;
1164 static void
1165 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1167     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
1169 #ifdef DYNA_DRAW_VERBOSE
1170     g_print("[F&S:R=%c]", release?'T':'F');
1171 #endif
1173     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1174         return; // just clicked
1176     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1177 #define BEZIER_SIZE       4
1178 #define BEZIER_MAX_BEZIERS  8
1179 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1181 #ifdef DYNA_DRAW_VERBOSE
1182         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1183                 dc->npoints, release ? "TRUE" : "FALSE");
1184 #endif
1186         /* Current calligraphic */
1187         if ( dc->cal1->_end == 0 || dc->cal2->_end == 0 ) {
1188             /* dc->npoints > 0 */
1189             /* g_print("calligraphics(1|2) reset\n"); */
1190             dc->cal1->reset();
1191             dc->cal2->reset();
1193             dc->cal1->moveto(dc->point1[0]);
1194             dc->cal2->moveto(dc->point2[0]);
1195         }
1197         NR::Point b1[BEZIER_MAX_LENGTH];
1198         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1199                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1200         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1202         NR::Point b2[BEZIER_MAX_LENGTH];
1203         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1204                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1205         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1207         if ( nb1 != -1 && nb2 != -1 ) {
1208             /* Fit and draw and reset state */
1209 #ifdef DYNA_DRAW_VERBOSE
1210             g_print("nb1:%d nb2:%d\n", nb1, nb2);
1211 #endif
1212             /* CanvasShape */
1213             if (! release) {
1214                 dc->currentcurve->reset();
1215                 dc->currentcurve->moveto(b1[0]);
1216                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1217                     dc->currentcurve->curveto(bp1[1],
1218                                      bp1[2], bp1[3]);
1219                 }
1220                 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
1221                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1222                     dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
1223                 }
1224                 // FIXME: dc->segments is always NULL at this point??
1225                 if (!dc->segments) { // first segment
1226                     add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1227                 }
1228                 dc->currentcurve->closepath();
1229                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1230             }
1232             /* Current calligraphic */
1233             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1234                 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
1235             }
1236             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1237                 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
1238             }
1239         } else {
1240             /* fixme: ??? */
1241 #ifdef DYNA_DRAW_VERBOSE
1242             g_print("[fit_and_split] failed to fit-cubic.\n");
1243 #endif
1244             draw_temporary_box(dc);
1246             for (gint i = 1; i < dc->npoints; i++) {
1247                 dc->cal1->lineto(dc->point1[i]);
1248             }
1249             for (gint i = 1; i < dc->npoints; i++) {
1250                 dc->cal2->lineto(dc->point2[i]);
1251             }
1252         }
1254         /* Fit and draw and copy last point */
1255 #ifdef DYNA_DRAW_VERBOSE
1256         g_print("[%d]Yup\n", dc->npoints);
1257 #endif
1258         if (!release) {
1259             g_assert(!dc->currentcurve->is_empty());
1261             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1262                                                    SP_TYPE_CANVAS_BPATH,
1263                                                    NULL);
1264             SPCurve *curve = dc->currentcurve->copy();
1265             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1266             curve->unref();
1268             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1269             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1270             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
1271             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1272             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1273             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1274             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1275             //sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), ((strokeColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*strokeOpacity)), 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1276             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1277             /* fixme: Cannot we cascade it to root more clearly? */
1278             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1280             dc->segments = g_slist_prepend(dc->segments, cbp);
1281         }
1283         dc->point1[0] = dc->point1[dc->npoints - 1];
1284         dc->point2[0] = dc->point2[dc->npoints - 1];
1285         dc->npoints = 1;
1286     } else {
1287         draw_temporary_box(dc);
1288     }
1291 static void
1292 draw_temporary_box(SPDynaDrawContext *dc)
1294     dc->currentcurve->reset();
1296     dc->currentcurve->moveto(dc->point1[dc->npoints-1]);
1297     for (gint i = dc->npoints-2; i >= 0; i--) {
1298         dc->currentcurve->lineto(dc->point1[i]);
1299     }
1300     for (gint i = 0; i < dc->npoints; i++) {
1301         dc->currentcurve->lineto(dc->point2[i]);
1302     }
1303     if (dc->npoints >= 2) {
1304         add_cap(dc->currentcurve, dc->point2[dc->npoints-2], dc->point2[dc->npoints-1], dc->point1[dc->npoints-1], dc->point1[dc->npoints-2], dc->cap_rounding);
1305     }
1307     dc->currentcurve->closepath();
1308     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1311 /*
1312   Local Variables:
1313   mode:c++
1314   c-file-style:"stroustrup"
1315   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1316   indent-tabs-mode:nil
1317   fill-column:99
1318   End:
1319 */
1320 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :