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