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