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