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