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