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