2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
21 * Contributor(s): Blender Foundation
23 * ***** END GPL LICENSE BLOCK *****
26 /** \file blender/blenkernel/intern/mesh_evaluate.c
29 * Functions to evaluate mesh data.
34 #include "MEM_guardedalloc.h"
36 #include "DNA_object_types.h"
37 #include "DNA_mesh_types.h"
38 #include "DNA_meshdata_types.h"
40 #include "BLI_utildefines.h"
41 #include "BLI_memarena.h"
42 #include "BLI_mempool.h"
44 #include "BLI_edgehash.h"
45 #include "BLI_bitmap.h"
46 #include "BLI_polyfill2d.h"
47 #include "BLI_linklist.h"
48 #include "BLI_linklist_stack.h"
49 #include "BLI_alloca.h"
50 #include "BLI_stack.h"
53 #include "BKE_customdata.h"
55 #include "BKE_multires.h"
56 #include "BKE_report.h"
58 #include "BLI_strict_flags.h"
60 #include "mikktspace.h"
66 # include "PIL_time_utildefines.h"
69 /* -------------------------------------------------------------------- */
71 /** \name Mesh Normal Calculation
75 * Call when there are no polygons.
77 static void mesh_calc_normals_vert_fallback(MVert *mverts, int numVerts)
80 for (i = 0; i < numVerts; i++) {
81 MVert *mv = &mverts[i];
84 normalize_v3_v3(no, mv->co);
85 normal_float_to_short_v3(mv->no, no);
89 /* Calculate vertex and face normals, face normals are returned in *r_faceNors if non-NULL
90 * and vertex normals are stored in actual mverts.
92 void BKE_mesh_calc_normals_mapping(
93 MVert *mverts, int numVerts,
94 const MLoop *mloop, const MPoly *mpolys, int numLoops, int numPolys, float (*r_polyNors)[3],
95 const MFace *mfaces, int numFaces, const int *origIndexFace, float (*r_faceNors)[3])
97 BKE_mesh_calc_normals_mapping_ex(
98 mverts, numVerts, mloop, mpolys,
99 numLoops, numPolys, r_polyNors, mfaces, numFaces,
100 origIndexFace, r_faceNors, false);
102 /* extended version of 'BKE_mesh_calc_normals_poly' with option not to calc vertex normals */
103 void BKE_mesh_calc_normals_mapping_ex(
104 MVert *mverts, int numVerts,
105 const MLoop *mloop, const MPoly *mpolys,
106 int numLoops, int numPolys, float (*r_polyNors)[3],
107 const MFace *mfaces, int numFaces, const int *origIndexFace, float (*r_faceNors)[3],
108 const bool only_face_normals)
110 float (*pnors)[3] = r_polyNors, (*fnors)[3] = r_faceNors;
116 if (only_face_normals == false) {
117 mesh_calc_normals_vert_fallback(mverts, numVerts);
122 /* if we are not calculating verts and no verts were passes then we have nothing to do */
123 if ((only_face_normals == true) && (r_polyNors == NULL) && (r_faceNors == NULL)) {
124 printf("%s: called with nothing to do\n", __func__);
128 if (!pnors) pnors = MEM_callocN(sizeof(float[3]) * (size_t)numPolys, __func__);
129 /* if (!fnors) fnors = MEM_callocN(sizeof(float[3]) * numFaces, "face nors mesh.c"); */ /* NO NEED TO ALLOC YET */
132 if (only_face_normals == false) {
133 /* vertex normals are optional, they require some extra calculations,
134 * so make them optional */
135 BKE_mesh_calc_normals_poly(mverts, numVerts, mloop, mpolys, numLoops, numPolys, pnors, false);
138 /* only calc poly normals */
140 for (i = 0; i < numPolys; i++, mp++) {
141 BKE_mesh_calc_poly_normal(mp, mloop + mp->loopstart, mverts, pnors[i]);
146 /* fnors == r_faceNors */ /* NO NEED TO ALLOC YET */
151 for (i = 0; i < numFaces; i++, mf++, origIndexFace++) {
152 if (*origIndexFace < numPolys) {
153 copy_v3_v3(fnors[i], pnors[*origIndexFace]);
156 /* eek, we're not corresponding to polys */
157 printf("error in %s: tessellation face indices are incorrect. normals may look bad.\n", __func__);
162 if (pnors != r_polyNors) MEM_freeN(pnors);
163 /* if (fnors != r_faceNors) MEM_freeN(fnors); */ /* NO NEED TO ALLOC YET */
165 fnors = pnors = NULL;
169 static void mesh_calc_normals_poly_accum(
170 const MPoly *mp, const MLoop *ml,
172 float r_polyno[3], float (*r_tnorms)[3])
174 const int nverts = mp->totloop;
175 float (*edgevecbuf)[3] = BLI_array_alloca(edgevecbuf, (size_t)nverts);
178 /* Polygon Normal and edge-vector */
179 /* inline version of #BKE_mesh_calc_poly_normal, also does edge-vectors */
181 int i_prev = nverts - 1;
182 const float *v_prev = mvert[ml[i_prev].v].co;
186 /* Newell's Method */
187 for (i = 0; i < nverts; i++) {
188 v_curr = mvert[ml[i].v].co;
189 add_newell_cross_v3_v3v3(r_polyno, v_prev, v_curr);
191 /* Unrelated to normalize, calculate edge-vector */
192 sub_v3_v3v3(edgevecbuf[i_prev], v_prev, v_curr);
193 normalize_v3(edgevecbuf[i_prev]);
198 if (UNLIKELY(normalize_v3(r_polyno) == 0.0f)) {
199 r_polyno[2] = 1.0f; /* other axis set to 0.0 */
203 /* accumulate angle weighted face normal */
204 /* inline version of #accumulate_vertex_normals_poly */
206 const float *prev_edge = edgevecbuf[nverts - 1];
208 for (i = 0; i < nverts; i++) {
209 const float *cur_edge = edgevecbuf[i];
211 /* calculate angle between the two poly edges incident on
213 const float fac = saacos(-dot_v3v3(cur_edge, prev_edge));
216 madd_v3_v3fl(r_tnorms[ml[i].v], r_polyno, fac);
217 prev_edge = cur_edge;
223 void BKE_mesh_calc_normals_poly(
224 MVert *mverts, int numVerts,
225 const MLoop *mloop, const MPoly *mpolys,
226 int UNUSED(numLoops), int numPolys, float (*r_polynors)[3],
227 const bool only_face_normals)
229 float (*pnors)[3] = r_polynors;
234 if (only_face_normals) {
235 BLI_assert((pnors != NULL) || (numPolys == 0));
237 #pragma omp parallel for if (numPolys > BKE_MESH_OMP_LIMIT)
238 for (i = 0; i < numPolys; i++) {
239 BKE_mesh_calc_poly_normal(&mpolys[i], mloop + mpolys[i].loopstart, mverts, pnors[i]);
244 /* first go through and calculate normals for all the polys */
245 tnorms = MEM_callocN(sizeof(*tnorms) * (size_t)numVerts, __func__);
249 for (i = 0; i < numPolys; i++, mp++) {
250 mesh_calc_normals_poly_accum(mp, mloop + mp->loopstart, mverts, pnors[i], tnorms);
254 float tpnor[3]; /* temp poly normal */
256 for (i = 0; i < numPolys; i++, mp++) {
257 mesh_calc_normals_poly_accum(mp, mloop + mp->loopstart, mverts, tpnor, tnorms);
261 for (i = 0; i < numVerts; i++) {
262 MVert *mv = &mverts[i];
263 float *no = tnorms[i];
265 if (UNLIKELY(normalize_v3(no) == 0.0f)) {
266 /* following Mesh convention; we use vertex coordinate itself for normal in this case */
267 normalize_v3_v3(no, mv->co);
270 normal_float_to_short_v3(mv->no, no);
276 void BKE_mesh_calc_normals(Mesh *mesh)
279 TIMEIT_START(BKE_mesh_calc_normals);
281 BKE_mesh_calc_normals_poly(mesh->mvert, mesh->totvert,
282 mesh->mloop, mesh->mpoly, mesh->totloop, mesh->totpoly,
285 TIMEIT_END(BKE_mesh_calc_normals);
289 void BKE_mesh_calc_normals_tessface(
290 MVert *mverts, int numVerts,
291 const MFace *mfaces, int numFaces,
292 float (*r_faceNors)[3])
294 float (*tnorms)[3] = MEM_callocN(sizeof(*tnorms) * (size_t)numVerts, "tnorms");
295 float (*fnors)[3] = (r_faceNors) ? r_faceNors : MEM_callocN(sizeof(*fnors) * (size_t)numFaces, "meshnormals");
298 for (i = 0; i < numFaces; i++) {
299 const MFace *mf = &mfaces[i];
300 float *f_no = fnors[i];
301 float *n4 = (mf->v4) ? tnorms[mf->v4] : NULL;
302 const float *c4 = (mf->v4) ? mverts[mf->v4].co : NULL;
305 normal_quad_v3(f_no, mverts[mf->v1].co, mverts[mf->v2].co, mverts[mf->v3].co, mverts[mf->v4].co);
307 normal_tri_v3(f_no, mverts[mf->v1].co, mverts[mf->v2].co, mverts[mf->v3].co);
309 accumulate_vertex_normals(tnorms[mf->v1], tnorms[mf->v2], tnorms[mf->v3], n4,
310 f_no, mverts[mf->v1].co, mverts[mf->v2].co, mverts[mf->v3].co, c4);
313 /* following Mesh convention; we use vertex coordinate itself for normal in this case */
314 for (i = 0; i < numVerts; i++) {
315 MVert *mv = &mverts[i];
316 float *no = tnorms[i];
318 if (UNLIKELY(normalize_v3(no) == 0.0f)) {
319 normalize_v3_v3(no, mv->co);
322 normal_float_to_short_v3(mv->no, no);
327 if (fnors != r_faceNors)
331 void BKE_mesh_calc_normals_looptri(
332 MVert *mverts, int numVerts,
334 const MLoopTri *looptri, int looptri_num,
335 float (*r_tri_nors)[3])
337 float (*tnorms)[3] = MEM_callocN(sizeof(*tnorms) * (size_t)numVerts, "tnorms");
338 float (*fnors)[3] = (r_tri_nors) ? r_tri_nors : MEM_callocN(sizeof(*fnors) * (size_t)looptri_num, "meshnormals");
341 for (i = 0; i < looptri_num; i++) {
342 const MLoopTri *lt = &looptri[i];
343 float *f_no = fnors[i];
344 const unsigned int vtri[3] = {
352 mverts[vtri[0]].co, mverts[vtri[1]].co, mverts[vtri[2]].co);
354 accumulate_vertex_normals_tri(
355 tnorms[vtri[0]], tnorms[vtri[1]], tnorms[vtri[2]],
356 f_no, mverts[vtri[0]].co, mverts[vtri[1]].co, mverts[vtri[2]].co);
359 /* following Mesh convention; we use vertex coordinate itself for normal in this case */
360 for (i = 0; i < numVerts; i++) {
361 MVert *mv = &mverts[i];
362 float *no = tnorms[i];
364 if (UNLIKELY(normalize_v3(no) == 0.0f)) {
365 normalize_v3_v3(no, mv->co);
368 normal_float_to_short_v3(mv->no, no);
373 if (fnors != r_tri_nors)
377 void BKE_lnor_spacearr_init(MLoopNorSpaceArray *lnors_spacearr, const int numLoops)
379 if (!(lnors_spacearr->lspacearr && lnors_spacearr->loops_pool)) {
382 if (!lnors_spacearr->mem) {
383 lnors_spacearr->mem = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
385 mem = lnors_spacearr->mem;
386 lnors_spacearr->lspacearr = BLI_memarena_calloc(mem, sizeof(MLoopNorSpace *) * (size_t)numLoops);
387 lnors_spacearr->loops_pool = BLI_memarena_alloc(mem, sizeof(LinkNode) * (size_t)numLoops);
391 void BKE_lnor_spacearr_clear(MLoopNorSpaceArray *lnors_spacearr)
393 BLI_memarena_clear(lnors_spacearr->mem);
394 lnors_spacearr->lspacearr = NULL;
395 lnors_spacearr->loops_pool = NULL;
398 void BKE_lnor_spacearr_free(MLoopNorSpaceArray *lnors_spacearr)
400 BLI_memarena_free(lnors_spacearr->mem);
401 lnors_spacearr->lspacearr = NULL;
402 lnors_spacearr->loops_pool = NULL;
403 lnors_spacearr->mem = NULL;
406 MLoopNorSpace *BKE_lnor_space_create(MLoopNorSpaceArray *lnors_spacearr)
408 return BLI_memarena_calloc(lnors_spacearr->mem, sizeof(MLoopNorSpace));
411 /* This threshold is a bit touchy (usual float precision issue), this value seems OK. */
412 #define LNOR_SPACE_TRIGO_THRESHOLD (1.0f - 1e-6f)
414 /* Should only be called once.
415 * Beware, this modifies ref_vec and other_vec in place!
416 * In case no valid space can be generated, ref_alpha and ref_beta are set to zero (which means 'use auto lnors').
418 void BKE_lnor_space_define(MLoopNorSpace *lnor_space, const float lnor[3],
419 float vec_ref[3], float vec_other[3], BLI_Stack *edge_vectors)
421 const float pi2 = (float)M_PI * 2.0f;
423 const float dtp_ref = dot_v3v3(vec_ref, lnor);
424 const float dtp_other = dot_v3v3(vec_other, lnor);
426 if (UNLIKELY(fabsf(dtp_ref) >= LNOR_SPACE_TRIGO_THRESHOLD || fabsf(dtp_other) >= LNOR_SPACE_TRIGO_THRESHOLD)) {
427 /* If vec_ref or vec_other are too much aligned with lnor, we can't build lnor space,
428 * tag it as invalid and abort. */
429 lnor_space->ref_alpha = lnor_space->ref_beta = 0.0f;
432 BLI_stack_clear(edge_vectors);
437 copy_v3_v3(lnor_space->vec_lnor, lnor);
439 /* Compute ref alpha, average angle of all available edge vectors to lnor. */
443 while (!BLI_stack_is_empty(edge_vectors)) {
444 const float *vec = BLI_stack_peek(edge_vectors);
445 alpha += saacosf(dot_v3v3(vec, lnor));
446 BLI_stack_discard(edge_vectors);
449 /* Note: In theory, this could be 'nbr > 2', but there is one case where we only have two edges for
450 * two loops: a smooth vertex with only two edges and two faces (our Monkey's nose has that, e.g.). */
451 BLI_assert(nbr >= 2); /* This piece of code shall only be called for more than one loop... */
452 lnor_space->ref_alpha = alpha / (float)nbr;
455 lnor_space->ref_alpha = (saacosf(dot_v3v3(vec_ref, lnor)) + saacosf(dot_v3v3(vec_other, lnor))) / 2.0f;
458 /* Project vec_ref on lnor's ortho plane. */
459 mul_v3_v3fl(tvec, lnor, dtp_ref);
460 sub_v3_v3(vec_ref, tvec);
461 normalize_v3_v3(lnor_space->vec_ref, vec_ref);
463 cross_v3_v3v3(tvec, lnor, lnor_space->vec_ref);
464 normalize_v3_v3(lnor_space->vec_ortho, tvec);
466 /* Project vec_other on lnor's ortho plane. */
467 mul_v3_v3fl(tvec, lnor, dtp_other);
468 sub_v3_v3(vec_other, tvec);
469 normalize_v3(vec_other);
471 /* Beta is angle between ref_vec and other_vec, around lnor. */
472 dtp = dot_v3v3(lnor_space->vec_ref, vec_other);
473 if (LIKELY(dtp < LNOR_SPACE_TRIGO_THRESHOLD)) {
474 const float beta = saacos(dtp);
475 lnor_space->ref_beta = (dot_v3v3(lnor_space->vec_ortho, vec_other) < 0.0f) ? pi2 - beta : beta;
478 lnor_space->ref_beta = pi2;
482 void BKE_lnor_space_add_loop(MLoopNorSpaceArray *lnors_spacearr, MLoopNorSpace *lnor_space, const int ml_index,
483 const bool do_add_loop)
485 lnors_spacearr->lspacearr[ml_index] = lnor_space;
487 BLI_linklist_prepend_nlink(&lnor_space->loops, SET_INT_IN_POINTER(ml_index), &lnors_spacearr->loops_pool[ml_index]);
491 MINLINE float unit_short_to_float(const short val)
493 return (float)val / (float)SHRT_MAX;
496 MINLINE short unit_float_to_short(const float val)
499 return (short)floorf(val * (float)SHRT_MAX + 0.5f);
502 void BKE_lnor_space_custom_data_to_normal(MLoopNorSpace *lnor_space, const short clnor_data[2], float r_custom_lnor[3])
504 /* NOP custom normal data or invalid lnor space, return. */
505 if (clnor_data[0] == 0 || lnor_space->ref_alpha == 0.0f || lnor_space->ref_beta == 0.0f) {
506 copy_v3_v3(r_custom_lnor, lnor_space->vec_lnor);
511 /* TODO Check whether using sincosf() gives any noticeable benefit
512 * (could not even get it working under linux though)! */
513 const float pi2 = (float)(M_PI * 2.0);
514 const float alphafac = unit_short_to_float(clnor_data[0]);
515 const float alpha = (alphafac > 0.0f ? lnor_space->ref_alpha : pi2 - lnor_space->ref_alpha) * alphafac;
516 const float betafac = unit_short_to_float(clnor_data[1]);
518 mul_v3_v3fl(r_custom_lnor, lnor_space->vec_lnor, cosf(alpha));
520 if (betafac == 0.0f) {
521 madd_v3_v3fl(r_custom_lnor, lnor_space->vec_ref, sinf(alpha));
524 const float sinalpha = sinf(alpha);
525 const float beta = (betafac > 0.0f ? lnor_space->ref_beta : pi2 - lnor_space->ref_beta) * betafac;
526 madd_v3_v3fl(r_custom_lnor, lnor_space->vec_ref, sinalpha * cosf(beta));
527 madd_v3_v3fl(r_custom_lnor, lnor_space->vec_ortho, sinalpha * sinf(beta));
532 void BKE_lnor_space_custom_normal_to_data(MLoopNorSpace *lnor_space, const float custom_lnor[3], short r_clnor_data[2])
534 /* We use null vector as NOP custom normal (can be simpler than giving autocomputed lnor...). */
535 if (is_zero_v3(custom_lnor) || compare_v3v3(lnor_space->vec_lnor, custom_lnor, 1e-4f)) {
536 r_clnor_data[0] = r_clnor_data[1] = 0;
541 const float pi2 = (float)(M_PI * 2.0);
542 const float cos_alpha = dot_v3v3(lnor_space->vec_lnor, custom_lnor);
543 float vec[3], cos_beta;
546 alpha = saacosf(cos_alpha);
547 if (alpha > lnor_space->ref_alpha) {
548 /* Note we could stick to [0, pi] range here, but makes decoding more complex, not worth it. */
549 r_clnor_data[0] = unit_float_to_short(-(pi2 - alpha) / (pi2 - lnor_space->ref_alpha));
552 r_clnor_data[0] = unit_float_to_short(alpha / lnor_space->ref_alpha);
555 /* Project custom lnor on (vec_ref, vec_ortho) plane. */
556 mul_v3_v3fl(vec, lnor_space->vec_lnor, -cos_alpha);
557 add_v3_v3(vec, custom_lnor);
560 cos_beta = dot_v3v3(lnor_space->vec_ref, vec);
562 if (cos_beta < LNOR_SPACE_TRIGO_THRESHOLD) {
563 float beta = saacosf(cos_beta);
564 if (dot_v3v3(lnor_space->vec_ortho, vec) < 0.0f) {
568 if (beta > lnor_space->ref_beta) {
569 r_clnor_data[1] = unit_float_to_short(-(pi2 - beta) / (pi2 - lnor_space->ref_beta));
572 r_clnor_data[1] = unit_float_to_short(beta / lnor_space->ref_beta);
581 #define LOOP_SPLIT_TASK_BLOCK_SIZE 1024
583 typedef struct LoopSplitTaskData {
584 /* Specific to each instance (each task). */
585 MLoopNorSpace *lnor_space; /* We have to create those outside of tasks, since afaik memarena is not threadsafe. */
587 const MLoop *ml_curr;
588 const MLoop *ml_prev;
591 const int *e2l_prev; /* Also used a flag to switch between single or fan process! */
594 /* This one is special, it's owned and managed by worker tasks, avoid to have to create it for each fan! */
595 BLI_Stack *edge_vectors;
600 typedef struct LoopSplitTaskDataCommon {
602 * Note we do not need to protect it, though, since two different tasks will *always* affect different
603 * elements in the arrays. */
604 MLoopNorSpaceArray *lnors_spacearr;
605 BLI_bitmap *sharp_verts;
606 float (*loopnors)[3];
607 short (*clnors_data)[2];
614 const int (*edge_to_loops)[2];
615 const int *loop_to_poly;
616 const float (*polynors)[3];
620 /* ***** Workers communication. ***** */
621 ThreadQueue *task_queue;
623 } LoopSplitTaskDataCommon;
625 #define INDEX_UNSET INT_MIN
626 #define INDEX_INVALID -1
627 /* See comment about edge_to_loops below. */
628 #define IS_EDGE_SHARP(_e2l) (ELEM((_e2l)[1], INDEX_UNSET, INDEX_INVALID))
630 static void split_loop_nor_single_do(LoopSplitTaskDataCommon *common_data, LoopSplitTaskData *data)
632 MLoopNorSpaceArray *lnors_spacearr = common_data->lnors_spacearr;
633 short (*clnors_data)[2] = common_data->clnors_data;
635 const MVert *mverts = common_data->mverts;
636 const MEdge *medges = common_data->medges;
637 const float (*polynors)[3] = common_data->polynors;
639 MLoopNorSpace *lnor_space = data->lnor_space;
640 float (*lnor)[3] = data->lnor;
641 const MLoop *ml_curr = data->ml_curr;
642 const MLoop *ml_prev = data->ml_prev;
643 const int ml_curr_index = data->ml_curr_index;
644 #if 0 /* Not needed for 'single' loop. */
645 const int ml_prev_index = data->ml_prev_index;
646 const int *e2l_prev = data->e2l_prev;
648 const int mp_index = data->mp_index;
650 /* Simple case (both edges around that vertex are sharp in current polygon),
651 * this loop just takes its poly normal.
653 copy_v3_v3(*lnor, polynors[mp_index]);
655 /* printf("BASIC: handling loop %d / edge %d / vert %d\n", ml_curr_index, ml_curr->e, ml_curr->v); */
657 /* If needed, generate this (simple!) lnor space. */
658 if (lnors_spacearr) {
659 float vec_curr[3], vec_prev[3];
661 const unsigned int mv_pivot_index = ml_curr->v; /* The vertex we are "fanning" around! */
662 const MVert *mv_pivot = &mverts[mv_pivot_index];
663 const MEdge *me_curr = &medges[ml_curr->e];
664 const MVert *mv_2 = (me_curr->v1 == mv_pivot_index) ? &mverts[me_curr->v2] : &mverts[me_curr->v1];
665 const MEdge *me_prev = &medges[ml_prev->e];
666 const MVert *mv_3 = (me_prev->v1 == mv_pivot_index) ? &mverts[me_prev->v2] : &mverts[me_prev->v1];
668 sub_v3_v3v3(vec_curr, mv_2->co, mv_pivot->co);
669 normalize_v3(vec_curr);
670 sub_v3_v3v3(vec_prev, mv_3->co, mv_pivot->co);
671 normalize_v3(vec_prev);
673 BKE_lnor_space_define(lnor_space, *lnor, vec_curr, vec_prev, NULL);
674 /* We know there is only one loop in this space, no need to create a linklist in this case... */
675 BKE_lnor_space_add_loop(lnors_spacearr, lnor_space, ml_curr_index, false);
678 BKE_lnor_space_custom_data_to_normal(lnor_space, clnors_data[ml_curr_index], *lnor);
683 static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSplitTaskData *data)
685 MLoopNorSpaceArray *lnors_spacearr = common_data->lnors_spacearr;
686 float (*loopnors)[3] = common_data->loopnors;
687 short (*clnors_data)[2] = common_data->clnors_data;
689 const MVert *mverts = common_data->mverts;
690 const MEdge *medges = common_data->medges;
691 const MLoop *mloops = common_data->mloops;
692 const MPoly *mpolys = common_data->mpolys;
693 const int (*edge_to_loops)[2] = common_data->edge_to_loops;
694 const int *loop_to_poly = common_data->loop_to_poly;
695 const float (*polynors)[3] = common_data->polynors;
697 MLoopNorSpace *lnor_space = data->lnor_space;
698 #if 0 /* Not needed for 'fan' loops. */
699 float (*lnor)[3] = data->lnor;
701 const MLoop *ml_curr = data->ml_curr;
702 const MLoop *ml_prev = data->ml_prev;
703 const int ml_curr_index = data->ml_curr_index;
704 const int ml_prev_index = data->ml_prev_index;
705 const int mp_index = data->mp_index;
706 const int *e2l_prev = data->e2l_prev;
708 BLI_Stack *edge_vectors = data->edge_vectors;
710 /* Gah... We have to fan around current vertex, until we find the other non-smooth edge,
711 * and accumulate face normals into the vertex!
712 * Note in case this vertex has only one sharp edges, this is a waste because the normal is the same as
713 * the vertex normal, but I do not see any easy way to detect that (would need to count number
714 * of sharp edges per vertex, I doubt the additional memory usage would be worth it, especially as
715 * it should not be a common case in real-life meshes anyway).
717 const unsigned int mv_pivot_index = ml_curr->v; /* The vertex we are "fanning" around! */
718 const MVert *mv_pivot = &mverts[mv_pivot_index];
719 const MEdge *me_org = &medges[ml_curr->e]; /* ml_curr would be mlfan_prev if we needed that one */
720 const int *e2lfan_curr;
721 float vec_curr[3], vec_prev[3], vec_org[3];
722 const MLoop *mlfan_curr, *mlfan_next;
723 const MPoly *mpfan_next;
724 float lnor[3] = {0.0f, 0.0f, 0.0f};
725 /* mlfan_vert_index: the loop of our current edge might not be the loop of our current vertex! */
726 int mlfan_curr_index, mlfan_vert_index, mpfan_curr_index;
728 /* We validate clnors data on the fly - cheapest way to do! */
729 int clnors_avg[2] = {0, 0};
730 short (*clnor_ref)[2] = NULL;
732 bool clnors_invalid = false;
734 /* Temp loop normal stack. */
735 BLI_SMALLSTACK_DECLARE(normal, float *);
736 /* Temp clnors stack. */
737 BLI_SMALLSTACK_DECLARE(clnors, short *);
739 e2lfan_curr = e2l_prev;
740 mlfan_curr = ml_prev;
741 mlfan_curr_index = ml_prev_index;
742 mlfan_vert_index = ml_curr_index;
743 mpfan_curr_index = mp_index;
745 BLI_assert(mlfan_curr_index >= 0);
746 BLI_assert(mlfan_vert_index >= 0);
747 BLI_assert(mpfan_curr_index >= 0);
749 /* Only need to compute previous edge's vector once, then we can just reuse old current one! */
751 const MVert *mv_2 = (me_org->v1 == mv_pivot_index) ? &mverts[me_org->v2] : &mverts[me_org->v1];
753 sub_v3_v3v3(vec_org, mv_2->co, mv_pivot->co);
754 normalize_v3(vec_org);
755 copy_v3_v3(vec_prev, vec_org);
757 if (lnors_spacearr) {
758 BLI_stack_push(edge_vectors, vec_org);
762 /* printf("FAN: vert %d, start edge %d\n", mv_pivot_index, ml_curr->e); */
765 const MEdge *me_curr = &medges[mlfan_curr->e];
766 /* Compute edge vectors.
767 * NOTE: We could pre-compute those into an array, in the first iteration, instead of computing them
768 * twice (or more) here. However, time gained is not worth memory and time lost,
769 * given the fact that this code should not be called that much in real-life meshes...
772 const MVert *mv_2 = (me_curr->v1 == mv_pivot_index) ? &mverts[me_curr->v2] : &mverts[me_curr->v1];
774 sub_v3_v3v3(vec_curr, mv_2->co, mv_pivot->co);
775 normalize_v3(vec_curr);
778 /* printf("\thandling edge %d / loop %d\n", mlfan_curr->e, mlfan_curr_index); */
781 /* Code similar to accumulate_vertex_normals_poly. */
782 /* Calculate angle between the two poly edges incident on this vertex. */
783 const float fac = saacos(dot_v3v3(vec_curr, vec_prev));
785 madd_v3_v3fl(lnor, polynors[mpfan_curr_index], fac);
788 /* Accumulate all clnors, if they are not all equal we have to fix that! */
789 short (*clnor)[2] = &clnors_data[mlfan_vert_index];
791 clnors_invalid |= ((*clnor_ref)[0] != (*clnor)[0] || (*clnor_ref)[1] != (*clnor)[1]);
796 clnors_avg[0] += (*clnor)[0];
797 clnors_avg[1] += (*clnor)[1];
799 /* We store here a pointer to all custom lnors processed. */
800 BLI_SMALLSTACK_PUSH(clnors, (short *)*clnor);
804 /* We store here a pointer to all loop-normals processed. */
805 BLI_SMALLSTACK_PUSH(normal, (float *)(loopnors[mlfan_vert_index]));
807 if (lnors_spacearr) {
808 /* Assign current lnor space to current 'vertex' loop. */
809 BKE_lnor_space_add_loop(lnors_spacearr, lnor_space, mlfan_vert_index, true);
810 if (me_curr != me_org) {
811 /* We store here all edges-normalized vectors processed. */
812 BLI_stack_push(edge_vectors, vec_curr);
816 if (IS_EDGE_SHARP(e2lfan_curr) || (me_curr == me_org)) {
817 /* Current edge is sharp and we have finished with this fan of faces around this vert,
818 * or this vert is smooth, and we have completed a full turn around it.
820 /* printf("FAN: Finished!\n"); */
824 copy_v3_v3(vec_prev, vec_curr);
826 /* Warning! This is rather complex!
827 * We have to find our next edge around the vertex (fan mode).
828 * First we find the next loop, which is either previous or next to mlfan_curr_index, depending
829 * whether both loops using current edge are in the same direction or not, and whether
830 * mlfan_curr_index actually uses the vertex we are fanning around!
831 * mlfan_curr_index is the index of mlfan_next here, and mlfan_next is not the real next one
832 * (i.e. not the future mlfan_curr)...
834 mlfan_curr_index = (e2lfan_curr[0] == mlfan_curr_index) ? e2lfan_curr[1] : e2lfan_curr[0];
835 mpfan_curr_index = loop_to_poly[mlfan_curr_index];
837 BLI_assert(mlfan_curr_index >= 0);
838 BLI_assert(mpfan_curr_index >= 0);
840 mlfan_next = &mloops[mlfan_curr_index];
841 mpfan_next = &mpolys[mpfan_curr_index];
842 if ((mlfan_curr->v == mlfan_next->v && mlfan_curr->v == mv_pivot_index) ||
843 (mlfan_curr->v != mlfan_next->v && mlfan_curr->v != mv_pivot_index))
845 /* We need the previous loop, but current one is our vertex's loop. */
846 mlfan_vert_index = mlfan_curr_index;
847 if (--mlfan_curr_index < mpfan_next->loopstart) {
848 mlfan_curr_index = mpfan_next->loopstart + mpfan_next->totloop - 1;
852 /* We need the next loop, which is also our vertex's loop. */
853 if (++mlfan_curr_index >= mpfan_next->loopstart + mpfan_next->totloop) {
854 mlfan_curr_index = mpfan_next->loopstart;
856 mlfan_vert_index = mlfan_curr_index;
858 mlfan_curr = &mloops[mlfan_curr_index];
859 /* And now we are back in sync, mlfan_curr_index is the index of mlfan_curr! Pff! */
861 e2lfan_curr = edge_to_loops[mlfan_curr->e];
865 float lnor_len = normalize_v3(lnor);
867 /* If we are generating lnor spacearr, we can now define the one for this fan,
868 * and optionally compute final lnor from custom data too!
870 if (lnors_spacearr) {
871 if (UNLIKELY(lnor_len == 0.0f)) {
872 /* Use vertex normal as fallback! */
873 copy_v3_v3(lnor, loopnors[mlfan_vert_index]);
877 BKE_lnor_space_define(lnor_space, lnor, vec_org, vec_curr, edge_vectors);
880 if (clnors_invalid) {
883 clnors_avg[0] /= clnors_nbr;
884 clnors_avg[1] /= clnors_nbr;
885 /* Fix/update all clnors of this fan with computed average value. */
886 printf("Invalid clnors in this fan!\n");
887 while ((clnor = BLI_SMALLSTACK_POP(clnors))) {
888 //print_v2("org clnor", clnor);
889 clnor[0] = (short)clnors_avg[0];
890 clnor[1] = (short)clnors_avg[1];
892 //print_v2("new clnors", clnors_avg);
894 /* Extra bonus: since smallstack is local to this func, no more need to empty it at all cost! */
896 BKE_lnor_space_custom_data_to_normal(lnor_space, *clnor_ref, lnor);
900 /* In case we get a zero normal here, just use vertex normal already set! */
901 if (LIKELY(lnor_len != 0.0f)) {
902 /* Copy back the final computed normal into all related loop-normals. */
905 while ((nor = BLI_SMALLSTACK_POP(normal))) {
906 copy_v3_v3(nor, lnor);
909 /* Extra bonus: since smallstack is local to this func, no more need to empty it at all cost! */
913 static void loop_split_worker_do(
914 LoopSplitTaskDataCommon *common_data, LoopSplitTaskData *data, BLI_Stack *edge_vectors)
916 BLI_assert(data->ml_curr);
917 if (data->e2l_prev) {
918 BLI_assert((edge_vectors == NULL) || BLI_stack_is_empty(edge_vectors));
919 data->edge_vectors = edge_vectors;
920 split_loop_nor_fan_do(common_data, data);
923 /* No need for edge_vectors for 'single' case! */
924 split_loop_nor_single_do(common_data, data);
928 static void loop_split_worker(TaskPool *UNUSED(pool), void *taskdata, int UNUSED(threadid))
930 LoopSplitTaskDataCommon *common_data = taskdata;
931 LoopSplitTaskData *data_buff;
933 /* Temp edge vectors stack, only used when computing lnor spacearr. */
934 BLI_Stack *edge_vectors = common_data->lnors_spacearr ? BLI_stack_new(sizeof(float[3]), __func__) : NULL;
937 TIMEIT_START(loop_split_worker);
940 while ((data_buff = BLI_thread_queue_pop(common_data->task_queue))) {
941 LoopSplitTaskData *data = data_buff;
944 for (i = 0; i < LOOP_SPLIT_TASK_BLOCK_SIZE; i++, data++) {
945 /* A NULL ml_curr is used to tag ended data! */
946 if (data->ml_curr == NULL) {
949 loop_split_worker_do(common_data, data, edge_vectors);
952 MEM_freeN(data_buff);
956 BLI_stack_free(edge_vectors);
960 TIMEIT_END(loop_split_worker);
964 /* Note we use data_buff to detect whether we are in threaded context or not, in later case it is NULL. */
965 static void loop_split_generator_do(LoopSplitTaskDataCommon *common_data, const bool threaded)
967 MLoopNorSpaceArray *lnors_spacearr = common_data->lnors_spacearr;
968 BLI_bitmap *sharp_verts = common_data->sharp_verts;
969 float (*loopnors)[3] = common_data->loopnors;
971 const MLoop *mloops = common_data->mloops;
972 const MPoly *mpolys = common_data->mpolys;
973 const int (*edge_to_loops)[2] = common_data->edge_to_loops;
974 const int numPolys = common_data->numPolys;
979 LoopSplitTaskData *data, *data_buff = NULL, data_mem;
982 /* Temp edge vectors stack, only used when computing lnor spacearr (and we are not multi-threading). */
983 BLI_Stack *edge_vectors = (lnors_spacearr && !data_buff) ? BLI_stack_new(sizeof(float[3]), __func__) : NULL;
986 TIMEIT_START(loop_split_generator);
990 memset(&data_mem, 0, sizeof(data_mem));
994 /* We now know edges that can be smoothed (with their vector, and their two loops), and edges that will be hard!
995 * Now, time to generate the normals.
997 for (mp = mpolys, mp_index = 0; mp_index < numPolys; mp++, mp_index++) {
998 const MLoop *ml_curr, *ml_prev;
1000 const int ml_last_index = (mp->loopstart + mp->totloop) - 1;
1001 int ml_curr_index = mp->loopstart;
1002 int ml_prev_index = ml_last_index;
1004 ml_curr = &mloops[ml_curr_index];
1005 ml_prev = &mloops[ml_prev_index];
1006 lnors = &loopnors[ml_curr_index];
1008 for (; ml_curr_index <= ml_last_index; ml_curr++, ml_curr_index++, lnors++) {
1009 const int *e2l_curr = edge_to_loops[ml_curr->e];
1010 const int *e2l_prev = edge_to_loops[ml_prev->e];
1012 if (!IS_EDGE_SHARP(e2l_curr) && (!lnors_spacearr || BLI_BITMAP_TEST_BOOL(sharp_verts, ml_curr->v))) {
1013 /* A smooth edge, and we are not generating lnor_spacearr, or the related vertex is sharp.
1014 * We skip it because it is either:
1015 * - in the middle of a 'smooth fan' already computed (or that will be as soon as we hit
1016 * one of its ends, i.e. one of its two sharp edges), or...
1017 * - the related vertex is a "full smooth" one, in which case pre-populated normals from vertex
1018 * are just fine (or it has already be handled in a previous loop in case of needed lnors spacearr)!
1020 /* printf("Skipping loop %d / edge %d / vert %d(%d)\n", ml_curr_index, ml_curr->e, ml_curr->v, sharp_verts[ml_curr->v]); */
1024 if (data_idx == 0) {
1025 data_buff = MEM_callocN(sizeof(*data_buff) * LOOP_SPLIT_TASK_BLOCK_SIZE, __func__);
1027 data = &data_buff[data_idx];
1030 if (IS_EDGE_SHARP(e2l_curr) && IS_EDGE_SHARP(e2l_prev)) {
1032 data->ml_curr = ml_curr;
1033 data->ml_prev = ml_prev;
1034 data->ml_curr_index = ml_curr_index;
1035 #if 0 /* Not needed for 'single' loop. */
1036 data->ml_prev_index = ml_prev_index;
1037 data->e2l_prev = NULL; /* Tag as 'single' task. */
1039 data->mp_index = mp_index;
1040 if (lnors_spacearr) {
1041 data->lnor_space = BKE_lnor_space_create(lnors_spacearr);
1044 /* We *do not need* to check/tag loops as already computed!
1045 * Due to the fact a loop only links to one of its two edges, a same fan *will never be walked
1047 * Since we consider edges having neighbor polys with inverted (flipped) normals as sharp, we are sure
1048 * that no fan will be skipped, even only considering the case (sharp curr_edge, smooth prev_edge),
1049 * and not the alternative (smooth curr_edge, sharp prev_edge).
1050 * All this due/thanks to link between normals and loop ordering (i.e. winding).
1053 #if 0 /* Not needed for 'fan' loops. */
1056 data->ml_curr = ml_curr;
1057 data->ml_prev = ml_prev;
1058 data->ml_curr_index = ml_curr_index;
1059 data->ml_prev_index = ml_prev_index;
1060 data->e2l_prev = e2l_prev; /* Also tag as 'fan' task. */
1061 data->mp_index = mp_index;
1062 if (lnors_spacearr) {
1063 data->lnor_space = BKE_lnor_space_create(lnors_spacearr);
1064 /* Tag related vertex as sharp, to avoid fanning around it again (in case it was a smooth one).
1065 * This *has* to be done outside of workers tasks! */
1066 BLI_BITMAP_ENABLE(sharp_verts, ml_curr->v);
1072 if (data_idx == LOOP_SPLIT_TASK_BLOCK_SIZE) {
1073 BLI_thread_queue_push(common_data->task_queue, data_buff);
1078 loop_split_worker_do(common_data, data, edge_vectors);
1079 memset(data, 0, sizeof(data_mem));
1084 ml_prev_index = ml_curr_index;
1089 /* Last block of data... Since it is calloc'ed and we use first NULL item as stopper, everything is fine. */
1090 if (LIKELY(data_idx)) {
1091 BLI_thread_queue_push(common_data->task_queue, data_buff);
1094 /* This will signal all other worker threads to wake up and finish! */
1095 BLI_thread_queue_nowait(common_data->task_queue);
1099 BLI_stack_free(edge_vectors);
1103 TIMEIT_END(loop_split_generator);
1107 static void loop_split_generator(TaskPool *UNUSED(pool), void *taskdata, int UNUSED(threadid))
1109 LoopSplitTaskDataCommon *common_data = taskdata;
1111 loop_split_generator_do(common_data, true);
1115 * Compute split normals, i.e. vertex normals associated with each poly (hence 'loop normals').
1116 * Useful to materialize sharp edges (or non-smooth faces) without actually modifying the geometry (splitting edges).
1118 void BKE_mesh_normals_loop_split(
1119 const MVert *mverts, const int numVerts, MEdge *medges, const int numEdges,
1120 MLoop *mloops, float (*r_loopnors)[3], const int numLoops,
1121 MPoly *mpolys, const float (*polynors)[3], const int numPolys,
1122 const bool use_split_normals, float split_angle,
1123 MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2], int *r_loop_to_poly)
1126 /* For now this is not supported. If we do not use split normals, we do not generate anything fancy! */
1127 BLI_assert(use_split_normals || !(r_lnors_spacearr));
1129 if (!use_split_normals) {
1130 /* In this case, we simply fill lnors with vnors (or fnors for flat faces), quite simple!
1131 * Note this is done here to keep some logic and consistency in this quite complex code,
1132 * since we may want to use lnors even when mesh's 'autosmooth' is disabled (see e.g. mesh mapping code).
1133 * As usual, we could handle that on case-by-case basis, but simpler to keep it well confined here.
1137 for (mp_index = 0; mp_index < numPolys; mp_index++) {
1138 MPoly *mp = &mpolys[mp_index];
1139 int ml_index = mp->loopstart;
1140 const int ml_index_end = ml_index + mp->totloop;
1141 const bool is_poly_flat = ((mp->flag & ME_SMOOTH) == 0);
1143 for (; ml_index < ml_index_end; ml_index++) {
1144 if (r_loop_to_poly) {
1145 r_loop_to_poly[ml_index] = mp_index;
1148 copy_v3_v3(r_loopnors[ml_index], polynors[mp_index]);
1151 normal_short_to_float_v3(r_loopnors[ml_index], mverts[mloops[ml_index].v].no);
1160 /* Mapping edge -> loops.
1161 * If that edge is used by more than two loops (polys), it is always sharp (and tagged as such, see below).
1162 * We also use the second loop index as a kind of flag: smooth edge: > 0,
1163 * sharp edge: < 0 (INDEX_INVALID || INDEX_UNSET),
1164 * unset: INDEX_UNSET
1165 * Note that currently we only have two values for second loop of sharp edges. However, if needed, we can
1166 * store the negated value of loop index instead of INDEX_INVALID to retrieve the real value later in code).
1167 * Note also that lose edges always have both values set to 0!
1169 int (*edge_to_loops)[2] = MEM_callocN(sizeof(int[2]) * (size_t)numEdges, __func__);
1171 /* Simple mapping from a loop to its polygon index. */
1172 int *loop_to_poly = r_loop_to_poly ? r_loop_to_poly : MEM_mallocN(sizeof(int) * (size_t)numLoops, __func__);
1175 int mp_index, me_index;
1176 bool check_angle = (split_angle < (float)M_PI);
1179 BLI_bitmap *sharp_verts = NULL;
1180 MLoopNorSpaceArray _lnors_spacearr = {NULL};
1182 LoopSplitTaskDataCommon common_data = {NULL};
1185 TIMEIT_START(BKE_mesh_normals_loop_split);
1189 /* When using custom loop normals, disable the angle feature! */
1191 check_angle = false;
1194 split_angle = cosf(split_angle);
1198 if (!r_lnors_spacearr && clnors_data) {
1199 /* We need to compute lnor spacearr if some custom lnor data are given to us! */
1200 r_lnors_spacearr = &_lnors_spacearr;
1202 if (r_lnors_spacearr) {
1203 BKE_lnor_spacearr_init(r_lnors_spacearr, numLoops);
1204 sharp_verts = BLI_BITMAP_NEW((size_t)numVerts, __func__);
1207 /* This first loop check which edges are actually smooth, and compute edge vectors. */
1208 for (mp = mpolys, mp_index = 0; mp_index < numPolys; mp++, mp_index++) {
1211 int ml_curr_index = mp->loopstart;
1212 const int ml_last_index = (ml_curr_index + mp->totloop) - 1;
1214 ml_curr = &mloops[ml_curr_index];
1216 for (; ml_curr_index <= ml_last_index; ml_curr++, ml_curr_index++) {
1217 e2l = edge_to_loops[ml_curr->e];
1219 loop_to_poly[ml_curr_index] = mp_index;
1221 /* Pre-populate all loop normals as if their verts were all-smooth, this way we don't have to compute
1224 normal_short_to_float_v3(r_loopnors[ml_curr_index], mverts[ml_curr->v].no);
1226 /* Check whether current edge might be smooth or sharp */
1227 if ((e2l[0] | e2l[1]) == 0) {
1228 /* 'Empty' edge until now, set e2l[0] (and e2l[1] to INDEX_UNSET to tag it as unset). */
1229 e2l[0] = ml_curr_index;
1230 /* We have to check this here too, else we might miss some flat faces!!! */
1231 e2l[1] = (mp->flag & ME_SMOOTH) ? INDEX_UNSET : INDEX_INVALID;
1233 else if (e2l[1] == INDEX_UNSET) {
1234 /* Second loop using this edge, time to test its sharpness.
1235 * An edge is sharp if it is tagged as such, or its face is not smooth,
1236 * or both poly have opposed (flipped) normals, i.e. both loops on the same edge share the same vertex,
1237 * or angle between both its polys' normals is above split_angle value.
1239 if (!(mp->flag & ME_SMOOTH) || (medges[ml_curr->e].flag & ME_SHARP) ||
1240 ml_curr->v == mloops[e2l[0]].v ||
1241 (check_angle && dot_v3v3(polynors[loop_to_poly[e2l[0]]], polynors[mp_index]) < split_angle))
1243 /* Note: we are sure that loop != 0 here ;) */
1244 e2l[1] = INDEX_INVALID;
1247 e2l[1] = ml_curr_index;
1250 else if (!IS_EDGE_SHARP(e2l)) {
1251 /* More than two loops using this edge, tag as sharp if not yet done. */
1252 e2l[1] = INDEX_INVALID;
1254 /* Else, edge is already 'disqualified' (i.e. sharp)! */
1258 if (r_lnors_spacearr) {
1259 /* Tag vertices that have at least one sharp edge as 'sharp' (used for the lnor spacearr computation).
1260 * XXX This third loop over edges is a bit disappointing, could not find any other way yet.
1261 * Not really performance-critical anyway.
1263 for (me_index = 0; me_index < numEdges; me_index++) {
1264 const int *e2l = edge_to_loops[me_index];
1265 const MEdge *me = &medges[me_index];
1266 if (IS_EDGE_SHARP(e2l)) {
1267 BLI_BITMAP_ENABLE(sharp_verts, me->v1);
1268 BLI_BITMAP_ENABLE(sharp_verts, me->v2);
1273 /* Init data common to all tasks. */
1274 common_data.lnors_spacearr = r_lnors_spacearr;
1275 common_data.loopnors = r_loopnors;
1276 common_data.clnors_data = clnors_data;
1278 common_data.mverts = mverts;
1279 common_data.medges = medges;
1280 common_data.mloops = mloops;
1281 common_data.mpolys = mpolys;
1282 common_data.sharp_verts = sharp_verts;
1283 common_data.edge_to_loops = (const int(*)[2])edge_to_loops;
1284 common_data.loop_to_poly = loop_to_poly;
1285 common_data.polynors = polynors;
1286 common_data.numPolys = numPolys;
1288 if (numLoops < LOOP_SPLIT_TASK_BLOCK_SIZE * 8) {
1289 /* Not enough loops to be worth the whole threading overhead... */
1290 loop_split_generator_do(&common_data, false);
1293 TaskScheduler *task_scheduler;
1294 TaskPool *task_pool;
1297 common_data.task_queue = BLI_thread_queue_init();
1299 task_scheduler = BLI_task_scheduler_get();
1300 task_pool = BLI_task_pool_create(task_scheduler, NULL);
1302 nbr_workers = max_ii(2, BLI_task_scheduler_num_threads(task_scheduler));
1303 for (i = 1; i < nbr_workers; i++) {
1304 BLI_task_pool_push(task_pool, loop_split_worker, &common_data, false, TASK_PRIORITY_HIGH);
1306 BLI_task_pool_push(task_pool, loop_split_generator, &common_data, false, TASK_PRIORITY_HIGH);
1307 BLI_task_pool_work_and_wait(task_pool);
1309 BLI_task_pool_free(task_pool);
1311 BLI_thread_queue_free(common_data.task_queue);
1314 MEM_freeN(edge_to_loops);
1315 if (!r_loop_to_poly) {
1316 MEM_freeN(loop_to_poly);
1319 if (r_lnors_spacearr) {
1320 MEM_freeN(sharp_verts);
1321 if (r_lnors_spacearr == &_lnors_spacearr) {
1322 BKE_lnor_spacearr_free(r_lnors_spacearr);
1327 TIMEIT_END(BKE_mesh_normals_loop_split);
1334 #undef INDEX_INVALID
1335 #undef IS_EDGE_SHARP
1338 * Compute internal representation of given custom normals (as an array of float[2]).
1339 * It also makes sure the mesh matches those custom normals, by setting sharp edges flag as needed to get a
1340 * same custom lnor for all loops sharing a same smooth fan.
1341 * If use_vertices if true, custom_loopnors is assumed to be per-vertex, not per-loop
1342 * (this allows to set whole vert's normals at once, useful in some cases).
1344 static void mesh_normals_loop_custom_set(
1345 const MVert *mverts, const int numVerts, MEdge *medges, const int numEdges,
1346 MLoop *mloops, float (*custom_loopnors)[3], const int numLoops,
1347 MPoly *mpolys, const float (*polynors)[3], const int numPolys,
1348 short (*r_clnors_data)[2], const bool use_vertices)
1350 /* We *may* make that poor BKE_mesh_normals_loop_split() even more complex by making it handling that
1351 * feature too, would probably be more efficient in absolute.
1352 * However, this function *is not* performance-critical, since it is mostly expected to be called
1353 * by io addons when importing custom normals, and modifier (and perhaps from some editing tools later?).
1354 * So better to keep some simplicity here, and just call BKE_mesh_normals_loop_split() twice!
1356 MLoopNorSpaceArray lnors_spacearr = {NULL};
1357 BLI_bitmap *done_loops = BLI_BITMAP_NEW((size_t)numLoops, __func__);
1358 float (*lnors)[3] = MEM_callocN(sizeof(*lnors) * (size_t)numLoops, __func__);
1359 int *loop_to_poly = MEM_mallocN(sizeof(int) * (size_t)numLoops, __func__);
1360 /* In this case we always consider split nors as ON, and do not want to use angle to define smooth fans! */
1361 const bool use_split_normals = true;
1362 const float split_angle = (float)M_PI;
1365 BLI_SMALLSTACK_DECLARE(clnors_data, short *);
1367 /* Compute current lnor spacearr. */
1368 BKE_mesh_normals_loop_split(mverts, numVerts, medges, numEdges, mloops, lnors, numLoops,
1369 mpolys, polynors, numPolys, use_split_normals, split_angle,
1370 &lnors_spacearr, NULL, loop_to_poly);
1372 /* Now, check each current smooth fan (one lnor space per smooth fan!), and if all its matching custom lnors
1373 * are not (enough) equal, add sharp edges as needed.
1374 * This way, next time we run BKE_mesh_normals_loop_split(), we'll get lnor spacearr/smooth fans matching
1375 * given custom lnors.
1376 * Note this code *will never* unsharp edges!
1377 * And quite obviously, when we set custom normals per vertices, running this is absolutely useless.
1379 if (!use_vertices) {
1380 for (i = 0; i < numLoops; i++) {
1381 if (!lnors_spacearr.lspacearr[i]) {
1382 /* This should not happen in theory, but in some rare case (probably ugly geometry)
1383 * we can get some NULL loopspacearr at this point. :/
1384 * Maybe we should set those loops' edges as sharp?
1386 BLI_BITMAP_ENABLE(done_loops, i);
1387 printf("WARNING! Getting invalid NULL loop space for loop %d!\n", i);
1391 if (!BLI_BITMAP_TEST(done_loops, i)) {
1393 * * In case of mono-loop smooth fan, loops is NULL, so everything is fine (we have nothing to do).
1394 * * Loops in this linklist are ordered (in reversed order compared to how they were discovered by
1395 * BKE_mesh_normals_loop_split(), but this is not a problem). Which means if we find a
1396 * mismatching clnor, we know all remaining loops will have to be in a new, different smooth fan/
1398 * * In smooth fan case, we compare each clnor against a ref one, to avoid small differences adding
1399 * up into a real big one in the end!
1401 LinkNode *loops = lnors_spacearr.lspacearr[i]->loops;
1402 MLoop *prev_ml = NULL;
1403 const float *org_nor = NULL;
1406 const int lidx = GET_INT_FROM_POINTER(loops->link);
1407 MLoop *ml = &mloops[lidx];
1408 const int nidx = lidx;
1409 float *nor = custom_loopnors[nidx];
1411 if (is_zero_v3(nor)) {
1418 else if (dot_v3v3(org_nor, nor) < LNOR_SPACE_TRIGO_THRESHOLD) {
1419 /* Current normal differs too much from org one, we have to tag the edge between
1420 * previous loop's face and current's one as sharp.
1421 * We know those two loops do not point to the same edge, since we do not allow reversed winding
1422 * in a same smooth fan.
1424 const MPoly *mp = &mpolys[loop_to_poly[lidx]];
1425 const MLoop *mlp = &mloops[(lidx == mp->loopstart) ? mp->loopstart + mp->totloop - 1 : lidx - 1];
1426 medges[(prev_ml->e == mlp->e) ? prev_ml->e : ml->e].flag |= ME_SHARP;
1432 loops = loops->next;
1433 BLI_BITMAP_ENABLE(done_loops, lidx);
1435 BLI_BITMAP_ENABLE(done_loops, i); /* For single loops, where lnors_spacearr.lspacearr[i]->loops is NULL. */
1439 /* And now, recompute our new auto lnors and lnor spacearr! */
1440 BKE_lnor_spacearr_clear(&lnors_spacearr);
1441 BKE_mesh_normals_loop_split(mverts, numVerts, medges, numEdges, mloops, lnors, numLoops,
1442 mpolys, polynors, numPolys, use_split_normals, split_angle,
1443 &lnors_spacearr, NULL, loop_to_poly);
1446 BLI_BITMAP_SET_ALL(done_loops, true, (size_t)numLoops);
1449 /* And we just have to convert plain object-space custom normals to our lnor space-encoded ones. */
1450 for (i = 0; i < numLoops; i++) {
1451 if (!lnors_spacearr.lspacearr[i]) {
1452 BLI_BITMAP_DISABLE(done_loops, i);
1453 printf("WARNING! Still getting invalid NULL loop space in second loop for loop %d!\n", i);
1457 if (BLI_BITMAP_TEST_BOOL(done_loops, i)) {
1458 /* Note we accumulate and average all custom normals in current smooth fan, to avoid getting different
1459 * clnors data (tiny differences in plain custom normals can give rather huge differences in
1460 * computed 2D factors).
1462 LinkNode *loops = lnors_spacearr.lspacearr[i]->loops;
1466 short clnor_data_tmp[2], *clnor_data;
1470 const int lidx = GET_INT_FROM_POINTER(loops->link);
1471 const int nidx = use_vertices ? (int)mloops[lidx].v : lidx;
1472 float *nor = custom_loopnors[nidx];
1474 if (is_zero_v3(nor)) {
1479 add_v3_v3(avg_nor, nor);
1480 BLI_SMALLSTACK_PUSH(clnors_data, (short *)r_clnors_data[lidx]);
1482 loops = loops->next;
1483 BLI_BITMAP_DISABLE(done_loops, lidx);
1486 mul_v3_fl(avg_nor, 1.0f / (float)nbr_nors);
1487 BKE_lnor_space_custom_normal_to_data(lnors_spacearr.lspacearr[i], avg_nor, clnor_data_tmp);
1489 while ((clnor_data = BLI_SMALLSTACK_POP(clnors_data))) {
1490 clnor_data[0] = clnor_data_tmp[0];
1491 clnor_data[1] = clnor_data_tmp[1];
1495 const int nidx = use_vertices ? (int)mloops[i].v : i;
1496 float *nor = custom_loopnors[nidx];
1498 BKE_lnor_space_custom_normal_to_data(lnors_spacearr.lspacearr[i], nor, r_clnors_data[i]);
1499 BLI_BITMAP_DISABLE(done_loops, i);
1505 MEM_freeN(loop_to_poly);
1506 MEM_freeN(done_loops);
1507 BKE_lnor_spacearr_free(&lnors_spacearr);
1510 void BKE_mesh_normals_loop_custom_set(
1511 const MVert *mverts, const int numVerts, MEdge *medges, const int numEdges,
1512 MLoop *mloops, float (*custom_loopnors)[3], const int numLoops,
1513 MPoly *mpolys, const float (*polynors)[3], const int numPolys,
1514 short (*r_clnors_data)[2])
1516 mesh_normals_loop_custom_set(mverts, numVerts, medges, numEdges, mloops, custom_loopnors, numLoops,
1517 mpolys, polynors, numPolys, r_clnors_data, false);
1520 void BKE_mesh_normals_loop_custom_from_vertices_set(
1521 const MVert *mverts, float (*custom_vertnors)[3], const int numVerts,
1522 MEdge *medges, const int numEdges, MLoop *mloops, const int numLoops,
1523 MPoly *mpolys, const float (*polynors)[3], const int numPolys,
1524 short (*r_clnors_data)[2])
1526 mesh_normals_loop_custom_set(mverts, numVerts, medges, numEdges, mloops, custom_vertnors, numLoops,
1527 mpolys, polynors, numPolys, r_clnors_data, true);
1530 #undef LNOR_SPACE_TRIGO_THRESHOLD
1535 /* -------------------------------------------------------------------- */
1537 /** \name Mesh Tangent Calculations
1540 /* Tangent space utils. */
1544 const MPoly *mpolys; /* faces */
1545 const MLoop *mloops; /* faces's vertices */
1546 const MVert *mverts; /* vertices */
1547 const MLoopUV *luvs; /* texture coordinates */
1548 float (*lnors)[3]; /* loops' normals */
1549 float (*tangents)[4]; /* output tangents */
1550 int num_polys; /* number of polygons */
1553 /* Mikktspace's API */
1554 static int get_num_faces(const SMikkTSpaceContext *pContext)
1556 BKEMeshToTangent *p_mesh = (BKEMeshToTangent *)pContext->m_pUserData;
1557 return p_mesh->num_polys;
1560 static int get_num_verts_of_face(const SMikkTSpaceContext *pContext, const int face_idx)
1562 BKEMeshToTangent *p_mesh = (BKEMeshToTangent *)pContext->m_pUserData;
1563 return p_mesh->mpolys[face_idx].totloop;
1566 static void get_position(const SMikkTSpaceContext *pContext, float r_co[3], const int face_idx, const int vert_idx)
1568 BKEMeshToTangent *p_mesh = (BKEMeshToTangent *)pContext->m_pUserData;
1569 const int loop_idx = p_mesh->mpolys[face_idx].loopstart + vert_idx;
1570 copy_v3_v3(r_co, p_mesh->mverts[p_mesh->mloops[loop_idx].v].co);
1573 static void get_texture_coordinate(const SMikkTSpaceContext *pContext, float r_uv[2], const int face_idx,
1576 BKEMeshToTangent *p_mesh = (BKEMeshToTangent *)pContext->m_pUserData;
1577 copy_v2_v2(r_uv, p_mesh->luvs[p_mesh->mpolys[face_idx].loopstart + vert_idx].uv);
1580 static void get_normal(const SMikkTSpaceContext *pContext, float r_no[3], const int face_idx, const int vert_idx)
1582 BKEMeshToTangent *p_mesh = (BKEMeshToTangent *)pContext->m_pUserData;
1583 copy_v3_v3(r_no, p_mesh->lnors[p_mesh->mpolys[face_idx].loopstart + vert_idx]);
1586 static void set_tspace(const SMikkTSpaceContext *pContext, const float fv_tangent[3], const float face_sign,
1587 const int face_idx, const int vert_idx)
1589 BKEMeshToTangent *p_mesh = (BKEMeshToTangent *)pContext->m_pUserData;
1590 float *p_res = p_mesh->tangents[p_mesh->mpolys[face_idx].loopstart + vert_idx];
1591 copy_v3_v3(p_res, fv_tangent);
1592 p_res[3] = face_sign;
1596 * Compute simplified tangent space normals, i.e. tangent vector + sign of bi-tangent one, which combined with
1597 * split normals can be used to recreate the full tangent space.
1598 * Note: * The mesh should be made of only tris and quads!
1600 void BKE_mesh_loop_tangents_ex(
1601 const MVert *mverts, const int UNUSED(numVerts), const MLoop *mloops,
1602 float (*r_looptangent)[4], float (*loopnors)[3], const MLoopUV *loopuvs,
1603 const int UNUSED(numLoops), const MPoly *mpolys, const int numPolys,
1604 ReportList *reports)
1606 BKEMeshToTangent mesh_to_tangent = {NULL};
1607 SMikkTSpaceContext s_context = {NULL};
1608 SMikkTSpaceInterface s_interface = {NULL};
1613 /* First check we do have a tris/quads only mesh. */
1614 for (mp = mpolys, mp_index = 0; mp_index < numPolys; mp++, mp_index++) {
1615 if (mp->totloop > 4) {
1616 BKE_report(reports, RPT_ERROR, "Tangent space can only be computed for tris/quads, aborting");
1621 /* Compute Mikktspace's tangent normals. */
1622 mesh_to_tangent.mpolys = mpolys;
1623 mesh_to_tangent.mloops = mloops;
1624 mesh_to_tangent.mverts = mverts;
1625 mesh_to_tangent.luvs = loopuvs;
1626 mesh_to_tangent.lnors = loopnors;
1627 mesh_to_tangent.tangents = r_looptangent;
1628 mesh_to_tangent.num_polys = numPolys;
1630 s_context.m_pUserData = &mesh_to_tangent;
1631 s_context.m_pInterface = &s_interface;
1632 s_interface.m_getNumFaces = get_num_faces;
1633 s_interface.m_getNumVerticesOfFace = get_num_verts_of_face;
1634 s_interface.m_getPosition = get_position;
1635 s_interface.m_getTexCoord = get_texture_coordinate;
1636 s_interface.m_getNormal = get_normal;
1637 s_interface.m_setTSpaceBasic = set_tspace;
1640 if (genTangSpaceDefault(&s_context) == false) {
1641 BKE_report(reports, RPT_ERROR, "Mikktspace failed to generate tangents for this mesh!");
1646 * Wrapper around BKE_mesh_loop_tangents_ex, which takes care of most boiling code.
1648 * - There must be a valid loop's CD_NORMALS available.
1649 * - The mesh should be made of only tris and quads!
1651 void BKE_mesh_loop_tangents(Mesh *mesh, const char *uvmap, float (*r_looptangents)[4], ReportList *reports)
1654 float (*loopnors)[3];
1656 /* Check we have valid texture coordinates first! */
1658 loopuvs = CustomData_get_layer_named(&mesh->ldata, CD_MLOOPUV, uvmap);
1661 loopuvs = CustomData_get_layer(&mesh->ldata, CD_MLOOPUV);
1664 BKE_reportf(reports, RPT_ERROR, "Tangent space computation needs an UVMap, \"%s\" not found, aborting", uvmap);
1668 loopnors = CustomData_get_layer(&mesh->ldata, CD_NORMAL);
1670 BKE_report(reports, RPT_ERROR, "Tangent space computation needs loop normals, none found, aborting");
1674 BKE_mesh_loop_tangents_ex(mesh->mvert, mesh->totvert, mesh->mloop, r_looptangents,
1675 loopnors, loopuvs, mesh->totloop, mesh->mpoly, mesh->totpoly, reports);
1681 /* -------------------------------------------------------------------- */
1683 /** \name Polygon Calculations
1687 * COMPUTE POLY NORMAL
1689 * Computes the normal of a planar
1690 * polygon See Graphics Gems for
1691 * computing newell normal.
1694 static void mesh_calc_ngon_normal(
1695 const MPoly *mpoly, const MLoop *loopstart,
1696 const MVert *mvert, float normal[3])
1698 const int nverts = mpoly->totloop;
1699 const float *v_prev = mvert[loopstart[nverts - 1].v].co;
1700 const float *v_curr;
1705 /* Newell's Method */
1706 for (i = 0; i < nverts; i++) {
1707 v_curr = mvert[loopstart[i].v].co;
1708 add_newell_cross_v3_v3v3(normal, v_prev, v_curr);
1712 if (UNLIKELY(normalize_v3(normal) == 0.0f)) {
1713 normal[2] = 1.0f; /* other axis set to 0.0 */
1717 void BKE_mesh_calc_poly_normal(
1718 const MPoly *mpoly, const MLoop *loopstart,
1719 const MVert *mvarray, float r_no[3])
1721 if (mpoly->totloop > 4) {
1722 mesh_calc_ngon_normal(mpoly, loopstart, mvarray, r_no);
1724 else if (mpoly->totloop == 3) {
1726 mvarray[loopstart[0].v].co,
1727 mvarray[loopstart[1].v].co,
1728 mvarray[loopstart[2].v].co
1731 else if (mpoly->totloop == 4) {
1732 normal_quad_v3(r_no,
1733 mvarray[loopstart[0].v].co,
1734 mvarray[loopstart[1].v].co,
1735 mvarray[loopstart[2].v].co,
1736 mvarray[loopstart[3].v].co
1739 else { /* horrible, two sided face! */
1745 /* duplicate of function above _but_ takes coords rather then mverts */
1746 static void mesh_calc_ngon_normal_coords(
1747 const MPoly *mpoly, const MLoop *loopstart,
1748 const float (*vertex_coords)[3], float r_normal[3])
1750 const int nverts = mpoly->totloop;
1751 const float *v_prev = vertex_coords[loopstart[nverts - 1].v];
1752 const float *v_curr;
1757 /* Newell's Method */
1758 for (i = 0; i < nverts; i++) {
1759 v_curr = vertex_coords[loopstart[i].v];
1760 add_newell_cross_v3_v3v3(r_normal, v_prev, v_curr);
1764 if (UNLIKELY(normalize_v3(r_normal) == 0.0f)) {
1765 r_normal[2] = 1.0f; /* other axis set to 0.0 */
1769 void BKE_mesh_calc_poly_normal_coords(
1770 const MPoly *mpoly, const MLoop *loopstart,
1771 const float (*vertex_coords)[3], float r_no[3])
1773 if (mpoly->totloop > 4) {
1774 mesh_calc_ngon_normal_coords(mpoly, loopstart, vertex_coords, r_no);
1776 else if (mpoly->totloop == 3) {
1778 vertex_coords[loopstart[0].v],
1779 vertex_coords[loopstart[1].v],
1780 vertex_coords[loopstart[2].v]
1783 else if (mpoly->totloop == 4) {
1784 normal_quad_v3(r_no,
1785 vertex_coords[loopstart[0].v],
1786 vertex_coords[loopstart[1].v],
1787 vertex_coords[loopstart[2].v],
1788 vertex_coords[loopstart[3].v]
1791 else { /* horrible, two sided face! */
1798 static void mesh_calc_ngon_center(
1799 const MPoly *mpoly, const MLoop *loopstart,
1800 const MVert *mvert, float cent[3])
1802 const float w = 1.0f / (float)mpoly->totloop;
1807 for (i = 0; i < mpoly->totloop; i++) {
1808 madd_v3_v3fl(cent, mvert[(loopstart++)->v].co, w);
1812 void BKE_mesh_calc_poly_center(
1813 const MPoly *mpoly, const MLoop *loopstart,
1814 const MVert *mvarray, float r_cent[3])
1816 if (mpoly->totloop == 3) {
1818 mvarray[loopstart[0].v].co,
1819 mvarray[loopstart[1].v].co,
1820 mvarray[loopstart[2].v].co
1823 else if (mpoly->totloop == 4) {
1824 cent_quad_v3(r_cent,
1825 mvarray[loopstart[0].v].co,
1826 mvarray[loopstart[1].v].co,
1827 mvarray[loopstart[2].v].co,
1828 mvarray[loopstart[3].v].co
1832 mesh_calc_ngon_center(mpoly, loopstart, mvarray, r_cent);
1836 /* note, passing polynormal is only a speedup so we can skip calculating it */
1837 float BKE_mesh_calc_poly_area(
1838 const MPoly *mpoly, const MLoop *loopstart,
1839 const MVert *mvarray)
1841 if (mpoly->totloop == 3) {
1842 return area_tri_v3(mvarray[loopstart[0].v].co,
1843 mvarray[loopstart[1].v].co,
1844 mvarray[loopstart[2].v].co
1849 const MLoop *l_iter = loopstart;
1851 float (*vertexcos)[3] = BLI_array_alloca(vertexcos, (size_t)mpoly->totloop);
1853 /* pack vertex cos into an array for area_poly_v3 */
1854 for (i = 0; i < mpoly->totloop; i++, l_iter++) {
1855 copy_v3_v3(vertexcos[i], mvarray[l_iter->v].co);
1858 /* finally calculate the area */
1859 area = area_poly_v3((const float (*)[3])vertexcos, (unsigned int)mpoly->totloop);
1865 /* note, results won't be correct if polygon is non-planar */
1866 static float mesh_calc_poly_planar_area_centroid(
1867 const MPoly *mpoly, const MLoop *loopstart, const MVert *mvarray,
1872 float total_area = 0.0f;
1873 float v1[3], v2[3], v3[3], normal[3], tri_cent[3];
1875 BKE_mesh_calc_poly_normal(mpoly, loopstart, mvarray, normal);
1876 copy_v3_v3(v1, mvarray[loopstart[0].v].co);
1877 copy_v3_v3(v2, mvarray[loopstart[1].v].co);
1880 for (i = 2; i < mpoly->totloop; i++) {
1881 copy_v3_v3(v3, mvarray[loopstart[i].v].co);
1883 tri_area = area_tri_signed_v3(v1, v2, v3, normal);
1884 total_area += tri_area;
1886 cent_tri_v3(tri_cent, v1, v2, v3);
1887 madd_v3_v3fl(r_cent, tri_cent, tri_area);
1892 mul_v3_fl(r_cent, 1.0f / total_area);
1897 #if 0 /* slow version of the function below */
1898 void BKE_mesh_calc_poly_angles(MPoly *mpoly, MLoop *loopstart,
1899 MVert *mvarray, float angles[])
1902 MLoop *mloop = &loopstart[-mpoly->loopstart];
1905 for (j = 0, ml = loopstart; j < mpoly->totloop; j++, ml++) {
1906 MLoop *ml_prev = ME_POLY_LOOP_PREV(mloop, mpoly, j);
1907 MLoop *ml_next = ME_POLY_LOOP_NEXT(mloop, mpoly, j);
1911 sub_v3_v3v3(e1, mvarray[ml_next->v].co, mvarray[ml->v].co);
1912 sub_v3_v3v3(e2, mvarray[ml_prev->v].co, mvarray[ml->v].co);
1914 angles[j] = (float)M_PI - angle_v3v3(e1, e2);
1918 #else /* equivalent the function above but avoid multiple subtractions + normalize */
1920 void BKE_mesh_calc_poly_angles(
1921 const MPoly *mpoly, const MLoop *loopstart,
1922 const MVert *mvarray, float angles[])
1927 int i_this = mpoly->totloop - 1;
1930 sub_v3_v3v3(nor_prev, mvarray[loopstart[i_this - 1].v].co, mvarray[loopstart[i_this].v].co);
1931 normalize_v3(nor_prev);
1933 while (i_next < mpoly->totloop) {
1934 sub_v3_v3v3(nor_next, mvarray[loopstart[i_this].v].co, mvarray[loopstart[i_next].v].co);
1935 normalize_v3(nor_next);
1936 angles[i_this] = angle_normalized_v3v3(nor_prev, nor_next);
1939 copy_v3_v3(nor_prev, nor_next);
1946 void BKE_mesh_poly_edgehash_insert(EdgeHash *ehash, const MPoly *mp, const MLoop *mloop)
1948 const MLoop *ml, *ml_next;
1949 int i = mp->totloop;
1951 ml_next = mloop; /* first loop */
1952 ml = &ml_next[i - 1]; /* last loop */
1955 BLI_edgehash_reinsert(ehash, ml->v, ml_next->v, NULL);
1962 void BKE_mesh_poly_edgebitmap_insert(unsigned int *edge_bitmap, const MPoly *mp, const MLoop *mloop)
1965 int i = mp->totloop;
1970 BLI_BITMAP_ENABLE(edge_bitmap, ml->e);
1978 /* -------------------------------------------------------------------- */
1980 /** \name Mesh Center Calculation
1983 bool BKE_mesh_center_median(const Mesh *me, float r_cent[3])
1985 int i = me->totvert;
1988 for (mvert = me->mvert; i--; mvert++) {
1989 add_v3_v3(r_cent, mvert->co);
1991 /* otherwise we get NAN for 0 verts */
1993 mul_v3_fl(r_cent, 1.0f / (float)me->totvert);
1996 return (me->totvert != 0);
1999 bool BKE_mesh_center_bounds(const Mesh *me, float r_cent[3])
2001 float min[3], max[3];
2002 INIT_MINMAX(min, max);
2003 if (BKE_mesh_minmax(me, min, max)) {
2004 mid_v3_v3v3(r_cent, min, max);
2011 bool BKE_mesh_center_centroid(const Mesh *me, float r_cent[3])
2013 int i = me->totpoly;
2016 float total_area = 0.0f;
2021 /* calculate a weighted average of polygon centroids */
2022 for (mpoly = me->mpoly; i--; mpoly++) {
2023 poly_area = mesh_calc_poly_planar_area_centroid(mpoly, me->mloop + mpoly->loopstart, me->mvert, poly_cent);
2025 madd_v3_v3fl(r_cent, poly_cent, poly_area);
2026 total_area += poly_area;
2028 /* otherwise we get NAN for 0 polys */
2030 mul_v3_fl(r_cent, 1.0f / total_area);
2033 /* zero area faces cause this, fallback to median */
2034 if (UNLIKELY(!is_finite_v3(r_cent))) {
2035 return BKE_mesh_center_median(me, r_cent);
2038 return (me->totpoly != 0);
2043 /* -------------------------------------------------------------------- */
2045 /** \name Mesh Volume Calculation
2048 static bool mesh_calc_center_centroid_ex(
2049 const MVert *mverts, int UNUSED(numVerts),
2050 const MLoopTri *lt, int numTris,
2051 const MLoop *mloop, float r_center[3])
2062 for (t = 0; t < numTris; t++, lt++) {
2063 const MVert *v1 = &mverts[mloop[lt->tri[0]].v];
2064 const MVert *v2 = &mverts[mloop[lt->tri[1]].v];
2065 const MVert *v3 = &mverts[mloop[lt->tri[2]].v];
2068 area = area_tri_v3(v1->co, v2->co, v3->co);
2069 madd_v3_v3fl(r_center, v1->co, area);
2070 madd_v3_v3fl(r_center, v2->co, area);
2071 madd_v3_v3fl(r_center, v3->co, area);
2074 if (totweight == 0.0f)
2077 mul_v3_fl(r_center, 1.0f / (3.0f * totweight));
2082 void BKE_mesh_calc_volume(const MVert *mverts, const int numVerts,
2083 const MLoopTri *lt, const int numTris,
2084 const MLoop *mloop, float *r_vol, float *r_com)
2090 if (r_vol) *r_vol = 0.0f;
2091 if (r_com) zero_v3(r_com);
2096 if (!mesh_calc_center_centroid_ex(mverts, numVerts, lt, numTris, mloop, center))
2100 for (f = 0; f < numTris; f++, lt++) {
2101 const MVert *v1 = &mverts[mloop[lt->tri[0]].v];
2102 const MVert *v2 = &mverts[mloop[lt->tri[1]].v];
2103 const MVert *v3 = &mverts[mloop[lt->tri[2]].v];
2106 vol = volume_tetrahedron_signed_v3(center, v1->co, v2->co, v3->co);
2111 /* averaging factor 1/4 is applied in the end */
2112 madd_v3_v3fl(r_com, center, vol); // XXX could extract this
2113 madd_v3_v3fl(r_com, v1->co, vol);
2114 madd_v3_v3fl(r_com, v2->co, vol);
2115 madd_v3_v3fl(r_com, v3->co, vol);
2119 /* Note: Depending on arbitrary centroid position,
2120 * totvol can become negative even for a valid mesh.
2121 * The true value is always the positive value.
2124 *r_vol = fabsf(totvol);
2127 /* Note: Factor 1/4 is applied once for all vertices here.
2128 * This also automatically negates the vector if totvol is negative.
2131 mul_v3_fl(r_com, 0.25f / totvol);
2136 /* -------------------------------------------------------------------- */
2138 /** \name NGon Tessellation (NGon/Tessface Conversion)
2142 * Convert a triangle or quadrangle of loop/poly data to tessface data
2144 void BKE_mesh_loops_to_mface_corners(
2145 CustomData *fdata, CustomData *ldata,
2146 CustomData *pdata, unsigned int lindex[4], int findex,
2147 const int polyindex,
2148 const int mf_len, /* 3 or 4 */
2150 /* cache values to avoid lookups every time */
2151 const int numTex, /* CustomData_number_of_layers(pdata, CD_MTEXPOLY) */
2152 const int numCol, /* CustomData_number_of_layers(ldata, CD_MLOOPCOL) */
2153 const bool hasPCol, /* CustomData_has_layer(ldata, CD_PREVIEW_MLOOPCOL) */
2154 const bool hasOrigSpace, /* CustomData_has_layer(ldata, CD_ORIGSPACE_MLOOP) */
2155 const bool hasLNor /* CustomData_has_layer(ldata, CD_NORMAL) */
2165 for (i = 0; i < numTex; i++) {
2166 texface = CustomData_get_n(fdata, CD_MTFACE, findex, i);
2167 texpoly = CustomData_get_n(pdata, CD_MTEXPOLY, polyindex, i);
2169 ME_MTEXFACE_CPY(texface, texpoly);
2171 for (j = 0; j < mf_len; j++) {
2172 mloopuv = CustomData_get_n(ldata, CD_MLOOPUV, (int)lindex[j], i);
2173 copy_v2_v2(texface->uv[j], mloopuv->uv);
2177 for (i = 0; i < numCol; i++) {
2178 mcol = CustomData_get_n(fdata, CD_MCOL, findex, i);
2180 for (j = 0; j < mf_len; j++) {
2181 mloopcol = CustomData_get_n(ldata, CD_MLOOPCOL, (int)lindex[j], i);
2182 MESH_MLOOPCOL_TO_MCOL(mloopcol, &mcol[j]);
2187 mcol = CustomData_get(fdata, findex, CD_PREVIEW_MCOL);
2189 for (j = 0; j < mf_len; j++) {
2190 mloopcol = CustomData_get(ldata, (int)lindex[j], CD_PREVIEW_MLOOPCOL);
2191 MESH_MLOOPCOL_TO_MCOL(mloopcol, &mcol[j]);
2196 OrigSpaceFace *of = CustomData_get(fdata, findex, CD_ORIGSPACE);
2199 for (j = 0; j < mf_len; j++) {
2200 lof = CustomData_get(ldata, (int)lindex[j], CD_ORIGSPACE_MLOOP);
2201 copy_v2_v2(of->uv[j], lof->uv);
2206 short (*tlnors)[3] = CustomData_get(fdata, findex, CD_TESSLOOPNORMAL);
2208 for (j = 0; j < mf_len; j++) {
2209 normal_float_to_short_v3(tlnors[j], CustomData_get(ldata, (int)lindex[j], CD_NORMAL));
2215 * Convert all CD layers from loop/poly to tessface data.
2217 * \param loopindices is an array of an int[4] per tessface, mapping tessface's verts to loops indices.
2219 * \note when mface is not NULL, mface[face_index].v4 is used to test quads, else, loopindices[face_index][3] is used.
2221 void BKE_mesh_loops_to_tessdata(CustomData *fdata, CustomData *ldata, CustomData *pdata, MFace *mface,
2222 int *polyindices, unsigned int (*loopindices)[4], const int num_faces)
2224 /* Note: performances are sub-optimal when we get a NULL mface, we could be ~25% quicker with dedicated code...
2225 * Issue is, unless having two different functions with nearly the same code, there's not much ways to solve
2226 * this. Better imho to live with it for now. :/ --mont29
2228 const int numTex = CustomData_number_of_layers(pdata, CD_MTEXPOLY);
2229 const int numCol = CustomData_number_of_layers(ldata, CD_MLOOPCOL);
2230 const bool hasPCol = CustomData_has_layer(ldata, CD_PREVIEW_MLOOPCOL);
2231 const bool hasOrigSpace = CustomData_has_layer(ldata, CD_ORIGSPACE_MLOOP);
2232 const bool hasLoopNormal = CustomData_has_layer(ldata, CD_NORMAL);
2235 unsigned int (*lidx)[4];
2237 for (i = 0; i < numTex; i++) {
2238 MTFace *texface = CustomData_get_layer_n(fdata, CD_MTFACE, i);
2239 MTexPoly *texpoly = CustomData_get_layer_n(pdata, CD_MTEXPOLY, i);
2240 MLoopUV *mloopuv = CustomData_get_layer_n(ldata, CD_MLOOPUV, i);
2242 for (findex = 0, pidx = polyindices, lidx = loopindices;
2244 pidx++, lidx++, findex++, texface++)
2246 ME_MTEXFACE_CPY(texface, &texpoly[*pidx]);
2248 for (j = (mface ? mface[findex].v4 : (*lidx)[3]) ? 4 : 3; j--;) {
2249 copy_v2_v2(texface->uv[j], mloopuv[(*lidx)[j]].uv);
2254 for (i = 0; i < numCol; i++) {
2255 MCol (*mcol)[4] = CustomData_get_layer_n(fdata, CD_MCOL, i);
2256 MLoopCol *mloopcol = CustomData_get_layer_n(ldata, CD_MLOOPCOL, i);
2258 for (findex = 0, lidx = loopindices; findex < num_faces; lidx++, findex++, mcol++) {
2259 for (j = (mface ? mface[findex].v4 : (*lidx)[3]) ? 4 : 3; j--;) {
2260 MESH_MLOOPCOL_TO_MCOL(&mloopcol[(*lidx)[j]], &(*mcol)[j]);
2266 MCol (*mcol)[4] = CustomData_get_layer(fdata, CD_PREVIEW_MCOL);
2267 MLoopCol *mloopcol = CustomData_get_layer(ldata, CD_PREVIEW_MLOOPCOL);
2269 for (findex = 0, lidx = loopindices; findex < num_faces; lidx++, findex++, mcol++) {
2270 for (j = (mface ? mface[findex].v4 : (*lidx)[3]) ? 4 : 3; j--;) {
2271 MESH_MLOOPCOL_TO_MCOL(&mloopcol[(*lidx)[j]], &(*mcol)[j]);
2277 OrigSpaceFace *of = CustomData_get_layer(fdata, CD_ORIGSPACE);
2278 OrigSpaceLoop *lof = CustomData_get_layer(ldata, CD_ORIGSPACE_MLOOP);
2280 for (findex = 0, lidx = loopindices; findex < num_faces; lidx++, findex++, of++) {
2281 for (j = (mface ? mface[findex].v4 : (*lidx)[3]) ? 4 : 3; j--;) {
2282 copy_v2_v2(of->uv[j], lof[(*lidx)[j]].uv);
2287 if (hasLoopNormal) {
2288 short (*fnors)[4][3] = CustomData_get_layer(fdata, CD_TESSLOOPNORMAL);
2289 float (*lnors)[3] = CustomData_get_layer(ldata, CD_NORMAL);
2291 for (findex = 0, lidx = loopindices; findex < num_faces; lidx++, findex++, fnors++) {
2292 for (j = (mface ? mface[findex].v4 : (*lidx)[3]) ? 4 : 3; j--;) {
2293 normal_float_to_short_v3((*fnors)[j], lnors[(*lidx)[j]]);
2300 * Recreate tessellation.
2302 * \param do_face_nor_copy: Controls whether the normals from the poly are copied to the tessellated faces.
2304 * \return number of tessellation faces.
2306 int BKE_mesh_recalc_tessellation(
2307 CustomData *fdata, CustomData *ldata, CustomData *pdata,
2309 int totface, int totloop, int totpoly,
2310 const bool do_face_nor_copy)
2312 /* use this to avoid locking pthread for _every_ polygon
2313 * and calling the fill function */
2315 #define USE_TESSFACE_SPEEDUP
2316 #define USE_TESSFACE_QUADS /* NEEDS FURTHER TESTING */
2318 /* We abuse MFace->edcode to tag quad faces. See below for details. */
2319 #define TESSFACE_IS_QUAD 1
2321 const int looptris_tot = poly_to_tri_count(totpoly, totloop);
2326 MemArena *arena = NULL;
2327 int *mface_to_poly_map;
2328 unsigned int (*lindices)[4];
2329 int poly_index, mface_index;
2332 mpoly = CustomData_get_layer(pdata, CD_MPOLY);
2333 mloop = CustomData_get_layer(ldata, CD_MLOOP);
2335 /* allocate the length of totfaces, avoid many small reallocs,
2336 * if all faces are tri's it will be correct, quads == 2x allocs */
2337 /* take care. we are _not_ calloc'ing so be sure to initialize each field */
2338 mface_to_poly_map = MEM_mallocN(sizeof(*mface_to_poly_map) * (size_t)looptris_tot, __func__);
2339 mface = MEM_mallocN(sizeof(*mface) * (size_t)looptris_tot, __func__);
2340 lindices = MEM_mallocN(sizeof(*lindices) * (size_t)looptris_tot, __func__);
2344 for (poly_index = 0; poly_index < totpoly; poly_index++, mp++) {
2345 const unsigned int mp_loopstart = (unsigned int)mp->loopstart;
2346 const unsigned int mp_totloop = (unsigned int)mp->totloop;
2347 unsigned int l1, l2, l3, l4;
2349 if (mp_totloop < 3) {
2353 #ifdef USE_TESSFACE_SPEEDUP
2355 #define ML_TO_MF(i1, i2, i3) \
2356 mface_to_poly_map[mface_index] = poly_index; \
2357 mf = &mface[mface_index]; \
2358 lidx = lindices[mface_index]; \
2359 /* set loop indices, transformed to vert indices later */ \
2360 l1 = mp_loopstart + i1; \
2361 l2 = mp_loopstart + i2; \
2362 l3 = mp_loopstart + i3; \
2363 mf->v1 = mloop[l1].v; \
2364 mf->v2 = mloop[l2].v; \
2365 mf->v3 = mloop[l3].v; \
2371 mf->mat_nr = mp->mat_nr; \
2372 mf->flag = mp->flag; \
2376 /* ALMOST IDENTICAL TO DEFINE ABOVE (see EXCEPTION) */
2377 #define ML_TO_MF_QUAD() \
2378 mface_to_poly_map[mface_index] = poly_index; \
2379 mf = &mface[mface_index]; \
2380 lidx = lindices[mface_index]; \
2381 /* set loop indices, transformed to vert indices later */ \
2382 l1 = mp_loopstart + 0; /* EXCEPTION */ \
2383 l2 = mp_loopstart + 1; /* EXCEPTION */ \
2384 l3 = mp_loopstart + 2; /* EXCEPTION */ \
2385 l4 = mp_loopstart + 3; /* EXCEPTION */ \
2386 mf->v1 = mloop[l1].v; \
2387 mf->v2 = mloop[l2].v; \
2388 mf->v3 = mloop[l3].v; \
2389 mf->v4 = mloop[l4].v; \
2394 mf->mat_nr = mp->mat_nr; \
2395 mf->flag = mp->flag; \
2396 mf->edcode = TESSFACE_IS_QUAD; \
2400 else if (mp_totloop == 3) {
2404 else if (mp_totloop == 4) {
2405 #ifdef USE_TESSFACE_QUADS
2415 #endif /* USE_TESSFACE_SPEEDUP */
2417 const float *co_curr, *co_prev;
2421 float axis_mat[3][3];
2422 float (*projverts)[2];
2423 unsigned int (*tris)[3];
2425 const unsigned int totfilltri = mp_totloop - 2;
2427 if (UNLIKELY(arena == NULL)) {
2428 arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
2431 tris = BLI_memarena_alloc(arena, sizeof(*tris) * (size_t)totfilltri);
2432 projverts = BLI_memarena_alloc(arena, sizeof(*projverts) * (size_t)mp_totloop);
2436 /* calc normal, flipped: to get a positive 2d cross product */
2437 ml = mloop + mp_loopstart;
2438 co_prev = mvert[ml[mp_totloop - 1].v].co;
2439 for (j = 0; j < mp_totloop; j++, ml++) {
2440 co_curr = mvert[ml->v].co;
2441 add_newell_cross_v3_v3v3(normal, co_prev, co_curr);
2444 if (UNLIKELY(normalize_v3(normal) == 0.0f)) {
2448 /* project verts to 2d */
2449 axis_dominant_v3_to_m3_negate(axis_mat, normal);
2451 ml = mloop + mp_loopstart;
2452 for (j = 0; j < mp_totloop; j++, ml++) {
2453 mul_v2_m3v3(projverts[j], axis_mat, mvert[ml->v].co);
2456 BLI_polyfill_calc_arena((const float (*)[2])projverts, mp_totloop, 1, tris, arena);
2459 for (j = 0; j < totfilltri; j++) {
2460 unsigned int *tri = tris[j];
2461 lidx = lindices[mface_index];
2463 mface_to_poly_map[mface_index] = poly_index;
2464 mf = &mface[mface_index];
2466 /* set loop indices, transformed to vert indices later */
2467 l1 = mp_loopstart + tri[0];
2468 l2 = mp_loopstart + tri[1];
2469 l3 = mp_loopstart + tri[2];
2471 mf->v1 = mloop[l1].v;
2472 mf->v2 = mloop[l2].v;
2473 mf->v3 = mloop[l3].v;
2481 mf->mat_nr = mp->mat_nr;
2482 mf->flag = mp->flag;
2488 BLI_memarena_clear(arena);
2493 BLI_memarena_free(arena);
2497 CustomData_free(fdata, totface);
2498 totface = mface_index;
2500 BLI_assert(totface <= looptris_tot);
2502 /* not essential but without this we store over-alloc'd memory in the CustomData layers */
2503 if (LIKELY(looptris_tot != totface)) {
2504 mface = MEM_reallocN(mface, sizeof(*mface) * (size_t)totface);
2505 mface_to_poly_map = MEM_reallocN(mface_to_poly_map, sizeof(*mface_to_poly_map) * (size_t)totface);
2508 CustomData_add_layer(fdata, CD_MFACE, CD_ASSIGN, mface, totface);
2510 /* CD_ORIGINDEX will contain an array of indices from tessfaces to the polygons
2511 * they are directly tessellated from */
2512 CustomData_add_layer(fdata, CD_ORIGINDEX, CD_ASSIGN, mface_to_poly_map, totface);
2513 CustomData_from_bmeshpoly(fdata, pdata, ldata, totface);
2515 if (do_face_nor_copy) {
2516 /* If polys have a normals layer, copying that to faces can help
2517 * avoid the need to recalculate normals later */
2518 if (CustomData_has_layer(pdata, CD_NORMAL)) {
2519 float (*pnors)[3] = CustomData_get_layer(pdata, CD_NORMAL);
2520 float (*fnors)[3] = CustomData_add_layer(fdata, CD_NORMAL, CD_CALLOC, NULL, totface);
2521 for (mface_index = 0; mface_index < totface; mface_index++) {
2522 copy_v3_v3(fnors[mface_index], pnors[mface_to_poly_map[mface_index]]);
2527 /* NOTE: quad detection issue - forth vertidx vs forth loopidx:
2528 * Polygons take care of their loops ordering, hence not of their vertices ordering.
2529 * Currently, our tfaces' forth vertex index might be 0 even for a quad. However, we know our forth loop index is
2530 * never 0 for quads (because they are sorted for polygons, and our quads are still mere copies of their polygons).
2531 * So we pass NULL as MFace pointer, and BKE_mesh_loops_to_tessdata will use the forth loop index as quad test.
2534 BKE_mesh_loops_to_tessdata(fdata, ldata, pdata, NULL, mface_to_poly_map, lindices, totface);
2536 /* NOTE: quad detection issue - forth vertidx vs forth loopidx:
2537 * ...However, most TFace code uses 'MFace->v4 == 0' test to check whether it is a tri or quad.
2538 * test_index_face() will check this and rotate the tessellated face if needed.
2540 #ifdef USE_TESSFACE_QUADS
2542 for (mface_index = 0; mface_index < totface; mface_index++, mf++) {
2543 if (mf->edcode == TESSFACE_IS_QUAD) {
2544 test_index_face(mf, fdata, mface_index, 4);
2550 MEM_freeN(lindices);
2554 #undef USE_TESSFACE_SPEEDUP
2555 #undef USE_TESSFACE_QUADS
2558 #undef ML_TO_MF_QUAD
2563 * Calculate tessellation into #MLoopTri which exist only for this purpose.
2565 void BKE_mesh_recalc_looptri(
2566 const MLoop *mloop, const MPoly *mpoly,
2568 int totloop, int totpoly,
2571 /* use this to avoid locking pthread for _every_ polygon
2572 * and calling the fill function */
2574 #define USE_TESSFACE_SPEEDUP
2579 MemArena *arena = NULL;
2580 int poly_index, mlooptri_index;
2585 for (poly_index = 0; poly_index < totpoly; poly_index++, mp++) {
2586 const unsigned int mp_loopstart = (unsigned int)mp->loopstart;
2587 const unsigned int mp_totloop = (unsigned int)mp->totloop;
2588 unsigned int l1, l2, l3;
2589 if (mp_totloop < 3) {
2593 #ifdef USE_TESSFACE_SPEEDUP
2595 #define ML_TO_MLT(i1, i2, i3) { \
2596 mlt = &mlooptri[mlooptri_index]; \
2597 l1 = mp_loopstart + i1; \
2598 l2 = mp_loopstart + i2; \
2599 l3 = mp_loopstart + i3; \
2600 ARRAY_SET_ITEMS(mlt->tri, l1, l2, l3); \
2601 mlt->poly = (unsigned int)poly_index; \
2604 else if (mp_totloop == 3) {
2608 else if (mp_totloop == 4) {
2614 #endif /* USE_TESSFACE_SPEEDUP */
2616 const float *co_curr, *co_prev;
2620 float axis_mat[3][3];
2621 float (*projverts)[2];
2622 unsigned int (*tris)[3];
2624 const unsigned int totfilltri = mp_totloop - 2;
2626 if (UNLIKELY(arena == NULL)) {
2627 arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
2630 tris = BLI_memarena_alloc(arena, sizeof(*tris) * (size_t)totfilltri);
2631 projverts = BLI_memarena_alloc(arena, sizeof(*projverts) * (size_t)mp_totloop);
2635 /* calc normal, flipped: to get a positive 2d cross product */
2636 ml = mloop + mp_loopstart;
2637 co_prev = mvert[ml[mp_totloop - 1].v].co;
2638 for (j = 0; j < mp_totloop; j++, ml++) {
2639 co_curr = mvert[ml->v].co;
2640 add_newell_cross_v3_v3v3(normal, co_prev, co_curr);
2643 if (UNLIKELY(normalize_v3(normal) == 0.0f)) {
2647 /* project verts to 2d */
2648 axis_dominant_v3_to_m3_negate(axis_mat, normal);
2650 ml = mloop + mp_loopstart;
2651 for (j = 0; j < mp_totloop; j++, ml++) {
2652 mul_v2_m3v3(projverts[j], axis_mat, mvert[ml->v].co);
2655 BLI_polyfill_calc_arena((const float (*)[2])projverts, mp_totloop, 1, tris, arena);
2658 for (j = 0; j < totfilltri; j++) {
2659 unsigned int *tri = tris[j];
2661 mlt = &mlooptri[mlooptri_index];
2663 /* set loop indices, transformed to vert indices later */
2664 l1 = mp_loopstart + tri[0];
2665 l2 = mp_loopstart + tri[1];
2666 l3 = mp_loopstart + tri[2];
2668 ARRAY_SET_ITEMS(mlt->tri, l1, l2, l3);
2669 mlt->poly = (unsigned int)poly_index;
2674 BLI_memarena_clear(arena);
2679 BLI_memarena_free(arena);
2683 BLI_assert(mlooptri_index == poly_to_tri_count(totpoly, totloop));
2684 UNUSED_VARS_NDEBUG(totloop);
2686 #undef USE_TESSFACE_SPEEDUP
2690 /* -------------------------------------------------------------------- */
2693 #ifdef USE_BMESH_SAVE_AS_COMPAT
2696 * This function recreates a tessellation.
2697 * returns number of tessellation faces.
2699 * for forwards compat only quad->tri polys to mface, skip ngons.
2701 int BKE_mesh_mpoly_to_mface(struct CustomData *fdata, struct CustomData *ldata,
2702 struct CustomData *pdata, int totface, int UNUSED(totloop), int totpoly)
2706 unsigned int lindex[4];
2713 const int numTex = CustomData_number_of_layers(pdata, CD_MTEXPOLY);
2714 const int numCol = CustomData_number_of_layers(ldata, CD_MLOOPCOL);
2715 const bool hasPCol = CustomData_has_layer(ldata, CD_PREVIEW_MLOOPCOL);
2716 const bool hasOrigSpace = CustomData_has_layer(ldata, CD_ORIGSPACE_MLOOP);
2717 const bool hasLNor = CustomData_has_layer(ldata, CD_NORMAL);
2719 /* over-alloc, ngons will be skipped */
2720 mface = MEM_mallocN(sizeof(*mface) * (size_t)totpoly, __func__);
2722 mpoly = CustomData_get_layer(pdata, CD_MPOLY);
2723 mloop = CustomData_get_layer(ldata, CD_MLOOP);
2727 for (i = 0; i < totpoly; i++, mp++) {
2728 if (ELEM(mp->totloop, 3, 4)) {
2729 const unsigned int mp_loopstart = (unsigned int)mp->loopstart;
2732 mf->mat_nr = mp->mat_nr;
2733 mf->flag = mp->flag;
2735 mf->v1 = mp_loopstart + 0;
2736 mf->v2 = mp_loopstart + 1;
2737 mf->v3 = mp_loopstart + 2;
2738 mf->v4 = (mp->totloop == 4) ? (mp_loopstart + 3) : 0;
2740 /* abuse edcode for temp storage and clear next loop */
2741 mf->edcode = (char)mp->totloop; /* only ever 3 or 4 */
2747 CustomData_free(fdata, totface);
2751 CustomData_add_layer(fdata, CD_MFACE, CD_ASSIGN, mface, totface);
2753 CustomData_from_bmeshpoly(fdata, pdata, ldata, totface);
2757 for (i = 0; i < totpoly; i++, mp++) {
2758 if (ELEM(mp->totloop, 3, 4)) {
2761 if (mf->edcode == 3) {
2762 /* sort loop indices to ensure winding is correct */
2763 /* NO SORT - looks like we can skip this */
2768 lindex[3] = 0; /* unused */
2770 /* transform loop indices to vert indices */
2771 mf->v1 = mloop[mf->v1].v;
2772 mf->v2 = mloop[mf->v2].v;
2773 mf->v3 = mloop[mf->v3].v;
2775 BKE_mesh_loops_to_mface_corners(fdata, ldata, pdata,
2777 numTex, numCol, hasPCol, hasOrigSpace, hasLNor);
2778 test_index_face(mf, fdata, k, 3);
2781 /* sort loop indices to ensure winding is correct */
2782 /* NO SORT - looks like we can skip this */
2789 /* transform loop indices to vert indices */
2790 mf->v1 = mloop[mf->v1].v;
2791 mf->v2 = mloop[mf->v2].v;
2792 mf->v3 = mloop[mf->v3].v;
2793 mf->v4 = mloop[mf->v4].v;
2795 BKE_mesh_loops_to_mface_corners(fdata, ldata, pdata,
2797 numTex, numCol, hasPCol, hasOrigSpace, hasLNor);
2798 test_index_face(mf, fdata, k, 4);
2809 #endif /* USE_BMESH_SAVE_AS_COMPAT */
2812 static void bm_corners_to_loops_ex(ID *id, CustomData *fdata, CustomData *ldata, CustomData *pdata,
2813 MFace *mface, int totloop, int findex, int loopstart, int numTex, int numCol)
2823 mf = mface + findex;
2825 for (i = 0; i < numTex; i++) {
2826 texface = CustomData_get_n(fdata, CD_MTFACE, findex, i);
2827 texpoly = CustomData_get_n(pdata, CD_MTEXPOLY, findex, i);
2829 ME_MTEXFACE_CPY(texpoly, texface);
2831 mloopuv = CustomData_get_n(ldata, CD_MLOOPUV, loopstart, i);
2832 copy_v2_v2(mloopuv->uv, texface->uv[0]); mloopuv++;
2833 copy_v2_v2(mloopuv->uv, texface->uv[1]); mloopuv++;
2834 copy_v2_v2(mloopuv->uv, texface->uv[2]); mloopuv++;
2837 copy_v2_v2(mloopuv->uv, texface->uv[3]); mloopuv++;
2841 for (i = 0; i < numCol; i++) {
2842 mloopcol = CustomData_get_n(ldata, CD_MLOOPCOL, loopstart, i);
2843 mcol = CustomData_get_n(fdata, CD_MCOL, findex, i);
2845 MESH_MLOOPCOL_FROM_MCOL(mloopcol, &mcol[0]); mloopcol++;
2846 MESH_MLOOPCOL_FROM_MCOL(mloopcol, &mcol[1]); mloopcol++;
2847 MESH_MLOOPCOL_FROM_MCOL(mloopcol, &mcol[2]); mloopcol++;
2849 MESH_MLOOPCOL_FROM_MCOL(mloopcol, &mcol[3]); mloopcol++;
2853 if (CustomData_has_layer(fdata, CD_TESSLOOPNORMAL)) {
2854 float (*lnors)[3] = CustomData_get(ldata, loopstart, CD_NORMAL);
2855 short (*tlnors)[3] = CustomData_get(fdata, findex, CD_TESSLOOPNORMAL);
2856 const int max = mf->v4 ? 4 : 3;
2858 for (i = 0; i < max; i++, lnors++, tlnors++) {
2859 normal_short_to_float_v3(*lnors, *tlnors);
2863 if (CustomData_has_layer(fdata, CD_MDISPS)) {
2864 MDisps *ld = CustomData_get(ldata, loopstart, CD_MDISPS);
2865 MDisps *fd = CustomData_get(fdata, findex, CD_MDISPS);
2866 float (*disps)[3] = fd->disps;
2867 int tot = mf->v4 ? 4 : 3;
2870 if (CustomData_external_test(fdata, CD_MDISPS)) {
2871 if (id && fdata->external) {
2872 CustomData_external_add(ldata, id, CD_MDISPS,
2873 totloop, fdata->external->filename);
2877 corners = multires_mdisp_corners(fd);
2880 /* Empty MDisp layers appear in at least one of the sintel.blend files.
2881 * Not sure why this happens, but it seems fine to just ignore them here.
2882 * If (corners == 0) for a non-empty layer though, something went wrong. */
2883 BLI_assert(fd->totdisp == 0);
2886 const int side = (int)sqrtf((float)(fd->totdisp / corners));
2887 const int side_sq = side * side;
2888 const size_t disps_size = sizeof(float[3]) * (size_t)side_sq;
2890 for (i = 0; i < tot; i++, disps += side_sq, ld++) {
2891 ld->totdisp = side_sq;
2892 ld->level = (int)(logf((float)side - 1.0f) / (float)M_LN2) + 1;
2895 MEM_freeN(ld->disps);
2897 ld->disps = MEM_mallocN(disps_size, "converted loop mdisps");
2899 memcpy(ld->disps, disps, disps_size);
2902 memset(ld->disps, 0, disps_size);
2910 void BKE_mesh_convert_mfaces_to_mpolys(Mesh *mesh)
2912 BKE_mesh_convert_mfaces_to_mpolys_ex(&mesh->id, &mesh->fdata, &mesh->ldata, &mesh->pdata,
2913 mesh->totedge, mesh->totface, mesh->totloop, mesh->totpoly,
2914 mesh->medge, mesh->mface,
2915 &mesh->totloop, &mesh->totpoly, &mesh->mloop, &mesh->mpoly);
2917 BKE_mesh_update_customdata_pointers(mesh, true);
2920 /* the same as BKE_mesh_convert_mfaces_to_mpolys but oriented to be used in do_versions from readfile.c
2921 * the difference is how active/render/clone/stencil indices are handled here
2923 * normally thay're being set from pdata which totally makes sense for meshes which are already
2924 * converted to bmesh structures, but when loading older files indices shall be updated in other
2925 * way around, so newly added pdata and ldata would have this indices set based on fdata layer
2927 * this is normally only needed when reading older files, in all other cases BKE_mesh_convert_mfaces_to_mpolys
2928 * shall be always used
2930 void BKE_mesh_do_versions_convert_mfaces_to_mpolys(Mesh *mesh)
2932 BKE_mesh_convert_mfaces_to_mpolys_ex(&mesh->id, &mesh->fdata, &mesh->ldata, &mesh->pdata,
2933 mesh->totedge, mesh->totface, mesh->totloop, mesh->totpoly,
2934 mesh->medge, mesh->mface,
2935 &mesh->totloop, &mesh->totpoly, &mesh->mloop, &mesh->mpoly);
2937 CustomData_bmesh_do_versions_update_active_layers(&mesh->fdata, &mesh->pdata, &mesh->ldata);
2939 BKE_mesh_update_customdata_pointers(mesh, true);
2942 void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, CustomData *fdata, CustomData *ldata, CustomData *pdata,
2943 int totedge_i, int totface_i, int totloop_i, int totpoly_i,
2944 MEdge *medge, MFace *mface,
2945 int *r_totloop, int *r_totpoly,
2946 MLoop **r_mloop, MPoly **r_mpoly)
2954 int i, j, totloop, totpoly, *polyindex;
2956 /* old flag, clear to allow for reuse */
2957 #define ME_FGON (1 << 3)
2959 /* just in case some of these layers are filled in (can happen with python created meshes) */
2960 CustomData_free(ldata, totloop_i);
2961 CustomData_free(pdata, totpoly_i);
2963 totpoly = totface_i;
2964 mpoly = MEM_callocN(sizeof(MPoly) * (size_t)totpoly, "mpoly converted");
2965 CustomData_add_layer(pdata, CD_MPOLY, CD_ASSIGN, mpoly, totpoly);
2967 numTex = CustomData_number_of_layers(fdata, CD_MTFACE);
2968 numCol = CustomData_number_of_layers(fdata, CD_MCOL);
2972 for (i = 0; i < totface_i; i++, mf++) {
2973 totloop += mf->v4 ? 4 : 3;
2976 mloop = MEM_callocN(sizeof(MLoop) * (size_t)totloop, "mloop converted");
2978 CustomData_add_layer(ldata, CD_MLOOP, CD_ASSIGN, mloop, totloop);
2980 CustomData_to_bmeshpoly(fdata, pdata, ldata, totloop, totpoly);
2983 /* ensure external data is transferred */
2984 CustomData_external_read(fdata, id, CD_MASK_MDISPS, totface_i);
2987 eh = BLI_edgehash_new_ex(__func__, (unsigned int)totedge_i);
2989 /* build edge hash */
2991 for (i = 0; i < totedge_i; i++, me++) {
2992 BLI_edgehash_insert(eh, me->v1, me->v2, SET_UINT_IN_POINTER(i));
2994 /* unrelated but avoid having the FGON flag enabled, so we can reuse it later for something else */
2995 me->flag &= ~ME_FGON;
2998 polyindex = CustomData_get_layer(fdata, CD_ORIGINDEX);
3000 j = 0; /* current loop index */
3004 for (i = 0; i < totface_i; i++, mf++, mp++) {
3007 mp->totloop = mf->v4 ? 4 : 3;
3009 mp->mat_nr = mf->mat_nr;
3010 mp->flag = mf->flag;
3012 # define ML(v1, v2) { \
3014 ml->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(eh, mf->v1, mf->v2)); \
3030 bm_corners_to_loops_ex(id, fdata, ldata, pdata, mface, totloop, i, mp->loopstart, numTex, numCol);