CMake: Disable some features when using MinGW and full cmake config
[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 "MEM_guardedalloc.h"
46
47 #include "DNA_mesh_types.h"
48 #include "DNA_meshdata_types.h"
49 #include "DNA_modifier_types.h"
50 #include "DNA_object_types.h"
51 #include "DNA_scene_types.h"
52
53 #include "BLI_utildefines.h"
54 #include "BLI_bitmap.h"
55 #include "BLI_blenlib.h"
56 #include "BLI_edgehash.h"
57 #include "BLI_math.h"
58 #include "BLI_memarena.h"
59 #include "BLI_threads.h"
60
61 #include "BKE_pbvh.h"
62 #include "BKE_ccg.h"
63 #include "BKE_cdderivedmesh.h"
64 #include "BKE_global.h"
65 #include "BKE_mesh.h"
66 #include "BKE_mesh_mapping.h"
67 #include "BKE_multires.h"
68 #include "BKE_paint.h"
69 #include "BKE_scene.h"
70 #include "BKE_subsurf.h"
71
72 #ifndef USE_DYNSIZE
73 #  include "BLI_array.h"
74 #endif
75
76 #include "GPU_draw.h"
77 #include "GPU_glew.h"
78 #include "GPU_buffers.h"
79 #include "GPU_shader.h"
80
81 #include "CCGSubSurf.h"
82
83 #ifdef WITH_OPENSUBDIV
84 #  include "opensubdiv_capi.h"
85 #endif
86
87 /* assumes MLoop's are layed out 4 for each poly, in order */
88 #define USE_LOOP_LAYOUT_FAST
89
90 extern GLubyte stipple_quarttone[128]; /* glutil.c, bad level data */
91
92 static ThreadRWMutex loops_cache_rwlock = BLI_RWLOCK_INITIALIZER;
93 static ThreadRWMutex origindex_cache_rwlock = BLI_RWLOCK_INITIALIZER;
94
95 static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
96                                          int drawInteriorEdges,
97                                          int useSubsurfUv,
98                                          DerivedMesh *dm,
99                                          bool use_gpu_backend);
100 static int ccgDM_use_grid_pbvh(CCGDerivedMesh *ccgdm);
101
102 ///
103
104 static void *arena_alloc(CCGAllocatorHDL a, int numBytes)
105 {
106         return BLI_memarena_alloc(a, numBytes);
107 }
108
109 static void *arena_realloc(CCGAllocatorHDL a, void *ptr, int newSize, int oldSize)
110 {
111         void *p2 = BLI_memarena_alloc(a, newSize);
112         if (ptr) {
113                 memcpy(p2, ptr, oldSize);
114         }
115         return p2;
116 }
117
118 static void arena_free(CCGAllocatorHDL UNUSED(a), void *UNUSED(ptr))
119 {
120         /* do nothing */
121 }
122
123 static void arena_release(CCGAllocatorHDL a)
124 {
125         BLI_memarena_free(a);
126 }
127
128 typedef enum {
129         CCG_USE_AGING = 1,
130         CCG_USE_ARENA = 2,
131         CCG_CALC_NORMALS = 4,
132         /* add an extra four bytes for a mask layer */
133         CCG_ALLOC_MASK = 8,
134         CCG_SIMPLE_SUBDIV = 16
135 } CCGFlags;
136
137 static CCGSubSurf *_getSubSurf(CCGSubSurf *prevSS, int subdivLevels,
138                                int numLayers, CCGFlags flags)
139 {
140         CCGMeshIFC ifc;
141         CCGSubSurf *ccgSS;
142         int useAging = !!(flags & CCG_USE_AGING);
143         int useArena = flags & CCG_USE_ARENA;
144         int normalOffset = 0;
145
146         /* (subdivLevels == 0) is not allowed */
147         subdivLevels = MAX2(subdivLevels, 1);
148
149         if (prevSS) {
150                 int oldUseAging;
151
152                 ccgSubSurf_getUseAgeCounts(prevSS, &oldUseAging, NULL, NULL, NULL);
153
154                 if ((oldUseAging != useAging) ||
155                     (ccgSubSurf_getSimpleSubdiv(prevSS) != !!(flags & CCG_SIMPLE_SUBDIV)))
156                 {
157                         ccgSubSurf_free(prevSS);
158                 }
159                 else {
160                         ccgSubSurf_setSubdivisionLevels(prevSS, subdivLevels);
161
162                         return prevSS;
163                 }
164         }
165
166         if (useAging) {
167                 ifc.vertUserSize = ifc.edgeUserSize = ifc.faceUserSize = 12;
168         }
169         else {
170                 ifc.vertUserSize = ifc.edgeUserSize = ifc.faceUserSize = 8;
171         }
172         ifc.numLayers = numLayers;
173         ifc.vertDataSize = sizeof(float) * numLayers;
174         normalOffset += sizeof(float) * numLayers;
175         if (flags & CCG_CALC_NORMALS)
176                 ifc.vertDataSize += sizeof(float) * 3;
177         if (flags & CCG_ALLOC_MASK)
178                 ifc.vertDataSize += sizeof(float);
179         ifc.simpleSubdiv = !!(flags & CCG_SIMPLE_SUBDIV);
180
181         if (useArena) {
182                 CCGAllocatorIFC allocatorIFC;
183                 CCGAllocatorHDL allocator = BLI_memarena_new(MEM_SIZE_OPTIMAL(1 << 16), "subsurf arena");
184
185                 allocatorIFC.alloc = arena_alloc;
186                 allocatorIFC.realloc = arena_realloc;
187                 allocatorIFC.free = arena_free;
188                 allocatorIFC.release = arena_release;
189
190                 ccgSS = ccgSubSurf_new(&ifc, subdivLevels, &allocatorIFC, allocator);
191         }
192         else {
193                 ccgSS = ccgSubSurf_new(&ifc, subdivLevels, NULL, NULL);
194         }
195
196         if (useAging) {
197                 ccgSubSurf_setUseAgeCounts(ccgSS, 1, 8, 8, 8);
198         }
199
200         if (flags & CCG_ALLOC_MASK) {
201                 normalOffset += sizeof(float);
202                 /* mask is allocated after regular layers */
203                 ccgSubSurf_setAllocMask(ccgSS, 1, sizeof(float) * numLayers);
204         }
205         
206         if (flags & CCG_CALC_NORMALS)
207                 ccgSubSurf_setCalcVertexNormals(ccgSS, 1, normalOffset);
208         else
209                 ccgSubSurf_setCalcVertexNormals(ccgSS, 0, 0);
210
211         return ccgSS;
212 }
213
214 static int getEdgeIndex(CCGSubSurf *ss, CCGEdge *e, int x, int edgeSize)
215 {
216         CCGVert *v0 = ccgSubSurf_getEdgeVert0(e);
217         CCGVert *v1 = ccgSubSurf_getEdgeVert1(e);
218         int v0idx = *((int *) ccgSubSurf_getVertUserData(ss, v0));
219         int v1idx = *((int *) ccgSubSurf_getVertUserData(ss, v1));
220         int edgeBase = *((int *) ccgSubSurf_getEdgeUserData(ss, e));
221
222         if (x == 0) {
223                 return v0idx;
224         }
225         else if (x == edgeSize - 1) {
226                 return v1idx;
227         }
228         else {
229                 return edgeBase + x - 1;
230         }
231 }
232
233 static int getFaceIndex(CCGSubSurf *ss, CCGFace *f, int S, int x, int y, int edgeSize, int gridSize)
234 {
235         int faceBase = *((int *) ccgSubSurf_getFaceUserData(ss, f));
236         int numVerts = ccgSubSurf_getFaceNumVerts(f);
237
238         if (x == gridSize - 1 && y == gridSize - 1) {
239                 CCGVert *v = ccgSubSurf_getFaceVert(f, S);
240                 return *((int *) ccgSubSurf_getVertUserData(ss, v));
241         }
242         else if (x == gridSize - 1) {
243                 CCGVert *v = ccgSubSurf_getFaceVert(f, S);
244                 CCGEdge *e = ccgSubSurf_getFaceEdge(f, S);
245                 int edgeBase = *((int *) ccgSubSurf_getEdgeUserData(ss, e));
246                 if (v == ccgSubSurf_getEdgeVert0(e)) {
247                         return edgeBase + (gridSize - 1 - y) - 1;
248                 }
249                 else {
250                         return edgeBase + (edgeSize - 2 - 1) - ((gridSize - 1 - y) - 1);
251                 }
252         }
253         else if (y == gridSize - 1) {
254                 CCGVert *v = ccgSubSurf_getFaceVert(f, S);
255                 CCGEdge *e = ccgSubSurf_getFaceEdge(f, (S + numVerts - 1) % numVerts);
256                 int edgeBase = *((int *) ccgSubSurf_getEdgeUserData(ss, e));
257                 if (v == ccgSubSurf_getEdgeVert0(e)) {
258                         return edgeBase + (gridSize - 1 - x) - 1;
259                 }
260                 else {
261                         return edgeBase + (edgeSize - 2 - 1) - ((gridSize - 1 - x) - 1);
262                 }
263         }
264         else if (x == 0 && y == 0) {
265                 return faceBase;
266         }
267         else if (x == 0) {
268                 S = (S + numVerts - 1) % numVerts;
269                 return faceBase + 1 + (gridSize - 2) * S + (y - 1);
270         }
271         else if (y == 0) {
272                 return faceBase + 1 + (gridSize - 2) * S + (x - 1);
273         }
274         else {
275                 return faceBase + 1 + (gridSize - 2) * numVerts + S * (gridSize - 2) * (gridSize - 2) + (y - 1) * (gridSize - 2) + (x - 1);
276         }
277 }
278
279 static void get_face_uv_map_vert(UvVertMap *vmap, struct MPoly *mpoly, struct MLoop *ml, int fi, CCGVertHDL *fverts)
280 {
281         UvMapVert *v, *nv;
282         int j, nverts = mpoly[fi].totloop;
283
284         for (j = 0; j < nverts; j++) {
285                 for (nv = v = BKE_mesh_uv_vert_map_get_vert(vmap, ml[j].v); v; v = v->next) {
286                         if (v->separate)
287                                 nv = v;
288                         if (v->f == fi)
289                                 break;
290                 }
291
292                 fverts[j] = SET_UINT_IN_POINTER(mpoly[nv->f].loopstart + nv->tfindex);
293         }
294 }
295
296 static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm, MLoopUV *mloopuv)
297 {
298         MPoly *mpoly = dm->getPolyArray(dm);
299         MLoop *mloop = dm->getLoopArray(dm);
300         MVert *mvert = dm->getVertArray(dm);
301         int totvert = dm->getNumVerts(dm);
302         int totface = dm->getNumPolys(dm);
303         int i, seam;
304         UvMapVert *v;
305         UvVertMap *vmap;
306         float limit[2];
307 #ifndef USE_DYNSIZE
308         CCGVertHDL *fverts = NULL;
309         BLI_array_declare(fverts);
310 #endif
311         EdgeSet *eset;
312         float creaseFactor = (float)ccgSubSurf_getSubdivisionLevels(ss);
313         float uv[3] = {0.0f, 0.0f, 0.0f}; /* only first 2 values are written into */
314
315         limit[0] = limit[1] = STD_UV_CONNECT_LIMIT;
316         /* previous behavior here is without accounting for winding, however this causes stretching in
317          * UV map in really simple cases with mirror + subsurf, see second part of T44530. Also, initially
318          * intention is to treat merged vertices from mirror modifier as seams, see code below with ME_VERT_MERGED
319          * This fixes a very old regression (2.49 was correct here) */
320         vmap = BKE_mesh_uv_vert_map_create(mpoly, mloop, mloopuv, totface, totvert, limit, false, true);
321         if (!vmap)
322                 return 0;
323         
324         ccgSubSurf_initFullSync(ss);
325
326         /* create vertices */
327         for (i = 0; i < totvert; i++) {
328                 if (!BKE_mesh_uv_vert_map_get_vert(vmap, i))
329                         continue;
330
331                 for (v = BKE_mesh_uv_vert_map_get_vert(vmap, i)->next; v; v = v->next)
332                         if (v->separate)
333                                 break;
334
335                 seam = (v != NULL) || ((mvert + i)->flag & ME_VERT_MERGED);
336
337                 for (v = BKE_mesh_uv_vert_map_get_vert(vmap, i); v; v = v->next) {
338                         if (v->separate) {
339                                 CCGVert *ssv;
340                                 int loopid = mpoly[v->f].loopstart + v->tfindex;
341                                 CCGVertHDL vhdl = SET_INT_IN_POINTER(loopid);
342
343                                 copy_v2_v2(uv, mloopuv[loopid].uv);
344
345                                 ccgSubSurf_syncVert(ss, vhdl, uv, seam, &ssv);
346                         }
347                 }
348         }
349
350         /* create edges */
351         eset = BLI_edgeset_new_ex(__func__, BLI_EDGEHASH_SIZE_GUESS_FROM_POLYS(totface));
352
353         for (i = 0; i < totface; i++) {
354                 MPoly *mp = &mpoly[i];
355                 int nverts = mp->totloop;
356                 int j, j_next;
357                 CCGFace *origf = ccgSubSurf_getFace(origss, SET_INT_IN_POINTER(i));
358                 /* unsigned int *fv = &mp->v1; */
359                 MLoop *ml = mloop + mp->loopstart;
360
361 #ifdef USE_DYNSIZE
362                 CCGVertHDL fverts[nverts];
363 #else
364                 BLI_array_empty(fverts);
365                 BLI_array_grow_items(fverts, nverts);
366 #endif
367
368                 get_face_uv_map_vert(vmap, mpoly, ml, i, fverts);
369
370                 for (j = 0, j_next = nverts - 1; j < nverts; j_next = j++) {
371                         unsigned int v0 = GET_UINT_FROM_POINTER(fverts[j_next]);
372                         unsigned int v1 = GET_UINT_FROM_POINTER(fverts[j]);
373                         MVert *mv0 = mvert + (ml[j_next].v);
374                         MVert *mv1 = mvert + (ml[j].v);
375
376                         if (BLI_edgeset_add(eset, v0, v1)) {
377                                 CCGEdge *e, *orige = ccgSubSurf_getFaceEdge(origf, j_next);
378                                 CCGEdgeHDL ehdl = SET_INT_IN_POINTER(mp->loopstart + j_next);
379                                 float crease;
380
381                                 if ((mv0->flag & mv1->flag) & ME_VERT_MERGED)
382                                         crease = creaseFactor;
383                                 else
384                                         crease = ccgSubSurf_getEdgeCrease(orige);
385
386                                 ccgSubSurf_syncEdge(ss, ehdl, fverts[j_next], fverts[j], crease, &e);
387                         }
388                 }
389         }
390
391         BLI_edgeset_free(eset);
392
393         /* create faces */
394         for (i = 0; i < totface; i++) {
395                 MPoly *mp = &mpoly[i];
396                 MLoop *ml = &mloop[mp->loopstart];
397                 int nverts = mp->totloop;
398                 CCGFace *f;
399
400 #ifdef USE_DYNSIZE
401                 CCGVertHDL fverts[nverts];
402 #else
403                 BLI_array_empty(fverts);
404                 BLI_array_grow_items(fverts, nverts);
405 #endif
406
407                 get_face_uv_map_vert(vmap, mpoly, ml, i, fverts);
408                 ccgSubSurf_syncFace(ss, SET_INT_IN_POINTER(i), nverts, fverts, &f);
409         }
410
411 #ifndef USE_DYNSIZE
412         BLI_array_free(fverts);
413 #endif
414
415         BKE_mesh_uv_vert_map_free(vmap);
416         ccgSubSurf_processSync(ss);
417
418         return 1;
419 }
420
421 #ifdef WITH_OPENSUBDIV
422 static void UNUSED_FUNCTION(set_subsurf_osd_ccg_uv)(CCGSubSurf *ss,
423                                                     DerivedMesh *dm,
424                                                     DerivedMesh *result,
425                                                     int layer_index)
426 {
427         CCGFace **faceMap;
428         MTFace *tf;
429         MLoopUV *mluv;
430         CCGFaceIterator fi;
431         int index, gridSize, gridFaces, totface, x, y, S;
432         MLoopUV *dmloopuv = CustomData_get_layer_n(&dm->loopData, CD_MLOOPUV, layer_index);
433         /* need to update both CD_MTFACE & CD_MLOOPUV, hrmf, we could get away with
434          * just tface except applying the modifier then looses subsurf UV */
435         MTFace *tface = CustomData_get_layer_n(&result->faceData, CD_MTFACE, layer_index);
436         MLoopUV *mloopuv = CustomData_get_layer_n(&result->loopData, CD_MLOOPUV, layer_index);
437
438         if (dmloopuv == NULL || (tface == NULL && mloopuv == NULL)) {
439                 return;
440         }
441
442         ccgSubSurf_evaluatorSetFVarUV(ss, dm, layer_index);
443
444         /* get some info from CCGSubSurf */
445         totface = ccgSubSurf_getNumFaces(ss);
446         gridSize = ccgSubSurf_getGridSize(ss);
447         gridFaces = gridSize - 1;
448
449         /* make a map from original faces to CCGFaces */
450         faceMap = MEM_mallocN(totface * sizeof(*faceMap), "facemapuv");
451         for (ccgSubSurf_initFaceIterator(ss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
452                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
453                 faceMap[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f))] = f;
454         }
455
456         /* load coordinates from uvss into tface */
457         tf = tface;
458         mluv = mloopuv;
459         for (index = 0; index < totface; index++) {
460                 CCGFace *f = faceMap[index];
461                 int numVerts = ccgSubSurf_getFaceNumVerts(f);
462                 for (S = 0; S < numVerts; S++) {
463                         for (y = 0; y < gridFaces; y++) {
464                                 for (x = 0; x < gridFaces; x++) {
465                                         const int delta[4][2] = {{0, 0},
466                                                                  {0, 1},
467                                                                  {1, 1},
468                                                                  {1, 0}};
469                                         float uv[4][2];
470                                         int i;
471                                         for (i = 0; i < 4; i++) {
472                                                 const int dx = delta[i][0],
473                                                           dy = delta[i][1];
474                                                 const float grid_u = ((float)(x + dx)) / (gridSize - 1),
475                                                             grid_v = ((float)(y + dy)) / (gridSize - 1);
476                                                 ccgSubSurf_evaluatorFVarUV(ss,
477                                                                            index,
478                                                                            S,
479                                                                            grid_u, grid_v,
480                                                                            uv[i]);
481                                         }
482                                         if (tf) {
483                                                 copy_v2_v2(tf->uv[0], uv[0]);
484                                                 copy_v2_v2(tf->uv[1], uv[1]);
485                                                 copy_v2_v2(tf->uv[2], uv[2]);
486                                                 copy_v2_v2(tf->uv[3], uv[3]);
487                                                 tf++;
488                                         }
489                                         if (mluv) {
490                                                 copy_v2_v2(mluv[0].uv, uv[0]);
491                                                 copy_v2_v2(mluv[1].uv, uv[1]);
492                                                 copy_v2_v2(mluv[2].uv, uv[2]);
493                                                 copy_v2_v2(mluv[3].uv, uv[3]);
494                                                 mluv += 4;
495                                         }
496                                 }
497                         }
498                 }
499         }
500         MEM_freeN(faceMap);
501 }
502 #endif  /* WITH_OPENSUBDIV */
503
504 static void set_subsurf_legacy_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh *result, int n)
505 {
506         CCGSubSurf *uvss;
507         CCGFace **faceMap;
508         MTFace *tf;
509         MLoopUV *mluv;
510         CCGFaceIterator fi;
511         int index, gridSize, gridFaces, /*edgeSize,*/ totface, x, y, S;
512         MLoopUV *dmloopuv = CustomData_get_layer_n(&dm->loopData, CD_MLOOPUV, n);
513         /* need to update both CD_MTFACE & CD_MLOOPUV, hrmf, we could get away with
514          * just tface except applying the modifier then looses subsurf UV */
515         MTFace *tface = CustomData_get_layer_n(&result->faceData, CD_MTFACE, n);
516         MLoopUV *mloopuv = CustomData_get_layer_n(&result->loopData, CD_MLOOPUV, n);
517
518         if (!dmloopuv || (!tface && !mloopuv))
519                 return;
520
521         /* create a CCGSubSurf from uv's */
522         uvss = _getSubSurf(NULL, ccgSubSurf_getSubdivisionLevels(ss), 2, CCG_USE_ARENA);
523
524         if (!ss_sync_from_uv(uvss, ss, dm, dmloopuv)) {
525                 ccgSubSurf_free(uvss);
526                 return;
527         }
528
529         /* get some info from CCGSubSurf */
530         totface = ccgSubSurf_getNumFaces(uvss);
531         /* edgeSize = ccgSubSurf_getEdgeSize(uvss); */ /*UNUSED*/
532         gridSize = ccgSubSurf_getGridSize(uvss);
533         gridFaces = gridSize - 1;
534
535         /* make a map from original faces to CCGFaces */
536         faceMap = MEM_mallocN(totface * sizeof(*faceMap), "facemapuv");
537         for (ccgSubSurf_initFaceIterator(uvss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
538                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
539                 faceMap[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f))] = f;
540         }
541
542         /* load coordinates from uvss into tface */
543         tf = tface;
544         mluv = mloopuv;
545
546         for (index = 0; index < totface; index++) {
547                 CCGFace *f = faceMap[index];
548                 int numVerts = ccgSubSurf_getFaceNumVerts(f);
549
550                 for (S = 0; S < numVerts; S++) {
551                         float (*faceGridData)[2] = ccgSubSurf_getFaceGridDataArray(uvss, f, S);
552
553                         for (y = 0; y < gridFaces; y++) {
554                                 for (x = 0; x < gridFaces; x++) {
555                                         float *a = faceGridData[(y + 0) * gridSize + x + 0];
556                                         float *b = faceGridData[(y + 0) * gridSize + x + 1];
557                                         float *c = faceGridData[(y + 1) * gridSize + x + 1];
558                                         float *d = faceGridData[(y + 1) * gridSize + x + 0];
559
560                                         if (tf) {
561                                                 copy_v2_v2(tf->uv[0], a);
562                                                 copy_v2_v2(tf->uv[1], d);
563                                                 copy_v2_v2(tf->uv[2], c);
564                                                 copy_v2_v2(tf->uv[3], b);
565                                                 tf++;
566                                         }
567
568                                         if (mluv) {
569                                                 copy_v2_v2(mluv[0].uv, a);
570                                                 copy_v2_v2(mluv[1].uv, d);
571                                                 copy_v2_v2(mluv[2].uv, c);
572                                                 copy_v2_v2(mluv[3].uv, b);
573                                                 mluv += 4;
574                                         }
575
576                                 }
577                         }
578                 }
579         }
580
581         ccgSubSurf_free(uvss);
582         MEM_freeN(faceMap);
583 }
584
585 static void set_subsurf_uv(CCGSubSurf *ss,
586                            DerivedMesh *dm,
587                            DerivedMesh *result,
588                            int layer_index)
589 {
590 #ifdef WITH_OPENSUBDIV
591         if (!ccgSubSurf_needGrids(ss)) {
592                 /* GPU backend is used, no need to evaluate UVs on CPU. */
593                 /* TODO(sergey): Think of how to support edit mode of UVs. */
594         }
595         else
596 #endif
597         {
598                 set_subsurf_legacy_uv(ss, dm, result, layer_index);
599         }
600 }
601
602 /* face weighting */
603 typedef struct FaceVertWeightEntry {
604         FaceVertWeight *weight;
605         float *w;
606         int valid;
607 } FaceVertWeightEntry;
608
609 typedef struct WeightTable {
610         FaceVertWeightEntry *weight_table;
611         int len;
612 } WeightTable;
613
614 static float *get_ss_weights(WeightTable *wtable, int gridCuts, int faceLen)
615 {
616         int x, y, i, j;
617         float *w, w1, w2, w4, fac, fac2, fx, fy;
618
619         if (wtable->len <= faceLen) {
620                 void *tmp = MEM_callocN(sizeof(FaceVertWeightEntry) * (faceLen + 1), "weight table alloc 2");
621                 
622                 if (wtable->len) {
623                         memcpy(tmp, wtable->weight_table, sizeof(FaceVertWeightEntry) * wtable->len);
624                         MEM_freeN(wtable->weight_table);
625                 }
626                 
627                 wtable->weight_table = tmp;
628                 wtable->len = faceLen + 1;
629         }
630
631         if (!wtable->weight_table[faceLen].valid) {
632                 wtable->weight_table[faceLen].valid = 1;
633                 wtable->weight_table[faceLen].w = w = MEM_callocN(sizeof(float) * faceLen * faceLen * (gridCuts + 2) * (gridCuts + 2), "weight table alloc");
634                 fac = 1.0f / (float)faceLen;
635
636                 for (i = 0; i < faceLen; i++) {
637                         for (x = 0; x < gridCuts + 2; x++) {
638                                 for (y = 0; y < gridCuts + 2; y++) {
639                                         fx = 0.5f - (float)x / (float)(gridCuts + 1) / 2.0f;
640                                         fy = 0.5f - (float)y / (float)(gridCuts + 1) / 2.0f;
641                                 
642                                         fac2 = faceLen - 4;
643                                         w1 = (1.0f - fx) * (1.0f - fy) + (-fac2 * fx * fy * fac);
644                                         w2 = (1.0f - fx + fac2 * fx * -fac) * (fy);
645                                         w4 = (fx) * (1.0f - fy + -fac2 * fy * fac);
646
647                                         /* these values aren't used for tri's and cause divide by zero */
648                                         if (faceLen > 3) {
649                                                 fac2 = 1.0f - (w1 + w2 + w4);
650                                                 fac2 = fac2 / (float)(faceLen - 3);
651                                                 for (j = 0; j < faceLen; j++) {
652                                                         w[j] = fac2;
653                                                 }
654                                         }
655                                         
656                                         w[i] = w1;
657                                         w[(i - 1 + faceLen) % faceLen] = w2;
658                                         w[(i + 1) % faceLen] = w4;
659
660                                         w += faceLen;
661                                 }
662                         }
663                 }
664         }
665
666         return wtable->weight_table[faceLen].w;
667 }
668
669 static void free_ss_weights(WeightTable *wtable)
670 {
671         int i;
672
673         for (i = 0; i < wtable->len; i++) {
674                 if (wtable->weight_table[i].valid)
675                         MEM_freeN(wtable->weight_table[i].w);
676         }
677         
678         if (wtable->weight_table)
679                 MEM_freeN(wtable->weight_table);
680 }
681
682 static void ss_sync_ccg_from_derivedmesh(CCGSubSurf *ss,
683                                          DerivedMesh *dm,
684                                          float (*vertexCos)[3],
685                                          int useFlatSubdiv)
686 {
687         float creaseFactor = (float) ccgSubSurf_getSubdivisionLevels(ss);
688 #ifndef USE_DYNSIZE
689         CCGVertHDL *fVerts = NULL;
690         BLI_array_declare(fVerts);
691 #endif
692         MVert *mvert = dm->getVertArray(dm);
693         MEdge *medge = dm->getEdgeArray(dm);
694         /* MFace *mface = dm->getTessFaceArray(dm); */ /* UNUSED */
695         MVert *mv;
696         MEdge *me;
697         MLoop *mloop = dm->getLoopArray(dm), *ml;
698         MPoly *mpoly = dm->getPolyArray(dm), *mp;
699         /*MFace *mf;*/ /*UNUSED*/
700         int totvert = dm->getNumVerts(dm);
701         int totedge = dm->getNumEdges(dm);
702         /*int totface = dm->getNumTessFaces(dm);*/ /*UNUSED*/
703         /*int totpoly = dm->getNumFaces(dm);*/ /*UNUSED*/
704         int i, j;
705         int *index;
706
707         ccgSubSurf_initFullSync(ss);
708
709         mv = mvert;
710         index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
711         for (i = 0; i < totvert; i++, mv++) {
712                 CCGVert *v;
713
714                 if (vertexCos) {
715                         ccgSubSurf_syncVert(ss, SET_INT_IN_POINTER(i), vertexCos[i], 0, &v);
716                 }
717                 else {
718                         ccgSubSurf_syncVert(ss, SET_INT_IN_POINTER(i), mv->co, 0, &v);
719                 }
720
721                 ((int *)ccgSubSurf_getVertUserData(ss, v))[1] = (index) ? *index++ : i;
722         }
723
724         me = medge;
725         index = (int *)dm->getEdgeDataArray(dm, CD_ORIGINDEX);
726         for (i = 0; i < totedge; i++, me++) {
727                 CCGEdge *e;
728                 float crease;
729
730                 crease = useFlatSubdiv ? creaseFactor :
731                          me->crease * creaseFactor / 255.0f;
732
733                 ccgSubSurf_syncEdge(ss, SET_INT_IN_POINTER(i), SET_UINT_IN_POINTER(me->v1),
734                                     SET_UINT_IN_POINTER(me->v2), crease, &e);
735
736                 ((int *)ccgSubSurf_getEdgeUserData(ss, e))[1] = (index) ? *index++ : i;
737         }
738
739         mp = mpoly;
740         index = (int *)dm->getPolyDataArray(dm, CD_ORIGINDEX);
741         for (i = 0; i < dm->numPolyData; i++, mp++) {
742                 CCGFace *f;
743
744 #ifdef USE_DYNSIZE
745                 CCGVertHDL fVerts[mp->totloop];
746 #else
747                 BLI_array_empty(fVerts);
748                 BLI_array_grow_items(fVerts, mp->totloop);
749 #endif
750
751                 ml = mloop + mp->loopstart;
752                 for (j = 0; j < mp->totloop; j++, ml++) {
753                         fVerts[j] = SET_UINT_IN_POINTER(ml->v);
754                 }
755
756                 /* this is very bad, means mesh is internally inconsistent.
757                  * it is not really possible to continue without modifying
758                  * other parts of code significantly to handle missing faces.
759                  * since this really shouldn't even be possible we just bail.*/
760                 if (ccgSubSurf_syncFace(ss, SET_INT_IN_POINTER(i), mp->totloop,
761                                         fVerts, &f) == eCCGError_InvalidValue)
762                 {
763                         static int hasGivenError = 0;
764
765                         if (!hasGivenError) {
766                                 //XXX error("Unrecoverable error in SubSurf calculation,"
767                                 //      " mesh is inconsistent.");
768
769                                 hasGivenError = 1;
770                         }
771
772                         return;
773                 }
774
775                 ((int *)ccgSubSurf_getFaceUserData(ss, f))[1] = (index) ? *index++ : i;
776         }
777
778         ccgSubSurf_processSync(ss);
779
780 #ifndef USE_DYNSIZE
781         BLI_array_free(fVerts);
782 #endif
783 }
784
785 #ifdef WITH_OPENSUBDIV
786 static void ss_sync_osd_from_derivedmesh(CCGSubSurf *ss,
787                                          DerivedMesh *dm)
788 {
789         ccgSubSurf_initFullSync(ss);
790         ccgSubSurf_prepareTopologyRefiner(ss, dm);
791         ccgSubSurf_processSync(ss);
792 }
793 #endif  /* WITH_OPENSUBDIV */
794
795 static void ss_sync_from_derivedmesh(CCGSubSurf *ss,
796                                      DerivedMesh *dm,
797                                      float (*vertexCos)[3],
798                                      int use_flat_subdiv)
799 {
800 #ifdef WITH_OPENSUBDIV
801         /* Reset all related descriptors if actual mesh topology changed or if
802          * other evaluation-related settings changed.
803          */
804         if (!ccgSubSurf_needGrids(ss)) {
805                 /* TODO(sergey): Use vertex coordinates and flat subdiv flag. */
806                 ccgSubSurf_checkTopologyChanged(ss, dm);
807                 ss_sync_osd_from_derivedmesh(ss, dm);
808         }
809         else
810 #endif
811         {
812                 ss_sync_ccg_from_derivedmesh(ss, dm, vertexCos, use_flat_subdiv);
813         }
814 }
815
816 /***/
817
818 static int ccgDM_getVertMapIndex(CCGSubSurf *ss, CCGVert *v)
819 {
820         return ((int *) ccgSubSurf_getVertUserData(ss, v))[1];
821 }
822
823 static int ccgDM_getEdgeMapIndex(CCGSubSurf *ss, CCGEdge *e)
824 {
825         return ((int *) ccgSubSurf_getEdgeUserData(ss, e))[1];
826 }
827
828 static int ccgDM_getFaceMapIndex(CCGSubSurf *ss, CCGFace *f)
829 {
830         return ((int *) ccgSubSurf_getFaceUserData(ss, f))[1];
831 }
832
833 static void minmax_v3_v3v3(const float vec[3], float min[3], float max[3])
834 {
835         if (min[0] > vec[0]) min[0] = vec[0];
836         if (min[1] > vec[1]) min[1] = vec[1];
837         if (min[2] > vec[2]) min[2] = vec[2];
838         if (max[0] < vec[0]) max[0] = vec[0];
839         if (max[1] < vec[1]) max[1] = vec[1];
840         if (max[2] < vec[2]) max[2] = vec[2];
841 }
842
843 static void ccgDM_getMinMax(DerivedMesh *dm, float r_min[3], float r_max[3])
844 {
845         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
846         CCGSubSurf *ss = ccgdm->ss;
847         CCGVertIterator vi;
848         CCGEdgeIterator ei;
849         CCGFaceIterator fi;
850         CCGKey key;
851         int i, edgeSize = ccgSubSurf_getEdgeSize(ss);
852         int gridSize = ccgSubSurf_getGridSize(ss);
853
854 #ifdef WITH_OPENSUBDIV
855         if (ccgdm->useGpuBackend) {
856                 ccgSubSurf_getMinMax(ccgdm->ss, r_min, r_max);
857                 return;
858         }
859 #endif
860
861         CCG_key_top_level(&key, ss);
862
863         if (!ccgSubSurf_getNumVerts(ss))
864                 r_min[0] = r_min[1] = r_min[2] = r_max[0] = r_max[1] = r_max[2] = 0.0;
865
866         for (ccgSubSurf_initVertIterator(ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) {
867                 CCGVert *v = ccgVertIterator_getCurrent(&vi);
868                 float *co = ccgSubSurf_getVertData(ss, v);
869
870                 minmax_v3_v3v3(co, r_min, r_max);
871         }
872
873         for (ccgSubSurf_initEdgeIterator(ss, &ei); !ccgEdgeIterator_isStopped(&ei); ccgEdgeIterator_next(&ei)) {
874                 CCGEdge *e = ccgEdgeIterator_getCurrent(&ei);
875                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
876
877                 for (i = 0; i < edgeSize; i++)
878                         minmax_v3_v3v3(CCG_elem_offset_co(&key, edgeData, i), r_min, r_max);
879         }
880
881         for (ccgSubSurf_initFaceIterator(ss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
882                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
883                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
884
885                 for (S = 0; S < numVerts; S++) {
886                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
887
888                         for (y = 0; y < gridSize; y++)
889                                 for (x = 0; x < gridSize; x++)
890                                         minmax_v3_v3v3(CCG_grid_elem_co(&key, faceGridData, x, y), r_min, r_max);
891                 }
892         }
893 }
894
895 static int ccgDM_getNumVerts(DerivedMesh *dm)
896 {
897         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
898
899         return ccgSubSurf_getNumFinalVerts(ccgdm->ss);
900 }
901
902 static int ccgDM_getNumEdges(DerivedMesh *dm)
903 {
904         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
905
906         return ccgSubSurf_getNumFinalEdges(ccgdm->ss);
907 }
908
909 static int ccgDM_getNumPolys(DerivedMesh *dm)
910 {
911         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
912
913         return ccgSubSurf_getNumFinalFaces(ccgdm->ss);
914 }
915
916 static int ccgDM_getNumTessFaces(DerivedMesh *dm)
917 {
918         return dm->numTessFaceData;
919 }
920
921 static int ccgDM_getNumLoops(DerivedMesh *dm)
922 {
923         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
924
925         /* All subsurf faces are quads */
926         return 4 * ccgSubSurf_getNumFinalFaces(ccgdm->ss);
927 }
928
929 static void ccgDM_getFinalVert(DerivedMesh *dm, int vertNum, MVert *mv)
930 {
931         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
932         CCGSubSurf *ss = ccgdm->ss;
933         CCGElem *vd;
934         CCGKey key;
935         int i;
936
937         CCG_key_top_level(&key, ss);
938         memset(mv, 0, sizeof(*mv));
939
940         if ((vertNum < ccgdm->edgeMap[0].startVert) && (ccgSubSurf_getNumFaces(ss) > 0)) {
941                 /* this vert comes from face data */
942                 int lastface = ccgSubSurf_getNumFaces(ss) - 1;
943                 CCGFace *f;
944                 int x, y, grid, numVerts;
945                 int offset;
946                 int gridSize = ccgSubSurf_getGridSize(ss);
947                 int gridSideVerts;
948                 int gridInternalVerts;
949                 int gridSideEnd;
950                 int gridInternalEnd;
951
952                 i = 0;
953                 while (i < lastface && vertNum >= ccgdm->faceMap[i + 1].startVert) {
954                         i++;
955                 }
956
957                 f = ccgdm->faceMap[i].face;
958                 numVerts = ccgSubSurf_getFaceNumVerts(f);
959
960                 gridSideVerts = gridSize - 2;
961                 gridInternalVerts = gridSideVerts * gridSideVerts;
962
963                 gridSideEnd = 1 + numVerts * gridSideVerts;
964                 gridInternalEnd = gridSideEnd + numVerts * gridInternalVerts;
965
966                 offset = vertNum - ccgdm->faceMap[i].startVert;
967                 if (offset < 1) {
968                         vd = ccgSubSurf_getFaceCenterData(f);
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 < gridSideEnd) {
973                         offset -= 1;
974                         grid = offset / gridSideVerts;
975                         x = offset % gridSideVerts + 1;
976                         vd = ccgSubSurf_getFaceGridEdgeData(ss, f, grid, x);
977                         copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
978                         normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
979                 }
980                 else if (offset < gridInternalEnd) {
981                         offset -= gridSideEnd;
982                         grid = offset / gridInternalVerts;
983                         offset %= gridInternalVerts;
984                         y = offset / gridSideVerts + 1;
985                         x = offset % gridSideVerts + 1;
986                         vd = ccgSubSurf_getFaceGridData(ss, f, grid, x, y);
987                         copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
988                         normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
989                 }
990         }
991         else if ((vertNum < ccgdm->vertMap[0].startVert) && (ccgSubSurf_getNumEdges(ss) > 0)) {
992                 /* this vert comes from edge data */
993                 CCGEdge *e;
994                 int lastedge = ccgSubSurf_getNumEdges(ss) - 1;
995                 int x;
996
997                 i = 0;
998                 while (i < lastedge && vertNum >= ccgdm->edgeMap[i + 1].startVert) {
999                         i++;
1000                 }
1001
1002                 e = ccgdm->edgeMap[i].edge;
1003
1004                 x = vertNum - ccgdm->edgeMap[i].startVert + 1;
1005                 vd = ccgSubSurf_getEdgeData(ss, e, x);
1006                 copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
1007                 normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
1008         }
1009         else {
1010                 /* this vert comes from vert data */
1011                 CCGVert *v;
1012                 i = vertNum - ccgdm->vertMap[0].startVert;
1013
1014                 v = ccgdm->vertMap[i].vert;
1015                 vd = ccgSubSurf_getVertData(ss, v);
1016                 copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
1017                 normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
1018         }
1019 }
1020
1021 static void ccgDM_getFinalVertCo(DerivedMesh *dm, int vertNum, float r_co[3])
1022 {
1023         MVert mvert;
1024
1025         ccgDM_getFinalVert(dm, vertNum, &mvert);
1026         copy_v3_v3(r_co, mvert.co);
1027 }
1028
1029 static void ccgDM_getFinalVertNo(DerivedMesh *dm, int vertNum, float r_no[3])
1030 {
1031         MVert mvert;
1032
1033         ccgDM_getFinalVert(dm, vertNum, &mvert);
1034         normal_short_to_float_v3(r_no, mvert.no);
1035 }
1036
1037 static void ccgDM_getFinalEdge(DerivedMesh *dm, int edgeNum, MEdge *med)
1038 {
1039         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1040         CCGSubSurf *ss = ccgdm->ss;
1041         int i;
1042
1043         memset(med, 0, sizeof(*med));
1044
1045         if (edgeNum < ccgdm->edgeMap[0].startEdge) {
1046                 /* this edge comes from face data */
1047                 int lastface = ccgSubSurf_getNumFaces(ss) - 1;
1048                 CCGFace *f;
1049                 int x, y, grid /*, numVerts*/;
1050                 int offset;
1051                 int gridSize = ccgSubSurf_getGridSize(ss);
1052                 int edgeSize = ccgSubSurf_getEdgeSize(ss);
1053                 int gridSideEdges;
1054                 int gridInternalEdges;
1055
1056                 /* code added in bmesh but works correctly without, commenting - campbell */
1057 #if 0
1058                 int lasti, previ;
1059                 i = lastface;
1060                 lasti = 0;
1061                 while (1) {
1062                         previ = i;
1063                         if (ccgdm->faceMap[i].startEdge >= edgeNum) {
1064                                 i -= fabsf(i - lasti) / 2.0f;
1065                         }
1066                         else if (ccgdm->faceMap[i].startEdge < edgeNum) {
1067                                 i += fabsf(i - lasti) / 2.0f;
1068                         }
1069                         else {
1070                                 break;
1071                         }
1072
1073                         if (i < 0) {
1074                                 i = 0;
1075                                 break;
1076                         }
1077
1078                         if (i > lastface) {
1079                                 i = lastface;
1080                                 break;
1081
1082                         }
1083
1084                         if (i == lasti)
1085                                 break;
1086
1087                         lasti = previ;
1088                 }
1089
1090                 i = i > 0 ? i - 1 : i;
1091 #endif
1092
1093                 i = 0;
1094                 while (i < lastface && edgeNum >= ccgdm->faceMap[i + 1].startEdge) {
1095                         i++;
1096                 }
1097
1098                 f = ccgdm->faceMap[i].face;
1099                 /* numVerts = ccgSubSurf_getFaceNumVerts(f); */ /*UNUSED*/
1100
1101                 gridSideEdges = gridSize - 1;
1102                 gridInternalEdges = (gridSideEdges - 1) * gridSideEdges * 2; 
1103
1104                 offset = edgeNum - ccgdm->faceMap[i].startEdge;
1105                 grid = offset / (gridSideEdges + gridInternalEdges);
1106                 offset %= (gridSideEdges + gridInternalEdges);
1107
1108                 if (offset < gridSideEdges) {
1109                         x = offset;
1110                         med->v1 = getFaceIndex(ss, f, grid, x, 0, edgeSize, gridSize);
1111                         med->v2 = getFaceIndex(ss, f, grid, x + 1, 0, edgeSize, gridSize);
1112                 }
1113                 else {
1114                         offset -= gridSideEdges;
1115                         x = (offset / 2) / gridSideEdges + 1;
1116                         y = (offset / 2) % gridSideEdges;
1117                         if (offset % 2 == 0) {
1118                                 med->v1 = getFaceIndex(ss, f, grid, x, y, edgeSize, gridSize);
1119                                 med->v2 = getFaceIndex(ss, f, grid, x, y + 1, edgeSize, gridSize);
1120                         }
1121                         else {
1122                                 med->v1 = getFaceIndex(ss, f, grid, y, x, edgeSize, gridSize);
1123                                 med->v2 = getFaceIndex(ss, f, grid, y + 1, x, edgeSize, gridSize);
1124                         }
1125                 }
1126         }
1127         else {
1128                 /* this vert comes from edge data */
1129                 CCGEdge *e;
1130                 int edgeSize = ccgSubSurf_getEdgeSize(ss);
1131                 int x;
1132                 short *edgeFlag;
1133                 unsigned int flags = 0;
1134
1135                 i = (edgeNum - ccgdm->edgeMap[0].startEdge) / (edgeSize - 1);
1136
1137                 e = ccgdm->edgeMap[i].edge;
1138
1139                 if (!ccgSubSurf_getEdgeNumFaces(e)) flags |= ME_LOOSEEDGE;
1140
1141                 x = edgeNum - ccgdm->edgeMap[i].startEdge;
1142
1143                 med->v1 = getEdgeIndex(ss, e, x, edgeSize);
1144                 med->v2 = getEdgeIndex(ss, e, x + 1, edgeSize);
1145
1146                 edgeFlag = (ccgdm->edgeFlags) ? &ccgdm->edgeFlags[i] : NULL;
1147                 if (edgeFlag)
1148                         flags |= (*edgeFlag & (ME_SEAM | ME_SHARP)) | ME_EDGEDRAW | ME_EDGERENDER;
1149                 else
1150                         flags |= ME_EDGEDRAW | ME_EDGERENDER;
1151
1152                 med->flag = flags;
1153         }
1154 }
1155
1156 static void ccgDM_getFinalFace(DerivedMesh *dm, int faceNum, MFace *mf)
1157 {
1158         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1159         CCGSubSurf *ss = ccgdm->ss;
1160         int gridSize = ccgSubSurf_getGridSize(ss);
1161         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1162         int gridSideEdges = gridSize - 1;
1163         int gridFaces = gridSideEdges * gridSideEdges;
1164         int i;
1165         CCGFace *f;
1166         /*int numVerts;*/
1167         int offset;
1168         int grid;
1169         int x, y;
1170         /*int lastface = ccgSubSurf_getNumFaces(ss) - 1;*/ /*UNUSED*/
1171         DMFlagMat *faceFlags = ccgdm->faceFlags;
1172
1173         memset(mf, 0, sizeof(*mf));
1174         if (faceNum >= ccgdm->dm.numTessFaceData)
1175                 return;
1176
1177         i = ccgdm->reverseFaceMap[faceNum];
1178
1179         f = ccgdm->faceMap[i].face;
1180         /*numVerts = ccgSubSurf_getFaceNumVerts(f);*/ /*UNUSED*/
1181
1182         offset = faceNum - ccgdm->faceMap[i].startFace;
1183         grid = offset / gridFaces;
1184         offset %= gridFaces;
1185         y = offset / gridSideEdges;
1186         x = offset % gridSideEdges;
1187
1188         mf->v1 = getFaceIndex(ss, f, grid, x + 0, y + 0, edgeSize, gridSize);
1189         mf->v2 = getFaceIndex(ss, f, grid, x + 0, y + 1, edgeSize, gridSize);
1190         mf->v3 = getFaceIndex(ss, f, grid, x + 1, y + 1, edgeSize, gridSize);
1191         mf->v4 = getFaceIndex(ss, f, grid, x + 1, y + 0, edgeSize, gridSize);
1192
1193         if (faceFlags) {
1194                 mf->flag = faceFlags[i].flag;
1195                 mf->mat_nr = faceFlags[i].mat_nr;
1196         }
1197         else {
1198                 mf->flag = ME_SMOOTH;
1199         }
1200
1201         mf->edcode = 0;
1202 }
1203
1204 /* Translate GridHidden into the ME_HIDE flag for MVerts. Assumes
1205  * vertices are in the order output by ccgDM_copyFinalVertArray. */
1206 void subsurf_copy_grid_hidden(DerivedMesh *dm, const MPoly *mpoly,
1207                               MVert *mvert, const MDisps *mdisps)
1208 {
1209         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
1210         CCGSubSurf *ss = ccgdm->ss;
1211         int level = ccgSubSurf_getSubdivisionLevels(ss);
1212         int gridSize = ccgSubSurf_getGridSize(ss);
1213         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1214         int totface = ccgSubSurf_getNumFaces(ss);
1215         int i, j, x, y;
1216         
1217         for (i = 0; i < totface; i++) {
1218                 CCGFace *f = ccgdm->faceMap[i].face;
1219
1220                 for (j = 0; j < mpoly[i].totloop; j++) {
1221                         const MDisps *md = &mdisps[mpoly[i].loopstart + j];
1222                         int hidden_gridsize = BKE_ccg_gridsize(md->level);
1223                         int factor = BKE_ccg_factor(level, md->level);
1224                         BLI_bitmap *hidden = md->hidden;
1225                         
1226                         if (!hidden)
1227                                 continue;
1228                         
1229                         for (y = 0; y < gridSize; y++) {
1230                                 for (x = 0; x < gridSize; x++) {
1231                                         int vndx, offset;
1232                                         
1233                                         vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize);
1234                                         offset = (y * factor) * hidden_gridsize + (x * factor);
1235                                         if (BLI_BITMAP_TEST(hidden, offset))
1236                                                 mvert[vndx].flag |= ME_HIDE;
1237                                 }
1238                         }
1239                 }
1240         }
1241 }
1242
1243 /* Translate GridPaintMask into vertex paint masks. Assumes vertices
1244  * are in the order output by ccgDM_copyFinalVertArray. */
1245 void subsurf_copy_grid_paint_mask(DerivedMesh *dm, const MPoly *mpoly,
1246                                   float *paint_mask,
1247                                   const GridPaintMask *grid_paint_mask)
1248 {
1249         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
1250         CCGSubSurf *ss = ccgdm->ss;
1251         int level = ccgSubSurf_getSubdivisionLevels(ss);
1252         int gridSize = ccgSubSurf_getGridSize(ss);
1253         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1254         int totface = ccgSubSurf_getNumFaces(ss);
1255         int i, j, x, y, factor, gpm_gridsize;
1256         
1257         for (i = 0; i < totface; i++) {
1258                 CCGFace *f = ccgdm->faceMap[i].face;
1259                 const MPoly *p = &mpoly[i];
1260                 
1261                 for (j = 0; j < p->totloop; j++) {
1262                         const GridPaintMask *gpm = &grid_paint_mask[p->loopstart + j];
1263                         if (!gpm->data)
1264                                 continue;
1265
1266                         factor = BKE_ccg_factor(level, gpm->level);
1267                         gpm_gridsize = BKE_ccg_gridsize(gpm->level);
1268                         
1269                         for (y = 0; y < gridSize; y++) {
1270                                 for (x = 0; x < gridSize; x++) {
1271                                         int vndx, offset;
1272                                         
1273                                         vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize);
1274                                         offset = y * factor * gpm_gridsize + x * factor;
1275                                         paint_mask[vndx] = gpm->data[offset];
1276                                 }
1277                         }
1278                 }
1279         }
1280 }
1281
1282 /* utility functon */
1283 BLI_INLINE void ccgDM_to_MVert(MVert *mv, const CCGKey *key, CCGElem *elem)
1284 {
1285         copy_v3_v3(mv->co, CCG_elem_co(key, elem));
1286         normal_float_to_short_v3(mv->no, CCG_elem_no(key, elem));
1287         mv->flag = mv->bweight = 0;
1288 }
1289
1290 static void ccgDM_copyFinalVertArray(DerivedMesh *dm, MVert *mvert)
1291 {
1292         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1293         CCGSubSurf *ss = ccgdm->ss;
1294         CCGElem *vd;
1295         CCGKey key;
1296         int index;
1297         int totvert, totedge, totface;
1298         int gridSize = ccgSubSurf_getGridSize(ss);
1299         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1300         unsigned int i = 0;
1301
1302         CCG_key_top_level(&key, ss);
1303
1304         totface = ccgSubSurf_getNumFaces(ss);
1305         for (index = 0; index < totface; index++) {
1306                 CCGFace *f = ccgdm->faceMap[index].face;
1307                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1308
1309                 vd = ccgSubSurf_getFaceCenterData(f);
1310                 ccgDM_to_MVert(&mvert[i++], &key, vd);
1311                 
1312                 for (S = 0; S < numVerts; S++) {
1313                         for (x = 1; x < gridSize - 1; x++) {
1314                                 vd = ccgSubSurf_getFaceGridEdgeData(ss, f, S, x);
1315                                 ccgDM_to_MVert(&mvert[i++], &key, vd);
1316                         }
1317                 }
1318
1319                 for (S = 0; S < numVerts; S++) {
1320                         for (y = 1; y < gridSize - 1; y++) {
1321                                 for (x = 1; x < gridSize - 1; x++) {
1322                                         vd = ccgSubSurf_getFaceGridData(ss, f, S, x, y);
1323                                         ccgDM_to_MVert(&mvert[i++], &key, vd);
1324                                 }
1325                         }
1326                 }
1327         }
1328
1329         totedge = ccgSubSurf_getNumEdges(ss);
1330         for (index = 0; index < totedge; index++) {
1331                 CCGEdge *e = ccgdm->edgeMap[index].edge;
1332                 int x;
1333
1334                 for (x = 1; x < edgeSize - 1; x++) {
1335                         /* This gives errors with -debug-fpe
1336                          * the normals don't seem to be unit length.
1337                          * this is most likely caused by edges with no
1338                          * faces which are now zerod out, see comment in:
1339                          * ccgSubSurf__calcVertNormals(), - campbell */
1340                         vd = ccgSubSurf_getEdgeData(ss, e, x);
1341                         ccgDM_to_MVert(&mvert[i++], &key, vd);
1342                 }
1343         }
1344
1345         totvert = ccgSubSurf_getNumVerts(ss);
1346         for (index = 0; index < totvert; index++) {
1347                 CCGVert *v = ccgdm->vertMap[index].vert;
1348
1349                 vd = ccgSubSurf_getVertData(ss, v);
1350                 ccgDM_to_MVert(&mvert[i++], &key, vd);
1351         }
1352 }
1353
1354
1355 /* utility functon */
1356 BLI_INLINE void ccgDM_to_MEdge(MEdge *med, const int v1, const int v2, const short flag)
1357 {
1358         med->v1 = v1;
1359         med->v2 = v2;
1360         med->crease = med->bweight = 0;
1361         med->flag = flag;
1362 }
1363
1364 static void ccgDM_copyFinalEdgeArray(DerivedMesh *dm, MEdge *medge)
1365 {
1366         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1367         CCGSubSurf *ss = ccgdm->ss;
1368         int index;
1369         int totedge, totface;
1370         int gridSize = ccgSubSurf_getGridSize(ss);
1371         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1372         unsigned int i = 0;
1373         short *edgeFlags = ccgdm->edgeFlags;
1374         const short ed_interior_flag = ccgdm->drawInteriorEdges ? (ME_EDGEDRAW | ME_EDGERENDER) : 0;
1375
1376         totface = ccgSubSurf_getNumFaces(ss);
1377         for (index = 0; index < totface; index++) {
1378                 CCGFace *f = ccgdm->faceMap[index].face;
1379                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1380
1381                 for (S = 0; S < numVerts; S++) {
1382                         for (x = 0; x < gridSize - 1; x++) {
1383                                 ccgDM_to_MEdge(&medge[i++],
1384                                                getFaceIndex(ss, f, S, x,     0, edgeSize, gridSize),
1385                                                getFaceIndex(ss, f, S, x + 1, 0, edgeSize, gridSize),
1386                                                ed_interior_flag);
1387                         }
1388
1389                         for (x = 1; x < gridSize - 1; x++) {
1390                                 for (y = 0; y < gridSize - 1; y++) {
1391                                         ccgDM_to_MEdge(&medge[i++],
1392                                                        getFaceIndex(ss, f, S, x, y,    edgeSize, gridSize),
1393                                                        getFaceIndex(ss, f, S, x, y + 1, edgeSize, gridSize),
1394                                                        ed_interior_flag);
1395                                         ccgDM_to_MEdge(&medge[i++],
1396                                                        getFaceIndex(ss, f, S, y, x,     edgeSize, gridSize),
1397                                                        getFaceIndex(ss, f, S, y + 1, x, edgeSize, gridSize),
1398                                                        ed_interior_flag);
1399                                 }
1400                         }
1401                 }
1402         }
1403
1404         totedge = ccgSubSurf_getNumEdges(ss);
1405         for (index = 0; index < totedge; index++) {
1406                 CCGEdge *e = ccgdm->edgeMap[index].edge;
1407                 short ed_flag = 0;
1408                 int x;
1409                 int edgeIdx = GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e));
1410
1411                 if (!ccgSubSurf_getEdgeNumFaces(e)) {
1412                         ed_flag |= ME_LOOSEEDGE;
1413                 }
1414
1415                 if (edgeFlags) {
1416                         if (edgeIdx != -1) {
1417                                 ed_flag |= ((edgeFlags[index] & (ME_SEAM | ME_SHARP)) | ME_EDGEDRAW | ME_EDGERENDER);
1418                         }
1419                 }
1420                 else {
1421                         ed_flag |= ME_EDGEDRAW | ME_EDGERENDER;
1422                 }
1423
1424                 for (x = 0; x < edgeSize - 1; x++) {
1425                         ccgDM_to_MEdge(&medge[i++],
1426                                        getEdgeIndex(ss, e, x, edgeSize),
1427                                        getEdgeIndex(ss, e, x + 1, edgeSize),
1428                                        ed_flag);
1429                 }
1430         }
1431 }
1432
1433 static void ccgDM_copyFinalFaceArray(DerivedMesh *dm, MFace *mface)
1434 {
1435         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1436         CCGSubSurf *ss = ccgdm->ss;
1437         int index;
1438         int totface;
1439         int gridSize = ccgSubSurf_getGridSize(ss);
1440         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1441         int i = 0;
1442         DMFlagMat *faceFlags = ccgdm->faceFlags;
1443
1444         totface = dm->getNumTessFaces(dm);
1445         for (index = 0; index < totface; index++) {
1446                 CCGFace *f = ccgdm->faceMap[index].face;
1447                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1448                 /* keep types in sync with MFace, avoid many conversions */
1449                 char flag = (faceFlags) ? faceFlags[index].flag : ME_SMOOTH;
1450                 short mat_nr = (faceFlags) ? faceFlags[index].mat_nr : 0;
1451
1452                 for (S = 0; S < numVerts; S++) {
1453                         for (y = 0; y < gridSize - 1; y++) {
1454                                 for (x = 0; x < gridSize - 1; x++) {
1455                                         MFace *mf = &mface[i];
1456                                         mf->v1 = getFaceIndex(ss, f, S, x + 0, y + 0,
1457                                                               edgeSize, gridSize);
1458                                         mf->v2 = getFaceIndex(ss, f, S, x + 0, y + 1,
1459                                                               edgeSize, gridSize);
1460                                         mf->v3 = getFaceIndex(ss, f, S, x + 1, y + 1,
1461                                                               edgeSize, gridSize);
1462                                         mf->v4 = getFaceIndex(ss, f, S, x + 1, y + 0,
1463                                                               edgeSize, gridSize);
1464                                         mf->mat_nr = mat_nr;
1465                                         mf->flag = flag;
1466                                         mf->edcode = 0;
1467
1468                                         i++;
1469                                 }
1470                         }
1471                 }
1472         }
1473 }
1474
1475 static void ccgDM_copyFinalLoopArray(DerivedMesh *dm, MLoop *mloop)
1476 {
1477         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1478         CCGSubSurf *ss = ccgdm->ss;
1479         int index;
1480         int totface;
1481         int gridSize = ccgSubSurf_getGridSize(ss);
1482         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1483         int i = 0;
1484         MLoop *mv;
1485         /* DMFlagMat *faceFlags = ccgdm->faceFlags; */ /* UNUSED */
1486
1487         if (!ccgdm->ehash) {
1488                 BLI_rw_mutex_lock(&loops_cache_rwlock, THREAD_LOCK_WRITE);
1489                 if (!ccgdm->ehash) {
1490                         MEdge *medge;
1491
1492                         ccgdm->ehash = BLI_edgehash_new_ex(__func__, ccgdm->dm.numEdgeData);
1493                         medge = ccgdm->dm.getEdgeArray((DerivedMesh *)ccgdm);
1494
1495                         for (i = 0; i < ccgdm->dm.numEdgeData; i++) {
1496                                 BLI_edgehash_insert(ccgdm->ehash, medge[i].v1, medge[i].v2, SET_INT_IN_POINTER(i));
1497                         }
1498                 }
1499                 BLI_rw_mutex_unlock(&loops_cache_rwlock);
1500         }
1501
1502         BLI_rw_mutex_lock(&loops_cache_rwlock, THREAD_LOCK_READ);
1503         totface = ccgSubSurf_getNumFaces(ss);
1504         mv = mloop;
1505         for (index = 0; index < totface; index++) {
1506                 CCGFace *f = ccgdm->faceMap[index].face;
1507                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1508                 /* int flag = (faceFlags) ? faceFlags[index * 2]: ME_SMOOTH; */ /* UNUSED */
1509                 /* int mat_nr = (faceFlags) ? faceFlags[index * 2 + 1]: 0; */ /* UNUSED */
1510
1511                 for (S = 0; S < numVerts; S++) {
1512                         for (y = 0; y < gridSize - 1; y++) {
1513                                 for (x = 0; x < gridSize - 1; x++) {
1514                                         unsigned int v1, v2, v3, v4;
1515
1516                                         v1 = getFaceIndex(ss, f, S, x + 0, y + 0,
1517                                                           edgeSize, gridSize);
1518
1519                                         v2 = getFaceIndex(ss, f, S, x + 0, y + 1,
1520                                                           edgeSize, gridSize);
1521                                         v3 = getFaceIndex(ss, f, S, x + 1, y + 1,
1522                                                           edgeSize, gridSize);
1523                                         v4 = getFaceIndex(ss, f, S, x + 1, y + 0,
1524                                                           edgeSize, gridSize);
1525
1526                                         mv->v = v1;
1527                                         mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v1, v2));
1528                                         mv++, i++;
1529
1530                                         mv->v = v2;
1531                                         mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v2, v3));
1532                                         mv++, i++;
1533
1534                                         mv->v = v3;
1535                                         mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v3, v4));
1536                                         mv++, i++;
1537
1538                                         mv->v = v4;
1539                                         mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v4, v1));
1540                                         mv++, i++;
1541                                 }
1542                         }
1543                 }
1544         }
1545         BLI_rw_mutex_unlock(&loops_cache_rwlock);
1546 }
1547
1548 static void ccgDM_copyFinalPolyArray(DerivedMesh *dm, MPoly *mpoly)
1549 {
1550         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1551         CCGSubSurf *ss = ccgdm->ss;
1552         int index;
1553         int totface;
1554         int gridSize = ccgSubSurf_getGridSize(ss);
1555         /* int edgeSize = ccgSubSurf_getEdgeSize(ss); */ /* UNUSED */
1556         int i = 0, k = 0;
1557         DMFlagMat *faceFlags = ccgdm->faceFlags;
1558
1559         totface = ccgSubSurf_getNumFaces(ss);
1560         for (index = 0; index < totface; index++) {
1561                 CCGFace *f = ccgdm->faceMap[index].face;
1562                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1563                 int flag = (faceFlags) ? faceFlags[index].flag : ME_SMOOTH;
1564                 int mat_nr = (faceFlags) ? faceFlags[index].mat_nr : 0;
1565
1566                 for (S = 0; S < numVerts; S++) {
1567                         for (y = 0; y < gridSize - 1; y++) {
1568                                 for (x = 0; x < gridSize - 1; x++) {
1569                                         MPoly *mp = &mpoly[i];
1570
1571                                         mp->mat_nr = mat_nr;
1572                                         mp->flag = flag;
1573                                         mp->loopstart = k;
1574                                         mp->totloop = 4;
1575
1576                                         k += 4;
1577                                         i++;
1578                                 }
1579                         }
1580                 }
1581         }
1582 }
1583
1584 static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3])
1585 {
1586         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1587         CCGSubSurf *ss = ccgdm->ss;
1588         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1589         int gridSize = ccgSubSurf_getGridSize(ss);
1590         int i;
1591         CCGVertIterator vi;
1592         CCGEdgeIterator ei;
1593         CCGFaceIterator fi;
1594         CCGFace **faceMap2;
1595         CCGEdge **edgeMap2;
1596         CCGVert **vertMap2;
1597         int index, totvert, totedge, totface;
1598         
1599         totvert = ccgSubSurf_getNumVerts(ss);
1600         vertMap2 = MEM_mallocN(totvert * sizeof(*vertMap2), "vertmap");
1601         for (ccgSubSurf_initVertIterator(ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) {
1602                 CCGVert *v = ccgVertIterator_getCurrent(&vi);
1603
1604                 vertMap2[GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v))] = v;
1605         }
1606
1607         totedge = ccgSubSurf_getNumEdges(ss);
1608         edgeMap2 = MEM_mallocN(totedge * sizeof(*edgeMap2), "edgemap");
1609         for (ccgSubSurf_initEdgeIterator(ss, &ei), i = 0; !ccgEdgeIterator_isStopped(&ei); i++, ccgEdgeIterator_next(&ei)) {
1610                 CCGEdge *e = ccgEdgeIterator_getCurrent(&ei);
1611
1612                 edgeMap2[GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e))] = e;
1613         }
1614
1615         totface = ccgSubSurf_getNumFaces(ss);
1616         faceMap2 = MEM_mallocN(totface * sizeof(*faceMap2), "facemap");
1617         for (ccgSubSurf_initFaceIterator(ss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
1618                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
1619
1620                 faceMap2[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f))] = f;
1621         }
1622
1623         i = 0;
1624         for (index = 0; index < totface; index++) {
1625                 CCGFace *f = faceMap2[index];
1626                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1627
1628                 copy_v3_v3(cos[i++], ccgSubSurf_getFaceCenterData(f));
1629                 
1630                 for (S = 0; S < numVerts; S++) {
1631                         for (x = 1; x < gridSize - 1; x++) {
1632                                 copy_v3_v3(cos[i++], ccgSubSurf_getFaceGridEdgeData(ss, f, S, x));
1633                         }
1634                 }
1635
1636                 for (S = 0; S < numVerts; S++) {
1637                         for (y = 1; y < gridSize - 1; y++) {
1638                                 for (x = 1; x < gridSize - 1; x++) {
1639                                         copy_v3_v3(cos[i++], ccgSubSurf_getFaceGridData(ss, f, S, x, y));
1640                                 }
1641                         }
1642                 }
1643         }
1644
1645         for (index = 0; index < totedge; index++) {
1646                 CCGEdge *e = edgeMap2[index];
1647                 int x;
1648
1649                 for (x = 1; x < edgeSize - 1; x++) {
1650                         copy_v3_v3(cos[i++], ccgSubSurf_getEdgeData(ss, e, x));
1651                 }
1652         }
1653
1654         for (index = 0; index < totvert; index++) {
1655                 CCGVert *v = vertMap2[index];
1656                 copy_v3_v3(cos[i++], ccgSubSurf_getVertData(ss, v));
1657         }
1658
1659         MEM_freeN(vertMap2);
1660         MEM_freeN(edgeMap2);
1661         MEM_freeN(faceMap2);
1662 }
1663
1664 static void ccgDM_foreachMappedVert(
1665         DerivedMesh *dm,
1666         void (*func)(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3]),
1667         void *userData,
1668         DMForeachFlag flag)
1669 {
1670         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1671         CCGVertIterator vi;
1672         CCGKey key;
1673         CCG_key_top_level(&key, ccgdm->ss);
1674
1675         for (ccgSubSurf_initVertIterator(ccgdm->ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) {
1676                 CCGVert *v = ccgVertIterator_getCurrent(&vi);
1677                 const int index = ccgDM_getVertMapIndex(ccgdm->ss, v);
1678
1679                 if (index != -1) {
1680                         CCGElem *vd = ccgSubSurf_getVertData(ccgdm->ss, v);
1681                         const float *no = (flag & DM_FOREACH_USE_NORMAL) ? CCG_elem_no(&key, vd) : NULL;
1682                         func(userData, index, CCG_elem_co(&key, vd), no, NULL);
1683                 }
1684         }
1685 }
1686
1687 static void ccgDM_foreachMappedEdge(
1688         DerivedMesh *dm,
1689         void (*func)(void *userData, int index, const float v0co[3], const float v1co[3]),
1690         void *userData)
1691 {
1692         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1693         CCGSubSurf *ss = ccgdm->ss;
1694         CCGEdgeIterator ei;
1695         CCGKey key;
1696         int i, edgeSize = ccgSubSurf_getEdgeSize(ss);
1697
1698         CCG_key_top_level(&key, ss);
1699
1700         for (ccgSubSurf_initEdgeIterator(ss, &ei); !ccgEdgeIterator_isStopped(&ei); ccgEdgeIterator_next(&ei)) {
1701                 CCGEdge *e = ccgEdgeIterator_getCurrent(&ei);
1702                 const int index = ccgDM_getEdgeMapIndex(ss, e);
1703
1704                 if (index != -1) {
1705                         CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
1706                         for (i = 0; i < edgeSize - 1; i++) {
1707                                 func(userData, index, CCG_elem_offset_co(&key, edgeData, i), CCG_elem_offset_co(&key, edgeData, i + 1));
1708                         }
1709                 }
1710         }
1711 }
1712
1713 static void ccgDM_foreachMappedLoop(
1714         DerivedMesh *dm,
1715         void (*func)(void *userData, int vertex_index, int face_index, const float co[3], const float no[3]),
1716         void *userData,
1717         DMForeachFlag flag)
1718 {
1719         /* We can't use dm->getLoopDataLayout(dm) here, we want to always access dm->loopData, EditDerivedBMesh would
1720          * return loop data from bmesh itself. */
1721         const float (*lnors)[3] = (flag & DM_FOREACH_USE_NORMAL) ? DM_get_loop_data_layer(dm, CD_NORMAL) : NULL;
1722
1723         MVert *mv = dm->getVertArray(dm);
1724         MLoop *ml = dm->getLoopArray(dm);
1725         MPoly *mp = dm->getPolyArray(dm);
1726         const int *v_index = dm->getVertDataArray(dm, CD_ORIGINDEX);
1727         const int *f_index = dm->getPolyDataArray(dm, CD_ORIGINDEX);
1728         int p_idx, i;
1729
1730         for (p_idx = 0; p_idx < dm->numPolyData; ++p_idx, ++mp) {
1731                 for (i = 0; i < mp->totloop; ++i, ++ml) {
1732                         const int v_idx = v_index ? v_index[ml->v] : ml->v;
1733                         const int f_idx = f_index ? f_index[p_idx] : p_idx;
1734                         const float *no = lnors ? *lnors++ : NULL;
1735                         if (!ELEM(ORIGINDEX_NONE, v_idx, f_idx)) {
1736                                 func(userData, v_idx, f_idx, mv[ml->v].co, no);
1737                         }
1738                 }
1739         }
1740 }
1741
1742 static void ccgDM_drawVerts(DerivedMesh *dm)
1743 {
1744         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1745         CCGSubSurf *ss = ccgdm->ss;
1746         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1747         int gridSize = ccgSubSurf_getGridSize(ss);
1748         CCGVertIterator vi;
1749         CCGEdgeIterator ei;
1750         CCGFaceIterator fi;
1751
1752         glBegin(GL_POINTS);
1753         for (ccgSubSurf_initVertIterator(ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) {
1754                 CCGVert *v = ccgVertIterator_getCurrent(&vi);
1755                 glVertex3fv(ccgSubSurf_getVertData(ss, v));
1756         }
1757
1758         for (ccgSubSurf_initEdgeIterator(ss, &ei); !ccgEdgeIterator_isStopped(&ei); ccgEdgeIterator_next(&ei)) {
1759                 CCGEdge *e = ccgEdgeIterator_getCurrent(&ei);
1760                 int x;
1761
1762                 for (x = 1; x < edgeSize - 1; x++)
1763                         glVertex3fv(ccgSubSurf_getEdgeData(ss, e, x));
1764         }
1765
1766         for (ccgSubSurf_initFaceIterator(ss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
1767                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
1768                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1769
1770                 glVertex3fv(ccgSubSurf_getFaceCenterData(f));
1771                 for (S = 0; S < numVerts; S++)
1772                         for (x = 1; x < gridSize - 1; x++)
1773                                 glVertex3fv(ccgSubSurf_getFaceGridEdgeData(ss, f, S, x));
1774                 for (S = 0; S < numVerts; S++)
1775                         for (y = 1; y < gridSize - 1; y++)
1776                                 for (x = 1; x < gridSize - 1; x++)
1777                                         glVertex3fv(ccgSubSurf_getFaceGridData(ss, f, S, x, y));
1778         }
1779         glEnd();
1780 }
1781
1782 static void ccgdm_pbvh_update(CCGDerivedMesh *ccgdm)
1783 {
1784         if (ccgdm->pbvh && ccgDM_use_grid_pbvh(ccgdm)) {
1785                 CCGFace **faces;
1786                 int totface;
1787
1788                 BKE_pbvh_get_grid_updates(ccgdm->pbvh, 1, (void ***)&faces, &totface);
1789                 if (totface) {
1790                         ccgSubSurf_updateFromFaces(ccgdm->ss, 0, faces, totface);
1791                         ccgSubSurf_updateNormals(ccgdm->ss, faces, totface);
1792                         MEM_freeN(faces);
1793                 }
1794         }
1795 }
1796
1797 static void ccgDM_drawEdges(DerivedMesh *dm, bool drawLooseEdges, bool drawAllEdges)
1798 {
1799         GPUDrawObject *gdo;
1800         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1801
1802 #ifdef WITH_OPENSUBDIV
1803         if (ccgdm->useGpuBackend) {
1804                 /* TODO(sergey): We currently only support all edges drawing. */
1805                 if (ccgSubSurf_prepareGLMesh(ccgdm->ss, true)) {
1806                         ccgSubSurf_drawGLMesh(ccgdm->ss, false, -1, -1);
1807                 }
1808                 return;
1809         }
1810 #endif
1811
1812         ccgdm_pbvh_update(ccgdm);
1813
1814 /* old debug feature for edges, unsupported for now */
1815 #if 0
1816         int useAging = 0;
1817
1818         if (!(G.f & G_BACKBUFSEL)) {
1819                 CCGSubSurf *ss = ccgdm->ss;
1820                 ccgSubSurf_getUseAgeCounts(ss, &useAging, NULL, NULL, NULL);
1821
1822                 /* it needs some way to upload this to VBO now */
1823                 if (useAging) {
1824                         int ageCol = 255 - ccgSubSurf_getEdgeAge(ss, e) * 4;
1825                         glColor3ub(0, ageCol > 0 ? ageCol : 0, 0);
1826                 }
1827         }
1828 #endif
1829
1830         GPU_edge_setup(dm);
1831         gdo = dm->drawObject;
1832         if (gdo->edges && gdo->points) {
1833                 if (drawAllEdges && drawLooseEdges) {
1834                         GPU_buffer_draw_elements(gdo->edges, GL_LINES, 0, (gdo->totedge - gdo->totinterior) * 2);
1835                 }
1836                 else if (drawAllEdges) {
1837                         GPU_buffer_draw_elements(gdo->edges, GL_LINES, 0, gdo->loose_edge_offset * 2);
1838                 }
1839                 else {
1840                         GPU_buffer_draw_elements(gdo->edges, GL_LINES, 0, gdo->tot_edge_drawn * 2);
1841                         GPU_buffer_draw_elements(gdo->edges, GL_LINES, gdo->loose_edge_offset * 2, gdo->tot_loose_edge_drawn * 2);
1842                 }
1843         }
1844
1845         if (gdo->edges && ccgdm->drawInteriorEdges) {
1846                 GPU_buffer_draw_elements(gdo->edges, GL_LINES, gdo->interior_offset * 2, gdo->totinterior * 2);
1847         }
1848         GPU_buffers_unbind();
1849 }
1850
1851 static void ccgDM_drawLooseEdges(DerivedMesh *dm)
1852 {
1853         int start;
1854         int count;
1855
1856 #ifdef WITH_OPENSUBDIV
1857         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1858         if (ccgdm->useGpuBackend) {
1859                 /* TODO(sergey): Needs implementation. */
1860                 return;
1861         }
1862 #endif
1863
1864         GPU_edge_setup(dm);
1865
1866         start = (dm->drawObject->loose_edge_offset * 2);
1867         count = (dm->drawObject->interior_offset - dm->drawObject->loose_edge_offset) * 2;
1868
1869         if (count) {
1870                 GPU_buffer_draw_elements(dm->drawObject->edges, GL_LINES, start, count);
1871         }
1872
1873         GPU_buffers_unbind();
1874 }
1875
1876 static void ccgDM_NormalFast(float *a, float *b, float *c, float *d, float no[3])
1877 {
1878         float a_cX = c[0] - a[0], a_cY = c[1] - a[1], a_cZ = c[2] - a[2];
1879         float b_dX = d[0] - b[0], b_dY = d[1] - b[1], b_dZ = d[2] - b[2];
1880
1881         no[0] = b_dY * a_cZ - b_dZ * a_cY;
1882         no[1] = b_dZ * a_cX - b_dX * a_cZ;
1883         no[2] = b_dX * a_cY - b_dY * a_cX;
1884         
1885         normalize_v3(no);
1886 }
1887
1888
1889 static void ccgDM_glNormalFast(float *a, float *b, float *c, float *d)
1890 {
1891         float a_cX = c[0] - a[0], a_cY = c[1] - a[1], a_cZ = c[2] - a[2];
1892         float b_dX = d[0] - b[0], b_dY = d[1] - b[1], b_dZ = d[2] - b[2];
1893         float no[3];
1894         
1895         no[0] = b_dY * a_cZ - b_dZ * a_cY;
1896         no[1] = b_dZ * a_cX - b_dX * a_cZ;
1897         no[2] = b_dX * a_cY - b_dY * a_cX;
1898
1899         /* don't normalize, GL_NORMALIZE is enabled */
1900         glNormal3fv(no);
1901 }
1902
1903 /* Only used by non-editmesh types */
1904 static void ccgDM_buffer_copy_normal(
1905         DerivedMesh *dm, short *varray)
1906 {
1907         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1908         CCGSubSurf *ss = ccgdm->ss;
1909         CCGKey key;
1910         const float (*lnors)[3] = dm->getLoopDataArray(dm, CD_NORMAL);
1911         int gridSize = ccgSubSurf_getGridSize(ss);
1912         int gridFaces = gridSize - 1;
1913         DMFlagMat *faceFlags = ccgdm->faceFlags;
1914         int i, totface = ccgSubSurf_getNumFaces(ss);
1915         int shademodel;
1916         int start = 0;
1917
1918         /* we are in sculpt mode, disable loop normals (since they won't get updated) */
1919         if (ccgdm->pbvh)
1920                 lnors = NULL;
1921
1922         CCG_key_top_level(&key, ss);
1923
1924         for (i = 0; i < totface; i++) {
1925                 CCGFace *f = ccgdm->faceMap[i].face;
1926                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
1927                 int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
1928                 const float (*ln)[3] = NULL;
1929
1930                 if (faceFlags) {
1931                         shademodel = (lnors || (faceFlags[index].flag & ME_SMOOTH)) ? GL_SMOOTH : GL_FLAT;
1932                 }
1933                 else {
1934                         shademodel = GL_SMOOTH;
1935                 }
1936
1937                 if (lnors) {
1938                         ln = lnors;
1939                         lnors += gridFaces * gridFaces * numVerts * 4;
1940                 }
1941
1942                 for (S = 0; S < numVerts; S++) {
1943                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
1944
1945                         if (ln) {
1946                                 /* Can't use quad strips here... */
1947                                 for (y = 0; y < gridFaces; y ++) {
1948                                         for (x = 0; x < gridFaces; x ++) {
1949                                                 normal_float_to_short_v3(&varray[start + 0],  ln[0]);
1950                                                 normal_float_to_short_v3(&varray[start + 4],  ln[3]);
1951                                                 normal_float_to_short_v3(&varray[start + 8],  ln[2]);
1952                                                 normal_float_to_short_v3(&varray[start + 12], ln[1]);
1953
1954                                                 start += 16;
1955                                                 ln += 4;
1956                                         }
1957                                 }
1958                         }
1959                         else if (shademodel == GL_SMOOTH) {
1960                                 for (y = 0; y < gridFaces; y ++) {
1961                                         for (x = 0; x < gridFaces; x ++) {
1962                                                 float *a = CCG_grid_elem_no(&key, faceGridData, x, y );
1963                                                 float *b = CCG_grid_elem_no(&key, faceGridData, x + 1, y);
1964                                                 float *c = CCG_grid_elem_no(&key, faceGridData, x + 1, y + 1);
1965                                                 float *d = CCG_grid_elem_no(&key, faceGridData, x, y + 1);
1966
1967                                                 normal_float_to_short_v3(&varray[start], a);
1968                                                 normal_float_to_short_v3(&varray[start + 4], b);
1969                                                 normal_float_to_short_v3(&varray[start + 8], c);
1970                                                 normal_float_to_short_v3(&varray[start + 12], d);
1971
1972                                                 start += 16;
1973                                         }
1974                                 }
1975                         }
1976                         else {
1977                                 for (y = 0; y < gridFaces; y ++) {
1978                                         for (x = 0; x < gridFaces; x ++) {
1979                                                 float f_no[3];
1980                                                 short f_no_s[3];
1981
1982                                                 float *a = CCG_grid_elem_co(&key, faceGridData, x, y );
1983                                                 float *b = CCG_grid_elem_co(&key, faceGridData, x + 1, y );
1984                                                 float *c = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
1985                                                 float *d = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
1986
1987                                                 ccgDM_NormalFast(a, b, c, d, f_no);
1988                                                 normal_float_to_short_v3(f_no_s, f_no);
1989         
1990                                                 copy_v3_v3_short(&varray[start], f_no_s);
1991                                                 copy_v3_v3_short(&varray[start + 4], f_no_s);
1992                                                 copy_v3_v3_short(&varray[start + 8], f_no_s);
1993                                                 copy_v3_v3_short(&varray[start + 12], f_no_s);
1994
1995                                                 start += 16;
1996                                         }
1997                                 }
1998                         }
1999                 }
2000         }
2001 }
2002
2003 typedef struct FaceCount {
2004         unsigned int i_visible;
2005         unsigned int i_hidden;
2006         unsigned int i_tri_visible;
2007         unsigned int i_tri_hidden;
2008 } FaceCount;
2009
2010
2011 /* Only used by non-editmesh types */
2012 static void ccgDM_buffer_copy_triangles(
2013         DerivedMesh *dm, unsigned int *varray,
2014         const int *mat_orig_to_new)
2015 {
2016         GPUBufferMaterial *gpumat, *gpumaterials = dm->drawObject->materials;
2017         const int gpu_totmat = dm->drawObject->totmaterial;
2018         const short dm_totmat = dm->totmat;
2019         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2020         CCGSubSurf *ss = ccgdm->ss;
2021         CCGKey key;
2022         int gridSize = ccgSubSurf_getGridSize(ss);
2023         int gridFaces = gridSize - 1;
2024         DMFlagMat *faceFlags = ccgdm->faceFlags;
2025         int i, totface = ccgSubSurf_getNumFaces(ss);
2026         short mat_nr = -1;
2027         int start;
2028         int totloops = 0;
2029         FaceCount *fc = MEM_mallocN(sizeof(*fc) * gpu_totmat, "gpumaterial.facecount");
2030
2031         CCG_key_top_level(&key, ss);
2032
2033         for (i = 0; i < gpu_totmat; i++) {
2034                 fc[i].i_visible = 0;
2035                 fc[i].i_tri_visible = 0;
2036                 fc[i].i_hidden = gpumaterials[i].totpolys - 1;
2037                 fc[i].i_tri_hidden = gpumaterials[i].totelements - 1;
2038         }
2039
2040         for (i = 0; i < totface; i++) {
2041                 CCGFace *f = ccgdm->faceMap[i].face;
2042                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2043                 int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2044                 bool is_hidden;
2045                 int mati;
2046
2047                 if (faceFlags) {
2048                         mat_nr = ME_MAT_NR_TEST(faceFlags[index].mat_nr, dm_totmat);
2049                         is_hidden = (faceFlags[index].flag & ME_HIDE) != 0;
2050                 }
2051                 else {
2052                         mat_nr = 0;
2053                         is_hidden = false;
2054                 }
2055                 mati = mat_orig_to_new[mat_nr];
2056                 gpumat = dm->drawObject->materials + mati;
2057
2058                 if (is_hidden) {
2059                         for (S = 0; S < numVerts; S++) {
2060                                 for (y = 0; y < gridFaces; y++) {
2061                                         for (x = 0; x < gridFaces; x++) {
2062                                                 start = gpumat->start + fc[mati].i_tri_hidden;
2063
2064                                                 varray[start--] = totloops + 1;
2065                                                 varray[start--] = totloops + 2;
2066                                                 varray[start--] = totloops + 3;
2067
2068                                                 varray[start--] = totloops;
2069                                                 varray[start--] = totloops + 1;
2070                                                 varray[start--] = totloops + 3;
2071
2072                                                 fc[mati].i_tri_hidden -= 6;
2073
2074                                                 totloops += 4;
2075                                         }
2076                                 }
2077                         }
2078                         gpumat->polys[fc[mati].i_hidden--] = i;
2079                 }
2080                 else {
2081                         for (S = 0; S < numVerts; S++) {
2082                                 for (y = 0; y < gridFaces; y++) {
2083                                         for (x = 0; x < gridFaces; x++) {
2084                                                 start = gpumat->start + fc[mati].i_tri_visible;
2085
2086                                                 varray[start++] = totloops + 3;
2087                                                 varray[start++] = totloops + 2;
2088                                                 varray[start++] = totloops + 1;
2089
2090                                                 varray[start++] = totloops + 3;
2091                                                 varray[start++] = totloops + 1;
2092                                                 varray[start++] = totloops;
2093
2094                                                 fc[mati].i_tri_visible += 6;
2095
2096                                                 totloops += 4;
2097                                         }
2098                                 }
2099                         }
2100                         gpumat->polys[fc[mati].i_visible++] = i;
2101                 }
2102         }
2103
2104         /* set the visible polygons */
2105         for (i = 0; i < gpu_totmat; i++) {
2106                 gpumaterials[i].totvisiblepolys = fc[i].i_visible;
2107         }
2108
2109         MEM_freeN(fc);
2110 }
2111
2112
2113 /* Only used by non-editmesh types */
2114 static void ccgDM_buffer_copy_vertex(
2115         DerivedMesh *dm, void *varray_p)
2116 {
2117         float *varray = varray_p;
2118         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2119         CCGSubSurf *ss = ccgdm->ss;
2120         CCGKey key;
2121         int gridSize = ccgSubSurf_getGridSize(ss);
2122         int gridFaces = gridSize - 1;
2123         int i, totface = ccgSubSurf_getNumFaces(ss);
2124         int totedge = ccgSubSurf_getNumEdges(ss);
2125         int start = 0;
2126         int edgeSize = ccgSubSurf_getEdgeSize(ss);
2127
2128         CCG_key_top_level(&key, ss);
2129
2130         for (i = 0; i < totface; i++) {
2131                 CCGFace *f = ccgdm->faceMap[i].face;
2132                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2133                 
2134                 for (S = 0; S < numVerts; S++) {
2135                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
2136                         for (y = 0; y < gridFaces; y++) {
2137                                 for (x = 0; x < gridFaces; x++) {
2138                                         float *a = CCG_grid_elem_co(&key, faceGridData, x, y);
2139                                         float *b = CCG_grid_elem_co(&key, faceGridData, x + 1, y);
2140                                         float *c = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
2141                                         float *d = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
2142
2143                                         copy_v3_v3(&varray[start], a);
2144                                         copy_v3_v3(&varray[start + 3], b);
2145                                         copy_v3_v3(&varray[start + 6], c);
2146                                         copy_v3_v3(&varray[start + 9], d);
2147
2148                                         start += 12;
2149                                 }
2150                         }
2151                 }
2152         }
2153
2154         /* upload loose points */
2155         for (i = 0; i < totedge; i++) {
2156                 CCGEdge *e = ccgdm->edgeMap[i].edge;
2157                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
2158
2159                 if (!ccgSubSurf_getEdgeNumFaces(e)) {
2160                         int j = 0;
2161                         for (j = 0; j < edgeSize; j++) {
2162                                 copy_v3_v3(&varray[start], CCG_elem_offset_co(&key, edgeData, j));
2163                                 start += 3;
2164                         }
2165                 }
2166         }
2167 }
2168
2169 /* Only used by non-editmesh types */
2170 static void ccgDM_buffer_copy_color(
2171         DerivedMesh *dm, unsigned char *varray,
2172         const void *user_data)
2173 {
2174         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2175         CCGSubSurf *ss = ccgdm->ss;
2176         CCGKey key;
2177         const unsigned char *mloopcol = user_data;
2178         int gridSize = ccgSubSurf_getGridSize(ss);
2179         int gridFaces = gridSize - 1;
2180         int i, totface = ccgSubSurf_getNumFaces(ss);
2181         int start = 0;
2182         int iface = 0;
2183
2184         CCG_key_top_level(&key, ss);
2185
2186
2187         for (i = 0; i < totface; i++) {
2188                 CCGFace *f = ccgdm->faceMap[i].face;
2189                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2190
2191                 for (S = 0; S < numVerts; S++) {
2192                         for (y = 0; y < gridFaces; y++) {
2193                                 for (x = 0; x < gridFaces; x++) {
2194                                         copy_v3_v3_uchar(&varray[start + 0], &mloopcol[iface * 16 + 0]);
2195                                         copy_v3_v3_uchar(&varray[start + 3], &mloopcol[iface * 16 + 12]);
2196                                         copy_v3_v3_uchar(&varray[start + 6], &mloopcol[iface * 16 + 8]);
2197                                         copy_v3_v3_uchar(&varray[start + 9], &mloopcol[iface * 16 + 4]);
2198
2199                                         start += 12;
2200                                         iface++;
2201                                 }
2202                         }
2203                 }
2204         }
2205 }
2206
2207 static void ccgDM_buffer_copy_uv(
2208         DerivedMesh *dm, void *varray_p)
2209 {
2210         float *varray = varray_p;
2211         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2212         CCGSubSurf *ss = ccgdm->ss;
2213         CCGKey key;
2214         MLoopUV *mloopuv = DM_get_loop_data_layer(dm, CD_MLOOPUV);
2215         int gridSize = ccgSubSurf_getGridSize(ss);
2216         int gridFaces = gridSize - 1;
2217         int i, totface = ccgSubSurf_getNumFaces(ss);
2218         int start = 0;
2219
2220         CCG_key_top_level(&key, ss);
2221
2222         for (i = 0; i < totface; i++) {
2223                 CCGFace *f = ccgdm->faceMap[i].face;
2224                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2225
2226                 for (S = 0; S < numVerts; S++) {
2227                         for (y = 0; y < gridFaces; y++) {
2228                                 for (x = 0; x < gridFaces; x++) {
2229                                         copy_v2_v2(&varray[start + 0], mloopuv[0].uv);
2230                                         copy_v2_v2(&varray[start + 2], mloopuv[3].uv);
2231                                         copy_v2_v2(&varray[start + 4], mloopuv[2].uv);
2232                                         copy_v2_v2(&varray[start + 6], mloopuv[1].uv);
2233
2234                                         mloopuv += 4;
2235                                         start += 8;
2236                                 }
2237                         }
2238                 }
2239         }
2240 }
2241
2242 static void ccgDM_buffer_copy_uv_texpaint(
2243         DerivedMesh *dm, float *varray)
2244 {
2245         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2246         CCGSubSurf *ss = ccgdm->ss;
2247         CCGKey key;
2248         int gridSize = ccgSubSurf_getGridSize(ss);
2249         int gridFaces = gridSize - 1;
2250         int i, totface = ccgSubSurf_getNumFaces(ss);
2251         int start = 0;
2252         DMFlagMat *faceFlags = ccgdm->faceFlags;
2253         int dm_totmat = dm->totmat;
2254         MLoopUV **mloopuv_base;
2255         MLoopUV  *stencil_base;
2256         int stencil;
2257
2258         CCG_key_top_level(&key, ss);
2259
2260         /* should have been checked for before, reassert */
2261         BLI_assert(DM_get_loop_data_layer(dm, CD_MLOOPUV));
2262         mloopuv_base = MEM_mallocN(dm_totmat * sizeof(*mloopuv_base), "texslots");
2263
2264         for (i = 0; i < dm_totmat; i++) {
2265                 mloopuv_base[i] = DM_paint_uvlayer_active_get(dm, i);
2266         }
2267
2268         stencil = CustomData_get_stencil_layer(&dm->loopData, CD_MLOOPUV);
2269         stencil_base = CustomData_get_layer_n(&dm->loopData, CD_MLOOPUV, stencil);
2270
2271         start = 0;
2272
2273         for (i = 0; i < totface; i++) {
2274                 CCGFace *f = ccgdm->faceMap[i].face;
2275                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2276                 int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2277                 int matnr;
2278
2279                 if (faceFlags) {
2280                         matnr = faceFlags[index].mat_nr;
2281                 }
2282                 else {
2283                         matnr = 0;
2284                 }
2285
2286                 for (S = 0; S < numVerts; S++) {
2287                         for (y = 0; y < gridFaces; y++) {
2288                                 for (x = 0; x < gridFaces; x++) {
2289                                         /* divide by 4, gives us current loop-index */
2290                                         unsigned int i_ml = start / 4;
2291                                         copy_v2_v2(&varray[start + 0],  mloopuv_base[matnr][i_ml + 0].uv);
2292                                         copy_v2_v2(&varray[start + 2],         stencil_base[i_ml + 0].uv);
2293                                         copy_v2_v2(&varray[start + 4],  mloopuv_base[matnr][i_ml + 3].uv);
2294                                         copy_v2_v2(&varray[start + 6],         stencil_base[i_ml + 3].uv);
2295                                         copy_v2_v2(&varray[start + 8],  mloopuv_base[matnr][i_ml + 2].uv);
2296                                         copy_v2_v2(&varray[start + 10],        stencil_base[i_ml + 2].uv);
2297                                         copy_v2_v2(&varray[start + 12], mloopuv_base[matnr][i_ml + 1].uv);
2298                                         copy_v2_v2(&varray[start + 14],        stencil_base[i_ml + 1].uv);
2299                                         start += 16;
2300                                 }
2301                         }
2302                 }
2303         }
2304
2305         MEM_freeN(mloopuv_base);
2306 }
2307
2308 static void ccgDM_buffer_copy_uvedge(
2309         DerivedMesh *dm, float *varray)
2310 {
2311         int i, totpoly;
2312         int start;
2313         const MLoopUV *mloopuv;
2314 #ifndef USE_LOOP_LAYOUT_FAST
2315         const MPoly *mpoly = dm->getPolyArray(dm);
2316 #endif
2317
2318         if ((mloopuv = DM_get_loop_data_layer(dm, CD_MLOOPUV)) == NULL) {
2319                 return;
2320         }
2321
2322         totpoly = dm->getNumPolys(dm);
2323         start = 0;
2324
2325 #ifndef USE_LOOP_LAYOUT_FAST
2326         for (i = 0; i < totpoly; i++, mpoly++) {
2327                 for (j = 0; j < mpoly->totloop; j++) {
2328                         copy_v2_v2(&varray[start], mloopuv[mpoly->loopstart + j].uv);
2329                         copy_v2_v2(&varray[start + 2], mloopuv[mpoly->loopstart + (j + 1) % mpoly->totloop].uv);
2330                         start += 4;
2331                 }
2332         }
2333 #else
2334         for (i = 0; i < totpoly; i++) {
2335                 copy_v2_v2(&varray[start +  0], mloopuv[(i * 4) + 0].uv);
2336                 copy_v2_v2(&varray[start +  2], mloopuv[(i * 4) + 1].uv);
2337
2338                 copy_v2_v2(&varray[start +  4], mloopuv[(i * 4) + 1].uv);
2339                 copy_v2_v2(&varray[start +  6], mloopuv[(i * 4) + 2].uv);
2340
2341                 copy_v2_v2(&varray[start +  8], mloopuv[(i * 4) + 2].uv);
2342                 copy_v2_v2(&varray[start + 10], mloopuv[(i * 4) + 3].uv);
2343
2344                 copy_v2_v2(&varray[start + 12], mloopuv[(i * 4) + 3].uv);
2345                 copy_v2_v2(&varray[start + 14], mloopuv[(i * 4) + 0].uv);
2346
2347                 start += 16;
2348         }
2349 #endif
2350 }
2351
2352 static void ccgDM_buffer_copy_edge(
2353         DerivedMesh *dm, unsigned int *varray)
2354 {
2355         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2356         CCGSubSurf *ss = ccgdm->ss;
2357         /* getEdgeSuze returns num of verts, edges is one less */
2358         int i, j, edgeSize = ccgSubSurf_getEdgeSize(ss) - 1;
2359         int totedge = ccgSubSurf_getNumEdges(ss);
2360         int grid_face_side = ccgSubSurf_getGridSize(ss) - 1;
2361         int totface = ccgSubSurf_getNumFaces(ss);
2362         unsigned int index_start;
2363         unsigned int tot_interior = 0;
2364         unsigned int grid_tot_face = grid_face_side * grid_face_side;
2365
2366         unsigned int iloose, inorm, iloosehidden, inormhidden;
2367         unsigned int tot_loose_hidden = 0, tot_loose = 0;
2368         unsigned int tot_hidden = 0, tot = 0;
2369         unsigned int iloosevert;
2370         /* int tot_interior = 0; */
2371
2372         /* first, handle hidden/loose existing edges, then interior edges */
2373         for (j = 0; j < totedge; j++) {
2374                 CCGEdge *e = ccgdm->edgeMap[j].edge;
2375
2376                 if (ccgdm->edgeFlags && !(ccgdm->edgeFlags[j] & ME_EDGEDRAW)) {
2377                         if (!ccgSubSurf_getEdgeNumFaces(e)) tot_loose_hidden++;
2378                         else tot_hidden++;
2379                 }
2380                 else {
2381                         if (!ccgSubSurf_getEdgeNumFaces(e)) tot_loose++;
2382                         else tot++;
2383                 }
2384         }
2385
2386         inorm = 0;
2387         inormhidden = tot * edgeSize;
2388         iloose = (tot + tot_hidden) * edgeSize;
2389         iloosehidden = (tot + tot_hidden + tot_loose) * edgeSize;
2390         iloosevert = dm->drawObject->tot_loop_verts;
2391
2392         /* part one, handle all normal edges */
2393         for (j = 0; j < totedge; j++) {
2394                 CCGFace *f;
2395                 int fhandle = 0;
2396                 int totvert = 0;
2397                 unsigned int S = 0;
2398                 CCGEdge *e = ccgdm->edgeMap[j].edge;
2399                 bool isloose = !ccgSubSurf_getEdgeNumFaces(e);
2400
2401                 if (!isloose) {
2402                         CCGVert *v1, *v2;
2403                         CCGVert *ev1 = ccgSubSurf_getEdgeVert0(e);
2404                         CCGVert *ev2 = ccgSubSurf_getEdgeVert1(e);
2405
2406                         f = ccgSubSurf_getEdgeFace(e, 0);
2407                         fhandle = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2408                         totvert = ccgSubSurf_getFaceNumVerts(f);
2409
2410                         /* find the index of vertices in the face */
2411                         for (i = 0; i < totvert; i++) {
2412                                 v1 = ccgSubSurf_getFaceVert(f, i);
2413                                 v2 = ccgSubSurf_getFaceVert(f, (i + 1) % totvert);
2414
2415                                 if ((ev1 == v1 && ev2 == v2) || (ev1 == v2 && ev2 == v1)) {
2416                                         S = i;
2417                                         break;
2418                                 }
2419                         }
2420                 }
2421
2422                 if (ccgdm->edgeFlags && !(ccgdm->edgeFlags[j] & ME_EDGEDRAW)) {
2423                         if (isloose) {
2424                                 for (i = 0; i < edgeSize; i++) {
2425                                         varray[iloosehidden * 2] = iloosevert;
2426                                         varray[iloosehidden * 2 + 1] = iloosevert + 1;
2427                                         iloosehidden++;
2428                                         iloosevert++;
2429                                 }
2430                                 /* we are through with this loose edge and moving to the next, so increase by one */
2431                                 iloosevert++;
2432                         }
2433                         else {
2434                                 index_start = ccgdm->faceMap[fhandle].startFace;
2435
2436                                 for (i = 0; i < grid_face_side; i++) {
2437                                         varray[inormhidden * 2] = (index_start + S * grid_tot_face + i * grid_face_side + grid_face_side - 1) * 4 + 1;
2438                                         varray[inormhidden * 2 + 1] = (index_start + S * grid_tot_face + i * grid_face_side + grid_face_side - 1) * 4 + 2;
2439                                         varray[inormhidden * 2 + 2] = (index_start + ((S + 1) % totvert) * grid_tot_face + grid_face_side * (grid_face_side - 1) + i) * 4 + 2;
2440                                         varray[inormhidden * 2 + 3] = (index_start + ((S + 1) % totvert) * grid_tot_face + grid_face_side * (grid_face_side - 1) + i) * 4 + 3;
2441                                         inormhidden += 2;
2442                                 }
2443                         }
2444                 }
2445                 else {
2446                         if (isloose) {
2447                                 for (i = 0; i < edgeSize; i++) {
2448                                         varray[iloose * 2] = iloosevert;
2449                                         varray[iloose * 2 + 1] = iloosevert + 1;
2450                                         iloose++;
2451                                         iloosevert++;
2452                                 }
2453                                 /* we are through with this loose edge and moving to the next, so increase by one */
2454                                 iloosevert++;
2455                         }
2456                         else {
2457                                 index_start = ccgdm->faceMap[fhandle].startFace;
2458
2459                                 for (i = 0; i < grid_face_side; i++) {
2460                                         varray[inorm * 2] = (index_start + S * grid_tot_face + i * grid_face_side + grid_face_side - 1) * 4 + 1;
2461                                         varray[inorm * 2 + 1] = (index_start + S * grid_tot_face + i * grid_face_side + grid_face_side - 1) * 4 + 2;
2462                                         varray[inorm * 2 + 2] = (index_start + ((S + 1) % totvert) * grid_tot_face + grid_face_side * (grid_face_side - 1) + i) * 4 + 2;
2463                                         varray[inorm * 2 + 3] = (index_start + ((S + 1) % totvert) * grid_tot_face + grid_face_side * (grid_face_side - 1) + i) * 4 + 3;
2464                                         inorm += 2;
2465                                 }
2466                         }
2467                 }
2468         }
2469
2470         /* part two, handle interior edges */
2471         inorm = totedge * grid_face_side * 2;
2472
2473         index_start = 0;
2474         for (i = 0; i < totface; i++) {
2475                 CCGFace *f = ccgdm->faceMap[i].face;
2476                 unsigned int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2477
2478                 for (S = 0; S < numVerts; S++) {
2479                         for (x = 1; x < grid_face_side; x++) {
2480                                 for (y = 0; y < grid_face_side; y++) {
2481                                         unsigned int tmp = (index_start + x * grid_face_side + y) * 4;
2482                                         varray[inorm * 2] = tmp;
2483                                         varray[inorm * 2 + 1] = tmp + 1;
2484                                         inorm++;
2485                                 }
2486                         }
2487                         for (x = 0; x < grid_face_side; x++) {
2488                                 for (y = 0; y < grid_face_side; y++) {
2489                                         unsigned int tmp = (index_start + x * grid_face_side + y) * 4;
2490                                         varray[inorm * 2] = tmp + 3;
2491                                         varray[inorm * 2 + 1] = tmp;
2492                                         inorm++;
2493                                 }
2494                         }
2495
2496                         tot_interior += grid_face_side * (2 * grid_face_side - 1);
2497                         index_start += grid_tot_face;
2498                 }
2499         }
2500
2501         dm->drawObject->tot_loose_edge_drawn = tot_loose * edgeSize;
2502         dm->drawObject->loose_edge_offset = (tot + tot_hidden) * edgeSize;
2503         dm->drawObject->tot_edge_drawn = tot * edgeSize;
2504
2505         dm->drawObject->interior_offset = totedge * edgeSize;
2506         dm->drawObject->totinterior = tot_interior;
2507 }
2508
2509 static void ccgDM_copy_gpu_data(
2510         DerivedMesh *dm, int type, void *varray_p,
2511         const int *mat_orig_to_new, const void *user_data)
2512 {
2513         /* 'varray_p' cast is redundant but include for self-documentation */
2514         switch (type) {
2515                 case GPU_BUFFER_VERTEX:
2516                         ccgDM_buffer_copy_vertex(dm, (float *)varray_p);
2517                         break;
2518                 case GPU_BUFFER_NORMAL:
2519                         ccgDM_buffer_copy_normal(dm, (short *)varray_p);
2520                         break;
2521                 case GPU_BUFFER_UV:
2522                         ccgDM_buffer_copy_uv(dm, (float *)varray_p);
2523                         break;
2524                 case GPU_BUFFER_UV_TEXPAINT:
2525                         ccgDM_buffer_copy_uv_texpaint(dm, (float *)varray_p);
2526                         break;
2527                 case GPU_BUFFER_COLOR:
2528                         ccgDM_buffer_copy_color(dm, (unsigned char *)varray_p, user_data);
2529                         break;
2530                 case GPU_BUFFER_UVEDGE:
2531                         ccgDM_buffer_copy_uvedge(dm, (float *)varray_p);
2532                         break;
2533                 case GPU_BUFFER_EDGE:
2534                         ccgDM_buffer_copy_edge(dm, (unsigned int *)varray_p);
2535                         break;
2536                 case GPU_BUFFER_TRIANGLES:
2537                         ccgDM_buffer_copy_triangles(dm, (unsigned int *)varray_p, mat_orig_to_new);
2538                         break;
2539                 default:
2540                         break;
2541         }
2542 }
2543
2544 static GPUDrawObject *ccgDM_GPUObjectNew(DerivedMesh *dm)
2545 {
2546         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2547         CCGSubSurf *ss = ccgdm->ss;
2548         GPUDrawObject *gdo;
2549         DMFlagMat *faceFlags = ccgdm->faceFlags;
2550         int gridFaces = ccgSubSurf_getGridSize(ss) - 1;
2551         const short dm_totmat = (faceFlags) ? dm->totmat : 1;
2552         GPUBufferMaterial *matinfo;
2553         int i;
2554         unsigned int tot_internal_edges = 0;
2555         int edgeVerts = ccgSubSurf_getEdgeSize(ss);
2556         int edgeSize = edgeVerts - 1;
2557
2558         int totedge = ccgSubSurf_getNumEdges(ss);
2559         int totface = ccgSubSurf_getNumFaces(ss);
2560
2561         /* object contains at least one material (default included) so zero means uninitialized dm */
2562         BLI_assert(dm_totmat != 0);
2563
2564         matinfo = MEM_callocN(sizeof(*matinfo) * dm_totmat, "GPU_drawobject_new.mat_orig_to_new");
2565         
2566         if (faceFlags) {
2567                 for (i = 0; i < totface; i++) {
2568                         CCGFace *f = ccgdm->faceMap[i].face;
2569                         int numVerts = ccgSubSurf_getFaceNumVerts(f);
2570                         int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2571                         const short new_matnr = ME_MAT_NR_TEST(faceFlags[index].mat_nr, dm_totmat);
2572                         matinfo[new_matnr].totelements += numVerts * gridFaces * gridFaces * 6;
2573                         matinfo[new_matnr].totloops += numVerts * gridFaces * gridFaces * 4;
2574                         matinfo[new_matnr].totpolys++;
2575                         tot_internal_edges += numVerts * gridFaces * (2 * gridFaces - 1);
2576                 }
2577         }
2578         else {
2579                 for (i = 0; i < totface; i++) {
2580                         CCGFace *f = ccgdm->faceMap[i].face;
2581                         int numVerts = ccgSubSurf_getFaceNumVerts(f);
2582                         matinfo[0].totelements += numVerts * gridFaces * gridFaces * 6;
2583                         matinfo[0].totloops += numVerts * gridFaces * gridFaces * 4;
2584                         matinfo[0].totpolys++;
2585                         tot_internal_edges += numVerts * gridFaces * (2 * gridFaces - 1);
2586                 }
2587         }
2588         
2589         /* create the GPUDrawObject */
2590         gdo = MEM_callocN(sizeof(GPUDrawObject), "GPUDrawObject");
2591         gdo->totvert = 0; /* used to count indices, doesn't really matter for ccgsubsurf */
2592         gdo->totedge = (totedge * edgeSize + tot_internal_edges);
2593
2594         GPU_buffer_material_finalize(gdo, matinfo, dm_totmat);
2595
2596         /* store total number of points used for triangles */
2597         gdo->tot_triangle_point = ccgSubSurf_getNumFinalFaces(ss) * 6;
2598         gdo->tot_loop_verts = ccgSubSurf_getNumFinalFaces(ss) * 4;
2599
2600         /* finally, count loose points */
2601         for (i = 0; i < totedge; i++) {
2602                 CCGEdge *e = ccgdm->edgeMap[i].edge;
2603
2604                 if (!ccgSubSurf_getEdgeNumFaces(e))
2605                         gdo->tot_loose_point += edgeVerts;
2606         }
2607
2608         return gdo;
2609 }
2610
2611 /* Only used by non-editmesh types */
2612 static void ccgDM_drawFacesSolid(DerivedMesh *dm, float (*partial_redraw_planes)[4], bool fast, DMSetMaterial setMaterial)
2613 {
2614         int a;
2615         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2616
2617         ccgdm_pbvh_update(ccgdm);
2618
2619         if (ccgdm->pbvh && ccgdm->multires.mmd) {
2620                 if (BKE_pbvh_has_faces(ccgdm->pbvh)) {
2621                         BKE_pbvh_draw(ccgdm->pbvh, partial_redraw_planes, NULL,
2622                                       setMaterial, false, fast);
2623                         glShadeModel(GL_FLAT);
2624                 }
2625
2626                 return;
2627         }
2628
2629 #ifdef WITH_OPENSUBDIV
2630         if (ccgdm->useGpuBackend) {
2631                 CCGSubSurf *ss = ccgdm->ss;
2632                 const DMFlagMat *faceFlags = ccgdm->faceFlags;
2633                 const int level = ccgSubSurf_getSubdivisionLevels(ss);
2634                 const int face_side = 1 << level;
2635                 const int grid_side = 1 << (level - 1);
2636                 const int face_patches = face_side * face_side;
2637                 const int grid_patches = grid_side * grid_side;
2638                 const int num_base_faces = ccgSubSurf_getNumGLMeshBaseFaces(ss);
2639                 int i, current_patch = 0;
2640                 int mat_nr = -1;
2641                 bool draw_smooth = false;
2642                 int start_draw_patch = -1, num_draw_patches = 0;
2643                 if (UNLIKELY(ccgSubSurf_prepareGLMesh(ss, setMaterial != NULL) == false)) {
2644                         return;
2645                 }
2646                 if (setMaterial == NULL) {
2647                         ccgSubSurf_drawGLMesh(ss,
2648                                               true,
2649                                               -1,
2650                                               -1);
2651                         return;
2652                 }
2653                 for (i = 0; i < num_base_faces; ++i) {
2654                         const int num_face_verts = ccgSubSurf_getNumGLMeshBaseFaceVerts(ss, i);
2655                         const int num_patches = (num_face_verts == 4) ? face_patches
2656                                                                       : num_face_verts * grid_patches;
2657                         int new_matnr;
2658                         bool new_draw_smooth;
2659                         if (faceFlags) {
2660                                 new_draw_smooth = (faceFlags[i].flag & ME_SMOOTH);
2661                                 new_matnr = (faceFlags[i].mat_nr + 1);
2662                         }
2663                         else {
2664                                 new_draw_smooth = true;
2665                                 new_matnr = 1;
2666                         }
2667                         if (new_draw_smooth != draw_smooth || new_matnr != mat_nr) {
2668                                 if (num_draw_patches != 0) {
2669                                         bool do_draw = setMaterial(mat_nr, NULL);
2670                                         if (do_draw) {
2671                                                 glShadeModel(draw_smooth ? GL_SMOOTH : GL_FLAT);
2672                                                 ccgSubSurf_drawGLMesh(ss,
2673                                                                       true,
2674                                                                       start_draw_patch,
2675                                                                       num_draw_patches);
2676                                         }
2677                                 }
2678                                 start_draw_patch = current_patch;
2679                                 num_draw_patches = num_patches;
2680                                 mat_nr = new_matnr;
2681                                 draw_smooth = new_draw_smooth;
2682                         }
2683                         else {
2684                                 num_draw_patches += num_patches;
2685                         }
2686                         current_patch += num_patches;
2687                 }
2688                 if (num_draw_patches != 0) {
2689                         bool do_draw = setMaterial(mat_nr, NULL);
2690                         if (do_draw) {
2691                                 glShadeModel(draw_smooth ? GL_SMOOTH : GL_FLAT);
2692                                 ccgSubSurf_drawGLMesh(ss,
2693                                                       true,
2694                                                       start_draw_patch,
2695                                                       num_draw_patches);
2696                         }
2697                 }
2698                 return;
2699         }
2700 #endif
2701
2702         GPU_vertex_setup(dm);
2703         GPU_normal_setup(dm);
2704         GPU_triangle_setup(dm);
2705         glShadeModel(GL_SMOOTH);
2706         for (a = 0; a < dm->drawObject->totmaterial; a++) {
2707                 if (!setMaterial || setMaterial(dm->drawObject->materials[a].mat_nr + 1, NULL)) {
2708                         GPU_buffer_draw_elements(dm->drawObject->triangles, GL_TRIANGLES, dm->drawObject->materials[a].start,
2709                                                  dm->drawObject->materials[a].totelements);
2710                 }
2711         }
2712         GPU_buffers_unbind();
2713 }
2714
2715 typedef struct {
2716         DMVertexAttribs attribs;
2717         int numdata;
2718
2719         GPUAttrib datatypes[GPU_MAX_ATTRIB]; /* TODO, messing up when switching materials many times - [#21056]*/
2720 } GPUMaterialConv;
2721
2722 /* Only used by non-editmesh types */
2723 static void ccgDM_drawMappedFacesGLSL(DerivedMesh *dm,
2724                                       DMSetMaterial setMaterial,
2725                                       DMSetDrawOptions setDrawOptions,
2726                                       void *userData)
2727 {
2728         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2729         CCGSubSurf *ss = ccgdm->ss;
2730         CCGKey key;
2731         GPUVertexAttribs gattribs;
2732         int a, b;
2733         const DMFlagMat *faceFlags = ccgdm->faceFlags;
2734         unsigned char *varray;
2735         size_t max_element_size = 0;
2736         int tot_loops = 0;
2737         int totpoly = ccgSubSurf_getNumFaces(ss);
2738         int gridSize = ccgSubSurf_getGridSize(ss);
2739         int gridFaces = gridSize - 1;
2740         int edgeSize = ccgSubSurf_getEdgeSize(ss);
2741
2742 #ifdef WITH_OPENSUBDIV
2743         if (ccgdm->useGpuBackend) {
2744                 const int level = ccgSubSurf_getSubdivisionLevels(ss);
2745                 const int face_side = 1 << level;
2746                 const int grid_side = 1 << (level - 1);
2747                 const int face_patches = face_side * face_side;
2748                 const int grid_patches = grid_side * grid_side;
2749                 const int num_base_faces = ccgSubSurf_getNumGLMeshBaseFaces(ss);
2750                 int i, current_patch = 0;
2751                 int mat_nr = -1;
2752                 bool draw_smooth = false;
2753                 int start_draw_patch = -1, num_draw_patches = 0;
2754                 GPU_draw_update_fvar_offset(dm);
2755                 if (UNLIKELY(ccgSubSurf_prepareGLMesh(ss, false) == false)) {
2756                         return;
2757                 }
2758                 for (i = 0; i < num_base_faces; ++i) {
2759                         const int num_face_verts = ccgSubSurf_getNumGLMeshBaseFaceVerts(ss, i);
2760                         const int num_patches = (num_face_verts == 4) ? face_patches
2761                                                                       : num_face_verts * grid_patches;
2762                         int new_matnr;
2763                         bool new_draw_smooth;
2764
2765                         if (faceFlags) {
2766                                 new_draw_smooth = (faceFlags[i].flag & ME_SMOOTH);
2767                                 new_matnr = (faceFlags[i].mat_nr + 1);
2768                         }
2769                         else {
2770                                 new_draw_smooth = true;
2771                                 new_matnr = 1;
2772                         }
2773                         if (new_draw_smooth != draw_smooth || new_matnr != mat_nr) {
2774                                 if (num_draw_patches != 0) {
2775                                         bool do_draw = setMaterial(mat_nr, &gattribs);
2776                                         if (do_draw) {
2777                                                 glShadeModel(draw_smooth ? GL_SMOOTH : GL_FLAT);
2778                                                 ccgSubSurf_drawGLMesh(ss,
2779                                                                       true,
2780                                                                       start_draw_patch,
2781                                                                       num_draw_patches);
2782                                         }
2783                                 }
2784                                 start_draw_patch = current_patch;
2785                                 num_draw_patches = num_patches;
2786                                 mat_nr = new_matnr;
2787                                 draw_smooth = new_draw_smooth;
2788                         }
2789                         else {
2790                                 num_draw_patches += num_patches;
2791                         }
2792                         current_patch += num_patches;
2793                 }
2794                 if (num_draw_patches != 0) {
2795                         bool do_draw = setMaterial(mat_nr, &gattribs);
2796                         if (do_draw) {
2797                                 glShadeModel(draw_smooth ? GL_SMOOTH : GL_FLAT);
2798                                 ccgSubSurf_drawGLMesh(ss,
2799                                                       true,
2800                                                       start_draw_patch,
2801                                                       num_draw_patches);
2802                         }
2803                 }
2804                 return;
2805         }
2806 #endif
2807
2808         glShadeModel(GL_SMOOTH);
2809
2810         CCG_key_top_level(&key, ss);
2811         ccgdm_pbvh_update(ccgdm);
2812
2813         if (setDrawOptions != NULL) {
2814                 const float (*lnors)[3] = dm->getLoopDataArray(dm, CD_NORMAL);
2815                 DMVertexAttribs attribs = {{{NULL}}};
2816                 int i;
2817                 int matnr = -1;
2818                 int do_draw = 0;
2819
2820 #define PASSATTRIB(dx, dy, vert) {                                            \
2821         if (attribs.totorco)                                                      \
2822                 index = getFaceIndex(ss, f, S, x + dx, y + dy, edgeSize, gridSize);   \
2823         else                                                                      \
2824                 index = 0;                                                            \
2825         DM_draw_attrib_vertex(&attribs, a, index, vert, ((a) * 4) + vert);        \
2826 } (void)0
2827
2828                 totpoly = ccgSubSurf_getNumFaces(ss);
2829                 for (a = 0, i = 0; i < totpoly; i++) {
2830                         CCGFace *f = ccgdm->faceMap[i].face;
2831                         const float (*ln)[3] = NULL;
2832                         int S, x, y, drawSmooth;
2833                         int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2834                         int origIndex = ccgDM_getFaceMapIndex(ss, f);
2835
2836                         int numVerts = ccgSubSurf_getFaceNumVerts(f);
2837                         int new_matnr;
2838
2839                         if (faceFlags) {
2840                                 drawSmooth = (lnors || (faceFlags[index].flag & ME_SMOOTH));
2841                                 new_matnr = faceFlags[index].mat_nr + 1;
2842                         }
2843                         else {
2844                                 drawSmooth = 1;
2845                                 new_matnr = 1;
2846                         }
2847
2848                         if (lnors) {
2849                                 ln = lnors;
2850                                 lnors += (gridFaces * gridFaces * numVerts) * 4;
2851                         }
2852
2853                         if (new_matnr != matnr) {
2854                                 do_draw = setMaterial(matnr = new_matnr, &gattribs);
2855                                 if (do_draw)
2856                                         DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
2857                         }
2858
2859                         if (!do_draw || (setDrawOptions && (origIndex != ORIGINDEX_NONE) &&
2860                                         (setDrawOptions(userData, origIndex) == DM_DRAW_OPTION_SKIP)))
2861                         {
2862                                 a += gridFaces * gridFaces * numVerts;
2863                                 continue;
2864                         }
2865
2866                         glShadeModel(drawSmooth ? GL_SMOOTH : GL_FLAT);
2867                         for (S = 0; S < numVerts; S++) {
2868                                 CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
2869                                 CCGElem *vda, *vdb;
2870
2871                                 if (ln) {
2872                                         glBegin(GL_QUADS);
2873                                         for (y = 0; y < gridFaces; y++) {
2874                                                 for (x = 0; x < gridFaces; x++) {
2875                                                         float *aco = CCG_grid_elem_co(&key, faceGridData, x, y);
2876                                                         float *bco = CCG_grid_elem_co(&key, faceGridData, x + 1, y);
2877                                                         float *cco = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
2878                                                         float *dco = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
2879
2880                                                         PASSATTRIB(0, 1, 1);
2881                                                         glNormal3fv(ln[1]);
2882                                                         glVertex3fv(dco);
2883                                                         PASSATTRIB(1, 1, 2);
2884                                                         glNormal3fv(ln[2]);
2885                                                         glVertex3fv(cco);
2886                                                         PASSATTRIB(1, 0, 3);
2887                                                         glNormal3fv(ln[3]);
2888                                                         glVertex3fv(bco);
2889                                                         PASSATTRIB(0, 0, 0);
2890                                                         glNormal3fv(ln[0]);
2891                                                         glVertex3fv(aco);
2892
2893                                                         ln += 4;
2894                                                         a++;
2895                                                 }
2896                                         }
2897                                         glEnd();
2898                                 }
2899                                 else if (drawSmooth) {
2900                                         for (y = 0; y < gridFaces; y++) {
2901                                                 glBegin(GL_QUAD_STRIP);
2902                                                 for (x = 0; x < gridFaces; x++) {
2903                                                         vda = CCG_grid_elem(&key, faceGridData, x, y + 0);
2904                                                         vdb = CCG_grid_elem(&key, faceGridData, x, y + 1);
2905
2906                                                         PASSATTRIB(0, 0, 0);
2907                                                         glNormal3fv(CCG_elem_no(&key, vda));
2908                                                         glVertex3fv(CCG_elem_co(&key, vda));
2909
2910                                                         PASSATTRIB(0, 1, 1);
2911                                                         glNormal3fv(CCG_elem_no(&key, vdb));
2912                                                         glVertex3fv(CCG_elem_co(&key, vdb));
2913
2914                                                         if (x != gridFaces - 1)
2915                                                                 a++;
2916                                                 }
2917
2918                                                 vda = CCG_grid_elem(&key, faceGridData, x, y + 0);
2919                                                 vdb = CCG_grid_elem(&key, faceGridData, x, y + 1);
2920
2921                                                 PASSATTRIB(0, 0, 3);
2922                                                 glNormal3fv(CCG_elem_no(&key, vda));
2923                                                 glVertex3fv(CCG_elem_co(&key, vda));
2924
2925                                                 PASSATTRIB(0, 1, 2);
2926                                                 glNormal3fv(CCG_elem_no(&key, vdb));
2927                                                 glVertex3fv(CCG_elem_co(&key, vdb));
2928
2929                                                 glEnd();
2930
2931                                                 a++;
2932                                         }
2933                                 }
2934                                 else {
2935                                         glBegin(GL_QUADS);
2936                                         for (y = 0; y < gridFaces; y++) {
2937                                                 for (x = 0; x < gridFaces; x++) {
2938                                                         float *aco = CCG_grid_elem_co(&key, faceGridData, x, y);
2939                                                         float *bco = CCG_grid_elem_co(&key, faceGridData, x + 1, y);
2940                                                         float *cco = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
2941                                                         float *dco = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
2942
2943                                                         ccgDM_glNormalFast(aco, bco, cco, dco);
2944
2945                                                         PASSATTRIB(0, 1, 1);
2946                                                         glVertex3fv(dco);
2947                         &