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