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"
46 static void sp_pencil_context_class_init(SPPencilContextClass *klass);
47 static void sp_pencil_context_init(SPPencilContext *pc);
48 static void sp_pencil_context_setup(SPEventContext *ec);
49 static void sp_pencil_context_dispose(GObject *object);
51 static gint sp_pencil_context_root_handler(SPEventContext *event_context, GdkEvent *event);
52 static gint pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent);
53 static gint pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent);
54 static gint pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent);
55 static gint pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state);
56 static gint pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const state);
58 static void spdc_set_startpoint(SPPencilContext *pc, Geom::Point const p);
59 static void spdc_set_endpoint(SPPencilContext *pc, Geom::Point const p);
60 static void spdc_finish_endpoint(SPPencilContext *pc);
61 static void spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint state);
62 static void fit_and_split(SPPencilContext *pc);
63 static void interpolate(SPPencilContext *pc);
64 static void sketch_interpolate(SPPencilContext *pc);
66 static SPDrawContextClass *pencil_parent_class;
67 static Geom::Point pencil_drag_origin_w(0, 0);
68 static bool pencil_within_tolerance = false;
70 /**
71 * Register SPPencilContext class with Gdk and return its type number.
72 */
73 GType
74 sp_pencil_context_get_type()
75 {
76 static GType type = 0;
77 if (!type) {
78 GTypeInfo info = {
79 sizeof(SPPencilContextClass),
80 NULL, NULL,
81 (GClassInitFunc) sp_pencil_context_class_init,
82 NULL, NULL,
83 sizeof(SPPencilContext),
84 4,
85 (GInstanceInitFunc) sp_pencil_context_init,
86 NULL, /* value_table */
87 };
88 type = g_type_register_static(SP_TYPE_DRAW_CONTEXT, "SPPencilContext", &info, (GTypeFlags)0);
89 }
90 return type;
91 }
93 /**
94 * Initialize SPPencilContext vtable.
95 */
96 static void
97 sp_pencil_context_class_init(SPPencilContextClass *klass)
98 {
99 GObjectClass *object_class;
100 SPEventContextClass *event_context_class;
102 object_class = (GObjectClass *) klass;
103 event_context_class = (SPEventContextClass *) klass;
105 pencil_parent_class = (SPDrawContextClass*)g_type_class_peek_parent(klass);
107 object_class->dispose = sp_pencil_context_dispose;
109 event_context_class->setup = sp_pencil_context_setup;
110 event_context_class->root_handler = sp_pencil_context_root_handler;
111 }
113 /**
114 * Callback to initialize SPPencilContext object.
115 */
116 static void
117 sp_pencil_context_init(SPPencilContext *pc)
118 {
119 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
121 event_context->cursor_shape = cursor_pencil_xpm;
122 event_context->hot_x = 4;
123 event_context->hot_y = 4;
125 pc->npoints = 0;
126 pc->state = SP_PENCIL_CONTEXT_IDLE;
127 pc->req_tangent = Geom::Point(0, 0);
129 // since SPPencilContext is not properly constructed...
130 pc->sketch_interpolation = Geom::Piecewise<Geom::D2<Geom::SBasis> >();
131 pc->sketch_n = 0;
132 }
134 /**
135 * Callback to setup SPPencilContext object.
136 */
137 static void
138 sp_pencil_context_setup(SPEventContext *ec)
139 {
140 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
141 if (prefs->getBool("/tools/freehand/pencil/selcue")) {
142 ec->enableSelectionCue();
143 }
145 if (((SPEventContextClass *) pencil_parent_class)->setup) {
146 ((SPEventContextClass *) pencil_parent_class)->setup(ec);
147 }
149 SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
150 pc->is_drawing = false;
152 pc->anchor_statusbar = false;
153 }
155 static void
156 sp_pencil_context_dispose(GObject *object)
157 {
158 G_OBJECT_CLASS(pencil_parent_class)->dispose(object);
159 }
161 /** Snaps new node relative to the previous node. */
162 static void
163 spdc_endpoint_snap(SPPencilContext const *pc, Geom::Point &p, guint const state)
164 {
165 if ((state & GDK_CONTROL_MASK)) { //CTRL enables constrained snapping
166 spdc_endpoint_snap_rotation(pc, p, pc->p[0], state);
167 } else {
168 if (!(state & GDK_SHIFT_MASK)) { //SHIFT disables all snapping, except the angular snapping above
169 //After all, the user explicitely asked for angular snapping by
170 //pressing CTRL
171 spdc_endpoint_snap_free(pc, p, state);
172 }
173 }
174 }
176 /**
177 * Callback for handling all pencil context events.
178 */
179 gint
180 sp_pencil_context_root_handler(SPEventContext *const ec, GdkEvent *event)
181 {
182 SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
184 gint ret = FALSE;
186 switch (event->type) {
187 case GDK_BUTTON_PRESS:
188 ret = pencil_handle_button_press(pc, event->button);
189 break;
191 case GDK_MOTION_NOTIFY:
192 ret = pencil_handle_motion_notify(pc, event->motion);
193 break;
195 case GDK_BUTTON_RELEASE:
196 ret = pencil_handle_button_release(pc, event->button);
197 break;
199 case GDK_KEY_PRESS:
200 ret = pencil_handle_key_press(pc, get_group0_keyval (&event->key), event->key.state);
201 break;
203 case GDK_KEY_RELEASE:
204 ret = pencil_handle_key_release(pc, get_group0_keyval (&event->key), event->key.state);
205 break;
207 default:
208 break;
209 }
211 if (!ret) {
212 gint (*const parent_root_handler)(SPEventContext *, GdkEvent *)
213 = ((SPEventContextClass *) pencil_parent_class)->root_handler;
214 if (parent_root_handler) {
215 ret = parent_root_handler(ec, event);
216 }
217 }
219 return ret;
220 }
222 static gint
223 pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent)
224 {
225 gint ret = FALSE;
226 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
227 if ( bevent.button == 1 && !event_context->space_panning) {
229 SPDrawContext *dc = SP_DRAW_CONTEXT (pc);
230 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
231 Inkscape::Selection *selection = sp_desktop_selection(desktop);
233 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
234 return TRUE;
235 }
237 Geom::Point const button_w(bevent.x, bevent.y);
239 /* Find desktop coordinates */
240 Geom::Point p = pc->desktop->w2d(button_w);
242 /* Test whether we hit any anchor. */
243 SPDrawAnchor *anchor = spdc_test_inside(pc, button_w);
245 pencil_drag_origin_w = Geom::Point(bevent.x,bevent.y);
246 pencil_within_tolerance = true;
248 switch (pc->state) {
249 case SP_PENCIL_CONTEXT_ADDLINE:
250 /* Current segment will be finished with release */
251 ret = TRUE;
252 break;
253 default:
254 /* Set first point of sequence */
255 if (bevent.state & GDK_CONTROL_MASK) {
256 spdc_create_single_dot(event_context, from_2geom(p), "/tools/freehand/pencil", bevent.state);
257 ret = true;
258 break;
259 }
260 if (anchor) {
261 p = to_2geom(anchor->dp);
262 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
263 } else {
265 if (!(bevent.state & GDK_SHIFT_MASK)) {
267 // This is the first click of a new curve; deselect item so that
268 // this curve is not combined with it (unless it is drawn from its
269 // anchor, which is handled by the sibling branch above)
270 selection->clear();
271 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
272 SnapManager &m = desktop->namedview->snap_manager;
273 m.setup(desktop);
274 Inkscape::SnappedPoint const s = m.freeSnap(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
275 if (s.getSnapped()) {
276 s.getPoint(p);
277 pc->prev_snap_was_succesful = true;
278 } else {
279 pc->prev_snap_was_succesful = false;
280 }
281 } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
282 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
283 }
284 }
285 pc->sa = anchor;
286 spdc_set_startpoint(pc, from_2geom(p));
287 ret = TRUE;
288 break;
289 }
291 pc->is_drawing = true;
292 }
293 return ret;
294 }
296 static gint
297 pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
298 {
299 if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
300 // mouse was accidentally moved during Ctrl+click;
301 // ignore the motion and create a single point
302 pc->is_drawing = false;
303 return TRUE;
304 }
305 gint ret = FALSE;
306 SPDesktop *const dt = pc->desktop;
308 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
309 if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
310 // allow scrolling
311 return FALSE;
312 }
314 if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
315 /* Grab mouse, so release will not pass unnoticed */
316 pc->grab = SP_CANVAS_ITEM(dt->acetate);
317 sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK |
318 GDK_BUTTON_RELEASE_MASK |
319 GDK_POINTER_MOTION_MASK ),
320 NULL, mevent.time);
321 }
323 /* Find desktop coordinates */
324 Geom::Point p = to_2geom(dt->w2d(Geom::Point(mevent.x, mevent.y)));
326 /* Test whether we hit any anchor. */
327 SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(mevent.x, mevent.y));
329 if (pencil_within_tolerance) {
330 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
331 gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
332 if ( Geom::LInfty( Geom::Point(mevent.x,mevent.y) - pencil_drag_origin_w ) < tolerance ) {
333 return FALSE; // Do not drag if we're within tolerance from origin.
334 }
335 }
337 // Once the user has moved farther than tolerance from the original location
338 // (indicating they intend to move the object, not click), then always process the
339 // motion notify coordinates as given (no snapping back to origin)
340 pencil_within_tolerance = false;
342 switch (pc->state) {
343 case SP_PENCIL_CONTEXT_ADDLINE:
344 /* Set red endpoint */
345 if (anchor) {
346 p = to_2geom(anchor->dp);
347 } else {
348 Geom::Point ptnr = from_2geom(p);
349 spdc_endpoint_snap(pc, ptnr, mevent.state);
350 p = to_2geom(ptnr);
351 }
352 spdc_set_endpoint(pc, from_2geom(p));
353 ret = TRUE;
354 break;
355 default:
356 /* We may be idle or already freehand */
357 if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
358 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
359 if ( !pc->sa && !pc->green_anchor ) {
360 /* Create green anchor */
361 pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
362 }
363 /** \todo
364 * fixme: I am not sure whether we want to snap to anchors
365 * in middle of freehand (Lauris)
366 */
367 SnapManager &m = dt->namedview->snap_manager;
369 if (anchor) {
370 p = to_2geom(anchor->dp);
371 } else if ((mevent.state & GDK_SHIFT_MASK) == 0) {
372 m.setup(dt);
373 Inkscape::SnappedPoint const s = m.freeSnap(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
374 if (s.getSnapped()) {
375 s.getPoint(p);
376 pc->prev_snap_was_succesful = true;
377 } else {
378 pc->prev_snap_was_succesful = false;
379 }
380 }
381 if ( pc->npoints != 0) { // buttonpress may have happened before we entered draw context!
382 if (!(pc->prev_snap_was_succesful && m.snapprefs.getSnapPostponedGlobally())) {
383 // When snapping is enabled but temporarily on hold because the mouse is moving
384 // fast, then we don't want to add nodes off-grid
385 spdc_add_freehand_point(pc, from_2geom(p), mevent.state);
386 ret = TRUE;
387 }
388 }
390 if (anchor && !pc->anchor_statusbar) {
391 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
392 pc->anchor_statusbar = true;
393 } else if (!anchor && pc->anchor_statusbar) {
394 pc->_message_context->clear();
395 pc->anchor_statusbar = false;
396 } else if (!anchor) {
397 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
398 }
400 } else {
401 if (anchor && !pc->anchor_statusbar) {
402 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
403 pc->anchor_statusbar = true;
404 } else if (!anchor && pc->anchor_statusbar) {
405 pc->_message_context->clear();
406 pc->anchor_statusbar = false;
407 }
408 }
409 break;
410 }
411 return ret;
412 }
414 static gint
415 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
416 {
417 gint ret = FALSE;
419 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
420 if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
421 SPDesktop *const dt = pc->desktop;
423 pc->is_drawing = false;
425 /* Find desktop coordinates */
426 Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y));
428 /* Test whether we hit any anchor. */
429 SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(revent.x,
430 revent.y));
432 switch (pc->state) {
433 case SP_PENCIL_CONTEXT_IDLE:
434 /* Releasing button in idle mode means single click */
435 /* We have already set up start point/anchor in button_press */
436 if (!(revent.state & GDK_CONTROL_MASK)) {
437 // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
438 pc->state = SP_PENCIL_CONTEXT_ADDLINE;
439 }
440 ret = TRUE;
441 break;
442 case SP_PENCIL_CONTEXT_ADDLINE:
443 /* Finish segment now */
444 if (anchor) {
445 p = anchor->dp;
446 } else {
447 spdc_endpoint_snap(pc, p, revent.state);
448 }
449 pc->ea = anchor;
450 spdc_set_endpoint(pc, p);
451 spdc_finish_endpoint(pc);
452 pc->state = SP_PENCIL_CONTEXT_IDLE;
453 ret = TRUE;
454 break;
455 case SP_PENCIL_CONTEXT_FREEHAND:
456 if (revent.state & GDK_MOD1_MASK) {
457 /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */
458 if (anchor) {
459 p = anchor->dp;
460 }
461 pc->ea = anchor;
463 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Sketching: release <b>Alt</b> to finalize current curve"));
465 sketch_interpolate(pc);
467 pc->state = SP_PENCIL_CONTEXT_SKETCH;
468 } else {
469 /* Finish segment now */
470 /// \todo fixme: Clean up what follows (Lauris)
471 if (anchor) {
472 p = anchor->dp;
473 }
474 pc->ea = anchor;
475 /* Write curves to object */
477 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
479 interpolate(pc);
480 spdc_concat_colors_and_flush(pc, FALSE);
481 pc->sa = NULL;
482 pc->ea = NULL;
483 if (pc->green_anchor) {
484 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
485 }
486 pc->state = SP_PENCIL_CONTEXT_IDLE;
487 }
488 ret = TRUE;
489 break;
490 case SP_PENCIL_CONTEXT_SKETCH:
491 default:
492 break;
493 }
495 if (pc->grab) {
496 /* Release grab now */
497 sp_canvas_item_ungrab(pc->grab, revent.time);
498 pc->grab = NULL;
499 }
501 ret = TRUE;
502 }
503 return ret;
504 }
506 static void
507 pencil_cancel (SPPencilContext *const pc)
508 {
509 if (pc->grab) {
510 /* Release grab now */
511 sp_canvas_item_ungrab(pc->grab, 0);
512 pc->grab = NULL;
513 }
515 pc->is_drawing = false;
517 pc->state = SP_PENCIL_CONTEXT_IDLE;
519 pc->red_curve->reset();
520 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
521 while (pc->green_bpaths) {
522 gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
523 pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
524 }
525 pc->green_curve->reset();
526 if (pc->green_anchor) {
527 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
528 }
530 pc->_message_context->clear();
531 pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
533 sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
534 }
536 static gint
537 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
538 {
539 gint ret = FALSE;
540 switch (keyval) {
541 case GDK_Up:
542 case GDK_Down:
543 case GDK_KP_Up:
544 case GDK_KP_Down:
545 // Prevent the zoom field from activation.
546 if (!mod_ctrl_only(state)) {
547 ret = TRUE;
548 }
549 break;
550 case GDK_Escape:
551 if (pc->npoints != 0) {
552 // if drawing, cancel, otherwise pass it up for deselecting
553 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
554 pencil_cancel (pc);
555 ret = TRUE;
556 }
557 }
558 break;
559 case GDK_z:
560 case GDK_Z:
561 if (mod_ctrl_only(state) && pc->npoints != 0) {
562 // if drawing, cancel, otherwise pass it up for undo
563 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
564 pencil_cancel (pc);
565 ret = TRUE;
566 }
567 }
568 break;
569 case GDK_g:
570 case GDK_G:
571 if (mod_shift_only(state)) {
572 sp_selection_to_guides(SP_EVENT_CONTEXT(pc)->desktop);
573 ret = true;
574 }
575 break;
576 default:
577 break;
578 }
579 return ret;
580 }
582 static gint
583 pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const /*state*/)
584 {
585 gint ret = FALSE;
586 switch (keyval) {
587 case GDK_Alt_L:
588 case GDK_Alt_R:
589 case GDK_Meta_L:
590 case GDK_Meta_R:
591 if (pc->state == SP_PENCIL_CONTEXT_SKETCH) {
592 spdc_concat_colors_and_flush(pc, FALSE);
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 (unsigned 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 = 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 Geom::Path fit(b[0]);
803 for (int c = 0; c < n_segs; c++) {
804 fit.appendNew<Geom::CubicBezier>(b[4*c+1], b[4*c+2], b[4*c+3]);
805 }
806 Geom::Piecewise<Geom::D2<Geom::SBasis> > fit_pwd2 = fit.toPwSb();
808 double t =0.;
809 if ( pc->sketch_n > 0 ) {
810 if (average_all_sketches) {
811 // Average = (sum of all) / n
812 // = (sum of all + new one) / n+1
813 // = ((old average)*n + new one) / n+1
814 t = pc->sketch_n / (pc->sketch_n + 1.);
815 } else {
816 t = 0.5;
817 }
818 }
819 pc->sketch_interpolation = Geom::lerp(fit_pwd2, pc->sketch_interpolation, t);
820 pc->sketch_n++;
822 pc->green_curve->reset();
823 pc->green_curve->set_pathvector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
824 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
826 /* Fit and draw and copy last point */
827 g_assert(!pc->green_curve->is_empty());
829 /* Set up direction of next curve. */
830 {
831 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
832 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
833 pc->p[0] = last_seg->finalPoint();
834 pc->npoints = 1;
835 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
836 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
837 ? Geom::Point(0, 0)
838 : Geom::unit_vector(req_vec) );
839 }
840 }
841 g_free(b);
842 g_free(points);
843 pc->ps.clear();
844 }
846 static void
847 fit_and_split(SPPencilContext *pc)
848 {
849 g_assert( pc->npoints > 1 );
851 double const tolerance_sq = 0;
853 Geom::Point b[4];
854 g_assert(is_zero(pc->req_tangent)
855 || is_unit_vector(pc->req_tangent));
856 Geom::Point const tHatEnd(0, 0);
857 int const n_segs = Geom::bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
858 pc->req_tangent, tHatEnd,
859 tolerance_sq, 1);
860 if ( n_segs > 0
861 && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
862 {
863 /* Fit and draw and reset state */
864 pc->red_curve->reset();
865 pc->red_curve->moveto(b[0]);
866 pc->red_curve->curveto(b[1], b[2], b[3]);
867 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
868 pc->red_curve_is_valid = true;
869 } else {
870 /* Fit and draw and copy last point */
872 g_assert(!pc->red_curve->is_empty());
874 /* Set up direction of next curve. */
875 {
876 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->red_curve->last_segment());
877 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
878 pc->p[0] = last_seg->finalPoint();
879 pc->npoints = 1;
880 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
881 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
882 ? Geom::Point(0, 0)
883 : Geom::unit_vector(req_vec) );
884 }
886 pc->green_curve->append_continuous(pc->red_curve, 0.0625);
887 SPCurve *curve = pc->red_curve->copy();
889 /// \todo fixme:
890 SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
891 curve->unref();
892 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
894 pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
896 pc->red_curve_is_valid = false;
897 }
898 }
901 /*
902 Local Variables:
903 mode:c++
904 c-file-style:"stroustrup"
905 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
906 indent-tabs-mode:nil
907 fill-column:99
908 End:
909 */
910 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :