1 /** \file
2 * Pencil event context implementation.
3 */
5 /*
6 * Authors:
7 * Lauris Kaplinski <lauris@kaplinski.com>
8 * bulia byak <buliabyak@users.sf.net>
9 *
10 * Copyright (C) 2000 Lauris Kaplinski
11 * Copyright (C) 2000-2001 Ximian, Inc.
12 * Copyright (C) 2002 Lauris Kaplinski
13 * Copyright (C) 2004 Monash University
14 *
15 * Released under GNU GPL, read the file 'COPYING' for more information
16 */
18 #include <gdk/gdkkeysyms.h>
20 #include "pencil-context.h"
21 #include "desktop.h"
22 #include "desktop-handles.h"
23 #include "selection.h"
24 #include "selection-chemistry.h"
25 #include "draw-anchor.h"
26 #include "message-stack.h"
27 #include "message-context.h"
28 #include "modifier-fns.h"
29 #include "sp-path.h"
30 #include "preferences.h"
31 #include "snap.h"
32 #include "pixmaps/cursor-pencil.xpm"
33 #include <2geom/bezier-utils.h>
34 #include "display/canvas-bpath.h"
35 #include <glibmm/i18n.h>
36 #include "libnr/in-svg-plane.h"
37 #include "context-fns.h"
38 #include "sp-namedview.h"
39 #include "xml/repr.h"
40 #include "document.h"
41 #include "desktop-style.h"
42 #include "macros.h"
43 #include "display/curve.h"
45 static void sp_pencil_context_class_init(SPPencilContextClass *klass);
46 static void sp_pencil_context_init(SPPencilContext *pc);
47 static void sp_pencil_context_setup(SPEventContext *ec);
48 static void sp_pencil_context_dispose(GObject *object);
50 static gint sp_pencil_context_root_handler(SPEventContext *event_context, GdkEvent *event);
51 static gint pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent);
52 static gint pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent);
53 static gint pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent);
54 static gint pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state);
55 static gint pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const state);
57 static void spdc_set_startpoint(SPPencilContext *pc, Geom::Point const p);
58 static void spdc_set_endpoint(SPPencilContext *pc, Geom::Point const p);
59 static void spdc_finish_endpoint(SPPencilContext *pc);
60 static void spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint state);
61 static void fit_and_split(SPPencilContext *pc);
62 static void interpolate(SPPencilContext *pc);
63 static void sketch_interpolate(SPPencilContext *pc);
65 static SPDrawContextClass *pencil_parent_class;
66 static Geom::Point pencil_drag_origin_w(0, 0);
67 static bool pencil_within_tolerance = false;
69 /**
70 * Register SPPencilContext class with Gdk and return its type number.
71 */
72 GType
73 sp_pencil_context_get_type()
74 {
75 static GType type = 0;
76 if (!type) {
77 GTypeInfo info = {
78 sizeof(SPPencilContextClass),
79 NULL, NULL,
80 (GClassInitFunc) sp_pencil_context_class_init,
81 NULL, NULL,
82 sizeof(SPPencilContext),
83 4,
84 (GInstanceInitFunc) sp_pencil_context_init,
85 NULL, /* value_table */
86 };
87 type = g_type_register_static(SP_TYPE_DRAW_CONTEXT, "SPPencilContext", &info, (GTypeFlags)0);
88 }
89 return type;
90 }
92 /**
93 * Initialize SPPencilContext vtable.
94 */
95 static void
96 sp_pencil_context_class_init(SPPencilContextClass *klass)
97 {
98 GObjectClass *object_class;
99 SPEventContextClass *event_context_class;
101 object_class = (GObjectClass *) klass;
102 event_context_class = (SPEventContextClass *) klass;
104 pencil_parent_class = (SPDrawContextClass*)g_type_class_peek_parent(klass);
106 object_class->dispose = sp_pencil_context_dispose;
108 event_context_class->setup = sp_pencil_context_setup;
109 event_context_class->root_handler = sp_pencil_context_root_handler;
110 }
112 /**
113 * Callback to initialize SPPencilContext object.
114 */
115 static void
116 sp_pencil_context_init(SPPencilContext *pc)
117 {
118 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
120 event_context->cursor_shape = cursor_pencil_xpm;
121 event_context->hot_x = 4;
122 event_context->hot_y = 4;
124 pc->npoints = 0;
125 pc->state = SP_PENCIL_CONTEXT_IDLE;
126 pc->req_tangent = Geom::Point(0, 0);
128 // since SPPencilContext is not properly constructed...
129 pc->sketch_interpolation = Geom::Path();
130 pc->sketch_n = 0;
131 }
133 /**
134 * Callback to setup SPPencilContext object.
135 */
136 static void
137 sp_pencil_context_setup(SPEventContext *ec)
138 {
139 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
140 if (prefs->getBool("/tools/freehand/pencil/selcue")) {
141 ec->enableSelectionCue();
142 }
144 if (((SPEventContextClass *) pencil_parent_class)->setup) {
145 ((SPEventContextClass *) pencil_parent_class)->setup(ec);
146 }
148 SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
149 pc->is_drawing = false;
151 pc->anchor_statusbar = false;
152 }
154 static void
155 sp_pencil_context_dispose(GObject *object)
156 {
157 G_OBJECT_CLASS(pencil_parent_class)->dispose(object);
158 }
160 /** Snaps new node relative to the previous node. */
161 static void
162 spdc_endpoint_snap(SPPencilContext const *pc, Geom::Point &p, guint const state)
163 {
164 if ((state & GDK_CONTROL_MASK)) { //CTRL enables constrained snapping
165 spdc_endpoint_snap_rotation(pc, p, pc->p[0], state);
166 } else {
167 if (!(state & GDK_SHIFT_MASK)) { //SHIFT disables all snapping, except the angular snapping above
168 //After all, the user explicitely asked for angular snapping by
169 //pressing CTRL
170 spdc_endpoint_snap_free(pc, p, state);
171 }
172 }
173 }
175 /**
176 * Callback for handling all pencil context events.
177 */
178 gint
179 sp_pencil_context_root_handler(SPEventContext *const ec, GdkEvent *event)
180 {
181 SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
183 gint ret = FALSE;
185 switch (event->type) {
186 case GDK_BUTTON_PRESS:
187 ret = pencil_handle_button_press(pc, event->button);
188 break;
190 case GDK_MOTION_NOTIFY:
191 ret = pencil_handle_motion_notify(pc, event->motion);
192 break;
194 case GDK_BUTTON_RELEASE:
195 ret = pencil_handle_button_release(pc, event->button);
196 break;
198 case GDK_KEY_PRESS:
199 ret = pencil_handle_key_press(pc, get_group0_keyval (&event->key), event->key.state);
200 break;
202 case GDK_KEY_RELEASE:
203 ret = pencil_handle_key_release(pc, get_group0_keyval (&event->key), event->key.state);
204 break;
206 default:
207 break;
208 }
210 if (!ret) {
211 gint (*const parent_root_handler)(SPEventContext *, GdkEvent *)
212 = ((SPEventContextClass *) pencil_parent_class)->root_handler;
213 if (parent_root_handler) {
214 ret = parent_root_handler(ec, event);
215 }
216 }
218 return ret;
219 }
221 static gint
222 pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent)
223 {
224 gint ret = FALSE;
225 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
226 if ( bevent.button == 1 && !event_context->space_panning) {
228 SPDrawContext *dc = SP_DRAW_CONTEXT (pc);
229 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
230 Inkscape::Selection *selection = sp_desktop_selection(desktop);
232 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
233 return TRUE;
234 }
236 Geom::Point const button_w(bevent.x, bevent.y);
238 /* Find desktop coordinates */
239 Geom::Point p = pc->desktop->w2d(button_w);
241 /* Test whether we hit any anchor. */
242 SPDrawAnchor *anchor = spdc_test_inside(pc, button_w);
244 pencil_drag_origin_w = Geom::Point(bevent.x,bevent.y);
245 pencil_within_tolerance = true;
247 switch (pc->state) {
248 case SP_PENCIL_CONTEXT_ADDLINE:
249 /* Current segment will be finished with release */
250 ret = TRUE;
251 break;
252 default:
253 /* Set first point of sequence */
254 if (bevent.state & GDK_CONTROL_MASK) {
255 spdc_create_single_dot(event_context, from_2geom(p), "/tools/freehand/pencil", bevent.state);
256 ret = true;
257 break;
258 }
259 if (anchor) {
260 p = to_2geom(anchor->dp);
261 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
262 } else {
264 if (!(bevent.state & GDK_SHIFT_MASK)) {
266 // This is the first click of a new curve; deselect item so that
267 // this curve is not combined with it (unless it is drawn from its
268 // anchor, which is handled by the sibling branch above)
269 selection->clear();
270 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
271 SnapManager &m = desktop->namedview->snap_manager;
272 m.setup(desktop);
273 Inkscape::SnappedPoint const s = m.freeSnap(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
274 if (s.getSnapped()) {
275 s.getPoint(p);
276 pc->prev_snap_was_succesful = true;
277 } else {
278 pc->prev_snap_was_succesful = false;
279 }
280 } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
281 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
282 }
283 }
284 pc->sa = anchor;
285 spdc_set_startpoint(pc, from_2geom(p));
286 ret = TRUE;
287 break;
288 }
290 pc->is_drawing = true;
291 }
292 return ret;
293 }
295 static gint
296 pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
297 {
298 if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
299 // mouse was accidentally moved during Ctrl+click;
300 // ignore the motion and create a single point
301 pc->is_drawing = false;
302 return TRUE;
303 }
304 gint ret = FALSE;
305 SPDesktop *const dt = pc->desktop;
307 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
308 if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
309 // allow scrolling
310 return FALSE;
311 }
313 if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
314 /* Grab mouse, so release will not pass unnoticed */
315 pc->grab = SP_CANVAS_ITEM(dt->acetate);
316 sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK |
317 GDK_BUTTON_RELEASE_MASK |
318 GDK_POINTER_MOTION_MASK ),
319 NULL, mevent.time);
320 }
322 /* Find desktop coordinates */
323 Geom::Point p = to_2geom(dt->w2d(Geom::Point(mevent.x, mevent.y)));
325 /* Test whether we hit any anchor. */
326 SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(mevent.x, mevent.y));
328 if (pencil_within_tolerance) {
329 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
330 gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
331 if ( Geom::LInfty( Geom::Point(mevent.x,mevent.y) - pencil_drag_origin_w ) < tolerance ) {
332 return FALSE; // Do not drag if we're within tolerance from origin.
333 }
334 }
336 // Once the user has moved farther than tolerance from the original location
337 // (indicating they intend to move the object, not click), then always process the
338 // motion notify coordinates as given (no snapping back to origin)
339 pencil_within_tolerance = false;
341 switch (pc->state) {
342 case SP_PENCIL_CONTEXT_ADDLINE:
343 /* Set red endpoint */
344 if (anchor) {
345 p = to_2geom(anchor->dp);
346 } else {
347 Geom::Point ptnr = from_2geom(p);
348 spdc_endpoint_snap(pc, ptnr, mevent.state);
349 p = to_2geom(ptnr);
350 }
351 spdc_set_endpoint(pc, from_2geom(p));
352 ret = TRUE;
353 break;
354 default:
355 /* We may be idle or already freehand */
356 if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
357 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
358 if ( !pc->sa && !pc->green_anchor ) {
359 /* Create green anchor */
360 pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
361 }
362 /** \todo
363 * fixme: I am not sure whether we want to snap to anchors
364 * in middle of freehand (Lauris)
365 */
366 SnapManager &m = dt->namedview->snap_manager;
368 if (anchor) {
369 p = to_2geom(anchor->dp);
370 } else if ((mevent.state & GDK_SHIFT_MASK) == 0) {
371 m.setup(dt);
372 Inkscape::SnappedPoint const s = m.freeSnap(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
373 if (s.getSnapped()) {
374 s.getPoint(p);
375 pc->prev_snap_was_succesful = true;
376 } else {
377 pc->prev_snap_was_succesful = false;
378 }
379 }
380 if ( pc->npoints != 0) { // buttonpress may have happened before we entered draw context!
381 if (!(pc->prev_snap_was_succesful && m.snapprefs.getSnapPostponedGlobally())) {
382 // When snapping is enabled but temporarily on hold because the mouse is moving
383 // fast, then we don't want to add nodes off-grid
384 spdc_add_freehand_point(pc, from_2geom(p), mevent.state);
385 ret = TRUE;
386 }
387 }
389 if (anchor && !pc->anchor_statusbar) {
390 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
391 pc->anchor_statusbar = true;
392 } else if (!anchor && pc->anchor_statusbar) {
393 pc->_message_context->clear();
394 pc->anchor_statusbar = false;
395 } else if (!anchor) {
396 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
397 }
399 } else {
400 if (anchor && !pc->anchor_statusbar) {
401 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
402 pc->anchor_statusbar = true;
403 } else if (!anchor && pc->anchor_statusbar) {
404 pc->_message_context->clear();
405 pc->anchor_statusbar = false;
406 }
407 }
408 break;
409 }
410 return ret;
411 }
413 static gint
414 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
415 {
416 gint ret = FALSE;
418 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
419 if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
420 SPDesktop *const dt = pc->desktop;
422 pc->is_drawing = false;
424 /* Find desktop coordinates */
425 Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y));
427 /* Test whether we hit any anchor. */
428 SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(revent.x,
429 revent.y));
431 switch (pc->state) {
432 case SP_PENCIL_CONTEXT_IDLE:
433 /* Releasing button in idle mode means single click */
434 /* We have already set up start point/anchor in button_press */
435 if (!(revent.state & GDK_CONTROL_MASK)) {
436 // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
437 pc->state = SP_PENCIL_CONTEXT_ADDLINE;
438 }
439 ret = TRUE;
440 break;
441 case SP_PENCIL_CONTEXT_ADDLINE:
442 /* Finish segment now */
443 if (anchor) {
444 p = anchor->dp;
445 } else {
446 spdc_endpoint_snap(pc, p, revent.state);
447 }
448 pc->ea = anchor;
449 spdc_set_endpoint(pc, p);
450 spdc_finish_endpoint(pc);
451 pc->state = SP_PENCIL_CONTEXT_IDLE;
452 ret = TRUE;
453 break;
454 case SP_PENCIL_CONTEXT_FREEHAND:
455 if (revent.state & GDK_MOD1_MASK) {
456 /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */
457 if (anchor) {
458 p = anchor->dp;
459 }
460 pc->ea = anchor;
462 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Sketching: release <b>Alt</b> to finalize current curve"));
464 sketch_interpolate(pc);
466 pc->state = SP_PENCIL_CONTEXT_SKETCH;
467 } else {
468 /* Finish segment now */
469 /// \todo fixme: Clean up what follows (Lauris)
470 if (anchor) {
471 p = anchor->dp;
472 }
473 pc->ea = anchor;
474 /* Write curves to object */
476 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
478 interpolate(pc);
479 spdc_concat_colors_and_flush(pc, FALSE);
480 pc->sa = NULL;
481 pc->ea = NULL;
482 if (pc->green_anchor) {
483 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
484 }
485 pc->state = SP_PENCIL_CONTEXT_IDLE;
486 }
487 ret = TRUE;
488 break;
489 case SP_PENCIL_CONTEXT_SKETCH:
490 default:
491 break;
492 }
494 if (pc->grab) {
495 /* Release grab now */
496 sp_canvas_item_ungrab(pc->grab, revent.time);
497 pc->grab = NULL;
498 }
500 ret = TRUE;
501 }
502 return ret;
503 }
505 static void
506 pencil_cancel (SPPencilContext *const pc)
507 {
508 if (pc->grab) {
509 /* Release grab now */
510 sp_canvas_item_ungrab(pc->grab, 0);
511 pc->grab = NULL;
512 }
514 pc->is_drawing = false;
516 pc->state = SP_PENCIL_CONTEXT_IDLE;
518 pc->red_curve->reset();
519 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
520 while (pc->green_bpaths) {
521 gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
522 pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
523 }
524 pc->green_curve->reset();
525 if (pc->green_anchor) {
526 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
527 }
529 pc->_message_context->clear();
530 pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
532 sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
533 }
535 static gint
536 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
537 {
538 gint ret = FALSE;
539 switch (keyval) {
540 case GDK_Up:
541 case GDK_Down:
542 case GDK_KP_Up:
543 case GDK_KP_Down:
544 // Prevent the zoom field from activation.
545 if (!mod_ctrl_only(state)) {
546 ret = TRUE;
547 }
548 break;
549 case GDK_Escape:
550 if (pc->npoints != 0) {
551 // if drawing, cancel, otherwise pass it up for deselecting
552 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
553 pencil_cancel (pc);
554 ret = TRUE;
555 }
556 }
557 break;
558 case GDK_z:
559 case GDK_Z:
560 if (mod_ctrl_only(state) && pc->npoints != 0) {
561 // if drawing, cancel, otherwise pass it up for undo
562 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
563 pencil_cancel (pc);
564 ret = TRUE;
565 }
566 }
567 break;
568 case GDK_g:
569 case GDK_G:
570 if (mod_shift_only(state)) {
571 sp_selection_to_guides(SP_EVENT_CONTEXT(pc)->desktop);
572 ret = true;
573 }
574 break;
575 default:
576 break;
577 }
578 return ret;
579 }
581 static gint
582 pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const /*state*/)
583 {
584 gint ret = FALSE;
585 switch (keyval) {
586 case GDK_Alt_L:
587 case GDK_Alt_R:
588 case GDK_Meta_L:
589 case GDK_Meta_R:
590 if (pc->state == SP_PENCIL_CONTEXT_SKETCH) {
591 spdc_concat_colors_and_flush(pc, FALSE);
592 pc->sketch_interpolation = Geom::Path();
593 pc->sketch_n = 0;
594 pc->sa = NULL;
595 pc->ea = NULL;
596 if (pc->green_anchor) {
597 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
598 }
599 pc->state = SP_PENCIL_CONTEXT_IDLE;
600 ret = TRUE;
601 }
602 break;
603 default:
604 break;
605 }
606 return ret;
607 }
609 /**
610 * Reset points and set new starting point.
611 */
612 static void
613 spdc_set_startpoint(SPPencilContext *const pc, Geom::Point const p)
614 {
615 pc->npoints = 0;
616 pc->red_curve_is_valid = false;
617 if (in_svg_plane(p)) {
618 pc->p[pc->npoints++] = p;
619 }
620 }
622 /**
623 * Change moving endpoint position.
624 * <ul>
625 * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
626 * <li>Otherwise we snap freely to whatever attractors are available.
627 * </ul>
628 *
629 * Number of points is (re)set to 2 always, 2nd point is modified.
630 * We change RED curve.
631 */
632 static void
633 spdc_set_endpoint(SPPencilContext *const pc, Geom::Point const p)
634 {
635 if (pc->npoints == 0) {
636 return;
637 /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
638 * zoom setting).
639 */
640 }
641 g_return_if_fail( pc->npoints > 0 );
643 pc->red_curve->reset();
644 if ( ( p == pc->p[0] )
645 || !in_svg_plane(p) )
646 {
647 pc->npoints = 1;
648 } else {
649 pc->p[1] = p;
650 pc->npoints = 2;
652 pc->red_curve->moveto(pc->p[0]);
653 pc->red_curve->lineto(pc->p[1]);
654 pc->red_curve_is_valid = true;
656 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
657 }
658 }
660 /**
661 * Finalize addline.
662 *
663 * \todo
664 * fixme: I'd like remove red reset from concat colors (lauris).
665 * Still not sure, how it will make most sense.
666 */
667 static void
668 spdc_finish_endpoint(SPPencilContext *const pc)
669 {
670 if ( ( pc->red_curve->is_empty() )
671 || ( *(pc->red_curve->first_point()) == *(pc->red_curve->second_point()) ) )
672 {
673 pc->red_curve->reset();
674 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
675 } else {
676 /* Write curves to object. */
677 spdc_concat_colors_and_flush(pc, FALSE);
678 pc->sa = NULL;
679 pc->ea = NULL;
680 }
681 }
684 static void
685 spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint /*state*/)
686 {
687 g_assert( pc->npoints > 0 );
688 g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));
690 if ( ( p != pc->p[ pc->npoints - 1 ] )
691 && in_svg_plane(p) )
692 {
693 pc->ps.push_back(p);
694 pc->p[pc->npoints++] = p;
695 fit_and_split(pc);
696 }
697 }
699 static inline double
700 square(double const x)
701 {
702 return x * x;
703 }
705 static void
706 interpolate(SPPencilContext *pc)
707 {
709 g_assert( pc->ps.size() > 1 );
711 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
712 double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
713 double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
714 tol) * exp(0.2*tol - 2);
716 g_assert(is_zero(pc->req_tangent)
717 || is_unit_vector(pc->req_tangent));
718 Geom::Point const tHatEnd(0, 0);
720 guint n_points = pc->ps.size();
721 pc->green_curve->reset();
722 pc->red_curve->reset();
723 pc->red_curve_is_valid = false;
725 Geom::Point * b = g_new(Geom::Point, 4*n_points);
726 Geom::Point * points = g_new(Geom::Point, 4*n_points);
727 for (int i = 0; i < pc->ps.size(); i++) {
728 points[i] = pc->ps[i];
729 }
731 // worst case gives us a segment per point
732 int max_segs = 4*n_points;
734 int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
735 tolerance_sq, max_segs);
737 if ( n_segs > 0)
738 {
739 /* Fit and draw and reset state */
740 pc->green_curve->moveto(b[0]);
741 for (int c = 0; c < n_segs; c++) {
742 pc->green_curve->curveto(b[4*c+1], b[4*c+2], b[4*c+3]);
743 }
744 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
746 /* Fit and draw and copy last point */
747 g_assert(!pc->green_curve->is_empty());
749 /* Set up direction of next curve. */
750 {
751 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
752 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
753 pc->p[0] = last_seg->finalPoint();
754 pc->npoints = 1;
755 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
756 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
757 ? Geom::Point(0, 0)
758 : Geom::unit_vector(req_vec) );
759 }
760 }
761 g_free(b);
762 g_free(points);
763 pc->ps.clear();
764 }
767 /* interpolates the sketched curve and tweaks the current sketch interpolation*/
768 static void
769 sketch_interpolate(SPPencilContext *pc)
770 {
771 g_assert( pc->ps.size() > 1 );
773 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
774 double const tol = 100.0 * 0.4; //prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
775 double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
776 tol) * exp(0.2*tol - 2);
778 bool average_all_sketches = prefs->getBool("/tools/freehand/pencil/average_all_sketches", true);
780 g_assert(is_zero(pc->req_tangent)
781 || is_unit_vector(pc->req_tangent));
782 Geom::Point const tHatEnd(0, 0);
784 guint n_points = pc->ps.size();
785 pc->red_curve->reset();
786 pc->red_curve_is_valid = false;
788 Geom::Point * b = g_new(Geom::Point, 4*n_points);
789 Geom::Point * points = g_new(Geom::Point, 4*n_points);
790 for (unsigned i = 0; i < pc->ps.size(); i++) {
791 points[i] = pc->ps[i];
792 }
794 // worst case gives us a segment per point
795 int max_segs = 4*n_points;
797 int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
798 tolerance_sq, max_segs);
800 if ( n_segs > 0)
801 {
802 // only take first cubic and average its coefficients with the old ones
804 Geom::Point coeffs[4];
805 if ( pc->sketch_n > 0 ) {
806 Geom::CubicBezier const * oldcubic = dynamic_cast<Geom::CubicBezier const *>( &pc->sketch_interpolation.front() );
807 g_assert(oldcubic);
808 for (unsigned i = 0; i < 4; i++){
809 if (average_all_sketches) {
810 // Average = (sum of all) / n
811 // = (sum of all + new one) / n+1
812 // = ((old average)*n + new one) / n+1
813 coeffs[i] = ((*oldcubic)[i] * pc->sketch_n + b[i]) / (pc->sketch_n + 1);
814 } else {
815 coeffs[i] = 0.5 * (b[i] + (*oldcubic)[i]);
816 }
817 }
818 } else {
819 for (unsigned i = 0; i < 4; i++){
820 coeffs[i] = b[i];
821 }
822 }
823 pc->sketch_n++;
825 pc->sketch_interpolation.start(coeffs[0]);
826 pc->sketch_interpolation.appendNew<Geom::CubicBezier>(coeffs[1], coeffs[2], coeffs[3]);
828 Geom::PathVector temp;
829 temp.push_back(pc->sketch_interpolation);
831 pc->green_curve->reset();
832 pc->green_curve->set_pathvector(temp);
833 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
835 /* Fit and draw and copy last point */
836 g_assert(!pc->green_curve->is_empty());
838 /* Set up direction of next curve. */
839 {
840 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
841 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
842 pc->p[0] = last_seg->finalPoint();
843 pc->npoints = 1;
844 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
845 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
846 ? Geom::Point(0, 0)
847 : Geom::unit_vector(req_vec) );
848 }
849 }
850 g_free(b);
851 g_free(points);
852 pc->ps.clear();
853 }
855 static void
856 fit_and_split(SPPencilContext *pc)
857 {
858 g_assert( pc->npoints > 1 );
860 double const tolerance_sq = 0;
862 Geom::Point b[4];
863 g_assert(is_zero(pc->req_tangent)
864 || is_unit_vector(pc->req_tangent));
865 Geom::Point const tHatEnd(0, 0);
866 int const n_segs = Geom::bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
867 pc->req_tangent, tHatEnd,
868 tolerance_sq, 1);
869 if ( n_segs > 0
870 && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
871 {
872 /* Fit and draw and reset state */
873 pc->red_curve->reset();
874 pc->red_curve->moveto(b[0]);
875 pc->red_curve->curveto(b[1], b[2], b[3]);
876 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
877 pc->red_curve_is_valid = true;
878 } else {
879 /* Fit and draw and copy last point */
881 g_assert(!pc->red_curve->is_empty());
883 /* Set up direction of next curve. */
884 {
885 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->red_curve->last_segment());
886 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
887 pc->p[0] = last_seg->finalPoint();
888 pc->npoints = 1;
889 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
890 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
891 ? Geom::Point(0, 0)
892 : Geom::unit_vector(req_vec) );
893 }
895 pc->green_curve->append_continuous(pc->red_curve, 0.0625);
896 SPCurve *curve = pc->red_curve->copy();
898 /// \todo fixme:
899 SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
900 curve->unref();
901 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
903 pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
905 pc->red_curve_is_valid = false;
906 }
907 }
910 /*
911 Local Variables:
912 mode:c++
913 c-file-style:"stroustrup"
914 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
915 indent-tabs-mode:nil
916 fill-column:99
917 End:
918 */
919 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :