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