vgroup_validmap needed to be assigned when locks were active.
[blender.git] / source / blender / editors / sculpt_paint / paint_vertex.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  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /** \file blender/editors/sculpt_paint/paint_vertex.c
31  *  \ingroup edsculpt
32  */
33
34
35 #include <math.h>
36 #include <string.h>
37
38 #ifdef WIN32
39 #include <io.h>
40 #else
41 #include <unistd.h>
42 #endif   
43
44 #include "MEM_guardedalloc.h"
45
46 #include "BLI_blenlib.h"
47 #include "BLI_math.h"
48 #include "BLI_utildefines.h"
49 #include "BLI_ghash.h"
50
51 #include "IMB_imbuf.h"
52 #include "IMB_imbuf_types.h"
53
54 #include "DNA_armature_types.h"
55 #include "DNA_mesh_types.h"
56 #include "DNA_particle_types.h"
57 #include "DNA_scene_types.h"
58 #include "DNA_brush_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_meshdata_types.h"
61
62 #include "RNA_access.h"
63 #include "RNA_define.h"
64 #include "RNA_enum_types.h"
65
66 #include "BKE_DerivedMesh.h"
67 #include "BKE_armature.h"
68 #include "BKE_action.h"
69 #include "BKE_brush.h"
70 #include "BKE_context.h"
71 #include "BKE_depsgraph.h"
72 #include "BKE_deform.h"
73 #include "BKE_mesh.h"
74 #include "BKE_modifier.h"
75 #include "BKE_object.h"
76 #include "BKE_paint.h"
77 #include "BKE_report.h"
78
79 #include "WM_api.h"
80 #include "WM_types.h"
81
82
83 #include "ED_armature.h"
84 #include "ED_mesh.h"
85 #include "ED_screen.h"
86 #include "ED_view3d.h"
87
88 #include "paint_intern.h"
89
90 /* brush->vertexpaint_tool */
91 #define VP_MIX  0
92 #define VP_ADD  1
93 #define VP_SUB  2
94 #define VP_MUL  3
95 #define VP_BLUR 4
96 #define VP_LIGHTEN      5
97 #define VP_DARKEN       6
98
99 /* polling - retrieve whether cursor should be set or operator should be done */
100
101
102 /* Returns true if vertex paint mode is active */
103 int vertex_paint_mode_poll(bContext *C)
104 {
105         Object *ob = CTX_data_active_object(C);
106
107         return ob && ob->mode == OB_MODE_VERTEX_PAINT && ((Mesh *)ob->data)->totface;
108 }
109
110 int vertex_paint_poll(bContext *C)
111 {
112         if(vertex_paint_mode_poll(C) && 
113            paint_brush(&CTX_data_tool_settings(C)->vpaint->paint)) {
114                 ScrArea *sa= CTX_wm_area(C);
115                 if(sa->spacetype==SPACE_VIEW3D) {
116                         ARegion *ar= CTX_wm_region(C);
117                         if(ar->regiontype==RGN_TYPE_WINDOW)
118                                 return 1;
119                         }
120                 }
121         return 0;
122 }
123
124 int weight_paint_mode_poll(bContext *C)
125 {
126         Object *ob = CTX_data_active_object(C);
127
128         return ob && ob->mode == OB_MODE_WEIGHT_PAINT && ((Mesh *)ob->data)->totface;
129 }
130
131 int weight_paint_poll(bContext *C)
132 {
133         Object *ob= CTX_data_active_object(C);
134         ScrArea *sa;
135
136         if(     (ob != NULL) &&
137                 (ob->mode & OB_MODE_WEIGHT_PAINT) &&
138                 (paint_brush(&CTX_data_tool_settings(C)->wpaint->paint) != NULL) &&
139                 (sa= CTX_wm_area(C)) &&
140                 (sa->spacetype == SPACE_VIEW3D)
141         ) {
142                 ARegion *ar= CTX_wm_region(C);
143                 if(ar->regiontype==RGN_TYPE_WINDOW) {
144                         return 1;
145                 }
146         }
147         return 0;
148 }
149
150 static VPaint *new_vpaint(int wpaint)
151 {
152         VPaint *vp= MEM_callocN(sizeof(VPaint), "VPaint");
153         
154         vp->flag= VP_AREA+VP_SPRAY;
155         
156         if(wpaint)
157                 vp->flag= VP_AREA;
158
159         return vp;
160 }
161
162 static int *get_indexarray(Mesh *me)
163 {
164         return MEM_mallocN(sizeof(int)*(me->totface+1), "vertexpaint");
165 }
166
167
168 /* in contradiction to cpack drawing colors, the MCOL colors (vpaint colors) are per byte! 
169    so not endian sensitive. Mcol = ABGR!!! so be cautious with cpack calls */
170
171 static unsigned int rgba_to_mcol(float r, float g, float b, float a)
172 {
173         int ir, ig, ib, ia;
174         unsigned int col;
175         char *cp;
176         
177         ir= floor(255.0f * r);
178         if(ir<0) ir= 0; else if(ir>255) ir= 255;
179         ig= floor(255.0f * g);
180         if(ig<0) ig= 0; else if(ig>255) ig= 255;
181         ib= floor(255.0f * b);
182         if(ib<0) ib= 0; else if(ib>255) ib= 255;
183         ia= floor(255.0f * a);
184         if(ia<0) ia= 0; else if(ia>255) ia= 255;
185         
186         cp= (char *)&col;
187         cp[0]= ia;
188         cp[1]= ib;
189         cp[2]= ig;
190         cp[3]= ir;
191         
192         return col;
193         
194 }
195
196 unsigned int vpaint_get_current_col(VPaint *vp)
197 {
198         Brush *brush = paint_brush(&vp->paint);
199         return rgba_to_mcol(brush->rgb[0], brush->rgb[1], brush->rgb[2], 1.0f);
200 }
201
202 static void do_shared_vertexcol(Mesh *me)
203 {
204         /* if no mcol: do not do */
205         /* if tface: only the involved faces, otherwise all */
206         MFace *mface;
207         MTFace *tface;
208         int a;
209         short *scolmain, *scol;
210         char *mcol;
211         
212         if(me->mcol==NULL || me->totvert==0 || me->totface==0) return;
213         
214         scolmain= MEM_callocN(4*sizeof(short)*me->totvert, "colmain");
215         
216         tface= me->mtface;
217         mface= me->mface;
218         mcol= (char *)me->mcol;
219         for(a=me->totface; a>0; a--, mface++, mcol+=16) {
220                 if((tface && tface->mode & TF_SHAREDCOL) || (me->editflag & ME_EDIT_PAINT_MASK)==0) {
221                         scol= scolmain+4*mface->v1;
222                         scol[0]++; scol[1]+= mcol[1]; scol[2]+= mcol[2]; scol[3]+= mcol[3];
223                         scol= scolmain+4*mface->v2;
224                         scol[0]++; scol[1]+= mcol[5]; scol[2]+= mcol[6]; scol[3]+= mcol[7];
225                         scol= scolmain+4*mface->v3;
226                         scol[0]++; scol[1]+= mcol[9]; scol[2]+= mcol[10]; scol[3]+= mcol[11];
227                         if(mface->v4) {
228                                 scol= scolmain+4*mface->v4;
229                                 scol[0]++; scol[1]+= mcol[13]; scol[2]+= mcol[14]; scol[3]+= mcol[15];
230                         }
231                 }
232                 if(tface) tface++;
233         }
234         
235         a= me->totvert;
236         scol= scolmain;
237         while(a--) {
238                 if(scol[0]>1) {
239                         scol[1]/= scol[0];
240                         scol[2]/= scol[0];
241                         scol[3]/= scol[0];
242                 }
243                 scol+= 4;
244         }
245         
246         tface= me->mtface;
247         mface= me->mface;
248         mcol= (char *)me->mcol;
249         for(a=me->totface; a>0; a--, mface++, mcol+=16) {
250                 if((tface && tface->mode & TF_SHAREDCOL) || (me->editflag & ME_EDIT_PAINT_MASK)==0) {
251                         scol= scolmain+4*mface->v1;
252                         mcol[1]= scol[1]; mcol[2]= scol[2]; mcol[3]= scol[3];
253                         scol= scolmain+4*mface->v2;
254                         mcol[5]= scol[1]; mcol[6]= scol[2]; mcol[7]= scol[3];
255                         scol= scolmain+4*mface->v3;
256                         mcol[9]= scol[1]; mcol[10]= scol[2]; mcol[11]= scol[3];
257                         if(mface->v4) {
258                                 scol= scolmain+4*mface->v4;
259                                 mcol[13]= scol[1]; mcol[14]= scol[2]; mcol[15]= scol[3];
260                         }
261                 }
262                 if(tface) tface++;
263         }
264
265         MEM_freeN(scolmain);
266 }
267
268 static void make_vertexcol(Object *ob)  /* single ob */
269 {
270         Mesh *me;
271         if(!ob || ob->id.lib) return;
272         me= get_mesh(ob);
273         if(me==NULL) return;
274         if(me->edit_mesh) return;
275
276         /* copies from shadedisplist to mcol */
277         if(!me->mcol) {
278                 CustomData_add_layer(&me->fdata, CD_MCOL, CD_CALLOC, NULL, me->totface);
279                 mesh_update_customdata_pointers(me);
280         }
281
282         //if(shade)
283         //      shadeMeshMCol(scene, ob, me);
284         //else
285
286         memset(me->mcol, 255, 4*sizeof(MCol)*me->totface);
287         
288         DAG_id_tag_update(&me->id, 0);
289         
290 }
291
292 /* mirror_vgroup is set to -1 when invalid */
293 static void wpaint_mirror_vgroup_ensure(Object *ob, int *vgroup_mirror)
294 {
295         bDeformGroup *defgroup= BLI_findlink(&ob->defbase, ob->actdef - 1);
296
297         if(defgroup) {
298                 bDeformGroup *curdef;
299                 int mirrdef;
300                 char name[MAXBONENAME];
301
302                 flip_side_name(name, defgroup->name, FALSE);
303
304                 if(strcmp(name, defgroup->name) != 0) {
305                         for (curdef= ob->defbase.first, mirrdef= 0; curdef; curdef=curdef->next, mirrdef++) {
306                                 if (!strcmp(curdef->name, name)) {
307                                         break;
308                                 }
309                         }
310
311                         if(curdef==NULL) {
312                                 int olddef= ob->actdef; /* tsk, ED_vgroup_add sets the active defgroup */
313                                 curdef= ED_vgroup_add_name(ob, name);
314                                 ob->actdef= olddef;
315                         }
316
317                         /* curdef should never be NULL unless this is
318                          * a  lamp and ED_vgroup_add_name fails */
319                         if(curdef) {
320                                 *vgroup_mirror= mirrdef;
321                                 return;
322                         }
323                 }
324         }
325
326         *vgroup_mirror= -1;
327 }
328
329 static void copy_vpaint_prev(VPaint *vp, unsigned int *mcol, int tot)
330 {
331         if(vp->vpaint_prev) {
332                 MEM_freeN(vp->vpaint_prev);
333                 vp->vpaint_prev= NULL;
334         }
335         vp->tot= tot;   
336         
337         if(mcol==NULL || tot==0) return;
338         
339         vp->vpaint_prev= MEM_mallocN(4*sizeof(int)*tot, "vpaint_prev");
340         memcpy(vp->vpaint_prev, mcol, 4*sizeof(int)*tot);
341         
342 }
343
344 static void copy_wpaint_prev (VPaint *wp, MDeformVert *dverts, int dcount)
345 {
346         if (wp->wpaint_prev) {
347                 free_dverts(wp->wpaint_prev, wp->tot);
348                 wp->wpaint_prev= NULL;
349         }
350         
351         if(dverts && dcount) {
352                 
353                 wp->wpaint_prev = MEM_mallocN (sizeof(MDeformVert)*dcount, "wpaint prev");
354                 wp->tot = dcount;
355                 copy_dverts (wp->wpaint_prev, dverts, dcount);
356         }
357 }
358
359
360 void vpaint_fill(Object *ob, unsigned int paintcol)
361 {
362         Mesh *me;
363         MFace *mf;
364         unsigned int *mcol;
365         int i, selected;
366
367         me= get_mesh(ob);
368         if(me==NULL || me->totface==0) return;
369
370         if(!me->mcol)
371                 make_vertexcol(ob);
372
373         selected= (me->editflag & ME_EDIT_PAINT_MASK);
374
375         mf = me->mface;
376         mcol = (unsigned int*)me->mcol;
377         for (i = 0; i < me->totface; i++, mf++, mcol+=4) {
378                 if (!selected || mf->flag & ME_FACE_SEL) {
379                         mcol[0] = paintcol;
380                         mcol[1] = paintcol;
381                         mcol[2] = paintcol;
382                         mcol[3] = paintcol;
383                 }
384         }
385         
386         DAG_id_tag_update(&me->id, 0);
387 }
388
389
390 /* fills in the selected faces with the current weight and vertex group */
391 void wpaint_fill(VPaint *wp, Object *ob, float paintweight)
392 {
393         Mesh *me;
394         MFace *mface;
395         MDeformWeight *dw, *uw;
396         int *indexar;
397         int index, vgroup;
398         unsigned int faceverts[5]={0,0,0,0,0};
399         unsigned char i;
400         int vgroup_mirror= -1;
401         int selected;
402         
403         int use_vert_sel;
404
405         me= ob->data;
406         if(me==NULL || me->totface==0 || me->dvert==NULL || !me->mface) return;
407         
408         selected= (me->editflag & ME_EDIT_PAINT_MASK);
409         
410         use_vert_sel= (me->editflag & ME_EDIT_VERT_SEL) != 0;
411
412         indexar= get_indexarray(me);
413
414         if(selected) {
415                 for(index=0, mface=me->mface; index<me->totface; index++, mface++) {
416                         if((mface->flag & ME_FACE_SEL)==0)
417                                 indexar[index]= 0;
418                         else
419                                 indexar[index]= index+1;
420                 }
421         }
422         else {
423                 for(index=0; index<me->totface; index++)
424                         indexar[index]= index+1;
425         }
426         
427         vgroup= ob->actdef-1;
428
429         /* if mirror painting, find the other group */          
430         if(me->editflag & ME_EDIT_MIRROR_X) {
431                 wpaint_mirror_vgroup_ensure(ob, &vgroup_mirror);
432         }
433         
434         copy_wpaint_prev(wp, me->dvert, me->totvert);
435         
436         for(index=0; index<me->totface; index++) {
437                 if(indexar[index] && indexar[index]<=me->totface) {
438                         mface= me->mface + (indexar[index]-1);
439                         /* just so we can loop through the verts */
440                         faceverts[0]= mface->v1;
441                         faceverts[1]= mface->v2;
442                         faceverts[2]= mface->v3;
443                         faceverts[3]= mface->v4;
444                         for (i=0; i<3 || faceverts[i]; i++) {
445                                 if(!me->dvert[faceverts[i]].flag) {
446
447                                         if(use_vert_sel && !(me->mvert[faceverts[i]].flag & SELECT)) {
448                                                 continue;
449                                         }
450
451                                         dw= defvert_verify_index(me->dvert+faceverts[i], vgroup);
452                                         if(dw) {
453                                                 uw= defvert_verify_index(wp->wpaint_prev+faceverts[i], vgroup);
454                                                 uw->weight= dw->weight; /* set the undo weight */
455                                                 dw->weight= paintweight;
456                                                 
457                                                 if(me->editflag & ME_EDIT_MIRROR_X) {   /* x mirror painting */
458                                                         int j= mesh_get_x_mirror_vert(ob, faceverts[i]);
459                                                         if(j>=0) {
460                                                                 /* copy, not paint again */
461                                                                 if(vgroup_mirror != -1) {
462                                                                         dw= defvert_verify_index(me->dvert+j, vgroup_mirror);
463                                                                         uw= defvert_verify_index(wp->wpaint_prev+j, vgroup_mirror);
464                                                                 } else {
465                                                                         dw= defvert_verify_index(me->dvert+j, vgroup);
466                                                                         uw= defvert_verify_index(wp->wpaint_prev+j, vgroup);
467                                                                 }
468                                                                 uw->weight= dw->weight; /* set the undo weight */
469                                                                 dw->weight= paintweight;
470                                                         }
471                                                 }
472                                         }
473                                         (me->dvert+faceverts[i])->flag= 1;
474                                 }
475                         }
476                 }
477         }
478         
479         index=0;
480         while (index<me->totvert) {
481                 (me->dvert+index)->flag= 0;
482                 index++;
483         }
484         
485         MEM_freeN(indexar);
486         copy_wpaint_prev(wp, NULL, 0);
487
488         DAG_id_tag_update(&me->id, 0);
489 }
490
491 /* XXX: should be re-implemented as a vertex/weight paint 'color correct' operator
492  
493 void vpaint_dogamma(Scene *scene)
494 {
495         VPaint *vp= scene->toolsettings->vpaint;
496         Mesh *me;
497         Object *ob;
498         float igam, fac;
499         int a, temp;
500         unsigned char *cp, gamtab[256];
501
502         ob= OBACT;
503         me= get_mesh(ob);
504
505         if(!(ob->mode & OB_MODE_VERTEX_PAINT)) return;
506         if(me==0 || me->mcol==0 || me->totface==0) return;
507
508         igam= 1.0/vp->gamma;
509         for(a=0; a<256; a++) {
510                 
511                 fac= ((float)a)/255.0;
512                 fac= vp->mul*pow( fac, igam);
513                 
514                 temp= 255.9*fac;
515                 
516                 if(temp<=0) gamtab[a]= 0;
517                 else if(temp>=255) gamtab[a]= 255;
518                 else gamtab[a]= temp;
519         }
520
521         a= 4*me->totface;
522         cp= (unsigned char *)me->mcol;
523         while(a--) {
524                 
525                 cp[1]= gamtab[ cp[1] ];
526                 cp[2]= gamtab[ cp[2] ];
527                 cp[3]= gamtab[ cp[3] ];
528                 
529                 cp+= 4;
530         }
531 }
532  */
533
534 static unsigned int mcol_blend(unsigned int col1, unsigned int col2, int fac)
535 {
536         char *cp1, *cp2, *cp;
537         int mfac;
538         unsigned int col=0;
539         
540         if(fac==0) return col1;
541         if(fac>=255) return col2;
542
543         mfac= 255-fac;
544         
545         cp1= (char *)&col1;
546         cp2= (char *)&col2;
547         cp=  (char *)&col;
548         
549         cp[0]= 255;
550         cp[1]= (mfac*cp1[1]+fac*cp2[1])/255;
551         cp[2]= (mfac*cp1[2]+fac*cp2[2])/255;
552         cp[3]= (mfac*cp1[3]+fac*cp2[3])/255;
553         
554         return col;
555 }
556
557 static unsigned int mcol_add(unsigned int col1, unsigned int col2, int fac)
558 {
559         char *cp1, *cp2, *cp;
560         int temp;
561         unsigned int col=0;
562         
563         if(fac==0) return col1;
564         
565         cp1= (char *)&col1;
566         cp2= (char *)&col2;
567         cp=  (char *)&col;
568         
569         cp[0]= 255;
570         temp= cp1[1] + ((fac*cp2[1])/255);
571         if(temp>254) cp[1]= 255; else cp[1]= temp;
572         temp= cp1[2] + ((fac*cp2[2])/255);
573         if(temp>254) cp[2]= 255; else cp[2]= temp;
574         temp= cp1[3] + ((fac*cp2[3])/255);
575         if(temp>254) cp[3]= 255; else cp[3]= temp;
576         
577         return col;
578 }
579
580 static unsigned int mcol_sub(unsigned int col1, unsigned int col2, int fac)
581 {
582         char *cp1, *cp2, *cp;
583         int temp;
584         unsigned int col=0;
585         
586         if(fac==0) return col1;
587         
588         cp1= (char *)&col1;
589         cp2= (char *)&col2;
590         cp=  (char *)&col;
591         
592         cp[0]= 255;
593         temp= cp1[1] - ((fac*cp2[1])/255);
594         if(temp<0) cp[1]= 0; else cp[1]= temp;
595         temp= cp1[2] - ((fac*cp2[2])/255);
596         if(temp<0) cp[2]= 0; else cp[2]= temp;
597         temp= cp1[3] - ((fac*cp2[3])/255);
598         if(temp<0) cp[3]= 0; else cp[3]= temp;
599         
600         return col;
601 }
602
603 static unsigned int mcol_mul(unsigned int col1, unsigned int col2, int fac)
604 {
605         char *cp1, *cp2, *cp;
606         int mfac;
607         unsigned int col=0;
608         
609         if(fac==0) return col1;
610
611         mfac= 255-fac;
612         
613         cp1= (char *)&col1;
614         cp2= (char *)&col2;
615         cp=  (char *)&col;
616         
617         /* first mul, then blend the fac */
618         cp[0]= 255;
619         cp[1]= (mfac*cp1[1] + fac*((cp2[1]*cp1[1])/255)  )/255;
620         cp[2]= (mfac*cp1[2] + fac*((cp2[2]*cp1[2])/255)  )/255;
621         cp[3]= (mfac*cp1[3] + fac*((cp2[3]*cp1[3])/255)  )/255;
622
623         
624         return col;
625 }
626
627 static unsigned int mcol_lighten(unsigned int col1, unsigned int col2, int fac)
628 {
629         char *cp1, *cp2, *cp;
630         int mfac;
631         unsigned int col=0;
632         
633         if(fac==0) return col1;
634         if(fac>=255) return col2;
635
636         mfac= 255-fac;
637         
638         cp1= (char *)&col1;
639         cp2= (char *)&col2;
640         cp=  (char *)&col;
641         
642         /* See if are lighter, if so mix, else dont do anything.
643         if the paint col is darker then the original, then ignore */
644         if (cp1[1]+cp1[2]+cp1[3] > cp2[1]+cp2[2]+cp2[3])
645                 return col1;
646         
647         cp[0]= 255;
648         cp[1]= (mfac*cp1[1]+fac*cp2[1])/255;
649         cp[2]= (mfac*cp1[2]+fac*cp2[2])/255;
650         cp[3]= (mfac*cp1[3]+fac*cp2[3])/255;
651         
652         return col;
653 }
654
655 static unsigned int mcol_darken(unsigned int col1, unsigned int col2, int fac)
656 {
657         char *cp1, *cp2, *cp;
658         int mfac;
659         unsigned int col=0;
660         
661         if(fac==0) return col1;
662         if(fac>=255) return col2;
663
664         mfac= 255-fac;
665         
666         cp1= (char *)&col1;
667         cp2= (char *)&col2;
668         cp=  (char *)&col;
669         
670         /* See if were darker, if so mix, else dont do anything.
671         if the paint col is brighter then the original, then ignore */
672         if (cp1[1]+cp1[2]+cp1[3] < cp2[1]+cp2[2]+cp2[3])
673                 return col1;
674         
675         cp[0]= 255;
676         cp[1]= (mfac*cp1[1]+fac*cp2[1])/255;
677         cp[2]= (mfac*cp1[2]+fac*cp2[2])/255;
678         cp[3]= (mfac*cp1[3]+fac*cp2[3])/255;
679         return col;
680 }
681
682 static void vpaint_blend(VPaint *vp, unsigned int *col, unsigned int *colorig, unsigned int paintcol, int alpha)
683 {
684         Brush *brush = paint_brush(&vp->paint);
685
686         if(brush->vertexpaint_tool==VP_MIX || brush->vertexpaint_tool==VP_BLUR) *col= mcol_blend( *col, paintcol, alpha);
687         else if(brush->vertexpaint_tool==VP_ADD) *col= mcol_add( *col, paintcol, alpha);
688         else if(brush->vertexpaint_tool==VP_SUB) *col= mcol_sub( *col, paintcol, alpha);
689         else if(brush->vertexpaint_tool==VP_MUL) *col= mcol_mul( *col, paintcol, alpha);
690         else if(brush->vertexpaint_tool==VP_LIGHTEN) *col= mcol_lighten( *col, paintcol, alpha);
691         else if(brush->vertexpaint_tool==VP_DARKEN) *col= mcol_darken( *col, paintcol, alpha);
692         
693         /* if no spray, clip color adding with colorig & orig alpha */
694         if((vp->flag & VP_SPRAY)==0) {
695                 unsigned int testcol=0, a;
696                 char *cp, *ct, *co;
697                 
698                 alpha= (int)(255.0f*brush_alpha(brush));
699                 
700                 if(brush->vertexpaint_tool==VP_MIX || brush->vertexpaint_tool==VP_BLUR) testcol= mcol_blend( *colorig, paintcol, alpha);
701                 else if(brush->vertexpaint_tool==VP_ADD) testcol= mcol_add( *colorig, paintcol, alpha);
702                 else if(brush->vertexpaint_tool==VP_SUB) testcol= mcol_sub( *colorig, paintcol, alpha);
703                 else if(brush->vertexpaint_tool==VP_MUL) testcol= mcol_mul( *colorig, paintcol, alpha);
704                 else if(brush->vertexpaint_tool==VP_LIGHTEN)  testcol= mcol_lighten( *colorig, paintcol, alpha);
705                 else if(brush->vertexpaint_tool==VP_DARKEN)   testcol= mcol_darken( *colorig, paintcol, alpha);
706                 
707                 cp= (char *)col;
708                 ct= (char *)&testcol;
709                 co= (char *)colorig;
710                 
711                 for(a=0; a<4; a++) {
712                         if( ct[a]<co[a] ) {
713                                 if( cp[a]<ct[a] ) cp[a]= ct[a];
714                                 else if( cp[a]>co[a] ) cp[a]= co[a];
715                         }
716                         else {
717                                 if( cp[a]<co[a] ) cp[a]= co[a];
718                                 else if( cp[a]>ct[a] ) cp[a]= ct[a];
719                         }
720                 }
721         }
722 }
723
724
725 static int sample_backbuf_area(ViewContext *vc, int *indexar, int totface, int x, int y, float size)
726 {
727         struct ImBuf *ibuf;
728         int a, tot=0, index;
729         
730         /* brecht: disabled this because it obviously failes for
731            brushes with size > 64, why is this here? */
732         /*if(size>64.0) size= 64.0;*/
733         
734         ibuf= view3d_read_backbuf(vc, x-size, y-size, x+size, y+size);
735         if(ibuf) {
736                 unsigned int *rt= ibuf->rect;
737
738                 memset(indexar, 0, sizeof(int)*(totface+1));
739                 
740                 size= ibuf->x*ibuf->y;
741                 while(size--) {
742                                 
743                         if(*rt) {
744                                 index= WM_framebuffer_to_index(*rt);
745                                 if(index>0 && index<=totface)
746                                         indexar[index] = 1;
747                         }
748                 
749                         rt++;
750                 }
751                 
752                 for(a=1; a<=totface; a++) {
753                         if(indexar[a]) indexar[tot++]= a;
754                 }
755
756                 IMB_freeImBuf(ibuf);
757         }
758         
759         return tot;
760 }
761
762 static float calc_vp_alpha_dl(VPaint *vp, ViewContext *vc, float vpimat[][3], float *vert_nor, const float mval[2], float pressure)
763 {
764         Brush *brush = paint_brush(&vp->paint);
765         float fac, fac_2, size, dx, dy;
766         float alpha;
767         int vertco[2];
768         const int radius= brush_size(brush);
769
770         project_int_noclip(vc->ar, vert_nor, vertco);
771         dx= mval[0]-vertco[0];
772         dy= mval[1]-vertco[1];
773         
774         if (brush_use_size_pressure(brush))
775                 size = pressure * radius;
776         else
777                 size = radius;
778         
779         fac_2= dx*dx + dy*dy;
780         if(fac_2 > size*size) return 0.f;
781         fac = sqrtf(fac_2);
782         
783         alpha= brush_alpha(brush) * brush_curve_strength_clamp(brush, fac, size);
784         
785         if (brush_use_alpha_pressure(brush))
786                 alpha *= pressure;
787                 
788         if(vp->flag & VP_NORMALS) {
789                 float *no= vert_nor+3;
790                 
791                 /* transpose ! */
792                 fac= vpimat[2][0]*no[0]+vpimat[2][1]*no[1]+vpimat[2][2]*no[2];
793                 if(fac > 0.0f) {
794                         dx= vpimat[0][0]*no[0]+vpimat[0][1]*no[1]+vpimat[0][2]*no[2];
795                         dy= vpimat[1][0]*no[0]+vpimat[1][1]*no[1]+vpimat[1][2]*no[2];
796                         
797                         alpha*= fac/sqrtf(dx*dx + dy*dy + fac*fac);
798                 }
799                 else return 0.f;
800         }
801         
802         return alpha;
803 }
804
805 static void wpaint_blend(VPaint *wp, MDeformWeight *dw, MDeformWeight *uw, float alpha, float paintval, int flip, int multipaint)
806 {
807         Brush *brush = paint_brush(&wp->paint);
808         int tool = brush->vertexpaint_tool;
809         
810         if(dw==NULL || uw==NULL) return;
811         
812         if (flip) {
813                 switch(tool) {
814                         case VP_MIX:
815                                 paintval = 1.f - paintval; break;
816                         case VP_ADD:
817                                 tool= VP_SUB; break;
818                         case VP_SUB:
819                                 tool= VP_ADD; break;
820                         case VP_LIGHTEN:
821                                 tool= VP_DARKEN; break;
822                         case VP_DARKEN:
823                                 tool= VP_LIGHTEN; break;
824                 }
825         }
826         
827         if(tool==VP_MIX || tool==VP_BLUR)
828                 dw->weight = paintval*alpha + dw->weight*(1.0f-alpha);
829         else if(tool==VP_ADD)
830                 dw->weight += paintval*alpha;
831         else if(tool==VP_SUB) 
832                 dw->weight -= paintval*alpha;
833         else if(tool==VP_MUL) 
834                 /* first mul, then blend the fac */
835                 dw->weight = ((1.0f-alpha) + alpha*paintval)*dw->weight;
836         else if(tool==VP_LIGHTEN) {
837                 if (dw->weight < paintval)
838                         dw->weight = paintval*alpha + dw->weight*(1.0f-alpha);
839         } else if(tool==VP_DARKEN) {
840                 if (dw->weight > paintval)
841                         dw->weight = paintval*alpha + dw->weight*(1.0f-alpha);
842         }
843         /*  delay clamping until the end so multi-paint can function when the active group is at the limits */
844         if(multipaint == FALSE) {
845                 CLAMP(dw->weight, 0.0f, 1.0f);
846         }
847         
848         /* if no spray, clip result with orig weight & orig alpha */
849         if((wp->flag & VP_SPRAY)==0) {
850                 float testw=0.0f;
851                 
852                 alpha= brush_alpha(brush);
853                 if(tool==VP_MIX || tool==VP_BLUR)
854                         testw = paintval*alpha + uw->weight*(1.0f-alpha);
855                 else if(tool==VP_ADD)
856                         testw = uw->weight + paintval*alpha;
857                 else if(tool==VP_SUB) 
858                         testw = uw->weight - paintval*alpha;
859                 else if(tool==VP_MUL) 
860                         /* first mul, then blend the fac */
861                         testw = ((1.0f-alpha) + alpha*paintval)*uw->weight;
862                 else if(tool==VP_LIGHTEN) {
863                         if (uw->weight < paintval)
864                                 testw = paintval*alpha + uw->weight*(1.0f-alpha);
865                         else
866                                 testw = uw->weight;
867                 } else if(tool==VP_DARKEN) {
868                         if (uw->weight > paintval)
869                                 testw = paintval*alpha + uw->weight*(1.0f-alpha);
870                         else
871                                 testw = uw->weight;
872                 }
873
874                 if(multipaint == FALSE) {
875                         CLAMP(testw, 0.0f, 1.0f);
876                         if( testw<uw->weight ) {
877                                 if(dw->weight < testw) dw->weight= testw;
878                                 else if(dw->weight > uw->weight) dw->weight= uw->weight;
879                         }
880                         else {
881                                 if(dw->weight > testw) dw->weight= testw;
882                                 else if(dw->weight < uw->weight) dw->weight= uw->weight;
883                         }
884                 }
885         }
886         
887 }
888
889 /* ----------------------------------------------------- */
890
891
892 /* sets wp->weight to the closest weight value to vertex */
893 /* note: we cant sample frontbuf, weight colors are interpolated too unpredictable */
894 static int weight_sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
895 {
896         ViewContext vc;
897         Mesh *me;
898         short change= FALSE;
899
900         view3d_set_viewcontext(C, &vc);
901         me= get_mesh(vc.obact);
902
903         if (me && me->dvert && vc.v3d && vc.rv3d) {
904                 int index;
905
906                 view3d_operator_needs_opengl(C);
907
908                 index= view3d_sample_backbuf(&vc, event->mval[0], event->mval[1]);
909
910                 if(index && index<=me->totface) {
911                         DerivedMesh *dm= mesh_get_derived_final(vc.scene, vc.obact, CD_MASK_BAREMESH);
912
913                         if(dm->getVertCo==NULL) {
914                                 BKE_report(op->reports, RPT_WARNING, "The modifier used does not support deformed locations");
915                         }
916                         else {
917                                 MFace *mf= ((MFace *)me->mface) + index-1;
918                                 const int vgroup= vc.obact->actdef - 1;
919                                 ToolSettings *ts= vc.scene->toolsettings;
920                                 float mval_f[2];
921                                 int v_idx_best= -1;
922                                 int fidx;
923                                 float len_best= FLT_MAX;
924
925                                 mval_f[0]= (float)event->mval[0];
926                                 mval_f[1]= (float)event->mval[1];
927
928                                 fidx= mf->v4 ? 3:2;
929                                 do {
930                                         float co[3], sco[3], len;
931                                         const int v_idx= (*(&mf->v1 + fidx));
932                                         dm->getVertCo(dm, v_idx, co);
933                                         project_float_noclip(vc.ar, co, sco);
934                                         len= len_squared_v2v2(mval_f, sco);
935                                         if(len < len_best) {
936                                                 len_best= len;
937                                                 v_idx_best= v_idx;
938                                         }
939                                 } while (fidx--);
940
941                                 if(v_idx_best != -1) { /* should always be valid */
942                                         ts->vgroup_weight= defvert_find_weight(&me->dvert[v_idx_best], vgroup);
943                                         change= TRUE;
944                                 }
945                         }
946                         dm->release(dm);
947                 }
948         }
949
950         if(change) {
951                 /* not really correct since the brush didnt change, but redraws the toolbar */
952                 WM_main_add_notifier(NC_BRUSH|NA_EDITED, NULL); /* ts->wpaint->paint.brush */
953
954                 return OPERATOR_FINISHED;
955         }
956         else {
957                 return OPERATOR_CANCELLED;
958         }
959 }
960
961 void PAINT_OT_weight_sample(wmOperatorType *ot)
962 {
963         /* identifiers */
964         ot->name= "Weight Paint Sample Weight";
965         ot->idname= "PAINT_OT_weight_sample";
966
967         /* api callbacks */
968         ot->invoke= weight_sample_invoke;
969         ot->poll= weight_paint_mode_poll;
970
971         /* flags */
972         ot->flag= OPTYPE_UNDO;
973 }
974
975 /* samples cursor location, and gives menu with vertex groups to activate */
976 static EnumPropertyItem *weight_paint_sample_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), int *free)
977 {
978         if (C) {
979                 wmWindow *win= CTX_wm_window(C);
980                 if(win && win->eventstate) {
981                         ViewContext vc;
982                         Mesh *me;
983
984                         view3d_set_viewcontext(C, &vc);
985                         me= get_mesh(vc.obact);
986
987                         if (me && me->dvert && vc.v3d && vc.rv3d) {
988                                 int index;
989
990                                 view3d_operator_needs_opengl(C);
991
992                                 index= view3d_sample_backbuf(&vc, win->eventstate->x - vc.ar->winrct.xmin, win->eventstate->y - vc.ar->winrct.ymin);
993
994                                 if(index && index<=me->totface) {
995                                         const int totgroup= BLI_countlist(&vc.obact->defbase);
996                                         if(totgroup) {
997                                                 MFace *mf= ((MFace *)me->mface) + index-1;
998                                                 int fidx= mf->v4 ? 3:2;
999                                                 int *groups= MEM_callocN(totgroup*sizeof(int), "groups");
1000                                                 int found= FALSE;
1001
1002                                                 do {
1003                                                         MDeformVert *dvert= me->dvert + (*(&mf->v1 + fidx));
1004                                                         int i= dvert->totweight;
1005                                                         MDeformWeight *dw;
1006                                                         for(dw= dvert->dw; i > 0; dw++, i--) {
1007                                                                 groups[dw->def_nr]= TRUE;
1008                                                                 found= TRUE;
1009                                                         }
1010                                                 } while (fidx--);
1011
1012                                                 if(found==FALSE) {
1013                                                         MEM_freeN(groups);
1014                                                 }
1015                                                 else {
1016                                                         EnumPropertyItem *item= NULL, item_tmp= {0};
1017                                                         int totitem= 0;
1018                                                         int i= 0;
1019                                                         bDeformGroup *dg;
1020                                                         for(dg= vc.obact->defbase.first; dg && i<totgroup; i++, dg= dg->next) {
1021                                                                 if(groups[i]) {
1022                                                                         item_tmp.identifier= item_tmp.name= dg->name;
1023                                                                         item_tmp.value= i;
1024                                                                         RNA_enum_item_add(&item, &totitem, &item_tmp);
1025                                                                 }
1026                                                         }
1027
1028                                                         RNA_enum_item_end(&item, &totitem);
1029                                                         *free= 1;
1030
1031                                                         MEM_freeN(groups);
1032                                                         return item;
1033                                                 }
1034                                         }
1035                                 }
1036                         }
1037                 }
1038         }
1039
1040         return DummyRNA_NULL_items;
1041 }
1042
1043 static int weight_sample_group_exec(bContext *C, wmOperator *op)
1044 {
1045         int type= RNA_enum_get(op->ptr, "group");
1046         ViewContext vc;
1047         view3d_set_viewcontext(C, &vc);
1048
1049         vc.obact->actdef= type + 1;
1050
1051         DAG_id_tag_update(&vc.obact->id, OB_RECALC_DATA);
1052         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, vc.obact);
1053         return OPERATOR_FINISHED;
1054 }
1055
1056 /* TODO, we could make this a menu into OBJECT_OT_vertex_group_set_active rather than its own operator */
1057 void PAINT_OT_weight_sample_group(wmOperatorType *ot)
1058 {
1059         PropertyRNA *prop= NULL;
1060
1061         /* identifiers */
1062         ot->name= "Weight Paint Sample Group";
1063         ot->idname= "PAINT_OT_weight_sample_group";
1064
1065         /* api callbacks */
1066         ot->exec= weight_sample_group_exec;
1067         ot->invoke= WM_menu_invoke;
1068         ot->poll= weight_paint_mode_poll;
1069
1070         /* flags */
1071         ot->flag= OPTYPE_UNDO;
1072
1073         /* keyingset to use (dynamic enum) */
1074         prop= RNA_def_enum(ot->srna, "group", DummyRNA_DEFAULT_items, 0, "Keying Set", "The Keying Set to use");
1075         RNA_def_enum_funcs(prop, weight_paint_sample_enum_itemf);
1076         ot->prop= prop;
1077 }
1078
1079
1080 #if 0 /* UNUSED */
1081 static void do_weight_paint_auto_normalize(MDeformVert *dvert, 
1082                                            int paint_nr, char *map)
1083 {
1084 //      MDeformWeight *dw = dvert->dw;
1085         float sum=0.0f, fac=0.0f, paintw=0.0f;
1086         int i, tot=0;
1087
1088         if (!map)
1089                 return;
1090
1091         for (i=0; i<dvert->totweight; i++) {
1092                 if (dvert->dw[i].def_nr == paint_nr)
1093                         paintw = dvert->dw[i].weight;
1094
1095                 if (map[dvert->dw[i].def_nr]) {
1096                         tot += 1;
1097                         if (dvert->dw[i].def_nr != paint_nr)
1098                                 sum += dvert->dw[i].weight;
1099                 }
1100         }
1101         
1102         if (!tot || sum <= (1.0f - paintw))
1103                 return;
1104
1105         fac = sum / (1.0f - paintw);
1106         fac = fac==0.0f ? 1.0f : 1.0f / fac;
1107
1108         for (i=0; i<dvert->totweight; i++) {
1109                 if (map[dvert->dw[i].def_nr]) {
1110                         if (dvert->dw[i].def_nr != paint_nr)
1111                                 dvert->dw[i].weight *= fac;
1112                 }
1113         }
1114 }
1115 #endif
1116
1117 /* the active group should be involved in auto normalize */
1118 static void do_weight_paint_auto_normalize_all_groups(MDeformVert *dvert, char *map, char do_auto_normalize)
1119 {
1120 //      MDeformWeight *dw = dvert->dw;
1121         float sum=0.0f, fac=0.0f;
1122         int i, tot=0;
1123
1124         if (do_auto_normalize == FALSE)
1125                 return;
1126
1127         for (i=0; i<dvert->totweight; i++) {
1128                 if (map[dvert->dw[i].def_nr]) {
1129                         tot += 1;
1130                         sum += dvert->dw[i].weight;
1131                 }
1132         }
1133         
1134         if (!tot || sum == 1.0f)
1135                 return;
1136
1137         fac = sum;
1138         fac = fac==0.0f ? 1.0f : 1.0f / fac;
1139
1140         for (i=0; i<dvert->totweight; i++) {
1141                 if (map[dvert->dw[i].def_nr]) {
1142                         dvert->dw[i].weight *= fac;
1143                 }
1144         }
1145 }
1146
1147 /*
1148 See if the current deform vertex has a locked group
1149 */
1150 static char has_locked_group(MDeformVert *dvert, const char *lock_flags)
1151 {
1152         int i;
1153         for(i = 0; i < dvert->totweight; i++) {
1154                 if(lock_flags[dvert->dw[i].def_nr] && dvert->dw[i].weight > 0.0f) {
1155                         return TRUE;
1156                 }
1157         }
1158         return FALSE;
1159 }
1160 /* 
1161  * gen_lck_flags gets the status of "flag" for each bDeformGroup
1162  *in ob->defbase and returns an array containing them
1163  */
1164 static char *gen_lock_flags(Object* ob, int defbase_tot)
1165 {
1166         char is_locked = FALSE;
1167         int i;
1168         //int defbase_tot = BLI_countlist(&ob->defbase);
1169         char *lock_flags = MEM_mallocN(defbase_tot*sizeof(char), "defflags");
1170         bDeformGroup *defgroup;
1171
1172         for(i = 0, defgroup = ob->defbase.first; i < defbase_tot && defgroup; defgroup = defgroup->next, i++) {
1173                 lock_flags[i] = ((defgroup->flag & DG_LOCK_WEIGHT) != 0);
1174                 is_locked |= lock_flags[i];
1175         }
1176         if(is_locked){
1177                 return lock_flags;
1178         }
1179         // don't forget to free it if it is unneeded
1180         MEM_freeN(lock_flags);
1181         return NULL;
1182 }
1183
1184 static int has_locked_group_selected(int defbase_tot, char *defbase_sel, char *lock_flags) {
1185         int i;
1186         for(i = 0; i < defbase_tot; i++) {
1187                 if(defbase_sel[i] && lock_flags[i]) {
1188                         return TRUE;
1189                 }
1190         }
1191         return FALSE;
1192 }
1193
1194
1195 #if 0 /* UNUSED */
1196 static int has_unselected_unlocked_bone_group(int defbase_tot, char *defbase_sel, int selected, char *lock_flags, char *vgroup_validmap) {
1197         int i;
1198         if(defbase_tot == selected) {
1199                 return FALSE;
1200         }
1201         for(i = 0; i < defbase_tot; i++) {
1202                 if(vgroup_validmap[i] && !defbase_sel[i] && !lock_flags[i]) {
1203                         return TRUE;
1204                 }
1205         }
1206         return FALSE;
1207 }
1208 #endif
1209
1210
1211 static void multipaint_selection(MDeformVert *dvert, float change, char *defbase_sel, int defbase_tot) {
1212         int i;
1213         MDeformWeight *dw;
1214         float val;
1215         // make sure they are all at most 1 after the change
1216         for(i = 0; i < defbase_tot; i++) {
1217                 if(defbase_sel[i]) {
1218                         dw = defvert_find_index(dvert, i);
1219                         if(dw && dw->weight) {
1220                                 val = dw->weight * change;
1221                                 if(val > 1) {
1222                                         /*  TODO: when the change is reduced, you need to recheck the earlier values to make sure they are not 0 (precision error) */
1223                                         change = 1.0f/dw->weight;
1224                                 }
1225                                 // the value should never reach zero while multi-painting if it was nonzero beforehand
1226                                 if(val <= 0) {
1227                                         return;
1228                                 }
1229                         }
1230                 }
1231         }
1232         // apply the valid change
1233         for(i = 0; i < defbase_tot; i++) {
1234                 if(defbase_sel[i]) {
1235                         dw = defvert_find_index(dvert, i);
1236                         if(dw && dw->weight) {
1237                                 dw->weight = dw->weight * change;
1238                         }
1239                 }
1240         }
1241 }
1242
1243 // move all change onto valid, unchanged groups.  If there is change left over, then return it.
1244 // assumes there are valid groups to shift weight onto
1245 static float redistribute_change(MDeformVert *ndv, char *change_status, int changeme, int changeto, const char *vgroup_validmap, float totchange, float total_valid, char do_auto_normalize) {
1246         float was_change;
1247         float change;
1248         float oldval;
1249         MDeformWeight *ndw;
1250         int i;
1251         do {
1252                 // assume there is no change until you see one
1253                 was_change = FALSE;
1254                 // change each group by the same amount each time
1255                 change = totchange/total_valid;
1256                 for(i = 0; i < ndv->totweight && total_valid && totchange; i++) {
1257                         ndw = (ndv->dw+i);
1258                         // change only the groups with a valid status
1259                         if(change_status[ndw->def_nr] == changeme) {
1260                                 oldval = ndw->weight;
1261                                 // if auto normalize is active, don't worry about upper bounds
1262                                 if(do_auto_normalize == FALSE && ndw->weight + change > 1) {
1263                                         totchange -= 1-ndw->weight;
1264                                         ndw->weight = 1;
1265                                         // stop the changes to this group
1266                                         change_status[ndw->def_nr] = changeto;
1267                                         total_valid--;
1268                                 } else if(ndw->weight + change < 0) { // check the lower bound
1269                                         totchange -= ndw->weight;
1270                                         ndw->weight = 0;
1271                                         change_status[ndw->def_nr] = changeto;
1272                                         total_valid--;
1273                                 } else {// a perfectly valid change occurred to ndw->weight
1274                                         totchange -= change;
1275                                         ndw->weight += change;
1276                                 }
1277                                 // see if there was a change
1278                                 if(oldval != ndw->weight) {
1279                                         was_change = TRUE;
1280                                 }
1281                         }
1282                 }
1283         // don't go again if there was no change, if there is no valid group, or there is no change left
1284         }while(was_change && total_valid && totchange);
1285         // left overs
1286         return totchange;
1287 }
1288
1289 // observe the changes made to the weights of groups.
1290 // make sure all locked groups on the vertex have the same deformation
1291 // by moving the changes made to groups onto other unlocked groups
1292 static void enforce_locks(MDeformVert *odv, MDeformVert *ndv, int defbase_tot,
1293                           const char *lock_flags, const char *vgroup_validmap, char do_auto_normalize)
1294 {
1295         float totchange = 0.0f;
1296         float totchange_allowed = 0.0f;
1297         float left_over;
1298
1299         int total_valid = 0;
1300         int total_changed = 0;
1301         int i;
1302         MDeformWeight *ndw;
1303         MDeformWeight *odw;
1304         MDeformWeight *ndw2;
1305         MDeformWeight *odw2;
1306         int designatedw = -1;
1307         int designatedw_changed = FALSE;
1308         float storedw;
1309         char *change_status;
1310         char new_weight_has_zero = FALSE;
1311
1312         if(!lock_flags || !has_locked_group(ndv, lock_flags)) {
1313                 return;
1314         }
1315         // record if a group was changed, unlocked and not changed, or locked
1316         change_status = MEM_callocN(sizeof(char)*defbase_tot, "unlocked_unchanged");
1317
1318         for(i = 0; i < defbase_tot; i++) {
1319                 ndw = defvert_find_index(ndv, i);
1320                 odw = defvert_find_index(odv, i);
1321                 // the weights are zero, so we can assume a lot
1322                 if(!ndw || !odw) {
1323                         if (!lock_flags[i] && vgroup_validmap[i]){
1324                                 defvert_verify_index(odv, i);
1325                                 defvert_verify_index(ndv, i);
1326                                 total_valid++;
1327                                 change_status[i] = 1; // can be altered while redistributing
1328                         }
1329                         continue;
1330                 }
1331                 // locked groups should not be changed
1332                 if(lock_flags[i]) {
1333                         ndw->weight = odw->weight;
1334                 }
1335                 else if(ndw->weight != odw->weight) { // changed groups are handled here
1336                         totchange += ndw->weight - odw->weight;
1337                         change_status[i] = 2; // was altered already
1338                         total_changed++;
1339                         if(ndw->weight == 0) {
1340                                 new_weight_has_zero = TRUE;
1341                         }
1342                         else if(designatedw == -1){
1343                                 designatedw = i;
1344                         }
1345                 } // unchanged, unlocked bone groups are handled here
1346                 else if (vgroup_validmap[i]){
1347                         totchange_allowed += ndw->weight;
1348                         total_valid++;
1349                         change_status[i] = 1; // can be altered while redistributing
1350                 }
1351         }
1352         // if there was any change, redistribute it
1353         if(total_changed) {
1354                 // auto normalize will allow weights to temporarily go above 1 in redistribution
1355                 if(vgroup_validmap && total_changed < 0 && total_valid) {
1356                         totchange_allowed = total_valid;
1357                 }
1358                 // there needs to be change allowed, or you should not bother
1359                 if(totchange_allowed) {
1360                         // the way you modify the unlocked+unchanged groups is different depending
1361                         // on whether or not you are painting the weight(s) up or down
1362                         if(totchange < 0) {
1363                                 totchange_allowed = total_valid - totchange_allowed;
1364                         }
1365                         else {
1366                                 totchange_allowed *= -1;
1367                         }
1368                         left_over = 0;
1369                         if(fabsf(totchange_allowed) < fabsf(totchange)) {
1370                                 // this amount goes back onto the changed, unlocked weights
1371                                 left_over = fabsf(fabsf(totchange) - fabsf(totchange_allowed));
1372                                 if(totchange > 0) {
1373                                         left_over *= -1;
1374                                 }
1375                         }
1376                         else {
1377                                 // all of the change will be permitted
1378                                 totchange_allowed = -totchange;
1379                         }
1380                         // move the weight evenly between the allowed groups, move excess back onto the used groups based on the change
1381                         totchange_allowed = redistribute_change(ndv, change_status, 1, -1, vgroup_validmap, totchange_allowed, total_valid, do_auto_normalize);
1382                         left_over += totchange_allowed;
1383                         if(left_over) {
1384                                 // more than one nonzero weights were changed with the same ratio, so keep them changed that way!
1385                                 if(total_changed > 1 && !new_weight_has_zero && designatedw >= 0) {
1386                                         // this dw is special, it is used as a base to determine how to change the others
1387                                         ndw = defvert_find_index(ndv, designatedw);
1388                                         odw = defvert_find_index(odv, designatedw);
1389                                         storedw = ndw->weight;
1390                                         for(i = 0; i < ndv->totweight; i++) {
1391                                                 if(change_status[ndw->def_nr] == 2) {
1392                                                         odw2 = (odv->dw+i);
1393                                                         ndw2 = (ndv->dw+i);
1394                                                         if(!designatedw_changed) {
1395                                                                 ndw->weight = (totchange_allowed + odw->weight + odw2->weight)/(1 + ndw2->weight/ndw->weight);
1396                                                                 designatedw_changed = TRUE;
1397                                                         }
1398                                                         ndw2->weight = ndw->weight * ndw2->weight / storedw;
1399                                                 }
1400                                         }
1401                                 }
1402                                 // a weight was changed to zero, only one weight was changed, or designatedw is still -1
1403                                 // put weight back as evenly as possible
1404                                 else {
1405                                         redistribute_change(ndv, change_status, 2, -2, vgroup_validmap, left_over, total_changed, do_auto_normalize);
1406                                 }
1407                         }
1408                 }
1409                 else {
1410                         // reset the weights
1411                         for(i = 0; i < ndv->totweight; i++) {
1412                                 ndv->dw[i].weight = odv->dw[i].weight;
1413                         }
1414                 }
1415         }
1416
1417         MEM_freeN(change_status);
1418 }
1419
1420 // multi-paint's initial, potential change is computed here based on the user's stroke
1421 static float get_mp_change(MDeformVert *odv, char *defbase_sel, float brush_change) {
1422         float selwsum = 0.0f;
1423         int i;
1424         MDeformWeight *dw;
1425         for(i=0; i < odv->totweight; i++) {
1426                 if(defbase_sel[(dw= &odv->dw[i])->def_nr]) {
1427                         selwsum += dw->weight;
1428                 }
1429         }
1430         if(selwsum && selwsum+brush_change > 0) {
1431                 return (selwsum+brush_change)/selwsum;
1432         }
1433         return 0.0f;
1434 }
1435
1436 // change the weights back to the wv's weights
1437 // it assumes you already have the correct pointer index
1438 static void reset_to_prev(MDeformVert *wv, MDeformVert *dv) {
1439         int i;
1440         MDeformWeight *d;
1441         MDeformWeight *w;
1442         for(i = 0; i < dv->totweight; i++) {
1443                 d= &dv->dw[i];
1444                 w= defvert_find_index(wv, d->def_nr);
1445                 /* if there was no w when there is a d, then the old weight was 0 */
1446                 d->weight = w ? w->weight : 0.0f;
1447         }
1448 }
1449
1450 static void clamp_weights(MDeformVert *dvert) {
1451         int i;
1452         for (i = 0; i < dvert->totweight; i++) {
1453                 CLAMP((dvert->dw+i)->weight, 0.0f, 1.0f);
1454         }
1455 }
1456
1457 /* struct to avoid passing many args each call to do_weight_paint_vertex()
1458  * this _could_ be made a part of the operators 'WPaintData' struct, or at
1459  * least a member, but for now keep its own struct, initialized on every
1460  * paint stroke update - campbell */
1461 typedef struct WeightPaintInfo {
1462
1463         int defbase_tot;
1464
1465         /* both must add up to 'defbase_tot' */
1466         int defbase_tot_sel;
1467         int defbase_tot_unsel;
1468
1469         int vgroup_mirror; /* mirror group or -1 */
1470
1471         char *lock_flags;  /* boolean array for locked bones,
1472                                                 * length of defbase_tot */
1473         char *defbase_sel; /* boolean array for selected bones,
1474                                                 * length of defbase_tot */
1475
1476         char *vgroup_validmap; /* same as WeightPaintData.vgroup_validmap,
1477                                 * only added here for convenience */
1478
1479         char do_flip;
1480         char do_multipaint;
1481         char do_auto_normalize;
1482 } WeightPaintInfo;
1483
1484 /* fresh start to make multi-paint and locking modular */
1485 /* returns TRUE if it thinks you need to reset the weights due to
1486  * normalizing while multi-painting */
1487 static int apply_mp_locks_normalize(Mesh *me, const WeightPaintInfo *wpi,
1488                                     const int index,
1489                                     MDeformWeight *dw, MDeformWeight *tdw,
1490                                     float change, float oldChange,
1491                                     float oldw, float neww)
1492 {
1493         MDeformVert *dv= me->dvert+index;
1494         MDeformVert dv_test= {NULL};
1495
1496         dv_test.dw= MEM_dupallocN(dv->dw);
1497         dv_test.flag = dv->flag;
1498         dv_test.totweight = dv->totweight;
1499         /* do not multi-paint if a locked group is selected or the active group is locked
1500          * !lock_flags[dw->def_nr] helps if nothing is selected, but active group is locked */
1501         if((wpi->lock_flags == NULL) || (wpi->lock_flags[dw->def_nr] == FALSE && has_locked_group_selected(wpi->defbase_tot, wpi->defbase_sel, wpi->lock_flags) == FALSE)) {
1502                 if(wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1503                         if(change && change!=1) {
1504                                 multipaint_selection(dv, change, wpi->defbase_sel, wpi->defbase_tot);
1505                         }
1506                 }
1507                 else { /* this lets users paint normally, but don't let them paint locked groups */
1508                         dw->weight = neww;
1509                 }
1510         }
1511         clamp_weights(dv);
1512
1513         enforce_locks(&dv_test, dv, wpi->defbase_tot, wpi->lock_flags, wpi->vgroup_validmap, wpi->do_auto_normalize);
1514
1515         do_weight_paint_auto_normalize_all_groups(dv, wpi->vgroup_validmap, wpi->do_auto_normalize);
1516
1517         if(oldChange && wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1518                 if(tdw->weight != oldw) {
1519                         if(neww > oldw) {
1520                                 if(tdw->weight <= oldw) {
1521                                         MEM_freeN(dv_test.dw);
1522                                         return TRUE;
1523                                 }
1524                         }
1525                         else {
1526                                 if(tdw->weight >= oldw) {
1527                                         MEM_freeN(dv_test.dw);
1528                                         return TRUE;
1529                                 }
1530                         }
1531                 }
1532         }
1533         MEM_freeN(dv_test.dw);
1534         return FALSE;
1535 }
1536
1537 /* within the current dvert index, get the dw that is selected and has a weight
1538  * above 0, this helps multi-paint */
1539 static int get_first_selected_nonzero_weight(MDeformVert *dvert, char *defbase_sel) {
1540         int i;
1541         MDeformWeight *dw;
1542         for(i=0; i< dvert->totweight; i++) {
1543                 dw = &dvert->dw[i];
1544                 if(defbase_sel[dw->def_nr] && dw->weight > 0) {
1545                         return i;
1546                 }
1547         }
1548         return -1;
1549 }
1550
1551
1552 static char *wpaint_make_validmap(Object *ob);
1553
1554
1555 static void do_weight_paint_vertex( /* vars which remain the same for every vert */
1556                                    VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1557                                     /* vars which change on each stroke */
1558                                    int index, float alpha, float paintweight
1559                                    )
1560 {
1561         Mesh *me= ob->data;
1562         
1563         MDeformWeight *dw, *uw;
1564         int vgroup= ob->actdef-1;
1565
1566         if(wp->flag & VP_ONLYVGROUP) {
1567                 dw= defvert_find_index(me->dvert+index, vgroup);
1568                 uw= defvert_find_index(wp->wpaint_prev+index, vgroup);
1569         }
1570         else {
1571                 dw= defvert_verify_index(me->dvert+index, vgroup);
1572                 uw= defvert_verify_index(wp->wpaint_prev+index, vgroup);
1573         }
1574         if(dw==NULL || uw==NULL)
1575                 return;
1576
1577         /* TODO: De-duplicate the simple weight paint - jason */
1578         /* ... or not, since its <10 SLOC - campbell */
1579
1580         /* If there are no locks or multipaint,
1581          * then there is no need to run the more complicated checks */
1582         if((wpi->do_multipaint == FALSE || wpi->defbase_tot_sel <= 1) && (wpi->lock_flags == NULL || has_locked_group(&me->dvert[index], wpi->lock_flags) == FALSE)) {
1583                 wpaint_blend(wp, dw, uw, alpha, paintweight, wpi->do_flip, FALSE);
1584                 do_weight_paint_auto_normalize_all_groups(me->dvert+index, wpi->vgroup_validmap, wpi->do_auto_normalize);
1585
1586                 if(me->editflag & ME_EDIT_MIRROR_X) {   /* x mirror painting */
1587                         int j= mesh_get_x_mirror_vert(ob, index);
1588                         if(j>=0) {
1589                                 /* copy, not paint again */
1590                                 uw= defvert_verify_index(me->dvert+j, (wpi->vgroup_mirror != -1) ? wpi->vgroup_mirror : vgroup);
1591                                         
1592                                 uw->weight= dw->weight;
1593
1594                                 do_weight_paint_auto_normalize_all_groups(me->dvert+j, wpi->vgroup_validmap, wpi->do_auto_normalize);
1595                         }
1596                 }
1597         }
1598         else {
1599                 /* use locks and/or multipaint */
1600                 float oldw;
1601                 float neww;
1602                 float testw=0;
1603                 float change = 0;
1604                 float oldChange = 0;
1605                 int i;
1606                 MDeformWeight *tdw = NULL, *tuw;
1607                 MDeformVert dv= {NULL};
1608
1609                 oldw = dw->weight;
1610                 wpaint_blend(wp, dw, uw, alpha, paintweight, wpi->do_flip, wpi->do_multipaint && wpi->defbase_tot_sel >1);
1611                 neww = dw->weight;
1612                 dw->weight = oldw;
1613                 
1614                 // setup multi-paint
1615                 if(wpi->defbase_tot_sel > 1 && wpi->do_multipaint) {
1616                         dv.dw= MEM_dupallocN((me->dvert+index)->dw);
1617                         dv.flag = me->dvert[index].flag;
1618                         dv.totweight = (me->dvert+index)->totweight;
1619                         tdw = dw;
1620                         tuw = uw;
1621                         change = get_mp_change(wp->wpaint_prev+index, wpi->defbase_sel, neww - oldw);
1622                         if(change) {
1623                                 if(!tdw->weight) {
1624                                         i = get_first_selected_nonzero_weight(me->dvert+index, wpi->defbase_sel);
1625                                         if(i>=0) {
1626                                                 tdw = &(me->dvert[index].dw[i]);
1627                                                 tuw = defvert_verify_index(wp->wpaint_prev+index, tdw->def_nr);
1628                                         }
1629                                         else {
1630                                                 change = 0;
1631                                         }
1632                                 }
1633                                 if(change && tuw->weight && tuw->weight * change) {
1634                                         if(tdw->weight != tuw->weight) {
1635                                                 oldChange = tdw->weight/tuw->weight;
1636                                                 testw = tuw->weight*change;
1637                                                 if( testw > tuw->weight ) {
1638                                                         if(change > oldChange) {
1639                                                                 /* reset the weights and use the new change */
1640                                                                 reset_to_prev(wp->wpaint_prev+index, me->dvert+index);
1641                                                         }
1642                                                         else {
1643                                                                 /* the old change was more significant, so set
1644                                                                  * the change to 0 so that it will not do another multi-paint */
1645                                                                 change = 0;
1646                                                         }
1647                                                 }
1648                                                 else {
1649                                                         if(change < oldChange) {
1650                                                                 reset_to_prev(wp->wpaint_prev+index, me->dvert+index);
1651                                                         }
1652                                                         else {
1653                                                                 change = 0;
1654                                                         }
1655                                                 }
1656                                         }
1657                                 }
1658                                 else {
1659                                         change = 0;
1660                                 }
1661                         }
1662                 }
1663                 
1664                 if(apply_mp_locks_normalize(me, wpi, index, dw, tdw, change, oldChange, oldw, neww)) {
1665                         reset_to_prev(&dv, me->dvert+index);
1666                         change = 0;
1667                         oldChange = 0;
1668                 }
1669                 if(dv.dw) {
1670                         MEM_freeN(dv.dw);
1671                 }
1672                 /* dvert may have been altered greatly */
1673                 dw = defvert_find_index(me->dvert+index, vgroup);
1674
1675                 if(me->editflag & ME_EDIT_MIRROR_X) {   /* x mirror painting */
1676                         int j= mesh_get_x_mirror_vert(ob, index);
1677                         if(j>=0) {
1678                                 /* copy, not paint again */
1679                                 uw= defvert_verify_index(me->dvert+j, (wpi->vgroup_mirror != -1) ? wpi->vgroup_mirror : vgroup);
1680                                 
1681                                 //uw->weight= dw->weight;
1682                                 
1683                                 apply_mp_locks_normalize(me, wpi, j, uw, tdw, change, oldChange, oldw, neww);
1684                         }
1685                 }
1686         }
1687 }
1688
1689
1690 /* *************** set wpaint operator ****************** */
1691
1692 static int set_wpaint(bContext *C, wmOperator *UNUSED(op))              /* toggle */
1693 {               
1694         Object *ob= CTX_data_active_object(C);
1695         Scene *scene= CTX_data_scene(C);
1696         VPaint *wp= scene->toolsettings->wpaint;
1697         Mesh *me;
1698         
1699         me= get_mesh(ob);
1700         if(ob->id.lib || me==NULL) return OPERATOR_PASS_THROUGH;
1701         
1702         if(ob->mode & OB_MODE_WEIGHT_PAINT) ob->mode &= ~OB_MODE_WEIGHT_PAINT;
1703         else ob->mode |= OB_MODE_WEIGHT_PAINT;
1704         
1705         
1706         /* Weightpaint works by overriding colors in mesh,
1707                 * so need to make sure we recalc on enter and
1708                 * exit (exit needs doing regardless because we
1709                                 * should redeform).
1710                 */
1711         DAG_id_tag_update(&me->id, 0);
1712         
1713         if(ob->mode & OB_MODE_WEIGHT_PAINT) {
1714                 Object *par;
1715                 
1716                 if(wp==NULL)
1717                         wp= scene->toolsettings->wpaint= new_vpaint(1);
1718
1719                 paint_init(&wp->paint, PAINT_CURSOR_WEIGHT_PAINT);
1720                 paint_cursor_start(C, weight_paint_poll);
1721                 
1722                 mesh_octree_table(ob, NULL, NULL, 's');
1723                 
1724                 /* verify if active weight group is also active bone */
1725                 par= modifiers_isDeformedByArmature(ob);
1726                 if(par && (par->mode & OB_MODE_POSE)) {
1727                         bArmature *arm= par->data;
1728
1729                         if(arm->act_bone)
1730                                 ED_vgroup_select_by_name(ob, arm->act_bone->name);
1731                 }
1732         }
1733         else {
1734                 mesh_octree_table(NULL, NULL, NULL, 'e');
1735                 mesh_mirrtopo_table(NULL, 'e');
1736         }
1737         
1738         WM_event_add_notifier(C, NC_SCENE|ND_MODE, scene);
1739         
1740         return OPERATOR_FINISHED;
1741 }
1742
1743 /* for switching to/from mode */
1744 static int paint_poll_test(bContext *C)
1745 {
1746         if(CTX_data_edit_object(C))
1747                 return 0;
1748         if(CTX_data_active_object(C)==NULL)
1749                 return 0;
1750         return 1;
1751 }
1752
1753 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
1754 {
1755         
1756         /* identifiers */
1757         ot->name= "Weight Paint Mode";
1758         ot->idname= "PAINT_OT_weight_paint_toggle";
1759         
1760         /* api callbacks */
1761         ot->exec= set_wpaint;
1762         ot->poll= paint_poll_test;
1763         
1764         /* flags */
1765         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1766         
1767 }
1768
1769 /* ************ weight paint operator ********** */
1770
1771 struct WPaintData {
1772         ViewContext vc;
1773         int *indexar;
1774         int vgroup_mirror;
1775         float *vertexcosnos;
1776         float wpimat[3][3];
1777         
1778         /*variables for auto normalize*/
1779         int auto_normalize;
1780         char *vgroup_validmap; /*stores if vgroups tie to deforming bones or not*/
1781         char *lock_flags;
1782         int defbase_tot;
1783 };
1784
1785 static char *wpaint_make_validmap(Object *ob)
1786 {
1787         bDeformGroup *dg;
1788         ModifierData *md;
1789         char *vgroup_validmap;
1790         GHash *gh = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "wpaint_make_validmap gh");
1791         int i = 0, step1=1;
1792
1793         /*add all names to a hash table*/
1794         for (dg=ob->defbase.first, i=0; dg; dg=dg->next, i++) {
1795                 BLI_ghash_insert(gh, dg->name, NULL);
1796         }
1797
1798         if (!i)
1799                 return NULL;
1800
1801         vgroup_validmap= MEM_callocN(i, "wpaint valid map");
1802
1803         /*now loop through the armature modifiers and identify deform bones*/
1804         for (md = ob->modifiers.first; md; md= !md->next && step1 ? (step1=0), modifiers_getVirtualModifierList(ob) : md->next) {
1805                 if (!(md->mode & (eModifierMode_Realtime|eModifierMode_Virtual)))
1806                         continue;
1807
1808                 if (md->type == eModifierType_Armature) 
1809                 {
1810                         ArmatureModifierData *amd= (ArmatureModifierData*) md;
1811
1812                         if(amd->object && amd->object->pose) {
1813                                 bPose *pose= amd->object->pose;
1814                                 bPoseChannel *chan;
1815                                 
1816                                 for (chan=pose->chanbase.first; chan; chan=chan->next) {
1817                                         if (chan->bone->flag & BONE_NO_DEFORM)
1818                                                 continue;
1819
1820                                         if (BLI_ghash_haskey(gh, chan->name)) {
1821                                                 BLI_ghash_remove(gh, chan->name, NULL, NULL);
1822                                                 BLI_ghash_insert(gh, chan->name, SET_INT_IN_POINTER(1));
1823                                         }
1824                                 }
1825                         }
1826                 }
1827         }
1828         
1829         /*add all names to a hash table*/
1830         for (dg=ob->defbase.first, i=0; dg; dg=dg->next, i++) {
1831                 if (BLI_ghash_lookup(gh, dg->name) != NULL) {
1832                         vgroup_validmap[i] = TRUE;
1833                 }
1834         }
1835
1836         BLI_ghash_free(gh, NULL, NULL);
1837
1838         return vgroup_validmap;
1839 }
1840
1841 static int wpaint_stroke_test_start(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1842 {
1843         Scene *scene= CTX_data_scene(C);
1844         struct PaintStroke *stroke = op->customdata;
1845         ToolSettings *ts= CTX_data_tool_settings(C);
1846         VPaint *wp= ts->wpaint;
1847         Object *ob= CTX_data_active_object(C);
1848         struct WPaintData *wpd;
1849         Mesh *me;
1850         float mat[4][4], imat[4][4];
1851         
1852         if(scene->obedit) return OPERATOR_CANCELLED;
1853         
1854         me= get_mesh(ob);
1855         if(me==NULL || me->totface==0) return OPERATOR_PASS_THROUGH;
1856         
1857         /* if nothing was added yet, we make dverts and a vertex deform group */
1858         if (!me->dvert) {
1859                 ED_vgroup_data_create(&me->id);
1860                 WM_event_add_notifier(C, NC_GEOM|ND_DATA, me);
1861         }
1862         
1863         /* make mode data storage */
1864         wpd= MEM_callocN(sizeof(struct WPaintData), "WPaintData");
1865         paint_stroke_set_mode_data(stroke, wpd);
1866         view3d_set_viewcontext(C, &wpd->vc);
1867         wpd->vgroup_mirror= -1;
1868         
1869         /*set up auto-normalize, and generate map for detecting which
1870           vgroups affect deform bones*/
1871         wpd->auto_normalize = ts->auto_normalize;
1872         wpd->defbase_tot = BLI_countlist(&ob->defbase);
1873         wpd->lock_flags = gen_lock_flags(ob, wpd->defbase_tot);
1874         if (wpd->auto_normalize || ts->multipaint || wpd->lock_flags)
1875                 wpd->vgroup_validmap = wpaint_make_validmap(ob);
1876         
1877         //      if(qual & LR_CTRLKEY) {
1878         //              sample_wpaint(scene, ar, v3d, 0);
1879         //              return;
1880         //      }
1881         //      if(qual & LR_SHIFTKEY) {
1882         //              sample_wpaint(scene, ar, v3d, 1);
1883         //              return;
1884         //      }
1885         
1886         /* ALLOCATIONS! no return after this line */
1887         /* painting on subsurfs should give correct points too, this returns me->totvert amount */
1888         wpd->vertexcosnos= mesh_get_mapped_verts_nors(scene, ob);
1889         wpd->indexar= get_indexarray(me);
1890         copy_wpaint_prev(wp, me->dvert, me->totvert);
1891         
1892         /* this happens on a Bone select, when no vgroup existed yet */
1893         if(ob->actdef<=0) {
1894                 Object *modob;
1895                 if((modob = modifiers_isDeformedByArmature(ob))) {
1896                         Bone *actbone= ((bArmature *)modob->data)->act_bone;
1897                         if(actbone) {
1898                                 bPoseChannel *pchan= get_pose_channel(modob->pose, actbone->name);
1899
1900                                 if(pchan) {
1901                                         bDeformGroup *dg= defgroup_find_name(ob, pchan->name);
1902                                         if(dg==NULL)
1903                                                 dg= ED_vgroup_add_name(ob, pchan->name);        /* sets actdef */
1904                                         else
1905                                                 ob->actdef= 1 + defgroup_find_index(ob, dg);
1906                                 }
1907                         }
1908                 }
1909         }
1910         if(ob->defbase.first==NULL) {
1911                 ED_vgroup_add(ob);
1912         }
1913         
1914         //      if(ob->lay & v3d->lay); else error("Active object is not in this layer");
1915         
1916         /* imat for normals */
1917         mul_m4_m4m4(mat, ob->obmat, wpd->vc.rv3d->viewmat);
1918         invert_m4_m4(imat, mat);
1919         copy_m3_m4(wpd->wpimat, imat);
1920         
1921         /* if mirror painting, find the other group */
1922         if(me->editflag & ME_EDIT_MIRROR_X) {
1923                 wpaint_mirror_vgroup_ensure(ob, &wpd->vgroup_mirror);
1924         }
1925         
1926         return 1;
1927 }
1928
1929 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
1930 {
1931         ToolSettings *ts= CTX_data_tool_settings(C);
1932         VPaint *wp= ts->wpaint;
1933         Brush *brush = paint_brush(&wp->paint);
1934         struct WPaintData *wpd= paint_stroke_mode_data(stroke);
1935         ViewContext *vc;
1936         Object *ob;
1937         Mesh *me;
1938         float mat[4][4];
1939         float paintweight;
1940         int *indexar;
1941         int totindex, index, totw;
1942         float alpha;
1943         float mval[2], pressure;
1944         int use_vert_sel;
1945
1946         /* intentionally dont initialize as NULL, make sure we initialize all members below */
1947         WeightPaintInfo wpi;
1948
1949         /* cannot paint if there is no stroke data */
1950         if (wpd == NULL) {
1951                 // XXX: force a redraw here, since even though we can't paint, 
1952                 // at least view won't freeze until stroke ends
1953                 ED_region_tag_redraw(CTX_wm_region(C));
1954                 return;
1955         }
1956                 
1957         vc= &wpd->vc;
1958         ob= vc->obact;
1959         me= ob->data;
1960         indexar= wpd->indexar;
1961         
1962         view3d_operator_needs_opengl(C);
1963                 
1964         /* load projection matrix */
1965         mul_m4_m4m4(mat, ob->obmat, vc->rv3d->persmat);
1966
1967         pressure = RNA_float_get(itemptr, "pressure");
1968         RNA_float_get_array(itemptr, "mouse", mval);
1969         mval[0]-= vc->ar->winrct.xmin;
1970         mval[1]-= vc->ar->winrct.ymin;
1971
1972
1973
1974         /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
1975         wpi.defbase_tot=        wpd->defbase_tot;
1976         wpi.defbase_sel=        MEM_mallocN(wpi.defbase_tot*sizeof(char), "wpi.defbase_sel");
1977         wpi.defbase_tot_sel=    get_selected_defgroups(ob, wpi.defbase_sel, wpi.defbase_tot);
1978         if(wpi.defbase_tot_sel == 0 && ob->actdef) wpi.defbase_tot_sel = 1;
1979         wpi.defbase_tot_unsel=  wpi.defbase_tot - wpi.defbase_tot_sel;
1980         wpi.vgroup_mirror=      wpd->vgroup_mirror;
1981         wpi.lock_flags=         wpd->lock_flags;
1982         wpi.vgroup_validmap=    wpd->vgroup_validmap;
1983         wpi.do_flip=            RNA_boolean_get(itemptr, "pen_flip");
1984         wpi.do_multipaint=      (ts->multipaint != 0);
1985         wpi.do_auto_normalize=  (ts->auto_normalize != 0);
1986         /* *** done setting up WeightPaintInfo *** */
1987
1988
1989
1990         swap_m4m4(wpd->vc.rv3d->persmat, mat);
1991
1992         use_vert_sel= (me->editflag & ME_EDIT_VERT_SEL) != 0;
1993
1994         /* which faces are involved */
1995         if(wp->flag & VP_AREA) {
1996                 // Ugly hack, to avoid drawing vertex index when getting the face index buffer - campbell
1997                 me->editflag &= ~ME_EDIT_VERT_SEL;
1998                 totindex= sample_backbuf_area(vc, indexar, me->totface, mval[0], mval[1], brush_size(brush));
1999                 me->editflag |= use_vert_sel ? ME_EDIT_VERT_SEL : 0;
2000         }
2001         else {
2002                 indexar[0]= view3d_sample_backbuf(vc, mval[0], mval[1]);
2003                 if(indexar[0]) totindex= 1;
2004                 else totindex= 0;
2005         }
2006                         
2007         if(wp->flag & VP_COLINDEX) {
2008                 for(index=0; index<totindex; index++) {
2009                         if(indexar[index] && indexar[index]<=me->totface) {
2010                                 MFace *mface= ((MFace *)me->mface) + (indexar[index]-1);
2011                                                 
2012                                 if(mface->mat_nr!=ob->actcol-1) {
2013                                         indexar[index]= 0;
2014                                 }
2015                         }
2016                 }
2017         }
2018                         
2019         if((me->editflag & ME_EDIT_PAINT_MASK) && me->mface) {
2020                 for(index=0; index<totindex; index++) {
2021                         if(indexar[index] && indexar[index]<=me->totface) {
2022                                 MFace *mface= ((MFace *)me->mface) + (indexar[index]-1);
2023                                                 
2024                                 if((mface->flag & ME_FACE_SEL)==0) {
2025                                         indexar[index]= 0;
2026                                 }
2027                         }                                       
2028                 }
2029         }
2030                         
2031         /* make sure each vertex gets treated only once */
2032         /* and calculate filter weight */
2033         totw= 0;
2034         if(brush->vertexpaint_tool==VP_BLUR) 
2035                 paintweight= 0.0f;
2036         else
2037                 paintweight= ts->vgroup_weight;
2038                         
2039         for(index=0; index<totindex; index++) {
2040                 if(indexar[index] && indexar[index]<=me->totface) {
2041                         MFace *mface= me->mface + (indexar[index]-1);
2042
2043                         if(use_vert_sel) {
2044                                 me->dvert[mface->v1].flag = (me->mvert[mface->v1].flag & SELECT);
2045                                 me->dvert[mface->v2].flag = (me->mvert[mface->v2].flag & SELECT);
2046                                 me->dvert[mface->v3].flag = (me->mvert[mface->v3].flag & SELECT);
2047                                 if(mface->v4) me->dvert[mface->v4].flag = (me->mvert[mface->v4].flag & SELECT);
2048                         }
2049                         else {
2050                                 me->dvert[mface->v1].flag= 1;
2051                                 me->dvert[mface->v2].flag= 1;
2052                                 me->dvert[mface->v3].flag= 1;
2053                                 if(mface->v4) me->dvert[mface->v4].flag= 1;
2054                         }
2055                                         
2056                         if(brush->vertexpaint_tool==VP_BLUR) {
2057                                 MDeformWeight *dw, *(*dw_func)(MDeformVert *, const int);
2058                                                 
2059                                 if(wp->flag & VP_ONLYVGROUP)
2060                                         dw_func= (MDeformWeight *(*)(MDeformVert *, const int))defvert_find_index;
2061                                 else
2062                                         dw_func= defvert_verify_index;
2063                                                 
2064                                 dw= dw_func(me->dvert+mface->v1, ob->actdef-1);
2065                                 if(dw) {paintweight+= dw->weight; totw++;}
2066                                 dw= dw_func(me->dvert+mface->v2, ob->actdef-1);
2067                                 if(dw) {paintweight+= dw->weight; totw++;}
2068                                 dw= dw_func(me->dvert+mface->v3, ob->actdef-1);
2069                                 if(dw) {paintweight+= dw->weight; totw++;}
2070                                 if(mface->v4) {
2071                                         dw= dw_func(me->dvert+mface->v4, ob->actdef-1);
2072                                         if(dw) {paintweight+= dw->weight; totw++;}
2073                                 }
2074                         }
2075                 }
2076         }
2077                         
2078         if(brush->vertexpaint_tool==VP_BLUR) 
2079                 paintweight/= (float)totw;
2080                         
2081         for(index=0; index<totindex; index++) {
2082                                 
2083                 if(indexar[index] && indexar[index]<=me->totface) {
2084                         MFace *mf= me->mface + (indexar[index]-1);
2085                         unsigned int fidx= mf->v4 ? 3:2;;
2086                         do {
2087                                 int vidx= *(&mf->v1 + fidx);
2088
2089                                 if(me->dvert[vidx].flag) {
2090                                         alpha= calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos+6*vidx, mval, pressure);
2091                                         if(alpha) {
2092                                                 do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight);
2093                                         }
2094                                         me->dvert[vidx].flag= 0;
2095                                 }
2096                         } while (fidx--);
2097                 }
2098         }
2099
2100
2101         /* *** free wpi members */
2102         MEM_freeN(wpi.defbase_sel);
2103         /* *** dont freeing wpi members */
2104
2105
2106         swap_m4m4(vc->rv3d->persmat, mat);
2107                         
2108         DAG_id_tag_update(ob->data, 0);
2109         ED_region_tag_redraw(vc->ar);
2110 }
2111
2112 static void wpaint_stroke_done(bContext *C, struct PaintStroke *stroke)
2113 {
2114         ToolSettings *ts= CTX_data_tool_settings(C);
2115         Object *ob= CTX_data_active_object(C);
2116         struct WPaintData *wpd= paint_stroke_mode_data(stroke);
2117         
2118         if(wpd) {
2119                 if(wpd->vertexcosnos)
2120                         MEM_freeN(wpd->vertexcosnos);
2121                 MEM_freeN(wpd->indexar);
2122                 
2123                 if (wpd->vgroup_validmap)
2124                         MEM_freeN(wpd->vgroup_validmap);
2125                 if(wpd->lock_flags)
2126                         MEM_freeN(wpd->lock_flags);
2127
2128                 MEM_freeN(wpd);
2129         }
2130         
2131         /* frees prev buffer */
2132         copy_wpaint_prev(ts->wpaint, NULL, 0);
2133         
2134         /* and particles too */
2135         if(ob->particlesystem.first) {
2136                 ParticleSystem *psys;
2137                 int i;
2138                 
2139                 for(psys= ob->particlesystem.first; psys; psys= psys->next) {
2140                         for(i=0; i<PSYS_TOT_VG; i++) {
2141                                 if(psys->vgroup[i]==ob->actdef) {
2142                                         psys->recalc |= PSYS_RECALC_RESET;
2143                                         break;
2144                                 }
2145                         }
2146                 }
2147         }
2148         
2149         DAG_id_tag_update(ob->data, 0);
2150 }
2151
2152
2153 static int wpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2154 {
2155         
2156         op->customdata = paint_stroke_new(C, NULL, wpaint_stroke_test_start,
2157                                           wpaint_stroke_update_step,
2158                                           wpaint_stroke_done, event->type);
2159         
2160         /* add modal handler */
2161         WM_event_add_modal_handler(C, op);
2162
2163         op->type->modal(C, op, event);
2164         
2165         return OPERATOR_RUNNING_MODAL;
2166 }
2167
2168 static int wpaint_cancel(bContext *C, wmOperator *op)
2169 {
2170         paint_stroke_cancel(C, op);
2171
2172         return OPERATOR_CANCELLED;
2173 }
2174
2175 void PAINT_OT_weight_paint(wmOperatorType *ot)
2176 {
2177         
2178         /* identifiers */
2179         ot->name= "Weight Paint";
2180         ot->idname= "PAINT_OT_weight_paint";
2181         
2182         /* api callbacks */
2183         ot->invoke= wpaint_invoke;
2184         ot->modal= paint_stroke_modal;
2185         /* ot->exec= vpaint_exec; <-- needs stroke property */
2186         ot->poll= weight_paint_poll;
2187         ot->cancel= wpaint_cancel;
2188         
2189         /* flags */
2190         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2191
2192         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2193 }
2194
2195 static int weight_paint_set_exec(bContext *C, wmOperator *UNUSED(op))
2196 {
2197         struct Scene *scene= CTX_data_scene(C);
2198         Object *obact = CTX_data_active_object(C);
2199
2200         wpaint_fill(scene->toolsettings->wpaint, obact, scene->toolsettings->vgroup_weight);
2201         ED_region_tag_redraw(CTX_wm_region(C)); // XXX - should redraw all 3D views
2202         return OPERATOR_FINISHED;
2203 }
2204
2205 void PAINT_OT_weight_set(wmOperatorType *ot)
2206 {
2207         /* identifiers */
2208         ot->name= "Set Weight";
2209         ot->idname= "PAINT_OT_weight_set";
2210
2211         /* api callbacks */
2212         ot->exec= weight_paint_set_exec;
2213         ot->poll= mask_paint_poll; /* it was facemask_paint_poll */
2214
2215         /* flags */
2216         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2217 }
2218
2219 /* ************ set / clear vertex paint mode ********** */
2220
2221
2222 static int set_vpaint(bContext *C, wmOperator *op)              /* toggle */
2223 {       
2224         Object *ob= CTX_data_active_object(C);
2225         Scene *scene= CTX_data_scene(C);
2226         VPaint *vp= scene->toolsettings->vpaint;
2227         Mesh *me;
2228         
2229         me= get_mesh(ob);
2230         
2231         if(me==NULL || object_data_is_libdata(ob)) {
2232                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2233                 return OPERATOR_PASS_THROUGH;
2234         }
2235         
2236         if(me && me->mcol==NULL) make_vertexcol(ob);
2237         
2238         /* toggle: end vpaint */
2239         if(ob->mode & OB_MODE_VERTEX_PAINT) {
2240                 
2241                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2242         }
2243         else {
2244                 ob->mode |= OB_MODE_VERTEX_PAINT;
2245                 /* Turn off weight painting */
2246                 if (ob->mode & OB_MODE_WEIGHT_PAINT)
2247                         set_wpaint(C, op);
2248                 
2249                 if(vp==NULL)
2250                         vp= scene->toolsettings->vpaint= new_vpaint(0);
2251                 
2252                 paint_cursor_start(C, vertex_paint_poll);
2253
2254                 paint_init(&vp->paint, PAINT_CURSOR_VERTEX_PAINT);
2255         }
2256         
2257         if (me)
2258                 /* update modifier stack for mapping requirements */
2259                 DAG_id_tag_update(&me->id, 0);
2260         
2261         WM_event_add_notifier(C, NC_SCENE|ND_MODE, scene);
2262         
2263         return OPERATOR_FINISHED;
2264 }
2265
2266 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2267 {
2268         
2269         /* identifiers */
2270         ot->name= "Vertex Paint Mode";
2271         ot->idname= "PAINT_OT_vertex_paint_toggle";
2272         
2273         /* api callbacks */
2274         ot->exec= set_vpaint;
2275         ot->poll= paint_poll_test;
2276         
2277         /* flags */
2278         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2279 }
2280
2281
2282
2283 /* ********************** vertex paint operator ******************* */
2284
2285 /* Implementation notes:
2286
2287 Operator->invoke()
2288   - validate context (add mcol)
2289   - create customdata storage
2290   - call paint once (mouse click)
2291   - add modal handler 
2292
2293 Operator->modal()
2294   - for every mousemove, apply vertex paint
2295   - exit on mouse release, free customdata
2296         (return OPERATOR_FINISHED also removes handler and operator)
2297
2298 For future:
2299   - implement a stroke event (or mousemove with past positons)
2300   - revise whether op->customdata should be added in object, in set_vpaint
2301
2302 */
2303
2304 typedef struct VPaintData {
2305         ViewContext vc;
2306         unsigned int paintcol;
2307         int *indexar;
2308         float *vertexcosnos;
2309         float vpimat[3][3];
2310 } VPaintData;
2311
2312 static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, wmEvent *UNUSED(event))
2313 {
2314         ToolSettings *ts= CTX_data_tool_settings(C);
2315         struct PaintStroke *stroke = op->customdata;
2316         VPaint *vp= ts->vpaint;
2317         struct VPaintData *vpd;
2318         Object *ob= CTX_data_active_object(C);
2319         Mesh *me;
2320         float mat[4][4], imat[4][4];
2321
2322         /* context checks could be a poll() */
2323         me= get_mesh(ob);
2324         if(me==NULL || me->totface==0) return OPERATOR_PASS_THROUGH;
2325         
2326         if(me->mcol==NULL) make_vertexcol(ob);
2327         if(me->mcol==NULL) return OPERATOR_CANCELLED;
2328         
2329         /* make mode data storage */
2330         vpd= MEM_callocN(sizeof(struct VPaintData), "VPaintData");
2331         paint_stroke_set_mode_data(stroke, vpd);
2332         view3d_set_viewcontext(C, &vpd->vc);
2333         
2334         vpd->vertexcosnos= mesh_get_mapped_verts_nors(vpd->vc.scene, ob);
2335         vpd->indexar= get_indexarray(me);
2336         vpd->paintcol= vpaint_get_current_col(vp);
2337         
2338         /* for filtering */
2339         copy_vpaint_prev(vp, (unsigned int *)me->mcol, me->totface);
2340         
2341         /* some old cruft to sort out later */
2342         mul_m4_m4m4(mat, ob->obmat, vpd->vc.rv3d->viewmat);
2343         invert_m4_m4(imat, mat);
2344         copy_m3_m4(vpd->vpimat, imat);
2345
2346         return 1;
2347 }
2348
2349 static void vpaint_paint_face(VPaint *vp, VPaintData *vpd, Object *ob, int index, const float mval[2], float pressure, int UNUSED(flip))
2350 {
2351         ViewContext *vc = &vpd->vc;
2352         Brush *brush = paint_brush(&vp->paint);
2353         Mesh *me = get_mesh(ob);
2354         MFace *mface= ((MFace*)me->mface) + index;
2355         unsigned int *mcol= ((unsigned int*)me->mcol) + 4*index;
2356         unsigned int *mcolorig= ((unsigned int*)vp->vpaint_prev) + 4*index;
2357         float alpha;
2358         int i;
2359         
2360         if((vp->flag & VP_COLINDEX && mface->mat_nr!=ob->actcol-1) ||
2361            ((me->editflag & ME_EDIT_PAINT_MASK) && !(mface->flag & ME_FACE_SEL)))
2362                 return;
2363
2364         if(brush->vertexpaint_tool==VP_BLUR) {
2365                 unsigned int fcol1= mcol_blend( mcol[0], mcol[1], 128);
2366                 if(mface->v4) {
2367                         unsigned int fcol2= mcol_blend( mcol[2], mcol[3], 128);
2368                         vpd->paintcol= mcol_blend( fcol1, fcol2, 128);
2369                 }
2370                 else {
2371                         vpd->paintcol= mcol_blend( mcol[2], fcol1, 170);
2372                 }
2373                 
2374         }
2375
2376         for(i = 0; i < (mface->v4 ? 4 : 3); ++i) {
2377                 alpha= calc_vp_alpha_dl(vp, vc, vpd->vpimat, vpd->vertexcosnos+6*(&mface->v1)[i], mval, pressure);
2378                 if(alpha)
2379                         vpaint_blend(vp, mcol+i, mcolorig+i, vpd->paintcol, (int)(alpha*255.0f));
2380         }
2381 }
2382
2383 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2384 {
2385         ToolSettings *ts= CTX_data_tool_settings(C);
2386         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2387         VPaint *vp= ts->vpaint;
2388         Brush *brush = paint_brush(&vp->paint);
2389         ViewContext *vc= &vpd->vc;
2390         Object *ob= vc->obact;
2391         Mesh *me= ob->data;
2392         float mat[4][4];
2393         int *indexar= vpd->indexar;
2394         int totindex, index, flip;
2395         float pressure, mval[2];
2396
2397         RNA_float_get_array(itemptr, "mouse", mval);
2398         flip = RNA_boolean_get(itemptr, "pen_flip");
2399         pressure = RNA_float_get(itemptr, "pressure");
2400                         
2401         view3d_operator_needs_opengl(C);
2402                         
2403         /* load projection matrix */
2404         mul_m4_m4m4(mat, ob->obmat, vc->rv3d->persmat);
2405
2406         mval[0]-= vc->ar->winrct.xmin;
2407         mval[1]-= vc->ar->winrct.ymin;
2408
2409                         
2410         /* which faces are involved */
2411         if(vp->flag & VP_AREA) {
2412                 totindex= sample_backbuf_area(vc, indexar, me->totface, mval[0], mval[1], brush_size(brush));
2413         }
2414         else {
2415                 indexar[0]= view3d_sample_backbuf(vc, mval[0], mval[1]);
2416                 if(indexar[0]) totindex= 1;
2417                 else totindex= 0;
2418         }
2419                         
2420         swap_m4m4(vc->rv3d->persmat, mat);
2421                         
2422         for(index=0; index<totindex; index++) {                         
2423                 if(indexar[index] && indexar[index]<=me->totface)
2424                         vpaint_paint_face(vp, vpd, ob, indexar[index]-1, mval, pressure, flip);
2425         }
2426                                                 
2427         swap_m4m4(vc->rv3d->persmat, mat);
2428
2429         /* was disabled because it is slow, but necessary for blur */
2430         if(brush->vertexpaint_tool == VP_BLUR)
2431                 do_shared_vertexcol(me);
2432                         
2433         ED_region_tag_redraw(vc->ar);
2434                         
2435         DAG_id_tag_update(ob->data, 0);
2436 }
2437
2438 static void vpaint_stroke_done(bContext *C, struct PaintStroke *stroke)
2439 {
2440         ToolSettings *ts= CTX_data_tool_settings(C);
2441         struct VPaintData *vpd= paint_stroke_mode_data(stroke);
2442         
2443         if(vpd->vertexcosnos)
2444                 MEM_freeN(vpd->vertexcosnos);
2445         MEM_freeN(vpd->indexar);
2446         
2447         /* frees prev buffer */
2448         copy_vpaint_prev(ts->vpaint, NULL, 0);
2449         
2450         MEM_freeN(vpd);
2451 }
2452
2453 static int vpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2454 {
2455         
2456         op->customdata = paint_stroke_new(C, NULL, vpaint_stroke_test_start,
2457                                           vpaint_stroke_update_step,
2458                                           vpaint_stroke_done, event->type);
2459         
2460         /* add modal handler */
2461         WM_event_add_modal_handler(C, op);
2462
2463         op->type->modal(C, op, event);
2464         
2465         return OPERATOR_RUNNING_MODAL;
2466 }
2467
2468 static int vpaint_cancel(bContext *C, wmOperator *op)
2469 {
2470         paint_stroke_cancel(C, op);
2471
2472         return OPERATOR_CANCELLED;
2473 }
2474
2475 void PAINT_OT_vertex_paint(wmOperatorType *ot)
2476 {
2477         /* identifiers */
2478         ot->name= "Vertex Paint";
2479         ot->idname= "PAINT_OT_vertex_paint";
2480         
2481         /* api callbacks */
2482         ot->invoke= vpaint_invoke;
2483         ot->modal= paint_stroke_modal;
2484         /* ot->exec= vpaint_exec; <-- needs stroke property */
2485         ot->poll= vertex_paint_poll;
2486         ot->cancel= vpaint_cancel;
2487         
2488         /* flags */
2489         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2490
2491         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2492 }
2493
2494 /* ********************** weight from bones operator ******************* */
2495
2496 static int weight_from_bones_poll(bContext *C)
2497 {
2498         Object *ob= CTX_data_active_object(C);
2499
2500         return (ob && (ob->mode & OB_MODE_WEIGHT_PAINT) && modifiers_isDeformedByArmature(ob));
2501 }
2502
2503 static int weight_from_bones_exec(bContext *C, wmOperator *op)
2504 {
2505         Scene *scene= CTX_data_scene(C);
2506         Object *ob= CTX_data_active_object(C);
2507         Object *armob= modifiers_isDeformedByArmature(ob);
2508         Mesh *me= ob->data;
2509         int type= RNA_enum_get(op->ptr, "type");
2510
2511         create_vgroups_from_armature(op->reports, scene, ob, armob, type, (me->editflag & ME_EDIT_MIRROR_X));
2512
2513         DAG_id_tag_update(&me->id, 0);
2514         WM_event_add_notifier(C, NC_GEOM|ND_DATA, me);
2515
2516         return OPERATOR_FINISHED;
2517 }
2518
2519 void PAINT_OT_weight_from_bones(wmOperatorType *ot)
2520 {
2521         static EnumPropertyItem type_items[]= {
2522                 {ARM_GROUPS_AUTO, "AUTOMATIC", 0, "Automatic", "Automatic weights froms bones"},
2523                 {ARM_GROUPS_ENVELOPE, "ENVELOPES", 0, "From Envelopes", "Weights from envelopes with user defined radius"},
2524                 {0, NULL, 0, NULL, NULL}};
2525
2526         /* identifiers */
2527         ot->name= "Weight from Bones";
2528         ot->idname= "PAINT_OT_weight_from_bones";
2529         
2530         /* api callbacks */
2531         ot->exec= weight_from_bones_exec;
2532         ot->invoke= WM_menu_invoke;
2533         ot->poll= weight_from_bones_poll;
2534         
2535         /* flags */
2536         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2537
2538         /* properties */
2539         ot->prop= RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "Method to use for assigning weights.");
2540 }
2541