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