Cleanup: commas at the end of enums
[blender.git] / source / blender / blenkernel / intern / subsurf_ccg.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) 2005 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/subsurf_ccg.c
29  *  \ingroup bke
30  */
31
32 #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
33 #  ifdef __GNUC__
34 #    pragma GCC diagnostic ignored "-Wvla"
35 #  endif
36 #  define USE_DYNSIZE
37 #endif
38
39 #include <stdlib.h>
40 #include <string.h>
41 #include <stdio.h>
42 #include <math.h>
43 #include <float.h>
44
45 #include "atomic_ops.h"
46
47 #include "MEM_guardedalloc.h"
48
49 #include "DNA_mesh_types.h"
50 #include "DNA_meshdata_types.h"
51 #include "DNA_modifier_types.h"
52 #include "DNA_object_types.h"
53 #include "DNA_scene_types.h"
54
55 #include "BLI_utildefines.h"
56 #include "BLI_bitmap.h"
57 #include "BLI_blenlib.h"
58 #include "BLI_edgehash.h"
59 #include "BLI_math.h"
60 #include "BLI_memarena.h"
61 #include "BLI_task.h"
62 #include "BLI_threads.h"
63
64 #include "BKE_pbvh.h"
65 #include "BKE_ccg.h"
66 #include "BKE_cdderivedmesh.h"
67 #include "BKE_global.h"
68 #include "BKE_mesh.h"
69 #include "BKE_mesh_mapping.h"
70 #include "BKE_modifier.h"
71 #include "BKE_multires.h"
72 #include "BKE_object.h"
73 #include "BKE_paint.h"
74 #include "BKE_scene.h"
75 #include "BKE_subsurf.h"
76
77 #ifndef USE_DYNSIZE
78 #  include "BLI_array.h"
79 #endif
80
81 #include "CCGSubSurf.h"
82
83 #ifdef WITH_OPENSUBDIV
84 #  include "opensubdiv_capi.h"
85 #endif
86
87 /* assumes MLoop's are laid out 4 for each poly, in order */
88 #define USE_LOOP_LAYOUT_FAST
89
90 static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
91                                          int drawInteriorEdges,
92                                          int useSubsurfUv,
93                                          DerivedMesh *dm,
94                                          bool use_gpu_backend);
95 static int ccgDM_use_grid_pbvh(CCGDerivedMesh *ccgdm);
96
97 ///
98
99 static void *arena_alloc(CCGAllocatorHDL a, int numBytes)
100 {
101         return BLI_memarena_alloc(a, numBytes);
102 }
103
104 static void *arena_realloc(CCGAllocatorHDL a, void *ptr, int newSize, int oldSize)
105 {
106         void *p2 = BLI_memarena_alloc(a, newSize);
107         if (ptr) {
108                 memcpy(p2, ptr, oldSize);
109         }
110         return p2;
111 }
112
113 static void arena_free(CCGAllocatorHDL UNUSED(a), void *UNUSED(ptr))
114 {
115         /* do nothing */
116 }
117
118 static void arena_release(CCGAllocatorHDL a)
119 {
120         BLI_memarena_free(a);
121 }
122
123 typedef enum {
124         CCG_USE_AGING = 1,
125         CCG_USE_ARENA = 2,
126         CCG_CALC_NORMALS = 4,
127         /* add an extra four bytes for a mask layer */
128         CCG_ALLOC_MASK = 8,
129         CCG_SIMPLE_SUBDIV = 16,
130 } CCGFlags;
131
132 static CCGSubSurf *_getSubSurf(CCGSubSurf *prevSS, int subdivLevels,
133                                int numLayers, CCGFlags flags)
134 {
135         CCGMeshIFC ifc;
136         CCGSubSurf *ccgSS;
137         int useAging = !!(flags & CCG_USE_AGING);
138         int useArena = flags & CCG_USE_ARENA;
139         int normalOffset = 0;
140
141         /* (subdivLevels == 0) is not allowed */
142         subdivLevels = MAX2(subdivLevels, 1);
143
144         if (prevSS) {
145                 int oldUseAging;
146
147                 ccgSubSurf_getUseAgeCounts(prevSS, &oldUseAging, NULL, NULL, NULL);
148
149                 if ((oldUseAging != useAging) ||
150                     (ccgSubSurf_getSimpleSubdiv(prevSS) != !!(flags & CCG_SIMPLE_SUBDIV)))
151                 {
152                         ccgSubSurf_free(prevSS);
153                 }
154                 else {
155                         ccgSubSurf_setSubdivisionLevels(prevSS, subdivLevels);
156
157                         return prevSS;
158                 }
159         }
160
161         if (useAging) {
162                 ifc.vertUserSize = ifc.edgeUserSize = ifc.faceUserSize = 12;
163         }
164         else {
165                 ifc.vertUserSize = ifc.edgeUserSize = ifc.faceUserSize = 8;
166         }
167         ifc.numLayers = numLayers;
168         ifc.vertDataSize = sizeof(float) * numLayers;
169         normalOffset += sizeof(float) * numLayers;
170         if (flags & CCG_CALC_NORMALS)
171                 ifc.vertDataSize += sizeof(float) * 3;
172         if (flags & CCG_ALLOC_MASK)
173                 ifc.vertDataSize += sizeof(float);
174         ifc.simpleSubdiv = !!(flags & CCG_SIMPLE_SUBDIV);
175
176         if (useArena) {
177                 CCGAllocatorIFC allocatorIFC;
178                 CCGAllocatorHDL allocator = BLI_memarena_new(MEM_SIZE_OPTIMAL(1 << 16), "subsurf arena");
179
180                 allocatorIFC.alloc = arena_alloc;
181                 allocatorIFC.realloc = arena_realloc;
182                 allocatorIFC.free = arena_free;
183                 allocatorIFC.release = arena_release;
184
185                 ccgSS = ccgSubSurf_new(&ifc, subdivLevels, &allocatorIFC, allocator);
186         }
187         else {
188                 ccgSS = ccgSubSurf_new(&ifc, subdivLevels, NULL, NULL);
189         }
190
191         if (useAging) {
192                 ccgSubSurf_setUseAgeCounts(ccgSS, 1, 8, 8, 8);
193         }
194
195         if (flags & CCG_ALLOC_MASK) {
196                 normalOffset += sizeof(float);
197                 /* mask is allocated after regular layers */
198                 ccgSubSurf_setAllocMask(ccgSS, 1, sizeof(float) * numLayers);
199         }
200
201         if (flags & CCG_CALC_NORMALS)
202                 ccgSubSurf_setCalcVertexNormals(ccgSS, 1, normalOffset);
203         else
204                 ccgSubSurf_setCalcVertexNormals(ccgSS, 0, 0);
205
206         return ccgSS;
207 }
208
209 static int getEdgeIndex(CCGSubSurf *ss, CCGEdge *e, int x, int edgeSize)
210 {
211         CCGVert *v0 = ccgSubSurf_getEdgeVert0(e);
212         CCGVert *v1 = ccgSubSurf_getEdgeVert1(e);
213         int v0idx = *((int *) ccgSubSurf_getVertUserData(ss, v0));
214         int v1idx = *((int *) ccgSubSurf_getVertUserData(ss, v1));
215         int edgeBase = *((int *) ccgSubSurf_getEdgeUserData(ss, e));
216
217         if (x == 0) {
218                 return v0idx;
219         }
220         else if (x == edgeSize - 1) {
221                 return v1idx;
222         }
223         else {
224                 return edgeBase + x - 1;
225         }
226 }
227
228 static int getFaceIndex(CCGSubSurf *ss, CCGFace *f, int S, int x, int y, int edgeSize, int gridSize)
229 {
230         int faceBase = *((int *) ccgSubSurf_getFaceUserData(ss, f));
231         int numVerts = ccgSubSurf_getFaceNumVerts(f);
232
233         if (x == gridSize - 1 && y == gridSize - 1) {
234                 CCGVert *v = ccgSubSurf_getFaceVert(f, S);
235                 return *((int *) ccgSubSurf_getVertUserData(ss, v));
236         }
237         else if (x == gridSize - 1) {
238                 CCGVert *v = ccgSubSurf_getFaceVert(f, S);
239                 CCGEdge *e = ccgSubSurf_getFaceEdge(f, S);
240                 int edgeBase = *((int *) ccgSubSurf_getEdgeUserData(ss, e));
241                 if (v == ccgSubSurf_getEdgeVert0(e)) {
242                         return edgeBase + (gridSize - 1 - y) - 1;
243                 }
244                 else {
245                         return edgeBase + (edgeSize - 2 - 1) - ((gridSize - 1 - y) - 1);
246                 }
247         }
248         else if (y == gridSize - 1) {
249                 CCGVert *v = ccgSubSurf_getFaceVert(f, S);
250                 CCGEdge *e = ccgSubSurf_getFaceEdge(f, (S + numVerts - 1) % numVerts);
251                 int edgeBase = *((int *) ccgSubSurf_getEdgeUserData(ss, e));
252                 if (v == ccgSubSurf_getEdgeVert0(e)) {
253                         return edgeBase + (gridSize - 1 - x) - 1;
254                 }
255                 else {
256                         return edgeBase + (edgeSize - 2 - 1) - ((gridSize - 1 - x) - 1);
257                 }
258         }
259         else if (x == 0 && y == 0) {
260                 return faceBase;
261         }
262         else if (x == 0) {
263                 S = (S + numVerts - 1) % numVerts;
264                 return faceBase + 1 + (gridSize - 2) * S + (y - 1);
265         }
266         else if (y == 0) {
267                 return faceBase + 1 + (gridSize - 2) * S + (x - 1);
268         }
269         else {
270                 return faceBase + 1 + (gridSize - 2) * numVerts + S * (gridSize - 2) * (gridSize - 2) + (y - 1) * (gridSize - 2) + (x - 1);
271         }
272 }
273
274 static void get_face_uv_map_vert(UvVertMap *vmap, struct MPoly *mpoly, struct MLoop *ml, int fi, CCGVertHDL *fverts)
275 {
276         UvMapVert *v, *nv;
277         int j, nverts = mpoly[fi].totloop;
278
279         for (j = 0; j < nverts; j++) {
280                 for (nv = v = BKE_mesh_uv_vert_map_get_vert(vmap, ml[j].v); v; v = v->next) {
281                         if (v->separate)
282                                 nv = v;
283                         if (v->poly_index == fi)
284                                 break;
285                 }
286
287                 fverts[j] = POINTER_FROM_UINT(mpoly[nv->poly_index].loopstart + nv->loop_of_poly_index);
288         }
289 }
290
291 static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm, MLoopUV *mloopuv)
292 {
293         MPoly *mpoly = dm->getPolyArray(dm);
294         MLoop *mloop = dm->getLoopArray(dm);
295         int totvert = dm->getNumVerts(dm);
296         int totface = dm->getNumPolys(dm);
297         int i, seam;
298         UvMapVert *v;
299         UvVertMap *vmap;
300         float limit[2];
301 #ifndef USE_DYNSIZE
302         CCGVertHDL *fverts = NULL;
303         BLI_array_declare(fverts);
304 #endif
305         EdgeSet *eset;
306         float uv[3] = {0.0f, 0.0f, 0.0f}; /* only first 2 values are written into */
307
308         limit[0] = limit[1] = STD_UV_CONNECT_LIMIT;
309         /* previous behavior here is without accounting for winding, however this causes stretching in
310          * UV map in really simple cases with mirror + subsurf, see second part of T44530. Also, initially
311          * intention is to treat merged vertices from mirror modifier as seams.
312          * This fixes a very old regression (2.49 was correct here) */
313         vmap = BKE_mesh_uv_vert_map_create(mpoly, mloop, mloopuv, totface, totvert, limit, false, true);
314         if (!vmap)
315                 return 0;
316
317         ccgSubSurf_initFullSync(ss);
318
319         /* create vertices */
320         for (i = 0; i < totvert; i++) {
321                 if (!BKE_mesh_uv_vert_map_get_vert(vmap, i))
322                         continue;
323
324                 for (v = BKE_mesh_uv_vert_map_get_vert(vmap, i)->next; v; v = v->next)
325                         if (v->separate)
326                                 break;
327
328                 seam = (v != NULL);
329
330                 for (v = BKE_mesh_uv_vert_map_get_vert(vmap, i); v; v = v->next) {
331                         if (v->separate) {
332                                 CCGVert *ssv;
333                                 int loopid = mpoly[v->poly_index].loopstart + v->loop_of_poly_index;
334                                 CCGVertHDL vhdl = POINTER_FROM_INT(loopid);
335
336                                 copy_v2_v2(uv, mloopuv[loopid].uv);
337
338                                 ccgSubSurf_syncVert(ss, vhdl, uv, seam, &ssv);
339                         }
340                 }
341         }
342
343         /* create edges */
344         eset = BLI_edgeset_new_ex(__func__, BLI_EDGEHASH_SIZE_GUESS_FROM_POLYS(totface));
345
346         for (i = 0; i < totface; i++) {
347                 MPoly *mp = &mpoly[i];
348                 int nverts = mp->totloop;
349                 int j, j_next;
350                 CCGFace *origf = ccgSubSurf_getFace(origss, POINTER_FROM_INT(i));
351                 /* unsigned int *fv = &mp->v1; */
352                 MLoop *ml = mloop + mp->loopstart;
353
354 #ifdef USE_DYNSIZE
355                 CCGVertHDL fverts[nverts];
356 #else
357                 BLI_array_clear(fverts);
358                 BLI_array_grow_items(fverts, nverts);
359 #endif
360
361                 get_face_uv_map_vert(vmap, mpoly, ml, i, fverts);
362
363                 for (j = 0, j_next = nverts - 1; j < nverts; j_next = j++) {
364                         unsigned int v0 = POINTER_AS_UINT(fverts[j_next]);
365                         unsigned int v1 = POINTER_AS_UINT(fverts[j]);
366
367                         if (BLI_edgeset_add(eset, v0, v1)) {
368                                 CCGEdge *e, *orige = ccgSubSurf_getFaceEdge(origf, j_next);
369                                 CCGEdgeHDL ehdl = POINTER_FROM_INT(mp->loopstart + j_next);
370                                 float crease = ccgSubSurf_getEdgeCrease(orige);
371
372                                 ccgSubSurf_syncEdge(ss, ehdl, fverts[j_next], fverts[j], crease, &e);
373                         }
374                 }
375         }
376
377         BLI_edgeset_free(eset);
378
379         /* create faces */
380         for (i = 0; i < totface; i++) {
381                 MPoly *mp = &mpoly[i];
382                 MLoop *ml = &mloop[mp->loopstart];
383                 int nverts = mp->totloop;
384                 CCGFace *f;
385
386 #ifdef USE_DYNSIZE
387                 CCGVertHDL fverts[nverts];
388 #else
389                 BLI_array_clear(fverts);
390                 BLI_array_grow_items(fverts, nverts);
391 #endif
392
393                 get_face_uv_map_vert(vmap, mpoly, ml, i, fverts);
394                 ccgSubSurf_syncFace(ss, POINTER_FROM_INT(i), nverts, fverts, &f);
395         }
396
397 #ifndef USE_DYNSIZE
398         BLI_array_free(fverts);
399 #endif
400
401         BKE_mesh_uv_vert_map_free(vmap);
402         ccgSubSurf_processSync(ss);
403
404         return 1;
405 }
406
407 #ifdef WITH_OPENSUBDIV
408 static void UNUSED_FUNCTION(set_subsurf_osd_ccg_uv)(CCGSubSurf *ss,
409                                                     DerivedMesh *dm,
410                                                     DerivedMesh *result,
411                                                     int layer_index)
412 {
413         CCGFace **faceMap;
414         MTFace *tf;
415         MLoopUV *mluv;
416         CCGFaceIterator fi;
417         int index, gridSize, gridFaces, totface, x, y, S;
418         MLoopUV *dmloopuv = CustomData_get_layer_n(&dm->loopData, CD_MLOOPUV, layer_index);
419         /* need to update both CD_MTFACE & CD_MLOOPUV, hrmf, we could get away with
420          * just tface except applying the modifier then looses subsurf UV */
421         MTFace *tface = CustomData_get_layer_n(&result->faceData, CD_MTFACE, layer_index);
422         MLoopUV *mloopuv = CustomData_get_layer_n(&result->loopData, CD_MLOOPUV, layer_index);
423
424         if (dmloopuv == NULL || (tface == NULL && mloopuv == NULL)) {
425                 return;
426         }
427
428         ccgSubSurf_evaluatorSetFVarUV(ss, dm, layer_index);
429
430         /* get some info from CCGSubSurf */
431         totface = ccgSubSurf_getNumFaces(ss);
432         gridSize = ccgSubSurf_getGridSize(ss);
433         gridFaces = gridSize - 1;
434
435         /* make a map from original faces to CCGFaces */
436         faceMap = MEM_mallocN(totface * sizeof(*faceMap), "facemapuv");
437         for (ccgSubSurf_initFaceIterator(ss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
438                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
439                 faceMap[POINTER_AS_INT(ccgSubSurf_getFaceFaceHandle(f))] = f;
440         }
441
442         /* load coordinates from uvss into tface */
443         tf = tface;
444         mluv = mloopuv;
445         for (index = 0; index < totface; index++) {
446                 CCGFace *f = faceMap[index];
447                 int numVerts = ccgSubSurf_getFaceNumVerts(f);
448                 for (S = 0; S < numVerts; S++) {
449                         for (y = 0; y < gridFaces; y++) {
450                                 for (x = 0; x < gridFaces; x++) {
451                                         const int delta[4][2] = {{0, 0},
452                                                                  {0, 1},
453                                                                  {1, 1},
454                                                                  {1, 0}};
455                                         float uv[4][2];
456                                         int i;
457                                         for (i = 0; i < 4; i++) {
458                                                 const int dx = delta[i][0],
459                                                           dy = delta[i][1];
460                                                 const float grid_u = ((float)(x + dx)) / (gridSize - 1),
461                                                             grid_v = ((float)(y + dy)) / (gridSize - 1);
462                                                 ccgSubSurf_evaluatorFVarUV(ss,
463                                                                            index,
464                                                                            S,
465                                                                            grid_u, grid_v,
466                                                                            uv[i]);
467                                         }
468                                         if (tf) {
469                                                 copy_v2_v2(tf->uv[0], uv[0]);
470                                                 copy_v2_v2(tf->uv[1], uv[1]);
471                                                 copy_v2_v2(tf->uv[2], uv[2]);
472                                                 copy_v2_v2(tf->uv[3], uv[3]);
473                                                 tf++;
474                                         }
475                                         if (mluv) {
476                                                 copy_v2_v2(mluv[0].uv, uv[0]);
477                                                 copy_v2_v2(mluv[1].uv, uv[1]);
478                                                 copy_v2_v2(mluv[2].uv, uv[2]);
479                                                 copy_v2_v2(mluv[3].uv, uv[3]);
480                                                 mluv += 4;
481                                         }
482                                 }
483                         }
484                 }
485         }
486         MEM_freeN(faceMap);
487 }
488 #endif  /* WITH_OPENSUBDIV */
489
490 static void set_subsurf_legacy_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh *result, int n)
491 {
492         CCGSubSurf *uvss;
493         CCGFace **faceMap;
494         MTFace *tf;
495         MLoopUV *mluv;
496         CCGFaceIterator fi;
497         int index, gridSize, gridFaces, /*edgeSize,*/ totface, x, y, S;
498         MLoopUV *dmloopuv = CustomData_get_layer_n(&dm->loopData, CD_MLOOPUV, n);
499         /* need to update both CD_MTFACE & CD_MLOOPUV, hrmf, we could get away with
500          * just tface except applying the modifier then looses subsurf UV */
501         MTFace *tface = CustomData_get_layer_n(&result->faceData, CD_MTFACE, n);
502         MLoopUV *mloopuv = CustomData_get_layer_n(&result->loopData, CD_MLOOPUV, n);
503
504         if (!dmloopuv || (!tface && !mloopuv))
505                 return;
506
507         /* create a CCGSubSurf from uv's */
508         uvss = _getSubSurf(NULL, ccgSubSurf_getSubdivisionLevels(ss), 2, CCG_USE_ARENA);
509
510         if (!ss_sync_from_uv(uvss, ss, dm, dmloopuv)) {
511                 ccgSubSurf_free(uvss);
512                 return;
513         }
514
515         /* get some info from CCGSubSurf */
516         totface = ccgSubSurf_getNumFaces(uvss);
517         /* edgeSize = ccgSubSurf_getEdgeSize(uvss); */ /*UNUSED*/
518         gridSize = ccgSubSurf_getGridSize(uvss);
519         gridFaces = gridSize - 1;
520
521         /* make a map from original faces to CCGFaces */
522         faceMap = MEM_mallocN(totface * sizeof(*faceMap), "facemapuv");
523         for (ccgSubSurf_initFaceIterator(uvss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
524                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
525                 faceMap[POINTER_AS_INT(ccgSubSurf_getFaceFaceHandle(f))] = f;
526         }
527
528         /* load coordinates from uvss into tface */
529         tf = tface;
530         mluv = mloopuv;
531
532         for (index = 0; index < totface; index++) {
533                 CCGFace *f = faceMap[index];
534                 int numVerts = ccgSubSurf_getFaceNumVerts(f);
535
536                 for (S = 0; S < numVerts; S++) {
537                         float (*faceGridData)[2] = ccgSubSurf_getFaceGridDataArray(uvss, f, S);
538
539                         for (y = 0; y < gridFaces; y++) {
540                                 for (x = 0; x < gridFaces; x++) {
541                                         float *a = faceGridData[(y + 0) * gridSize + x + 0];
542                                         float *b = faceGridData[(y + 0) * gridSize + x + 1];
543                                         float *c = faceGridData[(y + 1) * gridSize + x + 1];
544                                         float *d = faceGridData[(y + 1) * gridSize + x + 0];
545
546                                         if (tf) {
547                                                 copy_v2_v2(tf->uv[0], a);
548                                                 copy_v2_v2(tf->uv[1], d);
549                                                 copy_v2_v2(tf->uv[2], c);
550                                                 copy_v2_v2(tf->uv[3], b);
551                                                 tf++;
552                                         }
553
554                                         if (mluv) {
555                                                 copy_v2_v2(mluv[0].uv, a);
556                                                 copy_v2_v2(mluv[1].uv, d);
557                                                 copy_v2_v2(mluv[2].uv, c);
558                                                 copy_v2_v2(mluv[3].uv, b);
559                                                 mluv += 4;
560                                         }
561
562                                 }
563                         }
564                 }
565         }
566
567         ccgSubSurf_free(uvss);
568         MEM_freeN(faceMap);
569 }
570
571 static void set_subsurf_uv(CCGSubSurf *ss,
572                            DerivedMesh *dm,
573                            DerivedMesh *result,
574                            int layer_index)
575 {
576 #ifdef WITH_OPENSUBDIV
577         if (!ccgSubSurf_needGrids(ss)) {
578                 /* GPU backend is used, no need to evaluate UVs on CPU. */
579                 /* TODO(sergey): Think of how to support edit mode of UVs. */
580         }
581         else
582 #endif
583         {
584                 set_subsurf_legacy_uv(ss, dm, result, layer_index);
585         }
586 }
587
588 /* face weighting */
589 typedef struct FaceVertWeightEntry {
590         FaceVertWeight *weight;
591         float *w;
592         int valid;
593 } FaceVertWeightEntry;
594
595 typedef struct WeightTable {
596         FaceVertWeightEntry *weight_table;
597         int len;
598 } WeightTable;
599
600 static float *get_ss_weights(WeightTable *wtable, int gridCuts, int faceLen)
601 {
602         int x, y, i, j;
603         float *w, w1, w2, w4, fac, fac2, fx, fy;
604
605         if (wtable->len <= faceLen) {
606                 void *tmp = MEM_callocN(sizeof(FaceVertWeightEntry) * (faceLen + 1), "weight table alloc 2");
607
608                 if (wtable->len) {
609                         memcpy(tmp, wtable->weight_table, sizeof(FaceVertWeightEntry) * wtable->len);
610                         MEM_freeN(wtable->weight_table);
611                 }
612
613                 wtable->weight_table = tmp;
614                 wtable->len = faceLen + 1;
615         }
616
617         if (!wtable->weight_table[faceLen].valid) {
618                 wtable->weight_table[faceLen].valid = 1;
619                 wtable->weight_table[faceLen].w = w = MEM_callocN(sizeof(float) * faceLen * faceLen * (gridCuts + 2) * (gridCuts + 2), "weight table alloc");
620                 fac = 1.0f / (float)faceLen;
621
622                 for (i = 0; i < faceLen; i++) {
623                         for (x = 0; x < gridCuts + 2; x++) {
624                                 for (y = 0; y < gridCuts + 2; y++) {
625                                         fx = 0.5f - (float)x / (float)(gridCuts + 1) / 2.0f;
626                                         fy = 0.5f - (float)y / (float)(gridCuts + 1) / 2.0f;
627
628                                         fac2 = faceLen - 4;
629                                         w1 = (1.0f - fx) * (1.0f - fy) + (-fac2 * fx * fy * fac);
630                                         w2 = (1.0f - fx + fac2 * fx * -fac) * (fy);
631                                         w4 = (fx) * (1.0f - fy + -fac2 * fy * fac);
632
633                                         /* these values aren't used for tri's and cause divide by zero */
634                                         if (faceLen > 3) {
635                                                 fac2 = 1.0f - (w1 + w2 + w4);
636                                                 fac2 = fac2 / (float)(faceLen - 3);
637                                                 for (j = 0; j < faceLen; j++) {
638                                                         w[j] = fac2;
639                                                 }
640                                         }
641
642                                         w[i] = w1;
643                                         w[(i - 1 + faceLen) % faceLen] = w2;
644                                         w[(i + 1) % faceLen] = w4;
645
646                                         w += faceLen;
647                                 }
648                         }
649                 }
650         }
651
652         return wtable->weight_table[faceLen].w;
653 }
654
655 static void free_ss_weights(WeightTable *wtable)
656 {
657         int i;
658
659         for (i = 0; i < wtable->len; i++) {
660                 if (wtable->weight_table[i].valid)
661                         MEM_freeN(wtable->weight_table[i].w);
662         }
663
664         if (wtable->weight_table)
665                 MEM_freeN(wtable->weight_table);
666 }
667
668 static void ss_sync_ccg_from_derivedmesh(CCGSubSurf *ss,
669                                          DerivedMesh *dm,
670                                          float (*vertexCos)[3],
671                                          int useFlatSubdiv)
672 {
673         float creaseFactor = (float) ccgSubSurf_getSubdivisionLevels(ss);
674 #ifndef USE_DYNSIZE
675         CCGVertHDL *fVerts = NULL;
676         BLI_array_declare(fVerts);
677 #endif
678         MVert *mvert = dm->getVertArray(dm);
679         MEdge *medge = dm->getEdgeArray(dm);
680         /* MFace *mface = dm->getTessFaceArray(dm); */ /* UNUSED */
681         MVert *mv;
682         MEdge *me;
683         MLoop *mloop = dm->getLoopArray(dm), *ml;
684         MPoly *mpoly = dm->getPolyArray(dm), *mp;
685         /*MFace *mf;*/ /*UNUSED*/
686         int totvert = dm->getNumVerts(dm);
687         int totedge = dm->getNumEdges(dm);
688         /*int totface = dm->getNumTessFaces(dm);*/ /*UNUSED*/
689         /*int totpoly = dm->getNumFaces(dm);*/ /*UNUSED*/
690         int i, j;
691         int *index;
692
693         ccgSubSurf_initFullSync(ss);
694
695         mv = mvert;
696         index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
697         for (i = 0; i < totvert; i++, mv++) {
698                 CCGVert *v;
699
700                 if (vertexCos) {
701                         ccgSubSurf_syncVert(ss, POINTER_FROM_INT(i), vertexCos[i], 0, &v);
702                 }
703                 else {
704                         ccgSubSurf_syncVert(ss, POINTER_FROM_INT(i), mv->co, 0, &v);
705                 }
706
707                 ((int *)ccgSubSurf_getVertUserData(ss, v))[1] = (index) ? *index++ : i;
708         }
709
710         me = medge;
711         index = (int *)dm->getEdgeDataArray(dm, CD_ORIGINDEX);
712         for (i = 0; i < totedge; i++, me++) {
713                 CCGEdge *e;
714                 float crease;
715
716                 crease = useFlatSubdiv ? creaseFactor :
717                          me->crease * creaseFactor / 255.0f;
718
719                 ccgSubSurf_syncEdge(ss, POINTER_FROM_INT(i), POINTER_FROM_UINT(me->v1),
720                                     POINTER_FROM_UINT(me->v2), crease, &e);
721
722                 ((int *)ccgSubSurf_getEdgeUserData(ss, e))[1] = (index) ? *index++ : i;
723         }
724
725         mp = mpoly;
726         index = (int *)dm->getPolyDataArray(dm, CD_ORIGINDEX);
727         for (i = 0; i < dm->numPolyData; i++, mp++) {
728                 CCGFace *f;
729
730 #ifdef USE_DYNSIZE
731                 CCGVertHDL fVerts[mp->totloop];
732 #else
733                 BLI_array_clear(fVerts);
734                 BLI_array_grow_items(fVerts, mp->totloop);
735 #endif
736
737                 ml = mloop + mp->loopstart;
738                 for (j = 0; j < mp->totloop; j++, ml++) {
739                         fVerts[j] = POINTER_FROM_UINT(ml->v);
740                 }
741
742                 /* this is very bad, means mesh is internally inconsistent.
743                  * it is not really possible to continue without modifying
744                  * other parts of code significantly to handle missing faces.
745                  * since this really shouldn't even be possible we just bail.*/
746                 if (ccgSubSurf_syncFace(ss, POINTER_FROM_INT(i), mp->totloop,
747                                         fVerts, &f) == eCCGError_InvalidValue)
748                 {
749                         static int hasGivenError = 0;
750
751                         if (!hasGivenError) {
752                                 //XXX error("Unrecoverable error in SubSurf calculation,"
753                                 //      " mesh is inconsistent.");
754
755                                 hasGivenError = 1;
756                         }
757
758                         return;
759                 }
760
761                 ((int *)ccgSubSurf_getFaceUserData(ss, f))[1] = (index) ? *index++ : i;
762         }
763
764         ccgSubSurf_processSync(ss);
765
766 #ifndef USE_DYNSIZE
767         BLI_array_free(fVerts);
768 #endif
769 }
770
771 #ifdef WITH_OPENSUBDIV
772 static void ss_sync_osd_from_derivedmesh(CCGSubSurf *ss,
773                                          DerivedMesh *dm)
774 {
775         ccgSubSurf_initFullSync(ss);
776         ccgSubSurf_prepareTopologyRefiner(ss, dm);
777         ccgSubSurf_processSync(ss);
778 }
779 #endif  /* WITH_OPENSUBDIV */
780
781 static void ss_sync_from_derivedmesh(CCGSubSurf *ss,
782                                      DerivedMesh *dm,
783                                      float (*vertexCos)[3],
784                                      int use_flat_subdiv,
785                                      bool use_subdiv_uvs)
786 {
787 #ifndef WITH_OPENSUBDIV
788         UNUSED_VARS(use_subdiv_uvs);
789 #endif
790
791 #ifdef WITH_OPENSUBDIV
792         /* Reset all related descriptors if actual mesh topology changed or if
793          * other evaluation-related settings changed.
794          */
795         if (!ccgSubSurf_needGrids(ss)) {
796                 /* TODO(sergey): Use vertex coordinates and flat subdiv flag. */
797                 ccgSubSurf__sync_subdivUvs(ss, use_subdiv_uvs);
798                 ccgSubSurf_checkTopologyChanged(ss, dm);
799                 ss_sync_osd_from_derivedmesh(ss, dm);
800         }
801         else
802 #endif
803         {
804                 ss_sync_ccg_from_derivedmesh(ss, dm, vertexCos, use_flat_subdiv);
805         }
806 }
807
808 /***/
809
810 static int ccgDM_getVertMapIndex(CCGSubSurf *ss, CCGVert *v)
811 {
812         return ((int *) ccgSubSurf_getVertUserData(ss, v))[1];
813 }
814
815 static int ccgDM_getEdgeMapIndex(CCGSubSurf *ss, CCGEdge *e)
816 {
817         return ((int *) ccgSubSurf_getEdgeUserData(ss, e))[1];
818 }
819
820 static int ccgDM_getFaceMapIndex(CCGSubSurf *ss, CCGFace *f)
821 {
822         return ((int *) ccgSubSurf_getFaceUserData(ss, f))[1];
823 }
824
825 static void minmax_v3_v3v3(const float vec[3], float min[3], float max[3])
826 {
827         if (min[0] > vec[0]) min[0] = vec[0];
828         if (min[1] > vec[1]) min[1] = vec[1];
829         if (min[2] > vec[2]) min[2] = vec[2];
830         if (max[0] < vec[0]) max[0] = vec[0];
831         if (max[1] < vec[1]) max[1] = vec[1];
832         if (max[2] < vec[2]) max[2] = vec[2];
833 }
834
835 static void ccgDM_getMinMax(DerivedMesh *dm, float r_min[3], float r_max[3])
836 {
837         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
838         CCGSubSurf *ss = ccgdm->ss;
839         CCGVertIterator vi;
840         CCGEdgeIterator ei;
841         CCGFaceIterator fi;
842         CCGKey key;
843         int i, edgeSize = ccgSubSurf_getEdgeSize(ss);
844         int gridSize = ccgSubSurf_getGridSize(ss);
845
846 #ifdef WITH_OPENSUBDIV
847         if (ccgdm->useGpuBackend) {
848                 ccgSubSurf_getMinMax(ccgdm->ss, r_min, r_max);
849                 return;
850         }
851 #endif
852
853         CCG_key_top_level(&key, ss);
854
855         if (!ccgSubSurf_getNumVerts(ss))
856                 r_min[0] = r_min[1] = r_min[2] = r_max[0] = r_max[1] = r_max[2] = 0.0;
857
858         for (ccgSubSurf_initVertIterator(ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) {
859                 CCGVert *v = ccgVertIterator_getCurrent(&vi);
860                 float *co = ccgSubSurf_getVertData(ss, v);
861
862                 minmax_v3_v3v3(co, r_min, r_max);
863         }
864
865         for (ccgSubSurf_initEdgeIterator(ss, &ei); !ccgEdgeIterator_isStopped(&ei); ccgEdgeIterator_next(&ei)) {
866                 CCGEdge *e = ccgEdgeIterator_getCurrent(&ei);
867                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
868
869                 for (i = 0; i < edgeSize; i++)
870                         minmax_v3_v3v3(CCG_elem_offset_co(&key, edgeData, i), r_min, r_max);
871         }
872
873         for (ccgSubSurf_initFaceIterator(ss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
874                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
875                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
876
877                 for (S = 0; S < numVerts; S++) {
878                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
879
880                         for (y = 0; y < gridSize; y++)
881                                 for (x = 0; x < gridSize; x++)
882                                         minmax_v3_v3v3(CCG_grid_elem_co(&key, faceGridData, x, y), r_min, r_max);
883                 }
884         }
885 }
886
887 static int ccgDM_getNumVerts(DerivedMesh *dm)
888 {
889         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
890
891         return ccgSubSurf_getNumFinalVerts(ccgdm->ss);
892 }
893
894 static int ccgDM_getNumEdges(DerivedMesh *dm)
895 {
896         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
897
898         return ccgSubSurf_getNumFinalEdges(ccgdm->ss);
899 }
900
901 static int ccgDM_getNumPolys(DerivedMesh *dm)
902 {
903         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
904
905         return ccgSubSurf_getNumFinalFaces(ccgdm->ss);
906 }
907
908 static int ccgDM_getNumTessFaces(DerivedMesh *dm)
909 {
910         return dm->numTessFaceData;
911 }
912
913 static int ccgDM_getNumLoops(DerivedMesh *dm)
914 {
915         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
916
917         /* All subsurf faces are quads */
918         return 4 * ccgSubSurf_getNumFinalFaces(ccgdm->ss);
919 }
920
921 static void ccgDM_getFinalVert(DerivedMesh *dm, int vertNum, MVert *mv)
922 {
923         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
924         CCGSubSurf *ss = ccgdm->ss;
925         CCGElem *vd;
926         CCGKey key;
927         int i;
928
929         CCG_key_top_level(&key, ss);
930         memset(mv, 0, sizeof(*mv));
931
932         if ((vertNum < ccgdm->edgeMap[0].startVert) && (ccgSubSurf_getNumFaces(ss) > 0)) {
933                 /* this vert comes from face data */
934                 int lastface = ccgSubSurf_getNumFaces(ss) - 1;
935                 CCGFace *f;
936                 int x, y, grid, numVerts;
937                 int offset;
938                 int gridSize = ccgSubSurf_getGridSize(ss);
939                 int gridSideVerts;
940                 int gridInternalVerts;
941                 int gridSideEnd;
942                 int gridInternalEnd;
943
944                 i = 0;
945                 while (i < lastface && vertNum >= ccgdm->faceMap[i + 1].startVert) {
946                         i++;
947                 }
948
949                 f = ccgdm->faceMap[i].face;
950                 numVerts = ccgSubSurf_getFaceNumVerts(f);
951
952                 gridSideVerts = gridSize - 2;
953                 gridInternalVerts = gridSideVerts * gridSideVerts;
954
955                 gridSideEnd = 1 + numVerts * gridSideVerts;
956                 gridInternalEnd = gridSideEnd + numVerts * gridInternalVerts;
957
958                 offset = vertNum - ccgdm->faceMap[i].startVert;
959                 if (offset < 1) {
960                         vd = ccgSubSurf_getFaceCenterData(f);
961                         copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
962                         normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
963                 }
964                 else if (offset < gridSideEnd) {
965                         offset -= 1;
966                         grid = offset / gridSideVerts;
967                         x = offset % gridSideVerts + 1;
968                         vd = ccgSubSurf_getFaceGridEdgeData(ss, f, grid, x);
969                         copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
970                         normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
971                 }
972                 else if (offset < gridInternalEnd) {
973                         offset -= gridSideEnd;
974                         grid = offset / gridInternalVerts;
975                         offset %= gridInternalVerts;
976                         y = offset / gridSideVerts + 1;
977                         x = offset % gridSideVerts + 1;
978                         vd = ccgSubSurf_getFaceGridData(ss, f, grid, x, y);
979                         copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
980                         normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
981                 }
982         }
983         else if ((vertNum < ccgdm->vertMap[0].startVert) && (ccgSubSurf_getNumEdges(ss) > 0)) {
984                 /* this vert comes from edge data */
985                 CCGEdge *e;
986                 int lastedge = ccgSubSurf_getNumEdges(ss) - 1;
987                 int x;
988
989                 i = 0;
990                 while (i < lastedge && vertNum >= ccgdm->edgeMap[i + 1].startVert) {
991                         i++;
992                 }
993
994                 e = ccgdm->edgeMap[i].edge;
995
996                 x = vertNum - ccgdm->edgeMap[i].startVert + 1;
997                 vd = ccgSubSurf_getEdgeData(ss, e, x);
998                 copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
999                 normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
1000         }
1001         else {
1002                 /* this vert comes from vert data */
1003                 CCGVert *v;
1004                 i = vertNum - ccgdm->vertMap[0].startVert;
1005
1006                 v = ccgdm->vertMap[i].vert;
1007                 vd = ccgSubSurf_getVertData(ss, v);
1008                 copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
1009                 normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
1010         }
1011 }
1012
1013 static void ccgDM_getFinalVertCo(DerivedMesh *dm, int vertNum, float r_co[3])
1014 {
1015         MVert mvert;
1016
1017         ccgDM_getFinalVert(dm, vertNum, &mvert);
1018         copy_v3_v3(r_co, mvert.co);
1019 }
1020
1021 static void ccgDM_getFinalVertNo(DerivedMesh *dm, int vertNum, float r_no[3])
1022 {
1023         MVert mvert;
1024
1025         ccgDM_getFinalVert(dm, vertNum, &mvert);
1026         normal_short_to_float_v3(r_no, mvert.no);
1027 }
1028
1029 static void ccgDM_getFinalEdge(DerivedMesh *dm, int edgeNum, MEdge *med)
1030 {
1031         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1032         CCGSubSurf *ss = ccgdm->ss;
1033         int i;
1034
1035         memset(med, 0, sizeof(*med));
1036
1037         if (edgeNum < ccgdm->edgeMap[0].startEdge) {
1038                 /* this edge comes from face data */
1039                 int lastface = ccgSubSurf_getNumFaces(ss) - 1;
1040                 CCGFace *f;
1041                 int x, y, grid /*, numVerts*/;
1042                 int offset;
1043                 int gridSize = ccgSubSurf_getGridSize(ss);
1044                 int edgeSize = ccgSubSurf_getEdgeSize(ss);
1045                 int gridSideEdges;
1046                 int gridInternalEdges;
1047
1048                 i = 0;
1049                 while (i < lastface && edgeNum >= ccgdm->faceMap[i + 1].startEdge) {
1050                         i++;
1051                 }
1052
1053                 f = ccgdm->faceMap[i].face;
1054                 /* numVerts = ccgSubSurf_getFaceNumVerts(f); */ /*UNUSED*/
1055
1056                 gridSideEdges = gridSize - 1;
1057                 gridInternalEdges = (gridSideEdges - 1) * gridSideEdges * 2;
1058
1059                 offset = edgeNum - ccgdm->faceMap[i].startEdge;
1060                 grid = offset / (gridSideEdges + gridInternalEdges);
1061                 offset %= (gridSideEdges + gridInternalEdges);
1062
1063                 if (offset < gridSideEdges) {
1064                         x = offset;
1065                         med->v1 = getFaceIndex(ss, f, grid, x, 0, edgeSize, gridSize);
1066                         med->v2 = getFaceIndex(ss, f, grid, x + 1, 0, edgeSize, gridSize);
1067                 }
1068                 else {
1069                         offset -= gridSideEdges;
1070                         x = (offset / 2) / gridSideEdges + 1;
1071                         y = (offset / 2) % gridSideEdges;
1072                         if (offset % 2 == 0) {
1073                                 med->v1 = getFaceIndex(ss, f, grid, x, y, edgeSize, gridSize);
1074                                 med->v2 = getFaceIndex(ss, f, grid, x, y + 1, edgeSize, gridSize);
1075                         }
1076                         else {
1077                                 med->v1 = getFaceIndex(ss, f, grid, y, x, edgeSize, gridSize);
1078                                 med->v2 = getFaceIndex(ss, f, grid, y + 1, x, edgeSize, gridSize);
1079                         }
1080                 }
1081         }
1082         else {
1083                 /* this vert comes from edge data */
1084                 CCGEdge *e;
1085                 int edgeSize = ccgSubSurf_getEdgeSize(ss);
1086                 int x;
1087                 short *edgeFlag;
1088                 unsigned int flags = 0;
1089
1090                 i = (edgeNum - ccgdm->edgeMap[0].startEdge) / (edgeSize - 1);
1091
1092                 e = ccgdm->edgeMap[i].edge;
1093
1094                 if (!ccgSubSurf_getEdgeNumFaces(e)) flags |= ME_LOOSEEDGE;
1095
1096                 x = edgeNum - ccgdm->edgeMap[i].startEdge;
1097
1098                 med->v1 = getEdgeIndex(ss, e, x, edgeSize);
1099                 med->v2 = getEdgeIndex(ss, e, x + 1, edgeSize);
1100
1101                 edgeFlag = (ccgdm->edgeFlags) ? &ccgdm->edgeFlags[i] : NULL;
1102                 if (edgeFlag)
1103                         flags |= (*edgeFlag & (ME_SEAM | ME_SHARP)) | ME_EDGEDRAW | ME_EDGERENDER;
1104                 else
1105                         flags |= ME_EDGEDRAW | ME_EDGERENDER;
1106
1107                 med->flag = flags;
1108         }
1109 }
1110
1111 static void ccgDM_getFinalFace(DerivedMesh *dm, int faceNum, MFace *mf)
1112 {
1113         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1114         CCGSubSurf *ss = ccgdm->ss;
1115         int gridSize = ccgSubSurf_getGridSize(ss);
1116         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1117         int gridSideEdges = gridSize - 1;
1118         int gridFaces = gridSideEdges * gridSideEdges;
1119         int i;
1120         CCGFace *f;
1121         /*int numVerts;*/
1122         int offset;
1123         int grid;
1124         int x, y;
1125         /*int lastface = ccgSubSurf_getNumFaces(ss) - 1;*/ /*UNUSED*/
1126         DMFlagMat *faceFlags = ccgdm->faceFlags;
1127
1128         memset(mf, 0, sizeof(*mf));
1129         if (faceNum >= ccgdm->dm.numTessFaceData)
1130                 return;
1131
1132         i = ccgdm->reverseFaceMap[faceNum];
1133
1134         f = ccgdm->faceMap[i].face;
1135         /*numVerts = ccgSubSurf_getFaceNumVerts(f);*/ /*UNUSED*/
1136
1137         offset = faceNum - ccgdm->faceMap[i].startFace;
1138         grid = offset / gridFaces;
1139         offset %= gridFaces;
1140         y = offset / gridSideEdges;
1141         x = offset % gridSideEdges;
1142
1143         mf->v1 = getFaceIndex(ss, f, grid, x + 0, y + 0, edgeSize, gridSize);
1144         mf->v2 = getFaceIndex(ss, f, grid, x + 0, y + 1, edgeSize, gridSize);
1145         mf->v3 = getFaceIndex(ss, f, grid, x + 1, y + 1, edgeSize, gridSize);
1146         mf->v4 = getFaceIndex(ss, f, grid, x + 1, y + 0, edgeSize, gridSize);
1147
1148         if (faceFlags) {
1149                 mf->flag = faceFlags[i].flag;
1150                 mf->mat_nr = faceFlags[i].mat_nr;
1151         }
1152         else {
1153                 mf->flag = ME_SMOOTH;
1154         }
1155
1156         mf->edcode = 0;
1157 }
1158
1159 /* Translate GridHidden into the ME_HIDE flag for MVerts. Assumes
1160  * vertices are in the order output by ccgDM_copyFinalVertArray. */
1161 void subsurf_copy_grid_hidden(DerivedMesh *dm, const MPoly *mpoly,
1162                               MVert *mvert, const MDisps *mdisps)
1163 {
1164         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
1165         CCGSubSurf *ss = ccgdm->ss;
1166         int level = ccgSubSurf_getSubdivisionLevels(ss);
1167         int gridSize = ccgSubSurf_getGridSize(ss);
1168         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1169         int totface = ccgSubSurf_getNumFaces(ss);
1170         int i, j, x, y;
1171
1172         for (i = 0; i < totface; i++) {
1173                 CCGFace *f = ccgdm->faceMap[i].face;
1174
1175                 for (j = 0; j < mpoly[i].totloop; j++) {
1176                         const MDisps *md = &mdisps[mpoly[i].loopstart + j];
1177                         int hidden_gridsize = BKE_ccg_gridsize(md->level);
1178                         int factor = BKE_ccg_factor(level, md->level);
1179                         BLI_bitmap *hidden = md->hidden;
1180
1181                         if (!hidden)
1182                                 continue;
1183
1184                         for (y = 0; y < gridSize; y++) {
1185                                 for (x = 0; x < gridSize; x++) {
1186                                         int vndx, offset;
1187
1188                                         vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize);
1189                                         offset = (y * factor) * hidden_gridsize + (x * factor);
1190                                         if (BLI_BITMAP_TEST(hidden, offset))
1191                                                 mvert[vndx].flag |= ME_HIDE;
1192                                 }
1193                         }
1194                 }
1195         }
1196 }
1197
1198 /* Translate GridPaintMask into vertex paint masks. Assumes vertices
1199  * are in the order output by ccgDM_copyFinalVertArray. */
1200 void subsurf_copy_grid_paint_mask(DerivedMesh *dm, const MPoly *mpoly,
1201                                   float *paint_mask,
1202                                   const GridPaintMask *grid_paint_mask)
1203 {
1204         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
1205         CCGSubSurf *ss = ccgdm->ss;
1206         int level = ccgSubSurf_getSubdivisionLevels(ss);
1207         int gridSize = ccgSubSurf_getGridSize(ss);
1208         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1209         int totface = ccgSubSurf_getNumFaces(ss);
1210         int i, j, x, y, factor, gpm_gridsize;
1211
1212         for (i = 0; i < totface; i++) {
1213                 CCGFace *f = ccgdm->faceMap[i].face;
1214                 const MPoly *p = &mpoly[i];
1215
1216                 for (j = 0; j < p->totloop; j++) {
1217                         const GridPaintMask *gpm = &grid_paint_mask[p->loopstart + j];
1218                         if (!gpm->data)
1219                                 continue;
1220
1221                         factor = BKE_ccg_factor(level, gpm->level);
1222                         gpm_gridsize = BKE_ccg_gridsize(gpm->level);
1223
1224                         for (y = 0; y < gridSize; y++) {
1225                                 for (x = 0; x < gridSize; x++) {
1226                                         int vndx, offset;
1227
1228                                         vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize);
1229                                         offset = y * factor * gpm_gridsize + x * factor;
1230                                         paint_mask[vndx] = gpm->data[offset];
1231                                 }
1232                         }
1233                 }
1234         }
1235 }
1236
1237 /* utility function */
1238 BLI_INLINE void ccgDM_to_MVert(MVert *mv, const CCGKey *key, CCGElem *elem)
1239 {
1240         copy_v3_v3(mv->co, CCG_elem_co(key, elem));
1241         normal_float_to_short_v3(mv->no, CCG_elem_no(key, elem));
1242         mv->flag = mv->bweight = 0;
1243 }
1244
1245 static void ccgDM_copyFinalVertArray(DerivedMesh *dm, MVert *mvert)
1246 {
1247         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1248         CCGSubSurf *ss = ccgdm->ss;
1249         CCGElem *vd;
1250         CCGKey key;
1251         int index;
1252         int totvert, totedge, totface;
1253         int gridSize = ccgSubSurf_getGridSize(ss);
1254         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1255         unsigned int i = 0;
1256
1257         CCG_key_top_level(&key, ss);
1258
1259         totface = ccgSubSurf_getNumFaces(ss);
1260         for (index = 0; index < totface; index++) {
1261                 CCGFace *f = ccgdm->faceMap[index].face;
1262                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1263
1264                 vd = ccgSubSurf_getFaceCenterData(f);
1265                 ccgDM_to_MVert(&mvert[i++], &key, vd);
1266
1267                 for (S = 0; S < numVerts; S++) {
1268                         for (x = 1; x < gridSize - 1; x++) {
1269                                 vd = ccgSubSurf_getFaceGridEdgeData(ss, f, S, x);
1270                                 ccgDM_to_MVert(&mvert[i++], &key, vd);
1271                         }
1272                 }
1273
1274                 for (S = 0; S < numVerts; S++) {
1275                         for (y = 1; y < gridSize - 1; y++) {
1276                                 for (x = 1; x < gridSize - 1; x++) {
1277                                         vd = ccgSubSurf_getFaceGridData(ss, f, S, x, y);
1278                                         ccgDM_to_MVert(&mvert[i++], &key, vd);
1279                                 }
1280                         }
1281                 }
1282         }
1283
1284         totedge = ccgSubSurf_getNumEdges(ss);
1285         for (index = 0; index < totedge; index++) {
1286                 CCGEdge *e = ccgdm->edgeMap[index].edge;
1287                 int x;
1288
1289                 for (x = 1; x < edgeSize - 1; x++) {
1290                         /* This gives errors with -debug-fpe
1291                          * the normals don't seem to be unit length.
1292                          * this is most likely caused by edges with no
1293                          * faces which are now zerod out, see comment in:
1294                          * ccgSubSurf__calcVertNormals(), - campbell */
1295                         vd = ccgSubSurf_getEdgeData(ss, e, x);
1296                         ccgDM_to_MVert(&mvert[i++], &key, vd);
1297                 }
1298         }
1299
1300         totvert = ccgSubSurf_getNumVerts(ss);
1301         for (index = 0; index < totvert; index++) {
1302                 CCGVert *v = ccgdm->vertMap[index].vert;
1303
1304                 vd = ccgSubSurf_getVertData(ss, v);
1305                 ccgDM_to_MVert(&mvert[i++], &key, vd);
1306         }
1307 }
1308
1309
1310 /* utility function */
1311 BLI_INLINE void ccgDM_to_MEdge(MEdge *med, const int v1, const int v2, const short flag)
1312 {
1313         med->v1 = v1;
1314         med->v2 = v2;
1315         med->crease = med->bweight = 0;
1316         med->flag = flag;
1317 }
1318
1319 static void ccgDM_copyFinalEdgeArray(DerivedMesh *dm, MEdge *medge)
1320 {
1321         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1322         CCGSubSurf *ss = ccgdm->ss;
1323         int index;
1324         int totedge, totface;
1325         int gridSize = ccgSubSurf_getGridSize(ss);
1326         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1327         unsigned int i = 0;
1328         short *edgeFlags = ccgdm->edgeFlags;
1329         const short ed_interior_flag = ccgdm->drawInteriorEdges ? (ME_EDGEDRAW | ME_EDGERENDER) : 0;
1330
1331         totface = ccgSubSurf_getNumFaces(ss);
1332         for (index = 0; index < totface; index++) {
1333                 CCGFace *f = ccgdm->faceMap[index].face;
1334                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1335
1336                 for (S = 0; S < numVerts; S++) {
1337                         for (x = 0; x < gridSize - 1; x++) {
1338                                 ccgDM_to_MEdge(&medge[i++],
1339                                                getFaceIndex(ss, f, S, x,     0, edgeSize, gridSize),
1340                                                getFaceIndex(ss, f, S, x + 1, 0, edgeSize, gridSize),
1341                                                ed_interior_flag);
1342                         }
1343
1344                         for (x = 1; x < gridSize - 1; x++) {
1345                                 for (y = 0; y < gridSize - 1; y++) {
1346                                         ccgDM_to_MEdge(&medge[i++],
1347                                                        getFaceIndex(ss, f, S, x, y,    edgeSize, gridSize),
1348                                                        getFaceIndex(ss, f, S, x, y + 1, edgeSize, gridSize),
1349                                                        ed_interior_flag);
1350                                         ccgDM_to_MEdge(&medge[i++],
1351                                                        getFaceIndex(ss, f, S, y, x,     edgeSize, gridSize),
1352                                                        getFaceIndex(ss, f, S, y + 1, x, edgeSize, gridSize),
1353                                                        ed_interior_flag);
1354                                 }
1355                         }
1356                 }
1357         }
1358
1359         totedge = ccgSubSurf_getNumEdges(ss);
1360         for (index = 0; index < totedge; index++) {
1361                 CCGEdge *e = ccgdm->edgeMap[index].edge;
1362                 short ed_flag = 0;
1363                 int x;
1364                 int edgeIdx = POINTER_AS_INT(ccgSubSurf_getEdgeEdgeHandle(e));
1365
1366                 if (!ccgSubSurf_getEdgeNumFaces(e)) {
1367                         ed_flag |= ME_LOOSEEDGE;
1368                 }
1369
1370                 if (edgeFlags) {
1371                         if (edgeIdx != -1) {
1372                                 ed_flag |= ((edgeFlags[index] & (ME_SEAM | ME_SHARP)) | ME_EDGEDRAW | ME_EDGERENDER);
1373                         }
1374                 }
1375                 else {
1376                         ed_flag |= ME_EDGEDRAW | ME_EDGERENDER;
1377                 }
1378
1379                 for (x = 0; x < edgeSize - 1; x++) {
1380                         ccgDM_to_MEdge(&medge[i++],
1381                                        getEdgeIndex(ss, e, x, edgeSize),
1382                                        getEdgeIndex(ss, e, x + 1, edgeSize),
1383                                        ed_flag);
1384                 }
1385         }
1386 }
1387
1388 static void ccgDM_copyFinalFaceArray(DerivedMesh *dm, MFace *mface)
1389 {
1390         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1391         CCGSubSurf *ss = ccgdm->ss;
1392         int index;
1393         int totface;
1394         int gridSize = ccgSubSurf_getGridSize(ss);
1395         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1396         int i = 0;
1397         DMFlagMat *faceFlags = ccgdm->faceFlags;
1398
1399         totface = dm->getNumTessFaces(dm);
1400         for (index = 0; index < totface; index++) {
1401                 CCGFace *f = ccgdm->faceMap[index].face;
1402                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1403                 /* keep types in sync with MFace, avoid many conversions */
1404                 char flag = (faceFlags) ? faceFlags[index].flag : ME_SMOOTH;
1405                 short mat_nr = (faceFlags) ? faceFlags[index].mat_nr : 0;
1406
1407                 for (S = 0; S < numVerts; S++) {
1408                         for (y = 0; y < gridSize - 1; y++) {
1409                                 for (x = 0; x < gridSize - 1; x++) {
1410                                         MFace *mf = &mface[i];
1411                                         mf->v1 = getFaceIndex(ss, f, S, x + 0, y + 0,
1412                                                               edgeSize, gridSize);
1413                                         mf->v2 = getFaceIndex(ss, f, S, x + 0, y + 1,
1414                                                               edgeSize, gridSize);
1415                                         mf->v3 = getFaceIndex(ss, f, S, x + 1, y + 1,
1416                                                               edgeSize, gridSize);
1417                                         mf->v4 = getFaceIndex(ss, f, S, x + 1, y + 0,
1418                                                               edgeSize, gridSize);
1419                                         mf->mat_nr = mat_nr;
1420                                         mf->flag = flag;
1421                                         mf->edcode = 0;
1422
1423                                         i++;
1424                                 }
1425                         }
1426                 }
1427         }
1428 }
1429
1430 typedef struct CopyFinalLoopArrayData {
1431         CCGDerivedMesh *ccgdm;
1432         MLoop *mloop;
1433         int grid_size;
1434         int *grid_offset;
1435         int edge_size;
1436         size_t mloop_index;
1437 } CopyFinalLoopArrayData;
1438
1439 static void copyFinalLoopArray_task_cb(
1440         void *__restrict userdata,
1441         const int iter,
1442         const ParallelRangeTLS *__restrict UNUSED(tls))
1443 {
1444         CopyFinalLoopArrayData *data = userdata;
1445         CCGDerivedMesh *ccgdm = data->ccgdm;
1446         CCGSubSurf *ss = ccgdm->ss;
1447         const int grid_size = data->grid_size;
1448         const int edge_size = data->edge_size;
1449         CCGFace *f = ccgdm->faceMap[iter].face;
1450         const int num_verts = ccgSubSurf_getFaceNumVerts(f);
1451         const int grid_index = data->grid_offset[iter];
1452         const size_t loop_index = 4 * (size_t)grid_index * (grid_size - 1) * (grid_size - 1);
1453         MLoop *ml = &data->mloop[loop_index];
1454         for (int S = 0; S < num_verts; S++) {
1455                 for (int y = 0; y < grid_size - 1; y++) {
1456                         for (int x = 0; x < grid_size - 1; x++) {
1457
1458                                 uint v1 = getFaceIndex(ss, f, S, x + 0, y + 0,
1459                                                        edge_size, grid_size);
1460                                 uint v2 = getFaceIndex(ss, f, S, x + 0, y + 1,
1461                                                        edge_size, grid_size);
1462                                 uint v3 = getFaceIndex(ss, f, S, x + 1, y + 1,
1463                                                        edge_size, grid_size);
1464                                 uint v4 = getFaceIndex(ss, f, S, x + 1, y + 0,
1465                                                        edge_size, grid_size);
1466
1467                                 ml->v = v1;
1468                                 ml->e = POINTER_AS_UINT(BLI_edgehash_lookup(ccgdm->ehash, v1, v2));
1469                                 ml++;
1470
1471                                 ml->v = v2;
1472                                 ml->e = POINTER_AS_UINT(BLI_edgehash_lookup(ccgdm->ehash, v2, v3));
1473                                 ml++;
1474
1475                                 ml->v = v3;
1476                                 ml->e = POINTER_AS_UINT(BLI_edgehash_lookup(ccgdm->ehash, v3, v4));
1477                                 ml++;
1478
1479                                 ml->v = v4;
1480                                 ml->e = POINTER_AS_UINT(BLI_edgehash_lookup(ccgdm->ehash, v4, v1));
1481                                 ml++;
1482                         }
1483                 }
1484         }
1485 }
1486
1487 static void ccgDM_copyFinalLoopArray(DerivedMesh *dm, MLoop *mloop)
1488 {
1489         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1490         CCGSubSurf *ss = ccgdm->ss;
1491
1492         if (!ccgdm->ehash) {
1493                 BLI_mutex_lock(&ccgdm->loops_cache_lock);
1494                 if (!ccgdm->ehash) {
1495                         MEdge *medge;
1496                         EdgeHash *ehash;
1497
1498                         ehash = BLI_edgehash_new_ex(__func__, ccgdm->dm.numEdgeData);
1499                         medge = ccgdm->dm.getEdgeArray((DerivedMesh *)ccgdm);
1500
1501                         for (int i = 0; i < ccgdm->dm.numEdgeData; i++) {
1502                                 BLI_edgehash_insert(ehash, medge[i].v1, medge[i].v2, POINTER_FROM_INT(i));
1503                         }
1504
1505                         atomic_cas_ptr((void **)&ccgdm->ehash, ccgdm->ehash, ehash);
1506                 }
1507                 BLI_mutex_unlock(&ccgdm->loops_cache_lock);
1508         }
1509
1510         CopyFinalLoopArrayData data;
1511         data.ccgdm = ccgdm;
1512         data.mloop = mloop;
1513         data.grid_size = ccgSubSurf_getGridSize(ss);
1514         data.grid_offset = dm->getGridOffset(dm);
1515         data.edge_size = ccgSubSurf_getEdgeSize(ss);
1516
1517         /* NOTE: For a dense subdivision we've got enough work for each face and
1518          * hence can dedicate whole thread to single face. For less dense
1519          * subdivision we handle multiple faces per thread.
1520          */
1521         data.mloop_index = data.grid_size >= 5 ? 1 : 8;
1522
1523         ParallelRangeSettings settings;
1524         BLI_parallel_range_settings_defaults(&settings);
1525         settings.min_iter_per_thread = 1;
1526
1527         BLI_task_parallel_range(0, ccgSubSurf_getNumFaces(ss),
1528                                 &data,
1529                                 copyFinalLoopArray_task_cb,
1530                                 &settings);
1531 }
1532
1533 static void ccgDM_copyFinalPolyArray(DerivedMesh *dm, MPoly *mpoly)
1534 {
1535         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1536         CCGSubSurf *ss = ccgdm->ss;
1537         int index;
1538         int totface;
1539         int gridSize = ccgSubSurf_getGridSize(ss);
1540         /* int edgeSize = ccgSubSurf_getEdgeSize(ss); */ /* UNUSED */
1541         int i = 0, k = 0;
1542         DMFlagMat *faceFlags = ccgdm->faceFlags;
1543
1544         totface = ccgSubSurf_getNumFaces(ss);
1545         for (index = 0; index < totface; index++) {
1546                 CCGFace *f = ccgdm->faceMap[index].face;
1547                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1548                 int flag = (faceFlags) ? faceFlags[index].flag : ME_SMOOTH;
1549                 int mat_nr = (faceFlags) ? faceFlags[index].mat_nr : 0;
1550
1551                 for (S = 0; S < numVerts; S++) {
1552                         for (y = 0; y < gridSize - 1; y++) {
1553                                 for (x = 0; x < gridSize - 1; x++) {
1554                                         MPoly *mp = &mpoly[i];
1555
1556                                         mp->mat_nr = mat_nr;
1557                                         mp->flag = flag;
1558                                         mp->loopstart = k;
1559                                         mp->totloop = 4;
1560
1561                                         k += 4;
1562                                         i++;
1563                                 }
1564                         }
1565                 }
1566         }
1567 }
1568
1569 static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3])
1570 {
1571         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1572         CCGSubSurf *ss = ccgdm->ss;
1573         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1574         int gridSize = ccgSubSurf_getGridSize(ss);
1575         int i;
1576         CCGVertIterator vi;
1577         CCGEdgeIterator ei;
1578         CCGFaceIterator fi;
1579         CCGFace **faceMap2;
1580         CCGEdge **edgeMap2;
1581         CCGVert **vertMap2;
1582         int index, totvert, totedge, totface;
1583
1584         totvert = ccgSubSurf_getNumVerts(ss);
1585         vertMap2 = MEM_mallocN(totvert * sizeof(*vertMap2), "vertmap");
1586         for (ccgSubSurf_initVertIterator(ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) {
1587                 CCGVert *v = ccgVertIterator_getCurrent(&vi);
1588
1589                 vertMap2[POINTER_AS_INT(ccgSubSurf_getVertVertHandle(v))] = v;
1590         }
1591
1592         totedge = ccgSubSurf_getNumEdges(ss);
1593         edgeMap2 = MEM_mallocN(totedge * sizeof(*edgeMap2), "edgemap");
1594         for (ccgSubSurf_initEdgeIterator(ss, &ei), i = 0; !ccgEdgeIterator_isStopped(&ei); i++, ccgEdgeIterator_next(&ei)) {
1595                 CCGEdge *e = ccgEdgeIterator_getCurrent(&ei);
1596
1597                 edgeMap2[POINTER_AS_INT(ccgSubSurf_getEdgeEdgeHandle(e))] = e;
1598         }
1599
1600         totface = ccgSubSurf_getNumFaces(ss);
1601         faceMap2 = MEM_mallocN(totface * sizeof(*faceMap2), "facemap");
1602         for (ccgSubSurf_initFaceIterator(ss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
1603                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
1604
1605                 faceMap2[POINTER_AS_INT(ccgSubSurf_getFaceFaceHandle(f))] = f;
1606         }
1607
1608         i = 0;
1609         for (index = 0; index < totface; index++) {
1610                 CCGFace *f = faceMap2[index];
1611                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1612
1613                 copy_v3_v3(cos[i++], ccgSubSurf_getFaceCenterData(f));
1614
1615                 for (S = 0; S < numVerts; S++) {
1616                         for (x = 1; x < gridSize - 1; x++) {
1617                                 copy_v3_v3(cos[i++], ccgSubSurf_getFaceGridEdgeData(ss, f, S, x));
1618                         }
1619                 }
1620
1621                 for (S = 0; S < numVerts; S++) {
1622                         for (y = 1; y < gridSize - 1; y++) {
1623                                 for (x = 1; x < gridSize - 1; x++) {
1624                                         copy_v3_v3(cos[i++], ccgSubSurf_getFaceGridData(ss, f, S, x, y));
1625                                 }
1626                         }
1627                 }
1628         }
1629
1630         for (index = 0; index < totedge; index++) {
1631                 CCGEdge *e = edgeMap2[index];
1632                 int x;
1633
1634                 for (x = 1; x < edgeSize - 1; x++) {
1635                         copy_v3_v3(cos[i++], ccgSubSurf_getEdgeData(ss, e, x));
1636                 }
1637         }
1638
1639         for (index = 0; index < totvert; index++) {
1640                 CCGVert *v = vertMap2[index];
1641                 copy_v3_v3(cos[i++], ccgSubSurf_getVertData(ss, v));
1642         }
1643
1644         MEM_freeN(vertMap2);
1645         MEM_freeN(edgeMap2);
1646         MEM_freeN(faceMap2);
1647 }
1648
1649 static void ccgDM_foreachMappedVert(
1650         DerivedMesh *dm,
1651         void (*func)(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3]),
1652         void *userData,
1653         DMForeachFlag flag)
1654 {
1655         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1656         CCGVertIterator vi;
1657         CCGKey key;
1658         CCG_key_top_level(&key, ccgdm->ss);
1659
1660         for (ccgSubSurf_initVertIterator(ccgdm->ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) {
1661                 CCGVert *v = ccgVertIterator_getCurrent(&vi);
1662                 const int index = ccgDM_getVertMapIndex(ccgdm->ss, v);
1663
1664                 if (index != -1) {
1665                         CCGElem *vd = ccgSubSurf_getVertData(ccgdm->ss, v);
1666                         const float *no = (flag & DM_FOREACH_USE_NORMAL) ? CCG_elem_no(&key, vd) : NULL;
1667                         func(userData, index, CCG_elem_co(&key, vd), no, NULL);
1668                 }
1669         }
1670 }
1671
1672 static void ccgDM_foreachMappedEdge(
1673         DerivedMesh *dm,
1674         void (*func)(void *userData, int index, const float v0co[3], const float v1co[3]),
1675         void *userData)
1676 {
1677         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1678         CCGSubSurf *ss = ccgdm->ss;
1679         CCGEdgeIterator ei;
1680         CCGKey key;
1681         int i, edgeSize = ccgSubSurf_getEdgeSize(ss);
1682
1683         CCG_key_top_level(&key, ss);
1684
1685         for (ccgSubSurf_initEdgeIterator(ss, &ei); !ccgEdgeIterator_isStopped(&ei); ccgEdgeIterator_next(&ei)) {
1686                 CCGEdge *e = ccgEdgeIterator_getCurrent(&ei);
1687                 const int index = ccgDM_getEdgeMapIndex(ss, e);
1688
1689                 if (index != -1) {
1690                         CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
1691                         for (i = 0; i < edgeSize - 1; i++) {
1692                                 func(userData, index, CCG_elem_offset_co(&key, edgeData, i), CCG_elem_offset_co(&key, edgeData, i + 1));
1693                         }
1694                 }
1695         }
1696 }
1697
1698 static void ccgDM_foreachMappedLoop(
1699         DerivedMesh *dm,
1700         void (*func)(void *userData, int vertex_index, int face_index, const float co[3], const float no[3]),
1701         void *userData,
1702         DMForeachFlag flag)
1703 {
1704         /* We can't use dm->getLoopDataLayout(dm) here, we want to always access dm->loopData, EditDerivedBMesh would
1705          * return loop data from bmesh itself. */
1706         const float (*lnors)[3] = (flag & DM_FOREACH_USE_NORMAL) ? DM_get_loop_data_layer(dm, CD_NORMAL) : NULL;
1707
1708         MVert *mv = dm->getVertArray(dm);
1709         MLoop *ml = dm->getLoopArray(dm);
1710         MPoly *mp = dm->getPolyArray(dm);
1711         const int *v_index = dm->getVertDataArray(dm, CD_ORIGINDEX);
1712         const int *f_index = dm->getPolyDataArray(dm, CD_ORIGINDEX);
1713         int p_idx, i;
1714
1715         for (p_idx = 0; p_idx < dm->numPolyData; ++p_idx, ++mp) {
1716                 for (i = 0; i < mp->totloop; ++i, ++ml) {
1717                         const int v_idx = v_index ? v_index[ml->v] : ml->v;
1718                         const int f_idx = f_index ? f_index[p_idx] : p_idx;
1719                         const float *no = lnors ? *lnors++ : NULL;
1720                         if (!ELEM(ORIGINDEX_NONE, v_idx, f_idx)) {
1721                                 func(userData, v_idx, f_idx, mv[ml->v].co, no);
1722                         }
1723                 }
1724         }
1725 }
1726
1727 static void UNUSED_FUNCTION(ccgdm_pbvh_update)(CCGDerivedMesh *ccgdm)
1728 {
1729         if (ccgdm->pbvh && ccgDM_use_grid_pbvh(ccgdm)) {
1730                 CCGFace **faces;
1731                 int totface;
1732
1733                 BKE_pbvh_get_grid_updates(ccgdm->pbvh, 1, (void ***)&faces, &totface);
1734                 if (totface) {
1735                         ccgSubSurf_updateFromFaces(ccgdm->ss, 0, faces, totface);
1736                         ccgSubSurf_updateNormals(ccgdm->ss, faces, totface);
1737                         MEM_freeN(faces);
1738                 }
1739         }
1740 }
1741
1742 static void ccgDM_foreachMappedFaceCenter(
1743         DerivedMesh *dm,
1744         void (*func)(void *userData, int index, const float co[3], const float no[3]),
1745         void *userData,
1746         DMForeachFlag flag)
1747 {
1748         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1749         CCGSubSurf *ss = ccgdm->ss;
1750         CCGKey key;
1751         CCGFaceIterator fi;
1752
1753         CCG_key_top_level(&key, ss);
1754
1755         for (ccgSubSurf_initFaceIterator(ss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
1756                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
1757                 const int index = ccgDM_getFaceMapIndex(ss, f);
1758
1759                 if (index != -1) {
1760                         /* Face center data normal isn't updated atm. */
1761                         CCGElem *vd = ccgSubSurf_getFaceGridData(ss, f, 0, 0, 0);
1762                         const float *no = (flag & DM_FOREACH_USE_NORMAL) ? CCG_elem_no(&key, vd) : NULL;
1763                         func(userData, index, CCG_elem_co(&key, vd), no);
1764                 }
1765         }
1766 }
1767
1768 static void ccgDM_release(DerivedMesh *dm)
1769 {
1770         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1771
1772         if (DM_release(dm)) {
1773                 /* Before freeing, need to update the displacement map */
1774                 if (ccgdm->multires.modified_flags) {
1775                         /* Check that mmd still exists */
1776                         if (!ccgdm->multires.local_mmd &&
1777                             BLI_findindex(&ccgdm->multires.ob->modifiers, ccgdm->multires.mmd) < 0)
1778                         {
1779                                 ccgdm->multires.mmd = NULL;
1780                         }
1781
1782                         if (ccgdm->multires.mmd) {
1783                                 if (ccgdm->multires.modified_flags & MULTIRES_COORDS_MODIFIED)
1784                                         multires_modifier_update_mdisps(dm, NULL);
1785                                 if (ccgdm->multires.modified_flags & MULTIRES_HIDDEN_MODIFIED)
1786                                         multires_modifier_update_hidden(dm);
1787                         }
1788                 }
1789
1790                 if (ccgdm->ehash)
1791                         BLI_edgehash_free(ccgdm->ehash, NULL);
1792
1793                 if (ccgdm->reverseFaceMap) MEM_freeN(ccgdm->reverseFaceMap);
1794                 if (ccgdm->gridFaces) MEM_freeN(ccgdm->gridFaces);
1795                 if (ccgdm->gridData) MEM_freeN(ccgdm->gridData);
1796                 if (ccgdm->gridOffset) MEM_freeN(ccgdm->gridOffset);
1797                 if (ccgdm->gridFlagMats) MEM_freeN(ccgdm->gridFlagMats);
1798                 if (ccgdm->gridHidden) {
1799                         /* Using dm->getNumGrids(dm) accesses freed memory */
1800                         uint numGrids = ccgdm->numGrid;
1801                         for (uint i = 0; i < numGrids; i++) {
1802                                 if (ccgdm->gridHidden[i]) {
1803                                         MEM_freeN(ccgdm->gridHidden[i]);
1804                                 }
1805                         }
1806                         MEM_freeN(ccgdm->gridHidden);
1807                 }
1808                 if (ccgdm->freeSS) ccgSubSurf_free(ccgdm->ss);
1809                 if (ccgdm->pmap) MEM_freeN(ccgdm->pmap);
1810                 if (ccgdm->pmap_mem) MEM_freeN(ccgdm->pmap_mem);
1811                 MEM_freeN(ccgdm->edgeFlags);
1812                 MEM_freeN(ccgdm->faceFlags);
1813                 if (ccgdm->useGpuBackend == false) {
1814                         MEM_freeN(ccgdm->vertMap);
1815                         MEM_freeN(ccgdm->edgeMap);
1816                         MEM_freeN(ccgdm->faceMap);
1817                 }
1818
1819                 BLI_mutex_end(&ccgdm->loops_cache_lock);
1820                 BLI_rw_mutex_end(&ccgdm->origindex_cache_rwlock);
1821
1822                 MEM_freeN(ccgdm);
1823         }
1824 }
1825
1826 static void *ccgDM_get_vert_data_layer(DerivedMesh *dm, int type)
1827 {
1828         if (type == CD_ORIGINDEX) {
1829                 /* create origindex on demand to save memory */
1830                 CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
1831                 CCGSubSurf *ss = ccgdm->ss;
1832                 int *origindex;
1833                 int a, index, totnone, totorig;
1834
1835                 /* Avoid re-creation if the layer exists already */
1836                 BLI_rw_mutex_lock(&ccgdm->origindex_cache_rwlock, THREAD_LOCK_READ);
1837                 origindex = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
1838                 BLI_rw_mutex_unlock(&ccgdm->origindex_cache_rwlock);
1839                 if (origindex) {
1840                         return origindex;
1841                 }
1842
1843                 BLI_rw_mutex_lock(&ccgdm->origindex_cache_rwlock, THREAD_LOCK_WRITE);
1844                 DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1845                 origindex = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
1846
1847                 totorig = ccgSubSurf_getNumVerts(ss);
1848                 totnone = dm->numVertData - totorig;
1849
1850                 /* original vertices are at the end */
1851                 for (a = 0; a < totnone; a++)
1852                         origindex[a] = ORIGINDEX_NONE;
1853
1854                 for (index = 0; index < totorig; index++, a++) {
1855                         CCGVert *v = ccgdm->vertMap[index].vert;
1856                         origindex[a] = ccgDM_getVertMapIndex(ccgdm->ss, v);
1857                 }
1858                 BLI_rw_mutex_unlock(&ccgdm->origindex_cache_rwlock);
1859
1860                 return origindex;
1861         }
1862
1863         return DM_get_vert_data_layer(dm, type);
1864 }
1865
1866 static void *ccgDM_get_edge_data_layer(DerivedMesh *dm, int type)
1867 {
1868         if (type == CD_ORIGINDEX) {
1869                 /* create origindex on demand to save memory */
1870                 CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
1871                 CCGSubSurf *ss = ccgdm->ss;
1872                 int *origindex;
1873                 int a, i, index, totnone, totorig, totedge;
1874                 int edgeSize = ccgSubSurf_getEdgeSize(ss);
1875
1876                 /* Avoid re-creation if the layer exists already */
1877                 origindex = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1878                 if (origindex) {
1879                         return origindex;
1880                 }
1881
1882                 DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1883                 origindex = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1884
1885                 totedge = ccgSubSurf_getNumEdges(ss);
1886                 totorig = totedge * (edgeSize - 1);
1887                 totnone = dm->numEdgeData - totorig;
1888
1889                 /* original edges are at the end */
1890                 for (a = 0; a < totnone; a++)
1891                         origindex[a] = ORIGINDEX_NONE;
1892
1893                 for (index = 0; index < totedge; index++) {
1894                         CCGEdge *e = ccgdm->edgeMap[index].edge;
1895                         int mapIndex = ccgDM_getEdgeMapIndex(ss, e);
1896
1897                         for (i = 0; i < edgeSize - 1; i++, a++)
1898                                 origindex[a] = mapIndex;
1899                 }
1900
1901                 return origindex;
1902         }
1903
1904         return DM_get_edge_data_layer(dm, type);
1905 }
1906
1907 static void *ccgDM_get_tessface_data_layer(DerivedMesh *dm, int type)
1908 {
1909         if (type == CD_ORIGINDEX) {
1910                 /* create origindex on demand to save memory */
1911                 int *origindex;
1912
1913                 /* Avoid re-creation if the layer exists already */
1914                 origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
1915                 if (origindex) {
1916                         return origindex;
1917                 }
1918
1919                 DM_add_tessface_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1920                 origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
1921
1922                 /* silly loop counting up */
1923                 range_vn_i(origindex, dm->getNumTessFaces(dm), 0);
1924
1925                 return origindex;
1926         }
1927
1928         if (type == CD_TESSLOOPNORMAL) {
1929                 /* Create tessloopnormal on demand to save memory. */
1930                 /* Note that since tessellated face corners are the same a loops in CCGDM, and since all faces have four
1931                  * loops/corners, we can simplify the code here by converting tessloopnormals from 'short (*)[4][3]'
1932                  * to 'short (*)[3]'.
1933                  */
1934                 short (*tlnors)[3];
1935
1936                 /* Avoid re-creation if the layer exists already */
1937                 tlnors = DM_get_tessface_data_layer(dm, CD_TESSLOOPNORMAL);
1938                 if (!tlnors) {
1939                         float (*lnors)[3];
1940                         short (*tlnors_it)[3];
1941                         const int numLoops = ccgDM_getNumLoops(dm);
1942                         int i;
1943
1944                         lnors = dm->getLoopDataArray(dm, CD_NORMAL);
1945                         if (!lnors) {
1946                                 return NULL;
1947                         }
1948
1949                         DM_add_tessface_layer(dm, CD_TESSLOOPNORMAL, CD_CALLOC, NULL);
1950                         tlnors = tlnors_it = (short (*)[3])DM_get_tessface_data_layer(dm, CD_TESSLOOPNORMAL);
1951
1952                         /* With ccgdm, we have a simple one to one mapping between loops and tessellated face corners. */
1953                         for (i = 0; i < numLoops; ++i, ++tlnors_it, ++lnors) {
1954                                 normal_float_to_short_v3(*tlnors_it, *lnors);
1955                         }
1956                 }
1957
1958                 return tlnors;
1959         }
1960
1961         return DM_get_tessface_data_layer(dm, type);
1962 }
1963
1964 static void *ccgDM_get_poly_data_layer(DerivedMesh *dm, int type)
1965 {
1966         if (type == CD_ORIGINDEX) {
1967                 /* create origindex on demand to save memory */
1968                 CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
1969                 CCGSubSurf *ss = ccgdm->ss;
1970                 int *origindex;
1971                 int a, i, index, totface;
1972                 int gridFaces = ccgSubSurf_getGridSize(ss) - 1;
1973
1974                 /* Avoid re-creation if the layer exists already */
1975                 origindex = DM_get_poly_data_layer(dm, CD_ORIGINDEX);
1976                 if (origindex) {
1977                         return origindex;
1978                 }
1979
1980                 DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1981                 origindex = DM_get_poly_data_layer(dm, CD_ORIGINDEX);
1982
1983                 totface = ccgSubSurf_getNumFaces(ss);
1984
1985                 for (a = 0, index = 0; index < totface; index++) {
1986                         CCGFace *f = ccgdm->faceMap[index].face;
1987                         int numVerts = ccgSubSurf_getFaceNumVerts(f);
1988                         int mapIndex = ccgDM_getFaceMapIndex(ss, f);
1989
1990                         for (i = 0; i < gridFaces * gridFaces * numVerts; i++, a++)
1991                                 origindex[a] = mapIndex;
1992                 }
1993
1994                 return origindex;
1995         }
1996
1997         return DM_get_poly_data_layer(dm, type);
1998 }
1999
2000 static void *ccgDM_get_vert_data(DerivedMesh *dm, int index, int type)
2001 {
2002         if (type == CD_ORIGINDEX) {
2003                 /* ensure creation of CD_ORIGINDEX layer */
2004                 ccgDM_get_vert_data_layer(dm, type);
2005         }
2006
2007         return DM_get_vert_data(dm, index, type);
2008 }
2009
2010 static void *ccgDM_get_edge_data(DerivedMesh *dm, int index, int type)
2011 {
2012         if (type == CD_ORIGINDEX) {
2013                 /* ensure creation of CD_ORIGINDEX layer */
2014                 ccgDM_get_edge_data_layer(dm, type);
2015         }
2016
2017         return DM_get_edge_data(dm, index, type);
2018 }
2019
2020 static void *ccgDM_get_tessface_data(DerivedMesh *dm, int index, int type)
2021 {
2022         if (ELEM(type, CD_ORIGINDEX, CD_TESSLOOPNORMAL)) {
2023                 /* ensure creation of CD_ORIGINDEX/CD_TESSLOOPNORMAL layers */
2024                 ccgDM_get_tessface_data_layer(dm, type);
2025         }
2026
2027         return DM_get_tessface_data(dm, index, type);
2028 }
2029
2030 static void *ccgDM_get_poly_data(DerivedMesh *dm, int index, int type)
2031 {
2032         if (type == CD_ORIGINDEX) {
2033                 /* ensure creation of CD_ORIGINDEX layer */
2034                 ccgDM_get_tessface_data_layer(dm, type);
2035         }
2036
2037         return DM_get_poly_data(dm, index, type);
2038 }
2039
2040 static int ccgDM_getNumGrids(DerivedMesh *dm)
2041 {
2042         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2043         int index, numFaces, numGrids;
2044
2045         numFaces = ccgSubSurf_getNumFaces(ccgdm->ss);
2046         numGrids = 0;
2047
2048         for (index = 0; index < numFaces; index++) {
2049                 CCGFace *f = ccgdm->faceMap[index].face;
2050                 numGrids += ccgSubSurf_getFaceNumVerts(f);
2051         }
2052
2053         return numGrids;
2054 }
2055
2056 static int ccgDM_getGridSize(DerivedMesh *dm)
2057 {
2058         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2059         return ccgSubSurf_getGridSize(ccgdm->ss);
2060 }
2061
2062 static void ccgdm_create_grids(DerivedMesh *dm)
2063 {
2064         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2065         CCGSubSurf *ss = ccgdm->ss;
2066         CCGElem **gridData;
2067         DMFlagMat *gridFlagMats;
2068         CCGFace **gridFaces;
2069         int *gridOffset;
2070         int index, numFaces, numGrids, S, gIndex /*, gridSize*/;
2071
2072         if (ccgdm->gridData)
2073                 return;
2074
2075         numGrids = ccgDM_getNumGrids(dm);
2076         numFaces = ccgSubSurf_getNumFaces(ss);
2077         /*gridSize = ccgDM_getGridSize(dm);*/  /*UNUSED*/
2078
2079         /* compute offset into grid array for each face */
2080         gridOffset = MEM_mallocN(sizeof(int) * numFaces, "ccgdm.gridOffset");
2081
2082         for (gIndex = 0, index = 0; index < numFaces; index++) {
2083                 CCGFace *f = ccgdm->faceMap[index].face;
2084                 int numVerts = ccgSubSurf_getFaceNumVerts(f);
2085
2086                 gridOffset[index] = gIndex;
2087                 gIndex += numVerts;
2088         }
2089
2090         /* compute grid data */
2091         gridData = MEM_mallocN(sizeof(CCGElem *) * numGrids, "ccgdm.gridData");
2092         gridFaces = MEM_mallocN(sizeof(CCGFace *) * numGrids, "ccgdm.gridFaces");
2093         gridFlagMats = MEM_mallocN(sizeof(DMFlagMat) * numGrids, "ccgdm.gridFlagMats");
2094
2095         ccgdm->gridHidden = MEM_callocN(sizeof(*ccgdm->gridHidden) * numGrids, "ccgdm.gridHidden");
2096
2097         for (gIndex = 0, index = 0; index < numFaces; index++) {
2098                 CCGFace *f = ccgdm->faceMap[index].face;
2099                 int numVerts = ccgSubSurf_getFaceNumVerts(f);
2100
2101                 for (S = 0; S < numVerts; S++, gIndex++) {
2102                         gridData[gIndex] = ccgSubSurf_getFaceGridDataArray(ss, f, S);
2103                         gridFaces[gIndex] = f;
2104                         gridFlagMats[gIndex] = ccgdm->faceFlags[index];
2105                 }
2106         }
2107
2108         ccgdm->gridData = gridData;
2109         ccgdm->gridFaces = gridFaces;
2110         ccgdm->gridOffset = gridOffset;
2111         ccgdm->gridFlagMats = gridFlagMats;
2112         ccgdm->numGrid = numGrids;
2113 }
2114
2115 static CCGElem **ccgDM_getGridData(DerivedMesh *dm)
2116 {
2117         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2118
2119         ccgdm_create_grids(dm);
2120         return ccgdm->gridData;
2121 }
2122
2123 static int *ccgDM_getGridOffset(DerivedMesh *dm)
2124 {
2125         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2126
2127         ccgdm_create_grids(dm);
2128         return ccgdm->gridOffset;
2129 }
2130
2131 static void ccgDM_getGridKey(DerivedMesh *dm, CCGKey *key)
2132 {
2133         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2134         CCG_key_top_level(key, ccgdm->ss);
2135 }
2136
2137 static DMFlagMat *ccgDM_getGridFlagMats(DerivedMesh *dm)
2138 {
2139         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2140
2141         ccgdm_create_grids(dm);
2142         return ccgdm->gridFlagMats;
2143 }
2144
2145 static BLI_bitmap **ccgDM_getGridHidden(DerivedMesh *dm)
2146 {
2147         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2148
2149         ccgdm_create_grids(dm);
2150         return ccgdm->gridHidden;
2151 }
2152
2153 static const MeshElemMap *ccgDM_getPolyMap(Object *ob, DerivedMesh *dm)
2154 {
2155         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2156
2157         if (!ccgdm->multires.mmd && !ccgdm->pmap && ob->type == OB_MESH) {
2158                 Mesh *me = ob->data;
2159
2160                 BKE_mesh_vert_poly_map_create(&ccgdm->pmap, &ccgdm->pmap_mem,
2161                                      me->mpoly, me->mloop,
2162                                      me->totvert, me->totpoly, me->totloop);
2163         }
2164
2165         return ccgdm->pmap;
2166 }
2167
2168 static int ccgDM_use_grid_pbvh(CCGDerivedMesh *ccgdm)
2169 {
2170         MultiresModifierData *mmd = ccgdm->multires.mmd;
2171
2172         /* both of multires and subsurf modifiers are CCG, but
2173          * grids should only be used when sculpting on multires */
2174         if (!mmd)
2175                 return 0;
2176
2177         return 1;
2178 }
2179
2180 static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm)
2181 {
2182         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2183         CCGKey key;
2184         int numGrids;
2185
2186         CCG_key_top_level(&key, ccgdm->ss);
2187
2188         if (!ob) {
2189                 ccgdm->pbvh = NULL;
2190                 return NULL;
2191         }
2192
2193         if (!ob->sculpt)
2194                 return NULL;
2195
2196         bool grid_pbvh = ccgDM_use_grid_pbvh(ccgdm);
2197         if ((ob->mode & OB_MODE_SCULPT) == 0) {
2198                 /* In vwpaint, we may use a grid_pbvh for multires/subsurf, under certain conditions.
2199                  * More complex cases break 'history' trail back to original vertices, in that case we fall back to
2200                  * deformed cage only (i.e. original deformed mesh). */
2201                 VirtualModifierData virtualModifierData;
2202                 ModifierData *md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
2203
2204                 grid_pbvh = true;
2205                 bool has_one_ccg_modifier = false;
2206                 for (; md; md = md->next) {
2207                         /* We can only accept to use this ccgdm if:
2208                          *   - it's the only active ccgdm in the stack.
2209                          *   - there is no topology-modifying modifier in the stack.
2210                          * Otherwise, there is no way to map back to original geometry from grid-generated PBVH.
2211                          */
2212                         const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2213
2214                         if (!modifier_isEnabled(NULL, md, eModifierMode_Realtime)) {
2215                                 continue;
2216                         }
2217                         if (ELEM(mti->type, eModifierTypeType_OnlyDeform, eModifierTypeType_NonGeometrical)) {
2218                                 continue;
2219                         }
2220
2221                         if (ELEM(md->type, eModifierType_Subsurf, eModifierType_Multires)) {
2222                                 if (has_one_ccg_modifier) {
2223                                         /* We only allow a single active ccg modifier in the stack. */
2224                                         grid_pbvh = false;
2225                                         break;
2226                                 }
2227                                 has_one_ccg_modifier = true;
2228                                 continue;
2229                         }
2230
2231                         /* Any other non-deforming modifier makes it impossible to use grid pbvh. */
2232                         grid_pbvh = false;
2233                         break;
2234                 }
2235         }
2236
2237         if (ob->sculpt->pbvh) {
2238                 /* Note that we have to clean up exisitng pbvh instead of updating it in case it does not match current
2239                  * grid_pbvh status. */
2240                 const PBVHType pbvh_type = BKE_pbvh_type(ob->sculpt->pbvh);
2241                 if (grid_pbvh) {
2242                         if (pbvh_type == PBVH_GRIDS) {
2243                                 /* pbvh's grids, gridadj and gridfaces points to data inside ccgdm
2244                                  * but this can be freed on ccgdm release, this updates the pointers
2245                                  * when the ccgdm gets remade, the assumption is that the topology
2246                                  * does not change. */
2247                                 ccgdm_create_grids(dm);
2248                                 BKE_pbvh_grids_update(ob->sculpt->pbvh, ccgdm->gridData, (void **)ccgdm->gridFaces,
2249                                                       ccgdm->gridFlagMats, ccgdm->gridHidden);
2250                         }
2251                         else {
2252                                 BKE_pbvh_free(ob->sculpt->pbvh);
2253                                 ob->sculpt->pbvh = NULL;
2254                         }
2255                 }
2256                 else if (pbvh_type == PBVH_GRIDS) {
2257                         BKE_pbvh_free(ob->sculpt->pbvh);
2258                         ob->sculpt->pbvh = NULL;
2259                 }
2260
2261                 ccgdm->pbvh = ob->sculpt->pbvh;
2262         }
2263
2264         if (ccgdm->pbvh) {
2265                 return ccgdm->pbvh;
2266         }
2267
2268         /* No pbvh exists yet, we need to create one. only in case of multires
2269          * we build a pbvh over the modified mesh, in other cases the base mesh
2270          * is being sculpted, so we build a pbvh from that. */
2271         /* Note: vwpaint tries to always build a pbvh over the modified mesh. */
2272         if (grid_pbvh) {
2273                 ccgdm_create_grids(dm);
2274
2275                 numGrids = ccgDM_getNumGrids(dm);
2276
2277                 ob->sculpt->pbvh = ccgdm->pbvh = BKE_pbvh_new();
2278                 BKE_pbvh_build_grids(ccgdm->pbvh, ccgdm->gridData,
2279                                      numGrids, &key, (void **) ccgdm->gridFaces, ccgdm->gridFlagMats, ccgdm->gridHidden);
2280         }
2281         else if (ob->type == OB_MESH) {
2282                 Mesh *me = BKE_object_get_original_mesh(ob);
2283                 const int looptris_num = poly_to_tri_count(me->totpoly, me->totloop);
2284                 MLoopTri *looptri;
2285
2286                 looptri = MEM_mallocN(sizeof(*looptri) * looptris_num, __func__);
2287
2288                 BKE_mesh_recalc_looptri(
2289                         me->mloop, me->mpoly,
2290                         me->mvert,
2291                         me->totloop, me->totpoly,
2292                         looptri);
2293
2294                 ob->sculpt->pbvh = ccgdm->pbvh = BKE_pbvh_new();
2295                 BKE_pbvh_build_mesh(ccgdm->pbvh, me->mpoly, me->mloop, me->mvert, me->totvert, &me->vdata,
2296                                     looptri, looptris_num);
2297
2298                 if (ob->sculpt->modifiers_active && ob->derivedDeform != NULL) {
2299                         DerivedMesh *deformdm = ob->derivedDeform;
2300                         float (*vertCos)[3];
2301                         int totvert;
2302
2303                         totvert = deformdm->getNumVerts(deformdm);
2304                         vertCos = MEM_malloc_arrayN(totvert, sizeof(float[3]), "ccgDM_getPBVH vertCos");
2305                         deformdm->getVertCos(deformdm, vertCos);
2306                         BKE_pbvh_apply_vertCos(ccgdm->pbvh, vertCos, totvert);
2307                         MEM_freeN(vertCos);
2308                 }
2309         }
2310
2311         if (ccgdm->pbvh != NULL) {
2312                 pbvh_show_diffuse_color_set(ccgdm->pbvh, ob->sculpt->show_diffuse_color);
2313                 pbvh_show_mask_set(ccgdm->pbvh, ob->sculpt->show_mask);
2314         }
2315
2316         return ccgdm->pbvh;
2317 }
2318
2319 static void ccgDM_recalcTessellation(DerivedMesh *UNUSED(dm))
2320 {
2321         /* Nothing to do: CCG handles creating its own tessfaces */
2322 }
2323
2324 /* WARNING! *MUST* be called in an 'loops_cache_rwlock' protected thread context! */
2325 static void ccgDM_recalcLoopTri(DerivedMesh *dm)
2326 {
2327         MLoopTri *mlooptri = dm->looptris.array;
2328         const int tottri = dm->numPolyData * 2;
2329         int i, poly_index;
2330
2331         DM_ensure_looptri_data(dm);
2332         mlooptri = dm->looptris.array_wip;
2333
2334         BLI_assert(tottri == 0 || mlooptri != NULL);
2335         BLI_assert(poly_to_tri_count(dm->numPolyData, dm->numLoopData) == dm->looptris.num);
2336         BLI_assert(tottri == dm->looptris.num);
2337
2338         for (i = 0, poly_index = 0; i < tottri; i += 2, poly_index += 1) {
2339                 MLoopTri *lt;
2340                 lt = &mlooptri[i];
2341                 /* quad is (0, 3, 2, 1) */
2342                 lt->tri[0] = (poly_index * 4) + 0;
2343                 lt->tri[1] = (poly_index * 4) + 2;
2344                 lt->tri[2] = (poly_index * 4) + 3;
2345                 lt->poly = poly_index;
2346
2347                 lt = &mlooptri[i + 1];
2348                 lt->tri[0] = (poly_index * 4) + 0;
2349                 lt->tri[1] = (poly_index * 4) + 1;
2350                 lt->tri[2] = (poly_index * 4) + 2;
2351                 lt->poly = poly_index;
2352         }
2353
2354         BLI_assert(dm->looptris.array == NULL);
2355         atomic_cas_ptr((void **)&dm->looptris.array, dm->looptris.array, dm->looptris.array_wip);
2356         dm->looptris.array_wip = NULL;
2357 }
2358
2359 static void ccgDM_calcNormals(DerivedMesh *dm)
2360 {
2361         /* Nothing to do: CCG calculates normals during drawing */
2362         dm->dirty &= ~DM_DIRTY_NORMALS;
2363 }
2364
2365 static void set_default_ccgdm_callbacks(CCGDerivedMesh *ccgdm)
2366 {
2367         ccgdm->dm.getMinMax = ccgDM_getMinMax;
2368         ccgdm->dm.getNumVerts = ccgDM_getNumVerts;
2369         ccgdm->dm.getNumEdges = ccgDM_getNumEdges;
2370         ccgdm->dm.getNumLoops = ccgDM_getNumLoops;
2371         /* reuse of ccgDM_getNumTessFaces is intentional here: subsurf polys are just created from tessfaces */
2372         ccgdm->dm.getNumPolys = ccgDM_getNumPolys;
2373         ccgdm->dm.getNumTessFaces = ccgDM_getNumTessFaces;
2374
2375         ccgdm->dm.getVert = ccgDM_getFinalVert;
2376         ccgdm->dm.getEdge = ccgDM_getFinalEdge;
2377         ccgdm->dm.getTessFace = ccgDM_getFinalFace;
2378
2379         ccgdm->dm.getVertCo = ccgDM_getFinalVertCo;
2380         ccgdm->dm.getVertNo = ccgDM_getFinalVertNo;
2381
2382         ccgdm->dm.copyVertArray = ccgDM_copyFinalVertArray;
2383         ccgdm->dm.copyEdgeArray = ccgDM_copyFinalEdgeArray;
2384         ccgdm->dm.copyTessFaceArray = ccgDM_copyFinalFaceArray;
2385         ccgdm->dm.copyLoopArray = ccgDM_copyFinalLoopArray;
2386         ccgdm->dm.copyPolyArray = ccgDM_copyFinalPolyArray;
2387
2388         ccgdm->dm.getVertData = ccgDM_get_vert_data;
2389         ccgdm->dm.getEdgeData = ccgDM_get_edge_data;
2390         ccgdm->dm.getTessFaceData = ccgDM_get_tessface_data;
2391         ccgdm->dm.getPolyData = ccgDM_get_poly_data;
2392         ccgdm->dm.getVertDataArray = ccgDM_get_vert_data_layer;
2393         ccgdm->dm.getEdgeDataArray = ccgDM_get_edge_data_layer;
2394         ccgdm->dm.getTessFaceDataArray = ccgDM_get_tessface_data_layer;
2395         ccgdm->dm.getPolyDataArray = ccgDM_get_poly_data_layer;
2396         ccgdm->dm.getNumGrids = ccgDM_getNumGrids;
2397         ccgdm->dm.getGridSize = ccgDM_getGridSize;
2398         ccgdm->dm.getGridData = ccgDM_getGridData;
2399         ccgdm->dm.getGridOffset = ccgDM_getGridOffset;
2400         ccgdm->dm.getGridKey = ccgDM_getGridKey;
2401         ccgdm->dm.getGridFlagMats = ccgDM_getGridFlagMats;
2402         ccgdm->dm.getGridHidden = ccgDM_getGridHidden;
2403         ccgdm->dm.getPolyMap = ccgDM_getPolyMap;
2404         ccgdm->dm.getPBVH = ccgDM_getPBVH;
2405
2406         ccgdm->dm.calcNormals = ccgDM_calcNormals;
2407         ccgdm->dm.calcLoopNormals = CDDM_calc_loop_normals;
2408         ccgdm->dm.calcLoopNormalsSpaceArray = CDDM_calc_loop_normals_spacearr;
2409         ccgdm->dm.calcLoopTangents = DM_calc_loop_tangents;
2410         ccgdm->dm.recalcTessellation = ccgDM_recalcTessellation;
2411         ccgdm->dm.recalcLoopTri = ccgDM_recalcLoopTri;
2412
2413         ccgdm->dm.getVertCos = ccgdm_getVertCos;
2414         ccgdm->dm.foreachMappedVert = ccgDM_foreachMappedVert;
2415         ccgdm->dm.foreachMappedEdge = ccgDM_foreachMappedEdge;
2416         ccgdm->dm.foreachMappedLoop = ccgDM_foreachMappedLoop;
2417         ccgdm->dm.foreachMappedFaceCenter = ccgDM_foreachMappedFaceCenter;
2418
2419         ccgdm->dm.release = ccgDM_release;
2420 }
2421
2422 static void create_ccgdm_maps(CCGDerivedMesh *ccgdm,
2423                               CCGSubSurf *ss)
2424 {
2425         CCGVertIterator vi;
2426         CCGEdgeIterator ei;
2427         CCGFaceIterator fi;
2428         int totvert, totedge, totface;
2429
2430         totvert = ccgSubSurf_getNumVerts(ss);
2431         ccgdm->vertMap = MEM_mallocN(totvert * sizeof(*ccgdm->vertMap), "vertMap");
2432         for (ccgSubSurf_initVertIterator(ss, &vi);
2433              !ccgVertIterator_isStopped(&vi);
2434              ccgVertIterator_next(&vi))
2435         {
2436                 CCGVert *v = ccgVertIterator_getCurrent(&vi);
2437
2438                 ccgdm->vertMap[POINTER_AS_INT(ccgSubSurf_getVertVertHandle(v))].vert = v;
2439         }
2440
2441         totedge = ccgSubSurf_getNumEdges(ss);
2442         ccgdm->edgeMap = MEM_mallocN(totedge * sizeof(*ccgdm->edgeMap), "edgeMap");
2443         for (ccgSubSurf_initEdgeIterator(ss, &ei);
2444              !ccgEdgeIterator_isStopped(&ei);
2445              ccgEdgeIterator_next(&ei))
2446         {
2447                 CCGEdge *e = ccgEdgeIterator_getCurrent(&ei);
2448
2449                 ccgdm->edgeMap[POINTER_AS_INT(ccgSubSurf_getEdgeEdgeHandle(e))].edge = e;
2450         }
2451
2452         totface = ccgSubSurf_getNumFaces(ss);
2453         ccgdm->faceMap = MEM_mallocN(totface * sizeof(*ccgdm->faceMap), "faceMap");
2454         for (ccgSubSurf_initFaceIterator(ss, &fi);
2455              !ccgFaceIterator_isStopped(&fi);
2456              ccgFaceIterator_next(&fi))
2457         {
2458                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
2459
2460                 ccgdm->faceMap[POINTER_AS_INT(ccgSubSurf_getFaceFaceHandle(f))].face = f;
2461         }
2462 }
2463
2464 /* Fill in all geometry arrays making it possible to access any
2465  * hires data from the CPU.
2466  */
2467 static void set_ccgdm_all_geometry(CCGDerivedMesh *ccgdm,
2468                                    CCGSubSurf *ss,
2469                                    DerivedMesh *dm,
2470                                    bool useSubsurfUv)
2471 {
2472         const int totvert = ccgSubSurf_getNumVerts(ss);
2473         const int totedge = ccgSubSurf_getNumEdges(ss);
2474         const int totface = ccgSubSurf_getNumFaces(ss);
2475         int index;
2476         int i;
2477         int vertNum = 0, edgeNum = 0, faceNum = 0;
2478         int *vertOrigIndex, *faceOrigIndex, *polyOrigIndex, *base_polyOrigIndex, *edgeOrigIndex;
2479         short *edgeFlags = ccgdm->edgeFlags;
2480         DMFlagMat *faceFlags = ccgdm->faceFlags;
2481         int *polyidx = NULL;
2482 #ifndef USE_DYNSIZE
2483         int *loopidx = NULL, *vertidx = NULL;
2484         BLI_array_declare(loopidx);
2485         BLI_array_declare(vertidx);
2486 #endif
2487         int loopindex, loopindex2;
2488         int edgeSize;
2489         int gridSize;
2490         int gridFaces, gridCuts;
2491         int gridSideEdges;
2492         int gridInternalEdges;
2493         WeightTable wtable = {NULL};
2494         MEdge *medge = NULL;
2495         MPoly *mpoly = NULL;
2496         bool has_edge_cd;
2497
2498         edgeSize = ccgSubSurf_getEdgeSize(ss);
2499         gridSize = ccgSubSurf_getGridSize(ss);
2500         gridFaces = gridSize - 1;
2501         gridCuts = gridSize - 2;
2502         /*gridInternalVerts = gridSideVerts * gridSideVerts; - as yet, unused */
2503         gridSideEdges = gridSize - 1;
2504         gridInternalEdges = (gridSideEdges - 1) * gridSideEdges * 2;
2505
2506         /* mvert = dm->getVertArray(dm); */ /* UNUSED */
2507         medge = dm->getEdgeArray(dm);
2508         /* mface = dm->getTessFaceArray(dm); */ /* UNUSED */
2509
2510         mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
2511         base_polyOrigIndex = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX);
2512
2513         vertOrigIndex = DM_get_vert_data_layer(&ccgdm->dm, CD_ORIGINDEX);
2514         edgeOrigIndex = DM_get_edge_data_layer(&ccgdm->dm, CD_ORIGINDEX);
2515
2516         faceOrigIndex = DM_get_tessface_data_layer(&ccgdm->dm, CD_ORIGINDEX);
2517         polyOrigIndex = DM_get_poly_data_layer(&ccgdm->dm, CD_ORIGINDEX);
2518
2519         has_edge_cd = ((ccgdm->dm.edgeData.totlayer - (edgeOrigIndex ? 1 : 0)) != 0);
2520
2521         loopindex = loopindex2 = 0; /* current loop index */
2522         for (index = 0; index < totface; index++) {
2523                 CCGFace *f = ccgdm->faceMap[index].face;
2524                 int numVerts = ccgSubSurf_getFaceNumVerts(f);
2525                 int numFinalEdges = numVerts * (gridSideEdges + gridInternalEdges);
2526                 int origIndex = POINTER_AS_INT(ccgSubSurf_getFaceFaceHandle(f));
2527                 int g2_wid = gridCuts + 2;
2528                 float *w, *w2;
2529                 int s, x, y;
2530 #ifdef USE_DYNSIZE
2531                 int loopidx[numVerts], vertidx[numVerts];
2532 #endif
2533                 w = get_ss_weights(&wtable, gridCuts, numVerts);
2534
2535                 ccgdm->faceMap[index].startVert = vertNum;
2536                 ccgdm->faceMap[index].startEdge = edgeNum;
2537                 ccgdm->faceMap[index].startFace = faceNum;
2538
2539                 faceFlags->flag = mpoly ?  mpoly[origIndex].flag : 0;
2540                 faceFlags->mat_nr = mpoly ? mpoly[origIndex].mat_nr : 0;
2541                 faceFlags++;
2542
2543                 /* set the face base vert */
2544                 *((int *)ccgSubSurf_getFaceUserData(ss, f)) = vertNum;
2545
2546 #ifndef USE_DYNSIZE
2547                 BLI_array_clear(loopidx);
2548                 BLI_array_grow_items(loopidx, numVerts);
2549 #endif
2550                 for (s = 0; s < numVerts; s++) {
2551                         loopidx[s] = loopindex++;
2552                 }
2553
2554 #ifndef USE_DYNSIZE
2555                 BLI_array_clear(vertidx);
2556                 BLI_array_grow_items(vertidx, numVerts);
2557 #endif
2558                 for (s = 0; s < numVerts; s++) {
2559                         CCGVert *v = ccgSubSurf_getFaceVert(f, s);
2560                         vertidx[s] = POINTER_AS_INT(ccgSubSurf_getVertVertHandle(v));
2561                 }
2562
2563                 /*I think this is for interpolating the center vert?*/
2564                 w2 = w; // + numVerts*(g2_wid-1) * (g2_wid-1); //numVerts*((g2_wid-1) * g2_wid+g2_wid-1);
2565                 DM_interp_vert_data(dm, &ccgdm->dm, vertidx, w2,
2566                                     numVerts, vertNum);
2567                 if (vertOrigIndex) {
2568                         *vertOrigIndex = ORIGINDEX_NONE;
2569                         vertOrigIndex++;
2570                 }
2571
2572                 vertNum++;
2573
2574                 /*interpolate per-vert data*/
2575                 for (s = 0; s < numVerts; s++) {
2576                         for (x = 1; x < gridFaces; x++) {
2577                                 w2 = w + s * numVerts * g2_wid * g2_wid + x * numVerts;
2578                                 DM_interp_vert_data(dm, &ccgdm->dm, vertidx, w2,
2579                                                     numVerts, vertNum);
2580
2581                                 if (vertOrigIndex) {
2582                                         *vertOrigIndex = ORIGINDEX_NONE;
2583                                         vertOrigIndex++;
2584                                 }
2585
2586                                 vertNum++;
2587                         }
2588                 }
2589
2590                 /*interpolate per-vert data*/
2591                 for (s = 0; s < numVerts; s++) {
2592                         for (y = 1; y < gridFaces; y++) {
2593                                 for (x = 1; x < gridFaces; x++) {
2594                                         w2 = w + s * numVerts * g2_wid * g2_wid + (y * g2_wid + x) * numVerts;
2595                                         DM_interp_vert_data(dm, &ccgdm->dm, vertidx, w2,
2596                                                             numVerts, vertNum);
2597
2598                                         if (vertOrigIndex) {
2599                                                 *vertOrigIndex = ORIGINDEX_NONE;
2600                                                 vertOrigIndex++;
2601                                         }
2602
2603                                         vertNum++;
2604                                 }
2605                         }
2606                 }
2607
2608                 if (edgeOrigIndex) {
2609                         for (i = 0; i < numFinalEdges; ++i) {
2610                                 edgeOrigIndex[edgeNum + i] = ORIGINDEX_NONE;
2611                         }
2612                 }
2613
2614                 for (s = 0; s < numVerts; s++) {
2615                         /*interpolate per-face data*/
2616                         for (y = 0; y < gridFaces; y++) {
2617                                 for (x = 0; x < gridFaces; x++) {
2618                                         w2 = w + s * numVerts * g2_wid * g2_wid + (y * g2_wid + x) * numVerts;
2619                                         CustomData_interp(&dm->loopData, &ccgdm->dm.loopData,
2620                                                           loopidx, w2, NULL, numVerts, loopindex2);
2621                                         loopindex2++;
2622
2623                                         w2 = w + s * numVerts * g2_wid * g2_wid + ((y + 1) * g2_wid + (x)) * numVerts;
2624                                         CustomData_interp(&dm->loopData, &ccgdm->dm.loopData,
2625                                                           loopidx, w2, NULL, numVerts, loopindex2);
2626                                         loopindex2++;
2627
2628                                         w2 = w + s * numVerts * g2_wid * g2_wid + ((y + 1) * g2_wid + (x + 1)) * numVerts;
2629                                         CustomData_interp(&dm->loopData, &ccgdm->dm.loopData,
2630                                                           loopidx, w2, NULL, numVerts, loopindex2);
2631                                         loopindex2++;
2632
2633                                         w2 = w + s * numVerts * g2_wid * g2_wid + ((y) * g2_wid + (x + 1)) * numVerts;
2634                                         CustomData_interp(&dm->loopData, &ccgdm->dm.loopData,
2635                                                           loopidx, w2, NULL, numVerts, loopindex2);
2636                                         loopindex2++;
2637
2638                                         /*copy over poly data, e.g. mtexpoly*/
2639                                         CustomData_copy_data(&dm->polyData, &ccgdm->dm.polyData, origIndex, faceNum, 1);
2640
2641                                         /*set original index data*/
2642                                         if (faceOrigIndex) {
2643                                                 /* reference the index in 'polyOrigIndex' */
2644                                                 *faceOrigIndex = faceNum;
2645                                                 faceOrigIndex++;
2646                                         }
2647                                         if (polyOrigIndex) {
2648                                                 *polyOrigIndex = base_polyOrigIndex ? base_polyOrigIndex[origIndex] : origIndex;
2649                                                 polyOrigIndex++;
2650                                         }
2651
2652                                         ccgdm->reverseFaceMap[faceNum] = index;
2653
2654                                         /* This is a simple one to one mapping, here... */
2655                                         if (polyidx) {
2656                                                 polyidx[faceNum] = faceNum;
2657                                         }
2658
2659                                         faceNum++;
2660                                 }
2661                         }
2662                 }
2663
2664                 edgeNum += numFinalEdges;
2665         }
2666
2667         for (index = 0; index < totedge; ++index) {
2668                 CCGEdge *e = ccgdm->edgeMap[index].edge;
2669                 int numFinalEdges = edgeSize - 1;
2670                 int mapIndex = ccgDM_getEdgeMapIndex(ss, e);
2671                 int x;
2672                 int vertIdx[2];
2673                 int edgeIdx = POINTER_AS_INT(ccgSubSurf_getEdgeEdgeHandle(e));
2674
2675                 CCGVert *v;
2676                 v = ccgSubSurf_getEdgeVert0(e);
2677                 vertIdx[0] = POINTER_AS_INT(ccgSubSurf_getVertVertHandle(v));
2678                 v = ccgSubSurf_getEdgeVert1(e);
2679                 vertIdx[1] = POINTER_AS_INT(ccgSubSurf_getVertVertHandle(v));
2680
2681                 ccgdm->edgeMap[index].startVert = vertNum;
2682                 ccgdm->edgeMap[index].startEdge = edgeNum;
2683
2684                 if (edgeIdx >= 0 && edgeFlags)
2685                         edgeFlags[edgeIdx] = medge[edgeIdx].flag;
2686
2687                 /* set the edge base vert */
2688                 *((int *)ccgSubSurf_getEdgeUserData(ss, e)) = vertNum;
2689
2690                 for (x = 1; x < edgeSize - 1; x++) {
2691                         float w[2];
2692                         w[1] = (float) x / (edgeSize - 1);
2693                         w[0] = 1 - w[1];
2694                         DM_interp_vert_data(dm, &ccgdm->dm, vertIdx, w, 2, vertNum);
2695                         if (vertOrigIndex) {
2696                                 *vertOrigIndex = ORIGINDEX_NONE;
2697                                 vertOrigIndex++;
2698                         }
2699                         vertNum++;
2700                 }
2701
2702                 if (has_edge_cd) {
2703                         BLI_assert(edgeIdx >= 0 && edgeIdx < dm->getNumEdges(dm));
2704                         for (i = 0; i < numFinalEdges; ++i) {
2705                                 CustomData_copy_data(&dm->edgeData, &ccgdm->dm.edgeData, edgeIdx, edgeNum + i, 1);
2706                         }
2707                 }
2708
2709                 if (edgeOrigIndex) {
2710                         for (i = 0; i < numFinalEdges; ++i) {
2711                                 edgeOrigIndex[edgeNum + i] = mapIndex;
2712                         }
2713                 }
2714
2715                 edgeNum += numFinalEdges;
2716         }
2717
2718         if (useSubsurfUv) {
2719                 CustomData *ldata = &ccgdm->dm.loopData;
2720                 CustomData *dmldata = &dm->loopData;
2721                 int numlayer = CustomData_number_of_layers(ldata, CD_MLOOPUV);
2722                 int dmnumlayer = CustomData_number_of_layers(dmldata, CD_MLOOPUV);
2723
2724                 for (i = 0; i < numlayer && i < dmnumlayer; i++)
2725                         set_subsurf_uv(ss, dm, &ccgdm->dm, i);
2726         }
2727
2728         for (index = 0; index < totvert; ++index) {
2729                 CCGVert *v = ccgdm->vertMap[index].vert;
2730                 int mapIndex = ccgDM_getVertMapIndex(ccgdm->ss, v);
2731                 int vertIdx;
2732
2733                 vertIdx = POINTER_AS_INT(ccgSubSurf_getVertVertHandle(v));
2734
2735                 ccgdm->vertMap[index].startVert = vertNum;
2736
2737                 /* set the vert base vert */
2738                 *((int *) ccgSubSurf_getVertUserData(ss, v)) = vertNum;
2739
2740                 DM_copy_vert_data(dm, &ccgdm->dm, vertIdx, vertNum, 1);
2741
2742                 if (vertOrigIndex) {
2743                         *vertOrigIndex = mapIndex;
2744                         vertOrigIndex++;
2745                 }
2746                 vertNum++;
2747         }
2748
2749 #ifndef USE_DYNSIZE
2750         BLI_array_free(vertidx);
2751         BLI_array_free(loopidx);
2752 #endif
2753         free_ss_weights(&wtable);
2754
2755         BLI_assert(vertNum == ccgSubSurf_getNumFinalVerts(ss));
2756         BLI_assert(edgeNum == ccgSubSurf_getNumFinalEdges(ss));
2757         BLI_assert(loopindex2 == ccgSubSurf_getNumFinalFaces(ss) * 4);
2758         BLI_assert(faceNum == ccgSubSurf_getNumFinalFaces(ss));
2759
2760 }
2761
2762 /* Fill in only geometry arrays needed for the GPU tessellation. */
2763 static void set_ccgdm_gpu_geometry(CCGDerivedMesh *ccgdm, DerivedMesh *dm)
2764 {
2765         const int totface = dm->getNumPolys(dm);
2766         MPoly *mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
2767         int index;
2768         DMFlagMat *faceFlags = ccgdm->faceFlags;
2769
2770         for (index = 0; index < totface; index++) {
2771                 faceFlags->flag = mpoly ?  mpoly[index].flag : 0;
2772                 faceFlags->mat_nr = mpoly ? mpoly[index].mat_nr : 0;
2773                 faceFlags++;
2774         }
2775
2776         /* TODO(sergey): Fill in edge flags. */
2777 }
2778
2779 static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
2780                                          int drawInteriorEdges,
2781                                          int useSubsurfUv,
2782                                          DerivedMesh *dm,
2783                                          bool use_gpu_backend)
2784 {
2785 #ifdef WITH_OPENSUBDIV
2786         const int totedge = dm->getNumEdges(dm);
2787         const int totface = dm->getNumPolys(dm);
2788 #else
2789         const int totedge = ccgSubSurf_getNumEdges(ss);
2790         const int totface = ccgSubSurf_getNumFaces(ss);
2791 #endif
2792         CCGDerivedMesh *ccgdm = MEM_callocN(sizeof(*ccgdm), "ccgdm");
2793
2794         if (use_gpu_backend == false) {
2795                 BLI_assert(totedge == ccgSubSurf_getNumEdges(ss));
2796                 BLI_assert(totface == ccgSubSurf_getNumFaces(ss));
2797                 DM_from_template(&ccgdm->dm, dm, DM_TYPE_CCGDM,
2798                                  ccgSubSurf_getNumFinalVerts(ss),
2799                                  ccgSubSurf_getNumFinalEdges(ss),
2800                                  0,
2801                                  ccgSubSurf_getNumFinalFaces(ss) * 4,
2802                                  ccgSubSurf_getNumFinalFaces(ss));
2803
2804                 CustomData_free_layer_active(&ccgdm->dm.polyData, CD_NORMAL,
2805                                              ccgdm->dm.numPolyData);
2806
2807                 ccgdm->reverseFaceMap =
2808                         MEM_callocN(sizeof(int) * ccgSubSurf_getNumFinalFaces(ss),
2809                                     "reverseFaceMap");
2810
2811                 create_ccgdm_maps(ccgdm, ss);
2812         }
2813         else {
2814                 DM_from_template(&ccgdm->dm, dm, DM_TYPE_CCGDM,
2815                                  0, 0, 0, 0, dm->getNumPolys(dm));
2816                 CustomData_copy_data(&dm->polyData,
2817                                      &ccgdm->dm.polyData,
2818                                      0, 0, dm->getNumPolys(dm));
2819         }
2820
2821         set_default_ccgdm_callbacks(ccgdm);
2822
2823         ccgdm->ss = ss;
2824         ccgdm->drawInteriorEdges = drawInteriorEdges;
2825         ccgdm->useSubsurfUv = useSubsurfUv;
2826         ccgdm->useGpuBackend = use_gpu_backend;
2827
2828         /* CDDM hack. */
2829         ccgdm->edgeFlags = MEM_callocN(sizeof(short) * totedge, "edgeFlags");
2830         ccgdm->faceFlags = MEM_callocN(sizeof(DMFlagMat) * totface, "faceFlags");
2831
2832         if (use_gpu_backend == false) {
2833                 set_ccgdm_all_geometry(ccgdm, ss, dm, useSubsurfUv != 0);
2834         }
2835         else {
2836                 set_ccgdm_gpu_geometry(ccgdm, dm);
2837         }
2838
2839         ccgdm->dm.numVertData = ccgSubSurf_getNumFinalVerts(ss);
2840         ccgdm->dm.numEdgeData = ccgSubSurf_getNumFinalEdges(ss);
2841         ccgdm->dm.numPolyData = ccgSubSurf_getNumFinalFaces(ss);
2842         ccgdm->dm.numLoopData = ccgdm->dm.numPolyData * 4;
2843         ccgdm->dm.numTessFaceData = 0;
2844
2845         BLI_mutex_init(&ccgdm->loops_cache_lock);
2846         BLI_rw_mutex_init(&ccgdm->origindex_cache_rwlock);
2847
2848         return ccgdm;
2849 }
2850
2851 /***/
2852
2853 static bool subsurf_use_gpu_backend(SubsurfFlags flags)
2854 {
2855 #ifdef WITH_OPENSUBDIV
2856         /* Use GPU backend if it's a last modifier in the stack
2857          * and user chose to use any of the OSD compute devices,
2858          * but also check if GPU has all needed features.
2859          */
2860         return
2861                 (flags & SUBSURF_USE_GPU_BACKEND) != 0 &&
2862                 (U.opensubdiv_compute_type != USER_OPENSUBDIV_COMPUTE_NONE);
2863 #else
2864         (void)flags;
2865         return false;
2866 #endif
2867 }
2868
2869 struct DerivedMesh *subsurf_make_derived_from_derived(
2870         struct DerivedMesh *dm,
2871         struct SubsurfModifierData *smd,
2872         struct Scene *scene,
2873         float (*vertCos)[3],
2874         SubsurfFlags flags)
2875 {
2876         int useSimple = (smd->subdivType == ME_SIMPLE_SUBSURF) ? CCG_SIMPLE_SUBDIV : 0;
2877         CCGFlags useAging = (smd->flags & eSubsurfModifierFlag_DebugIncr) ? CCG_USE_AGING : 0;
2878         int useSubsurfUv = (smd->uv_smooth != SUBSURF_UV_SMOOTH_NONE);
2879         int drawInteriorEdges = !(smd->flags & eSubsurfModifierFlag_ControlEdges);
2880         CCGDerivedMesh *result;
2881         bool use_gpu_backend = subsurf_use_gpu_backend(flags);
2882
2883         /* note: editmode calculation can only run once per
2884          * modifier stack evaluation (uses freed cache) [#36299] */
2885         if (flags & SUBSURF_FOR_EDIT_MODE) {
2886                 int levels = (scene != NULL) ? get_render_subsurf_level(&scene->r, smd->levels, false) : smd->levels;
2887
2888                 /* TODO(sergey): Same as emCache below. */
2889                 if ((flags & SUBSURF_IN_EDIT_MODE) && smd->mCache) {
2890                         ccgSubSurf_free(smd->mCache);
2891                         smd->mCache = NULL;
2892                 }
2893
2894                 smd->emCache = _getSubSurf(smd->emCache, levels, 3, useSimple | useAging | CCG_CALC_NORMALS);
2895
2896 #ifdef WITH_OPENSUBDIV
2897                 ccgSubSurf_setSkipGrids(smd->emCache, use_gpu_backend);
2898 #endif
2899                 ss_sync_from_derivedmesh(smd->emCache, dm, vertCos, useSimple, useSubsurfUv);
2900                 result = getCCGDerivedMesh(smd->emCache,
2901                                            drawInteriorEdges,
2902                                            useSubsurfUv, dm, use_gpu_backend);
2903         }
2904         else if (flags & SUBSURF_USE_RENDER_PARAMS) {
2905                 /* Do not use cache in render mode. */
2906                 CCGSubSurf *ss;
2907                 int levels = (scene != NULL) ? get_render_subsurf_level(&scene->r, smd->renderLevels, true) : smd->renderLevels;
2908
2909                 if (levels == 0)
2910                         return dm;
2911
2912                 ss = _getSubSurf(NULL, levels, 3, useSimple | CCG_USE_ARENA | CCG_CALC_NORMALS);
2913
2914                 ss_sync_from_derivedmesh(ss, dm, vertCos, useSimple, useSubsurfUv);
2915
2916                 result = getCCGDerivedMesh(ss,
2917                                            drawInteriorEdges, useSubsurfUv, dm, false);
2918
2919                 result->freeSS = 1;
2920         }
2921         else {
2922                 int useIncremental = (smd->flags & eSubsurfModifierFlag_Incremental);
2923                 int levels = (scene != NULL) ? get_render_subsurf_level(&scene->r, smd->levels, false) : smd->levels;
2924                 CCGSubSurf *ss;
2925
2926                 /* It is quite possible there is a much better place to do this. It
2927                  * depends a bit on how rigorously we expect this function to never
2928                  * be called in editmode. In semi-theory we could share a single
2929                  * cache, but the handles used inside and outside editmode are not
2930                  * the same so we would need some way of converting them. Its probably
2931                  * not worth the effort. But then why am I even writing this long
2932                  * comment that no one will read? Hmmm. - zr
2933                  *
2934                  * Addendum: we can't really ensure that this is never called in edit
2935                  * mode, so now we have a parameter to verify it. - brecht
2936                  */
2937                 if (!(flags & SUBSURF_IN_EDIT_MODE) && smd->emCache) {
2938                         ccgSubSurf_free(smd->emCache);
2939                         smd->emCache = NULL;
2940                 }
2941
2942                 if (useIncremental && (flags & SUBSURF_IS_FINAL_CALC)) {
2943                         smd->mCache = ss = _getSubSurf(smd->mCache, levels, 3, useSimple | useAging | CCG_CALC_NORMALS);
2944
2945                         ss_sync_from_derivedmesh(ss, dm, vertCos, useSimple, useSubsurfUv);
2946
2947                         result = getCCGDerivedMesh(smd->mCache,
2948                                                    drawInteriorEdges,
2949                                                    useSubsurfUv, dm, false);
2950                 }
2951                 else {
2952                         CCGFlags ccg_flags = useSimple | CCG_USE_ARENA | CCG_CALC_NORMALS;
2953                         CCGSubSurf *prevSS = NULL;
2954
2955                         if (smd->mCache && (flags & SUBSURF_IS_FINAL_CALC)) {
2956 #ifdef WITH_OPENSUBDIV
2957                                 /* With OpenSubdiv enabled we always tries to re-use previous
2958                                  * subsurf structure in order to save computation time since
2959                                  * re-creation is rather a complicated business.
2960                                  *
2961                                  * TODO(sergey): There was a good eason why final calculation
2962                                  * used to free entirely cached subsurf structure. reason of
2963                                  * this is to be investigated still to be sure we don't have
2964                                  * regressions here.
2965                                  */
2966                                 if (use_gpu_backend) {
2967                                         prevSS = smd->mCache;
2968                                 }
2969                                 else
2970 #endif
2971                                 {
2972                                         ccgSubSurf_free(smd->mCache);
2973                                         smd->mCache = NULL;
2974                                 }
2975                         }
2976
2977
2978                         if (flags & SUBSURF_ALLOC_PAINT_MASK)
2979                                 ccg_flags |= CCG_ALLOC_MASK;
2980
2981                         ss = _getSubSurf(prevSS, levels, 3, ccg_flags);
2982 #ifdef WITH_OPENSUBDIV
2983                         ccgSubSurf_setSkipGrids(ss, use_gpu_backend);
2984 #endif
2985                         ss_sync_from_derivedmesh(ss, dm, vertCos, useSimple, useSubsurfUv);
2986
2987                         result = getCCGDerivedMesh(ss, drawInteriorEdges, useSubsurfUv, dm, use_gpu_backend);
2988
2989                         if (flags & SUBSURF_IS_FINAL_CALC)
2990                                 smd->mCache = ss;
2991                         else
2992                                 result->freeSS = 1;
2993
2994                         if (flags & SUBSURF_ALLOC_PAINT_MASK)
2995                                 ccgSubSurf_setNumLayers(ss, 4);
2996                 }
2997         }
2998
2999         return (DerivedMesh *)result;
3000 }
3001
3002 void subsurf_calculate_limit_positions(Mesh *me, float (*r_positions)[3])
3003 {
3004         /* Finds the subsurf limit positions for the verts in a mesh
3005          * and puts them in an array of floats. Please note that the
3006          * calculated vert positions is incorrect for the verts
3007          * on the boundary of the mesh.
3008          */
3009         CCGSubSurf *ss = _getSubSurf(NULL, 1, 3, CCG_USE_ARENA);
3010         float edge_sum[3], face_sum[3];
3011         CCGVertIterator vi;
3012         DerivedMesh *dm = CDDM_from_mesh(me);
3013
3014         ss_sync_from_derivedmesh(ss, dm, NULL, 0, 0);
3015
3016         for (ccgSubSurf_initVertIterator(ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) {
3017                 CCGVert *v = ccgVertIterator_getCurrent(&vi);
3018                 int idx = POINTER_AS_INT(ccgSubSurf_getVertVertHandle(v));
3019                 int N = ccgSubSurf_getVertNumEdges(v);
3020                 int numFaces = ccgSubSurf_getVertNumFaces(v);
3021                 float *co;
3022                 int i;
3023
3024                 zero_v3(edge_sum);
3025                 zero_v3(face_sum);
3026
3027                 for (i = 0; i < N; i++) {
3028                         CCGEdge *e = ccgSubSurf_getVertEdge(v, i);
3029                         add_v3_v3v3(edge_sum, edge_sum, ccgSubSurf_getEdgeData(ss, e, 1));
3030                 }
3031                 for (i = 0; i < numFaces; i++) {
3032                         CCGFace *f = ccgSubSurf_getVertFace(v, i);
3033                         add_v3_v3(face_sum, ccgSubSurf_getFaceCenterData(f));
3034                 }
3035
3036                 /* ad-hoc correction for boundary vertices, to at least avoid them
3037                  * moving completely out of place (brecht) */
3038                 if (numFaces && numFaces != N)
3039                         mul_v3_fl(face_sum, (float)N / (float)numFaces);
3040
3041                 co = ccgSubSurf_getVertData(ss, v);
3042                 r_positions[idx][0] = (co[0] * N * N + edge_sum[0] * 4 + face_sum[0]) / (N * (N + 5));
3043                 r_positions[idx][1] = (co[1] * N * N + edge_sum[1] * 4 + face_sum[1]) / (N * (N + 5));
3044                 r_positions[idx][2] = (co[2] * N * N + edge_sum[2] * 4 + face_sum[2]) / (N * (N + 5));
3045         }
3046
3047         ccgSubSurf_free(ss);
3048
3049         dm->release(dm);
3050 }
3051
3052 bool subsurf_has_edges(DerivedMesh *dm)
3053 {
3054         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
3055 #ifdef WITH_OPENSUBDIV
3056         if (ccgdm->useGpuBackend) {
3057                 return true;
3058         }
3059 #else
3060         (void)ccgdm;
3061 #endif
3062         return dm->getNumEdges(dm) != 0;
3063 }
3064
3065 bool subsurf_has_faces(DerivedMesh *dm)
3066 {
3067         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
3068 #ifdef WITH_OPENSUBDIV
3069         if (ccgdm->useGpuBackend) {
3070                 return true;
3071         }
3072 #else
3073         (void)ccgdm;
3074 #endif
3075         return dm->getNumPolys(dm) != 0;
3076 }