OSDN Git Service

[dennco] integrated engine related changes from denncoCreator
[dennco/dennco.git] / Source / platform / qt / qtdntimekeeperimpl.cpp
1 //  Copyright (c) 2012 Dennco Project
2 //
3 // This program is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation, either version 3 of the License, or
6 // (at your option) any later version.
7 //
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 // GNU General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16 //
17 //  Created by tkawata on 2/25/2012.
18 //
19 #include "qtdntimekeeperimpl.h"
20
21 #include <QThread>
22 #include <QDateTime>
23
24 class SleeperThread : public QThread
25 {
26 public:
27     static void msleep(unsigned long msecs)
28     {
29         QThread::msleep(msecs);
30     }
31 };
32
33 DNTimeKeeperImpl *DNTimeKeeperImpl::create()
34 {
35     return new QtDNTimeKeeperImpl;
36 }
37
38 QtDNTimeKeeperImpl::QtDNTimeKeeperImpl() : mIntervalTime(1000),mAdjustTime(0),mPrevTime(0),mStartTime(0),mTickTime(0)
39 {
40 }
41
42 QtDNTimeKeeperImpl::~QtDNTimeKeeperImpl()
43 {
44 }
45
46 bool  QtDNTimeKeeperImpl::setIntevalSec(float time)
47 {
48     mIntervalTime = time * 1000;
49     mAdjustTime = 0.0;
50     return true;
51 }
52
53 bool  QtDNTimeKeeperImpl::sleepUntilNextInterval()
54 {
55     if (mStartTime == 0)
56     {
57         start();
58     }
59     qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
60     qint64 dt = currentTime - mPrevTime;
61     qint64 wt = mIntervalTime - dt + (int)mAdjustTime;
62     if (wt < 1)  // wait at least 1ms.
63     {
64         wt = 1;
65     }
66     SleeperThread::msleep(wt);
67     qint64 t = QDateTime::currentMSecsSinceEpoch();
68
69     mAdjustTime += mIntervalTime - (t - mPrevTime);
70     if (mAdjustTime < -mIntervalTime * 0.3)
71     {
72         mAdjustTime = -mIntervalTime * 0.3;
73     }
74     mPrevTime = t;
75
76     mTickTime = (mPrevTime - mStartTime)/1000.0;
77
78     return true;
79 }
80
81 float QtDNTimeKeeperImpl::getTickTime()
82 {
83     return mTickTime;
84 }
85
86 bool QtDNTimeKeeperImpl::start()
87 {
88     mStartTime = QDateTime::currentMSecsSinceEpoch();
89     mPrevTime = mStartTime;
90     mAdjustTime = 0.0;
91     mTickTime = 0.0;
92     return true;
93 }
94
95 bool QtDNTimeKeeperImpl::stop()
96 {
97     mStartTime = 0;
98     return true;
99 }