Cleanup: use BLI_listbase_*** prefix for count,sort,sort_r
[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         int n;
753
754         (void) kcd;
755
756         n = BLI_listbase_count(hits);
757         if (n < 2)
758                 return;
759
760         prevlh = NULL;
761         for (r = hits->first; r; r = r->next) {
762                 lh = (KnifeLineHit *)r->ref;
763                 if (prevlh)
764                         knife_add_single_cut(kcd, prevlh, lh, f);
765                 prevlh = lh;
766         }
767
768 }
769
770 /* User has just left-clicked after the first time.
771  * Add all knife cuts implied by line from prev to curr.
772  * If that line crossed edges then kcd->linehits will be non-NULL.
773  * Make all of the KnifeVerts and KnifeEdges implied by this cut.
774  */
775 static void knife_add_cut(KnifeTool_OpData *kcd)
776 {
777         int i;
778         KnifeLineHit *lh;
779         GHash *facehits;
780         BMFace *f;
781         Ref *r;
782         GHashIterator giter;
783         ListBase *lst;
784
785         prepare_linehits_for_cut(kcd);
786         if (kcd->totlinehit == 0) {
787                 if (kcd->is_drag_hold == false) {
788                         kcd->prev = kcd->curr;
789                 }
790                 return;
791         }
792
793         /* make facehits: map face -> list of linehits touching it */
794         facehits = BLI_ghash_ptr_new("knife facehits");
795         for (i = 0; i < kcd->totlinehit; i++) {
796                 lh = &kcd->linehits[i];
797                 if (lh->f) {
798                         add_hit_to_facehits(kcd, facehits, lh->f, lh);
799                 }
800                 if (lh->v) {
801                         for (r = lh->v->faces.first; r; r = r->next) {
802                                 add_hit_to_facehits(kcd, facehits, r->ref, lh);
803                         }
804                 }
805                 if (lh->kfe) {
806                         for (r = lh->kfe->faces.first; r; r = r->next) {
807                                 add_hit_to_facehits(kcd, facehits, r->ref, lh);
808                         }
809                 }
810         }
811
812         /* Note: as following loop progresses, the 'v' fields of
813          * the linehits will be filled in (as edges are split or
814          * in-face verts are made), so it may be true that both
815          * the v and the kfe or f fields will be non-NULL. */
816         GHASH_ITER (giter, facehits) {
817                 f = (BMFace *)BLI_ghashIterator_getKey(&giter);
818                 lst = (ListBase *)BLI_ghashIterator_getValue(&giter);
819                 knife_cut_face(kcd, f, lst);
820         }
821
822         /* set up for next cut */
823         kcd->prev = kcd->curr;
824
825
826         if (kcd->prev.bmface) {
827                 KnifeLineHit *lh;
828                 /* was "in face" but now we have a KnifeVert it is snapped to */
829                 lh = &kcd->linehits[kcd->totlinehit - 1];
830
831                 if (kcd->is_drag_hold) {
832                         linehit_to_knifepos(&kcd->prev, lh);
833                 }
834                 else {
835                         kcd->prev.vert = lh->v;
836                 }
837                 kcd->prev.bmface = NULL;
838         }
839
840         BLI_ghash_free(facehits, NULL, NULL);
841         MEM_freeN(kcd->linehits);
842         kcd->linehits = NULL;
843         kcd->totlinehit = 0;
844 }
845
846 static void knife_finish_cut(KnifeTool_OpData *kcd)
847 {
848         if (kcd->linehits) {
849                 MEM_freeN(kcd->linehits);
850                 kcd->linehits = NULL;
851                 kcd->totlinehit = 0;
852         }
853 }
854
855 static void knifetool_draw_angle_snapping(const KnifeTool_OpData *kcd)
856 {
857         bglMats mats;
858         double u[3], u1[2], u2[2], v1[3], v2[3], dx, dy;
859         double wminx, wminy, wmaxx, wmaxy;
860
861         /* make u the window coords of prevcage */
862         view3d_get_transformation(kcd->ar, kcd->vc.rv3d, kcd->ob, &mats);
863         gluProject(kcd->prev.cage[0], kcd->prev.cage[1], kcd->prev.cage[2],
864                    mats.modelview, mats.projection, mats.viewport,
865                    &u[0], &u[1], &u[2]);
866
867         /* make u1, u2 the points on window going through u at snap angle */
868         wminx = kcd->ar->winrct.xmin;
869         wmaxx = kcd->ar->winrct.xmin + kcd->ar->winx;
870         wminy = kcd->ar->winrct.ymin;
871         wmaxy = kcd->ar->winrct.ymin + kcd->ar->winy;
872
873         switch (kcd->angle_snapping) {
874                 case ANGLE_0:
875                         u1[0] = wminx;
876                         u2[0] = wmaxx;
877                         u1[1] = u2[1] = u[1];
878                         break;
879                 case ANGLE_90:
880                         u1[0] = u2[0] = u[0];
881                         u1[1] = wminy;
882                         u2[1] = wmaxy;
883                         break;
884                 case ANGLE_45:
885                         /* clip against left or bottom */
886                         dx = u[0] - wminx;
887                         dy = u[1] - wminy;
888                         if (dy > dx) {
889                                 u1[0] = wminx;
890                                 u1[1] = u[1] - dx;
891                         }
892                         else {
893                                 u1[0] = u[0] - dy;
894                                 u1[1] = wminy;
895                         }
896                         /* clip against right or top */
897                         dx = wmaxx - u[0];
898                         dy = wmaxy - u[1];
899                         if (dy > dx) {
900                                 u2[0] = wmaxx;
901                                 u2[1] = u[1] + dx;
902                         }
903                         else {
904                                 u2[0] = u[0] + dy;
905                                 u2[1] = wmaxy;
906                         }
907                         break;
908                 case ANGLE_135:
909                         /* clip against right or bottom */
910                         dx = wmaxx - u[0];
911                         dy = u[1] - wminy;
912                         if (dy > dx) {
913                                 u1[0] = wmaxx;
914                                 u1[1] = u[1] - dx;
915                         }
916                         else {
917                                 u1[0] = u[0] + dy;
918                                 u1[1] = wminy;
919                         }
920                         /* clip against left or top */
921                         dx = u[0] - wminx;
922                         dy = wmaxy - u[1];
923                         if (dy > dx) {
924                                 u2[0] = wminx;
925                                 u2[1] = u[1] + dx;
926                         }
927                         else {
928                                 u2[0] = u[0] - dy;
929                                 u2[1] = wmaxy;
930                         }
931                         break;
932                 default:
933                         return;
934         }
935
936         /* unproject u1 and u2 back into object space */
937         gluUnProject(u1[0], u1[1], 0.0,
938                      mats.modelview, mats.projection, mats.viewport,
939                      &v1[0], &v1[1], &v1[2]);
940         gluUnProject(u2[0], u2[1], 0.0,
941                      mats.modelview, mats.projection, mats.viewport,
942                      &v2[0], &v2[1], &v2[2]);
943
944         UI_ThemeColor(TH_TRANSFORM);
945         glLineWidth(2.0);
946         glBegin(GL_LINES);
947         glVertex3dv(v1);
948         glVertex3dv(v2);
949         glEnd();
950 }
951
952 static void knife_init_colors(KnifeColors *colors)
953 {
954         /* possible BMESH_TODO: add explicit themes or calculate these by
955          * figuring out contrasting colors with grid / edges / verts
956          * a la UI_make_axis_color */
957         UI_GetThemeColor3ubv(TH_NURB_VLINE, colors->line);
958         UI_GetThemeColor3ubv(TH_NURB_ULINE, colors->edge);
959         UI_GetThemeColor3ubv(TH_HANDLE_SEL_VECT, colors->curpoint);
960         UI_GetThemeColor3ubv(TH_HANDLE_SEL_VECT, colors->curpoint_a);
961         colors->curpoint_a[3] = 102;
962         UI_GetThemeColor3ubv(TH_ACTIVE_SPLINE, colors->point);
963         UI_GetThemeColor3ubv(TH_ACTIVE_SPLINE, colors->point_a);
964         colors->point_a[3] = 102;
965 }
966
967 /* modal loop selection drawing callback */
968 static void knifetool_draw(const bContext *C, ARegion *UNUSED(ar), void *arg)
969 {
970         View3D *v3d = CTX_wm_view3d(C);
971         const KnifeTool_OpData *kcd = arg;
972
973         if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
974
975         glPolygonOffset(1.0f, 1.0f);
976
977         glPushMatrix();
978         glMultMatrixf(kcd->ob->obmat);
979
980         if (kcd->mode == MODE_DRAGGING) {
981                 if (kcd->angle_snapping != ANGLE_FREE)
982                         knifetool_draw_angle_snapping(kcd);
983
984                 glColor3ubv(kcd->colors.line);
985                 
986                 glLineWidth(2.0);
987
988                 glBegin(GL_LINES);
989                 glVertex3fv(kcd->prev.cage);
990                 glVertex3fv(kcd->curr.cage);
991                 glEnd();
992
993                 glLineWidth(1.0);
994         }
995
996         if (kcd->prev.vert) {
997                 glColor3ubv(kcd->colors.point);
998                 glPointSize(11);
999
1000                 glBegin(GL_POINTS);
1001                 glVertex3fv(kcd->prev.cage);
1002                 glEnd();
1003         }
1004
1005         if (kcd->prev.bmface) {
1006                 glColor3ubv(kcd->colors.curpoint);
1007                 glPointSize(9);
1008
1009                 glBegin(GL_POINTS);
1010                 glVertex3fv(kcd->prev.cage);
1011                 glEnd();
1012         }
1013
1014         if (kcd->curr.edge) {
1015                 glColor3ubv(kcd->colors.edge);
1016                 glLineWidth(2.0);
1017
1018                 glBegin(GL_LINES);
1019                 glVertex3fv(kcd->curr.edge->v1->cageco);
1020                 glVertex3fv(kcd->curr.edge->v2->cageco);
1021                 glEnd();
1022
1023                 glLineWidth(1.0);
1024         }
1025         else if (kcd->curr.vert) {
1026                 glColor3ubv(kcd->colors.point);
1027                 glPointSize(11);
1028
1029                 glBegin(GL_POINTS);
1030                 glVertex3fv(kcd->curr.cage);
1031                 glEnd();
1032         }
1033
1034         if (kcd->curr.bmface) {
1035                 glColor3ubv(kcd->colors.curpoint);
1036                 glPointSize(9);
1037
1038                 glBegin(GL_POINTS);
1039                 glVertex3fv(kcd->curr.cage);
1040                 glEnd();
1041         }
1042
1043         if (kcd->totlinehit > 0) {
1044                 KnifeLineHit *lh;
1045                 int i;
1046
1047                 glEnable(GL_BLEND);
1048                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1049
1050                 /* draw any snapped verts first */
1051                 glColor4ubv(kcd->colors.point_a);
1052                 glPointSize(11);
1053                 glBegin(GL_POINTS);
1054                 lh = kcd->linehits;
1055                 for (i = 0; i < kcd->totlinehit; i++, lh++) {
1056                         if (lh->v)
1057                                 glVertex3fv(lh->cagehit);
1058                 }
1059                 glEnd();
1060
1061                 /* now draw the rest */
1062                 glColor4ubv(kcd->colors.curpoint_a);
1063                 glPointSize(7);
1064                 glBegin(GL_POINTS);
1065                 lh = kcd->linehits;
1066                 for (i = 0; i < kcd->totlinehit; i++, lh++) {
1067                         if (!lh->v)
1068                                 glVertex3fv(lh->cagehit);
1069                 }
1070                 glEnd();
1071                 glDisable(GL_BLEND);
1072         }
1073
1074         if (kcd->totkedge > 0) {
1075                 BLI_mempool_iter iter;
1076                 KnifeEdge *kfe;
1077
1078                 glLineWidth(1.0);
1079                 glBegin(GL_LINES);
1080
1081                 BLI_mempool_iternew(kcd->kedges, &iter);
1082                 for (kfe = BLI_mempool_iterstep(&iter); kfe; kfe = BLI_mempool_iterstep(&iter)) {
1083                         if (!kfe->draw)
1084                                 continue;
1085
1086                         glColor3ubv(kcd->colors.line);
1087
1088                         glVertex3fv(kfe->v1->cageco);
1089                         glVertex3fv(kfe->v2->cageco);
1090                 }
1091
1092                 glEnd();
1093                 glLineWidth(1.0);
1094         }
1095
1096         if (kcd->totkvert > 0) {
1097                 BLI_mempool_iter iter;
1098                 KnifeVert *kfv;
1099
1100                 glPointSize(5.0);
1101
1102                 glBegin(GL_POINTS);
1103                 BLI_mempool_iternew(kcd->kverts, &iter);
1104                 for (kfv = BLI_mempool_iterstep(&iter); kfv; kfv = BLI_mempool_iterstep(&iter)) {
1105                         if (!kfv->draw)
1106                                 continue;
1107
1108                         glColor3ubv(kcd->colors.point);
1109
1110                         glVertex3fv(kfv->cageco);
1111                 }
1112
1113                 glEnd();
1114         }
1115
1116         glPopMatrix();
1117
1118         if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
1119 }
1120
1121 /**
1122  * Find intersection of v1-v2 with face f.
1123  * Only take intersections that are at least \a face_tol_sq (in screen space) away
1124  * from other intersection elements.
1125  * If v1-v2 is coplanar with f, call that "no intersection though
1126  * it really means "infinite number of intersections".
1127  * In such a case we should have gotten hits on edges or verts of the face.
1128  */
1129 static bool knife_ray_intersect_face(
1130         KnifeTool_OpData *kcd,
1131         const float s[2], const float v1[3], const float v2[3],
1132         BMFace *f, const float face_tol_sq,
1133         float hit_co[3], float hit_cageco[3])
1134 {
1135         int tottri, tri_i;
1136         float raydir[3];
1137         float tri_norm[3], tri_plane[4];
1138         float se1[2], se2[2];
1139         float d, lambda;
1140         BMLoop **tri;
1141         ListBase *lst;
1142         Ref *ref;
1143         KnifeEdge *kfe;
1144
1145         sub_v3_v3v3(raydir, v2, v1);
1146         normalize_v3(raydir);
1147         tri_i = get_lowest_face_tri(kcd, f);
1148         tottri = kcd->em->tottri;
1149         BLI_assert(tri_i >= 0 && tri_i < tottri);
1150
1151         for (; tri_i < tottri; tri_i++) {
1152                 const float *lv1, *lv2, *lv3;
1153
1154                 tri = kcd->em->looptris[tri_i];
1155                 if (tri[0]->f != f)
1156                         break;
1157                 lv1 = kcd->cagecos[BM_elem_index_get(tri[0]->v)];
1158                 lv2 = kcd->cagecos[BM_elem_index_get(tri[1]->v)];
1159                 lv3 = kcd->cagecos[BM_elem_index_get(tri[2]->v)];
1160                 /* using epsilon test in case ray is directly through an internal
1161                  * tesselation edge and might not hit either tesselation tri with
1162                  * an exact test;
1163                  * we will exclude hits near real edges by a later test */
1164                 if (isect_ray_tri_epsilon_v3(v1, raydir, lv1, lv2, lv3, &lambda, NULL, KNIFE_FLT_EPS)) {
1165                         /* check if line coplanar with tri */
1166                         normal_tri_v3(tri_norm, lv1, lv2, lv3);
1167                         plane_from_point_normal_v3(tri_plane, lv1, tri_norm);
1168                         if ((dist_squared_to_plane_v3(v1, tri_plane) < KNIFE_FLT_EPS) &&
1169                             (dist_squared_to_plane_v3(v2, tri_plane) < KNIFE_FLT_EPS))
1170                         {
1171                                 return false;
1172                         }
1173                         copy_v3_v3(hit_cageco, v1);
1174                         madd_v3_v3fl(hit_cageco, raydir, lambda);
1175                         /* Now check that far enough away from verts and edges */
1176                         lst = knife_get_face_kedges(kcd, f);
1177                         for (ref = lst->first; ref; ref = ref->next) {
1178                                 kfe = ref->ref;
1179                                 knife_project_v2(kcd, kfe->v1->cageco, se1);
1180                                 knife_project_v2(kcd, kfe->v2->cageco, se2);
1181                                 d = dist_squared_to_line_segment_v2(s, se1, se2);
1182                                 if (d < face_tol_sq) {
1183                                         return false;
1184                                 }
1185                         }
1186
1187                         transform_point_by_tri_v3(
1188                                 hit_co, hit_cageco,
1189                                 tri[0]->v->co, tri[1]->v->co, tri[2]->v->co,
1190                                 lv1, lv2, lv3);
1191                         return true;
1192                 }
1193         }
1194         return false;
1195 }
1196
1197 /* Calculate maximum excursion from (0,0,0) of mesh */
1198 static void calc_ortho_extent(KnifeTool_OpData *kcd)
1199 {
1200         BMIter iter;
1201         BMVert *v;
1202         BMesh *bm = kcd->em->bm;
1203         float max_xyz = 0.0f;
1204         int i;
1205
1206         BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
1207                 for (i = 0; i < 3; i++)
1208                         max_xyz = max_ff(max_xyz, fabsf(v->co[i]));
1209         }
1210         kcd->ortho_extent = max_xyz;
1211 }
1212
1213 /* Check if p is visible (not clipped, not occluded by another face).
1214  * s in screen projection of p. */
1215 static bool point_is_visible(KnifeTool_OpData *kcd, const float p[3], const float s[2], bglMats *mats)
1216 {
1217         BMFace *f_hit;
1218
1219         /* If box clipping on, make sure p is not clipped */
1220         if (kcd->vc.rv3d->rflag & RV3D_CLIPPING &&
1221             ED_view3d_clipping_test(kcd->vc.rv3d, p, true))
1222         {
1223                 return false;
1224         }
1225
1226         /* If not cutting through, make sure no face is in front of p */
1227         if (!kcd->cut_through) {
1228                 float dist;
1229                 float view[3], p_ofs[3];
1230
1231                 /* TODO: I think there's a simpler way to get the required raycast ray */
1232                 ED_view3d_unproject(mats, view, s[0], s[1], 0.0f);
1233
1234                 mul_m4_v3(kcd->ob->imat, view);
1235
1236                 /* make p_ofs a little towards view, so ray doesn't hit p's face. */
1237                 sub_v3_v3(view, p);
1238                 dist = normalize_v3(view);
1239                 madd_v3_v3v3fl(p_ofs, p, view, KNIFE_FLT_EPSBIG * 3.0f);
1240
1241                 /* avoid projecting behind the viewpoint */
1242                 if (kcd->is_ortho && (kcd->vc.rv3d->persp != RV3D_CAMOB)) {
1243                         dist = kcd->vc.v3d->far * 2.0f;
1244                 }
1245
1246                 if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1247                         float view_clip[2][3];
1248                         /* note: view_clip[0] should never get clipped */
1249                         copy_v3_v3(view_clip[0], p_ofs);
1250                         madd_v3_v3v3fl(view_clip[1], p_ofs, view, dist);
1251
1252                         if (clip_segment_v3_plane_n(view_clip[0], view_clip[1], kcd->vc.rv3d->clip_local, 6)) {
1253                                 dist = len_v3v3(p_ofs, view_clip[1]);
1254                         }
1255                 }
1256
1257                 /* see if there's a face hit between p1 and the view */
1258                 f_hit = BKE_bmbvh_ray_cast(kcd->bmbvh, p_ofs, view, KNIFE_FLT_EPS, &dist, NULL, NULL);
1259                 if (f_hit)
1260                         return false;
1261         }
1262
1263         return true;
1264 }
1265
1266 /* Clip the line (v1, v2) to planes perpendicular to it and distances d from
1267  * the closest point on the line to the origin */
1268 static void clip_to_ortho_planes(float v1[3], float v2[3], float d)
1269 {
1270         float closest[3];
1271         const float origin[3] = {0.0f, 0.0f, 0.0f};
1272
1273         closest_to_line_v3(closest, origin, v1, v2);
1274         dist_ensure_v3_v3fl(v1, closest, d);
1275         dist_ensure_v3_v3fl(v2, closest, d);
1276 }
1277
1278 static void set_linehit_depth(KnifeTool_OpData *kcd, KnifeLineHit *lh)
1279 {
1280         lh->m = dot_m4_v3_row_z(kcd->vc.rv3d->persmatob, lh->cagehit);
1281 }
1282
1283 /* Finds visible (or all, if cutting through) edges that intersects the current screen drag line */
1284 static void knife_find_line_hits(KnifeTool_OpData *kcd)
1285 {
1286         bglMats mats;
1287         SmallHash faces, kfes, kfvs;
1288         float v1[3], v2[3], v3[3], v4[3], s1[2], s2[2];
1289         BVHTree *planetree, *tree;
1290         BVHTreeOverlap *results, *result;
1291         BMLoop **ls;
1292         BMFace *f;
1293         KnifeEdge *kfe;
1294         KnifeVert *v;
1295         ListBase *lst;
1296         Ref *ref;
1297         KnifeLineHit *linehits = NULL;
1298         BLI_array_declare(linehits);
1299         SmallHashIter hiter;
1300         KnifeLineHit hit;
1301         void *val;
1302         float plane_cos[12];
1303         float s[2], se1[2], se2[2], sint[2];
1304         float r1[3], r2[3];
1305         float d, d1, d2, lambda;
1306         float vert_tol, vert_tol_sq;
1307         float line_tol, line_tol_sq;
1308         float face_tol, face_tol_sq;
1309         float eps_scale;
1310         int isect_kind;
1311         unsigned int tot;
1312         int i;
1313         const bool use_hit_prev = true;
1314         const bool use_hit_curr = (kcd->is_drag_hold == false);
1315
1316         bgl_get_mats(&mats);
1317
1318         if (kcd->linehits) {
1319                 MEM_freeN(kcd->linehits);
1320                 kcd->linehits = NULL;
1321                 kcd->totlinehit = 0;
1322         }
1323
1324         copy_v3_v3(v1, kcd->prev.cage);
1325         copy_v3_v3(v2, kcd->curr.cage);
1326
1327         /* project screen line's 3d coordinates back into 2d */
1328         knife_project_v2(kcd, v1, s1);
1329         knife_project_v2(kcd, v2, s2);
1330
1331         if (kcd->is_interactive) {
1332                 if (len_squared_v2v2(s1, s2) < 1.0f) {
1333                         return;
1334                 }
1335         }
1336         else {
1337                 if (len_squared_v2v2(s1, s2) < KNIFE_FLT_EPS_SQUARED) {
1338                         return;
1339                 }
1340         }
1341
1342         /* unproject screen line */
1343         ED_view3d_win_to_segment(kcd->ar, kcd->vc.v3d, s1, v1, v3, true);
1344         ED_view3d_win_to_segment(kcd->ar, kcd->vc.v3d, s2, v2, v4, true);
1345
1346         mul_m4_v3(kcd->ob->imat, v1);
1347         mul_m4_v3(kcd->ob->imat, v2);
1348         mul_m4_v3(kcd->ob->imat, v3);
1349         mul_m4_v3(kcd->ob->imat, v4);
1350
1351         /* numeric error, 'v1' -> 'v2', 'v2' -> 'v4' can end up being ~2000 units apart in otho mode
1352          * (from ED_view3d_win_to_segment_clip() above)
1353          * this gives precision error; rather then solving properly
1354          * (which may involve using doubles everywhere!),
1355          * limit the distance between these points */
1356         if (kcd->is_ortho && (kcd->vc.rv3d->persp != RV3D_CAMOB)) {
1357                 if (kcd->ortho_extent == 0.0f)
1358                         calc_ortho_extent(kcd);
1359                 clip_to_ortho_planes(v1, v3, kcd->ortho_extent + 10.0f);
1360                 clip_to_ortho_planes(v2, v4, kcd->ortho_extent + 10.0f);
1361         }
1362
1363         /* First use bvh tree to find faces, knife edges, and knife verts that might
1364          * intersect the cut plane with rays v1-v3 and v2-v4.
1365          * This deduplicates the candidates before doing more expensive intersection tests. */
1366
1367         tree = BKE_bmbvh_tree_get(kcd->bmbvh);
1368         planetree = BLI_bvhtree_new(4, FLT_EPSILON * 4, 8, 8);
1369         copy_v3_v3(plane_cos + 0, v1);
1370         copy_v3_v3(plane_cos + 3, v2);
1371         copy_v3_v3(plane_cos + 6, v3);
1372         copy_v3_v3(plane_cos + 9, v4);
1373         BLI_bvhtree_insert(planetree, 0, plane_cos, 4);
1374         BLI_bvhtree_balance(planetree);
1375
1376         results = BLI_bvhtree_overlap(tree, planetree, &tot);
1377         if (!results) {
1378                 BLI_bvhtree_free(planetree);
1379                 return;
1380         }
1381
1382         BLI_smallhash_init(&faces);
1383         BLI_smallhash_init(&kfes);
1384         BLI_smallhash_init(&kfvs);
1385
1386         for (i = 0, result = results; i < tot; i++, result++) {
1387                 ls = (BMLoop **)kcd->em->looptris[result->indexA];
1388                 f = ls[0]->f;
1389                 set_lowest_face_tri(kcd, f, result->indexA);
1390                 /* for faces, store index of lowest hit looptri in hash */
1391                 if (BLI_smallhash_haskey(&faces, (uintptr_t)f)) {
1392                         continue;
1393                 }
1394                 /* don't care what the value is except that it is non-NULL, for iterator */
1395                 BLI_smallhash_insert(&faces, (uintptr_t)f, f);
1396
1397                 lst = knife_get_face_kedges(kcd, f);
1398                 for (ref = lst->first; ref; ref = ref->next) {
1399                         kfe = ref->ref;
1400                         if (BLI_smallhash_haskey(&kfes, (uintptr_t)kfe))
1401                                 continue;
1402                         BLI_smallhash_insert(&kfes, (uintptr_t)kfe, kfe);
1403                         v = kfe->v1;
1404                         if (!BLI_smallhash_haskey(&kfvs, (uintptr_t)v))
1405                                 BLI_smallhash_insert(&kfvs, (uintptr_t)v, v);
1406                         v = kfe->v2;
1407                         if (!BLI_smallhash_haskey(&kfvs, (uintptr_t)v))
1408                                 BLI_smallhash_insert(&kfvs, (uintptr_t)v, v);
1409                 }
1410         }
1411
1412         /* Now go through the candidates and find intersections */
1413         /* These tolerances, in screen space, are for intermediate hits, as ends are already snapped to screen */
1414         {
1415                 /* Scale the epsilon by the zoom level
1416                  * to compensate for projection imprecision, see T41164 */
1417                 float zoom_xy[2] = {kcd->vc.rv3d->winmat[0][0],
1418                                     kcd->vc.rv3d->winmat[1][1]};
1419                 eps_scale = len_v2(zoom_xy);
1420         }
1421
1422         vert_tol = KNIFE_FLT_EPS_PX * eps_scale;
1423         line_tol = KNIFE_FLT_EPS_PX * eps_scale;
1424         face_tol = max_ff(vert_tol, line_tol);
1425
1426         vert_tol_sq = vert_tol * vert_tol;
1427         line_tol_sq = line_tol * line_tol;
1428         face_tol_sq = face_tol * face_tol;
1429
1430         /* Assume these tolerances swamp floating point rounding errors in calculations below */
1431
1432         /* first look for vertex hits */
1433         for (val = BLI_smallhash_iternew(&kfvs, &hiter, (uintptr_t *)&v); val;
1434              val = BLI_smallhash_iternext(&hiter, (uintptr_t *)&v))
1435         {
1436                 knife_project_v2(kcd, v->cageco, s);
1437                 d = dist_squared_to_line_segment_v2(s, s1, s2);
1438                 if (d <= vert_tol_sq) {
1439                         if (point_is_visible(kcd, v->cageco, s, &mats)) {
1440                                 memset(&hit, 0, sizeof(hit));
1441                                 hit.v = v;
1442
1443                                 /* If this isn't from an existing BMVert, it may have been added to a BMEdge originally.
1444                                  * knowing if the hit comes from an edge is important for edge-in-face checks later on
1445                                  * see: #knife_add_single_cut -> #knife_verts_edge_in_face, T42611 */
1446                                 if (v->v == NULL) {
1447                                         for (ref = v->edges.first; ref; ref = ref->next) {
1448                                                 kfe = ref->ref;
1449                                                 if (kfe->e) {
1450                                                         hit.kfe = kfe;
1451                                                         break;
1452                                                 }
1453                                         }
1454                                 }
1455
1456                                 copy_v3_v3(hit.hit, v->co);
1457                                 copy_v3_v3(hit.cagehit, v->cageco);
1458                                 copy_v2_v2(hit.schit, s);
1459                                 set_linehit_depth(kcd, &hit);
1460                                 BLI_array_append(linehits, hit);
1461                         }
1462                 }
1463         }
1464         /* now edge hits; don't add if a vertex at end of edge should have hit */
1465         for (val = BLI_smallhash_iternew(&kfes, &hiter, (uintptr_t *)&kfe); val;
1466              val = BLI_smallhash_iternext(&hiter, (uintptr_t *)&kfe))
1467         {
1468                 knife_project_v2(kcd, kfe->v1->cageco, se1);
1469                 knife_project_v2(kcd, kfe->v2->cageco, se2);
1470                 isect_kind = isect_seg_seg_v2_point(s1, s2, se1, se2, sint);
1471                 if (isect_kind == -1) {
1472                         /* isect_seg_seg_v2 doesn't do tolerance test around ends of s1-s2 */
1473                         closest_to_line_segment_v2(sint, s1, se1, se2);
1474                         if (len_squared_v2v2(sint, s1) <= line_tol_sq)
1475                                 isect_kind = 1;
1476                         else {
1477                                 closest_to_line_segment_v2(sint, s2, se1, se2);
1478                                 if (len_squared_v2v2(sint, s2) <= line_tol_sq)
1479                                         isect_kind = 1;
1480                         }
1481                 }
1482                 if (isect_kind == 1) {
1483                         d1 = len_v2v2(sint, se1);
1484                         d2 = len_v2v2(se2, se1);
1485                         if (!(d1 <= line_tol || d2 <= line_tol || fabsf(d1 - d2) <= line_tol)) {
1486                                 float p_cage[3], p_cage_tmp[3];
1487                                 lambda = d1 / d2;
1488                                 /* Can't just interpolate between ends of kfe because
1489                                  * that doesn't work with perspective transformation.
1490                                  * Need to find 3d intersection of ray through sint */
1491                                 knife_input_ray_segment(kcd, sint, 1.0f, r1, r2);
1492                                 isect_kind = isect_line_line_v3(kfe->v1->cageco, kfe->v2->cageco, r1, r2, p_cage, p_cage_tmp);
1493                                 if (isect_kind >= 1 && point_is_visible(kcd, p_cage, sint, &mats)) {
1494                                         memset(&hit, 0, sizeof(hit));
1495                                         if (kcd->snap_midpoints) {
1496                                                 /* choose intermediate point snap too */
1497                                                 mid_v3_v3v3(p_cage, kfe->v1->cageco, kfe->v2->cageco);
1498                                                 mid_v2_v2v2(sint, se1, se2);
1499                                                 lambda = 0.5f;
1500                                         }
1501                                         hit.kfe = kfe;
1502                                         transform_point_by_seg_v3(
1503                                                 hit.hit, p_cage,
1504                                                 kfe->v1->co, kfe->v2->co,
1505                                                 kfe->v1->cageco, kfe->v2->cageco);
1506                                         copy_v3_v3(hit.cagehit, p_cage);
1507                                         copy_v2_v2(hit.schit, sint);
1508                                         hit.perc = lambda;
1509                                         set_linehit_depth(kcd, &hit);
1510                                         BLI_array_append(linehits, hit);
1511                                 }
1512                         }
1513                 }
1514         }
1515         /* now face hits; don't add if a vertex or edge in face should have hit */
1516         for (val = BLI_smallhash_iternew(&faces, &hiter, (uintptr_t *)&f); val;
1517              val = BLI_smallhash_iternext(&hiter, (uintptr_t *)&f))
1518         {
1519                 float p[3], p_cage[3];
1520
1521                 if (use_hit_prev && knife_ray_intersect_face(kcd, s1, v1, v3, f, face_tol_sq, p, p_cage)) {
1522                         if (point_is_visible(kcd, p_cage, s1, &mats)) {
1523                                 memset(&hit, 0, sizeof(hit));
1524                                 hit.f = f;
1525                                 copy_v3_v3(hit.hit, p);
1526                                 copy_v3_v3(hit.cagehit, p_cage);
1527                                 copy_v2_v2(hit.schit, s1);
1528                                 set_linehit_depth(kcd, &hit);
1529                                 BLI_array_append(linehits, hit);
1530                         }
1531                 }
1532
1533                 if (use_hit_curr && knife_ray_intersect_face(kcd, s2, v2, v4, f, face_tol_sq, p, p_cage)) {
1534                         if (point_is_visible(kcd, p_cage, s2, &mats)) {
1535                                 memset(&hit, 0, sizeof(hit));
1536                                 hit.f = f;
1537                                 copy_v3_v3(hit.hit, p);
1538                                 copy_v3_v3(hit.cagehit, p_cage);
1539                                 copy_v2_v2(hit.schit, s2);
1540                                 set_linehit_depth(kcd, &hit);
1541                                 BLI_array_append(linehits, hit);
1542                         }
1543                 }
1544         }
1545
1546         kcd->linehits = linehits;
1547         kcd->totlinehit = BLI_array_count(linehits);
1548
1549         /* find position along screen line, used for sorting */
1550         for (i = 0; i < kcd->totlinehit; i++) {
1551                 KnifeLineHit *lh = kcd->linehits + i;
1552
1553                 lh->l = len_v2v2(lh->schit, s1) / len_v2v2(s2, s1);
1554         }
1555
1556         BLI_smallhash_release(&faces);
1557         BLI_smallhash_release(&kfes);
1558         BLI_smallhash_release(&kfvs);
1559         BLI_bvhtree_free(planetree);
1560         if (results)
1561                 MEM_freeN(results);
1562 }
1563
1564 static void knife_input_ray_segment(KnifeTool_OpData *kcd, const float mval[2], const float ofs,
1565                                     float r_origin[3], float r_origin_ofs[3])
1566 {
1567         bglMats mats;
1568
1569         bgl_get_mats(&mats);
1570
1571         /* unproject to find view ray */
1572         ED_view3d_unproject(&mats, r_origin,     mval[0], mval[1], 0.0f);
1573         ED_view3d_unproject(&mats, r_origin_ofs, mval[0], mval[1], ofs);
1574
1575         /* transform into object space */
1576         invert_m4_m4(kcd->ob->imat, kcd->ob->obmat); 
1577
1578         mul_m4_v3(kcd->ob->imat, r_origin);
1579         mul_m4_v3(kcd->ob->imat, r_origin_ofs);
1580 }
1581
1582 static BMFace *knife_find_closest_face(KnifeTool_OpData *kcd, float co[3], float cageco[3], bool *is_space)
1583 {
1584         BMFace *f;
1585         float dist = KMAXDIST;
1586         float origin[3];
1587         float origin_ofs[3];
1588         float ray[3];
1589
1590         /* unproject to find view ray */
1591         knife_input_ray_segment(kcd, kcd->curr.mval, 1.0f, origin, origin_ofs);
1592         sub_v3_v3v3(ray, origin_ofs, origin);
1593
1594         f = BKE_bmbvh_ray_cast(kcd->bmbvh, origin, ray, 0.0f, NULL, co, cageco);
1595
1596         if (is_space)
1597                 *is_space = !f;
1598
1599         if (!f) {
1600                 if (kcd->is_interactive) {
1601                         /* try to use backbuffer selection method if ray casting failed */
1602                         f = EDBM_face_find_nearest(&kcd->vc, &dist);
1603
1604                         /* cheat for now; just put in the origin instead
1605                          * of a true coordinate on the face.
1606                          * This just puts a point 1.0f infront of the view. */
1607                         add_v3_v3v3(co, origin, ray);
1608                 }
1609         }
1610
1611         return f;
1612 }
1613
1614 /* find the 2d screen space density of vertices within a radius.  used to scale snapping
1615  * distance for picking edges/verts.*/
1616 static int knife_sample_screen_density(KnifeTool_OpData *kcd, const float radius)
1617 {
1618         BMFace *f;
1619         bool is_space;
1620         float co[3], cageco[3], sco[2];
1621
1622         BLI_assert(kcd->is_interactive == true);
1623
1624         f = knife_find_closest_face(kcd, co, cageco, &is_space);
1625
1626         if (f && !is_space) {
1627                 const float radius_sq = radius * radius;
1628                 ListBase *lst;
1629                 Ref *ref;
1630                 float dis_sq;
1631                 int c = 0;
1632
1633                 knife_project_v2(kcd, cageco, sco);
1634
1635                 lst = knife_get_face_kedges(kcd, f);
1636                 for (ref = lst->first; ref; ref = ref->next) {
1637                         KnifeEdge *kfe = ref->ref;
1638                         int i;
1639
1640                         for (i = 0; i < 2; i++) {
1641                                 KnifeVert *kfv = i ? kfe->v2 : kfe->v1;
1642
1643                                 knife_project_v2(kcd, kfv->cageco, kfv->sco);
1644
1645                                 dis_sq = len_squared_v2v2(kfv->sco, sco);
1646                                 if (dis_sq < radius_sq) {
1647                                         if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1648                                                 if (ED_view3d_clipping_test(kcd->vc.rv3d, kfv->cageco, true) == 0) {
1649                                                         c++;
1650                                                 }
1651                                         }
1652                                         else {
1653                                                 c++;
1654                                         }
1655                                 }
1656                         }
1657                 }
1658
1659                 return c;
1660         }
1661
1662         return 0;
1663 }
1664
1665 /* returns snapping distance for edges/verts, scaled by the density of the
1666  * surrounding mesh (in screen space)*/
1667 static float knife_snap_size(KnifeTool_OpData *kcd, float maxsize)
1668 {
1669         float density;
1670
1671         if (kcd->is_interactive) {
1672                 density = (float)knife_sample_screen_density(kcd, maxsize * 2.0f);
1673         }
1674         else {
1675                 density = 1.0f;
1676         }
1677
1678         if (density < 1.0f)
1679                 density = 1.0f;
1680
1681         return min_ff(maxsize / (density * 0.5f), maxsize);
1682 }
1683
1684 /* p is closest point on edge to the mouse cursor */
1685 static KnifeEdge *knife_find_closest_edge(KnifeTool_OpData *kcd, float p[3], float cagep[3],
1686                                           BMFace **fptr, bool *is_space)
1687 {
1688         BMFace *f;
1689         float co[3], cageco[3], sco[2];
1690         float maxdist = knife_snap_size(kcd, kcd->ethresh);
1691
1692         if (kcd->ignore_vert_snapping)
1693                 maxdist *= 0.5f;
1694
1695         f = knife_find_closest_face(kcd, co, cageco, NULL);
1696         *is_space = !f;
1697
1698         kcd->curr.bmface = f;
1699
1700         if (f) {
1701                 const float maxdist_sq = maxdist * maxdist;
1702                 KnifeEdge *cure = NULL;
1703                 float cur_cagep[3];
1704                 ListBase *lst;
1705                 Ref *ref;
1706                 float dis_sq, curdis_sq = FLT_MAX;
1707
1708                 /* set p to co, in case we don't find anything, means a face cut */
1709                 copy_v3_v3(p, co);
1710                 copy_v3_v3(cagep, cageco);
1711
1712                 knife_project_v2(kcd, cageco, sco);
1713
1714                 /* look through all edges associated with this face */
1715                 lst = knife_get_face_kedges(kcd, f);
1716                 for (ref = lst->first; ref; ref = ref->next) {
1717                         KnifeEdge *kfe = ref->ref;
1718                         float test_cagep[3];
1719                         float lambda;
1720
1721                         /* project edge vertices into screen space */
1722                         knife_project_v2(kcd, kfe->v1->cageco, kfe->v1->sco);
1723                         knife_project_v2(kcd, kfe->v2->cageco, kfe->v2->sco);
1724
1725                         /* check if we're close enough and calculate 'lambda' */
1726                         if (kcd->is_angle_snapping) {
1727                         /* if snapping, check we're in bounds */
1728                                 float sco_snap[2];
1729                                 isect_line_line_v2_point(kfe->v1->sco, kfe->v2->sco, kcd->prev.mval, kcd->curr.mval, sco_snap);
1730                                 lambda = line_point_factor_v2(sco_snap, kfe->v1->sco, kfe->v2->sco);
1731
1732                                 /* be strict about angle-snapping within edge */
1733                                 if ((lambda < 0.0f - KNIFE_FLT_EPSBIG) || (lambda > 1.0f + KNIFE_FLT_EPSBIG)) {
1734                                         continue;
1735                                 }
1736
1737                                 dis_sq = len_squared_v2v2(sco, sco_snap);
1738                                 if (dis_sq < curdis_sq && dis_sq < maxdist_sq) {
1739                                         /* we already have 'lambda' */
1740                                 }
1741                                 else {
1742                                         continue;
1743                                 }
1744                         }
1745                         else {
1746                                 dis_sq = dist_squared_to_line_segment_v2(sco, kfe->v1->sco, kfe->v2->sco);
1747                                 if (dis_sq < curdis_sq && dis_sq < maxdist_sq) {
1748                                         lambda = line_point_factor_v2(sco, kfe->v1->sco, kfe->v2->sco);
1749                                 }
1750                                 else {
1751                                         continue;
1752                                 }
1753                         }
1754
1755                         /* now we have 'lambda' calculated (in screen-space) */
1756                         knife_interp_v3_v3v3(kcd, test_cagep, kfe->v1->cageco, kfe->v2->cageco, lambda);
1757
1758                         if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1759                                 /* check we're in the view */
1760                                 if (ED_view3d_clipping_test(kcd->vc.rv3d, test_cagep, true)) {
1761                                         continue;
1762                                 }
1763                         }
1764
1765                         cure = kfe;
1766                         curdis_sq = dis_sq;
1767                         copy_v3_v3(cur_cagep, test_cagep);
1768                 }
1769
1770                 if (fptr)
1771                         *fptr = f;
1772
1773                 if (cure) {
1774                         if (!kcd->ignore_edge_snapping || !(cure->e)) {
1775                                 KnifeVert *edgesnap = NULL;
1776
1777                                 if (kcd->snap_midpoints) {
1778                                         mid_v3_v3v3(p, cure->v1->co, cure->v2->co);
1779                                         mid_v3_v3v3(cagep, cure->v1->cageco, cure->v2->cageco);
1780                                 }
1781                                 else {
1782                                         float lambda = line_point_factor_v3(cur_cagep, cure->v1->cageco, cure->v2->cageco);
1783                                         copy_v3_v3(cagep, cur_cagep);
1784                                         interp_v3_v3v3(p, cure->v1->co, cure->v2->co, lambda);
1785                                 }
1786
1787                                 /* update mouse coordinates to the snapped-to edge's screen coordinates
1788                                  * this is important for angle snap, which uses the previous mouse position */
1789                                 edgesnap = new_knife_vert(kcd, p, cagep);
1790                                 kcd->curr.mval[0] = edgesnap->sco[0];
1791                                 kcd->curr.mval[1] = edgesnap->sco[1];
1792
1793                         }
1794                         else {
1795                                 return NULL;
1796                         }
1797                 }
1798
1799                 return cure;
1800         }
1801
1802         if (fptr)
1803                 *fptr = NULL;
1804
1805         return NULL;
1806 }
1807
1808 /* find a vertex near the mouse cursor, if it exists */
1809 static KnifeVert *knife_find_closest_vert(KnifeTool_OpData *kcd, float p[3], float cagep[3], BMFace **fptr,
1810                                           bool *is_space)
1811 {
1812         BMFace *f;
1813         float co[3], cageco[3], sco[2], maxdist = knife_snap_size(kcd, kcd->vthresh);
1814
1815         if (kcd->ignore_vert_snapping)
1816                 maxdist *= 0.5f;
1817
1818         f = knife_find_closest_face(kcd, co, cageco, is_space);
1819
1820         kcd->curr.bmface = f;
1821
1822         if (f) {
1823                 const float maxdist_sq = maxdist * maxdist;
1824                 ListBase *lst;
1825                 Ref *ref;
1826                 KnifeVert *curv = NULL;
1827                 float dis_sq, curdis_sq = FLT_MAX;
1828
1829                 /* set p to co, in case we don't find anything, means a face cut */
1830                 copy_v3_v3(p, co);
1831                 copy_v3_v3(cagep, cageco);
1832
1833                 knife_project_v2(kcd, cageco, sco);
1834
1835                 lst = knife_get_face_kedges(kcd, f);
1836                 for (ref = lst->first; ref; ref = ref->next) {
1837                         KnifeEdge *kfe = ref->ref;
1838                         int i;
1839
1840                         for (i = 0; i < 2; i++) {
1841                                 KnifeVert *kfv = i ? kfe->v2 : kfe->v1;
1842
1843                                 knife_project_v2(kcd, kfv->cageco, kfv->sco);
1844
1845                                 /* be strict about angle snapping, the vertex needs to be very close to the angle, or we ignore */
1846                                 if (kcd->is_angle_snapping) {
1847                                         if (dist_squared_to_line_segment_v2(kfv->sco, kcd->prev.mval, kcd->curr.mval) > KNIFE_FLT_EPSBIG) {
1848                                                 continue;
1849                                         }
1850                                 }
1851
1852                                 dis_sq = len_squared_v2v2(kfv->sco, sco);
1853                                 if (dis_sq < curdis_sq && dis_sq < maxdist_sq) {
1854                                         if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1855                                                 if (ED_view3d_clipping_test(kcd->vc.rv3d, kfv->cageco, true) == 0) {
1856                                                         curv = kfv;
1857                                                         curdis_sq = dis_sq;
1858                                                 }
1859                                         }
1860                                         else {
1861                                                 curv = kfv;
1862                                                 curdis_sq = dis_sq;
1863                                         }
1864                                 }
1865                         }
1866                 }
1867
1868                 if (!kcd->ignore_vert_snapping || !(curv && curv->v)) {
1869                         if (fptr)
1870                                 *fptr = f;
1871
1872                         if (curv) {
1873                                 copy_v3_v3(p, curv->co);
1874                                 copy_v3_v3(cagep, curv->cageco);
1875
1876                                 /* update mouse coordinates to the snapped-to vertex's screen coordinates
1877                                  * this is important for angle snap, which uses the previous mouse position */
1878                                 kcd->curr.mval[0] = curv->sco[0];
1879                                 kcd->curr.mval[1] = curv->sco[1];
1880                         }
1881
1882                         return curv;
1883                 }
1884                 else {
1885                         if (fptr)
1886                                 *fptr = f;
1887
1888                         return NULL;
1889                 }
1890         }
1891
1892         if (fptr)
1893                 *fptr = NULL;
1894
1895         return NULL;
1896 }
1897
1898 /* update both kcd->curr.mval and kcd->mval to snap to required angle */
1899 static bool knife_snap_angle(KnifeTool_OpData *kcd)
1900 {
1901         float dx, dy;
1902         float w, abs_tan;
1903
1904         dx = kcd->curr.mval[0] - kcd->prev.mval[0];
1905         dy = kcd->curr.mval[1] - kcd->prev.mval[1];
1906         if (dx == 0.0f && dy == 0.0f)
1907                 return false;
1908
1909         if (dx == 0.0f) {
1910                 kcd->angle_snapping = ANGLE_90;
1911                 kcd->curr.mval[0] = kcd->prev.mval[0];
1912         }
1913
1914         w = dy / dx;
1915         abs_tan = fabsf(w);
1916         if (abs_tan <= 0.4142f) { /* tan(22.5 degrees) = 0.4142 */
1917                 kcd->angle_snapping = ANGLE_0;
1918                 kcd->curr.mval[1] = kcd->prev.mval[1];
1919         }
1920         else if (abs_tan < 2.4142f) { /* tan(67.5 degrees) = 2.4142 */
1921                 if (w > 0) {
1922                         kcd->angle_snapping = ANGLE_45;
1923                         kcd->curr.mval[1] = kcd->prev.mval[1] + dx;
1924                 }
1925                 else {
1926                         kcd->angle_snapping = ANGLE_135;
1927                         kcd->curr.mval[1] = kcd->prev.mval[1] - dx;
1928                 }
1929         }
1930         else {
1931                 kcd->angle_snapping = ANGLE_90;
1932                 kcd->curr.mval[0] = kcd->prev.mval[0];
1933         }
1934
1935         copy_v2_v2(kcd->mval, kcd->curr.mval);
1936
1937         return true;
1938 }
1939
1940 /* update active knife edge/vert pointers */
1941 static int knife_update_active(KnifeTool_OpData *kcd)
1942 {
1943         knife_pos_data_clear(&kcd->curr);
1944         copy_v2_v2(kcd->curr.mval, kcd->mval);
1945
1946         /* view matrix may have changed, reproject */
1947         knife_project_v2(kcd, kcd->prev.cage, kcd->prev.mval);
1948
1949         if (kcd->angle_snapping != ANGLE_FREE && kcd->mode == MODE_DRAGGING) {
1950                 kcd->is_angle_snapping = knife_snap_angle(kcd);
1951         }
1952         else {
1953                 kcd->is_angle_snapping = false;
1954         }
1955
1956         kcd->curr.vert = knife_find_closest_vert(kcd, kcd->curr.co, kcd->curr.cage, &kcd->curr.bmface, &kcd->curr.is_space);
1957
1958         if (!kcd->curr.vert &&
1959             /* no edge snapping while dragging (edges are too sticky when cuts are immediate) */
1960             !kcd->is_drag_hold)
1961         {
1962                 kcd->curr.edge = knife_find_closest_edge(kcd, kcd->curr.co, kcd->curr.cage,
1963                                                          &kcd->curr.bmface, &kcd->curr.is_space);
1964         }
1965
1966         /* if no hits are found this would normally default to (0, 0, 0) so instead
1967          * get a point at the mouse ray closest to the previous point.
1968          * Note that drawing lines in `free-space` isn't properly supported
1969          * but theres no guarantee (0, 0, 0) has any geometry either - campbell */
1970         if (kcd->curr.vert == NULL && kcd->curr.edge == NULL && kcd->curr.bmface == NULL) {
1971                 float origin[3];
1972                 float origin_ofs[3];
1973
1974                 knife_input_ray_segment(kcd, kcd->curr.mval, 1.0f, origin, origin_ofs);
1975
1976                 if (!isect_line_plane_v3(kcd->curr.cage, origin, origin_ofs, kcd->prev.cage, kcd->proj_zaxis)) {
1977                         copy_v3_v3(kcd->curr.cage, kcd->prev.cage);
1978
1979                         /* should never fail! */
1980                         BLI_assert(0);
1981                 }
1982         }
1983
1984         if (kcd->mode == MODE_DRAGGING) {
1985                 knife_find_line_hits(kcd);
1986         }
1987         return 1;
1988 }
1989
1990 /* sort list of kverts by fraction along edge e */
1991 static void sort_by_frac_along(ListBase *lst, BMEdge *e)
1992 {
1993         /* note, since we know the point is along the edge, sort from distance to v1co */
1994         const float *v1co = e->v1->co;
1995         Ref *cur = NULL, *prev = NULL, *next = NULL;
1996
1997         if (lst->first == lst->last)
1998                 return;
1999
2000         for (cur = ((Ref *)lst->first)->next; cur; cur = next) {
2001                 KnifeVert *vcur = cur->ref;
2002                 const float vcur_fac_sq = len_squared_v3v3(v1co, vcur->co);
2003
2004                 next = cur->next;
2005                 prev = cur->prev;
2006
2007                 BLI_remlink(lst, cur);
2008
2009                 while (prev) {
2010                         KnifeVert *vprev = prev->ref;
2011                         if (len_squared_v3v3(v1co, vprev->co) <= vcur_fac_sq)
2012                                 break;
2013                         prev = prev->prev;
2014                 }
2015
2016                 BLI_insertlinkafter(lst, prev, cur);
2017         }
2018 }
2019
2020 /* The chain so far goes from an instantiated vertex to kfv (some may be reversed).
2021  * If possible, complete the chain to another instantiated vertex and return 1, else return 0.
2022  * The visited hash says which KnifeVert's have already been tried, not including kfv. */
2023 static bool find_chain_search(KnifeTool_OpData *kcd, KnifeVert *kfv, ListBase *fedges, SmallHash *visited,
2024                               ListBase *chain)
2025 {
2026         Ref *r;
2027         KnifeEdge *kfe;
2028         KnifeVert *kfv_other;
2029
2030         if (kfv->v)
2031                 return true;
2032
2033         BLI_smallhash_insert(visited, (uintptr_t)kfv, NULL);
2034         /* Try all possible next edges. Could either go through fedges
2035          * (all the KnifeEdges for the face being cut) or could go through
2036          * kve->edges and restrict to cutting face and uninstantiated edges.
2037          * Not clear which is better. Let's do the first. */
2038         for (r = fedges->first; r; r = r->next) {
2039                 kfe = r->ref;
2040                 kfv_other = NULL;
2041                 if (kfe->v1 == kfv)
2042                         kfv_other = kfe->v2;
2043                 else if (kfe->v2 == kfv)
2044                         kfv_other = kfe->v1;
2045                 if (kfv_other && !BLI_smallhash_haskey(visited, (uintptr_t)kfv_other)) {
2046                         knife_append_list(kcd, chain, kfe);
2047                         if (find_chain_search(kcd, kfv_other, fedges, visited, chain))
2048                                 return true;
2049                         BLI_remlink(chain, chain->last);
2050                 }
2051         }
2052         return false;
2053 }
2054
2055 static ListBase *find_chain_from_vertex(KnifeTool_OpData *kcd, KnifeEdge *kfe, BMVert *v, ListBase *fedges)
2056 {
2057         SmallHash visited_, *visited = &visited_;
2058         ListBase *ans;
2059         bool found;
2060
2061         ans = knife_empty_list(kcd);
2062         knife_append_list(kcd, ans, kfe);
2063         found = false;
2064         BLI_smallhash_init(visited);
2065         if (kfe->v1->v == v) {
2066                 BLI_smallhash_insert(visited, (uintptr_t)(kfe->v1), NULL);
2067                 found = find_chain_search(kcd, kfe->v2, fedges, visited, ans);
2068         }
2069         else {
2070                 BLI_assert(kfe->v2->v == v);
2071                 BLI_smallhash_insert(visited, (uintptr_t)(kfe->v2), NULL);
2072                 found = find_chain_search(kcd, kfe->v1, fedges, visited, ans);
2073         }
2074
2075         BLI_smallhash_release(visited);
2076
2077         if (found)
2078                 return ans;
2079         else
2080                 return NULL;
2081 }
2082
2083 /* Find a chain in fedges from one instantiated vertex to another.
2084  * Remove the edges in the chain from fedges and return a separate list of the chain. */
2085 static ListBase *find_chain(KnifeTool_OpData *kcd, ListBase *fedges)
2086 {
2087         Ref *r, *ref;
2088         KnifeEdge *kfe;
2089         BMVert *v1, *v2;
2090         ListBase *ans;
2091
2092         ans = NULL;
2093
2094         for (r = fedges->first; r; r = r->next) {
2095                 kfe = r->ref;
2096                 v1 = kfe->v1->v;
2097                 v2 = kfe->v2->v;
2098                 if (v1 && v2) {
2099                         ans = knife_empty_list(kcd);
2100                         knife_append_list(kcd, ans, kfe);
2101                         break;
2102                 }
2103                 if (v1)
2104                         ans = find_chain_from_vertex(kcd, kfe, v1, fedges);
2105                 else if (v2)
2106                         ans = find_chain_from_vertex(kcd, kfe, v2, fedges);
2107                 if (ans)
2108                         break;
2109         }
2110         if (ans) {
2111                 BLI_assert(BLI_listbase_count(ans) > 0);
2112                 for (r = ans->first; r; r = r->next) {
2113                         ref = find_ref(fedges, r->ref);
2114                         BLI_assert(ref != NULL);
2115                         BLI_remlink(fedges, ref);
2116                 }
2117         }
2118         return ans;
2119 }
2120
2121 /* The hole so far goes from kfvfirst to kfv (some may be reversed).
2122  * If possible, complete the hole back to kfvfirst and return 1, else return 0.
2123  * The visited hash says which KnifeVert's have already been tried, not including kfv or kfvfirst. */
2124 static bool find_hole_search(KnifeTool_OpData *kcd, KnifeVert *kfvfirst, KnifeVert *kfv, ListBase *fedges,
2125                              SmallHash *visited, ListBase *hole)
2126 {
2127         Ref *r;
2128         KnifeEdge *kfe, *kfelast;
2129         KnifeVert *kfv_other;
2130
2131         if (kfv == kfvfirst)
2132                 return true;
2133
2134         BLI_smallhash_insert(visited, (uintptr_t)kfv, NULL);
2135         kfelast = ((Ref *)hole->last)->ref;
2136         for (r = fedges->first; r; r = r->next) {
2137                 kfe = r->ref;
2138                 if (kfe == kfelast)
2139                         continue;
2140                 if (kfe->v1->v || kfe->v2->v)
2141                         continue;
2142                 kfv_other = NULL;
2143                 if (kfe->v1 == kfv)
2144                         kfv_other = kfe->v2;
2145                 else if (kfe->v2 == kfv)
2146                         kfv_other = kfe->v1;
2147                 if (kfv_other && !BLI_smallhash_haskey(visited, (uintptr_t)kfv_other)) {
2148                         knife_append_list(kcd, hole, kfe);
2149                         if (find_hole_search(kcd, kfvfirst, kfv_other, fedges, visited, hole))
2150                                 return true;
2151                         BLI_remlink(hole, hole->last);
2152                 }
2153         }
2154         return false;
2155 }
2156
2157 /* Find a hole (simple cycle with no instantiated vertices).
2158  * Remove the edges in the cycle from fedges and return a separate list of the cycle */
2159 static ListBase *find_hole(KnifeTool_OpData *kcd, ListBase *fedges)
2160 {
2161         ListBase *ans;
2162         Ref *r, *ref;
2163         KnifeEdge *kfe;
2164         SmallHash visited_, *visited = &visited_;
2165         bool found;
2166
2167         ans = NULL;
2168         found = false;
2169
2170         for (r = fedges->first; r && !found; r = r->next) {
2171                 kfe = r->ref;
2172                 if (kfe->v1->v || kfe->v2->v || kfe->v1 == kfe->v2)
2173                         continue;
2174
2175                 BLI_smallhash_init(visited);
2176                 ans = knife_empty_list(kcd);
2177                 knife_append_list(kcd, ans, kfe);
2178
2179                 found = find_hole_search(kcd, kfe->v1, kfe->v2, fedges, visited, ans);
2180
2181                 BLI_smallhash_release(visited);
2182         }
2183
2184         if (found) {
2185                 for (r = ans->first; r; r = r->next) {
2186                         kfe = r->ref;
2187                         ref = find_ref(fedges, r->ref);
2188                         if (ref)
2189                                 BLI_remlink(fedges, ref);
2190                 }
2191                 return ans;
2192         }
2193         else {
2194                 return NULL;
2195         }
2196 }
2197
2198 /* Try to find "nice" diagonals - short, and far apart from each other.
2199  * If found, return true and make a 'main chain' going across f which uses
2200  * the two diagonals and one part of the hole, and a 'side chain' that
2201  * completes the hole. */
2202 static bool find_hole_chains(KnifeTool_OpData *kcd, ListBase *hole, BMFace *f, ListBase **mainchain,
2203                              ListBase **sidechain)
2204 {
2205         float (*fco)[2], (*hco)[2];
2206         BMVert **fv;
2207         KnifeVert **hv;
2208         KnifeEdge **he;
2209         Ref *r;
2210         KnifeVert *kfv, *kfvother;
2211         KnifeEdge *kfe;
2212         ListBase *chain;
2213         BMVert *v;
2214         BMIter iter;
2215         int nh, nf, i, j, k, m, ax, ay, sep = 0 /* Quite warnings */, bestsep;
2216         int besti[2], bestj[2];
2217         float dist_sq, dist_best_sq;
2218
2219         nh = BLI_listbase_count(hole);
2220         nf = f->len;
2221         if (nh < 2 || nf < 3)
2222                 return false;
2223
2224         /* Gather 2d projections of hole and face vertex coordinates.
2225          * Use best-axis projection - not completely accurate, maybe revisit */
2226         axis_dominant_v3(&ax, &ay, f->no);
2227         hco = BLI_memarena_alloc(kcd->arena, nh * sizeof(float[2]));
2228         fco = BLI_memarena_alloc(kcd->arena, nf * sizeof(float[2]));
2229         hv = BLI_memarena_alloc(kcd->arena, nh * sizeof(KnifeVert *));
2230         fv = BLI_memarena_alloc(kcd->arena, nf * sizeof(BMVert *));
2231         he = BLI_memarena_alloc(kcd->arena, nh * sizeof(KnifeEdge *));
2232
2233         i = 0;
2234         kfv = NULL;
2235         kfvother = NULL;
2236         for (r = hole->first; r; r = r->next) {
2237                 kfe = r->ref;
2238                 he[i] = kfe;
2239                 if (kfvother == NULL) {
2240                         kfv = kfe->v1;
2241                 }
2242                 else {
2243                         kfv = kfvother;
2244                         BLI_assert(kfv == kfe->v1 || kfv == kfe->v2);
2245                 }
2246                 hco[i][0] = kfv->co[ax];
2247                 hco[i][1] = kfv->co[ay];
2248                 hv[i] = kfv;
2249                 kfvother = (kfe->v1 == kfv) ? kfe->v2 : kfe->v1;
2250                 i++;
2251         }
2252
2253         j = 0;
2254         BM_ITER_ELEM (v, &iter, f, BM_VERTS_OF_FACE) {
2255                 fco[j][0] = v->co[ax];
2256                 fco[j][1] = v->co[ay];
2257                 fv[j] = v;
2258                 j++;
2259         }
2260
2261         /* For first diagonal  (m == 0), want shortest length.
2262          * For second diagonal (m == 1), want max separation of index of hole
2263          * vertex from the hole vertex used in the first diagonal, and from there
2264          * want the one with shortest length not to the same vertex as the first diagonal. */
2265         for (m = 0; m < 2; m++) {
2266                 besti[m] = -1;
2267                 bestj[m] = -1;
2268                 dist_best_sq = FLT_MAX;
2269                 bestsep = 0;
2270                 for (i = 0; i < nh; i++) {
2271                         if (m == 1) {
2272                                 if (i == besti[0])
2273                                         continue;
2274                                 sep = (i + nh - besti[0]) % nh;
2275                                 sep = MIN2(sep, nh - sep);
2276                                 if (sep < bestsep)
2277                                         continue;
2278                                 dist_best_sq = FLT_MAX;
2279                         }
2280                         for (j = 0; j < nf; j++) {
2281                                 bool ok;
2282
2283                                 if (m == 1 && j == bestj[0])
2284                                         continue;
2285                                 dist_sq = len_squared_v2v2(hco[i], fco[j]);
2286                                 if (dist_sq > dist_best_sq)
2287                                         continue;
2288
2289                                 ok = true;
2290                                 for (k = 0; k < nh && ok; k++) {
2291                                         if (k == i || (k + 1) % nh == i)
2292                                                 continue;
2293                                         if (isect_line_line_v2(hco[i], fco[j], hco[k], hco[(k + 1) % nh]))
2294                                                 ok = false;
2295                                 }
2296                                 if (!ok)
2297                                         continue;
2298                                 for (k = 0; k < nf && ok; k++) {
2299                                         if (k == j || (k + 1) % nf == j)
2300                                                 continue;
2301                                         if (isect_line_line_v2(hco[i], fco[j], fco[k], fco[(k + 1) % nf]))
2302                                                 ok = false;
2303                                 }
2304                                 if (ok) {
2305                                         besti[m] = i;
2306                                         bestj[m] = j;
2307                                         if (m == 1)
2308                                                 bestsep = sep;
2309                                         dist_best_sq = dist_sq;
2310                                 }
2311                         }
2312                 }
2313         }
2314
2315         if (besti[0] != -1 && besti[1] != -1) {
2316                 BLI_assert(besti[0] != besti[1] && bestj[0] != bestj[1]);
2317                 kfe = new_knife_edge(kcd);
2318                 kfe->v1 = get_bm_knife_vert(kcd, fv[bestj[0]]);
2319                 kfe->v2 = hv[besti[0]];
2320                 chain = knife_empty_list(kcd);
2321                 knife_append_list(kcd, chain, kfe);
2322                 for (i = besti[0]; i != besti[1]; i = (i + 1) % nh) {
2323                         knife_append_list(kcd, chain, he[i]);
2324                 }
2325                 kfe = new_knife_edge(kcd);
2326                 kfe->v1 = hv[besti[1]];
2327                 kfe->v2 = get_bm_knife_vert(kcd, fv[bestj[1]]);
2328                 knife_append_list(kcd, chain, kfe);
2329                 *mainchain = chain;
2330
2331                 chain = knife_empty_list(kcd);
2332                 for (i = besti[1]; i != besti[0]; i = (i + 1) % nh) {
2333                         knife_append_list(kcd, chain, he[i]);
2334                 }
2335                 *sidechain = chain;
2336
2337                 return true;
2338         }
2339         else {
2340                 return false;
2341         }
2342 }
2343
2344 static bool knife_verts_edge_in_face(KnifeVert *v1, KnifeVert *v2, BMFace *f)
2345 {
2346         bool v1_inside, v2_inside;
2347         bool v1_inface, v2_inface;
2348
2349         if (!f || !v1 || !v2)
2350                 return false;
2351
2352         /* find out if v1 and v2, if set, are part of the face */
2353         v1_inface = v1->v ? BM_vert_in_face(f, v1->v) : false;
2354         v2_inface = v2->v ? BM_vert_in_face(f, v2->v) : false;
2355
2356         /* BM_face_point_inside_test uses best-axis projection so this isn't most accurate test... */
2357         v1_inside = v1_inface ? false : BM_face_point_inside_test(f, v1->co);
2358         v2_inside = v2_inface ? false : BM_face_point_inside_test(f, v2->co);
2359         if ((v1_inface && v2_inside) ||
2360             (v2_inface && v1_inside) ||
2361             (v1_inside && v2_inside))
2362         {
2363                 return true;
2364         }
2365
2366         if (v1_inface && v2_inface) {
2367                 float mid[3];
2368                 /* Can have case where v1 and v2 are on shared chain between two faces.
2369                  * BM_face_splits_check_legal does visibility and self-intersection tests,
2370                  * but it is expensive and maybe a bit buggy, so use a simple
2371                  * "is the midpoint in the face" test */
2372                 mid_v3_v3v3(mid, v1->co, v2->co);
2373                 return BM_face_point_inside_test(f, mid);
2374         }
2375         return false;
2376 }
2377
2378 static bool knife_edge_in_face(KnifeEdge *kfe, BMFace *f)
2379 {
2380         return knife_verts_edge_in_face(kfe->v1, kfe->v2, f);
2381 }
2382
2383 /* Split face f with KnifeEdges on chain.  f remains as one side, the face formed is put in *newface.
2384  * The new face will be on the left side of the chain as viewed from the normal-out side of f. */
2385 static void knife_make_chain_cut(KnifeTool_OpData *kcd, BMFace *f, ListBase *chain, BMFace **r_f_new)
2386 {
2387         BMesh *bm = kcd->em->bm;
2388         KnifeEdge *kfe, *kfelast;
2389         BMVert *v1, *v2;
2390         BMLoop *l_v1, *l_v2;
2391         BMFace *f_new;
2392         Ref *ref;
2393         KnifeVert *kfv, *kfvprev;
2394         BMLoop *l_new, *l_iter;
2395         int i;
2396         int nco = BLI_listbase_count(chain) - 1;
2397         float (*cos)[3] = BLI_array_alloca(cos, nco);
2398         KnifeVert **kverts = BLI_array_alloca(kverts, nco);
2399
2400         kfe = ((Ref *)chain->first)->ref;
2401         v1 = kfe->v1->v ? kfe->v1->v : kfe->v2->v;
2402         kfelast = ((Ref *)chain->last)->ref;
2403         v2 = kfelast->v2->v ? kfelast->v2->v : kfelast->v1->v;
2404         BLI_assert(v1 != NULL && v2 != NULL);
2405         kfvprev = kfe->v1->v == v1 ? kfe->v1 : kfe->v2;
2406         for (ref = chain->first, i = 0; i < nco && ref != chain->last; ref = ref->next, i++) {
2407                 kfe = ref->ref;
2408                 BLI_assert(kfvprev == kfe->v1 || kfvprev == kfe->v2);
2409                 kfv = kfe->v1 == kfvprev ? kfe->v2 : kfe->v1;
2410                 copy_v3_v3(cos[i], kfv->co);
2411                 kverts[i] = kfv;
2412                 kfvprev = kfv;
2413         }
2414         BLI_assert(i == nco);
2415         l_new = NULL;
2416
2417         if ((l_v1 = BM_face_vert_share_loop(f, v1)) &&
2418             (l_v2 = BM_face_vert_share_loop(f, v2)))
2419         {
2420                 if (nco == 0) {
2421                         /* Want to prevent creating two-sided polygons */
2422                         if (v1 == v2 || BM_edge_exists(v1, v2)) {
2423                                 f_new = NULL;
2424                         }
2425                         else {
2426                                 f_new = BM_face_split(bm, f, l_v1, l_v2, &l_new, NULL, true);
2427                         }
2428                 }
2429                 else {
2430                         f_new = BM_face_split_n(bm, f, l_v1, l_v2, cos, nco, &l_new, NULL);
2431                         if (f_new) {
2432                                 /* Now go through lnew chain matching up chain kv's and assign real v's to them */
2433                                 for (l_iter = l_new->next, i = 0; i < nco; l_iter = l_iter->next, i++) {
2434                                         BLI_assert(equals_v3v3(cos[i], l_iter->v->co));
2435                                         if (kcd->select_result) {
2436                                                 BM_edge_select_set(bm, l_iter->e, true);
2437                                         }
2438                                         kverts[i]->v = l_iter->v;
2439                                 }
2440                         }
2441                 }
2442         }
2443         else {
2444                 f_new = NULL;
2445         }
2446
2447         /* the select chain above doesnt account for the first loop */
2448         if (kcd->select_result) {
2449                 if (l_new) {
2450                         BM_edge_select_set(bm, l_new->e, true);
2451                 }
2452         }
2453         else if (f_new) {
2454                 BM_elem_select_copy(bm, bm, f_new, f);
2455         }
2456
2457         *r_f_new = f_new;
2458 }
2459
2460 static void knife_make_face_cuts(KnifeTool_OpData *kcd, BMFace *f, ListBase *kfedges)
2461 {
2462         BMesh *bm = kcd->em->bm;
2463         KnifeEdge *kfe;
2464         BMFace *fnew, *fnew2, *fhole;
2465         ListBase *chain, *hole, *sidechain;
2466         Ref *ref, *refnext;
2467         int count, oldcount;
2468
2469         oldcount = BLI_listbase_count(kfedges);
2470         while ((chain = find_chain(kcd, kfedges)) != NULL) {
2471                 ListBase fnew_kfedges;
2472                 knife_make_chain_cut(kcd, f, chain, &fnew);
2473                 if (!fnew) {
2474                         return;
2475                 }
2476
2477                 /* Move kfedges to fnew_kfedges if they are now in fnew.
2478                  * The chain edges were removed already */
2479                 BLI_listbase_clear(&fnew_kfedges);
2480                 for (ref = kfedges->first; ref; ref = refnext) {
2481                         kfe = ref->ref;
2482                         refnext = ref->next;
2483                         if (knife_edge_in_face(kfe, fnew)) {
2484                                 BLI_remlink(kfedges, ref);
2485                                 kfe->basef = fnew;
2486                                 BLI_addtail(&fnew_kfedges, ref);
2487                         }
2488                         else if (!knife_edge_in_face(kfe, f)) {
2489                                 /* Concave ngon's - this edge might not be in either faces, T41730 */
2490                                 BLI_remlink(kfedges, ref);
2491                         }
2492                 }
2493                 if (fnew_kfedges.first)
2494                         knife_make_face_cuts(kcd, fnew, &fnew_kfedges);
2495
2496                 /* find_chain should always remove edges if it returns true,
2497                  * but guard against infinite loop anyway */
2498                 count = BLI_listbase_count(kfedges);
2499                 if (count >= oldcount) {
2500                         BLI_assert(!"knife find_chain infinite loop");
2501                         return;
2502                 }
2503                 oldcount = count;
2504         }
2505
2506         while ((hole = find_hole(kcd, kfedges)) != NULL) {
2507                 if (find_hole_chains(kcd, hole, f, &chain, &sidechain)) {
2508                         ListBase fnew_kfedges, fnew2_kfedges;
2509
2510                         /* chain goes across f and sidechain comes back
2511                          * from the second last vertex to the second vertex.
2512                          */
2513                         knife_make_chain_cut(kcd, f, chain, &fnew);
2514                         if (!fnew) {
2515                                 BLI_assert(!"knife failed hole cut");
2516                                 return;
2517                         }
2518                         kfe = ((Ref *)sidechain->first)->ref;
2519                         if (knife_edge_in_face(kfe, f)) {
2520                                 knife_make_chain_cut(kcd, f, sidechain, &fnew2);
2521                                 if (fnew2 == NULL) {
2522                                         return;
2523                                 }
2524                                 fhole = f;
2525                         }
2526                         else if (knife_edge_in_face(kfe, fnew)) {
2527                                 knife_make_chain_cut(kcd, fnew, sidechain, &fnew2);
2528                                 if (fnew2 == NULL) {
2529                                         return;
2530                                 }
2531                                 fhole = fnew2;
2532                         }
2533                         else {
2534                                 /* shouldn't happen except in funny edge cases */
2535                                 return;
2536                         }
2537                         BM_face_kill(bm, fhole);
2538                         /* Move kfedges to either fnew or fnew2 if appropriate.
2539                          * The hole edges were removed already */
2540                         BLI_listbase_clear(&fnew_kfedges);
2541                         BLI_listbase_clear(&fnew2_kfedges);
2542                         for (ref = kfedges->first; ref; ref = refnext) {
2543                                 kfe = ref->ref;
2544                                 refnext = ref->next;
2545                                 if (knife_edge_in_face(kfe, fnew)) {
2546                                         BLI_remlink(kfedges, ref);
2547                                         kfe->basef = fnew;
2548                                         BLI_addtail(&fnew_kfedges, ref);
2549                                 }
2550                                 else if (knife_edge_in_face(kfe, fnew2)) {
2551                                         BLI_remlink(kfedges, ref);
2552                                         kfe->basef = fnew2;
2553                                         BLI_addtail(&fnew2_kfedges, ref);
2554                                 }
2555                         }
2556                         /* We'll skip knife edges that are in the newly formed hole.
2557                          * (Maybe we shouldn't have made a hole in the first place?) */
2558                         if (fnew != fhole && fnew_kfedges.first)
2559                                 knife_make_face_cuts(kcd, fnew, &fnew_kfedges);
2560                         if (fnew2 != fhole && fnew2_kfedges.first)
2561                                 knife_make_face_cuts(kcd, fnew2, &fnew2_kfedges);
2562                         if (f == fhole)
2563                                 break;
2564                         /* find_hole should always remove edges if it returns true,
2565                          * but guard against infinite loop anyway */
2566                         count = BLI_listbase_count(kfedges);
2567                         if (count >= oldcount) {
2568                                 BLI_assert(!"knife find_hole infinite loop");
2569                                 return;
2570                         }
2571                         oldcount = count;
2572                 }
2573         }
2574 }
2575
2576 /* Use the network of KnifeEdges and KnifeVerts accumulated to make real BMVerts and BMEdedges */
2577 static void knife_make_cuts(KnifeTool_OpData *kcd)
2578 {
2579         BMesh *bm = kcd->em->bm;
2580         KnifeEdge *kfe;
2581         KnifeVert *kfv;
2582         BMFace *f;
2583         BMEdge *e, *enew;
2584         ListBase *lst;
2585         Ref *ref;
2586         float pct;
2587         SmallHashIter hiter;
2588         BLI_mempool_iter iter;
2589         SmallHash fhash_, *fhash = &fhash_;
2590         SmallHash ehash_, *ehash = &ehash_;
2591
2592         BLI_smallhash_init(fhash);
2593         BLI_smallhash_init(ehash);
2594
2595         /* put list of cutting edges for a face into fhash, keyed by face */
2596         BLI_mempool_iternew(kcd->kedges, &iter);
2597         for (kfe = BLI_mempool_iterstep(&iter); kfe; kfe = BLI_mempool_iterstep(&iter)) {
2598                 f = kfe->basef;
2599                 if (!f || kfe->e)
2600                         continue;
2601                 lst = BLI_smallhash_lookup(fhash, (uintptr_t)f);
2602                 if (!lst) {
2603                         lst = knife_empty_list(kcd);
2604                         BLI_smallhash_insert(fhash, (uintptr_t)f, lst);
2605                 }
2606                 knife_append_list(kcd, lst, kfe);
2607         }
2608
2609         /* put list of splitting vertices for an edge into ehash, keyed by edge */
2610         BLI_mempool_iternew(kcd->kverts, &iter);
2611         for (kfv = BLI_mempool_iterstep(&iter); kfv; kfv = BLI_mempool_iterstep(&iter)) {
2612                 if (kfv->v)
2613                         continue;  /* already have a BMVert */
2614                 for (ref = kfv->edges.first; ref; ref = ref->next) {
2615                         kfe = ref->ref;
2616                         e = kfe->e;
2617                         if (!e)
2618                                 continue;
2619                         lst = BLI_smallhash_lookup(ehash, (uintptr_t)e);
2620                         if (!lst) {
2621                                 lst = knife_empty_list(kcd);
2622                                 BLI_smallhash_insert(ehash, (uintptr_t)e, lst);
2623                         }
2624                         /* there can be more than one kfe in kfv's list with same e */
2625                         if (!find_ref(lst, kfv))
2626                                 knife_append_list(kcd, lst, kfv);
2627                 }
2628         }
2629
2630         /* split bmesh edges where needed */
2631         for (lst = BLI_smallhash_iternew(ehash, &hiter, (uintptr_t *)&e); lst;
2632              lst = BLI_smallhash_iternext(&hiter, (uintptr_t *)&e))
2633         {
2634                 sort_by_frac_along(lst, e);
2635                 for (ref = lst->first; ref; ref = ref->next) {
2636                         kfv = ref->ref;
2637                         pct = line_point_factor_v3(kfv->co, e->v1->co, e->v2->co);
2638                         kfv->v = BM_edge_split(bm, e, e->v1, &enew, pct);
2639                 }
2640         }
2641
2642         if (kcd->only_select) {
2643                 EDBM_flag_disable_all(kcd->em, BM_ELEM_SELECT);
2644         }
2645
2646         /* do cuts for each face */
2647         for (lst = BLI_smallhash_iternew(fhash, &hiter, (uintptr_t *)&f); lst;
2648              lst = BLI_smallhash_iternext(&hiter, (uintptr_t *)&f))
2649         {
2650                 knife_make_face_cuts(kcd, f, lst);
2651         }
2652
2653         BLI_smallhash_release(fhash);
2654         BLI_smallhash_release(ehash);
2655 }
2656
2657 /* called on tool confirmation */
2658 static void knifetool_finish_ex(KnifeTool_OpData *kcd)
2659 {
2660         knife_make_cuts(kcd);
2661
2662         EDBM_selectmode_flush(kcd->em);
2663         EDBM_mesh_normals_update(kcd->em);
2664         EDBM_update_generic(kcd->em, true, true);
2665 }
2666 static void knifetool_finish(wmOperator *op)
2667 {
2668         KnifeTool_OpData *kcd = op->customdata;
2669         knifetool_finish_ex(kcd);
2670 }
2671
2672 static void knife_recalc_projmat(KnifeTool_OpData *kcd)
2673 {
2674         invert_m4_m4(kcd->ob->imat, kcd->ob->obmat);
2675         ED_view3d_ob_project_mat_get(kcd->ar->regiondata, kcd->ob, kcd->projmat);
2676         invert_m4_m4(kcd->projmat_inv, kcd->projmat);
2677
2678         copy_v3_v3(kcd->proj_zaxis, kcd->vc.rv3d->viewinv[2]);
2679         mul_mat3_m4_v3(kcd->ob->imat, kcd->proj_zaxis);
2680         normalize_v3(kcd->proj_zaxis);
2681
2682         kcd->is_ortho = ED_view3d_clip_range_get(kcd->vc.v3d, kcd->vc.rv3d,
2683                                                  &kcd->clipsta, &kcd->clipend, true);
2684 }
2685
2686 /* called when modal loop selection is done... */
2687 static void knifetool_exit_ex(bContext *C, KnifeTool_OpData *kcd)
2688 {
2689         if (!kcd)
2690                 return;
2691
2692         if (kcd->is_interactive) {
2693                 WM_cursor_modal_restore(CTX_wm_window(C));
2694
2695                 /* deactivate the extra drawing stuff in 3D-View */
2696                 ED_region_draw_cb_exit(kcd->ar->type, kcd->draw_handle);
2697         }
2698
2699         /* free the custom data */
2700         BLI_mempool_destroy(kcd->refs);
2701         BLI_mempool_destroy(kcd->kverts);
2702         BLI_mempool_destroy(kcd->kedges);
2703
2704         BLI_ghash_free(kcd->origedgemap, NULL, NULL);
2705         BLI_ghash_free(kcd->origvertmap, NULL, NULL);
2706         BLI_ghash_free(kcd->kedgefacemap, NULL, NULL);
2707         BLI_ghash_free(kcd->facetrimap, NULL, NULL);
2708
2709         BKE_bmbvh_free(kcd->bmbvh);
2710         BLI_memarena_free(kcd->arena);
2711
2712         /* tag for redraw */
2713         ED_region_tag_redraw(kcd->ar);
2714
2715         if (kcd->cagecos)
2716                 MEM_freeN((void *)kcd->cagecos);
2717
2718         if (kcd->linehits)
2719                 MEM_freeN(kcd->linehits);
2720
2721         /* destroy kcd itself */
2722         MEM_freeN(kcd);
2723 }
2724 static void knifetool_exit(bContext *C, wmOperator *op)
2725 {
2726         KnifeTool_OpData *kcd = op->customdata;
2727         knifetool_exit_ex(C, kcd);
2728         op->customdata = NULL;
2729 }
2730
2731 static void knifetool_update_mval(KnifeTool_OpData *kcd, const float mval[2])
2732 {
2733         knife_recalc_projmat(kcd);
2734         copy_v2_v2(kcd->mval, mval);
2735
2736         if (knife_update_active(kcd)) {
2737                 ED_region_tag_redraw(kcd->ar);
2738         }
2739 }
2740
2741 static void knifetool_update_mval_i(KnifeTool_OpData *kcd, const int mval_i[2])
2742 {
2743         float mval[2] = {UNPACK2(mval_i)};
2744         knifetool_update_mval(kcd, mval);
2745 }
2746
2747 /* called when modal loop selection gets set up... */
2748 static void knifetool_init(bContext *C, KnifeTool_OpData *kcd,
2749                            const bool only_select, const bool cut_through, const bool is_interactive)
2750 {
2751         Scene *scene = CTX_data_scene(C);
2752         Object *obedit = CTX_data_edit_object(C);
2753
2754         /* assign the drawing handle for drawing preview line... */
2755         kcd->ob = obedit;
2756         kcd->ar = CTX_wm_region(C);
2757
2758         em_setup_viewcontext(C, &kcd->vc);
2759
2760         kcd->em = BKE_editmesh_from_object(kcd->ob);
2761
2762         BM_mesh_elem_index_ensure(kcd->em->bm, BM_VERT);
2763
2764         kcd->cagecos = (const float (*)[3])BKE_editmesh_vertexCos_get(kcd->em, scene, NULL);
2765
2766         kcd->bmbvh = BKE_bmbvh_new_from_editmesh(kcd->em,
2767                                                  BMBVH_RETURN_ORIG |
2768                                                  (only_select ? BMBVH_RESPECT_SELECT : BMBVH_RESPECT_HIDDEN),
2769                                                  kcd->cagecos, false);
2770
2771         kcd->arena = BLI_memarena_new(MEM_SIZE_OPTIMAL(1 << 15), "knife");
2772         kcd->vthresh = KMAXDIST - 1;
2773         kcd->ethresh = KMAXDIST;
2774
2775         knife_recalc_projmat(kcd);
2776
2777         ED_region_tag_redraw(kcd->ar);
2778
2779         kcd->refs = BLI_mempool_create(sizeof(Ref), 0, 2048, 0);
2780         kcd->kverts = BLI_mempool_create(sizeof(KnifeVert), 0, 512, BLI_MEMPOOL_ALLOW_ITER);
2781         kcd->kedges = BLI_mempool_create(sizeof(KnifeEdge), 0, 512, BLI_MEMPOOL_ALLOW_ITER);
2782
2783         kcd->origedgemap = BLI_ghash_ptr_new("knife origedgemap");
2784         kcd->origvertmap = BLI_ghash_ptr_new("knife origvertmap");
2785         kcd->kedgefacemap = BLI_ghash_ptr_new("knife kedgefacemap");
2786         kcd->facetrimap = BLI_ghash_ptr_new("knife facetrimap");
2787
2788         /* cut all the way through the mesh if use_occlude_geometry button not pushed */
2789         kcd->is_interactive = is_interactive;
2790         kcd->cut_through = cut_through;
2791         kcd->only_select = only_select;
2792
2793         /* can't usefully select resulting edges in face mode */
2794         kcd->select_result = (kcd->em->selectmode != SCE_SELECT_FACE);
2795
2796         knife_pos_data_clear(&kcd->curr);
2797         knife_pos_data_clear(&kcd->prev);
2798
2799         if (is_interactive) {
2800                 kcd->draw_handle = ED_region_draw_cb_activate(kcd->ar->type, knifetool_draw, kcd, REGION_DRAW_POST_VIEW);
2801
2802                 knife_init_colors(&kcd->colors);
2803         }
2804 }
2805
2806 static void knifetool_cancel(bContext *C, wmOperator *op)
2807 {
2808         /* this is just a wrapper around exit() */
2809         knifetool_exit(C, op);
2810 }
2811
2812 static int knifetool_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2813 {
2814         const bool only_select = RNA_boolean_get(op->ptr, "only_selected");
2815         const bool cut_through = !RNA_boolean_get(op->ptr, "use_occlude_geometry");
2816
2817         KnifeTool_OpData *kcd;
2818
2819         if (only_select) {
2820                 Object *obedit = CTX_data_edit_object(C);
2821                 BMEditMesh *em = BKE_editmesh_from_object(obedit);
2822                 if (em->bm->totfacesel == 0) {
2823                         BKE_report(op->reports, RPT_ERROR, "Selected faces required");
2824                         return OPERATOR_CANCELLED;
2825                 }
2826         }
2827
2828         view3d_operator_needs_opengl(C);
2829
2830         /* alloc new customdata */
2831         kcd = op->customdata = MEM_callocN(sizeof(KnifeTool_OpData), __func__);
2832
2833         knifetool_init(C, kcd, only_select, cut_through, true);
2834
2835         /* add a modal handler for this operator - handles loop selection */
2836         WM_cursor_modal_set(CTX_wm_window(C), BC_KNIFECURSOR);
2837         WM_event_add_modal_handler(C, op);
2838
2839         knifetool_update_mval_i(kcd, event->mval);
2840
2841         knife_update_header(C, kcd);
2842
2843         return OPERATOR_RUNNING_MODAL;
2844 }
2845
2846 enum {
2847         KNF_MODAL_CANCEL = 1,
2848         KNF_MODAL_CONFIRM,
2849         KNF_MODAL_MIDPOINT_ON,
2850         KNF_MODAL_MIDPOINT_OFF,
2851         KNF_MODAL_NEW_CUT,
2852         KNF_MODEL_IGNORE_SNAP_ON,
2853         KNF_MODEL_IGNORE_SNAP_OFF,
2854         KNF_MODAL_ADD_CUT,
2855         KNF_MODAL_ANGLE_SNAP_TOGGLE,
2856         KNF_MODAL_CUT_THROUGH_TOGGLE,
2857         KNF_MODAL_PANNING,
2858         KNF_MODAL_ADD_CUT_CLOSED,
2859 };
2860
2861 wmKeyMap *knifetool_modal_keymap(wmKeyConfig *keyconf)
2862 {
2863         static EnumPropertyItem modal_items[] = {
2864                 {KNF_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
2865                 {KNF_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
2866                 {KNF_MODAL_MIDPOINT_ON, "SNAP_MIDPOINTS_ON", 0, "Snap To Midpoints On", ""},
2867                 {KNF_MODAL_MIDPOINT_OFF, "SNAP_MIDPOINTS_OFF", 0, "Snap To Midpoints Off", ""},
2868                 {KNF_MODEL_IGNORE_SNAP_ON, "IGNORE_SNAP_ON", 0, "Ignore Snapping On", ""},
2869                 {KNF_MODEL_IGNORE_SNAP_OFF, "IGNORE_SNAP_OFF", 0, "Ignore Snapping Off", ""},
2870                 {KNF_MODAL_ANGLE_SNAP_TOGGLE, "ANGLE_SNAP_TOGGLE", 0, "Toggle Angle Snapping", ""},
2871                 {KNF_MODAL_CUT_THROUGH_TOGGLE, "CUT_THROUGH_TOGGLE", 0, "Toggle Cut Through", ""},
2872                 {KNF_MODAL_NEW_CUT, "NEW_CUT", 0, "End Current Cut", ""},
2873                 {KNF_MODAL_ADD_CUT, "ADD_CUT", 0, "Add Cut", ""},
2874                 {KNF_MODAL_PANNING, "PANNING", 0, "Panning", ""},
2875                 {0, NULL, 0, NULL, NULL}
2876         };
2877
2878         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "Knife Tool Modal Map");
2879
2880         /* this function is called for each spacetype, only needs to add map once */
2881         if (keymap && keymap->modal_items)
2882                 return NULL;
2883
2884         keymap = WM_modalkeymap_add(keyconf, "Knife Tool Modal Map", modal_items);
2885
2886         /* items for modal map */
2887         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, KNF_MODAL_CANCEL);
2888         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_ANY, KM_ANY, 0, KNF_MODAL_PANNING);
2889         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_DBL_CLICK, KM_ANY, 0, KNF_MODAL_ADD_CUT_CLOSED);
2890         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_ANY, KM_ANY, 0, KNF_MODAL_ADD_CUT);
2891         WM_modalkeymap_add_item(keymap, RIGHTMOUSE, KM_PRESS, KM_ANY, 0, KNF_MODAL_CANCEL);
2892         WM_modalkeymap_add_item(keymap, RETKEY, KM_PRESS, KM_ANY, 0, KNF_MODAL_CONFIRM);
2893         WM_modalkeymap_add_item(keymap, PADENTER, KM_PRESS, KM_ANY, 0, KNF_MODAL_CONFIRM);
2894         WM_modalkeymap_add_item(keymap, SPACEKEY, KM_PRESS, KM_ANY, 0, KNF_MODAL_CONFIRM);
2895         WM_modalkeymap_add_item(keymap, EKEY, KM_PRESS, 0, 0, KNF_MODAL_NEW_CUT);
2896
2897         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_PRESS, KM_ANY, 0, KNF_MODAL_MIDPOINT_ON);
2898         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, KNF_MODAL_MIDPOINT_OFF);
2899         WM_modalkeymap_add_item(keymap, RIGHTCTRLKEY, KM_PRESS, KM_ANY, 0, KNF_MODAL_MIDPOINT_ON);
2900         WM_modalkeymap_add_item(keymap, RIGHTCTRLKEY, KM_RELEASE, KM_ANY, 0, KNF_MODAL_MIDPOINT_OFF);
2901
2902         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, KNF_MODEL_IGNORE_SNAP_ON);
2903         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_RELEASE, KM_ANY, 0, KNF_MODEL_IGNORE_SNAP_OFF);
2904         WM_modalkeymap_add_item(keymap, RIGHTSHIFTKEY, KM_PRESS, KM_ANY, 0, KNF_MODEL_IGNORE_SNAP_ON);
2905         WM_modalkeymap_add_item(keymap, RIGHTSHIFTKEY, KM_RELEASE, KM_ANY, 0, KNF_MODEL_IGNORE_SNAP_OFF);
2906
2907         WM_modalkeymap_add_item(keymap, CKEY, KM_PRESS, 0, 0, KNF_MODAL_ANGLE_SNAP_TOGGLE);
2908         WM_modalkeymap_add_item(keymap, ZKEY, KM_PRESS, 0, 0, KNF_MODAL_CUT_THROUGH_TOGGLE);
2909
2910         WM_modalkeymap_assign(keymap, "MESH_OT_knife_tool");
2911
2912         return keymap;
2913 }
2914
2915 static int knifetool_modal(bContext *C, wmOperator *op, const wmEvent *event)
2916 {
2917         Object *obedit = CTX_data_edit_object(C);
2918         KnifeTool_OpData *kcd = op->customdata;
2919         bool do_refresh = false;
2920
2921         if (!obedit || obedit->type != OB_MESH || BKE_editmesh_from_object(obedit) != kcd->em) {
2922                 knifetool_exit(C, op);
2923                 ED_area_headerprint(CTX_wm_area(C), NULL);
2924                 return OPERATOR_FINISHED;
2925         }
2926
2927         view3d_operator_needs_opengl(C);
2928         ED_view3d_init_mats_rv3d(obedit, kcd->vc.rv3d);  /* needed to initialize clipping */
2929
2930         if (kcd->mode == MODE_PANNING)
2931                 kcd->mode = kcd->prevmode;
2932
2933         /* handle modal keymap */
2934         if (event->type == EVT_MODAL_MAP) {
2935                 switch (event->val) {
2936                         case KNF_MODAL_CANCEL:
2937                                 /* finish */
2938                                 ED_region_tag_redraw(kcd->ar);
2939
2940                                 knifetool_exit(C, op);
2941                                 ED_area_headerprint(CTX_wm_area(C), NULL);
2942
2943                                 return OPERATOR_CANCELLED;
2944                         case KNF_MODAL_CONFIRM:
2945                                 /* finish */
2946                                 ED_region_tag_redraw(kcd->ar);
2947
2948                                 knifetool_finish(op);
2949                                 knifetool_exit(C, op);
2950                                 ED_area_headerprint(CTX_wm_area(C), NULL);
2951
2952                                 return OPERATOR_FINISHED;
2953                         case KNF_MODAL_MIDPOINT_ON:
2954                                 kcd->snap_midpoints = true;
2955
2956                                 knife_recalc_projmat(kcd);
2957                                 knife_update_active(kcd);
2958                                 knife_update_header(C, kcd);
2959                                 ED_region_tag_redraw(kcd->ar);
2960                                 do_refresh = true;
2961                                 break;
2962                         case KNF_MODAL_MIDPOINT_OFF:
2963                                 kcd->snap_midpoints = false;
2964
2965                                 knife_recalc_projmat(kcd);
2966                                 knife_update_active(kcd);
2967                                 knife_update_header(C, kcd);
2968                                 ED_region_tag_redraw(kcd->ar);
2969                                 do_refresh = true;
2970                                 break;
2971                         case KNF_MODEL_IGNORE_SNAP_ON:
2972                                 ED_region_tag_redraw(kcd->ar);
2973                                 kcd->ignore_vert_snapping = kcd->ignore_edge_snapping = true;
2974                                 knife_update_header(C, kcd);
2975                                 do_refresh = true;
2976                                 break;
2977                         case KNF_MODEL_IGNORE_SNAP_OFF:
2978                                 ED_region_tag_redraw(kcd->ar);
2979                                 kcd->ignore_vert_snapping = kcd->ignore_edge_snapping = false;
2980                                 knife_update_header(C, kcd);
2981                                 do_refresh = true;
2982                                 break;
2983                         case KNF_MODAL_ANGLE_SNAP_TOGGLE:
2984                                 kcd->angle_snapping = !kcd->angle_snapping;
2985                                 knife_update_header(C, kcd);
2986                                 do_refresh = true;
2987                                 break;
2988                         case KNF_MODAL_CUT_THROUGH_TOGGLE:
2989                                 kcd->cut_through = !kcd->cut_through;
2990                                 knife_update_header(C, kcd);
2991                                 do_refresh = true;
2992                                 break;
2993                         case KNF_MODAL_NEW_CUT:
2994                                 ED_region_tag_redraw(kcd->ar);
2995                                 knife_finish_cut(kcd);
2996                                 kcd->mode = MODE_IDLE;
2997                                 break;
2998                         case KNF_MODAL_ADD_CUT:
2999                                 knife_recalc_projmat(kcd);
3000
3001                                 /* get the value of the event which triggered this one */
3002                                 if (event->prevval != KM_RELEASE) {
3003                                         if (kcd->mode == MODE_DRAGGING) {
3004                                                 knife_add_cut(kcd);
3005                                         }
3006                                         else if (kcd->mode != MODE_PANNING) {
3007                                                 knife_start_cut(kcd);
3008                                                 kcd->mode = MODE_DRAGGING;
3009                                                 kcd->init = kcd->curr;
3010                                         }
3011
3012                                         /* freehand drawing is incompatible with cut-through */
3013                                         if (kcd->cut_through == false) {
3014                                                 kcd->is_drag_hold = true;
3015                                         }
3016                                 }
3017                                 else {
3018                                         kcd->is_drag_hold = false;
3019                                 }
3020
3021                                 ED_region_tag_redraw(kcd->ar);
3022                                 break;
3023                         case KNF_MODAL_ADD_CUT_CLOSED:
3024                                 if (kcd->mode == MODE_DRAGGING) {
3025                                         kcd->prev = kcd->curr;
3026                                         kcd->curr = kcd->init;
3027
3028                                         knife_project_v2(kcd, kcd->curr.cage, kcd->curr.mval);
3029                                         knifetool_update_mval(kcd, kcd->curr.mval);
3030
3031                                         knife_add_cut(kcd);
3032
3033                                         /* KNF_MODAL_NEW_CUT */
3034                                         knife_finish_cut(kcd);
3035                                         kcd->mode = MODE_IDLE;
3036                                 }
3037                                 break;
3038                         case KNF_MODAL_PANNING:
3039                                 if (event->val != KM_RELEASE) {
3040                                         if (kcd->mode != MODE_PANNING) {
3041                                                 kcd->prevmode = kcd->mode;
3042                                                 kcd->mode = MODE_PANNING;
3043                                         }
3044                                 }
3045                                 else {
3046                                         kcd->mode = kcd->prevmode;
3047                                 }
3048
3049                                 ED_region_tag_redraw(kcd->ar);
3