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