de4bcda157fe864fc5f97983d498cb1f48d02c1e
[blender.git] / source / blender / src / editmesh.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  */
32
33
34 #include <stdlib.h>
35 #include <string.h>
36 #include <math.h>
37
38 #ifdef HAVE_CONFIG_H
39 #include <config.h>
40 #endif
41
42 #include "MEM_guardedalloc.h"
43
44 #include "PIL_time.h"
45
46 #include "DNA_customdata_types.h"
47 #include "DNA_mesh_types.h"
48 #include "DNA_meshdata_types.h"
49 #include "DNA_object_types.h"
50 #include "DNA_object_force.h"
51 #include "DNA_screen_types.h"
52 #include "DNA_key_types.h"
53 #include "DNA_scene_types.h"
54 #include "DNA_view3d_types.h"
55 #include "DNA_material_types.h"
56 #include "DNA_modifier_types.h"
57 #include "DNA_texture_types.h"
58 #include "DNA_userdef_types.h"
59
60 #include "BLI_blenlib.h"
61 #include "BLI_arithb.h"
62 #include "BLI_editVert.h"
63 #include "BLI_dynstr.h"
64 #include "BLI_rand.h"
65
66 #include "BKE_DerivedMesh.h"
67 #include "BKE_depsgraph.h"
68 #include "BKE_cloth.h"
69 #include "BKE_customdata.h"
70 #include "BKE_global.h"
71 #include "BKE_key.h"
72 #include "BKE_library.h"
73 #include "BKE_main.h"
74 #include "BKE_material.h"
75 #include "BKE_mesh.h"
76 #include "BKE_modifier.h"
77 #include "BKE_multires.h"
78 #include "BKE_object.h"
79 #include "BKE_pointcache.h"
80 #include "BKE_texture.h"
81 #include "BKE_utildefines.h"
82
83 #ifdef WITH_VERSE
84 #include "BKE_verse.h"
85 #endif
86
87 #include "BIF_editkey.h"
88 #include "BIF_editmesh.h"
89 #include "BIF_editmode_undo.h"
90 #include "BIF_interface.h"
91 #include "BIF_meshtools.h"
92 #include "BIF_mywindow.h"
93 #include "BIF_retopo.h"
94 #include "BIF_space.h"
95 #include "BIF_screen.h"
96 #include "BIF_toolbox.h"
97
98 #ifdef WITH_VERSE
99 #include "BIF_verse.h"
100 #endif
101
102 #include "BSE_view.h"
103 #include "BSE_edit.h"
104 #include "BSE_trans_types.h"
105
106 #include "BDR_drawobject.h"
107 #include "BDR_editobject.h"
108 #include "BDR_editface.h"
109 #include "BDR_vpaint.h"
110
111 #include "LBM_fluidsim.h"
112
113 #include "multires.h"
114 #include "mydevice.h"
115 #include "blendef.h"
116
117 /* own include */
118 #include "editmesh.h"
119
120 /* 
121
122 editmesh.c:
123 - add/alloc/free data
124 - hashtables
125 - enter/exit editmode
126
127 */
128
129
130 /* ***************** HASH ********************* */
131
132
133 #define EDHASHSIZE              (512*512)
134 #define EDHASH(a, b)    (a % EDHASHSIZE)
135
136
137 /* ************ ADD / REMOVE / FIND ****************** */
138
139 /* used to bypass normal calloc with fast one */
140 static void *(*callocvert)(size_t, size_t) = calloc;
141 static void *(*callocedge)(size_t, size_t) = calloc;
142 static void *(*callocface)(size_t, size_t) = calloc;
143
144 EditVert *addvertlist(float *vec, EditVert *example)
145 {
146         EditMesh *em = G.editMesh;
147         EditVert *eve;
148         static int hashnr= 0;
149
150         eve= callocvert(sizeof(EditVert), 1);
151         BLI_addtail(&em->verts, eve);
152         
153         if(vec) VECCOPY(eve->co, vec);
154
155         eve->hash= hashnr++;
156         if( hashnr>=EDHASHSIZE) hashnr= 0;
157
158         /* new verts get keyindex of -1 since they did not
159          * have a pre-editmode vertex order
160          */
161         eve->keyindex = -1;
162 #ifdef WITH_VERSE
163         createVerseVert(eve);
164 #endif
165
166         if(example)
167                 CustomData_em_copy_data(&em->vdata, &em->vdata, example->data, &eve->data);
168         else
169                 CustomData_em_set_default(&em->vdata, &eve->data);
170
171         return eve;
172 }
173
174 void free_editvert (EditVert *eve)
175 {
176 #ifdef WITH_VERSE
177         if(eve->vvert) {
178                 /* it prevents from removing all verse vertexes
179                  * during entering edit mode ... messy solution */
180                 if(G.editMesh->vnode)
181                         b_verse_send_vertex_delete(eve);
182                 else
183                         ((VerseVert*)eve->vvert)->vertex = NULL;
184         }
185 #endif
186
187         EM_remove_selection(eve, EDITVERT);
188         CustomData_em_free_block(&G.editMesh->vdata, &eve->data);
189         if(eve->fast==0)
190                 free(eve);
191 }
192
193
194 EditEdge *findedgelist(EditVert *v1, EditVert *v2)
195 {
196         EditVert *v3;
197         struct HashEdge *he;
198
199         /* swap ? */
200         if( v1 > v2) {
201                 v3= v2; 
202                 v2= v1; 
203                 v1= v3;
204         }
205         
206         if(G.editMesh->hashedgetab==NULL)
207                 G.editMesh->hashedgetab= MEM_callocN(EDHASHSIZE*sizeof(struct HashEdge), "hashedgetab");
208
209         he= G.editMesh->hashedgetab + EDHASH(v1->hash, v2->hash);
210         
211         while(he) {
212                 
213                 if(he->eed && he->eed->v1==v1 && he->eed->v2==v2) return he->eed;
214                 
215                 he= he->next;
216         }
217         return 0;
218 }
219
220 static void insert_hashedge(EditEdge *eed)
221 {
222         /* assuming that eed is not in the list yet, and that a find has been done before */
223         
224         struct HashEdge *first, *he;
225
226         first= G.editMesh->hashedgetab + EDHASH(eed->v1->hash, eed->v2->hash);
227
228         if( first->eed==0 ) {
229                 first->eed= eed;
230         }
231         else {
232                 he= &eed->hash; 
233                 he->eed= eed;
234                 he->next= first->next;
235                 first->next= he;
236         }
237 }
238
239 static void remove_hashedge(EditEdge *eed)
240 {
241         /* assuming eed is in the list */
242         
243         struct HashEdge *first, *he, *prev=NULL;
244
245         he=first= G.editMesh->hashedgetab + EDHASH(eed->v1->hash, eed->v2->hash);
246
247         while(he) {
248                 if(he->eed == eed) {
249                         /* remove from list */
250                         if(he==first) {
251                                 if(first->next) {
252                                         he= first->next;
253                                         first->eed= he->eed;
254                                         first->next= he->next;
255                                 }
256                                 else he->eed= 0;
257                         }
258                         else {
259                                 prev->next= he->next;
260                         }
261                         return;
262                 }
263                 prev= he;
264                 he= he->next;
265         }
266 }
267
268 EditEdge *addedgelist(EditVert *v1, EditVert *v2, EditEdge *example)
269 {
270         EditMesh *em = G.editMesh;
271         EditVert *v3;
272         EditEdge *eed;
273         int swap= 0;
274         
275         if(v1==v2) return NULL;
276         if(v1==NULL || v2==NULL) return NULL;
277
278         /* swap ? */
279         if(v1>v2) {
280                 v3= v2; 
281                 v2= v1; 
282                 v1= v3;
283                 swap= 1;
284         }
285         
286         /* find in hashlist */
287         eed= findedgelist(v1, v2);
288
289         if(eed==NULL) {
290         
291                 eed= (EditEdge *)callocedge(sizeof(EditEdge), 1);
292                 eed->v1= v1;
293                 eed->v2= v2;
294                 BLI_addtail(&em->edges, eed);
295                 eed->dir= swap;
296                 insert_hashedge(eed);
297                 
298                 /* copy edge data:
299                    rule is to do this with addedgelist call, before addfacelist */
300                 if(example) {
301                         eed->crease= example->crease;
302                         eed->sharp = example->sharp;
303                         eed->seam = example->seam;
304                         eed->h |= (example->h & EM_FGON);
305                 }
306         }
307
308         return eed;
309 }
310
311 void remedge(EditEdge *eed)
312 {
313         EditMesh *em = G.editMesh;
314
315         BLI_remlink(&em->edges, eed);
316         remove_hashedge(eed);
317 }
318
319 void free_editedge(EditEdge *eed)
320 {
321         EM_remove_selection(eed, EDITEDGE);
322         if(eed->fast==0){ 
323                 free(eed);
324         }
325 }
326
327 void free_editface(EditFace *efa)
328 {
329 #ifdef WITH_VERSE
330         if(efa->vface) {
331                 /* it prevents from removing all verse faces
332                  * during entering edit mode ... messy solution */
333                 if(G.editMesh->vnode)
334                         b_verse_send_face_delete(efa);
335                 else
336                         ((VerseFace*)efa->vface)->face = NULL;
337         }
338 #endif
339         EM_remove_selection(efa, EDITFACE);
340         
341         if (G.editMesh->act_face==efa)
342                 EM_set_actFace(NULL);
343                 
344         CustomData_em_free_block(&G.editMesh->fdata, &efa->data);
345         if(efa->fast==0)
346                 free(efa);
347 }
348
349 void free_vertlist(ListBase *edve) 
350 {
351         EditVert *eve, *next;
352
353         if (!edve) return;
354
355         eve= edve->first;
356         while(eve) {
357                 next= eve->next;
358                 free_editvert(eve);
359                 eve= next;
360         }
361         edve->first= edve->last= NULL;
362 }
363
364 void free_edgelist(ListBase *lb)
365 {
366         EditEdge *eed, *next;
367         
368         eed= lb->first;
369         while(eed) {
370                 next= eed->next;
371                 free_editedge(eed);
372                 eed= next;
373         }
374         lb->first= lb->last= NULL;
375 }
376
377 void free_facelist(ListBase *lb)
378 {
379         EditFace *efa, *next;
380         
381         efa= lb->first;
382         while(efa) {
383                 next= efa->next;
384                 free_editface(efa);
385                 efa= next;
386         }
387         lb->first= lb->last= NULL;
388 }
389
390 EditFace *addfacelist(EditVert *v1, EditVert *v2, EditVert *v3, EditVert *v4, EditFace *example, EditFace *exampleEdges)
391 {
392         EditMesh *em = G.editMesh;
393         EditFace *efa;
394         EditEdge *e1, *e2=0, *e3=0, *e4=0;
395
396         /* added sanity check... seems to happen for some tools, or for enter editmode for corrupted meshes */
397         if(v1==v4 || v2==v4 || v3==v4) v4= NULL;
398         
399         /* add face to list and do the edges */
400         if(exampleEdges) {
401                 e1= addedgelist(v1, v2, exampleEdges->e1);
402                 e2= addedgelist(v2, v3, exampleEdges->e2);
403                 if(v4) e3= addedgelist(v3, v4, exampleEdges->e3); 
404                 else e3= addedgelist(v3, v1, exampleEdges->e3);
405                 if(v4) e4= addedgelist(v4, v1, exampleEdges->e4);
406         }
407         else {
408                 e1= addedgelist(v1, v2, NULL);
409                 e2= addedgelist(v2, v3, NULL);
410                 if(v4) e3= addedgelist(v3, v4, NULL); 
411                 else e3= addedgelist(v3, v1, NULL);
412                 if(v4) e4= addedgelist(v4, v1, NULL);
413         }
414         
415         if(v1==v2 || v2==v3 || v1==v3) return NULL;
416         if(e2==0) return NULL;
417
418         efa= (EditFace *)callocface(sizeof(EditFace), 1);
419         efa->v1= v1;
420         efa->v2= v2;
421         efa->v3= v3;
422         efa->v4= v4;
423
424         efa->e1= e1;
425         efa->e2= e2;
426         efa->e3= e3;
427         efa->e4= e4;
428
429         if(example) {
430                 efa->mat_nr= example->mat_nr;
431                 efa->flag= example->flag;
432                 CustomData_em_copy_data(&em->fdata, &em->fdata, example->data, &efa->data);
433         }
434         else {
435                 if (G.obedit && G.obedit->actcol)
436                         efa->mat_nr= G.obedit->actcol-1;
437
438                 CustomData_em_set_default(&em->fdata, &efa->data);
439         }
440
441         BLI_addtail(&em->faces, efa);
442
443         if(efa->v4) {
444                 CalcNormFloat4(efa->v1->co, efa->v2->co, efa->v3->co, efa->v4->co, efa->n);
445                 CalcCent4f(efa->cent, efa->v1->co, efa->v2->co, efa->v3->co, efa->v4->co);
446         }
447         else {
448                 CalcNormFloat(efa->v1->co, efa->v2->co, efa->v3->co, efa->n);
449                 CalcCent3f(efa->cent, efa->v1->co, efa->v2->co, efa->v3->co);
450         }
451
452 #ifdef WITH_VERSE
453         createVerseFace(efa);
454 #endif
455
456         return efa;
457 }
458
459 /* ************************ end add/new/find ************  */
460
461 /* ************************ Edit{Vert,Edge,Face} utilss ***************************** */
462
463 /* some nice utility functions */
464
465 EditVert *editedge_getOtherVert(EditEdge *eed, EditVert *eve)
466 {
467         if (eve==eed->v1) {
468                 return eed->v2;
469         } else if (eve==eed->v2) {
470                 return eed->v1;
471         } else {
472                 return NULL;
473         }
474 }
475
476 EditVert *editedge_getSharedVert(EditEdge *eed, EditEdge *eed2) 
477 {
478         if (eed->v1==eed2->v1 || eed->v1==eed2->v2) {
479                 return eed->v1;
480         } else if (eed->v2==eed2->v1 || eed->v2==eed2->v2) {
481                 return eed->v2;
482         } else {
483                 return NULL;
484         }
485 }
486
487 int editedge_containsVert(EditEdge *eed, EditVert *eve) 
488 {
489         return (eed->v1==eve || eed->v2==eve);
490 }
491
492 int editface_containsVert(EditFace *efa, EditVert *eve) 
493 {
494         return (efa->v1==eve || efa->v2==eve || efa->v3==eve || (efa->v4 && efa->v4==eve));
495 }
496
497 int editface_containsEdge(EditFace *efa, EditEdge *eed) 
498 {
499         return (efa->e1==eed || efa->e2==eed || efa->e3==eed || (efa->e4 && efa->e4==eed));
500 }
501
502
503 /* ************************ stuct EditMesh manipulation ***************************** */
504
505 /* fake callocs for fastmalloc below */
506 static void *calloc_fastvert(size_t size, size_t nr)
507 {
508         EditVert *eve= G.editMesh->curvert++;
509         eve->fast= 1;
510         return eve;
511 }
512 static void *calloc_fastedge(size_t size, size_t nr)
513 {
514         EditEdge *eed= G.editMesh->curedge++;
515         eed->fast= 1;
516         return eed;
517 }
518 static void *calloc_fastface(size_t size, size_t nr)
519 {
520         EditFace *efa= G.editMesh->curface++;
521         efa->fast= 1;
522         return efa;
523 }
524
525 /* allocate 1 chunk for all vertices, edges, faces. These get tagged to
526    prevent it from being freed
527 */
528 static void init_editmesh_fastmalloc(EditMesh *em, int totvert, int totedge, int totface)
529 {
530         if(totvert) em->allverts= MEM_callocN(totvert*sizeof(EditVert), "allverts");
531         else em->allverts= NULL;
532         em->curvert= em->allverts;
533         
534         if(totedge==0) totedge= 4*totface;      // max possible
535
536         if(totedge) em->alledges= MEM_callocN(totedge*sizeof(EditEdge), "alledges");
537         else em->alledges= NULL;
538         em->curedge= em->alledges;
539         
540         if(totface) em->allfaces= MEM_callocN(totface*sizeof(EditFace), "allfaces");
541         else em->allfaces= NULL;
542         em->curface= em->allfaces;
543
544         callocvert= calloc_fastvert;
545         callocedge= calloc_fastedge;
546         callocface= calloc_fastface;
547 }
548
549 static void end_editmesh_fastmalloc(void)
550 {
551         callocvert= calloc;
552         callocedge= calloc;
553         callocface= calloc;
554 }
555
556 void free_editMesh(EditMesh *em)
557 {
558 #ifdef WITH_VERSE
559         struct VNode *vnode=NULL;
560 #endif
561         if(em==NULL) return;
562
563 #ifdef WITH_VERSE
564         if(em->vnode) {
565                 vnode = (VNode*)em->vnode;
566                 em->vnode = NULL;
567         }
568 #endif
569
570         if(em->verts.first) free_vertlist(&em->verts);
571         if(em->edges.first) free_edgelist(&em->edges);
572         if(em->faces.first) free_facelist(&em->faces);
573         if(em->selected.first) BLI_freelistN(&(em->selected));
574
575         CustomData_free(&em->vdata, 0);
576         CustomData_free(&em->fdata, 0);
577
578         if(em->derivedFinal) {
579                 if (em->derivedFinal!=em->derivedCage) {
580                         em->derivedFinal->needsFree= 1;
581                         em->derivedFinal->release(em->derivedFinal);
582                 }
583                 em->derivedFinal= NULL;
584         }
585         if(em->derivedCage) {
586                 em->derivedCage->needsFree= 1;
587                 em->derivedCage->release(em->derivedCage);
588                 em->derivedCage= NULL;
589         }
590
591 #ifdef WITH_VERSE
592         if(vnode) {
593                 em->vnode = (void*)vnode;
594         }
595 #endif
596
597         /* DEBUG: hashtabs are slowest part of enter/exit editmode. here a testprint */
598 #if 0
599         if(em->hashedgetab) {
600                 HashEdge *he, *hen;
601                 int a, used=0, max=0, nr;
602                 he= em->hashedgetab;
603                 for(a=0; a<EDHASHSIZE; a++, he++) {
604                         if(he->eed) used++;
605                         hen= he->next;
606                         nr= 0;
607                         while(hen) {
608                                 nr++;
609                                 hen= hen->next;
610                         }
611                         if(max<nr) max= nr;
612                 }
613                 printf("hastab used %d max %d\n", used, max);
614         }
615 #endif
616         if(em->hashedgetab) MEM_freeN(em->hashedgetab);
617         em->hashedgetab= NULL;
618         
619         if(em->allverts) MEM_freeN(em->allverts);
620         if(em->alledges) MEM_freeN(em->alledges);
621         if(em->allfaces) MEM_freeN(em->allfaces);
622         
623         em->allverts= em->curvert= NULL;
624         em->alledges= em->curedge= NULL;
625         em->allfaces= em->curface= NULL;
626         
627         mesh_octree_table(NULL, NULL, 'e');
628         
629         G.totvert= G.totface= 0;
630
631         if(em->retopo_paint_data) retopo_free_paint_data(em->retopo_paint_data);
632         em->retopo_paint_data= NULL;
633 }
634
635 /* on G.editMesh */
636 static void editMesh_set_hash(void)
637 {
638         EditEdge *eed;
639
640         G.editMesh->hashedgetab= NULL;
641         
642         for(eed=G.editMesh->edges.first; eed; eed= eed->next)  {
643                 if( findedgelist(eed->v1, eed->v2)==NULL )
644                         insert_hashedge(eed);
645         }
646
647 }
648
649
650 /* ************************ IN & OUT EDITMODE ***************************** */
651
652
653 static void edge_normal_compare(EditEdge *eed, EditFace *efa1)
654 {
655         EditFace *efa2;
656         float cent1[3], cent2[3];
657         float inp;
658         
659         efa2 = eed->tmp.f;
660         if(efa1==efa2) return;
661         
662         inp= efa1->n[0]*efa2->n[0] + efa1->n[1]*efa2->n[1] + efa1->n[2]*efa2->n[2];
663         if(inp<0.999 && inp >-0.999) eed->f2= 1;
664                 
665         if(efa1->v4) CalcCent4f(cent1, efa1->v1->co, efa1->v2->co, efa1->v3->co, efa1->v4->co);
666         else CalcCent3f(cent1, efa1->v1->co, efa1->v2->co, efa1->v3->co);
667         if(efa2->v4) CalcCent4f(cent2, efa2->v1->co, efa2->v2->co, efa2->v3->co, efa2->v4->co);
668         else CalcCent3f(cent2, efa2->v1->co, efa2->v2->co, efa2->v3->co);
669         
670         VecSubf(cent1, cent2, cent1);
671         Normalize(cent1);
672         inp= cent1[0]*efa1->n[0] + cent1[1]*efa1->n[1] + cent1[2]*efa1->n[2]; 
673
674         if(inp < -0.001 ) eed->f1= 1;
675 }
676
677 #if 0
678 typedef struct {
679         EditEdge *eed;
680         float noLen,no[3];
681         int adjCount;
682 } EdgeDrawFlagInfo;
683
684 static int edgeDrawFlagInfo_cmp(const void *av, const void *bv)
685 {
686         const EdgeDrawFlagInfo *a = av;
687         const EdgeDrawFlagInfo *b = bv;
688
689         if (a->noLen<b->noLen) return -1;
690         else if (a->noLen>b->noLen) return 1;
691         else return 0;
692 }
693 #endif
694
695 static void edge_drawflags(void)
696 {
697         EditMesh *em = G.editMesh;
698         EditVert *eve;
699         EditEdge *eed, *e1, *e2, *e3, *e4;
700         EditFace *efa;
701         
702         /* - count number of times edges are used in faces: 0 en 1 time means draw edge
703          * - edges more than 1 time used: in *tmp.f is pointer to first face
704          * - check all faces, when normal differs to much: draw (flag becomes 1)
705          */
706
707         /* later on: added flags for 'cylinder' and 'sphere' intersection tests in old
708            game engine (2.04)
709          */
710         
711         recalc_editnormals();
712         
713         /* init */
714         eve= em->verts.first;
715         while(eve) {
716                 eve->f1= 1;             /* during test it's set at zero */
717                 eve= eve->next;
718         }
719         eed= em->edges.first;
720         while(eed) {
721                 eed->f2= eed->f1= 0;
722                 eed->tmp.f = 0;
723                 eed= eed->next;
724         }
725
726         efa= em->faces.first;
727         while(efa) {
728                 e1= efa->e1;
729                 e2= efa->e2;
730                 e3= efa->e3;
731                 e4= efa->e4;
732                 if(e1->f2<4) e1->f2+= 1;
733                 if(e2->f2<4) e2->f2+= 1;
734                 if(e3->f2<4) e3->f2+= 1;
735                 if(e4 && e4->f2<4) e4->f2+= 1;
736                 
737                 if(e1->tmp.f == 0) e1->tmp.f = (void *) efa;
738                 if(e2->tmp.f == 0) e2->tmp.f = (void *) efa;
739                 if(e3->tmp.f ==0) e3->tmp.f = (void *) efa;
740                 if(e4 && (e4->tmp.f == 0)) e4->tmp.f = (void *) efa;
741                 
742                 efa= efa->next;
743         }
744
745         if(G.f & G_ALLEDGES) {
746                 efa= em->faces.first;
747                 while(efa) {
748                         if(efa->e1->f2>=2) efa->e1->f2= 1;
749                         if(efa->e2->f2>=2) efa->e2->f2= 1;
750                         if(efa->e3->f2>=2) efa->e3->f2= 1;
751                         if(efa->e4 && efa->e4->f2>=2) efa->e4->f2= 1;
752                         
753                         efa= efa->next;
754                 }               
755         }       
756         else {
757                 
758                 /* handle single-edges for 'test cylinder flag' (old engine) */
759                 
760                 eed= em->edges.first;
761                 while(eed) {
762                         if(eed->f2==1) eed->f1= 1;
763                         eed= eed->next;
764                 }
765
766                 /* all faces, all edges with flag==2: compare normal */
767                 efa= em->faces.first;
768                 while(efa) {
769                         if(efa->e1->f2==2) edge_normal_compare(efa->e1, efa);
770                         else efa->e1->f2= 1;
771                         if(efa->e2->f2==2) edge_normal_compare(efa->e2, efa);
772                         else efa->e2->f2= 1;
773                         if(efa->e3->f2==2) edge_normal_compare(efa->e3, efa);
774                         else efa->e3->f2= 1;
775                         if(efa->e4) {
776                                 if(efa->e4->f2==2) edge_normal_compare(efa->e4, efa);
777                                 else efa->e4->f2= 1;
778                         }
779                         efa= efa->next;
780                 }
781                 
782                 /* sphere collision flag */
783                 
784                 eed= em->edges.first;
785                 while(eed) {
786                         if(eed->f1!=1) {
787                                 eed->v1->f1= eed->v2->f1= 0;
788                         }
789                         eed= eed->next;
790                 }
791                 
792         }
793 }
794
795 /* turns Mesh into editmesh */
796 void make_editMesh()
797 {
798         Mesh *me= G.obedit->data;
799         EditMesh *em= G.editMesh;
800         MFace *mface;
801         MVert *mvert;
802         MSelect *mselect;
803         KeyBlock *actkey;
804         EditVert *eve, **evlist, *eve1, *eve2, *eve3, *eve4;
805         EditFace *efa;
806         EditEdge *eed;
807         EditSelection *ese;
808         int tot, a, eekadoodle= 0, cloth_enabled = 0;
809         ClothModifierData *clmd = NULL;
810         Cloth *cloth = NULL;
811         float temp[3];
812
813 #ifdef WITH_VERSE
814         if(me->vnode){
815                 create_edit_mesh_from_geom_node(me->vnode);
816                 return;
817         }
818 #endif
819
820         /* because of reload */
821         free_editMesh(em);
822         
823         em->act_face = NULL;
824         G.totvert= tot= me->totvert;
825         G.totedge= me->totedge;
826         G.totface= me->totface;
827         
828         if(tot==0) {
829                 countall();
830                 return;
831         }
832         
833         /* initialize fastmalloc for editmesh */
834         init_editmesh_fastmalloc(em, me->totvert, me->totedge, me->totface);
835
836         actkey = ob_get_keyblock(G.obedit);
837         if(actkey) {
838                 strcpy(G.editModeTitleExtra, "(Key) ");
839                 key_to_mesh(actkey, me);
840                 tot= actkey->totelem;
841         }
842
843         /* make editverts */
844         CustomData_copy(&me->vdata, &em->vdata, CD_MASK_EDITMESH, CD_CALLOC, 0);
845         mvert= me->mvert;
846         
847         /* lots of checks to be sure if we have nice cloth object */
848         if(modifiers_isClothEnabled(G.obedit))
849         {
850                 clmd = (ClothModifierData *) modifiers_findByType(G.obedit, eModifierType_Cloth);
851                 cloth = clmd->clothObject;
852                 
853                 /* just to be sure also check vertcount */
854                 /* also check if we have a protected cache */
855                 if(cloth && (tot == cloth->numverts) && (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_CCACHE_PROTECT))
856                 {
857                         /* check if we have cache for this frame */
858                         int stack_index = modifiers_indexInObject(G.obedit, (ModifierData *)clmd);
859                 
860                         if(BKE_ptcache_id_exist((ID *)G.obedit, G.scene->r.cfra, stack_index))
861                         {
862                                 cloth_enabled = 1;
863                                 
864                                 clmd->sim_parms->editedframe = G.scene->r.cfra;
865                                 clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_EDITMODE;
866                                 
867                                 /* inverse matrix is not uptodate... */
868                                 Mat4Invert ( G.obedit->imat, G.obedit->obmat );
869                                 if(G.rt > 0)
870                                 printf("make_editmesh --> cloth_enabled\n");
871                         }
872                 }
873         }
874
875         evlist= (EditVert **)MEM_mallocN(tot*sizeof(void *),"evlist");
876         for(a=0; a<tot; a++, mvert++) {
877                 
878                 if(cloth_enabled)
879                 {
880                         VECCOPY(temp, cloth->verts[a].x);
881                         Mat4MulVecfl ( G.obedit->imat, temp );
882                         eve= addvertlist(temp, NULL);
883                         
884                         /* TODO: what about normals? */
885                 }
886                 else    
887                         eve= addvertlist(mvert->co, NULL);
888                 evlist[a]= eve;
889                 
890                 // face select sets selection in next loop
891                 if( (FACESEL_PAINT_TEST)==0 )
892                         eve->f |= (mvert->flag & 1);
893                 
894                 if (mvert->flag & ME_HIDE) eve->h= 1;           
895                 eve->no[0]= mvert->no[0]/32767.0;
896                 eve->no[1]= mvert->no[1]/32767.0;
897                 eve->no[2]= mvert->no[2]/32767.0;
898
899                 /* lets overwrite the keyindex of the editvert
900                  * with the order it used to be in before
901                  * editmode
902                  */
903                 eve->keyindex = a;
904
905                 CustomData_to_em_block(&me->vdata, &em->vdata, a, &eve->data);
906         }
907
908         if(actkey && actkey->totelem!=me->totvert);
909         else {
910                 MEdge *medge= me->medge;
911                 
912                 CustomData_copy(&me->edata, &em->edata, CD_MASK_EDITMESH, CD_CALLOC, 0);
913                 /* make edges */
914                 for(a=0; a<me->totedge; a++, medge++) {
915                         eed= addedgelist(evlist[medge->v1], evlist[medge->v2], NULL);
916                         /* eed can be zero when v1 and v2 are identical, dxf import does this... */
917                         if(eed) {
918                                 eed->crease= ((float)medge->crease)/255.0;
919                                 
920                                 if(medge->flag & ME_SEAM) eed->seam= 1;
921                                 if(medge->flag & ME_SHARP) eed->sharp = 1;
922                                 if(medge->flag & SELECT) eed->f |= SELECT;
923                                 if(medge->flag & ME_FGON) eed->h= EM_FGON;      // 2 different defines!
924                                 if(medge->flag & ME_HIDE) eed->h |= 1;
925                                 if(G.scene->selectmode==SCE_SELECT_EDGE) 
926                                         EM_select_edge(eed, eed->f & SELECT);           // force edge selection to vertices, seems to be needed ...
927                                 CustomData_to_em_block(&me->edata,&em->edata, a, &eed->data);
928                         }
929                 }
930                 
931                 CustomData_copy(&me->fdata, &em->fdata, CD_MASK_EDITMESH, CD_CALLOC, 0);
932
933                 /* make faces */
934                 mface= me->mface;
935
936                 for(a=0; a<me->totface; a++, mface++) {
937                         eve1= evlist[mface->v1];
938                         eve2= evlist[mface->v2];
939                         if(!mface->v3) eekadoodle= 1;
940                         eve3= evlist[mface->v3];
941                         if(mface->v4) eve4= evlist[mface->v4]; else eve4= NULL;
942                         
943                         efa= addfacelist(eve1, eve2, eve3, eve4, NULL, NULL);
944
945                         if(efa) {
946                                 CustomData_to_em_block(&me->fdata, &em->fdata, a, &efa->data);
947
948                                 efa->mat_nr= mface->mat_nr;
949                                 efa->flag= mface->flag & ~ME_HIDE;
950                                 
951                                 /* select and hide face flag */
952                                 if(mface->flag & ME_FACE_SEL) {
953                                         efa->f |= SELECT;
954                                 }
955                                 if(mface->flag & ME_HIDE) efa->h= 1;
956
957                                 if((FACESEL_PAINT_TEST) && (efa->f & SELECT))
958                                         EM_select_face(efa, 1); /* flush down */
959                                 
960                                 if (a==me->act_face)
961                                         em->act_face = efa;
962                         }
963                 }
964         }
965         
966         if(eekadoodle)
967                 error("This Mesh has old style edgecodes, please put it in the bugtracker!");
968         
969         MEM_freeN(evlist);
970
971         end_editmesh_fastmalloc();      // resets global function pointers
972         
973         if(me->mselect){
974                 //restore editselections
975                 EM_init_index_arrays(1,1,1);
976                 mselect = me->mselect;
977                 
978                 for(a=0; a<me->totselect; a++, mselect++){
979                         /*check if recorded selection is still valid, if so copy into editmesh*/
980                         if( (mselect->type == EDITVERT && me->mvert[mselect->index].flag & SELECT) || (mselect->type == EDITEDGE && me->medge[mselect->index].flag & SELECT) || (mselect->type == EDITFACE && me->mface[mselect->index].flag & ME_FACE_SEL) ){
981                                 ese = MEM_callocN(sizeof(EditSelection), "Edit Selection");
982                                 ese->type = mselect->type;      
983                                 if(ese->type == EDITVERT) ese->data = EM_get_vert_for_index(mselect->index); else
984                                 if(ese->type == EDITEDGE) ese->data = EM_get_edge_for_index(mselect->index); else
985                                 if(ese->type == EDITFACE) ese->data = EM_get_face_for_index(mselect->index);
986                                 BLI_addtail(&(em->selected),ese);
987                         }
988                 }
989                 EM_free_index_arrays();
990         }
991         /* this creates coherent selections. also needed for older files */
992         EM_selectmode_set();
993         /* paranoia check to enforce hide rules */
994         EM_hide_reset();
995         /* sets helper flags which arent saved */
996         EM_fgon_flags();
997         
998         countall();
999         
1000 }
1001
1002 /* makes Mesh out of editmesh */
1003 void load_editMesh(void)
1004 {
1005         EditMesh *em = G.editMesh;
1006         Mesh *me= G.obedit->data;
1007         MVert *mvert, *oldverts;
1008         MEdge *medge;
1009         MFace *mface;
1010         MSelect *mselect;
1011         EditVert *eve;
1012         EditFace *efa;
1013         EditEdge *eed;
1014         EditSelection *ese;
1015         float *fp, *newkey, *oldkey, nor[3];
1016         int i, a, ototvert, totedge=0, cloth_enabled = 0;
1017         ClothModifierData *clmd = NULL;
1018         Cloth *cloth = NULL;
1019         float temp[3], dt = 0.0;
1020         
1021 #ifdef WITH_VERSE
1022         if(em->vnode) {
1023                 struct VNode *vnode = (VNode*)em->vnode;
1024                 ((VGeomData*)vnode->data)->editmesh = NULL;
1025                 em->vnode = NULL;
1026         }
1027 #endif
1028
1029         countall();
1030
1031         /* this one also tests of edges are not in faces: */
1032         /* eed->f2==0: not in face, f2==1: draw it */
1033         /* eed->f1 : flag for dynaface (cylindertest, old engine) */
1034         /* eve->f1 : flag for dynaface (sphere test, old engine) */
1035         /* eve->f2 : being used in vertexnormals */
1036         edge_drawflags();
1037         
1038         eed= em->edges.first;
1039         while(eed) {
1040                 totedge++;
1041                 eed= eed->next;
1042         }
1043         
1044         /* new Vertex block */
1045         if(G.totvert==0) mvert= NULL;
1046         else mvert= MEM_callocN(G.totvert*sizeof(MVert), "loadeditMesh vert");
1047
1048         /* new Edge block */
1049         if(totedge==0) medge= NULL;
1050         else medge= MEM_callocN(totedge*sizeof(MEdge), "loadeditMesh edge");
1051         
1052         /* new Face block */
1053         if(G.totface==0) mface= NULL;
1054         else mface= MEM_callocN(G.totface*sizeof(MFace), "loadeditMesh face");
1055
1056         /* lets save the old verts just in case we are actually working on
1057          * a key ... we now do processing of the keys at the end */
1058         oldverts= me->mvert;
1059         ototvert= me->totvert;
1060
1061         /* don't free this yet */
1062         CustomData_set_layer(&me->vdata, CD_MVERT, NULL);
1063
1064         /* free custom data */
1065         CustomData_free(&me->vdata, me->totvert);
1066         CustomData_free(&me->edata, me->totedge);
1067         CustomData_free(&me->fdata, me->totface);
1068
1069         /* add new custom data */
1070         me->totvert= G.totvert;
1071         me->totedge= totedge;
1072         me->totface= G.totface;
1073
1074         CustomData_copy(&em->vdata, &me->vdata, CD_MASK_MESH, CD_CALLOC, me->totvert);
1075         CustomData_copy(&em->edata, &me->edata, CD_MASK_MESH, CD_CALLOC, me->totedge);
1076         CustomData_copy(&em->fdata, &me->fdata, CD_MASK_MESH, CD_CALLOC, me->totface);
1077
1078         CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, mvert, me->totvert);
1079         CustomData_add_layer(&me->edata, CD_MEDGE, CD_ASSIGN, medge, me->totedge);
1080         CustomData_add_layer(&me->fdata, CD_MFACE, CD_ASSIGN, mface, me->totface);
1081         mesh_update_customdata_pointers(me);
1082
1083         /* the vertices, use ->tmp.l as counter */
1084         eve= em->verts.first;
1085         a= 0;
1086         
1087         /* lots of checks to be sure if we have nice cloth object */
1088         if(modifiers_isClothEnabled(G.obedit))
1089         {
1090                 clmd = (ClothModifierData *) modifiers_findByType(G.obedit, eModifierType_Cloth);
1091                 cloth = clmd->clothObject;
1092                 
1093                 /* just to be sure also check vertcount */
1094                 /* also check if we have a protected cache */
1095                 if(cloth && (G.totvert == cloth->numverts) && (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_CCACHE_PROTECT))
1096                 {
1097                         /* check if we have cache for this frame */
1098                         int stack_index = modifiers_indexInObject(G.obedit, (ModifierData *)clmd);
1099                 
1100                         if(BKE_ptcache_id_exist((ID *)G.obedit, clmd->sim_parms->editedframe, stack_index))
1101                         {
1102                                 cloth_enabled = 1;
1103                                 
1104                                 /* inverse matrix is not uptodate... */
1105                                 Mat4Invert ( G.obedit->imat, G.obedit->obmat );
1106                                 dt = 1.0f / clmd->sim_parms->stepsPerFrame;
1107                         }
1108                         if(G.rt > 0)
1109                         printf("loadmesh --> tot: %d, num: %d\n", G.totvert, cloth->numverts);
1110                 }
1111         }
1112         
1113         i=0;
1114         while(eve) {
1115                 
1116                 if(cloth_enabled)
1117                 {       
1118                         if(G.rt > 0)
1119                         printf("loadmesh --> cloth_enabled\n");
1120                         
1121                         VECCOPY(temp, cloth->verts[i].x);
1122                         VECCOPY(cloth->verts[i].x, eve->co);
1123                         Mat4MulVecfl ( G.obedit->obmat, cloth->verts[i].x );
1124                         
1125                         
1126                         // not physical correct but gives nicer results when commented
1127                         VECSUB(temp, cloth->verts[i].x, temp);
1128                         VecMulf(temp, 1.0f / (dt*10.0));
1129                         VECADD(cloth->verts[i].v, cloth->verts[i].v, temp);
1130                         
1131                         if(oldverts) {
1132                                 VECCOPY(mvert->co, oldverts[i].co);
1133                                 if(G.rt > 0)
1134                                 printf("loadmesh --> cloth_enabled oldverts\n");
1135                         }
1136                         i++;
1137                 }
1138                 else    
1139                         VECCOPY(mvert->co, eve->co);
1140                 mvert->mat_nr= 255;  /* what was this for, halos? */
1141                 
1142                 /* vertex normal */
1143                 VECCOPY(nor, eve->no);
1144                 VecMulf(nor, 32767.0);
1145                 VECCOPY(mvert->no, nor);
1146
1147                 /* note: it used to remove me->dvert when it was not in use, cancelled
1148                    that... annoying when you have a fresh vgroup */
1149                 CustomData_from_em_block(&em->vdata, &me->vdata, eve->data, a);
1150
1151                 eve->tmp.l = a++;  /* counter */
1152                         
1153                 mvert->flag= 0;
1154                 if(eve->f1==1) mvert->flag |= ME_SPHERETEST;
1155                 mvert->flag |= (eve->f & SELECT);
1156                 if (eve->h) mvert->flag |= ME_HIDE;                     
1157
1158 #ifdef WITH_VERSE
1159                 if(eve->vvert) {
1160                         ((VerseVert*)eve->vvert)->vertex = NULL;
1161                         eve->vvert = NULL;
1162                 }
1163 #endif                  
1164                 eve= eve->next;
1165                 mvert++;
1166         }
1167         
1168         /* burn changes to cache */
1169         if(cloth_enabled)
1170         {
1171                 if(G.rt > 0)
1172                 printf("loadmesh --> cloth_enabled cloth_write_cache\n");
1173                 cloth_write_cache(G.obedit, clmd, clmd->sim_parms->editedframe);
1174                 cloth_read_cache(G.obedit, clmd, G.scene->r.cfra);
1175                 implicit_set_positions(clmd);
1176                 
1177                 clmd->sim_parms->flags &= ~CLOTH_SIMSETTINGS_FLAG_EDITMODE;
1178         }
1179         else
1180         {
1181                 if(modifiers_isClothEnabled(G.obedit)) {
1182                         ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(G.obedit, eModifierType_Cloth);
1183                         if(G.rt > 0)
1184                         printf("loadmesh --> CLOTH_SIMSETTINGS_FLAG_RESET\n");
1185                         /* only reset cloth when no cache was used */
1186                         clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_RESET;
1187                         clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_CCACHE_FFREE;
1188                         clmd->sim_parms->flags &= ~CLOTH_SIMSETTINGS_FLAG_EDITMODE;
1189                 }
1190         }
1191
1192         /* the edges */
1193         a= 0;
1194         eed= em->edges.first;
1195         while(eed) {
1196                 medge->v1= (unsigned int) eed->v1->tmp.l;
1197                 medge->v2= (unsigned int) eed->v2->tmp.l;
1198                 
1199                 medge->flag= (eed->f & SELECT) | ME_EDGERENDER;
1200                 if(eed->f2<2) medge->flag |= ME_EDGEDRAW;
1201                 if(eed->f2==0) medge->flag |= ME_LOOSEEDGE;
1202                 if(eed->sharp) medge->flag |= ME_SHARP;
1203                 if(eed->seam) medge->flag |= ME_SEAM;
1204                 if(eed->h & EM_FGON) medge->flag |= ME_FGON;    // different defines yes
1205                 if(eed->h & 1) medge->flag |= ME_HIDE;
1206                 
1207                 medge->crease= (char)(255.0*eed->crease);
1208                 CustomData_from_em_block(&em->edata, &me->edata, eed->data, a);         
1209
1210                 eed->tmp.l = a++;
1211                 
1212                 medge++;
1213                 eed= eed->next;
1214         }
1215
1216         /* the faces */
1217         a = 0;
1218         efa= em->faces.first;
1219         i = 0;
1220         me->act_face = -1;
1221         while(efa) {
1222                 mface= &((MFace *) me->mface)[i];
1223                 
1224                 mface->v1= (unsigned int) efa->v1->tmp.l;
1225                 mface->v2= (unsigned int) efa->v2->tmp.l;
1226                 mface->v3= (unsigned int) efa->v3->tmp.l;
1227                 if (efa->v4) mface->v4 = (unsigned int) efa->v4->tmp.l;
1228
1229                 mface->mat_nr= efa->mat_nr;
1230                 
1231                 mface->flag= efa->flag;
1232                 /* bit 0 of flag is already taken for smooth... */
1233                 
1234                 if(efa->h) {
1235                         mface->flag |= ME_HIDE;
1236                         mface->flag &= ~ME_FACE_SEL;
1237                 } else {
1238                         if(efa->f & 1) mface->flag |= ME_FACE_SEL;
1239                         else mface->flag &= ~ME_FACE_SEL;
1240                 }
1241                 
1242                 /* mat_nr in vertex */
1243                 if(me->totcol>1) {
1244                         mvert= me->mvert+mface->v1;
1245                         if(mvert->mat_nr == (char)255) mvert->mat_nr= mface->mat_nr;
1246                         mvert= me->mvert+mface->v2;
1247                         if(mvert->mat_nr == (char)255) mvert->mat_nr= mface->mat_nr;
1248                         mvert= me->mvert+mface->v3;
1249                         if(mvert->mat_nr == (char)255) mvert->mat_nr= mface->mat_nr;
1250                         if(mface->v4) {
1251                                 mvert= me->mvert+mface->v4;
1252                                 if(mvert->mat_nr == (char)255) mvert->mat_nr= mface->mat_nr;
1253                         }
1254                 }
1255                         
1256                 /* watch: efa->e1->f2==0 means loose edge */ 
1257                         
1258                 if(efa->e1->f2==1) {
1259                         efa->e1->f2= 2;
1260                 }                       
1261                 if(efa->e2->f2==1) {
1262                         efa->e2->f2= 2;
1263                 }
1264                 if(efa->e3->f2==1) {
1265                         efa->e3->f2= 2;
1266                 }
1267                 if(efa->e4 && efa->e4->f2==1) {
1268                         efa->e4->f2= 2;
1269                 }
1270
1271                 CustomData_from_em_block(&em->fdata, &me->fdata, efa->data, i);
1272
1273                 /* no index '0' at location 3 or 4 */
1274                 test_index_face(mface, &me->fdata, i, efa->v4?4:3);
1275                 
1276                 if (EM_get_actFace() == efa)
1277                         me->act_face = a;
1278
1279 #ifdef WITH_VERSE
1280                 if(efa->vface) {
1281                         ((VerseFace*)efa->vface)->face = NULL;
1282                         efa->vface = NULL;
1283                 }
1284 #endif          
1285                 efa->tmp.l = a++;
1286                 i++;
1287                 efa= efa->next;
1288         }
1289
1290         /* patch hook indices and vertex parents */
1291         {
1292                 Object *ob;
1293                 ModifierData *md;
1294                 EditVert *eve, **vertMap = NULL;
1295                 int i,j;
1296
1297                 for (ob=G.main->object.first; ob; ob=ob->id.next) {
1298                         if (ob->parent==G.obedit && ELEM(ob->partype, PARVERT1,PARVERT3)) {
1299                                 
1300                                 /* duplicate code from below, make it function later...? */
1301                                 if (!vertMap) {
1302                                         vertMap = MEM_callocN(sizeof(*vertMap)*ototvert, "vertMap");
1303                                         
1304                                         for (eve=em->verts.first; eve; eve=eve->next) {
1305                                                 if (eve->keyindex!=-1)
1306                                                         vertMap[eve->keyindex] = eve;
1307                                         }
1308                                 }
1309                                 if(ob->par1 < ototvert) {
1310                                         eve = vertMap[ob->par1];
1311                                         if(eve) ob->par1= eve->tmp.l;
1312                                 }
1313                                 if(ob->par2 < ototvert) {
1314                                         eve = vertMap[ob->par2];
1315                                         if(eve) ob->par2= eve->tmp.l;
1316                                 }
1317                                 if(ob->par3 < ototvert) {
1318                                         eve = vertMap[ob->par3];
1319                                         if(eve) ob->par3= eve->tmp.l;
1320                                 }
1321                                 
1322                         }
1323                         if (ob->data==me) {
1324                                 for (md=ob->modifiers.first; md; md=md->next) {
1325                                         if (md->type==eModifierType_Hook) {
1326                                                 HookModifierData *hmd = (HookModifierData*) md;
1327
1328                                                 if (!vertMap) {
1329                                                         vertMap = MEM_callocN(sizeof(*vertMap)*ototvert, "vertMap");
1330
1331                                                         for (eve=em->verts.first; eve; eve=eve->next) {
1332                                                                 if (eve->keyindex!=-1)
1333                                                                         vertMap[eve->keyindex] = eve;
1334                                                         }
1335                                                 }
1336                                                 
1337                                                 for (i=j=0; i<hmd->totindex; i++) {
1338                                                         if(hmd->indexar[i] < ototvert) {
1339                                                                 eve = vertMap[hmd->indexar[i]];
1340                                                                 
1341                                                                 if (eve) {
1342                                                                         hmd->indexar[j++] = eve->tmp.l;
1343                                                                 }
1344                                                         }
1345                                                         else j++;
1346                                                 }
1347
1348                                                 hmd->totindex = j;
1349                                         }
1350                                 }
1351                         }
1352                 }
1353
1354                 if (vertMap) MEM_freeN(vertMap);
1355         }
1356
1357         /* are there keys? */
1358         if(me->key) {
1359                 KeyBlock *currkey, *actkey = ob_get_keyblock(G.obedit);
1360
1361                 /* Lets reorder the key data so that things line up roughly
1362                  * with the way things were before editmode */
1363                 currkey = me->key->block.first;
1364                 while(currkey) {
1365                         
1366                         fp= newkey= MEM_callocN(me->key->elemsize*G.totvert,  "currkey->data");
1367                         oldkey = currkey->data;
1368
1369                         eve= em->verts.first;
1370
1371                         i = 0;
1372                         mvert = me->mvert;
1373                         while(eve) {
1374                                 if (eve->keyindex >= 0 && eve->keyindex < currkey->totelem) { // valid old vertex
1375                                         if(currkey == actkey) {
1376                                                 if (actkey == me->key->refkey) {
1377                                                         VECCOPY(fp, mvert->co);
1378                                                 }
1379                                                 else {
1380                                                         VECCOPY(fp, mvert->co);
1381                                                         if(oldverts) {
1382                                                                 VECCOPY(mvert->co, oldverts[eve->keyindex].co);
1383                                                         }
1384                                                 }
1385                                         }
1386                                         else {
1387                                                 if(oldkey) {
1388                                                         VECCOPY(fp, oldkey + 3 * eve->keyindex);
1389                                                 }
1390                                         }
1391                                 }
1392                                 else {
1393                                         VECCOPY(fp, mvert->co);
1394                                 }
1395                                 fp+= 3;
1396                                 ++i;
1397                                 ++mvert;
1398                                 eve= eve->next;
1399                         }
1400                         currkey->totelem= G.totvert;
1401                         if(currkey->data) MEM_freeN(currkey->data);
1402                         currkey->data = newkey;
1403                         
1404                         currkey= currkey->next;
1405                 }
1406         }
1407
1408         if(oldverts) MEM_freeN(oldverts);
1409         
1410         i = 0;
1411         for(ese=em->selected.first; ese; ese=ese->next) i++;
1412         me->totselect = i;
1413         if(i==0) mselect= NULL;
1414         else mselect= MEM_callocN(i*sizeof(MSelect), "loadeditMesh selections");
1415         
1416         if(me->mselect) MEM_freeN(me->mselect);
1417         me->mselect= mselect;
1418         
1419         for(ese=em->selected.first; ese; ese=ese->next){
1420                 mselect->type = ese->type;
1421                 if(ese->type == EDITVERT) mselect->index = ((EditVert*)ese->data)->tmp.l;
1422                 else if(ese->type == EDITEDGE) mselect->index = ((EditEdge*)ese->data)->tmp.l;
1423                 else if(ese->type == EDITFACE) mselect->index = ((EditFace*)ese->data)->tmp.l;
1424                 mselect++;
1425         }
1426         
1427         /* to be sure: clear ->tmp.l pointers */
1428         eve= em->verts.first;
1429         while(eve) {
1430                 eve->tmp.l = 0;
1431                 eve= eve->next;
1432         }
1433         
1434         eed= em->edges.first;
1435         while(eed) { 
1436                 eed->tmp.l = 0;
1437                 eed= eed->next;
1438         }
1439         
1440         efa= em->faces.first;
1441         while(efa) {
1442                 efa->tmp.l = 0;
1443                 efa= efa->next;
1444         }
1445         
1446         /* remake softbody of all users */
1447         if(me->id.us>1) {
1448                 Base *base;
1449                 for(base= G.scene->base.first; base; base= base->next) {
1450                         if(base->object->data==me) {
1451                                 base->object->softflag |= OB_SB_REDO;
1452                                 base->object->recalc |= OB_RECALC_DATA;
1453                         }
1454                 }
1455         }
1456
1457         mesh_calc_normals(me->mvert, me->totvert, me->mface, me->totface, NULL);
1458 }
1459
1460 void remake_editMesh(void)
1461 {
1462         make_editMesh();
1463         allqueue(REDRAWVIEW3D, 0);
1464         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);
1465         BIF_undo_push("Undo all changes");
1466 }
1467
1468 /* ***************              (partial exit editmode) *************/
1469
1470
1471 void separatemenu(void)
1472 {
1473         short event;
1474
1475         if(G.editMesh->verts.first==NULL) return;
1476            
1477         event = pupmenu("Separate %t|Selected%x1|All Loose Parts%x2|By Material%x3");
1478         
1479         if (event==0) return;
1480         waitcursor(1);
1481         
1482         switch (event) {
1483         case 1: 
1484                 separate_mesh();                    
1485                 break;
1486         case 2:                     
1487                 separate_mesh_loose();              
1488                 break;
1489         case 3:
1490                 separate_material();
1491                 break;
1492         }
1493         waitcursor(0);
1494 }
1495
1496 void separate_material(void)
1497 {
1498         EditMesh *em = G.editMesh;
1499         unsigned char curr_mat;
1500         Mesh *me;
1501         
1502         if(multires_test()) return;
1503         
1504         me= get_mesh(G.obedit);
1505         if(me->key) {
1506                 error("Can't separate with vertex keys");
1507                 return;
1508         }
1509
1510         if(G.obedit && em) {
1511                 if(G.obedit->type == OB_MESH) {
1512                         for (curr_mat = 1; curr_mat < G.obedit->totcol; ++curr_mat) {
1513                                 /* clear selection, we're going to use that to select material group */
1514                                 EM_clear_flag_all(SELECT);
1515                                 /* select the material */
1516                                 editmesh_select_by_material(curr_mat);
1517                                 /* and now separate */
1518                                 separate_mesh();
1519                         }
1520                 }
1521         }
1522         
1523         countall();
1524         allqueue(REDRAWVIEW3D, 0);
1525         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);
1526
1527 }
1528
1529 void separate_mesh(void)
1530 {
1531         EditMesh *em = G.editMesh;
1532         EditMesh emcopy;
1533         EditVert *eve, *v1;
1534         EditEdge *eed, *e1;
1535         EditFace *efa, *vl1;
1536         Object *oldob;
1537         Mesh *me, *men;
1538         Base *base, *oldbase;
1539         ListBase edve, eded, edvl;
1540 #ifdef WITH_VERSE
1541         struct VNode *vnode = NULL;
1542 #endif
1543         
1544         TEST_EDITMESH
1545         if(multires_test()) return;
1546
1547         waitcursor(1);
1548         
1549         me= get_mesh(G.obedit);
1550         if(me->key) {
1551                 error("Can't separate with vertex keys");
1552                 return;
1553         }
1554         
1555         /* blender crashes in derivedmesh drawing if I don't do this... but why? 
1556                 Anyhoo, this function is horrible anyway (ton) 
1557                 the fluidsimFlag also has to be reset btw. (n_t) */
1558         if(G.obedit->fluidsimSettings) {
1559                 fluidsimSettingsFree(G.obedit->fluidsimSettings);
1560                 G.obedit->fluidsimSettings = NULL;
1561                 G.obedit->fluidsimFlag = 0;
1562         }
1563         
1564         if(em->selected.first) BLI_freelistN(&(em->selected)); /* clear the selection order */
1565                 
1566         EM_selectmode_set();    // enforce full consistant selection flags 
1567         
1568         /* we are going to abuse the system as follows:
1569          * 1. add a duplicate object: this will be the new one, we remember old pointer
1570          * 2: then do a split if needed.
1571          * 3. put apart: all NOT selected verts, edges, faces
1572          * 4. call load_editMesh(): this will be the new object
1573          * 5. freelist and get back old verts, edges, facs
1574          */
1575         
1576         /* make only obedit selected */
1577         base= FIRSTBASE;
1578         while(base) {
1579                 if(base->lay & G.vd->lay) {
1580                         if(base->object==G.obedit) base->flag |= SELECT;
1581                         else base->flag &= ~SELECT;
1582                 }
1583                 base= base->next;
1584         }
1585         
1586 #ifdef WITH_VERSE
1587         if(G.editMesh->vnode) {
1588                 vnode = G.editMesh->vnode;
1589                 G.editMesh->vnode = NULL;
1590         }
1591 #endif
1592         /* no test for split, split doesn't split when a loose part is selected */
1593         /* SPLIT: first make duplicate */
1594         adduplicateflag(SELECT);
1595
1596 #ifdef WITH_VERSE
1597         if(vnode) {
1598                 G.editMesh->vnode = vnode;
1599         }
1600 #endif
1601         /* SPLIT: old faces have 3x flag 128 set, delete these ones */
1602         delfaceflag(128);
1603         
1604         /* since we do tricky things with verts/edges/faces, this makes sure all is selected coherent */
1605         EM_selectmode_set();
1606         
1607         /* set apart: everything that is not selected */
1608         edve.first= edve.last= eded.first= eded.last= edvl.first= edvl.last= 0;
1609         eve= em->verts.first;
1610         while(eve) {
1611                 v1= eve->next;
1612                 if((eve->f & SELECT)==0) {
1613                         BLI_remlink(&em->verts, eve);
1614                         BLI_addtail(&edve, eve);
1615 #ifdef WITH_VERSE
1616                         if(eve->vvert) {
1617                                 ((VerseVert*)eve->vvert)->vertex = NULL;
1618                                 eve->vvert = NULL;
1619                         }
1620 #endif
1621                 }
1622                 
1623                 eve= v1;
1624         }
1625         eed= em->edges.first;
1626         while(eed) {
1627                 e1= eed->next;
1628                 if((eed->f & SELECT)==0) {
1629                         BLI_remlink(&em->edges, eed);
1630                         BLI_addtail(&eded, eed);
1631                 }
1632                 eed= e1;
1633         }
1634         efa= em->faces.first;
1635         while(efa) {
1636                 vl1= efa->next;
1637                 if((efa->f & SELECT)==0) {
1638                         BLI_remlink(&em->faces, efa);
1639                         BLI_addtail(&edvl, efa);
1640 #ifdef WITH_VERSE
1641                         if(efa->vface) {
1642                                 ((VerseFace*)efa->vface)->face = NULL;
1643                                 efa->vface = NULL;
1644                         }
1645 #endif
1646                 }
1647                 efa= vl1;
1648         }
1649         
1650         oldob= G.obedit;
1651         oldbase= BASACT;
1652         
1653 #ifdef WITH_VERSE
1654         if(G.obedit->vnode) {
1655                 vnode = G.obedit->vnode;
1656                 G.obedit->vnode = NULL;
1657         }
1658 #endif
1659         adduplicate(1, 0); /* notrans and a linked duplicate */
1660         
1661 #ifdef WITH_VERSE
1662         if(vnode) {
1663                 G.obedit->vnode = vnode;
1664         }
1665 #endif
1666         
1667         G.obedit= BASACT->object;       /* basact was set in adduplicate()  */
1668         
1669         men= copy_mesh(me);
1670         set_mesh(G.obedit, men);
1671         /* because new mesh is a copy: reduce user count */
1672         men->id.us--;
1673         
1674         load_editMesh();
1675         
1676         BASACT->flag &= ~SELECT;
1677         
1678         /* we cannot free the original buffer... */
1679         emcopy= *G.editMesh;
1680         emcopy.allverts= NULL;
1681         emcopy.alledges= NULL;
1682         emcopy.allfaces= NULL;
1683         emcopy.derivedFinal= emcopy.derivedCage= NULL;
1684         memset(&emcopy.vdata, 0, sizeof(emcopy.vdata));
1685         memset(&emcopy.fdata, 0, sizeof(emcopy.fdata));
1686         free_editMesh(&emcopy);
1687         
1688         em->verts= edve;
1689         em->edges= eded;
1690         em->faces= edvl;
1691         
1692         /* hashedges are freed now, make new! */
1693         editMesh_set_hash();
1694
1695         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);     
1696         G.obedit= oldob;
1697         BASACT= oldbase;
1698         BASACT->flag |= SELECT;
1699         
1700         waitcursor(0);
1701
1702         countall();
1703         allqueue(REDRAWVIEW3D, 0);
1704         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);     
1705
1706 }
1707
1708 void separate_mesh_loose(void)
1709 {
1710         EditMesh *em = G.editMesh;
1711         EditMesh emcopy;
1712         EditVert *eve, *v1;
1713         EditEdge *eed, *e1;
1714         EditFace *efa, *vl1;
1715         Object *oldob=NULL;
1716         Mesh *me, *men;
1717         Base *base, *oldbase;
1718         ListBase edve, eded, edvl;
1719         int vertsep=0;  
1720         short done=0, check=1;
1721 #ifdef WITH_VERSE
1722         struct VNode *vnode = NULL;
1723 #endif
1724                         
1725         me= get_mesh(G.obedit);
1726 #ifdef WITH_VERSE
1727         if(me->vnode) {
1728                 error("Can't separate a mesh shared at verse server");
1729                 return;
1730         }
1731 #endif
1732         if(me->key) {
1733                 error("Can't separate a mesh with vertex keys");
1734                 return;
1735         }
1736         
1737         /* same problem as in separate_mesh above (n_t) */
1738         if(G.obedit->fluidsimSettings) {
1739                 fluidsimSettingsFree(G.obedit->fluidsimSettings);
1740                 G.obedit->fluidsimSettings = NULL;
1741                 G.obedit->fluidsimFlag = 0;
1742         }
1743
1744         TEST_EDITMESH
1745         if(multires_test()) return;
1746         waitcursor(1);  
1747         
1748         /* we are going to abuse the system as follows:
1749          * 1. add a duplicate object: this will be the new one, we remember old pointer
1750          * 2: then do a split if needed.
1751          * 3. put apart: all NOT selected verts, edges, faces
1752          * 4. call load_editMesh(): this will be the new object
1753          * 5. freelist and get back old verts, edges, facs
1754          */
1755                         
1756         while(!done){           
1757                 vertsep=check=1;
1758                 
1759                 countall();
1760                 
1761                 /* make only obedit selected */
1762                 base= FIRSTBASE;
1763                 while(base) {
1764                         if(base->lay & G.vd->lay) {
1765                                 if(base->object==G.obedit) base->flag |= SELECT;
1766                                 else base->flag &= ~SELECT;
1767                         }
1768                         base= base->next;
1769                 }               
1770                 
1771                 /*--------- Select connected-----------*/               
1772                 
1773                 EM_clear_flag_all(SELECT);
1774
1775                 /* Select a random vert to start with */
1776                 eve= em->verts.first;
1777                 eve->f |= SELECT;
1778                 
1779                 while(check==1) {
1780                         check= 0;                       
1781                         eed= em->edges.first;                   
1782                         while(eed) {                            
1783                                 if(eed->h==0) {
1784                                         if(eed->v1->f & SELECT) {
1785                                                 if( (eed->v2->f & SELECT)==0 ) {
1786                                                         eed->v2->f |= SELECT;
1787                                                         vertsep++;
1788                                                         check= 1;
1789                                                 }
1790                                         }
1791                                         else if(eed->v2->f & SELECT) {
1792                                                 if( (eed->v1->f & SELECT)==0 ) {
1793                                                         eed->v1->f |= SELECT;
1794                                                         vertsep++;
1795                                                         check= SELECT;
1796                                                 }
1797                                         }
1798                                 }
1799                                 eed= eed->next;                         
1800                         }
1801                 }               
1802                 /*----------End of select connected--------*/
1803                 
1804                 
1805                 /* If the amount of vertices that is about to be split == the total amount 
1806                    of verts in the mesh, it means that there is only 1 unconnected object, so we don't have to separate
1807                 */
1808                 if(G.totvert==vertsep) done=1;                          
1809                 else{                   
1810                         /* No splitting: select connected goes fine */
1811                         
1812                         EM_select_flush();      // from verts->edges->faces
1813
1814                         /* set apart: everything that is not selected */
1815                         edve.first= edve.last= eded.first= eded.last= edvl.first= edvl.last= 0;
1816                         eve= em->verts.first;
1817                         while(eve) {
1818                                 v1= eve->next;
1819                                 if((eve->f & SELECT)==0) {
1820                                         BLI_remlink(&em->verts, eve);
1821                                         BLI_addtail(&edve, eve);
1822 #ifdef WITH_VERSE
1823                                         if(eve->vvert) {
1824                                                 b_verse_send_vertex_delete(eve);
1825                                         }
1826 #endif
1827                                 }
1828                                 eve= v1;
1829                         }
1830                         eed= em->edges.first;
1831                         while(eed) {
1832                                 e1= eed->next;
1833                                 if( (eed->f & SELECT)==0 ) {
1834                                         BLI_remlink(&em->edges, eed);
1835                                         BLI_addtail(&eded, eed);
1836                                 }
1837                                 eed= e1;
1838                         }
1839                         efa= em->faces.first;
1840                         while(efa) {
1841                                 vl1= efa->next;
1842                                 if( (efa->f & SELECT)==0 ) {
1843                                         BLI_remlink(&em->faces, efa);
1844                                         BLI_addtail(&edvl, efa);
1845 #ifdef WITH_VERSE
1846                                         if(efa->vface) {
1847                                                 b_verse_send_face_delete(efa);
1848                                         }
1849 #endif
1850                                 }
1851                                 efa= vl1;
1852                         }
1853                         
1854                         oldob= G.obedit;
1855                         oldbase= BASACT;
1856                         
1857 #ifdef WITH_VERSE
1858                         if(G.obedit->vnode) {
1859                                 vnode = G.obedit->vnode;
1860                                 G.obedit->vnode = NULL;
1861                         }
1862 #endif
1863                         adduplicate(1, 0); /* notrans and a linked duplicate*/
1864 #ifdef WITH_VERSE
1865                         if(vnode) {
1866                                 G.obedit->vnode = vnode;
1867                         }
1868 #endif
1869                         
1870                         G.obedit= BASACT->object;       /* basact was set in adduplicate()  */
1871
1872                         men= copy_mesh(me);
1873                         set_mesh(G.obedit, men);
1874                         /* because new mesh is a copy: reduce user count */
1875                         men->id.us--;
1876                         
1877                         load_editMesh();
1878                         
1879                         BASACT->flag &= ~SELECT;
1880                         
1881                         /* we cannot free the original buffer... */
1882                         emcopy= *G.editMesh;
1883                         emcopy.allverts= NULL;
1884                         emcopy.alledges= NULL;
1885                         emcopy.allfaces= NULL;
1886                         emcopy.derivedFinal= emcopy.derivedCage= NULL;
1887                         memset(&emcopy.vdata, 0, sizeof(emcopy.vdata));
1888                         memset(&emcopy.fdata, 0, sizeof(emcopy.fdata));
1889                         free_editMesh(&emcopy);
1890                         
1891                         em->verts= edve;
1892                         em->edges= eded;
1893                         em->faces= edvl;
1894                         
1895                         /* hashedges are freed now, make new! */
1896                         editMesh_set_hash();
1897                         
1898                         G.obedit= oldob;
1899                         BASACT= oldbase;
1900                         BASACT->flag |= SELECT; 
1901                                         
1902                 }               
1903         }
1904         
1905         /* unselect the vertices that we (ab)used for the separation*/
1906         EM_clear_flag_all(SELECT);
1907                 
1908         waitcursor(0);
1909         countall();
1910         allqueue(REDRAWVIEW3D, 0);
1911         DAG_object_flush_update(G.scene, G.obedit, OB_RECALC_DATA);     
1912 }
1913
1914 /* ******************************************** */
1915
1916 /* *************** UNDO ***************************** */
1917 /* new mesh undo, based on pushing editmesh data itself */
1918 /* reuses same code as for global and curve undo... unify that (ton) */
1919
1920 /* only one 'hack', to save memory it doesn't store the first push, but does a remake editmesh */
1921
1922 /* a compressed version of editmesh data */
1923
1924 typedef struct EditVertC
1925 {
1926         float no[3];
1927         float co[3];
1928         unsigned char f, h;
1929         int keyindex;
1930 } EditVertC;
1931
1932 typedef struct EditEdgeC
1933 {
1934         int v1, v2;
1935         unsigned char f, h, seam, sharp, pad;
1936         short crease, fgoni;
1937 } EditEdgeC;
1938
1939 typedef struct EditFaceC
1940 {
1941         int v1, v2, v3, v4;
1942         unsigned char mat_nr, flag, f, h, fgonf;
1943         short pad1;
1944 } EditFaceC;
1945
1946 typedef struct EditSelectionC{
1947         short type;
1948         int index;
1949 }EditSelectionC;
1950
1951 typedef struct EM_MultiresUndo {
1952         int users;
1953         Multires *mr;
1954 } EM_MultiresUndo;
1955
1956 typedef struct UndoMesh {
1957         EditVertC *verts;
1958         EditEdgeC *edges;
1959         EditFaceC *faces;
1960         EditSelectionC *selected;
1961         int totvert, totedge, totface, totsel;
1962         short selectmode;
1963         RetopoPaintData *retopo_paint_data;
1964         char retopo_mode;
1965         CustomData vdata, edata, fdata;
1966         EM_MultiresUndo *mru;
1967 } UndoMesh;
1968
1969 /* for callbacks */
1970
1971 static void free_undoMesh(void *umv)
1972 {
1973         UndoMesh *um= umv;
1974         
1975         if(um->verts) MEM_freeN(um->verts);
1976         if(um->edges) MEM_freeN(um->edges);
1977         if(um->faces) MEM_freeN(um->faces);
1978         if(um->selected) MEM_freeN(um->selected);
1979         if(um->retopo_paint_data) retopo_free_paint_data(um->retopo_paint_data);
1980         CustomData_free(&um->vdata, um->totvert);
1981         CustomData_free(&um->edata, um->totedge);
1982         CustomData_free(&um->fdata, um->totface);
1983         if(um->mru) {
1984                 --um->mru->users;
1985                 if(um->mru->users==0) {
1986                         multires_free(um->mru->mr);
1987                         um->mru->mr= NULL;
1988                         MEM_freeN(um->mru);
1989                 }
1990         }
1991         MEM_freeN(um);
1992 }
1993
1994 static void *editMesh_to_undoMesh(void)
1995 {
1996         EditMesh *em= G.editMesh;
1997         UndoMesh *um;
1998         EditVert *eve;
1999         EditEdge *eed;
2000         EditFace *efa;
2001         EditSelection *ese;
2002         EditVertC *evec=NULL;
2003         EditEdgeC *eedc=NULL;
2004         EditFaceC *efac=NULL;
2005         EditSelectionC *esec=NULL;
2006         int a;
2007         
2008         um= MEM_callocN(sizeof(UndoMesh), "undomesh");
2009         
2010         um->selectmode = G.scene->selectmode;
2011         
2012         for(eve=em->verts.first; eve; eve= eve->next) um->totvert++;
2013         for(eed=em->edges.first; eed; eed= eed->next) um->totedge++;
2014         for(efa=em->faces.first; efa; efa= efa->next) um->totface++;
2015         for(ese=em->selected.first; ese; ese=ese->next) um->totsel++; 
2016         /* malloc blocks */
2017         
2018         if(um->totvert) evec= um->verts= MEM_callocN(um->totvert*sizeof(EditVertC), "allvertsC");
2019         if(um->totedge) eedc= um->edges= MEM_callocN(um->totedge*sizeof(EditEdgeC), "alledgesC");
2020         if(um->totface) efac= um->faces= MEM_callocN(um->totface*sizeof(EditFaceC), "allfacesC");
2021         if(um->totsel) esec= um->selected= MEM_callocN(um->totsel*sizeof(EditSelectionC), "allselections");
2022
2023         if(um->totvert) CustomData_copy(&em->vdata, &um->vdata, CD_MASK_EDITMESH, CD_CALLOC, um->totvert);
2024         if(um->totedge) CustomData_copy(&em->edata, &um->edata, CD_MASK_EDITMESH, CD_CALLOC, um->totedge);
2025         if(um->totface) CustomData_copy(&em->fdata, &um->fdata, CD_MASK_EDITMESH, CD_CALLOC, um->totface);
2026         
2027         /* now copy vertices */
2028         a = 0;
2029         for(eve=em->verts.first; eve; eve= eve->next, evec++, a++) {
2030                 VECCOPY(evec->co, eve->co);
2031                 VECCOPY(evec->no, eve->no);
2032
2033                 evec->f= eve->f;
2034                 evec->h= eve->h;
2035                 evec->keyindex= eve->keyindex;
2036                 eve->tmp.l = a; /*store index*/
2037
2038                 CustomData_from_em_block(&em->vdata, &um->vdata, eve->data, a);
2039         }
2040         
2041         /* copy edges */
2042         a = 0;
2043         for(eed=em->edges.first; eed; eed= eed->next, eedc++, a++)  {
2044                 eedc->v1= (int)eed->v1->tmp.l;
2045                 eedc->v2= (int)eed->v2->tmp.l;
2046                 eedc->f= eed->f;
2047                 eedc->h= eed->h;
2048                 eedc->seam= eed->seam;
2049                 eedc->sharp= eed->sharp;
2050                 eedc->crease= (short)(eed->crease*255.0);
2051                 eedc->fgoni= eed->fgoni;
2052                 eed->tmp.l = a; /*store index*/
2053                 CustomData_from_em_block(&em->edata, &um->edata, eed->data, a);
2054         
2055         }
2056         
2057         /* copy faces */
2058         a = 0;
2059         for(efa=em->faces.first; efa; efa= efa->next, efac++, a++) {
2060                 efac->v1= (int)efa->v1->tmp.l;
2061                 efac->v2= (int)efa->v2->tmp.l;
2062                 efac->v3= (int)efa->v3->tmp.l;
2063                 if(efa->v4) efac->v4= (int)efa->v4->tmp.l;
2064                 else efac->v4= -1;
2065                 
2066                 efac->mat_nr= efa->mat_nr;
2067                 efac->flag= efa->flag;
2068                 efac->f= efa->f;
2069                 efac->h= efa->h;
2070                 efac->fgonf= efa->fgonf;
2071
2072                 efa->tmp.l = a; /*store index*/
2073
2074                 CustomData_from_em_block(&em->fdata, &um->fdata, efa->data, a);
2075         }
2076         
2077         a = 0;
2078         for(ese=em->selected.first; ese; ese=ese->next, esec++){
2079                 esec->type = ese->type;
2080                 if(ese->type == EDITVERT) a = esec->index = ((EditVert*)ese->data)->tmp.l; 
2081                 else if(ese->type == EDITEDGE) a = esec->index = ((EditEdge*)ese->data)->tmp.l; 
2082                 else if(ese->type == EDITFACE) a = esec->index = ((EditFace*)ese->data)->tmp.l;
2083         }
2084
2085         um->retopo_paint_data= retopo_paint_data_copy(em->retopo_paint_data);
2086         um->retopo_mode= G.scene->toolsettings->retopo_mode;
2087         
2088         {
2089                 Multires *mr= get_mesh(G.obedit)->mr;
2090                 UndoMesh *prev= undo_editmode_get_prev(G.obedit);
2091                 
2092                 um->mru= NULL;
2093                 
2094                 if(mr) {
2095                         if(prev && prev->mru && prev->mru->mr && prev->mru->mr->current == mr->current) {
2096                                 um->mru= prev->mru;
2097                                 ++um->mru->users;
2098                         }
2099                         else {
2100                                 um->mru= MEM_callocN(sizeof(EM_MultiresUndo), "EM_MultiresUndo");
2101                                 um->mru->users= 1;
2102                                 um->mru->mr= multires_copy(mr);
2103                         }
2104                 }
2105         }
2106         
2107         return um;
2108 }
2109
2110 static void undoMesh_to_editMesh(void *umv)
2111 {
2112         UndoMesh *um= (UndoMesh*)umv;
2113         EditMesh *em= G.editMesh;
2114         EditVert *eve, **evar=NULL;
2115         EditEdge *eed;
2116         EditFace *efa;
2117         EditSelection *ese;
2118         EditVertC *evec;
2119         EditEdgeC *eedc;
2120         EditFaceC *efac;
2121         EditSelectionC *esec;
2122         int a=0;
2123
2124 #ifdef WITH_VERSE
2125         struct VNode *vnode = G.editMesh->vnode;
2126         if(vnode) {
2127                 /* send delete command to all verse vertexes and verse face ...
2128                  * verse mesh will be recreated from new edit mesh */
2129                 destroy_versemesh(vnode);
2130         }
2131 #endif  
2132         G.scene->selectmode = um->selectmode;
2133         
2134         free_editMesh(G.editMesh);
2135         
2136         /* malloc blocks */
2137         memset(em, 0, sizeof(EditMesh));
2138                 
2139         init_editmesh_fastmalloc(em, um->totvert, um->totedge, um->totface);
2140
2141 #ifdef WITH_VERSE
2142         G.editMesh->vnode = vnode;
2143 #endif
2144
2145         CustomData_free(&em->vdata, 0);
2146         CustomData_free(&em->edata, 0);
2147         CustomData_free(&em->fdata, 0);
2148
2149         CustomData_copy(&um->vdata, &em->vdata, CD_MASK_EDITMESH, CD_CALLOC, 0);
2150         CustomData_copy(&um->edata, &em->edata, CD_MASK_EDITMESH, CD_CALLOC, 0);
2151         CustomData_copy(&um->fdata, &em->fdata, CD_MASK_EDITMESH, CD_CALLOC, 0);
2152
2153         /* now copy vertices */
2154
2155         if(um->totvert) evar= MEM_mallocN(um->totvert*sizeof(EditVert *), "vertex ar");
2156         for(a=0, evec= um->verts; a<um->totvert; a++, evec++) {
2157                 eve= addvertlist(evec->co, NULL);
2158                 evar[a]= eve;
2159
2160                 VECCOPY(eve->no, evec->no);
2161                 eve->f= evec->f;
2162                 eve->h= evec->h;
2163                 eve->keyindex= evec->keyindex;
2164
2165                 CustomData_to_em_block(&um->vdata, &em->vdata, a, &eve->data);
2166         }
2167
2168         /* copy edges */
2169         for(a=0, eedc= um->edges; a<um->totedge; a++, eedc++) {
2170                 eed= addedgelist(evar[eedc->v1], evar[eedc->v2], NULL);
2171
2172                 eed->f= eedc->f;
2173                 eed->h= eedc->h;
2174                 eed->seam= eedc->seam;
2175                 eed->sharp= eedc->sharp;
2176                 eed->fgoni= eedc->fgoni;
2177                 eed->crease= ((float)eedc->crease)/255.0;
2178                 CustomData_to_em_block(&um->edata, &em->edata, a, &eed->data);
2179         }
2180         
2181         /* copy faces */
2182         for(a=0, efac= um->faces; a<um->totface; a++, efac++) {
2183                 if(efac->v4 != -1)
2184                         efa= addfacelist(evar[efac->v1], evar[efac->v2], evar[efac->v3], evar[efac->v4], NULL, NULL);
2185                 else 
2186                         efa= addfacelist(evar[efac->v1], evar[efac->v2], evar[efac->v3], NULL, NULL ,NULL);
2187
2188                 efa->mat_nr= efac->mat_nr;
2189                 efa->flag= efac->flag;
2190                 efa->f= efac->f;
2191                 efa->h= efac->h;
2192                 efa->fgonf= efac->fgonf;
2193                 
2194                 CustomData_to_em_block(&um->fdata, &em->fdata, a, &efa->data);
2195         }
2196         
2197         end_editmesh_fastmalloc();
2198         if(evar) MEM_freeN(evar);
2199         
2200         G.totvert = um->totvert;
2201         G.totedge = um->totedge;
2202         G.totface = um->totface;
2203         /*restore stored editselections*/
2204         if(um->totsel){
2205                 EM_init_index_arrays(1,1,1);
2206                 for(a=0, esec= um->selected; a<um->totsel; a++, esec++){
2207                         ese = MEM_callocN(sizeof(EditSelection), "Edit Selection");
2208                         ese->type = esec->type;
2209                         if(ese->type == EDITVERT) ese->data = EM_get_vert_for_index(esec->index); else
2210                         if(ese->type == EDITEDGE) ese->data = EM_get_edge_for_index(esec->index); else
2211                         if(ese->type == EDITFACE) ese->data = EM_get_face_for_index(esec->index);
2212                         BLI_addtail(&(em->selected),ese);
2213                 }
2214                 EM_free_index_arrays();
2215         }
2216
2217         retopo_free_paint();
2218         em->retopo_paint_data= retopo_paint_data_copy(um->retopo_paint_data);
2219         G.scene->toolsettings->retopo_mode= um->retopo_mode;
2220         if(G.scene->toolsettings->retopo_mode) {
2221                 if(G.vd->depths) G.vd->depths->damaged= 1;
2222                 retopo_queue_updates(G.vd);
2223                 retopo_paint_view_update(G.vd);
2224         }
2225         
2226         {
2227                 Mesh *me= get_mesh(G.obedit);
2228                 multires_free(me->mr);
2229                 me->mr= NULL;
2230                 if(um->mru && um->mru->mr) me->mr= multires_copy(um->mru->mr);
2231         }
2232 }
2233
2234
2235 /* and this is all the undo system needs to know */
2236 void undo_push_mesh(char *name)
2237 {
2238         undo_editmode_push(name, free_undoMesh, undoMesh_to_editMesh, editMesh_to_undoMesh, NULL);
2239 }
2240
2241
2242
2243 /* *************** END UNDO *************/
2244
2245 static EditVert **g_em_vert_array = NULL;
2246 static EditEdge **g_em_edge_array = NULL;
2247 static EditFace **g_em_face_array = NULL;
2248
2249 void EM_init_index_arrays(int forVert, int forEdge, int forFace)
2250 {
2251         EditVert *eve;
2252         EditEdge *eed;
2253         EditFace *efa;
2254         int i;
2255
2256         if (forVert) {
2257                 g_em_vert_array = MEM_mallocN(sizeof(*g_em_vert_array)*G.totvert, "em_v_arr");
2258
2259                 for (i=0,eve=G.editMesh->verts.first; eve; i++,eve=eve->next)
2260                         g_em_vert_array[i] = eve;
2261         }
2262
2263         if (forEdge) {
2264                 g_em_edge_array = MEM_mallocN(sizeof(*g_em_edge_array)*G.totedge, "em_e_arr");
2265
2266                 for (i=0,eed=G.editMesh->edges.first; eed; i++,eed=eed->next)
2267                         g_em_edge_array[i] = eed;
2268         }
2269
2270         if (forFace) {
2271                 g_em_face_array = MEM_mallocN(sizeof(*g_em_face_array)*G.totface, "em_f_arr");
2272
2273                 for (i=0,efa=G.editMesh->faces.first; efa; i++,efa=efa->next)
2274                         g_em_face_array[i] = efa;
2275         }
2276 }
2277
2278 void EM_free_index_arrays(void)
2279 {
2280         if (g_em_vert_array) MEM_freeN(g_em_vert_array);
2281         if (g_em_edge_array) MEM_freeN(g_em_edge_array);
2282         if (g_em_face_array) MEM_freeN(g_em_face_array);
2283         g_em_vert_array = NULL;
2284         g_em_edge_array = NULL;
2285         g_em_face_array = NULL;
2286 }
2287
2288 EditVert *EM_get_vert_for_index(int index)
2289 {
2290         return g_em_vert_array?g_em_vert_array[index]:NULL;
2291 }
2292
2293 EditEdge *EM_get_edge_for_index(int index)
2294 {
2295         return g_em_edge_array?g_em_edge_array[index]:NULL;
2296 }
2297
2298 EditFace *EM_get_face_for_index(int index)
2299 {
2300         return g_em_face_array?g_em_face_array[index]:NULL;
2301 }
2302
2303 /* can we edit UV's for this mesh?*/
2304 int EM_texFaceCheck(void)
2305 {
2306         /* some of these checks could be a touch overkill */
2307         if (    (G.obedit) &&
2308                         (G.obedit->type == OB_MESH) &&
2309                         (G.editMesh) &&
2310                         (G.editMesh->faces.first) &&
2311                         (CustomData_has_layer(&G.editMesh->fdata, CD_MTFACE)))
2312                 return 1;
2313         return 0;
2314 }
2315
2316 /* can we edit colors for this mesh?*/
2317 int EM_vertColorCheck(void)
2318 {
2319         /* some of these checks could be a touch overkill */
2320         if (    (G.obedit) &&
2321                         (G.obedit->type == OB_MESH) &&
2322                         (G.editMesh) &&
2323                         (G.editMesh->faces.first) &&
2324                         (CustomData_has_layer(&G.editMesh->fdata, CD_MCOL)))
2325                 return 1;
2326         return 0;
2327 }
2328