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