3843b782d879aefe15e5ac17d2bb03ab220b7712
[blender.git] / source / blender / editors / mesh / editmesh.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributor(s): Blender Foundation, full recode 2002-2008
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28
29 #include <stdlib.h>
30 #include <string.h>
31 #include <math.h>
32
33 #include "MEM_guardedalloc.h"
34
35 #include "DNA_scene_types.h"
36 #include "DNA_object_types.h"
37 #include "DNA_key_types.h"
38 #include "DNA_meshdata_types.h"
39 #include "DNA_modifier_types.h"
40
41 #include "BLI_blenlib.h"
42 #include "BLI_math.h"
43 #include "BLI_editVert.h"
44 #include "BLI_dynstr.h"
45 #include "BLI_rand.h"
46 #include "BLI_utildefines.h"
47
48 #include "BKE_DerivedMesh.h"
49 #include "BKE_context.h"
50 #include "BKE_depsgraph.h"
51 #include "BKE_global.h"
52 #include "BKE_key.h"
53 #include "BKE_main.h"
54 #include "BKE_material.h"
55 #include "BKE_mesh.h"
56 #include "BKE_paint.h"
57 #include "BKE_report.h"
58 #include "BKE_multires.h"
59
60 #include "ED_mesh.h"
61 #include "ED_object.h"
62 #include "ED_screen.h"
63 #include "ED_util.h"
64 #include "ED_view3d.h"
65
66 #include "RNA_access.h"
67 #include "RNA_define.h"
68
69 #include "WM_api.h"
70 #include "WM_types.h"
71
72 /* own include */
73 #include "mesh_intern.h"
74
75 /* 
76 editmesh.c:
77         - add/alloc/free data
78         - hashtables
79         - enter/exit editmode
80 */
81
82 /* XXX */
83 static void BIF_undo_push(const char *UNUSED(arg)) {}
84 static void error(const char *UNUSED(arg)) {}
85
86
87 /* ***************** HASH ********************* */
88
89
90 #define EDHASHSIZE              (512*512)
91 #define EDHASH(a, b)    (a % EDHASHSIZE)
92
93
94 /* ************ ADD / REMOVE / FIND ****************** */
95
96 static void *calloc_em(EditMesh *UNUSED(em), size_t size, size_t nr)
97 {
98         return calloc(size, nr);
99 }
100
101 /* used to bypass normal calloc with fast one */
102 static void *(*callocvert)(EditMesh *, size_t, size_t) = calloc_em;
103 static void *(*callocedge)(EditMesh *, size_t, size_t) = calloc_em;
104 static void *(*callocface)(EditMesh *, size_t, size_t) = calloc_em;
105
106 EditVert *addvertlist(EditMesh *em, float *vec, EditVert *example)
107 {
108         EditVert *eve;
109         static int hashnr= 0;
110
111         eve= callocvert(em, sizeof(EditVert), 1);
112         BLI_addtail(&em->verts, eve);
113         em->totvert++;
114         
115         if(vec) VECCOPY(eve->co, vec);
116
117         eve->hash= hashnr++;
118         if( hashnr>=EDHASHSIZE) hashnr= 0;
119
120         /* new verts get keyindex of -1 since they did not
121          * have a pre-editmode vertex order
122          */
123         eve->keyindex = -1;
124
125         if(example) {
126                 CustomData_em_copy_data(&em->vdata, &em->vdata, example->data, &eve->data);
127                 eve->bweight = example->bweight;
128         }
129         else {
130                 CustomData_em_set_default(&em->vdata, &eve->data);
131         }
132
133         return eve;
134 }
135
136 void free_editvert (EditMesh *em, EditVert *eve)
137 {
138
139         EM_remove_selection(em, eve, EDITVERT);
140         CustomData_em_free_block(&em->vdata, &eve->data);
141         if(eve->fast==0)
142                 free(eve);
143         
144         em->totvert--;
145 }
146
147
148 EditEdge *findedgelist(EditMesh *em, EditVert *v1, EditVert *v2)
149 {
150         EditVert *v3;
151         struct HashEdge *he;
152
153         /* swap ? */
154         if( v1 > v2) {
155                 v3= v2; 
156                 v2= v1; 
157                 v1= v3;
158         }
159         
160         if(em->hashedgetab==NULL)
161                 em->hashedgetab= MEM_callocN(EDHASHSIZE*sizeof(struct HashEdge), "hashedgetab");
162
163         he= em->hashedgetab + EDHASH(v1->hash, v2->hash);
164         
165         while(he) {
166                 
167                 if(he->eed && he->eed->v1==v1 && he->eed->v2==v2) return he->eed;
168                 
169                 he= he->next;
170         }
171         return 0;
172 }
173
174 static void insert_hashedge(EditMesh *em, EditEdge *eed)
175 {
176         /* assuming that eed is not in the list yet, and that a find has been done before */
177         
178         struct HashEdge *first, *he;
179
180         first= em->hashedgetab + EDHASH(eed->v1->hash, eed->v2->hash);
181
182         if( first->eed==0 ) {
183                 first->eed= eed;
184         }
185         else {
186                 he= &eed->hash; 
187                 he->eed= eed;
188                 he->next= first->next;
189                 first->next= he;
190         }
191 }
192
193 static void remove_hashedge(EditMesh *em, EditEdge *eed)
194 {
195         /* assuming eed is in the list */
196         
197         struct HashEdge *first, *he, *prev=NULL;
198
199         he=first= em->hashedgetab + EDHASH(eed->v1->hash, eed->v2->hash);
200
201         while(he) {
202                 if(he->eed == eed) {
203                         /* remove from list */
204                         if(he==first) {
205                                 if(first->next) {
206                                         he= first->next;
207                                         first->eed= he->eed;
208                                         first->next= he->next;
209                                 }
210                                 else he->eed= 0;
211                         }
212                         else {
213                                 prev->next= he->next;
214                         }
215                         return;
216                 }
217                 prev= he;
218                 he= he->next;
219         }
220 }
221
222 EditEdge *addedgelist(EditMesh *em, EditVert *v1, EditVert *v2, EditEdge *example)
223 {
224         EditVert *v3;
225         EditEdge *eed;
226         int swap= 0;
227         
228         if(v1==v2) return NULL;
229         if(v1==NULL || v2==NULL) return NULL;
230
231         /* swap ? */
232         if(v1>v2) {
233                 v3= v2; 
234                 v2= v1; 
235                 v1= v3;
236                 swap= 1;
237         }
238         
239         /* find in hashlist */
240         eed= findedgelist(em, v1, v2);
241
242         if(eed==NULL) {
243         
244                 eed= (EditEdge *)callocedge(em, sizeof(EditEdge), 1);
245                 eed->v1= v1;
246                 eed->v2= v2;
247                 BLI_addtail(&em->edges, eed);
248                 eed->dir= swap;
249                 insert_hashedge(em, eed);
250                 em->totedge++;
251                 
252                 /* copy edge data:
253                    rule is to do this with addedgelist call, before addfacelist */
254                 if(example) {
255                         eed->crease= example->crease;
256                         eed->bweight= example->bweight;
257                         eed->sharp = example->sharp;
258                         eed->seam = example->seam;
259                         eed->h |= (example->h & EM_FGON);
260                 }
261         }
262         
263         return eed;
264 }
265
266 void remedge(EditMesh *em, EditEdge *eed)
267 {
268         BLI_remlink(&em->edges, eed);
269         remove_hashedge(em, eed);
270         
271         em->totedge--;
272 }
273
274 void free_editedge(EditMesh *em, EditEdge *eed)
275 {
276         EM_remove_selection(em, eed, EDITEDGE);
277         if(eed->fast==0){ 
278                 free(eed);
279         }
280 }
281
282 void free_editface(EditMesh *em, EditFace *efa)
283 {
284         EM_remove_selection(em, efa, EDITFACE);
285         
286         if (em->act_face==efa) {
287                 EM_set_actFace(em, em->faces.first == efa ? NULL : em->faces.first);
288         }
289                 
290         CustomData_em_free_block(&em->fdata, &efa->data);
291         if(efa->fast==0)
292                 free(efa);
293         
294         em->totface--;
295 }
296
297 void free_vertlist(EditMesh *em, ListBase *edve) 
298 {
299         EditVert *eve, *next;
300
301         if (!edve) return;
302
303         eve= edve->first;
304         while(eve) {
305                 next= eve->next;
306                 free_editvert(em, eve);
307                 eve= next;
308         }
309         edve->first= edve->last= NULL;
310         em->totvert= em->totvertsel= 0;
311 }
312
313 void free_edgelist(EditMesh *em, ListBase *lb)
314 {
315         EditEdge *eed, *next;
316         
317         eed= lb->first;
318         while(eed) {
319                 next= eed->next;
320                 free_editedge(em, eed);
321                 eed= next;
322         }
323         lb->first= lb->last= NULL;
324         em->totedge= em->totedgesel= 0;
325 }
326
327 void free_facelist(EditMesh *em, ListBase *lb)
328 {
329         EditFace *efa, *next;
330         
331         efa= lb->first;
332         while(efa) {
333                 next= efa->next;
334                 free_editface(em, efa);
335                 efa= next;
336         }
337         lb->first= lb->last= NULL;
338         em->totface= em->totfacesel= 0;
339 }
340
341 EditFace *addfacelist(EditMesh *em, EditVert *v1, EditVert *v2, EditVert *v3, EditVert *v4, EditFace *example, EditFace *exampleEdges)
342 {
343         EditFace *efa;
344         EditEdge *e1, *e2=0, *e3=0, *e4=0;
345
346         /* added sanity check... seems to happen for some tools, or for enter editmode for corrupted meshes */
347         if(v1==v4 || v2==v4 || v3==v4) v4= NULL;
348         
349         /* add face to list and do the edges */
350         if(exampleEdges) {
351                 e1= addedgelist(em, v1, v2, exampleEdges->e1);
352                 e2= addedgelist(em, v2, v3, exampleEdges->e2);
353                 if(v4) e3= addedgelist(em, v3, v4, exampleEdges->e3); 
354                 else e3= addedgelist(em, v3, v1, exampleEdges->e3);
355                 if(v4) e4= addedgelist(em, v4, v1, exampleEdges->e4);
356         }
357         else {
358                 e1= addedgelist(em, v1, v2, NULL);
359                 e2= addedgelist(em, v2, v3, NULL);
360                 if(v4) e3= addedgelist(em, v3, v4, NULL); 
361                 else e3= addedgelist(em, v3, v1, NULL);
362                 if(v4) e4= addedgelist(em, v4, v1, NULL);
363         }
364         
365         if(v1==v2 || v2==v3 || v1==v3) return NULL;
366         if(e2==0) return NULL;
367
368         efa= (EditFace *)callocface(em, sizeof(EditFace), 1);
369         efa->v1= v1;
370         efa->v2= v2;
371         efa->v3= v3;
372         efa->v4= v4;
373
374         efa->e1= e1;
375         efa->e2= e2;
376         efa->e3= e3;
377         efa->e4= e4;
378
379         if(example) {
380                 efa->mat_nr= example->mat_nr;
381                 efa->flag= example->flag;
382                 CustomData_em_copy_data(&em->fdata, &em->fdata, example->data, &efa->data);
383                 CustomData_em_validate_data(&em->fdata, efa->data, efa->v4 ? 4 : 3);
384         }
385         else {
386                 efa->mat_nr= em->mat_nr;
387
388                 CustomData_em_set_default(&em->fdata, &efa->data);
389         }
390
391         BLI_addtail(&em->faces, efa);
392         em->totface++;
393         
394         if(efa->v4) {
395                 normal_quad_v3( efa->n,efa->v1->co, efa->v2->co, efa->v3->co, efa->v4->co);
396                 cent_quad_v3(efa->cent, efa->v1->co, efa->v2->co, efa->v3->co, efa->v4->co);
397         }
398         else {
399                 normal_tri_v3( efa->n,efa->v1->co, efa->v2->co, efa->v3->co);
400                 cent_tri_v3(efa->cent, efa->v1->co, efa->v2->co, efa->v3->co);
401         }
402
403         return efa;
404 }
405
406 /* ************************ end add/new/find ************  */
407
408 /* ************************ Edit{Vert,Edge,Face} utilss ***************************** */
409
410 /* some nice utility functions */
411
412 EditVert *editedge_getOtherVert(EditEdge *eed, EditVert *eve)
413 {
414         if (eve==eed->v1) {
415                 return eed->v2;
416         } else if (eve==eed->v2) {
417                 return eed->v1;
418         } else {
419                 return NULL;
420         }
421 }
422
423 EditVert *editedge_getSharedVert(EditEdge *eed, EditEdge *eed2) 
424 {
425         if (eed->v1==eed2->v1 || eed->v1==eed2->v2) {
426                 return eed->v1;
427         } else if (eed->v2==eed2->v1 || eed->v2==eed2->v2) {
428                 return eed->v2;
429         } else {
430                 return NULL;
431         }
432 }
433
434 int editedge_containsVert(EditEdge *eed, EditVert *eve) 
435 {
436         return (eed->v1==eve || eed->v2==eve);
437 }
438
439 int editface_containsVert(EditFace *efa, EditVert *eve) 
440 {
441         return (efa->v1==eve || efa->v2==eve || efa->v3==eve || (efa->v4 && efa->v4==eve));
442 }
443
444 int editface_containsEdge(EditFace *efa, EditEdge *eed) 
445 {
446         return (efa->e1==eed || efa->e2==eed || efa->e3==eed || (efa->e4 && efa->e4==eed));
447 }
448
449
450 /* ************************ stuct EditMesh manipulation ***************************** */
451
452 /* fake callocs for fastmalloc below */
453 static void *calloc_fastvert(EditMesh *em, size_t UNUSED(size), size_t UNUSED(nr))
454 {
455         EditVert *eve= em->curvert++;
456         eve->fast= 1;
457         return eve;
458 }
459 static void *calloc_fastedge(EditMesh *em, size_t UNUSED(size), size_t UNUSED(nr))
460 {
461         EditEdge *eed= em->curedge++;
462         eed->fast= 1;
463         return eed;
464 }
465 static void *calloc_fastface(EditMesh *em, size_t UNUSED(size), size_t UNUSED(nr))
466 {
467         EditFace *efa= em->curface++;
468         efa->fast= 1;
469         return efa;
470 }
471
472 /* allocate 1 chunk for all vertices, edges, faces. These get tagged to
473    prevent it from being freed
474 */
475 static void init_editmesh_fastmalloc(EditMesh *em, int totvert, int totedge, int totface)
476 {
477         if(totvert) em->allverts= MEM_callocN(totvert*sizeof(EditVert), "allverts");
478         else em->allverts= NULL;
479         em->curvert= em->allverts;
480         
481         if(totedge==0) totedge= 4*totface;      // max possible
482
483         if(totedge) em->alledges= MEM_callocN(totedge*sizeof(EditEdge), "alledges");
484         else em->alledges= NULL;
485         em->curedge= em->alledges;
486         
487         if(totface) em->allfaces= MEM_callocN(totface*sizeof(EditFace), "allfaces");
488         else em->allfaces= NULL;
489         em->curface= em->allfaces;
490
491         callocvert= calloc_fastvert;
492         callocedge= calloc_fastedge;
493         callocface= calloc_fastface;
494 }
495
496 static void end_editmesh_fastmalloc(void)
497 {
498         callocvert= calloc_em;
499         callocedge= calloc_em;
500         callocface= calloc_em;
501 }
502
503 /* do not free editmesh itself here */
504 void free_editMesh(EditMesh *em)
505 {
506         if(em==NULL) return;
507
508         if(em->verts.first) free_vertlist(em, &em->verts);
509         if(em->edges.first) free_edgelist(em, &em->edges);
510         if(em->faces.first) free_facelist(em, &em->faces);
511         if(em->selected.first) BLI_freelistN(&(em->selected));
512
513         CustomData_free(&em->vdata, 0);
514         CustomData_free(&em->fdata, 0);
515
516         if(em->derivedFinal) {
517                 if (em->derivedFinal!=em->derivedCage) {
518                         em->derivedFinal->needsFree= 1;
519                         em->derivedFinal->release(em->derivedFinal);
520                 }
521                 em->derivedFinal= NULL;
522         }
523         if(em->derivedCage) {
524                 em->derivedCage->needsFree= 1;
525                 em->derivedCage->release(em->derivedCage);
526                 em->derivedCage= NULL;
527         }
528
529         /* DEBUG: hashtabs are slowest part of enter/exit editmode. here a testprint */
530 #if 0
531         if(em->hashedgetab) {
532                 HashEdge *he, *hen;
533                 int a, used=0, max=0, nr;
534                 he= em->hashedgetab;
535                 for(a=0; a<EDHASHSIZE; a++, he++) {
536                         if(he->eed) used++;
537                         hen= he->next;
538                         nr= 0;
539                         while(hen) {
540                                 nr++;
541                                 hen= hen->next;
542                         }
543                         if(max<nr) max= nr;
544                 }
545                 printf("hastab used %d max %d\n", used, max);
546         }
547 #endif
548         if(em->hashedgetab) MEM_freeN(em->hashedgetab);
549         em->hashedgetab= NULL;
550         
551         if(em->allverts) MEM_freeN(em->allverts);
552         if(em->alledges) MEM_freeN(em->alledges);
553         if(em->allfaces) MEM_freeN(em->allfaces);
554         
555         em->allverts= em->curvert= NULL;
556         em->alledges= em->curedge= NULL;
557         em->allfaces= em->curface= NULL;
558         
559         mesh_octree_table(NULL, NULL, NULL, 'e');
560         mesh_mirrtopo_table(NULL, 'e');
561
562         em->totvert= em->totedge= em->totface= 0;
563
564 // XXX  if(em->retopo_paint_data) retopo_free_paint_data(em->retopo_paint_data);
565         em->retopo_paint_data= NULL;
566         em->act_face = NULL;
567 }
568
569 static void editMesh_set_hash(EditMesh *em)
570 {
571         EditEdge *eed;
572
573         if(em->hashedgetab) MEM_freeN(em->hashedgetab);
574         em->hashedgetab= NULL;
575         
576         for(eed=em->edges.first; eed; eed= eed->next)  {
577                 if( findedgelist(em, eed->v1, eed->v2)==NULL )
578                         insert_hashedge(em, eed);
579         }
580
581 }
582
583
584 /* ************************ IN & OUT EDITMODE ***************************** */
585
586
587 static void edge_normal_compare(EditEdge *eed, EditFace *efa1)
588 {
589         EditFace *efa2;
590         float cent1[3], cent2[3];
591         float inp;
592         
593         efa2 = eed->tmp.f;
594         if(efa1==efa2) return;
595         
596         inp= efa1->n[0]*efa2->n[0] + efa1->n[1]*efa2->n[1] + efa1->n[2]*efa2->n[2];
597         if(inp<0.999 && inp >-0.999) eed->f2= 1;
598                 
599         if(efa1->v4) cent_quad_v3(cent1, efa1->v1->co, efa1->v2->co, efa1->v3->co, efa1->v4->co);
600         else cent_tri_v3(cent1, efa1->v1->co, efa1->v2->co, efa1->v3->co);
601         if(efa2->v4) cent_quad_v3(cent2, efa2->v1->co, efa2->v2->co, efa2->v3->co, efa2->v4->co);
602         else cent_tri_v3(cent2, efa2->v1->co, efa2->v2->co, efa2->v3->co);
603         
604         sub_v3_v3v3(cent1, cent2, cent1);
605         normalize_v3(cent1);
606         inp= cent1[0]*efa1->n[0] + cent1[1]*efa1->n[1] + cent1[2]*efa1->n[2]; 
607
608         if(inp < -0.001 ) eed->f1= 1;
609 }
610
611 #if 0
612 typedef struct {
613         EditEdge *eed;
614         float noLen,no[3];
615         int adjCount;
616 } EdgeDrawFlagInfo;
617
618 static int edgeDrawFlagInfo_cmp(const void *av, const void *bv)
619 {
620         const EdgeDrawFlagInfo *a = av;
621         const EdgeDrawFlagInfo *b = bv;
622
623         if (a->noLen<b->noLen) return -1;
624         else if (a->noLen>b->noLen) return 1;
625         else return 0;
626 }
627 #endif
628
629 static void edge_drawflags(Mesh *me, EditMesh *em)
630 {
631         EditVert *eve;
632         EditEdge *eed, *e1, *e2, *e3, *e4;
633         EditFace *efa;
634         
635         /* - count number of times edges are used in faces: 0 en 1 time means draw edge
636          * - edges more than 1 time used: in *tmp.f is pointer to first face
637          * - check all faces, when normal differs to much: draw (flag becomes 1)
638          */
639
640         /* later on: added flags for 'cylinder' and 'sphere' intersection tests in old
641            game engine (2.04)
642          */
643         
644         recalc_editnormals(em);
645         
646         /* init */
647         eve= em->verts.first;
648         while(eve) {
649                 eve->f1= 1;             /* during test it's set at zero */
650                 eve= eve->next;
651         }
652         eed= em->edges.first;
653         while(eed) {
654                 eed->f2= eed->f1= 0;
655                 eed->tmp.f = 0;
656                 eed= eed->next;
657         }
658
659         efa= em->faces.first;
660         while(efa) {
661                 e1= efa->e1;
662                 e2= efa->e2;
663                 e3= efa->e3;
664                 e4= efa->e4;
665                 if(e1->f2<4) e1->f2+= 1;
666                 if(e2->f2<4) e2->f2+= 1;
667                 if(e3->f2<4) e3->f2+= 1;
668                 if(e4 && e4->f2<4) e4->f2+= 1;
669                 
670                 if(e1->tmp.f == 0) e1->tmp.f = (void *) efa;
671                 if(e2->tmp.f == 0) e2->tmp.f = (void *) efa;
672                 if(e3->tmp.f ==0) e3->tmp.f = (void *) efa;
673                 if(e4 && (e4->tmp.f == 0)) e4->tmp.f = (void *) efa;
674                 
675                 efa= efa->next;
676         }
677
678         if(me->drawflag & ME_ALLEDGES) {
679                 efa= em->faces.first;
680                 while(efa) {
681                         if(efa->e1->f2>=2) efa->e1->f2= 1;
682                         if(efa->e2->f2>=2) efa->e2->f2= 1;
683                         if(efa->e3->f2>=2) efa->e3->f2= 1;
684                         if(efa->e4 && efa->e4->f2>=2) efa->e4->f2= 1;
685                         
686                         efa= efa->next;
687                 }               
688         }       
689         else {
690                 
691                 /* handle single-edges for 'test cylinder flag' (old engine) */
692                 
693                 eed= em->edges.first;
694                 while(eed) {
695                         if(eed->f2==1) eed->f1= 1;
696                         eed= eed->next;
697                 }
698
699                 /* all faces, all edges with flag==2: compare normal */
700                 efa= em->faces.first;
701                 while(efa) {
702                         if(efa->e1->f2==2) edge_normal_compare(efa->e1, efa);
703                         else efa->e1->f2= 1;
704                         if(efa->e2->f2==2) edge_normal_compare(efa->e2, efa);
705                         else efa->e2->f2= 1;
706                         if(efa->e3->f2==2) edge_normal_compare(efa->e3, efa);
707                         else efa->e3->f2= 1;
708                         if(efa->e4) {
709                                 if(efa->e4->f2==2) edge_normal_compare(efa->e4, efa);
710                                 else efa->e4->f2= 1;
711                         }
712                         efa= efa->next;
713                 }
714                 
715                 /* sphere collision flag */
716                 
717                 eed= em->edges.first;
718                 while(eed) {
719                         if(eed->f1!=1) {
720                                 eed->v1->f1= eed->v2->f1= 0;
721                         }
722                         eed= eed->next;
723                 }
724                 
725         }
726 }
727
728 /* turns Mesh into editmesh */
729 void make_editMesh(Scene *scene, Object *ob)
730 {
731         Mesh *me= ob->data;
732         MFace *mface;
733         MVert *mvert;
734         MSelect *mselect;
735         KeyBlock *actkey;
736         EditMesh *em;
737         EditVert *eve, **evlist, *eve1, *eve2, *eve3, *eve4;
738         EditFace *efa, *efa_last_sel= NULL;
739         EditEdge *eed;
740         EditSelection *ese;
741         float *co, (*keyco)[3]= NULL;
742         int tot, a, eekadoodle= 0;
743         const short is_paint_sel= paint_facesel_test(ob);
744
745         if(me->edit_mesh==NULL)
746                 me->edit_mesh= MEM_callocN(sizeof(EditMesh), "editmesh");
747         else 
748                 /* because of reload */
749                 free_editMesh(me->edit_mesh);
750         
751         em= me->edit_mesh;
752         
753         em->selectmode= scene->toolsettings->selectmode; // warning needs to be synced
754         em->act_face = NULL;
755         em->totvert= tot= me->totvert;
756         em->totedge= me->totedge;
757         em->totface= me->totface;
758         
759         if(tot==0) {
760                 return;
761         }
762         
763         if(ob->actcol > 0)
764                 em->mat_nr= ob->actcol-1;
765
766         /* initialize fastmalloc for editmesh */
767         init_editmesh_fastmalloc(em, me->totvert, me->totedge, me->totface);
768
769         actkey = ob_get_keyblock(ob);
770         if(actkey) {
771                 /* undo-ing in past for previous editmode sessions gives corrupt 'keyindex' values */
772                 undo_editmode_clear();
773                 keyco= actkey->data;
774                 em->shapenr= ob->shapenr;
775         }
776
777         /* make editverts */
778         CustomData_copy(&me->vdata, &em->vdata, CD_MASK_EDITMESH, CD_CALLOC, 0);
779         mvert= me->mvert;
780
781         evlist= (EditVert **)MEM_mallocN(tot*sizeof(void *),"evlist");
782         for(a=0; a<tot; a++, mvert++) {
783                 
784                 co= mvert->co;
785
786                 /* edit the shape key coordinate if available */
787                 if(keyco && a < actkey->totelem)
788                         co= keyco[a];
789
790                 eve= addvertlist(em, co, NULL);
791                 evlist[a]= eve;
792                 
793                 /* face select sets selection in next loop */
794                 if(!is_paint_sel)
795                         eve->f |= (mvert->flag & 1);
796                 
797                 if (mvert->flag & ME_HIDE) eve->h= 1;           
798                 eve->no[0]= mvert->no[0]/32767.0;
799                 eve->no[1]= mvert->no[1]/32767.0;
800                 eve->no[2]= mvert->no[2]/32767.0;
801
802                 eve->bweight= ((float)mvert->bweight)/255.0f;
803
804                 /* lets overwrite the keyindex of the editvert
805                  * with the order it used to be in before
806                  * editmode
807                  */
808                 eve->keyindex = a;
809
810                 CustomData_to_em_block(&me->vdata, &em->vdata, a, &eve->data);
811         }
812
813         if(actkey && actkey->totelem!=me->totvert);
814         else {
815                 MEdge *medge= me->medge;
816                 
817                 CustomData_copy(&me->edata, &em->edata, CD_MASK_EDITMESH, CD_CALLOC, 0);
818                 /* make edges */
819                 for(a=0; a<me->totedge; a++, medge++) {
820                         eed= addedgelist(em, evlist[medge->v1], evlist[medge->v2], NULL);
821                         /* eed can be zero when v1 and v2 are identical, dxf import does this... */
822                         if(eed) {
823                                 eed->crease= ((float)medge->crease)/255.0f;
824                                 eed->bweight= ((float)medge->bweight)/255.0f;
825                                 
826                                 if(medge->flag & ME_SEAM) eed->seam= 1;
827                                 if(medge->flag & ME_SHARP) eed->sharp = 1;
828                                 if(medge->flag & SELECT) eed->f |= SELECT;
829                                 if(medge->flag & ME_FGON) eed->h= EM_FGON;      // 2 different defines!
830                                 if(medge->flag & ME_HIDE) eed->h |= 1;
831                                 if(em->selectmode==SCE_SELECT_EDGE) 
832                                         EM_select_edge(eed, eed->f & SELECT);           // force edge selection to vertices, seems to be needed ...
833                                 CustomData_to_em_block(&me->edata,&em->edata, a, &eed->data);
834                         }
835                 }
836                 
837                 CustomData_copy(&me->fdata, &em->fdata, CD_MASK_EDITMESH, CD_CALLOC, 0);
838
839                 /* make faces */
840                 mface= me->mface;
841
842                 for(a=0; a<me->totface; a++, mface++) {
843                         eve1= evlist[mface->v1];
844                         eve2= evlist[mface->v2];
845                         if(!mface->v3) eekadoodle= 1;
846                         eve3= evlist[mface->v3];
847                         if(mface->v4) eve4= evlist[mface->v4]; else eve4= NULL;
848                         
849                         efa= addfacelist(em, eve1, eve2, eve3, eve4, NULL, NULL);
850
851                         if(efa) {
852                                 CustomData_to_em_block(&me->fdata, &em->fdata, a, &efa->data);
853
854                                 efa->mat_nr= mface->mat_nr;
855                                 efa->flag= mface->flag & ~ME_HIDE;
856                                 
857                                 /* select and hide face flag */
858                                 if(mface->flag & ME_HIDE) {
859                                         efa->h= 1;
860                                 } else {
861                                         if (a==me->act_face) {
862                                                 EM_set_actFace(em, efa);
863                                         }
864                                         
865                                         /* dont allow hidden and selected */
866                                         if(mface->flag & ME_FACE_SEL) {
867                                                 efa->f |= SELECT;
868                                                 
869                                                 if(is_paint_sel) {
870                                                         EM_select_face(efa, 1); /* flush down */
871                                                 }
872
873                                                 efa_last_sel= efa;
874                                         }
875                                 }
876                         }
877                 }
878         }
879         
880         if(EM_get_actFace(em, 0)==NULL && efa_last_sel) {
881                 EM_set_actFace(em, efa_last_sel);
882         }
883
884         if(eekadoodle)
885                 error("This Mesh has old style edgecodes, please put it in the bugtracker!");
886         
887         MEM_freeN(evlist);
888
889         end_editmesh_fastmalloc();      // resets global function pointers
890         
891         if(me->mselect){
892                 //restore editselections
893                 EM_init_index_arrays(em, 1,1,1);
894                 mselect = me->mselect;
895                 
896                 for(a=0; a<me->totselect; a++, mselect++){
897                         /*check if recorded selection is still valid, if so copy into editmesh*/
898                         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) ){
899                                 ese = MEM_callocN(sizeof(EditSelection), "Edit Selection");
900                                 ese->type = mselect->type;      
901                                 if(ese->type == EDITVERT) ese->data = EM_get_vert_for_index(mselect->index); else
902                                 if(ese->type == EDITEDGE) ese->data = EM_get_edge_for_index(mselect->index); else
903                                 if(ese->type == EDITFACE) ese->data = EM_get_face_for_index(mselect->index);
904                                 BLI_addtail(&(em->selected),ese);
905                         }
906                 }
907                 EM_free_index_arrays();
908         }
909         /* this creates coherent selections. also needed for older files */
910         EM_selectmode_set(em);
911         /* paranoia check to enforce hide rules */
912         EM_hide_reset(em);
913         /* sets helper flags which arent saved */
914         EM_fgon_flags(em);
915         
916         if (EM_get_actFace(em, 0)==NULL) {
917                 EM_set_actFace(em, em->faces.first ); /* will use the first face, this is so we alwats have an active face */
918         }
919 }
920
921 /* makes Mesh out of editmesh */
922 void load_editMesh(Scene *scene, Object *obedit)
923 {
924         Mesh *me= obedit->data;
925         MVert *mvert, *oldverts;
926         MEdge *medge;
927         MFace *mface;
928         MSelect *mselect;
929         EditMesh *em= me->edit_mesh;
930         EditVert *eve;
931         EditFace *efa, *efa_act;
932         EditEdge *eed;
933         EditSelection *ese;
934         float *fp, *newkey, *oldkey, nor[3];
935         int i, a, ototvert;
936         
937         /* this one also tests of edges are not in faces: */
938         /* eed->f2==0: not in face, f2==1: draw it */
939         /* eed->f1 : flag for dynaface (cylindertest, old engine) */
940         /* eve->f1 : flag for dynaface (sphere test, old engine) */
941         /* eve->f2 : being used in vertexnormals */
942         edge_drawflags(me, em);
943         
944         EM_stats_update(em);
945         
946         /* new Vertex block */
947         if(em->totvert==0) mvert= NULL;
948         else mvert= MEM_callocN(em->totvert*sizeof(MVert), "loadeditMesh vert");
949
950         /* new Edge block */
951         if(em->totedge==0) medge= NULL;
952         else medge= MEM_callocN(em->totedge*sizeof(MEdge), "loadeditMesh edge");
953         
954         /* new Face block */
955         if(em->totface==0) mface= NULL;
956         else mface= MEM_callocN(em->totface*sizeof(MFace), "loadeditMesh face");
957
958         /* lets save the old verts just in case we are actually working on
959          * a key ... we now do processing of the keys at the end */
960         oldverts= me->mvert;
961         ototvert= me->totvert;
962
963         /* don't free this yet */
964         CustomData_set_layer(&me->vdata, CD_MVERT, NULL);
965
966         /* free custom data */
967         CustomData_free(&me->vdata, me->totvert);
968         CustomData_free(&me->edata, me->totedge);
969         CustomData_free(&me->fdata, me->totface);
970
971         /* add new custom data */
972         me->totvert= em->totvert;
973         me->totedge= em->totedge;
974         me->totface= em->totface;
975
976         CustomData_copy(&em->vdata, &me->vdata, CD_MASK_MESH, CD_CALLOC, me->totvert);
977         CustomData_copy(&em->edata, &me->edata, CD_MASK_MESH, CD_CALLOC, me->totedge);
978         CustomData_copy(&em->fdata, &me->fdata, CD_MASK_MESH, CD_CALLOC, me->totface);
979
980         CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, mvert, me->totvert);
981         CustomData_add_layer(&me->edata, CD_MEDGE, CD_ASSIGN, medge, me->totedge);
982         CustomData_add_layer(&me->fdata, CD_MFACE, CD_ASSIGN, mface, me->totface);
983         mesh_update_customdata_pointers(me);
984
985         /* the vertices, use ->tmp.l as counter */
986         eve= em->verts.first;
987         a= 0;
988
989         while(eve) {
990                 VECCOPY(mvert->co, eve->co);
991
992                 /* vertex normal */
993                 VECCOPY(nor, eve->no);
994                 mul_v3_fl(nor, 32767.0);
995                 VECCOPY(mvert->no, nor);
996
997                 /* note: it used to remove me->dvert when it was not in use, cancelled
998                    that... annoying when you have a fresh vgroup */
999                 CustomData_from_em_block(&em->vdata, &me->vdata, eve->data, a);
1000
1001                 eve->tmp.l = a++;  /* counter */
1002                         
1003                 mvert->flag= 0;
1004                 mvert->flag |= (eve->f & SELECT);
1005                 if (eve->h) mvert->flag |= ME_HIDE;
1006                 
1007                 mvert->bweight= (char)(255.0*eve->bweight);
1008
1009                 eve= eve->next;
1010                 mvert++;
1011         }
1012
1013         /* the edges */
1014         a= 0;
1015         eed= em->edges.first;
1016         while(eed) {
1017                 medge->v1= (unsigned int) eed->v1->tmp.l;
1018                 medge->v2= (unsigned int) eed->v2->tmp.l;
1019                 
1020                 medge->flag= (eed->f & SELECT) | ME_EDGERENDER;
1021                 if(eed->f2<2) medge->flag |= ME_EDGEDRAW;
1022                 if(eed->f2==0) medge->flag |= ME_LOOSEEDGE;
1023                 if(eed->sharp) medge->flag |= ME_SHARP;
1024                 if(eed->seam) medge->flag |= ME_SEAM;
1025                 if(eed->h & EM_FGON) medge->flag |= ME_FGON;    // different defines yes
1026                 if(eed->h & 1) medge->flag |= ME_HIDE;
1027                 
1028                 medge->crease= (char)(255.0*eed->crease);
1029                 medge->bweight= (char)(255.0*eed->bweight);
1030                 CustomData_from_em_block(&em->edata, &me->edata, eed->data, a);         
1031
1032                 eed->tmp.l = a++;
1033                 
1034                 medge++;
1035                 eed= eed->next;
1036         }
1037
1038         /* the faces */
1039         a = 0;
1040         efa= em->faces.first;
1041         efa_act= EM_get_actFace(em, 0);
1042         i = 0;
1043         me->act_face = -1;
1044         while(efa) {
1045                 mface= &((MFace *) me->mface)[i];
1046                 
1047                 mface->v1= (unsigned int) efa->v1->tmp.l;
1048                 mface->v2= (unsigned int) efa->v2->tmp.l;
1049                 mface->v3= (unsigned int) efa->v3->tmp.l;
1050                 if (efa->v4) mface->v4 = (unsigned int) efa->v4->tmp.l;
1051
1052                 mface->mat_nr= efa->mat_nr;
1053                 
1054                 mface->flag= efa->flag;
1055                 /* bit 0 of flag is already taken for smooth... */
1056                 
1057                 if(efa->h) {
1058                         mface->flag |= ME_HIDE;
1059                         mface->flag &= ~ME_FACE_SEL;
1060                 } else {
1061                         if(efa->f & 1) mface->flag |= ME_FACE_SEL;
1062                         else mface->flag &= ~ME_FACE_SEL;
1063                 }
1064                         
1065                 /* watch: efa->e1->f2==0 means loose edge */ 
1066                         
1067                 if(efa->e1->f2==1) {
1068                         efa->e1->f2= 2;
1069                 }                       
1070                 if(efa->e2->f2==1) {
1071                         efa->e2->f2= 2;
1072                 }
1073                 if(efa->e3->f2==1) {
1074                         efa->e3->f2= 2;
1075                 }
1076                 if(efa->e4 && efa->e4->f2==1) {
1077                         efa->e4->f2= 2;
1078                 }
1079
1080                 CustomData_from_em_block(&em->fdata, &me->fdata, efa->data, i);
1081
1082                 /* no index '0' at location 3 or 4 */
1083                 test_index_face(mface, &me->fdata, i, efa->v4?4:3);
1084                 
1085                 if (efa_act == efa)
1086                         me->act_face = a;
1087
1088                 efa->tmp.l = a++;
1089                 i++;
1090                 efa= efa->next;
1091         }
1092
1093         /* patch hook indices and vertex parents */
1094         {
1095                 Object *ob;
1096                 ModifierData *md;
1097                 EditVert **vertMap = NULL;
1098                 int j;
1099
1100                 for (ob=G.main->object.first; ob; ob=ob->id.next) {
1101                         if (ob->parent==ob && ELEM(ob->partype, PARVERT1,PARVERT3)) {
1102                                 
1103                                 /* duplicate code from below, make it function later...? */
1104                                 if (!vertMap) {
1105                                         vertMap = MEM_callocN(sizeof(*vertMap)*ototvert, "vertMap");
1106                                         
1107                                         for (eve=em->verts.first; eve; eve=eve->next) {
1108                                                 if (eve->keyindex!=-1)
1109                                                         vertMap[eve->keyindex] = eve;
1110                                         }
1111                                 }
1112                                 if(ob->par1 < ototvert) {
1113                                         eve = vertMap[ob->par1];
1114                                         if(eve) ob->par1= eve->tmp.l;
1115                                 }
1116                                 if(ob->par2 < ototvert) {
1117                                         eve = vertMap[ob->par2];
1118                                         if(eve) ob->par2= eve->tmp.l;
1119                                 }
1120                                 if(ob->par3 < ototvert) {
1121                                         eve = vertMap[ob->par3];
1122                                         if(eve) ob->par3= eve->tmp.l;
1123                                 }
1124                                 
1125                         }
1126                         if (ob->data==me) {
1127                                 for (md=ob->modifiers.first; md; md=md->next) {
1128                                         if (md->type==eModifierType_Hook) {
1129                                                 HookModifierData *hmd = (HookModifierData*) md;
1130
1131                                                 if (!vertMap) {
1132                                                         vertMap = MEM_callocN(sizeof(*vertMap)*ototvert, "vertMap");
1133
1134                                                         for (eve=em->verts.first; eve; eve=eve->next) {
1135                                                                 if (eve->keyindex!=-1)
1136                                                                         vertMap[eve->keyindex] = eve;
1137                                                         }
1138                                                 }
1139                                                 
1140                                                 for (i=j=0; i<hmd->totindex; i++) {
1141                                                         if(hmd->indexar[i] < ototvert) {
1142                                                                 eve = vertMap[hmd->indexar[i]];
1143                                                                 
1144                                                                 if (eve) {
1145                                                                         hmd->indexar[j++] = eve->tmp.l;
1146                                                                 }
1147                                                         }
1148                                                         else j++;
1149                                                 }
1150
1151                                                 hmd->totindex = j;
1152                                         }
1153                                 }
1154                         }
1155                 }
1156
1157                 if (vertMap) MEM_freeN(vertMap);
1158         }
1159
1160         /* are there keys? */
1161         if(me->key) {
1162                 KeyBlock *currkey;
1163                 KeyBlock *actkey= BLI_findlink(&me->key->block, em->shapenr-1);
1164
1165                 float (*ofs)[3] = NULL;
1166
1167                 /* editing the base key should update others */
1168                 if(me->key->type==KEY_RELATIVE && oldverts) {
1169                         int act_is_basis = 0;
1170                         /* find if this key is a basis for any others */
1171                         for(currkey = me->key->block.first; currkey; currkey= currkey->next) {
1172                                 if(em->shapenr-1 == currkey->relative) {
1173                                         act_is_basis = 1;
1174                                         break;
1175                                 }
1176                         }
1177
1178                         if(act_is_basis) { /* active key is a base */
1179                                 i=0;
1180                                 ofs= MEM_callocN(sizeof(float) * 3 * em->totvert,  "currkey->data");
1181                                 eve= em->verts.first;
1182                                 mvert = me->mvert;
1183                                 while(eve) {
1184                                         if(eve->keyindex>=0)
1185                                                 VECSUB(ofs[i], mvert->co, oldverts[eve->keyindex].co);
1186
1187                                         eve= eve->next;
1188                                         i++;
1189                                         mvert++;
1190                                 }
1191                         }
1192                 }
1193
1194
1195                 /* Lets reorder the key data so that things line up roughly
1196                  * with the way things were before editmode */
1197                 currkey = me->key->block.first;
1198                 while(currkey) {
1199                         int apply_offset = (ofs && (currkey != actkey) && (em->shapenr-1 == currkey->relative));
1200
1201                         fp= newkey= MEM_callocN(me->key->elemsize*em->totvert,  "currkey->data");
1202                         oldkey = currkey->data;
1203
1204                         eve= em->verts.first;
1205
1206                         i = 0;
1207                         mvert = me->mvert;
1208                         while(eve) {
1209                                 if (eve->keyindex >= 0 && eve->keyindex < currkey->totelem) { // valid old vertex
1210                                         if(currkey == actkey) {
1211                                                 if(actkey == me->key->refkey) {
1212                                                         VECCOPY(fp, mvert->co);
1213                                                 }
1214                                                 else {
1215                                                         VECCOPY(fp, mvert->co);
1216                                                         if(oldverts) {
1217                                                                 VECCOPY(mvert->co, oldverts[eve->keyindex].co);
1218                                                         }
1219                                                 }
1220                                         }
1221                                         else {
1222                                                 if(oldkey) {
1223                                                         VECCOPY(fp, oldkey + 3 * eve->keyindex);
1224                                                 }
1225                                         }
1226                                 }
1227                                 else {
1228                                         VECCOPY(fp, mvert->co);
1229                                 }
1230
1231                                 /* propagate edited basis offsets to other shapes */
1232                                 if(apply_offset) {
1233                                         VECADD(fp, fp, ofs[i]);
1234                                 }
1235
1236                                 fp+= 3;
1237                                 ++i;
1238                                 ++mvert;
1239                                 eve= eve->next;
1240                         }
1241                         currkey->totelem= em->totvert;
1242                         if(currkey->data) MEM_freeN(currkey->data);
1243                         currkey->data = newkey;
1244                         
1245                         currkey= currkey->next;
1246                 }
1247
1248                 if(ofs) MEM_freeN(ofs);
1249         }
1250
1251         if(oldverts) MEM_freeN(oldverts);
1252         
1253         i = 0;
1254         for(ese=em->selected.first; ese; ese=ese->next) i++;
1255         me->totselect = i;
1256         if(i==0) mselect= NULL;
1257         else mselect= MEM_callocN(i*sizeof(MSelect), "loadeditMesh selections");
1258         
1259         if(me->mselect) MEM_freeN(me->mselect);
1260         me->mselect= mselect;
1261         
1262         for(ese=em->selected.first; ese; ese=ese->next){
1263                 mselect->type = ese->type;
1264                 if(ese->type == EDITVERT) mselect->index = ((EditVert*)ese->data)->tmp.l;
1265                 else if(ese->type == EDITEDGE) mselect->index = ((EditEdge*)ese->data)->tmp.l;
1266                 else if(ese->type == EDITFACE) mselect->index = ((EditFace*)ese->data)->tmp.l;
1267                 mselect++;
1268         }
1269         
1270         /* to be sure: clear ->tmp.l pointers */
1271         eve= em->verts.first;
1272         while(eve) {
1273                 eve->tmp.l = 0;
1274                 eve= eve->next;
1275         }
1276         
1277         eed= em->edges.first;
1278         while(eed) { 
1279                 eed->tmp.l = 0;
1280                 eed= eed->next;
1281         }
1282         
1283         efa= em->faces.first;
1284         while(efa) {
1285                 efa->tmp.l = 0;
1286                 efa= efa->next;
1287         }
1288         
1289         /* remake softbody of all users */
1290         if(me->id.us>1) {
1291                 Base *base;
1292                 for(base= scene->base.first; base; base= base->next)
1293                         if(base->object->data==me)
1294                                 base->object->recalc |= OB_RECALC_DATA;
1295         }
1296
1297         mesh_calc_normals(me->mvert, me->totvert, me->mface, me->totface, NULL);
1298
1299         /* topology could be changed, ensure mdisps are ok */
1300         multires_topology_changed(scene, obedit);
1301 }
1302
1303 void remake_editMesh(Scene *scene, Object *ob)
1304 {
1305         make_editMesh(scene, ob);
1306         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1307         BIF_undo_push("Undo all changes");
1308 }
1309
1310 /* *************** Operator: separate parts *************/
1311
1312 static EnumPropertyItem prop_separate_types[] = {
1313         {0, "SELECTED", 0, "Selection", ""},
1314         {1, "MATERIAL", 0, "By Material", ""},
1315         {2, "LOOSE", 0, "By loose parts", ""},
1316         {0, NULL, 0, NULL, NULL}
1317 };
1318
1319 /* return 1: success */
1320 static int mesh_separate_selected(wmOperator *op, Main *bmain, Scene *scene, Base *editbase)
1321 {
1322         EditMesh *em, *emnew;
1323         EditVert *eve, *v1;
1324         EditEdge *eed, *e1;
1325         EditFace *efa, *f1;
1326         Object *obedit;
1327         Mesh *me, *menew;
1328         Base *basenew;
1329         
1330         if(editbase==NULL) return 0;
1331         
1332         obedit= editbase->object;
1333         me= obedit->data;
1334         em= BKE_mesh_get_editmesh(me);
1335         if(me->key) {
1336                 BKE_report(op->reports, RPT_WARNING, "Can't separate mesh with shape keys.");
1337                 BKE_mesh_end_editmesh(me, em);
1338                 return 0;
1339         }
1340         
1341         if(em->selected.first) 
1342                 BLI_freelistN(&(em->selected)); /* clear the selection order */
1343                 
1344         EM_selectmode_set(em);  // enforce full consistent selection flags 
1345         
1346         EM_stats_update(em);
1347         
1348         if(em->totvertsel==0) {
1349                 BKE_mesh_end_editmesh(me, em);
1350                 return 0;
1351         }
1352         
1353         /* we are going to work as follows:
1354          * 1. add a linked duplicate object: this will be the new one, we remember old pointer
1355          * 2. give new object empty mesh and put in editmode
1356          * 3: do a split if needed on current editmesh.
1357          * 4. copy over: all NOT selected verts, edges, faces
1358          * 5. call load_editMesh() on the new object
1359          */
1360         
1361         /* 1 */
1362         basenew= ED_object_add_duplicate(bmain, scene, editbase, 0);    /* 0 = fully linked */
1363         ED_base_object_select(basenew, BA_DESELECT);
1364         
1365         /* 2 */
1366         basenew->object->data= menew= add_mesh(me->id.name+2);  /* empty */
1367         assign_matarar(basenew->object, give_matarar(obedit), *give_totcolp(obedit)); /* new in 2.5 */
1368         me->id.us--;
1369         make_editMesh(scene, basenew->object);
1370         emnew= menew->edit_mesh;
1371         CustomData_copy(&em->vdata, &emnew->vdata, CD_MASK_EDITMESH, CD_DEFAULT, 0);
1372         CustomData_copy(&em->edata, &emnew->edata, CD_MASK_EDITMESH, CD_DEFAULT, 0);
1373         CustomData_copy(&em->fdata, &emnew->fdata, CD_MASK_EDITMESH, CD_DEFAULT, 0);
1374         
1375         /* 3 */
1376         /* SPLIT: first make duplicate */
1377         adduplicateflag(em, SELECT);
1378         /* SPLIT: old faces have 3x flag 128 set, delete these ones */
1379         delfaceflag(em, 128);
1380         /* since we do tricky things with verts/edges/faces, this makes sure all is selected coherent */
1381         EM_selectmode_set(em);
1382         
1383         /* 4 */
1384         /* move over: everything that is selected */
1385         for(eve= em->verts.first; eve; eve= v1) {
1386                 v1= eve->next;
1387                 if(eve->f & SELECT) {
1388                         BLI_remlink(&em->verts, eve);
1389                         BLI_addtail(&emnew->verts, eve);
1390                 }
1391         }
1392         
1393         for(eed= em->edges.first; eed; eed= e1) {
1394                 e1= eed->next;
1395                 if(eed->f & SELECT) {
1396                         BLI_remlink(&em->edges, eed);
1397                         BLI_addtail(&emnew->edges, eed);
1398                 }
1399         }
1400         
1401         for(efa= em->faces.first; efa; efa= f1) {
1402                 f1= efa->next;
1403                 if (efa == em->act_face && (efa->f & SELECT)) {
1404                         EM_set_actFace(em, NULL);
1405                 }
1406
1407                 if(efa->f & SELECT) {
1408                         BLI_remlink(&em->faces, efa);
1409                         BLI_addtail(&emnew->faces, efa);
1410                 }
1411         }
1412
1413         /* 5 */
1414         load_editMesh(scene, basenew->object);
1415         free_editMesh(emnew);
1416         MEM_freeN(menew->edit_mesh);
1417         menew->edit_mesh= NULL;
1418         
1419         /* hashedges are invalid now, make new! */
1420         editMesh_set_hash(em);
1421
1422         DAG_id_tag_update(&obedit->id, OB_RECALC_DATA); 
1423         DAG_id_tag_update(&basenew->object->id, OB_RECALC_DATA);        
1424
1425         BKE_mesh_end_editmesh(me, em);
1426
1427         return 1;
1428 }
1429
1430 /* return 1: success */
1431 static int mesh_separate_material(wmOperator *op, Main *bmain, Scene *scene, Base *editbase)
1432 {
1433         Mesh *me= editbase->object->data;
1434         EditMesh *em= BKE_mesh_get_editmesh(me);
1435         unsigned char curr_mat;
1436         
1437         for (curr_mat = 1; curr_mat < editbase->object->totcol; ++curr_mat) {
1438                 /* clear selection, we're going to use that to select material group */
1439                 EM_clear_flag_all(em, SELECT);
1440                 /* select the material */
1441                 EM_select_by_material(em, curr_mat);
1442                 /* and now separate */
1443                 if(0==mesh_separate_selected(op, bmain, scene, editbase)) {
1444                         BKE_mesh_end_editmesh(me, em);
1445                         return 0;
1446                 }
1447         }
1448
1449         BKE_mesh_end_editmesh(me, em);
1450         return 1;
1451 }
1452
1453 /* return 1: success */
1454 static int mesh_separate_loose(wmOperator *op, Main *bmain, Scene *scene, Base *editbase)
1455 {
1456         Mesh *me;
1457         EditMesh *em;
1458         int doit= 1;
1459         
1460         me= editbase->object->data;
1461         em= BKE_mesh_get_editmesh(me);
1462         
1463         if(me->key) {
1464                 error("Can't separate with vertex keys");
1465                 BKE_mesh_end_editmesh(me, em);
1466                 return 0;
1467         }
1468         
1469         EM_clear_flag_all(em, SELECT);
1470
1471         while(doit) {
1472                 /* Select a random vert to start with */
1473                 EditVert *eve;
1474                 int tot;
1475
1476                 /* check if all verts that are visible have been done */
1477                 for(eve=em->verts.first; eve; eve= eve->next)
1478                         if(!eve->h) break;
1479                 if(eve==NULL) break; /* only hidden verts left, quit early */
1480
1481                 /* first non hidden vert */
1482                 eve->f |= SELECT;
1483                 
1484                 selectconnected_mesh_all(em);
1485                 
1486                 /* don't separate the very last part */
1487                 for(eve=em->verts.first; eve; eve= eve->next)
1488                         if((eve->f & SELECT)==0) break;
1489                 if(eve==NULL) break;
1490
1491                 tot= BLI_countlist(&em->verts);
1492
1493                 /* and now separate */
1494                 doit= mesh_separate_selected(op, bmain, scene, editbase);
1495
1496                 /* with hidden verts this can happen */
1497                 if(tot == BLI_countlist(&em->verts))
1498                         break;
1499         }
1500
1501         BKE_mesh_end_editmesh(me, em);
1502         return 1;
1503 }
1504
1505
1506 static int mesh_separate_exec(bContext *C, wmOperator *op)
1507 {
1508         Main *bmain= CTX_data_main(C);
1509         Scene *scene= CTX_data_scene(C);
1510         Base *base= CTX_data_active_base(C);
1511         int retval= 0, type= RNA_enum_get(op->ptr, "type");
1512         
1513         if(type == 0)
1514                 retval= mesh_separate_selected(op, bmain, scene, base);
1515         else if(type == 1)
1516                 retval= mesh_separate_material(op, bmain, scene, base);
1517         else if(type == 2)
1518                 retval= mesh_separate_loose(op, bmain, scene, base);
1519            
1520         if(retval) {
1521                 WM_event_add_notifier(C, NC_GEOM|ND_DATA, base->object->data);
1522
1523                 // XXX: new object was created, but selection wasn't actually changed
1524                 //      need this for outliner update without adding new ND. nazgul.
1525                 WM_event_add_notifier(C, NC_SCENE|ND_OB_SELECT, scene);
1526
1527                 return OPERATOR_FINISHED;
1528         }
1529         return OPERATOR_CANCELLED;
1530 }
1531
1532 void MESH_OT_separate(wmOperatorType *ot)
1533 {
1534         /* identifiers */
1535         ot->name= "Separate";
1536         ot->description= "Separate selected geometry into a new mesh";
1537         ot->idname= "MESH_OT_separate";
1538         
1539         /* api callbacks */
1540         ot->invoke= WM_menu_invoke;
1541         ot->exec= mesh_separate_exec;
1542         ot->poll= ED_operator_editmesh;
1543         
1544         /* flags */
1545         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1546         
1547         ot->prop= RNA_def_enum(ot->srna, "type", prop_separate_types, 0, "Type", "");
1548 }
1549
1550
1551 /* ******************************************** */
1552
1553 /* *************** UNDO ***************************** */
1554 /* new mesh undo, based on pushing editmesh data itself */
1555 /* reuses same code as for global and curve undo... unify that (ton) */
1556
1557 /* only one 'hack', to save memory it doesn't store the first push, but does a remake editmesh */
1558
1559 /* a compressed version of editmesh data */
1560
1561 typedef struct EditVertC
1562 {
1563         float no[3];
1564         float co[3];
1565         unsigned char f, h;
1566         short bweight;
1567         int keyindex;
1568 } EditVertC;
1569
1570 typedef struct EditEdgeC
1571 {
1572         int v1, v2;
1573         unsigned char f, h, seam, sharp, pad;
1574         short crease, bweight, fgoni;
1575 } EditEdgeC;
1576
1577 typedef struct EditFaceC
1578 {
1579         int v1, v2, v3, v4;
1580         unsigned char flag, f, h, fgonf, pad1;
1581         short mat_nr;
1582 } EditFaceC;
1583
1584 typedef struct EditSelectionC{
1585         short type;
1586         int index;
1587 }EditSelectionC;
1588
1589 typedef struct UndoMesh {
1590         EditVertC *verts;
1591         EditEdgeC *edges;
1592         EditFaceC *faces;
1593         EditSelectionC *selected;
1594         int totvert, totedge, totface, totsel;
1595         int selectmode, shapenr;
1596         char retopo_mode;
1597         CustomData vdata, edata, fdata;
1598 } UndoMesh;
1599
1600 /* for callbacks */
1601
1602 static void free_undoMesh(void *umv)
1603 {
1604         UndoMesh *um= umv;
1605         
1606         if(um->verts) MEM_freeN(um->verts);
1607         if(um->edges) MEM_freeN(um->edges);
1608         if(um->faces) MEM_freeN(um->faces);
1609         if(um->selected) MEM_freeN(um->selected);
1610 // XXX  if(um->retopo_paint_data) retopo_free_paint_data(um->retopo_paint_data);
1611         CustomData_free(&um->vdata, um->totvert);
1612         CustomData_free(&um->edata, um->totedge);
1613         CustomData_free(&um->fdata, um->totface);
1614         MEM_freeN(um);
1615 }
1616
1617 static void *editMesh_to_undoMesh(void *emv)
1618 {
1619         EditMesh *em= (EditMesh *)emv;
1620         UndoMesh *um;
1621         EditVert *eve;
1622         EditEdge *eed;
1623         EditFace *efa;
1624         EditSelection *ese;
1625         EditVertC *evec=NULL;
1626         EditEdgeC *eedc=NULL;
1627         EditFaceC *efac=NULL;
1628         EditSelectionC *esec=NULL;
1629         int a;
1630
1631         um= MEM_callocN(sizeof(UndoMesh), "undomesh");
1632         
1633         um->selectmode = em->selectmode;
1634         um->shapenr = em->shapenr;
1635         
1636         for(eve=em->verts.first; eve; eve= eve->next) um->totvert++;
1637         for(eed=em->edges.first; eed; eed= eed->next) um->totedge++;
1638         for(efa=em->faces.first; efa; efa= efa->next) um->totface++;
1639         for(ese=em->selected.first; ese; ese=ese->next) um->totsel++; 
1640         /* malloc blocks */
1641         
1642         if(um->totvert) evec= um->verts= MEM_callocN(um->totvert*sizeof(EditVertC), "allvertsC");
1643         if(um->totedge) eedc= um->edges= MEM_callocN(um->totedge*sizeof(EditEdgeC), "alledgesC");
1644         if(um->totface) efac= um->faces= MEM_callocN(um->totface*sizeof(EditFaceC), "allfacesC");
1645         if(um->totsel) esec= um->selected= MEM_callocN(um->totsel*sizeof(EditSelectionC), "allselections");
1646
1647         if(um->totvert) CustomData_copy(&em->vdata, &um->vdata, CD_MASK_EDITMESH, CD_CALLOC, um->totvert);
1648         if(um->totedge) CustomData_copy(&em->edata, &um->edata, CD_MASK_EDITMESH, CD_CALLOC, um->totedge);
1649         if(um->totface) CustomData_copy(&em->fdata, &um->fdata, CD_MASK_EDITMESH, CD_CALLOC, um->totface);
1650         
1651         /* now copy vertices */
1652         a = 0;
1653         for(eve=em->verts.first; eve; eve= eve->next, evec++, a++) {
1654                 VECCOPY(evec->co, eve->co);
1655                 VECCOPY(evec->no, eve->no);
1656
1657                 evec->f= eve->f;
1658                 evec->h= eve->h;
1659                 evec->keyindex= eve->keyindex;
1660                 eve->tmp.l = a; /*store index*/
1661                 evec->bweight= (short)(eve->bweight*255.0);
1662
1663                 CustomData_from_em_block(&em->vdata, &um->vdata, eve->data, a);
1664         }
1665         
1666         /* copy edges */
1667         a = 0;
1668         for(eed=em->edges.first; eed; eed= eed->next, eedc++, a++)  {
1669                 eedc->v1= (int)eed->v1->tmp.l;
1670                 eedc->v2= (int)eed->v2->tmp.l;
1671                 eedc->f= eed->f;
1672                 eedc->h= eed->h;
1673                 eedc->seam= eed->seam;
1674                 eedc->sharp= eed->sharp;
1675                 eedc->crease= (short)(eed->crease*255.0);
1676                 eedc->bweight= (short)(eed->bweight*255.0);
1677                 eedc->fgoni= eed->fgoni;
1678                 eed->tmp.l = a; /*store index*/
1679                 CustomData_from_em_block(&em->edata, &um->edata, eed->data, a);
1680         
1681         }
1682         
1683         /* copy faces */
1684         a = 0;
1685         for(efa=em->faces.first; efa; efa= efa->next, efac++, a++) {
1686                 efac->v1= (int)efa->v1->tmp.l;
1687                 efac->v2= (int)efa->v2->tmp.l;
1688                 efac->v3= (int)efa->v3->tmp.l;
1689                 if(efa->v4) efac->v4= (int)efa->v4->tmp.l;
1690                 else efac->v4= -1;
1691                 
1692                 efac->mat_nr= efa->mat_nr;
1693                 efac->flag= efa->flag;
1694                 efac->f= efa->f;
1695                 efac->h= efa->h;
1696                 efac->fgonf= efa->fgonf;
1697
1698                 efa->tmp.l = a; /*store index*/
1699
1700                 CustomData_from_em_block(&em->fdata, &um->fdata, efa->data, a);
1701         }
1702         
1703         a = 0;
1704         for(ese=em->selected.first; ese; ese=ese->next, esec++){
1705                 esec->type = ese->type;
1706                 if(ese->type == EDITVERT) a = esec->index = ((EditVert*)ese->data)->tmp.l; 
1707                 else if(ese->type == EDITEDGE) a = esec->index = ((EditEdge*)ese->data)->tmp.l; 
1708                 else if(ese->type == EDITFACE) a = esec->index = ((EditFace*)ese->data)->tmp.l;
1709         }
1710
1711 // XXX  um->retopo_paint_data= retopo_paint_data_copy(em->retopo_paint_data);
1712 //      um->retopo_mode= scene->toolsettings->retopo_mode;
1713         
1714         return um;
1715 }
1716
1717 static void undoMesh_to_editMesh(void *umv, void *emv)
1718 {
1719         EditMesh *em= (EditMesh *)emv;
1720         UndoMesh *um= (UndoMesh *)umv;
1721         EditVert *eve, **evar=NULL;
1722         EditEdge *eed;
1723         EditFace *efa;
1724         EditSelection *ese;
1725         EditVertC *evec;
1726         EditEdgeC *eedc;
1727         EditFaceC *efac;
1728         EditSelectionC *esec;
1729         int a=0;
1730
1731         free_editMesh(em);
1732         
1733         /* malloc blocks */
1734         memset(em, 0, sizeof(EditMesh));
1735                 
1736         em->selectmode = um->selectmode;
1737         em->shapenr = um->shapenr;
1738         
1739         init_editmesh_fastmalloc(em, um->totvert, um->totedge, um->totface);
1740
1741         CustomData_free(&em->vdata, 0);
1742         CustomData_free(&em->edata, 0);
1743         CustomData_free(&em->fdata, 0);
1744
1745         CustomData_copy(&um->vdata, &em->vdata, CD_MASK_EDITMESH, CD_CALLOC, 0);
1746         CustomData_copy(&um->edata, &em->edata, CD_MASK_EDITMESH, CD_CALLOC, 0);
1747         CustomData_copy(&um->fdata, &em->fdata, CD_MASK_EDITMESH, CD_CALLOC, 0);
1748
1749         /* now copy vertices */
1750
1751         if(um->totvert) evar= MEM_mallocN(um->totvert*sizeof(EditVert *), "vertex ar");
1752         for(a=0, evec= um->verts; a<um->totvert; a++, evec++) {
1753                 eve= addvertlist(em, evec->co, NULL);
1754                 evar[a]= eve;
1755
1756                 VECCOPY(eve->no, evec->no);
1757                 eve->f= evec->f;
1758                 eve->h= evec->h;
1759                 eve->keyindex= evec->keyindex;
1760                 eve->bweight= ((float)evec->bweight)/255.0f;
1761
1762                 CustomData_to_em_block(&um->vdata, &em->vdata, a, &eve->data);
1763         }
1764
1765         /* copy edges */
1766         for(a=0, eedc= um->edges; a<um->totedge; a++, eedc++) {
1767                 eed= addedgelist(em, evar[eedc->v1], evar[eedc->v2], NULL);
1768
1769                 eed->f= eedc->f;
1770                 eed->h= eedc->h;
1771                 eed->seam= eedc->seam;
1772                 eed->sharp= eedc->sharp;
1773                 eed->fgoni= eedc->fgoni;
1774                 eed->crease= ((float)eedc->crease)/255.0f;
1775                 eed->bweight= ((float)eedc->bweight)/255.0f;
1776                 CustomData_to_em_block(&um->edata, &em->edata, a, &eed->data);
1777         }
1778         
1779         /* copy faces */
1780         for(a=0, efac= um->faces; a<um->totface; a++, efac++) {
1781                 if(efac->v4 != -1)
1782                         efa= addfacelist(em, evar[efac->v1], evar[efac->v2], evar[efac->v3], evar[efac->v4], NULL, NULL);
1783                 else 
1784                         efa= addfacelist(em, evar[efac->v1], evar[efac->v2], evar[efac->v3], NULL, NULL ,NULL);
1785
1786                 efa->mat_nr= efac->mat_nr;
1787                 efa->flag= efac->flag;
1788                 efa->f= efac->f;
1789                 efa->h= efac->h;
1790                 efa->fgonf= efac->fgonf;
1791                 
1792                 CustomData_to_em_block(&um->fdata, &em->fdata, a, &efa->data);
1793         }
1794         
1795         end_editmesh_fastmalloc();
1796         if(evar) MEM_freeN(evar);
1797         
1798         em->totvert = um->totvert;
1799         em->totedge = um->totedge;
1800         em->totface = um->totface;
1801         /*restore stored editselections*/
1802         if(um->totsel){
1803                 EM_init_index_arrays(em, 1,1,1);
1804                 for(a=0, esec= um->selected; a<um->totsel; a++, esec++){
1805                         ese = MEM_callocN(sizeof(EditSelection), "Edit Selection");
1806                         ese->type = esec->type;
1807                         if(ese->type == EDITVERT) ese->data = EM_get_vert_for_index(esec->index); else
1808                         if(ese->type == EDITEDGE) ese->data = EM_get_edge_for_index(esec->index); else
1809                         if(ese->type == EDITFACE) ese->data = EM_get_face_for_index(esec->index);
1810                         BLI_addtail(&(em->selected),ese);
1811                 }
1812                 EM_free_index_arrays();
1813         }
1814
1815         /* restore total selections */
1816         EM_nvertices_selected(em);
1817         EM_nedges_selected(em);
1818         EM_nfaces_selected(em);
1819
1820 // XXX  retopo_free_paint();
1821 //      em->retopo_paint_data= retopo_paint_data_copy(um->retopo_paint_data);
1822 //      scene->toolsettings->retopo_mode= um->retopo_mode;
1823 //      if(scene->toolsettings->retopo_mode) {
1824 // XXX          if(G.vd->depths) G.vd->depths->damaged= 1;
1825 //              retopo_queue_updates(G.vd);
1826 //              retopo_paint_view_update(G.vd);
1827 //      }
1828         
1829 }
1830
1831 static void *getEditMesh(bContext *C)
1832 {
1833         Object *obedit= CTX_data_edit_object(C);
1834         if(obedit && obedit->type==OB_MESH) {
1835                 Mesh *me= obedit->data;
1836                 return me->edit_mesh;
1837         }
1838         return NULL;
1839 }
1840
1841 /* and this is all the undo system needs to know */
1842 void undo_push_mesh(bContext *C, const char *name)
1843 {
1844         undo_editmode_push(C, name, getEditMesh, free_undoMesh, undoMesh_to_editMesh, editMesh_to_undoMesh, NULL);
1845 }
1846
1847
1848
1849 /* *************** END UNDO *************/
1850
1851 static EditVert **g_em_vert_array = NULL;
1852 static EditEdge **g_em_edge_array = NULL;
1853 static EditFace **g_em_face_array = NULL;
1854
1855 void EM_init_index_arrays(EditMesh *em, int forVert, int forEdge, int forFace)
1856 {
1857         EditVert *eve;
1858         EditEdge *eed;
1859         EditFace *efa;
1860         int i;
1861
1862         if (forVert) {
1863                 em->totvert= BLI_countlist(&em->verts);
1864
1865                 if(em->totvert) {
1866                         g_em_vert_array = MEM_mallocN(sizeof(*g_em_vert_array)*em->totvert, "em_v_arr");
1867
1868                         for (i=0,eve=em->verts.first; eve; i++,eve=eve->next)
1869                                 g_em_vert_array[i] = eve;
1870                 }
1871         }
1872
1873         if (forEdge) {
1874                 em->totedge= BLI_countlist(&em->edges);
1875
1876                 if(em->totedge) {
1877                         g_em_edge_array = MEM_mallocN(sizeof(*g_em_edge_array)*em->totedge, "em_e_arr");
1878
1879                         for (i=0,eed=em->edges.first; eed; i++,eed=eed->next)
1880                                 g_em_edge_array[i] = eed;
1881                 }
1882         }
1883
1884         if (forFace) {
1885                 em->totface= BLI_countlist(&em->faces);
1886
1887                 if(em->totface) {
1888                         g_em_face_array = MEM_mallocN(sizeof(*g_em_face_array)*em->totface, "em_f_arr");
1889
1890                         for (i=0,efa=em->faces.first; efa; i++,efa=efa->next)
1891                                 g_em_face_array[i] = efa;
1892                 }
1893         }
1894 }
1895
1896 void EM_free_index_arrays(void)
1897 {
1898         if (g_em_vert_array) MEM_freeN(g_em_vert_array);
1899         if (g_em_edge_array) MEM_freeN(g_em_edge_array);
1900         if (g_em_face_array) MEM_freeN(g_em_face_array);
1901         g_em_vert_array = NULL;
1902         g_em_edge_array = NULL;
1903         g_em_face_array = NULL;
1904 }
1905
1906 EditVert *EM_get_vert_for_index(int index)
1907 {
1908         return g_em_vert_array?g_em_vert_array[index]:NULL;
1909 }
1910
1911 EditEdge *EM_get_edge_for_index(int index)
1912 {
1913         return g_em_edge_array?g_em_edge_array[index]:NULL;
1914 }
1915
1916 EditFace *EM_get_face_for_index(int index)
1917 {
1918         return g_em_face_array?g_em_face_array[index]:NULL;
1919 }
1920
1921 /* can we edit UV's for this mesh?*/
1922 int EM_texFaceCheck(EditMesh *em)
1923 {
1924         /* some of these checks could be a touch overkill */
1925         if (    (em) &&
1926                         (em->faces.first) &&
1927                         (CustomData_has_layer(&em->fdata, CD_MTFACE)))
1928                 return 1;
1929         return 0;
1930 }
1931
1932 /* can we edit colors for this mesh?*/
1933 int EM_vertColorCheck(EditMesh *em)
1934 {
1935         /* some of these checks could be a touch overkill */
1936         if (    (em) &&
1937                         (em->faces.first) &&
1938                         (CustomData_has_layer(&em->fdata, CD_MCOL)))
1939                 return 1;
1940         return 0;
1941 }
1942
1943
1944 void em_setup_viewcontext(bContext *C, ViewContext *vc)
1945 {
1946         view3d_set_viewcontext(C, vc);
1947         
1948         if(vc->obedit) {
1949                 Mesh *me= vc->obedit->data;
1950                 vc->em= me->edit_mesh;
1951         }
1952 }