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 <2geom/isnan.h>
38 #include <2geom/pathvector.h>
39 #include <2geom/bezier-utils.h>
40 #include "display/curve.h"
41 #include <glib/gmem.h>
42 #include "macros.h"
43 #include "document.h"
44 #include "selection.h"
45 #include "desktop.h"
46 #include "desktop-events.h"
47 #include "desktop-handles.h"
48 #include "desktop-style.h"
49 #include "message-context.h"
50 #include "preferences.h"
51 #include "pixmaps/cursor-calligraphy.xpm"
52 #include "xml/repr.h"
53 #include "context-fns.h"
54 #include "sp-item.h"
55 #include "inkscape.h"
56 #include "color.h"
57 #include "splivarot.h"
58 #include "sp-item-group.h"
59 #include "sp-shape.h"
60 #include "sp-path.h"
61 #include "sp-text.h"
62 #include "display/canvas-bpath.h"
63 #include "display/canvas-arena.h"
64 #include "livarot/Shape.h"
66 #include "dyna-draw-context.h"
68 #define DDC_RED_RGBA 0xff0000ff
70 #define TOLERANCE_CALLIGRAPHIC 0.1
72 #define DYNA_EPSILON 0.5e-6
73 #define DYNA_EPSILON_START 0.5e-2
74 #define DYNA_VEL_START 1e-5
76 #define DYNA_MIN_WIDTH 1.0e-6
78 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
79 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
80 static void sp_dyna_draw_context_dispose(GObject *object);
82 static void sp_dyna_draw_context_setup(SPEventContext *ec);
83 static void sp_dyna_draw_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *value);
84 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
86 static void clear_current(SPDynaDrawContext *dc);
87 static void set_to_accumulated(SPDynaDrawContext *dc, bool unionize, bool subtract);
88 static void add_cap(SPCurve *curve, Geom::Point const &from, Geom::Point const &to, double rounding);
89 static bool accumulate_calligraphic(SPDynaDrawContext *dc);
91 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
93 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, Geom::Point p);
94 static Geom::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, Geom::Point v);
95 static Geom::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, Geom::Point n);
96 static void draw_temporary_box(SPDynaDrawContext *dc);
99 static SPEventContextClass *dd_parent_class = 0;
101 GType sp_dyna_draw_context_get_type(void)
102 {
103 static GType type = 0;
104 if (!type) {
105 GTypeInfo info = {
106 sizeof(SPDynaDrawContextClass),
107 0, // base_init
108 0, // base_finalize
109 (GClassInitFunc)sp_dyna_draw_context_class_init,
110 0, // class_finalize
111 0, // class_data
112 sizeof(SPDynaDrawContext),
113 0, // n_preallocs
114 (GInstanceInitFunc)sp_dyna_draw_context_init,
115 0 // value_table
116 };
117 type = g_type_register_static(SP_TYPE_COMMON_CONTEXT, "SPDynaDrawContext", &info, static_cast<GTypeFlags>(0));
118 }
119 return type;
120 }
122 static void
123 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
124 {
125 GObjectClass *object_class = (GObjectClass *) klass;
126 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
128 dd_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
130 object_class->dispose = sp_dyna_draw_context_dispose;
132 event_context_class->setup = sp_dyna_draw_context_setup;
133 event_context_class->set = sp_dyna_draw_context_set;
134 event_context_class->root_handler = sp_dyna_draw_context_root_handler;
135 }
137 static void
138 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
139 {
140 ddc->cursor_shape = cursor_calligraphy_xpm;
141 ddc->hot_x = 4;
142 ddc->hot_y = 4;
144 ddc->vel_thin = 0.1;
145 ddc->flatness = 0.9;
146 ddc->cap_rounding = 0.0;
148 ddc->abs_width = false;
149 ddc->keep_selected = true;
151 ddc->hatch_spacing = 0;
152 ddc->hatch_spacing_step = 0;
153 new (&ddc->hatch_pointer_past) std::list<double>();
154 new (&ddc->hatch_nearest_past) std::list<double>();
155 new (&ddc->inertia_vectors) std::list<Geom::Point>();
156 new (&ddc->hatch_vectors) std::list<Geom::Point>();
157 ddc->hatch_last_nearest = Geom::Point(0,0);
158 ddc->hatch_last_pointer = Geom::Point(0,0);
159 ddc->hatch_escaped = false;
160 ddc->hatch_area = NULL;
161 ddc->hatch_item = NULL;
162 ddc->hatch_livarot_path = NULL;
164 ddc->trace_bg = false;
165 ddc->just_started_drawing = false;
166 }
168 static void
169 sp_dyna_draw_context_dispose(GObject *object)
170 {
171 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
173 if (ddc->hatch_area) {
174 gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
175 ddc->hatch_area = NULL;
176 }
179 G_OBJECT_CLASS(dd_parent_class)->dispose(object);
181 ddc->hatch_pointer_past.~list();
182 ddc->hatch_nearest_past.~list();
183 ddc->inertia_vectors.~list();
184 ddc->hatch_vectors.~list();
185 }
187 static void
188 sp_dyna_draw_context_setup(SPEventContext *ec)
189 {
190 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
192 if (((SPEventContextClass *) dd_parent_class)->setup)
193 ((SPEventContextClass *) dd_parent_class)->setup(ec);
195 ddc->accumulated = new SPCurve();
196 ddc->currentcurve = new SPCurve();
198 ddc->cal1 = new SPCurve();
199 ddc->cal2 = new SPCurve();
201 ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
202 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
203 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
204 /* fixme: Cannot we cascade it to root more clearly? */
205 g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
207 {
208 /* TODO: this can be done either with an arcto, and should maybe also be put in a general file (other tools use this as well) */
209 SPCurve *c = new SPCurve();
210 const double C1 = 0.552;
211 c->moveto(-1,0);
212 c->curveto(-1, C1, -C1, 1, 0, 1 );
213 c->curveto(C1, 1, 1, C1, 1, 0 );
214 c->curveto(1, -C1, C1, -1, 0, -1 );
215 c->curveto(-C1, -1, -1, -C1, -1, 0 );
216 c->closepath();
217 ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
218 c->unref();
219 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
220 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
221 sp_canvas_item_hide(ddc->hatch_area);
222 }
224 sp_event_context_read(ec, "mass");
225 sp_event_context_read(ec, "wiggle");
226 sp_event_context_read(ec, "angle");
227 sp_event_context_read(ec, "width");
228 sp_event_context_read(ec, "thinning");
229 sp_event_context_read(ec, "tremor");
230 sp_event_context_read(ec, "flatness");
231 sp_event_context_read(ec, "tracebackground");
232 sp_event_context_read(ec, "usepressure");
233 sp_event_context_read(ec, "usetilt");
234 sp_event_context_read(ec, "abs_width");
235 sp_event_context_read(ec, "keep_selected");
236 sp_event_context_read(ec, "cap_rounding");
238 ddc->is_drawing = false;
239 ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
241 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
242 if (prefs->getBool("/tools/calligraphic/selcue")) {
243 ec->enableSelectionCue();
244 }
245 }
247 static void
248 sp_dyna_draw_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val)
249 {
250 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
251 Glib::ustring path = val->getEntryName();
253 if (path == "tracebackground") {
254 ddc->trace_bg = val->getBool();
255 } else if (path == "keep_selected") {
256 ddc->keep_selected = val->getBool();
257 } else {
258 //pass on up to parent class to handle common attributes.
259 if ( dd_parent_class->set ) {
260 dd_parent_class->set(ec, val);
261 }
262 }
264 //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
265 }
267 static double
268 flerp(double f0, double f1, double p)
269 {
270 return f0 + ( f1 - f0 ) * p;
271 }
273 /* Get normalized point */
274 static Geom::Point
275 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, Geom::Point v)
276 {
277 Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
278 double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
279 return Geom::Point(( v[Geom::X] - drect.min()[Geom::X] ) / max, ( v[Geom::Y] - drect.min()[Geom::Y] ) / max);
280 }
282 /* Get view point */
283 static Geom::Point
284 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, Geom::Point n)
285 {
286 Geom::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
287 double const max = MAX ( drect.dimensions()[Geom::X], drect.dimensions()[Geom::Y] );
288 return Geom::Point(n[Geom::X] * max + drect.min()[Geom::X], n[Geom::Y] * max + drect.min()[Geom::Y]);
289 }
291 static void
292 sp_dyna_draw_reset(SPDynaDrawContext *dc, Geom::Point p)
293 {
294 dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
295 dc->vel = Geom::Point(0,0);
296 dc->vel_max = 0;
297 dc->acc = Geom::Point(0,0);
298 dc->ang = Geom::Point(0,0);
299 dc->del = Geom::Point(0,0);
300 }
302 static void
303 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
304 {
305 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
306 dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
307 else
308 dc->pressure = DDC_DEFAULT_PRESSURE;
310 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
311 dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
312 else
313 dc->xtilt = DDC_DEFAULT_TILT;
315 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
316 dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
317 else
318 dc->ytilt = DDC_DEFAULT_TILT;
319 }
322 static gboolean
323 sp_dyna_draw_apply(SPDynaDrawContext *dc, Geom::Point p)
324 {
325 Geom::Point n = sp_dyna_draw_get_npoint(dc, p);
327 /* Calculate mass and drag */
328 double const mass = flerp(1.0, 160.0, dc->mass);
329 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
331 /* Calculate force and acceleration */
332 Geom::Point force = n - dc->cur;
334 // If force is below the absolute threshold DYNA_EPSILON,
335 // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
336 // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
337 // discard this move.
338 // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
339 // especially bothersome at the start of the stroke where we don't yet have the inertia to
340 // smooth them out.
341 if ( Geom::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && Geom::L2(force) < DYNA_EPSILON_START)) {
342 return FALSE;
343 }
345 dc->acc = force / mass;
347 /* Calculate new velocity */
348 dc->vel += dc->acc;
350 if (Geom::L2(dc->vel) > dc->vel_max)
351 dc->vel_max = Geom::L2(dc->vel);
353 /* Calculate angle of drawing tool */
355 double a1;
356 if (dc->usetilt) {
357 // 1a. calculate nib angle from input device tilt:
358 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
360 if (length > 0) {
361 Geom::Point ang1 = Geom::Point(dc->ytilt/length, dc->xtilt/length);
362 a1 = atan2(ang1);
363 }
364 else
365 a1 = 0.0;
366 }
367 else {
368 // 1b. fixed dc->angle (absolutely flat nib):
369 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
370 Geom::Point ang1 = Geom::Point(-sin(radians), cos(radians));
371 a1 = atan2(ang1);
372 }
374 // 2. perpendicular to dc->vel (absolutely non-flat nib):
375 gdouble const mag_vel = Geom::L2(dc->vel);
376 if ( mag_vel < DYNA_EPSILON ) {
377 return FALSE;
378 }
379 Geom::Point ang2 = Geom::rot90(dc->vel) / mag_vel;
381 // 3. Average them using flatness parameter:
382 // calculate angles
383 double a2 = atan2(ang2);
384 // flip a2 to force it to be in the same half-circle as a1
385 bool flipped = false;
386 if (fabs (a2-a1) > 0.5*M_PI) {
387 a2 += M_PI;
388 flipped = true;
389 }
390 // normalize a2
391 if (a2 > M_PI)
392 a2 -= 2*M_PI;
393 if (a2 < -M_PI)
394 a2 += 2*M_PI;
395 // find the flatness-weighted bisector angle, unflip if a2 was flipped
396 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
397 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
399 // Try to detect a sudden flip when the new angle differs too much from the previous for the
400 // current velocity; in that case discard this move
401 double angle_delta = Geom::L2(Geom::Point (cos (new_ang), sin (new_ang)) - dc->ang);
402 if ( angle_delta / Geom::L2(dc->vel) > 4000 ) {
403 return FALSE;
404 }
406 // convert to point
407 dc->ang = Geom::Point (cos (new_ang), sin (new_ang));
409 // g_print ("force %g acc %g vel_max %g vel %g a1 %g a2 %g new_ang %g\n", Geom::L2(force), Geom::L2(dc->acc), dc->vel_max, Geom::L2(dc->vel), a1, a2, new_ang);
411 /* Apply drag */
412 dc->vel *= 1.0 - drag;
414 /* Update position */
415 dc->last = dc->cur;
416 dc->cur += dc->vel;
418 return TRUE;
419 }
421 static void
422 sp_dyna_draw_brush(SPDynaDrawContext *dc)
423 {
424 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
426 // How much velocity thins strokestyle
427 double vel_thin = flerp (0, 160, dc->vel_thin);
429 // Influence of pressure on thickness
430 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
432 // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
433 // drag)
434 Geom::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
435 Geom::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
437 double trace_thick = 1;
438 if (dc->trace_bg) {
439 // pick single pixel
440 NRPixBlock pb;
441 int x = (int) floor(brush_w[Geom::X]);
442 int y = (int) floor(brush_w[Geom::Y]);
443 nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
444 sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
445 const unsigned char *s = NR_PIXBLOCK_PX(&pb);
446 double R = s[0] / 255.0;
447 double G = s[1] / 255.0;
448 double B = s[2] / 255.0;
449 double A = s[3] / 255.0;
450 double max = MAX (MAX (R, G), B);
451 double min = MIN (MIN (R, G), B);
452 double L = A * (max + min)/2 + (1 - A); // blend with white bg
453 trace_thick = 1 - L;
454 //g_print ("L %g thick %g\n", L, trace_thick);
455 }
457 double width = (pressure_thick * trace_thick - vel_thin * Geom::L2(dc->vel)) * dc->width;
459 double tremble_left = 0, tremble_right = 0;
460 if (dc->tremor > 0) {
461 // obtain two normally distributed random variables, using polar Box-Muller transform
462 double x1, x2, w, y1, y2;
463 do {
464 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
465 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
466 w = x1 * x1 + x2 * x2;
467 } while ( w >= 1.0 );
468 w = sqrt( (-2.0 * log( w ) ) / w );
469 y1 = x1 * w;
470 y2 = x2 * w;
472 // deflect both left and right edges randomly and independently, so that:
473 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
474 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
475 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
476 // comparatively smooth and slow ones excessively jittery
477 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
478 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*Geom::L2(dc->vel));
479 }
481 if ( width < 0.02 * dc->width ) {
482 width = 0.02 * dc->width;
483 }
485 double dezoomify_factor = 0.05 * 1000;
486 if (!dc->abs_width) {
487 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
488 }
490 Geom::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
491 Geom::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
493 dc->point1[dc->npoints] = brush + del_left;
494 dc->point2[dc->npoints] = brush - del_right;
496 dc->del = 0.5*(del_left + del_right);
498 dc->npoints++;
499 }
501 void
502 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
503 {
504 desktop->setToolboxAdjustmentValue (id, value);
505 }
507 static void
508 calligraphic_cancel(SPDynaDrawContext *dc)
509 {
510 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
511 dc->dragging = FALSE;
512 dc->is_drawing = false;
513 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
514 /* Remove all temporary line segments */
515 while (dc->segments) {
516 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
517 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
518 }
519 /* reset accumulated curve */
520 dc->accumulated->reset();
521 clear_current(dc);
522 if (dc->repr) {
523 dc->repr = NULL;
524 }
525 }
528 gint
529 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
530 GdkEvent *event)
531 {
532 SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
533 SPDesktop *desktop = event_context->desktop;
535 gint ret = FALSE;
537 switch (event->type) {
538 case GDK_BUTTON_PRESS:
539 if (event->button.button == 1 && !event_context->space_panning) {
541 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
543 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
544 return TRUE;
545 }
547 dc->accumulated->reset();
548 if (dc->repr) {
549 dc->repr = NULL;
550 }
552 /* initialize first point */
553 dc->npoints = 0;
555 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
556 ( GDK_KEY_PRESS_MASK |
557 GDK_BUTTON_RELEASE_MASK |
558 GDK_POINTER_MOTION_MASK |
559 GDK_BUTTON_PRESS_MASK ),
560 NULL,
561 event->button.time);
563 ret = TRUE;
565 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
566 dc->is_drawing = true;
567 dc->just_started_drawing = true;
568 }
569 break;
570 case GDK_MOTION_NOTIFY:
571 {
572 Geom::Point const motion_w(event->motion.x,
573 event->motion.y);
574 Geom::Point motion_dt(desktop->w2d(motion_w));
575 sp_dyna_draw_extinput(dc, event);
577 dc->_message_context->clear();
579 // for hatching:
580 double hatch_dist = 0;
581 Geom::Point hatch_unit_vector(0,0);
582 Geom::Point nearest(0,0);
583 Geom::Point pointer(0,0);
584 Geom::Matrix motion_to_curve(Geom::identity());
586 if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
588 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
589 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
590 // One item selected, and it's a path;
591 // let's try to track it as a guide
593 if (selected != dc->hatch_item) {
594 dc->hatch_item = selected;
595 if (dc->hatch_livarot_path)
596 delete dc->hatch_livarot_path;
597 dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
598 dc->hatch_livarot_path->ConvertWithBackData(0.01);
599 }
601 // calculate pointer point in the guide item's coords
602 motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
603 pointer = motion_dt * motion_to_curve;
605 // calculate the nearest point on the guide path
606 boost::optional<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
607 nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
610 // distance from pointer to nearest
611 hatch_dist = Geom::L2(pointer - nearest);
612 // unit-length vector
613 hatch_unit_vector = (pointer - nearest)/hatch_dist;
615 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
616 } else {
617 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
618 }
619 }
621 if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
622 dc->dragging = TRUE;
624 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
626 #define HATCH_VECTOR_ELEMENTS 12
627 #define INERTIA_ELEMENTS 24
628 #define SPEED_ELEMENTS 12
629 #define SPEED_MIN 0.3
630 #define SPEED_NORMAL 0.35
631 #define INERTIA_FORCE 0.5
633 // speed is the movement of the nearest point along the guide path, divided by
634 // the movement of the pointer at the same period; it is averaged for the last
635 // SPEED_ELEMENTS motion events. Normally, as you track the guide path, speed
636 // is about 1, i.e. the nearest point on the path is moved by about the same
637 // distance as the pointer. If the speed starts to decrease, we are losing
638 // contact with the guide; if it drops below SPEED_MIN, we are on our own and
639 // not attracted to guide anymore. Most often this happens when you have
640 // tracked to the end of a guide calligraphic stroke and keep moving
641 // further. We try to handle this situation gracefully: not stick with the
642 // guide forever but let go of it smoothly and without sharp jerks (non-zero
643 // mass recommended; with zero mass, jerks are still quite noticeable).
645 double speed = 1;
646 if (Geom::L2(dc->hatch_last_nearest) != 0) {
647 // the distance nearest moved since the last motion event
648 double nearest_moved = Geom::L2(nearest - dc->hatch_last_nearest);
649 // the distance pointer moved since the last motion event
650 double pointer_moved = Geom::L2(pointer - dc->hatch_last_pointer);
651 // store them in stacks limited to SPEED_ELEMENTS
652 dc->hatch_nearest_past.push_front(nearest_moved);
653 if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
654 dc->hatch_nearest_past.pop_back();
655 dc->hatch_pointer_past.push_front(pointer_moved);
656 if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
657 dc->hatch_pointer_past.pop_back();
659 // If the stacks are full,
660 if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
661 // calculate the sums of all stored movements
662 double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
663 double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
664 // and divide to get the speed
665 speed = nearest_sum/pointer_sum;
666 //g_print ("nearest sum %g pointer_sum %g speed %g\n", nearest_sum, pointer_sum, speed);
667 }
668 }
670 if ( dc->hatch_escaped // already escaped, do not reattach
671 || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
672 || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
673 ) {
674 // We are NOT attracted to the guide!
676 //g_print ("\nlast_nearest %g %g nearest %g %g pointer %g %g pos %d %g\n", dc->last_nearest[Geom::X], dc->last_nearest[Geom::Y], nearest[Geom::X], nearest[Geom::Y], pointer[Geom::X], pointer[Geom::Y], position->piece, position->t);
678 // Remember hatch_escaped so we don't get
679 // attracted again until the end of this stroke
680 dc->hatch_escaped = true;
682 if (dc->inertia_vectors.size() >= INERTIA_ELEMENTS/2) { // move by inertia
683 Geom::Point moved_past_escape = motion_dt - dc->inertia_vectors.front();
684 Geom::Point inertia =
685 dc->inertia_vectors.front() - dc->inertia_vectors.back();
687 double dot = Geom::dot (moved_past_escape, inertia);
688 dot /= Geom::L2(moved_past_escape) * Geom::L2(inertia);
690 if (dot > 0) { // mouse is still moving in approx the same direction
691 Geom::Point should_have_moved =
692 (inertia) * (1/Geom::L2(inertia)) * Geom::L2(moved_past_escape);
693 motion_dt = dc->inertia_vectors.front() +
694 (INERTIA_FORCE * should_have_moved + (1 - INERTIA_FORCE) * moved_past_escape);
695 }
696 }
698 } else {
700 // Calculate angle cosine of this vector-to-guide and all past vectors
701 // summed, to detect if we accidentally flipped to the other side of the
702 // guide
703 Geom::Point hatch_vector_accumulated = std::accumulate
704 (dc->hatch_vectors.begin(), dc->hatch_vectors.end(), Geom::Point(0,0));
705 double dot = Geom::dot (pointer - nearest, hatch_vector_accumulated);
706 dot /= Geom::L2(pointer - nearest) * Geom::L2(hatch_vector_accumulated);
708 if (dc->hatch_spacing != 0) { // spacing was already set
709 double target;
710 if (speed > SPEED_NORMAL) {
711 // all ok, strictly obey the spacing
712 target = dc->hatch_spacing;
713 } else {
714 // looks like we're starting to lose speed,
715 // so _gradually_ let go attraction to prevent jerks
716 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;
717 }
718 if (!IS_NAN(dot) && dot < -0.5) {// flip
719 target = -target;
720 }
722 // This is the track pointer that we will use instead of the real one
723 Geom::Point new_pointer = nearest + target * hatch_unit_vector;
725 // some limited feedback: allow persistent pulling to slightly change
726 // the spacing
727 dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
729 // return it to the desktop coords
730 motion_dt = new_pointer * motion_to_curve.inverse();
732 if (speed >= SPEED_NORMAL) {
733 dc->inertia_vectors.push_front(motion_dt);
734 if (dc->inertia_vectors.size() > INERTIA_ELEMENTS)
735 dc->inertia_vectors.pop_back();
736 }
738 } else {
739 // this is the first motion event, set the dist
740 dc->hatch_spacing = hatch_dist;
741 }
743 // remember last points
744 dc->hatch_last_pointer = pointer;
745 dc->hatch_last_nearest = nearest;
747 dc->hatch_vectors.push_front(pointer - nearest);
748 if (dc->hatch_vectors.size() > HATCH_VECTOR_ELEMENTS)
749 dc->hatch_vectors.pop_back();
750 }
752 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
754 } else {
755 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
756 }
758 if (dc->just_started_drawing) {
759 dc->just_started_drawing = false;
760 sp_dyna_draw_reset(dc, motion_dt);
761 }
763 if (!sp_dyna_draw_apply(dc, motion_dt)) {
764 ret = TRUE;
765 break;
766 }
768 if ( dc->cur != dc->last ) {
769 sp_dyna_draw_brush(dc);
770 g_assert( dc->npoints > 0 );
771 fit_and_split(dc, FALSE);
772 }
773 ret = TRUE;
774 }
776 // Draw the hatching circle if necessary
777 if (event->motion.state & GDK_CONTROL_MASK) {
778 if (dc->hatch_spacing == 0 && hatch_dist != 0) {
779 // Haven't set spacing yet: gray, center free, update radius live
780 Geom::Point c = desktop->w2d(motion_w);
781 Geom::Matrix const sm (Geom::Scale(hatch_dist, hatch_dist) * Geom::Translate(c));
782 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
783 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
784 sp_canvas_item_show(dc->hatch_area);
785 } else if (dc->dragging && !dc->hatch_escaped) {
786 // Tracking: green, center snapped, fixed radius
787 Geom::Point c = motion_dt;
788 Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
789 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
790 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
791 sp_canvas_item_show(dc->hatch_area);
792 } else if (dc->dragging && dc->hatch_escaped) {
793 // Tracking escaped: red, center free, fixed radius
794 Geom::Point c = motion_dt;
795 Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
797 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
798 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
799 sp_canvas_item_show(dc->hatch_area);
800 } else {
801 // Not drawing but spacing set: gray, center snapped, fixed radius
802 Geom::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
803 if (!IS_NAN(c[Geom::X]) && !IS_NAN(c[Geom::Y])) {
804 Geom::Matrix const sm (Geom::Scale(dc->hatch_spacing, dc->hatch_spacing) * Geom::Translate(c));
805 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
806 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
807 sp_canvas_item_show(dc->hatch_area);
808 }
809 }
810 } else {
811 sp_canvas_item_hide(dc->hatch_area);
812 }
813 }
814 break;
817 case GDK_BUTTON_RELEASE:
818 {
819 Geom::Point const motion_w(event->button.x, event->button.y);
820 Geom::Point const motion_dt(desktop->w2d(motion_w));
822 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
823 sp_canvas_end_forced_full_redraws(desktop->canvas);
824 dc->is_drawing = false;
826 if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
827 dc->dragging = FALSE;
829 sp_dyna_draw_apply(dc, motion_dt);
831 /* Remove all temporary line segments */
832 while (dc->segments) {
833 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
834 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
835 }
837 /* Create object */
838 fit_and_split(dc, TRUE);
839 if (accumulate_calligraphic(dc))
840 set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK, event->button.state & GDK_MOD1_MASK); // performs document_done
841 else
842 g_warning ("Failed to create path: invalid data in dc->cal1 or dc->cal2");
844 /* reset accumulated curve */
845 dc->accumulated->reset();
847 clear_current(dc);
848 if (dc->repr) {
849 dc->repr = NULL;
850 }
852 if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
853 if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
854 if (!dc->inertia_vectors.empty()) dc->inertia_vectors.clear();
855 if (!dc->hatch_vectors.empty()) dc->hatch_vectors.clear();
856 dc->hatch_last_nearest = Geom::Point(0,0);
857 dc->hatch_last_pointer = Geom::Point(0,0);
858 dc->hatch_escaped = false;
859 dc->hatch_item = NULL;
860 dc->hatch_livarot_path = NULL;
861 dc->just_started_drawing = false;
863 if (dc->hatch_spacing != 0 && !dc->keep_selected) {
864 // we do not select the newly drawn path, so increase spacing by step
865 if (dc->hatch_spacing_step == 0) {
866 dc->hatch_spacing_step = dc->hatch_spacing;
867 }
868 dc->hatch_spacing += dc->hatch_spacing_step;
869 }
871 dc->_message_context->clear();
872 ret = TRUE;
873 }
874 break;
875 }
877 case GDK_KEY_PRESS:
878 switch (get_group0_keyval (&event->key)) {
879 case GDK_Up:
880 case GDK_KP_Up:
881 if (!MOD__CTRL_ONLY) {
882 dc->angle += 5.0;
883 if (dc->angle > 90.0)
884 dc->angle = 90.0;
885 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
886 ret = TRUE;
887 }
888 break;
889 case GDK_Down:
890 case GDK_KP_Down:
891 if (!MOD__CTRL_ONLY) {
892 dc->angle -= 5.0;
893 if (dc->angle < -90.0)
894 dc->angle = -90.0;
895 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
896 ret = TRUE;
897 }
898 break;
899 case GDK_Right:
900 case GDK_KP_Right:
901 if (!MOD__CTRL_ONLY) {
902 dc->width += 0.01;
903 if (dc->width > 1.0)
904 dc->width = 1.0;
905 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
906 ret = TRUE;
907 }
908 break;
909 case GDK_Left:
910 case GDK_KP_Left:
911 if (!MOD__CTRL_ONLY) {
912 dc->width -= 0.01;
913 if (dc->width < 0.01)
914 dc->width = 0.01;
915 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
916 ret = TRUE;
917 }
918 break;
919 case GDK_Home:
920 case GDK_KP_Home:
921 dc->width = 0.01;
922 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
923 ret = TRUE;
924 break;
925 case GDK_End:
926 case GDK_KP_End:
927 dc->width = 1.0;
928 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
929 ret = TRUE;
930 break;
931 case GDK_x:
932 case GDK_X:
933 if (MOD__ALT_ONLY) {
934 desktop->setToolboxFocusTo ("altx-calligraphy");
935 ret = TRUE;
936 }
937 break;
938 case GDK_Escape:
939 if (dc->is_drawing) {
940 // if drawing, cancel, otherwise pass it up for deselecting
941 calligraphic_cancel (dc);
942 ret = TRUE;
943 }
944 break;
945 case GDK_z:
946 case GDK_Z:
947 if (MOD__CTRL_ONLY && dc->is_drawing) {
948 // if drawing, cancel, otherwise pass it up for undo
949 calligraphic_cancel (dc);
950 ret = TRUE;
951 }
952 break;
953 default:
954 break;
955 }
956 break;
958 case GDK_KEY_RELEASE:
959 switch (get_group0_keyval(&event->key)) {
960 case GDK_Control_L:
961 case GDK_Control_R:
962 dc->_message_context->clear();
963 dc->hatch_spacing = 0;
964 dc->hatch_spacing_step = 0;
965 break;
966 default:
967 break;
968 }
970 default:
971 break;
972 }
974 if (!ret) {
975 if (((SPEventContextClass *) dd_parent_class)->root_handler) {
976 ret = ((SPEventContextClass *) dd_parent_class)->root_handler(event_context, event);
977 }
978 }
980 return ret;
981 }
984 static void
985 clear_current(SPDynaDrawContext *dc)
986 {
987 /* reset bpath */
988 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
989 /* reset curve */
990 dc->currentcurve->reset();
991 dc->cal1->reset();
992 dc->cal2->reset();
993 /* reset points */
994 dc->npoints = 0;
995 }
997 static void
998 set_to_accumulated(SPDynaDrawContext *dc, bool unionize, bool subtract)
999 {
1000 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1002 if (!dc->accumulated->is_empty()) {
1003 if (!dc->repr) {
1004 /* Create object */
1005 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1006 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1008 /* Set style */
1009 sp_desktop_apply_style_tool (desktop, repr, "/tools/calligraphic", false);
1011 dc->repr = repr;
1013 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1014 Inkscape::GC::release(dc->repr);
1015 item->transform = sp_item_i2doc_affine(SP_ITEM(desktop->currentLayer())).inverse();
1016 item->updateRepr();
1017 }
1018 Geom::PathVector pathv = dc->accumulated->get_pathvector() * desktop->dt2doc();
1019 gchar *str = sp_svg_write_path(pathv);
1020 g_assert( str != NULL );
1021 dc->repr->setAttribute("d", str);
1022 g_free(str);
1024 if (unionize) {
1025 sp_desktop_selection(desktop)->add(dc->repr);
1026 sp_selected_path_union_skip_undo(desktop);
1027 } else if (subtract) {
1028 sp_desktop_selection(desktop)->add(dc->repr);
1029 sp_selected_path_diff_skip_undo(desktop);
1030 } else {
1031 if (dc->keep_selected) {
1032 sp_desktop_selection(desktop)->set(dc->repr);
1033 }
1034 }
1036 } else {
1037 if (dc->repr) {
1038 sp_repr_unparent(dc->repr);
1039 }
1040 dc->repr = NULL;
1041 }
1043 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC,
1044 _("Draw calligraphic stroke"));
1045 }
1047 static void
1048 add_cap(SPCurve *curve,
1049 Geom::Point const &from,
1050 Geom::Point const &to,
1051 double rounding)
1052 {
1053 if (Geom::L2( to - from ) > DYNA_EPSILON) {
1054 Geom::Point vel = rounding * Geom::rot90( to - from ) / sqrt(2.0);
1055 double mag = Geom::L2(vel);
1057 Geom::Point v = mag * Geom::rot90( to - from ) / Geom::L2( to - from );
1058 curve->curveto(from + v, to + v, to);
1059 }
1060 }
1062 static bool
1063 accumulate_calligraphic(SPDynaDrawContext *dc)
1064 {
1065 if (
1066 dc->cal1->is_empty() ||
1067 dc->cal2->is_empty() ||
1068 (dc->cal1->get_segment_count() <= 0) ||
1069 dc->cal1->first_path()->closed()
1070 ) {
1071 dc->cal1->reset();
1072 dc->cal2->reset();
1073 return false; // failure
1074 }
1076 SPCurve *rev_cal2 = dc->cal2->create_reverse();
1077 if (
1078 (rev_cal2->get_segment_count() <= 0) ||
1079 rev_cal2->first_path()->closed()
1080 ) {
1081 rev_cal2->unref();
1082 dc->cal1->reset();
1083 dc->cal2->reset();
1084 return false; // failure
1085 }
1087 Geom::CubicBezier const * dc_cal1_firstseg = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->first_segment() );
1088 Geom::CubicBezier const * rev_cal2_firstseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->first_segment() );
1089 Geom::CubicBezier const * dc_cal1_lastseg = dynamic_cast<Geom::CubicBezier const *>( dc->cal1->last_segment() );
1090 Geom::CubicBezier const * rev_cal2_lastseg = dynamic_cast<Geom::CubicBezier const *>( rev_cal2->last_segment() );
1092 if (
1093 !dc_cal1_firstseg ||
1094 !rev_cal2_firstseg ||
1095 !dc_cal1_lastseg ||
1096 !rev_cal2_lastseg
1097 ) {
1098 rev_cal2->unref();
1099 dc->cal1->reset();
1100 dc->cal2->reset();
1101 return false; // failure
1102 }
1104 dc->accumulated->reset(); /* Is this required ?? */
1106 dc->accumulated->append(dc->cal1, false);
1108 add_cap(dc->accumulated, (*dc_cal1_lastseg)[3], (*rev_cal2_firstseg)[0], dc->cap_rounding);
1110 dc->accumulated->append(rev_cal2, true);
1112 add_cap(dc->accumulated, (*rev_cal2_lastseg)[3], (*dc_cal1_firstseg)[0], dc->cap_rounding);
1114 dc->accumulated->closepath();
1116 rev_cal2->unref();
1118 dc->cal1->reset();
1119 dc->cal2->reset();
1121 return true; // success
1122 }
1124 static double square(double const x)
1125 {
1126 return x * x;
1127 }
1129 static void
1130 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1131 {
1132 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1134 double const tolerance_sq = square( desktop->w2d().descrim() * TOLERANCE_CALLIGRAPHIC );
1136 #ifdef DYNA_DRAW_VERBOSE
1137 g_print("[F&S:R=%c]", release?'T':'F');
1138 #endif
1140 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1141 return; // just clicked
1143 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1144 #define BEZIER_SIZE 4
1145 #define BEZIER_MAX_BEZIERS 8
1146 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1148 #ifdef DYNA_DRAW_VERBOSE
1149 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1150 dc->npoints, release ? "TRUE" : "FALSE");
1151 #endif
1153 /* Current calligraphic */
1154 if ( dc->cal1->is_empty() || dc->cal2->is_empty() ) {
1155 /* dc->npoints > 0 */
1156 /* g_print("calligraphics(1|2) reset\n"); */
1157 dc->cal1->reset();
1158 dc->cal2->reset();
1160 dc->cal1->moveto(dc->point1[0]);
1161 dc->cal2->moveto(dc->point2[0]);
1162 }
1164 Geom::Point b1[BEZIER_MAX_LENGTH];
1165 gint const nb1 = Geom::bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1166 tolerance_sq, BEZIER_MAX_BEZIERS);
1167 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1169 Geom::Point b2[BEZIER_MAX_LENGTH];
1170 gint const nb2 = Geom::bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1171 tolerance_sq, BEZIER_MAX_BEZIERS);
1172 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1174 if ( nb1 != -1 && nb2 != -1 ) {
1175 /* Fit and draw and reset state */
1176 #ifdef DYNA_DRAW_VERBOSE
1177 g_print("nb1:%d nb2:%d\n", nb1, nb2);
1178 #endif
1179 /* CanvasShape */
1180 if (! release) {
1181 dc->currentcurve->reset();
1182 dc->currentcurve->moveto(b1[0]);
1183 for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1184 dc->currentcurve->curveto(bp1[1], bp1[2], bp1[3]);
1185 }
1186 dc->currentcurve->lineto(b2[BEZIER_SIZE*(nb2-1) + 3]);
1187 for (Geom::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1188 dc->currentcurve->curveto(bp2[2], bp2[1], bp2[0]);
1189 }
1190 // FIXME: dc->segments is always NULL at this point??
1191 if (!dc->segments) { // first segment
1192 add_cap(dc->currentcurve, b2[0], b1[0], dc->cap_rounding);
1193 }
1194 dc->currentcurve->closepath();
1195 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1196 }
1198 /* Current calligraphic */
1199 for (Geom::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1200 dc->cal1->curveto(bp1[1], bp1[2], bp1[3]);
1201 }
1202 for (Geom::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1203 dc->cal2->curveto(bp2[1], bp2[2], bp2[3]);
1204 }
1205 } else {
1206 /* fixme: ??? */
1207 #ifdef DYNA_DRAW_VERBOSE
1208 g_print("[fit_and_split] failed to fit-cubic.\n");
1209 #endif
1210 draw_temporary_box(dc);
1212 for (gint i = 1; i < dc->npoints; i++) {
1213 dc->cal1->lineto(dc->point1[i]);
1214 }
1215 for (gint i = 1; i < dc->npoints; i++) {
1216 dc->cal2->lineto(dc->point2[i]);
1217 }
1218 }
1220 /* Fit and draw and copy last point */
1221 #ifdef DYNA_DRAW_VERBOSE
1222 g_print("[%d]Yup\n", dc->npoints);
1223 #endif
1224 if (!release) {
1225 g_assert(!dc->currentcurve->is_empty());
1227 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(desktop),
1228 SP_TYPE_CANVAS_BPATH,
1229 NULL);
1230 SPCurve *curve = dc->currentcurve->copy();
1231 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1232 curve->unref();
1234 guint32 fillColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", true);
1235 //guint32 strokeColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", false);
1236 double opacity = sp_desktop_get_master_opacity_tool (desktop, "/tools/calligraphic");
1237 double fillOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", true);
1238 //double strokeOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", false);
1239 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1240 //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1241 //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);
1242 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1243 /* fixme: Cannot we cascade it to root more clearly? */
1244 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), desktop);
1246 dc->segments = g_slist_prepend(dc->segments, cbp);
1247 }
1249 dc->point1[0] = dc->point1[dc->npoints - 1];
1250 dc->point2[0] = dc->point2[dc->npoints - 1];
1251 dc->npoints = 1;
1252 } else {
1253 draw_temporary_box(dc);
1254 }
1255 }
1257 static void
1258 draw_temporary_box(SPDynaDrawContext *dc)
1259 {
1260 dc->currentcurve->reset();
1262 dc->currentcurve->moveto(dc->point2[dc->npoints-1]);
1263 for (gint i = dc->npoints-2; i >= 0; i--) {
1264 dc->currentcurve->lineto(dc->point2[i]);
1265 }
1266 for (gint i = 0; i < dc->npoints; i++) {
1267 dc->currentcurve->lineto(dc->point1[i]);
1268 }
1270 if (dc->npoints >= 2) {
1271 add_cap(dc->currentcurve, dc->point1[dc->npoints-1], dc->point2[dc->npoints-1], dc->cap_rounding);
1272 }
1274 dc->currentcurve->closepath();
1275 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1276 }
1278 /*
1279 Local Variables:
1280 mode:c++
1281 c-file-style:"stroustrup"
1282 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1283 indent-tabs-mode:nil
1284 fill-column:99
1285 End:
1286 */
1287 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :