Image ReadImage(tjhandle tj, int width, int height, int quality = 75) { static std::vector< char > img; static int count = 0; img.resize(3 * width * height); glReadBuffer(GL_FRONT); #ifdef TIME_READPIXEL using namespace std::chrono; steady_clock::time_point t = steady_clock::now(); #endif glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, &img[0]); #ifdef TIME_READPIXEL const milliseconds E = duration_cast< milliseconds >(steady_clock::now() - t); cout << E.count() << ' '; //doesn't flush, prints after closing window #endif char* out = nullptr; unsigned long size = 0; tjCompress2(tj, (unsigned char*) &img[0], width, 3 * width, height, TJPF_RGB, (unsigned char **) &out, &size, TJSAMP_444, quality, 0); return Image(ImagePtr((char*) out, TJDeleter()), size, count++); }
void FunctionScheduler::addFunctionUniformDistribution( Function<void()>&& cb, milliseconds minInterval, milliseconds maxInterval, StringPiece nameID, milliseconds startDelay) { addFunctionGenericDistribution( std::move(cb), UniformDistributionFunctor(minInterval, maxInterval), nameID.str(), to<std::string>( "[", minInterval.count(), " , ", maxInterval.count(), "] ms"), startDelay); }
int main(int argc, char **argv) { if (argc < 4) { puts("Usage: ./out $num_passengers $capacity $time_interval $cycles"); exit(1); } int num_passengers = stoi(argv[1]), capacity = stoi(argv[2]), time_interval = stoi(argv[3]), cycles = stoi(argv[4]); pthread_t passenger_threads[num_passengers]; pthread_t coaster_thread; s = high_resolution_clock::now(); RollerCoaster coaster_car = RollerCoaster(capacity, time_interval, cycles); Passenger* passengers[num_passengers]; pthread_create(&coaster_thread, NULL, roller_coaster, (void*) &coaster_car); for (int i = 0; i < num_passengers; ++i) { passengers[i] = new Passenger(i + 1, coaster_car); pthread_create(&passenger_threads[i], NULL, passenger, (void*) passengers[i]); } for (int i = 0; i < num_passengers; ++i) pthread_join(passenger_threads[i], NULL); pthread_join(coaster_thread, NULL); cout << "Total waiting time of all passengers: " << wait_time.count() << " millisec\n"; return 0; }
void SocketImpl::set_timeout( const milliseconds& value ) { tcp::socket::native_handle_type native_socket(0); #ifdef BUILD_SSL if ( m_socket not_eq nullptr ) { #endif native_socket = m_socket->native_handle( ); #ifdef BUILD_SSL } else { native_socket = m_ssl_socket->lowest_layer( ).native_handle( ); } #endif struct timeval timeout = { 0, 0 }; timeout.tv_usec = static_cast< long >( value.count( ) * 1000 ); int status = setsockopt( native_socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast< char* >( &timeout ), sizeof( timeout ) ); if ( status == -1 and m_logger not_eq nullptr ) { m_logger->log( Logger::Level::WARNING, "Failed to set socket option, send timeout." ); } status = setsockopt( native_socket, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast< char* >( &timeout ), sizeof( timeout ) ); if ( status == -1 and m_logger not_eq nullptr ) { m_logger->log( Logger::Level::WARNING, "Failed to set socket option, receive timeout." ); } }
void FunctionScheduler::addFunction(Function<void()>&& cb, milliseconds interval, StringPiece nameID, milliseconds startDelay) { addFunctionGenericDistribution( std::move(cb), ConstIntervalFunctor(interval), nameID.str(), to<std::string>(interval.count(), "ms"), startDelay); }
log_entry::log_entry(logger& l, logger::LogLevel level): mLogger(l), mLevel(level) { if(mLevel < 0) return; using namespace std::chrono; const milliseconds ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()); const seconds s = duration_cast<seconds>(ms); const std::time_t t = s.count(); const std::size_t fractional_seconds = ms.count() % 1000; mLogger.lock(); const char timeFormat[] = "%Y-%m-%d %H:%M:%S"; const size_t buffSize = 100; char buff[buffSize]; if(0 != std::strftime(buff, buffSize, timeFormat, std::localtime(&t))) { mLogger.get() << buff; } else { size_t dBuffSize = buffSize; std::unique_ptr<char[]> dbuff; do { dBuffSize *= 2; dbuff.reset(new char[dBuffSize]); } while(0 == std::strftime(dbuff.get(), dBuffSize, timeFormat, std::localtime(&t))); mLogger.get() << dbuff.get(); } mLogger.get() << '.' << fractional_seconds << " "; if(level >= 0 && level <= logger::logDEBUG) { const char* levels[] = {"ERROR","WARNING","INFO","DEBUG"}; mLogger.get() << levels[level]; } mLogger.get() << ": "; }
bool WeightedLoadBalancerStrategy::mySendInterest(const Interest& interest, shared_ptr<MyMeasurementInfo>& measurementsEntryInfo, shared_ptr<pit::Entry>& pitEntry) { typedef MyMeasurementInfo::WeightedFaceSetByDelay WeightedFaceSetByDelay; const WeightedFaceSetByDelay& facesByDelay = measurementsEntryInfo->weightedFaces.get<MyMeasurementInfo::ByDelay>(); const milliseconds totalDelay = measurementsEntryInfo->totalDelay; const milliseconds inverseTotalDelay = MyMeasurementInfo::calculateInverseDelaySum(measurementsEntryInfo); boost::random::uniform_int_distribution<> dist(0, inverseTotalDelay.count()); const uint64_t selection = dist(m_randomGenerator); NFD_LOG_TRACE("selection = " << selection); uint64_t cumulativeWeight = 0; for (WeightedFaceSetByDelay::const_iterator i = facesByDelay.begin(); i != facesByDelay.end(); ++i) { NFD_LOG_TRACE("cumulative weight = " << cumulativeWeight); // weight = inverted delay measurement const uint64_t weight = totalDelay.count() - i->lastDelay.count(); cumulativeWeight += weight; if(selection <= cumulativeWeight && pitEntry->canForwardTo(i->face)) { NFD_LOG_TRACE("fowarding " << interest.getName() << " out face " << i->face.getId()); this->sendInterest(pitEntry, this->getFace(i->face.getId())); return true; } } return false; }
Image ReadImage(int width, int height, float quality = 100) { static std::vector< char > img; static int count = 0; img.resize(3 * width * height); glReadBuffer(GL_FRONT); #ifdef TIME_READPIXEL using namespace std::chrono; steady_clock::time_point t = steady_clock::now(); #endif glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, &img[0]); #ifdef TIME_READPIXEL const milliseconds E = duration_cast< milliseconds >(steady_clock::now() - t); cout << E.count() << ' '; //doesn't flush, prints after closing window #endif uint8_t* out; const size_t size = WebPEncodeRGB((uint8_t*) &img[0], width, height, 3 * width, quality, &out); return Image(ImagePtr((char*) out, WebpDeleter()), size, count++); }
void Transition::update(milliseconds elapsed) { switch (state_) { case State::empty: case State::full: return; case State::increase: progress_ += static_cast<float>(elapsed.count()) / time_to_complete_.count(); if (progress_ >= 1.0f) { progress_ = 1.0f; state_ = State::full; } break; case State::decrease: progress_ -= static_cast<float>(elapsed.count()) / time_to_complete_.count(); if (progress_ <= 0.0f) { progress_ = 0.0f; state_ = State::empty; } break; } }
void AppState::initTimerEngine() { const milliseconds interval(1); const milliseconds dueTime(0); //创建定时器,无属性,自动复位,匿名 HANDLE handle = CreateWaitableTimer(NULL, FALSE, NULL); LARGE_INTEGER liDueTime; liDueTime.QuadPart = -(nanoseconds(dueTime).count() / 100); if (!SetWaitableTimer(handle, &liDueTime, interval.count(), NULL, NULL, FALSE)) { throw std::runtime_error("dispatcherTimerEngine init error!"); } DispatcherTimerEngine& engine = DispatcherTimerEngine::instance(); engine.setInterval(interval); engine.start(dueTime); //添加等待对象,以及触发事件 addEventHandle(handle, std::bind(&DispatcherTimerEngine::update, &engine)); }
void SimpleThinkingWriter::output(const ChessBoard& board, const SearchResult& result, const vector<Move>& main_variation, const int nodes, const milliseconds& time, const Searcher::depth_t depth) { if (!post()) { return; } ostringstream oss; int turn_number = board.turn_number(); int ply = 0; if (board.turn_color() == Color::Black) { oss << turn_number << ". ... "; ++turn_number; ++ply; } for (const Move move : main_variation) { if (ply % 2 == 0) { oss << " " << turn_number << "."; ++turn_number; } oss << " " << move.source() << move.destination(); if (move.is_promotion()) { oss << PieceSet::instance().piece(move.created_piece()).symbol(Color::Black); } ++ply; } const int score = board.turn_color() == Color::White ? result.score : -result.score; m_writer->thinking_output(depth, score, time.count() / 10, nodes, oss.str()); } // namespace olaf
void set_resend_interval(socket &s, milliseconds i) { s.setopt(REQ, REQ_RESEND_IVL, static_cast<int>(i.count())); }
namespace win { const size_t kKeyboardCodeCount = 256; const KeyCode kKeyCodeConvertTable[kKeyboardCodeCount] = { KeyCode::None, KeyCode::Escape, KeyCode::D1, KeyCode::D2, KeyCode::D3, KeyCode::D4, KeyCode::D5, KeyCode::D6, KeyCode::D7, KeyCode::D8, KeyCode::D9, KeyCode::D0, KeyCode::Minus, KeyCode::Equals, KeyCode::Back, KeyCode::Tab, KeyCode::Q, KeyCode::W, KeyCode::E, KeyCode::R, KeyCode::T, KeyCode::Y, KeyCode::U, KeyCode::I, KeyCode::O, KeyCode::P, KeyCode::LeftBracket, KeyCode::RightBracket, KeyCode::Enter, KeyCode::LeftCtrl, KeyCode::A, KeyCode::S, KeyCode::D, KeyCode::F, KeyCode::G, KeyCode::H, KeyCode::J, KeyCode::K, KeyCode::L, KeyCode::Semicolon, KeyCode::Apostrophe, KeyCode::AccentGrave, KeyCode::LeftShift, KeyCode::BackSlash, KeyCode::Z, KeyCode::X, KeyCode::C, KeyCode::V, KeyCode::B, KeyCode::N, KeyCode::M, KeyCode::Comma, KeyCode::Period, KeyCode::Slash, KeyCode::RightShift, KeyCode::NumPadMultiply, KeyCode::LeftAlt, KeyCode::Space, KeyCode::CapsLock, KeyCode::F1, KeyCode::F2, KeyCode::F3, KeyCode::F4, KeyCode::F5, KeyCode::F6, KeyCode::F7, KeyCode::F8, KeyCode::F9, KeyCode::F10, KeyCode::Unknown, //DIK_SCROLL }; class AppState : public boost::noncopyable { static const size_t kKeyInputBufferSize = 16; static const size_t kMouseInputBufferSize = 32; public: int exitCode = 0; HWND windowHwnd; _WinWindow* w = nullptr; AppState() { hInstance_ = GetModuleHandle(nullptr); ASSERT(app_state_ == nullptr); app_state_ = this; } ~AppState() { ASSERT(app_state_ != nullptr); app_state_ = nullptr; } public: template<typename F> void addEventHandle(HANDLE handle, const F& f) { wait_event_handle_table_.push_back(handle); wait_event_func_table_.push_back(f); } HINSTANCE getAppHandle() { return hInstance_; } void initWindow(); void initTimerEngine(); void initInputDevices(); int run(); static AppState& instance() { ASSERT(app_state_ != nullptr); return *app_state_; } private: void invokeEventFunc(size_t inx) { ASSERT(inx < wait_event_func_table_.size()); std::function<void()>& f = wait_event_func_table_[inx]; if (f) { f(); } } KeyCode getKeyCode(uint32_t key_code) { ASSERT(key_code < base::sizeofArray(kKeyCodeConvertTable)); return kKeyCodeConvertTable[key_code]; } void fillMouseInputData(const DIDEVICEOBJECTDATA& data, MouseInputData* fill); void updateKeyInputState(); void updateMouseInputState(); private: HINSTANCE hInstance_; std::vector<HANDLE> wait_event_handle_table_; std::vector<std::function<void()>> wait_event_func_table_; ComPtr<IDirectInput8A> direct_input_; ComPtr<IDirectInputDevice8A> keyboard_device_; ComPtr<IDirectInputDevice8A> mouse_device_; ComPtr<IDirect3D9> d3d_; ComPtr<IDirect3DDevice9> d3d_device_; std::array<uint8_t, kKeyboardCodeCount> key_input_diks_; DIMOUSESTATE2 mouse_input_diks_; static AppState* app_state_; }; AppState* AppState::app_state_ = nullptr; LRESULT CALLBACK windowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CLOSE: { auto& func = AppState::instance().w->baseWindow.onCloseClickedFunc; if (!func || func()) { DestroyWindow(AppState::instance().windowHwnd); } return 0; } case WM_DESTROY: { PostQuitMessage(AppState::instance().exitCode); return 0; } case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); FillRect(hdc, &ps.rcPaint, (HBRUSH) (COLOR_WINDOW + 1)); EndPaint(hwnd, &ps); return 0; } } return DefWindowProc(hwnd, uMsg, wParam, lParam); } void AppState::initWindow() { const wchar_t WINDOW_CLASS_NAME[] = L"Sample Window Class"; WNDCLASSW wc = { }; wc.lpfnWndProc = windowProc; wc.hInstance = hInstance_; wc.lpszClassName = WINDOW_CLASS_NAME; if (!RegisterClassW(&wc)) { throw std::runtime_error("RegisterClassW error!"); } windowHwnd = CreateWindowExW( 0, // Optional window styles. WINDOW_CLASS_NAME, // Window class L"dddd", //Window Title WS_OVERLAPPEDWINDOW, // Window style // Size and position CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, // Parent window NULL, // Menu hInstance_, // Instance handle NULL // Additional application data ); if (!windowHwnd) { throw std::runtime_error("CreateWindowExW error!"); } } void AppState::initTimerEngine() { const milliseconds interval(1); const milliseconds dueTime(0); //创建定时器,无属性,自动复位,匿名 HANDLE handle = CreateWaitableTimer(NULL, FALSE, NULL); LARGE_INTEGER liDueTime; liDueTime.QuadPart = -(nanoseconds(dueTime).count() / 100); if (!SetWaitableTimer(handle, &liDueTime, interval.count(), NULL, NULL, FALSE)) { throw std::runtime_error("dispatcherTimerEngine init error!"); } DispatcherTimerEngine& engine = DispatcherTimerEngine::instance(); engine.setInterval(interval); engine.start(dueTime); //添加等待对象,以及触发事件 addEventHandle(handle, std::bind(&DispatcherTimerEngine::update, &engine)); } void AppState::initInputDevices() { //创建DirectInput8对象 IDirectInput8A* direct_input; dx::throwIfFailed( DirectInput8Create( hInstance_, DIRECTINPUT_VERSION, IID_IDirectInput8, (void **) &direct_input, nullptr) ); direct_input_.reset(direct_input); //创建DirectInput8设备(键盘) IDirectInputDevice8A* keyboard_device; dx::throwIfFailed( direct_input_->CreateDevice(GUID_SysKeyboard, &keyboard_device, nullptr) ); keyboard_device_.reset(keyboard_device); //为键盘设置格式 dx::throwIfFailed( keyboard_device_->SetDataFormat(&c_dfDIKeyboard) ); //为键盘设置行为 dx::throwIfFailed( keyboard_device_->SetCooperativeLevel(windowHwnd, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE) ); //为键盘设置缓冲方式 DIPROPDWORD dipdw; dipdw.diph.dwSize = sizeof(DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = kKeyInputBufferSize; // Arbitary buffer size dx::throwIfFailed( keyboard_device_->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph) ); //创建事件,为自动型(使用完自动置为无信号状态),初始化为无信号状态 HANDLE handle = CreateEvent(NULL, FALSE, FALSE, NULL); if (!handle) { throw std::runtime_error("CreateEvent keyboard error!"); } //为键盘安装事件通知关联,并准备获取采集 keyboard_device_->SetEventNotification(handle); keyboard_device_->Acquire(); //添加等待对象,以及触发事件 addEventHandle(handle, std::bind(&AppState::updateKeyInputState, this)); //创建DirectInput8设备(鼠标) IDirectInputDevice8A* mouse_device; dx::throwIfFailed( direct_input_->CreateDevice(GUID_SysMouse, &mouse_device, NULL) ); mouse_device_.reset(mouse_device); //为鼠标设置格式(8按键鼠标) dx::throwIfFailed( mouse_device_->SetDataFormat(&c_dfDIMouse2) ); //为鼠标设置行为 dx::throwIfFailed( mouse_device_->SetCooperativeLevel(windowHwnd, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE) ); //鼠标设置缓冲方式 dipdw.diph.dwSize = sizeof(DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw.diph.dwObj = 0; dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = kMouseInputBufferSize; dx::throwIfFailed( mouse_device_->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph) ); handle = CreateEvent(NULL, FALSE, FALSE, NULL); if (!handle) { throw std::runtime_error("CreateEvent mouse error!"); } mouse_device_->SetEventNotification(handle); mouse_device_->Acquire(); addEventHandle(handle, std::bind(&AppState::updateMouseInputState, this)); /* _pD3D = Direct3DCreate9(D3D_SDK_VERSION); if(_pD3D == nullptr) { BOOST_THROW_EXCEPTION(std::runtime_error("Direct3DCreate9 error!")); } D3DPRESENT_PARAMETERS d3dpp; ZeroMemory( &d3dpp, sizeof( d3dpp ) ); d3dpp.Windowed = TRUE; //不是全屏 d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; hr = _pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, WindowHwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &_pd3dDevice); if (FAILED(hr)) { BOOST_THROW_EXCEPTION(std::runtime_error("CreateDevice IDirect3DDevice9 error!")); } IDirect3DSurface8* lpDSCursor; hr = _pd3dDevice->CreateImageSurface(32, 32, D3DFMT_A8R8G8B8,&lpDSCursor); */ } void AppState::updateKeyInputState() { DIDEVICEOBJECTDATA didod[kKeyInputBufferSize]; // Receives buffered data KeyInputData data_buff[kKeyInputBufferSize]; DWORD dwElements = kKeyInputBufferSize; dx::throwIfFailed( keyboard_device_->GetDeviceState(sizeof(key_input_diks_), key_input_diks_.data()) ); HRESULT hr = keyboard_device_->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), didod, &dwElements, 0); if (hr == DI_OK) { ASSERT(dwElements != 0); std::transform(didod, didod + dwElements, data_buff, [this](DIDEVICEOBJECTDATA& d) { return KeyInputData {getKeyCode(d.dwOfs) , d.dwData & 0x80}; }); KeyboardInput::instance().updateState( { data_buff, data_buff + dwElements }); } else { LOGI(kLogSignWin,"GetDeviceData[%ld]", hr); } } void AppState::fillMouseInputData(const DIDEVICEOBJECTDATA& data, MouseInputData* fill) { auto f_btn = [](MouseInputData* fill_data,MouseCode code,DWORD dwData) { fill_data->code = code; fill_data->downState = dwData & 0x80; }; auto f_wheel = [](MouseInputData* fill_data,MouseCode code,DWORD dwData) { fill_data->code = code; fill_data->increment = dwData; }; switch (data.dwOfs) { case DIMOFS_BUTTON0: { f_btn(fill, MouseCode::LeftButton, data.dwData); break; } case DIMOFS_BUTTON1: { f_btn(fill, MouseCode::RightButton, data.dwData); break; } case DIMOFS_BUTTON2: { f_btn(fill, MouseCode::MidButton, data.dwData); break; } case DIMOFS_BUTTON3: { f_btn(fill, MouseCode::ExtraButton0, data.dwData); break; } case DIMOFS_BUTTON4: { f_btn(fill, MouseCode::ExtraButton1, data.dwData); break; } case DIMOFS_BUTTON5: { f_btn(fill, MouseCode::ExtraButton2, data.dwData); break; } case DIMOFS_BUTTON6: { f_btn(fill, MouseCode::ExtraButton3, data.dwData); break; } case DIMOFS_BUTTON7: { f_btn(fill, MouseCode::ExtraButton4, data.dwData); break; } case DIMOFS_X: { f_wheel(fill, MouseCode::MoveX, data.dwData); break; } case DIMOFS_Y: { f_wheel(fill, MouseCode::MoveY, data.dwData); break; } case DIMOFS_Z: { f_wheel(fill, MouseCode::Wheel, data.dwData); break; } default: ASSERT_MSG(false,"not the input type"); break; } } void AppState::updateMouseInputState() { DIDEVICEOBJECTDATA didod[kMouseInputBufferSize]; // Receives buffered data MouseInputData data_buff[kMouseInputBufferSize]; DWORD dwElements = kMouseInputBufferSize; dx::throwIfFailed( mouse_device_->GetDeviceState(sizeof(mouse_input_diks_), &mouse_input_diks_) ); HRESULT hr = mouse_device_->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), didod, &dwElements, 0); if (hr == DI_OK) { ASSERT(dwElements != 0); std::transform(didod, didod + dwElements, data_buff, [this](DIDEVICEOBJECTDATA& d) { MouseInputData data; fillMouseInputData(d, &data); return data; }); MouseInput::instance().updateState( { data_buff, data_buff + dwElements }); } else { LOGI(kLogSignWin,"GetDeviceData[%ld]", hr); } } int AppState::run() { const size_t wait_count = wait_event_handle_table_.size(); const HANDLE* wait_handle_table = wait_event_handle_table_.data(); MSG msg = { }; while (true) { size_t resoult_offset = MsgWaitForMultipleObjects( wait_count, wait_handle_table, FALSE, INFINITE, QS_ALLINPUT) - WAIT_OBJECT_0; if (resoult_offset < wait_count) { invokeEventFunc(resoult_offset); } else { while (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { if (msg.message == WM_QUIT) goto _Exit; TranslateMessage(&msg); DispatchMessage(&msg); } } } _Exit: return exitCode; } _WinApp::_WinApp() : app_state_(new AppState()) { } _WinApp::~_WinApp() { } int _WinApp::run() { return app_state_->run(); } void _WinApp::exit(int exitCode) { app_state_->exitCode = exitCode; DestroyWindow(app_state_->windowHwnd); } void _WinApp::init() { app_state_->initWindow(); app_state_->initTimerEngine(); app_state_->initInputDevices(); } _WinWindow::_WinWindow(system::BaseWindow& w) : baseWindow(w) { } void _WinWindow::init() { AppState::instance().w = this; } void _WinWindow::notifyTitleUpdate(const std::string& text) { std::u16string s = base::to<std::u16string>(text); SetWindowTextW(AppState::instance().windowHwnd, reinterpret_cast<const wchar_t*>(s.c_str())); } void _WinWindow::show() { ShowWindow(AppState::instance().windowHwnd, SW_SHOW); AppState::instance().w = this; } } // namespace win
void sleep_for(milliseconds d) { // usleep is nanoseconds. usleep (d.count() * 1000); }
Timer::Timer(milliseconds expiration_time, bool start_active) : current_time_{ start_active ? 0 : expiration_time.count() + 1}, expiration_time_{expiration_time} { timers_.insert(this); }
void PoolingAcceptor::onTimer(const milliseconds& delta) { LOG(INFO)<< "[" << __FUNCTION__ << "] " << delta.count(); }
milliseconds abs(const milliseconds& t) { return milliseconds(abs(t.count())); }
void TimedAxisController::setInterval(unsigned int interval) { assert(interval < MAX_MILLI.count()); this->interval = milliseconds(interval); }
//------------------------------------------------------------------------------ int main(int argc, char** argv) { //USER INPUT if(argc < 2) { std::cout << "usage: " << argv[0] << " <size>" << std::endl; exit(EXIT_FAILURE); } const int SIZE = atoi(argv[1]); //GRAPHICS SETUP glfwSetErrorCallback(error_callback); if(!glfwInit()) { std::cerr << "ERROR - glfwInit" << std::endl; exit(EXIT_FAILURE); } tjhandle tj = tjInitCompress(); //========================================================================== using WSS = wsp::WebSocketService; WSS imageStreamer; //WSS::ResetLogLevels(); //init service shared_ptr< ImageContext > context(new ImageContext); auto is = async(launch::async, [&context](WSS& imageStreamer){ imageStreamer.Init(5000, //port nullptr, //SSL certificate path nullptr, //SSL key path context, //context instance, //will be copied internally WSS::Entry< ImageService, WSS::ASYNC_REP >("image-stream")); //start event loop: one iteration every >= 50ms imageStreamer.StartLoop(5, //ms [](){return !END;} //continuation condition (exit on false) //checked at each iteration, loops forever //in this case ); }, std::ref(imageStreamer)); //========================================================================== //WARNING: THIS DOESN'T WORK // glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif GLFWwindow* window = glfwCreateWindow(1024, 768, "image streaming", NULL, NULL); if (!window) { std::cerr << "ERROR - glfwCreateWindow" << std::endl; glfwTerminate(); exit(EXIT_FAILURE); } glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl; std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl; std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl; //GEOMETRY //geometry: textured quad float quad[] = {-1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f}; float texcoord[] = {0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f}; //OpenGL >= 3.3 core requires a vertex array object containing multiple attribute //buffers GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); //geometry buffer GLuint quadvbo; glGenBuffers(1, &quadvbo); glBindBuffer(GL_ARRAY_BUFFER, quadvbo); glBufferData(GL_ARRAY_BUFFER, 6 * 4 * sizeof(float), &quad[0], GL_STATIC_DRAW); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); //texture coordinate buffer GLuint texbo; glGenBuffers(1, &texbo); glBindBuffer(GL_ARRAY_BUFFER, texbo); glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(real_t), &texcoord[0], GL_STATIC_DRAW); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // create texture std::vector< float > tc(SIZE * SIZE, 0.5f); GLuint tex; glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, SIZE, SIZE, 0, GL_RED, GL_FLOAT, &tc[0]); //optional glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); //required glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); //OPENGL RENDERING SHADERS GLuint glprogram = create_program(vertexShaderSrc, fragmentShaderSrc); //enable gl program glUseProgram(glprogram); //extract ids of shader variables GLint mvpID = glGetUniformLocation(glprogram, "MVP"); GLint textureID = glGetUniformLocation(glprogram, "cltexture"); GLint frameID = glGetUniformLocation(glprogram, "frame"); //only need texture unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, tex); glUniform1i(textureID, 0); //beckground color glClearColor(0.0f, 0.0f, 0.4f, 0.0f); //RENDER LOOP //rendering & simulation loop UserData data(vao, quadvbo, texbo, mvpID, frameID, context, 0); glfwSetWindowUserPointer(window, &data); int width = 0; int height = 0; using namespace std::chrono; const milliseconds T(20); while (!glfwWindowShouldClose(window)) { steady_clock::time_point t = steady_clock::now(); glfwGetFramebufferSize(window, &width, &height); Draw(window, data, width, height); glfwSwapBuffers(window); data.context->SetServiceDataSync(ReadImage(tj, width, height, 100)); ++data.frame; const milliseconds E = duration_cast< milliseconds >(steady_clock::now() - t); #ifdef TIME_RENDER_STEP cout << E.count() << ' '; #endif std::this_thread::sleep_for( max(duration_values<milliseconds>::zero(), T - E)); glfwPollEvents(); } //CLEANUP glDeleteBuffers(1, &quadvbo); glDeleteBuffers(1, &texbo); glDeleteTextures(1, &tex); glfwDestroyWindow(window); glfwTerminate(); is.wait(); tjDestroy(tj); exit(EXIT_SUCCESS); return 0; }