Cleanup: remove redundant, invalid info from headers
[blender.git] / source / blender / blenkernel / intern / deform.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  */
19
20 /** \file blender/blenkernel/intern/deform.c
21  *  \ingroup bke
22  */
23
24
25 #include <string.h>
26 #include <math.h>
27 #include <ctype.h>
28 #include <stdlib.h>
29 #include <stddef.h>
30
31 #include "MEM_guardedalloc.h"
32
33 #include "DNA_meshdata_types.h"
34 #include "DNA_mesh_types.h"
35 #include "DNA_object_types.h"
36 #include "DNA_scene_types.h"
37
38 #include "BLI_listbase.h"
39 #include "BLI_math.h"
40 #include "BLI_string.h"
41 #include "BLI_string_utils.h"
42 #include "BLI_utildefines.h"
43
44 #include "BLT_translation.h"
45
46 #include "BKE_customdata.h"
47 #include "BKE_data_transfer.h"
48 #include "BKE_deform.h"  /* own include */
49 #include "BKE_mesh_mapping.h"
50 #include "BKE_object_deform.h"
51
52 #include "data_transfer_intern.h"
53
54
55 bDeformGroup *BKE_defgroup_new(Object *ob, const char *name)
56 {
57         bDeformGroup *defgroup;
58
59         BLI_assert(OB_TYPE_SUPPORT_VGROUP(ob->type));
60
61         defgroup = MEM_callocN(sizeof(bDeformGroup), __func__);
62
63         BLI_strncpy(defgroup->name, name, sizeof(defgroup->name));
64
65         BLI_addtail(&ob->defbase, defgroup);
66         defgroup_unique_name(defgroup, ob);
67
68         return defgroup;
69 }
70
71 void defgroup_copy_list(ListBase *outbase, const ListBase *inbase)
72 {
73         bDeformGroup *defgroup, *defgroupn;
74
75         BLI_listbase_clear(outbase);
76
77         for (defgroup = inbase->first; defgroup; defgroup = defgroup->next) {
78                 defgroupn = defgroup_duplicate(defgroup);
79                 BLI_addtail(outbase, defgroupn);
80         }
81 }
82
83 bDeformGroup *defgroup_duplicate(const bDeformGroup *ingroup)
84 {
85         bDeformGroup *outgroup;
86
87         if (!ingroup) {
88                 BLI_assert(0);
89                 return NULL;
90         }
91
92         outgroup = MEM_callocN(sizeof(bDeformGroup), "copy deformGroup");
93
94         /* For now, just copy everything over. */
95         memcpy(outgroup, ingroup, sizeof(bDeformGroup));
96
97         outgroup->next = outgroup->prev = NULL;
98
99         return outgroup;
100 }
101
102 /**
103  * Overwrite weights filtered by vgroup_subset.
104  * - do nothing if neither are set.
105  * - add destination weight if needed
106  */
107 void defvert_copy_subset(
108         MDeformVert *dvert_dst, const MDeformVert *dvert_src,
109         const bool *vgroup_subset, const int vgroup_tot)
110 {
111         int defgroup;
112         for (defgroup = 0; defgroup < vgroup_tot; defgroup++) {
113                 if (vgroup_subset[defgroup]) {
114                         defvert_copy_index(dvert_dst, defgroup, dvert_src, defgroup);
115                 }
116         }
117 }
118
119 /**
120  * Overwrite weights filtered by vgroup_subset and with mirroring specified by the flip map
121  * - do nothing if neither are set.
122  * - add destination weight if needed
123  */
124 void defvert_mirror_subset(
125         MDeformVert *dvert_dst, const MDeformVert *dvert_src,
126         const bool *vgroup_subset, const int vgroup_tot,
127         const int *flip_map, const int flip_map_len)
128 {
129         int defgroup;
130         for (defgroup = 0; defgroup < vgroup_tot && defgroup < flip_map_len; defgroup++) {
131                 if (vgroup_subset[defgroup] && (dvert_dst != dvert_src || flip_map[defgroup] != defgroup)) {
132                         defvert_copy_index(dvert_dst, flip_map[defgroup], dvert_src, defgroup);
133                 }
134         }
135 }
136
137 void defvert_copy(MDeformVert *dvert_dst, const MDeformVert *dvert_src)
138 {
139         if (dvert_dst->totweight == dvert_src->totweight) {
140                 if (dvert_src->totweight)
141                         memcpy(dvert_dst->dw, dvert_src->dw, dvert_src->totweight * sizeof(MDeformWeight));
142         }
143         else {
144                 if (dvert_dst->dw)
145                         MEM_freeN(dvert_dst->dw);
146
147                 if (dvert_src->totweight)
148                         dvert_dst->dw = MEM_dupallocN(dvert_src->dw);
149                 else
150                         dvert_dst->dw = NULL;
151
152                 dvert_dst->totweight = dvert_src->totweight;
153         }
154 }
155
156 /**
157  * Copy an index from one dvert to another.
158  * - do nothing if neither are set.
159  * - add destination weight if needed.
160  */
161 void defvert_copy_index(
162         MDeformVert       *dvert_dst, const int defgroup_dst,
163         const MDeformVert *dvert_src, const int defgroup_src)
164 {
165         MDeformWeight *dw_src, *dw_dst;
166
167         dw_src = defvert_find_index(dvert_src, defgroup_src);
168
169         if (dw_src) {
170                 /* source is valid, verify destination */
171                 dw_dst = defvert_verify_index(dvert_dst, defgroup_dst);
172                 dw_dst->weight = dw_src->weight;
173         }
174         else {
175                 /* source was NULL, assign zero, could also remove */
176                 dw_dst = defvert_find_index(dvert_dst, defgroup_dst);
177
178                 if (dw_dst) {
179                         dw_dst->weight = 0.0f;
180                 }
181         }
182 }
183
184 /**
185  * Only sync over matching weights, don't add or remove groups
186  * warning, loop within loop.
187  */
188 void defvert_sync(MDeformVert *dvert_dst, const MDeformVert *dvert_src, const bool use_verify)
189 {
190         if (dvert_src->totweight && dvert_dst->totweight) {
191                 int i;
192                 MDeformWeight *dw_src;
193                 for (i = 0, dw_src = dvert_src->dw; i < dvert_src->totweight; i++, dw_src++) {
194                         MDeformWeight *dw_dst;
195                         if (use_verify) dw_dst = defvert_verify_index(dvert_dst, dw_src->def_nr);
196                         else            dw_dst = defvert_find_index(dvert_dst, dw_src->def_nr);
197
198                         if (dw_dst) {
199                                 dw_dst->weight = dw_src->weight;
200                         }
201                 }
202         }
203 }
204
205 /**
206  * be sure all flip_map values are valid
207  */
208 void defvert_sync_mapped(
209         MDeformVert *dvert_dst, const MDeformVert *dvert_src,
210         const int *flip_map, const int flip_map_len, const bool use_verify)
211 {
212         if (dvert_src->totweight && dvert_dst->totweight) {
213                 int i;
214                 MDeformWeight *dw_src;
215                 for (i = 0, dw_src = dvert_src->dw; i < dvert_src->totweight; i++, dw_src++) {
216                         if (dw_src->def_nr < flip_map_len) {
217                                 MDeformWeight *dw_dst;
218                                 if (use_verify) dw_dst = defvert_verify_index(dvert_dst, flip_map[dw_src->def_nr]);
219                                 else            dw_dst = defvert_find_index(dvert_dst, flip_map[dw_src->def_nr]);
220
221                                 if (dw_dst) {
222                                         dw_dst->weight = dw_src->weight;
223                                 }
224                         }
225                 }
226         }
227 }
228
229 /**
230  * be sure all flip_map values are valid
231  */
232 void defvert_remap(MDeformVert *dvert, int *map, const int map_len)
233 {
234         MDeformWeight *dw = dvert->dw;
235         unsigned int i;
236         for (i = dvert->totweight; i != 0; i--, dw++) {
237                 if (dw->def_nr < map_len) {
238                         dw->def_nr = map[dw->def_nr];
239
240                         /* just in case */
241                         BLI_assert(dw->def_nr >= 0);
242                 }
243         }
244 }
245
246 /**
247  * Same as #defvert_normalize but takes a bool array.
248  */
249 void defvert_normalize_subset(MDeformVert *dvert,
250                               const bool *vgroup_subset, const int vgroup_tot)
251 {
252         if (dvert->totweight == 0) {
253                 /* nothing */
254         }
255         else if (dvert->totweight == 1) {
256                 MDeformWeight *dw = dvert->dw;
257                 if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
258                         dw->weight = 1.0f;
259                 }
260         }
261         else {
262                 MDeformWeight *dw;
263                 unsigned int i;
264                 float tot_weight = 0.0f;
265
266                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
267                         if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
268                                 tot_weight += dw->weight;
269                         }
270                 }
271
272                 if (tot_weight > 0.0f) {
273                         float scalar = 1.0f / tot_weight;
274                         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
275                                 if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
276                                         dw->weight *= scalar;
277
278                                         /* in case of division errors with very low weights */
279                                         CLAMP(dw->weight, 0.0f, 1.0f);
280                                 }
281                         }
282                 }
283         }
284 }
285
286 void defvert_normalize(MDeformVert *dvert)
287 {
288         if (dvert->totweight == 0) {
289                 /* nothing */
290         }
291         else if (dvert->totweight == 1) {
292                 dvert->dw[0].weight = 1.0f;
293         }
294         else {
295                 MDeformWeight *dw;
296                 unsigned int i;
297                 float tot_weight = 0.0f;
298
299                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
300                         tot_weight += dw->weight;
301                 }
302
303                 if (tot_weight > 0.0f) {
304                         float scalar = 1.0f / tot_weight;
305                         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
306                                 dw->weight *= scalar;
307
308                                 /* in case of division errors with very low weights */
309                                 CLAMP(dw->weight, 0.0f, 1.0f);
310                         }
311                 }
312         }
313 }
314
315 /**
316  * Same as defvert_normalize() if the locked vgroup is not a member of the subset
317  */
318 void defvert_normalize_lock_single(
319         MDeformVert *dvert,
320         const bool *vgroup_subset, const int vgroup_tot,
321         const int def_nr_lock)
322 {
323         if (dvert->totweight == 0) {
324                 /* nothing */
325         }
326         else if (dvert->totweight == 1) {
327                 MDeformWeight *dw = dvert->dw;
328                 if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
329                         if (def_nr_lock != 0) {
330                                 dw->weight = 1.0f;
331                         }
332                 }
333         }
334         else {
335                 MDeformWeight *dw_lock = NULL;
336                 MDeformWeight *dw;
337                 unsigned int i;
338                 float tot_weight = 0.0f;
339                 float lock_iweight = 1.0f;
340
341                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
342                         if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
343                                 if (dw->def_nr != def_nr_lock) {
344                                         tot_weight += dw->weight;
345                                 }
346                                 else {
347                                         dw_lock = dw;
348                                         lock_iweight = (1.0f - dw_lock->weight);
349                                         CLAMP(lock_iweight, 0.0f, 1.0f);
350                                 }
351                         }
352                 }
353
354                 if (tot_weight > 0.0f) {
355                         /* paranoid, should be 1.0 but in case of float error clamp anyway */
356
357                         float scalar = (1.0f / tot_weight) * lock_iweight;
358                         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
359                                 if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
360                                         if (dw != dw_lock) {
361                                                 dw->weight *= scalar;
362
363                                                 /* in case of division errors with very low weights */
364                                                 CLAMP(dw->weight, 0.0f, 1.0f);
365                                         }
366                                 }
367                         }
368                 }
369         }
370 }
371
372 /**
373  * Same as defvert_normalize() if no locked vgroup is a member of the subset
374  */
375 void defvert_normalize_lock_map(
376         MDeformVert *dvert,
377         const bool *vgroup_subset, const int vgroup_tot,
378         const bool *lock_flags, const int defbase_tot)
379 {
380         if (dvert->totweight == 0) {
381                 /* nothing */
382         }
383         else if (dvert->totweight == 1) {
384                 MDeformWeight *dw = dvert->dw;
385                 if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
386                         if ((dw->def_nr < defbase_tot) && (lock_flags[dw->def_nr] == false)) {
387                                 dw->weight = 1.0f;
388                         }
389                 }
390         }
391         else {
392                 MDeformWeight *dw;
393                 unsigned int i;
394                 float tot_weight = 0.0f;
395                 float lock_iweight = 0.0f;
396
397                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
398                         if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
399                                 if ((dw->def_nr < defbase_tot) && (lock_flags[dw->def_nr] == false)) {
400                                         tot_weight += dw->weight;
401                                 }
402                                 else {
403                                         /* invert after */
404                                         lock_iweight += dw->weight;
405                                 }
406                         }
407                 }
408
409                 lock_iweight = max_ff(0.0f, 1.0f - lock_iweight);
410
411                 if (tot_weight > 0.0f) {
412                         /* paranoid, should be 1.0 but in case of float error clamp anyway */
413
414                         float scalar = (1.0f / tot_weight) * lock_iweight;
415                         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
416                                 if ((dw->def_nr < vgroup_tot) && vgroup_subset[dw->def_nr]) {
417                                         if ((dw->def_nr < defbase_tot) && (lock_flags[dw->def_nr] == false)) {
418                                                 dw->weight *= scalar;
419
420                                                 /* in case of division errors with very low weights */
421                                                 CLAMP(dw->weight, 0.0f, 1.0f);
422                                         }
423                                 }
424                         }
425                 }
426         }
427 }
428
429 void defvert_flip(MDeformVert *dvert, const int *flip_map, const int flip_map_len)
430 {
431         MDeformWeight *dw;
432         int i;
433
434         for (dw = dvert->dw, i = 0; i < dvert->totweight; dw++, i++) {
435                 if (dw->def_nr < flip_map_len) {
436                         if (flip_map[dw->def_nr] >= 0) {
437                                 dw->def_nr = flip_map[dw->def_nr];
438                         }
439                 }
440         }
441 }
442
443 void defvert_flip_merged(MDeformVert *dvert, const int *flip_map, const int flip_map_len)
444 {
445         MDeformWeight *dw, *dw_cpy;
446         float weight;
447         int i, totweight = dvert->totweight;
448
449         /* copy weights */
450         for (dw = dvert->dw, i = 0; i < totweight; dw++, i++) {
451                 if (dw->def_nr < flip_map_len) {
452                         if (flip_map[dw->def_nr] >= 0) {
453                                 /* error checkers complain of this but we'll never get NULL return */
454                                 dw_cpy = defvert_verify_index(dvert, flip_map[dw->def_nr]);
455                                 dw = &dvert->dw[i]; /* in case array got realloced */
456
457                                 /* distribute weights: if only one of the vertex groups was
458                                  * assigned this will halve the weights, otherwise it gets
459                                  * evened out. this keeps it proportional to other groups */
460                                 weight = 0.5f * (dw_cpy->weight + dw->weight);
461                                 dw_cpy->weight = weight;
462                                 dw->weight = weight;
463                         }
464                 }
465         }
466 }
467
468 bDeformGroup *defgroup_find_name(Object *ob, const char *name)
469 {
470         return BLI_findstring(&ob->defbase, name, offsetof(bDeformGroup, name));
471 }
472
473 int defgroup_name_index(Object *ob, const char *name)
474 {
475         return (name) ? BLI_findstringindex(&ob->defbase, name, offsetof(bDeformGroup, name)) : -1;
476 }
477
478 /**
479  * \note caller must free.
480  */
481 int *defgroup_flip_map(Object *ob, int *flip_map_len, const bool use_default)
482 {
483         int defbase_tot = *flip_map_len = BLI_listbase_count(&ob->defbase);
484
485         if (defbase_tot == 0) {
486                 return NULL;
487         }
488         else {
489                 bDeformGroup *dg;
490                 char name_flip[sizeof(dg->name)];
491                 int i, flip_num, *map = MEM_mallocN(defbase_tot * sizeof(int), __func__);
492
493                 for (i = 0; i < defbase_tot; i++) {
494                         map[i] = -1;
495                 }
496
497                 for (dg = ob->defbase.first, i = 0; dg; dg = dg->next, i++) {
498                         if (map[i] == -1) { /* may be calculated previously */
499
500                                 /* in case no valid value is found, use this */
501                                 if (use_default)
502                                         map[i] = i;
503
504                                 BLI_string_flip_side_name(name_flip, dg->name, false, sizeof(name_flip));
505
506                                 if (!STREQ(name_flip, dg->name)) {
507                                         flip_num = defgroup_name_index(ob, name_flip);
508                                         if (flip_num >= 0) {
509                                                 map[i] = flip_num;
510                                                 map[flip_num] = i; /* save an extra lookup */
511                                         }
512                                 }
513                         }
514                 }
515                 return map;
516         }
517 }
518
519 /**
520  * \note caller must free.
521  */
522 int *defgroup_flip_map_single(Object *ob, int *flip_map_len, const bool use_default, int defgroup)
523 {
524         int defbase_tot = *flip_map_len = BLI_listbase_count(&ob->defbase);
525
526         if (defbase_tot == 0) {
527                 return NULL;
528         }
529         else {
530                 bDeformGroup *dg;
531                 char name_flip[sizeof(dg->name)];
532                 int i, flip_num, *map = MEM_mallocN(defbase_tot * sizeof(int), __func__);
533
534                 for (i = 0; i < defbase_tot; i++) {
535                         map[i] = use_default ? i : -1;
536                 }
537
538                 dg = BLI_findlink(&ob->defbase, defgroup);
539
540                 BLI_string_flip_side_name(name_flip, dg->name, false, sizeof(name_flip));
541                 if (!STREQ(name_flip, dg->name)) {
542                         flip_num = defgroup_name_index(ob, name_flip);
543
544                         if (flip_num != -1) {
545                                 map[defgroup] = flip_num;
546                                 map[flip_num] = defgroup;
547                         }
548                 }
549
550                 return map;
551         }
552 }
553
554 int defgroup_flip_index(Object *ob, int index, const bool use_default)
555 {
556         bDeformGroup *dg = BLI_findlink(&ob->defbase, index);
557         int flip_index = -1;
558
559         if (dg) {
560                 char name_flip[sizeof(dg->name)];
561                 BLI_string_flip_side_name(name_flip, dg->name, false, sizeof(name_flip));
562
563                 if (!STREQ(name_flip, dg->name)) {
564                         flip_index = defgroup_name_index(ob, name_flip);
565                 }
566         }
567
568         return (flip_index == -1 && use_default) ? index : flip_index;
569 }
570
571 static bool defgroup_find_name_dupe(const char *name, bDeformGroup *dg, Object *ob)
572 {
573         bDeformGroup *curdef;
574
575         for (curdef = ob->defbase.first; curdef; curdef = curdef->next) {
576                 if (dg != curdef) {
577                         if (STREQ(curdef->name, name)) {
578                                 return true;
579                         }
580                 }
581         }
582
583         return false;
584 }
585
586 static bool defgroup_unique_check(void *arg, const char *name)
587 {
588         struct {Object *ob; void *dg; } *data = arg;
589         return defgroup_find_name_dupe(name, data->dg, data->ob);
590 }
591
592 void defgroup_unique_name(bDeformGroup *dg, Object *ob)
593 {
594         struct {Object *ob; void *dg; } data;
595         data.ob = ob;
596         data.dg = dg;
597
598         BLI_uniquename_cb(defgroup_unique_check, &data, DATA_("Group"), '.', dg->name, sizeof(dg->name));
599 }
600
601 float defvert_find_weight(const struct MDeformVert *dvert, const int defgroup)
602 {
603         MDeformWeight *dw = defvert_find_index(dvert, defgroup);
604         return dw ? dw->weight : 0.0f;
605 }
606
607 /**
608  * Take care with this the rationale is:
609  * - if the object has no vertex group. act like vertex group isn't set and return 1.0,
610  * - if the vertex group exists but the 'defgroup' isn't found on this vertex, _still_ return 0.0
611  *
612  * This is a bit confusing, just saves some checks from the caller.
613  */
614 float defvert_array_find_weight_safe(const struct MDeformVert *dvert, const int index, const int defgroup)
615 {
616         /* Invalid defgroup index means the vgroup selected is invalid, does not exist, in that case it is OK to return 1.0
617          * (i.e. maximum weight, as if no vgroup was selected).
618          * But in case of valid defgroup and NULL dvert data pointer, it means that vgroup **is** valid,
619          * and just totally empty, so we shall return '0.0' value then!
620          */
621         if (defgroup == -1) {
622                 return 1.0f;
623         }
624         else if (dvert == NULL) {
625                 return 0.0f;
626         }
627
628         return defvert_find_weight(dvert + index, defgroup);
629 }
630
631
632 MDeformWeight *defvert_find_index(const MDeformVert *dvert, const int defgroup)
633 {
634         if (dvert && defgroup >= 0) {
635                 MDeformWeight *dw = dvert->dw;
636                 unsigned int i;
637
638                 for (i = dvert->totweight; i != 0; i--, dw++) {
639                         if (dw->def_nr == defgroup) {
640                                 return dw;
641                         }
642                 }
643         }
644         else {
645                 BLI_assert(0);
646         }
647
648         return NULL;
649 }
650
651 /**
652  * Ensures that mv has a deform weight entry for the specified defweight group.
653  *
654  * \note this function is mirrored in editmesh_tools.c, for use for editvertices.
655  */
656 MDeformWeight *defvert_verify_index(MDeformVert *dvert, const int defgroup)
657 {
658         MDeformWeight *dw_new;
659
660         /* do this check always, this function is used to check for it */
661         if (!dvert || defgroup < 0) {
662                 BLI_assert(0);
663                 return NULL;
664         }
665
666         dw_new = defvert_find_index(dvert, defgroup);
667         if (dw_new)
668                 return dw_new;
669
670         dw_new = MEM_mallocN(sizeof(MDeformWeight) * (dvert->totweight + 1), "deformWeight");
671         if (dvert->dw) {
672                 memcpy(dw_new, dvert->dw, sizeof(MDeformWeight) * dvert->totweight);
673                 MEM_freeN(dvert->dw);
674         }
675         dvert->dw = dw_new;
676         dw_new += dvert->totweight;
677         dw_new->weight = 0.0f;
678         dw_new->def_nr = defgroup;
679         /* Group index */
680
681         dvert->totweight++;
682
683         return dw_new;
684 }
685
686 /* TODO. merge with code above! */
687
688 /**
689  * Adds the given vertex to the specified vertex group, with given weight.
690  *
691  * \warning this does NOT check for existing, assume caller already knows its not there.
692  */
693 void defvert_add_index_notest(MDeformVert *dvert, int defgroup, const float weight)
694 {
695         MDeformWeight *dw_new;
696
697         /* do this check always, this function is used to check for it */
698         if (!dvert || defgroup < 0) {
699                 BLI_assert(0);
700                 return;
701         }
702
703         dw_new = MEM_callocN(sizeof(MDeformWeight) * (dvert->totweight + 1), "defvert_add_to group, new deformWeight");
704         if (dvert->dw) {
705                 memcpy(dw_new, dvert->dw, sizeof(MDeformWeight) * dvert->totweight);
706                 MEM_freeN(dvert->dw);
707         }
708         dvert->dw = dw_new;
709         dw_new += dvert->totweight;
710         dw_new->weight = weight;
711         dw_new->def_nr = defgroup;
712         dvert->totweight++;
713 }
714
715
716 /**
717  * Removes the given vertex from the vertex group.
718  *
719  * \warning This function frees the given MDeformWeight, do not use it afterward!
720  */
721 void defvert_remove_group(MDeformVert *dvert, MDeformWeight *dw)
722 {
723         if (dvert && dw) {
724                 int i = dw - dvert->dw;
725
726                 /* Security check! */
727                 if (i < 0 || i >= dvert->totweight) {
728                         return;
729                 }
730
731                 dvert->totweight--;
732                 /* If there are still other deform weights attached to this vert then remove
733                  * this deform weight, and reshuffle the others.
734                  */
735                 if (dvert->totweight) {
736                         BLI_assert(dvert->dw != NULL);
737
738                         if (i != dvert->totweight) {
739                                 dvert->dw[i] = dvert->dw[dvert->totweight];
740                         }
741
742                         dvert->dw = MEM_reallocN(dvert->dw, sizeof(MDeformWeight) * dvert->totweight);
743                 }
744                 else {
745                         /* If there are no other deform weights left then just remove this one. */
746                         MEM_freeN(dvert->dw);
747                         dvert->dw = NULL;
748                 }
749         }
750 }
751
752 void defvert_clear(MDeformVert *dvert)
753 {
754         if (dvert->dw) {
755                 MEM_freeN(dvert->dw);
756                 dvert->dw = NULL;
757         }
758
759         dvert->totweight = 0;
760 }
761
762 /**
763  * \return The first group index shared by both deform verts
764  * or -1 if none are found.
765  */
766 int defvert_find_shared(const MDeformVert *dvert_a, const MDeformVert *dvert_b)
767 {
768         if (dvert_a->totweight && dvert_b->totweight) {
769                 MDeformWeight *dw = dvert_a->dw;
770                 unsigned int i;
771
772                 for (i = dvert_a->totweight; i != 0; i--, dw++) {
773                         if (dw->weight > 0.0f && defvert_find_weight(dvert_b, dw->def_nr) > 0.0f) {
774                                 return dw->def_nr;
775                         }
776                 }
777         }
778
779         return -1;
780 }
781
782 /**
783  * return true if has no weights
784  */
785 bool defvert_is_weight_zero(const struct MDeformVert *dvert, const int defgroup_tot)
786 {
787         MDeformWeight *dw = dvert->dw;
788         unsigned int i;
789         for (i = dvert->totweight; i != 0; i--, dw++) {
790                 if (dw->weight != 0.0f) {
791                         /* check the group is in-range, happens on rare situations */
792                         if (LIKELY(dw->def_nr < defgroup_tot)) {
793                                 return false;
794                         }
795                 }
796         }
797         return true;
798 }
799
800
801 /**
802  * \return The representative weight of a multipaint group, used for
803  * viewport colors and actual painting.
804  *
805  * Result equal to sum of weights with auto normalize, and average otherwise.
806  * Value is not clamped, since painting relies on multiplication being always
807  * commutative with the collective weight function.
808  */
809 float BKE_defvert_multipaint_collective_weight(
810         const struct MDeformVert *dv, int defbase_tot,
811         const bool *defbase_sel, int defbase_tot_sel, bool do_autonormalize)
812 {
813         int i;
814         float total = 0.0f;
815         const MDeformWeight *dw = dv->dw;
816
817         for (i = dv->totweight; i != 0; i--, dw++) {
818                 /* in multipaint, get the average if auto normalize is inactive
819                  * get the sum if it is active */
820                 if (dw->def_nr < defbase_tot) {
821                         if (defbase_sel[dw->def_nr]) {
822                                 total += dw->weight;
823                         }
824                 }
825         }
826
827         if (do_autonormalize == false) {
828                 total /= defbase_tot_sel;
829         }
830
831         return total;
832 }
833
834
835 /* -------------------------------------------------------------------- */
836
837 /** \name Defvert Array functions
838  * \{ */
839
840 void BKE_defvert_array_copy(MDeformVert *dst, const MDeformVert *src, int copycount)
841 {
842         /* Assumes dst is already set up */
843         int i;
844
845         if (!src || !dst)
846                 return;
847
848         memcpy(dst, src, copycount * sizeof(MDeformVert));
849
850         for (i = 0; i < copycount; i++) {
851                 if (src[i].dw) {
852                         dst[i].dw = MEM_mallocN(sizeof(MDeformWeight) * src[i].totweight, "copy_deformWeight");
853                         memcpy(dst[i].dw, src[i].dw, sizeof(MDeformWeight) * src[i].totweight);
854                 }
855         }
856
857 }
858
859 void BKE_defvert_array_free_elems(MDeformVert *dvert, int totvert)
860 {
861         /* Instead of freeing the verts directly,
862          * call this function to delete any special
863          * vert data */
864         int i;
865
866         if (!dvert)
867                 return;
868
869         /* Free any special data from the verts */
870         for (i = 0; i < totvert; i++) {
871                 if (dvert[i].dw) MEM_freeN(dvert[i].dw);
872         }
873 }
874
875 void BKE_defvert_array_free(MDeformVert *dvert, int totvert)
876 {
877         /* Instead of freeing the verts directly,
878          * call this function to delete any special
879          * vert data */
880         if (!dvert)
881                 return;
882
883         /* Free any special data from the verts */
884         BKE_defvert_array_free_elems(dvert, totvert);
885
886         MEM_freeN(dvert);
887 }
888
889 void BKE_defvert_extract_vgroup_to_vertweights(
890         MDeformVert *dvert, const int defgroup, const int num_verts, float *r_weights, const bool invert_vgroup)
891 {
892         if (dvert && defgroup != -1) {
893                 int i = num_verts;
894
895                 while (i--) {
896                         const float w = defvert_find_weight(&dvert[i], defgroup);
897                         r_weights[i] = invert_vgroup ? (1.0f - w) : w;
898                 }
899         }
900         else {
901                 copy_vn_fl(r_weights, num_verts, invert_vgroup ? 1.0f : 0.0f);
902         }
903 }
904
905 /**
906  * The following three make basic interpolation,
907  * using temp vert_weights array to avoid looking up same weight several times.
908  */
909 void BKE_defvert_extract_vgroup_to_edgeweights(
910         MDeformVert *dvert, const int defgroup, const int num_verts, MEdge *edges, const int num_edges,
911         float *r_weights, const bool invert_vgroup)
912 {
913         if (dvert && defgroup != -1) {
914                 int i = num_edges;
915                 float *tmp_weights = MEM_mallocN(sizeof(*tmp_weights) * (size_t)num_verts, __func__);
916
917                 BKE_defvert_extract_vgroup_to_vertweights(dvert, defgroup, num_verts, tmp_weights, invert_vgroup);
918
919                 while (i--) {
920                         MEdge *me = &edges[i];
921
922                         r_weights[i] = (tmp_weights[me->v1] + tmp_weights[me->v2]) * 0.5f;
923                 }
924
925                 MEM_freeN(tmp_weights);
926         }
927         else {
928                 copy_vn_fl(r_weights, num_edges, 0.0f);
929         }
930 }
931
932 void BKE_defvert_extract_vgroup_to_loopweights(
933         MDeformVert *dvert, const int defgroup, const int num_verts, MLoop *loops, const int num_loops,
934         float *r_weights, const bool invert_vgroup)
935 {
936         if (dvert && defgroup != -1) {
937                 int i = num_loops;
938                 float *tmp_weights = MEM_mallocN(sizeof(*tmp_weights) * (size_t)num_verts, __func__);
939
940                 BKE_defvert_extract_vgroup_to_vertweights(dvert, defgroup, num_verts, tmp_weights, invert_vgroup);
941
942                 while (i--) {
943                         MLoop *ml = &loops[i];
944
945                         r_weights[i] = tmp_weights[ml->v];
946                 }
947
948                 MEM_freeN(tmp_weights);
949         }
950         else {
951                 copy_vn_fl(r_weights, num_loops, 0.0f);
952         }
953 }
954
955 void BKE_defvert_extract_vgroup_to_polyweights(
956         MDeformVert *dvert, const int defgroup, const int num_verts, MLoop *loops, const int UNUSED(num_loops),
957         MPoly *polys, const int num_polys, float *r_weights, const bool invert_vgroup)
958 {
959         if (dvert && defgroup != -1) {
960                 int i = num_polys;
961                 float *tmp_weights = MEM_mallocN(sizeof(*tmp_weights) * (size_t)num_verts, __func__);
962
963                 BKE_defvert_extract_vgroup_to_vertweights(dvert, defgroup, num_verts, tmp_weights, invert_vgroup);
964
965                 while (i--) {
966                         MPoly *mp = &polys[i];
967                         MLoop *ml = &loops[mp->loopstart];
968                         int j = mp->totloop;
969                         float w = 0.0f;
970
971                         for (; j--; ml++) {
972                                 w += tmp_weights[ml->v];
973                         }
974                         r_weights[i] = w / (float)mp->totloop;
975                 }
976
977                 MEM_freeN(tmp_weights);
978         }
979         else {
980                 copy_vn_fl(r_weights, num_polys, 0.0f);
981         }
982 }
983
984 /** \} */
985
986
987 /* -------------------------------------------------------------------- */
988
989 /** \name Data Transfer
990  * \{ */
991
992 static void vgroups_datatransfer_interp(
993         const CustomDataTransferLayerMap *laymap, void *dest,
994         const void **sources, const float *weights, const int count, const float mix_factor)
995 {
996         MDeformVert **data_src = (MDeformVert **)sources;
997         MDeformVert *data_dst = (MDeformVert *)dest;
998         const int idx_src = laymap->data_src_n;
999         const int idx_dst = laymap->data_dst_n;
1000
1001         const int mix_mode = laymap->mix_mode;
1002
1003         int i, j;
1004
1005         MDeformWeight *dw_src;
1006         MDeformWeight *dw_dst = defvert_find_index(data_dst, idx_dst);
1007         float weight_src = 0.0f, weight_dst = 0.0f;
1008
1009         if (sources) {
1010                 for (i = count; i--;) {
1011                         for (j = data_src[i]->totweight; j--;) {
1012                                 if ((dw_src = &data_src[i]->dw[j])->def_nr == idx_src) {
1013                                         weight_src += dw_src->weight * weights[i];
1014                                         break;
1015                                 }
1016                         }
1017                 }
1018         }
1019
1020         if (dw_dst) {
1021                 weight_dst = dw_dst->weight;
1022         }
1023         else if (mix_mode == CDT_MIX_REPLACE_ABOVE_THRESHOLD) {
1024                 return;  /* Do not affect destination. */
1025         }
1026
1027         weight_src = data_transfer_interp_float_do(mix_mode, weight_dst, weight_src, mix_factor);
1028
1029         CLAMP(weight_src, 0.0f, 1.0f);
1030
1031         if (!dw_dst) {
1032                 defvert_add_index_notest(data_dst, idx_dst, weight_src);
1033         }
1034         else {
1035                 dw_dst->weight = weight_src;
1036         }
1037 }
1038
1039 static bool data_transfer_layersmapping_vgroups_multisrc_to_dst(
1040         ListBase *r_map, const int mix_mode, const float mix_factor, const float *mix_weights,
1041         const int num_elem_dst, const bool use_create, const bool use_delete,
1042         Object *ob_src, Object *ob_dst, MDeformVert *data_src, MDeformVert *data_dst,
1043         CustomData *UNUSED(cd_src), CustomData *cd_dst, const bool UNUSED(use_dupref_dst),
1044         const int tolayers, bool *use_layers_src, const int num_layers_src)
1045 {
1046         int idx_src;
1047         int idx_dst;
1048         int tot_dst = BLI_listbase_count(&ob_dst->defbase);
1049
1050         const size_t elem_size = sizeof(*((MDeformVert *)NULL));
1051
1052         switch (tolayers) {
1053                 case DT_LAYERS_INDEX_DST:
1054                         idx_dst = tot_dst;
1055
1056                         /* Find last source actually used! */
1057                         idx_src = num_layers_src;
1058                         while (idx_src-- && !use_layers_src[idx_src]);
1059                         idx_src++;
1060
1061                         if (idx_dst < idx_src) {
1062                                 if (!use_create) {
1063                                         return false;
1064                                 }
1065                                 /* Create as much vgroups as necessary! */
1066                                 for (; idx_dst < idx_src; idx_dst++) {
1067                                         BKE_object_defgroup_add(ob_dst);
1068                                 }
1069                         }
1070                         else if (use_delete && idx_dst > idx_src) {
1071                                 while (idx_dst-- > idx_src) {
1072                                         BKE_object_defgroup_remove(ob_dst, ob_dst->defbase.last);
1073                                 }
1074                         }
1075                         if (r_map) {
1076                                 /* At this stage, we **need** a valid CD_MDEFORMVERT layer on dest!
1077                                  * Again, use_create is not relevant in this case */
1078                                 if (!data_dst) {
1079                                         data_dst = CustomData_add_layer(cd_dst, CD_MDEFORMVERT, CD_CALLOC, NULL, num_elem_dst);
1080                                 }
1081
1082                                 while (idx_src--) {
1083                                         if (!use_layers_src[idx_src]) {
1084                                                 continue;
1085                                         }
1086                                         data_transfer_layersmapping_add_item(r_map, CD_FAKE_MDEFORMVERT, mix_mode, mix_factor, mix_weights,
1087                                                                              data_src, data_dst, idx_src, idx_src,
1088                                                                              elem_size, 0, 0, 0, vgroups_datatransfer_interp, NULL);
1089                                 }
1090                         }
1091                         break;
1092                 case DT_LAYERS_NAME_DST:
1093                         {
1094                                 bDeformGroup *dg_src, *dg_dst;
1095
1096                                 if (use_delete) {
1097                                         /* Remove all unused dst vgroups first, simpler in this case. */
1098                                         for (dg_dst = ob_dst->defbase.first; dg_dst;) {
1099                                                 bDeformGroup *dg_dst_next = dg_dst->next;
1100
1101                                                 if (defgroup_name_index(ob_src, dg_dst->name) == -1) {
1102                                                         BKE_object_defgroup_remove(ob_dst, dg_dst);
1103                                                 }
1104                                                 dg_dst = dg_dst_next;
1105                                         }
1106                                 }
1107
1108                                 for (idx_src = 0, dg_src = ob_src->defbase.first;
1109                                      idx_src < num_layers_src;
1110                                      idx_src++, dg_src = dg_src->next)
1111                                 {
1112                                         if (!use_layers_src[idx_src]) {
1113                                                 continue;
1114                                         }
1115
1116                                         if ((idx_dst = defgroup_name_index(ob_dst, dg_src->name)) == -1) {
1117                                                 if (!use_create) {
1118                                                         if (r_map) {
1119                                                                 BLI_freelistN(r_map);
1120                                                         }
1121                                                         return false;
1122                                                 }
1123                                                 BKE_object_defgroup_add_name(ob_dst, dg_src->name);
1124                                                 idx_dst = ob_dst->actdef - 1;
1125                                         }
1126                                         if (r_map) {
1127                                                 /* At this stage, we **need** a valid CD_MDEFORMVERT layer on dest!
1128                                                  * use_create is not relevant in this case */
1129                                                 if (!data_dst) {
1130                                                         data_dst = CustomData_add_layer(cd_dst, CD_MDEFORMVERT, CD_CALLOC, NULL, num_elem_dst);
1131                                                 }
1132
1133                                                 data_transfer_layersmapping_add_item(
1134                                                         r_map, CD_FAKE_MDEFORMVERT, mix_mode, mix_factor, mix_weights,
1135                                                         data_src, data_dst, idx_src, idx_dst,
1136                                                         elem_size, 0, 0, 0, vgroups_datatransfer_interp, NULL);
1137                                         }
1138                                 }
1139                                 break;
1140                         }
1141                 default:
1142                         return false;
1143         }
1144
1145         return true;
1146 }
1147
1148 bool data_transfer_layersmapping_vgroups(
1149         ListBase *r_map, const int mix_mode, const float mix_factor, const float *mix_weights,
1150         const int num_elem_dst, const bool use_create, const bool use_delete, Object *ob_src, Object *ob_dst,
1151         CustomData *cd_src, CustomData *cd_dst, const bool use_dupref_dst, const int fromlayers, const int tolayers)
1152 {
1153         int idx_src, idx_dst;
1154         MDeformVert *data_src, *data_dst = NULL;
1155
1156         const size_t elem_size = sizeof(*((MDeformVert *)NULL));
1157
1158         /* Note: VGroups are a bit hairy, since their layout is defined on object level (ob->defbase), while their actual
1159          *       data is a (mesh) CD layer.
1160          *       This implies we may have to handle data layout itself while having NULL data itself,
1161          *       and even have to support NULL data_src in transfer data code (we always create a data_dst, though).
1162          */
1163
1164         if (BLI_listbase_is_empty(&ob_src->defbase)) {
1165                 if (use_delete) {
1166                         BKE_object_defgroup_remove_all(ob_dst);
1167                 }
1168                 return true;
1169         }
1170
1171         data_src = CustomData_get_layer(cd_src, CD_MDEFORMVERT);
1172
1173         data_dst = CustomData_get_layer(cd_dst, CD_MDEFORMVERT);
1174         if (data_dst && use_dupref_dst && r_map) {
1175                 /* If dest is a derivedmesh, we do not want to overwrite cdlayers of org mesh! */
1176                 data_dst = CustomData_duplicate_referenced_layer(cd_dst, CD_MDEFORMVERT, num_elem_dst);
1177         }
1178
1179         if (fromlayers == DT_LAYERS_ACTIVE_SRC || fromlayers >= 0) {
1180                 /* Note: use_delete has not much meaning in this case, ignored. */
1181
1182                 if (fromlayers >= 0) {
1183                         idx_src = fromlayers;
1184                         if (idx_src >= BLI_listbase_count(&ob_src->defbase)) {
1185                                 /* This can happen when vgroups are removed from source object...
1186                                  * Remapping would be really tricky here, we'd need to go over all objects in Main everytime we delete
1187                                  * a vgroup... for now, simpler and safer to abort. */
1188                                 return false;
1189                         }
1190                 }
1191                 else if ((idx_src = ob_src->actdef - 1) == -1) {
1192                         return false;
1193                 }
1194
1195                 if (tolayers >= 0) {
1196                         /* Note: in this case we assume layer exists! */
1197                         idx_dst = tolayers;
1198                         BLI_assert(idx_dst < BLI_listbase_count(&ob_dst->defbase));
1199                 }
1200                 else if (tolayers == DT_LAYERS_ACTIVE_DST) {
1201                         if ((idx_dst = ob_dst->actdef - 1) == -1) {
1202                                 bDeformGroup *dg_src;
1203                                 if (!use_create) {
1204                                         return true;
1205                                 }
1206                                 dg_src = BLI_findlink(&ob_src->defbase, idx_src);
1207                                 BKE_object_defgroup_add_name(ob_dst, dg_src->name);
1208                                 idx_dst = ob_dst->actdef - 1;
1209                         }
1210                 }
1211                 else if (tolayers == DT_LAYERS_INDEX_DST) {
1212                         int num = BLI_listbase_count(&ob_src->defbase);
1213                         idx_dst = idx_src;
1214                         if (num <= idx_dst) {
1215                                 if (!use_create) {
1216                                         return true;
1217                                 }
1218                                 /* Create as much vgroups as necessary! */
1219                                 for (; num <= idx_dst; num++) {
1220                                         BKE_object_defgroup_add(ob_dst);
1221                                 }
1222                         }
1223                 }
1224                 else if (tolayers == DT_LAYERS_NAME_DST) {
1225                         bDeformGroup *dg_src = BLI_findlink(&ob_src->defbase, idx_src);
1226                         if ((idx_dst = defgroup_name_index(ob_dst, dg_src->name)) == -1) {
1227                                 if (!use_create) {
1228                                         return true;
1229                                 }
1230                                 BKE_object_defgroup_add_name(ob_dst, dg_src->name);
1231                                 idx_dst = ob_dst->actdef - 1;
1232                         }
1233                 }
1234                 else {
1235                         return false;
1236                 }
1237
1238                 if (r_map) {
1239                         /* At this stage, we **need** a valid CD_MDEFORMVERT layer on dest!
1240                          * use_create is not relevant in this case */
1241                         if (!data_dst) {
1242                                 data_dst = CustomData_add_layer(cd_dst, CD_MDEFORMVERT, CD_CALLOC, NULL, num_elem_dst);
1243                         }
1244
1245                         data_transfer_layersmapping_add_item(r_map, CD_FAKE_MDEFORMVERT, mix_mode, mix_factor, mix_weights,
1246                                                              data_src, data_dst, idx_src, idx_dst,
1247                                                              elem_size, 0, 0, 0, vgroups_datatransfer_interp, NULL);
1248                 }
1249         }
1250         else {
1251                 int num_src, num_sel_unused;
1252                 bool *use_layers_src = NULL;
1253                 bool ret = false;
1254
1255                 switch (fromlayers) {
1256                         case DT_LAYERS_ALL_SRC:
1257                                 use_layers_src = BKE_object_defgroup_subset_from_select_type(ob_src, WT_VGROUP_ALL,
1258                                                                                              &num_src, &num_sel_unused);
1259                                 break;
1260                         case DT_LAYERS_VGROUP_SRC_BONE_SELECT:
1261                                 use_layers_src = BKE_object_defgroup_subset_from_select_type(ob_src, WT_VGROUP_BONE_SELECT,
1262                                                                                              &num_src, &num_sel_unused);
1263                                 break;
1264                         case DT_LAYERS_VGROUP_SRC_BONE_DEFORM:
1265                                 use_layers_src = BKE_object_defgroup_subset_from_select_type(ob_src, WT_VGROUP_BONE_DEFORM,
1266                                                                                              &num_src, &num_sel_unused);
1267                                 break;
1268                 }
1269
1270                 if (use_layers_src) {
1271                         ret = data_transfer_layersmapping_vgroups_multisrc_to_dst(
1272                                 r_map, mix_mode, mix_factor, mix_weights, num_elem_dst, use_create, use_delete,
1273                                 ob_src, ob_dst, data_src, data_dst, cd_src, cd_dst, use_dupref_dst,
1274                                 tolayers, use_layers_src, num_src);
1275                 }
1276
1277                 MEM_SAFE_FREE(use_layers_src);
1278                 return ret;
1279         }
1280
1281         return true;
1282 }
1283
1284 /** \} */