minor edits to main weight paint function for better readability - do_weight_paint_ve...
[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, const int vgroup_active)
292 {
293         bDeformGroup *defgroup= BLI_findlink(&ob->defbase, vgroup_active);
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) make_vertexcol(ob);
368         if(!me->mcol) return; /* possible we can't make mcol's */
369
370
371         selected= (me->editflag & ME_EDIT_PAINT_MASK);
372
373         mf = me->mface;
374         mcol = (unsigned int*)me->mcol;
375         for (i = 0; i < me->totface; i++, mf++, mcol+=4) {
376                 if (!selected || mf->flag & ME_FACE_SEL) {
377                         mcol[0] = paintcol;
378                         mcol[1] = paintcol;
379                         mcol[2] = paintcol;
380                         mcol[3] = paintcol;
381                 }
382         }
383         
384         DAG_id_tag_update(&me->id, 0);
385 }
386
387
388 /* fills in the selected faces with the current weight and vertex group */
389 void wpaint_fill(VPaint *wp, Object *ob, float paintweight)
390 {
391         Mesh *me= ob->data;
392         MFace *mf;
393         MDeformWeight *dw, *uw;
394         int vgroup_active, vgroup_mirror= -1;
395         unsigned int index;
396
397         /* mutually exclusive, could be made into a */
398         const short paint_selmode= ME_EDIT_PAINT_SEL_MODE(me);
399
400         if(me->totface==0 || me->dvert==NULL || !me->mface) return;
401         
402         vgroup_active = ob->actdef - 1;
403
404         /* if mirror painting, find the other group */
405         if(me->editflag & ME_EDIT_MIRROR_X) {
406                 vgroup_mirror= wpaint_mirror_vgroup_ensure(ob, vgroup_active);
407         }
408         
409         copy_wpaint_prev(wp, me->dvert, me->totvert);
410         
411         for(index=0, mf= me->mface; index < me->totface; index++, mf++) {
412                 unsigned int fidx= mf->v4 ? 3:2;
413
414                 if ((paint_selmode == SCE_SELECT_FACE) && !(mf->flag & ME_FACE_SEL)) {
415                         continue;
416                 }
417
418                 do {
419                         unsigned int vidx= *(&mf->v1 + fidx);
420
421                         if(!me->dvert[vidx].flag) {
422                                 if((paint_selmode == SCE_SELECT_VERTEX) && !(me->mvert[vidx].flag & SELECT)) {
423                                         continue;
424                                 }
425
426                                 dw= defvert_verify_index(&me->dvert[vidx], vgroup_active);
427                                 if(dw) {
428                                         uw= defvert_verify_index(wp->wpaint_prev+vidx, vgroup_active);
429                                         uw->weight= dw->weight; /* set the undo weight */
430                                         dw->weight= paintweight;
431
432                                         if(me->editflag & ME_EDIT_MIRROR_X) {   /* x mirror painting */
433                                                 int j= mesh_get_x_mirror_vert(ob, vidx);
434                                                 if(j>=0) {
435                                                         /* copy, not paint again */
436                                                         if(vgroup_mirror != -1) {
437                                                                 dw= defvert_verify_index(me->dvert+j, vgroup_mirror);
438                                                                 uw= defvert_verify_index(wp->wpaint_prev+j, vgroup_mirror);
439                                                         } else {
440                                                                 dw= defvert_verify_index(me->dvert+j, vgroup_active);
441                                                                 uw= defvert_verify_index(wp->wpaint_prev+j, vgroup_active);
442                                                         }
443                                                         uw->weight= dw->weight; /* set the undo weight */
444                                                         dw->weight= paintweight;
445                                                 }
446                                         }
447                                 }
448                                 me->dvert[vidx].flag= 1;
449                         }
450
451                 } while (fidx--);
452         }
453
454         {
455                 MDeformVert *dv= me->dvert;
456                 for(index= me->totvert; index != 0; index--, dv++) {
457                         dv->flag= 0;
458                 }
459         }
460
461         copy_wpaint_prev(wp, NULL, 0);
462
463         DAG_id_tag_update(&me->id, 0);
464 }
465
466 /* XXX: should be re-implemented as a vertex/weight paint 'color correct' operator
467  
468 void vpaint_dogamma(Scene *scene)
469 {
470         VPaint *vp= scene->toolsettings->vpaint;
471         Mesh *me;
472         Object *ob;
473         float igam, fac;
474         int a, temp;
475         unsigned char *cp, gamtab[256];
476
477         ob= OBACT;
478         me= get_mesh(ob);
479
480         if(!(ob->mode & OB_MODE_VERTEX_PAINT)) return;
481         if(me==0 || me->mcol==0 || me->totface==0) return;
482
483         igam= 1.0/vp->gamma;
484         for(a=0; a<256; a++) {
485                 
486                 fac= ((float)a)/255.0;
487                 fac= vp->mul*pow( fac, igam);
488                 
489                 temp= 255.9*fac;
490                 
491                 if(temp<=0) gamtab[a]= 0;
492                 else if(temp>=255) gamtab[a]= 255;
493                 else gamtab[a]= temp;
494         }
495
496         a= 4*me->totface;
497         cp= (unsigned char *)me->mcol;
498         while(a--) {
499                 
500                 cp[1]= gamtab[ cp[1] ];
501                 cp[2]= gamtab[ cp[2] ];
502                 cp[3]= gamtab[ cp[3] ];
503                 
504                 cp+= 4;
505         }
506 }
507  */
508
509 static unsigned int mcol_blend(unsigned int col1, unsigned int col2, int fac)
510 {
511         char *cp1, *cp2, *cp;
512         int mfac;
513         unsigned int col=0;
514         
515         if(fac==0) return col1;
516         if(fac>=255) return col2;
517
518         mfac= 255-fac;
519         
520         cp1= (char *)&col1;
521         cp2= (char *)&col2;
522         cp=  (char *)&col;
523         
524         cp[0]= 255;
525         cp[1]= (mfac*cp1[1]+fac*cp2[1])/255;
526         cp[2]= (mfac*cp1[2]+fac*cp2[2])/255;
527         cp[3]= (mfac*cp1[3]+fac*cp2[3])/255;
528         
529         return col;
530 }
531
532 static unsigned int mcol_add(unsigned int col1, unsigned int col2, int fac)
533 {
534         char *cp1, *cp2, *cp;
535         int temp;
536         unsigned int col=0;
537         
538         if(fac==0) return col1;
539         
540         cp1= (char *)&col1;
541         cp2= (char *)&col2;
542         cp=  (char *)&col;
543         
544         cp[0]= 255;
545         temp= cp1[1] + ((fac*cp2[1])/255);
546         if(temp>254) cp[1]= 255; else cp[1]= temp;
547         temp= cp1[2] + ((fac*cp2[2])/255);
548         if(temp>254) cp[2]= 255; else cp[2]= temp;
549         temp= cp1[3] + ((fac*cp2[3])/255);
550         if(temp>254) cp[3]= 255; else cp[3]= temp;
551         
552         return col;
553 }
554
555 static unsigned int mcol_sub(unsigned int col1, unsigned int col2, int fac)
556 {
557         char *cp1, *cp2, *cp;
558         int temp;
559         unsigned int col=0;
560         
561         if(fac==0) return col1;
562         
563         cp1= (char *)&col1;
564         cp2= (char *)&col2;
565         cp=  (char *)&col;
566         
567         cp[0]= 255;
568         temp= cp1[1] - ((fac*cp2[1])/255);
569         if(temp<0) cp[1]= 0; else cp[1]= temp;
570         temp= cp1[2] - ((fac*cp2[2])/255);
571         if(temp<0) cp[2]= 0; else cp[2]= temp;
572         temp= cp1[3] - ((fac*cp2[3])/255);
573         if(temp<0) cp[3]= 0; else cp[3]= temp;
574         
575         return col;
576 }
577
578 static unsigned int mcol_mul(unsigned int col1, unsigned int col2, int fac)
579 {
580         char *cp1, *cp2, *cp;
581         int mfac;
582         unsigned int col=0;
583         
584         if(fac==0) return col1;
585
586         mfac= 255-fac;
587         
588         cp1= (char *)&col1;
589         cp2= (char *)&col2;
590         cp=  (char *)&col;
591         
592         /* first mul, then blend the fac */
593         cp[0]= 255;
594         cp[1]= (mfac*cp1[1] + fac*((cp2[1]*cp1[1])/255)  )/255;
595         cp[2]= (mfac*cp1[2] + fac*((cp2[2]*cp1[2])/255)  )/255;
596         cp[3]= (mfac*cp1[3] + fac*((cp2[3]*cp1[3])/255)  )/255;
597
598         
599         return col;
600 }
601
602 static unsigned int mcol_lighten(unsigned int col1, unsigned int col2, int fac)
603 {
604         char *cp1, *cp2, *cp;
605         int mfac;
606         unsigned int col=0;
607         
608         if(fac==0) return col1;
609         if(fac>=255) return col2;
610
611         mfac= 255-fac;
612         
613         cp1= (char *)&col1;
614         cp2= (char *)&col2;
615         cp=  (char *)&col;
616         
617         /* See if are lighter, if so mix, else dont do anything.
618         if the paint col is darker then the original, then ignore */
619         if (cp1[1]+cp1[2]+cp1[3] > cp2[1]+cp2[2]+cp2[3])
620                 return col1;
621         
622         cp[0]= 255;
623         cp[1]= (mfac*cp1[1]+fac*cp2[1])/255;
624         cp[2]= (mfac*cp1[2]+fac*cp2[2])/255;
625         cp[3]= (mfac*cp1[3]+fac*cp2[3])/255;
626         
627         return col;
628 }
629
630 static unsigned int mcol_darken(unsigned int col1, unsigned int col2, int fac)
631 {
632         char *cp1, *cp2, *cp;
633         int mfac;
634         unsigned int col=0;
635         
636         if(fac==0) return col1;
637         if(fac>=255) return col2;
638
639         mfac= 255-fac;
640         
641         cp1= (char *)&col1;
642         cp2= (char *)&col2;
643         cp=  (char *)&col;
644         
645         /* See if were darker, if so mix, else dont do anything.
646         if the paint col is brighter then the original, then ignore */
647         if (cp1[1]+cp1[2]+cp1[3] < cp2[1]+cp2[2]+cp2[3])
648                 return col1;
649         
650         cp[0]= 255;
651         cp[1]= (mfac*cp1[1]+fac*cp2[1])/255;
652         cp[2]= (mfac*cp1[2]+fac*cp2[2])/255;
653         cp[3]= (mfac*cp1[3]+fac*cp2[3])/255;
654         return col;
655 }
656
657 static void vpaint_blend(VPaint *vp, unsigned int *col, unsigned int *colorig, unsigned int paintcol, int alpha)
658 {
659         Brush *brush = paint_brush(&vp->paint);
660
661         if(brush->vertexpaint_tool==VP_MIX || brush->vertexpaint_tool==VP_BLUR) *col= mcol_blend( *col, paintcol, alpha);
662         else if(brush->vertexpaint_tool==VP_ADD) *col= mcol_add( *col, paintcol, alpha);
663         else if(brush->vertexpaint_tool==VP_SUB) *col= mcol_sub( *col, paintcol, alpha);
664         else if(brush->vertexpaint_tool==VP_MUL) *col= mcol_mul( *col, paintcol, alpha);
665         else if(brush->vertexpaint_tool==VP_LIGHTEN) *col= mcol_lighten( *col, paintcol, alpha);
666         else if(brush->vertexpaint_tool==VP_DARKEN) *col= mcol_darken( *col, paintcol, alpha);
667         
668         /* if no spray, clip color adding with colorig & orig alpha */
669         if((vp->flag & VP_SPRAY)==0) {
670                 unsigned int testcol=0, a;
671                 char *cp, *ct, *co;
672                 
673                 alpha= (int)(255.0f*brush_alpha(brush));
674                 
675                 if(brush->vertexpaint_tool==VP_MIX || brush->vertexpaint_tool==VP_BLUR) testcol= mcol_blend( *colorig, paintcol, alpha);
676                 else if(brush->vertexpaint_tool==VP_ADD) testcol= mcol_add( *colorig, paintcol, alpha);
677                 else if(brush->vertexpaint_tool==VP_SUB) testcol= mcol_sub( *colorig, paintcol, alpha);
678                 else if(brush->vertexpaint_tool==VP_MUL) testcol= mcol_mul( *colorig, paintcol, alpha);
679                 else if(brush->vertexpaint_tool==VP_LIGHTEN)  testcol= mcol_lighten( *colorig, paintcol, alpha);
680                 else if(brush->vertexpaint_tool==VP_DARKEN)   testcol= mcol_darken( *colorig, paintcol, alpha);
681                 
682                 cp= (char *)col;
683                 ct= (char *)&testcol;
684                 co= (char *)colorig;
685                 
686                 for(a=0; a<4; a++) {
687                         if( ct[a]<co[a] ) {
688                                 if( cp[a]<ct[a] ) cp[a]= ct[a];
689                                 else if( cp[a]>co[a] ) cp[a]= co[a];
690                         }
691                         else {
692                                 if( cp[a]<co[a] ) cp[a]= co[a];
693                                 else if( cp[a]>ct[a] ) cp[a]= ct[a];
694                         }
695                 }
696         }
697 }
698
699
700 static int sample_backbuf_area(ViewContext *vc, int *indexar, int totface, int x, int y, float size)
701 {
702         struct ImBuf *ibuf;
703         int a, tot=0, index;
704         
705         /* brecht: disabled this because it obviously failes for
706            brushes with size > 64, why is this here? */
707         /*if(size>64.0) size= 64.0;*/
708         
709         ibuf= view3d_read_backbuf(vc, x-size, y-size, x+size, y+size);
710         if(ibuf) {
711                 unsigned int *rt= ibuf->rect;
712
713                 memset(indexar, 0, sizeof(int)*(totface+1));
714                 
715                 size= ibuf->x*ibuf->y;
716                 while(size--) {
717                                 
718                         if(*rt) {
719                                 index= WM_framebuffer_to_index(*rt);
720                                 if(index>0 && index<=totface)
721                                         indexar[index] = 1;
722                         }
723                 
724                         rt++;
725                 }
726                 
727                 for(a=1; a<=totface; a++) {
728                         if(indexar[a]) indexar[tot++]= a;
729                 }
730
731                 IMB_freeImBuf(ibuf);
732         }
733         
734         return tot;
735 }
736
737 /* whats _dl mean? */
738 static float calc_vp_strength_dl(VPaint *vp, ViewContext *vc, const float *vert_nor,
739                               const float mval[2], const float brush_size_final)
740 {
741         Brush *brush = paint_brush(&vp->paint);
742         float dist_squared;
743         float vertco[2], delta[2];
744
745         project_float_noclip(vc->ar, vert_nor, vertco);
746         sub_v2_v2v2(delta, mval, vertco);
747         dist_squared= dot_v2v2(delta, delta); /* len squared */
748         if (dist_squared > brush_size_final * brush_size_final) {
749                 return 0.0f;
750         }
751         else {
752                 const float dist = sqrtf(dist_squared);
753                 return brush_curve_strength_clamp(brush, dist, brush_size_final);
754         }
755 }
756
757 static float calc_vp_alpha_dl(VPaint *vp, ViewContext *vc,
758                               float vpimat[][3], const float *vert_nor,
759                               const float mval[2],
760                               const float brush_size_final, const float brush_alpha_final)
761 {
762         float strength = calc_vp_strength_dl(vp, vc, vert_nor, mval, brush_size_final);
763
764         if (strength > 0.0f) {
765                 float alpha= brush_alpha_final * strength;
766
767                 if(vp->flag & VP_NORMALS) {
768                         float dvec[3];
769                         const float *no= vert_nor + 3;
770
771                         /* transpose ! */
772                         dvec[2] = dot_v3v3(vpimat[2], no);
773                         if (dvec[2] > 0.0f) {
774                                 dvec[0] = dot_v3v3(vpimat[0], no);
775                                 dvec[1] = dot_v3v3(vpimat[1], no);
776
777                                 alpha *= dvec[2] / len_v3(dvec);
778                         }
779                         else {
780                                 return 0.0f;
781                         }
782                 }
783
784                 return alpha;
785         }
786
787         return 0.0f;
788 }
789
790 static void wpaint_blend(VPaint *wp, MDeformWeight *dw, MDeformWeight *uw, float alpha, float paintval, int flip, int multipaint)
791 {
792         Brush *brush = paint_brush(&wp->paint);
793         int tool = brush->vertexpaint_tool;
794
795         if (flip) {
796                 switch(tool) {
797                         case VP_MIX:
798                                 paintval = 1.f - paintval; break;
799                         case VP_ADD:
800                                 tool= VP_SUB; break;
801                         case VP_SUB:
802                                 tool= VP_ADD; break;
803                         case VP_LIGHTEN:
804                                 tool= VP_DARKEN; break;
805                         case VP_DARKEN:
806                                 tool= VP_LIGHTEN; break;
807                 }
808         }
809         
810         if(tool==VP_MIX || tool==VP_BLUR)
811                 dw->weight = paintval*alpha + dw->weight*(1.0f-alpha);
812         else if(tool==VP_ADD)
813                 dw->weight += paintval*alpha;
814         else if(tool==VP_SUB) 
815                 dw->weight -= paintval*alpha;
816         else if(tool==VP_MUL) 
817                 /* first mul, then blend the fac */
818                 dw->weight = ((1.0f-alpha) + alpha*paintval)*dw->weight;
819         else if(tool==VP_LIGHTEN) {
820                 if (dw->weight < paintval)
821                         dw->weight = paintval*alpha + dw->weight*(1.0f-alpha);
822         } else if(tool==VP_DARKEN) {
823                 if (dw->weight > paintval)
824                         dw->weight = paintval*alpha + dw->weight*(1.0f-alpha);
825         }
826         /*  delay clamping until the end so multi-paint can function when the active group is at the limits */
827         if(multipaint == FALSE) {
828                 CLAMP(dw->weight, 0.0f, 1.0f);
829         }
830         
831         /* if no spray, clip result with orig weight & orig alpha */
832         if((wp->flag & VP_SPRAY)==0) {
833                 float testw=0.0f;
834                 
835                 alpha= brush_alpha(brush);
836                 if(tool==VP_MIX || tool==VP_BLUR)
837                         testw = paintval*alpha + uw->weight*(1.0f-alpha);
838                 else if(tool==VP_ADD)
839                         testw = uw->weight + paintval*alpha;
840                 else if(tool==VP_SUB) 
841                         testw = uw->weight - paintval*alpha;
842                 else if(tool==VP_MUL) 
843                         /* first mul, then blend the fac */
844                         testw = ((1.0f-alpha) + alpha*paintval)*uw->weight;
845                 else if(tool==VP_LIGHTEN) {
846                         if (uw->weight < paintval)
847                                 testw = paintval*alpha + uw->weight*(1.0f-alpha);
848                         else
849                                 testw = uw->weight;
850                 } else if(tool==VP_DARKEN) {
851                         if (uw->weight > paintval)
852                                 testw = paintval*alpha + uw->weight*(1.0f-alpha);
853                         else
854                                 testw = uw->weight;
855                 }
856
857                 if(multipaint == FALSE) {
858                         CLAMP(testw, 0.0f, 1.0f);
859                         if( testw<uw->weight ) {
860                                 if(dw->weight < testw) dw->weight= testw;
861                                 else if(dw->weight > uw->weight) dw->weight= uw->weight;
862                         }
863                         else {
864                                 if(dw->weight > testw) dw->weight= testw;
865                                 else if(dw->weight < uw->weight) dw->weight= uw->weight;
866                         }
867                 }
868         }
869         
870 }
871
872 /* ----------------------------------------------------- */
873
874
875 /* sets wp->weight to the closest weight value to vertex */
876 /* note: we cant sample frontbuf, weight colors are interpolated too unpredictable */
877 static int weight_sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
878 {
879         ViewContext vc;
880         Mesh *me;
881         short change= FALSE;
882
883         view3d_set_viewcontext(C, &vc);
884         me= get_mesh(vc.obact);
885
886         if (me && me->dvert && vc.v3d && vc.rv3d) {
887                 int index;
888
889                 view3d_operator_needs_opengl(C);
890
891                 index= view3d_sample_backbuf(&vc, event->mval[0], event->mval[1]);
892
893                 if(index && index<=me->totface) {
894                         DerivedMesh *dm= mesh_get_derived_final(vc.scene, vc.obact, CD_MASK_BAREMESH);
895
896                         if(dm->getVertCo==NULL) {
897                                 BKE_report(op->reports, RPT_WARNING, "The modifier used does not support deformed locations");
898                         }
899                         else {
900                                 MFace *mf= ((MFace *)me->mface) + index-1;
901                                 const int vgroup_active= vc.obact->actdef - 1;
902                                 ToolSettings *ts= vc.scene->toolsettings;
903                                 float mval_f[2];
904                                 int v_idx_best= -1;
905                                 int fidx;
906                                 float len_best= FLT_MAX;
907
908                                 mval_f[0]= (float)event->mval[0];
909                                 mval_f[1]= (float)event->mval[1];
910
911                                 fidx= mf->v4 ? 3:2;
912                                 do {
913                                         float co[3], sco[3], len;
914                                         const int v_idx= (*(&mf->v1 + fidx));
915                                         dm->getVertCo(dm, v_idx, co);
916                                         project_float_noclip(vc.ar, co, sco);
917                                         len= len_squared_v2v2(mval_f, sco);
918                                         if(len < len_best) {
919                                                 len_best= len;
920                                                 v_idx_best= v_idx;
921                                         }
922                                 } while (fidx--);
923
924                                 if(v_idx_best != -1) { /* should always be valid */
925                                         ts->vgroup_weight= defvert_find_weight(&me->dvert[v_idx_best], vgroup_active);
926                                         change= TRUE;
927                                 }
928                         }
929                         dm->release(dm);
930                 }
931         }
932
933         if(change) {
934                 /* not really correct since the brush didnt change, but redraws the toolbar */
935                 WM_main_add_notifier(NC_BRUSH|NA_EDITED, NULL); /* ts->wpaint->paint.brush */
936
937                 return OPERATOR_FINISHED;
938         }
939         else {
940                 return OPERATOR_CANCELLED;
941         }
942 }
943
944 void PAINT_OT_weight_sample(wmOperatorType *ot)
945 {
946         /* identifiers */
947         ot->name= "Weight Paint Sample Weight";
948         ot->idname= "PAINT_OT_weight_sample";
949
950         /* api callbacks */
951         ot->invoke= weight_sample_invoke;
952         ot->poll= weight_paint_mode_poll;
953
954         /* flags */
955         ot->flag= OPTYPE_UNDO;
956 }
957
958 /* samples cursor location, and gives menu with vertex groups to activate */
959 static EnumPropertyItem *weight_paint_sample_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), int *free)
960 {
961         if (C) {
962                 wmWindow *win= CTX_wm_window(C);
963                 if(win && win->eventstate) {
964                         ViewContext vc;
965                         Mesh *me;
966
967                         view3d_set_viewcontext(C, &vc);
968                         me= get_mesh(vc.obact);
969
970                         if (me && me->dvert && vc.v3d && vc.rv3d) {
971                                 int index;
972
973                                 view3d_operator_needs_opengl(C);
974
975                                 index= view3d_sample_backbuf(&vc, win->eventstate->x - vc.ar->winrct.xmin, win->eventstate->y - vc.ar->winrct.ymin);
976
977                                 if(index && index<=me->totface) {
978                                         const int defbase_tot= BLI_countlist(&vc.obact->defbase);
979                                         if(defbase_tot) {
980                                                 MFace *mf= ((MFace *)me->mface) + index-1;
981                                                 unsigned int fidx= mf->v4 ? 3:2;
982                                                 int *groups= MEM_callocN(defbase_tot*sizeof(int), "groups");
983                                                 int found= FALSE;
984
985                                                 do {
986                                                         MDeformVert *dvert= me->dvert + (*(&mf->v1 + fidx));
987                                                         int i= dvert->totweight;
988                                                         MDeformWeight *dw;
989                                                         for(dw= dvert->dw; i > 0; dw++, i--) {
990                                                                 if (dw->def_nr < defbase_tot) {
991                                                                         groups[dw->def_nr]= TRUE;
992                                                                         found= TRUE;
993                                                                 }
994                                                         }
995                                                 } while (fidx--);
996
997                                                 if(found==FALSE) {
998                                                         MEM_freeN(groups);
999                                                 }
1000                                                 else {
1001                                                         EnumPropertyItem *item= NULL, item_tmp= {0};
1002                                                         int totitem= 0;
1003                                                         int i= 0;
1004                                                         bDeformGroup *dg;
1005                                                         for(dg= vc.obact->defbase.first; dg && i<defbase_tot; i++, dg= dg->next) {
1006                                                                 if(groups[i]) {
1007                                                                         item_tmp.identifier= item_tmp.name= dg->name;
1008                                                                         item_tmp.value= i;
1009                                                                         RNA_enum_item_add(&item, &totitem, &item_tmp);
1010                                                                 }
1011                                                         }
1012
1013                                                         RNA_enum_item_end(&item, &totitem);
1014                                                         *free= 1;
1015
1016                                                         MEM_freeN(groups);
1017                                                         return item;
1018                                                 }
1019                                         }
1020                                 }
1021                         }
1022                 }
1023         }
1024
1025         return DummyRNA_NULL_items;
1026 }
1027
1028 static int weight_sample_group_exec(bContext *C, wmOperator *op)
1029 {
1030         int type= RNA_enum_get(op->ptr, "group");
1031         ViewContext vc;
1032         view3d_set_viewcontext(C, &vc);
1033
1034         BLI_assert(type + 1 >= 0);
1035         vc.obact->actdef= type + 1;
1036
1037         DAG_id_tag_update(&vc.obact->id, OB_RECALC_DATA);
1038         WM_event_add_notifier(C, NC_OBJECT|ND_DRAW, vc.obact);
1039         return OPERATOR_FINISHED;
1040 }
1041
1042 /* TODO, we could make this a menu into OBJECT_OT_vertex_group_set_active rather than its own operator */
1043 void PAINT_OT_weight_sample_group(wmOperatorType *ot)
1044 {
1045         PropertyRNA *prop= NULL;
1046
1047         /* identifiers */
1048         ot->name= "Weight Paint Sample Group";
1049         ot->idname= "PAINT_OT_weight_sample_group";
1050
1051         /* api callbacks */
1052         ot->exec= weight_sample_group_exec;
1053         ot->invoke= WM_menu_invoke;
1054         ot->poll= weight_paint_mode_poll;
1055
1056         /* flags */
1057         ot->flag= OPTYPE_UNDO;
1058
1059         /* keyingset to use (dynamic enum) */
1060         prop= RNA_def_enum(ot->srna, "group", DummyRNA_DEFAULT_items, 0, "Keying Set", "The Keying Set to use");
1061         RNA_def_enum_funcs(prop, weight_paint_sample_enum_itemf);
1062         ot->prop= prop;
1063 }
1064
1065
1066 #if 0 /* UNUSED */
1067 static void do_weight_paint_auto_normalize(MDeformVert *dvert, 
1068                                            int paint_nr, char *map)
1069 {
1070 //      MDeformWeight *dw = dvert->dw;
1071         float sum=0.0f, fac=0.0f, paintw=0.0f;
1072         int i, tot=0;
1073
1074         if (!map)
1075                 return;
1076
1077         for (i=0; i<dvert->totweight; i++) {
1078                 if (dvert->dw[i].def_nr == paint_nr)
1079                         paintw = dvert->dw[i].weight;
1080
1081                 if (map[dvert->dw[i].def_nr]) {
1082                         tot += 1;
1083                         if (dvert->dw[i].def_nr != paint_nr)
1084                                 sum += dvert->dw[i].weight;
1085                 }
1086         }
1087         
1088         if (!tot || sum <= (1.0f - paintw))
1089                 return;
1090
1091         fac = sum / (1.0f - paintw);
1092         fac = fac==0.0f ? 1.0f : 1.0f / fac;
1093
1094         for (i=0; i<dvert->totweight; i++) {
1095                 if (map[dvert->dw[i].def_nr]) {
1096                         if (dvert->dw[i].def_nr != paint_nr)
1097                                 dvert->dw[i].weight *= fac;
1098                 }
1099         }
1100 }
1101 #endif
1102
1103 /* the active group should be involved in auto normalize */
1104 static void do_weight_paint_auto_normalize_all_groups(MDeformVert *dvert, const int defbase_tot,
1105                                                       const char *vgroup_validmap, char do_auto_normalize)
1106 {
1107         if (do_auto_normalize == FALSE) {
1108                 return;
1109         }
1110         else {
1111                 float sum= 0.0f, fac;
1112                 unsigned int i, tot=0;
1113                 MDeformWeight *dw;
1114
1115                 for (i= dvert->totweight, dw= dvert->dw; i != 0; i--, dw++) {
1116                         if (dw->def_nr < defbase_tot) {
1117                                 if (vgroup_validmap[dw->def_nr]) {
1118                                         tot++;
1119                                         sum += dw->weight;
1120                                 }
1121                         }
1122                 }
1123
1124                 if ((tot == 0) || (sum == 1.0f) || (sum == 0.0f)) {
1125                         return;
1126                 }
1127
1128                 fac= 1.0f / sum;
1129
1130                 for (i= dvert->totweight, dw= dvert->dw; i != 0; i--, dw++) {
1131                         if (dw->def_nr < defbase_tot) {
1132                                 if (vgroup_validmap[dw->def_nr]) {
1133                                         dw->weight *= fac;
1134                                 }
1135                         }
1136                 }
1137         }
1138 }
1139
1140 /*
1141 See if the current deform vertex has a locked group
1142 */
1143 static char has_locked_group(MDeformVert *dvert, const int defbase_tot,
1144                              const char *bone_groups, const char *lock_flags)
1145 {
1146         int i;
1147         MDeformWeight *dw;
1148
1149         for (i= dvert->totweight, dw= dvert->dw; i != 0; i--, dw++) {
1150                 if (dw->def_nr < defbase_tot) {
1151                         if (bone_groups[dw->def_nr] && lock_flags[dw->def_nr] && dw->weight > 0.0f) {
1152                                 return TRUE;
1153                         }
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, const char *defbase_sel, const 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, const int defbase_tot, float change, const char *defbase_sel)
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, const int defbase_tot,
1251                                  char *change_status, const char change_me, int changeto,
1252                                  float totchange, float total_valid,
1253                                  char do_auto_normalize)
1254 {
1255         float was_change;
1256         float change;
1257         float oldval;
1258         MDeformWeight *ndw;
1259         int i;
1260         do {
1261                 /* assume there is no change until you see one */
1262                 was_change = FALSE;
1263                 /* change each group by the same amount each time */
1264                 change = totchange/total_valid;
1265                 for(i = 0; i < ndv->totweight && total_valid && totchange; i++) {
1266                         ndw = (ndv->dw+i);
1267
1268                         /* ignore anything outside the value range */
1269                         if (ndw->def_nr < defbase_tot) {
1270
1271                                 /* change only the groups with a valid status */
1272                                 if(change_status[ndw->def_nr] == change_me) {
1273                                         oldval = ndw->weight;
1274                                         /* if auto normalize is active, don't worry about upper bounds */
1275                                         if(do_auto_normalize == FALSE && ndw->weight + change > 1) {
1276                                                 totchange -= 1-ndw->weight;
1277                                                 ndw->weight = 1;
1278                                                 /* stop the changes to this group */
1279                                                 change_status[ndw->def_nr] = changeto;
1280                                                 total_valid--;
1281                                         }
1282                                         else if(ndw->weight + change < 0) { /* check the lower bound */
1283                                                 totchange -= ndw->weight;
1284                                                 ndw->weight = 0;
1285                                                 change_status[ndw->def_nr] = changeto;
1286                                                 total_valid--;
1287                                         }
1288                                         else {/* a perfectly valid change occurred to ndw->weight */
1289                                                 totchange -= change;
1290                                                 ndw->weight += change;
1291                                         }
1292                                         /* see if there was a change */
1293                                         if(oldval != ndw->weight) {
1294                                                 was_change = TRUE;
1295                                         }
1296                                 }
1297                         }
1298                 }
1299                 /* don't go again if there was no change, if there is no valid group,
1300                  * or there is no change left */
1301         } while(was_change && total_valid && totchange);
1302         /* left overs */
1303         return totchange;
1304 }
1305 static float get_mp_change(MDeformVert *odv, const int defbase_tot, const char *defbase_sel, float brush_change);
1306 /* observe the changes made to the weights of groups.
1307  * make sure all locked groups on the vertex have the same deformation
1308  * by moving the changes made to groups onto other unlocked groups */
1309 static void enforce_locks(MDeformVert *odv, MDeformVert *ndv,
1310                           const int defbase_tot, const char *defbase_sel,
1311                           const char *lock_flags, const char *vgroup_validmap,
1312                           char do_auto_normalize, char do_multipaint)
1313 {
1314         float totchange = 0.0f;
1315         float totchange_allowed = 0.0f;
1316         float left_over;
1317
1318         int total_valid = 0;
1319         int total_changed = 0;
1320         unsigned int i;
1321         MDeformWeight *ndw;
1322         MDeformWeight *odw;
1323
1324         float changed_sum = 0.0f;
1325
1326         char *change_status;
1327
1328         if(!lock_flags || !has_locked_group(ndv, defbase_tot, vgroup_validmap, lock_flags)) {
1329                 return;
1330         }
1331         /* record if a group was changed, unlocked and not changed, or locked */
1332         change_status = MEM_callocN(sizeof(char)*defbase_tot, "unlocked_unchanged");
1333
1334         for(i = 0; i < defbase_tot; i++) {
1335                 ndw = defvert_find_index(ndv, i);
1336                 odw = defvert_find_index(odv, i);
1337                 /* the weights are zero, so we can assume a lot */
1338                 if(!ndw || !odw) {
1339                         if (!lock_flags[i] && vgroup_validmap[i]) {
1340                                 defvert_verify_index(odv, i);
1341                                 defvert_verify_index(ndv, i);
1342                                 total_valid++;
1343                                 change_status[i] = 1; /* can be altered while redistributing */
1344                         }
1345                         continue;
1346                 }
1347                 /* locked groups should not be changed */
1348                 if(lock_flags[i]) {
1349                         ndw->weight = odw->weight;
1350                 }
1351                 else if(ndw->weight != odw->weight) { /* changed groups are handled here */
1352                         totchange += ndw->weight - odw->weight;
1353                         changed_sum += ndw->weight;
1354                         change_status[i] = 2; /* was altered already */
1355                         total_changed++;
1356                 } /* unchanged, unlocked bone groups are handled here */
1357                 else if (vgroup_validmap[i]) {
1358                         totchange_allowed += ndw->weight;
1359                         total_valid++;
1360                         change_status[i] = 1; /* can be altered while redistributing */
1361                 }
1362         }
1363         /* if there was any change, redistribute it */
1364         if(total_changed) {
1365                 /* auto normalize will allow weights to temporarily go above 1 in redistribution */
1366                 if(vgroup_validmap && total_changed < 0 && total_valid) {
1367                         totchange_allowed = total_valid;
1368                 }
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                 /* there needs to be change allowed, or you should not bother */
1378                 if(totchange_allowed) {
1379                         left_over = 0;
1380                         if(fabsf(totchange_allowed) < fabsf(totchange)) {
1381                                 /* this amount goes back onto the changed, unlocked weights */
1382                                 left_over = fabsf(fabsf(totchange) - fabsf(totchange_allowed));
1383                                 if(totchange > 0) {
1384                                         left_over *= -1;
1385                                 }
1386                         }
1387                         else {
1388                                 /* all of the change will be permitted */
1389                                 totchange_allowed = -totchange;
1390                         }
1391                         /* move the weight evenly between the allowed groups, move excess back onto the used groups based on the change */
1392                         totchange_allowed = redistribute_change(ndv, defbase_tot, change_status, 1, -1, totchange_allowed, total_valid, do_auto_normalize);
1393                         left_over += totchange_allowed;
1394                         if(left_over) {
1395                                 /* more than one nonzero weights were changed with the same ratio with multipaint, so keep them changed that way! */
1396                                 if(total_changed > 1 && do_multipaint) {
1397                                         float undo_change = get_mp_change(ndv, defbase_tot, defbase_sel, left_over);
1398                                         multipaint_selection(ndv, defbase_tot, undo_change, defbase_sel);
1399                                 }       
1400                                 /* or designatedw is still -1 put weight back as evenly as possible */
1401                                 else {
1402                                         redistribute_change(ndv, defbase_tot, change_status, 2, -2, left_over, total_changed, do_auto_normalize);
1403                                 }
1404                         }
1405                 }
1406                 else {
1407                         /* reset the weights */
1408                         unsigned int i;
1409                         MDeformWeight *dw_old= odv->dw;
1410                         MDeformWeight *dw_new= ndv->dw;
1411
1412                         for (i= odv->totweight; i != 0; i--, dw_old++, dw_new++) {
1413                                 dw_new->weight= dw_old->weight;
1414                         }
1415                 }
1416         }
1417
1418         MEM_freeN(change_status);
1419 }
1420
1421 /* multi-paint's initial, potential change is computed here based on the user's stroke */
1422 static float get_mp_change(MDeformVert *odv, const int defbase_tot, const char *defbase_sel, float brush_change)
1423 {
1424         float selwsum = 0.0f;
1425         unsigned int i;
1426         MDeformWeight *dw= odv->dw;
1427
1428         for (i= odv->totweight; i != 0; i--, dw++) {
1429                 if (dw->def_nr < defbase_tot) {
1430                         if(defbase_sel[dw->def_nr]) {
1431                                 selwsum += dw->weight;
1432                         }
1433                 }
1434         }
1435         if(selwsum && selwsum+brush_change > 0) {
1436                 return (selwsum+brush_change)/selwsum;
1437         }
1438         return 0.0f;
1439 }
1440
1441 /* change the weights back to the wv's weights
1442  * it assumes you already have the correct pointer index */
1443 static void defvert_reset_to_prev(MDeformVert *dv_prev, MDeformVert *dv)
1444 {
1445         MDeformWeight *dw= dv->dw;
1446         MDeformWeight *dw_prev;
1447         unsigned int i;
1448         for (i= dv->totweight; i != 0; i--, dw++) {
1449                 dw_prev= defvert_find_index(dv_prev, dw->def_nr);
1450                 /* if there was no w when there is a d, then the old weight was 0 */
1451                 dw->weight = dw_prev ? dw_prev->weight : 0.0f;
1452         }
1453 }
1454
1455 static void clamp_weights(MDeformVert *dvert)
1456 {
1457         MDeformWeight *dw= dvert->dw;
1458         unsigned int i;
1459         for (i= dvert->totweight; i != 0; i--, dw++) {
1460                 CLAMP(dw->weight, 0.0f, 1.0f);
1461         }
1462 }
1463
1464 /* struct to avoid passing many args each call to do_weight_paint_vertex()
1465  * this _could_ be made a part of the operators 'WPaintData' struct, or at
1466  * least a member, but for now keep its own struct, initialized on every
1467  * paint stroke update - campbell */
1468 typedef struct WeightPaintInfo {
1469
1470         int defbase_tot;
1471
1472         /* both must add up to 'defbase_tot' */
1473         int defbase_tot_sel;
1474         int defbase_tot_unsel;
1475
1476         int vgroup_active; /* (ob->actdef - 1) */
1477         int vgroup_mirror; /* mirror group or -1 */
1478
1479         const char *lock_flags;  /* boolean array for locked bones,
1480                                   * length of defbase_tot */
1481         const char *defbase_sel; /* boolean array for selected bones,
1482                                   * length of defbase_tot, cant be const because of how its passed */
1483
1484         const char *vgroup_validmap; /* same as WeightPaintData.vgroup_validmap,
1485                                       * only added here for convenience */
1486
1487         char do_flip;
1488         char do_multipaint;
1489         char do_auto_normalize;
1490 } WeightPaintInfo;
1491
1492 /* fresh start to make multi-paint and locking modular */
1493 /* returns TRUE if it thinks you need to reset the weights due to
1494  * normalizing while multi-painting
1495  *
1496  * note: this assumes dw->def_nr range has been checked by the caller
1497  */
1498 static int apply_mp_locks_normalize(Mesh *me, const WeightPaintInfo *wpi,
1499                                     const unsigned int index,
1500                                     MDeformWeight *dw, MDeformWeight *tdw,
1501                                     float change, float oldChange,
1502                                     float oldw, float neww)
1503 {
1504         MDeformVert *dv= &me->dvert[index];
1505         MDeformVert dv_test= {NULL};
1506
1507         dv_test.dw= MEM_dupallocN(dv->dw);
1508         dv_test.flag = dv->flag;
1509         dv_test.totweight = dv->totweight;
1510         /* do not multi-paint if a locked group is selected or the active group is locked
1511          * !lock_flags[dw->def_nr] helps if nothing is selected, but active group is locked */
1512         if ( (wpi->lock_flags == NULL) ||
1513              ((wpi->lock_flags[dw->def_nr] == FALSE) && /* def_nr range has to be checked for by caller */
1514               has_locked_group_selected(wpi->defbase_tot, wpi->defbase_sel, wpi->lock_flags) == FALSE))
1515         {
1516                 if(wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1517                         if(change && change!=1) {
1518                                 multipaint_selection(dv, wpi->defbase_tot, change, wpi->defbase_sel);
1519                         }
1520                 }
1521                 else { /* this lets users paint normally, but don't let them paint locked groups */
1522                         dw->weight = neww;
1523                 }
1524         }
1525         clamp_weights(dv);
1526
1527         enforce_locks(&dv_test, dv, wpi->defbase_tot, wpi->defbase_sel, wpi->lock_flags, wpi->vgroup_validmap, wpi->do_auto_normalize, wpi->do_multipaint);
1528
1529         do_weight_paint_auto_normalize_all_groups(dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->do_auto_normalize);
1530
1531         if(oldChange && wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1532                 if(tdw->weight != oldw) {
1533                         if(neww > oldw) {
1534                                 if(tdw->weight <= oldw) {
1535                                         MEM_freeN(dv_test.dw);
1536                                         return TRUE;
1537                                 }
1538                         }
1539                         else {
1540                                 if(tdw->weight >= oldw) {
1541                                         MEM_freeN(dv_test.dw);
1542                                         return TRUE;
1543                                 }
1544                         }
1545                 }
1546         }
1547         MEM_freeN(dv_test.dw);
1548         return FALSE;
1549 }
1550
1551 /* within the current dvert index, get the dw that is selected and has a weight
1552  * above 0, this helps multi-paint */
1553 static int get_first_selected_nonzero_weight(MDeformVert *dvert, const int defbase_tot, const char *defbase_sel)
1554 {
1555         int i;
1556         MDeformWeight *dw= dvert->dw;
1557         for(i=0; i< dvert->totweight; i++, dw++) {
1558                 if (dw->def_nr < defbase_tot) {
1559                         if (defbase_sel[dw->def_nr] && dw->weight > 0.0f) {
1560                                 return i;
1561                         }
1562                 }
1563         }
1564         return -1;
1565 }
1566
1567
1568 static char *wpaint_make_validmap(Object *ob);
1569
1570
1571 static void do_weight_paint_vertex( /* vars which remain the same for every vert */
1572                                    VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1573                                     /* vars which change on each stroke */
1574                                    const unsigned int index, float alpha, float paintweight
1575                                    )
1576 {
1577         Mesh *me= ob->data;
1578         MDeformVert *dv= &me->dvert[index];
1579         
1580         MDeformWeight *dw, *uw;
1581
1582         /* mirror vars */
1583         int index_mirr;
1584         int vgroup_mirr;
1585
1586         if(wp->flag & VP_ONLYVGROUP) {
1587                 dw= defvert_find_index(dv, wpi->vgroup_active);
1588                 uw= defvert_find_index(wp->wpaint_prev+index, wpi->vgroup_active);
1589         }
1590         else {
1591                 dw= defvert_verify_index(dv, wpi->vgroup_active);
1592                 uw= defvert_verify_index(wp->wpaint_prev+index, wpi->vgroup_active);
1593         }
1594
1595         if(dw==NULL || uw==NULL) {
1596                 return;
1597         }
1598
1599         /* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
1600         if (me->editflag & ME_EDIT_MIRROR_X) {
1601                 index_mirr = mesh_get_x_mirror_vert(ob, index);
1602                 vgroup_mirr = (wpi->vgroup_mirror != -1) ? wpi->vgroup_mirror : wpi->vgroup_active;
1603         }
1604         else {
1605                 index_mirr =  -1;
1606                 vgroup_mirr = -1; /* wont be used in this case, only set to avoid warnings */
1607         }
1608
1609         /* TODO: De-duplicate the simple weight paint - jason */
1610         /* ... or not, since its <10 SLOC - campbell */
1611
1612         /* If there are no locks or multipaint,
1613          * then there is no need to run the more complicated checks */
1614         if ( (wpi->do_multipaint == FALSE || wpi->defbase_tot_sel <= 1) &&
1615              (wpi->lock_flags == NULL || has_locked_group(dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags) == FALSE))
1616         {
1617                 wpaint_blend(wp, dw, uw, alpha, paintweight, wpi->do_flip, FALSE);
1618
1619                 /* x mirror painting */
1620                 if(index_mirr != -1) {
1621                         MDeformVert *dv_mirr = &me->dvert[index_mirr];
1622                         MDeformWeight *dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1623
1624                         /* copy, not paint again */
1625                         dw_mirr->weight = dw->weight;
1626                 }
1627
1628                 /* important to normalize after mirror, otherwise mirror gets weight
1629                  * which has already been scaled down in relation to other weights,
1630                  * then scales a second time [#26193]. Tricky multi-paint code doesn't
1631                  * suffer from this problem - campbell */
1632                 do_weight_paint_auto_normalize_all_groups(dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->do_auto_normalize);
1633         }
1634         else {
1635                 /* use locks and/or multipaint */
1636                 float oldw;
1637                 float neww;
1638                 float testw=0;
1639                 float change = 0;
1640                 float oldChange = 0;
1641                 int i;
1642                 MDeformWeight *tdw = NULL, *tuw;
1643                 MDeformVert dv_copy= {NULL};
1644
1645                 oldw = dw->weight;
1646                 wpaint_blend(wp, dw, uw, alpha, paintweight, wpi->do_flip, wpi->do_multipaint && wpi->defbase_tot_sel >1);
1647                 neww = dw->weight;
1648                 dw->weight = oldw;
1649                 
1650                 /* setup multi-paint */
1651                 if(wpi->defbase_tot_sel > 1 && wpi->do_multipaint) {
1652                         dv_copy.dw= MEM_dupallocN(dv->dw);
1653                         dv_copy.flag = dv->flag;
1654                         dv_copy.totweight = dv->totweight;
1655                         tdw = dw;
1656                         tuw = uw;
1657                         change = get_mp_change(&wp->wpaint_prev[index], wpi->defbase_tot, wpi->defbase_sel, neww - oldw);
1658                         if(change) {
1659                                 if(!tdw->weight) {
1660                                         i = get_first_selected_nonzero_weight(dv, wpi->defbase_tot, wpi->defbase_sel);
1661                                         if(i>=0) {
1662                                                 tdw = &(dv->dw[i]);
1663                                                 tuw = defvert_verify_index(&wp->wpaint_prev[index], tdw->def_nr);
1664                                         }
1665                                         else {
1666                                                 change = 0;
1667                                         }
1668                                 }
1669                                 if(change && tuw->weight && tuw->weight * change) {
1670                                         if(tdw->weight != tuw->weight) {
1671                                                 oldChange = tdw->weight/tuw->weight;
1672                                                 testw = tuw->weight*change;
1673                                                 if( testw > tuw->weight ) {
1674                                                         if(change > oldChange) {
1675                                                                 /* reset the weights and use the new change */
1676                                                                 defvert_reset_to_prev(wp->wpaint_prev+index, dv);
1677                                                         }
1678                                                         else {
1679                                                                 /* the old change was more significant, so set
1680                                                                  * the change to 0 so that it will not do another multi-paint */
1681                                                                 change = 0;
1682                                                         }
1683                                                 }
1684                                                 else {
1685                                                         if(change < oldChange) {
1686                                                                 defvert_reset_to_prev(wp->wpaint_prev+index, dv);
1687                                                         }
1688                                                         else {
1689                                                                 change = 0;
1690                                                         }
1691                                                 }
1692                                         }
1693                                 }
1694                                 else {
1695                                         change = 0;
1696                                 }
1697                         }
1698                 }
1699                 
1700                 if(apply_mp_locks_normalize(me, wpi, index, dw, tdw, change, oldChange, oldw, neww)) {
1701                         defvert_reset_to_prev(&dv_copy, dv);
1702                         change = 0;
1703                         oldChange = 0;
1704                 }
1705                 if(dv_copy.dw) {
1706                         MEM_freeN(dv_copy.dw);
1707                 }
1708 #if 0
1709                 /* dv may have been altered greatly */
1710                 dw = defvert_find_index(dv, vgroup);
1711 #else
1712                 dw = NULL; /* UNUSED after assignment, set to NULL to ensuyre we don't
1713                                 * use again, we thats needed un-ifdef the line above */
1714                 (void)dw;  /* quiet warnigns */
1715 #endif
1716
1717                 /* x mirror painting */
1718                 if(index_mirr != -1) {
1719                         MDeformVert *dv_mirr= &me->dvert[index_mirr];
1720                         MDeformWeight *dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1721                         /* copy, not paint again */
1722
1723                         /* dw_mirr->weight = dw->weight; */  /* TODO, explain the logic in not assigning weight! - campbell */
1724                         apply_mp_locks_normalize(me, wpi, index_mirr, dw_mirr, tdw, change, oldChange, oldw, neww);
1725                 }
1726         }
1727 }
1728
1729
1730 /* *************** set wpaint operator ****************** */
1731
1732 static int set_wpaint(bContext *C, wmOperator *UNUSED(op))              /* toggle */
1733 {               
1734         Object *ob= CTX_data_active_object(C);
1735         Scene *scene= CTX_data_scene(C);
1736         VPaint *wp= scene->toolsettings->wpaint;
1737         Mesh *me;
1738         
1739         me= get_mesh(ob);
1740         if(ob->id.lib || me==NULL) return OPERATOR_PASS_THROUGH;
1741         
1742         if(ob->mode & OB_MODE_WEIGHT_PAINT) ob->mode &= ~OB_MODE_WEIGHT_PAINT;
1743         else ob->mode |= OB_MODE_WEIGHT_PAINT;
1744         
1745         
1746         /* Weightpaint works by overriding colors in mesh,
1747                 * so need to make sure we recalc on enter and
1748                 * exit (exit needs doing regardless because we
1749                                 * should redeform).
1750                 */
1751         DAG_id_tag_update(&me->id, 0);
1752         
1753         if(ob->mode & OB_MODE_WEIGHT_PAINT) {
1754                 Object *par;
1755                 
1756                 if(wp==NULL)
1757                         wp= scene->toolsettings->wpaint= new_vpaint(1);
1758
1759                 paint_init(&wp->paint, PAINT_CURSOR_WEIGHT_PAINT);
1760                 paint_cursor_start(C, weight_paint_poll);
1761                 
1762                 mesh_octree_table(ob, NULL, NULL, 's');
1763                 
1764                 /* verify if active weight group is also active bone */
1765                 par= modifiers_isDeformedByArmature(ob);
1766                 if(par && (par->mode & OB_MODE_POSE)) {
1767                         bArmature *arm= par->data;
1768
1769                         if(arm->act_bone)
1770                                 ED_vgroup_select_by_name(ob, arm->act_bone->name);
1771                 }
1772         }
1773         else {
1774                 mesh_octree_table(NULL, NULL, NULL, 'e');
1775                 mesh_mirrtopo_table(NULL, 'e');
1776         }
1777         
1778         WM_event_add_notifier(C, NC_SCENE|ND_MODE, scene);
1779         
1780         return OPERATOR_FINISHED;
1781 }
1782
1783 /* for switching to/from mode */
1784 static int paint_poll_test(bContext *C)
1785 {
1786         Object *ob= CTX_data_active_object(C);
1787         if(CTX_data_edit_object(C))
1788                 return 0;
1789         if(CTX_data_active_object(C)==NULL)
1790                 return 0;
1791         if(!ob->data || ((ID *)ob->data)->lib)
1792                 return 0;
1793         return 1;
1794 }
1795
1796 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
1797 {
1798         
1799         /* identifiers */
1800         ot->name= "Weight Paint Mode";
1801         ot->idname= "PAINT_OT_weight_paint_toggle";
1802         
1803         /* api callbacks */
1804         ot->exec= set_wpaint;
1805         ot->poll= paint_poll_test;
1806         
1807         /* flags */
1808         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1809         
1810 }
1811
1812 /* ************ weight paint operator ********** */
1813
1814 struct WPaintData {
1815         ViewContext vc;
1816         int *indexar;
1817         int vgroup_active;
1818         int vgroup_mirror;
1819         float *vertexcosnos;
1820         float wpimat[3][3];
1821         
1822         /*variables for auto normalize*/
1823         const char *vgroup_validmap; /*stores if vgroups tie to deforming bones or not*/
1824         const char *lock_flags;
1825         int defbase_tot;
1826 };
1827
1828 static char *wpaint_make_validmap(Object *ob)
1829 {
1830         bDeformGroup *dg;
1831         ModifierData *md;
1832         char *vgroup_validmap;
1833         GHash *gh;
1834         int i, step1=1;
1835
1836         if(ob->defbase.first == NULL) {
1837                 return NULL;
1838         }
1839
1840         gh= BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "wpaint_make_validmap gh");
1841
1842         /*add all names to a hash table*/
1843         for (dg=ob->defbase.first; dg; dg=dg->next) {
1844                 BLI_ghash_insert(gh, dg->name, NULL);
1845         }
1846
1847         /*now loop through the armature modifiers and identify deform bones*/
1848         for (md = ob->modifiers.first; md; md= !md->next && step1 ? (step1=0), modifiers_getVirtualModifierList(ob) : md->next) {
1849                 if (!(md->mode & (eModifierMode_Realtime|eModifierMode_Virtual)))
1850                         continue;
1851
1852                 if (md->type == eModifierType_Armature) {
1853                         ArmatureModifierData *amd= (ArmatureModifierData*) md;
1854
1855                         if(amd->object && amd->object->pose) {
1856                                 bPose *pose= amd->object->pose;
1857                                 bPoseChannel *chan;
1858                                 
1859                                 for (chan=pose->chanbase.first; chan; chan=chan->next) {
1860                                         if (chan->bone->flag & BONE_NO_DEFORM)
1861                                                 continue;
1862
1863                                         if (BLI_ghash_haskey(gh, chan->name)) {
1864                                                 BLI_ghash_remove(gh, chan->name, NULL, NULL);
1865                                                 BLI_ghash_insert(gh, chan->name, SET_INT_IN_POINTER(1));
1866                                         }
1867                                 }
1868                         }
1869                 }
1870         }
1871
1872         vgroup_validmap= MEM_mallocN(BLI_ghash_size(gh), "wpaint valid map");
1873
1874         /*add all names to a hash table*/
1875         for (dg=ob->defbase.first, i=0; dg; dg=dg->next, i++) {
1876                 vgroup_validmap[i]= (BLI_ghash_lookup(gh, dg->name) != NULL);
1877         }
1878
1879         BLI_assert(i == BLI_ghash_size(gh));
1880
1881         BLI_ghash_free(gh, NULL, NULL);
1882
1883         return vgroup_validmap;
1884 }
1885
1886 static int wpaint_stroke_test_start(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1887 {
1888         Scene *scene= CTX_data_scene(C);
1889         struct PaintStroke *stroke = op->customdata;
1890         ToolSettings *ts= scene->toolsettings;
1891         VPaint *wp= ts->wpaint;
1892         Object *ob= CTX_data_active_object(C);
1893         struct WPaintData *wpd;
1894         Mesh *me;
1895         bDeformGroup *dg;
1896
1897         float mat[4][4], imat[4][4];
1898         
1899         if(scene->obedit) {
1900                 return FALSE;
1901         }
1902         
1903         me= get_mesh(ob);
1904         if(me==NULL || me->totface==0) return OPERATOR_PASS_THROUGH;
1905         
1906         /* if nothing was added yet, we make dverts and a vertex deform group */
1907         if (!me->dvert) {
1908                 ED_vgroup_data_create(&me->id);
1909                 WM_event_add_notifier(C, NC_GEOM|ND_DATA, me);
1910         }
1911
1912         /* this happens on a Bone select, when no vgroup existed yet */
1913         if (ob->actdef <= 0) {
1914                 Object *modob;
1915                 if((modob = modifiers_isDeformedByArmature(ob))) {
1916                         Bone *actbone= ((bArmature *)modob->data)->act_bone;
1917                         if(actbone) {
1918                                 bPoseChannel *pchan= get_pose_channel(modob->pose, actbone->name);
1919
1920                                 if(pchan) {
1921                                         bDeformGroup *dg= defgroup_find_name(ob, pchan->name);
1922                                         if(dg==NULL) {
1923                                                 dg= ED_vgroup_add_name(ob, pchan->name);        /* sets actdef */
1924                                         }
1925                                         else {
1926                                                 int actdef = 1 + BLI_findindex(&ob->defbase, dg);
1927                                                 BLI_assert(actdef >= 0);
1928                                                 ob->actdef= actdef;
1929                                         }
1930                                 }
1931                         }
1932                 }
1933         }
1934         if(ob->defbase.first==NULL) {
1935                 ED_vgroup_add(ob);
1936         }
1937
1938         /* ensure we dont try paint onto an invalid group */
1939         if (ob->actdef <= 0) {
1940                 BKE_report(op->reports, RPT_WARNING, "No active vertex group for painting, aborting");
1941                 return FALSE;
1942         }
1943
1944         /* check if we are attempting to paint onto a locked vertex group,
1945          * and other options disallow it from doing anything useful */
1946         dg = BLI_findlink(&ob->defbase, (ob->actdef-1));
1947         if (dg->flag & DG_LOCK_WEIGHT) {
1948                 BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
1949                 return FALSE;
1950         }
1951
1952         /* ALLOCATIONS! no return after this line */
1953         /* make mode data storage */
1954         wpd= MEM_callocN(sizeof(struct WPaintData), "WPaintData");
1955         paint_stroke_set_mode_data(stroke, wpd);
1956         view3d_set_viewcontext(C, &wpd->vc);
1957
1958         wpd->vgroup_active = ob->actdef - 1;
1959         wpd->vgroup_mirror = -1;
1960
1961         /* set up auto-normalize, and generate map for detecting which
1962          * vgroups affect deform bones*/
1963         wpd->defbase_tot = BLI_countlist(&ob->defbase);
1964         wpd->lock_flags = gen_lock_flags(ob, wpd->defbase_tot);
1965         if (ts->auto_normalize || ts->multipaint || wpd->lock_flags) {
1966                 wpd->vgroup_validmap = wpaint_make_validmap(ob);
1967         }
1968
1969         /* painting on subsurfs should give correct points too, this returns me->totvert amount */
1970         wpd->vertexcosnos= mesh_get_mapped_verts_nors(scene, ob);
1971         wpd->indexar= get_indexarray(me);
1972         copy_wpaint_prev(wp, me->dvert, me->totvert);
1973
1974         /* imat for normals */
1975         mult_m4_m4m4(mat, wpd->vc.rv3d->viewmat, ob->obmat);
1976         invert_m4_m4(imat, mat);
1977         copy_m3_m4(wpd->wpimat, imat);
1978
1979         /* if mirror painting, find the other group */
1980         if(me->editflag & ME_EDIT_MIRROR_X) {
1981                 wpd->vgroup_mirror = wpaint_mirror_vgroup_ensure(ob, wpd->vgroup_active);
1982         }
1983         
1984         return TRUE;
1985 }
1986
1987 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
1988 {
1989         const Scene *scene= CTX_data_scene(C);
1990         ToolSettings *ts= CTX_data_tool_settings(C);
1991         VPaint *wp= ts->wpaint;
1992         Brush *brush = paint_brush(&wp->paint);
1993         struct WPaintData *wpd= paint_stroke_mode_data(stroke);
1994         ViewContext *vc;
1995         Object *ob;
1996         Mesh *me;
1997         float mat[4][4];
1998         float paintweight;
1999         int *indexar;
2000         float totw;
2001         unsigned int index, totindex;
2002         float alpha;
2003         float mval[2];
2004         int use_vert_sel;
2005         char *defbase_sel;
2006
2007         const float pressure = RNA_float_get(itemptr, "pressure");
2008         const float brush_size_final = brush_size(brush) * (brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2009         const float brush_alpha_final = brush_alpha(brush) * (brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2010
2011         /* intentionally dont initialize as NULL, make sure we initialize all members below */
2012         WeightPaintInfo wpi;
2013
2014         /* cannot paint if there is no stroke data */
2015         if (wpd == NULL) {
2016                 /* XXX: force a redraw here, since even though we can't paint,
2017                  * at least view won't freeze until stroke ends */
2018                 ED_region_tag_redraw(CTX_wm_region(C));
2019                 return;
2020         }
2021                 
2022         vc= &wpd->vc;
2023         ob= vc->obact;
2024         me= ob->data;
2025         indexar= wpd->indexar;
2026         
2027         view3d_operator_needs_opengl(C);
2028                 
2029         /* load projection matrix */
2030         mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2031
2032         RNA_float_get_array(itemptr, "mouse", mval);
2033         mval[0]-= vc->ar->winrct.xmin;
2034         mval[1]-= vc->ar->winrct.ymin;
2035
2036
2037
2038         /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2039         wpi.defbase_tot=        wpd->defbase_tot;
2040         defbase_sel=            MEM_mallocN(wpi.defbase_tot*sizeof(char), "wpi.defbase_sel");
2041         wpi.defbase_tot_sel=    get_selected_defgroups(ob, defbase_sel, wpi.defbase_tot);
2042         wpi.defbase_sel=        defbase_sel; /* so we can stay const */
2043         if(wpi.defbase_tot_sel == 0 && ob->actdef > 0) wpi.defbase_tot_sel = 1;
2044
2045         wpi.defbase_tot_unsel=  wpi.defbase_tot - wpi.defbase_tot_sel;
2046         wpi.vgroup_active=      wpd->vgroup_active;
2047         wpi.vgroup_mirror=      wpd->vgroup_mirror;
2048         wpi.lock_flags=         wpd->lock_flags;
2049         wpi.vgroup_validmap=    wpd->vgroup_validmap;
2050         wpi.do_flip=            RNA_boolean_get(itemptr, "pen_flip");
2051         wpi.do_multipaint=      (ts->multipaint != 0);
2052         wpi.do_auto_normalize=  ((ts->auto_normalize != 0) && (wpi.vgroup_validmap != NULL));
2053         /* *** done setting up WeightPaintInfo *** */
2054
2055
2056
2057         swap_m4m4(wpd->vc.rv3d->persmat, mat);
2058
2059         use_vert_sel= (me->editflag & ME_EDIT_VERT_SEL) != 0;
2060
2061         /* which faces are involved */
2062         if(wp->flag & VP_AREA) {
2063                 /* Ugly hack, to avoid drawing vertex index when getting the face index buffer - campbell */
2064                 me->editflag &= ~ME_EDIT_VERT_SEL;
2065                 totindex= sample_backbuf_area(vc, indexar, me->totface, mval[0], mval[1], brush_size_final);
2066                 me->editflag |= use_vert_sel ? ME_EDIT_VERT_SEL : 0;
2067         }
2068         else {
2069                 indexar[0]= view3d_sample_backbuf(vc, mval[0], mval[1]);
2070                 if(indexar[0]) totindex= 1;
2071                 else totindex= 0;
2072         }
2073                         
2074         if(wp->flag & VP_COLINDEX) {
2075                 for(index=0; index<totindex; index++) {
2076                         if(indexar[index] && indexar[index]<=me->totface) {
2077                                 MFace *mface= ((MFace *)me->mface) + (indexar[index]-1);
2078                                                 
2079                                 if(mface->mat_nr!=ob->actcol-1) {
2080                                         indexar[index]= 0;
2081                                 }
2082                         }
2083                 }
2084         }
2085                         
2086         if((me->editflag & ME_EDIT_PAINT_MASK) && me->mface) {
2087                 for(index=0; index<totindex; index++) {
2088                         if(indexar[index] && indexar[index]<=me->totface) {
2089                                 MFace *mface= ((MFace *)me->mface) + (indexar[index]-1);
2090                                                 
2091                                 if((mface->flag & ME_FACE_SEL)==0) {
2092                                         indexar[index]= 0;
2093                                 }
2094                         }                                       
2095                 }
2096         }
2097                         
2098         /* make sure each vertex gets treated only once */
2099         /* and calculate filter weight */
2100         totw= 0.0f;
2101         if(brush->vertexpaint_tool==VP_BLUR) 
2102                 paintweight= 0.0f;
2103         else
2104                 paintweight= ts->vgroup_weight;
2105                         
2106         for(index=0; index<totindex; index++) {
2107                 if(indexar[index] && indexar[index]<=me->totface) {
2108                         MFace *mface= me->mface + (indexar[index]-1);
2109
2110                         if(use_vert_sel) {
2111                                 me->dvert[mface->v1].flag = (me->mvert[mface->v1].flag & SELECT);
2112                                 me->dvert[mface->v2].flag = (me->mvert[mface->v2].flag & SELECT);
2113                                 me->dvert[mface->v3].flag = (me->mvert[mface->v3].flag & SELECT);
2114                                 if(mface->v4) me->dvert[mface->v4].flag = (me->mvert[mface->v4].flag & SELECT);
2115                         }
2116                         else {
2117                                 me->dvert[mface->v1].flag= 1;
2118                                 me->dvert[mface->v2].flag= 1;
2119                                 me->dvert[mface->v3].flag= 1;
2120                                 if(mface->v4) me->dvert[mface->v4].flag= 1;
2121                         }
2122                                         
2123                         if(brush->vertexpaint_tool==VP_BLUR) {
2124                                 MDeformWeight *dw, *(*dw_func)(MDeformVert *, const int);
2125                                 unsigned int fidx= mface->v4 ? 3:2;
2126                                                 
2127                                 if(wp->flag & VP_ONLYVGROUP)
2128                                         dw_func= (MDeformWeight *(*)(MDeformVert *, const int))defvert_find_index;
2129                                 else
2130                                         dw_func= defvert_verify_index;
2131
2132                                 do {
2133                                         unsigned int vidx= *(&mface->v1 + fidx);
2134                                         const float fac = calc_vp_strength_dl(wp, vc, wpd->vertexcosnos+6*vidx, mval, brush_size_final);
2135                                         if (fac > 0.0f) {
2136                                                 dw = dw_func(&me->dvert[vidx], wpi.vgroup_active);
2137                                                 paintweight += dw ? (dw->weight * fac) : 0.0f;
2138                                                 totw += fac;
2139                                         }
2140
2141                                 } while (fidx--);
2142
2143                         }
2144                 }
2145         }
2146                         
2147         if (brush->vertexpaint_tool==VP_BLUR) {
2148                 paintweight /= totw;
2149         }
2150
2151         for(index=0; index<totindex; index++) {
2152                                 
2153                 if(indexar[index] && indexar[index]<=me->totface) {
2154                         MFace *mf= me->mface + (indexar[index]-1);
2155                         unsigned int fidx= mf->v4 ? 3:2;
2156                         do {
2157                                 unsigned int vidx= *(&mf->v1 + fidx);
2158
2159                                 if(me->dvert[vidx].flag) {
2160                                         alpha= calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos+6*vidx,
2161                                                                 mval, brush_size_final, brush_alpha_final);
2162                                         if(alpha) {
2163                                                 do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight);
2164                                         }
2165                                         me->dvert[vidx].flag= 0;
2166                                 }
2167                         } while (fidx--);
2168                 }
2169         }
2170
2171
2172         /* *** free wpi members */
2173         MEM_freeN((void *)wpi.defbase_sel);
2174         /* *** dont freeing wpi members */
2175
2176
2177         swap_m4m4(vc->rv3d->persmat, mat);
2178                         
2179         DAG_id_tag_update(ob->data, 0);
2180         ED_region_tag_redraw(vc->ar);
2181 }
2182
2183 static void wpaint_stroke_done(bContext *C, struct PaintStroke *stroke)
2184 {
2185         ToolSettings *ts= CTX_data_tool_settings(C);
2186         Object *ob= CTX_data_active_object(C);
2187         struct WPaintData *wpd= paint_stroke_mode_data(stroke);
2188         
2189         if(wpd) {
2190                 if(wpd->vertexcosnos)
2191                         MEM_freeN(wpd->vertexcosnos);
2192                 MEM_freeN(wpd->indexar);
2193                 
2194                 if (wpd->vgroup_validmap)
2195                         MEM_freeN((void *)wpd->vgroup_validmap);
2196                 if(wpd->lock_flags)
2197                         MEM_freeN((void *)wpd->lock_flags);
2198
2199                 MEM_freeN(wpd);
2200         }
2201         
2202         /* frees prev buffer */
2203         copy_wpaint_prev(ts->wpaint, NULL, 0);
2204         
2205         /* and particles too */
2206         if(ob->particlesystem.first) {
2207                 ParticleSystem *psys;
2208                 int i;
2209                 
2210                 for(psys= ob->particlesystem.first; psys; psys= psys->next) {
2211                         for(i=0; i<PSYS_TOT_VG; i++) {
2212                                 if(psys->vgroup[i]==ob->actdef) {
2213                                         psys->recalc |= PSYS_RECALC_RESET;
2214                                         break;
2215                                 }
2216                         }
2217                 }
2218         }
2219         
2220         DAG_id_tag_update(ob->data, 0);
2221 }
2222
2223
2224 static int wpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2225 {
2226         
2227         op->customdata = paint_stroke_new(C, NULL, wpaint_stroke_test_start,
2228                                           wpaint_stroke_update_step,
2229                                           wpaint_stroke_done, event->type);
2230         
2231         /* add modal handler */
2232         WM_event_add_modal_handler(C, op);
2233
2234         op->type->modal(C, op, event);
2235         
2236         return OPERATOR_RUNNING_MODAL;
2237 }
2238
2239 static int wpaint_cancel(bContext *C, wmOperator *op)
2240 {
2241         paint_stroke_cancel(C, op);
2242
2243         return OPERATOR_CANCELLED;
2244 }
2245
2246 void PAINT_OT_weight_paint(wmOperatorType *ot)
2247 {
2248         
2249         /* identifiers */
2250         ot->name= "Weight Paint";
2251         ot->idname= "PAINT_OT_weight_paint";
2252         
2253         /* api callbacks */
2254         ot->invoke= wpaint_invoke;
2255         ot->modal= paint_stroke_modal;
2256         /* ot->exec= vpaint_exec; <-- needs stroke property */
2257         ot->poll= weight_paint_poll;
2258         ot->cancel= wpaint_cancel;
2259         
2260         /* flags */
2261         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2262
2263         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2264 }
2265
2266 static int weight_paint_set_exec(bContext *C, wmOperator *UNUSED(op))
2267 {
2268         struct Scene *scene= CTX_data_scene(C);
2269         Object *obact = CTX_data_active_object(C);
2270
2271         wpaint_fill(scene->toolsettings->wpaint, obact, scene->toolsettings->vgroup_weight);
2272         ED_region_tag_redraw(CTX_wm_region(C)); /* XXX - should redraw all 3D views */
2273         return OPERATOR_FINISHED;
2274 }
2275
2276 void PAINT_OT_weight_set(wmOperatorType *ot)
2277 {
2278         /* identifiers */
2279         ot->name= "Set Weight";
2280         ot->idname= "PAINT_OT_weight_set";
2281
2282         /* api callbacks */
2283         ot->exec= weight_paint_set_exec;
2284         ot->poll= mask_paint_poll; /* it was facemask_paint_poll */
2285
2286         /* flags */
2287         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2288 }
2289
2290 /* ************ set / clear vertex paint mode ********** */
2291
2292
2293 static int set_vpaint(bContext *C, wmOperator *op)              /* toggle */
2294 {       
2295         Object *ob= CTX_data_active_object(C);
2296         Scene *scene= CTX_data_scene(C);
2297         VPaint *vp= scene->toolsettings->vpaint;
2298         Mesh *me;
2299         
2300         me= get_mesh(ob);
2301         
2302         if(me==NULL || object_data_is_libdata(ob)) {
2303                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2304                 return OPERATOR_PASS_THROUGH;
2305         }
2306         
2307         if(me && me->mcol==NULL) make_vertexcol(ob);
2308         
2309         /* toggle: end vpaint */
2310         if(ob->mode & OB_MODE_VERTEX_PAINT) {
2311                 
2312                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2313         }
2314         else {
2315                 ob->mode |= OB_MODE_VERTEX_PAINT;
2316                 /* Turn off weight painting */
2317                 if (ob->mode & OB_MODE_WEIGHT_PAINT)
2318                         set_wpaint(C, op);
2319                 
2320                 if(vp==NULL)
2321                         vp= scene->toolsettings->vpaint= new_vpaint(0);
2322                 
2323                 paint_cursor_start(C, vertex_paint_poll);
2324
2325                 paint_init(&vp->paint, PAINT_CURSOR_VERTEX_PAINT);
2326         }
2327         
2328         if (me)
2329                 /* update modifier stack for mapping requirements */
2330                 DAG_id_tag_update(&me->id, 0);
2331         
2332         WM_event_add_notifier(C, NC_SCENE|ND_MODE, scene);
2333         
2334         return OPERATOR_FINISHED;
2335 }
2336
2337 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2338 {
2339         
2340         /* identifiers */
2341         ot->name= "Vertex Paint Mode";
2342         ot->idname= "PAINT_OT_vertex_paint_toggle";
2343         
2344         /* api callbacks */
2345         ot->exec= set_vpaint;
2346         ot->poll= paint_poll_test;
2347         
2348         /* flags */
2349         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2350 }
2351
2352
2353
2354 /* ********************** vertex paint operator ******************* */
2355
2356 /* Implementation notes:
2357
2358 Operator->invoke()
2359   - validate context (add mcol)
2360   - create customdata storage
2361   - call paint once (mouse click)
2362   - add modal handler 
2363
2364 Operator->modal()
2365   - for every mousemove, apply vertex paint
2366   - exit on mouse release, free customdata
2367         (return OPERATOR_FINISHED also removes handler and operator)
2368
2369 For future:
2370   - implement a stroke event (or mousemove with past positons)
2371   - revise whether op->customdata should be added in object, in set_vpaint
2372
2373 */
2374
2375 typedef struct VPaintData {
2376         ViewContext vc;
2377         unsigned int paintcol;
2378         int *indexar;
2379         float *vertexcosnos;
2380         float vpimat[3][3];
2381 } VPaintData;
2382
2383 static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, wmEvent *UNUSED(event))
2384 {
2385         ToolSettings *ts= CTX_data_tool_settings(C);
2386         struct PaintStroke *stroke = op->customdata;
2387         VPaint *vp= ts->vpaint;
2388         struct VPaintData *vpd;
2389         Object *ob= CTX_data_active_object(C);
2390         Mesh *me;
2391         float mat[4][4], imat[4][4];
2392
2393         /* context checks could be a poll() */
2394         me= get_mesh(ob);
2395         if(me==NULL || me->totface==0) return OPERATOR_PASS_THROUGH;
2396         
2397         if(me->mcol==NULL) make_vertexcol(ob);
2398         if(me->mcol==NULL) return OPERATOR_CANCELLED;
2399         
2400         /* make mode data storage */
2401         vpd= MEM_callocN(sizeof(struct VPaintData), "VPaintData");
2402         paint_stroke_set_mode_data(stroke, vpd);
2403         view3d_set_viewcontext(C, &vpd->vc);
2404         
2405         vpd->vertexcosnos= mesh_get_mapped_verts_nors(vpd->vc.scene, ob);
2406         vpd->indexar= get_indexarray(me);
2407         vpd->paintcol= vpaint_get_current_col(vp);
2408         
2409         /* for filtering */
2410         copy_vpaint_prev(vp, (unsigned int *)me->mcol, me->totface);
2411         
2412         /* some old cruft to sort out later */
2413         mult_m4_m4m4(mat, vpd->vc.rv3d->viewmat, ob->obmat);
2414         invert_m4_m4(imat, mat);
2415         copy_m3_m4(vpd->vpimat, imat);
2416
2417         return 1;
2418 }
2419
2420 static void vpaint_paint_face(VPaint *vp, VPaintData *vpd, Object *ob,
2421                               const unsigned int index, const float mval[2],
2422                               const float brush_size_final, const float brush_alpha_final,
2423                               int UNUSED(flip))
2424 {
2425         ViewContext *vc = &vpd->vc;
2426         Brush *brush = paint_brush(&vp->paint);
2427         Mesh *me = get_mesh(ob);
2428         MFace *mface= &me->mface[index];
2429         unsigned int *mcol= ((unsigned int*)me->mcol) + 4*index;
2430         unsigned int *mcolorig= ((unsigned int*)vp->vpaint_prev) + 4*index;
2431         float alpha;
2432         int i;
2433         
2434         if((vp->flag & VP_COLINDEX && mface->mat_nr!=ob->actcol-1) ||
2435            ((me->editflag & ME_EDIT_PAINT_MASK) && !(mface->flag & ME_FACE_SEL)))
2436                 return;
2437
2438         if(brush->vertexpaint_tool==VP_BLUR) {
2439                 unsigned int fcol1= mcol_blend( mcol[0], mcol[1], 128);
2440                 if(mface->v4) {
2441                         unsigned int fcol2= mcol_blend( mcol[2], mcol[3], 128);
2442                         vpd->paintcol= mcol_blend( fcol1, fcol2, 128);
2443                 }
2444                 else {
2445                         vpd->paintcol= mcol_blend( mcol[2], fcol1, 170);
2446                 }
2447                 
2448         }
2449
2450         for(i = 0; i < (mface->v4 ? 4 : 3); ++i) {
2451                 alpha = calc_vp_alpha_dl(vp, vc, vpd->vpimat, vpd->vertexcosnos+6*(&mface->v1)[i],
2452                                          mval, brush_size_final, brush_alpha_final);
2453                 if(alpha) {
2454                         vpaint_blend(vp, mcol+i, mcolorig+i, vpd->paintcol, (int)(alpha*255.0f));
2455                 }
2456         }
2457 }
2458
2459 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2460 {
2461         const Scene *scene= CTX_data_scene(C);
2462         ToolSettings *ts= CTX_data_tool_settings(C);
2463         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2464         VPaint *vp= ts->vpaint;
2465         Brush *brush = paint_brush(&vp->paint);
2466         ViewContext *vc= &vpd->vc;
2467         Object *ob= vc->obact;
2468         Mesh *me= ob->data;
2469         float mat[4][4];
2470         int *indexar= vpd->indexar;
2471         int totindex, index, flip;
2472         float mval[2];
2473
2474         const float pressure = RNA_float_get(itemptr, "pressure");
2475         const float brush_size_final = brush_size(brush) * (brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2476         const float brush_alpha_final = brush_alpha(brush) * (brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2477
2478         RNA_float_get_array(itemptr, "mouse", mval);
2479         flip = RNA_boolean_get(itemptr, "pen_flip");
2480                         
2481         view3d_operator_needs_opengl(C);
2482                         
2483         /* load projection matrix */
2484         mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2485
2486         mval[0]-= vc->ar->winrct.xmin;
2487         mval[1]-= vc->ar->winrct.ymin;
2488
2489                         
2490         /* which faces are involved */
2491         if(vp->flag & VP_AREA) {
2492                 totindex= sample_backbuf_area(vc, indexar, me->totface, mval[0], mval[1], brush_size_final);
2493         }
2494         else {
2495                 indexar[0]= view3d_sample_backbuf(vc, mval[0], mval[1]);
2496                 if(indexar[0]) totindex= 1;
2497                 else totindex= 0;
2498         }
2499                         
2500         swap_m4m4(vc->rv3d->persmat, mat);
2501                         
2502         for(index=0; index<totindex; index++) {                         
2503                 if (indexar[index] && indexar[index]<=me->totface) {
2504                         vpaint_paint_face(vp, vpd, ob, indexar[index]-1, mval, brush_size_final, brush_alpha_final, flip);
2505                 }
2506         }
2507                                                 
2508         swap_m4m4(vc->rv3d->persmat, mat);
2509
2510         /* was disabled because it is slow, but necessary for blur */
2511         if(brush->vertexpaint_tool == VP_BLUR)
2512                 do_shared_vertexcol(me);
2513                         
2514         ED_region_tag_redraw(vc->ar);
2515                         
2516         DAG_id_tag_update(ob->data, 0);
2517 }
2518
2519 static void vpaint_stroke_done(bContext *C, struct PaintStroke *stroke)
2520 {
2521         ToolSettings *ts= CTX_data_tool_settings(C);
2522         struct VPaintData *vpd= paint_stroke_mode_data(stroke);
2523         
2524         if(vpd->vertexcosnos)
2525                 MEM_freeN(vpd->vertexcosnos);
2526         MEM_freeN(vpd->indexar);
2527         
2528         /* frees prev buffer */
2529         copy_vpaint_prev(ts->vpaint, NULL, 0);
2530         
2531         MEM_freeN(vpd);
2532 }
2533
2534 static int vpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2535 {
2536         
2537         op->customdata = paint_stroke_new(C, NULL, vpaint_stroke_test_start,
2538                                           vpaint_stroke_update_step,
2539                                           vpaint_stroke_done, event->type);
2540         
2541         /* add modal handler */
2542         WM_event_add_modal_handler(C, op);
2543
2544         op->type->modal(C, op, event);
2545         
2546         return OPERATOR_RUNNING_MODAL;
2547 }
2548
2549 static int vpaint_cancel(bContext *C, wmOperator *op)
2550 {
2551         paint_stroke_cancel(C, op);
2552
2553         return OPERATOR_CANCELLED;
2554 }
2555
2556 void PAINT_OT_vertex_paint(wmOperatorType *ot)
2557 {
2558         /* identifiers */
2559         ot->name= "Vertex Paint";
2560         ot->idname= "PAINT_OT_vertex_paint";
2561         
2562         /* api callbacks */
2563         ot->invoke= vpaint_invoke;
2564         ot->modal= paint_stroke_modal;
2565         /* ot->exec= vpaint_exec; <-- needs stroke property */
2566         ot->poll= vertex_paint_poll;
2567         ot->cancel= vpaint_cancel;
2568         
2569         /* flags */
2570         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2571
2572         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2573 }
2574
2575 /* ********************** weight from bones operator ******************* */
2576
2577 static int weight_from_bones_poll(bContext *C)
2578 {
2579         Object *ob= CTX_data_active_object(C);
2580
2581         return (ob && (ob->mode & OB_MODE_WEIGHT_PAINT) && modifiers_isDeformedByArmature(ob));
2582 }
2583
2584 static int weight_from_bones_exec(bContext *C, wmOperator *op)
2585 {
2586         Scene *scene= CTX_data_scene(C);
2587         Object *ob= CTX_data_active_object(C);
2588         Object *armob= modifiers_isDeformedByArmature(ob);
2589         Mesh *me= ob->data;
2590         int type= RNA_enum_get(op->ptr, "type");
2591
2592         create_vgroups_from_armature(op->reports, scene, ob, armob, type, (me->editflag & ME_EDIT_MIRROR_X));
2593
2594         DAG_id_tag_update(&me->id, 0);
2595         WM_event_add_notifier(C, NC_GEOM|ND_DATA, me);
2596
2597         return OPERATOR_FINISHED;
2598 }
2599
2600 void PAINT_OT_weight_from_bones(wmOperatorType *ot)
2601 {
2602         static EnumPropertyItem type_items[]= {
2603                 {ARM_GROUPS_AUTO, "AUTOMATIC", 0, "Automatic", "Automatic weights froms bones"},
2604                 {ARM_GROUPS_ENVELOPE, "ENVELOPES", 0, "From Envelopes", "Weights from envelopes with user defined radius"},
2605                 {0, NULL, 0, NULL, NULL}};
2606
2607         /* identifiers */
2608         ot->name= "Weight from Bones";
2609         ot->idname= "PAINT_OT_weight_from_bones";
2610         
2611         /* api callbacks */
2612         ot->exec= weight_from_bones_exec;
2613         ot->invoke= WM_menu_invoke;
2614         ot->poll= weight_from_bones_poll;
2615         
2616         /* flags */
2617         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2618
2619         /* properties */
2620         ot->prop= RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "Method to use for assigning weights");
2621 }
2622