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