Fix css style order when using external css files
[ryzomcore.git] / ryzom / client / src / main_loop.cpp
blobbab17a7b68aba99af8fbaa0f10f5c8d6bbe11fd9
1 // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
2 // Copyright (C) 2010 Winch Gate Property Limited
3 //
4 // This source file has been modified by the following contributors:
5 // Copyright (C) 2013 Laszlo KIS-ADAM (dfighter) <dfighter1985@gmail.com>
6 // Copyright (C) 2013-2020 Jan BOON (Kaetemi) <jan.boon@kaetemi.be>
7 //
8 // This program is free software: you can redistribute it and/or modify
9 // it under the terms of the GNU Affero General Public License as
10 // published by the Free Software Foundation, either version 3 of the
11 // License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU Affero General Public License for more details.
18 // You should have received a copy of the GNU Affero General Public License
19 // along with this program. If not, see <http://www.gnu.org/licenses/>.
22 /////////////
23 // INCLUDE //
24 /////////////
27 #include "stdpch.h"
29 // Misc.
30 #include "nel/misc/path.h"
31 #include "nel/misc/i18n.h"
32 #include "nel/misc/hierarchical_timer.h"
33 #include "nel/misc/displayer.h"
34 #include "nel/misc/value_smoother.h"
35 #include "nel/misc/geom_ext.h"
36 // Net
37 #include "nel/net/module_manager.h"
38 // 3D Interface.
39 #include "nel/3d/bloom_effect.h"
40 #include "nel/3d/u_driver.h"
41 #include "nel/3d/u_scene.h"
42 #include "nel/3d/u_landscape.h"
43 #include "nel/3d/u_camera.h"
44 #include "nel/3d/u_text_context.h"
45 #include "nel/3d/u_instance.h"
46 #include "nel/3d/u_material.h"
47 #include "nel/3d/u_instance_material.h"
48 #include "nel/3d/u_cloud_scape.h"
49 #include "nel/3d/stereo_hmd.h"
50 #include "nel/3d/render_target_manager.h"
51 #include "nel/3d/driver_user.h"
52 #include "nel/3d/fxaa.h"
53 // game share
54 #include "game_share/brick_types.h"
55 #include "game_share/light_cycle.h"
56 #include "game_share/time_weather_season/time_and_season.h"
57 #include "game_share/bot_chat_types.h"
58 // PACS
59 #include "nel/pacs/u_global_position.h"
60 // client sheets
61 #include "client_sheets/weather_function_params_sheet.h"
62 // std
63 #include <string>
64 // Client
65 #include "game_share/constants.h"
66 #include "main_loop.h"
67 #include "input.h"
68 #include "client_cfg.h"
69 #include "actions_client.h"
70 #include "motion/user_controls.h"
71 #include "entity_animation_manager.h"
72 #include "pacs_client.h"
73 #include "view.h"
74 #include "time_client.h"
75 #include "cursor_functions.h"
76 #include "pacs_client.h"
77 #include "entity_fx.h"
78 #include "light_cycle_manager.h"
79 #include "weather_manager_client.h"
80 #include "weather.h"
81 #include "game_share/time_weather_season/weather_predict.h"
82 #include "entities.h"
83 #include "net_manager.h"
84 #include "world_database_manager.h"
85 #include "continent_manager.h"
86 #include "ig_callback.h"
87 #include "release.h"
88 //#include "fog_map.h"
89 #include "movie_shooter.h"
90 #include "sound_manager.h"
91 #include "graph.h"
92 #include "interface_v3/interface_manager.h"
93 #include "demo.h"
94 #include "color_slot_manager.h"
95 #include "interface_v3/input_handler_manager.h"
96 #include "ingame_database_manager.h"
97 #include "sky_render.h"
98 #include "prim_file.h"
99 #include "misc.h"
100 #include "interface_v3/people_interraction.h"
101 #include "debug_client.h"
102 #include "nel/gui/action_handler.h"
103 #include "interface_v3/action_handler_misc.h"
104 #include "interface_v3/action_handler_item.h"
105 #include "fx_manager.h"
106 #include "ground_fx_manager.h"
107 #include "string_manager_client.h"
108 #include "interface_v3/group_in_scene_bubble.h"
109 #include "game_context_menu.h"
110 #include "init_main_loop.h"
111 #include "micro_life_manager.h"
112 #include "timed_fx_manager.h"
113 #include "interface_v3/sphrase_manager.h"
114 #include "outpost_manager.h"
115 #include "sky.h" // new-style sky
116 #include "sky_render.h" // new-style sky
117 #include "interface_v3/music_player.h"
118 #include "permanent_ban.h"
119 #include "camera_recorder.h"
120 #include "connection.h"
121 #include "landscape_poly_drawer.h"
122 #include "nel/gui/lua_ihm.h"
123 #include "interface_v3/lua_ihm_ryzom.h"
124 #include "far_tp.h"
125 #include "session_browser_impl.h"
126 #include "bg_downloader_access.h"
127 #include "login_progress_post_thread.h"
128 #include "npc_icon.h"
129 #include "item_group_manager.h"
130 // R2ED
131 #include "r2/editor.h"
133 #include "nel/misc/check_fpu.h"
137 #ifdef USE_WATER_ENV_MAP
138 #include "water_env_map_rdr.h"
139 #endif
141 // temp
142 #include "precipitation.h"
143 #include "interface_v3/bot_chat_manager.h"
144 #include "string_manager_client.h"
146 #include "nel/gui/lua_manager.h"
147 #include "nel/gui/group_table.h"
149 // pulled from main_loop.cpp
150 #include "ping.h"
151 #include "profiling.h"
152 #include "camera.h"
153 #include "main_loop_debug.h"
154 #include "main_loop_temp.h"
155 #include "main_loop_utilities.h"
158 ///////////
159 // USING //
160 ///////////
161 using namespace NLMISC;
162 using namespace NL3D;
163 using namespace NLPACS;
164 using namespace NLNET;
165 using namespace std;
167 #ifdef DEBUG_NEW
168 #define new DEBUG_NEW
169 #endif
174 ////////////
175 // EXTERN //
176 ////////////
177 extern UDriver *Driver;
178 extern UScene *Scene;
179 extern UScene *SceneRoot;
180 extern ULandscape *Landscape;
181 extern UCloudScape *CloudScape;
182 extern bool InitCloudScape;
183 extern CLandscapeIGManager LandscapeIGManager;
184 extern UTextContext *TextContext;
185 extern CEntityAnimationManager *EAM;
186 extern TTime UniversalTime;
187 extern UMaterial GenericMat;
188 extern UCamera MainCam;
189 extern CEventsListener EventsListener;
190 extern CMatrix MainSceneViewMatrix;
191 extern CMatrix InvMainSceneViewMatrix;
192 extern std::vector<UTextureFile*> LogoBitmaps;
193 extern bool IsInRingSession;
194 extern std::string UsedFSAddr;
196 // temp
197 extern NLMISC::CValueSmoother smoothFPS;
198 extern NLMISC::CValueSmoother moreSmoothFPS;
200 void loadBackgroundBitmap (TBackground background);
201 void destroyLoadingBitmap ();
202 void drawLoadingBitmap (float progress);
203 void updateStatReport ();
205 CFogState MainFogState;
206 CFogState RootFogState;
209 #define RYZOM_FIRST_FRAME_TO_SKIP 30
212 const float CANOPY_DEPTH_RANGE_START = 0.95f;
213 const float SKY_DEPTH_RANGE_START = 0.99f;
215 CRGBA ThunderColor;
217 float SimulatedServerDate = 0.f;
218 uint64 SimulatedServerTick = 0;
223 /////////////
224 // GLOBALS //
225 /////////////
226 bool game_exit = false;
227 bool ryzom_exit = false;
228 bool game_exit_request = false;
229 bool ryzom_exit_request = false;
230 bool paying_account_request = false;
231 bool paying_account_already_request = false;
232 bool game_exit_after_paying_account_request = false;
233 bool Render = true;
235 float MouseX; // Mouse pos X for the frame.
236 float MouseY; // Mouse pos Y for the frame.
237 float OldMouseX; // Mouse pos X of the last frame.
238 float OldMouseY; // Mouse pos Y of the last frame.
240 uint32 Width; // Width of the window.
241 uint32 Height; // Height of the window.
242 uint32 OldWidth; // Last Width of the window.
243 uint32 OldHeight; // Last Height of the window.
245 bool ShowInterface = true; // Do the Chat OSD have to be displayed.
246 bool DebugUIView = false;
247 bool DebugUICtrl = false;
248 bool DebugUIGroup = false;
249 std::string DebugUIFilter;
250 bool ShowHelp = false; // Do the Help have to be displayed.
251 uint8 ShowInfos = 0; // 0=no info 1=text info 2=graph info
253 bool bZeroCpu = false; // For no Cpu use if application is minimize TODO: intercept minimize message, called by CTRL + Z at this
255 bool MovieShooterSaving= false; // Are we in Shooting mode?
258 bool DisplayWeatherFunction = false;
260 // temp
261 float DelayBeforeCloudUpdate = 0.f; // delay in s before cloud state must be recomputed
262 const float CloudUpdatePeriod = 45.f; // period used for clouds update
264 TScreenshotRequest ScreenshotRequest = ScreenshotRequestNone;
267 // First frames to skip
268 bool FirstFrame = false;
269 uint SkipFrame = 0;
271 // temp : for timed fxs test
272 bool ShowTimedFX = false;
273 CTimedFXManager::TDebugDisplayMode ShowTimedFXMode = CTimedFXManager::NoText;
275 //CGraph FpsGraph ("frame rate (fps)", 10.0f, 110.0f, 100.0f, 100.0f, CRGBA(128,0,0,128), 1000, 60.0f);
276 //CGraph SpfGraph ("mspf", 10.0f, 10.0f, 100.0f, 100.0f, CRGBA(0,128,0,128), 0, 800.0f);
277 // TestYoyo
278 //CGraph CameraThirPersonGraph ("Camera Thir Person", 300.0f, 460.0f, 200.0f, 200.0f, CRGBA(0,64,128,128), 0, 5.0f, 1);
280 // DEBUG
281 bool PACSBorders = false;
282 bool ARKPACSBorders = false;
283 bool DebugClusters = false;
284 CVector LastDebugClusterCameraThirdPersonStart= CVector::Null;
285 CVector LastDebugClusterCameraThirdPersonEnd= CVector::Null;
286 CVector LastDebugClusterCameraThirdPersonTestStart= CVector::Null;
287 CVector LastDebugClusterCameraThirdPersonPelvisPos= CVector::Null;
288 CVector LastDebugClusterCameraThirdPersonResult= CVector::Null;
289 bool LastDebugClusterCameraThirdPersonForceFPV= false;
290 bool SoundBox = false;
291 CPing Ping;
292 sint CompassMode = 0; // 0: compass with regard to the user front, 1: to the camera direction.
294 float BanMsgCountdown = 0.f;
295 const float BanMsgRepeatTime = 5.f;
297 CGameContextMenu GameContextMenu;
303 static CRefPtr<CCDBNodeLeaf> s_FpsLeaf;
304 static CRefPtr<CCDBNodeLeaf> s_UiDirectionLeaf;
307 // Profile
309 0 : AllMeshNoVP
310 1 : AllMeshVP
311 2 : FX
312 3 : Landscape
313 4 : Vegetable
314 5 : Skeleton
315 6 : Water
316 7 : Cloud
317 8 : CoarseMesh*/
318 bool Filter3D[RYZOM_MAX_FILTER_3D] = {true, true, true, true, true, true, true, true, true, true};
319 bool Scene_Profile= false;
323 // Hierarchical timer
324 H_AUTO_DECL ( RZ_Client_Check_Actions )
325 H_AUTO_DECL ( RZ_Client_Main_Loop )
326 H_AUTO_DECL ( RZ_Client_Main_Loop_Zero_Cpu )
327 H_AUTO_DECL ( RZ_Client_Main_Loop_Cursor )
328 H_AUTO_DECL ( RZ_Client_Main_Loop_Time_Update )
329 H_AUTO_DECL ( RZ_Client_Main_Loop_Selection_FX )
330 H_AUTO_DECL ( RZ_Client_Main_Loop_Sky_And_Weather )
331 H_AUTO_DECL ( RZ_Client_Main_Loop_Render_Root )
332 H_AUTO_DECL ( RZ_Client_Main_Loop_Render_Main )
333 H_AUTO_DECL ( RZ_Client_Main_Loop_Anim_Cloud_Scape )
334 H_AUTO_DECL ( RZ_Client_Main_Loop_Update_Cloud_Scape )
335 H_AUTO_DECL ( RZ_Client_Main_Loop_Render_Cloud_Scape )
336 H_AUTO_DECL ( RZ_Client_Main_Loop_Debug )
337 H_AUTO_DECL ( RZ_Client_Main_Loop_Guild_Symbol )
338 H_AUTO_DECL ( RZ_Client_Main_Loop_Render_Thunder )
339 H_AUTO_DECL ( RZ_Client_Main_Loop_Interface )
340 H_AUTO_DECL ( RZ_Client_Main_Loop_Sound )
341 H_AUTO_DECL ( RZ_Client_Main_Loop_Net )
343 ///////////////
344 // FUNCTIONS //
345 ///////////////
347 //update the sound manager (listener pos, user walk/run sound...)
348 void updateSound();
350 void displaySpecialTextProgress(const char *text);
352 void endMovieShooting();
353 void updateMovieShooting();
355 void updateLightDesc();
356 void updateClouds();
358 void displayPACSBorders();
359 void displayPACSPrimitive();
360 void displaySoundBox();
361 void displayDebugClusters();
363 void displaySceneProfiles();
365 // validate current dialogs (end them if the player is too far from its interlocutor)
366 void validateDialogs(const CGameContextMenu &gcm);
369 // ***************************************************************************
371 enum TSkyMode { NoSky, OldSky, NewSky };
372 static TSkyMode s_SkyMode = NoSky;
374 void preRenderNewSky ()
376 CSky &sky = ContinentMngr.cur()->CurrentSky;
377 // setup fog, lighting & sky object. We use the same light direction than with the main scene
378 CClientDate cd = SmoothedClientDate;
379 if (ClientCfg.R2EDEnabled && R2::getEditor().getFixedLighting())
381 cd.Hour = 12.f;
383 sky.setup(cd, SmoothedClientDate, WeatherManager.getWeatherValue(), MainFogState.FogColor, Scene->getSunDirection(), false);
386 void commitCamera()
388 // Set the sky camera
389 if (s_SkyMode == NewSky)
391 CSky &sky = ContinentMngr.cur()->CurrentSky;
392 // setup camera
393 CFrustum frust = MainCam.getFrustum();
394 UCamera camSky = sky.getScene()->getCam();
395 sky.getScene()->setViewport(Scene->getViewport());
396 camSky.setTransformMode(UTransform::DirectMatrix);
397 // must have our own Far!!!
398 frust.Far= SkyCameraZFar;
399 camSky.setFrustum(frust);
400 CMatrix skyCameraMatrix;
401 skyCameraMatrix.identity();
402 skyCameraMatrix= MainCam.getMatrix();
403 skyCameraMatrix.setPos(CVector::Null);
404 camSky.setMatrix(skyCameraMatrix);
407 // Set The Root Camera
408 UCamera camRoot = SceneRoot->getCam();
409 if(!camRoot.empty())
411 // Update Camera Position/Rotation.
412 //camRoot.setPos(View.currentViewPos());
413 //camRoot.setRotQuat(View.currentViewQuat());
414 camRoot.setPos(MainCam.getPos());
415 camRoot.setRotQuat(MainCam.getRotQuat());
419 // ***************************************************************************
421 void beginRenderCanopyPart()
423 SceneRoot->beginPartRender();
425 void endRenderCanopyPart()
427 SceneRoot->endPartRender(false);
430 void beginRenderMainScenePart()
432 Scene->beginPartRender();
434 void endRenderMainScenePart(bool keepTraversals)
436 Scene->endPartRender(!keepTraversals, true, keepTraversals);
439 void beginRenderSkyPart()
441 if (s_SkyMode == NewSky)
443 CSky &sky = ContinentMngr.cur()->CurrentSky;
444 sky.getScene()->beginPartRender();
447 void endRenderSkyPart()
449 if (s_SkyMode == NewSky)
451 CSky &sky = ContinentMngr.cur()->CurrentSky;
452 sky.getScene()->endPartRender(false);
457 // ***************************************************************************************************************************
458 // Render a part of the canopy
459 static void renderCanopyPart(UScene::TRenderPart renderPart)
461 H_AUTO_USE ( RZ_Client_Main_Loop_Render_Root )
462 Driver->setDepthRange(CANOPY_DEPTH_RANGE_START, SKY_DEPTH_RANGE_START);
464 ContinentMngr.getFogState(CanopyFog, LightCycleManager.getLightLevel(), LightCycleManager.getLightDesc().DuskRatio, LightCycleManager.getState(), View.viewPos(), RootFogState);
465 RootFogState.setupInDriver(*Driver);
467 // Render the root scene
468 SceneRoot->renderPart(renderPart);
471 // ***************************************************************************************************************************
472 // Render a part of the main scene
473 static void renderMainScenePart(UScene::TRenderPart renderPart, bool wantTraversals, bool keepTraversals)
475 H_AUTO_USE ( RZ_Client_Main_Loop_Render_Main )
476 Driver->setDepthRange(0.f, CANOPY_DEPTH_RANGE_START);
477 if(ClientCfg.Fog == false )
479 Driver->enableFog (false);
481 else
483 MainFogState.setupInDriver (*Driver);
485 Scene->renderPart(renderPart, true, wantTraversals, keepTraversals);
489 // ***************************************************************************************************************************
490 // Render a part of the sky
491 static void renderSkyPart(UScene::TRenderPart renderPart)
493 nlassert(s_SkyMode != NoSky);
494 Driver->setDepthRange(SKY_DEPTH_RANGE_START, 1.f);
495 Driver->enableFog(false);
496 if (s_SkyMode == NewSky)
498 CSky &sky = ContinentMngr.cur()->CurrentSky;
499 sky.getScene()->renderPart(renderPart);
501 else
503 // old style sky
504 renderSky(LightCycleManager, MainFogState.FogColor);
506 #ifdef RENDER_CLOUDS
507 if (CloudScape != NULL && Filter3D[FilterCloud])
509 H_AUTO_USE( RZ_Client_Main_Loop_Render_Cloud_Scape )
510 CloudScape->render ();
512 #endif
515 // ***************************************************************************************************************************
516 // Utility to force full detail
517 struct CForceFullDetail
519 public:
520 void backup()
522 maxFullDetailChar = Scene->getMaxSkeletonsInNotCLodForm();
523 oldBalancingMode = Scene->getPolygonBalancingMode();
524 oldSkyBalancingMode = UScene::PolygonBalancingOff;
525 UScene *skyScene = getSkyScene();
526 if (skyScene) oldSkyBalancingMode = skyScene->getPolygonBalancingMode();
528 void set()
530 Scene->setMaxSkeletonsInNotCLodForm(1000000);
531 Scene->setPolygonBalancingMode(UScene::PolygonBalancingOff);
532 UScene *skyScene = getSkyScene();
533 if (skyScene) skyScene->setPolygonBalancingMode(UScene::PolygonBalancingOff);
535 void restore()
537 Scene->setMaxSkeletonsInNotCLodForm(maxFullDetailChar);
538 Scene->setPolygonBalancingMode(oldBalancingMode);
539 UScene *skyScene = getSkyScene();
540 if (skyScene) skyScene->setPolygonBalancingMode(oldSkyBalancingMode);
542 private:
543 uint maxFullDetailChar;
544 UScene::TPolygonBalancingMode oldBalancingMode;
545 UScene::TPolygonBalancingMode oldSkyBalancingMode;
547 static CForceFullDetail s_ForceFullDetail;
549 void clearBuffers()
551 if (Render)
553 if (Driver->getPolygonMode() == UDriver::Filled)
555 Driver->clearZBuffer();
558 // Sky is used to clear the frame buffer now, but if in line or point polygon mode, we should draw it
559 if (Driver->getPolygonMode() != UDriver::Filled || !Filter3D[FilterSky])
561 if (!Driver->isLost())
563 Driver->clearBuffers (ClientCfg.BGColor);
567 else
569 Driver->clearBuffers(ClientCfg.BGColor);
573 void renderScene(bool forceFullDetail, bool bloom)
575 CTextureUser *effectRenderTarget = NULL;
576 if (bloom)
578 // set bloom parameters before applying bloom effect
579 CBloomEffect::getInstance().setSquareBloom(ClientCfg.SquareBloom);
580 CBloomEffect::getInstance().setDensityBloom((uint8)ClientCfg.DensityBloom);
582 // init effect render target
583 Driver->beginDefaultRenderTarget();
585 if (forceFullDetail)
587 s_ForceFullDetail.backup();
588 s_ForceFullDetail.set();
590 clearBuffers();
591 doRenderScene(true, false);
592 if (forceFullDetail)
594 s_ForceFullDetail.restore();
596 if (bloom)
598 // apply bloom effect
599 CBloomEffect::getInstance().applyBloom();
601 // draw final result to backbuffer
602 Driver->endDefaultRenderTarget(Scene);
606 // ***************************************************************************************************************************
608 void updateWaterEnvMap()
610 #ifdef USE_WATER_ENV_MAP
611 if (WaterEnvMapRefCount > 0) // water env map needed
613 if (!WaterEnvMap)
615 CSky &sky = ContinentMngr.cur()->CurrentSky;
616 if (sky.getScene())
618 nlassert(WaterEnvMapSkyCam.empty());
619 WaterEnvMapSkyCam = sky.getScene()->createCamera(); // deleted in unselect
620 nlassert(WaterEnvMapCanopyCam.empty());
621 WaterEnvMapCanopyCam = SceneRoot->createCamera(); // deleted in unselect
622 // Create water env map if not already created
623 WaterEnvMap = Driver->createWaterEnvMap();
624 if(WaterEnvMap)
626 WaterEnvMap->init(128, 256, ClientCfg.WaterEnvMapUpdateTime);
627 WaterEnvMap->setWaterEnvMapRenderCallback(&WaterEnvMapRdr);
628 Scene->setWaterEnvMap(WaterEnvMap);
632 WaterEnvMapRdr.CurrDate = SmoothedClientDate;
633 WaterEnvMapRdr.AnimationDate = SmoothedClientDate;
634 if (ClientCfg.R2EDEnabled && R2::getEditor().getFixedLighting())
636 WaterEnvMapRdr.CurrDate.Hour = 12.f;
638 WaterEnvMapRdr.CurrFogColor = MainFogState.FogColor;
639 WaterEnvMapRdr.CurrTime = TimeInSec - FirstTimeInSec;
640 WaterEnvMapRdr.CurrWeather = WeatherManager.getWeatherValue();
641 CSky &sky = ContinentMngr.cur()->CurrentSky;
642 WaterEnvMap->setAlpha(sky.getWaterEnvMapAlpha());
643 Scene->updateWaterEnvMaps(TimeInSec - FirstTimeInSec);
645 #endif
648 // ***************************************************************************************************************************
650 void updateWeather()
652 H_AUTO_USE ( RZ_Client_Main_Loop_Sky_And_Weather )
654 //HeightGrid.update(Scene->getCam().getPos());
656 // update description of light cycle
657 updateLightDesc();
659 // server driven weather mgt
660 updateDBDrivenWeatherValue();
662 // Update the weather manager
663 updateWeatherManager(MainCam.getMatrix(), ContinentMngr.cur());
665 // compute thunder color
666 ThunderColor.modulateFromui(WeatherManager.getCurrWeatherState().ThunderColor, (uint) (256.f * WeatherManager.getThunderLevel()));
668 // Update the lighting
669 LightCycleManager.setHour(DayNightCycleHour, WeatherManager, ThunderColor);
671 #ifdef RENDER_CLOUDS
672 if (Filter3D[FilterCloud])
674 H_AUTO_USE ( RZ_Client_Main_Loop_Update_Cloud_Scape );
675 updateClouds();
677 #endif
679 ContinentMngr.getFogState(MainFog, LightCycleManager.getLightLevel(), LightCycleManager.getLightDesc().DuskRatio, LightCycleManager.getState(), View.viewPos(), MainFogState);
681 // TODO: ZBuffer clear was originally before this, but should not be necessary normally.
682 // The anim function renders new clouds. Ensure this does not break.
683 // These are old-style nel clouds.
685 #ifdef RENDER_CLOUDS
686 if (CloudScape != NULL && Filter3D[FilterCloud])
688 H_AUTO_USE ( RZ_Client_Main_Loop_Anim_Cloud_Scape );
690 Driver->enableFog (false);
692 // Force polygon mode to filled
693 NL3D::UDriver::TPolygonMode oldMode = Driver->getPolygonMode();
694 Driver->setPolygonMode(NL3D::UDriver::Filled);
696 CloudScape->anim (DT); // WARNING this function work with screen
698 Driver->enableFog (true);
700 // Reset backuped polygon mode
701 Driver->setPolygonMode(oldMode);
703 #endif
705 // Update new sky
706 s_SkyMode = NoSky;
707 if (ContinentMngr.cur() && !ContinentMngr.cur()->Indoor)
709 if(Driver->getPolygonMode() == UDriver::Filled)
711 if (Filter3D[FilterSky])
713 CSky &sky = ContinentMngr.cur()->CurrentSky;
714 if (sky.getScene())
716 s_SkyMode = NewSky;
717 sky.getScene()->animate(TimeInSec-FirstTimeInSec);
718 // Setup the sky camera
719 preRenderNewSky();
721 else
723 s_SkyMode = OldSky;
730 void beginRenderScene()
732 // Update Filter Flags
733 Scene->enableElementRender(UScene::FilterAllMeshNoVP, Filter3D[FilterMeshNoVP]);
734 Scene->enableElementRender(UScene::FilterAllMeshVP, Filter3D[FilterMeshVP]);
735 Scene->enableElementRender(UScene::FilterFX, Filter3D[FilterFXs]);
736 Scene->enableElementRender(UScene::FilterLandscape, Filter3D[FilterLandscape]);
737 Scene->enableElementRender(UScene::FilterSkeleton, Filter3D[FilterSkeleton]);
738 Scene->enableElementRender(UScene::FilterWater, Filter3D[FilterWater]);
739 Scene->enableElementRender(UScene::FilterCoarseMesh, Filter3D[FilterCoarseMesh]);
741 // profile this frame?
742 if(Scene_Profile)
743 Scene->profileNextRender();
745 // initialisation of polygons renderer
746 CLandscapePolyDrawer::getInstance().beginRenderLandscapePolyPart();
748 // Start Part Rendering
749 beginRenderCanopyPart();
750 beginRenderMainScenePart();
751 beginRenderSkyPart();
754 void drawRenderScene(bool wantTraversals, bool keepTraversals)
756 // Render part
757 // WARNING: always must begin rendering with at least UScene::RenderOpaque,
758 // else dynamic shadows won't work
759 renderCanopyPart(UScene::RenderOpaque);
760 renderMainScenePart(UScene::RenderOpaque, wantTraversals, keepTraversals);
762 // render of polygons on landscape
763 CLandscapePolyDrawer::getInstance().renderLandscapePolyPart();
765 if (s_SkyMode != NoSky) renderSkyPart((UScene::TRenderPart) (UScene::RenderOpaque | UScene::RenderTransparent));
766 renderCanopyPart((UScene::TRenderPart) (UScene::RenderTransparent | UScene::RenderFlare));
767 renderMainScenePart((UScene::TRenderPart) (UScene::RenderTransparent | UScene::RenderFlare), wantTraversals, keepTraversals);
768 if (s_SkyMode == NewSky) renderSkyPart(UScene::RenderFlare);
771 void endRenderScene(bool keepTraversals)
773 // End Part Rendering
774 endRenderSkyPart();
775 endRenderMainScenePart(keepTraversals);
776 endRenderCanopyPart();
778 // reset depth range
779 Driver->setDepthRange(0.f, CANOPY_DEPTH_RANGE_START);
782 // ***************************************************************************************************************************
783 // Render all scenes
784 void doRenderScene(bool wantTraversals, bool keepTraversals)
786 beginRenderScene();
787 drawRenderScene(wantTraversals, keepTraversals);
788 endRenderScene(keepTraversals);
792 // ***************************************************************************
793 class CMusicFader
795 public:
796 uint NFrameSkip;
797 float TotalTime;
798 bool Done;
800 public:
801 CMusicFader(uint nframeToSkip, float fadeTime)
803 NFrameSkip= nframeToSkip;
804 // avoid div by zero
805 fadeTime= max(fadeTime, 0.01f);
806 TotalTime= fadeTime;
807 Done= false;
810 void fade();
812 void CMusicFader::fade()
814 // ended?
815 if(NFrameSkip==0 && Done)
816 return;
818 // else fade
819 if(NFrameSkip==0)
821 // stop music (slow fade out of 3 secondes)
822 if(SoundMngr)
823 SoundMngr->stopMusic(uint(TotalTime*1000));
824 Done= true;
826 else
827 NFrameSkip--;
830 // ***************************************************************************
831 void updateGameQuitting()
833 static sint64 firstTimeLostConnection= 0;
835 // Yoyo: prefer now leave the user press "Quit Now" if don't want to wait server
837 // if want quiting, and if server stalled, quit now
838 if(game_exit_request)
840 // abort until 10 seconds if connection lost
841 if(!NetMngr.getConnectionQuality())
843 if(!firstTimeLostConnection)
844 firstTimeLostConnection= T1;
846 else
848 firstTimeLostConnection= 0;
851 // if connection lost until 10 seconds
852 if(firstTimeLostConnection && T1-firstTimeLostConnection > 10000)
854 game_exit= true;
855 ryzom_exit= ryzom_exit_request;
858 else
860 // reset
861 firstTimeLostConnection= 0;
864 // update the window
865 CInterfaceManager *pIM= CInterfaceManager::getInstance();
867 CInterfaceGroup *group= dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:free_trial_game_quitting"));
868 if(group)
870 // if Free trial
871 if(paying_account_request)
873 // if no current modal window, or if not the quit window
874 if(group != CWidgetManager::getInstance()->getModalWindow())
876 // disable
877 CWidgetManager::getInstance()->disableModalWindow();
878 CWidgetManager::getInstance()->enableModalWindow(NULL, group);
882 else
884 // if the current modal window is the quit window, disable
885 if(group == CWidgetManager::getInstance()->getModalWindow())
887 // disable
888 CWidgetManager::getInstance()->disableModalWindow();
893 group= dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:game_quitting"));
894 if(group)
896 // if exit request
897 if(game_exit_request && !paying_account_request)
899 // if no current modal window, or if not the quit window
900 if(group != CWidgetManager::getInstance()->getModalWindow())
902 // disable
903 CWidgetManager::getInstance()->disableModalWindow();
904 CWidgetManager::getInstance()->enableModalWindow(NULL, group);
906 bool farTPing = FarTP.isFarTPInProgress();
907 // Far TP: skipping not allowed (because we can't duplicate the avatar...), anyway the quit button would quit the game (no far tp)
908 CInterfaceElement *quitNowButton = group->getElement(group->getId() + ":indent_middle:ryzom");
909 if (quitNowButton)
910 quitNowButton->setActive(!farTPing);
911 // From ring session or from mainland's ring access point: cancelling not allowed (would lead to inconsistencies with the SU & DSS)
912 CInterfaceElement *backToGame = group->getElement(group->getId() + ":indent_middle:cancel");
913 if (backToGame)
914 backToGame->setActive(!(farTPing && (IsInRingSession || FarTP.isFastDisconnectGranted())));
915 CInterfaceElement *quittingRules = group->getElement(group->getId() + ":text_mean");
916 if (quittingRules)
917 quittingRules->setActive(!farTPing);
918 CInterfaceElement *quittingText = group->getElement(group->getId() + ":text");
919 if (quittingText)
920 quittingText->setActive(!farTPing);
923 // else
924 else
926 // if the current modal window is the quit window, disable
927 if(group == CWidgetManager::getInstance()->getModalWindow())
929 // disable
930 CWidgetManager::getInstance()->disableModalWindow();
937 void setDefaultChatWindow(CChatWindow *defaultChatWindow)
939 if (defaultChatWindow)
941 CInterfaceManager *im = CInterfaceManager::getInstance();
942 if (defaultChatWindow->getContainer())
944 CInterfaceGroup *ig = defaultChatWindow->getContainer()->getGroup("eb");
945 if (ig) CWidgetManager::getInstance()->setDefaultCaptureKeyboard(ig);
950 void updateDayNightCycleHour()
952 if (ClientCfg.R2EDEnabled && R2::getEditor().getFixedLighting())
954 DayNightCycleHour = 12.f;
956 else
958 // if there's a forced time, apply it
959 if( ForcedDayNightCycleHour < 0 )
960 DayNightCycleHour = (float)RT.getRyzomTime();
961 else
962 DayNightCycleHour = ForcedDayNightCycleHour;
967 // ***************************************************************************
968 //---------------------------------------------------
969 // mainLoop :
970 // Main loop of the application (displayer, input, ...).
971 // Return true to exit the game, false to return to character selection
972 //---------------------------------------------------
973 bool mainLoop()
975 resetIngameTime ();
977 NLMISC::TTime initStart = ryzomGetLocalTime();
978 NLMISC::TTime initLast = initStart;
979 NLMISC::TTime initCurrent = initLast;
981 game_exit = false;
982 game_exit_request = false;
983 paying_account_request = false;
984 paying_account_already_request = false;
985 game_exit_after_paying_account_request = false;
986 FarTP.setMainLoopEntered();
988 nlinfo ("Starting main loop...", (uint32)(initCurrent-initLast)/1000, (uint32)(initCurrent-initStart)/1000);
990 // Get the Width and Height of the window and set the Old values..
991 Driver->getWindowSize(Width, Height);
992 OldWidth = Width; OldHeight = Height;
994 CGraph::init( Driver );
995 CGraph::Display = false;
997 T1 = ryzomGetLocalTime (); //(sint64)CGDTime::getTime (); // \todo GUIGUI : VOIR COMMENT MANAGER LE TEMPS
998 TSend = ((T1+DTSend)/DTSend)*DTSend;
1000 // initialize the structure for the ping.
1001 Ping.init();
1003 // initialize screenshots directory
1004 initScreenshot();
1006 // Call a function for a demo to init.
1008 if (ClientCfg.Local)
1010 if (!ClientCfg.Light)
1011 initDemo();
1014 // Get the Connection State.
1015 CNetworkConnection::TConnectionState lastConnectionState = CNetworkConnection::Connected;
1016 CNetworkConnection::TConnectionState connectionState = NetMngr.getConnectionState();
1018 updateLightDesc();
1020 SetMouseFreeLook ();
1021 SetMouseCursor ();
1022 // Set the cursor.
1023 ContextCur.context("STAND BY");
1024 UserControls.reset();
1026 // set the default box for keyboard
1027 setDefaultChatWindow(PeopleInterraction.ChatGroup.Window);
1030 // Init GameContextMenu.
1031 GameContextMenu.init("");
1033 // Active inputs
1034 Actions.enable(true);
1035 EditActions.enable(true);
1037 // For stoping the outgame music, start after 30 frames, and duration of 3 seconds
1038 CMusicFader outgameFader(60, 3);
1041 // check for banned player
1042 if (testPermanentBanMarkers())
1044 setPermanentBanMarkers(true); // re-set any marker that could have been removed by the trouble maker
1045 applyPermanentBanPunishment();
1046 PermanentlyBanned = true;
1050 CNiceInputAuto niceInputs;
1051 // R2 editor and modules
1052 R2::getEditor().autoConfigInit(IsInRingSession);
1054 if (ClientCfg.BeepWhenLaunched)
1056 beep( 680, 400 );
1057 beep( 440, 400 );
1058 Driver->showWindow();
1061 FPU_CHECKER_ONCE
1063 CurrSeason = computeCurrSeason();
1065 initLast = initCurrent;
1066 initCurrent = ryzomGetLocalTime();
1067 nlinfo ("PROFILE: %d seconds (%d total) for Starting main loop", (uint32)(initCurrent-initLast)/1000, (uint32)(initCurrent-initStart)/1000);
1069 if (ClientCfg.R2EDEnabled && !ClientCfg.Local)
1071 R2::getEditor().waitScenario();
1074 CSessionBrowserImpl::getInstance().init(CLuaManager::getInstance().getLuaState());
1077 CLuaManager::getInstance().executeLuaScript("game:onMainLoopBegin()");
1080 if (StartInitTime != 0)
1082 CLoginProgressPostThread::getInstance().step(CLoginStep(LoginStep_InGameEntry, "login_step_game_entry&load_time=" + toString((NLMISC::CTime::getLocalTime() - StartInitTime) / 1000)));
1083 StartInitTime = 0;
1086 ProgressBar.finish();
1088 bool musicTriggerAutoPlay = true;
1090 // Main loop. If the window is no more Active -> Exit.
1091 while( !UserEntity->permanentDeath()
1092 && !game_exit )
1094 // If an action handler execute. NB: MUST BE DONE BEFORE ANY THING ELSE PROFILE CRASH!!!!!!!!!!!!!!!!!
1095 testLaunchProfile();
1097 // Test and may run a VBLock profile (only once)
1098 testLaunchProfileVBLock();
1100 // Start Bench
1101 H_AUTO_USE ( RZ_Client_Main_Loop )
1103 #ifdef RYZOM_BG_DOWNLOADER
1104 if (isBGDownloadEnabled())
1106 CBGDownloaderAccess &bgDownloader = CBGDownloaderAccess::getInstance();
1107 // if the ui is frozen, wait for a few frame to allow client to do first frame load,
1108 // without having to compete with the downloader frame
1109 if (!FirstFrame && bgDownloader.isDownloaderUIFrozen() && SkipFrame == 0)
1111 unpauseBGDownloader();
1114 #endif
1116 FPU_CHECKER_ONCE
1118 EGSPD::CSeason::TSeason newLocalSeason = computeCurrSeason();
1119 if (newLocalSeason != CurrSeason)
1121 LoadingBackground= TeleportKaravanBackground;
1122 beginLoading (LoadingBackground);
1123 extern void selectTipsOfTheDay (uint tips);
1124 selectTipsOfTheDay (rand());
1125 UseEscapeDuringLoading = false;
1127 #define BAR_STEP_TP 2
1128 ProgressBar.reset (BAR_STEP_TP);
1129 string nmsg("Loading...");
1130 ProgressBar.newMessage ( ClientCfg.buildLoadingString(nmsg) );
1131 ProgressBar.progress(0);
1132 ContinentMngr.select(UserEntity->pos(), ProgressBar);
1133 ProgressBar.finish();
1134 CurrSeason = newLocalSeason;
1137 if (ClientCfg.R2EDEnabled)
1139 if (R2::ResetWanted)
1141 R2::getEditor().reset();
1142 R2::ResetWanted = false;
1145 if (R2::ResetScenarioWanted)
1147 R2::getEditor().resetScenario();
1148 R2::ResetScenarioWanted = false;
1150 if (R2::ReloadScenarioWanted)
1152 R2::getEditor().reloadScenario();
1153 R2::ReloadScenarioWanted = false;
1159 if (PermanentlyBanned)
1161 if (UserEntity)
1163 UserEntity->runVelocity(0);
1164 UserEntity->walkVelocity(0);
1166 BanMsgCountdown -= DT;
1167 if (BanMsgCountdown < 0.f)
1169 CInterfaceManager *pIM = CInterfaceManager::getInstance();
1170 string msg = CI18N::get("msgPermanentlyBanned");
1171 string cat = getStringCategory(msg, msg);
1172 pIM->displaySystemInfo(msg, cat);
1173 BanMsgCountdown = BanMsgRepeatTime;
1179 // Stop the Outgame music, with fade effect
1180 outgameFader.fade();
1182 // update quit feature
1183 updateGameQuitting();
1185 // update module manager
1186 NLNET::IModuleManager::getInstance().updateModules();
1188 if (ClientCfg.R2EDEnabled)
1190 R2::getEditor().getDMC().flushActions();
1192 if (UserEntity) { UserEntity->updateNpcContolSpeed(); }
1196 // update outpost stuff
1197 OutpostManager.update();
1200 // flush observers
1201 IngameDbMngr.flushObserverCalls();
1202 NLGUI::CDBManager::getInstance()->flushObserverCalls();
1206 EventsListener.setUIHandledButtonMask(NLMISC::noButton);
1208 // Fast mode.
1209 if(bZeroCpu)
1211 H_AUTO_USE ( RZ_Client_Main_Loop_Zero_Cpu )
1213 // Grab Inputs.
1214 CInputHandlerManager::getInstance()->pumpEventsNoIM();
1217 // NetWork Update.
1218 NetMngr.update();
1219 IngameDbMngr.flushObserverCalls();
1220 NLGUI::CDBManager::getInstance()->flushObserverCalls();
1221 // lets some CPU.
1222 NetMngr.send();
1223 nlSleep(100);
1224 // End of the frame.
1229 continue;
1232 CSessionBrowserImpl::getInstance().update();
1234 //////////////////////////
1235 // INITIALIZE THE FRAME //
1236 //////////////////////////
1237 CInterfaceManager *pIMinstance;
1240 if (ClientCfg.IsInvalidated)
1241 updateFromClientCfg();
1244 // Update the event listener
1245 EventsListener.update ();
1249 EventsListener.updateMouseSmoothing(); // IMPORTANT: this should be called before updateClientTime && events handling in the frame
1252 // Update Time.
1253 updateClientTime();
1256 // Grab Inputs.
1257 CInputHandlerManager::getInstance()->pumpEvents();
1259 CLandscapePolyDrawer::getInstance().deletePolygons();
1260 CDecalRenderList::getInstance().clearRenderList();
1263 // Update the Interface Manager Events.
1264 pIMinstance = CInterfaceManager::getInstance();
1267 // NB: must update frame events, even if ShowInterface==0, else may OutOfMemory (cause vector<> never cleared).
1268 pIMinstance->updateFrameEvents ();
1271 if ((ContinentMngr.cur()) && (UserEntity != NULL))
1272 ContinentMngr.cur()->FoW.explore((float)UserEntity->pos().x, (float)UserEntity->pos().y);
1274 // Check if the window size has changed.
1275 OldWidth = Width; OldHeight = Height;
1276 Driver->getWindowSize(Width, Height);
1279 // if yes, must update the camera perspective
1280 if(OldWidth!=Width || OldHeight!=Height)
1281 updateCameraPerspective();
1283 // Get Mouse Position.
1284 OldMouseX = MouseX; OldMouseY = MouseY;
1286 #ifdef RYZOM_BG_DOWNLOADER
1287 updateBGDownloaderUI();
1288 #endif
1291 // Get the pointer pos
1292 if(pIMinstance)
1294 H_AUTO_USE ( RZ_Client_Main_Loop_Cursor )
1296 // Change only if screen is not minimized
1297 if(!CViewRenderer::getInstance()->isMinimized())
1299 // Get the cursor instance
1300 CViewPointer *cursor = static_cast< CViewPointer* >( CWidgetManager::getInstance()->getPointer() );
1301 if(cursor)
1303 // Get the pointer position (in pixel)
1304 sint32 x, y;
1305 cursor->getPointerPos(x, y);
1307 uint32 w, h;
1308 CViewRenderer &viewRender = *CViewRenderer::getInstance();
1309 viewRender.getScreenSize(w, h);
1311 if(w)
1312 MouseX = (float)x/(float)w;
1313 else
1314 MouseX = 0;
1315 if(h)
1316 MouseY = (float)y/(float)h;
1317 else
1318 MouseY = 0;
1323 ///////////////////////
1324 // PROCESS THE FRAME //
1325 ///////////////////////
1326 // NetWork Update.
1330 NetMngr.update();
1331 IngameDbMngr.flushObserverCalls();
1332 NLGUI::CDBManager::getInstance()->flushObserverCalls();
1333 bool prevDatabaseInitStatus = IngameDbMngr.initInProgress();
1334 IngameDbMngr.setChangesProcessed();
1335 bool newDatabaseInitStatus = IngameDbMngr.initInProgress();
1336 if ((!newDatabaseInitStatus) && prevDatabaseInitStatus)
1338 // When database received, activate allegiance buttons (for neutral state) in fame window
1339 CInterfaceManager *pIM = CInterfaceManager::getInstance();
1340 CInterfaceGroup *group = dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:fame:content:you"));
1341 if (group)
1342 group->updateAllLinks();
1343 // send a msg to lua for specific ui update
1344 CLuaManager::getInstance().executeLuaScript("game:onInGameDbInitialized()");
1349 // For Debug (after netmngr update). Log entity stage change.
1350 EntitiesMngr.logStageChange(T1);
1352 // Update Ryzom Time.
1354 H_AUTO_USE ( RZ_Client_Main_Loop_Time_Update )
1355 if (!ClientCfg.Local)
1357 if(NetMngr.getCurrentServerTick() > LastGameCycle)
1358 RT.updateRyzomClock(NetMngr.getCurrentServerTick());
1360 else if (ClientCfg.SimulateServerTick)
1362 SimulatedServerDate += DT;
1363 uint numTicks = (uint) floor(SimulatedServerDate * 10);
1364 SimulatedServerTick += numTicks;
1365 SimulatedServerDate = (float)((double)SimulatedServerDate - (double) numTicks * 0.1);
1366 RT.updateRyzomClock((uint32)SimulatedServerTick);
1370 updateDayNightCycleHour();
1374 updateSmoothedTime();
1376 if (!ClientCfg.Light)
1378 // Call a function for a demo to update.
1379 if(ClientCfg.Local)
1381 updateDemo( (double)(T1-T0)*0.001 );
1385 // R2ED pre render update
1386 if (ClientCfg.R2EDEnabled)
1388 R2::getEditor().updatePreCamera();
1392 * Update position of all the primitives. Make a PACS move.
1394 EntitiesMngr.updatePreCamera();
1396 // Snap the user entity on the ground
1397 UserEntity->snapToGround();
1400 // update bot chat
1401 CBotChatManager::getInstance()->update();
1402 IngameDbMngr.flushObserverCalls();
1403 NLGUI::CDBManager::getInstance()->flushObserverCalls();
1405 // updateItemEdition
1406 CInterfaceItemEdition::getInstance()->update();
1409 * Update user controls and compute the camera position
1411 UserControls.update();
1413 // Update Landscape RefineCenter
1414 if (Landscape) Landscape->setRefineCenterUser(View.refinePos());
1416 // Update camera recorder, possibly replacing current view
1417 updateCameraRecorder();
1419 // Update Camera Position/Orientation.
1420 CVector currViewPos = View.currentViewPos();
1421 MainCam.setTransformMode(UTransformable::RotQuat);
1422 MainCam.setPos(currViewPos);
1423 MainCam.setRotQuat(View.currentViewQuat());
1424 if (StereoHMD)
1426 CMatrix camMatrix;
1427 camMatrix.translate(MainCam.getMatrix().getPos());
1428 CVector dir = MainCam.getMatrix().getJ();
1429 dir.z = 0;
1430 dir.normalize();
1431 if (dir.y < 0)
1432 camMatrix.rotateZ(float(NLMISC::Pi+asin(dir.x)));
1433 else
1434 camMatrix.rotateZ(float(NLMISC::Pi+NLMISC::Pi-asin(dir.x)));
1436 StereoHMD->setInterfaceMatrix(camMatrix);
1438 NLMISC::CQuat hmdOrient = StereoHMD->getOrientation();
1439 // NLMISC::CMatrix camMatrix = MainCam.getMatrix();
1440 NLMISC::CMatrix hmdMatrix;
1441 hmdMatrix.setRot(hmdOrient);
1442 NLMISC::CMatrix posMatrix; // minimal head modeling, will be changed in the future
1443 posMatrix.translate(StereoHMD->getEyePosition());
1444 NLMISC::CMatrix mat = ((camMatrix * hmdMatrix) * posMatrix);
1445 MainCam.setPos(mat.getPos());
1446 MainCam.setRotQuat(mat.getRot());
1448 if (true) // TODO: ClientCfg.Headphone
1450 // NOTE: non-(StereoHMD+Headphone) impl in user_entity.cpp
1451 SoundMngr->setListenerPos(mat.getPos()); // TODO: Move ears back ... :)
1452 SoundMngr->setListenerOrientation(mat.getJ(), mat.getK());
1455 if (StereoDisplay)
1457 StereoDisplay->updateCamera(0, &MainCam);
1458 if (SceneRoot)
1460 UCamera cam = SceneRoot->getCam();
1461 StereoDisplay->updateCamera(1, &cam);
1465 // see if camera is below water (useful for sort order)
1466 if (ContinentMngr.cur())
1468 float waterHeight;
1469 bool splashEnabled;
1470 if (ContinentMngr.cur()->WaterMap.getWaterHeight(CVector2f(currViewPos.x, currViewPos.y), waterHeight, splashEnabled))
1472 // camera is above / below a water surface
1473 Scene->setLayersRenderingOrder(currViewPos.z > waterHeight);
1474 UserEntity->setOrderingLayer(currViewPos.z > waterHeight ? 0 : 2);
1476 else
1478 UserEntity->setOrderingLayer(2);
1479 Scene->setLayersRenderingOrder(true);
1483 // Build the camera clipping planes
1484 vector<CPlane> planes;
1485 buildCameraClippingPyramid (planes);
1488 * Clip the entities.
1489 * Update display for visible entities.
1490 * Update display for clipped entities at a lower frequency.
1492 static uint clippedUpdateTime = 0;
1493 EntitiesMngr.updatePostCamera(clippedUpdateTime, planes, MainCam.getPos());
1494 clippedUpdateTime++;
1495 clippedUpdateTime&=RZ_CLIPPED_UPDATE_TIME_MASK;
1497 // Update the position for the vision.
1498 NetMngr.setReferencePosition(UserEntity->pos());
1500 // For Debug (after entities update). Log entity stage change.
1501 EntitiesMngr.logStageChange(T1);
1503 if (!ClientCfg.Light)
1505 // Animate all the playlists
1506 EAM->setup (TimeInSec);
1510 // update the sound of the player (walk, run....) if sound is allocated.
1511 updateSound();
1513 if (Landscape)
1515 if (!ClientCfg.Light)
1517 // Not in an indoor ?
1518 if (ContinentMngr.cur() && !ContinentMngr.cur()->Indoor)
1520 // Load Zone in streaming according to the refine position (not necessarily the User Position);
1521 string zoneAdded, zoneRemoved;
1522 const R2::CScenarioEntryPoints::CCompleteIsland *ci = R2::CScenarioEntryPoints::getInstance().getCompleteIslandFromCoords(CVector2f((float) UserEntity->pos().x, (float) UserEntity->pos().y));
1523 Landscape->refreshZonesAround(View.refinePos(), ClientCfg.Vision + ExtraZoneLoadingVision, zoneAdded, zoneRemoved, ci ? &(ci->ZoneIDs) : NULL);
1524 LandscapeIGManager.loadZoneIG(zoneAdded);
1525 LandscapeIGManager.unloadZoneIG(zoneRemoved);
1530 // Update PACS
1531 if(GR)
1532 GR->refreshLrAround (View.refinePos(), LRRefeshRadius);
1534 // load / unload streamable obj (villages ...)
1535 if (ClientCfg.VillagesEnabled)
1537 ContinentMngr.updateStreamable(View.refinePos());
1540 if (!ClientCfg.Light)
1542 // Load / unload streaming Instances textures.
1543 Driver->updateAsyncTexture();
1545 // Manage Fx
1546 manageFxEntities();
1548 // Animate all systems in scene.
1549 Scene->animate(TimeInSec-FirstTimeInSec);
1554 if (!ClientCfg.Light)
1556 CClientDate newDate(RT.getRyzomDay(), DayNightCycleHour);
1557 if (newDate < CTimedFXManager::getInstance().getDate() ||
1558 abs((sint32)RT.getRyzomDay() - CTimedFXManager::getInstance().getDate().Day) > 1)
1560 // The manager make the assumption that no more than one day can occurs between 2 ticks
1561 // This only happens when date is changed manually
1562 if (IGCallbacks)
1564 IGCallbacks->changeSeason(); // the season doesn't change, but this force fxs to be recreated
1567 CTimedFXManager::getInstance().update(newDate, CurrSeason, Scene->getCam().getPos());
1569 CProjectileManager::getInstance().update();
1571 // temp temp : for debug
1572 //TestGroundFX.update();
1576 // Set the right camera cluster.
1577 if(GR)
1579 UInstanceGroup *pPlayerClusterSystem = NULL;
1581 // Normal Mode
1582 if(UserControls.mode() != CUserControls::ThirdMode)
1584 // get the Pacs global position of the camera
1585 UGlobalPosition gPos;
1586 if((UserControls.mode() != CUserControls::AIMode)
1587 && UserEntity->getPrimitive())
1588 UserEntity->getPrimitive()->getGlobalPosition(gPos, dynamicWI);
1589 else
1590 gPos = GR->retrievePosition(View.viewPos());
1592 // get the cluster IG associated to this pacs position
1593 pPlayerClusterSystem = getCluster(gPos);
1594 MainCam.setClusterSystem(pPlayerClusterSystem);
1596 // important to update this each frame, for shadow map consideration against the "matis serre bug"
1597 CollisionManager->setPlayerInside(pPlayerClusterSystem!=NULL);
1599 // Camera 3rd person complex mode
1600 else
1602 UGlobalPosition gPos;
1603 if(UserEntity->getPrimitive())
1604 UserEntity->getPrimitive()->getGlobalPosition(gPos, dynamicWI);
1605 // get the cluster IG associated to this pacs position
1606 pPlayerClusterSystem = getCluster(gPos);
1608 // set the one found in CView::updateCameraCollision()
1609 MainCam.setClusterSystem(View.getThirdPersonClusterSystem());
1611 // important to update this each frame, for shadow map consideration against the "matis serre bug"
1612 CollisionManager->setPlayerInside(pPlayerClusterSystem!=NULL);
1614 // For debug only
1615 View.getCamera3rdPersonSetup(LastDebugClusterCameraThirdPersonStart,
1616 LastDebugClusterCameraThirdPersonEnd,
1617 LastDebugClusterCameraThirdPersonTestStart);
1618 LastDebugClusterCameraThirdPersonResult= View.currentViewPos();
1619 LastDebugClusterCameraThirdPersonPelvisPos= View.viewPos() + CVector(0.f,0.f,1.f);
1620 LastDebugClusterCameraThirdPersonForceFPV= View.forceFirstPersonView();
1621 // TestYoyo
1622 //CameraThirPersonGraph.addOneValue ((startPos - endPos).norm());
1625 // If we are flushing open all doors
1626 if (SkipFrame > 0)
1628 // update only the cluster system where the player is!
1629 if (pPlayerClusterSystem != NULL)
1631 static vector<string> PortalsName;
1632 PortalsName.clear();
1633 pPlayerClusterSystem->getDynamicPortals(PortalsName);
1634 for (uint32 i = 0; i < PortalsName.size(); ++i)
1635 pPlayerClusterSystem->setDynamicPortal (PortalsName[i], true);
1641 // R2ED pre render update
1642 if (ClientCfg.R2EDEnabled)
1644 R2::getEditor().updateBeforeRender();
1647 if (!ClientCfg.Light)
1649 // Render
1650 if(Render)
1652 // Update water env map (happens when continent changed etc)
1653 updateWaterEnvMap();
1655 // Update weather
1656 updateWeather();
1660 uint i = 0;
1661 CTextureUser *effectRenderTarget = NULL;
1662 bool haveEffects = Render && Driver->getPolygonMode() == UDriver::Filled
1663 && (ClientCfg.Bloom || FXAA);
1664 bool defaultRenderTarget = false;
1665 if (haveEffects)
1667 if (!StereoDisplay)
1669 Driver->beginDefaultRenderTarget();
1670 defaultRenderTarget = true;
1672 if (ClientCfg.Bloom)
1674 CBloomEffect::getInstance().setSquareBloom(ClientCfg.SquareBloom);
1675 CBloomEffect::getInstance().setDensityBloom((uint8)ClientCfg.DensityBloom);
1678 bool fullDetail = false;
1679 while ((!StereoDisplay && i == 0) || (StereoDisplay && StereoDisplay->nextPass()))
1681 ++i;
1682 ///////////////////
1683 // SETUP CAMERAS //
1684 ///////////////////
1686 if (StereoDisplay)
1688 // modify cameras for stereo display
1689 const CViewport &vp = StereoDisplay->getCurrentViewport();
1690 Driver->setViewport(vp);
1691 nlassert(Scene);
1692 Scene->setViewport(vp);
1693 if (SceneRoot)
1695 SceneRoot->setViewport(vp);
1697 //MainCam.setTransformMode(UTransformable::DirectMatrix);
1698 StereoDisplay->getCurrentMatrix(0, &MainCam);
1699 StereoDisplay->getCurrentFrustum(0, &MainCam);
1700 if (SceneRoot)
1702 // matrix updated during commitCamera from maincam
1703 UCamera cam = SceneRoot->getCam();
1704 StereoDisplay->getCurrentFrustum(1, &cam);
1708 // Commit camera changes
1709 commitCamera();
1711 //////////////////////////
1712 // RENDER THE FRAME 3D //
1713 //////////////////////////
1715 bool stereoRenderTarget = (StereoDisplay != NULL) && StereoDisplay->beginRenderTarget();
1717 if (!StereoDisplay || StereoDisplay->wantClear())
1719 // Clear buffers
1720 clearBuffers();
1723 if (!StereoDisplay || StereoDisplay->wantScene())
1725 if (!ClientCfg.Light && Render)
1727 if (!StereoDisplay || StereoDisplay->isSceneFirst())
1729 // nb : force full detail if a screenshot is asked
1730 // todo : move outside render code
1731 if (!fullDetail)
1733 fullDetail = ScreenshotRequest != ScreenshotRequestNone && ClientCfg.ScreenShotFullDetail;
1734 if (fullDetail)
1736 s_ForceFullDetail.backup();
1737 s_ForceFullDetail.set();
1742 // Render scene
1743 bool wantTraversals = !StereoDisplay || StereoDisplay->isSceneFirst();
1744 bool keepTraversals = StereoDisplay && !StereoDisplay->isSceneLast();
1745 doRenderScene(wantTraversals, keepTraversals);
1747 if (!StereoDisplay || StereoDisplay->isSceneLast())
1749 if (fullDetail)
1751 s_ForceFullDetail.restore();
1752 fullDetail = false;
1758 if (!StereoDisplay || StereoDisplay->wantSceneEffects())
1760 if (!ClientCfg.Light && Render && haveEffects)
1762 if (StereoDisplay) Driver->setViewport(NL3D::CViewport());
1763 UCamera pCam = Scene->getCam();
1764 Driver->setMatrixMode2D11();
1765 if (FXAA) FXAA->applyEffect();
1766 if (ClientCfg.Bloom) CBloomEffect::instance().applyBloom();
1767 Driver->setMatrixMode3D(pCam);
1768 if (StereoDisplay) Driver->setViewport(StereoDisplay->getCurrentViewport());
1772 if (!StereoDisplay || StereoDisplay->wantInterface3D())
1774 if (!ClientCfg.Light)
1776 // Render
1777 if (Render)
1779 // for that frame and
1780 // tmp : display height grid
1781 //static volatile bool displayHeightGrid = true;
1782 /*if (displayHeightGrid)
1784 HeightGrid.display(*Driver);
1786 // display results?
1787 if(Scene_Profile)
1789 displaySceneProfiles();
1790 Scene_Profile= false;
1792 // Render the primitives
1794 H_AUTO_USE ( RZ_Client_Main_Loop_Debug )
1795 PrimFiles.display (*Driver);
1797 } /* if (Render) */
1799 // Draw Extra 3D Objects
1800 Driver->setMatrixMode3D(MainCam);
1801 Driver->setModelMatrix(CMatrix::Identity);
1803 // Display PACS borders.
1804 if (PACSBorders)
1806 H_AUTO_USE ( RZ_Client_Main_Loop_Debug )
1807 displayPACSBorders();
1808 displayPACSPrimitive();
1811 // Display PACS borders only (for ARK).
1812 if (ARKPACSBorders)
1814 displayPACSPrimitive();
1817 // display Sound box
1818 if (SoundBox)
1820 H_AUTO_USE ( RZ_Client_Main_Loop_Debug )
1821 displaySoundBox();
1824 // display Debug of Clusters
1825 if (DebugClusters)
1827 H_AUTO_USE ( RZ_Client_Main_Loop_Debug )
1828 displayDebugClusters();
1830 } /* if (!ClientCfg.Light) */
1831 else
1833 // static UTextureFile *backgroundBitmap = NULL;
1834 // if (backgroundBitmap == NULL)
1835 // backgroundBitmap = Driver->createTextureFile("temp_background.tga");
1836 // Driver->setMatrixMode2D11();
1837 // Driver->drawBitmap (0.f, 0.f, 1024.f/1024.f, 1024.f/768.f, (UTexture&)*backgroundBitmap);
1838 // Driver->setMatrixMode3D(MainCam);
1840 Driver->clearBuffers(CRGBA (0,0,0,0));
1841 displayPACSBorders();
1842 displayPACSPrimitive();
1845 if (!ClientCfg.Light && !Landscape)
1847 displayPACSBorders();
1850 // Display some things not in the scene like the name, the entity path, etc.
1851 EntitiesMngr.updatePostRender();
1853 // Render the stat graphs if needed
1855 H_AUTO_USE ( RZ_Client_Main_Loop_Debug )
1856 CGraph::render (ShowInfos);
1859 } /* if (!StereoDisplay || StereoDisplay->wantInterface3D()) */
1861 if (!StereoDisplay || StereoDisplay->wantInterface2D())
1863 // Render in 2D Mode to display 2D Interfaces and 2D texts.
1864 Driver->setMatrixMode2D11();
1866 // draw a big quad to represent thunder strokes
1867 /*if (Render && WeatherManager.getThunderLevel() != 0.f)
1869 H_AUTO_USE ( RZ_Client_Main_Loop_Render_Thunder )
1870 Driver->drawQuad(0, 0, 1, 1, ThunderColor);
1872 // TODO : boris : add sound here !
1873 // Needs more explosions
1876 // Update the contextual menu
1878 H_AUTO_USE ( RZ_Client_Main_Loop_Interface )
1880 // Update the game cursor.
1881 ContextCur.check();
1882 GameContextMenu.update();
1884 // validate dialogs
1885 validateDialogs(GameContextMenu);
1887 // Display interface v3
1888 Driver->enableFog (false);
1889 if (!Driver->isLost())
1891 if(ShowInterface)
1892 pIMinstance->updateFrameViews (MainCam);
1893 if(DebugUIView)
1894 pIMinstance->displayUIViewBBoxs(DebugUIFilter);
1895 if(DebugUICtrl)
1896 pIMinstance->displayUICtrlBBoxs(DebugUIFilter);
1897 if(DebugUIGroup)
1898 pIMinstance->displayUIGroupBBoxs(DebugUIFilter);
1901 // special case in OpenGL : all scene has been display in render target,
1902 // now, final texture is display with a quad
1903 /*if (!ClientCfg.Light && ClientCfg.Bloom && Render && bloomStage == 2) // NO VR BLOOMZ
1905 // End bloom effect system after drawing the 3d interface (z buffer related).
1906 if (StereoDisplay) Driver->setViewport(NL3D::CViewport());
1907 CBloomEffect::instance().endInterfacesDisplayBloom();
1908 if (StereoDisplay) Driver->setViewport(StereoDisplay->getCurrentViewport());
1909 bloomStage = 0;
1914 H_AUTO_USE ( RZ_Client_Main_Loop_Debug )
1915 if (!Driver->isLost())
1917 // If show information is Active.
1918 if(ShowInfos == 1)
1919 displayDebug();
1921 // If show information is Active.
1922 if(ShowInfos == 2)
1923 displayNetDebug();
1925 // If show information is Active.
1926 if(ShowInfos == 4)
1927 displayDebugFps();
1929 // If show information is Active.
1930 if(ShowInfos == 5)
1931 displayDebugUIUnderMouse();
1933 // If show information is Active.
1934 displayStreamingDebug();
1936 // If Show Help is active -> Display an help.
1937 if(ShowHelp)
1938 displayHelp();
1940 // Yoyo: indicate profiling state
1941 if( Profiling )
1942 displaySpecialTextProgress("Profiling");
1944 // Display frame rate
1946 // Create a shadow when displaying a text.
1947 TextContext->setShaded(true);
1948 TextContext->setShadeOutline(false);
1949 // Set the font size.
1950 TextContext->setFontSize(10);
1951 // Set the text color
1952 TextContext->setColor(CRGBA(255,255,255));
1954 // temporary values for conversions
1955 float x, y, width, height;
1957 for(uint i = 0; i < ClientCfg.Logos.size(); i++)
1959 std::vector<string> res;
1960 explode(ClientCfg.Logos[i],std::string(":"), res);
1961 if(res.size()==9 && i<LogoBitmaps.size() && LogoBitmaps[i]!=NULL)
1963 fromString(res[5], x);
1964 fromString(res[6], y);
1965 fromString(res[7], width);
1966 fromString(res[8], height);
1967 Driver->drawBitmap(x/(float)ClientCfg.Width, y/(float)ClientCfg.Height, width/(float)ClientCfg.Width, height/(float)ClientCfg.Height, *LogoBitmaps[i]);
1973 // FPS
1975 static TTicks oldTick = CTime::getPerformanceTime();
1976 TTicks newTick = CTime::getPerformanceTime();
1977 double deltaTime = CTime::ticksToSecond (newTick-oldTick);
1978 oldTick = newTick;
1979 smoothFPS.addValue((float)deltaTime);
1980 moreSmoothFPS.addValue((float)deltaTime);
1981 deltaTime = smoothFPS.getSmoothValue ();
1982 if (deltaTime > 0.0)
1984 CCDBNodeLeaf *pNL = s_FpsLeaf ? &*s_FpsLeaf
1985 : &*(s_FpsLeaf = NLGUI::CDBManager::getInstance()->getDbProp("UI:VARIABLES:FPS"));
1986 pNL->setValue64((sint64)(1.f/deltaTime));
1990 // R2ED post render update
1991 if (ClientCfg.R2EDEnabled)
1993 // IMPORTANT : this should be called after CEntitiesMngr::updatePostRender() because
1994 // entity may be added / removed there !
1995 R2::getEditor().updateAfterRender();
1998 // Update FXs (remove them).
1999 FXMngr.update();
2001 // Detect disconnection / server down: display information text
2002 // but keep the rendering so that the player can remember where he is
2003 // and what he was doing. He can't move because the connection quality returns false.
2005 if ((connectionState == CNetworkConnection::Disconnect) && (lastConnectionState != CNetworkConnection::Disconnect) && (!FarTP.isFarTPInProgress()))
2007 UserControls.stopFreeLook(); // let the player click on Exit
2008 pIMinstance->messageBoxWithHelp(CI18N::get("uiDisconnected"));
2010 // If we have started a Far TP sequence and are waiting for onServerQuitOK()
2011 // from the EGS, resume the sequence because the EGS is down and won't reply.
2012 FarTP.onServerQuitOk();
2015 // Yoyo: MovieShooter.
2016 if(MovieShooterSaving)
2018 H_AUTO_USE ( RZ_Client_Main_Loop_Debug )
2020 // Add the buffer frame to the movie.
2021 if(!MovieShooter.addFrame(TimeInSec, Driver))
2023 // Fail to add the frame => abort.
2024 endMovieShooting();
2026 else
2028 // Ok, just add a display.
2029 displaySpecialTextProgress("MovieShooting");
2033 if (isRecordingCamera())
2035 displaySpecialTextProgress("CameraRecording");
2038 // Temp for weather test
2039 if (ClientCfg.ManualWeatherSetup)
2041 H_AUTO_USE ( RZ_Client_Main_Loop_Debug )
2042 static float displayHourDelta = 0.04f; // static for edition during debug..
2044 // Display weather function
2045 if (DisplayWeatherFunction)
2047 uint64 currDay = RT.getRyzomDay();
2048 float currHour = DayNightCycleHour;
2049 float singleHourDelta = fmodf(currHour, 1.f);
2050 uint32 wndWidth, wndHeight;
2051 Driver->getWindowSize(wndWidth, wndHeight);
2052 Driver->setMatrixMode2D(CFrustum(0, 800, 600, 0, 0, 1, false));
2053 const float lineHeight = 100.f;
2055 // draw the weather function
2056 for(uint x = 0; x < wndWidth; ++x)
2058 float weatherValue;
2059 if(ContinentMngr.cur())
2060 weatherValue = ::getBlendedWeather(currDay, currHour, *WeatherFunctionParams, ContinentMngr.cur()->WeatherFunction);
2061 else
2062 weatherValue = ::getBlendedWeather(currDay, currHour, *WeatherFunctionParams, 0);
2064 NLMISC::clamp(weatherValue, 0.f, 1.f);
2065 CRGBA seasonToColor[EGSPD::CSeason::Invalid] =
2067 CRGBA::Green,
2068 CRGBA::Yellow,
2069 CRGBA::Red,
2070 CRGBA::Blue
2072 Driver->drawLine((float) x, 0.f, (float) x, lineHeight * weatherValue, seasonToColor[CRyzomTime::getSeasonByDay((uint32)currDay)]);
2073 currHour += displayHourDelta;
2074 if (currHour >= 24.f)
2076 ++currDay;
2077 currHour -= 24.f;
2079 singleHourDelta += displayHourDelta;
2080 if (singleHourDelta >= 1.f)
2082 singleHourDelta -= 1.f;
2083 Driver->drawLine((float) x, 100.f, (float) x, 130, CRGBA::Red);
2087 if(ContinentMngr.cur())
2089 // draw lines for current weather setups
2090 uint numWeatherSetups = ContinentMngr.cur()->WeatherFunction[CurrSeason].getNumWeatherSetups();
2091 for (uint y = 0; y < numWeatherSetups; ++y)
2093 float py = lineHeight * (y / (float) numWeatherSetups);
2094 Driver->drawLine(0.f, py, 800.f, py, CRGBA::Magenta);
2099 // Ctrl+ & Ctrl- change the weather value
2100 if (Actions.valide ("inc_time"))
2102 ManualWeatherValue += DT * 0.04f;
2104 if (Actions.valide ("dec_time"))
2106 ManualWeatherValue -= DT * 0.04f;
2108 NLMISC::clamp(ManualWeatherValue, 0.f, 1.f);
2110 if (ForcedDayNightCycleHour < 0) // if time is forced then can't change it manually ...
2112 // Ctrl-K increase hour
2113 if (Actions.valide ("inc_hour"))
2115 RT.increaseTickOffset( (uint32)(2000 * displayHourDelta) );
2116 RT.updateRyzomClock(NetMngr.getCurrentServerTick());
2119 // Ctrl-L decrease hour
2120 if (Actions.valide ("dec_hour"))
2122 RT.decreaseTickOffset( (uint32)(2000 * displayHourDelta) );
2123 RT.updateRyzomClock(NetMngr.getCurrentServerTick());
2124 CTimedFXManager::getInstance().setDate(CClientDate(RT.getRyzomDay(), (float) RT.getRyzomTime()));
2125 if (IGCallbacks)
2127 IGCallbacks->changeSeason(); // the season doesn't change, but this force fxs to be recreated
2132 // Ctrl-M generate statistics in a file
2134 if (Actions.valide ("weather_stats"))
2136 // Only usable if there is a continent loaded.
2137 if(ContinentMngr.cur())
2138 CPredictWeather::generateWeatherStats("weather_stats.csv", WeatherFunctionParams, ContinentMngr.cur()->WeatherFunction);
2141 // Ctrl-B decrease display factor
2142 if (Actions.valide ("dec_display_factor"))
2144 displayHourDelta *= 0.90f;
2146 // Ctrl-J increase display factor
2147 if (Actions.valide ("inc_display_factor"))
2149 displayHourDelta *= 1.1f;
2150 displayHourDelta = std::min(1000.f, displayHourDelta);
2154 // Ctrl-AltGR-Z show timed FXs
2155 if (ShowTimedFX)
2157 if (!Driver->isLost())
2159 CTimedFXManager::getInstance().displayFXBoxes(ShowTimedFXMode);
2163 #if !FINAL_VERSION
2164 CVector2f camPos(Scene->getCam().getPos().x, Scene->getCam().getPos().y);
2165 if (!ClientCfg.Light)
2167 if (DisplayMicroLifeZones)
2169 CMicroLifeManager::getInstance().renderMLZones(camPos);
2172 if (DisplayWaterMap)
2174 if (ContinentMngr.cur())
2176 ContinentMngr.cur()->WaterMap.render(camPos);
2179 #endif
2181 #ifdef NL_DEBUG
2182 if (!ClientCfg.Light)
2184 if (DisplayMicroLifeActiveTiles)
2186 CMicroLifeManager::getInstance().renderActiveTiles();
2189 #endif
2190 // tmp : debug of ground fxs
2191 //TestGroundFX.displayFXBoxes();
2193 // Temp for sound debug
2195 H_AUTO_USE ( RZ_Client_Main_Loop_Debug )
2197 if (SoundMngr != 0)
2199 static bool drawSound = false;
2200 static float camHeigh = 150.0f;
2202 #if FINAL_VERSION
2203 if (ClientCfg.ExtendedCommands)
2204 #endif
2205 if (Actions.valide ("draw_sound"))
2206 drawSound = !drawSound;
2208 if (Actions.valide ("inc_camera_height"))
2209 camHeigh -= 10.0f;
2210 if (Actions.valide ("dec_camera_height"))
2211 camHeigh += 10.0f;
2213 if (drawSound)
2214 SoundMngr->drawSounds(camHeigh);
2217 } /* if (!StereoDisplay || StereoDisplay->wantInterface2D()) */
2219 if (StereoDisplay)
2221 StereoDisplay->endRenderTarget();
2223 } /* stereo pass */
2225 if (defaultRenderTarget)
2227 // draw final result to backbuffer
2228 Driver->endDefaultRenderTarget(Scene);
2231 // Draw to screen.
2232 static CQuat MainCamOri;
2233 if (FirstFrame)
2235 // Frame to skip before swap buffer
2236 SkipFrame = RYZOM_FIRST_FRAME_TO_SKIP;
2237 FirstFrame = false;
2238 MainCam.getRotQuat(MainCamOri);
2241 if (SkipFrame == 0)
2243 if (StartPlayTime == 0)
2245 StartPlayTime = NLMISC::CTime::getLocalTime();
2248 // Start background sound play now ! (nb: restarted if load just ended, or if sound re-enabled)
2249 if (SoundMngr)
2251 H_AUTO_USE ( RZ_Client_Main_Loop_Sound )
2253 // fade out loading music
2254 if (SoundMngr->getEventMusicPlayed() == LoadingMusic)
2256 SoundMngr->stopEventMusic(LoadingMusic, CSoundManager::LoadingMusicXFade);
2259 SoundMngr->playBackgroundSound();
2261 // Fade in Game Sound now (before endLoading)
2262 // fade in game sound
2263 SoundMngr->fadeInGameSound(ClientCfg.SoundTPFade);
2266 // end loading (if previous load)
2267 endLoading ();
2269 // if a screenshot request was made then do it now
2270 switch(ScreenshotRequest)
2272 case ScreenshotRequestTGA:
2273 screenShotTGA();
2274 ScreenshotRequest = ScreenshotRequestNone;
2275 break;
2276 case ScreenshotRequestJPG:
2277 screenShotJPG();
2278 ScreenshotRequest = ScreenshotRequestNone;
2279 break;
2280 case ScreenshotRequestPNG:
2281 screenShotPNG();
2282 ScreenshotRequest = ScreenshotRequestNone;
2283 break;
2284 default:
2285 break;
2288 // TMP TMP
2289 static volatile bool dumpValidPolys = false;
2290 if (dumpValidPolys) { tempDumpValidPolys(); dumpValidPolys = false; }
2292 // TMP TMP
2293 static volatile bool dumpColPolys = false;
2294 if (dumpColPolys) { tempDumpColPolys(); }
2296 if (ClientCfg.R2EDEnabled)
2298 R2::getEditor().updateBeforeSwapBuffer();
2301 Driver->swapBuffers();
2303 if(Profiling)
2305 ++ ProfileNumFrame;
2306 if (ProfileNumFrame == ClientCfg.NumFrameForProfile)
2308 WantProfiling = true;
2312 // If the device is lost then no rendering will occur, so let some time to other applications
2313 if (Driver->isLost())
2315 nlSleep(50);
2316 nldebug("lost device");
2319 else
2321 SkipFrame--;
2323 // Turn the camera to make a 360 degree turn
2324 // UTransformable::TTransformMode m = MainCam.getTransformMode();
2325 if (SkipFrame == 0)
2327 MainCam.setRotQuat(MainCamOri);
2329 else
2331 CMatrix mat = CMatrix::Identity;
2332 mat.setRot(MainCamOri);
2333 mat.rotateZ(2*(float)Pi*((float)(SkipFrame)/(float)RYZOM_FIRST_FRAME_TO_SKIP));
2334 CQuat qTmp;
2335 mat.getRot(qTmp);
2336 MainCam.setRotQuat(qTmp);
2341 // Force the client to sleep a bit.
2342 if(ClientCfg.Sleep >= 0)
2344 H_AUTO_USE ( RZ_Client_Main_Loop_Debug )
2345 nlSleep(ClientCfg.Sleep);
2348 //++MainLoopCounter;
2350 // Send new data Only when server tick changed.
2351 if(NetMngr.getCurrentServerTick() > LastGameCycle)
2353 H_AUTO_USE ( RZ_Client_Main_Loop_Net )
2354 // Put here things you have to send to the server only once per tick like user position.
2355 // UPDATE COMPASS
2356 NLMISC::CCDBNodeLeaf *node = s_UiDirectionLeaf ? (&*s_UiDirectionLeaf)
2357 : &*(s_UiDirectionLeaf = NLGUI::CDBManager::getInstance()->getDbProp("UI:VARIABLES:DIRECTION"));
2358 CInterfaceProperty prop;
2359 prop.setNodePtr(node);
2360 if(CompassMode == 1)
2362 double camDir = atan2(View.view().y, View.view().x);
2363 prop.setDouble(camDir);
2365 else
2366 prop.setDouble(atan2(UserEntity->front().y, UserEntity->front().x));
2367 // Update the server with our position and orientation.
2369 CBitMemStream out;
2370 if(UserEntity->sendToServer(out))
2371 NetMngr.push(out);
2373 // Give information to the server about the combat position (ability to strike).
2375 CBitMemStream out;
2376 if(UserEntity->msgForCombatPos(out))
2377 NetMngr.push(out);
2380 // Create the message for the server to move the user (except in combat mode).
2381 if(Ping.rdyToPing())
2383 CBitMemStream out;
2384 if(GenericMsgHeaderMngr.pushNameToStream("DEBUG:PING", out))
2386 const TTime mask = 0xFFFFFFFF;
2387 uint32 localTime = (uint32)(mask&ryzomGetLocalTime ());
2388 out.serial(localTime);
2389 NetMngr.push(out);
2391 Ping.rdyToPing(false);
2393 else
2394 nlwarning("mainloop: unknown message named 'DEBUG:PING'.");
2397 // Send the Packet.
2398 NetMngr.send(NetMngr.getCurrentServerTick());
2399 // Update the Last tick received from the server.
2400 LastGameCycle = NetMngr.getCurrentServerTick();
2403 if (ClientCfg.AutoReloadFiles)
2405 // Check for files update.
2406 CFile::checkFileChange();
2408 // Check for configuration files update.
2409 CConfigFile::checkConfigFiles();
2412 // Get the Connection State.
2413 lastConnectionState = connectionState;
2414 connectionState = NetMngr.getConnectionState();
2416 // Update movie shooter
2417 updateMovieShooting();
2419 // Update the bubble manager
2420 InSceneBubbleManager.update();
2422 // Update the NPC icon system
2423 CNPCIconCache::getInstance().update();
2425 // Update Phrase Manager
2426 CSPhraseManager *pPM= CSPhraseManager::getInstance();
2427 pPM->updateEquipInvalidation(NetMngr.getCurrentServerTick());
2428 pPM->updateAllActionRegen();
2430 // Update ingame duration and stat report sending
2431 updateStatReport ();
2433 // Auto play once on character login
2434 if (musicTriggerAutoPlay)
2436 musicTriggerAutoPlay = false;
2437 if (ClientCfg.SoundOn && ClientCfg.MediaPlayerAutoPlay)
2439 MusicPlayer.stop();
2440 CAHManager::getInstance()->runActionHandler("music_player", NULL, "play_songs");
2441 MusicPlayer.play();
2444 // Update the music player
2445 MusicPlayer.update ();
2447 // Memory Debug
2448 if (ClientCfg.CheckMemoryEveryNFrame != -1)
2450 static int frameToSkip = ClientCfg.CheckMemoryEveryNFrame;
2451 if (frameToSkip == 0)
2453 frameToSkip = ClientCfg.CheckMemoryEveryNFrame;
2454 //NLMEMORY::CheckHeap (true);
2456 else
2457 frameToSkip--;
2460 ///////////////
2461 // FAR_TP -> //
2462 ///////////////
2463 // Enter a network loop during the FarTP process, without doing the whole real main loop.
2464 // This code must remain at the very end of the main loop.
2465 if(LoginSM.getCurrentState() == CLoginStateMachine::st_enter_far_tp_main_loop)
2467 CLuaManager::getInstance().executeLuaScript("game:onFarTpStart()");
2468 // Will loop the network until the end of the relogging process
2469 FarTP.farTPmainLoop();
2471 if( FarTP.isReselectingChar() )
2473 if ( game_exit ) // check if the user has decided to quit
2474 break;
2476 // we have just completed init main loop, after reselecting character
2477 // repeat the steps before the main loop itself
2479 // new char, retrigger music autoplay
2480 musicTriggerAutoPlay = true;
2482 // pre main loop in mainLoop
2483 resetIngameTime ();
2485 game_exit = false;
2486 game_exit_request = false;
2487 FarTP.setMainLoopEntered();
2489 // Get the Width and Height of the window and set the Old values..
2490 Driver->getWindowSize(Width, Height);
2491 OldWidth = Width; OldHeight = Height;
2493 CGraph::init( Driver );
2494 CGraph::Display = false;
2496 T1 = ryzomGetLocalTime();
2497 TSend = ((T1+DTSend)/DTSend)*DTSend;
2499 SetMouseFreeLook ();
2500 SetMouseCursor ();
2501 // Set the cursor.
2502 ContextCur.context("STAND BY");
2503 UserControls.reset();
2505 // set the default box for keyboard
2506 CChatWindow *defaultChatWindow;
2507 if (ClientCfg.R2EDEnabled)
2509 defaultChatWindow = PeopleInterraction.DebugInfo;
2511 else
2513 defaultChatWindow = PeopleInterraction.ChatGroup.Window;
2515 setDefaultChatWindow(defaultChatWindow);
2517 // Init GameContextMenu.
2518 GameContextMenu.init("");
2520 // Active inputs
2521 Actions.enable(true);
2522 EditActions.enable(true);
2524 // check for banned player
2525 if (testPermanentBanMarkers())
2527 setPermanentBanMarkers(true); // re-set any marker that could have been removed by the trouble maker
2528 applyPermanentBanPunishment();
2529 PermanentlyBanned = true;
2533 // For stoping the outgame music, start after 30 frames, and duration of 3 seconds
2534 outgameFader = CMusicFader(60, 3);
2536 // Short reinit of the main loop after farTP or character reselection
2537 Ping.init();
2538 updateLightDesc();
2540 // R2ED enabled ?
2541 R2::getEditor().autoConfigInit(IsInRingSession);
2543 // TODO: temporary commented, CEditor must be initialized before to call next lines
2544 // if (!IsInRingSession)
2545 // R2::getEditor().registerLuaFunc();
2547 CurrSeason = computeCurrSeason();
2549 // Get the Connection State (must be done after any Far TP to prevent the uiDisconnected box to be displayed)
2550 lastConnectionState = CNetworkConnection::Connected;
2551 connectionState = NetMngr.getConnectionState();
2553 CLuaManager::getInstance().executeLuaScript("game:onFarTpEnd()");
2555 ///////////////
2556 // <- FAR_TP //
2557 ///////////////
2559 } // end of main loop
2561 CInterfaceManager *im = CInterfaceManager::getInstance();
2562 if (CLuaManager::getInstance().getLuaState())
2564 CLuaManager::getInstance().executeLuaScript("game:onMainLoopEnd()");
2567 // Stop Running Profiles (kick result)
2568 if(Profiling)
2570 WantProfiling= false;
2571 Profiling= false;
2572 CHTimer::endBench();
2573 Driver->endBench();
2575 if(ProfilingVBLock)
2577 WantProfilingVBLock= false;
2578 ProfilingVBLock= false;
2579 vector<string> strs;
2580 Driver->endProfileVBHardLock(strs);
2583 if ( ! FarTP.isReselectingChar() ) // skip some parts if the user wants to quit in the middle of a char reselect
2585 // Saving ingame resolution when in windowed mode
2586 saveIngameResolution();
2588 // Release the structure for the ping.
2589 Ping.release ();
2591 // Disable inputs
2592 Actions.enable(false);
2593 EditActions.enable(false);
2595 CWidgetManager::getInstance()->setDefaultCaptureKeyboard(NULL);
2597 // Interface saving
2598 CInterfaceManager::getInstance()->uninitInGame0();
2599 CItemGroupManager::getInstance()->uninit();
2601 /////////////////////////////////
2602 // Display the end background. //
2603 /////////////////////////////////
2604 // Create the loading texture.
2605 loadBackgroundBitmap (EndBackground);
2607 // TTime endTime = ryzomGetLocalTime () + (TTime)(ClientCfg.EndScreenTimeOut*1000.f);
2608 // do
2609 // {
2610 // // Grab Inputs.
2611 // CInputHandlerManager::getInstance()->pumpEventsNoIM();
2612 // Display the background
2613 drawLoadingBitmap (0);
2614 // Display to screen.
2615 Driver->swapBuffers();
2616 // } while(ryzomGetLocalTime () < endTime);
2618 // Destroy the Loading Background.
2619 destroyLoadingBitmap ();
2621 IngameDbMngr.resetInitState();
2624 ryzom_exit = true;
2626 return ryzom_exit || (Driver == NULL) || (!Driver->isActive ());
2627 }// mainLoop //
2629 //---------------------------------------------------
2630 // Just Display some text with ... anim at some place.
2631 //---------------------------------------------------
2632 void displaySpecialTextProgress(const char *text)
2634 // Create a shadow when displaying a text.
2635 TextContext->setShaded(true);
2636 TextContext->setShadeOutline(false);
2637 // Set the font size.
2638 TextContext->setFontSize(12);
2639 // Set the text color
2640 TextContext->setColor(CRGBA(255,255,255));
2642 TextContext->setHotSpot(UTextContext::BottomLeft);
2644 // cool .... anim.
2645 const uint MaxDot= 8;
2646 static uint counter=0;
2647 counter= (counter+1) % (MaxDot+1);
2648 // format counter.
2649 char str[MaxDot+1];
2650 uint i;
2651 for(i=0;i<counter;i++)
2652 str[i]= '.';
2653 str[counter]= 0;
2654 // display text
2655 TextContext->printfAt(0.05f,0.80f,"%s%s", text, str );
2659 //---------------------------------------------------
2660 // MovieShooter methods
2661 //---------------------------------------------------
2664 void endMovieShooting()
2666 MovieShooterSaving= false;
2669 bool MovieShooterReplay = false;
2670 bool MovieShooterSave = false;
2672 void updateMovieShooting()
2674 #ifdef _MOVIE_SHOOTER_ON_
2675 if (MovieShooterReplay)
2677 if(!MovieShooter.enabled())
2679 Driver->systemMessageBox("MovieShooter not enabled", "MovieShooter");
2681 else
2683 if( !MovieShooterSaving )
2687 MovieShooter.replayMovie(Driver, TextContext);
2689 catch (const Exception &e)
2691 Driver->systemMessageBox(e.what(), "MovieShooter");
2695 MovieShooterReplay = false;
2698 if (MovieShooterSave)
2700 if(!MovieShooter.enabled())
2702 Driver->systemMessageBox("MovieShooter not enabled", "MovieShooter");
2704 else
2706 if( !MovieShooterSaving )
2710 // Create a New Dir
2711 string theDir;
2712 uint num= 0;
2715 num++;
2716 char tmp[256];
2717 sprintf(tmp, "%03d", num);
2718 theDir= ClientCfg.MovieShooterPath + "/" + "Movie" + tmp;
2720 while( CFile::isDirectory(theDir) );
2721 // create the dir
2722 CFile::createDirectory(theDir);
2724 // Save the movie.
2725 MovieShooter.saveMovie(Driver, TextContext, theDir.c_str(), ClientCfg.MovieShooterFramePeriod, ClientCfg.MovieShooterBlend, ClientCfg.MovieShooterPrefix.c_str());
2727 catch (const Exception &e)
2729 Driver->systemMessageBox(e.what(), "MovieShooter");
2733 MovieShooterSave = false;
2735 #endif // _MOVIE_SHOOTER_ON_
2739 //---------------------------------------------------
2740 // updateSound :
2741 // update the listener pos and user walk/run/idle sound (stereo)
2742 //---------------------------------------------------
2743 void updateSound()
2745 if(SoundMngr)
2747 SoundMngr->update ();
2749 }// updateSound //
2754 //===================================================================================================
2755 void updateLightDesc()
2757 if (!ClientCfg.Light)
2759 // Update the lighting description (when season change, or for first setup)
2760 static bool init = false;
2761 EGSPD::CSeason::TSeason season = CurrSeason;
2762 if (!init || season != CurrSeason)
2764 CLightCycleDesc desc;
2765 buildLightCycleDesc(desc, CurrSeason);
2766 LightCycleManager.setLightDesc(desc);
2767 init = true;
2769 if (CurrSeason != season)
2771 CurrSeason = season;
2772 // also update seasonal fxs
2773 if (IGCallbacks)
2775 IGCallbacks->changeSeason();
2781 //===================================================================================================
2782 static void updateCloudScape(const CCloudState &desc, const CWeatherContext &wc, float /* wind */, float dayNight, float updateDelay, bool mustInit)
2784 if (!CloudScape) return;
2785 SCloudScapeSetup css;
2786 NLMISC::clamp(dayNight, 0.f, 1.f);
2787 css.CloudSpeed = desc.DiffusionSpeed;
2788 float duskRatio = LightCycleManager.getLightDesc().DuskRatio;
2789 switch(LightCycleManager.getState())
2791 case CLightCycleManager::DayToNight:
2792 if (dayNight < duskRatio) // day->dusk
2794 float blendFactor = duskRatio != 0 ? dayNight / duskRatio : 0.f;
2795 css.Ambient.blendFromui(desc.AmbientDay, desc.AmbientDusk, (uint) (256.f * blendFactor));
2796 css.Diffuse.blendFromui(desc.DiffuseDay, desc.DiffuseDusk, (uint) (256.f * blendFactor));
2798 else // dusk->night
2800 float blendFactor = duskRatio != 1 ? (dayNight - duskRatio) / (1.f - duskRatio) : 0.f;
2801 css.Ambient.blendFromui(desc.AmbientDusk, desc.AmbientNight, (uint) (256.f * blendFactor));
2802 css.Diffuse.blendFromui(desc.DiffuseDusk, desc.DiffuseNight, (uint) (256.f * blendFactor));
2804 break;
2805 default: // not a day->night transition, so no step for dusk
2806 css.Ambient.blendFromui(desc.AmbientDay, desc.AmbientNight, (uint) (256.f * dayNight));
2807 css.Diffuse.blendFromui(desc.DiffuseDay, desc.DiffuseNight, (uint) (256.f * dayNight));
2808 break;
2811 css.NbCloud = desc.NumClouds;
2812 css.WindSpeed = WeatherManager.getCurrWeatherState().WindIntensity * wc.WFP->CloudWindSpeedFactor + wc.WFP->CloudMinSpeed;
2813 if (mustInit)
2815 css.TimeToChange = 0;
2816 CloudScape->init(&css);
2817 CloudScape->setNbCloudToUpdateIn80ms (ClientCfg.CloudUpdate);
2818 CloudScape->setQuality (ClientCfg.CloudQuality);
2820 else
2822 css.TimeToChange = updateDelay;
2823 CloudScape->set(css);
2827 //===================================================================================================
2828 void updateClouds()
2830 // build a weather context
2831 CWeatherContext wc;
2832 wc.GR = GR;
2833 if(ContinentMngr.cur())
2834 wc.WF = ContinentMngr.cur()->WeatherFunction;
2835 else
2836 wc.WF = NULL;
2838 if (ClientCfg.ManualWeatherSetup && !ForceTrueWeatherValue)
2840 // Try to update the clouds quickly for manual test
2841 if (CloudScape)
2843 CCloudState cs;
2844 WeatherManager.computeCloudState(ManualWeatherValue, CurrSeason, cs, wc.WF);
2845 updateCloudScape(cs, wc, WeatherManager.getCurrWeatherState().WindIntensity, LightCycleManager.getLightLevel(), 1.f, InitCloudScape);
2846 InitCloudScape = false;
2849 else
2851 // update the clouds
2852 if (InitCloudScape)
2854 InitCloudScape = false;
2855 // 1 ) set current state
2856 CCloudState cs;
2857 WeatherManager.computeCloudState(RT.getRyzomDay(), DayNightCycleHour, wc, cs);
2858 updateCloudScape(cs, wc, WeatherManager.getCurrWeatherState().WindIntensity, LightCycleManager.getLightLevel(), 0.f, true);
2859 // 2 )set next state
2860 // compute date of next update
2861 const CLightCycleDesc &lcd = LightCycleManager.getLightDesc();
2862 float updateDelay = 0.f;
2863 if (lcd.RealDayLength != 0.f)
2865 updateDelay = CloudUpdatePeriod / lcd.RealDayLength * lcd.NumHours;
2867 WeatherManager.computeCloudState(RT.getRyzomDay(), DayNightCycleHour + updateDelay, wc, cs);
2868 updateCloudScape(cs, wc, WeatherManager.getCurrWeatherState().WindIntensity, LightCycleManager.getLightLevel(), 0.f, true);
2869 DelayBeforeCloudUpdate = CloudUpdatePeriod;
2871 else
2873 DelayBeforeCloudUpdate -= DT;
2874 if (DelayBeforeCloudUpdate <= 0.f)
2876 DelayBeforeCloudUpdate += CloudUpdatePeriod;
2877 if (DelayBeforeCloudUpdate <= 0.f)
2879 DelayBeforeCloudUpdate = CloudUpdatePeriod;
2881 // set next state
2882 // compute date of next update
2883 const CLightCycleDesc &lcd = LightCycleManager.getLightDesc();
2884 float updateDelay = 0.f;
2885 if (lcd.RealDayLength != 0.f)
2887 updateDelay = DelayBeforeCloudUpdate / lcd.RealDayLength * lcd.NumHours;
2889 CCloudState cs;
2890 WeatherManager.computeCloudState(RT.getRyzomDay(), DayNightCycleHour + updateDelay, wc, cs);
2891 updateCloudScape(cs, wc, WeatherManager.getCurrWeatherState().WindIntensity, LightCycleManager.getLightLevel(), updateDelay, false);
2898 //-----------------------------------------------
2899 // displayPACSBorders :
2900 // Display Borders from PACS.
2901 //-----------------------------------------------
2902 void displayPACSBorders()
2904 static std::vector<std::pair<NLMISC::CLine, uint8> > edges;
2905 if(UserEntity->getPrimitive())
2907 UGlobalPosition gPos;
2908 UserEntity->getPrimitive()->getGlobalPosition(gPos, dynamicWI);
2909 if (GR) GR->getBorders(gPos, edges);
2911 CLineColor line;
2912 // ...
2913 for(uint i=0; i<edges.size(); ++i)
2915 line = (edges[i].first);
2916 // Choose the color according to the edge type.
2917 switch(edges[i].second)
2919 // Block
2920 case 0:
2921 line.Color0 = CRGBA::Red;
2922 line.Color1 = CRGBA::Red;
2923 break;
2924 // Surmountable
2925 case 1:
2926 line.Color0 = CRGBA::Green;
2927 line.Color1 = CRGBA::Green;
2928 break;
2929 // Link
2930 case 2:
2931 line.Color0 = CRGBA::Yellow;
2932 line.Color1 = CRGBA::Yellow;
2933 break;
2934 // Waterline
2935 case 3:
2936 line.Color0 = CRGBA::Blue;
2937 line.Color1 = CRGBA::Blue;
2938 break;
2939 case 4: // Exterior
2940 line.Color0 = CRGBA::Magenta;
2941 line.Color1 = CRGBA::Magenta;
2942 break;
2943 case 5: // Exterior door
2944 line.Color0 = CRGBA(127, 127, 127);
2945 line.Color1 = CRGBA(127, 127, 127);
2946 break;
2947 // Unknown
2948 default:
2949 line.Color0 = CRGBA::White;
2950 line.Color1 = CRGBA::White;
2951 break;
2953 // Draw the line.
2954 Driver->drawLine(line, GenericMat);
2957 // Clear the vetor.
2958 edges.clear();
2959 }// displayPACSBorders //
2961 const uint PacsBoxPointCount = 24;
2963 CVector PacsBox[PacsBoxPointCount] =
2965 CVector( -0.5f, -0.5f, 0), CVector( 0.5f, -0.5f, 0),
2966 CVector( 0.5f, -0.5f, 0), CVector( 0.5f, 0.5f, 0),
2967 CVector( 0.5f, 0.5f, 0), CVector( -0.5f, 0.5f, 0),
2968 CVector( -0.5f, 0.5f, 0), CVector( -0.5f, -0.5f, 0),
2970 CVector( -0.5f, -0.5f, 1), CVector( 0.5f, -0.5f, 1),
2971 CVector( 0.5f, -0.5f, 1), CVector( 0.5f, 0.5f, 1),
2972 CVector( 0.5f, 0.5f, 1), CVector( -0.5f, 0.5f, 1),
2973 CVector( -0.5f, 0.5f, 1), CVector( -0.5f, -0.5f, 1),
2975 CVector( -0.5f, -0.5f, 0), CVector( -0.5f, -0.5f, 1),
2976 CVector( 0.5f, -0.5f, 0), CVector( 0.5f, -0.5f, 1),
2977 CVector( 0.5f, 0.5f, 0), CVector( 0.5f, 0.5f, 1),
2978 CVector( -0.5f, 0.5f, 0), CVector( -0.5f, 0.5f, 1),
2981 const uint PacsCylPointCount = 48;
2983 CVector PacsCyl[PacsCylPointCount] =
2985 CVector( 0, 1, 0),CVector( 0.7071067f, 0.7071067f, 0),
2986 CVector( 0.7071067f, 0.7071067f, 0),CVector( 1, 0, 0),
2987 CVector( 1, 0, 0),CVector( 0.7071067f, -0.7071067f,0),
2988 CVector( 0.7071067f, -0.7071067f,0),CVector( 0, -1, 0),
2989 CVector( 0, -1, 0),CVector( -0.7071067f,-0.7071067f,0),
2990 CVector( -0.7071067f,-0.7071067f,0),CVector( -1, 0, 0),
2991 CVector( -1, 0, 0),CVector( -0.7071067f,0.7071067f, 0),
2992 CVector( -0.7071067f,0.7071067f, 0),CVector( 0, 1, 0),
2994 CVector( 0, 1, 1),CVector( 0.7071067f, 0.7071067f, 1),
2995 CVector( 0.7071067f, 0.7071067f, 1),CVector( 1, 0, 1),
2996 CVector( 1, 0, 1),CVector( 0.7071067f, -0.7071067f,1),
2997 CVector( 0.7071067f, -0.7071067f,1),CVector( 0, -1, 1),
2998 CVector( 0, -1, 1),CVector( -0.7071067f,-0.7071067f,1),
2999 CVector( -0.7071067f,-0.7071067f,1),CVector( -1, 0, 1),
3000 CVector( -1, 0, 1),CVector( -0.7071067f,0.7071067f, 1),
3001 CVector( -0.7071067f,0.7071067f, 1),CVector( 0, 1, 1),
3003 CVector( 0, 1, 1),CVector( 0, 1, 0),
3004 CVector( 0.7071067f, 0.7071067f, 1),CVector( 0.7071067f, 0.7071067f, 0),
3005 CVector( 1, 0, 1),CVector( 1, 0, 0),
3006 CVector( 0.7071067f, -0.7071067f,1),CVector( 0.7071067f, -0.7071067f,0),
3007 CVector( 0, -1, 1),CVector( 0, -1, 0),
3008 CVector( -0.7071067f,-0.7071067f,1),CVector( -0.7071067f,-0.7071067f,0),
3009 CVector( -1, 0, 1),CVector( -1, 0, 0),
3010 CVector( -0.7071067f,0.7071067f, 1),CVector( -0.7071067f,0.7071067f, 0),
3013 void displayPACSPrimitive()
3015 std::vector<const UMovePrimitive*> movePrimitives;
3017 // if no continent selected, skip
3018 if(!PACS)
3019 return;
3021 PACS->getPrimitives(movePrimitives);
3023 uint i;
3024 for (i=0; i<movePrimitives.size(); i++)
3026 // World image
3027 const UMovePrimitive *prim = movePrimitives[i];
3028 uint8 wI = prim->getFirstWorldImageV();
3030 // Distance
3031 CVector position = prim->getFinalPosition(wI);
3032 if ((position-UserEntity->pos()).sqrnorm() < (200*200))
3034 // Choose a color
3035 CLineColor line;
3036 if (prim->isCollisionable())
3038 // Static collision
3039 if (prim->getReactionType() == UMovePrimitive::DoNothing)
3041 line.Color0 = CRGBA::Red;
3043 else
3045 line.Color0 = CRGBA::Yellow;
3048 else
3050 // Trigger
3051 line.Color0 = CRGBA::White;
3053 line.Color1 = line.Color0;
3055 // Lines
3056 CVector *lines;
3058 // Line count
3059 uint linecount;
3061 // Transform matrix
3062 CMatrix scale;
3063 scale.identity();
3064 CMatrix rot;
3065 rot.identity();
3067 // Draw the primitive
3068 if (prim->getPrimitiveType() == UMovePrimitive::_2DOrientedBox)
3070 lines = PacsBox;
3071 linecount = PacsBoxPointCount/2;
3072 float width;
3073 float depth;
3074 prim->getSize (width, depth);
3075 scale.scale(CVector (width, depth, prim->getHeight()));
3076 rot.rotateZ((float)prim->getOrientation(wI));
3078 else
3080 lines = PacsCyl;
3081 linecount = PacsCylPointCount/2;
3082 float radius = prim->getRadius ();
3083 scale.scale(CVector (radius, radius, prim->getHeight()));
3086 CMatrix pos;
3087 pos.identity();
3088 pos.setPos (position);
3089 pos = pos*rot*scale;
3091 // Draw the primitive
3092 uint j;
3093 for (j=0; j<linecount; j++)
3095 line.V0 = pos * lines[j*2];
3096 line.V1 = pos * lines[j*2+1];
3098 // Draw the line.
3099 Driver->drawLine(line, GenericMat);
3105 //-----------------------------------------------
3106 // displaySoundBox :
3107 //-----------------------------------------------
3108 void displaySoundBox()
3110 if (SoundMngr != 0)
3112 SoundMngr->drawSounds(50.f);
3117 //-----------------------------------------------
3118 // displaySceneProfiles();
3119 // nlinfo the Scene Profile results
3120 //-----------------------------------------------
3121 string buildStrVBFormat(uint32 format)
3123 // Yoyo: Uggly: hardcoded :)
3124 string res;
3126 if(format & 0x0001)
3127 res+= "Vertex";
3128 if(format & 0x0002)
3129 res+= "|Normal";
3130 if(format & 0x0004)
3131 res+= "|TexCoord0";
3132 if(format & 0x0008)
3133 res+= "|TexCoord1 ";
3134 if(format & 0x0010)
3135 res+= "|TexCoord2";
3136 if(format & 0x0020)
3137 res+= "|TexCoord3 ";
3138 if(format & 0x0040)
3139 res+= "|TexCoord4 ";
3140 if(format & 0x0080)
3141 res+= "|TexCoord5 ";
3142 if(format & 0x0100)
3143 res+= "|TexCoord6 ";
3144 if(format & 0x0200)
3145 res+= "|TexCoord7";
3146 if(format & 0x0400)
3147 res+= "|PrimaryColor";
3148 if(format & 0x0800)
3149 res+= "|SecondaryColor";
3150 if(format & 0x1000)
3151 res+= "|Weight";
3152 if(format & 0x2000)
3153 res+= "|PaletteSkin";
3154 if(format & 0x4000)
3155 res+= "|Fog";
3157 return res;
3159 void displaySceneProfiles()
3161 // **** Scene Profile
3162 UScene::CBenchResults res;
3163 Scene->getProfileResults(res);
3165 static uint id=0;
3166 nlinfo("****** Scene Profile Result: %d *******", id );
3167 id++;
3169 // Display Mesh PerVertexFormat Benchs
3170 nlinfo(" * Mesh Per VertexFormat:");
3171 std::map<uint32, uint32>::iterator it;
3172 for(it=res.MeshProfileTriVBFormat.begin();it!=res.MeshProfileTriVBFormat.end();it++)
3174 // build the format
3175 string format= buildStrVBFormat(it->first);
3176 nlinfo(" NumTris: %5d. Format: %s", it->second, format.c_str() );
3179 // Display MeshMRM PerVertexFormat Benchs
3180 nlinfo(" * MeshMRM Per VertexFormat:");
3181 for(it=res.MeshMRMProfileTriVBFormat.begin();it!=res.MeshMRMProfileTriVBFormat.end();it++)
3183 // build the format
3184 string format= buildStrVBFormat(it->first);
3185 nlinfo(" NumTris: %5d. Format: %s", it->second, format.c_str() );
3188 // Display BlockRendering Information
3189 nlinfo(" * Mesh BlockRender Info:");
3190 nlinfo(" NumMeshRdrNormal: %d", res.NumMeshRdrNormal);
3191 nlinfo(" NumMeshRdrBlock: %d", res.NumMeshRdrBlock);
3192 nlinfo(" NumMeshRdrBlockWithVBHeap: %d", res.NumMeshRdrBlockWithVBHeap);
3193 nlinfo(" NumMeshRdrNormal TriCount: %d", res.NumMeshTriRdrNormal);
3194 nlinfo(" NumMeshRdrBlock TriCount: %d", res.NumMeshTriRdrBlock);
3195 nlinfo(" NumMeshRdrBlockWithVBHeap TriCount: %d", res.NumMeshTriRdrBlockWithVBHeap);
3197 nlinfo(" * MeshMRM BlockRender Info:");
3198 nlinfo(" NumMeshMRMRdrNormal: %d", res.NumMeshMRMRdrNormal);
3199 nlinfo(" NumMeshMRMRdrBlock: %d", res.NumMeshMRMRdrBlock);
3200 nlinfo(" NumMeshMRMRdrBlockWithVBHeap: %d", res.NumMeshMRMRdrBlockWithVBHeap);
3201 nlinfo(" NumMeshMRMRdrNormal TriCount: %d", res.NumMeshMRMTriRdrNormal);
3202 nlinfo(" NumMeshMRMRdrBlock TriCount: %d", res.NumMeshMRMTriRdrBlock);
3203 nlinfo(" NumMeshMRMRdrBlockWithVBHeap TriCount: %d", res.NumMeshMRMTriRdrBlockWithVBHeap);
3205 // Display VBHard usage Information
3206 nlinfo(" * VBHard usage Info:");
3207 nlinfo(" NumMeshVBufferStd: %d", res.NumMeshVBufferStd);
3208 nlinfo(" NumMeshVBufferHard: %d", res.NumMeshVBufferHard);
3209 nlinfo(" NumMeshMRMVBufferStd: %d", res.NumMeshMRMVBufferStd);
3210 nlinfo(" NumMeshMRMVBufferHard: %d", res.NumMeshMRMVBufferHard);
3213 nlinfo("****** END Scene Profile Result *******");
3215 // **** Additionaly, display QuadGridClipManager profile
3216 Scene->profileQuadGridClipManager();
3218 // **** Additionaly, display List of Landscape IG Loaded
3219 if (Landscape)
3221 nlinfo("****** Land IG Profile *******");
3222 std::vector<std::pair<UInstanceGroup *, std::string> > igList;
3223 LandscapeIGManager.getAllIGWithNames(igList);
3224 // For all ig
3225 for(uint i=0;i<igList.size();i++)
3227 string igName= CFile::getFilenameWithoutExtension(igList[i].second);
3228 if( LandscapeIGManager.isIGAddedToScene(igName) )
3229 nlinfo("%s", igList[i].second.c_str() );
3232 nlinfo("****** END Land IG Profile *******");
3237 //-----------------------------------------------
3238 // validateDialogs();
3239 // validate current dialogs by checking the distance between the two talking entities. End dialogs if they are too far
3240 //-----------------------------------------------
3241 void validateDialogs(const CGameContextMenu &gcm)
3244 if ( UserEntity->trader() != CLFECOMMON::INVALID_SLOT )
3246 CEntityCL * trader = EntitiesMngr.entity(UserEntity->trader());
3247 if (trader)
3249 CVectorD vect1 = trader->pos();
3250 CVectorD vect2 = UserEntity->pos();
3252 double distanceSquare = pow(vect1.x-vect2.x,2) + pow(vect1.y-vect2.y,2);
3254 if (gcm.isBuilding())
3256 if (distanceSquare > MaxTalkingOutpostBuildingDistSquare)
3258 // Prevent also the Server of ending bot chat
3259 if (CBotChatManager::getInstance()->getCurrPage())
3260 CBotChatManager::getInstance()->endDialog();
3263 else
3265 if(distanceSquare > MaxTalkingDistSquare)
3267 // Prevent also the Server of ending bot chat
3268 if(CBotChatManager::getInstance()->getCurrPage())
3269 CBotChatManager::getInstance()->endDialog();
3276 NLMISC_DYNVARIABLE(float, FPS, "The second smoothed frame rate per second")
3278 if (get) *pointer = 1.0f/smoothFPS.getSmoothValue ();
3281 // show hide all the debuging of ui
3282 NLMISC_COMMAND(debugUI, "Debug the ui : show/hide quads of bboxs and hotspots", "debugUI 1 or 0")
3284 if (args.size() > 1) return false;
3285 bool on = true;
3286 DebugUIFilter.clear();
3287 if (args.size() == 1)
3289 if(!args[0].empty() && !isdigit(args[0][0]))
3291 on= true;
3292 DebugUIFilter= args[0];
3294 else
3295 fromString(args[0], on);
3298 CGroupCell::setDebugUICell( on );
3299 DebugUIView = on;
3300 DebugUICtrl = on;
3301 DebugUIGroup = on;
3302 return true;
3306 // show hide the debuging of ui
3307 NLMISC_COMMAND(debugUIView, "Debug the ui : show/hide quads of bboxs and hotspots for views", "")
3309 DebugUIView = !DebugUIView;
3310 return true;
3313 // show hide the debuging of ui
3314 NLMISC_COMMAND(debugUICtrl, "Debug the ui : show/hide quads of bboxs and hotspots for ctrl", "")
3316 DebugUICtrl = !DebugUICtrl;
3317 return true;
3320 // show hide the debuging of ui
3321 NLMISC_COMMAND(debugUIGroup, "Debug the ui : show/hide quads of bboxs and hotspots for group", "")
3323 DebugUIGroup = !DebugUIGroup;
3324 return true;
3327 // show hide the debuging of cells
3328 NLMISC_COMMAND(debugUICell, "Debug the ui : show/hide quads of bboxs for cells", "")
3330 CGroupCell::setDebugUICell( !CGroupCell::getDebugUICell() );
3331 return true;
3334 // Set weather value
3335 NLMISC_COMMAND(setWeatherValue, "Set weather value", "")
3337 if (args.size() != 1) return false;
3338 float value;
3339 fromString(args[0], value);
3340 ManualWeatherValue = value / (ContinentMngr.cur()->WeatherFunction[CurrSeason].getNumWeatherSetups() - 1);
3341 return true;
3344 class CHandlerDebugUIGroup : public IActionHandler
3346 virtual void execute (CCtrlBase * /* pCaller */, const std::string &/* sParams */)
3348 DebugUIGroup = !DebugUIGroup;
3351 REGISTER_ACTION_HANDLER( CHandlerDebugUIGroup, "debug_ui_group");
3353 class CHandlerDebugUICtrl : public IActionHandler
3355 virtual void execute (CCtrlBase * /* pCaller */, const std::string &/* sParams */)
3357 DebugUICtrl = !DebugUICtrl;
3360 REGISTER_ACTION_HANDLER( CHandlerDebugUICtrl, "debug_ui_ctrl");
3362 class CHandlerDebugUIView : public IActionHandler
3364 virtual void execute (CCtrlBase * /* pCaller */, const std::string &/* sParams */)
3366 DebugUIView = !DebugUIView;
3369 REGISTER_ACTION_HANDLER( CHandlerDebugUIView, "debug_ui_view");
3372 class CAHShowTimedFX : public IActionHandler
3374 void execute(CCtrlBase * /* pCaller */, const std::string &/* params */)
3376 if (ShowTimedFX)
3378 ShowTimedFXMode = (CTimedFXManager::TDebugDisplayMode) (ShowTimedFXMode + 1);
3379 if (ShowTimedFXMode == CTimedFXManager::DebugModeCount)
3381 ShowTimedFX = false;
3384 else
3386 ShowTimedFX = true;
3387 ShowTimedFXMode = CTimedFXManager::NoText;
3391 // ***************************************************************************
3392 REGISTER_ACTION_HANDLER (CAHShowTimedFX, "show_timed_fx");
3395 // ***************************************************************************
3396 void displayDebugClusters()
3398 // Get the Cluster system where the player (not the camera!) lies
3399 UGlobalPosition gPos;
3400 if(UserEntity->getPrimitive())
3401 UserEntity->getPrimitive()->getGlobalPosition(gPos, dynamicWI);
3402 // get the cluster IG associated to this pacs position
3403 UInstanceGroup *ig = getCluster(gPos);
3405 // Then display debug for it!
3406 if(ig)
3407 ig->displayDebugClusters(Driver, TextContext);
3409 // Draw the last camera 3rd person setuped
3410 CLineColor line;
3412 // start to test start
3413 line.V0= LastDebugClusterCameraThirdPersonStart;
3414 line.V1= LastDebugClusterCameraThirdPersonTestStart;
3415 line.Color0= CRGBA::Blue;
3416 line.Color1= CRGBA::Green;
3417 Driver->drawLine(line, GenericMat);
3419 // test start to result
3420 line.V0= LastDebugClusterCameraThirdPersonTestStart;
3421 if(LastDebugClusterCameraThirdPersonForceFPV)
3422 line.V1= LastDebugClusterCameraThirdPersonEnd;
3423 else
3424 line.V1= LastDebugClusterCameraThirdPersonResult;
3425 line.Color0= CRGBA::Red;
3426 line.Color1= CRGBA::Green;
3427 Driver->drawLine(line, GenericMat);
3429 // result to end
3430 if(!LastDebugClusterCameraThirdPersonForceFPV)
3432 line.V0= LastDebugClusterCameraThirdPersonResult;
3433 line.V1= LastDebugClusterCameraThirdPersonEnd;
3434 line.Color0= CRGBA::Yellow;
3435 line.Color1= CRGBA::Green;
3436 Driver->drawLine(line, GenericMat);
3439 // pelvis pos to test start
3440 line.V0= LastDebugClusterCameraThirdPersonPelvisPos;
3441 line.V1= LastDebugClusterCameraThirdPersonTestStart;
3442 line.Color0= CRGBA::Magenta;
3443 line.Color1= CRGBA::Green;
3444 Driver->drawLine(line, GenericMat);
3448 NLMISC_COMMAND(dumpFontTexture, "Write font texture to file", "")
3450 CInterfaceManager *im = CInterfaceManager::getInstance();
3451 if (TextContext)
3453 std::string fname = CFile::findNewFile("font-texture.tga");
3454 TextContext->dumpCacheTexture(fname.c_str());
3455 im->displaySystemInfo(fname + " created", "SYS");
3457 else
3459 im->displaySystemInfo("Error: TextContext == NULL", "SYS");
3461 return true;
3465 // ***************************************************************************
3466 void inGamePatchUncompleteWarning()
3468 CInterfaceManager *im = CInterfaceManager::getInstance();
3469 CLuaManager::getInstance().executeLuaScript("bgdownloader:inGamePatchUncompleteWarning()");
3471 CInterfaceManager *im = CInterfaceManager::getInstance();
3472 CGroupContainer *gc = dynamic_cast<CGroupContainer *>(CWidgetManager::getInstance()->getElementFromId("ui:interface:bg_downloader"));
3473 if (gc)
3475 gc->setActive(true);
3476 CWidgetManager::getInstance()->setTopWindow(gc);
3477 gc->enableBlink(2);
3479 im->messageBoxWithHelp(CI18N::get("uiBGD_InGamePatchIncomplete"));
3480 im->displaySystemInfo(CI18N::get("uiBGD_InGamePatchIncompleteBC"), "BC");