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