Fix T42488: Knife (selected_only + occlude) failed
[blender-staging.git] / source / blender / editors / mesh / editmesh_knife.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2007 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Joseph Eagar, Joshua Leung, Howard Trickey,
23  *                 Campbell Barton
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/mesh/editmesh_knife.c
29  *  \ingroup edmesh
30  *
31  * Interactive editmesh knife tool.
32  */
33
34 #ifdef _MSC_VER
35 #  define _USE_MATH_DEFINES
36 #endif
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_listbase.h"
41 #include "BLI_string.h"
42 #include "BLI_array.h"
43 #include "BLI_alloca.h"
44 #include "BLI_linklist.h"
45 #include "BLI_math.h"
46 #include "BLI_smallhash.h"
47 #include "BLI_memarena.h"
48
49 #include "BLF_translation.h"
50
51 #include "BKE_DerivedMesh.h"
52 #include "BKE_context.h"
53 #include "BKE_editmesh.h"
54 #include "BKE_editmesh_bvh.h"
55 #include "BKE_report.h"
56
57 #include "BIF_gl.h"
58 #include "BIF_glutil.h" /* for paint cursor */
59
60 #include "ED_screen.h"
61 #include "ED_space_api.h"
62 #include "ED_view3d.h"
63 #include "ED_mesh.h"
64
65 #include "WM_api.h"
66 #include "WM_types.h"
67
68 #include "DNA_object_types.h"
69 #include "UI_resources.h"
70
71 #include "RNA_access.h"
72 #include "RNA_define.h"
73
74 #include "mesh_intern.h"  /* own include */
75
76 #define KMAXDIST    10  /* max mouse distance from edge before not detecting it */
77
78 #define KNIFE_FLT_EPS          0.00001f
79 #define KNIFE_FLT_EPS_SQUARED  (KNIFE_FLT_EPS * KNIFE_FLT_EPS)
80 #define KNIFE_FLT_EPSBIG       0.0005f
81 #define KNIFE_FLT_EPS_PX       0.2f
82
83 typedef struct KnifeColors {
84         unsigned char line[3];
85         unsigned char edge[3];
86         unsigned char curpoint[3];
87         unsigned char curpoint_a[4];
88         unsigned char point[3];
89         unsigned char point_a[4];
90 } KnifeColors;
91
92 /* knifetool operator */
93 typedef struct KnifeVert {
94         BMVert *v; /* non-NULL if this is an original vert */
95         ListBase edges;
96         ListBase faces;
97
98         float co[3], cageco[3], sco[2]; /* sco is screen coordinates for cageco */
99         bool is_face, in_space;
100         bool draw;
101 } KnifeVert;
102
103 typedef struct Ref {
104         struct Ref *next, *prev;
105         void *ref;
106 } Ref;
107
108 typedef struct KnifeEdge {
109         KnifeVert *v1, *v2;
110         BMFace *basef; /* face to restrict face fill to */
111         ListBase faces;
112
113         BMEdge *e /* , *e_old */; /* non-NULL if this is an original edge */
114         bool draw;
115 } KnifeEdge;
116
117 typedef struct KnifeLineHit {
118         float hit[3], cagehit[3];
119         float schit[2];  /* screen coordinates for cagehit */
120         float l; /* lambda along cut line */
121         float perc; /* lambda along hit line */
122         float m; /* depth front-to-back */
123
124         /* Exactly one of kfe, v, or f should be non-NULL,
125          * saying whether cut line crosses and edge,
126          * is snapped to a vert, or is in the middle of some face. */
127         KnifeEdge *kfe;
128         KnifeVert *v;
129         BMFace *f;
130 } KnifeLineHit;
131
132 typedef struct KnifePosData {
133         float co[3];
134         float cage[3];
135
136         /* At most one of vert, edge, or bmface should be non-NULL,
137          * saying whether the point is snapped to a vertex, edge, or in a face.
138          * If none are set, this point is in space and is_space should be true. */
139         KnifeVert *vert;
140         KnifeEdge *edge;
141         BMFace *bmface;
142         bool is_space;
143
144         float mval[2]; /* mouse screen position (may be non-integral if snapped to something) */
145 } KnifePosData;
146
147 /* struct for properties used while drawing */
148 typedef struct KnifeTool_OpData {
149         ARegion *ar;        /* region that knifetool was activated in */
150         void *draw_handle;  /* for drawing preview loop */
151         ViewContext vc;     /* note: _don't_ use 'mval', instead use the one we define below */
152         float mval[2];      /* mouse value with snapping applied */
153         //bContext *C;
154
155         Object *ob;
156         BMEditMesh *em;
157
158         MemArena *arena;
159
160         GHash *origvertmap;
161         GHash *origedgemap;
162         GHash *kedgefacemap;
163         GHash *facetrimap;
164
165         BMBVHTree *bmbvh;
166
167         BLI_mempool *kverts;
168         BLI_mempool *kedges;
169
170         float vthresh;
171         float ethresh;
172
173         /* used for drag-cutting */
174         KnifeLineHit *linehits;
175         int totlinehit;
176
177         /* Data for mouse-position-derived data */
178         KnifePosData curr;  /* current point under the cursor */
179         KnifePosData prev;  /* last added cut (a line draws from the cursor to this) */
180         KnifePosData init;  /* the first point in the cut-list, used for closing the loop */
181
182         int totkedge, totkvert;
183
184         BLI_mempool *refs;
185
186         float projmat[4][4];
187         float projmat_inv[4][4];
188         /* vector along view z axis (object space, normalized) */
189         float proj_zaxis[3];
190
191         KnifeColors colors;
192
193         /* run by the UI or not */
194         bool is_interactive;
195
196         /* operatpr options */
197         bool cut_through;    /* preference, can be modified at runtime (that feature may go) */
198         bool only_select;    /* set on initialization */
199         bool select_result;  /* set on initialization */
200
201         bool is_ortho;
202         float ortho_extent;
203         float clipsta, clipend;
204
205         enum {
206                 MODE_IDLE,
207                 MODE_DRAGGING,
208                 MODE_CONNECT,
209                 MODE_PANNING
210         } mode;
211         bool is_drag_hold;
212
213         int prevmode;
214         bool snap_midpoints;
215         bool ignore_edge_snapping;
216         bool ignore_vert_snapping;
217
218         /* use to check if we're currently dragging an angle snapped line */
219         bool is_angle_snapping;
220
221         enum {
222                 ANGLE_FREE,
223                 ANGLE_0,
224                 ANGLE_45,
225                 ANGLE_90,
226                 ANGLE_135
227         } angle_snapping;
228
229         const float (*cagecos)[3];
230 } KnifeTool_OpData;
231
232 static ListBase *knife_get_face_kedges(KnifeTool_OpData *kcd, BMFace *f);
233
234 static void knife_input_ray_segment(KnifeTool_OpData *kcd, const float mval[2], const float ofs,
235                                     float r_origin[3], float r_dest[3]);
236
237 static bool knife_verts_edge_in_face(KnifeVert *v1, KnifeVert *v2, BMFace *f);
238
239 static void knife_update_header(bContext *C, KnifeTool_OpData *kcd)
240 {
241 #define HEADER_LENGTH 256
242         char header[HEADER_LENGTH];
243
244         BLI_snprintf(header, HEADER_LENGTH, IFACE_("LMB: define cut lines, Return/Spacebar: confirm, Esc or RMB: cancel, "
245                                                    "E: new cut, Ctrl: midpoint snap (%s), Shift: ignore snap (%s), "
246                                                    "C: angle constrain (%s), Z: cut through (%s)"),
247                      WM_bool_as_string(kcd->snap_midpoints),
248                      WM_bool_as_string(kcd->ignore_edge_snapping),
249                      WM_bool_as_string(kcd->angle_snapping),
250                      WM_bool_as_string(kcd->cut_through));
251         ED_area_headerprint(CTX_wm_area(C), header);
252 #undef HEADER_LENGTH
253 }
254
255 static void knife_project_v2(const KnifeTool_OpData *kcd, const float co[3], float sco[2])
256 {
257         ED_view3d_project_float_v2_m4(kcd->ar, co, sco, (float (*)[4])kcd->projmat);
258 }
259
260 /* use when lambda is in screen-space */
261 static void knife_interp_v3_v3v3(
262         const KnifeTool_OpData *kcd,
263         float r_co[3], const float v1[3], const float v2[3], float lambda_ss)
264 {
265         if (kcd->is_ortho) {
266                 interp_v3_v3v3(r_co, v1, v2, lambda_ss);
267         }
268         else {
269                 /* transform into screen-space, interp, then transform back */
270                 float v1_ss[3], v2_ss[3];
271
272                 mul_v3_project_m4_v3(v1_ss, (float (*)[4])kcd->projmat, v1);
273                 mul_v3_project_m4_v3(v2_ss, (float (*)[4])kcd->projmat, v2);
274
275                 interp_v3_v3v3(r_co, v1_ss, v2_ss, lambda_ss);
276
277                 mul_project_m4_v3((float (*)[4])kcd->projmat_inv, r_co);
278         }
279 }
280
281 static void knife_pos_data_clear(KnifePosData *kpd)
282 {
283         zero_v3(kpd->co);
284         zero_v3(kpd->cage);
285         kpd->vert = NULL;
286         kpd->edge = NULL;
287         kpd->bmface = NULL;
288         zero_v2(kpd->mval);
289 }
290
291 static ListBase *knife_empty_list(KnifeTool_OpData *kcd)
292 {
293         ListBase *lst;
294
295         lst = BLI_memarena_alloc(kcd->arena, sizeof(ListBase));
296         BLI_listbase_clear(lst);
297         return lst;
298 }
299
300 static void knife_append_list(KnifeTool_OpData *kcd, ListBase *lst, void *elem)
301 {
302         Ref *ref;
303
304         ref = BLI_mempool_calloc(kcd->refs);
305         ref->ref = elem;
306         BLI_addtail(lst, ref);
307 }
308
309 static Ref *find_ref(ListBase *lb, void *ref)
310 {
311         Ref *ref1;
312
313         for (ref1 = lb->first; ref1; ref1 = ref1->next) {
314                 if (ref1->ref == ref)
315                         return ref1;
316         }
317
318         return NULL;
319 }
320
321 static void knife_append_list_no_dup(KnifeTool_OpData *kcd, ListBase *lst, void *elem)
322 {
323         if (!find_ref(lst, elem))
324                 knife_append_list(kcd, lst, elem);
325 }
326
327 static KnifeEdge *new_knife_edge(KnifeTool_OpData *kcd)
328 {
329         kcd->totkedge++;
330         return BLI_mempool_calloc(kcd->kedges);
331 }
332
333 static void knife_add_to_vert_edges(KnifeTool_OpData *kcd, KnifeEdge *kfe)
334 {
335         knife_append_list(kcd, &kfe->v1->edges, kfe);
336         knife_append_list(kcd, &kfe->v2->edges, kfe);
337 }
338
339 /* Add faces of an edge to a KnifeVert's faces list.  No checks for dups. */
340 static void knife_add_edge_faces_to_vert(KnifeTool_OpData *kcd, KnifeVert *kfv, BMEdge *e)
341 {
342         BMIter bmiter;
343         BMFace *f;
344
345         BM_ITER_ELEM (f, &bmiter, e, BM_FACES_OF_EDGE) {
346                 knife_append_list(kcd, &kfv->faces, f);
347         }
348 }
349
350 /* Find a face in common in the two faces lists.
351  * If more than one, return the first; if none, return NULL */
352 static BMFace *knife_find_common_face(ListBase *faces1, ListBase *faces2)
353 {
354         Ref *ref1, *ref2;
355
356         for (ref1 = faces1->first; ref1; ref1 = ref1->next) {
357                 for (ref2 = faces2->first; ref2; ref2 = ref2->next) {
358                         if (ref1->ref == ref2->ref)
359                                 return (BMFace *)(ref1->ref);
360                 }
361         }
362         return NULL;
363 }
364
365 static KnifeVert *new_knife_vert(KnifeTool_OpData *kcd, const float co[3], const float cageco[3])
366 {
367         KnifeVert *kfv = BLI_mempool_calloc(kcd->kverts);
368
369         kcd->totkvert++;
370
371         copy_v3_v3(kfv->co, co);
372         copy_v3_v3(kfv->cageco, cageco);
373
374         knife_project_v2(kcd, kfv->cageco, kfv->sco);
375
376         return kfv;
377 }
378
379 /* get a KnifeVert wrapper for an existing BMVert */
380 static KnifeVert *get_bm_knife_vert(KnifeTool_OpData *kcd, BMVert *v)
381 {
382         KnifeVert *kfv = BLI_ghash_lookup(kcd->origvertmap, v);
383         const float *cageco;
384
385         if (!kfv) {
386                 BMIter bmiter;
387                 BMFace *f;
388
389                 if (BM_elem_index_get(v) >= 0)
390                         cageco = kcd->cagecos[BM_elem_index_get(v)];
391                 else
392                         cageco = v->co;
393                 kfv = new_knife_vert(kcd, v->co, cageco);
394                 kfv->v = v;
395                 BLI_ghash_insert(kcd->origvertmap, v, kfv);
396                 BM_ITER_ELEM (f, &bmiter, v, BM_FACES_OF_VERT) {
397                         knife_append_list(kcd, &kfv->faces, f);
398                 }
399         }
400
401         return kfv;
402 }
403
404 /* get a KnifeEdge wrapper for an existing BMEdge */
405 static KnifeEdge *get_bm_knife_edge(KnifeTool_OpData *kcd, BMEdge *e)
406 {
407         KnifeEdge *kfe = BLI_ghash_lookup(kcd->origedgemap, e);
408         if (!kfe) {
409                 BMIter bmiter;
410                 BMFace *f;
411
412                 kfe = new_knife_edge(kcd);
413                 kfe->e = e;
414                 kfe->v1 = get_bm_knife_vert(kcd, e->v1);
415                 kfe->v2 = get_bm_knife_vert(kcd, e->v2);
416
417                 knife_add_to_vert_edges(kcd, kfe);
418
419                 BLI_ghash_insert(kcd->origedgemap, e, kfe);
420
421                 BM_ITER_ELEM (f, &bmiter, e, BM_FACES_OF_EDGE) {
422                         knife_append_list(kcd, &kfe->faces, f);
423                 }
424         }
425
426         return kfe;
427 }
428
429 /* Record the index in kcd->em->looptris of first looptri triple for a given face,
430  * given an index for some triple in that array.
431  * This assumes that all of the triangles for a given face are contiguous
432  * in that array (as they are by the current tesselation routines).
433  * Actually store index + 1 in the hash, because 0 looks like "no entry"
434  * to hash lookup routine; will reverse this in the get routine.
435  * Doing this lazily rather than all at once for all faces.
436  */
437 static void set_lowest_face_tri(KnifeTool_OpData *kcd, BMFace *f, int index)
438 {
439         int i;
440
441         if (BLI_ghash_lookup(kcd->facetrimap, f))
442                 return;
443
444         BLI_assert(index >= 0 && index < kcd->em->tottri);
445         BLI_assert(kcd->em->looptris[index][0]->f == f);
446         for (i = index - 1; i >= 0; i--) {
447                 if (kcd->em->looptris[i][0]->f != f) {
448                         i++;
449                         break;
450                 }
451         }
452         if (i == -1)
453                 i++;
454
455         BLI_ghash_insert(kcd->facetrimap, f, SET_INT_IN_POINTER(i + 1));
456 }
457
458 /* This should only be called for faces that have had a lowest face tri set by previous function */
459 static int get_lowest_face_tri(KnifeTool_OpData *kcd, BMFace *f)
460 {
461         int ans;
462
463         ans = GET_INT_FROM_POINTER(BLI_ghash_lookup(kcd->facetrimap, f));
464         BLI_assert(ans != 0);
465         return ans - 1;
466 }
467
468 /* User has just clicked for first time or first time after a restart (E key).
469  * Copy the current position data into prev. */
470 static void knife_start_cut(KnifeTool_OpData *kcd)
471 {
472         kcd->prev = kcd->curr;
473         kcd->curr.is_space = 0; /*TODO: why do we do this? */
474
475         if (kcd->prev.vert == NULL && kcd->prev.edge == NULL) {
476                 float origin[3], origin_ofs[3];
477                 float ofs_local[3];
478
479                 negate_v3_v3(ofs_local, kcd->vc.rv3d->ofs);
480                 invert_m4_m4(kcd->ob->imat, kcd->ob->obmat);
481                 mul_m4_v3(kcd->ob->imat, ofs_local);
482
483                 knife_input_ray_segment(kcd, kcd->curr.mval, 1.0f, origin, origin_ofs);
484
485                 if (!isect_line_plane_v3(kcd->prev.cage, origin, origin_ofs, ofs_local, kcd->proj_zaxis)) {
486                         zero_v3(kcd->prev.cage);
487                 }
488
489                 copy_v3_v3(kcd->prev.co, kcd->prev.cage); /*TODO: do we need this? */
490                 copy_v3_v3(kcd->curr.cage, kcd->prev.cage);
491                 copy_v3_v3(kcd->curr.co, kcd->prev.co);
492         }
493 }
494
495 static ListBase *knife_get_face_kedges(KnifeTool_OpData *kcd, BMFace *f)
496 {
497         ListBase *lst = BLI_ghash_lookup(kcd->kedgefacemap, f);
498
499         if (!lst) {
500                 BMIter bmiter;
501                 BMEdge *e;
502
503                 lst = knife_empty_list(kcd);
504
505                 BM_ITER_ELEM (e, &bmiter, f, BM_EDGES_OF_FACE) {
506                         knife_append_list(kcd, lst, get_bm_knife_edge(kcd, e));
507                 }
508
509                 BLI_ghash_insert(kcd->kedgefacemap, f, lst);
510         }
511
512         return lst;
513 }
514
515 static void knife_edge_append_face(KnifeTool_OpData *kcd, KnifeEdge *kfe, BMFace *f)
516 {
517         knife_append_list(kcd, knife_get_face_kedges(kcd, f), kfe);
518         knife_append_list(kcd, &kfe->faces, f);
519 }
520
521 static KnifeVert *knife_split_edge(
522         KnifeTool_OpData *kcd, KnifeEdge *kfe,
523         const float co[3], const float cageco[3],
524         KnifeEdge **r_kfe)
525 {
526         KnifeEdge *newkfe = new_knife_edge(kcd);
527         Ref *ref;
528         BMFace *f;
529
530         newkfe->v1 = kfe->v1;
531         newkfe->v2 = new_knife_vert(kcd, co, cageco);
532         newkfe->v2->draw = 1;
533         if (kfe->e) {
534                 knife_add_edge_faces_to_vert(kcd, newkfe->v2, kfe->e);
535         }
536         else {
537                 /* kfe cuts across an existing face.
538                  * If v1 and v2 are in multiple faces together (e.g., if they
539                  * are in doubled polys) then this arbitrarily chooses one of them */
540                 f = knife_find_common_face(&kfe->v1->faces, &kfe->v2->faces);
541                 if (f)
542                         knife_append_list(kcd, &newkfe->v2->faces, f);
543         }
544         newkfe->basef = kfe->basef;
545
546         ref = find_ref(&kfe->v1->edges, kfe);
547         BLI_remlink(&kfe->v1->edges, ref);
548
549         kfe->v1 = newkfe->v2;
550         BLI_addtail(&kfe->v1->edges, ref);
551
552         for (ref = kfe->faces.first; ref; ref = ref->next)
553                 knife_edge_append_face(kcd, newkfe, ref->ref);
554
555         knife_add_to_vert_edges(kcd, newkfe);
556
557         newkfe->draw = kfe->draw;
558         newkfe->e = kfe->e;
559
560         *r_kfe = newkfe;
561
562         return newkfe->v2;
563 }
564
565 static void linehit_to_knifepos(KnifePosData *kpos, KnifeLineHit *lh)
566 {
567         kpos->bmface = lh->f;
568         kpos->vert = lh->v;
569         kpos->edge = lh->kfe;
570         copy_v3_v3(kpos->cage, lh->cagehit);
571         copy_v3_v3(kpos->co, lh->hit);
572         copy_v2_v2(kpos->mval, lh->schit);
573 }
574
575 /* primary key: lambda along cut
576  * secondary key: lambda along depth
577  * tertiary key: pointer comparisons of verts if both snapped to verts
578  */
579 static int linehit_compare(const void *vlh1, const void *vlh2)
580 {
581         const KnifeLineHit *lh1 = vlh1;
582         const KnifeLineHit *lh2 = vlh2;
583
584         if      (lh1->l < lh2->l) return -1;
585         else if (lh1->l > lh2->l) return  1;
586         else {
587                 if      (lh1->m < lh2->m) return -1;
588                 else if (lh1->m > lh2->m) return  1;
589                 else {
590                         if      (lh1->v < lh2->v) return -1;
591                         else if (lh1->v > lh2->v) return  1;
592                         else return 0;
593                 }
594         }
595 }
596
597 /*
598  * Sort linehits by distance along cut line, and secondarily from
599  * front to back (from eye), and tertiarily by snap vertex,
600  * and remove any duplicates.
601  */
602 static void prepare_linehits_for_cut(KnifeTool_OpData *kcd)
603 {
604         KnifeLineHit *linehits, *lhi, *lhj;
605         int i, j, n;
606
607         n = kcd->totlinehit;
608         linehits = kcd->linehits;
609         if (n == 0)
610                 return;
611
612         qsort(linehits, n, sizeof(KnifeLineHit), linehit_compare);
613
614         /* Remove any edge hits that are preceded or followed
615          * by a vertex hit that is very near. Mark such edge hits using
616          * l == -1 and then do another pass to actually remove.
617          * Also remove all but one of a series of vertex hits for the same vertex. */
618         for (i = 0; i < n; i++) {
619                 lhi = &linehits[i];
620                 if (lhi->v) {
621                         for (j = i - 1; j >= 0; j--) {
622                                 lhj = &linehits[j];
623                                 if (!lhj->kfe ||
624                                     fabsf(lhi->l - lhj->l) > KNIFE_FLT_EPSBIG ||
625                                     fabsf(lhi->m - lhj->m) > KNIFE_FLT_EPSBIG)
626                                 {
627                                         break;
628                                 }
629                                 lhj->l = -1.0f;
630                         }
631                         for (j = i + 1; j < n; j++) {
632                                 lhj = &linehits[j];
633                                 if (fabsf(lhi->l - lhj->l) > KNIFE_FLT_EPSBIG ||
634                                     fabsf(lhi->m - lhj->m) > KNIFE_FLT_EPSBIG)
635                                 {
636                                         break;
637                                 }
638                                 if (lhj->kfe || lhi->v == lhj->v) {
639                                         lhj->l = -1.0f;
640                                 }
641                         }
642                 }
643         }
644
645         /* delete-in-place loop: copying from pos j to pos i+1 */
646         i = 0;
647         j = 1;
648         while (j < n) {
649                 lhi = &linehits[i];
650                 lhj = &linehits[j];
651                 if (lhj->l == -1.0f) {
652                         j++; /* skip copying this one */
653                 }
654                 else {
655                         /* copy unless a no-op */
656                         if (lhi->l == -1.0f) {
657                                 /* could happen if linehits[0] is being deleted */
658                                 memcpy(&linehits[i], &linehits[j], sizeof(KnifeLineHit));
659                         }
660                         else {
661                                 if (i + 1 != j)
662                                         memcpy(&linehits[i + 1], &linehits[j], sizeof(KnifeLineHit));
663                                 i++;
664                         }
665                         j++;
666                 }
667         }
668         kcd->totlinehit = i + 1;
669 }
670
671 /* Add hit to list of hits in facehits[f], where facehits is a map, if not already there */
672 static void add_hit_to_facehits(KnifeTool_OpData *kcd, GHash *facehits, BMFace *f, KnifeLineHit *hit)
673 {
674         ListBase *lst = BLI_ghash_lookup(facehits, f);
675
676         if (!lst) {
677                 lst = knife_empty_list(kcd);
678                 BLI_ghash_insert(facehits, f, lst);
679         }
680         knife_append_list_no_dup(kcd, lst, hit);
681 }
682
683 static void knife_add_single_cut(KnifeTool_OpData *kcd, KnifeLineHit *lh1, KnifeLineHit *lh2, BMFace *f)
684 {
685         KnifeEdge *kfe, *kfe2;
686
687         if ((lh1->v && lh1->v == lh2->v) ||
688             (lh1->kfe && lh1->kfe == lh2->kfe))
689         {
690                 return;
691         }
692
693         /* Check if edge actually lies within face (might not, if this face is concave) */
694         if ((lh1->v && !lh1->kfe) && (lh2->v && !lh2->kfe)) {
695                 if (!knife_verts_edge_in_face(lh1->v, lh2->v, f)) {
696                         return;
697                 }
698         }
699
700         kfe = new_knife_edge(kcd);
701         kfe->draw = true;
702         kfe->basef = f;
703
704         if (lh1->v) {
705                 kfe->v1 = lh1->v;
706         }
707         else if (lh1->kfe) {
708                 kfe->v1 = knife_split_edge(kcd, lh1->kfe, lh1->hit, lh1->cagehit, &kfe2);
709                 lh1->v = kfe->v1;  /* record the KnifeVert for this hit  */
710         }
711         else {
712                 BLI_assert(lh1->f);
713                 kfe->v1 = new_knife_vert(kcd, lh1->hit, lh1->cagehit);
714                 kfe->v1->draw = true;
715                 kfe->v1->is_face = true;
716                 knife_append_list(kcd, &kfe->v1->faces, lh1->f);
717                 lh1->v = kfe->v1;  /* record the KnifeVert for this hit */
718         }
719
720         if (lh2->v) {
721                 kfe->v2 = lh2->v;
722         }
723         else if (lh2->kfe) {
724                 kfe->v2 = knife_split_edge(kcd, lh2->kfe, lh2->hit, lh2->cagehit, &kfe2);
725                 lh2->v = kfe->v2;  /* future uses of lh2 won't split again */
726         }
727         else {
728                 BLI_assert(lh2->f);
729                 kfe->v2 = new_knife_vert(kcd, lh2->hit, lh2->cagehit);
730                 kfe->v2->draw = true;
731                 kfe->v2->is_face = true;
732                 knife_append_list(kcd, &kfe->v2->faces, lh2->f);
733                 lh2->v = kfe->v2;  /* record the KnifeVert for this hit */
734         }
735
736         knife_add_to_vert_edges(kcd, kfe);
737
738         /* TODO: check if this is ever needed */
739         if (kfe->basef && !find_ref(&kfe->faces, kfe->basef))
740                 knife_edge_append_face(kcd, kfe, kfe->basef);
741
742 }
743
744 /* Given a list of KnifeLineHits for one face, sorted by l
745  * and then by m, make the required KnifeVerts and
746  * KnifeEdges.
747  */
748 static void knife_cut_face(KnifeTool_OpData *kcd, BMFace *f, ListBase *hits)
749 {
750         Ref *r;
751         KnifeLineHit *lh, *prevlh;
752
753         if (BLI_listbase_count_ex(hits, 2) != 2)
754                 return;
755
756         prevlh = NULL;
757         for (r = hits->first; r; r = r->next) {
758                 lh = (KnifeLineHit *)r->ref;
759                 if (prevlh)
760                         knife_add_single_cut(kcd, prevlh, lh, f);
761                 prevlh = lh;
762         }
763
764 }
765
766 /* User has just left-clicked after the first time.
767  * Add all knife cuts implied by line from prev to curr.
768  * If that line crossed edges then kcd->linehits will be non-NULL.
769  * Make all of the KnifeVerts and KnifeEdges implied by this cut.
770  */
771 static void knife_add_cut(KnifeTool_OpData *kcd)
772 {
773         int i;
774         KnifeLineHit *lh;
775         GHash *facehits;
776         BMFace *f;
777         Ref *r;
778         GHashIterator giter;
779         ListBase *lst;
780
781         prepare_linehits_for_cut(kcd);
782         if (kcd->totlinehit == 0) {
783                 if (kcd->is_drag_hold == false) {
784                         kcd->prev = kcd->curr;
785                 }
786                 return;
787         }
788
789         /* make facehits: map face -> list of linehits touching it */
790         facehits = BLI_ghash_ptr_new("knife facehits");
791         for (i = 0; i < kcd->totlinehit; i++) {
792                 lh = &kcd->linehits[i];
793                 if (lh->f) {
794                         add_hit_to_facehits(kcd, facehits, lh->f, lh);
795                 }
796                 if (lh->v) {
797                         for (r = lh->v->faces.first; r; r = r->next) {
798                                 add_hit_to_facehits(kcd, facehits, r->ref, lh);
799                         }
800                 }
801                 if (lh->kfe) {
802                         for (r = lh->kfe->faces.first; r; r = r->next) {
803                                 add_hit_to_facehits(kcd, facehits, r->ref, lh);
804                         }
805                 }
806         }
807
808         /* Note: as following loop progresses, the 'v' fields of
809          * the linehits will be filled in (as edges are split or
810          * in-face verts are made), so it may be true that both
811          * the v and the kfe or f fields will be non-NULL. */
812         GHASH_ITER (giter, facehits) {
813                 f = (BMFace *)BLI_ghashIterator_getKey(&giter);
814                 lst = (ListBase *)BLI_ghashIterator_getValue(&giter);
815                 knife_cut_face(kcd, f, lst);
816         }
817
818         /* set up for next cut */
819         kcd->prev = kcd->curr;
820
821
822         if (kcd->prev.bmface) {
823                 KnifeLineHit *lh;
824                 /* was "in face" but now we have a KnifeVert it is snapped to */
825                 lh = &kcd->linehits[kcd->totlinehit - 1];
826
827                 if (kcd->is_drag_hold) {
828                         linehit_to_knifepos(&kcd->prev, lh);
829                 }
830                 else {
831                         kcd->prev.vert = lh->v;
832                 }
833                 kcd->prev.bmface = NULL;
834         }
835
836         BLI_ghash_free(facehits, NULL, NULL);
837         MEM_freeN(kcd->linehits);
838         kcd->linehits = NULL;
839         kcd->totlinehit = 0;
840 }
841
842 static void knife_finish_cut(KnifeTool_OpData *kcd)
843 {
844         if (kcd->linehits) {
845                 MEM_freeN(kcd->linehits);
846                 kcd->linehits = NULL;
847                 kcd->totlinehit = 0;
848         }
849 }
850
851 static void knifetool_draw_angle_snapping(const KnifeTool_OpData *kcd)
852 {
853         bglMats mats;
854         double u[3], u1[2], u2[2], v1[3], v2[3], dx, dy;
855         double wminx, wminy, wmaxx, wmaxy;
856
857         /* make u the window coords of prevcage */
858         view3d_get_transformation(kcd->ar, kcd->vc.rv3d, kcd->ob, &mats);
859         gluProject(kcd->prev.cage[0], kcd->prev.cage[1], kcd->prev.cage[2],
860                    mats.modelview, mats.projection, mats.viewport,
861                    &u[0], &u[1], &u[2]);
862
863         /* make u1, u2 the points on window going through u at snap angle */
864         wminx = kcd->ar->winrct.xmin;
865         wmaxx = kcd->ar->winrct.xmin + kcd->ar->winx;
866         wminy = kcd->ar->winrct.ymin;
867         wmaxy = kcd->ar->winrct.ymin + kcd->ar->winy;
868
869         switch (kcd->angle_snapping) {
870                 case ANGLE_0:
871                         u1[0] = wminx;
872                         u2[0] = wmaxx;
873                         u1[1] = u2[1] = u[1];
874                         break;
875                 case ANGLE_90:
876                         u1[0] = u2[0] = u[0];
877                         u1[1] = wminy;
878                         u2[1] = wmaxy;
879                         break;
880                 case ANGLE_45:
881                         /* clip against left or bottom */
882                         dx = u[0] - wminx;
883                         dy = u[1] - wminy;
884                         if (dy > dx) {
885                                 u1[0] = wminx;
886                                 u1[1] = u[1] - dx;
887                         }
888                         else {
889                                 u1[0] = u[0] - dy;
890                                 u1[1] = wminy;
891                         }
892                         /* clip against right or top */
893                         dx = wmaxx - u[0];
894                         dy = wmaxy - u[1];
895                         if (dy > dx) {
896                                 u2[0] = wmaxx;
897                                 u2[1] = u[1] + dx;
898                         }
899                         else {
900                                 u2[0] = u[0] + dy;
901                                 u2[1] = wmaxy;
902                         }
903                         break;
904                 case ANGLE_135:
905                         /* clip against right or bottom */
906                         dx = wmaxx - u[0];
907                         dy = u[1] - wminy;
908                         if (dy > dx) {
909                                 u1[0] = wmaxx;
910                                 u1[1] = u[1] - dx;
911                         }
912                         else {
913                                 u1[0] = u[0] + dy;
914                                 u1[1] = wminy;
915                         }
916                         /* clip against left or top */
917                         dx = u[0] - wminx;
918                         dy = wmaxy - u[1];
919                         if (dy > dx) {
920                                 u2[0] = wminx;
921                                 u2[1] = u[1] + dx;
922                         }
923                         else {
924                                 u2[0] = u[0] - dy;
925                                 u2[1] = wmaxy;
926                         }
927                         break;
928                 default:
929                         return;
930         }
931
932         /* unproject u1 and u2 back into object space */
933         gluUnProject(u1[0], u1[1], 0.0,
934                      mats.modelview, mats.projection, mats.viewport,
935                      &v1[0], &v1[1], &v1[2]);
936         gluUnProject(u2[0], u2[1], 0.0,
937                      mats.modelview, mats.projection, mats.viewport,
938                      &v2[0], &v2[1], &v2[2]);
939
940         UI_ThemeColor(TH_TRANSFORM);
941         glLineWidth(2.0);
942         glBegin(GL_LINES);
943         glVertex3dv(v1);
944         glVertex3dv(v2);
945         glEnd();
946 }
947
948 static void knife_init_colors(KnifeColors *colors)
949 {
950         /* possible BMESH_TODO: add explicit themes or calculate these by
951          * figuring out contrasting colors with grid / edges / verts
952          * a la UI_make_axis_color */
953         UI_GetThemeColor3ubv(TH_NURB_VLINE, colors->line);
954         UI_GetThemeColor3ubv(TH_NURB_ULINE, colors->edge);
955         UI_GetThemeColor3ubv(TH_HANDLE_SEL_VECT, colors->curpoint);
956         UI_GetThemeColor3ubv(TH_HANDLE_SEL_VECT, colors->curpoint_a);
957         colors->curpoint_a[3] = 102;
958         UI_GetThemeColor3ubv(TH_ACTIVE_SPLINE, colors->point);
959         UI_GetThemeColor3ubv(TH_ACTIVE_SPLINE, colors->point_a);
960         colors->point_a[3] = 102;
961 }
962
963 /* modal loop selection drawing callback */
964 static void knifetool_draw(const bContext *C, ARegion *UNUSED(ar), void *arg)
965 {
966         View3D *v3d = CTX_wm_view3d(C);
967         const KnifeTool_OpData *kcd = arg;
968
969         if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
970
971         glPolygonOffset(1.0f, 1.0f);
972
973         glPushMatrix();
974         glMultMatrixf(kcd->ob->obmat);
975
976         if (kcd->mode == MODE_DRAGGING) {
977                 if (kcd->angle_snapping != ANGLE_FREE)
978                         knifetool_draw_angle_snapping(kcd);
979
980                 glColor3ubv(kcd->colors.line);
981                 
982                 glLineWidth(2.0);
983
984                 glBegin(GL_LINES);
985                 glVertex3fv(kcd->prev.cage);
986                 glVertex3fv(kcd->curr.cage);
987                 glEnd();
988
989                 glLineWidth(1.0);
990         }
991
992         if (kcd->prev.vert) {
993                 glColor3ubv(kcd->colors.point);
994                 glPointSize(11);
995
996                 glBegin(GL_POINTS);
997                 glVertex3fv(kcd->prev.cage);
998                 glEnd();
999         }
1000
1001         if (kcd->prev.bmface) {
1002                 glColor3ubv(kcd->colors.curpoint);
1003                 glPointSize(9);
1004
1005                 glBegin(GL_POINTS);
1006                 glVertex3fv(kcd->prev.cage);
1007                 glEnd();
1008         }
1009
1010         if (kcd->curr.edge) {
1011                 glColor3ubv(kcd->colors.edge);
1012                 glLineWidth(2.0);
1013
1014                 glBegin(GL_LINES);
1015                 glVertex3fv(kcd->curr.edge->v1->cageco);
1016                 glVertex3fv(kcd->curr.edge->v2->cageco);
1017                 glEnd();
1018
1019                 glLineWidth(1.0);
1020         }
1021         else if (kcd->curr.vert) {
1022                 glColor3ubv(kcd->colors.point);
1023                 glPointSize(11);
1024
1025                 glBegin(GL_POINTS);
1026                 glVertex3fv(kcd->curr.cage);
1027                 glEnd();
1028         }
1029
1030         if (kcd->curr.bmface) {
1031                 glColor3ubv(kcd->colors.curpoint);
1032                 glPointSize(9);
1033
1034                 glBegin(GL_POINTS);
1035                 glVertex3fv(kcd->curr.cage);
1036                 glEnd();
1037         }
1038
1039         if (kcd->totlinehit > 0) {
1040                 KnifeLineHit *lh;
1041                 int i;
1042
1043                 glEnable(GL_BLEND);
1044                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1045
1046                 /* draw any snapped verts first */
1047                 glColor4ubv(kcd->colors.point_a);
1048                 glPointSize(11);
1049                 glBegin(GL_POINTS);
1050                 lh = kcd->linehits;
1051                 for (i = 0; i < kcd->totlinehit; i++, lh++) {
1052                         if (lh->v)
1053                                 glVertex3fv(lh->cagehit);
1054                 }
1055                 glEnd();
1056
1057                 /* now draw the rest */
1058                 glColor4ubv(kcd->colors.curpoint_a);
1059                 glPointSize(7);
1060                 glBegin(GL_POINTS);
1061                 lh = kcd->linehits;
1062                 for (i = 0; i < kcd->totlinehit; i++, lh++) {
1063                         if (!lh->v)
1064                                 glVertex3fv(lh->cagehit);
1065                 }
1066                 glEnd();
1067                 glDisable(GL_BLEND);
1068         }
1069
1070         if (kcd->totkedge > 0) {
1071                 BLI_mempool_iter iter;
1072                 KnifeEdge *kfe;
1073
1074                 glLineWidth(1.0);
1075                 glBegin(GL_LINES);
1076
1077                 BLI_mempool_iternew(kcd->kedges, &iter);
1078                 for (kfe = BLI_mempool_iterstep(&iter); kfe; kfe = BLI_mempool_iterstep(&iter)) {
1079                         if (!kfe->draw)
1080                                 continue;
1081
1082                         glColor3ubv(kcd->colors.line);
1083
1084                         glVertex3fv(kfe->v1->cageco);
1085                         glVertex3fv(kfe->v2->cageco);
1086                 }
1087
1088                 glEnd();
1089                 glLineWidth(1.0);
1090         }
1091
1092         if (kcd->totkvert > 0) {
1093                 BLI_mempool_iter iter;
1094                 KnifeVert *kfv;
1095
1096                 glPointSize(5.0);
1097
1098                 glBegin(GL_POINTS);
1099                 BLI_mempool_iternew(kcd->kverts, &iter);
1100                 for (kfv = BLI_mempool_iterstep(&iter); kfv; kfv = BLI_mempool_iterstep(&iter)) {
1101                         if (!kfv->draw)
1102                                 continue;
1103
1104                         glColor3ubv(kcd->colors.point);
1105
1106                         glVertex3fv(kfv->cageco);
1107                 }
1108
1109                 glEnd();
1110         }
1111
1112         glPopMatrix();
1113
1114         if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
1115 }
1116
1117 /**
1118  * Find intersection of v1-v2 with face f.
1119  * Only take intersections that are at least \a face_tol_sq (in screen space) away
1120  * from other intersection elements.
1121  * If v1-v2 is coplanar with f, call that "no intersection though
1122  * it really means "infinite number of intersections".
1123  * In such a case we should have gotten hits on edges or verts of the face.
1124  */
1125 static bool knife_ray_intersect_face(
1126         KnifeTool_OpData *kcd,
1127         const float s[2], const float v1[3], const float v2[3],
1128         BMFace *f, const float face_tol_sq,
1129         float hit_co[3], float hit_cageco[3])
1130 {
1131         int tottri, tri_i;
1132         float raydir[3];
1133         float tri_norm[3], tri_plane[4];
1134         float se1[2], se2[2];
1135         float d, lambda;
1136         BMLoop **tri;
1137         ListBase *lst;
1138         Ref *ref;
1139         KnifeEdge *kfe;
1140
1141         sub_v3_v3v3(raydir, v2, v1);
1142         normalize_v3(raydir);
1143         tri_i = get_lowest_face_tri(kcd, f);
1144         tottri = kcd->em->tottri;
1145         BLI_assert(tri_i >= 0 && tri_i < tottri);
1146
1147         for (; tri_i < tottri; tri_i++) {
1148                 const float *lv1, *lv2, *lv3;
1149
1150                 tri = kcd->em->looptris[tri_i];
1151                 if (tri[0]->f != f)
1152                         break;
1153                 lv1 = kcd->cagecos[BM_elem_index_get(tri[0]->v)];
1154                 lv2 = kcd->cagecos[BM_elem_index_get(tri[1]->v)];
1155                 lv3 = kcd->cagecos[BM_elem_index_get(tri[2]->v)];
1156                 /* using epsilon test in case ray is directly through an internal
1157                  * tesselation edge and might not hit either tesselation tri with
1158                  * an exact test;
1159                  * we will exclude hits near real edges by a later test */
1160                 if (isect_ray_tri_epsilon_v3(v1, raydir, lv1, lv2, lv3, &lambda, NULL, KNIFE_FLT_EPS)) {
1161                         /* check if line coplanar with tri */
1162                         normal_tri_v3(tri_norm, lv1, lv2, lv3);
1163                         plane_from_point_normal_v3(tri_plane, lv1, tri_norm);
1164                         if ((dist_squared_to_plane_v3(v1, tri_plane) < KNIFE_FLT_EPS) &&
1165                             (dist_squared_to_plane_v3(v2, tri_plane) < KNIFE_FLT_EPS))
1166                         {
1167                                 return false;
1168                         }
1169                         copy_v3_v3(hit_cageco, v1);
1170                         madd_v3_v3fl(hit_cageco, raydir, lambda);
1171                         /* Now check that far enough away from verts and edges */
1172                         lst = knife_get_face_kedges(kcd, f);
1173                         for (ref = lst->first; ref; ref = ref->next) {
1174                                 kfe = ref->ref;
1175                                 knife_project_v2(kcd, kfe->v1->cageco, se1);
1176                                 knife_project_v2(kcd, kfe->v2->cageco, se2);
1177                                 d = dist_squared_to_line_segment_v2(s, se1, se2);
1178                                 if (d < face_tol_sq) {
1179                                         return false;
1180                                 }
1181                         }
1182
1183                         transform_point_by_tri_v3(
1184                                 hit_co, hit_cageco,
1185                                 tri[0]->v->co, tri[1]->v->co, tri[2]->v->co,
1186                                 lv1, lv2, lv3);
1187                         return true;
1188                 }
1189         }
1190         return false;
1191 }
1192
1193 /* Calculate maximum excursion from (0,0,0) of mesh */
1194 static void calc_ortho_extent(KnifeTool_OpData *kcd)
1195 {
1196         BMIter iter;
1197         BMVert *v;
1198         BMesh *bm = kcd->em->bm;
1199         float max_xyz = 0.0f;
1200         int i;
1201
1202         BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
1203                 for (i = 0; i < 3; i++)
1204                         max_xyz = max_ff(max_xyz, fabsf(v->co[i]));
1205         }
1206         kcd->ortho_extent = max_xyz;
1207 }
1208
1209 /* Check if p is visible (not clipped, not occluded by another face).
1210  * s in screen projection of p. */
1211 static bool point_is_visible(KnifeTool_OpData *kcd, const float p[3], const float s[2], bglMats *mats)
1212 {
1213         BMFace *f_hit;
1214
1215         /* If box clipping on, make sure p is not clipped */
1216         if (kcd->vc.rv3d->rflag & RV3D_CLIPPING &&
1217             ED_view3d_clipping_test(kcd->vc.rv3d, p, true))
1218         {
1219                 return false;
1220         }
1221
1222         /* If not cutting through, make sure no face is in front of p */
1223         if (!kcd->cut_through) {
1224                 float dist;
1225                 float view[3], p_ofs[3];
1226
1227                 /* TODO: I think there's a simpler way to get the required raycast ray */
1228                 ED_view3d_unproject(mats, view, s[0], s[1], 0.0f);
1229
1230                 mul_m4_v3(kcd->ob->imat, view);
1231
1232                 /* make p_ofs a little towards view, so ray doesn't hit p's face. */
1233                 sub_v3_v3(view, p);
1234                 dist = normalize_v3(view);
1235                 madd_v3_v3v3fl(p_ofs, p, view, KNIFE_FLT_EPSBIG * 3.0f);
1236
1237                 /* avoid projecting behind the viewpoint */
1238                 if (kcd->is_ortho && (kcd->vc.rv3d->persp != RV3D_CAMOB)) {
1239                         dist = kcd->vc.v3d->far * 2.0f;
1240                 }
1241
1242                 if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1243                         float view_clip[2][3];
1244                         /* note: view_clip[0] should never get clipped */
1245                         copy_v3_v3(view_clip[0], p_ofs);
1246                         madd_v3_v3v3fl(view_clip[1], p_ofs, view, dist);
1247
1248                         if (clip_segment_v3_plane_n(view_clip[0], view_clip[1], kcd->vc.rv3d->clip_local, 6)) {
1249                                 dist = len_v3v3(p_ofs, view_clip[1]);
1250                         }
1251                 }
1252
1253                 /* see if there's a face hit between p1 and the view */
1254                 f_hit = BKE_bmbvh_ray_cast(kcd->bmbvh, p_ofs, view, KNIFE_FLT_EPS, &dist, NULL, NULL);
1255                 if (f_hit)
1256                         return false;
1257         }
1258
1259         return true;
1260 }
1261
1262 /* Clip the line (v1, v2) to planes perpendicular to it and distances d from
1263  * the closest point on the line to the origin */
1264 static void clip_to_ortho_planes(float v1[3], float v2[3], float d)
1265 {
1266         float closest[3];
1267         const float origin[3] = {0.0f, 0.0f, 0.0f};
1268
1269         closest_to_line_v3(closest, origin, v1, v2);
1270         dist_ensure_v3_v3fl(v1, closest, d);
1271         dist_ensure_v3_v3fl(v2, closest, d);
1272 }
1273
1274 static void set_linehit_depth(KnifeTool_OpData *kcd, KnifeLineHit *lh)
1275 {
1276         lh->m = dot_m4_v3_row_z(kcd->vc.rv3d->persmatob, lh->cagehit);
1277 }
1278
1279 /* Finds visible (or all, if cutting through) edges that intersects the current screen drag line */
1280 static void knife_find_line_hits(KnifeTool_OpData *kcd)
1281 {
1282         bglMats mats;
1283         SmallHash faces, kfes, kfvs;
1284         float v1[3], v2[3], v3[3], v4[3], s1[2], s2[2];
1285         BVHTree *planetree, *tree;
1286         BVHTreeOverlap *results, *result;
1287         BMLoop **ls;
1288         BMFace *f;
1289         KnifeEdge *kfe;
1290         KnifeVert *v;
1291         ListBase *lst;
1292         Ref *ref;
1293         KnifeLineHit *linehits = NULL;
1294         BLI_array_declare(linehits);
1295         SmallHashIter hiter;
1296         KnifeLineHit hit;
1297         void *val;
1298         float plane_cos[12];
1299         float s[2], se1[2], se2[2], sint[2];
1300         float r1[3], r2[3];
1301         float d, d1, d2, lambda;
1302         float vert_tol, vert_tol_sq;
1303         float line_tol, line_tol_sq;
1304         float face_tol, face_tol_sq;
1305         float eps_scale;
1306         int isect_kind;
1307         unsigned int tot;
1308         int i;
1309         const bool use_hit_prev = true;
1310         const bool use_hit_curr = (kcd->is_drag_hold == false);
1311
1312         bgl_get_mats(&mats);
1313
1314         if (kcd->linehits) {
1315                 MEM_freeN(kcd->linehits);
1316                 kcd->linehits = NULL;
1317                 kcd->totlinehit = 0;
1318         }
1319
1320         copy_v3_v3(v1, kcd->prev.cage);
1321         copy_v3_v3(v2, kcd->curr.cage);
1322
1323         /* project screen line's 3d coordinates back into 2d */
1324         knife_project_v2(kcd, v1, s1);
1325         knife_project_v2(kcd, v2, s2);
1326
1327         if (kcd->is_interactive) {
1328                 if (len_squared_v2v2(s1, s2) < 1.0f) {
1329                         return;
1330                 }
1331         }
1332         else {
1333                 if (len_squared_v2v2(s1, s2) < KNIFE_FLT_EPS_SQUARED) {
1334                         return;
1335                 }
1336         }
1337
1338         /* unproject screen line */
1339         ED_view3d_win_to_segment(kcd->ar, kcd->vc.v3d, s1, v1, v3, true);
1340         ED_view3d_win_to_segment(kcd->ar, kcd->vc.v3d, s2, v2, v4, true);
1341
1342         mul_m4_v3(kcd->ob->imat, v1);
1343         mul_m4_v3(kcd->ob->imat, v2);
1344         mul_m4_v3(kcd->ob->imat, v3);
1345         mul_m4_v3(kcd->ob->imat, v4);
1346
1347         /* numeric error, 'v1' -> 'v2', 'v2' -> 'v4' can end up being ~2000 units apart in otho mode
1348          * (from ED_view3d_win_to_segment_clip() above)
1349          * this gives precision error; rather then solving properly
1350          * (which may involve using doubles everywhere!),
1351          * limit the distance between these points */
1352         if (kcd->is_ortho && (kcd->vc.rv3d->persp != RV3D_CAMOB)) {
1353                 if (kcd->ortho_extent == 0.0f)
1354                         calc_ortho_extent(kcd);
1355                 clip_to_ortho_planes(v1, v3, kcd->ortho_extent + 10.0f);
1356                 clip_to_ortho_planes(v2, v4, kcd->ortho_extent + 10.0f);
1357         }
1358
1359         /* First use bvh tree to find faces, knife edges, and knife verts that might
1360          * intersect the cut plane with rays v1-v3 and v2-v4.
1361          * This deduplicates the candidates before doing more expensive intersection tests. */
1362
1363         tree = BKE_bmbvh_tree_get(kcd->bmbvh);
1364         planetree = BLI_bvhtree_new(4, FLT_EPSILON * 4, 8, 8);
1365         copy_v3_v3(plane_cos + 0, v1);
1366         copy_v3_v3(plane_cos + 3, v2);
1367         copy_v3_v3(plane_cos + 6, v3);
1368         copy_v3_v3(plane_cos + 9, v4);
1369         BLI_bvhtree_insert(planetree, 0, plane_cos, 4);
1370         BLI_bvhtree_balance(planetree);
1371
1372         results = BLI_bvhtree_overlap(tree, planetree, &tot);
1373         if (!results) {
1374                 BLI_bvhtree_free(planetree);
1375                 return;
1376         }
1377
1378         BLI_smallhash_init(&faces);
1379         BLI_smallhash_init(&kfes);
1380         BLI_smallhash_init(&kfvs);
1381
1382         for (i = 0, result = results; i < tot; i++, result++) {
1383                 ls = (BMLoop **)kcd->em->looptris[result->indexA];
1384                 f = ls[0]->f;
1385                 set_lowest_face_tri(kcd, f, result->indexA);
1386
1387                 /* occlude but never cut unselected faces (when only_select is used) */
1388                 if (kcd->only_select && !BM_elem_flag_test(f, BM_ELEM_SELECT)) {
1389                         continue;
1390                 }
1391                 /* for faces, store index of lowest hit looptri in hash */
1392                 if (BLI_smallhash_haskey(&faces, (uintptr_t)f)) {
1393                         continue;
1394                 }
1395                 /* don't care what the value is except that it is non-NULL, for iterator */
1396                 BLI_smallhash_insert(&faces, (uintptr_t)f, f);
1397
1398                 lst = knife_get_face_kedges(kcd, f);
1399                 for (ref = lst->first; ref; ref = ref->next) {
1400                         kfe = ref->ref;
1401                         if (BLI_smallhash_haskey(&kfes, (uintptr_t)kfe))
1402                                 continue;
1403                         BLI_smallhash_insert(&kfes, (uintptr_t)kfe, kfe);
1404                         v = kfe->v1;
1405                         if (!BLI_smallhash_haskey(&kfvs, (uintptr_t)v))
1406                                 BLI_smallhash_insert(&kfvs, (uintptr_t)v, v);
1407                         v = kfe->v2;
1408                         if (!BLI_smallhash_haskey(&kfvs, (uintptr_t)v))
1409                                 BLI_smallhash_insert(&kfvs, (uintptr_t)v, v);
1410                 }
1411         }
1412
1413         /* Now go through the candidates and find intersections */
1414         /* These tolerances, in screen space, are for intermediate hits, as ends are already snapped to screen */
1415         {
1416                 /* Scale the epsilon by the zoom level
1417                  * to compensate for projection imprecision, see T41164 */
1418                 const float zoom_xy[2] = {
1419                         kcd->vc.rv3d->winmat[0][0],
1420                         kcd->vc.rv3d->winmat[1][1]};
1421                 eps_scale = len_v2(zoom_xy);
1422         }
1423
1424         vert_tol = KNIFE_FLT_EPS_PX * eps_scale;
1425         line_tol = KNIFE_FLT_EPS_PX * eps_scale;
1426         face_tol = max_ff(vert_tol, line_tol);
1427
1428         vert_tol_sq = vert_tol * vert_tol;
1429         line_tol_sq = line_tol * line_tol;
1430         face_tol_sq = face_tol * face_tol;
1431
1432         /* Assume these tolerances swamp floating point rounding errors in calculations below */
1433
1434         /* first look for vertex hits */
1435         for (val = BLI_smallhash_iternew(&kfvs, &hiter, (uintptr_t *)&v); val;
1436              val = BLI_smallhash_iternext(&hiter, (uintptr_t *)&v))
1437         {
1438                 knife_project_v2(kcd, v->cageco, s);
1439                 d = dist_squared_to_line_segment_v2(s, s1, s2);
1440                 if (d <= vert_tol_sq) {
1441                         if (point_is_visible(kcd, v->cageco, s, &mats)) {
1442                                 memset(&hit, 0, sizeof(hit));
1443                                 hit.v = v;
1444
1445                                 /* If this isn't from an existing BMVert, it may have been added to a BMEdge originally.
1446                                  * knowing if the hit comes from an edge is important for edge-in-face checks later on
1447                                  * see: #knife_add_single_cut -> #knife_verts_edge_in_face, T42611 */
1448                                 if (v->v == NULL) {
1449                                         for (ref = v->edges.first; ref; ref = ref->next) {
1450                                                 kfe = ref->ref;
1451                                                 if (kfe->e) {
1452                                                         hit.kfe = kfe;
1453                                                         break;
1454                                                 }
1455                                         }
1456                                 }
1457
1458                                 copy_v3_v3(hit.hit, v->co);
1459                                 copy_v3_v3(hit.cagehit, v->cageco);
1460                                 copy_v2_v2(hit.schit, s);
1461                                 set_linehit_depth(kcd, &hit);
1462                                 BLI_array_append(linehits, hit);
1463                         }
1464                 }
1465         }
1466         /* now edge hits; don't add if a vertex at end of edge should have hit */
1467         for (val = BLI_smallhash_iternew(&kfes, &hiter, (uintptr_t *)&kfe); val;
1468              val = BLI_smallhash_iternext(&hiter, (uintptr_t *)&kfe))
1469         {
1470                 knife_project_v2(kcd, kfe->v1->cageco, se1);
1471                 knife_project_v2(kcd, kfe->v2->cageco, se2);
1472                 isect_kind = isect_seg_seg_v2_point(s1, s2, se1, se2, sint);
1473                 if (isect_kind == -1) {
1474                         /* isect_seg_seg_v2 doesn't do tolerance test around ends of s1-s2 */
1475                         closest_to_line_segment_v2(sint, s1, se1, se2);
1476                         if (len_squared_v2v2(sint, s1) <= line_tol_sq)
1477                                 isect_kind = 1;
1478                         else {
1479                                 closest_to_line_segment_v2(sint, s2, se1, se2);
1480                                 if (len_squared_v2v2(sint, s2) <= line_tol_sq)
1481                                         isect_kind = 1;
1482                         }
1483                 }
1484                 if (isect_kind == 1) {
1485                         d1 = len_v2v2(sint, se1);
1486                         d2 = len_v2v2(se2, se1);
1487                         if (!(d1 <= line_tol || d2 <= line_tol || fabsf(d1 - d2) <= line_tol)) {
1488                                 float p_cage[3], p_cage_tmp[3];
1489                                 lambda = d1 / d2;
1490                                 /* Can't just interpolate between ends of kfe because
1491                                  * that doesn't work with perspective transformation.
1492                                  * Need to find 3d intersection of ray through sint */
1493                                 knife_input_ray_segment(kcd, sint, 1.0f, r1, r2);
1494                                 isect_kind = isect_line_line_v3(kfe->v1->cageco, kfe->v2->cageco, r1, r2, p_cage, p_cage_tmp);
1495                                 if (isect_kind >= 1 && point_is_visible(kcd, p_cage, sint, &mats)) {
1496                                         memset(&hit, 0, sizeof(hit));
1497                                         if (kcd->snap_midpoints) {
1498                                                 /* choose intermediate point snap too */
1499                                                 mid_v3_v3v3(p_cage, kfe->v1->cageco, kfe->v2->cageco);
1500                                                 mid_v2_v2v2(sint, se1, se2);
1501                                                 lambda = 0.5f;
1502                                         }
1503                                         hit.kfe = kfe;
1504                                         transform_point_by_seg_v3(
1505                                                 hit.hit, p_cage,
1506                                                 kfe->v1->co, kfe->v2->co,
1507                                                 kfe->v1->cageco, kfe->v2->cageco);
1508                                         copy_v3_v3(hit.cagehit, p_cage);
1509                                         copy_v2_v2(hit.schit, sint);
1510                                         hit.perc = lambda;
1511                                         set_linehit_depth(kcd, &hit);
1512                                         BLI_array_append(linehits, hit);
1513                                 }
1514                         }
1515                 }
1516         }
1517         /* now face hits; don't add if a vertex or edge in face should have hit */
1518         for (val = BLI_smallhash_iternew(&faces, &hiter, (uintptr_t *)&f); val;
1519              val = BLI_smallhash_iternext(&hiter, (uintptr_t *)&f))
1520         {
1521                 float p[3], p_cage[3];
1522
1523                 if (use_hit_prev && knife_ray_intersect_face(kcd, s1, v1, v3, f, face_tol_sq, p, p_cage)) {
1524                         if (point_is_visible(kcd, p_cage, s1, &mats)) {
1525                                 memset(&hit, 0, sizeof(hit));
1526                                 hit.f = f;
1527                                 copy_v3_v3(hit.hit, p);
1528                                 copy_v3_v3(hit.cagehit, p_cage);
1529                                 copy_v2_v2(hit.schit, s1);
1530                                 set_linehit_depth(kcd, &hit);
1531                                 BLI_array_append(linehits, hit);
1532                         }
1533                 }
1534
1535                 if (use_hit_curr && knife_ray_intersect_face(kcd, s2, v2, v4, f, face_tol_sq, p, p_cage)) {
1536                         if (point_is_visible(kcd, p_cage, s2, &mats)) {
1537                                 memset(&hit, 0, sizeof(hit));
1538                                 hit.f = f;
1539                                 copy_v3_v3(hit.hit, p);
1540                                 copy_v3_v3(hit.cagehit, p_cage);
1541                                 copy_v2_v2(hit.schit, s2);
1542                                 set_linehit_depth(kcd, &hit);
1543                                 BLI_array_append(linehits, hit);
1544                         }
1545                 }
1546         }
1547
1548         kcd->linehits = linehits;
1549         kcd->totlinehit = BLI_array_count(linehits);
1550
1551         /* find position along screen line, used for sorting */
1552         for (i = 0; i < kcd->totlinehit; i++) {
1553                 KnifeLineHit *lh = kcd->linehits + i;
1554
1555                 lh->l = len_v2v2(lh->schit, s1) / len_v2v2(s2, s1);
1556         }
1557
1558         BLI_smallhash_release(&faces);
1559         BLI_smallhash_release(&kfes);
1560         BLI_smallhash_release(&kfvs);
1561         BLI_bvhtree_free(planetree);
1562         if (results)
1563                 MEM_freeN(results);
1564 }
1565
1566 static void knife_input_ray_segment(KnifeTool_OpData *kcd, const float mval[2], const float ofs,
1567                                     float r_origin[3], float r_origin_ofs[3])
1568 {
1569         bglMats mats;
1570
1571         bgl_get_mats(&mats);
1572
1573         /* unproject to find view ray */
1574         ED_view3d_unproject(&mats, r_origin,     mval[0], mval[1], 0.0f);
1575         ED_view3d_unproject(&mats, r_origin_ofs, mval[0], mval[1], ofs);
1576
1577         /* transform into object space */
1578         invert_m4_m4(kcd->ob->imat, kcd->ob->obmat); 
1579
1580         mul_m4_v3(kcd->ob->imat, r_origin);
1581         mul_m4_v3(kcd->ob->imat, r_origin_ofs);
1582 }
1583
1584 static BMFace *knife_find_closest_face(KnifeTool_OpData *kcd, float co[3], float cageco[3], bool *is_space)
1585 {
1586         BMFace *f;
1587         float dist = KMAXDIST;
1588         float origin[3];
1589         float origin_ofs[3];
1590         float ray[3];
1591
1592         /* unproject to find view ray */
1593         knife_input_ray_segment(kcd, kcd->curr.mval, 1.0f, origin, origin_ofs);
1594         sub_v3_v3v3(ray, origin_ofs, origin);
1595
1596         f = BKE_bmbvh_ray_cast(kcd->bmbvh, origin, ray, 0.0f, NULL, co, cageco);
1597
1598         if (f && kcd->only_select && BM_elem_flag_test(f, BM_ELEM_SELECT) == 0) {
1599                 f = NULL;
1600         }
1601
1602         if (is_space)
1603                 *is_space = !f;
1604
1605         if (!f) {
1606                 if (kcd->is_interactive) {
1607                         /* try to use backbuffer selection method if ray casting failed */
1608                         f = EDBM_face_find_nearest(&kcd->vc, &dist);
1609
1610                         /* cheat for now; just put in the origin instead
1611                          * of a true coordinate on the face.
1612                          * This just puts a point 1.0f infront of the view. */
1613                         add_v3_v3v3(co, origin, ray);
1614                 }
1615         }
1616
1617         return f;
1618 }
1619
1620 /* find the 2d screen space density of vertices within a radius.  used to scale snapping
1621  * distance for picking edges/verts.*/
1622 static int knife_sample_screen_density(KnifeTool_OpData *kcd, const float radius)
1623 {
1624         BMFace *f;
1625         bool is_space;
1626         float co[3], cageco[3], sco[2];
1627
1628         BLI_assert(kcd->is_interactive == true);
1629
1630         f = knife_find_closest_face(kcd, co, cageco, &is_space);
1631
1632         if (f && !is_space) {
1633                 const float radius_sq = radius * radius;
1634                 ListBase *lst;
1635                 Ref *ref;
1636                 float dis_sq;
1637                 int c = 0;
1638
1639                 knife_project_v2(kcd, cageco, sco);
1640
1641                 lst = knife_get_face_kedges(kcd, f);
1642                 for (ref = lst->first; ref; ref = ref->next) {
1643                         KnifeEdge *kfe = ref->ref;
1644                         int i;
1645
1646                         for (i = 0; i < 2; i++) {
1647                                 KnifeVert *kfv = i ? kfe->v2 : kfe->v1;
1648
1649                                 knife_project_v2(kcd, kfv->cageco, kfv->sco);
1650
1651                                 dis_sq = len_squared_v2v2(kfv->sco, sco);
1652                                 if (dis_sq < radius_sq) {
1653                                         if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1654                                                 if (ED_view3d_clipping_test(kcd->vc.rv3d, kfv->cageco, true) == 0) {
1655                                                         c++;
1656                                                 }
1657                                         }
1658                                         else {
1659                                                 c++;
1660                                         }
1661                                 }
1662                         }
1663                 }
1664
1665                 return c;
1666         }
1667
1668         return 0;
1669 }
1670
1671 /* returns snapping distance for edges/verts, scaled by the density of the
1672  * surrounding mesh (in screen space)*/
1673 static float knife_snap_size(KnifeTool_OpData *kcd, float maxsize)
1674 {
1675         float density;
1676
1677         if (kcd->is_interactive) {
1678                 density = (float)knife_sample_screen_density(kcd, maxsize * 2.0f);
1679         }
1680         else {
1681                 density = 1.0f;
1682         }
1683
1684         if (density < 1.0f)
1685                 density = 1.0f;
1686
1687         return min_ff(maxsize / (density * 0.5f), maxsize);
1688 }
1689
1690 /* p is closest point on edge to the mouse cursor */
1691 static KnifeEdge *knife_find_closest_edge(KnifeTool_OpData *kcd, float p[3], float cagep[3],
1692                                           BMFace **fptr, bool *is_space)
1693 {
1694         BMFace *f;
1695         float co[3], cageco[3], sco[2];
1696         float maxdist = knife_snap_size(kcd, kcd->ethresh);
1697
1698         if (kcd->ignore_vert_snapping)
1699                 maxdist *= 0.5f;
1700
1701         f = knife_find_closest_face(kcd, co, cageco, NULL);
1702         *is_space = !f;
1703
1704         kcd->curr.bmface = f;
1705
1706         if (f) {
1707                 const float maxdist_sq = maxdist * maxdist;
1708                 KnifeEdge *cure = NULL;
1709                 float cur_cagep[3];
1710                 ListBase *lst;
1711                 Ref *ref;
1712                 float dis_sq, curdis_sq = FLT_MAX;
1713
1714                 /* set p to co, in case we don't find anything, means a face cut */
1715                 copy_v3_v3(p, co);
1716                 copy_v3_v3(cagep, cageco);
1717
1718                 knife_project_v2(kcd, cageco, sco);
1719
1720                 /* look through all edges associated with this face */
1721                 lst = knife_get_face_kedges(kcd, f);
1722                 for (ref = lst->first; ref; ref = ref->next) {
1723                         KnifeEdge *kfe = ref->ref;
1724                         float test_cagep[3];
1725                         float lambda;
1726
1727                         /* project edge vertices into screen space */
1728                         knife_project_v2(kcd, kfe->v1->cageco, kfe->v1->sco);
1729                         knife_project_v2(kcd, kfe->v2->cageco, kfe->v2->sco);
1730
1731                         /* check if we're close enough and calculate 'lambda' */
1732                         if (kcd->is_angle_snapping) {
1733                         /* if snapping, check we're in bounds */
1734                                 float sco_snap[2];
1735                                 isect_line_line_v2_point(kfe->v1->sco, kfe->v2->sco, kcd->prev.mval, kcd->curr.mval, sco_snap);
1736                                 lambda = line_point_factor_v2(sco_snap, kfe->v1->sco, kfe->v2->sco);
1737
1738                                 /* be strict about angle-snapping within edge */
1739                                 if ((lambda < 0.0f - KNIFE_FLT_EPSBIG) || (lambda > 1.0f + KNIFE_FLT_EPSBIG)) {
1740                                         continue;
1741                                 }
1742
1743                                 dis_sq = len_squared_v2v2(sco, sco_snap);
1744                                 if (dis_sq < curdis_sq && dis_sq < maxdist_sq) {
1745                                         /* we already have 'lambda' */
1746                                 }
1747                                 else {
1748                                         continue;
1749                                 }
1750                         }
1751                         else {
1752                                 dis_sq = dist_squared_to_line_segment_v2(sco, kfe->v1->sco, kfe->v2->sco);
1753                                 if (dis_sq < curdis_sq && dis_sq < maxdist_sq) {
1754                                         lambda = line_point_factor_v2(sco, kfe->v1->sco, kfe->v2->sco);
1755                                 }
1756                                 else {
1757                                         continue;
1758                                 }
1759                         }
1760
1761                         /* now we have 'lambda' calculated (in screen-space) */
1762                         knife_interp_v3_v3v3(kcd, test_cagep, kfe->v1->cageco, kfe->v2->cageco, lambda);
1763
1764                         if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1765                                 /* check we're in the view */
1766                                 if (ED_view3d_clipping_test(kcd->vc.rv3d, test_cagep, true)) {
1767                                         continue;
1768                                 }
1769                         }
1770
1771                         cure = kfe;
1772                         curdis_sq = dis_sq;
1773                         copy_v3_v3(cur_cagep, test_cagep);
1774                 }
1775
1776                 if (fptr)
1777                         *fptr = f;
1778
1779                 if (cure) {
1780                         if (!kcd->ignore_edge_snapping || !(cure->e)) {
1781                                 KnifeVert *edgesnap = NULL;
1782
1783                                 if (kcd->snap_midpoints) {
1784                                         mid_v3_v3v3(p, cure->v1->co, cure->v2->co);
1785                                         mid_v3_v3v3(cagep, cure->v1->cageco, cure->v2->cageco);
1786                                 }
1787                                 else {
1788                                         float lambda = line_point_factor_v3(cur_cagep, cure->v1->cageco, cure->v2->cageco);
1789                                         copy_v3_v3(cagep, cur_cagep);
1790                                         interp_v3_v3v3(p, cure->v1->co, cure->v2->co, lambda);
1791                                 }
1792
1793                                 /* update mouse coordinates to the snapped-to edge's screen coordinates
1794                                  * this is important for angle snap, which uses the previous mouse position */
1795                                 edgesnap = new_knife_vert(kcd, p, cagep);
1796                                 kcd->curr.mval[0] = edgesnap->sco[0];
1797                                 kcd->curr.mval[1] = edgesnap->sco[1];
1798
1799                         }
1800                         else {
1801                                 return NULL;
1802                         }
1803                 }
1804
1805                 return cure;
1806         }
1807
1808         if (fptr)
1809                 *fptr = NULL;
1810
1811         return NULL;
1812 }
1813
1814 /* find a vertex near the mouse cursor, if it exists */
1815 static KnifeVert *knife_find_closest_vert(KnifeTool_OpData *kcd, float p[3], float cagep[3], BMFace **fptr,
1816                                           bool *is_space)
1817 {
1818         BMFace *f;
1819         float co[3], cageco[3], sco[2], maxdist = knife_snap_size(kcd, kcd->vthresh);
1820
1821         if (kcd->ignore_vert_snapping)
1822                 maxdist *= 0.5f;
1823
1824         f = knife_find_closest_face(kcd, co, cageco, is_space);
1825
1826         kcd->curr.bmface = f;
1827
1828         if (f) {
1829                 const float maxdist_sq = maxdist * maxdist;
1830                 ListBase *lst;
1831                 Ref *ref;
1832                 KnifeVert *curv = NULL;
1833                 float dis_sq, curdis_sq = FLT_MAX;
1834
1835                 /* set p to co, in case we don't find anything, means a face cut */
1836                 copy_v3_v3(p, co);
1837                 copy_v3_v3(cagep, cageco);
1838
1839                 knife_project_v2(kcd, cageco, sco);
1840
1841                 lst = knife_get_face_kedges(kcd, f);
1842                 for (ref = lst->first; ref; ref = ref->next) {
1843                         KnifeEdge *kfe = ref->ref;
1844                         int i;
1845
1846                         for (i = 0; i < 2; i++) {
1847                                 KnifeVert *kfv = i ? kfe->v2 : kfe->v1;
1848
1849                                 knife_project_v2(kcd, kfv->cageco, kfv->sco);
1850
1851                                 /* be strict about angle snapping, the vertex needs to be very close to the angle, or we ignore */
1852                                 if (kcd->is_angle_snapping) {
1853                                         if (dist_squared_to_line_segment_v2(kfv->sco, kcd->prev.mval, kcd->curr.mval) > KNIFE_FLT_EPSBIG) {
1854                                                 continue;
1855                                         }
1856                                 }
1857
1858                                 dis_sq = len_squared_v2v2(kfv->sco, sco);
1859                                 if (dis_sq < curdis_sq && dis_sq < maxdist_sq) {
1860                                         if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1861                                                 if (ED_view3d_clipping_test(kcd->vc.rv3d, kfv->cageco, true) == 0) {
1862                                                         curv = kfv;
1863                                                         curdis_sq = dis_sq;
1864                                                 }
1865                                         }
1866                                         else {
1867                                                 curv = kfv;
1868                                                 curdis_sq = dis_sq;
1869                                         }
1870                                 }
1871                         }
1872                 }
1873
1874                 if (!kcd->ignore_vert_snapping || !(curv && curv->v)) {
1875                         if (fptr)
1876                                 *fptr = f;
1877
1878                         if (curv) {
1879                                 copy_v3_v3(p, curv->co);
1880                                 copy_v3_v3(cagep, curv->cageco);
1881
1882                                 /* update mouse coordinates to the snapped-to vertex's screen coordinates
1883                                  * this is important for angle snap, which uses the previous mouse position */
1884                                 kcd->curr.mval[0] = curv->sco[0];
1885                                 kcd->curr.mval[1] = curv->sco[1];
1886                         }
1887
1888                         return curv;
1889                 }
1890                 else {
1891                         if (fptr)
1892                                 *fptr = f;
1893
1894                         return NULL;
1895                 }
1896         }
1897
1898         if (fptr)
1899                 *fptr = NULL;
1900
1901         return NULL;
1902 }
1903
1904 /* update both kcd->curr.mval and kcd->mval to snap to required angle */
1905 static bool knife_snap_angle(KnifeTool_OpData *kcd)
1906 {
1907         float dx, dy;
1908         float w, abs_tan;
1909
1910         dx = kcd->curr.mval[0] - kcd->prev.mval[0];
1911         dy = kcd->curr.mval[1] - kcd->prev.mval[1];
1912         if (dx == 0.0f && dy == 0.0f)
1913                 return false;
1914
1915         if (dx == 0.0f) {
1916                 kcd->angle_snapping = ANGLE_90;
1917                 kcd->curr.mval[0] = kcd->prev.mval[0];
1918         }
1919
1920         w = dy / dx;
1921         abs_tan = fabsf(w);
1922         if (abs_tan <= 0.4142f) { /* tan(22.5 degrees) = 0.4142 */
1923                 kcd->angle_snapping = ANGLE_0;
1924                 kcd->curr.mval[1] = kcd->prev.mval[1];
1925         }
1926         else if (abs_tan < 2.4142f) { /* tan(67.5 degrees) = 2.4142 */
1927                 if (w > 0) {
1928                         kcd->angle_snapping = ANGLE_45;
1929                         kcd->curr.mval[1] = kcd->prev.mval[1] + dx;
1930                 }
1931                 else {
1932                         kcd->angle_snapping = ANGLE_135;
1933                         kcd->curr.mval[1] = kcd->prev.mval[1] - dx;
1934                 }
1935         }
1936         else {
1937                 kcd->angle_snapping = ANGLE_90;
1938                 kcd->curr.mval[0] = kcd->prev.mval[0];
1939         }
1940
1941         copy_v2_v2(kcd->mval, kcd->curr.mval);
1942
1943         return true;
1944 }
1945
1946 /* update active knife edge/vert pointers */
1947 static int knife_update_active(KnifeTool_OpData *kcd)
1948 {
1949         knife_pos_data_clear(&kcd->curr);
1950         copy_v2_v2(kcd->curr.mval, kcd->mval);
1951
1952         /* view matrix may have changed, reproject */
1953         knife_project_v2(kcd, kcd->prev.cage, kcd->prev.mval);
1954
1955         if (kcd->angle_snapping != ANGLE_FREE && kcd->mode == MODE_DRAGGING) {
1956                 kcd->is_angle_snapping = knife_snap_angle(kcd);
1957         }
1958         else {
1959                 kcd->is_angle_snapping = false;
1960         }
1961
1962         kcd->curr.vert = knife_find_closest_vert(kcd, kcd->curr.co, kcd->curr.cage, &kcd->curr.bmface, &kcd->curr.is_space);
1963
1964         if (!kcd->curr.vert &&
1965             /* no edge snapping while dragging (edges are too sticky when cuts are immediate) */
1966             !kcd->is_drag_hold)
1967         {
1968                 kcd->curr.edge = knife_find_closest_edge(kcd, kcd->curr.co, kcd->curr.cage,
1969                                                          &kcd->curr.bmface, &kcd->curr.is_space);
1970         }
1971
1972         /* if no hits are found this would normally default to (0, 0, 0) so instead
1973          * get a point at the mouse ray closest to the previous point.
1974          * Note that drawing lines in `free-space` isn't properly supported
1975          * but theres no guarantee (0, 0, 0) has any geometry either - campbell */
1976         if (kcd->curr.vert == NULL && kcd->curr.edge == NULL && kcd->curr.bmface == NULL) {
1977                 float origin[3];
1978                 float origin_ofs[3];
1979
1980                 knife_input_ray_segment(kcd, kcd->curr.mval, 1.0f, origin, origin_ofs);
1981
1982                 if (!isect_line_plane_v3(kcd->curr.cage, origin, origin_ofs, kcd->prev.cage, kcd->proj_zaxis)) {
1983                         copy_v3_v3(kcd->curr.cage, kcd->prev.cage);
1984
1985                         /* should never fail! */
1986                         BLI_assert(0);
1987                 }
1988         }
1989
1990         if (kcd->mode == MODE_DRAGGING) {
1991                 knife_find_line_hits(kcd);
1992         }
1993         return 1;
1994 }
1995
1996 /* sort list of kverts by fraction along edge e */
1997 static void sort_by_frac_along(ListBase *lst, BMEdge *e)
1998 {
1999         /* note, since we know the point is along the edge, sort from distance to v1co */
2000         const float *v1co = e->v1->co;
2001         Ref *cur = NULL, *prev = NULL, *next = NULL;
2002
2003         if (lst->first == lst->last)
2004                 return;
2005
2006         for (cur = ((Ref *)lst->first)->next; cur; cur = next) {
2007                 KnifeVert *vcur = cur->ref;
2008                 const float vcur_fac_sq = len_squared_v3v3(v1co, vcur->co);
2009
2010                 next = cur->next;
2011                 prev = cur->prev;
2012
2013                 BLI_remlink(lst, cur);
2014
2015                 while (prev) {
2016                         KnifeVert *vprev = prev->ref;
2017                         if (len_squared_v3v3(v1co, vprev->co) <= vcur_fac_sq)
2018                                 break;
2019                         prev = prev->prev;
2020                 }
2021
2022                 BLI_insertlinkafter(lst, prev, cur);
2023         }
2024 }
2025
2026 /* The chain so far goes from an instantiated vertex to kfv (some may be reversed).
2027  * If possible, complete the chain to another instantiated vertex and return 1, else return 0.
2028  * The visited hash says which KnifeVert's have already been tried, not including kfv. */
2029 static bool find_chain_search(KnifeTool_OpData *kcd, KnifeVert *kfv, ListBase *fedges, SmallHash *visited,
2030                               ListBase *chain)
2031 {
2032         Ref *r;
2033         KnifeEdge *kfe;
2034         KnifeVert *kfv_other;
2035
2036         if (kfv->v)
2037                 return true;
2038
2039         BLI_smallhash_insert(visited, (uintptr_t)kfv, NULL);
2040         /* Try all possible next edges. Could either go through fedges
2041          * (all the KnifeEdges for the face being cut) or could go through
2042          * kve->edges and restrict to cutting face and uninstantiated edges.
2043          * Not clear which is better. Let's do the first. */
2044         for (r = fedges->first; r; r = r->next) {
2045                 kfe = r->ref;
2046                 kfv_other = NULL;
2047                 if (kfe->v1 == kfv)
2048                         kfv_other = kfe->v2;
2049                 else if (kfe->v2 == kfv)
2050                         kfv_other = kfe->v1;
2051                 if (kfv_other && !BLI_smallhash_haskey(visited, (uintptr_t)kfv_other)) {
2052                         knife_append_list(kcd, chain, kfe);
2053                         if (find_chain_search(kcd, kfv_other, fedges, visited, chain))
2054                                 return true;
2055                         BLI_remlink(chain, chain->last);
2056                 }
2057         }
2058         return false;
2059 }
2060
2061 static ListBase *find_chain_from_vertex(KnifeTool_OpData *kcd, KnifeEdge *kfe, BMVert *v, ListBase *fedges)
2062 {
2063         SmallHash visited_, *visited = &visited_;
2064         ListBase *ans;
2065         bool found;
2066
2067         ans = knife_empty_list(kcd);
2068         knife_append_list(kcd, ans, kfe);
2069         found = false;
2070         BLI_smallhash_init(visited);
2071         if (kfe->v1->v == v) {
2072                 BLI_smallhash_insert(visited, (uintptr_t)(kfe->v1), NULL);
2073                 found = find_chain_search(kcd, kfe->v2, fedges, visited, ans);
2074         }
2075         else {
2076                 BLI_assert(kfe->v2->v == v);
2077                 BLI_smallhash_insert(visited, (uintptr_t)(kfe->v2), NULL);
2078                 found = find_chain_search(kcd, kfe->v1, fedges, visited, ans);
2079         }
2080
2081         BLI_smallhash_release(visited);
2082
2083         if (found)
2084                 return ans;
2085         else
2086                 return NULL;
2087 }
2088
2089 /* Find a chain in fedges from one instantiated vertex to another.
2090  * Remove the edges in the chain from fedges and return a separate list of the chain. */
2091 static ListBase *find_chain(KnifeTool_OpData *kcd, ListBase *fedges)
2092 {
2093         Ref *r, *ref;
2094         KnifeEdge *kfe;
2095         BMVert *v1, *v2;
2096         ListBase *ans;
2097
2098         ans = NULL;
2099
2100         for (r = fedges->first; r; r = r->next) {
2101                 kfe = r->ref;
2102                 v1 = kfe->v1->v;
2103                 v2 = kfe->v2->v;
2104                 if (v1 && v2) {
2105                         ans = knife_empty_list(kcd);
2106                         knife_append_list(kcd, ans, kfe);
2107                         break;
2108                 }
2109                 if (v1)
2110                         ans = find_chain_from_vertex(kcd, kfe, v1, fedges);
2111                 else if (v2)
2112                         ans = find_chain_from_vertex(kcd, kfe, v2, fedges);
2113                 if (ans)
2114                         break;
2115         }
2116         if (ans) {
2117                 BLI_assert(!BLI_listbase_is_empty(ans));
2118                 for (r = ans->first; r; r = r->next) {
2119                         ref = find_ref(fedges, r->ref);
2120                         BLI_assert(ref != NULL);
2121                         BLI_remlink(fedges, ref);
2122                 }
2123         }
2124         return ans;
2125 }
2126
2127 /* The hole so far goes from kfvfirst to kfv (some may be reversed).
2128  * If possible, complete the hole back to kfvfirst and return 1, else return 0.
2129  * The visited hash says which KnifeVert's have already been tried, not including kfv or kfvfirst. */
2130 static bool find_hole_search(KnifeTool_OpData *kcd, KnifeVert *kfvfirst, KnifeVert *kfv, ListBase *fedges,
2131                              SmallHash *visited, ListBase *hole)
2132 {
2133         Ref *r;
2134         KnifeEdge *kfe, *kfelast;
2135         KnifeVert *kfv_other;
2136
2137         if (kfv == kfvfirst)
2138                 return true;
2139
2140         BLI_smallhash_insert(visited, (uintptr_t)kfv, NULL);
2141         kfelast = ((Ref *)hole->last)->ref;
2142         for (r = fedges->first; r; r = r->next) {
2143                 kfe = r->ref;
2144                 if (kfe == kfelast)
2145                         continue;
2146                 if (kfe->v1->v || kfe->v2->v)
2147                         continue;
2148                 kfv_other = NULL;
2149                 if (kfe->v1 == kfv)
2150                         kfv_other = kfe->v2;
2151                 else if (kfe->v2 == kfv)
2152                         kfv_other = kfe->v1;
2153                 if (kfv_other && !BLI_smallhash_haskey(visited, (uintptr_t)kfv_other)) {
2154                         knife_append_list(kcd, hole, kfe);
2155                         if (find_hole_search(kcd, kfvfirst, kfv_other, fedges, visited, hole))
2156                                 return true;
2157                         BLI_remlink(hole, hole->last);
2158                 }
2159         }
2160         return false;
2161 }
2162
2163 /* Find a hole (simple cycle with no instantiated vertices).
2164  * Remove the edges in the cycle from fedges and return a separate list of the cycle */
2165 static ListBase *find_hole(KnifeTool_OpData *kcd, ListBase *fedges)
2166 {
2167         ListBase *ans;
2168         Ref *r, *ref;
2169         KnifeEdge *kfe;
2170         SmallHash visited_, *visited = &visited_;
2171         bool found;
2172
2173         ans = NULL;
2174         found = false;
2175
2176         for (r = fedges->first; r && !found; r = r->next) {
2177                 kfe = r->ref;
2178                 if (kfe->v1->v || kfe->v2->v || kfe->v1 == kfe->v2)
2179                         continue;
2180
2181                 BLI_smallhash_init(visited);
2182                 ans = knife_empty_list(kcd);
2183                 knife_append_list(kcd, ans, kfe);
2184
2185                 found = find_hole_search(kcd, kfe->v1, kfe->v2, fedges, visited, ans);
2186
2187                 BLI_smallhash_release(visited);
2188         }
2189
2190         if (found) {
2191                 for (r = ans->first; r; r = r->next) {
2192                         kfe = r->ref;
2193                         ref = find_ref(fedges, r->ref);
2194                         if (ref)
2195                                 BLI_remlink(fedges, ref);
2196                 }
2197                 return ans;
2198         }
2199         else {
2200                 return NULL;
2201         }
2202 }
2203
2204 /* Try to find "nice" diagonals - short, and far apart from each other.
2205  * If found, return true and make a 'main chain' going across f which uses
2206  * the two diagonals and one part of the hole, and a 'side chain' that
2207  * completes the hole. */
2208 static bool find_hole_chains(KnifeTool_OpData *kcd, ListBase *hole, BMFace *f, ListBase **mainchain,
2209                              ListBase **sidechain)
2210 {
2211         float (*fco)[2], (*hco)[2];
2212         BMVert **fv;
2213         KnifeVert **hv;
2214         KnifeEdge **he;
2215         Ref *r;
2216         KnifeVert *kfv, *kfvother;
2217         KnifeEdge *kfe;
2218         ListBase *chain;
2219         BMVert *v;
2220         BMIter iter;
2221         int nh, nf, i, j, k, m, ax, ay, sep = 0 /* Quite warnings */, bestsep;
2222         int besti[2], bestj[2];
2223         float dist_sq, dist_best_sq;
2224
2225         nh = BLI_listbase_count(hole);
2226         nf = f->len;
2227         if (nh < 2 || nf < 3)
2228                 return false;
2229
2230         /* Gather 2d projections of hole and face vertex coordinates.
2231          * Use best-axis projection - not completely accurate, maybe revisit */
2232         axis_dominant_v3(&ax, &ay, f->no);
2233         hco = BLI_memarena_alloc(kcd->arena, nh * sizeof(float[2]));
2234         fco = BLI_memarena_alloc(kcd->arena, nf * sizeof(float[2]));
2235         hv = BLI_memarena_alloc(kcd->arena, nh * sizeof(KnifeVert *));
2236         fv = BLI_memarena_alloc(kcd->arena, nf * sizeof(BMVert *));
2237         he = BLI_memarena_alloc(kcd->arena, nh * sizeof(KnifeEdge *));
2238
2239         i = 0;
2240         kfv = NULL;
2241         kfvother = NULL;
2242         for (r = hole->first; r; r = r->next) {
2243                 kfe = r->ref;
2244                 he[i] = kfe;
2245                 if (kfvother == NULL) {
2246                         kfv = kfe->v1;
2247                 }
2248                 else {
2249                         kfv = kfvother;
2250                         BLI_assert(kfv == kfe->v1 || kfv == kfe->v2);
2251                 }
2252                 hco[i][0] = kfv->co[ax];
2253                 hco[i][1] = kfv->co[ay];
2254                 hv[i] = kfv;
2255                 kfvother = (kfe->v1 == kfv) ? kfe->v2 : kfe->v1;
2256                 i++;
2257         }
2258
2259         j = 0;
2260         BM_ITER_ELEM (v, &iter, f, BM_VERTS_OF_FACE) {
2261                 fco[j][0] = v->co[ax];
2262                 fco[j][1] = v->co[ay];
2263                 fv[j] = v;
2264                 j++;
2265         }
2266
2267         /* For first diagonal  (m == 0), want shortest length.
2268          * For second diagonal (m == 1), want max separation of index of hole
2269          * vertex from the hole vertex used in the first diagonal, and from there
2270          * want the one with shortest length not to the same vertex as the first diagonal. */
2271         for (m = 0; m < 2; m++) {
2272                 besti[m] = -1;
2273                 bestj[m] = -1;
2274                 dist_best_sq = FLT_MAX;
2275                 bestsep = 0;
2276                 for (i = 0; i < nh; i++) {
2277                         if (m == 1) {
2278                                 if (i == besti[0])
2279                                         continue;
2280                                 sep = (i + nh - besti[0]) % nh;
2281                                 sep = MIN2(sep, nh - sep);
2282                                 if (sep < bestsep)
2283                                         continue;
2284                                 dist_best_sq = FLT_MAX;
2285                         }
2286                         for (j = 0; j < nf; j++) {
2287                                 bool ok;
2288
2289                                 if (m == 1 && j == bestj[0])
2290                                         continue;
2291                                 dist_sq = len_squared_v2v2(hco[i], fco[j]);
2292                                 if (dist_sq > dist_best_sq)
2293                                         continue;
2294
2295                                 ok = true;
2296                                 for (k = 0; k < nh && ok; k++) {
2297                                         if (k == i || (k + 1) % nh == i)
2298                                                 continue;
2299                                         if (isect_line_line_v2(hco[i], fco[j], hco[k], hco[(k + 1) % nh]))
2300                                                 ok = false;
2301                                 }
2302                                 if (!ok)
2303                                         continue;
2304                                 for (k = 0; k < nf && ok; k++) {
2305                                         if (k == j || (k + 1) % nf == j)
2306                                                 continue;
2307                                         if (isect_line_line_v2(hco[i], fco[j], fco[k], fco[(k + 1) % nf]))
2308                                                 ok = false;
2309                                 }
2310                                 if (ok) {
2311                                         besti[m] = i;
2312                                         bestj[m] = j;
2313                                         if (m == 1)
2314                                                 bestsep = sep;
2315                                         dist_best_sq = dist_sq;
2316                                 }
2317                         }
2318                 }
2319         }
2320
2321         if (besti[0] != -1 && besti[1] != -1) {
2322                 BLI_assert(besti[0] != besti[1] && bestj[0] != bestj[1]);
2323                 kfe = new_knife_edge(kcd);
2324                 kfe->v1 = get_bm_knife_vert(kcd, fv[bestj[0]]);
2325                 kfe->v2 = hv[besti[0]];
2326                 chain = knife_empty_list(kcd);
2327                 knife_append_list(kcd, chain, kfe);
2328                 for (i = besti[0]; i != besti[1]; i = (i + 1) % nh) {
2329                         knife_append_list(kcd, chain, he[i]);
2330                 }
2331                 kfe = new_knife_edge(kcd);
2332                 kfe->v1 = hv[besti[1]];
2333                 kfe->v2 = get_bm_knife_vert(kcd, fv[bestj[1]]);
2334                 knife_append_list(kcd, chain, kfe);
2335                 *mainchain = chain;
2336
2337                 chain = knife_empty_list(kcd);
2338                 for (i = besti[1]; i != besti[0]; i = (i + 1) % nh) {
2339                         knife_append_list(kcd, chain, he[i]);
2340                 }
2341                 *sidechain = chain;
2342
2343                 return true;
2344         }
2345         else {
2346                 return false;
2347         }
2348 }
2349
2350 static bool knife_verts_edge_in_face(KnifeVert *v1, KnifeVert *v2, BMFace *f)
2351 {
2352         bool v1_inside, v2_inside;
2353         bool v1_inface, v2_inface;
2354
2355         if (!f || !v1 || !v2)
2356                 return false;
2357
2358         /* find out if v1 and v2, if set, are part of the face */
2359         v1_inface = v1->v ? BM_vert_in_face(f, v1->v) : false;
2360         v2_inface = v2->v ? BM_vert_in_face(f, v2->v) : false;
2361
2362         /* BM_face_point_inside_test uses best-axis projection so this isn't most accurate test... */
2363         v1_inside = v1_inface ? false : BM_face_point_inside_test(f, v1->co);
2364         v2_inside = v2_inface ? false : BM_face_point_inside_test(f, v2->co);
2365         if ((v1_inface && v2_inside) ||
2366             (v2_inface && v1_inside) ||
2367             (v1_inside && v2_inside))
2368         {
2369                 return true;
2370         }
2371
2372         if (v1_inface && v2_inface) {
2373                 float mid[3];
2374                 /* Can have case where v1 and v2 are on shared chain between two faces.
2375                  * BM_face_splits_check_legal does visibility and self-intersection tests,
2376                  * but it is expensive and maybe a bit buggy, so use a simple
2377                  * "is the midpoint in the face" test */
2378                 mid_v3_v3v3(mid, v1->co, v2->co);
2379                 return BM_face_point_inside_test(f, mid);
2380         }
2381         return false;
2382 }
2383
2384 static bool knife_edge_in_face(KnifeEdge *kfe, BMFace *f)
2385 {
2386         return knife_verts_edge_in_face(kfe->v1, kfe->v2, f);
2387 }
2388
2389 /* Split face f with KnifeEdges on chain.  f remains as one side, the face formed is put in *newface.
2390  * The new face will be on the left side of the chain as viewed from the normal-out side of f. */
2391 static void knife_make_chain_cut(KnifeTool_OpData *kcd, BMFace *f, ListBase *chain, BMFace **r_f_new)
2392 {
2393         BMesh *bm = kcd->em->bm;
2394         KnifeEdge *kfe, *kfelast;
2395         BMVert *v1, *v2;
2396         BMLoop *l_v1, *l_v2;
2397         BMFace *f_new;
2398         Ref *ref;
2399         KnifeVert *kfv, *kfvprev;
2400         BMLoop *l_new, *l_iter;
2401         int i;
2402         int nco = BLI_listbase_count(chain) - 1;
2403         float (*cos)[3] = BLI_array_alloca(cos, nco);
2404         KnifeVert **kverts = BLI_array_alloca(kverts, nco);
2405
2406         kfe = ((Ref *)chain->first)->ref;
2407         v1 = kfe->v1->v ? kfe->v1->v : kfe->v2->v;
2408         kfelast = ((Ref *)chain->last)->ref;
2409         v2 = kfelast->v2->v ? kfelast->v2->v : kfelast->v1->v;
2410         BLI_assert(v1 != NULL && v2 != NULL);
2411         kfvprev = kfe->v1->v == v1 ? kfe->v1 : kfe->v2;
2412         for (ref = chain->first, i = 0; i < nco && ref != chain->last; ref = ref->next, i++) {
2413                 kfe = ref->ref;
2414                 BLI_assert(kfvprev == kfe->v1 || kfvprev == kfe->v2);
2415                 kfv = kfe->v1 == kfvprev ? kfe->v2 : kfe->v1;
2416                 copy_v3_v3(cos[i], kfv->co);
2417                 kverts[i] = kfv;
2418                 kfvprev = kfv;
2419         }
2420         BLI_assert(i == nco);
2421         l_new = NULL;
2422
2423         if ((l_v1 = BM_face_vert_share_loop(f, v1)) &&
2424             (l_v2 = BM_face_vert_share_loop(f, v2)))
2425         {
2426                 if (nco == 0) {
2427                         /* Want to prevent creating two-sided polygons */
2428                         if (v1 == v2 || BM_edge_exists(v1, v2)) {
2429                                 f_new = NULL;
2430                         }
2431                         else {
2432                                 f_new = BM_face_split(bm, f, l_v1, l_v2, &l_new, NULL, true);
2433                         }
2434                 }
2435                 else {
2436                         f_new = BM_face_split_n(bm, f, l_v1, l_v2, cos, nco, &l_new, NULL);
2437                         if (f_new) {
2438                                 /* Now go through lnew chain matching up chain kv's and assign real v's to them */
2439                                 for (l_iter = l_new->next, i = 0; i < nco; l_iter = l_iter->next, i++) {
2440                                         BLI_assert(equals_v3v3(cos[i], l_iter->v->co));
2441                                         if (kcd->select_result) {
2442                                                 BM_edge_select_set(bm, l_iter->e, true);
2443                                         }
2444                                         kverts[i]->v = l_iter->v;
2445                                 }
2446                         }
2447                 }
2448         }
2449         else {
2450                 f_new = NULL;
2451         }
2452
2453         /* the select chain above doesnt account for the first loop */
2454         if (kcd->select_result) {
2455                 if (l_new) {
2456                         BM_edge_select_set(bm, l_new->e, true);
2457                 }
2458         }
2459         else if (f_new) {
2460                 BM_elem_select_copy(bm, bm, f_new, f);
2461         }
2462
2463         *r_f_new = f_new;
2464 }
2465
2466 static void knife_make_face_cuts(KnifeTool_OpData *kcd, BMFace *f, ListBase *kfedges)
2467 {
2468         BMesh *bm = kcd->em->bm;
2469         KnifeEdge *kfe;
2470         BMFace *fnew, *fnew2, *fhole;
2471         ListBase *chain, *hole, *sidechain;
2472         Ref *ref, *refnext;
2473         int count, oldcount;
2474
2475         oldcount = BLI_listbase_count(kfedges);
2476         while ((chain = find_chain(kcd, kfedges)) != NULL) {
2477                 ListBase fnew_kfedges;
2478                 knife_make_chain_cut(kcd, f, chain, &fnew);
2479                 if (!fnew) {
2480                         return;
2481                 }
2482
2483                 /* Move kfedges to fnew_kfedges if they are now in fnew.
2484                  * The chain edges were removed already */
2485                 BLI_listbase_clear(&fnew_kfedges);
2486                 for (ref = kfedges->first; ref; ref = refnext) {
2487                         kfe = ref->ref;
2488                         refnext = ref->next;
2489                         if (knife_edge_in_face(kfe, fnew)) {
2490                                 BLI_remlink(kfedges, ref);
2491                                 kfe->basef = fnew;
2492                                 BLI_addtail(&fnew_kfedges, ref);
2493                         }
2494                         else if (!knife_edge_in_face(kfe, f)) {
2495                                 /* Concave ngon's - this edge might not be in either faces, T41730 */
2496                                 BLI_remlink(kfedges, ref);
2497                         }
2498                 }
2499                 if (fnew_kfedges.first)
2500                         knife_make_face_cuts(kcd, fnew, &fnew_kfedges);
2501
2502                 /* find_chain should always remove edges if it returns true,
2503                  * but guard against infinite loop anyway */
2504                 count = BLI_listbase_count(kfedges);
2505                 if (count >= oldcount) {
2506                         BLI_assert(!"knife find_chain infinite loop");
2507                         return;
2508                 }
2509                 oldcount = count;
2510         }
2511
2512         while ((hole = find_hole(kcd, kfedges)) != NULL) {
2513                 if (find_hole_chains(kcd, hole, f, &chain, &sidechain)) {
2514                         ListBase fnew_kfedges, fnew2_kfedges;
2515
2516                         /* chain goes across f and sidechain comes back
2517                          * from the second last vertex to the second vertex.
2518                          */
2519                         knife_make_chain_cut(kcd, f, chain, &fnew);
2520                         if (!fnew) {
2521                                 BLI_assert(!"knife failed hole cut");
2522                                 return;
2523                         }
2524                         kfe = ((Ref *)sidechain->first)->ref;
2525                         if (knife_edge_in_face(kfe, f)) {
2526                                 knife_make_chain_cut(kcd, f, sidechain, &fnew2);
2527                                 if (fnew2 == NULL) {
2528                                         return;
2529                                 }
2530                                 fhole = f;
2531                         }
2532                         else if (knife_edge_in_face(kfe, fnew)) {
2533                                 knife_make_chain_cut(kcd, fnew, sidechain, &fnew2);
2534                                 if (fnew2 == NULL) {
2535                                         return;
2536                                 }
2537                                 fhole = fnew2;
2538                         }
2539                         else {
2540                                 /* shouldn't happen except in funny edge cases */
2541                                 return;
2542                         }
2543                         BM_face_kill(bm, fhole);
2544                         /* Move kfedges to either fnew or fnew2 if appropriate.
2545                          * The hole edges were removed already */
2546                         BLI_listbase_clear(&fnew_kfedges);
2547                         BLI_listbase_clear(&fnew2_kfedges);
2548                         for (ref = kfedges->first; ref; ref = refnext) {
2549                                 kfe = ref->ref;
2550                                 refnext = ref->next;
2551                                 if (knife_edge_in_face(kfe, fnew)) {
2552                                         BLI_remlink(kfedges, ref);
2553                                         kfe->basef = fnew;
2554                                         BLI_addtail(&fnew_kfedges, ref);
2555                                 }
2556                                 else if (knife_edge_in_face(kfe, fnew2)) {
2557                                         BLI_remlink(kfedges, ref);
2558                                         kfe->basef = fnew2;
2559                                         BLI_addtail(&fnew2_kfedges, ref);
2560                                 }
2561                         }
2562                         /* We'll skip knife edges that are in the newly formed hole.
2563                          * (Maybe we shouldn't have made a hole in the first place?) */
2564                         if (fnew != fhole && fnew_kfedges.first)
2565                                 knife_make_face_cuts(kcd, fnew, &fnew_kfedges);
2566                         if (fnew2 != fhole && fnew2_kfedges.first)
2567                                 knife_make_face_cuts(kcd, fnew2, &fnew2_kfedges);
2568                         if (f == fhole)
2569                                 break;
2570                         /* find_hole should always remove edges if it returns true,
2571                          * but guard against infinite loop anyway */
2572                         count = BLI_listbase_count(kfedges);
2573                         if (count >= oldcount) {
2574                                 BLI_assert(!"knife find_hole infinite loop");
2575                                 return;
2576                         }
2577                         oldcount = count;
2578                 }
2579         }
2580 }
2581
2582 /* Use the network of KnifeEdges and KnifeVerts accumulated to make real BMVerts and BMEdedges */
2583 static void knife_make_cuts(KnifeTool_OpData *kcd)
2584 {
2585         BMesh *bm = kcd->em->bm;
2586         KnifeEdge *kfe;
2587         KnifeVert *kfv;
2588         BMFace *f;
2589         BMEdge *e, *enew;
2590         ListBase *lst;
2591         Ref *ref;
2592         float pct;
2593         SmallHashIter hiter;
2594         BLI_mempool_iter iter;
2595         SmallHash fhash_, *fhash = &fhash_;
2596         SmallHash ehash_, *ehash = &ehash_;
2597
2598         BLI_smallhash_init(fhash);
2599         BLI_smallhash_init(ehash);
2600
2601         /* put list of cutting edges for a face into fhash, keyed by face */
2602         BLI_mempool_iternew(kcd->kedges, &iter);
2603         for (kfe = BLI_mempool_iterstep(&iter); kfe; kfe = BLI_mempool_iterstep(&iter)) {
2604                 f = kfe->basef;
2605                 if (!f || kfe->e)
2606                         continue;
2607                 lst = BLI_smallhash_lookup(fhash, (uintptr_t)f);
2608                 if (!lst) {
2609                         lst = knife_empty_list(kcd);
2610                         BLI_smallhash_insert(fhash, (uintptr_t)f, lst);
2611                 }
2612                 knife_append_list(kcd, lst, kfe);
2613         }
2614
2615         /* put list of splitting vertices for an edge into ehash, keyed by edge */
2616         BLI_mempool_iternew(kcd->kverts, &iter);
2617         for (kfv = BLI_mempool_iterstep(&iter); kfv; kfv = BLI_mempool_iterstep(&iter)) {
2618                 if (kfv->v)
2619                         continue;  /* already have a BMVert */
2620                 for (ref = kfv->edges.first; ref; ref = ref->next) {
2621                         kfe = ref->ref;
2622                         e = kfe->e;
2623                         if (!e)
2624                                 continue;
2625                         lst = BLI_smallhash_lookup(ehash, (uintptr_t)e);
2626                         if (!lst) {
2627                                 lst = knife_empty_list(kcd);
2628                                 BLI_smallhash_insert(ehash, (uintptr_t)e, lst);
2629                         }
2630                         /* there can be more than one kfe in kfv's list with same e */
2631                         if (!find_ref(lst, kfv))
2632                                 knife_append_list(kcd, lst, kfv);
2633                 }
2634         }
2635
2636         /* split bmesh edges where needed */
2637         for (lst = BLI_smallhash_iternew(ehash, &hiter, (uintptr_t *)&e); lst;
2638              lst = BLI_smallhash_iternext(&hiter, (uintptr_t *)&e))
2639         {
2640                 sort_by_frac_along(lst, e);
2641                 for (ref = lst->first; ref; ref = ref->next) {
2642                         kfv = ref->ref;
2643                         pct = line_point_factor_v3(kfv->co, e->v1->co, e->v2->co);
2644                         kfv->v = BM_edge_split(bm, e, e->v1, &enew, pct);
2645                 }
2646         }
2647
2648         if (kcd->only_select) {
2649                 EDBM_flag_disable_all(kcd->em, BM_ELEM_SELECT);
2650         }
2651
2652         /* do cuts for each face */
2653         for (lst = BLI_smallhash_iternew(fhash, &hiter, (uintptr_t *)&f); lst;
2654              lst = BLI_smallhash_iternext(&hiter, (uintptr_t *)&f))
2655         {
2656                 knife_make_face_cuts(kcd, f, lst);
2657         }
2658
2659         BLI_smallhash_release(fhash);
2660         BLI_smallhash_release(ehash);
2661 }
2662
2663 /* called on tool confirmation */
2664 static void knifetool_finish_ex(KnifeTool_OpData *kcd)
2665 {
2666         knife_make_cuts(kcd);
2667
2668         EDBM_selectmode_flush(kcd->em);
2669         EDBM_mesh_normals_update(kcd->em);
2670         EDBM_update_generic(kcd->em, true, true);
2671 }
2672 static void knifetool_finish(wmOperator *op)
2673 {
2674         KnifeTool_OpData *kcd = op->customdata;
2675         knifetool_finish_ex(kcd);
2676 }
2677
2678 static void knife_recalc_projmat(KnifeTool_OpData *kcd)
2679 {
2680         invert_m4_m4(kcd->ob->imat, kcd->ob->obmat);
2681         ED_view3d_ob_project_mat_get(kcd->ar->regiondata, kcd->ob, kcd->projmat);
2682         invert_m4_m4(kcd->projmat_inv, kcd->projmat);
2683
2684         copy_v3_v3(kcd->proj_zaxis, kcd->vc.rv3d->viewinv[2]);
2685         mul_mat3_m4_v3(kcd->ob->imat, kcd->proj_zaxis);
2686         normalize_v3(kcd->proj_zaxis);
2687
2688         kcd->is_ortho = ED_view3d_clip_range_get(kcd->vc.v3d, kcd->vc.rv3d,
2689                                                  &kcd->clipsta, &kcd->clipend, true);
2690 }
2691
2692 /* called when modal loop selection is done... */
2693 static void knifetool_exit_ex(bContext *C, KnifeTool_OpData *kcd)
2694 {
2695         if (!kcd)
2696                 return;
2697
2698         if (kcd->is_interactive) {
2699                 WM_cursor_modal_restore(CTX_wm_window(C));
2700
2701                 /* deactivate the extra drawing stuff in 3D-View */
2702                 ED_region_draw_cb_exit(kcd->ar->type, kcd->draw_handle);
2703         }
2704
2705         /* free the custom data */
2706         BLI_mempool_destroy(kcd->refs);
2707         BLI_mempool_destroy(kcd->kverts);
2708         BLI_mempool_destroy(kcd->kedges);
2709
2710         BLI_ghash_free(kcd->origedgemap, NULL, NULL);
2711         BLI_ghash_free(kcd->origvertmap, NULL, NULL);
2712         BLI_ghash_free(kcd->kedgefacemap, NULL, NULL);
2713         BLI_ghash_free(kcd->facetrimap, NULL, NULL);
2714
2715         BKE_bmbvh_free(kcd->bmbvh);
2716         BLI_memarena_free(kcd->arena);
2717
2718         /* tag for redraw */
2719         ED_region_tag_redraw(kcd->ar);
2720
2721         if (kcd->cagecos)
2722                 MEM_freeN((void *)kcd->cagecos);
2723
2724         if (kcd->linehits)
2725                 MEM_freeN(kcd->linehits);
2726
2727         /* destroy kcd itself */
2728         MEM_freeN(kcd);
2729 }
2730 static void knifetool_exit(bContext *C, wmOperator *op)
2731 {
2732         KnifeTool_OpData *kcd = op->customdata;
2733         knifetool_exit_ex(C, kcd);
2734         op->customdata = NULL;
2735 }
2736
2737 static void knifetool_update_mval(KnifeTool_OpData *kcd, const float mval[2])
2738 {
2739         knife_recalc_projmat(kcd);
2740         copy_v2_v2(kcd->mval, mval);
2741
2742         if (knife_update_active(kcd)) {
2743                 ED_region_tag_redraw(kcd->ar);
2744         }
2745 }
2746
2747 static void knifetool_update_mval_i(KnifeTool_OpData *kcd, const int mval_i[2])
2748 {
2749         float mval[2] = {UNPACK2(mval_i)};
2750         knifetool_update_mval(kcd, mval);
2751 }
2752
2753 /* called when modal loop selection gets set up... */
2754 static void knifetool_init(bContext *C, KnifeTool_OpData *kcd,
2755                            const bool only_select, const bool cut_through, const bool is_interactive)
2756 {
2757         Scene *scene = CTX_data_scene(C);
2758         Object *obedit = CTX_data_edit_object(C);
2759
2760         /* assign the drawing handle for drawing preview line... */
2761         kcd->ob = obedit;
2762         kcd->ar = CTX_wm_region(C);
2763
2764         em_setup_viewcontext(C, &kcd->vc);
2765
2766         kcd->em = BKE_editmesh_from_object(kcd->ob);
2767
2768         BM_mesh_elem_index_ensure(kcd->em->bm, BM_VERT);
2769
2770         kcd->cagecos = (const float (*)[3])BKE_editmesh_vertexCos_get(kcd->em, scene, NULL);
2771
2772         kcd->bmbvh = BKE_bmbvh_new_from_editmesh(
2773                 kcd->em,
2774                 BMBVH_RETURN_ORIG |
2775                 ((only_select && cut_through) ? BMBVH_RESPECT_SELECT : BMBVH_RESPECT_HIDDEN),
2776                 kcd->cagecos, false);
2777
2778         kcd->arena = BLI_memarena_new(MEM_SIZE_OPTIMAL(1 << 15), "knife");
2779         kcd->vthresh = KMAXDIST - 1;
2780         kcd->ethresh = KMAXDIST;
2781
2782         knife_recalc_projmat(kcd);
2783
2784         ED_region_tag_redraw(kcd->ar);
2785
2786         kcd->refs = BLI_mempool_create(sizeof(Ref), 0, 2048, 0);
2787         kcd->kverts = BLI_mempool_create(sizeof(KnifeVert), 0, 512, BLI_MEMPOOL_ALLOW_ITER);
2788         kcd->kedges = BLI_mempool_create(sizeof(KnifeEdge), 0, 512, BLI_MEMPOOL_ALLOW_ITER);
2789
2790         kcd->origedgemap = BLI_ghash_ptr_new("knife origedgemap");
2791         kcd->origvertmap = BLI_ghash_ptr_new("knife origvertmap");
2792         kcd->kedgefacemap = BLI_ghash_ptr_new("knife kedgefacemap");
2793         kcd->facetrimap = BLI_ghash_ptr_new("knife facetrimap");
2794
2795         /* cut all the way through the mesh if use_occlude_geometry button not pushed */
2796         kcd->is_interactive = is_interactive;
2797         kcd->cut_through = cut_through;
2798         kcd->only_select = only_select;
2799
2800         /* can't usefully select resulting edges in face mode */
2801         kcd->select_result = (kcd->em->selectmode != SCE_SELECT_FACE);
2802
2803         knife_pos_data_clear(&kcd->curr);
2804         knife_pos_data_clear(&kcd->prev);
2805
2806         if (is_interactive) {
2807                 kcd->draw_handle = ED_region_draw_cb_activate(kcd->ar->type, knifetool_draw, kcd, REGION_DRAW_POST_VIEW);
2808
2809                 knife_init_colors(&kcd->colors);
2810         }
2811 }
2812
2813 static void knifetool_cancel(bContext *C, wmOperator *op)
2814 {
2815         /* this is just a wrapper around exit() */
2816         knifetool_exit(C, op);
2817 }
2818
2819 static int knifetool_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2820 {
2821         const bool only_select = RNA_boolean_get(op->ptr, "only_selected");
2822         const bool cut_through = !RNA_boolean_get(op->ptr, "use_occlude_geometry");
2823
2824         KnifeTool_OpData *kcd;
2825
2826         if (only_select) {
2827                 Object *obedit = CTX_data_edit_object(C);
2828                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2829                 if (em->bm->totfacesel == 0) {
2830                         BKE_report(op->reports, RPT_ERROR, "Selected faces required");
2831                         return OPERATOR_CANCELLED;
2832                 }
2833         }
2834
2835         view3d_operator_needs_opengl(C);
2836
2837         /* alloc new customdata */
2838         kcd = op->customdata = MEM_callocN(sizeof(KnifeTool_OpData), __func__);
2839
2840         knifetool_init(C, kcd, only_select, cut_through, true);
2841
2842         /* add a modal handler for this operator - handles loop selection */
2843         WM_cursor_modal_set(CTX_wm_window(C), BC_KNIFECURSOR);
2844         WM_event_add_modal_handler(C, op);
2845
2846         knifetool_update_mval_i(kcd, event->mval);
2847
2848         knife_update_header(C, kcd);
2849
2850         return OPERATOR_RUNNING_MODAL;
2851 }
2852
2853 enum {
2854         KNF_MODAL_CANCEL = 1,
2855         KNF_MODAL_CONFIRM,
2856         KNF_MODAL_MIDPOINT_ON,
2857         KNF_MODAL_MIDPOINT_OFF,
2858         KNF_MODAL_NEW_CUT,
2859         KNF_MODEL_IGNORE_SNAP_ON,
2860         KNF_MODEL_IGNORE_SNAP_OFF,
2861         KNF_MODAL_ADD_CUT,
2862         KNF_MODAL_ANGLE_SNAP_TOGGLE,
2863         KNF_MODAL_CUT_THROUGH_TOGGLE,
2864         KNF_MODAL_PANNING,
2865         KNF_MODAL_ADD_CUT_CLOSED,
2866 };
2867
2868 wmKeyMap *knifetool_modal_keymap(wmKeyConfig *keyconf)
2869 {
2870         static EnumPropertyItem modal_items[] = {
2871                 {KNF_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
2872                 {KNF_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
2873                 {KNF_MODAL_MIDPOINT_ON, "SNAP_MIDPOINTS_ON", 0, "Snap To Midpoints On", ""},
2874                 {KNF_MODAL_MIDPOINT_OFF, "SNAP_MIDPOINTS_OFF", 0, "Snap To Midpoints Off", ""},
2875                 {KNF_MODEL_IGNORE_SNAP_ON, "IGNORE_SNAP_ON", 0, "Ignore Snapping On", ""},
2876                 {KNF_MODEL_IGNORE_SNAP_OFF, "IGNORE_SNAP_OFF", 0, "Ignore Snapping Off", ""},
2877                 {KNF_MODAL_ANGLE_SNAP_TOGGLE, "ANGLE_SNAP_TOGGLE", 0, "Toggle Angle Snapping", ""},
2878                 {KNF_MODAL_CUT_THROUGH_TOGGLE, "CUT_THROUGH_TOGGLE", 0, "Toggle Cut Through", ""},
2879                 {KNF_MODAL_NEW_CUT, "NEW_CUT", 0, "End Current Cut", ""},
2880                 {KNF_MODAL_ADD_CUT, "ADD_CUT", 0, "Add Cut", ""},
2881                 {KNF_MODAL_PANNING, "PANNING", 0, "Panning", ""},
2882                 {0, NULL, 0, NULL, NULL}
2883         };
2884
2885         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "Knife Tool Modal Map");
2886
2887         /* this function is called for each spacetype, only needs to add map once */
2888         if (keymap && keymap->modal_items)
2889                 return NULL;
2890
2891         keymap = WM_modalkeymap_add(keyconf, "Knife Tool Modal Map", modal_items);
2892
2893         /* items for modal map */
2894         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, KNF_MODAL_CANCEL);
2895         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_ANY, KM_ANY, 0, KNF_MODAL_PANNING);
2896         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_DBL_CLICK, KM_ANY, 0, KNF_MODAL_ADD_CUT_CLOSED);
2897         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_ANY, KM_ANY, 0, KNF_MODAL_ADD_CUT);
2898         WM_modalkeymap_add_item(keymap, RIGHTMOUSE, KM_PRESS, KM_ANY, 0, KNF_MODAL_CANCEL);
2899         WM_modalkeymap_add_item(keymap, RETKEY, KM_PRESS, KM_ANY, 0, KNF_MODAL_CONFIRM);
2900         WM_modalkeymap_add_item(keymap, PADENTER, KM_PRESS, KM_ANY, 0, KNF_MODAL_CONFIRM);
2901         WM_modalkeymap_add_item(keymap, SPACEKEY, KM_PRESS, KM_ANY, 0, KNF_MODAL_CONFIRM);
2902         WM_modalkeymap_add_item(keymap, EKEY, KM_PRESS, 0, 0, KNF_MODAL_NEW_CUT);
2903
2904         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_PRESS, KM_ANY, 0, KNF_MODAL_MIDPOINT_ON);
2905         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, KNF_MODAL_MIDPOINT_OFF);
2906         WM_modalkeymap_add_item(keymap, RIGHTCTRLKEY, KM_PRESS, KM_ANY, 0, KNF_MODAL_MIDPOINT_ON);
2907         WM_modalkeymap_add_item(keymap, RIGHTCTRLKEY, KM_RELEASE, KM_ANY, 0, KNF_MODAL_MIDPOINT_OFF);
2908
2909         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, KNF_MODEL_IGNORE_SNAP_ON);
2910         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_RELEASE, KM_ANY, 0, KNF_MODEL_IGNORE_SNAP_OFF);
2911         WM_modalkeymap_add_item(keymap, RIGHTSHIFTKEY, KM_PRESS, KM_ANY, 0, KNF_MODEL_IGNORE_SNAP_ON);
2912         WM_modalkeymap_add_item(keymap, RIGHTSHIFTKEY, KM_RELEASE, KM_ANY, 0, KNF_MODEL_IGNORE_SNAP_OFF);
2913
2914         WM_modalkeymap_add_item(keymap, CKEY, KM_PRESS, 0, 0, KNF_MODAL_ANGLE_SNAP_TOGGLE);
2915         WM_modalkeymap_add_item(keymap, ZKEY, KM_PRESS, 0, 0, KNF_MODAL_CUT_THROUGH_TOGGLE);
2916
2917         WM_modalkeymap_assign(keymap, "MESH_OT_knife_tool");
2918
2919         return keymap;
2920 }
2921
2922 static int knifetool_modal(bContext *C, wmOperator *op, const wmEvent *event)
2923 {
2924         Object *obedit = CTX_data_edit_object(C);
2925         KnifeTool_OpData *kcd = op->customdata;
2926         bool do_refresh = false;
2927
2928         if (!obedit || obedit->type != OB_MESH || BKE_editmesh_from_object(obedit) != kcd->em) {
2929                 knifetool_exit(C, op);
2930                 ED_area_headerprint(CTX_wm_area(C), NULL);
2931                 return OPERATOR_FINISHED;
2932         }
2933
2934         view3d_operator_needs_opengl(C);
2935         ED_view3d_init_mats_rv3d(obedit, kcd->vc.rv3d);  /* needed to initialize clipping */
2936
2937         if (kcd->mode == MODE_PANNING)
2938                 kcd->mode = kcd->prevmode;
2939
2940         /* handle modal keymap */
2941         if (event->type == EVT_MODAL_MAP) {
2942                 switch (event->val) {
2943                         case KNF_MODAL_CANCEL:
2944                                 /* finish */
2945                                 ED_region_tag_redraw(kcd->ar);
2946
2947                                 knifetool_exit(C, op);
2948                                 ED_area_headerprint(CTX_wm_area(C), NULL);
2949
2950                                 return OPERATOR_CANCELLED;
2951                         case KNF_MODAL_CONFIRM:
2952                                 /* finish */
2953                                 ED_region_tag_redraw(kcd->ar);
2954
2955                                 knifetool_finish(op);
2956                                 knifetool_exit(C, op);
2957                                 ED_area_headerprint(CTX_wm_area(C), NULL);
2958
2959                                 return OPERATOR_FINISHED;
2960                         case KNF_MODAL_MIDPOINT_ON:
2961                                 kcd->snap_midpoints = true;
2962
2963                                 knife_recalc_projmat(kcd);
2964                                 knife_update_active(kcd);
2965                                 knife_update_header(C, kcd);
2966                                 ED_region_tag_redraw(kcd->ar);
2967                                 do_refresh = true;
2968                                 break;
2969                         case KNF_MODAL_MIDPOINT_OFF:
2970                                 kcd->snap_midpoints = false;
2971
2972                                 knife_recalc_projmat(kcd);
2973                                 knife_update_active(kcd);
2974                                 knife_update_header(C, kcd);
2975                                 ED_region_tag_redraw(kcd->ar);
2976                                 do_refresh = true;
2977                                 break;
2978                         case KNF_MODEL_IGNORE_SNAP_ON:
2979                                 ED_region_tag_redraw(kcd->ar);
2980                                 kcd->ignore_vert_snapping = kcd->ignore_edge_snapping = true;
2981                                 knife_update_header(C, kcd);
2982                                 do_refresh = true;
2983                                 break;
2984                         case KNF_MODEL_IGNORE_SNAP_OFF:
2985                                 ED_region_tag_redraw(kcd->ar);
2986                                 kcd->ignore_vert_snapping = kcd->ignore_edge_snapping = false;
2987                                 knife_update_header(C, kcd);
2988                                 do_refresh = true;
2989                                 break;
2990                         case KNF_MODAL_ANGLE_SNAP_TOGGLE:
2991                                 kcd->angle_snapping = !kcd->angle_snapping;
2992                                 knife_update_header(C, kcd);
2993                                 do_refresh = true;
2994                                 break;
2995                         case KNF_MODAL_CUT_THROUGH_TOGGLE:
2996                                 kcd->cut_through = !kcd->cut_through;
2997                                 knife_update_header(C, kcd);
2998                                 do_refresh = true;
2999                                 break;
3000                         case KNF_MODAL_NEW_CUT:
3001                                 ED_region_tag_redraw(kcd->ar);
3002                                 knife_finish_cut(kcd);
3003                                 kcd->mode = MODE_IDLE;
3004                                 break;
3005                         case KNF_MODAL_ADD_CUT:
3006                                 knife_recalc_projmat(kcd);
3007
3008                                 /* get the value of the event which triggered this one */
3009                                 if (event->prevval != KM_RELEASE) {
3010                                         if (kcd->mode == MODE_DRAGGING) {
3011                                                 knife_add_cut(kcd);
3012                                         }
3013                                         else if (kcd->mode != MODE_PANNING) {
3014                                                 knife_start_cut(kcd);
3015                                                 kcd->mode = MODE_DRAGGING;
3016                                                 kcd->init = kcd->curr;
3017                                         }
3018
3019                                         /* freehand drawing is incompatible with cut-through */
3020                                         if (kcd->cut_through == false) {
3021                                                 kcd->is_drag_hold = true;
3022                                         }
3023                                 }
3024                                 else {
3025                                         kcd->is_drag_hold = false;
3026
3027                                         /* needed because the last face 'hit' is ignored when dragging */
3028                                         knifetool_update_mval(kcd, kcd->curr.mval);
3029                                 }
3030
3031                                 ED_region_tag_redraw(kcd->ar);
3032                                 break;
3033                         case KNF_MODAL_ADD_CUT_CLOSED:
3034                                 if (kcd->mode == MODE_DRAGGING) {
3035
3036                                         /* shouldn't be possible with default key-layout, just incase... */
3037                                         if (kcd->is_drag_hold) {
3038                                                 kcd->is_drag_hold = false;
3039                                                 knifetool_update_mval(kcd, kcd->curr.mval);
3040                                         }
3041
3042                                         kcd->prev = kcd->curr;
3043                                         kcd->curr = kcd->init;
3044
3045                                         knife_project_v2(kcd, kcd->curr.cage, kcd->curr.mval);
3046                                         knifetool_update_mval(kcd, kcd->curr.mval);
3047
3048                                         knife_add_cut(kcd);
3049
3050                                         /* KNF_MODAL_NEW_CUT */
3051                                         knife_finish_cut(kcd);
3052                                         kcd->mode = MODE