b144ae2dedbed7138753c2d6a2f9da666a2a6110
[blender.git] / source / blender / draw / intern / draw_cache_impl_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  * The Original Code is Copyright (C) 2017 by Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, Mike Erwin, Dalai Felinto
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file draw_cache_impl_mesh.c
27  *  \ingroup draw
28  *
29  * \brief Mesh API for render engines
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "BLI_buffer.h"
35 #include "BLI_utildefines.h"
36 #include "BLI_math_vector.h"
37 #include "BLI_math_bits.h"
38 #include "BLI_math_color.h"
39 #include "BLI_string.h"
40 #include "BLI_alloca.h"
41 #include "BLI_edgehash.h"
42
43 #include "DNA_mesh_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_space_types.h"
47 #include "DNA_scene_types.h"
48
49 #include "BKE_customdata.h"
50 #include "BKE_deform.h"
51 #include "BKE_editmesh.h"
52 #include "BKE_editmesh_cache.h"
53 #include "BKE_editmesh_tangent.h"
54 #include "BKE_mesh.h"
55 #include "BKE_mesh_tangent.h"
56 #include "BKE_mesh_runtime.h"
57 #include "BKE_object.h"
58 #include "BKE_object_deform.h"
59 #include "BKE_colorband.h"
60 #include "BKE_cdderivedmesh.h"
61
62 #include "DEG_depsgraph_query.h"
63
64 #include "bmesh.h"
65
66 #include "GPU_batch.h"
67 #include "GPU_batch_presets.h"
68 #include "GPU_draw.h"
69 #include "GPU_material.h"
70
71 #include "DRW_render.h"
72
73 #include "ED_image.h"
74 #include "ED_mesh.h"
75 #include "ED_uvedit.h"
76
77 #include "draw_cache_impl.h"  /* own include */
78
79
80 static void mesh_batch_cache_clear(Mesh *me);
81
82 /* Vertex Group Selection and display options */
83 typedef struct DRW_MeshWeightState {
84         int defgroup_active;
85         int defgroup_len;
86
87         short flags;
88         char alert_mode;
89
90         /* Set of all selected bones for Multipaint. */
91         bool *defgroup_sel; /* [defgroup_len] */
92         int   defgroup_sel_count;
93 } DRW_MeshWeightState;
94
95 /* DRW_MeshWeightState.flags */
96 enum {
97         DRW_MESH_WEIGHT_STATE_MULTIPAINT          = (1 << 0),
98         DRW_MESH_WEIGHT_STATE_AUTO_NORMALIZE      = (1 << 1),
99 };
100
101 /* ---------------------------------------------------------------------- */
102
103 /** \name Mesh/BMesh Interface (direct access to basic data).
104  * \{ */
105
106 static int mesh_render_verts_len_get(Mesh *me)
107 {
108         return me->edit_btmesh ? me->edit_btmesh->bm->totvert : me->totvert;
109 }
110
111 static int mesh_render_edges_len_get(Mesh *me)
112 {
113         return me->edit_btmesh ? me->edit_btmesh->bm->totedge : me->totedge;
114 }
115
116 static int mesh_render_looptri_len_get(Mesh *me)
117 {
118         return me->edit_btmesh ? me->edit_btmesh->tottri : poly_to_tri_count(me->totpoly, me->totloop);
119 }
120
121 static int mesh_render_polys_len_get(Mesh *me)
122 {
123         return me->edit_btmesh ? me->edit_btmesh->bm->totface : me->totpoly;
124 }
125
126 static int mesh_render_mat_len_get(Mesh *me)
127 {
128         return MAX2(1, me->totcol);
129 }
130
131 static int UNUSED_FUNCTION(mesh_render_loops_len_get)(Mesh *me)
132 {
133         return me->edit_btmesh ? me->edit_btmesh->bm->totloop : me->totloop;
134 }
135
136 /** \} */
137
138
139 /* ---------------------------------------------------------------------- */
140
141 /** \name Mesh/BMesh Interface (indirect, partially cached access to complex data).
142  * \{ */
143
144 typedef struct EdgeAdjacentPolys {
145         int count;
146         int face_index[2];
147 } EdgeAdjacentPolys;
148
149 typedef struct EdgeAdjacentVerts {
150         int vert_index[2]; /* -1 if none */
151 } EdgeAdjacentVerts;
152
153 typedef struct EdgeDrawAttr {
154         uchar v_flag;
155         uchar e_flag;
156         uchar crease;
157         uchar bweight;
158 } EdgeDrawAttr;
159
160 typedef struct MeshRenderData {
161         int types;
162
163         int vert_len;
164         int edge_len;
165         int tri_len;
166         int loop_len;
167         int poly_len;
168         int mat_len;
169         int loose_vert_len;
170         int loose_edge_len;
171
172         /* Support for mapped mesh data. */
173         struct {
174                 /* Must be set if we want to get mapped data. */
175                 bool use;
176                 bool supported;
177
178                 Mesh *me_cage;
179
180                 int vert_len;
181                 int edge_len;
182                 int tri_len;
183                 int loop_len;
184                 int poly_len;
185
186                 int *loose_verts;
187                 int  loose_vert_len;
188
189                 int *loose_edges;
190                 int  loose_edge_len;
191
192                 /* origindex layers */
193                 int *v_origindex;
194                 int *e_origindex;
195                 int *l_origindex;
196                 int *p_origindex;
197         } mapped;
198
199         BMEditMesh *edit_bmesh;
200         struct EditMeshData *edit_data;
201
202         Mesh *me;
203
204         MVert *mvert;
205         const MEdge *medge;
206         const MLoop *mloop;
207         const MPoly *mpoly;
208         float (*orco)[3];  /* vertex coordinates normalized to bounding box */
209         bool is_orco_allocated;
210         MDeformVert *dvert;
211         MLoopUV *mloopuv;
212         MLoopCol *mloopcol;
213         float (*loop_normals)[3];
214
215         /* CustomData 'cd' cache for efficient access. */
216         struct {
217                 struct {
218                         MLoopUV **uv;
219                         int       uv_len;
220                         int       uv_active;
221
222                         MLoopCol **vcol;
223                         int        vcol_len;
224                         int        vcol_active;
225
226                         float (**tangent)[4];
227                         int      tangent_len;
228                         int      tangent_active;
229
230                         bool *auto_vcol;
231                 } layers;
232
233                 /* Custom-data offsets (only needed for BMesh access) */
234                 struct {
235                         int crease;
236                         int bweight;
237                         int *uv;
238                         int *vcol;
239 #ifdef WITH_FREESTYLE
240                         int freestyle_edge;
241                         int freestyle_face;
242 #endif
243                 } offset;
244
245                 struct {
246                         char (*auto_mix)[32];
247                         char (*uv)[32];
248                         char (*vcol)[32];
249                         char (*tangent)[32];
250                 } uuid;
251
252                 /* for certain cases we need an output loop-data storage (bmesh tangents) */
253                 struct {
254                         CustomData ldata;
255                         /* grr, special case variable (use in place of 'dm->tangent_mask') */
256                         short tangent_mask;
257                 } output;
258         } cd;
259
260         BMVert *eve_act;
261         BMEdge *eed_act;
262         BMFace *efa_act;
263
264         /* Data created on-demand (usually not for bmesh-based data). */
265         EdgeAdjacentPolys *edges_adjacent_polys;
266         MLoopTri *mlooptri;
267         int *loose_edges;
268         int *loose_verts;
269
270         float (*poly_normals)[3];
271         float (*vert_weight);
272         char (*vert_color)[3];
273         GPUPackedNormal *poly_normals_pack;
274         GPUPackedNormal *vert_normals_pack;
275         bool *edge_select_bool;
276         bool *edge_visible_bool;
277 } MeshRenderData;
278
279 enum {
280         MR_DATATYPE_VERT       = 1 << 0,
281         MR_DATATYPE_EDGE       = 1 << 1,
282         MR_DATATYPE_LOOPTRI    = 1 << 2,
283         MR_DATATYPE_LOOP       = 1 << 3,
284         MR_DATATYPE_POLY       = 1 << 4,
285         MR_DATATYPE_OVERLAY    = 1 << 5,
286         MR_DATATYPE_SHADING    = 1 << 6,
287         MR_DATATYPE_DVERT      = 1 << 7,
288         MR_DATATYPE_LOOPCOL    = 1 << 8,
289         MR_DATATYPE_LOOPUV     = 1 << 9,
290         MR_DATATYPE_LOOSE_VERT = 1 << 10,
291         MR_DATATYPE_LOOSE_EDGE = 1 << 11,
292 };
293
294 /**
295  * These functions look like they would be slow but they will typically return true on the first iteration.
296  * Only false when all attached elements are hidden.
297  */
298 static bool bm_vert_has_visible_edge(const BMVert *v)
299 {
300         const BMEdge *e_iter, *e_first;
301
302         e_iter = e_first = v->e;
303         do {
304                 if (!BM_elem_flag_test(e_iter, BM_ELEM_HIDDEN)) {
305                         return true;
306                 }
307         } while ((e_iter = BM_DISK_EDGE_NEXT(e_iter, v)) != e_first);
308         return false;
309 }
310
311 static bool bm_edge_has_visible_face(const BMEdge *e)
312 {
313         const BMLoop *l_iter, *l_first;
314         l_iter = l_first = e->l;
315         do {
316                 if (!BM_elem_flag_test(l_iter->f, BM_ELEM_HIDDEN)) {
317                         return true;
318                 }
319         } while ((l_iter = l_iter->radial_next) != l_first);
320         return false;
321 }
322
323 /* Return true is all layers in _b_ are inside _a_. */
324 static bool mesh_cd_layers_type_overlap(
325         const uchar av[CD_NUMTYPES], const ushort al[CD_NUMTYPES],
326         const uchar bv[CD_NUMTYPES], const ushort bl[CD_NUMTYPES])
327 {
328         for (int i = 0; i < CD_NUMTYPES; ++i) {
329                 if ((av[i] & bv[i]) != bv[i]) {
330                         return false;
331                 }
332                 if ((al[i] & bl[i]) != bl[i]) {
333                         return false;
334                 }
335         }
336         return true;
337 }
338
339 static void mesh_cd_layers_type_merge(
340         uchar av[CD_NUMTYPES], ushort al[CD_NUMTYPES],
341         uchar bv[CD_NUMTYPES], ushort bl[CD_NUMTYPES])
342 {
343         for (int i = 0; i < CD_NUMTYPES; ++i) {
344                 av[i] |= bv[i];
345                 al[i] |= bl[i];
346         }
347 }
348
349 static void mesh_cd_calc_active_uv_layer(
350         const Mesh *me, ushort cd_lused[CD_NUMTYPES])
351 {
352         const CustomData *cd_ldata = (me->edit_btmesh) ? &me->edit_btmesh->bm->ldata : &me->ldata;
353
354         int layer = CustomData_get_active_layer(cd_ldata, CD_MLOOPUV);
355         if (layer != -1) {
356                 cd_lused[CD_MLOOPUV] |= (1 << layer);
357         }
358 }
359
360 static void mesh_cd_calc_used_gpu_layers(
361         const Mesh *me, uchar cd_vused[CD_NUMTYPES], ushort cd_lused[CD_NUMTYPES],
362         struct GPUMaterial **gpumat_array, int gpumat_array_len)
363 {
364         const CustomData *cd_ldata = (me->edit_btmesh) ? &me->edit_btmesh->bm->ldata : &me->ldata;
365
366         /* See: DM_vertex_attributes_from_gpu for similar logic */
367         GPUVertexAttribs gattribs = {{{0}}};
368
369         for (int i = 0; i < gpumat_array_len; i++) {
370                 GPUMaterial *gpumat = gpumat_array[i];
371                 if (gpumat) {
372                         GPU_material_vertex_attributes(gpumat, &gattribs);
373                         for (int j = 0; j < gattribs.totlayer; j++) {
374                                 const char *name = gattribs.layer[j].name;
375                                 int type = gattribs.layer[j].type;
376                                 int layer = -1;
377
378                                 if (type == CD_AUTO_FROM_NAME) {
379                                         /* We need to deduct what exact layer is used.
380                                          *
381                                          * We do it based on the specified name.
382                                          */
383                                         if (name[0] != '\0') {
384                                                 layer = CustomData_get_named_layer(cd_ldata, CD_MLOOPUV, name);
385                                                 type = CD_MTFACE;
386
387                                                 if (layer == -1) {
388                                                         layer = CustomData_get_named_layer(cd_ldata, CD_MLOOPCOL, name);
389                                                         type = CD_MCOL;
390                                                 }
391 #if 0                                   /* Tangents are always from UV's - this will never happen. */
392                                                 if (layer == -1) {
393                                                         layer = CustomData_get_named_layer(cd_ldata, CD_TANGENT, name);
394                                                         type = CD_TANGENT;
395                                                 }
396 #endif
397                                                 if (layer == -1) {
398                                                         continue;
399                                                 }
400                                         }
401                                         else {
402                                                 /* Fall back to the UV layer, which matches old behavior. */
403                                                 type = CD_MTFACE;
404                                         }
405                                 }
406
407                                 switch (type) {
408                                         case CD_MTFACE:
409                                         {
410                                                 if (layer == -1) {
411                                                         layer = (name[0] != '\0') ?
412                                                                 CustomData_get_named_layer(cd_ldata, CD_MLOOPUV, name) :
413                                                                 CustomData_get_active_layer(cd_ldata, CD_MLOOPUV);
414                                                 }
415                                                 if (layer != -1) {
416                                                         cd_lused[CD_MLOOPUV] |= (1 << layer);
417                                                 }
418                                                 break;
419                                         }
420                                         case CD_TANGENT:
421                                         {
422                                                 if (layer == -1) {
423                                                         layer = (name[0] != '\0') ?
424                                                                 CustomData_get_named_layer(cd_ldata, CD_MLOOPUV, name) :
425                                                                 CustomData_get_active_layer(cd_ldata, CD_MLOOPUV);
426                                                 }
427                                                 if (layer != -1) {
428                                                         cd_lused[CD_TANGENT] |= (1 << layer);
429                                                 }
430                                                 else {
431                                                         /* no UV layers at all => requesting orco */
432                                                         cd_lused[CD_TANGENT] |= DM_TANGENT_MASK_ORCO;
433                                                         cd_vused[CD_ORCO] |= 1;
434                                                 }
435                                                 break;
436                                         }
437                                         case CD_MCOL:
438                                         {
439                                                 if (layer == -1) {
440                                                         layer = (name[0] != '\0') ?
441                                                                 CustomData_get_named_layer(cd_ldata, CD_MLOOPCOL, name) :
442                                                                 CustomData_get_active_layer(cd_ldata, CD_MLOOPCOL);
443                                                 }
444                                                 if (layer != -1) {
445                                                         cd_lused[CD_MLOOPCOL] |= (1 << layer);
446                                                 }
447                                                 break;
448                                         }
449                                         case CD_ORCO:
450                                         {
451                                                 cd_vused[CD_ORCO] |= 1;
452                                                 break;
453                                         }
454                                 }
455                         }
456                 }
457         }
458 }
459
460
461 static void mesh_render_calc_normals_loop_and_poly(const Mesh *me, const float split_angle, MeshRenderData *rdata)
462 {
463         BLI_assert((me->flag & ME_AUTOSMOOTH) != 0);
464
465         int totloop = me->totloop;
466         int totpoly = me->totpoly;
467         float (*loop_normals)[3] = MEM_mallocN(sizeof(*loop_normals) * totloop, __func__);
468         float (*poly_normals)[3] = MEM_mallocN(sizeof(*poly_normals) * totpoly, __func__);
469         short (*clnors)[2] = CustomData_get_layer(&me->ldata, CD_CUSTOMLOOPNORMAL);
470
471         BKE_mesh_calc_normals_poly(
472                 me->mvert, NULL, me->totvert,
473                 me->mloop, me->mpoly, totloop, totpoly, poly_normals, false);
474
475         BKE_mesh_normals_loop_split(
476                 me->mvert, me->totvert, me->medge, me->totedge,
477                 me->mloop, loop_normals, totloop, me->mpoly, poly_normals, totpoly,
478                 true, split_angle, NULL, clnors, NULL);
479
480         rdata->loop_len = totloop;
481         rdata->poly_len = totpoly;
482         rdata->loop_normals = loop_normals;
483         rdata->poly_normals = poly_normals;
484 }
485
486 static void mesh_cd_extract_auto_layers_names_and_srgb(
487         Mesh *me, const ushort cd_lused[CD_NUMTYPES],
488         char **r_auto_layers_names, int **r_auto_layers_srgb, int *r_auto_layers_len)
489 {
490         const CustomData *cd_ldata = (me->edit_btmesh) ? &me->edit_btmesh->bm->ldata : &me->ldata;
491
492         int uv_len_used = count_bits_i(cd_lused[CD_MLOOPUV]);
493         int vcol_len_used = count_bits_i(cd_lused[CD_MLOOPCOL]);
494         int uv_len = CustomData_number_of_layers(cd_ldata, CD_MLOOPUV);
495         int vcol_len = CustomData_number_of_layers(cd_ldata, CD_MLOOPCOL);
496
497         uint auto_names_len = 32 * (uv_len_used + vcol_len_used);
498         uint auto_ofs = 0;
499         /* Allocate max, resize later. */
500         char *auto_names = MEM_callocN(sizeof(char) * auto_names_len, __func__);
501         int *auto_is_srgb = MEM_callocN(sizeof(int) * (uv_len_used + vcol_len_used), __func__);
502
503         for (int i = 0; i < uv_len; i++) {
504                 if ((cd_lused[CD_MLOOPUV] & (1 << i)) != 0) {
505                         const char *name = CustomData_get_layer_name(cd_ldata, CD_MLOOPUV, i);
506                         uint hash = BLI_ghashutil_strhash_p(name);
507                         /* +1 to include '\0' terminator. */
508                         auto_ofs += 1 + BLI_snprintf_rlen(auto_names + auto_ofs, auto_names_len - auto_ofs, "ba%u", hash);
509                 }
510         }
511
512         uint auto_is_srgb_ofs = uv_len_used;
513         for (int i = 0; i < vcol_len; i++) {
514                 if ((cd_lused[CD_MLOOPCOL] & (1 << i)) != 0) {
515                         const char *name = CustomData_get_layer_name(cd_ldata, CD_MLOOPCOL, i);
516                         /* We only do vcols that are not overridden by a uv layer with same name. */
517                         if (CustomData_get_named_layer_index(cd_ldata, CD_MLOOPUV, name) == -1) {
518                                 uint hash = BLI_ghashutil_strhash_p(name);
519                                 /* +1 to include '\0' terminator. */
520                                 auto_ofs += 1 + BLI_snprintf_rlen(auto_names + auto_ofs, auto_names_len - auto_ofs, "ba%u", hash);
521                                 auto_is_srgb[auto_is_srgb_ofs] = true;
522                                 auto_is_srgb_ofs++;
523                         }
524                 }
525         }
526
527         auto_names = MEM_reallocN(auto_names, sizeof(char) * auto_ofs);
528         auto_is_srgb = MEM_reallocN(auto_is_srgb, sizeof(int) * auto_is_srgb_ofs);
529
530         *r_auto_layers_names = auto_names;
531         *r_auto_layers_srgb = auto_is_srgb;
532         *r_auto_layers_len = auto_is_srgb_ofs;
533 }
534
535 /**
536  * TODO(campbell): 'gpumat_array' may include materials linked to the object.
537  * While not default, object materials should be supported.
538  * Although this only impacts the data that's generated, not the materials that display.
539  */
540 static MeshRenderData *mesh_render_data_create_ex(
541         Mesh *me, const int types, const uchar cd_vused[CD_NUMTYPES], const ushort cd_lused[CD_NUMTYPES])
542 {
543         MeshRenderData *rdata = MEM_callocN(sizeof(*rdata), __func__);
544         rdata->types = types;
545         rdata->mat_len = mesh_render_mat_len_get(me);
546
547         CustomData_reset(&rdata->cd.output.ldata);
548
549         const bool is_auto_smooth = (me->flag & ME_AUTOSMOOTH) != 0;
550         const float split_angle = is_auto_smooth ? me->smoothresh : (float)M_PI;
551
552         if (me->edit_btmesh) {
553                 BMEditMesh *embm = me->edit_btmesh;
554                 BMesh *bm = embm->bm;
555
556                 rdata->edit_bmesh = embm;
557                 rdata->edit_data = me->runtime.edit_data;
558
559                 if (embm->mesh_eval_cage && (embm->mesh_eval_cage->runtime.is_original == false)) {
560                         Mesh *me_cage = embm->mesh_eval_cage;
561
562                         rdata->mapped.me_cage = me_cage;
563                         if (types & MR_DATATYPE_VERT) {
564                                 rdata->mapped.vert_len = me_cage->totvert;
565                         }
566                         if (types & MR_DATATYPE_EDGE) {
567                                 rdata->mapped.edge_len = me_cage->totedge;
568                         }
569                         if (types & MR_DATATYPE_LOOP) {
570                                 rdata->mapped.loop_len = me_cage->totloop;
571                         }
572                         if (types & MR_DATATYPE_POLY) {
573                                 rdata->mapped.poly_len = me_cage->totpoly;
574                         }
575                         if (types & MR_DATATYPE_LOOPTRI) {
576                                 rdata->mapped.tri_len = poly_to_tri_count(me_cage->totpoly, me_cage->totloop);
577                         }
578
579                         rdata->mapped.v_origindex = CustomData_get_layer(&me_cage->vdata, CD_ORIGINDEX);
580                         rdata->mapped.e_origindex = CustomData_get_layer(&me_cage->edata, CD_ORIGINDEX);
581                         rdata->mapped.l_origindex = CustomData_get_layer(&me_cage->ldata, CD_ORIGINDEX);
582                         rdata->mapped.p_origindex = CustomData_get_layer(&me_cage->pdata, CD_ORIGINDEX);
583                         rdata->mapped.supported = (
584                                 rdata->mapped.v_origindex &&
585                                 rdata->mapped.e_origindex &&
586                                 rdata->mapped.p_origindex);
587                 }
588
589                 int bm_ensure_types = 0;
590                 if (types & MR_DATATYPE_VERT) {
591                         rdata->vert_len = bm->totvert;
592                         bm_ensure_types |= BM_VERT;
593                 }
594                 if (types & MR_DATATYPE_EDGE) {
595                         rdata->edge_len = bm->totedge;
596                         bm_ensure_types |= BM_EDGE;
597                 }
598                 if (types & MR_DATATYPE_LOOPTRI) {
599                         bm_ensure_types |= BM_LOOP;
600                 }
601                 if (types & MR_DATATYPE_LOOP) {
602                         int totloop = bm->totloop;
603                         if (is_auto_smooth) {
604                                 rdata->loop_normals = MEM_mallocN(sizeof(*rdata->loop_normals) * totloop, __func__);
605                                 int cd_loop_clnors_offset = CustomData_get_offset(&bm->ldata, CD_CUSTOMLOOPNORMAL);
606                                 BM_loops_calc_normal_vcos(
607                                         bm, NULL, NULL, NULL, true, split_angle, rdata->loop_normals, NULL, NULL,
608                                         cd_loop_clnors_offset, false);
609                         }
610                         rdata->loop_len = totloop;
611                         bm_ensure_types |= BM_LOOP;
612                 }
613                 if (types & MR_DATATYPE_POLY) {
614                         rdata->poly_len = bm->totface;
615                         bm_ensure_types |= BM_FACE;
616                 }
617                 if (types & MR_DATATYPE_OVERLAY) {
618                         rdata->efa_act = BM_mesh_active_face_get(bm, false, true);
619                         rdata->eed_act = BM_mesh_active_edge_get(bm);
620                         rdata->eve_act = BM_mesh_active_vert_get(bm);
621                         rdata->cd.offset.crease = CustomData_get_offset(&bm->edata, CD_CREASE);
622                         rdata->cd.offset.bweight = CustomData_get_offset(&bm->edata, CD_BWEIGHT);
623
624 #ifdef WITH_FREESTYLE
625                         rdata->cd.offset.freestyle_edge = CustomData_get_offset(&bm->edata, CD_FREESTYLE_EDGE);
626                         rdata->cd.offset.freestyle_face = CustomData_get_offset(&bm->pdata, CD_FREESTYLE_FACE);
627 #endif
628                 }
629                 if (types & (MR_DATATYPE_DVERT)) {
630                         bm_ensure_types |= BM_VERT;
631                 }
632                 if (rdata->edit_data != NULL) {
633                         bm_ensure_types |= BM_VERT;
634                 }
635
636                 BM_mesh_elem_index_ensure(bm, bm_ensure_types);
637                 BM_mesh_elem_table_ensure(bm, bm_ensure_types & ~BM_LOOP);
638
639                 if (types & MR_DATATYPE_LOOPTRI) {
640                         /* Edit mode ensures this is valid, no need to calculate. */
641                         BLI_assert((bm->totloop == 0) || (embm->looptris != NULL));
642                         int tottri = embm->tottri;
643                         MLoopTri *mlooptri = MEM_mallocN(sizeof(*rdata->mlooptri) * embm->tottri, __func__);
644                         for (int index = 0; index < tottri ; index ++ ) {
645                                 BMLoop **bmtri = embm->looptris[index];
646                                 MLoopTri *mtri = &mlooptri[index];
647                                 mtri->tri[0] = BM_elem_index_get(bmtri[0]);
648                                 mtri->tri[1] = BM_elem_index_get(bmtri[1]);
649                                 mtri->tri[2] = BM_elem_index_get(bmtri[2]);
650                         }
651                         rdata->mlooptri = mlooptri;
652                         rdata->tri_len = tottri;
653                 }
654
655                 if (types & MR_DATATYPE_LOOSE_VERT) {
656                         BLI_assert(types & MR_DATATYPE_VERT);
657                         rdata->loose_vert_len = 0;
658
659                         {
660                                 int *lverts = MEM_mallocN(rdata->vert_len * sizeof(int), __func__);
661                                 BLI_assert((bm->elem_table_dirty & BM_VERT) == 0);
662                                 for (int i = 0; i < bm->totvert; i++) {
663                                         const BMVert *eve = BM_vert_at_index(bm, i);
664                                         if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
665                                                 /* Loose vert */
666                                                 if (eve->e == NULL || !bm_vert_has_visible_edge(eve)) {
667                                                         lverts[rdata->loose_vert_len++] = i;
668                                                 }
669                                         }
670                                 }
671                                 rdata->loose_verts = MEM_reallocN(lverts, rdata->loose_vert_len * sizeof(int));
672                         }
673
674                         if (rdata->mapped.supported) {
675                                 Mesh *me_cage = embm->mesh_eval_cage;
676                                 rdata->mapped.loose_vert_len = 0;
677
678                                 if (rdata->loose_vert_len) {
679                                         int *lverts = MEM_mallocN(me_cage->totvert * sizeof(int), __func__);
680                                         const int *v_origindex = rdata->mapped.v_origindex;
681                                         for (int i = 0; i < me_cage->totvert; i++) {
682                                                 const int v_orig = v_origindex[i];
683                                                 if (v_orig != ORIGINDEX_NONE) {
684                                                         BMVert *eve = BM_vert_at_index(bm, v_orig);
685                                                         if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
686                                                                 /* Loose vert */
687                                                                 if (eve->e == NULL || !bm_vert_has_visible_edge(eve)) {
688                                                                         lverts[rdata->mapped.loose_vert_len++] = i;
689                                                                 }
690                                                         }
691                                                 }
692                                         }
693                                         rdata->mapped.loose_verts = MEM_reallocN(lverts, rdata->mapped.loose_vert_len * sizeof(int));
694                                 }
695                         }
696                 }
697
698                 if (types & MR_DATATYPE_LOOSE_EDGE) {
699                         BLI_assert(types & MR_DATATYPE_EDGE);
700                         rdata->loose_edge_len = 0;
701
702                         {
703                                 int *ledges = MEM_mallocN(rdata->edge_len * sizeof(int), __func__);
704                                 BLI_assert((bm->elem_table_dirty & BM_EDGE) == 0);
705                                 for (int i = 0; i < bm->totedge; i++) {
706                                         const BMEdge *eed = BM_edge_at_index(bm, i);
707                                         if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
708                                                 /* Loose edge */
709                                                 if (eed->l == NULL || !bm_edge_has_visible_face(eed)) {
710                                                         ledges[rdata->loose_edge_len++] = i;
711                                                 }
712                                         }
713                                 }
714                                 rdata->loose_edges = MEM_reallocN(ledges, rdata->loose_edge_len * sizeof(int));
715                         }
716
717                         if (rdata->mapped.supported) {
718                                 Mesh *me_cage = embm->mesh_eval_cage;
719                                 rdata->mapped.loose_edge_len = 0;
720
721                                 if (rdata->loose_edge_len) {
722                                         int *ledges = MEM_mallocN(me_cage->totedge * sizeof(int), __func__);
723                                         const int *e_origindex = rdata->mapped.e_origindex;
724                                         for (int i = 0; i < me_cage->totedge; i++) {
725                                                 const int e_orig = e_origindex[i];
726                                                 if (e_orig != ORIGINDEX_NONE) {
727                                                         BMEdge *eed = BM_edge_at_index(bm, e_orig);
728                                                         if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
729                                                                 /* Loose edge */
730                                                                 if (eed->l == NULL || !bm_edge_has_visible_face(eed)) {
731                                                                         ledges[rdata->mapped.loose_edge_len++] = i;
732                                                                 }
733                                                         }
734                                                 }
735                                         }
736                                         rdata->mapped.loose_edges = MEM_reallocN(ledges, rdata->mapped.loose_edge_len * sizeof(int));
737                                 }
738                         }
739                 }
740         }
741         else {
742                 rdata->me = me;
743
744                 if (types & (MR_DATATYPE_VERT)) {
745                         rdata->vert_len = me->totvert;
746                         rdata->mvert = CustomData_get_layer(&me->vdata, CD_MVERT);
747                 }
748                 if (types & (MR_DATATYPE_EDGE)) {
749                         rdata->edge_len = me->totedge;
750                         rdata->medge = CustomData_get_layer(&me->edata, CD_MEDGE);
751                 }
752                 if (types & MR_DATATYPE_LOOPTRI) {
753                         const int tri_len = rdata->tri_len = poly_to_tri_count(me->totpoly, me->totloop);
754                         MLoopTri *mlooptri = MEM_mallocN(sizeof(*mlooptri) * tri_len, __func__);
755                         BKE_mesh_recalc_looptri(me->mloop, me->mpoly, me->mvert, me->totloop, me->totpoly, mlooptri);
756                         rdata->mlooptri = mlooptri;
757                 }
758                 if (types & MR_DATATYPE_LOOP) {
759                         rdata->loop_len = me->totloop;
760                         rdata->mloop = CustomData_get_layer(&me->ldata, CD_MLOOP);
761
762                         if (is_auto_smooth) {
763                                 mesh_render_calc_normals_loop_and_poly(me, split_angle, rdata);
764                         }
765                 }
766                 if (types & MR_DATATYPE_POLY) {
767                         rdata->poly_len = me->totpoly;
768                         rdata->mpoly = CustomData_get_layer(&me->pdata, CD_MPOLY);
769                 }
770                 if (types & MR_DATATYPE_DVERT) {
771                         rdata->vert_len = me->totvert;
772                         rdata->dvert = CustomData_get_layer(&me->vdata, CD_MDEFORMVERT);
773                 }
774                 if (types & MR_DATATYPE_LOOPCOL) {
775                         rdata->loop_len = me->totloop;
776                         rdata->mloopcol = CustomData_get_layer(&me->ldata, CD_MLOOPCOL);
777                 }
778                 if (types & MR_DATATYPE_LOOPUV) {
779                         rdata->loop_len = me->totloop;
780                         rdata->mloopuv = CustomData_get_layer(&me->ldata, CD_MLOOPUV);
781                 }
782         }
783
784         if (types & MR_DATATYPE_SHADING) {
785                 CustomData *cd_vdata, *cd_ldata;
786
787                 BLI_assert(cd_vused != NULL && cd_lused != NULL);
788
789                 if (me->edit_btmesh) {
790                         BMesh *bm = me->edit_btmesh->bm;
791                         cd_vdata = &bm->vdata;
792                         cd_ldata = &bm->ldata;
793                 }
794                 else {
795                         cd_vdata = &me->vdata;
796                         cd_ldata = &me->ldata;
797                 }
798
799                 rdata->cd.layers.uv_active = CustomData_get_active_layer(cd_ldata, CD_MLOOPUV);
800                 rdata->cd.layers.vcol_active = CustomData_get_active_layer(cd_ldata, CD_MLOOPCOL);
801                 rdata->cd.layers.tangent_active = rdata->cd.layers.uv_active;
802
803 #define CD_VALIDATE_ACTIVE_LAYER(active_index, used) \
804                 if ((active_index != -1) && (used & (1 << active_index)) == 0) { \
805                         active_index = -1; \
806                 } ((void)0)
807
808                 CD_VALIDATE_ACTIVE_LAYER(rdata->cd.layers.uv_active, cd_lused[CD_MLOOPUV]);
809                 CD_VALIDATE_ACTIVE_LAYER(rdata->cd.layers.tangent_active, cd_lused[CD_TANGENT]);
810                 CD_VALIDATE_ACTIVE_LAYER(rdata->cd.layers.vcol_active, cd_lused[CD_MLOOPCOL]);
811
812 #undef CD_VALIDATE_ACTIVE_LAYER
813
814                 rdata->is_orco_allocated = false;
815                 if (cd_vused[CD_ORCO] & 1) {
816                         rdata->orco = CustomData_get_layer(cd_vdata, CD_ORCO);
817                         /* If orco is not available compute it ourselves */
818                         if (!rdata->orco) {
819                                 rdata->is_orco_allocated = true;
820                                 if (me->edit_btmesh) {
821                                         BMesh *bm = me->edit_btmesh->bm;
822                                         rdata->orco = MEM_mallocN(sizeof(*rdata->orco) * rdata->vert_len, "orco mesh");
823                                         BLI_assert((bm->elem_table_dirty & BM_VERT) == 0);
824                                         for (int i = 0; i < bm->totvert; i++) {
825                                                 copy_v3_v3(rdata->orco[i], BM_vert_at_index(bm, i)->co);
826                                         }
827                                         BKE_mesh_orco_verts_transform(me, rdata->orco, rdata->vert_len, 0);
828                                 }
829                                 else {
830                                         rdata->orco = MEM_mallocN(sizeof(*rdata->orco) * rdata->vert_len, "orco mesh");
831                                         MVert *mvert = rdata->mvert;
832                                         for (int a = 0; a < rdata->vert_len; a++, mvert++) {
833                                                 copy_v3_v3(rdata->orco[a], mvert->co);
834                                         }
835                                         BKE_mesh_orco_verts_transform(me, rdata->orco, rdata->vert_len, 0);
836                                 }
837                         }
838                 }
839                 else {
840                         rdata->orco = NULL;
841                 }
842
843                 /* don't access mesh directly, instead use vars taken from BMesh or Mesh */
844 #define me DONT_USE_THIS
845 #ifdef  me /* quiet warning */
846 #endif
847                 struct {
848                         uint uv_len;
849                         uint vcol_len;
850                 } cd_layers_src = {
851                         .uv_len = CustomData_number_of_layers(cd_ldata, CD_MLOOPUV),
852                         .vcol_len = CustomData_number_of_layers(cd_ldata, CD_MLOOPCOL),
853                 };
854
855                 rdata->cd.layers.uv_len = count_bits_i(cd_lused[CD_MLOOPUV]);
856                 rdata->cd.layers.tangent_len = count_bits_i(cd_lused[CD_TANGENT]);
857                 rdata->cd.layers.vcol_len = count_bits_i(cd_lused[CD_MLOOPCOL]);
858
859                 rdata->cd.layers.uv = MEM_mallocN(sizeof(*rdata->cd.layers.uv) * rdata->cd.layers.uv_len, __func__);
860                 rdata->cd.layers.vcol = MEM_mallocN(sizeof(*rdata->cd.layers.vcol) * rdata->cd.layers.vcol_len, __func__);
861                 rdata->cd.layers.tangent = MEM_mallocN(sizeof(*rdata->cd.layers.tangent) * rdata->cd.layers.tangent_len, __func__);
862
863                 rdata->cd.uuid.uv = MEM_mallocN(sizeof(*rdata->cd.uuid.uv) * rdata->cd.layers.uv_len, __func__);
864                 rdata->cd.uuid.vcol = MEM_mallocN(sizeof(*rdata->cd.uuid.vcol) * rdata->cd.layers.vcol_len, __func__);
865                 rdata->cd.uuid.tangent = MEM_mallocN(sizeof(*rdata->cd.uuid.tangent) * rdata->cd.layers.tangent_len, __func__);
866
867                 rdata->cd.offset.uv = MEM_mallocN(sizeof(*rdata->cd.offset.uv) * rdata->cd.layers.uv_len, __func__);
868                 rdata->cd.offset.vcol = MEM_mallocN(sizeof(*rdata->cd.offset.vcol) * rdata->cd.layers.vcol_len, __func__);
869
870                 /* Allocate max */
871                 rdata->cd.layers.auto_vcol = MEM_callocN(
872                         sizeof(*rdata->cd.layers.auto_vcol) * rdata->cd.layers.vcol_len, __func__);
873                 rdata->cd.uuid.auto_mix = MEM_mallocN(
874                         sizeof(*rdata->cd.uuid.auto_mix) * (rdata->cd.layers.vcol_len + rdata->cd.layers.uv_len), __func__);
875
876                 /* XXX FIXME XXX */
877                 /* We use a hash to identify each data layer based on its name.
878                  * Gawain then search for this name in the current shader and bind if it exists.
879                  * NOTE : This is prone to hash collision.
880                  * One solution to hash collision would be to format the cd layer name
881                  * to a safe glsl var name, but without name clash.
882                  * NOTE 2 : Replicate changes to code_generate_vertex_new() in gpu_codegen.c */
883                 if (rdata->cd.layers.vcol_len != 0) {
884                         for (int i_src = 0, i_dst = 0; i_src < cd_layers_src.vcol_len; i_src++, i_dst++) {
885                                 if ((cd_lused[CD_MLOOPCOL] & (1 << i_src)) == 0) {
886                                         i_dst--;
887                                         if (rdata->cd.layers.vcol_active >= i_src) {
888                                                 rdata->cd.layers.vcol_active--;
889                                         }
890                                 }
891                                 else {
892                                         const char *name = CustomData_get_layer_name(cd_ldata, CD_MLOOPCOL, i_src);
893                                         uint hash = BLI_ghashutil_strhash_p(name);
894                                         BLI_snprintf(rdata->cd.uuid.vcol[i_dst], sizeof(*rdata->cd.uuid.vcol), "c%u", hash);
895                                         rdata->cd.layers.vcol[i_dst] = CustomData_get_layer_n(cd_ldata, CD_MLOOPCOL, i_src);
896                                         if (rdata->edit_bmesh) {
897                                                 rdata->cd.offset.vcol[i_dst] = CustomData_get_n_offset(
898                                                         &rdata->edit_bmesh->bm->ldata, CD_MLOOPCOL, i_src);
899                                         }
900
901                                         /* Gather number of auto layers. */
902                                         /* We only do vcols that are not overridden by uvs */
903                                         if (CustomData_get_named_layer_index(cd_ldata, CD_MLOOPUV, name) == -1) {
904                                                 BLI_snprintf(
905                                                         rdata->cd.uuid.auto_mix[rdata->cd.layers.uv_len + i_dst],
906                                                         sizeof(*rdata->cd.uuid.auto_mix), "a%u", hash);
907                                                 rdata->cd.layers.auto_vcol[i_dst] = true;
908                                         }
909                                 }
910                         }
911                 }
912
913                 /* Start Fresh */
914                 CustomData_free_layers(cd_ldata, CD_TANGENT, rdata->loop_len);
915                 CustomData_free_layers(cd_ldata, CD_MLOOPTANGENT, rdata->loop_len);
916
917                 if (rdata->cd.layers.uv_len != 0) {
918                         for (int i_src = 0, i_dst = 0; i_src < cd_layers_src.uv_len; i_src++, i_dst++) {
919                                 if ((cd_lused[CD_MLOOPUV] & (1 << i_src)) == 0) {
920                                         i_dst--;
921                                         if (rdata->cd.layers.uv_active >= i_src) {
922                                                 rdata->cd.layers.uv_active--;
923                                         }
924                                 }
925                                 else {
926                                         const char *name = CustomData_get_layer_name(cd_ldata, CD_MLOOPUV, i_src);
927                                         uint hash = BLI_ghashutil_strhash_p(name);
928
929                                         BLI_snprintf(rdata->cd.uuid.uv[i_dst], sizeof(*rdata->cd.uuid.uv), "u%u", hash);
930                                         rdata->cd.layers.uv[i_dst] = CustomData_get_layer_n(cd_ldata, CD_MLOOPUV, i_src);
931                                         if (rdata->edit_bmesh) {
932                                                 rdata->cd.offset.uv[i_dst] = CustomData_get_n_offset(
933                                                         &rdata->edit_bmesh->bm->ldata, CD_MLOOPUV, i_src);
934                                         }
935                                         BLI_snprintf(rdata->cd.uuid.auto_mix[i_dst], sizeof(*rdata->cd.uuid.auto_mix), "a%u", hash);
936                                 }
937                         }
938                 }
939
940                 if (rdata->cd.layers.tangent_len != 0) {
941
942                         /* -------------------------------------------------------------------- */
943                         /* Pre-calculate tangents into 'rdata->cd.output.ldata' */
944
945                         BLI_assert(!CustomData_has_layer(&rdata->cd.output.ldata, CD_TANGENT));
946
947                         /* Tangent Names */
948                         char tangent_names[MAX_MTFACE][MAX_NAME];
949                         for (int i_src = 0, i_dst = 0; i_src < cd_layers_src.uv_len; i_src++, i_dst++) {
950                                 if ((cd_lused[CD_TANGENT] & (1 << i_src)) == 0) {
951                                         i_dst--;
952                                 }
953                                 else {
954                                         BLI_strncpy(
955                                                 tangent_names[i_dst],
956                                                 CustomData_get_layer_name(cd_ldata, CD_MLOOPUV, i_src), MAX_NAME);
957                                 }
958                         }
959
960                         /* If tangent from orco is requested, decrement tangent_len */
961                         int actual_tangent_len = (cd_lused[CD_TANGENT] & DM_TANGENT_MASK_ORCO) ?
962                                 rdata->cd.layers.tangent_len - 1 : rdata->cd.layers.tangent_len;
963                         if (rdata->edit_bmesh) {
964                                 BMEditMesh *em = rdata->edit_bmesh;
965                                 BMesh *bm = em->bm;
966
967                                 if (is_auto_smooth && rdata->loop_normals == NULL) {
968                                         /* Should we store the previous array of `loop_normals` in somewhere? */
969                                         rdata->loop_len = bm->totloop;
970                                         rdata->loop_normals = MEM_mallocN(sizeof(*rdata->loop_normals) * rdata->loop_len, __func__);
971                                         BM_loops_calc_normal_vcos(bm, NULL, NULL, NULL, true, split_angle, rdata->loop_normals, NULL, NULL, -1, false);
972                                 }
973
974                                 bool calc_active_tangent = false;
975
976                                 BKE_editmesh_loop_tangent_calc(
977                                         em, calc_active_tangent,
978                                         tangent_names, actual_tangent_len,
979                                         rdata->poly_normals, rdata->loop_normals,
980                                         rdata->orco,
981                                         &rdata->cd.output.ldata, bm->totloop,
982                                         &rdata->cd.output.tangent_mask);
983                         }
984                         else {
985 #undef me
986
987                                 if (is_auto_smooth && rdata->loop_normals == NULL) {
988                                         /* Should we store the previous array of `loop_normals` in CustomData? */
989                                         mesh_render_calc_normals_loop_and_poly(me, split_angle, rdata);
990                                 }
991
992                                 bool calc_active_tangent = false;
993
994                                 BKE_mesh_calc_loop_tangent_ex(
995                                         me->mvert,
996                                         me->mpoly, me->totpoly,
997                                         me->mloop,
998                                         rdata->mlooptri, rdata->tri_len,
999                                         cd_ldata,
1000                                         calc_active_tangent,
1001                                         tangent_names, actual_tangent_len,
1002                                         rdata->poly_normals, rdata->loop_normals,
1003                                         rdata->orco,
1004                                         &rdata->cd.output.ldata, me->totloop,
1005                                         &rdata->cd.output.tangent_mask);
1006
1007                                         /* If we store tangents in the mesh, set temporary. */
1008 #if 0
1009                                 CustomData_set_layer_flag(cd_ldata, CD_TANGENT, CD_FLAG_TEMPORARY);
1010 #endif
1011
1012 #define me DONT_USE_THIS
1013 #ifdef  me /* quiet warning */
1014 #endif
1015                         }
1016
1017                         /* End tangent calculation */
1018                         /* -------------------------------------------------------------------- */
1019
1020                         BLI_assert(CustomData_number_of_layers(&rdata->cd.output.ldata, CD_TANGENT) == rdata->cd.layers.tangent_len);
1021
1022                         int i_dst = 0;
1023                         for (int i_src = 0; i_src < cd_layers_src.uv_len; i_src++, i_dst++) {
1024                                 if ((cd_lused[CD_TANGENT] & (1 << i_src)) == 0) {
1025                                         i_dst--;
1026                                         if (rdata->cd.layers.tangent_active >= i_src) {
1027                                                 rdata->cd.layers.tangent_active--;
1028                                         }
1029                                 }
1030                                 else {
1031                                         const char *name = CustomData_get_layer_name(cd_ldata, CD_MLOOPUV, i_src);
1032                                         uint hash = BLI_ghashutil_strhash_p(name);
1033
1034                                         BLI_snprintf(rdata->cd.uuid.tangent[i_dst], sizeof(*rdata->cd.uuid.tangent), "t%u", hash);
1035
1036                                         /* Done adding tangents. */
1037
1038                                         /* note: BKE_editmesh_loop_tangent_calc calculates 'CD_TANGENT',
1039                                          * not 'CD_MLOOPTANGENT' (as done below). It's OK, they're compatible. */
1040
1041                                         /* note: normally we'd use 'i_src' here, but 'i_dst' is in sync with 'rdata->cd.output' */
1042                                         rdata->cd.layers.tangent[i_dst] = CustomData_get_layer_n(&rdata->cd.output.ldata, CD_TANGENT, i_dst);
1043                                         if (rdata->tri_len != 0) {
1044                                                 BLI_assert(rdata->cd.layers.tangent[i_dst] != NULL);
1045                                         }
1046                                 }
1047                         }
1048                         if (cd_lused[CD_TANGENT] & DM_TANGENT_MASK_ORCO) {
1049                                 const char *name = CustomData_get_layer_name(&rdata->cd.output.ldata, CD_TANGENT, i_dst);
1050                                 uint hash = BLI_ghashutil_strhash_p(name);
1051                                 BLI_snprintf(rdata->cd.uuid.tangent[i_dst], sizeof(*rdata->cd.uuid.tangent), "t%u", hash);
1052
1053                                 rdata->cd.layers.tangent[i_dst] = CustomData_get_layer_n(&rdata->cd.output.ldata, CD_TANGENT, i_dst);
1054                         }
1055                 }
1056
1057 #undef me
1058         }
1059
1060         return rdata;
1061 }
1062
1063 /* Warning replace mesh pointer. */
1064 #define MBC_GET_FINAL_MESH(me) \
1065         /* Hack to show the final result. */ \
1066         const bool _use_em_final = ( \
1067                 (me)->edit_btmesh && \
1068                 (me)->edit_btmesh->mesh_eval_final && \
1069                 ((me)->edit_btmesh->mesh_eval_final->runtime.is_original == false)); \
1070         Mesh _me_fake; \
1071         if (_use_em_final) { \
1072                 _me_fake = *(me)->edit_btmesh->mesh_eval_final; \
1073                 _me_fake.mat = (me)->mat; \
1074                 _me_fake.totcol = (me)->totcol; \
1075                 (me) = &_me_fake; \
1076         } ((void)0)
1077
1078 static void mesh_render_data_free(MeshRenderData *rdata)
1079 {
1080         if (rdata->is_orco_allocated) {
1081                 MEM_SAFE_FREE(rdata->orco);
1082         }
1083         MEM_SAFE_FREE(rdata->cd.offset.uv);
1084         MEM_SAFE_FREE(rdata->cd.offset.vcol);
1085         MEM_SAFE_FREE(rdata->cd.uuid.auto_mix);
1086         MEM_SAFE_FREE(rdata->cd.uuid.uv);
1087         MEM_SAFE_FREE(rdata->cd.uuid.vcol);
1088         MEM_SAFE_FREE(rdata->cd.uuid.tangent);
1089         MEM_SAFE_FREE(rdata->cd.layers.uv);
1090         MEM_SAFE_FREE(rdata->cd.layers.vcol);
1091         MEM_SAFE_FREE(rdata->cd.layers.tangent);
1092         MEM_SAFE_FREE(rdata->cd.layers.auto_vcol);
1093         MEM_SAFE_FREE(rdata->loose_verts);
1094         MEM_SAFE_FREE(rdata->loose_edges);
1095         MEM_SAFE_FREE(rdata->edges_adjacent_polys);
1096         MEM_SAFE_FREE(rdata->mlooptri);
1097         MEM_SAFE_FREE(rdata->loop_normals);
1098         MEM_SAFE_FREE(rdata->poly_normals);
1099         MEM_SAFE_FREE(rdata->poly_normals_pack);
1100         MEM_SAFE_FREE(rdata->vert_normals_pack);
1101         MEM_SAFE_FREE(rdata->vert_weight);
1102         MEM_SAFE_FREE(rdata->edge_select_bool);
1103         MEM_SAFE_FREE(rdata->edge_visible_bool);
1104         MEM_SAFE_FREE(rdata->vert_color);
1105
1106         MEM_SAFE_FREE(rdata->mapped.loose_verts);
1107         MEM_SAFE_FREE(rdata->mapped.loose_edges);
1108
1109         CustomData_free(&rdata->cd.output.ldata, rdata->loop_len);
1110
1111         MEM_freeN(rdata);
1112 }
1113
1114 static MeshRenderData *mesh_render_data_create(Mesh *me, const int types)
1115 {
1116         return mesh_render_data_create_ex(me, types, NULL, NULL);
1117 }
1118
1119 /** \} */
1120
1121 /* ---------------------------------------------------------------------- */
1122
1123 /** \name Accessor Functions
1124  * \{ */
1125
1126 static const char *mesh_render_data_uv_auto_layer_uuid_get(const MeshRenderData *rdata, int layer)
1127 {
1128         BLI_assert(rdata->types & MR_DATATYPE_SHADING);
1129         return rdata->cd.uuid.auto_mix[layer];
1130 }
1131
1132 static const char *mesh_render_data_vcol_auto_layer_uuid_get(const MeshRenderData *rdata, int layer)
1133 {
1134         BLI_assert(rdata->types & MR_DATATYPE_SHADING);
1135         return rdata->cd.uuid.auto_mix[rdata->cd.layers.uv_len + layer];
1136 }
1137
1138 static const char *mesh_render_data_uv_layer_uuid_get(const MeshRenderData *rdata, int layer)
1139 {
1140         BLI_assert(rdata->types & MR_DATATYPE_SHADING);
1141         return rdata->cd.uuid.uv[layer];
1142 }
1143
1144 static const char *mesh_render_data_vcol_layer_uuid_get(const MeshRenderData *rdata, int layer)
1145 {
1146         BLI_assert(rdata->types & MR_DATATYPE_SHADING);
1147         return rdata->cd.uuid.vcol[layer];
1148 }
1149
1150 static const char *mesh_render_data_tangent_layer_uuid_get(const MeshRenderData *rdata, int layer)
1151 {
1152         BLI_assert(rdata->types & MR_DATATYPE_SHADING);
1153         return rdata->cd.uuid.tangent[layer];
1154 }
1155
1156 static int mesh_render_data_verts_len_get(const MeshRenderData *rdata)
1157 {
1158         BLI_assert(rdata->types & MR_DATATYPE_VERT);
1159         return rdata->vert_len;
1160 }
1161 static int mesh_render_data_verts_len_get_maybe_mapped(const MeshRenderData *rdata)
1162 {
1163         BLI_assert(rdata->types & MR_DATATYPE_VERT);
1164         return ((rdata->mapped.use == false) ? rdata->vert_len : rdata->mapped.vert_len);
1165 }
1166
1167 static int UNUSED_FUNCTION(mesh_render_data_loose_verts_len_get)(const MeshRenderData *rdata)
1168 {
1169         BLI_assert(rdata->types & MR_DATATYPE_OVERLAY);
1170         return rdata->loose_vert_len;
1171 }
1172 static int mesh_render_data_loose_verts_len_get_maybe_mapped(const MeshRenderData *rdata)
1173 {
1174         BLI_assert(rdata->types & MR_DATATYPE_OVERLAY);
1175         return ((rdata->mapped.use == false) ? rdata->loose_vert_len : rdata->mapped.loose_vert_len);
1176 }
1177
1178 static int mesh_render_data_edges_len_get(const MeshRenderData *rdata)
1179 {
1180         BLI_assert(rdata->types & MR_DATATYPE_EDGE);
1181         return rdata->edge_len;
1182 }
1183 static int mesh_render_data_edges_len_get_maybe_mapped(const MeshRenderData *rdata)
1184 {
1185         BLI_assert(rdata->types & MR_DATATYPE_EDGE);
1186         return ((rdata->mapped.use == false) ? rdata->edge_len : rdata->mapped.edge_len);
1187 }
1188
1189 static int UNUSED_FUNCTION(mesh_render_data_loose_edges_len_get)(const MeshRenderData *rdata)
1190 {
1191         BLI_assert(rdata->types & MR_DATATYPE_OVERLAY);
1192         return rdata->loose_edge_len;
1193 }
1194 static int mesh_render_data_loose_edges_len_get_maybe_mapped(const MeshRenderData *rdata)
1195 {
1196         BLI_assert(rdata->types & MR_DATATYPE_OVERLAY);
1197         return ((rdata->mapped.use == false) ? rdata->loose_edge_len : rdata->mapped.loose_edge_len);
1198 }
1199
1200 static int mesh_render_data_looptri_len_get(const MeshRenderData *rdata)
1201 {
1202         BLI_assert(rdata->types & MR_DATATYPE_LOOPTRI);
1203         return rdata->tri_len;
1204 }
1205 static int mesh_render_data_looptri_len_get_maybe_mapped(const MeshRenderData *rdata)
1206 {
1207         BLI_assert(rdata->types & MR_DATATYPE_LOOPTRI);
1208         return ((rdata->mapped.use == false) ? rdata->tri_len : rdata->mapped.tri_len);
1209 }
1210
1211 static int UNUSED_FUNCTION(mesh_render_data_mat_len_get)(const MeshRenderData *rdata)
1212 {
1213         BLI_assert(rdata->types & MR_DATATYPE_POLY);
1214         return rdata->mat_len;
1215 }
1216
1217 static int mesh_render_data_loops_len_get(const MeshRenderData *rdata)
1218 {
1219         BLI_assert(rdata->types & MR_DATATYPE_LOOP);
1220         return rdata->loop_len;
1221 }
1222
1223 static int mesh_render_data_polys_len_get(const MeshRenderData *rdata)
1224 {
1225         BLI_assert(rdata->types & MR_DATATYPE_POLY);
1226         return rdata->poly_len;
1227 }
1228 static int mesh_render_data_polys_len_get_maybe_mapped(const MeshRenderData *rdata)
1229 {
1230         BLI_assert(rdata->types & MR_DATATYPE_POLY);
1231         return ((rdata->mapped.use == false) ? rdata->poly_len : rdata->mapped.poly_len);
1232 }
1233
1234 /** \} */
1235
1236
1237 /* ---------------------------------------------------------------------- */
1238
1239 /* TODO remove prototype. */
1240 static void mesh_create_edit_facedots(MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor_data_facedots);
1241
1242 /** \name Internal Cache (Lazy Initialization)
1243  * \{ */
1244
1245 /** Ensure #MeshRenderData.poly_normals_pack */
1246 static void mesh_render_data_ensure_poly_normals_pack(MeshRenderData *rdata)
1247 {
1248         GPUPackedNormal *pnors_pack = rdata->poly_normals_pack;
1249         if (pnors_pack == NULL) {
1250                 if (rdata->edit_bmesh) {
1251                         BMesh *bm = rdata->edit_bmesh->bm;
1252                         BMIter fiter;
1253                         BMFace *efa;
1254                         int i;
1255
1256                         pnors_pack = rdata->poly_normals_pack = MEM_mallocN(sizeof(*pnors_pack) * rdata->poly_len, __func__);
1257                         if (rdata->edit_data && rdata->edit_data->vertexCos != NULL) {
1258                                 BKE_editmesh_cache_ensure_poly_normals(rdata->edit_bmesh, rdata->edit_data);
1259                                 const float (*pnors)[3] = rdata->edit_data->polyNos;
1260                                 for (i = 0; i < bm->totface; i++) {
1261                                         pnors_pack[i] = GPU_normal_convert_i10_v3(pnors[i]);
1262                                 }
1263                         }
1264                         else {
1265                                 BM_ITER_MESH_INDEX(efa, &fiter, bm, BM_FACES_OF_MESH, i) {
1266                                         pnors_pack[i] = GPU_normal_convert_i10_v3(efa->no);
1267                                 }
1268                         }
1269                 }
1270                 else {
1271                         float (*pnors)[3] = rdata->poly_normals;
1272
1273                         if (!pnors) {
1274                                 pnors = rdata->poly_normals = MEM_mallocN(sizeof(*pnors) * rdata->poly_len, __func__);
1275                                 BKE_mesh_calc_normals_poly(
1276                                         rdata->mvert, NULL, rdata->vert_len,
1277                                         rdata->mloop, rdata->mpoly, rdata->loop_len, rdata->poly_len, pnors, true);
1278                         }
1279
1280                         pnors_pack = rdata->poly_normals_pack = MEM_mallocN(sizeof(*pnors_pack) * rdata->poly_len, __func__);
1281                         for (int i = 0; i < rdata->poly_len; i++) {
1282                                 pnors_pack[i] = GPU_normal_convert_i10_v3(pnors[i]);
1283                         }
1284                 }
1285         }
1286 }
1287
1288 /** Ensure #MeshRenderData.vert_normals_pack */
1289 static void mesh_render_data_ensure_vert_normals_pack(MeshRenderData *rdata)
1290 {
1291         GPUPackedNormal *vnors_pack = rdata->vert_normals_pack;
1292         if (vnors_pack == NULL) {
1293                 if (rdata->edit_bmesh) {
1294                         BMesh *bm = rdata->edit_bmesh->bm;
1295                         BMIter viter;
1296                         BMVert *eve;
1297                         int i;
1298
1299                         vnors_pack = rdata->vert_normals_pack = MEM_mallocN(sizeof(*vnors_pack) * rdata->vert_len, __func__);
1300                         BM_ITER_MESH_INDEX(eve, &viter, bm, BM_VERT, i) {
1301                                 vnors_pack[i] = GPU_normal_convert_i10_v3(eve->no);
1302                         }
1303                 }
1304                 else {
1305                         /* data from mesh used directly */
1306                         BLI_assert(0);
1307                 }
1308         }
1309 }
1310
1311
1312 /** Ensure #MeshRenderData.vert_color */
1313 static void mesh_render_data_ensure_vert_color(MeshRenderData *rdata)
1314 {
1315         char (*vcol)[3] = rdata->vert_color;
1316         if (vcol == NULL) {
1317                 if (rdata->edit_bmesh) {
1318                         BMesh *bm = rdata->edit_bmesh->bm;
1319                         const int cd_loop_color_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPCOL);
1320                         if (cd_loop_color_offset == -1) {
1321                                 goto fallback;
1322                         }
1323
1324                         vcol = rdata->vert_color = MEM_mallocN(sizeof(*vcol) * rdata->loop_len, __func__);
1325
1326                         BMIter fiter;
1327                         BMFace *efa;
1328                         int i = 0;
1329
1330                         BM_ITER_MESH(efa, &fiter, bm, BM_FACES_OF_MESH) {
1331                                 BMLoop *l_iter, *l_first;
1332                                 l_iter = l_first = BM_FACE_FIRST_LOOP(efa);
1333                                 do {
1334                                         const MLoopCol *lcol = BM_ELEM_CD_GET_VOID_P(l_iter, cd_loop_color_offset);
1335                                         vcol[i][0] = lcol->r;
1336                                         vcol[i][1] = lcol->g;
1337                                         vcol[i][2] = lcol->b;
1338                                         i += 1;
1339                                 } while ((l_iter = l_iter->next) != l_first);
1340                         }
1341                         BLI_assert(i == rdata->loop_len);
1342                 }
1343                 else {
1344                         if (rdata->mloopcol == NULL) {
1345                                 goto fallback;
1346                         }
1347
1348                         vcol = rdata->vert_color = MEM_mallocN(sizeof(*vcol) * rdata->loop_len, __func__);
1349
1350                         for (int i = 0; i < rdata->loop_len; i++) {
1351                                 vcol[i][0] = rdata->mloopcol[i].r;
1352                                 vcol[i][1] = rdata->mloopcol[i].g;
1353                                 vcol[i][2] = rdata->mloopcol[i].b;
1354                         }
1355                 }
1356         }
1357         return;
1358
1359 fallback:
1360         vcol = rdata->vert_color = MEM_mallocN(sizeof(*vcol) * rdata->loop_len, __func__);
1361
1362         for (int i = 0; i < rdata->loop_len; i++) {
1363                 vcol[i][0] = 255;
1364                 vcol[i][1] = 255;
1365                 vcol[i][2] = 255;
1366         }
1367 }
1368
1369 static float evaluate_vertex_weight(const MDeformVert *dvert, const DRW_MeshWeightState *wstate)
1370 {
1371         float input = 0.0f;
1372         bool show_alert_color = false;
1373
1374         if (wstate->flags & DRW_MESH_WEIGHT_STATE_MULTIPAINT) {
1375                 /* Multi-Paint feature */
1376                 input = BKE_defvert_multipaint_collective_weight(
1377                         dvert, wstate->defgroup_len, wstate->defgroup_sel, wstate->defgroup_sel_count,
1378                         (wstate->flags & DRW_MESH_WEIGHT_STATE_AUTO_NORMALIZE) != 0);
1379
1380                 /* make it black if the selected groups have no weight on a vertex */
1381                 if (input == 0.0f) {
1382                         show_alert_color = true;
1383                 }
1384         }
1385         else {
1386                 /* default, non tricky behavior */
1387                 input = defvert_find_weight(dvert, wstate->defgroup_active);
1388
1389                 if (input == 0.0f) {
1390                         switch (wstate->alert_mode) {
1391                                 case OB_DRAW_GROUPUSER_ACTIVE:
1392                                         show_alert_color = true;
1393                                         break;
1394
1395                                 case OB_DRAW_GROUPUSER_ALL:
1396                                         show_alert_color = defvert_is_weight_zero(dvert, wstate->defgroup_len);
1397                                         break;
1398                         }
1399                 }
1400         }
1401
1402         if (show_alert_color) {
1403                 return -1.0f;
1404         }
1405         else {
1406                 CLAMP(input, 0.0f, 1.0f);
1407                 return input;
1408         }
1409 }
1410
1411 /** Ensure #MeshRenderData.vert_weight */
1412 static void mesh_render_data_ensure_vert_weight(MeshRenderData *rdata, const struct DRW_MeshWeightState *wstate)
1413 {
1414         float (*vweight) = rdata->vert_weight;
1415         if (vweight == NULL) {
1416                 if (wstate->defgroup_active == -1) {
1417                         goto fallback;
1418                 }
1419
1420                 if (rdata->edit_bmesh) {
1421                         BMesh *bm = rdata->edit_bmesh->bm;
1422                         const int cd_dvert_offset = CustomData_get_offset(&bm->vdata, CD_MDEFORMVERT);
1423                         if (cd_dvert_offset == -1) {
1424                                 goto fallback;
1425                         }
1426
1427                         BMIter viter;
1428                         BMVert *eve;
1429                         int i;
1430
1431                         vweight = rdata->vert_weight = MEM_mallocN(sizeof(*vweight) * rdata->vert_len, __func__);
1432                         BM_ITER_MESH_INDEX(eve, &viter, bm, BM_VERT, i) {
1433                                 const MDeformVert *dvert = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
1434                                 vweight[i] = evaluate_vertex_weight(dvert, wstate);
1435                         }
1436                 }
1437                 else {
1438                         if (rdata->dvert == NULL) {
1439                                 goto fallback;
1440                         }
1441
1442                         vweight = rdata->vert_weight = MEM_mallocN(sizeof(*vweight) * rdata->vert_len, __func__);
1443                         for (int i = 0; i < rdata->vert_len; i++) {
1444                                 vweight[i] = evaluate_vertex_weight(&rdata->dvert[i], wstate);
1445                         }
1446                 }
1447         }
1448         return;
1449
1450 fallback:
1451         vweight = rdata->vert_weight = MEM_callocN(sizeof(*vweight) * rdata->vert_len, __func__);
1452
1453         if ((wstate->defgroup_active < 0) && (wstate->defgroup_len > 0)) {
1454                 copy_vn_fl(vweight, rdata->vert_len, -2.0f);
1455         }
1456         else if (wstate->alert_mode != OB_DRAW_GROUPUSER_NONE) {
1457                 copy_vn_fl(vweight, rdata->vert_len, -1.0f);
1458         }
1459 }
1460
1461 /** \} */
1462
1463 /* ---------------------------------------------------------------------- */
1464
1465 /** \name Internal Cache Generation
1466  * \{ */
1467
1468 static bool mesh_render_data_edge_vcos_manifold_pnors(
1469         MeshRenderData *rdata, const int edge_index,
1470         float **r_vco1, float **r_vco2, float **r_pnor1, float **r_pnor2, bool *r_is_manifold)
1471 {
1472         BLI_assert(rdata->types & (MR_DATATYPE_VERT | MR_DATATYPE_EDGE | MR_DATATYPE_LOOP | MR_DATATYPE_POLY));
1473
1474         if (rdata->edit_bmesh) {
1475                 BMesh *bm = rdata->edit_bmesh->bm;
1476                 BMEdge *eed = BM_edge_at_index(bm, edge_index);
1477                 if (BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
1478                         return false;
1479                 }
1480                 *r_vco1 = eed->v1->co;
1481                 *r_vco2 = eed->v2->co;
1482                 if (BM_edge_is_manifold(eed)) {
1483                         *r_pnor1 = eed->l->f->no;
1484                         *r_pnor2 = eed->l->radial_next->f->no;
1485                         *r_is_manifold = true;
1486                 }
1487                 else if (eed->l != NULL) {
1488                         *r_pnor1 = eed->l->f->no;
1489                         *r_pnor2 = eed->l->f->no;
1490                         *r_is_manifold = false;
1491                 }
1492                 else {
1493                         *r_pnor1 = eed->v1->no;
1494                         *r_pnor2 = eed->v1->no;
1495                         *r_is_manifold = false;
1496                 }
1497         }
1498         else {
1499                 MVert *mvert = rdata->mvert;
1500                 const MEdge *medge = rdata->medge;
1501                 EdgeAdjacentPolys *eap = rdata->edges_adjacent_polys;
1502                 float (*pnors)[3] = rdata->poly_normals;
1503
1504                 if (!eap) {
1505                         const MLoop *mloop = rdata->mloop;
1506                         const MPoly *mpoly = rdata->mpoly;
1507                         const int poly_len = rdata->poly_len;
1508                         const bool do_pnors = (poly_len != 0 && pnors == NULL);
1509
1510                         eap = rdata->edges_adjacent_polys = MEM_mallocN(sizeof(*eap) * rdata->edge_len, __func__);
1511                         for (int i = 0; i < rdata->edge_len; i++) {
1512                                 eap[i].count = 0;
1513                                 eap[i].face_index[0] = -1;
1514                                 eap[i].face_index[1] = -1;
1515                         }
1516                         if (do_pnors) {
1517                                 pnors = rdata->poly_normals = MEM_mallocN(sizeof(*pnors) * poly_len, __func__);
1518                         }
1519
1520                         for (int i = 0; i < poly_len; i++, mpoly++) {
1521                                 if (do_pnors) {
1522                                         BKE_mesh_calc_poly_normal(mpoly, mloop + mpoly->loopstart, mvert, pnors[i]);
1523                                 }
1524
1525                                 const int loopend = mpoly->loopstart + mpoly->totloop;
1526                                 for (int j = mpoly->loopstart; j < loopend; j++) {
1527                                         const int edge_idx = mloop[j].e;
1528                                         if (eap[edge_idx].count < 2) {
1529                                                 eap[edge_idx].face_index[eap[edge_idx].count] = i;
1530                                         }
1531                                         eap[edge_idx].count++;
1532                                 }
1533                         }
1534                 }
1535                 BLI_assert(eap && (rdata->poly_len == 0 || pnors != NULL));
1536
1537                 *r_vco1 = mvert[medge[edge_index].v1].co;
1538                 *r_vco2 = mvert[medge[edge_index].v2].co;
1539                 if (eap[edge_index].face_index[0] == -1) {
1540                         /* Edge has no poly... */
1541                         *r_pnor1 = *r_pnor2 = mvert[medge[edge_index].v1].co; /* XXX mvert.no are shorts... :( */
1542                         *r_is_manifold = false;
1543                 }
1544                 else {
1545                         *r_pnor1 = pnors[eap[edge_index].face_index[0]];
1546
1547                         float nor[3], v1[3], v2[3], r_center[3];
1548                         const MPoly *mpoly = rdata->mpoly + eap[edge_index].face_index[0];
1549                         const MLoop *mloop = rdata->mloop + mpoly->loopstart;
1550
1551                         BKE_mesh_calc_poly_center(mpoly, mloop, mvert, r_center);
1552                         sub_v3_v3v3(v1, *r_vco2, *r_vco1);
1553                         sub_v3_v3v3(v2, r_center, *r_vco1);
1554                         cross_v3_v3v3(nor, v1, v2);
1555
1556                         if (dot_v3v3(nor, *r_pnor1) < 0.0) {
1557                                 SWAP(float *, *r_vco1, *r_vco2);
1558                         }
1559
1560                         if (eap[edge_index].count == 2) {
1561                                 BLI_assert(eap[edge_index].face_index[1] >= 0);
1562                                 *r_pnor2 = pnors[eap[edge_index].face_index[1]];
1563                                 *r_is_manifold = true;
1564                         }
1565                         else {
1566                                 *r_pnor2 = pnors[eap[edge_index].face_index[0]];
1567                                 *r_is_manifold = false;
1568                         }
1569                 }
1570         }
1571
1572         return true;
1573 }
1574
1575 static uchar mesh_render_data_looptri_flag(MeshRenderData *rdata, const BMFace *efa)
1576 {
1577         uchar fflag = 0;
1578
1579         if (efa == rdata->efa_act)
1580                 fflag |= VFLAG_FACE_ACTIVE;
1581
1582         if (BM_elem_flag_test(efa, BM_ELEM_SELECT))
1583                 fflag |= VFLAG_FACE_SELECTED;
1584
1585 #ifdef WITH_FREESTYLE
1586         if (rdata->cd.offset.freestyle_face != -1) {
1587                 const FreestyleFace *ffa = BM_ELEM_CD_GET_VOID_P(efa, rdata->cd.offset.freestyle_face);
1588                 if (ffa->flag & FREESTYLE_FACE_MARK) {
1589                         fflag |= VFLAG_FACE_FREESTYLE;
1590                 }
1591         }
1592 #endif
1593
1594         return fflag;
1595 }
1596
1597 static void mesh_render_data_edge_flag(
1598         const MeshRenderData *rdata, const BMEdge *eed,
1599         EdgeDrawAttr *eattr)
1600 {
1601         eattr->e_flag |= VFLAG_EDGE_EXISTS;
1602
1603         if (eed == rdata->eed_act)
1604                 eattr->e_flag |= VFLAG_EDGE_ACTIVE;
1605
1606         if (BM_elem_flag_test(eed, BM_ELEM_SELECT))
1607                 eattr->e_flag |= VFLAG_EDGE_SELECTED;
1608
1609         if (BM_elem_flag_test(eed, BM_ELEM_SEAM))
1610                 eattr->e_flag |= VFLAG_EDGE_SEAM;
1611
1612         if (!BM_elem_flag_test(eed, BM_ELEM_SMOOTH))
1613                 eattr->e_flag |= VFLAG_EDGE_SHARP;
1614
1615         /* Use a byte for value range */
1616         if (rdata->cd.offset.crease != -1) {
1617                 float crease = BM_ELEM_CD_GET_FLOAT(eed, rdata->cd.offset.crease);
1618                 if (crease > 0) {
1619                         eattr->crease = (uchar)(crease * 255.0f);
1620                 }
1621         }
1622
1623         /* Use a byte for value range */
1624         if (rdata->cd.offset.bweight != -1) {
1625                 float bweight = BM_ELEM_CD_GET_FLOAT(eed, rdata->cd.offset.bweight);
1626                 if (bweight > 0) {
1627                         eattr->bweight = (uchar)(bweight * 255.0f);
1628                 }
1629         }
1630
1631 #ifdef WITH_FREESTYLE
1632         if (rdata->cd.offset.freestyle_edge != -1) {
1633                 const FreestyleEdge *fed = BM_ELEM_CD_GET_VOID_P(eed, rdata->cd.offset.freestyle_edge);
1634                 if (fed->flag & FREESTYLE_EDGE_MARK) {
1635                         eattr->e_flag |= VFLAG_EDGE_FREESTYLE;
1636                 }
1637         }
1638 #endif
1639 }
1640
1641 static uchar mesh_render_data_vertex_flag(MeshRenderData *rdata, const BMVert *eve)
1642 {
1643         uchar vflag = VFLAG_VERTEX_EXISTS;
1644
1645         /* Current vertex */
1646         if (eve == rdata->eve_act)
1647                 vflag |= VFLAG_VERTEX_ACTIVE;
1648
1649         if (BM_elem_flag_test(eve, BM_ELEM_SELECT))
1650                 vflag |= VFLAG_VERTEX_SELECTED;
1651
1652         return vflag;
1653 }
1654
1655 static void add_edit_tri(
1656         MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor, GPUVertBuf *vbo_lnor, GPUVertBuf *vbo_data, GPUIndexBufBuilder *elb,
1657         const uint pos_id, const uint vnor_id, const uint lnor_id, const uint data_id,
1658         const BMLoop **bm_looptri, const int base_vert_idx)
1659 {
1660         uchar fflag;
1661         uchar vflag;
1662
1663         /* Only draw vertices once. */
1664         if (elb) {
1665                 for (int i = 0; i < 3; ++i) {
1666                         if (!BM_elem_flag_test(bm_looptri[i]->v, BM_ELEM_TAG)) {
1667                                 BM_elem_flag_enable(bm_looptri[i]->v, BM_ELEM_TAG);
1668                                 GPU_indexbuf_add_generic_vert(elb, base_vert_idx + i);
1669                         }
1670                 }
1671         }
1672
1673         if (vbo_pos_nor) {
1674                 /* TODO(sybren): deduplicate this and all the other places it's pasted to in this file. */
1675                 if (rdata->edit_data && rdata->edit_data->vertexCos) {
1676                         for (uint i = 0; i < 3; i++) {
1677                                 int vidx = BM_elem_index_get(bm_looptri[i]->v);
1678                                 const float *pos = rdata->edit_data->vertexCos[vidx];
1679                                 GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx + i, pos);
1680                         }
1681                 }
1682                 else {
1683                         for (uint i = 0; i < 3; i++) {
1684                                 const float *pos = bm_looptri[i]->v->co;
1685                                 GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx + i, pos);
1686                         }
1687                 }
1688
1689                 for (uint i = 0; i < 3; i++) {
1690                         GPUPackedNormal vnor = GPU_normal_convert_i10_v3(bm_looptri[i]->v->no);
1691                         GPU_vertbuf_attr_set(vbo_pos_nor, vnor_id, base_vert_idx + i, &vnor);
1692                 }
1693         }
1694
1695         if (vbo_lnor) {
1696                 float (*lnors)[3] = rdata->loop_normals;
1697                 for (uint i = 0; i < 3; i++) {
1698                         const float *nor = (lnors) ? lnors[BM_elem_index_get(bm_looptri[i])] : bm_looptri[0]->f->no;
1699                         GPUPackedNormal lnor = GPU_normal_convert_i10_v3(nor);
1700                         GPU_vertbuf_attr_set(vbo_lnor, lnor_id, base_vert_idx + i, &lnor);
1701                 }
1702         }
1703
1704         if (vbo_data) {
1705                 fflag = mesh_render_data_looptri_flag(rdata, bm_looptri[0]->f);
1706                 for (uint i = 0; i < 3; i++) {
1707                         const int i_next = (i + 1) % 3;
1708                         const int i_prev = (i + 2) % 3;
1709                         vflag = mesh_render_data_vertex_flag(rdata, bm_looptri[i]->v);
1710                         /* Opposite edge to the vertex at 'i'. */
1711                         EdgeDrawAttr eattr = {0};
1712                         const bool is_edge_real = (bm_looptri[i_next] == bm_looptri[i_prev]->prev);
1713                         if (is_edge_real) {
1714                                 mesh_render_data_edge_flag(rdata, bm_looptri[i_next]->e, &eattr);
1715                         }
1716                         eattr.v_flag = fflag | vflag;
1717                         GPU_vertbuf_attr_set(vbo_data, data_id, base_vert_idx + i, &eattr);
1718                 }
1719         }
1720 }
1721 static bool add_edit_tri_mapped(
1722         MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor, GPUVertBuf *vbo_lnor, GPUVertBuf *vbo_data, GPUIndexBufBuilder *elb,
1723         const uint pos_id, const uint vnor_id, const uint lnor_id, const uint data_id,
1724         BMFace *efa, const MLoopTri *mlt, const float (*poly_normals)[3], const float (*loop_normals)[3], const int base_vert_idx)
1725 {
1726         if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
1727                 return false;
1728         }
1729
1730         BMEditMesh *embm = rdata->edit_bmesh;
1731         BMesh *bm = embm->bm;
1732         Mesh *me_cage = embm->mesh_eval_cage;
1733
1734         const MVert *mvert = me_cage->mvert;
1735         const MEdge *medge = me_cage->medge;
1736         const MLoop *mloop = me_cage->mloop;
1737
1738         const int *v_origindex = rdata->mapped.v_origindex;
1739         const int *e_origindex = rdata->mapped.e_origindex;
1740
1741         if (elb) {
1742                 for (int i = 0; i < 3; ++i) {
1743                         const int v_orig = v_origindex[mloop[mlt->tri[i]].v];
1744                         if (v_orig == ORIGINDEX_NONE) {
1745                                 continue;
1746                         }
1747                         BMVert *v = BM_vert_at_index(bm, v_orig);
1748                         if (!BM_elem_flag_test(v, BM_ELEM_TAG)) {
1749                                 BM_elem_flag_enable(v, BM_ELEM_TAG);
1750                                 GPU_indexbuf_add_generic_vert(elb, base_vert_idx + i);
1751                         }
1752                 }
1753         }
1754
1755         if (vbo_pos_nor) {
1756                 for (uint i = 0; i < 3; i++) {
1757                         const float *pos = mvert[mloop[mlt->tri[i]].v].co;
1758                         GPUPackedNormal vnor = GPU_normal_convert_i10_s3(mvert[mloop[mlt->tri[i]].v].no);
1759                         GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx + i, pos);
1760                         GPU_vertbuf_attr_set(vbo_pos_nor, vnor_id, base_vert_idx + i, &vnor);
1761                 }
1762         }
1763
1764         if (vbo_lnor) {
1765                 for (uint i = 0; i < 3; i++) {
1766                         const float *nor = loop_normals ? loop_normals[mlt->tri[i]] : poly_normals[mlt->poly];
1767                         GPUPackedNormal lnor = GPU_normal_convert_i10_v3(nor);
1768                         GPU_vertbuf_attr_set(vbo_lnor, lnor_id, base_vert_idx + i, &lnor);
1769                 }
1770         }
1771
1772         if (vbo_data) {
1773                 EdgeDrawAttr eattr[3] = {{0}}; /* Importantly VFLAG_VERTEX_EXISTS is not set. */
1774                 uchar fflag = mesh_render_data_looptri_flag(rdata, efa);
1775                 for (uint i = 0; i < 3; i++) {
1776                         const int i_next = (i + 1) % 3;
1777                         const int i_prev = (i + 2) % 3;
1778                         const int v_orig = v_origindex[mloop[mlt->tri[i]].v];
1779                         if (v_orig != ORIGINDEX_NONE) {
1780                                 BMVert *v = BM_vert_at_index(bm, v_orig);
1781                                 eattr[i].v_flag |= mesh_render_data_vertex_flag(rdata, v);
1782                         }
1783                         /* Opposite edge to the vertex at 'i'. */
1784                         const int e_idx = mloop[mlt->tri[i_next]].e;
1785                         const int e_orig = e_origindex[e_idx];
1786                         if (e_orig != ORIGINDEX_NONE) {
1787                                 const MEdge *ed = &medge[e_idx];
1788                                 const uint tri_edge[2]  = {mloop[mlt->tri[i_prev]].v, mloop[mlt->tri[i_next]].v};
1789                                 const bool is_edge_real = (
1790                                         ((ed->v1 == tri_edge[0]) && (ed->v2 == tri_edge[1])) ||
1791                                         ((ed->v1 == tri_edge[1]) && (ed->v2 == tri_edge[0])));
1792                                 if (is_edge_real) {
1793                                         BMEdge *eed = BM_edge_at_index(bm, e_orig);
1794                                         mesh_render_data_edge_flag(rdata, eed, &eattr[i]);
1795                                         /* Set vertex selected if both original verts are selected. */
1796                                         if (BM_elem_flag_test(eed->v1, BM_ELEM_SELECT) &&
1797                                             BM_elem_flag_test(eed->v2, BM_ELEM_SELECT))
1798                                         {
1799                                                 eattr[i_next].v_flag |= VFLAG_VERTEX_SELECTED;
1800                                                 eattr[i_prev].v_flag |= VFLAG_VERTEX_SELECTED;
1801                                         }
1802                                 }
1803                         }
1804                 }
1805                 for (uint i = 0; i < 3; i++) {
1806                         eattr[i].v_flag |= fflag;
1807                         GPU_vertbuf_attr_set(vbo_data, data_id, base_vert_idx + i, &eattr[i]);
1808                 }
1809         }
1810
1811         return true;
1812 }
1813
1814 static void add_edit_loose_edge(
1815         MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor, GPUVertBuf *vbo_data,
1816         const uint pos_id, const uint vnor_id, const uint data_id,
1817         const BMEdge *eed, const int base_vert_idx)
1818 {
1819         if (vbo_pos_nor) {
1820                 /* TODO(sybren): deduplicate this and all the other places it's pasted to in this file. */
1821                 if (rdata->edit_data && rdata->edit_data->vertexCos) {
1822                         for (uint i = 0; i < 2; i++) {
1823                                 int vidx = BM_elem_index_get((&eed->v1)[i]);
1824                                 const float *pos = rdata->edit_data->vertexCos[vidx];
1825                                 GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx + i, pos);
1826                         }
1827                 }
1828                 else {
1829                         for (int i = 0; i < 2; i++) {
1830                                 const float *pos = (&eed->v1)[i]->co;
1831                                 GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx + i, pos);
1832                         }
1833                 }
1834
1835                 for (int i = 0; i < 2; i++) {
1836                         GPUPackedNormal vnor = GPU_normal_convert_i10_v3((&eed->v1)[i]->no);
1837                         GPU_vertbuf_attr_set(vbo_pos_nor, vnor_id, base_vert_idx + i, &vnor);
1838                 }
1839         }
1840
1841         if (vbo_data) {
1842                 EdgeDrawAttr eattr = {0};
1843                 mesh_render_data_edge_flag(rdata, eed, &eattr);
1844                 for (int i = 0; i < 2; i++) {
1845                         eattr.v_flag = mesh_render_data_vertex_flag(rdata, (&eed->v1)[i]);
1846                         GPU_vertbuf_attr_set(vbo_data, data_id, base_vert_idx + i, &eattr);
1847                 }
1848         }
1849 }
1850 static void add_edit_loose_edge_mapped(
1851         MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor, GPUVertBuf *vbo_data,
1852         const uint pos_id, const uint vnor_id, const uint data_id,
1853         BMEdge *eed, const MVert *mvert, const MEdge *ed, const int base_vert_idx)
1854 {
1855         if (vbo_pos_nor) {
1856                 /* TODO(sybren): deduplicate this and all the other places it's pasted to in this file. */
1857                 for (int i = 0; i < 2; i++) {
1858                         const float *pos = mvert[*(&ed->v1 + i)].co;
1859                         GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx + i, pos);
1860
1861                         GPUPackedNormal vnor = GPU_normal_convert_i10_s3(mvert[*(&ed->v1 + i)].no);
1862                         GPU_vertbuf_attr_set(vbo_pos_nor, vnor_id, base_vert_idx + i, &vnor);
1863                 }
1864         }
1865
1866         if (vbo_data) {
1867                 EdgeDrawAttr eattr = {0};
1868                 mesh_render_data_edge_flag(rdata, eed, &eattr);
1869                 for (int i = 0; i < 2; i++) {
1870                         const int v_orig = rdata->mapped.v_origindex[*(&ed->v1 + i)];
1871                         eattr.v_flag = (v_orig != ORIGINDEX_NONE) ? mesh_render_data_vertex_flag(rdata, (&eed->v1)[i]) : 0;
1872                         GPU_vertbuf_attr_set(vbo_data, data_id, base_vert_idx + i, &eattr);
1873                 }
1874         }
1875 }
1876
1877 static void add_edit_loose_vert(
1878         MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor, GPUVertBuf *vbo_data,
1879         const uint pos_id, const uint vnor_id, const uint data_id,
1880         const BMVert *eve, const int base_vert_idx)
1881 {
1882         if (vbo_pos_nor) {
1883                 /* TODO(sybren): deduplicate this and all the other places it's pasted to in this file. */
1884                 if (rdata->edit_data && rdata->edit_data->vertexCos) {
1885                         int vidx = BM_elem_index_get(eve);
1886                         const float *pos = rdata->edit_data->vertexCos[vidx];
1887                         GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx, pos);
1888                 }
1889                 else {
1890                         const float *pos = eve->co;
1891                         GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx, pos);
1892                 }
1893
1894                 GPUPackedNormal vnor = GPU_normal_convert_i10_v3(eve->no);
1895                 GPU_vertbuf_attr_set(vbo_pos_nor, vnor_id, base_vert_idx, &vnor);
1896         }
1897
1898         if (vbo_data) {
1899                 uchar vflag[4] = {0, 0, 0, 0};
1900                 vflag[0] = mesh_render_data_vertex_flag(rdata, eve);
1901                 GPU_vertbuf_attr_set(vbo_data, data_id, base_vert_idx, vflag);
1902         }
1903 }
1904 static void add_edit_loose_vert_mapped(
1905         MeshRenderData *rdata, GPUVertBuf *vbo_pos_nor, GPUVertBuf *vbo_data,
1906         const uint pos_id, const uint vnor_id, const uint data_id,
1907         const BMVert *eve, const MVert *mv, const int base_vert_idx)
1908 {
1909         if (vbo_pos_nor) {
1910                 const float *pos = mv->co;
1911                 GPU_vertbuf_attr_set(vbo_pos_nor, pos_id, base_vert_idx, pos);
1912
1913                 GPUPackedNormal vnor = GPU_normal_convert_i10_s3(mv->no);
1914                 GPU_vertbuf_attr_set(vbo_pos_nor, vnor_id, base_vert_idx, &vnor);
1915         }
1916
1917         if (vbo_data) {
1918                 uchar vflag[4] = {0, 0, 0, 0};
1919                 vflag[0] = mesh_render_data_vertex_flag(rdata, eve);
1920                 GPU_vertbuf_attr_set(vbo_data, data_id, base_vert_idx, vflag);
1921         }
1922 }
1923
1924 static bool add_edit_facedot(
1925         MeshRenderData *rdata, GPUVertBuf *vbo,
1926         const uint fdot_pos_id, const uint fdot_nor_flag_id,
1927         const int poly, const int base_vert_idx)
1928 {
1929         BLI_assert(rdata->types & (MR_DATATYPE_VERT | MR_DATATYPE_LOOP | MR_DATATYPE_POLY));
1930         float pnor[3], center[3];
1931         bool selected;
1932         if (rdata->edit_bmesh) {
1933                 const BMFace *efa = BM_face_at_index(rdata->edit_bmesh->bm, poly);
1934                 if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
1935                         return false;
1936                 }
1937                 if (rdata->edit_data && rdata->edit_data->vertexCos) {
1938                         copy_v3_v3(center, rdata->edit_data->polyCos[poly]);
1939                         copy_v3_v3(pnor, rdata->edit_data->polyNos[poly]);
1940                 }
1941                 else {
1942                         BM_face_calc_center_median(efa, center);
1943                         copy_v3_v3(pnor, efa->no);
1944                 }
1945                 selected = (BM_elem_flag_test(efa, BM_ELEM_SELECT) != 0) ? true : false;
1946         }
1947         else {
1948                 MVert *mvert = rdata->mvert;
1949                 const MPoly *mpoly = rdata->mpoly + poly;
1950                 const MLoop *mloop = rdata->mloop + mpoly->loopstart;
1951
1952                 BKE_mesh_calc_poly_center(mpoly, mloop, mvert, center);
1953                 BKE_mesh_calc_poly_normal(mpoly, mloop, mvert, pnor);
1954
1955                 selected = false; /* No selection if not in edit mode */
1956         }
1957
1958         GPUPackedNormal nor = GPU_normal_convert_i10_v3(pnor);
1959         nor.w = (selected) ? 1 : 0;
1960         GPU_vertbuf_attr_set(vbo, fdot_nor_flag_id, base_vert_idx, &nor);
1961         GPU_vertbuf_attr_set(vbo, fdot_pos_id, base_vert_idx, center);
1962
1963         return true;
1964 }
1965 static bool add_edit_facedot_mapped(
1966         MeshRenderData *rdata, GPUVertBuf *vbo,
1967         const uint fdot_pos_id, const uint fdot_nor_flag_id,
1968         const int poly, const int base_vert_idx)
1969 {
1970         BLI_assert(rdata->types & (MR_DATATYPE_VERT | MR_DATATYPE_LOOP | MR_DATATYPE_POLY));
1971         float pnor[3], center[3];
1972         const int *p_origindex = rdata->mapped.p_origindex;
1973         const int p_orig = p_origindex[poly];
1974         if (p_orig == ORIGINDEX_NONE) {
1975                 return false;
1976         }
1977         BMEditMesh *em = rdata->edit_bmesh;
1978         const BMFace *efa = BM_face_at_index(rdata->edit_bmesh->bm, p_orig);
1979         if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
1980                 return false;
1981         }
1982
1983         Mesh *me_cage = em->mesh_eval_cage;
1984         const MVert *mvert = me_cage->mvert;
1985         const MLoop *mloop = me_cage->mloop;
1986         const MPoly *mpoly = me_cage->mpoly;
1987
1988         const MPoly *mp = mpoly + poly;
1989         const MLoop *ml = mloop + mp->loopstart;
1990
1991         BKE_mesh_calc_poly_center(mp, ml, mvert, center);
1992         BKE_mesh_calc_poly_normal(mp, ml, mvert, pnor);
1993
1994         GPUPackedNormal nor = GPU_normal_convert_i10_v3(pnor);
1995         nor.w = (BM_elem_flag_test(efa, BM_ELEM_SELECT) != 0) ? 1 : 0;
1996         GPU_vertbuf_attr_set(vbo, fdot_nor_flag_id, base_vert_idx, &nor);
1997         GPU_vertbuf_attr_set(vbo, fdot_pos_id, base_vert_idx, center);
1998
1999         return true;
2000 }
2001
2002 /** \} */
2003
2004 /* ---------------------------------------------------------------------- */
2005
2006 /** \name Vertex Group Selection
2007  * \{ */
2008
2009 /** Reset the selection structure, deallocating heap memory as appropriate. */
2010 static void drw_mesh_weight_state_clear(struct DRW_MeshWeightState *wstate)
2011 {
2012         MEM_SAFE_FREE(wstate->defgroup_sel);
2013
2014         memset(wstate, 0, sizeof(*wstate));
2015
2016         wstate->defgroup_active = -1;
2017 }
2018
2019 /** Copy selection data from one structure to another, including heap memory. */
2020 static void drw_mesh_weight_state_copy(
2021         struct DRW_MeshWeightState *wstate_dst, const struct DRW_MeshWeightState *wstate_src)
2022 {
2023         MEM_SAFE_FREE(wstate_dst->defgroup_sel);
2024
2025         memcpy(wstate_dst, wstate_src, sizeof(*wstate_dst));
2026
2027         if (wstate_src->defgroup_sel) {
2028                 wstate_dst->defgroup_sel = MEM_dupallocN(wstate_src->defgroup_sel);
2029         }
2030 }
2031
2032 /** Compare two selection structures. */
2033 static bool drw_mesh_weight_state_compare(const struct DRW_MeshWeightState *a, const struct DRW_MeshWeightState *b)
2034 {
2035         return a->defgroup_active == b->defgroup_active &&
2036                a->defgroup_len == b->defgroup_len &&
2037                a->flags == b->flags &&
2038                a->alert_mode == b->alert_mode &&
2039                a->defgroup_sel_count == b->defgroup_sel_count &&
2040                ((!a->defgroup_sel && !b->defgroup_sel) ||
2041                 (a->defgroup_sel && b->defgroup_sel &&
2042                  memcmp(a->defgroup_sel, b->defgroup_sel, a->defgroup_len * sizeof(bool)) == 0));
2043 }
2044
2045 static void drw_mesh_weight_state_extract(
2046         Object *ob, Mesh *me, ToolSettings *ts, bool paint_mode,
2047         struct DRW_MeshWeightState *wstate)
2048 {
2049         /* Extract complete vertex weight group selection state and mode flags. */
2050         memset(wstate, 0, sizeof(*wstate));
2051
2052         wstate->defgroup_active = ob->actdef - 1;
2053         wstate->defgroup_len = BLI_listbase_count(&ob->defbase);
2054
2055         wstate->alert_mode = ts->weightuser;
2056
2057         if (paint_mode && ts->multipaint) {
2058                 /* Multipaint needs to know all selected bones, not just the active group.
2059                  * This is actually a relatively expensive operation, but caching would be difficult. */
2060                 wstate->defgroup_sel = BKE_object_defgroup_selected_get(ob, wstate->defgroup_len, &wstate->defgroup_sel_count);
2061
2062                 if (wstate->defgroup_sel_count > 1) {
2063                         wstate->flags |= DRW_MESH_WEIGHT_STATE_MULTIPAINT | (ts->auto_normalize ? DRW_MESH_WEIGHT_STATE_AUTO_NORMALIZE : 0);
2064
2065                         if (me->editflag & ME_EDIT_MIRROR_X) {
2066                                 BKE_object_defgroup_mirror_selection(
2067                                         ob, wstate->defgroup_len, wstate->defgroup_sel, wstate->defgroup_sel, &wstate->defgroup_sel_count);
2068                         }
2069                 }
2070                 /* With only one selected bone Multipaint reverts to regular mode. */
2071                 else {
2072                         wstate->defgroup_sel_count = 0;
2073                         MEM_SAFE_FREE(wstate->defgroup_sel);
2074                 }
2075         }
2076 }
2077
2078 /** \} */
2079
2080 /* ---------------------------------------------------------------------- */
2081
2082 /** \name Mesh GPUBatch Cache
2083  * \{ */
2084
2085 typedef struct MeshBatchCache {
2086         /* In order buffers: All verts only specified once.
2087          * To be used with a GPUIndexBuf. */
2088         struct {
2089                 /* Vertex data. */
2090                 GPUVertBuf *pos_nor;
2091                 GPUVertBuf *weights;
2092                 /* Loop data. */
2093                 GPUVertBuf *loop_pos_nor;
2094                 GPUVertBuf *loop_uv_tan;
2095                 GPUVertBuf *loop_vcol;
2096         } ordered;
2097
2098         /* Tesselated: (all verts specified for each triangles).
2099          * Indices does not match the CPU data structure's. */
2100         struct {
2101                 GPUVertBuf *pos_nor;
2102
2103                 GPUVertBuf *wireframe_data;
2104         } tess;
2105
2106         /* Edit Mesh Data:
2107          * Data is also tesselated because of barycentric wireframe rendering. */
2108         struct {
2109                 GPUVertBuf *pos_nor;
2110                 GPUVertBuf *pos_nor_ledges;
2111                 GPUVertBuf *pos_nor_lverts;
2112                 GPUVertBuf *pos_nor_data_facedots;
2113                 GPUVertBuf *data;
2114                 GPUVertBuf *data_ledges;
2115                 GPUVertBuf *data_lverts;
2116                 GPUVertBuf *lnor;
2117         } edit;
2118
2119         /* Index Buffers:
2120          * Only need to be updated when topology changes. */
2121         struct {
2122                 /* Indices to verts. */
2123                 GPUIndexBuf *surf_tris;
2124                 /* Indices to vloops. */
2125                 GPUIndexBuf *loops_tris;
2126                 GPUIndexBuf *loops_lines;
2127                 /* Contains indices to unique edit vertices to not
2128                  * draw the same vert multiple times (because of tesselation). */
2129                 GPUIndexBuf *edit_verts_points;
2130         } ibo;
2131
2132         struct {
2133                 /* Surfaces / Render */
2134                 GPUBatch *surface;
2135                 GPUBatch *surface_weights;
2136                 /* Edit mode */
2137                 GPUBatch *edit_triangles;
2138                 GPUBatch *edit_vertices;
2139                 GPUBatch *edit_loose_edges;
2140                 GPUBatch *edit_loose_verts;
2141                 GPUBatch *edit_triangles_nor;
2142                 GPUBatch *edit_triangles_lnor;
2143                 GPUBatch *edit_loose_edges_nor;
2144                 GPUBatch *edit_facedots;
2145                 /* Common display / Other */
2146                 GPUBatch *all_verts;
2147                 GPUBatch *wire_loops; /* Loops around faces. */
2148                 GPUBatch *wire_triangles; /* Triangles for object mode wireframe. */
2149         } batch;
2150
2151         GPUIndexBuf **surf_per_mat_tris;
2152         GPUBatch **surf_per_mat;
2153
2154         /* OLD BATCH METHOD, thoses needs to be ported and added in the structs above. */
2155
2156         /* Indices buffers. */
2157         GPUIndexBuf *edges_in_order;
2158         GPUIndexBuf *edges_adjacency; /* Store edges with adjacent vertices. */
2159         GPUIndexBuf *triangles_in_order;
2160         GPUIndexBuf *ledges_in_order;
2161
2162         GPUBatch *all_edges;
2163         GPUBatch *all_triangles;
2164
2165         GPUVertBuf *pos_with_normals;
2166         GPUVertBuf *pos_with_normals_visible_only;
2167         GPUVertBuf *pos_with_normals_edit;
2168         GPUVertBuf *pos_with_normals_visible_only_edit;
2169         GPUVertBuf *tri_aligned_uv;  /* Active UV layer (mloopuv) */
2170
2171         /**
2172          * Other uses are all positions or loose elements.
2173          * This stores all visible elements, needed for selection.
2174          */
2175         GPUVertBuf *ed_fcenter_pos_with_nor_and_sel;
2176         GPUVertBuf *ed_edge_pos;
2177         GPUVertBuf *ed_vert_pos;
2178
2179         GPUBatch *triangles_with_normals;
2180         GPUBatch *ledges_with_normals;
2181
2182         /* Skip hidden (depending on paint select mode) */
2183         GPUBatch *triangles_with_weights;
2184         GPUBatch *triangles_with_vert_colors;
2185         /* Always skip hidden */
2186         GPUBatch *triangles_with_select_mask;
2187         GPUBatch *triangles_with_select_id;
2188         uint       triangles_with_select_id_offset;
2189
2190         GPUBatch *facedot_with_select_id;  /* shares vbo with 'edit_facedots' */
2191         GPUBatch *edges_with_select_id;
2192         GPUBatch *verts_with_select_id;
2193
2194         uint facedot_with_select_id_offset;
2195         uint edges_with_select_id_offset;
2196         uint verts_with_select_id_offset;
2197
2198         GPUBatch *points_with_normals;
2199         GPUBatch *fancy_edges; /* owns its vertex buffer (not shared) */
2200
2201         GPUBatch *edge_detection;
2202
2203         /* Texture Paint.*/
2204         /* per-texture batch */
2205         GPUBatch **texpaint_triangles;
2206         GPUBatch  *texpaint_triangles_single;
2207
2208         GPUBatch *overlay_weight_faces;
2209         GPUBatch *overlay_weight_verts;
2210         GPUBatch *overlay_paint_edges;
2211
2212         /* 2D/UV edit */
2213         GPUVertBuf *edituv_pos;
2214         GPUVertBuf *edituv_area;
2215         GPUVertBuf *edituv_angle;
2216         GPUVertBuf *edituv_data;
2217
2218         GPUIndexBuf *edituv_visible_faces;
2219         GPUIndexBuf *edituv_visible_edges;
2220
2221         GPUBatch *texpaint_uv_loops;
2222
2223         GPUBatch *edituv_faces_strech_area;
2224         GPUBatch *edituv_faces_strech_angle;
2225         GPUBatch *edituv_faces;
2226         GPUBatch *edituv_edges;
2227         GPUBatch *edituv_verts;
2228         GPUBatch *edituv_facedots;
2229
2230         char edituv_state;
2231
2232         /* arrays of bool uniform names (and value) that will be use to
2233          * set srgb conversion for auto attribs.*/
2234         char *auto_layer_names;
2235         int *auto_layer_is_srgb;
2236         int auto_layer_len;
2237
2238         /* settings to determine if cache is invalid */
2239         bool is_maybe_dirty;
2240         bool is_dirty; /* Instantly invalidates cache, skipping mesh check */
2241         int edge_len;
2242         int tri_len;
2243         int poly_len;
2244         int vert_len;
2245         int mat_len;
2246         bool is_editmode;
2247
2248         struct DRW_MeshWeightState weight_state;
2249
2250         uchar cd_vused[CD_NUMTYPES];
2251         uchar cd_vneeded[CD_NUMTYPES];
2252         ushort cd_lused[CD_NUMTYPES];
2253         ushort cd_lneeded[CD_NUMTYPES];
2254
2255         /* XXX, only keep for as long as sculpt mode uses shaded drawing. */
2256         bool is_sculpt_points_tag;
2257
2258         /* Valid only if edges_adjacency is up to date. */
2259         bool is_manifold;
2260 } MeshBatchCache;
2261
2262 /* GPUBatch cache management. */
2263
2264 static bool mesh_batch_cache_valid(Mesh *me)
2265 {
2266         MeshBatchCache *cache = me->runtime.batch_cache;
2267
2268         if (cache == NULL) {
2269                 return false;
2270         }
2271
2272         if (cache->mat_len != mesh_render_mat_len_get(me)) {
2273                 return false;
2274         }
2275
2276         if (cache->is_editmode != (me->edit_btmesh != NULL)) {
2277                 return false;
2278         }
2279
2280         if (cache->is_dirty) {
2281                 return false;
2282         }
2283
2284         if (cache->is_maybe_dirty == false) {
2285                 return true;
2286         }
2287         else {
2288                 if (cache->is_editmode) {
2289                         return false;
2290                 }
2291                 else if ((cache->vert_len != mesh_render_verts_len_get(me)) ||
2292                          (cache->edge_len != mesh_render_edges_len_get(me)) ||
2293                          (cache->tri_len  != mesh_render_looptri_len_get(me)) ||
2294                          (cache->poly_len != mesh_render_polys_len_get(me)) ||
2295                          (cache->mat_len   != mesh_render_mat_len_get(me)))
2296                 {
2297                         return false;
2298                 }
2299         }
2300
2301         return true;
2302 }
2303
2304 static void mesh_batch_cache_init(Mesh *me)
2305 {
2306         MeshBatchCache *cache = me->runtime.batch_cache;
2307
2308         if (!cache) {
2309                 cache = me->runtime.batch_cache = MEM_callocN(sizeof(*cache), __func__);
2310         }
2311         else {
2312                 memset(cache, 0, sizeof(*cache));
2313         }
2314
2315         cache->is_editmode = me->edit_btmesh != NULL;
2316
2317         if (cache->is_editmode == false) {
2318                 cache->edge_len = mesh_render_edges_len_get(me);
2319                 cache->tri_len = mesh_render_looptri_len_get(me);
2320                 cache->poly_len = mesh_render_polys_len_get(me);
2321                 cache->vert_len = mesh_render_verts_len_get(me);
2322         }
2323
2324         cache->mat_len = mesh_render_mat_len_get(me);
2325         cache->surf_per_mat_tris = MEM_callocN(sizeof(*cache->surf_per_mat_tris) * cache->mat_len, __func__);
2326         cache->surf_per_mat = MEM_callocN(sizeof(*cache->surf_per_mat) * cache->mat_len, __func__);
2327
2328         /* TODO Might be wiser to alloc in one chunck. */
2329         for (int i = 0; i < cache->mat_len; ++i) {
2330                 cache->surf_per_mat_tris[i] = MEM_callocN(sizeof(GPUIndexBuf), "GPUIndexBuf");
2331                 cache->surf_per_mat[i] = MEM_callocN(sizeof(GPUBatch), "GPUBatch");
2332         }
2333
2334         cache->is_maybe_dirty = false;
2335         cache->is_dirty = false;
2336
2337         drw_mesh_weight_state_clear(&cache->weight_state);
2338 }
2339
2340 static MeshBatchCache *mesh_batch_cache_get(Mesh *me)
2341 {
2342         if (!mesh_batch_cache_valid(me)) {
2343                 mesh_batch_cache_clear(me);
2344                 mesh_batch_cache_init(me);
2345         }
2346         return me->runtime.batch_cache;
2347 }
2348
2349 static void mesh_batch_cache_check_vertex_group(MeshBatchCache *cache, const struct DRW_MeshWeightState *wstate)
2350 {
2351         if (!drw_mesh_weight_state_compare(&cache->weight_state, wstate)) {
2352                 GPU_BATCH_CLEAR_SAFE(cache->batch.surface_weights);
2353                 GPU_VERTBUF_DISCARD_SAFE(cache->ordered.weights);
2354
2355                 drw_mesh_weight_state_clear(&cache->weight_state);
2356         }
2357 }
2358
2359 static void mesh_batch_cache_discard_shaded_tri(MeshBatchCache *cache)
2360 {
2361         GPU_VERTBUF_DISCARD_SAFE(cache->ordered.loop_pos_nor);
2362         GPU_VERTBUF_DISCARD_SAFE(cache->ordered.loop_uv_tan);
2363         GPU_VERTBUF_DISCARD_SAFE(cache->ordered.loop_vcol);
2364         /* TODO */
2365         // GPU_VERTBUF_DISCARD_SAFE(cache->ordered.loop_orco);
2366
2367         if (cache->surf_per_mat_tris) {
2368                 for (int i = 0; i < cache->mat_len; i++) {
2369                         GPU_INDEXBUF_DISCARD_SAFE(cache->surf_per_mat_tris[i]);
2370                 }
2371         }
2372         MEM_SAFE_FREE(cache->surf_per_mat_tris);
2373         if (cache->surf_per_mat) {
2374                 for (int i = 0; i < cache->mat_len; i++) {
2375                         GPU_BATCH_DISCARD_SAFE(cache->surf_per_mat[i]);
2376                 }
2377         }
2378         MEM_SAFE_FREE(cache->surf_per_mat);
2379
2380         MEM_SAFE_FREE(cache->texpaint_triangles);
2381
2382         MEM_SAFE_FREE(cache->auto_layer_names);
2383         MEM_SAFE_FREE(cache->auto_layer_is_srgb);
2384
2385         cache->mat_len = 0;
2386 }
2387
2388 static void mesh_batch_cache_discard_uvedit(MeshBatchCache *cache)
2389 {
2390         GPU_VERTBUF_DISCARD_SAFE(cache->edituv_pos);
2391         GPU_VERTBUF_DISCARD_SAFE(cache->edituv_area);
2392         GPU_VERTBUF_DISCARD_SAFE(cache->edituv_angle);
2393         GPU_VERTBUF_DISCARD_SAFE(cache->edituv_data);
2394
2395         GPU_INDEXBUF_DISCARD_SAFE(cache->edituv_visible_faces);
2396         GPU_INDEXBUF_DISCARD_SAFE(cache->edituv_visible_edges);
2397
2398         if (cache->edituv_faces_strech_area) {
2399                 gpu_batch_presets_unregister(cache->edituv_faces_strech_area);
2400         }
2401         if (cache->edituv_faces_strech_angle) {
2402                 gpu_batch_presets_unregister(cache->edituv_faces_strech_angle);
2403         }
2404         if (cache->edituv_faces) {
2405                 gpu_batch_presets_unregister(cache->edituv_faces);
2406         }
2407         if (cache->edituv_edges) {
2408                 gpu_batch_presets_unregister(cache->edituv_edges);
2409         }
2410         if (cache->edituv_verts) {
2411                 gpu_batch_presets_unregister(cache->edituv_verts);
2412         }
2413         if (cache->edituv_facedots) {
2414                 gpu_batch_presets_unregister(cache->edituv_facedots);
2415         }
2416
2417         GPU_BATCH_DISCARD_SAFE(cache->edituv_faces_strech_area);
2418         GPU_BATCH_DISCARD_SAFE(cache->edituv_faces_strech_angle);
2419         GPU_BATCH_DISCARD_SAFE(cache->edituv_faces);
2420         GPU_BATCH_DISCARD_SAFE(cache->edituv_edges);
2421         GPU_BATCH_DISCARD_SAFE(cache->edituv_verts);
2422         GPU_BATCH_DISCARD_SAFE(cache->edituv_facedots);
2423
2424         gpu_batch_presets_unregister(cache->texpaint_uv_loops);
2425
2426         GPU_BATCH_DISCARD_SAFE(cache->texpaint_uv_loops);
2427
2428         cache->edituv_state = 0;
2429 }
2430
2431 void DRW_mesh_batch_cache_dirty_tag(Mesh *me, int mode)
2432 {
2433         MeshBatchCache *cache = me->runtime.batch_cache;
2434         if (cache == NULL) {
2435                 return;
2436         }
2437         switch (mode) {
2438                 case BKE_MESH_BATCH_DIRTY_MAYBE_ALL:
2439                         cache->is_maybe_dirty = true;
2440                         break;
2441                 case BKE_MESH_BATCH_DIRTY_SELECT:
2442                         GPU_VERTBUF_DISCARD_SAFE(cache->edit.data);
2443                         GPU_VERTBUF_DISCARD_SAFE(cache->edit.data_ledges);
2444                         GPU_VERTBUF_DISCARD_SAFE(cache->edit.data_lverts);
2445                         GPU_VERTBUF_DISCARD_SAFE(cache->edit.pos_nor_data_facedots);
2446                         GPU_BATCH_DISCARD_SAFE(cache->batch.edit_triangles);
2447                         GPU_BATCH_DISCARD_SAFE(cache->batch.edit_vertices);
2448                         GPU_BATCH_DISCARD_SAFE(cache->batch.edit_loose_verts);
2449                         GPU_BATCH_DISCARD_SAFE(cache->batch.edit_loose_edges);
2450                         GPU_BATCH_DISCARD_SAFE(cache->batch.edit_facedots);
2451                         GPU_VERTBUF_DISCARD_SAFE(cache->ed_edge_pos);
2452                         GPU_VERTBUF_DISCARD_SAFE(cache->ed_vert_pos);
2453                         /* Edit mode selection. */
2454                         GPU_BATCH_DISCARD_SAFE(cache->facedot_with_select_id);
2455                         GPU_BATCH_DISCARD_SAFE(cache->edges_with_select_id);
2456                         GPU_BATCH_DISCARD_SAFE(cache->verts_with_select_id);
2457                         /* Paint mode selection */
2458                         /* TODO only do that in paint mode. */
2459                         GPU_VERTBUF_DISCARD_SAFE(cache->ordered.loop_pos_nor);
2460                         GPU_BATCH_DISCARD_SAFE(cache->batch.surface);
2461                         GPU_BATCH_DISCARD_SAFE(cache->batch.wire_loops);
2462                         if (cache->surf_per_mat) {
2463                                 for (int i = 0; i < cache->mat_len; i++) {
2464                                         GPU_BATCH_DISCARD_SAFE(cache->surf_per_mat[i]);
2465                                 }
2466                         }
2467                         GPU_BATCH_DISCARD_SAFE(cache->overlay_paint_edges);
2468                         GPU_BATCH_DISCARD_SAFE(cache->overlay_weight_faces);
2469                         GPU_BATCH_DISCARD_SAFE(cache->overlay_weight_verts);
2470                         /* Because visible UVs depends on edit mode selection, discard everything. */
2471                         mesh_batch_cache_discard_uvedit(cache);
2472                         break;
2473                 case BKE_MESH_BATCH_DIRTY_ALL:
2474                         cache->is_dirty = true;
2475                         break;
2476                 case BKE_MESH_BATCH_DIRTY_SHADING:
2477                         mesh_batch_cache_discard_shaded_tri(cache);
2478                         mesh_batch_cache_discard_uvedit(cache);
2479                         break;
2480                 case BKE_MESH_BATCH_DIRTY_SCULPT_COORDS:
2481                         cache->is_sculpt_points_tag = true;
2482                         break;
2483                 case BKE_MESH_BATCH_DIRTY_UVEDIT_ALL:
2484                         mesh_batch_cache_discard_uvedit(cache);
2485                         break;
2486                 case BKE_MESH_BATCH_DIRTY_UVEDIT_SELECT:
2487                         /* For now same as above. */
2488                         mesh_batch_cache_discard_uvedit(cache);
2489                         break;
2490                 default:
2491                         BLI_assert(0);
2492         }
2493 }
2494
2495 /**
2496  * This only clear the batches associated to the given vertex buffer.
2497  **/
2498 static void mesh_batch_cache_clear_selective(Mesh *me, GPUVertBuf *vert)
2499 {
2500         MeshBatchCache *cache = me->runtime.batch_cache;
2501         if (!cache) {
2502                 return;
2503         }
2504
2505         BLI_assert(vert != NULL);
2506
2507         if (ELEM(vert, cache->pos_with_normals, cache->pos_with_normals_visible_only,
2508                        cache->pos_with_normals_edit, cache->pos_with_normals_visible_only_edit))
2509         {
2510                 GPU_BATCH_DISCARD_SAFE(cache->triangles_with_normals);
2511                 GPU_BATCH_DISCARD_SAFE(cache->triangles_with_weights);
2512                 GPU_BATCH_DISCARD_SAFE(cache->triangles_with_vert_colors);
2513                 GPU_BATCH_DISCARD_SAFE(cache->triangles_with_select_id);
2514                 GPU_BATCH_DISCARD_SAFE(cache->triangles_with_select_mask);
2515                 GPU_BATCH_DISCARD_SAFE(cache->points_with_normals);
2516                 GPU_BATCH_DISCARD_SAFE(cache->ledges_with_normals);
2517                 // if (cache->shaded_triangles) {
2518                 //      for (int i = 0; i < cache->mat_len; i++) {
2519                 //              GPU_BATCH_DISCARD_SAFE(cache->shaded_triangles[i]);
2520                 //      }
2521                 // }
2522                 // MEM_SAFE_FREE(cache->shaded_triangles);
2523                 // if (cache->texpaint_triangles) {
2524                 //      for (int i = 0; i < cache->mat_len; i++) {
2525                 //              GPU_BATCH_DISCARD_SAFE(cache->texpaint_triangles[i]);
2526                 //      }
2527                 // }
2528                 MEM_SAFE_FREE(cache->texpaint_triangles);
2529                 GPU_BATCH_DISCARD_SAFE(cache->texpaint_triangles_single);
2530         }
2531         /* TODO: add the other ones if needed. */
2532         else {
2533                 /* Does not match any vertbuf in the batch cache! */
2534                 BLI_assert(0);
2535         }
2536 }
2537
2538 static void mesh_batch_cache_clear(Mesh *me)
2539 {
2540         MeshBatchCache *cache = me->runtime.batch_cache;
2541         if (!cache) {
2542                 return;
2543         }
2544
2545         for (int i = 0; i < sizeof(cache->ordered) / sizeof(void *); ++i) {
2546                 GPUVertBuf **vbo = (GPUVertBuf **)&cache->ordered;
2547                 GPU_VERTBUF_DISCARD_SAFE(vbo[i]);
2548         }
2549         for (int i = 0; i < sizeof(cache->tess) / sizeof(void *); ++i) {
2550                 GPUVertBuf **vbo = (GPUVertBuf **)&cache->tess;
2551                 GPU_VERTBUF_DISCARD_SAFE(vbo[i]);
2552         }
2553         for (int i = 0; i < sizeof(cache->edit) / sizeof(void *); ++i) {
2554                 GPUVertBuf **vbo = (GPUVertBuf **)&cache->edit;
2555                 GPU_VERTBUF_DISCARD_SAFE(vbo[i]);
2556         }
2557         for (int i = 0; i < sizeof(cache->ibo) / sizeof(void *); ++i) {
2558                 GPUIndexBuf **ibo = (GPUIndexBuf **)&cache->ibo;
2559                 GPU_INDEXBUF_DISCARD_SAFE(ibo[i]);
2560         }
2561         for (int i = 0; i < sizeof(cache->batch) / sizeof(void *); ++i) {
2562                 GPUBatch **batch = (GPUBatch **)&cache->batch;
2563                 GPU_BATCH_DISCARD_SAFE(batch[i]);
2564         }
2565
2566         GPU_BATCH_DISCARD_SAFE(cache->all_edges);
2567         GPU_BATCH_DISCARD_SAFE(cache->all_triangles);
2568
2569         GPU_INDEXBUF_DISCARD_SAFE(cache->edges_in_order);
2570         GPU_INDEXBUF_DISCARD_SAFE(cache->triangles_in_order);
2571         GPU_INDEXBUF_DISCARD_SAFE(cache->ledges_in_order);
2572
2573         GPU_BATCH_DISCARD_SAFE(cache->overlay_weight_faces);
2574         GPU_BATCH_DISCARD_SAFE(cache->overlay_weight_verts);
2575         GPU_BATCH_DISCARD_SAFE(cache->overlay_paint_edges);
2576
2577         GPU_BATCH_DISCARD_SAFE(cache->triangles_with_normals);
2578         GPU_BATCH_DISCARD_SAFE(cache->points_with_normals);
2579         GPU_BATCH_DISCARD_SAFE(cache->ledges_with_normals);
2580         GPU_VERTBUF_DISCARD_SAFE(cache->pos_with_normals);
2581         GPU_VERTBUF_DISCARD_SAFE(cache->pos_with_normals_visible_only);
2582         GPU_VERTBUF_DISCARD_SAFE(cache->pos_with_normals_edit);
2583         GPU_VERTBUF_DISCARD_SAFE(cache->pos_with_normals_visible_only_edit);
2584         GPU_BATCH_DISCARD_SAFE(cache->triangles_with_weights);
2585         GPU_BATCH_DISCARD_SAFE(cache->triangles_with_vert_colors);
2586         GPU_VERTBUF_DISCARD_SAFE(cache->tri_aligned_uv);
2587         GPU_VERTBUF_DISCARD_SAFE(cache->ed_fcenter_pos_with_nor_and_sel);
2588         GPU_VERTBUF_DISCARD_SAFE(cache->ed_edge_pos);
2589         GPU_VERTBUF_DISCARD_SAFE(cache->ed_vert_pos);
2590         GPU_BATCH_DISCARD_SAFE(cache->triangles_with_select_mask);
2591         GPU_BATCH_DISCARD_SAFE(cache->triangles_with_select_id);
2592         GPU_BATCH_DISCARD_SAFE(cache->facedot_with_select_id);
2593         GPU_BATCH_DISCARD_SAFE(cache->edges_with_select_id);
2594         GPU_BATCH_DISCARD_SAFE(cache->verts_with_select_id);
2595
2596         GPU_BATCH_DISCARD_SAFE(cache->fancy_edges);
2597
2598         GPU_INDEXBUF_DISCARD_SAFE(cache->edges_adjacency);
2599         GPU_BATCH_DISCARD_SAFE(cache->edge_detection);
2600
2601         mesh_batch_cache_discard_shaded_tri(cache);
2602
2603         mesh_batch_cache_discard_uvedit(cache);
2604
2605         if (cache->texpaint_triangles) {
2606                 for (int i = 0; i < cache->mat_len; i++) {
2607                         GPU_BATCH_DISCARD_SAFE(cache->texpaint_triangles[i]);
2608                 }
2609         }
2610         MEM_SAFE_FREE(cache->texpaint_triangles);
2611
2612         drw_mesh_weight_state_clear(&cache->weight_state);
2613 }
2614
2615 void DRW_mesh_batch_cache_free(Mesh *me)
2616 {
2617         mesh_batch_cache_clear(me);
2618         MEM_SAFE_FREE(me->runtime.batch_cache);
2619 }
2620
2621 /* GPUBatch cache usage. */
2622
2623 static void mesh_create_pos_and_nor_tess(MeshRenderData *rdata, GPUVertBuf *vbo, bool use_hide)
2624 {
2625         static GPUVertFormat format = { 0 };
2626         static struct { uint pos, nor; } attr_id;
2627         if (format.attr_len == 0) {
2628                 attr_id.pos = GPU_vertformat_attr_add(&format, "pos", GPU_COMP_F32, 3, GPU_FETCH_FLOAT);
2629                 attr_id.nor = GPU_vertformat_attr_add(&format, "nor", GPU_COMP_I10, 3, GPU_FETCH_INT_TO_FLOAT_UNIT);
2630                 GPU_vertformat_triple_load(&format);
2631         }
2632
2633         GPU_vertbuf_init_with_format(vbo, &format);
2634
2635         const int tri_len = mesh_render_data_looptri_len_get_maybe_mapped(rdata);
2636         const int vbo_len_capacity = tri_len * 3;
2637         int vbo_len_used = 0;
2638         GPU_vertbuf_data_alloc(vbo, vbo_len_capacity);
2639
2640         GPUVertBufRaw pos_step, nor_step;
2641         GPU_vertbuf_attr_get_raw_data(vbo, attr_id.pos, &pos_step);
2642         GPU_vertbuf_attr_get_raw_data(vbo, attr_id.nor, &nor_step);
2643
2644         if (rdata->mapped.use == false) {
2645                 float (*lnors)[3] = rdata->loop_normals;
2646                 if (rdata->edit_bmesh) {
2647                         GPUPackedNormal *pnors_pack, *vnors_pack;
2648
2649                         if (lnors == NULL) {
2650                                 mesh_render_data_ensure_poly_normals_pack(rdata);
2651                                 mesh_render_data_ensure_vert_normals_pack(rdata);
2652
2653                                 pnors_pack = rdata->poly_normals_pack;
2654                                 vnors_pack = rdata->vert_normals_pack;
2655                         }
2656
2657                         for (int i = 0; i < tri_len; i++) {
2658                                 const BMLoop **bm_looptri = (const BMLoop **)rdata->edit_bmesh->looptris[i];
2659                                 const BMFace *bm_face = bm_looptri[0]->f;
2660
2661                                 /* use_hide always for edit-mode */
2662                                 if (BM_elem_flag_test(bm_face, BM_ELEM_HIDDEN)) {
2663                                         continue;
2664                                 }
2665
2666                                 if (lnors) {
2667                                         for (uint t = 0; t < 3; t++) {
2668                                                 const float *nor = lnors[BM_elem_index_get(bm_looptri[t])];
2669                                                 *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = GPU_normal_convert_i10_v3(nor);
2670                                         }
2671                                 }
2672                                 else if (BM_elem_flag_test(bm_face, BM_ELEM_SMOOTH)) {
2673                                         for (uint t = 0; t < 3; t++) {
2674                                                 *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = vnors_pack[BM_elem_index_get(bm_looptri[t]->v)];
2675                                         }
2676                                 }
2677                                 else {
2678                                         const GPUPackedNormal *snor_pack = &pnors_pack[BM_elem_index_get(bm_face)];
2679                                         for (uint t = 0; t < 3; t++) {
2680                                                 *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = *snor_pack;
2681                                         }
2682                                 }
2683
2684                                 /* TODO(sybren): deduplicate this and all the other places it's pasted to in this file. */
2685                                 if (rdata->edit_data && rdata->edit_data->vertexCos) {
2686                                         for (uint t = 0; t < 3; t++) {
2687                                                 int vidx = BM_elem_index_get(bm_looptri[t]->v);
2688                                                 const float *pos = rdata->edit_data->vertexCos[vidx];
2689                                                 copy_v3_v3(GPU_vertbuf_raw_step(&pos_step), pos);
2690                                         }
2691                                 }
2692                                 else {
2693                                         for (uint t = 0; t < 3; t++) {
2694                                                 copy_v3_v3(GPU_vertbuf_raw_step(&pos_step), bm_looptri[t]->v->co);
2695                                         }
2696                                 }
2697                         }
2698                 }
2699                 else {
2700                         if (lnors == NULL) {
2701                                 /* Use normals from vertex. */
2702                                 mesh_render_data_ensure_poly_normals_pack(rdata);
2703                         }
2704
2705                         for (int i = 0; i < tri_len; i++) {
2706                                 const MLoopTri *mlt = &rdata->mlooptri[i];
2707                                 const MPoly *mp = &rdata->mpoly[mlt->poly];
2708
2709                                 if (use_hide && (mp->flag & ME_HIDE)) {
2710                                         continue;
2711                                 }
2712
2713                                 const uint vtri[3] = {
2714                                         rdata->mloop[mlt->tri[0]].v,
2715                                         rdata->mloop[mlt->tri[1]].v,
2716                                         rdata->mloop[mlt->tri[2]].v,
2717                                 };
2718
2719                                 if (lnors) {
2720                                         for (uint t = 0; t < 3; t++) {
2721                                                 const float *nor = lnors[mlt->tri[t]];
2722                                                 *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = GPU_normal_convert_i10_v3(nor);
2723                                         }
2724                                 }
2725                                 else if (mp->flag & ME_SMOOTH) {
2726                                         for (uint t = 0; t < 3; t++) {
2727                                                 const MVert *mv = &rdata->mvert[vtri[t]];
2728                                                 *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = GPU_normal_convert_i10_s3(mv->no);
2729                                         }
2730                                 }
2731                                 else {
2732                                         const GPUPackedNormal *pnors_pack = &rdata->poly_normals_pack[mlt->poly];
2733                                         for (uint t = 0; t < 3; t++) {
2734                                                 *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = *pnors_pack;
2735                                         }
2736                                 }
2737
2738                                 for (uint t = 0; t < 3; t++) {
2739                                         const MVert *mv = &rdata->mvert[vtri[t]];
2740                                         copy_v3_v3(GPU_vertbuf_raw_step(&pos_step), mv->co);
2741                                 }
2742                         }
2743                 }
2744         }
2745         else {
2746                 /* Note: mapped doesn't support lnors yet. */
2747                 BMesh *bm = rdata->edit_bmesh->bm;
2748                 Mesh *me_cage = rdata->mapped.me_cage;
2749
2750                 /* TODO(campbell): unlike non-mapped modes we don't generate these on demand, just use if they exist.
2751                  * this seems like a low priority TODO since mapped meshes typically
2752                  * use the final mesh evaluated mesh for showing faces. */
2753                 const float (*lnors)[3] = CustomData_get_layer(&me_cage->ldata, CD_NORMAL);
2754
2755                 /* TODO(campbell): this is quite an expensive operation for something
2756                  * that's not used unless 'normal' display option is enabled. */
2757                 if (!CustomData_has_layer(&me_cage->pdata, CD_NORMAL)) {
2758                         /* TODO(campbell): this is quite an expensive operation for something
2759                          * that's not used unless 'normal' display option is enabled. */
2760                         BKE_mesh_ensure_normals_for_display(me_cage);
2761                 }
2762                 const float (*polynors)[3] = CustomData_get_layer(&me_cage->pdata, CD_NORMAL);
2763
2764                 const MVert *mvert = rdata->mapped.me_cage->mvert;
2765                 const MLoop *mloop = rdata->mapped.me_cage->mloop;
2766                 const MPoly *mpoly = rdata->mapped.me_cage->mpoly;
2767
2768                 const MLoopTri *mlooptri = BKE_mesh_runtime_looptri_ensure(me_cage);
2769                 for (int i = 0; i < tri_len; i++) {
2770                         const MLoopTri *mlt = &mlooptri[i];
2771                         const int p_orig = rdata->mapped.p_origindex[mlt->poly];
2772                         if (p_orig != ORIGINDEX_NONE) {
2773                                 /* Assume 'use_hide' */
2774                                 BMFace *efa = BM_face_at_index(bm, p_orig);
2775                                 if (!BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
2776                                         const MPoly *mp = &mpoly[mlt->poly];
2777                                         const uint vtri[3] = {
2778                                                 mloop[mlt->tri[0]].v,
2779                                                 mloop[mlt->tri[1]].v,
2780                                                 mloop[mlt->tri[2]].v,
2781                                         };
2782
2783                                         if (lnors) {
2784                                                 for (uint t = 0; t < 3; t++) {
2785                                                         const float *nor = lnors[mlt->tri[t]];
2786                                                         *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = GPU_normal_convert_i10_v3(nor);
2787                                                 }
2788                                         }
2789                                         else if (mp->flag & ME_SMOOTH) {
2790                                                 for (uint t = 0; t < 3; t++) {
2791                                                         const MVert *mv = &mvert[vtri[t]];
2792                                                         *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = GPU_normal_convert_i10_s3(mv->no);
2793                                                 }
2794                                         }
2795                                         else {
2796                                                 /* we don't have cached 'rdata->poly_normals_pack'. */
2797                                                 const GPUPackedNormal pnor = GPU_normal_convert_i10_v3(polynors[mlt->poly]);
2798                                                 for (uint t = 0; t < 3; t++) {
2799                                                         *((GPUPackedNormal *)GPU_vertbuf_raw_step(&nor_step)) = pnor;
2800                                                 }
2801                                         }
2802
2803                                         for (uint t = 0; t < 3; t++) {
2804                                                 const MVert *mv = &mvert[vtri[t]];
2805                                                 copy_v3_v3(GPU_vertbuf_raw_step(&pos_step), mv->co);
2806                                         }
2807                                 }
2808                         }
2809                 }
2810         }
2811
2812         vbo_len_used = GPU_vertbuf_raw_used(&pos_step);
2813         BLI_assert(vbo_len_used == GPU_vertbuf_raw_used(&nor_step));
2814
2815         if (vbo_len_capacity != vbo_len_used) {
2816                 GPU_vertbuf_data_resize(vbo, vbo_len_used);
2817         }
2818 }
2819
2820 static GPUVertBuf *mesh_batch_cache_get_tri_pos_and_normals_ex(
2821         MeshRenderData *rdata, const bool use_hide,
2822         GPUVertBuf **r_vbo)
2823 {
2824         BLI_assert(rdata->types & (MR_DATATYPE_VERT | MR_DATATYPE_LOOPTRI | MR_DATATYPE_LOOP | MR_DATATYPE_POLY));
2825
2826         if (*r_vbo == NULL) {
2827                 *r_vbo = GPU_vertbuf_create(GPU_USAGE_STATIC);
2828                 mesh_create_pos_and_nor_tess(rdata, *r_vbo, use_hide);
2829         }
2830         return *r_vbo;
2831 }
2832
2833 static GPUVertBuf *mesh_batch_cache_get_tri_pos_and_normals_edit(
2834         MeshRenderData *rdata, MeshBatchCache *cache, bool use_hide)
2835 {
2836         return mesh_batch_cache_get_tri_pos_and_normals_ex(
2837                 rdata, use_hide,
2838                 use_hide ? &cache->pos_with_normals_visible_only_edit : &cache->pos_with_normals_edit);
2839 }
2840
2841 static GPUVertBuf *mesh_batch_cache_get_tri_pos_and_normals_final(
2842         MeshRenderData *rdata, MeshBatchCache *cache, bool use_hide)
2843 {
2844         return mesh_batch_cache_get_tri_pos_and_normals_ex(
2845                 rdata, use_hide,
2846                 use_hide ? &cache->pos_with_normals_visible_only : &cache->pos_with_normals);
2847 }
2848
2849 /* DEPRECATED Need to be ported */
2850 static GPUVertBuf *mesh_batch_cache_get_facedot_pos_with_normals_and_flag(
2851         MeshRenderData *rdata, MeshBatchCache *cache)
2852 {
2853         BLI_assert(rdata->types & (MR_DATATYPE_VERT | MR_DATATYPE_LOOP | MR_DATATYPE_POLY));
2854
2855         if (cache->edit.pos_nor_data_facedots == NULL) {
2856                 cache->edit.pos_nor_data_facedots = GPU_vertbuf_create(GPU_USAGE_STATIC);
2857                 mesh_create_edit_facedots(rdata, cache->edit.pos_nor_data_facedots);
2858         }
2859
2860         return cache->edit.pos_nor_data_facedots;
2861 }
2862
2863 static GPUVertBuf *mesh_batch_cache_get_edges_visible(
2864         MeshRenderData *rdata, MeshBatchCache *cache)
2865 {
2866         BLI_assert(rdata->types & (MR_DATATYPE_VERT | MR_DATATYPE_EDGE));
2867
2868         if (cache->ed_edge_pos == NULL) {
2869                 static GPUVertFormat format = { 0 };
2870                 static struct { uint pos, data; } attr_id;
2871                 if (format.attr_len == 0) {
2872                         attr_id.pos = GPU_vertformat_attr_add(&format, "pos", GPU_COMP_F32, 3, GPU_FETCH_FLOAT);
2873                 }
2874
2875                 const int vbo_len_capacity = mesh_render_data_edges_len_get_maybe_mapped(rdata) * 2;
2876                 int vidx = 0;
2877
2878                 GPUVertBuf *vbo = cache->ed_edge_pos = GPU_vertbuf_create_with_format(&format);
2879                 GPU_vertbuf_data_alloc(vbo, vbo_len_capacity);
2880
2881                 if (rdata->mapped.use == false) {
2882                         if (rdata->edit_bmesh) {
2883                                 BMesh *bm = rdata->edit_bmesh->bm;
2884                                 BMIter iter;
2885                                 BMEdge *eed;
2886
2887                                 BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
2888                                         if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
2889                                                 GPU_vertbuf_attr_set(vbo, attr_id.pos, vidx, eed->v1->co);
2890                                                 vidx += 1;
2891                                                 GPU_vertbuf_attr_set(vbo, attr_id.pos, vidx, eed->v2->co);
2892                                                 vidx += 1;
2893                                         }
2894                                 }
2895                         }
2896                         else {
2897                                 /* not yet done! */
2898                                 BLI_assert(0);
2899                         }
2900                 }
2901                 else {
2902                         BMesh *bm = rdata->edit_bmesh->bm;
2903                         const MVert *mvert = rdata->mapped.me_cage->mvert;
2904                         const MEdge *medge = rdata->mapped.me_cage->medge;
2905                         const int *e_origindex = rdata->mapped.e_origindex;
2906                         for (int i = 0; i < rdata->mapped.edge_len; i++) {
2907                                 const int e_orig = e_origindex[i];
2908                                 if (e_orig != ORIGINDEX_NONE) {
2909                                         BMEdge *eed = BM_edge_at_index(bm, e_orig);
2910                                         if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
2911                                                 const MEdge *ed = &medge[i];
2912                                                 GPU_vertbuf_attr_set(vbo, attr_id.pos, vidx, mvert[ed->v1].co);
2913                                                 vidx += 1;