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