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