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