3a24fcd652f8168d328d3e9a9ef5b1d6976b1005
[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 char *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 char *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 char *bone_groups, const char *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 int has_locked_group_selected(int defbase_tot, const char *defbase_sel, const char *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, char *defbase_sel, int selected, char *lock_flags, char *vgroup_validmap)
1423 {
1424         int i;
1425         if (defbase_tot == selected) {
1426                 return FALSE;
1427         }
1428         for (i = 0; i < defbase_tot; i++) {
1429                 if (vgroup_validmap[i] && !defbase_sel[i] && !lock_flags[i]) {
1430                         return TRUE;
1431                 }
1432         }
1433         return FALSE;
1434 }
1435 #endif
1436
1437
1438 static void multipaint_selection(MDeformVert *dvert, const int defbase_tot, float change, const char *defbase_sel)
1439 {
1440         int i;
1441         MDeformWeight *dw;
1442         float val;
1443         /* make sure they are all at most 1 after the change */
1444         for (i = 0; i < defbase_tot; i++) {
1445                 if (defbase_sel[i]) {
1446                         dw = defvert_find_index(dvert, i);
1447                         if (dw && dw->weight) {
1448                                 val = dw->weight * change;
1449                                 if (val > 1) {
1450                                         /* TODO: when the change is reduced, you need to recheck
1451                                          * the earlier values to make sure they are not 0
1452                                          * (precision error) */
1453                                         change = 1.0f / dw->weight;
1454                                 }
1455                                 /* the value should never reach zero while multi-painting if it
1456                                  * was nonzero beforehand */
1457                                 if (val <= 0) {
1458                                         return;
1459                                 }
1460                         }
1461                 }
1462         }
1463         /* apply the valid change */
1464         for (i = 0; i < defbase_tot; i++) {
1465                 if (defbase_sel[i]) {
1466                         dw = defvert_find_index(dvert, i);
1467                         if (dw && dw->weight) {
1468                                 dw->weight = dw->weight * change;
1469                         }
1470                 }
1471         }
1472 }
1473
1474 /* move all change onto valid, unchanged groups.  If there is change left over,
1475  * then return it.
1476  * assumes there are valid groups to shift weight onto */
1477 static float redistribute_change(MDeformVert *ndv, const int defbase_tot,
1478                                  char *change_status, const char change_me, int changeto,
1479                                  float totchange, float total_valid,
1480                                  char do_auto_normalize)
1481 {
1482         float was_change;
1483         float change;
1484         float oldval;
1485         MDeformWeight *ndw;
1486         int i;
1487         do {
1488                 /* assume there is no change until you see one */
1489                 was_change = FALSE;
1490                 /* change each group by the same amount each time */
1491                 change = totchange / total_valid;
1492                 for (i = 0; i < ndv->totweight && total_valid && totchange; i++) {
1493                         ndw = (ndv->dw + i);
1494
1495                         /* ignore anything outside the value range */
1496                         if (ndw->def_nr < defbase_tot) {
1497
1498                                 /* change only the groups with a valid status */
1499                                 if (change_status[ndw->def_nr] == change_me) {
1500                                         oldval = ndw->weight;
1501                                         /* if auto normalize is active, don't worry about upper bounds */
1502                                         if (do_auto_normalize == FALSE && ndw->weight + change > 1) {
1503                                                 totchange -= 1.0f - ndw->weight;
1504                                                 ndw->weight = 1.0f;
1505                                                 /* stop the changes to this group */
1506                                                 change_status[ndw->def_nr] = changeto;
1507                                                 total_valid--;
1508                                         }
1509                                         else if (ndw->weight + change < 0) { /* check the lower bound */
1510                                                 totchange -= ndw->weight;
1511                                                 ndw->weight = 0;
1512                                                 change_status[ndw->def_nr] = changeto;
1513                                                 total_valid--;
1514                                         }
1515                                         else { /* a perfectly valid change occurred to ndw->weight */
1516                                                 totchange -= change;
1517                                                 ndw->weight += change;
1518                                         }
1519                                         /* see if there was a change */
1520                                         if (oldval != ndw->weight) {
1521                                                 was_change = TRUE;
1522                                         }
1523                                 }
1524                         }
1525                 }
1526                 /* don't go again if there was no change, if there is no valid group,
1527                  * or there is no change left */
1528         } while (was_change && total_valid && totchange);
1529         /* left overs */
1530         return totchange;
1531 }
1532 static float get_mp_change(MDeformVert *odv, const int defbase_tot, const char *defbase_sel, float brush_change);
1533 /* observe the changes made to the weights of groups.
1534  * make sure all locked groups on the vertex have the same deformation
1535  * by moving the changes made to groups onto other unlocked groups */
1536 static void enforce_locks(MDeformVert *odv, MDeformVert *ndv,
1537                           const int defbase_tot, const char *defbase_sel,
1538                           const char *lock_flags, const char *vgroup_validmap,
1539                           char do_auto_normalize, char do_multipaint)
1540 {
1541         float totchange = 0.0f;
1542         float totchange_allowed = 0.0f;
1543         float left_over;
1544
1545         int total_valid = 0;
1546         int total_changed = 0;
1547         unsigned int i;
1548         MDeformWeight *ndw;
1549         MDeformWeight *odw;
1550
1551         // float changed_sum = 0.0f;  // UNUSED
1552
1553         char *change_status;
1554
1555         if (!lock_flags || !has_locked_group(ndv, defbase_tot, vgroup_validmap, lock_flags)) {
1556                 return;
1557         }
1558         /* record if a group was changed, unlocked and not changed, or locked */
1559         change_status = MEM_callocN(sizeof(char) * defbase_tot, "unlocked_unchanged");
1560
1561         for (i = 0; i < defbase_tot; i++) {
1562                 ndw = defvert_find_index(ndv, i);
1563                 odw = defvert_find_index(odv, i);
1564                 /* the weights are zero, so we can assume a lot */
1565                 if (!ndw || !odw) {
1566                         if (!lock_flags[i] && vgroup_validmap[i]) {
1567                                 defvert_verify_index(odv, i);
1568                                 defvert_verify_index(ndv, i);
1569                                 total_valid++;
1570                                 change_status[i] = 1; /* can be altered while redistributing */
1571                         }
1572                         continue;
1573                 }
1574                 /* locked groups should not be changed */
1575                 if (lock_flags[i]) {
1576                         ndw->weight = odw->weight;
1577                 }
1578                 else if (ndw->weight != odw->weight) { /* changed groups are handled here */
1579                         totchange += ndw->weight - odw->weight;
1580                         // changed_sum += ndw->weight;  // UNUSED
1581                         change_status[i] = 2; /* was altered already */
1582                         total_changed++;
1583                 } /* unchanged, unlocked bone groups are handled here */
1584                 else if (vgroup_validmap[i]) {
1585                         totchange_allowed += ndw->weight;
1586                         total_valid++;
1587                         change_status[i] = 1; /* can be altered while redistributing */
1588                 }
1589         }
1590         /* if there was any change, redistribute it */
1591         if (total_changed) {
1592                 /* auto normalize will allow weights to temporarily go above 1 in redistribution */
1593                 if (vgroup_validmap && total_changed < 0 && total_valid) {
1594                         totchange_allowed = total_valid;
1595                 }
1596                 /* the way you modify the unlocked + unchanged groups is different depending
1597                  * on whether or not you are painting the weight(s) up or down */
1598                 if (totchange < 0) {
1599                         totchange_allowed = total_valid - totchange_allowed;
1600                 }
1601                 else {
1602                         totchange_allowed *= -1;
1603                 }
1604                 /* there needs to be change allowed, or you should not bother */
1605                 if (totchange_allowed) {
1606                         left_over = 0;
1607                         if (fabsf(totchange_allowed) < fabsf(totchange)) {
1608                                 /* this amount goes back onto the changed, unlocked weights */
1609                                 left_over = fabsf(fabsf(totchange) - fabsf(totchange_allowed));
1610                                 if (totchange > 0) {
1611                                         left_over *= -1;
1612                                 }
1613                         }
1614                         else {
1615                                 /* all of the change will be permitted */
1616                                 totchange_allowed = -totchange;
1617                         }
1618                         /* move the weight evenly between the allowed groups, move excess back onto the used groups based on the change */
1619                         totchange_allowed = redistribute_change(ndv, defbase_tot, change_status, 1, -1, totchange_allowed, total_valid, do_auto_normalize);
1620                         left_over += totchange_allowed;
1621                         if (left_over) {
1622                                 /* more than one nonzero weights were changed with the same ratio with multipaint, so keep them changed that way! */
1623                                 if (total_changed > 1 && do_multipaint) {
1624                                         float undo_change = get_mp_change(ndv, defbase_tot, defbase_sel, left_over);
1625                                         multipaint_selection(ndv, defbase_tot, undo_change, defbase_sel);
1626                                 }
1627                                 /* or designatedw is still -1 put weight back as evenly as possible */
1628                                 else {
1629                                         redistribute_change(ndv, defbase_tot, change_status, 2, -2, left_over, total_changed, do_auto_normalize);
1630                                 }
1631                         }
1632                 }
1633                 else {
1634                         /* reset the weights */
1635                         MDeformWeight *dw_old = odv->dw;
1636                         MDeformWeight *dw_new = ndv->dw;
1637
1638                         for (i = odv->totweight; i != 0; i--, dw_old++, dw_new++) {
1639                                 dw_new->weight = dw_old->weight;
1640                         }
1641                 }
1642         }
1643
1644         MEM_freeN(change_status);
1645 }
1646
1647 /* multi-paint's initial, potential change is computed here based on the user's stroke */
1648 static float get_mp_change(MDeformVert *odv, const int defbase_tot, const char *defbase_sel, float brush_change)
1649 {
1650         float selwsum = 0.0f;
1651         unsigned int i;
1652         MDeformWeight *dw = odv->dw;
1653
1654         for (i = odv->totweight; i != 0; i--, dw++) {
1655                 if (dw->def_nr < defbase_tot) {
1656                         if (defbase_sel[dw->def_nr]) {
1657                                 selwsum += dw->weight;
1658                         }
1659                 }
1660         }
1661         if (selwsum && selwsum + brush_change > 0) {
1662                 return (selwsum + brush_change) / selwsum;
1663         }
1664         return 0.0f;
1665 }
1666
1667 /* change the weights back to the wv's weights
1668  * it assumes you already have the correct pointer index */
1669 static void defvert_reset_to_prev(MDeformVert *dv_prev, MDeformVert *dv)
1670 {
1671         MDeformWeight *dw = dv->dw;
1672         MDeformWeight *dw_prev;
1673         unsigned int i;
1674         for (i = dv->totweight; i != 0; i--, dw++) {
1675                 dw_prev = defvert_find_index(dv_prev, dw->def_nr);
1676                 /* if there was no w when there is a d, then the old weight was 0 */
1677                 dw->weight = dw_prev ? dw_prev->weight : 0.0f;
1678         }
1679 }
1680
1681 static void clamp_weights(MDeformVert *dvert)
1682 {
1683         MDeformWeight *dw = dvert->dw;
1684         unsigned int i;
1685         for (i = dvert->totweight; i != 0; i--, dw++) {
1686                 CLAMP(dw->weight, 0.0f, 1.0f);
1687         }
1688 }
1689
1690 /* struct to avoid passing many args each call to do_weight_paint_vertex()
1691  * this _could_ be made a part of the operators 'WPaintData' struct, or at
1692  * least a member, but for now keep its own struct, initialized on every
1693  * paint stroke update - campbell */
1694 typedef struct WeightPaintInfo {
1695
1696         int defbase_tot;
1697
1698         /* both must add up to 'defbase_tot' */
1699         int defbase_tot_sel;
1700         int defbase_tot_unsel;
1701
1702         int vgroup_active; /* (ob->actdef - 1) */
1703         int vgroup_mirror; /* mirror group or -1 */
1704
1705         const char *lock_flags;  /* boolean array for locked bones,
1706                                   * length of defbase_tot */
1707         const char *defbase_sel; /* boolean array for selected bones,
1708                                   * length of defbase_tot, cant be const because of how its passed */
1709
1710         const char *vgroup_validmap; /* same as WeightPaintData.vgroup_validmap,
1711                                       * only added here for convenience */
1712
1713         char do_flip;
1714         char do_multipaint;
1715         char do_auto_normalize;
1716
1717         float brush_alpha_value;  /* result of BKE_brush_alpha_get() */
1718 } WeightPaintInfo;
1719
1720 /* fresh start to make multi-paint and locking modular */
1721 /* returns TRUE if it thinks you need to reset the weights due to
1722  * normalizing while multi-painting
1723  *
1724  * note: this assumes dw->def_nr range has been checked by the caller
1725  */
1726 static int apply_mp_locks_normalize(Mesh *me, const WeightPaintInfo *wpi,
1727                                     const unsigned int index,
1728                                     MDeformWeight *dw, MDeformWeight *tdw,
1729                                     float change, float oldChange,
1730                                     float oldw, float neww)
1731 {
1732         MDeformVert *dv = &me->dvert[index];
1733         MDeformVert dv_test = {NULL};
1734
1735         dv_test.dw = MEM_dupallocN(dv->dw);
1736         dv_test.flag = dv->flag;
1737         dv_test.totweight = dv->totweight;
1738         /* do not multi-paint if a locked group is selected or the active group is locked
1739          * !lock_flags[dw->def_nr] helps if nothing is selected, but active group is locked */
1740         if ((wpi->lock_flags == NULL) ||
1741             ((wpi->lock_flags[dw->def_nr] == FALSE) && /* def_nr range has to be checked for by caller */
1742              has_locked_group_selected(wpi->defbase_tot, wpi->defbase_sel, wpi->lock_flags) == FALSE))
1743         {
1744                 if (wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1745                         if (change && change != 1) {
1746                                 multipaint_selection(dv, wpi->defbase_tot, change, wpi->defbase_sel);
1747                         }
1748                 }
1749                 else { /* this lets users paint normally, but don't let them paint locked groups */
1750                         dw->weight = neww;
1751                 }
1752         }
1753         clamp_weights(dv);
1754
1755         enforce_locks(&dv_test, dv, wpi->defbase_tot, wpi->defbase_sel, wpi->lock_flags, wpi->vgroup_validmap, wpi->do_auto_normalize, wpi->do_multipaint);
1756
1757         if (wpi->do_auto_normalize) {
1758                 /* XXX - should we pass the active group? - currently '-1' */
1759                 do_weight_paint_normalize_all(dv, wpi->defbase_tot, wpi->vgroup_validmap);
1760         }
1761
1762         if (oldChange && wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1763                 if (tdw->weight != oldw) {
1764                         if (neww > oldw) {
1765                                 if (tdw->weight <= oldw) {
1766                                         MEM_freeN(dv_test.dw);
1767                                         return TRUE;
1768                                 }
1769                         }
1770                         else {
1771                                 if (tdw->weight >= oldw) {
1772                                         MEM_freeN(dv_test.dw);
1773                                         return TRUE;
1774                                 }
1775                         }
1776                 }
1777         }
1778         MEM_freeN(dv_test.dw);
1779         return FALSE;
1780 }
1781
1782 /* within the current dvert index, get the dw that is selected and has a weight
1783  * above 0, this helps multi-paint */
1784 static int get_first_selected_nonzero_weight(MDeformVert *dvert, const int defbase_tot, const char *defbase_sel)
1785 {
1786         int i;
1787         MDeformWeight *dw = dvert->dw;
1788         for (i = 0; i < dvert->totweight; i++, dw++) {
1789                 if (dw->def_nr < defbase_tot) {
1790                         if (defbase_sel[dw->def_nr] && dw->weight > 0.0f) {
1791                                 return i;
1792                         }
1793                 }
1794         }
1795         return -1;
1796 }
1797
1798 static void do_weight_paint_vertex(
1799         /* vars which remain the same for every vert */
1800         VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1801         /* vars which change on each stroke */
1802         const unsigned int index, float alpha, float paintweight
1803         )
1804 {
1805         Mesh *me = ob->data;
1806         MDeformVert *dv = &me->dvert[index];
1807         
1808         MDeformWeight *dw, *dw_prev;
1809
1810         /* mirror vars */
1811         int index_mirr;
1812         int vgroup_mirr;
1813
1814         MDeformVert *dv_mirr;
1815         MDeformWeight *dw_mirr;
1816
1817         const short do_multipaint_totsel = (wpi->do_multipaint && wpi->defbase_tot_sel > 1);
1818
1819         if (wp->flag & VP_ONLYVGROUP) {
1820                 dw = defvert_find_index(dv, wpi->vgroup_active);
1821                 dw_prev = defvert_find_index(wp->wpaint_prev + index, wpi->vgroup_active);
1822         }
1823         else {
1824                 dw = defvert_verify_index(dv, wpi->vgroup_active);
1825                 dw_prev = defvert_verify_index(wp->wpaint_prev + index, wpi->vgroup_active);
1826         }
1827
1828         if (dw == NULL || dw_prev == NULL) {
1829                 return;
1830         }
1831
1832
1833         /* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
1834         if (me->editflag & ME_EDIT_MIRROR_X) {
1835                 index_mirr = mesh_get_x_mirror_vert(ob, index);
1836                 vgroup_mirr = (wpi->vgroup_mirror != -1) ? wpi->vgroup_mirror : wpi->vgroup_active;
1837
1838                 /* another possible error - mirror group _and_ active group are the same (which is fine),
1839                  * but we also are painting onto a center vertex - this would paint the same weight twice */
1840                 if (index_mirr == index && vgroup_mirr == wpi->vgroup_active) {
1841                         index_mirr = vgroup_mirr = -1;
1842                 }
1843         }
1844         else {
1845                 index_mirr = vgroup_mirr = -1;
1846         }
1847
1848
1849         /* get the mirror def vars */
1850         if (index_mirr != -1) {
1851                 dv_mirr = &me->dvert[index_mirr];
1852                 if (wp->flag & VP_ONLYVGROUP) {
1853                         dw_mirr = defvert_find_index(dv_mirr, vgroup_mirr);
1854
1855                         if (dw_mirr == NULL) {
1856                                 index_mirr = vgroup_mirr = -1;
1857                                 dv_mirr = NULL;
1858                         }
1859                 }
1860                 else {
1861                         if (index != index_mirr) {
1862                                 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1863                         }
1864                         else {
1865                                 /* dv and dv_mirr are the same */
1866                                 int totweight_prev = dv_mirr->totweight;
1867                                 int dw_offset = (int)(dw - dv_mirr->dw);
1868                                 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1869
1870                                 /* if we added another, get our old one back */
1871                                 if (totweight_prev != dv_mirr->totweight) {
1872                                         dw = &dv_mirr->dw[dw_offset];
1873                                 }
1874                         }
1875                 }
1876         }
1877         else {
1878                 dv_mirr = NULL;
1879                 dw_mirr = NULL;
1880         }
1881
1882
1883         /* TODO: De-duplicate the simple weight paint - jason */
1884         /* ... or not, since its <10 SLOC - campbell */
1885
1886         /* If there are no locks or multipaint,
1887          * then there is no need to run the more complicated checks */
1888         if ((do_multipaint_totsel == FALSE) &&
1889             (wpi->lock_flags == NULL || has_locked_group(dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags) == FALSE))
1890         {
1891                 dw->weight = wpaint_blend(wp, dw->weight, dw_prev->weight, alpha, paintweight,
1892                                           wpi->brush_alpha_value, wpi->do_flip, FALSE);
1893
1894                 /* WATCH IT: take care of the ordering of applying mirror -> normalize,
1895                  * can give wrong results [#26193], least confusing if normalize is done last */
1896
1897                 /* apply mirror */
1898                 if (index_mirr != -1) {
1899                         /* copy, not paint again */
1900                         dw_mirr->weight = dw->weight;
1901                 }
1902
1903                 /* apply normalize */
1904                 if (wpi->do_auto_normalize) {
1905                         /* note on normalize - this used to be applied after painting and normalize all weights,
1906                          * in some ways this is good because there is feedback where the more weights involved would
1907                          * 'resist' so you couldn't instantly zero out other weights by painting 1.0 on the active.
1908                          *
1909                          * However this gave a problem since applying mirror, then normalize both verts
1910                          * the resulting weight wont match on both sides.
1911                          *
1912                          * If this 'resisting', slower normalize is nicer, we could call
1913                          * do_weight_paint_normalize_all() and only use...
1914                          * do_weight_paint_normalize_all_active() when normalizing the mirror vertex.
1915                          * - campbell
1916                          */
1917                         do_weight_paint_normalize_all_active(dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->vgroup_active);
1918
1919                         if (index_mirr != -1) {
1920                                 /* only normalize if this is not a center vertex, else we get a conflict, normalizing twice */
1921                                 if (index != index_mirr) {
1922                                         do_weight_paint_normalize_all_active(dv_mirr, wpi->defbase_tot, wpi->vgroup_validmap, vgroup_mirr);
1923                                 }
1924                                 else {
1925                                         /* this case accounts for...
1926                                          * - painting onto a center vertex of a mesh
1927                                          * - x mirror is enabled
1928                                          * - auto normalize is enabled
1929                                          * - the group you are painting onto has a L / R version
1930                                          *
1931                                          * We want L/R vgroups to have the same weight but this cant be if both are over 0.5,
1932                                          * We _could_ have special check for that, but this would need its own normalize function which
1933                                          * holds 2 groups from changing at once.
1934                                          *
1935                                          * So! just balance out the 2 weights, it keeps them equal and everything normalized.
1936                                          *
1937                                          * While it wont hit the desired weight immediately as the user waggles their mouse,
1938                                          * constant painting and re-normalizing will get there. this is also just simpler logic.
1939                                          * - campbell */
1940                                         dw_mirr->weight = dw->weight = (dw_mirr->weight + dw->weight) * 0.5f;
1941                                 }
1942                         }
1943                 }
1944         }
1945         else {
1946                 /* use locks and/or multipaint */
1947                 float oldw;
1948                 float neww;
1949                 /* float testw = 0; */ /* UNUSED */
1950                 float observedChange = 0;
1951                 float change = 0;
1952                 float oldChange = 0;
1953                 int i;
1954                 MDeformWeight *tdw = NULL, *tdw_prev;
1955                 MDeformVert dv_copy = {NULL};
1956
1957                 oldw = dw->weight;
1958                 neww = wpaint_blend(wp, dw->weight, dw_prev->weight, alpha, paintweight,
1959                                     wpi->brush_alpha_value, wpi->do_flip, do_multipaint_totsel);
1960                 
1961                 /* setup multi-paint */
1962                 observedChange = neww - oldw;
1963                 if (do_multipaint_totsel && observedChange) {
1964                         dv_copy.dw = MEM_dupallocN(dv->dw);
1965                         dv_copy.flag = dv->flag;
1966                         dv_copy.totweight = dv->totweight;
1967                         tdw = dw;
1968                         tdw_prev = dw_prev;
1969                         change = get_mp_change(&wp->wpaint_prev[index], wpi->defbase_tot, wpi->defbase_sel, observedChange);
1970                         if (change) {
1971                                 if (!tdw->weight) {
1972                                         i = get_first_selected_nonzero_weight(dv, wpi->defbase_tot, wpi->defbase_sel);
1973                                         if (i >= 0) {
1974                                                 tdw = &(dv->dw[i]);
1975                                                 tdw_prev = defvert_verify_index(&wp->wpaint_prev[index], tdw->def_nr);
1976                                         }
1977                                         else {
1978                                                 change = 0;
1979                                         }
1980                                 }
1981                                 if (change && tdw_prev->weight && tdw_prev->weight * change) {
1982                                         if (tdw->weight != tdw_prev->weight) {
1983                                                 oldChange = tdw->weight / tdw_prev->weight;
1984                                                 /* testw = tdw_prev->weight * change; */ /* UNUSED */
1985                                                 if (observedChange > 0) {
1986                                                         if (change > oldChange) {
1987                                                                 /* reset the weights and use the new change */
1988                                                                 defvert_reset_to_prev(wp->wpaint_prev + index, dv);
1989                                                         }
1990                                                         else {
1991                                                                 /* the old change was more significant, so set
1992                                                                  * the change to 0 so that it will not do another multi-paint */
1993                                                                 change = 0;
1994                                                         }
1995                                                 }
1996                                                 else {
1997                                                         if (change < oldChange) {
1998                                                                 defvert_reset_to_prev(wp->wpaint_prev + index, dv);
1999                                                         }
2000                                                         else {
2001                                                                 change = 0;
2002                                                         }
2003                                                 }
2004                                         }
2005                                 }
2006                                 else {
2007                                         change = 0;
2008                                 }
2009                         }
2010                 }
2011                 
2012                 if (apply_mp_locks_normalize(me, wpi, index, dw, tdw, change, oldChange, oldw, neww)) {
2013                         defvert_reset_to_prev(&dv_copy, dv);
2014                         change = 0;
2015                         oldChange = 0;
2016                 }
2017                 if (dv_copy.dw) {
2018                         MEM_freeN(dv_copy.dw);
2019                 }
2020 #if 0
2021                 /* dv may have been altered greatly */
2022                 dw = defvert_find_index(dv, vgroup);
2023 #else
2024                 dw = NULL; /* UNUSED after assignment, set to NULL to ensure we don't
2025                             * use again, we thats needed un-ifdef the line above */
2026                 (void)dw;  /* quiet warnigns */
2027 #endif
2028
2029                 /* x mirror painting */
2030                 if (index_mirr != -1) {
2031                         /* copy, not paint again */
2032
2033                         /* dw_mirr->weight = dw->weight; */  /* TODO, explain the logic in not assigning weight! - campbell */
2034                         apply_mp_locks_normalize(me, wpi, index_mirr, dw_mirr, tdw, change, oldChange, oldw, neww);
2035                 }
2036         }
2037 }
2038
2039
2040 /* *************** set wpaint operator ****************** */
2041
2042 static int set_wpaint(bContext *C, wmOperator *UNUSED(op))  /* toggle */
2043 {               
2044         Object *ob = CTX_data_active_object(C);
2045         Scene *scene = CTX_data_scene(C);
2046         VPaint *wp = scene->toolsettings->wpaint;
2047         Mesh *me;
2048         
2049         me = BKE_mesh_from_object(ob);
2050         if (ob->id.lib || me == NULL) return OPERATOR_PASS_THROUGH;
2051         
2052         if (ob->mode & OB_MODE_WEIGHT_PAINT) ob->mode &= ~OB_MODE_WEIGHT_PAINT;
2053         else ob->mode |= OB_MODE_WEIGHT_PAINT;
2054         
2055         
2056         /* Weightpaint works by overriding colors in mesh,
2057          * so need to make sure we recalc on enter and
2058          * exit (exit needs doing regardless because we
2059          * should redeform).
2060          */
2061         DAG_id_tag_update(&me->id, 0);
2062         
2063         if (ob->mode & OB_MODE_WEIGHT_PAINT) {
2064                 Object *par;
2065                 
2066                 if (wp == NULL)
2067                         wp = scene->toolsettings->wpaint = new_vpaint(1);
2068
2069                 BKE_paint_init(&wp->paint, PAINT_CURSOR_WEIGHT_PAINT);
2070                 paint_cursor_start(C, weight_paint_poll);
2071                 
2072                 mesh_octree_table(ob, NULL, NULL, 's');
2073                 
2074                 /* verify if active weight group is also active bone */
2075                 par = modifiers_isDeformedByArmature(ob);
2076                 if (par && (par->mode & OB_MODE_POSE)) {
2077                         bArmature *arm = par->data;
2078
2079                         if (arm->act_bone)
2080                                 ED_vgroup_select_by_name(ob, arm->act_bone->name);
2081                 }
2082         }
2083         else {
2084                 mesh_octree_table(NULL, NULL, NULL, 'e');
2085                 mesh_mirrtopo_table(NULL, 'e');
2086
2087                 if (me->editflag & ME_EDIT_PAINT_VERT_SEL) {
2088                         BKE_mesh_flush_select_from_verts(me);
2089                 }
2090                 else if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
2091                         BKE_mesh_flush_select_from_polys(me);
2092                 }
2093         }
2094         
2095         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2096         
2097         return OPERATOR_FINISHED;
2098 }
2099
2100 /* for switching to/from mode */
2101 static int paint_poll_test(bContext *C)
2102 {
2103         Object *ob = CTX_data_active_object(C);
2104         if (CTX_data_edit_object(C))
2105                 return 0;
2106         if (CTX_data_active_object(C) == NULL)
2107                 return 0;
2108         if (!ob->data || ((ID *)ob->data)->lib)
2109                 return 0;
2110         return 1;
2111 }
2112
2113 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
2114 {
2115         
2116         /* identifiers */
2117         ot->name = "Weight Paint Mode";
2118         ot->idname = "PAINT_OT_weight_paint_toggle";
2119         ot->description = "Toggle weight paint mode in 3D view";
2120         
2121         /* api callbacks */
2122         ot->exec = set_wpaint;
2123         ot->poll = paint_poll_test;
2124         
2125         /* flags */
2126         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2127         
2128 }
2129
2130 /* ************ weight paint operator ********** */
2131
2132 struct WPaintData {
2133         ViewContext vc;
2134         int *indexar;
2135         int vgroup_active;
2136         int vgroup_mirror;
2137         DMCoNo *vertexcosnos;
2138         float wpimat[3][3];
2139
2140         /* variables for auto normalize */
2141         const char *vgroup_validmap; /* stores if vgroups tie to deforming bones or not */
2142         const char *lock_flags;
2143         int defbase_tot;
2144 };
2145
2146 /* ensure we have data on wpaint start, add if needed */
2147 static int wpaint_ensure_data(bContext *C, wmOperator *op)
2148 {
2149         Scene *scene = CTX_data_scene(C);
2150         Object *ob = CTX_data_active_object(C);
2151         Mesh *me = BKE_mesh_from_object(ob);
2152
2153         if (scene->obedit) {
2154                 return FALSE;
2155         }
2156
2157         if (me == NULL || me->totpoly == 0) {
2158                 return FALSE;
2159         }
2160
2161         /* if nothing was added yet, we make dverts and a vertex deform group */
2162         if (!me->dvert) {
2163                 ED_vgroup_data_create(&me->id);
2164                 WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
2165         }
2166
2167         /* this happens on a Bone select, when no vgroup existed yet */
2168         if (ob->actdef <= 0) {
2169                 Object *modob;
2170                 if ((modob = modifiers_isDeformedByArmature(ob))) {
2171                         Bone *actbone = ((bArmature *)modob->data)->act_bone;
2172                         if (actbone) {
2173                                 bPoseChannel *pchan = BKE_pose_channel_find_name(modob->pose, actbone->name);
2174
2175                                 if (pchan) {
2176                                         bDeformGroup *dg = defgroup_find_name(ob, pchan->name);
2177                                         if (dg == NULL) {
2178                                                 dg = ED_vgroup_add_name(ob, pchan->name);  /* sets actdef */
2179                                         }
2180                                         else {
2181                                                 int actdef = 1 + BLI_findindex(&ob->defbase, dg);
2182                                                 BLI_assert(actdef >= 0);
2183                                                 ob->actdef = actdef;
2184                                         }
2185                                 }
2186                         }
2187                 }
2188         }
2189         if (ob->defbase.first == NULL) {
2190                 ED_vgroup_add(ob);
2191         }
2192
2193         /* ensure we don't try paint onto an invalid group */
2194         if (ob->actdef <= 0) {
2195                 BKE_report(op->reports, RPT_WARNING, "No active vertex group for painting, aborting");
2196                 return FALSE;
2197         }
2198
2199         return TRUE;
2200 }
2201
2202 static int wpaint_stroke_test_start(bContext *C, wmOperator *op, const float UNUSED(mouse[2]))
2203 {
2204         Scene *scene = CTX_data_scene(C);
2205         struct PaintStroke *stroke = op->customdata;
2206         ToolSettings *ts = scene->toolsettings;
2207         VPaint *wp = ts->wpaint;
2208         Object *ob = CTX_data_active_object(C);
2209         Mesh *me = BKE_mesh_from_object(ob);
2210         struct WPaintData *wpd;
2211
2212         float mat[4][4], imat[4][4];
2213
2214         if (wpaint_ensure_data(C, op) == FALSE) {
2215                 return FALSE;
2216         }
2217
2218         {
2219                 /* check if we are attempting to paint onto a locked vertex group,
2220                  * and other options disallow it from doing anything useful */
2221                 bDeformGroup *dg = BLI_findlink(&ob->defbase, (ob->actdef - 1));
2222                 if (dg->flag & DG_LOCK_WEIGHT) {
2223                         BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
2224                         return FALSE;
2225                 }
2226         }
2227
2228         /* ALLOCATIONS! no return after this line */
2229         /* make mode data storage */
2230         wpd = MEM_callocN(sizeof(struct WPaintData), "WPaintData");
2231         paint_stroke_set_mode_data(stroke, wpd);
2232         view3d_set_viewcontext(C, &wpd->vc);
2233
2234         wpd->vgroup_active = ob->actdef - 1;
2235         wpd->vgroup_mirror = -1;
2236
2237         /* set up auto-normalize, and generate map for detecting which
2238          * vgroups affect deform bones */
2239         wpd->defbase_tot = BLI_countlist(&ob->defbase);
2240         wpd->lock_flags = BKE_objdef_lock_flags_get(ob, wpd->defbase_tot);
2241         if (ts->auto_normalize || ts->multipaint || wpd->lock_flags) {
2242                 wpd->vgroup_validmap = BKE_objdef_validmap_get(ob, wpd->defbase_tot);
2243         }
2244
2245         /* painting on subsurfs should give correct points too, this returns me->totvert amount */
2246         wpd->vertexcosnos = mesh_get_mapped_verts_nors(scene, ob);
2247         wpd->indexar = get_indexarray(me);
2248         copy_wpaint_prev(wp, me->dvert, me->totvert);
2249
2250         /* imat for normals */
2251         mult_m4_m4m4(mat, wpd->vc.rv3d->viewmat, ob->obmat);
2252         invert_m4_m4(imat, mat);
2253         copy_m3_m4(wpd->wpimat, imat);
2254
2255         /* if mirror painting, find the other group */
2256         if (me->editflag & ME_EDIT_MIRROR_X) {
2257                 wpd->vgroup_mirror = wpaint_mirror_vgroup_ensure(ob, wpd->vgroup_active);
2258         }
2259
2260         {
2261                 UnifiedPaintSettings *ups = &ts->unified_paint_settings;
2262                 ups->draw_pressure = true;
2263         }
2264         
2265         return TRUE;
2266 }
2267
2268 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2269 {
2270         Scene *scene = CTX_data_scene(C);
2271         ToolSettings *ts = CTX_data_tool_settings(C);
2272         VPaint *wp = ts->wpaint;
2273         Brush *brush = BKE_paint_brush(&wp->paint);
2274         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2275         ViewContext *vc;
2276         Object *ob;
2277         Mesh *me;
2278         float mat[4][4];
2279         float paintweight;
2280         int *indexar;
2281         float totw;
2282         unsigned int index, totindex;
2283         float alpha;
2284         float mval[2];
2285         bool use_vert_sel;
2286         bool use_face_sel;
2287         bool use_depth;
2288
2289         MDeformWeight *(*dw_func)(MDeformVert *, const int) =
2290                 (brush->vertexpaint_tool == PAINT_BLEND_BLUR) ?
2291                 ((wp->flag & VP_ONLYVGROUP) ?
2292                      (MDeformWeight *(*)(MDeformVert *, const int))defvert_find_index :
2293                       defvert_verify_index) : NULL;
2294
2295         const float pressure = RNA_float_get(itemptr, "pressure");
2296         const float brush_size_pressure = BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2297         const float brush_alpha_value = BKE_brush_alpha_get(scene, brush);
2298         const float brush_alpha_pressure = brush_alpha_value * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2299
2300         /* intentionally don't initialize as NULL, make sure we initialize all members below */
2301         WeightPaintInfo wpi;
2302
2303         /* cannot paint if there is no stroke data */
2304         if (wpd == NULL) {
2305                 /* XXX: force a redraw here, since even though we can't paint,
2306                  * at least view won't freeze until stroke ends */
2307                 ED_region_tag_redraw(CTX_wm_region(C));
2308                 return;
2309         }
2310
2311         vc = &wpd->vc;
2312         ob = vc->obact;
2313         me = ob->data;
2314         indexar = wpd->indexar;
2315         
2316         view3d_operator_needs_opengl(C);
2317         ED_view3d_init_mats_rv3d(ob, vc->rv3d);
2318
2319         /* load projection matrix */
2320         mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2321
2322         RNA_float_get_array(itemptr, "mouse", mval);
2323
2324         /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2325         wpi.defbase_tot =        wpd->defbase_tot;
2326         wpi.defbase_sel = BKE_objdef_selected_get(ob, wpi.defbase_tot, &wpi.defbase_tot_sel);
2327         if (wpi.defbase_tot_sel == 0 && ob->actdef > 0) {
2328                 wpi.defbase_tot_sel = 1;
2329         }
2330
2331         wpi.defbase_tot_unsel =  wpi.defbase_tot - wpi.defbase_tot_sel;
2332         wpi.vgroup_active =      wpd->vgroup_active;
2333         wpi.vgroup_mirror =      wpd->vgroup_mirror;
2334         wpi.lock_flags =         wpd->lock_flags;
2335         wpi.vgroup_validmap =    wpd->vgroup_validmap;
2336         wpi.do_flip =            RNA_boolean_get(itemptr, "pen_flip");
2337         wpi.do_multipaint =      (ts->multipaint != 0);
2338         wpi.do_auto_normalize =  ((ts->auto_normalize != 0) && (wpi.vgroup_validmap != NULL));
2339         wpi.brush_alpha_value =  brush_alpha_value;
2340         /* *** done setting up WeightPaintInfo *** */
2341
2342
2343
2344         swap_m4m4(wpd->vc.rv3d->persmat, mat);
2345
2346         use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
2347         use_face_sel = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
2348         use_depth = (vc->v3d->flag & V3D_ZBUF_SELECT);
2349
2350         /* which faces are involved */
2351         if (use_depth) {
2352                 if (wp->flag & VP_AREA) {
2353                         /* Ugly hack, to avoid drawing vertex index when getting the face index buffer - campbell */
2354                         me->editflag &= ~ME_EDIT_PAINT_VERT_SEL;
2355                         totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2356                         me->editflag |= use_vert_sel ? ME_EDIT_PAINT_VERT_SEL : 0;
2357                 }
2358                 else {
2359                         indexar[0] = view3d_sample_backbuf(vc, mval[0], mval[1]);
2360                         if (indexar[0]) totindex = 1;
2361                         else totindex = 0;
2362                 }
2363
2364                 if (use_face_sel && me->mpoly) {
2365                         for (index = 0; index < totindex; index++) {
2366                                 if (indexar[index] && indexar[index] <= me->totpoly) {
2367                                         MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2368
2369                                         if ((mpoly->flag & ME_FACE_SEL) == 0) {
2370                                                 indexar[index] = 0;
2371                                         }
2372                                 }
2373                         }
2374                 }
2375         }
2376         else {
2377                 indexar = NULL;
2378         }
2379
2380         /* make sure each vertex gets treated only once */
2381         /* and calculate filter weight */
2382         totw = 0.0f;
2383         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR)
2384                 paintweight = 0.0f;
2385         else
2386                 paintweight = BKE_brush_weight_get(scene, brush);
2387
2388 #define WP_BLUR_ACCUM(v_idx_var)  \
2389         { \
2390                 const unsigned int vidx = v_idx_var; \
2391                 const float fac = calc_vp_strength_col_dl(wp, vc, wpd->vertexcosnos[vidx].co, mval, brush_size_pressure, NULL); \
2392                 if (fac > 0.0f) { \
2393                         MDeformWeight *dw = dw_func(&me->dvert[vidx], wpi.vgroup_active); \
2394                         paintweight += dw ? (dw->weight * fac) : 0.0f; \
2395                         totw += fac; \
2396                 } \
2397         } (void)0
2398
2399
2400         if (use_depth) {
2401                 for (index = 0; index < totindex; index++) {
2402                         if (indexar[index] && indexar[index] <= me->totpoly) {
2403                                 MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2404                                 MLoop *ml = me->mloop + mpoly->loopstart;
2405                                 int i;
2406
2407                                 if (use_vert_sel) {
2408                                         for (i = 0; i < mpoly->totloop; i++, ml++) {
2409                                                 me->dvert[ml->v].flag = (me->mvert[ml->v].flag & SELECT);
2410                                         }
2411                                 }
2412                                 else {
2413                                         for (i = 0; i < mpoly->totloop; i++, ml++) {
2414                                                 me->dvert[ml->v].flag = 1;
2415                                         }
2416                                 }
2417
2418                                 if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2419                                         ml = me->mloop + mpoly->loopstart;
2420                                         for (i = 0; i < mpoly->totloop; i++, ml++) {
2421                                                 WP_BLUR_ACCUM(ml->v);
2422                                         }
2423                                 }
2424                         }
2425                 }
2426         }
2427         else {
2428                 const unsigned int totvert = me->totvert;
2429                 unsigned int       i;
2430
2431                 /* in the case of face selection we need to flush */
2432                 if (use_vert_sel || use_face_sel) {
2433                         for (i = 0; i < totvert; i++) {
2434                                 me->dvert[i].flag = me->mvert[i].flag & SELECT;
2435                         }
2436                 }
2437                 else {
2438                         for (i = 0; i < totvert; i++) {
2439                                 me->dvert[i].flag = SELECT;
2440                         }
2441                 }
2442
2443                 if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2444                         for (i = 0; i < totvert; i++) {
2445                                 WP_BLUR_ACCUM(i);
2446                         }
2447                 }
2448         }
2449
2450 #undef WP_BLUR_ACCUM
2451
2452
2453         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2454                 paintweight /= totw;
2455         }
2456
2457 #define WP_PAINT(v_idx_var)  \
2458         { \
2459                 unsigned int vidx = v_idx_var; \
2460                 if (me->dvert[vidx].flag) { \
2461                         alpha = calc_vp_alpha_col_dl(wp, vc, wpd->wpimat, &wpd->vertexcosnos[vidx], \
2462                                                  mval, brush_size_pressure, brush_alpha_pressure, NULL); \
2463                         if (alpha) { \
2464                                 do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight); \
2465                         } \
2466                         me->dvert[vidx].flag = 0; \
2467                 } \
2468         } (void)0
2469
2470         if (use_depth) {
2471                 for (index = 0; index < totindex; index++) {
2472
2473                         if (indexar[index] && indexar[index] <= me->totpoly) {
2474                                 MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2475                                 MLoop *ml = me->mloop + mpoly->loopstart;
2476                                 int i;
2477
2478                                 for (i = 0; i < mpoly->totloop; i++, ml++) {
2479                                         WP_PAINT(ml->v);
2480                                 }
2481                         }
2482                 }
2483         }
2484         else {
2485                 const unsigned int totvert = me->totvert;
2486                 unsigned int       i;
2487
2488                 for (i = 0; i < totvert; i++) {
2489                         WP_PAINT(i);
2490                 }
2491         }
2492 #undef WP_PAINT
2493
2494
2495         /* *** free wpi members */
2496         MEM_freeN((void *)wpi.defbase_sel);
2497         /* *** done freeing wpi members */
2498
2499
2500         swap_m4m4(vc->rv3d->persmat, mat);
2501
2502         {
2503                 UnifiedPaintSettings *ups = &ts->unified_paint_settings;
2504                 ups->pressure_value = pressure;
2505         }
2506
2507         DAG_id_tag_update(ob->data, 0);
2508         ED_region_tag_redraw(vc->ar);
2509 }
2510
2511 static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2512 {
2513         ToolSettings *ts = CTX_data_tool_settings(C);
2514         Object *ob = CTX_data_active_object(C);
2515         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2516         
2517         if (wpd) {
2518                 if (wpd->vertexcosnos)
2519                         MEM_freeN(wpd->vertexcosnos);
2520                 MEM_freeN(wpd->indexar);
2521                 
2522                 if (wpd->vgroup_validmap)
2523                         MEM_freeN((void *)wpd->vgroup_validmap);
2524                 if (wpd->lock_flags)
2525                         MEM_freeN((void *)wpd->lock_flags);
2526
2527                 MEM_freeN(wpd);
2528         }
2529         
2530         /* frees prev buffer */
2531         copy_wpaint_prev(ts->wpaint, NULL, 0);
2532         
2533         /* and particles too */
2534         if (ob->particlesystem.first) {
2535                 ParticleSystem *psys;
2536                 int i;
2537                 
2538                 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2539                         for (i = 0; i < PSYS_TOT_VG; i++) {
2540                                 if (psys->vgroup[i] == ob->actdef) {
2541                                         psys->recalc |= PSYS_RECALC_RESET;
2542                                         break;
2543                                 }
2544                         }
2545                 }
2546         }
2547
2548         {
2549                 UnifiedPaintSettings *ups = &ts->unified_paint_settings;
2550                 ups->draw_pressure = false;
2551         }
2552
2553         DAG_id_tag_update(ob->data, 0);
2554
2555         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2556 }
2557
2558
2559 static int wpaint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2560 {
2561         int retval;
2562
2563         op->customdata = paint_stroke_new(C, NULL, wpaint_stroke_test_start,
2564                                           wpaint_stroke_update_step, NULL,
2565                                           wpaint_stroke_done, event->type);
2566         
2567         /* add modal handler */
2568         WM_event_add_modal_handler(C, op);
2569
2570         retval = op->type->modal(C, op, event);
2571         OPERATOR_RETVAL_CHECK(retval);
2572         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
2573         
2574         return OPERATOR_RUNNING_MODAL;
2575 }
2576
2577 static int wpaint_cancel(bContext *C, wmOperator *op)
2578 {
2579         paint_stroke_cancel(C, op);
2580
2581         return OPERATOR_CANCELLED;
2582 }
2583
2584 void PAINT_OT_weight_paint(wmOperatorType *ot)
2585 {
2586         
2587         /* identifiers */
2588         ot->name = "Weight Paint";
2589         ot->idname = "PAINT_OT_weight_paint";
2590         ot->description = "Paint a stroke in the current vertex group's weights";
2591         
2592         /* api callbacks */
2593         ot->invoke = wpaint_invoke;
2594         ot->modal = paint_stroke_modal;
2595         /* ot->exec = vpaint_exec; <-- needs stroke property */
2596         ot->poll = weight_paint_poll;
2597         ot->cancel = wpaint_cancel;
2598         
2599         /* flags */
2600         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
2601
2602         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2603 }
2604
2605 static int weight_paint_set_exec(bContext *C, wmOperator *op)
2606 {
2607         struct Scene *scene = CTX_data_scene(C);
2608         Object *obact = CTX_data_active_object(C);
2609         ToolSettings *ts = CTX_data_tool_settings(C);
2610         Brush *brush = BKE_paint_brush(&ts->wpaint->paint);
2611         float vgroup_weight = BKE_brush_weight_get(scene, brush);
2612
2613         if (wpaint_ensure_data(C, op) == FALSE) {
2614                 return OPERATOR_CANCELLED;
2615         }
2616
2617         if (ED_wpaint_fill(scene->toolsettings->wpaint, obact, vgroup_weight)) {
2618                 ED_region_tag_redraw(CTX_wm_region(C)); /* XXX - should redraw all 3D views */
2619                 return OPERATOR_FINISHED;
2620         }
2621         else {
2622                 return OPERATOR_CANCELLED;
2623         }
2624 }
2625
2626 void PAINT_OT_weight_set(wmOperatorType *ot)
2627 {
2628         /* identifiers */
2629         ot->name = "Set Weight";
2630         ot->idname = "PAINT_OT_weight_set";
2631         ot->description = "Fill the active vertex group with the current paint weight";
2632
2633         /* api callbacks */
2634         ot->exec = weight_paint_set_exec;
2635         ot->poll = mask_paint_poll; /* it was facemask_paint_poll */
2636
2637         /* flags */
2638         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2639 }
2640
2641 /* ************ set / clear vertex paint mode ********** */
2642
2643
2644 static int set_vpaint(bContext *C, wmOperator *op)  /* toggle */
2645 {       
2646         Object *ob = CTX_data_active_object(C);
2647         Scene *scene = CTX_data_scene(C);
2648         VPaint *vp = scene->toolsettings->vpaint;
2649         Mesh *me;
2650         
2651         me = BKE_mesh_from_object(ob);
2652         
2653         if (me == NULL || BKE_object_obdata_is_libdata(ob)) {
2654                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2655                 return OPERATOR_PASS_THROUGH;
2656         }
2657         
2658         if (me && me->mloopcol == NULL) {
2659                 make_vertexcol(ob);
2660         }
2661         
2662         /* toggle: end vpaint */
2663         if (ob->mode & OB_MODE_VERTEX_PAINT) {
2664                 
2665                 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2666
2667                 if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
2668                         BKE_mesh_flush_select_from_polys(me);
2669                 }
2670         }
2671         else {
2672                 ob->mode |= OB_MODE_VERTEX_PAINT;
2673                 /* Turn off weight painting */
2674                 if (ob->mode & OB_MODE_WEIGHT_PAINT)
2675                         set_wpaint(C, op);
2676                 
2677                 if (vp == NULL)
2678                         vp = scene->toolsettings->vpaint = new_vpaint(0);
2679                 
2680                 paint_cursor_start(C, vertex_paint_poll);
2681
2682                 BKE_paint_init(&vp->paint, PAINT_CURSOR_VERTEX_PAINT);
2683         }
2684         
2685         /* update modifier stack for mapping requirements */
2686         DAG_id_tag_update(&me->id, 0);
2687         
2688         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2689         
2690         return OPERATOR_FINISHED;
2691 }
2692
2693 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2694 {
2695         
2696         /* identifiers */
2697         ot->name = "Vertex Paint Mode";
2698         ot->idname = "PAINT_OT_vertex_paint_toggle";
2699         ot->description = "Toggle the vertex paint mode in 3D view";
2700         
2701         /* api callbacks */
2702         ot->exec = set_vpaint;
2703         ot->poll = paint_poll_test;
2704         
2705         /* flags */
2706         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2707 }
2708
2709
2710
2711 /* ********************** vertex paint operator ******************* */
2712
2713 /* Implementation notes:
2714  *
2715  * Operator->invoke()
2716  * - validate context (add mcol)
2717  * - create customdata storage
2718  * - call paint once (mouse click)
2719  * - add modal handler 
2720  *
2721  * Operator->modal()
2722  * - for every mousemove, apply vertex paint
2723  * - exit on mouse release, free customdata
2724  *   (return OPERATOR_FINISHED also removes handler and operator)
2725  *
2726  * For future:
2727  * - implement a stroke event (or mousemove with past positons)
2728  * - revise whether op->customdata should be added in object, in set_vpaint
2729  */
2730
2731 typedef struct PolyFaceMap {
2732         struct PolyFaceMap *next, *prev;
2733         int facenr;
2734 } PolyFaceMap;
2735
2736 typedef struct VPaintData {
2737         ViewContext vc;
2738         unsigned int paintcol;
2739         int *indexar;
2740         DMCoNo *vertexcosnos;
2741         float vpimat[3][3];
2742
2743         /* modify 'me->mcol' directly, since the derived mesh is drawing from this
2744          * array, otherwise we need to refresh the modifier stack */
2745         int use_fast_update;
2746
2747         /* mpoly -> mface mapping */
2748         MemArena *polyfacemap_arena;
2749         ListBase *polyfacemap;
2750
2751         /* loops tagged as having been painted, to apply shared vertex color
2752          * blending only to modified loops */
2753         bool *mlooptag;
2754         bool *mfacetag;
2755
2756         bool is_texbrush;
2757 } VPaintData;
2758
2759 static void vpaint_build_poly_facemap(struct VPaintData *vd, Mesh *me)
2760 {
2761         MFace *mf;
2762         PolyFaceMap *e;
2763         int *origIndex;
2764         int i;
2765
2766         vd->polyfacemap_arena = BLI_memarena_new(1 << 13, "vpaint tmp");
2767         BLI_memarena_use_calloc(vd->polyfacemap_arena);
2768
2769         vd->polyfacemap = BLI_memarena_alloc(vd->polyfacemap_arena, sizeof(ListBase) * me->totpoly);
2770
2771         origIndex = CustomData_get_layer(&me->fdata, CD_ORIGINDEX);
2772         mf = me->mface;
2773
2774         if (!origIndex)
2775                 return;
2776
2777         for (i = 0; i < me->totface; i++, mf++, origIndex++) {
2778                 if (*origIndex == ORIGINDEX_NONE)
2779                         continue;
2780
2781                 e = BLI_memarena_alloc(vd->polyfacemap_arena, sizeof(PolyFaceMap));
2782                 e->facenr = i;
2783                 
2784                 BLI_addtail(&vd->polyfacemap[*origIndex], e);
2785         }
2786 }
2787
2788 static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const float UNUSED(mouse[2]))
2789 {
2790         ToolSettings *ts = CTX_data_tool_settings(C);
2791         struct PaintStroke *stroke = op->customdata;
2792         VPaint *vp = ts->vpaint;
2793         Brush *brush = BKE_paint_brush(&vp->paint);
2794         struct VPaintData *vpd;
2795         Object *ob = CTX_data_active_object(C);
2796         Mesh *me;
2797         float mat[4][4], imat[4][4];
2798
2799         /* context checks could be a poll() */
2800         me = BKE_mesh_from_object(ob);
2801         if (me == NULL || me->totpoly == 0)
2802                 return OPERATOR_PASS_THROUGH;
2803         
2804         if (me->mloopcol == NULL)
2805                 make_vertexcol(ob);
2806         if (me->mloopcol == NULL)
2807                 return OPERATOR_CANCELLED;
2808
2809         /* Update tessface data if needed
2810          * Added here too because e.g. switching to/from edit mode would remove tessface data,
2811          * yet "fast_update" could still be used! */
2812         update_tessface_data(ob, me);
2813
2814         /* make mode data storage */
2815         vpd = MEM_callocN(sizeof(struct VPaintData), "VPaintData");
2816         paint_stroke_set_mode_data(stroke, vpd);
2817         view3d_set_viewcontext(C, &vpd->vc);
2818         
2819         vpd->vertexcosnos = mesh_get_mapped_verts_nors(vpd->vc.scene, ob);
2820         vpd->indexar = get_indexarray(me);
2821         vpd->paintcol = vpaint_get_current_col(vp);
2822
2823         vpd->is_texbrush = !(brush->vertexpaint_tool == PAINT_BLEND_BLUR) &&
2824                            brush->mtex.tex;
2825
2826         /* are we painting onto a modified mesh?,
2827          * if not we can skip face map trickyness */
2828         if (vertex_paint_use_fast_update_check(ob)) {
2829                 vpaint_build_poly_facemap(vpd, me);
2830                 vpd->use_fast_update = TRUE;
2831 /*              printf("Fast update!\n");*/
2832         }
2833         else {
2834                 vpd->use_fast_update = FALSE;
2835 /*              printf("No fast update!\n");*/
2836         }
2837
2838         /* to keep tracked of modified loops for shared vertex color blending */
2839         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2840                 vpd->mlooptag = MEM_mallocN(sizeof(bool) * me->totloop, "VPaintData mlooptag");
2841                 if (vpd->use_fast_update)
2842                         vpd->mfacetag = MEM_mallocN(sizeof(bool) * me->totface * 4, "VPaintData mfacetag");
2843         }
2844
2845         /* for filtering */
2846         copy_vpaint_prev(vp, (unsigned int *)me->mloopcol, me->totloop);
2847         
2848         /* some old cruft to sort out later */
2849         mult_m4_m4m4(mat, vpd->vc.rv3d->viewmat, ob->obmat);
2850         invert_m4_m4(imat, mat);
2851         copy_m3_m4(vpd->vpimat, imat);
2852
2853         {
2854                 UnifiedPaintSettings *ups = &ts->unified_paint_settings;
2855                 ups->draw_pressure = true;
2856         }
2857
2858         return 1;
2859 }
2860
2861 static void vpaint_paint_poly(VPaint *vp, VPaintData *vpd, Mesh *me,
2862                               const unsigned int index, const float mval[2],
2863                               const float brush_size_pressure, const float brush_alpha_pressure)
2864 {
2865         ViewContext *vc = &vpd->vc;
2866         Brush *brush = BKE_paint_brush(&vp->paint);
2867         MPoly *mpoly = &me->mpoly[index];
2868         MFace *mf;
2869         MCol *mc;
2870         MLoop *ml;
2871         MLoopCol *mlc;
2872         PolyFaceMap *e;
2873         unsigned int *lcol = ((unsigned int *)me->mloopcol) + mpoly->loopstart;
2874         unsigned int *lcolorig = ((unsigned int *)vp->vpaint_prev) + mpoly->loopstart;
2875         bool *mlooptag = (vpd->mlooptag) ? vpd->mlooptag + mpoly->loopstart : NULL;
2876         bool *mftag;
2877         float alpha;
2878         int i, j;
2879         int totloop = mpoly->totloop;
2880
2881         int brush_alpha_pressure_i = (int)(brush_alpha_pressure * 255.0f);
2882
2883         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2884                 unsigned int blend[4] = {0};
2885                 unsigned int tcol;
2886                 char *col;
2887
2888                 for (j = 0; j < totloop; j++) {
2889                         col = (char *)(lcol + j);
2890                         blend[0] += col[0];
2891                         blend[1] += col[1];
2892                         blend[2] += col[2];
2893                         blend[3] += col[3];
2894                 }
2895
2896                 blend[0] = divide_round_i(blend[0], totloop);
2897                 blend[1] = divide_round_i(blend[1], totloop);
2898                 blend[2] = divide_round_i(blend[2], totloop);
2899                 blend[3] = divide_round_i(blend[3], totloop);
2900                 col = (char *)&tcol;
2901                 col[0] = blend[0];
2902                 col[1] = blend[1];
2903                 col[2] = blend[2];
2904                 col[3] = blend[3];
2905
2906                 vpd->paintcol = *((unsigned int *)col);
2907         }
2908
2909         ml = me->mloop + mpoly->loopstart;
2910         for (i = 0; i < totloop; i++, ml++) {
2911                 float rgba[4];
2912                 unsigned int paintcol;
2913                 alpha = calc_vp_alpha_col_dl(vp, vc, vpd->vpimat,
2914                                          &vpd->vertexcosnos[ml->v], mval,
2915                                          brush_size_pressure, brush_alpha_pressure, rgba);
2916
2917                 if (vpd->is_texbrush) {
2918                         float rgba_br[3];
2919                         rgb_uchar_to_float(rgba_br, (const unsigned char *)&vpd->paintcol);
2920                         mul_v3_v3(rgba_br, rgba);
2921                         rgb_float_to_uchar((unsigned char *)&paintcol, rgba_br);
2922                 }
2923                 else
2924                         paintcol = vpd->paintcol;
2925
2926                 if (alpha > 0.0f) {
2927                         const int alpha_i = (int)(alpha * 255.0f);
2928                         lcol[i] = vpaint_blend(vp, lcol[i], lcolorig[i], paintcol, alpha_i, brush_alpha_pressure_i);
2929
2930                         if (mlooptag) mlooptag[i] = 1;
2931                 }
2932         }
2933
2934         if (vpd->use_fast_update) {
2935                 /* update vertex colors for tessellations incrementally,
2936                  * rather then regenerating the tessellation altogether */
2937                 for (e = vpd->polyfacemap[index].first; e; e = e->next) {
2938                         mf = &me->mface[e->facenr];
2939                         mc = &me->mcol[e->facenr * 4];
2940                         mftag = &vpd->mfacetag[e->facenr * 4];
2941
2942                         ml = me->mloop + mpoly->loopstart;
2943                         mlc = me->mloopcol + mpoly->loopstart;
2944                         for (j = 0; j < totloop; j++, ml++, mlc++) {
2945                                 if (ml->v == mf->v1) {
2946                                         MESH_MLOOPCOL_TO_MCOL(mlc, mc + 0);
2947                                         if (mlooptag) mftag[0] = mlooptag[j];
2948                                 }
2949                                 else if (ml->v == mf->v2) {
2950                                         MESH_MLOOPCOL_TO_MCOL(mlc, mc + 1);
2951                                         if (mlooptag) mftag[1] = mlooptag[j];
2952                                 }
2953                                 else if (ml->v == mf->v3) {
2954                                         MESH_MLOOPCOL_TO_MCOL(mlc, mc + 2);
2955                                         if (mlooptag) mftag[2] = mlooptag[j];
2956                                 }
2957                                 else if (mf->v4 && ml->v == mf->v4) {
2958                                         MESH_MLOOPCOL_TO_MCOL(mlc, mc + 3);
2959                                         if (mlooptag) mftag[3] = mlooptag[j];
2960                                 }
2961                         }
2962                 }
2963         }
2964
2965 }
2966
2967 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2968 {
2969         Scene *scene = CTX_data_scene(C);
2970         ToolSettings *ts = CTX_data_tool_settings(C);
2971         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2972         VPaint *vp = ts->vpaint;
2973         Brush *brush = BKE_paint_brush(&vp->paint);
2974         ViewContext *vc = &vpd->vc;
2975         Object *ob = vc->obact;
2976         Mesh *me = ob->data;
2977         float mat[4][4];
2978         int *indexar = vpd->indexar;
2979         int totindex, index;
2980         float mval[2];
2981
2982         const float pressure = RNA_float_get(itemptr, "pressure");
2983         const float brush_size_pressure = BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2984         const float brush_alpha_pressure = BKE_brush_alpha_get(scene, brush) * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2985
2986         RNA_float_get_array(itemptr, "mouse", mval);
2987
2988         view3d_operator_needs_opengl(C);
2989         ED_view3d_init_mats_rv3d(ob, vc->rv3d);
2990
2991         /* load projection matrix */
2992         mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2993
2994         /* which faces are involved */
2995         if (vp->flag & VP_AREA) {
2996                 totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2997         }
2998         else {
2999                 indexar[0] = view3d_sample_backbuf(vc, mval[0], mval[1]);
3000                 if (indexar[0]) totindex = 1;
3001                 else totindex = 0;
3002         }
3003
3004         if ((me->editflag & ME_EDIT_PAINT_FACE_SEL) && me->mpoly) {
3005                 for (index = 0; index < totindex; index++) {
3006                         if (indexar[index] && indexar[index] <= me->totpoly) {
3007                                 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
3008                                                 
3009                                 if ((mpoly->flag & ME_FACE_SEL) == 0)
3010                                         indexar[index] = 0;
3011                         }
3012                 }
3013         }
3014         
3015         swap_m4m4(vc->rv3d->persmat, mat);
3016
3017         /* clear modified tag for blur tool */
3018         if (vpd->mlooptag)
3019                 memset(vpd->mlooptag, 0, sizeof(bool) * me->totloop);
3020         if (vpd->mfacetag)
3021                 memset(vpd->mfacetag, 0, sizeof(bool) * me->totface * 4);
3022
3023         for (index = 0; index < totindex; index++) {
3024                 if (indexar[index] && indexar[index] <= me->totpoly) {
3025                         vpaint_paint_poly(vp, vpd, me, indexar[index] - 1, mval, brush_size_pressure, brush_alpha_pressure);
3026                 }
3027         }
3028                 
3029         swap_m4m4(vc->rv3d->persmat, mat);
3030
3031         /* was disabled because it is slow, but necessary for blur */
3032         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
3033                 int do_tessface = vpd->use_fast_update;
3034                 do_shared_vertexcol(me, vpd->mlooptag, vpd->mfacetag, do_tessface);
3035         }
3036
3037         {