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