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