int main() { IDevice* device = createDevice(EDT_DIRECT3D11, 800, 600); IVideoDriver* driver = device->getVideoDriver(); IResourceGroupManager* resourceGroupManager = driver->getResourceGroupManager(); resourceGroupManager->init("Resources.cfg"); IInputDriver* input = device->getInputDriver(); ISceneManager* smgr = setupScene(device); driver->setDeferredShading(true); ITimer* timer = device->getTimer(); timer->reset(); const f32 color[] = { 0, 0, 0, 1.0f }; while (device->run()) { float dt = timer->tick(); if (input->keyDown(GVK_ESCAPE)) break; smgr->update(dt); driver->beginScene(true, true, color); smgr->drawAll(); driver->endScene(); } smgr->destroy(); device->drop(); return 0; }
int main() { IDevice* device = createDevice(EDT_DIRECT3D11, 800, 600); IVideoDriver* driver = device->getVideoDriver(); ISceneManager* smgr = device->createSceneManager(); ITimer* timer = device->getTimer(); timer->reset(); // test XMFLOAT4 plane(0, 1.0f, 0, 0); XMFLOAT3 p(1.0f, 3.0f, -2.0f); XMFLOAT3 p2 = math::ComputeMirrorPointAboutPlane(plane, p); std::cout << p2.x << "," << p2.y << "," << p2.z << std::endl; const f32 color[] = { 0, 1.0f, 0, 1.0f }; while (device->run()) { driver->beginScene(true, true, color); float dt = timer->tick(); smgr->update(dt); smgr->drawAll(); driver->endScene(); } smgr->destroy(); device->drop(); return 0; }
//------------------------------------------------------------------------- // r u n //------------------------------------------------------------------------- void CApplication::run() { ITimer* timer = m_device->getTimer(); u32 current, last = timer->getRealTime(); u32 delta = 0; m_running = true; while(m_device->run() && m_running) { // calc seconds since last frame current = timer->getRealTime(); delta = current-last; last = current; m_videoDriver->beginScene(true, true, SColor(255,100,101,140)); preRender(delta); m_sceneManager->drawAll(); m_gui->drawAll(); postRender(); m_videoDriver->endScene(); } logMessage("Exiting Run Loop"); stringc msg = "Frame Rate - Avg: "; msg += m_fpsAvg; msg += ", Min: "; msg += m_fpsMin; msg += ", Max: "; msg += m_fpsMax; logMessage(msg); }
bool Application::run(){ if(!device) return false; ITimer* irrTimer = device->getTimer(); u32 TimeStamp = irrTimer->getTime(), DeltaTime = 0; while(device->run() && driver){ DeltaTime = irrTimer->getTime() - TimeStamp; TimeStamp = irrTimer->getTime(); this->updateTitle(); if(device->isWindowActive()){ driver->beginScene(true, true, video::SColor(255,100,100,100)); smgr->drawAll(); device->getGUIEnvironment()->drawAll(); driver->endScene(); } if(scene) scene->update(DeltaTime, state); if(state != oldState) loadLevel(); } return true; }
///@brief bool dbLoopGDK() { dbPRINT("dbLoopGDK()\n"); DarkGDK_SGlobalStruct& app = DarkGDK_SGlobalStruct::getInstance(); IrrlichtDevice* device = app.Device; if (!device) return false; /// empty irrlicht message loop if (!device->run()) return false; ITimer* timer = device->getTimer(); /// get current time app.Time_Now = timer->getTime(); if (app.Time_Now >= app.Time_Last + 1000 ) { app.FPS_Now = app.FPS_Count; app.FPS_Count = 0; if (app.FPS_Min > app.FPS_Now) app.FPS_Min = app.FPS_Now; if (app.FPS_Max < app.FPS_Now) app.FPS_Max = app.FPS_Now; app.Time_Last = timer->getTime(); } video::IVideoDriver* driver = device->getVideoDriver(); /// check resize-event if ( app.ScreenSize != driver->getScreenSize() ) { app.ScreenSize = driver->getScreenSize(); app.ScreenRect = core::recti( 0, 0, app.ScreenSize.Width-1, app.ScreenSize.Height-1); driver->OnResize( app.ScreenSize ); /// resize aspect ratio of current active camera scene::ISceneManager* smgr = device->getSceneManager(); scene::ICameraSceneNode* camera = smgr->getActiveCamera(); if ( camera ) { app.CurrentCamera = camera; camera->setAspectRatio( (f32)app.ScreenSize.Width / (f32)app.ScreenSize.Width ); } } return true; }
int main() { SDeviceContextSettings settings; settings.MultiSamplingCount = 4; settings.MultiSamplingQuality = 32; IApplication* device = createDevice(EDT_DIRECT3D11, 800, 600, EWS_NONE, true, settings); IVideoDriver* driver = device->getVideoDriver(); ISceneManager* smgr = device->createSceneManager(); IMeshManager* meshManager = driver->getMeshManager(); IResourceGroupManager* resourceGroupManager = driver->getResourceGroupManager(); resourceGroupManager->init("Resources.cfg"); //resourceGroupManager->loadResourceGroup("General"); XMFLOAT3 vertices[4]; vertices[0] = XMFLOAT3(-10.0f, 0.0f, 10.0f); vertices[1] = XMFLOAT3(10.0f, 0.0f, 10.0f); vertices[2] = XMFLOAT3(-10.0f, 0.0f, -10.0f); vertices[3] = XMFLOAT3(10.0f, 0.0f, -10.0f); ISimpleMesh* mesh = meshManager->createSimpleMesh("pointlist", EVF_POSITION, vertices, NULL, 4, sizeof(XMFLOAT3), 0, math::SAxisAlignedBox(), false); IMeshNode* meshNode = smgr->addMeshNode(mesh, nullptr, nullptr); meshNode->setMaterialName("test/ts_material"); meshNode->setNeedCulling(false); ICameraNode* camera = smgr->addFpsCameraNode(1, nullptr, XMFLOAT3(0, 1.0f, -4.0f), XMFLOAT3(0, 1.0f, 0.0f)); char caption[200]; ITimer* timer = device->getTimer(); timer->reset(); while (device->run()) { const float clearColor[] = { 0.0f, 0.0f, 0.0f, 1.0f }; driver->beginScene(true, true, clearColor); float dt = timer->tick() * 0.001f; updateCamera(camera, dt); smgr->update(dt); smgr->drawAll(); driver->endScene(); sprintf(caption, "FPS:%f", getFps(dt)); device->setWindowCaption(caption); } device->drop(); return 0; }
ORZ_PLUS_INLINE void startTimer (TmrId _id, uint32 _time, PtrIntType _data, const boost::function<void (TmrId, PtrIntType)>& _callback, int32 _loop) { DynShrLock lock(m_timers.mutex(_id, _id)); ITimer* tmr = m_timers.get(_id, _id, false); if (!tmr) { return; } tmr->start(_time, _data, _callback, _loop); }
ORZ_PLUS_INLINE void stopTimer (TmrId _id) { DynShrLock lock(m_timers.mutex(_id, _id)); ITimer* tmr = m_timers.get(_id, _id, false); if (!tmr) { return; } tmr->stop(); }
void CDestroyAfterSecondsComponent::Update (TimeDuration duration) { if (m_timer != nullptr) { return m_timer->Update(duration); } m_timer = TimeMgrGet()->CreateTimer(this, duration); }
void bench_mandelbrot_single_cpu_par( ITimer& timer, Extent& ext, thrust::host_vector<int>& h, const int max_iter, Rectangle r ) { timer.start(); mandelbrot_cpu_par(ext, thrust::raw_pointer_cast(&h[0]), max_iter, r); timer.stop(); cout << max_iter << ";" << timer.delta() << endl; }
int main() { IAscriber* ascriber = Ascriber::getInstance(); ITimer* timer = new Timer(ascriber); new AnalogClock(timer, ascriber); new DigitalClock(timer, ascriber); while(1) { timer->tick(); this_thread::sleep_for (chrono::seconds(1)); } delete timer; return 0; }
int _tmain(int argc, _TCHAR* argv[]) { SDeviceContextSettings settings; settings.MultiSamplingCount = 1; settings.MultiSamplingQuality = 0; settings.WindowsProcedure = EditorWindow::WndProc; EditorWindow* window = new EditorWindow(SCREEN_WIDTH, SCREEN_HEIGHT); EditorWindow::_setInstance(window); IDevice* device = gf::createDevice(EDT_DIRECT3D11, SCREEN_WIDTH, SCREEN_HEIGHT, EWS_NONE, true, settings); IVideoDriver* driver = device->getVideoDriver(); EditorScene* scene = new EditorScene(device); EditorScene::_setInstance(scene); scene->setupInitialScene(); window->init(); ITimer* timer = device->getTimer(); timer->reset(); char caption[200]; while (device->run()) { const float clearColor[] = { 1.0f, 0.0f, 0.0f, 1.0f }; driver->beginScene(true, true, clearColor); f32 dt = timer->tick(); scene->update(dt); scene->drawAll(); driver->endScene(); sprintf(caption, "FPS:%f", getFps(dt)); device->setWindowCaption(caption); } delete scene; device->drop(); return 0; }
int main() { INotifier* notifier = ChangeManager::getInstance(); //MODEL ITimer* timer = new Timer(notifier); timer->setSeconds(56); timer->setMinutes(59); timer->setHours(23); timer->start(); IAscriber* ascriber = ChangeManager::getInstance(); //VIEW IWidget* analogClock = new AnalogClock(timer, ascriber); IWidget* digitalClock = new DigitalClock(timer, ascriber); //CLEAN delete timer; delete analogClock; delete digitalClock; return 0; }
int _tmain(int argc, _TCHAR* argv[]) { srand(time(0)); SAppSettings settings; settings.Graphics.MultiSamplingCount = 8; settings.Graphics.MultiSamplingQuality = 32; settings.Window.Width = 400; settings.Window.Height = 300; //IApplication* device = gf::createDevice(EDT_DIRECT3D11, SCREEN_WIDTH, SCREEN_HEIGHT, EWS_NONE, true, settings); device = gf::createApp(settings); driver = device->getVideoDriver(); math::SAxisAlignedBox aabb; aabb.Center = XMFLOAT3(0, 10.0f, 0); aabb.Extents = XMFLOAT3(500.0f, 500.0f, 500.0f); smgr = device->createSceneManager(aabb); IMeshManager* meshManager = driver->getMeshManager(); IMaterialManager* materialManager = driver->getMaterialManager(); ITextureManager* textureManager = driver->getTextureManager(); IPipelineManager* pipelineManager = driver->getPipelineManager(); IResourceGroupManager* resourceGroupManager = driver->getResourceGroupManager(); resourceGroupManager->init("Resources.cfg"); PhysicsEngine::getInstance(); setupPhysics(smgr); // create ground ISimpleMesh* groundMesh = meshManager->createPlaneMesh("ground", groundSize, groundSize, 10, 10, 30.0f, 30.0f); IMeshNode* groundNode = smgr->addMeshNode(groundMesh, nullptr, nullptr, false); groundNode->setMaterialName("ground_material"); createBoxes(smgr); // add directional light XMFLOAT3 light_dir(5.0f, -5.0f, -2.0f); f32 lightDistance = -20; ILightNode* light = smgr->addDirectionalLight(1, nullptr, light_dir); light->setSpecular(XMFLOAT4(1.0f, 1.0, 1.0f, 32.0f)); light->setDiffuse(XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f)); //light->setShadowCameraOrthographicSize(10.0f, 7.0f); XMFLOAT4 unit_dir = light->getDirection(); light->setPosition(XMFLOAT3(unit_dir.x * lightDistance, unit_dir.y * lightDistance, unit_dir.z * lightDistance)); light->setShadowMapSize(SCREEN_WIDTH, SCREEN_HEIGHT); light->setShadowCameraOrthographicSize(100.0f, 100.0f); light->enableShadow(true); camera = smgr->addFpsCameraNode(1, nullptr, XMFLOAT3(0, 1.0f, -4.0f), XMFLOAT3(0, 1.0f, 0.0f), XMFLOAT3(0, 1.0f, 0), true); camera->setPosition(XMFLOAT3(0, 20.0f, -40.0f)); camera->lookAt(XMFLOAT3(0, 0, 0)); camera->setNearZ(1.0f); camera->setFarZ(1000.0f); camera->setShadowRange(200.0f); smgr->setAmbient(XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f)); updateLightDirection(10.0f, light); ITimer* timer = device->getTimer(); timer->reset(); const f32 color2[] = { 1.0f, 0.0f, 0.0f, 1.0f }; device->setUpdateCallback(game_update); device->run(); /* while (device->run()) { const float clearColor[] = { 0.0f, 0.0f, 0.0f, 1.0f }; driver->beginScene(true, true, clearColor); float dt = timer->tick(); //float dt = ms * 0.001f; updatePhysics(dt); updateCamera(camera, dt); //updateLightDirection(dt, light); smgr->update(dt); smgr->drawAll(); driver->endScene(); sprintf_s(caption, "FPS:%f", getFps(dt)); device->setWindowCaption(caption); //Sleep(10); } */ //sphereMaterial.drop(); smgr->destroy(); device->drop(); delete g_ground; delete g_box; PhysicsEngine::deleteInstance(); return 0; }
int main() { SDeviceContextSettings settings; settings.MultiSamplingCount = 4; settings.MultiSamplingQuality = 32; IApplication* device = gf::createDevice(EDT_DIRECT3D11, SCREEN_WIDTH, SCREEN_HEIGHT, EWS_NONE, true, settings); IVideoDriver* driver = device->getVideoDriver(); ISceneManager* smgr = device->createSceneManager(); IMeshManager* meshManager = driver->getMeshManager(); IMaterialManager* materialManager = driver->getMaterialManager(); ITextureManager* textureManager = driver->getTextureManager(); IPipelineManager* pipelineManager = driver->getPipelineManager(); IResourceGroupManager* resourceGroupManager = driver->getResourceGroupManager(); resourceGroupManager->init("Resources.cfg"); const f32 groundSize = 1000.0f; ISimpleMesh* groundMesh = meshManager->createPlaneMesh("ground", groundSize, groundSize, 100, 100, 100.0f, 100.0f); IMeshNode* groundNode = smgr->addMeshNode(groundMesh, nullptr, nullptr, false); groundNode->setMaterialName("ground_material"); // add point lights const u32 lightColNum = 10; const u32 lightRowNum = 10; f32 xLightSpace = groundSize / (lightColNum - 1); f32 zLightSpace = groundSize / (lightRowNum - 1); for (u32 i = 0; i < lightRowNum; i++) { for (u32 j = 0; j < lightColNum; j++) { u32 id = i * lightColNum + j; f32 x = -groundSize * 0.5f + xLightSpace * j; f32 z = groundSize * 0.5f - zLightSpace * i; ILightNode* light = smgr->addPointLight(id, nullptr, true, XMFLOAT3(x, 50.0f, z), 200.0f); light->setSpecular(XMFLOAT4(12.0f, 12.0f, 12.0f, 32.0f)); light->setDiffuse(XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f)); light->setAttenuation(1.0f, 0.1f, 0); } } /* IModelMesh* carMesh = meshManager->getModelMesh("myfirst.mesh"); IMeshNode* carNode = smgr->addModelMeshNode(carMesh, NULL, false); carNode->translate(0, 0.1f, 0); carNode->setNeedCulling(false); carNode->scale(0.05f, 0.05f, 0.05f); carNode->pitch(XM_PIDIV2); */ IModelMesh* carMesh = meshManager->getModelMesh("car B red.mesh"); IMeshNode* carNode = smgr->addModelMeshNode(carMesh, NULL, false); carNode->translate(0, 1.0f, 0); //carNode->setNeedCulling(false); //carNode->scale(0.05f, 0.05f, 0.05f); //carNode->pitch(XM_PIDIV2); IModelMesh* wheelleftFrontMesh = meshManager->getModelMesh("wheel front left.mesh"); IMeshNode* wheelleftFront = smgr->addModelMeshNode(wheelleftFrontMesh, carNode, false); //carNode->setNeedCulling(false); ICameraNode* camera = smgr->addFpsCameraNode(1, nullptr, XMFLOAT3(0, 1.0f, -4.0f), XMFLOAT3(0, 1.0f, 0.0f)); camera->setFarZ(3000.0f); smgr->setAmbient(XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f)); char caption[200]; ITimer* timer = device->getTimer(); timer->reset(); const f32 color2[] = { 1.0f, 0.0f, 0.0f, 1.0f }; while (device->run()) { const float clearColor[] = { 0.0f, 0.0f, 0.0f, 1.0f }; driver->beginScene(true, true, clearColor); u32 ms = timer->tick(); float dt = ms * 0.001f; updateCamera(camera, dt); //updateCarPosition(dt, carNode, camera); smgr->update(ms); smgr->drawAll(); driver->endScene(); f32 fps = getFps(dt); sprintf_s(caption, "FPS:%f, delta:%f", fps, 1000.0f/fps); device->setWindowCaption(caption); } //sphereMaterial.drop(); smgr->destroy(); device->drop(); return 0; }
//! Test both the accuracy and speed of Irrlicht's fast_atof() implementation. bool fast_atof(void) { bool accurate = true; accurate &= testCalculation("340282346638528859811704183484516925440.000000"); accurate &= testCalculation("3.402823466e+38F"); accurate &= testCalculation("3402823466e+29F"); accurate &= testCalculation("-340282346638528859811704183484516925440.000000"); accurate &= testCalculation("-3.402823466e+38F"); accurate &= testCalculation("-3402823466e+29F"); accurate &= testCalculation("34028234663852885981170418348451692544.000000"); accurate &= testCalculation("3.402823466e+37F"); accurate &= testCalculation("3402823466e+28F"); accurate &= testCalculation("-34028234663852885981170418348451692544.000000"); accurate &= testCalculation("-3.402823466e+37F"); accurate &= testCalculation("-3402823466e+28F"); accurate &= testCalculation(".00234567"); accurate &= testCalculation("-.00234567"); accurate &= testCalculation("0.00234567"); accurate &= testCalculation("-0.00234567"); accurate &= testCalculation("1.175494351e-38F"); accurate &= testCalculation("1175494351e-47F"); accurate &= testCalculation("1.175494351e-37F"); accurate &= testCalculation("1.175494351e-36F"); accurate &= testCalculation("-1.175494351e-36F"); accurate &= testCalculation("123456.789"); accurate &= testCalculation("-123456.789"); accurate &= testCalculation("0000123456.789"); accurate &= testCalculation("-0000123456.789"); accurate &= testCalculation("-0.0690462109446526"); if(!accurate) { logTestString("Calculation is not accurate, so the speed is irrelevant\n"); return false; } IrrlichtDevice* device = createDevice(video::EDT_NULL); if (!device) return false; ITimer* timer = device->getTimer(); enum { ITERATIONS = 100000 }; int i; f32 value; u32 then = timer->getRealTime(); for(i = 0; i < ITERATIONS; ++i) value = (f32)atof("-340282346638528859811704183484516925440.000000"); const u32 atofTime = timer->getRealTime() - then; then += atofTime; for(i = 0; i < ITERATIONS; ++i) value = fast_atof("-340282346638528859811704183484516925440.000000"); const u32 fastAtofTime = timer->getRealTime() - then; then += fastAtofTime; for(i = 0; i < ITERATIONS; ++i) value = old_fast_atof("-340282346638528859811704183484516925440.000000"); const u32 oldFastAtofTime = timer->getRealTime() - then; logTestString(" atof time = %d\n fast_atof Time = %d\nold fast_atof time = %d\n", atofTime, fastAtofTime, oldFastAtofTime); device->drop(); if(fastAtofTime > (1.2f*atofTime)) { logTestString("The fast method is slower than atof()\n"); return false; } return true; }
int main() { SDeviceContextSettings settings; settings.MultiSamplingCount = 4; settings.MultiSamplingQuality = 32; IApplication* device = gf::createDevice(EDT_DIRECT3D11, SCREEN_WIDTH, SCREEN_HEIGHT, EWS_NONE, true, settings); IVideoDriver* driver = device->getVideoDriver(); ISceneManager* smgr = device->createSceneManager(); IMeshManager* meshManager = driver->getMeshManager(); IMaterialManager* materialManager = driver->getMaterialManager(); ITextureManager* textureManager = driver->getTextureManager(); IResourceGroupManager* resourceGroupManager = driver->getResourceGroupManager(); resourceGroupManager->init("Resources.cfg"); // resourceGroupManager->loadResourceGroup("General"); ILightNode* light = smgr->addDirectionalLight(1, nullptr, XMFLOAT3(3.0f, -2.0f, 1.5f)); light->setSpecular(XMFLOAT4(1.0f, 1.0f, 1.0f, 32.0f)); light->setDiffuse(XMFLOAT4(0.4f, 0.4f, 0.4f, 1.0f)); ILightNode* light2 = smgr->addDirectionalLight(2, nullptr, XMFLOAT3(-2.0f, -3.0f, -2.0f)); light2->setSpecular(XMFLOAT4(1.0f, 1.0f, 1.0f, 32.0f)); light2->setDiffuse(XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f)); ICameraNode* camera = smgr->addFpsCameraNode(1, nullptr, XMFLOAT3(0, 30.0f, -4.0f), XMFLOAT3(0, 30.0f, 0.0f), XMFLOAT3(0, 1.0f, 0), true); camera->setViewWidth(300); camera->setViewHeight(200); char caption[200]; std::string rawFileName("heightmap.raw"); ITerrainMesh* mesh = meshManager->createTerrainMesh("terrain", rawFileName, 3.0f, 0.4f, false, true, 1.0f); ITerrainNode* terrainNode = smgr->addTerrainNode(mesh); //terrainNode->setMaterialName("terrain/tessellation_material"); terrainNode->setMaterialName("terrain/terrain_material"); ITextureCube* skyTexture = textureManager->loadCubeTexture("Snow.dds"); smgr->setSkyDome(skyTexture); IRenderTarget* pRenderTarget = textureManager->getRenderTarget("target1"); ITimer* timer = device->getTimer(); timer->reset(); while (device->run()) { const float clearColor[] = { 0.0f, 0.0f, 0.0f, 1.0f }; driver->beginScene(true, true, clearColor); u32 ms = timer->tick(); float dt = ms * 0.001f; updateCamera(camera, dt); XMFLOAT3 camPos = camera->getPosition(); float terrainHeight = terrainNode->getHeight(camPos.x, camPos.z, true); camPos.y = terrainHeight + 3.0f; //camera->setPosition(camPos); smgr->update(ms); smgr->drawAll(); driver->endScene(); u32 num = smgr->getRenderedMeshNum(); sprintf(caption, "FPS:%f num:%d", getFps(dt), num); device->setWindowCaption(caption); } smgr->destroy(); device->drop(); return 0; }
int main(int argc, char* argv[]) { stringc sceneDirectory, saveDir; irr::io::path sceneFileName; UserDataSerializer serializer; if(argc < 2) { printf("error scene file name missing:\n"); printf(" irrbPhysics <input scene filename>\n"); return -1; } // initialize Irrlicht m_device = _createDevice(); if(!m_device) return -1; m_fileSystem = m_device->getFileSystem(); m_videoDriver = m_device->getVideoDriver(); m_sceneManager = m_device->getSceneManager(); m_gui = m_device->getGUIEnvironment(); m_debugNode = new CDebugNode(m_sceneManager); // create debug panel (text area) core::dimension2du screen = m_videoDriver->getScreenSize(); m_debugPanel = m_gui->addStaticText(L"",rect<s32>(screen.Width-202,0,screen.Width-2,100)); m_debugPanel->setBackgroundColor(SColor(128, 30, 30, 30)); m_debugPanel->setDrawBorder(true); IGUIFont* font=m_debugPanel->getOverrideFont(); if(!font) font = m_gui->getSkin()->getFont(); m_charHeight = font->getDimension(L"Ay").Height; s32 idx=0; m_charHeight += font->getKerningHeight(); // create help panel (text area) m_helpPanel = m_gui->addStaticText(L"",rect<s32>(2,0,202,200)); m_helpPanel->setBackgroundColor(SColor(128, 30, 30, 30)); m_helpPanel->setDrawBorder(true); _addHelpText("F1 - Toggle Help"); _addHelpText("F3 - Cycle Wire, Points, Solid"); _addHelpText("F4 - Toggle Physics Debug"); _addHelpText("F5 - Warp To Start Position"); _addHelpText("F9 - Detach Camera"); // turn hardware cursor off m_device->getCursorControl()->setVisible(false); #if defined(USE_BULLET) m_device->setWindowCaption(L"irrb Collision/Physics example - Using Bullet"); #elif defined(USE_IRRPHYSX) m_device->setWindowCaption(L"irrb Collision/Physics example - Using IrrPhysx"); #else m_device->setWindowCaption(L"irrb Collision/Physics example - Using Irrlicht"); #endif m_camera = m_sceneManager->addCameraSceneNodeFPS(0, 100.0f, m_moveSpeed, -1, keyMap, 5, true, m_jumpSpeed); m_camera->setPosition(vector3df(0,10,0)); m_camera->setFOV(core::PI / 2.5f); m_camera->setNearValue(.1f); m_camera->setFarValue(1000.f); // save off animator core::list<ISceneNodeAnimator*>::ConstIterator anims=m_camera->getAnimators().begin(); while(anims != m_camera->getAnimators().end()) { if ((*anims)->getType() == ESNAT_CAMERA_FPS) { m_fpsAnimator = (ISceneNodeAnimatorCameraFPS*)*anims; break; } ++anims; } // init physics library _initPhysicsLibrary(); m_displayPhysicsDebug = true; _enablePhysicsDebug(true); m_debugNode->setVisible(true); // load scene sceneFileName = argv[1]; sceneDirectory = m_fileSystem->getFileDir(sceneFileName); saveDir = m_fileSystem->getWorkingDirectory(); m_fileSystem->changeWorkingDirectoryTo(sceneDirectory); m_sceneManager->loadScene(sceneFileName.c_str(), &serializer); m_fileSystem->changeWorkingDirectoryTo(saveDir); // if the scene also contained a camera, set the active // camera to our fps camera and update the fps pos/rot. if(m_camera && (m_camera != m_sceneManager->getActiveCamera())) { ICameraSceneNode* anode = m_sceneManager->getActiveCamera(); m_camera->setPosition(anode->getPosition()); m_camera->setRotation(anode->getRotation()); m_sceneManager->setActiveCamera(m_camera); m_startPos = m_camera->getPosition(); _warp(m_startPos); } ITimer* timer = m_device->getTimer(); u32 current, last = timer->getRealTime(); u32 delta = 0; while(m_device->run() && m_running) { _clearDebugText(); m_videoDriver->beginScene(true, true, SColor(255,100,101,140)); // calc milliseconds since last frame current = timer->getRealTime(); delta = current-last; last = current; // update collision/physics simulation _stepSimulation(delta); m_sceneManager->drawAll(); static char buf[64]; sprintf(buf, "FPS: %d", m_videoDriver->getFPS()); _updateDebugText(0, buf); m_gui->drawAll(); m_videoDriver->endScene(); } m_device->drop(); delete m_eventReceiver; return 0; }
//! Test both the accuracy and speed of Irrlicht's strtol10() implementation. bool test_strtol(void) { bool accurate = true; accurate &= testCalculation_strtol("340282346638528859811704183484516925440"); accurate &= testCalculation_strtol("3402823466"); accurate &= testCalculation_strtol("3402823466e+29F"); accurate &= testCalculation_strtol("-340282346638528859811704183484516925440"); accurate &= testCalculation_strtol("-3402823466"); accurate &= testCalculation_strtol("-3402823466e+29F"); accurate &= testCalculation_strtol("402823466385288598117"); accurate &= testCalculation_strtol("402823466"); accurate &= testCalculation_strtol("402823466e+28F"); accurate &= testCalculation_strtol("402823466385288598117"); accurate &= testCalculation_strtol("-402823466"); accurate &= testCalculation_strtol("-402823466e+28F"); accurate &= testCalculation_strtol(".00234567"); accurate &= testCalculation_strtol("-234567"); accurate &= testCalculation_strtol("234567"); accurate &= testCalculation_strtol("-234567"); accurate &= testCalculation_strtol("1175494351"); accurate &= testCalculation_strtol("11754943512"); accurate &= testCalculation_strtol("11754943513"); accurate &= testCalculation_strtol("11754943514"); accurate &= testCalculation_strtol("-1175494351"); accurate &= testCalculation_strtol("123456789"); accurate &= testCalculation_strtol("-123456789"); accurate &= testCalculation_strtol("123456.789"); accurate &= testCalculation_strtol("-123456.789"); accurate &= testCalculation_strtol("-109446526"); if(!accurate) { logTestString("Calculation is not accurate, so the speed is irrelevant\n"); return false; } IrrlichtDevice* device = createDevice(video::EDT_NULL); if (!device) return false; ITimer* timer = device->getTimer(); const int ITERATIONS = 1000000; int i; s32 value; u32 then = timer->getRealTime(); for(i = 0; i < ITERATIONS; ++i) value = strtol("-3402823466", 0, 10); const u32 strtolTime = timer->getRealTime() - then; then += strtolTime; for(i = 0; i < ITERATIONS; ++i) value = strtol10("-3402823466"); const u32 strtol10Time = timer->getRealTime() - then; then += strtol10Time; for(i = 0; i < ITERATIONS; ++i) value = old_strtol10("-3402823466"); const u32 oldstrtol10Time = timer->getRealTime() - then; logTestString("Speed test\n strtol time = %d\n strtol10 time = %d\nold strtol10 time = %d\n", strtolTime, strtol10Time, oldstrtol10Time); device->closeDevice(); device->run(); device->drop(); if (strtol10Time > (1.2f*strtolTime)) { logTestString("The fast method is slower than strtol()\n"); return false; } return true; }
s32 main( s32 argc, c8** argv) { const c8* MY_TITLE = "CGUIPlot (c) 2013 by [email protected]"; video::E_DRIVER_TYPE DriverType = video::EDT_OPENGL; // we like to have some choice //DriverType = driverChoiceConsole(true); /// create NullDevice SIrrlichtCreationParameters params; params.DriverType = video::EDT_NULL; params.LoggingLevel = ELL_NONE; params.Fullscreen = false; IrrlichtDevice* nulldev = createDeviceEx( params ); if (nulldev) { video::IVideoModeList* videoModes = nulldev->getVideoModeList(); //params.WindowSize = videoModes->getDesktopResolution(); //params.WindowSize -= core::dimension2du(100,100); params.WindowSize = core::dimension2du(800,600); params.Bits = videoModes->getDesktopDepth(); nulldev->drop(); } else { printf("Could not create Null device\n"); exit(-1); } /// create Device params.LoggingLevel = ELL_INFORMATION; params.DriverType = DriverType; params.AntiAlias = video::EAAM_QUALITY; params.EventReceiver = 0; params.HighPrecisionFPU = true; params.Doublebuffer = true; params.Vsync = false; params.Fullscreen = false; // params.ZBufferBits = 32; // params.Stencilbuffer = true; // params.WithAlphaChannel = false; IrrlichtDevice* device = createDeviceEx( params ); if (!device) { printf("Could not create device\n"); exit(-2); } MyEventReceiver receiver( device ); gui::IGUIEnvironment* env = device->getGUIEnvironment(); video::IVideoDriver* driver = device->getVideoDriver(); core::dimension2du screen = driver->getScreenSize(); scene::ISceneManager* smgr = device->getSceneManager(); ITimer* timer = device->getTimer(); device->setResizable( true ); device->setWindowCaption( core::stringw( MY_TITLE ).c_str() ); //gui::IGUIFont* font = env->getBuiltInFont(); /// create some functions of time f(t) CSineOscillator<f32> vco_0(1, 0, 3); CSineOscillator<f32> vco_1(2, 0, 2); CSineOscillator<f32> vco_2(3, 0, 1); CRectangleOscillator<f32> vco_3(1, 0.1f, 0.4f, 2, -1); CSawOscillator<f32> vco_4(1, 0, 0.5f, -0.5f); CSawOscillator<f32> vco_5(3, 0.5f, 3, 0); CADSREnvelope<f32> adsr(1,3,0.7,2, CADSREnvelope<f32>::EMTT_LINEAR); /// create IGUIWindow as container for CGUIPlot gui::IGUIWindow* plotWindow = env->addWindow( core::recti( 100,100,screen.Width-100, screen.Height-100 ), false, L"CGUIPlot Window", env->getRootGUIElement(), -1); /// create CGUIPlot gui::CGUIPlotManager* plotMgr = new gui::CGUIPlotManager( env, plotWindow, -1, plotWindow->getClientRect()); gui::CGUIPlot* plot = plotMgr->addPlot( new gui::CGUIPlot( smgr, env, plotMgr, -1, plotMgr->getClientRect() ) ); // left, bottom, right, top plot->setZoomRect( core::rectf( -1,-3,10,3) ); plot->setDrawBackground( true ); plot->setBackgroundColor( video::SColor(128,255,255,255) ); scene::ISceneNode* smgrRoot = smgr->getRootSceneNode(); /// PolyLine { scene::ISceneNode* node = createPolyLine<f32>( smgr, smgrRoot, Functor_f32_f32(vco_0), -1, 10, 2048, video::SColor(255,255,0,0), 0.75f, 0xfcfc ); if (node) node->setDebugDataVisible( scene::EDS_BBOX ); plot->addShape( "VCO_0", node ); } /// PolyLine { scene::ISceneNode* node = createPolyLine<f32>( smgr, smgrRoot, Functor_f32_f32(vco_1), 0, 5, 2048, video::SColor(255,255,255,0), 1.5f, 0xdddd ); if (node) node->setDebugDataVisible( scene::EDS_BBOX ); plot->addShape( "VCO_1", node ); } /// PolyLine { scene::ISceneNode* node = createPolyLine<f32>( smgr, smgrRoot, Functor_f32_f32(vco_2), 0, 5, 2048, video::SColor(255,0,0,255), .5f, 0xffff ); if (node) node->setDebugDataVisible( scene::EDS_BBOX ); plot->addShape( "VCO_2", node ); } /// PolyLine { scene::ISceneNode* node = createPolyLine<f32>( smgr, smgrRoot, Functor_f32_f32(vco_3), 2, 8, 2048, video::SColor(255,255,0,255), 1.5f, 0xffff ); if (node) node->setDebugDataVisible( scene::EDS_BBOX ); plot->addShape( "VCO_3", node ); } /// PolyLine { scene::ISceneNode* node = createPolyLine<f32>( smgr, smgrRoot, Functor_f32_f32(vco_4), 0, 8, 1024, video::SColor(255,0,192,0), .5f, 0xffff ); if (node) node->setDebugDataVisible( scene::EDS_BBOX ); plot->addShape( "VCO_4", node ); } /// PolyLine [ADSR-curve] { scene::ISceneNode* node = createPolyLine<f32>( smgr, smgrRoot, Functor_f32_f32(adsr), 0, 8, 1024, video::SColor(255,192,0,192), .5f, 0xffff ); // if (node) node->setDebugDataVisible( scene::EDS_BBOX ); plot->addShape( "ADSR-Curve", node ); } /// [main loop] u32 timeLastWindowTitleUpate(0); u32 timeWaitWindowTitleUpate(500); while (device->run()) { /// Resize-Event if (screen != driver->getScreenSize() ) { screen = driver->getScreenSize(); scene::ICameraSceneNode* camera = smgr->getActiveCamera(); if (camera) { f32 aspect = (f32)screen.Width / (f32)screen.Height; camera->setAspectRatio( aspect ); } } /// if window is active ( can be minimized but still active ) if (device->isWindowActive()) { /// if window is active ( can be minimized but still active ) if (device->isWindowFocused()) { /// render all driver->beginScene( true, true, video::SColor(255,225,225,225) ); smgr->drawAll(); env->drawAll(); driver->endScene(); /// window-title update if ( timer->getRealTime() - timeLastWindowTitleUpate > timeWaitWindowTitleUpate ) { core::stringw txt = core::stringw( MY_TITLE ); txt += L" | fps( "; txt += driver->getFPS(); txt += L" ), poly( "; txt += driver->getPrimitiveCountDrawn(); txt += L" / "; txt += driver->getMaximalPrimitiveCount(); txt += L" ), "; // scene::ICameraSceneNode* cam = smgr->getActiveCamera(); // if (cam) // { // const core::vector3df& pos = cam->getAbsolutePosition(); // txt += L"cam( pos("; // txt += core::round32(pos.X); txt += L","; // txt += core::round32(pos.Y); txt += L","; // txt += core::round32(pos.Z); txt += L"), "; // // const core::vector3df& eye = cam->getTarget(); // txt += L"eye("; // txt += core::round32(eye.X); txt += L","; // txt += core::round32(eye.Y); txt += L","; // txt += core::round32(eye.Z); txt += L"), "; // txt += L"near("; // txt += cam->getNearValue(); // txt += L"), far("; // txt += core::round32(cam->getFarValue() ); txt += L")"; // txt += L" )"; // } device->setWindowCaption( txt.c_str() ); timeLastWindowTitleUpate = timer->getRealTime(); } } else { device->yield(); } } else { device->yield(); } } if (device) device->drop(); return 0; }
int main() { SDeviceContextSettings settings; settings.MultiSamplingCount = 1; settings.MultiSamplingQuality = 0; IApplication* device = createDevice(EDT_DIRECT3D11, SCREEN_WIDTH, SCREEN_HEIGHT, EWS_NONE, true, settings); IVideoDriver* driver = device->getVideoDriver(); ISceneManager* smgr = device->createSceneManager(); IMeshManager* meshManager = driver->getMeshManager(); IPipelineManager* pipelineManager = driver->getPipelineManager(); IResourceGroupManager* resourceGroupManager = driver->getResourceGroupManager(); resourceGroupManager->init("Resources.cfg"); ISimpleMesh* mesh = createWaterMesh(meshManager, "waterwave", 1000.0f, 1000.0f, 30, 30); IMeshNode* meshNode = smgr->addMeshNode(mesh, nullptr, nullptr); meshNode->setMaterialName("test/wave_material"); meshNode->setNeedCulling(false); IPipeline* pipeline = pipelineManager->get("test/wave_pipeline"); ILightNode* light = smgr->addPointLight(1, nullptr, false, XMFLOAT3(10.0f, 50.0f, -10.0f), 1000.0f); light->setSpecular(XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f)); light->setDiffuse(XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f)); light->setAttenuation(1.0f, 0.0f, 0.0f); // gTangentWorldMatrix XMVECTOR normal = XMVectorSet(0, 1.0f, 0, 0); XMVECTOR tangent = XMVectorSet(1.0f, 0, 0, 0); XMVECTOR B = XMVector3Cross(normal, tangent); XMMATRIX TBN = XMMATRIX(tangent, B, normal, XMVectorSet(0, 0, 0, 1.0f)); pipeline->setMatrix("gTangentWorldMatrix", TBN); ICameraNode* camera = smgr->addFpsCameraNode(1, nullptr, XMFLOAT3(0, 40.0f, -4.0f), XMFLOAT3(0, 40.0f, 0.0f)); camera->setFarZ(10000.0f); char caption[200]; ITimer* timer = device->getTimer(); timer->reset(); static float t1 = 0.0f; static float t2 = 0.0f; E_FILL_MODE fillMode = E_FILL_SOLID; /* SCompositorCreateParam param; param.Bloom.BlurPassCount = 3; param.Bloom.BrightnessThreshold = 0.85f; param.Bloom.BlurTexelDistance = 1.0f; param.Bloom.BlurTextureWidth = 400; param.Bloom.BlurTextureHeight = 300; ICompositor* bloom = smgr->createCompositor(ECT_BLOOM, param); smgr->addCompositor(bloom); */ while (device->run()) { const float clearColor[] = { 0.0f, 0.0f, 0.0f, 1.0f }; driver->beginScene(true, true, clearColor); float dt = timer->tick() * 0.001f; t1 += dt * 0.032f; t2 += dt * 0.02f; if (t1 > 1.0f) t1 -= 1.0f; if (t2 > 1.0f) t2 -= 1.0f; XMMATRIX texTransform1 = XMMatrixTranslation(t1, 0, 0); XMMATRIX texTransform2 = XMMatrixTranslation(0, t2, 0); pipeline->setMatrix("gTexTransform1", texTransform1); pipeline->setMatrix("gTexTransform2", texTransform2); updateCamera(camera, dt); smgr->update(dt); smgr->drawAll(); driver->endScene(); sprintf(caption, "FPS:%f", getFps(dt)); device->setWindowCaption(caption); } device->drop(); return 0; }
bool Application::run(){ if(!device){ return false; } Simulation sim; sim.Init(); //std::vector<Boid*> boids; int nbLead = 3; int nbUnit = 20; this->CreateBoids(nbLead, nbUnit, 10, sim, NULL,0,0,0); //this->SetCameraTarget(boids[0]); /*this->CreateBoids(150, &boids, &sim, Vector3(0.f, 0.f, 0.f)); this->CreateBoids(50, &boids, &sim, Vector3(40.f, 0.f, 0.f));*/ ITimer* irrTimer = device->getTimer(); u32 TimeStamp = irrTimer->getTime(); irr::u32 DeltaTime = 0; while(device->run()){ DeltaTime = irrTimer->getTime() - TimeStamp; TimeStamp = irrTimer->getTime(); sim.Update((float)DeltaTime); vector<Unit*> list = sim.GetAllUnits(); for(unsigned int i = 0; i < list.size(); i++){ Vector3 pos = list[i]->m_position; ((Boid*)list[i]->GetData())->setOrientation(core::vector3df(pos.X, pos.Y, pos.Z)); ((Boid*)list[i]->GetData())->setPosition(core::vector3df(pos.X, pos.Y, pos.Z)); } driver->beginScene(); smgr->drawAll(); irr::video::SMaterial m; m.Lighting=false; driver->setMaterial(m); driver->setTransform(video::ETS_WORLD, core::matrix4()); m_currentTime += DeltaTime; if(m_currentTime >= m_lastTime) { m_lastTime = TimeStamp + 10000 / (nbUnit * nbLead); if(list.size() > nbLead) { int r = rand()%list.size(); ps->setPosition(irr::core::vector3df(list[r]->m_position.X, list[r]->m_position.Y, list[r]->m_position.Z)); } else { ps->setEmitter(0); } } for(unsigned int i = 0; i < list.size(); i++){ if(list[i]->m_lead == NULL && list[i]->m_target != NULL) { Vector3 pos = list[i]->m_position; Vector3 posTarget = list[i]->m_target->m_position; driver->draw3DLine(irr::core::vector3df(pos.X,pos.Y,pos.Z),irr::core::vector3df(posTarget.X,posTarget.Y,posTarget.Z), ((Boid*)list[i]->GetData())->getColor()); } auto projectiles = list[i]->GetProjectileList(); for(unsigned int j = 0; j < projectiles.size(); j++){ Vector3 pos = projectiles[j].m_position; Vector3 posTarget = projectiles[j].m_position + (projectiles[j].m_velocity * projectiles[j].m_speed * 20.f); driver->draw3DLine(irr::core::vector3df(pos.X,pos.Y,pos.Z),irr::core::vector3df(posTarget.X,posTarget.Y,posTarget.Z), ((Boid*)list[i]->GetData())->getColor()); } } if(font) { std::vector<Unit*> rootUnits = sim.GetRootUnits(); for(unsigned int i = 0; i < rootUnits.size(); i++) { wchar_t str[1000]; swprintf(str, L"LEADER %d", i + 1); video::SColor color = ((Boid*)rootUnits.at(i)->GetData())->getColor(); font->draw(str, core::rect<s32>(20, (20 + 40)*i + 20,200,50), color); swprintf(str, L"Units: %d", rootUnits.at(i)->m_units.size() + 1); font->draw(str, core::rect<s32>(45, (20 + 40)*i + 40,200,50), color); } } driver->endScene(); } /*for(unsigned int i = 0; i < boids.size(); i++){ delete boids[i]; }*/ sim.Clear(); return true; }
int main() { const int nRobots = 2; //given robot numbers will be controlled by humans vector<int> humanBrainIds; //humanBrainIds.push_back(1); //humanBrainIds.push_back(0); //-- device ------------------------------------------------------------// IrrlichtDevice* device; device = createDevice( EDT_OPENGL, //driverType windowSize, 16, //bits false, false, //stencilbuffer false, //vsync NULL //receiver ); //advanced device params //SIrrlichtCreationParameters params; //params.DeviceType = EIDT_CONSOLE; //params.DriverType = EDT_OPENGL; //params.WindowSize = windowSize; //device = createDeviceEx(params); if (device == 0) return EXIT_FAILURE; // could not create selected driver. IVideoDriver* driver = device->getVideoDriver(); ISceneManager* smgr = device->getSceneManager(); //-- lights ------------------------------------------------------------// //ambient light //smgr->setAmbientLight( SColorf(1.0f,1.0f,1.0f,1.0f) ); //smgr->setAmbientLight( SColorf(.3f,.3f,.3f,1.0f) ); //diffusive light SLight light_data; light_data.AmbientColor = SColorf(.3,.3,.3); //light_data.Attenuation = vector3df(.3,.3,.3); //Attenuation cte, linear quadratic TODO ?? light_data.DiffuseColor = SColorf(.0,.0,.0); light_data.SpecularColor = SColorf(.0,.0,.0); light_data.CastShadows = true; light_data.Radius = 100.0f; light_data.Type = ELT_DIRECTIONAL; //ELT_POINT point light, it has a position in space and radiates light in all directions //ELT_SPOT spot light, it has a position in space, a direction, and a limited cone of influence //ELT_DIRECTIONAL directional light, coming from a direction from an infinite distance ILightSceneNode* light = smgr->addLightSceneNode(0, core::vector3df(.5f,.0f,.5f)); light->setLightData(light_data); //-- objects ------------------------------------------------------------// IMesh* mesh; ISceneNode * node; float HEIGHT=1000.f, WIDTH=1.f; //height between center/sky == height bottom/center //large so that scene looks 2d on interactive test mode. //on automatic mode, only middle pixel row is taken, so this does not matter //outter boundary //square node = smgr->addCubeSceneNode( 2.f*WIDTH, // width 0, // parent -1, // id vector3df(0, 0, 0), // center vector3df(0, 0, 0), // rotation vector3df(1.0f, HEIGHT, 1.0f)*-1.f // scale. *-1 turns it inside out. to use both faces make two cubes. ); //circle //mesh = smgr->getGeometryCreator()->createCylinderMesh( //1.f, //radius //1., //length //50, //tesselation //SColor(0,0,0,255), //color //false, //closeTop //0.f //oblique //); //node = smgr->addMeshSceneNode( //mesh, //0, //ISceneNode * parent //-1, //s32 id //vector3df(0, -HEIGHT, 0), //const core::vector3df & position //vector3df(0, 0, 0), //const core::vector3df & rotation //vector3df(1.0f, 2.f*HEIGHT, 1.0f) //const core::vector3df & scale //); node->getMaterial(0).AmbientColor.set(0,0,0,0); node->getMaterial(0).DiffuseColor.set(0,0,0,0); //node->getMaterial(0).SpecularColor.set(255,255,255,255); //node->getMaterial(0).Shininess = 20.0f; //node->getMaterial(0).EmissiveColor.set(0,0,0,0); //node->setMaterialFlag(EMF_WIREFRAME,true); //wireframe only //left cube node = smgr->addCubeSceneNode( 0.2, // width 0, // parent -1, // id vector3df(-.3, 0, 0), // center vector3df(0, 0, 0), // rotation vector3df(1.0f, HEIGHT, 1.0f) // scale ); node->getMaterial(0).AmbientColor.set(0,255,0,0); node->getMaterial(0).DiffuseColor.set(0,255,0,0); //right cube node = smgr->addCubeSceneNode( .2f, // width 0, // parent -1, // id vector3df(.3, 0, 0), // center vector3df(0, 0, 0), // rotation vector3df(1.0f, HEIGHT, 1.0f) // scale ); node->getMaterial(0).AmbientColor.set(0,0,255,0); node->getMaterial(0).DiffuseColor.set(0,0,255,0); //cylinder //mesh = smgr->getGeometryCreator()->createCylinderMesh( //.1f, //radius //1., //length //50, //tesselation //SColor(), //color //false, //closeTop //0.f //oblique //); //node = smgr->addMeshSceneNode( //mesh, //0, //ISceneNode * parent //-1, //s32 id //vector3df(0, -HEIGHT, 0), //const core::vector3df & position //vector3df(0, 0, 0), //const core::vector3df & rotation //vector3df(1.0f, 2.*HEIGHT, 1.0f) //const core::vector3df & scale //); //node->getMaterial(0).AmbientColor.set(0,0,0,255); //node->getMaterial(0).DiffuseColor.set(0,0,0,255); //sphere //node = smgr->addSphereSceneNode( //0.1, // radius //50, // poly count //0, // parent //FruitID, // id //vector3df(0, 0, 0), // center //vector3df(0, 0, 0), // rotation //vector3df(1.0f, 1.0f, 1.0f) // scale //); //node->getMaterial(0).AmbientColor.set(0,0,0,255); //node->getMaterial(0).DiffuseColor.set(0,0,0,255); //node->getMaterial(0).Lighting = true; //-- collision ------------------------------------------------------------// /* Put everything we want to do collision checking with inside the meta selector. */ IMetaTriangleSelector * meta = smgr->createMetaTriangleSelector(); array<ISceneNode *> nodes; smgr->getSceneNodesFromType(ESNT_ANY, nodes); // Find all nodes for (u32 i=0; i < nodes.size(); ++i) { ISceneNode * node = nodes[i]; ITriangleSelector * selector = 0; switch(node->getType()) { case ESNT_CUBE: case ESNT_ANIMATED_MESH: // Because the selector won't animate with the mesh, // and is only being used for camera collision, we'll just use an approximate // bounding box instead of ((IAnimatedMeshSceneNode*)node)->getMesh(0) selector = smgr->createTriangleSelectorFromBoundingBox(node); break; case ESNT_MESH: case ESNT_SPHERE: // Derived from IMeshSceneNode selector = smgr->createTriangleSelector(((IMeshSceneNode*)node)->getMesh(), node); break; case ESNT_TERRAIN: selector = smgr->createTerrainTriangleSelector((ITerrainSceneNode*)node); break; case ESNT_OCTREE: selector = smgr->createOctreeTriangleSelector(((IMeshSceneNode*)node)->getMesh(), node); break; default: // Don't create a selector for this node type break; } if(selector) { // Add it to the meta selector, which will take a reference to it meta->addTriangleSelector(selector); // And drop my reference to it, so that the meta selector owns it. selector->drop(); } } //-- robots ------------------------------------------------------------// //create robots Fly2D::Brain* brains[nRobots]; //all to a default type //for ( int i=0; i<nRobots; i++ ) //{ //brains[i] = new Fly2D::BrainForward; ////brains[i] = new Fly2D::BrainCircle(); //} brains[0] = new Fly2D::BrainForward; brains[1] = new Fly2D::BrainForward; //decide human control vector<Fly2D::BrainHuman*> hBrains; for ( vector<int>::iterator i = humanBrainIds.begin(); i != humanBrainIds.end(); ++i ) { if ( *i > nRobots ) { cerr << "no such robot: " << *i << endl; exit(EXIT_FAILURE); } delete brains[*i]; Fly2D::BrainHuman* hBrain = new Fly2D::BrainHuman; brains[*i] = hBrain; hBrains.push_back(hBrain); } Fly2D::ReceiverHuman hReceiver = Fly2D::ReceiverHuman( hBrains ); device->setEventReceiver( &hReceiver ); Robot* robots[nRobots]; robots[0] = new Fly2D::Robot( *device, *meta, *brains[0], vector3df(0,0,-0.5f), vector3df(0,0, 0.5f), 0.01 ); robots[1] = new Fly2D::Robot( *device, *meta, *brains[1], vector3df(0,0,0.5f), vector3df(0,0, -0.5f), 0.01 ); meta->drop(); // As soon as we're done with the selector, drop it. //-- run ------------------------------------------------------------// //TEST vector3df oldpos, oldtarget; //END TEST int nFrames = 0; ITimer* timer = device->getTimer(); int t0 = timer->getTime(); int w = driver->getScreenSize().Width; int h = driver->getScreenSize().Height; int dh = h/nRobots; int observeRobot = 0; while(device->run()) { //if (device->isWindowActive()) //only work if window has focus. //draw driver->setViewPort(rect<s32>(0,0,w,h)); driver->beginScene(true,true,0); for(int i=0; i<nRobots; i++) { driver->setViewPort(rect<s32>(0,dh*i,w,dh*(i+1))); //only part of window gets drawn into smgr->setActiveCamera(robots[i]->camera); smgr->drawAll(); //draws on window scene of active camera robots[i]->update(); } driver->endScene(); //TEST //if //( //robots[observeRobot].getPosition() != oldpos //|| robots[observeRobot].getTarget() != oldtarget //) //oldpos = robots[observeRobot].getPosition(); //oldtarget = robots[observeRobot].getTarget(); cout << robots[observeRobot]->str(); //FPS info //cout << "frame no:" << endl << nFrames << endl;; //cout << "average fps:" << endl << 1000*nFrames/(float)(timer->getTime()-t0) << endl; //nFrames++; cout << "fps:" << endl << driver->getFPS() << endl; //END TEST } device->drop(); return 0; }
/* Update one frame */ bool CApp::update() { using namespace irr; video::IVideoDriver* videoDriver = Device->getVideoDriver(); if ( !Device->run() ) return false; // Figure out delta time since last frame ITimer * timer = Device->getTimer(); u32 newTick = timer->getRealTime(); f32 deltaTime = RealTimeTick > 0 ? f32(newTick-RealTimeTick)/1000.0 : 0.f; // in seconds RealTimeTick = newTick; if ( Device->isWindowActive() || Config.RenderInBackground ) { gui::IGUIEnvironment* guiEnv = Device->getGUIEnvironment(); scene::ISceneManager* smgr = Device->getSceneManager(); gui::IGUISkin * skin = guiEnv->getSkin(); // update our controls MeshMaterialControl.update(SceneNode, SceneNode2T, SceneNodeTangents); LightControl.update(NodeLight); // Update vertices if ( ControlVertexColors->isDirty() ) { MeshManipulator->setVertexColors (SceneNode->getMesh(), ControlVertexColors->getColor()); MeshManipulator->setVertexColors (SceneNode2T->getMesh(), ControlVertexColors->getColor()); MeshManipulator->setVertexColors (SceneNodeTangents->getMesh(), ControlVertexColors->getColor()); ControlVertexColors->resetDirty(); } // update ambient light settings if ( GlobalAmbient->isDirty() ) { smgr->setAmbientLight( GlobalAmbient->getColor() ); GlobalAmbient->resetDirty(); } // Let the user move the light around const float zoomSpeed = 10.f * deltaTime; const float rotationSpeed = 100.f * deltaTime; if ( KeysPressed[KEY_PLUS] || KeysPressed[KEY_ADD]) ZoomOut(NodeLight, zoomSpeed); if ( KeysPressed[KEY_MINUS] || KeysPressed[KEY_SUBTRACT]) ZoomOut(NodeLight, -zoomSpeed); if ( KeysPressed[KEY_RIGHT]) RotateHorizontal(NodeLight, rotationSpeed); if ( KeysPressed[KEY_LEFT]) RotateHorizontal(NodeLight, -rotationSpeed); UpdateRotationAxis(NodeLight, LightRotationAxis); if ( KeysPressed[KEY_UP]) RotateAroundAxis(NodeLight, rotationSpeed, LightRotationAxis); if ( KeysPressed[KEY_DOWN]) RotateAroundAxis(NodeLight, -rotationSpeed, LightRotationAxis); // Let the user move the camera around if (MousePressed) { gui::ICursorControl* cursorControl = Device->getCursorControl(); const core::position2d<s32>& mousePos = cursorControl->getPosition (); RotateHorizontal(Camera, rotationSpeed * (MouseStart.X - mousePos.X)); RotateAroundAxis(Camera, rotationSpeed * (mousePos.Y - MouseStart.Y), CameraRotationAxis); MouseStart = mousePos; } // draw everything video::SColor bkColor( skin->getColor(gui::EGDC_APP_WORKSPACE) ); videoDriver->beginScene(true, true, bkColor); smgr->drawAll(); guiEnv->drawAll(); if ( MeshMaterialControl.isLightingEnabled() ) { // draw a line from the light to the target video::SMaterial lineMaterial; lineMaterial.Lighting = false; videoDriver->setMaterial(lineMaterial); videoDriver->setTransform(video::ETS_WORLD, core::IdentityMatrix); videoDriver->draw3DLine(NodeLight->getAbsolutePosition(), SceneNode->getAbsolutePosition()); } videoDriver->endScene(); } // be nice Device->sleep( 5 ); return true; }
int _tmain(int argc, _TCHAR* argv[]) { SDeviceContextSettings settings; settings.MultiSamplingCount = 4; settings.MultiSamplingQuality = 32; IDevice* device = gf::createDevice(EDT_DIRECT3D11, SCREEN_WIDTH, SCREEN_HEIGHT, EWS_NONE, true, settings); IVideoDriver* driver = device->getVideoDriver(); math::SAxisAlignedBox aabb; aabb.Center = XMFLOAT3(0, 0.0f, 0); aabb.Extents = XMFLOAT3(3000.0f, 1000.0f, 3000.0f); ISceneManager* smgr = device->createSceneManager(aabb); IMeshManager* meshManager = driver->getMeshManager(); IMaterialManager* materialManager = driver->getMaterialManager(); ITextureManager* textureManager = driver->getTextureManager(); IResourceGroupManager* resourceGroupManager = driver->getResourceGroupManager(); resourceGroupManager->init("Resources.cfg"); ILightNode* light = smgr->addDirectionalLight(1, nullptr, XMFLOAT3(3.0f, -2.0f, 1.5f)); light->setSpecular(XMFLOAT4(1.0f, 1.0f, 1.0f, 32.0f)); light->setDiffuse(XMFLOAT4(0.4f, 0.4f, 0.4f, 1.0f)); light->enableShadow(true); ICameraNode* camera = smgr->addFpsCameraNode(1, nullptr, XMFLOAT3(0, 30.0f, -4.0f), XMFLOAT3(0, 30.0f, 0.0f), XMFLOAT3(0, 1.0f, 0), true); camera->setShadowRange(200.0f); buildGrassLand(smgr); ISimpleMesh* groundMesh = meshManager->createPlaneMesh("ground", GROUND_SIZE, GROUND_SIZE, 50, 50, 10.0f, 10.0f); IMeshNode* groundNode = smgr->addMeshNode(groundMesh, nullptr, nullptr, false); groundNode->setMaterialName("ground_material"); ITextureCube* skyTexture = textureManager->loadCubeTexture("skybox1.dds"); smgr->setSkyDome(skyTexture); ITimer* timer = device->getTimer(); timer->reset(); char caption[200]; while (device->run()) { const float clearColor[] = { 0.0f, 0.0f, 0.0f, 1.0f }; driver->beginScene(true, true, clearColor); f32 dt = timer->tick(); updateCamera(camera, dt); g_grassLand->update(dt); smgr->update(dt); smgr->drawAll(); driver->endScene(); u32 num = smgr->getRenderedMeshNum(); sprintf(caption, "FPS:%f num:%d", getFps(dt), num); device->setWindowCaption(caption); } smgr->destroy(); device->drop(); return 0; }
int main() { // Event Receiver // ====================================================== MyEventReceiver receiver; // get Screen resolution // =============================================== //create a NULL device to detect screen resolution IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL); core::dimension2d<u32> deskRes = nulldevice->getVideoModeList()->getDesktopResolution(); nulldevice->drop(); // Create device // ======================================================= IrrlichtDevice *device; //1366, 768 //1024, 600 int FullScreen = 1; if (FullScreen == 1) { device = createDevice(video::EDT_DIRECT3D9, deskRes, 32, true, false, true, &receiver); } else { device = createDevice(video::EDT_DIRECT3D9, core::dimension2d<u32>(800, 600), 32, false, false, true, &receiver); } // Get a pointers // ====================================================== video::IVideoDriver* driver = device->getVideoDriver(); scene::ISceneManager* smgr = device->getSceneManager(); gui::IGUIEnvironment* guienv = device->getGUIEnvironment(); // Disable mip maps // ===================================================== //driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false); // Image // ================================================================ video::ITexture* controlsPic = driver->getTexture("./media/Controls.png"); video::ITexture* irrlichtLogo = driver->getTexture("./media/irrlichtlogo2.png"); // Terrain // ============================================================== scene::ITerrainSceneNode* terrain = smgr->addTerrainSceneNode("./media/heightmap3.jpg", 0, -1, core::vector3df(0, 0, 0), core::vector3df(0, 0, 0), core::vector3df(1, 1, 1)); if (terrain) { terrain->setID(NotPickable); terrain->setScale(core::vector3df(1.0f, 0.5f, 1.0f)); //terrain->setPosition(core::vector3df(0, 0, 0)); terrain->setMaterialFlag(video::EMF_LIGHTING, false); terrain->setMaterialTexture(0, driver->getTexture("./media/terrainTexture2.jpg")); } // Box // ================================================================== scene::ISceneNode* box = smgr->addCubeSceneNode(); box->setMaterialTexture(0, driver->getTexture("./media/redPixel.bmp")); box->setMaterialFlag(video::EMF_LIGHTING, false); box->setScale(core::vector3df(5, 5, 5)); box->setPosition(core::vector3df(-500, 1000, -500)); //box->setScale(core::vector3df(1, 2, 1)); // light // ================================================================ scene::ILightSceneNode* lightSun1 = smgr->addLightSceneNode(0, core::vector3df(812, terrain->getHeight(812, 812) + 812, 812), video::SColorf(1, 1, 0.94f, 1), 5000.0f); // ========================================================================= device->getCursorControl()->setVisible(false); // display frames per second // ============================================ int fps; int lastFPS = -1; gui::IGUIStaticText* guiText = guienv->addStaticText(L"Hello World! This is the Irrlicht Software renderer!", core::rect<s32>(10, 200, 100, 222), true); core::stringw str; // Frame rate independence // ============================================== u32 then = device->getTimer()->getTime(); u32 now; f32 tempT; f32 deltaTime; ITimer* Timer = device->getTimer(); // Action // =============================================================== Action Act(&receiver, device, terrain, &deltaTime); while (device->run()) { if (device->isWindowActive()) { // Frame rate independence // ========================================== now = Timer->getTime(); tempT = (f32)(now - then); deltaTime = (f32)(((tempT) < 60) ? tempT : 60); then = now; // ===================================================================== Act.update(); // Draw Scene // ======================================================= driver->beginScene(true, true, video::SColor(255, 100, 101, 140)); smgr->drawAll(); guienv->drawAll(); driver->draw2DImage(controlsPic, core::rect<s32>(10, 10, 200, 200), core::rect<s32>(0, 0, 256, 256), 0, 0, true); driver->draw2DImage(irrlichtLogo, core::rect<s32>(1100, 10, 1250, 150), core::rect<s32>(0, 0, 128, 128), 0, 0, true); // Selection box (must be implemented elsewhere of course /*driver->draw2DRectangle(video::SColor(50, 3, 67, 67), core::rect<s32>(512, 512, 680, 680)); driver->draw2DLine(core::position2d<s32>(512, 512), core::position2d<s32>(512, 680), video::SColor(255, 11, 208, 194)); driver->draw2DLine(core::position2d<s32>(512, 680), core::position2d<s32>(680, 680), video::SColor(255, 11, 208, 194)); driver->draw2DLine(core::position2d<s32>(680, 680), core::position2d<s32>(680, 512), video::SColor(255, 11, 208, 194)); driver->draw2DLine(core::position2d<s32>(680, 512), core::position2d<s32>(512, 512), video::SColor(255, 11, 208, 194));*/ Act.DrawCursor(); driver->endScene(); // Type FPS //========================================================== fps = driver->getFPS(); if (lastFPS != fps) { str = L"["; str += driver->getName(); str += "] FPS:"; str += fps; guiText->setText(str.c_str()); lastFPS = fps; } } else device->yield(); } // Drop Device //=========================================================== device->drop(); return 0; }
int main() { //int avg = 2 * 90 + 3 * 88 + 4 * 87 + 3 * 84 + 4 * 92 + 2 * 93 + 2 * 83 + 2 * 80 + 2 * 95; //std::cout << "Avg : " << avg << std::endl; SDeviceContextSettings settings; settings.MultiSamplingCount = 4; settings.MultiSamplingQuality = 32; IDevice* device = createDevice(EDT_DIRECT3D11, 800, 600, EWS_NONE, true, settings); IVideoDriver* driver = device->getVideoDriver(); ISceneManager* smgr = device->getSceneManager(); IMeshManager* meshManager = driver->getMeshManager(); IMaterialManager* materialManager = driver->getMaterialManager(); IResourceGroupManager* resourceGroupManager = driver->getResourceGroupManager(); resourceGroupManager->init("Resources.cfg"); resourceGroupManager->loadResourceGroup("General"); ISimpleMesh* cubeMesh = meshManager->createCubeMesh("cube1"); IMeshNode* cubeMeshNode = smgr->addMeshNode(cubeMesh, nullptr, nullptr, XMFLOAT3(0, 3.0f, 0)); cubeMeshNode->setMaterialName("test/material01"); //cubeMeshNode->remove(); ISimpleMesh* planeMesh = meshManager->createPlaneMesh("plane1", 10.0, 10.0f, 50, 50, 10.0f, 10.0f); IMeshNode* planeMeshNode = smgr->addMeshNode(planeMesh, nullptr); planeMeshNode->setMaterialName("test/ground_material"); IAnimatedMesh* animMesh = meshManager->getAnimatedMesh("lxq.mesh"); IAnimatedMeshNode* animNode = smgr->addAnimatedMeshNode(animMesh); animNode->scale(0.02f, 0.02f, 0.02f); IModelMesh* heroMesh = meshManager->getModelMesh("hero.mesh"); IMeshNode* heroNode = smgr->addModelMeshNode(heroMesh); heroNode->scale(0.01f, 0.01f, 0.01f); heroNode->translate(2.0f, 0.5f, 0); // create sampler state SSamplerDesc samplerDesc; samplerDesc.Filter = ESF_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = EAM_WRAP; samplerDesc.AddressV = EAM_WRAP; samplerDesc.AddressW = EAM_WRAP; ISampler* sampler = driver->getSamplerManager()->create(std::string("sampler1"), samplerDesc); IPipeline* pipeline = driver->getPipelineManager()->get("test/pipeline01"); //pipeline->setSampler(std::string("sampleType"), sampler); ILightNode* light = smgr->addLightNode(1); light->setType(ELT_POINT); light->setAmbient(XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f)); light->setPosition(2.0f, 5.0f, -3.0f); light->setSpecular(XMFLOAT4(1.0f, 1.0f, 1.0f, 32.0f)); light->setDiffuse(XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f)); light->setAttenuation(1.0f, 0.0f, 0.0f); light->setRange(100.0f); materialManager->destroy(std::string("test/material02")); //ICameraNode* camera = smgr->addFpsCameraNode(1, nullptr, XMFLOAT3(0, 1.0f, -4.0f), XMFLOAT3(0, 1.0f, 0.0f)); ICameraNode* camera = smgr->addFpsCameraNode(1, nullptr, XMFLOAT3(0, 1.0f, -4.0f), XMFLOAT3(0, 1.0f, 0.0f)); f32 rotx = 0; f32 roty = 0; f32 rotz = 0; char caption[200]; //FILE* fp = fopen("log.txt", "w"); ITimer* timer = device->createTimer(); timer->reset(); while (device->run()) { const float clearColor[] = { 0.0f, 0.0f, 0.0f, 1.0f }; driver->beginScene(true, true, clearColor); float dt = timer->tick(); rotx += dt * 2.0f; roty += dt * 1.0f; rotz += dt * 0.5f; if (rotx > XM_2PI) rotx -= XM_2PI; if (roty > XM_2PI) roty -= XM_2PI; if (rotz > XM_2PI) rotz -= XM_2PI; XMMATRIX Mx = XMMatrixRotationX(rotx); XMMATRIX My = XMMatrixRotationY(roty); XMMATRIX Mz = XMMatrixRotationZ(rotz); XMMATRIX rotM = Mx * My * Mz; cubeMeshNode->setOrientation(rotM); // heroNode->yaw(dt); animNode->addTime(dt * 3000.0f); updateCamera(camera, dt); // std::cout << dt << std::endl; smgr->drawAll(); driver->endScene(); sprintf(caption, "FPS:%f", getFps(dt)); device->setWindowCaption(caption); } device->drop(); return 0; }
void clear() { _frameStartTimer->start(); delete _orderedRenderables; _orderedRenderables = NULL; }
ITimer* CWin32Device::createTimer() const { ITimer* timer = new CWin32Timer; timer->reset(); return timer; }
// load a file if we recognize the type. DWORD CXMLWorldLoader::OnLoadWorldFile(DWORD size, void *params) { CHashString oldVersion = _T(""); CREATEOBJECTPARAMS cop; INITOBJECTPARAMS iop; SERIALIZEOBJECTPARAMS sop; DWORD retVal; IXMLArchive *Archive = NULL; DWORD currNode = 0; LOADINGUPDATEPARAMS pbp; VERIFY_MESSAGE_SIZE(size, sizeof(TCHAR *)); TCHAR *pFileName = (TCHAR *)params; // use both a hashstring and a pointer so that the first iteration of the loop // will pass SetParentName a NULL instead of an address of a hashstring // hashed to "" CHashString hszParentType(_T("CWorld")); CHashString hszParentName(_T("World")); CHashString hszName(_T("")); CHashString hszTypeName(_T("")); CHashString streamType(_T("File")); // delete previous world root DELETEOBJECTPARAMS dop; dop.name = &hszParentName; static DWORD msgHash_DeleteObject = CHashString(_T("DeleteObject")).GetUniqueID(); EngineGetToolBox()->SendMessage(msgHash_DeleteObject, sizeof(dop), &dop ); // delete is ok to fail if no world has been created yet // create new world root cop.name = &hszParentName; cop.parentName = NULL; cop.typeName = &hszParentType; static DWORD msgHash_CreateObject = CHashString(_T("CreateObject")).GetUniqueID(); DWORD returnValue = EngineGetToolBox()->SendMessage(msgHash_CreateObject, sizeof(cop), &cop ); if (returnValue != MSG_HANDLED) { EngineGetToolBox()->Log(LOGERROR, _T("Failed to create World Root Object\n")); return MSG_ERROR; } CREATEARCHIVE ca; ca.streamData = (void *)pFileName; ca.mode = STREAM_MODE_READ; ca.streamType = &streamType; #ifdef USEXMLFILESTREAMS // call the Archive factory to create an XML archive static DWORD msgHash_CreateXMLArchiveStream = CHashString(_T("CreateXMLArchiveStream")).GetUniqueID(); if (retVal = m_ToolBox->SendMessage(msgHash_CreateXMLArchiveStream, sizeof(CREATEARCHIVE), &ca) != MSG_HANDLED) #else // call the Archive factory to create an XML archive static DWORD msgHash_CreateXMLArchive = CHashString(_T("CreateXMLArchive")).GetUniqueID(); if (retVal = m_ToolBox->SendMessage(msgHash_CreateXMLArchive, sizeof(CREATEARCHIVE), &ca) != MSG_HANDLED) #endif { return retVal; } Archive = dynamic_cast<IXMLArchive *>(ca.archive); DWORD numNodes = Archive->GetNumberOfNodes(); // Deteriminte World Version int iWorldNumAttrib = Archive->GetNumAttributes(); StdString szNodeName; Archive->GetNode(szNodeName); pbp.currentPosition = Archive->GetCurrentNodePosition(); pbp.totalSize = numNodes; // update progress bar static DWORD msgHash_LoadingUpdate = CHashString(_T("LoadingUpdate")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_LoadingUpdate, sizeof(LOADINGUPDATEPARAMS), &pbp); // must start with <World> if (szNodeName != _T("CWorld")) { EngineGetToolBox()->SetErrorValue(WARN_INVALID_FILE); EngineGetToolBox()->Log(LOGWARNING, _T("Invalid world file %s\n"), pFileName); Archive->Close(); return MSG_ERROR; } // Version 1.0 if( iWorldNumAttrib == 1 ) { // read the name of the world StdString szName; Archive->Read( szName, _T("Name") ); m_WorldFileVersion = 1.0f; static DWORD msgHash_GetFileVersion = CHashString(_T("GetFileVersion")).GetUniqueID(); DWORD retval = m_ToolBox->SendMessage(msgHash_GetFileVersion, sizeof(IHashString), &oldVersion); if (retval != MSG_HANDLED) { m_ToolBox->Log(LOGERROR, _T("Could not get world version!")); return MSG_ERROR; } CHashString hszNewVersion = _T("1.0"); static DWORD msgHash_SetFileVersion = CHashString(_T("SetFileVersion")).GetUniqueID(); retval = m_ToolBox->SendMessage(msgHash_SetFileVersion, sizeof(IHashString), &hszNewVersion); if (retval != MSG_HANDLED) { m_ToolBox->Log(LOGERROR, _T("Could not set world version!")); return MSG_ERROR; } } // Version 1.5 else if( iWorldNumAttrib == 2 ) { StdString szName; Archive->Read( szName, _T("Name") ); float fileVersion = 0; Archive->Read( m_WorldFileVersion, _T("Version") ); static DWORD msgHash_GetFileVersion = CHashString(_T("GetFileVersion")).GetUniqueID(); DWORD retval = m_ToolBox->SendMessage(msgHash_GetFileVersion, sizeof(IHashString), &oldVersion); if (retval != MSG_HANDLED) { m_ToolBox->Log(LOGERROR, _T("Could not get world version!")); return MSG_ERROR; } TCHAR buf[50]; _stprintf(buf, "%.1f", m_WorldFileVersion); CHashString hszNewVersion(buf); static DWORD msgHash_SetFileVersion = CHashString(_T("SetFileVersion")).GetUniqueID(); retval = m_ToolBox->SendMessage(msgHash_SetFileVersion, sizeof(IHashString), &hszNewVersion); if (retval != MSG_HANDLED) { m_ToolBox->Log(LOGERROR, _T("Could not set world version!")); return MSG_ERROR; } } // Unknown Version else { EngineGetToolBox()->SetErrorValue(WARN_INVALID_FILE); EngineGetToolBox()->Log(LOGWARNING, _T("Invalid world file %s\n"), pFileName); Archive->Close(); static DWORD msgHash_SetFileVersion = CHashString(_T("SetFileVersion")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SetFileVersion, sizeof(IHashString), &oldVersion); return MSG_ERROR; } // failure checks bool componentFailed = false; int failedDepth = 0; float secondsPerFrame = 1 / m_fLoadingUpdateFPS; ITimer *timer = EngineGetToolBox()->GetTimer(); float lastLoadTime = timer->GetRealTime(); float elapsedTime = 0.0f; while (Archive->GetNode(szNodeName)) { int currDepth = Archive->GetDepth(); if (componentFailed == true) { // current node is child of failed if (currDepth > failedDepth) { continue; } // if sibling or uncle, reset comp failed flag else { componentFailed = false; } } hszTypeName.Init( szNodeName.c_str() ); StdString parentName; StdString parentType; StdString childType; Archive->GotoParentNode( parentType ); Archive->Read( parentName, _T("Name") ); if ( parentName != _T("") ) { hszParentName = parentName; } Archive->ReturnToChildNode( childType ); if( hszTypeName.GetString() != childType ) { assert( hszTypeName.GetString() == childType ); static DWORD msgHash_SetFileVersion = CHashString(_T("SetFileVersion")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SetFileVersion, sizeof(IHashString), &oldVersion); return MSG_ERROR; } //parentName = Archive->GetParentName(); StdString szName; Archive->Read( szName, _T("Name") ); hszName.Init( szName.c_str() ); cop.parentName = &hszParentName; cop.typeName = &hszTypeName; cop.name = &hszName; static DWORD msgHash_CreateObject = CHashString(_T("CreateObject")).GetUniqueID(); DWORD retval = m_ToolBox->SendMessage(msgHash_CreateObject, sizeof(CREATEOBJECTPARAMS), &cop, NULL, NULL); if (retval != MSG_HANDLED) { m_ToolBox->Log(LOGINFORMATION, _T("World loader: could not create component; skipping children!\n")); componentFailed = true; failedDepth = Archive->GetDepth(); continue; } // 1.0 -> 1.5 Readjusted scale and position on object by 1000/898 if( m_WorldFileVersion == 1.0 ) { float fConvert = 1000.0f/898.0f; if( hszTypeName.GetUniqueID() == CHashString(_T("CV3ORenderObject")).GetUniqueID() ) { StdString szFileName; Vec3 vPosition(0,0,0); Vec3 vRotation(0,0,0); Vec3 vScaling(0,0,0); Archive->Read( szFileName, _T("FileName") ); Archive->Read( vPosition, _T("Position") ); vPosition.x = ( vPosition.x * fConvert ); vPosition.y = ( vPosition.y * fConvert ); vPosition.z = ( vPosition.z * fConvert ); Archive->Read( vRotation, _T("Rotation") ); Archive->Read( vScaling, _T("Scaling") ); vScaling.x = ( vScaling.x * fConvert ); vScaling.y = ( vScaling.y * fConvert ); vScaling.z = ( vScaling.z * fConvert ); IArchive *MemArchive; CHashString memType(_T("Memory")); CREATEARCHIVE caOut; caOut.mode = STREAM_MODE_WRITE; caOut.streamData = NULL; caOut.streamSize = 0; caOut.streamType = &memType; static DWORD msgHash_CreateArchive = CHashString(_T("CreateArchive")).GetUniqueID(); if (m_ToolBox->SendMessage(msgHash_CreateArchive, sizeof(CREATEARCHIVE), &caOut) != MSG_HANDLED) { static DWORD msgHash_SetFileVersion = CHashString(_T("SetFileVersion")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SetFileVersion, sizeof(IHashString), &oldVersion); return true; } MemArchive = caOut.archive; MemArchive->Write( szFileName, _T("FileName") ); MemArchive->Write( vPosition, _T("Position") ); MemArchive->Write( vRotation, _T("Rotation") ); MemArchive->Write( vScaling, _T("Scaling") ); CREATESTREAM cs; cs.streamData = caOut.streamData; cs.streamSize = caOut.streamSize; cs.mode = STREAM_MODE_READ; static DWORD msgHash_CreateStream_Memory = CHashString(_T("CreateStream_Memory")).GetUniqueID(); if (m_ToolBox->SendMessage(msgHash_CreateStream_Memory, sizeof(CREATESTREAM), &cs) != MSG_HANDLED) { static DWORD msgHash_SetFileVersion = CHashString(_T("SetFileVersion")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SetFileVersion, sizeof(IHashString), &oldVersion); return true; } MemArchive->Init(cs.openStream); sop.name = &hszName; sop.archive = MemArchive; static DWORD msgHash_SerializeObject = CHashString(_T("SerializeObject")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SerializeObject, sizeof(SERIALIZEOBJECTPARAMS), &sop, NULL, NULL); MemArchive->Close(); } else if( hszTypeName.GetUniqueID() == CHashString(_T("CPhysicsObject")).GetUniqueID() ) { //StdString szDynamics; StdString szType; StdString szShapeFileName; //float fMass; //Vec3 vPosition; //Vec3 vRotation; //Vec3 vScaling; //Archive->Read( vPosition, _T("pos") ); //vPosition.SetX( vPosition.GetX() * fConvert ); //vPosition.SetY( vPosition.GetY() * fConvert ); //vPosition.SetZ( vPosition.GetZ() * fConvert ); //Archive->Read( vRotation, _T("rot") ); //Archive->Read( vScaling, _T("scale") ); //vScaling.SetX( vScaling.GetX() * fConvert ); //vScaling.SetY( vScaling.GetY() * fConvert ); //vScaling.SetZ( vScaling.GetZ() * fConvert ); //Archive->Read( fMass, _T("mass") ); Archive->Read( szType, _T("Type") ); Archive->Read( szShapeFileName, _T("filename") ); IArchive *MemArchive; CHashString memType(_T("Memory")); //int size = sizeof(char) * 256 * 2 + sizeof(float) + sizeof(Vec3) * 3 + 256; CREATEARCHIVE caOut; caOut.mode = STREAM_MODE_WRITE; caOut.streamData = NULL; caOut.streamSize = 0; caOut.streamType = &memType; static DWORD msgHash_CreateArchive = CHashString(_T("CreateArchive")).GetUniqueID(); if (m_ToolBox->SendMessage(msgHash_CreateArchive, sizeof(CREATEARCHIVE), &caOut) != MSG_HANDLED) { static DWORD msgHash_SetFileVersion = CHashString(_T("SetFileVersion")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SetFileVersion, sizeof(IHashString), &oldVersion); return true; } MemArchive = caOut.archive; //MemArchive->Write( vPosition, _T("pos") ); //MemArchive->Write( vRotation, _T("rot") ); //MemArchive->Write( vScaling, _T("scale") ); //MemArchive->Write( fMass, _T("mass") ); //MemArchive->Write( szDynamics, _T("dynamics") ); //MemArchive->Write( szShapeFileName, _T("shapeFile") ); MemArchive->Write( szType, _T("Type") ); MemArchive->Write( szShapeFileName, _T("filename") ); CREATESTREAM cs; cs.streamData = caOut.streamData; cs.streamSize = caOut.streamSize; cs.mode = STREAM_MODE_READ; static DWORD msgHash_CreateStream_Memory = CHashString(_T("CreateStream_Memory")).GetUniqueID(); if (m_ToolBox->SendMessage(msgHash_CreateStream_Memory, sizeof(CREATESTREAM), &cs) != MSG_HANDLED) { static DWORD msgHash_SetFileVersion = CHashString(_T("SetFileVersion")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SetFileVersion, sizeof(IHashString), &oldVersion); return true; } MemArchive->Init(cs.openStream); sop.name = &hszName; sop.archive = MemArchive; static DWORD msgHash_SerializeObject = CHashString(_T("SerializeObject")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SerializeObject, sizeof(SERIALIZEOBJECTPARAMS), &sop, NULL, NULL); MemArchive->Close(); } else if( hszTypeName.GetUniqueID() == CHashString(_T("CTerrainConfig")).GetUniqueID() ) { StdString szTerShaderLib; StdString szTerShaderEff; int iSectorRes; float fSectorSize; float fZScale; float fLODDistance; Archive->Read( szTerShaderLib, _T("TerrainShaderLibrary") ); Archive->Read( szTerShaderEff, _T("TerrainShaderEffect") ); Archive->Read( iSectorRes, _T("SectorResolution") ); Archive->Read( fSectorSize, _T("SectorSize") ); fSectorSize = fSectorSize * fConvert; Archive->Read( fZScale, _T("ZScale") ); fZScale = fZScale * fConvert; Archive->Read( fLODDistance, _T("LODDistance") ); IArchive *MemArchive; CHashString memType(_T("Memory")); CREATEARCHIVE caOut; caOut.mode = STREAM_MODE_WRITE; caOut.streamData = NULL; caOut.streamSize = 0; caOut.streamType = &memType; static DWORD msgHash_CreateArchive = CHashString(_T("CreateArchive")).GetUniqueID(); if (m_ToolBox->SendMessage(msgHash_CreateArchive, sizeof(CREATEARCHIVE), &caOut) != MSG_HANDLED) { static DWORD msgHash_SetFileVersion = CHashString(_T("SetFileVersion")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SetFileVersion, sizeof(IHashString), &oldVersion); return true; } MemArchive = caOut.archive; MemArchive->Write( szTerShaderLib, _T("TerrainShaderLibrary") ); MemArchive->Write( szTerShaderEff, _T("TerrainShaderEffect") ); MemArchive->Write( iSectorRes, _T("SectorResolution") ); MemArchive->Write( fSectorSize, _T("SectorSize") ); MemArchive->Write( fZScale, _T("ZScale") ); MemArchive->Write( fLODDistance, _T("LODDistance") ); CREATESTREAM cs; cs.streamData = caOut.streamData; cs.streamSize = caOut.streamSize; cs.mode = STREAM_MODE_READ; static DWORD msgHash_CreateStream_Memory = CHashString(_T("CreateStream_Memory")).GetUniqueID(); if (m_ToolBox->SendMessage(msgHash_CreateStream_Memory, sizeof(CREATESTREAM), &cs) != MSG_HANDLED) { static DWORD msgHash_SetFileVersion = CHashString(_T("SetFileVersion")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SetFileVersion, sizeof(IHashString), &oldVersion); return true; } MemArchive->Init(cs.openStream); sop.name = &hszName; sop.archive = MemArchive; static DWORD msgHash_SerializeObject = CHashString(_T("SerializeObject")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SerializeObject, sizeof(SERIALIZEOBJECTPARAMS), &sop, NULL, NULL); MemArchive->Close(); } else { sop.name = &hszName; sop.archive = Archive; static DWORD msgHash_SerializeObject = CHashString(_T("SerializeObject")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SerializeObject, sizeof(SERIALIZEOBJECTPARAMS), &sop, NULL, NULL); } } else { sop.name = &hszName; sop.archive = Archive; static DWORD msgHash_SerializeObject = CHashString(_T("SerializeObject")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SerializeObject, sizeof(SERIALIZEOBJECTPARAMS), &sop, NULL, NULL); } iop.name = &hszName; static DWORD msgHash_InitObject = CHashString(_T("InitObject")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_InitObject, sizeof(INITOBJECTPARAMS), &iop, NULL, NULL); elapsedTime += timer->GetRealTime() - lastLoadTime; lastLoadTime = timer->GetRealTime(); if (elapsedTime > secondsPerFrame) { elapsedTime = 0.0f; pbp.currentPosition = Archive->GetCurrentNodePosition(); pbp.totalSize = numNodes; m_ToolBox->SendMessage(msgHash_LoadingUpdate, sizeof(LOADINGUPDATEPARAMS), &pbp); } } pbp.currentPosition = 0; pbp.totalSize = 0; m_ToolBox->SendMessage(msgHash_LoadingUpdate, sizeof(LOADINGUPDATEPARAMS), &pbp); Archive->Close(); static DWORD msgHash_SetFileVersion = CHashString(_T("SetFileVersion")).GetUniqueID(); m_ToolBox->SendMessage(msgHash_SetFileVersion, sizeof(IHashString), &oldVersion); return MSG_HANDLED_STOP; }