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"
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 GtkType
123 sp_dyna_draw_context_get_type(void)
124 {
125 static GType type = 0;
126 if (!type) {
127 GTypeInfo info = {
128 sizeof(SPDynaDrawContextClass),
129 NULL, NULL,
130 (GClassInitFunc) sp_dyna_draw_context_class_init,
131 NULL, NULL,
132 sizeof(SPDynaDrawContext),
133 4,
134 (GInstanceInitFunc) sp_dyna_draw_context_init,
135 NULL, /* value_table */
136 };
137 type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
138 }
139 return type;
140 }
142 static void
143 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
144 {
145 GObjectClass *object_class = (GObjectClass *) klass;
146 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
148 parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
150 object_class->dispose = sp_dyna_draw_context_dispose;
152 event_context_class->setup = sp_dyna_draw_context_setup;
153 event_context_class->set = sp_dyna_draw_context_set;
154 event_context_class->root_handler = sp_dyna_draw_context_root_handler;
155 }
157 static void
158 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
159 {
160 SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
162 event_context->cursor_shape = cursor_calligraphy_xpm;
163 event_context->hot_x = 4;
164 event_context->hot_y = 4;
166 ddc->accumulated = NULL;
167 ddc->segments = NULL;
168 ddc->currentcurve = NULL;
169 ddc->currentshape = NULL;
170 ddc->npoints = 0;
171 ddc->cal1 = NULL;
172 ddc->cal2 = NULL;
173 ddc->repr = NULL;
175 /* DynaDraw values */
176 ddc->cur = NR::Point(0,0);
177 ddc->last = NR::Point(0,0);
178 ddc->vel = NR::Point(0,0);
179 ddc->vel_max = 0;
180 ddc->acc = NR::Point(0,0);
181 ddc->ang = NR::Point(0,0);
182 ddc->del = NR::Point(0,0);
184 /* attributes */
185 ddc->dragging = FALSE;
187 ddc->mass = 0.3;
188 ddc->drag = DRAG_DEFAULT;
189 ddc->angle = 30.0;
190 ddc->width = 0.2;
191 ddc->pressure = DDC_DEFAULT_PRESSURE;
193 ddc->vel_thin = 0.1;
194 ddc->flatness = 0.9;
195 ddc->cap_rounding = 0.0;
197 ddc->abs_width = false;
198 ddc->keep_selected = true;
200 ddc->hatch_spacing = 0;
201 ddc->hatch_spacing_step = 0;
202 new (&ddc->hatch_pointer_past) std::list<double>();
203 new (&ddc->hatch_nearest_past) std::list<double>();
204 ddc->hatch_last_nearest = NR::Point(0,0);
205 ddc->hatch_last_pointer = NR::Point(0,0);
206 ddc->hatch_vector_accumulated = NR::Point(0,0);
207 ddc->hatch_escaped = false;
208 ddc->hatch_area = NULL;
209 ddc->hatch_item = NULL;
210 ddc->hatch_livarot_path = NULL;
212 ddc->trace_bg = false;
213 }
215 static void
216 sp_dyna_draw_context_dispose(GObject *object)
217 {
218 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
220 if (ddc->hatch_area) {
221 gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
222 ddc->hatch_area = NULL;
223 }
225 if (ddc->accumulated) {
226 ddc->accumulated = sp_curve_unref(ddc->accumulated);
227 }
229 while (ddc->segments) {
230 gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
231 ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
232 }
234 if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
235 if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
236 if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
238 if (ddc->currentshape) {
239 gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
240 ddc->currentshape = NULL;
241 }
243 if (ddc->_message_context) {
244 delete ddc->_message_context;
245 }
247 G_OBJECT_CLASS(parent_class)->dispose(object);
249 ddc->hatch_pointer_past.~list();
250 ddc->hatch_nearest_past.~list();
251 }
253 static void
254 sp_dyna_draw_context_setup(SPEventContext *ec)
255 {
256 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
258 if (((SPEventContextClass *) parent_class)->setup)
259 ((SPEventContextClass *) parent_class)->setup(ec);
261 ddc->accumulated = sp_curve_new_sized(32);
262 ddc->currentcurve = sp_curve_new_sized(4);
264 ddc->cal1 = sp_curve_new_sized(32);
265 ddc->cal2 = sp_curve_new_sized(32);
267 ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
268 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
269 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
270 /* fixme: Cannot we cascade it to root more clearly? */
271 g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
273 {
274 SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
275 ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
276 sp_curve_unref(c);
277 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
278 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
279 sp_canvas_item_hide(ddc->hatch_area);
280 }
282 sp_event_context_read(ec, "mass");
283 sp_event_context_read(ec, "wiggle");
284 sp_event_context_read(ec, "angle");
285 sp_event_context_read(ec, "width");
286 sp_event_context_read(ec, "thinning");
287 sp_event_context_read(ec, "tremor");
288 sp_event_context_read(ec, "flatness");
289 sp_event_context_read(ec, "tracebackground");
290 sp_event_context_read(ec, "usepressure");
291 sp_event_context_read(ec, "usetilt");
292 sp_event_context_read(ec, "abs_width");
293 sp_event_context_read(ec, "keep_selected");
294 sp_event_context_read(ec, "cap_rounding");
296 ddc->is_drawing = false;
298 ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
300 if (prefs_get_int_attribute("tools.calligraphic", "selcue", 0) != 0) {
301 ec->enableSelectionCue();
302 }
303 }
305 static void
306 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
307 {
308 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
310 if (!strcmp(key, "mass")) {
311 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
312 ddc->mass = CLAMP(dval, -1000.0, 1000.0);
313 } else if (!strcmp(key, "wiggle")) {
314 double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
315 ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
316 } else if (!strcmp(key, "angle")) {
317 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
318 ddc->angle = CLAMP (dval, -90, 90);
319 } else if (!strcmp(key, "width")) {
320 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
321 ddc->width = CLAMP(dval, -1000.0, 1000.0);
322 } else if (!strcmp(key, "thinning")) {
323 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
324 ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
325 } else if (!strcmp(key, "tremor")) {
326 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
327 ddc->tremor = CLAMP(dval, 0.0, 1.0);
328 } else if (!strcmp(key, "flatness")) {
329 double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
330 ddc->flatness = CLAMP(dval, 0, 1.0);
331 } else if (!strcmp(key, "tracebackground")) {
332 ddc->trace_bg = (val && strcmp(val, "0"));
333 } else if (!strcmp(key, "usepressure")) {
334 ddc->usepressure = (val && strcmp(val, "0"));
335 } else if (!strcmp(key, "usetilt")) {
336 ddc->usetilt = (val && strcmp(val, "0"));
337 } else if (!strcmp(key, "abs_width")) {
338 ddc->abs_width = (val && strcmp(val, "0"));
339 } else if (!strcmp(key, "keep_selected")) {
340 ddc->keep_selected = (val && strcmp(val, "0"));
341 } else if (!strcmp(key, "cap_rounding")) {
342 ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
343 }
345 //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
346 }
348 static double
349 flerp(double f0, double f1, double p)
350 {
351 return f0 + ( f1 - f0 ) * p;
352 }
354 /* Get normalized point */
355 static NR::Point
356 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
357 {
358 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
359 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
360 return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
361 }
363 /* Get view point */
364 static NR::Point
365 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
366 {
367 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
368 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
369 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
370 }
372 static void
373 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
374 {
375 dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
376 dc->vel = NR::Point(0,0);
377 dc->vel_max = 0;
378 dc->acc = NR::Point(0,0);
379 dc->ang = NR::Point(0,0);
380 dc->del = NR::Point(0,0);
381 }
383 static void
384 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
385 {
386 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
387 dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
388 else
389 dc->pressure = DDC_DEFAULT_PRESSURE;
391 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
392 dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
393 else
394 dc->xtilt = DDC_DEFAULT_TILT;
396 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
397 dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
398 else
399 dc->ytilt = DDC_DEFAULT_TILT;
400 }
403 static gboolean
404 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
405 {
406 NR::Point n = sp_dyna_draw_get_npoint(dc, p);
408 /* Calculate mass and drag */
409 double const mass = flerp(1.0, 160.0, dc->mass);
410 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
412 /* Calculate force and acceleration */
413 NR::Point force = n - dc->cur;
415 // If force is below the absolute threshold DYNA_EPSILON,
416 // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
417 // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
418 // discard this move.
419 // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
420 // especially bothersome at the start of the stroke where we don't yet have the inertia to
421 // smooth them out.
422 if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
423 return FALSE;
424 }
426 dc->acc = force / mass;
428 /* Calculate new velocity */
429 dc->vel += dc->acc;
431 if (NR::L2(dc->vel) > dc->vel_max)
432 dc->vel_max = NR::L2(dc->vel);
434 /* Calculate angle of drawing tool */
436 double a1;
437 if (dc->usetilt) {
438 // 1a. calculate nib angle from input device tilt:
439 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
441 if (length > 0) {
442 NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
443 a1 = atan2(ang1);
444 }
445 else
446 a1 = 0.0;
447 }
448 else {
449 // 1b. fixed dc->angle (absolutely flat nib):
450 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
451 NR::Point ang1 = NR::Point(-sin(radians), cos(radians));
452 a1 = atan2(ang1);
453 }
455 // 2. perpendicular to dc->vel (absolutely non-flat nib):
456 gdouble const mag_vel = NR::L2(dc->vel);
457 if ( mag_vel < DYNA_EPSILON ) {
458 return FALSE;
459 }
460 NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
462 // 3. Average them using flatness parameter:
463 // calculate angles
464 double a2 = atan2(ang2);
465 // flip a2 to force it to be in the same half-circle as a1
466 bool flipped = false;
467 if (fabs (a2-a1) > 0.5*M_PI) {
468 a2 += M_PI;
469 flipped = true;
470 }
471 // normalize a2
472 if (a2 > M_PI)
473 a2 -= 2*M_PI;
474 if (a2 < -M_PI)
475 a2 += 2*M_PI;
476 // find the flatness-weighted bisector angle, unflip if a2 was flipped
477 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
478 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
480 // Try to detect a sudden flip when the new angle differs too much from the previous for the
481 // current velocity; in that case discard this move
482 double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
483 if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
484 return FALSE;
485 }
487 // convert to point
488 dc->ang = NR::Point (cos (new_ang), sin (new_ang));
490 // 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);
492 /* Apply drag */
493 dc->vel *= 1.0 - drag;
495 /* Update position */
496 dc->last = dc->cur;
497 dc->cur += dc->vel;
499 return TRUE;
500 }
502 static void
503 sp_dyna_draw_brush(SPDynaDrawContext *dc)
504 {
505 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
507 // How much velocity thins strokestyle
508 double vel_thin = flerp (0, 160, dc->vel_thin);
510 // Influence of pressure on thickness
511 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
513 // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
514 // drag)
515 NR::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
516 NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
518 double trace_thick = 1;
519 if (dc->trace_bg) {
520 // pick single pixel
521 NRPixBlock pb;
522 int x = (int) floor(brush_w[NR::X]);
523 int y = (int) floor(brush_w[NR::Y]);
524 nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
525 sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
526 const unsigned char *s = NR_PIXBLOCK_PX(&pb);
527 double R = s[0] / 255.0;
528 double G = s[1] / 255.0;
529 double B = s[2] / 255.0;
530 double A = s[3] / 255.0;
531 double max = MAX (MAX (R, G), B);
532 double min = MIN (MIN (R, G), B);
533 double L = A * (max + min)/2 + (1 - A); // blend with white bg
534 trace_thick = 1 - L;
535 //g_print ("L %g thick %g\n", L, trace_thick);
536 }
538 double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
540 double tremble_left = 0, tremble_right = 0;
541 if (dc->tremor > 0) {
542 // obtain two normally distributed random variables, using polar Box-Muller transform
543 double x1, x2, w, y1, y2;
544 do {
545 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
546 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
547 w = x1 * x1 + x2 * x2;
548 } while ( w >= 1.0 );
549 w = sqrt( (-2.0 * log( w ) ) / w );
550 y1 = x1 * w;
551 y2 = x2 * w;
553 // deflect both left and right edges randomly and independently, so that:
554 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
555 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
556 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
557 // comparatively smooth and slow ones excessively jittery
558 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
559 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
560 }
562 if ( width < 0.02 * dc->width ) {
563 width = 0.02 * dc->width;
564 }
566 double dezoomify_factor = 0.05 * 1000;
567 if (!dc->abs_width) {
568 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
569 }
571 NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
572 NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
574 dc->point1[dc->npoints] = brush + del_left;
575 dc->point2[dc->npoints] = brush - del_right;
577 dc->del = 0.5*(del_left + del_right);
579 dc->npoints++;
580 }
582 void
583 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
584 {
585 desktop->setToolboxAdjustmentValue (id, value);
586 }
588 static void
589 calligraphic_cancel(SPDynaDrawContext *dc)
590 {
591 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
592 dc->dragging = FALSE;
593 dc->is_drawing = false;
594 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
595 /* Remove all temporary line segments */
596 while (dc->segments) {
597 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
598 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
599 }
600 /* reset accumulated curve */
601 sp_curve_reset(dc->accumulated);
602 clear_current(dc);
603 if (dc->repr) {
604 dc->repr = NULL;
605 }
606 }
609 gint
610 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
611 GdkEvent *event)
612 {
613 SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
614 SPDesktop *desktop = event_context->desktop;
616 gint ret = FALSE;
618 switch (event->type) {
619 case GDK_BUTTON_PRESS:
620 if (event->button.button == 1 && !event_context->space_panning) {
622 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
624 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
625 return TRUE;
626 }
628 NR::Point const button_w(event->button.x,
629 event->button.y);
630 NR::Point const button_dt(desktop->w2d(button_w));
631 sp_dyna_draw_reset(dc, button_dt);
632 sp_dyna_draw_extinput(dc, event);
633 sp_dyna_draw_apply(dc, button_dt);
634 sp_curve_reset(dc->accumulated);
635 if (dc->repr) {
636 dc->repr = NULL;
637 }
639 /* initialize first point */
640 dc->npoints = 0;
642 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
643 ( GDK_KEY_PRESS_MASK |
644 GDK_BUTTON_RELEASE_MASK |
645 GDK_POINTER_MOTION_MASK |
646 GDK_BUTTON_PRESS_MASK ),
647 NULL,
648 event->button.time);
650 ret = TRUE;
652 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
653 dc->is_drawing = true;
654 }
655 break;
656 case GDK_MOTION_NOTIFY:
657 {
658 NR::Point const motion_w(event->motion.x,
659 event->motion.y);
660 NR::Point motion_dt(desktop->w2d(motion_w));
661 sp_dyna_draw_extinput(dc, event);
663 dc->_message_context->clear();
665 // for hatching:
666 double hatch_dist = 0;
667 NR::Point hatch_unit_vector(0,0);
668 NR::Point nearest(0,0);
669 NR::Point pointer(0,0);
670 NR::Matrix motion_to_curve(NR::identity());
672 if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
674 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
675 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
676 // One item selected, and it's a path;
677 // let's try to track it as a guide
679 if (selected != dc->hatch_item) {
680 dc->hatch_item = selected;
681 if (dc->hatch_livarot_path)
682 delete dc->hatch_livarot_path;
683 dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
684 dc->hatch_livarot_path->ConvertWithBackData(0.01);
685 }
687 // calculate pointer point in the guide item's coords
688 motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
689 pointer = motion_dt * motion_to_curve;
691 // calculate the nearest point on the guide path
692 NR::Maybe<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
693 nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
696 // distance from pointer to nearest
697 hatch_dist = NR::L2(pointer - nearest);
698 // unit-length vector
699 hatch_unit_vector = (pointer - nearest)/hatch_dist;
701 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
702 } else {
703 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
704 }
705 }
707 if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
708 dc->dragging = TRUE;
710 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
712 #define SPEED_ELEMENTS 12
713 #define SPEED_MIN 0.12
714 #define SPEED_NORMAL 0.65
716 // speed is the movement of the nearest point along the guide path, divided by
717 // the movement of the pointer at the same period; it is averaged for the last
718 // SPEED_ELEMENTS motion events. Normally, as you track the guide path, speed
719 // is about 1, i.e. the nearest point on the path is moved by about the same
720 // distance as the pointer. If the speed starts to decrease, we are losing
721 // contact with the guide; if it drops below SPEED_MIN, we are on our own and
722 // not attracted to guide anymore. Most often this happens when you have
723 // tracked to the end of a guide calligraphic stroke and keep moving
724 // further. We try to handle this situation gracefully: not stick with the
725 // guide forever but let go of it smoothly and without sharp jerks (non-zero
726 // mass recommended; with zero mass, jerks are still quite noticeable).
728 double speed = 1;
729 if (NR::L2(dc->hatch_last_nearest) != 0) {
730 // the distance nearest moved since the last motion event
731 double nearest_moved = NR::L2(nearest - dc->hatch_last_nearest);
732 // the distance pointer moved since the last motion event
733 double pointer_moved = NR::L2(pointer - dc->hatch_last_pointer);
734 // store them in stacks limited to SPEED_ELEMENTS
735 dc->hatch_nearest_past.push_front(nearest_moved);
736 if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
737 dc->hatch_nearest_past.pop_back();
738 dc->hatch_pointer_past.push_front(pointer_moved);
739 if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
740 dc->hatch_pointer_past.pop_back();
742 // If the stacks are full,
743 if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
744 // calculate the sums of all stored movements
745 double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
746 double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
747 // and divide to get the speed
748 speed = nearest_sum/pointer_sum;
749 //g_print ("nearest sum %g pointer_sum %g speed %g\n", nearest_sum, pointer_sum, speed);
750 }
751 }
753 if ( dc->hatch_escaped // already escaped, do not reattach
754 || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
755 || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
756 ) {
757 // We are NOT attracted to the guide!
759 //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);
761 // Remember hatch_escaped so we don't get
762 // attracted again until the end of this stroke
763 dc->hatch_escaped = true;
765 } else {
767 // Calculate angle cosine of this vector-to-guide and all past vectors
768 // summed, to detect if we accidentally flipped to the other side of the
769 // guide
770 double dot = NR::dot (pointer - nearest, dc->hatch_vector_accumulated);
771 dot /= NR::L2(pointer - nearest) * NR::L2(dc->hatch_vector_accumulated);
773 if (dc->hatch_spacing != 0) { // spacing was already set
774 double target;
775 if (speed > SPEED_NORMAL) {
776 // all ok, strictly obey the spacing
777 target = dc->hatch_spacing;
778 } else {
779 // looks like we're starting to lose speed,
780 // so _gradually_ let go attraction to prevent jerks
781 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;
782 }
783 if (!isNaN(dot) && dot < -0.5) {// flip
784 target = -target;
785 }
787 // This is the track pointer that we will use instead of the real one
788 NR::Point new_pointer = nearest + target * hatch_unit_vector;
790 // some limited feedback: allow persistent pulling to slightly change
791 // the spacing
792 dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
794 // return it to the desktop coords
795 motion_dt = new_pointer * motion_to_curve.inverse();
797 } else {
798 // this is the first motion event, set the dist
799 dc->hatch_spacing = hatch_dist;
800 }
802 // remember last points
803 dc->hatch_last_pointer = pointer;
804 dc->hatch_last_nearest = nearest;
805 dc->hatch_vector_accumulated += (pointer - nearest);
806 }
808 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
810 } else {
811 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
812 }
814 if (!sp_dyna_draw_apply(dc, motion_dt)) {
815 ret = TRUE;
816 break;
817 }
819 if ( dc->cur != dc->last ) {
820 sp_dyna_draw_brush(dc);
821 g_assert( dc->npoints > 0 );
822 fit_and_split(dc, FALSE);
823 }
824 ret = TRUE;
825 }
827 // Draw the hatching circle if necessary
828 if (event->motion.state & GDK_CONTROL_MASK) {
829 if (dc->hatch_spacing == 0 && hatch_dist != 0) {
830 // Haven't set spacing yet: gray, center free, update radius live
831 NR::Point c = desktop->w2d(motion_w);
832 NR::Matrix const sm (NR::scale(hatch_dist, hatch_dist) * NR::translate(c));
833 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
834 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
835 sp_canvas_item_show(dc->hatch_area);
836 } else if (dc->dragging && !dc->hatch_escaped) {
837 // Tracking: green, center snapped, fixed radius
838 NR::Point c = motion_dt;
839 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
840 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
841 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
842 sp_canvas_item_show(dc->hatch_area);
843 } else if (dc->dragging && dc->hatch_escaped) {
844 // Tracking escaped: red, center free, fixed radius
845 NR::Point c = desktop->w2d(motion_w);
846 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
848 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
849 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
850 sp_canvas_item_show(dc->hatch_area);
851 } else {
852 // Not drawing but spacing set: gray, center snapped, fixed radius
853 NR::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
854 if (!isNaN(c[NR::X]) && !isNaN(c[NR::Y])) {
855 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
856 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
857 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
858 sp_canvas_item_show(dc->hatch_area);
859 }
860 }
861 } else {
862 sp_canvas_item_hide(dc->hatch_area);
863 }
864 }
865 break;
868 case GDK_BUTTON_RELEASE:
869 {
870 NR::Point const motion_w(event->button.x, event->button.y);
871 NR::Point const motion_dt(desktop->w2d(motion_w));
873 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
874 sp_canvas_end_forced_full_redraws(desktop->canvas);
875 dc->is_drawing = false;
877 if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
878 dc->dragging = FALSE;
880 sp_dyna_draw_apply(dc, motion_dt);
882 /* Remove all temporary line segments */
883 while (dc->segments) {
884 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
885 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
886 }
888 /* Create object */
889 fit_and_split(dc, TRUE);
890 accumulate_calligraphic(dc);
891 set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
893 /* reset accumulated curve */
894 sp_curve_reset(dc->accumulated);
896 clear_current(dc);
897 if (dc->repr) {
898 dc->repr = NULL;
899 }
901 if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
902 if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
903 dc->hatch_last_nearest = NR::Point(0,0);
904 dc->hatch_last_pointer = NR::Point(0,0);
905 dc->hatch_vector_accumulated = NR::Point(0,0);
906 dc->hatch_escaped = false;
907 dc->hatch_item = NULL;
908 dc->hatch_livarot_path = NULL;
910 if (dc->hatch_spacing != 0 && !dc->keep_selected) {
911 // we do not select the newly drawn path, so increase spacing by step
912 if (dc->hatch_spacing_step == 0) {
913 dc->hatch_spacing_step = dc->hatch_spacing;
914 }
915 dc->hatch_spacing += dc->hatch_spacing_step;
916 }
918 dc->_message_context->clear();
919 ret = TRUE;
920 }
921 break;
922 }
924 case GDK_KEY_PRESS:
925 switch (get_group0_keyval (&event->key)) {
926 case GDK_Up:
927 case GDK_KP_Up:
928 if (!MOD__CTRL_ONLY) {
929 dc->angle += 5.0;
930 if (dc->angle > 90.0)
931 dc->angle = 90.0;
932 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
933 ret = TRUE;
934 }
935 break;
936 case GDK_Down:
937 case GDK_KP_Down:
938 if (!MOD__CTRL_ONLY) {
939 dc->angle -= 5.0;
940 if (dc->angle < -90.0)
941 dc->angle = -90.0;
942 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
943 ret = TRUE;
944 }
945 break;
946 case GDK_Right:
947 case GDK_KP_Right:
948 if (!MOD__CTRL_ONLY) {
949 dc->width += 0.01;
950 if (dc->width > 1.0)
951 dc->width = 1.0;
952 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
953 ret = TRUE;
954 }
955 break;
956 case GDK_Left:
957 case GDK_KP_Left:
958 if (!MOD__CTRL_ONLY) {
959 dc->width -= 0.01;
960 if (dc->width < 0.01)
961 dc->width = 0.01;
962 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
963 ret = TRUE;
964 }
965 break;
966 case GDK_Home:
967 case GDK_KP_Home:
968 dc->width = 0.01;
969 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
970 ret = TRUE;
971 break;
972 case GDK_End:
973 case GDK_KP_End:
974 dc->width = 1.0;
975 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
976 ret = TRUE;
977 break;
978 case GDK_x:
979 case GDK_X:
980 if (MOD__ALT_ONLY) {
981 desktop->setToolboxFocusTo ("altx-calligraphy");
982 ret = TRUE;
983 }
984 break;
985 case GDK_Escape:
986 if (dc->is_drawing) {
987 // if drawing, cancel, otherwise pass it up for deselecting
988 calligraphic_cancel (dc);
989 ret = TRUE;
990 }
991 break;
992 case GDK_z:
993 case GDK_Z:
994 if (MOD__CTRL_ONLY && dc->is_drawing) {
995 // if drawing, cancel, otherwise pass it up for undo
996 calligraphic_cancel (dc);
997 ret = TRUE;
998 }
999 break;
1000 default:
1001 break;
1002 }
1003 break;
1005 case GDK_KEY_RELEASE:
1006 switch (get_group0_keyval(&event->key)) {
1007 case GDK_Control_L:
1008 case GDK_Control_R:
1009 dc->_message_context->clear();
1010 dc->hatch_spacing = 0;
1011 dc->hatch_spacing_step = 0;
1012 break;
1013 default:
1014 break;
1015 }
1017 default:
1018 break;
1019 }
1021 if (!ret) {
1022 if (((SPEventContextClass *) parent_class)->root_handler) {
1023 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1024 }
1025 }
1027 return ret;
1028 }
1031 static void
1032 clear_current(SPDynaDrawContext *dc)
1033 {
1034 /* reset bpath */
1035 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
1036 /* reset curve */
1037 sp_curve_reset(dc->currentcurve);
1038 sp_curve_reset(dc->cal1);
1039 sp_curve_reset(dc->cal2);
1040 /* reset points */
1041 dc->npoints = 0;
1042 }
1044 static void
1045 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
1046 {
1047 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1049 if (!sp_curve_empty(dc->accumulated)) {
1050 NArtBpath *abp;
1051 gchar *str;
1053 if (!dc->repr) {
1054 /* Create object */
1055 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1056 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1058 /* Set style */
1059 sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
1061 dc->repr = repr;
1063 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1064 Inkscape::GC::release(dc->repr);
1065 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
1066 item->updateRepr();
1067 }
1068 abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
1069 str = sp_svg_write_path(abp);
1070 g_assert( str != NULL );
1071 g_free(abp);
1072 dc->repr->setAttribute("d", str);
1073 g_free(str);
1075 if (unionize) {
1076 sp_desktop_selection(desktop)->add(dc->repr);
1077 sp_selected_path_union_skip_undo();
1078 } else {
1079 if (dc->keep_selected) {
1080 sp_desktop_selection(desktop)->set(dc->repr);
1081 }
1082 }
1084 } else {
1085 if (dc->repr) {
1086 sp_repr_unparent(dc->repr);
1087 }
1088 dc->repr = NULL;
1089 }
1091 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC,
1092 _("Draw calligraphic stroke"));
1093 }
1095 static void
1096 add_cap(SPCurve *curve,
1097 NR::Point const &pre, NR::Point const &from,
1098 NR::Point const &to, NR::Point const &post,
1099 double rounding)
1100 {
1101 NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
1102 double mag = NR::L2(vel);
1104 NR::Point v_in = from - pre;
1105 double mag_in = NR::L2(v_in);
1106 if ( mag_in > DYNA_EPSILON ) {
1107 v_in = mag * v_in / mag_in;
1108 } else {
1109 v_in = NR::Point(0, 0);
1110 }
1112 NR::Point v_out = to - post;
1113 double mag_out = NR::L2(v_out);
1114 if ( mag_out > DYNA_EPSILON ) {
1115 v_out = mag * v_out / mag_out;
1116 } else {
1117 v_out = NR::Point(0, 0);
1118 }
1120 if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
1121 sp_curve_curveto(curve, from + v_in, to + v_out, to);
1122 }
1123 }
1125 static void
1126 accumulate_calligraphic(SPDynaDrawContext *dc)
1127 {
1128 if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
1129 sp_curve_reset(dc->accumulated); /* Is this required ?? */
1130 SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
1132 g_assert(dc->cal1->end > 1);
1133 g_assert(rev_cal2->end > 1);
1134 g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
1135 g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
1136 g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
1137 g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
1138 g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
1139 g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
1141 sp_curve_append(dc->accumulated, dc->cal1, FALSE);
1143 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);
1145 sp_curve_append(dc->accumulated, rev_cal2, TRUE);
1147 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);
1149 sp_curve_closepath(dc->accumulated);
1151 sp_curve_unref(rev_cal2);
1153 sp_curve_reset(dc->cal1);
1154 sp_curve_reset(dc->cal2);
1155 }
1156 }
1158 static double square(double const x)
1159 {
1160 return x * x;
1161 }
1163 static void
1164 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1165 {
1166 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
1168 #ifdef DYNA_DRAW_VERBOSE
1169 g_print("[F&S:R=%c]", release?'T':'F');
1170 #endif
1172 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1173 return; // just clicked
1175 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1176 #define BEZIER_SIZE 4
1177 #define BEZIER_MAX_BEZIERS 8
1178 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1180 #ifdef DYNA_DRAW_VERBOSE
1181 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1182 dc->npoints, release ? "TRUE" : "FALSE");
1183 #endif
1185 /* Current calligraphic */
1186 if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
1187 /* dc->npoints > 0 */
1188 /* g_print("calligraphics(1|2) reset\n"); */
1189 sp_curve_reset(dc->cal1);
1190 sp_curve_reset(dc->cal2);
1192 sp_curve_moveto(dc->cal1, dc->point1[0]);
1193 sp_curve_moveto(dc->cal2, dc->point2[0]);
1194 }
1196 NR::Point b1[BEZIER_MAX_LENGTH];
1197 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1198 tolerance_sq, BEZIER_MAX_BEZIERS);
1199 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1201 NR::Point b2[BEZIER_MAX_LENGTH];
1202 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1203 tolerance_sq, BEZIER_MAX_BEZIERS);
1204 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1206 if ( nb1 != -1 && nb2 != -1 ) {
1207 /* Fit and draw and reset state */
1208 #ifdef DYNA_DRAW_VERBOSE
1209 g_print("nb1:%d nb2:%d\n", nb1, nb2);
1210 #endif
1211 /* CanvasShape */
1212 if (! release) {
1213 sp_curve_reset(dc->currentcurve);
1214 sp_curve_moveto(dc->currentcurve, b1[0]);
1215 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1216 sp_curve_curveto(dc->currentcurve, bp1[1],
1217 bp1[2], bp1[3]);
1218 }
1219 sp_curve_lineto(dc->currentcurve,
1220 b2[BEZIER_SIZE*(nb2-1) + 3]);
1221 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1222 sp_curve_curveto(dc->currentcurve, 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 sp_curve_closepath(dc->currentcurve);
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 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
1235 }
1236 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1237 sp_curve_curveto(dc->cal2, 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 sp_curve_lineto(dc->cal1, dc->point1[i]);
1248 }
1249 for (gint i = 1; i < dc->npoints; i++) {
1250 sp_curve_lineto(dc->cal2, 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(!sp_curve_empty(dc->currentcurve));
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 = sp_curve_copy(dc->currentcurve);
1265 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1266 sp_curve_unref(curve);
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 }
1289 }
1291 static void
1292 draw_temporary_box(SPDynaDrawContext *dc)
1293 {
1294 sp_curve_reset(dc->currentcurve);
1296 sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
1297 for (gint i = dc->npoints-2; i >= 0; i--) {
1298 sp_curve_lineto(dc->currentcurve, dc->point1[i]);
1299 }
1300 for (gint i = 0; i < dc->npoints; i++) {
1301 sp_curve_lineto(dc->currentcurve, 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 sp_curve_closepath(dc->currentcurve);
1308 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1309 }
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 :