fix compile errors for previous merge
[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                 /* there needs to be change allowed, or you should not bother */
1425                 if(totchange_allowed) {
1426                         /* the way you modify the unlocked+unchanged groups is different depending
1427                          * on whether or not you are painting the weight(s) up or down */
1428                         if(totchange < 0) {
1429                                 totchange_allowed = total_valid - totchange_allowed;
1430                         }
1431                         else {
1432                                 totchange_allowed *= -1;
1433                         }
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(change_status[ndw->def_nr] == 2) {
1458                                                         odw2 = &odv->dw[i];
1459                                                         ndw2 = &ndv->dw[i];
1460                                                         if(!designatedw_changed) {
1461                                                                 ndw->weight = (totchange_allowed + odw->weight + odw2->weight)/(1.0f + ndw2->weight/ndw->weight);
1462                                                                 designatedw_changed = TRUE;
1463                                                         }
1464                                                         ndw2->weight = ndw->weight * ndw2->weight / storedw;
1465                                                 }
1466                                         }
1467                                 }
1468                                 /* a weight was changed to zero, only one weight was changed,
1469                                  * or designatedw is still -1 put weight back as evenly as possible */
1470                                 else {
1471                                         redistribute_change(ndv, change_status, 2, -2, left_over, total_changed, do_auto_normalize);
1472                                 }
1473                         }
1474                 }
1475                 else {
1476                         /* reset the weights */
1477                         unsigned int i;
1478                         MDeformWeight *dw_old= odv->dw;
1479                         MDeformWeight *dw_new= ndv->dw;
1480
1481                         for (i= odv->totweight; i != 0; i--, dw_old++, dw_new++) {
1482                                 dw_new->weight= dw_old->weight;
1483                         }
1484                 }
1485         }
1486
1487         MEM_freeN(change_status);
1488 }
1489
1490 /* multi-paint's initial, potential change is computed here based on the user's stroke */
1491 static float get_mp_change(MDeformVert *odv, char *defbase_sel, float brush_change)
1492 {
1493         float selwsum = 0.0f;
1494         unsigned int i;
1495         MDeformWeight *dw= odv->dw;
1496
1497         for (i= odv->totweight; i != 0; i--, dw++) {
1498                 if(defbase_sel[dw->def_nr]) {
1499                         selwsum += dw->weight;
1500                 }
1501         }
1502         if(selwsum && selwsum+brush_change > 0) {
1503                 return (selwsum+brush_change)/selwsum;
1504         }
1505         return 0.0f;
1506 }
1507
1508 /* change the weights back to the wv's weights
1509  * it assumes you already have the correct pointer index */
1510 static void reset_to_prev(MDeformVert *wv, MDeformVert *dvert)
1511 {
1512         MDeformWeight *dw= dvert->dw;
1513         MDeformWeight *w;
1514         unsigned int i;
1515         for (i= dvert->totweight; i != 0; i--, dw++) {
1516                 w= defvert_find_index(wv, dw->def_nr);
1517                 /* if there was no w when there is a d, then the old weight was 0 */
1518                 dw->weight = w ? w->weight : 0.0f;
1519         }
1520 }
1521
1522 static void clamp_weights(MDeformVert *dvert)
1523 {
1524         MDeformWeight *dw= dvert->dw;
1525         unsigned int i;
1526         for (i= dvert->totweight; i != 0; i--, dw++) {
1527                 CLAMP(dw->weight, 0.0f, 1.0f);
1528         }
1529 }
1530
1531 /* struct to avoid passing many args each call to do_weight_paint_vertex()
1532  * this _could_ be made a part of the operators 'WPaintData' struct, or at
1533  * least a member, but for now keep its own struct, initialized on every
1534  * paint stroke update - campbell */
1535 typedef struct WeightPaintInfo {
1536
1537         int defbase_tot;
1538
1539         /* both must add up to 'defbase_tot' */
1540         int defbase_tot_sel;
1541         int defbase_tot_unsel;
1542
1543         int vgroup_mirror; /* mirror group or -1 */
1544
1545         char *lock_flags;  /* boolean array for locked bones,
1546                                                 * length of defbase_tot */
1547         char *defbase_sel; /* boolean array for selected bones,
1548                                                 * length of defbase_tot */
1549
1550         char *vgroup_validmap; /* same as WeightPaintData.vgroup_validmap,
1551                                 * only added here for convenience */
1552
1553         char do_flip;
1554         char do_multipaint;
1555         char do_auto_normalize;
1556 } WeightPaintInfo;
1557
1558 /* fresh start to make multi-paint and locking modular */
1559 /* returns TRUE if it thinks you need to reset the weights due to
1560  * normalizing while multi-painting */
1561 static int apply_mp_locks_normalize(Mesh *me, const WeightPaintInfo *wpi,
1562                                     const unsigned int index,
1563                                     MDeformWeight *dw, MDeformWeight *tdw,
1564                                     float change, float oldChange,
1565                                     float oldw, float neww)
1566 {
1567         MDeformVert *dv= &me->dvert[index];
1568         MDeformVert dv_test= {NULL};
1569
1570         dv_test.dw= MEM_dupallocN(dv->dw);
1571         dv_test.flag = dv->flag;
1572         dv_test.totweight = dv->totweight;
1573         /* do not multi-paint if a locked group is selected or the active group is locked
1574          * !lock_flags[dw->def_nr] helps if nothing is selected, but active group is locked */
1575         if(             (wpi->lock_flags == NULL) ||
1576                 ((wpi->lock_flags[dw->def_nr] == FALSE) &&
1577                  has_locked_group_selected(wpi->defbase_tot, wpi->defbase_sel, wpi->lock_flags) == FALSE))
1578         {
1579                 if(wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1580                         if(change && change!=1) {
1581                                 multipaint_selection(dv, change, wpi->defbase_sel, wpi->defbase_tot);
1582                         }
1583                 }
1584                 else { /* this lets users paint normally, but don't let them paint locked groups */
1585                         dw->weight = neww;
1586                 }
1587         }
1588         clamp_weights(dv);
1589
1590         enforce_locks(&dv_test, dv, wpi->defbase_tot, wpi->lock_flags, wpi->vgroup_validmap, wpi->do_auto_normalize);
1591
1592         do_weight_paint_auto_normalize_all_groups(dv, wpi->vgroup_validmap, wpi->do_auto_normalize);
1593
1594         if(oldChange && wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1595                 if(tdw->weight != oldw) {
1596                         if(neww > oldw) {
1597                                 if(tdw->weight <= oldw) {
1598                                         MEM_freeN(dv_test.dw);
1599                                         return TRUE;
1600                                 }
1601                         }
1602                         else {
1603                                 if(tdw->weight >= oldw) {
1604                                         MEM_freeN(dv_test.dw);
1605                                         return TRUE;
1606                                 }
1607                         }
1608                 }
1609         }
1610         MEM_freeN(dv_test.dw);
1611         return FALSE;
1612 }
1613
1614 /* within the current dvert index, get the dw that is selected and has a weight
1615  * above 0, this helps multi-paint */
1616 static int get_first_selected_nonzero_weight(MDeformVert *dvert, char *defbase_sel)
1617 {
1618         int i;
1619         MDeformWeight *dw= dvert->dw;
1620         for(i=0; i< dvert->totweight; i++, dw++) {
1621                 if(defbase_sel[dw->def_nr] && dw->weight > 0.0f) {
1622                         return i;
1623                 }
1624         }
1625         return -1;
1626 }
1627
1628
1629 static char *wpaint_make_validmap(Object *ob);
1630
1631
1632 static void do_weight_paint_vertex( /* vars which remain the same for every vert */
1633                                    VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1634                                     /* vars which change on each stroke */
1635                                    const unsigned int index, float alpha, float paintweight
1636                                    )
1637 {
1638         Mesh *me= ob->data;
1639         MDeformVert *dv= &me->dvert[index];
1640         
1641         MDeformWeight *dw, *uw;
1642         int vgroup= ob->actdef-1;
1643
1644         if(wp->flag & VP_ONLYVGROUP) {
1645                 dw= defvert_find_index(dv, vgroup);
1646                 uw= defvert_find_index(wp->wpaint_prev+index, vgroup);
1647         }
1648         else {
1649                 dw= defvert_verify_index(dv, vgroup);
1650                 uw= defvert_verify_index(wp->wpaint_prev+index, vgroup);
1651         }
1652
1653         if(dw==NULL || uw==NULL) {
1654                 return;
1655         }
1656
1657         /* TODO: De-duplicate the simple weight paint - jason */
1658         /* ... or not, since its <10 SLOC - campbell */
1659
1660         /* If there are no locks or multipaint,
1661          * then there is no need to run the more complicated checks */
1662         if(     (wpi->do_multipaint == FALSE || wpi->defbase_tot_sel <= 1) &&
1663                 (wpi->lock_flags == NULL || has_locked_group(dv, wpi->lock_flags) == FALSE))
1664         {
1665                 wpaint_blend(wp, dw, uw, alpha, paintweight, wpi->do_flip, FALSE);
1666
1667                 if(me->editflag & ME_EDIT_MIRROR_X) {   /* x mirror painting */
1668                         int index_mirr= mesh_get_x_mirror_vert(ob, index);
1669                         if(index_mirr != -1) {
1670                                 MDeformVert *dv_mirr= &me->dvert[index_mirr];
1671                                 /* copy, not paint again */
1672                                 uw= defvert_verify_index(dv_mirr, (wpi->vgroup_mirror != -1) ? wpi->vgroup_mirror : vgroup);
1673                                 uw->weight= dw->weight;
1674                         }
1675                 }
1676
1677                 /* important to normalize after mirror, otherwise mirror gets weight
1678                  * which has already been scaled down in relation to other weights,
1679                  * then scales a second time [#26193]. Tricky multi-paint code doesn't
1680                  * suffer from this problem - campbell */
1681                 do_weight_paint_auto_normalize_all_groups(dv, wpi->vgroup_validmap, wpi->do_auto_normalize);
1682         }
1683         else {
1684                 /* use locks and/or multipaint */
1685                 float oldw;
1686                 float neww;
1687                 float testw=0;
1688                 float change = 0;
1689                 float oldChange = 0;
1690                 int i;
1691                 MDeformWeight *tdw = NULL, *tuw;
1692                 MDeformVert dv_copy= {NULL};
1693
1694                 oldw = dw->weight;
1695                 wpaint_blend(wp, dw, uw, alpha, paintweight, wpi->do_flip, wpi->do_multipaint && wpi->defbase_tot_sel >1);
1696                 neww = dw->weight;
1697                 dw->weight = oldw;
1698                 
1699                 /* setup multi-paint */
1700                 if(wpi->defbase_tot_sel > 1 && wpi->do_multipaint) {
1701                         dv_copy.dw= MEM_dupallocN(dv->dw);
1702                         dv_copy.flag = dv->flag;
1703                         dv_copy.totweight = dv->totweight;
1704                         tdw = dw;
1705                         tuw = uw;
1706                         change = get_mp_change(wp->wpaint_prev+index, wpi->defbase_sel, neww - oldw);
1707                         if(change) {
1708                                 if(!tdw->weight) {
1709                                         i = get_first_selected_nonzero_weight(dv, wpi->defbase_sel);
1710                                         if(i>=0) {
1711                                                 tdw = &(dv->dw[i]);
1712                                                 tuw = defvert_verify_index(wp->wpaint_prev+index, tdw->def_nr);
1713                                         }
1714                                         else {
1715                                                 change = 0;
1716                                         }
1717                                 }
1718                                 if(change && tuw->weight && tuw->weight * change) {
1719                                         if(tdw->weight != tuw->weight) {
1720                                                 oldChange = tdw->weight/tuw->weight;
1721                                                 testw = tuw->weight*change;
1722                                                 if( testw > tuw->weight ) {
1723                                                         if(change > oldChange) {
1724                                                                 /* reset the weights and use the new change */
1725                                                                 reset_to_prev(wp->wpaint_prev+index, dv);
1726                                                         }
1727                                                         else {
1728                                                                 /* the old change was more significant, so set
1729                                                                  * the change to 0 so that it will not do another multi-paint */
1730                                                                 change = 0;
1731                                                         }
1732                                                 }
1733                                                 else {
1734                                                         if(change < oldChange) {
1735                                                                 reset_to_prev(wp->wpaint_prev+index, dv);
1736                                                         }
1737                                                         else {
1738                                                                 change = 0;
1739                                                         }
1740                                                 }
1741                                         }
1742                                 }
1743                                 else {
1744                                         change = 0;
1745                                 }
1746                         }
1747                 }
1748                 
1749                 if(apply_mp_locks_normalize(me, wpi, index, dw, tdw, change, oldChange, oldw, neww)) {
1750                         reset_to_prev(&dv_copy, dv);
1751                         change = 0;
1752                         oldChange = 0;
1753                 }
1754                 if(dv_copy.dw) {
1755                         MEM_freeN(dv_copy.dw);
1756                 }
1757                 /* dv may have been altered greatly */
1758                 dw = defvert_find_index(dv, vgroup);
1759
1760                 if(me->editflag & ME_EDIT_MIRROR_X) {   /* x mirror painting */
1761                         int index_mirr= mesh_get_x_mirror_vert(ob, index);
1762                         if(index_mirr != -1) {
1763                                 MDeformVert *dv_mirr= &me->dvert[index_mirr];
1764                                 /* copy, not paint again */
1765                                 uw= defvert_verify_index(dv_mirr, (wpi->vgroup_mirror != -1) ? wpi->vgroup_mirror : vgroup);
1766                                 //uw->weight= dw->weight;
1767                                 apply_mp_locks_normalize(me, wpi, index_mirr, uw, tdw, change, oldChange, oldw, neww);
1768                         }
1769                 }
1770         }
1771 }
1772
1773
1774 /* *************** set wpaint operator ****************** */
1775
1776 static int set_wpaint(bContext *C, wmOperator *UNUSED(op))              /* toggle */
1777 {               
1778         Object *ob= CTX_data_active_object(C);
1779         Scene *scene= CTX_data_scene(C);
1780         VPaint *wp= scene->toolsettings->wpaint;
1781         Mesh *me;
1782         
1783         me= get_mesh(ob);
1784         if(ob->id.lib || me==NULL) return OPERATOR_PASS_THROUGH;
1785         
1786         if(ob->mode & OB_MODE_WEIGHT_PAINT) ob->mode &= ~OB_MODE_WEIGHT_PAINT;
1787         else ob->mode |= OB_MODE_WEIGHT_PAINT;
1788         
1789         
1790         /* Weightpaint works by overriding colors in mesh,
1791                 * so need to make sure we recalc on enter and
1792                 * exit (exit needs doing regardless because we
1793                                 * should redeform).
1794                 */
1795         DAG_id_tag_update(&me->id, 0);
1796         
1797         if(ob->mode & OB_MODE_WEIGHT_PAINT) {
1798                 Object *par;
1799                 
1800                 if(wp==NULL)
1801                         wp= scene->toolsettings->wpaint= new_vpaint(1);
1802
1803                 paint_init(&wp->paint, PAINT_CURSOR_WEIGHT_PAINT);
1804                 paint_cursor_start(C, weight_paint_poll);
1805                 
1806                 mesh_octree_table(ob, NULL, NULL, 's');
1807                 
1808                 /* verify if active weight group is also active bone */
1809                 par= modifiers_isDeformedByArmature(ob);
1810                 if(par && (par->mode & OB_MODE_POSE)) {
1811                         bArmature *arm= par->data;
1812
1813                         if(arm->act_bone)
1814                                 ED_vgroup_select_by_name(ob, arm->act_bone->name);
1815                 }
1816         }
1817         else {
1818                 mesh_octree_table(NULL, NULL, NULL, 'e');
1819                 mesh_mirrtopo_table(NULL, 'e');
1820         }
1821         
1822         WM_event_add_notifier(C, NC_SCENE|ND_MODE, scene);
1823         
1824         return OPERATOR_FINISHED;
1825 }
1826
1827 /* for switching to/from mode */
1828 static int paint_poll_test(bContext *C)
1829 {
1830         if(CTX_data_edit_object(C))
1831                 return 0;
1832         if(CTX_data_active_object(C)==NULL)
1833                 return 0;
1834         return 1;
1835 }
1836
1837 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
1838 {
1839         
1840         /* identifiers */
1841         ot->name= "Weight Paint Mode";
1842         ot->idname= "PAINT_OT_weight_paint_toggle";
1843         
1844         /* api callbacks */
1845         ot->exec= set_wpaint;
1846         ot->poll= paint_poll_test;
1847         
1848         /* flags */
1849         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1850         
1851 }
1852
1853 /* ************ weight paint operator ********** */
1854
1855 struct WPaintData {
1856         ViewContext vc;
1857         int *indexar;
1858         int vgroup_mirror;
1859         float *vertexcosnos;
1860         float wpimat[3][3];
1861         
1862         /*variables for auto normalize*/
1863         char *vgroup_validmap; /*stores if vgroups tie to deforming bones or not*/
1864         char *lock_flags;
1865         int defbase_tot;
1866 };
1867
1868 static char *wpaint_make_validmap(Object *ob)
1869 {
1870         bDeformGroup *dg;
1871         ModifierData *md;
1872         char *vgroup_validmap;
1873         GHash *gh;
1874         int i, step1=1;
1875
1876         if(ob->defbase.first == NULL) {
1877                 return NULL;
1878         }
1879
1880         gh= BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "wpaint_make_validmap gh");
1881
1882         /*add all names to a hash table*/
1883         for (dg=ob->defbase.first; dg; dg=dg->next) {
1884                 BLI_ghash_insert(gh, dg->name, NULL);
1885         }
1886
1887         /*now loop through the armature modifiers and identify deform bones*/
1888         for (md = ob->modifiers.first; md; md= !md->next && step1 ? (step1=0), modifiers_getVirtualModifierList(ob) : md->next) {
1889                 if (!(md->mode & (eModifierMode_Realtime|eModifierMode_Virtual)))
1890                         continue;
1891
1892                 if (md->type == eModifierType_Armature) {
1893                         ArmatureModifierData *amd= (ArmatureModifierData*) md;
1894
1895                         if(amd->object && amd->object->pose) {
1896                                 bPose *pose= amd->object->pose;
1897                                 bPoseChannel *chan;
1898                                 
1899                                 for (chan=pose->chanbase.first; chan; chan=chan->next) {
1900                                         if (chan->bone->flag & BONE_NO_DEFORM)
1901                                                 continue;
1902
1903                                         if (BLI_ghash_haskey(gh, chan->name)) {
1904                                                 BLI_ghash_remove(gh, chan->name, NULL, NULL);
1905                                                 BLI_ghash_insert(gh, chan->name, SET_INT_IN_POINTER(1));
1906                                         }
1907                                 }
1908                         }
1909                 }
1910         }
1911
1912         vgroup_validmap= MEM_mallocN(BLI_ghash_size(gh), "wpaint valid map");
1913
1914         /*add all names to a hash table*/
1915         for (dg=ob->defbase.first, i=0; dg; dg=dg->next, i++) {
1916                 vgroup_validmap[i]= (BLI_ghash_lookup(gh, dg->name) != NULL);
1917         }
1918
1919         BLI_ghash_free(gh, NULL, NULL);
1920
1921         return vgroup_validmap;
1922 }
1923
1924 static int wpaint_stroke_test_start(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1925 {
1926         Scene *scene= CTX_data_scene(C);
1927         struct PaintStroke *stroke = op->customdata;
1928         ToolSettings *ts= CTX_data_tool_settings(C);
1929         VPaint *wp= ts->wpaint;
1930         Object *ob= CTX_data_active_object(C);
1931         struct WPaintData *wpd;
1932         Mesh *me;
1933         float mat[4][4], imat[4][4];
1934         
1935         if(scene->obedit) return OPERATOR_CANCELLED;
1936         
1937         me= get_mesh(ob);
1938         if(me==NULL || me->totface==0) return OPERATOR_PASS_THROUGH;
1939         
1940         /*we can't assume mfaces have a correct origindex layer that indices to mpolys.
1941           so instead we have to regenerate the tesselation faces altogether.*/
1942         me->totface = mesh_recalcTesselation(&me->fdata, &me->ldata, &me->pdata, 
1943                 me->mvert, me->totface, me->totloop, me->totpoly, 1, 0);
1944         mesh_update_customdata_pointers(me);
1945         makeDerivedMesh(scene, ob, NULL, CD_MASK_BAREMESH, 0);
1946
1947         /* if nothing was added yet, we make dverts and a vertex deform group */
1948         if (!me->dvert) {
1949                 ED_vgroup_data_create(&me->id);
1950                 WM_event_add_notifier(C, NC_GEOM|ND_DATA, me);
1951         }
1952         
1953         /* make mode data storage */
1954         wpd= MEM_callocN(sizeof(struct WPaintData), "WPaintData");
1955         paint_stroke_set_mode_data(stroke, wpd);
1956         view3d_set_viewcontext(C, &wpd->vc);
1957         wpd->vgroup_mirror= -1;
1958         
1959         /*set up auto-normalize, and generate map for detecting which
1960           vgroups affect deform bones*/
1961         wpd->defbase_tot = BLI_countlist(&ob->defbase);
1962         wpd->lock_flags = gen_lock_flags(ob, wpd->defbase_tot);
1963         if (ts->auto_normalize || ts->multipaint || wpd->lock_flags) {
1964                 wpd->vgroup_validmap = wpaint_make_validmap(ob);
1965         }
1966
1967         /* ALLOCATIONS! no return after this line */
1968         /* painting on subsurfs should give correct points too, this returns me->totvert amount */
1969         wpd->vertexcosnos= mesh_get_mapped_verts_nors(scene, ob);
1970         wpd->indexar= get_indexarray(me);
1971         copy_wpaint_prev(wp, me->dvert, me->totvert);
1972         
1973         /* this happens on a Bone select, when no vgroup existed yet */
1974         if(ob->actdef<=0) {
1975                 Object *modob;
1976                 if((modob = modifiers_isDeformedByArmature(ob))) {
1977                         Bone *actbone= ((bArmature *)modob->data)->act_bone;
1978                         if(actbone) {
1979                                 bPoseChannel *pchan= get_pose_channel(modob->pose, actbone->name);
1980
1981                                 if(pchan) {
1982                                         bDeformGroup *dg= defgroup_find_name(ob, pchan->name);
1983                                         if(dg==NULL)
1984                                                 dg= ED_vgroup_add_name(ob, pchan->name);        /* sets actdef */
1985                                         else
1986                                                 ob->actdef= 1 + defgroup_find_index(ob, dg);
1987                                 }
1988                         }
1989                 }
1990         }
1991         if(ob->defbase.first==NULL) {
1992                 ED_vgroup_add(ob);
1993         }
1994
1995         /* imat for normals */
1996         mul_m4_m4m4(mat, ob->obmat, wpd->vc.rv3d->viewmat);
1997         invert_m4_m4(imat, mat);
1998         copy_m3_m4(wpd->wpimat, imat);
1999         
2000         /* if mirror painting, find the other group */
2001         if(me->editflag & ME_EDIT_MIRROR_X) {
2002                 wpd->vgroup_mirror= wpaint_mirror_vgroup_ensure(ob);
2003         }
2004         
2005         return 1;
2006 }
2007
2008 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2009 {
2010         ToolSettings *ts= CTX_data_tool_settings(C);
2011         VPaint *wp= ts->wpaint;
2012         Brush *brush = paint_brush(&wp->paint);
2013         struct WPaintData *wpd= paint_stroke_mode_data(stroke);
2014         ViewContext *vc;
2015         Object *ob;
2016         Mesh *me;
2017         float mat[4][4];
2018         float paintweight;
2019         int *indexar;
2020         int totw;
2021         unsigned int index, totindex;
2022         float alpha;
2023         float mval[2], pressure;
2024         int use_vert_sel;
2025
2026         /* intentionally dont initialize as NULL, make sure we initialize all members below */
2027         WeightPaintInfo wpi;
2028
2029         /* cannot paint if there is no stroke data */
2030         if (wpd == NULL) {
2031                 /* XXX: force a redraw here, since even though we can't paint,
2032                  * at least view won't freeze until stroke ends */
2033                 ED_region_tag_redraw(CTX_wm_region(C));
2034                 return;
2035         }
2036                 
2037         vc= &wpd->vc;
2038         ob= vc->obact;
2039         me= ob->data;
2040         indexar= wpd->indexar;
2041         
2042         view3d_operator_needs_opengl(C);
2043                 
2044         /* load projection matrix */
2045         mul_m4_m4m4(mat, ob->obmat, vc->rv3d->persmat);
2046
2047         pressure = RNA_float_get(itemptr, "pressure");
2048         RNA_float_get_array(itemptr, "mouse", mval);
2049         mval[0]-= vc->ar->winrct.xmin;
2050         mval[1]-= vc->ar->winrct.ymin;
2051
2052
2053
2054         /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2055         wpi.defbase_tot=        wpd->defbase_tot;
2056         wpi.defbase_sel=        MEM_mallocN(wpi.defbase_tot*sizeof(char), "wpi.defbase_sel");
2057         wpi.defbase_tot_sel=    get_selected_defgroups(ob, wpi.defbase_sel, wpi.defbase_tot);
2058         if(wpi.defbase_tot_sel == 0 && ob->actdef) wpi.defbase_tot_sel = 1;
2059         wpi.defbase_tot_unsel=  wpi.defbase_tot - wpi.defbase_tot_sel;
2060         wpi.vgroup_mirror=      wpd->vgroup_mirror;
2061         wpi.lock_flags=         wpd->lock_flags;
2062         wpi.vgroup_validmap=    wpd->vgroup_validmap;
2063         wpi.do_flip=            RNA_boolean_get(itemptr, "pen_flip");
2064         wpi.do_multipaint=      (ts->multipaint != 0);
2065         wpi.do_auto_normalize=  ((ts->auto_normalize != 0) && (wpi.vgroup_validmap != NULL));
2066         /* *** done setting up WeightPaintInfo *** */
2067
2068
2069
2070         swap_m4m4(wpd->vc.rv3d->persmat, mat);
2071
2072         use_vert_sel= (me->editflag & ME_EDIT_VERT_SEL) != 0;
2073
2074         /* which faces are involved */
2075         if(wp->flag & VP_AREA) {
2076                 /* Ugly hack, to avoid drawing vertex index when getting the face index buffer - campbell */
2077                 me->editflag &= ~ME_EDIT_VERT_SEL;
2078                 totindex= sample_backbuf_area(vc, indexar, me->totface, mval[0], mval[1], brush_size(brush));
2079                 me->editflag |= use_vert_sel ? ME_EDIT_VERT_SEL : 0;
2080         }
2081         else {
2082                 indexar[0]= view3d_sample_backbuf(vc, mval[0], mval[1]);
2083                 if(indexar[0]) totindex= 1;
2084                 else totindex= 0;
2085         }
2086                         
2087         if(wp->flag & VP_COLINDEX) {
2088                 for(index=0; index<totindex; index++) {
2089                         if(indexar[index] && indexar[index]<=me->totpoly) {
2090                                 MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
2091                                                 
2092                                 if(mpoly->mat_nr!=ob->actcol-1) {
2093                                         indexar[index]= 0;
2094                                 }
2095                         }
2096                 }
2097         }
2098                         
2099         if((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2100                 for(index=0; index<totindex; index++) {
2101                         if(indexar[index] && indexar[index]<=me->totpoly) {
2102                                 MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
2103                                                 
2104                                 if((mpoly->flag & ME_FACE_SEL)==0) {
2105                                         indexar[index]= 0;
2106                                 }
2107                         }                                       
2108                 }
2109         }
2110                         
2111         /* make sure each vertex gets treated only once */
2112         /* and calculate filter weight */
2113         totw= 0;
2114         if(brush->vertexpaint_tool==VP_BLUR) 
2115                 paintweight= 0.0f;
2116         else
2117                 paintweight= ts->vgroup_weight;
2118                         
2119         for(index=0; index<totindex; index++) {
2120                 if(indexar[index] && indexar[index]<=me->totpoly) {
2121                         MPoly *mpoly= me->mpoly + (indexar[index]-1);
2122                         MLoop *ml = me->mloop + mpoly->loopstart;
2123                         int i;
2124
2125                         if(use_vert_sel) {
2126                                 for (i=0; i<mpoly->totloop; i++, ml++) {
2127                                         me->dvert[ml->v].flag = (me->mvert[ml->v].flag & SELECT);
2128                                 }
2129                         }
2130                         else {
2131                                 for (i=0; i<mpoly->totloop; i++, ml++) {
2132                                         me->dvert[ml->v].flag = 1;
2133                                 }
2134                         }
2135                                         
2136                         if(brush->vertexpaint_tool==VP_BLUR) {
2137                                 MDeformWeight *dw, *(*dw_func)(MDeformVert *, const int);
2138                                                 
2139                                 if(wp->flag & VP_ONLYVGROUP)
2140                                         dw_func= (MDeformWeight *(*)(MDeformVert *, const int))defvert_find_index;
2141                                 else
2142                                         dw_func= defvert_verify_index;
2143                                                 
2144                                 ml = me->mloop + mpoly->loopstart;
2145                                 for (i=0; i<mpoly->totloop; i++, ml++) {
2146                                         dw = dw_func(me->dvert+ml->v, ob->actdef-1);
2147                                         if (dw) {
2148                                                 paintweight += dw->weight;
2149                                                 totw++;
2150                                         }
2151                                 }
2152                         }
2153                 }
2154         }
2155                         
2156         if(brush->vertexpaint_tool==VP_BLUR) 
2157                 paintweight/= (float)totw;
2158                         
2159         for(index=0; index<totindex; index++) {
2160                 if(indexar[index] && indexar[index]<=me->totpoly) {
2161                         MPoly *mpoly= me->mpoly + (indexar[index]-1);
2162                         MLoop *ml=me->mloop+mpoly->loopstart;
2163                         int i;
2164
2165                         for (i=0; i<mpoly->totloop; i++, ml++) {
2166                                 unsigned int vidx= ml->v;
2167                                 if (me->dvert[vidx].flag) {
2168                                         alpha= calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos+6*vidx, mval, pressure);
2169                                         if(alpha) {
2170                                                 do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight);
2171                                         }
2172                                         me->dvert[vidx].flag= 0;
2173                                 }
2174                         }
2175                 }
2176         }
2177
2178
2179         /* *** free wpi members */
2180         MEM_freeN(wpi.defbase_sel);
2181         /* *** dont freeing wpi members */
2182
2183
2184         swap_m4m4(vc->rv3d->persmat, mat);
2185                         
2186         DAG_id_tag_update(ob->data, 0);
2187         ED_region_tag_redraw(vc->ar);
2188 }
2189
2190 static void wpaint_stroke_done(bContext *C, struct PaintStroke *stroke)
2191 {
2192         ToolSettings *ts= CTX_data_tool_settings(C);
2193         Object *ob= CTX_data_active_object(C);
2194         struct WPaintData *wpd= paint_stroke_mode_data(stroke);
2195         
2196         if(wpd) {
2197                 if(wpd->vertexcosnos)
2198                         MEM_freeN(wpd->vertexcosnos);
2199                 MEM_freeN(wpd->indexar);
2200                 
2201                 if (wpd->vgroup_validmap)
2202                         MEM_freeN(wpd->vgroup_validmap);
2203                 if(wpd->lock_flags)
2204                         MEM_freeN(wpd->lock_flags);
2205
2206                 MEM_freeN(wpd);
2207         }
2208         
2209         /* frees prev buffer */
2210         copy_wpaint_prev(ts->wpaint, NULL, 0);
2211         
2212         /* and particles too */
2213         if(ob->particlesystem.first) {
2214                 ParticleSystem *psys;
2215                 int i;
2216                 
2217                 for(psys= ob->particlesystem.first; psys; psys= psys->next) {
2218                         for(i=0; i<PSYS_TOT_VG; i++) {
2219                                 if(psys->vgroup[i]==ob->actdef) {
2220                                         psys->recalc |= PSYS_RECALC_RESET;
2221                                         break;
2222                                 }
2223                         }
2224                 }
2225         }
2226         
2227         DAG_id_tag_update(ob->data, 0);
2228 }
2229
2230
2231 static int wpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2232 {
2233         
2234         op->customdata = paint_stroke_new(C, NULL, wpaint_stroke_test_start,
2235                                           wpaint_stroke_update_step,
2236                                           wpaint_stroke_done, event->type);
2237         
2238         /* add modal handler */
2239         WM_event_add_modal_handler(C, op);
2240
2241         op->type->modal(C, op, event);
2242         
2243         return OPERATOR_RUNNING_MODAL;
2244 }
2245
2246 static int wpaint_cancel(bContext *C, wmOperator *op)
2247 {
2248         paint_stroke_cancel(C, op);
2249
2250         return OPERATOR_CANCELLED;
2251 }
2252
2253 void PAINT_OT_weight_paint(wmOperatorType *ot)
2254 {
2255         
2256         /* identifiers */
2257         ot->name= "Weight Paint";
2258         ot->idname= "PAINT_OT_weight_paint";
2259         
2260         /* api callbacks */
2261         ot->invoke= wpaint_invoke;
2262         ot->modal= paint_stroke_modal;
2263         /* ot->exec= vpaint_exec; <-- needs stroke property */
2264         ot->poll= weight_paint_poll;
2265         ot->cancel= wpaint_cancel;
2266         
2267         /* flags */
2268         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2269
2270         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2271 }
2272
2273 static int weight_paint_set_exec(bContext *C, wmOperator *UNUSED(op))
2274 {
2275         struct Scene *scene= CTX_data_scene(C);
2276         Object *obact = CTX_data_active_object(C);
2277
2278         wpaint_fill(scene->toolsettings->wpaint, obact, scene->toolsettings->vgroup_weight);
2279         ED_region_tag_redraw(CTX_wm_region(C)); /* XXX - should redraw all 3D views */
2280         return OPERATOR_FINISHED;
2281 }
2282
2283 void PAINT_OT_weight_set(wmOperatorType *ot)
2284 {
2285         /* identifiers */
2286         ot->name= "Set Weight";
2287         ot->idname= "PAINT_OT_weight_set";
2288
2289         /* api callbacks */
2290         ot->exec= weight_paint_set_exec;
2291         ot->poll= mask_paint_poll; /* it was facemask_paint_poll */
2292
2293         /* flags */
2294         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2295 }
2296
2297 /* ************ set / clear vertex paint mode ********** */
2298
2299
2300 static int set_vpaint(bContext *C, wmOperator *op)              /* toggle */
2301 {       
2302         Object *ob= CTX_data_active_object(C);
2303         Scene *scene= CTX_data_scene(C);
2304         VPaint *vp= scene->toolsettings->vpaint;
2305         Mesh *me;
2306         
2307         me= get_mesh(ob);
2308         
2309         if(me==NULL || object_data_is_libdata(ob)) {
2310                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2311                 return OPERATOR_PASS_THROUGH;
2312         }
2313         
2314         if(me && me->mloopcol==NULL) make_vertexcol(ob);
2315         
2316         /* toggle: end vpaint */
2317         if(ob->mode & OB_MODE_VERTEX_PAINT) {
2318                 
2319                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2320         }
2321         else {
2322                 ob->mode |= OB_MODE_VERTEX_PAINT;
2323                 /* Turn off weight painting */
2324                 if (ob->mode & OB_MODE_WEIGHT_PAINT)
2325                         set_wpaint(C, op);
2326                 
2327                 if(vp==NULL)
2328                         vp= scene->toolsettings->vpaint= new_vpaint(0);
2329                 
2330                 paint_cursor_start(C, vertex_paint_poll);
2331
2332                 paint_init(&vp->paint, PAINT_CURSOR_VERTEX_PAINT);
2333         }
2334         
2335         if (me)
2336                 /* update modifier stack for mapping requirements */
2337                 DAG_id_tag_update(&me->id, 0);
2338         
2339         WM_event_add_notifier(C, NC_SCENE|ND_MODE, scene);
2340         
2341         return OPERATOR_FINISHED;
2342 }
2343
2344 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2345 {
2346         
2347         /* identifiers */
2348         ot->name= "Vertex Paint Mode";
2349         ot->idname= "PAINT_OT_vertex_paint_toggle";
2350         
2351         /* api callbacks */
2352         ot->exec= set_vpaint;
2353         ot->poll= paint_poll_test;
2354         
2355         /* flags */
2356         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2357 }
2358
2359
2360
2361 /* ********************** vertex paint operator ******************* */
2362
2363 /* Implementation notes:
2364
2365 Operator->invoke()
2366   - validate context (add mcol)
2367   - create customdata storage
2368   - call paint once (mouse click)
2369   - add modal handler 
2370
2371 Operator->modal()
2372   - for every mousemove, apply vertex paint
2373   - exit on mouse release, free customdata
2374         (return OPERATOR_FINISHED also removes handler and operator)
2375
2376 For future:
2377   - implement a stroke event (or mousemove with past positons)
2378   - revise whether op->customdata should be added in object, in set_vpaint
2379
2380 */
2381
2382 typedef struct polyfacemap_e {
2383         struct polyfacemap_e *next, *prev;
2384         int facenr;
2385 } polyfacemap_e;
2386
2387 typedef struct VPaintData {
2388         ViewContext vc;
2389         unsigned int paintcol;
2390         int *indexar;
2391         float *vertexcosnos;
2392         float vpimat[3][3];
2393         
2394         /*mpoly -> mface mapping*/
2395         MemArena *arena;
2396         ListBase *polyfacemap;
2397 } VPaintData;
2398
2399 static void vpaint_build_poly_facemap(struct VPaintData *vd, Mesh *me,
2400                                       Object *ob, Scene *scene)
2401 {
2402         MFace *mf;
2403         polyfacemap_e *e;
2404         int *origIndex;
2405         int i;
2406
2407         vd->arena = BLI_memarena_new(1<<13, "vpaint tmp");
2408         BLI_memarena_use_calloc(vd->arena);
2409
2410         vd->polyfacemap = BLI_memarena_alloc(vd->arena, sizeof(ListBase)*me->totpoly);
2411
2412         /*we can't assume mfaces have a correct origindex layer that indices to mpolys.
2413           so instead we have to regenerate the tesselation faces altogether.*/
2414         me->totface = mesh_recalcTesselation(&me->fdata, &me->ldata, &me->pdata, 
2415                 me->mvert, me->totface, me->totloop, me->totpoly, 1, 0);
2416         mesh_update_customdata_pointers(me);
2417         makeDerivedMesh(scene, ob, NULL, CD_MASK_BAREMESH, 0);
2418
2419         origIndex = CustomData_get_layer(&me->fdata, CD_ORIGINDEX);
2420         mf = me->mface;
2421
2422         if (!origIndex)
2423                 return;
2424
2425         for (i=0; i<me->totface; i++, mf++, origIndex++) {
2426                 if (*origIndex == ORIGINDEX_NONE)
2427                         continue;
2428
2429                 e = BLI_memarena_alloc(vd->arena, sizeof(polyfacemap_e));
2430                 e->facenr = i;
2431                 
2432                 BLI_addtail(&vd->polyfacemap[*origIndex], e);
2433         }
2434 }
2435
2436 static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, wmEvent *UNUSED(event))
2437 {
2438         ToolSettings *ts= CTX_data_tool_settings(C);
2439         struct PaintStroke *stroke = op->customdata;
2440         VPaint *vp= ts->vpaint;
2441         struct VPaintData *vpd;
2442         Object *ob= CTX_data_active_object(C);
2443         Scene *scene = CTX_data_scene(C);
2444         Mesh *me;
2445         float mat[4][4], imat[4][4];
2446
2447         /* context checks could be a poll() */
2448         me= get_mesh(ob);
2449         if(me==NULL || me->totpoly==0)
2450                 return OPERATOR_PASS_THROUGH;
2451         
2452         if(me->mloopcol==NULL)
2453                 make_vertexcol(ob);
2454         if(me->mloopcol==NULL)
2455                 return OPERATOR_CANCELLED;
2456         
2457         /* make mode data storage */
2458         vpd= MEM_callocN(sizeof(struct VPaintData), "VPaintData");
2459         paint_stroke_set_mode_data(stroke, vpd);
2460         view3d_set_viewcontext(C, &vpd->vc);
2461         
2462         vpd->vertexcosnos= mesh_get_mapped_verts_nors(vpd->vc.scene, ob);
2463         vpd->indexar= get_indexarray(me);
2464         vpd->paintcol= vpaint_get_current_col(vp);
2465         vpaint_build_poly_facemap(vpd, me, ob, scene);
2466         
2467         /* for filtering */
2468         copy_vpaint_prev(vp, (unsigned int *)me->mloopcol, me->totloop);
2469         
2470         /* some old cruft to sort out later */
2471         mul_m4_m4m4(mat, ob->obmat, vpd->vc.rv3d->viewmat);
2472         invert_m4_m4(imat, mat);
2473         copy_m3_m4(vpd->vpimat, imat);
2474
2475         return 1;
2476 }
2477
2478 #if 0
2479 static void vpaint_paint_face(VPaint *vp, VPaintData *vpd, Object *ob, int index, const float mval[2], float pressure, int UNUSED(flip))
2480 {
2481         ViewContext *vc = &vpd->vc;
2482         Brush *brush = paint_brush(&vp->paint);
2483         Mesh *me = get_mesh(ob);
2484         MFace *mface= &me->mface[index];
2485         unsigned int *mcol= ((unsigned int*)me->mcol) + 4*index;
2486         unsigned int *mcolorig= ((unsigned int*)vp->vpaint_prev) + 4*index;
2487         float alpha;
2488         int i;
2489         
2490         if((vp->flag & VP_COLINDEX && mface->mat_nr!=ob->actcol-1) ||
2491            ((me->editflag & ME_EDIT_PAINT_MASK) && !(mface->flag & ME_FACE_SEL)))
2492                 return;
2493
2494         if(brush->vertexpaint_tool==VP_BLUR) {
2495                 unsigned int fcol1= mcol_blend( mcol[0], mcol[1], 128);
2496                 if(mface->v4) {
2497                         unsigned int fcol2= mcol_blend( mcol[2], mcol[3], 128);
2498                         vpd->paintcol= mcol_blend( fcol1, fcol2, 128);
2499                 }
2500                 else {
2501                         vpd->paintcol= mcol_blend( mcol[2], fcol1, 170);
2502                 }
2503                 
2504         }
2505
2506         for(i = 0; i < (mface->v4 ? 4 : 3); ++i) {
2507                 alpha= calc_vp_alpha_dl(vp, vc, vpd->vpimat, vpd->vertexcosnos+6*(&mface->v1)[i], mval, pressure);
2508                 if(alpha)
2509                         vpaint_blend(vp, mcol+i, mcolorig+i, vpd->paintcol, (int)(alpha*255.0f));
2510         }
2511 }
2512 #endif
2513
2514 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2515 {
2516         ToolSettings *ts= CTX_data_tool_settings(C);
2517         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2518         VPaint *vp= ts->vpaint;
2519         Brush *brush = paint_brush(&vp->paint);
2520         ViewContext *vc= &vpd->vc;
2521         Object *ob= vc->obact;
2522         polyfacemap_e *e;
2523         Mesh *me= ob->data;
2524         float mat[4][4];
2525         int *indexar= vpd->indexar;
2526         int totindex, index, flip;
2527         float pressure, mval[2];
2528
2529         RNA_float_get_array(itemptr, "mouse", mval);
2530         flip = RNA_boolean_get(itemptr, "pen_flip");
2531         pressure = RNA_float_get(itemptr, "pressure");
2532                         
2533         view3d_operator_needs_opengl(C);
2534                         
2535         /* load projection matrix */
2536         mul_m4_m4m4(mat, ob->obmat, vc->rv3d->persmat);
2537
2538         mval[0]-= vc->ar->winrct.xmin;
2539         mval[1]-= vc->ar->winrct.ymin;
2540
2541                         
2542         /* which faces are involved */
2543         if(vp->flag & VP_AREA) {
2544                 totindex= sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size(brush));
2545         }
2546         else {
2547                 indexar[0]= view3d_sample_backbuf(vc, mval[0], mval[1]);
2548                 if(indexar[0]) totindex= 1;
2549                 else totindex= 0;
2550         }
2551                         
2552         swap_m4m4(vc->rv3d->persmat, mat);
2553                         
2554         if(vp->flag & VP_COLINDEX) {
2555                 for(index=0; index<totindex; index++) {
2556                         if(indexar[index] && indexar[index]<=me->totpoly) {
2557                                 MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
2558                                                 
2559                                 if(mpoly->mat_nr!=ob->actcol-1) {
2560                                         indexar[index]= 0;
2561                                 }
2562                         }                                       
2563                 }
2564         }
2565
2566         if((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2567                 for(index=0; index<totindex; index++) {
2568                         if(indexar[index] && indexar[index]<=me->totpoly) {
2569                                 MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
2570                                                 
2571                                 if((mpoly->flag & ME_FACE_SEL)==0)
2572                                         indexar[index]= 0;
2573                         }                                       
2574                 }
2575         }
2576         
2577         swap_m4m4(vc->rv3d->persmat, mat);
2578
2579         /* was disabled because it is slow, but necessary for blur */
2580         if(brush->vertexpaint_tool == VP_BLUR)
2581                 do_shared_vertexcol(me);
2582                         
2583         for(index=0; index<totindex; index++) {
2584                                 
2585                 if(indexar[index] && indexar[index]<=me->totpoly) {
2586                         MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
2587                         MFace *mf;
2588                         MCol *mc;
2589                         MLoop *ml;
2590                         MLoopCol *mlc;
2591                         unsigned int *lcol = ((unsigned int*)me->mloopcol) + mpoly->loopstart;
2592                         unsigned int *lcolorig = ((unsigned int*)vp->vpaint_prev) + mpoly->loopstart;
2593                         float alpha;
2594                         int i, j;
2595                                         
2596                         if(brush->vertexpaint_tool==VP_BLUR) {
2597                                 unsigned int blend[5] = {0};
2598                                 char *col;
2599
2600                                 for (j=0; j<mpoly->totloop; j += 2) {
2601                                         col = (char*)(lcol + j);
2602                                         blend[0] += col[0];
2603                                         blend[1] += col[1];
2604                                         blend[2] += col[2];
2605                                         blend[3] += col[3];
2606                                 }
2607
2608                                 blend[0] /= mpoly->totloop;
2609                                 blend[1] /= mpoly->totloop;
2610                                 blend[2] /= mpoly->totloop;
2611                                 blend[3] /= mpoly->totloop;
2612                                 col = (char*)(blend + 4);
2613                                 col[0] = blend[0];
2614                                 col[1] = blend[1];
2615                                 col[2] = blend[2];
2616                                 col[3] = blend[3];
2617
2618                                 vpd->paintcol = *((unsigned int*)col);
2619                         }
2620
2621                         ml = me->mloop + mpoly->loopstart;
2622                         for (i=0; i<mpoly->totloop; i++, ml++) {
2623                                 alpha= calc_vp_alpha_dl(vp, vc, vpd->vpimat, 
2624                                            vpd->vertexcosnos+6*ml->v, mval, pressure);
2625                                 if(alpha > 0.0f) vpaint_blend(vp, lcol+i, lcolorig+i, vpd->paintcol, (int)(alpha*255.0f));
2626                         }
2627         
2628                         #ifdef CPYCOL
2629                         #undef CPYCOL
2630                         #endif
2631                         #define CPYCOL(c, l) (c)->a = (l)->a, (c)->r = (l)->r, (c)->g = (l)->g, (c)->b = (l)->b
2632
2633                         /*update vertex colors for tesselations incrementally,
2634                           rather then regenerating the tesselation altogether.*/
2635                         for (e=vpd->polyfacemap[(indexar[index]-1)].first; e; e=e->next) {
2636                                 mf = me->mface + e->facenr;
2637                                 mc = me->mcol + e->facenr*4;
2638                                 
2639                                 ml = me->mloop + mpoly->loopstart;
2640                                 mlc = me->mloopcol + mpoly->loopstart;
2641                                 for (j=0; j<mpoly->totloop; j++, ml++, mlc++) {
2642                                         if (ml->v == mf->v1)
2643                                                 CPYCOL(mc, mlc);
2644                                         else if (ml->v == mf->v2)
2645                                                 CPYCOL(mc+1, mlc);
2646                                         else if (ml->v == mf->v3)
2647                                                 CPYCOL(mc+2, mlc);
2648                                         else if (mf->v4 && ml->v == mf->v4)
2649                                                 CPYCOL(mc+3, mlc);
2650
2651                                 }
2652                         }
2653                         #undef CPYCOL
2654                 }
2655         }
2656                 
2657         swap_m4m4(vc->rv3d->persmat, mat);
2658                         
2659         /* was disabled because it is slow, but necessary for blur */
2660         if(brush->vertexpaint_tool == VP_BLUR) {
2661                 do_shared_vertexcol(me);
2662         }
2663
2664         ED_region_tag_redraw(vc->ar);           
2665         DAG_id_tag_update(ob->data, 0);
2666 }
2667
2668 static void vpaint_stroke_done(bContext *C, struct PaintStroke *stroke)
2669 {
2670         ToolSettings *ts= CTX_data_tool_settings(C);
2671         struct VPaintData *vpd= paint_stroke_mode_data(stroke);
2672         
2673         if(vpd->vertexcosnos)
2674                 MEM_freeN(vpd->vertexcosnos);
2675         MEM_freeN(vpd->indexar);
2676         
2677         /* frees prev buffer */
2678         copy_vpaint_prev(ts->vpaint, NULL, 0);
2679         BLI_memarena_free(vpd->arena);
2680
2681         MEM_freeN(vpd);
2682 }
2683
2684 static int vpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2685 {
2686         
2687         op->customdata = paint_stroke_new(C, NULL, vpaint_stroke_test_start,
2688                                           vpaint_stroke_update_step,
2689                                           vpaint_stroke_done, event->type);
2690         
2691         /* add modal handler */
2692         WM_event_add_modal_handler(C, op);
2693
2694         op->type->modal(C, op, event);
2695         
2696         return OPERATOR_RUNNING_MODAL;
2697 }
2698
2699 static int vpaint_cancel(bContext *C, wmOperator *op)
2700 {
2701         paint_stroke_cancel(C, op);
2702
2703         return OPERATOR_CANCELLED;
2704 }
2705
2706 void PAINT_OT_vertex_paint(wmOperatorType *ot)
2707 {
2708         /* identifiers */
2709         ot->name= "Vertex Paint";
2710         ot->idname= "PAINT_OT_vertex_paint";
2711         
2712         /* api callbacks */
2713         ot->invoke= vpaint_invoke;
2714         ot->modal= paint_stroke_modal;
2715         /* ot->exec= vpaint_exec; <-- needs stroke property */
2716         ot->poll= vertex_paint_poll;
2717         ot->cancel= vpaint_cancel;
2718         
2719         /* flags */
2720         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2721
2722         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2723 }
2724
2725 /* ********************** weight from bones operator ******************* */
2726
2727 static int weight_from_bones_poll(bContext *C)
2728 {
2729         Object *ob= CTX_data_active_object(C);
2730
2731         return (ob && (ob->mode & OB_MODE_WEIGHT_PAINT) && modifiers_isDeformedByArmature(ob));
2732 }
2733
2734 static int weight_from_bones_exec(bContext *C, wmOperator *op)
2735 {
2736         Scene *scene= CTX_data_scene(C);
2737         Object *ob= CTX_data_active_object(C);
2738         Object *armob= modifiers_isDeformedByArmature(ob);
2739         Mesh *me= ob->data;
2740         int type= RNA_enum_get(op->ptr, "type");
2741
2742         create_vgroups_from_armature(op->reports, scene, ob, armob, type, (me->editflag & ME_EDIT_MIRROR_X));
2743
2744         DAG_id_tag_update(&me->id, 0);
2745         WM_event_add_notifier(C, NC_GEOM|ND_DATA, me);
2746
2747         return OPERATOR_FINISHED;
2748 }
2749
2750 void PAINT_OT_weight_from_bones(wmOperatorType *ot)
2751 {
2752         static EnumPropertyItem type_items[]= {
2753                 {ARM_GROUPS_AUTO, "AUTOMATIC", 0, "Automatic", "Automatic weights froms bones"},
2754                 {ARM_GROUPS_ENVELOPE, "ENVELOPES", 0, "From Envelopes", "Weights from envelopes with user defined radius"},
2755                 {0, NULL, 0, NULL, NULL}};
2756
2757         /* identifiers */
2758         ot->name= "Weight from Bones";
2759         ot->idname= "PAINT_OT_weight_from_bones";
2760         
2761         /* api callbacks */
2762         ot->exec= weight_from_bones_exec;
2763         ot->invoke= WM_menu_invoke;
2764         ot->poll= weight_from_bones_poll;
2765         
2766         /* flags */
2767         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2768
2769         /* properties */
2770         ot->prop= RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "Method to use for assigning weights");
2771 }
2772