aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs
blob: 5cfba3945205befcadcb99ceffe1a79f3af1c41f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
// Proprietary code of Avination Virtual Limited
// (c) 2012 Melanie Thielker
//

using System;
using System.Timers;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Physics.Manager;
using OpenSim.Region.Framework.Scenes.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using Timer = System.Timers.Timer;
using log4net;

namespace OpenSim.Region.Framework.Scenes
{
    [Serializable]
    public class KeyframeMotion
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public enum PlayMode : int
        {
            Forward = 0,
            Reverse = 1,
            Loop = 2,
            PingPong = 3
        };

        [Flags]
        public enum DataFormat : int
        {
            Translation = 2,
            Rotation = 1
        }

        [Serializable]
        public struct Keyframe
        {
            public Vector3? Position;
            public Quaternion? Rotation;
            public Quaternion StartRotation;
            public int TimeMS;
            public int TimeTotal;
            public Vector3 AngularVelocity;
        };

        private Vector3 m_serializedPosition;
        private Vector3 m_basePosition;
        private Quaternion m_baseRotation;

        private Keyframe m_currentFrame;

        private List<Keyframe> m_frames = new List<Keyframe>();

        private Keyframe[] m_keyframes;

        [NonSerialized()]
        protected Timer m_timer = null;

        // timer lock
        [NonSerialized()]
        private object m_onTimerLock;

        // timer overrun detect
        // prevents overlap or timer events threads frozen on the lock
        [NonSerialized()]
        private bool m_inOnTimer;

        // skip timer events.
        //timer.stop doesn't assure there aren't event threads still being fired
        [NonSerialized()]
        private bool m_timerStopped;

        [NonSerialized()]
        private bool m_isCrossing;

        [NonSerialized()]
        private bool m_waitingCrossing;

        // retry position for cross fail
        [NonSerialized()]
        private Vector3 m_nextPosition;

        [NonSerialized()]
        private SceneObjectGroup m_group;

        private PlayMode m_mode = PlayMode.Forward;
        private DataFormat m_data = DataFormat.Translation | DataFormat.Rotation;

        private bool m_running = false;
        [NonSerialized()]
        private bool m_selected = false;

        private int m_iterations = 0;

        private const double timerInterval = 50.0;

        public DataFormat Data
        {
            get { return m_data; }
        }

        public bool Selected
        {
            set
            {
                if (m_group != null)
                {
                    if (!value)
                    {
                        // Once we're let go, recompute positions
                        if (m_selected)
                            UpdateSceneObject(m_group);
                    }
                    else
                    {
                        // Save selection position in case we get moved
                        if (!m_selected)
                        {
                            StopTimer();
                            m_serializedPosition = m_group.AbsolutePosition;
                        }
                    }
                }
                m_isCrossing = false;
                m_waitingCrossing = false;
                m_selected = value;
            }
        }

        private void StartTimer()
        {
            if (m_timer == null)
                return;
            m_timerStopped = false;
            m_timer.Start();
        }

        private void StopTimer()
        {
            if (m_timer == null || m_timerStopped)
                return;
            m_timerStopped = true;
            m_timer.Stop();
        }

        private void RemoveTimer()
        {
            if (m_timer == null)
                return;
            m_timerStopped = true;
            m_timer.Stop();
            m_timer.Elapsed -= OnTimer;
            m_timer = null;
        }


        public static KeyframeMotion FromData(SceneObjectGroup grp, Byte[] data)
        {
            KeyframeMotion newMotion = null;

            try
            {
                MemoryStream ms = new MemoryStream(data);
                BinaryFormatter fmt = new BinaryFormatter();

                newMotion = (KeyframeMotion)fmt.Deserialize(ms);

                newMotion.m_group = grp;

                if (grp != null && grp.IsSelected)
                    newMotion.m_selected = true;

                newMotion.m_onTimerLock = new object();
                newMotion.m_timerStopped = false;
                newMotion.m_inOnTimer = false;
                newMotion.m_isCrossing = false;
                newMotion.m_waitingCrossing = false;
            }
            catch
            {
                newMotion = null;
            }

            return newMotion;
        }

        public void UpdateSceneObject(SceneObjectGroup grp)
        {
//            lock (m_onTimerLock)
            {
                m_isCrossing = false;
                m_waitingCrossing = false;
                StopTimer();

                if (grp == null)
                    return;

                m_group = grp;
                Vector3 grppos = grp.AbsolutePosition;
                Vector3 offset = grppos - m_serializedPosition;
                // avoid doing it more than once
                // current this will happen draging a prim to other region
                m_serializedPosition = grppos;

                m_basePosition += offset;
                m_currentFrame.Position += offset;

                m_nextPosition += offset;

                for (int i = 0; i < m_frames.Count; i++)
                {
                    Keyframe k = m_frames[i];
                    k.Position += offset;
                    m_frames[i]=k;
                }

                if (m_running)
                    Start();
            }
        }

        public KeyframeMotion(SceneObjectGroup grp, PlayMode mode, DataFormat data)
        {
            m_mode = mode;
            m_data = data;

            m_group = grp;
            if (grp != null)
            {
                m_basePosition = grp.AbsolutePosition;
                m_baseRotation = grp.GroupRotation;
            }

            m_onTimerLock = new object();
            m_timerStopped = true;
            m_inOnTimer = false;
            m_isCrossing = false;
            m_waitingCrossing = false;
        }

        public void SetKeyframes(Keyframe[] frames)
        {
            m_keyframes = frames;
        }

        public KeyframeMotion Copy(SceneObjectGroup newgrp)
        {
            StopTimer();

            KeyframeMotion newmotion = new KeyframeMotion(null, m_mode, m_data);

            newmotion.m_group = newgrp;

            if (m_keyframes != null)
            {
                newmotion.m_keyframes = new Keyframe[m_keyframes.Length];
                m_keyframes.CopyTo(newmotion.m_keyframes, 0);
            }

            newmotion.m_frames = new List<Keyframe>(m_frames);

            newmotion.m_basePosition = m_basePosition;
            newmotion.m_baseRotation = m_baseRotation;

            if (m_selected)
                newmotion.m_serializedPosition = m_serializedPosition;
            else
            {
                if (m_group != null)
                    newmotion.m_serializedPosition = m_group.AbsolutePosition;
                else
                    newmotion.m_serializedPosition = m_serializedPosition;
            }

            newmotion.m_currentFrame = m_currentFrame;

            newmotion.m_iterations = m_iterations;
            newmotion.m_running = m_running;

            if (m_running && !m_waitingCrossing)
                StartTimer();

            return newmotion;
        }

        public void Delete()
        {
            m_running = false;
            RemoveTimer();
            m_isCrossing = false;
            m_waitingCrossing = false;
            m_frames.Clear();
            m_keyframes = null;
        }

        public void Start()
        {
            m_isCrossing = false;
            m_waitingCrossing = false;
            if (m_keyframes != null && m_group != null && m_keyframes.Length > 0)
            {
                if (m_timer == null)
                {
                    m_timer = new Timer();
                    m_timer.Interval = timerInterval;
                    m_timer.AutoReset = true;
                    m_timer.Elapsed += OnTimer;
                }
                else
                {
                    StopTimer();
                    m_timer.Interval = timerInterval;
                }

                m_inOnTimer = false;
                StartTimer();
                m_running = true;
            }
            else
            {
                m_running = false;
                RemoveTimer();
            }
        }

        public void Stop()
        {
            m_running = false;
            m_isCrossing = false;
            m_waitingCrossing = false;

            RemoveTimer();

            m_basePosition = m_group.AbsolutePosition;
            m_baseRotation = m_group.GroupRotation;

            m_group.RootPart.Velocity = Vector3.Zero;
            m_group.RootPart.AngularVelocity = Vector3.Zero;
            m_group.SendGroupRootTerseUpdate();
//            m_group.RootPart.ScheduleTerseUpdate();
            m_frames.Clear();
        }

        public void Pause()
        {
            m_running = false;
            RemoveTimer();

            m_group.RootPart.Velocity = Vector3.Zero;
            m_group.RootPart.AngularVelocity = Vector3.Zero;
            m_group.SendGroupRootTerseUpdate();
//            m_group.RootPart.ScheduleTerseUpdate();

        }

        private void GetNextList()
        {
            m_frames.Clear();
            Vector3 pos = m_basePosition;
            Quaternion rot = m_baseRotation;

            if (m_mode == PlayMode.Loop || m_mode == PlayMode.PingPong || m_iterations == 0)
            {
                int direction = 1;
                if (m_mode == PlayMode.Reverse || ((m_mode == PlayMode.PingPong) && ((m_iterations & 1) != 0)))
                    direction = -1;

                int start = 0;
                int end = m_keyframes.Length;
//                if (m_mode == PlayMode.PingPong && m_keyframes.Length > 1)
//                    end = m_keyframes.Length - 1;

                if (direction < 0)
                {
                    start = m_keyframes.Length - 1;
                    end = -1;
//                    if (m_mode == PlayMode.PingPong && m_keyframes.Length > 1)
//                        end = 0;
                }

                for (int i = start; i != end ; i += direction)
                {
                    Keyframe k = m_keyframes[i];

                    if (k.Position.HasValue)
                    {
                        k.Position = (k.Position * direction);
//                        k.Velocity = (Vector3)k.Position / (k.TimeMS / 1000.0f);
                        k.Position += pos;
                    }
                    else
                    {
                        k.Position = pos;
//                        k.Velocity = Vector3.Zero;
                    }

                    k.StartRotation = rot;
                    if (k.Rotation.HasValue)
                    {
                        if (direction == -1)
                            k.Rotation = Quaternion.Conjugate((Quaternion)k.Rotation);
                        k.Rotation = rot * k.Rotation;
                    }
                    else
                    {
                        k.Rotation = rot;
                    }

/* ang vel not in use for now

                    float angle = 0;

                    float aa = k.StartRotation.X * k.StartRotation.X + k.StartRotation.Y * k.StartRotation.Y + k.StartRotation.Z * k.StartRotation.Z + k.StartRotation.W * k.StartRotation.W;
                    float bb = ((Quaternion)k.Rotation).X * ((Quaternion)k.Rotation).X + ((Quaternion)k.Rotation).Y * ((Quaternion)k.Rotation).Y + ((Quaternion)k.Rotation).Z * ((Quaternion)k.Rotation).Z + ((Quaternion)k.Rotation).W * ((Quaternion)k.Rotation).W;
                    float aa_bb = aa * bb;

                    if (aa_bb == 0)
                    {
                        angle = 0;
                    }
                    else
                    {
                        float ab = k.StartRotation.X * ((Quaternion)k.Rotation).X +
                                   k.StartRotation.Y * ((Quaternion)k.Rotation).Y +
                                   k.StartRotation.Z * ((Quaternion)k.Rotation).Z +
                                   k.StartRotation.W * ((Quaternion)k.Rotation).W;
                        float q = (ab * ab) / aa_bb;

                        if (q > 1.0f)
                        {
                            angle = 0;
                        }
                        else
                        {
                            angle = (float)Math.Acos(2 * q - 1);
                        }
                    }

                    k.AngularVelocity = (new Vector3(0, 0, 1) * (Quaternion)k.Rotation) * (angle / (k.TimeMS / 1000));
 */
                    k.TimeTotal = k.TimeMS;

                    m_frames.Add(k);

                    pos = (Vector3)k.Position;
                    rot = (Quaternion)k.Rotation;
                }

                m_basePosition = pos;
                m_baseRotation = rot;

                m_iterations++;
            }
        }

        protected void OnTimer(object sender, ElapsedEventArgs e)
        {
            if (m_timerStopped) // trap events still in air even after a timer.stop
                return;

            if (m_inOnTimer) // don't let overruns to happen
            {
                m_log.Warn("[KeyFrame]: timer overrun");
                return;
            }

            if (m_group == null)
                return;

            lock (m_onTimerLock)
            {

                m_inOnTimer = true;

                bool update = false;

                try
                {
                    if (m_selected)
                    {
                        if (m_group.RootPart.Velocity != Vector3.Zero)
                        {
                            m_group.RootPart.Velocity = Vector3.Zero;
                            m_group.SendGroupRootTerseUpdate();
//                            m_group.RootPart.ScheduleTerseUpdate();

                        }
                        m_inOnTimer = false;
                        return;
                    }

                    if (m_isCrossing)
                    {
                        // if crossing and timer running then cross failed
                        // wait some time then
                        // retry to set the position that evtually caused the outbound
                        // if still outside region this will call startCrossing below
                        m_isCrossing = false;
                        m_group.AbsolutePosition = m_nextPosition;
                        if (!m_isCrossing)
                        {
                            StopTimer();
                            m_timer.Interval = timerInterval;
                            StartTimer();
                        }
                        m_inOnTimer = false;
                        return;
                    }

                    if (m_frames.Count == 0)
                    {
                        GetNextList();

                        if (m_frames.Count == 0)
                        {
                            Stop();
                            m_inOnTimer = false;
                            return;
                        }

                        m_currentFrame = m_frames[0];
                        m_currentFrame.TimeMS += (int)timerInterval;

                        //force a update on a keyframe transition
                        update = true;
                    }

                    m_currentFrame.TimeMS -= (int)timerInterval;

                    // Do the frame processing
                    double steps = (double)m_currentFrame.TimeMS / timerInterval;

                    if (steps <= 0.0)
                    {
                        m_group.RootPart.Velocity = Vector3.Zero;
                        m_group.RootPart.AngularVelocity = Vector3.Zero;

                        m_nextPosition = (Vector3)m_currentFrame.Position;
                        m_group.AbsolutePosition = m_nextPosition;

                        // we are sending imediate updates, no doing force a extra terseUpdate
//                        m_group.UpdateGroupRotationR((Quaternion)m_currentFrame.Rotation);

                        m_group.RootPart.RotationOffset = (Quaternion)m_currentFrame.Rotation;
                        m_frames.RemoveAt(0);
                        if (m_frames.Count > 0)
                            m_currentFrame = m_frames[0];

                        update = true;
                    }
                    else
                    {
                        float complete = ((float)m_currentFrame.TimeTotal - (float)m_currentFrame.TimeMS) / (float)m_currentFrame.TimeTotal;

                        Vector3 v = (Vector3)m_currentFrame.Position - m_group.AbsolutePosition;
                        Vector3 motionThisFrame = v / (float)steps;
                        v = v * 1000 / m_currentFrame.TimeMS;

                        if (Vector3.Mag(motionThisFrame) >= 0.05f)
                        {
                            //                        m_group.AbsolutePosition += motionThisFrame;
                            m_nextPosition = m_group.AbsolutePosition + motionThisFrame;
                            m_group.AbsolutePosition = m_nextPosition;

                            m_group.RootPart.Velocity = v;
                            update = true;
                        }

                        if ((Quaternion)m_currentFrame.Rotation != m_group.GroupRotation)
                        {
                            Quaternion current = m_group.GroupRotation;

                            Quaternion step = Quaternion.Slerp(m_currentFrame.StartRotation, (Quaternion)m_currentFrame.Rotation, complete);
                            step.Normalize();
/* use simpler change detection
 * float angle = 0;

                            float aa = current.X * current.X + current.Y * current.Y + current.Z * current.Z + current.W * current.W;
                            float bb = step.X * step.X + step.Y * step.Y + step.Z * step.Z + step.W * step.W;
                            float aa_bb = aa * bb;

                            if (aa_bb == 0)
                            {
                                angle = 0;
                            }
                            else
                            {
                                float ab = current.X * step.X +
                                           current.Y * step.Y +
                                           current.Z * step.Z +
                                           current.W * step.W;
                                float q = (ab * ab) / aa_bb;

                                if (q > 1.0f)
                                {
                                    angle = 0;
                                }
                                else
                                {
                                    angle = (float)Math.Acos(2 * q - 1);
                                }
                            }

                            if (angle > 0.01f)
 */
                            if(Math.Abs(step.X - current.X) > 0.001f 
                                || Math.Abs(step.Y - current.Y) > 0.001f 
                                || Math.Abs(step.Z - current.Z) > 0.001f)
                                // assuming w is a dependente var

                            {
//                                m_group.UpdateGroupRotationR(step);
                                m_group.RootPart.RotationOffset = step;

                                //m_group.RootPart.UpdateAngularVelocity(m_currentFrame.AngularVelocity / 2);
                                update = true;
                            }
                        }
                    }

                    if (update)
                        m_group.SendGroupRootTerseUpdate();
//                        m_group.RootPart.ScheduleTerseUpdate();


                }
                catch ( Exception ex)
                {
                    // still happening sometimes
                    // lets try to see where
                    m_log.Warn("[KeyFrame]: timer overrun" + ex.Message);
                }

                finally
                {
                    // make sure we do not let this frozen
                    m_inOnTimer = false;
                }
            }
        }

        public Byte[] Serialize()
        {
            StopTimer();
            MemoryStream ms = new MemoryStream();

            BinaryFormatter fmt = new BinaryFormatter();
            SceneObjectGroup tmp = m_group;
            m_group = null;
            if (!m_selected && tmp != null)
                m_serializedPosition = tmp.AbsolutePosition;
            fmt.Serialize(ms, this);
            m_group = tmp;
            if (m_running && !m_waitingCrossing)
                StartTimer();

            return ms.ToArray();
        }

        public void StartCrossingCheck()
        {
            // timer will be restart by crossingFailure
            // or never since crossing worked and this 
            // should be deleted
            StopTimer();
           
            m_isCrossing = true;
            m_waitingCrossing = true;

// to remove / retune to smoth crossings
            if (m_group.RootPart.Velocity != Vector3.Zero)
            {
                m_group.RootPart.Velocity = Vector3.Zero;
                m_group.SendGroupRootTerseUpdate();
//                m_group.RootPart.ScheduleTerseUpdate();
            }
        }

        public void CrossingFailure()
        {
            m_waitingCrossing = false;

            if (m_group != null)
            {
                m_group.RootPart.Velocity = Vector3.Zero;
                m_group.SendGroupRootTerseUpdate();
//                m_group.RootPart.ScheduleTerseUpdate();

                if (m_running && m_timer != null)
                {
                    m_timer.Interval = 60000;
                    StartTimer();
                }
            }
        }
    }
}