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