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