Fix for T41536: 2.71 getActionFrame no longer returns frames accurately
[blender.git] / source / gameengine / Ketsji / BL_Action.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Mitchell Stokes.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file BL_Action.cpp
24  *  \ingroup ketsji
25  */
26
27 #include <cstdlib>
28 #include <stdio.h>
29
30 #include "BL_Action.h"
31 #include "BL_ArmatureObject.h"
32 #include "BL_DeformableGameObject.h"
33 #include "BL_ShapeDeformer.h"
34 #include "KX_IpoConvert.h"
35 #include "KX_GameObject.h"
36
37 #include "SG_Controller.h"
38
39 // These three are for getting the action from the logic manager
40 #include "KX_Scene.h"
41 #include "SCA_LogicManager.h"
42
43 extern "C" {
44 #include "BKE_animsys.h"
45 #include "BKE_action.h"
46 #include "RNA_access.h"
47 #include "RNA_define.h"
48
49 // Needed for material IPOs
50 #include "BKE_material.h"
51 #include "DNA_material_types.h"
52 #include "DNA_scene_types.h"
53 }
54
55 #include "MEM_guardedalloc.h"
56 #include "BKE_library.h"
57 #include "BKE_global.h"
58
59 BL_Action::BL_Action(class KX_GameObject* gameobj)
60 :
61         m_action(NULL),
62         m_tmpaction(NULL),
63         m_blendpose(NULL),
64         m_blendinpose(NULL),
65         m_obj(gameobj),
66         m_startframe(0.f),
67         m_endframe(0.f),
68         m_endtime(0.f),
69         m_localtime(0.f),
70         m_blendin(0.f),
71         m_blendframe(0.f),
72         m_blendstart(0.f),
73         m_speed(0.f),
74         m_priority(0),
75         m_playmode(ACT_MODE_PLAY),
76         m_blendmode(ACT_BLEND_BLEND),
77         m_ipo_flags(0),
78         m_done(true),
79         m_calc_localtime(true)
80 {
81 }
82
83 BL_Action::~BL_Action()
84 {
85         if (m_blendpose)
86                 BKE_pose_free(m_blendpose);
87         if (m_blendinpose)
88                 BKE_pose_free(m_blendinpose);
89         ClearControllerList();
90
91         if (m_tmpaction) {
92                 BKE_libblock_free(G.main, m_tmpaction);
93                 m_tmpaction = NULL;
94         }
95 }
96
97 void BL_Action::ClearControllerList()
98 {
99         // Clear out the controller list
100         std::vector<SG_Controller*>::iterator it;
101         for (it = m_sg_contr_list.begin(); it != m_sg_contr_list.end(); it++)
102         {
103                 m_obj->GetSGNode()->RemoveSGController((*it));
104                 delete *it;
105         }
106
107         m_sg_contr_list.clear();
108 }
109
110 bool BL_Action::Play(const char* name,
111                                         float start,
112                                         float end,
113                                         short priority,
114                                         float blendin,
115                                         short play_mode,
116                                         float layer_weight,
117                                         short ipo_flags,
118                                         float playback_speed,
119                                         short blend_mode)
120 {
121
122         // Only start playing a new action if we're done, or if
123         // the new action has a higher priority
124         if (!IsDone() && priority > m_priority)
125                 return false;
126         m_priority = priority;
127         bAction* prev_action = m_action;
128
129         KX_Scene* kxscene = m_obj->GetScene();
130
131         // First try to load the action
132         m_action = (bAction*)kxscene->GetLogicManager()->GetActionByName(name);
133         if (!m_action)
134         {
135                 printf("Failed to load action: %s\n", name);
136                 m_done = true;
137                 return false;
138         }
139
140         // If we have the same settings, don't play again
141         // This is to resolve potential issues with pulses on sensors such as the ones
142         // reported in bug #29412. The fix is here so it works for both logic bricks and Python.
143         // However, this may eventually lead to issues where a user wants to override an already
144         // playing action with the same action and settings. If this becomes an issue,
145         // then this fix may have to be re-evaluated.
146         if (!IsDone() && m_action == prev_action && m_startframe == start && m_endframe == end
147                         && m_priority == priority && m_speed == playback_speed)
148                 return false;
149
150         // Keep a copy of the action for threading purposes
151         if (m_tmpaction) {
152                 BKE_libblock_free(G.main, m_tmpaction);
153                 m_tmpaction = NULL;
154         }
155         m_tmpaction = BKE_action_copy(m_action);
156
157         // First get rid of any old controllers
158         ClearControllerList();
159
160         // Create an SG_Controller
161         SG_Controller *sg_contr = BL_CreateIPO(m_action, m_obj, kxscene->GetSceneConverter());
162         m_sg_contr_list.push_back(sg_contr);
163         m_obj->GetSGNode()->AddSGController(sg_contr);
164         sg_contr->SetObject(m_obj->GetSGNode());
165
166         // World
167         sg_contr = BL_CreateWorldIPO(m_action, kxscene->GetBlenderScene()->world, kxscene->GetSceneConverter());
168         if (sg_contr) {
169                 m_sg_contr_list.push_back(sg_contr);
170                 m_obj->GetSGNode()->AddSGController(sg_contr);
171                 sg_contr->SetObject(m_obj->GetSGNode());
172         }
173
174         // Try obcolor
175         sg_contr = BL_CreateObColorIPO(m_action, m_obj, kxscene->GetSceneConverter());
176         if (sg_contr) {
177                 m_sg_contr_list.push_back(sg_contr);
178                 m_obj->GetSGNode()->AddSGController(sg_contr);
179                 sg_contr->SetObject(m_obj->GetSGNode());
180         }
181
182         // Now try materials
183         if (m_obj->GetBlenderObject()->totcol==1) {
184                 Material *mat = give_current_material(m_obj->GetBlenderObject(), 1);
185                 if (mat) {
186                         sg_contr = BL_CreateMaterialIpo(m_action, mat, 0, m_obj, kxscene->GetSceneConverter());
187                         if (sg_contr) {
188                                 m_sg_contr_list.push_back(sg_contr);
189                                 m_obj->GetSGNode()->AddSGController(sg_contr);
190                                 sg_contr->SetObject(m_obj->GetSGNode());
191                         }
192                 }
193         } else {
194                 Material *mat;
195                 STR_HashedString matname;
196
197                 for (int matidx = 1; matidx <= m_obj->GetBlenderObject()->totcol; ++matidx) {
198                         mat = give_current_material(m_obj->GetBlenderObject(), matidx);
199                         if (mat) {
200                                 matname = mat->id.name;
201                                 sg_contr = BL_CreateMaterialIpo(m_action, mat, matname.hash(), m_obj, kxscene->GetSceneConverter());
202                                 if (sg_contr) {
203                                         m_sg_contr_list.push_back(sg_contr);
204                                         m_obj->GetSGNode()->AddSGController(sg_contr);
205                                         sg_contr->SetObject(m_obj->GetSGNode());
206                                 }
207                         }
208                 }
209         }
210
211         // Extra controllers
212         if (m_obj->GetGameObjectType() == SCA_IObject::OBJ_LIGHT)
213         {
214                 sg_contr = BL_CreateLampIPO(m_action, m_obj, kxscene->GetSceneConverter());
215                 m_sg_contr_list.push_back(sg_contr);
216                 m_obj->GetSGNode()->AddSGController(sg_contr);
217                 sg_contr->SetObject(m_obj->GetSGNode());
218         }
219         else if (m_obj->GetGameObjectType() == SCA_IObject::OBJ_CAMERA)
220         {
221                 sg_contr = BL_CreateCameraIPO(m_action, m_obj, kxscene->GetSceneConverter());
222                 m_sg_contr_list.push_back(sg_contr);
223                 m_obj->GetSGNode()->AddSGController(sg_contr);
224                 sg_contr->SetObject(m_obj->GetSGNode());
225         }
226         
227         m_ipo_flags = ipo_flags;
228         InitIPO();
229
230         // Setup blendin shapes/poses
231         if (m_obj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE)
232         {
233                 BL_ArmatureObject *obj = (BL_ArmatureObject*)m_obj;
234                 obj->GetPose(&m_blendinpose);
235         }
236         else
237         {
238                 BL_DeformableGameObject *obj = (BL_DeformableGameObject*)m_obj;
239                 BL_ShapeDeformer *shape_deformer = dynamic_cast<BL_ShapeDeformer*>(obj->GetDeformer());
240                 
241                 if (shape_deformer && shape_deformer->GetKey())
242                 {
243                         obj->GetShape(m_blendinshape);
244
245                         // Now that we have the previous blend shape saved, we can clear out the key to avoid any
246                         // further interference.
247                         KeyBlock *kb;
248                         for (kb=(KeyBlock *)shape_deformer->GetKey()->block.first; kb; kb=(KeyBlock *)kb->next)
249                                 kb->curval = 0.f;
250                 }
251         }
252
253         // Now that we have an action, we have something we can play
254         m_starttime = -1.f; // We get the start time on our first update
255         m_startframe = m_localtime = start;
256         m_endframe = end;
257         m_blendin = blendin;
258         m_playmode = play_mode;
259         m_blendmode = blend_mode;
260         m_endtime = 0.f;
261         m_blendframe = 0.f;
262         m_blendstart = 0.f;
263         m_speed = playback_speed;
264         m_layer_weight = layer_weight;
265         
266         m_done = false;
267
268         return true;
269 }
270
271 bool BL_Action::IsDone()
272 {
273         return m_done;
274 }
275
276 void BL_Action::InitIPO()
277 {
278         // Initialize the IPOs
279         std::vector<SG_Controller*>::iterator it;
280         for (it = m_sg_contr_list.begin(); it != m_sg_contr_list.end(); it++)
281         {
282                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true);
283                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, m_ipo_flags & ACT_IPOFLAG_FORCE);
284                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, m_ipo_flags & ACT_IPOFLAG_ADD);
285                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, m_ipo_flags & ACT_IPOFLAG_LOCAL);
286         }
287 }
288
289 bAction *BL_Action::GetAction()
290 {
291         return (IsDone()) ? NULL : m_action;
292 }
293
294 float BL_Action::GetFrame()
295 {
296         return m_localtime;
297 }
298
299 const char *BL_Action::GetName()
300 {
301         if (m_action != NULL) {
302                 return m_action->id.name + 2;
303         }
304         else {
305                 return "";
306         }
307
308                     
309 }
310
311 void BL_Action::SetFrame(float frame)
312 {
313         // Clamp the frame to the start and end frame
314         if (frame < min(m_startframe, m_endframe))
315                 frame = min(m_startframe, m_endframe);
316         else if (frame > max(m_startframe, m_endframe))
317                 frame = max(m_startframe, m_endframe);
318         
319         m_localtime = frame;
320         m_calc_localtime = false;
321 }
322
323 void BL_Action::SetPlayMode(short play_mode)
324 {
325         m_playmode = play_mode;
326 }
327
328 void BL_Action::SetTimes(float start, float end)
329 {
330         m_startframe = start;
331         m_endframe = end;
332 }
333
334 void BL_Action::SetLocalTime(float curtime)
335 {
336         float dt = (curtime-m_starttime)*KX_KetsjiEngine::GetAnimFrameRate()*m_speed;
337
338         if (m_endframe < m_startframe)
339                 dt = -dt;
340
341         m_localtime = m_startframe + dt;
342 }
343
344 void BL_Action::ResetStartTime(float curtime)
345 {
346         float dt = (m_localtime > m_startframe) ? m_localtime - m_startframe : m_startframe - m_localtime;
347
348         m_starttime = curtime - dt / (KX_KetsjiEngine::GetAnimFrameRate()*m_speed);
349         SetLocalTime(curtime);
350 }
351
352 void BL_Action::IncrementBlending(float curtime)
353 {
354         // Setup m_blendstart if we need to
355         if (m_blendstart == 0.f)
356                 m_blendstart = curtime;
357         
358         // Bump the blend frame
359         m_blendframe = (curtime - m_blendstart)*KX_KetsjiEngine::GetAnimFrameRate();
360
361         // Clamp
362         if (m_blendframe>m_blendin)
363                 m_blendframe = m_blendin;
364 }
365
366
367 void BL_Action::BlendShape(Key* key, float srcweight, std::vector<float>& blendshape)
368 {
369         vector<float>::const_iterator it;
370         float dstweight;
371         KeyBlock *kb;
372         
373         dstweight = 1.0F - srcweight;
374         //printf("Dst: %f\tSrc: %f\n", srcweight, dstweight);
375         for (it=blendshape.begin(), kb = (KeyBlock *)key->block.first; 
376              kb && it != blendshape.end();
377              kb = (KeyBlock *)kb->next, it++)
378         {
379                 //printf("OirgKeys: %f\t%f\n", kb->curval, (*it));
380                 kb->curval = kb->curval * dstweight + (*it) * srcweight;
381                 //printf("NewKey: %f\n", kb->curval);
382         }
383         //printf("\n");
384 }
385
386 void BL_Action::Update(float curtime)
387 {
388         // Don't bother if we're done with the animation
389         if (m_done)
390                 return;
391
392         curtime -= KX_KetsjiEngine::GetSuspendedDelta();
393
394         // Grab the start time here so we don't end up with a negative m_localtime when
395         // suspending and resuming scenes.
396         if (m_starttime < 0)
397                 m_starttime = curtime;
398
399         if (m_calc_localtime)
400                 SetLocalTime(curtime);
401         else
402         {
403                 ResetStartTime(curtime);
404                 m_calc_localtime = true;
405         }
406
407         // Handle wrap around
408         if (m_localtime < min(m_startframe, m_endframe) || m_localtime > max(m_startframe, m_endframe)) {
409                 switch (m_playmode) {
410                         case ACT_MODE_PLAY:
411                                 // Clamp
412                                 m_localtime = m_endframe;
413                                 m_done = true;
414                                 break;
415                         case ACT_MODE_LOOP:
416                                 // Put the time back to the beginning
417                                 m_localtime = m_startframe;
418                                 m_starttime = curtime;
419                                 break;
420                         case ACT_MODE_PING_PONG:
421                                 // Swap the start and end frames
422                                 float temp = m_startframe;
423                                 m_startframe = m_endframe;
424                                 m_endframe = temp;
425
426                                 m_starttime = curtime;
427
428                                 break;
429                 }
430         }
431
432         if (m_obj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE)
433         {
434                 BL_ArmatureObject *obj = (BL_ArmatureObject*)m_obj;
435
436                 if (m_layer_weight >= 0)
437                         obj->GetPose(&m_blendpose);
438
439                 // Extract the pose from the action
440                 obj->SetPoseByAction(m_tmpaction, m_localtime);
441
442                 // Handle blending between armature actions
443                 if (m_blendin && m_blendframe<m_blendin)
444                 {
445                         IncrementBlending(curtime);
446
447                         // Calculate weight
448                         float weight = 1.f - (m_blendframe/m_blendin);
449
450                         // Blend the poses
451                         obj->BlendInPose(m_blendinpose, weight, ACT_BLEND_BLEND);
452                 }
453
454
455                 // Handle layer blending
456                 if (m_layer_weight >= 0)
457                         obj->BlendInPose(m_blendpose, m_layer_weight, m_blendmode);
458
459                 obj->UpdateTimestep(curtime);
460         }
461         else
462         {
463                 BL_DeformableGameObject *obj = (BL_DeformableGameObject*)m_obj;
464                 BL_ShapeDeformer *shape_deformer = dynamic_cast<BL_ShapeDeformer*>(obj->GetDeformer());
465
466                 // Handle shape actions if we have any
467                 if (shape_deformer && shape_deformer->GetKey())
468                 {
469                         Key *key = shape_deformer->GetKey();
470
471                         PointerRNA ptrrna;
472                         RNA_id_pointer_create(&key->id, &ptrrna);
473
474                         animsys_evaluate_action(&ptrrna, m_tmpaction, NULL, m_localtime);
475
476                         // Handle blending between shape actions
477                         if (m_blendin && m_blendframe < m_blendin)
478                         {
479                                 IncrementBlending(curtime);
480
481                                 float weight = 1.f - (m_blendframe/m_blendin);
482
483                                 // We go through and clear out the keyblocks so there isn't any interference
484                                 // from other shape actions
485                                 KeyBlock *kb;
486                                 for (kb=(KeyBlock *)key->block.first; kb; kb=(KeyBlock *)kb->next)
487                                         kb->curval = 0.f;
488
489                                 // Now blend the shape
490                                 BlendShape(key, weight, m_blendinshape);
491                         }
492
493                         // Handle layer blending
494                         if (m_layer_weight >= 0)
495                         {
496                                 obj->GetShape(m_blendshape);
497                                 BlendShape(key, m_layer_weight, m_blendshape);
498                         }
499
500                         obj->SetActiveAction(NULL, 0, curtime);
501                 }
502         }
503
504         // This isn't thread-safe, so we move it into it's own function for now
505         //m_obj->UpdateIPO(m_localtime, m_ipo_flags & ACT_IPOFLAG_CHILD);
506
507         if (m_done)
508                 ClearControllerList();
509 }
510
511 void BL_Action::UpdateIPOs()
512 {
513         if (!m_done)
514                 m_obj->UpdateIPO(m_localtime, m_ipo_flags & ACT_IPOFLAG_CHILD);
515 }