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_object_deform.h"
76 #include "BKE_paint.h"
77 #include "BKE_report.h"
82 #include "GPU_buffers.h"
84 #include "ED_armature.h"
86 #include "ED_screen.h"
87 #include "ED_view3d.h"
89 #include "paint_intern.h"
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)
95 DerivedMesh *dm = ob->derivedFinal;
98 Mesh *me = BKE_mesh_from_object(ob);
100 return (me->mcol == CustomData_get_layer(&dm->faceData, CD_MCOL));
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)
112 DerivedMesh *dm = ob->derivedFinal;
115 return (me->mpoly == CustomData_get_layer(&dm->polyData, CD_MPOLY));
121 static void update_tessface_data(Object *ob, Mesh *me)
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! */
130 memset(me->mcol, 255, 4 * sizeof(MCol) * me->totface);
134 /* create tessfaces because they will be used for drawing & fast updates */
135 BKE_mesh_tessface_calc(me); /* does own call to update pointers */
140 /* this wont be used, theres no need to keep it */
141 BKE_mesh_tessface_clear(me);
146 /* polling - retrieve whether cursor should be set or operator should be done */
148 /* Returns true if vertex paint mode is active */
149 int vertex_paint_mode_poll(bContext *C)
151 Object *ob = CTX_data_active_object(C);
153 return ob && ob->mode == OB_MODE_VERTEX_PAINT && ((Mesh *)ob->data)->totpoly;
156 int vertex_paint_poll(bContext *C)
158 if (vertex_paint_mode_poll(C) &&
159 paint_brush(&CTX_data_tool_settings(C)->vpaint->paint))
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)
171 int weight_paint_mode_poll(bContext *C)
173 Object *ob = CTX_data_active_object(C);
175 return ob && ob->mode == OB_MODE_WEIGHT_PAINT && ((Mesh *)ob->data)->totpoly;
178 int weight_paint_poll(bContext *C)
180 Object *ob = CTX_data_active_object(C);
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))
189 ARegion *ar = CTX_wm_region(C);
190 if (ar->regiontype == RGN_TYPE_WINDOW) {
197 static VPaint *new_vpaint(int wpaint)
199 VPaint *vp = MEM_callocN(sizeof(VPaint), "VPaint");
201 vp->flag = VP_AREA + VP_SPRAY;
209 static int *get_indexarray(Mesh *me)
211 return MEM_mallocN(sizeof(int) * (me->totpoly + 1), "vertexpaint");
214 unsigned int vpaint_get_current_col(VPaint *vp)
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;
223 static void do_shared_vertex_tesscol(Mesh *me)
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);
230 short *scolmain, *scol;
233 if (me->mcol == NULL || me->totvert == 0 || me->totface == 0) return;
235 scolmain = MEM_callocN(4 * sizeof(short) * me->totvert, "colmain");
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];
248 scol = scolmain + 4 * mface->v4;
249 scol[0]++; scol[1] += mcol[13]; scol[2] += mcol[14]; scol[3] += mcol[15];
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];
276 scol = scolmain + 4 * mface->v4;
277 mcol[13] = scol[1]; mcol[14] = scol[2]; mcol[15] = scol[3];
285 static void do_shared_vertexcol(Mesh *me, int do_tessface)
287 const int use_face_sel = (me->editflag & ME_EDIT_PAINT_MASK);
290 int i, j, has_shared = 0;
292 /* if no mloopcol: do not do */
293 /* if mtexpoly: only the involved faces, otherwise all */
295 if (me->mloopcol == 0 || me->totvert == 0 || me->totpoly == 0) return;
297 scol = MEM_callocN(sizeof(float) * me->totvert * 5, "scol");
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;
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]);
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];
335 if (has_shared && do_tessface) {
336 do_shared_vertex_tesscol(me);
340 static void make_vertexcol(Object *ob) /* single ob */
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;
348 /* copies from shadedisplist to mcol */
351 CustomData_add_layer(&me->fdata, CD_MCOL, CD_DEFAULT, NULL, me->totface);
354 CustomData_add_layer(&me->ldata, CD_MLOOPCOL, CD_DEFAULT, NULL, me->totloop);
356 mesh_update_customdata_pointers(me, TRUE);
359 update_tessface_data(ob, me);
362 // shadeMeshMCol(scene, ob, me);
365 DAG_id_tag_update(&me->id, 0);
369 /* mirror_vgroup is set to -1 when invalid */
370 static int wpaint_mirror_vgroup_ensure(Object *ob, const int vgroup_active)
372 bDeformGroup *defgroup = BLI_findlink(&ob->defbase, vgroup_active);
375 bDeformGroup *curdef;
377 char name[MAXBONENAME];
379 flip_side_name(name, defgroup->name, FALSE);
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)) {
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);
394 /* curdef should never be NULL unless this is
395 * a lamp and ED_vgroup_add_name fails */
405 static void copy_vpaint_prev(VPaint *vp, unsigned int *lcol, int tot)
407 if (vp->vpaint_prev) {
408 MEM_freeN(vp->vpaint_prev);
409 vp->vpaint_prev = NULL;
413 if (lcol == NULL || tot == 0) return;
415 vp->vpaint_prev = MEM_mallocN(sizeof(int) * tot, "vpaint_prev");
416 memcpy(vp->vpaint_prev, lcol, sizeof(int) * tot);
420 static void copy_wpaint_prev(VPaint *wp, MDeformVert *dverts, int dcount)
422 if (wp->wpaint_prev) {
423 free_dverts(wp->wpaint_prev, wp->tot);
424 wp->wpaint_prev = NULL;
427 if (dverts && dcount) {
429 wp->wpaint_prev = MEM_mallocN(sizeof(MDeformVert) * dcount, "wpaint prev");
431 copy_dverts(wp->wpaint_prev, dverts, dcount);
436 void vpaint_fill(Object *ob, unsigned int paintcol)
443 me = BKE_mesh_from_object(ob);
444 if (me == NULL || me->totpoly == 0) return;
446 if (!me->mloopcol) make_vertexcol(ob);
447 if (!me->mloopcol) return; /* possible we can't make mcol's */
450 selected = (me->editflag & ME_EDIT_PAINT_MASK);
453 for (i = 0; i < me->totpoly; i++, mp++) {
454 if (!(!selected || mp->flag & ME_FACE_SEL))
457 lcol = me->mloopcol + mp->loopstart;
458 for (j = 0; j < mp->totloop; j++, lcol++) {
459 *(int *)lcol = paintcol;
463 /* remove stale me->mcol, will be added later */
464 BKE_mesh_tessface_clear(me);
466 DAG_id_tag_update(&me->id, 0);
470 /* fills in the selected faces with the current weight and vertex group */
471 void wpaint_fill(VPaint *wp, Object *ob, float paintweight)
475 MDeformWeight *dw, *dw_prev;
476 int vgroup_active, vgroup_mirror = -1;
479 /* mutually exclusive, could be made into a */
480 const short paint_selmode = ME_EDIT_PAINT_SEL_MODE(me);
482 if (me->totpoly == 0 || me->dvert == NULL || !me->mpoly) return;
484 vgroup_active = ob->actdef - 1;
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);
491 copy_wpaint_prev(wp, me->dvert, me->totvert);
493 for (index = 0, mp = me->mpoly; index < me->totpoly; index++, mp++) {
494 unsigned int fidx = mp->totloop - 1;
496 if ((paint_selmode == SCE_SELECT_FACE) && !(mp->flag & ME_FACE_SEL)) {
501 unsigned int vidx = me->mloop[mp->loopstart + fidx].v;
503 if (!me->dvert[vidx].flag) {
504 if ((paint_selmode == SCE_SELECT_VERTEX) && !(me->mvert[vidx].flag & SELECT)) {
508 dw = defvert_verify_index(&me->dvert[vidx], vgroup_active);
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;
514 if (me->editflag & ME_EDIT_MIRROR_X) { /* x mirror painting */
515 int j = mesh_get_x_mirror_vert(ob, vidx);
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);
523 dw = defvert_verify_index(me->dvert + j, vgroup_active);
524 dw_prev = defvert_verify_index(wp->wpaint_prev + j, vgroup_active);
526 dw_prev->weight = dw->weight; /* set the undo weight */
527 dw->weight = paintweight;
531 me->dvert[vidx].flag = 1;
538 MDeformVert *dv = me->dvert;
539 for (index = me->totvert; index != 0; index--, dv++) {
544 copy_wpaint_prev(wp, NULL, 0);
546 DAG_id_tag_update(&me->id, 0);
549 /* XXX: should be re-implemented as a vertex/weight paint 'color correct' operator */
551 void vpaint_dogamma(Scene *scene)
553 VPaint *vp = scene->toolsettings->vpaint;
558 unsigned char *cp, gamtab[256];
561 me = BKE_mesh_from_object(ob);
563 if (!(ob->mode & OB_MODE_VERTEX_PAINT)) return;
564 if (me == 0 || me->mcol == 0 || me->totface == 0) return;
566 igam = 1.0 / vp->gamma;
567 for (a = 0; a < 256; a++) {
569 fac = ((float)a) / 255.0;
570 fac = vp->mul * pow(fac, igam);
574 if (temp <= 0) gamtab[a] = 0;
575 else if (temp >= 255) gamtab[a] = 255;
576 else gamtab[a] = temp;
580 cp = (unsigned char *)me->mcol;
583 cp[1] = gamtab[cp[1]];
584 cp[2] = gamtab[cp[2]];
585 cp[3] = gamtab[cp[3]];
592 BLI_INLINE unsigned int mcol_blend(unsigned int col1, unsigned int col2, int fac)
594 unsigned char *cp1, *cp2, *cp;
596 unsigned int col = 0;
608 cp1 = (unsigned char *)&col1;
609 cp2 = (unsigned char *)&col2;
610 cp = (unsigned char *)&col;
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;
620 BLI_INLINE unsigned int mcol_add(unsigned int col1, unsigned int col2, int fac)
622 unsigned char *cp1, *cp2, *cp;
624 unsigned int col = 0;
630 cp1 = (unsigned char *)&col1;
631 cp2 = (unsigned char *)&col2;
632 cp = (unsigned char *)&col;
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;
645 BLI_INLINE unsigned int mcol_sub(unsigned int col1, unsigned int col2, int fac)
647 unsigned char *cp1, *cp2, *cp;
649 unsigned int col = 0;
655 cp1 = (unsigned char *)&col1;
656 cp2 = (unsigned char *)&col2;
657 cp = (unsigned char *)&col;
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;
670 BLI_INLINE unsigned int mcol_mul(unsigned int col1, unsigned int col2, int fac)
672 unsigned char *cp1, *cp2, *cp;
674 unsigned int col = 0;
682 cp1 = (unsigned char *)&col1;
683 cp2 = (unsigned char *)&col2;
684 cp = (unsigned char *)&col;
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;
695 BLI_INLINE unsigned int mcol_lighten(unsigned int col1, unsigned int col2, int fac)
697 unsigned char *cp1, *cp2, *cp;
699 unsigned int col = 0;
704 else if (fac >= 255) {
710 cp1 = (unsigned char *)&col1;
711 cp2 = (unsigned char *)&col2;
712 cp = (unsigned char *)&col;
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)) {
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;
728 BLI_INLINE unsigned int mcol_darken(unsigned int col1, unsigned int col2, int fac)
730 unsigned char *cp1, *cp2, *cp;
732 unsigned int col = 0;
737 else if (fac >= 255) {
743 cp1 = (unsigned char *)&col1;
744 cp2 = (unsigned char *)&col2;
745 cp = (unsigned char *)&col;
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)) {
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;
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)
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);
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)
784 Brush *brush = paint_brush(&vp->paint);
785 const int tool = brush->vertexpaint_tool;
787 col = vpaint_blend_tool(tool, col, paintcol, alpha_i);
789 /* if no spray, clip color adding with colorig & orig alpha */
790 if ((vp->flag & VP_SPRAY) == 0) {
791 unsigned int testcol, a;
794 testcol = vpaint_blend_tool(tool, colorig, paintcol, brush_alpha_value_i);
797 ct = (char *)&testcol;
798 co = (char *)&colorig;
800 for (a = 0; a < 4; a++) {
802 if (cp[a] < ct[a]) cp[a] = ct[a];
803 else if (cp[a] > co[a]) cp[a] = co[a];
806 if (cp[a] < co[a]) cp[a] = co[a];
807 else if (cp[a] > ct[a]) cp[a] = ct[a];
816 static int sample_backbuf_area(ViewContext *vc, int *indexar, int totface, int x, int y, float size)
819 int a, tot = 0, index;
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;*/
825 ibuf = view3d_read_backbuf(vc, x - size, y - size, x + size, y + size);
827 unsigned int *rt = ibuf->rect;
829 memset(indexar, 0, sizeof(int) * (totface + 1));
831 size = ibuf->x * ibuf->y;
835 index = WM_framebuffer_to_index(*rt);
836 if (index > 0 && index <= totface)
843 for (a = 1; a <= totface; a++) {
844 if (indexar[a]) indexar[tot++] = a;
853 /* whats _dl mean? */
854 static float calc_vp_strength_dl(VPaint *vp, ViewContext *vc, const float co[3],
855 const float mval[2], const float brush_size_pressure)
859 if (ED_view3d_project_float_global(vc->ar, co, vertco, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
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);
875 static float calc_vp_alpha_dl(VPaint *vp, ViewContext *vc,
876 float vpimat[3][3], const DMCoNo *v_co_no,
878 const float brush_size_pressure, const float brush_alpha_pressure)
880 float strength = calc_vp_strength_dl(vp, vc, v_co_no->co, mval, brush_size_pressure);
882 if (strength > 0.0f) {
883 float alpha = brush_alpha_pressure * strength;
885 if (vp->flag & VP_NORMALS) {
889 dvec[2] = dot_v3v3(vpimat[2], v_co_no->no);
890 if (dvec[2] > 0.0f) {
891 dvec[0] = dot_v3v3(vpimat[0], v_co_no->no);
892 dvec[1] = dot_v3v3(vpimat[1], v_co_no->no);
894 alpha *= dvec[2] / len_v3(dvec);
908 BLI_INLINE float wval_blend(const float weight, const float paintval, const float alpha)
910 return (paintval * alpha) + (weight * (1.0f - alpha));
912 BLI_INLINE float wval_add(const float weight, const float paintval, const float alpha)
914 return weight + (paintval * alpha);
916 BLI_INLINE float wval_sub(const float weight, const float paintval, const float alpha)
918 return weight - (paintval * alpha);
920 BLI_INLINE float wval_mul(const float weight, const float paintval, const float alpha)
921 { /* first mul, then blend the fac */
922 return ((1.0f - alpha) + (alpha * paintval)) * weight;
924 BLI_INLINE float wval_lighten(const float weight, const float paintval, const float alpha)
926 return (weight < paintval) ? wval_blend(weight, paintval, alpha) : weight;
928 BLI_INLINE float wval_darken(const float weight, const float paintval, const float alpha)
930 return (weight > paintval) ? wval_blend(weight, paintval, alpha) : weight;
934 /* vpaint has 'vpaint_blend_tool' */
935 /* result is not clamped from [0-1] */
936 static float wpaint_blend_tool(const int tool,
939 const float paintval, const float alpha)
942 case PAINT_BLEND_MIX:
943 case PAINT_BLEND_BLUR: return wval_blend(weight, paintval, alpha);
944 case PAINT_BLEND_ADD: return wval_add(weight, paintval, alpha);
945 case PAINT_BLEND_SUB: return wval_sub(weight, paintval, alpha);
946 case PAINT_BLEND_MUL: return wval_mul(weight, paintval, alpha);
947 case PAINT_BLEND_LIGHTEN: return wval_lighten(weight, paintval, alpha);
948 case PAINT_BLEND_DARKEN: return wval_darken(weight, paintval, alpha);
955 /* vpaint has 'vpaint_blend' */
956 static float wpaint_blend(VPaint *wp, float weight, float weight_prev,
957 const float alpha, float paintval,
958 const float brush_alpha_value,
959 const short do_flip, const short do_multipaint_totsel)
961 Brush *brush = paint_brush(&wp->paint);
962 int tool = brush->vertexpaint_tool;
966 case PAINT_BLEND_MIX:
967 paintval = 1.f - paintval; break;
968 case PAINT_BLEND_ADD:
969 tool = PAINT_BLEND_SUB; break;
970 case PAINT_BLEND_SUB:
971 tool = PAINT_BLEND_ADD; break;
972 case PAINT_BLEND_LIGHTEN:
973 tool = PAINT_BLEND_DARKEN; break;
974 case PAINT_BLEND_DARKEN:
975 tool = PAINT_BLEND_LIGHTEN; break;
979 weight = wpaint_blend_tool(tool, weight, paintval, alpha);
981 /* delay clamping until the end so multi-paint can function when the active group is at the limits */
982 if (do_multipaint_totsel == FALSE) {
983 CLAMP(weight, 0.0f, 1.0f);
986 /* if no spray, clip result with orig weight & orig alpha */
987 if ((wp->flag & VP_SPRAY) == 0) {
988 if (do_multipaint_totsel == FALSE) {
989 float testw = wpaint_blend_tool(tool, weight_prev, paintval, brush_alpha_value);
991 CLAMP(testw, 0.0f, 1.0f);
992 if (testw < weight_prev) {
993 if (weight < testw) weight = testw;
994 else if (weight > weight_prev) weight = weight_prev;
997 if (weight > testw) weight = testw;
998 else if (weight < weight_prev) weight = weight_prev;
1006 /* ----------------------------------------------------- */
1009 /* sets wp->weight to the closest weight value to vertex */
1010 /* note: we cant sample frontbuf, weight colors are interpolated too unpredictable */
1011 static int weight_sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1015 short change = FALSE;
1017 view3d_set_viewcontext(C, &vc);
1018 me = BKE_mesh_from_object(vc.obact);
1020 if (me && me->dvert && vc.v3d && vc.rv3d) {
1021 const int use_vert_sel = (me->editflag & ME_EDIT_VERT_SEL) != 0;
1022 int v_idx_best = -1;
1025 view3d_operator_needs_opengl(C);
1028 if (ED_mesh_pick_vert(C, me, event->mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE)) {
1033 if (ED_mesh_pick_face_vert(C, me, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
1036 else if (ED_mesh_pick_face(C, me, event->mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
1037 /* this relies on knowning the internal worksings of ED_mesh_pick_face_vert() */
1038 BKE_report(op->reports, RPT_WARNING, "The modifier used does not support deformed locations");
1042 if (v_idx_best != -1) { /* should always be valid */
1043 ToolSettings *ts = vc.scene->toolsettings;
1044 Brush *brush = paint_brush(&ts->wpaint->paint);
1045 const int vgroup_active = vc.obact->actdef - 1;
1046 float vgroup_weight = defvert_find_weight(&me->dvert[v_idx_best], vgroup_active);
1047 BKE_brush_weight_set(vc.scene, brush, vgroup_weight);
1053 /* not really correct since the brush didnt change, but redraws the toolbar */
1054 WM_main_add_notifier(NC_BRUSH | NA_EDITED, NULL); /* ts->wpaint->paint.brush */
1056 return OPERATOR_FINISHED;
1059 return OPERATOR_CANCELLED;
1063 void PAINT_OT_weight_sample(wmOperatorType *ot)
1066 ot->name = "Weight Paint Sample Weight";
1067 ot->idname = "PAINT_OT_weight_sample";
1068 ot->description = "Use the mouse to sample a weight in the 3D view";
1071 ot->invoke = weight_sample_invoke;
1072 ot->poll = weight_paint_mode_poll;
1075 ot->flag = OPTYPE_UNDO;
1078 /* samples cursor location, and gives menu with vertex groups to activate */
1079 static int weight_paint_sample_enum_itemf__helper(const MDeformVert *dvert, const int defbase_tot, int *groups)
1081 /* this func fills in used vgroup's */
1083 int i = dvert->totweight;
1085 for (dw = dvert->dw; i > 0; dw++, i--) {
1086 if (dw->def_nr < defbase_tot) {
1087 groups[dw->def_nr] = TRUE;
1093 static EnumPropertyItem *weight_paint_sample_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), int *free)
1096 wmWindow *win = CTX_wm_window(C);
1097 if (win && win->eventstate) {
1101 view3d_set_viewcontext(C, &vc);
1102 me = BKE_mesh_from_object(vc.obact);
1104 if (me && me->dvert && vc.v3d && vc.rv3d && vc.obact->defbase.first) {
1105 const int defbase_tot = BLI_countlist(&vc.obact->defbase);
1106 const int use_vert_sel = (me->editflag & ME_EDIT_VERT_SEL) != 0;
1107 int *groups = MEM_callocN(defbase_tot * sizeof(int), "groups");
1111 int mval[2] = {win->eventstate->x - vc.ar->winrct.xmin,
1112 win->eventstate->y - vc.ar->winrct.ymin};
1114 view3d_operator_needs_opengl(C);
1117 if (ED_mesh_pick_vert(C, me, mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE)) {
1118 MDeformVert *dvert = &me->dvert[index];
1119 found |= weight_paint_sample_enum_itemf__helper(dvert, defbase_tot, groups);
1123 if (ED_mesh_pick_face(C, me, mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
1124 MPoly *mp = &me->mpoly[index];
1125 unsigned int fidx = mp->totloop - 1;
1128 MDeformVert *dvert = &me->dvert[me->mloop[mp->loopstart + fidx].v];
1129 found |= weight_paint_sample_enum_itemf__helper(dvert, defbase_tot, groups);
1134 if (found == FALSE) {
1138 EnumPropertyItem *item = NULL, item_tmp = {0};
1142 for (dg = vc.obact->defbase.first; dg && i < defbase_tot; i++, dg = dg->next) {
1144 item_tmp.identifier = item_tmp.name = dg->name;
1146 RNA_enum_item_add(&item, &totitem, &item_tmp);
1150 RNA_enum_item_end(&item, &totitem);
1160 return DummyRNA_NULL_items;
1163 static int weight_sample_group_exec(bContext *C, wmOperator *op)
1165 int type = RNA_enum_get(op->ptr, "group");
1167 view3d_set_viewcontext(C, &vc);
1169 BLI_assert(type + 1 >= 0);
1170 vc.obact->actdef = type + 1;
1172 DAG_id_tag_update(&vc.obact->id, OB_RECALC_DATA);
1173 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, vc.obact);
1174 return OPERATOR_FINISHED;
1177 /* TODO, we could make this a menu into OBJECT_OT_vertex_group_set_active rather than its own operator */
1178 void PAINT_OT_weight_sample_group(wmOperatorType *ot)
1180 PropertyRNA *prop = NULL;
1183 ot->name = "Weight Paint Sample Group";
1184 ot->idname = "PAINT_OT_weight_sample_group";
1185 ot->description = "Select one of the vertex groups available under current mouse position";
1188 ot->exec = weight_sample_group_exec;
1189 ot->invoke = WM_menu_invoke;
1190 ot->poll = weight_paint_mode_poll;
1193 ot->flag = OPTYPE_UNDO;
1195 /* keyingset to use (dynamic enum) */
1196 prop = RNA_def_enum(ot->srna, "group", DummyRNA_DEFAULT_items, 0, "Keying Set", "The Keying Set to use");
1197 RNA_def_enum_funcs(prop, weight_paint_sample_enum_itemf);
1201 static void do_weight_paint_normalize_all(MDeformVert *dvert, const int defbase_tot, const char *vgroup_validmap)
1203 float sum = 0.0f, fac;
1204 unsigned int i, tot = 0;
1207 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1208 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1214 if ((tot == 0) || (sum == 1.0f)) {
1221 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1222 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1228 /* hrmf, not a factor in this case */
1231 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1232 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1239 /* same as function above except it normalizes against the active vgroup which remains unchanged
1241 * note that the active is just the group which is unchanged, it can be any,
1242 * can also be -1 to normalize all but in that case call 'do_weight_paint_normalize_all' */
1243 static void do_weight_paint_normalize_all_active(MDeformVert *dvert, const int defbase_tot, const char *vgroup_validmap,
1244 const int vgroup_active)
1246 float sum = 0.0f, fac;
1247 unsigned int i, tot = 0;
1249 float act_weight = 0.0f;
1251 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1252 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1253 if (dw->def_nr != vgroup_active) {
1258 act_weight = dw->weight;
1263 if ((tot == 0) || (sum + act_weight == 1.0f)) {
1268 fac = (1.0f / sum) * (1.0f - act_weight);
1270 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1271 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1272 if (dw->def_nr != vgroup_active) {
1275 /* paranoid but possibly with float error */
1276 CLAMP(dw->weight, 0.0f, 1.0f);
1282 /* corner case where we need to scale all weights evenly because they're all zero */
1284 /* hrmf, not a factor in this case */
1285 fac = (1.0f - act_weight) / tot;
1287 /* paranoid but possibly with float error */
1288 CLAMP(fac, 0.0f, 1.0f);
1290 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1291 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1292 if (dw->def_nr != vgroup_active) {
1301 * See if the current deform vertex has a locked group
1303 static char has_locked_group(MDeformVert *dvert, const int defbase_tot,
1304 const char *bone_groups, const char *lock_flags)
1309 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1310 if (dw->def_nr < defbase_tot) {
1311 if (bone_groups[dw->def_nr] && lock_flags[dw->def_nr] && dw->weight > 0.0f) {
1319 static int has_locked_group_selected(int defbase_tot, const char *defbase_sel, const char *lock_flags)
1322 for (i = 0; i < defbase_tot; i++) {
1323 if (defbase_sel[i] && lock_flags[i]) {
1332 static int has_unselected_unlocked_bone_group(int defbase_tot, char *defbase_sel, int selected, char *lock_flags, char *vgroup_validmap)
1335 if (defbase_tot == selected) {
1338 for (i = 0; i < defbase_tot; i++) {
1339 if (vgroup_validmap[i] && !defbase_sel[i] && !lock_flags[i]) {
1348 static void multipaint_selection(MDeformVert *dvert, const int defbase_tot, float change, const char *defbase_sel)
1353 /* make sure they are all at most 1 after the change */
1354 for (i = 0; i < defbase_tot; i++) {
1355 if (defbase_sel[i]) {
1356 dw = defvert_find_index(dvert, i);
1357 if (dw && dw->weight) {
1358 val = dw->weight * change;
1360 /* TODO: when the change is reduced, you need to recheck
1361 * the earlier values to make sure they are not 0
1362 * (precision error) */
1363 change = 1.0f / dw->weight;
1365 /* the value should never reach zero while multi-painting if it
1366 * was nonzero beforehand */
1373 /* apply the valid change */
1374 for (i = 0; i < defbase_tot; i++) {
1375 if (defbase_sel[i]) {
1376 dw = defvert_find_index(dvert, i);
1377 if (dw && dw->weight) {
1378 dw->weight = dw->weight * change;
1384 /* move all change onto valid, unchanged groups. If there is change left over,
1386 * assumes there are valid groups to shift weight onto */
1387 static float redistribute_change(MDeformVert *ndv, const int defbase_tot,
1388 char *change_status, const char change_me, int changeto,
1389 float totchange, float total_valid,
1390 char do_auto_normalize)
1398 /* assume there is no change until you see one */
1400 /* change each group by the same amount each time */
1401 change = totchange / total_valid;
1402 for (i = 0; i < ndv->totweight && total_valid && totchange; i++) {
1403 ndw = (ndv->dw + i);
1405 /* ignore anything outside the value range */
1406 if (ndw->def_nr < defbase_tot) {
1408 /* change only the groups with a valid status */
1409 if (change_status[ndw->def_nr] == change_me) {
1410 oldval = ndw->weight;
1411 /* if auto normalize is active, don't worry about upper bounds */
1412 if (do_auto_normalize == FALSE && ndw->weight + change > 1) {
1413 totchange -= 1.0f - ndw->weight;
1415 /* stop the changes to this group */
1416 change_status[ndw->def_nr] = changeto;
1419 else if (ndw->weight + change < 0) { /* check the lower bound */
1420 totchange -= ndw->weight;
1422 change_status[ndw->def_nr] = changeto;
1425 else { /* a perfectly valid change occurred to ndw->weight */
1426 totchange -= change;
1427 ndw->weight += change;
1429 /* see if there was a change */
1430 if (oldval != ndw->weight) {
1436 /* don't go again if there was no change, if there is no valid group,
1437 * or there is no change left */
1438 } while (was_change && total_valid && totchange);
1442 static float get_mp_change(MDeformVert *odv, const int defbase_tot, const char *defbase_sel, float brush_change);
1443 /* observe the changes made to the weights of groups.
1444 * make sure all locked groups on the vertex have the same deformation
1445 * by moving the changes made to groups onto other unlocked groups */
1446 static void enforce_locks(MDeformVert *odv, MDeformVert *ndv,
1447 const int defbase_tot, const char *defbase_sel,
1448 const char *lock_flags, const char *vgroup_validmap,
1449 char do_auto_normalize, char do_multipaint)
1451 float totchange = 0.0f;
1452 float totchange_allowed = 0.0f;
1455 int total_valid = 0;
1456 int total_changed = 0;
1461 float changed_sum = 0.0f;
1463 char *change_status;
1465 if (!lock_flags || !has_locked_group(ndv, defbase_tot, vgroup_validmap, lock_flags)) {
1468 /* record if a group was changed, unlocked and not changed, or locked */
1469 change_status = MEM_callocN(sizeof(char) * defbase_tot, "unlocked_unchanged");
1471 for (i = 0; i < defbase_tot; i++) {
1472 ndw = defvert_find_index(ndv, i);
1473 odw = defvert_find_index(odv, i);
1474 /* the weights are zero, so we can assume a lot */
1476 if (!lock_flags[i] && vgroup_validmap[i]) {
1477 defvert_verify_index(odv, i);
1478 defvert_verify_index(ndv, i);
1480 change_status[i] = 1; /* can be altered while redistributing */
1484 /* locked groups should not be changed */
1485 if (lock_flags[i]) {
1486 ndw->weight = odw->weight;
1488 else if (ndw->weight != odw->weight) { /* changed groups are handled here */
1489 totchange += ndw->weight - odw->weight;
1490 changed_sum += ndw->weight;
1491 change_status[i] = 2; /* was altered already */
1493 } /* unchanged, unlocked bone groups are handled here */
1494 else if (vgroup_validmap[i]) {
1495 totchange_allowed += ndw->weight;
1497 change_status[i] = 1; /* can be altered while redistributing */
1500 /* if there was any change, redistribute it */
1501 if (total_changed) {
1502 /* auto normalize will allow weights to temporarily go above 1 in redistribution */
1503 if (vgroup_validmap && total_changed < 0 && total_valid) {
1504 totchange_allowed = total_valid;
1506 /* the way you modify the unlocked + unchanged groups is different depending
1507 * on whether or not you are painting the weight(s) up or down */
1508 if (totchange < 0) {
1509 totchange_allowed = total_valid - totchange_allowed;
1512 totchange_allowed *= -1;
1514 /* there needs to be change allowed, or you should not bother */
1515 if (totchange_allowed) {
1517 if (fabsf(totchange_allowed) < fabsf(totchange)) {
1518 /* this amount goes back onto the changed, unlocked weights */
1519 left_over = fabsf(fabsf(totchange) - fabsf(totchange_allowed));
1520 if (totchange > 0) {
1525 /* all of the change will be permitted */
1526 totchange_allowed = -totchange;
1528 /* move the weight evenly between the allowed groups, move excess back onto the used groups based on the change */
1529 totchange_allowed = redistribute_change(ndv, defbase_tot, change_status, 1, -1, totchange_allowed, total_valid, do_auto_normalize);
1530 left_over += totchange_allowed;
1532 /* more than one nonzero weights were changed with the same ratio with multipaint, so keep them changed that way! */
1533 if (total_changed > 1 && do_multipaint) {
1534 float undo_change = get_mp_change(ndv, defbase_tot, defbase_sel, left_over);
1535 multipaint_selection(ndv, defbase_tot, undo_change, defbase_sel);
1537 /* or designatedw is still -1 put weight back as evenly as possible */
1539 redistribute_change(ndv, defbase_tot, change_status, 2, -2, left_over, total_changed, do_auto_normalize);
1544 /* reset the weights */
1545 MDeformWeight *dw_old = odv->dw;
1546 MDeformWeight *dw_new = ndv->dw;
1548 for (i = odv->totweight; i != 0; i--, dw_old++, dw_new++) {
1549 dw_new->weight = dw_old->weight;
1554 MEM_freeN(change_status);
1557 /* multi-paint's initial, potential change is computed here based on the user's stroke */
1558 static float get_mp_change(MDeformVert *odv, const int defbase_tot, const char *defbase_sel, float brush_change)
1560 float selwsum = 0.0f;
1562 MDeformWeight *dw = odv->dw;
1564 for (i = odv->totweight; i != 0; i--, dw++) {
1565 if (dw->def_nr < defbase_tot) {
1566 if (defbase_sel[dw->def_nr]) {
1567 selwsum += dw->weight;
1571 if (selwsum && selwsum + brush_change > 0) {
1572 return (selwsum + brush_change) / selwsum;
1577 /* change the weights back to the wv's weights
1578 * it assumes you already have the correct pointer index */
1579 static void defvert_reset_to_prev(MDeformVert *dv_prev, MDeformVert *dv)
1581 MDeformWeight *dw = dv->dw;
1582 MDeformWeight *dw_prev;
1584 for (i = dv->totweight; i != 0; i--, dw++) {
1585 dw_prev = defvert_find_index(dv_prev, dw->def_nr);
1586 /* if there was no w when there is a d, then the old weight was 0 */
1587 dw->weight = dw_prev ? dw_prev->weight : 0.0f;
1591 static void clamp_weights(MDeformVert *dvert)
1593 MDeformWeight *dw = dvert->dw;
1595 for (i = dvert->totweight; i != 0; i--, dw++) {
1596 CLAMP(dw->weight, 0.0f, 1.0f);
1600 /* struct to avoid passing many args each call to do_weight_paint_vertex()
1601 * this _could_ be made a part of the operators 'WPaintData' struct, or at
1602 * least a member, but for now keep its own struct, initialized on every
1603 * paint stroke update - campbell */
1604 typedef struct WeightPaintInfo {
1608 /* both must add up to 'defbase_tot' */
1609 int defbase_tot_sel;
1610 int defbase_tot_unsel;
1612 int vgroup_active; /* (ob->actdef - 1) */
1613 int vgroup_mirror; /* mirror group or -1 */
1615 const char *lock_flags; /* boolean array for locked bones,
1616 * length of defbase_tot */
1617 const char *defbase_sel; /* boolean array for selected bones,
1618 * length of defbase_tot, cant be const because of how its passed */
1620 const char *vgroup_validmap; /* same as WeightPaintData.vgroup_validmap,
1621 * only added here for convenience */
1625 char do_auto_normalize;
1627 float brush_alpha_value; /* result of BKE_brush_alpha_get() */
1630 /* fresh start to make multi-paint and locking modular */
1631 /* returns TRUE if it thinks you need to reset the weights due to
1632 * normalizing while multi-painting
1634 * note: this assumes dw->def_nr range has been checked by the caller
1636 static int apply_mp_locks_normalize(Mesh *me, const WeightPaintInfo *wpi,
1637 const unsigned int index,
1638 MDeformWeight *dw, MDeformWeight *tdw,
1639 float change, float oldChange,
1640 float oldw, float neww)
1642 MDeformVert *dv = &me->dvert[index];
1643 MDeformVert dv_test = {NULL};
1645 dv_test.dw = MEM_dupallocN(dv->dw);
1646 dv_test.flag = dv->flag;
1647 dv_test.totweight = dv->totweight;
1648 /* do not multi-paint if a locked group is selected or the active group is locked
1649 * !lock_flags[dw->def_nr] helps if nothing is selected, but active group is locked */
1650 if ((wpi->lock_flags == NULL) ||
1651 ((wpi->lock_flags[dw->def_nr] == FALSE) && /* def_nr range has to be checked for by caller */
1652 has_locked_group_selected(wpi->defbase_tot, wpi->defbase_sel, wpi->lock_flags) == FALSE))
1654 if (wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1655 if (change && change != 1) {
1656 multipaint_selection(dv, wpi->defbase_tot, change, wpi->defbase_sel);
1659 else { /* this lets users paint normally, but don't let them paint locked groups */
1665 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 if (wpi->do_auto_normalize) {
1668 /* XXX - should we pass the active group? - currently '-1' */
1669 do_weight_paint_normalize_all(dv, wpi->defbase_tot, wpi->vgroup_validmap);
1672 if (oldChange && wpi->do_multipaint && wpi->defbase_tot_sel > 1) {
1673 if (tdw->weight != oldw) {
1675 if (tdw->weight <= oldw) {
1676 MEM_freeN(dv_test.dw);
1681 if (tdw->weight >= oldw) {
1682 MEM_freeN(dv_test.dw);
1688 MEM_freeN(dv_test.dw);
1692 /* within the current dvert index, get the dw that is selected and has a weight
1693 * above 0, this helps multi-paint */
1694 static int get_first_selected_nonzero_weight(MDeformVert *dvert, const int defbase_tot, const char *defbase_sel)
1697 MDeformWeight *dw = dvert->dw;
1698 for (i = 0; i < dvert->totweight; i++, dw++) {
1699 if (dw->def_nr < defbase_tot) {
1700 if (defbase_sel[dw->def_nr] && dw->weight > 0.0f) {
1708 static void do_weight_paint_vertex(
1709 /* vars which remain the same for every vert */
1710 VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1711 /* vars which change on each stroke */
1712 const unsigned int index, float alpha, float paintweight
1715 Mesh *me = ob->data;
1716 MDeformVert *dv = &me->dvert[index];
1718 MDeformWeight *dw, *dw_prev;
1724 MDeformVert *dv_mirr;
1725 MDeformWeight *dw_mirr;
1727 const short do_multipaint_totsel = (wpi->do_multipaint && wpi->defbase_tot_sel > 1);
1729 if (wp->flag & VP_ONLYVGROUP) {
1730 dw = defvert_find_index(dv, wpi->vgroup_active);
1731 dw_prev = defvert_find_index(wp->wpaint_prev + index, wpi->vgroup_active);
1734 dw = defvert_verify_index(dv, wpi->vgroup_active);
1735 dw_prev = defvert_verify_index(wp->wpaint_prev + index, wpi->vgroup_active);
1738 if (dw == NULL || dw_prev == NULL) {
1743 /* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
1744 if (me->editflag & ME_EDIT_MIRROR_X) {
1745 index_mirr = mesh_get_x_mirror_vert(ob, index);
1746 vgroup_mirr = (wpi->vgroup_mirror != -1) ? wpi->vgroup_mirror : wpi->vgroup_active;
1748 /* another possible error - mirror group _and_ active group are the same (which is fine),
1749 * but we also are painting onto a center vertex - this would paint the same weight twice */
1750 if (index_mirr == index && vgroup_mirr == wpi->vgroup_active) {
1751 index_mirr = vgroup_mirr = -1;
1755 index_mirr = vgroup_mirr = -1;
1759 /* get the mirror def vars */
1760 if (index_mirr != -1) {
1761 dv_mirr = &me->dvert[index_mirr];
1762 if (wp->flag & VP_ONLYVGROUP) {
1763 dw_mirr = defvert_find_index(dv_mirr, vgroup_mirr);
1765 if (dw_mirr == NULL) {
1766 index_mirr = vgroup_mirr = -1;
1771 if (index != index_mirr) {
1772 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1775 /* dv and dv_mirr are the same */
1776 int totweight_prev = dv_mirr->totweight;
1777 int dw_offset = (int)(dw - dv_mirr->dw);
1778 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1780 /* if we added another, get our old one back */
1781 if (totweight_prev != dv_mirr->totweight) {
1782 dw = &dv_mirr->dw[dw_offset];
1793 /* TODO: De-duplicate the simple weight paint - jason */
1794 /* ... or not, since its <10 SLOC - campbell */
1796 /* If there are no locks or multipaint,
1797 * then there is no need to run the more complicated checks */
1798 if ((do_multipaint_totsel == FALSE) &&
1799 (wpi->lock_flags == NULL || has_locked_group(dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags) == FALSE))
1801 dw->weight = wpaint_blend(wp, dw->weight, dw_prev->weight, alpha, paintweight,
1802 wpi->brush_alpha_value, wpi->do_flip, FALSE);
1804 /* WATCH IT: take care of the ordering of applying mirror -> normalize,
1805 * can give wrong results [#26193], least confusing if normalize is done last */
1808 if (index_mirr != -1) {
1809 /* copy, not paint again */
1810 dw_mirr->weight = dw->weight;
1813 /* apply normalize */
1814 if (wpi->do_auto_normalize) {
1815 /* note on normalize - this used to be applied after painting and normalize all weights,
1816 * in some ways this is good because there is feedback where the more weights involved would
1817 * 'resist' so you couldn't instantly zero out other weights by painting 1.0 on the active.
1819 * However this gave a problem since applying mirror, then normalize both verts
1820 * the resulting weight wont match on both sides.
1822 * If this 'resisting', slower normalize is nicer, we could call
1823 * do_weight_paint_normalize_all() and only use...
1824 * do_weight_paint_normalize_all_active() when normalizing the mirror vertex.
1827 do_weight_paint_normalize_all_active(dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->vgroup_active);
1829 if (index_mirr != -1) {
1830 /* only normalize if this is not a center vertex, else we get a conflict, normalizing twice */
1831 if (index != index_mirr) {
1832 do_weight_paint_normalize_all_active(dv_mirr, wpi->defbase_tot, wpi->vgroup_validmap, vgroup_mirr);
1835 /* this case accounts for...
1836 * - painting onto a center vertex of a mesh
1837 * - x mirror is enabled
1838 * - auto normalize is enabled
1839 * - the group you are painting onto has a L / R version
1841 * We want L/R vgroups to have the same weight but this cant be if both are over 0.5,
1842 * We _could_ have special check for that, but this would need its own normalize function which
1843 * holds 2 groups from changing at once.
1845 * So! just balance out the 2 weights, it keeps them equal and everything normalized.
1847 * While it wont hit the desired weight immediately as the user waggles their mouse,
1848 * constant painting and re-normalizing will get there. this is also just simpler logic.
1850 dw_mirr->weight = dw->weight = (dw_mirr->weight + dw->weight) * 0.5f;
1856 /* use locks and/or multipaint */
1859 /* float testw = 0; */ /* UNUSED */
1860 float observedChange = 0;
1862 float oldChange = 0;
1864 MDeformWeight *tdw = NULL, *tdw_prev;
1865 MDeformVert dv_copy = {NULL};
1868 neww = wpaint_blend(wp, dw->weight, dw_prev->weight, alpha, paintweight,
1869 wpi->brush_alpha_value, wpi->do_flip, do_multipaint_totsel);
1871 /* setup multi-paint */
1872 observedChange = neww - oldw;
1873 if (do_multipaint_totsel && observedChange) {
1874 dv_copy.dw = MEM_dupallocN(dv->dw);
1875 dv_copy.flag = dv->flag;
1876 dv_copy.totweight = dv->totweight;
1879 change = get_mp_change(&wp->wpaint_prev[index], wpi->defbase_tot, wpi->defbase_sel, observedChange);
1882 i = get_first_selected_nonzero_weight(dv, wpi->defbase_tot, wpi->defbase_sel);
1885 tdw_prev = defvert_verify_index(&wp->wpaint_prev[index], tdw->def_nr);
1891 if (change && tdw_prev->weight && tdw_prev->weight * change) {
1892 if (tdw->weight != tdw_prev->weight) {
1893 oldChange = tdw->weight / tdw_prev->weight;
1894 /* testw = tdw_prev->weight * change; */ /* UNUSED */
1895 if (observedChange > 0) {
1896 if (change > oldChange) {
1897 /* reset the weights and use the new change */
1898 defvert_reset_to_prev(wp->wpaint_prev + index, dv);
1901 /* the old change was more significant, so set
1902 * the change to 0 so that it will not do another multi-paint */
1907 if (change < oldChange) {
1908 defvert_reset_to_prev(wp->wpaint_prev + index, dv);
1922 if (apply_mp_locks_normalize(me, wpi, index, dw, tdw, change, oldChange, oldw, neww)) {
1923 defvert_reset_to_prev(&dv_copy, dv);
1928 MEM_freeN(dv_copy.dw);
1931 /* dv may have been altered greatly */
1932 dw = defvert_find_index(dv, vgroup);
1934 dw = NULL; /* UNUSED after assignment, set to NULL to ensure we don't
1935 * use again, we thats needed un-ifdef the line above */
1936 (void)dw; /* quiet warnigns */
1939 /* x mirror painting */
1940 if (index_mirr != -1) {
1941 /* copy, not paint again */
1943 /* dw_mirr->weight = dw->weight; */ /* TODO, explain the logic in not assigning weight! - campbell */
1944 apply_mp_locks_normalize(me, wpi, index_mirr, dw_mirr, tdw, change, oldChange, oldw, neww);
1950 /* *************** set wpaint operator ****************** */
1952 static int set_wpaint(bContext *C, wmOperator *UNUSED(op)) /* toggle */
1954 Object *ob = CTX_data_active_object(C);
1955 Scene *scene = CTX_data_scene(C);
1956 VPaint *wp = scene->toolsettings->wpaint;
1959 me = BKE_mesh_from_object(ob);
1960 if (ob->id.lib || me == NULL) return OPERATOR_PASS_THROUGH;
1962 if (ob->mode & OB_MODE_WEIGHT_PAINT) ob->mode &= ~OB_MODE_WEIGHT_PAINT;
1963 else ob->mode |= OB_MODE_WEIGHT_PAINT;
1966 /* Weightpaint works by overriding colors in mesh,
1967 * so need to make sure we recalc on enter and
1968 * exit (exit needs doing regardless because we
1971 DAG_id_tag_update(&me->id, 0);
1973 if (ob->mode & OB_MODE_WEIGHT_PAINT) {
1977 wp = scene->toolsettings->wpaint = new_vpaint(1);
1979 BKE_paint_init(&wp->paint, PAINT_CURSOR_WEIGHT_PAINT);
1980 paint_cursor_start(C, weight_paint_poll);
1982 mesh_octree_table(ob, NULL, NULL, 's');
1984 /* verify if active weight group is also active bone */
1985 par = modifiers_isDeformedByArmature(ob);
1986 if (par && (par->mode & OB_MODE_POSE)) {
1987 bArmature *arm = par->data;
1990 ED_vgroup_select_by_name(ob, arm->act_bone->name);
1994 mesh_octree_table(NULL, NULL, NULL, 'e');
1995 mesh_mirrtopo_table(NULL, 'e');
1998 WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2000 return OPERATOR_FINISHED;
2003 /* for switching to/from mode */
2004 static int paint_poll_test(bContext *C)
2006 Object *ob = CTX_data_active_object(C);
2007 if (CTX_data_edit_object(C))
2009 if (CTX_data_active_object(C) == NULL)
2011 if (!ob->data || ((ID *)ob->data)->lib)
2016 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
2020 ot->name = "Weight Paint Mode";
2021 ot->idname = "PAINT_OT_weight_paint_toggle";
2022 ot->description = "Toggle weight paint mode in 3D view";
2025 ot->exec = set_wpaint;
2026 ot->poll = paint_poll_test;
2029 ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2033 /* ************ weight paint operator ********** */
2040 DMCoNo *vertexcosnos;
2043 /* variables for auto normalize */
2044 const char *vgroup_validmap; /* stores if vgroups tie to deforming bones or not */
2045 const char *lock_flags;
2049 static int wpaint_stroke_test_start(bContext *C, wmOperator *op, const float UNUSED(mouse[2]))
2051 Scene *scene = CTX_data_scene(C);
2052 struct PaintStroke *stroke = op->customdata;
2053 ToolSettings *ts = scene->toolsettings;
2054 VPaint *wp = ts->wpaint;
2055 Object *ob = CTX_data_active_object(C);
2056 struct WPaintData *wpd;
2059 float mat[4][4], imat[4][4];
2061 if (scene->obedit) {
2065 me = BKE_mesh_from_object(ob);
2066 if (me == NULL || me->totpoly == 0) return OPERATOR_PASS_THROUGH;
2068 /* if nothing was added yet, we make dverts and a vertex deform group */
2070 ED_vgroup_data_create(&me->id);
2071 WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
2074 /* this happens on a Bone select, when no vgroup existed yet */
2075 if (ob->actdef <= 0) {
2077 if ((modob = modifiers_isDeformedByArmature(ob))) {
2078 Bone *actbone = ((bArmature *)modob->data)->act_bone;
2080 bPoseChannel *pchan = BKE_pose_channel_find_name(modob->pose, actbone->name);
2083 bDeformGroup *dg = defgroup_find_name(ob, pchan->name);
2085 dg = ED_vgroup_add_name(ob, pchan->name); /* sets actdef */
2088 int actdef = 1 + BLI_findindex(&ob->defbase, dg);
2089 BLI_assert(actdef >= 0);
2090 ob->actdef = actdef;
2096 if (ob->defbase.first == NULL) {
2100 /* ensure we don't try paint onto an invalid group */
2101 if (ob->actdef <= 0) {
2102 BKE_report(op->reports, RPT_WARNING, "No active vertex group for painting, aborting");
2107 /* check if we are attempting to paint onto a locked vertex group,
2108 * and other options disallow it from doing anything useful */
2109 bDeformGroup *dg = BLI_findlink(&ob->defbase, (ob->actdef - 1));
2110 if (dg->flag & DG_LOCK_WEIGHT) {
2111 BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
2116 /* ALLOCATIONS! no return after this line */
2117 /* make mode data storage */
2118 wpd = MEM_callocN(sizeof(struct WPaintData), "WPaintData");
2119 paint_stroke_set_mode_data(stroke, wpd);
2120 view3d_set_viewcontext(C, &wpd->vc);
2122 wpd->vgroup_active = ob->actdef - 1;
2123 wpd->vgroup_mirror = -1;
2125 /* set up auto-normalize, and generate map for detecting which
2126 * vgroups affect deform bones */
2127 wpd->defbase_tot = BLI_countlist(&ob->defbase);
2128 wpd->lock_flags = BKE_objdef_lock_flags_get(ob, wpd->defbase_tot);
2129 if (ts->auto_normalize || ts->multipaint || wpd->lock_flags) {
2130 wpd->vgroup_validmap = BKE_objdef_validmap_get(ob, wpd->defbase_tot);
2133 /* painting on subsurfs should give correct points too, this returns me->totvert amount */
2134 wpd->vertexcosnos = mesh_get_mapped_verts_nors(scene, ob);
2135 wpd->indexar = get_indexarray(me);
2136 copy_wpaint_prev(wp, me->dvert, me->totvert);
2138 /* imat for normals */
2139 mult_m4_m4m4(mat, wpd->vc.rv3d->viewmat, ob->obmat);
2140 invert_m4_m4(imat, mat);
2141 copy_m3_m4(wpd->wpimat, imat);
2143 /* if mirror painting, find the other group */
2144 if (me->editflag & ME_EDIT_MIRROR_X) {
2145 wpd->vgroup_mirror = wpaint_mirror_vgroup_ensure(ob, wpd->vgroup_active);
2151 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2153 Scene *scene = CTX_data_scene(C);
2154 ToolSettings *ts = CTX_data_tool_settings(C);
2155 VPaint *wp = ts->wpaint;
2156 Brush *brush = paint_brush(&wp->paint);
2157 struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2165 unsigned int index, totindex;
2170 const float pressure = RNA_float_get(itemptr, "pressure");
2171 const float brush_size_pressure = BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2172 const float brush_alpha_value = BKE_brush_alpha_get(scene, brush);
2173 const float brush_alpha_pressure = brush_alpha_value * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2175 /* intentionally don't initialize as NULL, make sure we initialize all members below */
2176 WeightPaintInfo wpi;
2178 /* cannot paint if there is no stroke data */
2180 /* XXX: force a redraw here, since even though we can't paint,
2181 * at least view won't freeze until stroke ends */
2182 ED_region_tag_redraw(CTX_wm_region(C));
2189 indexar = wpd->indexar;
2191 view3d_operator_needs_opengl(C);
2193 /* load projection matrix */
2194 mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2196 RNA_float_get_array(itemptr, "mouse", mval);
2197 mval[0] -= vc->ar->winrct.xmin;
2198 mval[1] -= vc->ar->winrct.ymin;
2203 /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2204 wpi.defbase_tot = wpd->defbase_tot;
2205 wpi.defbase_sel = BKE_objdef_selected_get(ob, wpi.defbase_tot, &wpi.defbase_tot_sel);
2206 if (wpi.defbase_tot_sel == 0 && ob->actdef > 0) {
2207 wpi.defbase_tot_sel = 1;
2210 wpi.defbase_tot_unsel = wpi.defbase_tot - wpi.defbase_tot_sel;
2211 wpi.vgroup_active = wpd->vgroup_active;
2212 wpi.vgroup_mirror = wpd->vgroup_mirror;
2213 wpi.lock_flags = wpd->lock_flags;
2214 wpi.vgroup_validmap = wpd->vgroup_validmap;
2215 wpi.do_flip = RNA_boolean_get(itemptr, "pen_flip");
2216 wpi.do_multipaint = (ts->multipaint != 0);
2217 wpi.do_auto_normalize = ((ts->auto_normalize != 0) && (wpi.vgroup_validmap != NULL));
2218 wpi.brush_alpha_value = brush_alpha_value;
2219 /* *** done setting up WeightPaintInfo *** */
2223 swap_m4m4(wpd->vc.rv3d->persmat, mat);
2225 use_vert_sel = (me->editflag & ME_EDIT_VERT_SEL) != 0;
2227 /* which faces are involved */
2228 if (wp->flag & VP_AREA) {
2229 /* Ugly hack, to avoid drawing vertex index when getting the face index buffer - campbell */
2230 me->editflag &= ~ME_EDIT_VERT_SEL;
2231 totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2232 me->editflag |= use_vert_sel ? ME_EDIT_VERT_SEL : 0;
2235 indexar[0] = view3d_sample_backbuf(vc, mval[0], mval[1]);
2236 if (indexar[0]) totindex = 1;
2240 if ((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2241 for (index = 0; index < totindex; index++) {
2242 if (indexar[index] && indexar[index] <= me->totpoly) {
2243 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2245 if ((mpoly->flag & ME_FACE_SEL) == 0) {
2252 /* make sure each vertex gets treated only once */
2253 /* and calculate filter weight */
2255 if (brush->vertexpaint_tool == PAINT_BLEND_BLUR)
2258 paintweight = BKE_brush_weight_get(scene, brush);
2260 for (index = 0; index < totindex; index++) {
2261 if (indexar[index] && indexar[index] <= me->totpoly) {
2262 MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2263 MLoop *ml = me->mloop + mpoly->loopstart;
2267 for (i = 0; i < mpoly->totloop; i++, ml++) {
2268 me->dvert[ml->v].flag = (me->mvert[ml->v].flag & SELECT);
2272 for (i = 0; i < mpoly->totloop; i++, ml++) {
2273 me->dvert[ml->v].flag = 1;
2277 if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2278 MDeformWeight *dw, *(*dw_func)(MDeformVert *, const int);
2280 if (wp->flag & VP_ONLYVGROUP)
2281 dw_func = (MDeformWeight *(*)(MDeformVert *, const int))defvert_find_index;
2283 dw_func = defvert_verify_index;
2285 ml = me->mloop + mpoly->loopstart;
2286 for (i = 0; i < mpoly->totloop; i++, ml++) {
2287 unsigned int vidx = ml->v;
2288 const float fac = calc_vp_strength_dl(wp, vc, wpd->vertexcosnos[vidx].co, mval, brush_size_pressure);
2290 dw = dw_func(&me->dvert[vidx], wpi.vgroup_active);
2291 paintweight += dw ? (dw->weight * fac) : 0.0f;
2299 if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2300 paintweight /= totw;
2303 for (index = 0; index < totindex; index++) {
2305 if (indexar[index] && indexar[index] <= me->totpoly) {
2306 MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2307 MLoop *ml = me->mloop + mpoly->loopstart;
2310 for (i = 0; i < mpoly->totloop; i++, ml++) {
2311 unsigned int vidx = ml->v;
2313 if (me->dvert[vidx].flag) {
2314 alpha = calc_vp_alpha_dl(wp, vc, wpd->wpimat, &wpd->vertexcosnos[vidx],
2315 mval, brush_size_pressure, brush_alpha_pressure);
2317 do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight);
2319 me->dvert[vidx].flag = 0;
2326 /* *** free wpi members */
2327 MEM_freeN((void *)wpi.defbase_sel);
2328 /* *** don't freeing wpi members */
2331 swap_m4m4(vc->rv3d->persmat, mat);
2333 DAG_id_tag_update(ob->data, 0);
2334 ED_region_tag_redraw(vc->ar);
2337 static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2339 ToolSettings *ts = CTX_data_tool_settings(C);
2340 Object *ob = CTX_data_active_object(C);
2341 struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2344 if (wpd->vertexcosnos)
2345 MEM_freeN(wpd->vertexcosnos);
2346 MEM_freeN(wpd->indexar);
2348 if (wpd->vgroup_validmap)
2349 MEM_freeN((void *)wpd->vgroup_validmap);
2350 if (wpd->lock_flags)
2351 MEM_freeN((void *)wpd->lock_flags);
2356 /* frees prev buffer */
2357 copy_wpaint_prev(ts->wpaint, NULL, 0);
2359 /* and particles too */
2360 if (ob->particlesystem.first) {
2361 ParticleSystem *psys;
2364 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2365 for (i = 0; i < PSYS_TOT_VG; i++) {
2366 if (psys->vgroup[i] == ob->actdef) {
2367 psys->recalc |= PSYS_RECALC_RESET;
2374 DAG_id_tag_update(ob->data, 0);
2376 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2380 static int wpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2384 op->customdata = paint_stroke_new(C, NULL, wpaint_stroke_test_start,
2385 wpaint_stroke_update_step,
2386 wpaint_stroke_done, event->type);
2388 /* add modal handler */
2389 WM_event_add_modal_handler(C, op);
2391 retval = op->type->modal(C, op, event);
2392 OPERATOR_RETVAL_CHECK(retval);
2393 BLI_assert(retval == OPERATOR_RUNNING_MODAL);
2395 return OPERATOR_RUNNING_MODAL;
2398 static int wpaint_cancel(bContext *C, wmOperator *op)
2400 paint_stroke_cancel(C, op);
2402 return OPERATOR_CANCELLED;
2405 void PAINT_OT_weight_paint(wmOperatorType *ot)
2409 ot->name = "Weight Paint";
2410 ot->idname = "PAINT_OT_weight_paint";
2411 ot->description = "Paint a stroke in the current vertex group's weights";
2414 ot->invoke = wpaint_invoke;
2415 ot->modal = paint_stroke_modal;
2416 /* ot->exec = vpaint_exec; <-- needs stroke property */
2417 ot->poll = weight_paint_poll;
2418 ot->cancel = wpaint_cancel;
2421 ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
2423 RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2426 static int weight_paint_set_exec(bContext *C, wmOperator *UNUSED(op))
2428 struct Scene *scene = CTX_data_scene(C);
2429 Object *obact = CTX_data_active_object(C);
2430 ToolSettings *ts = CTX_data_tool_settings(C);
2431 Brush *brush = paint_brush(&ts->wpaint->paint);
2432 float vgroup_weight = BKE_brush_weight_get(scene, brush);
2434 wpaint_fill(scene->toolsettings->wpaint, obact, vgroup_weight);
2435 ED_region_tag_redraw(CTX_wm_region(C)); /* XXX - should redraw all 3D views */
2436 return OPERATOR_FINISHED;
2439 void PAINT_OT_weight_set(wmOperatorType *ot)
2442 ot->name = "Set Weight";
2443 ot->idname = "PAINT_OT_weight_set";
2444 ot->description = "Fill the active vertex group with the current paint weight";
2447 ot->exec = weight_paint_set_exec;
2448 ot->poll = mask_paint_poll; /* it was facemask_paint_poll */
2451 ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2454 /* ************ set / clear vertex paint mode ********** */
2457 static int set_vpaint(bContext *C, wmOperator *op) /* toggle */
2459 Object *ob = CTX_data_active_object(C);
2460 Scene *scene = CTX_data_scene(C);
2461 VPaint *vp = scene->toolsettings->vpaint;
2464 me = BKE_mesh_from_object(ob);
2466 if (me == NULL || BKE_object_obdata_is_libdata(ob)) {
2467 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2468 return OPERATOR_PASS_THROUGH;
2471 if (me && me->mloopcol == NULL) {
2475 /* toggle: end vpaint */
2476 if (ob->mode & OB_MODE_VERTEX_PAINT) {
2478 ob->mode &= ~OB_MODE_VERTEX_PAINT;
2481 ob->mode |= OB_MODE_VERTEX_PAINT;
2482 /* Turn off weight painting */
2483 if (ob->mode & OB_MODE_WEIGHT_PAINT)
2487 vp = scene->toolsettings->vpaint = new_vpaint(0);
2489 paint_cursor_start(C, vertex_paint_poll);
2491 BKE_paint_init(&vp->paint, PAINT_CURSOR_VERTEX_PAINT);
2495 /* update modifier stack for mapping requirements */
2496 DAG_id_tag_update(&me->id, 0);
2498 WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2500 return OPERATOR_FINISHED;
2503 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2507 ot->name = "Vertex Paint Mode";
2508 ot->idname = "PAINT_OT_vertex_paint_toggle";
2509 ot->description = "Toggle the vertex paint mode in 3D view";
2512 ot->exec = set_vpaint;
2513 ot->poll = paint_poll_test;
2516 ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2521 /* ********************** vertex paint operator ******************* */
2523 /* Implementation notes:
2525 * Operator->invoke()
2526 * - validate context (add mcol)
2527 * - create customdata storage
2528 * - call paint once (mouse click)
2529 * - add modal handler
2532 * - for every mousemove, apply vertex paint
2533 * - exit on mouse release, free customdata
2534 * (return OPERATOR_FINISHED also removes handler and operator)
2537 * - implement a stroke event (or mousemove with past positons)
2538 * - revise whether op->customdata should be added in object, in set_vpaint
2541 typedef struct PolyFaceMap {
2542 struct PolyFaceMap *next, *prev;
2546 typedef struct VPaintData {
2548 unsigned int paintcol;
2550 DMCoNo *vertexcosnos;
2553 /* modify 'me->mcol' directly, since the derived mesh is drawing from this array,
2554 * otherwise we need to refresh the modifier stack */
2555 int use_fast_update;
2557 /* mpoly -> mface mapping */
2558 MemArena *polyfacemap_arena;
2559 ListBase *polyfacemap;
2562 static void vpaint_build_poly_facemap(struct VPaintData *vd, Mesh *me)
2569 vd->polyfacemap_arena = BLI_memarena_new(1 << 13, "vpaint tmp");
2570 BLI_memarena_use_calloc(vd->polyfacemap_arena);
2572 vd->polyfacemap = BLI_memarena_alloc(vd->polyfacemap_arena, sizeof(ListBase) * me->totpoly);
2574 origIndex = CustomData_get_layer(&me->fdata, CD_ORIGINDEX);
2580 for (i = 0; i < me->totface; i++, mf++, origIndex++) {
2581 if (*origIndex == ORIGINDEX_NONE)
2584 e = BLI_memarena_alloc(vd->polyfacemap_arena, sizeof(PolyFaceMap));
2587 BLI_addtail(&vd->polyfacemap[*origIndex], e);
2591 static int vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const float UNUSED(mouse[2]))
2593 ToolSettings *ts = CTX_data_tool_settings(C);
2594 struct PaintStroke *stroke = op->customdata;
2595 VPaint *vp = ts->vpaint;
2596 struct VPaintData *vpd;
2597 Object *ob = CTX_data_active_object(C);
2599 float mat[4][4], imat[4][4];
2601 /* context checks could be a poll() */
2602 me = BKE_mesh_from_object(ob);
2603 if (me == NULL || me->totpoly == 0)
2604 return OPERATOR_PASS_THROUGH;
2606 if (me->mloopcol == NULL)
2608 if (me->mloopcol == NULL)
2609 return OPERATOR_CANCELLED;
2611 /* Update tessface data if needed
2612 * Added here too because e.g. switching to/from edit mode would remove tessface data,
2613 * yet "fast_update" could still be used! */
2614 update_tessface_data(ob, me);
2616 /* make mode data storage */
2617 vpd = MEM_callocN(sizeof(struct VPaintData), "VPaintData");
2618 paint_stroke_set_mode_data(stroke, vpd);
2619 view3d_set_viewcontext(C, &vpd->vc);
2621 vpd->vertexcosnos = mesh_get_mapped_verts_nors(vpd->vc.scene, ob);
2622 vpd->indexar = get_indexarray(me);
2623 vpd->paintcol = vpaint_get_current_col(vp);
2626 /* are we painting onto a modified mesh?,
2627 * if not we can skip face map trickyness */
2628 if (vertex_paint_use_fast_update_check(ob)) {
2629 vpaint_build_poly_facemap(vpd, me);
2630 vpd->use_fast_update = TRUE;
2631 /* printf("Fast update!\n");*/
2634 vpd->use_fast_update = FALSE;
2635 /* printf("No fast update!\n");*/
2639 copy_vpaint_prev(vp, (unsigned int *)me->mloopcol, me->totloop);
2641 /* some old cruft to sort out later */
2642 mult_m4_m4m4(mat, vpd->vc.rv3d->viewmat, ob->obmat);
2643 invert_m4_m4(imat, mat);
2644 copy_m3_m4(vpd->vpimat, imat);
2649 static void vpaint_paint_poly(VPaint *vp, VPaintData *vpd, Mesh *me,
2650 const unsigned int index, const float mval[2],
2651 const float brush_size_pressure, const float brush_alpha_pressure)
2653 ViewContext *vc = &vpd->vc;
2654 Brush *brush = paint_brush(&vp->paint);
2655 MPoly *mpoly = &me->mpoly[index];
2661 unsigned int *lcol = ((unsigned int *)me->mloopcol) + mpoly->loopstart;
2662 unsigned int *lcolorig = ((unsigned int *)vp->vpaint_prev) + mpoly->loopstart;
2666 int brush_alpha_pressure_i = (int)(brush_alpha_pressure * 255.0f);
2668 if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2669 unsigned int blend[4] = {0};
2673 for (j = 0; j < mpoly->totloop; j++) {
2674 col = (char *)(lcol + j);
2681 blend[0] /= mpoly->totloop;
2682 blend[1] /= mpoly->totloop;
2683 blend[2] /= mpoly->totloop;
2684 blend[3] /= mpoly->totloop;
2685 col = (char *)&tcol;
2691 vpd->paintcol = *((unsigned int *)col);
2694 ml = me->mloop + mpoly->loopstart;
2695 for (i = 0; i < mpoly->totloop; i++, ml++) {
2696 alpha = calc_vp_alpha_dl(vp, vc, vpd->vpimat,
2697 &vpd->vertexcosnos[ml->v], mval,
2698 brush_size_pressure, brush_alpha_pressure);
2700 const int alpha_i = (int)(alpha * 255.0f);
2701 lcol[i] = vpaint_blend(vp, lcol[i], lcolorig[i], vpd->paintcol, alpha_i, brush_alpha_pressure_i);
2705 if (vpd->use_fast_update) {
2706 /* update vertex colors for tessellations incrementally,
2707 * rather then regenerating the tessellation altogether */
2708 for (e = vpd->polyfacemap[index].first; e; e = e->next) {
2709 mf = &me->mface[e->facenr];
2710 mc = &me->mcol[e->facenr * 4];
2712 ml = me->mloop + mpoly->loopstart;
2713 mlc = me->mloopcol + mpoly->loopstart;
2714 for (j = 0; j < mpoly->totloop; j++, ml++, mlc++) {
2715 if (ml->v == mf->v1) {
2716 MESH_MLOOPCOL_TO_MCOL(mlc, mc + 0);
2718 else if (ml->v == mf->v2) {
2719 MESH_MLOOPCOL_TO_MCOL(mlc, mc + 1);
2721 else if (ml->v == mf->v3) {
2722 MESH_MLOOPCOL_TO_MCOL(mlc, mc + 2);
2724 else if (mf->v4 && ml->v == mf->v4) {
2725 MESH_MLOOPCOL_TO_MCOL(mlc, mc + 3);
2733 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2735 Scene *scene = CTX_data_scene(C);
2736 ToolSettings *ts = CTX_data_tool_settings(C);
2737 struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2738 VPaint *vp = ts->vpaint;
2739 Brush *brush = paint_brush(&vp->paint);
2740 ViewContext *vc = &vpd->vc;
2741 Object *ob = vc->obact;
2742 Mesh *me = ob->data;
2744 int *indexar = vpd->indexar;
2745 int totindex, index;
2748 const float pressure = RNA_float_get(itemptr, "pressure");
2749 const float brush_size_pressure = BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2750 const float brush_alpha_pressure = BKE_brush_alpha_get(scene, brush) * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2752 RNA_float_get_array(itemptr, "mouse", mval);
2754 view3d_operator_needs_opengl(C);
2756 /* load projection matrix */
2757 mult_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2759 mval[0] -= vc->ar->winrct.xmin;
2760 mval[1] -= vc->ar->winrct.ymin;
2763 /* which faces are involved */
2764 if (vp->flag & VP_AREA) {
2765 totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2768 indexar[0] = view3d_sample_backbuf(vc, mval[0], mval[1]);
2769 if (indexar[0]) totindex = 1;
2773 if ((me->editflag & ME_EDIT_PAINT_MASK) && me->mpoly) {
2774 for (index = 0; index < totindex; index++) {
2775 if (indexar[index] && indexar[index] <= me->totpoly) {
2776 MPoly *mpoly = ((MPoly *)me->mpoly) + (indexar[index] - 1);
2778 if ((mpoly->flag & ME_FACE_SEL) == 0)
2784 swap_m4m4(vc->rv3d->persmat, mat);
2786 for (index = 0; index < totindex; index++) {
2787 if (indexar[index] && indexar[index] <= me->totpoly) {
2788 vpaint_paint_poly(vp, vpd, me, indexar[index] - 1, mval, brush_size_pressure, brush_alpha_pressure);
2792 swap_m4m4(vc->rv3d->persmat, mat);
2794 /* was disabled because it is slow, but necessary for blur */
2795 if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2796 int do_tessface = vpd->use_fast_update;
2797 do_shared_vertexcol(me, do_tessface);
2800 ED_region_tag_redraw(vc->ar);
2802 if (vpd->use_fast_update == FALSE) {
2803 /* recalculate modifier stack to get new colors, slow,
2804 * avoid this if we can! */
2805 DAG_id_tag_update(ob->data, 0);
2807 else if (!GPU_buffer_legacy(ob->derivedFinal)) {
2808 /* If using new VBO drawing, mark mcol as dirty to force colors gpu buffer refresh! */
2809 ob->derivedFinal->dirty |= DM_DIRTY_MCOL_UPDATE_DRAW;
2813 static void vpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2815 ToolSettings *ts = CTX_data_tool_settings(C);
2816 struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2817 ViewContext *vc = &vpd->vc;
2818 Object *ob = vc->obact;
2820 if (vpd->vertexcosnos)
2821 MEM_freeN(vpd->vertexcosnos);
2822 MEM_freeN(vpd->indexar);
2824 /* frees prev buffer */
2825 copy_vpaint_prev(ts->vpaint, NULL, 0);
2827 if (vpd->polyfacemap_arena) {
2828 BLI_memarena_free(vpd->polyfacemap_arena);
2831 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2836 static int vpaint_invoke(bContext *C, wmOperator *op, wmEvent *event)
2840 op->customdata = paint_stroke_new(C, NULL, vpaint_stroke_test_start,
2841 vpaint_stroke_update_step,
2842 vpaint_stroke_done, event->type);
2844 /* add modal handler */
2845 WM_event_add_modal_handler(C, op);
2847 retval = op->type->modal(C, op, event);
2848 OPERATOR_RETVAL_CHECK(retval);
2849 BLI_assert(retval == OPERATOR_RUNNING_MODAL);
2851 return OPERATOR_RUNNING_MODAL;
2854 static int vpaint_cancel(bContext *C, wmOperator *op)
2856 paint_stroke_cancel(C, op);
2858 return OPERATOR_CANCELLED;
2861 void PAINT_OT_vertex_paint(wmOperatorType *ot)
2864 ot->name = "Vertex Paint";
2865 ot->idname = "PAINT_OT_vertex_paint";
2866 ot->description = "Paint a stroke in the active vertex color layer";
2869 ot->invoke = vpaint_invoke;
2870 ot->modal = paint_stroke_modal;
2871 /* ot->exec = vpaint_exec; <-- needs stroke property */
2872 ot->poll = vertex_paint_poll;
2873 ot->cancel = vpaint_cancel;
2876 ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
2878 RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2881 /* ********************** weight from bones operator ******************* */
2883 static int weight_from_bones_poll(bContext *C)
2885 Object *ob = CTX_data_active_object(C);
2887 return (ob && (ob->mode & OB_MODE_WEIGHT_PAINT) && modifiers_isDeformedByArmature(ob));
2890 static int weight_from_bones_exec(bContext *C, wmOperator *op)
2892 Scene *scene = CTX_data_scene(C);
2893 Object *ob = CTX_data_active_object(C);
2894 Object *armob = modifiers_isDeformedByArmature(ob);
2895 Mesh *me = ob->data;
2896 int type = RNA_enum_get(op->ptr, "type");
2898 create_vgroups_from_armature(op->reports, scene, ob, armob, type, (me->editflag & ME_EDIT_MIRROR_X));
2900 DAG_id_tag_update(&me->id, 0);
2901 WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
2903 return OPERATOR_FINISHED;
2906 void PAINT_OT_weight_from_bones(wmOperatorType *ot)
2908 static EnumPropertyItem type_items[] = {
2909 {ARM_GROUPS_AUTO, "AUTOMATIC", 0, "Automatic", "Automatic weights from bones"},
2910 {ARM_GROUPS_ENVELOPE, "ENVELOPES", 0, "From Envelopes", "Weights from envelopes with user defined radius"},
2911 {0, NULL, 0, NULL, NULL}};
2914 ot->name = "Weight from Bones";
2915 ot->idname = "PAINT_OT_weight_from_bones";
2916 ot->description = "Set the weights of the groups matching the attached armature's selected bones, "
2917 "using the distance between the vertices and the bones";
2920 ot->exec = weight_from_bones_exec;
2921 ot->invoke = WM_menu_invoke;
2922 ot->poll = weight_from_bones_poll;
2925 ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2928 ot->prop = RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "Method to use for assigning weights");