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
21  * \ingroup bke
22  */
23 
24 #include <math.h>
25 #include <stddef.h>
26 #include <string.h>
27 
28 #include "MEM_guardedalloc.h"
29 
30 #include "BLI_blenlib.h"
31 #include "BLI_endian_switch.h"
32 #include "BLI_math_vector.h"
33 #include "BLI_string_utils.h"
34 #include "BLI_utildefines.h"
35 
36 #include "BLT_translation.h"
37 
38 /* Allow using deprecated functionality for .blend file I/O. */
39 #define DNA_DEPRECATED_ALLOW
40 
41 #include "DNA_ID.h"
42 #include "DNA_anim_types.h"
43 #include "DNA_key_types.h"
44 #include "DNA_lattice_types.h"
45 #include "DNA_mesh_types.h"
46 #include "DNA_meshdata_types.h"
47 #include "DNA_object_types.h"
48 #include "DNA_scene_types.h"
49 
50 #include "BKE_anim_data.h"
51 #include "BKE_curve.h"
52 #include "BKE_customdata.h"
53 #include "BKE_deform.h"
54 #include "BKE_editmesh.h"
55 #include "BKE_idtype.h"
56 #include "BKE_key.h"
57 #include "BKE_lattice.h"
58 #include "BKE_lib_id.h"
59 #include "BKE_lib_query.h"
60 #include "BKE_main.h"
61 #include "BKE_mesh.h"
62 #include "BKE_scene.h"
63 
64 #include "RNA_access.h"
65 
66 #include "BLO_read_write.h"
67 
shapekey_copy_data(Main * UNUSED (bmain),ID * id_dst,const ID * id_src,const int UNUSED (flag))68 static void shapekey_copy_data(Main *UNUSED(bmain),
69                                ID *id_dst,
70                                const ID *id_src,
71                                const int UNUSED(flag))
72 {
73   Key *key_dst = (Key *)id_dst;
74   const Key *key_src = (const Key *)id_src;
75   BLI_duplicatelist(&key_dst->block, &key_src->block);
76 
77   KeyBlock *kb_dst, *kb_src;
78   for (kb_src = key_src->block.first, kb_dst = key_dst->block.first; kb_dst;
79        kb_src = kb_src->next, kb_dst = kb_dst->next) {
80     if (kb_dst->data) {
81       kb_dst->data = MEM_dupallocN(kb_dst->data);
82     }
83     if (kb_src == key_src->refkey) {
84       key_dst->refkey = kb_dst;
85     }
86   }
87 }
88 
shapekey_free_data(ID * id)89 static void shapekey_free_data(ID *id)
90 {
91   Key *key = (Key *)id;
92   KeyBlock *kb;
93 
94   while ((kb = BLI_pophead(&key->block))) {
95     if (kb->data) {
96       MEM_freeN(kb->data);
97     }
98     MEM_freeN(kb);
99   }
100 }
101 
shapekey_foreach_id(ID * id,LibraryForeachIDData * data)102 static void shapekey_foreach_id(ID *id, LibraryForeachIDData *data)
103 {
104   Key *key = (Key *)id;
105   BKE_LIB_FOREACHID_PROCESS_ID(data, key->from, IDWALK_CB_LOOPBACK);
106 }
107 
shapekey_blend_write(BlendWriter * writer,ID * id,const void * id_address)108 static void shapekey_blend_write(BlendWriter *writer, ID *id, const void *id_address)
109 {
110   Key *key = (Key *)id;
111   if (key->id.us > 0 || BLO_write_is_undo(writer)) {
112     /* write LibData */
113     BLO_write_id_struct(writer, Key, id_address, &key->id);
114     BKE_id_blend_write(writer, &key->id);
115 
116     if (key->adt) {
117       BKE_animdata_blend_write(writer, key->adt);
118     }
119 
120     /* direct data */
121     LISTBASE_FOREACH (KeyBlock *, kb, &key->block) {
122       BLO_write_struct(writer, KeyBlock, kb);
123       if (kb->data) {
124         BLO_write_raw(writer, kb->totelem * key->elemsize, kb->data);
125       }
126     }
127   }
128 }
129 
130 /* old defines from DNA_ipo_types.h for data-type, stored in DNA - don't modify! */
131 #define IPO_FLOAT 4
132 #define IPO_BEZTRIPLE 100
133 #define IPO_BPOINT 101
134 
switch_endian_keyblock(Key * key,KeyBlock * kb)135 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
136 {
137   int elemsize = key->elemsize;
138   char *data = kb->data;
139 
140   for (int a = 0; a < kb->totelem; a++) {
141     const char *cp = key->elemstr;
142     char *poin = data;
143 
144     while (cp[0]) {    /* cp[0] == amount */
145       switch (cp[1]) { /* cp[1] = type */
146         case IPO_FLOAT:
147         case IPO_BPOINT:
148         case IPO_BEZTRIPLE: {
149           int b = cp[0];
150           BLI_endian_switch_float_array((float *)poin, b);
151           poin += sizeof(float) * b;
152           break;
153         }
154       }
155 
156       cp += 2;
157     }
158     data += elemsize;
159   }
160 }
161 
shapekey_blend_read_data(BlendDataReader * reader,ID * id)162 static void shapekey_blend_read_data(BlendDataReader *reader, ID *id)
163 {
164   Key *key = (Key *)id;
165   BLO_read_list(reader, &(key->block));
166 
167   BLO_read_data_address(reader, &key->adt);
168   BKE_animdata_blend_read_data(reader, key->adt);
169 
170   BLO_read_data_address(reader, &key->refkey);
171 
172   LISTBASE_FOREACH (KeyBlock *, kb, &key->block) {
173     BLO_read_data_address(reader, &kb->data);
174 
175     if (BLO_read_requires_endian_switch(reader)) {
176       switch_endian_keyblock(key, kb);
177     }
178   }
179 }
180 
shapekey_blend_read_lib(BlendLibReader * reader,ID * id)181 static void shapekey_blend_read_lib(BlendLibReader *reader, ID *id)
182 {
183   Key *key = (Key *)id;
184   BLI_assert((key->id.tag & LIB_TAG_EXTERN) == 0);
185 
186   BLO_read_id_address(reader, key->id.lib, &key->ipo); /* XXX deprecated - old animation system */
187   BLO_read_id_address(reader, key->id.lib, &key->from);
188 }
189 
shapekey_blend_read_expand(BlendExpander * expander,ID * id)190 static void shapekey_blend_read_expand(BlendExpander *expander, ID *id)
191 {
192   Key *key = (Key *)id;
193   BLO_expand(expander, key->ipo); /* XXX deprecated - old animation system */
194 }
195 
196 IDTypeInfo IDType_ID_KE = {
197     .id_code = ID_KE,
198     .id_filter = 0,
199     .main_listbase_index = INDEX_ID_KE,
200     .struct_size = sizeof(Key),
201     .name = "Key",
202     .name_plural = "shape_keys",
203     .translation_context = BLT_I18NCONTEXT_ID_SHAPEKEY,
204     .flags = IDTYPE_FLAGS_NO_LIBLINKING | IDTYPE_FLAGS_NO_MAKELOCAL,
205 
206     .init_data = NULL,
207     .copy_data = shapekey_copy_data,
208     .free_data = shapekey_free_data,
209     .make_local = NULL,
210     .foreach_id = shapekey_foreach_id,
211     .foreach_cache = NULL,
212 
213     .blend_write = shapekey_blend_write,
214     .blend_read_data = shapekey_blend_read_data,
215     .blend_read_lib = shapekey_blend_read_lib,
216     .blend_read_expand = shapekey_blend_read_expand,
217 };
218 
219 #define KEY_MODE_DUMMY 0 /* use where mode isn't checked for */
220 #define KEY_MODE_BPOINT 1
221 #define KEY_MODE_BEZTRIPLE 2
222 
223 /* Internal use only. */
224 typedef struct WeightsArrayCache {
225   int num_defgroup_weights;
226   float **defgroup_weights;
227 } WeightsArrayCache;
228 
229 /** Free (or release) any data used by this shapekey (does not free the key itself). */
BKE_key_free(Key * key)230 void BKE_key_free(Key *key)
231 {
232   shapekey_free_data(&key->id);
233 }
234 
BKE_key_free_nolib(Key * key)235 void BKE_key_free_nolib(Key *key)
236 {
237   KeyBlock *kb;
238 
239   while ((kb = BLI_pophead(&key->block))) {
240     if (kb->data) {
241       MEM_freeN(kb->data);
242     }
243     MEM_freeN(kb);
244   }
245 }
246 
BKE_key_add(Main * bmain,ID * id)247 Key *BKE_key_add(Main *bmain, ID *id) /* common function */
248 {
249   Key *key;
250   char *el;
251 
252   key = BKE_id_new(bmain, ID_KE, "Key");
253 
254   key->type = KEY_NORMAL;
255   key->from = id;
256 
257   key->uidgen = 1;
258 
259   /* XXX the code here uses some defines which will soon be deprecated... */
260   switch (GS(id->name)) {
261     case ID_ME:
262       el = key->elemstr;
263 
264       el[0] = KEYELEM_FLOAT_LEN_COORD;
265       el[1] = IPO_FLOAT;
266       el[2] = 0;
267 
268       key->elemsize = sizeof(float[KEYELEM_FLOAT_LEN_COORD]);
269 
270       break;
271     case ID_LT:
272       el = key->elemstr;
273 
274       el[0] = KEYELEM_FLOAT_LEN_COORD;
275       el[1] = IPO_FLOAT;
276       el[2] = 0;
277 
278       key->elemsize = sizeof(float[KEYELEM_FLOAT_LEN_COORD]);
279 
280       break;
281     case ID_CU:
282       el = key->elemstr;
283 
284       el[0] = KEYELEM_ELEM_SIZE_CURVE;
285       el[1] = IPO_BPOINT;
286       el[2] = 0;
287 
288       key->elemsize = sizeof(float[KEYELEM_ELEM_SIZE_CURVE]);
289 
290       break;
291 
292     default:
293       break;
294   }
295 
296   return key;
297 }
298 
299 /* Sort shape keys and Ipo curves after a change.  This assumes that at most
300  * one key was moved, which is a valid assumption for the places it's
301  * currently being called.
302  */
303 
BKE_key_sort(Key * key)304 void BKE_key_sort(Key *key)
305 {
306   KeyBlock *kb;
307   KeyBlock *kb2;
308 
309   /* locate the key which is out of position */
310   for (kb = key->block.first; kb; kb = kb->next) {
311     if ((kb->next) && (kb->pos > kb->next->pos)) {
312       break;
313     }
314   }
315 
316   /* if we find a key, move it */
317   if (kb) {
318     kb = kb->next; /* next key is the out-of-order one */
319     BLI_remlink(&key->block, kb);
320 
321     /* find the right location and insert before */
322     for (kb2 = key->block.first; kb2; kb2 = kb2->next) {
323       if (kb2->pos > kb->pos) {
324         BLI_insertlinkafter(&key->block, kb2->prev, kb);
325         break;
326       }
327     }
328   }
329 
330   /* new rule; first key is refkey, this to match drawing channels... */
331   key->refkey = key->block.first;
332 }
333 
334 /**************** do the key ****************/
335 
key_curve_position_weights(float t,float data[4],int type)336 void key_curve_position_weights(float t, float data[4], int type)
337 {
338   float t2, t3, fc;
339 
340   if (type == KEY_LINEAR) {
341     data[0] = 0.0f;
342     data[1] = -t + 1.0f;
343     data[2] = t;
344     data[3] = 0.0f;
345   }
346   else if (type == KEY_CARDINAL) {
347     t2 = t * t;
348     t3 = t2 * t;
349     fc = 0.71f;
350 
351     data[0] = -fc * t3 + 2.0f * fc * t2 - fc * t;
352     data[1] = (2.0f - fc) * t3 + (fc - 3.0f) * t2 + 1.0f;
353     data[2] = (fc - 2.0f) * t3 + (3.0f - 2.0f * fc) * t2 + fc * t;
354     data[3] = fc * t3 - fc * t2;
355   }
356   else if (type == KEY_BSPLINE) {
357     t2 = t * t;
358     t3 = t2 * t;
359 
360     data[0] = -0.16666666f * t3 + 0.5f * t2 - 0.5f * t + 0.16666666f;
361     data[1] = 0.5f * t3 - t2 + 0.66666666f;
362     data[2] = -0.5f * t3 + 0.5f * t2 + 0.5f * t + 0.16666666f;
363     data[3] = 0.16666666f * t3;
364   }
365   else if (type == KEY_CATMULL_ROM) {
366     t2 = t * t;
367     t3 = t2 * t;
368     fc = 0.5f;
369 
370     data[0] = -fc * t3 + 2.0f * fc * t2 - fc * t;
371     data[1] = (2.0f - fc) * t3 + (fc - 3.0f) * t2 + 1.0f;
372     data[2] = (fc - 2.0f) * t3 + (3.0f - 2.0f * fc) * t2 + fc * t;
373     data[3] = fc * t3 - fc * t2;
374   }
375 }
376 
377 /* first derivative */
key_curve_tangent_weights(float t,float data[4],int type)378 void key_curve_tangent_weights(float t, float data[4], int type)
379 {
380   float t2, fc;
381 
382   if (type == KEY_LINEAR) {
383     data[0] = 0.0f;
384     data[1] = -1.0f;
385     data[2] = 1.0f;
386     data[3] = 0.0f;
387   }
388   else if (type == KEY_CARDINAL) {
389     t2 = t * t;
390     fc = 0.71f;
391 
392     data[0] = -3.0f * fc * t2 + 4.0f * fc * t - fc;
393     data[1] = 3.0f * (2.0f - fc) * t2 + 2.0f * (fc - 3.0f) * t;
394     data[2] = 3.0f * (fc - 2.0f) * t2 + 2.0f * (3.0f - 2.0f * fc) * t + fc;
395     data[3] = 3.0f * fc * t2 - 2.0f * fc * t;
396   }
397   else if (type == KEY_BSPLINE) {
398     t2 = t * t;
399 
400     data[0] = -0.5f * t2 + t - 0.5f;
401     data[1] = 1.5f * t2 - t * 2.0f;
402     data[2] = -1.5f * t2 + t + 0.5f;
403     data[3] = 0.5f * t2;
404   }
405   else if (type == KEY_CATMULL_ROM) {
406     t2 = t * t;
407     fc = 0.5f;
408 
409     data[0] = -3.0f * fc * t2 + 4.0f * fc * t - fc;
410     data[1] = 3.0f * (2.0f - fc) * t2 + 2.0f * (fc - 3.0f) * t;
411     data[2] = 3.0f * (fc - 2.0f) * t2 + 2.0f * (3.0f - 2.0f * fc) * t + fc;
412     data[3] = 3.0f * fc * t2 - 2.0f * fc * t;
413   }
414 }
415 
416 /* second derivative */
key_curve_normal_weights(float t,float data[4],int type)417 void key_curve_normal_weights(float t, float data[4], int type)
418 {
419   float fc;
420 
421   if (type == KEY_LINEAR) {
422     data[0] = 0.0f;
423     data[1] = 0.0f;
424     data[2] = 0.0f;
425     data[3] = 0.0f;
426   }
427   else if (type == KEY_CARDINAL) {
428     fc = 0.71f;
429 
430     data[0] = -6.0f * fc * t + 4.0f * fc;
431     data[1] = 6.0f * (2.0f - fc) * t + 2.0f * (fc - 3.0f);
432     data[2] = 6.0f * (fc - 2.0f) * t + 2.0f * (3.0f - 2.0f * fc);
433     data[3] = 6.0f * fc * t - 2.0f * fc;
434   }
435   else if (type == KEY_BSPLINE) {
436     data[0] = -1.0f * t + 1.0f;
437     data[1] = 3.0f * t - 2.0f;
438     data[2] = -3.0f * t + 1.0f;
439     data[3] = 1.0f * t;
440   }
441   else if (type == KEY_CATMULL_ROM) {
442     fc = 0.5f;
443 
444     data[0] = -6.0f * fc * t + 4.0f * fc;
445     data[1] = 6.0f * (2.0f - fc) * t + 2.0f * (fc - 3.0f);
446     data[2] = 6.0f * (fc - 2.0f) * t + 2.0f * (3.0f - 2.0f * fc);
447     data[3] = 6.0f * fc * t - 2.0f * fc;
448   }
449 }
450 
setkeys(float fac,ListBase * lb,KeyBlock * k[],float t[4],int cycl)451 static int setkeys(float fac, ListBase *lb, KeyBlock *k[], float t[4], int cycl)
452 {
453   /* return 1 means k[2] is the position, return 0 means interpolate */
454   KeyBlock *k1, *firstkey;
455   float d, dpos, ofs = 0, lastpos;
456   short bsplinetype;
457 
458   firstkey = lb->first;
459   k1 = lb->last;
460   lastpos = k1->pos;
461   dpos = lastpos - firstkey->pos;
462 
463   if (fac < firstkey->pos) {
464     fac = firstkey->pos;
465   }
466   else if (fac > k1->pos) {
467     fac = k1->pos;
468   }
469 
470   k1 = k[0] = k[1] = k[2] = k[3] = firstkey;
471   t[0] = t[1] = t[2] = t[3] = k1->pos;
472 
473   /* if (fac < 0.0 || fac > 1.0) return 1; */
474 
475   if (k1->next == NULL) {
476     return 1;
477   }
478 
479   if (cycl) { /* pre-sort */
480     k[2] = k1->next;
481     k[3] = k[2]->next;
482     if (k[3] == NULL) {
483       k[3] = k1;
484     }
485     while (k1) {
486       if (k1->next == NULL) {
487         k[0] = k1;
488       }
489       k1 = k1->next;
490     }
491     /* k1 = k[1]; */ /* UNUSED */
492     t[0] = k[0]->pos;
493     t[1] += dpos;
494     t[2] = k[2]->pos + dpos;
495     t[3] = k[3]->pos + dpos;
496     fac += dpos;
497     ofs = dpos;
498     if (k[3] == k[1]) {
499       t[3] += dpos;
500       ofs = 2.0f * dpos;
501     }
502     if (fac < t[1]) {
503       fac += dpos;
504     }
505     k1 = k[3];
506   }
507   else { /* pre-sort */
508     k[2] = k1->next;
509     t[2] = k[2]->pos;
510     k[3] = k[2]->next;
511     if (k[3] == NULL) {
512       k[3] = k[2];
513     }
514     t[3] = k[3]->pos;
515     k1 = k[3];
516   }
517 
518   while (t[2] < fac) { /* find correct location */
519     if (k1->next == NULL) {
520       if (cycl) {
521         k1 = firstkey;
522         ofs += dpos;
523       }
524       else if (t[2] == t[3]) {
525         break;
526       }
527     }
528     else {
529       k1 = k1->next;
530     }
531 
532     t[0] = t[1];
533     k[0] = k[1];
534     t[1] = t[2];
535     k[1] = k[2];
536     t[2] = t[3];
537     k[2] = k[3];
538     t[3] = k1->pos + ofs;
539     k[3] = k1;
540 
541     if (ofs > 2.1f + lastpos) {
542       break;
543     }
544   }
545 
546   bsplinetype = 0;
547   if (k[1]->type == KEY_BSPLINE || k[2]->type == KEY_BSPLINE) {
548     bsplinetype = 1;
549   }
550 
551   if (cycl == 0) {
552     if (bsplinetype == 0) { /* B spline doesn't go through the control points */
553       if (fac <= t[1]) {    /* fac for 1st key */
554         t[2] = t[1];
555         k[2] = k[1];
556         return 1;
557       }
558       if (fac >= t[2]) { /* fac after 2nd key */
559         return 1;
560       }
561     }
562     else if (fac > t[2]) { /* last key */
563       fac = t[2];
564       k[3] = k[2];
565       t[3] = t[2];
566     }
567   }
568 
569   d = t[2] - t[1];
570   if (d == 0.0f) {
571     if (bsplinetype == 0) {
572       return 1; /* both keys equal */
573     }
574   }
575   else {
576     d = (fac - t[1]) / d;
577   }
578 
579   /* interpolation */
580   key_curve_position_weights(d, t, k[1]->type);
581 
582   if (k[1]->type != k[2]->type) {
583     float t_other[4];
584     key_curve_position_weights(d, t_other, k[2]->type);
585     interp_v4_v4v4(t, t, t_other, d);
586   }
587 
588   return 0;
589 }
590 
flerp(int tot,float * in,const float * f0,const float * f1,const float * f2,const float * f3,const float * t)591 static void flerp(int tot,
592                   float *in,
593                   const float *f0,
594                   const float *f1,
595                   const float *f2,
596                   const float *f3,
597                   const float *t)
598 {
599   int a;
600 
601   for (a = 0; a < tot; a++) {
602     in[a] = t[0] * f0[a] + t[1] * f1[a] + t[2] * f2[a] + t[3] * f3[a];
603   }
604 }
605 
rel_flerp(int tot,float * in,const float * ref,const float * out,float fac)606 static void rel_flerp(int tot, float *in, const float *ref, const float *out, float fac)
607 {
608   int a;
609 
610   for (a = 0; a < tot; a++) {
611     in[a] -= fac * (ref[a] - out[a]);
612   }
613 }
614 
key_block_get_data(Key * key,KeyBlock * actkb,KeyBlock * kb,char ** freedata)615 static char *key_block_get_data(Key *key, KeyBlock *actkb, KeyBlock *kb, char **freedata)
616 {
617   if (kb == actkb) {
618     /* this hack makes it possible to edit shape keys in
619      * edit mode with shape keys blending applied */
620     if (GS(key->from->name) == ID_ME) {
621       Mesh *me;
622       BMVert *eve;
623       BMIter iter;
624       float(*co)[3];
625       int a;
626 
627       me = (Mesh *)key->from;
628 
629       if (me->edit_mesh && me->edit_mesh->bm->totvert == kb->totelem) {
630         a = 0;
631         co = MEM_mallocN(sizeof(float[3]) * me->edit_mesh->bm->totvert, "key_block_get_data");
632 
633         BM_ITER_MESH (eve, &iter, me->edit_mesh->bm, BM_VERTS_OF_MESH) {
634           copy_v3_v3(co[a], eve->co);
635           a++;
636         }
637 
638         *freedata = (char *)co;
639         return (char *)co;
640       }
641     }
642   }
643 
644   *freedata = NULL;
645   return kb->data;
646 }
647 
648 /* currently only the first value of 'ofs' may be set. */
key_pointer_size(const Key * key,const int mode,int * poinsize,int * ofs,int * step)649 static bool key_pointer_size(const Key *key, const int mode, int *poinsize, int *ofs, int *step)
650 {
651   if (key->from == NULL) {
652     return false;
653   }
654 
655   *step = 1;
656 
657   switch (GS(key->from->name)) {
658     case ID_ME:
659       *ofs = sizeof(float[KEYELEM_FLOAT_LEN_COORD]);
660       *poinsize = *ofs;
661       break;
662     case ID_LT:
663       *ofs = sizeof(float[KEYELEM_FLOAT_LEN_COORD]);
664       *poinsize = *ofs;
665       break;
666     case ID_CU:
667       if (mode == KEY_MODE_BPOINT) {
668         *ofs = sizeof(float[KEYELEM_FLOAT_LEN_BPOINT]);
669         *step = KEYELEM_ELEM_LEN_BPOINT;
670       }
671       else {
672         *ofs = sizeof(float[KEYELEM_FLOAT_LEN_BEZTRIPLE]);
673         *step = KEYELEM_ELEM_LEN_BEZTRIPLE;
674       }
675       *poinsize = sizeof(float[KEYELEM_ELEM_SIZE_CURVE]);
676       break;
677     default:
678       BLI_assert(!"invalid 'key->from' ID type");
679       return false;
680   }
681 
682   return true;
683 }
684 
cp_key(const int start,int end,const int tot,char * poin,Key * key,KeyBlock * actkb,KeyBlock * kb,float * weights,const int mode)685 static void cp_key(const int start,
686                    int end,
687                    const int tot,
688                    char *poin,
689                    Key *key,
690                    KeyBlock *actkb,
691                    KeyBlock *kb,
692                    float *weights,
693                    const int mode)
694 {
695   float ktot = 0.0, kd = 0.0;
696   int elemsize, poinsize = 0, a, step, *ofsp, ofs[32], flagflo = 0;
697   char *k1, *kref, *freek1, *freekref;
698   char *cp, elemstr[8];
699 
700   /* currently always 0, in future key_pointer_size may assign */
701   ofs[1] = 0;
702 
703   if (!key_pointer_size(key, mode, &poinsize, &ofs[0], &step)) {
704     return;
705   }
706 
707   if (end > tot) {
708     end = tot;
709   }
710 
711   if (tot != kb->totelem) {
712     ktot = 0.0;
713     flagflo = 1;
714     if (kb->totelem) {
715       kd = kb->totelem / (float)tot;
716     }
717     else {
718       return;
719     }
720   }
721 
722   k1 = key_block_get_data(key, actkb, kb, &freek1);
723   kref = key_block_get_data(key, actkb, key->refkey, &freekref);
724 
725   /* this exception is needed curves with multiple splines */
726   if (start != 0) {
727 
728     poin += poinsize * start;
729 
730     if (flagflo) {
731       ktot += start * kd;
732       a = (int)floor(ktot);
733       if (a) {
734         ktot -= a;
735         k1 += a * key->elemsize;
736       }
737     }
738     else {
739       k1 += start * key->elemsize;
740     }
741   }
742 
743   if (mode == KEY_MODE_BEZTRIPLE) {
744     elemstr[0] = 1;
745     elemstr[1] = IPO_BEZTRIPLE;
746     elemstr[2] = 0;
747   }
748 
749   /* just do it here, not above! */
750   elemsize = key->elemsize * step;
751 
752   for (a = start; a < end; a += step) {
753     cp = key->elemstr;
754     if (mode == KEY_MODE_BEZTRIPLE) {
755       cp = elemstr;
756     }
757 
758     ofsp = ofs;
759 
760     while (cp[0]) {
761 
762       switch (cp[1]) {
763         case IPO_FLOAT:
764           if (weights) {
765             memcpy(poin, kref, sizeof(float[KEYELEM_FLOAT_LEN_COORD]));
766             if (*weights != 0.0f) {
767               rel_flerp(
768                   KEYELEM_FLOAT_LEN_COORD, (float *)poin, (float *)kref, (float *)k1, *weights);
769             }
770             weights++;
771           }
772           else {
773             memcpy(poin, k1, sizeof(float[KEYELEM_FLOAT_LEN_COORD]));
774           }
775           break;
776         case IPO_BPOINT:
777           memcpy(poin, k1, sizeof(float[KEYELEM_FLOAT_LEN_BPOINT]));
778           break;
779         case IPO_BEZTRIPLE:
780           memcpy(poin, k1, sizeof(float[KEYELEM_FLOAT_LEN_BEZTRIPLE]));
781           break;
782         default:
783           /* should never happen */
784           if (freek1) {
785             MEM_freeN(freek1);
786           }
787           if (freekref) {
788             MEM_freeN(freekref);
789           }
790           BLI_assert(!"invalid 'cp[1]'");
791           return;
792       }
793 
794       poin += *ofsp;
795       cp += 2;
796       ofsp++;
797     }
798 
799     /* are we going to be nasty? */
800     if (flagflo) {
801       ktot += kd;
802       while (ktot >= 1.0f) {
803         ktot -= 1.0f;
804         k1 += elemsize;
805         kref += elemsize;
806       }
807     }
808     else {
809       k1 += elemsize;
810       kref += elemsize;
811     }
812   }
813 
814   if (freek1) {
815     MEM_freeN(freek1);
816   }
817   if (freekref) {
818     MEM_freeN(freekref);
819   }
820 }
821 
cp_cu_key(Curve * cu,Key * key,KeyBlock * actkb,KeyBlock * kb,const int start,int end,char * out,const int tot)822 static void cp_cu_key(Curve *cu,
823                       Key *key,
824                       KeyBlock *actkb,
825                       KeyBlock *kb,
826                       const int start,
827                       int end,
828                       char *out,
829                       const int tot)
830 {
831   Nurb *nu;
832   int a, step, a1, a2;
833 
834   for (a = 0, nu = cu->nurb.first; nu; nu = nu->next, a += step) {
835     if (nu->bp) {
836       step = KEYELEM_ELEM_LEN_BPOINT * nu->pntsu * nu->pntsv;
837 
838       a1 = max_ii(a, start);
839       a2 = min_ii(a + step, end);
840 
841       if (a1 < a2) {
842         cp_key(a1, a2, tot, out, key, actkb, kb, NULL, KEY_MODE_BPOINT);
843       }
844     }
845     else if (nu->bezt) {
846       step = KEYELEM_ELEM_LEN_BEZTRIPLE * nu->pntsu;
847 
848       /* exception because keys prefer to work with complete blocks */
849       a1 = max_ii(a, start);
850       a2 = min_ii(a + step, end);
851 
852       if (a1 < a2) {
853         cp_key(a1, a2, tot, out, key, actkb, kb, NULL, KEY_MODE_BEZTRIPLE);
854       }
855     }
856     else {
857       step = 0;
858     }
859   }
860 }
861 
key_evaluate_relative(const int start,int end,const int tot,char * basispoin,Key * key,KeyBlock * actkb,float ** per_keyblock_weights,const int mode)862 static void key_evaluate_relative(const int start,
863                                   int end,
864                                   const int tot,
865                                   char *basispoin,
866                                   Key *key,
867                                   KeyBlock *actkb,
868                                   float **per_keyblock_weights,
869                                   const int mode)
870 {
871   KeyBlock *kb;
872   int *ofsp, ofs[3], elemsize, b, step;
873   char *cp, *poin, *reffrom, *from, elemstr[8];
874   int poinsize, keyblock_index;
875 
876   /* currently always 0, in future key_pointer_size may assign */
877   ofs[1] = 0;
878 
879   if (!key_pointer_size(key, mode, &poinsize, &ofs[0], &step)) {
880     return;
881   }
882 
883   if (end > tot) {
884     end = tot;
885   }
886 
887   /* in case of beztriple */
888   elemstr[0] = 1; /* nr of ipofloats */
889   elemstr[1] = IPO_BEZTRIPLE;
890   elemstr[2] = 0;
891 
892   /* just here, not above! */
893   elemsize = key->elemsize * step;
894 
895   /* step 1 init */
896   cp_key(start, end, tot, basispoin, key, actkb, key->refkey, NULL, mode);
897 
898   /* step 2: do it */
899 
900   for (kb = key->block.first, keyblock_index = 0; kb; kb = kb->next, keyblock_index++) {
901     if (kb != key->refkey) {
902       float icuval = kb->curval;
903 
904       /* only with value, and no difference allowed */
905       if (!(kb->flag & KEYBLOCK_MUTE) && icuval != 0.0f && kb->totelem == tot) {
906         KeyBlock *refb;
907         float weight,
908             *weights = per_keyblock_weights ? per_keyblock_weights[keyblock_index] : NULL;
909         char *freefrom = NULL;
910 
911         /* reference now can be any block */
912         refb = BLI_findlink(&key->block, kb->relative);
913         if (refb == NULL) {
914           continue;
915         }
916 
917         poin = basispoin;
918         from = key_block_get_data(key, actkb, kb, &freefrom);
919 
920         /* For meshes, use the original values instead of the bmesh values to
921          * maintain a constant offset. */
922         reffrom = refb->data;
923 
924         poin += start * poinsize;
925         reffrom += key->elemsize * start; /* key elemsize yes! */
926         from += key->elemsize * start;
927 
928         for (b = start; b < end; b += step) {
929 
930           weight = weights ? (*weights * icuval) : icuval;
931 
932           cp = key->elemstr;
933           if (mode == KEY_MODE_BEZTRIPLE) {
934             cp = elemstr;
935           }
936 
937           ofsp = ofs;
938 
939           while (cp[0]) { /* (cp[0] == amount) */
940 
941             switch (cp[1]) {
942               case IPO_FLOAT:
943                 rel_flerp(KEYELEM_FLOAT_LEN_COORD,
944                           (float *)poin,
945                           (float *)reffrom,
946                           (float *)from,
947                           weight);
948                 break;
949               case IPO_BPOINT:
950                 rel_flerp(KEYELEM_FLOAT_LEN_BPOINT,
951                           (float *)poin,
952                           (float *)reffrom,
953                           (float *)from,
954                           weight);
955                 break;
956               case IPO_BEZTRIPLE:
957                 rel_flerp(KEYELEM_FLOAT_LEN_BEZTRIPLE,
958                           (float *)poin,
959                           (float *)reffrom,
960                           (float *)from,
961                           weight);
962                 break;
963               default:
964                 /* should never happen */
965                 if (freefrom) {
966                   MEM_freeN(freefrom);
967                 }
968                 BLI_assert(!"invalid 'cp[1]'");
969                 return;
970             }
971 
972             poin += *ofsp;
973 
974             cp += 2;
975             ofsp++;
976           }
977 
978           reffrom += elemsize;
979           from += elemsize;
980 
981           if (weights) {
982             weights++;
983           }
984         }
985 
986         if (freefrom) {
987           MEM_freeN(freefrom);
988         }
989       }
990     }
991   }
992 }
993 
do_key(const int start,int end,const int tot,char * poin,Key * key,KeyBlock * actkb,KeyBlock ** k,float * t,const int mode)994 static void do_key(const int start,
995                    int end,
996                    const int tot,
997                    char *poin,
998                    Key *key,
999                    KeyBlock *actkb,
1000                    KeyBlock **k,
1001                    float *t,
1002                    const int mode)
1003 {
1004   float k1tot = 0.0, k2tot = 0.0, k3tot = 0.0, k4tot = 0.0;
1005   float k1d = 0.0, k2d = 0.0, k3d = 0.0, k4d = 0.0;
1006   int a, step, ofs[32], *ofsp;
1007   int flagdo = 15, flagflo = 0, elemsize, poinsize = 0;
1008   char *k1, *k2, *k3, *k4, *freek1, *freek2, *freek3, *freek4;
1009   char *cp, elemstr[8];
1010 
1011   /* currently always 0, in future key_pointer_size may assign */
1012   ofs[1] = 0;
1013 
1014   if (!key_pointer_size(key, mode, &poinsize, &ofs[0], &step)) {
1015     return;
1016   }
1017 
1018   if (end > tot) {
1019     end = tot;
1020   }
1021 
1022   k1 = key_block_get_data(key, actkb, k[0], &freek1);
1023   k2 = key_block_get_data(key, actkb, k[1], &freek2);
1024   k3 = key_block_get_data(key, actkb, k[2], &freek3);
1025   k4 = key_block_get_data(key, actkb, k[3], &freek4);
1026 
1027   /* Test for more or less points (per key!) */
1028   if (tot != k[0]->totelem) {
1029     k1tot = 0.0;
1030     flagflo |= 1;
1031     if (k[0]->totelem) {
1032       k1d = k[0]->totelem / (float)tot;
1033     }
1034     else {
1035       flagdo -= 1;
1036     }
1037   }
1038   if (tot != k[1]->totelem) {
1039     k2tot = 0.0;
1040     flagflo |= 2;
1041     if (k[0]->totelem) {
1042       k2d = k[1]->totelem / (float)tot;
1043     }
1044     else {
1045       flagdo -= 2;
1046     }
1047   }
1048   if (tot != k[2]->totelem) {
1049     k3tot = 0.0;
1050     flagflo |= 4;
1051     if (k[0]->totelem) {
1052       k3d = k[2]->totelem / (float)tot;
1053     }
1054     else {
1055       flagdo -= 4;
1056     }
1057   }
1058   if (tot != k[3]->totelem) {
1059     k4tot = 0.0;
1060     flagflo |= 8;
1061     if (k[0]->totelem) {
1062       k4d = k[3]->totelem / (float)tot;
1063     }
1064     else {
1065       flagdo -= 8;
1066     }
1067   }
1068 
1069   /* this exception is needed for curves with multiple splines */
1070   if (start != 0) {
1071 
1072     poin += poinsize * start;
1073 
1074     if (flagdo & 1) {
1075       if (flagflo & 1) {
1076         k1tot += start * k1d;
1077         a = (int)floor(k1tot);
1078         if (a) {
1079           k1tot -= a;
1080           k1 += a * key->elemsize;
1081         }
1082       }
1083       else {
1084         k1 += start * key->elemsize;
1085       }
1086     }
1087     if (flagdo & 2) {
1088       if (flagflo & 2) {
1089         k2tot += start * k2d;
1090         a = (int)floor(k2tot);
1091         if (a) {
1092           k2tot -= a;
1093           k2 += a * key->elemsize;
1094         }
1095       }
1096       else {
1097         k2 += start * key->elemsize;
1098       }
1099     }
1100     if (flagdo & 4) {
1101       if (flagflo & 4) {
1102         k3tot += start * k3d;
1103         a = (int)floor(k3tot);
1104         if (a) {
1105           k3tot -= a;
1106           k3 += a * key->elemsize;
1107         }
1108       }
1109       else {
1110         k3 += start * key->elemsize;
1111       }
1112     }
1113     if (flagdo & 8) {
1114       if (flagflo & 8) {
1115         k4tot += start * k4d;
1116         a = (int)floor(k4tot);
1117         if (a) {
1118           k4tot -= a;
1119           k4 += a * key->elemsize;
1120         }
1121       }
1122       else {
1123         k4 += start * key->elemsize;
1124       }
1125     }
1126   }
1127 
1128   /* in case of beztriple */
1129   elemstr[0] = 1; /* nr of ipofloats */
1130   elemstr[1] = IPO_BEZTRIPLE;
1131   elemstr[2] = 0;
1132 
1133   /* only here, not above! */
1134   elemsize = key->elemsize * step;
1135 
1136   for (a = start; a < end; a += step) {
1137     cp = key->elemstr;
1138     if (mode == KEY_MODE_BEZTRIPLE) {
1139       cp = elemstr;
1140     }
1141 
1142     ofsp = ofs;
1143 
1144     while (cp[0]) { /* (cp[0] == amount) */
1145 
1146       switch (cp[1]) {
1147         case IPO_FLOAT:
1148           flerp(KEYELEM_FLOAT_LEN_COORD,
1149                 (float *)poin,
1150                 (float *)k1,
1151                 (float *)k2,
1152                 (float *)k3,
1153                 (float *)k4,
1154                 t);
1155           break;
1156         case IPO_BPOINT:
1157           flerp(KEYELEM_FLOAT_LEN_BPOINT,
1158                 (float *)poin,
1159                 (float *)k1,
1160                 (float *)k2,
1161                 (float *)k3,
1162                 (float *)k4,
1163                 t);
1164           break;
1165         case IPO_BEZTRIPLE:
1166           flerp(KEYELEM_FLOAT_LEN_BEZTRIPLE,
1167                 (void *)poin,
1168                 (void *)k1,
1169                 (void *)k2,
1170                 (void *)k3,
1171                 (void *)k4,
1172                 t);
1173           break;
1174         default:
1175           /* should never happen */
1176           if (freek1) {
1177             MEM_freeN(freek1);
1178           }
1179           if (freek2) {
1180             MEM_freeN(freek2);
1181           }
1182           if (freek3) {
1183             MEM_freeN(freek3);
1184           }
1185           if (freek4) {
1186             MEM_freeN(freek4);
1187           }
1188           BLI_assert(!"invalid 'cp[1]'");
1189           return;
1190       }
1191 
1192       poin += *ofsp;
1193       cp += 2;
1194       ofsp++;
1195     }
1196     /* lets do it the difficult way: when keys have a different size */
1197     if (flagdo & 1) {
1198       if (flagflo & 1) {
1199         k1tot += k1d;
1200         while (k1tot >= 1.0f) {
1201           k1tot -= 1.0f;
1202           k1 += elemsize;
1203         }
1204       }
1205       else {
1206         k1 += elemsize;
1207       }
1208     }
1209     if (flagdo & 2) {
1210       if (flagflo & 2) {
1211         k2tot += k2d;
1212         while (k2tot >= 1.0f) {
1213           k2tot -= 1.0f;
1214           k2 += elemsize;
1215         }
1216       }
1217       else {
1218         k2 += elemsize;
1219       }
1220     }
1221     if (flagdo & 4) {
1222       if (flagflo & 4) {
1223         k3tot += k3d;
1224         while (k3tot >= 1.0f) {
1225           k3tot -= 1.0f;
1226           k3 += elemsize;
1227         }
1228       }
1229       else {
1230         k3 += elemsize;
1231       }
1232     }
1233     if (flagdo & 8) {
1234       if (flagflo & 8) {
1235         k4tot += k4d;
1236         while (k4tot >= 1.0f) {
1237           k4tot -= 1.0f;
1238           k4 += elemsize;
1239         }
1240       }
1241       else {
1242         k4 += elemsize;
1243       }
1244     }
1245   }
1246 
1247   if (freek1) {
1248     MEM_freeN(freek1);
1249   }
1250   if (freek2) {
1251     MEM_freeN(freek2);
1252   }
1253   if (freek3) {
1254     MEM_freeN(freek3);
1255   }
1256   if (freek4) {
1257     MEM_freeN(freek4);
1258   }
1259 }
1260 
get_weights_array(Object * ob,char * vgroup,WeightsArrayCache * cache)1261 static float *get_weights_array(Object *ob, char *vgroup, WeightsArrayCache *cache)
1262 {
1263   MDeformVert *dvert = NULL;
1264   BMEditMesh *em = NULL;
1265   BMIter iter;
1266   BMVert *eve;
1267   int totvert = 0, defgrp_index = 0;
1268 
1269   /* no vgroup string set? */
1270   if (vgroup[0] == 0) {
1271     return NULL;
1272   }
1273 
1274   /* gather dvert and totvert */
1275   if (ob->type == OB_MESH) {
1276     Mesh *me = ob->data;
1277     dvert = me->dvert;
1278     totvert = me->totvert;
1279 
1280     if (me->edit_mesh && me->edit_mesh->bm->totvert == totvert) {
1281       em = me->edit_mesh;
1282     }
1283   }
1284   else if (ob->type == OB_LATTICE) {
1285     Lattice *lt = ob->data;
1286     dvert = lt->dvert;
1287     totvert = lt->pntsu * lt->pntsv * lt->pntsw;
1288   }
1289 
1290   if (dvert == NULL) {
1291     return NULL;
1292   }
1293 
1294   /* find the group (weak loop-in-loop) */
1295   defgrp_index = BKE_object_defgroup_name_index(ob, vgroup);
1296   if (defgrp_index != -1) {
1297     float *weights;
1298 
1299     if (cache) {
1300       if (cache->defgroup_weights == NULL) {
1301         int num_defgroup = BLI_listbase_count(&ob->defbase);
1302         cache->defgroup_weights = MEM_callocN(sizeof(*cache->defgroup_weights) * num_defgroup,
1303                                               "cached defgroup weights");
1304         cache->num_defgroup_weights = num_defgroup;
1305       }
1306 
1307       if (cache->defgroup_weights[defgrp_index]) {
1308         return cache->defgroup_weights[defgrp_index];
1309       }
1310     }
1311 
1312     weights = MEM_mallocN(totvert * sizeof(float), "weights");
1313 
1314     if (em) {
1315       int i;
1316       const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
1317       BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
1318         dvert = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
1319         weights[i] = BKE_defvert_find_weight(dvert, defgrp_index);
1320       }
1321     }
1322     else {
1323       for (int i = 0; i < totvert; i++, dvert++) {
1324         weights[i] = BKE_defvert_find_weight(dvert, defgrp_index);
1325       }
1326     }
1327 
1328     if (cache) {
1329       cache->defgroup_weights[defgrp_index] = weights;
1330     }
1331 
1332     return weights;
1333   }
1334   return NULL;
1335 }
1336 
keyblock_get_per_block_weights(Object * ob,Key * key,WeightsArrayCache * cache)1337 static float **keyblock_get_per_block_weights(Object *ob, Key *key, WeightsArrayCache *cache)
1338 {
1339   KeyBlock *keyblock;
1340   float **per_keyblock_weights;
1341   int keyblock_index;
1342 
1343   per_keyblock_weights = MEM_mallocN(sizeof(*per_keyblock_weights) * key->totkey,
1344                                      "per keyblock weights");
1345 
1346   for (keyblock = key->block.first, keyblock_index = 0; keyblock;
1347        keyblock = keyblock->next, keyblock_index++) {
1348     per_keyblock_weights[keyblock_index] = get_weights_array(ob, keyblock->vgroup, cache);
1349   }
1350 
1351   return per_keyblock_weights;
1352 }
1353 
keyblock_free_per_block_weights(Key * key,float ** per_keyblock_weights,WeightsArrayCache * cache)1354 static void keyblock_free_per_block_weights(Key *key,
1355                                             float **per_keyblock_weights,
1356                                             WeightsArrayCache *cache)
1357 {
1358   int a;
1359 
1360   if (cache) {
1361     if (cache->num_defgroup_weights) {
1362       for (a = 0; a < cache->num_defgroup_weights; a++) {
1363         if (cache->defgroup_weights[a]) {
1364           MEM_freeN(cache->defgroup_weights[a]);
1365         }
1366       }
1367       MEM_freeN(cache->defgroup_weights);
1368     }
1369     cache->defgroup_weights = NULL;
1370   }
1371   else {
1372     for (a = 0; a < key->totkey; a++) {
1373       if (per_keyblock_weights[a]) {
1374         MEM_freeN(per_keyblock_weights[a]);
1375       }
1376     }
1377   }
1378 
1379   MEM_freeN(per_keyblock_weights);
1380 }
1381 
do_mesh_key(Object * ob,Key * key,char * out,const int tot)1382 static void do_mesh_key(Object *ob, Key *key, char *out, const int tot)
1383 {
1384   KeyBlock *k[4], *actkb = BKE_keyblock_from_object(ob);
1385   float t[4];
1386   int flag = 0;
1387 
1388   if (key->type == KEY_RELATIVE) {
1389     WeightsArrayCache cache = {0, NULL};
1390     float **per_keyblock_weights;
1391     per_keyblock_weights = keyblock_get_per_block_weights(ob, key, &cache);
1392     key_evaluate_relative(
1393         0, tot, tot, (char *)out, key, actkb, per_keyblock_weights, KEY_MODE_DUMMY);
1394     keyblock_free_per_block_weights(key, per_keyblock_weights, &cache);
1395   }
1396   else {
1397     const float ctime_scaled = key->ctime / 100.0f;
1398 
1399     flag = setkeys(ctime_scaled, &key->block, k, t, 0);
1400 
1401     if (flag == 0) {
1402       do_key(0, tot, tot, (char *)out, key, actkb, k, t, KEY_MODE_DUMMY);
1403     }
1404     else {
1405       cp_key(0, tot, tot, (char *)out, key, actkb, k[2], NULL, KEY_MODE_DUMMY);
1406     }
1407   }
1408 }
1409 
do_cu_key(Curve * cu,Key * key,KeyBlock * actkb,KeyBlock ** k,float * t,char * out,const int tot)1410 static void do_cu_key(
1411     Curve *cu, Key *key, KeyBlock *actkb, KeyBlock **k, float *t, char *out, const int tot)
1412 {
1413   Nurb *nu;
1414   int a, step;
1415 
1416   for (a = 0, nu = cu->nurb.first; nu; nu = nu->next, a += step) {
1417     if (nu->bp) {
1418       step = KEYELEM_ELEM_LEN_BPOINT * nu->pntsu * nu->pntsv;
1419       do_key(a, a + step, tot, out, key, actkb, k, t, KEY_MODE_BPOINT);
1420     }
1421     else if (nu->bezt) {
1422       step = KEYELEM_ELEM_LEN_BEZTRIPLE * nu->pntsu;
1423       do_key(a, a + step, tot, out, key, actkb, k, t, KEY_MODE_BEZTRIPLE);
1424     }
1425     else {
1426       step = 0;
1427     }
1428   }
1429 }
1430 
do_rel_cu_key(Curve * cu,Key * key,KeyBlock * actkb,char * out,const int tot)1431 static void do_rel_cu_key(Curve *cu, Key *key, KeyBlock *actkb, char *out, const int tot)
1432 {
1433   Nurb *nu;
1434   int a, step;
1435 
1436   for (a = 0, nu = cu->nurb.first; nu; nu = nu->next, a += step) {
1437     if (nu->bp) {
1438       step = KEYELEM_ELEM_LEN_BPOINT * nu->pntsu * nu->pntsv;
1439       key_evaluate_relative(a, a + step, tot, out, key, actkb, NULL, KEY_MODE_BPOINT);
1440     }
1441     else if (nu->bezt) {
1442       step = KEYELEM_ELEM_LEN_BEZTRIPLE * nu->pntsu;
1443       key_evaluate_relative(a, a + step, tot, out, key, actkb, NULL, KEY_MODE_BEZTRIPLE);
1444     }
1445     else {
1446       step = 0;
1447     }
1448   }
1449 }
1450 
do_curve_key(Object * ob,Key * key,char * out,const int tot)1451 static void do_curve_key(Object *ob, Key *key, char *out, const int tot)
1452 {
1453   Curve *cu = ob->data;
1454   KeyBlock *k[4], *actkb = BKE_keyblock_from_object(ob);
1455   float t[4];
1456   int flag = 0;
1457 
1458   if (key->type == KEY_RELATIVE) {
1459     do_rel_cu_key(cu, cu->key, actkb, out, tot);
1460   }
1461   else {
1462     const float ctime_scaled = key->ctime / 100.0f;
1463 
1464     flag = setkeys(ctime_scaled, &key->block, k, t, 0);
1465 
1466     if (flag == 0) {
1467       do_cu_key(cu, key, actkb, k, t, out, tot);
1468     }
1469     else {
1470       cp_cu_key(cu, key, actkb, k[2], 0, tot, out, tot);
1471     }
1472   }
1473 }
1474 
do_latt_key(Object * ob,Key * key,char * out,const int tot)1475 static void do_latt_key(Object *ob, Key *key, char *out, const int tot)
1476 {
1477   Lattice *lt = ob->data;
1478   KeyBlock *k[4], *actkb = BKE_keyblock_from_object(ob);
1479   float t[4];
1480   int flag;
1481 
1482   if (key->type == KEY_RELATIVE) {
1483     float **per_keyblock_weights;
1484     per_keyblock_weights = keyblock_get_per_block_weights(ob, key, NULL);
1485     key_evaluate_relative(
1486         0, tot, tot, (char *)out, key, actkb, per_keyblock_weights, KEY_MODE_DUMMY);
1487     keyblock_free_per_block_weights(key, per_keyblock_weights, NULL);
1488   }
1489   else {
1490     const float ctime_scaled = key->ctime / 100.0f;
1491 
1492     flag = setkeys(ctime_scaled, &key->block, k, t, 0);
1493 
1494     if (flag == 0) {
1495       do_key(0, tot, tot, (char *)out, key, actkb, k, t, KEY_MODE_DUMMY);
1496     }
1497     else {
1498       cp_key(0, tot, tot, (char *)out, key, actkb, k[2], NULL, KEY_MODE_DUMMY);
1499     }
1500   }
1501 
1502   if (lt->flag & LT_OUTSIDE) {
1503     outside_lattice(lt);
1504   }
1505 }
1506 
1507 /* returns key coordinates (+ tilt) when key applied, NULL otherwise */
BKE_key_evaluate_object_ex(Object * ob,int * r_totelem,float * arr,size_t arr_size)1508 float *BKE_key_evaluate_object_ex(Object *ob, int *r_totelem, float *arr, size_t arr_size)
1509 {
1510   Key *key = BKE_key_from_object(ob);
1511   KeyBlock *actkb = BKE_keyblock_from_object(ob);
1512   char *out;
1513   int tot = 0, size = 0;
1514 
1515   if (key == NULL || BLI_listbase_is_empty(&key->block)) {
1516     return NULL;
1517   }
1518 
1519   /* compute size of output array */
1520   if (ob->type == OB_MESH) {
1521     Mesh *me = ob->data;
1522 
1523     tot = me->totvert;
1524     size = tot * sizeof(float[KEYELEM_FLOAT_LEN_COORD]);
1525   }
1526   else if (ob->type == OB_LATTICE) {
1527     Lattice *lt = ob->data;
1528 
1529     tot = lt->pntsu * lt->pntsv * lt->pntsw;
1530     size = tot * sizeof(float[KEYELEM_FLOAT_LEN_COORD]);
1531   }
1532   else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
1533     Curve *cu = ob->data;
1534 
1535     tot = BKE_keyblock_curve_element_count(&cu->nurb);
1536     size = tot * sizeof(float[KEYELEM_ELEM_SIZE_CURVE]);
1537   }
1538 
1539   /* if nothing to interpolate, cancel */
1540   if (tot == 0 || size == 0) {
1541     return NULL;
1542   }
1543 
1544   /* allocate array */
1545   if (arr == NULL) {
1546     out = MEM_callocN(size, "BKE_key_evaluate_object out");
1547   }
1548   else {
1549     if (arr_size != size) {
1550       return NULL;
1551     }
1552 
1553     out = (char *)arr;
1554   }
1555 
1556   if (ob->shapeflag & OB_SHAPE_LOCK) {
1557     /* shape locked, copy the locked shape instead of blending */
1558     KeyBlock *kb = BLI_findlink(&key->block, ob->shapenr - 1);
1559 
1560     if (kb && (kb->flag & KEYBLOCK_MUTE)) {
1561       kb = key->refkey;
1562     }
1563 
1564     if (kb == NULL) {
1565       kb = key->block.first;
1566       ob->shapenr = 1;
1567     }
1568 
1569     if (OB_TYPE_SUPPORT_VGROUP(ob->type)) {
1570       float *weights = get_weights_array(ob, kb->vgroup, NULL);
1571 
1572       cp_key(0, tot, tot, out, key, actkb, kb, weights, 0);
1573 
1574       if (weights) {
1575         MEM_freeN(weights);
1576       }
1577     }
1578     else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
1579       cp_cu_key(ob->data, key, actkb, kb, 0, tot, out, tot);
1580     }
1581   }
1582   else {
1583 
1584     if (ob->type == OB_MESH) {
1585       do_mesh_key(ob, key, out, tot);
1586     }
1587     else if (ob->type == OB_LATTICE) {
1588       do_latt_key(ob, key, out, tot);
1589     }
1590     else if (ob->type == OB_CURVE) {
1591       do_curve_key(ob, key, out, tot);
1592     }
1593     else if (ob->type == OB_SURF) {
1594       do_curve_key(ob, key, out, tot);
1595     }
1596   }
1597 
1598   if (r_totelem) {
1599     *r_totelem = tot;
1600   }
1601   return (float *)out;
1602 }
1603 
BKE_key_evaluate_object(Object * ob,int * r_totelem)1604 float *BKE_key_evaluate_object(Object *ob, int *r_totelem)
1605 {
1606   return BKE_key_evaluate_object_ex(ob, r_totelem, NULL, 0);
1607 }
1608 
1609 /**
1610  * \param shape_index: The index to use or all (when -1).
1611  */
BKE_keyblock_element_count_from_shape(const Key * key,const int shape_index)1612 int BKE_keyblock_element_count_from_shape(const Key *key, const int shape_index)
1613 {
1614   int result = 0;
1615   int index = 0;
1616   for (const KeyBlock *kb = key->block.first; kb; kb = kb->next, index++) {
1617     if ((shape_index == -1) || (index == shape_index)) {
1618       result += kb->totelem;
1619     }
1620   }
1621   return result;
1622 }
1623 
BKE_keyblock_element_count(const Key * key)1624 int BKE_keyblock_element_count(const Key *key)
1625 {
1626   return BKE_keyblock_element_count_from_shape(key, -1);
1627 }
1628 
1629 /**
1630  * \param shape_index: The index to use or all (when -1).
1631  */
BKE_keyblock_element_calc_size_from_shape(const Key * key,const int shape_index)1632 size_t BKE_keyblock_element_calc_size_from_shape(const Key *key, const int shape_index)
1633 {
1634   return (size_t)BKE_keyblock_element_count_from_shape(key, shape_index) * key->elemsize;
1635 }
1636 
BKE_keyblock_element_calc_size(const Key * key)1637 size_t BKE_keyblock_element_calc_size(const Key *key)
1638 {
1639   return BKE_keyblock_element_calc_size_from_shape(key, -1);
1640 }
1641 
1642 /* -------------------------------------------------------------------- */
1643 /** \name Key-Block Data Access
1644  *
1645  * Utilities for getting/setting key data as a single array,
1646  * use #BKE_keyblock_element_calc_size to allocate the size of the data needed.
1647  * \{ */
1648 
1649 /**
1650  * \param shape_index: The index to use or all (when -1).
1651  */
BKE_keyblock_data_get_from_shape(const Key * key,float (* arr)[3],const int shape_index)1652 void BKE_keyblock_data_get_from_shape(const Key *key, float (*arr)[3], const int shape_index)
1653 {
1654   uint8_t *elements = (uint8_t *)arr;
1655   int index = 0;
1656   for (const KeyBlock *kb = key->block.first; kb; kb = kb->next, index++) {
1657     if ((shape_index == -1) || (index == shape_index)) {
1658       const int block_elem_len = kb->totelem * key->elemsize;
1659       memcpy(elements, kb->data, block_elem_len);
1660       elements += block_elem_len;
1661     }
1662   }
1663 }
1664 
BKE_keyblock_data_get(const Key * key,float (* arr)[3])1665 void BKE_keyblock_data_get(const Key *key, float (*arr)[3])
1666 {
1667   BKE_keyblock_data_get_from_shape(key, arr, -1);
1668 }
1669 
1670 /**
1671  * Set the data to all key-blocks (or shape_index if != -1).
1672  */
BKE_keyblock_data_set_with_mat4(Key * key,const int shape_index,const float (* coords)[3],const float mat[4][4])1673 void BKE_keyblock_data_set_with_mat4(Key *key,
1674                                      const int shape_index,
1675                                      const float (*coords)[3],
1676                                      const float mat[4][4])
1677 {
1678   if (key->elemsize != sizeof(float[3])) {
1679     BLI_assert(!"Invalid elemsize");
1680     return;
1681   }
1682 
1683   const float(*elements)[3] = coords;
1684 
1685   int index = 0;
1686   for (KeyBlock *kb = key->block.first; kb; kb = kb->next, index++) {
1687     if ((shape_index == -1) || (index == shape_index)) {
1688       const int block_elem_len = kb->totelem;
1689       float(*block_data)[3] = (float(*)[3])kb->data;
1690       for (int data_offset = 0; data_offset < block_elem_len; ++data_offset) {
1691         const float *src_data = (const float *)(elements + data_offset);
1692         float *dst_data = (float *)(block_data + data_offset);
1693         mul_v3_m4v3(dst_data, mat, src_data);
1694       }
1695       elements += block_elem_len;
1696     }
1697   }
1698 }
1699 
1700 /**
1701  * Set the data for all key-blocks (or shape_index if != -1),
1702  * transforming by \a mat.
1703  */
BKE_keyblock_curve_data_set_with_mat4(Key * key,const ListBase * nurb,const int shape_index,const void * data,const float mat[4][4])1704 void BKE_keyblock_curve_data_set_with_mat4(
1705     Key *key, const ListBase *nurb, const int shape_index, const void *data, const float mat[4][4])
1706 {
1707   const uint8_t *elements = data;
1708 
1709   int index = 0;
1710   for (KeyBlock *kb = key->block.first; kb; kb = kb->next, index++) {
1711     if ((shape_index == -1) || (index == shape_index)) {
1712       const int block_elem_size = kb->totelem * key->elemsize;
1713       BKE_keyblock_curve_data_transform(nurb, mat, elements, kb->data);
1714       elements += block_elem_size;
1715     }
1716   }
1717 }
1718 
1719 /**
1720  * Set the data for all key-blocks (or shape_index if != -1).
1721  */
BKE_keyblock_data_set(Key * key,const int shape_index,const void * data)1722 void BKE_keyblock_data_set(Key *key, const int shape_index, const void *data)
1723 {
1724   const uint8_t *elements = data;
1725   int index = 0;
1726   for (KeyBlock *kb = key->block.first; kb; kb = kb->next, index++) {
1727     if ((shape_index == -1) || (index == shape_index)) {
1728       const int block_elem_size = kb->totelem * key->elemsize;
1729       memcpy(kb->data, elements, block_elem_size);
1730       elements += block_elem_size;
1731     }
1732   }
1733 }
1734 
1735 /** \} */
1736 
BKE_key_idtype_support(const short id_type)1737 bool BKE_key_idtype_support(const short id_type)
1738 {
1739   switch (id_type) {
1740     case ID_ME:
1741     case ID_CU:
1742     case ID_LT:
1743       return true;
1744     default:
1745       return false;
1746   }
1747 }
1748 
BKE_key_from_id_p(ID * id)1749 Key **BKE_key_from_id_p(ID *id)
1750 {
1751   switch (GS(id->name)) {
1752     case ID_ME: {
1753       Mesh *me = (Mesh *)id;
1754       return &me->key;
1755     }
1756     case ID_CU: {
1757       Curve *cu = (Curve *)id;
1758       if (cu->vfont == NULL) {
1759         return &cu->key;
1760       }
1761       break;
1762     }
1763     case ID_LT: {
1764       Lattice *lt = (Lattice *)id;
1765       return &lt->key;
1766     }
1767     default:
1768       break;
1769   }
1770 
1771   return NULL;
1772 }
1773 
BKE_key_from_id(ID * id)1774 Key *BKE_key_from_id(ID *id)
1775 {
1776   Key **key_p;
1777   key_p = BKE_key_from_id_p(id);
1778   if (key_p) {
1779     return *key_p;
1780   }
1781 
1782   return NULL;
1783 }
1784 
BKE_key_from_object_p(const Object * ob)1785 Key **BKE_key_from_object_p(const Object *ob)
1786 {
1787   if (ob == NULL || ob->data == NULL) {
1788     return NULL;
1789   }
1790 
1791   return BKE_key_from_id_p(ob->data);
1792 }
1793 
BKE_key_from_object(const Object * ob)1794 Key *BKE_key_from_object(const Object *ob)
1795 {
1796   Key **key_p;
1797   key_p = BKE_key_from_object_p(ob);
1798   if (key_p) {
1799     return *key_p;
1800   }
1801 
1802   return NULL;
1803 }
1804 
BKE_keyblock_add(Key * key,const char * name)1805 KeyBlock *BKE_keyblock_add(Key *key, const char *name)
1806 {
1807   KeyBlock *kb;
1808   float curpos = -0.1;
1809   int tot;
1810 
1811   kb = key->block.last;
1812   if (kb) {
1813     curpos = kb->pos;
1814   }
1815 
1816   kb = MEM_callocN(sizeof(KeyBlock), "Keyblock");
1817   BLI_addtail(&key->block, kb);
1818   kb->type = KEY_LINEAR;
1819 
1820   tot = BLI_listbase_count(&key->block);
1821   if (name) {
1822     BLI_strncpy(kb->name, name, sizeof(kb->name));
1823   }
1824   else {
1825     if (tot == 1) {
1826       BLI_strncpy(kb->name, DATA_("Basis"), sizeof(kb->name));
1827     }
1828     else {
1829       BLI_snprintf(kb->name, sizeof(kb->name), DATA_("Key %d"), tot - 1);
1830     }
1831   }
1832 
1833   BLI_uniquename(&key->block, kb, DATA_("Key"), '.', offsetof(KeyBlock, name), sizeof(kb->name));
1834 
1835   kb->uid = key->uidgen++;
1836 
1837   key->totkey++;
1838   if (key->totkey == 1) {
1839     key->refkey = kb;
1840   }
1841 
1842   kb->slidermin = 0.0f;
1843   kb->slidermax = 1.0f;
1844 
1845   /**
1846    * \note caller may want to set this to current time, but don't do it here since we need to sort
1847    * which could cause problems in some cases, see #BKE_keyblock_add_ctime */
1848   kb->pos = curpos + 0.1f; /* only used for absolute shape keys */
1849 
1850   return kb;
1851 }
1852 
1853 /**
1854  * \note sorting is a problematic side effect in some cases,
1855  * better only do this explicitly by having its own function,
1856  *
1857  * \param key: The key datablock to add to.
1858  * \param name: Optional name for the new keyblock.
1859  * \param do_force: always use ctime even for relative keys.
1860  */
BKE_keyblock_add_ctime(Key * key,const char * name,const bool do_force)1861 KeyBlock *BKE_keyblock_add_ctime(Key *key, const char *name, const bool do_force)
1862 {
1863   KeyBlock *kb = BKE_keyblock_add(key, name);
1864   const float cpos = key->ctime / 100.0f;
1865 
1866   /* In case of absolute keys, there is no point in adding more than one key with the same pos.
1867    * Hence only set new keybloc pos to current time if none previous one already use it.
1868    * Now at least people just adding absolute keys without touching to ctime
1869    * won't have to systematically use retiming func (and have ordering issues, too). See T39897.
1870    */
1871   if (!do_force && (key->type != KEY_RELATIVE)) {
1872     KeyBlock *it_kb;
1873     for (it_kb = key->block.first; it_kb; it_kb = it_kb->next) {
1874       /* Use epsilon to avoid floating point precision issues.
1875        * 1e-3 because the position is stored as frame * 1e-2. */
1876       if (compare_ff(it_kb->pos, cpos, 1e-3f)) {
1877         return kb;
1878       }
1879     }
1880   }
1881   if (do_force || (key->type != KEY_RELATIVE)) {
1882     kb->pos = cpos;
1883     BKE_key_sort(key);
1884   }
1885 
1886   return kb;
1887 }
1888 
1889 /* only the active keyblock */
BKE_keyblock_from_object(Object * ob)1890 KeyBlock *BKE_keyblock_from_object(Object *ob)
1891 {
1892   Key *key = BKE_key_from_object(ob);
1893 
1894   if (key) {
1895     KeyBlock *kb = BLI_findlink(&key->block, ob->shapenr - 1);
1896     return kb;
1897   }
1898 
1899   return NULL;
1900 }
1901 
BKE_keyblock_from_object_reference(Object * ob)1902 KeyBlock *BKE_keyblock_from_object_reference(Object *ob)
1903 {
1904   Key *key = BKE_key_from_object(ob);
1905 
1906   if (key) {
1907     return key->refkey;
1908   }
1909 
1910   return NULL;
1911 }
1912 
1913 /* get the appropriate KeyBlock given an index */
BKE_keyblock_from_key(Key * key,int index)1914 KeyBlock *BKE_keyblock_from_key(Key *key, int index)
1915 {
1916   if (key) {
1917     KeyBlock *kb = key->block.first;
1918 
1919     for (int i = 1; i < key->totkey; i++) {
1920       kb = kb->next;
1921 
1922       if (index == i) {
1923         return kb;
1924       }
1925     }
1926   }
1927 
1928   return NULL;
1929 }
1930 
1931 /* get the appropriate KeyBlock given a name to search for */
BKE_keyblock_find_name(Key * key,const char name[])1932 KeyBlock *BKE_keyblock_find_name(Key *key, const char name[])
1933 {
1934   return BLI_findstring(&key->block, name, offsetof(KeyBlock, name));
1935 }
1936 
1937 /**
1938  * \brief copy shape-key attributes, but not key data.or name/uid
1939  */
BKE_keyblock_copy_settings(KeyBlock * kb_dst,const KeyBlock * kb_src)1940 void BKE_keyblock_copy_settings(KeyBlock *kb_dst, const KeyBlock *kb_src)
1941 {
1942   kb_dst->pos = kb_src->pos;
1943   kb_dst->curval = kb_src->curval;
1944   kb_dst->type = kb_src->type;
1945   kb_dst->relative = kb_src->relative;
1946   BLI_strncpy(kb_dst->vgroup, kb_src->vgroup, sizeof(kb_dst->vgroup));
1947   kb_dst->slidermin = kb_src->slidermin;
1948   kb_dst->slidermax = kb_src->slidermax;
1949 }
1950 
1951 /* Get RNA-Path for 'value' setting of the given ShapeKey
1952  * NOTE: the user needs to free the returned string once they're finish with it
1953  */
BKE_keyblock_curval_rnapath_get(Key * key,KeyBlock * kb)1954 char *BKE_keyblock_curval_rnapath_get(Key *key, KeyBlock *kb)
1955 {
1956   PointerRNA ptr;
1957   PropertyRNA *prop;
1958 
1959   /* sanity checks */
1960   if (ELEM(NULL, key, kb)) {
1961     return NULL;
1962   }
1963 
1964   /* create the RNA pointer */
1965   RNA_pointer_create(&key->id, &RNA_ShapeKey, kb, &ptr);
1966   /* get pointer to the property too */
1967   prop = RNA_struct_find_property(&ptr, "value");
1968 
1969   /* return the path */
1970   return RNA_path_from_ID_to_property(&ptr, prop);
1971 }
1972 
1973 /* conversion functions */
1974 
1975 /************************* Lattice ************************/
BKE_keyblock_update_from_lattice(Lattice * lt,KeyBlock * kb)1976 void BKE_keyblock_update_from_lattice(Lattice *lt, KeyBlock *kb)
1977 {
1978   BPoint *bp;
1979   float(*fp)[3];
1980   int a, tot;
1981 
1982   BLI_assert(kb->totelem == lt->pntsu * lt->pntsv * lt->pntsw);
1983 
1984   tot = kb->totelem;
1985   if (tot == 0) {
1986     return;
1987   }
1988 
1989   bp = lt->def;
1990   fp = kb->data;
1991   for (a = 0; a < kb->totelem; a++, fp++, bp++) {
1992     copy_v3_v3(*fp, bp->vec);
1993   }
1994 }
1995 
BKE_keyblock_convert_from_lattice(Lattice * lt,KeyBlock * kb)1996 void BKE_keyblock_convert_from_lattice(Lattice *lt, KeyBlock *kb)
1997 {
1998   int tot;
1999 
2000   tot = lt->pntsu * lt->pntsv * lt->pntsw;
2001   if (tot == 0) {
2002     return;
2003   }
2004 
2005   MEM_SAFE_FREE(kb->data);
2006 
2007   kb->data = MEM_mallocN(lt->key->elemsize * tot, __func__);
2008   kb->totelem = tot;
2009 
2010   BKE_keyblock_update_from_lattice(lt, kb);
2011 }
2012 
BKE_keyblock_convert_to_lattice(KeyBlock * kb,Lattice * lt)2013 void BKE_keyblock_convert_to_lattice(KeyBlock *kb, Lattice *lt)
2014 {
2015   BPoint *bp;
2016   const float(*fp)[3];
2017   int a, tot;
2018 
2019   bp = lt->def;
2020   fp = kb->data;
2021 
2022   tot = lt->pntsu * lt->pntsv * lt->pntsw;
2023   tot = min_ii(kb->totelem, tot);
2024 
2025   for (a = 0; a < tot; a++, fp++, bp++) {
2026     copy_v3_v3(bp->vec, *fp);
2027   }
2028 }
2029 
2030 /************************* Curve ************************/
2031 
BKE_keyblock_curve_element_count(ListBase * nurb)2032 int BKE_keyblock_curve_element_count(ListBase *nurb)
2033 {
2034   Nurb *nu;
2035   int tot = 0;
2036 
2037   nu = nurb->first;
2038   while (nu) {
2039     if (nu->bezt) {
2040       tot += KEYELEM_ELEM_LEN_BEZTRIPLE * nu->pntsu;
2041     }
2042     else if (nu->bp) {
2043       tot += KEYELEM_ELEM_LEN_BPOINT * nu->pntsu * nu->pntsv;
2044     }
2045 
2046     nu = nu->next;
2047   }
2048   return tot;
2049 }
2050 
BKE_keyblock_update_from_curve(Curve * UNUSED (cu),KeyBlock * kb,ListBase * nurb)2051 void BKE_keyblock_update_from_curve(Curve *UNUSED(cu), KeyBlock *kb, ListBase *nurb)
2052 {
2053   Nurb *nu;
2054   BezTriple *bezt;
2055   BPoint *bp;
2056   float *fp;
2057   int a, tot;
2058 
2059   /* count */
2060   BLI_assert(BKE_keyblock_curve_element_count(nurb) == kb->totelem);
2061 
2062   tot = kb->totelem;
2063   if (tot == 0) {
2064     return;
2065   }
2066 
2067   fp = kb->data;
2068   for (nu = nurb->first; nu; nu = nu->next) {
2069     if (nu->bezt) {
2070       for (a = nu->pntsu, bezt = nu->bezt; a; a--, bezt++) {
2071         for (int i = 0; i < 3; i++) {
2072           copy_v3_v3(&fp[i * 3], bezt->vec[i]);
2073         }
2074         fp[9] = bezt->tilt;
2075         fp[10] = bezt->radius;
2076         fp += KEYELEM_FLOAT_LEN_BEZTRIPLE;
2077       }
2078     }
2079     else {
2080       for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a; a--, bp++) {
2081         copy_v3_v3(fp, bp->vec);
2082         fp[3] = bp->tilt;
2083         fp[4] = bp->radius;
2084         fp += KEYELEM_FLOAT_LEN_BPOINT;
2085       }
2086     }
2087   }
2088 }
2089 
BKE_keyblock_curve_data_transform(const ListBase * nurb,const float mat[4][4],const void * src_data,void * dst_data)2090 void BKE_keyblock_curve_data_transform(const ListBase *nurb,
2091                                        const float mat[4][4],
2092                                        const void *src_data,
2093                                        void *dst_data)
2094 {
2095   const float *src = src_data;
2096   float *dst = dst_data;
2097   for (Nurb *nu = nurb->first; nu; nu = nu->next) {
2098     if (nu->bezt) {
2099       for (int a = nu->pntsu; a; a--) {
2100         for (int i = 0; i < 3; i++) {
2101           mul_v3_m4v3(&dst[i * 3], mat, &src[i * 3]);
2102         }
2103         dst[9] = src[9];
2104         dst[10] = src[10];
2105         src += KEYELEM_FLOAT_LEN_BEZTRIPLE;
2106         dst += KEYELEM_FLOAT_LEN_BEZTRIPLE;
2107       }
2108     }
2109     else {
2110       for (int a = nu->pntsu * nu->pntsv; a; a--) {
2111         mul_v3_m4v3(dst, mat, src);
2112         dst[3] = src[3];
2113         dst[4] = src[4];
2114         src += KEYELEM_FLOAT_LEN_BPOINT;
2115         dst += KEYELEM_FLOAT_LEN_BPOINT;
2116       }
2117     }
2118   }
2119 }
2120 
BKE_keyblock_convert_from_curve(Curve * cu,KeyBlock * kb,ListBase * nurb)2121 void BKE_keyblock_convert_from_curve(Curve *cu, KeyBlock *kb, ListBase *nurb)
2122 {
2123   int tot;
2124 
2125   /* count */
2126   tot = BKE_keyblock_curve_element_count(nurb);
2127   if (tot == 0) {
2128     return;
2129   }
2130 
2131   MEM_SAFE_FREE(kb->data);
2132 
2133   kb->data = MEM_mallocN(cu->key->elemsize * tot, __func__);
2134   kb->totelem = tot;
2135 
2136   BKE_keyblock_update_from_curve(cu, kb, nurb);
2137 }
2138 
BKE_keyblock_convert_to_curve(KeyBlock * kb,Curve * UNUSED (cu),ListBase * nurb)2139 void BKE_keyblock_convert_to_curve(KeyBlock *kb, Curve *UNUSED(cu), ListBase *nurb)
2140 {
2141   Nurb *nu;
2142   BezTriple *bezt;
2143   BPoint *bp;
2144   const float *fp;
2145   int a, tot;
2146 
2147   tot = BKE_keyblock_curve_element_count(nurb);
2148   tot = min_ii(kb->totelem, tot);
2149 
2150   fp = kb->data;
2151   for (nu = nurb->first; nu && tot > 0; nu = nu->next) {
2152     if (nu->bezt) {
2153       for (a = nu->pntsu, bezt = nu->bezt; a && (tot -= KEYELEM_ELEM_LEN_BEZTRIPLE) >= 0;
2154            a--, bezt++) {
2155         for (int i = 0; i < 3; i++) {
2156           copy_v3_v3(bezt->vec[i], &fp[i * 3]);
2157         }
2158         bezt->tilt = fp[9];
2159         bezt->radius = fp[10];
2160         fp += KEYELEM_FLOAT_LEN_BEZTRIPLE;
2161       }
2162     }
2163     else {
2164       for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a && (tot -= KEYELEM_ELEM_LEN_BPOINT) >= 0;
2165            a--, bp++) {
2166         copy_v3_v3(bp->vec, fp);
2167         bp->tilt = fp[3];
2168         bp->radius = fp[4];
2169         fp += KEYELEM_FLOAT_LEN_BPOINT;
2170       }
2171     }
2172   }
2173 }
2174 
2175 /************************* Mesh ************************/
BKE_keyblock_update_from_mesh(Mesh * me,KeyBlock * kb)2176 void BKE_keyblock_update_from_mesh(Mesh *me, KeyBlock *kb)
2177 {
2178   MVert *mvert;
2179   float(*fp)[3];
2180   int a, tot;
2181 
2182   BLI_assert(me->totvert == kb->totelem);
2183 
2184   tot = me->totvert;
2185   if (tot == 0) {
2186     return;
2187   }
2188 
2189   mvert = me->mvert;
2190   fp = kb->data;
2191   for (a = 0; a < tot; a++, fp++, mvert++) {
2192     copy_v3_v3(*fp, mvert->co);
2193   }
2194 }
2195 
BKE_keyblock_convert_from_mesh(Mesh * me,Key * key,KeyBlock * kb)2196 void BKE_keyblock_convert_from_mesh(Mesh *me, Key *key, KeyBlock *kb)
2197 {
2198   const int len = me->totvert;
2199 
2200   if (me->totvert == 0) {
2201     return;
2202   }
2203 
2204   MEM_SAFE_FREE(kb->data);
2205 
2206   kb->data = MEM_malloc_arrayN((size_t)len, (size_t)key->elemsize, __func__);
2207   kb->totelem = len;
2208 
2209   BKE_keyblock_update_from_mesh(me, kb);
2210 }
2211 
BKE_keyblock_convert_to_mesh(KeyBlock * kb,Mesh * me)2212 void BKE_keyblock_convert_to_mesh(KeyBlock *kb, Mesh *me)
2213 {
2214   MVert *mvert;
2215   const float(*fp)[3];
2216   int a, tot;
2217 
2218   mvert = me->mvert;
2219   fp = kb->data;
2220 
2221   tot = min_ii(kb->totelem, me->totvert);
2222 
2223   for (a = 0; a < tot; a++, fp++, mvert++) {
2224     copy_v3_v3(mvert->co, *fp);
2225   }
2226 }
2227 
2228 /**
2229  * Computes normals (vertices, polygons and/or loops ones) of given mesh for given shape key.
2230  *
2231  * \param kb: the KeyBlock to use to compute normals.
2232  * \param mesh: the Mesh to apply keyblock to.
2233  * \param r_vertnors: if non-NULL, an array of vectors, same length as number of vertices.
2234  * \param r_polynors: if non-NULL, an array of vectors, same length as number of polygons.
2235  * \param r_loopnors: if non-NULL, an array of vectors, same length as number of loops.
2236  */
BKE_keyblock_mesh_calc_normals(struct KeyBlock * kb,struct Mesh * mesh,float (* r_vertnors)[3],float (* r_polynors)[3],float (* r_loopnors)[3])2237 void BKE_keyblock_mesh_calc_normals(struct KeyBlock *kb,
2238                                     struct Mesh *mesh,
2239                                     float (*r_vertnors)[3],
2240                                     float (*r_polynors)[3],
2241                                     float (*r_loopnors)[3])
2242 {
2243   /* We use a temp, shallow copy of mesh to work. */
2244   Mesh me;
2245   bool free_polynors = false;
2246 
2247   if (r_vertnors == NULL && r_polynors == NULL && r_loopnors == NULL) {
2248     return;
2249   }
2250 
2251   me = *mesh;
2252   me.mvert = MEM_dupallocN(mesh->mvert);
2253   CustomData_reset(&me.vdata);
2254   CustomData_reset(&me.edata);
2255   CustomData_reset(&me.pdata);
2256   CustomData_reset(&me.ldata);
2257   CustomData_reset(&me.fdata);
2258 
2259   BKE_keyblock_convert_to_mesh(kb, &me);
2260 
2261   if (r_polynors == NULL && r_loopnors != NULL) {
2262     r_polynors = MEM_mallocN(sizeof(float[3]) * me.totpoly, __func__);
2263     free_polynors = true;
2264   }
2265   BKE_mesh_calc_normals_poly(me.mvert,
2266                              r_vertnors,
2267                              me.totvert,
2268                              me.mloop,
2269                              me.mpoly,
2270                              me.totloop,
2271                              me.totpoly,
2272                              r_polynors,
2273                              false);
2274 
2275   if (r_loopnors) {
2276     short(*clnors)[2] = CustomData_get_layer(&mesh->ldata, CD_CUSTOMLOOPNORMAL); /* May be NULL. */
2277 
2278     BKE_mesh_normals_loop_split(me.mvert,
2279                                 me.totvert,
2280                                 me.medge,
2281                                 me.totedge,
2282                                 me.mloop,
2283                                 r_loopnors,
2284                                 me.totloop,
2285                                 me.mpoly,
2286                                 r_polynors,
2287                                 me.totpoly,
2288                                 (me.flag & ME_AUTOSMOOTH) != 0,
2289                                 me.smoothresh,
2290                                 NULL,
2291                                 clnors,
2292                                 NULL);
2293   }
2294 
2295   CustomData_free(&me.vdata, me.totvert);
2296   CustomData_free(&me.edata, me.totedge);
2297   CustomData_free(&me.pdata, me.totpoly);
2298   CustomData_free(&me.ldata, me.totloop);
2299   CustomData_free(&me.fdata, me.totface);
2300   MEM_freeN(me.mvert);
2301 
2302   if (free_polynors) {
2303     MEM_freeN(r_polynors);
2304   }
2305 }
2306 
2307 /************************* raw coords ************************/
BKE_keyblock_update_from_vertcos(Object * ob,KeyBlock * kb,const float (* vertCos)[3])2308 void BKE_keyblock_update_from_vertcos(Object *ob, KeyBlock *kb, const float (*vertCos)[3])
2309 {
2310   const float(*co)[3] = vertCos;
2311   float *fp = kb->data;
2312   int tot, a;
2313 
2314 #ifndef NDEBUG
2315   if (ob->type == OB_LATTICE) {
2316     Lattice *lt = ob->data;
2317     BLI_assert((lt->pntsu * lt->pntsv * lt->pntsw) == kb->totelem);
2318   }
2319   else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
2320     Curve *cu = ob->data;
2321     BLI_assert(BKE_keyblock_curve_element_count(&cu->nurb) == kb->totelem);
2322   }
2323   else if (ob->type == OB_MESH) {
2324     Mesh *me = ob->data;
2325     BLI_assert(me->totvert == kb->totelem);
2326   }
2327   else {
2328     BLI_assert(0 == kb->totelem);
2329   }
2330 #endif
2331 
2332   tot = kb->totelem;
2333   if (tot == 0) {
2334     return;
2335   }
2336 
2337   /* Copy coords to keyblock */
2338   if (ELEM(ob->type, OB_MESH, OB_LATTICE)) {
2339     for (a = 0; a < tot; a++, fp += 3, co++) {
2340       copy_v3_v3(fp, *co);
2341     }
2342   }
2343   else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
2344     Curve *cu = (Curve *)ob->data;
2345     Nurb *nu;
2346     BezTriple *bezt;
2347     BPoint *bp;
2348 
2349     for (nu = cu->nurb.first; nu; nu = nu->next) {
2350       if (nu->bezt) {
2351         for (a = nu->pntsu, bezt = nu->bezt; a; a--, bezt++) {
2352           for (int i = 0; i < 3; i++, co++) {
2353             copy_v3_v3(&fp[i * 3], *co);
2354           }
2355           fp += KEYELEM_FLOAT_LEN_BEZTRIPLE;
2356         }
2357       }
2358       else {
2359         for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a; a--, bp++, co++) {
2360           copy_v3_v3(fp, *co);
2361           fp += KEYELEM_FLOAT_LEN_BPOINT;
2362         }
2363       }
2364     }
2365   }
2366 }
2367 
BKE_keyblock_convert_from_vertcos(Object * ob,KeyBlock * kb,const float (* vertCos)[3])2368 void BKE_keyblock_convert_from_vertcos(Object *ob, KeyBlock *kb, const float (*vertCos)[3])
2369 {
2370   int tot = 0, elemsize;
2371 
2372   MEM_SAFE_FREE(kb->data);
2373 
2374   /* Count of vertex coords in array */
2375   if (ob->type == OB_MESH) {
2376     Mesh *me = (Mesh *)ob->data;
2377     tot = me->totvert;
2378     elemsize = me->key->elemsize;
2379   }
2380   else if (ob->type == OB_LATTICE) {
2381     Lattice *lt = (Lattice *)ob->data;
2382     tot = lt->pntsu * lt->pntsv * lt->pntsw;
2383     elemsize = lt->key->elemsize;
2384   }
2385   else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
2386     Curve *cu = (Curve *)ob->data;
2387     elemsize = cu->key->elemsize;
2388     tot = BKE_keyblock_curve_element_count(&cu->nurb);
2389   }
2390 
2391   if (tot == 0) {
2392     return;
2393   }
2394 
2395   kb->data = MEM_mallocN(tot * elemsize, __func__);
2396 
2397   /* Copy coords to keyblock */
2398   BKE_keyblock_update_from_vertcos(ob, kb, vertCos);
2399 }
2400 
BKE_keyblock_convert_to_vertcos(Object * ob,KeyBlock * kb)2401 float (*BKE_keyblock_convert_to_vertcos(Object *ob, KeyBlock *kb))[3]
2402 {
2403   float(*vertCos)[3], (*co)[3];
2404   const float *fp = kb->data;
2405   int tot = 0, a;
2406 
2407   /* Count of vertex coords in array */
2408   if (ob->type == OB_MESH) {
2409     Mesh *me = (Mesh *)ob->data;
2410     tot = me->totvert;
2411   }
2412   else if (ob->type == OB_LATTICE) {
2413     Lattice *lt = (Lattice *)ob->data;
2414     tot = lt->pntsu * lt->pntsv * lt->pntsw;
2415   }
2416   else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
2417     Curve *cu = (Curve *)ob->data;
2418     tot = BKE_nurbList_verts_count(&cu->nurb);
2419   }
2420 
2421   if (tot == 0) {
2422     return NULL;
2423   }
2424 
2425   co = vertCos = MEM_mallocN(tot * sizeof(*vertCos), __func__);
2426 
2427   /* Copy coords to array */
2428   if (ELEM(ob->type, OB_MESH, OB_LATTICE)) {
2429     for (a = 0; a < tot; a++, fp += 3, co++) {
2430       copy_v3_v3(*co, fp);
2431     }
2432   }
2433   else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
2434     Curve *cu = (Curve *)ob->data;
2435     Nurb *nu;
2436     BezTriple *bezt;
2437     BPoint *bp;
2438 
2439     for (nu = cu->nurb.first; nu; nu = nu->next) {
2440       if (nu->bezt) {
2441         for (a = nu->pntsu, bezt = nu->bezt; a; a--, bezt++) {
2442           for (int i = 0; i < 3; i++, co++) {
2443             copy_v3_v3(*co, &fp[i * 3]);
2444           }
2445           fp += KEYELEM_FLOAT_LEN_BEZTRIPLE;
2446         }
2447       }
2448       else {
2449         for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a; a--, bp++, co++) {
2450           copy_v3_v3(*co, fp);
2451           fp += KEYELEM_FLOAT_LEN_BPOINT;
2452         }
2453       }
2454     }
2455   }
2456 
2457   return vertCos;
2458 }
2459 
2460 /************************* raw coord offsets ************************/
BKE_keyblock_update_from_offset(Object * ob,KeyBlock * kb,const float (* ofs)[3])2461 void BKE_keyblock_update_from_offset(Object *ob, KeyBlock *kb, const float (*ofs)[3])
2462 {
2463   int a;
2464   float *fp = kb->data;
2465 
2466   if (ELEM(ob->type, OB_MESH, OB_LATTICE)) {
2467     for (a = 0; a < kb->totelem; a++, fp += 3, ofs++) {
2468       add_v3_v3(fp, *ofs);
2469     }
2470   }
2471   else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
2472     Curve *cu = (Curve *)ob->data;
2473     Nurb *nu;
2474     BezTriple *bezt;
2475     BPoint *bp;
2476 
2477     for (nu = cu->nurb.first; nu; nu = nu->next) {
2478       if (nu->bezt) {
2479         for (a = nu->pntsu, bezt = nu->bezt; a; a--, bezt++) {
2480           for (int i = 0; i < 3; i++, ofs++) {
2481             add_v3_v3(&fp[i * 3], *ofs);
2482           }
2483           fp += KEYELEM_FLOAT_LEN_BEZTRIPLE;
2484         }
2485       }
2486       else {
2487         for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a; a--, bp++, ofs++) {
2488           add_v3_v3(fp, *ofs);
2489           fp += KEYELEM_FLOAT_LEN_BPOINT;
2490         }
2491       }
2492     }
2493   }
2494 }
2495 
2496 /* ==========================================================*/
2497 
2498 /**
2499  * Move shape key from org_index to new_index. Safe, clamps index to valid range,
2500  * updates reference keys, the object's active shape index,
2501  * the 'frame' value in case of absolute keys, etc.
2502  * Note indices are expected in real values (not 'fake' shapenr +1 ones).
2503  *
2504  * \param org_index: if < 0, current object's active shape will be used as skey to move.
2505  * \return true if something was done, else false.
2506  */
BKE_keyblock_move(Object * ob,int org_index,int new_index)2507 bool BKE_keyblock_move(Object *ob, int org_index, int new_index)
2508 {
2509   Key *key = BKE_key_from_object(ob);
2510   KeyBlock *kb;
2511   const int act_index = ob->shapenr - 1;
2512   const int totkey = key->totkey;
2513   int i;
2514   bool rev, in_range = false;
2515 
2516   if (org_index < 0) {
2517     org_index = act_index;
2518   }
2519 
2520   CLAMP(new_index, 0, key->totkey - 1);
2521   CLAMP(org_index, 0, key->totkey - 1);
2522 
2523   if (new_index == org_index) {
2524     return false;
2525   }
2526 
2527   rev = ((new_index - org_index) < 0) ? true : false;
2528 
2529   /* We swap 'org' element with its previous/next neighbor (depending on direction of the move)
2530    * repeatedly, until we reach final position.
2531    * This allows us to only loop on the list once! */
2532   for (kb = (rev ? key->block.last : key->block.first), i = (rev ? totkey - 1 : 0); kb;
2533        kb = (rev ? kb->prev : kb->next), rev ? i-- : i++) {
2534     if (i == org_index) {
2535       in_range = true; /* Start list items swapping... */
2536     }
2537     else if (i == new_index) {
2538       in_range = false; /* End list items swapping. */
2539     }
2540 
2541     if (in_range) {
2542       KeyBlock *other_kb = rev ? kb->prev : kb->next;
2543 
2544       /* Swap with previous/next list item. */
2545       BLI_listbase_swaplinks(&key->block, kb, other_kb);
2546 
2547       /* Swap absolute positions. */
2548       SWAP(float, kb->pos, other_kb->pos);
2549 
2550       kb = other_kb;
2551     }
2552 
2553     /* Adjust relative indices, this has to be done on the whole list! */
2554     if (kb->relative == org_index) {
2555       kb->relative = new_index;
2556     }
2557     else if (kb->relative < org_index && kb->relative >= new_index) {
2558       /* remove after, insert before this index */
2559       kb->relative++;
2560     }
2561     else if (kb->relative > org_index && kb->relative <= new_index) {
2562       /* remove before, insert after this index */
2563       kb->relative--;
2564     }
2565   }
2566 
2567   /* Need to update active shape number if it's affected,
2568    * same principle as for relative indices above. */
2569   if (org_index == act_index) {
2570     ob->shapenr = new_index + 1;
2571   }
2572   else if (act_index < org_index && act_index >= new_index) {
2573     ob->shapenr++;
2574   }
2575   else if (act_index > org_index && act_index <= new_index) {
2576     ob->shapenr--;
2577   }
2578 
2579   /* First key is always refkey, matches interface and BKE_key_sort */
2580   key->refkey = key->block.first;
2581 
2582   return true;
2583 }
2584 
2585 /**
2586  * Check if given keyblock (as index) is used as basis by others in given key.
2587  */
BKE_keyblock_is_basis(Key * key,const int index)2588 bool BKE_keyblock_is_basis(Key *key, const int index)
2589 {
2590   KeyBlock *kb;
2591   int i;
2592 
2593   if (key->type == KEY_RELATIVE) {
2594     for (i = 0, kb = key->block.first; kb; i++, kb = kb->next) {
2595       if ((i != index) && (kb->relative == index)) {
2596         return true;
2597       }
2598     }
2599   }
2600 
2601   return false;
2602 }
2603