Sculpt: svn merge https://svn.blender.org/svnroot/bf-blender/trunk/blender -r24330...
[blender.git] / source / blender / blenkernel / intern / cdderivedmesh.c
1 /*
2 * $Id$
3 *
4 * ***** BEGIN GPL LICENSE BLOCK *****
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software  Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 *
20 * The Original Code is Copyright (C) 2006 Blender Foundation.
21 * All rights reserved.
22 *
23 * The Original Code is: all of this file.
24 *
25 * Contributor(s): Ben Batt <benbatt@gmail.com>
26 *
27 * ***** END GPL LICENSE BLOCK *****
28 *
29 * Implementation of CDDerivedMesh.
30 *
31 * BKE_cdderivedmesh.h contains the function prototypes for this file.
32 *
33 */ 
34
35 /* TODO maybe BIF_gl.h should include string.h? */
36 #include <string.h>
37 #include "BIF_gl.h"
38
39 #include "BKE_cdderivedmesh.h"
40 #include "BKE_customdata.h"
41 #include "BKE_DerivedMesh.h"
42 #include "BKE_displist.h"
43 #include "BKE_global.h"
44 #include "BKE_mesh.h"
45 #include "BKE_multires.h"
46 #include "BKE_utildefines.h"
47
48 #include "BLI_math.h"
49 #include "BLI_blenlib.h"
50 #include "BLI_edgehash.h"
51 #include "BLI_editVert.h"
52 #include "BLI_pbvh.h"
53
54 #include "DNA_mesh_types.h"
55 #include "DNA_meshdata_types.h"
56 #include "DNA_modifier_types.h"
57 #include "DNA_object_fluidsim.h"
58 #include "DNA_object_types.h"
59 #include "DNA_scene_types.h"
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
81         /* Cached */
82         struct PBVH *pbvh;
83         /* Mesh connectivity */
84         struct ListBase *fmap;
85         struct IndexNode *fmap_mem;
86 } CDDerivedMesh;
87
88 /**************** DerivedMesh interface functions ****************/
89 static int cdDM_getNumVerts(DerivedMesh *dm)
90 {
91         return dm->numVertData;
92 }
93
94 static int cdDM_getNumEdges(DerivedMesh *dm)
95 {
96         return dm->numEdgeData;
97 }
98
99 static int cdDM_getNumFaces(DerivedMesh *dm)
100 {
101         return dm->numFaceData;
102 }
103
104 static void cdDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
105 {
106         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
107         *vert_r = cddm->mvert[index];
108 }
109
110 static void cdDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
111 {
112         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
113         *edge_r = cddm->medge[index];
114 }
115
116 static void cdDM_getFace(DerivedMesh *dm, int index, MFace *face_r)
117 {
118         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
119         *face_r = cddm->mface[index];
120 }
121
122 static void cdDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
123 {
124         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
125         memcpy(vert_r, cddm->mvert, sizeof(*vert_r) * dm->numVertData);
126 }
127
128 static void cdDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
129 {
130         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
131         memcpy(edge_r, cddm->medge, sizeof(*edge_r) * dm->numEdgeData);
132 }
133
134 static void cdDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
135 {
136         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
137         memcpy(face_r, cddm->mface, sizeof(*face_r) * dm->numFaceData);
138 }
139
140 static void cdDM_getMinMax(DerivedMesh *dm, float min_r[3], float max_r[3])
141 {
142         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
143         int i;
144
145         if (dm->numVertData) {
146                 for (i=0; i<dm->numVertData; i++) {
147                         DO_MINMAX(cddm->mvert[i].co, min_r, max_r);
148                 }
149         } else {
150                 min_r[0] = min_r[1] = min_r[2] = max_r[0] = max_r[1] = max_r[2] = 0.0;
151         }
152 }
153
154 static void cdDM_getVertCo(DerivedMesh *dm, int index, float co_r[3])
155 {
156         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
157
158         VECCOPY(co_r, cddm->mvert[index].co);
159 }
160
161 static void cdDM_getVertCos(DerivedMesh *dm, float (*cos_r)[3])
162 {
163         MVert *mv = CDDM_get_verts(dm);
164         int i;
165
166         for(i = 0; i < dm->numVertData; i++, mv++)
167                 VECCOPY(cos_r[i], mv->co);
168 }
169
170 static void cdDM_getVertNo(DerivedMesh *dm, int index, float no_r[3])
171 {
172         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
173         short *no = cddm->mvert[index].no;
174
175         no_r[0] = no[0]/32767.f;
176         no_r[1] = no[1]/32767.f;
177         no_r[2] = no[2]/32767.f;
178 }
179
180 static ListBase *cdDM_getFaceMap(DerivedMesh *dm)
181 {
182         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
183
184         if(!cddm->fmap) {
185                 create_vert_face_map(&cddm->fmap, &cddm->fmap_mem, cddm->mface,
186                                      dm->getNumVerts(dm), dm->getNumFaces(dm));
187                 printf("rebuild fmap\n");
188         }
189
190         return cddm->fmap;
191 }
192
193 static struct PBVH *cdDM_getPBVH(DerivedMesh *dm)
194 {
195         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
196
197         if(!cddm->pbvh) {
198                 cddm->pbvh = BLI_pbvh_new();
199                 BLI_pbvh_build(cddm->pbvh, cddm->mface, cddm->mvert,
200                                dm->getNumFaces(dm), dm->getNumVerts(dm));
201                 printf("rebuild pbvh\n");
202         }
203
204         return cddm->pbvh;
205 }
206
207 static void cdDM_drawVerts(DerivedMesh *dm)
208 {
209         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
210         MVert *mv = cddm->mvert;
211         int i;
212
213         if( GPU_buffer_legacy(dm) ) {
214                 glBegin(GL_POINTS);
215                 for(i = 0; i < dm->numVertData; i++, mv++)
216                         glVertex3fv(mv->co);
217                 glEnd();
218         }
219         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
220                 GPU_vertex_setup(dm);
221                 if( !GPU_buffer_legacy(dm) ) {
222                         glDrawArrays(GL_POINTS,0,dm->drawObject->nelements);
223                 }
224                 GPU_buffer_unbind();
225         }
226 }
227
228 static void cdDM_drawUVEdges(DerivedMesh *dm)
229 {
230         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
231         MFace *mf = cddm->mface;
232         MTFace *tf = DM_get_face_data_layer(dm, CD_MTFACE);
233         int i;
234
235         if(mf) {
236                 if( GPU_buffer_legacy(dm) ) {
237                         glBegin(GL_LINES);
238                         for(i = 0; i < dm->numFaceData; i++, mf++, tf++) {
239                                 if(!(mf->flag&ME_HIDE)) {
240                                         glVertex2fv(tf->uv[0]);
241                                         glVertex2fv(tf->uv[1]);
242
243                                         glVertex2fv(tf->uv[1]);
244                                         glVertex2fv(tf->uv[2]);
245
246                                         if(!mf->v4) {
247                                                 glVertex2fv(tf->uv[2]);
248                                                 glVertex2fv(tf->uv[0]);
249                                         } else {
250                                                 glVertex2fv(tf->uv[2]);
251                                                 glVertex2fv(tf->uv[3]);
252
253                                                 glVertex2fv(tf->uv[3]);
254                                                 glVertex2fv(tf->uv[0]);
255                                         }
256                                 }
257                         }
258                         glEnd();
259                 }
260                 else {
261                         int prevstart = 0;
262                         int prevdraw = 1;
263                         int draw = 1;
264                         int curpos = 0;
265
266                         GPU_uvedge_setup(dm);
267                         if( !GPU_buffer_legacy(dm) ) {
268                                 for(i = 0; i < dm->numFaceData; i++, mf++) {
269                                         if(mf->flag&ME_LOOSEEDGE) {
270                                                 draw = 1;
271                                         } 
272                                         else {
273                                                 draw = 0;
274                                         }
275                                         if( prevdraw != draw ) {
276                                                 if( prevdraw > 0 && (curpos-prevstart) > 0) {
277                                                         glDrawArrays(GL_LINES,prevstart,curpos-prevstart);
278                                                 }
279                                                 prevstart = curpos;
280                                         }
281                                         if( mf->v4 ) {
282                                                 curpos += 8;
283                                         }
284                                         else {
285                                                 curpos += 6;
286                                         }
287                                         prevdraw = draw;
288                                 }
289                                 if( prevdraw > 0 && (curpos-prevstart) > 0 ) {
290                                         glDrawArrays(GL_LINES,prevstart,curpos-prevstart);
291                                 }
292                         }
293                         GPU_buffer_unbind();
294                 }
295         }
296 }
297
298 static void cdDM_drawEdges(DerivedMesh *dm, int drawLooseEdges)
299 {
300         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
301         MVert *mvert = cddm->mvert;
302         MEdge *medge = cddm->medge;
303         int i;
304         
305         if( GPU_buffer_legacy(dm) ) {
306                 DEBUG_VBO( "Using legacy code. cdDM_drawEdges\n" );
307                 glBegin(GL_LINES);
308                 for(i = 0; i < dm->numEdgeData; i++, medge++) {
309                         if((medge->flag&ME_EDGEDRAW)
310                            && (drawLooseEdges || !(medge->flag&ME_LOOSEEDGE))) {
311                                 glVertex3fv(mvert[medge->v1].co);
312                                 glVertex3fv(mvert[medge->v2].co);
313                         }
314                 }
315                 glEnd();
316         }
317         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
318                 int prevstart = 0;
319                 int prevdraw = 1;
320                 int draw = 1;
321
322                 GPU_edge_setup(dm);
323                 if( !GPU_buffer_legacy(dm) ) {
324                         for(i = 0; i < dm->numEdgeData; i++, medge++) {
325                                 if((medge->flag&ME_EDGEDRAW)
326                                    && (drawLooseEdges || !(medge->flag&ME_LOOSEEDGE))) {
327                                         draw = 1;
328                                 } 
329                                 else {
330                                         draw = 0;
331                                 }
332                                 if( prevdraw != draw ) {
333                                         if( prevdraw > 0 && (i-prevstart) > 0 ) {
334                                                 GPU_buffer_draw_elements( dm->drawObject->edges, GL_LINES, prevstart*2, (i-prevstart)*2  );
335                                         }
336                                         prevstart = i;
337                                 }
338                                 prevdraw = draw;
339                         }
340                         if( prevdraw > 0 && (i-prevstart) > 0 ) {
341                                 GPU_buffer_draw_elements( dm->drawObject->edges, GL_LINES, prevstart*2, (i-prevstart)*2  );
342                         }
343                 }
344                 GPU_buffer_unbind();
345         }
346 }
347
348 static void cdDM_drawLooseEdges(DerivedMesh *dm)
349 {
350         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
351         MVert *mvert = cddm->mvert;
352         MEdge *medge = cddm->medge;
353         int i;
354
355         if( GPU_buffer_legacy(dm) ) {
356                 DEBUG_VBO( "Using legacy code. cdDM_drawLooseEdges\n" );
357                 glBegin(GL_LINES);
358                 for(i = 0; i < dm->numEdgeData; i++, medge++) {
359                         if(medge->flag&ME_LOOSEEDGE) {
360                                 glVertex3fv(mvert[medge->v1].co);
361                                 glVertex3fv(mvert[medge->v2].co);
362                         }
363                 }
364                 glEnd();
365         }
366         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
367                 int prevstart = 0;
368                 int prevdraw = 1;
369                 int draw = 1;
370
371                 GPU_edge_setup(dm);
372                 if( !GPU_buffer_legacy(dm) ) {
373                         for(i = 0; i < dm->numEdgeData; i++, medge++) {
374                                 if(medge->flag&ME_LOOSEEDGE) {
375                                         draw = 1;
376                                 } 
377                                 else {
378                                         draw = 0;
379                                 }
380                                 if( prevdraw != draw ) {
381                                         if( prevdraw > 0 && (i-prevstart) > 0) {
382                                                 GPU_buffer_draw_elements( dm->drawObject->edges, GL_LINES, prevstart*2, (i-prevstart)*2  );
383                                         }
384                                         prevstart = i;
385                                 }
386                                 prevdraw = draw;
387                         }
388                         if( prevdraw > 0 && (i-prevstart) > 0 ) {
389                                 GPU_buffer_draw_elements( dm->drawObject->edges, GL_LINES, prevstart*2, (i-prevstart)*2  );
390                         }
391                 }
392                 GPU_buffer_unbind();
393         }
394 }
395
396 static int nodes_drawn = 0;
397 static int is_partial = 0;
398 /* XXX: Just a temporary replacement for the real drawing code */
399 static void draw_partial_cb(PBVHNode *node, void *data)
400 {
401         /* XXX: Just some quick code to show leaf nodes in different colors */
402         /*float col[3]; int i;
403         if(is_partial) {
404                 col[0] = (rand() / (float)RAND_MAX); col[1] = col[2] = 0.6;
405         }
406         else {
407                 srand((long long)data_v);
408                 for(i = 0; i < 3; ++i)
409                         col[i] = (rand() / (float)RAND_MAX) * 0.3 + 0.7;
410         }
411         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, col);
412
413         glColor3f(1, 0, 0);*/
414         GPU_draw_buffers(BLI_pbvh_node_get_draw_buffers(node));
415         ++nodes_drawn;
416 }
417
418 /* Adapted from:
419    http://www.gamedev.net/community/forums/topic.asp?topic_id=512123
420    Returns true if the AABB is at least partially within the frustum
421    (ok, not a real frustum), false otherwise.
422 */
423 int planes_contain_AABB(PBVHNode *node, void *data)
424 {
425         float (*planes)[4] = data;
426         int i, axis;
427         float vmin[3], vmax[3], bb_min[3], bb_max[3];
428
429         BLI_pbvh_node_get_BB(node, bb_min, bb_max);
430
431         for(i = 0; i < 4; ++i) { 
432                 for(axis = 0; axis < 3; ++axis) {
433                         if(planes[i][axis] > 0) { 
434                                 vmin[axis] = bb_min[axis];
435                                 vmax[axis] = bb_max[axis];
436                         }
437                         else {
438                                 vmin[axis] = bb_max[axis];
439                                 vmax[axis] = bb_min[axis];
440                         }
441                 }
442                 
443                 if(dot_v3v3(planes[i], vmin) + planes[i][3] > 0)
444                         return 0;
445         } 
446
447         return 1;
448 }
449
450 static void cdDM_drawFacesSolid(DerivedMesh *dm,
451                                 float (*partial_redraw_planes)[4],
452                                 int (*setMaterial)(int, void *attribs))
453 {
454         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
455         MVert *mvert = cddm->mvert;
456         MFace *mface = cddm->mface;
457         float *nors= dm->getFaceDataArray(dm, CD_NORMAL);
458         int a, glmode = -1, shademodel = -1, matnr = -1, drawCurrentMat = 1;
459
460 #define PASSVERT(index) {                                               \
461         if(shademodel == GL_SMOOTH) {                           \
462                 short *no = mvert[index].no;                    \
463                 glNormal3sv(no);                                                \
464         }                                                                                       \
465         glVertex3fv(mvert[index].co);   \
466 }
467
468         if(cddm->pbvh) {
469                 float (*face_nors)[3] = CustomData_get_layer(&dm->faceData, CD_NORMAL);
470
471                 BLI_pbvh_update(cddm->pbvh, PBVH_UpdateNormals|PBVH_UpdateDrawBuffers,
472                         face_nors);
473
474                 /* should be per face */
475                 if(dm->numFaceData && mface->flag & ME_SMOOTH)
476                         glShadeModel(GL_SMOOTH);
477
478                 if(partial_redraw_planes) {
479                         BLI_pbvh_search_callback(cddm->pbvh, planes_contain_AABB,
480                                         partial_redraw_planes, draw_partial_cb, NULL);
481                 }
482                 else {
483                         BLI_pbvh_search_callback(cddm->pbvh, NULL, NULL,
484                                         draw_partial_cb, NULL);
485                 }
486
487                 is_partial = !!partial_redraw_planes;
488
489                 //printf("nodes drawn=%d\n", nodes_drawn);
490                 nodes_drawn = 0;
491
492                 glShadeModel(GL_FLAT);
493
494                 return;
495         }
496
497         if( GPU_buffer_legacy(dm) ) {
498                 DEBUG_VBO( "Using legacy code. cdDM_drawFacesSolid\n" );
499                 glBegin(glmode = GL_QUADS);
500                 for(a = 0; a < dm->numFaceData; a++, mface++) {
501                         int new_glmode, new_matnr, new_shademodel;
502
503                         new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
504                         new_matnr = mface->mat_nr + 1;
505                         new_shademodel = (mface->flag & ME_SMOOTH)?GL_SMOOTH:GL_FLAT;
506                         
507                         if(new_glmode != glmode || new_matnr != matnr
508                            || new_shademodel != shademodel) {
509                                 glEnd();
510
511                                 drawCurrentMat = setMaterial(matnr = new_matnr, NULL);
512
513                                 glShadeModel(shademodel = new_shademodel);
514                                 glBegin(glmode = new_glmode);
515                         } 
516                         
517                         if(drawCurrentMat) {
518                                 if(shademodel == GL_FLAT) {
519                                         if (nors) {
520                                                 glNormal3fv(nors);
521                                         }
522                                         else {
523                                                 /* TODO make this better (cache facenormals as layer?) */
524                                                 float nor[3];
525                                                 if(mface->v4) {
526                                                         normal_quad_v3( nor,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co);
527                                                 } else {
528                                                         normal_tri_v3( nor,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co);
529                                                 }
530                                                 glNormal3fv(nor);
531                                         }
532                                 }
533
534                                 PASSVERT(mface->v1);
535                                 PASSVERT(mface->v2);
536                                 PASSVERT(mface->v3);
537                                 if(mface->v4) {
538                                         PASSVERT(mface->v4);
539                                 }
540                         }
541
542                         if(nors) nors += 3;
543                 }
544                 glEnd();
545         }
546         else {  /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
547                 GPU_vertex_setup( dm );
548                 GPU_normal_setup( dm );
549                 if( !GPU_buffer_legacy(dm) ) {
550                         glShadeModel(GL_SMOOTH);
551                         for( a = 0; a < dm->drawObject->nmaterials; a++ ) {
552                                 if( setMaterial(dm->drawObject->materials[a].mat_nr+1, NULL) )
553                                         glDrawArrays(GL_TRIANGLES, dm->drawObject->materials[a].start, dm->drawObject->materials[a].end-dm->drawObject->materials[a].start);
554                         }
555                 }
556                 GPU_buffer_unbind( );
557         }
558
559 #undef PASSVERT
560         glShadeModel(GL_FLAT);
561 }
562
563 static void cdDM_drawFacesColored(DerivedMesh *dm, int useTwoSided, unsigned char *col1, unsigned char *col2)
564 {
565         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
566         int a, glmode;
567         unsigned char *cp1, *cp2;
568         MVert *mvert = cddm->mvert;
569         MFace *mface = cddm->mface;
570
571         cp1 = col1;
572         if(col2) {
573                 cp2 = col2;
574         } else {
575                 cp2 = NULL;
576                 useTwoSided = 0;
577         }
578
579         /* there's a conflict here... twosided colors versus culling...? */
580         /* defined by history, only texture faces have culling option */
581         /* we need that as mesh option builtin, next to double sided lighting */
582         if(col1 && col2)
583                 glEnable(GL_CULL_FACE);
584
585         if( GPU_buffer_legacy(dm) ) {
586                 DEBUG_VBO( "Using legacy code. cdDM_drawFacesColored\n" );
587                 glShadeModel(GL_SMOOTH);
588                 glBegin(glmode = GL_QUADS);
589                 for(a = 0; a < dm->numFaceData; a++, mface++, cp1 += 16) {
590                         int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
591
592                         if(new_glmode != glmode) {
593                                 glEnd();
594                                 glBegin(glmode = new_glmode);
595                         }
596                                 
597                         glColor3ub(cp1[0], cp1[1], cp1[2]);
598                         glVertex3fv(mvert[mface->v1].co);
599                         glColor3ub(cp1[4], cp1[5], cp1[6]);
600                         glVertex3fv(mvert[mface->v2].co);
601                         glColor3ub(cp1[8], cp1[9], cp1[10]);
602                         glVertex3fv(mvert[mface->v3].co);
603                         if(mface->v4) {
604                                 glColor3ub(cp1[12], cp1[13], cp1[14]);
605                                 glVertex3fv(mvert[mface->v4].co);
606                         }
607                                 
608                         if(useTwoSided) {
609                                 glColor3ub(cp2[8], cp2[9], cp2[10]);
610                                 glVertex3fv(mvert[mface->v3].co );
611                                 glColor3ub(cp2[4], cp2[5], cp2[6]);
612                                 glVertex3fv(mvert[mface->v2].co );
613                                 glColor3ub(cp2[0], cp2[1], cp2[2]);
614                                 glVertex3fv(mvert[mface->v1].co );
615                                 if(mface->v4) {
616                                         glColor3ub(cp2[12], cp2[13], cp2[14]);
617                                         glVertex3fv(mvert[mface->v4].co );
618                                 }
619                         }
620                         if(col2) cp2 += 16;
621                 }
622                 glEnd();
623         }
624         else { /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
625                 GPU_color4_upload(dm,cp1);
626                 GPU_vertex_setup(dm);
627                 GPU_color_setup(dm);
628                 if( !GPU_buffer_legacy(dm) ) {
629                         glShadeModel(GL_SMOOTH);
630                         glDrawArrays(GL_TRIANGLES, 0, dm->drawObject->nelements);
631
632                         if( useTwoSided ) {
633                                 GPU_color4_upload(dm,cp2);
634                                 GPU_color_setup(dm);
635                                 glCullFace(GL_FRONT);
636                                 glDrawArrays(GL_TRIANGLES, 0, dm->drawObject->nelements);
637                                 glCullFace(GL_BACK);
638                         }
639                 }
640                 GPU_buffer_unbind();
641         }
642
643         glShadeModel(GL_FLAT);
644         glDisable(GL_CULL_FACE);
645 }
646
647 static void cdDM_drawFacesTex_common(DerivedMesh *dm,
648                int (*drawParams)(MTFace *tface, MCol *mcol, int matnr),
649                int (*drawParamsMapped)(void *userData, int index),
650                void *userData) 
651 {
652         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
653         MVert *mv = cddm->mvert;
654         MFace *mf = DM_get_face_data_layer(dm, CD_MFACE);
655         MCol *realcol = dm->getFaceDataArray(dm, CD_TEXTURE_MCOL);
656         float *nors= dm->getFaceDataArray(dm, CD_NORMAL);
657         MTFace *tf = DM_get_face_data_layer(dm, CD_MTFACE);
658         int i, j, orig, *index = DM_get_face_data_layer(dm, CD_ORIGINDEX);
659         int startFace = 0, lastFlag = 0xdeadbeef;
660         MCol *mcol = dm->getFaceDataArray(dm, CD_WEIGHT_MCOL);
661         if(!mcol)
662                 mcol = dm->getFaceDataArray(dm, CD_MCOL);
663
664         if( GPU_buffer_legacy(dm) ) {
665                 DEBUG_VBO( "Using legacy code. cdDM_drawFacesTex_common\n" );
666                 for(i = 0; i < dm->numFaceData; i++, mf++) {
667                         MVert *mvert;
668                         int flag;
669                         unsigned char *cp = NULL;
670
671                         if(drawParams) {
672                                 flag = drawParams(tf? &tf[i]: NULL, mcol? &mcol[i*4]: NULL, mf->mat_nr);
673                         }
674                         else {
675                                 if(index) {
676                                         orig = *index++;
677                                         if(orig == ORIGINDEX_NONE)              { if(nors) nors += 3; continue; }
678                                         if(drawParamsMapped) flag = drawParamsMapped(userData, orig);
679                                         else    { if(nors) nors += 3; continue; }
680                                 }
681                                 else
682                                         if(drawParamsMapped) flag = drawParamsMapped(userData, i);
683                                         else    { if(nors) nors += 3; continue; }
684                         }
685                         
686                         if(flag != 0) {
687                                 if (flag==1 && mcol)
688                                         cp= (unsigned char*) &mcol[i*4];
689
690                                 if(!(mf->flag&ME_SMOOTH)) {
691                                         if (nors) {
692                                                 glNormal3fv(nors);
693                                         }
694                                         else {
695                                                 float nor[3];
696                                                 if(mf->v4) {
697                                                         normal_quad_v3( nor,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co, mv[mf->v4].co);
698                                                 } else {
699                                                         normal_tri_v3( nor,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co);
700                                                 }
701                                                 glNormal3fv(nor);
702                                         }
703                                 }
704
705                                 glBegin(mf->v4?GL_QUADS:GL_TRIANGLES);
706                                 if(tf) glTexCoord2fv(tf[i].uv[0]);
707                                 if(cp) glColor3ub(cp[3], cp[2], cp[1]);
708                                 mvert = &mv[mf->v1];
709                                 if(mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
710                                 glVertex3fv(mvert->co);
711                                         
712                                 if(tf) glTexCoord2fv(tf[i].uv[1]);
713                                 if(cp) glColor3ub(cp[7], cp[6], cp[5]);
714                                 mvert = &mv[mf->v2];
715                                 if(mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
716                                 glVertex3fv(mvert->co);
717
718                                 if(tf) glTexCoord2fv(tf[i].uv[2]);
719                                 if(cp) glColor3ub(cp[11], cp[10], cp[9]);
720                                 mvert = &mv[mf->v3];
721                                 if(mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
722                                 glVertex3fv(mvert->co);
723
724                                 if(mf->v4) {
725                                         if(tf) glTexCoord2fv(tf[i].uv[3]);
726                                         if(cp) glColor3ub(cp[15], cp[14], cp[13]);
727                                         mvert = &mv[mf->v4];
728                                         if(mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
729                                         glVertex3fv(mvert->co);
730                                 }
731                                 glEnd();
732                         }
733                         
734                         if(nors) nors += 3;
735                 }
736         } else { /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
737                 MCol *col = realcol;
738                 if(!col)
739                         col = mcol;
740
741                 GPU_vertex_setup( dm );
742                 GPU_normal_setup( dm );
743                 GPU_uv_setup( dm );
744                 if( col != 0 ) {
745                         /*if( realcol && dm->drawObject->colType == CD_TEXTURE_MCOL )  {
746                                 col = 0;
747                         } else if( mcol && dm->drawObject->colType == CD_MCOL ) {
748                                 col = 0;
749                         }
750                         
751                         if( col != 0 ) {*/
752                                 unsigned char *colors = MEM_mallocN(dm->getNumFaces(dm)*4*3*sizeof(unsigned char), "cdDM_drawFacesTex_common");
753                                 for( i=0; i < dm->getNumFaces(dm); i++ ) {
754                                         for( j=0; j < 4; j++ ) {
755                                                 colors[i*12+j*3] = col[i*4+j].r;
756                                                 colors[i*12+j*3+1] = col[i*4+j].g;
757                                                 colors[i*12+j*3+2] = col[i*4+j].b;
758                                         }
759                                 }
760                                 GPU_color3_upload(dm,colors);
761                                 MEM_freeN(colors);
762                                 if(realcol)
763                                         dm->drawObject->colType = CD_TEXTURE_MCOL;
764                                 else if(mcol)
765                                         dm->drawObject->colType = CD_MCOL;
766                         //}
767                         GPU_color_setup( dm );
768                 }
769
770                 if( !GPU_buffer_legacy(dm) ) {
771                         glShadeModel( GL_SMOOTH );
772                         for(i = 0; i < dm->drawObject->nelements/3; i++) {
773                                 int actualFace = dm->drawObject->faceRemap[i];
774                                 int flag = 1;
775
776                                 if(drawParams) {
777                                         flag = drawParams(tf? &tf[actualFace]: NULL, mcol? &mcol[actualFace*4]: NULL, mf[actualFace].mat_nr);
778                                 }
779                                 else {
780                                         if(index) {
781                                                 orig = index[actualFace];
782                                                 if(drawParamsMapped)
783                                                         flag = drawParamsMapped(userData, orig);
784                                         }
785                                         else
786                                                 if(drawParamsMapped)
787                                                         flag = drawParamsMapped(userData, actualFace);
788                                 }
789                                 if( flag != lastFlag ) {
790                                         if( startFace < i ) {
791                                                 if( lastFlag != 0 ) { /* if the flag is 0 it means the face is hidden or invisible */
792                                                         if (lastFlag==1 && mcol)
793                                                                 GPU_color_switch(1);
794                                                         else
795                                                                 GPU_color_switch(0);
796                                                         glDrawArrays(GL_TRIANGLES,startFace*3,(i-startFace)*3);
797                                                 }
798                                         }
799                                         lastFlag = flag;
800                                         startFace = i;
801                                 }
802                         }
803                         if( startFace < dm->drawObject->nelements/3 ) {
804                                 if( lastFlag != 0 ) { /* if the flag is 0 it means the face is hidden or invisible */
805                                         if (lastFlag==1 && mcol)
806                                                 GPU_color_switch(1);
807                                         else
808                                                 GPU_color_switch(0);
809                                         glDrawArrays(GL_TRIANGLES,startFace*3,dm->drawObject->nelements-startFace*3);
810                                 }
811                         }
812                 }
813
814                 GPU_buffer_unbind();
815                 glShadeModel( GL_FLAT );
816         }
817 }
818
819 static void cdDM_drawFacesTex(DerivedMesh *dm, int (*setDrawOptions)(MTFace *tface, MCol *mcol, int matnr))
820 {
821         cdDM_drawFacesTex_common(dm, setDrawOptions, NULL, NULL);
822 }
823
824 static void cdDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index, int *drawSmooth_r), void *userData, int useColors)
825 {
826         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
827         MVert *mv = cddm->mvert;
828         MFace *mf = cddm->mface;
829         MCol *mc;
830         float *nors= dm->getFaceDataArray(dm, CD_NORMAL);
831         int i, orig, *index = DM_get_face_data_layer(dm, CD_ORIGINDEX);
832
833
834         mc = DM_get_face_data_layer(dm, CD_ID_MCOL);
835         if(!mc)
836                 mc = DM_get_face_data_layer(dm, CD_WEIGHT_MCOL);
837         if(!mc)
838                 mc = DM_get_face_data_layer(dm, CD_MCOL);
839
840         if( GPU_buffer_legacy(dm) ) {
841                 DEBUG_VBO( "Using legacy code. cdDM_drawMappedFaces\n" );
842                 for(i = 0; i < dm->numFaceData; i++, mf++) {
843                         int drawSmooth = (mf->flag & ME_SMOOTH);
844
845                         if(index) {
846                                 orig = *index++;
847                                 if(setDrawOptions && orig == ORIGINDEX_NONE)
848                                         { if(nors) nors += 3; continue; }
849                         }
850                         else
851                                 orig = i;
852
853                         if(!setDrawOptions || setDrawOptions(userData, orig, &drawSmooth)) {
854                                 unsigned char *cp = NULL;
855
856                                 if(useColors && mc)
857                                         cp = (unsigned char *)&mc[i * 4];
858
859                                 glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
860                                 glBegin(mf->v4?GL_QUADS:GL_TRIANGLES);
861
862                                 if (!drawSmooth) {
863                                         if (nors) {
864                                                 glNormal3fv(nors);
865                                         }
866                                         else {
867                                                 float nor[3];
868                                                 if(mf->v4) {
869                                                         normal_quad_v3( nor,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co, mv[mf->v4].co);
870                                                 } else {
871                                                         normal_tri_v3( nor,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co);
872                                                 }
873                                                 glNormal3fv(nor);
874                                         }
875
876                                         if(cp) glColor3ub(cp[3], cp[2], cp[1]);
877                                         glVertex3fv(mv[mf->v1].co);
878                                         if(cp) glColor3ub(cp[7], cp[6], cp[5]);
879                                         glVertex3fv(mv[mf->v2].co);
880                                         if(cp) glColor3ub(cp[11], cp[10], cp[9]);
881                                         glVertex3fv(mv[mf->v3].co);
882                                         if(mf->v4) {
883                                                 if(cp) glColor3ub(cp[15], cp[14], cp[13]);
884                                                 glVertex3fv(mv[mf->v4].co);
885                                         }
886                                 } else {
887                                         if(cp) glColor3ub(cp[3], cp[2], cp[1]);
888                                         glNormal3sv(mv[mf->v1].no);
889                                         glVertex3fv(mv[mf->v1].co);
890                                         if(cp) glColor3ub(cp[7], cp[6], cp[5]);
891                                         glNormal3sv(mv[mf->v2].no);
892                                         glVertex3fv(mv[mf->v2].co);
893                                         if(cp) glColor3ub(cp[11], cp[10], cp[9]);
894                                         glNormal3sv(mv[mf->v3].no);
895                                         glVertex3fv(mv[mf->v3].co);
896                                         if(mf->v4) {
897                                                 if(cp) glColor3ub(cp[15], cp[14], cp[13]);
898                                                 glNormal3sv(mv[mf->v4].no);
899                                                 glVertex3fv(mv[mf->v4].co);
900                                         }
901                                 }
902
903                                 glEnd();
904                         }
905                         
906                         if (nors) nors += 3;
907                 }
908         }
909         else { /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */
910                 int state = 1;
911                 int prevstate = 1;
912                 int prevstart = 0;
913                 GPU_vertex_setup(dm);
914                 GPU_normal_setup(dm);
915                 if( useColors && mc )
916                         GPU_color_setup(dm);
917                 if( !GPU_buffer_legacy(dm) ) {
918                         glShadeModel(GL_SMOOTH);
919                         for( i = 0; i < dm->drawObject->nelements/3; i++ ) {
920                                 int actualFace = dm->drawObject->faceRemap[i];
921                                 int drawSmooth = (mf[actualFace].flag & ME_SMOOTH);
922                                 int dontdraw = 0;
923                                 if(index) {
924                                         orig = index[actualFace];
925                                         if(setDrawOptions && orig == ORIGINDEX_NONE)
926                                                 dontdraw = 1;
927                                 }
928                                 else
929                                         orig = i;
930                                 if( dontdraw ) {
931                                         state = 0;
932                                 }
933                                 else {
934                                         if(!setDrawOptions || setDrawOptions(userData, orig, &drawSmooth)) {
935                                                 state = 1;
936                                         }
937                                         else {
938                                                 state = 0;
939                                         }
940                                 }
941                                 if( prevstate != state && prevstate == 1 ) {
942                                         if( i-prevstart > 0 ) {
943                                                 glDrawArrays(GL_TRIANGLES,prevstart*3,(i-prevstart)*3);
944                                         }
945                                         prevstart = i;
946                                 }
947                                 prevstate = state;
948                         }
949                         if(state==1) {
950                                 glDrawArrays(GL_TRIANGLES,prevstart*3,dm->drawObject->nelements-prevstart*3);
951                         }
952                         glShadeModel(GL_FLAT);
953                 }
954                 GPU_buffer_unbind();
955         }
956 }
957
958 static void cdDM_drawMappedFacesTex(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index), void *userData)
959 {
960         cdDM_drawFacesTex_common(dm, NULL, setDrawOptions, userData);
961 }
962
963 static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs), int (*setDrawOptions)(void *userData, int index), void *userData)
964 {
965         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
966         GPUVertexAttribs gattribs;
967         DMVertexAttribs attribs;
968         MVert *mvert = cddm->mvert;
969         MFace *mface = cddm->mface;
970         MTFace *tf = dm->getFaceDataArray(dm, CD_MTFACE);
971         float (*nors)[3] = dm->getFaceDataArray(dm, CD_NORMAL);
972         int a, b, dodraw, smoothnormal, matnr, new_matnr;
973         int transp, new_transp, orig_transp;
974         int orig, *index = dm->getFaceDataArray(dm, CD_ORIGINDEX);
975
976         matnr = -1;
977         smoothnormal = 0;
978         dodraw = 0;
979         transp = GPU_get_material_blend_mode();
980         orig_transp = transp;
981
982         glShadeModel(GL_SMOOTH);
983
984         if( GPU_buffer_legacy(dm) || setDrawOptions != 0 ) {
985                 DEBUG_VBO( "Using legacy code. cdDM_drawMappedFacesGLSL\n" );
986                 memset(&attribs, 0, sizeof(attribs));
987
988                 glBegin(GL_QUADS);
989
990                 for(a = 0; a < dm->numFaceData; a++, mface++) {
991                         new_matnr = mface->mat_nr + 1;
992
993                         if(new_matnr != matnr) {
994                                 glEnd();
995
996                                 dodraw = setMaterial(matnr = new_matnr, &gattribs);
997                                 if(dodraw)
998                                         DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
999
1000                                 glBegin(GL_QUADS);
1001                         }
1002
1003                         if(!dodraw) {
1004                                 continue;
1005                         }
1006                         else if(setDrawOptions) {
1007                                 orig = (index)? index[a]: a;
1008
1009                                 if(orig == ORIGINDEX_NONE)
1010                                         continue;
1011                                 else if(!setDrawOptions(userData, orig))
1012                                         continue;
1013                         }
1014
1015                         if(tf) {
1016                                 new_transp = tf[a].transp;
1017
1018                                 if(new_transp != transp) {
1019                                         glEnd();
1020
1021                                         if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID)
1022                                                 GPU_set_material_blend_mode(orig_transp);
1023                                         else
1024                                                 GPU_set_material_blend_mode(new_transp);
1025                                         transp = new_transp;
1026
1027                                         glBegin(GL_QUADS);
1028                                 }
1029                         }
1030
1031                         smoothnormal = (mface->flag & ME_SMOOTH);
1032
1033                         if(!smoothnormal) {
1034                                 if(nors) {
1035                                         glNormal3fv(nors[a]);
1036                                 }
1037                                 else {
1038                                         /* TODO ideally a normal layer should always be available */
1039                                         float nor[3];
1040                                         if(mface->v4) {
1041                                                 normal_quad_v3( nor,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co, mvert[mface->v4].co);
1042                                         } else {
1043                                                 normal_tri_v3( nor,mvert[mface->v1].co, mvert[mface->v2].co, mvert[mface->v3].co);
1044                                         }
1045                                         glNormal3fv(nor);
1046                                 }
1047                         }
1048
1049 #define PASSVERT(index, vert) {                                                                                                 \
1050                 if(attribs.totorco)                                                                                                                     \
1051                         glVertexAttrib3fvARB(attribs.orco.glIndex, attribs.orco.array[index]);  \
1052                 for(b = 0; b < attribs.tottface; b++) {                                                                         \
1053                         MTFace *tf = &attribs.tface[b].array[a];                                                                \
1054                         glVertexAttrib2fvARB(attribs.tface[b].glIndex, tf->uv[vert]);                   \
1055                 }                                                                                                                                                       \
1056                 for(b = 0; b < attribs.totmcol; b++) {                                                                          \
1057                         MCol *cp = &attribs.mcol[b].array[a*4 + vert];                                                  \
1058                         GLubyte col[4];                                                                                                                 \
1059                         col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;                             \
1060                         glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col);                                    \
1061                 }                                                                                                                                                       \
1062                 if(attribs.tottang) {                                                                                                           \
1063                         float *tang = attribs.tang.array[a*4 + vert];                                                   \
1064                         glVertexAttrib3fvARB(attribs.tang.glIndex, tang);                                               \
1065                 }                                                                                                                                                       \
1066                 if(smoothnormal)                                                                                                                        \
1067                         glNormal3sv(mvert[index].no);                                                                                   \
1068                 glVertex3fv(mvert[index].co);                                                                                           \
1069         }
1070
1071                         PASSVERT(mface->v1, 0);
1072                         PASSVERT(mface->v2, 1);
1073                         PASSVERT(mface->v3, 2);
1074                         if(mface->v4)
1075                                 PASSVERT(mface->v4, 3)
1076                         else
1077                                 PASSVERT(mface->v3, 2)
1078
1079 #undef PASSVERT
1080                 }
1081                 glEnd();
1082         }
1083         else {
1084                 GPUBuffer *buffer = 0;
1085                 char *varray = 0;
1086                 int numdata = 0, elementsize = 0, offset;
1087                 int start = 0, numfaces = 0, prevdraw = 0, curface = 0;
1088                 GPUAttrib datatypes[32];
1089                 memset(&attribs, 0, sizeof(attribs));
1090
1091                 GPU_vertex_setup(dm);
1092                 GPU_normal_setup(dm);
1093
1094                 if( !GPU_buffer_legacy(dm) ) {
1095                         for(a = 0; a < dm->numFaceData; a++, mface++) {
1096                                 new_matnr = mface->mat_nr + 1;
1097
1098                                 if(new_matnr != matnr ) {
1099                                         numfaces = curface - start;
1100                                         if( numfaces > 0 ) {
1101                                                 if( prevdraw ) {
1102                                                         GPU_buffer_unlock(buffer);
1103                                                         GPU_interleaved_attrib_setup(buffer,datatypes,numdata);
1104                                                         glDrawArrays(GL_TRIANGLES,start*3,numfaces*3);
1105                                                         GPU_buffer_free(buffer,0);
1106                                                 }
1107                                         }
1108                                         start = curface;
1109                                         prevdraw = dodraw;
1110                                         dodraw = setMaterial(matnr = new_matnr, &gattribs);
1111                                         if(dodraw) {
1112                                                 DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
1113
1114                                                 if(attribs.totorco) {
1115                                                         datatypes[numdata].index = attribs.orco.glIndex;
1116                                                         datatypes[numdata].size = 3;
1117                                                         datatypes[numdata].type = GL_FLOAT;
1118                                                         numdata++;
1119                                                 }
1120                                                 for(b = 0; b < attribs.tottface; b++) {
1121                                                         datatypes[numdata].index = attribs.tface[b].glIndex;
1122                                                         datatypes[numdata].size = 2;
1123                                                         datatypes[numdata].type = GL_FLOAT;
1124                                                         numdata++;
1125                                                 }       
1126                                                 for(b = 0; b < attribs.totmcol; b++) {
1127                                                         datatypes[numdata].index = attribs.mcol[b].glIndex;
1128                                                         datatypes[numdata].size = 4;
1129                                                         datatypes[numdata].type = GL_UNSIGNED_BYTE;
1130                                                         numdata++;
1131                                                 }       
1132                                                 if(attribs.tottang) {
1133                                                         datatypes[numdata].index = attribs.tang.glIndex;
1134                                                         datatypes[numdata].size = 3;
1135                                                         datatypes[numdata].type = GL_FLOAT;
1136                                                         numdata++;
1137                                                 }
1138                                                 if( numdata != 0 ) {
1139                                                         elementsize = GPU_attrib_element_size( datatypes, numdata );
1140                                                         buffer = GPU_buffer_alloc( elementsize*dm->drawObject->nelements, 0 );
1141                                                         if( buffer == 0 ) {
1142                                                                 GPU_buffer_unbind();
1143                                                                 dm->drawObject->legacy = 1;
1144                                                                 return;
1145                                                         }
1146                                                         varray = GPU_buffer_lock_stream(buffer);
1147                                                         if( varray == 0 ) {
1148                                                                 GPU_buffer_unbind();
1149                                                                 GPU_buffer_free(buffer, 0);
1150                                                                 dm->drawObject->legacy = 1;
1151                                                                 return;
1152                                                         }
1153                                                 }
1154                                         }
1155                                 }
1156                                 if(!dodraw) {
1157                                         continue;
1158                                 }
1159
1160                                 if(tf) {
1161                                         new_transp = tf[a].transp;
1162
1163                                         if(new_transp != transp) {
1164                                                 numfaces = curface - start;
1165                                                 if( numfaces > 0 ) {
1166                                                         if( dodraw ) {
1167                                                                 if( numdata != 0 ) {
1168                                                                         GPU_buffer_unlock(buffer);
1169                                                                         GPU_interleaved_attrib_setup(buffer,datatypes,numdata);
1170                                                                 }
1171                                                                 glDrawArrays(GL_TRIANGLES,start*3,(curface-start)*3);
1172                                                                 if( numdata != 0 ) {
1173                                                                         varray = GPU_buffer_lock_stream(buffer);
1174                                                                 }
1175                                                         }
1176                                                 }
1177                                                 start = curface;
1178
1179                                                 if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID)
1180                                                         GPU_set_material_blend_mode(orig_transp);
1181                                                 else
1182                                                         GPU_set_material_blend_mode(new_transp);
1183                                                 transp = new_transp;
1184                                         }
1185                                 }
1186                                 
1187                                 if( numdata != 0 ) {
1188                                         offset = 0;
1189                                         if(attribs.totorco) {
1190                                                 VECCOPY((float *)&varray[elementsize*curface*3],(float *)attribs.orco.array[mface->v1]);
1191                                                 VECCOPY((float *)&varray[elementsize*curface*3+elementsize],(float *)attribs.orco.array[mface->v2]);
1192                                                 VECCOPY((float *)&varray[elementsize*curface*3+elementsize*2],(float *)attribs.orco.array[mface->v3]);
1193                                                 offset += sizeof(float)*3;
1194                                         }
1195                                         for(b = 0; b < attribs.tottface; b++) {
1196                                                 MTFace *tf = &attribs.tface[b].array[a];
1197                                                 VECCOPY((float *)&varray[elementsize*curface*3+offset],tf->uv[0]);
1198                                                 VECCOPY((float *)&varray[elementsize*curface*3+offset+elementsize],tf->uv[1]);
1199                                                 VECCOPY((float *)&varray[elementsize*curface*3+offset+elementsize*2],tf->uv[2]);
1200                                                 offset += sizeof(float)*2;
1201                                         }
1202                                         for(b = 0; b < attribs.totmcol; b++) {
1203                                                 MCol *cp = &attribs.mcol[b].array[a*4 + 0];
1204                                                 GLubyte col[4];
1205                                                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1206                                                 QUATCOPY((unsigned char *)&varray[elementsize*curface*3+offset], col);
1207                                                 cp = &attribs.mcol[b].array[a*4 + 1];
1208                                                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1209                                                 QUATCOPY((unsigned char *)&varray[elementsize*curface*3+offset+elementsize], col);
1210                                                 cp = &attribs.mcol[b].array[a*4 + 2];
1211                                                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1212                                                 QUATCOPY((unsigned char *)&varray[elementsize*curface*3+offset+elementsize*2], col);
1213                                                 offset += sizeof(unsigned char)*4;
1214                                         }       
1215                                         if(attribs.tottang) {
1216                                                 float *tang = attribs.tang.array[a*4 + 0];
1217                                                 VECCOPY((float *)&varray[elementsize*curface*3+offset], tang);
1218                                                 tang = attribs.tang.array[a*4 + 1];
1219                                                 VECCOPY((float *)&varray[elementsize*curface*3+offset+elementsize], tang);
1220                                                 tang = attribs.tang.array[a*4 + 2];
1221                                                 VECCOPY((float *)&varray[elementsize*curface*3+offset+elementsize], tang);
1222                                                 offset += sizeof(float)*3;
1223                                         }
1224                                 }
1225                                 curface++;
1226                                 if(mface->v4) {
1227                                         if( numdata != 0 ) {
1228                                                 offset = 0;
1229                                                 if(attribs.totorco) {
1230                                                         VECCOPY((float *)&varray[elementsize*curface*3],(float *)attribs.orco.array[mface->v3]);
1231                                                         VECCOPY((float *)&varray[elementsize*curface*3+elementsize],(float *)attribs.orco.array[mface->v4]);
1232                                                         VECCOPY((float *)&varray[elementsize*curface*3+elementsize*2],(float *)attribs.orco.array[mface->v1]);
1233                                                         offset += sizeof(float)*3;
1234                                                 }
1235                                                 for(b = 0; b < attribs.tottface; b++) {
1236                                                         MTFace *tf = &attribs.tface[b].array[a];
1237                                                         VECCOPY((float *)&varray[elementsize*curface*3+offset],tf->uv[2]);
1238                                                         VECCOPY((float *)&varray[elementsize*curface*3+offset+elementsize],tf->uv[3]);
1239                                                         VECCOPY((float *)&varray[elementsize*curface*3+offset+elementsize*2],tf->uv[0]);
1240                                                         offset += sizeof(float)*2;
1241                                                 }
1242                                                 for(b = 0; b < attribs.totmcol; b++) {
1243                                                         MCol *cp = &attribs.mcol[b].array[a*4 + 2];
1244                                                         GLubyte col[4];
1245                                                         col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1246                                                         QUATCOPY((unsigned char *)&varray[elementsize*curface*3+offset], col);
1247                                                         cp = &attribs.mcol[b].array[a*4 + 3];
1248                                                         col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1249                                                         QUATCOPY((unsigned char *)&varray[elementsize*curface*3+offset+elementsize], col);
1250                                                         cp = &attribs.mcol[b].array[a*4 + 0];
1251                                                         col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;
1252                                                         QUATCOPY((unsigned char *)&varray[elementsize*curface*3+offset+elementsize*2], col);
1253                                                         offset += sizeof(unsigned char)*4;
1254                                                 }       
1255                                                 if(attribs.tottang) {
1256                                                         float *tang = attribs.tang.array[a*4 + 2];
1257                                                         VECCOPY((float *)&varray[elementsize*curface*3+offset], tang);
1258                                                         tang = attribs.tang.array[a*4 + 3];
1259                                                         VECCOPY((float *)&varray[elementsize*curface*3+offset+elementsize], tang);
1260                                                         tang = attribs.tang.array[a*4 + 0];
1261                                                         VECCOPY((float *)&varray[elementsize*curface*3+offset+elementsize], tang);
1262                                                         offset += sizeof(float)*3;
1263                                                 }
1264                                         }
1265                                         curface++;
1266                                 }
1267                         }
1268                         numfaces = curface - start;
1269                         if( numfaces > 0 ) {
1270                                 if( dodraw ) {
1271                                         if( numdata != 0 ) {
1272                                                 GPU_buffer_unlock(buffer);
1273                                                 GPU_interleaved_attrib_setup(buffer,datatypes,numdata);
1274                                         }
1275                                         glDrawArrays(GL_TRIANGLES,start*3,(curface-start)*3);
1276                                 }
1277                         }
1278                         GPU_buffer_unbind();
1279                 }
1280                 GPU_buffer_free( buffer, 0 );
1281         }
1282
1283         glShadeModel(GL_FLAT);
1284 }
1285
1286 static void cdDM_drawFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs))
1287 {
1288         dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
1289 }
1290
1291 static void cdDM_drawMappedEdges(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index), void *userData)
1292 {
1293         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
1294         MVert *vert = cddm->mvert;
1295         MEdge *edge = cddm->medge;
1296         int i, orig, *index = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1297
1298         glBegin(GL_LINES);
1299         for(i = 0; i < dm->numEdgeData; i++, edge++) {
1300                 if(index) {
1301                         orig = *index++;
1302                         if(setDrawOptions && orig == ORIGINDEX_NONE) continue;
1303                 }
1304                 else
1305                         orig = i;
1306
1307                 if(!setDrawOptions || setDrawOptions(userData, orig)) {
1308                         glVertex3fv(vert[edge->v1].co);
1309                         glVertex3fv(vert[edge->v2].co);
1310                 }
1311         }
1312         glEnd();
1313 }
1314
1315 static void cdDM_foreachMappedVert(
1316                            DerivedMesh *dm,
1317                            void (*func)(void *userData, int index, float *co,
1318                                         float *no_f, short *no_s),
1319                            void *userData)
1320 {
1321         MVert *mv = CDDM_get_verts(dm);
1322         int i, orig, *index = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
1323
1324         for(i = 0; i < dm->numVertData; i++, mv++) {
1325                 if(index) {
1326                         orig = *index++;
1327                         if(orig == ORIGINDEX_NONE) continue;
1328                         func(userData, orig, mv->co, NULL, mv->no);
1329                 }
1330                 else
1331                         func(userData, i, mv->co, NULL, mv->no);
1332         }
1333 }
1334
1335 static void cdDM_foreachMappedEdge(
1336                            DerivedMesh *dm,
1337                            void (*func)(void *userData, int index,
1338                                         float *v0co, float *v1co),
1339                            void *userData)
1340 {
1341         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
1342         MVert *mv = cddm->mvert;
1343         MEdge *med = cddm->medge;
1344         int i, orig, *index = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1345
1346         for(i = 0; i < dm->numEdgeData; i++, med++) {
1347                 if (index) {
1348                         orig = *index++;
1349                         if(orig == ORIGINDEX_NONE) continue;
1350                         func(userData, orig, mv[med->v1].co, mv[med->v2].co);
1351                 }
1352                 else
1353                         func(userData, i, mv[med->v1].co, mv[med->v2].co);
1354         }
1355 }
1356
1357 static void cdDM_foreachMappedFaceCenter(
1358                            DerivedMesh *dm,
1359                            void (*func)(void *userData, int index,
1360                                         float *cent, float *no),
1361                            void *userData)
1362 {
1363         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1364         MVert *mv = cddm->mvert;
1365         MFace *mf = cddm->mface;
1366         int i, orig, *index = DM_get_face_data_layer(dm, CD_ORIGINDEX);
1367
1368         for(i = 0; i < dm->numFaceData; i++, mf++) {
1369                 float cent[3];
1370                 float no[3];
1371
1372                 if (index) {
1373                         orig = *index++;
1374                         if(orig == ORIGINDEX_NONE) continue;
1375                 }
1376                 else
1377                         orig = i;
1378
1379                 VECCOPY(cent, mv[mf->v1].co);
1380                 add_v3_v3v3(cent, cent, mv[mf->v2].co);
1381                 add_v3_v3v3(cent, cent, mv[mf->v3].co);
1382
1383                 if (mf->v4) {
1384                         normal_quad_v3( no,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co, mv[mf->v4].co);
1385                         add_v3_v3v3(cent, cent, mv[mf->v4].co);
1386                         mul_v3_fl(cent, 0.25f);
1387                 } else {
1388                         normal_tri_v3( no,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co);
1389                         mul_v3_fl(cent, 0.33333333333f);
1390                 }
1391
1392                 func(userData, orig, cent, no);
1393         }
1394 }
1395
1396 static void cdDM_free_internal(CDDerivedMesh *cddm)
1397 {
1398         if(cddm->pbvh) BLI_pbvh_free(cddm->pbvh);
1399         if(cddm->fmap) MEM_freeN(cddm->fmap);
1400         if(cddm->fmap_mem) MEM_freeN(cddm->fmap_mem);
1401 }
1402
1403 static void cdDM_release(DerivedMesh *dm)
1404 {
1405         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1406
1407         if (DM_release(dm)) {
1408                 cdDM_free_internal(cddm);
1409                 MEM_freeN(cddm);
1410         }
1411 }
1412
1413 /**************** CDDM interface functions ****************/
1414 static CDDerivedMesh *cdDM_create(const char *desc)
1415 {
1416         CDDerivedMesh *cddm;
1417         DerivedMesh *dm;
1418
1419         cddm = MEM_callocN(sizeof(*cddm), desc);
1420         dm = &cddm->dm;
1421
1422         dm->getMinMax = cdDM_getMinMax;
1423
1424         dm->getNumVerts = cdDM_getNumVerts;
1425         dm->getNumFaces = cdDM_getNumFaces;
1426         dm->getNumEdges = cdDM_getNumEdges;
1427
1428         dm->getVert = cdDM_getVert;
1429         dm->getEdge = cdDM_getEdge;
1430         dm->getFace = cdDM_getFace;
1431         dm->copyVertArray = cdDM_copyVertArray;
1432         dm->copyEdgeArray = cdDM_copyEdgeArray;
1433         dm->copyFaceArray = cdDM_copyFaceArray;
1434         dm->getVertData = DM_get_vert_data;
1435         dm->getEdgeData = DM_get_edge_data;
1436         dm->getFaceData = DM_get_face_data;
1437         dm->getVertDataArray = DM_get_vert_data_layer;
1438         dm->getEdgeDataArray = DM_get_edge_data_layer;
1439         dm->getFaceDataArray = DM_get_face_data_layer;
1440
1441         dm->getVertCos = cdDM_getVertCos;
1442         dm->getVertCo = cdDM_getVertCo;
1443         dm->getVertNo = cdDM_getVertNo;
1444
1445         dm->getPBVH = cdDM_getPBVH;
1446         dm->getFaceMap = cdDM_getFaceMap;
1447
1448         dm->drawVerts = cdDM_drawVerts;
1449
1450         dm->drawUVEdges = cdDM_drawUVEdges;
1451         dm->drawEdges = cdDM_drawEdges;
1452         dm->drawLooseEdges = cdDM_drawLooseEdges;
1453         dm->drawMappedEdges = cdDM_drawMappedEdges;
1454
1455         dm->drawFacesSolid = cdDM_drawFacesSolid;
1456         dm->drawFacesColored = cdDM_drawFacesColored;
1457         dm->drawFacesTex = cdDM_drawFacesTex;
1458         dm->drawFacesGLSL = cdDM_drawFacesGLSL;
1459         dm->drawMappedFaces = cdDM_drawMappedFaces;
1460         dm->drawMappedFacesTex = cdDM_drawMappedFacesTex;
1461         dm->drawMappedFacesGLSL = cdDM_drawMappedFacesGLSL;
1462
1463         dm->foreachMappedVert = cdDM_foreachMappedVert;
1464         dm->foreachMappedEdge = cdDM_foreachMappedEdge;
1465         dm->foreachMappedFaceCenter = cdDM_foreachMappedFaceCenter;
1466
1467         dm->release = cdDM_release;
1468
1469         return cddm;
1470 }
1471
1472 DerivedMesh *CDDM_new(int numVerts, int numEdges, int numFaces)
1473 {
1474         CDDerivedMesh *cddm = cdDM_create("CDDM_new dm");
1475         DerivedMesh *dm = &cddm->dm;
1476
1477         DM_init(dm, numVerts, numEdges, numFaces);
1478
1479         CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
1480         CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
1481         CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numFaces);
1482
1483         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
1484         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
1485         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numFaces);
1486
1487         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
1488         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1489         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1490
1491         return dm;
1492 }
1493
1494 DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *ob)
1495 {
1496         CDDerivedMesh *cddm = cdDM_create("CDDM_from_mesh dm");
1497         DerivedMesh *dm = &cddm->dm;
1498         CustomDataMask mask = CD_MASK_MESH & (~CD_MASK_MDISPS);
1499         int alloctype;
1500
1501         /* this does a referenced copy, with an exception for fluidsim */
1502
1503         DM_init(dm, mesh->totvert, mesh->totedge, mesh->totface);
1504
1505         dm->deformedOnly = 1;
1506
1507         alloctype= CD_REFERENCE;
1508
1509         CustomData_merge(&mesh->vdata, &dm->vertData, mask, alloctype,
1510                          mesh->totvert);
1511         CustomData_merge(&mesh->edata, &dm->edgeData, mask, alloctype,
1512                          mesh->totedge);
1513         CustomData_merge(&mesh->fdata, &dm->faceData, mask, alloctype,
1514                          mesh->totface);
1515
1516         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
1517         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1518         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1519
1520         return dm;
1521 }
1522
1523 DerivedMesh *CDDM_from_editmesh(EditMesh *em, Mesh *me)
1524 {
1525         DerivedMesh *dm = CDDM_new(BLI_countlist(&em->verts),
1526                                    BLI_countlist(&em->edges),
1527                                    BLI_countlist(&em->faces));
1528         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1529         EditVert *eve;
1530         EditEdge *eed;
1531         EditFace *efa;
1532         MVert *mvert = cddm->mvert;
1533         MEdge *medge = cddm->medge;
1534         MFace *mface = cddm->mface;
1535         int i, *index;
1536
1537         dm->deformedOnly = 1;
1538
1539         CustomData_merge(&em->vdata, &dm->vertData, CD_MASK_DERIVEDMESH,
1540                          CD_CALLOC, dm->numVertData);
1541         /* CustomData_merge(&em->edata, &dm->edgeData, CD_MASK_DERIVEDMESH,
1542                          CD_CALLOC, dm->numEdgeData); */
1543         CustomData_merge(&em->fdata, &dm->faceData, CD_MASK_DERIVEDMESH,
1544                          CD_CALLOC, dm->numFaceData);
1545
1546         /* set eve->hash to vert index */
1547         for(i = 0, eve = em->verts.first; eve; eve = eve->next, ++i)
1548                 eve->tmp.l = i;
1549
1550         /* Need to be able to mark loose edges */
1551         for(eed = em->edges.first; eed; eed = eed->next) {
1552                 eed->f2 = 0;
1553         }
1554         for(efa = em->faces.first; efa; efa = efa->next) {
1555                 efa->e1->f2 = 1;
1556                 efa->e2->f2 = 1;
1557                 efa->e3->f2 = 1;
1558                 if(efa->e4) efa->e4->f2 = 1;
1559         }
1560
1561         index = dm->getVertDataArray(dm, CD_ORIGINDEX);
1562         for(i = 0, eve = em->verts.first; i < dm->numVertData;
1563             i++, eve = eve->next, index++) {
1564                 MVert *mv = &mvert[i];
1565
1566                 VECCOPY(mv->co, eve->co);
1567
1568                 mv->no[0] = eve->no[0] * 32767.0;
1569                 mv->no[1] = eve->no[1] * 32767.0;
1570                 mv->no[2] = eve->no[2] * 32767.0;
1571                 mv->bweight = (unsigned char) (eve->bweight * 255.0f);
1572
1573                 mv->mat_nr = 0;
1574                 mv->flag = 0;
1575
1576                 *index = i;
1577
1578                 CustomData_from_em_block(&em->vdata, &dm->vertData, eve->data, i);
1579         }
1580
1581         index = dm->getEdgeDataArray(dm, CD_ORIGINDEX);
1582         for(i = 0, eed = em->edges.first; i < dm->numEdgeData;
1583             i++, eed = eed->next, index++) {
1584                 MEdge *med = &medge[i];
1585
1586                 med->v1 = eed->v1->tmp.l;
1587                 med->v2 = eed->v2->tmp.l;
1588                 med->crease = (unsigned char) (eed->crease * 255.0f);
1589                 med->bweight = (unsigned char) (eed->bweight * 255.0f);
1590                 med->flag = ME_EDGEDRAW|ME_EDGERENDER;
1591                 
1592                 if(eed->seam) med->flag |= ME_SEAM;
1593                 if(eed->sharp) med->flag |= ME_SHARP;
1594                 if(!eed->f2) med->flag |= ME_LOOSEEDGE;
1595
1596                 *index = i;
1597
1598                 /* CustomData_from_em_block(&em->edata, &dm->edgeData, eed->data, i); */
1599         }
1600
1601         index = dm->getFaceDataArray(dm, CD_ORIGINDEX);
1602         for(i = 0, efa = em->faces.first; i < dm->numFaceData;
1603             i++, efa = efa->next, index++) {
1604                 MFace *mf = &mface[i];
1605
1606                 mf->v1 = efa->v1->tmp.l;
1607                 mf->v2 = efa->v2->tmp.l;
1608                 mf->v3 = efa->v3->tmp.l;
1609                 mf->v4 = efa->v4 ? efa->v4->tmp.l : 0;
1610                 mf->mat_nr = efa->mat_nr;
1611                 mf->flag = efa->flag;
1612
1613                 *index = i;
1614
1615                 CustomData_from_em_block(&em->fdata, &dm->faceData, efa->data, i);
1616                 test_index_face(mf, &dm->faceData, i, efa->v4?4:3);
1617         }
1618
1619         return dm;
1620 }
1621
1622 DerivedMesh *CDDM_copy(DerivedMesh *source)
1623 {
1624         CDDerivedMesh *cddm = cdDM_create("CDDM_copy cddm");
1625         DerivedMesh *dm = &cddm->dm;
1626         int numVerts = source->numVertData;
1627         int numEdges = source->numEdgeData;
1628         int numFaces = source->numFaceData;
1629
1630         /* this initializes dm, and copies all non mvert/medge/mface layers */
1631         DM_from_template(dm, source, numVerts, numEdges, numFaces);
1632         dm->deformedOnly = source->deformedOnly;
1633
1634         CustomData_copy_data(&source->vertData, &dm->vertData, 0, 0, numVerts);
1635         CustomData_copy_data(&source->edgeData, &dm->edgeData, 0, 0, numEdges);
1636         CustomData_copy_data(&source->faceData, &dm->faceData, 0, 0, numFaces);
1637
1638         /* now add mvert/medge/mface layers */
1639         cddm->mvert = source->dupVertArray(source);
1640         cddm->medge = source->dupEdgeArray(source);
1641         cddm->mface = source->dupFaceArray(source);
1642
1643         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_ASSIGN, cddm->mvert, numVerts);
1644         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_ASSIGN, cddm->medge, numEdges);
1645         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_ASSIGN, cddm->mface, numFaces);
1646
1647         return dm;
1648 }
1649
1650 DerivedMesh *CDDM_from_template(DerivedMesh *source,
1651                                 int numVerts, int numEdges, int numFaces)
1652 {
1653         CDDerivedMesh *cddm = cdDM_create("CDDM_from_template dest");
1654         DerivedMesh *dm = &cddm->dm;
1655
1656         /* this does a copy of all non mvert/medge/mface layers */
1657         DM_from_template(dm, source, numVerts, numEdges, numFaces);
1658
1659         /* now add mvert/medge/mface layers */
1660         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
1661         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
1662         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numFaces);
1663
1664         if(!CustomData_get_layer(&dm->vertData, CD_ORIGINDEX))
1665                 CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
1666         if(!CustomData_get_layer(&dm->edgeData, CD_ORIGINDEX))
1667                 CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
1668         if(!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX))
1669                 CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numFaces);
1670
1671         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
1672         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1673         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1674
1675         return dm;
1676 }
1677
1678 void CDDM_apply_vert_coords(DerivedMesh *dm, float (*vertCoords)[3])
1679 {
1680         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1681         MVert *vert;
1682         int i;
1683
1684         /* this will just return the pointer if it wasn't a referenced layer */
1685         vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT);
1686         cddm->mvert = vert;
1687
1688         for(i = 0; i < dm->numVertData; ++i, ++vert)
1689                 VECCOPY(vert->co, vertCoords[i]);
1690 }
1691
1692 void CDDM_apply_vert_normals(DerivedMesh *dm, short (*vertNormals)[3])
1693 {
1694         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1695         MVert *vert;
1696         int i;
1697
1698         /* this will just return the pointer if it wasn't a referenced layer */
1699         vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT);
1700         cddm->mvert = vert;
1701
1702         for(i = 0; i < dm->numVertData; ++i, ++vert)
1703                 VECCOPY(vert->no, vertNormals[i]);
1704 }
1705
1706 /* adapted from mesh_calc_normals */
1707 void CDDM_calc_normals(DerivedMesh *dm)
1708 {
1709         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1710         float (*temp_nors)[3];
1711         float (*face_nors)[3];
1712         int i;
1713         int numVerts = dm->numVertData;
1714         int numFaces = dm->numFaceData;
1715         MFace *mf;
1716         MVert *mv;
1717
1718         if(numVerts == 0) return;
1719
1720         temp_nors = MEM_callocN(numVerts * sizeof(*temp_nors),
1721                                 "CDDM_calc_normals temp_nors");
1722
1723         /* we don't want to overwrite any referenced layers */
1724         mv = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT);
1725         cddm->mvert = mv;
1726
1727         /* make a face normal layer if not present */
1728         face_nors = CustomData_get_layer(&dm->faceData, CD_NORMAL);
1729         if(!face_nors)
1730                 face_nors = CustomData_add_layer(&dm->faceData, CD_NORMAL, CD_CALLOC,
1731                                                  NULL, dm->numFaceData);
1732
1733         /* calculate face normals and add to vertex normals */
1734         mf = CDDM_get_faces(dm);
1735         for(i = 0; i < numFaces; i++, mf++) {
1736                 float *f_no = face_nors[i];
1737
1738                 if(mf->v4)
1739                         normal_quad_v3( f_no,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co, mv[mf->v4].co);
1740                 else
1741                         normal_tri_v3( f_no,mv[mf->v1].co, mv[mf->v2].co, mv[mf->v3].co);
1742                 
1743                 add_v3_v3v3(temp_nors[mf->v1], temp_nors[mf->v1], f_no);
1744                 add_v3_v3v3(temp_nors[mf->v2], temp_nors[mf->v2], f_no);
1745                 add_v3_v3v3(temp_nors[mf->v3], temp_nors[mf->v3], f_no);
1746                 if(mf->v4)
1747                         add_v3_v3v3(temp_nors[mf->v4], temp_nors[mf->v4], f_no);
1748         }
1749
1750         /* normalize vertex normals and assign */
1751         for(i = 0; i < numVerts; i++, mv++) {
1752                 float *no = temp_nors[i];
1753                 
1754                 if (normalize_v3(no) == 0.0) {
1755                         VECCOPY(no, mv->co);
1756                         normalize_v3(no);
1757                 }
1758
1759                 mv->no[0] = (short)(no[0] * 32767.0);
1760                 mv->no[1] = (short)(no[1] * 32767.0);
1761                 mv->no[2] = (short)(no[2] * 32767.0);
1762         }
1763         
1764         MEM_freeN(temp_nors);
1765 }
1766
1767 void CDDM_calc_edges(DerivedMesh *dm)
1768 {
1769         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1770         CustomData edgeData;
1771         EdgeHashIterator *ehi;
1772         MFace *mf = cddm->mface;
1773         MEdge *med;
1774         EdgeHash *eh = BLI_edgehash_new();
1775         int i, *index, numEdges, maxFaces = dm->numFaceData;
1776
1777         for (i = 0; i < maxFaces; i++, mf++) {
1778                 if (!BLI_edgehash_haskey(eh, mf->v1, mf->v2))
1779                         BLI_edgehash_insert(eh, mf->v1, mf->v2, NULL);
1780                 if (!BLI_edgehash_haskey(eh, mf->v2, mf->v3))
1781                         BLI_edgehash_insert(eh, mf->v2, mf->v3, NULL);
1782                 
1783                 if (mf->v4) {
1784                         if (!BLI_edgehash_haskey(eh, mf->v3, mf->v4))
1785                                 BLI_edgehash_insert(eh, mf->v3, mf->v4, NULL);
1786                         if (!BLI_edgehash_haskey(eh, mf->v4, mf->v1))
1787                                 BLI_edgehash_insert(eh, mf->v4, mf->v1, NULL);
1788                 } else {
1789                         if (!BLI_edgehash_haskey(eh, mf->v3, mf->v1))
1790                                 BLI_edgehash_insert(eh, mf->v3, mf->v1, NULL);
1791                 }
1792         }
1793
1794         numEdges = BLI_edgehash_size(eh);
1795
1796         /* write new edges into a temporary CustomData */
1797         memset(&edgeData, 0, sizeof(edgeData));
1798         CustomData_add_layer(&edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
1799         CustomData_add_layer(&edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
1800
1801         ehi = BLI_edgehashIterator_new(eh);
1802         med = CustomData_get_layer(&edgeData, CD_MEDGE);
1803         index = CustomData_get_layer(&edgeData, CD_ORIGINDEX);
1804         for(i = 0; !BLI_edgehashIterator_isDone(ehi);
1805             BLI_edgehashIterator_step(ehi), ++i, ++med, ++index) {
1806                 BLI_edgehashIterator_getKey(ehi, (int*)&med->v1, (int*)&med->v2);
1807
1808                 med->flag = ME_EDGEDRAW|ME_EDGERENDER;
1809                 *index = ORIGINDEX_NONE;
1810         }
1811         BLI_edgehashIterator_free(ehi);
1812
1813         /* free old CustomData and assign new one */
1814         CustomData_free(&dm->edgeData, dm->numEdgeData);
1815         dm->edgeData = edgeData;
1816         dm->numEdgeData = numEdges;
1817
1818         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1819
1820         BLI_edgehash_free(eh, NULL);
1821 }
1822
1823 void CDDM_lower_num_verts(DerivedMesh *dm, int numVerts)
1824 {
1825         if (numVerts < dm->numVertData)
1826                 CustomData_free_elem(&dm->vertData, numVerts, dm->numVertData-numVerts);
1827
1828         dm->numVertData = numVerts;
1829 }
1830
1831 void CDDM_lower_num_edges(DerivedMesh *dm, int numEdges)
1832 {
1833         if (numEdges < dm->numEdgeData)
1834                 CustomData_free_elem(&dm->edgeData, numEdges, dm->numEdgeData-numEdges);
1835
1836         dm->numEdgeData = numEdges;
1837 }
1838
1839 void CDDM_lower_num_faces(DerivedMesh *dm, int numFaces)
1840 {
1841         if (numFaces < dm->numFaceData)
1842                 CustomData_free_elem(&dm->faceData, numFaces, dm->numFaceData-numFaces);
1843
1844         dm->numFaceData = numFaces;
1845 }
1846
1847 MVert *CDDM_get_vert(DerivedMesh *dm, int index)
1848 {
1849         return &((CDDerivedMesh*)dm)->mvert[index];
1850 }
1851
1852 MEdge *CDDM_get_edge(DerivedMesh *dm, int index)
1853 {
1854         return &((CDDerivedMesh*)dm)->medge[index];
1855 }
1856
1857 MFace *CDDM_get_face(DerivedMesh *dm, int index)
1858 {
1859         return &((CDDerivedMesh*)dm)->mface[index];
1860 }
1861
1862 MVert *CDDM_get_verts(DerivedMesh *dm)
1863 {
1864         return ((CDDerivedMesh*)dm)->mvert;
1865 }
1866
1867 MEdge *CDDM_get_edges(DerivedMesh *dm)
1868 {
1869         return ((CDDerivedMesh*)dm)->medge;
1870 }
1871
1872 MFace *CDDM_get_faces(DerivedMesh *dm)
1873 {
1874         return ((CDDerivedMesh*)dm)->mface;
1875 }
1876
1877 /* Multires DerivedMesh, extends CDDM */
1878 typedef struct MultiresDM {
1879         CDDerivedMesh cddm;
1880
1881         MultiresModifierData *mmd;
1882         int local_mmd;
1883
1884         int lvl, totlvl;
1885         float (*orco)[3];
1886         MVert *subco;
1887
1888         ListBase *vert_face_map, *vert_edge_map;
1889         IndexNode *vert_face_map_mem, *vert_edge_map_mem;
1890         int *face_offsets;
1891
1892         Object *ob;
1893         int modified;
1894
1895         void (*update)(DerivedMesh*);
1896 } MultiresDM;
1897
1898 static void MultiresDM_release(DerivedMesh *dm)
1899 {
1900         MultiresDM *mrdm = (MultiresDM*)dm;
1901         int mvert_layer;
1902
1903         /* Before freeing, need to update the displacement map */
1904         if(dm->needsFree && mrdm->modified) {
1905                 /* Check that mmd still exists */
1906                 if(!mrdm->local_mmd && BLI_findindex(&mrdm->ob->modifiers, mrdm->mmd) < 0)
1907                         mrdm->mmd = NULL;
1908                 if(mrdm->mmd)
1909                         mrdm->update(dm);
1910         }
1911
1912         /* If the MVert data is being used as the sculpt undo store, don't free it */
1913         mvert_layer = CustomData_get_layer_index(&dm->vertData, CD_MVERT);
1914         if(mvert_layer != -1) {
1915                 CustomDataLayer *cd = &dm->vertData.layers[mvert_layer];
1916                 if(mrdm->mmd && cd->data == mrdm->mmd->undo_verts)
1917                         cd->flag |= CD_FLAG_NOFREE;
1918         }
1919
1920         if(DM_release(dm)) {
1921                 cdDM_free_internal(&mrdm->cddm);
1922                 MEM_freeN(mrdm->subco);
1923                 MEM_freeN(mrdm->orco);
1924                 if(mrdm->vert_face_map)
1925                         MEM_freeN(mrdm->vert_face_map);
1926                 if(mrdm->vert_face_map_mem)
1927                         MEM_freeN(mrdm->vert_face_map_mem);
1928                 if(mrdm->vert_edge_map)
1929                         MEM_freeN(mrdm->vert_edge_map);
1930                 if(mrdm->vert_edge_map_mem)
1931                         MEM_freeN(mrdm->vert_edge_map_mem);
1932                 if(mrdm->face_offsets)
1933                         MEM_freeN(mrdm->face_offsets);
1934                 MEM_freeN(mrdm);
1935         }
1936 }
1937
1938 DerivedMesh *MultiresDM_new(MultiresSubsurf *ms, DerivedMesh *orig, int numVerts, int numEdges, int numFaces)
1939 {
1940         MultiresDM *mrdm = MEM_callocN(sizeof(MultiresDM), "MultiresDM");
1941         CDDerivedMesh *cddm = cdDM_create("MultiresDM CDDM");
1942         DerivedMesh *dm = NULL;
1943
1944         mrdm->cddm = *cddm;
1945         MEM_freeN(cddm);
1946         dm = &mrdm->cddm.dm;
1947
1948         mrdm->mmd = ms->mmd;
1949         mrdm->ob = ms->ob;
1950         mrdm->local_mmd = ms->local_mmd;
1951
1952         if(dm) {
1953                 MDisps *disps;
1954                 MVert *mvert;
1955                 int i;
1956
1957                 DM_from_template(dm, orig, numVerts, numEdges, numFaces);
1958                 CustomData_free_layers(&dm->faceData, CD_MDISPS, numFaces);
1959
1960                 disps = CustomData_get_layer(&orig->faceData, CD_MDISPS);
1961                 if(disps)
1962                         CustomData_add_layer(&dm->faceData, CD_MDISPS, CD_REFERENCE, disps, numFaces);
1963
1964
1965                 mvert = CustomData_get_layer(&orig->vertData, CD_MVERT);
1966                 mrdm->orco = MEM_callocN(sizeof(float) * 3 * orig->getNumVerts(orig), "multires orco");
1967                 for(i = 0; i < orig->getNumVerts(orig); ++i)
1968                         copy_v3_v3(mrdm->orco[i], mvert[i].co);
1969         }
1970         else
1971                 DM_init(dm, numVerts, numEdges, numFaces);
1972
1973         if(!CustomData_get_layer(&dm->vertData, CD_ORIGINDEX))
1974                 CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
1975         if(!CustomData_get_layer(&dm->edgeData, CD_ORIGINDEX))
1976                 CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
1977         if(!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX))
1978                 CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numFaces);
1979
1980         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
1981         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
1982         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numFaces);
1983
1984         mrdm->cddm.mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
1985         mrdm->cddm.medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1986         mrdm->cddm.mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1987
1988         mrdm->lvl = ms->mmd->lvl;
1989         mrdm->totlvl = ms->mmd->totlvl;
1990         mrdm->subco = MEM_callocN(sizeof(MVert)*numVerts, "multires subdivided verts");
1991         mrdm->modified = 0;
1992
1993         dm->release = MultiresDM_release;
1994
1995         return dm;
1996 }
1997
1998 Mesh *MultiresDM_get_mesh(DerivedMesh *dm)
1999 {
2000         return get_mesh(((MultiresDM*)dm)->ob);
2001 }
2002
2003 Object *MultiresDM_get_object(DerivedMesh *dm)
2004 {
2005         return ((MultiresDM*)dm)->ob;
2006 }
2007
2008 void *MultiresDM_get_orco(DerivedMesh *dm)
2009 {
2010         return ((MultiresDM*)dm)->orco;
2011
2012 }
2013
2014 MVert *MultiresDM_get_subco(DerivedMesh *dm)
2015 {
2016         return ((MultiresDM*)dm)->subco;
2017 }
2018
2019 int MultiresDM_get_totlvl(DerivedMesh *dm)
2020 {
2021         return ((MultiresDM*)dm)->totlvl;
2022 }
2023
2024 int MultiresDM_get_lvl(DerivedMesh *dm)
2025 {
2026         return ((MultiresDM*)dm)->lvl;
2027 }
2028
2029 void MultiresDM_set_orco(DerivedMesh *dm, float (*orco)[3])
2030 {
2031         ((MultiresDM*)dm)->orco = orco;
2032 }
2033
2034 void MultiresDM_set_update(DerivedMesh *dm, void (*update)(DerivedMesh*))
2035 {
2036         ((MultiresDM*)dm)->update = update;
2037 }
2038
2039 ListBase *MultiresDM_get_vert_face_map(DerivedMesh *dm)
2040 {
2041         MultiresDM *mrdm = (MultiresDM*)dm;
2042         Mesh *me = mrdm->ob->data;
2043
2044         if(!mrdm->vert_face_map)
2045                 create_vert_face_map(&mrdm->vert_face_map, &mrdm->vert_face_map_mem, me->mface,
2046                                      me->totvert, me->totface);
2047
2048         return mrdm->vert_face_map;
2049 }
2050
2051 ListBase *MultiresDM_get_vert_edge_map(DerivedMesh *dm)
2052 {
2053         MultiresDM *mrdm = (MultiresDM*)dm;
2054         Mesh *me = mrdm->ob->data;
2055
2056         if(!mrdm->vert_edge_map)
2057                 create_vert_edge_map(&mrdm->vert_edge_map, &mrdm->vert_edge_map_mem, me->medge,
2058                                      me->totvert, me->totedge);
2059
2060         return mrdm->vert_edge_map;
2061 }
2062
2063 int *MultiresDM_get_face_offsets(DerivedMesh *dm)
2064 {
2065         MultiresDM *mrdm = (MultiresDM*)dm;
2066         Mesh *me = mrdm->ob->data;
2067         int i, accum = 0;
2068
2069         if(!mrdm->face_offsets) {
2070                 int len = (int)pow(2, mrdm->lvl - 2) - 1;
2071                 int area = len * len;
2072                 int t = 1 + len * 3 + area * 3, q = t + len + area;
2073
2074                 mrdm->face_offsets = MEM_callocN(sizeof(int) * me->totface, "mrdm face offsets");
2075                 for(i = 0; i < me->totface; ++i) {
2076                         mrdm->face_offsets[i] = accum;
2077
2078                         accum += (me->mface[i].v4 ? q : t);
2079                 }
2080         }
2081
2082         return mrdm->face_offsets;
2083 }
2084
2085 void MultiresDM_mark_as_modified(DerivedMesh *dm)
2086 {
2087         ((MultiresDM*)dm)->modified = 1;
2088 }