this someone didn't get committed
[blender-staging.git] / source / blender / editors / sculpt_paint / paint_vertex.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <math.h>
31 #include <string.h>
32
33 #ifdef WIN32
34 #include <io.h>
35 #else
36 #include <unistd.h>
37 #endif   
38
39 #include "MEM_guardedalloc.h"
40
41 #include "IMB_imbuf.h"
42 #include "IMB_imbuf_types.h"
43
44 #include "BLI_blenlib.h"
45 #include "BLI_math.h"
46 #include "BLI_memarena.h"
47 #include "BLI_cellalloc.h"
48 #include "BLI_ghash.h"
49
50 #include "DNA_anim_types.h"
51 #include "DNA_action_types.h"
52 #include "DNA_armature_types.h"
53 #include "DNA_brush_types.h"
54 #include "DNA_cloth_types.h"
55 #include "DNA_mesh_types.h"
56 #include "DNA_meshdata_types.h"
57 #include "DNA_modifier_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_object_force.h"
60 #include "DNA_particle_types.h"
61 #include "DNA_screen_types.h"
62 #include "DNA_space_types.h"
63 #include "DNA_scene_types.h"
64 #include "DNA_view3d_types.h"
65 #include "DNA_userdef_types.h"
66
67 #include "RNA_access.h"
68 #include "RNA_define.h"
69
70 #include "BKE_armature.h"
71 #include "BKE_brush.h"
72 #include "BKE_DerivedMesh.h"
73 #include "BKE_cloth.h"
74 #include "BKE_context.h"
75 #include "BKE_customdata.h"
76 #include "BKE_depsgraph.h"
77 #include "BKE_deform.h"
78 #include "BKE_displist.h"
79 #include "BKE_global.h"
80 #include "BKE_mesh.h"
81 #include "BKE_modifier.h"
82 #include "BKE_object.h"
83 #include "BKE_paint.h"
84 #include "BKE_utildefines.h"
85
86 #include "WM_api.h"
87 #include "WM_types.h"
88
89 #include "BIF_gl.h"
90 #include "BIF_glutil.h"
91
92 #include "ED_mesh.h"
93 #include "ED_object.h"
94 #include "ED_screen.h"
95 #include "ED_util.h"
96 #include "ED_view3d.h"
97
98 #include "paint_intern.h"
99
100         /* vp->mode */
101 #define VP_MIX  0
102 #define VP_ADD  1
103 #define VP_SUB  2
104 #define VP_MUL  3
105 #define VP_BLUR 4
106 #define VP_LIGHTEN      5
107 #define VP_DARKEN       6
108
109 #define MAXINDEX        512000
110
111 /* XXX */
112 static void error() {}
113
114 /* polling - retrieve whether cursor should be set or operator should be done */
115
116
117 /* Returns true if vertex paint mode is active */
118 int vertex_paint_mode_poll(bContext *C)
119 {
120         Object *ob = CTX_data_active_object(C);
121
122         return ob && ob->mode == OB_MODE_VERTEX_PAINT;
123 }
124
125 int vertex_paint_poll(bContext *C)
126 {
127         if(vertex_paint_mode_poll(C) && 
128            paint_brush(&CTX_data_tool_settings(C)->vpaint->paint)) {
129                 ScrArea *sa= CTX_wm_area(C);
130                 if(sa->spacetype==SPACE_VIEW3D) {
131                         ARegion *ar= CTX_wm_region(C);
132                         if(ar->regiontype==RGN_TYPE_WINDOW)
133                                 return 1;
134                 }
135         }
136         return 0;
137 }
138
139 int weight_paint_poll(bContext *C)
140 {
141         Object *ob = CTX_data_active_object(C);
142
143         if(ob && ob->mode & OB_MODE_WEIGHT_PAINT &&
144            paint_brush(&CTX_data_tool_settings(C)->wpaint->paint)) {
145                 ScrArea *sa= CTX_wm_area(C);
146                 if(sa->spacetype==SPACE_VIEW3D) {
147                         ARegion *ar= CTX_wm_region(C);
148                         if(ar->regiontype==RGN_TYPE_WINDOW)
149                                 return 1;
150                 }
151         }
152         return 0;
153 }
154
155 static VPaint *new_vpaint(int wpaint)
156 {
157         VPaint *vp= MEM_callocN(sizeof(VPaint), "VPaint");
158         
159         vp->gamma= vp->mul= 1.0f;
160         
161         vp->flag= VP_AREA+VP_SOFT+VP_SPRAY;
162         
163         if(wpaint)
164                 vp->flag= VP_AREA+VP_SOFT;
165
166         return vp;
167 }
168
169 static int *get_indexarray(void)
170 {
171         return MEM_mallocN(sizeof(int)*MAXINDEX + 2, "vertexpaint");
172 }
173
174
175 /* in contradiction to cpack drawing colors, the MCOL colors (vpaint colors) are per byte! 
176    so not endian sensitive. Mcol = ABGR!!! so be cautious with cpack calls */
177
178 unsigned int rgba_to_mcol(float r, float g, float b, float a)
179 {
180         int ir, ig, ib, ia;
181         unsigned int col;
182         char *cp;
183         
184         ir= floor(255.0*r);
185         if(ir<0) ir= 0; else if(ir>255) ir= 255;
186         ig= floor(255.0*g);
187         if(ig<0) ig= 0; else if(ig>255) ig= 255;
188         ib= floor(255.0*b);
189         if(ib<0) ib= 0; else if(ib>255) ib= 255;
190         ia= floor(255.0*a);
191         if(ia<0) ia= 0; else if(ia>255) ia= 255;
192         
193         cp= (char *)&col;
194         cp[0]= ia;
195         cp[1]= ib;
196         cp[2]= ig;
197         cp[3]= ir;
198         
199         return col;
200         
201 }
202
203 unsigned int vpaint_get_current_col(VPaint *vp)
204 {
205         Brush *brush = paint_brush(&vp->paint);
206         return rgba_to_mcol(brush->rgb[0], brush->rgb[1], brush->rgb[2], 1.0f);
207 }
208
209 static void do_shared_vertex_tesscol(Mesh *me)
210 {
211         /* if no mcol: do not do */
212         /* if tface: only the involved faces, otherwise all */
213         MFace *mface;
214         MTFace *tface;
215         int a;
216         short *scolmain, *scol;
217         char *mcol;
218         
219         if(me->mcol==0 || me->totvert==0 || me->totface==0) return;
220         
221         scolmain= MEM_callocN(4*sizeof(short)*me->totvert, "colmain");
222         
223         tface= me->mtface;
224         mface= me->mface;
225         mcol= (char *)me->mcol;
226         for(a=me->totface; a>0; a--, mface++, mcol+=16) {
227                 if((tface && tface->mode & TF_SHAREDCOL) || (me->editflag & ME_EDIT_PAINT_MASK)==0) {
228                         scol= scolmain+4*mface->v1;
229                         scol[0]++; scol[1]+= mcol[1]; scol[2]+= mcol[2]; scol[3]+= mcol[3];
230                         scol= scolmain+4*mface->v2;
231                         scol[0]++; scol[1]+= mcol[5]; scol[2]+= mcol[6]; scol[3]+= mcol[7];
232                         scol= scolmain+4*mface->v3;
233                         scol[0]++; scol[1]+= mcol[9]; scol[2]+= mcol[10]; scol[3]+= mcol[11];
234                         if(mface->v4) {
235                                 scol= scolmain+4*mface->v4;
236                                 scol[0]++; scol[1]+= mcol[13]; scol[2]+= mcol[14]; scol[3]+= mcol[15];
237                         }
238                 }
239                 if(tface) tface++;
240         }
241         
242         a= me->totvert;
243         scol= scolmain;
244         while(a--) {
245                 if(scol[0]>1) {
246                         scol[1]/= scol[0];
247                         scol[2]/= scol[0];
248                         scol[3]/= scol[0];
249                 }
250                 scol+= 4;
251         }
252         
253         tface= me->mtface;
254         mface= me->mface;
255         mcol= (char *)me->mcol;
256         for(a=me->totface; a>0; a--, mface++, mcol+=16) {
257                 if((tface && tface->mode & TF_SHAREDCOL) || (me->editflag & ME_EDIT_PAINT_MASK)==0) {
258                         scol= scolmain+4*mface->v1;
259                         mcol[1]= scol[1]; mcol[2]= scol[2]; mcol[3]= scol[3];
260                         scol= scolmain+4*mface->v2;
261                         mcol[5]= scol[1]; mcol[6]= scol[2]; mcol[7]= scol[3];
262                         scol= scolmain+4*mface->v3;
263                         mcol[9]= scol[1]; mcol[10]= scol[2]; mcol[11]= scol[3];
264                         if(mface->v4) {
265                                 scol= scolmain+4*mface->v4;
266                                 mcol[13]= scol[1]; mcol[14]= scol[2]; mcol[15]= scol[3];
267                         }
268                 }
269                 if(tface) tface++;
270         }
271
272         MEM_freeN(scolmain);
273 }
274
275 void do_shared_vertexcol(Mesh *me)
276 {
277         MLoop *ml = me->mloop;
278         MLoopCol *lcol = me->mloopcol;
279         MTexPoly *mtp = me->mtpoly;
280         MPoly *mp = me->mpoly;
281         float (*scol)[5];
282         int i;
283
284         /* if no mloopcol: do not do */
285         /* if mtexpoly: only the involved faces, otherwise all */
286
287         if(me->mloopcol==0 || me->totvert==0 || me->totpoly==0) return;
288
289         scol = MEM_callocN(sizeof(float)*me->totvert*5, "scol");
290
291         for (i=0; i<me->totloop; i++, ml++, lcol++) {
292                 if (i >= mp->loopstart + mp->totloop) {
293                         mp++;
294                         if (mtp) mtp++;
295                 }
296
297                 if (mtp && !(mtp->mode & TF_SHAREDCOL))
298                         continue;
299
300                 scol[ml->v][0] += lcol->r;
301                 scol[ml->v][1] += lcol->g;
302                 scol[ml->v][2] += lcol->b;
303                 scol[ml->v][3] += lcol->a;
304                 scol[ml->v][4] += 1.0;
305         }
306         
307         for (i=0; i<me->totvert; i++) {
308                 if (!scol[i][4]) continue;
309
310                 scol[i][0] /= scol[i][4];
311                 scol[i][1] /= scol[i][4];
312                 scol[i][2] /= scol[i][4];
313                 scol[i][3] /= scol[i][4];
314         }
315         
316         ml = me->mloop;
317         lcol = me->mloopcol;
318         for (i=0; i<me->totloop; i++, ml++, lcol++) {
319                 if (!scol[ml->v][4]) continue;
320
321                 lcol->r = scol[ml->v][0];
322                 lcol->g = scol[ml->v][1];
323                 lcol->b = scol[ml->v][2];
324                 lcol->a = scol[ml->v][3];
325         }
326
327         MEM_freeN(scol);
328
329         do_shared_vertex_tesscol(me);
330 }
331
332 static void make_vertexcol(Object *ob)  /* single ob */
333 {
334         Mesh *me;
335         if(!ob || ob->id.lib) return;
336         me= get_mesh(ob);
337         if(me==0) return;
338         if(me->edit_btmesh) return;
339
340         /* copies from shadedisplist to mcol */
341         if(!me->mcol)
342                 CustomData_add_layer(&me->fdata, CD_MCOL, CD_DEFAULT, NULL, me->totface);
343         if (!me->mloopcol)
344                 CustomData_add_layer(&me->ldata, CD_MLOOPCOL, CD_DEFAULT, NULL, me->totloop);
345         
346         mesh_update_customdata_pointers(me);
347
348         //if(shade)
349         //      shadeMeshMCol(scene, ob, me);
350         //else
351
352         memset(me->mcol, 255, 4*sizeof(MCol)*me->totface);
353
354         DAG_id_flush_update(&me->id, OB_RECALC_DATA);
355         
356 }
357
358 static void copy_vpaint_prev(VPaint *vp, unsigned int *lcol, int tot)
359 {
360         if(vp->vpaint_prev) {
361                 MEM_freeN(vp->vpaint_prev);
362                 vp->vpaint_prev= NULL;
363         }
364         vp->tot= tot;   
365         
366         if(lcol==NULL || tot==0) return;
367         
368         vp->vpaint_prev= MEM_mallocN(sizeof(int)*tot, "vpaint_prev");
369         memcpy(vp->vpaint_prev, lcol, sizeof(int)*tot);
370         
371 }
372
373 static void copy_wpaint_prev (VPaint *wp, MDeformVert *dverts, int dcount)
374 {
375         if (wp->wpaint_prev) {
376                 free_dverts(wp->wpaint_prev, wp->tot);
377                 wp->wpaint_prev= NULL;
378         }
379         
380         if(dverts && dcount) {
381                 
382                 wp->wpaint_prev = MEM_mallocN (sizeof(MDeformVert)*dcount, "wpaint prev");
383                 wp->tot = dcount;
384                 copy_dverts (wp->wpaint_prev, dverts, dcount);
385         }
386 }
387
388
389 void vpaint_fill(Object *ob, unsigned int paintcol)
390 {
391         Mesh *me;
392         MFace *mf;
393         MPoly *mp;
394         MLoopCol *lcol;
395         unsigned int *mcol;
396         int i, j, selected;
397
398         me= get_mesh(ob);
399         if(me==0 || me->totface==0) return;
400
401         if(!me->mcol)
402                 make_vertexcol(ob);
403
404         selected= (me->editflag & ME_EDIT_PAINT_MASK);
405
406         mf = me->mface;
407         mcol = (unsigned int*)me->mcol;
408         for (i = 0; i < me->totface; i++, mf++, mcol+=4) {
409                 if (!selected || mf->flag & ME_FACE_SEL) {
410                         mcol[0] = paintcol;
411                         mcol[1] = paintcol;
412                         mcol[2] = paintcol;
413                         mcol[3] = paintcol;
414                 }
415         }
416
417         mp = me->mpoly;
418         lcol = me->mloopcol;
419         for (i=0; i<me->totpoly; i++, mp++) {
420                 if (!(!selected || mp->flag & ME_FACE_SEL))
421                         continue;
422
423                 lcol = me->mloopcol + mp->loopstart;
424                 for (j=0; j<mp->totloop; j++, lcol++) {
425                         *(int*)lcol = paintcol;
426                 }
427         }
428         
429         DAG_id_flush_update(&me->id, OB_RECALC_DATA);
430 }
431
432
433 /* fills in the selected faces with the current weight and vertex group */
434 void wpaint_fill(VPaint *wp, Object *ob, float paintweight)
435 {
436         Mesh *me;
437         MFace *mface;
438         MDeformWeight *dw, *uw;
439         int *indexar;
440         int index, vgroup;
441         unsigned int faceverts[5]={0,0,0,0,0};
442         unsigned char i;
443         int vgroup_mirror= -1;
444         int selected;
445         
446         me= ob->data;
447         if(me==0 || me->totface==0 || me->dvert==0 || !me->mface) return;
448         
449         selected= (me->editflag & ME_EDIT_PAINT_MASK);
450
451         indexar= get_indexarray();
452         if(selected) {
453                 for(index=0, mface=me->mface; index<me->totface; index++, mface++) {
454                         if((mface->flag & ME_FACE_SEL)==0)
455                                 indexar[index]= 0;
456                         else
457                                 indexar[index]= index+1;
458                 }
459         }
460         else {
461                 for(index=0; index<me->totface; index++)
462                         indexar[index]= index+1;
463         }
464         
465         vgroup= ob->actdef-1;
466         
467         /* directly copied from weight_paint, should probaby split into a separate function */
468         /* if mirror painting, find the other group */          
469         if(me->editflag & ME_EDIT_MIRROR_X) {
470                 bDeformGroup *defgroup= BLI_findlink(&ob->defbase, ob->actdef-1);
471                 if(defgroup) {
472                         bDeformGroup *curdef;
473                         int actdef= 0;
474                         char name[32];
475
476                         BLI_strncpy(name, defgroup->name, 32);
477                         bone_flip_name(name, 0);                /* 0 = don't strip off number extensions */
478                         
479                         for (curdef = ob->defbase.first; curdef; curdef=curdef->next, actdef++)
480                                 if (!strcmp(curdef->name, name))
481                                         break;
482                         if(curdef==NULL) {
483                                 int olddef= ob->actdef; /* tsk, ED_vgroup_add sets the active defgroup */
484                                 curdef= ED_vgroup_add_name (ob, name);
485                                 ob->actdef= olddef;
486                         }
487                         
488                         if(curdef && curdef!=defgroup)
489                                 vgroup_mirror= actdef;
490                 }
491         }
492         /* end copy from weight_paint*/
493         
494         copy_wpaint_prev(wp, me->dvert, me->totvert);
495         
496         for(index=0; index<me->totface; index++) {
497                 if(indexar[index] && indexar[index]<=me->totface) {
498                         mface= me->mface + (indexar[index]-1);
499                         /* just so we can loop through the verts */
500                         faceverts[0]= mface->v1;
501                         faceverts[1]= mface->v2;
502                         faceverts[2]= mface->v3;
503                         faceverts[3]= mface->v4;
504                         for (i=0; i<3 || faceverts[i]; i++) {
505                                 if(!((me->dvert+faceverts[i])->flag)) {
506                                         dw= ED_vgroup_weight_verify(me->dvert+faceverts[i], vgroup);
507                                         if(dw) {
508                                                 uw= ED_vgroup_weight_verify(wp->wpaint_prev+faceverts[i], vgroup);
509                                                 uw->weight= dw->weight; /* set the undo weight */
510                                                 dw->weight= paintweight;
511                                                 
512                                                 if(me->editflag & ME_EDIT_MIRROR_X) {   /* x mirror painting */
513                                                         int j= mesh_get_x_mirror_vert(ob, faceverts[i]);
514                                                         if(j>=0) {
515                                                                 /* copy, not paint again */
516                                                                 if(vgroup_mirror != -1) {
517                                                                         dw= ED_vgroup_weight_verify(me->dvert+j, vgroup_mirror);
518                                                                         uw= ED_vgroup_weight_verify(wp->wpaint_prev+j, vgroup_mirror);
519                                                                 } else {
520                                                                         dw= ED_vgroup_weight_verify(me->dvert+j, vgroup);
521                                                                         uw= ED_vgroup_weight_verify(wp->wpaint_prev+j, vgroup);
522                                                                 }
523                                                                 uw->weight= dw->weight; /* set the undo weight */
524                                                                 dw->weight= paintweight;
525                                                         }
526                                                 }
527                                         }
528                                         (me->dvert+faceverts[i])->flag= 1;
529                                 }
530                         }
531                 }
532         }
533         
534         index=0;
535         while (index<me->totvert) {
536                 (me->dvert+index)->flag= 0;
537                 index++;
538         }
539         
540         MEM_freeN(indexar);
541         copy_wpaint_prev(wp, NULL, 0);
542
543         DAG_id_flush_update(&me->id, OB_RECALC_DATA);
544 }
545
546
547 void vpaint_dogamma(Scene *scene)
548 {
549         VPaint *vp= scene->toolsettings->vpaint;
550         Mesh *me;
551         Object *ob;
552         float igam, fac;
553         int a, temp;
554         unsigned char *cp, gamtab[256];
555
556         ob= OBACT;
557         me= get_mesh(ob);
558
559         if(!(ob->mode & OB_MODE_VERTEX_PAINT)) return;
560         if(me==0 || me->mcol==0 || me->totface==0) return;
561
562         igam= 1.0/vp->gamma;
563         for(a=0; a<256; a++) {
564                 
565                 fac= ((float)a)/255.0;
566                 fac= vp->mul*pow( fac, igam);
567                 
568                 temp= 255.9*fac;
569                 
570                 if(temp<=0) gamtab[a]= 0;
571                 else if(temp>=255) gamtab[a]= 255;
572                 else gamtab[a]= temp;
573         }
574
575         a= 4*me->totface;
576         cp= (unsigned char *)me->mcol;
577         while(a--) {
578                 
579                 cp[1]= gamtab[ cp[1] ];
580                 cp[2]= gamtab[ cp[2] ];
581                 cp[3]= gamtab[ cp[3] ];
582                 
583                 cp+= 4;
584         }
585 }
586
587 static unsigned int mcol_blend(unsigned int col1, unsigned int col2, int fac)
588 {
589         char *cp1, *cp2, *cp;
590         int mfac;
591         unsigned int col=0;
592         
593         if(fac==0) return col1;
594         if(fac>=255) return col2;
595
596         mfac= 255-fac;
597         
598         cp1= (char *)&col1;
599         cp2= (char *)&col2;
600         cp=  (char *)&col;
601         
602         cp[0]= 255;
603         cp[1]= (mfac*cp1[1]+fac*cp2[1])/255;
604         cp[2]= (mfac*cp1[2]+fac*cp2[2])/255;
605         cp[3]= (mfac*cp1[3]+fac*cp2[3])/255;
606         
607         return col;
608 }
609
610 static unsigned int mcol_add(unsigned int col1, unsigned int col2, int fac)
611 {
612         char *cp1, *cp2, *cp;
613         int temp;
614         unsigned int col=0;
615         
616         if(fac==0) return col1;
617         
618         cp1= (char *)&col1;
619         cp2= (char *)&col2;
620         cp=  (char *)&col;
621         
622         cp[0]= 255;
623         temp= cp1[1] + ((fac*cp2[1])/255);
624         if(temp>254) cp[1]= 255; else cp[1]= temp;
625         temp= cp1[2] + ((fac*cp2[2])/255);
626         if(temp>254) cp[2]= 255; else cp[2]= temp;
627         temp= cp1[3] + ((fac*cp2[3])/255);
628         if(temp>254) cp[3]= 255; else cp[3]= temp;
629         
630         return col;
631 }
632
633 static unsigned int mcol_sub(unsigned int col1, unsigned int col2, int fac)
634 {
635         char *cp1, *cp2, *cp;
636         int temp;
637         unsigned int col=0;
638         
639         if(fac==0) return col1;
640         
641         cp1= (char *)&col1;
642         cp2= (char *)&col2;
643         cp=  (char *)&col;
644         
645         cp[0]= 255;
646         temp= cp1[1] - ((fac*cp2[1])/255);
647         if(temp<0) cp[1]= 0; else cp[1]= temp;
648         temp= cp1[2] - ((fac*cp2[2])/255);
649         if(temp<0) cp[2]= 0; else cp[2]= temp;
650         temp= cp1[3] - ((fac*cp2[3])/255);
651         if(temp<0) cp[3]= 0; else cp[3]= temp;
652         
653         return col;
654 }
655
656 static unsigned int mcol_mul(unsigned int col1, unsigned int col2, int fac)
657 {
658         char *cp1, *cp2, *cp;
659         int mfac;
660         unsigned int col=0;
661         
662         if(fac==0) return col1;
663
664         mfac= 255-fac;
665         
666         cp1= (char *)&col1;
667         cp2= (char *)&col2;
668         cp=  (char *)&col;
669         
670         /* first mul, then blend the fac */
671         cp[0]= 255;
672         cp[1]= (mfac*cp1[1] + fac*((cp2[1]*cp1[1])/255)  )/255;
673         cp[2]= (mfac*cp1[2] + fac*((cp2[2]*cp1[2])/255)  )/255;
674         cp[3]= (mfac*cp1[3] + fac*((cp2[3]*cp1[3])/255)  )/255;
675
676         
677         return col;
678 }
679
680 static unsigned int mcol_lighten(unsigned int col1, unsigned int col2, int fac)
681 {
682         char *cp1, *cp2, *cp;
683         int mfac;
684         unsigned int col=0;
685         
686         if(fac==0) return col1;
687         if(fac>=255) return col2;
688
689         mfac= 255-fac;
690         
691         cp1= (char *)&col1;
692         cp2= (char *)&col2;
693         cp=  (char *)&col;
694         
695         /* See if are lighter, if so mix, else dont do anything.
696         if the paint col is darker then the original, then ignore */
697         if (cp1[1]+cp1[2]+cp1[3] > cp2[1]+cp2[2]+cp2[3])
698                 return col1;
699         
700         cp[0]= 255;
701         cp[1]= (mfac*cp1[1]+fac*cp2[1])/255;
702         cp[2]= (mfac*cp1[2]+fac*cp2[2])/255;
703         cp[3]= (mfac*cp1[3]+fac*cp2[3])/255;
704         
705         return col;
706 }
707
708 static unsigned int mcol_darken(unsigned int col1, unsigned int col2, int fac)
709 {
710         char *cp1, *cp2, *cp;
711         int mfac;
712         unsigned int col=0;
713         
714         if(fac==0) return col1;
715         if(fac>=255) return col2;
716
717         mfac= 255-fac;
718         
719         cp1= (char *)&col1;
720         cp2= (char *)&col2;
721         cp=  (char *)&col;
722         
723         /* See if were darker, if so mix, else dont do anything.
724         if the paint col is brighter then the original, then ignore */
725         if (cp1[1]+cp1[2]+cp1[3] < cp2[1]+cp2[2]+cp2[3])
726                 return col1;
727         
728         cp[0]= 255;
729         cp[1]= (mfac*cp1[1]+fac*cp2[1])/255;
730         cp[2]= (mfac*cp1[2]+fac*cp2[2])/255;
731         cp[3]= (mfac*cp1[3]+fac*cp2[3])/255;
732         return col;
733 }
734
735 static void vpaint_blend(VPaint *vp, unsigned int *col, unsigned int *colorig, unsigned int paintcol, int alpha)
736 {
737         Brush *brush = paint_brush(&vp->paint);
738
739         if(vp->mode==VP_MIX || vp->mode==VP_BLUR) *col= mcol_blend( *col, paintcol, alpha);
740         else if(vp->mode==VP_ADD) *col= mcol_add( *col, paintcol, alpha);
741         else if(vp->mode==VP_SUB) *col= mcol_sub( *col, paintcol, alpha);
742         else if(vp->mode==VP_MUL) *col= mcol_mul( *col, paintcol, alpha);
743         else if(vp->mode==VP_LIGHTEN) *col= mcol_lighten( *col, paintcol, alpha);
744         else if(vp->mode==VP_DARKEN) *col= mcol_darken( *col, paintcol, alpha);
745         
746         /* if no spray, clip color adding with colorig & orig alpha */
747         if((vp->flag & VP_SPRAY)==0) {
748                 unsigned int testcol=0, a;
749                 char *cp, *ct, *co;
750                 
751                 alpha= (int)(255.0*brush->alpha);
752                 
753                 if(vp->mode==VP_MIX || vp->mode==VP_BLUR) testcol= mcol_blend( *colorig, paintcol, alpha);
754                 else if(vp->mode==VP_ADD) testcol= mcol_add( *colorig, paintcol, alpha);
755                 else if(vp->mode==VP_SUB) testcol= mcol_sub( *colorig, paintcol, alpha);
756                 else if(vp->mode==VP_MUL) testcol= mcol_mul( *colorig, paintcol, alpha);
757                 else if(vp->mode==VP_LIGHTEN)  testcol= mcol_lighten( *colorig, paintcol, alpha);
758                 else if(vp->mode==VP_DARKEN)   testcol= mcol_darken( *colorig, paintcol, alpha);
759                 
760                 cp= (char *)col;
761                 ct= (char *)&testcol;
762                 co= (char *)colorig;
763                 
764                 for(a=0; a<4; a++) {
765                         if( ct[a]<co[a] ) {
766                                 if( cp[a]<ct[a] ) cp[a]= ct[a];
767                                 else if( cp[a]>co[a] ) cp[a]= co[a];
768                         }
769                         else {
770                                 if( cp[a]<co[a] ) cp[a]= co[a];
771                                 else if( cp[a]>ct[a] ) cp[a]= ct[a];
772                         }
773                 }
774         }
775 }
776
777
778 static int sample_backbuf_area(ViewContext *vc, int *indexar, int totface, int x, int y, float size)
779 {
780         struct ImBuf *ibuf;
781         int a, tot=0, index;
782         
783         if(totface+4>=MAXINDEX) return 0;
784         
785         /* brecht: disabled this because it obviously failes for
786            brushes with size > 64, why is this here? */
787         /*if(size>64.0) size= 64.0;*/
788         
789         ibuf= view3d_read_backbuf(vc, x-size, y-size, x+size, y+size);
790         if(ibuf) {
791                 unsigned int *rt= ibuf->rect;
792
793                 memset(indexar, 0, sizeof(int)*totface+4);      /* plus 2! first element is total, +2 was giving valgrind errors, +4 seems ok */
794                 
795                 size= ibuf->x*ibuf->y;
796                 while(size--) {
797                                 
798                         if(*rt) {
799                                 index= WM_framebuffer_to_index(*rt);
800                                 if(index>0 && index<=totface)
801                                         indexar[index] = 1;
802                         }
803                 
804                         rt++;
805                 }
806                 
807                 for(a=1; a<=totface; a++) {
808                         if(indexar[a]) indexar[tot++]= a;
809                 }
810
811                 IMB_freeImBuf(ibuf);
812         }
813         
814         return tot;
815 }
816
817 static int calc_vp_alpha_dl(VPaint *vp, ViewContext *vc, float vpimat[][3], float *vert_nor, float *mval)
818 {
819         Brush *brush = paint_brush(&vp->paint);
820         float fac, dx, dy;
821         int alpha;
822         short vertco[2];
823         
824         if(vp->flag & VP_SOFT) {
825                 project_short_noclip(vc->ar, vert_nor, vertco);
826                 dx= mval[0]-vertco[0];
827                 dy= mval[1]-vertco[1];
828                 
829                 fac= sqrt(dx*dx + dy*dy);
830                 if(fac > brush->size) return 0;
831                 if(vp->flag & VP_HARD)
832                         alpha= 255;
833                 else
834                         alpha= 255.0*brush->alpha*(1.0-fac/brush->size);
835         }
836         else {
837                 alpha= 255.0*brush->alpha;
838         }
839
840         if(vp->flag & VP_NORMALS) {
841                 float *no= vert_nor+3;
842                 
843                         /* transpose ! */
844                 fac= vpimat[2][0]*no[0]+vpimat[2][1]*no[1]+vpimat[2][2]*no[2];
845                 if(fac>0.0) {
846                         dx= vpimat[0][0]*no[0]+vpimat[0][1]*no[1]+vpimat[0][2]*no[2];
847                         dy= vpimat[1][0]*no[0]+vpimat[1][1]*no[1]+vpimat[1][2]*no[2];
848                         
849                         alpha*= fac/sqrt(dx*dx + dy*dy + fac*fac);
850                 }
851                 else return 0;
852         }
853         
854         return alpha;
855 }
856
857 static void wpaint_blend(VPaint *wp, MDeformWeight *dw, MDeformWeight *uw, float alpha, float paintval)
858 {
859         Brush *brush = paint_brush(&wp->paint);
860         
861         if(dw==NULL || uw==NULL) return;
862         
863         if(wp->mode==VP_MIX || wp->mode==VP_BLUR)
864                 dw->weight = paintval*alpha + dw->weight*(1.0-alpha);
865         else if(wp->mode==VP_ADD)
866                 dw->weight += paintval*alpha;
867         else if(wp->mode==VP_SUB) 
868                 dw->weight -= paintval*alpha;
869         else if(wp->mode==VP_MUL) 
870                 /* first mul, then blend the fac */
871                 dw->weight = ((1.0-alpha) + alpha*paintval)*dw->weight;
872         else if(wp->mode==VP_LIGHTEN) {
873                 if (dw->weight < paintval)
874                         dw->weight = paintval*alpha + dw->weight*(1.0-alpha);
875         } else if(wp->mode==VP_DARKEN) {
876                 if (dw->weight > paintval)
877                         dw->weight = paintval*alpha + dw->weight*(1.0-alpha);
878         }
879         CLAMP(dw->weight, 0.0f, 1.0f);
880         
881         /* if no spray, clip result with orig weight & orig alpha */
882         if((wp->flag & VP_SPRAY)==0) {
883                 float testw=0.0f;
884                 
885                 alpha= brush->alpha;
886                 if(wp->mode==VP_MIX || wp->mode==VP_BLUR)
887                         testw = paintval*alpha + uw->weight*(1.0-alpha);
888                 else if(wp->mode==VP_ADD)
889                         testw = uw->weight + paintval*alpha;
890                 else if(wp->mode==VP_SUB) 
891                         testw = uw->weight - paintval*alpha;
892                 else if(wp->mode==VP_MUL) 
893                         /* first mul, then blend the fac */
894                         testw = ((1.0-alpha) + alpha*paintval)*uw->weight;              
895                 else if(wp->mode==VP_LIGHTEN) {
896                         if (uw->weight < paintval)
897                                 testw = paintval*alpha + uw->weight*(1.0-alpha);
898                         else
899                                 testw = uw->weight;
900                 } else if(wp->mode==VP_DARKEN) {
901                         if (uw->weight > paintval)
902                                 testw = paintval*alpha + uw->weight*(1.0-alpha);
903                         else
904                                 testw = uw->weight;
905                 }
906                 CLAMP(testw, 0.0f, 1.0f);
907                 
908                 if( testw<uw->weight ) {
909                         if(dw->weight < testw) dw->weight= testw;
910                         else if(dw->weight > uw->weight) dw->weight= uw->weight;
911                 }
912                 else {
913                         if(dw->weight > testw) dw->weight= testw;
914                         else if(dw->weight < uw->weight) dw->weight= uw->weight;
915                 }
916         }
917         
918 }
919
920 /* ----------------------------------------------------- */
921
922 /* used for 3d view, on active object, assumes me->dvert exists */
923 /* if mode==1: */
924 /*     samples cursor location, and gives menu with vertex groups to activate */
925 /* else */
926 /*     sets wp->weight to the closest weight value to vertex */
927 /*     note: we cant sample frontbuf, weight colors are interpolated too unpredictable */
928 #if 0
929 void sample_wpaint(Scene *scene, ARegion *ar, View3D *v3d, int mode)
930 {
931         ViewContext vc;
932         ToolSettings *ts= scene->toolsettings;
933         Object *ob= OBACT;
934         Mesh *me= get_mesh(ob);
935         int index, i;
936         short mval[2] = {0, 0}, sco[2];
937
938         if (!me) return;
939         
940 //      getmouseco_areawin(mval);
941         index= view3d_sample_backbuf(&vc, mval[0], mval[1]);
942         
943         if(index && index<=me->totpoly) {
944                 MPoly *mpoly;
945                 
946                 mpoly= ((MPoly *)me->mpoly) + index-1;          
947                 if(mode==1) {   /* sampe which groups are in here */
948                         MDeformVert *dv;
949                         MLoop *ml;
950                         int a, totgroup;
951                         
952                         totgroup= BLI_countlist(&ob->defbase);
953                         if(totgroup) {
954                                 int totmenu=0;
955                                 int *groups=MEM_callocN(totgroup*sizeof(int), "groups");
956                                 
957                                 ml = me->mloop+mpoly->loopstart;
958                                 for (i=0; i<mpoly->totloop; i++, ml++) {
959                                         dv = me->dvert+ml->v;
960                                         if (dv->dw[a].def_nr<totgroup)
961                                                 groups[dv->dw[a].def_nr]= 1;
962                                         
963                                 }
964
965                                 for(a=0; a<totgroup; a++)
966                                         if(groups[a]) totmenu++;
967                                 
968                                 if(totmenu==0) {
969                                         //notice("No Vertex Group Selected");
970                                 }
971                                 else {
972                                         bDeformGroup *dg;
973                                         short val;
974                                         char item[40], *str= MEM_mallocN(40*totmenu+40, "menu");
975                                         
976                                         strcpy(str, "Vertex Groups %t");
977                                         for(a=0, dg=ob->defbase.first; dg && a<totgroup; a++, dg= dg->next) {
978                                                 if(groups[a]) {
979                                                         sprintf(item, "|%s %%x%d", dg->name, a);
980                                                         strcat(str, item);
981                                                 }
982                                         }
983                                         
984                                         val= 0; // XXX pupmenu(str);
985                                         if(val>=0) {
986                                                 ob->actdef= val+1;
987                                                 DAG_id_flush_update(&me->id, OB_RECALC_DATA);
988                                         }
989                                         MEM_freeN(str);
990                                 }
991                                 MEM_freeN(groups);
992                         }
993 //                      else notice("No Vertex Groups in Object");
994                 }
995                 else {
996                         DerivedMesh *dm;
997                         MDeformWeight *dw;
998                         MLoop *ml;
999                         float w, co[3], fmin = 10000000.0f;
1000                         int loopi = mpoly->loopstart;
1001                         
1002                         dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
1003                         if(dm->getVertCo==NULL) {
1004                                 //notice("Not supported yet");
1005                         }
1006                         else {
1007                                 /* find minimum distance */
1008                                 ml = me->mloop + mpoly->loopstart;
1009                                 for (i=0; i<mpoly->totloop; i++, ml++) {
1010                                         dm->getVertCo(dm, ml->v, co);
1011                                         project_short_noclip(ar, co, sco);
1012                                         w4= ((mval[0]-sco[0])*(mval[0]-sco[0]) + (mval[1]-sco[1])*(mval[1]-sco[1]));
1013                                 }
1014                                 else w4= 1.0e10;
1015                                 
1016                                 fac= MIN4(w1, w2, w3, w4);
1017                                 if(w1==fac) {
1018                                         dw= ED_vgroup_weight_get(me->dvert+mface->v1, ob->actdef-1);
1019                                         if(dw) ts->vgroup_weight= dw->weight; else ts->vgroup_weight= 0.0f;
1020                                 }
1021                                 else if(w2==fac) {
1022                                         dw= ED_vgroup_weight_get(me->dvert+mface->v2, ob->actdef-1);
1023                                         if(dw) ts->vgroup_weight= dw->weight; else ts->vgroup_weight= 0.0f;
1024                                 }
1025                                 else if(w3==fac) {
1026                                         dw= ED_vgroup_weight_get(me->dvert+mface->v3, ob->actdef-1);
1027                                         if(dw) ts->vgroup_weight= dw->weight; else ts->vgroup_weight= 0.0f;
1028                                 }
1029                                 else if(w4==fac) {
1030                                         if(mface->v4) {
1031                                                 dw= ED_vgroup_weight_get(me->dvert+mface->v4, ob->actdef-1);
1032                                                 if(dw) ts->vgroup_weight= dw->weight; else ts->vgroup_weight= 0.0f;
1033 >>>>>>> .merge-right.r23146
1034                                         }
1035                                 }
1036
1037                                 ml = me->mloop + loopi;
1038                                 dw= get_defweight(me->dvert+ml->v, ob->actdef-1);
1039                                 if(dw) ts->vgroup_weight= dw->weight; else ts->vgroup_weight= 0.0f;
1040                         }
1041                         dm->release(dm);
1042                 }               
1043                 
1044         }
1045         
1046 }
1047 #endif
1048
1049 static void do_weight_paint_auto_normalize(MDeformVert *dvert, 
1050                                            int paint_nr, char *map)
1051 {
1052 //      MDeformWeight *dw = dvert->dw;
1053         float sum=0.0f, fac=0.0f, paintw=0.0f;
1054         int i, tot=0;
1055
1056         if (!map)
1057                 return;
1058
1059         for (i=0; i<dvert->totweight; i++) {
1060                 if (dvert->dw[i].def_nr == paint_nr)
1061                         paintw = dvert->dw[i].weight;
1062
1063                 if (map[dvert->dw[i].def_nr]) {
1064                         tot += 1;
1065                         if (dvert->dw[i].def_nr != paint_nr)
1066                                 sum += dvert->dw[i].weight;
1067                 }
1068         }
1069         
1070         if (!tot || sum <= (1.0f - paintw))
1071                 return;
1072
1073         fac = sum / (1.0f - paintw);
1074         fac = fac==0.0f ? 1.0f : 1.0f / fac;
1075
1076         for (i=0; i<dvert->totweight; i++) {
1077                 if (map[dvert->dw[i].def_nr]) {
1078                         if (dvert->dw[i].def_nr != paint_nr)
1079                                 dvert->dw[i].weight *= fac;
1080                 }
1081         }
1082 }
1083
1084 static void do_weight_paint_vertex(VPaint *wp, Object *ob, int index, 
1085                                    int alpha, float paintweight, 
1086                                    int vgroup_mirror, char *validmap)
1087 {
1088         Mesh *me= ob->data;
1089         MDeformWeight *dw, *uw;
1090         int vgroup= ob->actdef-1;
1091         
1092         if(wp->flag & VP_ONLYVGROUP) {
1093                 dw= ED_vgroup_weight_get(me->dvert+index, vgroup);
1094                 uw= ED_vgroup_weight_get(wp->wpaint_prev+index, vgroup);
1095         }
1096         else {
1097                 dw= ED_vgroup_weight_verify(me->dvert+index, vgroup);
1098                 uw= ED_vgroup_weight_verify(wp->wpaint_prev+index, vgroup);
1099         }
1100         if(dw==NULL || uw==NULL)
1101                 return;
1102         
1103         wpaint_blend(wp, dw, uw, (float)alpha/255.0, paintweight);
1104         do_weight_paint_auto_normalize(me->dvert+index, vgroup, validmap);
1105
1106         if(me->editflag & ME_EDIT_MIRROR_X) {   /* x mirror painting */
1107                 int j= mesh_get_x_mirror_vert(ob, index);
1108                 if(j>=0) {
1109                         /* copy, not paint again */
1110                         if(vgroup_mirror != -1)
1111                                 uw= ED_vgroup_weight_verify(me->dvert+j, vgroup_mirror);
1112                         else
1113                                 uw= ED_vgroup_weight_verify(me->dvert+j, vgroup);
1114                                 
1115                         uw->weight= dw->weight;
1116
1117                         do_weight_paint_auto_normalize(me->dvert+j, vgroup, validmap);
1118                 }
1119         }
1120 }
1121
1122
1123 /* *************** set wpaint operator ****************** */
1124
1125 static int set_wpaint(bContext *C, wmOperator *op)              /* toggle */
1126 {               
1127         Object *ob= CTX_data_active_object(C);
1128         Scene *scene= CTX_data_scene(C);
1129         VPaint *wp= scene->toolsettings->wpaint;
1130         Mesh *me;
1131         
1132         me= get_mesh(ob);
1133         if(ob->id.lib || me==NULL) return OPERATOR_PASS_THROUGH;
1134         
1135         if(me && me->totface>=MAXINDEX) {
1136                 error("Maximum number of faces: %d", MAXINDEX-1);
1137                 ob->mode &= ~OB_MODE_WEIGHT_PAINT;
1138                 return OPERATOR_CANCELLED;
1139         }
1140         
1141         if(ob->mode & OB_MODE_WEIGHT_PAINT) ob->mode &= ~OB_MODE_WEIGHT_PAINT;
1142         else ob->mode |= OB_MODE_WEIGHT_PAINT;
1143         
1144         
1145         /* Weightpaint works by overriding colors in mesh,
1146                 * so need to make sure we recalc on enter and
1147                 * exit (exit needs doing regardless because we
1148                                 * should redeform).
1149                 */
1150         DAG_id_flush_update(&me->id, OB_RECALC_DATA);
1151         
1152         if(ob->mode & OB_MODE_WEIGHT_PAINT) {
1153                 Object *par;
1154                 
1155                 if(wp==NULL)
1156                         wp= scene->toolsettings->wpaint= new_vpaint(1);
1157
1158                 paint_init(&wp->paint, PAINT_CURSOR_WEIGHT_PAINT);
1159                 paint_cursor_start(C, weight_paint_poll);
1160                 
1161                 mesh_octree_table(ob, NULL, NULL, 's');
1162                 
1163                 /* verify if active weight group is also active bone */
1164                 par= modifiers_isDeformedByArmature(ob);
1165                 if(par && (par->mode & OB_MODE_POSE)) {
1166                         bArmature *arm= ob->data;
1167
1168                         if(arm->act_bone)
1169                                 ED_vgroup_select_by_name(ob, arm->act_bone->name);
1170                 }
1171         }
1172         else {
1173                 mesh_octree_table(ob, NULL, NULL, 'e');
1174         }
1175         
1176         WM_event_add_notifier(C, NC_SCENE|ND_MODE, scene);
1177         
1178         return OPERATOR_FINISHED;
1179 }
1180
1181 /* for switching to/from mode */
1182 static int paint_poll_test(bContext *C)
1183 {
1184         if(ED_operator_view3d_active(C)==0)
1185                 return 0;
1186         if(CTX_data_edit_object(C))
1187                 return 0;
1188         if(CTX_data_active_object(C)==NULL)
1189                 return 0;
1190         return 1;
1191 }
1192
1193 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
1194 {
1195         
1196         /* identifiers */
1197         ot->name= "Weight Paint Mode";
1198         ot->idname= "PAINT_OT_weight_paint_toggle";
1199         
1200         /* api callbacks */
1201         ot->exec= set_wpaint;
1202         ot->poll= paint_poll_test;
1203         
1204         /* flags */
1205         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1206         
1207 }
1208
1209 /* ************ paint radial controls *************/
1210
1211 static int vpaint_radial_control_invoke(bContext *C, wmOperator *op, wmEvent *event)
1212 {
1213         Paint *p = paint_get_active(CTX_data_scene(C));
1214         Brush *brush = paint_brush(p);
1215         
1216         WM_paint_cursor_end(CTX_wm_manager(C), p->paint_cursor);
1217         p->paint_cursor = NULL;
1218         brush_radial_control_invoke(op, brush, 1);
1219         return WM_radial_control_invoke(C, op, event);
1220 }
1221
1222 static int vpaint_radial_control_modal(bContext *C, wmOperator *op, wmEvent *event)
1223 {
1224         int ret = WM_radial_control_modal(C, op, event);
1225         if(ret != OPERATOR_RUNNING_MODAL)
1226                 paint_cursor_start(C, vertex_paint_poll);
1227         return ret;
1228 }
1229
1230 static int vpaint_radial_control_exec(bContext *C, wmOperator *op)
1231 {
1232         Brush *brush = paint_brush(&CTX_data_scene(C)->toolsettings->vpaint->paint);
1233         int ret = brush_radial_control_exec(op, brush, 1);
1234         
1235         WM_event_add_notifier(C, NC_BRUSH|NA_EDITED, brush);
1236         
1237         return ret;
1238 }
1239
1240 static int wpaint_radial_control_invoke(bContext *C, wmOperator *op, wmEvent *event)
1241 {
1242         Paint *p = paint_get_active(CTX_data_scene(C));
1243         Brush *brush = paint_brush(p);
1244         
1245         WM_paint_cursor_end(CTX_wm_manager(C), p->paint_cursor);
1246         p->paint_cursor = NULL;
1247         brush_radial_control_invoke(op, brush, 1);
1248         return WM_radial_control_invoke(C, op, event);
1249 }
1250
1251 static int wpaint_radial_control_modal(bContext *C, wmOperator *op, wmEvent *event)
1252 {
1253         int ret = WM_radial_control_modal(C, op, event);
1254         if(ret != OPERATOR_RUNNING_MODAL)
1255                 paint_cursor_start(C, weight_paint_poll);
1256         return ret;
1257 }
1258
1259 static int wpaint_radial_control_exec(bContext *C, wmOperator *op)
1260 {
1261         Brush *brush = paint_brush(&CTX_data_scene(C)->toolsettings->wpaint->paint);
1262         int ret = brush_radial_control_exec(op, brush, 1);
1263         
1264         WM_event_add_notifier(C, NC_BRUSH|NA_EDITED, brush);
1265         
1266         return ret;
1267 }
1268
1269 void PAINT_OT_weight_paint_radial_control(wmOperatorType *ot)
1270 {
1271         WM_OT_radial_control_partial(ot);
1272
1273         ot->name= "Weight Paint Radial Control";
1274         ot->idname= "PAINT_OT_weight_paint_radial_control";
1275
1276         ot->invoke= wpaint_radial_control_invoke;
1277         ot->modal= wpaint_radial_control_modal;
1278         ot->exec= wpaint_radial_control_exec;
1279         ot->poll= weight_paint_poll;
1280         
1281         /* flags */
1282         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
1283 }
1284
1285 void PAINT_OT_vertex_paint_radial_control(wmOperatorType *ot)
1286 {
1287         WM_OT_radial_control_partial(ot);
1288
1289         ot->name= "Vertex Paint Radial Control";
1290         ot->idname= "PAINT_OT_vertex_paint_radial_control";
1291
1292         ot->invoke= vpaint_radial_control_invoke;
1293         ot->modal= vpaint_radial_control_modal;
1294         ot->exec= vpaint_radial_control_exec;
1295         ot->poll= vertex_paint_poll;
1296         
1297         /* flags */
1298         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
1299 }
1300
1301 /* ************ weight paint operator ********** */
1302
1303 struct WPaintData {
1304         ViewContext vc;
1305         int *indexar;
1306         int vgroup_mirror;
1307         float *vertexcosnos;
1308         float wpimat[3][3];
1309         
1310         /*variables for auto normalize*/
1311         int auto_normalize;
1312         char *vgroup_validmap; /*stores if vgroups tie to deforming bones or not*/
1313 };
1314
1315 static char *wpaint_make_validmap(Mesh *me, Object *ob)
1316 {
1317         bDeformGroup *dg;
1318         ModifierData *md;
1319         char *validmap;
1320         bPose *pose;
1321         bPoseChannel *chan;
1322         ArmatureModifierData *amd;
1323         GHash *gh = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp);
1324         int i = 0, step1=1;
1325
1326         /*add all names to a hash table*/
1327         for (dg=ob->defbase.first, i=0; dg; dg=dg->next, i++) {
1328                 BLI_ghash_insert(gh, dg->name, NULL);
1329         }
1330
1331         if (!i)
1332                 return NULL;
1333
1334         validmap = MEM_callocN(i, "wpaint valid map");
1335
1336         /*now loop through the armature modifiers and identify deform bones*/
1337         for (md = ob->modifiers.first; md; md= !md->next && step1 ? (step1=0), modifiers_getVirtualModifierList(ob) : md->next) {
1338                 if (!(md->mode & (eModifierMode_Realtime|eModifierMode_Virtual)))
1339                         continue;
1340
1341                 if (md->type == eModifierType_Armature) 
1342                 {
1343                         amd = (ArmatureModifierData*) md;
1344                         pose = amd->object->pose;
1345                         
1346                         for (chan=pose->chanbase.first; chan; chan=chan->next) {
1347                                 if (chan->bone->flag & BONE_NO_DEFORM)
1348                                         continue;
1349
1350                                 if (BLI_ghash_haskey(gh, chan->name)) {
1351                                         BLI_ghash_remove(gh, chan->name, NULL, NULL);
1352                                         BLI_ghash_insert(gh, chan->name, SET_INT_IN_POINTER(1));
1353                                 }
1354                         }
1355                 }
1356         }
1357         
1358         /*add all names to a hash table*/
1359         for (dg=ob->defbase.first, i=0; dg; dg=dg->next, i++) {
1360                 if (BLI_ghash_lookup(gh, dg->name) != NULL) {
1361                         validmap[i] = 1;
1362                 }
1363         }
1364
1365         BLI_ghash_free(gh, NULL, NULL);
1366
1367         return validmap;
1368 }
1369
1370 static int wpaint_stroke_test_start(bContext *C, wmOperator *op, wmEvent *event)
1371 {
1372         Scene *scene= CTX_data_scene(C);
1373         struct PaintStroke *stroke = op->customdata;
1374         ToolSettings *ts= CTX_data_tool_settings(C);
1375         VPaint *wp= ts->wpaint;
1376         Object *ob= CTX_data_active_object(C);
1377         struct WPaintData *wpd;
1378         Mesh *me;
1379         float mat[4][4], imat[4][4];
1380         
1381         if(scene->obedit) return OPERATOR_CANCELLED;
1382         
1383         me= get_mesh(ob);
1384         if(me==NULL || me->totface==0) return OPERATOR_PASS_THROUGH;
1385         
1386         /*we can't assume mfaces have a correct origindex layer that indices to mpolys.
1387           so instead we have to regenerate the tesselation faces altogether.*/
1388         me->totface = mesh_recalcTesselation(&me->fdata, &me->ldata, &me->pdata, 
1389                 me->mvert, me->totface, me->totloop, me->totpoly, 1);
1390         mesh_update_customdata_pointers(me);
1391         makeDerivedMesh(scene, ob, NULL, CD_MASK_BAREMESH);
1392
1393         /* if nothing was added yet, we make dverts and a vertex deform group */
1394         if (!me->dvert)
1395                 ED_vgroup_data_create(&me->id);
1396         
1397         /* make mode data storage */
1398         wpd= MEM_callocN(sizeof(struct WPaintData), "WPaintData");
1399         paint_stroke_set_mode_data(stroke, wpd);
1400         view3d_set_viewcontext(C, &wpd->vc);
1401         wpd->vgroup_mirror= -1;
1402         
1403         /*set up auto-normalize, and generate map for detecting which
1404           vgroups affect deform bones*/
1405         wpd->auto_normalize = ts->auto_normalize;
1406         if (wpd->auto_normalize)
1407                 wpd->vgroup_validmap = wpaint_make_validmap(me, ob);
1408         
1409         //      if(qual & LR_CTRLKEY) {
1410         //              sample_wpaint(scene, ar, v3d, 0);
1411         //              return;
1412         //      }
1413         //      if(qual & LR_SHIFTKEY) {
1414         //              sample_wpaint(scene, ar, v3d, 1);
1415         //              return;
1416         //      }
1417         
1418         /* ALLOCATIONS! no return after this line */
1419         /* painting on subsurfs should give correct points too, this returns me->totvert amount */
1420         wpd->vertexcosnos= mesh_get_mapped_verts_nors(scene, ob);
1421         wpd->indexar= get_indexarray();
1422         copy_wpaint_prev(wp, me->dvert, me->totvert);
1423         
1424         /* this happens on a Bone select, when no vgroup existed yet */
1425         if(ob->actdef<=0) {
1426                 Object *modob;
1427                 if((modob = modifiers_isDeformedByArmature(ob))) {
1428                         bPoseChannel *pchan;
1429                         for(pchan= modob->pose->chanbase.first; pchan; pchan= pchan->next)
1430                                 if(pchan->bone->flag & SELECT)
1431                                         break;
1432                         if(pchan) {
1433                                 bDeformGroup *dg= get_named_vertexgroup(ob, pchan->name);
1434                                 if(dg==NULL)
1435                                         dg= ED_vgroup_add_name(ob, pchan->name);        /* sets actdef */
1436                                 else
1437                                         ob->actdef= get_defgroup_num(ob, dg);
1438                         }
1439                 }
1440         }
1441         if(ob->defbase.first==NULL) {
1442                 ED_vgroup_add(ob);
1443         }       
1444         
1445         //      if(ob->lay & v3d->lay); else error("Active object is not in this layer");
1446         
1447         /* imat for normals */
1448         mul_m4_m4m4(mat, ob->obmat, wpd->vc.rv3d->viewmat);
1449         invert_m4_m4(imat, mat);
1450         copy_m3_m4(wpd->wpimat, imat);
1451         
1452         /* if mirror painting, find the other group */
1453         if(me->editflag & ME_EDIT_MIRROR_X) {
1454                 bDeformGroup *defgroup= BLI_findlink(&ob->defbase, ob->actdef-1);
1455                 if(defgroup) {
1456                         bDeformGroup *curdef;
1457                         int actdef= 0;
1458                         char name[32];
1459                         
1460                         BLI_strncpy(name, defgroup->name, 32);
1461                         bone_flip_name(name, 0);                /* 0 = don't strip off number extensions */
1462                         
1463                         for (curdef = ob->defbase.first; curdef; curdef=curdef->next, actdef++)
1464                                 if (!strcmp(curdef->name, name))
1465                                         break;
1466                         if(curdef==NULL) {
1467                                 int olddef= ob->actdef; /* tsk, ED_vgroup_add sets the active defgroup */
1468                                 curdef= ED_vgroup_add_name (ob, name);
1469                                 ob->actdef= olddef;
1470                         }
1471                         
1472                         if(curdef && curdef!=defgroup)
1473                                 wpd->vgroup_mirror= actdef;
1474                 }
1475         }
1476         
1477         return 1;
1478 }
1479
1480 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
1481 {
1482         ToolSettings *ts= CTX_data_tool_settings(C);
1483         VPaint *wp= ts->wpaint;
1484         Brush *brush = paint_brush(&wp->paint);
1485         struct WPaintData *wpd= paint_stroke_mode_data(stroke);
1486         ViewContext *vc= &wpd->vc;
1487         Object *ob= vc->obact;
1488         Mesh *me= ob->data;
1489         float mat[4][4];
1490         float paintweight= ts->vgroup_weight;
1491         int *indexar= wpd->indexar;
1492         int totindex, index, alpha, totw;
1493         float mval[2];
1494
1495         view3d_operator_needs_opengl(C);
1496                         
1497         /* load projection matrix */
1498         wmMultMatrix(ob->obmat);
1499         wmGetSingleMatrix(mat);
1500         wmLoadMatrix(wpd->vc.rv3d->viewmat);
1501
1502         RNA_float_get_array(itemptr, "mouse", mval);
1503         mval[0]-= vc->ar->winrct.xmin;
1504         mval[1]-= vc->ar->winrct.ymin;
1505                         
1506         swap_m4m4(wpd->vc.rv3d->persmat, mat);
1507                         
1508         /* which faces are involved */
1509         if(wp->flag & VP_AREA) {
1510                 totindex= sample_backbuf_area(vc, indexar, me->totface, mval[0], mval[1], brush->size);
1511         }
1512         else {
1513                 indexar[0]= view3d_sample_backbuf(vc, mval[0], mval[1]);
1514                 if(indexar[0]) totindex= 1;
1515                 else totindex= 0;
1516         }
1517                         
1518         if(wp->flag & VP_COLINDEX) {
1519                 for(index=0; index<totindex; index++) {
1520                         if(indexar[index] && indexar[index]<=me->totpoly) {
1521                                 MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
1522                                                 
1523                                 if(mpoly->mat_nr!=ob->actcol-1) {
1524                                         indexar[index]= 0;
1525                                 }
1526                         }                                       
1527                 }
1528         }
1529                         
1530         if((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
1531                 for(index=0; index<totindex; index++) {
1532                         if(indexar[index] && indexar[index]<=me->totpoly) {
1533                                 MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
1534                                                 
1535                                 if((mpoly->flag & ME_FACE_SEL)==0) {
1536                                         indexar[index]= 0;
1537                                 }
1538                         }                                       
1539                 }
1540         }
1541                         
1542         /* make sure each vertex gets treated only once */
1543         /* and calculate filter weight */
1544         totw= 0;
1545         if(wp->mode==VP_BLUR) 
1546                 paintweight= 0.0f;
1547         else
1548                 paintweight= ts->vgroup_weight;
1549                         
1550         for(index=0; index<totindex; index++) {
1551                 if(indexar[index] && indexar[index]<=me->totpoly) {
1552                         MPoly *mpoly= me->mpoly + (indexar[index]-1);
1553                         MLoop *ml = me->mloop + mpoly->loopstart;
1554                         int i;
1555
1556                         for (i=0; i<mpoly->totloop; i++, ml++) {
1557                                 (me->dvert+ml->v)->flag = 1;
1558                         }
1559                                         
1560                         if(wp->mode==VP_BLUR) {
1561                                 MDeformWeight *dw, *(*dw_func)(MDeformVert *, int) = ED_vgroup_weight_verify;
1562                                                 
1563                                 if(wp->flag & VP_ONLYVGROUP)
1564                                         dw_func= ED_vgroup_weight_get;
1565                                                 
1566                                 ml = me->mloop + mpoly->loopstart;
1567                                 for (i=0; i<mpoly->totloop; i++, ml++) {
1568                                         dw = dw_func(me->dvert+ml->v, ob->actdef-1);
1569                                         if (dw) {
1570                                                 paintweight += dw->weight;
1571                                                 totw++;
1572                                         }                                       
1573                                 }
1574                         }
1575                 }
1576         }
1577                         
1578         if(wp->mode==VP_BLUR) 
1579                 paintweight/= (float)totw;
1580                         
1581         for(index=0; index<totindex; index++) {
1582                                 
1583                 if(indexar[index] && indexar[index]<=me->totpoly) {
1584                         MPoly *mpoly= me->mpoly + (indexar[index]-1);
1585                         MLoop *ml=me->mloop+mpoly->loopstart;
1586                         int i;
1587
1588                         for (i=0; i<mpoly->totloop; i++, ml++) {
1589                                 if ((me->dvert+ml->v)->flag) {
1590                                         alpha= calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos+6*ml->v, mval);
1591                                         if(alpha) {
1592                                                 do_weight_paint_vertex(wp, ob, ml->v, 
1593                                                         alpha, paintweight, wpd->vgroup_mirror, 
1594                                                         wpd->vgroup_validmap);
1595                                         }
1596                                         (me->dvert+ml->v)->flag= 0;
1597                                 }
1598                         }
1599                 }
1600         }
1601                         
1602         swap_m4m4(vc->rv3d->persmat, mat);
1603                         
1604         DAG_id_flush_update(ob->data, OB_RECALC_DATA);
1605         ED_region_tag_redraw(vc->ar);
1606 }
1607
1608 static void wpaint_stroke_done(bContext *C, struct PaintStroke *stroke)
1609 {
1610         ToolSettings *ts= CTX_data_tool_settings(C);
1611         Object *ob= CTX_data_active_object(C);
1612         struct WPaintData *wpd= paint_stroke_mode_data(stroke);
1613         
1614         if(wpd->vertexcosnos)
1615                 MEM_freeN(wpd->vertexcosnos);
1616         MEM_freeN(wpd->indexar);
1617         
1618         if (wpd->vgroup_validmap)
1619                 MEM_freeN(wpd->vgroup_validmap);
1620
1621         /* frees prev buffer */
1622         copy_wpaint_prev(ts->wpaint, NULL, 0);
1623         
1624         /* and particles too */
1625         if(ob->particlesystem.first) {
1626                 ParticleSystem *psys;
1627                 int i;
1628                 
1629                 for(psys= ob->particlesystem.first; psys; psys= psys->next) {
1630                         for(i=0; i<PSYS_TOT_VG; i++) {
1631                                 if(psys->vgroup[i]==ob->actdef) {
1632                                         psys->recalc |= PSYS_RECALC_RESET;
1633                                         break;
1634                                 }
1635                         }
1636                 }
1637         }
1638         
1639         DAG_id_flush_update(ob->data, OB_RECALC_DATA);
1640         
1641         MEM_freeN(wpd);
1642 }
1643
1644
1645 static int wpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
1646 {
1647         
1648         op->customdata = paint_stroke_new(C, wpaint_stroke_test_start,
1649                                           wpaint_stroke_update_step,
1650                                           wpaint_stroke_done);
1651         
1652         /* add modal handler */
1653         WM_event_add_modal_handler(C, op);
1654
1655         op->type->modal(C, op, event);
1656         
1657         return OPERATOR_RUNNING_MODAL;
1658 }
1659
1660 void PAINT_OT_weight_paint(wmOperatorType *ot)
1661 {
1662         
1663         /* identifiers */
1664         ot->name= "Weight Paint";
1665         ot->idname= "PAINT_OT_weight_paint";
1666         
1667         /* api callbacks */
1668         ot->invoke= wpaint_invoke;
1669         ot->modal= paint_stroke_modal;
1670         /* ot->exec= vpaint_exec; <-- needs stroke property */
1671         ot->poll= weight_paint_poll;
1672         
1673         /* flags */
1674         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
1675
1676         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
1677 }
1678
1679 static int weight_paint_set_exec(bContext *C, wmOperator *op)
1680 {
1681         struct Scene *scene= CTX_data_scene(C);
1682         Object *obact = CTX_data_active_object(C);
1683
1684         wpaint_fill(scene->toolsettings->wpaint, obact, scene->toolsettings->vgroup_weight);
1685         ED_region_tag_redraw(CTX_wm_region(C)); // XXX - should redraw all 3D views
1686         return OPERATOR_FINISHED;
1687 }
1688
1689 void PAINT_OT_weight_set(wmOperatorType *ot)
1690 {
1691         /* identifiers */
1692         ot->name= "Weight Set";
1693         ot->idname= "PAINT_OT_weight_set";
1694
1695         /* api callbacks */
1696         ot->exec= weight_paint_set_exec;
1697         ot->poll= facemask_paint_poll;
1698
1699         /* flags */
1700         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1701
1702         RNA_def_boolean(ot->srna, "extend", 0, "Extend", "Extend selection instead of deselecting everything first.");
1703 }
1704
1705 /* ************ set / clear vertex paint mode ********** */
1706
1707
1708 static int set_vpaint(bContext *C, wmOperator *op)              /* toggle */
1709 {       
1710         Object *ob= CTX_data_active_object(C);
1711         Scene *scene= CTX_data_scene(C);
1712         VPaint *vp= scene->toolsettings->vpaint;
1713         Mesh *me;
1714         
1715         me= get_mesh(ob);
1716         
1717         if(me==NULL || object_data_is_libdata(ob)) {
1718                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
1719                 return OPERATOR_PASS_THROUGH;
1720         }
1721         
1722         if(me && me->totface>=MAXINDEX) {
1723                 error("Maximum number of faces: %d", MAXINDEX-1);
1724                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
1725                 return OPERATOR_FINISHED;
1726         }
1727         
1728         if(me && me->mloopcol==NULL) make_vertexcol(ob);
1729         
1730         /* toggle: end vpaint */
1731         if(ob->mode & OB_MODE_VERTEX_PAINT) {
1732                 
1733                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
1734         }
1735         else {
1736                 ob->mode |= OB_MODE_VERTEX_PAINT;
1737                 /* Turn off weight painting */
1738                 if (ob->mode & OB_MODE_WEIGHT_PAINT)
1739                         set_wpaint(C, op);
1740                 
1741                 if(vp==NULL)
1742                         vp= scene->toolsettings->vpaint= new_vpaint(0);
1743                 
1744                 paint_cursor_start(C, vertex_paint_poll);
1745
1746                 paint_init(&vp->paint, PAINT_CURSOR_VERTEX_PAINT);
1747         }
1748         
1749         if (me)
1750                 /* update modifier stack for mapping requirements */
1751                 DAG_id_flush_update(&me->id, OB_RECALC_DATA);
1752         
1753         WM_event_add_notifier(C, NC_SCENE|ND_MODE, scene);
1754         
1755         return OPERATOR_FINISHED;
1756 }
1757
1758 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
1759 {
1760         
1761         /* identifiers */
1762         ot->name= "Vertex Paint Mode";
1763         ot->idname= "PAINT_OT_vertex_paint_toggle";
1764         
1765         /* api callbacks */
1766         ot->exec= set_vpaint;
1767         ot->poll= paint_poll_test;
1768         
1769         /* flags */
1770         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1771         
1772 }
1773
1774
1775
1776 /* ********************** vertex paint operator ******************* */
1777
1778 /* Implementation notes:
1779
1780 Operator->invoke()
1781   - validate context (add mcol)
1782   - create customdata storage
1783   - call paint once (mouse click)
1784   - add modal handler 
1785
1786 Operator->modal()
1787   - for every mousemove, apply vertex paint
1788   - exit on mouse release, free customdata
1789     (return OPERATOR_FINISHED also removes handler and operator)
1790
1791 For future:
1792   - implement a stroke event (or mousemove with past positons)
1793   - revise whether op->customdata should be added in object, in set_vpaint
1794
1795 */
1796
1797 typedef struct polyfacemap_e {
1798         struct polyfacemap_e *next, *prev;
1799         int facenr;
1800 } polyfacemap_e;
1801
1802 typedef struct VPaintData {
1803         ViewContext vc;
1804         unsigned int paintcol;
1805         int *indexar;
1806         float *vertexcosnos;
1807         float vpimat[3][3];
1808         
1809         /*mpoly -> mface mapping*/
1810         MemArena *arena;
1811         ListBase *polyfacemap;
1812 } VPaintData;
1813
1814 static void vpaint_build_poly_facemap(struct VPaintData *vd, Mesh *me,
1815                                       Object *ob, Scene *scene)
1816 {
1817         MFace *mf;
1818         polyfacemap_e *e;
1819         int *origIndex;
1820         int i;
1821
1822         vd->arena = BLI_memarena_new(1<<13);
1823         BLI_memarena_use_calloc(vd->arena);
1824
1825         vd->polyfacemap = BLI_memarena_alloc(vd->arena, sizeof(ListBase)*me->totpoly);
1826
1827         /*we can't assume mfaces have a correct origindex layer that indices to mpolys.
1828           so instead we have to regenerate the tesselation faces altogether.*/
1829         me->totface = mesh_recalcTesselation(&me->fdata, &me->ldata, &me->pdata, 
1830                 me->mvert, me->totface, me->totloop, me->totpoly, 1);
1831         mesh_update_customdata_pointers(me);
1832         makeDerivedMesh(scene, ob, NULL, CD_MASK_BAREMESH);
1833
1834         origIndex = CustomData_get_layer(&me->fdata, CD_ORIGINDEX);
1835         mf = me->mface;
1836
1837         if (!origIndex)
1838                 return;
1839
1840         for (i=0; i<me->totface; i++, mf++, origIndex++) {
1841                 if (*origIndex == ORIGINDEX_NONE)
1842                         continue;
1843
1844                 e = BLI_memarena_alloc(vd->arena, sizeof(polyfacemap_e));
1845                 e->facenr = i;
1846                 
1847                 BLI_addtail(&vd->polyfacemap[*origIndex], e);
1848         }
1849 }
1850
1851 static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, wmEvent *event)
1852 {
1853         ToolSettings *ts= CTX_data_tool_settings(C);
1854         struct PaintStroke *stroke = op->customdata;
1855         VPaint *vp= ts->vpaint;
1856         struct VPaintData *vpd;
1857         Object *ob= CTX_data_active_object(C);
1858         Scene *scene = CTX_data_scene(C);
1859         Mesh *me;
1860         float mat[4][4], imat[4][4];
1861
1862         /* context checks could be a poll() */
1863         me= get_mesh(ob);
1864         if(me==NULL || me->totpoly==0)
1865                 return OPERATOR_PASS_THROUGH;
1866         
1867         if(me->mloopcol==NULL)
1868                 make_vertexcol(ob);
1869         if(me->mloopcol==NULL)
1870                 return OPERATOR_CANCELLED;
1871
1872         /* make mode data storage */
1873         vpd= MEM_callocN(sizeof(struct VPaintData), "VPaintData");
1874         paint_stroke_set_mode_data(stroke, vpd);
1875         view3d_set_viewcontext(C, &vpd->vc);
1876         
1877         vpd->vertexcosnos= mesh_get_mapped_verts_nors(vpd->vc.scene, ob);
1878         vpd->indexar= get_indexarray();
1879         vpd->paintcol= vpaint_get_current_col(vp);
1880         vpaint_build_poly_facemap(vpd, me, ob, scene);
1881         
1882         /* for filtering */
1883         copy_vpaint_prev(vp, (unsigned int *)me->mloopcol, me->totloop);
1884         
1885         /* some old cruft to sort out later */
1886         mul_m4_m4m4(mat, ob->obmat, vpd->vc.rv3d->viewmat);
1887         invert_m4_m4(imat, mat);
1888         copy_m3_m4(vpd->vpimat, imat);
1889
1890         return 1;
1891 }
1892
1893 static void vpaint_paint_face(VPaint *vp, VPaintData *vpd, Object *ob, int index, float mval[2])
1894 {
1895         ViewContext *vc = &vpd->vc;
1896         Mesh *me = get_mesh(ob);
1897         MFace *mface= ((MFace*)me->mface) + index;
1898         unsigned int *mcol= ((unsigned int*)me->mcol) + 4*index;
1899         unsigned int *mcolorig= ((unsigned int*)vp->vpaint_prev) + 4*index;
1900         int alpha, i;
1901         
1902         if((vp->flag & VP_COLINDEX && mface->mat_nr!=ob->actcol-1) ||
1903            ((me->editflag & ME_EDIT_PAINT_MASK) && !(mface->flag & ME_FACE_SEL)))
1904                 return;
1905
1906         if(vp->mode==VP_BLUR) {
1907                 unsigned int fcol1= mcol_blend( mcol[0], mcol[1], 128);
1908                 if(mface->v4) {
1909                         unsigned int fcol2= mcol_blend( mcol[2], mcol[3], 128);
1910                         vpd->paintcol= mcol_blend( fcol1, fcol2, 128);
1911                 }
1912                 else {
1913                         vpd->paintcol= mcol_blend( mcol[2], fcol1, 170);
1914                 }
1915                 
1916         }
1917
1918         for(i = 0; i < (mface->v4 ? 4 : 3); ++i) {
1919                 alpha= calc_vp_alpha_dl(vp, vc, vpd->vpimat, vpd->vertexcosnos+6*(&mface->v1)[i], mval);
1920                 if(alpha)
1921                         vpaint_blend(vp, mcol+i, mcolorig+i, vpd->paintcol, alpha);
1922         }
1923 }
1924
1925 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
1926 {
1927         ToolSettings *ts= CTX_data_tool_settings(C);
1928         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
1929         VPaint *vp= ts->vpaint;
1930         Brush *brush = paint_brush(&vp->paint);
1931         ViewContext *vc= &vpd->vc;
1932         Object *ob= vc->obact;
1933         polyfacemap_e *e;
1934         Mesh *me= ob->data;
1935         float mat[4][4];
1936         int *indexar= vpd->indexar;
1937         int totindex, index;
1938         float mval[2];
1939
1940         RNA_float_get_array(itemptr, "mouse", mval);
1941                         
1942         view3d_operator_needs_opengl(C);
1943                         
1944         /* load projection matrix */
1945         wmMultMatrix(ob->obmat);
1946         wmGetSingleMatrix(mat);
1947         wmLoadMatrix(vc->rv3d->viewmat);
1948
1949         mval[0]-= vc->ar->winrct.xmin;
1950         mval[1]-= vc->ar->winrct.ymin;
1951
1952                         
1953         /* which faces are involved */
1954         if(vp->flag & VP_AREA) {
1955                 totindex= sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush->size);
1956         }
1957         else {
1958                 indexar[0]= view3d_sample_backbuf(vc, mval[0], mval[1]);
1959                 if(indexar[0]) totindex= 1;
1960                 else totindex= 0;
1961         }
1962                         
1963         swap_m4m4(vc->rv3d->persmat, mat);
1964                         
1965         if(vp->flag & VP_COLINDEX) {
1966                 for(index=0; index<totindex; index++) {
1967                         if(indexar[index] && indexar[index]<=me->totpoly) {
1968                                 MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
1969                                                 
1970                                 if(mpoly->mat_nr!=ob->actcol-1) {
1971                                         indexar[index]= 0;
1972                                 }
1973                         }                                       
1974                 }
1975         }
1976
1977         if((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
1978                 for(index=0; index<totindex; index++) {
1979                         if(indexar[index] && indexar[index]<=me->totpoly) {
1980                                 MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
1981                                                 
1982                                 if((mpoly->flag & ME_FACE_SEL)==0)
1983                                         indexar[index]= 0;
1984                         }                                       
1985                 }
1986         }
1987         
1988         swap_m4m4(vc->rv3d->persmat, mat);
1989
1990         /* was disabled because it is slow, but necessary for blur */
1991         if(vp->mode == VP_BLUR)
1992                 do_shared_vertexcol(me);
1993                         
1994         for(index=0; index<totindex; index++) {
1995                                 
1996                 if(indexar[index] && indexar[index]<=me->totpoly) {
1997                         MPoly *mpoly= ((MPoly *)me->mpoly) + (indexar[index]-1);
1998                         MFace *mf;
1999                         MCol *mc;
2000                         MLoop *ml;
2001                         MLoopCol *mlc;
2002                         unsigned int *lcol = ((unsigned int*)me->mloopcol) + mpoly->loopstart;
2003                         unsigned int *lcolorig = ((unsigned int*)vp->vpaint_prev) + mpoly->loopstart;
2004                         int i, j, alpha;
2005                                         
2006                         if(vp->mode==VP_BLUR) {
2007                                 unsigned int blend[5] = {0};
2008                                 char *col;
2009
2010                                 for (j=0; j<mpoly->totloop; j += 2) {
2011                                         col = (char*)(lcol + j);
2012                                         blend[0] += col[0];
2013                                         blend[1] += col[1];
2014                                         blend[2] += col[2];
2015                                         blend[3] += col[3];
2016                                 }
2017
2018                                 blend[0] /= mpoly->totloop;
2019                                 blend[1] /= mpoly->totloop;
2020                                 blend[2] /= mpoly->totloop;
2021                                 blend[3] /= mpoly->totloop;
2022                                 col = (char*)(blend + 4);
2023                                 col[0] = blend[0];
2024                                 col[1] = blend[1];
2025                                 col[2] = blend[2];
2026                                 col[3] = blend[3];
2027
2028                                 vpd->paintcol = *((unsigned int*)col);
2029                         }
2030
2031                         ml = me->mloop + mpoly->loopstart;
2032                         for (i=0; i<mpoly->totloop; i++, ml++) {
2033                                 alpha= calc_vp_alpha_dl(vp, vc, vpd->vpimat, vpd->vertexcosnos+6*ml->v, mval);
2034                                 if(alpha) vpaint_blend(vp, lcol+i, lcolorig+i, vpd->paintcol, alpha);
2035                         }
2036         
2037                         #ifdef CPYCOL
2038                         #undef CPYCOL
2039                         #endif
2040                         #define CPYCOL(c, l) (c)->a = (l)->a, (c)->r = (l)->r, (c)->g = (l)->g, (c)->b = (l)->b
2041
2042                         /*update vertex colors for tesselations incrementally,
2043                           rather then regenerating the tesselation altogether.*/
2044                         for (e=vpd->polyfacemap[(indexar[index]-1)].first; e; e=e->next) {
2045                                 mf = me->mface + e->facenr;
2046                                 mc = me->mcol + e->facenr*4;
2047                                 
2048                                 ml = me->mloop + mpoly->loopstart;
2049                                 mlc = me->mloopcol + mpoly->loopstart;
2050                                 for (j=0; j<mpoly->totloop; j++, ml++, mlc++) {
2051                                         if (ml->v == mf->v1)
2052                                                 CPYCOL(mc, mlc);
2053                                         else if (ml->v == mf->v2)
2054                                                 CPYCOL(mc+1, mlc);
2055                                         else if (ml->v == mf->v3)
2056                                                 CPYCOL(mc+2, mlc);
2057                                         else if (mf->v4 && ml->v == mf->v4)
2058                                                 CPYCOL(mc+3, mlc);
2059
2060                                 }
2061                         }
2062                         #undef CPYCOL
2063                 }
2064         }
2065                 
2066         swap_m4m4(vc->rv3d->persmat, mat);
2067                         
2068         do_shared_vertexcol(me);
2069
2070         ED_region_tag_redraw(vc->ar);           
2071         DAG_id_flush_update(ob->data, OB_RECALC_DATA);
2072 }
2073
2074 static void vpaint_stroke_done(bContext *C, struct PaintStroke *stroke)
2075 {
2076         ToolSettings *ts= CTX_data_tool_settings(C);
2077         struct VPaintData *vpd= paint_stroke_mode_data(stroke);
2078         
2079         if(vpd->vertexcosnos)
2080                 MEM_freeN(vpd->vertexcosnos);
2081         MEM_freeN(vpd->indexar);
2082         
2083         /* frees prev buffer */
2084         copy_vpaint_prev(ts->vpaint, NULL, 0);
2085         BLI_memarena_free(vpd->arena);
2086
2087         MEM_freeN(vpd);
2088 }
2089
2090 static int vpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2091 {
2092         
2093         op->customdata = paint_stroke_new(C, vpaint_stroke_test_start,
2094                                           vpaint_stroke_update_step,
2095                                           vpaint_stroke_done);
2096         
2097         /* add modal handler */
2098         WM_event_add_modal_handler(C, op);
2099
2100         op->type->modal(C, op, event);
2101         
2102         return OPERATOR_RUNNING_MODAL;
2103 }
2104
2105 void PAINT_OT_vertex_paint(wmOperatorType *ot)
2106 {
2107         /* identifiers */
2108         ot->name= "Vertex Paint";
2109         ot->idname= "PAINT_OT_vertex_paint";
2110         
2111         /* api callbacks */
2112         ot->invoke= vpaint_invoke;
2113         ot->modal= paint_stroke_modal;
2114         /* ot->exec= vpaint_exec; <-- needs stroke property */
2115         ot->poll= vertex_paint_poll;
2116         
2117         /* flags */
2118         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2119
2120         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2121 }
2122