Cleanup: remove redundant doxygen \file argument
[blender.git] / source / blender / blenkernel / intern / constraint.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 \ingroup bke
21  */
22
23
24 #include <stdio.h>
25 #include <stddef.h>
26 #include <string.h>
27 #include <math.h>
28 #include <float.h>
29
30 #include "MEM_guardedalloc.h"
31
32 #include "BLI_blenlib.h"
33 #include "BLI_math.h"
34 #include "BLI_kdopbvh.h"
35 #include "BLI_utildefines.h"
36 #include "BLI_string_utils.h"
37 #include "BLT_translation.h"
38
39 #include "DNA_armature_types.h"
40 #include "DNA_cachefile_types.h"
41 #include "DNA_constraint_types.h"
42 #include "DNA_modifier_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_action_types.h"
45 #include "DNA_curve_types.h"
46 #include "DNA_mesh_types.h"
47 #include "DNA_meshdata_types.h"
48
49 #include "DNA_lattice_types.h"
50 #include "DNA_scene_types.h"
51 #include "DNA_tracking_types.h"
52 #include "DNA_movieclip_types.h"
53
54
55 #include "BKE_action.h"
56 #include "BKE_anim.h" /* for the curve calculation part */
57 #include "BKE_armature.h"
58 #include "BKE_bvhutils.h"
59 #include "BKE_cachefile.h"
60 #include "BKE_camera.h"
61 #include "BKE_constraint.h"
62 #include "BKE_curve.h"
63 #include "BKE_deform.h"
64 #include "BKE_displist.h"
65 #include "BKE_editmesh.h"
66 #include "BKE_global.h"
67 #include "BKE_idprop.h"
68 #include "BKE_library.h"
69 #include "BKE_mesh_runtime.h"
70 #include "BKE_movieclip.h"
71 #include "BKE_object.h"
72 #include "BKE_scene.h"
73 #include "BKE_shrinkwrap.h"
74 #include "BKE_tracking.h"
75
76 #include "BIK_api.h"
77
78 #include "DEG_depsgraph.h"
79 #include "DEG_depsgraph_query.h"
80
81 #include "CLG_log.h"
82
83 #ifdef WITH_PYTHON
84 #  include "BPY_extern.h"
85 #endif
86
87 #ifdef WITH_ALEMBIC
88 #  include "ABC_alembic.h"
89 #endif
90
91 /* ---------------------------------------------------------------------------- */
92 /* Useful macros for testing various common flag combinations */
93
94 /* Constraint Target Macros */
95 #define VALID_CONS_TARGET(ct) ((ct) && (ct->tar))
96
97 static CLG_LogRef LOG = {"bke.constraint"};
98
99 /* ************************ Constraints - General Utilities *************************** */
100 /* These functions here don't act on any specific constraints, and are therefore should/will
101  * not require any of the special function-pointers afforded by the relevant constraint
102  * type-info structs.
103  */
104
105 static void damptrack_do_transform(float matrix[4][4], const float tarvec[3], int track_axis);
106
107 static bConstraint *constraint_find_original(Object *ob, bPoseChannel *pchan, bConstraint *con, Object **r_orig_ob);
108 static bConstraint *constraint_find_original_for_update(bConstraintOb *cob, bConstraint *con);
109
110 /* -------------- Naming -------------- */
111
112 /* Find the first available, non-duplicate name for a given constraint */
113 void BKE_constraint_unique_name(bConstraint *con, ListBase *list)
114 {
115         BLI_uniquename(list, con, DATA_("Const"), '.', offsetof(bConstraint, name), sizeof(con->name));
116 }
117
118 /* ----------------- Evaluation Loop Preparation --------------- */
119
120 /* package an object/bone for use in constraint evaluation */
121 /* This function MEM_calloc's a bConstraintOb struct, that will need to be freed after evaluation */
122 bConstraintOb *BKE_constraints_make_evalob(Depsgraph *depsgraph, Scene *scene, Object *ob, void *subdata, short datatype)
123 {
124         bConstraintOb *cob;
125
126         /* create regardless of whether we have any data! */
127         cob = MEM_callocN(sizeof(bConstraintOb), "bConstraintOb");
128
129         /* for system time, part of deglobalization, code nicer later with local time (ton) */
130         cob->scene = scene;
131         cob->depsgraph = depsgraph;
132
133         /* based on type of available data */
134         switch (datatype) {
135                 case CONSTRAINT_OBTYPE_OBJECT:
136                 {
137                         /* disregard subdata... calloc should set other values right */
138                         if (ob) {
139                                 cob->ob = ob;
140                                 cob->type = datatype;
141
142                                 if (cob->ob->rotmode > 0) {
143                                         /* Should be some kind of Euler order, so use it */
144                                         /* NOTE: Versions <= 2.76 assumed that "default" order
145                                          *       would always get used, so we may seem some rig
146                                          *       breakage as a result. However, this change here
147                                          *       is needed to fix T46599
148                                          */
149                                         cob->rotOrder = ob->rotmode;
150                                 }
151                                 else {
152                                         /* Quats/Axis-Angle, so Eulers should just use default order */
153                                         cob->rotOrder = EULER_ORDER_DEFAULT;
154                                 }
155                                 copy_m4_m4(cob->matrix, ob->obmat);
156                         }
157                         else
158                                 unit_m4(cob->matrix);
159
160                         copy_m4_m4(cob->startmat, cob->matrix);
161                         break;
162                 }
163                 case CONSTRAINT_OBTYPE_BONE:
164                 {
165                         /* only set if we have valid bone, otherwise default */
166                         if (ob && subdata) {
167                                 cob->ob = ob;
168                                 cob->pchan = (bPoseChannel *)subdata;
169                                 cob->type = datatype;
170
171                                 if (cob->pchan->rotmode > 0) {
172                                         /* should be some type of Euler order */
173                                         cob->rotOrder = cob->pchan->rotmode;
174                                 }
175                                 else {
176                                         /* Quats, so eulers should just use default order */
177                                         cob->rotOrder = EULER_ORDER_DEFAULT;
178                                 }
179
180                                 /* matrix in world-space */
181                                 mul_m4_m4m4(cob->matrix, ob->obmat, cob->pchan->pose_mat);
182                         }
183                         else
184                                 unit_m4(cob->matrix);
185
186                         copy_m4_m4(cob->startmat, cob->matrix);
187                         break;
188                 }
189                 default: /* other types not yet handled */
190                         unit_m4(cob->matrix);
191                         unit_m4(cob->startmat);
192                         break;
193         }
194
195         return cob;
196 }
197
198 /* cleanup after constraint evaluation */
199 void BKE_constraints_clear_evalob(bConstraintOb *cob)
200 {
201         float delta[4][4], imat[4][4];
202
203         /* prevent crashes */
204         if (cob == NULL)
205                 return;
206
207         /* calculate delta of constraints evaluation */
208         invert_m4_m4(imat, cob->startmat);
209         /* XXX This would seem to be in wrong order. However, it does not work in 'right' order - would be nice to
210          *     understand why premul is needed here instead of usual postmul?
211          *     In any case, we **do not get a delta** here (e.g. startmat & matrix having same location, still gives
212          *     a 'delta' with non-null translation component :/ ).*/
213         mul_m4_m4m4(delta, cob->matrix, imat);
214
215         /* copy matrices back to source */
216         switch (cob->type) {
217                 case CONSTRAINT_OBTYPE_OBJECT:
218                 {
219                         /* cob->ob might not exist! */
220                         if (cob->ob) {
221                                 /* copy new ob-matrix back to owner */
222                                 copy_m4_m4(cob->ob->obmat, cob->matrix);
223
224                                 /* copy inverse of delta back to owner */
225                                 invert_m4_m4(cob->ob->constinv, delta);
226                         }
227                         break;
228                 }
229                 case CONSTRAINT_OBTYPE_BONE:
230                 {
231                         /* cob->ob or cob->pchan might not exist */
232                         if (cob->ob && cob->pchan) {
233                                 /* copy new pose-matrix back to owner */
234                                 mul_m4_m4m4(cob->pchan->pose_mat, cob->ob->imat, cob->matrix);
235
236                                 /* copy inverse of delta back to owner */
237                                 invert_m4_m4(cob->pchan->constinv, delta);
238                         }
239                         break;
240                 }
241         }
242
243         /* free tempolary struct */
244         MEM_freeN(cob);
245 }
246
247 /* -------------- Space-Conversion API -------------- */
248
249 /* This function is responsible for the correct transformations/conversions
250  * of a matrix from one space to another for constraint evaluation.
251  * For now, this is only implemented for Objects and PoseChannels.
252  */
253 void BKE_constraint_mat_convertspace(
254         Object *ob, bPoseChannel *pchan, float mat[4][4], short from, short to, const bool keep_scale)
255 {
256         float diff_mat[4][4];
257         float imat[4][4];
258
259         /* prevent crashes in these unlikely events  */
260         if (ob == NULL || mat == NULL) return;
261         /* optimize trick - check if need to do anything */
262         if (from == to) return;
263
264         /* are we dealing with pose-channels or objects */
265         if (pchan) {
266                 /* pose channels */
267                 switch (from) {
268                         case CONSTRAINT_SPACE_WORLD: /* ---------- FROM WORLDSPACE ---------- */
269                         {
270                                 /* world to pose */
271                                 invert_m4_m4(imat, ob->obmat);
272                                 mul_m4_m4m4(mat, imat, mat);
273
274                                 /* use pose-space as stepping stone for other spaces... */
275                                 if (ELEM(to, CONSTRAINT_SPACE_LOCAL, CONSTRAINT_SPACE_PARLOCAL)) {
276                                         /* call self with slightly different values */
277                                         BKE_constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to, keep_scale);
278                                 }
279                                 break;
280                         }
281                         case CONSTRAINT_SPACE_POSE: /* ---------- FROM POSESPACE ---------- */
282                         {
283                                 /* pose to world */
284                                 if (to == CONSTRAINT_SPACE_WORLD) {
285                                         mul_m4_m4m4(mat, ob->obmat, mat);
286                                 }
287                                 /* pose to local */
288                                 else if (to == CONSTRAINT_SPACE_LOCAL) {
289                                         if (pchan->bone) {
290                                                 BKE_armature_mat_pose_to_bone(pchan, mat, mat);
291                                         }
292                                 }
293                                 /* pose to local with parent */
294                                 else if (to == CONSTRAINT_SPACE_PARLOCAL) {
295                                         if (pchan->bone) {
296                                                 invert_m4_m4(imat, pchan->bone->arm_mat);
297                                                 mul_m4_m4m4(mat, imat, mat);
298                                         }
299                                 }
300                                 break;
301                         }
302                         case CONSTRAINT_SPACE_LOCAL: /* ------------ FROM LOCALSPACE --------- */
303                         {
304                                 /* local to pose - do inverse procedure that was done for pose to local */
305                                 if (pchan->bone) {
306                                         /* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */
307                                         BKE_armature_mat_bone_to_pose(pchan, mat, mat);
308                                 }
309
310                                 /* use pose-space as stepping stone for other spaces */
311                                 if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_PARLOCAL)) {
312                                         /* call self with slightly different values */
313                                         BKE_constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to, keep_scale);
314                                 }
315                                 break;
316                         }
317                         case CONSTRAINT_SPACE_PARLOCAL: /* -------------- FROM LOCAL WITH PARENT ---------- */
318                         {
319                                 /* local + parent to pose */
320                                 if (pchan->bone) {
321                                         copy_m4_m4(diff_mat, pchan->bone->arm_mat);
322                                         mul_m4_m4m4(mat, mat, diff_mat);
323                                 }
324
325                                 /* use pose-space as stepping stone for other spaces */
326                                 if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL)) {
327                                         /* call self with slightly different values */
328                                         BKE_constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to, keep_scale);
329                                 }
330                                 break;
331                         }
332                 }
333         }
334         else {
335                 /* objects */
336                 if (from == CONSTRAINT_SPACE_WORLD && to == CONSTRAINT_SPACE_LOCAL) {
337                         /* check if object has a parent */
338                         if (ob->parent) {
339                                 /* 'subtract' parent's effects from owner */
340                                 mul_m4_m4m4(diff_mat, ob->parent->obmat, ob->parentinv);
341                                 invert_m4_m4_safe(imat, diff_mat);
342                                 mul_m4_m4m4(mat, imat, mat);
343                         }
344                         else {
345                                 /* Local space in this case will have to be defined as local to the owner's
346                                  * transform-property-rotated axes. So subtract this rotation component.
347                                  */
348                                 /* XXX This is actually an ugly hack, local space of a parent-less object *is* the same as
349                                  *     global space!
350                                  *     Think what we want actually here is some kind of 'Final Space', i.e. once transformations
351                                  *     are applied - users are often confused about this too, this is not consistent with bones
352                                  *     local space either... Meh :|
353                                  *     --mont29
354                                  */
355                                 BKE_object_to_mat4(ob, diff_mat);
356                                 if (!keep_scale) {
357                                         normalize_m4(diff_mat);
358                                 }
359                                 zero_v3(diff_mat[3]);
360
361                                 invert_m4_m4_safe(imat, diff_mat);
362                                 mul_m4_m4m4(mat, imat, mat);
363                         }
364                 }
365                 else if (from == CONSTRAINT_SPACE_LOCAL && to == CONSTRAINT_SPACE_WORLD) {
366                         /* check that object has a parent - otherwise this won't work */
367                         if (ob->parent) {
368                                 /* 'add' parent's effect back to owner */
369                                 mul_m4_m4m4(diff_mat, ob->parent->obmat, ob->parentinv);
370                                 mul_m4_m4m4(mat, diff_mat, mat);
371                         }
372                         else {
373                                 /* Local space in this case will have to be defined as local to the owner's
374                                  * transform-property-rotated axes. So add back this rotation component.
375                                  */
376                                 /* XXX See comment above for world->local case... */
377                                 BKE_object_to_mat4(ob, diff_mat);
378                                 if (!keep_scale) {
379                                         normalize_m4(diff_mat);
380                                 }
381                                 zero_v3(diff_mat[3]);
382
383                                 mul_m4_m4m4(mat, diff_mat, mat);
384                         }
385                 }
386         }
387 }
388
389 /* ------------ General Target Matrix Tools ---------- */
390
391 /* function that sets the given matrix based on given vertex group in mesh */
392 static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[4][4])
393 {
394         /* when not in EditMode, use the 'final' evaluated mesh, depsgraph
395          * ensures we build with CD_MDEFORMVERT layer
396          */
397         Mesh *me_eval = ob->runtime.mesh_eval;
398         BMEditMesh *em = BKE_editmesh_from_object(ob);
399         float plane[3];
400         float imat[3][3], tmat[3][3];
401         const int defgroup = defgroup_name_index(ob, substring);
402
403         /* initialize target matrix using target matrix */
404         copy_m4_m4(mat, ob->obmat);
405
406         /* get index of vertex group */
407         if (defgroup == -1) {
408                 return;
409         }
410
411         float vec[3] = {0.0f, 0.0f, 0.0f};
412         float normal[3] = {0.0f, 0.0f, 0.0f};
413         float weightsum = 0.0f;
414         if (me_eval) {
415                 MDeformVert *dvert = CustomData_get_layer(&me_eval->vdata, CD_MDEFORMVERT);
416                 int numVerts = me_eval->totvert;
417
418                 /* check that dvert is a valid pointers (just in case) */
419                 if (dvert) {
420                         MDeformVert *dv = dvert;
421                         MVert *mv = me_eval->mvert;
422
423                         /* get the average of all verts with that are in the vertex-group */
424                         for (int i = 0; i < numVerts; i++, dv++, mv++) {
425                                 MDeformWeight *dw = defvert_find_index(dv, defgroup);
426
427                                 if (dw && dw->weight > 0.0f) {
428                                         float nor[3];
429                                         normal_short_to_float_v3(nor, mv->no);
430                                         madd_v3_v3fl(vec, mv->co, dw->weight);
431                                         madd_v3_v3fl(normal, nor, dw->weight);
432                                         weightsum += dw->weight;
433                                 }
434                         }
435                 }
436         }
437         else if (em) {
438                 if (CustomData_has_layer(&em->bm->vdata, CD_MDEFORMVERT)) {
439                         BMVert *v;
440                         BMIter iter;
441
442                         BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
443                                 MDeformVert *dv = CustomData_bmesh_get(&em->bm->vdata, v->head.data, CD_MDEFORMVERT);
444                                 MDeformWeight *dw = defvert_find_index(dv, defgroup);
445
446                                 if (dw && dw->weight > 0.0f) {
447                                         madd_v3_v3fl(vec, v->co, dw->weight);
448                                         madd_v3_v3fl(normal, v->no, dw->weight);
449                                         weightsum += dw->weight;
450                                 }
451                         }
452                 }
453         }
454         else {
455                 /* No valid edit or evaluated mesh, just abort. */
456                 return;
457         }
458
459         /* calculate averages of normal and coordinates */
460         if (weightsum > 0) {
461                 mul_v3_fl(vec, 1.0f / weightsum);
462                 mul_v3_fl(normal, 1.0f / weightsum);
463         }
464
465         /* derive the rotation from the average normal:
466          * - code taken from transform_gizmo.c,
467          *   calc_gizmo_stats, V3D_MANIP_NORMAL case
468          */
469         /*      we need the transpose of the inverse for a normal... */
470         copy_m3_m4(imat, ob->obmat);
471
472         invert_m3_m3(tmat, imat);
473         transpose_m3(tmat);
474         mul_m3_v3(tmat, normal);
475
476         normalize_v3(normal);
477         copy_v3_v3(plane, tmat[1]);
478
479         cross_v3_v3v3(mat[0], normal, plane);
480         if (len_squared_v3(mat[0]) < SQUARE(1e-3f)) {
481                 copy_v3_v3(plane, tmat[0]);
482                 cross_v3_v3v3(mat[0], normal, plane);
483         }
484
485         copy_v3_v3(mat[2], normal);
486         cross_v3_v3v3(mat[1], mat[2], mat[0]);
487
488         normalize_m4(mat);
489
490         /* apply the average coordinate as the new location */
491         mul_v3_m4v3(mat[3], ob->obmat, vec);
492 }
493
494 /* function that sets the given matrix based on given vertex group in lattice */
495 static void contarget_get_lattice_mat(Object *ob, const char *substring, float mat[4][4])
496 {
497         Lattice *lt = (Lattice *)ob->data;
498
499         DispList *dl = ob->runtime.curve_cache ? BKE_displist_find(&ob->runtime.curve_cache->disp, DL_VERTS) : NULL;
500         const float *co = dl ? dl->verts : NULL;
501         BPoint *bp = lt->def;
502
503         MDeformVert *dv = lt->dvert;
504         int tot_verts = lt->pntsu * lt->pntsv * lt->pntsw;
505         float vec[3] = {0.0f, 0.0f, 0.0f}, tvec[3];
506         int grouped = 0;
507         int i, n;
508         const int defgroup = defgroup_name_index(ob, substring);
509
510         /* initialize target matrix using target matrix */
511         copy_m4_m4(mat, ob->obmat);
512
513         /* get index of vertex group */
514         if (defgroup == -1) return;
515         if (dv == NULL) return;
516
517         /* 1. Loop through control-points checking if in nominated vertex-group.
518          * 2. If it is, add it to vec to find the average point.
519          */
520         for (i = 0; i < tot_verts; i++, dv++) {
521                 for (n = 0; n < dv->totweight; n++) {
522                         MDeformWeight *dw = defvert_find_index(dv, defgroup);
523                         if (dw && dw->weight > 0.0f) {
524                                 /* copy coordinates of point to temporary vector, then add to find average */
525                                 memcpy(tvec, co ? co : bp->vec, 3 * sizeof(float));
526
527                                 add_v3_v3(vec, tvec);
528                                 grouped++;
529                         }
530                 }
531
532                 /* advance pointer to coordinate data */
533                 if (co) co += 3;
534                 else bp++;
535         }
536
537         /* find average location, then multiply by ob->obmat to find world-space location */
538         if (grouped)
539                 mul_v3_fl(vec, 1.0f / grouped);
540         mul_v3_m4v3(tvec, ob->obmat, vec);
541
542         /* copy new location to matrix */
543         copy_v3_v3(mat[3], tvec);
544 }
545
546 /* generic function to get the appropriate matrix for most target cases */
547 /* The cases where the target can be object data have not been implemented */
548 static void constraint_target_to_mat4(Object *ob, const char *substring, float mat[4][4], short from, short to, short flag, float headtail)
549 {
550         /* Case OBJECT */
551         if (substring[0] == '\0') {
552                 copy_m4_m4(mat, ob->obmat);
553                 BKE_constraint_mat_convertspace(ob, NULL, mat, from, to, false);
554         }
555         /*  Case VERTEXGROUP */
556         /* Current method just takes the average location of all the points in the
557          * VertexGroup, and uses that as the location value of the targets. Where
558          * possible, the orientation will also be calculated, by calculating an
559          * 'average' vertex normal, and deriving the rotation from that.
560          *
561          * NOTE: EditMode is not currently supported, and will most likely remain that
562          *       way as constraints can only really affect things on object/bone level.
563          */
564         else if (ob->type == OB_MESH) {
565                 contarget_get_mesh_mat(ob, substring, mat);
566                 BKE_constraint_mat_convertspace(ob, NULL, mat, from, to, false);
567         }
568         else if (ob->type == OB_LATTICE) {
569                 contarget_get_lattice_mat(ob, substring, mat);
570                 BKE_constraint_mat_convertspace(ob, NULL, mat, from, to, false);
571         }
572         /* Case BONE */
573         else {
574                 bPoseChannel *pchan;
575
576                 pchan = BKE_pose_channel_find_name(ob->pose, substring);
577                 if (pchan) {
578                         /* Multiply the PoseSpace accumulation/final matrix for this
579                          * PoseChannel by the Armature Object's Matrix to get a worldspace
580                          * matrix.
581                          */
582                         bool is_bbone = (pchan->bone) && (pchan->bone->segments > 1) && (flag & CONSTRAINT_BBONE_SHAPE);
583                         bool full_bbone = (flag & CONSTRAINT_BBONE_SHAPE_FULL) != 0;
584
585                         if (headtail < 0.000001f && !(is_bbone && full_bbone)) {
586                                 /* skip length interpolation if set to head */
587                                 mul_m4_m4m4(mat, ob->obmat, pchan->pose_mat);
588                         }
589                         else if (is_bbone && pchan->bone->segments == pchan->runtime.bbone_segments) {
590                                 /* use point along bbone */
591                                 Mat4 *bbone = pchan->runtime.bbone_pose_mats;
592                                 float tempmat[4][4];
593                                 float loc[3], fac;
594
595                                 /* figure out which segment(s) the headtail value falls in */
596                                 fac = (float)pchan->bone->segments * headtail;
597
598                                 if (fac >= pchan->bone->segments - 1) {
599                                         /* special case: end segment doesn't get created properly... */
600                                         float pt[3], sfac;
601                                         int index;
602
603                                         /* bbone points are in bonespace, so need to move to posespace first */
604                                         index = pchan->bone->segments - 1;
605                                         mul_v3_m4v3(pt, pchan->pose_mat, bbone[index].mat[3]);
606
607                                         /* interpolate between last segment point and the endpoint */
608                                         sfac = fac - (float)(pchan->bone->segments - 1); /* fac is just the "leftover" between penultimate and last points */
609                                         interp_v3_v3v3(loc, pt, pchan->pose_tail, sfac);
610                                 }
611                                 else {
612                                         /* get indices for finding interpolating between points along the bbone */
613                                         float pt_a[3], pt_b[3], pt[3];
614                                         int   index_a, index_b;
615
616                                         index_a = floorf(fac);
617                                         CLAMP(index_a, 0, MAX_BBONE_SUBDIV - 1);
618
619                                         index_b = ceilf(fac);
620                                         CLAMP(index_b, 0, MAX_BBONE_SUBDIV - 1);
621
622                                         /* interpolate between these points */
623                                         copy_v3_v3(pt_a, bbone[index_a].mat[3]);
624                                         copy_v3_v3(pt_b, bbone[index_b].mat[3]);
625
626                                         interp_v3_v3v3(pt, pt_a, pt_b, fac - floorf(fac));
627
628                                         /* move the point from bone local space to pose space... */
629                                         mul_v3_m4v3(loc, pchan->pose_mat, pt);
630                                 }
631
632                                 /* apply full transformation of the segment if requested */
633                                 if (full_bbone) {
634                                         int index = floorf(fac);
635                                         CLAMP(index, 0, pchan->bone->segments - 1);
636
637                                         mul_m4_m4m4(tempmat, pchan->pose_mat, bbone[index].mat);
638                                 }
639                                 else {
640                                         copy_m4_m4(tempmat, pchan->pose_mat);
641                                 }
642
643                                 /* use interpolated distance for subtarget */
644                                 copy_v3_v3(tempmat[3], loc);
645
646                                 mul_m4_m4m4(mat, ob->obmat, tempmat);
647                         }
648                         else {
649                                 float tempmat[4][4], loc[3];
650
651                                 /* interpolate along length of bone */
652                                 interp_v3_v3v3(loc, pchan->pose_head, pchan->pose_tail, headtail);
653
654                                 /* use interpolated distance for subtarget */
655                                 copy_m4_m4(tempmat, pchan->pose_mat);
656                                 copy_v3_v3(tempmat[3], loc);
657
658                                 mul_m4_m4m4(mat, ob->obmat, tempmat);
659                         }
660                 }
661                 else
662                         copy_m4_m4(mat, ob->obmat);
663
664                 /* convert matrix space as required */
665                 BKE_constraint_mat_convertspace(ob, pchan, mat, from, to, false);
666         }
667 }
668
669 /* ************************* Specific Constraints ***************************** */
670 /* Each constraint defines a set of functions, which will be called at the appropriate
671  * times. In addition to this, each constraint should have a type-info struct, where
672  * its functions are attached for use.
673  */
674
675 /* Template for type-info data:
676  * - make a copy of this when creating new constraints, and just change the functions
677  *   pointed to as necessary
678  * - although the naming of functions doesn't matter, it would help for code
679  *   readability, to follow the same naming convention as is presented here
680  * - any functions that a constraint doesn't need to define, don't define
681  *   for such cases, just use NULL
682  * - these should be defined after all the functions have been defined, so that
683  *   forward-definitions/prototypes don't need to be used!
684  * - keep this copy #if-def'd so that future constraints can get based off this
685  */
686 #if 0
687 static bConstraintTypeInfo CTI_CONSTRNAME = {
688         CONSTRAINT_TYPE_CONSTRNAME, /* type */
689         sizeof(bConstrNameConstraint), /* size */
690         "ConstrName", /* name */
691         "bConstrNameConstraint", /* struct name */
692         constrname_free, /* free data */
693         constrname_id_looper, /* id looper */
694         constrname_copy, /* copy data */
695         constrname_new_data, /* new data */
696         constrname_get_tars, /* get constraint targets */
697         constrname_flush_tars, /* flush constraint targets */
698         constrname_get_tarmat, /* get target matrix */
699         constrname_evaluate /* evaluate */
700 };
701 #endif
702
703 /* This function should be used for the get_target_matrix member of all
704  * constraints that are not picky about what happens to their target matrix.
705  */
706 static void default_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint *con, bConstraintOb *UNUSED(cob), bConstraintTarget *ct, float UNUSED(ctime))
707 {
708         if (VALID_CONS_TARGET(ct))
709                 constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->flag, con->headtail);
710         else if (ct)
711                 unit_m4(ct->matrix);
712 }
713
714 /* This is a variant that extracts full transformation from B-Bone segments.
715  */
716 static void default_get_tarmat_full_bbone(struct Depsgraph *UNUSED(depsgraph), bConstraint *con, bConstraintOb *UNUSED(cob), bConstraintTarget *ct, float UNUSED(ctime))
717 {
718         if (VALID_CONS_TARGET(ct))
719                 constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->flag | CONSTRAINT_BBONE_SHAPE_FULL, con->headtail);
720         else if (ct)
721                 unit_m4(ct->matrix);
722 }
723
724 /* This following macro should be used for all standard single-target *_get_tars functions
725  * to save typing and reduce maintenance woes.
726  * (Hopefully all compilers will be happy with the lines with just a space on them. Those are
727  *  really just to help this code easier to read)
728  */
729 // TODO: cope with getting rotation order...
730 #define SINGLETARGET_GET_TARS(con, datatar, datasubtarget, ct, list) \
731         { \
732                 ct = MEM_callocN(sizeof(bConstraintTarget), "tempConstraintTarget"); \
733                  \
734                 ct->tar = datatar; \
735                 BLI_strncpy(ct->subtarget, datasubtarget, sizeof(ct->subtarget)); \
736                 ct->space = con->tarspace; \
737                 ct->flag = CONSTRAINT_TAR_TEMP; \
738                  \
739                 if (ct->tar) { \
740                         if ((ct->tar->type == OB_ARMATURE) && (ct->subtarget[0])) { \
741                                 bPoseChannel *pchan = BKE_pose_channel_find_name(ct->tar->pose, ct->subtarget); \
742                                 ct->type = CONSTRAINT_OBTYPE_BONE; \
743                                 ct->rotOrder = (pchan) ? (pchan->rotmode) : EULER_ORDER_DEFAULT; \
744                         } \
745                         else if (OB_TYPE_SUPPORT_VGROUP(ct->tar->type) && (ct->subtarget[0])) { \
746                                 ct->type = CONSTRAINT_OBTYPE_VERT; \
747                                 ct->rotOrder = EULER_ORDER_DEFAULT; \
748                         } \
749                         else { \
750                                 ct->type = CONSTRAINT_OBTYPE_OBJECT; \
751                                 ct->rotOrder = ct->tar->rotmode; \
752                         } \
753                 } \
754                  \
755                 BLI_addtail(list, ct); \
756         } (void)0
757
758 /* This following macro should be used for all standard single-target *_get_tars functions
759  * to save typing and reduce maintenance woes. It does not do the subtarget related operations
760  * (Hopefully all compilers will be happy with the lines with just a space on them. Those are
761  *  really just to help this code easier to read)
762  */
763 // TODO: cope with getting rotation order...
764 #define SINGLETARGETNS_GET_TARS(con, datatar, ct, list) \
765         { \
766                 ct = MEM_callocN(sizeof(bConstraintTarget), "tempConstraintTarget"); \
767                  \
768                 ct->tar = datatar; \
769                 ct->space = con->tarspace; \
770                 ct->flag = CONSTRAINT_TAR_TEMP; \
771                  \
772                 if (ct->tar) ct->type = CONSTRAINT_OBTYPE_OBJECT; \
773                  \
774                 BLI_addtail(list, ct); \
775         } (void)0
776
777 /* This following macro should be used for all standard single-target *_flush_tars functions
778  * to save typing and reduce maintenance woes.
779  * Note: the pointer to ct will be changed to point to the next in the list (as it gets removed)
780  * (Hopefully all compilers will be happy with the lines with just a space on them. Those are
781  *  really just to help this code easier to read)
782  */
783 #define SINGLETARGET_FLUSH_TARS(con, datatar, datasubtarget, ct, list, no_copy) \
784         { \
785                 if (ct) { \
786                         bConstraintTarget *ctn = ct->next; \
787                         if (no_copy == 0) { \
788                                 datatar = ct->tar; \
789                                 BLI_strncpy(datasubtarget, ct->subtarget, sizeof(datasubtarget)); \
790                                 con->tarspace = (char)ct->space; \
791                         } \
792                          \
793                         BLI_freelinkN(list, ct); \
794                         ct = ctn; \
795                 } \
796         } (void)0
797
798 /* This following macro should be used for all standard single-target *_flush_tars functions
799  * to save typing and reduce maintenance woes. It does not do the subtarget related operations.
800  * Note: the pointer to ct will be changed to point to the next in the list (as it gets removed)
801  * (Hopefully all compilers will be happy with the lines with just a space on them. Those are
802  *  really just to help this code easier to read)
803  */
804 #define SINGLETARGETNS_FLUSH_TARS(con, datatar, ct, list, no_copy) \
805         { \
806                 if (ct) { \
807                         bConstraintTarget *ctn = ct->next; \
808                         if (no_copy == 0) { \
809                                 datatar = ct->tar; \
810                                 con->tarspace = (char)ct->space; \
811                         } \
812                          \
813                         BLI_freelinkN(list, ct); \
814                         ct = ctn; \
815                 } \
816         } (void)0
817
818 /* --------- ChildOf Constraint ------------ */
819
820 static void childof_new_data(void *cdata)
821 {
822         bChildOfConstraint *data = (bChildOfConstraint *)cdata;
823
824         data->flag = (CHILDOF_LOCX | CHILDOF_LOCY | CHILDOF_LOCZ |
825                       CHILDOF_ROTX | CHILDOF_ROTY | CHILDOF_ROTZ |
826                       CHILDOF_SIZEX | CHILDOF_SIZEY | CHILDOF_SIZEZ);
827         unit_m4(data->invmat);
828 }
829
830 static void childof_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
831 {
832         bChildOfConstraint *data = con->data;
833
834         /* target only */
835         func(con, (ID **)&data->tar, false, userdata);
836 }
837
838 static int childof_get_tars(bConstraint *con, ListBase *list)
839 {
840         if (con && list) {
841                 bChildOfConstraint *data = con->data;
842                 bConstraintTarget *ct;
843
844                 /* standard target-getting macro for single-target constraints */
845                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
846
847                 return 1;
848         }
849
850         return 0;
851 }
852
853 static void childof_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
854 {
855         if (con && list) {
856                 bChildOfConstraint *data = con->data;
857                 bConstraintTarget *ct = list->first;
858
859                 /* the following macro is used for all standard single-target constraints */
860                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
861         }
862 }
863
864 static void childof_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
865 {
866         bChildOfConstraint *data = con->data;
867         bConstraintTarget *ct = targets->first;
868
869         /* only evaluate if there is a target */
870         if (VALID_CONS_TARGET(ct)) {
871                 float parmat[4][4];
872
873                 /* simple matrix parenting */
874                 if (data->flag == CHILDOF_ALL) {
875
876                         /* multiply target (parent matrix) by offset (parent inverse) to get
877                          * the effect of the parent that will be exerted on the owner
878                          */
879                         mul_m4_m4m4(parmat, ct->matrix, data->invmat);
880
881                         /* now multiply the parent matrix by the owner matrix to get the
882                          * the effect of this constraint (i.e. owner is 'parented' to parent)
883                          */
884                         mul_m4_m4m4(cob->matrix, parmat, cob->matrix);
885                 }
886                 else {
887                         float invmat[4][4], tempmat[4][4];
888                         float loc[3], eul[3], size[3];
889                         float loco[3], eulo[3], sizo[3];
890
891                         /* get offset (parent-inverse) matrix */
892                         copy_m4_m4(invmat, data->invmat);
893
894                         /* extract components of both matrices */
895                         copy_v3_v3(loc, ct->matrix[3]);
896                         mat4_to_eulO(eul, ct->rotOrder, ct->matrix);
897                         mat4_to_size(size, ct->matrix);
898
899                         copy_v3_v3(loco, invmat[3]);
900                         mat4_to_eulO(eulo, cob->rotOrder, invmat);
901                         mat4_to_size(sizo, invmat);
902
903                         /* disable channels not enabled */
904                         if (!(data->flag & CHILDOF_LOCX)) loc[0] = loco[0] = 0.0f;
905                         if (!(data->flag & CHILDOF_LOCY)) loc[1] = loco[1] = 0.0f;
906                         if (!(data->flag & CHILDOF_LOCZ)) loc[2] = loco[2] = 0.0f;
907                         if (!(data->flag & CHILDOF_ROTX)) eul[0] = eulo[0] = 0.0f;
908                         if (!(data->flag & CHILDOF_ROTY)) eul[1] = eulo[1] = 0.0f;
909                         if (!(data->flag & CHILDOF_ROTZ)) eul[2] = eulo[2] = 0.0f;
910                         if (!(data->flag & CHILDOF_SIZEX)) size[0] = sizo[0] = 1.0f;
911                         if (!(data->flag & CHILDOF_SIZEY)) size[1] = sizo[1] = 1.0f;
912                         if (!(data->flag & CHILDOF_SIZEZ)) size[2] = sizo[2] = 1.0f;
913
914                         /* make new target mat and offset mat */
915                         loc_eulO_size_to_mat4(ct->matrix, loc, eul, size, ct->rotOrder);
916                         loc_eulO_size_to_mat4(invmat, loco, eulo, sizo, cob->rotOrder);
917
918                         /* multiply target (parent matrix) by offset (parent inverse) to get
919                          * the effect of the parent that will be exerted on the owner
920                          */
921                         mul_m4_m4m4(parmat, ct->matrix, invmat);
922
923                         /* now multiply the parent matrix by the owner matrix to get the
924                          * the effect of this constraint (i.e.  owner is 'parented' to parent)
925                          */
926                         copy_m4_m4(tempmat, cob->matrix);
927                         mul_m4_m4m4(cob->matrix, parmat, tempmat);
928
929                         /* without this, changes to scale and rotation can change location
930                          * of a parentless bone or a disconnected bone. Even though its set
931                          * to zero above. */
932                         if (!(data->flag & CHILDOF_LOCX)) cob->matrix[3][0] = tempmat[3][0];
933                         if (!(data->flag & CHILDOF_LOCY)) cob->matrix[3][1] = tempmat[3][1];
934                         if (!(data->flag & CHILDOF_LOCZ)) cob->matrix[3][2] = tempmat[3][2];
935                 }
936         }
937 }
938
939 /* XXX note, con->flag should be CONSTRAINT_SPACEONCE for bone-childof, patched in readfile.c */
940 static bConstraintTypeInfo CTI_CHILDOF = {
941         CONSTRAINT_TYPE_CHILDOF, /* type */
942         sizeof(bChildOfConstraint), /* size */
943         "Child Of", /* name */
944         "bChildOfConstraint", /* struct name */
945         NULL, /* free data */
946         childof_id_looper, /* id looper */
947         NULL, /* copy data */
948         childof_new_data, /* new data */
949         childof_get_tars, /* get constraint targets */
950         childof_flush_tars, /* flush constraint targets */
951         default_get_tarmat, /* get a target matrix */
952         childof_evaluate /* evaluate */
953 };
954
955 /* -------- TrackTo Constraint ------- */
956
957 static void trackto_new_data(void *cdata)
958 {
959         bTrackToConstraint *data = (bTrackToConstraint *)cdata;
960
961         data->reserved1 = TRACK_Y;
962         data->reserved2 = UP_Z;
963 }
964
965 static void trackto_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
966 {
967         bTrackToConstraint *data = con->data;
968
969         /* target only */
970         func(con, (ID **)&data->tar, false, userdata);
971 }
972
973 static int trackto_get_tars(bConstraint *con, ListBase *list)
974 {
975         if (con && list) {
976                 bTrackToConstraint *data = con->data;
977                 bConstraintTarget *ct;
978
979                 /* standard target-getting macro for single-target constraints */
980                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
981
982                 return 1;
983         }
984
985         return 0;
986 }
987
988 static void trackto_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
989 {
990         if (con && list) {
991                 bTrackToConstraint *data = con->data;
992                 bConstraintTarget *ct = list->first;
993
994                 /* the following macro is used for all standard single-target constraints */
995                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
996         }
997 }
998
999
1000 static int basis_cross(int n, int m)
1001 {
1002         switch (n - m) {
1003                 case 1:
1004                 case -2:
1005                         return 1;
1006
1007                 case -1:
1008                 case 2:
1009                         return -1;
1010
1011                 default:
1012                         return 0;
1013         }
1014 }
1015
1016 static void vectomat(const float vec[3], const float target_up[3], short axis, short upflag, short flags, float m[3][3])
1017 {
1018         float n[3];
1019         float u[3]; /* vector specifying the up axis */
1020         float proj[3];
1021         float right[3];
1022         float neg = -1;
1023         int right_index;
1024
1025         if (normalize_v3_v3(n, vec) == 0.0f) {
1026                 n[0] = 0.0f;
1027                 n[1] = 0.0f;
1028                 n[2] = 1.0f;
1029         }
1030         if (axis > 2) axis -= 3;
1031         else negate_v3(n);
1032
1033         /* n specifies the transformation of the track axis */
1034         if (flags & TARGET_Z_UP) {
1035                 /* target Z axis is the global up axis */
1036                 copy_v3_v3(u, target_up);
1037         }
1038         else {
1039                 /* world Z axis is the global up axis */
1040                 u[0] = 0;
1041                 u[1] = 0;
1042                 u[2] = 1;
1043         }
1044
1045         /* note: even though 'n' is normalized, don't use 'project_v3_v3v3_normalized' below
1046          * because precision issues cause a problem in near degenerate states, see: T53455. */
1047
1048         /* project the up vector onto the plane specified by n */
1049         project_v3_v3v3(proj, u, n); /* first u onto n... */
1050         sub_v3_v3v3(proj, u, proj); /* then onto the plane */
1051         /* proj specifies the transformation of the up axis */
1052
1053         if (normalize_v3(proj) == 0.0f) { /* degenerate projection */
1054                 proj[0] = 0.0f;
1055                 proj[1] = 1.0f;
1056                 proj[2] = 0.0f;
1057         }
1058
1059         /* Normalized cross product of n and proj specifies transformation of the right axis */
1060         cross_v3_v3v3(right, proj, n);
1061         normalize_v3(right);
1062
1063         if (axis != upflag) {
1064                 right_index = 3 - axis - upflag;
1065                 neg = (float)basis_cross(axis, upflag);
1066
1067                 /* account for up direction, track direction */
1068                 m[right_index][0] = neg * right[0];
1069                 m[right_index][1] = neg * right[1];
1070                 m[right_index][2] = neg * right[2];
1071
1072                 copy_v3_v3(m[upflag], proj);
1073
1074                 copy_v3_v3(m[axis], n);
1075         }
1076         /* identity matrix - don't do anything if the two axes are the same */
1077         else {
1078                 unit_m3(m);
1079         }
1080 }
1081
1082
1083 static void trackto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1084 {
1085         bTrackToConstraint *data = con->data;
1086         bConstraintTarget *ct = targets->first;
1087
1088         if (VALID_CONS_TARGET(ct)) {
1089                 float size[3], vec[3];
1090                 float totmat[3][3];
1091
1092                 /* Get size property, since ob->size is only the object's own relative size, not its global one */
1093                 mat4_to_size(size, cob->matrix);
1094
1095                 /* Clear the object's rotation */
1096                 cob->matrix[0][0] = size[0];
1097                 cob->matrix[0][1] = 0;
1098                 cob->matrix[0][2] = 0;
1099                 cob->matrix[1][0] = 0;
1100                 cob->matrix[1][1] = size[1];
1101                 cob->matrix[1][2] = 0;
1102                 cob->matrix[2][0] = 0;
1103                 cob->matrix[2][1] = 0;
1104                 cob->matrix[2][2] = size[2];
1105
1106                 /* targetmat[2] instead of ownermat[2] is passed to vectomat
1107                  * for backwards compatibility it seems... (Aligorith)
1108                  */
1109                 sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);
1110                 vectomat(vec, ct->matrix[2],
1111                          (short)data->reserved1, (short)data->reserved2,
1112                          data->flags, totmat);
1113
1114                 mul_m4_m3m4(cob->matrix, totmat, cob->matrix);
1115         }
1116 }
1117
1118 static bConstraintTypeInfo CTI_TRACKTO = {
1119         CONSTRAINT_TYPE_TRACKTO, /* type */
1120         sizeof(bTrackToConstraint), /* size */
1121         "Track To", /* name */
1122         "bTrackToConstraint", /* struct name */
1123         NULL, /* free data */
1124         trackto_id_looper, /* id looper */
1125         NULL, /* copy data */
1126         trackto_new_data, /* new data */
1127         trackto_get_tars, /* get constraint targets */
1128         trackto_flush_tars, /* flush constraint targets */
1129         default_get_tarmat, /* get target matrix */
1130         trackto_evaluate /* evaluate */
1131 };
1132
1133 /* --------- Inverse-Kinematics --------- */
1134
1135 static void kinematic_new_data(void *cdata)
1136 {
1137         bKinematicConstraint *data = (bKinematicConstraint *)cdata;
1138
1139         data->weight = 1.0f;
1140         data->orientweight = 1.0f;
1141         data->iterations = 500;
1142         data->dist = 1.0f;
1143         data->flag = CONSTRAINT_IK_TIP | CONSTRAINT_IK_STRETCH | CONSTRAINT_IK_POS;
1144 }
1145
1146 static void kinematic_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1147 {
1148         bKinematicConstraint *data = con->data;
1149
1150         /* chain target */
1151         func(con, (ID **)&data->tar, false, userdata);
1152
1153         /* poletarget */
1154         func(con, (ID **)&data->poletar, false, userdata);
1155 }
1156
1157 static int kinematic_get_tars(bConstraint *con, ListBase *list)
1158 {
1159         if (con && list) {
1160                 bKinematicConstraint *data = con->data;
1161                 bConstraintTarget *ct;
1162
1163                 /* standard target-getting macro for single-target constraints is used twice here */
1164                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1165                 SINGLETARGET_GET_TARS(con, data->poletar, data->polesubtarget, ct, list);
1166
1167                 return 2;
1168         }
1169
1170         return 0;
1171 }
1172
1173 static void kinematic_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
1174 {
1175         if (con && list) {
1176                 bKinematicConstraint *data = con->data;
1177                 bConstraintTarget *ct = list->first;
1178
1179                 /* the following macro is used for all standard single-target constraints */
1180                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
1181                 SINGLETARGET_FLUSH_TARS(con, data->poletar, data->polesubtarget, ct, list, no_copy);
1182         }
1183 }
1184
1185 static void kinematic_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
1186 {
1187         bKinematicConstraint *data = con->data;
1188
1189         if (VALID_CONS_TARGET(ct))
1190                 constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->flag, con->headtail);
1191         else if (ct) {
1192                 if (data->flag & CONSTRAINT_IK_AUTO) {
1193                         Object *ob = cob->ob;
1194
1195                         if (ob == NULL) {
1196                                 unit_m4(ct->matrix);
1197                         }
1198                         else {
1199                                 float vec[3];
1200                                 /* move grabtarget into world space */
1201                                 mul_v3_m4v3(vec, ob->obmat, data->grabtarget);
1202                                 copy_m4_m4(ct->matrix, ob->obmat);
1203                                 copy_v3_v3(ct->matrix[3], vec);
1204                         }
1205                 }
1206                 else
1207                         unit_m4(ct->matrix);
1208         }
1209 }
1210
1211 static bConstraintTypeInfo CTI_KINEMATIC = {
1212         CONSTRAINT_TYPE_KINEMATIC, /* type */
1213         sizeof(bKinematicConstraint), /* size */
1214         "IK", /* name */
1215         "bKinematicConstraint", /* struct name */
1216         NULL, /* free data */
1217         kinematic_id_looper, /* id looper */
1218         NULL, /* copy data */
1219         kinematic_new_data, /* new data */
1220         kinematic_get_tars, /* get constraint targets */
1221         kinematic_flush_tars, /* flush constraint targets */
1222         kinematic_get_tarmat, /* get target matrix */
1223         NULL /* evaluate - solved as separate loop */
1224 };
1225
1226 /* -------- Follow-Path Constraint ---------- */
1227
1228 static void followpath_new_data(void *cdata)
1229 {
1230         bFollowPathConstraint *data = (bFollowPathConstraint *)cdata;
1231
1232         data->trackflag = TRACK_Y;
1233         data->upflag = UP_Z;
1234         data->offset = 0;
1235         data->followflag = 0;
1236 }
1237
1238 static void followpath_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1239 {
1240         bFollowPathConstraint *data = con->data;
1241
1242         /* target only */
1243         func(con, (ID **)&data->tar, false, userdata);
1244 }
1245
1246 static int followpath_get_tars(bConstraint *con, ListBase *list)
1247 {
1248         if (con && list) {
1249                 bFollowPathConstraint *data = con->data;
1250                 bConstraintTarget *ct;
1251
1252                 /* standard target-getting macro for single-target constraints without subtargets */
1253                 SINGLETARGETNS_GET_TARS(con, data->tar, ct, list);
1254
1255                 return 1;
1256         }
1257
1258         return 0;
1259 }
1260
1261 static void followpath_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
1262 {
1263         if (con && list) {
1264                 bFollowPathConstraint *data = con->data;
1265                 bConstraintTarget *ct = list->first;
1266
1267                 /* the following macro is used for all standard single-target constraints */
1268                 SINGLETARGETNS_FLUSH_TARS(con, data->tar, ct, list, no_copy);
1269         }
1270 }
1271
1272 static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph),
1273                                   bConstraint *con, bConstraintOb *UNUSED(cob),
1274                                   bConstraintTarget *ct, float UNUSED(ctime))
1275 {
1276         bFollowPathConstraint *data = con->data;
1277
1278         if (VALID_CONS_TARGET(ct) && (ct->tar->type == OB_CURVE)) {
1279                 Curve *cu = ct->tar->data;
1280                 float vec[4], dir[3], radius;
1281                 float curvetime;
1282
1283                 unit_m4(ct->matrix);
1284
1285                 /* note: when creating constraints that follow path, the curve gets the CU_PATH set now,
1286                  * currently for paths to work it needs to go through the bevlist/displist system (ton)
1287                  */
1288
1289                 if (ct->tar->runtime.curve_cache && ct->tar->runtime.curve_cache->path && ct->tar->runtime.curve_cache->path->data) {
1290                         float quat[4];
1291                         if ((data->followflag & FOLLOWPATH_STATIC) == 0) {
1292                                 /* animated position along curve depending on time */
1293                                 Nurb *nu = cu->nurb.first;
1294                                 curvetime = cu->ctime - data->offset;
1295
1296                                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1297                                  * but this will only work if it actually is animated...
1298                                  *
1299                                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1300                                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1301                                  */
1302                                 curvetime /= cu->pathlen;
1303
1304                                 if (nu && nu->flagu & CU_NURB_CYCLIC) {
1305                                         /* If the curve is cyclic, enable looping around if the time is
1306                                          * outside the bounds 0..1 */
1307                                         if ((curvetime < 0.0f) || (curvetime > 1.0f)) {
1308                                                 curvetime -= floorf(curvetime);
1309                                         }
1310                                 }
1311                                 else {
1312                                         /* The curve is not cyclic, so clamp to the begin/end points. */
1313                                         CLAMP(curvetime, 0.0f, 1.0f);
1314                                 }
1315                         }
1316                         else {
1317                                 /* fixed position along curve */
1318                                 curvetime = data->offset_fac;
1319                         }
1320
1321                         if (where_on_path(ct->tar, curvetime, vec, dir, (data->followflag & FOLLOWPATH_FOLLOW) ? quat : NULL, &radius, NULL) ) {  /* quat_pt is quat or NULL*/
1322                                 float totmat[4][4];
1323                                 unit_m4(totmat);
1324
1325                                 if (data->followflag & FOLLOWPATH_FOLLOW) {
1326                                         quat_apply_track(quat, data->trackflag, data->upflag);
1327                                         quat_to_mat4(totmat, quat);
1328                                 }
1329
1330                                 if (data->followflag & FOLLOWPATH_RADIUS) {
1331                                         float tmat[4][4], rmat[4][4];
1332                                         scale_m4_fl(tmat, radius);
1333                                         mul_m4_m4m4(rmat, tmat, totmat);
1334                                         copy_m4_m4(totmat, rmat);
1335                                 }
1336
1337                                 copy_v3_v3(totmat[3], vec);
1338
1339                                 mul_m4_m4m4(ct->matrix, ct->tar->obmat, totmat);
1340                         }
1341                 }
1342         }
1343         else if (ct)
1344                 unit_m4(ct->matrix);
1345 }
1346
1347 static void followpath_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1348 {
1349         bConstraintTarget *ct = targets->first;
1350
1351         /* only evaluate if there is a target */
1352         if (VALID_CONS_TARGET(ct)) {
1353                 float obmat[4][4];
1354                 float size[3];
1355                 bFollowPathConstraint *data = con->data;
1356
1357                 /* get Object transform (loc/rot/size) to determine transformation from path */
1358                 /* TODO: this used to be local at one point, but is probably more useful as-is */
1359                 copy_m4_m4(obmat, cob->matrix);
1360
1361                 /* get scaling of object before applying constraint */
1362                 mat4_to_size(size, cob->matrix);
1363
1364                 /* apply targetmat - containing location on path, and rotation */
1365                 mul_m4_m4m4(cob->matrix, ct->matrix, obmat);
1366
1367                 /* un-apply scaling caused by path */
1368                 if ((data->followflag & FOLLOWPATH_RADIUS) == 0) { /* XXX - assume that scale correction means that radius will have some scale error in it - Campbell */
1369                         float obsize[3];
1370
1371                         mat4_to_size(obsize, cob->matrix);
1372                         if (obsize[0])
1373                                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1374                         if (obsize[1])
1375                                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1376                         if (obsize[2])
1377                                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1378                 }
1379         }
1380 }
1381
1382 static bConstraintTypeInfo CTI_FOLLOWPATH = {
1383         CONSTRAINT_TYPE_FOLLOWPATH, /* type */
1384         sizeof(bFollowPathConstraint), /* size */
1385         "Follow Path", /* name */
1386         "bFollowPathConstraint", /* struct name */
1387         NULL, /* free data */
1388         followpath_id_looper, /* id looper */
1389         NULL, /* copy data */
1390         followpath_new_data, /* new data */
1391         followpath_get_tars, /* get constraint targets */
1392         followpath_flush_tars, /* flush constraint targets */
1393         followpath_get_tarmat, /* get target matrix */
1394         followpath_evaluate /* evaluate */
1395 };
1396
1397 /* --------- Limit Location --------- */
1398
1399
1400 static void loclimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1401 {
1402         bLocLimitConstraint *data = con->data;
1403
1404         if (data->flag & LIMIT_XMIN) {
1405                 if (cob->matrix[3][0] < data->xmin)
1406                         cob->matrix[3][0] = data->xmin;
1407         }
1408         if (data->flag & LIMIT_XMAX) {
1409                 if (cob->matrix[3][0] > data->xmax)
1410                         cob->matrix[3][0] = data->xmax;
1411         }
1412         if (data->flag & LIMIT_YMIN) {
1413                 if (cob->matrix[3][1] < data->ymin)
1414                         cob->matrix[3][1] = data->ymin;
1415         }
1416         if (data->flag & LIMIT_YMAX) {
1417                 if (cob->matrix[3][1] > data->ymax)
1418                         cob->matrix[3][1] = data->ymax;
1419         }
1420         if (data->flag & LIMIT_ZMIN) {
1421                 if (cob->matrix[3][2] < data->zmin)
1422                         cob->matrix[3][2] = data->zmin;
1423         }
1424         if (data->flag & LIMIT_ZMAX) {
1425                 if (cob->matrix[3][2] > data->zmax)
1426                         cob->matrix[3][2] = data->zmax;
1427         }
1428 }
1429
1430 static bConstraintTypeInfo CTI_LOCLIMIT = {
1431         CONSTRAINT_TYPE_LOCLIMIT, /* type */
1432         sizeof(bLocLimitConstraint), /* size */
1433         "Limit Location", /* name */
1434         "bLocLimitConstraint", /* struct name */
1435         NULL, /* free data */
1436         NULL, /* id looper */
1437         NULL, /* copy data */
1438         NULL, /* new data */
1439         NULL, /* get constraint targets */
1440         NULL, /* flush constraint targets */
1441         NULL, /* get target matrix */
1442         loclimit_evaluate /* evaluate */
1443 };
1444
1445 /* -------- Limit Rotation --------- */
1446
1447 static void rotlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1448 {
1449         bRotLimitConstraint *data = con->data;
1450         float loc[3];
1451         float eul[3];
1452         float size[3];
1453
1454         copy_v3_v3(loc, cob->matrix[3]);
1455         mat4_to_size(size, cob->matrix);
1456
1457         mat4_to_eulO(eul, cob->rotOrder, cob->matrix);
1458
1459         /* constraint data uses radians internally */
1460
1461         /* limiting of euler values... */
1462         if (data->flag & LIMIT_XROT) {
1463                 if (eul[0] < data->xmin)
1464                         eul[0] = data->xmin;
1465
1466                 if (eul[0] > data->xmax)
1467                         eul[0] = data->xmax;
1468         }
1469         if (data->flag & LIMIT_YROT) {
1470                 if (eul[1] < data->ymin)
1471                         eul[1] = data->ymin;
1472
1473                 if (eul[1] > data->ymax)
1474                         eul[1] = data->ymax;
1475         }
1476         if (data->flag & LIMIT_ZROT) {
1477                 if (eul[2] < data->zmin)
1478                         eul[2] = data->zmin;
1479
1480                 if (eul[2] > data->zmax)
1481                         eul[2] = data->zmax;
1482         }
1483
1484         loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder);
1485 }
1486
1487 static bConstraintTypeInfo CTI_ROTLIMIT = {
1488         CONSTRAINT_TYPE_ROTLIMIT, /* type */
1489         sizeof(bRotLimitConstraint), /* size */
1490         "Limit Rotation", /* name */
1491         "bRotLimitConstraint", /* struct name */
1492         NULL, /* free data */
1493         NULL, /* id looper */
1494         NULL, /* copy data */
1495         NULL, /* new data */
1496         NULL, /* get constraint targets */
1497         NULL, /* flush constraint targets */
1498         NULL, /* get target matrix */
1499         rotlimit_evaluate /* evaluate */
1500 };
1501
1502 /* --------- Limit Scale --------- */
1503
1504
1505 static void sizelimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1506 {
1507         bSizeLimitConstraint *data = con->data;
1508         float obsize[3], size[3];
1509
1510         mat4_to_size(size, cob->matrix);
1511         mat4_to_size(obsize, cob->matrix);
1512
1513         if (data->flag & LIMIT_XMIN) {
1514                 if (size[0] < data->xmin)
1515                         size[0] = data->xmin;
1516         }
1517         if (data->flag & LIMIT_XMAX) {
1518                 if (size[0] > data->xmax)
1519                         size[0] = data->xmax;
1520         }
1521         if (data->flag & LIMIT_YMIN) {
1522                 if (size[1] < data->ymin)
1523                         size[1] = data->ymin;
1524         }
1525         if (data->flag & LIMIT_YMAX) {
1526                 if (size[1] > data->ymax)
1527                         size[1] = data->ymax;
1528         }
1529         if (data->flag & LIMIT_ZMIN) {
1530                 if (size[2] < data->zmin)
1531                         size[2] = data->zmin;
1532         }
1533         if (data->flag & LIMIT_ZMAX) {
1534                 if (size[2] > data->zmax)
1535                         size[2] = data->zmax;
1536         }
1537
1538         if (obsize[0])
1539                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1540         if (obsize[1])
1541                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1542         if (obsize[2])
1543                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1544 }
1545
1546 static bConstraintTypeInfo CTI_SIZELIMIT = {
1547         CONSTRAINT_TYPE_SIZELIMIT, /* type */
1548         sizeof(bSizeLimitConstraint), /* size */
1549         "Limit Scale", /* name */
1550         "bSizeLimitConstraint", /* struct name */
1551         NULL, /* free data */
1552         NULL, /* id looper */
1553         NULL, /* copy data */
1554         NULL, /* new data */
1555         NULL, /* get constraint targets */
1556         NULL, /* flush constraint targets */
1557         NULL, /* get target matrix */
1558         sizelimit_evaluate /* evaluate */
1559 };
1560
1561 /* ----------- Copy Location ------------- */
1562
1563 static void loclike_new_data(void *cdata)
1564 {
1565         bLocateLikeConstraint *data = (bLocateLikeConstraint *)cdata;
1566
1567         data->flag = LOCLIKE_X | LOCLIKE_Y | LOCLIKE_Z;
1568 }
1569
1570 static void loclike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1571 {
1572         bLocateLikeConstraint *data = con->data;
1573
1574         /* target only */
1575         func(con, (ID **)&data->tar, false, userdata);
1576 }
1577
1578 static int loclike_get_tars(bConstraint *con, ListBase *list)
1579 {
1580         if (con && list) {
1581                 bLocateLikeConstraint *data = con->data;
1582                 bConstraintTarget *ct;
1583
1584                 /* standard target-getting macro for single-target constraints */
1585                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1586
1587                 return 1;
1588         }
1589
1590         return 0;
1591 }
1592
1593 static void loclike_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
1594 {
1595         if (con && list) {
1596                 bLocateLikeConstraint *data = con->data;
1597                 bConstraintTarget *ct = list->first;
1598
1599                 /* the following macro is used for all standard single-target constraints */
1600                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
1601         }
1602 }
1603
1604 static void loclike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1605 {
1606         bLocateLikeConstraint *data = con->data;
1607         bConstraintTarget *ct = targets->first;
1608
1609         if (VALID_CONS_TARGET(ct)) {
1610                 float offset[3] = {0.0f, 0.0f, 0.0f};
1611
1612                 if (data->flag & LOCLIKE_OFFSET)
1613                         copy_v3_v3(offset, cob->matrix[3]);
1614
1615                 if (data->flag & LOCLIKE_X) {
1616                         cob->matrix[3][0] = ct->matrix[3][0];
1617
1618                         if (data->flag & LOCLIKE_X_INVERT) cob->matrix[3][0] *= -1;
1619                         cob->matrix[3][0] += offset[0];
1620                 }
1621                 if (data->flag & LOCLIKE_Y) {
1622                         cob->matrix[3][1] = ct->matrix[3][1];
1623
1624                         if (data->flag & LOCLIKE_Y_INVERT) cob->matrix[3][1] *= -1;
1625                         cob->matrix[3][1] += offset[1];
1626                 }
1627                 if (data->flag & LOCLIKE_Z) {
1628                         cob->matrix[3][2] = ct->matrix[3][2];
1629
1630                         if (data->flag & LOCLIKE_Z_INVERT) cob->matrix[3][2] *= -1;
1631                         cob->matrix[3][2] += offset[2];
1632                 }
1633         }
1634 }
1635
1636 static bConstraintTypeInfo CTI_LOCLIKE = {
1637         CONSTRAINT_TYPE_LOCLIKE, /* type */
1638         sizeof(bLocateLikeConstraint), /* size */
1639         "Copy Location", /* name */
1640         "bLocateLikeConstraint", /* struct name */
1641         NULL, /* free data */
1642         loclike_id_looper, /* id looper */
1643         NULL, /* copy data */
1644         loclike_new_data, /* new data */
1645         loclike_get_tars, /* get constraint targets */
1646         loclike_flush_tars, /* flush constraint targets */
1647         default_get_tarmat, /* get target matrix */
1648         loclike_evaluate /* evaluate */
1649 };
1650
1651 /* ----------- Copy Rotation ------------- */
1652
1653 static void rotlike_new_data(void *cdata)
1654 {
1655         bRotateLikeConstraint *data = (bRotateLikeConstraint *)cdata;
1656
1657         data->flag = ROTLIKE_X | ROTLIKE_Y | ROTLIKE_Z;
1658 }
1659
1660 static void rotlike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1661 {
1662         bRotateLikeConstraint *data = con->data;
1663
1664         /* target only */
1665         func(con, (ID **)&data->tar, false, userdata);
1666 }
1667
1668 static int rotlike_get_tars(bConstraint *con, ListBase *list)
1669 {
1670         if (con && list) {
1671                 bRotateLikeConstraint *data = con->data;
1672                 bConstraintTarget *ct;
1673
1674                 /* standard target-getting macro for single-target constraints */
1675                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1676
1677                 return 1;
1678         }
1679
1680         return 0;
1681 }
1682
1683 static void rotlike_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
1684 {
1685         if (con && list) {
1686                 bRotateLikeConstraint *data = con->data;
1687                 bConstraintTarget *ct = list->first;
1688
1689                 /* the following macro is used for all standard single-target constraints */
1690                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
1691         }
1692 }
1693
1694 static void rotlike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1695 {
1696         bRotateLikeConstraint *data = con->data;
1697         bConstraintTarget *ct = targets->first;
1698
1699         if (VALID_CONS_TARGET(ct)) {
1700                 float loc[3];
1701                 float eul[3], obeul[3];
1702                 float size[3];
1703
1704                 copy_v3_v3(loc, cob->matrix[3]);
1705                 mat4_to_size(size, cob->matrix);
1706
1707                 /* to allow compatible rotations, must get both rotations in the order of the owner... */
1708                 mat4_to_eulO(obeul, cob->rotOrder, cob->matrix);
1709                 /* we must get compatible eulers from the beginning because some of them can be modified below (see bug #21875) */
1710                 mat4_to_compatible_eulO(eul, obeul, cob->rotOrder, ct->matrix);
1711
1712                 if ((data->flag & ROTLIKE_X) == 0)
1713                         eul[0] = obeul[0];
1714                 else {
1715                         if (data->flag & ROTLIKE_OFFSET)
1716                                 rotate_eulO(eul, cob->rotOrder, 'X', obeul[0]);
1717
1718                         if (data->flag & ROTLIKE_X_INVERT)
1719                                 eul[0] *= -1;
1720                 }
1721
1722                 if ((data->flag & ROTLIKE_Y) == 0)
1723                         eul[1] = obeul[1];
1724                 else {
1725                         if (data->flag & ROTLIKE_OFFSET)
1726                                 rotate_eulO(eul, cob->rotOrder, 'Y', obeul[1]);
1727
1728                         if (data->flag & ROTLIKE_Y_INVERT)
1729                                 eul[1] *= -1;
1730                 }
1731
1732                 if ((data->flag & ROTLIKE_Z) == 0)
1733                         eul[2] = obeul[2];
1734                 else {
1735                         if (data->flag & ROTLIKE_OFFSET)
1736                                 rotate_eulO(eul, cob->rotOrder, 'Z', obeul[2]);
1737
1738                         if (data->flag & ROTLIKE_Z_INVERT)
1739                                 eul[2] *= -1;
1740                 }
1741
1742                 /* good to make eulers compatible again, since we don't know how much they were changed above */
1743                 compatible_eul(eul, obeul);
1744                 loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder);
1745         }
1746 }
1747
1748 static bConstraintTypeInfo CTI_ROTLIKE = {
1749         CONSTRAINT_TYPE_ROTLIKE, /* type */
1750         sizeof(bRotateLikeConstraint), /* size */
1751         "Copy Rotation", /* name */
1752         "bRotateLikeConstraint", /* struct name */
1753         NULL, /* free data */
1754         rotlike_id_looper, /* id looper */
1755         NULL, /* copy data */
1756         rotlike_new_data, /* new data */
1757         rotlike_get_tars, /* get constraint targets */
1758         rotlike_flush_tars, /* flush constraint targets */
1759         default_get_tarmat, /* get target matrix */
1760         rotlike_evaluate /* evaluate */
1761 };
1762
1763 /* ---------- Copy Scale ---------- */
1764
1765 static void sizelike_new_data(void *cdata)
1766 {
1767         bSizeLikeConstraint *data = (bSizeLikeConstraint *)cdata;
1768
1769         data->flag = SIZELIKE_X | SIZELIKE_Y | SIZELIKE_Z | SIZELIKE_MULTIPLY;
1770 }
1771
1772 static void sizelike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1773 {
1774         bSizeLikeConstraint *data = con->data;
1775
1776         /* target only */
1777         func(con, (ID **)&data->tar, false, userdata);
1778 }
1779
1780 static int sizelike_get_tars(bConstraint *con, ListBase *list)
1781 {
1782         if (con && list) {
1783                 bSizeLikeConstraint *data = con->data;
1784                 bConstraintTarget *ct;
1785
1786                 /* standard target-getting macro for single-target constraints */
1787                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1788
1789                 return 1;
1790         }
1791
1792         return 0;
1793 }
1794
1795 static void sizelike_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
1796 {
1797         if (con && list) {
1798                 bSizeLikeConstraint *data = con->data;
1799                 bConstraintTarget *ct = list->first;
1800
1801                 /* the following macro is used for all standard single-target constraints */
1802                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
1803         }
1804 }
1805
1806 static void sizelike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1807 {
1808         bSizeLikeConstraint *data = con->data;
1809         bConstraintTarget *ct = targets->first;
1810
1811         if (VALID_CONS_TARGET(ct)) {
1812                 float obsize[3], size[3];
1813
1814                 mat4_to_size(size, ct->matrix);
1815                 mat4_to_size(obsize, cob->matrix);
1816
1817                 if (data->flag & SIZELIKE_OFFSET) {
1818                         /* Scale is a multiplicative quantity, so adding it makes no sense.
1819                          * However, the additive mode has to stay for backward compatibility. */
1820                         if (data->flag & SIZELIKE_MULTIPLY) {
1821                                 /* size[i] *= obsize[i] */
1822                                 mul_v3_v3(size, obsize);
1823                         }
1824                         else {
1825                                 /* 2.7 compatibility mode: size[i] += (obsize[i] - 1.0f) */
1826                                 add_v3_v3(size, obsize);
1827                                 add_v3_fl(size, -1.0f);
1828                         }
1829                 }
1830
1831                 if ((data->flag & SIZELIKE_X) && (obsize[0] != 0)) {
1832                         mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1833                 }
1834                 if ((data->flag & SIZELIKE_Y) && (obsize[1] != 0)) {
1835                         mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1836                 }
1837                 if ((data->flag & SIZELIKE_Z) && (obsize[2] != 0)) {
1838                         mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1839                 }
1840         }
1841 }
1842
1843 static bConstraintTypeInfo CTI_SIZELIKE = {
1844         CONSTRAINT_TYPE_SIZELIKE, /* type */
1845         sizeof(bSizeLikeConstraint), /* size */
1846         "Copy Scale", /* name */
1847         "bSizeLikeConstraint", /* struct name */
1848         NULL, /* free data */
1849         sizelike_id_looper, /* id looper */
1850         NULL, /* copy data */
1851         sizelike_new_data, /* new data */
1852         sizelike_get_tars, /* get constraint targets */
1853         sizelike_flush_tars, /* flush constraint targets */
1854         default_get_tarmat, /* get target matrix */
1855         sizelike_evaluate /* evaluate */
1856 };
1857
1858 /* ----------- Copy Transforms ------------- */
1859
1860 static void translike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1861 {
1862         bTransLikeConstraint *data = con->data;
1863
1864         /* target only */
1865         func(con, (ID **)&data->tar, false, userdata);
1866 }
1867
1868 static int translike_get_tars(bConstraint *con, ListBase *list)
1869 {
1870         if (con && list) {
1871                 bTransLikeConstraint *data = con->data;
1872                 bConstraintTarget *ct;
1873
1874                 /* standard target-getting macro for single-target constraints */
1875                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1876
1877                 return 1;
1878         }
1879
1880         return 0;
1881 }
1882
1883 static void translike_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
1884 {
1885         if (con && list) {
1886                 bTransLikeConstraint *data = con->data;
1887                 bConstraintTarget *ct = list->first;
1888
1889                 /* the following macro is used for all standard single-target constraints */
1890                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
1891         }
1892 }
1893
1894 static void translike_evaluate(bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets)
1895 {
1896         bConstraintTarget *ct = targets->first;
1897
1898         if (VALID_CONS_TARGET(ct)) {
1899                 /* just copy the entire transform matrix of the target */
1900                 copy_m4_m4(cob->matrix, ct->matrix);
1901         }
1902 }
1903
1904 static bConstraintTypeInfo CTI_TRANSLIKE = {
1905         CONSTRAINT_TYPE_TRANSLIKE, /* type */
1906         sizeof(bTransLikeConstraint), /* size */
1907         "Copy Transforms", /* name */
1908         "bTransLikeConstraint", /* struct name */
1909         NULL, /* free data */
1910         translike_id_looper, /* id looper */
1911         NULL, /* copy data */
1912         NULL, /* new data */
1913         translike_get_tars, /* get constraint targets */
1914         translike_flush_tars, /* flush constraint targets */
1915         default_get_tarmat_full_bbone, /* get target matrix */
1916         translike_evaluate /* evaluate */
1917 };
1918
1919 /* ---------- Maintain Volume ---------- */
1920
1921 static void samevolume_new_data(void *cdata)
1922 {
1923         bSameVolumeConstraint *data = (bSameVolumeConstraint *)cdata;
1924
1925         data->flag = SAMEVOL_Y;
1926         data->volume = 1.0f;
1927 }
1928
1929 static void samevolume_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1930 {
1931         bSameVolumeConstraint *data = con->data;
1932
1933         float volume = data->volume;
1934         float fac = 1.0f, total_scale;
1935         float obsize[3];
1936
1937         mat4_to_size(obsize, cob->matrix);
1938
1939         /* calculate normalizing scale factor for non-essential values */
1940         total_scale = obsize[0] * obsize[1] * obsize[2];
1941         if (total_scale != 0)
1942                 fac = sqrtf(volume / total_scale);
1943
1944         /* apply scaling factor to the channels not being kept */
1945         switch (data->flag) {
1946                 case SAMEVOL_X:
1947                         mul_v3_fl(cob->matrix[1], fac);
1948                         mul_v3_fl(cob->matrix[2], fac);
1949                         break;
1950                 case SAMEVOL_Y:
1951                         mul_v3_fl(cob->matrix[0], fac);
1952                         mul_v3_fl(cob->matrix[2], fac);
1953                         break;
1954                 case SAMEVOL_Z:
1955                         mul_v3_fl(cob->matrix[0], fac);
1956                         mul_v3_fl(cob->matrix[1], fac);
1957                         break;
1958         }
1959 }
1960
1961 static bConstraintTypeInfo CTI_SAMEVOL = {
1962         CONSTRAINT_TYPE_SAMEVOL, /* type */
1963         sizeof(bSameVolumeConstraint), /* size */
1964         "Maintain Volume", /* name */
1965         "bSameVolumeConstraint", /* struct name */
1966         NULL, /* free data */
1967         NULL, /* id looper */
1968         NULL, /* copy data */
1969         samevolume_new_data, /* new data */
1970         NULL, /* get constraint targets */
1971         NULL, /* flush constraint targets */
1972         NULL, /* get target matrix */
1973         samevolume_evaluate /* evaluate */
1974 };
1975
1976 /* ----------- Python Constraint -------------- */
1977
1978 static void pycon_free(bConstraint *con)
1979 {
1980         bPythonConstraint *data = con->data;
1981
1982         /* id-properties */
1983         IDP_FreeProperty(data->prop);
1984         MEM_freeN(data->prop);
1985
1986         /* multiple targets */
1987         BLI_freelistN(&data->targets);
1988 }
1989
1990 static void pycon_copy(bConstraint *con, bConstraint *srccon)
1991 {
1992         bPythonConstraint *pycon = (bPythonConstraint *)con->data;
1993         bPythonConstraint *opycon = (bPythonConstraint *)srccon->data;
1994
1995         pycon->prop = IDP_CopyProperty(opycon->prop);
1996         BLI_duplicatelist(&pycon->targets, &opycon->targets);
1997 }
1998
1999 static void pycon_new_data(void *cdata)
2000 {
2001         bPythonConstraint *data = (bPythonConstraint *)cdata;
2002
2003         /* everything should be set correctly by calloc, except for the prop->type constant.*/
2004         data->prop = MEM_callocN(sizeof(IDProperty), "PyConstraintProps");
2005         data->prop->type = IDP_GROUP;
2006 }
2007
2008 static int pycon_get_tars(bConstraint *con, ListBase *list)
2009 {
2010         if (con && list) {
2011                 bPythonConstraint *data = con->data;
2012
2013                 list->first = data->targets.first;
2014                 list->last = data->targets.last;
2015
2016                 return data->tarnum;
2017         }
2018
2019         return 0;
2020 }
2021
2022 static void pycon_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2023 {
2024         bPythonConstraint *data = con->data;
2025         bConstraintTarget *ct;
2026
2027         /* targets */
2028         for (ct = data->targets.first; ct; ct = ct->next)
2029                 func(con, (ID **)&ct->tar, false, userdata);
2030
2031         /* script */
2032         func(con, (ID **)&data->text, true, userdata);
2033 }
2034
2035 /* Whether this approach is maintained remains to be seen (aligorith) */
2036 static void pycon_get_tarmat(struct Depsgraph *UNUSED(depsgraph),
2037                              bConstraint *con, bConstraintOb *UNUSED(cob),
2038                              bConstraintTarget *ct, float UNUSED(ctime))
2039 {
2040 #ifdef WITH_PYTHON
2041         bPythonConstraint *data = con->data;
2042 #endif
2043
2044         if (VALID_CONS_TARGET(ct)) {
2045                 if (ct->tar->type == OB_CURVE && ct->tar->runtime.curve_cache == NULL) {
2046                         unit_m4(ct->matrix);
2047                         return;
2048                 }
2049
2050                 /* firstly calculate the matrix the normal way, then let the py-function override
2051                  * this matrix if it needs to do so
2052                  */
2053                 constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->flag, con->headtail);
2054
2055                 /* only execute target calculation if allowed */
2056 #ifdef WITH_PYTHON
2057                 if (G.f & G_FLAG_SCRIPT_AUTOEXEC)
2058                         BPY_pyconstraint_target(data, ct);
2059 #endif
2060         }
2061         else if (ct)
2062                 unit_m4(ct->matrix);
2063 }
2064
2065 static void pycon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
2066 {
2067 #ifndef WITH_PYTHON
2068         UNUSED_VARS(con, cob, targets);
2069         return;
2070 #else
2071         bPythonConstraint *data = con->data;
2072
2073         /* only evaluate in python if we're allowed to do so */
2074         if ((G.f & G_FLAG_SCRIPT_AUTOEXEC) == 0) return;
2075
2076         /* Now, run the actual 'constraint' function, which should only access the matrices */
2077         BPY_pyconstraint_exec(data, cob, targets);
2078 #endif /* WITH_PYTHON */
2079 }
2080
2081 static bConstraintTypeInfo CTI_PYTHON = {
2082         CONSTRAINT_TYPE_PYTHON, /* type */
2083         sizeof(bPythonConstraint), /* size */
2084         "Script", /* name */
2085         "bPythonConstraint", /* struct name */
2086         pycon_free, /* free data */
2087         pycon_id_looper, /* id looper */
2088         pycon_copy, /* copy data */
2089         pycon_new_data, /* new data */
2090         pycon_get_tars, /* get constraint targets */
2091         NULL, /* flush constraint targets */
2092         pycon_get_tarmat, /* get target matrix */
2093         pycon_evaluate /* evaluate */
2094 };
2095
2096 /* ----------- Armature Constraint -------------- */
2097
2098 static void armdef_free(bConstraint *con)
2099 {
2100         bArmatureConstraint *data = con->data;
2101
2102         /* Target list. */
2103         BLI_freelistN(&data->targets);
2104 }
2105
2106 static void armdef_copy(bConstraint *con, bConstraint *srccon)
2107 {
2108         bArmatureConstraint *pcon = (bArmatureConstraint *)con->data;
2109         bArmatureConstraint *opcon = (bArmatureConstraint *)srccon->data;
2110
2111         BLI_duplicatelist(&pcon->targets, &opcon->targets);
2112 }
2113
2114 static int armdef_get_tars(bConstraint *con, ListBase *list)
2115 {
2116         if (con && list) {
2117                 bArmatureConstraint *data = con->data;
2118
2119                 *list = data->targets;
2120
2121                 return BLI_listbase_count(&data->targets);
2122         }
2123
2124         return 0;
2125 }
2126
2127 static void armdef_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2128 {
2129         bArmatureConstraint *data = con->data;
2130         bConstraintTarget *ct;
2131
2132         /* Target list. */
2133         for (ct = data->targets.first; ct; ct = ct->next) {
2134                 func(con, (ID **)&ct->tar, false, userdata);
2135         }
2136 }
2137
2138 /* Compute the world space pose matrix of the target bone. */
2139 static void armdef_get_tarmat(struct Depsgraph *UNUSED(depsgraph),
2140                               bConstraint *UNUSED(con), bConstraintOb *UNUSED(cob),
2141                               bConstraintTarget *ct, float UNUSED(ctime))
2142 {
2143         if (ct != NULL) {
2144                 if (ct->tar && ct->tar->type == OB_ARMATURE) {
2145                         bPoseChannel *pchan = BKE_pose_channel_find_name(ct->tar->pose, ct->subtarget);
2146
2147                         if (pchan != NULL) {
2148                                 mul_m4_m4m4(ct->matrix, ct->tar->obmat, pchan->pose_mat);
2149                                 return;
2150                         }
2151                 }
2152
2153                 unit_m4(ct->matrix);
2154         }
2155 }
2156
2157 /* Compute and accumulate transformation for a single target bone. */
2158 static void armdef_accumulate_bone(bConstraintTarget *ct, bPoseChannel *pchan, const float wco[3], bool force_envelope, float *r_totweight, float r_sum_mat[4][4], DualQuat *r_sum_dq)
2159 {
2160         float mat[4][4], iobmat[4][4], basemat[4][4], co[3];
2161         Bone *bone = pchan->bone;
2162         float weight = ct->weight;
2163
2164         /* Our object's location in target pose space. */
2165         invert_m4_m4(iobmat, ct->tar->obmat);
2166         mul_v3_m4v3(co, iobmat, wco);
2167
2168         /* Multiply by the envelope weight when appropriate. */
2169         if (force_envelope || (bone->flag & BONE_MULT_VG_ENV)) {
2170                 weight *= distfactor_to_bone(co, bone->arm_head, bone->arm_tail,
2171                                              bone->rad_head, bone->rad_tail, bone->dist);
2172         }
2173
2174         /* Find the correct bone transform matrix in world space. */
2175         if (bone->segments > 1 && bone->segments == pchan->runtime.bbone_segments) {
2176                 Mat4 *b_bone_mats = pchan->runtime.bbone_deform_mats;
2177                 float (*iamat)[4] = b_bone_mats[0].mat;
2178
2179                 /* The target is a B-Bone:
2180                  * FIRST: find the segment (see b_bone_deform in armature.c)
2181                  * Need to transform co back to bonespace, only need y. */
2182                 float y = iamat[0][1] * co[0] + iamat[1][1] * co[1] + iamat[2][1] * co[2] + iamat[3][1];
2183
2184                 float segment = bone->length / ((float)bone->segments);
2185                 int a = (int)(y / segment);
2186
2187                 CLAMP(a, 0, bone->segments - 1);
2188
2189                 /* Convert the selected matrix into object space. */
2190                 mul_m4_series(mat, ct->tar->obmat, b_bone_mats[a + 1].mat, iobmat);
2191         }
2192         else {
2193                 /* Simple bone. This requires DEG_OPCODE_BONE_DONE dependency due to chan_mat. */
2194                 mul_m4_series(mat, ct->tar->obmat, pchan->chan_mat, iobmat);
2195         }
2196
2197         /* Accumulate the transformation. */
2198         *r_totweight += weight;
2199
2200         if (r_sum_dq != NULL) {
2201                 DualQuat tmpdq;
2202
2203                 mul_m4_series(basemat, ct->tar->obmat, bone->arm_mat, iobmat);
2204
2205                 mat4_to_dquat(&tmpdq, basemat, mat);
2206                 add_weighted_dq_dq(r_sum_dq, &tmpdq, weight);
2207         }
2208         else {
2209                 mul_m4_fl(mat, weight);
2210                 add_m4_m4m4(r_sum_mat, r_sum_mat, mat);
2211         }
2212 }
2213
2214 static void armdef_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
2215 {
2216         bArmatureConstraint *data = con->data;
2217
2218         float sum_mat[4][4], input_co[3];
2219         DualQuat sum_dq;
2220         float weight = 0.0f;
2221
2222         /* Prepare for blending. */
2223         zero_m4(sum_mat);
2224         memset(&sum_dq, 0, sizeof(sum_dq));
2225
2226         DualQuat *pdq = (data->flag & CONSTRAINT_ARMATURE_QUATERNION) ? &sum_dq : NULL;
2227         bool use_envelopes = (data->flag & CONSTRAINT_ARMATURE_ENVELOPE) != 0;
2228
2229         if (cob->pchan && cob->pchan->bone && !(data->flag & CONSTRAINT_ARMATURE_CUR_LOCATION)) {
2230                 /* For constraints on bones, use the rest position to bind b-bone segments
2231                  * and envelopes, to allow safely changing the bone location as if parented. */
2232                 copy_v3_v3(input_co, cob->pchan->bone->arm_head);
2233                 mul_m4_v3(cob->ob->obmat, input_co);
2234         }
2235         else {
2236                 copy_v3_v3(input_co, cob->matrix[3]);
2237         }
2238
2239         /* Process all targets. */
2240         for (bConstraintTarget *ct = targets->first; ct; ct = ct->next) {
2241                 if (ct->weight <= 0.0f) {
2242                         continue;
2243                 }
2244
2245                 /* Lookup the bone and abort if failed. */
2246                 if (!VALID_CONS_TARGET(ct) || ct->tar->type != OB_ARMATURE) {
2247                         return;
2248                 }
2249
2250                 bPoseChannel *pchan = BKE_pose_channel_find_name(ct->tar->pose, ct->subtarget);
2251
2252                 if (pchan == NULL || pchan->bone == NULL) {
2253                         return;
2254                 }
2255
2256                 armdef_accumulate_bone(ct, pchan, input_co, use_envelopes, &weight, sum_mat, pdq);
2257         }
2258
2259         /* Compute the final transform. */
2260         if (weight > 0.0f) {
2261                 if (pdq != NULL) {
2262                         normalize_dq(pdq, weight);
2263                         dquat_to_mat4(sum_mat, pdq);
2264                 }
2265                 else {
2266                         mul_m4_fl(sum_mat, 1.0f / weight);
2267                 }
2268
2269                 /* Apply the transform to the result matrix. */
2270                 mul_m4_m4m4(cob->matrix, sum_mat, cob->matrix);
2271         }
2272 }
2273
2274 static bConstraintTypeInfo CTI_ARMATURE = {
2275         CONSTRAINT_TYPE_ARMATURE, /* type */
2276         sizeof(bArmatureConstraint), /* size */
2277         "Armature", /* name */
2278         "bArmatureConstraint", /* struct name */
2279         armdef_free, /* free data */
2280         armdef_id_looper, /* id looper */
2281         armdef_copy, /* copy data */
2282         NULL, /* new data */
2283         armdef_get_tars, /* get constraint targets */
2284         NULL, /* flush constraint targets */
2285         armdef_get_tarmat, /* get target matrix */
2286         armdef_evaluate /* evaluate */
2287 };
2288
2289 /* -------- Action Constraint ----------- */
2290
2291 static void actcon_new_data(void *cdata)
2292 {
2293         bActionConstraint *data = (bActionConstraint *)cdata;
2294
2295         /* set type to 20 (Loc X), as 0 is Rot X for backwards compatibility */
2296         data->type = 20;
2297 }
2298
2299 static void actcon_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2300 {
2301         bActionConstraint *data = con->data;
2302
2303         /* target */
2304         func(con, (ID **)&data->tar, false, userdata);
2305
2306         /* action */
2307         func(con, (ID **)&data->act, true, userdata);
2308 }
2309
2310 static int actcon_get_tars(bConstraint *con, ListBase *list)
2311 {
2312         if (con && list) {
2313                 bActionConstraint *data = con->data;
2314                 bConstraintTarget *ct;
2315
2316                 /* standard target-getting macro for single-target constraints */
2317                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2318
2319                 return 1;
2320         }
2321
2322         return 0;
2323 }
2324
2325 static void actcon_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
2326 {
2327         if (con && list) {
2328                 bActionConstraint *data = con->data;
2329                 bConstraintTarget *ct = list->first;
2330
2331                 /* the following macro is used for all standard single-target constraints */
2332                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
2333         }
2334 }
2335
2336 static void actcon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
2337 {
2338         bActionConstraint *data = con->data;
2339
2340         if (VALID_CONS_TARGET(ct)) {
2341                 float tempmat[4][4], vec[3];
2342                 float s, t;
2343                 short axis;
2344
2345                 /* initialize return matrix */
2346                 unit_m4(ct->matrix);
2347
2348                 /* get the transform matrix of the target */
2349                 constraint_target_to_mat4(ct->tar, ct->subtarget, tempmat, CONSTRAINT_SPACE_WORLD, ct->space, con->flag, con->headtail);
2350
2351                 /* determine where in transform range target is */
2352                 /* data->type is mapped as follows for backwards compatibility:
2353                  * 00,01,02 - rotation (it used to be like this)
2354                  * 10,11,12 - scaling
2355                  * 20,21,22 - location
2356                  */
2357                 if (data->type < 10) {
2358                         /* extract rotation (is in whatever space target should be in) */
2359                         mat4_to_eul(vec, tempmat);
2360                         mul_v3_fl(vec, RAD2DEGF(1.0f)); /* rad -> deg */
2361                         axis = data->type;
2362                 }
2363                 else if (data->type < 20) {
2364                         /* extract scaling (is in whatever space target should be in) */
2365                         mat4_to_size(vec, tempmat);
2366                         axis = data->type - 10;
2367                 }
2368                 else {
2369                         /* extract location */
2370                         copy_v3_v3(vec, tempmat[3]);
2371                         axis = data->type - 20;
2372                 }
2373
2374                 BLI_assert((unsigned int)axis < 3);
2375
2376                 /* Target defines the animation */
2377                 s = (vec[axis] - data->min) / (data->max - data->min);
2378                 CLAMP(s, 0, 1);
2379                 t = (s * (data->end - data->start)) + data->start;
2380
2381                 if (G.debug & G_DEBUG)
2382                         printf("do Action Constraint %s - Ob %s Pchan %s\n", con->name, cob->ob->id.name + 2, (cob->pchan) ? cob->pchan->name : NULL);
2383
2384                 /* Get the appropriate information from the action */
2385                 if (cob->type == CONSTRAINT_OBTYPE_OBJECT || (data->flag & ACTCON_BONE_USE_OBJECT_ACTION)) {
2386                         Object workob;
2387
2388                         /* evaluate using workob */
2389                         /* FIXME: we don't have any consistent standards on limiting effects on object... */
2390                         what_does_obaction(cob->ob, &workob, NULL, data->act, NULL, t);
2391                         BKE_object_to_mat4(&workob, ct->matrix);
2392                 }
2393                 else if (cob->type == CONSTRAINT_OBTYPE_BONE) {
2394                         Object workob;
2395                         bPose pose = {{0}};
2396                         bPoseChannel *pchan, *tchan;
2397
2398                         /* make a copy of the bone of interest in the temp pose before evaluating action, so that it can get set
2399                          * - we need to manually copy over a few settings, including rotation order, otherwise this fails
2400                          */
2401                         pchan = cob->pchan;
2402
2403                         tchan = BKE_pose_channel_verify(&pose, pchan->name);
2404                         tchan->rotmode = pchan->rotmode;
2405
2406                         /* evaluate action using workob (it will only set the PoseChannel in question) */
2407                         what_does_obaction(cob->ob, &workob, &pose, data->act, pchan->name, t);
2408
2409                         /* convert animation to matrices for use here */
2410                         BKE_pchan_calc_mat(tchan);
2411                         copy_m4_m4(ct->matrix, tchan->chan_mat);
2412
2413                         /* Clean up */
2414                         BKE_pose_free_data(&pose);
2415                 }
2416                 else {
2417                         /* behavior undefined... */
2418                         puts("Error: unknown owner type for Action Constraint");
2419                 }
2420         }
2421 }
2422
2423 static void actcon_evaluate(bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets)
2424 {
2425         bConstraintTarget *ct = targets->first;
2426
2427         if (VALID_CONS_TARGET(ct)) {
2428                 float temp[4][4];
2429
2430                 /* Nice and simple... we just need to multiply the matrices, as the get_target_matrix
2431                  * function has already taken care of everything else.
2432                  */
2433                 copy_m4_m4(temp, cob->matrix);
2434                 mul_m4_m4m4(cob->matrix, temp, ct->matrix);
2435         }
2436 }
2437
2438 static bConstraintTypeInfo CTI_ACTION = {
2439         CONSTRAINT_TYPE_ACTION, /* type */
2440         sizeof(bActionConstraint), /* size */
2441         "Action", /* name */
2442         "bActionConstraint", /* struct name */
2443         NULL, /* free data */
2444         actcon_id_looper, /* id looper */
2445         NULL, /* copy data */
2446         actcon_new_data, /* new data */
2447         actcon_get_tars, /* get constraint targets */
2448         actcon_flush_tars, /* flush constraint targets */
2449         actcon_get_tarmat, /* get target matrix */
2450         actcon_evaluate /* evaluate */
2451 };
2452
2453 /* --------- Locked Track ---------- */
2454
2455 static void locktrack_new_data(void *cdata)
2456 {
2457         bLockTrackConstraint *data = (bLockTrackConstraint *)cdata;
2458
2459         data->trackflag = TRACK_Y;
2460         data->lockflag = LOCK_Z;
2461 }
2462
2463 static void locktrack_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2464 {
2465         bLockTrackConstraint *data = con->data;
2466
2467         /* target only */
2468         func(con, (ID **)&data->tar, false, userdata);
2469 }
2470
2471 static int locktrack_get_tars(bConstraint *con, ListBase *list)
2472 {
2473         if (con && list) {
2474                 bLockTrackConstraint *data = con->data;
2475                 bConstraintTarget *ct;
2476
2477                 /* the following macro is used for all standard single-target constraints */
2478                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2479
2480                 return 1;
2481         }
2482
2483         return 0;
2484 }
2485
2486 static void locktrack_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
2487 {
2488         if (con && list) {
2489                 bLockTrackConstraint *data = con->data;
2490                 bConstraintTarget *ct = list->first;
2491
2492                 /* the following macro is used for all standard single-target constraints */
2493                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
2494         }
2495 }
2496
2497 static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
2498 {
2499         bLockTrackConstraint *data = con->data;
2500         bConstraintTarget *ct = targets->first;
2501
2502         if (VALID_CONS_TARGET(ct)) {
2503                 float vec[3], vec2[3];
2504                 float totmat[3][3];
2505                 float tmpmat[3][3];
2506                 float invmat[3][3];
2507                 float mdet;
2508
2509                 /* Vector object -> target */
2510                 sub_v3_v3v3(vec, ct->matrix[3], cob->matrix[3]);
2511                 switch (data->lockflag) {
2512                         case LOCK_X: /* LOCK X */
2513                         {
2514                                 switch (data->trackflag) {
2515                                         case TRACK_Y: /* LOCK X TRACK Y */
2516                                         {
2517                                                 /* Projection of Vector on the plane */
2518                                                 project_v3_v3v3(vec2, vec, cob->matrix[0]);
2519                                                 sub_v3_v3v3(totmat[1], vec, vec2);
2520                                                 normalize_v3(totmat[1]);
2521
2522                                                 /* the x axis is fixed */
2523                                                 normalize_v3_v3(totmat[0], cob->matrix[0]);
2524
2525                                                 /* the z axis gets mapped onto a third orthogonal vector */
2526                                                 cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2527                                                 break;
2528                                         }
2529                                         case TRACK_Z: /* LOCK X TRACK Z */
2530                                         {
2531                                                 /* Projection of Vector on the plane */
2532                                                 project_v3_v3v3(vec2, vec, cob->matrix[0]);
2533                                                 sub_v3_v3v3(totmat[2], vec, vec2);
2534                                                 normalize_v3(totmat[2]);
2535
2536                                                 /* the x axis is fixed */
2537                                                 normalize_v3_v3(totmat[0], cob->matrix[0]);
2538
2539                                                 /* the z axis gets mapped onto a third orthogonal vector */
2540                                                 cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2541                                                 break;
2542                                         }
2543                                         case TRACK_nY: /* LOCK X TRACK -Y */
2544                                         {
2545                                                 /* Projection of Vector on the plane */
2546                                                 project_v3_v3v3(vec2, vec, cob->matrix[0]);
2547                                                 sub_v3_v3v3(totmat[1], vec, vec2);
2548                                                 normalize_v3(totmat[1]);
2549                                                 negate_v3(totmat[1]);
2550
2551                                                 /* the x axis is fixed */
2552                                                 normalize_v3_v3(totmat[0], cob->matrix[0]);
2553
2554                                                 /* the z axis gets mapped onto a third orthogonal vector */
2555                                                 cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2556                                                 break;
2557                                         }
2558                                         case TRACK_nZ: /* LOCK X TRACK -Z */
2559                                         {
2560                                                 /* Projection of Vector on the plane */
2561                                                 project_v3_v3v3(vec2, vec, cob->matrix[0]);
2562                                                 sub_v3_v3v3(totmat[2], vec, vec2);
2563                                                 normalize_v3(totmat[2]);
2564                                                 negate_v3(totmat[2]);
2565
2566                                                 /* the x axis is fixed */
2567                                                 normalize_v3_v3(totmat[0], cob->matrix[0]);
2568
2569                                                 /* the z axis gets mapped onto a third orthogonal vector */
2570                                                 cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2571                                                 break;
2572                                         }
2573                                         default:
2574                                         {
2575                                                 unit_m3(totmat);
2576                                                 break;
2577                                         }
2578                                 }
2579                                 break;
2580                         }
2581                         case LOCK_Y: /* LOCK Y */
2582                         {
2583                                 switch (data->trackflag) {
2584                                         case TRACK_X: /* LOCK Y TRACK X */
2585                                         {
2586                                                 /* Projection of Vector on the plane */
2587                                                 project_v3_v3v3(vec2, vec, cob->matrix[1]);
2588                                                 sub_v3_v3v3(totmat[0], vec, vec2);
2589                                                 normalize_v3(totmat[0]);
2590
2591                                                 /* the y axis is fixed */
2592                                                 normalize_v3_v3(totmat[1], cob->matrix[1]);
2593
2594                                                 /* the z axis gets mapped onto a third orthogonal vector */
2595                                                 cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2596                                                 break;
2597                                         }
2598                                         case TRACK_Z: /* LOCK Y TRACK Z */
2599                                         {
2600                                                 /* Projection of Vector on the plane */
2601                                                 project_v3_v3v3(vec2, vec, cob->matrix[1]);
2602                                                 sub_v3_v3v3(totmat[2], vec, vec2);
2603                                                 normalize_v3(totmat[2]);
2604
2605                                                 /* the y axis is fixed */
2606                                                 normalize_v3_v3(totmat[1], cob->matrix[1]);
2607
2608                                                 /* the z axis gets mapped onto a third orthogonal vector */
2609                                                 cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2610                                                 break;
2611                                         }
2612                                         case TRACK_nX: /* LOCK Y TRACK -X */
2613                                         {
2614                                                 /* Projection of Vector on the plane */
2615                                                 project_v3_v3v3(vec2, vec, cob->matrix[1]);
2616                                                 sub_v3_v3v3(totmat[0], vec, vec2);
2617                                                 normalize_v3(totmat[0]);
2618                                                 negate_v3(totmat[0]);
2619
2620                                                 /* the y axis is fixed */
2621                                                 normalize_v3_v3(totmat[1], cob->matrix[1]);
2622
2623                                                 /* the z axis gets mapped onto a third orthogonal vector */
2624                                                 cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2625                                                 break;
2626                                         }
2627                                         case TRACK_nZ: /* LOCK Y TRACK -Z */
2628                                         {
2629                                                 /* Projection of Vector on the plane */
2630                                                 project_v3_v3v3(vec2, vec, cob->matrix[1]);
2631                                                 sub_v3_v3v3(totmat[2], vec, vec2);
2632                                                 normalize_v3(totmat[2]);
2633                                                 negate_v3(totmat[2]);
2634
2635                                                 /* the y axis is fixed */
2636                                                 normalize_v3_v3(totmat[1], cob->matrix[1]);
2637
2638                                                 /* the z axis gets mapped onto a third orthogonal vector */
2639                                                 cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2640                                                 break;
2641                                         }
2642                                         default:
2643                                         {
2644                                                 unit_m3(totmat);
2645                                                 break;
2646                                         }
2647                                 }
2648                                 break;
2649                         }
2650                         case LOCK_Z: /* LOCK Z */
2651                         {
2652                                 switch (data->trackflag) {
2653                                         case TRACK_X: /* LOCK Z TRACK X */
2654                                         {
2655                                                 /* Projection of Vector on the plane */
2656                                                 project_v3_v3v3(vec2, vec, cob->matrix[2]);
2657                                                 sub_v3_v3v3(totmat[0], vec, vec2);
2658                                                 normalize_v3(totmat[0]);
2659
2660                                                 /* the z axis is fixed */
2661                                                 normalize_v3_v3(totmat[2], cob->matrix[2]);
2662
2663                                                 /* the x axis gets mapped onto a third orthogonal vector */
2664                                                 cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2665                                                 break;
2666                                         }
2667                                         case TRACK_Y: /* LOCK Z TRACK Y */
2668                                         {
2669                                                 /* Projection of Vector on the plane */
2670                                                 project_v3_v3v3(vec2, vec, cob->matrix[2]);
2671                                                 sub_v3_v3v3(totmat[1], vec, vec2);
2672                                                 normalize_v3(totmat[1]);
2673
2674                                                 /* the z axis is fixed */
2675                                                 normalize_v3_v3(totmat[2], cob->matrix[2]);
2676
2677                                                 /* the x axis gets mapped onto a third orthogonal vector */
2678                                                 cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2679                                                 break;
2680                                         }
2681                                         case TRACK_nX: /* LOCK Z TRACK -X */
2682                                         {
2683                                                 /* Projection of Vector on the plane */
2684                                                 project_v3_v3v3(vec2, vec, cob->matrix[2]);
2685                                                 sub_v3_v3v3(totmat[0], vec, vec2);
2686                                                 normalize_v3(totmat[0]);
2687                                                 negate_v3(totmat[0]);
2688
2689                                                 /* the z axis is fixed */
2690                                                 normalize_v3_v3(totmat[2], cob->matrix[2]);
2691
2692                                                 /* the x axis gets mapped onto a third orthogonal vector */
2693                                                 cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2694                                                 break;
2695                                         }
2696                                         case TRACK_nY: /* LOCK Z TRACK -Y */
2697                                         {
2698                                                 /* Projection of Vector on the plane */
2699                                                 project_v3_v3v3(vec2, vec, cob->matrix[2]);
2700                                                 sub_v3_v3v3(totmat[1], vec, vec2);
2701                                                 normalize_v3(totmat[1]);
2702                                                 negate_v3(totmat[1]);
2703
2704                                                 /* the z axis is fixed */
2705                                                 normalize_v3_v3(totmat[2], cob->matrix[2]);
2706
2707                                                 /* the x axis gets mapped onto a third orthogonal vector */
2708                                                 cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2709                                                 break;
2710                                         }
2711                                         default:
2712                                         {
2713                                                 unit_m3(totmat);
2714                                                 break;
2715                                         }
2716                                 }
2717                                 break;
2718                         }
2719                         default:
2720                         {
2721                                 unit_m3(totmat);
2722                                 break;
2723                         }
2724                 }
2725                 /* Block to keep matrix heading */
2726                 copy_m3_m4(tmpmat, cob->matrix);
2727                 normalize_m3(tmpmat);
2728                 invert_m3_m3(invmat, tmpmat);
2729                 mul_m3_m3m3(tmpmat, totmat, invmat);
2730                 totmat[0][0] = tmpmat[0][0]; totmat[0][1] = tmpmat[0][1]; totmat[0][2] = tmpmat[0][2];
2731                 totmat[1][0] = tmpmat[1][0]; totmat[1][1] = tmpmat[1][1]; totmat[1][2] = tmpmat[1][2];
2732                 totmat[2][0] = tmpmat[2][0]; totmat[2][1] = tmpmat[2][1]; totmat[2][2] = tmpmat[2][2];
2733
2734                 mdet = determinant_m3(totmat[0][0], totmat[0][1], totmat[0][2],
2735                                       totmat[1][0], totmat[1][1], totmat[1][2],
2736                                       totmat[2][0], totmat[2][1], totmat[2][2]);
2737                 if (mdet == 0) {
2738                         unit_m3(totmat);
2739                 }
2740
2741                 /* apply out transformation to the object */
2742                 mul_m4_m3m4(cob->matrix, totmat, cob->matrix);
2743         }
2744 }
2745
2746 static bConstraintTypeInfo CTI_LOCKTRACK = {
2747         CONSTRAINT_TYPE_LOCKTRACK, /* type */
2748         sizeof(bLockTrackConstraint), /* size */
2749         "Locked Track", /* name */
2750         "bLockTrackConstraint", /* struct name */
2751         NULL, /* free data */
2752         locktrack_id_looper, /* id looper */
2753         NULL, /* copy data */
2754         locktrack_new_data, /* new data */
2755         locktrack_get_tars, /* get constraint targets */
2756         locktrack_flush_tars, /* flush constraint targets */
2757         default_get_tarmat, /* get target matrix */
2758         locktrack_evaluate /* evaluate */
2759 };
2760
2761 /* ---------- Limit Distance Constraint ----------- */
2762
2763 static void distlimit_new_data(void *cdata)
2764 {
2765         bDistLimitConstraint *data = (bDistLimitConstraint *)cdata;
2766
2767         data->dist = 0.0f;
2768 }
2769
2770 static void distlimit_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2771 {
2772         bDistLimitConstraint *data = con->data;
2773
2774         /* target only */
2775         func(con, (ID **)&data->tar, false, userdata);
2776 }
2777
2778 static int distlimit_get_tars(bConstraint *con, ListBase *list)
2779 {
2780         if (con && list) {
2781                 bDistLimitConstraint *data = con->data;
2782                 bConstraintTarget *ct;
2783
2784                 /* standard target-getting macro for single-target constraints */
2785                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2786
2787                 return 1;
2788         }
2789
2790         return 0;
2791 }
2792
2793 static void distlimit_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
2794 {
2795         if (con && list) {
2796                 bDistLimitConstraint *data = con->data;
2797                 bConstraintTarget *ct = list->first;
2798
2799                 /* the following macro is used for all standard single-target constraints */
2800                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
2801         }
2802 }
2803
2804 static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
2805 {
2806         bDistLimitConstraint *data = con->data;
2807         bConstraintTarget *ct = targets->first;
2808
2809         /* only evaluate if there is a target */
2810         if (VALID_CONS_TARGET(ct)) {
2811                 float dvec[3], dist, sfac = 1.0f;
2812                 short clamp_surf = 0;
2813
2814                 /* calculate our current distance from the target */
2815                 dist = len_v3v3(cob->matrix[3], ct->matrix[3]);
2816
2817                 /* set distance (flag is only set when user demands it) */
2818                 if (data->dist == 0) {
2819                         data->dist = dist;
2820
2821                         /* Write the computed distance back to the master copy if in COW evaluation. */
2822                         bConstraint *orig_con = constraint_find_original_for_update(cob, con);
2823
2824                         if (orig_con != NULL) {
2825                                 bDistLimitConstraint *orig_data = orig_con->data;
2826
2827                                 orig_data->dist = data->dist;
2828                         }
2829                 }
2830
2831                 /* check if we're which way to clamp from, and calculate interpolation factor (if needed) */
2832                 if (data->mode == LIMITDIST_OUTSIDE) {
2833                         /* if inside, then move to surface */
2834                         if (dist <= data->dist) {
2835                                 clamp_surf = 1;
2836                                 if (dist != 0.0f) sfac = data->dist / dist;
2837                         }
2838                         /* if soft-distance is enabled, start fading once owner is dist+softdist from the target */
2839                         else if (data->flag & LIMITDIST_USESOFT) {
2840                                 if (dist <= (data->dist + data->soft)) {
2841                                         /* pass */
2842                                 }
2843                         }
2844                 }
2845                 else if (data->mode == LIMITDIST_INSIDE) {
2846                         /* if outside, then move to surface */
2847                         if (dist >= data->dist) {
2848                                 clamp_surf = 1;
2849                                 if (dist != 0.0f) sfac = data->dist / dist;
2850                         }
2851                         /* if soft-distance is enabled, start fading once owner is dist-soft from the target */
2852                         else if (data->flag & LIMITDIST_USESOFT) {
2853                                 /* FIXME: there's a problem with "jumping" when this kicks in */
2854                                 if (dist >= (data->dist - data->soft)) {
2855                                         sfac = (float)(data->soft * (1.0f - expf(-(dist - data->dist) / data->soft)) + data->dist);
2856                                         if (dist != 0.0f) sfac /= dist;
2857
2858                                         clamp_surf = 1;
2859                                 }
2860                         }
2861                 }
2862                 else {
2863                         if (IS_EQF(dist, data->dist) == 0) {
2864                                 clamp_surf = 1;
2865                                 if (dist != 0.0f) sfac = data->dist / dist;
2866                         }
2867                 }
2868
2869                 /* clamp to 'surface' (i.e. move owner so that dist == data->dist) */
2870                 if (clamp_surf) {
2871                         /* simply interpolate along line formed by target -> owner */
2872                         interp_v3_v3v3(dvec, ct->matrix[3], cob->matrix[3], sfac);
2873
2874                         /* copy new vector onto owner */
2875                         copy_v3_v3(cob->matrix[3], dvec);
2876                 }
2877         }
2878 }
2879
2880 static bConstraintTypeInfo CTI_DISTLIMIT = {
2881         CONSTRAINT_TYPE_DISTLIMIT, /* type */
2882         sizeof(bDistLimitConstraint), /* size */
2883         "Limit Distance", /* name */
2884         "bDistLimitConstraint", /* struct name */
2885         NULL, /* free data */
2886         distlimit_id_looper, /* id looper */
2887         NULL, /* copy data */
2888         distlimit_new_data, /* new data */
2889         distlimit_get_tars, /* get constraint targets */
2890         distlimit_flush_tars, /* flush constraint targets */
2891         default_get_tarmat, /* get a target matrix */
2892         distlimit_evaluate /* evaluate */
2893 };
2894
2895 /* ---------- Stretch To ------------ */
2896
2897 static void stretchto_new_data(void *cdata)
2898 {
2899         bStretchToConstraint *data = (bStretchToConstraint *)cdata;
2900
2901         data->volmode = 0;
2902         data->plane = 0;
2903         data->orglength = 0.0;
2904         data->bulge = 1.0;
2905         data->bulge_max = 1.0f;
2906         data->bulge_min = 1.0f;
2907 }
2908
2909 static void stretchto_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2910 {
2911         bStretchToConstraint *data = con->data;
2912
2913         /* target only */
2914         func(con, (ID **)&data->tar, false, userdata);
2915 }
2916
2917 static int stretchto_get_tars(bConstraint *con, ListBase *list)
2918 {
2919         if (con && list) {
2920                 bStretchToConstraint *data = con->data;
2921                 bConstraintTarget *ct;
2922
2923                 /* standard target-getting macro for single-target constraints */
2924                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2925
2926                 return 1;
2927         }
2928
2929         return 0;
2930 }
2931
2932 static void stretchto_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
2933 {
2934         if (con && list) {
2935                 bStretchToConstraint *data = con->data;
2936                 bConstraintTarget *ct = list->first;
2937
2938                 /* the following macro is used for all standard single-target constraints */
2939                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
2940         }
2941 }
2942
2943 static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
2944 {
2945         bStretchToConstraint *data = con->data;
2946         bConstraintTarget *ct = targets->first;
2947
2948         /* only evaluate if there is a target */
2949         if (VALID_CONS_TARGET(ct)) {
2950                 float size[3], scale[3], vec[3], xx[3], zz[3], orth[3];
2951                 float totmat[3][3];
2952                 float dist, bulge;
2953
2954                 /* store scaling before destroying obmat */
2955                 mat4_to_size(size, cob->matrix);
2956
2957                 /* store X orientation before destroying obmat */
2958                 normalize_v3_v3(xx, cob->matrix[0]);
2959
2960                 /* store Z orientation before destroying obmat */
2961                 normalize_v3_v3(zz, cob->matrix[2]);
2962
2963                 /* XXX That makes the constraint buggy with asymmetrically scaled objects, see #29940. */
2964 #if 0
2965                 sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);
2966                 vec[0] /= size[0];
2967                 vec[1] /= size[1];
2968                 vec[2] /= size[2];
2969
2970                 dist = normalize_v3(vec);
2971 #endif
2972
2973                 dist = len_v3v3(cob->matrix[3], ct->matrix[3]);
2974                 /* Only Y constrained object axis scale should be used, to keep same length when scaling it. */
2975                 dist /= size[1];
2976
2977                 /* data->orglength==0 occurs on first run, and after 'R' button is clicked */
2978                 if (data->orglength == 0) {
2979                         data->orglength = dist;
2980
2981                         /* Write the computed length back to the master copy if in COW evaluation. */
2982                         bConstraint *orig_con = constraint_find_original_for_update(cob, con);
2983
2984                         if (orig_con != NULL) {
2985                                 bStretchToConstraint *orig_data = orig_con->data;
2986
2987                                 orig_data->orglength = data->orglength;
2988                         }
2989                 }
2990
2991                 scale[1] = dist / data->orglength;
2992
2993                 bulge = powf(data->orglength / dist, data->bulge);
2994
2995                 if (bulge > 1.0f) {
2996                         if (data->flag & STRETCHTOCON_USE_BULGE_MAX) {
2997                                 float bulge_max = max_ff(data->bulge_max, 1.0f);
2998                                 float hard = min_ff(bulge, bulge_max);
2999
3000                                 float range = bulge_max - 1.0f;
3001                                 float scale_fac = (range > 0.0f) ? 1.0f / range : 0.0f;
3002                                 float soft = 1.0f + range * atanf((bulge - 1.0f) * scale_fac) / (float)M_PI_2;
3003
3004                                 bulge = interpf(soft, hard, data->bulge_smooth);
3005                         }
3006                 }
3007                 if (bulge < 1.0f) {
3008                         if (data->flag & STRETCHTOCON_USE_BULGE_MIN) {
3009                                 float bulge_min = CLAMPIS(data->bulge_min, 0.0f, 1.0f);
3010                                 float hard = max_ff(bulge, bulge_min);
3011
3012                                 float range = 1.0f - bulge_min;
3013                                 float scale_fac = (range > 0.0f) ? 1.0f / range : 0.0f;
3014                                 float soft = 1.0f - range * atanf((1.0f - bulge) * scale_fac) / (float)M_PI_2;
3015
3016                                 bulge = interpf(soft, hard, data->bulge_smooth);
3017                         }
3018                 }
3019
3020                 switch (data->volmode) {
3021                         /* volume preserving scaling */
3022                         case VOLUME_XZ:
3023                                 scale[0] = sqrtf(bulge);
3024                                 scale[2] = scale[0];
3025                                 break;
3026                         case VOLUME_X:
3027                                 scale[0] = bulge;
3028                                 scale[2] = 1.0;
3029                                 break;
3030                         case VOLUME_Z:
3031                                 scale[0] = 1.0;
3032                                 scale[2] = bulge;
3033                                 break;
3034                         /* don't care for volume */
3035                         case NO_VOLUME:
3036                                 scale[0] = 1.0;
3037                                 scale[2] = 1.0;
3038                                 break;