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