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