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