Merged revision(s) 57908-57978 from trunk/blender into soc-2013-dingto.
[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
57 #include "BKE_pbvh.h"
58 #include "BKE_ccg.h"
59 #include "BKE_cdderivedmesh.h"
60 #include "BKE_global.h"
61 #include "BKE_mesh.h"
62 #include "BKE_modifier.h"
63 #include "BKE_multires.h"
64 #include "BKE_paint.h"
65 #include "BKE_scene.h"
66 #include "BKE_subsurf.h"
67 #include "BKE_editmesh.h"
68
69 #include "PIL_time.h"
70
71 #ifndef USE_DYNSIZE
72 #  include "BLI_array.h"
73 #endif
74
75 #include "GL/glew.h"
76
77 #include "GPU_draw.h"
78 #include "GPU_extensions.h"
79 #include "GPU_material.h"
80
81 #include "CCGSubSurf.h"
82
83 extern GLubyte stipple_quarttone[128]; /* glutil.c, bad level data */
84
85 static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
86                                          int drawInteriorEdges,
87                                          int useSubsurfUv,
88                                          DerivedMesh *dm);
89 static int ccgDM_use_grid_pbvh(CCGDerivedMesh *ccgdm);
90
91 ///
92
93 static void *arena_alloc(CCGAllocatorHDL a, int numBytes)
94 {
95         return BLI_memarena_alloc(a, numBytes);
96 }
97
98 static void *arena_realloc(CCGAllocatorHDL a, void *ptr, int newSize, int oldSize)
99 {
100         void *p2 = BLI_memarena_alloc(a, newSize);
101         if (ptr) {
102                 memcpy(p2, ptr, oldSize);
103         }
104         return p2;
105 }
106
107 static void arena_free(CCGAllocatorHDL UNUSED(a), void *UNUSED(ptr))
108 {
109         /* do nothing */
110 }
111
112 static void arena_release(CCGAllocatorHDL a)
113 {
114         BLI_memarena_free(a);
115 }
116
117 typedef enum {
118         CCG_USE_AGING = 1,
119         CCG_USE_ARENA = 2,
120         CCG_CALC_NORMALS = 4,
121         /* add an extra four bytes for a mask layer */
122         CCG_ALLOC_MASK = 8,
123         CCG_SIMPLE_SUBDIV = 16
124 } CCGFlags;
125
126 static CCGSubSurf *_getSubSurf(CCGSubSurf *prevSS, int subdivLevels,
127                                int numLayers, CCGFlags flags)
128 {
129         CCGMeshIFC ifc;
130         CCGSubSurf *ccgSS;
131         int useAging = !!(flags & CCG_USE_AGING);
132         int useArena = flags & CCG_USE_ARENA;
133         int normalOffset = 0;
134
135         /* (subdivLevels == 0) is not allowed */
136         subdivLevels = MAX2(subdivLevels, 1);
137
138         if (prevSS) {
139                 int oldUseAging;
140
141                 ccgSubSurf_getUseAgeCounts(prevSS, &oldUseAging, NULL, NULL, NULL);
142
143                 if ((oldUseAging != useAging) ||
144                         (ccgSubSurf_getSimpleSubdiv(prevSS) !=
145                          !!(flags & CCG_SIMPLE_SUBDIV)))
146                 {
147                         ccgSubSurf_free(prevSS);
148                 }
149                 else {
150                         ccgSubSurf_setSubdivisionLevels(prevSS, subdivLevels);
151
152                         return prevSS;
153                 }
154         }
155
156         if (useAging) {
157                 ifc.vertUserSize = ifc.edgeUserSize = ifc.faceUserSize = 12;
158         }
159         else {
160                 ifc.vertUserSize = ifc.edgeUserSize = ifc.faceUserSize = 8;
161         }
162         ifc.numLayers = numLayers;
163         ifc.vertDataSize = sizeof(float) * numLayers;
164         normalOffset += sizeof(float) * numLayers;
165         if (flags & CCG_CALC_NORMALS)
166                 ifc.vertDataSize += sizeof(float) * 3;
167         if (flags & CCG_ALLOC_MASK)
168                 ifc.vertDataSize += sizeof(float);
169         ifc.simpleSubdiv = !!(flags & CCG_SIMPLE_SUBDIV);
170
171         if (useArena) {
172                 CCGAllocatorIFC allocatorIFC;
173                 CCGAllocatorHDL allocator = BLI_memarena_new((1 << 16), "subsurf arena");
174
175                 allocatorIFC.alloc = arena_alloc;
176                 allocatorIFC.realloc = arena_realloc;
177                 allocatorIFC.free = arena_free;
178                 allocatorIFC.release = arena_release;
179
180                 ccgSS = ccgSubSurf_new(&ifc, subdivLevels, &allocatorIFC, allocator);
181         }
182         else {
183                 ccgSS = ccgSubSurf_new(&ifc, subdivLevels, NULL, NULL);
184         }
185
186         if (useAging) {
187                 ccgSubSurf_setUseAgeCounts(ccgSS, 1, 8, 8, 8);
188         }
189
190         if (flags & CCG_ALLOC_MASK) {
191                 normalOffset += sizeof(float);
192                 /* mask is allocated after regular layers */
193                 ccgSubSurf_setAllocMask(ccgSS, 1, sizeof(float) * numLayers);
194         }
195         
196         if (flags & CCG_CALC_NORMALS)
197                 ccgSubSurf_setCalcVertexNormals(ccgSS, 1, normalOffset);
198         else
199                 ccgSubSurf_setCalcVertexNormals(ccgSS, 0, 0);
200
201         return ccgSS;
202 }
203
204 static int getEdgeIndex(CCGSubSurf *ss, CCGEdge *e, int x, int edgeSize)
205 {
206         CCGVert *v0 = ccgSubSurf_getEdgeVert0(e);
207         CCGVert *v1 = ccgSubSurf_getEdgeVert1(e);
208         int v0idx = *((int *) ccgSubSurf_getVertUserData(ss, v0));
209         int v1idx = *((int *) ccgSubSurf_getVertUserData(ss, v1));
210         int edgeBase = *((int *) ccgSubSurf_getEdgeUserData(ss, e));
211
212         if (x == 0) {
213                 return v0idx;
214         }
215         else if (x == edgeSize - 1) {
216                 return v1idx;
217         }
218         else {
219                 return edgeBase + x - 1;
220         }
221 }
222
223 static int getFaceIndex(CCGSubSurf *ss, CCGFace *f, int S, int x, int y, int edgeSize, int gridSize)
224 {
225         int faceBase = *((int *) ccgSubSurf_getFaceUserData(ss, f));
226         int numVerts = ccgSubSurf_getFaceNumVerts(f);
227
228         if (x == gridSize - 1 && y == gridSize - 1) {
229                 CCGVert *v = ccgSubSurf_getFaceVert(f, S);
230                 return *((int *) ccgSubSurf_getVertUserData(ss, v));
231         }
232         else if (x == gridSize - 1) {
233                 CCGVert *v = ccgSubSurf_getFaceVert(f, S);
234                 CCGEdge *e = ccgSubSurf_getFaceEdge(f, S);
235                 int edgeBase = *((int *) ccgSubSurf_getEdgeUserData(ss, e));
236                 if (v == ccgSubSurf_getEdgeVert0(e)) {
237                         return edgeBase + (gridSize - 1 - y) - 1;
238                 }
239                 else {
240                         return edgeBase + (edgeSize - 2 - 1) - ((gridSize - 1 - y) - 1);
241                 }
242         }
243         else if (y == gridSize - 1) {
244                 CCGVert *v = ccgSubSurf_getFaceVert(f, S);
245                 CCGEdge *e = ccgSubSurf_getFaceEdge(f, (S + numVerts - 1) % numVerts);
246                 int edgeBase = *((int *) ccgSubSurf_getEdgeUserData(ss, e));
247                 if (v == ccgSubSurf_getEdgeVert0(e)) {
248                         return edgeBase + (gridSize - 1 - x) - 1;
249                 }
250                 else {
251                         return edgeBase + (edgeSize - 2 - 1) - ((gridSize - 1 - x) - 1);
252                 }
253         }
254         else if (x == 0 && y == 0) {
255                 return faceBase;
256         }
257         else if (x == 0) {
258                 S = (S + numVerts - 1) % numVerts;
259                 return faceBase + 1 + (gridSize - 2) * S + (y - 1);
260         }
261         else if (y == 0) {
262                 return faceBase + 1 + (gridSize - 2) * S + (x - 1);
263         }
264         else {
265                 return faceBase + 1 + (gridSize - 2) * numVerts + S * (gridSize - 2) * (gridSize - 2) + (y - 1) * (gridSize - 2) + (x - 1);
266         }
267 }
268
269 static void get_face_uv_map_vert(UvVertMap *vmap, struct MPoly *mpoly, struct MLoop *ml, int fi, CCGVertHDL *fverts)
270 {
271         UvMapVert *v, *nv;
272         int j, nverts = mpoly[fi].totloop;
273
274         for (j = 0; j < nverts; j++) {
275                 for (nv = v = BKE_mesh_uv_vert_map_get_vert(vmap, ml[j].v); v; v = v->next) {
276                         if (v->separate)
277                                 nv = v;
278                         if (v->f == fi)
279                                 break;
280                 }
281
282                 fverts[j] = SET_UINT_IN_POINTER(mpoly[nv->f].loopstart + nv->tfindex);
283         }
284 }
285
286 static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm, MLoopUV *mloopuv)
287 {
288         MPoly *mpoly = dm->getPolyArray(dm);
289         MLoop *mloop = dm->getLoopArray(dm);
290         MVert *mvert = dm->getVertArray(dm);
291         int totvert = dm->getNumVerts(dm);
292         int totface = dm->getNumPolys(dm);
293         int i, seam;
294         UvMapVert *v;
295         UvVertMap *vmap;
296         float limit[2];
297 #ifndef USE_DYNSIZE
298         CCGVertHDL *fverts = NULL;
299         BLI_array_declare(fverts);
300 #endif
301         EdgeHash *ehash;
302         float creaseFactor = (float)ccgSubSurf_getSubdivisionLevels(ss);
303         float uv[3] = {0.0f, 0.0f, 0.0f}; /* only first 2 values are written into */
304
305         limit[0] = limit[1] = STD_UV_CONNECT_LIMIT;
306         vmap = BKE_mesh_uv_vert_map_create(mpoly, mloop, mloopuv, totface, totvert, 0, limit);
307         if (!vmap)
308                 return 0;
309         
310         ccgSubSurf_initFullSync(ss);
311
312         /* create vertices */
313         for (i = 0; i < totvert; i++) {
314                 if (!BKE_mesh_uv_vert_map_get_vert(vmap, i))
315                         continue;
316
317                 for (v = BKE_mesh_uv_vert_map_get_vert(vmap, i)->next; v; v = v->next)
318                         if (v->separate)
319                                 break;
320
321                 seam = (v != NULL) || ((mvert + i)->flag & ME_VERT_MERGED);
322
323                 for (v = BKE_mesh_uv_vert_map_get_vert(vmap, i); v; v = v->next) {
324                         if (v->separate) {
325                                 CCGVert *ssv;
326                                 int loopid = mpoly[v->f].loopstart + v->tfindex;
327                                 CCGVertHDL vhdl = SET_INT_IN_POINTER(loopid);
328
329                                 copy_v2_v2(uv, mloopuv[loopid].uv);
330
331                                 ccgSubSurf_syncVert(ss, vhdl, uv, seam, &ssv);
332                         }
333                 }
334         }
335
336         /* create edges */
337         ehash = BLI_edgehash_new();
338
339         for (i = 0; i < totface; i++) {
340                 MPoly *mp = &((MPoly *) mpoly)[i];
341                 int nverts = mp->totloop;
342                 int j, j_next;
343                 CCGFace *origf = ccgSubSurf_getFace(origss, SET_INT_IN_POINTER(i));
344                 /* unsigned int *fv = &mp->v1; */
345                 MLoop *ml = mloop + mp->loopstart;
346
347 #ifdef USE_DYNSIZE
348                 CCGVertHDL fverts[nverts];
349 #else
350                 BLI_array_empty(fverts);
351                 BLI_array_grow_items(fverts, nverts);
352 #endif
353
354                 get_face_uv_map_vert(vmap, mpoly, ml, i, fverts);
355
356                 for (j = 0, j_next = nverts - 1; j < nverts; j_next = j++) {
357                         unsigned int v0 = GET_UINT_FROM_POINTER(fverts[j_next]);
358                         unsigned int v1 = GET_UINT_FROM_POINTER(fverts[j]);
359                         MVert *mv0 = mvert + (ml[j_next].v);
360                         MVert *mv1 = mvert + (ml[j].v);
361
362                         if (!BLI_edgehash_haskey(ehash, v0, v1)) {
363                                 CCGEdge *e, *orige = ccgSubSurf_getFaceEdge(origf, j_next);
364                                 CCGEdgeHDL ehdl = SET_INT_IN_POINTER(mp->loopstart + j_next);
365                                 float crease;
366
367                                 if ((mv0->flag & mv1->flag) & ME_VERT_MERGED)
368                                         crease = creaseFactor;
369                                 else
370                                         crease = ccgSubSurf_getEdgeCrease(orige);
371
372                                 ccgSubSurf_syncEdge(ss, ehdl, fverts[j_next], fverts[j], crease, &e);
373                                 BLI_edgehash_insert(ehash, v0, v1, NULL);
374                         }
375                 }
376         }
377
378         BLI_edgehash_free(ehash, NULL);
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 min_r[3], float max_r[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                 min_r[0] = min_r[1] = min_r[2] = max_r[0] = max_r[1] = max_r[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, min_r, max_r);
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), min_r, max_r);
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), min_r, max_r);
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 co_r[3])
868 {
869         MVert mvert;
870
871         ccgDM_getFinalVert(dm, vertNum, &mvert);
872         copy_v3_v3(co_r, mvert.co);
873 }
874
875 static void ccgDM_getFinalVertNo(DerivedMesh *dm, int vertNum, float no_r[3])
876 {
877         MVert mvert;
878
879         ccgDM_getFinalVert(dm, vertNum, &mvert);
880         normal_short_to_float_v3(no_r, 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 = ccg_gridsize(md->level);
1069                         int factor = 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_GET(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 = ccg_factor(level, gpm->level);
1112                         gpm_gridsize = 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                 MEdge *medge;
1334
1335                 ccgdm->ehash = BLI_edgehash_new();
1336                 medge = ccgdm->dm.getEdgeArray((DerivedMesh *)ccgdm);
1337
1338                 for (i = 0; i < ccgdm->dm.numEdgeData; i++) {
1339                         BLI_edgehash_insert(ccgdm->ehash, medge[i].v1, medge[i].v2, SET_INT_IN_POINTER(i));
1340                 }
1341         }
1342
1343         totface = ccgSubSurf_getNumFaces(ss);
1344         mv = mloop;
1345         for (index = 0; index < totface; index++) {
1346                 CCGFace *f = ccgdm->faceMap[index].face;
1347                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1348                 /* int flag = (faceFlags) ? faceFlags[index * 2]: ME_SMOOTH; */ /* UNUSED */
1349                 /* int mat_nr = (faceFlags) ? faceFlags[index * 2 + 1]: 0; */ /* UNUSED */
1350
1351                 for (S = 0; S < numVerts; S++) {
1352                         for (y = 0; y < gridSize - 1; y++) {
1353                                 for (x = 0; x < gridSize - 1; x++) {
1354                                         unsigned int v1, v2, v3, v4;
1355
1356                                         v1 = getFaceIndex(ss, f, S, x + 0, y + 0,
1357                                                           edgeSize, gridSize);
1358
1359                                         v2 = getFaceIndex(ss, f, S, x + 0, y + 1,
1360                                                           edgeSize, gridSize);
1361                                         v3 = getFaceIndex(ss, f, S, x + 1, y + 1,
1362                                                           edgeSize, gridSize);
1363                                         v4 = getFaceIndex(ss, f, S, x + 1, y + 0,
1364                                                           edgeSize, gridSize);
1365
1366                                         mv->v = v1;
1367                                         mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v1, v2));
1368                                         mv++, i++;
1369
1370                                         mv->v = v2;
1371                                         mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v2, v3));
1372                                         mv++, i++;
1373
1374                                         mv->v = v3;
1375                                         mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v3, v4));
1376                                         mv++, i++;
1377
1378                                         mv->v = v4;
1379                                         mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v4, v1));
1380                                         mv++, i++;
1381                                 }
1382                         }
1383                 }
1384         }
1385 }
1386
1387 static void ccgDM_copyFinalPolyArray(DerivedMesh *dm, MPoly *mpoly)
1388 {
1389         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1390         CCGSubSurf *ss = ccgdm->ss;
1391         int index;
1392         int totface;
1393         int gridSize = ccgSubSurf_getGridSize(ss);
1394         /* int edgeSize = ccgSubSurf_getEdgeSize(ss); */ /* UNUSED */
1395         int i = 0, k = 0;
1396         DMFlagMat *faceFlags = ccgdm->faceFlags;
1397
1398         totface = ccgSubSurf_getNumFaces(ss);
1399         for (index = 0; index < totface; index++) {
1400                 CCGFace *f = ccgdm->faceMap[index].face;
1401                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1402                 int flag = (faceFlags) ? faceFlags[index].flag : ME_SMOOTH;
1403                 int mat_nr = (faceFlags) ? faceFlags[index].mat_nr : 0;
1404
1405                 for (S = 0; S < numVerts; S++) {
1406                         for (y = 0; y < gridSize - 1; y++) {
1407                                 for (x = 0; x < gridSize - 1; x++) {
1408                                         MPoly *mp = &mpoly[i];
1409
1410                                         mp->mat_nr = mat_nr;
1411                                         mp->flag = flag;
1412                                         mp->loopstart = k;
1413                                         mp->totloop = 4;
1414
1415                                         k += 4;
1416                                         i++;
1417                                 }
1418                         }
1419                 }
1420         }
1421 }
1422
1423 static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3])
1424 {
1425         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1426         CCGSubSurf *ss = ccgdm->ss;
1427         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1428         int gridSize = ccgSubSurf_getGridSize(ss);
1429         int i;
1430         CCGVertIterator *vi;
1431         CCGEdgeIterator *ei;
1432         CCGFaceIterator *fi;
1433         CCGFace **faceMap2;
1434         CCGEdge **edgeMap2;
1435         CCGVert **vertMap2;
1436         int index, totvert, totedge, totface;
1437         
1438         totvert = ccgSubSurf_getNumVerts(ss);
1439         vertMap2 = MEM_mallocN(totvert * sizeof(*vertMap2), "vertmap");
1440         for (vi = ccgSubSurf_getVertIterator(ss); !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
1441                 CCGVert *v = ccgVertIterator_getCurrent(vi);
1442
1443                 vertMap2[GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v))] = v;
1444         }
1445         ccgVertIterator_free(vi);
1446
1447         totedge = ccgSubSurf_getNumEdges(ss);
1448         edgeMap2 = MEM_mallocN(totedge * sizeof(*edgeMap2), "edgemap");
1449         for (ei = ccgSubSurf_getEdgeIterator(ss), i = 0; !ccgEdgeIterator_isStopped(ei); i++, ccgEdgeIterator_next(ei)) {
1450                 CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
1451
1452                 edgeMap2[GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e))] = e;
1453         }
1454
1455         totface = ccgSubSurf_getNumFaces(ss);
1456         faceMap2 = MEM_mallocN(totface * sizeof(*faceMap2), "facemap");
1457         for (fi = ccgSubSurf_getFaceIterator(ss); !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
1458                 CCGFace *f = ccgFaceIterator_getCurrent(fi);
1459
1460                 faceMap2[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f))] = f;
1461         }
1462         ccgFaceIterator_free(fi);
1463
1464         i = 0;
1465         for (index = 0; index < totface; index++) {
1466                 CCGFace *f = faceMap2[index];
1467                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1468
1469                 copy_v3_v3(cos[i++], ccgSubSurf_getFaceCenterData(f));
1470                 
1471                 for (S = 0; S < numVerts; S++) {
1472                         for (x = 1; x < gridSize - 1; x++) {
1473                                 copy_v3_v3(cos[i++], ccgSubSurf_getFaceGridEdgeData(ss, f, S, x));
1474                         }
1475                 }
1476
1477                 for (S = 0; S < numVerts; S++) {
1478                         for (y = 1; y < gridSize - 1; y++) {
1479                                 for (x = 1; x < gridSize - 1; x++) {
1480                                         copy_v3_v3(cos[i++], ccgSubSurf_getFaceGridData(ss, f, S, x, y));
1481                                 }
1482                         }
1483                 }
1484         }
1485
1486         for (index = 0; index < totedge; index++) {
1487                 CCGEdge *e = edgeMap2[index];
1488                 int x;
1489
1490                 for (x = 1; x < edgeSize - 1; x++) {
1491                         copy_v3_v3(cos[i++], ccgSubSurf_getEdgeData(ss, e, x));
1492                 }
1493         }
1494
1495         for (index = 0; index < totvert; index++) {
1496                 CCGVert *v = vertMap2[index];
1497                 copy_v3_v3(cos[i++], ccgSubSurf_getVertData(ss, v));
1498         }
1499
1500         MEM_freeN(vertMap2);
1501         MEM_freeN(edgeMap2);
1502         MEM_freeN(faceMap2);
1503 }
1504
1505 static void ccgDM_foreachMappedVert(
1506         DerivedMesh *dm,
1507         void (*func)(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3]),
1508         void *userData)
1509 {
1510         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1511         CCGVertIterator *vi;
1512         CCGKey key;
1513         CCG_key_top_level(&key, ccgdm->ss);
1514
1515         for (vi = ccgSubSurf_getVertIterator(ccgdm->ss); !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
1516                 CCGVert *v = ccgVertIterator_getCurrent(vi);
1517                 CCGElem *vd = ccgSubSurf_getVertData(ccgdm->ss, v);
1518                 int index = ccgDM_getVertMapIndex(ccgdm->ss, v);
1519
1520                 if (index != -1)
1521                         func(userData, index, CCG_elem_co(&key, vd), CCG_elem_no(&key, vd), NULL);
1522         }
1523
1524         ccgVertIterator_free(vi);
1525 }
1526
1527 static void ccgDM_foreachMappedEdge(
1528         DerivedMesh *dm,
1529         void (*func)(void *userData, int index, const float v0co[3], const float v1co[3]),
1530         void *userData)
1531 {
1532         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1533         CCGSubSurf *ss = ccgdm->ss;
1534         CCGEdgeIterator *ei;
1535         CCGKey key;
1536         int i, edgeSize = ccgSubSurf_getEdgeSize(ss);
1537
1538         CCG_key_top_level(&key, ss);
1539
1540         for (ei = ccgSubSurf_getEdgeIterator(ss); !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
1541                 CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
1542                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
1543                 int index = ccgDM_getEdgeMapIndex(ss, e);
1544
1545                 if (index != -1) {
1546                         for (i = 0; i < edgeSize - 1; i++)
1547                                 func(userData, index, CCG_elem_offset_co(&key, edgeData, i), CCG_elem_offset_co(&key, edgeData, i + 1));
1548                 }
1549         }
1550
1551         ccgEdgeIterator_free(ei);
1552 }
1553
1554 static void ccgDM_drawVerts(DerivedMesh *dm)
1555 {
1556         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1557         CCGSubSurf *ss = ccgdm->ss;
1558         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1559         int gridSize = ccgSubSurf_getGridSize(ss);
1560         CCGVertIterator *vi;
1561         CCGEdgeIterator *ei;
1562         CCGFaceIterator *fi;
1563
1564         glBegin(GL_POINTS);
1565         for (vi = ccgSubSurf_getVertIterator(ss); !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
1566                 CCGVert *v = ccgVertIterator_getCurrent(vi);
1567                 glVertex3fv(ccgSubSurf_getVertData(ss, v));
1568         }
1569         ccgVertIterator_free(vi);
1570
1571         for (ei = ccgSubSurf_getEdgeIterator(ss); !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
1572                 CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
1573                 int x;
1574
1575                 for (x = 1; x < edgeSize - 1; x++)
1576                         glVertex3fv(ccgSubSurf_getEdgeData(ss, e, x));
1577         }
1578         ccgEdgeIterator_free(ei);
1579
1580         for (fi = ccgSubSurf_getFaceIterator(ss); !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
1581                 CCGFace *f = ccgFaceIterator_getCurrent(fi);
1582                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1583
1584                 glVertex3fv(ccgSubSurf_getFaceCenterData(f));
1585                 for (S = 0; S < numVerts; S++)
1586                         for (x = 1; x < gridSize - 1; x++)
1587                                 glVertex3fv(ccgSubSurf_getFaceGridEdgeData(ss, f, S, x));
1588                 for (S = 0; S < numVerts; S++)
1589                         for (y = 1; y < gridSize - 1; y++)
1590                                 for (x = 1; x < gridSize - 1; x++)
1591                                         glVertex3fv(ccgSubSurf_getFaceGridData(ss, f, S, x, y));
1592         }
1593         ccgFaceIterator_free(fi);
1594         glEnd();
1595 }
1596
1597 static void ccgdm_pbvh_update(CCGDerivedMesh *ccgdm)
1598 {
1599         if (ccgdm->pbvh && ccgDM_use_grid_pbvh(ccgdm)) {
1600                 CCGFace **faces;
1601                 int totface;
1602
1603                 BKE_pbvh_get_grid_updates(ccgdm->pbvh, 1, (void ***)&faces, &totface);
1604                 if (totface) {
1605                         ccgSubSurf_updateFromFaces(ccgdm->ss, 0, faces, totface);
1606                         ccgSubSurf_updateNormals(ccgdm->ss, faces, totface);
1607                         MEM_freeN(faces);
1608                 }
1609         }
1610 }
1611
1612 static void ccgDM_drawEdges(DerivedMesh *dm, int drawLooseEdges, int drawAllEdges)
1613 {
1614         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1615         CCGSubSurf *ss = ccgdm->ss;
1616         CCGKey key;
1617         int i, j, edgeSize = ccgSubSurf_getEdgeSize(ss);
1618         int totedge = ccgSubSurf_getNumEdges(ss);
1619         int gridSize = ccgSubSurf_getGridSize(ss);
1620         int useAging;
1621
1622         CCG_key_top_level(&key, ss);
1623         ccgdm_pbvh_update(ccgdm);
1624
1625         ccgSubSurf_getUseAgeCounts(ss, &useAging, NULL, NULL, NULL);
1626
1627         for (j = 0; j < totedge; j++) {
1628                 CCGEdge *e = ccgdm->edgeMap[j].edge;
1629                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
1630
1631                 if (!drawLooseEdges && !ccgSubSurf_getEdgeNumFaces(e))
1632                         continue;
1633
1634                 if (!drawAllEdges && ccgdm->edgeFlags && !(ccgdm->edgeFlags[j] & ME_EDGEDRAW))
1635                         continue;
1636
1637                 if (useAging && !(G.f & G_BACKBUFSEL)) {
1638                         int ageCol = 255 - ccgSubSurf_getEdgeAge(ss, e) * 4;
1639                         glColor3ub(0, ageCol > 0 ? ageCol : 0, 0);
1640                 }
1641
1642                 glBegin(GL_LINE_STRIP);
1643                 for (i = 0; i < edgeSize - 1; i++) {
1644                         glVertex3fv(CCG_elem_offset_co(&key, edgeData, i));
1645                         glVertex3fv(CCG_elem_offset_co(&key, edgeData, i + 1));
1646                 }
1647                 glEnd();
1648         }
1649
1650         if (useAging && !(G.f & G_BACKBUFSEL)) {
1651                 glColor3ub(0, 0, 0);
1652         }
1653
1654         if (ccgdm->drawInteriorEdges) {
1655                 int totface = ccgSubSurf_getNumFaces(ss);
1656
1657                 for (j = 0; j < totface; j++) {
1658                         CCGFace *f = ccgdm->faceMap[j].face;
1659                         int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
1660
1661                         for (S = 0; S < numVerts; S++) {
1662                                 CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
1663
1664                                 glBegin(GL_LINE_STRIP);
1665                                 for (x = 0; x < gridSize; x++)
1666                                         glVertex3fv(CCG_elem_offset_co(&key, faceGridData, x));
1667                                 glEnd();
1668                                 for (y = 1; y < gridSize - 1; y++) {
1669                                         glBegin(GL_LINE_STRIP);
1670                                         for (x = 0; x < gridSize; x++)
1671                                                 glVertex3fv(CCG_grid_elem_co(&key, faceGridData, x, y));
1672                                         glEnd();
1673                                 }
1674                                 for (x = 1; x < gridSize - 1; x++) {
1675                                         glBegin(GL_LINE_STRIP);
1676                                         for (y = 0; y < gridSize; y++)
1677                                                 glVertex3fv(CCG_grid_elem_co(&key, faceGridData, x, y));
1678                                         glEnd();
1679                                 }
1680                         }
1681                 }
1682         }
1683 }
1684
1685 static void ccgDM_drawLooseEdges(DerivedMesh *dm)
1686 {
1687         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1688         CCGSubSurf *ss = ccgdm->ss;
1689         CCGKey key;
1690         int totedge = ccgSubSurf_getNumEdges(ss);
1691         int i, j, edgeSize = ccgSubSurf_getEdgeSize(ss);
1692
1693         CCG_key_top_level(&key, ss);
1694
1695         for (j = 0; j < totedge; j++) {
1696                 CCGEdge *e = ccgdm->edgeMap[j].edge;
1697                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
1698
1699                 if (!ccgSubSurf_getEdgeNumFaces(e)) {
1700                         glBegin(GL_LINE_STRIP);
1701                         for (i = 0; i < edgeSize - 1; i++) {
1702                                 glVertex3fv(CCG_elem_offset_co(&key, edgeData, i));
1703                                 glVertex3fv(CCG_elem_offset_co(&key, edgeData, i + 1));
1704                         }
1705                         glEnd();
1706                 }
1707         }
1708 }
1709
1710 static void ccgDM_glNormalFast(float *a, float *b, float *c, float *d)
1711 {
1712         float a_cX = c[0] - a[0], a_cY = c[1] - a[1], a_cZ = c[2] - a[2];
1713         float b_dX = d[0] - b[0], b_dY = d[1] - b[1], b_dZ = d[2] - b[2];
1714         float no[3];
1715
1716         no[0] = b_dY * a_cZ - b_dZ * a_cY;
1717         no[1] = b_dZ * a_cX - b_dX * a_cZ;
1718         no[2] = b_dX * a_cY - b_dY * a_cX;
1719
1720         /* don't normalize, GL_NORMALIZE is enabled */
1721         glNormal3fv(no);
1722 }
1723
1724 /* Only used by non-editmesh types */
1725 static void ccgDM_drawFacesSolid(DerivedMesh *dm, float (*partial_redraw_planes)[4], int fast, DMSetMaterial setMaterial)
1726 {
1727         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1728         CCGSubSurf *ss = ccgdm->ss;
1729         CCGKey key;
1730         int gridSize = ccgSubSurf_getGridSize(ss);
1731         DMFlagMat *faceFlags = ccgdm->faceFlags;
1732         int step = (fast) ? gridSize - 1 : 1;
1733         int i, totface = ccgSubSurf_getNumFaces(ss);
1734         int drawcurrent = 0, matnr = -1, shademodel = -1;
1735
1736         CCG_key_top_level(&key, ss);
1737         ccgdm_pbvh_update(ccgdm);
1738
1739         if (ccgdm->pbvh && ccgdm->multires.mmd && !fast) {
1740                 if (dm->numTessFaceData) {
1741                         BKE_pbvh_draw(ccgdm->pbvh, partial_redraw_planes, NULL,
1742                                       setMaterial, FALSE);
1743                         glShadeModel(GL_FLAT);
1744                 }
1745
1746                 return;
1747         }
1748
1749         for (i = 0; i < totface; i++) {
1750                 CCGFace *f = ccgdm->faceMap[i].face;
1751                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
1752                 int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
1753                 int new_matnr, new_shademodel;
1754
1755                 if (faceFlags) {
1756                         new_shademodel = (faceFlags[index].flag & ME_SMOOTH) ? GL_SMOOTH : GL_FLAT;
1757                         new_matnr = faceFlags[index].mat_nr;
1758                 }
1759                 else {
1760                         new_shademodel = GL_SMOOTH;
1761                         new_matnr = 0;
1762                 }
1763                 
1764                 if (shademodel != new_shademodel || matnr != new_matnr) {
1765                         matnr = new_matnr;
1766                         shademodel = new_shademodel;
1767
1768                         drawcurrent = setMaterial(matnr + 1, NULL);
1769
1770                         glShadeModel(shademodel);
1771                 }
1772
1773                 if (!drawcurrent)
1774                         continue;
1775
1776                 for (S = 0; S < numVerts; S++) {
1777                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
1778
1779                         if (shademodel == GL_SMOOTH) {
1780                                 for (y = 0; y < gridSize - 1; y += step) {
1781                                         glBegin(GL_QUAD_STRIP);
1782                                         for (x = 0; x < gridSize; x += step) {
1783                                                 CCGElem *a = CCG_grid_elem(&key, faceGridData, x, y + 0);
1784                                                 CCGElem *b = CCG_grid_elem(&key, faceGridData, x, y + step);
1785
1786                                                 glNormal3fv(CCG_elem_no(&key, a));
1787                                                 glVertex3fv(CCG_elem_co(&key, a));
1788                                                 glNormal3fv(CCG_elem_no(&key, b));
1789                                                 glVertex3fv(CCG_elem_co(&key, b));
1790                                         }
1791                                         glEnd();
1792                                 }
1793                         }
1794                         else {
1795                                 glBegin(GL_QUADS);
1796                                 for (y = 0; y < gridSize - 1; y += step) {
1797                                         for (x = 0; x < gridSize - 1; x += step) {
1798                                                 float *a = CCG_grid_elem_co(&key, faceGridData, x, y + 0);
1799                                                 float *b = CCG_grid_elem_co(&key, faceGridData, x + step, y + 0);
1800                                                 float *c = CCG_grid_elem_co(&key, faceGridData, x + step, y + step);
1801                                                 float *d = CCG_grid_elem_co(&key, faceGridData, x, y + step);
1802
1803                                                 ccgDM_glNormalFast(a, b, c, d);
1804
1805                                                 glVertex3fv(d);
1806                                                 glVertex3fv(c);
1807                                                 glVertex3fv(b);
1808                                                 glVertex3fv(a);
1809                                         }
1810                                 }
1811                                 glEnd();
1812                         }
1813                 }
1814         }
1815 }
1816
1817 /* Only used by non-editmesh types */
1818 static void ccgDM_drawMappedFacesGLSL(DerivedMesh *dm,
1819                                       DMSetMaterial setMaterial,
1820                                       DMSetDrawOptions setDrawOptions,
1821                                       void *userData)
1822 {
1823         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1824         CCGSubSurf *ss = ccgdm->ss;
1825         CCGKey key;
1826         GPUVertexAttribs gattribs;
1827         DMVertexAttribs attribs = {{{NULL}}};
1828         /* MTFace *tf = dm->getTessFaceDataArray(dm, CD_MTFACE); */ /* UNUSED */
1829         int gridSize = ccgSubSurf_getGridSize(ss);
1830         int gridFaces = gridSize - 1;
1831         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1832         DMFlagMat *faceFlags = ccgdm->faceFlags;
1833         int a, b, i, do_draw, numVerts, matnr, new_matnr, totface;
1834
1835         CCG_key_top_level(&key, ss);
1836         ccgdm_pbvh_update(ccgdm);
1837
1838         do_draw = 0;
1839         matnr = -1;
1840
1841 #define PASSATTRIB(dx, dy, vert) {                                            \
1842         if (attribs.totorco) {                                                    \
1843                 index = getFaceIndex(ss, f, S, x + dx, y + dy, edgeSize, gridSize);   \
1844                 glVertexAttrib3fvARB(attribs.orco.gl_index,                           \
1845                                      attribs.orco.array[index]);                      \
1846         }                                                                         \
1847         for (b = 0; b < attribs.tottface; b++) {                                  \
1848                 MTFace *tf = &attribs.tface[b].array[a];                              \
1849                 glVertexAttrib2fvARB(attribs.tface[b].gl_index, tf->uv[vert]);        \
1850         }                                                                         \
1851         for (b = 0; b < attribs.totmcol; b++) {                                   \
1852                 MCol *cp = &attribs.mcol[b].array[a * 4 + vert];                      \
1853                 GLubyte col[4];                                                       \
1854                 col[0] = cp->b; col[1] = cp->g; col[2] = cp->r; col[3] = cp->a;       \
1855                 glVertexAttrib4ubvARB(attribs.mcol[b].gl_index, col);                 \
1856         }                                                                         \
1857         if (attribs.tottang) {                                                    \
1858                 float *tang = attribs.tang.array[a * 4 + vert];                       \
1859                 glVertexAttrib4fvARB(attribs.tang.gl_index, tang);                    \
1860         }                                                                         \
1861 } (void)0
1862
1863         totface = ccgSubSurf_getNumFaces(ss);
1864         for (a = 0, i = 0; i < totface; i++) {
1865                 CCGFace *f = ccgdm->faceMap[i].face;
1866                 int S, x, y, drawSmooth;
1867                 int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
1868                 int origIndex = ccgDM_getFaceMapIndex(ss, f);
1869                 
1870                 numVerts = ccgSubSurf_getFaceNumVerts(f);
1871
1872                 if (faceFlags) {
1873                         drawSmooth = (faceFlags[index].flag & ME_SMOOTH);
1874                         new_matnr = faceFlags[index].mat_nr + 1;
1875                 }
1876                 else {
1877                         drawSmooth = 1;
1878                         new_matnr = 1;
1879                 }
1880
1881                 if (new_matnr != matnr) {
1882                         do_draw = setMaterial(matnr = new_matnr, &gattribs);
1883                         if (do_draw)
1884                                 DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1885                 }
1886
1887                 if (!do_draw || (setDrawOptions && (origIndex != ORIGINDEX_NONE) &&
1888                                 (setDrawOptions(userData, origIndex) == DM_DRAW_OPTION_SKIP)))
1889                 {
1890                         a += gridFaces * gridFaces * numVerts;
1891                         continue;
1892                 }
1893
1894                 glShadeModel(drawSmooth ? GL_SMOOTH : GL_FLAT);
1895                 for (S = 0; S < numVerts; S++) {
1896                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
1897                         CCGElem *vda, *vdb;
1898
1899                         if (drawSmooth) {
1900                                 for (y = 0; y < gridFaces; y++) {
1901                                         glBegin(GL_QUAD_STRIP);
1902                                         for (x = 0; x < gridFaces; x++) {
1903                                                 vda = CCG_grid_elem(&key, faceGridData, x, y + 0);
1904                                                 vdb = CCG_grid_elem(&key, faceGridData, x, y + 1);
1905                                                 
1906                                                 PASSATTRIB(0, 0, 0);
1907                                                 glNormal3fv(CCG_elem_no(&key, vda));
1908                                                 glVertex3fv(CCG_elem_co(&key, vda));
1909
1910                                                 PASSATTRIB(0, 1, 1);
1911                                                 glNormal3fv(CCG_elem_no(&key, vdb));
1912                                                 glVertex3fv(CCG_elem_co(&key, vdb));
1913
1914                                                 if (x != gridFaces - 1)
1915                                                         a++;
1916                                         }
1917
1918                                         vda = CCG_grid_elem(&key, faceGridData, x, y + 0);
1919                                         vdb = CCG_grid_elem(&key, faceGridData, x, y + 1);
1920
1921                                         PASSATTRIB(0, 0, 3);
1922                                         glNormal3fv(CCG_elem_no(&key, vda));
1923                                         glVertex3fv(CCG_elem_co(&key, vda));
1924
1925                                         PASSATTRIB(0, 1, 2);
1926                                         glNormal3fv(CCG_elem_no(&key, vdb));
1927                                         glVertex3fv(CCG_elem_co(&key, vdb));
1928
1929                                         glEnd();
1930
1931                                         a++;
1932                                 }
1933                         }
1934                         else {
1935                                 glBegin(GL_QUADS);
1936                                 for (y = 0; y < gridFaces; y++) {
1937                                         for (x = 0; x < gridFaces; x++) {
1938                                                 float *aco = CCG_grid_elem_co(&key, faceGridData, x, y);
1939                                                 float *bco = CCG_grid_elem_co(&key, faceGridData, x + 1, y);
1940                                                 float *cco = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
1941                                                 float *dco = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
1942
1943                                                 ccgDM_glNormalFast(aco, bco, cco, dco);
1944
1945                                                 PASSATTRIB(0, 1, 1);
1946                                                 glVertex3fv(dco);
1947                                                 PASSATTRIB(1, 1, 2);
1948                                                 glVertex3fv(cco);
1949                                                 PASSATTRIB(1, 0, 3);
1950                                                 glVertex3fv(bco);
1951                                                 PASSATTRIB(0, 0, 0);
1952                                                 glVertex3fv(aco);
1953                                                 
1954                                                 a++;
1955                                         }
1956                                 }
1957                                 glEnd();
1958                         }
1959                 }
1960         }
1961
1962 #undef PASSATTRIB
1963 }
1964
1965 static void ccgDM_drawFacesGLSL(DerivedMesh *dm, DMSetMaterial setMaterial)
1966 {
1967         dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
1968 }
1969
1970 /* Only used by non-editmesh types */
1971 static void ccgDM_drawMappedFacesMat(DerivedMesh *dm,
1972                                      void (*setMaterial)(void *userData, int, void *attribs),
1973                                      int (*setFace)(void *userData, int index), void *userData)
1974 {
1975         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1976         CCGSubSurf *ss = ccgdm->ss;
1977         CCGKey key;
1978         GPUVertexAttribs gattribs;
1979         DMVertexAttribs attribs = {{{NULL}}};
1980         int gridSize = ccgSubSurf_getGridSize(ss);
1981         int gridFaces = gridSize - 1;
1982         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1983         DMFlagMat *faceFlags = ccgdm->faceFlags;
1984         int a, b, i, numVerts, matnr, new_matnr, totface;
1985
1986         CCG_key_top_level(&key, ss);
1987         ccgdm_pbvh_update(ccgdm);
1988
1989         matnr = -1;
1990
1991 #define PASSATTRIB(dx, dy, vert) {                                            \
1992         if (attribs.totorco) {                                                    \
1993                 index = getFaceIndex(ss, f, S, x + dx, y + dy, edgeSize, gridSize);   \
1994                 if (attribs.orco.gl_texco)                                            \
1995                         glTexCoord3fv(attribs.orco.array[index]);                         \
1996                 else                                                                  \
1997                         glVertexAttrib3fvARB(attribs.orco.gl_index,                       \
1998                                              attribs.orco.array[index]);                  \
1999         }                                                                         \
2000         for (b = 0; b < attribs.tottface; b++) {                                  \
2001                 MTFace *tf = &attribs.tface[b].array[a];                              \
2002                 if (attribs.tface[b].gl_texco)                                        \
2003                         glTexCoord2fv(tf->uv[vert]);                                      \
2004                 else                                                                  \
2005                         glVertexAttrib2fvARB(attribs.tface[b].gl_index, tf->uv[vert]);    \
2006         }                                                                         \
2007         for (b = 0; b < attribs.totmcol; b++) {                                   \
2008                 MCol *cp = &attribs.mcol[b].array[a * 4 + vert];                      \
2009                 GLubyte col[4];                                                       \
2010                 col[0] = cp->b; col[1] = cp->g; col[2] = cp->r; col[3] = cp->a;       \
2011                 glVertexAttrib4ubvARB(attribs.mcol[b].gl_index, col);                 \
2012         }                                                                         \
2013         if (attribs.tottang) {                                                    \
2014                 float *tang = attribs.tang.array[a * 4 + vert];                       \
2015                 glVertexAttrib4fvARB(attribs.tang.gl_index, tang);                    \
2016         }                                                                         \
2017 } (void)0
2018
2019         totface = ccgSubSurf_getNumFaces(ss);
2020         for (a = 0, i = 0; i < totface; i++) {
2021                 CCGFace *f = ccgdm->faceMap[i].face;
2022                 int S, x, y, drawSmooth;
2023                 int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2024                 int origIndex = ccgDM_getFaceMapIndex(ss, f);
2025                 
2026                 numVerts = ccgSubSurf_getFaceNumVerts(f);
2027
2028                 /* get flags */
2029                 if (faceFlags) {
2030                         drawSmooth = (faceFlags[index].flag & ME_SMOOTH);
2031                         new_matnr = faceFlags[index].mat_nr + 1;
2032                 }
2033                 else {
2034                         drawSmooth = 1;
2035                         new_matnr = 1;
2036                 }
2037
2038                 /* material */
2039                 if (new_matnr != matnr) {
2040                         setMaterial(userData, matnr = new_matnr, &gattribs);
2041                         DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
2042                 }
2043
2044                 /* face hiding */
2045                 if ((setFace && (origIndex != ORIGINDEX_NONE) && !setFace(userData, origIndex))) {
2046                         a += gridFaces * gridFaces * numVerts;
2047                         continue;
2048                 }
2049
2050                 /* draw face*/
2051                 glShadeModel(drawSmooth ? GL_SMOOTH : GL_FLAT);
2052                 for (S = 0; S < numVerts; S++) {
2053                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
2054                         CCGElem *vda, *vdb;
2055
2056                         if (drawSmooth) {
2057                                 for (y = 0; y < gridFaces; y++) {
2058                                         glBegin(GL_QUAD_STRIP);
2059                                         for (x = 0; x < gridFaces; x++) {
2060                                                 vda = CCG_grid_elem(&key, faceGridData, x, y);
2061                                                 vdb = CCG_grid_elem(&key, faceGridData, x, y + 1);
2062                                                 
2063                                                 PASSATTRIB(0, 0, 0);
2064                                                 glNormal3fv(CCG_elem_no(&key, vda));
2065                                                 glVertex3fv(CCG_elem_co(&key, vda));
2066
2067                                                 PASSATTRIB(0, 1, 1);
2068                                                 glNormal3fv(CCG_elem_no(&key, vdb));
2069                                                 glVertex3fv(CCG_elem_co(&key, vdb));
2070
2071                                                 if (x != gridFaces - 1)
2072                                                         a++;
2073                                         }
2074
2075                                         vda = CCG_grid_elem(&key, faceGridData, x, y + 0);
2076                                         vdb = CCG_grid_elem(&key, faceGridData, x, y + 1);
2077
2078                                         PASSATTRIB(0, 0, 3);
2079                                         glNormal3fv(CCG_elem_no(&key, vda));
2080                                         glVertex3fv(CCG_elem_co(&key, vda));
2081
2082                                         PASSATTRIB(0, 1, 2);
2083                                         glNormal3fv(CCG_elem_no(&key, vdb));
2084                                         glVertex3fv(CCG_elem_co(&key, vdb));
2085
2086                                         glEnd();
2087
2088                                         a++;
2089                                 }
2090                         }
2091                         else {
2092                                 glBegin(GL_QUADS);
2093                                 for (y = 0; y < gridFaces; y++) {
2094                                         for (x = 0; x < gridFaces; x++) {
2095                                                 float *aco = CCG_grid_elem_co(&key, faceGridData, x, y + 0);
2096                                                 float *bco = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 0);
2097                                                 float *cco = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
2098                                                 float *dco = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
2099
2100                                                 ccgDM_glNormalFast(aco, bco, cco, dco);
2101
2102                                                 PASSATTRIB(0, 1, 1);
2103                                                 glVertex3fv(dco);
2104                                                 PASSATTRIB(1, 1, 2);
2105                                                 glVertex3fv(cco);
2106                                                 PASSATTRIB(1, 0, 3);
2107                                                 glVertex3fv(bco);
2108                                                 PASSATTRIB(0, 0, 0);
2109                                                 glVertex3fv(aco);
2110                                                 
2111                                                 a++;
2112                                         }
2113                                 }
2114                                 glEnd();
2115                         }
2116                 }
2117         }
2118
2119 #undef PASSATTRIB
2120 }
2121
2122 static void ccgDM_drawFacesTex_common(DerivedMesh *dm,
2123                                       DMSetDrawOptionsTex drawParams,
2124                                       DMSetDrawOptions drawParamsMapped,
2125                                       DMCompareDrawOptions compareDrawOptions,
2126                                       void *userData)
2127 {
2128         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2129         CCGSubSurf *ss = ccgdm->ss;
2130         CCGKey key;
2131         MCol *mcol = dm->getTessFaceDataArray(dm, CD_PREVIEW_MCOL);
2132         MTFace *tf = DM_get_tessface_data_layer(dm, CD_MTFACE);
2133         DMFlagMat *faceFlags = ccgdm->faceFlags;
2134         DMDrawOption draw_option;
2135         int i, totface, gridSize = ccgSubSurf_getGridSize(ss);
2136         int gridFaces = gridSize - 1;
2137
2138         (void) compareDrawOptions;
2139
2140         CCG_key_top_level(&key, ss);
2141         ccgdm_pbvh_update(ccgdm);
2142
2143         if (!mcol)
2144                 mcol = dm->getTessFaceDataArray(dm, CD_MCOL);
2145
2146         if (!mcol)
2147                 mcol = dm->getTessFaceDataArray(dm, CD_TEXTURE_MCOL);
2148
2149         totface = ccgSubSurf_getNumFaces(ss);
2150         for (i = 0; i < totface; i++) {
2151                 CCGFace *f = ccgdm->faceMap[i].face;
2152                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2153                 int drawSmooth, index = ccgDM_getFaceMapIndex(ss, f);
2154                 int origIndex = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2155                 unsigned char *cp = NULL;
2156                 int mat_nr;
2157
2158                 if (faceFlags) {
2159                         drawSmooth = (faceFlags[origIndex].flag & ME_SMOOTH);
2160                         mat_nr = faceFlags[origIndex].mat_nr;
2161                 }
2162                 else {
2163                         drawSmooth = 1;
2164                         mat_nr = 0;
2165                 }
2166
2167                 if (drawParams)
2168                         draw_option = drawParams(tf, (mcol != NULL), mat_nr);
2169                 else if (index != ORIGINDEX_NONE)
2170                         draw_option = (drawParamsMapped) ? drawParamsMapped(userData, index) : DM_DRAW_OPTION_NORMAL;
2171                 else
2172                         draw_option = GPU_enable_material(mat_nr, NULL) ? DM_DRAW_OPTION_NORMAL : DM_DRAW_OPTION_SKIP;
2173
2174
2175                 if (draw_option == DM_DRAW_OPTION_SKIP) {
2176                         if (tf) tf += gridFaces * gridFaces * numVerts;
2177                         if (mcol) mcol += gridFaces * gridFaces * numVerts * 4;
2178                         continue;
2179                 }
2180
2181                 /* flag 1 == use vertex colors */
2182                 if (mcol) {
2183                         if (draw_option != DM_DRAW_OPTION_NO_MCOL)
2184                                 cp = (unsigned char *)mcol;
2185                         mcol += gridFaces * gridFaces * numVerts * 4;
2186                 }
2187
2188                 for (S = 0; S < numVerts; S++) {
2189                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
2190                         CCGElem *a, *b;
2191
2192                         if (drawSmooth) {
2193                                 glShadeModel(GL_SMOOTH);
2194                                 for (y = 0; y < gridFaces; y++) {
2195                                         glBegin(GL_QUAD_STRIP);
2196                                         for (x = 0; x < gridFaces; x++) {
2197                                                 a = CCG_grid_elem(&key, faceGridData, x, y + 0);
2198                                                 b = CCG_grid_elem(&key, faceGridData, x, y + 1);
2199
2200                                                 if (tf) glTexCoord2fv(tf->uv[0]);
2201                                                 if (cp) glColor3ub(cp[3], cp[2], cp[1]);
2202                                                 glNormal3fv(CCG_elem_no(&key, a));
2203                                                 glVertex3fv(CCG_elem_co(&key, a));
2204
2205                                                 if (tf) glTexCoord2fv(tf->uv[1]);
2206                                                 if (cp) glColor3ub(cp[7], cp[6], cp[5]);
2207                                                 glNormal3fv(CCG_elem_no(&key, b));
2208                                                 glVertex3fv(CCG_elem_co(&key, b));
2209                                                 
2210                                                 if (x != gridFaces - 1) {
2211                                                         if (tf) tf++;
2212                                                         if (cp) cp += 16;
2213                                                 }
2214                                         }
2215
2216                                         a = CCG_grid_elem(&key, faceGridData, x, y + 0);
2217                                         b = CCG_grid_elem(&key, faceGridData, x, y + 1);
2218
2219                                         if (tf) glTexCoord2fv(tf->uv[3]);
2220                                         if (cp) glColor3ub(cp[15], cp[14], cp[13]);
2221                                         glNormal3fv(CCG_elem_no(&key, a));
2222                                         glVertex3fv(CCG_elem_co(&key, a));
2223
2224                                         if (tf) glTexCoord2fv(tf->uv[2]);
2225                                         if (cp) glColor3ub(cp[11], cp[10], cp[9]);
2226                                         glNormal3fv(CCG_elem_no(&key, b));
2227                                         glVertex3fv(CCG_elem_co(&key, b));
2228
2229                                         if (tf) tf++;
2230                                         if (cp) cp += 16;
2231
2232                                         glEnd();
2233                                 }
2234                         }
2235                         else {
2236                                 glShadeModel((cp) ? GL_SMOOTH : GL_FLAT);
2237                                 glBegin(GL_QUADS);
2238                                 for (y = 0; y < gridFaces; y++) {
2239                                         for (x = 0; x < gridFaces; x++) {
2240                                                 float *a_co = CCG_grid_elem_co(&key, faceGridData, x, y + 0);
2241                                                 float *b_co = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 0);
2242                                                 float *c_co = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
2243                                                 float *d_co = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
2244
2245                                                 ccgDM_glNormalFast(a_co, b_co, c_co, d_co);
2246
2247                                                 if (tf) glTexCoord2fv(tf->uv[1]);
2248                                                 if (cp) glColor3ub(cp[7], cp[6], cp[5]);
2249                                                 glVertex3fv(d_co);
2250
2251                                                 if (tf) glTexCoord2fv(tf->uv[2]);
2252                                                 if (cp) glColor3ub(cp[11], cp[10], cp[9]);
2253                                                 glVertex3fv(c_co);
2254
2255                                                 if (tf) glTexCoord2fv(tf->uv[3]);
2256                                                 if (cp) glColor3ub(cp[15], cp[14], cp[13]);
2257                                                 glVertex3fv(b_co);
2258
2259                                                 if (tf) glTexCoord2fv(tf->uv[0]);
2260                                                 if (cp) glColor3ub(cp[3], cp[2], cp[1]);
2261                                                 glVertex3fv(a_co);
2262
2263                                                 if (tf) tf++;
2264                                                 if (cp) cp += 16;
2265                                         }
2266                                 }
2267                                 glEnd();
2268                         }
2269                 }
2270         }
2271 }
2272
2273 static void ccgDM_drawFacesTex(DerivedMesh *dm,
2274                                DMSetDrawOptionsTex setDrawOptions,
2275                                DMCompareDrawOptions compareDrawOptions,
2276                                void *userData)
2277 {
2278         ccgDM_drawFacesTex_common(dm, setDrawOptions, NULL, compareDrawOptions, userData);
2279 }
2280
2281 static void ccgDM_drawMappedFacesTex(DerivedMesh *dm,
2282                                      DMSetDrawOptions setDrawOptions,
2283                                      DMCompareDrawOptions compareDrawOptions,
2284                                      void *userData)
2285 {
2286         ccgDM_drawFacesTex_common(dm, NULL, setDrawOptions, compareDrawOptions, userData);
2287 }
2288
2289 static void ccgDM_drawUVEdges(DerivedMesh *dm)
2290 {
2291
2292         MFace *mf = dm->getTessFaceArray(dm);
2293         MTFace *tf = DM_get_tessface_data_layer(dm, CD_MTFACE);
2294         int i;
2295         
2296         if (tf) {
2297                 glBegin(GL_LINES);
2298                 for (i = 0; i < dm->numTessFaceData; i++, mf++, tf++) {
2299                         if (!(mf->flag & ME_HIDE)) {
2300                                 glVertex2fv(tf->uv[0]);
2301                                 glVertex2fv(tf->uv[1]);
2302         
2303                                 glVertex2fv(tf->uv[1]);
2304                                 glVertex2fv(tf->uv[2]);
2305         
2306                                 if (!mf->v4) {
2307                                         glVertex2fv(tf->uv[2]);
2308                                         glVertex2fv(tf->uv[0]);
2309                                 }
2310                                 else {
2311                                         glVertex2fv(tf->uv[2]);
2312                                         glVertex2fv(tf->uv[3]);
2313         
2314                                         glVertex2fv(tf->uv[3]);
2315                                         glVertex2fv(tf->uv[0]);
2316                                 }
2317                         }
2318                 }
2319                 glEnd();
2320         }
2321 }
2322
2323 static void ccgDM_drawMappedFaces(DerivedMesh *dm,
2324                                   DMSetDrawOptions setDrawOptions,
2325                                   DMSetMaterial setMaterial,
2326                                   DMCompareDrawOptions compareDrawOptions,
2327                                   void *userData, DMDrawFlag flag)
2328 {
2329         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2330         CCGSubSurf *ss = ccgdm->ss;
2331         CCGKey key;
2332         MCol *mcol = NULL;
2333         int i, gridSize = ccgSubSurf_getGridSize(ss);
2334         DMFlagMat *faceFlags = ccgdm->faceFlags;
2335         int useColors = flag & DM_DRAW_USE_COLORS;
2336         int gridFaces = gridSize - 1, totface;
2337
2338         CCG_key_top_level(&key, ss);
2339
2340         /* currently unused -- each original face is handled separately */
2341         (void)compareDrawOptions;
2342
2343         if (useColors) {
2344                 mcol = dm->getTessFaceDataArray(dm, CD_PREVIEW_MCOL);
2345                 if (!mcol)
2346                         mcol = dm->getTessFaceDataArray(dm, CD_MCOL);
2347         }
2348
2349         totface = ccgSubSurf_getNumFaces(ss);
2350         for (i = 0; i < totface; i++) {
2351                 CCGFace *f = ccgdm->faceMap[i].face;
2352                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2353                 int drawSmooth, index = ccgDM_getFaceMapIndex(ss, f);
2354                 int origIndex;
2355                 unsigned char *cp = NULL;
2356
2357                 origIndex = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2358
2359                 if (flag & DM_DRAW_ALWAYS_SMOOTH) drawSmooth = 1;
2360                 else if (faceFlags) drawSmooth = (faceFlags[origIndex].flag & ME_SMOOTH);
2361                 else drawSmooth = 1;
2362
2363                 if (mcol) {
2364                         cp = (unsigned char *)mcol;
2365                         mcol += gridFaces * gridFaces * numVerts * 4;
2366                 }
2367
2368                 {
2369                         DMDrawOption draw_option = DM_DRAW_OPTION_NORMAL;
2370
2371                         if (index == ORIGINDEX_NONE)
2372                                 draw_option = setMaterial(faceFlags ? faceFlags[origIndex].mat_nr + 1 : 1, NULL);  /* XXX, no faceFlags no material */
2373                         else if (setDrawOptions)
2374                                 draw_option = setDrawOptions(userData, index);
2375
2376                         if (draw_option != DM_DRAW_OPTION_SKIP) {
2377                                 if (draw_option == DM_DRAW_OPTION_STIPPLE) {
2378                                         glEnable(GL_POLYGON_STIPPLE);
2379                                         glPolygonStipple(stipple_quarttone);
2380                                 }
2381
2382                                 /* no need to set shading mode to flat because
2383                                  *  normals are already used to change shading */
2384                                 glShadeModel(GL_SMOOTH);
2385                                 
2386                                 for (S = 0; S < numVerts; S++) {
2387                                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
2388                                         if (drawSmooth) {
2389                                                 for (y = 0; y < gridFaces; y++) {
2390                                                         CCGElem *a, *b;
2391                                                         glBegin(GL_QUAD_STRIP);
2392                                                         for (x = 0; x < gridFaces; x++) {
2393                                                                 a = CCG_grid_elem(&key, faceGridData, x, y + 0);
2394                                                                 b = CCG_grid_elem(&key, faceGridData, x, y + 1);
2395         
2396                                                                 if (cp) glColor3ub(cp[3], cp[2], cp[1]);
2397                                                                 glNormal3fv(CCG_elem_no(&key, a));
2398                                                                 glVertex3fv(CCG_elem_co(&key, a));
2399                                                                 if (cp) glColor3ub(cp[7], cp[6], cp[5]);
2400                                                                 glNormal3fv(CCG_elem_no(&key, b));
2401                                                                 glVertex3fv(CCG_elem_co(&key, b));
2402
2403                                                                 if (x != gridFaces - 1) {
2404                                                                         if (cp) cp += 16;
2405                                                                 }
2406                                                         }
2407
2408                                                         a = CCG_grid_elem(&key, faceGridData, x, y + 0);
2409                                                         b = CCG_grid_elem(&key, faceGridData, x, y + 1);
2410
2411                                                         if (cp) glColor3ub(cp[15], cp[14], cp[13]);
2412                                                         glNormal3fv(CCG_elem_no(&key, a));
2413                                                         glVertex3fv(CCG_elem_co(&key, a));
2414                                                         if (cp) glColor3ub(cp[11], cp[10], cp[9]);
2415                                                         glNormal3fv(CCG_elem_no(&key, b));
2416                                                         glVertex3fv(CCG_elem_co(&key, b));
2417
2418                                                         if (cp) cp += 16;
2419
2420                                                         glEnd();
2421                                                 }
2422                                         }
2423                                         else {
2424                                                 glBegin(GL_QUADS);
2425                                                 for (y = 0; y < gridFaces; y++) {
2426                                                         for (x = 0; x < gridFaces; x++) {
2427                                                                 float *a = CCG_grid_elem_co(&key, faceGridData, x, y + 0);
2428                                                                 float *b = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 0);
2429                                                                 float *c = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
2430                                                                 float *d = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
2431
2432                                                                 ccgDM_glNormalFast(a, b, c, d);
2433         
2434                                                                 if (cp) glColor3ub(cp[7], cp[6], cp[5]);
2435                                                                 glVertex3fv(d);
2436                                                                 if (cp) glColor3ub(cp[11], cp[10], cp[9]);
2437                                                                 glVertex3fv(c);
2438                                                                 if (cp) glColor3ub(cp[15], cp[14], cp[13]);
2439                                                                 glVertex3fv(b);
2440                                                                 if (cp) glColor3ub(cp[3], cp[2], cp[1]);
2441                                                                 glVertex3fv(a);
2442
2443                                                                 if (cp) cp += 16;
2444                                                         }
2445                                                 }
2446                                                 glEnd();
2447                                         }
2448                                 }
2449                                 if (draw_option == DM_DRAW_OPTION_STIPPLE)
2450                                         glDisable(GL_POLYGON_STIPPLE);
2451                         }
2452                 }
2453         }
2454 }
2455
2456 static void ccgDM_drawMappedEdges(DerivedMesh *dm,
2457                                   DMSetDrawOptions setDrawOptions,
2458                                   void *userData)
2459 {
2460         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2461         CCGSubSurf *ss = ccgdm->ss;
2462         CCGEdgeIterator *ei;
2463         CCGKey key;
2464         int i, useAging, edgeSize = ccgSubSurf_getEdgeSize(ss);
2465
2466         CCG_key_top_level(&key, ss);
2467         ccgSubSurf_getUseAgeCounts(ss, &useAging, NULL, NULL, NULL);
2468
2469         for (ei = ccgSubSurf_getEdgeIterator(ss); !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
2470                 CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
2471                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
2472                 int index = ccgDM_getEdgeMapIndex(ss, e);
2473
2474                 glBegin(GL_LINE_STRIP);
2475                 if (index != -1 && (!setDrawOptions || (setDrawOptions(userData, index) != DM_DRAW_OPTION_SKIP))) {
2476                         if (useAging && !(G.f & G_BACKBUFSEL)) {
2477                                 int ageCol = 255 - ccgSubSurf_getEdgeAge(ss, e) * 4;
2478                                 glColor3ub(0, ageCol > 0 ? ageCol : 0, 0);
2479                         }
2480
2481                         for (i = 0; i < edgeSize - 1; i++) {
2482                                 glVertex3fv(CCG_elem_offset_co(&key, edgeData, i));
2483                                 glVertex3fv(CCG_elem_offset_co(&key, edgeData, i + 1));
2484                         }
2485                 }
2486                 glEnd();
2487         }
2488
2489         ccgEdgeIterator_free(ei);
2490 }
2491
2492 static void ccgDM_drawMappedEdgesInterp(DerivedMesh *dm,
2493                                         DMSetDrawOptions setDrawOptions,
2494                                         DMSetDrawInterpOptions setDrawInterpOptions,
2495                                         void *userData)
2496 {
2497         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2498         CCGSubSurf *ss = ccgdm->ss;
2499         CCGKey key;
2500         CCGEdgeIterator *ei;
2501         int i, useAging, edgeSize = ccgSubSurf_getEdgeSize(ss);
2502
2503         CCG_key_top_level(&key, ss);
2504         ccgSubSurf_getUseAgeCounts(ss, &useAging, NULL, NULL, NULL);
2505
2506         for (ei = ccgSubSurf_getEdgeIterator(ss); !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
2507                 CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
2508                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
2509                 int index = ccgDM_getEdgeMapIndex(ss, e);
2510
2511                 glBegin(GL_LINE_STRIP);
2512                 if (index != -1 && (!setDrawOptions || (setDrawOptions(userData, index) != DM_DRAW_OPTION_SKIP))) {
2513                         for (i = 0; i < edgeSize; i++) {
2514                                 setDrawInterpOptions(userData, index, (float) i / (edgeSize - 1));
2515
2516                                 if (useAging && !(G.f & G_BACKBUFSEL)) {
2517                                         int ageCol = 255 - ccgSubSurf_getEdgeAge(ss, e) * 4;
2518                                         glColor3ub(0, ageCol > 0 ? ageCol : 0, 0);
2519                                 }
2520
2521                                 glVertex3fv(CCG_elem_offset_co(&key, edgeData, i));
2522                         }
2523                 }
2524                 glEnd();
2525         }
2526
2527         ccgEdgeIterator_free(ei);
2528 }
2529
2530 static void ccgDM_foreachMappedFaceCenter(
2531         DerivedMesh *dm,
2532         void (*func)(void *userData, int index, const float co[3], const float no[3]),
2533         void *userData)
2534 {
2535         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2536         CCGSubSurf *ss = ccgdm->ss;
2537         CCGKey key;
2538         CCGFaceIterator *fi;
2539
2540         CCG_key_top_level(&key, ss);
2541
2542         for (fi = ccgSubSurf_getFaceIterator(ss); !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
2543                 CCGFace *f = ccgFaceIterator_getCurrent(fi);
2544                 int index = ccgDM_getFaceMapIndex(ss, f);
2545
2546                 if (index != -1) {
2547                         /* Face center data normal isn't updated atm. */
2548                         CCGElem *vd = ccgSubSurf_getFaceGridData(ss, f, 0, 0, 0);
2549
2550                         func(userData, index, CCG_elem_co(&key, vd), CCG_elem_no(&key, vd));
2551                 }
2552         }
2553
2554         ccgFaceIterator_free(fi);
2555 }
2556
2557 static void ccgDM_release(DerivedMesh *dm)
2558 {
2559         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2560
2561         if (DM_release(dm)) {
2562                 /* Before freeing, need to update the displacement map */
2563                 if (ccgdm->multires.modified_flags) {
2564                         /* Check that mmd still exists */
2565                         if (!ccgdm->multires.local_mmd &&
2566                             BLI_findindex(&ccgdm->multires.ob->modifiers, ccgdm->multires.mmd) < 0)
2567                         {
2568                                 ccgdm->multires.mmd = NULL;
2569                         }
2570                         
2571                         if (ccgdm->multires.mmd) {
2572                                 if (ccgdm->multires.modified_flags & MULTIRES_COORDS_MODIFIED)
2573                                         multires_modifier_update_mdisps(dm);
2574                                 if (ccgdm->multires.modified_flags & MULTIRES_HIDDEN_MODIFIED)
2575                                         multires_modifier_update_hidden(dm);
2576                         }
2577                 }
2578
2579                 if (ccgdm->ehash)
2580                         BLI_edgehash_free(ccgdm->ehash, NULL);
2581
2582                 if (ccgdm->reverseFaceMap) MEM_freeN(ccgdm->reverseFaceMap);
2583                 if (ccgdm->gridFaces) MEM_freeN(ccgdm->gridFaces);
2584                 if (ccgdm->gridData) MEM_freeN(ccgdm->gridData);
2585                 if (ccgdm->gridAdjacency) MEM_freeN(ccgdm->gridAdjacency);
2586                 if (ccgdm->gridOffset) MEM_freeN(ccgdm->gridOffset);
2587                 if (ccgdm->gridFlagMats) MEM_freeN(ccgdm->gridFlagMats);
2588                 if (ccgdm->gridHidden) {
2589                         int i, numGrids = dm->getNumGrids(dm);
2590                         for (i = 0; i < numGrids; i++) {
2591                                 if (ccgdm->gridHidden[i])
2592                                         MEM_freeN(ccgdm->gridHidden[i]);
2593                         }
2594                         MEM_freeN(ccgdm->gridHidden);
2595                 }
2596                 if (ccgdm->freeSS) ccgSubSurf_free(ccgdm->ss);
2597                 if (ccgdm->pmap) MEM_freeN(ccgdm->pmap);
2598                 if (ccgdm->pmap_mem) MEM_freeN(ccgdm->pmap_mem);
2599                 MEM_freeN(ccgdm->edgeFlags);
2600                 MEM_freeN(ccgdm->faceFlags);
2601                 MEM_freeN(ccgdm->vertMap);
2602                 MEM_freeN(ccgdm->edgeMap);
2603                 MEM_freeN(ccgdm->faceMap);
2604                 MEM_freeN(ccgdm);
2605         }
2606 }
2607
2608 static void ccg_loops_to_corners(CustomData *fdata, CustomData *ldata, 
2609                                  CustomData *pdata, int loopstart, int findex,  int polyindex,
2610                                  const int numTex, const int numCol, const int hasPCol, const int hasOrigSpace)
2611 {
2612         MTFace *texface;
2613         MTexPoly *texpoly;
2614         MCol *mcol;
2615         MLoopCol *mloopcol;
2616         MLoopUV *mloopuv;
2617         int i, j;
2618
2619         for (i = 0; i < numTex; i++) {
2620                 texface = CustomData_get_n(fdata, CD_MTFACE, findex, i);
2621                 texpoly = CustomData_get_n(pdata, CD_MTEXPOLY, polyindex, i);
2622                 
2623                 ME_MTEXFACE_CPY(texface, texpoly);
2624
2625                 mloopuv = CustomData_get_n(ldata, CD_MLOOPUV, loopstart, i);
2626                 for (j = 0; j < 4; j++, mloopuv++) {
2627                         copy_v2_v2(texface->uv[j], mloopuv->uv);
2628                 }
2629         }
2630
2631         for (i = 0; i < numCol; i++) {
2632                 mloopcol = CustomData_get_n(ldata, CD_MLOOPCOL, loopstart, i);
2633                 mcol = CustomData_get_n(fdata, CD_MCOL, findex, i);
2634
2635                 for (j = 0; j < 4; j++, mloopcol++) {
2636                         MESH_MLOOPCOL_TO_MCOL(mloopcol, &mcol[j]);
2637                 }
2638         }
2639         
2640         if (hasPCol) {
2641                 mloopcol = CustomData_get(ldata, loopstart, CD_PREVIEW_MLOOPCOL);
2642                 mcol = CustomData_get(fdata, findex, CD_PREVIEW_MCOL);
2643
2644                 for (j = 0; j < 4; j++, mloopcol++) {
2645                         MESH_MLOOPCOL_TO_MCOL(mloopcol, &mcol[j]);
2646                 }
2647         }
2648
2649         if (hasOrigSpace) {
2650                 OrigSpaceFace *of = CustomData_get(fdata, findex, CD_ORIGSPACE);
2651                 OrigSpaceLoop *lof;
2652
2653                 lof = CustomData_get(ldata, loopstart, CD_ORIGSPACE_MLOOP);
2654                 for (j = 0; j < 4; j++, lof++) {
2655                         copy_v2_v2(of->uv[j], lof->uv);
2656                 }
2657         }
2658 }
2659
2660 static void *ccgDM_get_vert_data_layer(DerivedMesh *dm, int type)
2661 {
2662         if (type == CD_ORIGINDEX) {
2663                 /* create origindex on demand to save memory */
2664                 CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2665                 CCGSubSurf *ss = ccgdm->ss;
2666                 int *origindex;
2667                 int a, index, totnone, totorig;
2668
2669                 /* Avoid re-creation if the layer exists already */
2670                 origindex = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
2671                 if (origindex) {
2672                         return origindex;
2673                 }
2674
2675                 DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2676                 origindex = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
2677
2678                 totorig = ccgSubSurf_getNumVerts(ss);
2679                 totnone = dm->numVertData - totorig;
2680
2681                 /* original vertices are at the end */
2682                 for (a = 0; a < totnone; a++)
2683                         origindex[a] = ORIGINDEX_NONE;
2684
2685                 for (index = 0; index < totorig; index++, a++) {
2686                         CCGVert *v = ccgdm->vertMap[index].vert;
2687                         origindex[a] = ccgDM_getVertMapIndex(ccgdm->ss, v);
2688                 }
2689
2690                 return origindex;
2691         }
2692
2693         return DM_get_vert_data_layer(dm, type);
2694 }
2695
2696 static void *ccgDM_get_edge_data_layer(DerivedMesh *dm, int type)
2697 {
2698         if (type == CD_ORIGINDEX) {
2699                 /* create origindex on demand to save memory */
2700                 CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2701                 CCGSubSurf *ss = ccgdm->ss;
2702                 int *origindex;
2703                 int a, i, index, totnone, totorig, totedge;
2704                 int edgeSize = ccgSubSurf_getEdgeSize(ss);
2705
2706                 /* Avoid re-creation if the layer exists already */
2707                 origindex = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
2708                 if (origindex) {
2709                         return origindex;
2710                 }
2711
2712                 DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2713                 origindex = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
2714
2715                 totedge = ccgSubSurf_getNumEdges(ss);
2716                 totorig = totedge * (edgeSize - 1);
2717                 totnone = dm->numEdgeData - totorig;
2718
2719                 /* original edges are at the end */
2720                 for (a = 0; a < totnone; a++)
2721                         origindex[a] = ORIGINDEX_NONE;
2722
2723                 for (index = 0; index < totedge; index++) {
2724                         CCGEdge *e = ccgdm->edgeMap[index].edge;
2725                         int mapIndex = ccgDM_getEdgeMapIndex(ss, e);
2726
2727                         for (i = 0; i < edgeSize - 1; i++, a++)
2728                                 origindex[a] = mapIndex;
2729                 }
2730
2731                 return origindex;
2732         }
2733
2734         return DM_get_edge_data_layer(dm, type);
2735 }
2736
2737 static void *ccgDM_get_tessface_data_layer(DerivedMesh *dm, int type)
2738 {
2739         if (type == CD_ORIGINDEX) {
2740                 /* create origindex on demand to save memory */
2741                 int *origindex;
2742
2743                 /* Avoid re-creation if the layer exists already */
2744                 origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
2745                 if (origindex) {
2746                         return origindex;
2747                 }
2748
2749                 DM_add_tessface_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2750                 origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
2751
2752                 /* silly loop counting up */
2753                 range_vn_i(origindex, dm->getNumTessFaces(dm), 0);
2754
2755                 return origindex;
2756         }
2757
2758         return DM_get_tessface_data_layer(dm, type);
2759 }
2760
2761 static void *ccgDM_get_poly_data_layer(DerivedMesh *dm, int type)
2762 {
2763         if (type == CD_ORIGINDEX) {
2764                 /* create origindex on demand to save memory */
2765                 CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2766                 CCGSubSurf *ss = ccgdm->ss;
2767                 int *origindex;
2768                 int a, i, index, totface;
2769                 int gridFaces = ccgSubSurf_getGridSize(ss) - 1;
2770
2771                 /* Avoid re-creation if the layer exists already */
2772                 origindex = DM_get_poly_data_layer(dm, CD_ORIGINDEX);
2773                 if (origindex) {
2774                         return origindex;
2775                 }
2776
2777                 DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2778                 origindex = DM_get_poly_data_layer(dm, CD_ORIGINDEX);
2779
2780                 totface = ccgSubSurf_getNumFaces(ss);
2781
2782                 for (a = 0, index = 0; index < totface; index++) {
2783                         CCGFace *f = ccgdm->faceMap[index].face;
2784                         int numVerts = ccgSubSurf_getFaceNumVerts(f);
2785                         int mapIndex = ccgDM_getFaceMapIndex(ss, f);
2786
2787                         for (i = 0; i < gridFaces * gridFaces * numVerts; i++, a++)
2788                                 origindex[a] = mapIndex;
2789                 }
2790
2791                 return origindex;
2792         }
2793
2794         return DM_get_poly_data_layer(dm, type);
2795 }
2796
2797 static void *ccgDM_get_vert_data(DerivedMesh *dm, int index, int type)
2798 {
2799         if (type == CD_ORIGINDEX) {
2800                 /* ensure creation of CD_ORIGINDEX layer */
2801                 ccgDM_get_vert_data_layer(dm, type);
2802         }
2803
2804         return DM_get_vert_data(dm, index, type);
2805 }
2806
2807 static void *ccgDM_get_edge_data(DerivedMesh *dm, int index, int type)
2808 {
2809         if (type == CD_ORIGINDEX) {
2810                 /* ensure creation of CD_ORIGINDEX layer */
2811                 ccgDM_get_edge_data_layer(dm, type);
2812         }
2813
2814         return DM_get_edge_data(dm, index, type);
2815 }
2816
2817 static void *ccgDM_get_tessface_data(DerivedMesh *dm, int index, int type)
2818 {
2819         if (type == CD_ORIGINDEX) {
2820                 /* ensure creation of CD_ORIGINDEX layer */
2821                 ccgDM_get_tessface_data_layer(dm, type);
2822         }
2823
2824         return DM_get_tessface_data(dm, index, type);
2825 }
2826
2827 static void *ccgDM_get_poly_data(DerivedMesh *dm, int index, int type)
2828 {
2829         if (type == CD_ORIGINDEX) {
2830                 /* ensure creation of CD_ORIGINDEX layer */
2831                 ccgDM_get_tessface_data_layer(dm, type);
2832         }
2833
2834         return DM_get_poly_data(dm, index, type);
2835 }
2836
2837 static int ccgDM_getNumGrids(DerivedMesh *dm)
2838 {
2839         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2840         int index, numFaces, numGrids;
2841
2842         numFaces = ccgSubSurf_getNumFaces(ccgdm->ss);
2843         numGrids = 0;
2844
2845         for (index = 0; index < numFaces; index++) {
2846                 CCGFace *f = ccgdm->faceMap[index].face;
2847                 numGrids += ccgSubSurf_getFaceNumVerts(f);
2848         }
2849
2850         return numGrids;
2851 }
2852
2853 static int ccgDM_getGridSize(DerivedMesh *dm)
2854 {
2855         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2856         return ccgSubSurf_getGridSize(ccgdm->ss);
2857 }
2858
2859 static int ccgdm_adjacent_grid(int *gridOffset, CCGFace *f, int S, int offset)
2860 {
2861         CCGFace *adjf;
2862         CCGEdge *e;
2863         int i, j = 0, numFaces, fIndex, numEdges = 0;
2864
2865         e = ccgSubSurf_getFaceEdge(f, S);
2866         numFaces = ccgSubSurf_getEdgeNumFaces(e);
2867
2868         if (numFaces != 2)
2869                 return -1;
2870
2871         for (i = 0; i < numFaces; i++) {
2872                 adjf = ccgSubSurf_getEdgeFace(e, i);
2873
2874                 if (adjf != f) {
2875                         numEdges = ccgSubSurf_getFaceNumVerts(adjf);
2876                         for (j = 0; j < numEdges; j++)
2877                                 if (ccgSubSurf_getFaceEdge(adjf, j) == e)
2878                                         break;
2879
2880                         if (j != numEdges)
2881                                 break;
2882                 }
2883         }
2884
2885         if (numEdges == 0)
2886                 return -1;
2887         
2888         fIndex = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(adjf));
2889
2890         return gridOffset[fIndex] + (j + offset) % numEdges;
2891 }
2892
2893 static void ccgdm_create_grids(DerivedMesh *dm)
2894 {
2895         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2896         CCGSubSurf *ss = ccgdm->ss;
2897         CCGElem **gridData;
2898         DMGridAdjacency *gridAdjacency, *adj;
2899         DMFlagMat *gridFlagMats;
2900         CCGFace **gridFaces;
2901         int *gridOffset;
2902         int index, numFaces, numGrids, S, gIndex /*, gridSize*/;
2903
2904         if (ccgdm->gridData)
2905                 return;
2906         
2907         numGrids = ccgDM_getNumGrids(dm);
2908         numFaces = ccgSubSurf_getNumFaces(ss);
2909         /*gridSize = ccgDM_getGridSize(dm);*/  /*UNUSED*/
2910
2911         /* compute offset into grid array for each face */
2912         gridOffset = MEM_mallocN(sizeof(int) * numFaces, "ccgdm.gridOffset");
2913
2914         for (gIndex = 0, index = 0; index < numFaces; index++) {
2915                 CCGFace *f = ccgdm->faceMap[index].face;
2916                 int numVerts = ccgSubSurf_getFaceNumVerts(f);
2917
2918                 gridOffset[index] = gIndex;
2919                 gIndex += numVerts;
2920         }
2921
2922         /* compute grid data */
2923         gridData = MEM_mallocN(sizeof(CCGElem *) * numGrids, "ccgdm.gridData");
2924         gridAdjacency = MEM_mallocN(sizeof(DMGridAdjacency) * numGrids, "ccgdm.gridAdjacency");
2925         gridFaces = MEM_mallocN(sizeof(CCGFace *) * numGrids, "ccgdm.gridFaces");
2926         gridFlagMats = MEM_mallocN(sizeof(DMFlagMat) * numGrids, "ccgdm.gridFlagMats");
2927
2928         ccgdm->gridHidden = MEM_callocN(sizeof(BLI_bitmap) * numGrids, "ccgdm.gridHidden");
2929
2930         for (gIndex = 0, index = 0; index < numFaces; index++) {
2931                 CCGFace *f = ccgdm->faceMap[index].face;
2932                 int numVerts = ccgSubSurf_getFaceNumVerts(f);
2933
2934                 for (S = 0; S < numVerts; S++, gIndex++) {
2935                         int prevS = (S - 1 + numVerts) % numVerts;
2936                         int nextS = (S + 1 + numVerts) % numVerts;
2937
2938                         gridData[gIndex] = ccgSubSurf_getFaceGridDataArray(ss, f, S);
2939                         gridFaces[gIndex] = f;
2940                         gridFlagMats[gIndex] = ccgdm->faceFlags[index];
2941
2942                         adj = &gridAdjacency[gIndex];
2943
2944                         adj->index[0] = gIndex - S + nextS;