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