Fix for a crash when freeing copied scenes.
[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 #ifdef WITH_FREESTYLE
968                         flags |= (*edgeFlag & (ME_SEAM | ME_SHARP | ME_FREESTYLE_EDGE)) | ME_EDGEDRAW | ME_EDGERENDER;
969 #else
970                         flags |= (*edgeFlag & (ME_SEAM | ME_SHARP)) | ME_EDGEDRAW | ME_EDGERENDER;
971 #endif
972                 else
973                         flags |= ME_EDGEDRAW | ME_EDGERENDER;
974
975                 med->flag = flags;
976         }
977 }
978
979 static void ccgDM_getFinalFace(DerivedMesh *dm, int faceNum, MFace *mf)
980 {
981         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
982         CCGSubSurf *ss = ccgdm->ss;
983         int gridSize = ccgSubSurf_getGridSize(ss);
984         int edgeSize = ccgSubSurf_getEdgeSize(ss);
985         int gridSideEdges = gridSize - 1;
986         int gridFaces = gridSideEdges * gridSideEdges;
987         int i;
988         CCGFace *f;
989         /*int numVerts;*/
990         int offset;
991         int grid;
992         int x, y;
993         /*int lastface = ccgSubSurf_getNumFaces(ss) - 1;*/ /*UNUSED*/
994         DMFlagMat *faceFlags = ccgdm->faceFlags;
995
996         memset(mf, 0, sizeof(*mf));
997         if (faceNum >= ccgdm->dm.numTessFaceData)
998                 return;
999
1000         i = ccgdm->reverseFaceMap[faceNum];
1001
1002         f = ccgdm->faceMap[i].face;
1003         /*numVerts = ccgSubSurf_getFaceNumVerts(f);*/ /*UNUSED*/
1004
1005         offset = faceNum - ccgdm->faceMap[i].startFace;
1006         grid = offset / gridFaces;
1007         offset %= gridFaces;
1008         y = offset / gridSideEdges;
1009         x = offset % gridSideEdges;
1010
1011         mf->v1 = getFaceIndex(ss, f, grid, x + 0, y + 0, edgeSize, gridSize);
1012         mf->v2 = getFaceIndex(ss, f, grid, x + 0, y + 1, edgeSize, gridSize);
1013         mf->v3 = getFaceIndex(ss, f, grid, x + 1, y + 1, edgeSize, gridSize);
1014         mf->v4 = getFaceIndex(ss, f, grid, x + 1, y + 0, edgeSize, gridSize);
1015
1016         if (faceFlags) {
1017                 mf->flag = faceFlags[i].flag;
1018                 mf->mat_nr = faceFlags[i].mat_nr;
1019         }
1020         else {
1021                 mf->flag = ME_SMOOTH;
1022 }
1023
1024         mf->edcode = 0;
1025 }
1026
1027 /* Translate GridHidden into the ME_HIDE flag for MVerts. Assumes
1028  * vertices are in the order output by ccgDM_copyFinalVertArray. */
1029 void subsurf_copy_grid_hidden(DerivedMesh *dm, const MPoly *mpoly,
1030                               MVert *mvert, const MDisps *mdisps)
1031 {
1032         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
1033         CCGSubSurf *ss = ccgdm->ss;
1034         int level = ccgSubSurf_getSubdivisionLevels(ss);
1035         int gridSize = ccgSubSurf_getGridSize(ss);
1036         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1037         int totface = ccgSubSurf_getNumFaces(ss);
1038         int i, j, x, y;
1039         
1040         for (i = 0; i < totface; i++) {
1041                 CCGFace *f = ccgdm->faceMap[i].face;
1042
1043                 for (j = 0; j < mpoly[i].totloop; j++) {
1044                         const MDisps *md = &mdisps[mpoly[i].loopstart + j];
1045                         int hidden_gridsize = ccg_gridsize(md->level);
1046                         int factor = ccg_factor(level, md->level);
1047                         
1048                         if (!md->hidden)
1049                                 continue;
1050                         
1051                         for (y = 0; y < gridSize; y++) {
1052                                 for (x = 0; x < gridSize; x++) {
1053                                         int vndx, offset;
1054                                         
1055                                         vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize);
1056                                         offset = (y * factor) * hidden_gridsize + (x * factor);
1057                                         if (BLI_BITMAP_GET(md->hidden, offset))
1058                                                 mvert[vndx].flag |= ME_HIDE;
1059                                 }
1060                         }
1061                 }
1062         }
1063 }
1064
1065 /* Translate GridPaintMask into vertex paint masks. Assumes vertices
1066  * are in the order output by ccgDM_copyFinalVertArray. */
1067 void subsurf_copy_grid_paint_mask(DerivedMesh *dm, const MPoly *mpoly,
1068                                   float *paint_mask,
1069                                   const GridPaintMask *grid_paint_mask)
1070 {
1071         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
1072         CCGSubSurf *ss = ccgdm->ss;
1073         int level = ccgSubSurf_getSubdivisionLevels(ss);
1074         int gridSize = ccgSubSurf_getGridSize(ss);
1075         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1076         int totface = ccgSubSurf_getNumFaces(ss);
1077         int i, j, x, y, factor, gpm_gridsize;
1078         
1079         for (i = 0; i < totface; i++) {
1080                 CCGFace *f = ccgdm->faceMap[i].face;
1081                 const MPoly *p = &mpoly[i];
1082                 
1083                 for (j = 0; j < p->totloop; j++) {
1084                         const GridPaintMask *gpm = &grid_paint_mask[p->loopstart + j];
1085                         if (!gpm->data)
1086                                 continue;
1087
1088                         factor = ccg_factor(level, gpm->level);
1089                         gpm_gridsize = ccg_gridsize(gpm->level);
1090                         
1091                         for (y = 0; y < gridSize; y++) {
1092                                 for (x = 0; x < gridSize; x++) {
1093                                         int vndx, offset;
1094                                         
1095                                         vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize);
1096                                         offset = y * factor * gpm_gridsize + x * factor;
1097                                         paint_mask[vndx] = gpm->data[offset];
1098                                 }
1099                         }
1100                 }
1101         }
1102 }
1103
1104 /* utility functon */
1105 BLI_INLINE void ccgDM_to_MVert(MVert *mv, const CCGKey *key, CCGElem *elem)
1106 {
1107         copy_v3_v3(mv->co, CCG_elem_co(key, elem));
1108         normal_float_to_short_v3(mv->no, CCG_elem_no(key, elem));
1109         mv->flag = mv->bweight = 0;
1110 }
1111
1112 static void ccgDM_copyFinalVertArray(DerivedMesh *dm, MVert *mvert)
1113 {
1114         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1115         CCGSubSurf *ss = ccgdm->ss;
1116         CCGElem *vd;
1117         CCGKey key;
1118         int index;
1119         int totvert, totedge, totface;
1120         int gridSize = ccgSubSurf_getGridSize(ss);
1121         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1122         unsigned int i = 0;
1123
1124         CCG_key_top_level(&key, ss);
1125
1126         totface = ccgSubSurf_getNumFaces(ss);
1127         for (index = 0; index < totface; index++) {
1128                 CCGFace *f = ccgdm->faceMap[index].face;
1129                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1130
1131                 vd = ccgSubSurf_getFaceCenterData(f);
1132                 ccgDM_to_MVert(&mvert[i++], &key, vd);
1133                 
1134                 for (S = 0; S < numVerts; S++) {
1135                         for (x = 1; x < gridSize - 1; x++) {
1136                                 vd = ccgSubSurf_getFaceGridEdgeData(ss, f, S, x);
1137                                 ccgDM_to_MVert(&mvert[i++], &key, vd);
1138                         }
1139                 }
1140
1141                 for (S = 0; S < numVerts; S++) {
1142                         for (y = 1; y < gridSize - 1; y++) {
1143                                 for (x = 1; x < gridSize - 1; x++) {
1144                                         vd = ccgSubSurf_getFaceGridData(ss, f, S, x, y);
1145                                         ccgDM_to_MVert(&mvert[i++], &key, vd);
1146                                 }
1147                         }
1148                 }
1149         }
1150
1151         totedge = ccgSubSurf_getNumEdges(ss);
1152         for (index = 0; index < totedge; index++) {
1153                 CCGEdge *e = ccgdm->edgeMap[index].edge;
1154                 int x;
1155
1156                 for (x = 1; x < edgeSize - 1; x++) {
1157                         /* This gives errors with -debug-fpe
1158                          * the normals don't seem to be unit length.
1159                          * this is most likely caused by edges with no
1160                          * faces which are now zerod out, see comment in:
1161                          * ccgSubSurf__calcVertNormals(), - campbell */
1162                         vd = ccgSubSurf_getEdgeData(ss, e, x);
1163                         ccgDM_to_MVert(&mvert[i++], &key, vd);
1164                 }
1165         }
1166
1167         totvert = ccgSubSurf_getNumVerts(ss);
1168         for (index = 0; index < totvert; index++) {
1169                 CCGVert *v = ccgdm->vertMap[index].vert;
1170
1171                 vd = ccgSubSurf_getVertData(ss, v);
1172                 ccgDM_to_MVert(&mvert[i++], &key, vd);
1173         }
1174 }
1175
1176
1177 /* utility functon */
1178 BLI_INLINE void ccgDM_to_MEdge(MEdge *med, const int v1, const int v2, const short flag)
1179 {
1180         med->v1 = v1;
1181         med->v2 = v2;
1182         med->crease = med->bweight = 0;
1183         med->flag = flag;
1184 }
1185
1186 static void ccgDM_copyFinalEdgeArray(DerivedMesh *dm, MEdge *medge)
1187 {
1188         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1189         CCGSubSurf *ss = ccgdm->ss;
1190         int index;
1191         int totedge, totface;
1192         int gridSize = ccgSubSurf_getGridSize(ss);
1193         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1194         unsigned int i = 0;
1195         short *edgeFlags = ccgdm->edgeFlags;
1196         const short ed_interior_flag = ccgdm->drawInteriorEdges ? (ME_EDGEDRAW | ME_EDGERENDER) : 0;
1197
1198         totface = ccgSubSurf_getNumFaces(ss);
1199         for (index = 0; index < totface; index++) {
1200                 CCGFace *f = ccgdm->faceMap[index].face;
1201                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1202
1203                 for (S = 0; S < numVerts; S++) {
1204                         for (x = 0; x < gridSize - 1; x++) {
1205                                 ccgDM_to_MEdge(&medge[i++],
1206                                                getFaceIndex(ss, f, S, x,     0, edgeSize, gridSize),
1207                                                getFaceIndex(ss, f, S, x + 1, 0, edgeSize, gridSize),
1208                                                ed_interior_flag);
1209                         }
1210
1211                         for (x = 1; x < gridSize - 1; x++) {
1212                                 for (y = 0; y < gridSize - 1; y++) {
1213                                         ccgDM_to_MEdge(&medge[i++],
1214                                                        getFaceIndex(ss, f, S, x, y,    edgeSize, gridSize),
1215                                                        getFaceIndex(ss, f, S, x, y + 1, edgeSize, gridSize),
1216                                                        ed_interior_flag);
1217                                         ccgDM_to_MEdge(&medge[i++],
1218                                                        getFaceIndex(ss, f, S, y, x,     edgeSize, gridSize),
1219                                                        getFaceIndex(ss, f, S, y + 1, x, edgeSize, gridSize),
1220                                                        ed_interior_flag);
1221                                 }
1222                         }
1223                 }
1224         }
1225
1226         totedge = ccgSubSurf_getNumEdges(ss);
1227         for (index = 0; index < totedge; index++) {
1228                 CCGEdge *e = ccgdm->edgeMap[index].edge;
1229                 short ed_flag = 0;
1230                 int x;
1231                 int edgeIdx = GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e));
1232
1233                 if (!ccgSubSurf_getEdgeNumFaces(e)) {
1234                         ed_flag |= ME_LOOSEEDGE;
1235                 }
1236
1237                 if (edgeFlags) {
1238                         if (edgeIdx != -1) {
1239 #ifdef WITH_FREESTYLE
1240                                 ed_flag |= ((edgeFlags[index] & (ME_SEAM | ME_SHARP | ME_FREESTYLE_EDGE)) | ME_EDGEDRAW | ME_EDGERENDER);
1241 #else
1242                                 ed_flag |= ((edgeFlags[index] & (ME_SEAM | ME_SHARP)) | ME_EDGEDRAW | ME_EDGERENDER);
1243 #endif
1244                         }
1245                 }
1246                 else {
1247                         ed_flag |= ME_EDGEDRAW | ME_EDGERENDER;
1248                 }
1249
1250                 for (x = 0; x < edgeSize - 1; x++) {
1251                         ccgDM_to_MEdge(&medge[i++],
1252                                        getEdgeIndex(ss, e, x, edgeSize),
1253                                        getEdgeIndex(ss, e, x + 1, edgeSize),
1254                                        ed_flag);
1255                 }
1256         }
1257 }
1258
1259 static void ccgDM_copyFinalFaceArray(DerivedMesh *dm, MFace *mface)
1260 {
1261         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1262         CCGSubSurf *ss = ccgdm->ss;
1263         int index;
1264         int totface;
1265         int gridSize = ccgSubSurf_getGridSize(ss);
1266         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1267         int i = 0;
1268         DMFlagMat *faceFlags = ccgdm->faceFlags;
1269
1270         totface = ccgSubSurf_getNumFaces(ss);
1271         for (index = 0; index < totface; index++) {
1272                 CCGFace *f = ccgdm->faceMap[index].face;
1273                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1274                 /* keep types in sync with MFace, avoid many conversions */
1275                 char flag = (faceFlags) ? faceFlags[index].flag : ME_SMOOTH;
1276                 short mat_nr = (faceFlags) ? faceFlags[index].mat_nr : 0;
1277
1278                 for (S = 0; S < numVerts; S++) {
1279                         for (y = 0; y < gridSize - 1; y++) {
1280                                 for (x = 0; x < gridSize - 1; x++) {
1281                                         MFace *mf = &mface[i];
1282                                         mf->v1 = getFaceIndex(ss, f, S, x + 0, y + 0,
1283                                                               edgeSize, gridSize);
1284                                         mf->v2 = getFaceIndex(ss, f, S, x + 0, y + 1,
1285                                                               edgeSize, gridSize);
1286                                         mf->v3 = getFaceIndex(ss, f, S, x + 1, y + 1,
1287                                                               edgeSize, gridSize);
1288                                         mf->v4 = getFaceIndex(ss, f, S, x + 1, y + 0,
1289                                                               edgeSize, gridSize);
1290                                         mf->mat_nr = mat_nr;
1291                                         mf->flag = flag;
1292                                         mf->edcode = 0;
1293
1294                                         i++;
1295                                 }
1296                         }
1297                 }
1298         }
1299 }
1300
1301 static void ccgDM_copyFinalLoopArray(DerivedMesh *dm, MLoop *mloop)
1302 {
1303         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1304         CCGSubSurf *ss = ccgdm->ss;
1305         int index;
1306         int totface;
1307         int gridSize = ccgSubSurf_getGridSize(ss);
1308         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1309         int i = 0;
1310         MLoop *mv;
1311         /* DMFlagMat *faceFlags = ccgdm->faceFlags; */ /* UNUSED */
1312
1313         if (!ccgdm->ehash) {
1314                 MEdge *medge;
1315
1316                 ccgdm->ehash = BLI_edgehash_new();
1317                 medge = ccgdm->dm.getEdgeArray((DerivedMesh *)ccgdm);
1318
1319                 for (i = 0; i < ccgdm->dm.numEdgeData; i++) {
1320                         BLI_edgehash_insert(ccgdm->ehash, medge[i].v1, medge[i].v2, SET_INT_IN_POINTER(i));
1321                 }
1322         }
1323
1324         totface = ccgSubSurf_getNumFaces(ss);
1325         mv = mloop;
1326         for (index = 0; index < totface; index++) {
1327                 CCGFace *f = ccgdm->faceMap[index].face;
1328                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1329                 /* int flag = (faceFlags) ? faceFlags[index * 2]: ME_SMOOTH; */ /* UNUSED */
1330                 /* int mat_nr = (faceFlags) ? faceFlags[index * 2 + 1]: 0; */ /* UNUSED */
1331
1332                 for (S = 0; S < numVerts; S++) {
1333                         for (y = 0; y < gridSize - 1; y++) {
1334                                 for (x = 0; x < gridSize - 1; x++) {
1335                                         int v1, v2, v3, v4;
1336
1337                                         v1 = getFaceIndex(ss, f, S, x + 0, y + 0,
1338                                                           edgeSize, gridSize);
1339
1340                                         v2 = getFaceIndex(ss, f, S, x + 0, y + 1,
1341                                                           edgeSize, gridSize);
1342                                         v3 = getFaceIndex(ss, f, S, x + 1, y + 1,
1343                                                           edgeSize, gridSize);
1344                                         v4 = getFaceIndex(ss, f, S, x + 1, y + 0,
1345                                                           edgeSize, gridSize);
1346
1347                                         mv->v = v1;
1348                                         mv->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v1, v2));
1349                                         mv++, i++;
1350
1351                                         mv->v = v2;
1352                                         mv->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v2, v3));
1353                                         mv++, i++;
1354
1355                                         mv->v = v3;
1356                                         mv->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v3, v4));
1357                                         mv++, i++;
1358
1359                                         mv->v = v4;
1360                                         mv->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v4, v1));
1361                                         mv++, i++;
1362                                 }
1363                         }
1364                 }
1365         }
1366 }
1367
1368 static void ccgDM_copyFinalPolyArray(DerivedMesh *dm, MPoly *mpoly)
1369 {
1370         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1371         CCGSubSurf *ss = ccgdm->ss;
1372         int index;
1373         int totface;
1374         int gridSize = ccgSubSurf_getGridSize(ss);
1375         /* int edgeSize = ccgSubSurf_getEdgeSize(ss); */ /* UNUSED */
1376         int i = 0, k = 0;
1377         DMFlagMat *faceFlags = ccgdm->faceFlags;
1378
1379         totface = ccgSubSurf_getNumFaces(ss);
1380         for (index = 0; index < totface; index++) {
1381                 CCGFace *f = ccgdm->faceMap[index].face;
1382                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1383                 int flag = (faceFlags) ? faceFlags[index].flag : ME_SMOOTH;
1384                 int mat_nr = (faceFlags) ? faceFlags[index].mat_nr : 0;
1385
1386                 for (S = 0; S < numVerts; S++) {
1387                         for (y = 0; y < gridSize - 1; y++) {
1388                                 for (x = 0; x < gridSize - 1; x++) {
1389                                         MPoly *mp = &mpoly[i];
1390
1391                                         mp->mat_nr = mat_nr;
1392                                         mp->flag = flag;
1393                                         mp->loopstart = k;
1394                                         mp->totloop = 4;
1395
1396                                         k += 4;
1397                                         i++;
1398                                 }
1399                         }
1400                 }
1401         }
1402 }
1403
1404 static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3])
1405 {
1406         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1407         CCGSubSurf *ss = ccgdm->ss;
1408         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1409         int gridSize = ccgSubSurf_getGridSize(ss);
1410         int i;
1411         CCGVertIterator *vi;
1412         CCGEdgeIterator *ei;
1413         CCGFaceIterator *fi;
1414         CCGFace **faceMap2;
1415         CCGEdge **edgeMap2;
1416         CCGVert **vertMap2;
1417         int index, totvert, totedge, totface;
1418         
1419         totvert = ccgSubSurf_getNumVerts(ss);
1420         vertMap2 = MEM_mallocN(totvert * sizeof(*vertMap2), "vertmap");
1421         for (vi = ccgSubSurf_getVertIterator(ss); !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
1422                 CCGVert *v = ccgVertIterator_getCurrent(vi);
1423
1424                 vertMap2[GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v))] = v;
1425         }
1426         ccgVertIterator_free(vi);
1427
1428         totedge = ccgSubSurf_getNumEdges(ss);
1429         edgeMap2 = MEM_mallocN(totedge * sizeof(*edgeMap2), "edgemap");
1430         for (ei = ccgSubSurf_getEdgeIterator(ss), i = 0; !ccgEdgeIterator_isStopped(ei); i++, ccgEdgeIterator_next(ei)) {
1431                 CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
1432
1433                 edgeMap2[GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e))] = e;
1434         }
1435
1436         totface = ccgSubSurf_getNumFaces(ss);
1437         faceMap2 = MEM_mallocN(totface * sizeof(*faceMap2), "facemap");
1438         for (fi = ccgSubSurf_getFaceIterator(ss); !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
1439                 CCGFace *f = ccgFaceIterator_getCurrent(fi);
1440
1441                 faceMap2[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f))] = f;
1442         }
1443         ccgFaceIterator_free(fi);
1444
1445         i = 0;
1446         for (index = 0; index < totface; index++) {
1447                 CCGFace *f = faceMap2[index];
1448                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1449
1450                 copy_v3_v3(cos[i++], ccgSubSurf_getFaceCenterData(f));
1451                 
1452                 for (S = 0; S < numVerts; S++) {
1453                         for (x = 1; x < gridSize - 1; x++) {
1454                                 copy_v3_v3(cos[i++], ccgSubSurf_getFaceGridEdgeData(ss, f, S, x));
1455                         }
1456                 }
1457
1458                 for (S = 0; S < numVerts; S++) {
1459                         for (y = 1; y < gridSize - 1; y++) {
1460                                 for (x = 1; x < gridSize - 1; x++) {
1461                                         copy_v3_v3(cos[i++], ccgSubSurf_getFaceGridData(ss, f, S, x, y));
1462                                 }
1463                         }
1464                 }
1465         }
1466
1467         for (index = 0; index < totedge; index++) {
1468                 CCGEdge *e = edgeMap2[index];
1469                 int x;
1470
1471                 for (x = 1; x < edgeSize - 1; x++) {
1472                         copy_v3_v3(cos[i++], ccgSubSurf_getEdgeData(ss, e, x));
1473                 }
1474         }
1475
1476         for (index = 0; index < totvert; index++) {
1477                 CCGVert *v = vertMap2[index];
1478                 copy_v3_v3(cos[i++], ccgSubSurf_getVertData(ss, v));
1479         }
1480
1481         MEM_freeN(vertMap2);
1482         MEM_freeN(edgeMap2);
1483         MEM_freeN(faceMap2);
1484 }
1485
1486 static void ccgDM_foreachMappedVert(
1487         DerivedMesh *dm,
1488         void (*func)(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3]),
1489         void *userData)
1490 {
1491         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1492         CCGVertIterator *vi;
1493         CCGKey key;
1494         CCG_key_top_level(&key, ccgdm->ss);
1495
1496         for (vi = ccgSubSurf_getVertIterator(ccgdm->ss); !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
1497                 CCGVert *v = ccgVertIterator_getCurrent(vi);
1498                 CCGElem *vd = ccgSubSurf_getVertData(ccgdm->ss, v);
1499                 int index = ccgDM_getVertMapIndex(ccgdm->ss, v);
1500
1501                 if (index != -1)
1502                         func(userData, index, CCG_elem_co(&key, vd), CCG_elem_no(&key, vd), NULL);
1503         }
1504
1505         ccgVertIterator_free(vi);
1506 }
1507
1508 static void ccgDM_foreachMappedEdge(
1509         DerivedMesh *dm,
1510         void (*func)(void *userData, int index, const float v0co[3], const float v1co[3]),
1511         void *userData)
1512 {
1513         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1514         CCGSubSurf *ss = ccgdm->ss;
1515         CCGEdgeIterator *ei;
1516         CCGKey key;
1517         int i, edgeSize = ccgSubSurf_getEdgeSize(ss);
1518
1519         CCG_key_top_level(&key, ss);
1520
1521         for (ei = ccgSubSurf_getEdgeIterator(ss); !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
1522                 CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
1523                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
1524                 int index = ccgDM_getEdgeMapIndex(ss, e);
1525
1526                 if (index != -1) {
1527                         for (i = 0; i < edgeSize - 1; i++)
1528                                 func(userData, index, CCG_elem_offset_co(&key, edgeData, i), CCG_elem_offset_co(&key, edgeData, i + 1));
1529                 }
1530         }
1531
1532         ccgEdgeIterator_free(ei);
1533 }
1534
1535 static void ccgDM_drawVerts(DerivedMesh *dm)
1536 {
1537         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1538         CCGSubSurf *ss = ccgdm->ss;
1539         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1540         int gridSize = ccgSubSurf_getGridSize(ss);
1541         CCGVertIterator *vi;
1542         CCGEdgeIterator *ei;
1543         CCGFaceIterator *fi;
1544
1545         glBegin(GL_POINTS);
1546         for (vi = ccgSubSurf_getVertIterator(ss); !ccgVertIterator_isStopped(vi); ccgVertIterator_next(vi)) {
1547                 CCGVert *v = ccgVertIterator_getCurrent(vi);
1548                 glVertex3fv(ccgSubSurf_getVertData(ss, v));
1549         }
1550         ccgVertIterator_free(vi);
1551
1552         for (ei = ccgSubSurf_getEdgeIterator(ss); !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
1553                 CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
1554                 int x;
1555
1556                 for (x = 1; x < edgeSize - 1; x++)
1557                         glVertex3fv(ccgSubSurf_getEdgeData(ss, e, x));
1558         }
1559         ccgEdgeIterator_free(ei);
1560
1561         for (fi = ccgSubSurf_getFaceIterator(ss); !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
1562                 CCGFace *f = ccgFaceIterator_getCurrent(fi);
1563                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1564
1565                 glVertex3fv(ccgSubSurf_getFaceCenterData(f));
1566                 for (S = 0; S < numVerts; S++)
1567                         for (x = 1; x < gridSize - 1; x++)
1568                                 glVertex3fv(ccgSubSurf_getFaceGridEdgeData(ss, f, S, x));
1569                 for (S = 0; S < numVerts; S++)
1570                         for (y = 1; y < gridSize - 1; y++)
1571                                 for (x = 1; x < gridSize - 1; x++)
1572                                         glVertex3fv(ccgSubSurf_getFaceGridData(ss, f, S, x, y));
1573         }
1574         ccgFaceIterator_free(fi);
1575         glEnd();
1576 }
1577
1578 static void ccgdm_pbvh_update(CCGDerivedMesh *ccgdm)
1579 {
1580         if (ccgdm->pbvh && ccgDM_use_grid_pbvh(ccgdm)) {
1581                 CCGFace **faces;
1582                 int totface;
1583
1584                 BKE_pbvh_get_grid_updates(ccgdm->pbvh, 1, (void ***)&faces, &totface);
1585                 if (totface) {
1586                         ccgSubSurf_updateFromFaces(ccgdm->ss, 0, faces, totface);
1587                         ccgSubSurf_updateNormals(ccgdm->ss, faces, totface);
1588                         MEM_freeN(faces);
1589                 }
1590         }
1591 }
1592
1593 static void ccgDM_drawEdges(DerivedMesh *dm, int drawLooseEdges, int drawAllEdges)
1594 {
1595         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1596         CCGSubSurf *ss = ccgdm->ss;
1597         CCGKey key;
1598         int i, j, edgeSize = ccgSubSurf_getEdgeSize(ss);
1599         int totedge = ccgSubSurf_getNumEdges(ss);
1600         int gridSize = ccgSubSurf_getGridSize(ss);
1601         int useAging;
1602
1603         CCG_key_top_level(&key, ss);
1604         ccgdm_pbvh_update(ccgdm);
1605
1606         ccgSubSurf_getUseAgeCounts(ss, &useAging, NULL, NULL, NULL);
1607
1608         for (j = 0; j < totedge; j++) {
1609                 CCGEdge *e = ccgdm->edgeMap[j].edge;
1610                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
1611
1612                 if (!drawLooseEdges && !ccgSubSurf_getEdgeNumFaces(e))
1613                         continue;
1614
1615                 if (!drawAllEdges && ccgdm->edgeFlags && !(ccgdm->edgeFlags[j] & ME_EDGEDRAW))
1616                         continue;
1617
1618                 if (useAging && !(G.f & G_BACKBUFSEL)) {
1619                         int ageCol = 255 - ccgSubSurf_getEdgeAge(ss, e) * 4;
1620                         glColor3ub(0, ageCol > 0 ? ageCol : 0, 0);
1621                 }
1622
1623                 glBegin(GL_LINE_STRIP);
1624                 for (i = 0; i < edgeSize - 1; i++) {
1625                         glVertex3fv(CCG_elem_offset_co(&key, edgeData, i));
1626                         glVertex3fv(CCG_elem_offset_co(&key, edgeData, i + 1));
1627                 }
1628                 glEnd();
1629         }
1630
1631         if (useAging && !(G.f & G_BACKBUFSEL)) {
1632                 glColor3ub(0, 0, 0);
1633         }
1634
1635         if (ccgdm->drawInteriorEdges) {
1636                 int totface = ccgSubSurf_getNumFaces(ss);
1637
1638                 for (j = 0; j < totface; j++) {
1639                         CCGFace *f = ccgdm->faceMap[j].face;
1640                         int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
1641
1642                         for (S = 0; S < numVerts; S++) {
1643                                 CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
1644
1645                                 glBegin(GL_LINE_STRIP);
1646                                 for (x = 0; x < gridSize; x++)
1647                                         glVertex3fv(CCG_elem_offset_co(&key, faceGridData, x));
1648                                 glEnd();
1649                                 for (y = 1; y < gridSize - 1; y++) {
1650                                         glBegin(GL_LINE_STRIP);
1651                                         for (x = 0; x < gridSize; x++)
1652                                                 glVertex3fv(CCG_grid_elem_co(&key, faceGridData, x, y));
1653                                         glEnd();
1654                                 }
1655                                 for (x = 1; x < gridSize - 1; x++) {
1656                                         glBegin(GL_LINE_STRIP);
1657                                         for (y = 0; y < gridSize; y++)
1658                                                 glVertex3fv(CCG_grid_elem_co(&key, faceGridData, x, y));
1659                                         glEnd();
1660                                 }
1661                         }
1662                 }
1663         }
1664 }
1665
1666 static void ccgDM_drawLooseEdges(DerivedMesh *dm)
1667 {
1668         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1669         CCGSubSurf *ss = ccgdm->ss;
1670         CCGKey key;
1671         int totedge = ccgSubSurf_getNumEdges(ss);
1672         int i, j, edgeSize = ccgSubSurf_getEdgeSize(ss);
1673
1674         CCG_key_top_level(&key, ss);
1675
1676         for (j = 0; j < totedge; j++) {
1677                 CCGEdge *e = ccgdm->edgeMap[j].edge;
1678                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
1679
1680                 if (!ccgSubSurf_getEdgeNumFaces(e)) {
1681                         glBegin(GL_LINE_STRIP);
1682                         for (i = 0; i < edgeSize - 1; i++) {
1683                                 glVertex3fv(CCG_elem_offset_co(&key, edgeData, i));
1684                                 glVertex3fv(CCG_elem_offset_co(&key, edgeData, i + 1));
1685                         }
1686                         glEnd();
1687                 }
1688         }
1689 }
1690
1691 static void ccgDM_glNormalFast(float *a, float *b, float *c, float *d)
1692 {
1693         float a_cX = c[0] - a[0], a_cY = c[1] - a[1], a_cZ = c[2] - a[2];
1694         float b_dX = d[0] - b[0], b_dY = d[1] - b[1], b_dZ = d[2] - b[2];
1695         float no[3];
1696
1697         no[0] = b_dY * a_cZ - b_dZ * a_cY;
1698         no[1] = b_dZ * a_cX - b_dX * a_cZ;
1699         no[2] = b_dX * a_cY - b_dY * a_cX;
1700
1701         /* don't normalize, GL_NORMALIZE is enabled */
1702         glNormal3fv(no);
1703 }
1704
1705 /* Only used by non-editmesh types */
1706 static void ccgDM_drawFacesSolid(DerivedMesh *dm, float (*partial_redraw_planes)[4], int fast, DMSetMaterial setMaterial)
1707 {
1708         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1709         CCGSubSurf *ss = ccgdm->ss;
1710         CCGKey key;
1711         int gridSize = ccgSubSurf_getGridSize(ss);
1712         DMFlagMat *faceFlags = ccgdm->faceFlags;
1713         int step = (fast) ? gridSize - 1 : 1;
1714         int i, totface = ccgSubSurf_getNumFaces(ss);
1715         int drawcurrent = 0, matnr = -1, shademodel = -1;
1716
1717         CCG_key_top_level(&key, ss);
1718         ccgdm_pbvh_update(ccgdm);
1719
1720         if (ccgdm->pbvh && ccgdm->multires.mmd && !fast) {
1721                 if (dm->numTessFaceData) {
1722                         BKE_pbvh_draw(ccgdm->pbvh, partial_redraw_planes, NULL,
1723                                                   setMaterial, FALSE);
1724                         glShadeModel(GL_FLAT);
1725                 }
1726
1727                 return;
1728         }
1729
1730         for (i = 0; i < totface; i++) {
1731                 CCGFace *f = ccgdm->faceMap[i].face;
1732                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
1733                 int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
1734                 int new_matnr, new_shademodel;
1735
1736                 if (faceFlags) {
1737                         new_shademodel = (faceFlags[index].flag & ME_SMOOTH) ? GL_SMOOTH : GL_FLAT;
1738                         new_matnr = faceFlags[index].mat_nr;
1739                 }
1740                 else {
1741                         new_shademodel = GL_SMOOTH;
1742                         new_matnr = 0;
1743                 }
1744                 
1745                 if (shademodel != new_shademodel || matnr != new_matnr) {
1746                         matnr = new_matnr;
1747                         shademodel = new_shademodel;
1748
1749                         drawcurrent = setMaterial(matnr + 1, NULL);
1750
1751                         glShadeModel(shademodel);
1752                 }
1753
1754                 if (!drawcurrent)
1755                         continue;
1756
1757                 for (S = 0; S < numVerts; S++) {
1758                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
1759
1760                         if (shademodel == GL_SMOOTH) {
1761                                 for (y = 0; y < gridSize - 1; y += step) {
1762                                         glBegin(GL_QUAD_STRIP);
1763                                         for (x = 0; x < gridSize; x += step) {
1764                                                 CCGElem *a = CCG_grid_elem(&key, faceGridData, x, y + 0);
1765                                                 CCGElem *b = CCG_grid_elem(&key, faceGridData, x, y + step);
1766
1767                                                 glNormal3fv(CCG_elem_no(&key, a));
1768                                                 glVertex3fv(CCG_elem_co(&key, a));
1769                                                 glNormal3fv(CCG_elem_no(&key, b));
1770                                                 glVertex3fv(CCG_elem_co(&key, b));
1771                                         }
1772                                         glEnd();
1773                                 }
1774                         }
1775                         else {
1776                                 glBegin(GL_QUADS);
1777                                 for (y = 0; y < gridSize - 1; y += step) {
1778                                         for (x = 0; x < gridSize - 1; x += step) {
1779                                                 float *a = CCG_grid_elem_co(&key, faceGridData, x, y + 0);
1780                                                 float *b = CCG_grid_elem_co(&key, faceGridData, x + step, y + 0);
1781                                                 float *c = CCG_grid_elem_co(&key, faceGridData, x + step, y + step);
1782                                                 float *d = CCG_grid_elem_co(&key, faceGridData, x, y + step);
1783
1784                                                 ccgDM_glNormalFast(a, b, c, d);
1785
1786                                                 glVertex3fv(d);
1787                                                 glVertex3fv(c);
1788                                                 glVertex3fv(b);
1789                                                 glVertex3fv(a);
1790                                         }
1791                                 }
1792                                 glEnd();
1793                         }
1794                 }
1795         }
1796 }
1797
1798 /* Only used by non-editmesh types */
1799 static void ccgDM_drawMappedFacesGLSL(DerivedMesh *dm,
1800                                       DMSetMaterial setMaterial,
1801                                       DMSetDrawOptions setDrawOptions,
1802                                       void *userData)
1803 {
1804         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1805         CCGSubSurf *ss = ccgdm->ss;
1806         CCGKey key;
1807         GPUVertexAttribs gattribs;
1808         DMVertexAttribs attribs = {{{NULL}}};
1809         /* MTFace *tf = dm->getTessFaceDataArray(dm, CD_MTFACE); */ /* UNUSED */
1810         int gridSize = ccgSubSurf_getGridSize(ss);
1811         int gridFaces = gridSize - 1;
1812         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1813         DMFlagMat *faceFlags = ccgdm->faceFlags;
1814         int a, b, i, do_draw, numVerts, matnr, new_matnr, totface;
1815
1816         CCG_key_top_level(&key, ss);
1817         ccgdm_pbvh_update(ccgdm);
1818
1819         do_draw = 0;
1820         matnr = -1;
1821
1822 #define PASSATTRIB(dx, dy, vert) {                                            \
1823         if (attribs.totorco) {                                                    \
1824                 index = getFaceIndex(ss, f, S, x + dx, y + dy, edgeSize, gridSize);   \
1825                 glVertexAttrib3fvARB(attribs.orco.gl_index,                           \
1826                                      attribs.orco.array[index]);                      \
1827         }                                                                         \
1828         for (b = 0; b < attribs.tottface; b++) {                                  \
1829                 MTFace *tf = &attribs.tface[b].array[a];                              \
1830                 glVertexAttrib2fvARB(attribs.tface[b].gl_index, tf->uv[vert]);        \
1831         }                                                                         \
1832         for (b = 0; b < attribs.totmcol; b++) {                                   \
1833                 MCol *cp = &attribs.mcol[b].array[a * 4 + vert];                      \
1834                 GLubyte col[4];                                                       \
1835                 col[0] = cp->b; col[1] = cp->g; col[2] = cp->r; col[3] = cp->a;       \
1836                 glVertexAttrib4ubvARB(attribs.mcol[b].gl_index, col);                 \
1837         }                                                                         \
1838         if (attribs.tottang) {                                                    \
1839                 float *tang = attribs.tang.array[a * 4 + vert];                       \
1840                 glVertexAttrib4fvARB(attribs.tang.gl_index, tang);                    \
1841         }                                                                         \
1842 } (void)0
1843
1844         totface = ccgSubSurf_getNumFaces(ss);
1845         for (a = 0, i = 0; i < totface; i++) {
1846                 CCGFace *f = ccgdm->faceMap[i].face;
1847                 int S, x, y, drawSmooth;
1848                 int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
1849                 int origIndex = ccgDM_getFaceMapIndex(ss, f);
1850                 
1851                 numVerts = ccgSubSurf_getFaceNumVerts(f);
1852
1853                 if (faceFlags) {
1854                         drawSmooth = (faceFlags[index].flag & ME_SMOOTH);
1855                         new_matnr = faceFlags[index].mat_nr + 1;
1856                 }
1857                 else {
1858                         drawSmooth = 1;
1859                         new_matnr = 1;
1860                 }
1861
1862                 if (new_matnr != matnr) {
1863                         do_draw = setMaterial(matnr = new_matnr, &gattribs);
1864                         if (do_draw)
1865                                 DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1866                 }
1867
1868                 if (!do_draw || (setDrawOptions && (origIndex != ORIGINDEX_NONE) &&
1869                                 (setDrawOptions(userData, origIndex) == DM_DRAW_OPTION_SKIP)))
1870                 {
1871                         a += gridFaces * gridFaces * numVerts;
1872                         continue;
1873                 }
1874
1875                 glShadeModel(drawSmooth ? GL_SMOOTH : GL_FLAT);
1876                 for (S = 0; S < numVerts; S++) {
1877                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
1878                         CCGElem *vda, *vdb;
1879
1880                         if (drawSmooth) {
1881                                 for (y = 0; y < gridFaces; y++) {
1882                                         glBegin(GL_QUAD_STRIP);
1883                                         for (x = 0; x < gridFaces; x++) {
1884                                                 vda = CCG_grid_elem(&key, faceGridData, x, y + 0);
1885                                                 vdb = CCG_grid_elem(&key, faceGridData, x, y + 1);
1886                                                 
1887                                                 PASSATTRIB(0, 0, 0);
1888                                                 glNormal3fv(CCG_elem_no(&key, vda));
1889                                                 glVertex3fv(CCG_elem_co(&key, vda));
1890
1891                                                 PASSATTRIB(0, 1, 1);
1892                                                 glNormal3fv(CCG_elem_no(&key, vdb));
1893                                                 glVertex3fv(CCG_elem_co(&key, vdb));
1894
1895                                                 if (x != gridFaces - 1)
1896                                                         a++;
1897                                         }
1898
1899                                         vda = CCG_grid_elem(&key, faceGridData, x, y + 0);
1900                                         vdb = CCG_grid_elem(&key, faceGridData, x, y + 1);
1901
1902                                         PASSATTRIB(0, 0, 3);
1903                                         glNormal3fv(CCG_elem_no(&key, vda));
1904                                         glVertex3fv(CCG_elem_co(&key, vda));
1905
1906                                         PASSATTRIB(0, 1, 2);
1907                                         glNormal3fv(CCG_elem_no(&key, vdb));
1908                                         glVertex3fv(CCG_elem_co(&key, vdb));
1909
1910                                         glEnd();
1911
1912                                         a++;
1913                                 }
1914                         }
1915                         else {
1916                                 glBegin(GL_QUADS);
1917                                 for (y = 0; y < gridFaces; y++) {
1918                                         for (x = 0; x < gridFaces; x++) {
1919                                                 float *aco = CCG_grid_elem_co(&key, faceGridData, x, y);
1920                                                 float *bco = CCG_grid_elem_co(&key, faceGridData, x + 1, y);
1921                                                 float *cco = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
1922                                                 float *dco = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
1923
1924                                                 ccgDM_glNormalFast(aco, bco, cco, dco);
1925
1926                                                 PASSATTRIB(0, 1, 1);
1927                                                 glVertex3fv(dco);
1928                                                 PASSATTRIB(1, 1, 2);
1929                                                 glVertex3fv(cco);
1930                                                 PASSATTRIB(1, 0, 3);
1931                                                 glVertex3fv(bco);
1932                                                 PASSATTRIB(0, 0, 0);
1933                                                 glVertex3fv(aco);
1934                                                 
1935                                                 a++;
1936                                         }
1937                                 }
1938                                 glEnd();
1939                         }
1940                 }
1941         }
1942
1943 #undef PASSATTRIB
1944 }
1945
1946 static void ccgDM_drawFacesGLSL(DerivedMesh *dm, DMSetMaterial setMaterial)
1947 {
1948         dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
1949 }
1950
1951 /* Only used by non-editmesh types */
1952 static void ccgDM_drawMappedFacesMat(DerivedMesh *dm,
1953                                      void (*setMaterial)(void *userData, int, void *attribs),
1954                                      int (*setFace)(void *userData, int index), void *userData)
1955 {
1956         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1957         CCGSubSurf *ss = ccgdm->ss;
1958         CCGKey key;
1959         GPUVertexAttribs gattribs;
1960         DMVertexAttribs attribs = {{{NULL}}};
1961         int gridSize = ccgSubSurf_getGridSize(ss);
1962         int gridFaces = gridSize - 1;
1963         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1964         DMFlagMat *faceFlags = ccgdm->faceFlags;
1965         int a, b, i, numVerts, matnr, new_matnr, totface;
1966
1967         CCG_key_top_level(&key, ss);
1968         ccgdm_pbvh_update(ccgdm);
1969
1970         matnr = -1;
1971
1972 #define PASSATTRIB(dx, dy, vert) {                                            \
1973         if (attribs.totorco) {                                                    \
1974                 index = getFaceIndex(ss, f, S, x + dx, y + dy, edgeSize, gridSize);   \
1975                 if (attribs.orco.gl_texco)                                            \
1976                         glTexCoord3fv(attribs.orco.array[index]);                         \
1977                 else                                                                  \
1978                         glVertexAttrib3fvARB(attribs.orco.gl_index,                       \
1979                                              attribs.orco.array[index]);                  \
1980         }                                                                         \
1981         for (b = 0; b < attribs.tottface; b++) {                                  \
1982                 MTFace *tf = &attribs.tface[b].array[a];                              \
1983                 if (attribs.tface[b].gl_texco)                                        \
1984                         glTexCoord2fv(tf->uv[vert]);                                      \
1985                 else                                                                  \
1986                         glVertexAttrib2fvARB(attribs.tface[b].gl_index, tf->uv[vert]);    \
1987         }                                                                         \
1988         for (b = 0; b < attribs.totmcol; b++) {                                   \
1989                 MCol *cp = &attribs.mcol[b].array[a * 4 + vert];                      \
1990                 GLubyte col[4];                                                       \
1991                 col[0] = cp->b; col[1] = cp->g; col[2] = cp->r; col[3] = cp->a;       \
1992                 glVertexAttrib4ubvARB(attribs.mcol[b].gl_index, col);                 \
1993         }                                                                         \
1994         if (attribs.tottang) {                                                    \
1995                 float *tang = attribs.tang.array[a * 4 + vert];                       \
1996                 glVertexAttrib4fvARB(attribs.tang.gl_index, tang);                    \
1997         }                                                                         \
1998 } (void)0
1999
2000         totface = ccgSubSurf_getNumFaces(ss);
2001         for (a = 0, i = 0; i < totface; i++) {
2002                 CCGFace *f = ccgdm->faceMap[i].face;
2003                 int S, x, y, drawSmooth;
2004                 int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2005                 int origIndex = ccgDM_getFaceMapIndex(ss, f);
2006                 
2007                 numVerts = ccgSubSurf_getFaceNumVerts(f);
2008
2009                 /* get flags */
2010                 if (faceFlags) {
2011                         drawSmooth = (faceFlags[index].flag & ME_SMOOTH);
2012                         new_matnr = faceFlags[index].mat_nr + 1;
2013                 }
2014                 else {
2015                         drawSmooth = 1;
2016                         new_matnr = 1;
2017                 }
2018
2019                 /* material */
2020                 if (new_matnr != matnr) {
2021                         setMaterial(userData, matnr = new_matnr, &gattribs);
2022                         DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
2023                 }
2024
2025                 /* face hiding */
2026                 if ((setFace && (origIndex != ORIGINDEX_NONE) && !setFace(userData, origIndex))) {
2027                         a += gridFaces * gridFaces * numVerts;
2028                         continue;
2029                 }
2030
2031                 /* draw face*/
2032                 glShadeModel(drawSmooth ? GL_SMOOTH : GL_FLAT);
2033                 for (S = 0; S < numVerts; S++) {
2034                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
2035                         CCGElem *vda, *vdb;
2036
2037                         if (drawSmooth) {
2038                                 for (y = 0; y < gridFaces; y++) {
2039                                         glBegin(GL_QUAD_STRIP);
2040                                         for (x = 0; x < gridFaces; x++) {
2041                                                 vda = CCG_grid_elem(&key, faceGridData, x, y);
2042                                                 vdb = CCG_grid_elem(&key, faceGridData, x, y + 1);
2043                                                 
2044                                                 PASSATTRIB(0, 0, 0);
2045                                                 glNormal3fv(CCG_elem_no(&key, vda));
2046                                                 glVertex3fv(CCG_elem_co(&key, vda));
2047
2048                                                 PASSATTRIB(0, 1, 1);
2049                                                 glNormal3fv(CCG_elem_no(&key, vdb));
2050                                                 glVertex3fv(CCG_elem_co(&key, vdb));
2051
2052                                                 if (x != gridFaces - 1)
2053                                                         a++;
2054                                         }
2055
2056                                         vda = CCG_grid_elem(&key, faceGridData, x, y + 0);
2057                                         vdb = CCG_grid_elem(&key, faceGridData, x, y + 1);
2058
2059                                         PASSATTRIB(0, 0, 3);
2060                                         glNormal3fv(CCG_elem_no(&key, vda));
2061                                         glVertex3fv(CCG_elem_co(&key, vda));
2062
2063                                         PASSATTRIB(0, 1, 2);
2064                                         glNormal3fv(CCG_elem_no(&key, vdb));
2065                                         glVertex3fv(CCG_elem_co(&key, vdb));
2066
2067                                         glEnd();
2068
2069                                         a++;
2070                                 }
2071                         }
2072                         else {
2073                                 glBegin(GL_QUADS);
2074                                 for (y = 0; y < gridFaces; y++) {
2075                                         for (x = 0; x < gridFaces; x++) {
2076                                                 float *aco = CCG_grid_elem_co(&key, faceGridData, x, y + 0);
2077                                                 float *bco = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 0);
2078                                                 float *cco = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
2079                                                 float *dco = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
2080
2081                                                 ccgDM_glNormalFast(aco, bco, cco, dco);
2082
2083                                                 PASSATTRIB(0, 1, 1);
2084                                                 glVertex3fv(dco);
2085                                                 PASSATTRIB(1, 1, 2);
2086                                                 glVertex3fv(cco);
2087                                                 PASSATTRIB(1, 0, 3);
2088                                                 glVertex3fv(bco);
2089                                                 PASSATTRIB(0, 0, 0);
2090                                                 glVertex3fv(aco);
2091                                                 
2092                                                 a++;
2093                                         }
2094                                 }
2095                                 glEnd();
2096                         }
2097                 }
2098         }
2099
2100 #undef PASSATTRIB
2101 }
2102
2103 static void ccgDM_drawFacesTex_common(DerivedMesh *dm,
2104                                       DMSetDrawOptionsTex drawParams,
2105                                       DMSetDrawOptions drawParamsMapped,
2106                                       DMCompareDrawOptions compareDrawOptions,
2107                                       void *userData)
2108 {
2109         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2110         CCGSubSurf *ss = ccgdm->ss;
2111         CCGKey key;
2112         MCol *mcol = dm->getTessFaceDataArray(dm, CD_PREVIEW_MCOL);
2113         MTFace *tf = DM_get_tessface_data_layer(dm, CD_MTFACE);
2114         DMFlagMat *faceFlags = ccgdm->faceFlags;
2115         DMDrawOption draw_option;
2116         int i, totface, gridSize = ccgSubSurf_getGridSize(ss);
2117         int gridFaces = gridSize - 1;
2118
2119         (void) compareDrawOptions;
2120
2121         CCG_key_top_level(&key, ss);
2122         ccgdm_pbvh_update(ccgdm);
2123
2124         if (!mcol)
2125                 mcol = dm->getTessFaceDataArray(dm, CD_MCOL);
2126
2127         if (!mcol)
2128                 mcol = dm->getTessFaceDataArray(dm, CD_TEXTURE_MCOL);
2129
2130         totface = ccgSubSurf_getNumFaces(ss);
2131         for (i = 0; i < totface; i++) {
2132                 CCGFace *f = ccgdm->faceMap[i].face;
2133                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2134                 int drawSmooth, index = ccgDM_getFaceMapIndex(ss, f);
2135                 int origIndex = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2136                 unsigned char *cp = NULL;
2137                 int mat_nr;
2138
2139                 if (faceFlags) {
2140                         drawSmooth = (faceFlags[origIndex].flag & ME_SMOOTH);
2141                         mat_nr = faceFlags[origIndex].mat_nr;
2142                 }
2143                 else {
2144                         drawSmooth = 1;
2145                         mat_nr = 0;
2146                 }
2147
2148                 if (drawParams)
2149                         draw_option = drawParams(tf, (mcol != NULL), mat_nr);
2150                 else if (index != ORIGINDEX_NONE)
2151                         draw_option = (drawParamsMapped) ? drawParamsMapped(userData, index) : DM_DRAW_OPTION_NORMAL;
2152                 else
2153                         draw_option = GPU_enable_material(mat_nr, NULL) ? DM_DRAW_OPTION_NORMAL : DM_DRAW_OPTION_SKIP;
2154
2155
2156                 if (draw_option == DM_DRAW_OPTION_SKIP) {
2157                         if (tf) tf += gridFaces * gridFaces * numVerts;
2158                         if (mcol) mcol += gridFaces * gridFaces * numVerts * 4;
2159                         continue;
2160                 }
2161
2162                 /* flag 1 == use vertex colors */
2163                 if (mcol) {
2164                         if (draw_option != DM_DRAW_OPTION_NO_MCOL)
2165                                 cp = (unsigned char *)mcol;
2166                         mcol += gridFaces * gridFaces * numVerts * 4;
2167                 }
2168
2169                 for (S = 0; S < numVerts; S++) {
2170                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
2171                         CCGElem *a, *b;
2172
2173                         if (drawSmooth) {
2174                                 glShadeModel(GL_SMOOTH);
2175                                 for (y = 0; y < gridFaces; y++) {
2176                                         glBegin(GL_QUAD_STRIP);
2177                                         for (x = 0; x < gridFaces; x++) {
2178                                                 a = CCG_grid_elem(&key, faceGridData, x, y + 0);
2179                                                 b = CCG_grid_elem(&key, faceGridData, x, y + 1);
2180
2181                                                 if (tf) glTexCoord2fv(tf->uv[0]);
2182                                                 if (cp) glColor3ub(cp[3], cp[2], cp[1]);
2183                                                 glNormal3fv(CCG_elem_no(&key, a));
2184                                                 glVertex3fv(CCG_elem_co(&key, a));
2185
2186                                                 if (tf) glTexCoord2fv(tf->uv[1]);
2187                                                 if (cp) glColor3ub(cp[7], cp[6], cp[5]);
2188                                                 glNormal3fv(CCG_elem_no(&key, b));
2189                                                 glVertex3fv(CCG_elem_co(&key, b));
2190                                                 
2191                                                 if (x != gridFaces - 1) {
2192                                                         if (tf) tf++;
2193                                                         if (cp) cp += 16;
2194                                                 }
2195                                         }
2196
2197                                         a = CCG_grid_elem(&key, faceGridData, x, y + 0);
2198                                         b = CCG_grid_elem(&key, faceGridData, x, y + 1);
2199
2200                                         if (tf) glTexCoord2fv(tf->uv[3]);
2201                                         if (cp) glColor3ub(cp[15], cp[14], cp[13]);
2202                                         glNormal3fv(CCG_elem_no(&key, a));
2203                                         glVertex3fv(CCG_elem_co(&key, a));
2204
2205                                         if (tf) glTexCoord2fv(tf->uv[2]);
2206                                         if (cp) glColor3ub(cp[11], cp[10], cp[9]);
2207                                         glNormal3fv(CCG_elem_no(&key, b));
2208                                         glVertex3fv(CCG_elem_co(&key, b));
2209
2210                                         if (tf) tf++;
2211                                         if (cp) cp += 16;
2212
2213                                         glEnd();
2214                                 }
2215                         }
2216                         else {
2217                                 glShadeModel((cp) ? GL_SMOOTH : GL_FLAT);
2218                                 glBegin(GL_QUADS);
2219                                 for (y = 0; y < gridFaces; y++) {
2220                                         for (x = 0; x < gridFaces; x++) {
2221                                                 float *a_co = CCG_grid_elem_co(&key, faceGridData, x, y + 0);
2222                                                 float *b_co = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 0);
2223                                                 float *c_co = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
2224                                                 float *d_co = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
2225
2226                                                 ccgDM_glNormalFast(a_co, b_co, c_co, d_co);
2227
2228                                                 if (tf) glTexCoord2fv(tf->uv[1]);
2229                                                 if (cp) glColor3ub(cp[7], cp[6], cp[5]);
2230                                                 glVertex3fv(d_co);
2231
2232                                                 if (tf) glTexCoord2fv(tf->uv[2]);
2233                                                 if (cp) glColor3ub(cp[11], cp[10], cp[9]);
2234                                                 glVertex3fv(c_co);
2235
2236                                                 if (tf) glTexCoord2fv(tf->uv[3]);
2237                                                 if (cp) glColor3ub(cp[15], cp[14], cp[13]);
2238                                                 glVertex3fv(b_co);
2239
2240                                                 if (tf) glTexCoord2fv(tf->uv[0]);
2241                                                 if (cp) glColor3ub(cp[3], cp[2], cp[1]);
2242                                                 glVertex3fv(a_co);
2243
2244                                                 if (tf) tf++;
2245                                                 if (cp) cp += 16;
2246                                         }
2247                                 }
2248                                 glEnd();
2249                         }
2250                 }
2251         }
2252 }
2253
2254 static void ccgDM_drawFacesTex(DerivedMesh *dm,
2255                                DMSetDrawOptionsTex setDrawOptions,
2256                                DMCompareDrawOptions compareDrawOptions,
2257                                void *userData)
2258 {
2259         ccgDM_drawFacesTex_common(dm, setDrawOptions, NULL, compareDrawOptions, userData);
2260 }
2261
2262 static void ccgDM_drawMappedFacesTex(DerivedMesh *dm,
2263                                      DMSetDrawOptions setDrawOptions,
2264                                      DMCompareDrawOptions compareDrawOptions,
2265                                      void *userData)
2266 {
2267         ccgDM_drawFacesTex_common(dm, NULL, setDrawOptions, compareDrawOptions, userData);
2268 }
2269
2270 static void ccgDM_drawUVEdges(DerivedMesh *dm)
2271 {
2272
2273         MFace *mf = dm->getTessFaceArray(dm);
2274         MTFace *tf = DM_get_tessface_data_layer(dm, CD_MTFACE);
2275         int i;
2276         
2277         if (tf) {
2278                 glBegin(GL_LINES);
2279                 for (i = 0; i < dm->numTessFaceData; i++, mf++, tf++) {
2280                         if (!(mf->flag & ME_HIDE)) {
2281                                 glVertex2fv(tf->uv[0]);
2282                                 glVertex2fv(tf->uv[1]);
2283         
2284                                 glVertex2fv(tf->uv[1]);
2285                                 glVertex2fv(tf->uv[2]);
2286         
2287                                 if (!mf->v4) {
2288                                         glVertex2fv(tf->uv[2]);
2289                                         glVertex2fv(tf->uv[0]);
2290                                 }
2291                                 else {
2292                                         glVertex2fv(tf->uv[2]);
2293                                         glVertex2fv(tf->uv[3]);
2294         
2295                                         glVertex2fv(tf->uv[3]);
2296                                         glVertex2fv(tf->uv[0]);
2297                                 }
2298                         }
2299                 }
2300                 glEnd();
2301         }
2302 }
2303
2304 static void ccgDM_drawMappedFaces(DerivedMesh *dm,
2305                                   DMSetDrawOptions setDrawOptions,
2306                                   DMSetMaterial setMaterial,
2307                                   DMCompareDrawOptions compareDrawOptions,
2308                                   void *userData, DMDrawFlag flag)
2309 {
2310         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2311         CCGSubSurf *ss = ccgdm->ss;
2312         CCGKey key;
2313         MCol *mcol = NULL;
2314         int i, gridSize = ccgSubSurf_getGridSize(ss);
2315         DMFlagMat *faceFlags = ccgdm->faceFlags;
2316         int useColors = flag & DM_DRAW_USE_COLORS;
2317         int gridFaces = gridSize - 1, totface;
2318
2319         CCG_key_top_level(&key, ss);
2320
2321         /* currently unused -- each original face is handled separately */
2322         (void)compareDrawOptions;
2323
2324         if (useColors) {
2325                 mcol = dm->getTessFaceDataArray(dm, CD_PREVIEW_MCOL);
2326                 if (!mcol)
2327                         mcol = dm->getTessFaceDataArray(dm, CD_MCOL);
2328         }
2329
2330         totface = ccgSubSurf_getNumFaces(ss);
2331         for (i = 0; i < totface; i++) {
2332                 CCGFace *f = ccgdm->faceMap[i].face;
2333                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2334                 int drawSmooth, index = ccgDM_getFaceMapIndex(ss, f);
2335                 int origIndex;
2336                 unsigned char *cp = NULL;
2337
2338                 origIndex = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2339
2340                 if (flag & DM_DRAW_ALWAYS_SMOOTH) drawSmooth = 1;
2341                 else if (faceFlags) drawSmooth = (faceFlags[origIndex].flag & ME_SMOOTH);
2342                 else drawSmooth = 1;
2343
2344                 if (mcol) {
2345                         cp = (unsigned char *)mcol;
2346                         mcol += gridFaces * gridFaces * numVerts * 4;
2347                 }
2348
2349                 {
2350                         DMDrawOption draw_option = DM_DRAW_OPTION_NORMAL;
2351
2352                         if (index == ORIGINDEX_NONE)
2353                                 draw_option = setMaterial(faceFlags ? faceFlags[origIndex].mat_nr + 1 : 1, NULL);  /* XXX, no faceFlags no material */
2354                         else if (setDrawOptions)
2355                                 draw_option = setDrawOptions(userData, index);
2356
2357                         if (draw_option != DM_DRAW_OPTION_SKIP) {
2358                                 if (draw_option == DM_DRAW_OPTION_STIPPLE) {
2359                                         glEnable(GL_POLYGON_STIPPLE);
2360                                         glPolygonStipple(stipple_quarttone);
2361                                 }
2362
2363                                 /* no need to set shading mode to flat because
2364                                  *  normals are already used to change shading */
2365                                 glShadeModel(GL_SMOOTH);
2366                                 
2367                                 for (S = 0; S < numVerts; S++) {
2368                                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
2369                                         if (drawSmooth) {
2370                                                 for (y = 0; y < gridFaces; y++) {
2371                                                         CCGElem *a, *b;
2372                                                         glBegin(GL_QUAD_STRIP);
2373                                                         for (x = 0; x < gridFaces; x++) {
2374                                                                 a = CCG_grid_elem(&key, faceGridData, x, y + 0);
2375                                                                 b = CCG_grid_elem(&key, faceGridData, x, y + 1);
2376         
2377                                                                 if (cp) glColor3ub(cp[3], cp[2], cp[1]);
2378                                                                 glNormal3fv(CCG_elem_no(&key, a));
2379                                                                 glVertex3fv(CCG_elem_co(&key, a));
2380                                                                 if (cp) glColor3ub(cp[7], cp[6], cp[5]);
2381                                                                 glNormal3fv(CCG_elem_no(&key, b));
2382                                                                 glVertex3fv(CCG_elem_co(&key, b));
2383
2384                                                                 if (x != gridFaces - 1) {
2385                                                                         if (cp) cp += 16;
2386                                                                 }
2387                                                         }
2388
2389                                                         a = CCG_grid_elem(&key, faceGridData, x, y + 0);
2390                                                         b = CCG_grid_elem(&key, faceGridData, x, y + 1);
2391
2392                                                         if (cp) glColor3ub(cp[15], cp[14], cp[13]);
2393                                                         glNormal3fv(CCG_elem_no(&key, a));
2394                                                         glVertex3fv(CCG_elem_co(&key, a));
2395                                                         if (cp) glColor3ub(cp[11], cp[10], cp[9]);
2396                                                         glNormal3fv(CCG_elem_no(&key, b));
2397                                                         glVertex3fv(CCG_elem_co(&key, b));
2398
2399                                                         if (cp) cp += 16;
2400
2401                                                         glEnd();
2402                                                 }
2403                                         }
2404                                         else {
2405                                                 glBegin(GL_QUADS);
2406                                                 for (y = 0; y < gridFaces; y++) {
2407                                                         for (x = 0; x < gridFaces; x++) {
2408                                                                 float *a = CCG_grid_elem_co(&key, faceGridData, x, y + 0);
2409                                                                 float *b = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 0);
2410                                                                 float *c = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
2411                                                                 float *d = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
2412
2413                                                                 ccgDM_glNormalFast(a, b, c, d);
2414         
2415                                                                 if (cp) glColor3ub(cp[7], cp[6], cp[5]);
2416                                                                 glVertex3fv(d);
2417                                                                 if (cp) glColor3ub(cp[11], cp[10], cp[9]);
2418                                                                 glVertex3fv(c);
2419                                                                 if (cp) glColor3ub(cp[15], cp[14], cp[13]);
2420                                                                 glVertex3fv(b);
2421                                                                 if (cp) glColor3ub(cp[3], cp[2], cp[1]);
2422                                                                 glVertex3fv(a);
2423
2424                                                                 if (cp) cp += 16;
2425                                                         }
2426                                                 }
2427                                                 glEnd();
2428                                         }
2429                                 }
2430                                 if (draw_option == DM_DRAW_OPTION_STIPPLE)
2431                                         glDisable(GL_POLYGON_STIPPLE);
2432                         }
2433                 }
2434         }
2435 }
2436
2437 static void ccgDM_drawMappedEdges(DerivedMesh *dm,
2438                                   DMSetDrawOptions setDrawOptions,
2439                                   void *userData)
2440 {
2441         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2442         CCGSubSurf *ss = ccgdm->ss;
2443         CCGEdgeIterator *ei;
2444         CCGKey key;
2445         int i, useAging, edgeSize = ccgSubSurf_getEdgeSize(ss);
2446
2447         CCG_key_top_level(&key, ss);
2448         ccgSubSurf_getUseAgeCounts(ss, &useAging, NULL, NULL, NULL);
2449
2450         for (ei = ccgSubSurf_getEdgeIterator(ss); !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
2451                 CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
2452                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
2453                 int index = ccgDM_getEdgeMapIndex(ss, e);
2454
2455                 glBegin(GL_LINE_STRIP);
2456                 if (index != -1 && (!setDrawOptions || (setDrawOptions(userData, index) != DM_DRAW_OPTION_SKIP))) {
2457                         if (useAging && !(G.f & G_BACKBUFSEL)) {
2458                                 int ageCol = 255 - ccgSubSurf_getEdgeAge(ss, e) * 4;
2459                                 glColor3ub(0, ageCol > 0 ? ageCol : 0, 0);
2460                         }
2461
2462                         for (i = 0; i < edgeSize - 1; i++) {
2463                                 glVertex3fv(CCG_elem_offset_co(&key, edgeData, i));
2464                                 glVertex3fv(CCG_elem_offset_co(&key, edgeData, i + 1));
2465                         }
2466                 }
2467                 glEnd();
2468         }
2469
2470         ccgEdgeIterator_free(ei);
2471 }
2472
2473 static void ccgDM_drawMappedEdgesInterp(DerivedMesh *dm,
2474                                         DMSetDrawOptions setDrawOptions,
2475                                         DMSetDrawInterpOptions setDrawInterpOptions,
2476                                         void *userData)
2477 {
2478         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2479         CCGSubSurf *ss = ccgdm->ss;
2480         CCGKey key;
2481         CCGEdgeIterator *ei;
2482         int i, useAging, edgeSize = ccgSubSurf_getEdgeSize(ss);
2483
2484         CCG_key_top_level(&key, ss);
2485         ccgSubSurf_getUseAgeCounts(ss, &useAging, NULL, NULL, NULL);
2486
2487         for (ei = ccgSubSurf_getEdgeIterator(ss); !ccgEdgeIterator_isStopped(ei); ccgEdgeIterator_next(ei)) {
2488                 CCGEdge *e = ccgEdgeIterator_getCurrent(ei);
2489                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
2490                 int index = ccgDM_getEdgeMapIndex(ss, e);
2491
2492                 glBegin(GL_LINE_STRIP);
2493                 if (index != -1 && (!setDrawOptions || (setDrawOptions(userData, index) != DM_DRAW_OPTION_SKIP))) {
2494                         for (i = 0; i < edgeSize; i++) {
2495                                 setDrawInterpOptions(userData, index, (float) i / (edgeSize - 1));
2496
2497                                 if (useAging && !(G.f & G_BACKBUFSEL)) {
2498                                         int ageCol = 255 - ccgSubSurf_getEdgeAge(ss, e) * 4;
2499                                         glColor3ub(0, ageCol > 0 ? ageCol : 0, 0);
2500                                 }
2501
2502                                 glVertex3fv(CCG_elem_offset_co(&key, edgeData, i));
2503                         }
2504                 }
2505                 glEnd();
2506         }
2507
2508         ccgEdgeIterator_free(ei);
2509 }
2510
2511 static void ccgDM_foreachMappedFaceCenter(
2512         DerivedMesh *dm,
2513         void (*func)(void *userData, int index, const float co[3], const float no[3]),
2514         void *userData)
2515 {
2516         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2517         CCGSubSurf *ss = ccgdm->ss;
2518         CCGKey key;
2519         CCGFaceIterator *fi;
2520
2521         CCG_key_top_level(&key, ss);
2522
2523         for (fi = ccgSubSurf_getFaceIterator(ss); !ccgFaceIterator_isStopped(fi); ccgFaceIterator_next(fi)) {
2524                 CCGFace *f = ccgFaceIterator_getCurrent(fi);
2525                 int index = ccgDM_getFaceMapIndex(ss, f);
2526
2527                 if (index != -1) {
2528                         /* Face center data normal isn't updated atm. */
2529                         CCGElem *vd = ccgSubSurf_getFaceGridData(ss, f, 0, 0, 0);
2530
2531                         func(userData, index, CCG_elem_co(&key, vd), CCG_elem_no(&key, vd));
2532                 }
2533         }
2534
2535         ccgFaceIterator_free(fi);
2536 }
2537
2538 static void ccgDM_release(DerivedMesh *dm)
2539 {
2540         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2541
2542         if (DM_release(dm)) {
2543                 /* Before freeing, need to update the displacement map */
2544                 if (ccgdm->multires.modified_flags) {
2545                         /* Check that mmd still exists */
2546                         if (!ccgdm->multires.local_mmd &&
2547                             BLI_findindex(&ccgdm->multires.ob->modifiers, ccgdm->multires.mmd) < 0)
2548                         {
2549                                 ccgdm->multires.mmd = NULL;
2550                         }
2551                         
2552                         if (ccgdm->multires.mmd) {
2553                                 if (ccgdm->multires.modified_flags & MULTIRES_COORDS_MODIFIED)
2554                                         multires_modifier_update_mdisps(dm);
2555                                 if (ccgdm->multires.modified_flags & MULTIRES_HIDDEN_MODIFIED)
2556                                         multires_modifier_update_hidden(dm);
2557                         }
2558                 }
2559
2560                 if (ccgdm->ehash)
2561                         BLI_edgehash_free(ccgdm->ehash, NULL);
2562
2563                 if (ccgdm->reverseFaceMap) MEM_freeN(ccgdm->reverseFaceMap);
2564                 if (ccgdm->gridFaces) MEM_freeN(ccgdm->gridFaces);
2565                 if (ccgdm->gridData) MEM_freeN(ccgdm->gridData);
2566                 if (ccgdm->gridAdjacency) MEM_freeN(ccgdm->gridAdjacency);
2567                 if (ccgdm->gridOffset) MEM_freeN(ccgdm->gridOffset);
2568                 if (ccgdm->gridFlagMats) MEM_freeN(ccgdm->gridFlagMats);
2569                 if (ccgdm->gridHidden) {
2570                         int i, numGrids = dm->getNumGrids(dm);
2571                         for (i = 0; i < numGrids; i++) {
2572                                 if (ccgdm->gridHidden[i])
2573                                         MEM_freeN(ccgdm->gridHidden[i]);
2574                         }
2575                         MEM_freeN(ccgdm->gridHidden);
2576                 }
2577                 if (ccgdm->freeSS) ccgSubSurf_free(ccgdm->ss);
2578                 if (ccgdm->pmap) MEM_freeN(ccgdm->pmap);
2579                 if (ccgdm->pmap_mem) MEM_freeN(ccgdm->pmap_mem);
2580                 MEM_freeN(ccgdm->edgeFlags);
2581                 MEM_freeN(ccgdm->faceFlags);
2582                 MEM_freeN(ccgdm->vertMap);
2583                 MEM_freeN(ccgdm->edgeMap);
2584                 MEM_freeN(ccgdm->faceMap);
2585                 MEM_freeN(ccgdm);
2586         }
2587 }
2588
2589 static void ccg_loops_to_corners(CustomData *fdata, CustomData *ldata, 
2590                                  CustomData *pdata, int loopstart, int findex,  int polyindex,
2591                                  const int numTex, const int numCol, const int hasPCol, const int hasOrigSpace)
2592 {
2593         MTFace *texface;
2594         MTexPoly *texpoly;
2595         MCol *mcol;
2596         MLoopCol *mloopcol;
2597         MLoopUV *mloopuv;
2598         int i, j;
2599
2600         for (i = 0; i < numTex; i++) {
2601                 texface = CustomData_get_n(fdata, CD_MTFACE, findex, i);
2602                 texpoly = CustomData_get_n(pdata, CD_MTEXPOLY, polyindex, i);
2603                 
2604                 ME_MTEXFACE_CPY(texface, texpoly);
2605
2606                 mloopuv = CustomData_get_n(ldata, CD_MLOOPUV, loopstart, i);
2607                 for (j = 0; j < 4; j++, mloopuv++) {
2608                         copy_v2_v2(texface->uv[j], mloopuv->uv);
2609                 }
2610         }
2611
2612         for (i = 0; i < numCol; i++) {
2613                 mloopcol = CustomData_get_n(ldata, CD_MLOOPCOL, loopstart, i);
2614                 mcol = CustomData_get_n(fdata, CD_MCOL, findex, i);
2615
2616                 for (j = 0; j < 4; j++, mloopcol++) {
2617                         MESH_MLOOPCOL_TO_MCOL(mloopcol, &mcol[j]);
2618                 }
2619         }
2620         
2621         if (hasPCol) {
2622                 mloopcol = CustomData_get(ldata, loopstart, CD_PREVIEW_MLOOPCOL);
2623                 mcol = CustomData_get(fdata, findex, CD_PREVIEW_MCOL);
2624
2625                 for (j = 0; j < 4; j++, mloopcol++) {
2626                         MESH_MLOOPCOL_TO_MCOL(mloopcol, &mcol[j]);
2627                 }
2628         }
2629
2630         if (hasOrigSpace) {
2631                 OrigSpaceFace *of = CustomData_get(fdata, findex, CD_ORIGSPACE);
2632                 OrigSpaceLoop *lof;
2633
2634                 lof = CustomData_get(ldata, loopstart, CD_ORIGSPACE_MLOOP);
2635                 for (j = 0; j < 4; j++, lof++) {
2636                         copy_v2_v2(of->uv[j], lof->uv);
2637                 }
2638         }
2639 }
2640
2641 static void *ccgDM_get_vert_data_layer(DerivedMesh *dm, int type)
2642 {
2643         if (type == CD_ORIGINDEX) {
2644                 /* create origindex on demand to save memory */
2645                 CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2646                 CCGSubSurf *ss = ccgdm->ss;
2647                 int *origindex;
2648                 int a, index, totnone, totorig;
2649
2650                 /* Avoid re-creation if the layer exists already */
2651                 origindex = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
2652                 if (origindex) {
2653                         return origindex;
2654                 }
2655
2656                 DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2657                 origindex = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
2658
2659                 totorig = ccgSubSurf_getNumVerts(ss);
2660                 totnone = dm->numVertData - totorig;
2661
2662                 /* original vertices are at the end */
2663                 for (a = 0; a < totnone; a++)
2664                         origindex[a] = ORIGINDEX_NONE;
2665
2666                 for (index = 0; index < totorig; index++, a++) {
2667                         CCGVert *v = ccgdm->vertMap[index].vert;
2668                         origindex[a] = ccgDM_getVertMapIndex(ccgdm->ss, v);
2669                 }
2670
2671                 return origindex;
2672         }
2673
2674         return DM_get_vert_data_layer(dm, type);
2675 }
2676
2677 static void *ccgDM_get_edge_data_layer(DerivedMesh *dm, int type)
2678 {
2679         if (type == CD_ORIGINDEX) {
2680                 /* create origindex on demand to save memory */
2681                 CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2682                 CCGSubSurf *ss = ccgdm->ss;
2683                 int *origindex;
2684                 int a, i, index, totnone, totorig, totedge;
2685                 int edgeSize = ccgSubSurf_getEdgeSize(ss);
2686
2687                 /* Avoid re-creation if the layer exists already */
2688                 origindex = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
2689                 if (origindex) {
2690                         return origindex;
2691                 }
2692
2693                 DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2694                 origindex = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
2695
2696                 totedge = ccgSubSurf_getNumEdges(ss);
2697                 totorig = totedge * (edgeSize - 1);
2698                 totnone = dm->numEdgeData - totorig;
2699
2700                 /* original edges are at the end */
2701                 for (a = 0; a < totnone; a++)
2702                         origindex[a] = ORIGINDEX_NONE;
2703
2704                 for (index = 0; index < totedge; index++) {
2705                         CCGEdge *e = ccgdm->edgeMap[index].edge;
2706                         int mapIndex = ccgDM_getEdgeMapIndex(ss, e);
2707
2708                         for (i = 0; i < edgeSize - 1; i++, a++)
2709                                 origindex[a] = mapIndex;
2710                 }
2711
2712                 return origindex;
2713         }
2714
2715         return DM_get_edge_data_layer(dm, type);
2716 }
2717
2718 static void *ccgDM_get_tessface_data_layer(DerivedMesh *dm, int type)
2719 {
2720         if (type == CD_ORIGINDEX) {
2721                 /* create origindex on demand to save memory */
2722                 int *origindex;
2723
2724                 /* Avoid re-creation if the layer exists already */
2725                 origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
2726                 if (origindex) {
2727                         return origindex;
2728                 }
2729
2730                 DM_add_tessface_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2731                 origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
2732
2733                 /* silly loop counting up */
2734                 range_vn_i(origindex, dm->getNumTessFaces(dm), 0);
2735
2736                 return origindex;
2737         }
2738
2739         return DM_get_tessface_data_layer(dm, type);
2740 }
2741
2742 static void *ccgDM_get_poly_data_layer(DerivedMesh *dm, int type)
2743 {
2744         if (type == CD_ORIGINDEX) {
2745                 /* create origindex on demand to save memory */
2746                 CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2747                 CCGSubSurf *ss = ccgdm->ss;
2748                 int *origindex;
2749                 int a, i, index, totface;
2750                 int gridFaces = ccgSubSurf_getGridSize(ss) - 1;
2751
2752                 /* Avoid re-creation if the layer exists already */
2753                 origindex = DM_get_poly_data_layer(dm, CD_ORIGINDEX);
2754                 if (origindex) {
2755                         return origindex;
2756                 }
2757
2758                 DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
2759                 origindex = DM_get_poly_data_layer(dm, CD_ORIGINDEX);
2760
2761                 totface = ccgSubSurf_getNumFaces(ss);
2762
2763                 for (a = 0, index = 0; index < totface; index++) {
2764                         CCGFace *f = ccgdm->faceMap[index].face;
2765                         int numVerts = ccgSubSurf_getFaceNumVerts(f);
2766                         int mapIndex = ccgDM_getFaceMapIndex(ss, f);
2767
2768                         for (i = 0; i < gridFaces * gridFaces * numVerts; i++, a++)
2769                                 origindex[a] = mapIndex;
2770                 }
2771
2772                 return origindex;
2773         }
2774
2775         return DM_get_poly_data_layer(dm, type);
2776 }
2777
2778 static void *ccgDM_get_vert_data(DerivedMesh *dm, int index, int type)
2779 {
2780         if (type == CD_ORIGINDEX) {
2781                 /* ensure creation of CD_ORIGINDEX layer */
2782                 ccgDM_get_vert_data_layer(dm, type);
2783         }
2784
2785         return DM_get_vert_data(dm, index, type);
2786 }
2787
2788 static void *ccgDM_get_edge_data(DerivedMesh *dm, int index, int type)
2789 {
2790         if (type == CD_ORIGINDEX) {
2791                 /* ensure creation of CD_ORIGINDEX layer */
2792                 ccgDM_get_edge_data_layer(dm, type);
2793         }
2794
2795         return DM_get_edge_data(dm, index, type);
2796 }
2797
2798 static void *ccgDM_get_tessface_data(DerivedMesh *dm, int index, int type)
2799 {
2800         if (type == CD_ORIGINDEX) {
2801                 /* ensure creation of CD_ORIGINDEX layer */
2802                 ccgDM_get_tessface_data_layer(dm, type);
2803         }
2804
2805         return DM_get_tessface_data(dm, index, type);
2806 }
2807
2808 static void *ccgDM_get_poly_data(DerivedMesh *dm, int index, int type)
2809 {
2810         if (type == CD_ORIGINDEX) {
2811                 /* ensure creation of CD_ORIGINDEX layer */
2812                 ccgDM_get_tessface_data_layer(dm, type);
2813         }
2814
2815         return DM_get_poly_data(dm, index, type);
2816 }
2817
2818 static int ccgDM_getNumGrids(DerivedMesh *dm)
2819 {
2820         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2821         int index, numFaces, numGrids;
2822
2823         numFaces = ccgSubSurf_getNumFaces(ccgdm->ss);
2824         numGrids = 0;
2825
2826         for (index = 0; index < numFaces; index++) {
2827                 CCGFace *f = ccgdm->faceMap[index].face;
2828                 numGrids += ccgSubSurf_getFaceNumVerts(f);
2829         }
2830
2831         return numGrids;
2832 }
2833
2834 static int ccgDM_getGridSize(DerivedMesh *dm)
2835 {
2836         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2837         return ccgSubSurf_getGridSize(ccgdm->ss);
2838 }
2839
2840 static int ccgdm_adjacent_grid(int *gridOffset, CCGFace *f, int S, int offset)
2841 {
2842         CCGFace *adjf;
2843         CCGEdge *e;
2844         int i, j = 0, numFaces, fIndex, numEdges = 0;
2845
2846         e = ccgSubSurf_getFaceEdge(f, S);
2847         numFaces = ccgSubSurf_getEdgeNumFaces(e);
2848
2849         if (numFaces != 2)
2850                 return -1;
2851
2852         for (i = 0; i < numFaces; i++) {
2853                 adjf = ccgSubSurf_getEdgeFace(e, i);
2854
2855                 if (adjf != f) {
2856                         numEdges = ccgSubSurf_getFaceNumVerts(adjf);
2857                         for (j = 0; j < numEdges; j++)
2858                                 if (ccgSubSurf_getFaceEdge(adjf, j) == e)
2859                                         break;
2860
2861                         if (j != numEdges)
2862                                 break;
2863                 }
2864         }
2865
2866         if (numEdges == 0)
2867                 return -1;
2868         
2869         fIndex = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(adjf));
2870
2871         return gridOffset[fIndex] + (j + offset) % numEdges;
2872 }
2873
2874 static void ccgdm_create_grids(DerivedMesh *dm)
2875 {
2876         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
2877         CCGSubSurf *ss = ccgdm->ss;
2878         CCGElem **gridData;
2879         DMGridAdjacency *gridAdjacency, *adj;
2880         DMFlagMat *gridFlagMats;
2881         CCGFace **gridFaces;
2882         int *gridOffset;
2883         int index, numFaces, numGrids, S, gIndex /*, gridSize*/;
2884
2885         if (ccgdm->gridData)
2886                 return;
2887         
2888         numGrids = ccgDM_getNumGrids(dm);
2889         numFaces = ccgSubSurf_getNumFaces(ss);
2890         /*gridSize = ccgDM_getGridSize(dm);*/  /*UNUSED*/
2891
2892         /* compute offset into grid array for each face */
2893         gridOffset = MEM_mallocN(sizeof(int) * numFaces, "ccgdm.gridOffset");
2894
2895         for (gIndex = 0, index = 0; index < numFaces; index++) {
2896                 CCGFace *f = ccgdm->faceMap[index].face;
2897                 int numVerts = ccgSubSurf_getFaceNumVerts(f);
2898
2899                 gridOffset[index] = gIndex;
2900                 gIndex += numVerts;
2901         }
2902
2903         /* compute grid data */
2904         gridData = MEM_mallocN(sizeof(CCGElem *) * numGrids, "ccgdm.gridData");
2905         gridAdjacency = MEM_mallocN(sizeof(DMGridAdjacency) * numGrids, "ccgdm.gridAdjacency");
2906         gridFaces = MEM_mallocN(sizeof(CCGFace *) * numGrids, "ccgdm.gridFaces");
2907         gridFlagMats = MEM_mallocN(sizeof(DMFlagMat) * numGrids, "ccgdm.gridFlagMats");
2908
2909         ccgdm->gridHidden = MEM_callocN(sizeof(BLI_bitmap) * numGrids, "ccgdm.gridHidden");
2910
2911         for (gIndex = 0, index = 0; index < numFaces; index++) {
2912                 CCGFace *f = ccgdm->faceMap[index].face;
2913                 int numVerts = ccgSubSurf_getFaceNumVerts(f);
2914
2915                 for (S = 0; S < numVerts; S++, gIndex++) {
2916                         int prevS = (S - 1 + numVerts) % numVerts;
2917                         int nextS = (S + 1 + numVerts) % numVerts;
2918
2919                         gridData[gIndex] = ccgSubSurf_getFaceGridDataArray(ss, f, S);
2920                         gridFaces[gIndex] = f;
2921                         gridFlagMats[gIndex] = ccgdm->faceFlags[index];
2922
2923                         adj = &gridAdjacency[gIndex];
2924
2925                         adj->index[0] = gIndex - S + nextS;
2926                         adj->rotation[0] = 3;
2927                         adj->index[1] = ccgdm_adjacent_grid(gridOffset, f, prevS, 0);
2928                         adj->rotation[1] = 1;
2929                         adj->index[2] = ccgdm_adjacent_grid(gridOffset, f, S, 1);
2930                         adj->rotation[2] = 3;
2931                         adj->index[3] = gIndex - S + prevS;
2932                         adj->rotation[3] = 1;
2933                 }
2934         }
2935
2936         ccgdm->gridData = gridData;
2937         ccgdm->gridFaces = gridFaces;