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/sbasis-to-bezier.h>
34 #include <2geom/bezier-utils.h>
35 #include "display/canvas-bpath.h"
36 #include <glibmm/i18n.h>
37 #include "libnr/in-svg-plane.h"
38 #include "context-fns.h"
39 #include "sp-namedview.h"
40 #include "xml/repr.h"
41 #include "document.h"
42 #include "desktop-style.h"
43 #include "macros.h"
44 #include "display/curve.h"
45 #include "livarot/Path.h"
47 static void sp_pencil_context_class_init(SPPencilContextClass *klass);
48 static void sp_pencil_context_init(SPPencilContext *pc);
49 static void sp_pencil_context_setup(SPEventContext *ec);
50 static void sp_pencil_context_dispose(GObject *object);
52 static gint sp_pencil_context_root_handler(SPEventContext *event_context, GdkEvent *event);
53 static gint pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent);
54 static gint pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent);
55 static gint pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent);
56 static gint pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state);
57 static gint pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const state);
59 static void spdc_set_startpoint(SPPencilContext *pc, Geom::Point const p);
60 static void spdc_set_endpoint(SPPencilContext *pc, Geom::Point const p);
61 static void spdc_finish_endpoint(SPPencilContext *pc);
62 static void spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint state);
63 static void fit_and_split(SPPencilContext *pc);
64 static void interpolate(SPPencilContext *pc);
65 static void sketch_interpolate(SPPencilContext *pc);
67 static SPDrawContextClass *pencil_parent_class;
68 static Geom::Point pencil_drag_origin_w(0, 0);
69 static bool pencil_within_tolerance = false;
71 /**
72 * Register SPPencilContext class with Gdk and return its type number.
73 */
74 GType
75 sp_pencil_context_get_type()
76 {
77 static GType type = 0;
78 if (!type) {
79 GTypeInfo info = {
80 sizeof(SPPencilContextClass),
81 NULL, NULL,
82 (GClassInitFunc) sp_pencil_context_class_init,
83 NULL, NULL,
84 sizeof(SPPencilContext),
85 4,
86 (GInstanceInitFunc) sp_pencil_context_init,
87 NULL, /* value_table */
88 };
89 type = g_type_register_static(SP_TYPE_DRAW_CONTEXT, "SPPencilContext", &info, (GTypeFlags)0);
90 }
91 return type;
92 }
94 /**
95 * Initialize SPPencilContext vtable.
96 */
97 static void
98 sp_pencil_context_class_init(SPPencilContextClass *klass)
99 {
100 GObjectClass *object_class;
101 SPEventContextClass *event_context_class;
103 object_class = (GObjectClass *) klass;
104 event_context_class = (SPEventContextClass *) klass;
106 pencil_parent_class = (SPDrawContextClass*)g_type_class_peek_parent(klass);
108 object_class->dispose = sp_pencil_context_dispose;
110 event_context_class->setup = sp_pencil_context_setup;
111 event_context_class->root_handler = sp_pencil_context_root_handler;
112 }
114 /**
115 * Callback to initialize SPPencilContext object.
116 */
117 static void
118 sp_pencil_context_init(SPPencilContext *pc)
119 {
120 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
122 event_context->cursor_shape = cursor_pencil_xpm;
123 event_context->hot_x = 4;
124 event_context->hot_y = 4;
126 pc->npoints = 0;
127 pc->state = SP_PENCIL_CONTEXT_IDLE;
128 pc->req_tangent = Geom::Point(0, 0);
130 // since SPPencilContext is not properly constructed...
131 pc->sketch_interpolation = Geom::Piecewise<Geom::D2<Geom::SBasis> >();
132 pc->sketch_n = 0;
133 }
135 /**
136 * Callback to setup SPPencilContext object.
137 */
138 static void
139 sp_pencil_context_setup(SPEventContext *ec)
140 {
141 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
142 if (prefs->getBool("/tools/freehand/pencil/selcue")) {
143 ec->enableSelectionCue();
144 }
146 if (((SPEventContextClass *) pencil_parent_class)->setup) {
147 ((SPEventContextClass *) pencil_parent_class)->setup(ec);
148 }
150 SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
151 pc->is_drawing = false;
153 pc->anchor_statusbar = false;
154 }
156 static void
157 sp_pencil_context_dispose(GObject *object)
158 {
159 G_OBJECT_CLASS(pencil_parent_class)->dispose(object);
160 }
162 /** Snaps new node relative to the previous node. */
163 static void
164 spdc_endpoint_snap(SPPencilContext const *pc, Geom::Point &p, guint const state)
165 {
166 if ((state & GDK_CONTROL_MASK)) { //CTRL enables constrained snapping
167 spdc_endpoint_snap_rotation(pc, p, pc->p[0], state);
168 } else {
169 if (!(state & GDK_SHIFT_MASK)) { //SHIFT disables all snapping, except the angular snapping above
170 //After all, the user explicitely asked for angular snapping by
171 //pressing CTRL
172 spdc_endpoint_snap_free(pc, p, state);
173 }
174 }
175 }
177 /**
178 * Callback for handling all pencil context events.
179 */
180 gint
181 sp_pencil_context_root_handler(SPEventContext *const ec, GdkEvent *event)
182 {
183 SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
185 gint ret = FALSE;
187 switch (event->type) {
188 case GDK_BUTTON_PRESS:
189 ret = pencil_handle_button_press(pc, event->button);
190 break;
192 case GDK_MOTION_NOTIFY:
193 ret = pencil_handle_motion_notify(pc, event->motion);
194 break;
196 case GDK_BUTTON_RELEASE:
197 ret = pencil_handle_button_release(pc, event->button);
198 break;
200 case GDK_KEY_PRESS:
201 ret = pencil_handle_key_press(pc, get_group0_keyval (&event->key), event->key.state);
202 break;
204 case GDK_KEY_RELEASE:
205 ret = pencil_handle_key_release(pc, get_group0_keyval (&event->key), event->key.state);
206 break;
208 default:
209 break;
210 }
212 if (!ret) {
213 gint (*const parent_root_handler)(SPEventContext *, GdkEvent *)
214 = ((SPEventContextClass *) pencil_parent_class)->root_handler;
215 if (parent_root_handler) {
216 ret = parent_root_handler(ec, event);
217 }
218 }
220 return ret;
221 }
223 static gint
224 pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent)
225 {
226 gint ret = FALSE;
227 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
228 if ( bevent.button == 1 && !event_context->space_panning) {
230 SPDrawContext *dc = SP_DRAW_CONTEXT (pc);
231 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
232 Inkscape::Selection *selection = sp_desktop_selection(desktop);
234 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
235 return TRUE;
236 }
238 Geom::Point const button_w(bevent.x, bevent.y);
240 /* Find desktop coordinates */
241 Geom::Point p = pc->desktop->w2d(button_w);
243 /* Test whether we hit any anchor. */
244 SPDrawAnchor *anchor = spdc_test_inside(pc, button_w);
246 pencil_drag_origin_w = Geom::Point(bevent.x,bevent.y);
247 pencil_within_tolerance = true;
249 switch (pc->state) {
250 case SP_PENCIL_CONTEXT_ADDLINE:
251 /* Current segment will be finished with release */
252 ret = TRUE;
253 break;
254 default:
255 /* Set first point of sequence */
256 SnapManager &m = desktop->namedview->snap_manager;
257 m.setup(desktop);
259 if (anchor) {
260 p = anchor->dp;
261 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
262 } else {
264 if (!(bevent.state & GDK_SHIFT_MASK)) {
265 // This is the first click of a new curve; deselect item so that
266 // this curve is not combined with it (unless it is drawn from its
267 // anchor, which is handled by the sibling branch above)
268 selection->clear();
269 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
270 m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, p, Inkscape::SNAPSOURCE_HANDLE);
271 } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
272 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
273 m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, p, Inkscape::SNAPSOURCE_HANDLE);
274 }
275 }
276 pc->sa = anchor;
277 spdc_set_startpoint(pc, p);
278 ret = TRUE;
279 break;
280 }
282 pc->is_drawing = true;
283 }
284 return ret;
285 }
287 static gint
288 pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
289 {
290 SPDesktop *const dt = pc->desktop;
292 if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
293 // mouse was accidentally moved during Ctrl+click;
294 // ignore the motion and create a single point
295 pc->is_drawing = false;
296 return TRUE;
297 }
298 gint ret = FALSE;
300 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
301 if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
302 // allow scrolling
303 return FALSE;
304 }
306 if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
307 /* Grab mouse, so release will not pass unnoticed */
308 pc->grab = SP_CANVAS_ITEM(dt->acetate);
309 sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK |
310 GDK_BUTTON_RELEASE_MASK |
311 GDK_POINTER_MOTION_MASK ),
312 NULL, mevent.time);
313 }
315 /* Find desktop coordinates */
316 Geom::Point p = dt->w2d(Geom::Point(mevent.x, mevent.y));
318 /* Test whether we hit any anchor. */
319 SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(mevent.x, mevent.y));
321 if (pencil_within_tolerance) {
322 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
323 gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
324 if ( Geom::LInfty( Geom::Point(mevent.x,mevent.y) - pencil_drag_origin_w ) < tolerance ) {
325 return FALSE; // Do not drag if we're within tolerance from origin.
326 }
327 }
329 // Once the user has moved farther than tolerance from the original location
330 // (indicating they intend to move the object, not click), then always process the
331 // motion notify coordinates as given (no snapping back to origin)
332 pencil_within_tolerance = false;
334 switch (pc->state) {
335 case SP_PENCIL_CONTEXT_ADDLINE:
336 /* Set red endpoint */
337 if (anchor) {
338 p = anchor->dp;
339 } else {
340 Geom::Point ptnr(p);
341 spdc_endpoint_snap(pc, ptnr, mevent.state);
342 p = ptnr;
343 }
344 spdc_set_endpoint(pc, p);
345 ret = TRUE;
346 break;
347 default:
348 /* We may be idle or already freehand */
349 if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
350 if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
351 sp_event_context_discard_delayed_snap_event(event_context);
352 }
353 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
355 if ( !pc->sa && !pc->green_anchor ) {
356 /* Create green anchor */
357 pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
358 }
359 /** \todo
360 * fixme: I am not sure whether we want to snap to anchors
361 * in middle of freehand (Lauris)
362 */
363 if (anchor) {
364 p = anchor->dp;
365 }
367 if ( pc->npoints != 0) { // buttonpress may have happened before we entered draw context!
368 spdc_add_freehand_point(pc, p, mevent.state);
369 ret = TRUE;
370 }
372 if (anchor && !pc->anchor_statusbar) {
373 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
374 pc->anchor_statusbar = true;
375 } else if (!anchor && pc->anchor_statusbar) {
376 pc->_message_context->clear();
377 pc->anchor_statusbar = false;
378 } else if (!anchor) {
379 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
380 }
382 } else {
383 if (anchor && !pc->anchor_statusbar) {
384 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
385 pc->anchor_statusbar = true;
386 } else if (!anchor && pc->anchor_statusbar) {
387 pc->_message_context->clear();
388 pc->anchor_statusbar = false;
389 }
390 }
391 break;
392 }
393 return ret;
394 }
396 static gint
397 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
398 {
399 gint ret = FALSE;
401 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
402 if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
403 SPDesktop *const dt = pc->desktop;
405 pc->is_drawing = false;
407 /* Find desktop coordinates */
408 Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y));
410 /* Test whether we hit any anchor. */
411 SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(revent.x,
412 revent.y));
414 switch (pc->state) {
415 case SP_PENCIL_CONTEXT_IDLE:
416 /* Releasing button in idle mode means single click */
417 /* We have already set up start point/anchor in button_press */
418 pc->state = SP_PENCIL_CONTEXT_ADDLINE;
419 ret = TRUE;
420 break;
421 case SP_PENCIL_CONTEXT_ADDLINE:
422 /* Finish segment now */
423 if (anchor) {
424 p = anchor->dp;
425 } else {
426 spdc_endpoint_snap(pc, p, revent.state);
427 }
428 pc->ea = anchor;
429 spdc_set_endpoint(pc, p);
430 spdc_finish_endpoint(pc);
431 pc->state = SP_PENCIL_CONTEXT_IDLE;
432 sp_event_context_discard_delayed_snap_event(event_context);
433 ret = TRUE;
434 break;
435 case SP_PENCIL_CONTEXT_FREEHAND:
436 if (revent.state & GDK_MOD1_MASK) {
437 /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */
439 sketch_interpolate(pc);
441 if (pc->green_anchor) {
442 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
443 }
445 pc->state = SP_PENCIL_CONTEXT_SKETCH;
446 } else {
447 /* Finish segment now */
448 /// \todo fixme: Clean up what follows (Lauris)
449 if (anchor) {
450 p = anchor->dp;
451 }
452 pc->ea = anchor;
453 /* Write curves to object */
455 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
457 interpolate(pc);
458 spdc_concat_colors_and_flush(pc, FALSE);
459 pc->sa = NULL;
460 pc->ea = NULL;
461 if (pc->green_anchor) {
462 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
463 }
464 pc->state = SP_PENCIL_CONTEXT_IDLE;
465 // reset sketch mode too
466 pc->sketch_n = 0;
467 }
468 ret = TRUE;
469 break;
470 case SP_PENCIL_CONTEXT_SKETCH:
471 default:
472 break;
473 }
475 if (pc->grab) {
476 /* Release grab now */
477 sp_canvas_item_ungrab(pc->grab, revent.time);
478 pc->grab = NULL;
479 }
481 ret = TRUE;
482 }
483 return ret;
484 }
486 static void
487 pencil_cancel (SPPencilContext *const pc)
488 {
489 if (pc->grab) {
490 /* Release grab now */
491 sp_canvas_item_ungrab(pc->grab, 0);
492 pc->grab = NULL;
493 }
495 pc->is_drawing = false;
496 pc->state = SP_PENCIL_CONTEXT_IDLE;
497 sp_event_context_discard_delayed_snap_event(SP_EVENT_CONTEXT(pc));
499 pc->red_curve->reset();
500 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
501 while (pc->green_bpaths) {
502 gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
503 pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
504 }
505 pc->green_curve->reset();
506 if (pc->green_anchor) {
507 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
508 }
510 pc->_message_context->clear();
511 pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
513 sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
514 }
516 static gint
517 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
518 {
519 gint ret = FALSE;
520 switch (keyval) {
521 case GDK_Up:
522 case GDK_Down:
523 case GDK_KP_Up:
524 case GDK_KP_Down:
525 // Prevent the zoom field from activation.
526 if (!mod_ctrl_only(state)) {
527 ret = TRUE;
528 }
529 break;
530 case GDK_Escape:
531 if (pc->npoints != 0) {
532 // if drawing, cancel, otherwise pass it up for deselecting
533 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
534 pencil_cancel (pc);
535 ret = TRUE;
536 }
537 }
538 break;
539 case GDK_z:
540 case GDK_Z:
541 if (mod_ctrl_only(state) && pc->npoints != 0) {
542 // if drawing, cancel, otherwise pass it up for undo
543 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
544 pencil_cancel (pc);
545 ret = TRUE;
546 }
547 }
548 break;
549 case GDK_g:
550 case GDK_G:
551 if (mod_shift_only(state)) {
552 sp_selection_to_guides(SP_EVENT_CONTEXT(pc)->desktop);
553 ret = true;
554 }
555 break;
556 case GDK_Alt_L:
557 case GDK_Alt_R:
558 case GDK_Meta_L:
559 case GDK_Meta_R:
560 if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
561 pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("<b>Sketch mode</b>: holding <b>Alt</b> interpolates between sketched paths. Release <b>Alt</b> to finalize."));
562 }
563 break;
564 default:
565 break;
566 }
567 return ret;
568 }
570 static gint
571 pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const /*state*/)
572 {
573 gint ret = FALSE;
574 switch (keyval) {
575 case GDK_Alt_L:
576 case GDK_Alt_R:
577 case GDK_Meta_L:
578 case GDK_Meta_R:
579 if (pc->state == SP_PENCIL_CONTEXT_SKETCH) {
580 spdc_concat_colors_and_flush(pc, FALSE);
581 pc->sketch_n = 0;
582 pc->sa = NULL;
583 pc->ea = NULL;
584 if (pc->green_anchor) {
585 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
586 }
587 pc->state = SP_PENCIL_CONTEXT_IDLE;
588 sp_event_context_discard_delayed_snap_event(SP_EVENT_CONTEXT(pc));
589 pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand sketch"));
590 ret = TRUE;
591 }
592 break;
593 default:
594 break;
595 }
596 return ret;
597 }
599 /**
600 * Reset points and set new starting point.
601 */
602 static void
603 spdc_set_startpoint(SPPencilContext *const pc, Geom::Point const p)
604 {
605 pc->npoints = 0;
606 pc->red_curve_is_valid = false;
607 if (in_svg_plane(p)) {
608 pc->p[pc->npoints++] = p;
609 }
610 }
612 /**
613 * Change moving endpoint position.
614 * <ul>
615 * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
616 * <li>Otherwise we snap freely to whatever attractors are available.
617 * </ul>
618 *
619 * Number of points is (re)set to 2 always, 2nd point is modified.
620 * We change RED curve.
621 */
622 static void
623 spdc_set_endpoint(SPPencilContext *const pc, Geom::Point const p)
624 {
625 if (pc->npoints == 0) {
626 return;
627 /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
628 * zoom setting).
629 */
630 }
631 g_return_if_fail( pc->npoints > 0 );
633 pc->red_curve->reset();
634 if ( ( p == pc->p[0] )
635 || !in_svg_plane(p) )
636 {
637 pc->npoints = 1;
638 } else {
639 pc->p[1] = p;
640 pc->npoints = 2;
642 pc->red_curve->moveto(pc->p[0]);
643 pc->red_curve->lineto(pc->p[1]);
644 pc->red_curve_is_valid = true;
646 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
647 }
648 }
650 /**
651 * Finalize addline.
652 *
653 * \todo
654 * fixme: I'd like remove red reset from concat colors (lauris).
655 * Still not sure, how it will make most sense.
656 */
657 static void
658 spdc_finish_endpoint(SPPencilContext *const pc)
659 {
660 if ( ( pc->red_curve->is_empty() )
661 || ( *(pc->red_curve->first_point()) == *(pc->red_curve->second_point()) ) )
662 {
663 pc->red_curve->reset();
664 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
665 } else {
666 /* Write curves to object. */
667 spdc_concat_colors_and_flush(pc, FALSE);
668 pc->sa = NULL;
669 pc->ea = NULL;
670 }
671 }
674 static void
675 spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint /*state*/)
676 {
677 g_assert( pc->npoints > 0 );
678 g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));
680 if ( ( p != pc->p[ pc->npoints - 1 ] )
681 && in_svg_plane(p) )
682 {
683 pc->ps.push_back(p);
684 pc->p[pc->npoints++] = p;
685 fit_and_split(pc);
686 }
687 }
689 static inline double
690 square(double const x)
691 {
692 return x * x;
693 }
695 static void
696 interpolate(SPPencilContext *pc)
697 {
698 if ( pc->ps.size() <= 1 ) {
699 return;
700 }
702 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
703 double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
704 double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
705 tol) * exp(0.2*tol - 2);
707 g_assert(is_zero(pc->req_tangent)
708 || is_unit_vector(pc->req_tangent));
709 Geom::Point const tHatEnd(0, 0);
711 guint n_points = pc->ps.size();
712 pc->green_curve->reset();
713 pc->red_curve->reset();
714 pc->red_curve_is_valid = false;
716 Geom::Point * b = g_new(Geom::Point, 4*n_points);
717 Geom::Point * points = g_new(Geom::Point, 4*n_points);
718 for (unsigned int i = 0; i < pc->ps.size(); i++) {
719 points[i] = pc->ps[i];
720 }
722 // worst case gives us a segment per point
723 int max_segs = 4*n_points;
725 int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
726 tolerance_sq, max_segs);
728 if ( n_segs > 0)
729 {
730 /* Fit and draw and reset state */
731 pc->green_curve->moveto(b[0]);
732 for (int c = 0; c < n_segs; c++) {
733 pc->green_curve->curveto(b[4*c+1], b[4*c+2], b[4*c+3]);
734 }
735 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
737 /* Fit and draw and copy last point */
738 g_assert(!pc->green_curve->is_empty());
740 /* Set up direction of next curve. */
741 {
742 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
743 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
744 pc->p[0] = last_seg->finalPoint();
745 pc->npoints = 1;
746 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
747 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
748 ? Geom::Point(0, 0)
749 : Geom::unit_vector(req_vec) );
750 }
751 }
752 g_free(b);
753 g_free(points);
754 pc->ps.clear();
755 }
758 /* interpolates the sketched curve and tweaks the current sketch interpolation*/
759 static void
760 sketch_interpolate(SPPencilContext *pc)
761 {
762 if ( pc->ps.size() <= 1 ) {
763 return;
764 }
766 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
767 double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
768 double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
769 tol) * exp(0.2*tol - 2);
771 bool average_all_sketches = prefs->getBool("/tools/freehand/pencil/average_all_sketches", true);
773 g_assert(is_zero(pc->req_tangent)
774 || is_unit_vector(pc->req_tangent));
775 Geom::Point const tHatEnd(0, 0);
777 guint n_points = pc->ps.size();
778 pc->red_curve->reset();
779 pc->red_curve_is_valid = false;
781 Geom::Point * b = g_new(Geom::Point, 4*n_points);
782 Geom::Point * points = g_new(Geom::Point, 4*n_points);
783 for (unsigned i = 0; i < pc->ps.size(); i++) {
784 points[i] = pc->ps[i];
785 }
787 // worst case gives us a segment per point
788 int max_segs = 4*n_points;
790 int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
791 tolerance_sq, max_segs);
793 if ( n_segs > 0)
794 {
795 Geom::Path fit(b[0]);
796 for (int c = 0; c < n_segs; c++) {
797 fit.appendNew<Geom::CubicBezier>(b[4*c+1], b[4*c+2], b[4*c+3]);
798 }
799 Geom::Piecewise<Geom::D2<Geom::SBasis> > fit_pwd2 = fit.toPwSb();
801 double t =0.;
802 if ( pc->sketch_n > 0 ) {
803 if (average_all_sketches) {
804 // Average = (sum of all) / n
805 // = (sum of all + new one) / n+1
806 // = ((old average)*n + new one) / n+1
807 t = pc->sketch_n / (pc->sketch_n + 1.);
808 } else {
809 t = 0.5;
810 }
811 pc->sketch_interpolation = Geom::lerp(t, fit_pwd2, pc->sketch_interpolation);
812 // simplify path, to eliminate small segments
813 Path *path = new Path;
814 path->LoadPathVector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
815 path->Simplify(0.5);
816 Geom::PathVector *pathv = path->MakePathVector();
817 pc->sketch_interpolation = (*pathv)[0].toPwSb();
818 delete path;
819 delete pathv;
820 } else {
821 pc->sketch_interpolation = fit_pwd2;
822 }
823 pc->sketch_n++;
825 pc->green_curve->reset();
826 pc->green_curve->set_pathvector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
827 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
829 /* Fit and draw and copy last point */
830 g_assert(!pc->green_curve->is_empty());
832 /* Set up direction of next curve. */
833 {
834 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
835 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
836 pc->p[0] = last_seg->finalPoint();
837 pc->npoints = 1;
838 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
839 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
840 ? Geom::Point(0, 0)
841 : Geom::unit_vector(req_vec) );
842 }
843 }
844 g_free(b);
845 g_free(points);
846 pc->ps.clear();
847 }
849 static void
850 fit_and_split(SPPencilContext *pc)
851 {
852 g_assert( pc->npoints > 1 );
854 double const tolerance_sq = 0;
856 Geom::Point b[4];
857 g_assert(is_zero(pc->req_tangent)
858 || is_unit_vector(pc->req_tangent));
859 Geom::Point const tHatEnd(0, 0);
860 int const n_segs = Geom::bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
861 pc->req_tangent, tHatEnd,
862 tolerance_sq, 1);
863 if ( n_segs > 0
864 && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
865 {
866 /* Fit and draw and reset state */
867 pc->red_curve->reset();
868 pc->red_curve->moveto(b[0]);
869 pc->red_curve->curveto(b[1], b[2], b[3]);
870 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
871 pc->red_curve_is_valid = true;
872 } else {
873 /* Fit and draw and copy last point */
875 g_assert(!pc->red_curve->is_empty());
877 /* Set up direction of next curve. */
878 {
879 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->red_curve->last_segment());
880 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
881 pc->p[0] = last_seg->finalPoint();
882 pc->npoints = 1;
883 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
884 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
885 ? Geom::Point(0, 0)
886 : Geom::unit_vector(req_vec) );
887 }
889 pc->green_curve->append_continuous(pc->red_curve, 0.0625);
890 SPCurve *curve = pc->red_curve->copy();
892 /// \todo fixme:
893 SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
894 curve->unref();
895 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
897 pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
899 pc->red_curve_is_valid = false;
900 }
901 }
904 /*
905 Local Variables:
906 mode:c++
907 c-file-style:"stroustrup"
908 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
909 indent-tabs-mode:nil
910 fill-column:99
911 End:
912 */
913 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :