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