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