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