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