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