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