78a8b975b854ed0388a02baae632bbc3887a0703
[blender.git] / source / blender / blenkernel / intern / cdderivedmesh.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) 2006 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Ben Batt <benbatt@gmail.com>
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  *
27  * Implementation of CDDerivedMesh.
28  *
29  * BKE_cdderivedmesh.h contains the function prototypes for this file.
30  *
31  */
32
33 /** \file blender/blenkernel/intern/cdderivedmesh.c
34  *  \ingroup bke
35  */
36
37 #include "GL/glew.h"
38
39 #include "BLI_math.h"
40 #include "BLI_blenlib.h"
41 #include "BLI_edgehash.h"
42 #include "BLI_math.h"
43 #include "BLI_pbvh.h"
44 #include "BLI_array.h"
45 #include "BLI_smallhash.h"
46 #include "BLI_utildefines.h"
47 #include "BLI_scanfill.h"
48
49 #include "BKE_cdderivedmesh.h"
50 #include "BKE_global.h"
51 #include "BKE_mesh.h"
52 #include "BKE_paint.h"
53 #include "BKE_utildefines.h"
54 #include "BKE_tessmesh.h"
55
56 #include "DNA_mesh_types.h"
57 #include "DNA_meshdata_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_curve_types.h" /* for Curve */
60
61 #include "MEM_guardedalloc.h"
62
63 #include "GPU_buffers.h"
64 #include "GPU_draw.h"
65 #include "GPU_extensions.h"
66 #include "GPU_material.h"
67
68 #include <string.h>
69 #include <limits.h>
70 #include <math.h>
71
72 typedef struct {
73         DerivedMesh dm;
74
75         /* these point to data in the DerivedMesh custom data layers,
76          * they are only here for efficiency and convenience **/
77         MVert *mvert;
78         MEdge *medge;
79         MFace *mface;
80         MLoop *mloop;
81         MPoly *mpoly;
82
83         /* Cached */
84         struct PBVH *pbvh;
85         int pbvh_draw;
86
87         /* Mesh connectivity */
88         MeshElemMap *pmap;
89         int *pmap_mem;
90 } CDDerivedMesh;
91
92 /**************** DerivedMesh interface functions ****************/
93 static int cdDM_getNumVerts(DerivedMesh *dm)
94 {
95         return dm->numVertData;
96 }
97
98 static int cdDM_getNumEdges(DerivedMesh *dm)
99 {
100         return dm->numEdgeData;
101 }
102
103 static int cdDM_getNumTessFaces(DerivedMesh *dm)
104 {
105         /* uncomment and add a breakpoint on the printf()
106          * to help debug tessfaces issues since BMESH merge. */
107 #if 0
108         if (dm->numTessFaceData == 0 && dm->numPolyData != 0) {
109                 printf("%s: has no faces!, call DM_ensure_tessface() if you need them\n");
110         }
111 #endif
112         return dm->numTessFaceData;
113 }
114
115 static int cdDM_getNumLoops(DerivedMesh *dm)
116 {
117         return dm->numLoopData;
118 }
119
120 static int cdDM_getNumPolys(DerivedMesh *dm)
121 {
122         return dm->numPolyData;
123 }
124
125 static void cdDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
126 {
127         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
128         *vert_r = cddm->mvert[index];
129 }
130
131 static void cdDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
132 {
133         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
134         *edge_r = cddm->medge[index];
135 }
136
137 static void cdDM_getTessFace(DerivedMesh *dm, int index, MFace *face_r)
138 {
139         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
140         *face_r = cddm->mface[index];
141 }
142
143 static void cdDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
144 {
145         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
146         memcpy(vert_r, cddm->mvert, sizeof(*vert_r) * dm->numVertData);
147 }
148
149 static void cdDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
150 {
151         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
152         memcpy(edge_r, cddm->medge, sizeof(*edge_r) * dm->numEdgeData);
153 }
154
155 static void cdDM_copyTessFaceArray(DerivedMesh *dm, MFace *face_r)
156 {
157         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
158         memcpy(face_r, cddm->mface, sizeof(*face_r) * dm->numTessFaceData);
159 }
160
161 static void cdDM_copyLoopArray(DerivedMesh *dm, MLoop *loop_r)
162 {
163         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
164         memcpy(loop_r, cddm->mloop, sizeof(*loop_r) * dm->numLoopData);
165 }
166
167 static void cdDM_copyPolyArray(DerivedMesh *dm, MPoly *poly_r)
168 {
169         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
170         memcpy(poly_r, cddm->mpoly, sizeof(*poly_r) * dm->numPolyData);
171 }
172
173 static void cdDM_getMinMax(DerivedMesh *dm, float min_r[3], float max_r[3])
174 {
175         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
176         int i;
177
178         if (dm->numVertData) {
179                 for (i = 0; i < dm->numVertData; i++) {
180                         DO_MINMAX(cddm->mvert[i].co, min_r, max_r);
181                 }
182         }
183         else {
184                 zero_v3(min_r);
185                 zero_v3(max_r);
186         }
187 }
188
189 static void cdDM_getVertCo(DerivedMesh *dm, int index, float co_r[3])
190 {
191         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
192
193         copy_v3_v3(co_r, cddm->mvert[index].co);
194 }
195
196 static void cdDM_getVertCos(DerivedMesh *dm, float (*cos_r)[3])
197 {
198         MVert *mv = CDDM_get_verts(dm);
199         int i;
200
201         for (i = 0; i < dm->numVertData; i++, mv++)
202                 copy_v3_v3(cos_r[i], mv->co);
203 }
204
205 static void cdDM_getVertNo(DerivedMesh *dm, int index, float no_r[3])
206 {
207         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
208         normal_short_to_float_v3(no_r, cddm->mvert[index].no);
209 }
210
211 static const MeshElemMap *cdDM_getPolyMap(Object *ob, DerivedMesh *dm)
212 {
213         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
214
215         if (!cddm->pmap && ob->type == OB_MESH) {
216                 Mesh *me= ob->data;
217
218                 create_vert_poly_map(&cddm->pmap, &cddm->pmap_mem,
219                                      me->mpoly, me->mloop,
220                                      me->totvert, me->totpoly, me->totloop);
221         }
222
223         return cddm->pmap;
224 }
225
226 static int can_pbvh_draw(Object *ob, DerivedMesh *dm)
227 {
228         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
229         Mesh *me = ob->data;
230         int deformed = 0;
231
232         /* active modifiers means extra deformation, which can't be handled correct
233          * on birth of PBVH and sculpt "layer" levels, so use PBVH only for internal brush
234          * stuff and show final DerivedMesh so user would see actual object shape */
235         deformed |= ob->sculpt->modifiers_active;
236
237         /* as in case with modifiers, we can't synchronize deformation made against
238          * PBVH and non-locked keyblock, so also use PBVH only for brushes and
239          * final DM to give final result to user */
240         deformed |= ob->sculpt->kb && (ob->shapeflag & OB_SHAPE_LOCK) == 0;
241
242         if (deformed)
243                 return 0;
244
245         return cddm->mvert == me->mvert || ob->sculpt->kb;
246 }
247
248 static struct PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm)
249 {
250         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
251
252         if (!ob) {
253                 cddm->pbvh= NULL;
254                 return NULL;
255         }
256
257         if (!ob->sculpt)
258                 return NULL;
259
260         if (ob->sculpt->pbvh) {
261                 cddm->pbvh= ob->sculpt->pbvh;
262                 cddm->pbvh_draw = can_pbvh_draw(ob, dm);
263         }
264
265         /* always build pbvh from original mesh, and only use it for drawing if
266          * this derivedmesh is just original mesh. it's the multires subsurf dm
267          * that this is actually for, to support a pbvh on a modified mesh */
268         if (!cddm->pbvh && ob->type == OB_MESH) {
269                 SculptSession *ss = ob->sculpt;
270                 Mesh *me = ob->data;
271                 int deformed = 0;
272
273                 cddm->pbvh = BLI_pbvh_new();
274                 cddm->pbvh_draw = can_pbvh_draw(ob, dm);
275
276                 BKE_mesh_tessface_ensure(me);
277                 
278                 BLI_pbvh_build_mesh(cddm->pbvh, me->mface, me->mvert,
279                                     me->totface, me->totvert);
280
281                 deformed = ss->modifiers_active || me->key;
282
283                 if (deformed && ob->derivedDeform) {
284                         DerivedMesh *deformdm = ob->derivedDeform;
285                         float (*vertCos)[3];
286                         int totvert;
287
288                         totvert = deformdm->getNumVerts(deformdm);
289                         vertCos = MEM_callocN(3*totvert*sizeof(float), "cdDM_getPBVH vertCos");
290                         deformdm->getVertCos(deformdm, vertCos);
291                         BLI_pbvh_apply_vertCos(cddm->pbvh, vertCos);
292                         MEM_freeN(vertCos);
293                 }
294         }
295
296         return cddm->pbvh;
297 }
298
299 /* update vertex normals so that drawing smooth faces works during sculpt
300  * TODO: proper fix is to support the pbvh in all drawing modes */
301 static void cdDM_update_normals_from_pbvh(DerivedMesh *dm)
302 {
303         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
304         float (*face_nors)[3];
305
306         if (!cddm->pbvh || !cddm->pbvh_draw || !dm->numTessFaceData)
307                 return;
308
309         face_nors = CustomData_get_layer(&dm->faceData, CD_NORMAL);
310
311         BLI_pbvh_update(cddm->pbvh, PBVH_UpdateNormals, face_nors);
312 }
313
314 static void cdDM_drawVerts(DerivedMesh *dm)
315 {
316         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
317         MVert *mv = cddm->mvert;
318         int i;
319
320         if (GPU_buffer_legacy(dm)) {
321                 glBegin(GL_POINTS);
322                 for (i = 0; i < dm->numVertData; i++, mv++)
323                         glVertex3fv(mv->co);
324                 glEnd();
325         }
326         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
327                 GPU_vertex_setup(dm);
328                 if (!GPU_buffer_legacy(dm)) {
329                         if (dm->drawObject->tot_triangle_point)
330                                 glDrawArrays(GL_POINTS, 0, dm->drawObject->tot_triangle_point);
331                         else
332                                 glDrawArrays(GL_POINTS, 0, dm->drawObject->tot_loose_point);
333                 }
334                 GPU_buffer_unbind();
335         }
336 }
337
338 static void cdDM_drawUVEdges(DerivedMesh *dm)
339 {
340         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
341         MFace *mf = cddm->mface;
342         MTFace *tf = DM_get_tessface_data_layer(dm, CD_MTFACE);
343         int i;
344
345         if (mf) {
346                 if (GPU_buffer_legacy(dm)) {
347                         glBegin(GL_LINES);
348                         for (i = 0; i < dm->numTessFaceData; i++, mf++, tf++) {
349                                 if (!(mf->flag&ME_HIDE)) {
350                                         glVertex2fv(tf->uv[0]);
351                                         glVertex2fv(tf->uv[1]);
352
353                                         glVertex2fv(tf->uv[1]);
354                                         glVertex2fv(tf->uv[2]);
355
356                                         if (!mf->v4) {
357                                                 glVertex2fv(tf->uv[2]);
358                                                 glVertex2fv(tf->uv[0]);
359                                         }
360                                         else {
361                                                 glVertex2fv(tf->uv[2]);
362                                                 glVertex2fv(tf->uv[3]);
363
364                                                 glVertex2fv(tf->uv[3]);
365                                                 glVertex2fv(tf->uv[0]);
366                                         }
367                                 }
368                         }
369                         glEnd();
370                 }
371                 else {
372                         int prevstart = 0;
373                         int prevdraw = 1;
374                         int draw = 1;
375                         int curpos = 0;
376
377                         GPU_uvedge_setup(dm);
378                         if (!GPU_buffer_legacy(dm)) {
379                                 for (i = 0; i < dm->numTessFaceData; i++, mf++) {
380                                         if (!(mf->flag&ME_HIDE)) {
381                                                 draw = 1;
382                                         } 
383                                         else {
384                                                 draw = 0;
385                                         }
386                                         if ( prevdraw != draw ) {
387                                                 if ( prevdraw > 0 && (curpos-prevstart) > 0) {
388                                                         glDrawArrays(GL_LINES, prevstart, curpos-prevstart);
389                                                 }
390                                                 prevstart = curpos;
391                                         }
392                                         if ( mf->v4 ) {
393                                                 curpos += 8;
394                                         }
395                                         else {
396                                                 curpos += 6;
397                                         }
398                                         prevdraw = draw;
399                                 }
400                                 if ( prevdraw > 0 && (curpos-prevstart) > 0 ) {
401                                         glDrawArrays(GL_LINES, prevstart, curpos-prevstart);
402                                 }
403                         }
404                         GPU_buffer_unbind();
405                 }
406         }
407 }
408
409 static void cdDM_drawEdges(DerivedMesh *dm, int drawLooseEdges, int drawAllEdges)
410 {
411         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
412         MVert *mvert = cddm->mvert;
413         MEdge *medge = cddm->medge;
414         int i;
415         
416         if (GPU_buffer_legacy(dm)) {
417                 DEBUG_VBO("Using legacy code. cdDM_drawEdges\n");
418                 glBegin(GL_LINES);
419                 for (i = 0; i < dm->numEdgeData; i++, medge++) {
420                         if ((drawAllEdges || (medge->flag & ME_EDGEDRAW)) &&
421                             (drawLooseEdges || !(medge->flag & ME_LOOSEEDGE)))
422                         {
423                                 glVertex3fv(mvert[medge->v1].co);
424                                 glVertex3fv(mvert[medge->v2].co);
425                         }
426                 }
427                 glEnd();
428         }
429         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
430                 int prevstart = 0;
431                 int prevdraw = 1;
432                 int draw = TRUE;
433
434                 GPU_edge_setup(dm);
435                 if (!GPU_buffer_legacy(dm)) {
436                         for (i = 0; i < dm->numEdgeData; i++, medge++) {
437                                 if ((drawAllEdges || (medge->flag & ME_EDGEDRAW)) &&
438                                     (drawLooseEdges || !(medge->flag & ME_LOOSEEDGE)))
439                                 {
440                                         draw = TRUE;
441                                 } 
442                                 else {
443                                         draw = FALSE;
444                                 }
445                                 if ( prevdraw != draw ) {
446                                         if ( prevdraw > 0 && (i-prevstart) > 0 ) {
447                                                 GPU_buffer_draw_elements(dm->drawObject->edges, GL_LINES, prevstart * 2, (i - prevstart) * 2);
448                                         }
449                                         prevstart = i;
450                                 }
451                                 prevdraw = draw;
452                         }
453                         if ( prevdraw > 0 && (i-prevstart) > 0 ) {
454                                 GPU_buffer_draw_elements(dm->drawObject->edges, GL_LINES, prevstart * 2, (i-prevstart) * 2);
455                         }
456                 }
457                 GPU_buffer_unbind();
458         }
459 }
460
461 static void cdDM_drawLooseEdges(DerivedMesh *dm)
462 {
463         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
464         MVert *mvert = cddm->mvert;
465         MEdge *medge = cddm->medge;
466         int i;
467
468         if (GPU_buffer_legacy(dm)) {
469                 DEBUG_VBO("Using legacy code. cdDM_drawLooseEdges\n");
470                 glBegin(GL_LINES);
471                 for (i = 0; i < dm->numEdgeData; i++, medge++) {
472                         if (medge->flag&ME_LOOSEEDGE) {
473                                 glVertex3fv(mvert[medge->v1].co);
474                                 glVertex3fv(mvert[medge->v2].co);
475                         }
476                 }
477                 glEnd();
478         }
479         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
480                 int prevstart = 0;
481                 int prevdraw = 1;
482                 int draw = 1;
483
484                 GPU_edge_setup(dm);
485                 if (!GPU_buffer_legacy(dm)) {
486                         for (i = 0; i < dm->numEdgeData; i++, medge++) {
487                                 if (medge->flag&ME_LOOSEEDGE) {
488                                         draw = 1;
489                                 } 
490                                 else {
491                                         draw = 0;
492                                 }
493                                 if ( prevdraw != draw ) {
494                                         if ( prevdraw > 0 && (i-prevstart) > 0) {
495                                                 GPU_buffer_draw_elements(dm->drawObject->edges, GL_LINES, prevstart * 2, (i - prevstart) * 2);
496                                         }
497                                         prevstart = i;
498                                 }
499                                 prevdraw = draw;
500                         }
501                         if ( prevdraw > 0 && (i-prevstart) > 0 ) {
502                                 GPU_buffer_draw_elements(dm->drawObject->edges, GL_LINES, prevstart * 2, (i - prevstart) * 2);
503                         }
504                 }
505                 GPU_buffer_unbind();
506         }
507 }
508
509 static void cdDM_drawFacesSolid(DerivedMesh *dm,
510                                 float (*partial_redraw_planes)[4],
511                                 int UNUSED(fast), DMSetMaterial setMaterial)
512 {
513         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
514         MVert *mvert = cddm->mvert;
515         MFace *mface = cddm->mface;
516         float *nors= dm->getTessFaceDataArray(dm, CD_NORMAL);
517         int a, glmode = -1, shademodel = -1, matnr = -1, drawCurrentMat = 1;
518
519 #define PASSVERT(index) {                                               \
520         if (shademodel == GL_SMOOTH) {                          \
521                 short *no = mvert[index].no;                    \
522                 glNormal3sv(no);                                                \
523         }                                                                                       \
524         glVertex3fv(mvert[index].co);   \
525 }
526
527         if (cddm->pbvh && cddm->pbvh_draw) {
528                 if (dm->numTessFaceData) {
529                         float (*face_nors)[3] = CustomData_get_layer(&dm->faceData, CD_NORMAL);
530
531                         BLI_pbvh_draw(cddm->pbvh, partial_redraw_planes, face_nors, setMaterial);
532                         glShadeModel(GL_FLAT);
533                 }
534
535                 return;
536         }
537
538         if (GPU_buffer_legacy(dm)) {
539                 DEBUG_VBO("Using legacy code. cdDM_drawFacesSolid\n");
540                 glBegin(glmode = GL_QUADS);
541                 for (a = 0; a < dm->numTessFaceData; a++, mface++) {
542                         int new_glmode, new_matnr, new_shademodel;
543
544                         new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
545                         new_matnr = mface->mat_nr + 1;
546                         new_shademodel = (mface->flag & ME_SMOOTH)?GL_SMOOTH:GL_FLAT;
547                         
548                         if (new_glmode != glmode || new_matnr != matnr || new_shademodel != shademodel) {
549                                 glEnd();
550
551                                 drawCurrentMat = setMaterial(matnr = new_matnr, NULL);
552
553                                 glShadeModel(shademodel = new_shademodel);
554                                 glBegin(glmode = new_glmode);
555                         } 
556                         
557                         if (drawCurrentMat) {
558                                 if (shademodel == GL_FLAT) {
559                                         if (nors) {
560                                                 glNormal3fv(nors);
561                                         }
562                                         else {
563                                                 /* TODO make this better (cache facenormals as layer?) */
564                                                 float nor[3];
565                                                 if (mface->v4) {
566                                                         normal_quad_v3(nor, mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co);
567                                                 }
568                                                 else {
569                                                         normal_tri_v3(nor, mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co);
570                                                 }
571                                                 glNormal3fv(nor);
572                                         }
573                                 }
574
575                                 PASSVERT(mface->v1);
576                                 PASSVERT(mface->v2);
577                                 PASSVERT(mface->v3);
578                                 if (mface->v4) {
579                                         PASSVERT(mface->v4);
580                                 }
581                         }
582
583                         if (nors) nors += 3;
584                 }
585                 glEnd();
586         }
587         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
588                 GPU_vertex_setup(dm);
589                 GPU_normal_setup(dm);
590                 if (!GPU_buffer_legacy(dm)) {
591                         glShadeModel(GL_SMOOTH);
592                         for (a = 0; a < dm->drawObject->totmaterial; a++) {
593                                 if (setMaterial(dm->drawObject->materials[a].mat_nr + 1, NULL)) {
594                                         glDrawArrays(GL_TRIANGLES, dm->drawObject->materials[a].start,
595                                                      dm->drawObject->materials[a].totpoint);
596                                 }
597                         }
598                 }
599                 GPU_buffer_unbind();
600         }
601
602 #undef PASSVERT
603         glShadeModel(GL_FLAT);
604 }
605
606 static void cdDM_drawFacesTex_common(DerivedMesh *dm,
607                            DMSetDrawOptionsTex drawParams,
608                            DMSetDrawOptions drawParamsMapped,
609                            DMCompareDrawOptions compareDrawOptions,
610                            void *userData) 
611 {
612         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
613         MVert *mv = cddm->mvert;
614         MFace *mf = DM_get_tessface_data_layer(dm, CD_MFACE);
615         MCol *realcol = dm->getTessFaceDataArray(dm, CD_TEXTURE_MCOL);
616         float *nors= dm->getTessFaceDataArray(dm, CD_NORMAL);
617         MTFace *tf = DM_get_tessface_data_layer(dm, CD_MTFACE);
618         int i, j, orig, *index = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
619         int startFace = 0 /*, lastFlag = 0xdeadbeef */ /* UNUSED */;
620         MCol *mcol = dm->getTessFaceDataArray(dm, CD_PREVIEW_MCOL);
621         if (!mcol)
622                 mcol = dm->getTessFaceDataArray(dm, CD_MCOL);
623
624         cdDM_update_normals_from_pbvh(dm);
625
626         if (GPU_buffer_legacy(dm)) {
627                 DEBUG_VBO("Using legacy code. cdDM_drawFacesTex_common\n");
628                 for (i = 0; i < dm->numTessFaceData; i++, mf++) {
629                         MVert *mvert;
630                         DMDrawOption draw_option;
631                         unsigned char *cp = NULL;
632
633                         if (drawParams) {
634                                 draw_option = drawParams(tf? &tf[i]: NULL, (mcol != NULL), mf->mat_nr);
635                         }
636                         else {
637                                 if (index) {
638                                         orig = *index++;
639                                         if (orig == ORIGINDEX_NONE)             { if (nors) nors += 3; continue; }
640                                         if (drawParamsMapped) draw_option = drawParamsMapped(userData, orig);
641                                         else    { if (nors) nors += 3; continue; }
642                                 }
643                                 else
644                                         if (drawParamsMapped) draw_option = drawParamsMapped(userData, i);
645                                         else    { if (nors) nors += 3; continue; }
646                         }
647                         
648                         if (draw_option != DM_DRAW_OPTION_SKIP) {
649                                 if (draw_option != DM_DRAW_OPTION_NO_MCOL && mcol)
650                                         cp = (unsigned char*) &mcol[i*4];
651
652                                 if (!(mf->flag&ME_SMOOTH)) {
653                                         if (nors) {
654                                                 glNormal3fv(nors);
655                                         }
656                                         else {
657                                                 float nor[3];
658                                                 if (mf->v4) {
659                                                         normal_quad_v3(nor, mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co, mv[mf->v4].co);
660                                                 }
661                                                 else {
662                                                         normal_tri_v3(nor, mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co);
663                                                 }
664                                                 glNormal3fv(nor);
665                                         }
666                                 }
667
668                                 glBegin(mf->v4?GL_QUADS:GL_TRIANGLES);
669                                 if (tf) glTexCoord2fv(tf[i].uv[0]);
670                                 if (cp) glColor3ub(cp[3], cp[2], cp[1]);
671                                 mvert = &mv[mf->v1];
672                                 if (mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
673                                 glVertex3fv(mvert->co);
674                                         
675                                 if (tf) glTexCoord2fv(tf[i].uv[1]);
676                                 if (cp) glColor3ub(cp[7], cp[6], cp[5]);
677                                 mvert = &mv[mf->v2];
678                                 if (mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
679                                 glVertex3fv(mvert->co);
680
681                                 if (tf) glTexCoord2fv(tf[i].uv[2]);
682                                 if (cp) glColor3ub(cp[11], cp[10], cp[9]);
683                                 mvert = &mv[mf->v3];
684                                 if (mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
685                                 glVertex3fv(mvert->co);
686
687                                 if (mf->v4) {
688                                         if (tf) glTexCoord2fv(tf[i].uv[3]);
689                                         if (cp) glColor3ub(cp[15], cp[14], cp[13]);
690                                         mvert = &mv[mf->v4];
691                                         if (mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
692                                         glVertex3fv(mvert->co);
693                                 }
694                                 glEnd();
695                         }
696                         
697                         if (nors) nors += 3;
698                 }
699         }
700         else { /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
701                 MCol *col = realcol;
702                 if (!col)
703                         col = mcol;
704
705                 GPU_vertex_setup(dm);
706                 GPU_normal_setup(dm);
707                 GPU_uv_setup(dm);
708                 if ( col != NULL ) {
709 #if 0
710                         if (realcol && dm->drawObject->colType == CD_TEXTURE_MCOL) {
711                                 col = 0;
712                         }
713                         else if (mcol && dm->drawObject->colType == CD_MCOL) {
714                                 col = 0;
715                         }
716                         
717                         if (col != 0)
718 #endif
719                         {
720                                 unsigned char *colors = MEM_mallocN(dm->getNumTessFaces(dm)*4*3*sizeof(unsigned char), "cdDM_drawFacesTex_common");
721                                 for (i = 0; i < dm->getNumTessFaces(dm); i++) {
722                                         for (j = 0; j < 4; j++) {
723                                                 /* bgr -> rgb is intentional (and stupid), but how its stored internally */
724                                                 colors[i*12+j*3] = col[i*4+j].b;
725                                                 colors[i*12+j*3+1] = col[i*4+j].g;
726                                                 colors[i*12+j*3+2] = col[i*4+j].r;
727                                         }
728                                 }
729                                 GPU_color3_upload(dm, colors);
730                                 MEM_freeN(colors);
731                                 if (realcol)
732                                         dm->drawObject->colType = CD_TEXTURE_MCOL;
733                                 else if (mcol)
734                                         dm->drawObject->colType = CD_MCOL;
735                         }
736                         GPU_color_setup(dm);
737                 }
738
739                 if (!GPU_buffer_legacy(dm)) {
740                         int tottri = dm->drawObject->tot_triangle_point/3;
741                         int next_actualFace = dm->drawObject->triangle_to_mface[0];
742
743                         glShadeModel(GL_SMOOTH);
744                         /* lastFlag = 0; */ /* UNUSED */
745                         for (i = 0; i < tottri; i++) {
746                                 int actualFace = next_actualFace;
747                                 DMDrawOption draw_option = DM_DRAW_OPTION_NORMAL;
748                                 int flush = 0;
749
750                                 if (i != tottri-1)
751                                         next_actualFace= dm->drawObject->triangle_to_mface[i+1];
752
753                                 if (drawParams) {
754                                         draw_option = drawParams(tf? &tf[actualFace]: NULL, (mcol != NULL), mf[actualFace].mat_nr);
755                                 }
756                                 else {
757                                         if (index) {
758                                                 orig = index[actualFace];
759                                                 if (orig == ORIGINDEX_NONE) continue;
760                                                 if (drawParamsMapped)
761                                                         draw_option = drawParamsMapped(userData, orig);
762                                         }
763                                         else
764                                                 if (drawParamsMapped)
765                                                         draw_option = drawParamsMapped(userData, actualFace);
766                                 }
767
768                                 /* flush buffer if current triangle isn't drawable or it's last triangle */
769                                 flush = (draw_option == DM_DRAW_OPTION_SKIP) || (i == tottri - 1);
770
771                                 if (!flush && compareDrawOptions) {
772                                         /* also compare draw options and flush buffer if they're different
773                                          * need for face selection highlight in edit mode */
774                                         flush|= compareDrawOptions(userData, actualFace, next_actualFace) == 0;
775                                 }
776
777                                 if (flush) {
778                                         int first = startFace*3;
779                                         /* Add one to the length if we're drawing at the end of the array */
780                                         int count = (i-startFace+(draw_option != DM_DRAW_OPTION_SKIP ? 1 : 0))*3;
781
782                                         if (count) {
783                                                 if (col)
784                                                         GPU_color_switch(1);
785                                                 else
786                                                         GPU_color_switch(0);
787
788                                                 glDrawArrays(GL_TRIANGLES, first, count);
789                                         }
790
791                                         startFace = i + 1;
792                                 }
793                         }
794                 }
795
796                 GPU_buffer_unbind();
797                 glShadeModel(GL_FLAT);
798         }
799 }
800
801 static void cdDM_drawFacesTex(DerivedMesh *dm,
802                            DMSetDrawOptionsTex setDrawOptions,
803                            DMCompareDrawOptions compareDrawOptions,
804                            void *userData)
805 {
806         cdDM_drawFacesTex_common(dm, setDrawOptions, NULL, compareDrawOptions, userData);
807 }
808
809 static void cdDM_drawMappedFaces(DerivedMesh *dm,
810                         DMSetDrawOptions setDrawOptions,
811                         DMSetMaterial setMaterial,
812                         DMCompareDrawOptions compareDrawOptions,
813                         void *userData, DMDrawFlag flag)
814 {
815         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
816         MVert *mv = cddm->mvert;
817         MFace *mf = cddm->mface;
818         MCol *mc;
819         float *nors= DM_get_tessface_data_layer(dm, CD_NORMAL);
820         int useColors = flag & DM_DRAW_USE_COLORS;
821         int i, orig, *index = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
822
823         mc = DM_get_tessface_data_layer(dm, CD_ID_MCOL);
824         if (!mc)
825                 mc = DM_get_tessface_data_layer(dm, CD_PREVIEW_MCOL);
826         if (!mc)
827                 mc = DM_get_tessface_data_layer(dm, CD_MCOL);
828
829         cdDM_update_normals_from_pbvh(dm);
830
831         /* back-buffer always uses legacy since VBO's would need the
832          * color array temporarily overwritten for drawing, then reset. */
833         if (GPU_buffer_legacy(dm) || G.f & G_BACKBUFSEL) {
834                 DEBUG_VBO("Using legacy code. cdDM_drawMappedFaces\n");
835                 for (i = 0; i < dm->numTessFaceData; i++, mf++) {
836                         int drawSmooth = (flag & DM_DRAW_ALWAYS_SMOOTH) ? 1 : (mf->flag & ME_SMOOTH);
837                         DMDrawOption draw_option = DM_DRAW_OPTION_NORMAL;
838
839                         orig = (index==NULL) ? i : *index++;
840                         
841                         if (orig == ORIGINDEX_NONE)
842                                 draw_option= setMaterial(mf->mat_nr + 1, NULL);
843                         else if (setDrawOptions != NULL)
844                                 draw_option= setDrawOptions(userData, orig);
845
846                         if (draw_option != DM_DRAW_OPTION_SKIP) {
847                                 unsigned char *cp = NULL;
848
849                                 if (useColors && mc)
850                                         cp = (unsigned char *)&mc[i * 4];
851
852                                 /* no need to set shading mode to flat because
853                                  *  normals are already used to change shading */
854                                 glShadeModel(GL_SMOOTH);
855                                 glBegin(mf->v4?GL_QUADS:GL_TRIANGLES);
856
857                                 if (!drawSmooth) {
858                                         if (nors) {
859                                                 glNormal3fv(nors);
860                                         }
861                                         else {
862                                                 float nor[3];
863                                                 if (mf->v4) {
864                                                         normal_quad_v3(nor, mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co, mv[mf->v4].co);
865                                                 }
866                                                 else {
867                                                         normal_tri_v3(nor, mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co);
868                                                 }
869                                                 glNormal3fv(nor);
870                                         }
871
872                                         if (cp) glColor3ub(cp[3], cp[2], cp[1]);
873                                         glVertex3fv(mv[mf->v1].co);
874                                         if (cp) glColor3ub(cp[7], cp[6], cp[5]);
875                                         glVertex3fv(mv[mf->v2].co);
876                                         if (cp) glColor3ub(cp[11], cp[10], cp[9]);
877                                         glVertex3fv(mv[mf->v3].co);
878                                         if (mf->v4) {
879                                                 if (cp) glColor3ub(cp[15], cp[14], cp[13]);
880                                                 glVertex3fv(mv[mf->v4].co);
881                                         }
882                                 }
883                                 else {
884                                         if (cp) glColor3ub(cp[3], cp[2], cp[1]);
885                                         glNormal3sv(mv[mf->v1].no);
886                                         glVertex3fv(mv[mf->v1].co);
887                                         if (cp) glColor3ub(cp[7], cp[6], cp[5]);
888                                         glNormal3sv(mv[mf->v2].no);
889                                         glVertex3fv(mv[mf->v2].co);
890                                         if (cp) glColor3ub(cp[11], cp[10], cp[9]);
891                                         glNormal3sv(mv[mf->v3].no);
892                                         glVertex3fv(mv[mf->v3].co);
893                                         if (mf->v4) {
894                                                 if (cp) glColor3ub(cp[15], cp[14], cp[13]);
895                                                 glNormal3sv(mv[mf->v4].no);
896                                                 glVertex3fv(mv[mf->v4].co);
897                                         }
898                                 }
899
900                                 glEnd();
901                         }
902                         
903                         if (nors) nors += 3;
904                 }
905         }
906         else { /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
907                 int prevstart = 0;
908                 GPU_vertex_setup(dm);
909                 GPU_normal_setup(dm);
910                 if ( useColors && mc )
911                         GPU_color_setup(dm);
912                 if (!GPU_buffer_legacy(dm)) {
913                         int tottri = dm->drawObject->tot_triangle_point/3;
914                         glShadeModel(GL_SMOOTH);
915                         
916                         if (tottri == 0) {
917                                 /* avoid buffer problems in following code */
918                         }
919                         if (setDrawOptions == NULL) {
920                                 /* just draw the entire face array */
921                                 glDrawArrays(GL_TRIANGLES, 0, (tottri) * 3);
922                         }
923                         else {
924                                 /* we need to check if the next material changes */
925                                 int next_actualFace = dm->drawObject->triangle_to_mface[0];
926                                 
927                                 for (i = 0; i < tottri; i++) {
928                                         //int actualFace = dm->drawObject->triangle_to_mface[i];
929                                         int actualFace = next_actualFace;
930                                         MFace *mface = mf + actualFace;
931                                         /*int drawSmooth= (flag & DM_DRAW_ALWAYS_SMOOTH) ? 1 : (mface->flag & ME_SMOOTH);*/ /* UNUSED */
932                                         DMDrawOption draw_option = DM_DRAW_OPTION_NORMAL;
933                                         int flush = 0;
934
935                                         if (i != tottri-1)
936                                                 next_actualFace= dm->drawObject->triangle_to_mface[i+1];
937
938                                         orig = (index==NULL) ? actualFace : index[actualFace];
939
940                                         if (orig == ORIGINDEX_NONE)
941                                                 draw_option= setMaterial(mface->mat_nr + 1, NULL);
942                                         else if (setDrawOptions != NULL)
943                                                 draw_option= setDrawOptions(userData, orig);
944         
945                                         /* Goal is to draw as long of a contiguous triangle
946                                          * array as possible, so draw when we hit either an
947                                          * invisible triangle or at the end of the array */
948
949                                         /* flush buffer if current triangle isn't drawable or it's last triangle... */
950                                         flush = (draw_option == DM_DRAW_OPTION_SKIP) || (i == tottri - 1);
951
952                                         /* ... or when material setting is dissferent  */
953                                         flush |= mf[actualFace].mat_nr != mf[next_actualFace].mat_nr;
954
955                                         if (!flush && compareDrawOptions) {
956                                                 flush |= compareDrawOptions(userData, actualFace, next_actualFace) == 0;
957                                         }
958
959                                         if (flush) {
960                                                 int first = prevstart*3;
961                                                 /* Add one to the length if we're drawing at the end of the array */
962                                                 int count = (i-prevstart+(draw_option != DM_DRAW_OPTION_SKIP ? 1 : 0))*3;
963
964                                                 if (count)
965                                                         glDrawArrays(GL_TRIANGLES, first, count);
966
967                                                 prevstart = i + 1;
968                                         }
969                                 }
970                         }
971
972                         glShadeModel(GL_FLAT);
973                 }
974                 GPU_buffer_unbind();
975         }
976 }
977
978 static void cdDM_drawMappedFacesTex(DerivedMesh *dm,
979                            DMSetDrawOptions setDrawOptions,
980                            DMCompareDrawOptions compareDrawOptions,
981                            void *userData)
982 {
983         cdDM_drawFacesTex_common(dm, NULL, setDrawOptions, compareDrawOptions, userData);
984 }
985
986 static void cddm_draw_attrib_vertex(DMVertexAttribs *attribs, MVert *mvert, int a, int index, int vert, int smoothnormal)
987 {
988         int b;
989
990         /* orco texture coordinates */
991         if (attribs->totorco) {
992                 if (attribs->orco.gl_texco)
993                         glTexCoord3fv(attribs->orco.array[index]);
994                 else
995                         glVertexAttrib3fvARB(attribs->orco.gl_index, attribs->orco.array[index]);
996         }
997
998         /* uv texture coordinates */
999         for (b = 0; b < attribs->tottface; b++) {
1000                 MTFace *tf = &attribs->tface[b].array[a];
1001
1002                 if (attribs->tface[b].gl_texco)
1003                         glTexCoord2fv(tf->uv[vert]);
1004                 else
1005                         glVertexAttrib2fvARB(attribs->tface[b].gl_index, tf->uv[vert]);
1006         }
1007
1008         /* vertex colors */
1009         for (b = 0; b < attribs->totmcol; b++) {
1010                 MCol *cp = &attribs->mcol[b].array[a*4 + vert];
1011                 GLubyte col[4];
1012                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1013                 glVertexAttrib4ubvARB(attribs->mcol[b].gl_index, col);
1014         }
1015
1016         /* tangent for normal mapping */
1017         if (attribs->tottang) {
1018                 float *tang = attribs->tang.array[a*4 + vert];
1019                 glVertexAttrib4fvARB(attribs->tang.gl_index, tang);
1020         }
1021
1022         /* vertex normal */
1023         if (smoothnormal)
1024                 glNormal3sv(mvert[index].no);
1025         
1026         /* vertex coordinate */
1027         glVertex3fv(mvert[index].co);
1028 }
1029
1030 static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm,
1031                            DMSetMaterial setMaterial,
1032                            DMSetDrawOptions setDrawOptions,
1033                            void *userData)
1034 {
1035         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
1036         GPUVertexAttribs gattribs;
1037         DMVertexAttribs attribs;
1038         MVert *mvert = cddm->mvert;
1039         MFace *mface = cddm->mface;
1040         /* MTFace *tf = dm->getTessFaceDataArray(dm, CD_MTFACE); */ /* UNUSED */
1041         float (*nors)[3] = dm->getTessFaceDataArray(dm, CD_NORMAL);
1042         int a, b, dodraw, matnr, new_matnr;
1043         int orig, *index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
1044
1045         cdDM_update_normals_from_pbvh(dm);
1046
1047         matnr = -1;
1048         dodraw = 0;
1049
1050         glShadeModel(GL_SMOOTH);
1051
1052         if ( GPU_buffer_legacy(dm) || setDrawOptions != NULL ) {
1053                 DEBUG_VBO("Using legacy code. cdDM_drawMappedFacesGLSL\n");
1054                 memset(&attribs, 0, sizeof(attribs));
1055
1056                 glBegin(GL_QUADS);
1057
1058                 for (a = 0; a < dm->numTessFaceData; a++, mface++) {
1059                         const int smoothnormal = (mface->flag & ME_SMOOTH);
1060                         new_matnr = mface->mat_nr + 1;
1061
1062                         if (new_matnr != matnr) {
1063                                 glEnd();
1064
1065                                 dodraw = setMaterial(matnr = new_matnr, &gattribs);
1066                                 if (dodraw)
1067                                         DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1068
1069                                 glBegin(GL_QUADS);
1070                         }
1071
1072                         if (!dodraw) {
1073                                 continue;
1074                         }
1075                         else if (setDrawOptions) {
1076                                 orig = (index)? index[a]: a;
1077
1078                                 if (orig == ORIGINDEX_NONE) {
1079                                         /* since the material is set by setMaterial(), faces with no
1080                                          * origin can be assumed to be generated by a modifier */ 
1081                                         
1082                                         /* continue */
1083                                 }
1084                                 else if (setDrawOptions(userData, orig) == DM_DRAW_OPTION_SKIP)
1085                                         continue;
1086                         }
1087
1088                         if (!smoothnormal) {
1089                                 if (nors) {
1090                                         glNormal3fv(nors[a]);
1091                                 }
1092                                 else {
1093                                         /* TODO ideally a normal layer should always be available */
1094                                         float nor[3];
1095                                         if (mface->v4) {
1096                                                 normal_quad_v3(nor, mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co);
1097                                         }
1098                                         else {
1099                                                 normal_tri_v3(nor, mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co);
1100                                         }
1101                                         glNormal3fv(nor);
1102                                 }
1103                         }
1104
1105                         cddm_draw_attrib_vertex(&attribs, mvert, a, mface->v1, 0, smoothnormal);
1106                         cddm_draw_attrib_vertex(&attribs, mvert, a, mface->v2, 1, smoothnormal);
1107                         cddm_draw_attrib_vertex(&attribs, mvert, a, mface->v3, 2, smoothnormal);
1108
1109                         if (mface->v4)
1110                                 cddm_draw_attrib_vertex(&attribs, mvert, a, mface->v4, 3, smoothnormal);
1111                         else
1112                                 cddm_draw_attrib_vertex(&attribs, mvert, a, mface->v3, 2, smoothnormal);
1113                 }
1114                 glEnd();
1115         }
1116         else {
1117                 GPUBuffer *buffer = NULL;
1118                 char *varray = NULL;
1119                 int numdata = 0, elementsize = 0, offset;
1120                 int start = 0, numfaces = 0 /* , prevdraw = 0 */ /* UNUSED */, curface = 0;
1121                 int i;
1122
1123                 MFace *mf = mface;
1124                 GPUAttrib datatypes[GPU_MAX_ATTRIB]; /* TODO, messing up when switching materials many times - [#21056]*/
1125                 memset(&attribs, 0, sizeof(attribs));
1126
1127                 GPU_vertex_setup(dm);
1128                 GPU_normal_setup(dm);
1129
1130                 if (!GPU_buffer_legacy(dm)) {
1131                         for (i = 0; i < dm->drawObject->tot_triangle_point/3; i++) {
1132
1133                                 a = dm->drawObject->triangle_to_mface[i];
1134
1135                                 mface = mf + a;
1136                                 new_matnr = mface->mat_nr + 1;
1137
1138                                 if (new_matnr != matnr) {
1139                                         numfaces = curface - start;
1140                                         if (numfaces > 0) {
1141
1142                                                 if (dodraw) {
1143
1144                                                         if (numdata != 0) {
1145
1146                                                                 GPU_buffer_unlock(buffer);
1147
1148                                                                 GPU_interleaved_attrib_setup(buffer, datatypes, numdata);
1149                                                         }
1150
1151                                                         glDrawArrays(GL_TRIANGLES, start*3, numfaces*3);
1152
1153                                                         if (numdata != 0) {
1154
1155                                                                 GPU_buffer_free(buffer);
1156
1157                                                                 buffer = NULL;
1158                                                         }
1159
1160                                                 }
1161                                         }
1162                                         numdata = 0;
1163                                         start = curface;
1164                                         /* prevdraw = dodraw; */ /* UNUSED */
1165                                         dodraw = setMaterial(matnr = new_matnr, &gattribs);
1166                                         if (dodraw) {
1167                                                 DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1168
1169                                                 if (attribs.totorco) {
1170                                                         datatypes[numdata].index = attribs.orco.gl_index;
1171                                                         datatypes[numdata].size = 3;
1172                                                         datatypes[numdata].type = GL_FLOAT;
1173                                                         numdata++;
1174                                                 }
1175                                                 for (b = 0; b < attribs.tottface; b++) {
1176                                                         datatypes[numdata].index = attribs.tface[b].gl_index;
1177                                                         datatypes[numdata].size = 2;
1178                                                         datatypes[numdata].type = GL_FLOAT;
1179                                                         numdata++;
1180                                                 }       
1181                                                 for (b = 0; b < attribs.totmcol; b++) {
1182                                                         datatypes[numdata].index = attribs.mcol[b].gl_index;
1183                                                         datatypes[numdata].size = 4;
1184                                                         datatypes[numdata].type = GL_UNSIGNED_BYTE;
1185                                                         numdata++;
1186                                                 }       
1187                                                 if (attribs.tottang) {
1188                                                         datatypes[numdata].index = attribs.tang.gl_index;
1189                                                         datatypes[numdata].size = 4;
1190                                                         datatypes[numdata].type = GL_FLOAT;
1191                                                         numdata++;
1192                                                 }
1193                                                 if (numdata != 0) {
1194                                                         elementsize = GPU_attrib_element_size(datatypes, numdata);
1195                                                         buffer = GPU_buffer_alloc(elementsize * dm->drawObject->tot_triangle_point);
1196                                                         if (buffer == NULL) {
1197                                                                 GPU_buffer_unbind();
1198                                                                 dm->drawObject->legacy = 1;
1199                                                                 return;
1200                                                         }
1201                                                         varray = GPU_buffer_lock_stream(buffer);
1202                                                         if (varray == NULL) {
1203                                                                 GPU_buffer_unbind();
1204                                                                 GPU_buffer_free(buffer);
1205                                                                 dm->drawObject->legacy = 1;
1206                                                                 return;
1207                                                         }
1208                                                 }
1209                                                 else {
1210                                                         /* if the buffer was set, don't use it again.
1211                                                          * prevdraw was assumed true but didnt run so set to false - [#21036] */
1212                                                         /* prevdraw= 0; */ /* UNUSED */
1213                                                         buffer = NULL;
1214                                                 }
1215                                         }
1216                                 }
1217
1218                                 if (dodraw && numdata != 0 ) {
1219                                         offset = 0;
1220                                         if (attribs.totorco) {
1221                                                 copy_v3_v3((float *)&varray[elementsize*curface*3], (float *)attribs.orco.array[mface->v1]);
1222                                                 copy_v3_v3((float *)&varray[elementsize*curface*3+elementsize], (float *)attribs.orco.array[mface->v2]);
1223                                                 copy_v3_v3((float *)&varray[elementsize*curface*3+elementsize*2], (float *)attribs.orco.array[mface->v3]);
1224                                                 offset += sizeof(float)*3;
1225                                         }
1226                                         for (b = 0; b < attribs.tottface; b++) {
1227                                                 MTFace *tf = &attribs.tface[b].array[a];
1228                                                 copy_v2_v2((float *)&varray[elementsize*curface*3+offset], tf->uv[0]);
1229                                                 copy_v2_v2((float *)&varray[elementsize*curface*3+offset+elementsize], tf->uv[1]);
1230
1231                                                 copy_v2_v2((float *)&varray[elementsize*curface*3+offset+elementsize*2], tf->uv[2]);
1232                                                 offset += sizeof(float)*2;
1233                                         }
1234                                         for (b = 0; b < attribs.totmcol; b++) {
1235                                                 MCol *cp = &attribs.mcol[b].array[a*4 + 0];
1236                                                 GLubyte col[4];
1237                                                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1238                                                 copy_v4_v4_char((char *)&varray[elementsize*curface*3+offset], (char *)col);
1239                                                 cp = &attribs.mcol[b].array[a*4 + 1];
1240                                                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1241                                                 copy_v4_v4_char((char *)&varray[elementsize*curface*3+offset+elementsize], (char *)col);
1242                                                 cp = &attribs.mcol[b].array[a*4 + 2];
1243                                                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1244                                                 copy_v4_v4_char((char *)&varray[elementsize*curface*3+offset+elementsize*2], (char *)col);
1245                                                 offset += sizeof(unsigned char)*4;
1246                                         }       
1247                                         if (attribs.tottang) {
1248                                                 float *tang = attribs.tang.array[a*4 + 0];
1249                                                 copy_v4_v4((float *)&varray[elementsize*curface*3+offset], tang);
1250                                                 tang = attribs.tang.array[a*4 + 1];
1251                                                 copy_v4_v4((float *)&varray[elementsize*curface*3+offset+elementsize], tang);
1252                                                 tang = attribs.tang.array[a*4 + 2];
1253                                                 copy_v4_v4((float *)&varray[elementsize*curface*3+offset+elementsize*2], tang);
1254                                                 offset += sizeof(float)*4;
1255                                         }
1256                                         (void)offset;
1257                                 }
1258                                 curface++;
1259                                 if (mface->v4) {
1260                                         if (dodraw && numdata != 0 ) {
1261                                                 offset = 0;
1262                                                 if (attribs.totorco) {
1263                                                         copy_v3_v3((float *)&varray[elementsize*curface*3], (float *)attribs.orco.array[mface->v3]);
1264                                                         copy_v3_v3((float *)&varray[elementsize*curface*3+elementsize], (float *)attribs.orco.array[mface->v4]);
1265                                                         copy_v3_v3((float *)&varray[elementsize*curface*3+elementsize*2], (float *)attribs.orco.array[mface->v1]);
1266                                                         offset += sizeof(float)*3;
1267                                                 }
1268                                                 for (b = 0; b < attribs.tottface; b++) {
1269                                                         MTFace *tf = &attribs.tface[b].array[a];
1270                                                         copy_v2_v2((float *)&varray[elementsize*curface*3+offset], tf->uv[2]);
1271                                                         copy_v2_v2((float *)&varray[elementsize*curface*3+offset+elementsize], tf->uv[3]);
1272                                                         copy_v2_v2((float *)&varray[elementsize*curface*3+offset+elementsize*2], tf->uv[0]);
1273                                                         offset += sizeof(float)*2;
1274                                                 }
1275                                                 for (b = 0; b < attribs.totmcol; b++) {
1276                                                         MCol *cp = &attribs.mcol[b].array[a*4 + 2];
1277                                                         GLubyte col[4];
1278                                                         col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1279                                                         copy_v4_v4_char((char *)&varray[elementsize*curface*3+offset], (char *)col);
1280                                                         cp = &attribs.mcol[b].array[a*4 + 3];
1281                                                         col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1282                                                         copy_v4_v4_char((char *)&varray[elementsize*curface*3+offset+elementsize], (char *)col);
1283                                                         cp = &attribs.mcol[b].array[a*4 + 0];
1284                                                         col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1285                                                         copy_v4_v4_char((char *)&varray[elementsize*curface*3+offset+elementsize*2], (char *)col);
1286                                                         offset += sizeof(unsigned char)*4;
1287                                                 }       
1288                                                 if (attribs.tottang) {
1289                                                         float *tang = attribs.tang.array[a*4 + 2];
1290                                                         copy_v4_v4((float *)&varray[elementsize*curface*3+offset], tang);
1291                                                         tang = attribs.tang.array[a*4 + 3];
1292                                                         copy_v4_v4((float *)&varray[elementsize*curface*3+offset+elementsize], tang);
1293                                                         tang = attribs.tang.array[a*4 + 0];
1294                                                         copy_v4_v4((float *)&varray[elementsize*curface*3+offset+elementsize*2], tang);
1295                                                         offset += sizeof(float)*4;
1296                                                 }
1297                                                 (void)offset;
1298                                         }
1299                                         curface++;
1300                                         i++;
1301                                 }
1302                         }
1303                         numfaces = curface - start;
1304                         if (numfaces > 0) {
1305                                 if (dodraw) {
1306                                         if (numdata != 0) {
1307                                                 GPU_buffer_unlock(buffer);
1308                                                 GPU_interleaved_attrib_setup(buffer, datatypes, numdata);
1309                                         }
1310                                         glDrawArrays(GL_TRIANGLES, start*3, (curface-start)*3);
1311                                 }
1312                         }
1313                         GPU_buffer_unbind();
1314                 }
1315                 GPU_buffer_free(buffer);
1316         }
1317
1318         glShadeModel(GL_FLAT);
1319 }
1320
1321 static void cdDM_drawFacesGLSL(DerivedMesh *dm, DMSetMaterial setMaterial)
1322 {
1323         dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
1324 }
1325
1326 static void cdDM_drawMappedFacesMat(DerivedMesh *dm,
1327         void (*setMaterial)(void *userData, int, void *attribs),
1328         int (*setFace)(void *userData, int index), void *userData)
1329 {
1330         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
1331         GPUVertexAttribs gattribs;
1332         DMVertexAttribs attribs;
1333         MVert *mvert = cddm->mvert;
1334         MFace *mf = cddm->mface;
1335         float (*nors)[3] = dm->getTessFaceDataArray(dm, CD_NORMAL);
1336         int a, matnr, new_matnr;
1337         int orig, *index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
1338
1339         cdDM_update_normals_from_pbvh(dm);
1340
1341         matnr = -1;
1342
1343         glShadeModel(GL_SMOOTH);
1344
1345         memset(&attribs, 0, sizeof(attribs));
1346
1347         glBegin(GL_QUADS);
1348
1349         for (a = 0; a < dm->numTessFaceData; a++, mf++) {
1350                 const int smoothnormal = (mf->flag & ME_SMOOTH);
1351
1352                 /* material */
1353                 new_matnr = mf->mat_nr + 1;
1354
1355                 if (new_matnr != matnr) {
1356                         glEnd();
1357
1358                         setMaterial(userData, matnr = new_matnr, &gattribs);
1359                         DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1360
1361                         glBegin(GL_QUADS);
1362                 }
1363
1364                 /* skipping faces */
1365                 if (setFace) {
1366                         orig = (index)? index[a]: a;
1367
1368                         if (orig != ORIGINDEX_NONE && !setFace(userData, orig))
1369                                 continue;
1370                 }
1371
1372                 /* smooth normal */
1373                 if (!smoothnormal) {
1374                         if (nors) {
1375                                 glNormal3fv(nors[a]);
1376                         }
1377                         else {
1378                                 /* TODO ideally a normal layer should always be available */
1379                                 float nor[3];
1380
1381                                 if (mf->v4)
1382                                         normal_quad_v3(nor, mvert[mf->v1].co, mvert[mf->v2].co, mvert[mf->v3].co, mvert[mf->v4].co);
1383                                 else
1384                                         normal_tri_v3(nor, mvert[mf->v1].co, mvert[mf->v2].co, mvert[mf->v3].co);
1385
1386                                 glNormal3fv(nor);
1387                         }
1388                 }
1389
1390                 /* vertices */
1391                 cddm_draw_attrib_vertex(&attribs, mvert, a, mf->v1, 0, smoothnormal);
1392                 cddm_draw_attrib_vertex(&attribs, mvert, a, mf->v2, 1, smoothnormal);
1393                 cddm_draw_attrib_vertex(&attribs, mvert, a, mf->v3, 2, smoothnormal);
1394
1395                 if (mf->v4)
1396                         cddm_draw_attrib_vertex(&attribs, mvert, a, mf->v4, 3, smoothnormal);
1397                 else
1398                         cddm_draw_attrib_vertex(&attribs, mvert, a, mf->v3, 2, smoothnormal);
1399         }
1400         glEnd();
1401
1402         glShadeModel(GL_FLAT);
1403 }
1404
1405 static void cdDM_drawMappedEdges(DerivedMesh *dm, DMSetDrawOptions setDrawOptions, void *userData)
1406 {
1407         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
1408         MVert *vert = cddm->mvert;
1409         MEdge *edge = cddm->medge;
1410         int i, orig, *index = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1411
1412         glBegin(GL_LINES);
1413         for (i = 0; i < dm->numEdgeData; i++, edge++) {
1414                 if (index) {
1415                         orig = *index++;
1416                         if (setDrawOptions && orig == ORIGINDEX_NONE) continue;
1417                 }
1418                 else
1419                         orig = i;
1420
1421                 if (!setDrawOptions || (setDrawOptions(userData, orig) != DM_DRAW_OPTION_SKIP)) {
1422                         glVertex3fv(vert[edge->v1].co);
1423                         glVertex3fv(vert[edge->v2].co);
1424                 }
1425         }
1426         glEnd();
1427 }
1428
1429 static void cdDM_foreachMappedVert(
1430         DerivedMesh *dm,
1431         void (*func)(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3]),
1432         void *userData)
1433 {
1434         MVert *mv = CDDM_get_verts(dm);
1435         int i, orig, *index = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
1436
1437         for (i = 0; i < dm->numVertData; i++, mv++) {
1438                 if (index) {
1439                         orig = *index++;
1440                         if (orig == ORIGINDEX_NONE) continue;
1441                         func(userData, orig, mv->co, NULL, mv->no);
1442                 }
1443                 else
1444                         func(userData, i, mv->co, NULL, mv->no);
1445         }
1446 }
1447
1448 static void cdDM_foreachMappedEdge(
1449         DerivedMesh *dm,
1450         void (*func)(void *userData, int index, const float v0co[3], const float v1co[3]),
1451         void *userData)
1452 {
1453         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
1454         MVert *mv = cddm->mvert;
1455         MEdge *med = cddm->medge;
1456         int i, orig, *index = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1457
1458         for (i = 0; i < dm->numEdgeData; i++, med++) {
1459                 if (index) {
1460                         orig = *index++;
1461                         if (orig == ORIGINDEX_NONE) continue;
1462                         func(userData, orig, mv[med->v1].co, mv[med->v2].co);
1463                 }
1464                 else
1465                         func(userData, i, mv[med->v1].co, mv[med->v2].co);
1466         }
1467 }
1468
1469 static void cdDM_foreachMappedFaceCenter(
1470         DerivedMesh *dm,
1471         void (*func)(void *userData, int index, const float cent[3], const float no[3]),
1472         void *userData)
1473 {
1474         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1475         MVert *mv = cddm->mvert;
1476         MPoly *mp = cddm->mpoly;
1477         MLoop *ml = cddm->mloop;
1478         int i, j, orig, *index;
1479
1480         index = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX);
1481         mp = cddm->mpoly;
1482         for (i = 0; i < dm->numPolyData; i++, mp++) {
1483                 float cent[3];
1484                 float no[3];
1485
1486                 if (index) {
1487                         orig = *index++;
1488                         if (orig == ORIGINDEX_NONE) continue;
1489                 }
1490                 else
1491                         orig = i;
1492                 
1493                 ml = &cddm->mloop[mp->loopstart];
1494                 cent[0] = cent[1] = cent[2] = 0.0f;
1495                 for (j=0; j<mp->totloop; j++, ml++) {
1496                         add_v3_v3v3(cent, cent, mv[ml->v].co);
1497                 }
1498                 mul_v3_fl(cent, 1.0f / (float)j);
1499
1500                 ml = &cddm->mloop[mp->loopstart];
1501                 if (j > 3) {
1502                         normal_quad_v3(no,
1503                                        mv[(ml + 0)->v].co,
1504                                        mv[(ml + 1)->v].co,
1505                                        mv[(ml + 2)->v].co,
1506                                        mv[(ml + 3)->v].co);
1507                 }
1508                 else {
1509                         normal_tri_v3(no,
1510                                       mv[(ml + 0)->v].co,
1511                                       mv[(ml + 1)->v].co,
1512                                       mv[(ml + 2)->v].co);
1513                 }
1514
1515                 func(userData, orig, cent, no);
1516         }
1517
1518 }
1519
1520 void CDDM_recalc_tessellation_ex(DerivedMesh *dm, const int do_face_nor_cpy)
1521 {
1522         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1523
1524         dm->numTessFaceData = mesh_recalcTessellation(&dm->faceData, &dm->loopData, &dm->polyData,
1525                                                      cddm->mvert,
1526                                                      dm->numTessFaceData, dm->numLoopData, dm->numPolyData,
1527                                                      do_face_nor_cpy);
1528
1529         if (!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX)) {
1530                 int *polyIndex = CustomData_get_layer(&dm->faceData, CD_POLYINDEX);
1531                 CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_REFERENCE, polyIndex, dm->numTessFaceData);
1532         }
1533
1534         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1535
1536         /* Tessellation recreated faceData, and the active layer indices need to get re-propagated
1537          * from loops and polys to faces */
1538         CustomData_bmesh_update_active_layers(&dm->faceData, &dm->polyData, &dm->loopData);
1539 }
1540
1541 void CDDM_recalc_tessellation(DerivedMesh *dm)
1542 {
1543         CDDM_recalc_tessellation_ex(dm, TRUE);
1544 }
1545
1546 static void cdDM_free_internal(CDDerivedMesh *cddm)
1547 {
1548         if (cddm->pmap) MEM_freeN(cddm->pmap);
1549         if (cddm->pmap_mem) MEM_freeN(cddm->pmap_mem);
1550 }
1551
1552 static void cdDM_release(DerivedMesh *dm)
1553 {
1554         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1555
1556         if (DM_release(dm)) {
1557                 cdDM_free_internal(cddm);
1558                 MEM_freeN(cddm);
1559         }
1560 }
1561
1562 int CDDM_Check(DerivedMesh *dm)
1563 {
1564         return dm && dm->getMinMax == cdDM_getMinMax;
1565 }
1566
1567 /**************** CDDM interface functions ****************/
1568 static CDDerivedMesh *cdDM_create(const char *desc)
1569 {
1570         CDDerivedMesh *cddm;
1571         DerivedMesh *dm;
1572
1573         cddm = MEM_callocN(sizeof(*cddm), desc);
1574         dm = &cddm->dm;
1575
1576         dm->getMinMax = cdDM_getMinMax;
1577
1578         dm->getNumVerts = cdDM_getNumVerts;
1579         dm->getNumEdges = cdDM_getNumEdges;
1580         dm->getNumTessFaces = cdDM_getNumTessFaces;
1581         dm->getNumLoops = cdDM_getNumLoops;
1582         dm->getNumPolys = cdDM_getNumPolys;
1583
1584         dm->getVert = cdDM_getVert;
1585         dm->getEdge = cdDM_getEdge;
1586         dm->getTessFace = cdDM_getTessFace;
1587
1588         dm->copyVertArray = cdDM_copyVertArray;
1589         dm->copyEdgeArray = cdDM_copyEdgeArray;
1590         dm->copyTessFaceArray = cdDM_copyTessFaceArray;
1591         dm->copyLoopArray = cdDM_copyLoopArray;
1592         dm->copyPolyArray = cdDM_copyPolyArray;
1593
1594         dm->getVertData = DM_get_vert_data;
1595         dm->getEdgeData = DM_get_edge_data;
1596         dm->getTessFaceData = DM_get_tessface_data;
1597         dm->getVertDataArray = DM_get_vert_data_layer;
1598         dm->getEdgeDataArray = DM_get_edge_data_layer;
1599         dm->getTessFaceDataArray = DM_get_tessface_data_layer;
1600
1601         dm->calcNormals = CDDM_calc_normals_mapping;
1602         dm->recalcTessellation = CDDM_recalc_tessellation;
1603
1604         dm->getVertCos = cdDM_getVertCos;
1605         dm->getVertCo = cdDM_getVertCo;
1606         dm->getVertNo = cdDM_getVertNo;
1607
1608         dm->getPBVH = cdDM_getPBVH;
1609         dm->getPolyMap = cdDM_getPolyMap;
1610
1611         dm->drawVerts = cdDM_drawVerts;
1612
1613         dm->drawUVEdges = cdDM_drawUVEdges;
1614         dm->drawEdges = cdDM_drawEdges;
1615         dm->drawLooseEdges = cdDM_drawLooseEdges;
1616         dm->drawMappedEdges = cdDM_drawMappedEdges;
1617
1618         dm->drawFacesSolid = cdDM_drawFacesSolid;
1619         dm->drawFacesTex = cdDM_drawFacesTex;
1620         dm->drawFacesGLSL = cdDM_drawFacesGLSL;
1621         dm->drawMappedFaces = cdDM_drawMappedFaces;
1622         dm->drawMappedFacesTex = cdDM_drawMappedFacesTex;
1623         dm->drawMappedFacesGLSL = cdDM_drawMappedFacesGLSL;
1624         dm->drawMappedFacesMat = cdDM_drawMappedFacesMat;
1625
1626         dm->foreachMappedVert = cdDM_foreachMappedVert;
1627         dm->foreachMappedEdge = cdDM_foreachMappedEdge;
1628         dm->foreachMappedFaceCenter = cdDM_foreachMappedFaceCenter;
1629
1630         dm->release = cdDM_release;
1631
1632         return cddm;
1633 }
1634
1635 DerivedMesh *CDDM_new(int numVerts, int numEdges, int numTessFaces, int numLoops, int numPolys)
1636 {
1637         CDDerivedMesh *cddm = cdDM_create("CDDM_new dm");
1638         DerivedMesh *dm = &cddm->dm;
1639
1640         DM_init(dm, DM_TYPE_CDDM, numVerts, numEdges, numTessFaces, numLoops, numPolys);
1641
1642         CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
1643         CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
1644         CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numTessFaces);
1645         CustomData_add_layer(&dm->faceData, CD_POLYINDEX, CD_CALLOC, NULL, numTessFaces);
1646         CustomData_add_layer(&dm->polyData, CD_ORIGINDEX, CD_CALLOC, NULL, numPolys);
1647
1648         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
1649         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
1650         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numTessFaces);
1651         CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL, numLoops);
1652         CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL, numPolys);
1653
1654         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
1655         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1656         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1657         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
1658         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
1659
1660         return dm;
1661 }
1662
1663 DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *UNUSED(ob))
1664 {
1665         CDDerivedMesh *cddm = cdDM_create("CDDM_from_mesh dm");
1666         DerivedMesh *dm = &cddm->dm;
1667         CustomDataMask mask = CD_MASK_MESH & (~CD_MASK_MDISPS);
1668         int alloctype;
1669         int *polyindex = NULL;
1670
1671         /* this does a referenced copy, with an exception for fluidsim */
1672
1673         DM_init(dm, DM_TYPE_CDDM, mesh->totvert, mesh->totedge, mesh->totface,
1674                     mesh->totloop, mesh->totpoly);
1675
1676         dm->deformedOnly = 1;
1677
1678         alloctype= CD_REFERENCE;
1679
1680         CustomData_merge(&mesh->vdata, &dm->vertData, mask, alloctype,
1681                                          mesh->totvert);
1682         CustomData_merge(&mesh->edata, &dm->edgeData, mask, alloctype,
1683                                          mesh->totedge);
1684         CustomData_merge(&mesh->fdata, &dm->faceData, mask|CD_MASK_POLYINDEX, alloctype,
1685                                          mesh->totface);
1686         CustomData_merge(&mesh->ldata, &dm->loopData, mask, alloctype,
1687                          mesh->totloop);
1688         CustomData_merge(&mesh->pdata, &dm->polyData, mask, alloctype,
1689                          mesh->totpoly);
1690
1691         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
1692         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1693         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
1694         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
1695         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1696
1697         /* commented since even when CD_POLYINDEX was first added this line fails
1698          * on the default cube, (after editmode toggle too) - campbell */
1699 #if 0
1700         BLI_assert(CustomData_has_layer(&cddm->dm.faceData, CD_POLYINDEX));
1701 #endif
1702
1703         polyindex = CustomData_get_layer(&dm->faceData, CD_POLYINDEX);
1704         if (!CustomData_has_layer(&cddm->dm.faceData, CD_ORIGINDEX)) {
1705                 CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_REFERENCE, polyindex, mesh->totface);
1706         }
1707
1708         return dm;
1709 }
1710
1711 DerivedMesh *CDDM_from_curve(Object *ob)
1712 {
1713         return CDDM_from_curve_customDB(ob, &ob->disp);
1714 }
1715
1716 DerivedMesh *CDDM_from_curve_customDB(Object *ob, ListBase *dispbase)
1717 {
1718         DerivedMesh *dm;
1719         CDDerivedMesh *cddm;
1720         MVert *allvert;
1721         MEdge *alledge;
1722         MLoop *allloop;
1723         MPoly *allpoly;
1724         int totvert, totedge, totloop, totpoly;
1725
1726         if (nurbs_to_mdata_customdb(ob, dispbase, &allvert, &totvert, &alledge,
1727                 &totedge, &allloop, &allpoly, &totloop, &totpoly) != 0) {
1728                 /* Error initializing mdata. This often happens when curve is empty */
1729                 return CDDM_new(0, 0, 0, 0, 0);
1730         }
1731
1732         dm = CDDM_new(totvert, totedge, 0, totloop, totpoly);
1733         dm->deformedOnly = 1;
1734
1735         cddm = (CDDerivedMesh*)dm;
1736
1737         memcpy(cddm->mvert, allvert, totvert*sizeof(MVert));
1738         memcpy(cddm->medge, alledge, totedge*sizeof(MEdge));
1739         memcpy(cddm->mloop, allloop, totloop*sizeof(MLoop));
1740         memcpy(cddm->mpoly, allpoly, totpoly*sizeof(MPoly));
1741
1742         MEM_freeN(allvert);
1743         MEM_freeN(alledge);
1744         MEM_freeN(allloop);
1745         MEM_freeN(allpoly);
1746
1747         CDDM_calc_edges(dm);
1748
1749         return dm;
1750 }
1751
1752 static void loops_to_customdata_corners(BMesh *bm, CustomData *facedata,
1753                                           int cdindex, BMLoop *l3[3],
1754                                           int numCol, int numTex)
1755 {
1756         BMLoop *l;
1757         BMFace *f = l3[0]->f;
1758         MTFace *texface;
1759         MTexPoly *texpoly;
1760         MCol *mcol;
1761         MLoopCol *mloopcol;
1762         MLoopUV *mloopuv;
1763         int i, j, hasPCol = CustomData_has_layer(&bm->ldata, CD_PREVIEW_MLOOPCOL);
1764
1765         for (i = 0; i < numTex; i++) {
1766                 texface = CustomData_get_n(facedata, CD_MTFACE, cdindex, i);
1767                 texpoly = CustomData_bmesh_get_n(&bm->pdata, f->head.data, CD_MTEXPOLY, i);
1768                 
1769                 ME_MTEXFACE_CPY(texface, texpoly);
1770         
1771                 for (j = 0 ; j < 3; j++) {
1772                         l = l3[j];
1773                         mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->head.data, CD_MLOOPUV, i);
1774                         copy_v2_v2(texface->uv[j], mloopuv->uv);
1775                 }
1776         }
1777
1778         for (i = 0; i < numCol; i++) {
1779                 mcol = CustomData_get_n(facedata, CD_MCOL, cdindex, i);
1780                 
1781                 for (j = 0; j < 3; j++) {
1782                         l = l3[j];
1783                         mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->head.data, CD_MLOOPCOL, i);
1784                         MESH_MLOOPCOL_TO_MCOL(mloopcol, &mcol[j]);
1785                 }
1786         }
1787
1788         if (hasPCol) {
1789                 mcol = CustomData_get(facedata, cdindex, CD_PREVIEW_MCOL);
1790
1791                 for (j = 0; j < 3; j++) {
1792                         l = l3[j];
1793                         mloopcol = CustomData_bmesh_get(&bm->ldata, l->head.data, CD_PREVIEW_MLOOPCOL);
1794                         MESH_MLOOPCOL_TO_MCOL(mloopcol, &mcol[j]);
1795                 }
1796         }
1797 }
1798
1799 DerivedMesh *CDDM_from_BMEditMesh(BMEditMesh *em, Mesh *UNUSED(me), int use_mdisps, int use_tessface)
1800 {
1801         BMesh *bm = em->bm;
1802
1803         DerivedMesh *dm = CDDM_new(bm->totvert,
1804                                    bm->totedge,
1805                                    use_tessface ? em->tottri : 0,
1806                                    bm->totloop,
1807                                    bm->totface);
1808
1809         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1810         BMIter iter, liter;
1811         BMVert *eve;
1812         BMEdge *eed;
1813         BMFace *efa;
1814         MVert *mvert = cddm->mvert;
1815         MEdge *medge = cddm->medge;
1816         MFace *mface = cddm->mface;
1817         MLoop *mloop = cddm->mloop;
1818         MPoly *mpoly = cddm->mpoly;
1819         int numCol = CustomData_number_of_layers(&bm->ldata, CD_MLOOPCOL);
1820         int numTex = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
1821         int *index, add_orig;
1822         int has_crease, has_edge_bweight, has_vert_bweight;
1823         CustomDataMask mask;
1824         unsigned int i, j;
1825         
1826         has_edge_bweight = CustomData_has_layer(&bm->edata, CD_BWEIGHT);
1827         has_vert_bweight = CustomData_has_layer(&bm->vdata, CD_BWEIGHT);
1828         has_crease = CustomData_has_layer(&bm->edata, CD_CREASE);
1829         
1830         dm->deformedOnly = 1;
1831         
1832         /*don't add origindex layer if one already exists*/
1833         add_orig = !CustomData_has_layer(&bm->pdata, CD_ORIGINDEX);
1834
1835         mask = use_mdisps ? CD_MASK_DERIVEDMESH|CD_MASK_MDISPS : CD_MASK_DERIVEDMESH;
1836         
1837         /* don't process shapekeys, we only feed them through the modifier stack as needed,
1838          * e.g. for applying modifiers or the like*/
1839         mask &= ~CD_MASK_SHAPEKEY;
1840         CustomData_merge(&bm->vdata, &dm->vertData, mask,
1841                          CD_CALLOC, dm->numVertData);
1842         CustomData_merge(&bm->edata, &dm->edgeData, mask,
1843                          CD_CALLOC, dm->numEdgeData);
1844         CustomData_merge(&bm->ldata, &dm->loopData, mask,
1845                          CD_CALLOC, dm->numLoopData);
1846         CustomData_merge(&bm->pdata, &dm->polyData, mask,
1847                          CD_CALLOC, dm->numPolyData);
1848         
1849         /*add tessellation mface layers*/
1850         if (use_tessface) {
1851                 CustomData_from_bmeshpoly(&dm->faceData, &dm->polyData, &dm->loopData, em->tottri);
1852         }
1853
1854         index = dm->getVertDataArray(dm, CD_ORIGINDEX);
1855
1856         eve = BM_iter_new(&iter, bm, BM_VERTS_OF_MESH, NULL);
1857         for (i = 0; eve; eve = BM_iter_step(&iter), i++, index++) {
1858                 MVert *mv = &mvert[i];
1859
1860                 copy_v3_v3(mv->co, eve->co);
1861
1862                 BM_elem_index_set(eve, i); /* set_inline */
1863
1864                 normal_float_to_short_v3(mv->no, eve->no);
1865
1866                 mv->flag = BM_vert_flag_to_mflag(eve);
1867
1868                 if (has_vert_bweight)
1869                         mv->bweight = (unsigned char)(BM_elem_float_data_get(&bm->vdata, eve, CD_BWEIGHT)*255.0f);
1870
1871                 if (add_orig) *index = i;
1872
1873                 CustomData_from_bmesh_block(&bm->vdata, &dm->vertData, eve->head.data, i);
1874         }
1875         bm->elem_index_dirty &= ~BM_VERT;
1876
1877         index = dm->getEdgeDataArray(dm, CD_ORIGINDEX);
1878         eed = BM_iter_new(&iter, bm, BM_EDGES_OF_MESH, NULL);
1879         for (i = 0; eed; eed = BM_iter_step(&iter), i++, index++) {
1880                 MEdge *med = &medge[i];
1881
1882                 BM_elem_index_set(eed, i); /* set_inline */
1883
1884                 med->v1 = BM_elem_index_get(eed->v1);
1885                 med->v2 = BM_elem_index_get(eed->v2);
1886
1887                 if (has_crease)
1888                         med->crease = (unsigned char)(BM_elem_float_data_get(&bm->edata, eed, CD_CREASE)*255.0f);
1889                 if (has_edge_bweight)
1890                         med->bweight = (unsigned char)(BM_elem_float_data_get(&bm->edata, eed, CD_BWEIGHT)*255.0f);
1891                 
1892                 med->flag = BM_edge_flag_to_mflag(eed);
1893
1894                 CustomData_from_bmesh_block(&bm->edata, &dm->edgeData, eed->head.data, i);
1895                 if (add_orig) *index = i;
1896         }
1897         bm->elem_index_dirty &= ~BM_EDGE;
1898
1899         /* avoid this where possiblem, takes extra memory */
1900         if (use_tessface) {
1901                 int *polyindex;
1902
1903                 BM_mesh_elem_index_ensure(bm, BM_FACE);
1904
1905                 polyindex = dm->getTessFaceDataArray(dm, CD_POLYINDEX);
1906                 index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
1907                 for (i = 0; i < dm->numTessFaceData; i++, index++, polyindex++) {
1908                         MFace *mf = &mface[i];
1909                         BMLoop **l = em->looptris[i];
1910                         efa = l[0]->f;
1911
1912                         mf->v1 = BM_elem_index_get(l[0]->v);
1913                         mf->v2 = BM_elem_index_get(l[1]->v);
1914                         mf->v3 = BM_elem_index_get(l[2]->v);
1915                         mf->v4 = 0;
1916                         mf->mat_nr = efa->mat_nr;
1917                         mf->flag = BM_face_flag_to_mflag(efa);
1918
1919                         *index = add_orig ? BM_elem_index_get(efa) : *(int*)CustomData_bmesh_get(&bm->pdata, efa->head.data, CD_ORIGINDEX);
1920                         *polyindex = BM_elem_index_get(efa);
1921
1922                         loops_to_customdata_corners(bm, &dm->faceData, i, l, numCol, numTex);
1923                         test_index_face(mf, &dm->faceData, i, 3);
1924                 }
1925         }
1926         
1927         index = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX);
1928         j = 0;
1929         efa = BM_iter_new(&iter, bm, BM_FACES_OF_MESH, NULL);
1930         for (i = 0; efa; i++, efa = BM_iter_step(&iter), index++) {
1931                 BMLoop *l;
1932                 MPoly *mp = &mpoly[i];
1933
1934                 BM_elem_index_set(efa, i); /* set_inline */
1935
1936                 mp->totloop = efa->len;
1937                 mp->flag = BM_face_flag_to_mflag(efa);
1938                 mp->loopstart = j;
1939                 mp->mat_nr = efa->mat_nr;
1940                 
1941                 BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
1942                         mloop->v = BM_elem_index_get(l->v);
1943                         mloop->e = BM_elem_index_get(l->e);
1944                         CustomData_from_bmesh_block(&bm->ldata, &dm->loopData, l->head.data, j);
1945
1946                         j++;
1947                         mloop++;
1948                 }
1949
1950                 CustomData_from_bmesh_block(&bm->pdata, &dm->polyData, efa->head.data, i);
1951
1952                 if (add_orig) *index = i;
1953         }
1954         bm->elem_index_dirty &= ~BM_FACE;
1955
1956         return dm;
1957 }
1958
1959 static DerivedMesh *cddm_copy_ex(DerivedMesh *source, int faces_from_tessfaces)
1960 {
1961         CDDerivedMesh *cddm = cdDM_create("CDDM_copy cddm");
1962         DerivedMesh *dm = &cddm->dm;
1963         int numVerts = source->numVertData;
1964         int numEdges = source->numEdgeData;
1965         int numTessFaces = source->numTessFaceData;
1966         int numLoops = source->numLoopData;
1967         int numPolys = source->numPolyData;
1968
1969         /* ensure these are created if they are made on demand */
1970         source->getVertDataArray(source, CD_ORIGINDEX);
1971         source->getEdgeDataArray(source, CD_ORIGINDEX);
1972         source->getTessFaceDataArray(source, CD_ORIGINDEX);
1973
1974         /* this initializes dm, and copies all non mvert/medge/mface layers */
1975         DM_from_template(dm, source, DM_TYPE_CDDM, numVerts, numEdges, numTessFaces,
1976                 numLoops, numPolys);
1977         dm->deformedOnly = source->deformedOnly;
1978         dm->dirty = source->dirty;
1979
1980         CustomData_copy_data(&source->vertData, &dm->vertData, 0, 0, numVerts);
1981         CustomData_copy_data(&source->edgeData, &dm->edgeData, 0, 0, numEdges);
1982         CustomData_copy_data(&source->faceData, &dm->faceData, 0, 0, numTessFaces);
1983
1984         /* now add mvert/medge/mface layers */
1985         cddm->mvert = source->dupVertArray(source);
1986         cddm->medge = source->dupEdgeArray(source);
1987         cddm->mface = source->dupTessFaceArray(source);
1988
1989         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_ASSIGN, cddm->mvert, numVerts);
1990         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_ASSIGN, cddm->medge, numEdges);
1991         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_ASSIGN, cddm->mface, numTessFaces);
1992         
1993         if (!faces_from_tessfaces)
1994                 DM_DupPolys(source, dm);
1995         else
1996                 CDDM_tessfaces_to_faces(dm);
1997
1998         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
1999         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
2000
2001         return dm;
2002 }
2003
2004 DerivedMesh *CDDM_copy(DerivedMesh *source)
2005 {
2006         return cddm_copy_ex(source, 0);
2007 }
2008
2009 DerivedMesh *CDDM_copy_from_tessface(DerivedMesh *source)
2010 {
2011         return cddm_copy_ex(source, 1);
2012 }
2013
2014 /* note, the CD_ORIGINDEX layers are all 0, so if there is a direct
2015  * relationship between mesh data this needs to be set by the caller. */
2016 DerivedMesh *CDDM_from_template(DerivedMesh *source,
2017                                 int numVerts, int numEdges, int numTessFaces,
2018                                 int numLoops, int numPolys)
2019 {
2020         CDDerivedMesh *cddm = cdDM_create("CDDM_from_template dest");
2021         DerivedMesh *dm = &cddm->dm;
2022
2023         /* ensure these are created if they are made on demand */
2024         source->getVertDataArray(source, CD_ORIGINDEX);
2025         source->getEdgeDataArray(source, CD_ORIGINDEX);
2026         source->getTessFaceDataArray(source, CD_ORIGINDEX);
2027
2028         /* this does a copy of all non mvert/medge/mface layers */
2029         DM_from_template(dm, source, DM_TYPE_CDDM, numVerts, numEdges, numTessFaces, numLoops, numPolys);
2030
2031         /* now add mvert/medge/mface layers */
2032         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
2033         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
2034         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numTessFaces);
2035         CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL, numLoops);
2036         CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL, numPolys);
2037
2038         if (!CustomData_get_layer(&dm->vertData, CD_ORIGINDEX))
2039                 CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
2040         if (!CustomData_get_layer(&dm->edgeData, CD_ORIGINDEX))
2041                 CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
2042         if (!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX))
2043                 CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numTessFaces);
2044         if (!CustomData_get_layer(&dm->faceData, CD_POLYINDEX))
2045                 CustomData_add_layer(&dm->faceData, CD_POLYINDEX, CD_CALLOC, NULL, numTessFaces);
2046
2047         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
2048         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
2049         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
2050         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
2051         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
2052
2053         return dm;
2054 }
2055
2056 void CDDM_apply_vert_coords(DerivedMesh *dm, float (*vertCoords)[3])
2057 {
2058         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2059         MVert *vert;
2060         int i;
2061
2062         /* this will just return the pointer if it wasn't a referenced layer */
2063         vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2064         cddm->mvert = vert;
2065
2066         for (i = 0; i < dm->numVertData; ++i, ++vert)
2067                 copy_v3_v3(vert->co, vertCoords[i]);
2068 }
2069
2070 void CDDM_apply_vert_normals(DerivedMesh *dm, short (*vertNormals)[3])
2071 {
2072         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2073         MVert *vert;
2074         int i;
2075
2076         /* this will just return the pointer if it wasn't a referenced layer */
2077         vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2078         cddm->mvert = vert;
2079
2080         for (i = 0; i < dm->numVertData; ++i, ++vert)
2081                 copy_v3_v3_short(vert->no, vertNormals[i]);
2082 }
2083
2084 void CDDM_calc_normals_mapping_ex(DerivedMesh *dm, const short only_face_normals)
2085 {
2086         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2087         float (*face_nors)[3] = NULL;
2088
2089         if (dm->numVertData == 0) return;
2090
2091         /* now we skip calculating vertex normals for referenced layer,
2092          * no need to duplicate verts.
2093          * WATCH THIS, bmesh only change!,
2094          * need to take care of the side effects here - campbell */
2095         #if 0
2096         /* we don't want to overwrite any referenced layers */
2097         cddm->mvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2098         #endif
2099
2100
2101         if (dm->numTessFaceData == 0) {
2102                 /* No tessellation on this mesh yet, need to calculate one.
2103                  *
2104                  * Important not to update face normals from polys since it
2105                  * interfears with assigning the new normal layer in the following code.
2106                  */
2107                 CDDM_recalc_tessellation_ex(dm, FALSE);
2108         }
2109         else {
2110                 /* A tessellation already exists, it should always have a CD_POLYINDEX */
2111                 BLI_assert(CustomData_has_layer(&dm->faceData, CD_POLYINDEX));
2112                 CustomData_free_layers(&dm->faceData, CD_NORMAL, dm->numTessFaceData);
2113         }
2114
2115
2116         face_nors = MEM_mallocN(sizeof(float)*3*dm->numTessFaceData, "face_nors");
2117
2118         /* calculate face normals */
2119         mesh_calc_normals_mapping_ex(cddm->mvert, dm->numVertData, CDDM_get_loops(dm), CDDM_get_polys(dm),
2120                                                                  dm->numLoopData, dm->numPolyData, NULL, cddm->mface, dm->numTessFaceData,
2121                                                                  CustomData_get_layer(&dm->faceData, CD_POLYINDEX), face_nors,
2122                                                                  only_face_normals);
2123
2124         CustomData_add_layer(&dm->faceData, CD_NORMAL, CD_ASSIGN,
2125                                                  face_nors, dm->numTessFaceData);
2126 }
2127
2128
2129 void CDDM_calc_normals_mapping(DerivedMesh *dm)
2130 {
2131         /* use this to skip calculating normals on original vert's, this may need to be changed */
2132         const short only_face_normals = CustomData_is_referenced_layer(&dm->vertData, CD_MVERT);
2133
2134         CDDM_calc_normals_mapping_ex(dm, only_face_normals);
2135 }
2136
2137 /* bmesh note: this matches what we have in trunk */
2138 void CDDM_calc_normals(DerivedMesh *dm)
2139 {
2140         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2141         float (*poly_nors)[3];
2142
2143         if (dm->numVertData == 0) return;
2144
2145         /* we don't want to overwrite any referenced layers */
2146         cddm->mvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2147
2148         /* fill in if it exists */
2149         poly_nors = CustomData_get_layer(&dm->polyData, CD_NORMAL);
2150         if (!poly_nors) {
2151                 poly_nors = CustomData_add_layer(&dm->polyData, CD_NORMAL, CD_CALLOC, NULL, dm->numPolyData);
2152         }
2153
2154         mesh_calc_normals(cddm->mvert, dm->numVertData, CDDM_get_loops(dm), CDDM_get_polys(dm),
2155                           dm->numLoopData, dm->numPolyData, poly_nors);
2156 }
2157
2158 void CDDM_calc_normals_tessface(DerivedMesh *dm)
2159 {
2160         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2161         float (*face_nors)[3];
2162
2163         if (dm->numVertData == 0) return;
2164
2165         /* we don't want to overwrite any referenced layers */
2166         cddm->mvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData);
2167
2168         /* fill in if it exists */
2169         face_nors = CustomData_get_layer(&dm->faceData, CD_NORMAL);
2170         if (!face_nors) {
2171                 face_nors = CustomData_add_layer(&dm->faceData, CD_NORMAL, CD_CALLOC, NULL, dm->numTessFaceData);
2172         }
2173
2174         mesh_calc_normals_tessface(cddm->mvert, dm->numVertData,
2175                                                            cddm->mface, dm->numTessFaceData, face_nors);
2176 }
2177
2178 #if 1
2179 /* merge verts
2180  *
2181  * vtargetmap is a table that maps vertices to target vertices.  a value of -1
2182  * indicates a vertex is a target, and is to be kept.
2183  *
2184  * this frees dm, and returns a new one.
2185  *
2186  * this is a really horribly written function.  ger. - joeedh
2187  *
2188  * note, CDDM_recalc_tessellation has to run on the returned DM if you want to access tessfaces.
2189  */
2190 DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap)
2191 {
2192         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2193         CDDerivedMesh *cddm2 = NULL;
2194         MVert *mv, *mvert = NULL;
2195         BLI_array_declare(mvert);
2196         MEdge *med, *medge = NULL;
2197         BLI_array_declare(medge);
2198         MPoly *mp, *mpoly = NULL;
2199         BLI_array_declare(mpoly);
2200         MLoop *ml, *mloop = NULL;
2201         BLI_array_declare(mloop);
2202         EdgeHash *ehash = BLI_edgehash_new();
2203         int *newv = NULL, *newe = NULL, *newl = NULL;
2204         int *oldv = NULL, *olde = NULL, *oldl = NULL, *oldp = NULL;
2205         BLI_array_declare(oldv); BLI_array_declare(olde); BLI_array_declare(oldl); BLI_array_declare(oldp);
2206         int i, j, c, totloop, totpoly;
2207         
2208         totloop = dm->numLoopData;
2209         totpoly = dm->numPolyData;
2210         
2211         newv = MEM_callocN(sizeof(int)*dm->numVertData, "newv vtable CDDM_merge_verts");
2212         newe = MEM_callocN(sizeof(int)*dm->numEdgeData, "newv etable CDDM_merge_verts");
2213         newl = MEM_callocN(sizeof(int)*totloop, "newv ltable CDDM_merge_verts");
2214         
2215         /*fill newl with destination vertex indices*/
2216         mv = cddm->mvert;
2217         c = 0;
2218         for (i = 0; i < dm->numVertData; i++, mv++) {
2219                 if (vtargetmap[i] == -1) {
2220                         BLI_array_append(oldv, i);
2221                         newv[i] = c++;
2222                         BLI_array_append(mvert, *mv);
2223                 }
2224         }
2225         
2226         /*now link target vertices to destination indices*/
2227         for (i = 0; i < dm->numVertData; i++) {
2228                 if (vtargetmap[i] != -1) {
2229                         newv[i] = newv[vtargetmap[i]];
2230                 }
2231         }
2232         
2233         /*find-replace merged vertices with target vertices*/   
2234         ml = cddm->mloop;
2235         for (i = 0; i < totloop; i++, ml++) {
2236                 if (vtargetmap[ml->v] != -1) {
2237                         ml->v = vtargetmap[ml->v];
2238                 }
2239         }
2240
2241         /*now go through and fix edges and faces*/
2242         med = cddm->medge;
2243         c = 0;
2244         for (i = 0; i < dm->numEdgeData; i++, med++) {
2245                 
2246                 if (LIKELY(med->v1 != med->v2)) {
2247                         const unsigned int v1 = (vtargetmap[med->v1] != -1) ? vtargetmap[med->v1] : med->v1;
2248                         const unsigned int v2 = (vtargetmap[med->v2] != -1) ? vtargetmap[med->v2] : med->v2;
2249                         void **eh_p= BLI_edgehash_lookup_p(ehash, v1, v2);
2250
2251                         if (eh_p) {
2252                                 newe[i] = GET_INT_FROM_POINTER(*eh_p);
2253                         }
2254                         else {
2255                                 BLI_array_append(olde, i);
2256                                 newe[i] = c;
2257                                 BLI_array_append(medge, *med);
2258                                 BLI_edgehash_insert(ehash, v1, v2, SET_INT_IN_POINTER(c));
2259                                 c++;
2260                         }
2261                 }
2262                 else {
2263                         newe[i] = -1;
2264                 }
2265         }
2266         
2267         mp = cddm->mpoly;
2268         for (i = 0; i < totpoly; i++, mp++) {
2269                 MPoly *mp2;
2270                 
2271                 ml = cddm->mloop + mp->loopstart;
2272
2273                 c = 0;
2274                 for (j = 0; j < mp->totloop; j++, ml++) {
2275                         med = cddm->medge + ml->e;
2276                         if (LIKELY(med->v1 != med->v2)) {
2277                                 newl[j+mp->loopstart] = BLI_array_count(mloop);
2278                                 BLI_array_append(oldl, j+mp->loopstart);
2279                                 BLI_array_append(mloop, *ml);
2280                                 c++;
2281                         }
2282                 }
2283
2284                 if (UNLIKELY(c == 0)) {
2285                         continue;
2286                 }
2287                 
2288                 mp2 = BLI_array_append_r(mpoly, *mp);
2289                 mp2->totloop = c;
2290                 mp2->loopstart = BLI_array_count(mloop) - c;
2291                 
2292                 BLI_array_append(oldp, i);
2293         }
2294         
2295         /*create new cddm*/     
2296         cddm2 = (CDDerivedMesh*) CDDM_from_template((DerivedMesh*)cddm, BLI_array_count(mvert), BLI_array_count(medge), 0, BLI_array_count(mloop), BLI_array_count(mpoly));
2297         
2298         /*update edge indices and copy customdata*/
2299         med = medge;
2300         for (i = 0; i < cddm2->dm.numEdgeData; i++, med++) {
2301                 if (newv[med->v1] != -1)
2302                         med->v1 = newv[med->v1];
2303                 if (newv[med->v2] != -1)
2304                         med->v2 = newv[med->v2];
2305                 
2306                 CustomData_copy_data(&dm->edgeData, &cddm2->dm.edgeData, olde[i], i, 1);
2307         }
2308         
2309         /*update loop indices and copy customdata*/
2310         ml = mloop;
2311         for (i = 0; i < cddm2->dm.numLoopData; i++, ml++) {
2312                 if (newe[ml->e] != -1)
2313                         ml->e = newe[ml->e];
2314                 if (newv[ml->v] != -1)
2315                         ml->v = newv[ml->v];
2316                         
2317                 CustomData_copy_data(&dm->loopData, &cddm2->dm.loopData, oldl[i], i, 1);
2318         }
2319         
2320         /*copy vertex customdata*/      
2321         mv = mvert;
2322         for (i = 0; i < cddm2->dm.numVertData; i++, mv++) {
2323                 CustomData_copy_data(&dm->vertData, &cddm2->dm.vertData, oldv[i], i, 1);
2324         }
2325         
2326         /*copy poly customdata*/
2327         mp = mpoly;
2328         for (i = 0; i < cddm2->dm.numPolyData; i++, mp++) {
2329                 CustomData_copy_data(&dm->polyData, &cddm2->dm.polyData, oldp[i], i, 1);
2330         }
2331         
2332         /*copy over data.  CustomData_add_layer can do this, need to look it up.*/
2333         memcpy(cddm2->mvert, mvert, sizeof(MVert)*BLI_array_count(mvert));
2334         memcpy(cddm2->medge, medge, sizeof(MEdge)*BLI_array_count(medge));
2335         memcpy(cddm2->mloop, mloop, sizeof(MLoop)*BLI_array_count(mloop));
2336         memcpy(cddm2->mpoly, mpoly, sizeof(MPoly)*BLI_array_count(mpoly));
2337         BLI_array_free(mvert); BLI_array_free(medge); BLI_array_free(mloop); BLI_array_free(mpoly);
2338         
2339         if (newv) 
2340                 MEM_freeN(newv); 
2341         if (newe)
2342                 MEM_freeN(newe); 
2343         if (newl)
2344                 MEM_freeN(newl);
2345         if (oldv) 
2346                 MEM_freeN(oldv); 
2347         if (olde) 
2348                 MEM_freeN(olde); 
2349         if (oldl) 
2350                 MEM_freeN(oldl); 
2351         if (oldp) 
2352                 MEM_freeN(oldp);
2353         if (ehash)
2354                 BLI_edgehash_free(ehash, NULL);
2355
2356         /*free old derivedmesh*/
2357         dm->needsFree = 1;
2358         dm->release(dm);
2359         
2360         return (DerivedMesh*)cddm2;
2361 }
2362 #endif
2363
2364 void CDDM_calc_edges_tessface(DerivedMesh *dm)
2365 {
2366         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2367         CustomData edgeData;
2368         EdgeHashIterator *ehi;
2369         MFace *mf = cddm->mface;
2370         MEdge *med;
2371         EdgeHash *eh = BLI_edgehash_new();
2372         int i, *index, numEdges, maxFaces = dm->numTessFaceData;
2373
2374         for (i = 0; i < maxFaces; i++, mf++) {
2375                 if (!BLI_edgehash_haskey(eh, mf->v1, mf->v2))
2376                         BLI_edgehash_insert(eh, mf->v1, mf->v2, NULL);
2377                 if (!BLI_edgehash_haskey(eh, mf->v2, mf->v3))
2378                         BLI_edgehash_insert(eh, mf->v2, mf->v3, NULL);
2379                 
2380                 if (mf->v4) {
2381                         if (!BLI_edgehash_haskey(eh, mf->v3, mf->v4))
2382                                 BLI_edgehash_insert(eh, mf->v3, mf->v4, NULL);
2383                         if (!BLI_edgehash_haskey(eh, mf->v4, mf->v1))
2384                                 BLI_edgehash_insert(eh, mf->v4, mf->v1, NULL);
2385                 }
2386                 else {
2387                         if (!BLI_edgehash_haskey(eh, mf->v3, mf->v1))
2388                                 BLI_edgehash_insert(eh, mf->v3, mf->v1, NULL);
2389                 }
2390         }
2391
2392         numEdges = BLI_edgehash_size(eh);
2393
2394         /* write new edges into a temporary CustomData */
2395         memset(&edgeData, 0, sizeof(edgeData));
2396         CustomData_add_layer(&edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
2397         CustomData_add_layer(&edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
2398
2399         ehi = BLI_edgehashIterator_new(eh);
2400         med = CustomData_get_layer(&edgeData, CD_MEDGE);
2401         index = CustomData_get_layer(&edgeData, CD_ORIGINDEX);
2402         for (i = 0; !BLI_edgehashIterator_isDone(ehi);
2403                 BLI_edgehashIterator_step(ehi), ++i, ++med, ++index) {
2404                 BLI_edgehashIterator_getKey(ehi, &med->v1, &med->v2);
2405
2406                 med->flag = ME_EDGEDRAW|ME_EDGERENDER;
2407                 *index = ORIGINDEX_NONE;
2408         }
2409         BLI_edgehashIterator_free(ehi);
2410
2411         /* free old CustomData and assign new one */
2412         CustomData_free(&dm->edgeData, dm->numEdgeData);
2413         dm->edgeData = edgeData;
2414         dm->numEdgeData = numEdges;
2415
2416         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
2417
2418         BLI_edgehash_free(eh, NULL);
2419 }
2420
2421 /* warning, this uses existing edges but CDDM_calc_edges_tessface() doesn't */
2422 void CDDM_calc_edges(DerivedMesh *dm)
2423 {
2424         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2425         CustomData edgeData;
2426         EdgeHashIterator *ehi;
2427         MPoly *mp = cddm->mpoly;
2428         MLoop *ml;
2429         MEdge *med;
2430         EdgeHash *eh = BLI_edgehash_new();
2431         int v1, v2;
2432         int *eindex;
2433         int i, j, *index, numEdges = cddm->dm.numEdgeData, maxFaces = dm->numPolyData;
2434
2435         eindex = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
2436
2437         med = cddm->medge;
2438         if (med) {
2439                 for (i = 0; i < numEdges; i++, med++) {
2440                         BLI_edgehash_insert(eh, med->v1, med->v2, SET_INT_IN_POINTER(i+1));
2441                 }
2442         }
2443
2444         for (i = 0; i < maxFaces; i++, mp++) {
2445                 ml = cddm->mloop + mp->loopstart;
2446                 for (j = 0; j < mp->totloop; j++, ml++) {
2447                         v1 = ml->v;
2448                         v2 = ME_POLY_LOOP_NEXT(cddm->mloop, mp, j)->v;
2449                         if (!BLI_edgehash_haskey(eh, v1, v2)) {
2450                                 BLI_edgehash_insert(eh, v1, v2, NULL);
2451                         }
2452                 }
2453         }
2454
2455         numEdges = BLI_edgehash_size(eh);
2456
2457         /* write new edges into a temporary CustomData */
2458         memset(&edgeData, 0, sizeof(edgeData));
2459         CustomData_add_layer(&edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
2460         CustomData_add_layer(&edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
2461
2462         ehi = BLI_edgehashIterator_new(eh);
2463         med = CustomData_get_layer(&edgeData, CD_MEDGE);
2464         index = CustomData_get_layer(&edgeData, CD_ORIGINDEX);
2465         for (i = 0; !BLI_edgehashIterator_isDone(ehi);
2466             BLI_edgehashIterator_step(ehi), ++i, ++med, ++index) {
2467                 BLI_edgehashIterator_getKey(ehi, &med->v1, &med->v2);
2468                 j = GET_INT_FROM_POINTER(BLI_edgehashIterator_getValue(ehi));
2469
2470                 med->flag = ME_EDGEDRAW|ME_EDGERENDER;
2471                 *index = j==0 ? ORIGINDEX_NONE : eindex[j-1];
2472
2473                 BLI_edgehashIterator_setValue(ehi, SET_INT_IN_POINTER(i));
2474         }
2475         BLI_edgehashIterator_free(ehi);
2476
2477         /* free old CustomData and assign new one */
2478         CustomData_free(&dm->edgeData, dm->numEdgeData);
2479         dm->edgeData = edgeData;
2480         dm->numEdgeData = numEdges;
2481
2482         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
2483
2484         mp = cddm->mpoly;
2485         for (i = 0; i < maxFaces; i++, mp++) {
2486                 ml = cddm->mloop + mp->loopstart;
2487                 for (j = 0; j < mp->totloop; j++, ml++) {
2488                         v1 = ml->v;
2489                         v2 = ME_POLY_LOOP_NEXT(cddm->mloop, mp, j)->v;
2490                         ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, v1, v2));
2491                 }
2492         }
2493
2494         BLI_edgehash_free(eh, NULL);
2495 }
2496
2497 void CDDM_lower_num_verts(DerivedMesh *dm, int numVerts)
2498 {
2499         if (numVerts < dm->numVertData)
2500                 CustomData_free_elem(&dm->vertData, numVerts, dm->numVertData-numVerts);
2501
2502         dm->numVertData = numVerts;
2503 }
2504
2505 void CDDM_lower_num_edges(DerivedMesh *dm, int numEdges)
2506 {
2507         if (numEdges < dm->numEdgeData)
2508                 CustomData_free_elem(&dm->edgeData, numEdges, dm->numEdgeData-numEdges);
2509
2510         dm->numEdgeData = numEdges;
2511 }
2512
2513 void CDDM_lower_num_tessfaces(DerivedMesh *dm, int numTessFaces)
2514 {
2515         if (numTessFaces < dm->numTessFaceData)
2516                 CustomData_free_elem(&dm->faceData, numTessFaces, dm->numTessFaceData-numTessFaces);
2517
2518         dm->numTessFaceData = numTessFaces;
2519 }
2520
2521 void CDDM_lower_num_polys(DerivedMesh *dm, int numPolys)
2522 {
2523         if (numPolys < dm->numPolyData)
2524                 CustomData_free_elem(&dm->polyData, numPolys, dm->numPolyData-numPolys);
2525
2526         dm->numPolyData = numPolys;
2527 }
2528
2529 /* mesh element access functions */
2530
2531 MVert *CDDM_get_vert(DerivedMesh *dm, int index)
2532 {
2533         return &((CDDerivedMesh*)dm)->mvert[index];
2534 }
2535
2536 MEdge *CDDM_get_edge(DerivedMesh *dm, int index)
2537 {
2538         return &((CDDerivedMesh*)dm)->medge[index];
2539 }
2540
2541 MFace *CDDM_get_tessface(DerivedMesh *dm, int index)
2542 {
2543         return &((CDDerivedMesh*)dm)->mface[index];
2544 }
2545
2546 MLoop *CDDM_get_loop(DerivedMesh *dm, int index)
2547 {
2548         return &((CDDerivedMesh*)dm)->mloop[index];
2549 }
2550
2551 MPoly *CDDM_get_poly(DerivedMesh *dm, int index)
2552 {
2553         return &((CDDerivedMesh*)dm)->mpoly[index];
2554 }
2555
2556 /* array access functions */
2557
2558 MVert *CDDM_get_verts(DerivedMesh *dm)
2559 {
2560         return ((CDDerivedMesh*)dm)->mvert;
2561 }
2562
2563 MEdge *CDDM_get_edges(DerivedMesh *dm)
2564 {
2565         return ((CDDerivedMesh*)dm)->medge;
2566 }
2567
2568 MFace *CDDM_get_tessfaces(DerivedMesh *dm)
2569 {
2570         return ((CDDerivedMesh*)dm)->mface;
2571 }
2572
2573 MLoop *CDDM_get_loops(DerivedMesh *dm)
2574 {
2575         return ((CDDerivedMesh*)dm)->mloop;
2576 }
2577
2578 MPoly *CDDM_get_polys(DerivedMesh *dm)
2579 {
2580         return ((CDDerivedMesh*)dm)->mpoly;
2581 }
2582
2583 void CDDM_tessfaces_to_faces(DerivedMesh *dm)
2584 {
2585         /*converts mfaces to mpolys/mloops*/
2586         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2587         MFace *mf;
2588         MEdge *me;
2589         EdgeHash *eh = BLI_edgehash_new();
2590         int i, totloop;
2591
2592         /* ... on second thaughts, better comment this and assume caller knows edge state. */
2593 #if 0
2594         /* ensure we have all the edges we need */
2595         CDDM_calc_edges_tessface(dm);
2596 #else
2597 #  ifndef NDEBUG
2598         {
2599                 /* ensure we have correct edges on non release builds */
2600                 i = cddm->dm.numEdgeData;
2601                 CDDM_calc_edges_tessface(dm);
2602                 BLI_assert(cddm->dm.numEdgeData == i);
2603         }
2604 #  endif
2605 #endif
2606
2607         /*build edge hash*/
2608         me = cddm->medge;
2609         for (i = 0; i < cddm->dm.numEdgeData; i++, me++) {
2610                 BLI_edgehash_insert(eh, me->v1, me->v2, SET_INT_IN_POINTER(i));
2611         }
2612
2613         mf = cddm->mface;
2614         totloop = 0;
2615         for (i = 0; i < cddm->dm.numTessFaceData; i++, mf++) {
2616                 totloop += mf->v4 ? 4 : 3;
2617         }
2618
2619         CustomData_free(&cddm->dm.polyData, cddm->dm.numPolyData);
2620         CustomData_free(&cddm->dm.loopData, cddm->dm.numLoopData);
2621         
2622         cddm->dm.numLoopData = totloop;
2623         cddm->dm.numPolyData = cddm->dm.numTessFaceData;
2624
2625         if (totloop) {
2626                 MLoop *ml;
2627                 MPoly *mp;
2628                 int l, *polyindex;
2629
2630                 cddm->mloop = MEM_callocN(sizeof(MLoop)*totloop, "cddm->mloop in CDDM_tessfaces_to_faces");
2631                 cddm->mpoly = MEM_callocN(sizeof(MPoly)*cddm->dm.numTessFaceData, "cddm->mpoly in CDDM_tessfaces_to_faces");
2632
2633                 CustomData_add_layer(&cddm->dm.loopData, CD_MLOOP, CD_ASSIGN, cddm->mloop, totloop);
2634                 CustomData_add_layer(&cddm->dm.polyData, CD_MPOLY, CD_ASSIGN, cddm->mpoly, cddm->dm.numPolyData);
2635                 CustomData_merge(&cddm->dm.faceData, &cddm->dm.polyData,
2636                         CD_MASK_ORIGINDEX, CD_DUPLICATE, cddm->dm.numTessFaceData);
2637
2638                 polyindex = CustomData_get_layer(&cddm->dm.faceData, CD_POLYINDEX);
2639
2640                 mf = cddm->mface;
2641                 mp = cddm->mpoly;
2642                 ml = cddm->mloop;
2643                 l = 0;
2644                 for (i = 0; i < cddm->dm.numTessFaceData; i++, mf++, mp++, polyindex++) {
2645                         mp->flag = mf->flag;
2646                         mp->loopstart = l;
2647                         mp->mat_nr = mf->mat_nr;
2648                         mp->totloop = mf->v4 ? 4 : 3;
2649
2650                         ml->v = mf->v1;
2651                         ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, mf->v1, mf->v2));
2652                         ml++, l++;
2653
2654                         ml->v = mf->v2;
2655                         ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, mf->v2, mf->v3));
2656                         ml++, l++;
2657
2658                         ml->v = mf->v3;
2659                         ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, mf->v3, mf->v4?mf->v4:mf->v1));
2660                         ml++, l++;
2661
2662                         if (mf->v4) {
2663                                 ml->v = mf->v4;
2664                                 ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, mf->v4, mf->v1));
2665                                 ml++, l++;
2666                         }
2667
2668                         *polyindex = i;
2669                 }
2670         }
2671
2672         BLI_edgehash_free(eh, NULL);
2673 }
2674
2675 void CDDM_set_mvert(DerivedMesh *dm, MVert *mvert)
2676 {
2677         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2678         
2679         if (!CustomData_has_layer(&dm->vertData, CD_MVERT))
2680                 CustomData_add_layer(&dm->vertData, CD_MVERT, CD_ASSIGN, mvert, dm->numVertData);
2681                                 
2682         cddm->mvert = mvert;
2683 }
2684
2685 void CDDM_set_medge(DerivedMesh *dm, MEdge *medge)
2686 {
2687         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2688
2689         if (!CustomData_has_layer(&dm->edgeData, CD_MEDGE))
2690                 CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_ASSIGN, medge, dm->numEdgeData);
2691
2692         cddm->medge = medge;
2693 }
2694
2695 void CDDM_set_mface(DerivedMesh *dm, MFace *mface)
2696 {
2697         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2698
2699         if (!CustomData_has_layer(&dm->faceData, CD_MFACE))
2700                 CustomData_add_layer(&dm->faceData, CD_MFACE, CD_ASSIGN, mface, dm->numTessFaceData);
2701
2702         cddm->mface = mface;
2703 }
2704
2705 void CDDM_set_mloop(DerivedMesh *dm, MLoop *mloop)
2706 {
2707         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2708
2709         if (!CustomData_has_layer(&dm->loopData, CD_MLOOP))
2710                 CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_ASSIGN, mloop, dm->numLoopData);
2711
2712         cddm->mloop = mloop;
2713 }
2714
2715 void CDDM_set_mpoly(DerivedMesh *dm, MPoly *mpoly)
2716 {
2717         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
2718
2719         if (!CustomData_has_layer(&dm->polyData, CD_MPOLY))
2720                 CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_ASSIGN, mpoly, dm->numPolyData);
2721
2722         cddm->mpoly = mpoly;
2723 }