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