d1966d248ba6c3e6af642461b6904c201483ca24
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>
32 #include <numeric>
34 #include "svg/svg.h"
35 #include "display/canvas-bpath.h"
36 #include "display/bezier-utils.h"
38 #include <glib/gmem.h>
39 #include "macros.h"
40 #include "document.h"
41 #include "selection.h"
42 #include "desktop.h"
43 #include "desktop-events.h"
44 #include "desktop-handles.h"
45 #include "desktop-affine.h"
46 #include "desktop-style.h"
47 #include "message-context.h"
48 #include "pixmaps/cursor-calligraphy.xpm"
49 #include "pixmaps/cursor-thin.xpm"
50 #include "pixmaps/cursor-thicken.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-shape.h"
62 #include "sp-path.h"
63 #include "sp-text.h"
64 #include "display/canvas-bpath.h"
65 #include "display/canvas-arena.h"
66 #include "livarot/Shape.h"
67 #include "isnan.h"
69 #include "dyna-draw-context.h"
71 #define DDC_RED_RGBA 0xff0000ff
73 #define TOLERANCE_CALLIGRAPHIC 0.1
75 #define DYNA_EPSILON 0.5e-6
76 #define DYNA_EPSILON_START 0.5e-2
77 #define DYNA_VEL_START 1e-5
79 #define DYNA_MIN_WIDTH 1.0e-6
81 #define DRAG_MIN 0.0
82 #define DRAG_DEFAULT 1.0
83 #define DRAG_MAX 1.0
85 // FIXME: move it to some shared file to be reused by both calligraphy and dropper
86 #define C1 0.552
87 static NArtBpath const hatch_area_circle[] = {
88 { NR_MOVETO, 0, 0, 0, 0, -1, 0 },
89 { NR_CURVETO, -1, C1, -C1, 1, 0, 1 },
90 { NR_CURVETO, C1, 1, 1, C1, 1, 0 },
91 { NR_CURVETO, 1, -C1, C1, -1, 0, -1 },
92 { NR_CURVETO, -C1, -1, -1, -C1, -1, 0 },
93 { NR_END, 0, 0, 0, 0, 0, 0 }
94 };
95 #undef C1
98 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
99 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
100 static void sp_dyna_draw_context_dispose(GObject *object);
102 static void sp_dyna_draw_context_setup(SPEventContext *ec);
103 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
104 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
106 static void clear_current(SPDynaDrawContext *dc);
107 static void set_to_accumulated(SPDynaDrawContext *dc, bool unionize);
108 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
109 static void accumulate_calligraphic(SPDynaDrawContext *dc);
111 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
113 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
114 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
115 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
116 static void draw_temporary_box(SPDynaDrawContext *dc);
119 static SPEventContextClass *parent_class;
121 GtkType
122 sp_dyna_draw_context_get_type(void)
123 {
124 static GType type = 0;
125 if (!type) {
126 GTypeInfo info = {
127 sizeof(SPDynaDrawContextClass),
128 NULL, NULL,
129 (GClassInitFunc) sp_dyna_draw_context_class_init,
130 NULL, NULL,
131 sizeof(SPDynaDrawContext),
132 4,
133 (GInstanceInitFunc) sp_dyna_draw_context_init,
134 NULL, /* value_table */
135 };
136 type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
137 }
138 return type;
139 }
141 static void
142 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
143 {
144 GObjectClass *object_class = (GObjectClass *) klass;
145 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
147 parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
149 object_class->dispose = sp_dyna_draw_context_dispose;
151 event_context_class->setup = sp_dyna_draw_context_setup;
152 event_context_class->set = sp_dyna_draw_context_set;
153 event_context_class->root_handler = sp_dyna_draw_context_root_handler;
154 }
156 static void
157 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
158 {
159 SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
161 event_context->cursor_shape = cursor_calligraphy_xpm;
162 event_context->hot_x = 4;
163 event_context->hot_y = 4;
165 ddc->accumulated = NULL;
166 ddc->segments = NULL;
167 ddc->currentcurve = NULL;
168 ddc->currentshape = NULL;
169 ddc->npoints = 0;
170 ddc->cal1 = NULL;
171 ddc->cal2 = NULL;
172 ddc->repr = NULL;
174 /* DynaDraw values */
175 ddc->cur = NR::Point(0,0);
176 ddc->last = NR::Point(0,0);
177 ddc->vel = NR::Point(0,0);
178 ddc->vel_max = 0;
179 ddc->acc = NR::Point(0,0);
180 ddc->ang = NR::Point(0,0);
181 ddc->del = NR::Point(0,0);
183 /* attributes */
184 ddc->dragging = FALSE;
186 ddc->mass = 0.3;
187 ddc->drag = DRAG_DEFAULT;
188 ddc->angle = 30.0;
189 ddc->width = 0.2;
190 ddc->pressure = DDC_DEFAULT_PRESSURE;
192 ddc->vel_thin = 0.1;
193 ddc->flatness = 0.9;
194 ddc->cap_rounding = 0.0;
196 ddc->abs_width = false;
197 ddc->keep_selected = true;
199 ddc->hatch_spacing = 0;
200 new (&ddc->hatch_pointer_past) std::list<double>();
201 new (&ddc->hatch_nearest_past) std::list<double>();
202 ddc->hatch_last_nearest = NR::Point(0,0);
203 ddc->hatch_last_pointer = NR::Point(0,0);
204 ddc->hatch_vector_accumulated = NR::Point(0,0);
205 ddc->hatch_escaped = false;
206 ddc->hatch_area = NULL;
207 ddc->hatch_item = NULL;
208 ddc->hatch_livarot_path = NULL;
210 ddc->trace_bg = false;
212 ddc->is_dilating = 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->dilate_area) {
226 gtk_object_destroy(GTK_OBJECT(ddc->dilate_area));
227 ddc->dilate_area = NULL;
228 }
230 if (ddc->accumulated) {
231 ddc->accumulated = sp_curve_unref(ddc->accumulated);
232 }
234 while (ddc->segments) {
235 gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
236 ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
237 }
239 if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
240 if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
241 if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
243 if (ddc->currentshape) {
244 gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
245 ddc->currentshape = NULL;
246 }
248 if (ddc->_message_context) {
249 delete ddc->_message_context;
250 }
252 G_OBJECT_CLASS(parent_class)->dispose(object);
254 ddc->hatch_pointer_past.~list();
255 ddc->hatch_nearest_past.~list();
256 }
258 static void
259 sp_dyna_draw_context_setup(SPEventContext *ec)
260 {
261 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
263 if (((SPEventContextClass *) parent_class)->setup)
264 ((SPEventContextClass *) parent_class)->setup(ec);
266 ddc->accumulated = sp_curve_new_sized(32);
267 ddc->currentcurve = sp_curve_new_sized(4);
269 ddc->cal1 = sp_curve_new_sized(32);
270 ddc->cal2 = sp_curve_new_sized(32);
272 ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
273 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
274 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
275 /* fixme: Cannot we cascade it to root more clearly? */
276 g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
278 {
279 SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
280 ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
281 sp_curve_unref(c);
282 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
283 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
284 sp_canvas_item_hide(ddc->hatch_area);
285 }
287 {
288 SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
289 ddc->dilate_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
290 sp_curve_unref(c);
291 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->dilate_area), 0x00000000,(SPWindRule)0);
292 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->dilate_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
293 sp_canvas_item_hide(ddc->dilate_area);
294 }
296 sp_event_context_read(ec, "mass");
297 sp_event_context_read(ec, "wiggle");
298 sp_event_context_read(ec, "angle");
299 sp_event_context_read(ec, "width");
300 sp_event_context_read(ec, "thinning");
301 sp_event_context_read(ec, "tremor");
302 sp_event_context_read(ec, "flatness");
303 sp_event_context_read(ec, "tracebackground");
304 sp_event_context_read(ec, "usepressure");
305 sp_event_context_read(ec, "usetilt");
306 sp_event_context_read(ec, "abs_width");
307 sp_event_context_read(ec, "keep_selected");
308 sp_event_context_read(ec, "cap_rounding");
310 ddc->is_drawing = false;
312 ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
313 }
315 static void
316 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
317 {
318 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
320 if (!strcmp(key, "mass")) {
321 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
322 ddc->mass = CLAMP(dval, -1000.0, 1000.0);
323 } else if (!strcmp(key, "wiggle")) {
324 double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
325 ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
326 } else if (!strcmp(key, "angle")) {
327 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
328 ddc->angle = CLAMP (dval, -90, 90);
329 } else if (!strcmp(key, "width")) {
330 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
331 ddc->width = CLAMP(dval, -1000.0, 1000.0);
332 } else if (!strcmp(key, "thinning")) {
333 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
334 ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
335 } else if (!strcmp(key, "tremor")) {
336 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
337 ddc->tremor = CLAMP(dval, 0.0, 1.0);
338 } else if (!strcmp(key, "flatness")) {
339 double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
340 ddc->flatness = CLAMP(dval, 0, 1.0);
341 } else if (!strcmp(key, "tracebackground")) {
342 ddc->trace_bg = (val && strcmp(val, "0"));
343 } else if (!strcmp(key, "usepressure")) {
344 ddc->usepressure = (val && strcmp(val, "0"));
345 } else if (!strcmp(key, "usetilt")) {
346 ddc->usetilt = (val && strcmp(val, "0"));
347 } else if (!strcmp(key, "abs_width")) {
348 ddc->abs_width = (val && strcmp(val, "0"));
349 } else if (!strcmp(key, "keep_selected")) {
350 ddc->keep_selected = (val && strcmp(val, "0"));
351 } else if (!strcmp(key, "cap_rounding")) {
352 ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
353 }
355 //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
356 }
358 static double
359 flerp(double f0, double f1, double p)
360 {
361 return f0 + ( f1 - f0 ) * p;
362 }
364 /* Get normalized point */
365 static NR::Point
366 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
367 {
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(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
371 }
373 /* Get view point */
374 static NR::Point
375 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
376 {
377 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
378 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
379 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
380 }
382 static void
383 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
384 {
385 dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
386 dc->vel = NR::Point(0,0);
387 dc->vel_max = 0;
388 dc->acc = NR::Point(0,0);
389 dc->ang = NR::Point(0,0);
390 dc->del = NR::Point(0,0);
391 }
393 static void
394 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
395 {
396 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
397 dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
398 else
399 dc->pressure = DDC_DEFAULT_PRESSURE;
401 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
402 dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
403 else
404 dc->xtilt = DDC_DEFAULT_TILT;
406 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
407 dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
408 else
409 dc->ytilt = DDC_DEFAULT_TILT;
410 }
413 static gboolean
414 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
415 {
416 NR::Point n = sp_dyna_draw_get_npoint(dc, p);
418 /* Calculate mass and drag */
419 double const mass = flerp(1.0, 160.0, dc->mass);
420 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
422 /* Calculate force and acceleration */
423 NR::Point force = n - dc->cur;
425 // If force is below the absolute threshold DYNA_EPSILON,
426 // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
427 // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
428 // discard this move.
429 // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
430 // especially bothersome at the start of the stroke where we don't yet have the inertia to
431 // smooth them out.
432 if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
433 return FALSE;
434 }
436 dc->acc = force / mass;
438 /* Calculate new velocity */
439 dc->vel += dc->acc;
441 if (NR::L2(dc->vel) > dc->vel_max)
442 dc->vel_max = NR::L2(dc->vel);
444 /* Calculate angle of drawing tool */
446 double a1;
447 if (dc->usetilt) {
448 // 1a. calculate nib angle from input device tilt:
449 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
451 if (length > 0) {
452 NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
453 a1 = atan2(ang1);
454 }
455 else
456 a1 = 0.0;
457 }
458 else {
459 // 1b. fixed dc->angle (absolutely flat nib):
460 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
461 NR::Point ang1 = NR::Point(-sin(radians), cos(radians));
462 a1 = atan2(ang1);
463 }
465 // 2. perpendicular to dc->vel (absolutely non-flat nib):
466 gdouble const mag_vel = NR::L2(dc->vel);
467 if ( mag_vel < DYNA_EPSILON ) {
468 return FALSE;
469 }
470 NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
472 // 3. Average them using flatness parameter:
473 // calculate angles
474 double a2 = atan2(ang2);
475 // flip a2 to force it to be in the same half-circle as a1
476 bool flipped = false;
477 if (fabs (a2-a1) > 0.5*M_PI) {
478 a2 += M_PI;
479 flipped = true;
480 }
481 // normalize a2
482 if (a2 > M_PI)
483 a2 -= 2*M_PI;
484 if (a2 < -M_PI)
485 a2 += 2*M_PI;
486 // find the flatness-weighted bisector angle, unflip if a2 was flipped
487 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
488 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
490 // Try to detect a sudden flip when the new angle differs too much from the previous for the
491 // current velocity; in that case discard this move
492 double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
493 if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
494 return FALSE;
495 }
497 // convert to point
498 dc->ang = NR::Point (cos (new_ang), sin (new_ang));
500 // 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);
502 /* Apply drag */
503 dc->vel *= 1.0 - drag;
505 /* Update position */
506 dc->last = dc->cur;
507 dc->cur += dc->vel;
509 return TRUE;
510 }
512 static void
513 sp_dyna_draw_brush(SPDynaDrawContext *dc)
514 {
515 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
517 // How much velocity thins strokestyle
518 double vel_thin = flerp (0, 160, dc->vel_thin);
520 // Influence of pressure on thickness
521 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
523 // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
524 // drag)
525 NR::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
526 NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
528 double trace_thick = 1;
529 if (dc->trace_bg) {
530 // pick single pixel
531 NRPixBlock pb;
532 int x = (int) floor(brush_w[NR::X]);
533 int y = (int) floor(brush_w[NR::Y]);
534 nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
535 sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
536 const unsigned char *s = NR_PIXBLOCK_PX(&pb);
537 double R = s[0] / 255.0;
538 double G = s[1] / 255.0;
539 double B = s[2] / 255.0;
540 double A = s[3] / 255.0;
541 double max = MAX (MAX (R, G), B);
542 double min = MIN (MIN (R, G), B);
543 double L = A * (max + min)/2 + (1 - A); // blend with white bg
544 trace_thick = 1 - L;
545 //g_print ("L %g thick %g\n", L, trace_thick);
546 }
548 double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
550 double tremble_left = 0, tremble_right = 0;
551 if (dc->tremor > 0) {
552 // obtain two normally distributed random variables, using polar Box-Muller transform
553 double x1, x2, w, y1, y2;
554 do {
555 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
556 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
557 w = x1 * x1 + x2 * x2;
558 } while ( w >= 1.0 );
559 w = sqrt( (-2.0 * log( w ) ) / w );
560 y1 = x1 * w;
561 y2 = x2 * w;
563 // deflect both left and right edges randomly and independently, so that:
564 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
565 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
566 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
567 // comparatively smooth and slow ones excessively jittery
568 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
569 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
570 }
572 if ( width < 0.02 * dc->width ) {
573 width = 0.02 * dc->width;
574 }
576 double dezoomify_factor = 0.05 * 1000;
577 if (!dc->abs_width) {
578 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
579 }
581 NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
582 NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
584 dc->point1[dc->npoints] = brush + del_left;
585 dc->point2[dc->npoints] = brush - del_right;
587 dc->del = 0.5*(del_left + del_right);
589 dc->npoints++;
590 }
592 double
593 get_dilate_radius (SPDynaDrawContext *dc)
594 {
595 // 10 times the pen width:
596 return 500 * dc->width/SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
597 }
599 double
600 get_dilate_force (SPDynaDrawContext *dc)
601 {
602 return 8 * dc->pressure/SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
603 }
605 bool
606 sp_ddc_dilate (SPDynaDrawContext *dc, NR::Point p, bool expand)
607 {
608 Inkscape::Selection *selection = sp_desktop_selection(SP_EVENT_CONTEXT(dc)->desktop);
610 if (selection->isEmpty()) {
611 return false;
612 }
614 bool did = false;
615 double radius = get_dilate_radius(dc);
616 double offset = get_dilate_force(dc);
618 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
619 items != NULL;
620 items = items->next) {
622 SPItem *item = (SPItem *) items->data;
624 // only paths
625 if (!SP_IS_PATH(item))
626 continue;
628 SPCurve *curve = NULL;
629 curve = sp_shape_get_curve(SP_SHAPE(item));
630 if (curve == NULL)
631 continue;
633 // skip those paths whose bboxes are entirely out of reach with our radius
634 NR::Maybe<NR::Rect> bbox = item->getBounds(sp_item_i2doc_affine(item));
635 if (bbox) {
636 bbox->growBy(radius);
637 if (!bbox->contains(p)) {
638 continue;
639 }
640 }
642 Path *orig = Path_for_item(item, false);
643 if (orig == NULL) {
644 sp_curve_unref(curve);
645 continue;
646 }
647 Path *res = new Path;
648 res->SetBackData(false);
650 Shape *theShape = new Shape;
651 Shape *theRes = new Shape;
653 orig->ConvertWithBackData(0.05);
654 orig->Fill(theShape, 0);
656 SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
657 gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
658 if (val && strcmp(val, "nonzero") == 0)
659 {
660 theRes->ConvertToShape(theShape, fill_nonZero);
661 }
662 else if (val && strcmp(val, "evenodd") == 0)
663 {
664 theRes->ConvertToShape(theShape, fill_oddEven);
665 }
666 else
667 {
668 theRes->ConvertToShape(theShape, fill_nonZero);
669 }
671 bool did_this = false;
672 if (theShape->MakeOffset(theRes,
673 expand? offset : -offset,
674 join_straight, butt_straight,
675 true, p[NR::X], p[NR::Y], radius) == 0) // 0 means the shape was actually changed
676 did_this = true;
678 // the rest only makes sense if we actually changed the path
679 if (did_this) {
680 theRes->ConvertToShape(theShape, fill_positive);
682 res->Reset();
683 theRes->ConvertToForme(res);
685 if (offset >= 0.5)
686 {
687 res->ConvertEvenLines(0.5);
688 res->Simplify(0.5);
689 }
690 else
691 {
692 res->ConvertEvenLines(0.5*offset);
693 res->Simplify(0.5 * offset);
694 }
696 sp_curve_unref(curve);
697 if (res->descr_cmd.size() > 1) {
698 gchar *str = res->svg_dump_path();
699 SP_OBJECT_REPR(item)->setAttribute("d", str);
700 g_free(str);
701 } else {
702 // TODO: if there's 0 or 1 node left, delete this path altogether
703 }
704 }
706 delete theShape;
707 delete theRes;
708 delete orig;
709 delete res;
711 if (did_this)
712 did = true;
713 }
715 return did;
716 }
718 void
719 sp_ddc_update_cursors (SPDynaDrawContext *dc)
720 {
721 if (dc->is_dilating) {
722 double radius = get_dilate_radius(dc);
723 NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(SP_EVENT_CONTEXT(dc)->desktop->point()));
724 sp_canvas_item_affine_absolute(dc->dilate_area, sm);
725 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
726 sp_canvas_item_show(dc->dilate_area);
727 }
728 }
730 void
731 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
732 {
733 desktop->setToolboxAdjustmentValue (id, value);
734 }
736 static void
737 calligraphic_cancel(SPDynaDrawContext *dc)
738 {
739 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
740 dc->dragging = FALSE;
741 dc->is_drawing = false;
742 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
743 /* Remove all temporary line segments */
744 while (dc->segments) {
745 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
746 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
747 }
748 /* reset accumulated curve */
749 sp_curve_reset(dc->accumulated);
750 clear_current(dc);
751 if (dc->repr) {
752 dc->repr = NULL;
753 }
754 }
757 gint
758 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
759 GdkEvent *event)
760 {
761 SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
762 SPDesktop *desktop = event_context->desktop;
764 gint ret = FALSE;
766 switch (event->type) {
767 case GDK_BUTTON_PRESS:
768 if ( event->button.button == 1 ) {
770 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
772 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
773 return TRUE;
774 }
776 NR::Point const button_w(event->button.x,
777 event->button.y);
778 NR::Point const button_dt(desktop->w2d(button_w));
779 sp_dyna_draw_reset(dc, button_dt);
780 sp_dyna_draw_extinput(dc, event);
781 sp_dyna_draw_apply(dc, button_dt);
782 sp_curve_reset(dc->accumulated);
783 if (dc->repr) {
784 dc->repr = NULL;
785 }
787 /* initialize first point */
788 dc->npoints = 0;
790 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
791 ( GDK_KEY_PRESS_MASK |
792 GDK_BUTTON_RELEASE_MASK |
793 GDK_POINTER_MOTION_MASK |
794 GDK_BUTTON_PRESS_MASK ),
795 NULL,
796 event->button.time);
798 ret = TRUE;
800 dc->is_drawing = true;
801 }
802 break;
803 case GDK_MOTION_NOTIFY:
804 {
805 NR::Point const motion_w(event->motion.x,
806 event->motion.y);
807 NR::Point motion_dt(desktop->w2d(motion_w));
809 // draw the dilating cursor
810 if (event->motion.state & GDK_MOD1_MASK) {
811 double radius = get_dilate_radius(dc);
812 NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(desktop->w2d(motion_w)));
813 sp_canvas_item_affine_absolute(dc->dilate_area, sm);
814 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
815 sp_canvas_item_show(dc->dilate_area);
817 guint num = 0;
818 if (!desktop->selection->isEmpty()) {
819 num = g_slist_length((GSList *) desktop->selection->itemList());
820 }
821 if (num == 0) {
822 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select paths</b> to thin or thicken"));
823 } else {
824 dc->_message_context->setF(Inkscape::NORMAL_MESSAGE,
825 event->motion.state & GDK_SHIFT_MASK?
826 _("<b>Thickening %d</b> selected paths; without <b>Shift</b> to thin") :
827 _("<b>Thinning %d</b> selected paths; with <b>Shift</b> to thicken"), num);
828 }
830 } else {
831 dc->_message_context->clear();
832 sp_canvas_item_hide(dc->dilate_area);
833 }
835 // dilating:
836 if (dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) && event->motion.state & GDK_MOD1_MASK) {
837 sp_ddc_dilate (dc, desktop->dt2doc(motion_dt), event->motion.state & GDK_SHIFT_MASK? true : false);
838 dc->is_dilating = true;
839 // it's slow, so prevent clogging up with events
840 gobble_motion_events(GDK_BUTTON1_MASK);
841 return TRUE;
842 }
845 // for hatching:
846 double hatch_dist = 0;
847 NR::Point hatch_unit_vector(0,0);
848 NR::Point nearest(0,0);
849 NR::Point pointer(0,0);
850 NR::Matrix motion_to_curve(NR::identity());
852 if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
854 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
855 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
856 // One item selected, and it's a path;
857 // let's try to track it as a guide
859 if (selected != dc->hatch_item) {
860 dc->hatch_item = selected;
861 if (dc->hatch_livarot_path)
862 delete dc->hatch_livarot_path;
863 dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
864 dc->hatch_livarot_path->ConvertWithBackData(0.01);
865 }
867 // calculate pointer point in the guide item's coords
868 motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
869 pointer = motion_dt * motion_to_curve;
871 // calculate the nearest point on the guide path
872 NR::Maybe<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
873 nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
876 // distance from pointer to nearest
877 hatch_dist = NR::L2(pointer - nearest);
878 // unit-length vector
879 hatch_unit_vector = (pointer - nearest)/hatch_dist;
881 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
882 } else {
883 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
884 }
885 }
887 if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
888 dc->dragging = TRUE;
890 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
892 #define SPEED_ELEMENTS 12
893 #define SPEED_MIN 0.12
894 #define SPEED_NORMAL 0.65
896 // speed is the movement of the nearest point along the guide path, divided by
897 // the movement of the pointer at the same period; it is averaged for the last
898 // SPEED_ELEMENTS motion events. Normally, as you track the guide path, speed
899 // is about 1, i.e. the nearest point on the path is moved by about the same
900 // distance as the pointer. If the speed starts to decrease, we are losing
901 // contact with the guide; if it drops below SPEED_MIN, we are on our own and
902 // not attracted to guide anymore. Most often this happens when you have
903 // tracked to the end of a guide calligraphic stroke and keep moving
904 // further. We try to handle this situation gracefully: not stick with the
905 // guide forever but let go of it smoothly and without sharp jerks (non-zero
906 // mass recommended; with zero mass, jerks are still quite noticeable).
908 double speed = 1;
909 if (NR::L2(dc->hatch_last_nearest) != 0) {
910 // the distance nearest moved since the last motion event
911 double nearest_moved = NR::L2(nearest - dc->hatch_last_nearest);
912 // the distance pointer moved since the last motion event
913 double pointer_moved = NR::L2(pointer - dc->hatch_last_pointer);
914 // store them in stacks limited to SPEED_ELEMENTS
915 dc->hatch_nearest_past.push_front(nearest_moved);
916 if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
917 dc->hatch_nearest_past.pop_back();
918 dc->hatch_pointer_past.push_front(pointer_moved);
919 if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
920 dc->hatch_pointer_past.pop_back();
922 // If the stacks are full,
923 if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
924 // calculate the sums of all stored movements
925 double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
926 double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
927 // and divide to get the speed
928 speed = nearest_sum/pointer_sum;
929 //g_print ("nearest sum %g pointer_sum %g speed %g\n", nearest_sum, pointer_sum, speed);
930 }
931 }
933 if ( dc->hatch_escaped // already escaped, do not reattach
934 || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
935 || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
936 ) {
937 // We are NOT attracted to the guide!
939 //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);
940 //g_print ("------nm %g pm %g ratio %g\n", nearest_moved, pointer_moved, ratio);
941 //g_print ("------dist %g spacing %g\n", dist, dc->spacing);
942 //g_print ("acting up: %s dist %g \n", position_is_ok? (dc->hatch_escaped? "escaped" : "dist") : "livarot", dist/dc->hatch_spacing);
944 // Remember hatch_escaped so we don't get
945 // attracted again until the end of this stroke
946 dc->hatch_escaped = true;
948 } else {
950 // Calculate angle cosine of this vector-to-guide and all past vectors
951 // summed, to detect if we accidentally flipped to the other side of the
952 // guide
953 double dot = NR::dot (pointer - nearest, dc->hatch_vector_accumulated);
954 dot /= NR::L2(pointer - nearest) * NR::L2(dc->hatch_vector_accumulated);
956 if (dc->hatch_spacing != 0) { // spacing was already set
957 double target;
958 if (speed > SPEED_NORMAL) {
959 // all ok, strictly obey the spacing
960 target = dc->hatch_spacing;
961 } else {
962 // looks like we're starting to lose speed,
963 // so _gradually_ let go attraction to prevent jerks
964 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;
965 }
966 if (!isnan(dot) && dot < -0.5) {// flip
967 target = -target;
968 //g_print ("FLIP\n");
969 }
971 // This is the track pointer that we will use instead of the real one
972 NR::Point new_pointer = nearest + target * hatch_unit_vector;
973 //g_print ("NEW %g %g\n", new_point[NR::X], new_point[NR::Y]);
975 // some limited feedback: allow persistent pulling to slightly change
976 // the spacing
977 dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
979 // return it to the desktop coords
980 motion_dt = new_pointer * motion_to_curve.inverse();
982 } else {
983 // this is the first motion event, set the dist
984 dc->hatch_spacing = hatch_dist;
985 }
987 // remember last points
988 dc->hatch_last_pointer = pointer;
989 dc->hatch_last_nearest = nearest;
990 dc->hatch_vector_accumulated += (pointer - nearest);
991 }
993 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
995 } else {
996 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
997 }
999 sp_dyna_draw_extinput(dc, event);
1000 if (!sp_dyna_draw_apply(dc, motion_dt)) {
1001 ret = TRUE;
1002 break;
1003 }
1005 if ( dc->cur != dc->last ) {
1006 sp_dyna_draw_brush(dc);
1007 g_assert( dc->npoints > 0 );
1008 fit_and_split(dc, FALSE);
1009 }
1010 ret = TRUE;
1011 }
1013 // Draw the hatching circle if necessary
1014 if (event->motion.state & GDK_CONTROL_MASK) {
1015 if (dc->hatch_spacing == 0 && hatch_dist != 0) {
1016 // Haven't set spacing yet: gray, center free, update radius live
1017 NR::Point c = desktop->w2d(motion_w);
1018 NR::Matrix const sm (NR::scale(hatch_dist, hatch_dist) * NR::translate(c));
1019 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1020 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1021 sp_canvas_item_show(dc->hatch_area);
1022 } else if (dc->dragging && !dc->hatch_escaped) {
1023 // Tracking: green, center snapped, fixed radius
1024 NR::Point c = motion_dt;
1025 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1026 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1027 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1028 sp_canvas_item_show(dc->hatch_area);
1029 } else if (dc->dragging && dc->hatch_escaped) {
1030 // Tracking escaped: red, center free, fixed radius
1031 NR::Point c = desktop->w2d(motion_w);
1032 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1034 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1035 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1036 sp_canvas_item_show(dc->hatch_area);
1037 } else {
1038 // Not drawing but spacing set: gray, center snapped, fixed radius
1039 NR::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
1040 if (!isNaN(c[NR::X]) && !isNaN(c[NR::Y])) {
1041 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1042 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1043 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1044 sp_canvas_item_show(dc->hatch_area);
1045 }
1046 }
1047 } else {
1048 sp_canvas_item_hide(dc->hatch_area);
1049 }
1050 }
1051 break;
1054 case GDK_BUTTON_RELEASE:
1055 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
1056 dc->is_drawing = false;
1058 if ( dc->is_dilating && event->button.button == 1 ) {
1059 dc->is_dilating = false;
1060 sp_document_done(sp_desktop_document(SP_EVENT_CONTEXT(dc)->desktop),
1061 SP_VERB_CONTEXT_CALLIGRAPHIC,
1062 (event->button.state & GDK_SHIFT_MASK ? _("Thicken paths") : _("Thin paths")));
1063 ret = TRUE;
1064 } else if ( dc->dragging && event->button.button == 1 ) {
1065 dc->dragging = FALSE;
1067 NR::Point const motion_w(event->button.x, event->button.y);
1068 NR::Point const motion_dt(desktop->w2d(motion_w));
1069 sp_dyna_draw_apply(dc, motion_dt);
1071 /* Remove all temporary line segments */
1072 while (dc->segments) {
1073 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
1074 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
1075 }
1077 /* Create object */
1078 fit_and_split(dc, TRUE);
1079 accumulate_calligraphic(dc);
1080 set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
1082 /* reset accumulated curve */
1083 sp_curve_reset(dc->accumulated);
1085 clear_current(dc);
1086 if (dc->repr) {
1087 dc->repr = NULL;
1088 }
1090 if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
1091 if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
1092 dc->hatch_last_nearest = NR::Point(0,0);
1093 dc->hatch_last_pointer = NR::Point(0,0);
1094 dc->hatch_vector_accumulated = NR::Point(0,0);
1095 dc->hatch_escaped = false;
1096 dc->hatch_item = NULL;
1097 dc->hatch_livarot_path = NULL;
1099 dc->_message_context->clear();
1100 ret = TRUE;
1101 }
1102 break;
1104 case GDK_KEY_PRESS:
1105 switch (get_group0_keyval (&event->key)) {
1106 case GDK_Up:
1107 case GDK_KP_Up:
1108 if (!MOD__CTRL_ONLY) {
1109 dc->angle += 5.0;
1110 if (dc->angle > 90.0)
1111 dc->angle = 90.0;
1112 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1113 ret = TRUE;
1114 }
1115 break;
1116 case GDK_Down:
1117 case GDK_KP_Down:
1118 if (!MOD__CTRL_ONLY) {
1119 dc->angle -= 5.0;
1120 if (dc->angle < -90.0)
1121 dc->angle = -90.0;
1122 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1123 ret = TRUE;
1124 }
1125 break;
1126 case GDK_Right:
1127 case GDK_KP_Right:
1128 if (!MOD__CTRL_ONLY) {
1129 dc->width += 0.01;
1130 if (dc->width > 1.0)
1131 dc->width = 1.0;
1132 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
1133 sp_ddc_update_cursors(dc);
1134 ret = TRUE;
1135 }
1136 break;
1137 case GDK_Left:
1138 case GDK_KP_Left:
1139 if (!MOD__CTRL_ONLY) {
1140 dc->width -= 0.01;
1141 if (dc->width < 0.01)
1142 dc->width = 0.01;
1143 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1144 sp_ddc_update_cursors(dc);
1145 ret = TRUE;
1146 }
1147 break;
1148 case GDK_Home:
1149 case GDK_KP_Home:
1150 dc->width = 0.01;
1151 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1152 sp_ddc_update_cursors(dc);
1153 ret = TRUE;
1154 break;
1155 case GDK_End:
1156 case GDK_KP_End:
1157 dc->width = 1.0;
1158 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1159 sp_ddc_update_cursors(dc);
1160 ret = TRUE;
1161 break;
1162 case GDK_x:
1163 case GDK_X:
1164 if (MOD__ALT_ONLY) {
1165 desktop->setToolboxFocusTo ("altx-calligraphy");
1166 ret = TRUE;
1167 }
1168 break;
1169 case GDK_Escape:
1170 if (dc->is_drawing) {
1171 // if drawing, cancel, otherwise pass it up for deselecting
1172 calligraphic_cancel (dc);
1173 ret = TRUE;
1174 }
1175 break;
1176 case GDK_z:
1177 case GDK_Z:
1178 if (MOD__CTRL_ONLY && dc->is_drawing) {
1179 // if drawing, cancel, otherwise pass it up for undo
1180 calligraphic_cancel (dc);
1181 ret = TRUE;
1182 }
1183 break;
1184 case GDK_Meta_L:
1185 case GDK_Meta_R:
1186 event_context->cursor_shape = cursor_thicken_xpm;
1187 sp_event_context_update_cursor(event_context);
1188 break;
1189 case GDK_Alt_L:
1190 case GDK_Alt_R:
1191 if (MOD__SHIFT) {
1192 event_context->cursor_shape = cursor_thicken_xpm;
1193 sp_event_context_update_cursor(event_context);
1194 } else {
1195 event_context->cursor_shape = cursor_thin_xpm;
1196 sp_event_context_update_cursor(event_context);
1197 }
1198 break;
1199 case GDK_Shift_L:
1200 case GDK_Shift_R:
1201 if (MOD__ALT) {
1202 event_context->cursor_shape = cursor_thicken_xpm;
1203 sp_event_context_update_cursor(event_context);
1204 }
1205 break;
1206 default:
1207 break;
1208 }
1209 break;
1211 case GDK_KEY_RELEASE:
1212 switch (get_group0_keyval(&event->key)) {
1213 case GDK_Control_L:
1214 case GDK_Control_R:
1215 dc->_message_context->clear();
1216 dc->hatch_spacing = 0;
1217 break;
1218 case GDK_Alt_L:
1219 case GDK_Alt_R:
1220 event_context->cursor_shape = cursor_calligraphy_xpm;
1221 sp_event_context_update_cursor(event_context);
1222 break;
1223 case GDK_Shift_L:
1224 case GDK_Shift_R:
1225 if (MOD__ALT) {
1226 event_context->cursor_shape = cursor_thin_xpm;
1227 sp_event_context_update_cursor(event_context);
1228 }
1229 break;
1230 case GDK_Meta_L:
1231 case GDK_Meta_R:
1232 event_context->cursor_shape = cursor_calligraphy_xpm;
1233 sp_event_context_update_cursor(event_context);
1234 break;
1235 default:
1236 break;
1237 }
1239 default:
1240 break;
1241 }
1243 if (!ret) {
1244 if (((SPEventContextClass *) parent_class)->root_handler) {
1245 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1246 }
1247 }
1249 return ret;
1250 }
1253 static void
1254 clear_current(SPDynaDrawContext *dc)
1255 {
1256 /* reset bpath */
1257 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
1258 /* reset curve */
1259 sp_curve_reset(dc->currentcurve);
1260 sp_curve_reset(dc->cal1);
1261 sp_curve_reset(dc->cal2);
1262 /* reset points */
1263 dc->npoints = 0;
1264 }
1266 static void
1267 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
1268 {
1269 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1271 if (!sp_curve_empty(dc->accumulated)) {
1272 NArtBpath *abp;
1273 gchar *str;
1275 if (!dc->repr) {
1276 /* Create object */
1277 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1278 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1280 /* Set style */
1281 sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
1283 dc->repr = repr;
1285 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1286 Inkscape::GC::release(dc->repr);
1287 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
1288 item->updateRepr();
1289 }
1290 abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
1291 str = sp_svg_write_path(abp);
1292 g_assert( str != NULL );
1293 g_free(abp);
1294 dc->repr->setAttribute("d", str);
1295 g_free(str);
1297 if (unionize) {
1298 sp_desktop_selection(desktop)->add(dc->repr);
1299 sp_selected_path_union_skip_undo();
1300 } else {
1301 if (dc->keep_selected) {
1302 sp_desktop_selection(desktop)->set(dc->repr);
1303 } else {
1304 sp_desktop_selection(desktop)->clear();
1305 }
1306 }
1308 } else {
1309 if (dc->repr) {
1310 sp_repr_unparent(dc->repr);
1311 }
1312 dc->repr = NULL;
1313 }
1315 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC,
1316 _("Draw calligraphic stroke"));
1317 }
1319 static void
1320 add_cap(SPCurve *curve,
1321 NR::Point const &pre, NR::Point const &from,
1322 NR::Point const &to, NR::Point const &post,
1323 double rounding)
1324 {
1325 NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
1326 double mag = NR::L2(vel);
1328 NR::Point v_in = from - pre;
1329 double mag_in = NR::L2(v_in);
1330 if ( mag_in > DYNA_EPSILON ) {
1331 v_in = mag * v_in / mag_in;
1332 } else {
1333 v_in = NR::Point(0, 0);
1334 }
1336 NR::Point v_out = to - post;
1337 double mag_out = NR::L2(v_out);
1338 if ( mag_out > DYNA_EPSILON ) {
1339 v_out = mag * v_out / mag_out;
1340 } else {
1341 v_out = NR::Point(0, 0);
1342 }
1344 if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
1345 sp_curve_curveto(curve, from + v_in, to + v_out, to);
1346 }
1347 }
1349 static void
1350 accumulate_calligraphic(SPDynaDrawContext *dc)
1351 {
1352 if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
1353 sp_curve_reset(dc->accumulated); /* Is this required ?? */
1354 SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
1356 g_assert(dc->cal1->end > 1);
1357 g_assert(rev_cal2->end > 1);
1358 g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
1359 g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
1360 g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
1361 g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
1362 g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
1363 g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
1365 sp_curve_append(dc->accumulated, dc->cal1, FALSE);
1367 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);
1369 sp_curve_append(dc->accumulated, rev_cal2, TRUE);
1371 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);
1373 sp_curve_closepath(dc->accumulated);
1375 sp_curve_unref(rev_cal2);
1377 sp_curve_reset(dc->cal1);
1378 sp_curve_reset(dc->cal2);
1379 }
1380 }
1382 static double square(double const x)
1383 {
1384 return x * x;
1385 }
1387 static void
1388 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1389 {
1390 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
1392 #ifdef DYNA_DRAW_VERBOSE
1393 g_print("[F&S:R=%c]", release?'T':'F');
1394 #endif
1396 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1397 return; // just clicked
1399 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1400 #define BEZIER_SIZE 4
1401 #define BEZIER_MAX_BEZIERS 8
1402 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1404 #ifdef DYNA_DRAW_VERBOSE
1405 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1406 dc->npoints, release ? "TRUE" : "FALSE");
1407 #endif
1409 /* Current calligraphic */
1410 if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
1411 /* dc->npoints > 0 */
1412 /* g_print("calligraphics(1|2) reset\n"); */
1413 sp_curve_reset(dc->cal1);
1414 sp_curve_reset(dc->cal2);
1416 sp_curve_moveto(dc->cal1, dc->point1[0]);
1417 sp_curve_moveto(dc->cal2, dc->point2[0]);
1418 }
1420 NR::Point b1[BEZIER_MAX_LENGTH];
1421 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1422 tolerance_sq, BEZIER_MAX_BEZIERS);
1423 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1425 NR::Point b2[BEZIER_MAX_LENGTH];
1426 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1427 tolerance_sq, BEZIER_MAX_BEZIERS);
1428 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1430 if ( nb1 != -1 && nb2 != -1 ) {
1431 /* Fit and draw and reset state */
1432 #ifdef DYNA_DRAW_VERBOSE
1433 g_print("nb1:%d nb2:%d\n", nb1, nb2);
1434 #endif
1435 /* CanvasShape */
1436 if (! release) {
1437 sp_curve_reset(dc->currentcurve);
1438 sp_curve_moveto(dc->currentcurve, b1[0]);
1439 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1440 sp_curve_curveto(dc->currentcurve, bp1[1],
1441 bp1[2], bp1[3]);
1442 }
1443 sp_curve_lineto(dc->currentcurve,
1444 b2[BEZIER_SIZE*(nb2-1) + 3]);
1445 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1446 sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
1447 }
1448 // FIXME: dc->segments is always NULL at this point??
1449 if (!dc->segments) { // first segment
1450 add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1451 }
1452 sp_curve_closepath(dc->currentcurve);
1453 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1454 }
1456 /* Current calligraphic */
1457 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1458 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
1459 }
1460 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1461 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
1462 }
1463 } else {
1464 /* fixme: ??? */
1465 #ifdef DYNA_DRAW_VERBOSE
1466 g_print("[fit_and_split] failed to fit-cubic.\n");
1467 #endif
1468 draw_temporary_box(dc);
1470 for (gint i = 1; i < dc->npoints; i++) {
1471 sp_curve_lineto(dc->cal1, dc->point1[i]);
1472 }
1473 for (gint i = 1; i < dc->npoints; i++) {
1474 sp_curve_lineto(dc->cal2, dc->point2[i]);
1475 }
1476 }
1478 /* Fit and draw and copy last point */
1479 #ifdef DYNA_DRAW_VERBOSE
1480 g_print("[%d]Yup\n", dc->npoints);
1481 #endif
1482 if (!release) {
1483 g_assert(!sp_curve_empty(dc->currentcurve));
1485 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1486 SP_TYPE_CANVAS_BPATH,
1487 NULL);
1488 SPCurve *curve = sp_curve_copy(dc->currentcurve);
1489 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1490 sp_curve_unref(curve);
1492 guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1493 //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1494 double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
1495 double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1496 //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1497 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1498 //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1499 //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);
1500 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1501 /* fixme: Cannot we cascade it to root more clearly? */
1502 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1504 dc->segments = g_slist_prepend(dc->segments, cbp);
1505 }
1507 dc->point1[0] = dc->point1[dc->npoints - 1];
1508 dc->point2[0] = dc->point2[dc->npoints - 1];
1509 dc->npoints = 1;
1510 } else {
1511 draw_temporary_box(dc);
1512 }
1513 }
1515 static void
1516 draw_temporary_box(SPDynaDrawContext *dc)
1517 {
1518 sp_curve_reset(dc->currentcurve);
1520 sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
1521 for (gint i = dc->npoints-2; i >= 0; i--) {
1522 sp_curve_lineto(dc->currentcurve, dc->point1[i]);
1523 }
1524 for (gint i = 0; i < dc->npoints; i++) {
1525 sp_curve_lineto(dc->currentcurve, dc->point2[i]);
1526 }
1527 if (dc->npoints >= 2) {
1528 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);
1529 }
1531 sp_curve_closepath(dc->currentcurve);
1532 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1533 }
1535 /*
1536 Local Variables:
1537 mode:c++
1538 c-file-style:"stroustrup"
1539 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1540 indent-tabs-mode:nil
1541 fill-column:99
1542 End:
1543 */
1544 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :