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