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