Merge branch 'master' into blender2.8
[blender.git] / source / blender / bmesh / intern / bmesh_mesh.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  * Contributor(s): Geoffrey Bantle.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/bmesh/intern/bmesh_mesh.c
24  *  \ingroup bmesh
25  *
26  * BM mesh level functions.
27  */
28
29 #include "MEM_guardedalloc.h"
30
31 #include "DNA_listBase.h"
32 #include "DNA_object_types.h"
33 #include "DNA_scene_types.h"
34
35 #include "BLI_linklist_stack.h"
36 #include "BLI_listbase.h"
37 #include "BLI_math.h"
38 #include "BLI_stack.h"
39 #include "BLI_task.h"
40 #include "BLI_utildefines.h"
41
42 #include "BKE_cdderivedmesh.h"
43 #include "BKE_editmesh.h"
44 #include "BKE_mesh.h"
45 #include "BKE_multires.h"
46
47 #include "atomic_ops.h"
48
49 #include "intern/bmesh_private.h"
50
51 /* used as an extern, defined in bmesh.h */
52 const BMAllocTemplate bm_mesh_allocsize_default = {512, 1024, 2048, 512};
53 const BMAllocTemplate bm_mesh_chunksize_default = {512, 1024, 2048, 512};
54
55 static void bm_mempool_init_ex(
56         const BMAllocTemplate *allocsize, const bool use_toolflags,
57         BLI_mempool **r_vpool, BLI_mempool **r_epool, BLI_mempool **r_lpool, BLI_mempool **r_fpool)
58 {
59         size_t vert_size, edge_size, loop_size, face_size;
60
61         if (use_toolflags == true) {
62                 vert_size = sizeof(BMVert_OFlag);
63                 edge_size = sizeof(BMEdge_OFlag);
64                 loop_size = sizeof(BMLoop);
65                 face_size = sizeof(BMFace_OFlag);
66         }
67         else {
68                 vert_size = sizeof(BMVert);
69                 edge_size = sizeof(BMEdge);
70                 loop_size = sizeof(BMLoop);
71                 face_size = sizeof(BMFace);
72         }
73
74         if (r_vpool) {
75                 *r_vpool = BLI_mempool_create(
76                         vert_size, allocsize->totvert,
77                         bm_mesh_chunksize_default.totvert, BLI_MEMPOOL_ALLOW_ITER);
78         }
79         if (r_epool) {
80                 *r_epool = BLI_mempool_create(
81                         edge_size, allocsize->totedge,
82                         bm_mesh_chunksize_default.totedge, BLI_MEMPOOL_ALLOW_ITER);
83         }
84         if (r_lpool) {
85                 *r_lpool = BLI_mempool_create(
86                         loop_size, allocsize->totloop,
87                         bm_mesh_chunksize_default.totloop, BLI_MEMPOOL_NOP);
88         }
89         if (r_fpool) {
90                 *r_fpool = BLI_mempool_create(
91                         face_size, allocsize->totface,
92                         bm_mesh_chunksize_default.totface, BLI_MEMPOOL_ALLOW_ITER);
93         }
94 }
95
96 static void bm_mempool_init(BMesh *bm, const BMAllocTemplate *allocsize, const bool use_toolflags)
97 {
98         bm_mempool_init_ex(
99                 allocsize, use_toolflags,
100                 &bm->vpool, &bm->epool, &bm->lpool, &bm->fpool);
101
102 #ifdef USE_BMESH_HOLES
103         bm->looplistpool = BLI_mempool_create(sizeof(BMLoopList), 512, 512, BLI_MEMPOOL_NOP);
104 #endif
105 }
106
107 void BM_mesh_elem_toolflags_ensure(BMesh *bm)
108 {
109         BLI_assert(bm->use_toolflags);
110
111         if (bm->vtoolflagpool && bm->etoolflagpool && bm->ftoolflagpool) {
112                 return;
113         }
114
115         bm->vtoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totvert, 512, BLI_MEMPOOL_NOP);
116         bm->etoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totedge, 512, BLI_MEMPOOL_NOP);
117         bm->ftoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totface, 512, BLI_MEMPOOL_NOP);
118
119         BMIter iter;
120         BMVert_OFlag *v_olfag;
121         BLI_mempool *toolflagpool = bm->vtoolflagpool;
122         BM_ITER_MESH (v_olfag, &iter, bm, BM_VERTS_OF_MESH) {
123                 v_olfag->oflags = BLI_mempool_calloc(toolflagpool);
124         }
125
126         BMEdge_OFlag *e_olfag;
127         toolflagpool = bm->etoolflagpool;
128         BM_ITER_MESH (e_olfag, &iter, bm, BM_EDGES_OF_MESH) {
129                 e_olfag->oflags = BLI_mempool_calloc(toolflagpool);
130         }
131
132         BMFace_OFlag *f_olfag;
133         toolflagpool = bm->ftoolflagpool;
134         BM_ITER_MESH (f_olfag, &iter, bm, BM_FACES_OF_MESH) {
135                 f_olfag->oflags = BLI_mempool_calloc(toolflagpool);
136         }
137
138         bm->totflags = 1;
139 }
140
141 void BM_mesh_elem_toolflags_clear(BMesh *bm)
142 {
143         if (bm->vtoolflagpool) {
144                 BLI_mempool_destroy(bm->vtoolflagpool);
145                 bm->vtoolflagpool = NULL;
146         }
147         if (bm->etoolflagpool) {
148                 BLI_mempool_destroy(bm->etoolflagpool);
149                 bm->etoolflagpool = NULL;
150         }
151         if (bm->ftoolflagpool) {
152                 BLI_mempool_destroy(bm->ftoolflagpool);
153                 bm->ftoolflagpool = NULL;
154         }
155 }
156
157 /**
158  * \brief BMesh Make Mesh
159  *
160  * Allocates a new BMesh structure.
161  *
162  * \return The New bmesh
163  *
164  * \note ob is needed by multires
165  */
166 BMesh *BM_mesh_create(
167         const BMAllocTemplate *allocsize,
168         const struct BMeshCreateParams *params)
169 {
170         /* allocate the structure */
171         BMesh *bm = MEM_callocN(sizeof(BMesh), __func__);
172
173         /* allocate the memory pools for the mesh elements */
174         bm_mempool_init(bm, allocsize, params->use_toolflags);
175
176         /* allocate one flag pool that we don't get rid of. */
177         bm->use_toolflags = params->use_toolflags;
178         bm->toolflag_index = 0;
179         bm->totflags = 0;
180
181         CustomData_reset(&bm->vdata);
182         CustomData_reset(&bm->edata);
183         CustomData_reset(&bm->ldata);
184         CustomData_reset(&bm->pdata);
185
186         return bm;
187 }
188
189 /**
190  * \brief BMesh Free Mesh Data
191  *
192  *      Frees a BMesh structure.
193  *
194  * \note frees mesh, but not actual BMesh struct
195  */
196 void BM_mesh_data_free(BMesh *bm)
197 {
198         BMVert *v;
199         BMEdge *e;
200         BMLoop *l;
201         BMFace *f;
202
203         BMIter iter;
204         BMIter itersub;
205
206         const bool is_ldata_free = CustomData_bmesh_has_free(&bm->ldata);
207         const bool is_pdata_free = CustomData_bmesh_has_free(&bm->pdata);
208
209         /* Check if we have to call free, if not we can avoid a lot of looping */
210         if (CustomData_bmesh_has_free(&(bm->vdata))) {
211                 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
212                         CustomData_bmesh_free_block(&(bm->vdata), &(v->head.data));
213                 }
214         }
215         if (CustomData_bmesh_has_free(&(bm->edata))) {
216                 BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
217                         CustomData_bmesh_free_block(&(bm->edata), &(e->head.data));
218                 }
219         }
220
221         if (is_ldata_free || is_pdata_free) {
222                 BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
223                         if (is_pdata_free)
224                                 CustomData_bmesh_free_block(&(bm->pdata), &(f->head.data));
225                         if (is_ldata_free) {
226                                 BM_ITER_ELEM (l, &itersub, f, BM_LOOPS_OF_FACE) {
227                                         CustomData_bmesh_free_block(&(bm->ldata), &(l->head.data));
228                                 }
229                         }
230                 }
231         }
232
233         /* Free custom data pools, This should probably go in CustomData_free? */
234         if (bm->vdata.totlayer) BLI_mempool_destroy(bm->vdata.pool);
235         if (bm->edata.totlayer) BLI_mempool_destroy(bm->edata.pool);
236         if (bm->ldata.totlayer) BLI_mempool_destroy(bm->ldata.pool);
237         if (bm->pdata.totlayer) BLI_mempool_destroy(bm->pdata.pool);
238
239         /* free custom data */
240         CustomData_free(&bm->vdata, 0);
241         CustomData_free(&bm->edata, 0);
242         CustomData_free(&bm->ldata, 0);
243         CustomData_free(&bm->pdata, 0);
244
245         /* destroy element pools */
246         BLI_mempool_destroy(bm->vpool);
247         BLI_mempool_destroy(bm->epool);
248         BLI_mempool_destroy(bm->lpool);
249         BLI_mempool_destroy(bm->fpool);
250
251         if (bm->vtable) MEM_freeN(bm->vtable);
252         if (bm->etable) MEM_freeN(bm->etable);
253         if (bm->ftable) MEM_freeN(bm->ftable);
254
255         /* destroy flag pool */
256         BM_mesh_elem_toolflags_clear(bm);
257
258 #ifdef USE_BMESH_HOLES
259         BLI_mempool_destroy(bm->looplistpool);
260 #endif
261
262         BLI_freelistN(&bm->selected);
263
264         if (bm->lnor_spacearr) {
265                 BKE_lnor_spacearr_free(bm->lnor_spacearr);
266                 MEM_freeN(bm->lnor_spacearr);
267         }
268
269         BMO_error_clear(bm);
270 }
271
272 /**
273  * \brief BMesh Clear Mesh
274  *
275  * Clear all data in bm
276  */
277 void BM_mesh_clear(BMesh *bm)
278 {
279         const bool use_toolflags = bm->use_toolflags;
280
281         /* free old mesh */
282         BM_mesh_data_free(bm);
283         memset(bm, 0, sizeof(BMesh));
284
285         /* allocate the memory pools for the mesh elements */
286         bm_mempool_init(bm, &bm_mesh_allocsize_default, use_toolflags);
287
288         bm->use_toolflags = use_toolflags;
289         bm->toolflag_index = 0;
290         bm->totflags = 0;
291
292         CustomData_reset(&bm->vdata);
293         CustomData_reset(&bm->edata);
294         CustomData_reset(&bm->ldata);
295         CustomData_reset(&bm->pdata);
296 }
297
298 /**
299  * \brief BMesh Free Mesh
300  *
301  *      Frees a BMesh data and its structure.
302  */
303 void BM_mesh_free(BMesh *bm)
304 {
305         BM_mesh_data_free(bm);
306
307         if (bm->py_handle) {
308                 /* keep this out of 'BM_mesh_data_free' because we want python
309                  * to be able to clear the mesh and maintain access. */
310                 bpy_bm_generic_invalidate(bm->py_handle);
311                 bm->py_handle = NULL;
312         }
313
314         MEM_freeN(bm);
315 }
316
317
318 /**
319  * Helpers for #BM_mesh_normals_update and #BM_verts_calc_normal_vcos
320  */
321
322 /* We use that existing internal API flag, assuming no other tool using it would run concurrently to clnors editing. */
323 #define BM_LNORSPACE_UPDATE _FLAG_MF
324
325 typedef struct BMEdgesCalcVectorsData {
326         /* Read-only data. */
327         const float (*vcos)[3];
328
329         /* Read-write data, but no need to protect it, no concurrency to fear here. */
330         float (*edgevec)[3];
331 } BMEdgesCalcVectorsData;
332
333
334 static void mesh_edges_calc_vectors_cb(void *userdata, MempoolIterData *mp_e)
335 {
336         BMEdgesCalcVectorsData *data = userdata;
337         BMEdge *e = (BMEdge *)mp_e;
338
339         if (e->l) {
340                 const float *v1_co = data->vcos ? data->vcos[BM_elem_index_get(e->v1)] : e->v1->co;
341                 const float *v2_co = data->vcos ? data->vcos[BM_elem_index_get(e->v2)] : e->v2->co;
342                 sub_v3_v3v3(data->edgevec[BM_elem_index_get(e)], v2_co, v1_co);
343                 normalize_v3(data->edgevec[BM_elem_index_get(e)]);
344         }
345         else {
346                 /* the edge vector will not be needed when the edge has no radial */
347         }
348 }
349
350 static void bm_mesh_edges_calc_vectors(BMesh *bm, float (*edgevec)[3], const float (*vcos)[3])
351 {
352         BM_mesh_elem_index_ensure(bm, BM_EDGE | (vcos ?  BM_VERT : 0));
353
354         BMEdgesCalcVectorsData data = {
355             .vcos = vcos,
356             .edgevec = edgevec
357         };
358
359         BM_iter_parallel(bm, BM_EDGES_OF_MESH, mesh_edges_calc_vectors_cb, &data, bm->totedge >= BM_OMP_LIMIT);
360 }
361
362
363 typedef struct BMVertsCalcNormalsData {
364         /* Read-only data. */
365         const float (*fnos)[3];
366         const float (*edgevec)[3];
367         const float (*vcos)[3];
368
369         /* Read-write data, protected by an atomic-based fake spinlock-like system... */
370         float (*vnos)[3];
371 } BMVertsCalcNormalsData;
372
373 static void mesh_verts_calc_normals_accum_cb(void *userdata, MempoolIterData *mp_f)
374 {
375         BMVertsCalcNormalsData *data = userdata;
376         BMFace *f = (BMFace *)mp_f;
377
378         const float *f_no = data->fnos ? data->fnos[BM_elem_index_get(f)] : f->no;
379
380         BMLoop *l_first, *l_iter;
381         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
382         do {
383                 const float *e1diff, *e2diff;
384                 float dotprod;
385                 float fac;
386
387                 /* calculate the dot product of the two edges that
388                  * meet at the loop's vertex */
389                 e1diff = data->edgevec[BM_elem_index_get(l_iter->prev->e)];
390                 e2diff = data->edgevec[BM_elem_index_get(l_iter->e)];
391                 dotprod = dot_v3v3(e1diff, e2diff);
392
393                 /* edge vectors are calculated from e->v1 to e->v2, so
394                  * adjust the dot product if one but not both loops
395                  * actually runs from from e->v2 to e->v1 */
396                 if ((l_iter->prev->e->v1 == l_iter->prev->v) ^ (l_iter->e->v1 == l_iter->v)) {
397                         dotprod = -dotprod;
398                 }
399
400                 fac = saacos(-dotprod);
401
402                 /* accumulate weighted face normal into the vertex's normal */
403                 float *v_no = data->vnos ? data->vnos[BM_elem_index_get(l_iter->v)] : l_iter->v->no;
404
405                 /* This block is a lockless threadsafe madd_v3_v3fl.
406                  * It uses the first float of the vector as a sort of cheap spinlock,
407                  * assuming FLT_MAX is a safe 'illegal' value that cannot be set here otherwise.
408                  * It also assumes that collisions between threads are highly unlikely,
409                  * else performances would be quite bad here. */
410                 float virtual_lock = v_no[0];
411                 while (true) {
412                         /* This loops until following conditions are met:
413                          *   - v_no[0] has same value as virtual_lock (i.e. it did not change since last try).
414                          *   - v_no[0] was not FLT_MAX, i.e. it was not locked by another thread.
415                          */
416                         const float vl = atomic_cas_float(&v_no[0], virtual_lock, FLT_MAX);
417                         if (vl == virtual_lock && vl != FLT_MAX) {
418                                 break;
419                         }
420                         virtual_lock = vl;
421                 }
422                 BLI_assert(v_no[0] == FLT_MAX);
423                 /* Now we own that normal value, and can change it.
424                  * But first scalar of the vector must not be changed yet, it's our lock! */
425                 virtual_lock += f_no[0] * fac;
426                 v_no[1] += f_no[1] * fac;
427                 v_no[2] += f_no[2] * fac;
428                 /* Second atomic operation to 'release' our lock on that vector and set its first scalar value. */
429                 /* Note that we do not need to loop here, since we 'locked' v_no[0],
430                  * nobody should have changed it in the mean time. */
431                 virtual_lock = atomic_cas_float(&v_no[0], FLT_MAX, virtual_lock);
432                 BLI_assert(virtual_lock == FLT_MAX);
433
434         } while ((l_iter = l_iter->next) != l_first);
435 }
436
437 static void mesh_verts_calc_normals_normalize_cb(void *userdata, MempoolIterData *mp_v)
438 {
439         BMVertsCalcNormalsData *data = userdata;
440         BMVert *v = (BMVert *)mp_v;
441
442         float *v_no = data->vnos ? data->vnos[BM_elem_index_get(v)] : v->no;
443         if (UNLIKELY(normalize_v3(v_no) == 0.0f)) {
444                 const float *v_co = data->vcos ? data->vcos[BM_elem_index_get(v)] : v->co;
445                 normalize_v3_v3(v_no, v_co);
446         }
447 }
448
449 static void bm_mesh_verts_calc_normals(
450         BMesh *bm, const float (*edgevec)[3], const float (*fnos)[3],
451         const float (*vcos)[3], float (*vnos)[3])
452 {
453         BM_mesh_elem_index_ensure(bm, (BM_EDGE | BM_FACE) | ((vnos || vcos) ?  BM_VERT : 0));
454
455         BMVertsCalcNormalsData data = {
456             .fnos = fnos,
457             .edgevec = edgevec,
458             .vcos = vcos,
459             .vnos = vnos
460         };
461
462         BM_iter_parallel(bm, BM_FACES_OF_MESH, mesh_verts_calc_normals_accum_cb, &data, bm->totface >= BM_OMP_LIMIT);
463
464         /* normalize the accumulated vertex normals */
465         BM_iter_parallel(bm, BM_VERTS_OF_MESH, mesh_verts_calc_normals_normalize_cb, &data, bm->totvert >= BM_OMP_LIMIT);
466 }
467
468
469 static void mesh_faces_calc_normals_cb(void *UNUSED(userdata), MempoolIterData *mp_f)
470 {
471         BMFace *f = (BMFace *)mp_f;
472
473         BM_face_normal_update(f);
474 }
475
476
477 /**
478  * \brief BMesh Compute Normals
479  *
480  * Updates the normals of a mesh.
481  */
482 void BM_mesh_normals_update(BMesh *bm)
483 {
484         float (*edgevec)[3] = MEM_mallocN(sizeof(*edgevec) * bm->totedge, __func__);
485
486         /* Parallel mempool iteration does not allow to generate indices inline anymore... */
487         BM_mesh_elem_index_ensure(bm, (BM_EDGE | BM_FACE));
488
489         /* calculate all face normals */
490         BM_iter_parallel(bm, BM_FACES_OF_MESH, mesh_faces_calc_normals_cb, NULL, bm->totface >= BM_OMP_LIMIT);
491
492         /* Zero out vertex normals */
493         BMIter viter;
494         BMVert *v;
495         int i;
496
497         BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
498                 BM_elem_index_set(v, i); /* set_inline */
499                 zero_v3(v->no);
500         }
501         bm->elem_index_dirty &= ~BM_VERT;
502
503         /* Compute normalized direction vectors for each edge.
504          * Directions will be used for calculating the weights of the face normals on the vertex normals.
505          */
506         bm_mesh_edges_calc_vectors(bm, edgevec, NULL);
507
508         /* Add weighted face normals to vertices, and normalize vert normals. */
509         bm_mesh_verts_calc_normals(bm, (const float(*)[3])edgevec, NULL, NULL, NULL);
510         MEM_freeN(edgevec);
511 }
512
513 /**
514  * \brief BMesh Compute Normals from/to external data.
515  *
516  * Computes the vertex normals of a mesh into vnos, using given vertex coordinates (vcos) and polygon normals (fnos).
517  */
518 void BM_verts_calc_normal_vcos(BMesh *bm, const float (*fnos)[3], const float (*vcos)[3], float (*vnos)[3])
519 {
520         float (*edgevec)[3] = MEM_mallocN(sizeof(*edgevec) * bm->totedge, __func__);
521
522         /* Compute normalized direction vectors for each edge.
523          * Directions will be used for calculating the weights of the face normals on the vertex normals.
524          */
525         bm_mesh_edges_calc_vectors(bm, edgevec, vcos);
526
527         /* Add weighted face normals to vertices, and normalize vert normals. */
528         bm_mesh_verts_calc_normals(bm, (const float(*)[3])edgevec, fnos, vcos, vnos);
529         MEM_freeN(edgevec);
530 }
531
532 /**
533  * Helpers for #BM_mesh_loop_normals_update and #BM_loops_calc_normal_vcos
534  */
535 static void bm_mesh_edges_sharp_tag(
536         BMesh *bm,
537         const float (*vnos)[3], const float (*fnos)[3], float (*r_lnos)[3],
538         const float split_angle, const bool do_sharp_edges_tag)
539 {
540         BMIter eiter;
541         BMEdge *e;
542         int i;
543
544         const bool check_angle = (split_angle < (float)M_PI);
545         const float split_angle_cos = check_angle ? cosf(split_angle) : -1.0f;
546
547         {
548                 char htype = BM_VERT | BM_LOOP;
549                 if (fnos) {
550                         htype |= BM_FACE;
551                 }
552                 BM_mesh_elem_index_ensure(bm, htype);
553         }
554
555         /* This first loop checks which edges are actually smooth, and pre-populate lnos with vnos (as if they were
556          * all smooth).
557          */
558         BM_ITER_MESH_INDEX (e, &eiter, bm, BM_EDGES_OF_MESH, i) {
559                 BMLoop *l_a, *l_b;
560
561                 BM_elem_index_set(e, i); /* set_inline */
562                 BM_elem_flag_disable(e, BM_ELEM_TAG); /* Clear tag (means edge is sharp). */
563
564                 /* An edge with only two loops, might be smooth... */
565                 if (BM_edge_loop_pair(e, &l_a, &l_b)) {
566                         bool is_angle_smooth = true;
567                         if (check_angle) {
568                                 const float *no_a = fnos ? fnos[BM_elem_index_get(l_a->f)] : l_a->f->no;
569                                 const float *no_b = fnos ? fnos[BM_elem_index_get(l_b->f)] : l_b->f->no;
570                                 is_angle_smooth = (dot_v3v3(no_a, no_b) >= split_angle_cos);
571                         }
572
573                         /* We only tag edges that are *really* smooth:
574                          * If the angle between both its polys' normals is below split_angle value,
575                          * and it is tagged as such,
576                          * and both its faces are smooth,
577                          * and both its faces have compatible (non-flipped) normals,
578                          * i.e. both loops on the same edge do not share the same vertex.
579                          */
580                         if (BM_elem_flag_test(e, BM_ELEM_SMOOTH) &&
581                             BM_elem_flag_test(l_a->f, BM_ELEM_SMOOTH) &&
582                             BM_elem_flag_test(l_b->f, BM_ELEM_SMOOTH) &&
583                             l_a->v != l_b->v)
584                         {
585                                 if (is_angle_smooth) {
586                                         const float *no;
587                                         BM_elem_flag_enable(e, BM_ELEM_TAG);
588
589                                         /* linked vertices might be fully smooth, copy their normals to loop ones. */
590                                         if (r_lnos) {
591                                                 no = vnos ? vnos[BM_elem_index_get(l_a->v)] : l_a->v->no;
592                                                 copy_v3_v3(r_lnos[BM_elem_index_get(l_a)], no);
593                                                 no = vnos ? vnos[BM_elem_index_get(l_b->v)] : l_b->v->no;
594                                                 copy_v3_v3(r_lnos[BM_elem_index_get(l_b)], no);
595                                         }
596                                 }
597                                 else if (do_sharp_edges_tag) {
598                                         /* Note that we do not care about the other sharp-edge cases (sharp poly, non-manifold edge, etc.),
599                                          * only tag edge as sharp when it is due to angle threashold. */
600                                         BM_elem_flag_disable(e, BM_ELEM_SMOOTH);
601                                 }
602                         }
603                 }
604         }
605
606         bm->elem_index_dirty &= ~BM_EDGE;
607 }
608
609 /**
610  * Check whether given loop is part of an unknown-so-far cyclic smooth fan, or not.
611  * Needed because cyclic smooth fans have no obvious 'entry point', and yet we need to walk them once, and only once.
612  */
613 bool BM_loop_check_cyclic_smooth_fan(BMLoop *l_curr)
614 {
615         BMLoop *lfan_pivot_next = l_curr;
616         BMEdge *e_next = l_curr->e;
617
618         BLI_assert(!BM_elem_flag_test(lfan_pivot_next, BM_ELEM_TAG));
619         BM_elem_flag_enable(lfan_pivot_next, BM_ELEM_TAG);
620
621         while (true) {
622                 /* Much simpler than in sibling code with basic Mesh data! */
623                 lfan_pivot_next = BM_vert_step_fan_loop(lfan_pivot_next, &e_next);
624
625                 if (!lfan_pivot_next || !BM_elem_flag_test(e_next, BM_ELEM_TAG)) {
626                         /* Sharp loop/edge, so not a cyclic smooth fan... */
627                         return false;
628                 }
629                 /* Smooth loop/edge... */
630                 else if (BM_elem_flag_test(lfan_pivot_next, BM_ELEM_TAG)) {
631                         if (lfan_pivot_next == l_curr) {
632                                 /* We walked around a whole cyclic smooth fan without finding any already-processed loop, means we can
633                                  * use initial l_curr/l_prev edge as start for this smooth fan. */
634                                 return true;
635                         }
636                         /* ... already checked in some previous looping, we can abort. */
637                         return false;
638                 }
639                 else {
640                         /* ... we can skip it in future, and keep checking the smooth fan. */
641                         BM_elem_flag_enable(lfan_pivot_next, BM_ELEM_TAG);
642                 }
643         }
644 }
645
646 /* BMesh version of BKE_mesh_normals_loop_split() in mesh_evaluate.c
647  * Will use first clnors_data array, and fallback to cd_loop_clnors_offset (use NULL and -1 to not use clnors). */
648 static void bm_mesh_loops_calc_normals(
649         BMesh *bm, const float (*vcos)[3], const float (*fnos)[3], float (*r_lnos)[3],
650         MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2],
651         const int cd_loop_clnors_offset, const bool do_rebuild)
652 {
653         BMIter fiter;
654         BMFace *f_curr;
655         const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
656
657         MLoopNorSpaceArray _lnors_spacearr = {NULL};
658
659         /* Temp normal stack. */
660         BLI_SMALLSTACK_DECLARE(normal, float *);
661         /* Temp clnors stack. */
662         BLI_SMALLSTACK_DECLARE(clnors, short *);
663         /* Temp edge vectors stack, only used when computing lnor spacearr. */
664         BLI_Stack *edge_vectors = NULL;
665
666         {
667                 char htype = 0;
668                 if (vcos) {
669                         htype |= BM_VERT;
670                 }
671                 /* Face/Loop indices are set inline below. */
672                 BM_mesh_elem_index_ensure(bm, htype);
673         }
674
675         if (!r_lnors_spacearr && has_clnors) {
676                 /* We need to compute lnor spacearr if some custom lnor data are given to us! */
677                 r_lnors_spacearr = &_lnors_spacearr;
678         }
679         if (r_lnors_spacearr) {
680                 BKE_lnor_spacearr_init(r_lnors_spacearr, bm->totloop, MLNOR_SPACEARR_BMLOOP_PTR);
681                 edge_vectors = BLI_stack_new(sizeof(float[3]), __func__);
682         }
683
684         /* Clear all loops' tags (means none are to be skipped for now). */
685         int index_face, index_loop = 0;
686         BM_ITER_MESH_INDEX (f_curr, &fiter, bm, BM_FACES_OF_MESH, index_face) {
687                 BMLoop *l_curr, *l_first;
688
689                 BM_elem_index_set(f_curr, index_face); /* set_inline */
690
691                 l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
692                 do {
693                         BM_elem_index_set(l_curr, index_loop++); /* set_inline */
694                         BM_elem_flag_disable(l_curr, BM_ELEM_TAG);
695                 } while ((l_curr = l_curr->next) != l_first);
696         }
697         bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP);
698
699         /* We now know edges that can be smoothed (they are tagged), and edges that will be hard (they aren't).
700          * Now, time to generate the normals.
701          */
702         BM_ITER_MESH (f_curr, &fiter, bm, BM_FACES_OF_MESH) {
703                 BMLoop *l_curr, *l_first;
704
705                 l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
706                 do {
707                         if (do_rebuild && !BM_ELEM_API_FLAG_TEST(l_curr, BM_LNORSPACE_UPDATE) &&
708                             !(bm->spacearr_dirty & BM_SPACEARR_DIRTY_ALL))
709                         {
710                                 continue;
711                         }
712                         /* A smooth edge, we have to check for cyclic smooth fan case.
713                          * If we find a new, never-processed cyclic smooth fan, we can do it now using that loop/edge as
714                          * 'entry point', otherwise we can skip it. */
715                         /* Note: In theory, we could make bm_mesh_loop_check_cyclic_smooth_fan() store mlfan_pivot's in a stack,
716                          * to avoid having to fan again around the vert during actual computation of clnor & clnorspace.
717                          * However, this would complicate the code, add more memory usage, and BM_vert_step_fan_loop()
718                          * is quite cheap in term of CPU cycles, so really think it's not worth it. */
719                         if (BM_elem_flag_test(l_curr->e, BM_ELEM_TAG) &&
720                             (BM_elem_flag_test(l_curr, BM_ELEM_TAG) || !BM_loop_check_cyclic_smooth_fan(l_curr)))
721                         {
722                         }
723                         else if (!BM_elem_flag_test(l_curr->e, BM_ELEM_TAG) &&
724                                  !BM_elem_flag_test(l_curr->prev->e, BM_ELEM_TAG))
725                         {
726                                 /* Simple case (both edges around that vertex are sharp in related polygon),
727                                  * this vertex just takes its poly normal.
728                                  */
729                                 const int l_curr_index = BM_elem_index_get(l_curr);
730                                 const float *no = fnos ? fnos[BM_elem_index_get(f_curr)] : f_curr->no;
731                                 copy_v3_v3(r_lnos[l_curr_index], no);
732
733                                 /* If needed, generate this (simple!) lnor space. */
734                                 if (r_lnors_spacearr) {
735                                         float vec_curr[3], vec_prev[3];
736                                         MLoopNorSpace *lnor_space = BKE_lnor_space_create(r_lnors_spacearr);
737
738                                         {
739                                                 const BMVert *v_pivot = l_curr->v;
740                                                 const float *co_pivot = vcos ? vcos[BM_elem_index_get(v_pivot)] : v_pivot->co;
741                                                 const BMVert *v_1 = BM_edge_other_vert(l_curr->e, v_pivot);
742                                                 const float *co_1 = vcos ? vcos[BM_elem_index_get(v_1)] : v_1->co;
743                                                 const BMVert *v_2 = BM_edge_other_vert(l_curr->prev->e, v_pivot);
744                                                 const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
745
746                                                 sub_v3_v3v3(vec_curr, co_1, co_pivot);
747                                                 normalize_v3(vec_curr);
748                                                 sub_v3_v3v3(vec_prev, co_2, co_pivot);
749                                                 normalize_v3(vec_prev);
750                                         }
751
752                                         BKE_lnor_space_define(lnor_space, r_lnos[l_curr_index], vec_curr, vec_prev, NULL);
753                                         /* We know there is only one loop in this space, no need to create a linklist in this case... */
754                                         BKE_lnor_space_add_loop(r_lnors_spacearr, lnor_space, l_curr_index, l_curr, true);
755
756                                         if (has_clnors) {
757                                                 short (*clnor)[2] = clnors_data ? &clnors_data[l_curr_index] :
758                                                                                   BM_ELEM_CD_GET_VOID_P(l_curr, cd_loop_clnors_offset);
759                                                 BKE_lnor_space_custom_data_to_normal(lnor_space, *clnor, r_lnos[l_curr_index]);
760                                         }
761                                 }
762                         }
763                         /* We *do not need* to check/tag loops as already computed!
764                          * Due to the fact a loop only links to one of its two edges, a same fan *will never be walked more than
765                          * once!*
766                          * Since we consider edges having neighbor faces with inverted (flipped) normals as sharp, we are sure that
767                          * no fan will be skipped, even only considering the case (sharp curr_edge, smooth prev_edge), and not the
768                          * alternative (smooth curr_edge, sharp prev_edge).
769                          * All this due/thanks to link between normals and loop ordering.
770                          */
771                         else {
772                                 /* We have to fan around current vertex, until we find the other non-smooth edge,
773                                  * and accumulate face normals into the vertex!
774                                  * Note in case this vertex has only one sharp edge, this is a waste because the normal is the same as
775                                  * the vertex normal, but I do not see any easy way to detect that (would need to count number
776                                  * of sharp edges per vertex, I doubt the additional memory usage would be worth it, especially as
777                                  * it should not be a common case in real-life meshes anyway).
778                                  */
779                                 BMVert *v_pivot = l_curr->v;
780                                 BMEdge *e_next;
781                                 const BMEdge *e_org = l_curr->e;
782                                 BMLoop *lfan_pivot, *lfan_pivot_next;
783                                 int lfan_pivot_index;
784                                 float lnor[3] = {0.0f, 0.0f, 0.0f};
785                                 float vec_curr[3], vec_next[3], vec_org[3];
786
787                                 /* We validate clnors data on the fly - cheapest way to do! */
788                                 int clnors_avg[2] = {0, 0};
789                                 short (*clnor_ref)[2] = NULL;
790                                 int clnors_nbr = 0;
791                                 bool clnors_invalid = false;
792
793                                 const float *co_pivot = vcos ? vcos[BM_elem_index_get(v_pivot)] : v_pivot->co;
794
795                                 MLoopNorSpace *lnor_space = r_lnors_spacearr ? BKE_lnor_space_create(r_lnors_spacearr) : NULL;
796
797                                 BLI_assert((edge_vectors == NULL) || BLI_stack_is_empty(edge_vectors));
798
799                                 lfan_pivot = l_curr;
800                                 lfan_pivot_index = BM_elem_index_get(lfan_pivot);
801                                 e_next = lfan_pivot->e;  /* Current edge here, actually! */
802
803                                 /* Only need to compute previous edge's vector once, then we can just reuse old current one! */
804                                 {
805                                         const BMVert *v_2 = BM_edge_other_vert(e_next, v_pivot);
806                                         const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
807
808                                         sub_v3_v3v3(vec_org, co_2, co_pivot);
809                                         normalize_v3(vec_org);
810                                         copy_v3_v3(vec_curr, vec_org);
811
812                                         if (r_lnors_spacearr) {
813                                                 BLI_stack_push(edge_vectors, vec_org);
814                                         }
815                                 }
816
817                                 while (true) {
818                                         /* Much simpler than in sibling code with basic Mesh data! */
819                                         lfan_pivot_next = BM_vert_step_fan_loop(lfan_pivot, &e_next);
820                                         if (lfan_pivot_next) {
821                                                 BLI_assert(lfan_pivot_next->v == v_pivot);
822                                         }
823                                         else {
824                                                 /* next edge is non-manifold, we have to find it ourselves! */
825                                                 e_next = (lfan_pivot->e == e_next) ? lfan_pivot->prev->e : lfan_pivot->e;
826                                         }
827
828                                         /* Compute edge vector.
829                                          * NOTE: We could pre-compute those into an array, in the first iteration, instead of computing them
830                                          *       twice (or more) here. However, time gained is not worth memory and time lost,
831                                          *       given the fact that this code should not be called that much in real-life meshes...
832                                          */
833                                         {
834                                                 const BMVert *v_2 = BM_edge_other_vert(e_next, v_pivot);
835                                                 const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
836
837                                                 sub_v3_v3v3(vec_next, co_2, co_pivot);
838                                                 normalize_v3(vec_next);
839                                         }
840
841                                         {
842                                                 /* Code similar to accumulate_vertex_normals_poly_v3. */
843                                                 /* Calculate angle between the two poly edges incident on this vertex. */
844                                                 const BMFace *f = lfan_pivot->f;
845                                                 const float fac = saacos(dot_v3v3(vec_next, vec_curr));
846                                                 const float *no = fnos ? fnos[BM_elem_index_get(f)] : f->no;
847                                                 /* Accumulate */
848                                                 madd_v3_v3fl(lnor, no, fac);
849
850                                                 if (has_clnors) {
851                                                         /* Accumulate all clnors, if they are not all equal we have to fix that! */
852                                                         short (*clnor)[2] = clnors_data ? &clnors_data[lfan_pivot_index] :
853                                                                                           BM_ELEM_CD_GET_VOID_P(lfan_pivot, cd_loop_clnors_offset);
854                                                         if (clnors_nbr) {
855                                                                 clnors_invalid |= ((*clnor_ref)[0] != (*clnor)[0] || (*clnor_ref)[1] != (*clnor)[1]);
856                                                         }
857                                                         else {
858                                                                 clnor_ref = clnor;
859                                                         }
860                                                         clnors_avg[0] += (*clnor)[0];
861                                                         clnors_avg[1] += (*clnor)[1];
862                                                         clnors_nbr++;
863                                                         /* We store here a pointer to all custom lnors processed. */
864                                                         BLI_SMALLSTACK_PUSH(clnors, (short *)*clnor);
865                                                 }
866                                         }
867
868                                         /* We store here a pointer to all loop-normals processed. */
869                                         BLI_SMALLSTACK_PUSH(normal, (float *)r_lnos[lfan_pivot_index]);
870
871                                         if (r_lnors_spacearr) {
872                                                 /* Assign current lnor space to current 'vertex' loop. */
873                                                 BKE_lnor_space_add_loop(r_lnors_spacearr, lnor_space, lfan_pivot_index, lfan_pivot, false);
874                                                 if (e_next != e_org) {
875                                                         /* We store here all edges-normalized vectors processed. */
876                                                         BLI_stack_push(edge_vectors, vec_next);
877                                                 }
878                                         }
879
880                                         if (!BM_elem_flag_test(e_next, BM_ELEM_TAG) || (e_next == e_org)) {
881                                                 /* Next edge is sharp, we have finished with this fan of faces around this vert! */
882                                                 break;
883                                         }
884
885                                         /* Copy next edge vector to current one. */
886                                         copy_v3_v3(vec_curr, vec_next);
887                                         /* Next pivot loop to current one. */
888                                         lfan_pivot = lfan_pivot_next;
889                                         lfan_pivot_index = BM_elem_index_get(lfan_pivot);
890                                 }
891
892                                 {
893                                         float lnor_len = normalize_v3(lnor);
894
895                                         /* If we are generating lnor spacearr, we can now define the one for this fan. */
896                                         if (r_lnors_spacearr) {
897                                                 if (UNLIKELY(lnor_len == 0.0f)) {
898                                                         /* Use vertex normal as fallback! */
899                                                         copy_v3_v3(lnor, r_lnos[lfan_pivot_index]);
900                                                         lnor_len = 1.0f;
901                                                 }
902
903                                                 BKE_lnor_space_define(lnor_space, lnor, vec_org, vec_next, edge_vectors);
904
905                                                 if (has_clnors) {
906                                                         if (clnors_invalid) {
907                                                                 short *clnor;
908
909                                                                 clnors_avg[0] /= clnors_nbr;
910                                                                 clnors_avg[1] /= clnors_nbr;
911                                                                 /* Fix/update all clnors of this fan with computed average value. */
912
913                                                                 /* Prints continuously when merge custom normals, so commenting. */
914                                                                 /* printf("Invalid clnors in this fan!\n"); */
915
916                                                                 while ((clnor = BLI_SMALLSTACK_POP(clnors))) {
917                                                                         //print_v2("org clnor", clnor);
918                                                                         clnor[0] = (short)clnors_avg[0];
919                                                                         clnor[1] = (short)clnors_avg[1];
920                                                                 }
921                                                                 //print_v2("new clnors", clnors_avg);
922                                                         }
923                                                         else {
924                                                                 /* We still have to consume the stack! */
925                                                                 while (BLI_SMALLSTACK_POP(clnors));
926                                                         }
927                                                         BKE_lnor_space_custom_data_to_normal(lnor_space, *clnor_ref, lnor);
928                                                 }
929                                         }
930
931                                         /* In case we get a zero normal here, just use vertex normal already set! */
932                                         if (LIKELY(lnor_len != 0.0f)) {
933                                                 /* Copy back the final computed normal into all related loop-normals. */
934                                                 float *nor;
935
936                                                 while ((nor = BLI_SMALLSTACK_POP(normal))) {
937                                                         copy_v3_v3(nor, lnor);
938                                                 }
939                                         }
940                                         else {
941                                                 /* We still have to consume the stack! */
942                                                 while (BLI_SMALLSTACK_POP(normal));
943                                         }
944                                 }
945
946                                 /* Tag related vertex as sharp, to avoid fanning around it again (in case it was a smooth one). */
947                                 if (r_lnors_spacearr) {
948                                         BM_elem_flag_enable(l_curr->v, BM_ELEM_TAG);
949                                 }
950                         }
951                 } while ((l_curr = l_curr->next) != l_first);
952         }
953
954         if (r_lnors_spacearr) {
955                 BLI_stack_free(edge_vectors);
956                 if (r_lnors_spacearr == &_lnors_spacearr) {
957                         BKE_lnor_spacearr_free(r_lnors_spacearr);
958                 }
959         }
960 }
961
962 static void bm_mesh_loops_calc_normals_no_autosmooth(
963         BMesh *bm, const float (*vnos)[3], const float (*fnos)[3], float (*r_lnos)[3])
964 {
965         BMIter fiter;
966         BMFace *f_curr;
967
968         {
969                 char htype = BM_LOOP;
970                 if (vnos) {
971                         htype |= BM_VERT;
972                 }
973                 if (fnos) {
974                         htype |= BM_FACE;
975                 }
976                 BM_mesh_elem_index_ensure(bm, htype);
977         }
978
979         BM_ITER_MESH (f_curr, &fiter, bm, BM_FACES_OF_MESH) {
980                 BMLoop *l_curr, *l_first;
981                 const bool is_face_flat = !BM_elem_flag_test(f_curr, BM_ELEM_SMOOTH);
982
983                 l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
984                 do {
985                         const float *no = is_face_flat ? (fnos ? fnos[BM_elem_index_get(f_curr)] : f_curr->no) :
986                                                          (vnos ? vnos[BM_elem_index_get(l_curr->v)] : l_curr->v->no);
987                         copy_v3_v3(r_lnos[BM_elem_index_get(l_curr)], no);
988
989                 } while ((l_curr = l_curr->next) != l_first);
990         }
991 }
992
993 #if 0  /* Unused currently */
994 /**
995  * \brief BMesh Compute Loop Normals
996  *
997  * Updates the loop normals of a mesh. Assumes vertex and face normals are valid (else call BM_mesh_normals_update()
998  * first)!
999  */
1000 void BM_mesh_loop_normals_update(
1001         BMesh *bm, const bool use_split_normals, const float split_angle, float (*r_lnos)[3],
1002         MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2], const int cd_loop_clnors_offset)
1003 {
1004         const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
1005
1006         if (use_split_normals) {
1007                 /* Tag smooth edges and set lnos from vnos when they might be completely smooth...
1008                  * When using custom loop normals, disable the angle feature! */
1009                 bm_mesh_edges_sharp_tag(bm, NULL, NULL, has_clnors ? (float)M_PI : split_angle, r_lnos);
1010
1011                 /* Finish computing lnos by accumulating face normals in each fan of faces defined by sharp edges. */
1012                 bm_mesh_loops_calc_normals(bm, NULL, NULL, r_lnos, r_lnors_spacearr, clnors_data, cd_loop_clnors_offset);
1013         }
1014         else {
1015                 BLI_assert(!r_lnors_spacearr);
1016                 bm_mesh_loops_calc_normals_no_autosmooth(bm, NULL, NULL, r_lnos);
1017         }
1018 }
1019 #endif
1020
1021 /**
1022  * \brief BMesh Compute Loop Normals from/to external data.
1023  *
1024  * Compute split normals, i.e. vertex normals associated with each poly (hence 'loop normals').
1025  * Useful to materialize sharp edges (or non-smooth faces) without actually modifying the geometry (splitting edges).
1026  */
1027 void BM_loops_calc_normal_vcos(
1028         BMesh *bm, const float (*vcos)[3], const float (*vnos)[3], const float (*fnos)[3],
1029         const bool use_split_normals, const float split_angle, float (*r_lnos)[3],
1030         MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2],
1031         const int cd_loop_clnors_offset, const bool do_rebuild)
1032 {
1033         const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
1034
1035         if (use_split_normals) {
1036                 /* Tag smooth edges and set lnos from vnos when they might be completely smooth...
1037                  * When using custom loop normals, disable the angle feature! */
1038                 bm_mesh_edges_sharp_tag(bm, vnos, fnos, r_lnos, has_clnors ? (float)M_PI : split_angle, false);
1039
1040                 /* Finish computing lnos by accumulating face normals in each fan of faces defined by sharp edges. */
1041                 bm_mesh_loops_calc_normals(
1042                             bm, vcos, fnos, r_lnos, r_lnors_spacearr, clnors_data, cd_loop_clnors_offset, do_rebuild);
1043         }
1044         else {
1045                 BLI_assert(!r_lnors_spacearr);
1046                 bm_mesh_loops_calc_normals_no_autosmooth(bm, vnos, fnos, r_lnos);
1047         }
1048 }
1049
1050 /** Define sharp edges as needed to mimic 'autosmooth' from angle threshold.
1051  *
1052  * Used when defining an empty custom loop normals data layer, to keep same shading as with autosmooth!
1053  */
1054 void BM_edges_sharp_from_angle_set(BMesh *bm, const float split_angle)
1055 {
1056         if (split_angle >= (float)M_PI) {
1057                 /* Nothing to do! */
1058                 return;
1059         }
1060
1061         bm_mesh_edges_sharp_tag(bm, NULL, NULL, NULL, split_angle, true);
1062 }
1063
1064 void BM_lnorspacearr_store(BMesh *bm, float(*r_lnors)[3])
1065 {
1066         BLI_assert(bm->lnor_spacearr != NULL);
1067
1068         if (!CustomData_has_layer(&bm->ldata, CD_CUSTOMLOOPNORMAL)) {
1069                 BM_data_layer_add(bm, &bm->ldata, CD_CUSTOMLOOPNORMAL);
1070         }
1071
1072         int cd_loop_clnors_offset = CustomData_get_offset(&bm->ldata, CD_CUSTOMLOOPNORMAL);
1073
1074         BM_loops_calc_normal_vcos(
1075                 bm, NULL, NULL, NULL, true, M_PI, r_lnors, bm->lnor_spacearr, NULL, cd_loop_clnors_offset, false);
1076         bm->spacearr_dirty &= ~(BM_SPACEARR_DIRTY | BM_SPACEARR_DIRTY_ALL);
1077 }
1078
1079 #define CLEAR_SPACEARRAY_THRESHOLD(x) ((x) / 2)
1080
1081 void BM_lnorspace_invalidate(BMesh *bm, const bool do_invalidate_all)
1082 {
1083         if (bm->spacearr_dirty & BM_SPACEARR_DIRTY_ALL) {
1084                 return;
1085         }
1086         if (do_invalidate_all || bm->totvertsel > CLEAR_SPACEARRAY_THRESHOLD(bm->totvert)) {
1087                 bm->spacearr_dirty |= BM_SPACEARR_DIRTY_ALL;
1088                 return;
1089         }
1090         if (bm->lnor_spacearr == NULL) {
1091                 bm->spacearr_dirty |= BM_SPACEARR_DIRTY_ALL;
1092                 return;
1093         }
1094
1095         BMVert *v;
1096         BMLoop *l;
1097         BMIter viter, liter;
1098         /* Note: we could use temp tag of BMItem for that, but probably better not use it in such a low-level func?
1099          * --mont29 */
1100         BLI_bitmap *done_verts = BLI_BITMAP_NEW(bm->totvert, __func__);
1101
1102         BM_mesh_elem_index_ensure(bm, BM_VERT);
1103
1104         /* When we affect a given vertex, we may affect following smooth fans:
1105          *     - all smooth fans of said vertex;
1106          *     - all smooth fans of all immediate loop-neighbors vertices;
1107          * This can be simplified as 'all loops of selected vertices and their immediate neighbors'
1108          * need to be tagged for update.
1109          */
1110         BM_ITER_MESH(v, &viter, bm, BM_VERTS_OF_MESH) {
1111                 if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
1112                         BM_ITER_ELEM(l, &liter, v, BM_LOOPS_OF_VERT) {
1113                                 BM_ELEM_API_FLAG_ENABLE(l, BM_LNORSPACE_UPDATE);
1114
1115                                 /* Note that we only handle unselected neighbor vertices here, main loop will take care of
1116                                  * selected ones. */
1117                                 if ((!BM_elem_flag_test(l->prev->v, BM_ELEM_SELECT)) &&
1118                                     !BLI_BITMAP_TEST(done_verts, BM_elem_index_get(l->prev->v)))
1119                                 {
1120
1121                                         BMLoop *l_prev;
1122                                         BMIter liter_prev;
1123                                         BM_ITER_ELEM(l_prev, &liter_prev, l->prev->v, BM_LOOPS_OF_VERT) {
1124                                                 BM_ELEM_API_FLAG_ENABLE(l_prev, BM_LNORSPACE_UPDATE);
1125                                         }
1126                                         BLI_BITMAP_ENABLE(done_verts, BM_elem_index_get(l_prev->v));
1127                                 }
1128
1129                                 if ((!BM_elem_flag_test(l->next->v, BM_ELEM_SELECT)) &&
1130                                     !BLI_BITMAP_TEST(done_verts, BM_elem_index_get(l->next->v)))
1131                                 {
1132
1133                                         BMLoop *l_next;
1134                                         BMIter liter_next;
1135                                         BM_ITER_ELEM(l_next, &liter_next, l->next->v, BM_LOOPS_OF_VERT) {
1136                                                 BM_ELEM_API_FLAG_ENABLE(l_next, BM_LNORSPACE_UPDATE);
1137                                         }
1138                                         BLI_BITMAP_ENABLE(done_verts, BM_elem_index_get(l_next->v));
1139                                 }
1140                         }
1141
1142                         BLI_BITMAP_ENABLE(done_verts, BM_elem_index_get(v));
1143                 }
1144         }
1145
1146         MEM_freeN(done_verts);
1147         bm->spacearr_dirty |= BM_SPACEARR_DIRTY;
1148 }
1149
1150 void BM_lnorspace_rebuild(BMesh *bm, bool preserve_clnor)
1151 {
1152         BLI_assert(bm->lnor_spacearr != NULL);
1153
1154         if (!(bm->spacearr_dirty & (BM_SPACEARR_DIRTY | BM_SPACEARR_DIRTY_ALL))) {
1155                 return;
1156         }
1157         BMFace *f;
1158         BMLoop *l;
1159         BMIter fiter, liter;
1160
1161         float(*r_lnors)[3] = MEM_callocN(sizeof(*r_lnors) * bm->totloop, __func__);
1162         float(*oldnors)[3] = preserve_clnor ? MEM_mallocN(sizeof(*oldnors) * bm->totloop, __func__) : NULL;
1163
1164         int cd_loop_clnors_offset = CustomData_get_offset(&bm->ldata, CD_CUSTOMLOOPNORMAL);
1165
1166         BM_mesh_elem_index_ensure(bm, BM_LOOP);
1167
1168         if (preserve_clnor) {
1169                 BLI_assert(bm->lnor_spacearr->lspacearr != NULL);
1170
1171                 BM_ITER_MESH(f, &fiter, bm, BM_FACES_OF_MESH) {
1172                         BM_ITER_ELEM(l, &liter, f, BM_LOOPS_OF_FACE) {
1173                                 if (BM_ELEM_API_FLAG_TEST(l, BM_LNORSPACE_UPDATE) || bm->spacearr_dirty & BM_SPACEARR_DIRTY_ALL) {
1174                                         short(*clnor)[2] = BM_ELEM_CD_GET_VOID_P(l, cd_loop_clnors_offset);
1175                                         int l_index = BM_elem_index_get(l);
1176
1177                                         BKE_lnor_space_custom_data_to_normal(
1178                                                 bm->lnor_spacearr->lspacearr[l_index], *clnor,
1179                                                 oldnors[l_index]);
1180                                 }
1181                         }
1182                 }
1183         }
1184
1185         if (bm->spacearr_dirty & BM_SPACEARR_DIRTY_ALL) {
1186                 BKE_lnor_spacearr_clear(bm->lnor_spacearr);
1187         }
1188         BM_loops_calc_normal_vcos(
1189                 bm, NULL, NULL, NULL, true, M_PI, r_lnors, bm->lnor_spacearr, NULL, cd_loop_clnors_offset, true);
1190         MEM_freeN(r_lnors);
1191
1192         BM_ITER_MESH(f, &fiter, bm, BM_FACES_OF_MESH) {
1193                 BM_ITER_ELEM(l, &liter, f, BM_LOOPS_OF_FACE) {
1194                         if (BM_ELEM_API_FLAG_TEST(l, BM_LNORSPACE_UPDATE) || bm->spacearr_dirty & BM_SPACEARR_DIRTY_ALL) {
1195                                 if (preserve_clnor) {
1196                                         short(*clnor)[2] = BM_ELEM_CD_GET_VOID_P(l, cd_loop_clnors_offset);
1197                                         int l_index = BM_elem_index_get(l);
1198                                         BKE_lnor_space_custom_normal_to_data(
1199                                                 bm->lnor_spacearr->lspacearr[l_index], oldnors[l_index],
1200                                                 *clnor);
1201                                 }
1202                                 BM_ELEM_API_FLAG_DISABLE(l, BM_LNORSPACE_UPDATE);
1203                         }
1204                 }
1205         }
1206
1207         MEM_SAFE_FREE(oldnors);
1208         bm->spacearr_dirty &= ~(BM_SPACEARR_DIRTY | BM_SPACEARR_DIRTY_ALL);
1209
1210 #ifndef NDEBUG
1211         BM_lnorspace_err(bm);
1212 #endif
1213 }
1214
1215 void BM_lnorspace_update(BMesh *bm)
1216 {
1217         if (bm->lnor_spacearr == NULL) {
1218                 bm->lnor_spacearr = MEM_callocN(sizeof(*bm->lnor_spacearr), __func__);
1219         }
1220         if (bm->lnor_spacearr->lspacearr == NULL) {
1221                 float(*lnors)[3] = MEM_callocN(sizeof(*lnors) * bm->totloop, __func__);
1222
1223                 BM_lnorspacearr_store(bm, lnors);
1224
1225                 MEM_freeN(lnors);
1226         }
1227         else if (bm->spacearr_dirty & (BM_SPACEARR_DIRTY | BM_SPACEARR_DIRTY_ALL)) {
1228                 BM_lnorspace_rebuild(bm, false);
1229         }
1230 }
1231
1232 void BM_normals_loops_edges_tag(BMesh *bm, const bool do_edges)
1233 {
1234         BMFace *f;
1235         BMEdge *e;
1236         BMIter fiter, eiter;
1237         BMLoop *l_curr, *l_first;
1238
1239         if (do_edges) {
1240                 int index_edge;
1241                 BM_ITER_MESH_INDEX(e, &eiter, bm, BM_EDGES_OF_MESH, index_edge) {
1242                         BMLoop *l_a, *l_b;
1243
1244                         BM_elem_index_set(e, index_edge);  /* set_inline */
1245                         BM_elem_flag_disable(e, BM_ELEM_TAG);
1246                         if (BM_edge_loop_pair(e, &l_a, &l_b)) {
1247                                 if (BM_elem_flag_test(e, BM_ELEM_SMOOTH) && l_a->v != l_b->v) {
1248                                         BM_elem_flag_enable(e, BM_ELEM_TAG);
1249                                 }
1250                         }
1251                 }
1252                 bm->elem_index_dirty &= ~BM_EDGE;
1253         }
1254
1255         int index_face, index_loop = 0;
1256         BM_ITER_MESH_INDEX(f, &fiter, bm, BM_FACES_OF_MESH, index_face) {
1257                 BM_elem_index_set(f, index_face);  /* set_inline */
1258                 l_curr = l_first = BM_FACE_FIRST_LOOP(f);
1259                 do {
1260                         BM_elem_index_set(l_curr, index_loop++);  /* set_inline */
1261                         BM_elem_flag_disable(l_curr, BM_ELEM_TAG);
1262                 } while ((l_curr = l_curr->next) != l_first);
1263         }
1264         bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP);
1265 }
1266
1267 /**
1268  * Auxillary function only used by rebuild to detect if any spaces were not marked as invalid.
1269  * Reports error if any of the lnor spaces change after rebuilding, meaning that all the possible
1270  * lnor spaces to be rebuilt were not correctly marked.
1271  */
1272 #ifndef NDEBUG
1273 void BM_lnorspace_err(BMesh *bm)
1274 {
1275         bm->spacearr_dirty |= BM_SPACEARR_DIRTY_ALL;
1276         bool clear = true;
1277
1278         MLoopNorSpaceArray *temp = MEM_callocN(sizeof(*temp), __func__);
1279         temp->lspacearr = NULL;
1280
1281         BKE_lnor_spacearr_init(temp, bm->totloop, MLNOR_SPACEARR_BMLOOP_PTR);
1282
1283         int cd_loop_clnors_offset = CustomData_get_offset(&bm->ldata, CD_CUSTOMLOOPNORMAL);
1284         float(*lnors)[3] = MEM_callocN(sizeof(*lnors) * bm->totloop, __func__);
1285         BM_loops_calc_normal_vcos(bm, NULL, NULL, NULL, true, M_PI, lnors, temp, NULL, cd_loop_clnors_offset, true);
1286
1287         for (int i = 0; i < bm->totloop; i++) {
1288                 int j = 0;
1289                 j += compare_ff(temp->lspacearr[i]->ref_alpha, bm->lnor_spacearr->lspacearr[i]->ref_alpha, 1e-4f);
1290                 j += compare_ff(temp->lspacearr[i]->ref_beta, bm->lnor_spacearr->lspacearr[i]->ref_beta, 1e-4f);
1291                 j += compare_v3v3(temp->lspacearr[i]->vec_lnor, bm->lnor_spacearr->lspacearr[i]->vec_lnor, 1e-4f);
1292                 j += compare_v3v3(temp->lspacearr[i]->vec_ortho, bm->lnor_spacearr->lspacearr[i]->vec_ortho, 1e-4f);
1293                 j += compare_v3v3(temp->lspacearr[i]->vec_ref, bm->lnor_spacearr->lspacearr[i]->vec_ref, 1e-4f);
1294
1295                 if (j != 5) {
1296                         clear = false;
1297                         break;
1298                 }
1299         }
1300         BKE_lnor_spacearr_free(temp);
1301         MEM_freeN(temp);
1302         MEM_freeN(lnors);
1303         BLI_assert(clear);
1304
1305         bm->spacearr_dirty &= ~BM_SPACEARR_DIRTY_ALL;
1306 }
1307 #endif
1308
1309 static void bm_loop_normal_mark_indiv_do_loop(
1310         BMLoop *l, BLI_bitmap *loops, MLoopNorSpaceArray *lnor_spacearr, int *totloopsel)
1311 {
1312         if (l != NULL) {
1313                 const int l_idx = BM_elem_index_get(l);
1314
1315                 if (!BLI_BITMAP_TEST(loops, BM_elem_index_get(l))) {
1316                         /* If vert and face selected share a loop, mark it for editing. */
1317                         BLI_BITMAP_ENABLE(loops, l_idx);
1318                         (*totloopsel)++;
1319
1320                         /* Mark all loops in same loop normal space (aka smooth fan). */
1321                         if ((lnor_spacearr->lspacearr[l_idx]->flags & MLNOR_SPACE_IS_SINGLE) == 0) {
1322                                 for (LinkNode *node = lnor_spacearr->lspacearr[l_idx]->loops; node; node = node->next) {
1323                                         const int lfan_idx = BM_elem_index_get((BMLoop *)node->link);
1324                                         if (!BLI_BITMAP_TEST(loops, lfan_idx)) {
1325                                                 BLI_BITMAP_ENABLE(loops, lfan_idx);
1326                                                 (*totloopsel)++;
1327                                         }
1328                                 }
1329                         }
1330                 }
1331         }
1332 }
1333
1334 /* Mark the individual clnors to be edited, if multiple selection methods are used. */
1335 static int bm_loop_normal_mark_indiv(BMesh *bm, BLI_bitmap *loops)
1336 {
1337         BMEditSelection *ese, *ese_prev;
1338         int totloopsel = 0;
1339
1340         BM_mesh_elem_index_ensure(bm, BM_LOOP);
1341
1342         BLI_assert(bm->lnor_spacearr != NULL);
1343         BLI_assert(bm->lnor_spacearr->data_type == MLNOR_SPACEARR_BMLOOP_PTR);
1344
1345         /* Goes from last selected to the first selected element. */
1346         for (ese = bm->selected.last; ese; ese = ese->prev) {
1347                 if (ese->htype == BM_FACE) {
1348                         ese_prev = ese;
1349                         /* If current face is selected, then any verts to be edited must have been selected before it. */
1350                         while ((ese_prev = ese_prev->prev)) {
1351                                 if (ese_prev->htype == BM_VERT) {
1352                                         bm_loop_normal_mark_indiv_do_loop(
1353                                                 BM_face_vert_share_loop((BMFace *)ese->ele, (BMVert *)ese_prev->ele),
1354                                                 loops, bm->lnor_spacearr, &totloopsel);
1355                                 }
1356                                 else if (ese_prev->htype == BM_EDGE) {
1357                                         bm_loop_normal_mark_indiv_do_loop(
1358                                                 BM_face_vert_share_loop((BMFace *)ese->ele, ((BMEdge *)ese_prev->ele)->v1),
1359                                                 loops, bm->lnor_spacearr, &totloopsel);
1360
1361                                         bm_loop_normal_mark_indiv_do_loop(
1362                                                 BM_face_vert_share_loop((BMFace *)ese->ele, ((BMEdge *)ese_prev->ele)->v2),
1363                                                 loops, bm->lnor_spacearr, &totloopsel);
1364                                 }
1365                         }
1366                 }
1367         }
1368
1369         return totloopsel;
1370 }
1371
1372 static void loop_normal_editdata_init(BMesh *bm, BMLoopNorEditData *lnor_ed, BMVert *v, BMLoop *l, const int offset)
1373 {
1374         BLI_assert(bm->lnor_spacearr != NULL);
1375         BLI_assert(bm->lnor_spacearr->lspacearr != NULL);
1376
1377         const int l_index = BM_elem_index_get(l);
1378         short *clnors_data = BM_ELEM_CD_GET_VOID_P(l, offset);
1379
1380         lnor_ed->loop_index = l_index;
1381         lnor_ed->loop = l;
1382
1383         float custom_normal[3];
1384         BKE_lnor_space_custom_data_to_normal(bm->lnor_spacearr->lspacearr[l_index], clnors_data, custom_normal);
1385
1386         lnor_ed->clnors_data = clnors_data;
1387         copy_v3_v3(lnor_ed->nloc, custom_normal);
1388         copy_v3_v3(lnor_ed->niloc, custom_normal);
1389
1390         lnor_ed->loc = v->co;
1391 }
1392
1393 BMLoopNorEditDataArray *BM_loop_normal_editdata_array_init(BMesh *bm)
1394 {
1395         BMLoop *l;
1396         BMVert *v;
1397         BMIter liter, viter;
1398
1399         bool verts = (bm->selectmode & SCE_SELECT_VERTEX) != 0;
1400         bool edges = (bm->selectmode & SCE_SELECT_EDGE) != 0;
1401         bool faces = (bm->selectmode & SCE_SELECT_FACE) != 0;
1402         int totloopsel = 0;
1403
1404         BLI_assert(bm->spacearr_dirty == 0);
1405
1406         BMLoopNorEditDataArray *lnors_ed_arr = MEM_mallocN(
1407                 sizeof(*lnors_ed_arr), __func__);
1408         lnors_ed_arr->lidx_to_lnor_editdata = MEM_callocN(
1409                 sizeof(*lnors_ed_arr->lidx_to_lnor_editdata) * bm->totloop, __func__);
1410
1411         if (!CustomData_has_layer(&bm->ldata, CD_CUSTOMLOOPNORMAL)) {
1412                 BM_data_layer_add(bm, &bm->ldata, CD_CUSTOMLOOPNORMAL);
1413         }
1414         const int cd_custom_normal_offset = CustomData_get_offset(&bm->ldata, CD_CUSTOMLOOPNORMAL);
1415
1416         BM_mesh_elem_index_ensure(bm, BM_LOOP);
1417
1418         BLI_bitmap *loops = BLI_BITMAP_NEW(bm->totloop, __func__);
1419         if (faces && (verts || edges)) {
1420                 /* More than one selection mode, check for individual normals to edit. */
1421                 totloopsel = bm_loop_normal_mark_indiv(bm, loops);
1422         }
1423
1424         if (totloopsel) {
1425                 BMLoopNorEditData *lnor_ed = lnors_ed_arr->lnor_editdata = MEM_mallocN(sizeof(*lnor_ed) * totloopsel, __func__);
1426
1427                 BM_ITER_MESH(v, &viter, bm, BM_VERTS_OF_MESH) {
1428                         BM_ITER_ELEM(l, &liter, v, BM_LOOPS_OF_VERT) {
1429                                 if (BLI_BITMAP_TEST(loops, BM_elem_index_get(l))) {
1430                                         loop_normal_editdata_init(bm, lnor_ed, v, l, cd_custom_normal_offset);
1431                                         lnors_ed_arr->lidx_to_lnor_editdata[BM_elem_index_get(l)] = lnor_ed;
1432                                         lnor_ed++;
1433                                 }
1434                         }
1435                 }
1436                 lnors_ed_arr->totloop = totloopsel;
1437         }
1438         else {  /* If multiple selection modes are inactive OR no such loop is found, fall back to editing all loops. */
1439                 totloopsel = BM_total_loop_select(bm);
1440                 BMLoopNorEditData *lnor_ed = lnors_ed_arr->lnor_editdata = MEM_mallocN(sizeof(*lnor_ed) * totloopsel, __func__);
1441
1442                 BM_ITER_MESH(v, &viter, bm, BM_VERTS_OF_MESH) {
1443                         if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
1444                                 BM_ITER_ELEM(l, &liter, v, BM_LOOPS_OF_VERT) {
1445                                         loop_normal_editdata_init(bm, lnor_ed, v, l, cd_custom_normal_offset);
1446                                         lnors_ed_arr->lidx_to_lnor_editdata[BM_elem_index_get(l)] = lnor_ed;
1447                                         lnor_ed++;
1448                                 }
1449                         }
1450                 }
1451                 lnors_ed_arr->totloop = totloopsel;
1452         }
1453
1454         MEM_freeN(loops);
1455         lnors_ed_arr->cd_custom_normal_offset = cd_custom_normal_offset;
1456         return lnors_ed_arr;
1457 }
1458
1459 void BM_loop_normal_editdata_array_free(BMLoopNorEditDataArray *lnors_ed_arr)
1460 {
1461         MEM_SAFE_FREE(lnors_ed_arr->lnor_editdata);
1462         MEM_SAFE_FREE(lnors_ed_arr->lidx_to_lnor_editdata);
1463         MEM_freeN(lnors_ed_arr);
1464 }
1465
1466 int BM_total_loop_select(BMesh *bm)
1467 {
1468         int r_sel = 0;
1469         BMVert *v;
1470         BMIter viter;
1471
1472         BM_ITER_MESH(v, &viter, bm, BM_VERTS_OF_MESH) {
1473                 if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
1474                         r_sel += BM_vert_face_count(v);
1475                 }
1476         }
1477         return r_sel;
1478 }
1479
1480 /**
1481  * \brief BMesh Begin Edit
1482  *
1483  * Functions for setting up a mesh for editing and cleaning up after
1484  * the editing operations are done. These are called by the tools/operator
1485  * API for each time a tool is executed.
1486  */
1487 void bmesh_edit_begin(BMesh *UNUSED(bm), BMOpTypeFlag UNUSED(type_flag))
1488 {
1489         /* Most operators seem to be using BMO_OPTYPE_FLAG_UNTAN_MULTIRES to change the MDisps to
1490          * absolute space during mesh edits. With this enabled, changes to the topology
1491          * (loop cuts, edge subdivides, etc) are not reflected in the higher levels of
1492          * the mesh at all, which doesn't seem right. Turning off completely for now,
1493          * until this is shown to be better for certain types of mesh edits. */
1494 #ifdef BMOP_UNTAN_MULTIRES_ENABLED
1495         /* switch multires data out of tangent space */
1496         if ((type_flag & BMO_OPTYPE_FLAG_UNTAN_MULTIRES) && CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
1497                 bmesh_mdisps_space_set(bm, MULTIRES_SPACE_TANGENT, MULTIRES_SPACE_ABSOLUTE);
1498
1499                 /* ensure correct normals, if possible */
1500                 bmesh_rationalize_normals(bm, 0);
1501                 BM_mesh_normals_update(bm);
1502         }
1503 #endif
1504 }
1505
1506 /**
1507  * \brief BMesh End Edit
1508  */
1509 void bmesh_edit_end(BMesh *bm, BMOpTypeFlag type_flag)
1510 {
1511         ListBase select_history;
1512
1513         /* BMO_OPTYPE_FLAG_UNTAN_MULTIRES disabled for now, see comment above in bmesh_edit_begin. */
1514 #ifdef BMOP_UNTAN_MULTIRES_ENABLED
1515         /* switch multires data into tangent space */
1516         if ((flag & BMO_OPTYPE_FLAG_UNTAN_MULTIRES) && CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
1517                 /* set normals to their previous winding */
1518                 bmesh_rationalize_normals(bm, 1);
1519                 bmesh_mdisps_space_set(bm, MULTIRES_SPACE_ABSOLUTE, MULTIRES_SPACE_TANGENT);
1520         }
1521         else if (flag & BMO_OP_FLAG_RATIONALIZE_NORMALS) {
1522                 bmesh_rationalize_normals(bm, 1);
1523         }
1524 #endif
1525
1526         /* compute normals, clear temp flags and flush selections */
1527         if (type_flag & BMO_OPTYPE_FLAG_NORMALS_CALC) {
1528                 bm->spacearr_dirty |= BM_SPACEARR_DIRTY_ALL;
1529                 BM_mesh_normals_update(bm);
1530         }
1531
1532
1533         if ((type_flag & BMO_OPTYPE_FLAG_SELECT_VALIDATE) == 0) {
1534                 select_history = bm->selected;
1535                 BLI_listbase_clear(&bm->selected);
1536         }
1537
1538         if (type_flag & BMO_OPTYPE_FLAG_SELECT_FLUSH) {
1539                 BM_mesh_select_mode_flush(bm);
1540         }
1541
1542         if ((type_flag & BMO_OPTYPE_FLAG_SELECT_VALIDATE) == 0) {
1543                 bm->selected = select_history;
1544         }
1545         if (type_flag & BMO_OPTYPE_FLAG_INVALIDATE_CLNOR_ALL) {
1546                 bm->spacearr_dirty |= BM_SPACEARR_DIRTY_ALL;
1547         }
1548 }
1549
1550 void BM_mesh_elem_index_ensure_ex(BMesh *bm, const char htype, int elem_offset[4])
1551 {
1552
1553 #ifdef DEBUG
1554         BM_ELEM_INDEX_VALIDATE(bm, "Should Never Fail!", __func__);
1555 #endif
1556
1557         if (elem_offset == NULL) {
1558                 /* Simple case. */
1559                 const char htype_needed = bm->elem_index_dirty & htype;
1560                 if (htype_needed == 0) {
1561                         goto finally;
1562                 }
1563         }
1564
1565         if (htype & BM_VERT) {
1566                 if ((bm->elem_index_dirty & BM_VERT) || (elem_offset && elem_offset[0])) {
1567                         BMIter iter;
1568                         BMElem *ele;
1569
1570                         int index = elem_offset ? elem_offset[0] : 0;
1571                         BM_ITER_MESH (ele, &iter, bm, BM_VERTS_OF_MESH) {
1572                                 BM_elem_index_set(ele, index++); /* set_ok */
1573                         }
1574                         BLI_assert(elem_offset || index == bm->totvert);
1575                 }
1576                 else {
1577                         // printf("%s: skipping vert index calc!\n", __func__);
1578                 }
1579         }
1580
1581         if (htype & BM_EDGE) {
1582                 if ((bm->elem_index_dirty & BM_EDGE) || (elem_offset && elem_offset[1])) {
1583                         BMIter iter;
1584                         BMElem *ele;
1585
1586                         int index = elem_offset ? elem_offset[1] : 0;
1587                         BM_ITER_MESH (ele, &iter, bm, BM_EDGES_OF_MESH) {
1588                                 BM_elem_index_set(ele, index++); /* set_ok */
1589                         }
1590                         BLI_assert(elem_offset || index == bm->totedge);
1591                 }
1592                 else {
1593                         // printf("%s: skipping edge index calc!\n", __func__);
1594                 }
1595         }
1596
1597         if (htype & (BM_FACE | BM_LOOP)) {
1598                 if ((bm->elem_index_dirty & (BM_FACE | BM_LOOP)) || (elem_offset && (elem_offset[2] || elem_offset[3]))) {
1599                         BMIter iter;
1600                         BMElem *ele;
1601
1602                         const bool update_face = (htype & BM_FACE) && (bm->elem_index_dirty & BM_FACE);
1603                         const bool update_loop = (htype & BM_LOOP) && (bm->elem_index_dirty & BM_LOOP);
1604
1605                         int index_loop = elem_offset ? elem_offset[2] : 0;
1606                         int index = elem_offset ? elem_offset[3] : 0;
1607
1608                         BM_ITER_MESH (ele, &iter, bm, BM_FACES_OF_MESH) {
1609                                 if (update_face) {
1610                                         BM_elem_index_set(ele, index++); /* set_ok */
1611                                 }
1612
1613                                 if (update_loop) {
1614                                         BMLoop *l_iter, *l_first;
1615
1616                                         l_iter = l_first = BM_FACE_FIRST_LOOP((BMFace *)ele);
1617                                         do {
1618                                                 BM_elem_index_set(l_iter, index_loop++); /* set_ok */
1619                                         } while ((l_iter = l_iter->next) != l_first);
1620                                 }
1621                         }
1622
1623                         BLI_assert(elem_offset || !update_face || index == bm->totface);
1624                         if (update_loop) {
1625                                 BLI_assert(elem_offset || !update_loop || index_loop == bm->totloop);
1626                         }
1627                 }
1628                 else {
1629                         // printf("%s: skipping face/loop index calc!\n", __func__);
1630                 }
1631         }
1632
1633 finally:
1634         bm->elem_index_dirty &= ~htype;
1635         if (elem_offset) {
1636                 if (htype & BM_VERT) {
1637                         elem_offset[0] += bm->totvert;
1638                         if (elem_offset[0] != bm->totvert) {
1639                                 bm->elem_index_dirty |= BM_VERT;
1640                         }
1641                 }
1642                 if (htype & BM_EDGE) {
1643                         elem_offset[1] += bm->totedge;
1644                         if (elem_offset[1] != bm->totedge) {
1645                                 bm->elem_index_dirty |= BM_EDGE;
1646                         }
1647                 }
1648                 if (htype & BM_LOOP) {
1649                         elem_offset[2] += bm->totloop;
1650                         if (elem_offset[2] != bm->totloop) {
1651                                 bm->elem_index_dirty |= BM_LOOP;
1652                         }
1653                 }
1654                 if (htype & BM_FACE) {
1655                         elem_offset[3] += bm->totface;
1656                         if (elem_offset[3] != bm->totface) {
1657                                 bm->elem_index_dirty |= BM_FACE;
1658                         }
1659                 }
1660         }
1661 }
1662
1663 void BM_mesh_elem_index_ensure(BMesh *bm, const char htype)
1664 {
1665         BM_mesh_elem_index_ensure_ex(bm, htype, NULL);
1666 }
1667
1668
1669 /**
1670  * Array checking/setting macros
1671  *
1672  * Currently vert/edge/loop/face index data is being abused, in a few areas of the code.
1673  *
1674  * To avoid correcting them afterwards, set 'bm->elem_index_dirty' however its possible
1675  * this flag is set incorrectly which could crash blender.
1676  *
1677  * These functions ensure its correct and are called more often in debug mode.
1678  */
1679
1680 void BM_mesh_elem_index_validate(
1681         BMesh *bm, const char *location, const char *func,
1682         const char *msg_a, const char *msg_b)
1683 {
1684         const char iter_types[3] = {BM_VERTS_OF_MESH,
1685                                     BM_EDGES_OF_MESH,
1686                                     BM_FACES_OF_MESH};
1687
1688         const char flag_types[3] = {BM_VERT, BM_EDGE, BM_FACE};
1689         const char *type_names[3] = {"vert", "edge", "face"};
1690
1691         BMIter iter;
1692         BMElem *ele;
1693         int i;
1694         bool is_any_error = 0;
1695
1696         for (i = 0; i < 3; i++) {
1697                 const bool is_dirty = (flag_types[i] & bm->elem_index_dirty) != 0;
1698                 int index = 0;
1699                 bool is_error = false;
1700                 int err_val = 0;
1701                 int err_idx = 0;
1702
1703                 BM_ITER_MESH (ele, &iter, bm, iter_types[i]) {
1704                         if (!is_dirty) {
1705                                 if (BM_elem_index_get(ele) != index) {
1706                                         err_val = BM_elem_index_get(ele);
1707                                         err_idx = index;
1708                                         is_error = true;
1709                                 }
1710                         }
1711
1712                         BM_elem_index_set(ele, index); /* set_ok */
1713                         index++;
1714                 }
1715
1716                 if ((is_error == true) && (is_dirty == false)) {
1717                         is_any_error = true;
1718                         fprintf(stderr,
1719                                 "Invalid Index: at %s, %s, %s[%d] invalid index %d, '%s', '%s'\n",
1720                                 location, func, type_names[i], err_idx, err_val, msg_a, msg_b);
1721                 }
1722                 else if ((is_error == false) && (is_dirty == true)) {
1723
1724 #if 0       /* mostly annoying */
1725
1726                         /* dirty may have been incorrectly set */
1727                         fprintf(stderr,
1728                                 "Invalid Dirty: at %s, %s (%s), dirty flag was set but all index values are correct, '%s', '%s'\n",
1729                                 location, func, type_names[i], msg_a, msg_b);
1730 #endif
1731                 }
1732         }
1733
1734 #if 0 /* mostly annoying, even in debug mode */
1735 #ifdef DEBUG
1736         if (is_any_error == 0) {
1737                 fprintf(stderr,
1738                         "Valid Index Success: at %s, %s, '%s', '%s'\n",
1739                         location, func, msg_a, msg_b);
1740         }
1741 #endif
1742 #endif
1743         (void) is_any_error; /* shut up the compiler */
1744
1745 }
1746
1747 /* debug check only - no need to optimize */
1748 #ifndef NDEBUG
1749 bool BM_mesh_elem_table_check(BMesh *bm)
1750 {
1751         BMIter iter;
1752         BMElem *ele;
1753         int i;
1754
1755         if (bm->vtable && ((bm->elem_table_dirty & BM_VERT) == 0)) {
1756                 BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, i) {
1757                         if (ele != (BMElem *)bm->vtable[i]) {
1758                                 return false;
1759                         }
1760                 }
1761         }
1762
1763         if (bm->etable && ((bm->elem_table_dirty & BM_EDGE) == 0)) {
1764                 BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, i) {
1765                         if (ele != (BMElem *)bm->etable[i]) {
1766                                 return false;
1767                         }
1768                 }
1769         }
1770
1771         if (bm->ftable && ((bm->elem_table_dirty & BM_FACE) == 0)) {
1772                 BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, i) {
1773                         if (ele != (BMElem *)bm->ftable[i]) {
1774                                 return false;
1775                         }
1776                 }
1777         }
1778
1779         return true;
1780 }
1781 #endif
1782
1783
1784
1785 void BM_mesh_elem_table_ensure(BMesh *bm, const char htype)
1786 {
1787         /* assume if the array is non-null then its valid and no need to recalc */
1788         const char htype_needed = (((bm->vtable && ((bm->elem_table_dirty & BM_VERT) == 0)) ? 0 : BM_VERT) |
1789                                    ((bm->etable && ((bm->elem_table_dirty & BM_EDGE) == 0)) ? 0 : BM_EDGE) |
1790                                    ((bm->ftable && ((bm->elem_table_dirty & BM_FACE) == 0)) ? 0 : BM_FACE)) & htype;
1791
1792         BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
1793
1794         /* in debug mode double check we didn't need to recalculate */
1795         BLI_assert(BM_mesh_elem_table_check(bm) == true);
1796
1797         if (htype_needed == 0) {
1798                 goto finally;
1799         }
1800
1801         if (htype_needed & BM_VERT) {
1802                 if (bm->vtable && bm->totvert <= bm->vtable_tot && bm->totvert * 2 >= bm->vtable_tot) {
1803                         /* pass (re-use the array) */
1804                 }
1805                 else {
1806                         if (bm->vtable)
1807                                 MEM_freeN(bm->vtable);
1808                         bm->vtable = MEM_mallocN(sizeof(void **) * bm->totvert, "bm->vtable");
1809                         bm->vtable_tot = bm->totvert;
1810                 }
1811         }
1812         if (htype_needed & BM_EDGE) {
1813                 if (bm->etable && bm->totedge <= bm->etable_tot && bm->totedge * 2 >= bm->etable_tot) {
1814                         /* pass (re-use the array) */
1815                 }
1816                 else {
1817                         if (bm->etable)
1818                                 MEM_freeN(bm->etable);
1819                         bm->etable = MEM_mallocN(sizeof(void **) * bm->totedge, "bm->etable");
1820                         bm->etable_tot = bm->totedge;
1821                 }
1822         }
1823         if (htype_needed & BM_FACE) {
1824                 if (bm->ftable && bm->totface <= bm->ftable_tot && bm->totface * 2 >= bm->ftable_tot) {
1825                         /* pass (re-use the array) */
1826                 }
1827                 else {
1828                         if (bm->ftable)
1829                                 MEM_freeN(bm->ftable);
1830                         bm->ftable = MEM_mallocN(sizeof(void **) * bm->totface, "bm->ftable");
1831                         bm->ftable_tot = bm->totface;
1832                 }
1833         }
1834
1835         if (htype_needed & BM_VERT) {
1836                 BM_iter_as_array(bm, BM_VERTS_OF_MESH, NULL, (void **)bm->vtable, bm->totvert);
1837         }
1838
1839         if (htype_needed & BM_EDGE) {
1840                 BM_iter_as_array(bm, BM_EDGES_OF_MESH, NULL, (void **)bm->etable, bm->totedge);
1841         }
1842
1843         if (htype_needed & BM_FACE) {
1844                 BM_iter_as_array(bm, BM_FACES_OF_MESH, NULL, (void **)bm->ftable, bm->totface);
1845         }
1846
1847 finally:
1848         /* Only clear dirty flags when all the pointers and data are actually valid.
1849          * This prevents possible threading issues when dirty flag check failed but
1850          * data wasn't ready still.
1851          */
1852         bm->elem_table_dirty &= ~htype_needed;
1853 }
1854
1855 /* use BM_mesh_elem_table_ensure where possible to avoid full rebuild */
1856 void BM_mesh_elem_table_init(BMesh *bm, const char htype)
1857 {
1858         BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
1859
1860         /* force recalc */
1861         BM_mesh_elem_table_free(bm, BM_ALL_NOLOOP);
1862         BM_mesh_elem_table_ensure(bm, htype);
1863 }
1864
1865 void BM_mesh_elem_table_free(BMesh *bm, const char htype)
1866 {
1867         if (htype & BM_VERT) {
1868                 MEM_SAFE_FREE(bm->vtable);
1869         }
1870
1871         if (htype & BM_EDGE) {
1872                 MEM_SAFE_FREE(bm->etable);
1873         }
1874
1875         if (htype & BM_FACE) {
1876                 MEM_SAFE_FREE(bm->ftable);
1877         }
1878 }
1879
1880 BMVert *BM_vert_at_index_find(BMesh *bm, const int index)
1881 {
1882         return BLI_mempool_findelem(bm->vpool, index);
1883 }
1884
1885 BMEdge *BM_edge_at_index_find(BMesh *bm, const int index)
1886 {
1887         return BLI_mempool_findelem(bm->epool, index);
1888 }
1889
1890 BMFace *BM_face_at_index_find(BMesh *bm, const int index)
1891 {
1892         return BLI_mempool_findelem(bm->fpool, index);
1893 }
1894
1895 /**
1896  * Use lookup table when available, else use slower find functions.
1897  *
1898  * \note Try to use #BM_mesh_elem_table_ensure instead.
1899  */
1900 BMVert *BM_vert_at_index_find_or_table(BMesh *bm, const int index)
1901 {
1902         if ((bm->elem_table_dirty & BM_VERT) == 0) {
1903                 return (index < bm->totvert) ? bm->vtable[index] : NULL;
1904         }
1905         else {
1906                 return BM_vert_at_index_find(bm, index);
1907         }
1908 }
1909
1910 BMEdge *BM_edge_at_index_find_or_table(BMesh *bm, const int index)
1911 {
1912         if ((bm->elem_table_dirty & BM_EDGE) == 0) {
1913                 return (index < bm->totedge) ? bm->etable[index] : NULL;
1914         }
1915         else {
1916                 return BM_edge_at_index_find(bm, index);
1917         }
1918 }
1919
1920 BMFace *BM_face_at_index_find_or_table(BMesh *bm, const int index)
1921 {
1922         if ((bm->elem_table_dirty & BM_FACE) == 0) {
1923                 return (index < bm->totface) ? bm->ftable[index] : NULL;
1924         }
1925         else {
1926                 return BM_face_at_index_find(bm, index);
1927         }
1928 }
1929
1930
1931 /**
1932  * Return the amount of element of type 'type' in a given bmesh.
1933  */
1934 int BM_mesh_elem_count(BMesh *bm, const char htype)
1935 {
1936         BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
1937
1938         switch (htype) {
1939                 case BM_VERT: return bm->totvert;
1940                 case BM_EDGE: return bm->totedge;
1941                 case BM_FACE: return bm->totface;
1942                 default:
1943                 {
1944                         BLI_assert(0);
1945                         return 0;
1946                 }
1947         }
1948 }
1949
1950
1951 /**
1952  * Remaps the vertices, edges and/or faces of the bmesh as indicated by vert/edge/face_idx arrays
1953  * (xxx_idx[org_index] = new_index).
1954  *
1955  * A NULL array means no changes.
1956  *
1957  * Note: - Does not mess with indices, just sets elem_index_dirty flag.
1958  *       - For verts/edges/faces only (as loops must remain "ordered" and "aligned"
1959  *         on a per-face basis...).
1960  *
1961  * WARNING: Be careful if you keep pointers to affected BM elements, or arrays, when using this func!
1962  */
1963 void BM_mesh_remap(
1964         BMesh *bm,
1965         const uint *vert_idx,
1966         const uint *edge_idx,
1967         const uint *face_idx)
1968 {
1969         /* Mapping old to new pointers. */
1970         GHash *vptr_map = NULL, *eptr_map = NULL, *fptr_map = NULL;
1971         BMIter iter, iterl;
1972         BMVert *ve;
1973         BMEdge *ed;
1974         BMFace *fa;
1975         BMLoop *lo;
1976
1977         if (!(vert_idx || edge_idx || face_idx))
1978                 return;
1979
1980         BM_mesh_elem_table_ensure(
1981                 bm,
1982                 (vert_idx ? BM_VERT : 0) |
1983                 (edge_idx ? BM_EDGE : 0) |
1984                 (face_idx ? BM_FACE : 0));
1985
1986         /* Remap Verts */
1987         if (vert_idx) {
1988                 BMVert **verts_pool, *verts_copy, **vep;
1989                 int i, totvert = bm->totvert;
1990                 const uint *new_idx;
1991                 /* Special case: Python uses custom - data layers to hold PyObject references.
1992                  * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
1993                 const int cd_vert_pyptr  = CustomData_get_offset(&bm->vdata, CD_BM_ELEM_PYPTR);
1994
1995                 /* Init the old-to-new vert pointers mapping */
1996                 vptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap vert pointers mapping", bm->totvert);
1997
1998                 /* Make a copy of all vertices. */
1999                 verts_pool = bm->vtable;
2000                 verts_copy = MEM_mallocN(sizeof(BMVert) * totvert, "BM_mesh_remap verts copy");
2001                 void **pyptrs = (cd_vert_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totvert, __func__) : NULL;
2002                 for (i = totvert, ve = verts_copy + totvert - 1, vep = verts_pool + totvert - 1; i--; ve--, vep--) {
2003                         *ve = **vep;
2004 /*                      printf("*vep: %p, verts_pool[%d]: %p\n", *vep, i, verts_pool[i]);*/
2005                         if (cd_vert_pyptr != -1) {
2006                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)ve), cd_vert_pyptr);
2007                                 pyptrs[i] = *pyptr;
2008                         }
2009                 }
2010
2011                 /* Copy back verts to their new place, and update old2new pointers mapping. */
2012                 new_idx = vert_idx + totvert - 1;
2013                 ve = verts_copy + totvert - 1;
2014                 vep = verts_pool + totvert - 1; /* old, org pointer */
2015                 for (i = totvert; i--; new_idx--, ve--, vep--) {
2016                         BMVert *new_vep = verts_pool[*new_idx];
2017                         *new_vep = *ve;
2018 /*                      printf("mapping vert from %d to %d (%p/%p to %p)\n", i, *new_idx, *vep, verts_pool[i], new_vep);*/
2019                         BLI_ghash_insert(vptr_map, *vep, new_vep);
2020                         if (cd_vert_pyptr != -1) {
2021                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_vep), cd_vert_pyptr);
2022                                 *pyptr = pyptrs[*new_idx];
2023                         }
2024                 }
2025                 bm->elem_index_dirty |= BM_VERT;
2026                 bm->elem_table_dirty |= BM_VERT;
2027
2028                 MEM_freeN(verts_copy);
2029                 if (pyptrs) {
2030                         MEM_freeN(pyptrs);
2031                 }
2032         }
2033
2034         /* Remap Edges */
2035         if (edge_idx) {
2036                 BMEdge **edges_pool, *edges_copy, **edp;
2037                 int i, totedge = bm->totedge;
2038                 const uint *new_idx;
2039                 /* Special case: Python uses custom - data layers to hold PyObject references.
2040                  * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
2041                 const int cd_edge_pyptr  = CustomData_get_offset(&bm->edata, CD_BM_ELEM_PYPTR);
2042
2043                 /* Init the old-to-new vert pointers mapping */
2044                 eptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap edge pointers mapping", bm->totedge);
2045
2046                 /* Make a copy of all vertices. */
2047                 edges_pool = bm->etable;
2048                 edges_copy = MEM_mallocN(sizeof(BMEdge) * totedge, "BM_mesh_remap edges copy");
2049                 void **pyptrs = (cd_edge_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totedge, __func__) : NULL;
2050                 for (i = totedge, ed = edges_copy + totedge - 1, edp = edges_pool + totedge - 1; i--; ed--, edp--) {
2051                         *ed = **edp;
2052                         if (cd_edge_pyptr != -1) {
2053                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)ed), cd_edge_pyptr);
2054                                 pyptrs[i] = *pyptr;
2055                         }
2056                 }
2057
2058                 /* Copy back verts to their new place, and update old2new pointers mapping. */
2059                 new_idx = edge_idx + totedge - 1;
2060                 ed = edges_copy + totedge - 1;
2061                 edp = edges_pool + totedge - 1; /* old, org pointer */
2062                 for (i = totedge; i--; new_idx--, ed--, edp--) {
2063                         BMEdge *new_edp = edges_pool[*new_idx];
2064                         *new_edp = *ed;
2065                         BLI_ghash_insert(eptr_map, *edp, new_edp);
2066 /*                      printf("mapping edge from %d to %d (%p/%p to %p)\n", i, *new_idx, *edp, edges_pool[i], new_edp);*/
2067                         if (cd_edge_pyptr != -1) {
2068                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_edp), cd_edge_pyptr);
2069                                 *pyptr = pyptrs[*new_idx];
2070                         }
2071                 }
2072                 bm->elem_index_dirty |= BM_EDGE;
2073                 bm->elem_table_dirty |= BM_EDGE;
2074
2075                 MEM_freeN(edges_copy);
2076                 if (pyptrs) {
2077                         MEM_freeN(pyptrs);
2078                 }
2079         }
2080
2081         /* Remap Faces */
2082         if (face_idx) {
2083                 BMFace **faces_pool, *faces_copy, **fap;
2084                 int i, totface = bm->totface;
2085                 const uint *new_idx;
2086                 /* Special case: Python uses custom - data layers to hold PyObject references.
2087                  * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
2088                 const int cd_poly_pyptr  = CustomData_get_offset(&bm->pdata, CD_BM_ELEM_PYPTR);
2089
2090                 /* Init the old-to-new vert pointers mapping */
2091                 fptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap face pointers mapping", bm->totface);
2092
2093                 /* Make a copy of all vertices. */
2094                 faces_pool = bm->ftable;
2095                 faces_copy = MEM_mallocN(sizeof(BMFace) * totface, "BM_mesh_remap faces copy");
2096                 void **pyptrs = (cd_poly_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totface, __func__) : NULL;
2097                 for (i = totface, fa = faces_copy + totface - 1, fap = faces_pool + totface - 1; i--; fa--, fap--) {
2098                         *fa = **fap;
2099                         if (cd_poly_pyptr != -1) {
2100                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)fa), cd_poly_pyptr);
2101                                 pyptrs[i] = *pyptr;
2102                         }
2103                 }
2104
2105                 /* Copy back verts to their new place, and update old2new pointers mapping. */
2106                 new_idx = face_idx + totface - 1;
2107                 fa = faces_copy + totface - 1;
2108                 fap = faces_pool + totface - 1; /* old, org pointer */
2109                 for (i = totface; i--; new_idx--, fa--, fap--) {
2110                         BMFace *new_fap = faces_pool[*new_idx];
2111                         *new_fap = *fa;
2112                         BLI_ghash_insert(fptr_map, *fap, new_fap);
2113                         if (cd_poly_pyptr != -1) {
2114                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_fap), cd_poly_pyptr);
2115                                 *pyptr = pyptrs[*new_idx];
2116                         }
2117                 }
2118
2119                 bm->elem_index_dirty |= BM_FACE | BM_LOOP;
2120                 bm->elem_table_dirty |= BM_FACE;
2121
2122                 MEM_freeN(faces_copy);
2123                 if (pyptrs) {
2124                         MEM_freeN(pyptrs);
2125                 }
2126         }
2127
2128         /* And now, fix all vertices/edges/faces/loops pointers! */
2129         /* Verts' pointers, only edge pointers... */
2130         if (eptr_map) {
2131                 BM_ITER_MESH (ve, &iter, bm, BM_VERTS_OF_MESH) {
2132 /*                      printf("Vert e: %p -> %p\n", ve->e, BLI_ghash_lookup(eptr_map, ve->e));*/
2133                         if (ve->e) {
2134                                 ve->e = BLI_ghash_lookup(eptr_map, ve->e);
2135                                 BLI_assert(ve->e);
2136                         }
2137                 }
2138         }
2139
2140         /* Edges' pointers, only vert pointers (as we don't mess with loops!), and - ack! - edge pointers,
2141          * as we have to handle disklinks... */
2142         if (vptr_map || eptr_map) {
2143                 BM_ITER_MESH (ed, &iter, bm, BM_EDGES_OF_MESH) {
2144                         if (vptr_map) {
2145 /*                              printf("Edge v1: %p -> %p\n", ed->v1, BLI_ghash_lookup(vptr_map, ed->v1));*/
2146 /*                              printf("Edge v2: %p -> %p\n", ed->v2, BLI_ghash_lookup(vptr_map, ed->v2));*/
2147                                 ed->v1 = BLI_ghash_lookup(vptr_map, ed->v1);
2148                                 ed->v2 = BLI_ghash_lookup(vptr_map, ed->v2);
2149                                 BLI_assert(ed->v1);
2150                                 BLI_assert(ed->v2);
2151                         }
2152                         if (eptr_map) {
2153 /*                              printf("Edge v1_disk_link prev: %p -> %p\n", ed->v1_disk_link.prev,*/
2154 /*                                     BLI_ghash_lookup(eptr_map, ed->v1_disk_link.prev));*/
2155 /*                              printf("Edge v1_disk_link next: %p -> %p\n", ed->v1_disk_link.next,*/
2156 /*                                     BLI_ghash_lookup(eptr_map, ed->v1_disk_link.next));*/
2157 /*                              printf("Edge v2_disk_link prev: %p -> %p\n", ed->v2_disk_link.prev,*/
2158 /*                                     BLI_ghash_lookup(eptr_map, ed->v2_disk_link.prev));*/
2159 /*                              printf("Edge v2_disk_link next: %p -> %p\n", ed->v2_disk_link.next,*/
2160 /*                                     BLI_ghash_lookup(eptr_map, ed->v2_disk_link.next));*/
2161                                 ed->v1_disk_link.prev = BLI_ghash_lookup(eptr_map, ed->v1_disk_link.prev);
2162                                 ed->v1_disk_link.next = BLI_ghash_lookup(eptr_map, ed->v1_disk_link.next);
2163                                 ed->v2_disk_link.prev = BLI_ghash_lookup(eptr_map, ed->v2_disk_link.prev);
2164                                 ed->v2_disk_link.next = BLI_ghash_lookup(eptr_map, ed->v2_disk_link.next);
2165                                 BLI_assert(ed->v1_disk_link.prev);
2166                                 BLI_assert(ed->v1_disk_link.next);
2167                                 BLI_assert(ed->v2_disk_link.prev);
2168                                 BLI_assert(ed->v2_disk_link.next);
2169                         }
2170                 }
2171         }
2172
2173         /* Faces' pointers (loops, in fact), always needed... */
2174         BM_ITER_MESH (fa, &iter, bm, BM_FACES_OF_MESH) {
2175                 BM_ITER_ELEM (lo, &iterl, fa, BM_LOOPS_OF_FACE) {
2176                         if (vptr_map) {
2177 /*                              printf("Loop v: %p -> %p\n", lo->v, BLI_ghash_lookup(vptr_map, lo->v));*/
2178                                 lo->v = BLI_ghash_lookup(vptr_map, lo->v);
2179                                 BLI_assert(lo->v);
2180                         }
2181                         if (eptr_map) {
2182 /*                              printf("Loop e: %p -> %p\n", lo->e, BLI_ghash_lookup(eptr_map, lo->e));*/
2183                                 lo->e = BLI_ghash_lookup(eptr_map, lo->e);
2184                                 BLI_assert(lo->e);
2185                         }
2186                         if (fptr_map) {
2187 /*                              printf("Loop f: %p -> %p\n", lo->f, BLI_ghash_lookup(fptr_map, lo->f));*/
2188                                 lo->f = BLI_ghash_lookup(fptr_map, lo->f);
2189                                 BLI_assert(lo->f);
2190                         }
2191                 }
2192         }
2193
2194         /* Selection history */
2195         {
2196                 BMEditSelection *ese;
2197                 for (ese = bm->selected.first; ese; ese = ese->next) {
2198                         switch (ese->htype) {
2199                                 case BM_VERT:
2200                                         if (vptr_map) {
2201                                                 ese->ele = BLI_ghash_lookup(vptr_map, ese->ele);
2202                                                 BLI_assert(ese->ele);
2203                                         }
2204                                         break;
2205                                 case BM_EDGE:
2206                                         if (eptr_map) {
2207                                                 ese->ele = BLI_ghash_lookup(eptr_map, ese->ele);
2208                                                 BLI_assert(ese->ele);
2209                                         }
2210                                         break;
2211                                 case BM_FACE:
2212                                         if (fptr_map) {
2213                                                 ese->ele = BLI_ghash_lookup(fptr_map, ese->ele);
2214                                                 BLI_assert(ese->ele);
2215                                         }
2216                                         break;
2217                         }
2218                 }
2219         }
2220
2221         if (fptr_map) {
2222                 if (bm->act_face) {
2223                         bm->act_face = BLI_ghash_lookup(fptr_map, bm->act_face);
2224                         BLI_assert(bm->act_face);
2225                 }
2226         }
2227
2228         if (vptr_map)
2229                 BLI_ghash_free(vptr_map, NULL, NULL);
2230         if (eptr_map)
2231                 BLI_ghash_free(eptr_map, NULL, NULL);
2232         if (fptr_map)
2233                 BLI_ghash_free(fptr_map, NULL, NULL);
2234 }
2235
2236 /**
2237  * Use new memory pools for this mesh.
2238  *
2239  * \note needed for re-sizing elements (adding/removing tool flags)
2240  * but could also be used for packing fragmented bmeshes.
2241  */
2242 void BM_mesh_rebuild(
2243         BMesh *bm, const struct BMeshCreateParams *params,
2244         BLI_mempool *vpool_dst, BLI_mempool *epool_dst, BLI_mempool *lpool_dst, BLI_mempool *fpool_dst)
2245 {
2246         const char remap =
2247                 (vpool_dst ? BM_VERT : 0) |
2248                 (epool_dst ? BM_EDGE : 0) |
2249                 (lpool_dst ? BM_LOOP : 0) |
2250                 (fpool_dst ? BM_FACE : 0);
2251
2252         BMVert **vtable_dst = (remap & BM_VERT) ? MEM_mallocN(bm->totvert * sizeof(BMVert *), __func__) : NULL;
2253         BMEdge **etable_dst = (remap & BM_EDGE) ? MEM_mallocN(bm->totedge * sizeof(BMEdge *), __func__) : NULL;
2254         BMLoop **ltable_dst = (remap & BM_LOOP) ? MEM_mallocN(bm->totloop * sizeof(BMLoop *), __func__) : NULL;
2255         BMFace **ftable_dst = (remap & BM_FACE) ? MEM_mallocN(bm->totface * sizeof(BMFace *), __func__) : NULL;
2256
2257         const bool use_toolflags = params->use_toolflags;
2258
2259         if (remap & BM_VERT) {
2260                 BMIter iter;
2261                 int index;
2262                 BMVert *v_src;
2263                 BM_ITER_MESH_INDEX (v_src, &iter, bm, BM_VERTS_OF_MESH, index) {
2264                         BMVert *v_dst = BLI_mempool_alloc(vpool_dst);
2265                         memcpy(v_dst, v_src, sizeof(BMVert));
2266                         if (use_toolflags) {
2267                                 ((BMVert_OFlag *)v_dst)->oflags = bm->vtoolflagpool ? BLI_mempool_calloc(bm->vtoolflagpool) : NULL;
2268                         }
2269
2270                         vtable_dst[index] = v_dst;
2271                         BM_elem_index_set(v_src, index);  /* set_ok */
2272                 }
2273         }
2274
2275         if (remap & BM_EDGE) {
2276                 BMIter iter;
2277                 int index;
2278                 BMEdge *e_src;
2279                 BM_ITER_MESH_INDEX (e_src, &iter, bm, BM_EDGES_OF_MESH, index) {
2280                         BMEdge *e_dst = BLI_mempool_alloc(epool_dst);
2281                         memcpy(e_dst, e_src, sizeof(BMEdge));
2282                         if (use_toolflags) {
2283                                 ((BMEdge_OFlag *)e_dst)->oflags = bm->etoolflagpool ? BLI_mempool_calloc(bm->etoolflagpool) : NULL;
2284                         }
2285
2286                         etable_dst[index] = e_dst;
2287                         BM_elem_index_set(e_src, index);  /* set_ok */
2288                 }
2289         }
2290
2291         if (remap & (BM_LOOP | BM_FACE)) {
2292                 BMIter iter;
2293                 int index, index_loop = 0;
2294                 BMFace *f_src;
2295                 BM_ITER_MESH_INDEX (f_src, &iter, bm, BM_FACES_OF_MESH, index) {
2296
2297                         if (remap & BM_FACE) {
2298                                 BMFace *f_dst = BLI_mempool_alloc(fpool_dst);
2299                                 memcpy(f_dst, f_src, sizeof(BMFace));
2300                                 if (use_toolflags) {
2301                                         ((BMFace_OFlag *)f_dst)->oflags = bm->ftoolflagpool ? BLI_mempool_calloc(bm->ftoolflagpool) : NULL;
2302                                 }
2303
2304                                 ftable_dst[index] = f_dst;
2305                                 BM_elem_index_set(f_src, index);  /* set_ok */
2306                         }
2307
2308                         /* handle loops */
2309                         if (remap & BM_LOOP) {
2310                                 BMLoop *l_iter_src, *l_first_src;
2311                                 l_iter_src = l_first_src = BM_FACE_FIRST_LOOP((BMFace *)f_src);
2312                                 do {
2313                                         BMLoop *l_dst = BLI_mempool_alloc(lpool_dst);
2314                                         memcpy(l_dst, l_iter_src, sizeof(BMLoop));
2315                                         ltable_dst[index_loop] = l_dst;
2316                                         BM_elem_index_set(l_iter_src, index_loop++); /* set_ok */
2317                                 } while ((l_iter_src = l_iter_src->next) != l_first_src);
2318                         }
2319                 }
2320         }
2321
2322 #define MAP_VERT(ele) vtable_dst[BM_elem_index_get(ele)]
2323 #define MAP_EDGE(ele) etable_dst[BM_elem_index_get(ele)]
2324 #define MAP_LOOP(ele) ltable_dst[BM_elem_index_get(ele)]
2325 #define MAP_FACE(ele) ftable_dst[BM_elem_index_get(ele)]
2326
2327 #define REMAP_VERT(ele) { if (remap & BM_VERT) { ele = MAP_VERT(ele); }} ((void)0)
2328 #define REMAP_EDGE(ele) { if (remap & BM_EDGE) { ele = MAP_EDGE(ele); }} ((void)0)
2329 #define REMAP_LOOP(ele) { if (remap & BM_LOOP) { ele = MAP_LOOP(ele); }} ((void)0)
2330 #define REMAP_FACE(ele) { if (remap & BM_FACE) { ele = MAP_FACE(ele); }} ((void)0)
2331
2332         /* verts */
2333         {
2334                 for (int i = 0; i < bm->totvert; i++) {
2335                         BMVert *v = vtable_dst[i];
2336                         if (v->e) {
2337                                 REMAP_EDGE(v->e);
2338                         }
2339                 }
2340         }
2341
2342         /* edges */
2343         {
2344                 for (int i = 0; i < bm->totedge; i++) {
2345                         BMEdge *e = etable_dst[i];
2346                         REMAP_VERT(e->v1);
2347                         REMAP_VERT(e->v2);
2348                         REMAP_EDGE(e->v1_disk_link.next);
2349                         REMAP_EDGE(e->v1_disk_link.prev);
2350                         REMAP_EDGE(e->v2_disk_link.next);
2351                         REMAP_EDGE(e->v2_disk_link.prev);
2352                         if (e->l) {
2353                                 REMAP_LOOP(e->l);
2354                         }
2355                 }
2356         }
2357
2358         /* faces */
2359         {
2360                 for (int i = 0; i < bm->totface; i++) {
2361                         BMFace *f = ftable_dst[i];
2362                         REMAP_LOOP(f->l_first);
2363
2364                         {
2365                                 BMLoop *l_iter, *l_first;
2366                                 l_iter = l_first = BM_FACE_FIRST_LOOP((BMFace *)f);
2367                                 do {
2368                                         REMAP_VERT(l_iter->v);
2369                                         REMAP_EDGE(l_iter->e);
2370                                         REMAP_FACE(l_iter->f);
2371
2372                                         REMAP_LOOP(l_iter->radial_next);
2373                                         REMAP_LOOP(l_iter->radial_prev);
2374                                         REMAP_LOOP(l_iter->next);
2375                                         REMAP_LOOP(l_iter->prev);
2376                                 } while ((l_iter = l_iter->next) != l_first);
2377                         }
2378                 }
2379         }
2380
2381         for (BMEditSelection *ese = bm->selected.first; ese; ese = ese->next) {
2382                 switch (ese->htype) {
2383                         case BM_VERT:
2384                                 if (remap & BM_VERT) {
2385                                         ese->ele = (BMElem *)MAP_VERT(ese->ele);
2386                                 }
2387                                 break;
2388                         case BM_EDGE:
2389                                 if (remap & BM_EDGE) {
2390                                         ese->ele = (BMElem *)MAP_EDGE(ese->ele);
2391                                 }
2392                                 break;
2393                         case BM_FACE:
2394                                 if (remap & BM_FACE) {
2395                                         ese->ele = (BMElem *)MAP_FACE(ese->ele);
2396                                 }
2397                                 break;
2398                 }
2399         }
2400
2401         if (bm->act_face) {
2402                 REMAP_FACE(bm->act_face);
2403         }
2404
2405 #undef MAP_VERT
2406 #undef MAP_EDGE
2407 #undef MAP_LOOP
2408 #undef MAP_EDGE
2409
2410 #undef REMAP_VERT
2411 #undef REMAP_EDGE
2412 #undef REMAP_LOOP
2413 #undef REMAP_EDGE
2414
2415         /* Cleanup, re-use local tables if the current mesh had tables allocated.
2416          * could use irrespective but it may use more memory then the caller wants (and not be needed). */
2417         if (remap & BM_VERT) {
2418                 if (bm->vtable) {
2419                         SWAP(BMVert **, vtable_dst, bm->vtable);
2420                         bm->vtable_tot = bm->totvert;
2421                         bm->elem_table_dirty &= ~BM_VERT;
2422                 }
2423                 MEM_freeN(vtable_dst);
2424                 BLI_mempool_destroy(bm->vpool);
2425                 bm->vpool = vpool_dst;
2426         }
2427
2428         if (remap & BM_EDGE) {
2429                 if (bm->etable) {
2430                         SWAP(BMEdge **, etable_dst, bm->etable);
2431                         bm->etable_tot = bm->totedge;
2432                         bm->elem_table_dirty &= ~BM_EDGE;
2433                 }
2434                 MEM_freeN(etable_dst);
2435                 BLI_mempool_destroy(bm->epool);
2436                 bm->epool = epool_dst;
2437         }
2438
2439         if (remap & BM_LOOP) {
2440                 /* no loop table */
2441                 MEM_freeN(ltable_dst);
2442                 BLI_mempool_destroy(bm->lpool);
2443                 bm->lpool = lpool_dst;
2444         }
2445
2446         if (remap & BM_FACE) {
2447                 if (bm->ftable) {
2448                         SWAP(BMFace **, ftable_dst, bm->ftable);
2449                         bm->ftable_tot = bm->totface;
2450                         bm->elem_table_dirty &= ~BM_FACE;
2451                 }
2452                 MEM_freeN(ftable_dst);
2453                 BLI_mempool_destroy(bm->fpool);
2454                 bm->fpool = fpool_dst;
2455         }
2456 }
2457
2458 /**
2459  * Re-allocates mesh data with/without toolflags.
2460  */
2461 void BM_mesh_toolflags_set(BMesh *bm, bool use_toolflags)
2462 {
2463         if (bm->use_toolflags == use_toolflags) {
2464                 return;
2465         }
2466
2467         const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_BM(bm);
2468
2469         BLI_mempool *vpool_dst = NULL;
2470         BLI_mempool *epool_dst = NULL;
2471         BLI_mempool *fpool_dst = NULL;
2472
2473         bm_mempool_init_ex(
2474                 &allocsize, use_toolflags,
2475                 &vpool_dst, &epool_dst, NULL, &fpool_dst);
2476
2477         if (use_toolflags == false) {
2478                 BLI_mempool_destroy(bm->vtoolflagpool);
2479                 BLI_mempool_destroy(bm->etoolflagpool);
2480                 BLI_mempool_destroy(bm->ftoolflagpool);
2481
2482                 bm->vtoolflagpool = NULL;
2483                 bm->etoolflagpool = NULL;
2484                 bm->ftoolflagpool = NULL;
2485         }
2486
2487         BM_mesh_rebuild(
2488                 bm,
2489                 &((struct BMeshCreateParams){.use_toolflags = use_toolflags,}),
2490                 vpool_dst, epool_dst, NULL, fpool_dst);
2491
2492         bm->use_toolflags = use_toolflags;
2493 }