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