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