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