2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Contributor(s): none yet.
25 * ***** END GPL LICENSE BLOCK *****
28 /** \file blender/editors/sculpt_paint/paint_vertex.c
42 #include "MEM_guardedalloc.h"
44 #include "BLI_blenlib.h"
46 #include "BLI_memarena.h"
47 #include "BLI_utildefines.h"
48 #include "BLI_ghash.h"
50 #include "IMB_imbuf.h"
51 #include "IMB_imbuf_types.h"
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"
61 #include "RNA_access.h"
62 #include "RNA_define.h"
63 #include "RNA_enum_types.h"
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"
73 #include "BKE_modifier.h"
74 #include "BKE_object.h"
75 #include "BKE_paint.h"
76 #include "BKE_report.h"
82 #include "ED_armature.h"
84 #include "ED_screen.h"
85 #include "ED_view3d.h"
87 #include "paint_intern.h"
89 /* check if we can do partial updates and have them draw realtime
90 * (without rebuilding the 'derivedFinal') */
91 static int vertex_paint_use_fast_update_check(Object *ob)
93 DerivedMesh *dm = ob->derivedFinal;
96 Mesh *me = BKE_mesh_from_object(ob);
98 return (me->mcol == CustomData_get_layer(&dm->faceData, CD_MCOL));
105 /* if the polygons from the mesh and the 'derivedFinal' match
106 * we can assume that no modifiers are applied and that its worth adding tessellated faces
107 * so 'vertex_paint_use_fast_update_check()' returns TRUE */
108 static int vertex_paint_use_tessface_check(Object *ob)
110 DerivedMesh *dm = ob->derivedFinal;
113 Mesh *me = BKE_mesh_from_object(ob);
114 return (me->mpoly == CustomData_get_layer(&dm->faceData, CD_MPOLY));
120 /* polling - retrieve whether cursor should be set or operator should be done */
122 /* Returns true if vertex paint mode is active */
123 int vertex_paint_mode_poll(bContext *C)
125 Object *ob = CTX_data_active_object(C);
127 return ob && ob->mode == OB_MODE_VERTEX_PAINT && ((Mesh *)ob->data)->totpoly;
130 int vertex_paint_poll(bContext *C)
132 if (vertex_paint_mode_poll(C) &&
133 paint_brush(&CTX_data_tool_settings(C)->vpaint->paint))
135 ScrArea *sa = CTX_wm_area(C);
136 if (sa->spacetype == SPACE_VIEW3D) {
137 ARegion *ar = CTX_wm_region(C);
138 if (ar->regiontype == RGN_TYPE_WINDOW)
145 int weight_paint_mode_poll(bContext *C)
147 Object *ob = CTX_data_active_object(C);
149 return ob && ob->mode == OB_MODE_WEIGHT_PAINT && ((Mesh *)ob->data)->totpoly;
152 int weight_paint_poll(bContext *C)
154 Object *ob = CTX_data_active_object(C);
158 (ob->mode & OB_MODE_WEIGHT_PAINT) &&
159 (paint_brush(&CTX_data_tool_settings(C)->wpaint->paint) != NULL) &&
160 (sa = CTX_wm_area(C)) &&
161 (sa->spacetype == SPACE_VIEW3D))
163 ARegion *ar = CTX_wm_region(C);
164 if (ar->regiontype == RGN_TYPE_WINDOW) {
171 static VPaint *new_vpaint(int wpaint)
173 VPaint *vp = MEM_callocN(sizeof(VPaint), "VPaint");
175 vp->flag = VP_AREA + VP_SPRAY;
183 static int *get_indexarray(Mesh *me)
185 return MEM_mallocN(sizeof(int) * (me->totpoly + 1), "vertexpaint");
188 unsigned int vpaint_get_current_col(VPaint *vp)
190 Brush *brush = paint_brush(&vp->paint);
191 unsigned char col[4];
192 rgb_float_to_uchar(col, brush->rgb);
193 col[3] = 255; /* alpha isn't used, could even be removed to speedup paint a little */
194 return *(unsigned int *)col;
197 static void do_shared_vertex_tesscol(Mesh *me)
199 /* if no mcol: do not do */
200 /* if tface: only the involved faces, otherwise all */
201 const int use_face_sel = (me->editflag & ME_EDIT_PAINT_MASK);
204 short *scolmain, *scol;
207 if (me->mcol == NULL || me->totvert == 0 || me->totface == 0) return;
209 scolmain = MEM_callocN(4 * sizeof(short) * me->totvert, "colmain");
212 mcol = (char *)me->mcol;
213 for (a = me->totface; a > 0; a--, mface++, mcol += 16) {
214 if ((use_face_sel == FALSE) || (mface->flag & ME_FACE_SEL)) {
215 scol = scolmain + 4 * mface->v1;
216 scol[0]++; scol[1] += mcol[1]; scol[2] += mcol[2]; scol[3] += mcol[3];
217 scol = scolmain + 4 * mface->v2;
218 scol[0]++; scol[1] += mcol[5]; scol[2] += mcol[6]; scol[3] += mcol[7];
219 scol = scolmain + 4 * mface->v3;
220 scol[0]++; scol[1] += mcol[9]; scol[2] += mcol[10]; scol[3] += mcol[11];
222 scol = scolmain + 4 * mface->v4;
223 scol[0]++; scol[1] += mcol[13]; scol[2] += mcol[14]; scol[3] += mcol[15];
240 mcol = (char *)me->mcol;
241 for (a = me->totface; a > 0; a--, mface++, mcol += 16) {
242 if ((use_face_sel == FALSE) || (mface->flag & ME_FACE_SEL)) {
243 scol = scolmain + 4 * mface->v1;
244 mcol[1] = scol[1]; mcol[2] = scol[2]; mcol[3] = scol[3];
245 scol = scolmain + 4 * mface->v2;
246 mcol[5] = scol[1]; mcol[6] = scol[2]; mcol[7] = scol[3];
247 scol = scolmain + 4 * mface->v3;
248 mcol[9] = scol[1]; mcol[10] = scol[2]; mcol[11] = scol[3];
250 scol = scolmain + 4 * mface->v4;
251 mcol[13] = scol[1]; mcol[14] = scol[2]; mcol[15] = scol[3];
259 void do_shared_vertexcol(Mesh *me, int do_tessface)
261 const int use_face_sel = (me->editflag & ME_EDIT_PAINT_MASK);
264 int i, j, has_shared = 0;
266 /* if no mloopcol: do not do */
267 /* if mtexpoly: only the involved faces, otherwise all */
269 if (me->mloopcol == 0 || me->totvert == 0 || me->totpoly == 0) return;
271 scol = MEM_callocN(sizeof(float) * me->totvert * 5, "scol");
273 for (i = 0, mp = me->mpoly; i < me->totpoly; i++, mp++) {
274 if ((use_face_sel == FALSE) || (mp->flag & ME_FACE_SEL)) {
275 MLoop *ml = me->mloop + mp->loopstart;
276 MLoopCol *lcol = me->mloopcol + mp->loopstart;
277 for (j = 0; j < mp->totloop; j++, ml++, lcol++) {
278 scol[ml->v][0] += lcol->r;
279 scol[ml->v][1] += lcol->g;
280 scol[ml->v][2] += lcol->b;
281 scol[ml->v][3] += 1.0f;
288 for (i = 0; i < me->totvert; i++) {
289 if (scol[i][3] != 0.0f) {
290 mul_v3_fl(scol[i], 1.0f / scol[i][3]);
294 for (i = 0, mp = me->mpoly; i < me->totpoly; i++, mp++) {
295 if ((use_face_sel == FALSE) || (mp->flag & ME_FACE_SEL)) {
296 MLoop *ml = me->mloop + mp->loopstart;
297 MLoopCol *lcol = me->mloopcol + mp->loopstart;
298 for (j = 0; j < mp->totloop; j++, ml++, lcol++) {
299 lcol->r = scol[ml->v][0];
300 lcol->g = scol[ml->v][1];
301 lcol->b = scol[ml->v][2];
309 if (has_shared && do_tessface) {
310 do_shared_vertex_tesscol(me);
314 static void make_vertexcol(Object *ob) /* single ob */
317 if (!ob || ob->id.lib) return;
318 me = BKE_mesh_from_object(ob);
319 if (me == NULL) return;
320 if (me->edit_btmesh) return;
322 /* copies from shadedisplist to mcol */
325 CustomData_add_layer(&me->fdata, CD_MCOL, CD_DEFAULT, NULL, me->totface);
328 CustomData_add_layer(&me->ldata, CD_MLOOPCOL, CD_DEFAULT, NULL, me->totloop);
330 mesh_update_customdata_pointers(me, TRUE);
333 if (vertex_paint_use_tessface_check(ob)) {
334 /* assume if these exist, that they are up to date & valid */
335 if (!me->mcol || !me->mface) {
336 /* should always be true */
338 memset(me->mcol, 255, 4 * sizeof(MCol) * me->totface);
341 /* create tessfaces because they will be used for drawing & fast updates */
342 BKE_mesh_tessface_calc(me); /* does own call to update pointers */
347 /* this wont be used, theres no need to keep it */
348 BKE_mesh_tessface_clear(me);
353 // shadeMeshMCol(scene, ob, me);
356 DAG_id_tag_update(&me->id, 0);
360 /* mirror_vgroup is set to -1 when invalid */
361 static int wpaint_mirror_vgroup_ensure(Object *ob, const int vgroup_active)
363 bDeformGroup *defgroup = BLI_findlink(&ob->defbase, vgroup_active);
366 bDeformGroup *curdef;
368 char name[MAXBONENAME];
370 flip_side_name(name, defgroup->name, FALSE);
372 if (strcmp(name, defgroup->name) != 0) {
373 for (curdef = ob->defbase.first, mirrdef = 0; curdef; curdef = curdef->next, mirrdef++) {
374 if (!strcmp(curdef->name, name)) {
379 if (curdef == NULL) {
380 int olddef = ob->actdef; /* tsk, ED_vgroup_add sets the active defgroup */
381 curdef = ED_vgroup_add_name(ob, name);
385 /* curdef should never be NULL unless this is
386 * a lamp and ED_vgroup_add_name fails */
396 static void copy_vpaint_prev(VPaint *vp, unsigned int *lcol, int tot)
398 if (vp->vpaint_prev) {
399 MEM_freeN(vp->vpaint_prev);
400 vp->vpaint_prev = NULL;
404 if (lcol == NULL || tot == 0) return;
406 vp->vpaint_prev = MEM_mallocN(sizeof(int) * tot, "vpaint_prev");
407 memcpy(vp->vpaint_prev, lcol, sizeof(int) * tot);
411 static void copy_wpaint_prev(VPaint *wp, MDeformVert *dverts, int dcount)
413 if (wp->wpaint_prev) {
414 free_dverts(wp->wpaint_prev, wp->tot);
415 wp->wpaint_prev = NULL;
418 if (dverts && dcount) {
420 wp->wpaint_prev = MEM_mallocN(sizeof(MDeformVert) * dcount, "wpaint prev");
422 copy_dverts(wp->wpaint_prev, dverts, dcount);
427 void vpaint_fill(Object *ob, unsigned int paintcol)
434 me = BKE_mesh_from_object(ob);
435 if (me == NULL || me->totpoly == 0) return;
437 if (!me->mloopcol) make_vertexcol(ob);
438 if (!me->mloopcol) return; /* possible we can't make mcol's */
441 selected = (me->editflag & ME_EDIT_PAINT_MASK);
444 for (i = 0; i < me->totpoly; i++, mp++) {
445 if (!(!selected || mp->flag & ME_FACE_SEL))
448 lcol = me->mloopcol + mp->loopstart;
449 for (j = 0; j < mp->totloop; j++, lcol++) {
450 *(int *)lcol = paintcol;
454 /* remove stale me->mcol, will be added later */
455 BKE_mesh_tessface_clear(me);
457 DAG_id_tag_update(&me->id, 0);
461 /* fills in the selected faces with the current weight and vertex group */
462 void wpaint_fill(VPaint *wp, Object *ob, float paintweight)
466 MDeformWeight *dw, *dw_prev;
467 int vgroup_active, vgroup_mirror = -1;
470 /* mutually exclusive, could be made into a */
471 const short paint_selmode = ME_EDIT_PAINT_SEL_MODE(me);
473 if (me->totpoly == 0 || me->dvert == NULL || !me->mpoly) return;
475 vgroup_active = ob->actdef - 1;
477 /* if mirror painting, find the other group */
478 if (me->editflag & ME_EDIT_MIRROR_X) {
479 vgroup_mirror = wpaint_mirror_vgroup_ensure(ob, vgroup_active);
482 copy_wpaint_prev(wp, me->dvert, me->totvert);
484 for (index = 0, mp = me->mpoly; index < me->totpoly; index++, mp++) {
485 unsigned int fidx = mp->totloop - 1;
487 if ((paint_selmode == SCE_SELECT_FACE) && !(mp->flag & ME_FACE_SEL)) {
492 unsigned int vidx = me->mloop[mp->loopstart + fidx].v;
494 if (!me->dvert[vidx].flag) {
495 if ((paint_selmode == SCE_SELECT_VERTEX) && !(me->mvert[vidx].flag & SELECT)) {
499 dw = defvert_verify_index(&me->dvert[vidx], vgroup_active);
501 dw_prev = defvert_verify_index(wp->wpaint_prev + vidx, vgroup_active);
502 dw_prev->weight = dw->weight; /* set the undo weight */
503 dw->weight = paintweight;
505 if (me->editflag & ME_EDIT_MIRROR_X) { /* x mirror painting */
506 int j = mesh_get_x_mirror_vert(ob, vidx);
508 /* copy, not paint again */
509 if (vgroup_mirror != -1) {
510 dw = defvert_verify_index(me->dvert + j, vgroup_mirror);
511 dw_prev = defvert_verify_index(wp->wpaint_prev + j, vgroup_mirror);
514 dw = defvert_verify_index(me->dvert + j, vgroup_active);
515 dw_prev = defvert_verify_index(wp->wpaint_prev + j, vgroup_active);
517 dw_prev->weight = dw->weight; /* set the undo weight */
518 dw->weight = paintweight;
522 me->dvert[vidx].flag = 1;
529 MDeformVert *dv = me->dvert;
530 for (index = me->totvert; index != 0; index--, dv++) {
535 copy_wpaint_prev(wp, NULL, 0);
537 DAG_id_tag_update(&me->id, 0);
540 /* XXX: should be re-implemented as a vertex/weight paint 'color correct' operator */
542 void vpaint_dogamma(Scene *scene)
544 VPaint *vp = scene->toolsettings->vpaint;
549 unsigned char *cp, gamtab[256];
552 me = BKE_mesh_from_object(ob);
554 if (!(ob->mode & OB_MODE_VERTEX_PAINT)) return;
555 if (me == 0 || me->mcol == 0 || me->totface == 0) return;
557 igam = 1.0 / vp->gamma;
558 for (a = 0; a < 256; a++) {
560 fac = ((float)a) / 255.0;
561 fac = vp->mul * pow(fac, igam);
565 if (temp <= 0) gamtab[a] = 0;
566 else if (temp >= 255) gamtab[a] = 255;
567 else gamtab[a] = temp;
571 cp = (unsigned char *)me->mcol;
574 cp[1] = gamtab[cp[1]];
575 cp[2] = gamtab[cp[2]];
576 cp[3] = gamtab[cp[3]];
583 BLI_INLINE unsigned int mcol_blend(unsigned int col1, unsigned int col2, int fac)
585 unsigned char *cp1, *cp2, *cp;
587 unsigned int col = 0;
599 cp1 = (unsigned char *)&col1;
600 cp2 = (unsigned char *)&col2;
601 cp = (unsigned char *)&col;
603 cp[0] = (mfac * cp1[0] + fac * cp2[0]) / 255;
604 cp[1] = (mfac * cp1[1] + fac * cp2[1]) / 255;
605 cp[2] = (mfac * cp1[2] + fac * cp2[2]) / 255;
611 BLI_INLINE unsigned int mcol_add(unsigned int col1, unsigned int col2, int fac)
613 unsigned char *cp1, *cp2, *cp;
615 unsigned int col = 0;
621 cp1 = (unsigned char *)&col1;
622 cp2 = (unsigned char *)&col2;
623 cp = (unsigned char *)&col;
625 temp = cp1[0] + ((fac * cp2[0]) / 255);
626 cp[0] = (temp > 254) ? 255 : temp;
627 temp = cp1[1] + ((fac * cp2[1]) / 255);
628 cp[1] = (temp > 254) ? 255 : temp;
629 temp = cp1[2] + ((fac * cp2[2]) / 255);
630 cp[2] = (temp > 254) ? 255 : temp;
636 BLI_INLINE unsigned int mcol_sub(unsigned int col1, unsigned int col2, int fac)
638 unsigned char *cp1, *cp2, *cp;
640 unsigned int col = 0;
646 cp1 = (unsigned char *)&col1;
647 cp2 = (unsigned char *)&col2;
648 cp = (unsigned char *)&col;
650 temp = cp1[0] - ((fac * cp2[0]) / 255);
651 cp1[0] = (temp < 0) ? 0 : temp;
652 temp = cp1[1] - ((fac * cp2[1]) / 255);
653 cp1[1] = (temp < 0) ? 0 : temp;
654 temp = cp1[2] - ((fac * cp2[2]) / 255);
655 cp1[2] = (temp < 0) ? 0 : temp;
661 BLI_INLINE unsigned int mcol_mul(unsigned int col1, unsigned int col2, int fac)
663 unsigned char *cp1, *cp2, *cp;
665 unsigned int col = 0;
673 cp1 = (unsigned char *)&col1;
674 cp2 = (unsigned char *)&col2;
675 cp = (unsigned char *)&col;
677 /* first mul, then blend the fac */
678 cp[0] = (mfac * cp1[0] + fac * ((cp2[0] * cp1[0]) / 255)) / 255;
679 cp[1] = (mfac * cp1[1] + fac * ((cp2[1] * cp1[1]) / 255)) / 255;
680 cp[2] = (mfac * cp1[2] + fac * ((cp2[2] * cp1[2]) / 255)) / 255;
686 BLI_INLINE unsigned int mcol_lighten(unsigned int col1, unsigned int col2, int fac)
688 unsigned char *cp1, *cp2, *cp;
690 unsigned int col = 0;
695 else if (fac >= 255) {
701 cp1 = (unsigned char *)&col1;
702 cp2 = (unsigned char *)&col2;
703 cp = (unsigned char *)&col;
705 /* See if are lighter, if so mix, else don't do anything.
706 * if the paint col is darker then the original, then ignore */
707 if (rgb_to_grayscale_byte(cp1) > rgb_to_grayscale_byte(cp2)) {
711 cp[0] = (mfac * cp1[0] + fac * cp2[0]) / 255;
712 cp[1] = (mfac * cp1[1] + fac * cp2[1]) / 255;
713 cp[2] = (mfac * cp1[2] + fac * cp2[2]) / 255;
719 BLI_INLINE unsigned int mcol_darken(unsigned int col1, unsigned int col2, int fac)
721 unsigned char *cp1, *cp2, *cp;
723 unsigned int col = 0;
728 else if (fac >= 255) {
734 cp1 = (unsigned char *)&col1;
735 cp2 = (unsigned char *)&col2;
736 cp = (unsigned char *)&col;
738 /* See if were darker, if so mix, else don't do anything.
739 * if the paint col is brighter then the original, then ignore */
740 if (rgb_to_grayscale_byte(cp1) < rgb_to_grayscale_byte(cp2)) {
744 cp[0] = (mfac * cp1[0] + fac * cp2[0]) / 255;
745 cp[1] = (mfac * cp1[1] + fac * cp2[1]) / 255;
746 cp[2] = (mfac * cp1[2] + fac * cp2[2]) / 255;
751 /* wpaint has 'wpaint_blend_tool' */
752 static unsigned int vpaint_blend_tool(const int tool, const unsigned int col,
753 const unsigned int paintcol, const int alpha_i)
756 case PAINT_BLEND_MIX:
757 case PAINT_BLEND_BLUR: return mcol_blend(col, paintcol, alpha_i);
758 case PAINT_BLEND_ADD: return mcol_add(col, paintcol, alpha_i);
759 case PAINT_BLEND_SUB: return mcol_sub(col, paintcol, alpha_i);
760 case PAINT_BLEND_MUL: return mcol_mul(col, paintcol, alpha_i);
761 case PAINT_BLEND_LIGHTEN: return mcol_lighten(col, paintcol, alpha_i);
762 case PAINT_BLEND_DARKEN: return mcol_darken(col, paintcol, alpha_i);
769 /* wpaint has 'wpaint_blend' */
770 static unsigned int vpaint_blend(VPaint *vp, unsigned int col, unsigned int colorig, const
771 unsigned int paintcol, const int alpha_i,
772 /* pre scaled from [0-1] --> [0-255] */
773 const int brush_alpha_value_i)
775 Brush *brush = paint_brush(&vp->paint);
776 const int tool = brush->vertexpaint_tool;
778 col = vpaint_blend_tool(tool, col, paintcol, alpha_i);
780 /* if no spray, clip color adding with colorig & orig alpha */
781 if ((vp->flag & VP_SPRAY) == 0) {
782 unsigned int testcol, a;
785 testcol = vpaint_blend_tool(tool, colorig, paintcol, brush_alpha_value_i);
788 ct = (char *)&testcol;
789 co = (char *)&colorig;
791 for (a = 0; a < 4; a++) {
793 if (cp[a] < ct[a]) cp[a] = ct[a];
794 else if (cp[a] > co[a]) cp[a] = co[a];
797 if (cp[a] < co[a]) cp[a] = co[a];
798 else if (cp[a] > ct[a]) cp[a] = ct[a];
807 static int sample_backbuf_area(ViewContext *vc, int *indexar, int totface, int x, int y, float size)
810 int a, tot = 0, index;
812 /* brecht: disabled this because it obviously fails for
813 * brushes with size > 64, why is this here? */
814 /*if (size > 64.0) size = 64.0;*/
816 ibuf = view3d_read_backbuf(vc, x - size, y - size, x + size, y + size);
818 unsigned int *rt = ibuf->rect;
820 memset(indexar, 0, sizeof(int) * (totface + 1));
822 size = ibuf->x * ibuf->y;
826 index = WM_framebuffer_to_index(*rt);
827 if (index > 0 && index <= totface)
834 for (a = 1; a <= totface; a++) {
835 if (indexar[a]) indexar[tot++] = a;
844 /* whats _dl mean? */
845 static float calc_vp_strength_dl(VPaint *vp, ViewContext *vc, const float vert_nor[3],
846 const float mval[2], const float brush_size_pressure)
848 Brush *brush = paint_brush(&vp->paint);
850 float vertco[2], delta[2];
852 project_float_noclip(vc->ar, vert_nor, vertco);
853 sub_v2_v2v2(delta, mval, vertco);
854 dist_squared = dot_v2v2(delta, delta); /* len squared */
855 if (dist_squared > brush_size_pressure * brush_size_pressure) {
859 const float dist = sqrtf(dist_squared);
860 return BKE_brush_curve_strength_clamp(brush, dist, brush_size_pressure);
864 static float calc_vp_alpha_dl(VPaint *vp, ViewContext *vc,
865 float vpimat[][3], const float *vert_nor,
867 const float brush_size_pressure, const float brush_alpha_pressure)
869 float strength = calc_vp_strength_dl(vp, vc, vert_nor, mval, brush_size_pressure);
871 if (strength > 0.0f) {
872 float alpha = brush_alpha_pressure * strength;
874 if (vp->flag & VP_NORMALS) {
876 const float *no = vert_nor + 3;
879 dvec[2] = dot_v3v3(vpimat[2], no);
880 if (dvec[2] > 0.0f) {
881 dvec[0] = dot_v3v3(vpimat[0], no);
882 dvec[1] = dot_v3v3(vpimat[1], no);
884 alpha *= dvec[2] / len_v3(dvec);
898 BLI_INLINE float wval_blend(const float weight, const float paintval, const float alpha)
900 return (paintval * alpha) + (weight * (1.0f - alpha));
902 BLI_INLINE float wval_add(const float weight, const float paintval, const float alpha)
904 return weight + (paintval * alpha);
906 BLI_INLINE float wval_sub(const float weight, const float paintval, const float alpha)
908 return weight - (paintval * alpha);
910 BLI_INLINE float wval_mul(const float weight, const float paintval, const float alpha)
911 { /* first mul, then blend the fac */
912 return ((1.0f - alpha) + (alpha * paintval)) * weight;
914 BLI_INLINE float wval_lighten(const float weight, const float paintval, const float alpha)
916 return (weight < paintval) ? wval_blend(weight, paintval, alpha) : weight;
918 BLI_INLINE float wval_darken(const float weight, const float paintval, const float alpha)
920 return (weight > paintval) ? wval_blend(weight, paintval, alpha) : weight;
924 /* vpaint has 'vpaint_blend_tool' */
925 /* result is not clamped from [0-1] */
926 static float wpaint_blend_tool(const int tool,
929 const float paintval, const float alpha)
932 case PAINT_BLEND_MIX:
933 case PAINT_BLEND_BLUR: return wval_blend(weight, paintval, alpha);
934 case PAINT_BLEND_ADD: return wval_add(weight, paintval, alpha);
935 case PAINT_BLEND_SUB: return wval_sub(weight, paintval, alpha);
936 case PAINT_BLEND_MUL: return wval_mul(weight, paintval, alpha);
937 case PAINT_BLEND_LIGHTEN: return wval_lighten(weight, paintval, alpha);
938 case PAINT_BLEND_DARKEN: return wval_darken(weight, paintval, alpha);
945 /* vpaint has 'vpaint_blend' */
946 static float wpaint_blend(VPaint *wp, float weight, float weight_prev,
947 const float alpha, float paintval,
948 const float brush_alpha_value,
949 const short do_flip, const short do_multipaint_totsel)
951 Brush *brush = paint_brush(&wp->paint);
952 int tool = brush->vertexpaint_tool;
956 case PAINT_BLEND_MIX:
957 paintval = 1.f - paintval; break;
958 case PAINT_BLEND_ADD:
959 tool = PAINT_BLEND_SUB; break;
960 case PAINT_BLEND_SUB:
961 tool = PAINT_BLEND_ADD; break;
962 case PAINT_BLEND_LIGHTEN:
963 tool = PAINT_BLEND_DARKEN; break;
964 case PAINT_BLEND_DARKEN:
965 tool = PAINT_BLEND_LIGHTEN; break;
969 weight = wpaint_blend_tool(tool, weight, paintval, alpha);
971 /* delay clamping until the end so multi-paint can function when the active group is at the limits */
972 if (do_multipaint_totsel == FALSE) {
973 CLAMP(weight, 0.0f, 1.0f);
976 /* if no spray, clip result with orig weight & orig alpha */
977 if ((wp->flag & VP_SPRAY) == 0) {
978 if (do_multipaint_totsel == FALSE) {
979 float testw = wpaint_blend_tool(tool, weight_prev, paintval, brush_alpha_value);
981 CLAMP(testw, 0.0f, 1.0f);
982 if (testw < weight_prev) {
983 if (weight < testw) weight = testw;
984 else if (weight > weight_prev) weight = weight_prev;
987 if (weight > testw) weight = testw;
988 else if (weight < weight_prev) weight = weight_prev;
996 /* ----------------------------------------------------- */
999 /* sets wp->weight to the closest weight value to vertex */
1000 /* note: we cant sample frontbuf, weight colors are interpolated too unpredictable */
1001 static int weight_sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1005 short change = FALSE;
1007 view3d_set_viewcontext(C, &vc);
1008 me = BKE_mesh_from_object(vc.obact);
1010 if (me && me->dvert && vc.v3d && vc.rv3d) {
1013 view3d_operator_needs_opengl(C);
1015 index = view3d_sample_backbuf(&vc, event->mval[0], event->mval[1]);
1017 if (index && index <= me->totpoly) {
1018 DerivedMesh *dm = mesh_get_derived_final(vc.scene, vc.obact, CD_MASK_BAREMESH);
1020 if (dm->getVertCo == NULL) {
1021 BKE_report(op->reports, RPT_WARNING, "The modifier used does not support deformed locations");
1024 MPoly *mp = ((MPoly *)me->mpoly) + (index - 1);
1025 const int vgroup_active = vc.obact->actdef - 1;
1026 Scene *scene = vc.scene;
1027 ToolSettings *ts = vc.scene->toolsettings;
1028 Brush *brush = paint_brush(&ts->wpaint->paint);
1030 int v_idx_best = -1;
1032 float len_best = FLT_MAX;
1034 mval_f[0] = (float)event->mval[0];
1035 mval_f[1] = (float)event->mval[1];
1037 fidx = mp->totloop - 1;
1039 float co[3], sco[3], len;
1040 const int v_idx = me->mloop[mp->loopstart + fidx].v;
1041 dm->getVertCo(dm, v_idx, co);
1042 project_float_noclip(vc.ar, co, sco);
1043 len = len_squared_v2v2(mval_f, sco);
1044 if (len < len_best) {
1050 if (v_idx_best != -1) { /* should always be valid */
1051 float vgroup_weight = defvert_find_weight(&me->dvert[v_idx_best], vgroup_active);
1052 BKE_brush_weight_set(scene, brush, vgroup_weight);
1061 /* not really correct since the brush didnt change, but redraws the toolbar */
1062 WM_main_add_notifier(NC_BRUSH | NA_EDITED, NULL); /* ts->wpaint->paint.brush */
1064 return OPERATOR_FINISHED;
1067 return OPERATOR_CANCELLED;
1071 void PAINT_OT_weight_sample(wmOperatorType *ot)
1074 ot->name = "Weight Paint Sample Weight";
1075 ot->idname = "PAINT_OT_weight_sample";
1076 ot->description = "Use the mouse to sample a weight in the 3D view";
1079 ot->invoke = weight_sample_invoke;
1080 ot->poll = weight_paint_mode_poll;
1083 ot->flag = OPTYPE_UNDO;
1086 /* samples cursor location, and gives menu with vertex groups to activate */
1087 static EnumPropertyItem *weight_paint_sample_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), int *free)
1090 wmWindow *win = CTX_wm_window(C);
1091 if (win && win->eventstate) {
1095 view3d_set_viewcontext(C, &vc);
1096 me = BKE_mesh_from_object(vc.obact);
1098 if (me && me->dvert && vc.v3d && vc.rv3d) {
1101 view3d_operator_needs_opengl(C);
1103 index = view3d_sample_backbuf(&vc, win->eventstate->x - vc.ar->winrct.xmin, win->eventstate->y - vc.ar->winrct.ymin);
1105 if (index && index <= me->totpoly) {
1106 const int defbase_tot = BLI_countlist(&vc.obact->defbase);
1108 MPoly *mp = ((MPoly *)me->mpoly) + (index - 1);
1109 unsigned int fidx = mp->totloop - 1;
1110 int *groups = MEM_callocN(defbase_tot * sizeof(int), "groups");
1114 MDeformVert *dvert = me->dvert + me->mloop[mp->loopstart + fidx].v;
1115 int i = dvert->totweight;
1117 for (dw = dvert->dw; i > 0; dw++, i--) {
1118 if (dw->def_nr < defbase_tot) {
1119 groups[dw->def_nr] = TRUE;
1125 if (found == FALSE) {
1129 EnumPropertyItem *item = NULL, item_tmp = {0};
1133 for (dg = vc.obact->defbase.first; dg && i < defbase_tot; i++, dg = dg->next) {
1135 item_tmp.identifier = item_tmp.name = dg->name;
1137 RNA_enum_item_add(&item, &totitem, &item_tmp);
1141 RNA_enum_item_end(&item, &totitem);
1153 return DummyRNA_NULL_items;
1156 static int weight_sample_group_exec(bContext *C, wmOperator *op)
1158 int type = RNA_enum_get(op->ptr, "group");
1160 view3d_set_viewcontext(C, &vc);
1162 BLI_assert(type + 1 >= 0);
1163 vc.obact->actdef = type + 1;
1165 DAG_id_tag_update(&vc.obact->id, OB_RECALC_DATA);
1166 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, vc.obact);
1167 return OPERATOR_FINISHED;
1170 /* TODO, we could make this a menu into OBJECT_OT_vertex_group_set_active rather than its own operator */
1171 void PAINT_OT_weight_sample_group(wmOperatorType *ot)
1173 PropertyRNA *prop = NULL;
1176 ot->name = "Weight Paint Sample Group";
1177 ot->idname = "PAINT_OT_weight_sample_group";
1178 ot->description = "Select one of the vertex groups available under current mouse position";
1181 ot->exec = weight_sample_group_exec;
1182 ot->invoke = WM_menu_invoke;
1183 ot->poll = weight_paint_mode_poll;
1186 ot->flag = OPTYPE_UNDO;
1188 /* keyingset to use (dynamic enum) */
1189 prop = RNA_def_enum(ot->srna, "group", DummyRNA_DEFAULT_items, 0, "Keying Set", "The Keying Set to use");
1190 RNA_def_enum_funcs(prop, weight_paint_sample_enum_itemf);
1194 static void do_weight_paint_normalize_all(MDeformVert *dvert, const int defbase_tot, const char *vgroup_validmap)
1196 float sum = 0.0f, fac;
1197 unsigned int i, tot = 0;
1200 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1201 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1207 if ((tot == 0) || (sum == 1.0f)) {
1214 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1215 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1221 /* hrmf, not a factor in this case */
1224 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1225 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1232 /* same as function above except it normalizes against the active vgroup which remains unchanged
1234 * note that the active is just the group which is unchanged, it can be any,
1235 * can also be -1 to normalize all but in that case call 'do_weight_paint_normalize_all' */
1236 static void do_weight_paint_normalize_all_active(MDeformVert *dvert, const int defbase_tot, const char *vgroup_validmap,
1237 const int vgroup_active)
1239 float sum = 0.0f, fac;
1240 unsigned int i, tot = 0;
1242 float act_weight = 0.0f;
1244 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1245 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1246 if (dw->def_nr != vgroup_active) {
1251 act_weight = dw->weight;
1256 if ((tot == 0) || (sum + act_weight == 1.0f)) {
1261 fac = (1.0f / sum) * (1.0f - act_weight);
1263 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1264 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1265 if (dw->def_nr != vgroup_active) {
1268 /* paranoid but possibly with float error */
1269 CLAMP(dw->weight, 0.0f, 1.0f);
1275 /* corner case where we need to scale all weights evenly because they're all zero */
1277 /* hrmf, not a factor in this case */
1278 fac = (1.0f - act_weight) / tot;
1280 /* paranoid but possibly with float error */
1281 CLAMP(fac, 0.0f, 1.0f);
1283 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1284 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1285 if (dw->def_nr != vgroup_active) {
1294 * See if the current deform vertex has a locked group
1296 static char has_locked_group(MDeformVert *dvert, const int defbase_tot,
1297 const char *bone_groups, const char *lock_flags)
1302 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1303 if (dw->def_nr < defbase_tot) {
1304 if (bone_groups[dw->def_nr] && lock_flags[dw->def_nr] && dw->weight > 0.0f) {
1312 * gen_lck_flags gets the status of "flag" for each bDeformGroup
1313 * in ob->defbase and returns an array containing them
1315 static char *gen_lock_flags(Object *ob, int defbase_tot)
1317 char is_locked = FALSE;
1319 //int defbase_tot = BLI_countlist(&ob->defbase);
1320 char *lock_flags = MEM_mallocN(defbase_tot * sizeof(char), "defflags");
1321 bDeformGroup *defgroup;
1323 for (i = 0, defgroup = ob->defbase.first; i < defbase_tot && defgroup; defgroup = defgroup->next, i++) {
1324 lock_flags[i] = ((defgroup->flag & DG_LOCK_WEIGHT) != 0);
1325 is_locked |= lock_flags[i];
1331 MEM_freeN(lock_flags);
1335 static int has_locked_group_selected(int defbase_tot, const char *defbase_sel, const char *lock_flags)
1338 for (i = 0; i < defbase_tot; i++) {
1339 if (defbase_sel[i] && lock_flags[i]) {
1348 static int has_unselected_unlocked_bone_group(int defbase_tot, char *defbase_sel, int selected, char *lock_flags, char *vgroup_validmap)
1351 if (defbase_tot == selected) {
1354 for (i = 0; i < defbase_tot; i++) {
1355 if (vgroup_validmap[i] && !defbase_sel[i] && !lock_flags[i]) {
1364 static void multipaint_selection(MDeformVert *dvert, const int defbase_tot, float change, const char *defbase_sel)
1369 /* make sure they are all at most 1 after the change */
1370 for (i = 0; i < defbase_tot; i++) {
1371 if (defbase_sel[i]) {
1372 dw = defvert_find_index(dvert, i);
1373 if (dw && dw->weight) {
1374 val = dw->weight * change;
1376 /* TODO: when the change is reduced, you need to recheck
1377 * the earlier values to make sure they are not 0
1378 * (precision error) */
1379 change = 1.0f / dw->weight;
1381 /* the value should never reach zero while multi-painting if it
1382 * was nonzero beforehand */
1389 /* apply the valid change */
1390 for (i = 0; i < defbase_tot; i++) {
1391 if (defbase_sel[i]) {
1392 dw = defvert_find_index(dvert, i);
1393 if (dw && dw->weight) {
1394 dw->weight = dw->weight * change;
1400 /* move all change onto valid, unchanged groups. If there is change left over,
1402 * assumes there are valid groups to shift weight onto */
1403 static float redistribute_change(MDeformVert *ndv, const int defbase_tot,
1404 char *change_status, const char change_me, int changeto,
1405 float totchange, float total_valid,
1406 char do_auto_normalize)
1414 /* assume there is no change until you see one */
1416 /* change each group by the same amount each time */
1417 change = totchange / total_valid;
1418 for (i = 0; i < ndv->totweight && total_valid && totchange; i++) {
1419 ndw = (ndv->dw + i);
1421 /* ignore anything outside the value range */
1422 if (ndw->def_nr < defbase_tot) {
1424 /* change only the groups with a valid status */
1425 if (change_status[ndw->def_nr] == change_me) {
1426 oldval = ndw->weight;
1427 /* if auto normalize is active, don't worry about upper bounds */
1428 if (do_auto_normalize == FALSE && ndw->weight + change > 1) {
1429 totchange -= 1.0f - ndw->weight;
1431 /* stop the changes to this group */
1432 change_status[ndw->def_nr] = changeto;
1435 else if (ndw->weight + change < 0) { /* check the lower bound */
1436 totchange -= ndw->weight;
1438 change_status[ndw->def_nr] = changeto;
1441 else { /* a perfectly valid change occurred to ndw->weight */
1442 totchange -= change;
1443 ndw->weight += change;
1445 /* see if there was a change */
1446 if (oldval != ndw->weight) {
1452 /* don't go again if there was no change, if there is no valid group,
1453 * or there is no change left */
1454 } while (was_change && total_valid && totchange);
1458 static float get_mp_change(MDeformVert *odv, const int defbase_tot, const char *defbase_sel, float brush_change);
1459 /* observe the changes made to the weights of groups.
1460 * make sure all locked groups on the vertex have the same deformation
1461 * by moving the changes made to groups onto other unlocked groups */
1462 static void enforce_locks(MDeformVert *odv, MDeformVert *ndv,
1463 const int defbase_tot, const char *defbase_sel,
1464 const char *lock_flags, const char *vgroup_validmap,
1465 char do_auto_normalize, char do_multipaint)
1467 float totchange = 0.0f;
1468 float totchange_allowed = 0.0f;
1471 int total_valid = 0;
1472 int total_changed = 0;
1477 float changed_sum = 0.0f;
1479 char *change_status;
1481 if (!lock_flags || !has_locked_group(ndv, defbase_tot, vgroup_validmap, lock_flags)) {
1484 /* record if a group was changed, unlocked and not changed, or locked */
1485 change_status = MEM_callocN(sizeof(char) * defbase_tot, "unlocked_unchanged");
1487 for (i = 0; i < defbase_tot; i++) {
1488 ndw = defvert_find_index(ndv, i);
1489 odw = defvert_find_index(odv, i);
1490 /* the weights are zero, so we can assume a lot */
1492 if (!lock_flags[i] && vgroup_validmap[i]) {
1493 defvert_verify_index(odv, i);
1494 defvert_verify_index(ndv, i);
1496 change_status[i] = 1; /* can be altered while redistributing */
1500 /* locked groups should not be changed */
1501 if (lock_flags[i]) {
1502 ndw->weight = odw->weight;
1504 else if (ndw->weight != odw->weight) { /* changed groups are handled here */
1505 totchange += ndw->weight - odw->weight;
1506 changed_sum += ndw->weight;
1507 change_status[i] = 2; /* was altered already */
1509 } /* unchanged, unlocked bone groups are handled here */
1510 else if (vgroup_validmap[i]) {
1511 totchange_allowed += ndw->weight;
1513 change_status[i] = 1; /* can be altered while redistributing */
1516 /* if there was any change, redistribute it */
1517 if (total_changed) {
1518 /* auto normalize will allow weights to temporarily go above 1 in redistribution */
1519 if (vgroup_validmap && total_changed < 0 && total_valid) {
1520 totchange_allowed = total_valid;
1522 /* the way you modify the unlocked + unchanged groups is different depending
1523 * on whether or not you are painting the weight(s) up or down */
1524 if (totchange < 0) {
1525 totchange_allowed = total_valid - totchange_allowed;
1528 totchange_allowed *= -1;
1530 /* there needs to be change allowed, or you should not bother */
1531 if (totchange_allowed) {
1533 if (fabsf(totchange_allowed) < fabsf(totchange)) {
1534 /* this amount goes back onto the changed, unlocked weights */
1535 left_over = fabsf(fabsf(totchange) - fabsf(totchange_allowed));
1536 if (totchange > 0) {
1541 /* all of the change will be permitted */
1542 totchange_allowed = -totchange;
1544 /* move the weight evenly between the allowed groups, move excess back onto the used groups based on the change */
1545 totchange_allowed = redistribute_change(ndv, defbase_tot, change_status, 1, -1, totchange_allowed, total_valid, do_auto_normalize);
1546 left_over += totchange_allowed;
1548 /* more than one nonzero weights were changed with the same ratio with multipaint, so keep them changed that way! */
1549 if (total_changed > 1 && do_multipaint) {
1550 float undo_change = get_mp_change(ndv, defbase_tot, defbase_sel, left_over);
1551 multipaint_selection(ndv, defbase_tot, undo_change, defbase_sel);
1553 /* or designatedw is still -1 put weight back as evenly as possible */
1555 redistribute_change(ndv, defbase_tot, change_status, 2, -2, left_over, total_changed, do_auto_normalize);
1560 /* reset the weights */
1562 MDeformWeight *dw_old = odv->dw;
1563 MDeformWeight *dw_new = ndv->dw;
1565 for (i = odv->totweight; i != 0; i--, dw_old++, dw_new++) {
1566 dw_new->weight = dw_old->weight;
1571 MEM_freeN(change_status);
1574 /* multi-paint's initial, potential change is computed here based on the user's stroke */
1575 static float get_mp_change(MDeformVert *odv, const int defbase_tot, const char *defbase_sel, float brush_change)
1577 float selwsum = 0.0f;
1579 MDeformWeight *dw = odv->dw;
1581 for (i = odv->totweight; i != 0; i--, dw++) {
1582 if (dw->def_nr < defbase_tot) {
1583 if (defbase_sel[dw->def_nr]) {
1584 selwsum += dw->weight;
1588 if (selwsum && selwsum + brush_change > 0) {
1589 return (selwsum + brush_change) / selwsum;
1594 /* change the weights back to the wv's weights
1595 * it assumes you already have the correct pointer index */
1596 static void defvert_reset_to_prev(MDeformVert *dv_prev, MDeformVert *dv)
1598 MDeformWeight *dw = dv->dw;
1599 MDeformWeight *dw_prev;
1601 for (i = dv->totweight; i != 0; i--, dw++) {
1602 dw_prev = defvert_find_index(dv_prev, dw->def_nr);
1603 /* if there was no w when there is a d, then the old weight was 0 */
1604 dw->weight = dw_prev ? dw_prev->weight : 0.0f;
1608 static void clamp_weights(MDeformVert *dvert)
1610 MDeformWeight *dw = dvert->dw;
1612 for (i = dvert->totweight; i != 0; i--, dw++) {
1613 CLAMP(dw->weight, 0.0f, 1.0f);
1617 /* struct to avoid passing many args each call to do_weight_paint_vertex()
1618 * this _could_ be made a part of the operators 'WPaintData' struct, or at
1619 * least a member, but for now keep its own struct, initialized on every
1620 * paint stroke update - campbell */
1621 typedef struct WeightPaintInfo {
1625 /* both must add up to 'defbase_tot' */
1626 int defbase_tot_sel;
1627 int defbase_tot_unsel;
1629 int vgroup_active; /* (ob->actdef - 1) */
1630 int vgroup_mirror; /* mirror group or -1 */
1632 const char *lock_flags; /* boolean array for locked bones,
1633 * length of defbase_tot */
1634 const char *defbase_sel; /* boolean array for selected bones,
1635 * length of defbase_tot, cant be const because of how its passed */
1637 const char *vgroup_validmap; /* same as WeightPaintData.vgroup_validmap,
1638 * only added here for convenience */
1642 char do_auto_normalize;
1644 float brush_alpha_value; /* result of BKE_brush_alpha_get() */
1647 /* fresh start to make multi-paint and locking modular */
1648 /* returns TRUE if it thinks you need to reset the weights due to
1649 * normalizing while multi-painting
1651 * note: this assumes dw->def_nr range has been checked by the caller
1653 static int apply_mp_locks_normalize(Mesh *me, const WeightPaintInfo *wpi,
1654 const unsigned int index,
1655 MDeformWeight *dw, MDeformWeight *tdw,
1656 float change, float oldChange,
1657 float oldw, float neww)
1659 MDeformVert *dv = &me->dvert[index];
1660 MDeformVert dv_test = {NULL};
1662 dv_test.dw = MEM_dupallocN(dv->dw);
1663 dv_test.flag = dv->flag;
1664 dv_test.totweight = dv->totweight;
1665 /* do not multi-paint if a locked group is selected or the active group is locked
1666 * !lock_flags[dw->def_nr] helps if nothing is selected, but active group is locked */
1667 if ( (wpi->lock_flags == NULL) ||
1668 ((wpi->lock_flags[dw->def_nr] == FALSE) && /* def_nr range has to be checked for by caller */
1669 has_locked_group_selected(wpi->defbase_tot, wpi->defbase_sel, wpi->lock_flags) == FALSE))
1671 if (wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1672 if (change && change != 1) {
1673 multipaint_selection(dv, wpi->defbase_tot, change, wpi->defbase_sel);
1676 else { /* this lets users paint normally, but don't let them paint locked groups */
1682 enforce_locks(&dv_test, dv, wpi->defbase_tot, wpi->defbase_sel, wpi->lock_flags, wpi->vgroup_validmap, wpi->do_auto_normalize, wpi->do_multipaint);
1684 if (wpi->do_auto_normalize) {
1685 /* XXX - should we pass the active group? - currently '-1' */
1686 do_weight_paint_normalize_all(dv, wpi->defbase_tot, wpi->vgroup_validmap);
1689 if (oldChange && wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1690 if (tdw->weight != oldw) {
1692 if (tdw->weight <= oldw) {
1693 MEM_freeN(dv_test.dw);
1698 if (tdw->weight >= oldw) {
1699 MEM_freeN(dv_test.dw);
1705 MEM_freeN(dv_test.dw);
1709 /* within the current dvert index, get the dw that is selected and has a weight
1710 * above 0, this helps multi-paint */
1711 static int get_first_selected_nonzero_weight(MDeformVert *dvert, const int defbase_tot, const char *defbase_sel)
1714 MDeformWeight *dw = dvert->dw;
1715 for (i = 0; i < dvert->totweight; i++, dw++) {
1716 if (dw->def_nr < defbase_tot) {
1717 if (defbase_sel[dw->def_nr] && dw->weight > 0.0f) {
1726 static char *wpaint_make_validmap(Object *ob);
1729 static void do_weight_paint_vertex(
1730 /* vars which remain the same for every vert */
1731 VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1732 /* vars which change on each stroke */
1733 const unsigned int index, float alpha, float paintweight
1736 Mesh *me = ob->data;
1737 MDeformVert *dv = &me->dvert[index];
1739 MDeformWeight *dw, *dw_prev;
1745 MDeformVert *dv_mirr;
1746 MDeformWeight *dw_mirr;
1748 const short do_multipaint_totsel = (wpi->do_multipaint && wpi->defbase_tot_sel > 1);
1750 if (wp->flag & VP_ONLYVGROUP) {
1751 dw = defvert_find_index(dv, wpi->vgroup_active);
1752 dw_prev = defvert_find_index(wp->wpaint_prev + index, wpi->vgroup_active);
1755 dw = defvert_verify_index(dv, wpi->vgroup_active);
1756 dw_prev = defvert_verify_index(wp->wpaint_prev + index, wpi->vgroup_active);
1759 if (dw == NULL || dw_prev == NULL) {
1764 /* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
1765 if (me->editflag & ME_EDIT_MIRROR_X) {
1766 index_mirr = mesh_get_x_mirror_vert(ob, index);
1767 vgroup_mirr = (wpi->vgroup_mirror != -1) ? wpi->vgroup_mirror : wpi->vgroup_active;
1769 /* another possible error - mirror group _and_ active group are the same (which is fine),
1770 * but we also are painting onto a center vertex - this would paint the same weight twice */
1771 if (index_mirr == index && vgroup_mirr == wpi->vgroup_active) {
1772 index_mirr = vgroup_mirr = -1;
1776 index_mirr = vgroup_mirr = -1;
1780 /* get the mirror def vars */
1781 if (index_mirr != -1) {
1782 dv_mirr = &me->dvert[index_mirr];
1783 if (wp->flag & VP_ONLYVGROUP) {
1784 dw_mirr = defvert_find_index(dv_mirr, vgroup_mirr);
1786 if (dw_mirr == NULL) {
1787 index_mirr = vgroup_mirr = -1;
1792 if (index != index_mirr) {
1793 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1796 /* dv and dv_mirr are the same */
1797 int totweight_prev = dv_mirr->totweight;
1798 int dw_offset = (int)(dw - dv_mirr->dw);
1799 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1801 /* if we added another, get our old one back */
1802 if (totweight_prev != dv_mirr->totweight) {
1803 dw = &dv_mirr->dw[dw_offset];
1814 /* TODO: De-duplicate the simple weight paint - jason */
1815 /* ... or not, since its <10 SLOC - campbell */
1817 /* If there are no locks or multipaint,
1818 * then there is no need to run the more complicated checks */
1819 if ( (do_multipaint_totsel == FALSE) &&
1820 (wpi->lock_flags == NULL || has_locked_group(dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags) == FALSE))
1822 dw->weight = wpaint_blend(wp, dw->weight, dw_prev->weight, alpha, paintweight,
1823 wpi->brush_alpha_value, wpi->do_flip, FALSE);
1825 /* WATCH IT: take care of the ordering of applying mirror -> normalize,
1826 * can give wrong results [#26193], least confusing if normalize is done last */
1829 if (index_mirr != -1) {
1830 /* copy, not paint again */
1831 dw_mirr->weight = dw->weight;
1834 /* apply normalize */
1835 if (wpi->do_auto_normalize) {
1836 /* note on normalize - this used to be applied after painting and normalize all weights,
1837 * in some ways this is good because there is feedback where the more weights involved would
1838 * 'resist' so you couldn't instantly zero out other weights by painting 1.0 on the active.
1840 * However this gave a problem since applying mirror, then normalize both verts
1841 * the resulting weight wont match on both sides.
1843 * If this 'resisting', slower normalize is nicer, we could call
1844 * do_weight_paint_normalize_all() and only use...
1845 * do_weight_paint_normalize_all_active() when normalizing the mirror vertex.
1848 do_weight_paint_normalize_all_active(dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->vgroup_active);
1850 if (index_mirr != -1) {
1851 /* only normalize if this is not a center vertex, else we get a conflict, normalizing twice */
1852 if (index != index_mirr) {
1853 do_weight_paint_normalize_all_active(dv_mirr, wpi->defbase_tot, wpi->vgroup_validmap, vgroup_mirr);
1856 /* this case accounts for...
1857 * - painting onto a center vertex of a mesh
1858 * - x mirror is enabled
1859 * - auto normalize is enabled
1860 * - the group you are painting onto has a L / R version
1862 * We want L/R vgroups to have the same weight but this cant be if both are over 0.5,
1863 * We _could_ have special check for that, but this would need its own normalize function which
1864 * holds 2 groups from changing at once.
1866 * So! just balance out the 2 weights, it keeps them equal and everything normalized.
1868 * While it wont hit the desired weight immediately as the user waggles their mouse,
1869 * constant painting and re-normalizing will get there. this is also just simpler logic.
1871 dw_mirr->weight = dw->weight = (dw_mirr->weight + dw->weight) * 0.5f;
1877 /* use locks and/or multipaint */
1880 /* float testw = 0; */ /* UNUSED */
1881 float observedChange = 0;
1883 float oldChange = 0;
1885 MDeformWeight *tdw = NULL, *tdw_prev;
1886 MDeformVert dv_copy = {NULL};
1889 neww = wpaint_blend(wp, dw->weight, dw_prev->weight, alpha, paintweight,
1890 wpi->brush_alpha_value, wpi->do_flip, do_multipaint_totsel);
1892 /* setup multi-paint */
1893 observedChange = neww - oldw;
1894 if (do_multipaint_totsel && observedChange) {
1895 dv_copy.dw = MEM_dupallocN(dv->dw);
1896 dv_copy.flag = dv->flag;
1897 dv_copy.totweight = dv->totweight;
1900 change = get_mp_change(&wp->wpaint_prev[index], wpi->defbase_tot, wpi->defbase_sel, observedChange);
1903 i = get_first_selected_nonzero_weight(dv, wpi->defbase_tot, wpi->defbase_sel);
1906 tdw_prev = defvert_verify_index(&wp->wpaint_prev[index], tdw->def_nr);
1912 if (change && tdw_prev->weight && tdw_prev->weight * change) {
1913 if (tdw->weight != tdw_prev->weight) {
1914 oldChange = tdw->weight / tdw_prev->weight;
1915 /* testw = tdw_prev->weight * change; */ /* UNUSED */
1916 if (observedChange > 0) {
1917 if (change > oldChange) {
1918 /* reset the weights and use the new change */
1919 defvert_reset_to_prev(wp->wpaint_prev + index, dv);
1922 /* the old change was more significant, so set
1923 * the change to 0 so that it will not do another multi-paint */
1928 if (change < oldChange) {
1929 defvert_reset_to_prev(wp->wpaint_prev + index, dv);
1943 if (apply_mp_locks_normalize(me, wpi, index, dw, tdw, change, oldChange, oldw, neww)) {
1944 defvert_reset_to_prev(&dv_copy, dv);
1949 MEM_freeN(dv_copy.dw);
1952 /* dv may have been altered greatly */
1953 dw = defvert_find_index(dv, vgroup);
1955 dw = NULL; /* UNUSED after assignment, set to NULL to ensure we don't
1956 * use again, we thats needed un-ifdef the line above */
1957 (void)dw; /* quiet warnigns */
1960 /* x mirror painting */
1961 if (index_mirr != -1) {
1962 /* copy, not paint again */
1964 /* dw_mirr->weight = dw->weight; */ /* TODO, explain the logic in not assigning weight! - campbell */
1965 apply_mp_locks_normalize(me, wpi, index_mirr, dw_mirr, tdw, change, oldChange, oldw, neww);
1971 /* *************** set wpaint operator ****************** */
1973 static int set_wpaint(bContext *C, wmOperator *UNUSED(op)) /* toggle */
1975 Object *ob = CTX_data_active_object(C);
1976 Scene *scene = CTX_data_scene(C);
1977 VPaint *wp = scene->toolsettings->wpaint;
1980 me = BKE_mesh_from_object(ob);
1981 if (ob->id.lib || me == NULL) return OPERATOR_PASS_THROUGH;
1983 if (ob->mode & OB_MODE_WEIGHT_PAINT) ob->mode &= ~OB_MODE_WEIGHT_PAINT;
1984 else ob->mode |= OB_MODE_WEIGHT_PAINT;
1987 /* Weightpaint works by overriding colors in mesh,
1988 * so need to make sure we recalc on enter and
1989 * exit (exit needs doing regardless because we
1992 DAG_id_tag_update(&me->id, 0);
1994 if (ob->mode & OB_MODE_WEIGHT_PAINT) {
1998 wp = scene->toolsettings->wpaint = new_vpaint(1);
2000 BKE_paint_init(&wp->paint, PAINT_CURSOR_WEIGHT_PAINT);
2001 paint_cursor_start(C, weight_paint_poll);
2003 mesh_octree_table(ob, NULL, NULL, 's');
2005 /* verify if active weight group is also active bone */
2006 par = modifiers_isDeformedByArmature(ob);
2007 if (par && (par->mode & OB_MODE_POSE)) {
2008 bArmature *arm = par->data;
2011 ED_vgroup_select_by_name(ob, arm->act_bone->name);
2015 mesh_octree_table(NULL, NULL, NULL, 'e');
2016 mesh_mirrtopo_table(NULL, 'e');
2019 WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2021 return OPERATOR_FINISHED;
2024 /* for switching to/from mode */
2025 static int paint_poll_test(bContext *C)
2027 Object *ob = CTX_data_active_object(C);
2028 if (CTX_data_edit_object(C))
2030 if (CTX_data_active_object(C) == NULL)
2032 if (!ob->data || ((ID *)ob->data)->lib)
2037 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
2041 ot->name = "Weight Paint Mode";
2042 ot->idname = "PAINT_OT_weight_paint_toggle";
2043 ot->description = "Toggle weight paint mode in 3D view";
2046 ot->exec = set_wpaint;
2047 ot->poll = paint_poll_test;
2050 ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2054 /* ************ weight paint operator ********** */
2061 float *vertexcosnos;
2064 /* variables for auto normalize */
2065 const char *vgroup_validmap; /* stores if vgroups tie to deforming bones or not */
2066 const char *lock_flags;
2070 static char *wpaint_make_validmap(Object *ob)
2074 char *vgroup_validmap;
2078 if (ob->defbase.first == NULL) {
2082 gh = BLI_ghash_str_new("wpaint_make_validmap gh");
2084 /* add all names to a hash table */
2085 for (dg = ob->defbase.first; dg; dg = dg->next) {
2086 BLI_ghash_insert(gh, dg->name, NULL);
2089 /* now loop through the armature modifiers and identify deform bones */
2090 for (md = ob->modifiers.first; md; md = !md->next && step1 ? (step1 = 0), modifiers_getVirtualModifierList(ob) : md->next) {
2091 if (!(md->mode & (eModifierMode_Realtime | eModifierMode_Virtual)))
2094 if (md->type == eModifierType_Armature) {
2095 ArmatureModifierData *amd = (ArmatureModifierData *) md;
2097 if (amd->object && amd->object->pose) {
2098 bPose *pose = amd->object->pose;
2101 for (chan = pose->chanbase.first; chan; chan = chan->next) {
2102 if (chan->bone->flag & BONE_NO_DEFORM)
2105 if (BLI_ghash_remove(gh, chan->name, NULL, NULL)) {
2106 BLI_ghash_insert(gh, chan->name, SET_INT_IN_POINTER(1));
2113 vgroup_validmap = MEM_mallocN(BLI_ghash_size(gh), "wpaint valid map");
2115 /* add all names to a hash table */
2116 for (dg = ob->defbase.first, i = 0; dg; dg = dg->next, i++) {
2117 vgroup_validmap[i] = (BLI_ghash_lookup(gh, dg->name) != NULL);
2120 BLI_assert(i == BLI_ghash_size(gh));
2122 BLI_ghash_free(gh, NULL, NULL);
2124 return vgroup_validmap;
2127 static int wpaint_stroke_test_start(bContext *C, wmOperator *op, const float UNUSED(mouse[2]))
2129 Scene *scene = CTX_data_scene(C);
2130 struct PaintStroke *stroke = op->customdata;
2131 ToolSettings *ts = scene->toolsettings;
2132 VPaint *wp = ts->wpaint;
2133 Object *ob = CTX_data_active_object(C);
2134 struct WPaintData *wpd;
2138 float mat[4][4], imat[4][4];
2140 if (scene->obedit) {
2144 me = BKE_mesh_from_object(ob);
2145 if (me == NULL || me->totpoly == 0) return OPERATOR_PASS_THROUGH;
2147 /* if nothing was added yet, we make dverts and a vertex deform group */
2149 ED_vgroup_data_create(&me->id);
2150 WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
2153 /* this happens on a Bone select, when no vgroup existed yet */
2154 if (ob->actdef <= 0) {
2156 if ((modob = modifiers_isDeformedByArmature(ob))) {
2157 Bone *actbone = ((bArmature *)modob->data)->act_bone;
2159 bPoseChannel *pchan = BKE_pose_channel_find_name(modob->pose, actbone->name);
2162 bDeformGroup *dg = defgroup_find_name(ob, pchan->name);
2164 dg = ED_vgroup_add_name(ob, pchan->name); /* sets actdef */
2167 int actdef = 1 + BLI_findindex(&ob->defbase, dg);
2168 BLI_assert(actdef >= 0);
2169 ob->actdef = actdef;
2175 if (ob->defbase.first == NULL) {
2179 /* ensure we don't try paint onto an invalid group */
2180 if (ob->actdef <= 0) {
2181 BKE_report(op->reports, RPT_WARNING, "No active vertex group for painting, aborting");
2185 /* check if we are attempting to paint onto a locked vertex group,
2186 * and other options disallow it from doing anything useful */
2187 dg = BLI_findlink(&ob->defbase, (ob->actdef - 1));
2188 if (dg->flag & DG_LOCK_WEIGHT) {
2189 BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
2193 /* ALLOCATIONS! no return after this line */
2194 /* make mode data storage */
2195 wpd = MEM_callocN(sizeof(struct WPaintData), "WPaintData");
2196 paint_stroke_set_mode_data(stroke, wpd);
2197 view3d_set_viewcontext(C, &wpd->vc);
2199 wpd->vgroup_active = ob->actdef - 1;
2200 wpd->vgroup_mirror = -1;
2202 /* set up auto-normalize, and generate map for detecting which
2203 * vgroups affect deform bones */
2204 wpd->defbase_tot = BLI_countlist(&ob->defbase);
2205 wpd->lock_flags = gen_lock_flags(ob, wpd->defbase_tot);
2206 if (ts->auto_normalize || ts->multipaint || wpd->lock_flags) {
2207 wpd->vgroup_validmap = wpaint_make_validmap(ob);
2210 /* painting on subsurfs should give correct points too, this returns me->totvert amount */
2211 wpd->vertexcosnos = mesh_get_mapped_verts_nors(scene, ob);
2212 wpd->indexar = get_indexarray(me);
2213 copy_wpaint_prev(wp, me->dvert, me->totvert);
2215 /* imat for normals */
2216 mult_m4_m4m4(mat, wpd->vc.rv3d->viewmat, ob->obmat);
2217 invert_m4_m4(imat, mat);
2218 copy_m3_m4(wpd->wpimat, imat);
2220 /* if mirror painting, find the other group */
2221 if (me->editflag & ME_EDIT_MIRROR_X) {
2222 wpd->vgroup_mirror = wpaint_mirror_vgroup_ensure(ob, wpd->vgroup_active);
2228 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2230 Scene *scene = CTX_data_scene(C);
2231 ToolSettings *ts = CTX_data_tool_settings(C);
2232 VPaint *wp = ts->wpaint;
2233 Brush *brush = paint_brush(&wp->paint);
2234 struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2242 unsigned int index, totindex;
2248 const float pressure = RNA_float_get(itemptr, "pressure");
2249 const float brush_size_pressure = BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2250 const float brush_alpha_value = BKE_brush_alpha_get(scene, brush);
2251 const float brush_alpha_pressure = brush_alpha_value * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2253 /* intentionally don't initialize as NULL, make sure we initialize all members below */
2254 WeightPaintInfo wpi;
2256 /* cannot paint if there is no stroke data */
2258 /* XXX: force a redraw here, since even though we can't paint,
2259 * at least view won't freeze until stroke ends */
2260 ED_region_tag_redraw(CTX_wm_region(C));
2267 indexar = wpd->indexar;
2269 view3d_operator_needs_opengl(C);
2271 /* load projection matrix */
2272 mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2274 RNA_float_get_array(itemptr, "mouse", mval);
2275 mval[0] -= vc->ar->winrct.xmin;
2276 mval[1] -= vc->ar->winrct.ymin;
2280 /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2281 wpi.defbase_tot = wpd->defbase_tot;
2282 defbase_sel = MEM_mallocN(wpi.defbase_tot * sizeof(char), "wpi.defbase_sel");
2283 wpi.defbase_tot_sel = get_selected_defgroups(ob, defbase_sel, wpi.defbase_tot);
2284 wpi.defbase_sel = defbase_sel; /* so we can stay const */
2285 if (wpi.defbase_tot_sel == 0 && ob->actdef > 0) wpi.defbase_tot_sel = 1;
2287 wpi.defbase_tot_unsel = wpi.defbase_tot - wpi.defbase_tot_sel;
2288 wpi.vgroup_active = wpd->vgroup_active;
2289 wpi.vgroup_mirror = wpd->vgroup_mirror;
2290 wpi.lock_flags = wpd->lock_flags;
2291 wpi.vgroup_validmap = wpd->vgroup_validmap;
2292 wpi.do_flip = RNA_boolean_get(itemptr, "pen_flip");
2293 wpi.do_multipaint = (ts->multipaint != 0);
2294 wpi.do_auto_normalize = ((ts->auto_normalize != 0) && (wpi.vgroup_validmap != NULL));
2295 wpi.brush_alpha_value = brush_alpha_value;
2296 /* *** done setting up WeightPaintInfo *** */
2300 swap_m4m4(wpd->vc.rv3d->persmat, mat);
2302 use_vert_sel = (me->editflag & ME_EDIT_VERT_SEL) != 0;
2304 /* which faces are involved */
2305 if (wp->flag & VP_AREA) {
2306 /* Ugly hack, to avoid drawing vertex index when getting the face index buffer - campbell */
2307 me->editflag &= ~ME_EDIT_VERT_SEL;
2308 totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2309 me->editflag |= use_vert_sel ? ME_EDIT_VERT_SEL : 0;
2312 indexar[0] = view3d_sample_backbuf(vc, mval[0], mval[1]);
2313 if (indexar[0]) totindex = 1;
2317 if (wp->flag & VP_COLINDEX) {
2318 for (index = 0; index < totindex; index++) {
2319 if (indexar[index] && indexar[index] <= me->totpoly) {
2320 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2322 if (mpoly->mat_nr != ob->actcol - 1) {
2329 if ((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2330 for (index = 0; index < totindex; index++) {
2331 if (indexar[index] && indexar[index] <= me->totpoly) {
2332 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2334 if ((mpoly->flag & ME_FACE_SEL) == 0) {
2341 /* make sure each vertex gets treated only once */
2342 /* and calculate filter weight */
2344 if (brush->vertexpaint_tool == PAINT_BLEND_BLUR)
2347 paintweight = BKE_brush_weight_get(scene, brush);
2349 for (index = 0; index < totindex; index++) {
2350 if (indexar[index] && indexar[index] <= me->totpoly) {
2351 MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2352 MLoop *ml = me->mloop + mpoly->loopstart;
2356 for (i = 0; i < mpoly->totloop; i++, ml++) {
2357 me->dvert[ml->v].flag = (me->mvert[ml->v].flag & SELECT);
2361 for (i = 0; i < mpoly->totloop; i++, ml++) {
2362 me->dvert[ml->v].flag = 1;
2366 if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2367 MDeformWeight *dw, *(*dw_func)(MDeformVert *, const int);
2369 if (wp->flag & VP_ONLYVGROUP)
2370 dw_func = (MDeformWeight *(*)(MDeformVert *, const int))defvert_find_index;
2372 dw_func = defvert_verify_index;
2374 ml = me->mloop + mpoly->loopstart;
2375 for (i = 0; i < mpoly->totloop; i++, ml++) {
2376 unsigned int vidx = ml->v;
2377 const float fac = calc_vp_strength_dl(wp, vc, wpd->vertexcosnos + 6 * vidx, mval, brush_size_pressure);
2379 dw = dw_func(&me->dvert[vidx], wpi.vgroup_active);
2380 paintweight += dw ? (dw->weight * fac) : 0.0f;
2388 if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2389 paintweight /= totw;
2392 for (index = 0; index < totindex; index++) {
2394 if (indexar[index] && indexar[index] <= me->totpoly) {
2395 MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2396 MLoop *ml = me->mloop + mpoly->loopstart;
2399 for (i = 0; i < mpoly->totloop; i++, ml++) {
2400 unsigned int vidx = ml->v;
2402 if (me->dvert[vidx].flag) {
2403 alpha = calc_vp_alpha_dl(wp, vc, wpd->wpimat, wpd->vertexcosnos + 6 * vidx,
2404 mval, brush_size_pressure, brush_alpha_pressure);
2406 do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight);
2408 me->dvert[vidx].flag = 0;
2415 /* *** free wpi members */
2416 MEM_freeN((void *)wpi.defbase_sel);
2417 /* *** don't freeing wpi members */
2420 swap_m4m4(vc->rv3d->persmat, mat);
2422 DAG_id_tag_update(ob->data, 0);
2423 ED_region_tag_redraw(vc->ar);
2426 static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2428 ToolSettings *ts = CTX_data_tool_settings(C);
2429 Object *ob = CTX_data_active_object(C);
2430 struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2433 if (wpd->vertexcosnos)
2434 MEM_freeN(wpd->vertexcosnos);
2435 MEM_freeN(wpd->indexar);
2437 if (wpd->vgroup_validmap)
2438 MEM_freeN((void *)wpd->vgroup_validmap);
2439 if (wpd->lock_flags)
2440 MEM_freeN((void *)wpd->lock_flags);
2445 /* frees prev buffer */
2446 copy_wpaint_prev(ts->wpaint, NULL, 0);
2448 /* and particles too */
2449 if (ob->particlesystem.first) {
2450 ParticleSystem *psys;
2453 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2454 for (i = 0; i < PSYS_TOT_VG; i++) {
2455 if (psys->vgroup[i] == ob->actdef) {
2456 psys->recalc |= PSYS_RECALC_RESET;
2463 DAG_id_tag_update(ob->data, 0);
2465 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2469 static int wpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2472 op->customdata = paint_stroke_new(C, NULL, wpaint_stroke_test_start,
2473 wpaint_stroke_update_step,
2474 wpaint_stroke_done, event->type);
2476 /* add modal handler */
2477 WM_event_add_modal_handler(C, op);
2479 op->type->modal(C, op, event);
2481 return OPERATOR_RUNNING_MODAL;
2484 static int wpaint_cancel(bContext *C, wmOperator *op)
2486 paint_stroke_cancel(C, op);
2488 return OPERATOR_CANCELLED;
2491 void PAINT_OT_weight_paint(wmOperatorType *ot)
2495 ot->name = "Weight Paint";
2496 ot->idname = "PAINT_OT_weight_paint";
2497 ot->description = "Paint a stroke in the current vertex group's weights";
2500 ot->invoke = wpaint_invoke;
2501 ot->modal = paint_stroke_modal;
2502 /* ot->exec = vpaint_exec; <-- needs stroke property */
2503 ot->poll = weight_paint_poll;
2504 ot->cancel = wpaint_cancel;
2507 ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
2509 RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2512 static int weight_paint_set_exec(bContext *C, wmOperator *UNUSED(op))
2514 struct Scene *scene = CTX_data_scene(C);
2515 Object *obact = CTX_data_active_object(C);
2516 ToolSettings *ts = CTX_data_tool_settings(C);
2517 Brush *brush = paint_brush(&ts->wpaint->paint);
2518 float vgroup_weight = BKE_brush_weight_get(scene, brush);
2520 wpaint_fill(scene->toolsettings->wpaint, obact, vgroup_weight);
2521 ED_region_tag_redraw(CTX_wm_region(C)); /* XXX - should redraw all 3D views */
2522 return OPERATOR_FINISHED;
2525 void PAINT_OT_weight_set(wmOperatorType *ot)
2528 ot->name = "Set Weight";
2529 ot->idname = "PAINT_OT_weight_set";
2530 ot->description = "Fill the active vertex group with the current paint weight";
2533 ot->exec = weight_paint_set_exec;
2534 ot->poll = mask_paint_poll; /* it was facemask_paint_poll */
2537 ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2540 /* ************ set / clear vertex paint mode ********** */
2543 static int set_vpaint(bContext *C, wmOperator *op) /* toggle */
2545 Object *ob = CTX_data_active_object(C);
2546 Scene *scene = CTX_data_scene(C);
2547 VPaint *vp = scene->toolsettings->vpaint;
2550 me = BKE_mesh_from_object(ob);
2552 if (me == NULL || BKE_object_obdata_is_libdata(ob)) {
2553 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2554 return OPERATOR_PASS_THROUGH;
2557 if (me && me->mloopcol == NULL) {
2561 /* toggle: end vpaint */
2562 if (ob->mode & OB_MODE_VERTEX_PAINT) {
2564 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2567 ob->mode |= OB_MODE_VERTEX_PAINT;
2568 /* Turn off weight painting */
2569 if (ob->mode & OB_MODE_WEIGHT_PAINT)
2573 vp = scene->toolsettings->vpaint = new_vpaint(0);
2575 paint_cursor_start(C, vertex_paint_poll);
2577 BKE_paint_init(&vp->paint, PAINT_CURSOR_VERTEX_PAINT);
2581 /* update modifier stack for mapping requirements */
2582 DAG_id_tag_update(&me->id, 0);
2584 WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2586 return OPERATOR_FINISHED;
2589 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2593 ot->name = "Vertex Paint Mode";
2594 ot->idname = "PAINT_OT_vertex_paint_toggle";
2595 ot->description = "Toggle the vertex paint mode in 3D view";
2598 ot->exec = set_vpaint;
2599 ot->poll = paint_poll_test;
2602 ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2607 /* ********************** vertex paint operator ******************* */
2609 /* Implementation notes:
2611 * Operator->invoke()
2612 * - validate context (add mcol)
2613 * - create customdata storage
2614 * - call paint once (mouse click)
2615 * - add modal handler
2618 * - for every mousemove, apply vertex paint
2619 * - exit on mouse release, free customdata
2620 * (return OPERATOR_FINISHED also removes handler and operator)
2623 * - implement a stroke event (or mousemove with past positons)
2624 * - revise whether op->customdata should be added in object, in set_vpaint
2627 typedef struct PolyFaceMap {
2628 struct PolyFaceMap *next, *prev;
2632 typedef struct VPaintData {
2634 unsigned int paintcol;
2636 float *vertexcosnos;
2639 /* modify 'me->mcol' directly, since the derived mesh is drawing from this array,
2640 * otherwise we need to refresh the modifier stack */
2641 int use_fast_update;
2643 /* mpoly -> mface mapping */
2644 MemArena *polyfacemap_arena;
2645 ListBase *polyfacemap;
2648 static void vpaint_build_poly_facemap(struct VPaintData *vd, Mesh *me)
2655 vd->polyfacemap_arena = BLI_memarena_new(1 << 13, "vpaint tmp");
2656 BLI_memarena_use_calloc(vd->polyfacemap_arena);
2658 vd->polyfacemap = BLI_memarena_alloc(vd->polyfacemap_arena, sizeof(ListBase) * me->totpoly);
2660 origIndex = CustomData_get_layer(&me->fdata, CD_POLYINDEX);
2666 for (i = 0; i < me->totface; i++, mf++, origIndex++) {
2667 if (*origIndex == ORIGINDEX_NONE)
2670 e = BLI_memarena_alloc(vd->polyfacemap_arena, sizeof(PolyFaceMap));
2673 BLI_addtail(&vd->polyfacemap[*origIndex], e);
2677 static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const float UNUSED(mouse[2]))
2679 ToolSettings *ts = CTX_data_tool_settings(C);
2680 struct PaintStroke *stroke = op->customdata;
2681 VPaint *vp = ts->vpaint;
2682 struct VPaintData *vpd;
2683 Object *ob = CTX_data_active_object(C);
2685 float mat[4][4], imat[4][4];
2687 /* context checks could be a poll() */
2688 me = BKE_mesh_from_object(ob);
2689 if (me == NULL || me->totpoly == 0)
2690 return OPERATOR_PASS_THROUGH;
2692 if (me->mloopcol == NULL)
2694 if (me->mloopcol == NULL)
2695 return OPERATOR_CANCELLED;
2697 /* make mode data storage */
2698 vpd = MEM_callocN(sizeof(struct VPaintData), "VPaintData");
2699 paint_stroke_set_mode_data(stroke, vpd);
2700 view3d_set_viewcontext(C, &vpd->vc);
2702 vpd->vertexcosnos = mesh_get_mapped_verts_nors(vpd->vc.scene, ob);
2703 vpd->indexar = get_indexarray(me);
2704 vpd->paintcol = vpaint_get_current_col(vp);
2707 /* are we painting onto a modified mesh?,
2708 * if not we can skip face map trickyness */
2709 if (vertex_paint_use_fast_update_check(ob)) {
2710 vpaint_build_poly_facemap(vpd, me);
2711 vpd->use_fast_update = TRUE;
2714 vpd->use_fast_update = FALSE;
2718 copy_vpaint_prev(vp, (unsigned int *)me->mloopcol, me->totloop);
2720 /* some old cruft to sort out later */
2721 mult_m4_m4m4(mat, vpd->vc.rv3d->viewmat, ob->obmat);
2722 invert_m4_m4(imat, mat);
2723 copy_m3_m4(vpd->vpimat, imat);
2729 static void vpaint_paint_face(VPaint *vp, VPaintData *vpd, Object *ob,
2730 const unsigned int index, const float mval[2],
2731 const float brush_size_pressure, const float brush_alpha_pressure,
2734 ViewContext *vc = &vpd->vc;
2735 Brush *brush = paint_brush(&vp->paint);
2736 Mesh *me = BKE_mesh_from_object(ob);
2737 MFace *mface = &me->mface[index];
2738 unsigned int *mcol = ((unsigned int *)me->mcol) + 4 * index;
2739 unsigned int *mcolorig = ((unsigned int *)vp->vpaint_prev) + 4 * index;
2743 int brush_alpha_pressure_i;
2745 if ((vp->flag & VP_COLINDEX && mface->mat_nr != ob->actcol - 1) ||
2746 ((me->editflag & ME_EDIT_PAINT_MASK) && !(mface->flag & ME_FACE_SEL)))
2749 if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2750 unsigned int fcol1 = mcol_blend(mcol[0], mcol[1], 128);
2752 unsigned int fcol2 = mcol_blend(mcol[2], mcol[3], 128);
2753 vpd->paintcol = mcol_blend(fcol1, fcol2, 128);
2756 vpd->paintcol = mcol_blend(mcol[2], fcol1, 170);
2760 brush_alpha_pressure_i = (int)(brush_alpha_pressure * 255.0f);
2762 for (i = 0; i < (mface->v4 ? 4 : 3); ++i) {
2763 alpha = calc_vp_alpha_dl(vp, vc, vpd->vpimat, vpd->vertexcosnos + 6 * (&mface->v1)[i],
2764 mval, brush_size_pressure, brush_alpha_pressure);
2766 const int alpha_i = (int)(alpha * 255.0f);
2767 mcol[i] = vpaint_blend(vp, mcol[i], mcolorig[i], vpd->paintcol, alpha_i, brush_alpha_pressure_i);
2773 /* BMESH version of vpaint_paint_face (commented above) */
2775 static void vpaint_paint_poly(VPaint *vp, VPaintData *vpd, Object *ob,
2776 const unsigned int index, const float mval[2],
2777 const float brush_size_pressure, const float brush_alpha_pressure)
2779 ViewContext *vc = &vpd->vc;
2780 Brush *brush = paint_brush(&vp->paint);
2781 Mesh *me = BKE_mesh_from_object(ob);
2782 MPoly *mpoly = &me->mpoly[index];
2788 unsigned int *lcol = ((unsigned int *)me->mloopcol) + mpoly->loopstart;
2789 unsigned int *lcolorig = ((unsigned int *)vp->vpaint_prev) + mpoly->loopstart;
2793 int brush_alpha_pressure_i = (int)(brush_alpha_pressure * 255.0f);
2795 if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2796 unsigned int blend[4] = {0};
2800 for (j = 0; j < mpoly->totloop; j++) {
2801 col = (char *)(lcol + j);
2808 blend[0] /= mpoly->totloop;
2809 blend[1] /= mpoly->totloop;
2810 blend[2] /= mpoly->totloop;
2811 blend[3] /= mpoly->totloop;
2812 col = (char *)&tcol;
2818 vpd->paintcol = *((unsigned int *)col);
2821 ml = me->mloop + mpoly->loopstart;
2822 for (i = 0; i < mpoly->totloop; i++, ml++) {
2823 alpha = calc_vp_alpha_dl(vp, vc, vpd->vpimat,
2824 vpd->vertexcosnos + 6 * ml->v, mval,
2825 brush_size_pressure, brush_alpha_pressure);
2827 const int alpha_i = (int)(alpha * 255.0f);
2828 lcol[i] = vpaint_blend(vp, lcol[i], lcolorig[i], vpd->paintcol, alpha_i, brush_alpha_pressure_i);
2832 if (vpd->use_fast_update) {
2837 #define CPYCOL(c, l) (c)->a = (l)->a, (c)->r = (l)->r, (c)->g = (l)->g, (c)->b = (l)->b
2839 /* update vertex colors for tessellations incrementally,
2840 * rather then regenerating the tessellation altogether */
2841 for (e = vpd->polyfacemap[index].first; e; e = e->next) {
2842 mf = me->mface + e->facenr;
2843 mc = me->mcol + e->facenr * 4;
2845 ml = me->mloop + mpoly->loopstart;
2846 mlc = me->mloopcol + mpoly->loopstart;
2847 for (j = 0; j < mpoly->totloop; j++, ml++, mlc++) {
2848 if (ml->v == mf->v1)
2850 else if (ml->v == mf->v2)
2851 CPYCOL(mc + 1, mlc);
2852 else if (ml->v == mf->v3)
2853 CPYCOL(mc + 2, mlc);
2854 else if (mf->v4 && ml->v == mf->v4)
2855 CPYCOL(mc + 3, mlc);
2864 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2866 Scene *scene = CTX_data_scene(C);
2867 ToolSettings *ts = CTX_data_tool_settings(C);
2868 struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2869 VPaint *vp = ts->vpaint;
2870 Brush *brush = paint_brush(&vp->paint);
2871 ViewContext *vc = &vpd->vc;
2872 Object *ob = vc->obact;
2873 Mesh *me = ob->data;
2875 int *indexar = vpd->indexar;
2876 int totindex, index;
2879 const float pressure = RNA_float_get(itemptr, "pressure");
2880 const float brush_size_pressure = BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2881 const float brush_alpha_pressure = BKE_brush_alpha_get(scene, brush) * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2883 RNA_float_get_array(itemptr, "mouse", mval);
2885 view3d_operator_needs_opengl(C);
2887 /* load projection matrix */
2888 mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2890 mval[0] -= vc->ar->winrct.xmin;
2891 mval[1] -= vc->ar->winrct.ymin;
2894 /* which faces are involved */
2895 if (vp->flag & VP_AREA) {
2896 totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2899 indexar[0] = view3d_sample_backbuf(vc, mval[0], mval[1]);
2900 if (indexar[0]) totindex = 1;
2905 if (vp->flag & VP_COLINDEX) {
2906 for (index = 0; index < totindex; index++) {
2907 if (indexar[index] && indexar[index] <= me->totpoly) {
2908 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2910 if (mpoly->mat_nr != ob->actcol - 1) {
2917 if ((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2918 for (index = 0; index < totindex; index++) {
2919 if (indexar[index] && indexar[index] <= me->totpoly) {
2920 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2922 if ((mpoly->flag & ME_FACE_SEL) == 0)
2928 swap_m4m4(vc->rv3d->persmat, mat);
2931 for (index = 0; index < totindex; index++) {
2933 if (indexar[index] && indexar[index] <= me->totpoly) {
2934 vpaint_paint_poly(vp, vpd, ob, indexar[index] - 1, mval, brush_size_pressure, brush_alpha_pressure);
2938 swap_m4m4(vc->rv3d->persmat, mat);
2940 /* was disabled because it is slow, but necessary for blur */
2941 if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2942 int do_tessface = vpd->use_fast_update;
2943 do_shared_vertexcol(me, do_tessface);