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