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