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