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