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