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