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