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