diff --git a/src/xrEngine/CameraBase.cpp b/src/xrEngine/CameraBase.cpp index f058244ce20..b8e7c110ed1 100644 --- a/src/xrEngine/CameraBase.cpp +++ b/src/xrEngine/CameraBase.cpp @@ -9,23 +9,23 @@ CCameraBase::CCameraBase(CObject* p, u32 flags) { - m_Flags.assign (flags); - vPosition.set (0,0,0); - vDirection.set (0,0,1); - vNormal.set (0,1,0); - yaw = 0; - pitch = 0; - roll = 0; - lim_yaw.set (0.f,0.f); - lim_pitch.set (0.f,0.f); - lim_roll.set (0.f,0.f); - bClampYaw = false; - bClampPitch = false; - bClampRoll = false; - SetParent (p); - f_fov = 90; - f_aspect = 1.f; - tag = 0; + m_Flags.assign(flags); + vPosition.set(0, 0, 0); + vDirection.set(0, 0, 1); + vNormal.set(0, 1, 0); + yaw = 0; + pitch = 0; + roll = 0; + lim_yaw.set(0.f, 0.f); + lim_pitch.set(0.f, 0.f); + lim_roll.set(0.f, 0.f); + bClampYaw = false; + bClampPitch = false; + bClampRoll = false; + SetParent(p); + f_fov = 90; + f_aspect = 1.f; + tag = 0; } CCameraBase::~CCameraBase() @@ -34,51 +34,61 @@ CCameraBase::~CCameraBase() void CCameraBase::Load(LPCSTR section) { - rot_speed = pSettings->r_fvector3 (section,"rot_speed"); + rot_speed = pSettings->r_fvector3(section, "rot_speed"); - lim_yaw = pSettings->r_fvector2 (section,"lim_yaw"); - lim_pitch = pSettings->r_fvector2 (section,"lim_pitch"); + lim_yaw = pSettings->r_fvector2(section, "lim_yaw"); + lim_pitch = pSettings->r_fvector2(section, "lim_pitch"); - bClampPitch = (0!=lim_pitch[0])||(0!=lim_pitch[1]); - bClampYaw = (0!=lim_yaw[0])||(0!=lim_yaw[1]); + bClampPitch = (0 != lim_pitch[0]) || (0 != lim_pitch[1]); + bClampYaw = (0 != lim_yaw[0]) || (0 != lim_yaw[1]); - if (bClampPitch) pitch = (lim_pitch[0]+lim_pitch[1])*0.5f; - if (bClampYaw) yaw = (lim_yaw[0]+lim_yaw[1])*0.5f; + if (bClampPitch) pitch = (lim_pitch[0] + lim_pitch[1])*0.5f; + if (bClampYaw) yaw = (lim_yaw[0] + lim_yaw[1])*0.5f; } -IC float AClamp(Fvector2& l, float v){ - return (2*v-l[0]-l[1])/(l[1]-l[0]); +IC float AClamp(Fvector2& l, float v) +{ + return (2 * v - l[0] - l[1]) / (l[1] - l[0]); } -float CCameraBase::CheckLimYaw( ){ - if (bClampYaw){ - return AClamp(lim_yaw,yaw); - }else - return 0; +float CCameraBase::CheckLimYaw() +{ + if (bClampYaw) + { + return AClamp(lim_yaw, yaw); + } + else + return 0; } -float CCameraBase::CheckLimPitch( ){ - if (bClampYaw){ - return AClamp(lim_pitch,pitch); - }else - return 0; +float CCameraBase::CheckLimPitch() +{ + if (bClampYaw) + { + return AClamp(lim_pitch, pitch); + } + else + return 0; } -float CCameraBase::CheckLimRoll( ){ - if (bClampYaw){ - return AClamp(lim_roll,roll); - }else - return 0; +float CCameraBase::CheckLimRoll() +{ + if (bClampYaw) + { + return AClamp(lim_roll, roll); + } + else + return 0; } SCamEffectorInfo::SCamEffectorInfo() { - p.set (0,0,0); - d.set (0,0,1); - n.set (0,1,0); + p.set(0, 0, 0); + d.set(0, 0, 1); + n.set(0, 1, 0); - fFov = 90.0f; - fFar = 100.0f; - fAspect = 1.f; - dont_apply = false; - affected_on_hud = true; + fFov = 90.0f; + fFar = 100.0f; + fAspect = 1.f; + dont_apply = false; + affected_on_hud = true; } \ No newline at end of file diff --git a/src/xrEngine/CameraBase.h b/src/xrEngine/CameraBase.h index fde61f92880..706fa4e675d 100644 --- a/src/xrEngine/CameraBase.h +++ b/src/xrEngine/CameraBase.h @@ -11,76 +11,77 @@ // refs class CObject; -class ENGINE_API CCameraBase +class ENGINE_API CCameraBase { protected: - CObject* parent; + CObject* parent; public: - BOOL bClampYaw, bClampPitch, bClampRoll; - float yaw,pitch,roll; + BOOL bClampYaw, bClampPitch, bClampRoll; + float yaw, pitch, roll; - enum{ - flRelativeLink = (1<<0), - flPositionRigid = (1<<1), - flDirectionRigid = (1<<2), - }; - Flags32 m_Flags; + enum + { + flRelativeLink = (1 << 0), + flPositionRigid = (1 << 1), + flDirectionRigid = (1 << 2), + }; + Flags32 m_Flags; - ECameraStyle style; - Fvector2 lim_yaw,lim_pitch,lim_roll; - Fvector rot_speed; + ECameraStyle style; + Fvector2 lim_yaw, lim_pitch, lim_roll; + Fvector rot_speed; - Fvector vPosition; - Fvector vDirection; - Fvector vNormal; - float f_fov; - float f_aspect; + Fvector vPosition; + Fvector vDirection; + Fvector vNormal; + float f_fov; + float f_aspect; -IC Fvector Position () const { return vPosition; } -IC Fvector Direction () const { return vDirection;} -IC Fvector Up () const { return vNormal; } -IC Fvector Right () const { return Fvector().crossproduct( vNormal, vDirection ); } -IC float Fov () const { return f_fov; } -IC float Aspect () const { return f_aspect; } + IC Fvector Position() const { return vPosition; } + IC Fvector Direction() const { return vDirection; } + IC Fvector Up() const { return vNormal; } + IC Fvector Right() const { return Fvector().crossproduct(vNormal, vDirection); } + IC float Fov() const { return f_fov; } + IC float Aspect() const { return f_aspect; } - int tag; + int tag; public: - CCameraBase ( CObject* p, u32 flags ); - virtual ~CCameraBase ( ); - virtual void Load (LPCSTR section); - void SetParent ( CObject* p ) {parent=p; VERIFY(p);} - virtual void OnActivate ( CCameraBase* old_cam ) {;} - virtual void OnDeactivate ( ) {;} - virtual void Move ( int cmd, float val=0, float factor=1.0f) {;} - virtual void Update ( Fvector& point, Fvector& noise_angle ) {;} - virtual void Get ( Fvector& P, Fvector& D, Fvector& N ) {P.set(vPosition);D.set(vDirection);N.set(vNormal);} - virtual void Set ( const Fvector& P, const Fvector& D, const Fvector& N ){vPosition.set(P);vDirection.set(D);vNormal.set(N);} - virtual void Set ( float Y, float P, float R ) {yaw=Y;pitch=P;roll=R;} - - virtual float GetWorldYaw ( ) { return 0; }; - virtual float GetWorldPitch ( ) { return 0; }; + CCameraBase(CObject* p, u32 flags); + virtual ~CCameraBase(); + virtual void Load(LPCSTR section); + void SetParent(CObject* p) { parent = p; VERIFY(p); } + virtual void OnActivate(CCameraBase* old_cam) { ; } + virtual void OnDeactivate() { ; } + virtual void Move(int cmd, float val = 0, float factor = 1.0f) { ; } + virtual void Update(Fvector& point, Fvector& noise_angle) { ; } + virtual void Get(Fvector& P, Fvector& D, Fvector& N) { P.set(vPosition); D.set(vDirection); N.set(vNormal); } + virtual void Set(const Fvector& P, const Fvector& D, const Fvector& N) { vPosition.set(P); vDirection.set(D); vNormal.set(N); } + virtual void Set(float Y, float P, float R) { yaw = Y; pitch = P; roll = R; } - virtual float CheckLimYaw ( ); - virtual float CheckLimPitch ( ); - virtual float CheckLimRoll ( ); + virtual float GetWorldYaw() { return 0; }; + virtual float GetWorldPitch() { return 0; }; + + virtual float CheckLimYaw(); + virtual float CheckLimPitch(); + virtual float CheckLimRoll(); }; template -IC void tviewport_size( CRenderDeviceBase& D, float _viewport_near, const T &cam_info, float& h_w, float& h_h) +IC void tviewport_size(CRenderDeviceBase& D, float _viewport_near, const T& cam_info, float& h_w, float& h_h) { - h_h = _viewport_near*tan(deg2rad(cam_info.Fov())/2.f); - VERIFY2( _valid(h_h), make_string("invalide viewporrt params fov: %f ", cam_info.Fov()) ); - float aspect = D.fASPECT;//cam_info.Aspect(); - VERIFY( aspect>EPS ); - h_w = h_h/aspect; + h_h = _viewport_near*tan(deg2rad(cam_info.Fov()) / 2.f); + VERIFY2(_valid(h_h), make_string("invalide viewporrt params fov: %f ", cam_info.Fov())); + float aspect = D.fASPECT;//cam_info.Aspect(); + VERIFY(aspect > EPS); + h_w = h_h / aspect; } template -IC void viewport_size( float _viewport_near, const T &cam_info, float& h_w, float& h_h) +IC void viewport_size(float _viewport_near, const T& cam_info, float& h_w, float& h_h) { - tviewport_size( Device, _viewport_near, cam_info, h_w, h_h ); + tviewport_size(Device, _viewport_near, cam_info, h_w, h_h); } #endif // !defined(AFX_CAMERABASE_H__B11F8AE1_1213_11D4_B4E3_4854E82A090D__INCLUDED_) diff --git a/src/xrEngine/CameraDebug.h b/src/xrEngine/CameraDebug.h index 2abf3fd7f28..0c233464bc7 100644 --- a/src/xrEngine/CameraDebug.h +++ b/src/xrEngine/CameraDebug.h @@ -10,24 +10,24 @@ #include "iinputreceiver.h" class ENGINE_API CCameraDebug : - public CCameraBase, - public pureRender, - public IInputReceiver +public CCameraBase, +public pureRender, +public IInputReceiver { - D3DXMATRIX g_matPosition; - D3DXVECTOR3 g_vecVelocity; - D3DXVECTOR3 g_vecAngularVelocity; - Fvector savedP,savedD,savedN; - ECameraStyle savedStyle; - Flags32 savedDF; +D3DXMATRIX g_matPosition; +D3DXVECTOR3 g_vecVelocity; +D3DXVECTOR3 g_vecAngularVelocity; +Fvector savedP,savedD,savedN; +ECameraStyle savedStyle; +Flags32 savedDF; public: - virtual void OnMove (void); - virtual void OnCameraActivate ( CCameraBase* old_cam ); - virtual void OnCameraDeactivate ( ); - virtual void OnRender ( ); - virtual void IR_OnKeyboardPress (int dik); +virtual void OnMove (void); +virtual void OnCameraActivate ( CCameraBase* old_cam ); +virtual void OnCameraDeactivate ( ); +virtual void OnRender ( ); +virtual void IR_OnKeyboardPress (int dik); - CCameraDebug(); - virtual ~CCameraDebug(); +CCameraDebug(); +virtual ~CCameraDebug(); }; */ diff --git a/src/xrEngine/CameraDefs.h b/src/xrEngine/CameraDefs.h index b037b1c5fea..9ac5f59bf42 100644 --- a/src/xrEngine/CameraDefs.h +++ b/src/xrEngine/CameraDefs.h @@ -5,54 +5,57 @@ struct ENGINE_API SBaseEffector { - typedef fastdelegate::FastDelegate0<> CB_ON_B_REMOVE; - CB_ON_B_REMOVE m_on_b_remove_callback; - virtual ~SBaseEffector(){} + typedef fastdelegate::FastDelegate0<> CB_ON_B_REMOVE; + CB_ON_B_REMOVE m_on_b_remove_callback; + virtual ~SBaseEffector() {} }; struct ENGINE_API SCamEffectorInfo { - Fvector p; - Fvector d; - Fvector n; - Fvector r; - float fFov; - float fFar; - float fAspect; - bool dont_apply; - bool affected_on_hud; - SCamEffectorInfo(); - SCamEffectorInfo& operator = (const SCamEffectorInfo& other) - { - p = other.p; - d = other.d; - n = other.n; - r = other.r; - fFov = other.fFov; - fFar = other.fFar; - fAspect = other.fAspect; - dont_apply = other.dont_apply; - affected_on_hud = other.affected_on_hud; - return *this; - } + Fvector p; + Fvector d; + Fvector n; + Fvector r; + float fFov; + float fFar; + float fAspect; + bool dont_apply; + bool affected_on_hud; + SCamEffectorInfo(); + SCamEffectorInfo& operator = (const SCamEffectorInfo& other) + { + p = other.p; + d = other.d; + n = other.n; + r = other.r; + fFov = other.fFov; + fFar = other.fFar; + fAspect = other.fAspect; + dont_apply = other.dont_apply; + affected_on_hud = other.affected_on_hud; + return *this; + } }; -enum ECameraStyle { - csCamDebug, - csFirstEye, - csLookAt, +enum ECameraStyle +{ + csCamDebug, + csFirstEye, + csLookAt, csMax, - csFixed, - cs_forcedword = u32(-1) + csFixed, + cs_forcedword = u32(-1) }; -enum ECamEffectorType { - cefDemo =0, - cefNext +enum ECamEffectorType +{ + cefDemo = 0, + cefNext }; -enum EEffectorPPType { - ppeNext =0, +enum EEffectorPPType +{ + ppeNext = 0, }; // refs diff --git a/src/xrEngine/CameraManager.cpp b/src/xrEngine/CameraManager.cpp index 8b308f3723a..0b9c4b26506 100644 --- a/src/xrEngine/CameraManager.cpp +++ b/src/xrEngine/CameraManager.cpp @@ -16,468 +16,485 @@ #include "gamefont.h" #include "render.h" -float psCamInert = 0.f; -float psCamSlideInert = 0.25f; +float psCamInert = 0.f; +float psCamSlideInert = 0.25f; -SPPInfo pp_identity; -SPPInfo pp_zero; +SPPInfo pp_identity; +SPPInfo pp_zero; -SPPInfo& SPPInfo::add (const SPPInfo &ppi) +SPPInfo& SPPInfo::add(const SPPInfo& ppi) { - blur += ppi.blur; - gray += ppi.gray; - duality.h += ppi.duality.h; - duality.v += ppi.duality.v; - - noise.intensity = _max(noise.intensity, ppi.noise.intensity); - noise.grain = _max(noise.grain, ppi.noise.grain); - noise.fps = _max(noise.fps, ppi.noise.fps); - color_base += ppi.color_base; - color_gray += ppi.color_gray; - color_add += ppi.color_add; - - if(ppi.cm_tex1.size()) - { - if(cm_tex1.size()) - { - cm_tex2 = ppi.cm_tex1; - cm_interpolate = 1.0f - cm_influence/(cm_influence+ppi.cm_influence); - }else - { - cm_tex1 = ppi.cm_tex1; - cm_influence = ppi.cm_influence; - cm_interpolate = 0.0f; - } - cm_influence = _max(cm_influence, ppi.cm_influence); - } - return *this; + blur += ppi.blur; + gray += ppi.gray; + duality.h += ppi.duality.h; + duality.v += ppi.duality.v; + + noise.intensity = _max(noise.intensity, ppi.noise.intensity); + noise.grain = _max(noise.grain, ppi.noise.grain); + noise.fps = _max(noise.fps, ppi.noise.fps); + color_base += ppi.color_base; + color_gray += ppi.color_gray; + color_add += ppi.color_add; + + if (ppi.cm_tex1.size()) + { + if (cm_tex1.size()) + { + cm_tex2 = ppi.cm_tex1; + cm_interpolate = 1.0f - cm_influence / (cm_influence + ppi.cm_influence); + } + else + { + cm_tex1 = ppi.cm_tex1; + cm_influence = ppi.cm_influence; + cm_interpolate = 0.0f; + } + cm_influence = _max(cm_influence, ppi.cm_influence); + } + return *this; } -SPPInfo& SPPInfo::sub (const SPPInfo &ppi) +SPPInfo& SPPInfo::sub(const SPPInfo& ppi) { - blur -= ppi.blur; - gray -= ppi.gray; - duality.h -= ppi.duality.h; - duality.v -= ppi.duality.v; - color_base -= ppi.color_base; - color_gray -= ppi.color_gray; - color_add -= ppi.color_add; - return *this; + blur -= ppi.blur; + gray -= ppi.gray; + duality.h -= ppi.duality.h; + duality.v -= ppi.duality.v; + color_base -= ppi.color_base; + color_gray -= ppi.color_gray; + color_add -= ppi.color_add; + return *this; } -SPPInfo::SPPInfo () +SPPInfo::SPPInfo() { - blur = gray = duality.h = duality.v = 0; - noise.intensity=0; noise.grain = 1; noise.fps = 10; - color_base.set (.5f, .5f, .5f); - color_gray.set (.333f, .333f, .333f); - color_add.set (0.f, 0.f, 0.f); - cm_influence = 0.0f; - cm_interpolate = 0.0f; + blur = gray = duality.h = duality.v = 0; + noise.intensity = 0; + noise.grain = 1; + noise.fps = 10; + color_base.set(.5f, .5f, .5f); + color_gray.set(.333f, .333f, .333f); + color_add.set(0.f, 0.f, 0.f); + cm_influence = 0.0f; + cm_interpolate = 0.0f; } -void SPPInfo::normalize() +void SPPInfo::normalize() {} void SPPInfo::validate(LPCSTR str) { - VERIFY2(_valid(duality.h),str); - VERIFY2(_valid(duality.v),str); - VERIFY2(_valid(blur),str); - VERIFY2(_valid(gray),str); - VERIFY2(_valid(noise.intensity),str); - VERIFY2(_valid(noise.grain),str); - VERIFY2(_valid(noise.fps),str); - VERIFY2(_valid(color_base.r),str); - VERIFY2(_valid(color_base.g),str); - VERIFY2(_valid(color_base.b),str); - VERIFY2(_valid(color_gray.r),str); - VERIFY2(_valid(color_gray.g),str); - VERIFY2(_valid(color_gray.b),str); - VERIFY2(_valid(color_add.r),str); - VERIFY2(_valid(color_add.g),str); - VERIFY2(_valid(color_add.b),str); + VERIFY2(_valid(duality.h), str); + VERIFY2(_valid(duality.v), str); + VERIFY2(_valid(blur), str); + VERIFY2(_valid(gray), str); + VERIFY2(_valid(noise.intensity), str); + VERIFY2(_valid(noise.grain), str); + VERIFY2(_valid(noise.fps), str); + VERIFY2(_valid(color_base.r), str); + VERIFY2(_valid(color_base.g), str); + VERIFY2(_valid(color_base.b), str); + VERIFY2(_valid(color_gray.r), str); + VERIFY2(_valid(color_gray.g), str); + VERIFY2(_valid(color_gray.b), str); + VERIFY2(_valid(color_add.r), str); + VERIFY2(_valid(color_add.g), str); + VERIFY2(_valid(color_add.b), str); } SPPInfo& SPPInfo::lerp(const SPPInfo& def, const SPPInfo& to, float factor) { - VERIFY(_valid(factor)); - SPPInfo& pp = *this; - clamp(factor, 0.0f, 1.0f); - - pp.duality.h += def.duality.h + (to.duality.h - def.duality.h) * factor; - pp.duality.v += def.duality.v + (to.duality.v - def.duality.v) * factor; - pp.gray += def.gray + (to.gray - def.gray) * factor; - pp.blur += def.blur + (to.blur - def.blur) * factor; - pp.noise.intensity = to.noise.intensity;// + (to.noise.intensity - def.noise.intensity) * factor; - pp.noise.grain = to.noise.grain;// + (to.noise.grain - def.noise.grain) * factor; - pp.noise.fps = to.noise.fps; // + (to.noise.fps - def.noise.fps) * factor; - - pp.color_base.set ( - def.color_base.r + (to.color_base.r - def.color_base.r) * factor, - def.color_base.g + (to.color_base.g - def.color_base.g) * factor, - def.color_base.b + (to.color_base.b - def.color_base.b) * factor - ); - - pp.color_gray.set ( - def.color_gray.r + (to.color_gray.r - def.color_gray.r) * factor, - def.color_gray.g + (to.color_gray.g - def.color_gray.g) * factor, - def.color_gray.b + (to.color_gray.b - def.color_gray.b) * factor - ); - - pp.color_add.set ( - def.color_add.r + (to.color_add.r - def.color_add.r) * factor, - def.color_add.g + (to.color_add.g - def.color_add.g) * factor, - def.color_add.b + (to.color_add.b - def.color_add.b) * factor - ); - - pp.cm_tex1 = to.cm_tex1; - pp.cm_tex2 = to.cm_tex2; - pp.cm_influence += def.cm_influence + (to.cm_influence - def.cm_influence) * factor; - pp.cm_interpolate += def.cm_interpolate + (to.cm_interpolate - def.cm_interpolate) * factor; - - return *this; + VERIFY(_valid(factor)); + SPPInfo& pp = *this; + clamp(factor, 0.0f, 1.0f); + + pp.duality.h += def.duality.h + (to.duality.h - def.duality.h) * factor; + pp.duality.v += def.duality.v + (to.duality.v - def.duality.v) * factor; + pp.gray += def.gray + (to.gray - def.gray) * factor; + pp.blur += def.blur + (to.blur - def.blur) * factor; + pp.noise.intensity = to.noise.intensity;// + (to.noise.intensity - def.noise.intensity) * factor; + pp.noise.grain = to.noise.grain;// + (to.noise.grain - def.noise.grain) * factor; + pp.noise.fps = to.noise.fps; // + (to.noise.fps - def.noise.fps) * factor; + + pp.color_base.set( + def.color_base.r + (to.color_base.r - def.color_base.r) * factor, + def.color_base.g + (to.color_base.g - def.color_base.g) * factor, + def.color_base.b + (to.color_base.b - def.color_base.b) * factor + ); + + pp.color_gray.set( + def.color_gray.r + (to.color_gray.r - def.color_gray.r) * factor, + def.color_gray.g + (to.color_gray.g - def.color_gray.g) * factor, + def.color_gray.b + (to.color_gray.b - def.color_gray.b) * factor + ); + + pp.color_add.set( + def.color_add.r + (to.color_add.r - def.color_add.r) * factor, + def.color_add.g + (to.color_add.g - def.color_add.g) * factor, + def.color_add.b + (to.color_add.b - def.color_add.b) * factor + ); + + pp.cm_tex1 = to.cm_tex1; + pp.cm_tex2 = to.cm_tex2; + pp.cm_influence += def.cm_influence + (to.cm_influence - def.cm_influence) * factor; + pp.cm_interpolate += def.cm_interpolate + (to.cm_interpolate - def.cm_interpolate) * factor; + + return *this; } CCameraManager::CCameraManager(bool bApplyOnUpdate) { #ifdef DEBUG - dbg_upd_frame = 0; + dbg_upd_frame = 0; #endif - m_bAutoApply = bApplyOnUpdate; - - pp_identity.blur = 0; - pp_identity.gray = 0; - pp_identity.duality.h = 0; - pp_identity.duality.v = 0; - pp_identity.noise.intensity = 0; - pp_identity.noise.grain = 1.0f; - pp_identity.noise.fps = 30; - pp_identity.color_base.set (.5f, .5f, .5f); - pp_identity.color_gray.set (.333f, .333f, .333f); - pp_identity.color_add.set (0, 0, 0); - - pp_zero.blur = pp_zero.gray = pp_zero.duality.h = pp_zero.duality.v = 0.0f; - pp_zero.noise.intensity =0; - pp_zero.noise.grain = 0.0f; - pp_zero.noise.fps = 0.0f; - pp_zero.color_base.set (0,0,0); - pp_zero.color_gray.set (0,0,0); - pp_zero.color_add.set (0,0,0); - - pp_affected = pp_identity; + m_bAutoApply = bApplyOnUpdate; + + pp_identity.blur = 0; + pp_identity.gray = 0; + pp_identity.duality.h = 0; + pp_identity.duality.v = 0; + pp_identity.noise.intensity = 0; + pp_identity.noise.grain = 1.0f; + pp_identity.noise.fps = 30; + pp_identity.color_base.set(.5f, .5f, .5f); + pp_identity.color_gray.set(.333f, .333f, .333f); + pp_identity.color_add.set(0, 0, 0); + + pp_zero.blur = pp_zero.gray = pp_zero.duality.h = pp_zero.duality.v = 0.0f; + pp_zero.noise.intensity = 0; + pp_zero.noise.grain = 0.0f; + pp_zero.noise.fps = 0.0f; + pp_zero.color_base.set(0, 0, 0); + pp_zero.color_gray.set(0, 0, 0); + pp_zero.color_add.set(0, 0, 0); + + pp_affected = pp_identity; } CCameraManager::~CCameraManager() { - for (EffectorCamIt it=m_EffectorsCam.begin(); it!=m_EffectorsCam.end(); it++ ) - xr_delete(*it); - for (EffectorPPIt it=m_EffectorsPP.begin(); it!=m_EffectorsPP.end(); it++ ) - xr_delete(*it); + for (EffectorCamIt it = m_EffectorsCam.begin(); it != m_EffectorsCam.end(); it++) + xr_delete(*it); + for (EffectorPPIt it = m_EffectorsPP.begin(); it != m_EffectorsPP.end(); it++) + xr_delete(*it); } -CEffectorCam* CCameraManager::GetCamEffector(ECamEffectorType type) -{ - for (EffectorCamIt it=m_EffectorsCam.begin(); it!=m_EffectorsCam.end(); it++ ) - if ((*it)->eType==type) - { - return *it; - } - return 0; +CEffectorCam* CCameraManager::GetCamEffector(ECamEffectorType type) +{ + for (EffectorCamIt it = m_EffectorsCam.begin(); it != m_EffectorsCam.end(); it++) + if ((*it)->eType == type) + { + return *it; + } + return 0; } CEffectorCam* CCameraManager::AddCamEffector(CEffectorCam* ef) { - m_EffectorsCam_added_deffered.push_back(ef); - return m_EffectorsCam_added_deffered.back(); + m_EffectorsCam_added_deffered.push_back(ef); + return m_EffectorsCam_added_deffered.back(); } void CCameraManager::UpdateDeffered() { - EffectorCamIt it = m_EffectorsCam_added_deffered.begin(); - EffectorCamIt it_e = m_EffectorsCam_added_deffered.end(); - for (; it!=it_e; ++it) - { - RemoveCamEffector ( (*it)->eType ); - - if((*it)->AbsolutePositioning()) - m_EffectorsCam.push_front(*it); - else - m_EffectorsCam.push_back (*it); - } - - m_EffectorsCam_added_deffered.clear (); + EffectorCamIt it = m_EffectorsCam_added_deffered.begin(); + EffectorCamIt it_e = m_EffectorsCam_added_deffered.end(); + for (; it != it_e; ++it) + { + RemoveCamEffector((*it)->eType); + + if ((*it)->AbsolutePositioning()) + m_EffectorsCam.push_front(*it); + else + m_EffectorsCam.push_back(*it); + } + + m_EffectorsCam_added_deffered.clear(); } void CCameraManager::RemoveCamEffector(ECamEffectorType type) { - for (EffectorCamIt it=m_EffectorsCam.begin(); it!=m_EffectorsCam.end(); it++ ) - if ((*it)->eType==type) - { - OnEffectorReleased (*it); - m_EffectorsCam.erase(it); - return; - } + for (EffectorCamIt it = m_EffectorsCam.begin(); it != m_EffectorsCam.end(); it++) + if ((*it)->eType == type) + { + OnEffectorReleased(*it); + m_EffectorsCam.erase(it); + return; + } } -CEffectorPP* CCameraManager::GetPPEffector(EEffectorPPType type) -{ - for (EffectorPPIt it=m_EffectorsPP.begin(); it!=m_EffectorsPP.end(); it++ ) - if ((*it)->Type()==type) return *it; - return 0; +CEffectorPP* CCameraManager::GetPPEffector(EEffectorPPType type) +{ + for (EffectorPPIt it = m_EffectorsPP.begin(); it != m_EffectorsPP.end(); it++) + if ((*it)->Type() == type) return *it; + return 0; } -ECamEffectorType CCameraManager::RequestCamEffectorId () +ECamEffectorType CCameraManager::RequestCamEffectorId() { - for ( ECamEffectorType index = (ECamEffectorType)effCustomEffectorStartID; - GetCamEffector(index); - index = (ECamEffectorType)(index+1) ) { ; } - return index; + for (ECamEffectorType index = (ECamEffectorType)effCustomEffectorStartID; + GetCamEffector(index); + index = (ECamEffectorType)(index + 1)) + { + ; + } + return index; } -EEffectorPPType CCameraManager::RequestPPEffectorId () +EEffectorPPType CCameraManager::RequestPPEffectorId() { - for ( EEffectorPPType index = (EEffectorPPType)effCustomEffectorStartID; - GetPPEffector(index); - index = (EEffectorPPType)(index+1) ) { ; } - return index; + for (EEffectorPPType index = (EEffectorPPType)effCustomEffectorStartID; + GetPPEffector(index); + index = (EEffectorPPType)(index + 1)) + { + ; + } + return index; } -CEffectorPP* CCameraManager::AddPPEffector(CEffectorPP* ef) +CEffectorPP* CCameraManager::AddPPEffector(CEffectorPP* ef) { - RemovePPEffector (ef->Type()); - m_EffectorsPP.push_back (ef); - return m_EffectorsPP.back (); + RemovePPEffector(ef->Type()); + m_EffectorsPP.push_back(ef); + return m_EffectorsPP.back(); } void CCameraManager::RemovePPEffector(EEffectorPPType type) { - for (EffectorPPIt it=m_EffectorsPP.begin(); it!=m_EffectorsPP.end(); it++ ) - if ((*it)->Type()==type){ - if ((*it)->FreeOnRemove()) - { - OnEffectorReleased (*it); -// xr_delete (*it); - } - m_EffectorsPP.erase (it); - return; - } + for (EffectorPPIt it = m_EffectorsPP.begin(); it != m_EffectorsPP.end(); it++) + if ((*it)->Type() == type) + { + if ((*it)->FreeOnRemove()) + { + OnEffectorReleased(*it); + // xr_delete (*it); + } + m_EffectorsPP.erase(it); + return; + } } void CCameraManager::OnEffectorReleased(SBaseEffector* e) { - if(!e->m_on_b_remove_callback.empty()) - e->m_on_b_remove_callback(); + if (!e->m_on_b_remove_callback.empty()) + e->m_on_b_remove_callback(); - xr_delete(e); + xr_delete(e); } void CCameraManager::UpdateFromCamera(const CCameraBase* C) -{ - Update(C->vPosition,C->vDirection,C->vNormal, C->f_fov, C->f_aspect, g_pGamePersistent->Environment().CurrentEnv->far_plane, C->m_Flags.flags); +{ + Update(C->vPosition, C->vDirection, C->vNormal, C->f_fov, C->f_aspect, g_pGamePersistent->Environment().CurrentEnv->far_plane, C->m_Flags.flags); } void CCameraManager::Update(const Fvector& P, const Fvector& D, const Fvector& N, float fFOV_Dest, float fASPECT_Dest, float fFAR_Dest, u32 flags) { #ifdef DEBUG - if (!Device.Paused()) { - VERIFY (dbg_upd_frame!=Device.dwFrame);// already updated !!! - dbg_upd_frame = Device.dwFrame; - } + if (!Device.Paused()) + { + VERIFY(dbg_upd_frame != Device.dwFrame);// already updated !!! + dbg_upd_frame = Device.dwFrame; + } #endif // DEBUG - // camera - if (flags&CCameraBase::flPositionRigid) - m_cam_info.p.set (P); - else - m_cam_info.p.inertion (P, psCamInert); - if (flags&CCameraBase::flDirectionRigid) - { - m_cam_info.d.set (D); - m_cam_info.n.set (N); - }else{ - m_cam_info.d.inertion (D, psCamInert); - m_cam_info.n.inertion (N, psCamInert); - } - - // Normalize - m_cam_info.d.normalize (); - m_cam_info.n.normalize (); - m_cam_info.r.crossproduct (m_cam_info.n, m_cam_info.d); - m_cam_info.n.crossproduct (m_cam_info.d, m_cam_info.r); - - float aspect = Device.fHeight_2/Device.fWidth_2; - float src = 10*Device.fTimeDelta; clamp(src,0.f,1.f); - float dst = 1-src; - m_cam_info.fFov = m_cam_info.fFov*dst + fFOV_Dest*src; - m_cam_info.fFar = m_cam_info.fFar*dst + fFAR_Dest*src; - m_cam_info.fAspect = m_cam_info.fAspect*dst + (fASPECT_Dest*aspect)*src; - m_cam_info.dont_apply = false; - - UpdateCamEffectors (); - - UpdatePPEffectors (); - - if (false==m_cam_info.dont_apply && m_bAutoApply) - ApplyDevice (VIEWPORT_NEAR); - - UpdateDeffered (); + // camera + if (flags&CCameraBase::flPositionRigid) + m_cam_info.p.set(P); + else + m_cam_info.p.inertion(P, psCamInert); + if (flags&CCameraBase::flDirectionRigid) + { + m_cam_info.d.set(D); + m_cam_info.n.set(N); + } + else + { + m_cam_info.d.inertion(D, psCamInert); + m_cam_info.n.inertion(N, psCamInert); + } + + // Normalize + m_cam_info.d.normalize(); + m_cam_info.n.normalize(); + m_cam_info.r.crossproduct(m_cam_info.n, m_cam_info.d); + m_cam_info.n.crossproduct(m_cam_info.d, m_cam_info.r); + + float aspect = Device.fHeight_2 / Device.fWidth_2; + float src = 10 * Device.fTimeDelta; + clamp(src, 0.f, 1.f); + float dst = 1 - src; + m_cam_info.fFov = m_cam_info.fFov*dst + fFOV_Dest*src; + m_cam_info.fFar = m_cam_info.fFar*dst + fFAR_Dest*src; + m_cam_info.fAspect = m_cam_info.fAspect*dst + (fASPECT_Dest*aspect)*src; + m_cam_info.dont_apply = false; + + UpdateCamEffectors(); + + UpdatePPEffectors(); + + if (false == m_cam_info.dont_apply && m_bAutoApply) + ApplyDevice(VIEWPORT_NEAR); + + UpdateDeffered(); } bool CCameraManager::ProcessCameraEffector(CEffectorCam* eff) { - bool res = false; - if(eff->Valid() && eff->ProcessCam(m_cam_info)) - { - res = true; - }else - { - if(eff->AllowProcessingIfInvalid()) - { - eff->ProcessIfInvalid(m_cam_info); - res = true; - } - - EffectorCamVec::iterator it = std::find(m_EffectorsCam.begin(), m_EffectorsCam.end(), eff); - - m_EffectorsCam.erase(it); - OnEffectorReleased (eff); - } - return res; + bool res = false; + if (eff->Valid() && eff->ProcessCam(m_cam_info)) + { + res = true; + } + else + { + if (eff->AllowProcessingIfInvalid()) + { + eff->ProcessIfInvalid(m_cam_info); + res = true; + } + + EffectorCamVec::iterator it = std::find(m_EffectorsCam.begin(), m_EffectorsCam.end(), eff); + + m_EffectorsCam.erase(it); + OnEffectorReleased(eff); + } + return res; } void CCameraManager::UpdateCamEffectors() { - if (m_EffectorsCam.empty()) return; - EffectorCamVec::reverse_iterator rit = m_EffectorsCam.rbegin(); - for(; rit!=m_EffectorsCam.rend(); ++rit) - ProcessCameraEffector(*rit); - - m_cam_info.d.normalize (); - m_cam_info.n.normalize (); - m_cam_info.r.crossproduct (m_cam_info.n,m_cam_info.d); - m_cam_info.n.crossproduct (m_cam_info.d,m_cam_info.r); + if (m_EffectorsCam.empty()) return; + EffectorCamVec::reverse_iterator rit = m_EffectorsCam.rbegin(); + for (; rit != m_EffectorsCam.rend(); ++rit) + ProcessCameraEffector(*rit); + + m_cam_info.d.normalize(); + m_cam_info.n.normalize(); + m_cam_info.r.crossproduct(m_cam_info.n, m_cam_info.d); + m_cam_info.n.crossproduct(m_cam_info.d, m_cam_info.r); } void CCameraManager::UpdatePPEffectors() { - pp_affected.validate ("before applying pp"); - - int _count = 0; - if(m_EffectorsPP.size()) - { - bool b = false; - pp_affected = pp_identity; - for(int i = m_EffectorsPP.size()-1; i >= 0; --i) - { - CEffectorPP* eff = m_EffectorsPP[i]; - SPPInfo l_PPInf = pp_zero; - if(eff->Valid() && eff->Process(l_PPInf)) - { - ++_count; - if(!b) - { - pp_affected.add (l_PPInf); - pp_affected.sub (pp_identity); - pp_affected.validate("in cycle"); - } - if(!eff->bOverlap) - { - b = true; - pp_affected = l_PPInf; - } - }else - RemovePPEffector (eff->Type()); - } - if (0==_count) - pp_affected = pp_identity; - else - pp_affected.normalize (); - } else - { - pp_affected = pp_identity; - } - - if( !positive(pp_affected.noise.grain) ) - pp_affected.noise.grain = pp_identity.noise.grain; - - pp_affected.validate ("after applying pp"); + pp_affected.validate("before applying pp"); + + int _count = 0; + if (m_EffectorsPP.size()) + { + bool b = false; + pp_affected = pp_identity; + for (int i = m_EffectorsPP.size() - 1; i >= 0; --i) + { + CEffectorPP* eff = m_EffectorsPP[i]; + SPPInfo l_PPInf = pp_zero; + if (eff->Valid() && eff->Process(l_PPInf)) + { + ++_count; + if (!b) + { + pp_affected.add(l_PPInf); + pp_affected.sub(pp_identity); + pp_affected.validate("in cycle"); + } + if (!eff->bOverlap) + { + b = true; + pp_affected = l_PPInf; + } + } + else + RemovePPEffector(eff->Type()); + } + if (0 == _count) + pp_affected = pp_identity; + else + pp_affected.normalize(); + } + else + { + pp_affected = pp_identity; + } + + if (!positive(pp_affected.noise.grain)) + pp_affected.noise.grain = pp_identity.noise.grain; + + pp_affected.validate("after applying pp"); } -void CCameraManager::ApplyDevice (float _viewport_near) +void CCameraManager::ApplyDevice(float _viewport_near) { - // Device params - Device.mView.build_camera_dir(m_cam_info.p, m_cam_info.d, m_cam_info.n); - - Device.vCameraPosition.set ( m_cam_info.p ); - Device.vCameraDirection.set ( m_cam_info.d ); - Device.vCameraTop.set ( m_cam_info.n ); - Device.vCameraRight.set ( m_cam_info.r ); - - // projection - Device.fFOV = m_cam_info.fFov; - Device.fASPECT = m_cam_info.fAspect; - Device.mProject.build_projection(deg2rad(m_cam_info.fFov), m_cam_info.fAspect, _viewport_near, m_cam_info.fFar); - - if( g_pGamePersistent && g_pGamePersistent->m_pMainMenu->IsActive() ) - ResetPP (); - else - { - pp_affected.validate ("apply device"); - // postprocess - IRender_Target* T = ::Render->getTarget(); - T->set_duality_h (pp_affected.duality.h); - T->set_duality_v (pp_affected.duality.v); - T->set_blur (pp_affected.blur); - T->set_gray (pp_affected.gray); - T->set_noise (pp_affected.noise.intensity); - - clamp (pp_affected.noise.grain,EPS_L,1000.0f); - - T->set_noise_scale (pp_affected.noise.grain); - - T->set_noise_fps (pp_affected.noise.fps); - T->set_color_base (pp_affected.color_base); - T->set_color_gray (pp_affected.color_gray); - T->set_color_add (pp_affected.color_add); - - T->set_cm_imfluence (pp_affected.cm_influence); - T->set_cm_interpolate (pp_affected.cm_interpolate); - T->set_cm_textures (pp_affected.cm_tex1, pp_affected.cm_tex2); - } + // Device params + Device.mView.build_camera_dir(m_cam_info.p, m_cam_info.d, m_cam_info.n); + + Device.vCameraPosition.set(m_cam_info.p); + Device.vCameraDirection.set(m_cam_info.d); + Device.vCameraTop.set(m_cam_info.n); + Device.vCameraRight.set(m_cam_info.r); + + // projection + Device.fFOV = m_cam_info.fFov; + Device.fASPECT = m_cam_info.fAspect; + Device.mProject.build_projection(deg2rad(m_cam_info.fFov), m_cam_info.fAspect, _viewport_near, m_cam_info.fFar); + + if (g_pGamePersistent && g_pGamePersistent->m_pMainMenu->IsActive()) + ResetPP(); + else + { + pp_affected.validate("apply device"); + // postprocess + IRender_Target* T = ::Render->getTarget(); + T->set_duality_h(pp_affected.duality.h); + T->set_duality_v(pp_affected.duality.v); + T->set_blur(pp_affected.blur); + T->set_gray(pp_affected.gray); + T->set_noise(pp_affected.noise.intensity); + + clamp(pp_affected.noise.grain, EPS_L, 1000.0f); + + T->set_noise_scale(pp_affected.noise.grain); + + T->set_noise_fps(pp_affected.noise.fps); + T->set_color_base(pp_affected.color_base); + T->set_color_gray(pp_affected.color_gray); + T->set_color_add(pp_affected.color_add); + + T->set_cm_imfluence(pp_affected.cm_influence); + T->set_cm_interpolate(pp_affected.cm_interpolate); + T->set_cm_textures(pp_affected.cm_tex1, pp_affected.cm_tex2); + } } void CCameraManager::ResetPP() { - IRender_Target* T = ::Render->getTarget(); - T->set_duality_h (pp_identity.duality.h); - T->set_duality_v (pp_identity.duality.v); - T->set_blur (pp_identity.blur); - T->set_gray (pp_identity.gray); - T->set_noise (pp_identity.noise.intensity); - T->set_noise_scale (pp_identity.noise.grain); - T->set_noise_fps (pp_identity.noise.fps); - T->set_color_base (pp_identity.color_base); - T->set_color_gray (pp_identity.color_gray); - T->set_color_add (pp_identity.color_add); - T->set_cm_imfluence (0.0f); - T->set_cm_interpolate (1.0f); - T->set_cm_textures ("", ""); + IRender_Target* T = ::Render->getTarget(); + T->set_duality_h(pp_identity.duality.h); + T->set_duality_v(pp_identity.duality.v); + T->set_blur(pp_identity.blur); + T->set_gray(pp_identity.gray); + T->set_noise(pp_identity.noise.intensity); + T->set_noise_scale(pp_identity.noise.grain); + T->set_noise_fps(pp_identity.noise.fps); + T->set_color_base(pp_identity.color_base); + T->set_color_gray(pp_identity.color_gray); + T->set_color_add(pp_identity.color_add); + T->set_cm_imfluence(0.0f); + T->set_cm_interpolate(1.0f); + T->set_cm_textures("", ""); } void CCameraManager::Dump() { - Fmatrix mInvCamera; - Fvector _R,_U,_T,_P; - - mInvCamera.invert(Device.mView); - _R.set( mInvCamera._11, mInvCamera._12, mInvCamera._13 ); - _U.set( mInvCamera._21, mInvCamera._22, mInvCamera._23 ); - _T.set( mInvCamera._31, mInvCamera._32, mInvCamera._33 ); - _P.set( mInvCamera._41, mInvCamera._42, mInvCamera._43 ); - Log("CCameraManager::Dump::vPosition = ",_P); - Log("CCameraManager::Dump::vDirection = ",_T); - Log("CCameraManager::Dump::vNormal = ",_U); - Log("CCameraManager::Dump::vRight = ",_R); + Fmatrix mInvCamera; + Fvector _R, _U, _T, _P; + + mInvCamera.invert(Device.mView); + _R.set(mInvCamera._11, mInvCamera._12, mInvCamera._13); + _U.set(mInvCamera._21, mInvCamera._22, mInvCamera._23); + _T.set(mInvCamera._31, mInvCamera._32, mInvCamera._33); + _P.set(mInvCamera._41, mInvCamera._42, mInvCamera._43); + Log("CCameraManager::Dump::vPosition = ", _P); + Log("CCameraManager::Dump::vDirection = ", _T); + Log("CCameraManager::Dump::vNormal = ", _U); + Log("CCameraManager::Dump::vRight = ", _R); } diff --git a/src/xrEngine/CameraManager.h b/src/xrEngine/CameraManager.h index 7eeca1f1da0..db7ff31f2b8 100644 --- a/src/xrEngine/CameraManager.h +++ b/src/xrEngine/CameraManager.h @@ -2,136 +2,156 @@ #include "CameraDefs.h" -struct ENGINE_API SPPInfo { - struct SColor{ - float r, g, b; - SColor (){} - SColor (float _r, float _g, float _b):r(_r),g(_g),b(_b){} - IC operator u32() { - int _r = clampr (iFloor(r*255.f+.5f),0,255); - int _g = clampr (iFloor(g*255.f+.5f),0,255); - int _b = clampr (iFloor(b*255.f+.5f),0,255); - return color_rgba (_r,_g,_b,0); - } - - IC operator const Fvector&() { - return *((Fvector*)this); - } - - IC SColor& operator += (const SColor &ppi) { - r += ppi.r; g += ppi.g; b += ppi.b; - return *this; - } - IC SColor& operator -= (const SColor &ppi) { - r -= ppi.r; g -= ppi.g; b -= ppi.b; - return *this; - } - IC SColor& set (float _r, float _g, float _b) { - r=_r;g=_g;b=_b; - return *this; - } - }; - float blur, gray; - struct SDuality { - float h, v; - SDuality (){} - SDuality (float _h, float _v):h(_h),v(_v){} - IC SDuality& set (float _h, float _v) { - h=_h;v=_v; - return *this; - } - } duality; - struct SNoise { - float intensity, grain; - float fps; - SNoise (){} - SNoise (float _i, float _g, float _f):intensity(_i),grain(_g),fps(_f){} - IC SNoise& set (float _i, float _g, float _f){ - intensity=_i;grain=_g;fps=_f; - return *this; - } - } noise; - - SColor color_base; - SColor color_gray; - SColor color_add; - float cm_influence; - float cm_interpolate; - shared_str cm_tex1; - shared_str cm_tex2; - - SPPInfo& add (const SPPInfo &ppi); - SPPInfo& sub (const SPPInfo &ppi); - void normalize (); - SPPInfo (); - SPPInfo& lerp (const SPPInfo& def, const SPPInfo& to, float factor); - void validate(LPCSTR str); +struct ENGINE_API SPPInfo +{ + struct SColor + { + float r, g, b; + SColor() {} + SColor(float _r, float _g, float _b) :r(_r), g(_g), b(_b) {} + IC operator u32() + { + int _r = clampr(iFloor(r*255.f + .5f), 0, 255); + int _g = clampr(iFloor(g*255.f + .5f), 0, 255); + int _b = clampr(iFloor(b*255.f + .5f), 0, 255); + return color_rgba(_r, _g, _b, 0); + } + + IC operator const Fvector& () + { + return *((Fvector*)this); + } + + IC SColor& operator += (const SColor& ppi) + { + r += ppi.r; + g += ppi.g; + b += ppi.b; + return *this; + } + IC SColor& operator -= (const SColor& ppi) + { + r -= ppi.r; + g -= ppi.g; + b -= ppi.b; + return *this; + } + IC SColor& set(float _r, float _g, float _b) + { + r = _r; + g = _g; + b = _b; + return *this; + } + }; + float blur, gray; + struct SDuality + { + float h, v; + SDuality() {} + SDuality(float _h, float _v) :h(_h), v(_v) {} + IC SDuality& set(float _h, float _v) + { + h = _h; + v = _v; + return *this; + } + } duality; + struct SNoise + { + float intensity, grain; + float fps; + SNoise() {} + SNoise(float _i, float _g, float _f) :intensity(_i), grain(_g), fps(_f) {} + IC SNoise& set(float _i, float _g, float _f) + { + intensity = _i; + grain = _g; + fps = _f; + return *this; + } + } noise; + + SColor color_base; + SColor color_gray; + SColor color_add; + float cm_influence; + float cm_interpolate; + shared_str cm_tex1; + shared_str cm_tex2; + + SPPInfo& add(const SPPInfo& ppi); + SPPInfo& sub(const SPPInfo& ppi); + void normalize(); + SPPInfo(); + SPPInfo& lerp(const SPPInfo& def, const SPPInfo& to, float factor); + void validate(LPCSTR str); }; -DEFINE_LIST (CEffectorCam*,EffectorCamVec,EffectorCamIt); -DEFINE_VECTOR (CEffectorPP*,EffectorPPVec,EffectorPPIt); +DEFINE_LIST(CEffectorCam*, EffectorCamVec, EffectorCamIt); +DEFINE_VECTOR(CEffectorPP*, EffectorPPVec, EffectorPPIt); -#define effCustomEffectorStartID 10000 +#define effCustomEffectorStartID 10000 struct SCamEffectorInfo; class ENGINE_API CCameraManager { protected: - SCamEffectorInfo m_cam_info; + SCamEffectorInfo m_cam_info; - BENCH_SEC_SCRAMBLEMEMBER1 + BENCH_SEC_SCRAMBLEMEMBER1 - EffectorCamVec m_EffectorsCam; - EffectorCamVec m_EffectorsCam_added_deffered; - EffectorPPVec m_EffectorsPP; + EffectorCamVec m_EffectorsCam; + EffectorCamVec m_EffectorsCam_added_deffered; + EffectorPPVec m_EffectorsPP; - bool m_bAutoApply; - SPPInfo pp_affected; - void UpdateDeffered(); + bool m_bAutoApply; + SPPInfo pp_affected; + void UpdateDeffered(); - BENCH_SEC_SCRAMBLEVTBL1 - virtual void UpdateCamEffectors (); - virtual void UpdatePPEffectors (); - virtual bool ProcessCameraEffector (CEffectorCam* eff); - void OnEffectorReleased (SBaseEffector* e); + BENCH_SEC_SCRAMBLEVTBL1 + virtual void UpdateCamEffectors(); + virtual void UpdatePPEffectors(); + virtual bool ProcessCameraEffector(CEffectorCam* eff); + void OnEffectorReleased(SBaseEffector* e); public: -#ifdef DEBUG - u32 dbg_upd_frame; +#ifdef DEBUG + u32 dbg_upd_frame; #endif - BENCH_SEC_SCRAMBLEMEMBER2 - - void Dump (); - u32 Count () {return m_EffectorsCam.size()+m_EffectorsCam_added_deffered.size();} - CEffectorCam* AddCamEffector (CEffectorCam* ef); - CEffectorCam* GetCamEffector (ECamEffectorType type); - void RemoveCamEffector (ECamEffectorType type); - - ECamEffectorType RequestCamEffectorId (); - EEffectorPPType RequestPPEffectorId (); - CEffectorPP* GetPPEffector (EEffectorPPType type); - CEffectorPP* AddPPEffector (CEffectorPP* ef); - void RemovePPEffector (EEffectorPPType type); - - IC Fvector Position () const { return m_cam_info.p; } - IC Fvector Direction () const { return m_cam_info.d;} - IC Fvector Up () const { return m_cam_info.n; } - IC Fvector Right () const { return m_cam_info.r; } - IC float Fov () const { return m_cam_info.fFov; } - IC float Aspect () const { return m_cam_info.fAspect; } - - IC void camera_Matrix (Fmatrix& M){M.set(m_cam_info.r,m_cam_info.n,m_cam_info.d,m_cam_info.p);} - void Update (const Fvector& P, const Fvector& D, const Fvector& N, float fFOV_Dest, float fASPECT_Dest, float fFAR_Dest, u32 flags); - void UpdateFromCamera (const CCameraBase* C); - - void ApplyDevice (float _viewport_near); - static void ResetPP (); - - CCameraManager (bool bApplyOnUpdate); - virtual ~CCameraManager (); + BENCH_SEC_SCRAMBLEMEMBER2 + + void Dump(); + u32 Count() { return m_EffectorsCam.size() + m_EffectorsCam_added_deffered.size(); } + CEffectorCam* AddCamEffector(CEffectorCam* ef); + CEffectorCam* GetCamEffector(ECamEffectorType type); + void RemoveCamEffector(ECamEffectorType type); + + ECamEffectorType RequestCamEffectorId(); + EEffectorPPType RequestPPEffectorId(); + CEffectorPP* GetPPEffector(EEffectorPPType type); + CEffectorPP* AddPPEffector(CEffectorPP* ef); + void RemovePPEffector(EEffectorPPType type); + + IC Fvector Position() const { return m_cam_info.p; } + IC Fvector Direction() const { return m_cam_info.d; } + IC Fvector Up() const { return m_cam_info.n; } + IC Fvector Right() const { return m_cam_info.r; } + IC float Fov() const { return m_cam_info.fFov; } + IC float Aspect() const { return m_cam_info.fAspect; } + + IC void camera_Matrix(Fmatrix& M) { M.set(m_cam_info.r, m_cam_info.n, m_cam_info.d, m_cam_info.p); } + void Update(const Fvector& P, const Fvector& D, const Fvector& N, float fFOV_Dest, float fASPECT_Dest, float fFAR_Dest, u32 flags); + void UpdateFromCamera(const CCameraBase* C); + + void ApplyDevice(float _viewport_near); + static void ResetPP(); + + CCameraManager(bool bApplyOnUpdate); + virtual ~CCameraManager(); }; -ENGINE_API extern SPPInfo pp_identity; -ENGINE_API extern SPPInfo pp_zero; +ENGINE_API extern SPPInfo pp_identity; +ENGINE_API extern SPPInfo pp_zero; -ENGINE_API extern float psCamInert; -ENGINE_API extern float psCamSlideInert; +ENGINE_API extern float psCamInert; +ENGINE_API extern float psCamSlideInert; diff --git a/src/xrEngine/CopyProtection.h b/src/xrEngine/CopyProtection.h index d9070104673..0f8a63bcb3f 100644 --- a/src/xrEngine/CopyProtection.h +++ b/src/xrEngine/CopyProtection.h @@ -5,41 +5,47 @@ #endif // [4/28/2004] -#ifdef USE_COPYPROTECTION +#ifdef USE_COPYPROTECTION #pragma pack(push,1) -typedef struct SECUROM_PID{ - int pid_error; - unsigned long pid_version; - union{ - unsigned char pid_buf[264]; - struct{ - unsigned char pid_reserved[3]; - unsigned char pid_type; - unsigned long pid_length; - unsigned char pid_data[256]; - }; - }; -}tSECUROM_PID; +typedef struct SECUROM_PID +{ + int pid_error; + unsigned long pid_version; + union + { + unsigned char pid_buf[264]; + struct + { + unsigned char pid_reserved[3]; + unsigned char pid_type; + unsigned long pid_length; + unsigned char pid_data[256]; + }; + }; +} tSECUROM_PID; #pragma pack(pop) -IC void CheckCopyProtection () +IC void CheckCopyProtection() { - u32 ret; + u32 ret; - __asm{ - mov eax,8791h; - mov ebx,2107h; - mov ecx,6345h; - }; - ret=GetVersion(); + __asm + { + mov eax, 8791h; + mov ebx, 2107h; + mov ecx, 6345h; + }; + ret = GetVersion(); - if(ret!=0x6345){ - MessageBox(NULL,"Copy protection violation!","Error",MB_OK | MB_ICONHAND); - TerminateProcess(GetCurrentProcess(),0x66); - } + if (ret != 0x6345) + { + MessageBox(NULL, "Copy protection violation!", "Error", MB_OK | MB_ICONHAND); + TerminateProcess(GetCurrentProcess(), 0x66); + } } #else -IC void CheckCopyProtection () { +IC void CheckCopyProtection() +{ } #endif diff --git a/src/xrEngine/CustomHUD.cpp b/src/xrEngine/CustomHUD.cpp index 8ff11889857..427d17fa3cf 100644 --- a/src/xrEngine/CustomHUD.cpp +++ b/src/xrEngine/CustomHUD.cpp @@ -1,19 +1,19 @@ #include "stdafx.h" #include "CustomHUD.h" -Flags32 psHUD_Flags = {HUD_CROSSHAIR_RT|HUD_WEAPON_RT|HUD_WEAPON_RT2|HUD_CROSSHAIR_DYNAMIC|HUD_CROSSHAIR_RT2|HUD_DRAW_RT|HUD_DRAW_RT2}; +Flags32 psHUD_Flags = {HUD_CROSSHAIR_RT | HUD_WEAPON_RT | HUD_WEAPON_RT2 | HUD_CROSSHAIR_DYNAMIC | HUD_CROSSHAIR_RT2 | HUD_DRAW_RT | HUD_DRAW_RT2}; ENGINE_API CCustomHUD* g_hud = NULL; CCustomHUD::CCustomHUD() { - g_hud = this; - Device.seqResolutionChanged.Add(this); + g_hud = this; + Device.seqResolutionChanged.Add(this); } CCustomHUD::~CCustomHUD() { - g_hud = NULL; - Device.seqResolutionChanged.Remove(this); + g_hud = NULL; + Device.seqResolutionChanged.Remove(this); } diff --git a/src/xrEngine/CustomHUD.h b/src/xrEngine/CustomHUD.h index e86fae2abcb..828b24c9e91 100644 --- a/src/xrEngine/CustomHUD.h +++ b/src/xrEngine/CustomHUD.h @@ -1,47 +1,47 @@ #pragma once -ENGINE_API extern Flags32 psHUD_Flags; -#define HUD_CROSSHAIR (1<<0) -#define HUD_CROSSHAIR_DIST (1<<1) -#define HUD_WEAPON (1<<2) -#define HUD_INFO (1<<3) -#define HUD_DRAW (1<<4) -#define HUD_CROSSHAIR_RT (1<<5) -#define HUD_WEAPON_RT (1<<6) -#define HUD_CROSSHAIR_DYNAMIC (1<<7) -#define HUD_CROSSHAIR_RT2 (1<<9) -#define HUD_DRAW_RT (1<<10) -#define HUD_WEAPON_RT2 (1<<11) -#define HUD_DRAW_RT2 (1<<12) +ENGINE_API extern Flags32 psHUD_Flags; +#define HUD_CROSSHAIR (1<<0) +#define HUD_CROSSHAIR_DIST (1<<1) +#define HUD_WEAPON (1<<2) +#define HUD_INFO (1<<3) +#define HUD_DRAW (1<<4) +#define HUD_CROSSHAIR_RT (1<<5) +#define HUD_WEAPON_RT (1<<6) +#define HUD_CROSSHAIR_DYNAMIC (1<<7) +#define HUD_CROSSHAIR_RT2 (1<<9) +#define HUD_DRAW_RT (1<<10) +#define HUD_WEAPON_RT2 (1<<11) +#define HUD_DRAW_RT2 (1<<12) class ENGINE_API IRender_Visual; class CUI; -class ENGINE_API CCustomHUD: - public DLL_Pure, - public IEventReceiver, - public pureScreenResolutionChanged +class ENGINE_API CCustomHUD : + public DLL_Pure, + public IEventReceiver, + public pureScreenResolutionChanged { public: - CCustomHUD (); - virtual ~CCustomHUD (); - - BENCH_SEC_SCRAMBLEVTBL2 - - virtual void Render_First (){;} - virtual void Render_Last (){;} - - BENCH_SEC_SCRAMBLEVTBL1 - - virtual void OnFrame (){;} - virtual void OnEvent (EVENT E, u64 P1, u64 P2){;} - - virtual void Load (){;} - virtual void OnDisconnected ()=0; - virtual void OnConnected ()=0; - virtual void RenderActiveItemUI ()=0; - virtual bool RenderActiveItemUIQuery ()=0; - virtual void net_Relcase (CObject *object) = 0; + CCustomHUD(); + virtual ~CCustomHUD(); + + BENCH_SEC_SCRAMBLEVTBL2 + + virtual void Render_First() { ; } + virtual void Render_Last() { ; } + + BENCH_SEC_SCRAMBLEVTBL1 + + virtual void OnFrame() { ; } + virtual void OnEvent(EVENT E, u64 P1, u64 P2) { ; } + + virtual void Load() { ; } + virtual void OnDisconnected() = 0; + virtual void OnConnected() = 0; + virtual void RenderActiveItemUI() = 0; + virtual bool RenderActiveItemUIQuery() = 0; + virtual void net_Relcase(CObject* object) = 0; }; extern ENGINE_API CCustomHUD* g_hud; \ No newline at end of file diff --git a/src/xrEngine/Device_Initialize.cpp b/src/xrEngine/Device_Initialize.cpp index 5e2668b6a00..864b8d31456 100644 --- a/src/xrEngine/Device_Initialize.cpp +++ b/src/xrEngine/Device_Initialize.cpp @@ -3,89 +3,91 @@ #include "dedicated_server_only.h" #ifdef INGAME_EDITOR -# include "../include/editor/ide.hpp" -# include "engine_impl.hpp" +# include "../include/editor/ide.hpp" +# include "engine_impl.hpp" #endif // #ifdef INGAME_EDITOR -extern LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); +extern LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); #ifdef INGAME_EDITOR -void CRenderDevice::initialize_editor () +void CRenderDevice::initialize_editor() { - m_editor_module = LoadLibrary("editor.dll"); - if (!m_editor_module) { - Msg ("! cannot load library \"editor.dll\""); - return; - } + m_editor_module = LoadLibrary("editor.dll"); + if (!m_editor_module) + { + Msg("! cannot load library \"editor.dll\""); + return; + } - m_editor_initialize = (initialize_function_ptr)GetProcAddress(m_editor_module, "initialize"); - VERIFY (m_editor_initialize); + m_editor_initialize = (initialize_function_ptr)GetProcAddress(m_editor_module, "initialize"); + VERIFY(m_editor_initialize); - m_editor_finalize = (finalize_function_ptr)GetProcAddress(m_editor_module, "finalize"); - VERIFY (m_editor_finalize); + m_editor_finalize = (finalize_function_ptr)GetProcAddress(m_editor_module, "finalize"); + VERIFY(m_editor_finalize); - m_engine = xr_new(); - m_editor_initialize (m_editor, m_engine); - VERIFY (m_editor); + m_engine = xr_new(); + m_editor_initialize(m_editor, m_engine); + VERIFY(m_editor); - m_hWnd = m_editor->view_handle(); - VERIFY (m_hWnd != INVALID_HANDLE_VALUE); + m_hWnd = m_editor->view_handle(); + VERIFY(m_hWnd != INVALID_HANDLE_VALUE); } #endif // #ifdef INGAME_EDITOR -PROTECT_API void CRenderDevice::Initialize () +PROTECT_API void CRenderDevice::Initialize() { - Log("Initializing Engine..."); - TimerGlobal.Start (); - TimerMM.Start (); + Log("Initializing Engine..."); + TimerGlobal.Start(); + TimerMM.Start(); #ifdef INGAME_EDITOR - if (strstr(Core.Params,"-editor")) - initialize_editor (); + if (strstr(Core.Params, "-editor")) + initialize_editor(); #endif // #ifdef INGAME_EDITOR - // Unless a substitute hWnd has been specified, create a window to render into - if( m_hWnd == NULL) + // Unless a substitute hWnd has been specified, create a window to render into + if (m_hWnd == NULL) { - const char* wndclass ="_XRAY_1.5"; + const char* wndclass = "_XRAY_1.5"; // Register the windows class - HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(0); - WNDCLASS wndClass = { 0, WndProc, 0, 0, hInstance, - LoadIcon( hInstance, MAKEINTRESOURCE(IDI_ICON1) ), - LoadCursor( NULL, IDC_ARROW ), - (HBRUSH)GetStockObject(BLACK_BRUSH), - NULL, wndclass }; - RegisterClass( &wndClass ); + HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(0); + WNDCLASS wndClass = {0, WndProc, 0, 0, hInstance, + LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)), + LoadCursor(NULL, IDC_ARROW), + (HBRUSH)GetStockObject(BLACK_BRUSH), + NULL, wndclass + }; + RegisterClass(&wndClass); // Set the window's initial style m_dwWindowStyle = WS_BORDER | WS_DLGFRAME; // Set the window's initial width RECT rc; - SetRect ( &rc, 0, 0, 640, 480 ); - AdjustWindowRect( &rc, m_dwWindowStyle, FALSE ); + SetRect(&rc, 0, 0, 640, 480); + AdjustWindowRect(&rc, m_dwWindowStyle, FALSE); // Create the render window - m_hWnd = CreateWindowEx( WS_EX_TOPMOST, - wndclass, "S.T.A.L.K.E.R.: Call of Pripyat", m_dwWindowStyle, - /*rc.left, rc.top, */CW_USEDEFAULT, CW_USEDEFAULT, - (rc.right-rc.left), (rc.bottom-rc.top), 0L, - 0, hInstance, 0L ); + m_hWnd = CreateWindowEx(WS_EX_TOPMOST, + wndclass, "S.T.A.L.K.E.R.: Call of Pripyat", m_dwWindowStyle, + /*rc.left, rc.top, */CW_USEDEFAULT, CW_USEDEFAULT, + (rc.right - rc.left), (rc.bottom - rc.top), 0L, + 0, hInstance, 0L); } // Save window properties - m_dwWindowStyle = GetWindowLong( m_hWnd, GWL_STYLE ); - GetWindowRect ( m_hWnd, &m_rcWindowBounds ); - GetClientRect ( m_hWnd, &m_rcWindowClient ); - - /* - if (strstr(lpCmdLine,"-gpu_sw")!=NULL) HW.Caps.bForceGPU_SW = TRUE; - else HW.Caps.bForceGPU_SW = FALSE; - if (strstr(lpCmdLine,"-gpu_nopure")!=NULL) HW.Caps.bForceGPU_NonPure = TRUE; - else HW.Caps.bForceGPU_NonPure = FALSE; - if (strstr(lpCmdLine,"-gpu_ref")!=NULL) HW.Caps.bForceGPU_REF = TRUE; - else HW.Caps.bForceGPU_REF = FALSE; - */ + m_dwWindowStyle = GetWindowLong(m_hWnd, GWL_STYLE); + GetWindowRect(m_hWnd, &m_rcWindowBounds); + GetClientRect(m_hWnd, &m_rcWindowClient); + + /* + if (strstr(lpCmdLine,"-gpu_sw")!=NULL) HW.Caps.bForceGPU_SW = TRUE; + else HW.Caps.bForceGPU_SW = FALSE; + if (strstr(lpCmdLine,"-gpu_nopure")!=NULL) HW.Caps.bForceGPU_NonPure = TRUE; + else HW.Caps.bForceGPU_NonPure = FALSE; + if (strstr(lpCmdLine,"-gpu_ref")!=NULL) HW.Caps.bForceGPU_REF = TRUE; + else HW.Caps.bForceGPU_REF = FALSE; + */ } diff --git a/src/xrEngine/Device_Misc.cpp b/src/xrEngine/Device_Misc.cpp index b11bb9a5c52..bcae6e592f3 100644 --- a/src/xrEngine/Device_Misc.cpp +++ b/src/xrEngine/Device_Misc.cpp @@ -5,23 +5,26 @@ // Error handling //----------------------------- FLAGS -static struct _DF { - char * name; - u32 mask; -} DF[] = { - {"rsFullscreen", rsFullscreen }, - {"rsClearBB", rsClearBB }, - {"rsVSync", rsVSync }, - {"rsWireframe", rsWireframe }, - {NULL,0} +static struct _DF +{ + char* name; + u32 mask; +} DF[] = +{ + {"rsFullscreen", rsFullscreen}, + {"rsClearBB", rsClearBB}, + {"rsVSync", rsVSync}, + {"rsWireframe", rsWireframe}, + {NULL, 0} }; void CRenderDevice::DumpFlags() { - Log("- Dumping device flags"); - _DF *p = DF; - while (p->name) { - Msg("* %20s %s",p->name,psDeviceFlags.test(p->mask)?"on":"off"); - p++; - } + Log("- Dumping device flags"); + _DF* p = DF; + while (p->name) + { + Msg("* %20s %s", p->name, psDeviceFlags.test(p->mask) ? "on" : "off"); + p++; + } } diff --git a/src/xrEngine/Device_create.cpp b/src/xrEngine/Device_create.cpp index ce7a188142b..bfa907a30ca 100644 --- a/src/xrEngine/Device_create.cpp +++ b/src/xrEngine/Device_create.cpp @@ -9,202 +9,202 @@ #include "securom_api.h" -extern XRCDB_API BOOL *cdb_bDebug; +extern XRCDB_API BOOL* cdb_bDebug; -void SetupGPU(IRenderDeviceRender *pRender) +void SetupGPU(IRenderDeviceRender* pRender) { - // Command line - char *lpCmdLine = Core.Params; + // Command line + char* lpCmdLine = Core.Params; - BOOL bForceGPU_SW; - BOOL bForceGPU_NonPure; - BOOL bForceGPU_REF; + BOOL bForceGPU_SW; + BOOL bForceGPU_NonPure; + BOOL bForceGPU_REF; - if (strstr(lpCmdLine,"-gpu_sw")!=NULL) bForceGPU_SW = TRUE; - else bForceGPU_SW = FALSE; - if (strstr(lpCmdLine,"-gpu_nopure")!=NULL) bForceGPU_NonPure = TRUE; - else bForceGPU_NonPure = FALSE; - if (strstr(lpCmdLine,"-gpu_ref")!=NULL) bForceGPU_REF = TRUE; - else bForceGPU_REF = FALSE; + if (strstr(lpCmdLine, "-gpu_sw") != NULL) bForceGPU_SW = TRUE; + else bForceGPU_SW = FALSE; + if (strstr(lpCmdLine, "-gpu_nopure") != NULL) bForceGPU_NonPure = TRUE; + else bForceGPU_NonPure = FALSE; + if (strstr(lpCmdLine, "-gpu_ref") != NULL) bForceGPU_REF = TRUE; + else bForceGPU_REF = FALSE; - pRender->SetupGPU(bForceGPU_SW, bForceGPU_NonPure, bForceGPU_REF); + pRender->SetupGPU(bForceGPU_SW, bForceGPU_NonPure, bForceGPU_REF); } -void CRenderDevice::_SetupStates () +void CRenderDevice::_SetupStates() { - // General Render States - mView.identity (); - mProject.identity (); - mFullTransform.identity (); - vCameraPosition.set (0,0,0); - vCameraDirection.set (0,0,1); - vCameraTop.set (0,1,0); - vCameraRight.set (1,0,0); - - m_pRender->SetupStates(); - - /* - HW.Caps.Update (); - for (u32 i=0; iSetSamplerState ( i, D3DSAMP_MAXANISOTROPY, 4 )); - CHK_DX(HW.pDevice->SetSamplerState ( i, D3DSAMP_MIPMAPLODBIAS, *((LPDWORD) (&fBias)))); - CHK_DX(HW.pDevice->SetSamplerState ( i, D3DSAMP_MINFILTER, D3DTEXF_LINEAR )); - CHK_DX(HW.pDevice->SetSamplerState ( i, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR )); - CHK_DX(HW.pDevice->SetSamplerState ( i, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR )); - } - CHK_DX(HW.pDevice->SetRenderState( D3DRS_DITHERENABLE, TRUE )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_COLORVERTEX, TRUE )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_ZENABLE, TRUE )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_SHADEMODE, D3DSHADE_GOURAUD )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_ALPHAFUNC, D3DCMP_GREATER )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_LOCALVIEWER, TRUE )); - - CHK_DX(HW.pDevice->SetRenderState( D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_SPECULARMATERIALSOURCE,D3DMCS_MATERIAL )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_EMISSIVEMATERIALSOURCE,D3DMCS_COLOR1 )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_MULTISAMPLEANTIALIAS, FALSE )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_NORMALIZENORMALS, TRUE )); - - if (psDeviceFlags.test(rsWireframe)) { CHK_DX(HW.pDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_WIREFRAME )); } - else { CHK_DX(HW.pDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID )); } - - // ******************** Fog parameters - CHK_DX(HW.pDevice->SetRenderState( D3DRS_FOGCOLOR, 0 )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_RANGEFOGENABLE, FALSE )); - if (HW.Caps.bTableFog) { - CHK_DX(HW.pDevice->SetRenderState( D3DRS_FOGTABLEMODE, D3DFOG_LINEAR )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_FOGVERTEXMODE, D3DFOG_NONE )); - } else { - CHK_DX(HW.pDevice->SetRenderState( D3DRS_FOGTABLEMODE, D3DFOG_NONE )); - CHK_DX(HW.pDevice->SetRenderState( D3DRS_FOGVERTEXMODE, D3DFOG_LINEAR )); - } - */ + // General Render States + mView.identity(); + mProject.identity(); + mFullTransform.identity(); + vCameraPosition.set(0, 0, 0); + vCameraDirection.set(0, 0, 1); + vCameraTop.set(0, 1, 0); + vCameraRight.set(1, 0, 0); + + m_pRender->SetupStates(); + + /* + HW.Caps.Update (); + for (u32 i=0; iSetSamplerState ( i, D3DSAMP_MAXANISOTROPY, 4 )); + CHK_DX(HW.pDevice->SetSamplerState ( i, D3DSAMP_MIPMAPLODBIAS, *((LPDWORD) (&fBias)))); + CHK_DX(HW.pDevice->SetSamplerState ( i, D3DSAMP_MINFILTER, D3DTEXF_LINEAR )); + CHK_DX(HW.pDevice->SetSamplerState ( i, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR )); + CHK_DX(HW.pDevice->SetSamplerState ( i, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR )); + } + CHK_DX(HW.pDevice->SetRenderState( D3DRS_DITHERENABLE, TRUE )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_COLORVERTEX, TRUE )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_ZENABLE, TRUE )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_SHADEMODE, D3DSHADE_GOURAUD )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_ALPHAFUNC, D3DCMP_GREATER )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_LOCALVIEWER, TRUE )); + + CHK_DX(HW.pDevice->SetRenderState( D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_SPECULARMATERIALSOURCE,D3DMCS_MATERIAL )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_EMISSIVEMATERIALSOURCE,D3DMCS_COLOR1 )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_MULTISAMPLEANTIALIAS, FALSE )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_NORMALIZENORMALS, TRUE )); + + if (psDeviceFlags.test(rsWireframe)) { CHK_DX(HW.pDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_WIREFRAME )); } + else { CHK_DX(HW.pDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID )); } + + // ******************** Fog parameters + CHK_DX(HW.pDevice->SetRenderState( D3DRS_FOGCOLOR, 0 )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_RANGEFOGENABLE, FALSE )); + if (HW.Caps.bTableFog) { + CHK_DX(HW.pDevice->SetRenderState( D3DRS_FOGTABLEMODE, D3DFOG_LINEAR )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_FOGVERTEXMODE, D3DFOG_NONE )); + } else { + CHK_DX(HW.pDevice->SetRenderState( D3DRS_FOGTABLEMODE, D3DFOG_NONE )); + CHK_DX(HW.pDevice->SetRenderState( D3DRS_FOGVERTEXMODE, D3DFOG_LINEAR )); + } + */ } /* -void CRenderDevice::_Create (LPCSTR shName) +void CRenderDevice::_Create (LPCSTR shName) { - Memory.mem_compact (); +Memory.mem_compact (); - // after creation - b_is_Ready = TRUE; - _SetupStates (); +// after creation +b_is_Ready = TRUE; +_SetupStates (); - // Signal everyone - device created - RCache.OnDeviceCreate (); - Gamma.Update (); - Resources->OnDeviceCreate (shName); - ::Render->create (); - Statistic->OnDeviceCreate (); +// Signal everyone - device created +RCache.OnDeviceCreate (); +Gamma.Update (); +Resources->OnDeviceCreate (shName); +::Render->create (); +Statistic->OnDeviceCreate (); #ifndef DEDICATED_SERVER - m_WireShader.create ("editor\\wire"); - m_SelectionShader.create ("editor\\selection"); +m_WireShader.create ("editor\\wire"); +m_SelectionShader.create ("editor\\selection"); - DU.OnDeviceCreate (); +DU.OnDeviceCreate (); #endif - dwFrame = 0; +dwFrame = 0; } */ -void CRenderDevice::_Create (LPCSTR shName) +void CRenderDevice::_Create(LPCSTR shName) { - Memory.mem_compact (); + Memory.mem_compact(); - // after creation - b_is_Ready = TRUE; - _SetupStates (); + // after creation + b_is_Ready = TRUE; + _SetupStates(); - m_pRender->OnDeviceCreate(shName); + m_pRender->OnDeviceCreate(shName); - dwFrame = 0; + dwFrame = 0; } /* -void CRenderDevice::Create () +void CRenderDevice::Create () { - if (b_is_Ready) return; // prevent double call - Statistic = xr_new(); - Log ("Starting RENDER device..."); +if (b_is_Ready) return; // prevent double call +Statistic = xr_new(); +Log ("Starting RENDER device..."); #ifdef _EDITOR - psCurrentVidMode[0] = dwWidth; - psCurrentVidMode[1] = dwHeight; +psCurrentVidMode[0] = dwWidth; +psCurrentVidMode[1] = dwHeight; #endif - HW.CreateDevice (m_hWnd); - dwWidth = HW.DevPP.BackBufferWidth ; - dwHeight = HW.DevPP.BackBufferHeight ; - fWidth_2 = float(dwWidth/2) ; - fHeight_2 = float(dwHeight/2) ; - fFOV = 90.f; - fASPECT = 1.f; +HW.CreateDevice (m_hWnd); +dwWidth = HW.DevPP.BackBufferWidth ; +dwHeight = HW.DevPP.BackBufferHeight ; +fWidth_2 = float(dwWidth/2) ; +fHeight_2 = float(dwHeight/2) ; +fFOV = 90.f; +fASPECT = 1.f; - string_path fname; - FS.update_path (fname,"$game_data$","shaders.xr"); +string_path fname; +FS.update_path (fname,"$game_data$","shaders.xr"); - ////////////////////////////////////////////////////////////////////////// - Resources = xr_new (); - _Create (fname); +////////////////////////////////////////////////////////////////////////// +Resources = xr_new (); +_Create (fname); - PreCache (0); +PreCache (0); } */ void CRenderDevice::ConnectToRender() { - if (!m_pRender) - m_pRender = RenderFactory->CreateRenderDeviceRender(); + if (!m_pRender) + m_pRender = RenderFactory->CreateRenderDeviceRender(); } -PROTECT_API void CRenderDevice::Create () +PROTECT_API void CRenderDevice::Create() { - SECUROM_MARKER_SECURITY_ON(4) + SECUROM_MARKER_SECURITY_ON(4) - if (b_is_Ready) return; // prevent double call - Statistic = xr_new(); + if (b_is_Ready) return; // prevent double call + Statistic = xr_new(); -#ifdef DEBUG -cdb_clRAY = &Statistic->clRAY; // total: ray-testing -cdb_clBOX = &Statistic->clBOX; // total: box query -cdb_clFRUSTUM = &Statistic->clFRUSTUM; // total: frustum query -cdb_bDebug = &bDebug; +#ifdef DEBUG + cdb_clRAY = &Statistic->clRAY; // total: ray-testing + cdb_clBOX = &Statistic->clBOX; // total: box query + cdb_clFRUSTUM = &Statistic->clFRUSTUM; // total: frustum query + cdb_bDebug = &bDebug; #endif - if (!m_pRender) - m_pRender = RenderFactory->CreateRenderDeviceRender(); - SetupGPU(m_pRender); - Log ("Starting RENDER device..."); + if (!m_pRender) + m_pRender = RenderFactory->CreateRenderDeviceRender(); + SetupGPU(m_pRender); + Log("Starting RENDER device..."); #ifdef _EDITOR - psCurrentVidMode[0] = dwWidth; - psCurrentVidMode[1] = dwHeight; + psCurrentVidMode[0] = dwWidth; + psCurrentVidMode[1] = dwHeight; #endif // #ifdef _EDITOR - fFOV = 90.f; - fASPECT = 1.f; - m_pRender->Create ( - m_hWnd, - dwWidth, - dwHeight, - fWidth_2, - fHeight_2, + fFOV = 90.f; + fASPECT = 1.f; + m_pRender->Create( + m_hWnd, + dwWidth, + dwHeight, + fWidth_2, + fHeight_2, #ifdef INGAME_EDITOR - editor() ? false : + editor() ? false : #endif // #ifdef INGAME_EDITOR - true - ); + true + ); - string_path fname; - FS.update_path (fname,"$game_data$","shaders.xr"); + string_path fname; + FS.update_path(fname, "$game_data$", "shaders.xr"); - ////////////////////////////////////////////////////////////////////////// - _Create (fname); + ////////////////////////////////////////////////////////////////////////// + _Create(fname); - PreCache (0, false, false); + PreCache(0, false, false); - SECUROM_MARKER_SECURITY_OFF(4) + SECUROM_MARKER_SECURITY_OFF(4) } \ No newline at end of file diff --git a/src/xrEngine/Device_destroy.cpp b/src/xrEngine/Device_destroy.cpp index 62fff55aa98..d0f64d8bf74 100644 --- a/src/xrEngine/Device_destroy.cpp +++ b/src/xrEngine/Device_destroy.cpp @@ -5,92 +5,94 @@ #include "IGame_Persistent.h" #include "xr_IOConsole.h" -void CRenderDevice::_Destroy (BOOL bKeepTextures) +void CRenderDevice::_Destroy(BOOL bKeepTextures) { - DU->OnDeviceDestroy(); + DU->OnDeviceDestroy(); - // before destroy - b_is_Ready = FALSE; - Statistic->OnDeviceDestroy (); - ::Render->destroy (); - m_pRender->OnDeviceDestroy(bKeepTextures); - //Resources->OnDeviceDestroy (bKeepTextures); - //RCache.OnDeviceDestroy (); + // before destroy + b_is_Ready = FALSE; + Statistic->OnDeviceDestroy(); + ::Render->destroy(); + m_pRender->OnDeviceDestroy(bKeepTextures); + //Resources->OnDeviceDestroy (bKeepTextures); + //RCache.OnDeviceDestroy (); - Memory.mem_compact (); + Memory.mem_compact(); } -void CRenderDevice::Destroy (void) { - if (!b_is_Ready) return; +void CRenderDevice::Destroy(void) +{ + if (!b_is_Ready) return; - Log("Destroying Direct3D..."); + Log("Destroying Direct3D..."); - ShowCursor (TRUE); - m_pRender->ValidateHW(); + ShowCursor(TRUE); + m_pRender->ValidateHW(); - _Destroy (FALSE); + _Destroy(FALSE); - // real destroy - m_pRender->DestroyHW(); + // real destroy + m_pRender->DestroyHW(); - //xr_delete (Resources); - //HW.DestroyDevice (); + //xr_delete (Resources); + //HW.DestroyDevice (); - seqRender.R.clear (); - seqAppActivate.R.clear (); - seqAppDeactivate.R.clear (); - seqAppStart.R.clear (); - seqAppEnd.R.clear (); - seqFrame. R.clear (); - seqFrameMT.R.clear (); - seqDeviceReset.R.clear (); - seqParallel.clear (); + seqRender.R.clear(); + seqAppActivate.R.clear(); + seqAppDeactivate.R.clear(); + seqAppStart.R.clear(); + seqAppEnd.R.clear(); + seqFrame.R.clear(); + seqFrameMT.R.clear(); + seqDeviceReset.R.clear(); + seqParallel.clear(); - RenderFactory->DestroyRenderDeviceRender(m_pRender); - m_pRender = 0; - xr_delete (Statistic); + RenderFactory->DestroyRenderDeviceRender(m_pRender); + m_pRender = 0; + xr_delete(Statistic); } #include "IGame_Level.h" #include "CustomHUD.h" extern BOOL bNeed_re_create_env; -void CRenderDevice::Reset (bool precache) +void CRenderDevice::Reset(bool precache) { - u32 dwWidth_before = dwWidth; - u32 dwHeight_before = dwHeight; - - ShowCursor (TRUE); - u32 tm_start = TimerAsync(); - if (g_pGamePersistent){ - -//. g_pGamePersistent->Environment().OnDeviceDestroy(); - } - - m_pRender->Reset( m_hWnd, dwWidth, dwHeight, fWidth_2, fHeight_2); - - if (g_pGamePersistent) - { -//. g_pGamePersistent->Environment().OnDeviceCreate(); - //bNeed_re_create_env = TRUE; - g_pGamePersistent->Environment().bNeed_re_create_env = TRUE; - } - _SetupStates (); - if (precache) - PreCache (20, true, false); - u32 tm_end = TimerAsync(); - Msg ("*** RESET [%d ms]",tm_end-tm_start); - - // TODO: Remove this! It may hide crash - Memory.mem_compact(); + u32 dwWidth_before = dwWidth; + u32 dwHeight_before = dwHeight; + + ShowCursor(TRUE); + u32 tm_start = TimerAsync(); + if (g_pGamePersistent) + { + + //. g_pGamePersistent->Environment().OnDeviceDestroy(); + } + + m_pRender->Reset(m_hWnd, dwWidth, dwHeight, fWidth_2, fHeight_2); + + if (g_pGamePersistent) + { + //. g_pGamePersistent->Environment().OnDeviceCreate(); + //bNeed_re_create_env = TRUE; + g_pGamePersistent->Environment().bNeed_re_create_env = TRUE; + } + _SetupStates(); + if (precache) + PreCache(20, true, false); + u32 tm_end = TimerAsync(); + Msg("*** RESET [%d ms]", tm_end - tm_start); + + // TODO: Remove this! It may hide crash + Memory.mem_compact(); #ifndef DEDICATED_SERVER - ShowCursor (FALSE); + ShowCursor(FALSE); #endif - - seqDeviceReset.Process(rp_DeviceReset); - if(dwWidth_before!=dwWidth || dwHeight_before!=dwHeight) - { - seqResolutionChanged.Process(rp_ScreenResolutionChanged); - } + seqDeviceReset.Process(rp_DeviceReset); + + if (dwWidth_before != dwWidth || dwHeight_before != dwHeight) + { + seqResolutionChanged.Process(rp_ScreenResolutionChanged); + } } diff --git a/src/xrEngine/Device_overdraw.cpp b/src/xrEngine/Device_overdraw.cpp index 85dcca4a397..d2a6b60b430 100644 --- a/src/xrEngine/Device_overdraw.cpp +++ b/src/xrEngine/Device_overdraw.cpp @@ -1,13 +1,13 @@ #include "stdafx.h" -void CRenderDevice::overdrawBegin () +void CRenderDevice::overdrawBegin() { - VERIFY(0); - m_pRender->overdrawBegin(); + VERIFY(0); + m_pRender->overdrawBegin(); } -void CRenderDevice::overdrawEnd () +void CRenderDevice::overdrawEnd() { - VERIFY(0); - m_pRender->overdrawEnd(); + VERIFY(0); + m_pRender->overdrawEnd(); } diff --git a/src/xrEngine/Device_wndproc.cpp b/src/xrEngine/Device_wndproc.cpp index 4bdb937d261..20af8b286ad 100644 --- a/src/xrEngine/Device_wndproc.cpp +++ b/src/xrEngine/Device_wndproc.cpp @@ -1,69 +1,77 @@ #include "stdafx.h" -bool CRenderDevice::on_message (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT &result) +bool CRenderDevice::on_message(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result) { - switch (uMsg) { - case WM_SYSKEYDOWN : { - return true; - } - case WM_ACTIVATE : { + switch (uMsg) + { + case WM_SYSKEYDOWN: + { + return true; + } + case WM_ACTIVATE: + { #ifdef INGAME_EDITOR - if (editor()) { - Device.b_is_Active = TRUE; - break; - } + if (editor()) + { + Device.b_is_Active = TRUE; + break; + } #endif // #ifdef INGAME_EDITOR - OnWM_Activate (wParam, lParam); - return (false); - } - case WM_SETCURSOR : { + OnWM_Activate(wParam, lParam); + return (false); + } + case WM_SETCURSOR: + { #ifdef INGAME_EDITOR - if (editor()) - break; + if (editor()) + break; #endif // #ifdef INGAME_EDITOR - result = 1; - return (true); - } - case WM_SYSCOMMAND : { + result = 1; + return (true); + } + case WM_SYSCOMMAND: + { #ifdef INGAME_EDITOR - if (editor()) - break; + if (editor()) + break; #endif // #ifdef INGAME_EDITOR - // Prevent moving/sizing and power loss in fullscreen mode - switch (wParam) { - case SC_MOVE: - case SC_SIZE: - case SC_MAXIMIZE: - case SC_MONITORPOWER: - result = 1; - return (true); - } - return (false); - } - case WM_CLOSE : { + // Prevent moving/sizing and power loss in fullscreen mode + switch (wParam) + { + case SC_MOVE: + case SC_SIZE: + case SC_MAXIMIZE: + case SC_MONITORPOWER: + result = 1; + return (true); + } + return (false); + } + case WM_CLOSE: + { #ifdef INGAME_EDITOR - if (editor()) - break; + if (editor()) + break; #endif // #ifdef INGAME_EDITOR - result = 0; - return (true); - } - } + result = 0; + return (true); + } + } - return (false); + return (false); } //----------------------------------------------------------------------------- // Name: WndProc() // Desc: Static msg handler which passes messages to the application class. //----------------------------------------------------------------------------- -LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) +LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { - LRESULT result; - if (Device.on_message(hWnd, uMsg, wParam, lParam, result)) - return (result); + LRESULT result; + if (Device.on_message(hWnd, uMsg, wParam, lParam, result)) + return (result); - return (DefWindowProc(hWnd, uMsg, wParam, lParam)); + return (DefWindowProc(hWnd, uMsg, wParam, lParam)); } diff --git a/src/xrEngine/Effector.h b/src/xrEngine/Effector.h index 5a4cf6c8063..a92c21a881b 100644 --- a/src/xrEngine/Effector.h +++ b/src/xrEngine/Effector.h @@ -7,27 +7,27 @@ class ENGINE_API CEffectorCam :public SBaseEffector { protected: - ECamEffectorType eType; - - friend class CCameraManager; - float fLifeTime; - bool bHudAffect; + ECamEffectorType eType; + + friend class CCameraManager; + float fLifeTime; + bool bHudAffect; public: - CEffectorCam (ECamEffectorType type, float tm) {eType=type; fLifeTime=tm; bHudAffect=true;}; - CEffectorCam () {eType=(ECamEffectorType)0; fLifeTime=0.0f; bHudAffect=true;}; - virtual ~CEffectorCam () {}; - void SetType (ECamEffectorType type) {eType=type;} - void SetHudAffect (bool val) {bHudAffect=val;} - bool GetHudAffect () {return bHudAffect;} - - IC ECamEffectorType GetType () {return eType;} - virtual BOOL Valid () {return fLifeTime>0.0f;} - - BENCH_SEC_SCRAMBLEVTBL1 - - virtual BOOL ProcessCam (SCamEffectorInfo& info) {fLifeTime-=Device.fTimeDelta; return Valid();};; - - virtual void ProcessIfInvalid(SCamEffectorInfo& info) {}; - virtual BOOL AllowProcessingIfInvalid() {return FALSE;} - virtual bool AbsolutePositioning() {return false;} + CEffectorCam(ECamEffectorType type, float tm) { eType = type; fLifeTime = tm; bHudAffect = true; }; + CEffectorCam() { eType = (ECamEffectorType)0; fLifeTime = 0.0f; bHudAffect = true; }; + virtual ~CEffectorCam() {}; + void SetType(ECamEffectorType type) { eType = type; } + void SetHudAffect(bool val) { bHudAffect = val; } + bool GetHudAffect() { return bHudAffect; } + + IC ECamEffectorType GetType() { return eType; } + virtual BOOL Valid() { return fLifeTime > 0.0f; } + + BENCH_SEC_SCRAMBLEVTBL1 + + virtual BOOL ProcessCam(SCamEffectorInfo& info) { fLifeTime -= Device.fTimeDelta; return Valid(); };; + + virtual void ProcessIfInvalid(SCamEffectorInfo& info) {}; + virtual BOOL AllowProcessingIfInvalid() { return FALSE; } + virtual bool AbsolutePositioning() { return false; } }; diff --git a/src/xrEngine/EffectorPP.cpp b/src/xrEngine/EffectorPP.cpp index 0b23716f1ed..af3873408f9 100644 --- a/src/xrEngine/EffectorPP.cpp +++ b/src/xrEngine/EffectorPP.cpp @@ -10,18 +10,18 @@ // Construction/Destruction ////////////////////////////////////////////////////////////////////// -CEffectorPP::CEffectorPP(EEffectorPPType type, f32 lifeTime, bool free_on_remove) -:bOverlap(true) +CEffectorPP::CEffectorPP(EEffectorPPType type, f32 lifeTime, bool free_on_remove) + :bOverlap(true) { - eType = type; - fLifeTime = lifeTime; - bFreeOnRemove = free_on_remove; + eType = type; + fLifeTime = lifeTime; + bFreeOnRemove = free_on_remove; } CEffectorPP::~CEffectorPP() {} -BOOL CEffectorPP::Process(SPPInfo &PPInfo) +BOOL CEffectorPP::Process(SPPInfo& PPInfo) { - fLifeTime -= Device.fTimeDelta; - return TRUE; + fLifeTime -= Device.fTimeDelta; + return TRUE; } diff --git a/src/xrEngine/EffectorPP.h b/src/xrEngine/EffectorPP.h index c0ad923a74b..800b4305251 100644 --- a/src/xrEngine/EffectorPP.h +++ b/src/xrEngine/EffectorPP.h @@ -6,21 +6,21 @@ struct SPPInfo; // ïîñòïðîöåññ class ENGINE_API CEffectorPP :public SBaseEffector { - EEffectorPPType eType; - bool bFreeOnRemove; + EEffectorPPType eType; + bool bFreeOnRemove; protected: - float fLifeTime; + float fLifeTime; public: - CEffectorPP (EEffectorPPType type, f32 lifeTime, bool free_on_remove=true); - CEffectorPP ():bFreeOnRemove(true),fLifeTime(0.0f),bOverlap(true){}; - virtual ~CEffectorPP (); - BENCH_SEC_SCRAMBLEVTBL1 - virtual BOOL Process (SPPInfo &PPInfo); - virtual BOOL Valid () {return fLifeTime>0.0f;} - IC EEffectorPPType Type () const {return eType;} - IC bool FreeOnRemove () const {return bFreeOnRemove;} - IC void SetType (EEffectorPPType t) {eType=t;} - virtual void Stop (float speed) {fLifeTime=0.0f;}; + CEffectorPP(EEffectorPPType type, f32 lifeTime, bool free_on_remove = true); + CEffectorPP() :bFreeOnRemove(true), fLifeTime(0.0f), bOverlap(true) {}; + virtual ~CEffectorPP(); + BENCH_SEC_SCRAMBLEVTBL1 + virtual BOOL Process(SPPInfo& PPInfo); + virtual BOOL Valid() { return fLifeTime > 0.0f; } + IC EEffectorPPType Type() const { return eType; } + IC bool FreeOnRemove() const { return bFreeOnRemove; } + IC void SetType(EEffectorPPType t) { eType = t; } + virtual void Stop(float speed) { fLifeTime = 0.0f; }; - bool bOverlap; + bool bOverlap; }; diff --git a/src/xrEngine/Engine.cpp b/src/xrEngine/Engine.cpp index 41280ce9dc6..035781fb2de 100644 --- a/src/xrEngine/Engine.cpp +++ b/src/xrEngine/Engine.cpp @@ -6,8 +6,8 @@ #include "Engine.h" #include "dedicated_server_only.h" -CEngine Engine; -xrDispatchTable PSGP; +CEngine Engine; +xrDispatchTable PSGP; ////////////////////////////////////////////////////////////////////// // Construction/Destruction @@ -15,51 +15,53 @@ xrDispatchTable PSGP; CEngine::CEngine() { - + } CEngine::~CEngine() { - + } -extern void msCreate (LPCSTR name); +extern void msCreate(LPCSTR name); -PROTECT_API void CEngine::Initialize (void) +PROTECT_API void CEngine::Initialize(void) { - // Bind PSGP - hPSGP = LoadLibrary("xrCPU_Pipe.dll"); - R_ASSERT (hPSGP); - xrBinder* bindCPU = (xrBinder*) GetProcAddress(hPSGP,"xrBind_PSGP"); R_ASSERT(bindCPU); - bindCPU (&PSGP, &CPU::ID ); + // Bind PSGP + hPSGP = LoadLibrary("xrCPU_Pipe.dll"); + R_ASSERT(hPSGP); + xrBinder* bindCPU = (xrBinder*)GetProcAddress(hPSGP, "xrBind_PSGP"); + R_ASSERT(bindCPU); + bindCPU(&PSGP, &CPU::ID); - // Other stuff - Engine.Sheduler.Initialize ( ); - // + // Other stuff + Engine.Sheduler.Initialize(); + // #ifdef DEBUG - msCreate ("game"); + msCreate("game"); #endif } typedef void __cdecl ttapi_Done_func(void); -void CEngine::Destroy () +void CEngine::Destroy() { - Engine.Sheduler.Destroy ( ); + Engine.Sheduler.Destroy(); #ifdef DEBUG_MEMORY_MANAGER - extern void dbg_dump_leaks_prepare ( ); - if (Memory.debug_mode) dbg_dump_leaks_prepare (); + extern void dbg_dump_leaks_prepare(); + if (Memory.debug_mode) dbg_dump_leaks_prepare(); #endif // DEBUG_MEMORY_MANAGER - Engine.External.Destroy ( ); - - if (hPSGP) - { - ttapi_Done_func* ttapi_Done = (ttapi_Done_func*) GetProcAddress(hPSGP,"ttapi_Done"); R_ASSERT(ttapi_Done); - if (ttapi_Done) - ttapi_Done(); + Engine.External.Destroy(); + + if (hPSGP) + { + ttapi_Done_func* ttapi_Done = (ttapi_Done_func*)GetProcAddress(hPSGP, "ttapi_Done"); + R_ASSERT(ttapi_Done); + if (ttapi_Done) + ttapi_Done(); - FreeLibrary (hPSGP); - hPSGP =0; - ZeroMemory (&PSGP,sizeof(PSGP)); - } + FreeLibrary(hPSGP); + hPSGP = 0; + ZeroMemory(&PSGP, sizeof(PSGP)); + } } diff --git a/src/xrEngine/Engine.h b/src/xrEngine/Engine.h index 43cc1e2a857..f1f0dc72feb 100644 --- a/src/xrEngine/Engine.h +++ b/src/xrEngine/Engine.h @@ -13,22 +13,22 @@ class ENGINE_API CEngine { - HMODULE hPSGP; + HMODULE hPSGP; public: - BENCH_SEC_SCRAMBLEMEMBER1 - // DLL api stuff - CEngineAPI External; - CEventAPI Event; - CSheduler Sheduler; + BENCH_SEC_SCRAMBLEMEMBER1 + // DLL api stuff + CEngineAPI External; + CEventAPI Event; + CSheduler Sheduler; - void Initialize (); - void Destroy (); - - CEngine(); - ~CEngine(); + void Initialize(); + void Destroy(); + + CEngine(); + ~CEngine(); }; -ENGINE_API extern xrDispatchTable PSGP; -ENGINE_API extern CEngine Engine; +ENGINE_API extern xrDispatchTable PSGP; +ENGINE_API extern CEngine Engine; #endif // !defined(AFX_ENGINE_H__22802DD7_D7EB_4234_9781_E237657471AC__INCLUDED_) diff --git a/src/xrEngine/EngineAPI.cpp b/src/xrEngine/EngineAPI.cpp index 8a8eca50125..9b4e0c7d0d6 100644 --- a/src/xrEngine/EngineAPI.cpp +++ b/src/xrEngine/EngineAPI.cpp @@ -14,373 +14,392 @@ extern xr_token* vid_quality_token; // Construction/Destruction ////////////////////////////////////////////////////////////////////// -void __cdecl dummy (void) { +void __cdecl dummy(void) +{ }; -CEngineAPI::CEngineAPI () +CEngineAPI::CEngineAPI() { - hGame = 0; - hRender = 0; - hTuner = 0; - pCreate = 0; - pDestroy = 0; - tune_pause = dummy ; - tune_resume = dummy ; + hGame = 0; + hRender = 0; + hTuner = 0; + pCreate = 0; + pDestroy = 0; + tune_pause = dummy; + tune_resume = dummy; } CEngineAPI::~CEngineAPI() { - // destroy quality token here - if (vid_quality_token) - { - for( int i=0; vid_quality_token[i].name; i++ ) - { - xr_free (vid_quality_token[i].name); - } - xr_free (vid_quality_token); - vid_quality_token = NULL; - } + // destroy quality token here + if (vid_quality_token) + { + for (int i = 0; vid_quality_token[i].name; i++) + { + xr_free(vid_quality_token[i].name); + } + xr_free(vid_quality_token); + vid_quality_token = NULL; + } } extern u32 renderer_value; //con cmd ENGINE_API int g_current_renderer = 0; -ENGINE_API bool is_enough_address_space_available () +ENGINE_API bool is_enough_address_space_available() { - SYSTEM_INFO system_info; + SYSTEM_INFO system_info; - SECUROM_MARKER_HIGH_SECURITY_ON(12) + SECUROM_MARKER_HIGH_SECURITY_ON(12) - GetSystemInfo ( &system_info ); + GetSystemInfo(&system_info); - SECUROM_MARKER_HIGH_SECURITY_OFF(12) + SECUROM_MARKER_HIGH_SECURITY_OFF(12) - return (*(u32*)&system_info.lpMaximumApplicationAddress) > 0x90000000; + return (*(u32*)&system_info.lpMaximumApplicationAddress) > 0x90000000; } #ifndef DEDICATED_SERVER void CEngineAPI::InitializeNotDedicated() { - SECUROM_MARKER_HIGH_SECURITY_ON(2) - - LPCSTR r2_name = "xrRender_R2.dll"; - LPCSTR r3_name = "xrRender_R3.dll"; - LPCSTR r4_name = "xrRender_R4.dll"; - - if (psDeviceFlags.test(rsR4)) - { - // try to initialize R4 - Log ("Loading DLL:", r4_name); - hRender = LoadLibrary (r4_name); - if (0==hRender) - { - // try to load R1 - Msg ("! ...Failed - incompatible hardware/pre-Vista OS."); - psDeviceFlags.set (rsR2,TRUE); - } - } - - if (psDeviceFlags.test(rsR3)) - { - // try to initialize R3 - Log ("Loading DLL:", r3_name); - hRender = LoadLibrary (r3_name); - if (0==hRender) - { - // try to load R1 - Msg ("! ...Failed - incompatible hardware/pre-Vista OS."); - psDeviceFlags.set (rsR2,TRUE); - } - else - g_current_renderer = 3; - } - - if (psDeviceFlags.test(rsR2)) - { - // try to initialize R2 - psDeviceFlags.set (rsR4,FALSE); - psDeviceFlags.set (rsR3,FALSE); - Log ("Loading DLL:", r2_name); - hRender = LoadLibrary (r2_name); - if (0==hRender) - { - // try to load R1 - Msg ("! ...Failed - incompatible hardware."); - } - else - g_current_renderer = 2; - } - - SECUROM_MARKER_HIGH_SECURITY_OFF(2) + SECUROM_MARKER_HIGH_SECURITY_ON(2) + + LPCSTR r2_name = "xrRender_R2.dll"; + LPCSTR r3_name = "xrRender_R3.dll"; + LPCSTR r4_name = "xrRender_R4.dll"; + + if (psDeviceFlags.test(rsR4)) + { + // try to initialize R4 + Log("Loading DLL:", r4_name); + hRender = LoadLibrary(r4_name); + if (0 == hRender) + { + // try to load R1 + Msg("! ...Failed - incompatible hardware/pre-Vista OS."); + psDeviceFlags.set(rsR2, TRUE); + } + } + + if (psDeviceFlags.test(rsR3)) + { + // try to initialize R3 + Log("Loading DLL:", r3_name); + hRender = LoadLibrary(r3_name); + if (0 == hRender) + { + // try to load R1 + Msg("! ...Failed - incompatible hardware/pre-Vista OS."); + psDeviceFlags.set(rsR2, TRUE); + } + else + g_current_renderer = 3; + } + + if (psDeviceFlags.test(rsR2)) + { + // try to initialize R2 + psDeviceFlags.set(rsR4, FALSE); + psDeviceFlags.set(rsR3, FALSE); + Log("Loading DLL:", r2_name); + hRender = LoadLibrary(r2_name); + if (0 == hRender) + { + // try to load R1 + Msg("! ...Failed - incompatible hardware."); + } + else + g_current_renderer = 2; + } + + SECUROM_MARKER_HIGH_SECURITY_OFF(2) } #endif // DEDICATED_SERVER void CEngineAPI::Initialize(void) { - ////////////////////////////////////////////////////////////////////////// - // render - LPCSTR r1_name = "xrRender_R1.dll"; - - #ifndef DEDICATED_SERVER - InitializeNotDedicated(); - #endif // DEDICATED_SERVER - - if (0==hRender) - { - // try to load R1 - psDeviceFlags.set (rsR4,FALSE); - psDeviceFlags.set (rsR3,FALSE); - psDeviceFlags.set (rsR2,FALSE); - renderer_value = 0; //con cmd - - Log ("Loading DLL:", r1_name); - hRender = LoadLibrary (r1_name); - if (0==hRender) R_CHK (GetLastError()); - R_ASSERT (hRender); - g_current_renderer = 1; - } - - Device.ConnectToRender(); - - // game - { - LPCSTR g_name = "xrGame.dll"; - Log ("Loading DLL:",g_name); - hGame = LoadLibrary (g_name); - if (0==hGame) R_CHK (GetLastError()); - R_ASSERT2 (hGame,"Game DLL raised exception during loading or there is no game DLL at all"); - pCreate = (Factory_Create*) GetProcAddress(hGame,"xrFactory_Create" ); R_ASSERT(pCreate); - pDestroy = (Factory_Destroy*) GetProcAddress(hGame,"xrFactory_Destroy" ); R_ASSERT(pDestroy); - } - - ////////////////////////////////////////////////////////////////////////// - // vTune - tune_enabled = FALSE; - if (strstr(Core.Params,"-tune")) { - LPCSTR g_name = "vTuneAPI.dll"; - Log ("Loading DLL:",g_name); - hTuner = LoadLibrary (g_name); - if (0==hTuner) R_CHK (GetLastError()); - R_ASSERT2 (hTuner,"Intel vTune is not installed"); - tune_enabled = TRUE; - tune_pause = (VTPause*) GetProcAddress(hTuner,"VTPause" ); R_ASSERT(tune_pause); - tune_resume = (VTResume*) GetProcAddress(hTuner,"VTResume" ); R_ASSERT(tune_resume); - } + ////////////////////////////////////////////////////////////////////////// + // render + LPCSTR r1_name = "xrRender_R1.dll"; + +#ifndef DEDICATED_SERVER + InitializeNotDedicated(); +#endif // DEDICATED_SERVER + + if (0 == hRender) + { + // try to load R1 + psDeviceFlags.set(rsR4, FALSE); + psDeviceFlags.set(rsR3, FALSE); + psDeviceFlags.set(rsR2, FALSE); + renderer_value = 0; //con cmd + + Log("Loading DLL:", r1_name); + hRender = LoadLibrary(r1_name); + if (0 == hRender) R_CHK(GetLastError()); + R_ASSERT(hRender); + g_current_renderer = 1; + } + + Device.ConnectToRender(); + + // game + { + LPCSTR g_name = "xrGame.dll"; + Log("Loading DLL:", g_name); + hGame = LoadLibrary(g_name); + if (0 == hGame) R_CHK(GetLastError()); + R_ASSERT2(hGame, "Game DLL raised exception during loading or there is no game DLL at all"); + pCreate = (Factory_Create*)GetProcAddress(hGame, "xrFactory_Create"); + R_ASSERT(pCreate); + pDestroy = (Factory_Destroy*)GetProcAddress(hGame, "xrFactory_Destroy"); + R_ASSERT(pDestroy); + } + + ////////////////////////////////////////////////////////////////////////// + // vTune + tune_enabled = FALSE; + if (strstr(Core.Params, "-tune")) + { + LPCSTR g_name = "vTuneAPI.dll"; + Log("Loading DLL:", g_name); + hTuner = LoadLibrary(g_name); + if (0 == hTuner) R_CHK(GetLastError()); + R_ASSERT2(hTuner, "Intel vTune is not installed"); + tune_enabled = TRUE; + tune_pause = (VTPause*)GetProcAddress(hTuner, "VTPause"); + R_ASSERT(tune_pause); + tune_resume = (VTResume*)GetProcAddress(hTuner, "VTResume"); + R_ASSERT(tune_resume); + } } -void CEngineAPI::Destroy (void) +void CEngineAPI::Destroy(void) { - if (hGame) { FreeLibrary(hGame); hGame = 0; } - if (hRender) { FreeLibrary(hRender); hRender = 0; } - pCreate = 0; - pDestroy = 0; - Engine.Event._destroy (); - XRC.r_clear_compact (); + if (hGame) { FreeLibrary(hGame); hGame = 0; } + if (hRender) { FreeLibrary(hRender); hRender = 0; } + pCreate = 0; + pDestroy = 0; + Engine.Event._destroy(); + XRC.r_clear_compact(); } extern "C" { - typedef bool __cdecl SupportsAdvancedRendering (void); - typedef bool _declspec(dllexport) SupportsDX10Rendering(); - typedef bool _declspec(dllexport) SupportsDX11Rendering(); + typedef bool __cdecl SupportsAdvancedRendering(void); + typedef bool _declspec(dllexport) SupportsDX10Rendering(); + typedef bool _declspec(dllexport) SupportsDX11Rendering(); }; void CEngineAPI::CreateRendererList() { #ifdef DEDICATED_SERVER - vid_quality_token = xr_alloc(2); + vid_quality_token = xr_alloc(2); - vid_quality_token[0].id = 0; - vid_quality_token[0].name = xr_strdup("renderer_r1"); + vid_quality_token[0].id = 0; + vid_quality_token[0].name = xr_strdup("renderer_r1"); - vid_quality_token[1].id = -1; - vid_quality_token[1].name = NULL; + vid_quality_token[1].id = -1; + vid_quality_token[1].name = NULL; #else - // TODO: ask renderers if they are supported! - if(vid_quality_token != NULL) return; - bool bSupports_r2 = false; - bool bSupports_r2_5 = false; - bool bSupports_r3 = false; - bool bSupports_r4 = false; - - LPCSTR r2_name = "xrRender_R2.dll"; - LPCSTR r3_name = "xrRender_R3.dll"; - LPCSTR r4_name = "xrRender_R4.dll"; - - if (strstr(Core.Params,"-perfhud_hack")) - { - bSupports_r2 = true; - bSupports_r2_5 = true; - bSupports_r3 = true; - bSupports_r4 = true; - } - else - { - // try to initialize R2 - Log ("Loading DLL:", r2_name); - hRender = LoadLibrary (r2_name); - if (hRender) - { - bSupports_r2 = true; - SupportsAdvancedRendering *test_rendering = (SupportsAdvancedRendering*) GetProcAddress(hRender,"SupportsAdvancedRendering"); - R_ASSERT(test_rendering); - bSupports_r2_5 = test_rendering(); - FreeLibrary(hRender); - } - - // try to initialize R3 - Log ("Loading DLL:", r3_name); - // Hide "d3d10.dll not found" message box for XP - SetErrorMode(SEM_FAILCRITICALERRORS); - hRender = LoadLibrary (r3_name); - // Restore error handling - SetErrorMode(0); - if (hRender) - { - SupportsDX10Rendering *test_dx10_rendering = (SupportsDX10Rendering*) GetProcAddress(hRender,"SupportsDX10Rendering"); - R_ASSERT(test_dx10_rendering); - bSupports_r3 = test_dx10_rendering(); - FreeLibrary(hRender); - } - - // try to initialize R4 - Log ("Loading DLL:", r4_name); - // Hide "d3d10.dll not found" message box for XP - SetErrorMode (SEM_FAILCRITICALERRORS); - hRender = LoadLibrary (r4_name); - // Restore error handling - SetErrorMode (0); - if (hRender) - { - SupportsDX11Rendering *test_dx11_rendering = (SupportsDX11Rendering*) GetProcAddress(hRender,"SupportsDX11Rendering"); - R_ASSERT(test_dx11_rendering); - bSupports_r4 = test_dx11_rendering(); - FreeLibrary(hRender); - } - } - - hRender = 0; - - xr_vector _tmp; - u32 i = 0; - bool bBreakLoop = false; - for(; i<6; ++i) - { - switch (i) - { - case 1: - if (!bSupports_r2) - bBreakLoop = true; - break; - case 3: //"renderer_r2.5" - if (!bSupports_r2_5) - bBreakLoop = true; - break; - case 4: //"renderer_r_dx10" - if (!bSupports_r3) - bBreakLoop = true; - break; - case 5: //"renderer_r_dx11" - if (!bSupports_r4) - bBreakLoop = true; - break; - default: ; - } - - if (bBreakLoop) break; - - _tmp.push_back (NULL); - LPCSTR val = NULL; - switch (i) - { - case 0: val ="renderer_r1"; break; - case 1: val ="renderer_r2a"; break; - case 2: val ="renderer_r2"; break; - case 3: val ="renderer_r2.5"; break; - case 4: val ="renderer_r3"; break; // -) - case 5: val ="renderer_r4"; break; // -) - } - if (bBreakLoop) break; - _tmp.back() = xr_strdup(val); - } - u32 _cnt = _tmp.size()+1; - vid_quality_token = xr_alloc(_cnt); - - vid_quality_token[_cnt-1].id = -1; - vid_quality_token[_cnt-1].name = NULL; - -#ifdef DEBUG - Msg("Available render modes[%d]:",_tmp.size()); -#endif // DEBUG - for(u32 i=0; i<_tmp.size();++i) - { - vid_quality_token[i].id = i; - vid_quality_token[i].name = _tmp[i]; -#ifdef DEBUG - Msg ("[%s]",_tmp[i]); -#endif // DEBUG - } - - /* - if(vid_quality_token != NULL) return; - - D3DCAPS9 caps; - CHW _HW; - _HW.CreateD3D (); - _HW.pD3D->GetDeviceCaps (D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,&caps); - _HW.DestroyD3D (); - u16 ps_ver_major = u16 ( u32(u32(caps.PixelShaderVersion)&u32(0xf << 8ul))>>8 ); - - xr_vector _tmp; - u32 i = 0; - for(; i<5; ++i) - { - bool bBreakLoop = false; - switch (i) - { - case 3: //"renderer_r2.5" - if (ps_ver_major < 3) - bBreakLoop = true; - break; - case 4: //"renderer_r_dx10" - bBreakLoop = true; - break; - default: ; - } - - if (bBreakLoop) break; - - _tmp.push_back (NULL); - LPCSTR val = NULL; - switch (i) - { - case 0: val ="renderer_r1"; break; - case 1: val ="renderer_r2a"; break; - case 2: val ="renderer_r2"; break; - case 3: val ="renderer_r2.5"; break; - case 4: val ="renderer_r_dx10"; break; // -) - } - _tmp.back() = xr_strdup(val); - } - u32 _cnt = _tmp.size()+1; - vid_quality_token = xr_alloc(_cnt); - - vid_quality_token[_cnt-1].id = -1; - vid_quality_token[_cnt-1].name = NULL; + // TODO: ask renderers if they are supported! + if (vid_quality_token != NULL) return; + bool bSupports_r2 = false; + bool bSupports_r2_5 = false; + bool bSupports_r3 = false; + bool bSupports_r4 = false; + + LPCSTR r2_name = "xrRender_R2.dll"; + LPCSTR r3_name = "xrRender_R3.dll"; + LPCSTR r4_name = "xrRender_R4.dll"; + + if (strstr(Core.Params, "-perfhud_hack")) + { + bSupports_r2 = true; + bSupports_r2_5 = true; + bSupports_r3 = true; + bSupports_r4 = true; + } + else + { + // try to initialize R2 + Log("Loading DLL:", r2_name); + hRender = LoadLibrary(r2_name); + if (hRender) + { + bSupports_r2 = true; + SupportsAdvancedRendering* test_rendering = (SupportsAdvancedRendering*)GetProcAddress(hRender, "SupportsAdvancedRendering"); + R_ASSERT(test_rendering); + bSupports_r2_5 = test_rendering(); + FreeLibrary(hRender); + } + + // try to initialize R3 + Log("Loading DLL:", r3_name); + // Hide "d3d10.dll not found" message box for XP + SetErrorMode(SEM_FAILCRITICALERRORS); + hRender = LoadLibrary(r3_name); + // Restore error handling + SetErrorMode(0); + if (hRender) + { + SupportsDX10Rendering* test_dx10_rendering = (SupportsDX10Rendering*)GetProcAddress(hRender, "SupportsDX10Rendering"); + R_ASSERT(test_dx10_rendering); + bSupports_r3 = test_dx10_rendering(); + FreeLibrary(hRender); + } + + // try to initialize R4 + Log("Loading DLL:", r4_name); + // Hide "d3d10.dll not found" message box for XP + SetErrorMode(SEM_FAILCRITICALERRORS); + hRender = LoadLibrary(r4_name); + // Restore error handling + SetErrorMode(0); + if (hRender) + { + SupportsDX11Rendering* test_dx11_rendering = (SupportsDX11Rendering*)GetProcAddress(hRender, "SupportsDX11Rendering"); + R_ASSERT(test_dx11_rendering); + bSupports_r4 = test_dx11_rendering(); + FreeLibrary(hRender); + } + } + + hRender = 0; + + xr_vector _tmp; + u32 i = 0; + bool bBreakLoop = false; + for (; i < 6; ++i) + { + switch (i) + { + case 1: + if (!bSupports_r2) + bBreakLoop = true; + break; + case 3: //"renderer_r2.5" + if (!bSupports_r2_5) + bBreakLoop = true; + break; + case 4: //"renderer_r_dx10" + if (!bSupports_r3) + bBreakLoop = true; + break; + case 5: //"renderer_r_dx11" + if (!bSupports_r4) + bBreakLoop = true; + break; + default: + ; + } + + if (bBreakLoop) break; + + _tmp.push_back(NULL); + LPCSTR val = NULL; + switch (i) + { + case 0: + val = "renderer_r1"; + break; + case 1: + val = "renderer_r2a"; + break; + case 2: + val = "renderer_r2"; + break; + case 3: + val = "renderer_r2.5"; + break; + case 4: + val = "renderer_r3"; + break; // -) + case 5: + val = "renderer_r4"; + break; // -) + } + if (bBreakLoop) break; + _tmp.back() = xr_strdup(val); + } + u32 _cnt = _tmp.size() + 1; + vid_quality_token = xr_alloc(_cnt); + + vid_quality_token[_cnt - 1].id = -1; + vid_quality_token[_cnt - 1].name = NULL; #ifdef DEBUG - Msg("Available render modes[%d]:",_tmp.size()); + Msg("Available render modes[%d]:", _tmp.size()); #endif // DEBUG - for(u32 i=0; i<_tmp.size();++i) - { - vid_quality_token[i].id = i; - vid_quality_token[i].name = _tmp[i]; + for (u32 i = 0; i < _tmp.size(); ++i) + { + vid_quality_token[i].id = i; + vid_quality_token[i].name = _tmp[i]; #ifdef DEBUG - Msg ("[%s]",_tmp[i]); + Msg("[%s]", _tmp[i]); #endif // DEBUG - } - */ + } + + /* + if(vid_quality_token != NULL) return; + + D3DCAPS9 caps; + CHW _HW; + _HW.CreateD3D (); + _HW.pD3D->GetDeviceCaps (D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,&caps); + _HW.DestroyD3D (); + u16 ps_ver_major = u16 ( u32(u32(caps.PixelShaderVersion)&u32(0xf << 8ul))>>8 ); + + xr_vector _tmp; + u32 i = 0; + for(; i<5; ++i) + { + bool bBreakLoop = false; + switch (i) + { + case 3: //"renderer_r2.5" + if (ps_ver_major < 3) + bBreakLoop = true; + break; + case 4: //"renderer_r_dx10" + bBreakLoop = true; + break; + default: ; + } + + if (bBreakLoop) break; + + _tmp.push_back (NULL); + LPCSTR val = NULL; + switch (i) + { + case 0: val ="renderer_r1"; break; + case 1: val ="renderer_r2a"; break; + case 2: val ="renderer_r2"; break; + case 3: val ="renderer_r2.5"; break; + case 4: val ="renderer_r_dx10"; break; // -) + } + _tmp.back() = xr_strdup(val); + } + u32 _cnt = _tmp.size()+1; + vid_quality_token = xr_alloc(_cnt); + + vid_quality_token[_cnt-1].id = -1; + vid_quality_token[_cnt-1].name = NULL; + + #ifdef DEBUG + Msg("Available render modes[%d]:",_tmp.size()); + #endif // DEBUG + for(u32 i=0; i<_tmp.size();++i) + { + vid_quality_token[i].id = i; + vid_quality_token[i].name = _tmp[i]; + #ifdef DEBUG + Msg ("[%s]",_tmp[i]); + #endif // DEBUG + } + */ #endif //#ifndef DEDICATED_SERVER } \ No newline at end of file diff --git a/src/xrEngine/EngineAPI.h b/src/xrEngine/EngineAPI.h index 6e62c0511e2..1086c673c1e 100644 --- a/src/xrEngine/EngineAPI.h +++ b/src/xrEngine/EngineAPI.h @@ -9,56 +9,57 @@ #pragma once // Abstract 'Pure' class for DLL interface -class ENGINE_API DLL_Pure { +class ENGINE_API DLL_Pure +{ public: - CLASS_ID CLS_ID; + CLASS_ID CLS_ID; - DLL_Pure(void *params) {CLS_ID=0; }; - DLL_Pure() {CLS_ID=0; }; - virtual DLL_Pure* _construct () { return this; } - virtual ~DLL_Pure() {}; + DLL_Pure(void* params) { CLS_ID = 0; }; + DLL_Pure() { CLS_ID = 0; }; + virtual DLL_Pure* _construct() { return this; } + virtual ~DLL_Pure() {}; }; // Class creation/destroying interface extern "C" { -typedef DLL_API DLL_Pure* __cdecl Factory_Create (CLASS_ID CLS_ID); -typedef DLL_API void __cdecl Factory_Destroy (DLL_Pure* O); + typedef DLL_API DLL_Pure* __cdecl Factory_Create(CLASS_ID CLS_ID); + typedef DLL_API void __cdecl Factory_Destroy(DLL_Pure* O); }; // Tuning interface extern "C" { - typedef void __cdecl VTPause (void); - typedef void __cdecl VTResume (void); + typedef void __cdecl VTPause(void); + typedef void __cdecl VTResume(void); }; -class ENGINE_API CEngineAPI +class ENGINE_API CEngineAPI { private: - HMODULE hGame; - HMODULE hRender; - HMODULE hTuner; + HMODULE hGame; + HMODULE hRender; + HMODULE hTuner; public: - BENCH_SEC_SCRAMBLEMEMBER1 - Factory_Create* pCreate; - Factory_Destroy* pDestroy; - BOOL tune_enabled; - VTPause* tune_pause ; - VTResume* tune_resume ; - void Initialize (); - - #ifndef DEDICATED_SERVER - void InitializeNotDedicated(); - #endif // DEDICATED_SERVER - - void Destroy (); + BENCH_SEC_SCRAMBLEMEMBER1 + Factory_Create* pCreate; + Factory_Destroy* pDestroy; + BOOL tune_enabled; + VTPause* tune_pause; + VTResume* tune_resume; + void Initialize(); + +#ifndef DEDICATED_SERVER + void InitializeNotDedicated(); +#endif // DEDICATED_SERVER + + void Destroy(); - void CreateRendererList(); + void CreateRendererList(); - CEngineAPI (); - ~CEngineAPI (); + CEngineAPI(); + ~CEngineAPI(); }; -#define NEW_INSTANCE(a) Engine.External.pCreate(a) -#define DEL_INSTANCE(a) { Engine.External.pDestroy(a); a=NULL; } +#define NEW_INSTANCE(a) Engine.External.pCreate(a) +#define DEL_INSTANCE(a) { Engine.External.pDestroy(a); a=NULL; } #endif // !defined(AFX_ENGINEAPI_H__CF21372B_C8B8_4891_82FC_D872C84E1DD4__INCLUDED_) diff --git a/src/xrEngine/EnnumerateVertices.h b/src/xrEngine/EnnumerateVertices.h index e43a85f970e..14e136d4dc0 100644 --- a/src/xrEngine/EnnumerateVertices.h +++ b/src/xrEngine/EnnumerateVertices.h @@ -2,6 +2,6 @@ struct SEnumVerticesCallback { - virtual void operator () (const Fvector& p) = 0; + virtual void operator () (const Fvector& p) = 0; }; diff --git a/src/xrEngine/Envelope.cpp b/src/xrEngine/Envelope.cpp index eb683526775..e5f5de28f0c 100644 --- a/src/xrEngine/Envelope.cpp +++ b/src/xrEngine/Envelope.cpp @@ -5,80 +5,88 @@ CEnvelope::~CEnvelope() { - Clear(); + Clear(); } CEnvelope::CEnvelope(CEnvelope* source) { - *this = *source; - for (u32 i=0; ikeys.size(); i++) - keys[i] = xr_new (*source->keys[i]); + *this = *source; + for (u32 i = 0; i < source->keys.size(); i++) + keys[i] = xr_new(*source->keys[i]); } -void CEnvelope::ClearAndFree() +void CEnvelope::ClearAndFree() { - Clear(); + Clear(); keys.clear(); } void CEnvelope::Clear() { - for (KeyIt k_it=keys.begin(); k_it!=keys.end(); k_it++) - xr_delete(*k_it); + for (KeyIt k_it = keys.begin(); k_it != keys.end(); k_it++) + xr_delete(*k_it); } void CEnvelope::FindNearestKey(float t, KeyIt& min_k, KeyIt& max_k, float eps) { - for (KeyIt k_it=keys.begin(); k_it!=keys.end(); k_it++){ - if (fsimilar((*k_it)->time,t,eps)){ - max_k = k_it+1; - min_k = (k_it==keys.begin())?k_it:k_it-1; - return; + for (KeyIt k_it = keys.begin(); k_it != keys.end(); k_it++) + { + if (fsimilar((*k_it)->time, t, eps)) + { + max_k = k_it + 1; + min_k = (k_it == keys.begin()) ? k_it : k_it - 1; + return; } - if ((*k_it)->time>t){ - max_k = k_it; - min_k = (k_it==keys.begin())?k_it:k_it-1; + if ((*k_it)->time > t) + { + max_k = k_it; + min_k = (k_it == keys.begin()) ? k_it : k_it - 1; return; } } - min_k=keys.empty()?keys.end():keys.end()-1; - max_k=keys.end(); + min_k = keys.empty() ? keys.end() : keys.end() - 1; + max_k = keys.end(); } KeyIt CEnvelope::FindKey(float t, float eps) { - for (KeyIt k_it=keys.begin(); k_it!=keys.end(); k_it++){ - if (fsimilar((*k_it)->time,t,eps)) return k_it; - if ((*k_it)->time>t) return keys.end(); + for (KeyIt k_it = keys.begin(); k_it != keys.end(); k_it++) + { + if (fsimilar((*k_it)->time, t, eps)) return k_it; + if ((*k_it)->time > t) return keys.end(); } return keys.end(); } void CEnvelope::InsertKey(float t, float val) -{ - for (KeyIt k_it=keys.begin(); k_it!=keys.end(); k_it++){ - if (fsimilar((*k_it)->time,t,EPS_L)){ - (*k_it)->value= val; +{ + for (KeyIt k_it = keys.begin(); k_it != keys.end(); k_it++) + { + if (fsimilar((*k_it)->time, t, EPS_L)) + { + (*k_it)->value = val; return; } // insert before - if ((*k_it)->time>t) break; + if ((*k_it)->time > t) break; } // create _new key - st_Key* K = xr_new(); - K->time = t; - K->value = val; - K->shape = SHAPE_TCB; - behavior[0] = BEH_CONSTANT; - behavior[1] = BEH_CONSTANT; - keys.insert (k_it,K); + st_Key* K = xr_new(); + K->time = t; + K->value = val; + K->shape = SHAPE_TCB; + behavior[0] = BEH_CONSTANT; + behavior[1] = BEH_CONSTANT; + keys.insert(k_it, K); } void CEnvelope::DeleteKey(float t) -{ - for (KeyIt k_it=keys.begin(); k_it!=keys.end(); k_it++){ - if (fsimilar((*k_it)->time,t,EPS_L)){ - xr_delete(*k_it); +{ + for (KeyIt k_it = keys.begin(); k_it != keys.end(); k_it++) + { + if (fsimilar((*k_it)->time, t, EPS_L)) + { + xr_delete(*k_it); keys.erase(k_it); return; } @@ -87,42 +95,48 @@ void CEnvelope::DeleteKey(float t) BOOL CEnvelope::ScaleKeys(float from_time, float to_time, float scale_factor, float eps) { - KeyIt min_k = FindKey(from_time,eps); - if (min_k==keys.end()){ - KeyIt k0; - FindNearestKey(from_time, k0, min_k, eps); + KeyIt min_k = FindKey(from_time, eps); + if (min_k == keys.end()) + { + KeyIt k0; + FindNearestKey(from_time, k0, min_k, eps); } - KeyIt max_k = FindKey(to_time,eps); - if (max_k==keys.end()){ - KeyIt k1; - FindNearestKey(to_time, max_k, k1, eps); + KeyIt max_k = FindKey(to_time, eps); + if (max_k == keys.end()) + { + KeyIt k1; + FindNearestKey(to_time, max_k, k1, eps); } - if (min_k!=keys.end()&&min_k!=max_k){ - if (max_k!=keys.end()) max_k++; - float t0 = (*min_k)->time; - float offset = 0; - for (KeyIt it=min_k+1; it!=max_k; it++){ - float new_time = offset+t0+((*it)->time-t0)*scale_factor; - offset += ((new_time-(*(it-1))->time)-((*it)->time-t0)); - t0 = (*it)->time; - (*it)->time = new_time; + if (min_k != keys.end() && min_k != max_k) + { + if (max_k != keys.end()) max_k++; + float t0 = (*min_k)->time; + float offset = 0; + for (KeyIt it = min_k + 1; it != max_k; it++) + { + float new_time = offset + t0 + ((*it)->time - t0)*scale_factor; + offset += ((new_time - (*(it - 1))->time) - ((*it)->time - t0)); + t0 = (*it)->time; + (*it)->time = new_time; } - for (; it!=keys.end(); it++){ - float new_time = offset+(*it)->time; - offset += ((new_time-(*(it-1))->time)-((*it)->time-t0)); - (*it)->time = new_time; + for (; it != keys.end(); it++) + { + float new_time = offset + (*it)->time; + offset += ((new_time - (*(it - 1))->time) - ((*it)->time - t0)); + (*it)->time = new_time; } - return TRUE; + return TRUE; } return FALSE; } float CEnvelope::GetLength(float* mn, float* mx) { - if (!keys.empty()){ - if (mn) *mn = keys.front()->time; - if (mx) *mx = keys.back()->time; - return keys.back()->time-keys.front()->time; + if (!keys.empty()) + { + if (mn) *mn = keys.front()->time; + if (mx) *mx = keys.back()->time; + return keys.back()->time - keys.front()->time; } if (mn) *mn = 0.f; if (mx) *mx = 0.f; @@ -131,115 +145,129 @@ float CEnvelope::GetLength(float* mn, float* mx) void CEnvelope::RotateKeys(float angle) { - for (u32 i=0; ivalue += angle; + for (u32 i = 0; i < keys.size(); i++) + keys[i]->value += angle; } -extern float evalEnvelope( CEnvelope *env, float time ); -float CEnvelope::Evaluate(float time){ - return evalEnvelope(this, time); +extern float evalEnvelope(CEnvelope* env, float time); +float CEnvelope::Evaluate(float time) +{ + return evalEnvelope(this, time); } void CEnvelope::Save(IWriter& F) { - F.w_u8 ((u8)behavior[0]); - F.w_u8 ((u8)behavior[1]); - F.w_u16 ((u16)keys.size()); - for (KeyIt k_it=keys.begin(); k_it!=keys.end(); k_it++) - (*k_it)->Save(F); + F.w_u8((u8)behavior[0]); + F.w_u8((u8)behavior[1]); + F.w_u16((u16)keys.size()); + for (KeyIt k_it = keys.begin(); k_it != keys.end(); k_it++) + (*k_it)->Save(F); } void CEnvelope::Load_1(IReader& F) { - Clear (); - F.r (behavior,sizeof(int)*2); - int y = F.r_u32(); - keys.resize (y); - for (u32 i=0; i (); + Clear(); + F.r(behavior, sizeof(int) * 2); + int y = F.r_u32(); + keys.resize(y); + for (u32 i = 0; i < keys.size(); i++) + { + keys[i] = xr_new(); keys[i]->Load_1(F); } } void CEnvelope::Load_2(IReader& F) { - Clear (); - behavior[0] = F.r_u8(); - behavior[1] = F.r_u8(); - keys.resize (F.r_u16()); - for (u32 i=0; i (); + Clear(); + behavior[0] = F.r_u8(); + behavior[1] = F.r_u8(); + keys.resize(F.r_u16()); + for (u32 i = 0; i < keys.size(); i++) + { + keys[i] = xr_new(); keys[i]->Load_2(F); } } -void CEnvelope::SaveA(IWriter&){ +void CEnvelope::SaveA(IWriter&) +{ } void CEnvelope::LoadA(IReader& F) { - Clear (); - string512 buf; - float f[9]; - F.r_string(buf,sizeof(buf)); - if (strstr(buf,"{ Envelope")){ - F.r_string(buf,sizeof(buf)); - int nkeys=atoi(buf); - keys.resize(nkeys); - for (u32 i=0; i (); - st_Key& K=*keys[i]; - F.r_string(buf,sizeof(buf)); - int cnt = sscanf (buf,"Key %f %f %f %f %f %f %f %f %f", f+0, f+1, f+2, f+3, f+4, f+5, f+6, f+7, f+8); - R_ASSERT(cnt==9); - K.value = f[ 0 ]; - K.time = f[ 1 ]; - K.shape = ( u8 ) f[ 2 ]; - if ( K.shape == SHAPE_TCB ) { - K.tension = f[ 3 ]; - K.continuity = f[ 4 ]; - K.bias = f[ 5 ]; - } - if ( K.shape == SHAPE_BEZ2 ) { - K.param[ 0 ] = f[ 3 ]; - K.param[ 1 ] = f[ 4 ]; - K.param[ 2 ] = f[ 5 ]; - K.param[ 3 ] = f[ 6 ]; - }else{ - K.param[ 0 ] = f[ 6 ]; - K.param[ 1 ] = f[ 7 ]; - } - } + Clear(); + string512 buf; + float f[9]; + F.r_string(buf, sizeof(buf)); + if (strstr(buf, "{ Envelope")) + { + F.r_string(buf, sizeof(buf)); + int nkeys = atoi(buf); + keys.resize(nkeys); + for (u32 i = 0; i < keys.size(); i++) + { + keys[i] = xr_new(); + st_Key& K = *keys[i]; + F.r_string(buf, sizeof(buf)); + int cnt = sscanf(buf, "Key %f %f %f %f %f %f %f %f %f", f + 0, f + 1, f + 2, f + 3, f + 4, f + 5, f + 6, f + 7, f + 8); + R_ASSERT(cnt == 9); + K.value = f[0]; + K.time = f[1]; + K.shape = (u8)f[2]; + if (K.shape == SHAPE_TCB) + { + K.tension = f[3]; + K.continuity = f[4]; + K.bias = f[5]; + } + if (K.shape == SHAPE_BEZ2) + { + K.param[0] = f[3]; + K.param[1] = f[4]; + K.param[2] = f[5]; + K.param[3] = f[6]; + } + else + { + K.param[0] = f[6]; + K.param[1] = f[7]; + } + } // behavior
 
-		F.r_string(buf,sizeof(buf));
-		int cnt = sscanf(buf,"Behaviors %d %d", behavior[0], behavior[1] );
-        R_ASSERT(cnt==2);
+        F.r_string(buf, sizeof(buf));
+        int cnt = sscanf(buf, "Behaviors %d %d", behavior[0], behavior[1]);
+        R_ASSERT(cnt == 2);
     }
 }
 
 void CEnvelope::Optimize()
 {
-	if (keys.empty())
-		return;
+    if (keys.empty())
+        return;
 
-	KeyIt it 		= keys.begin();
-    st_Key K 		= **it;	it++;
-    bool equal		= true;
-	for (;it!=keys.end();it++){
-    	if (!(*it)->equal(K)){
-        	equal	= false;
+    KeyIt it = keys.begin();
+    st_Key K = **it;
+    it++;
+    bool equal = true;
+    for (; it != keys.end(); it++)
+    {
+        if (!(*it)->equal(K))
+        {
+            equal = false;
             break;
         }
     }
-    if (equal&&(keys.size()>2)){
-        KeyVec		new_keys;
-		new_keys.push_back(xr_new(*keys.front()));
-		new_keys.push_back(xr_new(*keys.back()));
-        for (KeyIt k_it=keys.begin(); k_it!=keys.end(); k_it++)
+    if (equal && (keys.size() > 2))
+    {
+        KeyVec new_keys;
+        new_keys.push_back(xr_new(*keys.front()));
+        new_keys.push_back(xr_new(*keys.back()));
+        for (KeyIt k_it = keys.begin(); k_it != keys.end(); k_it++)
             xr_delete(*k_it);
-		keys.clear_and_free	();
-        keys				= new_keys;
+        keys.clear_and_free();
+        keys = new_keys;
     }
 }
 
diff --git a/src/xrEngine/Environment.cpp b/src/xrEngine/Environment.cpp
index 1a355a6e2e9..9f7441de884 100644
--- a/src/xrEngine/Environment.cpp
+++ b/src/xrEngine/Environment.cpp
@@ -2,7 +2,7 @@
 #pragma hdrstop
 
 #ifndef _EDITOR
-    #include "render.h"
+#include "render.h"
 #endif
 
 #include "Environment.h"
@@ -17,7 +17,7 @@
 //#include "resourcemanager.h"
 
 #ifndef _EDITOR
-	#include "IGame_Level.h"
+#include "IGame_Level.h"
 #endif
 
 //#include "D3DUtils.h"
@@ -31,623 +31,665 @@
 //////////////////////////////////////////////////////////////////////
 // Construction/Destruction
 //////////////////////////////////////////////////////////////////////
-ENGINE_API	float			psVisDistance	= 1.f;
-static const float			MAX_NOISE_FREQ	= 0.03f;
+ENGINE_API float psVisDistance = 1.f;
+static const float MAX_NOISE_FREQ = 0.03f;
 
 //#define WEATHER_LOGGING
 
 // real WEATHER->WFX transition time
-#define WFX_TRANS_TIME		5.f
+#define WFX_TRANS_TIME 5.f
 
 const float MAX_DIST_FACTOR = 0.95f;
 
 //////////////////////////////////////////////////////////////////////////
 // environment
-CEnvironment::CEnvironment	() :
-	CurrentEnv				(0),
-	m_ambients_config		(0)
+CEnvironment::CEnvironment() :
+CurrentEnv(0),
+m_ambients_config(0)
 {
-	bNeed_re_create_env = FALSE;
-	bWFX					= false;
-	Current[0]				= 0;
-	Current[1]				= 0;
-    CurrentWeather			= 0;
-    CurrentWeatherName		= 0;
-	eff_Rain				= 0;
-    eff_LensFlare 			= 0;
-    eff_Thunderbolt			= 0;
-	OnDeviceCreate			();
+    bNeed_re_create_env = FALSE;
+    bWFX = false;
+    Current[0] = 0;
+    Current[1] = 0;
+    CurrentWeather = 0;
+    CurrentWeatherName = 0;
+    eff_Rain = 0;
+    eff_LensFlare = 0;
+    eff_Thunderbolt = 0;
+    OnDeviceCreate();
 #ifdef _EDITOR
-	ed_from_time			= 0.f;
-	ed_to_time				= DAY_LENGTH;
+    ed_from_time = 0.f;
+    ed_to_time = DAY_LENGTH;
 #endif
 
 #ifndef _EDITOR
-	m_paused				= false;
+    m_paused = false;
 #endif
 
-	fGameTime				= 0.f;
-    fTimeFactor				= 12.f;
-
-	wind_strength_factor	= 0.f;
-	wind_gust_factor		= 0.f;
-
-	wind_blast_strength	= 0.f;
-	wind_blast_direction.set(1.f,0.f,0.f);
-
-	wind_blast_strength_start_value	= 0.f;
-	wind_blast_strength_stop_value	= 0.f;
-
-	// fill clouds hemi verts & faces 
-	const Fvector* verts;
-	CloudsVerts.resize		(xrHemisphereVertices(2,verts));
-	CopyMemory				(&CloudsVerts.front(),verts,CloudsVerts.size()*sizeof(Fvector));
-	const u16* indices;
-	CloudsIndices.resize	(xrHemisphereIndices(2,indices));
-	CopyMemory				(&CloudsIndices.front(),indices,CloudsIndices.size()*sizeof(u16));
-
-	// perlin noise
-	PerlinNoise1D			= xr_new(Random.randI(0,0xFFFF));
-	PerlinNoise1D->SetOctaves(2);
-	PerlinNoise1D->SetAmplitude(0.66666f);
-
-//	tsky0					= Device.Resources->_CreateTexture("$user$sky0");
-//	tsky1					= Device.Resources->_CreateTexture("$user$sky1");
-
-	string_path				file_name;
-	m_ambients_config		=
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\ambients.ltx"
-			),
-			TRUE,
-			TRUE,
-			FALSE
-		);
-	m_sound_channels_config	=
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\sound_channels.ltx"
-			),
-			TRUE,
-			TRUE,
-			FALSE
-		);
-	m_effects_config		=
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\effects.ltx"
-			),
-			TRUE,
-			TRUE,
-			FALSE
-		);
-	m_suns_config			=
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\suns.ltx"
-			),
-			TRUE,
-			TRUE,
-			FALSE
-		);
-	m_thunderbolt_collections_config	=
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\thunderbolt_collections.ltx"
-			),
-			TRUE,
-			TRUE,
-			FALSE
-		);
-	m_thunderbolts_config	=
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\thunderbolts.ltx"
-			),
-			TRUE,
-			TRUE,
-			FALSE
-		);
-
-	CInifile*		config =
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\environment.ltx"
-			),
-			TRUE,
-			TRUE,
-			FALSE
-		);
+    fGameTime = 0.f;
+    fTimeFactor = 12.f;
+
+    wind_strength_factor = 0.f;
+    wind_gust_factor = 0.f;
+
+    wind_blast_strength = 0.f;
+    wind_blast_direction.set(1.f, 0.f, 0.f);
+
+    wind_blast_strength_start_value = 0.f;
+    wind_blast_strength_stop_value = 0.f;
+
+    // fill clouds hemi verts & faces
+    const Fvector* verts;
+    CloudsVerts.resize(xrHemisphereVertices(2, verts));
+    CopyMemory(&CloudsVerts.front(), verts, CloudsVerts.size()*sizeof(Fvector));
+    const u16* indices;
+    CloudsIndices.resize(xrHemisphereIndices(2, indices));
+    CopyMemory(&CloudsIndices.front(), indices, CloudsIndices.size()*sizeof(u16));
+
+    // perlin noise
+    PerlinNoise1D = xr_new(Random.randI(0, 0xFFFF));
+    PerlinNoise1D->SetOctaves(2);
+    PerlinNoise1D->SetAmplitude(0.66666f);
+
+    // tsky0 = Device.Resources->_CreateTexture("$user$sky0");
+    // tsky1 = Device.Resources->_CreateTexture("$user$sky1");
+
+    string_path file_name;
+    m_ambients_config =
+        xr_new(
+        FS.update_path(
+        file_name,
+        "$game_config$",
+        "environment\\ambients.ltx"
+        ),
+        TRUE,
+        TRUE,
+        FALSE
+        );
+    m_sound_channels_config =
+        xr_new(
+        FS.update_path(
+        file_name,
+        "$game_config$",
+        "environment\\sound_channels.ltx"
+        ),
+        TRUE,
+        TRUE,
+        FALSE
+        );
+    m_effects_config =
+        xr_new(
+        FS.update_path(
+        file_name,
+        "$game_config$",
+        "environment\\effects.ltx"
+        ),
+        TRUE,
+        TRUE,
+        FALSE
+        );
+    m_suns_config =
+        xr_new(
+        FS.update_path(
+        file_name,
+        "$game_config$",
+        "environment\\suns.ltx"
+        ),
+        TRUE,
+        TRUE,
+        FALSE
+        );
+    m_thunderbolt_collections_config =
+        xr_new(
+        FS.update_path(
+        file_name,
+        "$game_config$",
+        "environment\\thunderbolt_collections.ltx"
+        ),
+        TRUE,
+        TRUE,
+        FALSE
+        );
+    m_thunderbolts_config =
+        xr_new(
+        FS.update_path(
+        file_name,
+        "$game_config$",
+        "environment\\thunderbolts.ltx"
+        ),
+        TRUE,
+        TRUE,
+        FALSE
+        );
+
+    CInifile* config =
+        xr_new(
+        FS.update_path(
+        file_name,
+        "$game_config$",
+        "environment\\environment.ltx"
+        ),
+        TRUE,
+        TRUE,
+        FALSE
+        );
     // params
-	p_var_alt		= deg2rad(config->r_float					( "environment","altitude" ));  
-	p_var_long		= deg2rad	(config->r_float				( "environment","delta_longitude" ));
-	p_min_dist		= _min		(.95f,config->r_float			( "environment","min_dist_factor" ));
-	p_tilt			= deg2rad	(config->r_float				( "environment","tilt" ));
-	p_second_prop	= config->r_float							( "environment","second_propability" );
-	clamp			(p_second_prop,0.f,1.f);
-	p_sky_color		= config->r_float							( "environment","sky_color" );
-	p_sun_color		= config->r_float							( "environment","sun_color" );
-	p_fog_color		= config->r_float							( "environment","fog_color" );
-
-	xr_delete		(config);
+    p_var_alt = deg2rad(config->r_float("environment", "altitude"));
+    p_var_long = deg2rad(config->r_float("environment", "delta_longitude"));
+    p_min_dist = _min(.95f, config->r_float("environment", "min_dist_factor"));
+    p_tilt = deg2rad(config->r_float("environment", "tilt"));
+    p_second_prop = config->r_float("environment", "second_propability");
+    clamp(p_second_prop, 0.f, 1.f);
+    p_sky_color = config->r_float("environment", "sky_color");
+    p_sun_color = config->r_float("environment", "sun_color");
+    p_fog_color = config->r_float("environment", "fog_color");
+
+    xr_delete(config);
 }
 
-CEnvironment::~CEnvironment	()
+CEnvironment::~CEnvironment()
 {
-	xr_delete				(PerlinNoise1D);
-	OnDeviceDestroy			();
+    xr_delete(PerlinNoise1D);
+    OnDeviceDestroy();
 
-	VERIFY					(m_ambients_config);
-	CInifile::Destroy		(m_ambients_config);
-	m_ambients_config		= 0;
+    VERIFY(m_ambients_config);
+    CInifile::Destroy(m_ambients_config);
+    m_ambients_config = 0;
 
-	VERIFY					(m_sound_channels_config);
-	CInifile::Destroy		(m_sound_channels_config);
-	m_sound_channels_config	= 0;
+    VERIFY(m_sound_channels_config);
+    CInifile::Destroy(m_sound_channels_config);
+    m_sound_channels_config = 0;
 
-	VERIFY					(m_effects_config);
-	CInifile::Destroy		(m_effects_config);
-	m_effects_config		= 0;
+    VERIFY(m_effects_config);
+    CInifile::Destroy(m_effects_config);
+    m_effects_config = 0;
 
-	VERIFY					(m_suns_config);
-	CInifile::Destroy		(m_suns_config);
-	m_suns_config			= 0;
+    VERIFY(m_suns_config);
+    CInifile::Destroy(m_suns_config);
+    m_suns_config = 0;
 
-	VERIFY					(m_thunderbolt_collections_config);
-	CInifile::Destroy		(m_thunderbolt_collections_config);
-	m_thunderbolt_collections_config	= 0;
+    VERIFY(m_thunderbolt_collections_config);
+    CInifile::Destroy(m_thunderbolt_collections_config);
+    m_thunderbolt_collections_config = 0;
 
-	VERIFY					(m_thunderbolts_config);
-	CInifile::Destroy		(m_thunderbolts_config);
-	m_thunderbolts_config	= 0;
+    VERIFY(m_thunderbolts_config);
+    CInifile::Destroy(m_thunderbolts_config);
+    m_thunderbolts_config = 0;
 
-	destroy_mixer			();
+    destroy_mixer();
 }
 
 void CEnvironment::Invalidate()
 {
-	bWFX					= false;
-	Current[0]				= 0;
-	Current[1]				= 0;
-	if (eff_LensFlare)		eff_LensFlare->Invalidate();
+    bWFX = false;
+    Current[0] = 0;
+    Current[1] = 0;
+    if (eff_LensFlare) eff_LensFlare->Invalidate();
 }
 
 float CEnvironment::TimeDiff(float prev, float cur)
 {
-	if (prev>cur)	return	(DAY_LENGTH-prev)+cur;
-	else			return	cur-prev;
+    if (prev > cur) return (DAY_LENGTH - prev) + cur;
+    else return cur - prev;
 }
 
 float CEnvironment::TimeWeight(float val, float min_t, float max_t)
 {
-	float weight	= 0.f;
-	float length	= TimeDiff(min_t,max_t);
-	if (!fis_zero(length,EPS)){
-		if (min_t>max_t){
-			if ((val>=min_t)||(val<=max_t))	weight = TimeDiff(min_t,val)/length;
-		}else{
-			if ((val>=min_t)&&(val<=max_t))	weight = TimeDiff(min_t,val)/length;
-		}
-		clamp		(weight,0.f,1.f);
-	}
-	return			weight;
+    float weight = 0.f;
+    float length = TimeDiff(min_t, max_t);
+    if (!fis_zero(length, EPS))
+    {
+        if (min_t > max_t)
+        {
+            if ((val >= min_t) || (val <= max_t)) weight = TimeDiff(min_t, val) / length;
+        }
+        else
+        {
+            if ((val >= min_t) && (val <= max_t)) weight = TimeDiff(min_t, val) / length;
+        }
+        clamp(weight, 0.f, 1.f);
+    }
+    return weight;
 }
 void CEnvironment::ChangeGameTime(float game_time)
 {
-	fGameTime				= NormalizeTime(fGameTime + game_time);
+    fGameTime = NormalizeTime(fGameTime + game_time);
 };
 
 void CEnvironment::SetGameTime(float game_time, float time_factor)
 {
 #ifndef _EDITOR
-	if (m_paused) {
-		g_pGameLevel->SetEnvironmentGameTimeFactor	(iFloor(fGameTime*1000.f), fTimeFactor);
-		return;
-	}
+    if (m_paused)
+    {
+        g_pGameLevel->SetEnvironmentGameTimeFactor(iFloor(fGameTime*1000.f), fTimeFactor);
+        return;
+    }
 #endif
-	if (bWFX)
-		wfx_time			-= TimeDiff(fGameTime,game_time);
-	fGameTime				= game_time;  
-	fTimeFactor				= time_factor;	
+    if (bWFX)
+        wfx_time -= TimeDiff(fGameTime, game_time);
+    fGameTime = game_time;
+    fTimeFactor = time_factor;
 }
 
 float CEnvironment::NormalizeTime(float tm)
 {
-	if (tm<0.f)				return tm+DAY_LENGTH;
-	else if (tm>DAY_LENGTH)	return tm-DAY_LENGTH;
-	else					return tm;
+    if (tm < 0.f) return tm + DAY_LENGTH;
+    else if (tm > DAY_LENGTH) return tm - DAY_LENGTH;
+    else return tm;
 }
 
 void CEnvironment::SetWeather(shared_str name, bool forced)
 {
-//.	static BOOL bAlready = FALSE;
-//.	if(bAlready)	return;
-	if (name.size())	{
-//.		bAlready = TRUE;
-        EnvsMapIt it		= WeatherCycles.find(name);
-		if (it == WeatherCycles.end())
-		{
-			Msg("! Invalid weather name: %s", name.c_str());
-			return;
-		}
-        R_ASSERT3			(it!=WeatherCycles.end(),"Invalid weather name.",*name);
-		CurrentCycleName	= it->first;
-		if (forced)			{Invalidate();			}
-		if (!bWFX){
-			CurrentWeather		= &it->second;
-			CurrentWeatherName	= it->first;
-		}
-		if (forced)			{SelectEnvs(fGameTime);	}
+    //. static BOOL bAlready = FALSE;
+    //. if(bAlready) return;
+    if (name.size())
+    {
+        //. bAlready = TRUE;
+        EnvsMapIt it = WeatherCycles.find(name);
+        if (it == WeatherCycles.end())
+        {
+            Msg("! Invalid weather name: %s", name.c_str());
+            return;
+        }
+        R_ASSERT3(it != WeatherCycles.end(), "Invalid weather name.", *name);
+        CurrentCycleName = it->first;
+        if (forced) { Invalidate(); }
+        if (!bWFX)
+        {
+            CurrentWeather = &it->second;
+            CurrentWeatherName = it->first;
+        }
+        if (forced) { SelectEnvs(fGameTime); }
 #ifdef WEATHER_LOGGING
-		Msg					("Starting Cycle: %s [%s]",*name,forced?"forced":"deferred");
+        Msg("Starting Cycle: %s [%s]", *name, forced ? "forced" : "deferred");
 #endif
-    }else{
+    }
+    else
+    {
 #ifndef _EDITOR
-		FATAL				("! Empty weather name");
+        FATAL("! Empty weather name");
 #endif
     }
 }
 
 bool CEnvironment::SetWeatherFX(shared_str name)
 {
-	if (bWFX)				return false;
-	if (name.size()){
-		EnvsMapIt it		= WeatherFXs.find(name);
-		R_ASSERT3			(it!=WeatherFXs.end(),"Invalid weather effect name.",*name);
-		EnvVec* PrevWeather = CurrentWeather; VERIFY(PrevWeather);
-		CurrentWeather		= &it->second;
-		CurrentWeatherName	= it->first;
-
-		float rewind_tm		= WFX_TRANS_TIME*fTimeFactor;
-		float start_tm		= fGameTime+rewind_tm;
-		float current_length;
-		float current_weight;
-		if (Current[0]->exec_time > Current[1]->exec_time){
-			float x			= fGameTime>Current[0]->exec_time?fGameTime-Current[0]->exec_time:(DAY_LENGTH-Current[0]->exec_time)+fGameTime;
-			current_length	= (DAY_LENGTH-Current[0]->exec_time)+Current[1]->exec_time;
-			current_weight	= x/current_length; 
-		}else{
-			current_length	= Current[1]->exec_time-Current[0]->exec_time;
-			current_weight	= (fGameTime-Current[0]->exec_time)/current_length; 
-		}
-		clamp				(current_weight,0.f,1.f);
-
-		std::sort			(CurrentWeather->begin(),CurrentWeather->end(),sort_env_etl_pred);
-		CEnvDescriptor* C0	= CurrentWeather->at(0);
-		CEnvDescriptor* C1	= CurrentWeather->at(1);
-		CEnvDescriptor* CE	= CurrentWeather->at(CurrentWeather->size()-2);
-		CEnvDescriptor* CT	= CurrentWeather->at(CurrentWeather->size()-1);
-		C0->copy			(*Current[0]);	C0->exec_time = NormalizeTime(fGameTime-((rewind_tm/(Current[1]->exec_time-fGameTime))*current_length-rewind_tm));
-		C1->copy			(*Current[1]);	C1->exec_time = NormalizeTime(start_tm);
-		for (EnvIt t_it=CurrentWeather->begin()+2; t_it!=CurrentWeather->end()-1; t_it++)
-			(*t_it)->exec_time= NormalizeTime(start_tm+(*t_it)->exec_time_loaded);
-		SelectEnv			(PrevWeather,WFX_end_desc[0],CE->exec_time);
-		SelectEnv			(PrevWeather,WFX_end_desc[1],WFX_end_desc[0]->exec_time+0.5f);
-		CT->copy			(*WFX_end_desc[0]);CT->exec_time = NormalizeTime(CE->exec_time+rewind_tm);
-		wfx_time			= TimeDiff(fGameTime,CT->exec_time);
-		bWFX				= true;
-
-		// sort wfx envs
-		std::sort			(CurrentWeather->begin(),CurrentWeather->end(),sort_env_pred);
-
-		Current[0]			= C0;
-		Current[1]			= C1;
+    if (bWFX) return false;
+    if (name.size())
+    {
+        EnvsMapIt it = WeatherFXs.find(name);
+        R_ASSERT3(it != WeatherFXs.end(), "Invalid weather effect name.", *name);
+        EnvVec* PrevWeather = CurrentWeather;
+        VERIFY(PrevWeather);
+        CurrentWeather = &it->second;
+        CurrentWeatherName = it->first;
+
+        float rewind_tm = WFX_TRANS_TIME*fTimeFactor;
+        float start_tm = fGameTime + rewind_tm;
+        float current_length;
+        float current_weight;
+        if (Current[0]->exec_time > Current[1]->exec_time)
+        {
+            float x = fGameTime > Current[0]->exec_time ? fGameTime - Current[0]->exec_time : (DAY_LENGTH - Current[0]->exec_time) + fGameTime;
+            current_length = (DAY_LENGTH - Current[0]->exec_time) + Current[1]->exec_time;
+            current_weight = x / current_length;
+        }
+        else
+        {
+            current_length = Current[1]->exec_time - Current[0]->exec_time;
+            current_weight = (fGameTime - Current[0]->exec_time) / current_length;
+        }
+        clamp(current_weight, 0.f, 1.f);
+
+        std::sort(CurrentWeather->begin(), CurrentWeather->end(), sort_env_etl_pred);
+        CEnvDescriptor* C0 = CurrentWeather->at(0);
+        CEnvDescriptor* C1 = CurrentWeather->at(1);
+        CEnvDescriptor* CE = CurrentWeather->at(CurrentWeather->size() - 2);
+        CEnvDescriptor* CT = CurrentWeather->at(CurrentWeather->size() - 1);
+        C0->copy(*Current[0]);
+        C0->exec_time = NormalizeTime(fGameTime - ((rewind_tm / (Current[1]->exec_time - fGameTime))*current_length - rewind_tm));
+        C1->copy(*Current[1]);
+        C1->exec_time = NormalizeTime(start_tm);
+        for (EnvIt t_it = CurrentWeather->begin() + 2; t_it != CurrentWeather->end() - 1; t_it++)
+            (*t_it)->exec_time = NormalizeTime(start_tm + (*t_it)->exec_time_loaded);
+        SelectEnv(PrevWeather, WFX_end_desc[0], CE->exec_time);
+        SelectEnv(PrevWeather, WFX_end_desc[1], WFX_end_desc[0]->exec_time + 0.5f);
+        CT->copy(*WFX_end_desc[0]);
+        CT->exec_time = NormalizeTime(CE->exec_time + rewind_tm);
+        wfx_time = TimeDiff(fGameTime, CT->exec_time);
+        bWFX = true;
+
+        // sort wfx envs
+        std::sort(CurrentWeather->begin(), CurrentWeather->end(), sort_env_pred);
+
+        Current[0] = C0;
+        Current[1] = C1;
 #ifdef WEATHER_LOGGING
-		Msg					("Starting WFX: '%s' - %3.2f sec",*name,wfx_time);
-//		for (EnvIt l_it=CurrentWeather->begin(); l_it!=CurrentWeather->end(); l_it++)
-//			Msg				(". Env: '%s' Tm: %3.2f",*(*l_it)->m_identifier.c_str(),(*l_it)->exec_time);
+        Msg("Starting WFX: '%s' - %3.2f sec", *name, wfx_time);
+        // for (EnvIt l_it=CurrentWeather->begin(); l_it!=CurrentWeather->end(); l_it++)
+        // Msg (". Env: '%s' Tm: %3.2f",*(*l_it)->m_identifier.c_str(),(*l_it)->exec_time);
 #endif
-	}else{
+    }
+    else
+    {
 #ifndef _EDITOR
-		FATAL				("! Empty weather effect name");
+        FATAL("! Empty weather effect name");
 #endif
-	}
-	return true;
+    }
+    return true;
 }
 
 bool CEnvironment::StartWeatherFXFromTime(shared_str name, float time)
 {
-	if(!SetWeatherFX(name))				
-		return false;
+    if (!SetWeatherFX(name))
+        return false;
 
-	for (EnvIt it=CurrentWeather->begin(); it!=CurrentWeather->end(); it++)
-		(*it)->exec_time = NormalizeTime((*it)->exec_time - wfx_time + time);
+    for (EnvIt it = CurrentWeather->begin(); it != CurrentWeather->end(); it++)
+        (*it)->exec_time = NormalizeTime((*it)->exec_time - wfx_time + time);
 
-	wfx_time = time;
-	return true;
+    wfx_time = time;
+    return true;
 }
 
-void CEnvironment::StopWFX	()
+void CEnvironment::StopWFX()
 {
-	VERIFY					(CurrentCycleName.size());
-	bWFX					= false;
-	SetWeather				(CurrentCycleName,false);
-	Current[0]				= WFX_end_desc[0];
-	Current[1]				= WFX_end_desc[1];
+    VERIFY(CurrentCycleName.size());
+    bWFX = false;
+    SetWeather(CurrentCycleName, false);
+    Current[0] = WFX_end_desc[0];
+    Current[1] = WFX_end_desc[1];
 #ifdef WEATHER_LOGGING
-	Msg						("WFX - end. Weather: '%s' Desc: '%s'/'%s' GameTime: %3.2f",CurrentWeatherName.c_str(),Current[0]->m_identifier.c_str(),Current[1]->m_identifier.c_str(),fGameTime);
+    Msg("WFX - end. Weather: '%s' Desc: '%s'/'%s' GameTime: %3.2f", CurrentWeatherName.c_str(), Current[0]->m_identifier.c_str(), Current[1]->m_identifier.c_str(), fGameTime);
 #endif
 }
 
 IC bool lb_env_pred(const CEnvDescriptor* x, float val)
-{	return x->exec_time < val;	}
+{
+    return x->exec_time < val;
+}
 
 void CEnvironment::SelectEnv(EnvVec* envs, CEnvDescriptor*& e, float gt)
 {
-	EnvIt env		= std::lower_bound(envs->begin(),envs->end(),gt,lb_env_pred);
-	if (env==envs->end()){
-		e			= envs->front();
-	}else{
-		e			= *env;
-	}
+    EnvIt env = std::lower_bound(envs->begin(), envs->end(), gt, lb_env_pred);
+    if (env == envs->end())
+    {
+        e = envs->front();
+    }
+    else
+    {
+        e = *env;
+    }
 }
 
 void CEnvironment::SelectEnvs(EnvVec* envs, CEnvDescriptor*& e0, CEnvDescriptor*& e1, float gt)
 {
-	EnvIt env		= std::lower_bound(envs->begin(),envs->end(),gt,lb_env_pred);
-	if (env==envs->end()){
-		e0			= *(envs->end()-1);
-		e1			= envs->front();
-	}else{
-		e1			= *env;
-		if (env==envs->begin())	e0 = *(envs->end()-1);
-		else					e0 = *(env-1);
-	}
+    EnvIt env = std::lower_bound(envs->begin(), envs->end(), gt, lb_env_pred);
+    if (env == envs->end())
+    {
+        e0 = *(envs->end() - 1);
+        e1 = envs->front();
+    }
+    else
+    {
+        e1 = *env;
+        if (env == envs->begin()) e0 = *(envs->end() - 1);
+        else e0 = *(env - 1);
+    }
 }
 
 void CEnvironment::SelectEnvs(float gt)
 {
-	VERIFY				(CurrentWeather);
-    if ((Current[0]==Current[1])&&(Current[0]==0)){
-		VERIFY			(!bWFX);
-		// first or forced start
-		SelectEnvs		(CurrentWeather,Current[0],Current[1],gt);
-    }else{
-		bool bSelect	= false;
-		if (Current[0]->exec_time>Current[1]->exec_time){
-			// terminator
-			bSelect		= (gt>Current[1]->exec_time)&&(gtexec_time);
-		}else{
-			bSelect		= (gt>Current[1]->exec_time);
-		}
-		if (bSelect){
-			Current[0]	= Current[1];
-			SelectEnv	(CurrentWeather,Current[1],gt);
+    VERIFY(CurrentWeather);
+    if ((Current[0] == Current[1]) && (Current[0] == 0))
+    {
+        VERIFY(!bWFX);
+        // first or forced start
+        SelectEnvs(CurrentWeather, Current[0], Current[1], gt);
+    }
+    else
+    {
+        bool bSelect = false;
+        if (Current[0]->exec_time > Current[1]->exec_time)
+        {
+            // terminator
+            bSelect = (gt > Current[1]->exec_time) && (gt < Current[0]->exec_time);
+        }
+        else
+        {
+            bSelect = (gt > Current[1]->exec_time);
+        }
+        if (bSelect)
+        {
+            Current[0] = Current[1];
+            SelectEnv(CurrentWeather, Current[1], gt);
 #ifdef WEATHER_LOGGING
-			Msg			("Weather: '%s' Desc: '%s' Time: %3.2f/%3.2f",CurrentWeatherName.c_str(),Current[1]->m_identifier.c_str(),Current[1]->exec_time,fGameTime);
+            Msg("Weather: '%s' Desc: '%s' Time: %3.2f/%3.2f", CurrentWeatherName.c_str(), Current[1]->m_identifier.c_str(), Current[1]->exec_time, fGameTime);
 #endif
-		}
+        }
     }
 }
 
 int get_ref_count(IUnknown* ii)
 {
-	if(ii){
-		ii->AddRef();
-		return ii->Release();
-	}else
-	return 0;
+    if (ii)
+    {
+        ii->AddRef();
+        return ii->Release();
+    }
+    else
+        return 0;
 }
 
-void CEnvironment::lerp		(float& current_weight)
+void CEnvironment::lerp(float& current_weight)
 {
-	if (bWFX&&(wfx_time<=0.f)) StopWFX();
-
-	SelectEnvs				(fGameTime);
-    VERIFY					(Current[0]&&Current[1]);
-
-	current_weight			= TimeWeight(fGameTime,Current[0]->exec_time,Current[1]->exec_time);
-	// modifiers
-	CEnvModifier			EM;
-	EM.far_plane			= 0;
-	EM.fog_color.set		( 0,0,0 );
-	EM.fog_density			= 0;
-	EM.ambient.set			( 0,0,0 );
-	EM.sky_color.set		( 0,0,0 );
-	EM.hemi_color.set		( 0,0,0 );
-	EM.use_flags.zero		();
-
-	Fvector	view			= Device.vCameraPosition;
-	float	mpower			= 0;
-	for (xr_vector::iterator mit=Modifiers.begin(); mit!=Modifiers.end(); mit++)
-		mpower				+= EM.sum(*mit,view);
-
-	// final lerp
-	CurrentEnv->lerp		(this,*Current[0],*Current[1],current_weight,EM,mpower);
+    if (bWFX && (wfx_time <= 0.f)) StopWFX();
+
+    SelectEnvs(fGameTime);
+    VERIFY(Current[0] && Current[1]);
+
+    current_weight = TimeWeight(fGameTime, Current[0]->exec_time, Current[1]->exec_time);
+    // modifiers
+    CEnvModifier EM;
+    EM.far_plane = 0;
+    EM.fog_color.set(0, 0, 0);
+    EM.fog_density = 0;
+    EM.ambient.set(0, 0, 0);
+    EM.sky_color.set(0, 0, 0);
+    EM.hemi_color.set(0, 0, 0);
+    EM.use_flags.zero();
+
+    Fvector view = Device.vCameraPosition;
+    float mpower = 0;
+    for (xr_vector::iterator mit = Modifiers.begin(); mit != Modifiers.end(); mit++)
+        mpower += EM.sum(*mit, view);
+
+    // final lerp
+    CurrentEnv->lerp(this, *Current[0], *Current[1], current_weight, EM, mpower);
 }
 
 void CEnvironment::OnFrame()
 {
 #ifdef _EDITOR
-	SetGameTime				(fGameTime+Device.fTimeDelta*fTimeFactor,fTimeFactor);
-    if (fsimilar(ed_to_time,DAY_LENGTH)&&fsimilar(ed_from_time,0.f)){
-	    if (fGameTime>DAY_LENGTH)	fGameTime-=DAY_LENGTH;
-    }else{
-	    if (fGameTime>ed_to_time){	
-        	fGameTime=fGameTime-ed_to_time+ed_from_time;
-            Current[0]=Current[1]=0;
+    SetGameTime(fGameTime + Device.fTimeDelta*fTimeFactor, fTimeFactor);
+    if (fsimilar(ed_to_time, DAY_LENGTH) && fsimilar(ed_from_time, 0.f))
+    {
+        if (fGameTime > DAY_LENGTH) fGameTime -= DAY_LENGTH;
+    }
+    else
+    {
+        if (fGameTime > ed_to_time)
+        {
+            fGameTime = fGameTime - ed_to_time + ed_from_time;
+            Current[0] = Current[1] = 0;
         }
-    	if (fGameTimeiGetAsyncKeyState(DIK_O))		SetWeatherFX("surge_day"); 
-	float					current_weight;
-	lerp					(current_weight);
+    // if (pInput->iGetAsyncKeyState(DIK_O)) SetWeatherFX("surge_day");
+    float current_weight;
+    lerp(current_weight);
 
-	//	Igor. Dynamic sun position. 
-	if ( !::Render->is_sun_static())
-		calculate_dynamic_sun_dir();
+    // Igor. Dynamic sun position.
+    if (!::Render->is_sun_static())
+        calculate_dynamic_sun_dir();
 
 #ifndef MASTER_GOLD
-	if(CurrentEnv->sun_dir.y>0)
-	{
-		Log("CurrentEnv->sun_dir", CurrentEnv->sun_dir);
-//		Log("current_weight", current_weight);
-//		Log("mpower", mpower);
+    if (CurrentEnv->sun_dir.y > 0)
+    {
+        Log("CurrentEnv->sun_dir", CurrentEnv->sun_dir);
+        // Log("current_weight", current_weight);
+        // Log("mpower", mpower);
 
-		Log("Current[0]->sun_dir", Current[0]->sun_dir);
-		Log("Current[1]->sun_dir", Current[1]->sun_dir);
+        Log("Current[0]->sun_dir", Current[0]->sun_dir);
+        Log("Current[1]->sun_dir", Current[1]->sun_dir);
 
-	}
-	VERIFY2						(CurrentEnv->sun_dir.y<0,"Invalid sun direction settings in lerp");
+    }
+    VERIFY2(CurrentEnv->sun_dir.y < 0, "Invalid sun direction settings in lerp");
 #endif // #ifndef MASTER_GOLD
 
-	PerlinNoise1D->SetFrequency		(wind_gust_factor*MAX_NOISE_FREQ);
-	wind_strength_factor			= clampr(PerlinNoise1D->GetContinious(Device.fTimeGlobal)+0.5f,0.f,1.f); 
+    PerlinNoise1D->SetFrequency(wind_gust_factor*MAX_NOISE_FREQ);
+    wind_strength_factor = clampr(PerlinNoise1D->GetContinious(Device.fTimeGlobal) + 0.5f, 0.f, 1.f);
 
-    shared_str l_id						=	(current_weight<0.5f)?Current[0]->lens_flare_id:Current[1]->lens_flare_id;
-	eff_LensFlare->OnFrame				(l_id);
-	shared_str t_id						=	(current_weight<0.5f)?Current[0]->tb_id:Current[1]->tb_id;
-    eff_Thunderbolt->OnFrame			(t_id,CurrentEnv->bolt_period,CurrentEnv->bolt_duration);
-	eff_Rain->OnFrame					();
+    shared_str l_id = (current_weight < 0.5f) ? Current[0]->lens_flare_id : Current[1]->lens_flare_id;
+    eff_LensFlare->OnFrame(l_id);
+    shared_str t_id = (current_weight < 0.5f) ? Current[0]->tb_id : Current[1]->tb_id;
+    eff_Thunderbolt->OnFrame(t_id, CurrentEnv->bolt_period, CurrentEnv->bolt_duration);
+    eff_Rain->OnFrame();
 
-	// ******************** Environment params (setting)
-	m_pRender->OnFrame(*this);
+    // ******************** Environment params (setting)
+    m_pRender->OnFrame(*this);
 }
 
 void CEnvironment::calculate_dynamic_sun_dir()
 {
-	float g = (360.0f/365.25f)*(180.0f + fGameTime/DAY_LENGTH);
+    float g = (360.0f / 365.25f)*(180.0f + fGameTime / DAY_LENGTH);
 
-	g = deg2rad(g);
+    g = deg2rad(g);
 
-	//	Declination
-	float D = 0.396372f-22.91327f*_cos(g)+4.02543f*_sin(g)-0.387205f*_cos(2*g)+
-		0.051967f*_sin(2*g)-0.154527f*_cos(3*g) + 0.084798f*_sin(3*g);
+    // Declination
+    float D = 0.396372f - 22.91327f*_cos(g) + 4.02543f*_sin(g) - 0.387205f*_cos(2 * g) +
+        0.051967f*_sin(2 * g) - 0.154527f*_cos(3 * g) + 0.084798f*_sin(3 * g);
 
-	//	Now calculate the time correction for solar angle:
-	float TC = 0.004297f+0.107029f*_cos(g)-1.837877f*_sin(g)-0.837378f*_cos(2*g)-
-		2.340475f*_sin(2*g);
+    // Now calculate the time correction for solar angle:
+    float TC = 0.004297f + 0.107029f*_cos(g) - 1.837877f*_sin(g) - 0.837378f*_cos(2 * g) -
+        2.340475f*_sin(2 * g);
 
-	//	IN degrees
-	float Longitude = -30.4f;
+    // IN degrees
+    float Longitude = -30.4f;
 
-	float SHA = (fGameTime/(DAY_LENGTH/24)-12)*15 + Longitude + TC;
+    float SHA = (fGameTime / (DAY_LENGTH / 24) - 12) * 15 + Longitude + TC;
 
-	//	Need this to correctly determine SHA sign
-	if (SHA>180) SHA -= 360;
-	if (SHA<-180) SHA += 360;
+    // Need this to correctly determine SHA sign
+    if (SHA > 180) SHA -= 360;
+    if (SHA < -180) SHA += 360;
 
-	//	IN degrees
-	float const Latitude = 50.27f;
-	float const LatitudeR = deg2rad(Latitude);
+    // IN degrees
+    float const Latitude = 50.27f;
+    float const LatitudeR = deg2rad(Latitude);
 
-	//	Now we can calculate the Sun Zenith Angle (SZA):
-	float cosSZA = _sin(LatitudeR)
-		* _sin(deg2rad(D)) + _cos(LatitudeR)*
-		_cos(deg2rad(D)) * _cos(deg2rad(SHA));
+    // Now we can calculate the Sun Zenith Angle (SZA):
+    float cosSZA = _sin(LatitudeR)
+        * _sin(deg2rad(D)) + _cos(LatitudeR)*
+        _cos(deg2rad(D)) * _cos(deg2rad(SHA));
 
-	clamp( cosSZA, -1.0f, 1.0f);
+    clamp(cosSZA, -1.0f, 1.0f);
 
-	float SZA = acosf(cosSZA);
-	float SEA = PI/2-SZA;
+    float SZA = acosf(cosSZA);
+    float SEA = PI / 2 - SZA;
 
-	//	To finish we will calculate the Azimuth Angle (AZ):
-	float cosAZ = 0.f;
-	float const sin_SZA = _sin(SZA);
-	float const cos_Latitude = _cos(LatitudeR);
-	float const sin_SZA_X_cos_Latitude = sin_SZA*cos_Latitude;
-	if (!fis_zero(sin_SZA_X_cos_Latitude))
-		cosAZ	= (_sin(deg2rad(D))-_sin(LatitudeR)*_cos(SZA))/sin_SZA_X_cos_Latitude;
+    // To finish we will calculate the Azimuth Angle (AZ):
+    float cosAZ = 0.f;
+    float const sin_SZA = _sin(SZA);
+    float const cos_Latitude = _cos(LatitudeR);
+    float const sin_SZA_X_cos_Latitude = sin_SZA*cos_Latitude;
+    if (!fis_zero(sin_SZA_X_cos_Latitude))
+        cosAZ = (_sin(deg2rad(D)) - _sin(LatitudeR)*_cos(SZA)) / sin_SZA_X_cos_Latitude;
 
-	clamp( cosAZ, -1.0f, 1.0f);
-	float AZ = acosf(cosAZ);
+    clamp(cosAZ, -1.0f, 1.0f);
+    float AZ = acosf(cosAZ);
 
-	const Fvector2 minAngle = Fvector2().set(deg2rad(1.0f), deg2rad(3.0f));
+    const Fvector2 minAngle = Fvector2().set(deg2rad(1.0f), deg2rad(3.0f));
 
-	if (SEAsun_dir.setHP	(AZ,SEA);
-	R_ASSERT					( _valid(CurrentEnv->sun_dir) );
+    R_ASSERT(_valid(AZ));
+    R_ASSERT(_valid(SEA));
+    CurrentEnv->sun_dir.setHP(AZ, SEA);
+    R_ASSERT(_valid(CurrentEnv->sun_dir));
 
-	CurrentEnv->sun_color.mul	(fSunBlend);
+    CurrentEnv->sun_color.mul(fSunBlend);
 }
 
-void CEnvironment::create_mixer ()
+void CEnvironment::create_mixer()
 {
-	VERIFY					(!CurrentEnv);
-	CurrentEnv				= xr_new("00:00:00");
+    VERIFY(!CurrentEnv);
+    CurrentEnv = xr_new("00:00:00");
 }
 
 void CEnvironment::destroy_mixer()
 {
-	xr_delete				(CurrentEnv);
+    xr_delete(CurrentEnv);
 }
 
-SThunderboltDesc* CEnvironment::thunderbolt_description			(CInifile& config, shared_str const& section)
+SThunderboltDesc* CEnvironment::thunderbolt_description(CInifile& config, shared_str const& section)
 {
-	SThunderboltDesc*		result = xr_new();
-	result->load			(config, section);
-	return					(result);
+    SThunderboltDesc* result = xr_new();
+    result->load(config, section);
+    return (result);
 }
 
-SThunderboltCollection* CEnvironment::thunderbolt_collection	(CInifile* pIni, CInifile* thunderbolts, LPCSTR section)
+SThunderboltCollection* CEnvironment::thunderbolt_collection(CInifile* pIni, CInifile* thunderbolts, LPCSTR section)
 {
-	SThunderboltCollection*	result = xr_new();
-	result->load			(pIni, thunderbolts, section);
-	return					(result);
+    SThunderboltCollection* result = xr_new();
+    result->load(pIni, thunderbolts, section);
+    return (result);
 }
 
-SThunderboltCollection* CEnvironment::thunderbolt_collection	(xr_vector& collection,  shared_str const& id)
+SThunderboltCollection* CEnvironment::thunderbolt_collection(xr_vector& collection, shared_str const& id)
 {
-	typedef xr_vector	Container;
-	Container::iterator		i = collection.begin();
-	Container::iterator		e = collection.end();
-	for ( ; i != e; ++i)
-		if ((*i)->section == id)
-			return			(*i);
-
-	NODEFAULT;
+    typedef xr_vector Container;
+    Container::iterator i = collection.begin();
+    Container::iterator e = collection.end();
+    for (; i != e; ++i)
+        if ((*i)->section == id)
+            return (*i);
+
+    NODEFAULT;
 #ifdef DEBUG
-	return					(0);
+    return (0);
 #endif // #ifdef DEBUG
 }
 
-CLensFlareDescriptor* CEnvironment::add_flare					(xr_vector& collection, shared_str const& id)
+CLensFlareDescriptor* CEnvironment::add_flare(xr_vector& collection, shared_str const& id)
 {
-	typedef xr_vector	Flares;
-
-	Flares::const_iterator	i = collection.begin();
-	Flares::const_iterator	e = collection.end();
-	for ( ; i != e; ++i) {
-		if ((*i)->section == id)
-			return			(*i);
-	}
-
-	CLensFlareDescriptor*	result = xr_new();
-	result->load			(m_suns_config, id.c_str());
-	collection.push_back	(result);	
-	return					(result);
+    typedef xr_vector Flares;
+
+    Flares::const_iterator i = collection.begin();
+    Flares::const_iterator e = collection.end();
+    for (; i != e; ++i)
+    {
+        if ((*i)->section == id)
+            return (*i);
+    }
+
+    CLensFlareDescriptor* result = xr_new();
+    result->load(m_suns_config, id.c_str());
+    collection.push_back(result);
+    return (result);
 }
\ No newline at end of file
diff --git a/src/xrEngine/Environment.h b/src/xrEngine/Environment.h
index 23918b6add5..015eb9a1462 100644
--- a/src/xrEngine/Environment.h
+++ b/src/xrEngine/Environment.h
@@ -2,372 +2,381 @@
 #define EnvironmentH
 
 // refs
-class ENGINE_API	IRender_Visual;
-class ENGINE_API	CInifile;
-class ENGINE_API 	CEnvironment;
+class ENGINE_API IRender_Visual;
+class ENGINE_API CInifile;
+class ENGINE_API CEnvironment;
 
 // refs - effects
-class ENGINE_API	CEnvironment;
-class ENGINE_API	CLensFlare;
-class ENGINE_API	CEffect_Rain;
-class ENGINE_API	CEffect_Thunderbolt;
+class ENGINE_API CEnvironment;
+class ENGINE_API CLensFlare;
+class ENGINE_API CEffect_Rain;
+class ENGINE_API CEffect_Thunderbolt;
 
-class ENGINE_API	CPerlinNoise1D;
+class ENGINE_API CPerlinNoise1D;
 
 struct SThunderboltDesc;
 struct SThunderboltCollection;
 class CLensFlareDescriptor;
 
-#define DAY_LENGTH		86400.f
+#define DAY_LENGTH 86400.f
 
 #include "../Include/xrRender/FactoryPtr.h"
 #include "../Include/xrRender/EnvironmentRender.h"
 
 #ifdef INGAME_EDITOR
-#	define	INGAME_EDITOR_VIRTUAL	virtual
+# define INGAME_EDITOR_VIRTUAL virtual
 #else // #ifdef INGAME_EDITOR
-#	define	INGAME_EDITOR_VIRTUAL
+# define INGAME_EDITOR_VIRTUAL
 #endif // #ifdef INGAME_EDITOR
 
 // t-defs
-class ENGINE_API	CEnvModifier
+class ENGINE_API CEnvModifier
 {
 public:
-	Fvector3			position;
-	float				radius;
-	float				power;
-
-	float				far_plane;
-	Fvector3			fog_color;
-	float				fog_density;
-	Fvector3			ambient;
-	Fvector3			sky_color;		
-	Fvector3			hemi_color;
-	Flags16				use_flags;
-
-	void				load		(IReader* fs, u32 version);
-	float				sum			(CEnvModifier&	_another, Fvector3& view);
+    Fvector3 position;
+    float radius;
+    float power;
+
+    float far_plane;
+    Fvector3 fog_color;
+    float fog_density;
+    Fvector3 ambient;
+    Fvector3 sky_color;
+    Fvector3 hemi_color;
+    Flags16 use_flags;
+
+    void load(IReader* fs, u32 version);
+    float sum(CEnvModifier& _another, Fvector3& view);
 };
 
-class ENGINE_API	CEnvAmbient
+class ENGINE_API CEnvAmbient
 {
 public:
-	struct SEffect{
-		u32 			life_time;
-		ref_sound		sound;		
-		shared_str		particles;
-		Fvector			offset;
-		float			wind_gust_factor;
-		float			wind_blast_in_time;
-		float			wind_blast_out_time;
-		float			wind_blast_strength;
-		Fvector			wind_blast_direction;
-
-		INGAME_EDITOR_VIRTUAL	~SEffect				()	{}
-	};
-	DEFINE_VECTOR(SEffect*,EffectVec,EffectVecIt);
-	struct SSndChannel
-	{
-		shared_str				m_load_section;
-		Fvector2				m_sound_dist;
-		Ivector4				m_sound_period;
-
-		typedef xr_vector	sounds_type;
-
-		void					load					(CInifile& config, LPCSTR sect);
-		ref_sound&				get_rnd_sound			()	{return sounds()[Random.randI(sounds().size())];}
-		u32						get_rnd_sound_time		()	{return (m_sound_period.z < m_sound_period.w) ? Random.randI(m_sound_period.z,m_sound_period.w) : 0;}
-		u32						get_rnd_sound_first_time()	{return (m_sound_period.x < m_sound_period.y) ? Random.randI(m_sound_period.x,m_sound_period.y) : 0;}
-		float					get_rnd_sound_dist		()	{return (m_sound_dist.x < m_sound_dist.y) ? Random.randF(m_sound_dist.x, m_sound_dist.y) : 0;}
-		INGAME_EDITOR_VIRTUAL	~SSndChannel			()	{}
-		inline INGAME_EDITOR_VIRTUAL sounds_type& sounds()  {return m_sounds;}
-
-	protected:
-		xr_vector	m_sounds;
-	};
-	DEFINE_VECTOR(SSndChannel*,SSndChannelVec,SSndChannelVecIt);
+    struct SEffect
+    {
+        u32 life_time;
+        ref_sound sound;
+        shared_str particles;
+        Fvector offset;
+        float wind_gust_factor;
+        float wind_blast_in_time;
+        float wind_blast_out_time;
+        float wind_blast_strength;
+        Fvector wind_blast_direction;
+
+        INGAME_EDITOR_VIRTUAL ~SEffect() {}
+    };
+    DEFINE_VECTOR(SEffect*, EffectVec, EffectVecIt);
+    struct SSndChannel
+    {
+        shared_str m_load_section;
+        Fvector2 m_sound_dist;
+        Ivector4 m_sound_period;
+
+        typedef xr_vector sounds_type;
+
+        void load(CInifile& config, LPCSTR sect);
+        ref_sound& get_rnd_sound() { return sounds()[Random.randI(sounds().size())]; }
+        u32 get_rnd_sound_time() { return (m_sound_period.z < m_sound_period.w) ? Random.randI(m_sound_period.z, m_sound_period.w) : 0; }
+        u32 get_rnd_sound_first_time() { return (m_sound_period.x < m_sound_period.y) ? Random.randI(m_sound_period.x, m_sound_period.y) : 0; }
+        float get_rnd_sound_dist() { return (m_sound_dist.x < m_sound_dist.y) ? Random.randF(m_sound_dist.x, m_sound_dist.y) : 0; }
+        INGAME_EDITOR_VIRTUAL ~SSndChannel() {}
+        inline INGAME_EDITOR_VIRTUAL sounds_type& sounds() { return m_sounds; }
+
+    protected:
+        xr_vector m_sounds;
+    };
+    DEFINE_VECTOR(SSndChannel*, SSndChannelVec, SSndChannelVecIt);
 protected:
-	shared_str				m_load_section;
+    shared_str m_load_section;
 
-	EffectVec				m_effects;
-	Ivector2				m_effect_period;
+    EffectVec m_effects;
+    Ivector2 m_effect_period;
 
-	SSndChannelVec			m_sound_channels;
-	shared_str              m_ambients_config_filename;
+    SSndChannelVec m_sound_channels;
+    shared_str m_ambients_config_filename;
 
 public:
-	IC const shared_str&	name				()	{return m_load_section;}
-	IC const shared_str&	get_ambients_config_filename ()	{return m_ambients_config_filename;}
-
-	INGAME_EDITOR_VIRTUAL	void	load		(
-								CInifile& ambients_config,
-								CInifile& sound_channels_config,
-								CInifile& effects_config,
-								const shared_str& section
-							);
-	IC SEffect*				get_rnd_effect		()	{return effects().empty()?0:effects()[Random.randI(effects().size())];}
-	IC u32					get_rnd_effect_time ()	{return Random.randI(m_effect_period.x, m_effect_period.y);}
-
-	INGAME_EDITOR_VIRTUAL	SEffect*		create_effect			(CInifile& config, LPCSTR id);
-	INGAME_EDITOR_VIRTUAL	SSndChannel*	create_sound_channel	(CInifile& config, LPCSTR id);
-	INGAME_EDITOR_VIRTUAL					~CEnvAmbient			();
-							void			destroy					();
-	inline INGAME_EDITOR_VIRTUAL EffectVec&			effects			() { return m_effects; }
-	inline INGAME_EDITOR_VIRTUAL SSndChannelVec&	get_snd_channels() { return m_sound_channels; }
+    IC const shared_str& name() { return m_load_section; }
+    IC const shared_str& get_ambients_config_filename() { return m_ambients_config_filename; }
+
+    INGAME_EDITOR_VIRTUAL void load(
+        CInifile& ambients_config,
+        CInifile& sound_channels_config,
+        CInifile& effects_config,
+        const shared_str& section
+        );
+    IC SEffect* get_rnd_effect() { return effects().empty() ? 0 : effects()[Random.randI(effects().size())]; }
+    IC u32 get_rnd_effect_time() { return Random.randI(m_effect_period.x, m_effect_period.y); }
+
+    INGAME_EDITOR_VIRTUAL SEffect* create_effect(CInifile& config, LPCSTR id);
+    INGAME_EDITOR_VIRTUAL SSndChannel* create_sound_channel(CInifile& config, LPCSTR id);
+    INGAME_EDITOR_VIRTUAL ~CEnvAmbient();
+    void destroy();
+    inline INGAME_EDITOR_VIRTUAL EffectVec& effects() { return m_effects; }
+    inline INGAME_EDITOR_VIRTUAL SSndChannelVec& get_snd_channels() { return m_sound_channels; }
 };
 
-class ENGINE_API	CEnvDescriptor
+class ENGINE_API CEnvDescriptor
 {
 public:
-	float				exec_time;
-	float				exec_time_loaded;
+    float exec_time;
+    float exec_time_loaded;
 
-	shared_str			sky_texture_name	;
-	shared_str			sky_texture_env_name;
-	shared_str			clouds_texture_name	;
+    shared_str sky_texture_name;
+    shared_str sky_texture_env_name;
+    shared_str clouds_texture_name;
 
-	BENCH_SEC_SCRAMBLEMEMBER1
+    BENCH_SEC_SCRAMBLEMEMBER1
 
-	/*
-	ref_texture			sky_texture		;
-	ref_texture			sky_texture_env	;
-	ref_texture			clouds_texture	;
-	*/
-	FactoryPtr	m_pDescriptor;
+        /*
+        ref_texture sky_texture ;
+        ref_texture sky_texture_env ;
+        ref_texture clouds_texture ;
+        */
+        FactoryPtr m_pDescriptor;
 
-	Fvector4			clouds_color	;
-	Fvector3			sky_color		;
-	float				sky_rotation	;
+    Fvector4 clouds_color;
+    Fvector3 sky_color;
+    float sky_rotation;
 
-	float				far_plane;
+    float far_plane;
 
-	Fvector3			fog_color;
-	float				fog_density;
-	float				fog_distance;
+    Fvector3 fog_color;
+    float fog_density;
+    float fog_distance;
 
-	float				rain_density;
-	Fvector3			rain_color;
+    float rain_density;
+    Fvector3 rain_color;
 
-	float				bolt_period;
-	float				bolt_duration;
+    float bolt_period;
+    float bolt_duration;
 
-    float				wind_velocity;
-    float				wind_direction;  
-    
-	Fvector3			ambient		;
-	Fvector4			hemi_color	;	// w = R2 correction
-	Fvector3			sun_color	;
-	Fvector3			sun_dir		;
-	float				m_fSunShaftsIntensity;
-	float				m_fWaterIntensity;
+    float wind_velocity;
+    float wind_direction;
 
+    Fvector3 ambient;
+    Fvector4 hemi_color; // w = R2 correction
+    Fvector3 sun_color;
+    Fvector3 sun_dir;
+    float m_fSunShaftsIntensity;
+    float m_fWaterIntensity;
 
-//	int					lens_flare_id;
-//	int					tb_id;
-	shared_str			lens_flare_id;
-	shared_str			tb_id;
-    
-	CEnvAmbient*		env_ambient;
 
+    // int lens_flare_id;
+    // int tb_id;
+    shared_str lens_flare_id;
+    shared_str tb_id;
 
-						CEnvDescriptor	(shared_str const& identifier);
+    CEnvAmbient* env_ambient;
 
-	void				load			(CEnvironment& environment, CInifile& config);
-	void				copy			(const CEnvDescriptor& src)
-	{
-		float tm0		= exec_time;
-		float tm1		= exec_time_loaded; 
-		*this			= src;
-		exec_time		= tm0;
-		exec_time_loaded= tm1;
-	}
 
-	void				on_device_create	();
-	void				on_device_destroy	();
+    CEnvDescriptor(shared_str const& identifier);
 
-	shared_str			m_identifier;
+    void load(CEnvironment& environment, CInifile& config);
+    void copy(const CEnvDescriptor& src)
+    {
+        float tm0 = exec_time;
+        float tm1 = exec_time_loaded;
+        *this = src;
+        exec_time = tm0;
+        exec_time_loaded = tm1;
+    }
+
+    void on_device_create();
+    void on_device_destroy();
+
+    shared_str m_identifier;
 };
 
-class ENGINE_API		CEnvDescriptorMixer: public CEnvDescriptor{
+class ENGINE_API CEnvDescriptorMixer : public CEnvDescriptor
+{
 public:
-	/*
-	STextureList		sky_r_textures;		
-	STextureList		sky_r_textures_env;	
-	STextureList		clouds_r_textures;	
-	*/
-	FactoryPtr	m_pDescriptorMixer;
-	float				weight;				
-
-	float				fog_near;		
-	float				fog_far;		
+    /*
+    STextureList sky_r_textures;
+    STextureList sky_r_textures_env;
+    STextureList clouds_r_textures;
+    */
+    FactoryPtr m_pDescriptorMixer;
+    float weight;
+
+    float fog_near;
+    float fog_far;
 public:
-						CEnvDescriptorMixer	(shared_str const& identifier);
-	INGAME_EDITOR_VIRTUAL void lerp			(CEnvironment* parent, CEnvDescriptor& A, CEnvDescriptor& B, float f, CEnvModifier& M, float m_power);
-	void				clear				();
-	void				destroy				();
+    CEnvDescriptorMixer(shared_str const& identifier);
+    INGAME_EDITOR_VIRTUAL void lerp(CEnvironment* parent, CEnvDescriptor& A, CEnvDescriptor& B, float f, CEnvModifier& M, float m_power);
+    void clear();
+    void destroy();
 };
 
-class ENGINE_API	CEnvironment
+class ENGINE_API CEnvironment
 {
-	friend class dxEnvironmentRender;
-	struct str_pred : public std::binary_function	{	
-		IC bool operator()(const shared_str& x, const shared_str& y) const
-		{	return xr_strcmp(x,y)<0;	}
-	};
+    friend class dxEnvironmentRender;
+    struct str_pred : public std::binary_function < shared_str, shared_str, bool >
+    {
+        IC bool operator()(const shared_str& x, const shared_str& y) const
+        {
+            return xr_strcmp(x, y) < 0;
+        }
+    };
 public:
-	DEFINE_VECTOR			(CEnvAmbient*,EnvAmbVec,EnvAmbVecIt);
-	DEFINE_VECTOR			(CEnvDescriptor*,EnvVec,EnvIt);
-	DEFINE_MAP_PRED			(shared_str,EnvVec,EnvsMap,EnvsMapIt,str_pred);
+    DEFINE_VECTOR(CEnvAmbient*, EnvAmbVec, EnvAmbVecIt);
+    DEFINE_VECTOR(CEnvDescriptor*, EnvVec, EnvIt);
+    DEFINE_MAP_PRED(shared_str, EnvVec, EnvsMap, EnvsMapIt, str_pred);
 private:
-	// clouds
-	FvectorVec				CloudsVerts;
-	U16Vec					CloudsIndices;
+    // clouds
+    FvectorVec CloudsVerts;
+    U16Vec CloudsIndices;
 private:
-	float					NormalizeTime	(float tm);
-	float					TimeDiff		(float prev, float cur);
-	float					TimeWeight		(float val, float min_t, float max_t);
-	void					SelectEnvs		(EnvVec* envs, CEnvDescriptor*& e0, CEnvDescriptor*& e1, float tm);
-	void					SelectEnv		(EnvVec* envs, CEnvDescriptor*& e, float tm);
+    float NormalizeTime(float tm);
+    float TimeDiff(float prev, float cur);
+    float TimeWeight(float val, float min_t, float max_t);
+    void SelectEnvs(EnvVec* envs, CEnvDescriptor*& e0, CEnvDescriptor*& e1, float tm);
+    void SelectEnv(EnvVec* envs, CEnvDescriptor*& e, float tm);
 
-	void					calculate_dynamic_sun_dir();
+    void calculate_dynamic_sun_dir();
 public:
-	static bool sort_env_pred	(const CEnvDescriptor* x, const CEnvDescriptor* y)
-	{	return x->exec_time < y->exec_time;	}
-	static bool sort_env_etl_pred	(const CEnvDescriptor* x, const CEnvDescriptor* y)
-	{	return x->exec_time_loaded < y->exec_time_loaded;	}
+    static bool sort_env_pred(const CEnvDescriptor* x, const CEnvDescriptor* y)
+    {
+        return x->exec_time < y->exec_time;
+    }
+    static bool sort_env_etl_pred(const CEnvDescriptor* x, const CEnvDescriptor* y)
+    {
+        return x->exec_time_loaded < y->exec_time_loaded;
+    }
 protected:
-	CPerlinNoise1D*			PerlinNoise1D;
+    CPerlinNoise1D* PerlinNoise1D;
 
-	float					fGameTime;
+    float fGameTime;
 public:
-	FactoryPtr	m_pRender;
-	BOOL					bNeed_re_create_env;
-
-	float					wind_strength_factor;	
-	float					wind_gust_factor;
-
-	// wind blast params
-	float					wind_blast_strength;
-	Fvector					wind_blast_direction;
-	Fquaternion				wind_blast_start_time;
-	Fquaternion				wind_blast_stop_time;
-	float					wind_blast_strength_start_value;
-	float					wind_blast_strength_stop_value;
-	Fquaternion				wind_blast_current;
-	// Environments
-	BENCH_SEC_SCRAMBLEMEMBER2
-	CEnvDescriptorMixer*	CurrentEnv;
-	CEnvDescriptor*			Current[2];
-
-	bool					bWFX;
-	float					wfx_time;
-	CEnvDescriptor*			WFX_end_desc[2];
-    
-    EnvVec*					CurrentWeather;
-    shared_str				CurrentWeatherName;
-	shared_str				CurrentCycleName;
-
-	EnvsMap					WeatherCycles;
-	EnvsMap					WeatherFXs;
-	xr_vector	Modifiers;
-	EnvAmbVec				Ambients;
-
-	CEffect_Rain*			eff_Rain;
-	CLensFlare*				eff_LensFlare;
-	CEffect_Thunderbolt*	eff_Thunderbolt;
-
-	float					fTimeFactor;
-
-    void					SelectEnvs			(float gt);
-
-	void					UpdateAmbient		();
-	INGAME_EDITOR_VIRTUAL CEnvAmbient* AppendEnvAmb	(const shared_str& sect);
-
-	void					Invalidate			();
+    FactoryPtr m_pRender;
+    BOOL bNeed_re_create_env;
+
+    float wind_strength_factor;
+    float wind_gust_factor;
+
+    // wind blast params
+    float wind_blast_strength;
+    Fvector wind_blast_direction;
+    Fquaternion wind_blast_start_time;
+    Fquaternion wind_blast_stop_time;
+    float wind_blast_strength_start_value;
+    float wind_blast_strength_stop_value;
+    Fquaternion wind_blast_current;
+    // Environments
+    BENCH_SEC_SCRAMBLEMEMBER2
+        CEnvDescriptorMixer* CurrentEnv;
+    CEnvDescriptor* Current[2];
+
+    bool bWFX;
+    float wfx_time;
+    CEnvDescriptor* WFX_end_desc[2];
+
+    EnvVec* CurrentWeather;
+    shared_str CurrentWeatherName;
+    shared_str CurrentCycleName;
+
+    EnvsMap WeatherCycles;
+    EnvsMap WeatherFXs;
+    xr_vector Modifiers;
+    EnvAmbVec Ambients;
+
+    CEffect_Rain* eff_Rain;
+    CLensFlare* eff_LensFlare;
+    CEffect_Thunderbolt* eff_Thunderbolt;
+
+    float fTimeFactor;
+
+    void SelectEnvs(float gt);
+
+    void UpdateAmbient();
+    INGAME_EDITOR_VIRTUAL CEnvAmbient* AppendEnvAmb(const shared_str& sect);
+
+    void Invalidate();
 public:
-							CEnvironment		();
+    CEnvironment();
 
-	INGAME_EDITOR_VIRTUAL	~CEnvironment		();
+    INGAME_EDITOR_VIRTUAL ~CEnvironment();
 
-	INGAME_EDITOR_VIRTUAL void	load			();
-    INGAME_EDITOR_VIRTUAL void	unload			();
+    INGAME_EDITOR_VIRTUAL void load();
+    INGAME_EDITOR_VIRTUAL void unload();
 
-	void					mods_load			();
-	void					mods_unload			();
+    void mods_load();
+    void mods_unload();
 
-	void					OnFrame				();
-	void					lerp				(float& current_weight);
+    void OnFrame();
+    void lerp(float& current_weight);
 
-	void					RenderSky			();
-	void					RenderClouds		();
-	void					RenderFlares		();
-	void					RenderLast			();
+    void RenderSky();
+    void RenderClouds();
+    void RenderFlares();
+    void RenderLast();
 
-	bool					SetWeatherFX		(shared_str name);
-	bool					StartWeatherFXFromTime	(shared_str name, float time);
-	bool					IsWFXPlaying		(){return bWFX;}
-	void					StopWFX				();
+    bool SetWeatherFX(shared_str name);
+    bool StartWeatherFXFromTime(shared_str name, float time);
+    bool IsWFXPlaying() { return bWFX; }
+    void StopWFX();
 
-	void					SetWeather			(shared_str name, bool forced=false);
-    shared_str				GetWeather			()					{ return CurrentWeatherName;}
-	void					ChangeGameTime		(float game_time);
-	void					SetGameTime			(float game_time, float time_factor);
+    void SetWeather(shared_str name, bool forced = false);
+    shared_str GetWeather() { return CurrentWeatherName; }
+    void ChangeGameTime(float game_time);
+    void SetGameTime(float game_time, float time_factor);
 
-	void					OnDeviceCreate		();
-	void					OnDeviceDestroy		();
+    void OnDeviceCreate();
+    void OnDeviceDestroy();
 
-	// editor-related
+    // editor-related
 #ifdef _EDITOR
 public:
-	float					ed_from_time		;
-	float					ed_to_time			;
+    float ed_from_time;
+    float ed_to_time;
 public:
-    void					ED_Reload			();
-    float					GetGameTime			(){return fGameTime;}
+    void ED_Reload();
+    float GetGameTime() { return fGameTime; }
 #else // #ifdef _EDITOR
-#	ifdef INGAME_EDITOR
-		float				GetGameTime			(){return fGameTime;}
-#	endif // #ifdef INGAME_EDITOR
+# ifdef INGAME_EDITOR
+    float GetGameTime() { return fGameTime; }
+# endif // #ifdef INGAME_EDITOR
 
-	bool					m_paused;
+    bool m_paused;
 #endif // #ifdef _EDITOR
 
-	CInifile*				m_ambients_config;
-	CInifile*				m_sound_channels_config;
-	CInifile*				m_effects_config;
-	CInifile*				m_suns_config;
-	CInifile*				m_thunderbolt_collections_config;
-	CInifile*				m_thunderbolts_config;
+    CInifile* m_ambients_config;
+    CInifile* m_sound_channels_config;
+    CInifile* m_effects_config;
+    CInifile* m_suns_config;
+    CInifile* m_thunderbolt_collections_config;
+    CInifile* m_thunderbolts_config;
 
 protected:
-	INGAME_EDITOR_VIRTUAL	CEnvDescriptor* create_descriptor	(shared_str const& identifier, CInifile* config);
-	INGAME_EDITOR_VIRTUAL	void load_weathers					();
-	INGAME_EDITOR_VIRTUAL	void load_weather_effects			();
-	INGAME_EDITOR_VIRTUAL	void create_mixer					();
-							void destroy_mixer					();
+    INGAME_EDITOR_VIRTUAL CEnvDescriptor* create_descriptor(shared_str const& identifier, CInifile* config);
+    INGAME_EDITOR_VIRTUAL void load_weathers();
+    INGAME_EDITOR_VIRTUAL void load_weather_effects();
+    INGAME_EDITOR_VIRTUAL void create_mixer();
+    void destroy_mixer();
 
-							void load_level_specific_ambients   ();
+    void load_level_specific_ambients();
 
 public:
-	INGAME_EDITOR_VIRTUAL	SThunderboltDesc* thunderbolt_description		(CInifile& config, shared_str const& section);
-	INGAME_EDITOR_VIRTUAL	SThunderboltCollection* thunderbolt_collection	(CInifile* pIni, CInifile* thunderbolts, LPCSTR section);
-	INGAME_EDITOR_VIRTUAL	SThunderboltCollection* thunderbolt_collection	(xr_vector& collection,  shared_str const& id);
-	INGAME_EDITOR_VIRTUAL	CLensFlareDescriptor*	add_flare				(xr_vector& collection, shared_str const& id);
+    INGAME_EDITOR_VIRTUAL SThunderboltDesc* thunderbolt_description(CInifile& config, shared_str const& section);
+    INGAME_EDITOR_VIRTUAL SThunderboltCollection* thunderbolt_collection(CInifile* pIni, CInifile* thunderbolts, LPCSTR section);
+    INGAME_EDITOR_VIRTUAL SThunderboltCollection* thunderbolt_collection(xr_vector& collection, shared_str const& id);
+    INGAME_EDITOR_VIRTUAL CLensFlareDescriptor* add_flare(xr_vector& collection, shared_str const& id);
 
 public:
-	float						p_var_alt;
-	float						p_var_long;
-	float						p_min_dist;
-	float						p_tilt;
-	float						p_second_prop;
-	float						p_sky_color;
-	float						p_sun_color;
-	float						p_fog_color;
+    float p_var_alt;
+    float p_var_long;
+    float p_min_dist;
+    float p_tilt;
+    float p_second_prop;
+    float p_sky_color;
+    float p_sun_color;
+    float p_fog_color;
 };
 
 #undef INGAME_EDITOR_VIRTUAL
 
-ENGINE_API extern Flags32	psEnvFlags;
-ENGINE_API extern float		psVisDistance;
+ENGINE_API extern Flags32 psEnvFlags;
+ENGINE_API extern float psVisDistance;
 
 #endif //EnvironmentH
\ No newline at end of file
diff --git a/src/xrEngine/Environment_misc.cpp b/src/xrEngine/Environment_misc.cpp
index 91ed675b340..32351540750 100644
--- a/src/xrEngine/Environment_misc.cpp
+++ b/src/xrEngine/Environment_misc.cpp
@@ -12,70 +12,70 @@
 
 #include "securom_api.h"
 
-void CEnvModifier::load	(IReader* fs, u32 version)
+void CEnvModifier::load(IReader* fs, u32 version)
 {
-	use_flags.one					();
-	fs->r_fvector3	(position);
-	radius			= fs->r_float	();
-	power			= fs->r_float	();
-	far_plane		= fs->r_float	();
-	fs->r_fvector3	(fog_color);
-	fog_density		= fs->r_float	();
-	fs->r_fvector3	(ambient);
-	fs->r_fvector3	(sky_color);
-	fs->r_fvector3	(hemi_color);
-
-	if(version>=0x0016)
-	{
-		use_flags.assign(fs->r_u16());
-	}
+    use_flags.one();
+    fs->r_fvector3(position);
+    radius = fs->r_float();
+    power = fs->r_float();
+    far_plane = fs->r_float();
+    fs->r_fvector3(fog_color);
+    fog_density = fs->r_float();
+    fs->r_fvector3(ambient);
+    fs->r_fvector3(sky_color);
+    fs->r_fvector3(hemi_color);
+
+    if (version >= 0x0016)
+    {
+        use_flags.assign(fs->r_u16());
+    }
 }
 
-float	CEnvModifier::sum	(CEnvModifier& M, Fvector3& view)
+float CEnvModifier::sum(CEnvModifier& M, Fvector3& view)
 {
-	float	_dist_sq	=	view.distance_to_sqr(M.position);
-	if (_dist_sq>=(M.radius*M.radius))	
-		return			0;
-
-	float	_att		=	1-_sqrt(_dist_sq)/M.radius;	//[0..1];
-	float	_power		=	M.power*_att;
-	
-
-	if(M.use_flags.test(eViewDist))
-	{
-		far_plane			+=	M.far_plane*_power;
-		use_flags.set		(eViewDist, TRUE);
-	}
-	if(M.use_flags.test(eFogColor))
-	{
-		fog_color.mad		(M.fog_color,_power);
-		use_flags.set		(eFogColor, TRUE);
-	}
-	if(M.use_flags.test(eFogDensity))
-	{
-		fog_density			+=	M.fog_density*_power;
-		use_flags.set		(eFogDensity, TRUE);
-	}
-
-	if(M.use_flags.test(eAmbientColor))
-	{
-		ambient.mad			(M.ambient,_power);
-		use_flags.set		(eAmbientColor, TRUE);
-	}
-
-	if(M.use_flags.test(eSkyColor))
-	{
-		sky_color.mad		(M.sky_color,_power);
-		use_flags.set		(eSkyColor, TRUE);
-	}
-
-	if(M.use_flags.test(eHemiColor))
-	{
-		hemi_color.mad		(M.hemi_color,_power);
-		use_flags.set		(eHemiColor, TRUE);
-	}
-	
-	return				_power;
+    float _dist_sq = view.distance_to_sqr(M.position);
+    if (_dist_sq >= (M.radius*M.radius))
+        return 0;
+
+    float _att = 1 - _sqrt(_dist_sq) / M.radius; //[0..1];
+    float _power = M.power*_att;
+
+
+    if (M.use_flags.test(eViewDist))
+    {
+        far_plane += M.far_plane*_power;
+        use_flags.set(eViewDist, TRUE);
+    }
+    if (M.use_flags.test(eFogColor))
+    {
+        fog_color.mad(M.fog_color, _power);
+        use_flags.set(eFogColor, TRUE);
+    }
+    if (M.use_flags.test(eFogDensity))
+    {
+        fog_density += M.fog_density*_power;
+        use_flags.set(eFogDensity, TRUE);
+    }
+
+    if (M.use_flags.test(eAmbientColor))
+    {
+        ambient.mad(M.ambient, _power);
+        use_flags.set(eAmbientColor, TRUE);
+    }
+
+    if (M.use_flags.test(eSkyColor))
+    {
+        sky_color.mad(M.sky_color, _power);
+        use_flags.set(eSkyColor, TRUE);
+    }
+
+    if (M.use_flags.test(eHemiColor))
+    {
+        hemi_color.mad(M.hemi_color, _power);
+        use_flags.set(eHemiColor, TRUE);
+    }
+
+    return _power;
 }
 
 //-----------------------------------------------------------------------------
@@ -83,682 +83,699 @@ float	CEnvModifier::sum	(CEnvModifier& M, Fvector3& view)
 //-----------------------------------------------------------------------------
 void CEnvAmbient::SSndChannel::load(CInifile& config, LPCSTR sect)
 {
-	m_load_section			= sect;
-
-	m_sound_dist.x		= config.r_float		(m_load_section, "min_distance");
-	m_sound_dist.y		= config.r_float		(m_load_section, "max_distance");
-	m_sound_period.x	= config.r_s32			(m_load_section, "period0");
-	m_sound_period.y	= config.r_s32			(m_load_section, "period1");
-	m_sound_period.z	= config.r_s32			(m_load_section, "period2");
-	m_sound_period.w	= config.r_s32			(m_load_section, "period3");
-
-//	m_sound_period			= config.r_ivector4(sect,"sound_period");
-	R_ASSERT				(m_sound_period.x <= m_sound_period.y && m_sound_period.z <= m_sound_period.w);
-//	m_sound_period.mul		(1000);// now in ms
-//	m_sound_dist			= config.r_fvector2(sect,"sound_dist"); 
-	R_ASSERT2				(m_sound_dist.y > m_sound_dist.x, sect);
-
-	LPCSTR snds				= config.r_string	(sect,"sounds");
-	u32 cnt					= _GetItemCount			(snds);
-	string_path				tmp;
-	R_ASSERT3				(cnt,"sounds empty", sect);
-
-	m_sounds.resize			(cnt);
-
-	for (u32 k=0; k m_sound_dist.x, sect);
+
+    LPCSTR snds = config.r_string(sect, "sounds");
+    u32 cnt = _GetItemCount(snds);
+    string_path tmp;
+    R_ASSERT3(cnt, "sounds empty", sect);
+
+    m_sounds.resize(cnt);
+
+    for (u32 k = 0; k < cnt; ++k)
+    {
+        _GetItem(snds, k, tmp);
+        m_sounds[k].create(tmp, st_Effect, sg_SourceType);
+    }
 }
 
-CEnvAmbient::SEffect* CEnvAmbient::create_effect	(CInifile& config, LPCSTR id)
+CEnvAmbient::SEffect* CEnvAmbient::create_effect(CInifile& config, LPCSTR id)
 {
-	SEffect*					result = xr_new();
-	result->life_time			= iFloor(config.r_float(id,"life_time")*1000.f);
-	result->particles			= config.r_string	(id,"particles");		
-	VERIFY						(result->particles.size());
-	result->offset				= config.r_fvector3	(id,"offset");
-	result->wind_gust_factor	= config.r_float(id,"wind_gust_factor");
-	
-	if (config.line_exist(id,"sound"))
-		result->sound.create	(config.r_string(id,"sound"),st_Effect,sg_SourceType);
-
-	if (config.line_exist(id,"wind_blast_strength")) {
-		result->wind_blast_strength		= config.r_float(id,"wind_blast_strength");
-		result->wind_blast_direction.setHP	(deg2rad(config.r_float(id,"wind_blast_longitude")), 0.f);
-		result->wind_blast_in_time		= config.r_float(id,"wind_blast_in_time");
-		result->wind_blast_out_time		= config.r_float(id,"wind_blast_out_time");
-		return							(result);
-	}
-
-	result->wind_blast_strength			= 0.f;
-	result->wind_blast_direction.set	(0.f, 0.f, 1.f);
-	result->wind_blast_in_time			= 0.f;
-	result->wind_blast_out_time			= 0.f;
-
-	return								(result);
+    SEffect* result = xr_new();
+    result->life_time = iFloor(config.r_float(id, "life_time")*1000.f);
+    result->particles = config.r_string(id, "particles");
+    VERIFY(result->particles.size());
+    result->offset = config.r_fvector3(id, "offset");
+    result->wind_gust_factor = config.r_float(id, "wind_gust_factor");
+
+    if (config.line_exist(id, "sound"))
+        result->sound.create(config.r_string(id, "sound"), st_Effect, sg_SourceType);
+
+    if (config.line_exist(id, "wind_blast_strength"))
+    {
+        result->wind_blast_strength = config.r_float(id, "wind_blast_strength");
+        result->wind_blast_direction.setHP(deg2rad(config.r_float(id, "wind_blast_longitude")), 0.f);
+        result->wind_blast_in_time = config.r_float(id, "wind_blast_in_time");
+        result->wind_blast_out_time = config.r_float(id, "wind_blast_out_time");
+        return (result);
+    }
+
+    result->wind_blast_strength = 0.f;
+    result->wind_blast_direction.set(0.f, 0.f, 1.f);
+    result->wind_blast_in_time = 0.f;
+    result->wind_blast_out_time = 0.f;
+
+    return (result);
 }
 
-CEnvAmbient::SSndChannel* CEnvAmbient::create_sound_channel	(CInifile& config, LPCSTR id)
+CEnvAmbient::SSndChannel* CEnvAmbient::create_sound_channel(CInifile& config, LPCSTR id)
 {
-	SSndChannel*			result = xr_new();
-	result->load			(config, id);
-	return					(result);
+    SSndChannel* result = xr_new();
+    result->load(config, id);
+    return (result);
 }
 
-CEnvAmbient::~CEnvAmbient						()
+CEnvAmbient::~CEnvAmbient()
 {
-	destroy					();
+    destroy();
 }
 
-void CEnvAmbient::destroy ()
+void CEnvAmbient::destroy()
 {
-	delete_data				(m_effects);
-	delete_data				(m_sound_channels);
+    delete_data(m_effects);
+    delete_data(m_sound_channels);
 }
 
-void CEnvAmbient::load( 
-		CInifile& ambients_config,
-		CInifile& sound_channels_config,
-		CInifile& effects_config,
-		const shared_str& sect
-	)
+void CEnvAmbient::load(
+    CInifile& ambients_config,
+    CInifile& sound_channels_config,
+    CInifile& effects_config,
+    const shared_str& sect
+    )
 {
-	m_ambients_config_filename = ambients_config.fname();
-	m_load_section		= sect;
-	string_path			tmp;
-	
-	// sounds
-	LPCSTR channels			= ambients_config.r_string	(sect,"sound_channels");
-	u32 cnt					= _GetItemCount(channels);
-//	R_ASSERT3				(cnt,"sound_channels empty", sect.c_str());
-	m_sound_channels.resize	(cnt);
-
-	for (u32 i=0; i2 || C.y<0 || C.y>2 || C.z<0 || C.z>2)	{ Msg("! Invalid '%s' in env-section '%s'",#C,m_identifier.c_str());}
-void CEnvDescriptor::load	(CEnvironment& environment, CInifile& config)
+#define C_CHECK(C) if (C.x<0 || C.x>2 || C.y<0 || C.y>2 || C.z<0 || C.z>2) { Msg("! Invalid '%s' in env-section '%s'",#C,m_identifier.c_str());}
+void CEnvDescriptor::load(CEnvironment& environment, CInifile& config)
 {
-	Ivector3 tm				={0,0,0};
-	sscanf					(m_identifier.c_str(),"%d:%d:%d",&tm.x,&tm.y,&tm.z);
-	R_ASSERT3				((tm.x>=0)&&(tm.x<24)&&(tm.y>=0)&&(tm.y<60)&&(tm.z>=0)&&(tm.z<60),"Incorrect weather time",m_identifier.c_str());
-	exec_time				= tm.x*3600.f+tm.y*60.f+tm.z;
-	exec_time_loaded		= exec_time;
-	string_path				st,st_env;
-	xr_strcpy				(st,config.r_string	(m_identifier.c_str(),"sky_texture"));
-	strconcat				(sizeof(st_env),st_env,st,"#small"		);
-	sky_texture_name		= st;
-	sky_texture_env_name	= st_env;
-	clouds_texture_name		= config.r_string	(m_identifier.c_str(),"clouds_texture");
-	LPCSTR	cldclr			= config.r_string	(m_identifier.c_str(),"clouds_color");
-	float	multiplier		= 0, save=0;
-	sscanf					(cldclr,"%f,%f,%f,%f,%f",&clouds_color.x,&clouds_color.y,&clouds_color.z,&clouds_color.w,&multiplier);
-	save=clouds_color.w;	clouds_color.mul		(.5f*multiplier);		
-	clouds_color.w			= save; 
-	
-	sky_color				= config.r_fvector3	(m_identifier.c_str(),"sky_color");		
-	
-	if (config.line_exist(m_identifier.c_str(),"sky_rotation"))	sky_rotation	= deg2rad(config.r_float(m_identifier.c_str(),"sky_rotation"));
-	else											sky_rotation	= 0;
-	far_plane				= config.r_float	(m_identifier.c_str(),"far_plane");
-	fog_color				= config.r_fvector3	(m_identifier.c_str(),"fog_color");
-	fog_density				= config.r_float	(m_identifier.c_str(),"fog_density");
-	fog_distance			= config.r_float	(m_identifier.c_str(),"fog_distance");
-	rain_density			= config.r_float	(m_identifier.c_str(),"rain_density");		clamp(rain_density,0.f,1.f);
-	rain_color				= config.r_fvector3	(m_identifier.c_str(),"rain_color");            
-	wind_velocity			= config.r_float	(m_identifier.c_str(),"wind_velocity");
-	wind_direction			= deg2rad(config.r_float(m_identifier.c_str(),"wind_direction"));
-	ambient					= config.r_fvector3	(m_identifier.c_str(),"ambient_color");
-	hemi_color				= config.r_fvector4	(m_identifier.c_str(),"hemisphere_color");
-	sun_color				= config.r_fvector3	(m_identifier.c_str(),"sun_color");
-//	if (config.line_exist(m_identifier.c_str(),"sun_altitude"))
-		sun_dir.setHP			(
-			deg2rad(config.r_float(m_identifier.c_str(),"sun_altitude")),
-			deg2rad(config.r_float(m_identifier.c_str(),"sun_longitude"))
-		);
-	R_ASSERT				( _valid(sun_dir) );
-//	else
-//		sun_dir.setHP			(
-//			deg2rad(config.r_fvector2(m_identifier.c_str(),"sun_dir").y),
-//			deg2rad(config.r_fvector2(m_identifier.c_str(),"sun_dir").x)
-//		);
-	VERIFY2					(sun_dir.y < 0, "Invalid sun direction settings while loading");
-
-	lens_flare_id			= environment.eff_LensFlare->AppendDef(environment, environment.m_suns_config, config.r_string(m_identifier.c_str(),"sun"));
-	tb_id					= environment.eff_Thunderbolt->AppendDef(environment, environment.m_thunderbolt_collections_config, environment.m_thunderbolts_config, config.r_string(m_identifier.c_str(),"thunderbolt_collection"));
-	bolt_period				= (tb_id.size())?config.r_float	(m_identifier.c_str(),"thunderbolt_period"):0.f;
-	bolt_duration			= (tb_id.size())?config.r_float	(m_identifier.c_str(),"thunderbolt_duration"):0.f;
-	env_ambient				= config.line_exist(m_identifier.c_str(),"ambient")?environment.AppendEnvAmb	(config.r_string(m_identifier.c_str(),"ambient")):0;
-
-	if (config.line_exist(m_identifier.c_str(),"sun_shafts_intensity"))
-		m_fSunShaftsIntensity = config.r_float(m_identifier.c_str(),"sun_shafts_intensity");
-
-	if (config.line_exist(m_identifier.c_str(),"water_intensity"))
-		m_fWaterIntensity = config.r_float(m_identifier.c_str(),"water_intensity");
-
-	C_CHECK					(clouds_color);
-	C_CHECK					(sky_color	);
-	C_CHECK					(fog_color	);
-	C_CHECK					(rain_color	);
-	C_CHECK					(ambient	);
-	C_CHECK					(hemi_color	);
-	C_CHECK					(sun_color	);
-	on_device_create		();
+    Ivector3 tm = {0, 0, 0};
+    sscanf(m_identifier.c_str(), "%d:%d:%d", &tm.x, &tm.y, &tm.z);
+    R_ASSERT3((tm.x >= 0) && (tm.x < 24) && (tm.y >= 0) && (tm.y < 60) && (tm.z >= 0) && (tm.z < 60), "Incorrect weather time", m_identifier.c_str());
+    exec_time = tm.x*3600.f + tm.y*60.f + tm.z;
+    exec_time_loaded = exec_time;
+    string_path st, st_env;
+    xr_strcpy(st, config.r_string(m_identifier.c_str(), "sky_texture"));
+    strconcat(sizeof(st_env), st_env, st, "#small");
+    sky_texture_name = st;
+    sky_texture_env_name = st_env;
+    clouds_texture_name = config.r_string(m_identifier.c_str(), "clouds_texture");
+    LPCSTR cldclr = config.r_string(m_identifier.c_str(), "clouds_color");
+    float multiplier = 0, save = 0;
+    sscanf(cldclr, "%f,%f,%f,%f,%f", &clouds_color.x, &clouds_color.y, &clouds_color.z, &clouds_color.w, &multiplier);
+    save = clouds_color.w;
+    clouds_color.mul(.5f*multiplier);
+    clouds_color.w = save;
+
+    sky_color = config.r_fvector3(m_identifier.c_str(), "sky_color");
+
+    if (config.line_exist(m_identifier.c_str(), "sky_rotation")) sky_rotation = deg2rad(config.r_float(m_identifier.c_str(), "sky_rotation"));
+    else sky_rotation = 0;
+    far_plane = config.r_float(m_identifier.c_str(), "far_plane");
+    fog_color = config.r_fvector3(m_identifier.c_str(), "fog_color");
+    fog_density = config.r_float(m_identifier.c_str(), "fog_density");
+    fog_distance = config.r_float(m_identifier.c_str(), "fog_distance");
+    rain_density = config.r_float(m_identifier.c_str(), "rain_density");
+    clamp(rain_density, 0.f, 1.f);
+    rain_color = config.r_fvector3(m_identifier.c_str(), "rain_color");
+    wind_velocity = config.r_float(m_identifier.c_str(), "wind_velocity");
+    wind_direction = deg2rad(config.r_float(m_identifier.c_str(), "wind_direction"));
+    ambient = config.r_fvector3(m_identifier.c_str(), "ambient_color");
+    hemi_color = config.r_fvector4(m_identifier.c_str(), "hemisphere_color");
+    sun_color = config.r_fvector3(m_identifier.c_str(), "sun_color");
+    // if (config.line_exist(m_identifier.c_str(),"sun_altitude"))
+    sun_dir.setHP(
+        deg2rad(config.r_float(m_identifier.c_str(), "sun_altitude")),
+        deg2rad(config.r_float(m_identifier.c_str(), "sun_longitude"))
+        );
+    R_ASSERT(_valid(sun_dir));
+    // else
+    // sun_dir.setHP (
+    // deg2rad(config.r_fvector2(m_identifier.c_str(),"sun_dir").y),
+    // deg2rad(config.r_fvector2(m_identifier.c_str(),"sun_dir").x)
+    // );
+    VERIFY2(sun_dir.y < 0, "Invalid sun direction settings while loading");
+
+    lens_flare_id = environment.eff_LensFlare->AppendDef(environment, environment.m_suns_config, config.r_string(m_identifier.c_str(), "sun"));
+    tb_id = environment.eff_Thunderbolt->AppendDef(environment, environment.m_thunderbolt_collections_config, environment.m_thunderbolts_config, config.r_string(m_identifier.c_str(), "thunderbolt_collection"));
+    bolt_period = (tb_id.size()) ? config.r_float(m_identifier.c_str(), "thunderbolt_period") : 0.f;
+    bolt_duration = (tb_id.size()) ? config.r_float(m_identifier.c_str(), "thunderbolt_duration") : 0.f;
+    env_ambient = config.line_exist(m_identifier.c_str(), "ambient") ? environment.AppendEnvAmb(config.r_string(m_identifier.c_str(), "ambient")) : 0;
+
+    if (config.line_exist(m_identifier.c_str(), "sun_shafts_intensity"))
+        m_fSunShaftsIntensity = config.r_float(m_identifier.c_str(), "sun_shafts_intensity");
+
+    if (config.line_exist(m_identifier.c_str(), "water_intensity"))
+        m_fWaterIntensity = config.r_float(m_identifier.c_str(), "water_intensity");
+
+    C_CHECK(clouds_color);
+    C_CHECK(sky_color);
+    C_CHECK(fog_color);
+    C_CHECK(rain_color);
+    C_CHECK(ambient);
+    C_CHECK(hemi_color);
+    C_CHECK(sun_color);
+    on_device_create();
 }
 
-void CEnvDescriptor::on_device_create	()
+void CEnvDescriptor::on_device_create()
 {
-	m_pDescriptor->OnDeviceCreate(*this);
-	/*
-	if (sky_texture_name.size())	
-		sky_texture.create		(sky_texture_name.c_str());
+    m_pDescriptor->OnDeviceCreate(*this);
+    /*
+    if (sky_texture_name.size())
+    sky_texture.create (sky_texture_name.c_str());
 
-	if (sky_texture_env_name.size())
-		sky_texture_env.create	(sky_texture_env_name.c_str());
+    if (sky_texture_env_name.size())
+    sky_texture_env.create (sky_texture_env_name.c_str());
 
-	if (clouds_texture_name.size())	
-		clouds_texture.create	(clouds_texture_name.c_str());
-		*/
+    if (clouds_texture_name.size())
+    clouds_texture.create (clouds_texture_name.c_str());
+    */
 }
 
-void CEnvDescriptor::on_device_destroy	()
+void CEnvDescriptor::on_device_destroy()
 {
-	m_pDescriptor->OnDeviceDestroy();
-	/*
-	sky_texture.destroy		();
-	sky_texture_env.destroy	();
-	clouds_texture.destroy	();
-	*/
+    m_pDescriptor->OnDeviceDestroy();
+    /*
+    sky_texture.destroy ();
+    sky_texture_env.destroy ();
+    clouds_texture.destroy ();
+    */
 }
 
 //-----------------------------------------------------------------------------
 // Environment Mixer
 //-----------------------------------------------------------------------------
 CEnvDescriptorMixer::CEnvDescriptorMixer(shared_str const& identifier) :
-	CEnvDescriptor	(identifier)
+CEnvDescriptor(identifier)
 {
 }
 
 void CEnvDescriptorMixer::destroy()
 {
-	m_pDescriptorMixer->Destroy();
-	/*
-	sky_r_textures.clear		();
-	sky_r_textures_env.clear	();
-	clouds_r_textures.clear		();
-	*/
-
-	//	Reuse existing code
-	on_device_destroy();
-/*
-	sky_texture.destroy			();
-	sky_texture_env.destroy		();
-	clouds_texture.destroy		();
-	*/
+    m_pDescriptorMixer->Destroy();
+    /*
+    sky_r_textures.clear ();
+    sky_r_textures_env.clear ();
+    clouds_r_textures.clear ();
+    */
+
+    // Reuse existing code
+    on_device_destroy();
+    /*
+     sky_texture.destroy ();
+     sky_texture_env.destroy ();
+     clouds_texture.destroy ();
+     */
 }
 
-void CEnvDescriptorMixer::clear	()
+void CEnvDescriptorMixer::clear()
 {
-	m_pDescriptorMixer->Clear();
-	/*
-	std::pair	zero = mk_pair(u32(0),ref_texture(0));
-	sky_r_textures.clear		();
-	sky_r_textures.push_back	(zero);
-	sky_r_textures.push_back	(zero);
-	sky_r_textures.push_back	(zero);
-
-	sky_r_textures_env.clear	();
-	sky_r_textures_env.push_back(zero);
-	sky_r_textures_env.push_back(zero);
-	sky_r_textures_env.push_back(zero);
-
-	clouds_r_textures.clear		();
-	clouds_r_textures.push_back	(zero);
-	clouds_r_textures.push_back	(zero);
-	clouds_r_textures.push_back	(zero);
-	*/
+    m_pDescriptorMixer->Clear();
+    /*
+    std::pair zero = mk_pair(u32(0),ref_texture(0));
+    sky_r_textures.clear ();
+    sky_r_textures.push_back (zero);
+    sky_r_textures.push_back (zero);
+    sky_r_textures.push_back (zero);
+
+    sky_r_textures_env.clear ();
+    sky_r_textures_env.push_back(zero);
+    sky_r_textures_env.push_back(zero);
+    sky_r_textures_env.push_back(zero);
+
+    clouds_r_textures.clear ();
+    clouds_r_textures.push_back (zero);
+    clouds_r_textures.push_back (zero);
+    clouds_r_textures.push_back (zero);
+    */
 }
 
 int get_ref_count(IUnknown* ii);
 
-void CEnvDescriptorMixer::lerp	(CEnvironment* , CEnvDescriptor& A, CEnvDescriptor& B, float f, CEnvModifier& Mdf, float modifier_power)
+void CEnvDescriptorMixer::lerp(CEnvironment*, CEnvDescriptor& A, CEnvDescriptor& B, float f, CEnvModifier& Mdf, float modifier_power)
 {
-	float	modif_power		=	1.f/(modifier_power+1);	// the environment itself
-	float	fi				=	1-f;
-
-	m_pDescriptorMixer->lerp(&*A.m_pDescriptor, &*B.m_pDescriptor);
-	/*
-	sky_r_textures.clear		();
-	sky_r_textures.push_back	(mk_pair(0,A.sky_texture));
-	sky_r_textures.push_back	(mk_pair(1,B.sky_texture));
-
-	sky_r_textures_env.clear	();
-
-	sky_r_textures_env.push_back(mk_pair(0,A.sky_texture_env));
-	sky_r_textures_env.push_back(mk_pair(1,B.sky_texture_env));
-
-	clouds_r_textures.clear		();
-	clouds_r_textures.push_back	(mk_pair(0,A.clouds_texture));
-	clouds_r_textures.push_back	(mk_pair(1,B.clouds_texture));
-	*/
-
-	weight					=	f;
-
-	clouds_color.lerp		(A.clouds_color,B.clouds_color,f);
-
-	sky_rotation			=	(fi*A.sky_rotation + f*B.sky_rotation);
-
-//.	far_plane				=	(fi*A.far_plane + f*B.far_plane + Mdf.far_plane)*psVisDistance*modif_power;
-	if(Mdf.use_flags.test(eViewDist))
-		far_plane				=	(fi*A.far_plane + f*B.far_plane + Mdf.far_plane)*psVisDistance*modif_power;
-	else
-		far_plane				=	(fi*A.far_plane + f*B.far_plane)*psVisDistance;
-	
-//.	fog_color.lerp			(A.fog_color,B.fog_color,f).add(Mdf.fog_color).mul(modif_power);
-	fog_color.lerp			(A.fog_color,B.fog_color,f);
-	if(Mdf.use_flags.test(eFogColor))
-		fog_color.add(Mdf.fog_color).mul(modif_power);
-
-//.	fog_density				=	(fi*A.fog_density + f*B.fog_density + Mdf.fog_density)*modif_power;
-	fog_density				=	(fi*A.fog_density + f*B.fog_density);
-	if(Mdf.use_flags.test(eFogDensity))
-	{
-		fog_density			+= Mdf.fog_density;
-		fog_density			*= modif_power;
-	}
-
-	fog_distance			=	(fi*A.fog_distance + f*B.fog_distance);
-	fog_near				=	(1.0f - fog_density)*0.85f * fog_distance;
-	fog_far					=	0.99f * fog_distance;
-	
-	rain_density			=	fi*A.rain_density + f*B.rain_density;
-	rain_color.lerp			(A.rain_color,B.rain_color,f);
-	bolt_period				=	fi*A.bolt_period + f*B.bolt_period;
-	bolt_duration			=	fi*A.bolt_duration + f*B.bolt_duration;
-	// wind
-	wind_velocity			=	fi*A.wind_velocity + f*B.wind_velocity;
-	wind_direction			=	fi*A.wind_direction + f*B.wind_direction;
-
-	m_fSunShaftsIntensity	=	fi*A.m_fSunShaftsIntensity + f*B.m_fSunShaftsIntensity;
-	m_fWaterIntensity		=	fi*A.m_fWaterIntensity + f*B.m_fWaterIntensity;
-
-	// colors
-//.	sky_color.lerp			(A.sky_color,B.sky_color,f).add(Mdf.sky_color).mul(modif_power);
-	sky_color.lerp			(A.sky_color,B.sky_color,f);
-	if(Mdf.use_flags.test(eSkyColor))
-		sky_color.add(Mdf.sky_color).mul(modif_power);
-
-//.	ambient.lerp			(A.ambient,B.ambient,f).add(Mdf.ambient).mul(modif_power);
-	ambient.lerp			(A.ambient,B.ambient,f);
-	if(Mdf.use_flags.test(eAmbientColor))
-		ambient.add(Mdf.ambient).mul(modif_power);
-
-	hemi_color.lerp			(A.hemi_color,B.hemi_color,f);
-
-	if(Mdf.use_flags.test(eHemiColor))
-	{
-		hemi_color.x			+= Mdf.hemi_color.x;
-		hemi_color.y			+= Mdf.hemi_color.y; 
-		hemi_color.z			+= Mdf.hemi_color.z;
-		hemi_color.x			*= modif_power;
-		hemi_color.y			*= modif_power;
-		hemi_color.z			*= modif_power;
-	}
-
-	sun_color.lerp			(A.sun_color,B.sun_color,f);
-
-	R_ASSERT				( _valid(A.sun_dir) );
-	R_ASSERT				( _valid(B.sun_dir) );
-	sun_dir.lerp			(A.sun_dir,B.sun_dir,f).normalize();
-	R_ASSERT				( _valid(sun_dir) );
-
-	VERIFY2					(sun_dir.y<0,"Invalid sun direction settings while lerp");}
+    float modif_power = 1.f / (modifier_power + 1); // the environment itself
+    float fi = 1 - f;
+
+    m_pDescriptorMixer->lerp(&*A.m_pDescriptor, &*B.m_pDescriptor);
+    /*
+    sky_r_textures.clear ();
+    sky_r_textures.push_back (mk_pair(0,A.sky_texture));
+    sky_r_textures.push_back (mk_pair(1,B.sky_texture));
+
+    sky_r_textures_env.clear ();
+
+    sky_r_textures_env.push_back(mk_pair(0,A.sky_texture_env));
+    sky_r_textures_env.push_back(mk_pair(1,B.sky_texture_env));
+
+    clouds_r_textures.clear ();
+    clouds_r_textures.push_back (mk_pair(0,A.clouds_texture));
+    clouds_r_textures.push_back (mk_pair(1,B.clouds_texture));
+    */
+
+    weight = f;
+
+    clouds_color.lerp(A.clouds_color, B.clouds_color, f);
+
+    sky_rotation = (fi*A.sky_rotation + f*B.sky_rotation);
+
+    //. far_plane = (fi*A.far_plane + f*B.far_plane + Mdf.far_plane)*psVisDistance*modif_power;
+    if (Mdf.use_flags.test(eViewDist))
+        far_plane = (fi*A.far_plane + f*B.far_plane + Mdf.far_plane)*psVisDistance*modif_power;
+    else
+        far_plane = (fi*A.far_plane + f*B.far_plane)*psVisDistance;
+
+    //. fog_color.lerp (A.fog_color,B.fog_color,f).add(Mdf.fog_color).mul(modif_power);
+    fog_color.lerp(A.fog_color, B.fog_color, f);
+    if (Mdf.use_flags.test(eFogColor))
+        fog_color.add(Mdf.fog_color).mul(modif_power);
+
+    //. fog_density = (fi*A.fog_density + f*B.fog_density + Mdf.fog_density)*modif_power;
+    fog_density = (fi*A.fog_density + f*B.fog_density);
+    if (Mdf.use_flags.test(eFogDensity))
+    {
+        fog_density += Mdf.fog_density;
+        fog_density *= modif_power;
+    }
+
+    fog_distance = (fi*A.fog_distance + f*B.fog_distance);
+    fog_near = (1.0f - fog_density)*0.85f * fog_distance;
+    fog_far = 0.99f * fog_distance;
+
+    rain_density = fi*A.rain_density + f*B.rain_density;
+    rain_color.lerp(A.rain_color, B.rain_color, f);
+    bolt_period = fi*A.bolt_period + f*B.bolt_period;
+    bolt_duration = fi*A.bolt_duration + f*B.bolt_duration;
+    // wind
+    wind_velocity = fi*A.wind_velocity + f*B.wind_velocity;
+    wind_direction = fi*A.wind_direction + f*B.wind_direction;
+
+    m_fSunShaftsIntensity = fi*A.m_fSunShaftsIntensity + f*B.m_fSunShaftsIntensity;
+    m_fWaterIntensity = fi*A.m_fWaterIntensity + f*B.m_fWaterIntensity;
+
+    // colors
+    //. sky_color.lerp (A.sky_color,B.sky_color,f).add(Mdf.sky_color).mul(modif_power);
+    sky_color.lerp(A.sky_color, B.sky_color, f);
+    if (Mdf.use_flags.test(eSkyColor))
+        sky_color.add(Mdf.sky_color).mul(modif_power);
+
+    //. ambient.lerp (A.ambient,B.ambient,f).add(Mdf.ambient).mul(modif_power);
+    ambient.lerp(A.ambient, B.ambient, f);
+    if (Mdf.use_flags.test(eAmbientColor))
+        ambient.add(Mdf.ambient).mul(modif_power);
+
+    hemi_color.lerp(A.hemi_color, B.hemi_color, f);
+
+    if (Mdf.use_flags.test(eHemiColor))
+    {
+        hemi_color.x += Mdf.hemi_color.x;
+        hemi_color.y += Mdf.hemi_color.y;
+        hemi_color.z += Mdf.hemi_color.z;
+        hemi_color.x *= modif_power;
+        hemi_color.y *= modif_power;
+        hemi_color.z *= modif_power;
+    }
+
+    sun_color.lerp(A.sun_color, B.sun_color, f);
+
+    R_ASSERT(_valid(A.sun_dir));
+    R_ASSERT(_valid(B.sun_dir));
+    sun_dir.lerp(A.sun_dir, B.sun_dir, f).normalize();
+    R_ASSERT(_valid(sun_dir));
+
+    VERIFY2(sun_dir.y < 0, "Invalid sun direction settings while lerp");
+}
 
 //-----------------------------------------------------------------------------
 // Environment IO
 //-----------------------------------------------------------------------------
-CEnvAmbient* CEnvironment::AppendEnvAmb		(const shared_str& sect)
+CEnvAmbient* CEnvironment::AppendEnvAmb(const shared_str& sect)
 {
-	for (EnvAmbVecIt it=Ambients.begin(); it!=Ambients.end(); it++)
-		if ((*it)->name().equal(sect))
-			return						(*it);
-
-	Ambients.push_back		(xr_new());
-	Ambients.back()->load	(
-		*m_ambients_config,
-		*m_sound_channels_config,
-		*m_effects_config,
-		sect
-	);
-	return					(Ambients.back());
+    for (EnvAmbVecIt it = Ambients.begin(); it != Ambients.end(); it++)
+        if ((*it)->name().equal(sect))
+            return (*it);
+
+    Ambients.push_back(xr_new());
+    Ambients.back()->load(
+        *m_ambients_config,
+        *m_sound_channels_config,
+        *m_effects_config,
+        sect
+        );
+    return (Ambients.back());
 }
 
-void	CEnvironment::mods_load			()
+void CEnvironment::mods_load()
 {
-	Modifiers.clear_and_free			();
-	string_path							path;
-	if (FS.exist(path,"$level$","level.env_mod"))	
-	{
-		IReader*	fs	= FS.r_open		(path);
-		u32			id	= 0;
-		u32 ver		= 0x0015;
-		u32 sz;
-
-		while( 0!=(sz=fs->find_chunk(id)) )	
-		{
-			if(id==0 && sz==sizeof(u32))
-			{
-				ver				= fs->r_u32();
-			}else
-			{
-				CEnvModifier		E;
-				E.load				(fs, ver);
-				Modifiers.push_back	(E);
-			}
-			id					++;
-		}
-		FS.r_close	(fs);
-	}
-
-	load_level_specific_ambients ();
+    Modifiers.clear_and_free();
+    string_path path;
+    if (FS.exist(path, "$level$", "level.env_mod"))
+    {
+        IReader* fs = FS.r_open(path);
+        u32 id = 0;
+        u32 ver = 0x0015;
+        u32 sz;
+
+        while (0 != (sz = fs->find_chunk(id)))
+        {
+            if (id == 0 && sz == sizeof(u32))
+            {
+                ver = fs->r_u32();
+            }
+            else
+            {
+                CEnvModifier E;
+                E.load(fs, ver);
+                Modifiers.push_back(E);
+            }
+            id++;
+        }
+        FS.r_close(fs);
+    }
+
+    load_level_specific_ambients();
 }
 
-void	CEnvironment::mods_unload		()
+void CEnvironment::mods_unload()
 {
-	Modifiers.clear_and_free			();
+    Modifiers.clear_and_free();
 }
 
-void    CEnvironment::load_level_specific_ambients ()
+void CEnvironment::load_level_specific_ambients()
 {
-	SECUROM_MARKER_PERFORMANCE_ON(13)
+    SECUROM_MARKER_PERFORMANCE_ON(13)
 
-	const shared_str level_name = g_pGameLevel->name();
+        const shared_str level_name = g_pGameLevel->name();
 
-	string_path path;
-	strconcat(sizeof(path), path, "environment\\ambients\\", level_name.c_str(), ".ltx");
+    string_path path;
+    strconcat(sizeof(path), path, "environment\\ambients\\", level_name.c_str(), ".ltx");
 
-	string_path full_path;
-	CInifile* level_ambients = xr_new(
-			FS.update_path(full_path, "$game_config$", path),
-			TRUE,
-			TRUE,
-			FALSE);
+    string_path full_path;
+    CInifile* level_ambients = xr_new(
+        FS.update_path(full_path, "$game_config$", path),
+        TRUE,
+        TRUE,
+        FALSE);
 
-	for ( EnvAmbVecIt I=Ambients.begin(), E=Ambients.end(); I!=E; ++I )
-	{
-		CEnvAmbient* ambient = *I;
+    for (EnvAmbVecIt I = Ambients.begin(), E = Ambients.end(); I != E; ++I)
+    {
+        CEnvAmbient* ambient = *I;
 
-		shared_str section_name = ambient->name();
+        shared_str section_name = ambient->name();
 
-		// choose a source ini file
-		CInifile* source = (level_ambients && level_ambients->section_exist(section_name)) ? 
-							level_ambients : m_ambients_config;
+        // choose a source ini file
+        CInifile* source = (level_ambients && level_ambients->section_exist(section_name)) ?
+        level_ambients : m_ambients_config;
 
 
-		// check and reload if needed
-		if ( xr_strcmp( ambient->get_ambients_config_filename().c_str(), source->fname() ) )
-		{
-			ambient->destroy();
-			ambient->load(*source, *m_sound_channels_config, *m_effects_config, section_name);
-		}
-	}
+        // check and reload if needed
+        if (xr_strcmp(ambient->get_ambients_config_filename().c_str(), source->fname()))
+        {
+            ambient->destroy();
+            ambient->load(*source, *m_sound_channels_config, *m_effects_config, section_name);
+        }
+    }
 
-	xr_delete(level_ambients);
+    xr_delete(level_ambients);
 
-	SECUROM_MARKER_PERFORMANCE_OFF(13)
+    SECUROM_MARKER_PERFORMANCE_OFF(13)
 }
 
-CEnvDescriptor* CEnvironment::create_descriptor	(shared_str const& identifier, CInifile* config)
+CEnvDescriptor* CEnvironment::create_descriptor(shared_str const& identifier, CInifile* config)
 {
-	CEnvDescriptor*	result = xr_new(identifier);
-	if (config)
-		result->load(*this, *config);
-	return			(result);
+    CEnvDescriptor* result = xr_new(identifier);
+    if (config)
+        result->load(*this, *config);
+    return (result);
 }
 
-void CEnvironment::load_weathers		()
+void CEnvironment::load_weathers()
 {
-	if (!WeatherCycles.empty())
-		return;
+    if (!WeatherCycles.empty())
+        return;
 
-	typedef xr_vector		file_list_type;
-	file_list_type*					file_list = FS.file_list_open("$game_weathers$","");
-	VERIFY							(file_list);
+    typedef xr_vector file_list_type;
+    file_list_type* file_list = FS.file_list_open("$game_weathers$", "");
+    VERIFY(file_list);
     xr_string id;
-	file_list_type::const_iterator	i = file_list->begin();
-	file_list_type::const_iterator	e = file_list->end();
-	for ( ; i != e; ++i) {
-		u32							length = xr_strlen(*i);
-		VERIFY						(length >= 4);
-		VERIFY						((*i)[length - 4] == '.');
-		VERIFY						((*i)[length - 3] == 'l');
-		VERIFY						((*i)[length - 2] == 't');
-		VERIFY						((*i)[length - 1] == 'x');
-        id.assign(*i, length-4);
-		EnvVec& env					= WeatherCycles[id.c_str()];
-
-		string_path					file_name;
-		FS.update_path				(file_name, "$game_weathers$", id.c_str());
-		xr_strcat					(file_name, ".ltx");
-		CInifile*					config = CInifile::Create(file_name);
-
-		typedef CInifile::Root		sections_type;
-		sections_type&				sections = config->sections();
-
-		env.reserve					(sections.size());
-
-		sections_type::const_iterator	i = sections.begin();
-		sections_type::const_iterator	e = sections.end();
-		for ( ; i != e; ++i) {
-			CEnvDescriptor*			object = create_descriptor((*i)->Name, config);
-			env.push_back			(object);
-		}
-
-		CInifile::Destroy			(config);
-	}
-
-	FS.file_list_close				(file_list);
-
-	// sorting weather envs
-	EnvsMapIt _I=WeatherCycles.begin();
-	EnvsMapIt _E=WeatherCycles.end();
-	for (; _I!=_E; _I++){
-		R_ASSERT3	(_I->second.size()>1,"Environment in weather must >=2",*_I->first);
-		std::sort(_I->second.begin(),_I->second.end(),sort_env_etl_pred);
-	}
-	R_ASSERT2	(!WeatherCycles.empty(),"Empty weathers.");
-	SetWeather	((*WeatherCycles.begin()).first.c_str());
+    file_list_type::const_iterator i = file_list->begin();
+    file_list_type::const_iterator e = file_list->end();
+    for (; i != e; ++i)
+    {
+        u32 length = xr_strlen(*i);
+        VERIFY(length >= 4);
+        VERIFY((*i)[length - 4] == '.');
+        VERIFY((*i)[length - 3] == 'l');
+        VERIFY((*i)[length - 2] == 't');
+        VERIFY((*i)[length - 1] == 'x');
+        id.assign(*i, length - 4);
+        EnvVec& env = WeatherCycles[id.c_str()];
+
+        string_path file_name;
+        FS.update_path(file_name, "$game_weathers$", id.c_str());
+        xr_strcat(file_name, ".ltx");
+        CInifile* config = CInifile::Create(file_name);
+
+        typedef CInifile::Root sections_type;
+        sections_type& sections = config->sections();
+
+        env.reserve(sections.size());
+
+        sections_type::const_iterator i = sections.begin();
+        sections_type::const_iterator e = sections.end();
+        for (; i != e; ++i)
+        {
+            CEnvDescriptor* object = create_descriptor((*i)->Name, config);
+            env.push_back(object);
+        }
+
+        CInifile::Destroy(config);
+    }
+
+    FS.file_list_close(file_list);
+
+    // sorting weather envs
+    EnvsMapIt _I = WeatherCycles.begin();
+    EnvsMapIt _E = WeatherCycles.end();
+    for (; _I != _E; _I++)
+    {
+        R_ASSERT3(_I->second.size() > 1, "Environment in weather must >=2", *_I->first);
+        std::sort(_I->second.begin(), _I->second.end(), sort_env_etl_pred);
+    }
+    R_ASSERT2(!WeatherCycles.empty(), "Empty weathers.");
+    SetWeather((*WeatherCycles.begin()).first.c_str());
 }
 
-void CEnvironment::load_weather_effects	()
+void CEnvironment::load_weather_effects()
 {
-	if (!WeatherFXs.empty())
-		return;
+    if (!WeatherFXs.empty())
+        return;
 
-	typedef xr_vector		file_list_type;
-	file_list_type*					file_list = FS.file_list_open("$game_weather_effects$","");
-	VERIFY							(file_list);
+    typedef xr_vector file_list_type;
+    file_list_type* file_list = FS.file_list_open("$game_weather_effects$", "");
+    VERIFY(file_list);
     xr_string id;
-	file_list_type::const_iterator	i = file_list->begin();
-	file_list_type::const_iterator	e = file_list->end();
-	for ( ; i != e; ++i) {
-		u32							length = xr_strlen(*i);
-		VERIFY						(length >= 4);
-		VERIFY						((*i)[length - 4] == '.');
-		VERIFY						((*i)[length - 3] == 'l');
-		VERIFY						((*i)[length - 2] == 't');
-		VERIFY						((*i)[length - 1] == 'x');
-		id.assign(*i, length-4);
-		EnvVec& env					= WeatherFXs[id.c_str()];
-
-		string_path					file_name;
-		FS.update_path				(file_name, "$game_weather_effects$", id.c_str());
-		xr_strcat					(file_name, ".ltx");
-		CInifile*					config = CInifile::Create(file_name);
-
-		typedef CInifile::Root		sections_type;
-		sections_type&				sections = config->sections();
-
-		env.reserve					(sections.size() + 2);
-		env.push_back				(create_descriptor("00:00:00", false));
-
-		sections_type::const_iterator	i = sections.begin();
-		sections_type::const_iterator	e = sections.end();
-		for ( ; i != e; ++i) {
-			CEnvDescriptor*			object = create_descriptor((*i)->Name, config);
-			env.push_back			(object);
-		}
-
-		CInifile::Destroy			(config);
-
-		env.push_back				(create_descriptor("24:00:00", false));
-		env.back()->exec_time_loaded = DAY_LENGTH;
-
-	}
-
-	FS.file_list_close				(file_list);
+    file_list_type::const_iterator i = file_list->begin();
+    file_list_type::const_iterator e = file_list->end();
+    for (; i != e; ++i)
+    {
+        u32 length = xr_strlen(*i);
+        VERIFY(length >= 4);
+        VERIFY((*i)[length - 4] == '.');
+        VERIFY((*i)[length - 3] == 'l');
+        VERIFY((*i)[length - 2] == 't');
+        VERIFY((*i)[length - 1] == 'x');
+        id.assign(*i, length - 4);
+        EnvVec& env = WeatherFXs[id.c_str()];
+
+        string_path file_name;
+        FS.update_path(file_name, "$game_weather_effects$", id.c_str());
+        xr_strcat(file_name, ".ltx");
+        CInifile* config = CInifile::Create(file_name);
+
+        typedef CInifile::Root sections_type;
+        sections_type& sections = config->sections();
+
+        env.reserve(sections.size() + 2);
+        env.push_back(create_descriptor("00:00:00", false));
+
+        sections_type::const_iterator i = sections.begin();
+        sections_type::const_iterator e = sections.end();
+        for (; i != e; ++i)
+        {
+            CEnvDescriptor* object = create_descriptor((*i)->Name, config);
+            env.push_back(object);
+        }
+
+        CInifile::Destroy(config);
+
+        env.push_back(create_descriptor("24:00:00", false));
+        env.back()->exec_time_loaded = DAY_LENGTH;
+
+    }
+
+    FS.file_list_close(file_list);
 
 #if 0
-	int line_count	= pSettings->line_count("weather_effects");
-	for (int w_idx=0; w_idxr_line("weather_effects",w_idx,&weather,§_w)){
-			EnvVec& env		= WeatherFXs[weather];
-			env.push_back	(xr_new("00:00:00")); env.back()->exec_time_loaded = 0;
-//. why?	env.push_back	(xr_new("00:00:00")); env.back()->exec_time_loaded = 0;
-			int env_count	= pSettings->line_count(sect_w);
-			LPCSTR exec_tm, sect_e;
-			for (int env_idx=0; env_idxr_line(sect_w,env_idx,&exec_tm,§_e))
-					env.push_back	(create_descriptor(sect_e));
-			}
-			env.push_back	(create_descriptor("23:59:59"));
-			env.back()->exec_time_loaded = DAY_LENGTH;
-		}
-	}
+    int line_count = pSettings->line_count("weather_effects");
+    for (int w_idx = 0; w_idx < line_count; w_idx++)
+    {
+        LPCSTR weather, sect_w;
+        if (pSettings->r_line("weather_effects", w_idx, &weather, §_w))
+        {
+            EnvVec& env = WeatherFXs[weather];
+            env.push_back(xr_new("00:00:00"));
+            env.back()->exec_time_loaded = 0;
+            //. why? env.push_back (xr_new("00:00:00")); env.back()->exec_time_loaded = 0;
+            int env_count = pSettings->line_count(sect_w);
+            LPCSTR exec_tm, sect_e;
+            for (int env_idx = 0; env_idx < env_count; env_idx++)
+            {
+                if (pSettings->r_line(sect_w, env_idx, &exec_tm, §_e))
+                    env.push_back(create_descriptor(sect_e));
+            }
+            env.push_back(create_descriptor("23:59:59"));
+            env.back()->exec_time_loaded = DAY_LENGTH;
+        }
+    }
 #endif // #if 0
 
-	// sorting weather envs
-	EnvsMapIt _I=WeatherFXs.begin();
-	EnvsMapIt _E=WeatherFXs.end();
-	for (; _I!=_E; _I++){
-		R_ASSERT3	(_I->second.size()>1,"Environment in weather must >=2",*_I->first);
-		std::sort	(_I->second.begin(),_I->second.end(),sort_env_etl_pred);
-	}
+    // sorting weather envs
+    EnvsMapIt _I = WeatherFXs.begin();
+    EnvsMapIt _E = WeatherFXs.end();
+    for (; _I != _E; _I++)
+    {
+        R_ASSERT3(_I->second.size() > 1, "Environment in weather must >=2", *_I->first);
+        std::sort(_I->second.begin(), _I->second.end(), sort_env_etl_pred);
+    }
 }
 
-void CEnvironment::load		()
+void CEnvironment::load()
 {
-	if (!CurrentEnv)
-		create_mixer		();
-
-	m_pRender->OnLoad();
-	//tonemap					= Device.Resources->_CreateTexture("$user$tonemap");	//. hack
-	if (!eff_Rain)    		eff_Rain 		= xr_new();
-	if (!eff_LensFlare)		eff_LensFlare 	= xr_new();
-	if (!eff_Thunderbolt)	eff_Thunderbolt	= xr_new();
-	
-	load_weathers			();
-	load_weather_effects	();
+    if (!CurrentEnv)
+        create_mixer();
+
+    m_pRender->OnLoad();
+    //tonemap = Device.Resources->_CreateTexture("$user$tonemap"); //. hack
+    if (!eff_Rain) eff_Rain = xr_new();
+    if (!eff_LensFlare) eff_LensFlare = xr_new();
+    if (!eff_Thunderbolt) eff_Thunderbolt = xr_new();
+
+    load_weathers();
+    load_weather_effects();
 }
 
-void CEnvironment::unload	()
+void CEnvironment::unload()
 {
-	EnvsMapIt _I,_E;
-	// clear weathers
-	_I		= WeatherCycles.begin();
-	_E		= WeatherCycles.end();
-	for (; _I!=_E; _I++){
-		for (EnvIt it=_I->second.begin(); it!=_I->second.end(); it++)
-			xr_delete	(*it);
-	}
-
-	WeatherCycles.clear		();
-	// clear weather effect
-	_I		= WeatherFXs.begin();
-	_E		= WeatherFXs.end();
-	for (; _I!=_E; _I++){
-		for (EnvIt it=_I->second.begin(); it!=_I->second.end(); it++)
-			xr_delete	(*it);
-	}
-	WeatherFXs.clear		();
-	// clear ambient
-	for (EnvAmbVecIt it=Ambients.begin(); it!=Ambients.end(); it++)
-		xr_delete		(*it);
-	Ambients.clear		();
-	// misc
-	xr_delete			(eff_Rain);
-	xr_delete			(eff_LensFlare);
-	xr_delete			(eff_Thunderbolt);
-	CurrentWeather		= 0;
-	CurrentWeatherName	= 0;
-	CurrentEnv->clear	();
-	Invalidate			();
-
-	m_pRender->OnUnload	();
-//	tonemap				= 0;
+    EnvsMapIt _I, _E;
+    // clear weathers
+    _I = WeatherCycles.begin();
+    _E = WeatherCycles.end();
+    for (; _I != _E; _I++)
+    {
+        for (EnvIt it = _I->second.begin(); it != _I->second.end(); it++)
+            xr_delete(*it);
+    }
+
+    WeatherCycles.clear();
+    // clear weather effect
+    _I = WeatherFXs.begin();
+    _E = WeatherFXs.end();
+    for (; _I != _E; _I++)
+    {
+        for (EnvIt it = _I->second.begin(); it != _I->second.end(); it++)
+            xr_delete(*it);
+    }
+    WeatherFXs.clear();
+    // clear ambient
+    for (EnvAmbVecIt it = Ambients.begin(); it != Ambients.end(); it++)
+        xr_delete(*it);
+    Ambients.clear();
+    // misc
+    xr_delete(eff_Rain);
+    xr_delete(eff_LensFlare);
+    xr_delete(eff_Thunderbolt);
+    CurrentWeather = 0;
+    CurrentWeatherName = 0;
+    CurrentEnv->clear();
+    Invalidate();
+
+    m_pRender->OnUnload();
+    // tonemap = 0;
 }
diff --git a/src/xrEngine/Environment_render.cpp b/src/xrEngine/Environment_render.cpp
index 5cdae2815cc..ef789b33b77 100644
--- a/src/xrEngine/Environment_render.cpp
+++ b/src/xrEngine/Environment_render.cpp
@@ -3,84 +3,84 @@
 
 #include "Environment.h"
 #ifndef _EDITOR
-    #include "render.h"
+#include "render.h"
 #endif
 #include "xr_efflensflare.h"
 #include "rain.h"
 #include "thunderbolt.h"
 
 #ifndef _EDITOR
-#	include "igame_level.h"
+# include "igame_level.h"
 #endif
 /*
 //////////////////////////////////////////////////////////////////////////
 // half box def
-static	Fvector3	hbox_verts[24]	=
+static Fvector3 hbox_verts[24] =
 {
-	{-1.f,	-1.f,	-1.f}, {-1.f,	-1.01f,	-1.f},	// down
-	{ 1.f,	-1.f,	-1.f}, { 1.f,	-1.01f,	-1.f},	// down
-	{-1.f,	-1.f,	 1.f}, {-1.f,	-1.01f,	 1.f},	// down
-	{ 1.f,	-1.f,	 1.f}, { 1.f,	-1.01f,	 1.f},	// down
-	{-1.f,	 1.f,	-1.f}, {-1.f,	 1.f,	-1.f},
-	{ 1.f,	 1.f,	-1.f}, { 1.f,	 1.f,	-1.f},
-	{-1.f,	 1.f,	 1.f}, {-1.f,	 1.f,	 1.f},
-	{ 1.f,	 1.f,	 1.f}, { 1.f,	 1.f,	 1.f},
-	{-1.f,	 0.f,	-1.f}, {-1.f,	-1.f,	-1.f},	// half
-	{ 1.f,	 0.f,	-1.f}, { 1.f,	-1.f,	-1.f},	// half
-	{ 1.f,	 0.f,	 1.f}, { 1.f,	-1.f,	 1.f},	// half
-	{-1.f,	 0.f,	 1.f}, {-1.f,	-1.f,	 1.f}	// half
+{-1.f, -1.f, -1.f}, {-1.f, -1.01f, -1.f}, // down
+{ 1.f, -1.f, -1.f}, { 1.f, -1.01f, -1.f}, // down
+{-1.f, -1.f, 1.f}, {-1.f, -1.01f, 1.f}, // down
+{ 1.f, -1.f, 1.f}, { 1.f, -1.01f, 1.f}, // down
+{-1.f, 1.f, -1.f}, {-1.f, 1.f, -1.f},
+{ 1.f, 1.f, -1.f}, { 1.f, 1.f, -1.f},
+{-1.f, 1.f, 1.f}, {-1.f, 1.f, 1.f},
+{ 1.f, 1.f, 1.f}, { 1.f, 1.f, 1.f},
+{-1.f, 0.f, -1.f}, {-1.f, -1.f, -1.f}, // half
+{ 1.f, 0.f, -1.f}, { 1.f, -1.f, -1.f}, // half
+{ 1.f, 0.f, 1.f}, { 1.f, -1.f, 1.f}, // half
+{-1.f, 0.f, 1.f}, {-1.f, -1.f, 1.f} // half
 };
-static	u16			hbox_faces[20*3]	=
+static u16 hbox_faces[20*3] =
 {
-	0,	 2,	 3,
-	3,	 1,	 0,
-	4,	 5,	 7,
-	7,	 6,	 4,
-	0,	 1,	 9,
-	9,	 8,	 0,
-	8,	 9,	 5,
-	5,	 4,	 8,
-	1,	 3,	10,
-	10,	 9,	 1,
-	9,	10,	 7,
-	7,	 5,	 9,
-	3,	 2,	11,
-	11,	10,	 3,
-	10,	11,	 6,
-	6,	 7,	10,
-	2,	 0,	 8,
-	8,	11,	 2,
-	11,	 8,	 4,
-	4,	 6,	11
+0, 2, 3,
+3, 1, 0,
+4, 5, 7,
+7, 6, 4,
+0, 1, 9,
+9, 8, 0,
+8, 9, 5,
+5, 4, 8,
+1, 3, 10,
+10, 9, 1,
+9, 10, 7,
+7, 5, 9,
+3, 2, 11,
+11, 10, 3,
+10, 11, 6,
+6, 7, 10,
+2, 0, 8,
+8, 11, 2,
+11, 8, 4,
+4, 6, 11
 };
 
 #pragma pack(push,1)
-struct v_skybox				{
-	Fvector3	p;
-	u32			color;
-	Fvector3	uv	[2];
-
-	void		set			(Fvector3& _p, u32 _c, Fvector3& _tc)
-	{
-		p					= _p;
-		color				= _c;
-		uv[0]				= _tc;
-		uv[1]				= _tc;
-	}
+struct v_skybox {
+Fvector3 p;
+u32 color;
+Fvector3 uv [2];
+
+void set (Fvector3& _p, u32 _c, Fvector3& _tc)
+{
+p = _p;
+color = _c;
+uv[0] = _tc;
+uv[1] = _tc;
+}
 };
-const	u32 v_skybox_fvf	= D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX2 | D3DFVF_TEXCOORDSIZE3(0) | D3DFVF_TEXCOORDSIZE3(1);
-struct v_clouds				{
-	Fvector3	p;
-	u32			color;
-	u32			intensity;
-	void		set			(Fvector3& _p, u32 _c, u32 _i)
-	{
-		p					= _p;
-		color				= _c;
-		intensity			= _i;
-	}
+const u32 v_skybox_fvf = D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX2 | D3DFVF_TEXCOORDSIZE3(0) | D3DFVF_TEXCOORDSIZE3(1);
+struct v_clouds {
+Fvector3 p;
+u32 color;
+u32 intensity;
+void set (Fvector3& _p, u32 _c, u32 _i)
+{
+p = _p;
+color = _c;
+intensity = _i;
+}
 };
-const	u32 v_clouds_fvf	= D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_SPECULAR;
+const u32 v_clouds_fvf = D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_SPECULAR;
 #pragma pack(pop)
 */
 
@@ -89,205 +89,205 @@ const	u32 v_clouds_fvf	= D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_SPECULAR;
 //-----------------------------------------------------------------------------
 extern ENGINE_API float psHUD_FOV;
 //BOOL bNeed_re_create_env = FALSE;
-void CEnvironment::RenderSky		()
+void CEnvironment::RenderSky()
 {
 #ifndef _EDITOR
-	if (0==g_pGameLevel)		return;
+    if (0 == g_pGameLevel) return;
 #endif
 
-	m_pRender->RenderSky(*this);
-	/*
-	// clouds_sh.create		("clouds","null");
-	//. this is the bug-fix for the case when the sky is broken
-	//. for some unknown reason the geoms happen to be invalid sometimes
-	//. if vTune show this in profile, please add simple cache (move-to-forward last found) 
-	//. to the following functions:
-	//.		CResourceManager::_CreateDecl
-	//.		CResourceManager::CreateGeom
-	if(bNeed_re_create_env)
-	{
-		sh_2sky.create			(&m_b_skybox,"skybox_2t");
-		sh_2geom.create			(v_skybox_fvf,RCache.Vertex.Buffer(), RCache.Index.Buffer());
-		clouds_sh.create		("clouds","null");
-		clouds_geom.create		(v_clouds_fvf,RCache.Vertex.Buffer(), RCache.Index.Buffer());
-		bNeed_re_create_env		= FALSE;
-	}
-	::Render->rmFar				();
-
-	// draw sky box
-	Fmatrix						mSky;
-	mSky.rotateY				(CurrentEnv->sky_rotation);
-	mSky.translate_over			(Device.vCameraPosition);
-
-	u32		i_offset,v_offset;
-	u32		C					= color_rgba(iFloor(CurrentEnv->sky_color.x*255.f), iFloor(CurrentEnv->sky_color.y*255.f), iFloor(CurrentEnv->sky_color.z*255.f), iFloor(CurrentEnv->weight*255.f));
-
-	// Fill index buffer
-	u16*	pib					= RCache.Index.Lock	(20*3,i_offset);
-	CopyMemory					(pib,hbox_faces,20*3*2);
-	RCache.Index.Unlock			(20*3);
-
-	// Fill vertex buffer
-	v_skybox* pv				= (v_skybox*)	RCache.Vertex.Lock	(12,sh_2geom.stride(),v_offset);
-	for (u32 v=0; v<12; v++)	pv[v].set		(hbox_verts[v*2],C,hbox_verts[v*2+1]);
-	RCache.Vertex.Unlock		(12,sh_2geom.stride());
-
-	// Render
-	RCache.set_xform_world		(mSky);
-	RCache.set_Geometry			(sh_2geom);
-	RCache.set_Shader			(sh_2sky);
-	RCache.set_Textures			(&CurrentEnv->sky_r_textures);
-	RCache.Render				(D3DPT_TRIANGLELIST,v_offset,0,12,i_offset,20);
-
-	// Sun
-	::Render->rmNormal			();
-	eff_LensFlare->Render		(TRUE,FALSE,FALSE);
-	*/
+    m_pRender->RenderSky(*this);
+    /*
+    // clouds_sh.create ("clouds","null");
+    //. this is the bug-fix for the case when the sky is broken
+    //. for some unknown reason the geoms happen to be invalid sometimes
+    //. if vTune show this in profile, please add simple cache (move-to-forward last found)
+    //. to the following functions:
+    //. CResourceManager::_CreateDecl
+    //. CResourceManager::CreateGeom
+    if(bNeed_re_create_env)
+    {
+    sh_2sky.create (&m_b_skybox,"skybox_2t");
+    sh_2geom.create (v_skybox_fvf,RCache.Vertex.Buffer(), RCache.Index.Buffer());
+    clouds_sh.create ("clouds","null");
+    clouds_geom.create (v_clouds_fvf,RCache.Vertex.Buffer(), RCache.Index.Buffer());
+    bNeed_re_create_env = FALSE;
+    }
+    ::Render->rmFar ();
+
+    // draw sky box
+    Fmatrix mSky;
+    mSky.rotateY (CurrentEnv->sky_rotation);
+    mSky.translate_over (Device.vCameraPosition);
+
+    u32 i_offset,v_offset;
+    u32 C = color_rgba(iFloor(CurrentEnv->sky_color.x*255.f), iFloor(CurrentEnv->sky_color.y*255.f), iFloor(CurrentEnv->sky_color.z*255.f), iFloor(CurrentEnv->weight*255.f));
+
+    // Fill index buffer
+    u16* pib = RCache.Index.Lock (20*3,i_offset);
+    CopyMemory (pib,hbox_faces,20*3*2);
+    RCache.Index.Unlock (20*3);
+
+    // Fill vertex buffer
+    v_skybox* pv = (v_skybox*) RCache.Vertex.Lock (12,sh_2geom.stride(),v_offset);
+    for (u32 v=0; v<12; v++) pv[v].set (hbox_verts[v*2],C,hbox_verts[v*2+1]);
+    RCache.Vertex.Unlock (12,sh_2geom.stride());
+
+    // Render
+    RCache.set_xform_world (mSky);
+    RCache.set_Geometry (sh_2geom);
+    RCache.set_Shader (sh_2sky);
+    RCache.set_Textures (&CurrentEnv->sky_r_textures);
+    RCache.Render (D3DPT_TRIANGLELIST,v_offset,0,12,i_offset,20);
+
+    // Sun
+    ::Render->rmNormal ();
+    eff_LensFlare->Render (TRUE,FALSE,FALSE);
+    */
 }
 
-void CEnvironment::RenderClouds			()
+void CEnvironment::RenderClouds()
 {
 #ifndef _EDITOR
-	if (0==g_pGameLevel)		return	;
+    if (0 == g_pGameLevel) return;
 #endif
-	// draw clouds
-	if (fis_zero(CurrentEnv->clouds_color.w,EPS_L))	return;
-
-	m_pRender->RenderClouds(*this);
-	/*
-
-	::Render->rmFar				();
-
-	Fmatrix						mXFORM, mScale;
-	mScale.scale				(10,0.4f,10);
-	mXFORM.rotateY				(CurrentEnv->sky_rotation);
-	mXFORM.mulB_43				(mScale);
-	mXFORM.translate_over		(Device.vCameraPosition);
-
-	Fvector wd0,wd1;
-	Fvector4 wind_dir;
-	wd0.setHP					(PI_DIV_4,0);
-	wd1.setHP					(PI_DIV_4+PI_DIV_8,0);
-	wind_dir.set				(wd0.x,wd0.z,wd1.x,wd1.z).mul(0.5f).add(0.5f).mul(255.f);
-	u32		i_offset,v_offset;
-	u32		C0					= color_rgba(iFloor(wind_dir.x),iFloor(wind_dir.y),iFloor(wind_dir.w),iFloor(wind_dir.z));
-	u32		C1					= color_rgba(iFloor(CurrentEnv->clouds_color.x*255.f),iFloor(CurrentEnv->clouds_color.y*255.f),iFloor(CurrentEnv->clouds_color.z*255.f),iFloor(CurrentEnv->clouds_color.w*255.f));
-
-	// Fill index buffer
-	u16*	pib					= RCache.Index.Lock	(CloudsIndices.size(),i_offset);
-	CopyMemory					(pib,&CloudsIndices.front(),CloudsIndices.size()*sizeof(u16));
-	RCache.Index.Unlock			(CloudsIndices.size());
-
-	// Fill vertex buffer
-	v_clouds* pv				= (v_clouds*)	RCache.Vertex.Lock	(CloudsVerts.size(),clouds_geom.stride(),v_offset);
-	for (FvectorIt it=CloudsVerts.begin(); it!=CloudsVerts.end(); it++,pv++)
-		pv->set					(*it,C0,C1);
-	RCache.Vertex.Unlock		(CloudsVerts.size(),clouds_geom.stride());
-
-	// Render
-	RCache.set_xform_world		(mXFORM);
-	RCache.set_Geometry			(clouds_geom);
-	RCache.set_Shader			(clouds_sh);
-	RCache.set_Textures			(&CurrentEnv->clouds_r_textures);
-	RCache.Render				(D3DPT_TRIANGLELIST,v_offset,0,CloudsVerts.size(),i_offset,CloudsIndices.size()/3);
-
-	::Render->rmNormal			();
-	*/
+    // draw clouds
+    if (fis_zero(CurrentEnv->clouds_color.w, EPS_L)) return;
+
+    m_pRender->RenderClouds(*this);
+    /*
+
+    ::Render->rmFar ();
+
+    Fmatrix mXFORM, mScale;
+    mScale.scale (10,0.4f,10);
+    mXFORM.rotateY (CurrentEnv->sky_rotation);
+    mXFORM.mulB_43 (mScale);
+    mXFORM.translate_over (Device.vCameraPosition);
+
+    Fvector wd0,wd1;
+    Fvector4 wind_dir;
+    wd0.setHP (PI_DIV_4,0);
+    wd1.setHP (PI_DIV_4+PI_DIV_8,0);
+    wind_dir.set (wd0.x,wd0.z,wd1.x,wd1.z).mul(0.5f).add(0.5f).mul(255.f);
+    u32 i_offset,v_offset;
+    u32 C0 = color_rgba(iFloor(wind_dir.x),iFloor(wind_dir.y),iFloor(wind_dir.w),iFloor(wind_dir.z));
+    u32 C1 = color_rgba(iFloor(CurrentEnv->clouds_color.x*255.f),iFloor(CurrentEnv->clouds_color.y*255.f),iFloor(CurrentEnv->clouds_color.z*255.f),iFloor(CurrentEnv->clouds_color.w*255.f));
+
+    // Fill index buffer
+    u16* pib = RCache.Index.Lock (CloudsIndices.size(),i_offset);
+    CopyMemory (pib,&CloudsIndices.front(),CloudsIndices.size()*sizeof(u16));
+    RCache.Index.Unlock (CloudsIndices.size());
+
+    // Fill vertex buffer
+    v_clouds* pv = (v_clouds*) RCache.Vertex.Lock (CloudsVerts.size(),clouds_geom.stride(),v_offset);
+    for (FvectorIt it=CloudsVerts.begin(); it!=CloudsVerts.end(); it++,pv++)
+    pv->set (*it,C0,C1);
+    RCache.Vertex.Unlock (CloudsVerts.size(),clouds_geom.stride());
+
+    // Render
+    RCache.set_xform_world (mXFORM);
+    RCache.set_Geometry (clouds_geom);
+    RCache.set_Shader (clouds_sh);
+    RCache.set_Textures (&CurrentEnv->clouds_r_textures);
+    RCache.Render (D3DPT_TRIANGLELIST,v_offset,0,CloudsVerts.size(),i_offset,CloudsIndices.size()/3);
+
+    ::Render->rmNormal ();
+    */
 }
 
-void CEnvironment::RenderFlares		()
+void CEnvironment::RenderFlares()
 {
 #ifndef _EDITOR
-	if (0==g_pGameLevel)			return	;
+    if (0 == g_pGameLevel) return;
 #endif
-	// 1
-	eff_LensFlare->Render			(FALSE,TRUE,TRUE);
+    // 1
+    eff_LensFlare->Render(FALSE, TRUE, TRUE);
 }
 
-void CEnvironment::RenderLast		()
+void CEnvironment::RenderLast()
 {
 #ifndef _EDITOR
-	if (0==g_pGameLevel)			return	;
+    if (0 == g_pGameLevel) return;
 #endif
-	// 2
-	eff_Rain->Render				();
-	eff_Thunderbolt->Render			();
+    // 2
+    eff_Rain->Render();
+    eff_Thunderbolt->Render();
 }
 
 void CEnvironment::OnDeviceCreate()
 {
-//.	bNeed_re_create_env			= TRUE;
-	m_pRender->OnDeviceCreate();
-	/*
-	sh_2sky.create			(&m_b_skybox,"skybox_2t");
-	sh_2geom.create			(v_skybox_fvf,RCache.Vertex.Buffer(), RCache.Index.Buffer());
-	clouds_sh.create		("clouds","null");
-	clouds_geom.create		(v_clouds_fvf,RCache.Vertex.Buffer(), RCache.Index.Buffer());
-	*/
-
-	// weathers
-	{
-		EnvsMapIt _I,_E;
-		_I		= WeatherCycles.begin();
-		_E		= WeatherCycles.end();
-		for (; _I!=_E; _I++)
-			for (EnvIt it=_I->second.begin(); it!=_I->second.end(); it++)
-				(*it)->on_device_create();
-	}
-	// effects
-	{
-		EnvsMapIt _I,_E;
-		_I		= WeatherFXs.begin();
-		_E		= WeatherFXs.end();
-		for (; _I!=_E; _I++)
-			for (EnvIt it=_I->second.begin(); it!=_I->second.end(); it++)
-				(*it)->on_device_create();
-	}
-
-
-	Invalidate	();
-	OnFrame		();
+    //. bNeed_re_create_env = TRUE;
+    m_pRender->OnDeviceCreate();
+    /*
+    sh_2sky.create (&m_b_skybox,"skybox_2t");
+    sh_2geom.create (v_skybox_fvf,RCache.Vertex.Buffer(), RCache.Index.Buffer());
+    clouds_sh.create ("clouds","null");
+    clouds_geom.create (v_clouds_fvf,RCache.Vertex.Buffer(), RCache.Index.Buffer());
+    */
+
+    // weathers
+    {
+        EnvsMapIt _I, _E;
+        _I = WeatherCycles.begin();
+        _E = WeatherCycles.end();
+        for (; _I != _E; _I++)
+            for (EnvIt it = _I->second.begin(); it != _I->second.end(); it++)
+                (*it)->on_device_create();
+    }
+    // effects
+    {
+        EnvsMapIt _I, _E;
+        _I = WeatherFXs.begin();
+        _E = WeatherFXs.end();
+        for (; _I != _E; _I++)
+            for (EnvIt it = _I->second.begin(); it != _I->second.end(); it++)
+                (*it)->on_device_create();
+    }
+
+
+    Invalidate();
+    OnFrame();
 }
 
 void CEnvironment::OnDeviceDestroy()
 {
-	m_pRender->OnDeviceDestroy();
-	/*
-	tsky0->surface_set						(NULL);
-	tsky1->surface_set						(NULL);
-	
-	sh_2sky.destroy							();
-	sh_2geom.destroy						();
-	clouds_sh.destroy						();
-	clouds_geom.destroy						();
-	*/
-	// weathers
-	{
-		EnvsMapIt _I,_E;
-		_I		= WeatherCycles.begin();
-		_E		= WeatherCycles.end();
-		for (; _I!=_E; _I++)
-			for (EnvIt it=_I->second.begin(); it!=_I->second.end(); it++)
-				(*it)->on_device_destroy();
-	}
-	// effects
-	{
-		EnvsMapIt _I,_E;
-		_I		= WeatherFXs.begin();
-		_E		= WeatherFXs.end();
-		for (; _I!=_E; _I++)
-			for (EnvIt it=_I->second.begin(); it!=_I->second.end(); it++)
-				(*it)->on_device_destroy();
-	}
-	CurrentEnv->destroy();
+    m_pRender->OnDeviceDestroy();
+    /*
+    tsky0->surface_set (NULL);
+    tsky1->surface_set (NULL);
+
+    sh_2sky.destroy ();
+    sh_2geom.destroy ();
+    clouds_sh.destroy ();
+    clouds_geom.destroy ();
+    */
+    // weathers
+    {
+        EnvsMapIt _I, _E;
+        _I = WeatherCycles.begin();
+        _E = WeatherCycles.end();
+        for (; _I != _E; _I++)
+            for (EnvIt it = _I->second.begin(); it != _I->second.end(); it++)
+                (*it)->on_device_destroy();
+    }
+    // effects
+    {
+        EnvsMapIt _I, _E;
+        _I = WeatherFXs.begin();
+        _E = WeatherFXs.end();
+        for (; _I != _E; _I++)
+            for (EnvIt it = _I->second.begin(); it != _I->second.end(); it++)
+                (*it)->on_device_destroy();
+    }
+    CurrentEnv->destroy();
 
 }
 
 #ifdef _EDITOR
 void CEnvironment::ED_Reload()
 {
-	OnDeviceDestroy			();
-	OnDeviceCreate			();
+    OnDeviceDestroy();
+    OnDeviceCreate();
 }
 #endif
 
diff --git a/src/xrEngine/EventAPI.cpp b/src/xrEngine/EventAPI.cpp
index 5bfe97d24ac..17a316ebad1 100644
--- a/src/xrEngine/EventAPI.cpp
+++ b/src/xrEngine/EventAPI.cpp
@@ -2,202 +2,214 @@
 #include "eventapi.h"
 #include "xr_ioconsole.h"
 
-extern	void msRead			();
-extern	void msCreate		(LPCSTR name);
+extern void msRead();
+extern void msCreate(LPCSTR name);
 
 //---------------------------------------------------------------------
 class ENGINE_API CEvent
 {
-	friend class CEventAPI;
+    friend class CEventAPI;
 private:
-	char*						Name;
-	xr_vector		Handlers;
-	u32							dwRefCount;
+    char* Name;
+    xr_vector Handlers;
+    u32 dwRefCount;
 public:
-	CEvent	(const char* S);
-	~CEvent	();
-
-	LPCSTR	GetFull()
-	{	return Name; }
-	u32	RefCount()
-	{	return dwRefCount; }
-
-	BOOL	Equal(CEvent& E)
-	{ return stricmp(Name,E.Name)==0; }
-
-	void	Attach(IEventReceiver* H)
-	{
-		if (std::find(Handlers.begin(),Handlers.end(),H)==Handlers.end())
-			Handlers.push_back(H);
-	}
-	void	Detach(IEventReceiver* H)
-	{
-		xr_vector::iterator I = std::find(Handlers.begin(),Handlers.end(),H);
-		if (I!=Handlers.end())
-			Handlers.erase(I);
-	}
-	void	Signal(u64 P1, u64 P2)
-	{
-		for (u32 I=0; IOnEvent(this,P1,P2);
-	}
+    CEvent(const char* S);
+    ~CEvent();
+
+    LPCSTR GetFull()
+    {
+        return Name;
+    }
+    u32 RefCount()
+    {
+        return dwRefCount;
+    }
+
+    BOOL Equal(CEvent& E)
+    {
+        return stricmp(Name, E.Name) == 0;
+    }
+
+    void Attach(IEventReceiver* H)
+    {
+        if (std::find(Handlers.begin(), Handlers.end(), H) == Handlers.end())
+            Handlers.push_back(H);
+    }
+    void Detach(IEventReceiver* H)
+    {
+        xr_vector::iterator I = std::find(Handlers.begin(), Handlers.end(), H);
+        if (I != Handlers.end())
+            Handlers.erase(I);
+    }
+    void Signal(u64 P1, u64 P2)
+    {
+        for (u32 I = 0; I < Handlers.size(); I++)
+            Handlers[I]->OnEvent(this, P1, P2);
+    }
 };
 //-----------------------------------------
 CEvent::CEvent(const char* S)
-{	
-	Name=xr_strdup(S); 
-	_strupr(Name);
-	dwRefCount=1; 
+{
+    Name = xr_strdup(S);
+    _strupr(Name);
+    dwRefCount = 1;
 }
 CEvent::~CEvent()
-{	xr_free(Name); }
+{
+    xr_free(Name);
+}
 
 //-----------------------------------------
-IC bool ev_sort(CEvent*E1, CEvent*E2)
-{	return E1->GetFull() < E2->GetFull(); }
+IC bool ev_sort(CEvent* E1, CEvent* E2)
+{
+    return E1->GetFull() < E2->GetFull();
+}
 
 void CEventAPI::Dump()
 {
-	std::sort(Events.begin(),Events.end(),ev_sort);
-	for (u32 i=0; iRefCount(),Events[i]->GetFull());
+    std::sort(Events.begin(), Events.end(), ev_sort);
+    for (u32 i = 0; i < Events.size(); i++)
+        Msg("* [%d] %s", Events[i]->RefCount(), Events[i]->GetFull());
 }
 
-EVENT	CEventAPI::Create(const char* N)
+EVENT CEventAPI::Create(const char* N)
 {
-	CS.Enter	();
-	CEvent	E	(N);
-	for (xr_vector::iterator I=Events.begin(); I!=Events.end(); I++)
-	{
-		if ((*I)->Equal(E)) {
-			EVENT F		= *I;
-			F->dwRefCount++;
-			CS.Leave	();
-			return		F;
-		}
-	}
-
-	EVENT X = xr_new	(N);
-	Events.push_back			(X);
-	CS.Leave					( );
-	return X;
+    CS.Enter();
+    CEvent E(N);
+    for (xr_vector::iterator I = Events.begin(); I != Events.end(); I++)
+    {
+        if ((*I)->Equal(E))
+        {
+            EVENT F = *I;
+            F->dwRefCount++;
+            CS.Leave();
+            return F;
+        }
+    }
+
+    EVENT X = xr_new(N);
+    Events.push_back(X);
+    CS.Leave();
+    return X;
 }
-void	CEventAPI::Destroy(EVENT& E)
+void CEventAPI::Destroy(EVENT& E)
 {
-	CS.Enter	();
-	E->dwRefCount--;
-	if (E->dwRefCount == 0) 
-	{
-		xr_vector::iterator I = std::find(Events.begin(),Events.end(),E);
-		R_ASSERT(I!=Events.end());
-		Events.erase(I);
-		xr_delete	(E);
-	}
-	CS.Leave	();
+    CS.Enter();
+    E->dwRefCount--;
+    if (E->dwRefCount == 0)
+    {
+        xr_vector::iterator I = std::find(Events.begin(), Events.end(), E);
+        R_ASSERT(I != Events.end());
+        Events.erase(I);
+        xr_delete(E);
+    }
+    CS.Leave();
 }
 
-EVENT	CEventAPI::Handler_Attach(const char* N, IEventReceiver* H)
+EVENT CEventAPI::Handler_Attach(const char* N, IEventReceiver* H)
 {
-	CS.Enter	();
-	EVENT	E = Create(N);
-	E->Attach(H);
-	CS.Leave	();
-	return E;
+    CS.Enter();
+    EVENT E = Create(N);
+    E->Attach(H);
+    CS.Leave();
+    return E;
 }
 
-void	CEventAPI::Handler_Detach(EVENT& E, IEventReceiver* H)
+void CEventAPI::Handler_Detach(EVENT& E, IEventReceiver* H)
 {
-	if (0==E)	return;
-	CS.Enter	();
-	E->Detach	(H);
-	Destroy		(E);
-	CS.Leave	();
+    if (0 == E) return;
+    CS.Enter();
+    E->Detach(H);
+    Destroy(E);
+    CS.Leave();
 }
-void	CEventAPI::Signal(EVENT E, u64 P1, u64 P2)
+void CEventAPI::Signal(EVENT E, u64 P1, u64 P2)
 {
-	CS.Enter	();
-	E->Signal	(P1,P2);	
-	CS.Leave	();
+    CS.Enter();
+    E->Signal(P1, P2);
+    CS.Leave();
 }
-void	CEventAPI::Signal(LPCSTR N, u64 P1, u64 P2)
+void CEventAPI::Signal(LPCSTR N, u64 P1, u64 P2)
 {
-	CS.Enter	();
-	EVENT		E = Create(N);
-	Signal		(E,P1,P2);
-	Destroy		(E);
-	CS.Leave	();
+    CS.Enter();
+    EVENT E = Create(N);
+    Signal(E, P1, P2);
+    Destroy(E);
+    CS.Leave();
 }
-void	CEventAPI::Defer(EVENT E, u64 P1, u64 P2)
+void CEventAPI::Defer(EVENT E, u64 P1, u64 P2)
 {
-	CS.Enter	();
-	E->dwRefCount++;
-	Events_Deferred.push_back	(Deferred());
-	Events_Deferred.back().E	= E;
-	Events_Deferred.back().P1	= P1;
-	Events_Deferred.back().P2	= P2;
-	CS.Leave	();
+    CS.Enter();
+    E->dwRefCount++;
+    Events_Deferred.push_back(Deferred());
+    Events_Deferred.back().E = E;
+    Events_Deferred.back().P1 = P1;
+    Events_Deferred.back().P2 = P2;
+    CS.Leave();
 }
-void	CEventAPI::Defer(LPCSTR N, u64 P1, u64 P2)
+void CEventAPI::Defer(LPCSTR N, u64 P1, u64 P2)
 {
-	CS.Enter	();
-	EVENT	E	= Create(N);
-	Defer		(E,P1,P2);
-	Destroy		(E);
-	CS.Leave	();
+    CS.Enter();
+    EVENT E = Create(N);
+    Defer(E, P1, P2);
+    Destroy(E);
+    CS.Leave();
 }
 
 #ifdef DEBUG
-void msParse			(LPCSTR c)
-{
-	if (0==stricmp(c,"exit")) 
-	{
-		Console->Execute	("quit");
-	}
-	if (0==stricmp(c,"quit"))
-	{
-		TerminateProcess	(GetCurrentProcess(),0);
-		Console->Execute	("quit");
-	}
+void msParse(LPCSTR c)
+{
+    if (0 == stricmp(c, "exit"))
+    {
+        Console->Execute("quit");
+    }
+    if (0 == stricmp(c, "quit"))
+    {
+        TerminateProcess(GetCurrentProcess(), 0);
+        Console->Execute("quit");
+    }
 }
 #endif
 
-void	CEventAPI::OnFrame	()
+void CEventAPI::OnFrame()
 {
 #ifdef DEBUG
-	msRead		();
+    msRead();
 #endif
-	CS.Enter	();
-	if (Events_Deferred.empty())	{ CS.Leave(); return; }
-	for (u32 I=0; IGetFull(),EName)==0){
-			CS.Leave(); 
-			return TRUE;
-		}
-
-	}
-	CS.Leave	();
-	return FALSE;
+    CS.Enter();
+    if (Events_Deferred.empty()) { CS.Leave(); return FALSE; }
+    for (u32 I = 0; I < Events_Deferred.size(); I++)
+    {
+        Deferred& DEF = Events_Deferred[I];
+        if (stricmp(DEF.E->GetFull(), EName) == 0)
+        {
+            CS.Leave();
+            return TRUE;
+        }
+
+    }
+    CS.Leave();
+    return FALSE;
 }
 
 void CEventAPI::_destroy()
 {
-	Dump	();
-	if (Events.empty())				Events.clear();
-	if (Events_Deferred.empty())	Events_Deferred.clear();
+    Dump();
+    if (Events.empty()) Events.clear();
+    if (Events_Deferred.empty()) Events_Deferred.clear();
 }
diff --git a/src/xrEngine/EventAPI.h b/src/xrEngine/EventAPI.h
index 1ea00fa0956..9571a947545 100644
--- a/src/xrEngine/EventAPI.h
+++ b/src/xrEngine/EventAPI.h
@@ -2,46 +2,46 @@
 
 #include "../xrcore/xrSyncronize.h"
 
-class ENGINE_API	CEvent;
-typedef CEvent*		EVENT;
+class ENGINE_API CEvent;
+typedef CEvent* EVENT;
 
 //---------------------------------------------------------------------
-class ENGINE_API	IEventReceiver
+class ENGINE_API IEventReceiver
 {
 public:
-	virtual void	OnEvent(EVENT E, u64 P1, u64 P2) = 0;
+    virtual void OnEvent(EVENT E, u64 P1, u64 P2) = 0;
 };
 //---------------------------------------------------------------------
-class ENGINE_API	CEventAPI
+class ENGINE_API CEventAPI
 {
-	struct Deferred
-	{
-		EVENT		E;
-		u64			P1;
-		u64			P2;
-	};
+    struct Deferred
+    {
+        EVENT E;
+        u64 P1;
+        u64 P2;
+    };
 private:
-	xr_vector		Events;
-	xr_vector		Events_Deferred;
-	xrCriticalSection		CS;
+    xr_vector Events;
+    xr_vector Events_Deferred;
+    xrCriticalSection CS;
 public:
 #ifdef PROFILE_CRITICAL_SECTIONS
-			CEventAPI		() : CS(MUTEX_PROFILE_ID(CEventAPI)) {}
+    CEventAPI () : CS(MUTEX_PROFILE_ID(CEventAPI)) {}
 #endif // PROFILE_CRITICAL_SECTIONS
-	EVENT	Create			(const char* N);
-	void	Destroy			(EVENT& E);
+    EVENT Create(const char* N);
+    void Destroy(EVENT& E);
 
-	EVENT	Handler_Attach	(const char* N, IEventReceiver* H);
-	void	Handler_Detach	(EVENT& E, IEventReceiver* H);
+    EVENT Handler_Attach(const char* N, IEventReceiver* H);
+    void Handler_Detach(EVENT& E, IEventReceiver* H);
 
-	void	Signal			(EVENT	E, u64 P1=0, u64 P2=0);
-	void	Signal			(LPCSTR E, u64 P1=0, u64 P2=0);
-	void	Defer			(EVENT	E, u64 P1=0, u64 P2=0);
-	void	Defer			(LPCSTR E, u64 P1=0, u64 P2=0);
+    void Signal(EVENT E, u64 P1 = 0, u64 P2 = 0);
+    void Signal(LPCSTR E, u64 P1 = 0, u64 P2 = 0);
+    void Defer(EVENT E, u64 P1 = 0, u64 P2 = 0);
+    void Defer(LPCSTR E, u64 P1 = 0, u64 P2 = 0);
 
-	void	OnFrame			();
-	void	Dump			();
-	BOOL	Peek			(LPCSTR EName);
+    void OnFrame();
+    void Dump();
+    BOOL Peek(LPCSTR EName);
 
-	void	_destroy		();
+    void _destroy();
 };
diff --git a/src/xrEngine/FDemoPlay.cpp b/src/xrEngine/FDemoPlay.cpp
index 25639b98f54..ea0f861eddd 100644
--- a/src/xrEngine/FDemoPlay.cpp
+++ b/src/xrEngine/FDemoPlay.cpp
@@ -16,282 +16,300 @@
 // Construction/Destruction
 //////////////////////////////////////////////////////////////////////
 
-CDemoPlay::CDemoPlay(const char *name, float ms, u32 cycles, float life_time) : CEffectorCam(cefDemo,life_time/*,FALSE*/)
+CDemoPlay::CDemoPlay(const char* name, float ms, u32 cycles, float life_time) : CEffectorCam(cefDemo, life_time/*,FALSE*/)
 {
-	Msg					("*** Playing demo: %s",name);
-	Console->Execute	("hud_weapon 0");
-	if( g_bBenchmark || g_SASH.IsRunning() )
-		Console->Execute	("hud_draw 0");
-
-	fSpeed				= ms;
-	dwCyclesLeft		= cycles?cycles:1;
-
-	m_pMotion			= 0;
-	m_MParam			= 0;
-	string_path			nm, fn;
-	xr_strcpy			(nm,sizeof(nm),name);	
-	LPSTR extp			=strext(nm);
-	if (extp)	
-		xr_strcpy			( nm, sizeof( nm ) - ( extp - nm ), ".anm");
-
-	if ( FS.exist(fn,"$level$",nm) || FS.exist(fn,"$game_anims$",nm) )
-	{
-		m_pMotion				= xr_new		();
-		m_pMotion->LoadMotion	(fn);
-		m_MParam				= xr_new	();
-		m_MParam->Set			(m_pMotion);
-		m_MParam->Play			();
-	}else{
-		if (!FS.exist(name))						{
-			g_pGameLevel->Cameras().RemoveCamEffector	(cefDemo);
-			return		;
-		}
-		IReader*	fs	= FS.r_open	(name);
-		u32 sz			= fs->length();
-		if				(sz%sizeof(Fmatrix) != 0)	{
-			FS.r_close	(fs);
-			g_pGameLevel->Cameras().RemoveCamEffector	(cefDemo);
-			return		;
-		}
-		
-		seq.resize		(sz/sizeof(Fmatrix));
-		m_count			= seq.size();
-		CopyMemory	(&*seq.begin(),fs->pointer(),sz);
-		FS.r_close		(fs);
-		Log				("~ Total key-frames: ",m_count);
-	}
-	stat_started		= FALSE;
-	Device.PreCache		(50, true, false);
+    Msg("*** Playing demo: %s", name);
+    Console->Execute("hud_weapon 0");
+    if (g_bBenchmark || g_SASH.IsRunning())
+        Console->Execute("hud_draw 0");
+
+    fSpeed = ms;
+    dwCyclesLeft = cycles ? cycles : 1;
+
+    m_pMotion = 0;
+    m_MParam = 0;
+    string_path nm, fn;
+    xr_strcpy(nm, sizeof(nm), name);
+    LPSTR extp = strext(nm);
+    if (extp)
+        xr_strcpy(nm, sizeof(nm) - (extp - nm), ".anm");
+
+    if (FS.exist(fn, "$level$", nm) || FS.exist(fn, "$game_anims$", nm))
+    {
+        m_pMotion = xr_new();
+        m_pMotion->LoadMotion(fn);
+        m_MParam = xr_new();
+        m_MParam->Set(m_pMotion);
+        m_MParam->Play();
+    }
+    else
+    {
+        if (!FS.exist(name))
+        {
+            g_pGameLevel->Cameras().RemoveCamEffector(cefDemo);
+            return;
+        }
+        IReader* fs = FS.r_open(name);
+        u32 sz = fs->length();
+        if (sz%sizeof(Fmatrix) != 0)
+        {
+            FS.r_close(fs);
+            g_pGameLevel->Cameras().RemoveCamEffector(cefDemo);
+            return;
+        }
+
+        seq.resize(sz / sizeof(Fmatrix));
+        m_count = seq.size();
+        CopyMemory(&*seq.begin(), fs->pointer(), sz);
+        FS.r_close(fs);
+        Log("~ Total key-frames: ", m_count);
+    }
+    stat_started = FALSE;
+    Device.PreCache(50, true, false);
 }
 
-CDemoPlay::~CDemoPlay		()
+CDemoPlay::~CDemoPlay()
 {
-	stat_Stop				();
-	xr_delete				(m_pMotion	);
-	xr_delete				(m_MParam	);
-	Console->Execute		("hud_weapon 1");
-	if(g_bBenchmark || g_SASH.IsRunning())		
-		Console->Execute	("hud_draw 1");
+    stat_Stop();
+    xr_delete(m_pMotion);
+    xr_delete(m_MParam);
+    Console->Execute("hud_weapon 1");
+    if (g_bBenchmark || g_SASH.IsRunning())
+        Console->Execute("hud_draw 1");
 }
 
-void CDemoPlay::stat_Start	()
+void CDemoPlay::stat_Start()
 {
-	//if (stat_started)		return;
-	VERIFY(!stat_started);
-	stat_started			= TRUE				;
-	Sleep					(1)					;
-	stat_StartFrame			=	Device.dwFrame	;
-	stat_Timer_frame.Start	()					;
-	stat_Timer_total.Start	()					;
-	stat_table.clear		()					;
-	stat_table.reserve		(1024)				;
-	fStartTime				= 0;
+    //if (stat_started) return;
+    VERIFY(!stat_started);
+    stat_started = TRUE;
+    Sleep(1);
+    stat_StartFrame = Device.dwFrame;
+    stat_Timer_frame.Start();
+    stat_Timer_total.Start();
+    stat_table.clear();
+    stat_table.reserve(1024);
+    fStartTime = 0;
 }
 
-extern string512		g_sBenchmarkName;
+extern string512 g_sBenchmarkName;
 
-void CDemoPlay::stat_Stop	()
+void CDemoPlay::stat_Stop()
 {
-	if (!stat_started)		return;
-
-	//g_SASH.EndBenchmark();
-
-	stat_started			= FALSE;
-	float	stat_total		= stat_Timer_total.GetElapsed_sec	();
-
-	float	rfps_min, rfps_max, rfps_middlepoint, rfps_average	;
-
-	// total
-	u32	dwFramesTotal		= Device.dwFrame-stat_StartFrame	;
-	rfps_average			= float(dwFramesTotal)/stat_total	;
-
-	// min/max/average
-	rfps_min				= flt_max;
-	rfps_max				= flt_min;
-	rfps_middlepoint		= 0;
-
-	//	Filtered FPS
-	const u32 iAvgFPS		=	_max((u32)rfps_average,10);
-	const u32 WindowSize	=	_max(16, iAvgFPS/2);
-
-	if ( stat_table.size() > WindowSize*4 )
-	{
-		for (u32	it=2; itrfps_max)	rfps_max = fps;
-			rfps_middlepoint	+=	fps;
-		}
-
-		rfps_middlepoint		/= float(stat_table.size()-1-WindowSize+1);
-	}
-	else
-	{
-		for (u32	it=1; itrfps_max)	rfps_max = fps;
-			rfps_middlepoint	+=	fps;
-		}
-		rfps_middlepoint		/= float(stat_table.size()-1);
-	}
-
-	/*
-	for (u32	it=1; itrfps_max)	rfps_max = fps;
-		rfps_middlepoint	+=	fps;
-	}
-	rfps_middlepoint		/= float(stat_table.size()-1);
-	*/
-
-	Msg("* [DEMO] FPS: average[%f], min[%f], max[%f], middle[%f]",rfps_average,rfps_min,rfps_max,rfps_middlepoint);
-
-	if(g_bBenchmark)
-	{
-		string_path			fname;
-
-		if(xr_strlen(g_sBenchmarkName))
-			xr_sprintf	(fname,sizeof(fname),"%s.result",g_sBenchmarkName);
-		else
-			xr_strcpy	(fname,sizeof(fname),"benchmark.result");
-
-
-		FS.update_path		(fname,"$app_data_root$",fname);
-		CInifile			res		(fname,FALSE,FALSE,TRUE);
-		res.w_float			("general","renderer",	float(::Render->get_generation())/10.f,	"dx-level required"		);
-		res.w_float			("general","min",		rfps_min,								"absolute minimum"		);
-		res.w_float			("general","max",		rfps_max,								"absolute maximum"		);
-		res.w_float			("general","average",	rfps_average,							"average for this run"	);
-		res.w_float			("general","middle",	rfps_middlepoint,						"per-frame middle-point");
-		for (u32	it=1; itExecute	("quit");
-	}
+    if (!stat_started) return;
+
+    //g_SASH.EndBenchmark();
+
+    stat_started = FALSE;
+    float stat_total = stat_Timer_total.GetElapsed_sec();
+
+    float rfps_min, rfps_max, rfps_middlepoint, rfps_average;
+
+    // total
+    u32 dwFramesTotal = Device.dwFrame - stat_StartFrame;
+    rfps_average = float(dwFramesTotal) / stat_total;
+
+    // min/max/average
+    rfps_min = flt_max;
+    rfps_max = flt_min;
+    rfps_middlepoint = 0;
+
+    // Filtered FPS
+    const u32 iAvgFPS = _max((u32)rfps_average, 10);
+    const u32 WindowSize = _max(16, iAvgFPS / 2);
+
+    if (stat_table.size() > WindowSize * 4)
+    {
+        for (u32 it = 2; it < stat_table.size() - WindowSize + 1; it++)
+        {
+            float fTime = 0;
+            for (u32 i = 0; i < WindowSize; ++i)
+                fTime += stat_table[it + i];
+            float fps = WindowSize / fTime;
+            if (fps < rfps_min) rfps_min = fps;
+            if (fps > rfps_max) rfps_max = fps;
+            rfps_middlepoint += fps;
+        }
+
+        rfps_middlepoint /= float(stat_table.size() - 1 - WindowSize + 1);
+    }
+    else
+    {
+        for (u32 it = 1; it < stat_table.size(); it++)
+        {
+            float fps = 1.f / stat_table[it];
+            if (fps < rfps_min) rfps_min = fps;
+            if (fps > rfps_max) rfps_max = fps;
+            rfps_middlepoint += fps;
+        }
+        rfps_middlepoint /= float(stat_table.size() - 1);
+    }
+
+    /*
+    for (u32 it=1; itrfps_max) rfps_max = fps;
+    rfps_middlepoint += fps;
+    }
+    rfps_middlepoint /= float(stat_table.size()-1);
+    */
+
+    Msg("* [DEMO] FPS: average[%f], min[%f], max[%f], middle[%f]", rfps_average, rfps_min, rfps_max, rfps_middlepoint);
+
+    if (g_bBenchmark)
+    {
+        string_path fname;
+
+        if (xr_strlen(g_sBenchmarkName))
+            xr_sprintf(fname, sizeof(fname), "%s.result", g_sBenchmarkName);
+        else
+            xr_strcpy(fname, sizeof(fname), "benchmark.result");
+
+
+        FS.update_path(fname, "$app_data_root$", fname);
+        CInifile res(fname, FALSE, FALSE, TRUE);
+        res.w_float("general", "renderer", float(::Render->get_generation()) / 10.f, "dx-level required");
+        res.w_float("general", "min", rfps_min, "absolute minimum");
+        res.w_float("general", "max", rfps_max, "absolute maximum");
+        res.w_float("general", "average", rfps_average, "average for this run");
+        res.w_float("general", "middle", rfps_middlepoint, "per-frame middle-point");
+        for (u32 it = 1; it < stat_table.size(); it++)
+        {
+            string32 id;
+            xr_sprintf(id, sizeof(id), "%7d", it);
+            for (u32 c = 0; id[c]; c++) if (' ' == id[c]) id[c] = '0';
+            res.w_float("per_frame_stats", id, 1.f / stat_table[it]);
+        }
+
+        Console->Execute("quit");
+    }
 }
 
 #define FIX(a) while (a>=m_count) a-=m_count
-void spline1( float t, Fvector *p, Fvector *ret )
+void spline1(float t, Fvector* p, Fvector* ret)
 {
-	float     t2  = t * t;
-	float     t3  = t2 * t;
-	float     m[4];
-
-	ret->x=0.0f;
-	ret->y=0.0f;
-	ret->z=0.0f;
-	m[0] = ( 0.5f * ( (-1.0f * t3) + ( 2.0f * t2) + (-1.0f * t) ) );
-	m[1] = ( 0.5f * ( ( 3.0f * t3) + (-5.0f * t2) + ( 0.0f * t) + 2.0f ) );
-	m[2] = ( 0.5f * ( (-3.0f * t3) + ( 4.0f * t2) + ( 1.0f * t) ) );
-	m[3] = ( 0.5f * ( ( 1.0f * t3) + (-1.0f * t2) + ( 0.0f * t) ) );
-
-	for( int i=0; i<4; i++ )
-	{
-		ret->x += p[i].x * m[i];
-		ret->y += p[i].y * m[i];
-		ret->z += p[i].z * m[i];
-	}
+    float t2 = t * t;
+    float t3 = t2 * t;
+    float m[4];
+
+    ret->x = 0.0f;
+    ret->y = 0.0f;
+    ret->z = 0.0f;
+    m[0] = (0.5f * ((-1.0f * t3) + (2.0f * t2) + (-1.0f * t)));
+    m[1] = (0.5f * ((3.0f * t3) + (-5.0f * t2) + (0.0f * t) + 2.0f));
+    m[2] = (0.5f * ((-3.0f * t3) + (4.0f * t2) + (1.0f * t)));
+    m[3] = (0.5f * ((1.0f * t3) + (-1.0f * t2) + (0.0f * t)));
+
+    for (int i = 0; i < 4; i++)
+    {
+        ret->x += p[i].x * m[i];
+        ret->y += p[i].y * m[i];
+        ret->z += p[i].z * m[i];
+    }
 }
 
 BOOL CDemoPlay::ProcessCam(SCamEffectorInfo& info)
 {
-	// skeep a few frames before counting
-	if (Device.dwPrecacheFrame)	return	TRUE;
-
-	if (stat_started)
-	{
-		//g_SASH.DisplayFrame(Device.fTimeGlobal);
-	}
-	else
-	{
-		//g_SASH.StartBenchmark();
-		stat_Start();
-	}
-
-	// Per-frame statistics
-	{
-		stat_table.push_back		(stat_Timer_frame.GetElapsed_sec());
-		stat_Timer_frame.Start		();
-	}
-
-	// Process motion
-	if (m_pMotion)
-	{
-		Fvector R;
-		Fmatrix mRotate;
-		m_pMotion->_Evaluate	(m_MParam->Frame(),info.p,R);
-		m_MParam->Update		(Device.fTimeDelta,1.f,true);
-		fLifeTime				-= Device.fTimeDelta;
-		if (m_MParam->bWrapped)	{ stat_Stop(); stat_Start(); }
-		mRotate.setXYZi			(R.x,R.y,R.z);
-		info.d.set				(mRotate.k);
-		info.n.set				(mRotate.j);
-	}
-	else
-	{
-		if (seq.empty()) {
-			g_pGameLevel->Cameras().RemoveCamEffector(cefDemo);
-			return		TRUE;
-		}
-
-		fStartTime		+=	Device.fTimeDelta;
-		
-		float	ip;
-		float	p		=	fStartTime/fSpeed;
-		float	t		=	modff(p, &ip);
-		int		frame	=	iFloor(ip);
-		VERIFY	(t>=0);
-		
-		if (frame>=m_count)
-		{
-			dwCyclesLeft			--	;
-			if (0==dwCyclesLeft)	return FALSE;
-			fStartTime				= 0	;
-			// just continue
-			// stat_Stop			();
-			// stat_Start			();
-		}
-		
-		int f1=frame; FIX(f1);
-		int f2=f1+1;  FIX(f2);
-		int f3=f2+1;  FIX(f3);
-		int f4=f3+1;  FIX(f4);
-		
-		Fmatrix *m1,*m2,*m3,*m4;
-		Fvector v[4];
-		m1 = (Fmatrix *) &seq[f1];
-		m2 = (Fmatrix *) &seq[f2];
-		m3 = (Fmatrix *) &seq[f3];
-		m4 = (Fmatrix *) &seq[f4];
-		
-		for (int i=0; i<4; i++) {
-			v[0].x = m1->m[i][0]; v[0].y = m1->m[i][1];  v[0].z = m1->m[i][2];
-			v[1].x = m2->m[i][0]; v[1].y = m2->m[i][1];  v[1].z = m2->m[i][2];
-			v[2].x = m3->m[i][0]; v[2].y = m3->m[i][1];  v[2].z = m3->m[i][2];
-			v[3].x = m4->m[i][0]; v[3].y = m4->m[i][1];  v[3].z = m4->m[i][2];
-			spline1	( t, &(v[0]), (Fvector *) &(Device.mView.m[i][0]) );
-		}
-		
-		Fmatrix mInvCamera;
-		mInvCamera.invert(Device.mView);
-		info.n.set( mInvCamera._21, mInvCamera._22, mInvCamera._23 );
-		info.d.set( mInvCamera._31, mInvCamera._32, mInvCamera._33 );
-		info.p.set( mInvCamera._41, mInvCamera._42, mInvCamera._43 );
-		
-		fLifeTime-=Device.fTimeDelta;
-	}
-	return TRUE;
+    // skeep a few frames before counting
+    if (Device.dwPrecacheFrame) return TRUE;
+
+    if (stat_started)
+    {
+        //g_SASH.DisplayFrame(Device.fTimeGlobal);
+    }
+    else
+    {
+        //g_SASH.StartBenchmark();
+        stat_Start();
+    }
+
+    // Per-frame statistics
+    {
+        stat_table.push_back(stat_Timer_frame.GetElapsed_sec());
+        stat_Timer_frame.Start();
+    }
+
+    // Process motion
+    if (m_pMotion)
+    {
+        Fvector R;
+        Fmatrix mRotate;
+        m_pMotion->_Evaluate(m_MParam->Frame(), info.p, R);
+        m_MParam->Update(Device.fTimeDelta, 1.f, true);
+        fLifeTime -= Device.fTimeDelta;
+        if (m_MParam->bWrapped) { stat_Stop(); stat_Start(); }
+        mRotate.setXYZi(R.x, R.y, R.z);
+        info.d.set(mRotate.k);
+        info.n.set(mRotate.j);
+    }
+    else
+    {
+        if (seq.empty())
+        {
+            g_pGameLevel->Cameras().RemoveCamEffector(cefDemo);
+            return TRUE;
+        }
+
+        fStartTime += Device.fTimeDelta;
+
+        float ip;
+        float p = fStartTime / fSpeed;
+        float t = modff(p, &ip);
+        int frame = iFloor(ip);
+        VERIFY(t >= 0);
+
+        if (frame >= m_count)
+        {
+            dwCyclesLeft--;
+            if (0 == dwCyclesLeft) return FALSE;
+            fStartTime = 0;
+            // just continue
+            // stat_Stop ();
+            // stat_Start ();
+        }
+
+        int f1 = frame;
+        FIX(f1);
+        int f2 = f1 + 1;
+        FIX(f2);
+        int f3 = f2 + 1;
+        FIX(f3);
+        int f4 = f3 + 1;
+        FIX(f4);
+
+        Fmatrix* m1, *m2, *m3, *m4;
+        Fvector v[4];
+        m1 = (Fmatrix*)&seq[f1];
+        m2 = (Fmatrix*)&seq[f2];
+        m3 = (Fmatrix*)&seq[f3];
+        m4 = (Fmatrix*)&seq[f4];
+
+        for (int i = 0; i < 4; i++)
+        {
+            v[0].x = m1->m[i][0];
+            v[0].y = m1->m[i][1];
+            v[0].z = m1->m[i][2];
+            v[1].x = m2->m[i][0];
+            v[1].y = m2->m[i][1];
+            v[1].z = m2->m[i][2];
+            v[2].x = m3->m[i][0];
+            v[2].y = m3->m[i][1];
+            v[2].z = m3->m[i][2];
+            v[3].x = m4->m[i][0];
+            v[3].y = m4->m[i][1];
+            v[3].z = m4->m[i][2];
+            spline1(t, &(v[0]), (Fvector*)&(Device.mView.m[i][0]));
+        }
+
+        Fmatrix mInvCamera;
+        mInvCamera.invert(Device.mView);
+        info.n.set(mInvCamera._21, mInvCamera._22, mInvCamera._23);
+        info.d.set(mInvCamera._31, mInvCamera._32, mInvCamera._33);
+        info.p.set(mInvCamera._41, mInvCamera._42, mInvCamera._43);
+
+        fLifeTime -= Device.fTimeDelta;
+    }
+    return TRUE;
 }
diff --git a/src/xrEngine/FDemoPlay.h b/src/xrEngine/FDemoPlay.h
index ba373fa8619..420c6f47492 100644
--- a/src/xrEngine/FDemoPlay.h
+++ b/src/xrEngine/FDemoPlay.h
@@ -7,35 +7,35 @@
 #include "effector.h"
 
 // refs
-class	COMotion;
-struct	SAnimParams;
+class COMotion;
+struct SAnimParams;
 
 // class
-class ENGINE_API CDemoPlay :	public CEffectorCam
+class ENGINE_API CDemoPlay : public CEffectorCam
 {
-    COMotion*			m_pMotion			;
-    SAnimParams*		m_MParam			;
-
-	xr_vector	seq					;
-	int					m_count				;
-	float				fStartTime			;
-	float				fSpeed				;
-	u32					dwCyclesLeft		;
-
-	// statistics
-	BOOL				stat_started		;
-	CTimer				stat_Timer_frame	;
-	CTimer				stat_Timer_total	;
-	u32					stat_StartFrame		;
-	xr_vector	stat_table			;
-	
-	void				stat_Start	()		;
-	void				stat_Stop	()		;
+    COMotion* m_pMotion;
+    SAnimParams* m_MParam;
+
+    xr_vector seq;
+    int m_count;
+    float fStartTime;
+    float fSpeed;
+    u32 dwCyclesLeft;
+
+    // statistics
+    BOOL stat_started;
+    CTimer stat_Timer_frame;
+    CTimer stat_Timer_total;
+    u32 stat_StartFrame;
+    xr_vector stat_table;
+
+    void stat_Start();
+    void stat_Stop();
 public:
-	virtual BOOL		ProcessCam		(SCamEffectorInfo& info);
+    virtual BOOL ProcessCam(SCamEffectorInfo& info);
 
-						CDemoPlay	(const char *name, float ms, u32 cycles, float life_time=60*60*1000);
-	virtual				~CDemoPlay	();
+    CDemoPlay(const char* name, float ms, u32 cycles, float life_time = 60 * 60 * 1000);
+    virtual ~CDemoPlay();
 };
 
 #endif // !defined(AFX_FDEMOPLAY_H__9B07E6E0_FC3C_11D3_B4E3_4854E82A090D__INCLUDED_)
diff --git a/src/xrEngine/FDemoRecord.cpp b/src/xrEngine/FDemoRecord.cpp
index c49f4d56d70..72fc6ca03c2 100644
--- a/src/xrEngine/FDemoRecord.cpp
+++ b/src/xrEngine/FDemoRecord.cpp
@@ -12,529 +12,573 @@
 #include "CameraManager.h"
 
 extern BOOL g_bDisableRedText;
-static Flags32	s_hud_flag	= {0};
-static Flags32	s_dev_flags	= {0};
+static Flags32 s_hud_flag = {0};
+static Flags32 s_dev_flags = {0};
 
 BOOL stored_weapon;
 BOOL stored_cross;
 BOOL stored_red_text;
 
-CDemoRecord * xrDemoRecord = 0;
-CDemoRecord::force_position CDemoRecord:: g_position = { false, { 0, 0, 0 } };
+CDemoRecord* xrDemoRecord = 0;
+CDemoRecord::force_position CDemoRecord::g_position = {false, {0, 0, 0}};
 
 Fbox curr_lm_fbox;
 void setup_lm_screenshot_matrices()
 {
-	psHUD_Flags.assign	(0);
-
-	// build camera matrix
-	Fbox bb								= curr_lm_fbox;
-	bb.getcenter						(Device.vCameraPosition);
-
-	Device.vCameraDirection.set			( 0.f,-1.f,0.f	);
-	Device.vCameraTop.set				( 0.f,0.f,1.f	);
-	Device.vCameraRight.set				( 1.f,0.f,0.f	);
-	Device.mView.build_camera_dir		(Device.vCameraPosition,Device.vCameraDirection,Device.vCameraTop);
-
-	bb.xform					(Device.mView);
-	// build project matrix
-	Device.mProject.build_projection_ortho(	bb.max.x-bb.min.x,
-											bb.max.y-bb.min.y,
-											bb.min.z,
-											bb.max.z);
+    psHUD_Flags.assign(0);
+
+    // build camera matrix
+    Fbox bb = curr_lm_fbox;
+    bb.getcenter(Device.vCameraPosition);
+
+    Device.vCameraDirection.set(0.f, -1.f, 0.f);
+    Device.vCameraTop.set(0.f, 0.f, 1.f);
+    Device.vCameraRight.set(1.f, 0.f, 0.f);
+    Device.mView.build_camera_dir(Device.vCameraPosition, Device.vCameraDirection, Device.vCameraTop);
+
+    bb.xform(Device.mView);
+    // build project matrix
+    Device.mProject.build_projection_ortho(bb.max.x - bb.min.x,
+        bb.max.y - bb.min.y,
+        bb.min.z,
+        bb.max.z);
 }
 
 Fbox get_level_screenshot_bound()
 {
-	Fbox res			=  g_pGameLevel->ObjectSpace.GetBoundingVolume();
-	if(g_pGameLevel->pLevel->section_exist("level_map"))
-	{
-		Fvector4 res2d = g_pGameLevel->pLevel->r_fvector4("level_map","bound_rect");
-		res.min.x = res2d.x;
-		res.min.z = res2d.y;
-
-		res.max.x = res2d.z;
-		res.max.z = res2d.w;
-	}
-
-	return res;
+    Fbox res = g_pGameLevel->ObjectSpace.GetBoundingVolume();
+    if (g_pGameLevel->pLevel->section_exist("level_map"))
+    {
+        Fvector4 res2d = g_pGameLevel->pLevel->r_fvector4("level_map", "bound_rect");
+        res.min.x = res2d.x;
+        res.min.z = res2d.y;
+
+        res.max.x = res2d.z;
+        res.max.z = res2d.w;
+    }
+
+    return res;
 }
 void _InitializeFont(CGameFont*& F, LPCSTR section, u32 flags);
-CDemoRecord::CDemoRecord(const char *name,float life_time) : CEffectorCam(cefDemo,life_time/*,FALSE*/)
+CDemoRecord::CDemoRecord(const char* name, float life_time) : CEffectorCam(cefDemo, life_time/*,FALSE*/)
 {
-	stored_red_text = g_bDisableRedText;
-	g_bDisableRedText = TRUE;
-	m_iLMScreenshotFragment = -1;
-/*
-	stored_weapon = psHUD_Flags.test(HUD_WEAPON);
-	stored_cross = psHUD_Flags.test(HUD_CROSSHAIR);
-	psHUD_Flags.set(HUD_WEAPON, FALSE);
-	psHUD_Flags.set(HUD_CROSSHAIR, FALSE);
-*/
-	m_b_redirect_input_to_level = false;
-	_unlink	(name);
-	file	= FS.w_open	(name);
-	if (file) 
-	{
-		g_position.set_position  = false;
-		IR_Capture		();	// capture input
-		m_Camera.invert	(Device.mView);
-
-		// parse yaw
-		Fvector& dir	= m_Camera.k;
-		Fvector DYaw;	DYaw.set(dir.x,0.f,dir.z); DYaw.normalize_safe();
-		if (DYaw.x<0)	m_HPB.x = acosf(DYaw.z);
-		else			m_HPB.x = 2*PI-acosf(DYaw.z);
-
-		// parse pitch
-		dir.normalize_safe	();
-		m_HPB.y			= asinf(dir.y);
-		m_HPB.z			= 0;
-
-		m_Position.set	(m_Camera.c);
-
-		m_vVelocity.set	(0,0,0);
-		m_vAngularVelocity.set(0,0,0);
-		iCount			= 0;
-		
-		m_vT.set(0,0,0);
-		m_vR.set(0,0,0);
-		m_bMakeCubeMap		= FALSE;
-		m_bMakeScreenshot	= FALSE;
-		m_bMakeLevelMap		= FALSE;
-
-		m_fSpeed0		= pSettings->r_float("demo_record","speed0");
-		m_fSpeed1		= pSettings->r_float("demo_record","speed1");
-		m_fSpeed2		= pSettings->r_float("demo_record","speed2");
-		m_fSpeed3		= pSettings->r_float("demo_record","speed3");
-		m_fAngSpeed0	= pSettings->r_float("demo_record","ang_speed0");
-		m_fAngSpeed1	= pSettings->r_float("demo_record","ang_speed1");
-		m_fAngSpeed2	= pSettings->r_float("demo_record","ang_speed2");
-		m_fAngSpeed3	= pSettings->r_float("demo_record","ang_speed3");
-	} else {
-		fLifeTime = -1;
-	}
+    stored_red_text = g_bDisableRedText;
+    g_bDisableRedText = TRUE;
+    m_iLMScreenshotFragment = -1;
+    /*
+     stored_weapon = psHUD_Flags.test(HUD_WEAPON);
+     stored_cross = psHUD_Flags.test(HUD_CROSSHAIR);
+     psHUD_Flags.set(HUD_WEAPON, FALSE);
+     psHUD_Flags.set(HUD_CROSSHAIR, FALSE);
+     */
+    m_b_redirect_input_to_level = false;
+    _unlink(name);
+    file = FS.w_open(name);
+    if (file)
+    {
+        g_position.set_position = false;
+        IR_Capture(); // capture input
+        m_Camera.invert(Device.mView);
+
+        // parse yaw
+        Fvector& dir = m_Camera.k;
+        Fvector DYaw;
+        DYaw.set(dir.x, 0.f, dir.z);
+        DYaw.normalize_safe();
+        if (DYaw.x < 0) m_HPB.x = acosf(DYaw.z);
+        else m_HPB.x = 2 * PI - acosf(DYaw.z);
+
+        // parse pitch
+        dir.normalize_safe();
+        m_HPB.y = asinf(dir.y);
+        m_HPB.z = 0;
+
+        m_Position.set(m_Camera.c);
+
+        m_vVelocity.set(0, 0, 0);
+        m_vAngularVelocity.set(0, 0, 0);
+        iCount = 0;
+
+        m_vT.set(0, 0, 0);
+        m_vR.set(0, 0, 0);
+        m_bMakeCubeMap = FALSE;
+        m_bMakeScreenshot = FALSE;
+        m_bMakeLevelMap = FALSE;
+
+        m_fSpeed0 = pSettings->r_float("demo_record", "speed0");
+        m_fSpeed1 = pSettings->r_float("demo_record", "speed1");
+        m_fSpeed2 = pSettings->r_float("demo_record", "speed2");
+        m_fSpeed3 = pSettings->r_float("demo_record", "speed3");
+        m_fAngSpeed0 = pSettings->r_float("demo_record", "ang_speed0");
+        m_fAngSpeed1 = pSettings->r_float("demo_record", "ang_speed1");
+        m_fAngSpeed2 = pSettings->r_float("demo_record", "ang_speed2");
+        m_fAngSpeed3 = pSettings->r_float("demo_record", "ang_speed3");
+    }
+    else
+    {
+        fLifeTime = -1;
+    }
 }
 
 CDemoRecord::~CDemoRecord()
 {
-	if (file) 
-	{
-		IR_Release	();	// release input
-		FS.w_close	(file);
-	}
-	g_bDisableRedText	= stored_red_text;
-
-	Device.seqRender.Remove		( this		);
+    if (file)
+    {
+        IR_Release(); // release input
+        FS.w_close(file);
+    }
+    g_bDisableRedText = stored_red_text;
+
+    Device.seqRender.Remove(this);
 }
 
-//								+X,				-X,				+Y,				-Y,			+Z,				-Z
-static Fvector cmNorm[6]	= {{0.f,1.f,0.f}, {0.f,1.f,0.f}, {0.f,0.f,-1.f},{0.f,0.f,1.f}, {0.f,1.f,0.f}, {0.f,1.f,0.f}};
-static Fvector cmDir[6]		= {{1.f,0.f,0.f}, {-1.f,0.f,0.f},{0.f,1.f,0.f}, {0.f,-1.f,0.f},{0.f,0.f,1.f}, {0.f,0.f,-1.f}};
+// +X, -X, +Y, -Y, +Z, -Z
+static Fvector cmNorm[6] = {{0.f, 1.f, 0.f}, {0.f, 1.f, 0.f}, {0.f, 0.f, -1.f}, {0.f, 0.f, 1.f}, {0.f, 1.f, 0.f}, {0.f, 1.f, 0.f}};
+static Fvector cmDir[6] = {{1.f, 0.f, 0.f}, {-1.f, 0.f, 0.f}, {0.f, 1.f, 0.f}, {0.f, -1.f, 0.f}, {0.f, 0.f, 1.f}, {0.f, 0.f, -1.f}};
 
 
 void CDemoRecord::MakeScreenshotFace()
 {
-	switch (m_Stage){
-	case 0:
-		s_hud_flag.assign	(psHUD_Flags);
-		psHUD_Flags.assign	(0);
-	break;
-	case 1:
-		Render->Screenshot	();
-		psHUD_Flags.assign	(s_hud_flag);
-		m_bMakeScreenshot= FALSE;
-	break;
-	}
-	m_Stage++;
+    switch (m_Stage)
+    {
+    case 0:
+        s_hud_flag.assign(psHUD_Flags);
+        psHUD_Flags.assign(0);
+        break;
+    case 1:
+        Render->Screenshot();
+        psHUD_Flags.assign(s_hud_flag);
+        m_bMakeScreenshot = FALSE;
+        break;
+    }
+    m_Stage++;
 }
 
 
-void GetLM_BBox(Fbox &bb, INT Step)
+void GetLM_BBox(Fbox& bb, INT Step)
 {
-	float half_x = bb.min.x + (bb.max.x - bb.min.x)/2;
-	float half_z = bb.min.z + (bb.max.z - bb.min.z)/2;
-	switch (Step)
-	{
-	case 0:
-		{
-			bb.max.x = half_x;
-			bb.min.z = half_z;
-		}break;
-	case 1:
-		{
-			bb.min.x = half_x;
-			bb.min.z = half_z;
-		}break;
-	case 2:
-		{
-			bb.max.x = half_x;
-			bb.max.z = half_z;
-		}break;
-	case 3:
-		{
-			bb.min.x = half_x;
-			bb.max.z = half_z;
-		}break;
-	default:
-		{			
-		}break;
-		
-	}
+    float half_x = bb.min.x + (bb.max.x - bb.min.x) / 2;
+    float half_z = bb.min.z + (bb.max.z - bb.min.z) / 2;
+    switch (Step)
+    {
+    case 0:
+    {
+        bb.max.x = half_x;
+        bb.min.z = half_z;
+    }
+        break;
+    case 1:
+    {
+        bb.min.x = half_x;
+        bb.min.z = half_z;
+    }
+        break;
+    case 2:
+    {
+        bb.max.x = half_x;
+        bb.max.z = half_z;
+    }
+        break;
+    case 3:
+    {
+        bb.min.x = half_x;
+        bb.max.z = half_z;
+    }
+        break;
+    default:
+    {
+    } break;
+
+    }
 };
 
 void CDemoRecord::MakeLevelMapProcess()
 {
-	switch (m_Stage)
-	{
-	case 0:
-		{
-			s_dev_flags			= psDeviceFlags;
-			s_hud_flag.assign	(psHUD_Flags);
-			psDeviceFlags.zero	();
-			psDeviceFlags.set	(rsClearBB|rsFullscreen|rsDrawStatic,TRUE);
-			if (!psDeviceFlags.equal(s_dev_flags,rsFullscreen))
-				Device.Reset();
-
-		}break;
-
-	case DEVICE_RESET_PRECACHE_FRAME_COUNT+30:
-		{
-			setup_lm_screenshot_matrices		();
-
-			string_path					tmp;
-			if(m_iLMScreenshotFragment==-1)
-				xr_sprintf				(tmp, sizeof(tmp),"map_%s", *g_pGameLevel->name());
-			else
-				xr_sprintf				(tmp, sizeof(tmp),"map_%s#%d", *g_pGameLevel->name(), m_iLMScreenshotFragment);
-
-			if(m_iLMScreenshotFragment!=-1)
-			{
-				++m_iLMScreenshotFragment;
-				
-				if(m_iLMScreenshotFragment!=4)
-				{
-					curr_lm_fbox		= get_level_screenshot_bound();
-					GetLM_BBox			(curr_lm_fbox, m_iLMScreenshotFragment);
-					m_Stage				-= 20;
-				}
-			}
-
-			Render->Screenshot			(IRender_interface::SM_FOR_LEVELMAP,tmp);
-
-			if(m_iLMScreenshotFragment==-1 || m_iLMScreenshotFragment==4)
-			{
-				psHUD_Flags.assign			(s_hud_flag);
-
-				BOOL bDevReset				= !psDeviceFlags.equal(s_dev_flags,rsFullscreen);
-				psDeviceFlags				= s_dev_flags;
-				if (bDevReset)				Device.Reset();
-				m_bMakeLevelMap				= FALSE;
-				m_iLMScreenshotFragment		= -1;
-			}
-		}break;
-	default:
-		{
-			setup_lm_screenshot_matrices		();
-		}break;
-	}
-	m_Stage++;
+    switch (m_Stage)
+    {
+    case 0:
+    {
+        s_dev_flags = psDeviceFlags;
+        s_hud_flag.assign(psHUD_Flags);
+        psDeviceFlags.zero();
+        psDeviceFlags.set(rsClearBB | rsFullscreen | rsDrawStatic, TRUE);
+        if (!psDeviceFlags.equal(s_dev_flags, rsFullscreen))
+            Device.Reset();
+
+    }
+        break;
+
+    case DEVICE_RESET_PRECACHE_FRAME_COUNT + 30:
+    {
+        setup_lm_screenshot_matrices();
+
+        string_path tmp;
+        if (m_iLMScreenshotFragment == -1)
+            xr_sprintf(tmp, sizeof(tmp), "map_%s", *g_pGameLevel->name());
+        else
+            xr_sprintf(tmp, sizeof(tmp), "map_%s#%d", *g_pGameLevel->name(), m_iLMScreenshotFragment);
+
+        if (m_iLMScreenshotFragment != -1)
+        {
+            ++m_iLMScreenshotFragment;
+
+            if (m_iLMScreenshotFragment != 4)
+            {
+                curr_lm_fbox = get_level_screenshot_bound();
+                GetLM_BBox(curr_lm_fbox, m_iLMScreenshotFragment);
+                m_Stage -= 20;
+            }
+        }
+
+        Render->Screenshot(IRender_interface::SM_FOR_LEVELMAP, tmp);
+
+        if (m_iLMScreenshotFragment == -1 || m_iLMScreenshotFragment == 4)
+        {
+            psHUD_Flags.assign(s_hud_flag);
+
+            BOOL bDevReset = !psDeviceFlags.equal(s_dev_flags, rsFullscreen);
+            psDeviceFlags = s_dev_flags;
+            if (bDevReset) Device.Reset();
+            m_bMakeLevelMap = FALSE;
+            m_iLMScreenshotFragment = -1;
+        }
+    }
+        break;
+    default:
+    {
+        setup_lm_screenshot_matrices();
+    }
+        break;
+    }
+    m_Stage++;
 }
 
-void CDemoRecord::MakeCubeMapFace(Fvector &D, Fvector &N)
+void CDemoRecord::MakeCubeMapFace(Fvector& D, Fvector& N)
 {
-	string32 buf;
-	switch (m_Stage){
-	case 0:
-		N.set		(cmNorm[m_Stage]);
-		D.set		(cmDir[m_Stage]);
-		s_hud_flag.assign(psHUD_Flags);
-		psHUD_Flags.assign	(0);
-	break;
-	case 1:
-	case 2:
-	case 3:
-	case 4:
-	case 5:
-		N.set		(cmNorm[m_Stage]);
-		D.set		(cmDir[m_Stage]);
-		Render->Screenshot	(IRender_interface::SM_FOR_CUBEMAP,itoa(m_Stage,buf,10));
-	break;
-	case 6:
-		Render->Screenshot	(IRender_interface::SM_FOR_CUBEMAP,itoa(m_Stage,buf,10));
-		N.set		(m_Camera.j);
-		D.set		(m_Camera.k);
-		psHUD_Flags.assign(s_hud_flag);
-		m_bMakeCubeMap = FALSE;
-	break;
-	}
-	m_Stage++;
+    string32 buf;
+    switch (m_Stage)
+    {
+    case 0:
+        N.set(cmNorm[m_Stage]);
+        D.set(cmDir[m_Stage]);
+        s_hud_flag.assign(psHUD_Flags);
+        psHUD_Flags.assign(0);
+        break;
+    case 1:
+    case 2:
+    case 3:
+    case 4:
+    case 5:
+        N.set(cmNorm[m_Stage]);
+        D.set(cmDir[m_Stage]);
+        Render->Screenshot(IRender_interface::SM_FOR_CUBEMAP, itoa(m_Stage, buf, 10));
+        break;
+    case 6:
+        Render->Screenshot(IRender_interface::SM_FOR_CUBEMAP, itoa(m_Stage, buf, 10));
+        N.set(m_Camera.j);
+        D.set(m_Camera.k);
+        psHUD_Flags.assign(s_hud_flag);
+        m_bMakeCubeMap = FALSE;
+        break;
+    }
+    m_Stage++;
 }
 
 BOOL CDemoRecord::ProcessCam(SCamEffectorInfo& info)
 {
-	info.dont_apply					= false;
-	if (0==file)					return TRUE;
-
-	if (m_bMakeScreenshot)
-	{
-		MakeScreenshotFace();
-		// update camera
-		info.n.set(m_Camera.j);
-		info.d.set(m_Camera.k);
-		info.p.set(m_Camera.c);
-	}else if (m_bMakeLevelMap)
-	{
-		MakeLevelMapProcess();
-		info.dont_apply = true;
-	}else if (m_bMakeCubeMap)
-	{
-		MakeCubeMapFace	(info.d, info.n);
-		info.p.set		(m_Camera.c);
-		info.fAspect	= 1.f;
-	}else
-	{
-		if(IR_GetKeyState(DIK_F1))
-		{
-
-			pApp->pFontSystem->SetColor	(color_rgba(255,0,0,255));
-			pApp->pFontSystem->SetAligment(CGameFont::alCenter);
-			pApp->pFontSystem->OutSetI	(0,-.05f);
-			pApp->pFontSystem->OutNext	("%s","RECORDING");
-			pApp->pFontSystem->OutNext	("Key frames count: %d",iCount);
-			pApp->pFontSystem->SetAligment(CGameFont::alLeft);
-			pApp->pFontSystem->OutSetI	(-0.2f,+.05f);
-			pApp->pFontSystem->OutNext	("SPACE");
-			pApp->pFontSystem->OutNext	("BACK");
-			pApp->pFontSystem->OutNext	("ESC");
-			pApp->pFontSystem->OutNext	("F11");
-			pApp->pFontSystem->OutNext	("LCONTROL+F11");
-			pApp->pFontSystem->OutNext	("F12");
-			pApp->pFontSystem->SetAligment(CGameFont::alLeft);
-			pApp->pFontSystem->OutSetI	(0,+.05f);
-			pApp->pFontSystem->OutNext	("= Append Key");
-			pApp->pFontSystem->OutNext	("= Cube Map");
-			pApp->pFontSystem->OutNext	("= Quit");
-			pApp->pFontSystem->OutNext	("= Level Map ScreenShot");
-			pApp->pFontSystem->OutNext	("= Level Map ScreenShot(High Quality)");
-			pApp->pFontSystem->OutNext	("= ScreenShot");
-
-		}
-
-		m_vVelocity.lerp		(m_vVelocity,m_vT,0.3f);
-		m_vAngularVelocity.lerp	(m_vAngularVelocity,m_vR,0.3f);
-
-		float speed = m_fSpeed1, ang_speed = m_fAngSpeed1;
-
-		if (IR_GetKeyState(DIK_LSHIFT))		
-		{ 
-			speed=m_fSpeed0; 
-			ang_speed=m_fAngSpeed0;
-		}else 
-		if (IR_GetKeyState(DIK_LALT))		
-		{ 
-			speed=m_fSpeed2; 
-			ang_speed=m_fAngSpeed2;
-		}else 
-		if (IR_GetKeyState(DIK_LCONTROL)) 
-		{ 
-			speed=m_fSpeed3; 
-			ang_speed=m_fAngSpeed3;
-		}
-		
-		m_vT.mul				(m_vVelocity, Device.fTimeDelta * speed);
-		m_vR.mul				(m_vAngularVelocity, Device.fTimeDelta * ang_speed);
-
-		m_HPB.x -= m_vR.y;
-		m_HPB.y -= m_vR.x;
-		m_HPB.z += m_vR.z;
-		if(g_position.set_position)
-		{
-			m_Position.set(g_position.p);
-			g_position.set_position = false;
-		} else
-			g_position.p.set( m_Position );
-		// move
-		Fvector vmove;
-
-		vmove.set				(m_Camera.k);
-		vmove.normalize_safe	();
-		vmove.mul				(m_vT.z);
-		m_Position.add			(vmove);
-
-		vmove.set				(m_Camera.i);
-		vmove.normalize_safe	();
-		vmove.mul				(m_vT.x);
-		m_Position.add			(vmove);
-
-		vmove.set				(m_Camera.j);
-		vmove.normalize_safe	();
-		vmove.mul				(m_vT.y);
-		m_Position.add			(vmove);
-
-		m_Camera.setHPB			(m_HPB.x,m_HPB.y,m_HPB.z);
-		m_Camera.translate_over	(m_Position);
-
-		// update camera
-		info.n.set(m_Camera.j);
-		info.d.set(m_Camera.k);
-		info.p.set(m_Camera.c);
-
-		fLifeTime-=Device.fTimeDelta;
-
-		m_vT.set(0,0,0);
-		m_vR.set(0,0,0);
-	}
-	return TRUE;
+    info.dont_apply = false;
+    if (0 == file) return TRUE;
+
+    if (m_bMakeScreenshot)
+    {
+        MakeScreenshotFace();
+        // update camera
+        info.n.set(m_Camera.j);
+        info.d.set(m_Camera.k);
+        info.p.set(m_Camera.c);
+    }
+    else if (m_bMakeLevelMap)
+    {
+        MakeLevelMapProcess();
+        info.dont_apply = true;
+    }
+    else if (m_bMakeCubeMap)
+    {
+        MakeCubeMapFace(info.d, info.n);
+        info.p.set(m_Camera.c);
+        info.fAspect = 1.f;
+    }
+    else
+    {
+        if (IR_GetKeyState(DIK_F1))
+        {
+
+            pApp->pFontSystem->SetColor(color_rgba(255, 0, 0, 255));
+            pApp->pFontSystem->SetAligment(CGameFont::alCenter);
+            pApp->pFontSystem->OutSetI(0, -.05f);
+            pApp->pFontSystem->OutNext("%s", "RECORDING");
+            pApp->pFontSystem->OutNext("Key frames count: %d", iCount);
+            pApp->pFontSystem->SetAligment(CGameFont::alLeft);
+            pApp->pFontSystem->OutSetI(-0.2f, +.05f);
+            pApp->pFontSystem->OutNext("SPACE");
+            pApp->pFontSystem->OutNext("BACK");
+            pApp->pFontSystem->OutNext("ESC");
+            pApp->pFontSystem->OutNext("F11");
+            pApp->pFontSystem->OutNext("LCONTROL+F11");
+            pApp->pFontSystem->OutNext("F12");
+            pApp->pFontSystem->SetAligment(CGameFont::alLeft);
+            pApp->pFontSystem->OutSetI(0, +.05f);
+            pApp->pFontSystem->OutNext("= Append Key");
+            pApp->pFontSystem->OutNext("= Cube Map");
+            pApp->pFontSystem->OutNext("= Quit");
+            pApp->pFontSystem->OutNext("= Level Map ScreenShot");
+            pApp->pFontSystem->OutNext("= Level Map ScreenShot(High Quality)");
+            pApp->pFontSystem->OutNext("= ScreenShot");
+
+        }
+
+        m_vVelocity.lerp(m_vVelocity, m_vT, 0.3f);
+        m_vAngularVelocity.lerp(m_vAngularVelocity, m_vR, 0.3f);
+
+        float speed = m_fSpeed1, ang_speed = m_fAngSpeed1;
+
+        if (IR_GetKeyState(DIK_LSHIFT))
+        {
+            speed = m_fSpeed0;
+            ang_speed = m_fAngSpeed0;
+        }
+        else if (IR_GetKeyState(DIK_LALT))
+        {
+            speed = m_fSpeed2;
+            ang_speed = m_fAngSpeed2;
+        }
+        else if (IR_GetKeyState(DIK_LCONTROL))
+        {
+            speed = m_fSpeed3;
+            ang_speed = m_fAngSpeed3;
+        }
+
+        m_vT.mul(m_vVelocity, Device.fTimeDelta * speed);
+        m_vR.mul(m_vAngularVelocity, Device.fTimeDelta * ang_speed);
+
+        m_HPB.x -= m_vR.y;
+        m_HPB.y -= m_vR.x;
+        m_HPB.z += m_vR.z;
+        if (g_position.set_position)
+        {
+            m_Position.set(g_position.p);
+            g_position.set_position = false;
+        }
+        else
+            g_position.p.set(m_Position);
+        // move
+        Fvector vmove;
+
+        vmove.set(m_Camera.k);
+        vmove.normalize_safe();
+        vmove.mul(m_vT.z);
+        m_Position.add(vmove);
+
+        vmove.set(m_Camera.i);
+        vmove.normalize_safe();
+        vmove.mul(m_vT.x);
+        m_Position.add(vmove);
+
+        vmove.set(m_Camera.j);
+        vmove.normalize_safe();
+        vmove.mul(m_vT.y);
+        m_Position.add(vmove);
+
+        m_Camera.setHPB(m_HPB.x, m_HPB.y, m_HPB.z);
+        m_Camera.translate_over(m_Position);
+
+        // update camera
+        info.n.set(m_Camera.j);
+        info.d.set(m_Camera.k);
+        info.p.set(m_Camera.c);
+
+        fLifeTime -= Device.fTimeDelta;
+
+        m_vT.set(0, 0, 0);
+        m_vR.set(0, 0, 0);
+    }
+    return TRUE;
 }
 
-void CDemoRecord::IR_OnKeyboardPress	(int dik)
+void CDemoRecord::IR_OnKeyboardPress(int dik)
 {
-	if (dik == DIK_MULTIPLY)	m_b_redirect_input_to_level	= !m_b_redirect_input_to_level;
-
-	if(m_b_redirect_input_to_level)
-	{
-		g_pGameLevel->IR_OnKeyboardPress(dik);
-		return;
-	}
-	if (dik == DIK_GRAVE)
-							Console->Show			();
-	if (dik == DIK_SPACE)	RecordKey				();
-	if (dik == DIK_BACK)	MakeCubemap				();
-	if (dik == DIK_F11)		MakeLevelMapScreenshot	(IR_GetKeyState(DIK_LCONTROL));
-	if (dik == DIK_F12)		MakeScreenshot			();
-	if (dik == DIK_ESCAPE)	fLifeTime				= -1;
+    if (dik == DIK_MULTIPLY) m_b_redirect_input_to_level = !m_b_redirect_input_to_level;
+
+    if (m_b_redirect_input_to_level)
+    {
+        g_pGameLevel->IR_OnKeyboardPress(dik);
+        return;
+    }
+    if (dik == DIK_GRAVE)
+        Console->Show();
+    if (dik == DIK_SPACE) RecordKey();
+    if (dik == DIK_BACK) MakeCubemap();
+    if (dik == DIK_F11) MakeLevelMapScreenshot(IR_GetKeyState(DIK_LCONTROL));
+    if (dik == DIK_F12) MakeScreenshot();
+    if (dik == DIK_ESCAPE) fLifeTime = -1;
 
 #ifndef MASTER_GOLD
-	if (dik == DIK_RETURN)
-	{	
-		if (g_pGameLevel->CurrentEntity())
-		{
-			g_pGameLevel->CurrentEntity()->ForceTransform(m_Camera);
-			fLifeTime		= -1; 
-		}
-	}
+    if (dik == DIK_RETURN)
+    {
+        if (g_pGameLevel->CurrentEntity())
+        {
+            g_pGameLevel->CurrentEntity()->ForceTransform(m_Camera);
+            fLifeTime = -1;
+        }
+    }
 #endif // #ifndef MASTER_GOLD
 
-	if	(dik == DIK_PAUSE)		
-		Device.Pause(!Device.Paused(), TRUE, TRUE, "demo_record");
+    if (dik == DIK_PAUSE)
+        Device.Pause(!Device.Paused(), TRUE, TRUE, "demo_record");
 }
 
-static void update_whith_timescale( Fvector &v, const Fvector &v_delta )
+static void update_whith_timescale(Fvector& v, const Fvector& v_delta)
 {
-	VERIFY(!fis_zero(Device.time_factor()));
-	float scale = 1.f/Device.time_factor();
-	v.mad( v, v_delta, scale );
+    VERIFY(!fis_zero(Device.time_factor()));
+    float scale = 1.f / Device.time_factor();
+    v.mad(v, v_delta, scale);
 }
 
 
 
-void CDemoRecord::IR_OnKeyboardHold	(int dik)
+void CDemoRecord::IR_OnKeyboardHold(int dik)
 {
-	if(m_b_redirect_input_to_level)
-	{
-		g_pGameLevel->IR_OnKeyboardHold(dik);
-		return;
-	}
-	Fvector		vT_delta = Fvector().set(0,0,0);
-	Fvector		vR_delta = Fvector().set(0,0,0);
-
-	switch(dik){
-	case DIK_A:
-	case DIK_NUMPAD1:
-	case DIK_LEFT:		vT_delta.x -= 1.0f; break; // Slide Left
-	case DIK_D:
-	case DIK_NUMPAD3:
-	case DIK_RIGHT:		vT_delta.x += 1.0f; break; // Slide Right
-	case DIK_S:			vT_delta.y -= 1.0f; break; // Slide Down
-	case DIK_W:			vT_delta.y += 1.0f; break; // Slide Up
-	// rotate	
-	case DIK_NUMPAD2:	vR_delta.x -= 1.0f; break; // Pitch Down
-	case DIK_NUMPAD8:	vR_delta.x += 1.0f; break; // Pitch Up
-	case DIK_E:	
-	case DIK_NUMPAD6:	vR_delta.y += 1.0f; break; // Turn Left
-	case DIK_Q:	
-	case DIK_NUMPAD4:	vR_delta.y -= 1.0f; break; // Turn Right
-	case DIK_NUMPAD9:	vR_delta.z -= 2.0f; break; // Turn Right
-	case DIK_NUMPAD7:	vR_delta.z += 2.0f; break; // Turn Right
-	}
-
-	update_whith_timescale( m_vT, vT_delta );
-	update_whith_timescale( m_vR, vR_delta );
+    if (m_b_redirect_input_to_level)
+    {
+        g_pGameLevel->IR_OnKeyboardHold(dik);
+        return;
+    }
+    Fvector vT_delta = Fvector().set(0, 0, 0);
+    Fvector vR_delta = Fvector().set(0, 0, 0);
+
+    switch (dik)
+    {
+    case DIK_A:
+    case DIK_NUMPAD1:
+    case DIK_LEFT:
+        vT_delta.x -= 1.0f;
+        break; // Slide Left
+    case DIK_D:
+    case DIK_NUMPAD3:
+    case DIK_RIGHT:
+        vT_delta.x += 1.0f;
+        break; // Slide Right
+    case DIK_S:
+        vT_delta.y -= 1.0f;
+        break; // Slide Down
+    case DIK_W:
+        vT_delta.y += 1.0f;
+        break; // Slide Up
+        // rotate
+    case DIK_NUMPAD2:
+        vR_delta.x -= 1.0f;
+        break; // Pitch Down
+    case DIK_NUMPAD8:
+        vR_delta.x += 1.0f;
+        break; // Pitch Up
+    case DIK_E:
+    case DIK_NUMPAD6:
+        vR_delta.y += 1.0f;
+        break; // Turn Left
+    case DIK_Q:
+    case DIK_NUMPAD4:
+        vR_delta.y -= 1.0f;
+        break; // Turn Right
+    case DIK_NUMPAD9:
+        vR_delta.z -= 2.0f;
+        break; // Turn Right
+    case DIK_NUMPAD7:
+        vR_delta.z += 2.0f;
+        break; // Turn Right
+    }
+
+    update_whith_timescale(m_vT, vT_delta);
+    update_whith_timescale(m_vR, vR_delta);
 
 }
 
-void CDemoRecord::IR_OnMouseMove		(int dx, int dy)
+void CDemoRecord::IR_OnMouseMove(int dx, int dy)
 {
-	if(m_b_redirect_input_to_level)
-	{
-		g_pGameLevel->IR_OnMouseMove(dx, dy);
-		return;
-	}
-
-	Fvector		vR_delta = Fvector().set(0,0,0);
-
-	float scale			= .5f;//psMouseSens;
-	if (dx||dy){
-		vR_delta.y			+= float(dx)*scale; // heading
-		vR_delta.x			+= ((psMouseInvert.test(1))?-1:1)*float(dy)*scale*(3.f/4.f); // pitch
-	}
-	update_whith_timescale( m_vR, vR_delta );
+    if (m_b_redirect_input_to_level)
+    {
+        g_pGameLevel->IR_OnMouseMove(dx, dy);
+        return;
+    }
+
+    Fvector vR_delta = Fvector().set(0, 0, 0);
+
+    float scale = .5f;//psMouseSens;
+    if (dx || dy)
+    {
+        vR_delta.y += float(dx)*scale; // heading
+        vR_delta.x += ((psMouseInvert.test(1)) ? -1 : 1)*float(dy)*scale*(3.f / 4.f); // pitch
+    }
+    update_whith_timescale(m_vR, vR_delta);
 }
 
-void CDemoRecord::IR_OnMouseHold		(int btn)
+void CDemoRecord::IR_OnMouseHold(int btn)
 {
-	if(m_b_redirect_input_to_level)
-	{
-		g_pGameLevel->IR_OnMouseHold(btn);
-		return;
-	}
-	Fvector		vT_delta = Fvector().set(0,0,0);
-	switch (btn){
-	case 0:			vT_delta.z += 1.0f; break; // Move Backward
-	case 1:			vT_delta.z -= 1.0f; break; // Move Forward
-	}
-	update_whith_timescale( m_vT, vT_delta );
+    if (m_b_redirect_input_to_level)
+    {
+        g_pGameLevel->IR_OnMouseHold(btn);
+        return;
+    }
+    Fvector vT_delta = Fvector().set(0, 0, 0);
+    switch (btn)
+    {
+    case 0:
+        vT_delta.z += 1.0f;
+        break; // Move Backward
+    case 1:
+        vT_delta.z -= 1.0f;
+        break; // Move Forward
+    }
+    update_whith_timescale(m_vT, vT_delta);
 }
 
-void CDemoRecord::RecordKey			()
+void CDemoRecord::RecordKey()
 {
-	Fmatrix			g_matView;
- 
-	g_matView.invert(m_Camera);
-	file->w			(&g_matView,sizeof(Fmatrix));
-	iCount++;
+    Fmatrix g_matView;
+
+    g_matView.invert(m_Camera);
+    file->w(&g_matView, sizeof(Fmatrix));
+    iCount++;
 }
 
-void CDemoRecord::MakeCubemap		()
+void CDemoRecord::MakeCubemap()
 {
-	m_bMakeCubeMap	= TRUE;
-	m_Stage			= 0;
+    m_bMakeCubeMap = TRUE;
+    m_Stage = 0;
 }
 
-void CDemoRecord::MakeScreenshot	()
+void CDemoRecord::MakeScreenshot()
 {
-	m_bMakeScreenshot = TRUE;
-	m_Stage = 0;
+    m_bMakeScreenshot = TRUE;
+    m_Stage = 0;
 }
 
 void CDemoRecord::MakeLevelMapScreenshot(BOOL bHQ)
 {
-	Console->Execute("run_string level.set_weather(\"map\",true)");
-
-	if(!bHQ)
-		m_iLMScreenshotFragment = -1;
-	else
-		m_iLMScreenshotFragment	= 0;
-	
-	curr_lm_fbox		= get_level_screenshot_bound();
-	GetLM_BBox			(curr_lm_fbox, m_iLMScreenshotFragment);
-
-	m_bMakeLevelMap		= TRUE;
-	m_Stage				= 0;
+    Console->Execute("run_string level.set_weather(\"map\",true)");
+
+    if (!bHQ)
+        m_iLMScreenshotFragment = -1;
+    else
+        m_iLMScreenshotFragment = 0;
+
+    curr_lm_fbox = get_level_screenshot_bound();
+    GetLM_BBox(curr_lm_fbox, m_iLMScreenshotFragment);
+
+    m_bMakeLevelMap = TRUE;
+    m_Stage = 0;
 }
 
 void CDemoRecord::OnRender()
 {
-	pApp->pFontSystem->OnRender();
+    pApp->pFontSystem->OnRender();
 }
diff --git a/src/xrEngine/FDemoRecord.h b/src/xrEngine/FDemoRecord.h
index 41ed6f5af6a..f88652d4003 100644
--- a/src/xrEngine/FDemoRecord.h
+++ b/src/xrEngine/FDemoRecord.h
@@ -7,63 +7,63 @@
 #include "effector.h"
 
 class ENGINE_API CDemoRecord :
-	public CEffectorCam,
-	public IInputReceiver,
-	public pureRender
+    public CEffectorCam,
+    public IInputReceiver,
+    public pureRender
 {
 private:
-	static struct force_position 
-	{
-			bool	set_position;
-			Fvector p;
-	} g_position;
-	int			iCount;
-	IWriter*	file;
-	Fvector		m_HPB;
-	Fvector		m_Position;
-	Fmatrix		m_Camera;
-	u32			m_Stage;
+    static struct force_position
+    {
+        bool set_position;
+        Fvector p;
+    } g_position;
+    int iCount;
+    IWriter* file;
+    Fvector m_HPB;
+    Fvector m_Position;
+    Fmatrix m_Camera;
+    u32 m_Stage;
 
-	Fvector		m_vT;
-    Fvector		m_vR;
-	Fvector		m_vVelocity;
-	Fvector		m_vAngularVelocity;
+    Fvector m_vT;
+    Fvector m_vR;
+    Fvector m_vVelocity;
+    Fvector m_vAngularVelocity;
 
-	BOOL		m_bMakeCubeMap;
-	BOOL		m_bMakeScreenshot;
-	int			m_iLMScreenshotFragment;
-	BOOL		m_bMakeLevelMap;
+    BOOL m_bMakeCubeMap;
+    BOOL m_bMakeScreenshot;
+    int m_iLMScreenshotFragment;
+    BOOL m_bMakeLevelMap;
 
-	float		m_fSpeed0;
-	float		m_fSpeed1;
-	float		m_fSpeed2;
-	float		m_fSpeed3;
-	float		m_fAngSpeed0;
-	float		m_fAngSpeed1;
-	float		m_fAngSpeed2;
-	float		m_fAngSpeed3;
+    float m_fSpeed0;
+    float m_fSpeed1;
+    float m_fSpeed2;
+    float m_fSpeed3;
+    float m_fAngSpeed0;
+    float m_fAngSpeed1;
+    float m_fAngSpeed2;
+    float m_fAngSpeed3;
 
-	void		MakeCubeMapFace			(Fvector &D, Fvector &N);
-	void		MakeLevelMapProcess		();
-	void		MakeScreenshotFace		();
-	void		RecordKey				();
-	void		MakeCubemap				();
-	void		MakeScreenshot			();
-	void		MakeLevelMapScreenshot	(BOOL bHQ);
+    void MakeCubeMapFace(Fvector& D, Fvector& N);
+    void MakeLevelMapProcess();
+    void MakeScreenshotFace();
+    void RecordKey();
+    void MakeCubemap();
+    void MakeScreenshot();
+    void MakeLevelMapScreenshot(BOOL bHQ);
 public:
-				CDemoRecord				(const char *name, float life_time=60*60*1000);
-	virtual		~CDemoRecord();
+    CDemoRecord(const char* name, float life_time = 60 * 60 * 1000);
+    virtual ~CDemoRecord();
 
-	virtual void IR_OnKeyboardPress		(int dik);
-	virtual void IR_OnKeyboardHold		(int dik);
-	virtual void IR_OnMouseMove			(int dx, int dy);
-	virtual void IR_OnMouseHold			(int btn);
-	
-	virtual BOOL ProcessCam				(SCamEffectorInfo& info);
-	static	void SetGlobalPosition		( const Fvector &p ) { g_position.p.set(p), g_position.set_position= true; }
-	static	void GetGlobalPosition		( Fvector &p ) { p.set( g_position.p ); }
-	BOOL		 m_b_redirect_input_to_level;
-	virtual void OnRender				();
+    virtual void IR_OnKeyboardPress(int dik);
+    virtual void IR_OnKeyboardHold(int dik);
+    virtual void IR_OnMouseMove(int dx, int dy);
+    virtual void IR_OnMouseHold(int btn);
+
+    virtual BOOL ProcessCam(SCamEffectorInfo& info);
+    static void SetGlobalPosition(const Fvector& p) { g_position.p.set(p), g_position.set_position = true; }
+    static void GetGlobalPosition(Fvector& p) { p.set(g_position.p); }
+    BOOL m_b_redirect_input_to_level;
+    virtual void OnRender();
 };
 
 #endif // !defined(AFX_FDEMORECORD_H__D7638760_FB61_11D3_B4E3_4854E82A090D__INCLUDED_)
diff --git a/src/xrEngine/Feel_Sound.h b/src/xrEngine/Feel_Sound.h
index c638ad103a9..7afaf765b3e 100644
--- a/src/xrEngine/Feel_Sound.h
+++ b/src/xrEngine/Feel_Sound.h
@@ -4,9 +4,9 @@ class ENGINE_API CObject;
 
 namespace Feel
 {
-	class	ENGINE_API Sound
-	{
-	public:
-		virtual		void			feel_sound_new		(CObject* who, int type, CSound_UserDataPtr user_data, const Fvector& Position, float power) {};
-	};
+class ENGINE_API Sound
+{
+public:
+    virtual void feel_sound_new(CObject* who, int type, CSound_UserDataPtr user_data, const Fvector& Position, float power) {};
+};
 };
diff --git a/src/xrEngine/Feel_Touch.cpp b/src/xrEngine/Feel_Touch.cpp
index 5f2aecec71f..9151d4c4435 100644
--- a/src/xrEngine/Feel_Touch.cpp
+++ b/src/xrEngine/Feel_Touch.cpp
@@ -4,7 +4,7 @@
 #include "xr_object.h"
 using namespace Feel;
 
-Touch::Touch():pure_relcase(&Touch::feel_touch_relcase)
+Touch::Touch() :pure_relcase(&Touch::feel_touch_relcase)
 {
 }
 
@@ -12,82 +12,88 @@ Touch::~Touch()
 {
 }
 
-bool Touch::feel_touch_contact	(CObject* O)
-{ 
-	return true; 
+bool Touch::feel_touch_contact(CObject* O)
+{
+    return true;
 }
 
-void Touch::feel_touch_deny		(CObject* O, DWORD T)
+void Touch::feel_touch_deny(CObject* O, DWORD T)
 {
-	DenyTouch						D;
-	D.O								= O;
-	D.Expire						= Device.dwTimeGlobal + T;
-	feel_touch_disable.push_back	(D);
+    DenyTouch D;
+    D.O = O;
+    D.Expire = Device.dwTimeGlobal + T;
+    feel_touch_disable.push_back(D);
 }
 
-void Touch::feel_touch_update	(Fvector& C, float R)
+void Touch::feel_touch_update(Fvector& C, float R)
 {
-	// Check if denied objects expire in time
-	DWORD	dwT			= Device.dwTimeGlobal;
-	for (u32 dit=0; ditObjectSpace.GetNearest	(q_nearest,C,R, NULL);
-	xr_vector::iterator	n_begin	= q_nearest.begin	();
-	xr_vector::iterator	n_end	= q_nearest.end		();
-	if (n_end!=n_begin)						{
-		// Process results (NEW)
-		for (xr_vector::iterator it = n_begin; it!=n_end; it++){
-			CObject* O = *it;
-			if (O->getDestroy())		continue;							// Don't touch candidates for destroy
-			if (!feel_touch_contact(O))	continue;							// Actual contact
+    // Find nearest objects
+    q_nearest.clear_not_free();
+    q_nearest.reserve(feel_touch.size());
+    g_pGameLevel->ObjectSpace.GetNearest(q_nearest, C, R, NULL);
+    xr_vector::iterator n_begin = q_nearest.begin();
+    xr_vector::iterator n_end = q_nearest.end();
+    if (n_end != n_begin)
+    {
+        // Process results (NEW)
+        for (xr_vector::iterator it = n_begin; it != n_end; it++)
+        {
+            CObject* O = *it;
+            if (O->getDestroy()) continue; // Don't touch candidates for destroy
+            if (!feel_touch_contact(O)) continue; // Actual contact
 
-			if (std::find(feel_touch.begin(),feel_touch.end(),O) == feel_touch.end()){
-				// check for deny
-				BOOL bDeny = FALSE;
-				for (dit=0; ditgetDestroy() || !feel_touch_contact(O) || (std::find(n_begin,n_end,O) == n_end))	// Don't touch candidates for destroy
-		{
-			// _delete_
-			feel_touch.erase		(feel_touch.begin()+d);
-			feel_touch_delete		(O);
-			d--;
-		}
-	}
+    // Process results (DELETE)
+    for (int d = 0; dgetDestroy() || !feel_touch_contact(O) || (std::find(n_begin, n_end, O) == n_end)) // Don't touch candidates for destroy
+        {
+            // _delete_
+            feel_touch.erase(feel_touch.begin() + d);
+            feel_touch_delete(O);
+            d--;
+        }
+    }
 
-	//. Engine.Sheduler.Slice	();	
+    //. Engine.Sheduler.Slice ();
 }
 
-void Touch::feel_touch_relcase	(CObject* O)
+void Touch::feel_touch_relcase(CObject* O)
 {
-	xr_vector::iterator I = std::find (feel_touch.begin(),feel_touch.end(),O);
-	if (I!=feel_touch.end()){
-		feel_touch.erase		(I);
-		feel_touch_delete		(O);
-		}
-	xr_vector::iterator Id=feel_touch_disable.begin(),IdE=feel_touch_disable.end();
-	for(;Id!=IdE;++Id)			if((*Id).O==O )	{ feel_touch_disable.erase(Id); break; }
+    xr_vector::iterator I = std::find(feel_touch.begin(), feel_touch.end(), O);
+    if (I != feel_touch.end())
+    {
+        feel_touch.erase(I);
+        feel_touch_delete(O);
+    }
+    xr_vector::iterator Id = feel_touch_disable.begin(), IdE = feel_touch_disable.end();
+    for (; Id != IdE; ++Id) if ((*Id).O == O) { feel_touch_disable.erase(Id); break; }
 }
diff --git a/src/xrEngine/Feel_Touch.h b/src/xrEngine/Feel_Touch.h
index a02a0d651fc..978768fc80a 100644
--- a/src/xrEngine/Feel_Touch.h
+++ b/src/xrEngine/Feel_Touch.h
@@ -5,32 +5,32 @@
 class ENGINE_API CObject;
 namespace Feel
 {
-	class ENGINE_API Touch: private pure_relcase
-	{
-	public:
-		struct DenyTouch
-		{
-			CObject*	O;
-			DWORD		Expire;
-		};
-	protected:
-		xr_vector	feel_touch_disable;
+class ENGINE_API Touch : private pure_relcase
+{
+public:
+    struct DenyTouch
+    {
+        CObject* O;
+        DWORD Expire;
+    };
+protected:
+    xr_vector feel_touch_disable;
 
-	public:
-		xr_vector		feel_touch;
-		xr_vector		q_nearest;
+public:
+    xr_vector feel_touch;
+    xr_vector q_nearest;
 
-	public:
-		void __stdcall			feel_touch_relcase			(CObject* O);
+public:
+    void __stdcall feel_touch_relcase(CObject* O);
 
-	public:
-								Touch						();
-		virtual					~Touch						();
+public:
+    Touch();
+    virtual ~Touch();
 
-		virtual bool			feel_touch_contact			(CObject* O);
-		virtual void			feel_touch_update			(Fvector& P, float	R);
-		virtual void			feel_touch_deny				(CObject* O, DWORD	T);
-		virtual void			feel_touch_new				(CObject* O)			{	};
-		virtual void			feel_touch_delete			(CObject* O)			{	};
-	};
+    virtual bool feel_touch_contact(CObject* O);
+    virtual void feel_touch_update(Fvector& P, float R);
+    virtual void feel_touch_deny(CObject* O, DWORD T);
+    virtual void feel_touch_new(CObject* O) { };
+    virtual void feel_touch_delete(CObject* O) { };
+};
 };
diff --git a/src/xrEngine/Feel_Vision.cpp b/src/xrEngine/Feel_Vision.cpp
index f00d493a7bc..69759ed1052 100644
--- a/src/xrEngine/Feel_Vision.cpp
+++ b/src/xrEngine/Feel_Vision.cpp
@@ -6,249 +6,270 @@
 #include "igame_level.h"
 #include "cl_intersect.h"
 
-namespace Feel {
-
-	Vision::Vision( CObject const* owner ) : 
-		pure_relcase( &Vision::feel_vision_relcase ),
-		m_owner(owner)
-	{	
-	}
-
-	Vision::~Vision()
-	{	
-	}
-
-	struct SFeelParam	{
-		Vision*						parent;
-		Vision::feel_visible_Item*	item;
-		float						vis;
-		float						vis_threshold;
-		SFeelParam(Vision* _parent, Vision::feel_visible_Item* _item, float _vis_threshold):parent(_parent),item(_item),vis(1.f),vis_threshold(_vis_threshold){}
-	};
-	IC BOOL feel_vision_callback(collide::rq_result& result, LPVOID params)
-	{
-		SFeelParam* fp	= (SFeelParam*)params;
-		float vis		= fp->parent->feel_vision_mtl_transp(result.O, result.element);
-		fp->vis			*= vis;
-		if (NULL==result.O && fis_zero(vis)){
-			CDB::TRI* T	= g_pGameLevel->ObjectSpace.GetStaticTris()+result.element;
-			Fvector* V	= g_pGameLevel->ObjectSpace.GetStaticVerts();
-			fp->item->Cache.verts[0].set	(V[T->verts[0]]);
-			fp->item->Cache.verts[1].set	(V[T->verts[1]]);
-			fp->item->Cache.verts[2].set	(V[T->verts[2]]);
-		}
-		return (fp->vis>fp->vis_threshold); 
-	}
-	void	Vision::o_new		(CObject* O)
-	{
-		feel_visible.push_back	(feel_visible_Item());
-		feel_visible_Item&	I	= feel_visible.back();
-		I.O						= O;
-		I.Cache_vis				= 1.f;
-		I.Cache.verts[0].set	(0,0,0);
-		I.Cache.verts[1].set	(0,0,0);
-		I.Cache.verts[2].set	(0,0,0);
-		I.fuzzy					= -EPS_S;
-		I.cp_LP					= O->get_new_local_point_on_mesh( I.bone_id );
-		I.cp_LAST				= O->get_last_local_point_on_mesh( I.cp_LP, I.bone_id );
-	}
-	void	Vision::o_delete	(CObject* O)
-	{
-		xr_vector::iterator I=feel_visible.begin(),TE=feel_visible.end();
-		for (; I!=TE; I++)
-			if (I->O==O) {
-				feel_visible.erase(I);
-				return;
-			}
-	}
-
-	void	Vision::feel_vision_clear	()
-	{
-		seen.clear			();
-		query.clear			();
-		diff.clear			();
-		feel_visible.clear	();
-	}
-
-	void	Vision::feel_vision_relcase	(CObject* object)
-	{
-		xr_vector::iterator Io;
-		Io = std::find		(seen.begin(),seen.end(),object);
-		if (Io!=seen.end())	seen.erase	(Io);
-		Io = std::find		(query.begin(),query.end(),object);
-		if (Io!=query.end())query.erase	(Io);
-		Io = std::find		(diff.begin(),diff.end(),object);
-		if (Io!=diff.end())	diff.erase	(Io);
-		xr_vector::iterator Ii=feel_visible.begin(),IiE=feel_visible.end();
-		for (; Ii!=IiE; ++Ii)if (Ii->O==object){ feel_visible.erase(Ii); break; }
-	}
-
-	void	Vision::feel_vision_query	(Fmatrix& mFull, Fvector& P)
-	{
-		CFrustum								Frustum		;
-		Frustum.CreateFromMatrix				(mFull,FRUSTUM_P_LRTB|FRUSTUM_P_FAR);
-
-		// Traverse object database
-		r_spatial.clear_not_free				();
-		g_SpatialSpace->q_frustum
-			(
-			r_spatial,
-			0,
-			STYPE_VISIBLEFORAI,
-			Frustum
-			);
-
-		// Determine visibility for dynamic part of scene
-		seen.clear_and_reserve					()	;
-		for (u32 o_it=0; o_itdcast_CObject	();
-			if (object && feel_vision_isRelevant(object))	seen.push_back				(object);
-		}
-		if (seen.size()>1) 
-		{
-			std::sort							(seen.begin(),seen.end());
-			xr_vector::iterator end	= std::unique	(seen.begin(),seen.end());
-			if (end!=seen.end()) seen.erase		(end,seen.end());
-		}
-	}
-
-	void	Vision::feel_vision_update	(CObject* parent, Fvector& P, float dt, float vis_threshold)
-	{
-		// B-A = objects, that become visible
-		if (!seen.empty()) 
-		{
-			xr_vector::iterator E		= std::remove(seen.begin(),seen.end(),parent);
-			seen.resize			(E-seen.begin());
-
-			{
-				diff.resize	(_max(seen.size(),query.size()));
-				xr_vector::iterator	E = std::set_difference(
-					seen.begin(), seen.end(),
-					query.begin(),query.end(),
-					diff.begin() );
-				diff.resize(E-diff.begin());
-				for (u32 i=0; i::iterator	E = std::set_difference(
-				query.begin(),query.end(),
-				seen.begin(), seen.end(),
-				diff.begin() );
-			diff.resize(E-diff.begin());
-			for (u32 i=0; i::iterator I=feel_visible.begin(),E=feel_visible.end();
-		for (; I!=E; I++){
-			if (0==I->O->CFORM())	{ I->fuzzy = -1; continue; }
-
-			// verify relation
-//			if (positive(I->fuzzy) && I->O->Position().similar(I->cp_LR_dst,lr_granularity) && P.similar(I->cp_LR_src,lr_granularity))
-//				continue;
-
-			I->cp_LR_dst		= I->O->Position();
-			I->cp_LR_src		= P;
-			I->cp_LAST			= I->O->get_last_local_point_on_mesh( I->cp_LP, I->bone_id );
-
-			// 
-			Fvector				D, OP = I->cp_LAST;
-			D.sub				(OP,P);
-			if ( fis_zero(D.magnitude()) ) {
-				I->fuzzy		= 1.f;
-				continue;
-			}
-
-			float				f = D.magnitude() + .2f;
-			if (f>fuzzy_guaranteed){
-				D.div						(f);
-				// setup ray defs & feel params
-				collide::ray_defs RD		(P,D,f,CDB::OPT_CULL,collide::rq_target(collide::rqtStatic|/**/collide::rqtObject|/**/collide::rqtObstacle));
-				SFeelParam	feel_params		(this,&*I,vis_threshold);
-				// check cache
-				if (I->Cache.result&&I->Cache.similar(P,D,f)){
-					// similar with previous query
-					feel_params.vis			= I->Cache_vis;
-//					Log("cache 0");
-				}else{
-					float _u,_v,_range;
-					if (CDB::TestRayTri(P,D,I->Cache.verts,_u,_v,_range,false)&&(_range>0 && _rangeObjectSpace.RayQuery	(RQR, RD, feel_vision_callback, &feel_params, NULL, NULL))	{
-							I->Cache_vis	= feel_params.vis	;
-							I->Cache.set	(P,D,f,TRUE	)		;
-						}
-						else{
-//							feel_params.vis	= 0.f;
-//							I->Cache_vis	= feel_params.vis	;
-							I->Cache.set	(P,D,f,FALSE)		;
-						}
-//						Log("query");
-					}
-				}
-//				Log("Vis",feel_params.vis);
-				r_spatial.clear_not_free();
-				g_SpatialSpace->q_ray( r_spatial, 0, STYPE_VISIBLEFORAI, P, D, f );
-
-				RD.flags				= CDB::OPT_ONLYFIRST;
-
-				bool collision_found	= false;
-				xr_vector::const_iterator	i = r_spatial.begin();
-				xr_vector::const_iterator	e = r_spatial.end();
-				for ( ; i != e; ++i ) {
-					if ( *i == m_owner )
-						continue;
-
-					if ( *i == I->O )
-						continue;
-
-					CObject const* object	= (*i)->dcast_CObject();
-					RQR.r_clear				( );
-					if ( object && object->collidable.model && !object->collidable.model->_RayQuery(RD,RQR) )
-						continue;
-
-					collision_found		= true;
-					break;
-				}
-
-				if (collision_found)
-					feel_params.vis		= 0.f;
-
-				if (feel_params.visfuzzy				-=	fuzzy_update_novis*dt;
-					clamp					(I->fuzzy,-.5f,1.f);
-					I->cp_LP				= I->O->get_new_local_point_on_mesh( I->bone_id );
-				}else{
-					// VISIBLE
-					I->fuzzy				+=	fuzzy_update_vis*dt;
-					clamp					(I->fuzzy,-.5f,1.f);
-				}
-			}
-			else {
-				// VISIBLE, 'cause near
-				I->fuzzy				+=	fuzzy_update_vis*dt;
-				clamp					(I->fuzzy,-.5f,1.f);
-			}
-		}
-	}
+namespace Feel
+{
+
+Vision::Vision(CObject const* owner) :
+pure_relcase(&Vision::feel_vision_relcase),
+m_owner(owner)
+{
+}
+
+Vision::~Vision()
+{
+}
+
+struct SFeelParam
+{
+    Vision* parent;
+    Vision::feel_visible_Item* item;
+    float vis;
+    float vis_threshold;
+    SFeelParam(Vision* _parent, Vision::feel_visible_Item* _item, float _vis_threshold) :parent(_parent), item(_item), vis(1.f), vis_threshold(_vis_threshold) {}
+};
+IC BOOL feel_vision_callback(collide::rq_result& result, LPVOID params)
+{
+    SFeelParam* fp = (SFeelParam*)params;
+    float vis = fp->parent->feel_vision_mtl_transp(result.O, result.element);
+    fp->vis *= vis;
+    if (NULL == result.O && fis_zero(vis))
+    {
+        CDB::TRI* T = g_pGameLevel->ObjectSpace.GetStaticTris() + result.element;
+        Fvector* V = g_pGameLevel->ObjectSpace.GetStaticVerts();
+        fp->item->Cache.verts[0].set(V[T->verts[0]]);
+        fp->item->Cache.verts[1].set(V[T->verts[1]]);
+        fp->item->Cache.verts[2].set(V[T->verts[2]]);
+    }
+    return (fp->vis > fp->vis_threshold);
+}
+void Vision::o_new(CObject* O)
+{
+    feel_visible.push_back(feel_visible_Item());
+    feel_visible_Item& I = feel_visible.back();
+    I.O = O;
+    I.Cache_vis = 1.f;
+    I.Cache.verts[0].set(0, 0, 0);
+    I.Cache.verts[1].set(0, 0, 0);
+    I.Cache.verts[2].set(0, 0, 0);
+    I.fuzzy = -EPS_S;
+    I.cp_LP = O->get_new_local_point_on_mesh(I.bone_id);
+    I.cp_LAST = O->get_last_local_point_on_mesh(I.cp_LP, I.bone_id);
+}
+void Vision::o_delete(CObject* O)
+{
+    xr_vector::iterator I = feel_visible.begin(), TE = feel_visible.end();
+    for (; I != TE; I++)
+        if (I->O == O)
+        {
+        feel_visible.erase(I);
+        return;
+        }
+}
+
+void Vision::feel_vision_clear()
+{
+    seen.clear();
+    query.clear();
+    diff.clear();
+    feel_visible.clear();
+}
+
+void Vision::feel_vision_relcase(CObject* object)
+{
+    xr_vector::iterator Io;
+    Io = std::find(seen.begin(), seen.end(), object);
+    if (Io != seen.end()) seen.erase(Io);
+    Io = std::find(query.begin(), query.end(), object);
+    if (Io != query.end())query.erase(Io);
+    Io = std::find(diff.begin(), diff.end(), object);
+    if (Io != diff.end()) diff.erase(Io);
+    xr_vector::iterator Ii = feel_visible.begin(), IiE = feel_visible.end();
+    for (; Ii != IiE; ++Ii)if (Ii->O == object) { feel_visible.erase(Ii); break; }
+}
+
+void Vision::feel_vision_query(Fmatrix& mFull, Fvector& P)
+{
+    CFrustum Frustum;
+    Frustum.CreateFromMatrix(mFull, FRUSTUM_P_LRTB | FRUSTUM_P_FAR);
+
+    // Traverse object database
+    r_spatial.clear_not_free();
+    g_SpatialSpace->q_frustum
+        (
+        r_spatial,
+        0,
+        STYPE_VISIBLEFORAI,
+        Frustum
+        );
+
+    // Determine visibility for dynamic part of scene
+    seen.clear_and_reserve();
+    for (u32 o_it = 0; o_it < r_spatial.size(); o_it++)
+    {
+        ISpatial* spatial = r_spatial[o_it];
+        CObject* object = spatial->dcast_CObject();
+        if (object && feel_vision_isRelevant(object)) seen.push_back(object);
+    }
+    if (seen.size()>1)
+    {
+        std::sort(seen.begin(), seen.end());
+        xr_vector::iterator end = std::unique(seen.begin(), seen.end());
+        if (end != seen.end()) seen.erase(end, seen.end());
+    }
+}
+
+void Vision::feel_vision_update(CObject* parent, Fvector& P, float dt, float vis_threshold)
+{
+    // B-A = objects, that become visible
+    if (!seen.empty())
+    {
+        xr_vector::iterator E = std::remove(seen.begin(), seen.end(), parent);
+        seen.resize(E - seen.begin());
+
+        {
+            diff.resize(_max(seen.size(), query.size()));
+            xr_vector::iterator E = std::set_difference(
+                seen.begin(), seen.end(),
+                query.begin(), query.end(),
+                diff.begin());
+            diff.resize(E - diff.begin());
+            for (u32 i = 0; i < diff.size(); i++)
+                o_new(diff[i]);
+        }
+    }
+
+    // A-B = objects, that are invisible
+    if (!query.empty())
+    {
+        diff.resize(_max(seen.size(), query.size()));
+        xr_vector::iterator E = std::set_difference(
+            query.begin(), query.end(),
+            seen.begin(), seen.end(),
+            diff.begin());
+        diff.resize(E - diff.begin());
+        for (u32 i = 0; i < diff.size(); i++)
+            o_delete(diff[i]);
+    }
+
+    // Copy results and perform traces
+    query = seen;
+    o_trace(P, dt, vis_threshold);
+}
+void Vision::o_trace(Fvector& P, float dt, float vis_threshold)
+{
+    RQR.r_clear();
+    xr_vector::iterator I = feel_visible.begin(), E = feel_visible.end();
+    for (; I != E; I++)
+    {
+        if (0 == I->O->CFORM()) { I->fuzzy = -1; continue; }
+
+        // verify relation
+        // if (positive(I->fuzzy) && I->O->Position().similar(I->cp_LR_dst,lr_granularity) && P.similar(I->cp_LR_src,lr_granularity))
+        // continue;
+
+        I->cp_LR_dst = I->O->Position();
+        I->cp_LR_src = P;
+        I->cp_LAST = I->O->get_last_local_point_on_mesh(I->cp_LP, I->bone_id);
+
+        //
+        Fvector D, OP = I->cp_LAST;
+        D.sub(OP, P);
+        if (fis_zero(D.magnitude()))
+        {
+            I->fuzzy = 1.f;
+            continue;
+        }
+
+        float f = D.magnitude() + .2f;
+        if (f > fuzzy_guaranteed)
+        {
+            D.div(f);
+            // setup ray defs & feel params
+            collide::ray_defs RD(P, D, f, CDB::OPT_CULL, collide::rq_target(collide::rqtStatic |/**/collide::rqtObject |/**/collide::rqtObstacle));
+            SFeelParam feel_params(this, &*I, vis_threshold);
+            // check cache
+            if (I->Cache.result&&I->Cache.similar(P, D, f))
+            {
+                // similar with previous query
+                feel_params.vis = I->Cache_vis;
+                // Log("cache 0");
+            }
+            else
+            {
+                float _u, _v, _range;
+                if (CDB::TestRayTri(P, D, I->Cache.verts, _u, _v, _range, false) && (_range > 0 && _range < f))
+                {
+                    feel_params.vis = 0.f;
+                    // Log("cache 1");
+                }
+                else
+                {
+                    // cache outdated. real query.
+                    VERIFY(!fis_zero(RD.dir.magnitude()));
+
+                    if (g_pGameLevel->ObjectSpace.RayQuery(RQR, RD, feel_vision_callback, &feel_params, NULL, NULL))
+                    {
+                        I->Cache_vis = feel_params.vis;
+                        I->Cache.set(P, D, f, TRUE);
+                    }
+                    else
+                    {
+                        // feel_params.vis = 0.f;
+                        // I->Cache_vis = feel_params.vis ;
+                        I->Cache.set(P, D, f, FALSE);
+                    }
+                    // Log("query");
+                }
+            }
+            // Log("Vis",feel_params.vis);
+            r_spatial.clear_not_free();
+            g_SpatialSpace->q_ray(r_spatial, 0, STYPE_VISIBLEFORAI, P, D, f);
+
+            RD.flags = CDB::OPT_ONLYFIRST;
+
+            bool collision_found = false;
+            xr_vector::const_iterator i = r_spatial.begin();
+            xr_vector::const_iterator e = r_spatial.end();
+            for (; i != e; ++i)
+            {
+                if (*i == m_owner)
+                    continue;
+
+                if (*i == I->O)
+                    continue;
+
+                CObject const* object = (*i)->dcast_CObject();
+                RQR.r_clear();
+                if (object && object->collidable.model && !object->collidable.model->_RayQuery(RD, RQR))
+                    continue;
+
+                collision_found = true;
+                break;
+            }
+
+            if (collision_found)
+                feel_params.vis = 0.f;
+
+            if (feel_params.vis < feel_params.vis_threshold)
+            {
+                // INVISIBLE, choose next point
+                I->fuzzy -= fuzzy_update_novis*dt;
+                clamp(I->fuzzy, -.5f, 1.f);
+                I->cp_LP = I->O->get_new_local_point_on_mesh(I->bone_id);
+            }
+            else
+            {
+                // VISIBLE
+                I->fuzzy += fuzzy_update_vis*dt;
+                clamp(I->fuzzy, -.5f, 1.f);
+            }
+        }
+        else
+        {
+            // VISIBLE, 'cause near
+            I->fuzzy += fuzzy_update_vis*dt;
+            clamp(I->fuzzy, -.5f, 1.f);
+        }
+    }
+}
 };
diff --git a/src/xrEngine/Feel_Vision.h b/src/xrEngine/Feel_Vision.h
index 0c965bfc793..64e5e578b6f 100644
--- a/src/xrEngine/Feel_Vision.h
+++ b/src/xrEngine/Feel_Vision.h
@@ -10,60 +10,63 @@ class ISpatial;
 
 namespace Feel
 {
-	const float fuzzy_update_vis	= 1000.f;		// speed of fuzzy-logic desisions
-	const float fuzzy_update_novis	= 1000.f;		// speed of fuzzy-logic desisions
-	const float fuzzy_guaranteed	= 0.001f;		// distance which is supposed 100% visible
-	const float lr_granularity		= 0.1f;			// assume similar positions
+const float fuzzy_update_vis = 1000.f; // speed of fuzzy-logic desisions
+const float fuzzy_update_novis = 1000.f; // speed of fuzzy-logic desisions
+const float fuzzy_guaranteed = 0.001f; // distance which is supposed 100% visible
+const float lr_granularity = 0.1f; // assume similar positions
 
-	class ENGINE_API Vision: private pure_relcase
-	{
-	private:
-		xr_vector			seen;
-		xr_vector			query;
-		xr_vector			diff;
-		collide::rq_results			RQR;
-		xr_vector		r_spatial;
-		CObject const*				m_owner;
+class ENGINE_API Vision : private pure_relcase
+{
+private:
+    xr_vector seen;
+    xr_vector query;
+    xr_vector diff;
+    collide::rq_results RQR;
+    xr_vector r_spatial;
+    CObject const* m_owner;
 
-		void						o_new		(CObject* E);
-		void						o_delete	(CObject* E);
-		void						o_trace		(Fvector& P, float dt, float vis_threshold);
-	public:
-									Vision		(CObject const* owner);
-		virtual					~	Vision		();
-		struct	 feel_visible_Item 
-		{
-			collide::ray_cache	Cache;
-			Fvector				cp_LP;
-			Fvector				cp_LR_src;
-			Fvector				cp_LR_dst;
-			Fvector				cp_LAST;	// last point found to be visible
-			CObject*			O;
-			float				fuzzy;		// note range: (-1[no]..1[yes])
-			float				Cache_vis;
-			u16					bone_id;
-		};
-		xr_vector	feel_visible;
-	public:
-		void						feel_vision_clear		();
-		void						feel_vision_query		(Fmatrix& mFull,	Fvector& P);
-		void						feel_vision_update		(CObject* parent,	Fvector& P, float dt, float vis_threshold);
-		void	__stdcall			feel_vision_relcase		(CObject* object);
-		void						feel_vision_get			(xr_vector& R)		{
-			R.clear					();
-			xr_vector::iterator I=feel_visible.begin(),E=feel_visible.end();
-			for (; I!=E; I++)	if (positive(I->fuzzy)) R.push_back(I->O);
-		}
-		Fvector						feel_vision_get_vispoint(CObject* _O)					{
-			xr_vector::iterator I=feel_visible.begin(),E=feel_visible.end();
-			for (; I!=E; I++)		if (_O == I->O) {
-				VERIFY	(positive(I->fuzzy));
-				return	I->cp_LAST;
-			}
-			VERIFY2		(0, "There is no such object in the potentially visible list" );
-			return		Fvector().set(flt_max,flt_max,flt_max);
-		}
-		virtual		bool			feel_vision_isRelevant	(CObject* O)					= 0;
-		virtual		float			feel_vision_mtl_transp	(CObject* O, u32 element)		= 0;	
-	};
+    void o_new(CObject* E);
+    void o_delete(CObject* E);
+    void o_trace(Fvector& P, float dt, float vis_threshold);
+public:
+    Vision(CObject const* owner);
+    virtual ~Vision();
+    struct feel_visible_Item
+    {
+        collide::ray_cache Cache;
+        Fvector cp_LP;
+        Fvector cp_LR_src;
+        Fvector cp_LR_dst;
+        Fvector cp_LAST; // last point found to be visible
+        CObject* O;
+        float fuzzy; // note range: (-1[no]..1[yes])
+        float Cache_vis;
+        u16 bone_id;
+    };
+    xr_vector feel_visible;
+public:
+    void feel_vision_clear();
+    void feel_vision_query(Fmatrix& mFull, Fvector& P);
+    void feel_vision_update(CObject* parent, Fvector& P, float dt, float vis_threshold);
+    void __stdcall feel_vision_relcase(CObject* object);
+    void feel_vision_get(xr_vector& R)
+    {
+        R.clear();
+        xr_vector::iterator I = feel_visible.begin(), E = feel_visible.end();
+        for (; I != E; I++) if (positive(I->fuzzy)) R.push_back(I->O);
+    }
+    Fvector feel_vision_get_vispoint(CObject* _O)
+    {
+        xr_vector::iterator I = feel_visible.begin(), E = feel_visible.end();
+        for (; I != E; I++) if (_O == I->O)
+        {
+            VERIFY(positive(I->fuzzy));
+            return I->cp_LAST;
+        }
+        VERIFY2(0, "There is no such object in the potentially visible list");
+        return Fvector().set(flt_max, flt_max, flt_max);
+    }
+    virtual bool feel_vision_isRelevant(CObject* O) = 0;
+    virtual float feel_vision_mtl_transp(CObject* O, u32 element) = 0;
+};
 };
diff --git a/src/xrEngine/Fmesh.h b/src/xrEngine/Fmesh.h
index 6f1bf2cbf47..6b15999d793 100644
--- a/src/xrEngine/Fmesh.h
+++ b/src/xrEngine/Fmesh.h
@@ -2,152 +2,161 @@
 #define fmeshH
 #pragma once
 
-//BOOL ValidateIndices		(u32 vCount, u32 iCount, u16* pIndices);
+//BOOL ValidateIndices (u32 vCount, u32 iCount, u16* pIndices);
 
 ///////////////////////////////////////////////////////////////////////////////////////////////////////
 // MESH as it is represented in file
-enum MT {
-	MT_NORMAL				=0,
-	MT_HIERRARHY			=1,
-	MT_PROGRESSIVE			=2,
-	MT_SKELETON_ANIM		=3,
-	MT_SKELETON_GEOMDEF_PM	=4,
-	MT_SKELETON_GEOMDEF_ST	=5,
-	MT_LOD					=6,
-	MT_TREE_ST				=7,
-	MT_PARTICLE_EFFECT		=8,
-	MT_PARTICLE_GROUP		=9,
-	MT_SKELETON_RIGID		=10,
-	MT_TREE_PM				=11,
-
-	MT_3DFLUIDVOLUME		=12,
+enum MT
+{
+    MT_NORMAL = 0,
+    MT_HIERRARHY = 1,
+    MT_PROGRESSIVE = 2,
+    MT_SKELETON_ANIM = 3,
+    MT_SKELETON_GEOMDEF_PM = 4,
+    MT_SKELETON_GEOMDEF_ST = 5,
+    MT_LOD = 6,
+    MT_TREE_ST = 7,
+    MT_PARTICLE_EFFECT = 8,
+    MT_PARTICLE_GROUP = 9,
+    MT_SKELETON_RIGID = 10,
+    MT_TREE_PM = 11,
+
+    MT_3DFLUIDVOLUME = 12,
 };
 
-enum OGF_Chuncks {
-	OGF_HEADER				= 1,
-	OGF_TEXTURE				= 2,
-	OGF_VERTICES			= 3,
-	OGF_INDICES				= 4,
-	OGF_P_MAP				= 5,	//---------------------- unused
-	OGF_SWIDATA				= 6,
-	OGF_VCONTAINER			= 7, // not used ??
-	OGF_ICONTAINER			= 8, // not used ??
-    OGF_CHILDREN			= 9,	// * For skeletons only
-	OGF_CHILDREN_L			= 10,	// Link to child visuals
-	OGF_LODDEF2				= 11,	// + 5 channel data
-	OGF_TREEDEF2			= 12,	// + 5 channel data
-	OGF_S_BONE_NAMES		= 13,	// * For skeletons only
-	OGF_S_MOTIONS 			= 14,	// * For skeletons only
-	OGF_S_SMPARAMS  		= 15,	// * For skeletons only
-	OGF_S_IKDATA			= 16,	// * For skeletons only
-	OGF_S_USERDATA			= 17,	// * For skeletons only (Ini-file)
-	OGF_S_DESC				= 18,	// * For skeletons only
-	OGF_S_MOTION_REFS		= 19,	// * For skeletons only
-	OGF_SWICONTAINER		= 20,	// * SlidingWindowItem record container
-	OGF_GCONTAINER			= 21,	// * both VB&IB
-	OGF_FASTPATH			= 22,	// * extended/fast geometry
-	OGF_S_LODS 				= 23,	// * For skeletons only (Ini-file)
-	OGF_S_MOTION_REFS2		= 24,	// * changes in format
-	OGF_COLLISION_VERTICES	= 25,
-	OGF_COLLISION_INDICES	= 26,
-    OGF_forcedword			= 0xFFFFFFFF         
-};							
-
-enum OGF_SkeletonVertType	{
-	OGF_VERTEXFORMAT_FVF_1L	= 1*0x12071980,
-	OGF_VERTEXFORMAT_FVF_2L	= 2*0x12071980,
-	OGF_VERTEXFORMAT_FVF_3L	= 4*0x12071980,
-	OGF_VERTEXFORMAT_FVF_4L	= 5*0x12071980,
-	OGF_VERTEXFORMAT_FVF_NL	= 3*0x12071980,
+enum OGF_Chuncks
+{
+    OGF_HEADER = 1,
+    OGF_TEXTURE = 2,
+    OGF_VERTICES = 3,
+    OGF_INDICES = 4,
+    OGF_P_MAP = 5, //---------------------- unused
+    OGF_SWIDATA = 6,
+    OGF_VCONTAINER = 7, // not used ??
+    OGF_ICONTAINER = 8, // not used ??
+    OGF_CHILDREN = 9, // * For skeletons only
+    OGF_CHILDREN_L = 10, // Link to child visuals
+    OGF_LODDEF2 = 11, // + 5 channel data
+    OGF_TREEDEF2 = 12, // + 5 channel data
+    OGF_S_BONE_NAMES = 13, // * For skeletons only
+    OGF_S_MOTIONS = 14, // * For skeletons only
+    OGF_S_SMPARAMS = 15, // * For skeletons only
+    OGF_S_IKDATA = 16, // * For skeletons only
+    OGF_S_USERDATA = 17, // * For skeletons only (Ini-file)
+    OGF_S_DESC = 18, // * For skeletons only
+    OGF_S_MOTION_REFS = 19, // * For skeletons only
+    OGF_SWICONTAINER = 20, // * SlidingWindowItem record container
+    OGF_GCONTAINER = 21, // * both VB&IB
+    OGF_FASTPATH = 22, // * extended/fast geometry
+    OGF_S_LODS = 23, // * For skeletons only (Ini-file)
+    OGF_S_MOTION_REFS2 = 24, // * changes in format
+    OGF_COLLISION_VERTICES = 25,
+    OGF_COLLISION_INDICES = 26,
+    OGF_forcedword = 0xFFFFFFFF
 };
 
-const u16	xrOGF_SMParamsVersion	= 4;
+enum OGF_SkeletonVertType
+{
+    OGF_VERTEXFORMAT_FVF_1L = 1 * 0x12071980,
+    OGF_VERTEXFORMAT_FVF_2L = 2 * 0x12071980,
+    OGF_VERTEXFORMAT_FVF_3L = 4 * 0x12071980,
+    OGF_VERTEXFORMAT_FVF_4L = 5 * 0x12071980,
+    OGF_VERTEXFORMAT_FVF_NL = 3 * 0x12071980,
+};
+
+const u16 xrOGF_SMParamsVersion = 4;
 
 // OGF_DESC
-struct ECORE_API ogf_desc	{
-	shared_str	source_file;
-    shared_str	build_name;
-    time_t		build_time;
-    shared_str	create_name;
-    time_t		create_time;
-    shared_str	modif_name;
-    time_t		modif_time;
-    		ogf_desc():build_time(0),create_time(0),modif_time(0){}
-    void 	Load	(IReader& F);
-    void 	Save	(IWriter& F);
+struct ECORE_API ogf_desc
+{
+    shared_str source_file;
+    shared_str build_name;
+    time_t build_time;
+    shared_str create_name;
+    time_t create_time;
+    shared_str modif_name;
+    time_t modif_time;
+    ogf_desc() :build_time(0), create_time(0), modif_time(0) {}
+    void Load(IReader& F);
+    void Save(IWriter& F);
 };
 
 // OGF_BBOX
-struct ogf_bbox		{
-	Fvector min;
-	Fvector max;
+struct ogf_bbox
+{
+    Fvector min;
+    Fvector max;
 };
 
 // OGF_BSPHERE
-struct ogf_bsphere	{
-	Fvector c;
-	float	r;
+struct ogf_bsphere
+{
+    Fvector c;
+    float r;
 };
 
 // OGF_HEADER
-const u8	xrOGF_FormatVersion		= 4;
-struct ogf_header {
-	u8			format_version;			// = xrOGF_FormatVersion
-	u8			type;					// MT
-	u16			shader_id;				// should not be ZERO
-	ogf_bbox	bb;
-	ogf_bsphere	bs;
+const u8 xrOGF_FormatVersion = 4;
+struct ogf_header
+{
+    u8 format_version; // = xrOGF_FormatVersion
+    u8 type; // MT
+    u16 shader_id; // should not be ZERO
+    ogf_bbox bb;
+    ogf_bsphere bs;
 };
 
 // Sliding Window Record
-struct ENGINE_API	FSlideWindow		{
-	u32				offset;
-	u16				num_tris;
-	u16				num_verts;
+struct ENGINE_API FSlideWindow
+{
+    u32 offset;
+    u16 num_tris;
+    u16 num_verts;
 };
-struct ENGINE_API	FSlideWindowItem	{
-	FSlideWindow*	sw;
-	u32				count;
-	u32				reserved[4];
-	FSlideWindowItem() : sw(0),count(0)	{};
+struct ENGINE_API FSlideWindowItem
+{
+    FSlideWindow* sw;
+    u32 count;
+    u32 reserved[4];
+    FSlideWindowItem() : sw(0), count(0) {};
 };
 
 // OGF_TEXTURE1
-//  Z-String - name
-//  Z-String - shader
+// Z-String - name
+// Z-String - shader
 
 // OGF_TEXTURE_L
-//	u32 T_link
-//  u32 S_link
+// u32 T_link
+// u32 S_link
 
 // OGF_MATERIAL
-//  Fmaterial
+// Fmaterial
 
 // OGF_CHIELDS_L
-//	u32	Count
-//	u32	idx[0...Count-1]
+// u32 Count
+// u32 idx[0...Count-1]
 
 // OGF_VERTICES
-//	u32		dwVertType;			// Type of vertices it contains
-//	u32		dwVertCount;		// Count of vertices
-//	..vertices itself
+// u32 dwVertType; // Type of vertices it contains
+// u32 dwVertCount; // Count of vertices
+// ..vertices itself
 
 // OGF_INDICES
-//	u32		Count
-//  ..indices itself (u16[Count]);
+// u32 Count
+// ..indices itself (u16[Count]);
 
 // OGF_VCONTAINER
-// u32		CID;		// Container ID
-// u32		Offset;		// Add for every IDX and use as the start vertex
-// u32		Count;		// Number of vertices
+// u32 CID; // Container ID
+// u32 Offset; // Add for every IDX and use as the start vertex
+// u32 Count; // Number of vertices
 
 // OGF_BONES
-// BYTE			Count;
-// BYTE			Indices[...]
+// BYTE Count;
+// BYTE Indices[...]
 
 // OGF_TREEDEF
 // xform : matrix4x4
 // scale : vec4
-// bias  : vec4
+// bias : vec4
 
 #endif // fmeshH
diff --git a/src/xrEngine/Frustum.cpp b/src/xrEngine/Frustum.cpp
index 227b2080f54..a9d798774c1 100644
--- a/src/xrEngine/Frustum.cpp
+++ b/src/xrEngine/Frustum.cpp
@@ -4,430 +4,476 @@
 #include "Frustum.h"
 
 //////////////////////////////////////////////////////////////////////
-void			CFrustum::fplane::cache	()	{
-	if(positive(n.x)) {
-		if(positive(n.y)) {
-			if(positive(n.z))	aabb_overlap_id	= 0;
-			else				aabb_overlap_id	= 1;
-		} else {
-			if(positive(n.z))	aabb_overlap_id	= 2;
-			else				aabb_overlap_id = 3;
-		}
-	} else {
-		if(positive(n.y)) {
-			if(positive(n.z))	aabb_overlap_id = 4;
-			else				aabb_overlap_id = 5;
-		} else {
-			if(positive(n.z))	aabb_overlap_id = 6;
-			else				aabb_overlap_id = 7;
-		}
-	}
+void CFrustum::fplane::cache()
+{
+    if (positive(n.x))
+    {
+        if (positive(n.y))
+        {
+            if (positive(n.z)) aabb_overlap_id = 0;
+            else aabb_overlap_id = 1;
+        }
+        else
+        {
+            if (positive(n.z)) aabb_overlap_id = 2;
+            else aabb_overlap_id = 3;
+        }
+    }
+    else
+    {
+        if (positive(n.y))
+        {
+            if (positive(n.z)) aabb_overlap_id = 4;
+            else aabb_overlap_id = 5;
+        }
+        else
+        {
+            if (positive(n.z)) aabb_overlap_id = 6;
+            else aabb_overlap_id = 7;
+        }
+    }
 }
-void			CFrustum::_add			(Fplane &P) 
-{ 
-	VERIFY(p_countr) { test_mask=0; return fcvNone;}	// none  - return
-			if (_abs(cls)>=r) test_mask&=~bit;			// fully - no need to test this plane
-		}
-	}
-	return test_mask ? fcvPartial:fcvFully;
+    u32 bit = 1;
+    for (int i = 0; i < p_count; i++, bit <<= 1)
+    {
+        if (test_mask&bit)
+        {
+            float cls = planes[i].classify(c);
+            if (cls > r) { test_mask = 0; return fcvNone; } // none - return
+            if (_abs(cls) >= r) test_mask &= ~bit; // fully - no need to test this plane
+        }
+    }
+    return test_mask ? fcvPartial : fcvFully;
 }
 
-BOOL	CFrustum::testSphere_dirty		(Fvector& c, float r) const
+BOOL CFrustum::testSphere_dirty(Fvector& c, float r) const
 {
-	switch (p_count) {
-		case 12:if (planes[11].classify(c)>r)	return FALSE;
-		case 11:if (planes[10].classify(c)>r)	return FALSE;
-		case 10:if (planes[9].classify(c)>r)	return FALSE;
-		case 9:	if (planes[8].classify(c)>r)	return FALSE;
-		case 8:	if (planes[7].classify(c)>r)	return FALSE;
-		case 7:	if (planes[6].classify(c)>r)	return FALSE;
-		case 6:	if (planes[5].classify(c)>r)	return FALSE;
-		case 5:	if (planes[4].classify(c)>r)	return FALSE;
-		case 4:	if (planes[3].classify(c)>r)	return FALSE;
-		case 3:	if (planes[2].classify(c)>r)	return FALSE;
-		case 2:	if (planes[1].classify(c)>r)	return FALSE;
-		case 1:	if (planes[0].classify(c)>r)	return FALSE;
-		case 0:	break;
-		default:	NODEFAULT;
-	}
-	return TRUE;
+    switch (p_count)
+    {
+    case 12:
+        if (planes[11].classify(c) > r) return FALSE;
+    case 11:
+        if (planes[10].classify(c) > r) return FALSE;
+    case 10:
+        if (planes[9].classify(c) > r) return FALSE;
+    case 9:
+        if (planes[8].classify(c) > r) return FALSE;
+    case 8:
+        if (planes[7].classify(c) > r) return FALSE;
+    case 7:
+        if (planes[6].classify(c) > r) return FALSE;
+    case 6:
+        if (planes[5].classify(c) > r) return FALSE;
+    case 5:
+        if (planes[4].classify(c) > r) return FALSE;
+    case 4:
+        if (planes[3].classify(c) > r) return FALSE;
+    case 3:
+        if (planes[2].classify(c) > r) return FALSE;
+    case 2:
+        if (planes[1].classify(c) > r) return FALSE;
+    case 1:
+        if (planes[0].classify(c) > r) return FALSE;
+    case 0:
+        break;
+    default:
+        NODEFAULT;
+    }
+    return TRUE;
 }
 
-EFC_Visible	CFrustum::testAABB			(const float* mM, u32& test_mask) const
+EFC_Visible CFrustum::testAABB(const float* mM, u32& test_mask) const
 {
-	// go for trivial rejection or acceptance using "faster overlap test"
-	u32		bit = 1;
-
-	for (int i=0; ir) { test_mask=0; return fcvNone;}	// none  - return
-			if (_abs(cls)>=r) test_mask&=~bit;			// fully - no need to test this plane
-			else {
-				EFC_Visible	r	= AABB_OverlapPlane(planes[i],mM);
-				if (fcvFully==r)	test_mask&=~bit;					// fully - no need to test this plane
-				else if (fcvNone==r){ test_mask=0; return fcvNone;	}	// none - return
-			}
-		}
-	}
-	return test_mask ? fcvPartial:fcvFully;
+    u32 bit = 1;
+    for (int i = 0; i < p_count; i++, bit <<= 1)
+    {
+        if (test_mask&bit)
+        {
+            float cls = planes[i].classify(c);
+            if (cls > r) { test_mask = 0; return fcvNone; } // none - return
+            if (_abs(cls) >= r) test_mask &= ~bit; // fully - no need to test this plane
+            else
+            {
+                EFC_Visible r = AABB_OverlapPlane(planes[i], mM);
+                if (fcvFully == r) test_mask &= ~bit; // fully - no need to test this plane
+                else if (fcvNone == r) { test_mask = 0; return fcvNone; } // none - return
+            }
+        }
+    }
+    return test_mask ? fcvPartial : fcvFully;
 }
 
-BOOL		CFrustum::testPolyInside_dirty(Fvector* p, int count) const
+BOOL CFrustum::testPolyInside_dirty(Fvector* p, int count) const
 {
-	Fvector* e = p+count;
-	for (int i=0; i0) return false;
-	}
-	return true;
+    Fvector* e = p + count;
+    for (int i = 0; i < p_count; i++)
+    {
+        const fplane& P = planes[i];
+        for (Fvector* I = p; I != e; I++)
+            if (P.classify(*I) > 0) return false;
+    }
+    return true;
 }
 
 //////////////////////////////////////////////////////////////////////
 void CFrustum::CreateFromPoints(Fvector* p, int count, Fvector& COP)
 {
-	VERIFY(count=3);
+    VERIFY(count < FRUSTUM_MAXPLANES);
+    VERIFY(count >= 3);
 
-	_clear();
-	for (int i=1; isize()>6) {
-		SimplifyPoly_AABB(poly,P);
-		P.build_precise	((*poly)[0],(*poly)[1],(*poly)[2]);
-	}
-
-	// Check plane orientation relative to viewer
-	// and reverse if needed
-	if (P.classify(vBase)<0)
-	{
-		std::reverse(poly->begin(),poly->end());
-		P.build_precise	((*poly)[0],(*poly)[1],(*poly)[2]);
-	}
-
-	// Base creation
-	CreateFromPoints(poly->begin(),poly->size(),vBase);
-
-	// Near clipping plane
-	_add		(P);
-
-	// Far clipping plane
-	Fmatrix &M	= mFullXFORM;
-	P.n.x		= -(M._14 - M._13);
-	P.n.y		= -(M._24 - M._23);
-	P.n.z		= -(M._34 - M._33);
-	P.d			= -(M._44 - M._43);
-	float denom = 1.0f / P.n.magnitude();
-	P.n.x		*= denom;
-	P.n.y		*= denom;
-	P.n.z		*= denom;
-	P.d			*= denom;
-	_add		(P);
+    Fplane P;
+    P.build_precise((*poly)[0], (*poly)[1], (*poly)[2]);
+
+    if (poly->size()>6)
+    {
+        SimplifyPoly_AABB(poly, P);
+        P.build_precise((*poly)[0], (*poly)[1], (*poly)[2]);
+    }
+
+    // Check plane orientation relative to viewer
+    // and reverse if needed
+    if (P.classify(vBase) < 0)
+    {
+        std::reverse(poly->begin(), poly->end());
+        P.build_precise((*poly)[0], (*poly)[1], (*poly)[2]);
+    }
+
+    // Base creation
+    CreateFromPoints(poly->begin(), poly->size(), vBase);
+
+    // Near clipping plane
+    _add(P);
+
+    // Far clipping plane
+    Fmatrix& M = mFullXFORM;
+    P.n.x = -(M._14 - M._13);
+    P.n.y = -(M._24 - M._23);
+    P.n.z = -(M._34 - M._33);
+    P.d = -(M._44 - M._43);
+    float denom = 1.0f / P.n.magnitude();
+    P.n.x *= denom;
+    P.n.y *= denom;
+    P.n.z *= denom;
+    P.d *= denom;
+    _add(P);
 }
 
 void CFrustum::SimplifyPoly_AABB(sPoly* poly, Fplane& plane)
 {
-	Fmatrix		mView,mInv;
-	Fvector		from,up,right,y;
-	from.set	((*poly)[0]);
-	y.set		(0,1,0);
-	if (_abs(plane.n.y)>0.99f) y.set(1,0,0);
-	right.crossproduct		(y,plane.n);
-	up.crossproduct			(plane.n,right);
-	mView.build_camera_dir	(from,plane.n,up);
-
-	// Project and find extents
-	Fvector2	min,max;
-	min.set		(flt_max,flt_max);
-	max.set		(flt_min,flt_min);
-	for (u32 i=0; isize(); i++)
-	{
-		Fvector2 tmp;
-		mView.transform_tiny32(tmp,(*poly)[i]);
-		min.min(tmp.x,tmp.y);
-		max.max(tmp.x,tmp.y);
-	}
-
-	// Build other 2 points and inverse project
-	Fvector2	p1,p2;
-	p1.set		(min.x,max.y);
-	p2.set		(max.x,min.y);
-	mInv.invert	(mView);
-	poly->clear	();
-
-	mInv.transform_tiny23(poly->last(),min);	poly->inc();
-	mInv.transform_tiny23(poly->last(),p1);		poly->inc();
-	mInv.transform_tiny23(poly->last(),max);	poly->inc();
-	mInv.transform_tiny23(poly->last(),p2);		poly->inc();
+    Fmatrix mView, mInv;
+    Fvector from, up, right, y;
+    from.set((*poly)[0]);
+    y.set(0, 1, 0);
+    if (_abs(plane.n.y) > 0.99f) y.set(1, 0, 0);
+    right.crossproduct(y, plane.n);
+    up.crossproduct(plane.n, right);
+    mView.build_camera_dir(from, plane.n, up);
+
+    // Project and find extents
+    Fvector2 min, max;
+    min.set(flt_max, flt_max);
+    max.set(flt_min, flt_min);
+    for (u32 i = 0; i < poly->size(); i++)
+    {
+        Fvector2 tmp;
+        mView.transform_tiny32(tmp, (*poly)[i]);
+        min.min(tmp.x, tmp.y);
+        max.max(tmp.x, tmp.y);
+    }
+
+    // Build other 2 points and inverse project
+    Fvector2 p1, p2;
+    p1.set(min.x, max.y);
+    p2.set(max.x, min.y);
+    mInv.invert(mView);
+    poly->clear();
+
+    mInv.transform_tiny23(poly->last(), min);
+    poly->inc();
+    mInv.transform_tiny23(poly->last(), p1);
+    poly->inc();
+    mInv.transform_tiny23(poly->last(), max);
+    poly->inc();
+    mInv.transform_tiny23(poly->last(), p2);
+    poly->inc();
 }
 
 void CFrustum::CreateOccluder(Fvector* p, int count, Fvector& vBase, CFrustum& clip)
 {
-	VERIFY(count=3);
-
-	BOOL	edge[FRUSTUM_SAFE];
-	float	cls	[FRUSTUM_SAFE];
-	ZeroMemory	(edge,sizeof(edge));
-	for (int i=0; i=count) next=0;
-				if (cls[next]=count) next=0;
-			_add(vBase,p[i],p[next]);
-		}
-	}
+    VERIFY(count < FRUSTUM_SAFE);
+    VERIFY(count >= 3);
+
+    BOOL edge[FRUSTUM_SAFE];
+    float cls[FRUSTUM_SAFE];
+    ZeroMemory(edge, sizeof(edge));
+    for (int i = 0; i < clip.p_count; i++)
+    {
+        // classify all points relative to plane #i
+        fplane& P = clip.planes[i];
+        for (int j = 0; j < count; j++) cls[j] = _abs(P.classify(p[j]));
+
+        // test edges to see which lies directly on plane
+        for (j = 0; j < count; j++)
+        {
+            if (cls[j] < EPS_L)
+            {
+                int next = j + 1;
+                if (next >= count) next = 0;
+                if (cls[next] < EPS_L)
+                {
+                    // both points lies on plane - mark as 'open'
+                    edge[j] = true;
+                }
+            }
+        }
+    }
+
+    // here we have all edges marked accordenly to 'open' / 'closed' classification
+    _clear();
+    _add(p[0], p[1], p[2]); // main plane
+    for (i = 0; i < count; i++)
+    {
+        if (!edge[i])
+        {
+            int next = i + 1;
+            if (next >= count) next = 0;
+            _add(vBase, p[i], p[next]);
+        }
+    }
 }
 
-sPoly*	CFrustum::ClipPoly(sPoly& S, sPoly& D) const
+sPoly* CFrustum::ClipPoly(sPoly& S, sPoly& D) const
 {
-	sPoly*	src		= &D;
-	sPoly*	dest	= &S;
-	for (int i=0; iclear		();
-
-		// classify all points relative to plane #i
-		float	cls	[FRUSTUM_SAFE];
-		for (u32 j=0; jsize(); j++) cls[j]=P.classify((*src)[j]);
-
-		// clip everything to this plane
-		cls[src->size()] = cls[0];
-		src->push_back((*src)[0]);
-		Fvector D; float denum,t;
-		for (j=0; jsize()-1; j++)
-		{
-			if ((*src)[j].similar((*src)[j+1],EPS_S)) continue;
-
-			if (negative(cls[j]))
-			{
-				dest->push_back((*src)[j]);
-				if (positive(cls[j+1]))
-				{
-					// segment intersects plane
-					D.sub((*src)[j+1],(*src)[j]);
-					denum = P.n.dotproduct(D);
-					if (denum!=0) {
-						t = -cls[j]/denum; //VERIFY(t<=1.f && t>=0);
-						dest->last().mad((*src)[j],D,t);
-						dest->inc();
-					}
-				}
-			} else {
-				// J - outside
-				if (negative(cls[j+1]))
-				{
-					// J+1  - inside
-					// segment intersects plane
-					D.sub((*src)[j+1],(*src)[j]);
-					denum = P.n.dotproduct(D);
-					if (denum!=0) {
-						t = -cls[j]/denum; //VERIFY(t<=1.f && t>=0);
-						dest->last().mad((*src)[j],D,t);
-						dest->inc();
-					}
-				}
-			}
-		}
-
-		// here we end up with complete polygon in 'dest' which is inside plane #i
-		if (dest->size()<3) return 0;
-	}
-	return dest;
+    sPoly* src = &D;
+    sPoly* dest = &S;
+    for (int i = 0; i < p_count; i++)
+    {
+        // cache plane and swap lists
+        const fplane& P = planes[i];
+        std::swap(src, dest);
+        dest->clear();
+
+        // classify all points relative to plane #i
+        float cls[FRUSTUM_SAFE];
+        for (u32 j = 0; j < src->size(); j++) cls[j] = P.classify((*src)[j]);
+
+        // clip everything to this plane
+        cls[src->size()] = cls[0];
+        src->push_back((*src)[0]);
+        Fvector D;
+        float denum, t;
+        for (j = 0; j < src->size() - 1; j++)
+        {
+            if ((*src)[j].similar((*src)[j + 1], EPS_S)) continue;
+
+            if (negative(cls[j]))
+            {
+                dest->push_back((*src)[j]);
+                if (positive(cls[j + 1]))
+                {
+                    // segment intersects plane
+                    D.sub((*src)[j + 1], (*src)[j]);
+                    denum = P.n.dotproduct(D);
+                    if (denum != 0)
+                    {
+                        t = -cls[j] / denum; //VERIFY(t<=1.f && t>=0);
+                        dest->last().mad((*src)[j], D, t);
+                        dest->inc();
+                    }
+                }
+            }
+            else
+            {
+                // J - outside
+                if (negative(cls[j + 1]))
+                {
+                    // J+1 - inside
+                    // segment intersects plane
+                    D.sub((*src)[j + 1], (*src)[j]);
+                    denum = P.n.dotproduct(D);
+                    if (denum != 0)
+                    {
+                        t = -cls[j] / denum; //VERIFY(t<=1.f && t>=0);
+                        dest->last().mad((*src)[j], D, t);
+                        dest->inc();
+                    }
+                }
+            }
+        }
+
+        // here we end up with complete polygon in 'dest' which is inside plane #i
+        if (dest->size() < 3) return 0;
+    }
+    return dest;
 }
 
 BOOL CFrustum::CreateFromClipPoly(Fvector* p, int count, Fvector& vBase, CFrustum& clip)
 {
-	VERIFY(count=3);
+    VERIFY(count < FRUSTUM_MAXPLANES);
+    VERIFY(count >= 3);
 
-	sPoly	poly1	(p,count);
-	sPoly	poly2;
-	sPoly*	dest	= clip.ClipPoly(poly1,poly2);
+    sPoly poly1(p, count);
+    sPoly poly2;
+    sPoly* dest = clip.ClipPoly(poly1, poly2);
 
-	// here we end up with complete frustum-polygon in 'dest'
-	if (0==dest)	return false;
+    // here we end up with complete frustum-polygon in 'dest'
+    if (0 == dest) return false;
 
-	CreateFromPoints(dest->begin(),dest->size(),vBase);
-	return	true;
+    CreateFromPoints(dest->begin(), dest->size(), vBase);
+    return true;
 }
 
-void CFrustum::CreateFromMatrix(Fmatrix &M, u32 mask)
+void CFrustum::CreateFromMatrix(Fmatrix& M, u32 mask)
 {
-	VERIFY			(_valid(M));
-	p_count			= 0;
-
-	// Left clipping plane
-	if (mask&FRUSTUM_P_LEFT)
-	{
-		planes[p_count].n.x		= -(M._14 + M._11);
-		planes[p_count].n.y		= -(M._24 + M._21);
-		planes[p_count].n.z		= -(M._34 + M._31);
-		planes[p_count].d		= -(M._44 + M._41);
-		p_count++;
-	}
-
-	// Right clipping plane
-	if (mask&FRUSTUM_P_RIGHT)
-	{
-		planes[p_count].n.x		= -(M._14 - M._11);
-		planes[p_count].n.y		= -(M._24 - M._21);
-		planes[p_count].n.z		= -(M._34 - M._31);
-		planes[p_count].d		= -(M._44 - M._41);
-		p_count++;
-	}
-
-	// Top clipping plane
-	if (mask&FRUSTUM_P_TOP)
-	{
-		planes[p_count].n.x		= -(M._14 - M._12);
-		planes[p_count].n.y		= -(M._24 - M._22);
-		planes[p_count].n.z		= -(M._34 - M._32);
-		planes[p_count].d		= -(M._44 - M._42);
-		p_count++;
-	}
-
-	// Bottom clipping plane
-	if (mask&FRUSTUM_P_BOTTOM)
-	{
-		planes[p_count].n.x		= -(M._14 + M._12);
-		planes[p_count].n.y		= -(M._24 + M._22);
-		planes[p_count].n.z		= -(M._34 + M._32);
-		planes[p_count].d		= -(M._44 + M._42);
-		p_count++;
-	}
-
-	// Far clipping plane
-	if (mask&FRUSTUM_P_FAR)
-	{
-		planes[p_count].n.x		= -(M._14 - M._13);
-		planes[p_count].n.y		= -(M._24 - M._23);
-		planes[p_count].n.z		= -(M._34 - M._33);
-		planes[p_count].d		= -(M._44 - M._43);
-		p_count++;
-	}
-
-	// Near clipping plane
-	if (mask&FRUSTUM_P_NEAR)
-	{
-		planes[p_count].n.x		= -(M._14 + M._13);
-		planes[p_count].n.y		= -(M._24 + M._23);
-		planes[p_count].n.z		= -(M._34 + M._33);
-		planes[p_count].d		= -(M._44 + M._43);
-		p_count++;
-	}
-
-	for (int i=0;i		sPoly;
-ENGINE_API		extern	u32	frustum_aabb_remap[8][6];
+#define FRUSTUM_SAFE (FRUSTUM_MAXPLANES*4)
+typedef svector sPoly;
+ENGINE_API extern u32 frustum_aabb_remap[8][6];
 
-class ENGINE_API	CFrustum
+class ENGINE_API CFrustum
 {
 public:
-	struct fplane	: public Fplane
-	{
-		u32			aabb_overlap_id;	// [0..7]
-		void		cache	();	
-	};
-	fplane			planes	[FRUSTUM_MAXPLANES];
-	int				p_count;
+    struct fplane : public Fplane
+    {
+        u32 aabb_overlap_id; // [0..7]
+        void cache();
+    };
+    fplane planes[FRUSTUM_MAXPLANES];
+    int p_count;
 
 public:
-	ICF EFC_Visible		AABB_OverlapPlane	(const fplane& P, const float* mM) const
-	{
-		// calc extreme pts (neg,pos) along normal axis (pos in dir of norm, etc.)
-		u32*	id		= frustum_aabb_remap[P.aabb_overlap_id];
+    ICF EFC_Visible AABB_OverlapPlane(const fplane& P, const float* mM) const
+    {
+        // calc extreme pts (neg,pos) along normal axis (pos in dir of norm, etc.)
+        u32* id = frustum_aabb_remap[P.aabb_overlap_id];
 
-		Fvector			Neg;
-		Neg.set			(mM[id[3]],mM[id[4]],mM[id[5]]);
-		if				(P.classify(Neg) > 0)	return	fcvNone;
+        Fvector Neg;
+        Neg.set(mM[id[3]], mM[id[4]], mM[id[5]]);
+        if (P.classify(Neg) > 0) return fcvNone;
 
-		Fvector			Pos;
-		Pos.set			(mM[id[0]],mM[id[1]],mM[id[2]]);
-		if				(P.classify(Pos) <= 0)	return	fcvFully;
+        Fvector Pos;
+        Pos.set(mM[id[0]], mM[id[1]], mM[id[2]]);
+        if (P.classify(Pos) <= 0) return fcvFully;
 
-		return			fcvPartial;
-	}
+        return fcvPartial;
+    }
 public:
-	IC void			_clear				()				{ p_count=0; }
-	void			_add				(Fplane &P);
-	void			_add				(Fvector& P1, Fvector& P2, Fvector& P3);
+    IC void _clear() { p_count = 0; }
+    void _add(Fplane& P);
+    void _add(Fvector& P1, Fvector& P2, Fvector& P3);
 
-	void			SimplifyPoly_AABB	(sPoly* P, Fplane& plane);
+    void SimplifyPoly_AABB(sPoly* P, Fplane& plane);
 
-	void			CreateOccluder		(Fvector* p,	int count,		Fvector& vBase, CFrustum& clip);
-	BOOL			CreateFromClipPoly	(Fvector* p,	int count,		Fvector& vBase, CFrustum& clip);	// returns 'false' if creation failed
-	void			CreateFromPoints	(Fvector* p,	int count,		Fvector& vBase );
-	void			CreateFromMatrix	(Fmatrix &M,	u32 mask);
-	void			CreateFromPortal	(sPoly* P,		Fvector& vPN,	Fvector& vBase, Fmatrix& mFullXFORM);
-	void			CreateFromPlanes	(Fplane* p,		int count);
+    void CreateOccluder(Fvector* p, int count, Fvector& vBase, CFrustum& clip);
+    BOOL CreateFromClipPoly(Fvector* p, int count, Fvector& vBase, CFrustum& clip); // returns 'false' if creation failed
+    void CreateFromPoints(Fvector* p, int count, Fvector& vBase);
+    void CreateFromMatrix(Fmatrix& M, u32 mask);
+    void CreateFromPortal(sPoly* P, Fvector& vPN, Fvector& vBase, Fmatrix& mFullXFORM);
+    void CreateFromPlanes(Fplane* p, int count);
 
-	sPoly*			ClipPoly			(sPoly& src, sPoly& dest) const;
+    sPoly* ClipPoly(sPoly& src, sPoly& dest) const;
 
-	u32				getMask				() const { return (1<CreateFontRender();
-	fCurrentHeight				= 0.0f;
-	fXStep						= 0.0f;
-	fYStep						= 0.0f;
-	uFlags						= flags;
-	nNumChars					= 0x100;
-	TCMap						= NULL;
-	Initialize	(pSettings->r_string(section,"shader"),pSettings->r_string(section,"texture"));
-	if (pSettings->line_exist(section,"size")){
-		float sz = pSettings->r_float(section,"size");
-		if (uFlags&fsDeviceIndependent)	SetHeightI(sz);
-		else							SetHeight(sz);
-	}
-	if (pSettings->line_exist(section,"interval"))
-		SetInterval(pSettings->r_fvector2(section,"interval"));
+    pFontRender = RenderFactory->CreateFontRender();
+    fCurrentHeight = 0.0f;
+    fXStep = 0.0f;
+    fYStep = 0.0f;
+    uFlags = flags;
+    nNumChars = 0x100;
+    TCMap = NULL;
+    Initialize(pSettings->r_string(section, "shader"), pSettings->r_string(section, "texture"));
+    if (pSettings->line_exist(section, "size"))
+    {
+        float sz = pSettings->r_float(section, "size");
+        if (uFlags&fsDeviceIndependent) SetHeightI(sz);
+        else SetHeight(sz);
+    }
+    if (pSettings->line_exist(section, "interval"))
+        SetInterval(pSettings->r_fvector2(section, "interval"));
 }
 
 CGameFont::CGameFont(LPCSTR shader, LPCSTR texture, u32 flags)
 {
-	pFontRender					= RenderFactory->CreateFontRender();
-	fCurrentHeight				= 0.0f;
-	fXStep						= 0.0f;
-	fYStep						= 0.0f;
-	uFlags						= flags;
-	nNumChars					= 0x100;
-	TCMap						= NULL;
-	Initialize					(shader,texture);
+    pFontRender = RenderFactory->CreateFontRender();
+    fCurrentHeight = 0.0f;
+    fXStep = 0.0f;
+    fYStep = 0.0f;
+    uFlags = flags;
+    nNumChars = 0x100;
+    TCMap = NULL;
+    Initialize(shader, texture);
 }
 
-void CGameFont::Initialize		(LPCSTR cShader, LPCSTR cTextureName)
+void CGameFont::Initialize(LPCSTR cShader, LPCSTR cTextureName)
 {
-	string_path					cTexture;
-
-	LPCSTR _lang				= pSettings->r_string("string_table", "font_prefix");
-	bool is_di					= strstr(cTextureName, "ui_font_hud_01") || 
-								  strstr(cTextureName, "ui_font_hud_02") ||
-								  strstr(cTextureName, "ui_font_console_02");
-	if(_lang && !is_di)
-		strconcat				(sizeof(cTexture),cTexture, cTextureName, _lang);
-	else
-		xr_strcpy				(cTexture, sizeof(cTexture), cTextureName);
-
-	uFlags						&=~fsValid;
-	vTS.set						(1.f,1.f); // îáÿçàòåëüíî !!!
-
-	eCurrentAlignment			= alLeft;
-	vInterval.set				(1.f,1.f);
-
-	strings.reserve				(128);
-
-	// check ini exist
-	string_path fn,buf;
-	xr_strcpy		(buf,cTexture); if (strext(buf)) *strext(buf)=0;
-	R_ASSERT2	(FS.exist(fn,"$game_textures$",buf,".ini"),fn);
-	CInifile* ini				= CInifile::Create(fn);
-
-	nNumChars = 0x100;
-	TCMap = ( Fvector* ) xr_realloc( ( void* ) TCMap , nNumChars * sizeof( Fvector ) );
-
-	if ( ini->section_exist( "mb_symbol_coords" ) ) {
-		nNumChars = 0x10000;
-		TCMap = ( Fvector* ) xr_realloc( ( void* ) TCMap , nNumChars * sizeof( Fvector ) );
-		uFlags |= fsMultibyte;
-		fHeight = ini->r_float( "mb_symbol_coords" , "height" );
-		
-		fXStep = ceil( fHeight / 2.0f );
-
-		// Searching for the first valid character
-
-		Fvector vFirstValid = {0,0,0};
-
-		if ( ini->line_exist( "mb_symbol_coords" , "09608" ) ) {
-			Fvector v = ini->r_fvector3( "mb_symbol_coords" , "09608" );
-			vFirstValid.set( v.x , v.y , 1 + v[2] - v[0] );
-		} else 
-		for ( u32 i=0 ; i < nNumChars ; i++ ) {
-			xr_sprintf( buf ,sizeof(buf), "%05d" , i );
-			if ( ini->line_exist( "mb_symbol_coords" , buf ) ) {
-				Fvector v = ini->r_fvector3( "mb_symbol_coords" , buf );
-				vFirstValid.set( v.x , v.y , 1 + v[2] - v[0] );
-				break;
-			}
-		}
-
-		// Filling entire character table
-
-		for ( u32 i=0 ; i < nNumChars ; i++ ) {
-			xr_sprintf( buf ,sizeof(buf), "%05d" , i );
-			if ( ini->line_exist( "mb_symbol_coords" , buf ) ) {
-				Fvector v = ini->r_fvector3( "mb_symbol_coords" , buf );
-				TCMap[i].set( v.x , v.y , 1 + v[2] - v[0] );
-			} else
-				TCMap[i] = vFirstValid; // "unassigned" unprintable characters
-		}
-
-		// Special case for space
-		TCMap[ 0x0020 ].set( 0 , 0 , 0 );
-		// Special case for ideographic space
-		TCMap[ 0x3000 ].set( 0 , 0 , 0 );
-
-
-	}else
-	if (ini->section_exist("symbol_coords"))
-	{
-		float d						= 0.0f;
-//.		if(ini->section_exist("width_correction"))
-//.			d						= ini->r_float("width_correction", "value");
-
-		fHeight						= ini->r_float("symbol_coords","height");
-		for (u32 i=0; ir_fvector3("symbol_coords",buf);
-			TCMap[i].set			(v.x,v.y,v[2]-v[0]+d);
-		}
-	}else{
-	if (ini->section_exist("char widths")){
-		fHeight					= ini->r_float("char widths","height");
-		int cpl					= 16;
-		for (u32 i=0; ir_float("char widths",buf);
-			TCMap[i].set		((i%cpl)*fHeight,(i/cpl)*fHeight,w);
-		}
-	}else{
-		R_ASSERT(ini->section_exist("font_size"));
-		fHeight					= ini->r_float("font_size","height");
-		float width				= ini->r_float("font_size","width");
-		const int cpl			= ini->r_s32	("font_size","cpl");
-		for (u32 i=0; iInitialize(cShader, cTexture);
+    string_path cTexture;
+
+    LPCSTR _lang = pSettings->r_string("string_table", "font_prefix");
+    bool is_di = strstr(cTextureName, "ui_font_hud_01") ||
+        strstr(cTextureName, "ui_font_hud_02") ||
+        strstr(cTextureName, "ui_font_console_02");
+    if (_lang && !is_di)
+        strconcat(sizeof(cTexture), cTexture, cTextureName, _lang);
+    else
+        xr_strcpy(cTexture, sizeof(cTexture), cTextureName);
+
+    uFlags &= ~fsValid;
+    vTS.set(1.f, 1.f); // îáÿçàòåëüíî !!!
+
+    eCurrentAlignment = alLeft;
+    vInterval.set(1.f, 1.f);
+
+    strings.reserve(128);
+
+    // check ini exist
+    string_path fn, buf;
+    xr_strcpy(buf, cTexture);
+    if (strext(buf)) *strext(buf) = 0;
+    R_ASSERT2(FS.exist(fn, "$game_textures$", buf, ".ini"), fn);
+    CInifile* ini = CInifile::Create(fn);
+
+    nNumChars = 0x100;
+    TCMap = (Fvector*)xr_realloc((void*)TCMap, nNumChars * sizeof(Fvector));
+
+    if (ini->section_exist("mb_symbol_coords"))
+    {
+        nNumChars = 0x10000;
+        TCMap = (Fvector*)xr_realloc((void*)TCMap, nNumChars * sizeof(Fvector));
+        uFlags |= fsMultibyte;
+        fHeight = ini->r_float("mb_symbol_coords", "height");
+
+        fXStep = ceil(fHeight / 2.0f);
+
+        // Searching for the first valid character
+
+        Fvector vFirstValid = {0, 0, 0};
+
+        if (ini->line_exist("mb_symbol_coords", "09608"))
+        {
+            Fvector v = ini->r_fvector3("mb_symbol_coords", "09608");
+            vFirstValid.set(v.x, v.y, 1 + v[2] - v[0]);
+        }
+        else
+            for (u32 i = 0; i < nNumChars; i++)
+            {
+            xr_sprintf(buf, sizeof(buf), "%05d", i);
+            if (ini->line_exist("mb_symbol_coords", buf))
+            {
+                Fvector v = ini->r_fvector3("mb_symbol_coords", buf);
+                vFirstValid.set(v.x, v.y, 1 + v[2] - v[0]);
+                break;
+            }
+            }
+
+        // Filling entire character table
+
+        for (u32 i = 0; i < nNumChars; i++)
+        {
+            xr_sprintf(buf, sizeof(buf), "%05d", i);
+            if (ini->line_exist("mb_symbol_coords", buf))
+            {
+                Fvector v = ini->r_fvector3("mb_symbol_coords", buf);
+                TCMap[i].set(v.x, v.y, 1 + v[2] - v[0]);
+            }
+            else
+                TCMap[i] = vFirstValid; // "unassigned" unprintable characters
+        }
+
+        // Special case for space
+        TCMap[0x0020].set(0, 0, 0);
+        // Special case for ideographic space
+        TCMap[0x3000].set(0, 0, 0);
+
+
+    }
+    else if (ini->section_exist("symbol_coords"))
+    {
+        float d = 0.0f;
+        //. if(ini->section_exist("width_correction"))
+        //. d = ini->r_float("width_correction", "value");
+
+        fHeight = ini->r_float("symbol_coords", "height");
+        for (u32 i = 0; i < nNumChars; i++)
+        {
+            xr_sprintf(buf, sizeof(buf), "%03d", i);
+            Fvector v = ini->r_fvector3("symbol_coords", buf);
+            TCMap[i].set(v.x, v.y, v[2] - v[0] + d);
+        }
+    }
+    else
+    {
+        if (ini->section_exist("char widths"))
+        {
+            fHeight = ini->r_float("char widths", "height");
+            int cpl = 16;
+            for (u32 i = 0; i < nNumChars; i++)
+            {
+                xr_sprintf(buf, sizeof(buf), "%d", i);
+                float w = ini->r_float("char widths", buf);
+                TCMap[i].set((i%cpl)*fHeight, (i / cpl)*fHeight, w);
+            }
+        }
+        else
+        {
+            R_ASSERT(ini->section_exist("font_size"));
+            fHeight = ini->r_float("font_size", "height");
+            float width = ini->r_float("font_size", "width");
+            const int cpl = ini->r_s32("font_size", "cpl");
+            for (u32 i = 0; i < nNumChars; i++)
+                TCMap[i].set((i%cpl)*width, (i / cpl)*fHeight, width);
+        }
+    }
+
+    fCurrentHeight = fHeight;
+
+    CInifile::Destroy(ini);
+
+    // Shading
+    pFontRender->Initialize(cShader, cTexture);
 }
 
 CGameFont::~CGameFont()
 {
-	if ( TCMap )
-		xr_free( TCMap );
+    if (TCMap)
+        xr_free(TCMap);
 
-	// Shading
-	RenderFactory->DestroyFontRender(pFontRender);
+    // Shading
+    RenderFactory->DestroyFontRender(pFontRender);
 }
 
 #define DI2PX(x) float(iFloor((x+1)*float(::Render->getTarget()->get_width())*0.5f))
 #define DI2PY(y) float(iFloor((y+1)*float(::Render->getTarget()->get_height())*0.5f))
 
-void CGameFont::OutSet			(float x, float y)
+void CGameFont::OutSet(float x, float y)
 {
-	fCurrentX=x;
-	fCurrentY=y;
+    fCurrentX = x;
+    fCurrentY = y;
 }
 
-void CGameFont::OutSetI			(float x, float y)
+void CGameFont::OutSetI(float x, float y)
 {
-	OutSet(DI2PX(x),DI2PY(y));
+    OutSet(DI2PX(x), DI2PY(y));
 }
 
-u32 CGameFont::smart_strlen( const char* S )
+u32 CGameFont::smart_strlen(const char* S)
 {
-	return ( IsMultibyte() ? mbhMulti2Wide( NULL , NULL , 0 , S ) : xr_strlen( S ) );
+    return (IsMultibyte() ? mbhMulti2Wide(NULL, NULL, 0, S) : xr_strlen(S));
 }
 
 void CGameFont::OnRender()
 {
-	pFontRender->OnRender(*this);
-	strings.clear_not_free();
+    pFontRender->OnRender(*this);
+    strings.clear_not_free();
 }
 
-u16 CGameFont::GetCutLengthPos( float fTargetWidth , const char * pszText )
+u16 CGameFont::GetCutLengthPos(float fTargetWidth, const char* pszText)
 {
-	VERIFY( pszText );
+    VERIFY(pszText);
 
-	wide_char wsStr[ MAX_MB_CHARS ], wsPos[ MAX_MB_CHARS ];
-	float fCurWidth = 0.0f , fDelta = 0.0f;
+    wide_char wsStr[MAX_MB_CHARS], wsPos[MAX_MB_CHARS];
+    float fCurWidth = 0.0f, fDelta = 0.0f;
 
-	u16	len	= mbhMulti2Wide( wsStr , wsPos , MAX_MB_CHARS , pszText );
+    u16 len = mbhMulti2Wide(wsStr, wsPos, MAX_MB_CHARS, pszText);
 
-	for ( u16 i = 1 ; i <= len ; i++ ) {
+    for (u16 i = 1; i <= len; i++)
+    {
 
-		fDelta = GetCharTC( wsStr[ i ] ).z - 2;
+        fDelta = GetCharTC(wsStr[i]).z - 2;
 
-		if ( IsNeedSpaceCharacter( wsStr[ i ] ) )
-			fDelta += fXStep;
+        if (IsNeedSpaceCharacter(wsStr[i]))
+            fDelta += fXStep;
 
-		if ( ( fCurWidth + fDelta ) > fTargetWidth )
-			break;
-		else 
-			fCurWidth += fDelta;
-	}
+        if ((fCurWidth + fDelta) > fTargetWidth)
+            break;
+        else
+            fCurWidth += fDelta;
+    }
 
-	return wsPos[ i - 1 ];
+    return wsPos[i - 1];
 }
 
-u16 CGameFont::SplitByWidth( u16 * puBuffer , u16 uBufferSize , float fTargetWidth , const char * pszText )
+u16 CGameFont::SplitByWidth(u16* puBuffer, u16 uBufferSize, float fTargetWidth, const char* pszText)
 {
-	VERIFY( puBuffer && uBufferSize && pszText );
+    VERIFY(puBuffer && uBufferSize && pszText);
 
-	wide_char wsStr[ MAX_MB_CHARS ] , wsPos[ MAX_MB_CHARS ];
-	float fCurWidth = 0.0f , fDelta = 0.0f;
-	u16 nLines = 0;
+    wide_char wsStr[MAX_MB_CHARS], wsPos[MAX_MB_CHARS];
+    float fCurWidth = 0.0f, fDelta = 0.0f;
+    u16 nLines = 0;
 
-	u16	len	= mbhMulti2Wide( wsStr , wsPos , MAX_MB_CHARS , pszText );
+    u16 len = mbhMulti2Wide(wsStr, wsPos, MAX_MB_CHARS, pszText);
 
-	for ( u16 i = 1 ; i <= len ; i++ ) {
+    for (u16 i = 1; i <= len; i++)
+    {
 
-		fDelta = GetCharTC( wsStr[ i ] ).z - 2;
+        fDelta = GetCharTC(wsStr[i]).z - 2;
 
-		if ( IsNeedSpaceCharacter( wsStr[ i ] ) )
-			fDelta += fXStep;
+        if (IsNeedSpaceCharacter(wsStr[i]))
+            fDelta += fXStep;
 
-		if ( 
-				( ( fCurWidth + fDelta ) > fTargetWidth ) && // overlength
-				( ! IsBadStartCharacter( wsStr[ i ] ) ) && // can start with this character
-				( i < len ) && // is not the last character
-				( ( i > 1 ) && ( ! IsBadEndCharacter( wsStr[ i - 1 ] ) ) ) // && // do not stop the string on a "bad" character
-//				( ( i > 1 ) && ( ! ( ( IsAlphaCharacter( wsStr[ i - 1 ] ) ) && (  IsAlphaCharacter( wsStr[ i ] ) ) ) ) ) // do not split numbers or words
-		) {
-			fCurWidth = fDelta;
-			VERIFY( nLines < uBufferSize );
-			puBuffer[ nLines++ ] = wsPos[ i - 1 ];
-		} else 
-			fCurWidth += fDelta;
-	}
+        if (
+            ((fCurWidth + fDelta) > fTargetWidth) && // overlength
+            (!IsBadStartCharacter(wsStr[i])) && // can start with this character
+            (i < len) && // is not the last character
+            ((i > 1) && (!IsBadEndCharacter(wsStr[i - 1]))) // && // do not stop the string on a "bad" character
+            // ( ( i > 1 ) && ( ! ( ( IsAlphaCharacter( wsStr[ i - 1 ] ) ) && ( IsAlphaCharacter( wsStr[ i ] ) ) ) ) ) // do not split numbers or words
+            )
+        {
+            fCurWidth = fDelta;
+            VERIFY(nLines < uBufferSize);
+            puBuffer[nLines++] = wsPos[i - 1];
+        }
+        else
+            fCurWidth += fDelta;
+    }
 
-	return nLines;
-}
+    return nLines;
+    }
 
 void CGameFont::MasterOut(
-	BOOL bCheckDevice , BOOL bUseCoords , BOOL bScaleCoords , BOOL bUseSkip , 
-	float _x , float _y , float _skip , LPCSTR fmt , va_list p )
+    BOOL bCheckDevice, BOOL bUseCoords, BOOL bScaleCoords, BOOL bUseSkip,
+    float _x, float _y, float _skip, LPCSTR fmt, va_list p)
 {
-	if ( bCheckDevice && ( ! RDEVICE.b_is_Active ) )
-		return;
-
-	String rs;
-
-	rs.x = ( bUseCoords ? ( bScaleCoords ? ( DI2PX( _x ) ) : _x ) : fCurrentX );
-	rs.y = ( bUseCoords ? ( bScaleCoords ? ( DI2PY( _y ) ) : _y ) : fCurrentY );
-	rs.c = dwCurrentColor;
-	rs.height = fCurrentHeight;
-	rs.align = eCurrentAlignment;
-#ifndef	_EDITOR
-	int vs_sz = vsprintf_s( rs.string , fmt , p );
+    if (bCheckDevice && (!RDEVICE.b_is_Active))
+        return;
+
+    String rs;
+
+    rs.x = (bUseCoords ? (bScaleCoords ? (DI2PX(_x)) : _x) : fCurrentX);
+    rs.y = (bUseCoords ? (bScaleCoords ? (DI2PY(_y)) : _y) : fCurrentY);
+    rs.c = dwCurrentColor;
+    rs.height = fCurrentHeight;
+    rs.align = eCurrentAlignment;
+#ifndef _EDITOR
+    int vs_sz = vsprintf_s(rs.string, fmt, p);
 #else
-	int vs_sz = vsprintf( rs.string , fmt , p );
+    int vs_sz = vsprintf(rs.string, fmt, p);
 #endif
-	//VERIFY( ( vs_sz != -1 ) && ( rs.string[ vs_sz ] == '\0' ) );
+    //VERIFY( ( vs_sz != -1 ) && ( rs.string[ vs_sz ] == '\0' ) );
 
-	rs.string[ sizeof(rs.string)-1 ] = 0;
-	if ( vs_sz == -1 )
-	{
-		return;
-	}
+    rs.string[sizeof(rs.string) - 1] = 0;
+    if (vs_sz == -1)
+    {
+        return;
+    }
 
-	if ( vs_sz )
-		strings.push_back( rs );
+    if (vs_sz)
+        strings.push_back(rs);
 
-	if ( bUseSkip )
-		OutSkip( _skip );
+    if (bUseSkip)
+        OutSkip(_skip);
 }
 
 #define MASTER_OUT(CHECK_DEVICE,USE_COORDS,SCALE_COORDS,USE_SKIP,X,Y,SKIP,FMT) \
-	{ va_list p; va_start ( p , fmt ); \
-	  MasterOut( CHECK_DEVICE , USE_COORDS , SCALE_COORDS , USE_SKIP , X , Y , SKIP , FMT, p ); \
-	  va_end( p ); }
+ { va_list p; va_start ( p , fmt ); \
+ MasterOut( CHECK_DEVICE , USE_COORDS , SCALE_COORDS , USE_SKIP , X , Y , SKIP , FMT, p ); \
+ va_end( p ); }
 
-void __cdecl CGameFont::OutI( float _x , float _y , LPCSTR fmt , ... )
+void __cdecl CGameFont::OutI(float _x, float _y, LPCSTR fmt, ...)
 {
-	MASTER_OUT( FALSE , TRUE , TRUE , FALSE , _x  , _y , 0.0f , fmt );
+    MASTER_OUT(FALSE, TRUE, TRUE, FALSE, _x, _y, 0.0f, fmt);
 };
 
-void __cdecl CGameFont::Out( float _x , float _y , LPCSTR fmt , ... )
+void __cdecl CGameFont::Out(float _x, float _y, LPCSTR fmt, ...)
 {
-	MASTER_OUT( TRUE , TRUE , FALSE , FALSE , _x , _y , 0.0f , fmt );
+    MASTER_OUT(TRUE, TRUE, FALSE, FALSE, _x, _y, 0.0f, fmt);
 };
 
-void __cdecl CGameFont::OutNext( LPCSTR fmt , ... )
+void __cdecl CGameFont::OutNext(LPCSTR fmt, ...)
 {
-	MASTER_OUT( TRUE , FALSE , FALSE , TRUE , 0.0f , 0.0f , 1.0f , fmt );
+    MASTER_OUT(TRUE, FALSE, FALSE, TRUE, 0.0f, 0.0f, 1.0f, fmt);
 };
 
 
-void CGameFont::OutSkip( float val )
+void CGameFont::OutSkip(float val)
 {
-	fCurrentY += val*CurrentHeight_();
+    fCurrentY += val*CurrentHeight_();
 }
 
-float CGameFont::SizeOf_( const char cChar )
+float CGameFont::SizeOf_(const char cChar)
 {
-	return ( GetCharTC( ( u16 ) ( u8 ) ( ( ( IsMultibyte() && cChar == ' ' ) ) ? 0 : cChar) ).z * vInterval.x );
+    return (GetCharTC((u16)(u8)(((IsMultibyte() && cChar == ' ')) ? 0 : cChar)).z * vInterval.x);
 }
 
-float CGameFont::SizeOf_( LPCSTR s )
+float CGameFont::SizeOf_(LPCSTR s)
 {
-	if ( ! ( s && s[ 0 ] ) )
-		return 0;
+    if (!(s && s[0]))
+        return 0;
 
-	if ( IsMultibyte() ) {
-		wide_char wsStr[ MAX_MB_CHARS ];
+    if (IsMultibyte())
+    {
+        wide_char wsStr[MAX_MB_CHARS];
 
-		mbhMulti2Wide( wsStr , NULL , MAX_MB_CHARS , s );
+        mbhMulti2Wide(wsStr, NULL, MAX_MB_CHARS, s);
 
-		return SizeOf_( wsStr );
-	}
+        return SizeOf_(wsStr);
+    }
 
-	int		len			= xr_strlen(s);
-	float	X			= 0;
-	if (len)
-		for (int j=0; j		strings;
+    Fvector* TCMap;
+    float fHeight;
+    float fXStep;
+    float fYStep;
+    float fTCHeight;
+    xr_vector strings;
 
-	IFontRender				*pFontRender;
+    IFontRender* pFontRender;
 
-	u32						nNumChars;
+    u32 nNumChars;
 
-	u32						uFlags;
+    u32 uFlags;
 
 public:
-	enum
-	{
-		fsGradient			= (1<<0),
-		fsDeviceIndependent	= (1<<1),
-		fsValid 			= (1<<2),
+    enum
+    {
+        fsGradient = (1 << 0),
+        fsDeviceIndependent = (1 << 1),
+        fsValid = (1 << 2),
 
-		fsMultibyte			= (1<<3),
+        fsMultibyte = (1 << 3),
 
-		fsForceDWORD		= u32(-1)
-	};
+        fsForceDWORD = u32(-1)
+    };
 
 protected:
-	IC const Fvector&		GetCharTC		(u16 c)		{return TCMap[c];}
+    IC const Fvector& GetCharTC(u16 c) { return TCMap[c]; }
 
 public:
-							CGameFont		(LPCSTR section, u32 flags=0);
-							CGameFont		(LPCSTR shader, LPCSTR texture, u32 flags=0);
-							~CGameFont		();
+    CGameFont(LPCSTR section, u32 flags = 0);
+    CGameFont(LPCSTR shader, LPCSTR texture, u32 flags = 0);
+    ~CGameFont();
 
-	void					Initialize		(LPCSTR shader, LPCSTR texture);
+    void Initialize(LPCSTR shader, LPCSTR texture);
 
-	IC void					SetColor		(u32 C)		{dwCurrentColor=C;};
+    IC void SetColor(u32 C) { dwCurrentColor = C; };
 
-	IC void					SetHeightI		(float S);
-	IC void					SetHeight		(float S);
+    IC void SetHeightI(float S);
+    IC void SetHeight(float S);
 
-	IC float				GetHeight		(){return fCurrentHeight;};
-	IC void					SetInterval		(float x, float y) {vInterval.set(x,y);};
-	IC void					SetInterval		(const Fvector2& v) {vInterval.set(v);};
-	IC void					SetAligment		(EAligment aligment){ eCurrentAlignment=aligment; }
+    IC float GetHeight() { return fCurrentHeight; };
+    IC void SetInterval(float x, float y) { vInterval.set(x, y); };
+    IC void SetInterval(const Fvector2& v) { vInterval.set(v); };
+    IC void SetAligment(EAligment aligment) { eCurrentAlignment = aligment; }
 
-	float					SizeOf_			( LPCSTR s );
-	float					SizeOf_			( const wide_char *wsStr );
+    float SizeOf_(LPCSTR s);
+    float SizeOf_(const wide_char* wsStr);
 
-	float					SizeOf_			( const char cChar );  // only ANSII 
+    float SizeOf_(const char cChar); // only ANSII
 
-	float					CurrentHeight_	();
+    float CurrentHeight_();
 
-	void					OutSetI			(float x, float y);
-	void					OutSet			(float x, float y);
+    void OutSetI(float x, float y);
+    void OutSet(float x, float y);
 
-	void 					MasterOut( 	BOOL bCheckDevice , BOOL bUseCoords , BOOL bScaleCoords , BOOL bUseSkip ,
-										float _x , float _y , float _skip , LPCSTR fmt , va_list p );
+    void MasterOut(BOOL bCheckDevice, BOOL bUseCoords, BOOL bScaleCoords, BOOL bUseSkip,
+        float _x, float _y, float _skip, LPCSTR fmt, va_list p);
 
-	u32						smart_strlen( const char* S );
-	BOOL					IsMultibyte() { return ( uFlags & fsMultibyte ); };
-	u16						SplitByWidth( u16 * puBuffer , u16 uBufferSize , float fTargetWidth , const char * pszText );
-	u16						GetCutLengthPos( float fTargetWidth , const char * pszText );
+    u32 smart_strlen(const char* S);
+    BOOL IsMultibyte() { return (uFlags & fsMultibyte); };
+    u16 SplitByWidth(u16* puBuffer, u16 uBufferSize, float fTargetWidth, const char* pszText);
+    u16 GetCutLengthPos(float fTargetWidth, const char* pszText);
 
-	void  					OutI			( float _x , float _y , LPCSTR fmt , ... );
-	void  					Out				( float _x , float _y , LPCSTR fmt , ... );
-	void             		OutNext			( LPCSTR fmt , ... );
+    void OutI(float _x, float _y, LPCSTR fmt, ...);
+    void Out(float _x, float _y, LPCSTR fmt, ...);
+    void OutNext(LPCSTR fmt, ...);
 
-	void					OutSkip			(float val=1.f);
+    void OutSkip(float val = 1.f);
 
-	void					OnRender		();
+    void OnRender();
 
-	IC	void				Clear			()  { strings.clear(); };
+    IC void Clear() { strings.clear(); };
 
 #ifdef DEBUG
-	shared_str				m_font_name;
+    shared_str m_font_name;
 #endif
 };
 
diff --git a/src/xrEngine/GameMtlLib.cpp b/src/xrEngine/GameMtlLib.cpp
index ecc9461fb3f..dd6afc10363 100644
--- a/src/xrEngine/GameMtlLib.cpp
+++ b/src/xrEngine/GameMtlLib.cpp
@@ -6,173 +6,186 @@
 //#include "../include/xrapi/xrapi.h"
 
 CGameMtlLibrary GMLib;
-//CSound_manager_interface*	Sound = NULL;
-#ifdef	_EDITOR
-CGameMtlLibrary*			PGMLib = NULL;
+//CSound_manager_interface* Sound = NULL;
+#ifdef _EDITOR
+CGameMtlLibrary* PGMLib = NULL;
 #endif
-CGameMtlLibrary::	CGameMtlLibrary		()
-	{
-	    material_index 		= 0;
-	    material_pair_index = 0;
+CGameMtlLibrary::CGameMtlLibrary()
+{
+    material_index = 0;
+    material_pair_index = 0;
 #ifndef _EDITOR
-        material_count	    = 0;
+    material_count = 0;
 #endif
-		PGMLib = &GMLib;
-    }
+    PGMLib = &GMLib;
+}
 
 void SGameMtl::Load(IReader& fs)
 {
-	R_ASSERT(fs.find_chunk(GAMEMTL_CHUNK_MAIN));
-	ID						= fs.r_u32();
-    fs.r_stringZ			(m_Name);
+    R_ASSERT(fs.find_chunk(GAMEMTL_CHUNK_MAIN));
+    ID = fs.r_u32();
+    fs.r_stringZ(m_Name);
 
-    if (fs.find_chunk(GAMEMTL_CHUNK_DESC)){
-		fs.r_stringZ		(m_Desc);
+    if (fs.find_chunk(GAMEMTL_CHUNK_DESC))
+    {
+        fs.r_stringZ(m_Desc);
     }
-    
-	R_ASSERT(fs.find_chunk(GAMEMTL_CHUNK_FLAGS));
-    Flags.assign			(fs.r_u32());
-
-	R_ASSERT(fs.find_chunk(GAMEMTL_CHUNK_PHYSICS));
-    fPHFriction				= fs.r_float();
-    fPHDamping				= fs.r_float();
-    fPHSpring				= fs.r_float();
-    fPHBounceStartVelocity 	= fs.r_float();
-    fPHBouncing				= fs.r_float();
-
-	R_ASSERT(fs.find_chunk(GAMEMTL_CHUNK_FACTORS));
-    fShootFactor			= fs.r_float();
-    fBounceDamageFactor		= fs.r_float();
-    fVisTransparencyFactor	= fs.r_float();
-    fSndOcclusionFactor		= fs.r_float();
-
-
-	if(fs.find_chunk(GAMEMTL_CHUNK_FACTORS_MP))
-	    fShootFactorMP	    = fs.r_float();
+
+    R_ASSERT(fs.find_chunk(GAMEMTL_CHUNK_FLAGS));
+    Flags.assign(fs.r_u32());
+
+    R_ASSERT(fs.find_chunk(GAMEMTL_CHUNK_PHYSICS));
+    fPHFriction = fs.r_float();
+    fPHDamping = fs.r_float();
+    fPHSpring = fs.r_float();
+    fPHBounceStartVelocity = fs.r_float();
+    fPHBouncing = fs.r_float();
+
+    R_ASSERT(fs.find_chunk(GAMEMTL_CHUNK_FACTORS));
+    fShootFactor = fs.r_float();
+    fBounceDamageFactor = fs.r_float();
+    fVisTransparencyFactor = fs.r_float();
+    fSndOcclusionFactor = fs.r_float();
+
+
+    if (fs.find_chunk(GAMEMTL_CHUNK_FACTORS_MP))
+        fShootFactorMP = fs.r_float();
     else
-	    fShootFactorMP	    = fShootFactor;
+        fShootFactorMP = fShootFactor;
 
-	if(fs.find_chunk(GAMEMTL_CHUNK_FLOTATION))
-	    fFlotationFactor	= fs.r_float();
+    if (fs.find_chunk(GAMEMTL_CHUNK_FLOTATION))
+        fFlotationFactor = fs.r_float();
 
-    if(fs.find_chunk(GAMEMTL_CHUNK_INJURIOUS))
-    	fInjuriousSpeed		= fs.r_float();
-    
-	if(fs.find_chunk(GAMEMTL_CHUNK_DENSITY))
-    	fDensityFactor		= fs.r_float();
+    if (fs.find_chunk(GAMEMTL_CHUNK_INJURIOUS))
+        fInjuriousSpeed = fs.r_float();
+
+    if (fs.find_chunk(GAMEMTL_CHUNK_DENSITY))
+        fDensityFactor = fs.r_float();
 }
 
 void CGameMtlLibrary::Load()
 {
-	string_path			name;
-	if (!FS.exist(name,	_game_data_,GAMEMTL_FILENAME)){
-    	Log				("! Can't find game material file: ",name);
-    	return;
+    string_path name;
+    if (!FS.exist(name, _game_data_, GAMEMTL_FILENAME))
+    {
+        Log("! Can't find game material file: ", name);
+        return;
     }
 
-    R_ASSERT			(material_pairs.empty());
-    R_ASSERT			(materials.empty());
+    R_ASSERT(material_pairs.empty());
+    R_ASSERT(materials.empty());
 
-	IReader*	F		= FS.r_open(name);
-    IReader& fs			= *F;
+    IReader* F = FS.r_open(name);
+    IReader& fs = *F;
 
     R_ASSERT(fs.find_chunk(GAMEMTLS_CHUNK_VERSION));
-    u16 version			= fs.r_u16();
-    if (GAMEMTL_CURRENT_VERSION!=version){
-        Log				("CGameMtlLibrary: invalid version. Library can't load.");
-		FS.r_close		(F);
-    	return;
+    u16 version = fs.r_u16();
+    if (GAMEMTL_CURRENT_VERSION != version)
+    {
+        Log("CGameMtlLibrary: invalid version. Library can't load.");
+        FS.r_close(F);
+        return;
     }
 
     R_ASSERT(fs.find_chunk(GAMEMTLS_CHUNK_AUTOINC));
-    material_index		= fs.r_u32();
-    material_pair_index	= fs.r_u32();
+    material_index = fs.r_u32();
+    material_pair_index = fs.r_u32();
 
-    materials.clear		();
+    materials.clear();
     material_pairs.clear();
 
-    IReader* OBJ 		= fs.open_chunk(GAMEMTLS_CHUNK_MTLS);
-    if (OBJ) {
-        u32				count;
-        for (IReader* O = OBJ->open_chunk_iterator(count); O; O = OBJ->open_chunk_iterator(count,O)) {
-        	SGameMtl*	M = xr_new ();
-	        M->Load		(*O);
-        	materials.push_back(M);
+    IReader* OBJ = fs.open_chunk(GAMEMTLS_CHUNK_MTLS);
+    if (OBJ)
+    {
+        u32 count;
+        for (IReader* O = OBJ->open_chunk_iterator(count); O; O = OBJ->open_chunk_iterator(count, O))
+        {
+            SGameMtl* M = xr_new();
+            M->Load(*O);
+            materials.push_back(M);
         }
-        OBJ->close		();
+        OBJ->close();
     }
 
-    OBJ 				= fs.open_chunk(GAMEMTLS_CHUNK_MTLS_PAIR);
-    if (OBJ){
-        u32				count;
-        for (IReader* O = OBJ->open_chunk_iterator(count); O; O = OBJ->open_chunk_iterator(count,O)) {
-        	SGameMtlPair* M	= xr_new (this);
-	        M->Load		(*O);
-        	material_pairs.push_back(M);
+    OBJ = fs.open_chunk(GAMEMTLS_CHUNK_MTLS_PAIR);
+    if (OBJ)
+    {
+        u32 count;
+        for (IReader* O = OBJ->open_chunk_iterator(count); O; O = OBJ->open_chunk_iterator(count, O))
+        {
+            SGameMtlPair* M = xr_new(this);
+            M->Load(*O);
+            material_pairs.push_back(M);
         }
-        OBJ->close		();
+        OBJ->close();
     }
 
 #ifndef _EDITOR
-	material_count		= (u32)materials.size();
-    material_pairs_rt.resize(material_count*material_count,0);
-    for (GameMtlPairIt p_it=material_pairs.begin(); material_pairs.end() != p_it; ++p_it){
-		SGameMtlPair* S	= *p_it;
-    	int idx0		= GetMaterialIdx(S->mtl0)*material_count+GetMaterialIdx(S->mtl1);
-    	int idx1		= GetMaterialIdx(S->mtl1)*material_count+GetMaterialIdx(S->mtl0);
-	    material_pairs_rt[idx0]=S;
-	    material_pairs_rt[idx1]=S;
+    material_count = (u32)materials.size();
+    material_pairs_rt.resize(material_count*material_count, 0);
+    for (GameMtlPairIt p_it = material_pairs.begin(); material_pairs.end() != p_it; ++p_it)
+    {
+        SGameMtlPair* S = *p_it;
+        int idx0 = GetMaterialIdx(S->mtl0)*material_count + GetMaterialIdx(S->mtl1);
+        int idx1 = GetMaterialIdx(S->mtl1)*material_count + GetMaterialIdx(S->mtl0);
+        material_pairs_rt[idx0] = S;
+        material_pairs_rt[idx1] = S;
     }
 #endif
 
-/*
-	for (GameMtlPairIt p_it=material_pairs.begin(); material_pairs.end() != p_it; ++p_it){
-		SGameMtlPair* S	= *p_it;
-		for (int k=0; kStepSounds.size(); k++){
-			Msg("%40s - 0x%x", S->StepSounds[k].handle->file_name(), S->StepSounds[k].g_type);
-		}
-	}
-*/
-	FS.r_close		(F);
+    /*
+     for (GameMtlPairIt p_it=material_pairs.begin(); material_pairs.end() != p_it; ++p_it){
+     SGameMtlPair* S = *p_it;
+     for (int k=0; kStepSounds.size(); k++){
+     Msg("%40s - 0x%x", S->StepSounds[k].handle->file_name(), S->StepSounds[k].g_type);
+     }
+     }
+     */
+    FS.r_close (F);
 }
 
 #ifdef GM_NON_GAME
-SGameMtlPair::~SGameMtlPair		()
+SGameMtlPair::~SGameMtlPair ()
 {
-}                
+}
 void SGameMtlPair::Load(IReader& fs)
 {
-	shared_str				buf;
-
-	R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_PAIR));
-	mtl0				= fs.r_u32();
-	mtl1				= fs.r_u32();
-	ID					= fs.r_u32();
-	ID_parent			= fs.r_u32();
-    u32 own_mask		= fs.r_u32(); 
-    if (GAMEMTL_NONE_ID==ID_parent) OwnProps.one	();
-    else							OwnProps.assign	(own_mask);
-
-	R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_BREAKING));
-	fs.r_stringZ		(buf); 	BreakingSounds	= buf.size()?*buf:"";
-
-	R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_STEP));
-	fs.r_stringZ		(buf);	StepSounds		= buf.size()?*buf:"";
-
-	R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_COLLIDE));
-	fs.r_stringZ		(buf);	CollideSounds	= buf.size()?*buf:"";
-	fs.r_stringZ		(buf);	CollideParticles= buf.size()?*buf:"";
-	fs.r_stringZ		(buf);	CollideMarks	= buf.size()?*buf:"";
+    shared_str buf;
+
+    R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_PAIR));
+    mtl0 = fs.r_u32();
+    mtl1 = fs.r_u32();
+    ID = fs.r_u32();
+    ID_parent = fs.r_u32();
+    u32 own_mask = fs.r_u32();
+    if (GAMEMTL_NONE_ID==ID_parent) OwnProps.one ();
+    else OwnProps.assign (own_mask);
+
+    R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_BREAKING));
+    fs.r_stringZ (buf);
+    BreakingSounds = buf.size()?*buf:"";
+
+    R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_STEP));
+    fs.r_stringZ(buf);
+    StepSounds = buf.size() ? *buf : "";
+
+    R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_COLLIDE));
+    fs.r_stringZ(buf);
+    CollideSounds = buf.size() ? *buf : "";
+    fs.r_stringZ(buf);
+    CollideParticles = buf.size() ? *buf : "";
+    fs.r_stringZ(buf);
+    CollideMarks = buf.size() ? *buf : "";
 }
 #endif
 
 #ifdef DEBUG
 LPCSTR SGameMtlPair::dbg_Name()
 {
-	static string256 nm;
-	SGameMtl* M0 = GMLib.GetMaterialByID(GetMtl0());
-	SGameMtl* M1 = GMLib.GetMaterialByID(GetMtl1());
-	xr_sprintf(nm,sizeof(nm),"Pair: %s - %s",*M0->m_Name,*M1->m_Name);
-	return nm;
+    static string256 nm;
+    SGameMtl* M0 = GMLib.GetMaterialByID(GetMtl0());
+    SGameMtl* M1 = GMLib.GetMaterialByID(GetMtl1());
+    xr_sprintf(nm, sizeof(nm), "Pair: %s - %s", *M0->m_Name, *M1->m_Name);
+    return nm;
 }
 #endif
diff --git a/src/xrEngine/GameMtlLib.h b/src/xrEngine/GameMtlLib.h
index baf34520a15..f13bd4f7a05 100644
--- a/src/xrEngine/GameMtlLib.h
+++ b/src/xrEngine/GameMtlLib.h
@@ -4,37 +4,37 @@
 //---------------------------------------------------------------------------
 #pragma once
 
-#define GAMEMTL_CURRENT_VERSION			0x0001
+#define GAMEMTL_CURRENT_VERSION 0x0001
 //----------------------------------------------------
 
-#define GAMEMTLS_CHUNK_VERSION        	0x1000
-#define GAMEMTLS_CHUNK_AUTOINC	        0x1001
-#define GAMEMTLS_CHUNK_MTLS	        	0x1002
-#define GAMEMTLS_CHUNK_MTLS_PAIR       	0x1003
+#define GAMEMTLS_CHUNK_VERSION 0x1000
+#define GAMEMTLS_CHUNK_AUTOINC 0x1001
+#define GAMEMTLS_CHUNK_MTLS 0x1002
+#define GAMEMTLS_CHUNK_MTLS_PAIR 0x1003
 //----------------------------------------------------
-#define GAMEMTL_CHUNK_MAIN	        	0x1000
-#define GAMEMTL_CHUNK_FLAGS	        	0x1001
-#define GAMEMTL_CHUNK_PHYSICS        	0x1002
-#define GAMEMTL_CHUNK_FACTORS        	0x1003
-#define GAMEMTL_CHUNK_FLOTATION   		0x1004
-#define GAMEMTL_CHUNK_DESC				0x1005
-#define GAMEMTL_CHUNK_INJURIOUS			0x1006
-#define GAMEMTL_CHUNK_DENSITY			0x1007
-#define GAMEMTL_CHUNK_FACTORS_MP       	0x1008
+#define GAMEMTL_CHUNK_MAIN 0x1000
+#define GAMEMTL_CHUNK_FLAGS 0x1001
+#define GAMEMTL_CHUNK_PHYSICS 0x1002
+#define GAMEMTL_CHUNK_FACTORS 0x1003
+#define GAMEMTL_CHUNK_FLOTATION 0x1004
+#define GAMEMTL_CHUNK_DESC 0x1005
+#define GAMEMTL_CHUNK_INJURIOUS 0x1006
+#define GAMEMTL_CHUNK_DENSITY 0x1007
+#define GAMEMTL_CHUNK_FACTORS_MP 0x1008
 //----------------------------------------------------
-#define GAMEMTLPAIR_CHUNK_PAIR   		0x1000
-//#define GAMEMTLPAIR_CHUNK_FLOTATION   0x1001 - obsolete
-#define GAMEMTLPAIR_CHUNK_BREAKING   	0x1002
-#define GAMEMTLPAIR_CHUNK_STEP   		0x1003
-//#define GAMEMTLPAIR_CHUNK_COLLIDE   	0x1004 - obsolete / rename HIT
-#define GAMEMTLPAIR_CHUNK_COLLIDE	  	0x1005
+#define GAMEMTLPAIR_CHUNK_PAIR 0x1000
+//#define GAMEMTLPAIR_CHUNK_FLOTATION 0x1001 - obsolete
+#define GAMEMTLPAIR_CHUNK_BREAKING 0x1002
+#define GAMEMTLPAIR_CHUNK_STEP 0x1003
+//#define GAMEMTLPAIR_CHUNK_COLLIDE 0x1004 - obsolete / rename HIT
+#define GAMEMTLPAIR_CHUNK_COLLIDE 0x1005
 //----------------------------------------------------
 
-#define GAMEMTL_SUBITEM_COUNT			4
+#define GAMEMTL_SUBITEM_COUNT 4
 
-#define GAMEMTL_NONE_ID					u32(-1)
-#define GAMEMTL_NONE_IDX				u16(-1)
-#define GAMEMTL_FILENAME				"gamemtl.xr"
+#define GAMEMTL_NONE_ID u32(-1)
+#define GAMEMTL_NONE_IDX u16(-1)
+#define GAMEMTL_FILENAME "gamemtl.xr"
 
 #ifdef _EDITOR
 #define GM_NON_GAME
@@ -49,316 +49,320 @@
 #define GM_NON_GAME
 #endif
 
-#ifndef	MTL_EXPORT_API
+#ifndef MTL_EXPORT_API
 #ifdef _EDITOR
-	#include "ElTree.hpp"
-	#define MTL_EXPORT_API ECORE_API
+#include "ElTree.hpp"
+#define MTL_EXPORT_API ECORE_API
 #else
-	#define MTL_EXPORT_API ENGINE_API
+#define MTL_EXPORT_API ENGINE_API
 #endif
 #endif
 
 #ifdef GM_NON_GAME
-	#define SoundVec	shared_str
-	#define PSVec 		shared_str
-	#define ShaderVec 	shared_str
-//	#define ShaderVec 	shared_str
+#define SoundVec shared_str
+#define PSVec shared_str
+#define ShaderVec shared_str
+// #define ShaderVec shared_str
 #else
-	DEFINE_VECTOR(ref_sound,SoundVec,SoundIt);
-	DEFINE_VECTOR(shared_str,PSVec,PSIt);
+DEFINE_VECTOR(ref_sound, SoundVec, SoundIt);
+DEFINE_VECTOR(shared_str, PSVec, PSIt);
 #include "../Include/xrRender/WallMarkArray.h"
 #include "../Include/xrRender/RenderFactory.h"
-//	DEFINE_VECTOR(ref_shader,ShaderVec,ShaderIt);
+// DEFINE_VECTOR(ref_shader,ShaderVec,ShaderIt);
 #endif
 
 struct MTL_EXPORT_API SGameMtl
 {
-	friend class CGameMtlLibrary;
+    friend class CGameMtlLibrary;
 protected:
-	int 				ID; 	// auto number
+    int ID; // auto number
 public:
-	enum{
-    	flBreakable		= (1ul<<0ul),
-//		flShootable 	= (1ul<<1ul),
-        flBounceable	= (1ul<<2ul),
-        flSkidmark		= (1ul<<3ul),
-        flBloodmark		= (1ul<<4ul),
-        flClimable		= (1ul<<5ul),
-//		flWalkOn		= (1ul<<6ul), // obsolette
-        flPassable		= (1ul<<7ul),
-        flDynamic		= (1ul<<8ul),
-        flLiquid 		= (1ul<<9ul),
-		flSuppressShadows	= (1ul<<10ul),
-		flSuppressWallmarks	= (1ul<<11ul),
-		flActorObstacle	= (1ul<<12ul),
-		flNoRicoshet	= (1ul<<13ul),
+    enum
+    {
+        flBreakable = (1ul << 0ul),
+        // flShootable = (1ul<<1ul),
+        flBounceable = (1ul << 2ul),
+        flSkidmark = (1ul << 3ul),
+        flBloodmark = (1ul << 4ul),
+        flClimable = (1ul << 5ul),
+        // flWalkOn = (1ul<<6ul), // obsolette
+        flPassable = (1ul << 7ul),
+        flDynamic = (1ul << 8ul),
+        flLiquid = (1ul << 9ul),
+        flSuppressShadows = (1ul << 10ul),
+        flSuppressWallmarks = (1ul << 11ul),
+        flActorObstacle = (1ul << 12ul),
+        flNoRicoshet = (1ul << 13ul),
+
 
 
-		
-        flInjurious		= (1ul<<28ul),// flInjurious = fInjuriousSpeed > 0.f
-		flShootable 	= (1ul<<29ul),
-        flTransparent	= (1ul<<30ul),
-        flSlowDown		= (1ul<<31ul) // flSlowDown = (fFlotationFactor<1.f)
+        flInjurious = (1ul << 28ul),// flInjurious = fInjuriousSpeed > 0.f
+        flShootable = (1ul << 29ul),
+        flTransparent = (1ul << 30ul),
+        flSlowDown = (1ul << 31ul) // flSlowDown = (fFlotationFactor<1.f)
     };
 public:
-	shared_str			m_Name;
-    shared_str			m_Desc;
+    shared_str m_Name;
+    shared_str m_Desc;
 
-    Flags32				Flags;
+    Flags32 Flags;
     // physics part
-    float				fPHFriction;            // ?
-    float				fPHDamping;             // ?
-    float				fPHSpring;              // ?
-    float				fPHBounceStartVelocity;	// ?
-	float				fPHBouncing;            // ?
-	// shoot&bounce&visibility&flotation
-    float		    	fFlotationFactor;		// 0.f - 1.f   	(1.f-ïîëíîñòüþ ïðîõîäèìûé)
-    float				fShootFactor;			// 0.f - 1.f	(1.f-ïîëíîñòüþ ïðîñòðåëèâàåìûé)
-    float				fShootFactorMP;			// 0.f - 1.f	(1.f-ïîëíîñòüþ ïðîñòðåëèâàåìûé)
-    float				fBounceDamageFactor;	// 0.f - 100.f
-    float				fInjuriousSpeed; 		// 0.f - ...	(0.f-íå îòáèðàåò çäîðîâüå (ñêîðîñòü óìåíüøåíèÿ çäîðîâüÿ))
-    float				fVisTransparencyFactor;	// 0.f - 1.f	(1.f-ïîëíîñòüþ ïðîçðà÷íûé)
-    float				fSndOcclusionFactor;	// 0.f - 1.f    (1.f-ïîëíîñòüþ ñëûøåí)
-	float				fDensityFactor;
+    float fPHFriction; // ?
+    float fPHDamping; // ?
+    float fPHSpring; // ?
+    float fPHBounceStartVelocity; // ?
+    float fPHBouncing; // ?
+    // shoot&bounce&visibility&flotation
+    float fFlotationFactor; // 0.f - 1.f (1.f-ïîëíîñòüþ ïðîõîäèìûé)
+    float fShootFactor; // 0.f - 1.f (1.f-ïîëíîñòüþ ïðîñòðåëèâàåìûé)
+    float fShootFactorMP; // 0.f - 1.f (1.f-ïîëíîñòüþ ïðîñòðåëèâàåìûé)
+    float fBounceDamageFactor; // 0.f - 100.f
+    float fInjuriousSpeed; // 0.f - ... (0.f-íå îòáèðàåò çäîðîâüå (ñêîðîñòü óìåíüøåíèÿ çäîðîâüÿ))
+    float fVisTransparencyFactor; // 0.f - 1.f (1.f-ïîëíîñòüþ ïðîçðà÷íûé)
+    float fSndOcclusionFactor; // 0.f - 1.f (1.f-ïîëíîñòüþ ñëûøåí)
+    float fDensityFactor;
 public:
-	SGameMtl			()
+    SGameMtl()
     {
-        ID						= -1;
-		m_Name					= "unknown";
-        Flags.zero				();
+        ID = -1;
+        m_Name = "unknown";
+        Flags.zero();
         // factors
-        fFlotationFactor		= 1.f;
-        fShootFactor			= 0.f;
-        fShootFactorMP			= 0.f;
-        fBounceDamageFactor		= 1.f;
-        fInjuriousSpeed 		= 0.f;
-        fVisTransparencyFactor	= 0.f;
-        fSndOcclusionFactor		= 0.f;
+        fFlotationFactor = 1.f;
+        fShootFactor = 0.f;
+        fShootFactorMP = 0.f;
+        fBounceDamageFactor = 1.f;
+        fInjuriousSpeed = 0.f;
+        fVisTransparencyFactor = 0.f;
+        fSndOcclusionFactor = 0.f;
         // physics
-        fPHFriction				= 1.f;
-        fPHDamping				= 1.f;
-        fPHSpring				= 1.f;
-        fPHBounceStartVelocity  = 0.f;
-        fPHBouncing				= 0.1f;
-		fDensityFactor			= 0.0f;
-	}
-    void 				Load			(IReader& fs);
-    void 				Save			(IWriter& fs);
-    IC int				GetID			(){return ID;}
+        fPHFriction = 1.f;
+        fPHDamping = 1.f;
+        fPHSpring = 1.f;
+        fPHBounceStartVelocity = 0.f;
+        fPHBouncing = 0.1f;
+        fDensityFactor = 0.0f;
+    }
+    void Load(IReader& fs);
+    void Save(IWriter& fs);
+    IC int GetID () {return ID;}
 #ifdef _EDITOR
-    void 				FillProp		(PropItemVec& values, ListItem* owner);
+    void FillProp(PropItemVec& values, ListItem* owner);
 #endif
 };
-DEFINE_VECTOR(SGameMtl*,GameMtlVec,GameMtlIt);
+DEFINE_VECTOR(SGameMtl*, GameMtlVec, GameMtlIt);
 
-struct MTL_EXPORT_API SGameMtlPair{
-	friend class CGameMtlLibrary;
-    CGameMtlLibrary*	m_Owner;
+struct MTL_EXPORT_API SGameMtlPair
+{
+    friend class CGameMtlLibrary;
+    CGameMtlLibrary* m_Owner;
 private:
-	int					mtl0;
-	int					mtl1;
+    int mtl0;
+    int mtl1;
 protected:
-	int 				ID; 	// auto number
-    int					ID_parent;
+    int ID; // auto number
+    int ID_parent;
 public:
-	enum{
-//		flFlotation		= (1<<0),
-        flBreakingSounds= (1<<1),
-        flStepSounds	= (1<<2),
-//		flCollideSounds	= (1<<3),
-        flCollideSounds		= (1<<4),
-        flCollideParticles	= (1<<5),
-        flCollideMarks		= (1<<6)
+    enum
+    {
+        // flFlotation = (1<<0),
+        flBreakingSounds = (1 << 1),
+        flStepSounds = (1 << 2),
+        // flCollideSounds = (1<<3),
+        flCollideSounds = (1 << 4),
+        flCollideParticles = (1 << 5),
+        flCollideMarks = (1 << 6)
     };
-    Flags32				OwnProps;
-//	properties
-    SoundVec			BreakingSounds;
-    SoundVec			StepSounds;
-    SoundVec			CollideSounds;
-    PSVec				CollideParticles;
+    Flags32 OwnProps;
+    // properties
+    SoundVec BreakingSounds;
+    SoundVec StepSounds;
+    SoundVec CollideSounds;
+    PSVec CollideParticles;
 
 
-#ifdef	GM_NON_GAME
-	#define ShaderVec 	shared_str
-    ShaderVec			CollideMarks;
-#else	//	GM_NON_GAME
-	FactoryPtr m_pCollideMarks;
-#endif	//	GM_NON_GAME
+#ifdef GM_NON_GAME
+#define ShaderVec shared_str
+    ShaderVec CollideMarks;
+#else // GM_NON_GAME
+    FactoryPtr m_pCollideMarks;
+#endif // GM_NON_GAME
 #ifdef _EDITOR
-    PropValue*			propBreakingSounds;
-    PropValue*			propStepSounds;
-    PropValue*			propCollideSounds;
-    PropValue*			propCollideParticles;
-    PropValue*			propCollideMarks;
-    void __stdcall	 	OnFlagChange	(PropValue* sender);
-	void __stdcall	 	OnParentClick	(ButtonValue* sender, bool& bModif, bool& bSafe);
-	void __stdcall	 	OnCommandClick	(ButtonValue* sender, bool& bModif, bool& bSafe);
-    void __stdcall	 	FillChooseMtl	(ChooseItemVec& items, void* param);
-	void 				CopyFrom		(SGameMtlPair* parent);
+    PropValue* propBreakingSounds;
+    PropValue* propStepSounds;
+    PropValue* propCollideSounds;
+    PropValue* propCollideParticles;
+    PropValue* propCollideMarks;
+    void __stdcall OnFlagChange (PropValue* sender);
+    void __stdcall OnParentClick (ButtonValue* sender, bool& bModif, bool& bSafe);
+    void __stdcall OnCommandClick(ButtonValue* sender, bool& bModif, bool& bSafe);
+    void __stdcall FillChooseMtl(ChooseItemVec& items, void* param);
+    void CopyFrom(SGameMtlPair* parent);
 #endif
 public:
-	SGameMtlPair		(CGameMtlLibrary* owner)
+    SGameMtlPair(CGameMtlLibrary* owner)
     {
-#ifndef	GM_NON_GAME
-		//m_pCollideMarks = RenderFactory->CreateGameMtlPair();
-#endif	//	GM_NON_GAME
-    	mtl0			= -1;
-    	mtl1			= -1;
-        ID				= -1;
-        ID_parent		= -1;
-        m_Owner			= owner;
-        OwnProps.one	();
-	}
-	~SGameMtlPair		();
-    IC int				GetMtl0			(){return mtl0;}
-    IC int				GetMtl1			(){return mtl1;}
-    IC int				GetID			(){return ID;}
-    IC void				SetPair			(int m0, int m1){mtl0=m0; mtl1=m1;}
-	IC bool				IsPair			(int m0, int m1){return !!(((mtl0==m0)&&(mtl1==m1))||((mtl0==m1)&&(mtl1==m0)));}
-    void				Save			(IWriter& fs);
-    void				Load			(IReader& fs);
-    IC int 				GetParent		(){return ID_parent;}
-    BOOL				SetParent		(int parent);
+#ifndef GM_NON_GAME
+        //m_pCollideMarks = RenderFactory->CreateGameMtlPair();
+#endif // GM_NON_GAME
+        mtl0 = -1;
+        mtl1 = -1;
+        ID = -1;
+        ID_parent = -1;
+        m_Owner = owner;
+        OwnProps.one();
+    }
+    ~SGameMtlPair();
+    IC int GetMtl0() { return mtl0; }
+    IC int GetMtl1() { return mtl1; }
+    IC int GetID() { return ID; }
+    IC void SetPair(int m0, int m1) { mtl0 = m0; mtl1 = m1; }
+    IC bool IsPair(int m0, int m1) { return !!(((mtl0 == m0) && (mtl1 == m1)) || ((mtl0 == m1) && (mtl1 == m0))); }
+    void Save(IWriter& fs);
+    void Load (IReader& fs);
+    IC int GetParent () {return ID_parent;}
+    BOOL SetParent (int parent);
 #ifdef _EDITOR
-	void 				FillProp		(PropItemVec& values);
-    void				TransferFromParent(SGameMtlPair* parent);
+    void FillProp(PropItemVec& values);
+    void TransferFromParent(SGameMtlPair* parent);
 #endif
 #ifdef DEBUG
-	LPCSTR				dbg_Name		();
+    LPCSTR dbg_Name();
 #endif
 };
 
-DEFINE_VECTOR(SGameMtlPair*,GameMtlPairVec,GameMtlPairIt);
+DEFINE_VECTOR(SGameMtlPair*, GameMtlPairVec, GameMtlPairIt);
 
-class MTL_EXPORT_API CGameMtlLibrary{
-	int					material_index;
-	int					material_pair_index;
-	BENCH_SEC_SCRAMBLEMEMBER1
+class MTL_EXPORT_API CGameMtlLibrary
+{
+    int material_index;
+    int material_pair_index;
+    BENCH_SEC_SCRAMBLEMEMBER1
 
-	GameMtlVec			materials;
-    GameMtlPairVec		material_pairs;
+        GameMtlVec materials;
+    GameMtlPairVec material_pairs;
 
 #ifndef _EDITOR
     // game part
-    u32					material_count;
-    GameMtlPairVec		material_pairs_rt;
+    u32 material_count;
+    GameMtlPairVec material_pairs_rt;
 #endif
 public:
-	CGameMtlLibrary		();
-	~CGameMtlLibrary	()
-	{
-		/*
-    	R_ASSERT		(0==material_pairs_rt.size());
-    	R_ASSERT		(0==material_pairs.size());
-    	R_ASSERT		(0==materials.size());
-		*/
+    CGameMtlLibrary();
+    ~CGameMtlLibrary()
+    {
+        /*
+        R_ASSERT (0==material_pairs_rt.size());
+        R_ASSERT (0==material_pairs.size());
+        R_ASSERT (0==materials.size());
+        */
     }
-	IC void				Unload			()
-	{
+    IC void Unload()
+    {
 #ifndef _EDITOR
-		material_count	= 0;
-		material_pairs_rt.clear();
+        material_count = 0;
+        material_pairs_rt.clear();
 #endif
-		for (GameMtlIt m_it=materials.begin(); materials.end() != m_it; ++m_it)
-			xr_delete	(*m_it);
-		materials.clear();
-		for (GameMtlPairIt p_it=material_pairs.begin(); material_pairs.end() != p_it; ++p_it)
-			xr_delete	(*p_it);
-		material_pairs.clear();
-	}
+        for (GameMtlIt m_it = materials.begin(); materials.end() != m_it; ++m_it)
+            xr_delete(*m_it);
+        materials.clear();
+        for (GameMtlPairIt p_it = material_pairs.begin(); material_pairs.end() != p_it; ++p_it)
+            xr_delete(*p_it);
+        material_pairs.clear();
+    }
     // material routine
-    IC GameMtlIt 		GetMaterialIt	(LPCSTR name)
+    IC GameMtlIt GetMaterialIt(LPCSTR name)
     {
-        for (GameMtlIt it=materials.begin(); materials.end() != it; ++it)
-            if (0==strcmpi(*(*it)->m_Name,name)) return it;
+        for (GameMtlIt it = materials.begin(); materials.end() != it; ++it)
+            if (0 == strcmpi(*(*it)->m_Name, name)) return it;
         return materials.end();
     }
-    IC GameMtlIt 		GetMaterialIt	(shared_str& name)
+    IC GameMtlIt GetMaterialIt(shared_str& name)
     {
-        for (GameMtlIt it=materials.begin(); materials.end() != it; ++it)
+        for (GameMtlIt it = materials.begin(); materials.end() != it; ++it)
             if (name.equal((*it)->m_Name)) return it;
         return materials.end();
     }
-    IC GameMtlIt 		GetMaterialItByID(int id)
+    IC GameMtlIt GetMaterialItByID(int id)
     {
-        for (GameMtlIt it=materials.begin(); materials.end() != it; ++it)
-            if ((*it)->ID==id) return it;
+        for (GameMtlIt it = materials.begin(); materials.end() != it; ++it)
+            if ((*it)->ID == id) return it;
         return materials.end();
     }
-	IC u32				GetMaterialID	(LPCSTR name)
+    IC u32 GetMaterialID(LPCSTR name)
     {
-    	GameMtlIt it	= GetMaterialIt	(name);
+        GameMtlIt it = GetMaterialIt (name);
         return (it==materials.end())?GAMEMTL_NONE_ID:(*it)->ID;
     }
 #ifdef _EDITOR
-	// editor
-	SGameMtl*			AppendMaterial	(SGameMtl* parent);
-	void				RemoveMaterial	(LPCSTR name);
-	IC SGameMtl*		GetMaterialByID	(int ID)
+    // editor
+    SGameMtl* AppendMaterial (SGameMtl* parent);
+    void RemoveMaterial (LPCSTR name);
+    IC SGameMtl* GetMaterialByID (int ID)
     {
-	    GameMtlIt it=GetMaterialItByID(ID);
-    	return materials.end() != it?*it:0;
+        GameMtlIt it=GetMaterialItByID(ID);
+        return materials.end() != it?*it:0;
     }
-	IC SGameMtl*		GetMaterial		(LPCSTR name)
+    IC SGameMtl* GetMaterial (LPCSTR name)
     {
-	    GameMtlIt it=GetMaterialIt(name);
-    	return materials.end() != it?*it:0;
-	}
+        GameMtlIt it = GetMaterialIt(name);
+        return materials.end() != it ? *it : 0;
+    }
 #else
-	// game
-	IC SGameMtl*		GetMaterialByID (s32 id)		{return GetMaterialByIdx(GetMaterialIdx(id));}
+    // game
+    IC SGameMtl* GetMaterialByID(s32 id) { return GetMaterialByIdx(GetMaterialIdx(id)); }
 #endif
-	IC u16				GetMaterialIdx	(int ID)		{GameMtlIt it=GetMaterialItByID(ID);VERIFY(materials.end() != it); return (u16)(it-materials.begin());}
-	IC u16				GetMaterialIdx	(LPCSTR name)	{GameMtlIt it=GetMaterialIt(name);VERIFY(materials.end() != it); return (u16)(it-materials.begin());}
-	IC SGameMtl*		GetMaterialByIdx(u16 idx)		{VERIFY(idx<(u16)materials.size()); return materials[idx];}
+    IC u16 GetMaterialIdx(int ID) { GameMtlIt it = GetMaterialItByID(ID); VERIFY(materials.end() != it); return (u16)(it - materials.begin()); }
+    IC u16 GetMaterialIdx(LPCSTR name) { GameMtlIt it = GetMaterialIt(name); VERIFY(materials.end() != it); return (u16)(it - materials.begin()); }
+    IC SGameMtl* GetMaterialByIdx(u16 idx) { VERIFY(idx < (u16)materials.size()); return materials[idx]; }
 
 
-	IC GameMtlIt		FirstMaterial	(){return materials.begin();}
-	IC GameMtlIt		LastMaterial	(){return materials.end();}
-	IC u32				CountMaterial	(){return materials.size();}
+    IC GameMtlIt FirstMaterial() { return materials.begin(); }
+    IC GameMtlIt LastMaterial () {return materials.end();}
+    IC u32 CountMaterial () {return materials.size();}
 
-// material pair routine
+    // material pair routine
 #ifdef _EDITOR
-	void 				CopyMtlPairs		(SGameMtl* from, SGameMtl* to);
-	BOOL				UpdateMtlPairs		(SGameMtl* src);
-	BOOL				UpdateMtlPairs		();
-	LPCSTR				MtlPairToName		(int mtl0, int mtl1);
-	void				NameToMtlPair		(LPCSTR name, int& mtl0, int& mtl1);
-	void				MtlNameToMtlPair	(LPCSTR name, int& mtl0, int& mtl1);
-	SGameMtlPair*		CreateMaterialPair	(int m0, int m1, SGameMtlPair* parent=0);
-	SGameMtlPair*		AppendMaterialPair	(int m0, int m1, SGameMtlPair* parent=0);
-	void				RemoveMaterialPair	(LPCSTR name);
-	void				RemoveMaterialPair	(GameMtlPairIt rem_it);
-	void				RemoveMaterialPair	(int mtl);
-	void				RemoveMaterialPair	(int mtl0, int mtl1);
-	GameMtlPairIt		GetMaterialPairIt	(int id);
-	SGameMtlPair*		GetMaterialPair		(int id);
-	GameMtlPairIt		GetMaterialPairIt	(int mtl0, int mtl1);
-	SGameMtlPair*		GetMaterialPair		(int mtl0, int mtl1);
-	SGameMtlPair*		GetMaterialPair		(LPCSTR name);
+    void CopyMtlPairs (SGameMtl* from, SGameMtl* to);
+    BOOL UpdateMtlPairs (SGameMtl* src);
+    BOOL UpdateMtlPairs ();
+    LPCSTR MtlPairToName (int mtl0, int mtl1);
+    void NameToMtlPair (LPCSTR name, int& mtl0, int& mtl1);
+    void MtlNameToMtlPair (LPCSTR name, int& mtl0, int& mtl1);
+    SGameMtlPair* CreateMaterialPair (int m0, int m1, SGameMtlPair* parent=0);
+    SGameMtlPair* AppendMaterialPair (int m0, int m1, SGameMtlPair* parent=0);
+    void RemoveMaterialPair (LPCSTR name);
+    void RemoveMaterialPair (GameMtlPairIt rem_it);
+    void RemoveMaterialPair (int mtl);
+    void RemoveMaterialPair (int mtl0, int mtl1);
+    GameMtlPairIt GetMaterialPairIt (int id);
+    SGameMtlPair* GetMaterialPair(int id);
+    GameMtlPairIt GetMaterialPairIt(int mtl0, int mtl1);
+    SGameMtlPair* GetMaterialPair(int mtl0, int mtl1);
+    SGameMtlPair* GetMaterialPair(LPCSTR name);
 #else
-	// game
-	IC SGameMtlPair*	GetMaterialPair		(u16 idx0, u16 idx1){R_ASSERT((idx0_a_vector_.empty(),_mtl_pair_->dbg_Name());\
-	_res_.clone(GET_RANDOM(_mtl_pair_##->_a_vector_),st_Effect,sg_SourceType);\
-	}
+ { VERIFY2(!_mtl_pair_##->_a_vector_.empty(),_mtl_pair_->dbg_Name());\
+ _res_.clone(GET_RANDOM(_mtl_pair_##->_a_vector_),st_Effect,sg_SourceType);\
+ }
 
-extern MTL_EXPORT_API CGameMtlLibrary		GMLib;
+extern MTL_EXPORT_API CGameMtlLibrary GMLib;
 
-//#ifdef	_EDITOR
-//extern MTL_EXPORT_API CGameMtlLibrary*		PGMLib;
+//#ifdef _EDITOR
+//extern MTL_EXPORT_API CGameMtlLibrary* PGMLib;
 //#else
 #include "../include/xrapi/xrapi.h"
 //#endif
diff --git a/src/xrEngine/GameMtlLib_Engine.cpp b/src/xrEngine/GameMtlLib_Engine.cpp
index 2f123e5dab1..bb6c9eb17d9 100644
--- a/src/xrEngine/GameMtlLib_Engine.cpp
+++ b/src/xrEngine/GameMtlLib_Engine.cpp
@@ -6,94 +6,101 @@
 
 void DestroySounds(SoundVec& lst)
 {
-	for (SoundIt it=lst.begin(); lst.end() != it; ++it)	
-		it->destroy();
+    for (SoundIt it = lst.begin(); lst.end() != it; ++it)
+        it->destroy();
 }
 /*
 void DestroyMarks(ShaderVec& lst)
 {
-	for (ShaderIt it=lst.begin(); lst.end() != it; ++it)
-		it->destroy();
+for (ShaderIt it=lst.begin(); lst.end() != it; ++it)
+it->destroy();
 }
 */
 
 void DestroyPSs(PSVec& lst)
 {
-//	for (PSIt it=lst.begin(); lst.end() != it; ++it)
-//		Device.Resources->Delete(*it);
+    // for (PSIt it=lst.begin(); lst.end() != it; ++it)
+    // Device.Resources->Delete(*it);
 }
 
 void CreateSounds(SoundVec& lst, LPCSTR buf)
 {
-	string128 tmp;
-	int cnt			=	_GetItemCount(buf);	R_ASSERT(cnt<=GAMEMTL_SUBITEM_COUNT+2);
-	lst.resize		(cnt);
-	for (int k=0; kAppendMark(_GetItem(buf,k,tmp));
+    string256 tmp;
+    int cnt = _GetItemCount(buf);
+    R_ASSERT(cnt <= GAMEMTL_SUBITEM_COUNT);
+    for (int k = 0; k < cnt; ++k)
+        pMarks->AppendMark(_GetItem(buf, k, tmp));
 }
 
 
 void CreatePSs(PSVec& lst, LPCSTR buf)
 {
-	string256 tmp;
-	int cnt=_GetItemCount(buf);	R_ASSERT(cnt<=GAMEMTL_SUBITEM_COUNT);
-	for (int k=0; kDestroyGameMtlPair(m_pCollideMarks);
-	//m_pCollideMarks->
+    // destroy all media
+    DestroySounds(BreakingSounds);
+    DestroySounds(StepSounds);
+    DestroySounds(CollideSounds);
+    DestroyPSs(CollideParticles);
+    // DestroyMarks (CollideMarks);
+    //RenderFactory->DestroyGameMtlPair(m_pCollideMarks);
+    //m_pCollideMarks->
 }
 
 void SGameMtlPair::Load(IReader& fs)
 {
-	shared_str				buf;
+    shared_str buf;
+
+    R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_PAIR));
+    mtl0 = fs.r_u32();
+    mtl1 = fs.r_u32();
+    ID = fs.r_u32();
+    ID_parent = fs.r_u32();
+    OwnProps.assign(fs.r_u32());
 
-	R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_PAIR));
-    mtl0				= fs.r_u32();
-    mtl1				= fs.r_u32();
-    ID					= fs.r_u32();
-    ID_parent			= fs.r_u32();
-    OwnProps.assign		(fs.r_u32());
- 
     R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_BREAKING));
-    fs.r_stringZ			(buf); 		CreateSounds		(BreakingSounds,*buf);
-    
+    fs.r_stringZ(buf);
+    CreateSounds(BreakingSounds, *buf);
+
     R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_STEP));
-    fs.r_stringZ			(buf);		CreateSounds		(StepSounds,*buf);
-    
-	R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_COLLIDE));
-    fs.r_stringZ			(buf);		CreateSounds		(CollideSounds,*buf);
-    fs.r_stringZ			(buf);		CreatePSs			(CollideParticles,*buf);
-    fs.r_stringZ			(buf);		
-	//CreateMarks			(CollideMarks,*buf);
-	CreateMarks			(&*m_pCollideMarks,*buf);
+    fs.r_stringZ(buf);
+    CreateSounds(StepSounds, *buf);
+
+    R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_COLLIDE));
+    fs.r_stringZ(buf);
+    CreateSounds(CollideSounds, *buf);
+    fs.r_stringZ(buf);
+    CreatePSs(CollideParticles, *buf);
+    fs.r_stringZ(buf);
+    //CreateMarks (CollideMarks,*buf);
+    CreateMarks(&*m_pCollideMarks, *buf);
 }
diff --git a/src/xrEngine/ICollidable.cpp b/src/xrEngine/ICollidable.cpp
index 081a1605c01..959f08d34d4 100644
--- a/src/xrEngine/ICollidable.cpp
+++ b/src/xrEngine/ICollidable.cpp
@@ -3,13 +3,13 @@
 #include "icollidable.h"
 #include "xr_collide_form.h"
 
-ICollidable::ICollidable()		
+ICollidable::ICollidable()
 {
-	collidable.model					=	NULL;		
-	ISpatial*		self				=	dynamic_cast (this);
-	if (self)		self->spatial.type	|=	STYPE_COLLIDEABLE;
+    collidable.model = NULL;
+    ISpatial* self = dynamic_cast (this);
+    if (self) self->spatial.type |= STYPE_COLLIDEABLE;
 };
-ICollidable::~ICollidable()		
+ICollidable::~ICollidable()
 {
-	xr_delete		( collidable.model );	
+    xr_delete(collidable.model);
 };
diff --git a/src/xrEngine/ICollidable.h b/src/xrEngine/ICollidable.h
index 79c3e0344f1..936b42a47da 100644
--- a/src/xrEngine/ICollidable.h
+++ b/src/xrEngine/ICollidable.h
@@ -1,14 +1,15 @@
 #pragma once
 
-class	ENGINE_API	ICollisionForm;
+class ENGINE_API ICollisionForm;
 
-class	ENGINE_API	ICollidable	{
+class ENGINE_API ICollidable
+{
 public:
-	struct 
-	{
-		ICollisionForm*			model;
-	}							collidable;
+    struct
+    {
+        ICollisionForm* model;
+    } collidable;
 public:
-	ICollidable();
-	virtual ~ICollidable();
+    ICollidable();
+    virtual ~ICollidable();
 };
diff --git a/src/xrEngine/IGame_Level.cpp b/src/xrEngine/IGame_Level.cpp
index c835c26f065..177e58b29f6 100644
--- a/src/xrEngine/IGame_Level.cpp
+++ b/src/xrEngine/IGame_Level.cpp
@@ -14,334 +14,345 @@
 
 #include "securom_api.h"
 
-ENGINE_API	IGame_Level*	g_pGameLevel	= NULL;
-extern	BOOL g_bLoaded;
+ENGINE_API IGame_Level* g_pGameLevel = NULL;
+extern BOOL g_bLoaded;
 
-IGame_Level::IGame_Level	()
+IGame_Level::IGame_Level()
 {
-	m_pCameras					= xr_new(true);
-	g_pGameLevel				= this;
-	pLevel						= NULL;
-	bReady						= false;
-	pCurrentEntity				= NULL;
-	pCurrentViewEntity			= NULL;
-	Device.DumpResourcesMemoryUsage();
+    m_pCameras = xr_new(true);
+    g_pGameLevel = this;
+    pLevel = NULL;
+    bReady = false;
+    pCurrentEntity = NULL;
+    pCurrentViewEntity = NULL;
+    Device.DumpResourcesMemoryUsage();
 }
 
 //#include "resourcemanager.h"
 
-IGame_Level::~IGame_Level	()
+IGame_Level::~IGame_Level()
 {
-	if(strstr(Core.Params,"-nes_texture_storing") )
-		//Device.Resources->StoreNecessaryTextures();
-		Device.m_pRender->ResourcesStoreNecessaryTextures();
-	xr_delete					( pLevel		);
-
-	// Render-level unload
-	Render->level_Unload		();
-	xr_delete					(m_pCameras);
-	// Unregister
-	Device.seqRender.Remove		(this);
-	Device.seqFrame.Remove		(this);
-	CCameraManager::ResetPP		();
-///////////////////////////////////////////
-	Sound->set_geometry_occ		(NULL);
-	Sound->set_handler			(NULL);
-	Device.DumpResourcesMemoryUsage();
-
-	u32		m_base=0,c_base=0,m_lmaps=0,c_lmaps=0;
-	if (Device.m_pRender) 
-		Device.m_pRender->ResourcesGetMemoryUsage(m_base,c_base,m_lmaps,c_lmaps);
-
-	Msg		("* [ D3D ]: textures[%d K]", (m_base+m_lmaps)/1024);
+    if (strstr(Core.Params, "-nes_texture_storing"))
+        //Device.Resources->StoreNecessaryTextures();
+        Device.m_pRender->ResourcesStoreNecessaryTextures();
+    xr_delete(pLevel);
+
+    // Render-level unload
+    Render->level_Unload();
+    xr_delete(m_pCameras);
+    // Unregister
+    Device.seqRender.Remove(this);
+    Device.seqFrame.Remove(this);
+    CCameraManager::ResetPP();
+    ///////////////////////////////////////////
+    Sound->set_geometry_occ(NULL);
+    Sound->set_handler(NULL);
+    Device.DumpResourcesMemoryUsage();
+
+    u32 m_base = 0, c_base = 0, m_lmaps = 0, c_lmaps = 0;
+    if (Device.m_pRender)
+        Device.m_pRender->ResourcesGetMemoryUsage(m_base, c_base, m_lmaps, c_lmaps);
+
+    Msg("* [ D3D ]: textures[%d K]", (m_base + m_lmaps) / 1024);
 
 }
 
-void IGame_Level::net_Stop			()
+void IGame_Level::net_Stop()
 {
-	for (int i=0; i<6; i++)
-		Objects.Update			(false);
-	// Destroy all objects
-	Objects.Unload				( );
-	IR_Release					( );
+    for (int i = 0; i < 6; i++)
+        Objects.Update(false);
+    // Destroy all objects
+    Objects.Unload();
+    IR_Release();
 
-	bReady						= false;	
+    bReady = false;
 }
 
 //-------------------------------------------------------------------------------------------
-//extern CStatTimer				tscreate;
-void __stdcall _sound_event		(ref_sound_data_ptr S, float range)
+//extern CStatTimer tscreate;
+void __stdcall _sound_event(ref_sound_data_ptr S, float range)
 {
-	if ( g_pGameLevel && S && S->feedback )	g_pGameLevel->SoundEvent_Register	(S,range);
+    if (g_pGameLevel && S && S->feedback) g_pGameLevel->SoundEvent_Register(S, range);
 }
-static void __stdcall	build_callback	(Fvector* V, int Vcnt, CDB::TRI* T, int Tcnt, void* params)
+static void __stdcall build_callback(Fvector* V, int Vcnt, CDB::TRI* T, int Tcnt, void* params)
 {
-	g_pGameLevel->Load_GameSpecific_CFORM( T, Tcnt );
+    g_pGameLevel->Load_GameSpecific_CFORM(T, Tcnt);
 }
 
-bool IGame_Level::Load			(u32 dwNum) 
+bool IGame_Level::Load(u32 dwNum)
 {
-	SECUROM_MARKER_PERFORMANCE_ON(10)
-
-	// Initialize level data
-	pApp->Level_Set				( dwNum );
-	string_path					temp;
-	if (!FS.exist(temp, "$level$", "level.ltx"))
-		Debug.fatal	(DEBUG_INFO,"Can't find level configuration file '%s'.",temp);
-	pLevel						= xr_new	( temp );
-	
-	// Open
-//	g_pGamePersistent->LoadTitle	("st_opening_stream");
-	g_pGamePersistent->LoadTitle	();
-	IReader* LL_Stream			= FS.r_open	("$level$","level");
-	IReader	&fs					= *LL_Stream;
-
-	// Header
-	hdrLEVEL					H;
-	fs.r_chunk_safe				(fsL_HEADER,&H,sizeof(H));
-	R_ASSERT2					(XRCL_PRODUCTION_VERSION==H.XRLC_version,"Incompatible level version.");
-
-	// CForms
-//	g_pGamePersistent->LoadTitle	("st_loading_cform");
-	g_pGamePersistent->LoadTitle	();
-	ObjectSpace.Load			( build_callback );
-	//Sound->set_geometry_occ		( &Static );
-	Sound->set_geometry_occ		(ObjectSpace.GetStaticModel	());
-	Sound->set_handler			( _sound_event );
-
-	pApp->LoadSwitch			();
-
-
-	// HUD + Environment
-	if(!g_hud)
-		g_hud					= (CCustomHUD*)NEW_INSTANCE	(CLSID_HUDMANAGER);
-
-	// Render-level Load
-	Render->level_Load			(LL_Stream);
-	// tscreate.FrameEnd			();
-	// Msg						("* S-CREATE: %f ms, %d times",tscreate.result,tscreate.count);
-
-	// Objects
-	g_pGamePersistent->Environment().mods_load	();
-	R_ASSERT					(Load_GameSpecific_Before());
-	Objects.Load				();
-//. ANDY	R_ASSERT					(Load_GameSpecific_After ());
-
-	// Done
-	FS.r_close					( LL_Stream );
-	bReady						= true;
-	if (!g_dedicated_server)	IR_Capture();
+    SECUROM_MARKER_PERFORMANCE_ON(10)
+
+        // Initialize level data
+        pApp->Level_Set(dwNum);
+    string_path temp;
+    if (!FS.exist(temp, "$level$", "level.ltx"))
+        Debug.fatal(DEBUG_INFO, "Can't find level configuration file '%s'.", temp);
+    pLevel = xr_new(temp);
+
+    // Open
+    // g_pGamePersistent->LoadTitle ("st_opening_stream");
+    g_pGamePersistent->LoadTitle();
+    IReader* LL_Stream = FS.r_open("$level$", "level");
+    IReader& fs = *LL_Stream;
+
+    // Header
+    hdrLEVEL H;
+    fs.r_chunk_safe(fsL_HEADER, &H, sizeof(H));
+    R_ASSERT2(XRCL_PRODUCTION_VERSION == H.XRLC_version, "Incompatible level version.");
+
+    // CForms
+    // g_pGamePersistent->LoadTitle ("st_loading_cform");
+    g_pGamePersistent->LoadTitle();
+    ObjectSpace.Load(build_callback);
+    //Sound->set_geometry_occ ( &Static );
+    Sound->set_geometry_occ(ObjectSpace.GetStaticModel());
+    Sound->set_handler(_sound_event);
+
+    pApp->LoadSwitch();
+
+
+    // HUD + Environment
+    if (!g_hud)
+        g_hud = (CCustomHUD*)NEW_INSTANCE(CLSID_HUDMANAGER);
+
+    // Render-level Load
+    Render->level_Load(LL_Stream);
+    // tscreate.FrameEnd ();
+    // Msg ("* S-CREATE: %f ms, %d times",tscreate.result,tscreate.count);
+
+    // Objects
+    g_pGamePersistent->Environment().mods_load();
+    R_ASSERT(Load_GameSpecific_Before());
+    Objects.Load();
+    //. ANDY R_ASSERT (Load_GameSpecific_After ());
+
+    // Done
+    FS.r_close(LL_Stream);
+    bReady = true;
+    if (!g_dedicated_server) IR_Capture();
 #ifndef DEDICATED_SERVER
-	Device.seqRender.Add		(this);
+    Device.seqRender.Add (this);
 #endif
 
-	Device.seqFrame.Add			(this);
+    Device.seqFrame.Add(this);
 
-	SECUROM_MARKER_PERFORMANCE_OFF(10)
+    SECUROM_MARKER_PERFORMANCE_OFF(10)
 
-	return true;	
+        return true;
 }
 
 #ifndef _EDITOR
 #include "../xrCPU_Pipe/ttapi.h"
 #endif
 
-int		psNET_DedicatedSleep	= 5;
-void	IGame_Level::OnRender		( ) 
+int psNET_DedicatedSleep = 5;
+void IGame_Level::OnRender()
 {
 #ifndef DEDICATED_SERVER
-//	if (_abs(Device.fTimeDelta)Calculate			();
-		Render->Render				();
-	} else {
-		Sleep						(psNET_DedicatedSleep);
-	}
-
-	#ifdef _GPA_ENABLED	
-		TAL_RetireID( rtID );
-	#endif // _GPA_ENABLED
-
-	// Font
-//	pApp->pFontSystem->SetSizeI(0.023f);
-//	pApp->pFontSystem->OnRender	();
+    // if (_abs(Device.fTimeDelta)Calculate ();
+        Render->Render ();
+    }
+    else
+    {
+        Sleep (psNET_DedicatedSleep);
+    }
+
+#ifdef _GPA_ENABLED
+    TAL_RetireID( rtID );
+#endif // _GPA_ENABLED
+
+    // Font
+    // pApp->pFontSystem->SetSizeI(0.023f);
+    // pApp->pFontSystem->OnRender ();
 #endif
 }
 
-void	IGame_Level::OnFrame		( ) 
+void IGame_Level::OnFrame()
 {
-	// Log				("- level:on-frame: ",u32(Device.dwFrame));
-//	if (_abs(Device.fTimeDelta)OnFrame				();
-
-	// Ambience
-	if (Sounds_Random.size() && (Device.dwTimeGlobal > Sounds_Random_dwNextTime))
-	{
-		Sounds_Random_dwNextTime		= Device.dwTimeGlobal + ::Random.randI	(10000,20000);
-		Fvector	pos;
-		pos.random_dir().normalize().mul(::Random.randF(30,100)).add	(Device.vCameraPosition);
-		int		id						= ::Random.randI(Sounds_Random.size());
-		if (Sounds_Random_Enabled)		{
-			Sounds_Random[id].play_at_pos	(0,pos,0);
-			Sounds_Random[id].set_volume	(1.f);
-			Sounds_Random[id].set_range		(10,200);
-		}
-	}
+    // Log ("- level:on-frame: ",u32(Device.dwFrame));
+    // if (_abs(Device.fTimeDelta)OnFrame();
+
+    // Ambience
+    if (Sounds_Random.size() && (Device.dwTimeGlobal > Sounds_Random_dwNextTime))
+    {
+        Sounds_Random_dwNextTime = Device.dwTimeGlobal + ::Random.randI(10000, 20000);
+        Fvector pos;
+        pos.random_dir().normalize().mul(::Random.randF(30, 100)).add(Device.vCameraPosition);
+        int id = ::Random.randI(Sounds_Random.size());
+        if (Sounds_Random_Enabled)
+        {
+            Sounds_Random[id].play_at_pos(0, pos, 0);
+            Sounds_Random[id].set_volume(1.f);
+            Sounds_Random[id].set_range(10, 200);
+        }
+    }
 }
 // ==================================================================================================
 
-void CServerInfo::AddItem( LPCSTR name_, LPCSTR value_, u32 color_ )
+void CServerInfo::AddItem(LPCSTR name_, LPCSTR value_, u32 color_)
 {
-	shared_str s_name( name_ );
-	AddItem( s_name, value_, color_ );
+    shared_str s_name(name_);
+    AddItem(s_name, value_, color_);
 }
 
-void CServerInfo::AddItem( shared_str& name_, LPCSTR value_, u32 color_ )
+void CServerInfo::AddItem(shared_str& name_, LPCSTR value_, u32 color_)
 {
-	SItem_ServerInfo it;
-	//	shared_str s_name = CStringTable().translate( name_ );
-
-	//	xr_strcpy( it.name, s_name.c_str() );
-	xr_strcpy( it.name, name_.c_str() );
-	xr_strcat( it.name, " = " );
-	xr_strcat( it.name, value_ );
-	it.color = color_;
-
-	if ( data.size() < max_item )
-	{
-		data.push_back( it );
-	}
+    SItem_ServerInfo it;
+    // shared_str s_name = CStringTable().translate( name_ );
+
+    // xr_strcpy( it.name, s_name.c_str() );
+    xr_strcpy(it.name, name_.c_str());
+    xr_strcat(it.name, " = ");
+    xr_strcat(it.name, value_);
+    it.color = color_;
+
+    if (data.size() < max_item)
+    {
+        data.push_back(it);
+    }
 }
 
-void IGame_Level::SetEntity( CObject* O  )
+void IGame_Level::SetEntity(CObject* O)
 {
-	if (pCurrentEntity)
-		pCurrentEntity->On_LostEntity();
-	
-	if (O)
-		O->On_SetEntity();
+    if (pCurrentEntity)
+        pCurrentEntity->On_LostEntity();
 
-	pCurrentEntity=pCurrentViewEntity=O;
+    if (O)
+        O->On_SetEntity();
+
+    pCurrentEntity = pCurrentViewEntity = O;
 }
 
-void IGame_Level::SetViewEntity( CObject* O  )
+void IGame_Level::SetViewEntity(CObject* O)
 {
-	if (pCurrentViewEntity)
-		pCurrentViewEntity->On_LostEntity();
+    if (pCurrentViewEntity)
+        pCurrentViewEntity->On_LostEntity();
 
-	if (O)
-		O->On_SetEntity();
+    if (O)
+        O->On_SetEntity();
 
-	pCurrentViewEntity=O;
+    pCurrentViewEntity = O;
 }
 
-void	IGame_Level::SoundEvent_Register	( ref_sound_data_ptr S, float range )
+void IGame_Level::SoundEvent_Register(ref_sound_data_ptr S, float range)
 {
-	if (!g_bLoaded)									return;
-	if (!S)											return;
-	if (S->g_object && S->g_object->getDestroy())	{S->g_object=0; return;}
-	if (0==S->feedback)								return;
-
-	clamp					(range,0.1f,500.f);
-
-	const CSound_params* p	= S->feedback->get_params();
-	Fvector snd_position	= p->position;
-	if(S->feedback->is_2D()){
-		snd_position.add	(Sound->listener_position());
-	}
-
-	VERIFY					(p && _valid(range) );
-	range					= _min(range,p->max_ai_distance);
-	VERIFY					(_valid(snd_position));
-	VERIFY					(_valid(p->max_ai_distance));
-	VERIFY					(_valid(p->volume));
-
-	// Query objects
-	Fvector					bb_size	=	{range,range,range};
-	g_SpatialSpace->q_box	(snd_ER,0,STYPE_REACTTOSOUND,snd_position,bb_size);
-
-	// Iterate
-	xr_vector::iterator	it	= snd_ER.begin	();
-	xr_vector::iterator	end	= snd_ER.end	();
-	for (; it!=end; it++)	{
-		Feel::Sound* L		= (*it)->dcast_FeelSound	();
-		if (0==L)			continue;
-		CObject* CO = (*it)->dcast_CObject();	VERIFY(CO);
-		if (CO->getDestroy()) continue;
-
-		// Energy and signal
-		VERIFY				(_valid((*it)->spatial.sphere.P));
-		float dist			= snd_position.distance_to((*it)->spatial.sphere.P);
-		if (dist>p->max_ai_distance) continue;
-		VERIFY				(_valid(dist));
-		VERIFY2				(!fis_zero(p->max_ai_distance), S->handle->file_name());
-		float Power			= (1.f-dist/p->max_ai_distance)*p->volume;
-		VERIFY				(_valid(Power));
-		if (Power>EPS_S)	{
-			float occ		= Sound->get_occlusion_to((*it)->spatial.sphere.P,snd_position);
-			VERIFY			(_valid(occ))	;
-			Power			*= occ;
-			if (Power>EPS_S)	{
-				_esound_delegate	D	=	{ L, S, Power };
-				snd_Events.push_back	(D)	;
-			}
-		}
-	}
-	snd_ER.clear_not_free	();
+    if (!g_bLoaded) return;
+    if (!S) return;
+    if (S->g_object && S->g_object->getDestroy()) { S->g_object = 0; return; }
+    if (0 == S->feedback) return;
+
+    clamp(range, 0.1f, 500.f);
+
+    const CSound_params* p = S->feedback->get_params();
+    Fvector snd_position = p->position;
+    if (S->feedback->is_2D())
+    {
+        snd_position.add(Sound->listener_position());
+    }
+
+    VERIFY(p && _valid(range));
+    range = _min(range, p->max_ai_distance);
+    VERIFY(_valid(snd_position));
+    VERIFY(_valid(p->max_ai_distance));
+    VERIFY(_valid(p->volume));
+
+    // Query objects
+    Fvector bb_size = {range, range, range};
+    g_SpatialSpace->q_box(snd_ER, 0, STYPE_REACTTOSOUND, snd_position, bb_size);
+
+    // Iterate
+    xr_vector::iterator it = snd_ER.begin();
+    xr_vector::iterator end = snd_ER.end();
+    for (; it != end; it++)
+    {
+        Feel::Sound* L = (*it)->dcast_FeelSound();
+        if (0 == L) continue;
+        CObject* CO = (*it)->dcast_CObject();
+        VERIFY(CO);
+        if (CO->getDestroy()) continue;
+
+        // Energy and signal
+        VERIFY(_valid((*it)->spatial.sphere.P));
+        float dist = snd_position.distance_to((*it)->spatial.sphere.P);
+        if (dist > p->max_ai_distance) continue;
+        VERIFY(_valid(dist));
+        VERIFY2(!fis_zero(p->max_ai_distance), S->handle->file_name());
+        float Power = (1.f - dist / p->max_ai_distance)*p->volume;
+        VERIFY(_valid(Power));
+        if (Power > EPS_S)
+        {
+            float occ = Sound->get_occlusion_to((*it)->spatial.sphere.P, snd_position);
+            VERIFY(_valid(occ));
+            Power *= occ;
+            if (Power > EPS_S)
+            {
+                _esound_delegate D = {L, S, Power};
+                snd_Events.push_back(D);
+            }
+        }
+    }
+    snd_ER.clear_not_free();
 }
 
-void	IGame_Level::SoundEvent_Dispatch	( )
+void IGame_Level::SoundEvent_Dispatch()
 {
-	while	(!snd_Events.empty())	{
-		_esound_delegate&	D	= snd_Events.back	();
-		VERIFY				(D.dest && D.source);
-		if (D.source->feedback)	{
-			D.dest->feel_sound_new	(
-				D.source->g_object,
-				D.source->g_type,
-				D.source->g_userdata,
-
-				D.source->feedback->is_2D() ? Device.vCameraPosition : 
-					D.source->feedback->get_params()->position,
-				D.power
-				);
-		}
-		snd_Events.pop_back		();
-	}
+    while (!snd_Events.empty())
+    {
+        _esound_delegate& D = snd_Events.back();
+        VERIFY(D.dest && D.source);
+        if (D.source->feedback)
+        {
+            D.dest->feel_sound_new(
+                D.source->g_object,
+                D.source->g_type,
+                D.source->g_userdata,
+
+                D.source->feedback->is_2D() ? Device.vCameraPosition :
+                D.source->feedback->get_params()->position,
+                D.power
+                );
+        }
+        snd_Events.pop_back();
+    }
 }
 
 // Lain: added
-void   IGame_Level::SoundEvent_OnDestDestroy (Feel::Sound* obj)
+void IGame_Level::SoundEvent_OnDestDestroy(Feel::Sound* obj)
 {
-	struct rem_pred
-	{
-		rem_pred(Feel::Sound* obj) : m_obj(obj) {}
+    struct rem_pred
+    {
+        rem_pred(Feel::Sound* obj) : m_obj(obj) {}
 
-		bool operator () (const _esound_delegate& d)
-		{
-			return d.dest == m_obj;
-		}
+        bool operator () (const _esound_delegate& d)
+        {
+            return d.dest == m_obj;
+        }
 
-	private:
-		Feel::Sound* m_obj;
-	};
+    private:
+        Feel::Sound* m_obj;
+    };
 
-	snd_Events.erase( std::remove_if(snd_Events.begin(), snd_Events.end(), rem_pred(obj)),
-	                  snd_Events.end() );
+    snd_Events.erase(std::remove_if(snd_Events.begin(), snd_Events.end(), rem_pred(obj)),
+        snd_Events.end());
 }
 
 
diff --git a/src/xrEngine/IGame_Level.h b/src/xrEngine/IGame_Level.h
index 42491abf608..8835922fd3d 100644
--- a/src/xrEngine/IGame_Level.h
+++ b/src/xrEngine/IGame_Level.h
@@ -17,124 +17,125 @@ namespace Feel { class ENGINE_API Sound; }
 class ENGINE_API CServerInfo
 {
 private:
-	struct SItem_ServerInfo
-	{
-		string128	name;
-		u32			color;
-	};
-	enum { max_item = 15 };
-	svector	data;
+    struct SItem_ServerInfo
+    {
+        string128 name;
+        u32 color;
+    };
+    enum { max_item = 15 };
+    svector data;
 
 public:
-	u32		Size()			{ return data.size(); }
-	void	ResetData()		{ data.clear(); }
+    u32 Size() { return data.size(); }
+    void ResetData() { data.clear(); }
 
-	void	AddItem( LPCSTR name_,		LPCSTR value_, u32 color_ = RGB(255,255,255) );
-	void	AddItem( shared_str& name_,	LPCSTR value_, u32 color_ = RGB(255,255,255) );
+    void AddItem(LPCSTR name_, LPCSTR value_, u32 color_ = RGB(255, 255, 255));
+    void AddItem(shared_str& name_, LPCSTR value_, u32 color_ = RGB(255, 255, 255));
 
-	IC SItem_ServerInfo&	operator[] ( u32 id ) { VERIFY( id < max_item ); return data[id]; }
+    IC SItem_ServerInfo& operator[] (u32 id) { VERIFY(id < max_item); return data[id]; }
 
-	CServerInfo() {};
-	~CServerInfo() {};
+    CServerInfo() {};
+    ~CServerInfo() {};
 };
 
 //-----------------------------------------------------------------------------------------------------------
-class ENGINE_API	IGame_Level	:
-	public DLL_Pure,
-	public IInputReceiver,
-	public pureRender,
-	public pureFrame,
-	public IEventReceiver
+class ENGINE_API IGame_Level :
+    public DLL_Pure,
+    public IInputReceiver,
+    public pureRender,
+    public pureFrame,
+    public IEventReceiver
 {
 protected:
-	// Network interface
-	CObject*					pCurrentEntity;
-	CObject*					pCurrentViewEntity;
-   
-	// Static sounds
-	xr_vector		Sounds_Random;
-	u32							Sounds_Random_dwNextTime;
-	BOOL						Sounds_Random_Enabled;
-	CCameraManager*				m_pCameras;
-
-	// temporary
-	xr_vector		snd_ER;
+    // Network interface
+    CObject* pCurrentEntity;
+    CObject* pCurrentViewEntity;
+
+    // Static sounds
+    xr_vector Sounds_Random;
+    u32 Sounds_Random_dwNextTime;
+    BOOL Sounds_Random_Enabled;
+    CCameraManager* m_pCameras;
+
+    // temporary
+    xr_vector snd_ER;
 public:
-	CObjectList					Objects; 
-	CObjectSpace				ObjectSpace;
-	CCameraManager&				Cameras			()				{return *m_pCameras;};
-
-	BOOL						bReady;
-
-	CInifile*					pLevel;
-public:	// deferred sound events
-	struct	_esound_delegate	{
-		Feel::Sound*			dest	;
-		ref_sound_data_ptr		source	;
-		float					power	;
-	};
-	xr_vector<_esound_delegate>	snd_Events;
+    CObjectList Objects;
+    CObjectSpace ObjectSpace;
+    CCameraManager& Cameras() { return *m_pCameras; };
+
+    BOOL bReady;
+
+    CInifile* pLevel;
+public: // deferred sound events
+    struct _esound_delegate
+    {
+        Feel::Sound* dest;
+        ref_sound_data_ptr source;
+        float power;
+    };
+    xr_vector<_esound_delegate> snd_Events;
 public:
-	// Main, global functions
-	IGame_Level					();
-	virtual ~IGame_Level		();
-
-	virtual shared_str			name					() const = 0;
-	virtual void				GetLevelInfo			( CServerInfo* si ) = 0;
-
-	virtual bool				net_Start				( const char* op_server, const char* op_client)	= 0;
-	virtual void				net_Load				( const char* name )							= 0;
-	virtual void				net_Save				( const char* name )							= 0;
-	virtual void				net_Stop				( );
-	virtual void				net_Update				( )										= 0;
-
-	virtual bool				Load					( u32 dwNum );
-	virtual bool				Load_GameSpecific_Before( )										{ return TRUE; };		// before object loading
-	virtual bool				Load_GameSpecific_After	( )										{ return TRUE; };		// after object loading
-	virtual void				Load_GameSpecific_CFORM	( CDB::TRI* T, u32 count )				= 0;
-
-	virtual void	_BCL		OnFrame					( void );
-	virtual void				OnRender				( void );
-
-	virtual	shared_str			OpenDemoFile			(const char* demo_file_name) = 0;
-	virtual void				net_StartPlayDemo		() = 0;
-
-	// Main interface
-	CObject*					CurrentEntity			( void ) const							{ return pCurrentEntity;				}
-	CObject*					CurrentViewEntity		( void ) const							{ return pCurrentViewEntity;			}
-	void						SetEntity				( CObject* O  );//							{ pCurrentEntity=pCurrentViewEntity=O;	}
-	void						SetViewEntity			( CObject* O  );//							{ pCurrentViewEntity=O;					}
-	
-	void						SoundEvent_Register		( ref_sound_data_ptr S, float range );
-	void						SoundEvent_Dispatch		( );
-	void                        SoundEvent_OnDestDestroy (Feel::Sound*);
-
-	// Loader interface
-	//ref_shader					LL_CreateShader			(int S, int T, int M, int C);
-	void						LL_CheckTextures		();
-	virtual void				SetEnvironmentGameTimeFactor(u64 const& GameTime, float const& fTimeFactor) = 0;
+    // Main, global functions
+    IGame_Level();
+    virtual ~IGame_Level();
+
+    virtual shared_str name() const = 0;
+    virtual void GetLevelInfo(CServerInfo* si) = 0;
+
+    virtual bool net_Start(const char* op_server, const char* op_client) = 0;
+    virtual void net_Load(const char* name) = 0;
+    virtual void net_Save(const char* name) = 0;
+    virtual void net_Stop();
+    virtual void net_Update() = 0;
+
+    virtual bool Load(u32 dwNum);
+    virtual bool Load_GameSpecific_Before() { return TRUE; }; // before object loading
+    virtual bool Load_GameSpecific_After() { return TRUE; }; // after object loading
+    virtual void Load_GameSpecific_CFORM(CDB::TRI* T, u32 count) = 0;
+
+    virtual void _BCL OnFrame(void);
+    virtual void OnRender(void);
+
+    virtual shared_str OpenDemoFile(const char* demo_file_name) = 0;
+    virtual void net_StartPlayDemo() = 0;
+
+    // Main interface
+    CObject* CurrentEntity(void) const { return pCurrentEntity; }
+    CObject* CurrentViewEntity(void) const { return pCurrentViewEntity; }
+    void SetEntity(CObject* O);// { pCurrentEntity=pCurrentViewEntity=O; }
+    void SetViewEntity(CObject* O);// { pCurrentViewEntity=O; }
+
+    void SoundEvent_Register(ref_sound_data_ptr S, float range);
+    void SoundEvent_Dispatch();
+    void SoundEvent_OnDestDestroy(Feel::Sound*);
+
+    // Loader interface
+    //ref_shader LL_CreateShader (int S, int T, int M, int C);
+    void LL_CheckTextures();
+    virtual void SetEnvironmentGameTimeFactor(u64 const& GameTime, float const& fTimeFactor) = 0;
 };
 
 //-----------------------------------------------------------------------------------------------------------
-extern ENGINE_API	IGame_Level*	g_pGameLevel;
+extern ENGINE_API IGame_Level* g_pGameLevel;
 
 template 
-	void relcase_register	(_class_type *self, void (xr_stdcall _class_type::* function_to_bind)(CObject*))
-	{
-		g_pGameLevel->Objects.relcase_register	(
-			CObjectList::RELCASE_CALLBACK (
-				self,
-				function_to_bind)
-		);
-	}
+void relcase_register(_class_type* self, void (xr_stdcall _class_type::* function_to_bind)(CObject*))
+{
+    g_pGameLevel->Objects.relcase_register(
+        CObjectList::RELCASE_CALLBACK(
+        self,
+        function_to_bind)
+        );
+}
 
 template 
-	void relcase_unregister	(_class_type *self, void (xr_stdcall _class_type::* function_to_bind)(CObject*))
-	{
-		g_pGameLevel->Objects.relcase_unregister	(
-			CObjectList::RELCASE_CALLBACK (
-				self,
-				function_to_bind)
-		);
-	}
-#endif    
+void relcase_unregister(_class_type* self, void (xr_stdcall _class_type::* function_to_bind)(CObject*))
+{
+    g_pGameLevel->Objects.relcase_unregister(
+        CObjectList::RELCASE_CALLBACK(
+        self,
+        function_to_bind)
+        );
+}
+#endif
diff --git a/src/xrEngine/IGame_Level_check_textures.cpp b/src/xrEngine/IGame_Level_check_textures.cpp
index c238614db6f..f20fc93a69d 100644
--- a/src/xrEngine/IGame_Level_check_textures.cpp
+++ b/src/xrEngine/IGame_Level_check_textures.cpp
@@ -4,25 +4,25 @@
 
 void IGame_Level::LL_CheckTextures()
 {
-	u32	m_base,c_base,m_lmaps,c_lmaps;
-	//Device.Resources->_GetMemoryUsage		(m_base,c_base,m_lmaps,c_lmaps);
-	Device.m_pRender->ResourcesGetMemoryUsage(m_base,c_base,m_lmaps,c_lmaps);
+    u32 m_base, c_base, m_lmaps, c_lmaps;
+    //Device.Resources->_GetMemoryUsage (m_base,c_base,m_lmaps,c_lmaps);
+    Device.m_pRender->ResourcesGetMemoryUsage(m_base, c_base, m_lmaps, c_lmaps);
 
-	Msg	("* t-report - base: %d, %d K",	c_base,		m_base/1024);
-	Msg	("* t-report - lmap: %d, %d K",	c_lmaps,	m_lmaps/1024);
-	BOOL	bError	= FALSE;
-	if (m_base>64*1024*1024 || c_base>400)
-	{
-		// LPCSTR msg	= "Too many base-textures (limit: 400 textures or 64M).\n        Reduce number of textures (better) or their resolution (worse).";
-		// Msg		("***FATAL***: %s",msg);
-		bError		= TRUE;
-	}
-	if (m_lmaps>32*1024*1024 || c_lmaps>8)
-	{
+    Msg("* t-report - base: %d, %d K", c_base, m_base / 1024);
+    Msg("* t-report - lmap: %d, %d K", c_lmaps, m_lmaps / 1024);
+    BOOL bError = FALSE;
+    if (m_base > 64 * 1024 * 1024 || c_base > 400)
+    {
+        // LPCSTR msg = "Too many base-textures (limit: 400 textures or 64M).\n        Reduce number of textures (better) or their resolution (worse).";
+        // Msg ("***FATAL***: %s",msg);
+        bError = TRUE;
+    }
+    if (m_lmaps > 32 * 1024 * 1024 || c_lmaps > 8)
+    {
 #ifdef DEBUG
-		LPCSTR msg	= "Too many lmap-textures (limit: 8 textures or 32M).\n        Reduce pixel density (worse) or use more vertex lighting (better).";
-		Msg			("***FATAL***: %s",msg);
+        LPCSTR msg = "Too many lmap-textures (limit: 8 textures or 32M).\n        Reduce pixel density (worse) or use more vertex lighting (better).";
+        Msg("***FATAL***: %s", msg);
 #endif // #ifdef DEBUG
-		bError		= TRUE;
-	}
+        bError = TRUE;
+    }
 }
diff --git a/src/xrEngine/IGame_ObjectPool.cpp b/src/xrEngine/IGame_ObjectPool.cpp
index de0f1e12eb1..0b0af84f70d 100644
--- a/src/xrEngine/IGame_ObjectPool.cpp
+++ b/src/xrEngine/IGame_ObjectPool.cpp
@@ -10,130 +10,131 @@ IGame_ObjectPool::IGame_ObjectPool(void)
 
 IGame_ObjectPool::~IGame_ObjectPool(void)
 {
-	R_ASSERT			(m_PrefetchObjects.empty());
+    R_ASSERT(m_PrefetchObjects.empty());
 }
 
-void IGame_ObjectPool::prefetch	()
+void IGame_ObjectPool::prefetch()
 {
-	R_ASSERT			(m_PrefetchObjects.empty());
-
-	int	p_count			= 0;
-	::Render->model_Logging	(FALSE);
-
-	string256				section;
-	// prefetch objects
-	strconcat				(sizeof(section),section,"prefetch_objects_",g_pGamePersistent->m_game_params.m_game_type);
-	CInifile::Sect const & sect	= pSettings->r_section(section);
-	for (CInifile::SectCIt I=sect.Data.begin(); I!=sect.Data.end(); I++)	{
-		const CInifile::Item& item= *I;
-		CLASS_ID CLS		= pSettings->r_clsid(item.first.c_str(),"class");
-		p_count				++;
-		CObject* pObject	= (CObject*) NEW_INSTANCE(CLS);
-		pObject->Load		(item.first.c_str());
-		VERIFY2				(pObject->cNameSect().c_str(),item.first.c_str());
-		m_PrefetchObjects.push_back	(pObject);
-	}
-
-	// out statistic
-	::Render->model_Logging	(TRUE);
+    R_ASSERT(m_PrefetchObjects.empty());
+
+    int p_count = 0;
+    ::Render->model_Logging(FALSE);
+
+    string256 section;
+    // prefetch objects
+    strconcat(sizeof(section), section, "prefetch_objects_", g_pGamePersistent->m_game_params.m_game_type);
+    CInifile::Sect const& sect = pSettings->r_section(section);
+    for (CInifile::SectCIt I = sect.Data.begin(); I != sect.Data.end(); I++)
+    {
+        const CInifile::Item& item = *I;
+        CLASS_ID CLS = pSettings->r_clsid(item.first.c_str(), "class");
+        p_count++;
+        CObject* pObject = (CObject*)NEW_INSTANCE(CLS);
+        pObject->Load(item.first.c_str());
+        VERIFY2(pObject->cNameSect().c_str(), item.first.c_str());
+        m_PrefetchObjects.push_back(pObject);
+    }
+
+    // out statistic
+    ::Render->model_Logging(TRUE);
 }
 
 void IGame_ObjectPool::clear()
 {
-	// Clear POOL
-	ObjectVecIt it			= m_PrefetchObjects.begin();
-	ObjectVecIt itE			= m_PrefetchObjects.end();
-	for (; it!=itE; it++)	
-		xr_delete			(*it);
-	m_PrefetchObjects.clear	(); 
+    // Clear POOL
+    ObjectVecIt it = m_PrefetchObjects.begin();
+    ObjectVecIt itE = m_PrefetchObjects.end();
+    for (; it != itE; it++)
+        xr_delete(*it);
+    m_PrefetchObjects.clear();
 }
 
-CObject*	IGame_ObjectPool::create			( LPCSTR	name	)
+CObject* IGame_ObjectPool::create(LPCSTR name)
 {
-	CLASS_ID CLS		=	pSettings->r_clsid		(name,"class");
-	CObject* O			=	(CObject*) NEW_INSTANCE	(CLS);
-	O->cNameSect_set	(name);
-	O->Load				(name);
-	return				O;
+    CLASS_ID CLS = pSettings->r_clsid(name, "class");
+    CObject* O = (CObject*)NEW_INSTANCE(CLS);
+    O->cNameSect_set(name);
+    O->Load(name);
+    return O;
 }
 
-void		IGame_ObjectPool::destroy			( CObject*	O		)
+void IGame_ObjectPool::destroy(CObject* O)
 {
-	xr_delete				(O);
+    xr_delete(O);
 }
 
 /*
-void IGame_ObjectPool::prefetch	()
+void IGame_ObjectPool::prefetch ()
 {
-	R_ASSERT			(map_POOL.empty());
-
-	u32	mem_0			= Memory.mem_usage();
-	float	p_time		= 1000.f*Device.GetTimerGlobal()->GetElapsed_sec();
-	int	p_count			= 0;
-	::Render->model_Logging	(FALSE);
-
-	string256 section;
-	// prefetch objects
-	strconcat				(section,"prefetch_objects_",g_pGamePersistent->m_game_params.m_game_type);
-	CInifile::Sect& sect	= pSettings->r_section(section);
-	for (CInifile::SectIt I=sect.begin(); I!=sect.end(); I++)	{
-		CInifile::Item& item= *I;
-		CLASS_ID CLS		= pSettings->r_clsid(item.first.c_str(),"class");
-		int count			= atoi(item.second.c_str());
-		count				+= (count==0)?1:0;
-		R_ASSERT2			((count>0) && (count<=128), "Too many objects for prefetching");
-		p_count				+=	count;
-		for (int c=0; cLoad	(item.first.c_str());
-			VERIFY2			(pObject->cNameSect().c_str(),item.first.c_str());
-			map_POOL.insert	(mk_pair(pObject->cNameSect(),pObject));
-		}
-	}
-
-	// out statistic
-	::Render->model_Logging	(TRUE);
-	p_time = 1000.f*Device.GetTimerGlobal()->GetElapsed_sec() - p_time;
-	u32		p_mem		= Memory.mem_usage() - mem_0;
-	if (p_count){
-		float 	a_time		= float(p_time)/float(p_count);
-		Msg					("* [Object-prefetch] objects: %d",		p_count);
-		Msg					("* [Object-prefetch] time:    %d ms",	iFloor(p_time));
-		Msg					("* [Object-prefetch] memory:  %dKb",	p_mem/1024);
-		Msg					("* [Object-prefetch] average: %2.2f ms, %d bytes", a_time, p_mem/p_count);
-	}
+R_ASSERT (map_POOL.empty());
+
+u32 mem_0 = Memory.mem_usage();
+float p_time = 1000.f*Device.GetTimerGlobal()->GetElapsed_sec();
+int p_count = 0;
+::Render->model_Logging (FALSE);
+
+string256 section;
+// prefetch objects
+strconcat (section,"prefetch_objects_",g_pGamePersistent->m_game_params.m_game_type);
+CInifile::Sect& sect = pSettings->r_section(section);
+for (CInifile::SectIt I=sect.begin(); I!=sect.end(); I++) {
+CInifile::Item& item= *I;
+CLASS_ID CLS = pSettings->r_clsid(item.first.c_str(),"class");
+int count = atoi(item.second.c_str());
+count += (count==0)?1:0;
+R_ASSERT2 ((count>0) && (count<=128), "Too many objects for prefetching");
+p_count += count;
+for (int c=0; cLoad (item.first.c_str());
+VERIFY2 (pObject->cNameSect().c_str(),item.first.c_str());
+map_POOL.insert (mk_pair(pObject->cNameSect(),pObject));
+}
+}
+
+// out statistic
+::Render->model_Logging (TRUE);
+p_time = 1000.f*Device.GetTimerGlobal()->GetElapsed_sec() - p_time;
+u32 p_mem = Memory.mem_usage() - mem_0;
+if (p_count){
+float a_time = float(p_time)/float(p_count);
+Msg ("* [Object-prefetch] objects: %d", p_count);
+Msg ("* [Object-prefetch] time: %d ms", iFloor(p_time));
+Msg ("* [Object-prefetch] memory: %dKb", p_mem/1024);
+Msg ("* [Object-prefetch] average: %2.2f ms, %d bytes", a_time, p_mem/p_count);
+}
 }
 
-void IGame_ObjectPool::clear	( )
+void IGame_ObjectPool::clear ( )
 {
-	// Clear POOL
-	for (POOL_IT it=map_POOL.begin(); it!=map_POOL.end(); it++)	
-		xr_delete	(it->second);
-	map_POOL.clear(); 
+// Clear POOL
+for (POOL_IT it=map_POOL.begin(); it!=map_POOL.end(); it++)
+xr_delete (it->second);
+map_POOL.clear();
 }
 
-CObject*	IGame_ObjectPool::create			( LPCSTR	name	)
+CObject* IGame_ObjectPool::create ( LPCSTR name )
+{
+string256 l_name;
+POOL_IT it = map_POOL.find (shared_str(strlwr(xr_strcpy(l_name,name))));
+if (it!=map_POOL.end())
 {
-	string256			l_name;
-	POOL_IT	it			=	map_POOL.find	(shared_str(strlwr(xr_strcpy(l_name,name))));
-	if (it!=map_POOL.end())
-	{
-		// Instance found
-		CObject* O			=	it->second;
-		map_POOL.erase		(it);
-		return				O;
-	} else {
-		// Create and load _new instance
-		// Msg				("! Uncached loading '%s'...",name);
-		CLASS_ID CLS		=	pSettings->r_clsid		(name,"class");
-		CObject* O			=	(CObject*) NEW_INSTANCE	(CLS);
-		O->Load				(name);
-		return				O;
-	}
+// Instance found
+CObject* O = it->second;
+map_POOL.erase (it);
+return O;
+} else {
+// Create and load _new instance
+// Msg ("! Uncached loading '%s'...",name);
+CLASS_ID CLS = pSettings->r_clsid (name,"class");
+CObject* O = (CObject*) NEW_INSTANCE (CLS);
+O->Load (name);
+return O;
+}
 }
 
-void		IGame_ObjectPool::destroy			( CObject*	O		)
+void IGame_ObjectPool::destroy ( CObject* O )
 {
-	map_POOL.insert			(mk_pair(O->cNameSect(),O));
+map_POOL.insert (mk_pair(O->cNameSect(),O));
 }
 */
\ No newline at end of file
diff --git a/src/xrEngine/IGame_ObjectPool.h b/src/xrEngine/IGame_ObjectPool.h
index 53db880be13..da912a4a808 100644
--- a/src/xrEngine/IGame_ObjectPool.h
+++ b/src/xrEngine/IGame_ObjectPool.h
@@ -1,34 +1,34 @@
 #pragma once
 
 // refs
-class ENGINE_API				CObject;
+class ENGINE_API CObject;
 
 //-----------------------------------------------------------------------------------------------------------
-class ENGINE_API 				IGame_ObjectPool
+class ENGINE_API IGame_ObjectPool
 {
-/*
-private:
-	struct str_pred : public std::binary_function 
-	{	
-		IC bool operator()(const shared_str& x, const shared_str& y) const
-		{	return xr_strcmp(x,y)<0;	}
-	};
-	typedef xr_multimap	POOL;
-	typedef POOL::iterator							POOL_IT;
-private:
-	POOL						map_POOL;
-*/
-	typedef xr_vector	ObjectVec;
-	typedef ObjectVec::iterator	ObjectVecIt;
-	ObjectVec					m_PrefetchObjects;
+    /*
+    private:
+    struct str_pred : public std::binary_function
+    {
+    IC bool operator()(const shared_str& x, const shared_str& y) const
+    { return xr_strcmp(x,y)<0; }
+    };
+    typedef xr_multimap POOL;
+    typedef POOL::iterator POOL_IT;
+    private:
+    POOL map_POOL;
+    */
+    typedef xr_vector ObjectVec;
+    typedef ObjectVec::iterator ObjectVecIt;
+    ObjectVec m_PrefetchObjects;
 public:
-	void						prefetch			( );
-	void						clear				( );
+    void prefetch();
+    void clear();
 
-	CObject*					create				( LPCSTR	name	);
-	void						destroy				( CObject*	O		);
+    CObject* create(LPCSTR name);
+    void destroy(CObject* O);
 
-	IGame_ObjectPool			();
-	virtual ~IGame_ObjectPool	();
+    IGame_ObjectPool();
+    virtual ~IGame_ObjectPool();
 };
 //-----------------------------------------------------------------------------------------------------------
diff --git a/src/xrEngine/IGame_Persistent.cpp b/src/xrEngine/IGame_Persistent.cpp
index de06a5a3d59..682bc7b0ab6 100644
--- a/src/xrEngine/IGame_Persistent.cpp
+++ b/src/xrEngine/IGame_Persistent.cpp
@@ -5,250 +5,254 @@
 
 #ifndef _EDITOR
 #include "environment.h"
-#	include "x_ray.h"
-#	include "IGame_Level.h"
-#	include "XR_IOConsole.h"
-#	include "Render.h"
-#	include "ps_instance.h"
-#	include "CustomHUD.h"
+# include "x_ray.h"
+# include "IGame_Level.h"
+# include "XR_IOConsole.h"
+# include "Render.h"
+# include "ps_instance.h"
+# include "CustomHUD.h"
 #endif
 
 #ifdef _EDITOR
-	bool g_dedicated_server	= false;
+bool g_dedicated_server = false;
 #endif
 
 #ifdef INGAME_EDITOR
-#	include "editor_environment_manager.hpp"
+# include "editor_environment_manager.hpp"
 #endif // INGAME_EDITOR
 
-ENGINE_API	IGame_Persistent*		g_pGamePersistent	= NULL;
+ENGINE_API IGame_Persistent* g_pGamePersistent = NULL;
 
-IGame_Persistent::IGame_Persistent	()
+IGame_Persistent::IGame_Persistent()
 {
-	RDEVICE.seqAppStart.Add			(this);
-	RDEVICE.seqAppEnd.Add			(this);
-	RDEVICE.seqFrame.Add			(this,REG_PRIORITY_HIGH+1);
-	RDEVICE.seqAppActivate.Add		(this);
-	RDEVICE.seqAppDeactivate.Add	(this);
+    RDEVICE.seqAppStart.Add(this);
+    RDEVICE.seqAppEnd.Add(this);
+    RDEVICE.seqFrame.Add(this, REG_PRIORITY_HIGH + 1);
+    RDEVICE.seqAppActivate.Add(this);
+    RDEVICE.seqAppDeactivate.Add(this);
 
-	m_pMainMenu						= NULL;
+    m_pMainMenu = NULL;
 
 #ifndef INGAME_EDITOR
-	#ifndef _EDITOR
-	pEnvironment					= xr_new();
-	#endif
+#ifndef _EDITOR
+    pEnvironment = xr_new();
+#endif
 #else // #ifdef INGAME_EDITOR
-	if (RDEVICE.editor())
-		pEnvironment				= xr_new();
-	else
-		pEnvironment				= xr_new();
+    if (RDEVICE.editor())
+        pEnvironment = xr_new();
+    else
+        pEnvironment = xr_new();
 #endif // #ifdef INGAME_EDITOR
 }
 
-IGame_Persistent::~IGame_Persistent	()
+IGame_Persistent::~IGame_Persistent()
 {
-	RDEVICE.seqFrame.Remove			(this);
-	RDEVICE.seqAppStart.Remove		(this);
-	RDEVICE.seqAppEnd.Remove			(this);
-	RDEVICE.seqAppActivate.Remove	(this);
-	RDEVICE.seqAppDeactivate.Remove	(this);
+    RDEVICE.seqFrame.Remove(this);
+    RDEVICE.seqAppStart.Remove(this);
+    RDEVICE.seqAppEnd.Remove(this);
+    RDEVICE.seqAppActivate.Remove(this);
+    RDEVICE.seqAppDeactivate.Remove(this);
 #ifndef _EDITOR
-	xr_delete						(pEnvironment);
+    xr_delete(pEnvironment);
 #endif
 }
 
-void IGame_Persistent::OnAppActivate		()
+void IGame_Persistent::OnAppActivate()
 {
 }
 
-void IGame_Persistent::OnAppDeactivate		()
+void IGame_Persistent::OnAppDeactivate()
 {
 }
 
-void IGame_Persistent::OnAppStart	()
+void IGame_Persistent::OnAppStart()
 {
 #ifndef _EDITOR
-	Environment().load				();
-#endif    
+    Environment().load();
+#endif
 }
 
-void IGame_Persistent::OnAppEnd		()
+void IGame_Persistent::OnAppEnd()
 {
 #ifndef _EDITOR
-	Environment().unload			 ();
-#endif    
-	OnGameEnd						();
+    Environment().unload();
+#endif
+    OnGameEnd();
 
 #ifndef _EDITOR
-	DEL_INSTANCE					(g_hud);
-#endif    
+    DEL_INSTANCE(g_hud);
+#endif
 }
 
 
-void IGame_Persistent::PreStart		(LPCSTR op)
+void IGame_Persistent::PreStart(LPCSTR op)
 {
-	string256						prev_type;
-	params							new_game_params;
-	xr_strcpy							(prev_type,m_game_params.m_game_type);
-	new_game_params.parse_cmd_line	(op);
-
-	// change game type
-	if (0!=xr_strcmp(prev_type,new_game_params.m_game_type)){
-		OnGameEnd					();
-	}
+    string256 prev_type;
+    params new_game_params;
+    xr_strcpy(prev_type, m_game_params.m_game_type);
+    new_game_params.parse_cmd_line(op);
+
+    // change game type
+    if (0 != xr_strcmp(prev_type, new_game_params.m_game_type))
+    {
+        OnGameEnd();
+    }
 }
-void IGame_Persistent::Start		(LPCSTR op)
+void IGame_Persistent::Start(LPCSTR op)
 {
-	string256						prev_type;
-	xr_strcpy							(prev_type,m_game_params.m_game_type);
-	m_game_params.parse_cmd_line	(op);
-	// change game type
-	if ((0!=xr_strcmp(prev_type,m_game_params.m_game_type))) 
-	{
-		if (*m_game_params.m_game_type)
-			OnGameStart					();
+    string256 prev_type;
+    xr_strcpy(prev_type, m_game_params.m_game_type);
+    m_game_params.parse_cmd_line(op);
+    // change game type
+    if ((0 != xr_strcmp(prev_type, m_game_params.m_game_type)))
+    {
+        if (*m_game_params.m_game_type)
+            OnGameStart();
 #ifndef _EDITOR
-		if(g_hud)
-			DEL_INSTANCE			(g_hud);
-#endif            
-	}
-	else UpdateGameType();
+        if (g_hud)
+            DEL_INSTANCE(g_hud);
+#endif
+    }
+    else UpdateGameType();
 
-	VERIFY							(ps_destroy.empty());
+    VERIFY(ps_destroy.empty());
 }
 
-void IGame_Persistent::Disconnect	()
+void IGame_Persistent::Disconnect()
 {
 #ifndef _EDITOR
-	// clear "need to play" particles
-	destroy_particles					(true);
+    // clear "need to play" particles
+    destroy_particles(true);
 
-	if(g_hud)
-			DEL_INSTANCE			(g_hud);
-//.		g_hud->OnDisconnected			();
+    if (g_hud)
+        DEL_INSTANCE(g_hud);
+    //. g_hud->OnDisconnected ();
 #endif
 }
 
 void IGame_Persistent::OnGameStart()
 {
 #ifndef _EDITOR
-//	LoadTitle("st_prefetching_objects");
-	LoadTitle();
-	if(!strstr(Core.Params,"-noprefetch"))
-		Prefetch();
+    // LoadTitle("st_prefetching_objects");
+    LoadTitle();
+    if (!strstr(Core.Params, "-noprefetch"))
+        Prefetch();
 #endif
 }
 
 #ifndef _EDITOR
 void IGame_Persistent::Prefetch()
 {
-	// prefetch game objects & models
-	float	p_time		=			1000.f*Device.GetTimerGlobal()->GetElapsed_sec();
-	u32	mem_0			=			Memory.mem_usage()	;
-
-	Log				("Loading objects...");
-	ObjectPool.prefetch					();
-	Log				("Loading models...");
-	Render->models_Prefetch				();
-	//Device.Resources->DeferredUpload	();
-	Device.m_pRender->ResourcesDeferredUpload();
-
-	p_time				=			1000.f*Device.GetTimerGlobal()->GetElapsed_sec() - p_time;
-	u32		p_mem		=			Memory.mem_usage() - mem_0	;
-
-	Msg					("* [prefetch] time:    %d ms",	iFloor(p_time));
-	Msg					("* [prefetch] memory:  %dKb",	p_mem/1024);
+    // prefetch game objects & models
+    float p_time = 1000.f*Device.GetTimerGlobal()->GetElapsed_sec();
+    u32 mem_0 = Memory.mem_usage();
+
+    Log("Loading objects...");
+    ObjectPool.prefetch();
+    Log("Loading models...");
+    Render->models_Prefetch();
+    //Device.Resources->DeferredUpload ();
+    Device.m_pRender->ResourcesDeferredUpload();
+
+    p_time = 1000.f*Device.GetTimerGlobal()->GetElapsed_sec() - p_time;
+    u32 p_mem = Memory.mem_usage() - mem_0;
+
+    Msg("* [prefetch] time:   %d ms", iFloor(p_time));
+    Msg("* [prefetch] memory: %dKb", p_mem / 1024);
 }
 #endif
 
 
-void IGame_Persistent::OnGameEnd	()
+void IGame_Persistent::OnGameEnd()
 {
 #ifndef _EDITOR
-	ObjectPool.clear					();
-	Render->models_Clear				(TRUE);
+    ObjectPool.clear();
+    Render->models_Clear(TRUE);
 #endif
 }
 
-void IGame_Persistent::OnFrame		()
+void IGame_Persistent::OnFrame()
 {
 #ifndef _EDITOR
 
-	if(!Device.Paused() || Device.dwPrecacheFrame)
-		Environment().OnFrame	();
-
-
-	Device.Statistic->Particles_starting= ps_needtoplay.size	();
-	Device.Statistic->Particles_active	= ps_active.size		();
-	Device.Statistic->Particles_destroy	= ps_destroy.size		();
-
-	// Play req particle systems
-	while (ps_needtoplay.size())
-	{
-		CPS_Instance*	psi		= ps_needtoplay.back	();
-		ps_needtoplay.pop_back	();
-		psi->Play				(false);
-	}
-	// Destroy inactive particle systems
-	while (ps_destroy.size())
-	{
-//		u32 cnt					= ps_destroy.size();
-		CPS_Instance*	psi		= ps_destroy.back();
-		VERIFY					(psi);
-		if (psi->Locked())
-		{
-			Log("--locked");
-			break;
-		}
-		ps_destroy.pop_back		();
-		psi->PSI_internal_delete();
-	}
+    if (!Device.Paused() || Device.dwPrecacheFrame)
+        Environment().OnFrame();
+
+
+    Device.Statistic->Particles_starting = ps_needtoplay.size();
+    Device.Statistic->Particles_active = ps_active.size();
+    Device.Statistic->Particles_destroy = ps_destroy.size();
+
+    // Play req particle systems
+    while (ps_needtoplay.size())
+    {
+        CPS_Instance* psi = ps_needtoplay.back();
+        ps_needtoplay.pop_back();
+        psi->Play(false);
+    }
+    // Destroy inactive particle systems
+    while (ps_destroy.size())
+    {
+        // u32 cnt = ps_destroy.size();
+        CPS_Instance* psi = ps_destroy.back();
+        VERIFY(psi);
+        if (psi->Locked())
+        {
+            Log("--locked");
+            break;
+        }
+        ps_destroy.pop_back();
+        psi->PSI_internal_delete();
+    }
 #endif
 }
 
-void IGame_Persistent::destroy_particles		(const bool &all_particles)
+void IGame_Persistent::destroy_particles(const bool& all_particles)
 {
 #ifndef _EDITOR
-	ps_needtoplay.clear				();
-
-	while (ps_destroy.size())
-	{
-		CPS_Instance*	psi		= ps_destroy.back	();		
-		VERIFY					(psi);
-		VERIFY					(!psi->Locked());
-		ps_destroy.pop_back		();
-		psi->PSI_internal_delete();
-	}
-
-	// delete active particles
-	if (all_particles) {
-		for (;!ps_active.empty();)
-			(*ps_active.begin())->PSI_internal_delete	();
-	}
-	else {
-		u32								active_size = ps_active.size();
-		CPS_Instance					**I = (CPS_Instance**)_alloca(active_size*sizeof(CPS_Instance*));
-		std::copy						(ps_active.begin(),ps_active.end(),I);
-
-		struct destroy_on_game_load {
-			static IC bool predicate (CPS_Instance*const& object)
-			{
-				return					(!object->destroy_on_game_load());
-			}
-		};
-
-		CPS_Instance					**E = std::remove_if(I,I + active_size,&destroy_on_game_load::predicate);
-		for ( ; I != E; ++I)
-			(*I)->PSI_internal_delete	();
-	}
-
-	VERIFY								(ps_needtoplay.empty() && ps_destroy.empty() && (!all_particles || ps_active.empty()));
+    ps_needtoplay.clear();
+
+    while (ps_destroy.size())
+    {
+        CPS_Instance* psi = ps_destroy.back();
+        VERIFY(psi);
+        VERIFY(!psi->Locked());
+        ps_destroy.pop_back();
+        psi->PSI_internal_delete();
+    }
+
+    // delete active particles
+    if (all_particles)
+    {
+        for (; !ps_active.empty();)
+            (*ps_active.begin())->PSI_internal_delete();
+    }
+    else
+    {
+        u32 active_size = ps_active.size();
+        CPS_Instance** I = (CPS_Instance**)_alloca(active_size*sizeof(CPS_Instance*));
+        std::copy(ps_active.begin(), ps_active.end(), I);
+
+        struct destroy_on_game_load
+        {
+            static IC bool predicate(CPS_Instance* const& object)
+            {
+                return (!object->destroy_on_game_load());
+            }
+        };
+
+        CPS_Instance** E = std::remove_if(I, I + active_size, &destroy_on_game_load::predicate);
+        for (; I != E; ++I)
+            (*I)->PSI_internal_delete();
+    }
+
+    VERIFY(ps_needtoplay.empty() && ps_destroy.empty() && (!all_particles || ps_active.empty()));
 #endif
 }
 
 void IGame_Persistent::OnAssetsChanged()
 {
 #ifndef _EDITOR
-	Device.m_pRender->OnAssetsChanged(); //Resources->m_textures_description.Load();
-#endif    
+    Device.m_pRender->OnAssetsChanged(); //Resources->m_textures_description.Load();
+#endif
 }
diff --git a/src/xrEngine/IGame_Persistent.h b/src/xrEngine/IGame_Persistent.h
index d36b3166c99..e816bf63352 100644
--- a/src/xrEngine/IGame_Persistent.h
+++ b/src/xrEngine/IGame_Persistent.h
@@ -12,122 +12,125 @@ class IRenderVisual;
 class IMainMenu;
 class ENGINE_API CPS_Instance;
 //-----------------------------------------------------------------------------------------------------------
-class ENGINE_API IGame_Persistent	: 
+class ENGINE_API IGame_Persistent :
 #ifndef _EDITOR
-	public DLL_Pure,
+    public DLL_Pure,
 #endif
-	public pureAppStart, 
-	public pureAppEnd,
-	public pureAppActivate, 
-	public pureAppDeactivate,
-	public pureFrame
+    public pureAppStart,
+    public pureAppEnd,
+    public pureAppActivate,
+    public pureAppDeactivate,
+    public pureFrame
 {
 public:
-	union params {
-		struct {
-			string256	m_game_or_spawn;
-			string256	m_game_type;
-			string256	m_alife;
-			string256	m_new_or_load;
-			EGameIDs	m_e_game_type;
-		};
-		string256		m_params[4];
-						params		()	{	reset();	}
-		void			reset		()
-		{
-			for (int i=0; i<4; ++i)
-				xr_strcpy	(m_params[i],"");
-		}
-		void						parse_cmd_line		(LPCSTR cmd_line)
-		{
-			reset					();
-			int						n = _min(4,_GetItemCount(cmd_line,'/'));
-			for (int i=0; i			ps_active;
-	xr_vector		ps_destroy;
-	xr_vector		ps_needtoplay;
+    xr_set ps_active;
+    xr_vector ps_destroy;
+    xr_vector ps_needtoplay;
 
 public:
-			void					destroy_particles	(const bool &all_particles);
+    void destroy_particles(const bool& all_particles);
 
 public:
-	virtual void					PreStart			(LPCSTR op);
-	virtual void					Start				(LPCSTR op);
-	virtual void					Disconnect			();
+    virtual void PreStart(LPCSTR op);
+    virtual void Start(LPCSTR op);
+    virtual void Disconnect();
 #ifndef _EDITOR
-	IGame_ObjectPool				ObjectPool;
-	CEnvironment*					pEnvironment;
-	CEnvironment&					Environment()	{return *pEnvironment;};
-	void							Prefetch			( );
+    IGame_ObjectPool ObjectPool;
+    CEnvironment* pEnvironment;
+    CEnvironment& Environment() { return *pEnvironment; };
+    void Prefetch();
 #endif
-	IMainMenu*						m_pMainMenu;	
+    IMainMenu* m_pMainMenu;
 
 
-	virtual bool					OnRenderPPUI_query	() { return FALSE; };	// should return true if we want to have second function called
-	virtual void					OnRenderPPUI_main	() {};
-	virtual void					OnRenderPPUI_PP		() {};
+    virtual bool OnRenderPPUI_query() { return FALSE; }; // should return true if we want to have second function called
+    virtual void OnRenderPPUI_main() {};
+    virtual void OnRenderPPUI_PP() {};
 
-	virtual	void					OnAppStart			();
-	virtual void					OnAppEnd			();
-	virtual	void					OnAppActivate		();
-	virtual void					OnAppDeactivate		();
-	virtual void		_BCL		OnFrame				();
+    virtual void OnAppStart();
+    virtual void OnAppEnd();
+    virtual void OnAppActivate();
+    virtual void OnAppDeactivate();
+    virtual void _BCL OnFrame();
 
-	// âûçûâàåòñÿ òîëüêî êîãäà èçìåíÿåòñÿ òèï èãðû
-	virtual	void					OnGameStart			(); 
-	virtual void					OnGameEnd			();
+    // âûçûâàåòñÿ òîëüêî êîãäà èçìåíÿåòñÿ òèï èãðû
+    virtual void OnGameStart();
+    virtual void OnGameEnd();
 
-	virtual void					UpdateGameType		() {};
-	virtual void					GetCurrentDof		(Fvector3& dof){dof.set(-1.4f, 0.0f, 250.f);};
-	virtual void					SetBaseDof			(const Fvector3& dof){};
-	virtual void					OnSectorChanged		(int sector){};
-	virtual void					OnAssetsChanged		();
+    virtual void UpdateGameType() {};
+    virtual void GetCurrentDof(Fvector3& dof) { dof.set(-1.4f, 0.0f, 250.f); };
+    virtual void SetBaseDof(const Fvector3& dof) {};
+    virtual void OnSectorChanged(int sector) {};
+    virtual void OnAssetsChanged();
 
-	virtual void					RegisterModel		(IRenderVisual* V)
+    virtual void RegisterModel(IRenderVisual* V)
 #ifndef _EDITOR
-     = 0;
+        = 0;
 #else
-	{}
+    {}
 #endif
-	virtual	float					MtlTransparent		(u32 mtl_idx)
+    virtual float MtlTransparent(u32 mtl_idx)
 #ifndef _EDITOR
-	= 0;
+        = 0;
 #else
-	{return 1.f;}
+    {return 1.f; }
 #endif
 
-	IGame_Persistent				();
-	virtual ~IGame_Persistent		();
+    IGame_Persistent();
+    virtual ~IGame_Persistent();
 
-	ICF		u32						GameType			() {return m_game_params.m_e_game_type;};
-	virtual void					Statistics			(CGameFont* F)
+    ICF u32 GameType() { return m_game_params.m_e_game_type; };
+    virtual void Statistics(CGameFont* F)
 #ifndef _EDITOR
-     = 0;
+        = 0;
 #else
-	{}
+    {}
 #endif
-	virtual	void					LoadTitle			(bool change_tip=false, shared_str map_name=""){}
-	virtual bool					CanBePaused			()		{ return true;}
+    virtual void LoadTitle(bool change_tip = false, shared_str map_name = "") {}
+    virtual bool CanBePaused() { return true; }
 };
 
 class IMainMenu
 {
 public:
-	virtual			~IMainMenu						()													{};
-	virtual void	Activate						(bool bActive)										=0; 
-	virtual	bool	IsActive						()													=0; 
-	virtual	bool	CanSkipSceneRendering			()													=0; 
-	virtual void	DestroyInternal					(bool bForce)										=0;
+    virtual ~IMainMenu() {};
+    virtual void Activate(bool bActive) = 0;
+    virtual bool IsActive() = 0;
+    virtual bool CanSkipSceneRendering() = 0;
+    virtual void DestroyInternal(bool bForce) = 0;
 };
 
-extern ENGINE_API	bool g_dedicated_server;
-extern ENGINE_API	IGame_Persistent*	g_pGamePersistent;
+extern ENGINE_API bool g_dedicated_server;
+extern ENGINE_API IGame_Persistent* g_pGamePersistent;
 #endif //IGame_PersistentH
 
diff --git a/src/xrEngine/IInputReceiver.cpp b/src/xrEngine/IInputReceiver.cpp
index 66544a7cff5..8f6059e8ccf 100644
--- a/src/xrEngine/IInputReceiver.cpp
+++ b/src/xrEngine/IInputReceiver.cpp
@@ -4,36 +4,36 @@
 #include "xr_input.h"
 #include "iinputreceiver.h"
 
-void	IInputReceiver::IR_Capture						(void)
+void IInputReceiver::IR_Capture(void)
 {
-	VERIFY(pInput);
-	pInput->iCapture(this);
+    VERIFY(pInput);
+    pInput->iCapture(this);
 }
 
-void	IInputReceiver::IR_Release						(void)
+void IInputReceiver::IR_Release(void)
 {
-	VERIFY(pInput);
-	pInput->iRelease(this);
+    VERIFY(pInput);
+    pInput->iRelease(this);
 }
 
-void	IInputReceiver::IR_GetLastMouseDelta			(Ivector2& p)
+void IInputReceiver::IR_GetLastMouseDelta(Ivector2& p)
 {
-	VERIFY(pInput);
-	pInput->iGetLastMouseDelta( p );
+    VERIFY(pInput);
+    pInput->iGetLastMouseDelta(p);
 }
 
-void IInputReceiver::IR_OnDeactivate					(void)
+void IInputReceiver::IR_OnDeactivate(void)
 {
-	int i;
-	for (i = 0; i < CInput::COUNT_KB_BUTTONS; i++ )
-		if (IR_GetKeyState(i))	
-			IR_OnKeyboardRelease	(i);
+    int i;
+    for (i = 0; i < CInput::COUNT_KB_BUTTONS; i++)
+        if (IR_GetKeyState(i))
+            IR_OnKeyboardRelease(i);
 
-	for (i = 0; i < CInput::COUNT_MOUSE_BUTTONS; i++ )
-		if(IR_GetBtnState(i))   
-			IR_OnMouseRelease( i );
-	IR_OnMouseStop	( DIMOFS_X, 0 );
-	IR_OnMouseStop	( DIMOFS_Y, 0 );
+    for (i = 0; i < CInput::COUNT_MOUSE_BUTTONS; i++)
+        if (IR_GetBtnState(i))
+            IR_OnMouseRelease(i);
+    IR_OnMouseStop(DIMOFS_X, 0);
+    IR_OnMouseStop(DIMOFS_Y, 0);
 }
 
 void IInputReceiver::IR_OnActivate(void)
@@ -42,43 +42,43 @@ void IInputReceiver::IR_OnActivate(void)
 
 BOOL IInputReceiver::IR_GetKeyState(int dik)
 {
-	VERIFY(pInput);
-	return pInput->iGetAsyncKeyState(dik);
+    VERIFY(pInput);
+    return pInput->iGetAsyncKeyState(dik);
 }
 
 BOOL IInputReceiver::IR_GetBtnState(int btn)
 {
-	VERIFY(pInput);
-	return pInput->iGetAsyncBtnState(btn);
+    VERIFY(pInput);
+    return pInput->iGetAsyncBtnState(btn);
 }
 
-void	IInputReceiver::IR_GetMousePosScreen			(Ivector2& p)
+void IInputReceiver::IR_GetMousePosScreen(Ivector2& p)
 {
-	GetCursorPos((LPPOINT)&p);
+    GetCursorPos((LPPOINT)&p);
 }
-void	IInputReceiver::IR_GetMousePosReal				(HWND hwnd, Ivector2 &p)
+void IInputReceiver::IR_GetMousePosReal(HWND hwnd, Ivector2& p)
 {
-	IR_GetMousePosScreen(p);
-	if (hwnd) ScreenToClient(hwnd,(LPPOINT)&p);
+    IR_GetMousePosScreen(p);
+    if (hwnd) ScreenToClient(hwnd, (LPPOINT)&p);
 }
-void	IInputReceiver::IR_GetMousePosReal				(Ivector2 &p)
+void IInputReceiver::IR_GetMousePosReal(Ivector2& p)
 {
-	IR_GetMousePosReal(RDEVICE.m_hWnd,p);
+    IR_GetMousePosReal(RDEVICE.m_hWnd, p);
 }
-void	IInputReceiver::IR_GetMousePosIndependent		(Fvector2 &f)
+void IInputReceiver::IR_GetMousePosIndependent(Fvector2& f)
 {
-	Ivector2 p;
-	IR_GetMousePosReal(p);
-	f.set(
-		2.f*float(p.x)/float(RDEVICE.dwWidth)-1.f,
-		2.f*float(p.y)/float(RDEVICE.dwHeight)-1.f
-		);
+    Ivector2 p;
+    IR_GetMousePosReal(p);
+    f.set(
+        2.f*float(p.x) / float(RDEVICE.dwWidth) - 1.f,
+        2.f*float(p.y) / float(RDEVICE.dwHeight) - 1.f
+        );
 }
-void	IInputReceiver::IR_GetMousePosIndependentCrop	(Fvector2 &f)
+void IInputReceiver::IR_GetMousePosIndependentCrop(Fvector2& f)
 {
-	IR_GetMousePosIndependent(f);
-	if (f.x<-1.f) f.x=-1.f;
-	if (f.x> 1.f) f.x= 1.f;
-	if (f.y<-1.f) f.y=-1.f;
-	if (f.y> 1.f) f.y= 1.f;
+    IR_GetMousePosIndependent(f);
+    if (f.x < -1.f) f.x = -1.f;
+    if (f.x > 1.f) f.x = 1.f;
+    if (f.y < -1.f) f.y = -1.f;
+    if (f.y > 1.f) f.y = 1.f;
 }
diff --git a/src/xrEngine/IInputReceiver.h b/src/xrEngine/IInputReceiver.h
index 695bda8c813..df5638cdcb8 100644
--- a/src/xrEngine/IInputReceiver.h
+++ b/src/xrEngine/IInputReceiver.h
@@ -6,37 +6,37 @@
 #define IINPUTRECEIVERH
 #pragma once
 
-class ENGINE_API	IInputReceiver
+class ENGINE_API IInputReceiver
 {
 public:
-	static void		IR_GetLastMouseDelta			(Ivector2& p);
-	static void		IR_GetMousePosScreen			(Ivector2& p);
-	static void		IR_GetMousePosReal				(HWND hwnd, Ivector2 &p);
-	static void		IR_GetMousePosReal				(Ivector2 &p);
-	static void		IR_GetMousePosIndependent		(Fvector2 &f);
-	static void		IR_GetMousePosIndependentCrop	(Fvector2 &f);
-	BOOL			IR_GetKeyState					(int dik);
-	BOOL			IR_GetBtnState					(int btn);
-	void			IR_Capture						(void);
-	void			IR_Release						(void);
+    static void IR_GetLastMouseDelta(Ivector2& p);
+    static void IR_GetMousePosScreen(Ivector2& p);
+    static void IR_GetMousePosReal(HWND hwnd, Ivector2& p);
+    static void IR_GetMousePosReal(Ivector2& p);
+    static void IR_GetMousePosIndependent(Fvector2& f);
+    static void IR_GetMousePosIndependentCrop(Fvector2& f);
+    BOOL IR_GetKeyState(int dik);
+    BOOL IR_GetBtnState(int btn);
+    void IR_Capture(void);
+    void IR_Release(void);
 
-	virtual void	IR_OnDeactivate					(void);
-	virtual void	IR_OnActivate					(void);
+    virtual void IR_OnDeactivate(void);
+    virtual void IR_OnActivate(void);
 
-	virtual void	IR_OnMousePress					(int btn)		{};
-	virtual void	IR_OnMouseRelease				(int btn)		{};
-	virtual void	IR_OnMouseHold					(int btn)		{};
-	virtual void	IR_OnMouseWheel					(int direction)	{};
-	virtual void	IR_OnMouseMove					(int x, int y)	{};
-	virtual void	IR_OnMouseStop					(int x, int y)	{};
+    virtual void IR_OnMousePress(int btn) {};
+    virtual void IR_OnMouseRelease(int btn) {};
+    virtual void IR_OnMouseHold(int btn) {};
+    virtual void IR_OnMouseWheel(int direction) {};
+    virtual void IR_OnMouseMove(int x, int y) {};
+    virtual void IR_OnMouseStop(int x, int y) {};
 
-	virtual void	IR_OnKeyboardPress				(int dik)		{};
-	virtual void	IR_OnKeyboardRelease			(int dik)		{};
-	virtual void	IR_OnKeyboardHold				(int dik)		{};
+    virtual void IR_OnKeyboardPress(int dik) {};
+    virtual void IR_OnKeyboardRelease(int dik) {};
+    virtual void IR_OnKeyboardHold(int dik) {};
 };
 
-ENGINE_API extern float			psMouseSens;
-ENGINE_API extern float			psMouseSensScale;
-ENGINE_API extern Flags32		psMouseInvert;
+ENGINE_API extern float psMouseSens;
+ENGINE_API extern float psMouseSensScale;
+ENGINE_API extern Flags32 psMouseInvert;
 
 #endif
diff --git a/src/xrEngine/IObjectPhysicsCollision.h b/src/xrEngine/IObjectPhysicsCollision.h
index 00474f0407a..63cf5be1f2b 100644
--- a/src/xrEngine/IObjectPhysicsCollision.h
+++ b/src/xrEngine/IObjectPhysicsCollision.h
@@ -5,6 +5,6 @@ class IPhysicsElement;
 xr_pure_interface IObjectPhysicsCollision
 {
 public:
-	virtual	const IPhysicsShell		*physics_shell()const		= 0;
-	virtual const IPhysicsElement	*physics_character()const	= 0;//depricated
+    virtual const IPhysicsShell *physics_shell()const = 0;
+    virtual const IPhysicsElement *physics_character()const = 0;//depricated
 };
\ No newline at end of file
diff --git a/src/xrEngine/IPHdebug.h b/src/xrEngine/IPHdebug.h
index b2ba876545c..5f5eaded926 100644
--- a/src/xrEngine/IPHdebug.h
+++ b/src/xrEngine/IPHdebug.h
@@ -2,9 +2,9 @@
 
 xr_pure_interface IPhDebugRender
 {
-	virtual void	open_cashed_draw	()																				= 0;
-	virtual void	close_cashed_draw	( u32 remove_time)																= 0;
-	virtual	void	draw_tri			( const Fvector &v0, const Fvector &v1, const Fvector &v2, u32 c, bool solid )	= 0;
+    virtual void open_cashed_draw() = 0;
+    virtual void close_cashed_draw(u32 remove_time) = 0;
+    virtual void draw_tri(const Fvector &v0, const Fvector &v1, const Fvector &v2, u32 c, bool solid) = 0;
 };
 
-extern	ENGINE_API IPhDebugRender* ph_debug_render;
\ No newline at end of file
+extern ENGINE_API IPhDebugRender* ph_debug_render;
\ No newline at end of file
diff --git a/src/xrEngine/IPhysicsGeometry.h b/src/xrEngine/IPhysicsGeometry.h
index e1c51ddb7a3..5619295c3cd 100644
--- a/src/xrEngine/IPhysicsGeometry.h
+++ b/src/xrEngine/IPhysicsGeometry.h
@@ -1,11 +1,11 @@
-#ifndef	__IPHYSICS_GEOMETRY_H__
-#define	__IPHYSICS_GEOMETRY_H__
+#ifndef __IPHYSICS_GEOMETRY_H__
+#define __IPHYSICS_GEOMETRY_H__
 
-class	IPhysicsGeometry
+class IPhysicsGeometry
 {
 public:
-	virtual		void		get_Box				(  Fmatrix& form, Fvector&	sz )const	=0;
-	virtual		bool		collide_fluids		() const								=0;
+    virtual void get_Box(Fmatrix& form, Fvector& sz)const = 0;
+    virtual bool collide_fluids() const = 0;
 };
 
 #endif
\ No newline at end of file
diff --git a/src/xrEngine/IPhysicsShell.h b/src/xrEngine/IPhysicsShell.h
index 668463508be..914b063288a 100644
--- a/src/xrEngine/IPhysicsShell.h
+++ b/src/xrEngine/IPhysicsShell.h
@@ -3,24 +3,24 @@
 #pragma once
 
 class IPhysicsGeometry;
-class	IPhysicsElement
+class IPhysicsElement
 {
 public:
-	virtual	const	Fmatrix			&XFORM				()							const			= 0;
-	virtual			void			get_LinearVel		( Fvector& velocity )		const			= 0;
-	virtual			void			get_AngularVel		( Fvector& velocity )		const			= 0;
-	virtual			void			get_Box				( Fvector&	sz, Fvector& c )const			= 0;
-	virtual	const	Fvector			&mass_Center		()							const			= 0;
-	virtual			u16				numberOfGeoms		()							const			= 0;
-	virtual	const	IPhysicsGeometry*geometry			( u16 i )					const			= 0;
+    virtual const Fmatrix& XFORM() const = 0;
+    virtual void get_LinearVel(Fvector& velocity) const = 0;
+    virtual void get_AngularVel(Fvector& velocity) const = 0;
+    virtual void get_Box(Fvector& sz, Fvector& c)const = 0;
+    virtual const Fvector& mass_Center() const = 0;
+    virtual u16 numberOfGeoms() const = 0;
+    virtual const IPhysicsGeometry* geometry(u16 i) const = 0;
 };
 
-class	IPhysicsShell
+class IPhysicsShell
 {
 public:
-	virtual	const	Fmatrix				&XFORM				()				const	= 0;
-	virtual	const	IPhysicsElement		&Element			( u16 index )	const	= 0;
-	virtual			u16					get_ElementsNumber	( )				const	= 0;
+    virtual const Fmatrix& XFORM() const = 0;
+    virtual const IPhysicsElement& Element(u16 index) const = 0;
+    virtual u16 get_ElementsNumber() const = 0;
 };
 
 
diff --git a/src/xrEngine/IRenderable.cpp b/src/xrEngine/IRenderable.cpp
index afe3d327f35..e9dbd311e7f 100644
--- a/src/xrEngine/IRenderable.cpp
+++ b/src/xrEngine/IRenderable.cpp
@@ -4,26 +4,26 @@
 
 IRenderable::IRenderable()
 {
-	renderable.xform.identity			();
-	renderable.visual					= NULL;
-	renderable.pROS						= NULL;
-	renderable.pROS_Allowed				= TRUE;
-	ISpatial*		self				= dynamic_cast (this);
-	if (self)		self->spatial.type	|= STYPE_RENDERABLE;
+    renderable.xform.identity();
+    renderable.visual = NULL;
+    renderable.pROS = NULL;
+    renderable.pROS_Allowed = TRUE;
+    ISpatial* self = dynamic_cast (this);
+    if (self) self->spatial.type |= STYPE_RENDERABLE;
 }
 
-extern ENGINE_API BOOL g_bRendering; 
+extern ENGINE_API BOOL g_bRendering;
 IRenderable::~IRenderable()
 {
-	VERIFY								(!g_bRendering); 
-	Render->model_Delete				(renderable.visual);
-	if (renderable.pROS)				Render->ros_destroy					(renderable.pROS);
-	renderable.visual					= NULL;
-	renderable.pROS						= NULL;
+    VERIFY(!g_bRendering);
+    Render->model_Delete(renderable.visual);
+    if (renderable.pROS) Render->ros_destroy(renderable.pROS);
+    renderable.visual = NULL;
+    renderable.pROS = NULL;
 }
 
-IRender_ObjectSpecific*				IRenderable::renderable_ROS				()	
+IRender_ObjectSpecific* IRenderable::renderable_ROS()
 {
-	if (0==renderable.pROS && renderable.pROS_Allowed)		renderable.pROS	= Render->ros_create(this);
-	return renderable.pROS	;
+    if (0 == renderable.pROS && renderable.pROS_Allowed) renderable.pROS = Render->ros_create(this);
+    return renderable.pROS;
 }
diff --git a/src/xrEngine/IRenderable.h b/src/xrEngine/IRenderable.h
index 9db14c62f63..009a48be061 100644
--- a/src/xrEngine/IRenderable.h
+++ b/src/xrEngine/IRenderable.h
@@ -5,23 +5,24 @@
 
 //////////////////////////////////////////////////////////////////////////
 // definition ("Renderable")
-class	ENGINE_API	IRenderable			{
+class ENGINE_API IRenderable
+{
 public:
-	struct 
-	{
-		Fmatrix							xform						;
-		IRenderVisual*					visual						;
-		IRender_ObjectSpecific*			pROS						;
-		BOOL							pROS_Allowed				;
-	}	renderable;
+    struct
+    {
+        Fmatrix xform;
+        IRenderVisual* visual;
+        IRender_ObjectSpecific* pROS;
+        BOOL pROS_Allowed;
+    } renderable;
 public:
-										IRenderable					();
-	virtual								~IRenderable				();
-	IRender_ObjectSpecific*				renderable_ROS				()	;
-	BENCH_SEC_SCRAMBLEVTBL2
-	virtual	void						renderable_Render			()	= 0;
-	virtual	BOOL						renderable_ShadowGenerate	()	{ return FALSE; };
-	virtual	BOOL						renderable_ShadowReceive	()	{ return FALSE; };
+    IRenderable();
+    virtual ~IRenderable();
+    IRender_ObjectSpecific* renderable_ROS();
+    BENCH_SEC_SCRAMBLEVTBL2
+        virtual void renderable_Render() = 0;
+    virtual BOOL renderable_ShadowGenerate() { return FALSE; };
+    virtual BOOL renderable_ShadowReceive() { return FALSE; };
 };
 
 #endif // IRENDERABLE_H_INCLUDED
\ No newline at end of file
diff --git a/src/xrEngine/ISheduled.cpp b/src/xrEngine/ISheduled.cpp
index a304f2d525f..d4d3c9e4f38 100644
--- a/src/xrEngine/ISheduled.cpp
+++ b/src/xrEngine/ISheduled.cpp
@@ -2,52 +2,52 @@
 #include "xrSheduler.h"
 #include "xr_object.h"
 
-ISheduled::ISheduled	()	
+ISheduled::ISheduled()
 {
-	shedule.t_min		= 20;
-	shedule.t_max		= 1000;
-	shedule.b_locked	= FALSE;
+    shedule.t_min = 20;
+    shedule.t_max = 1000;
+    shedule.b_locked = FALSE;
 #ifdef DEBUG
-	dbg_startframe		= 1;
-	dbg_update_shedule	= 0;
+    dbg_startframe = 1;
+    dbg_update_shedule = 0;
 #endif
 }
 
-extern		BOOL		g_bSheduleInProgress;
-ISheduled::~ISheduled	()
+extern BOOL g_bSheduleInProgress;
+ISheduled::~ISheduled()
 {
-	VERIFY2				(
-		!Engine.Sheduler.Registered(this),
-		make_string("0x%08x : %s",this,*shedule_Name())
-	);
+    VERIFY2(
+        !Engine.Sheduler.Registered(this),
+        make_string("0x%08x : %s", this, *shedule_Name())
+        );
 
-	// sad, but true
-	// we need this to become MASTER_GOLD
+    // sad, but true
+    // we need this to become MASTER_GOLD
 #ifndef DEBUG
-	Engine.Sheduler.Unregister				(this);
+    Engine.Sheduler.Unregister(this);
 #endif // DEBUG
 }
 
-void	ISheduled::shedule_register			()
+void ISheduled::shedule_register()
 {
-	Engine.Sheduler.Register				(this);
+    Engine.Sheduler.Register(this);
 }
 
-void	ISheduled::shedule_unregister		()
+void ISheduled::shedule_unregister()
 {
-	Engine.Sheduler.Unregister				(this);
+    Engine.Sheduler.Unregister(this);
 }
 
-void	ISheduled::shedule_Update			(u32 dt)
+void ISheduled::shedule_Update(u32 dt)
 {
 #ifdef DEBUG
-	if (dbg_startframe==dbg_update_shedule)	
-	{
-		LPCSTR		name	= "unknown";
-		CObject*	O		= dynamic_cast	(this);
-		if			(O)		name	= *O->cName();
-		Debug.fatal	(DEBUG_INFO,"'shedule_Update' called twice per frame for %s",name);
-	}
-	dbg_update_shedule	= dbg_startframe;
+    if (dbg_startframe == dbg_update_shedule)
+    {
+        LPCSTR name = "unknown";
+        CObject* O = dynamic_cast (this);
+        if (O) name = *O->cName();
+        Debug.fatal(DEBUG_INFO, "'shedule_Update' called twice per frame for %s", name);
+    }
+    dbg_update_shedule = dbg_startframe;
 #endif
 }
diff --git a/src/xrEngine/ISheduled.h b/src/xrEngine/ISheduled.h
index 8f2ea615fdc..8771523c03d 100644
--- a/src/xrEngine/ISheduled.h
+++ b/src/xrEngine/ISheduled.h
@@ -1,31 +1,32 @@
 #ifndef XRENGINE_ISHEDULED_H_INCLUDED
 #define XRENGINE_ISHEDULED_H_INCLUDED
 
-class	ENGINE_API	ISheduled
+class ENGINE_API ISheduled
 {
 public:
-	struct {
-		u32		t_min		:	14;		// minimal bound of update time (sample: 20ms)
-		u32		t_max		:	14;		// maximal bound of update time (sample: 200ms)
-		u32		b_RT		:	1;
-		u32		b_locked	:	1;
-	}	shedule;
+    struct
+    {
+        u32 t_min : 14; // minimal bound of update time (sample: 20ms)
+        u32 t_max : 14; // maximal bound of update time (sample: 200ms)
+        u32 b_RT : 1;
+        u32 b_locked : 1;
+    } shedule;
 
 #ifdef DEBUG
-	u32									dbg_startframe;
-	u32									dbg_update_shedule;
+    u32 dbg_startframe;
+    u32 dbg_update_shedule;
 #endif
 
-				ISheduled				();
-	virtual ~	ISheduled				();
+    ISheduled();
+    virtual ~ISheduled();
 
-	void								shedule_register	();
-	void								shedule_unregister	();
+    void shedule_register();
+    void shedule_unregister();
 
-	virtual float						shedule_Scale		()			= 0;
-	virtual void						shedule_Update		(u32 dt);
-	virtual	shared_str					shedule_Name		() const	{ return shared_str("unknown"); };
-	virtual bool						shedule_Needed		()			= 0;
+    virtual float shedule_Scale() = 0;
+    virtual void shedule_Update(u32 dt);
+    virtual shared_str shedule_Name() const { return shared_str("unknown"); };
+    virtual bool shedule_Needed() = 0;
 
 };
 
diff --git a/src/xrEngine/ISpatial.cpp b/src/xrEngine/ISpatial.cpp
index c06402302f7..6a868bccf2f 100644
--- a/src/xrEngine/ISpatial.cpp
+++ b/src/xrEngine/ISpatial.cpp
@@ -4,331 +4,343 @@
 #include "xr_object.h"
 #include "PS_Instance.h"
 
-ENGINE_API ISpatial_DB*		g_SpatialSpace			= NULL;
-ENGINE_API ISpatial_DB*		g_SpatialSpacePhysic	= NULL;
+ENGINE_API ISpatial_DB* g_SpatialSpace = NULL;
+ENGINE_API ISpatial_DB* g_SpatialSpacePhysic = NULL;
 
-Fvector	c_spatial_offset	[8]	= 
+Fvector c_spatial_offset[8] =
 {
-	{ -1, -1, -1	},
-	{  1, -1, -1	},
-	{ -1,  1, -1	},
-	{  1,  1, -1	},
-	{ -1, -1,  1	},
-	{  1, -1,  1	},
-	{ -1,  1,  1	},
-	{  1,  1,  1	}
+    {-1, -1, -1},
+    {1, -1, -1},
+    {-1, 1, -1},
+    {1, 1, -1},
+    {-1, -1, 1},
+    {1, -1, 1},
+    {-1, 1, 1},
+    {1, 1, 1}
 };
 
 //////////////////////////////////////////////////////////////////////////
-ISpatial::ISpatial			(ISpatial_DB* space)
+ISpatial::ISpatial(ISpatial_DB* space)
 {
-	spatial.sphere.P.set	(0,0,0);
-	spatial.sphere.R		= 0;
-	spatial.node_center.set	(0,0,0);
-	spatial.node_radius		= 0;
-	spatial.node_ptr		= NULL;
-	spatial.sector			= NULL;
-	spatial.space			= space;
+    spatial.sphere.P.set(0, 0, 0);
+    spatial.sphere.R = 0;
+    spatial.node_center.set(0, 0, 0);
+    spatial.node_radius = 0;
+    spatial.node_ptr = NULL;
+    spatial.sector = NULL;
+    spatial.space = space;
 }
-ISpatial::~ISpatial			(void)
+ISpatial::~ISpatial(void)
 {
-	spatial_unregister		();
+    spatial_unregister();
 }
-BOOL	ISpatial::spatial_inside()
+BOOL ISpatial::spatial_inside()
 {
-	float	dr	= -(- spatial.node_radius + spatial.sphere.R);
-	if (spatial.sphere.P.x < spatial.node_center.x - dr)	return FALSE;
-	if (spatial.sphere.P.x > spatial.node_center.x + dr)	return FALSE;
-	if (spatial.sphere.P.y < spatial.node_center.y - dr)	return FALSE;
-	if (spatial.sphere.P.y > spatial.node_center.y + dr)	return FALSE;
-	if (spatial.sphere.P.z < spatial.node_center.z - dr)	return FALSE;
-	if (spatial.sphere.P.z > spatial.node_center.z + dr)	return FALSE;
-	return TRUE;
+    float dr = -(-spatial.node_radius + spatial.sphere.R);
+    if (spatial.sphere.P.x < spatial.node_center.x - dr) return FALSE;
+    if (spatial.sphere.P.x > spatial.node_center.x + dr) return FALSE;
+    if (spatial.sphere.P.y < spatial.node_center.y - dr) return FALSE;
+    if (spatial.sphere.P.y > spatial.node_center.y + dr) return FALSE;
+    if (spatial.sphere.P.z < spatial.node_center.z - dr) return FALSE;
+    if (spatial.sphere.P.z > spatial.node_center.z + dr) return FALSE;
+    return TRUE;
 }
 
-BOOL	verify_sp	(ISpatial* sp, Fvector& node_center, float node_radius)
+BOOL verify_sp(ISpatial* sp, Fvector& node_center, float node_radius)
 {
-	float	dr	= -(- node_radius + sp->spatial.sphere.R);
-	if (sp->spatial.sphere.P.x < node_center.x - dr)	return FALSE;
-	if (sp->spatial.sphere.P.x > node_center.x + dr)	return FALSE;
-	if (sp->spatial.sphere.P.y < node_center.y - dr)	return FALSE;
-	if (sp->spatial.sphere.P.y > node_center.y + dr)	return FALSE;
-	if (sp->spatial.sphere.P.z < node_center.z - dr)	return FALSE;
-	if (sp->spatial.sphere.P.z > node_center.z + dr)	return FALSE;
-	return TRUE;
+    float dr = -(-node_radius + sp->spatial.sphere.R);
+    if (sp->spatial.sphere.P.x < node_center.x - dr) return FALSE;
+    if (sp->spatial.sphere.P.x > node_center.x + dr) return FALSE;
+    if (sp->spatial.sphere.P.y < node_center.y - dr) return FALSE;
+    if (sp->spatial.sphere.P.y > node_center.y + dr) return FALSE;
+    if (sp->spatial.sphere.P.z < node_center.z - dr) return FALSE;
+    if (sp->spatial.sphere.P.z > node_center.z + dr) return FALSE;
+    return TRUE;
 }
 
-void	ISpatial::spatial_register	()
+void ISpatial::spatial_register()
 {
-	spatial.type			|=	STYPEFLAG_INVALIDSECTOR;
-	if (spatial.node_ptr)
-	{
-		// already registered - nothing to do
-	} else {
-		// register
-		R_ASSERT				(spatial.space);
-		spatial.space->insert	(this);
-		spatial.sector			=	0;
-	}
+    spatial.type |= STYPEFLAG_INVALIDSECTOR;
+    if (spatial.node_ptr)
+    {
+        // already registered - nothing to do
+    }
+    else
+    {
+        // register
+        R_ASSERT(spatial.space);
+        spatial.space->insert(this);
+        spatial.sector = 0;
+    }
 }
 
-void	ISpatial::spatial_unregister()
+void ISpatial::spatial_unregister()
 {
-	if (spatial.node_ptr)
-	{
-		// remove
-		spatial.space->remove	(this);
-		spatial.node_ptr		= NULL;
-		spatial.sector			= NULL;
-	} else {
-		// already unregistered
-	}
+    if (spatial.node_ptr)
+    {
+        // remove
+        spatial.space->remove(this);
+        spatial.node_ptr = NULL;
+        spatial.sector = NULL;
+    }
+    else
+    {
+        // already unregistered
+    }
 }
 
-void	ISpatial::spatial_move	()
+void ISpatial::spatial_move()
 {
-	if (spatial.node_ptr)
-	{
-		//*** somehow it was determined that object has been moved
-		spatial.type		|=				STYPEFLAG_INVALIDSECTOR;
-
-		//*** check if we are supposed to correct it's spatial location
-		if						(spatial_inside())	return;		// ???
-		spatial.space->remove	(this);
-		spatial.space->insert	(this);
-	} else {
-		//*** we are not registered yet, or already unregistered
-		//*** ignore request
-	}
+    if (spatial.node_ptr)
+    {
+        //*** somehow it was determined that object has been moved
+        spatial.type |= STYPEFLAG_INVALIDSECTOR;
+
+        //*** check if we are supposed to correct it's spatial location
+        if (spatial_inside()) return; // ???
+        spatial.space->remove(this);
+        spatial.space->insert(this);
+    }
+    else
+    {
+        //*** we are not registered yet, or already unregistered
+        //*** ignore request
+    }
 }
 
-void	ISpatial::spatial_updatesector_internal()
+void ISpatial::spatial_updatesector_internal()
 {
-	IRender_Sector*		S				=	::Render->detectSector(spatial_sector_point());
-	spatial.type						&=	~STYPEFLAG_INVALIDSECTOR;
-	if (S)				spatial.sector	=	S;
+    IRender_Sector* S = ::Render->detectSector(spatial_sector_point());
+    spatial.type &= ~STYPEFLAG_INVALIDSECTOR;
+    if (S) spatial.sector = S;
 }
 
 //////////////////////////////////////////////////////////////////////////
-void			ISpatial_NODE::_init			(ISpatial_NODE* _parent)
+void ISpatial_NODE::_init(ISpatial_NODE* _parent)
 {
-	parent		=	_parent;
-	children[0]	=	children[1]	=	children[2]	=	children[3]	=
-	children[4]	=	children[5]	=	children[6]	=	children[7]	=	NULL;
-	items.clear();
+    parent = _parent;
+    children[0] = children[1] = children[2] = children[3] =
+        children[4] = children[5] = children[6] = children[7] = NULL;
+    items.clear();
 }
 
-void			ISpatial_NODE::_insert			(ISpatial* S)			
-{	
-	S->spatial.node_ptr			=	this;
-	items.push_back					(S);
-	S->spatial.space->stat_objects	++;
+void ISpatial_NODE::_insert(ISpatial* S)
+{
+    S->spatial.node_ptr = this;
+    items.push_back(S);
+    S->spatial.space->stat_objects++;
 }
 
-void			ISpatial_NODE::_remove			(ISpatial* S)			
-{	
-	S->spatial.node_ptr			=	NULL;
-	xr_vector::iterator	it = std::find(items.begin(),items.end(),S);
-	VERIFY				(it!=items.end());
-	items.erase			(it);
-	S->spatial.space->stat_objects	--;
+void ISpatial_NODE::_remove(ISpatial* S)
+{
+    S->spatial.node_ptr = NULL;
+    xr_vector::iterator it = std::find(items.begin(), items.end(), S);
+    VERIFY(it != items.end());
+    items.erase(it);
+    S->spatial.space->stat_objects--;
 }
 
 //////////////////////////////////////////////////////////////////////////
 
 ISpatial_DB::ISpatial_DB()
 #ifdef PROFILE_CRITICAL_SECTIONS
-	:cs(MUTEX_PROFILE_ID(ISpatial_DB))
+    :cs(MUTEX_PROFILE_ID(ISpatial_DB))
 #endif // PROFILE_CRITICAL_SECTIONS
 {
-	m_root					= NULL;
-	stat_nodes				= 0;
-	stat_objects			= 0;
+    m_root = NULL;
+    stat_nodes = 0;
+    stat_objects = 0;
 }
 
 ISpatial_DB::~ISpatial_DB()
 {
-	if ( m_root )
-	{
-		_node_destroy(m_root);
-	}
-
-	while (!allocator_pool.empty()){
-		allocator.destroy		(allocator_pool.back());
-		allocator_pool.pop_back	();
-	}
+    if (m_root)
+    {
+        _node_destroy(m_root);
+    }
+
+    while (!allocator_pool.empty())
+    {
+        allocator.destroy(allocator_pool.back());
+        allocator_pool.pop_back();
+    }
 }
 
-void			ISpatial_DB::initialize(Fbox& BB)
+void ISpatial_DB::initialize(Fbox& BB)
 {
-	if (0==m_root)			
-	{
-		// initialize
-		Fvector bbc,bbd;
-		BB.get_CD				(bbc,bbd);
-
-		bbc.set					(0,0,0);			// generic
-		bbd.set					(1024,1024,1024);	// generic
-
-		allocator_pool.reserve	(128);
-		m_center.set			(bbc);
-		m_bounds				= _max(_max(bbd.x,bbd.y),bbd.z);
-		rt_insert_object		= NULL;
-		if (0==m_root)	m_root	= _node_create();
-		m_root->_init			(NULL);
-	}
+    if (0 == m_root)
+    {
+        // initialize
+        Fvector bbc, bbd;
+        BB.get_CD(bbc, bbd);
+
+        bbc.set(0, 0, 0); // generic
+        bbd.set(1024, 1024, 1024); // generic
+
+        allocator_pool.reserve(128);
+        m_center.set(bbc);
+        m_bounds = _max(_max(bbd.x, bbd.y), bbd.z);
+        rt_insert_object = NULL;
+        if (0 == m_root) m_root = _node_create();
+        m_root->_init(NULL);
+    }
 }
-ISpatial_NODE*	ISpatial_DB::_node_create		()
+ISpatial_NODE* ISpatial_DB::_node_create()
 {
-	stat_nodes	++;
-	if (allocator_pool.empty())			return allocator.create();
-	else								
-	{
-		ISpatial_NODE*	N		= allocator_pool.back();
-		allocator_pool.pop_back	();
-		return			N;
-	}
+    stat_nodes++;
+    if (allocator_pool.empty()) return allocator.create();
+    else
+    {
+        ISpatial_NODE* N = allocator_pool.back();
+        allocator_pool.pop_back();
+        return N;
+    }
 }
-void			ISpatial_DB::_node_destroy(ISpatial_NODE* &P)
+void ISpatial_DB::_node_destroy(ISpatial_NODE*& P)
 {
-	VERIFY						(P->_empty());
-	stat_nodes					--;
-	allocator_pool.push_back	(P);
-	P							= NULL;
+    VERIFY(P->_empty());
+    stat_nodes--;
+    allocator_pool.push_back(P);
+    P = NULL;
 }
 
-void			ISpatial_DB::_insert	(ISpatial_NODE* N, Fvector& n_C, float n_R)
+void ISpatial_DB::_insert(ISpatial_NODE* N, Fvector& n_C, float n_R)
 {
-	//*** we are assured that object lives inside our node
-	float	n_vR	= 2*n_R;
-	VERIFY	(N);
-	VERIFY	(verify_sp(rt_insert_object,n_C,n_vR));
-
-	// we have to make sure we aren't the leaf node
-	if (n_R<=c_spatial_min)
-	{
-		// this is leaf node
-		N->_insert									(rt_insert_object);
-		rt_insert_object->spatial.node_center.set	(n_C);
-		rt_insert_object->spatial.node_radius		= n_vR;		// vR
-		return;
-	}
-
-	// we have to check if it can be putted further down
-	float	s_R			= rt_insert_object->spatial.sphere.R;	// spatial bounds
-	float	c_R			= n_R/2;								// children bounds
-	if (s_Rspatial.sphere.P;
-		u32			octant				=	_octant	(n_C,s_C);
-		Fvector		c_C;				c_C.mad	(n_C,c_spatial_offset[octant],c_R);
-		VERIFY			(octant == _octant(n_C,c_C));				// check table assosiations
-		ISpatial_NODE*	&chield			= N->children[octant];
-
-		if (0==chield)	{
-			chield			=	_node_create();
-			VERIFY			(chield);
-			chield->_init	(N);
-			VERIFY			(chield);
-		}
-		VERIFY			(chield);
-		_insert			(chield, c_C, c_R);
-		VERIFY			(chield);
-	}
-	else
-	{
-		// we have to "own" this object (potentially it can be putted down sometimes...)
-		N->_insert									(rt_insert_object);
-		rt_insert_object->spatial.node_center.set	(n_C);
-		rt_insert_object->spatial.node_radius		= n_vR;
-	}
+    //*** we are assured that object lives inside our node
+    float n_vR = 2 * n_R;
+    VERIFY(N);
+    VERIFY(verify_sp(rt_insert_object, n_C, n_vR));
+
+    // we have to make sure we aren't the leaf node
+    if (n_R <= c_spatial_min)
+    {
+        // this is leaf node
+        N->_insert(rt_insert_object);
+        rt_insert_object->spatial.node_center.set(n_C);
+        rt_insert_object->spatial.node_radius = n_vR; // vR
+        return;
+    }
+
+    // we have to check if it can be putted further down
+    float s_R = rt_insert_object->spatial.sphere.R; // spatial bounds
+    float c_R = n_R / 2; // children bounds
+    if (s_R < c_R)
+    {
+        // object can be pushed further down - select "octant", calc node position
+        Fvector& s_C = rt_insert_object->spatial.sphere.P;
+        u32 octant = _octant(n_C, s_C);
+        Fvector c_C;
+        c_C.mad(n_C, c_spatial_offset[octant], c_R);
+        VERIFY(octant == _octant(n_C, c_C)); // check table assosiations
+        ISpatial_NODE*& chield = N->children[octant];
+
+        if (0 == chield)
+        {
+            chield = _node_create();
+            VERIFY(chield);
+            chield->_init(N);
+            VERIFY(chield);
+        }
+        VERIFY(chield);
+        _insert(chield, c_C, c_R);
+        VERIFY(chield);
+    }
+    else
+    {
+        // we have to "own" this object (potentially it can be putted down sometimes...)
+        N->_insert(rt_insert_object);
+        rt_insert_object->spatial.node_center.set(n_C);
+        rt_insert_object->spatial.node_radius = n_vR;
+    }
 }
 
-void			ISpatial_DB::insert		(ISpatial* S)
+void ISpatial_DB::insert(ISpatial* S)
 {
-	cs.Enter			();
+    cs.Enter();
 #ifdef DEBUG
-	stat_insert.Begin	();
-
-	BOOL		bValid	= _valid(S->spatial.sphere.R) && _valid(S->spatial.sphere.P);
-	if (!bValid)	
-	{
-		CObject*	O	= dynamic_cast(S);
-		if	(O)			Debug.fatal(DEBUG_INFO,"Invalid OBJECT position or radius (%s)",O->cName());
-		else			{
-			CPS_Instance* P = dynamic_cast(S);
-			if (P)		Debug.fatal(DEBUG_INFO,"Invalid PS spatial position{%3.2f,%3.2f,%3.2f} or radius{%3.2f}",VPUSH(S->spatial.sphere.P),S->spatial.sphere.R);
-			else		Debug.fatal(DEBUG_INFO,"Invalid OTHER spatial position{%3.2f,%3.2f,%3.2f} or radius{%3.2f}",VPUSH(S->spatial.sphere.P),S->spatial.sphere.R);
-		}
-	}
+    stat_insert.Begin();
+
+    BOOL bValid = _valid(S->spatial.sphere.R) && _valid(S->spatial.sphere.P);
+    if (!bValid)
+    {
+        CObject* O = dynamic_cast(S);
+        if (O) Debug.fatal(DEBUG_INFO, "Invalid OBJECT position or radius (%s)", O->cName());
+        else
+        {
+            CPS_Instance* P = dynamic_cast(S);
+            if (P) Debug.fatal(DEBUG_INFO, "Invalid PS spatial position{%3.2f,%3.2f,%3.2f} or radius{%3.2f}", VPUSH(S->spatial.sphere.P), S->spatial.sphere.R);
+            else Debug.fatal(DEBUG_INFO, "Invalid OTHER spatial position{%3.2f,%3.2f,%3.2f} or radius{%3.2f}", VPUSH(S->spatial.sphere.P), S->spatial.sphere.R);
+        }
+    }
 #endif
 
-	if (verify_sp(S,m_center,m_bounds))
-	{
-		// Object inside our DB
-		rt_insert_object			= S;
-		_insert						(m_root,m_center,m_bounds);
-		VERIFY						(S->spatial_inside());
-	} else {
-		// Object outside our DB, put it into root node and hack bounds
-		// Object will reinsert itself until fits into "real", "controlled" space
-		m_root->_insert				(S);
-		S->spatial.node_center.set	(m_center);
-		S->spatial.node_radius		=	m_bounds;
-	}
+    if (verify_sp(S, m_center, m_bounds))
+    {
+        // Object inside our DB
+        rt_insert_object = S;
+        _insert(m_root, m_center, m_bounds);
+        VERIFY(S->spatial_inside());
+    }
+    else
+    {
+        // Object outside our DB, put it into root node and hack bounds
+        // Object will reinsert itself until fits into "real", "controlled" space
+        m_root->_insert(S);
+        S->spatial.node_center.set(m_center);
+        S->spatial.node_radius = m_bounds;
+    }
 #ifdef DEBUG
-	stat_insert.End		();
+    stat_insert.End();
 #endif
-	cs.Leave			();
+    cs.Leave();
 }
 
-void			ISpatial_DB::_remove	(ISpatial_NODE* N, ISpatial_NODE* N_sub)
+void ISpatial_DB::_remove(ISpatial_NODE* N, ISpatial_NODE* N_sub)
 {
-	if (0==N)							return;
-
-	//*** we are assured that node contains N_sub and this subnode is empty
-	u32 octant	= u32(-1);
-	if (N_sub==N->children[0])			octant = 0;
-	else if (N_sub==N->children[1])		octant = 1;
-	else if (N_sub==N->children[2])		octant = 2;
-	else if (N_sub==N->children[3])		octant = 3;
-	else if (N_sub==N->children[4])		octant = 4;
-	else if (N_sub==N->children[5])		octant = 5;
-	else if (N_sub==N->children[6])		octant = 6;
-	else if (N_sub==N->children[7])		octant = 7;
-	VERIFY		(octant<8);
-	VERIFY		(N_sub->_empty());
-	_node_destroy						(N->children[octant]);
-
-	// Recurse
-	if (N->_empty())					_remove(N->parent,N);
+    if (0 == N) return;
+
+    //*** we are assured that node contains N_sub and this subnode is empty
+    u32 octant = u32(-1);
+    if (N_sub == N->children[0]) octant = 0;
+    else if (N_sub == N->children[1]) octant = 1;
+    else if (N_sub == N->children[2]) octant = 2;
+    else if (N_sub == N->children[3]) octant = 3;
+    else if (N_sub == N->children[4]) octant = 4;
+    else if (N_sub == N->children[5]) octant = 5;
+    else if (N_sub == N->children[6]) octant = 6;
+    else if (N_sub == N->children[7]) octant = 7;
+    VERIFY(octant < 8);
+    VERIFY(N_sub->_empty());
+    _node_destroy(N->children[octant]);
+
+    // Recurse
+    if (N->_empty()) _remove(N->parent, N);
 }
 
-void			ISpatial_DB::remove		(ISpatial* S)
+void ISpatial_DB::remove(ISpatial* S)
 {
-	cs.Enter			();
+    cs.Enter();
 #ifdef DEBUG
-	stat_remove.Begin	();
+    stat_remove.Begin();
 #endif
-	ISpatial_NODE* N	= S->spatial.node_ptr;
-	N->_remove			(S);
+    ISpatial_NODE* N = S->spatial.node_ptr;
+    N->_remove(S);
 
-	// Recurse
-	if (N->_empty())	_remove(N->parent,N);
+    // Recurse
+    if (N->_empty()) _remove(N->parent, N);
 
 #ifdef DEBUG
-	stat_remove.End		();
+    stat_remove.End();
 #endif
-	cs.Leave			();
+    cs.Leave();
 }
 
-void			ISpatial_DB::update		(u32 nodes/* =8 */)
+void ISpatial_DB::update(u32 nodes/* =8 */)
 {
 #ifdef DEBUG
-	if (0==m_root)	return;
-	cs.Enter		();
-	VERIFY			(verify());
-	cs.Leave		();
+    if (0 == m_root) return;
+    cs.Enter();
+    VERIFY(verify());
+    cs.Leave();
 #endif
 }
diff --git a/src/xrEngine/ISpatial.h b/src/xrEngine/ISpatial.h
index ce55c5137de..6f9c148e5c9 100644
--- a/src/xrEngine/ISpatial.h
+++ b/src/xrEngine/ISpatial.h
@@ -11,185 +11,186 @@
 /*
 Requirements:
 0. Generic
-	* O(1) insertion
-		- radius completely determines	"level"
-		- position completely detemines "node"
-	* O(1) removal
-	* 
+* O(1) insertion
+- radius completely determines "level"
+- position completely detemines "node"
+* O(1) removal
+*
 1. Rendering
-	* Should live inside spatial DB
-	* Should have at least "bounding-sphere" or "bounding-box"
-	* Should have pointer to "sector" it lives in
-	* Approximate traversal order relative to point ("camera")
+* Should live inside spatial DB
+* Should have at least "bounding-sphere" or "bounding-box"
+* Should have pointer to "sector" it lives in
+* Approximate traversal order relative to point ("camera")
 2. Spatial queries
-	* Should live inside spatial DB
-	* Should have at least "bounding-sphere" or "bounding-box"
+* Should live inside spatial DB
+* Should have at least "bounding-sphere" or "bounding-box"
 */
 
-const float						c_spatial_min	= 8.f;
+const float c_spatial_min = 8.f;
 //////////////////////////////////////////////////////////////////////////
 enum
 {
-	STYPE_RENDERABLE			= (1<<0),
-	STYPE_LIGHTSOURCE			= (1<<1),
-	STYPE_COLLIDEABLE			= (1<<2),
-	STYPE_VISIBLEFORAI			= (1<<3),
-	STYPE_REACTTOSOUND			= (1<<4),
-	STYPE_PHYSIC				= (1<<5),
-	STYPE_OBSTACLE				= (1<<6),
-	STYPE_SHAPE					= (1<<7),
-	STYPE_LIGHTSOURCEHEMI		= (1<<8),
-
-	STYPEFLAG_INVALIDSECTOR		= (1<<16)
+    STYPE_RENDERABLE = (1 << 0),
+    STYPE_LIGHTSOURCE = (1 << 1),
+    STYPE_COLLIDEABLE = (1 << 2),
+    STYPE_VISIBLEFORAI = (1 << 3),
+    STYPE_REACTTOSOUND = (1 << 4),
+    STYPE_PHYSIC = (1 << 5),
+    STYPE_OBSTACLE = (1 << 6),
+    STYPE_SHAPE = (1 << 7),
+    STYPE_LIGHTSOURCEHEMI = (1 << 8),
+
+    STYPEFLAG_INVALIDSECTOR = (1 << 16)
 };
 //////////////////////////////////////////////////////////////////////////
-// Comment: 
-//		ordinal objects			- renderable?, collideable?, visibleforAI?
-//		physical-decorations	- renderable, collideable
-//		lights					- lightsource
-//		particles(temp-objects)	- renderable
-//		glow					- renderable
-//		sound					- ???
+// Comment:
+// ordinal objects - renderable?, collideable?, visibleforAI?
+// physical-decorations - renderable, collideable
+// lights - lightsource
+// particles(temp-objects) - renderable
+// glow - renderable
+// sound - ???
 //////////////////////////////////////////////////////////////////////////
-class ENGINE_API				IRender_Sector;
-class ENGINE_API				ISpatial;
-class ENGINE_API				ISpatial_NODE;
-class ENGINE_API				ISpatial_DB;
+class ENGINE_API IRender_Sector;
+class ENGINE_API ISpatial;
+class ENGINE_API ISpatial_NODE;
+class ENGINE_API ISpatial_DB;
 
 //////////////////////////////////////////////////////////////////////////
 // Fast type conversion
-class ENGINE_API				CObject;
-class ENGINE_API				IRenderable;
-class ENGINE_API				IRender_Light;
+class ENGINE_API CObject;
+class ENGINE_API IRenderable;
+class ENGINE_API IRender_Light;
 namespace Feel { class ENGINE_API Sound; }
 
 //////////////////////////////////////////////////////////////////////////
-class ENGINE_API				ISpatial
+class ENGINE_API ISpatial
 {
 public:
-	struct	_spatial
-	{
-		u32						type;
-		Fsphere					sphere;
-		Fvector					node_center;	// Cached node center for TBV optimization
-		float					node_radius;	// Cached node bounds for TBV optimization
-		ISpatial_NODE*			node_ptr;		// Cached parent node for "empty-members" optimization
-		IRender_Sector*			sector;
-		ISpatial_DB*			space;			// allow different spaces
-
-		_spatial() : type(0)	{}				// safe way to enhure type is zero before any contstructors takes place
-	}							spatial;
+    struct _spatial
+    {
+        u32 type;
+        Fsphere sphere;
+        Fvector node_center; // Cached node center for TBV optimization
+        float node_radius; // Cached node bounds for TBV optimization
+        ISpatial_NODE* node_ptr; // Cached parent node for "empty-members" optimization
+        IRender_Sector* sector;
+        ISpatial_DB* space; // allow different spaces
+
+        _spatial() : type(0) {} // safe way to enhure type is zero before any contstructors takes place
+    } spatial;
 public:
-	BOOL						spatial_inside		()			;
-				void			spatial_updatesector_internal()	;
+    BOOL spatial_inside();
+    void spatial_updatesector_internal();
 public:
-	virtual		void			spatial_register	()	;
-	virtual		void			spatial_unregister	()	;
-	virtual		void			spatial_move		()	;
-	virtual		Fvector			spatial_sector_point()	{ return spatial.sphere.P; }
-	ICF			void			spatial_updatesector()	{
-		if (0== (spatial.type&STYPEFLAG_INVALIDSECTOR))	return;
-		spatial_updatesector_internal				()	;
-	};
-
-	virtual		CObject*		dcast_CObject		()	{ return 0;	}
-	virtual		Feel::Sound*	dcast_FeelSound		()	{ return 0;	}
-	virtual		IRenderable*	dcast_Renderable	()	{ return 0;	}
-	virtual		IRender_Light*	dcast_Light			()	{ return 0; }
-
-				ISpatial		(ISpatial_DB* space	);
-	virtual		~ISpatial		();
+    virtual void spatial_register();
+    virtual void spatial_unregister();
+    virtual void spatial_move();
+    virtual Fvector spatial_sector_point() { return spatial.sphere.P; }
+    ICF void spatial_updatesector()
+    {
+        if (0 == (spatial.type&STYPEFLAG_INVALIDSECTOR)) return;
+        spatial_updatesector_internal();
+    };
+
+    virtual CObject* dcast_CObject() { return 0; }
+    virtual Feel::Sound* dcast_FeelSound() { return 0; }
+    virtual IRenderable* dcast_Renderable() { return 0; }
+    virtual IRender_Light* dcast_Light() { return 0; }
+
+    ISpatial(ISpatial_DB* space);
+    virtual ~ISpatial();
 };
 
 //////////////////////////////////////////////////////////////////////////
-class ENGINE_API				ISpatial_NODE
+class ENGINE_API ISpatial_NODE
 {
 public:
-	typedef	_W64 unsigned		ptrt;
+    typedef _W64 unsigned ptrt;
 public:
-	ISpatial_NODE*				parent;					// parent node for "empty-members" optimization
-	ISpatial_NODE*				children		[8];	// children nodes
-	xr_vector		items;					// own items
+    ISpatial_NODE* parent; // parent node for "empty-members" optimization
+    ISpatial_NODE* children[8]; // children nodes
+    xr_vector items; // own items
 public:
-	void						_init			(ISpatial_NODE* _parent);
-	void						_remove			(ISpatial*		_S);
-	void						_insert			(ISpatial*		_S);
-	BOOL						_empty			()						
-	{
-		return items.empty() && (
-			0==(
-				ptrt(children[0])|ptrt(children[1])|
-				ptrt(children[2])|ptrt(children[3])|
-				ptrt(children[4])|ptrt(children[5])|
-				ptrt(children[6])|ptrt(children[7])
-				)
-			);	
-	}
+    void _init(ISpatial_NODE* _parent);
+    void _remove(ISpatial* _S);
+    void _insert(ISpatial* _S);
+    BOOL _empty()
+    {
+        return items.empty() && (
+            0 == (
+            ptrt(children[0]) | ptrt(children[1]) |
+            ptrt(children[2]) | ptrt(children[3]) |
+            ptrt(children[4]) | ptrt(children[5]) |
+            ptrt(children[6]) | ptrt(children[7])
+            )
+            );
+    }
 };
 
 //////////////////////////////////////////////////////////////////////////
-class ENGINE_API					ISpatial_DB
+class ENGINE_API ISpatial_DB
 {
 private:
-	xrCriticalSection				cs;
-	poolSS		allocator;
-	xr_vector		allocator_pool;
-	ISpatial*						rt_insert_object;
+    xrCriticalSection cs;
+    poolSS allocator;
+    xr_vector allocator_pool;
+    ISpatial* rt_insert_object;
 public:
-	ISpatial_NODE*					m_root;
-	Fvector							m_center;
-	float							m_bounds;
-	xr_vector*			q_result;
-	u32								stat_nodes;
-	u32								stat_objects;
-	CStatTimer						stat_insert;
-	CStatTimer						stat_remove;
+    ISpatial_NODE* m_root;
+    Fvector m_center;
+    float m_bounds;
+    xr_vector* q_result;
+    u32 stat_nodes;
+    u32 stat_objects;
+    CStatTimer stat_insert;
+    CStatTimer stat_remove;
 private:
-	IC u32							_octant			(u32 x, u32 y, u32 z)			{	return z*4 + y*2 + x;	}
-	IC u32							_octant			(Fvector& base, Fvector& rel)
-	{
-		u32 o	= 0;
-		if (rel.x > base.x) o+=1;
-		if (rel.y > base.y) o+=2;
-		if (rel.z > base.z) o+=4;
-		return	o;
-	}
-
-	ISpatial_NODE*					_node_create	();
-	void 							_node_destroy	(ISpatial_NODE* &P);
-
-	void							_insert			(ISpatial_NODE* N, Fvector& n_center, float n_radius);
-	void							_remove			(ISpatial_NODE* N, ISpatial_NODE* N_sub);
+    IC u32 _octant(u32 x, u32 y, u32 z) { return z * 4 + y * 2 + x; }
+    IC u32 _octant(Fvector& base, Fvector& rel)
+    {
+        u32 o = 0;
+        if (rel.x > base.x) o += 1;
+        if (rel.y > base.y) o += 2;
+        if (rel.z > base.z) o += 4;
+        return o;
+    }
+
+    ISpatial_NODE* _node_create();
+    void _node_destroy(ISpatial_NODE*& P);
+
+    void _insert(ISpatial_NODE* N, Fvector& n_center, float n_radius);
+    void _remove(ISpatial_NODE* N, ISpatial_NODE* N_sub);
 public:
-	ISpatial_DB();
-	~ISpatial_DB();
+    ISpatial_DB();
+    ~ISpatial_DB();
 
-	// managing
-	void							initialize		(Fbox& BB);
-	//void							destroy			();
-	void							insert			(ISpatial* S);
-	void							remove			(ISpatial* S);
-	void							update			(u32 nodes=8);
-	BOOL							verify			();
+    // managing
+    void initialize(Fbox& BB);
+    //void destroy ();
+    void insert(ISpatial* S);
+    void remove(ISpatial* S);
+    void update(u32 nodes = 8);
+    BOOL verify();
 
 public:
-	enum
-	{
-		O_ONLYFIRST		= (1<<0),
-		O_ONLYNEAREST	= (1<<1),
-		O_ORDERED		= (1<<2),
-		O_force_u32		= u32(-1)
-	};
-
-	// query
-	void							q_ray			(xr_vector& R, u32 _o, u32 _mask_and, const Fvector&		_start,  const Fvector&	_dir, float _range);
-	void							q_box			(xr_vector& R, u32 _o, u32 _mask_or,  const Fvector&		_center, const Fvector& _size);
-	void							q_sphere		(xr_vector& R, u32 _o, u32 _mask_or,  const Fvector&		_center, const float _radius);
-	void							q_frustum		(xr_vector& R, u32 _o, u32 _mask_or,  const CFrustum&	_frustum);
+    enum
+    {
+        O_ONLYFIRST = (1 << 0),
+        O_ONLYNEAREST = (1 << 1),
+        O_ORDERED = (1 << 2),
+        O_force_u32 = u32(-1)
+    };
+
+    // query
+    void q_ray(xr_vector& R, u32 _o, u32 _mask_and, const Fvector& _start, const Fvector& _dir, float _range);
+    void q_box(xr_vector& R, u32 _o, u32 _mask_or, const Fvector& _center, const Fvector& _size);
+    void q_sphere(xr_vector& R, u32 _o, u32 _mask_or, const Fvector& _center, const float _radius);
+    void q_frustum(xr_vector& R, u32 _o, u32 _mask_or, const CFrustum& _frustum);
 };
 
-ENGINE_API extern ISpatial_DB*		g_SpatialSpace			;
-ENGINE_API extern ISpatial_DB*		g_SpatialSpacePhysic	;
+ENGINE_API extern ISpatial_DB* g_SpatialSpace;
+ENGINE_API extern ISpatial_DB* g_SpatialSpacePhysic;
 
 #pragma pack(pop)
 
diff --git a/src/xrEngine/ISpatial_q_box.cpp b/src/xrEngine/ISpatial_q_box.cpp
index 51b131ae9c8..f7e36e559f9 100644
--- a/src/xrEngine/ISpatial_q_box.cpp
+++ b/src/xrEngine/ISpatial_q_box.cpp
@@ -1,74 +1,77 @@
 #include "stdafx.h"
 #include "ISpatial.h"
 
-extern Fvector	c_spatial_offset[8];
+extern Fvector c_spatial_offset[8];
 
 template 
-class	walker
+class walker
 {
 public:
-	u32				mask;
-	Fvector			center;
-	Fvector			size;
-	Fbox			box;
-	ISpatial_DB*	space;
+    u32 mask;
+    Fvector center;
+    Fvector size;
+    Fbox box;
+    ISpatial_DB* space;
 public:
-	walker					(ISpatial_DB*	_space, u32 _mask, const Fvector& _center, const Fvector&	_size)
-	{
-		mask	= _mask;
-		center	= _center;
-		size	= _size;
-		box.setb(center,size);
-		space	= _space;
-	}
-	void		walk		(ISpatial_NODE* N, Fvector& n_C, float n_R)
-	{
-		// box
-		float	n_vR	=		2*n_R;
-		Fbox	BB;		BB.set	(n_C.x-n_vR, n_C.y-n_vR, n_C.z-n_vR, n_C.x+n_vR, n_C.y+n_vR, n_C.z+n_vR);
-		if		(!BB.intersect(box))			return;
+    walker(ISpatial_DB* _space, u32 _mask, const Fvector& _center, const Fvector& _size)
+    {
+        mask = _mask;
+        center = _center;
+        size = _size;
+        box.setb(center, size);
+        space = _space;
+    }
+    void walk(ISpatial_NODE* N, Fvector& n_C, float n_R)
+    {
+        // box
+        float n_vR = 2 * n_R;
+        Fbox BB;
+        BB.set(n_C.x - n_vR, n_C.y - n_vR, n_C.z - n_vR, n_C.x + n_vR, n_C.y + n_vR, n_C.z + n_vR);
+        if (!BB.intersect(box)) return;
 
-		// test items
-		xr_vector::iterator _it	=	N->items.begin	();
-		xr_vector::iterator _end	=	N->items.end	();
-		for (; _it!=_end; _it++)
-		{
-			ISpatial*		S	= *_it;
-			if (0==(S->spatial.type&mask))	continue;
+        // test items
+        xr_vector::iterator _it = N->items.begin();
+        xr_vector::iterator _end = N->items.end();
+        for (; _it != _end; _it++)
+        {
+            ISpatial* S = *_it;
+            if (0 == (S->spatial.type&mask)) continue;
 
-			Fvector&		sC		= S->spatial.sphere.P;
-			float			sR		= S->spatial.sphere.R;
-			Fbox			sB;		sB.set	(sC.x-sR, sC.y-sR, sC.z-sR, sC.x+sR, sC.y+sR, sC.z+sR);
-			if (!sB.intersect(box))	continue;
+            Fvector& sC = S->spatial.sphere.P;
+            float sR = S->spatial.sphere.R;
+            Fbox sB;
+            sB.set(sC.x - sR, sC.y - sR, sC.z - sR, sC.x + sR, sC.y + sR, sC.z + sR);
+            if (!sB.intersect(box)) continue;
 
-			space->q_result->push_back	(S);
-			if (b_first)			return;
-		}
+            space->q_result->push_back(S);
+            if (b_first) return;
+        }
 
-		// recurse
-		float	c_R		= n_R/2;
-		for (u32 octant=0; octant<8; octant++)
-		{
-			if (0==N->children[octant])	continue;
-			Fvector		c_C;			c_C.mad	(n_C,c_spatial_offset[octant],c_R);
-			walk						(N->children[octant],c_C,c_R);
-			if (b_first && !space->q_result->empty())	return;
-		}
-	}
+        // recurse
+        float c_R = n_R / 2;
+        for (u32 octant = 0; octant < 8; octant++)
+        {
+            if (0 == N->children[octant]) continue;
+            Fvector c_C;
+            c_C.mad(n_C, c_spatial_offset[octant], c_R);
+            walk(N->children[octant], c_C, c_R);
+            if (b_first && !space->q_result->empty()) return;
+        }
+    }
 };
 
-void	ISpatial_DB::q_box			(xr_vector& R, u32 _o, u32 _mask, const Fvector& _center, const Fvector& _size)
+void ISpatial_DB::q_box(xr_vector& R, u32 _o, u32 _mask, const Fvector& _center, const Fvector& _size)
 {
-	cs.Enter			();
-	q_result			= &R;
-	q_result->clear_not_free		();
-	if (_o & O_ONLYFIRST)			{ walker	W(this,_mask,_center,_size);	W.walk(m_root,m_center,m_bounds); } 
-	else							{ walker	W(this,_mask,_center,_size);	W.walk(m_root,m_center,m_bounds); } 
-	cs.Leave			();
+    cs.Enter();
+    q_result = &R;
+    q_result->clear_not_free();
+    if (_o & O_ONLYFIRST) { walker W(this, _mask, _center, _size); W.walk(m_root, m_center, m_bounds); }
+    else { walker W(this, _mask, _center, _size); W.walk(m_root, m_center, m_bounds); }
+    cs.Leave();
 }
 
-void	ISpatial_DB::q_sphere		(xr_vector& R, u32 _o, u32 _mask, const Fvector& _center, const float _radius)
+void ISpatial_DB::q_sphere(xr_vector& R, u32 _o, u32 _mask, const Fvector& _center, const float _radius)
 {
-	Fvector			_size			= {_radius,_radius,_radius};
-	q_box							(R,_o,_mask,_center,_size);
+    Fvector _size = {_radius, _radius, _radius};
+    q_box(R, _o, _mask, _center, _size);
 }
diff --git a/src/xrEngine/ISpatial_q_frustum.cpp b/src/xrEngine/ISpatial_q_frustum.cpp
index 54474ae4f30..ac02f591aa8 100644
--- a/src/xrEngine/ISpatial_q_frustum.cpp
+++ b/src/xrEngine/ISpatial_q_frustum.cpp
@@ -2,60 +2,63 @@
 #include "ISpatial.h"
 #include "frustum.h"
 
-extern Fvector	c_spatial_offset[8];
+extern Fvector c_spatial_offset[8];
 
-class	walker
+class walker
 {
 public:
-	u32				mask;
-	CFrustum*		F;
-	ISpatial_DB*	space;
+    u32 mask;
+    CFrustum* F;
+    ISpatial_DB* space;
 public:
-	walker					(ISpatial_DB*	_space, u32 _mask, const CFrustum* _F)
-	{
-		mask	= _mask;
-		F		= (CFrustum*)_F;
-		space	= _space;
-	}
-	void		walk		(ISpatial_NODE* N, Fvector& n_C, float n_R, u32 fmask)
-	{
-		// box
-		float	n_vR	=		2*n_R;
-		Fbox	BB;		BB.set	(n_C.x-n_vR, n_C.y-n_vR, n_C.z-n_vR, n_C.x+n_vR, n_C.y+n_vR, n_C.z+n_vR);
-		if		(fcvNone==F->testAABB(BB.data(),fmask))	return;
+    walker(ISpatial_DB* _space, u32 _mask, const CFrustum* _F)
+    {
+        mask = _mask;
+        F = (CFrustum*)_F;
+        space = _space;
+    }
+    void walk(ISpatial_NODE* N, Fvector& n_C, float n_R, u32 fmask)
+    {
+        // box
+        float n_vR = 2 * n_R;
+        Fbox BB;
+        BB.set(n_C.x - n_vR, n_C.y - n_vR, n_C.z - n_vR, n_C.x + n_vR, n_C.y + n_vR, n_C.z + n_vR);
+        if (fcvNone == F->testAABB(BB.data(), fmask)) return;
 
-		// test items
-		xr_vector::iterator _it	=	N->items.begin	();
-		xr_vector::iterator _end	=	N->items.end	();
-		for (; _it!=_end; _it++)
-		{
-			ISpatial*		S	= *_it;
-			if (0==(S->spatial.type&mask))	continue;
+        // test items
+        xr_vector::iterator _it = N->items.begin();
+        xr_vector::iterator _end = N->items.end();
+        for (; _it != _end; _it++)
+        {
+            ISpatial* S = *_it;
+            if (0 == (S->spatial.type&mask)) continue;
 
-			Fvector&		sC		= S->spatial.sphere.P;
-			float			sR		= S->spatial.sphere.R;
-			u32				tmask	= fmask;
-			if (fcvNone==F->testSphere(sC,sR,tmask))	continue;
+            Fvector& sC = S->spatial.sphere.P;
+            float sR = S->spatial.sphere.R;
+            u32 tmask = fmask;
+            if (fcvNone == F->testSphere(sC, sR, tmask)) continue;
 
-			space->q_result->push_back	(S);
-		}
+            space->q_result->push_back(S);
+        }
 
-		// recurse
-		float	c_R		= n_R/2;
-		for (u32 octant=0; octant<8; octant++)
-		{
-			if (0==N->children[octant])	continue;
-			Fvector		c_C;			c_C.mad	(n_C,c_spatial_offset[octant],c_R);
-			walk						(N->children[octant],c_C,c_R,fmask);
-		}
-	}
+        // recurse
+        float c_R = n_R / 2;
+        for (u32 octant = 0; octant < 8; octant++)
+        {
+            if (0 == N->children[octant]) continue;
+            Fvector c_C;
+            c_C.mad(n_C, c_spatial_offset[octant], c_R);
+            walk(N->children[octant], c_C, c_R, fmask);
+        }
+    }
 };
 
-void	ISpatial_DB::q_frustum		(xr_vector& R, u32 _o, u32 _mask, const CFrustum& _frustum)	
+void ISpatial_DB::q_frustum(xr_vector& R, u32 _o, u32 _mask, const CFrustum& _frustum)
 {
-	cs.Enter			();
-	q_result			= &R;
-	q_result->clear_not_free();
-	walker				W(this,_mask,&_frustum); W.walk(m_root,m_center,m_bounds,_frustum.getMask()); 
-	cs.Leave			();
+    cs.Enter();
+    q_result = &R;
+    q_result->clear_not_free();
+    walker W(this, _mask, &_frustum);
+    W.walk(m_root, m_center, m_bounds, _frustum.getMask());
+    cs.Leave();
 }
diff --git a/src/xrEngine/ISpatial_q_ray.cpp b/src/xrEngine/ISpatial_q_ray.cpp
index 9e1205361ed..8caef9c11ba 100644
--- a/src/xrEngine/ISpatial_q_ray.cpp
+++ b/src/xrEngine/ISpatial_q_ray.cpp
@@ -7,287 +7,330 @@
 
 // can you say "barebone"?
 #ifndef _MM_ALIGN16
-#	define _MM_ALIGN16		__declspec(align(16))
+# define _MM_ALIGN16 __declspec(align(16))
 #endif // _MM_ALIGN16
 
-struct	_MM_ALIGN16		vec_t	: public Fvector3	{ 
-	float		pad; 
+struct _MM_ALIGN16 vec_t : public Fvector3
+{
+    float pad;
 };
-vec_t	vec_c	( float _x, float _y, float _z)	{ vec_t v; v.x=_x;v.y=_y;v.z=_z;v.pad=0; return v; }
-struct _MM_ALIGN16		aabb_t	{ 
-	vec_t		min;
-	vec_t		max;
+vec_t vec_c(float _x, float _y, float _z) { vec_t v; v.x = _x; v.y = _y; v.z = _z; v.pad = 0; return v; }
+struct _MM_ALIGN16 aabb_t
+{
+    vec_t min;
+    vec_t max;
 };
-struct _MM_ALIGN16		ray_t	{
-	vec_t		pos;
-	vec_t		inv_dir;
-	vec_t		fwd_dir;
+struct _MM_ALIGN16 ray_t
+{
+    vec_t pos;
+    vec_t inv_dir;
+    vec_t fwd_dir;
 };
-struct ray_segment_t {
-	float		t_near,t_far;
+struct ray_segment_t
+{
+    float t_near, t_far;
 };
 
-ICF u32&	uf			(float &x)	{ return (u32&)x; }
-ICF BOOL	isect_fpu	(const Fvector& min, const Fvector& max, const ray_t &ray, Fvector& coord)
+ICF u32& uf(float& x) { return (u32&)x; }
+ICF BOOL isect_fpu(const Fvector& min, const Fvector& max, const ray_t& ray, Fvector& coord)
 {
-	Fvector				MaxT;
-	MaxT.x=MaxT.y=MaxT.z=-1.0f;
-	BOOL Inside			= TRUE;
+    Fvector MaxT;
+    MaxT.x = MaxT.y = MaxT.z = -1.0f;
+    BOOL Inside = TRUE;
 
-	// Find candidate planes.
-	if(ray.pos[0] < min[0]) {
-		coord[0]	= min[0];
-		Inside		= FALSE;
-		if(uf(ray.inv_dir[0]))	MaxT[0] = (min[0] - ray.pos[0]) * ray.inv_dir[0]; // Calculate T distances to candidate planes
-	} else if(ray.pos[0] > max[0]) {
-		coord[0]	= max[0];
-		Inside		= FALSE;
-		if(uf(ray.inv_dir[0]))	MaxT[0] = (max[0] - ray.pos[0]) * ray.inv_dir[0]; // Calculate T distances to candidate planes
-	}
-	if(ray.pos[1] < min[1]) {
-		coord[1]	= min[1];
-		Inside		= FALSE;
-		if(uf(ray.inv_dir[1]))	MaxT[1] = (min[1] - ray.pos[1]) * ray.inv_dir[1]; // Calculate T distances to candidate planes
-	} else if(ray.pos[1] > max[1]) {
-		coord[1]	= max[1];
-		Inside		= FALSE;
-		if(uf(ray.inv_dir[1]))	MaxT[1] = (max[1] - ray.pos[1]) * ray.inv_dir[1]; // Calculate T distances to candidate planes
-	}
-	if(ray.pos[2] < min[2]) {
-		coord[2]	= min[2];
-		Inside		= FALSE;
-		if(uf(ray.inv_dir[2]))	MaxT[2] = (min[2] - ray.pos[2]) * ray.inv_dir[2]; // Calculate T distances to candidate planes
-	} else if(ray.pos[2] > max[2]) {
-		coord[2]	= max[2];
-		Inside		= FALSE;
-		if(uf(ray.inv_dir[2]))	MaxT[2] = (max[2] - ray.pos[2]) * ray.inv_dir[2]; // Calculate T distances to candidate planes
-	}
+    // Find candidate planes.
+    if (ray.pos[0] < min[0])
+    {
+        coord[0] = min[0];
+        Inside = FALSE;
+        if (uf(ray.inv_dir[0])) MaxT[0] = (min[0] - ray.pos[0]) * ray.inv_dir[0]; // Calculate T distances to candidate planes
+    }
+    else if (ray.pos[0] > max[0])
+    {
+        coord[0] = max[0];
+        Inside = FALSE;
+        if (uf(ray.inv_dir[0])) MaxT[0] = (max[0] - ray.pos[0]) * ray.inv_dir[0]; // Calculate T distances to candidate planes
+    }
+    if (ray.pos[1] < min[1])
+    {
+        coord[1] = min[1];
+        Inside = FALSE;
+        if (uf(ray.inv_dir[1])) MaxT[1] = (min[1] - ray.pos[1]) * ray.inv_dir[1]; // Calculate T distances to candidate planes
+    }
+    else if (ray.pos[1] > max[1])
+    {
+        coord[1] = max[1];
+        Inside = FALSE;
+        if (uf(ray.inv_dir[1])) MaxT[1] = (max[1] - ray.pos[1]) * ray.inv_dir[1]; // Calculate T distances to candidate planes
+    }
+    if (ray.pos[2] < min[2])
+    {
+        coord[2] = min[2];
+        Inside = FALSE;
+        if (uf(ray.inv_dir[2])) MaxT[2] = (min[2] - ray.pos[2]) * ray.inv_dir[2]; // Calculate T distances to candidate planes
+    }
+    else if (ray.pos[2] > max[2])
+    {
+        coord[2] = max[2];
+        Inside = FALSE;
+        if (uf(ray.inv_dir[2])) MaxT[2] = (max[2] - ray.pos[2]) * ray.inv_dir[2]; // Calculate T distances to candidate planes
+    }
 
-	// Ray ray.pos inside bounding box
-	if(Inside)		{
-		coord		= ray.pos;
-		return		true;
-	}
+    // Ray ray.pos inside bounding box
+    if (Inside)
+    {
+        coord = ray.pos;
+        return true;
+    }
 
-	// Get largest of the maxT's for final choice of intersection
-	u32 WhichPlane = 0;
-	if	(MaxT[1] > MaxT[0])				WhichPlane = 1;
-	if	(MaxT[2] > MaxT[WhichPlane])	WhichPlane = 2;
+    // Get largest of the maxT's for final choice of intersection
+    u32 WhichPlane = 0;
+    if (MaxT[1] > MaxT[0]) WhichPlane = 1;
+    if (MaxT[2] > MaxT[WhichPlane]) WhichPlane = 2;
 
-	// Check final candidate actually inside box (if max < 0)
-	if(uf(MaxT[WhichPlane])&0x80000000) return false;
+    // Check final candidate actually inside box (if max < 0)
+    if (uf(MaxT[WhichPlane]) & 0x80000000) return false;
 
-	if  (0==WhichPlane)	{	// 1 & 2
-		coord[1] = ray.pos[1] + MaxT[0] * ray.fwd_dir[1];
-		if((coord[1] < min[1]) || (coord[1] > max[1]))	return false;
-		coord[2] = ray.pos[2] + MaxT[0] * ray.fwd_dir[2];
-		if((coord[2] < min[2]) || (coord[2] > max[2]))	return false;
-		return true;
-	}
-	if (1==WhichPlane)	{	// 0 & 2
-		coord[0] = ray.pos[0] + MaxT[1] * ray.fwd_dir[0];
-		if((coord[0] < min[0]) || (coord[0] > max[0]))	return false;
-		coord[2] = ray.pos[2] + MaxT[1] * ray.fwd_dir[2];
-		if((coord[2] < min[2]) || (coord[2] > max[2]))	return false;
-		return true;
-	}
-	if (2==WhichPlane)	{	// 0 & 1
-		coord[0] = ray.pos[0] + MaxT[2] * ray.fwd_dir[0];
-		if((coord[0] < min[0]) || (coord[0] > max[0]))	return false;
-		coord[1] = ray.pos[1] + MaxT[2] * ray.fwd_dir[1];
-		if((coord[1] < min[1]) || (coord[1] > max[1]))	return false;
-		return true;
-	}
-	return false;
+    if (0 == WhichPlane)   // 1 & 2
+    {
+        coord[1] = ray.pos[1] + MaxT[0] * ray.fwd_dir[1];
+        if ((coord[1] < min[1]) || (coord[1] > max[1])) return false;
+        coord[2] = ray.pos[2] + MaxT[0] * ray.fwd_dir[2];
+        if ((coord[2] < min[2]) || (coord[2] > max[2])) return false;
+        return true;
+    }
+    if (1 == WhichPlane)   // 0 & 2
+    {
+        coord[0] = ray.pos[0] + MaxT[1] * ray.fwd_dir[0];
+        if ((coord[0] < min[0]) || (coord[0] > max[0])) return false;
+        coord[2] = ray.pos[2] + MaxT[1] * ray.fwd_dir[2];
+        if ((coord[2] < min[2]) || (coord[2] > max[2])) return false;
+        return true;
+    }
+    if (2 == WhichPlane)   // 0 & 1
+    {
+        coord[0] = ray.pos[0] + MaxT[2] * ray.fwd_dir[0];
+        if ((coord[0] < min[0]) || (coord[0] > max[0])) return false;
+        coord[1] = ray.pos[1] + MaxT[2] * ray.fwd_dir[1];
+        if ((coord[1] < min[1]) || (coord[1] > max[1])) return false;
+        return true;
+    }
+    return false;
 }
 
 // turn those verbose intrinsics into something readable.
-#define loadps(mem)			_mm_load_ps((const float * const)(mem))
-#define storess(ss,mem)		_mm_store_ss((float * const)(mem),(ss))
-#define minss				_mm_min_ss
-#define maxss				_mm_max_ss
-#define minps				_mm_min_ps
-#define maxps				_mm_max_ps
-#define mulps				_mm_mul_ps
-#define subps				_mm_sub_ps
-#define rotatelps(ps)		_mm_shuffle_ps((ps),(ps), 0x39)	// a,b,c,d -> b,c,d,a
-#define muxhps(low,high)	_mm_movehl_ps((low),(high))		// low{a,b,c,d}|high{e,f,g,h} = {c,d,g,h}
+#define loadps(mem) _mm_load_ps((const float * const)(mem))
+#define storess(ss,mem) _mm_store_ss((float * const)(mem),(ss))
+#define minss _mm_min_ss
+#define maxss _mm_max_ss
+#define minps _mm_min_ps
+#define maxps _mm_max_ps
+#define mulps _mm_mul_ps
+#define subps _mm_sub_ps
+#define rotatelps(ps) _mm_shuffle_ps((ps),(ps), 0x39) // a,b,c,d -> b,c,d,a
+#define muxhps(low,high) _mm_movehl_ps((low),(high)) // low{a,b,c,d}|high{e,f,g,h} = {c,d,g,h}
 
 
-static const float flt_plus_inf = -logf(0);	// let's keep C and C++ compilers happy.
+static const float flt_plus_inf = -logf(0); // let's keep C and C++ compilers happy.
 static const float _MM_ALIGN16
-ps_cst_plus_inf	[4]	=	{  flt_plus_inf,  flt_plus_inf,  flt_plus_inf,  flt_plus_inf },
-ps_cst_minus_inf[4]	=	{ -flt_plus_inf, -flt_plus_inf, -flt_plus_inf, -flt_plus_inf };
+ps_cst_plus_inf[4] = {flt_plus_inf, flt_plus_inf, flt_plus_inf, flt_plus_inf},
+ps_cst_minus_inf[4] = {-flt_plus_inf, -flt_plus_inf, -flt_plus_inf, -flt_plus_inf};
 
-ICF BOOL isect_sse			(const aabb_t &box, const ray_t &ray, float &dist)	{
-	// you may already have those values hanging around somewhere
-	const __m128
-		plus_inf	= loadps(ps_cst_plus_inf),
-		minus_inf	= loadps(ps_cst_minus_inf);
+ICF BOOL isect_sse(const aabb_t& box, const ray_t& ray, float& dist)
+{
+    // you may already have those values hanging around somewhere
+    const __m128
+        plus_inf = loadps(ps_cst_plus_inf),
+        minus_inf = loadps(ps_cst_minus_inf);
 
-	// use whatever's apropriate to load.
-	const __m128
-		box_min		= loadps(&box.min),
-		box_max		= loadps(&box.max),
-		pos			= loadps(&ray.pos),
-		inv_dir		= loadps(&ray.inv_dir);
+    // use whatever's apropriate to load.
+    const __m128
+        box_min = loadps(&box.min),
+        box_max = loadps(&box.max),
+        pos = loadps(&ray.pos),
+        inv_dir = loadps(&ray.inv_dir);
 
-	// use a div if inverted directions aren't available
-	const __m128 l1 = mulps(subps(box_min, pos), inv_dir);
-	const __m128 l2 = mulps(subps(box_max, pos), inv_dir);
+    // use a div if inverted directions aren't available
+    const __m128 l1 = mulps(subps(box_min, pos), inv_dir);
+    const __m128 l2 = mulps(subps(box_max, pos), inv_dir);
 
-	// the order we use for those min/max is vital to filter out
-	// NaNs that happens when an inv_dir is +/- inf and
-	// (box_min - pos) is 0. inf * 0 = NaN
-	const __m128 filtered_l1a = minps(l1, plus_inf);
-	const __m128 filtered_l2a = minps(l2, plus_inf);
+    // the order we use for those min/max is vital to filter out
+    // NaNs that happens when an inv_dir is +/- inf and
+    // (box_min - pos) is 0. inf * 0 = NaN
+    const __m128 filtered_l1a = minps(l1, plus_inf);
+    const __m128 filtered_l2a = minps(l2, plus_inf);
 
-	const __m128 filtered_l1b = maxps(l1, minus_inf);
-	const __m128 filtered_l2b = maxps(l2, minus_inf);
+    const __m128 filtered_l1b = maxps(l1, minus_inf);
+    const __m128 filtered_l2b = maxps(l2, minus_inf);
 
-	// now that we're back on our feet, test those slabs.
-	__m128 lmax = maxps(filtered_l1a, filtered_l2a);
-	__m128 lmin = minps(filtered_l1b, filtered_l2b);
+    // now that we're back on our feet, test those slabs.
+    __m128 lmax = maxps(filtered_l1a, filtered_l2a);
+    __m128 lmin = minps(filtered_l1b, filtered_l2b);
 
-	// unfold back. try to hide the latency of the shufps & co.
-	const __m128 lmax0 = rotatelps(lmax);
-	const __m128 lmin0 = rotatelps(lmin);
-	lmax = minss(lmax, lmax0);
-	lmin = maxss(lmin, lmin0);
+    // unfold back. try to hide the latency of the shufps & co.
+    const __m128 lmax0 = rotatelps(lmax);
+    const __m128 lmin0 = rotatelps(lmin);
+    lmax = minss(lmax, lmax0);
+    lmin = maxss(lmin, lmin0);
 
-	const __m128 lmax1 = muxhps(lmax,lmax);
-	const __m128 lmin1 = muxhps(lmin,lmin);
-	lmax = minss(lmax, lmax1);
-	lmin = maxss(lmin, lmin1);
+    const __m128 lmax1 = muxhps(lmax, lmax);
+    const __m128 lmin1 = muxhps(lmin, lmin);
+    lmax = minss(lmax, lmax1);
+    lmin = maxss(lmin, lmin1);
 
-	const BOOL ret = _mm_comige_ss(lmax, _mm_setzero_ps()) & _mm_comige_ss(lmax,lmin);
+    const BOOL ret = _mm_comige_ss(lmax, _mm_setzero_ps()) & _mm_comige_ss(lmax, lmin);
 
-	storess		(lmin, &dist);
-	//storess	(lmax, &rs.t_far);
+    storess(lmin, &dist);
+    //storess (lmax, &rs.t_far);
 
-	return  ret;
+    return ret;
 }
 
-extern Fvector	c_spatial_offset[8];
+extern Fvector c_spatial_offset[8];
 
 template 
-class	_MM_ALIGN16			walker
+class _MM_ALIGN16 walker
 {
 public:
-	ray_t			ray;
-	u32				mask;
-	float			range;
-	float			range2;
-	ISpatial_DB*	space;
+    ray_t ray;
+    u32 mask;
+    float range;
+    float range2;
+    ISpatial_DB* space;
 public:
-	walker					(ISpatial_DB*	_space, u32 _mask, const Fvector& _start, const Fvector&	_dir, float _range)
-	{
-		mask			= _mask;
-		ray.pos.set		(_start);
-		ray.inv_dir.set	(1.f,1.f,1.f).div(_dir);
-		ray.fwd_dir.set (_dir);
-		if (!b_use_sse)	{
-			// for FPU - zero out inf
-			if (_abs(_dir.x)>flt_eps){}	else ray.inv_dir.x=0;
-			if (_abs(_dir.y)>flt_eps){}	else ray.inv_dir.y=0;
-			if (_abs(_dir.z)>flt_eps){}	else ray.inv_dir.z=0;
-		}
-		range	= _range;
-		range2	= _range*_range;
-		space	= _space;
-	}
-	// fpu
-	ICF BOOL		_box_fpu	(const Fvector& n_C, const float n_R, Fvector& coord)
-	{
-		// box
-		float		n_vR	=		2*n_R;
-		Fbox		BB;		BB.set	(n_C.x-n_vR, n_C.y-n_vR, n_C.z-n_vR, n_C.x+n_vR, n_C.y+n_vR, n_C.z+n_vR);
-		return 		isect_fpu		(BB.min,BB.max,ray,coord);
-	}
-	// sse
-	ICF BOOL		_box_sse	(const Fvector& n_C, const float n_R, float&  dist )
-	{
-		aabb_t		box;
-		float		n_vR	=		2*n_R;
-		box.min.set	(n_C.x-n_vR, n_C.y-n_vR, n_C.z-n_vR);	box.min.pad = 0;
-		box.max.set	(n_C.x+n_vR, n_C.y+n_vR, n_C.z+n_vR);	box.max.pad = 0;
-		return 		isect_sse		(box,ray,dist);
-	}
-	void			walk		(ISpatial_NODE* N, Fvector& n_C, float n_R)
-	{
-		// Actual ray/aabb test
-		if (b_use_sse)		{
-			// use SSE
-			float		d;
-			if (!_box_sse(n_C,n_R,d))				return;
-			if (d>range)							return;
-		} else {
-			// use FPU
-			Fvector		P;
-			if (!_box_fpu(n_C,n_R,P))				return;
-			if (P.distance_to_sqr(ray.pos)>range2)	return;
-		}
+    walker(ISpatial_DB* _space, u32 _mask, const Fvector& _start, const Fvector& _dir, float _range)
+    {
+        mask = _mask;
+        ray.pos.set(_start);
+        ray.inv_dir.set(1.f, 1.f, 1.f).div(_dir);
+        ray.fwd_dir.set(_dir);
+        if (!b_use_sse)
+        {
+            // for FPU - zero out inf
+            if (_abs(_dir.x) > flt_eps) {}
+            else ray.inv_dir.x = 0;
+            if (_abs(_dir.y) > flt_eps) {}
+            else ray.inv_dir.y = 0;
+            if (_abs(_dir.z) > flt_eps) {}
+            else ray.inv_dir.z = 0;
+        }
+        range = _range;
+        range2 = _range*_range;
+        space = _space;
+    }
+    // fpu
+    ICF BOOL _box_fpu(const Fvector& n_C, const float n_R, Fvector& coord)
+    {
+        // box
+        float n_vR = 2 * n_R;
+        Fbox BB;
+        BB.set(n_C.x - n_vR, n_C.y - n_vR, n_C.z - n_vR, n_C.x + n_vR, n_C.y + n_vR, n_C.z + n_vR);
+        return isect_fpu(BB.min, BB.max, ray, coord);
+    }
+    // sse
+    ICF BOOL _box_sse(const Fvector& n_C, const float n_R, float& dist)
+    {
+        aabb_t box;
+        float n_vR = 2 * n_R;
+        box.min.set(n_C.x - n_vR, n_C.y - n_vR, n_C.z - n_vR);
+        box.min.pad = 0;
+        box.max.set(n_C.x + n_vR, n_C.y + n_vR, n_C.z + n_vR);
+        box.max.pad = 0;
+        return isect_sse(box, ray, dist);
+    }
+    void walk(ISpatial_NODE* N, Fvector& n_C, float n_R)
+    {
+        // Actual ray/aabb test
+        if (b_use_sse)
+        {
+            // use SSE
+            float d;
+            if (!_box_sse(n_C, n_R, d)) return;
+            if (d > range) return;
+        }
+        else
+        {
+            // use FPU
+            Fvector P;
+            if (!_box_fpu(n_C, n_R, P)) return;
+            if (P.distance_to_sqr(ray.pos) > range2) return;
+        }
 
-		// test items
-		xr_vector::iterator _it	=	N->items.begin	();
-		xr_vector::iterator _end	=	N->items.end	();
-		for (; _it!=_end; _it++)
-		{
-			ISpatial*		S	= *_it;
-			if (mask!=(S->spatial.type&mask))	continue;
-			Fsphere&		sS	= S->spatial.sphere;
-			int				quantity;
-			float			afT[2];
-			Fsphere::ERP_Result	result	= sS.intersect(ray.pos,ray.fwd_dir,range,quantity,afT);
+        // test items
+        xr_vector::iterator _it = N->items.begin();
+        xr_vector::iterator _end = N->items.end();
+        for (; _it != _end; _it++)
+        {
+            ISpatial* S = *_it;
+            if (mask != (S->spatial.type&mask)) continue;
+            Fsphere& sS = S->spatial.sphere;
+            int quantity;
+            float afT[2];
+            Fsphere::ERP_Result result = sS.intersect(ray.pos, ray.fwd_dir, range, quantity, afT);
 
-			if (result==Fsphere::rpOriginInside || ((result==Fsphere::rpOriginOutside)&&(afT[0]q_result->push_back	(S);
-				if (b_first)				return;
-			}
-		}
+            if (result == Fsphere::rpOriginInside || ((result == Fsphere::rpOriginOutside) && (afT[0] < range)))
+            {
+                if (b_nearest)
+                {
+                    switch (result)
+                    {
+                    case Fsphere::rpOriginInside:
+                        range = afT[0] < range ? afT[0] : range;
+                        break;
+                    case Fsphere::rpOriginOutside:
+                        range = afT[0];
+                        break;
+                    }
+                    range2 = range*range;
+                }
+                space->q_result->push_back(S);
+                if (b_first) return;
+            }
+        }
 
-		// recurse
-		float	c_R		= n_R/2;
-		for (u32 octant=0; octant<8; octant++)
-		{
-			if (0==N->children[octant])	continue;
-			Fvector		c_C;			c_C.mad	(n_C,c_spatial_offset[octant],c_R);
-			walk						(N->children[octant],c_C,c_R);
-			if (b_first && !space->q_result->empty())	return;
-		}
-	}
+        // recurse
+        float c_R = n_R / 2;
+        for (u32 octant = 0; octant < 8; octant++)
+        {
+            if (0 == N->children[octant]) continue;
+            Fvector c_C;
+            c_C.mad(n_C, c_spatial_offset[octant], c_R);
+            walk(N->children[octant], c_C, c_R);
+            if (b_first && !space->q_result->empty()) return;
+        }
+    }
 };
 
-void	ISpatial_DB::q_ray	(xr_vector& R, u32 _o, u32 _mask_and, const Fvector&	_start,  const Fvector&	_dir, float _range)
+void ISpatial_DB::q_ray(xr_vector& R, u32 _o, u32 _mask_and, const Fvector& _start, const Fvector& _dir, float _range)
 {
-	cs.Enter						();
-	q_result						= &R;
-	q_result->clear_not_free		();
-	if (CPU::ID.feature&_CPU_FEATURE_SSE)	{
-		if (_o & O_ONLYFIRST)
-		{
-			if (_o & O_ONLYNEAREST)		{ walker	W(this,_mask_and,_start,_dir,_range);	W.walk(m_root,m_center,m_bounds); } 
-			else						{ walker	W(this,_mask_and,_start,_dir,_range);	W.walk(m_root,m_center,m_bounds); } 
-		} else {
-			if (_o & O_ONLYNEAREST)		{ walker	W(this,_mask_and,_start,_dir,_range);	W.walk(m_root,m_center,m_bounds); } 
-			else						{ walker	W(this,_mask_and,_start,_dir,_range);	W.walk(m_root,m_center,m_bounds); } 
-		}
-	} else {
-		if (_o & O_ONLYFIRST)
-		{
-			if (_o & O_ONLYNEAREST)		{ walker	W(this,_mask_and,_start,_dir,_range);	W.walk(m_root,m_center,m_bounds); } 
-			else						{ walker	W(this,_mask_and,_start,_dir,_range);	W.walk(m_root,m_center,m_bounds); } 
-		} else {
-			if (_o & O_ONLYNEAREST)		{ walker	W(this,_mask_and,_start,_dir,_range);	W.walk(m_root,m_center,m_bounds); } 
-			else						{ walker	W(this,_mask_and,_start,_dir,_range);	W.walk(m_root,m_center,m_bounds); } 
-		}
-	}
-	cs.Leave		();
+    cs.Enter();
+    q_result = &R;
+    q_result->clear_not_free();
+    if (CPU::ID.feature&_CPU_FEATURE_SSE)
+    {
+        if (_o & O_ONLYFIRST)
+        {
+            if (_o & O_ONLYNEAREST) { walker W(this, _mask_and, _start, _dir, _range); W.walk(m_root, m_center, m_bounds); }
+            else { walker W(this, _mask_and, _start, _dir, _range); W.walk(m_root, m_center, m_bounds); }
+        }
+        else
+        {
+            if (_o & O_ONLYNEAREST) { walker W(this, _mask_and, _start, _dir, _range); W.walk(m_root, m_center, m_bounds); }
+            else { walker W(this, _mask_and, _start, _dir, _range); W.walk(m_root, m_center, m_bounds); }
+        }
+    }
+    else
+    {
+        if (_o & O_ONLYFIRST)
+        {
+            if (_o & O_ONLYNEAREST) { walker W(this, _mask_and, _start, _dir, _range); W.walk(m_root, m_center, m_bounds); }
+            else { walker W(this, _mask_and, _start, _dir, _range); W.walk(m_root, m_center, m_bounds); }
+        }
+        else
+        {
+            if (_o & O_ONLYNEAREST) { walker W(this, _mask_and, _start, _dir, _range); W.walk(m_root, m_center, m_bounds); }
+            else { walker W(this, _mask_and, _start, _dir, _range); W.walk(m_root, m_center, m_bounds); }
+        }
+    }
+    cs.Leave();
 }
diff --git a/src/xrEngine/ISpatial_verify.cpp b/src/xrEngine/ISpatial_verify.cpp
index 6cdd8b31f5f..c6306aeae35 100644
--- a/src/xrEngine/ISpatial_verify.cpp
+++ b/src/xrEngine/ISpatial_verify.cpp
@@ -1,40 +1,42 @@
 #include "stdafx.h"
 #include "ISpatial.h"
 
-extern Fvector	c_spatial_offset[8];
+extern Fvector c_spatial_offset[8];
 
-class	walker
+class walker
 {
 public:
-	u32			o_count;
-	u32			n_count;
+    u32 o_count;
+    u32 n_count;
 public:
-	walker					()
-	{
-		o_count	= 0;
-		n_count	= 0;
-	}
-	void		walk		(ISpatial_NODE* N, Fvector& n_C, float n_R)
-	{
-		// test items
-		n_count			+=		1;
-		o_count			+=		N->items.size();
+    walker()
+    {
+        o_count = 0;
+        n_count = 0;
+    }
+    void walk(ISpatial_NODE* N, Fvector& n_C, float n_R)
+    {
+        // test items
+        n_count += 1;
+        o_count += N->items.size();
 
-		// recurse
-		float	c_R		=		n_R/2;
-		for (u32 octant=0; octant<8; octant++)
-		{
-			if (0==N->children[octant])	continue;
-			Fvector		c_C;			c_C.mad	(n_C,c_spatial_offset[octant],c_R);
-			walk						(N->children[octant],c_C,c_R);
-		}
-	}
+        // recurse
+        float c_R = n_R / 2;
+        for (u32 octant = 0; octant < 8; octant++)
+        {
+            if (0 == N->children[octant]) continue;
+            Fvector c_C;
+            c_C.mad(n_C, c_spatial_offset[octant], c_R);
+            walk(N->children[octant], c_C, c_R);
+        }
+    }
 };
 
-BOOL	ISpatial_DB::verify			()
+BOOL ISpatial_DB::verify()
 {
-	walker		W;		W.walk		(m_root,m_center,m_bounds);
-	BOOL		bResult = (W.o_count == stat_objects) && (W.n_count == stat_nodes);
-	VERIFY		(bResult);
-	return		bResult;
+    walker W;
+    W.walk(m_root, m_center, m_bounds);
+    BOOL bResult = (W.o_count == stat_objects) && (W.n_count == stat_nodes);
+    VERIFY(bResult);
+    return bResult;
 }
diff --git a/src/xrEngine/LightAnimLibrary.cpp b/src/xrEngine/LightAnimLibrary.cpp
index ddbb6ffd49f..baed3d65fad 100644
--- a/src/xrEngine/LightAnimLibrary.cpp
+++ b/src/xrEngine/LightAnimLibrary.cpp
@@ -4,96 +4,104 @@
 
 #include "LightAnimLibrary.h"
 //---------------------------------------------------------------------------
-#define LANIM_VERSION		0x0001
+#define LANIM_VERSION 0x0001
 //---------------------------------------------------------------------------
-#define CHUNK_VERSION		0x0000
-#define CHUNK_ITEM_LIST		0x0001
+#define CHUNK_VERSION 0x0000
+#define CHUNK_ITEM_LIST 0x0001
 //---------------------------------------------------------------------------
-#define CHUNK_ITEM_COMMON	0x0001
-#define CHUNK_ITEM_KEYS		0x0002
+#define CHUNK_ITEM_COMMON 0x0001
+#define CHUNK_ITEM_KEYS 0x0002
 //---------------------------------------------------------------------------
 
 ELightAnimLibrary LALib;
 
 CLAItem::CLAItem()
 {
-	fFPS		= 15.f;
-	iFrameCount	= 1;
+    fFPS = 15.f;
+    iFrameCount = 1;
 }
 
-void CLAItem::InitDefault(){
-	Keys[0]		= 0x00000000;
+void CLAItem::InitDefault()
+{
+    Keys[0] = 0x00000000;
 }
 
 void CLAItem::Load(IReader& F)
 {
-	R_ASSERT(F.find_chunk(CHUNK_ITEM_COMMON));
-    F.r_stringZ		(cName);
-    fFPS			= F.r_float();
-    iFrameCount		= F.r_u32();
-
-    int key_cnt,key;
-	R_ASSERT(F.find_chunk(CHUNK_ITEM_KEYS));
-	key_cnt			= F.r_u32();
-    for (int i=0; ifirst);
-		F.w_u32	(it->second);
+    F.open_chunk(CHUNK_ITEM_COMMON);
+    F.w_stringZ(cName);
+    F.w_float(fFPS);
+    F.w_u32(iFrameCount);
+    F.close_chunk();
+
+    F.open_chunk(CHUNK_ITEM_KEYS);
+    F.w_u32(Keys.size());
+    for (KeyPairIt it = Keys.begin(); it != Keys.end(); it++)
+    {
+        F.w_u32(it->first);
+        F.w_u32(it->second);
     }
-	F.close_chunk	();
+    F.close_chunk();
 }
 
 void CLAItem::InsertKey(int frame, u32 color)
 {
-	R_ASSERT(frame<=iFrameCount);
-	Keys[frame] = color;
+    R_ASSERT(frame <= iFrameCount);
+    Keys[frame] = color;
 }
 
 void CLAItem::DeleteKey(int frame)
 {
-	R_ASSERT(frame<=iFrameCount);
-    if (0==frame) return;
-	KeyPairIt it=Keys.find(frame);
-    if (it!=Keys.end()) Keys.erase(it);
+    R_ASSERT(frame <= iFrameCount);
+    if (0 == frame) return;
+    KeyPairIt it = Keys.find(frame);
+    if (it != Keys.end()) Keys.erase(it);
 }
 
 void CLAItem::MoveKey(int from, int to)
 {
-	R_ASSERT(from<=iFrameCount);
-	R_ASSERT(to<=iFrameCount);
-	KeyPairIt it=Keys.find(from);
-    if (it!=Keys.end()){
-    	Keys[to]=it->second;
-		Keys.erase(it);
+    R_ASSERT(from <= iFrameCount);
+    R_ASSERT(to <= iFrameCount);
+    KeyPairIt it = Keys.find(from);
+    if (it != Keys.end())
+    {
+        Keys[to] = it->second;
+        Keys.erase(it);
     }
 }
 
 void CLAItem::Resize(int new_len)
 {
-	VERIFY((new_len>=1));
-	if (new_len!=iFrameCount){
-    	if (new_len>iFrameCount){
-        	int old_len=iFrameCount;
-			iFrameCount = new_len;
-        	MoveKey(old_len,new_len);
-        }else{
-			KeyPairIt I = Keys.upper_bound(new_len-1);
-            if (I!=Keys.end()) Keys.erase(I, Keys.end());
+    VERIFY((new_len >= 1));
+    if (new_len != iFrameCount)
+    {
+        if (new_len > iFrameCount)
+        {
+            int old_len = iFrameCount;
+            iFrameCount = new_len;
+            MoveKey(old_len, new_len);
+        }
+        else
+        {
+            KeyPairIt I = Keys.upper_bound(new_len - 1);
+            if (I != Keys.end()) Keys.erase(I, Keys.end());
             iFrameCount = new_len;
         }
     }
@@ -101,71 +109,82 @@ void CLAItem::Resize(int new_len)
 
 u32 CLAItem::InterpolateRGB(int frame)
 {
-    R_ASSERT(frame<=iFrameCount);
+    R_ASSERT(frame <= iFrameCount);
 
-    KeyPairIt A=Keys.find(frame);
+    KeyPairIt A = Keys.find(frame);
     KeyPairIt B;
-    if (A!=Keys.end()){  			// êëþ÷ - âîçâðàùàåì öâåò êëþ÷à
-    	return A->second;
-    }else{							// íå êëþ÷
-    	B=Keys.upper_bound(frame);  // èùåì ñëåäóþùèé êëþ÷
-        if (B==Keys.end()){			// åñëè åãî íåò âåðíåì öâåò ïîñëåäíåãî êëþ÷à
-	    	B--;
-        	return B->second;
+    if (A != Keys.end())  // êëþ÷ - âîçâðàùàåì öâåò êëþ÷à
+    {
+        return A->second;
+    }
+    else   // íå êëþ÷
+    {
+        B = Keys.upper_bound(frame); // èùåì ñëåäóþùèé êëþ÷
+        if (B == Keys.end())  // åñëè åãî íåò âåðíåì öâåò ïîñëåäíåãî êëþ÷à
+        {
+            B--;
+            return B->second;
         }
-    	A=B;        				// èíà÷å â A çàíåñåì ïðåäûäóùèé êëþ÷
+        A = B; // èíà÷å â A çàíåñåì ïðåäûäóùèé êëþ÷
         A--;
     }
 
-    R_ASSERT(Keys.size()>1);
+    R_ASSERT(Keys.size() > 1);
     // èíòåðïîëèðóåì öâåò
     Fcolor c, c0, c1;
-    float a0=(float)A->first;
-    float a1=(float)B->first;
+    float a0 = (float)A->first;
+    float a1 = (float)B->first;
     c0.set(A->second);
     c1.set(B->second);
-    float t = float(frame-a0)/float(a1-a0);
-    c.lerp(c0,c1,t);
+    float t = float(frame - a0) / float(a1 - a0);
+    c.lerp(c0, c1, t);
     return c.get();
 }
 
 u32 CLAItem::InterpolateBGR(int frame)
 {
-	u32 c 	= InterpolateRGB(frame);
-    return color_rgba(color_get_B(c),color_get_G(c),color_get_R(c),color_get_A(c));
+    u32 c = InterpolateRGB(frame);
+    return color_rgba(color_get_B(c), color_get_G(c), color_get_R(c), color_get_A(c));
 }
 
 u32 CLAItem::CalculateRGB(float T, int& frame)
 {
-    frame	= iFloor(fmodf(T,float(iFrameCount)/fFPS)*fFPS);
+    frame = iFloor(fmodf(T, float(iFrameCount) / fFPS)*fFPS);
     return InterpolateRGB(frame);
 }
 
 u32 CLAItem::CalculateBGR(float T, int& frame)
 {
-    frame	= iFloor(fmodf(T,float(iFrameCount)/fFPS)*fFPS);
+    frame = iFloor(fmodf(T, float(iFrameCount) / fFPS)*fFPS);
     return InterpolateBGR(frame);
 }
 
 int CLAItem::PrevKeyFrame(int frame)
 {
-    KeyPairIt A=Keys.lower_bound(frame);
-    if (A!=Keys.end()){
-    	KeyPairIt B=A; B--;
-        if (B!=Keys.end()) return B->first;
+    KeyPairIt A = Keys.lower_bound(frame);
+    if (A != Keys.end())
+    {
+        KeyPairIt B = A;
+        B--;
+        if (B != Keys.end()) return B->first;
         return A->first;
-    }else{
-    	return Keys.rbegin()->first;
+    }
+    else
+    {
+        return Keys.rbegin()->first;
     }
 }
 
 int CLAItem::NextKeyFrame(int frame)
 {
-    KeyPairIt A=Keys.upper_bound(frame);
-    if (A!=Keys.end()){
+    KeyPairIt A = Keys.upper_bound(frame);
+    if (A != Keys.end())
+    {
         return A->first;
-    }else{
-    	return Keys.rbegin()->first;
+    }
+    else
+    {
+        return Keys.rbegin()->first;
     }
 }
 
@@ -182,131 +201,146 @@ ELightAnimLibrary::~ELightAnimLibrary()
 
 void ELightAnimLibrary::OnCreate()
 {
-	Load();
+    Load();
 }
 
 void ELightAnimLibrary::OnDestroy()
 {
-	Unload();
+    Unload();
 }
 
 void ELightAnimLibrary::Unload()
 {
-	for (LAItemIt it=Items.begin(); it!=Items.end(); it++)
-    	xr_delete(*it);
+    for (LAItemIt it = Items.begin(); it != Items.end(); it++)
+        xr_delete(*it);
     Items.clear();
 }
 
 __declspec(dllexport) void ELightAnimLibrary::Load()
 {
-	string_path fn;
-    FS.update_path(fn,_game_data_,"lanims.xr");
-	IReader* fs=FS.r_open(fn);
-    if (fs){
-    	u16 version	= 0;
-    	if (fs->find_chunk(CHUNK_VERSION)){
-        	version	= fs->r_u16();
+    string_path fn;
+    FS.update_path(fn, _game_data_, "lanims.xr");
+    IReader* fs = FS.r_open(fn);
+    if (fs)
+    {
+        u16 version = 0;
+        if (fs->find_chunk(CHUNK_VERSION))
+        {
+            version = fs->r_u16();
         }
         IReader* OBJ = fs->open_chunk(CHUNK_ITEM_LIST);
-        if (OBJ){
-	        IReader* O   = OBJ->open_chunk(0);
-    	    for (int count=1; O; count++) {
-        	    CLAItem* I = xr_new();
+        if (OBJ)
+        {
+            IReader* O = OBJ->open_chunk(0);
+            for (int count = 1; O; count++)
+            {
+                CLAItem* I = xr_new();
                 I->Load(*O);
-                if (version==0){
-                    for (CLAItem::KeyPairIt it=I->Keys.begin(); it!=I->Keys.end(); it++)
-                        it->second	= subst_alpha(bgr2rgb(it->second),color_get_A(it->second));
+                if (version == 0)
+                {
+                    for (CLAItem::KeyPairIt it = I->Keys.begin(); it != I->Keys.end(); it++)
+                        it->second = subst_alpha(bgr2rgb(it->second), color_get_A(it->second));
                 }
                 Items.push_back(I);
-            	O->close();
-	            O = OBJ->open_chunk(count);
-    	    }
-	        OBJ->close();
+                O->close();
+                O = OBJ->open_chunk(count);
+            }
+            OBJ->close();
         }
 
-		FS.r_close(fs);
+        FS.r_close(fs);
     }
 }
 
 void ELightAnimLibrary::Save()
 {
-	CMemoryWriter F;
-    F.open_chunk	(CHUNK_VERSION);
-    F.w_u16			(LANIM_VERSION);
-	F.close_chunk	();
-    F.open_chunk	(CHUNK_ITEM_LIST);
+    CMemoryWriter F;
+    F.open_chunk(CHUNK_VERSION);
+    F.w_u16(LANIM_VERSION);
+    F.close_chunk();
+    F.open_chunk(CHUNK_ITEM_LIST);
     int count = 0;
-	for (LAItemIt it=Items.begin(); it!=Items.end(); it++){
+    for (LAItemIt it = Items.begin(); it != Items.end(); it++)
+    {
         F.open_chunk(count++);
-		(*it)->Save		(F);
+        (*it)->Save(F);
         F.close_chunk();
     }
-	F.close_chunk	();
+    F.close_chunk();
 
-	string_path		fn;
-    FS.update_path	(fn,_game_data_,"lanims.xr");
+    string_path fn;
+    FS.update_path(fn, _game_data_, "lanims.xr");
 
     if (!F.save_to(fn))
-        Log			("!Can't save color animations:",fn);
+        Log("!Can't save color animations:", fn);
 }
 
 void ELightAnimLibrary::Reload()
 {
-	Unload();
-	Load();
+    Unload();
+    Load();
 }
 
 LAItemIt ELightAnimLibrary::FindItemI(LPCSTR name)
 {
-	if (name&&name[0])
-		for (LAItemIt it=Items.begin(); it!=Items.end(); it++)
-			if (0==xr_strcmp((*it)->cName,name)) return it;
-	return Items.end();
+    if (name&&name[0])
+        for (LAItemIt it=Items.begin(); it!=Items.end(); it++)
+            if (0==xr_strcmp((*it)->cName,name)) return it;
+    return Items.end();
 }
 
 CLAItem* ELightAnimLibrary::FindItem(LPCSTR name)
 {
-	LAItemIt it=FindItemI(name);
-	return (it!=Items.end())?*it:0;
+    LAItemIt it=FindItemI(name);
+    return (it!=Items.end())?*it:0;
 }
 
 CLAItem* ELightAnimLibrary::AppendItem(LPCSTR name, CLAItem* src)
 {
-    VERIFY2				(FindItem(name)==0,"Duplicate name found.");
-    CLAItem* I			= xr_new();
-    if (src)			*I = *src;
-    else			    I->InitDefault();
-    I->cName			= name;
-    Items.push_back		(I);
-	return I;
+    VERIFY2 (FindItem(name)==0,"Duplicate name found.");
+    CLAItem* I = xr_new();
+    if (src) *I = *src;
+    else I->InitDefault();
+    I->cName = name;
+    Items.push_back (I);
+    return I;
 }
 
 #ifdef _EDITOR
-void ELightAnimLibrary::RemoveObject(LPCSTR _fname, EItemType type, bool& res)   
+void ELightAnimLibrary::RemoveObject(LPCSTR _fname, EItemType type, bool& res)
 {
-	if (TYPE_FOLDER==type){
+    if (TYPE_FOLDER == type)
+    {
         res = true;
-		return;
-    }else if (TYPE_OBJECT==type){
-        LAItemIt it=FindItemI(_fname); 
-        if (it!=Items.end()){
-	        xr_delete(*it);
-    	    Items.erase(it);
+        return;
+    }
+    else if (TYPE_OBJECT == type)
+    {
+        LAItemIt it = FindItemI(_fname);
+        if (it != Items.end())
+        {
+            xr_delete(*it);
+            Items.erase(it);
             res = true;
             return;
         }
-    }else THROW;
+    }
+    else THROW;
     res = false;
 }
 //---------------------------------------------------------------------------
 
 void ELightAnimLibrary::RenameObject(LPCSTR nm0, LPCSTR nm1, EItemType type)
 {
-	if (TYPE_FOLDER==type){
-    }else if (TYPE_OBJECT==type){
-		CLAItem* I=FindItem(nm0); R_ASSERT(I);
-		I->cName	= nm1;
-	}
+    if (TYPE_FOLDER == type)
+    {
+    }
+    else if (TYPE_OBJECT == type)
+    {
+        CLAItem* I = FindItem(nm0);
+        R_ASSERT(I);
+        I->cName = nm1;
+    }
 }
 //---------------------------------------------------------------------------
 #endif
\ No newline at end of file
diff --git a/src/xrEngine/LightAnimLibrary.h b/src/xrEngine/LightAnimLibrary.h
index b1b2b38007c..adb7051951f 100644
--- a/src/xrEngine/LightAnimLibrary.h
+++ b/src/xrEngine/LightAnimLibrary.h
@@ -4,62 +4,64 @@
 #define LightAnimLibraryH
 //---------------------------------------------------------------------------
 #ifdef _EDITOR
-	#include "../xrEProps/FolderLib.h"              
+#include "../xrEProps/FolderLib.h"
 #endif
 
-class ENGINE_API CLAItem				{
+class ENGINE_API CLAItem
+{
 public:
-    shared_str		cName;
-    float   		fFPS;
-    DEFINE_MAP		(int,u32,KeyMap,KeyPairIt);
-    KeyMap			Keys;
-    int				iFrameCount;
+    shared_str cName;
+    float fFPS;
+    DEFINE_MAP(int, u32, KeyMap, KeyPairIt);
+    KeyMap Keys;
+    int iFrameCount;
 public:
-                	CLAItem				();
-                    
-	void			InitDefault			();
-    void			Load				(IReader& F);
-    void			Save				(IWriter& F);
-	float			Length_sec			(){return float(iFrameCount)/fFPS;}
-	u32				Length_ms			(){return iFloor(Length_sec()*1000.f);}
-    u32				InterpolateRGB		(int frame);
-    u32				InterpolateBGR		(int frame);
-    u32				CalculateRGB		(float T, int& frame);
-    u32				CalculateBGR		(float T, int& frame);
-    void		    Resize				(int new_len);
-    void		    InsertKey			(int frame, u32 color);
-    void		    DeleteKey			(int frame);
-    void		    MoveKey				(int from, int to);
-    bool		    IsKey				(int frame){return (Keys.end()!=Keys.find(frame));}
-    int		 	    PrevKeyFrame		(int frame);
-    int		 	    NextKeyFrame 		(int frame);
-    int		 	    FirstKeyFrame		(){return Keys.rend()->first;}
-    int		 	    LastKeyFrame		(){return Keys.rbegin()->first;}
-    u32*			GetKey				(int frame){KeyPairIt it=Keys.find(frame); return (it!=Keys.end())?&(it->second):0;}
+    CLAItem();
+
+    void InitDefault();
+    void Load(IReader& F);
+    void Save(IWriter& F);
+    float Length_sec() { return float(iFrameCount) / fFPS; }
+    u32 Length_ms() { return iFloor(Length_sec()*1000.f); }
+    u32 InterpolateRGB(int frame);
+    u32 InterpolateBGR(int frame);
+    u32 CalculateRGB(float T, int& frame);
+    u32 CalculateBGR(float T, int& frame);
+    void Resize(int new_len);
+    void InsertKey(int frame, u32 color);
+    void DeleteKey(int frame);
+    void MoveKey(int from, int to);
+    bool IsKey(int frame) { return (Keys.end() != Keys.find(frame)); }
+    int PrevKeyFrame(int frame);
+    int NextKeyFrame(int frame);
+    int FirstKeyFrame() { return Keys.rend()->first; }
+    int LastKeyFrame() { return Keys.rbegin()->first; }
+    u32* GetKey(int frame) { KeyPairIt it = Keys.find(frame); return (it != Keys.end()) ? &(it->second) : 0; }
 };
-DEFINE_VECTOR(CLAItem*,LAItemVec,LAItemIt);
+DEFINE_VECTOR(CLAItem*, LAItemVec, LAItemIt);
 
-class ENGINE_API ELightAnimLibrary{
+class ENGINE_API ELightAnimLibrary
+{
 public:
-    LAItemVec       Items;
-    LAItemIt		FindItemI			(LPCSTR name);
-    CLAItem*		FindItem			(LPCSTR name);
+    LAItemVec Items;
+    LAItemIt FindItemI(LPCSTR name);
+    CLAItem* FindItem(LPCSTR name);
 public:
-					ELightAnimLibrary	();
-					~ELightAnimLibrary	();
-#ifdef _EDITOR       
-    void  			RemoveObject		(LPCSTR fname, EItemType type, bool& res);
-    void		 	RenameObject		(LPCSTR fn0, LPCSTR fn1, EItemType type);
+    ELightAnimLibrary ();
+    ~ELightAnimLibrary ();
+#ifdef _EDITOR
+    void RemoveObject(LPCSTR fname, EItemType type, bool& res);
+    void RenameObject(LPCSTR fn0, LPCSTR fn1, EItemType type);
 #endif
 
-    void			OnCreate			();
-    void			OnDestroy			();
-    void			Load				();
-    void			Save				();
-    void			Reload				();
-    void			Unload				();
-    CLAItem*		AppendItem			(LPCSTR name, CLAItem* src);
-    LAItemVec&		Objects				(){return Items;}
+    void OnCreate();
+    void OnDestroy();
+    void Load();
+    void Save();
+    void Reload();
+    void Unload();
+    CLAItem* AppendItem(LPCSTR name, CLAItem* src);
+    LAItemVec& Objects() { return Items; }
 };
 
 extern ENGINE_API ELightAnimLibrary LALib;
diff --git a/src/xrEngine/MbHelpers.cpp b/src/xrEngine/MbHelpers.cpp
index 8d77623ce8f..afce4ee8379 100644
--- a/src/xrEngine/MbHelpers.cpp
+++ b/src/xrEngine/MbHelpers.cpp
@@ -17,134 +17,145 @@
 
 #ifdef MB_DUMB_CONVERSION
 
-unsigned short int mbhMulti2WideDumb
-	( wide_char *WideStr , wide_char *WidePos , const unsigned short int WideStrSize , const char *MultiStr  )
+unsigned short int mbhMulti2WideDumb(wide_char* WideStr, wide_char* WidePos,
+    const unsigned short int WideStrSize, const char* MultiStr)
 {
-	unsigned short int spos = 0;
-	unsigned short int dpos = 0;
-	unsigned char b1;
-	wide_char wc = 0 ;
+    unsigned short int spos = 0;
+    unsigned short int dpos = 0;
+    unsigned char b1;
+    wide_char wc = 0;
 
-	VERIFY( MultiStr );
+    VERIFY(MultiStr);
 
-	if ( ! MultiStr[ 0 ] )
-		return 0;
+    if (!MultiStr[0])
+        return 0;
 
-	if ( WideStr || WidePos )
-		VERIFY2( ( ( WideStrSize > 0 ) && ( WideStrSize < 0xFFFF ) ) , make_string( "'WideStrSize'=%hu" , WideStrSize ) );
+    if (WideStr || WidePos)
+        VERIFY2(((WideStrSize > 0) && (WideStrSize < 0xFFFF)), make_string("'WideStrSize'=%hu", WideStrSize));
 
-	while ( ( b1	= MultiStr[ spos++ ] ) != 0x00 ) {
+    while ((b1 = MultiStr[spos++]) != 0x00)
+    {
 
-		if ( WidePos )
-			WidePos[ dpos ] = spos;
-		
-		dpos++;
+        if (WidePos)
+            WidePos[dpos] = spos;
 
-		wc = b1;
+        dpos++;
 
-		if ( WideStr ) {
-			VERIFY2( ( dpos < WideStrSize ) , make_string( "S1: '%s',%hu<%hu" , MultiStr , dpos , WideStrSize ) );
-			WideStr[ dpos ] = wc;
-		}
-	}
+        wc = b1;
 
-	if ( WidePos )
-		WidePos[ dpos ] = spos;
+        if (WideStr)
+        {
+            VERIFY2((dpos < WideStrSize), make_string("S1: '%s',%hu<%hu", MultiStr, dpos, WideStrSize));
+            WideStr[dpos] = wc;
+        }
+    }
 
-	if ( WideStr ) {
-		VERIFY2( ( dpos < WideStrSize ) , make_string( "S2: '%s',%hu<%hu" , MultiStr , dpos , WideStrSize ) );
-		WideStr[ dpos + 1 ] = 0x0000;
-	}
+    if (WidePos)
+        WidePos[dpos] = spos;
 
-	if ( WideStr )
-		WideStr[ 0 ] = dpos;
+    if (WideStr)
+    {
+        VERIFY2((dpos < WideStrSize), make_string("S2: '%s',%hu<%hu", MultiStr, dpos, WideStrSize));
+        WideStr[dpos + 1] = 0x0000;
+    }
 
-	return dpos;
+    if (WideStr)
+        WideStr[0] = dpos;
+
+    return dpos;
 }
 
 #endif // MB_DUMB_CONVERSION
 
 ENGINE_API unsigned short int mbhMulti2Wide
-	( wide_char *WideStr , wide_char *WidePos , const unsigned short int WideStrSize , const char *MultiStr  )
+(wide_char* WideStr, wide_char* WidePos, const unsigned short int WideStrSize, const char* MultiStr)
 {
-	unsigned short int spos = 0;
-	unsigned short int dpos = 0;
-	unsigned char b1, b2, b3;
-	wide_char wc = 0 ;
-
-	VERIFY( MultiStr );
-
-	if ( ! MultiStr[ 0 ] )
-		return 0;
-
-	if ( WideStr || WidePos )
-		VERIFY2( ( ( WideStrSize > 0 ) && ( WideStrSize < 0xFFFF ) ) , make_string( "'WideStrSize'=%hu" , WideStrSize ) );
-
-	while ( ( b1 = MultiStr[ spos ] ) != 0x00 ) {
-
-		if ( WidePos )
-			WidePos[ dpos ] = spos;
-
-		spos++;
-		
-		if ( ( b1 & BITS1_MASK ) == BITS1_EXP ) {
-			wc = b1;
-		} else
-		if ( ( b1 & BITS3_MASK ) == BITS3_EXP ) {
-			b2 = MultiStr[ spos++ ];
-			#ifdef MB_DUMB_CONVERSION
-				if ( ! ( b2 && ( ( b2 & BITS2_MASK ) == BITS2_EXP ) ) )
-					return mbhMulti2WideDumb( WideStr , WidePos , WideStrSize , MultiStr );
-			#else // MB_DUMB_CONVERSION
-				VERIFY2( ( b2 && ( ( b2 & BITS2_MASK ) == BITS2_EXP ) ) , 
-					make_string( "B2: '%s',@%hu,[%hc][%hc]" , MultiStr , spos , b1 , b2 ) );
-			#endif // MB_DUMB_CONVERSION
-			wc = ( ( b1 & ~ BITS3_MASK ) << 6 ) | ( b2 & ~ BITS2_MASK );
-		} else
-		if ( ( b1 & BITS4_MASK ) == BITS4_EXP ) {
-			b2 = MultiStr[ spos++ ];
-			#ifdef MB_DUMB_CONVERSION
-				if ( ! ( b2 && ( ( b2 & BITS2_MASK ) == BITS2_EXP ) ) )
-					return mbhMulti2WideDumb( WideStr , WidePos , WideStrSize , MultiStr );
-			#else // MB_DUMB_CONVERSION
-				VERIFY2( ( b2 && ( ( b2 & BITS2_MASK ) == BITS2_EXP ) ) ,
-					make_string( "B31: '%s',@%hu,[%hc][%hc]" , MultiStr , spos , b1 , b2 ) );
-			#endif // MB_DUMB_CONVERSION
-			b3 = MultiStr[ spos++ ];
-			#ifdef MB_DUMB_CONVERSION
-				if ( ! ( b3 && ( ( b3 & BITS2_MASK ) == BITS2_EXP ) ) ) 
-					return mbhMulti2WideDumb( WideStr , WidePos , WideStrSize , MultiStr );
-			#else // MB_DUMB_CONVERSION
-				VERIFY2( ( b3 && ( ( b3 & BITS2_MASK ) == BITS2_EXP ) ) ,
-					make_string( "B32: '%s',@%hu,[%hc][%hc][%hc]" , MultiStr , spos , b1 , b2 , b3 ) );
-			#endif // MB_DUMB_CONVERSION
-			wc = ( ( b1 & ~ BITS4_MASK ) << 12 ) | ( ( b2 & ~ BITS2_MASK ) << 6 ) | ( b3 & ~ BITS2_MASK );
-		} else {
-			#ifdef MB_DUMB_CONVERSION
-				return mbhMulti2WideDumb( WideStr , WidePos , WideStrSize , MultiStr );
-			#else // MB_DUMB_CONVERSION
-				VERIFY2( 0 , make_string( "B1: '%s',@%hu,[%hc]" , MultiStr , spos , b1 ) );
-			#endif // MB_DUMB_CONVERSION
-		}
-
-		dpos++;
-
-		if ( WideStr ) {
-			VERIFY2( ( dpos < WideStrSize ) , make_string( "S1: '%s',%hu<%hu" , MultiStr , dpos , WideStrSize ) );
-			WideStr[ dpos ] = wc;
-		}
-	}
-
-	if ( WidePos )
-		WidePos[ dpos ] = spos;
-
-	if ( WideStr ) {
-		VERIFY2( ( dpos < WideStrSize ) , make_string( "S2: '%s',%hu<%hu" , MultiStr , dpos , WideStrSize ) );
-		WideStr[ dpos + 1 ] = 0x0000;
-	}
-
-	if ( WideStr )
-		WideStr[ 0 ] = dpos;
-
-	return dpos;
+    unsigned short int spos = 0;
+    unsigned short int dpos = 0;
+    unsigned char b1, b2, b3;
+    wide_char wc = 0;
+
+    VERIFY(MultiStr);
+
+    if (!MultiStr[0])
+        return 0;
+
+    if (WideStr || WidePos)
+        VERIFY2(((WideStrSize > 0) && (WideStrSize < 0xFFFF)), make_string("'WideStrSize'=%hu", WideStrSize));
+
+    while ((b1 = MultiStr[spos]) != 0x00)
+    {
+
+        if (WidePos)
+            WidePos[dpos] = spos;
+
+        spos++;
+
+        if ((b1 & BITS1_MASK) == BITS1_EXP)
+        {
+            wc = b1;
+        }
+        else if ( ( b1 & BITS3_MASK ) == BITS3_EXP )
+        {
+            b2 = MultiStr[ spos++ ];
+#ifdef MB_DUMB_CONVERSION
+            if (!(b2 && ((b2 & BITS2_MASK) == BITS2_EXP)))
+                return mbhMulti2WideDumb(WideStr, WidePos, WideStrSize, MultiStr);
+#else // MB_DUMB_CONVERSION
+            VERIFY2((b2 && ((b2 & BITS2_MASK) == BITS2_EXP)),
+                make_string("B2: '%s',@%hu,[%hc][%hc]", MultiStr, spos, b1, b2));
+#endif // MB_DUMB_CONVERSION
+            wc = ((b1 & ~BITS3_MASK) << 6) | (b2 & ~BITS2_MASK);
+        }
+        else if ( ( b1 & BITS4_MASK ) == BITS4_EXP )
+        {
+            b2 = MultiStr[ spos++ ];
+#ifdef MB_DUMB_CONVERSION
+            if (!(b2 && ((b2 & BITS2_MASK) == BITS2_EXP)))
+                return mbhMulti2WideDumb(WideStr, WidePos, WideStrSize, MultiStr);
+#else // MB_DUMB_CONVERSION
+            VERIFY2( ( b2 && ( ( b2 & BITS2_MASK ) == BITS2_EXP ) ) ,
+                make_string( "B31: '%s',@%hu,[%hc][%hc]" , MultiStr , spos , b1 , b2 ) );
+#endif // MB_DUMB_CONVERSION
+            b3 = MultiStr[ spos++ ];
+#ifdef MB_DUMB_CONVERSION
+            if (!(b3 && ((b3 & BITS2_MASK) == BITS2_EXP)))
+                return mbhMulti2WideDumb(WideStr, WidePos, WideStrSize, MultiStr);
+#else // MB_DUMB_CONVERSION
+            VERIFY2( ( b3 && ( ( b3 & BITS2_MASK ) == BITS2_EXP ) ) ,
+                make_string( "B32: '%s',@%hu,[%hc][%hc][%hc]" , MultiStr , spos , b1 , b2 , b3 ) );
+#endif // MB_DUMB_CONVERSION
+            wc = ((b1 & ~BITS4_MASK) << 12) | ((b2 & ~BITS2_MASK) << 6) | (b3 & ~BITS2_MASK);
+    }
+        else
+        {
+#ifdef MB_DUMB_CONVERSION
+            return mbhMulti2WideDumb(WideStr, WidePos, WideStrSize, MultiStr);
+#else // MB_DUMB_CONVERSION
+            VERIFY2(0, make_string("B1: '%s',@%hu,[%hc]", MultiStr, spos, b1));
+#endif // MB_DUMB_CONVERSION
+        }
+
+        dpos++;
+
+        if (WideStr)
+        {
+            VERIFY2((dpos < WideStrSize), make_string("S1: '%s',%hu<%hu", MultiStr, dpos, WideStrSize));
+            WideStr[dpos] = wc;
+        }
+}
+
+    if (WidePos)
+        WidePos[dpos] = spos;
+
+    if (WideStr)
+    {
+        VERIFY2((dpos < WideStrSize), make_string("S2: '%s',%hu<%hu", MultiStr, dpos, WideStrSize));
+        WideStr[dpos + 1] = 0x0000;
+    }
+
+    if (WideStr)
+        WideStr[0] = dpos;
+
+    return dpos;
 }
diff --git a/src/xrEngine/MbHelpers.h b/src/xrEngine/MbHelpers.h
index c8d0ff3e2c8..a643e42c92d 100644
--- a/src/xrEngine/MbHelpers.h
+++ b/src/xrEngine/MbHelpers.h
@@ -6,70 +6,70 @@
 typedef unsigned short int wide_char;
 
 ENGINE_API unsigned short int mbhMulti2Wide
-	( wide_char *WideStr , wide_char *WidePos , const unsigned short int WideStrSize , const char *MultiStr  );
+(wide_char* WideStr, wide_char* WidePos, const unsigned short int WideStrSize, const char* MultiStr);
 
-__inline BOOL IsNeedSpaceCharacter( wide_char wc )
+__inline BOOL IsNeedSpaceCharacter(wide_char wc)
 {
-	return ( 
-		( wc == 0x0020 )  ||
+    return (
+        (wc == 0x0020) ||
 
-		( wc == 0x3000 )  ||
+        (wc == 0x3000) ||
 
-		( wc == 0xFF01 )  ||
-		( wc == 0xFF0C )  ||
-//		( wc == 0xFF0D )  ||
-		( wc == 0xFF0E )  ||
-		( wc == 0xFF1A )  ||
-		( wc == 0xFF1B )  ||
-		( wc == 0xFF1F )  ||
+        (wc == 0xFF01) ||
+        (wc == 0xFF0C) ||
+        // ( wc == 0xFF0D ) ||
+        (wc == 0xFF0E) ||
+        (wc == 0xFF1A) ||
+        (wc == 0xFF1B) ||
+        (wc == 0xFF1F) ||
 
-		( wc == 0x2026 )  ||
+        (wc == 0x2026) ||
 
-		( wc == 0x3002 )  ||
-		( wc == 0x3001 ) 
-	);
+        (wc == 0x3002) ||
+        (wc == 0x3001)
+        );
 }
 
-__inline BOOL IsBadStartCharacter( wide_char wc )
+__inline BOOL IsBadStartCharacter(wide_char wc)
 {
-	return ( 
-		IsNeedSpaceCharacter( wc ) ||
-
-		( wc == 0x0021 )  ||
-		( wc == 0x002C )  ||
-//		( wc == 0x002D )  ||
-		( wc == 0x002E )  ||
-		( wc == 0x003A )  ||
-		( wc == 0x003B )  ||
-		( wc == 0x003F )  ||
-
-		( wc == 0x0029 )  ||
-		( wc == 0xFF09 )
-	);
+    return (
+        IsNeedSpaceCharacter(wc) ||
+
+        (wc == 0x0021) ||
+        (wc == 0x002C) ||
+        // ( wc == 0x002D ) ||
+        (wc == 0x002E) ||
+        (wc == 0x003A) ||
+        (wc == 0x003B) ||
+        (wc == 0x003F) ||
+
+        (wc == 0x0029) ||
+        (wc == 0xFF09)
+        );
 }
 
-__inline BOOL IsBadEndCharacter( wide_char wc )
+__inline BOOL IsBadEndCharacter(wide_char wc)
 {
-	return ( 
-		( wc == 0x0028 )  ||
+    return (
+        (wc == 0x0028) ||
 
-		( wc == 0xFF08 )  ||
+        (wc == 0xFF08) ||
 
-		( wc == 0x4E00 ) 
-	);
+        (wc == 0x4E00)
+        );
 }
 
-__inline BOOL IsAlphaCharacter( wide_char wc )
+__inline BOOL IsAlphaCharacter(wide_char wc)
 {
-	return ( 
-		( ( wc >= 0x0030 ) && ( wc <= 0x0039 ) ) ||
-		( ( wc >= 0x0041 ) && ( wc <= 0x005A ) ) ||
-		( ( wc >= 0x0061 ) && ( wc <= 0x007A ) ) ||
-
-		( ( wc >= 0xFF10 ) && ( wc <= 0xFF19 ) ) ||
-		( ( wc >= 0xFF21 ) && ( wc <= 0xFF3A ) ) ||
-		( ( wc >= 0xFF41 ) && ( wc <= 0xFF5A ) )
-	);
+    return (
+        ((wc >= 0x0030) && (wc <= 0x0039)) ||
+        ((wc >= 0x0041) && (wc <= 0x005A)) ||
+        ((wc >= 0x0061) && (wc <= 0x007A)) ||
+
+        ((wc >= 0xFF10) && (wc <= 0xFF19)) ||
+        ((wc >= 0xFF21) && (wc <= 0xFF3A)) ||
+        ((wc >= 0xFF41) && (wc <= 0xFF5A))
+        );
 }
 
 
diff --git a/src/xrEngine/ObjectAnimator.cpp b/src/xrEngine/ObjectAnimator.cpp
index 3992f52d71a..c704413df6b 100644
--- a/src/xrEngine/ObjectAnimator.cpp
+++ b/src/xrEngine/ObjectAnimator.cpp
@@ -3,109 +3,125 @@
 
 #include "ObjectAnimator.h"
 #include "motion.h"
- 
-bool motion_sort_pred	(COMotion* a, 	COMotion* b)	{	return a->namename;}
-bool motion_find_pred	(COMotion* a, 	shared_str b)	{	return a->namename < b->name; }
+bool motion_find_pred(COMotion* a, shared_str b) { return a->name < b; }
 
 //////////////////////////////////////////////////////////////////////
 // Construction/Destruction
 //////////////////////////////////////////////////////////////////////
 CObjectAnimator::CObjectAnimator()
 {
-	bLoop			= false;
-    m_Current		= 0;
-    m_Speed			= 1.f;
-	m_Name			= "";
+    bLoop = false;
+    m_Current = 0;
+    m_Speed = 1.f;
+    m_Name = "";
 }
 
 CObjectAnimator::~CObjectAnimator()
-{	
-	Clear				();
+{
+    Clear();
 }
 
 void CObjectAnimator::Clear()
 {
-	for(MotionIt m_it=m_Motions.begin(); m_it!=m_Motions.end(); m_it++)
-		xr_delete		(*m_it);
-	m_Motions.clear		();
-    SetActiveMotion		(0);
+    for (MotionIt m_it = m_Motions.begin(); m_it != m_Motions.end(); m_it++)
+        xr_delete(*m_it);
+    m_Motions.clear();
+    SetActiveMotion(0);
 }
 
 void CObjectAnimator::SetActiveMotion(COMotion* mot)
 {
-	m_Current			= mot;
-    if (m_Current) 		m_MParam.Set(m_Current);
-	m_XFORM.identity	();
+    m_Current = mot;
+    if (m_Current) m_MParam.Set(m_Current);
+    m_XFORM.identity();
 }
 
 void CObjectAnimator::LoadMotions(LPCSTR fname)
 {
-	string_path			full_path;
-	if (!FS.exist( full_path, "$level$", fname ))
-		if (!FS.exist( full_path, "$game_anims$", fname ))
-			Debug.fatal(DEBUG_INFO,"Can't find motion file '%s'.",fname);
-            
-    LPCSTR  ext			= strext(full_path);
-    if (ext){
-		Clear			();
-    	if (0==xr_strcmp(ext,".anm")){
-            COMotion* M	= xr_new ();
+    string_path full_path;
+    if (!FS.exist(full_path, "$level$", fname))
+        if (!FS.exist(full_path, "$game_anims$", fname))
+            Debug.fatal(DEBUG_INFO, "Can't find motion file '%s'.", fname);
+
+    LPCSTR ext = strext(full_path);
+    if (ext)
+    {
+        Clear();
+        if (0 == xr_strcmp(ext, ".anm"))
+        {
+            COMotion* M = xr_new();
             if (M->LoadMotion(full_path)) m_Motions.push_back(M);
-            else				FATAL("ERROR: Can't load motion. Incorrect file version.");
-        }else if (0==xr_strcmp(ext,".anms")){
-            IReader* F			= FS.r_open(full_path);
-            u32 dwMCnt			= F->r_u32(); VERIFY(dwMCnt);
-            for (u32 i=0; i ();
-                bool bRes		= M->Load(*F);
-                if (!bRes)		FATAL("ERROR: Can't load motion. Incorrect file version.");
+            else FATAL("ERROR: Can't load motion. Incorrect file version.");
+        }
+        else if (0 == xr_strcmp(ext, ".anms"))
+        {
+            IReader* F = FS.r_open(full_path);
+            u32 dwMCnt = F->r_u32();
+            VERIFY(dwMCnt);
+            for (u32 i = 0; i < dwMCnt; i++)
+            {
+                COMotion* M = xr_new();
+                bool bRes = M->Load(*F);
+                if (!bRes) FATAL("ERROR: Can't load motion. Incorrect file version.");
                 m_Motions.push_back(M);
             }
-            FS.r_close		(F);
+            FS.r_close(F);
         }
-        std::sort(m_Motions.begin(),m_Motions.end(),motion_sort_pred);
+        std::sort(m_Motions.begin(), m_Motions.end(), motion_sort_pred);
     }
 }
 
-void CObjectAnimator::Load(const char * name)
+void CObjectAnimator::Load(const char* name)
 {
-	m_Name				= name;
-	LoadMotions			(name); 
-	SetActiveMotion		(0);
+    m_Name = name;
+    LoadMotions(name);
+    SetActiveMotion(0);
 }
 
 void CObjectAnimator::Update(float dt)
 {
-	if (m_Current){
-		Fvector R,P;
-		m_Current->_Evaluate(m_MParam.Frame(),P,R);
-		m_MParam.Update	(dt,m_Speed,bLoop);
-		m_XFORM.setXYZi	(R.x,R.y,R.z);
+    if (m_Current)
+    {
+        Fvector R, P;
+        m_Current->_Evaluate(m_MParam.Frame(), P, R);
+        m_MParam.Update(dt, m_Speed, bLoop);
+        m_XFORM.setXYZi(R.x, R.y, R.z);
         m_XFORM.translate_over(P);
-	}
+    }
 }
 
 COMotion* CObjectAnimator::Play(bool loop, LPCSTR name)
 {
-	if (name&&name[0]){
-		MotionIt it = std::lower_bound(m_Motions.begin(),m_Motions.end(),name,motion_find_pred);
-        if ((it!=m_Motions.end())&&(0==xr_strcmp((*it)->Name(),name))){
-            bLoop 		= loop;
+    if (name&&name[0])
+    {
+        MotionIt it = std::lower_bound(m_Motions.begin(), m_Motions.end(), name, motion_find_pred);
+        if ((it != m_Motions.end()) && (0 == xr_strcmp((*it)->Name(), name)))
+        {
+            bLoop = loop;
             SetActiveMotion(*it);
-			m_MParam.Play	();
-            return 		*it;
-        }else{
-            Debug.fatal	(DEBUG_INFO,"OBJ ANIM::Cycle '%s' not found.",name);
+            m_MParam.Play();
+            return *it;
+        }
+        else
+        {
+            Debug.fatal(DEBUG_INFO, "OBJ ANIM::Cycle '%s' not found.", name);
             return NULL;
         }
-    }else{
-        if (!m_Motions.empty()){
-            bLoop 		= loop;
+    }
+    else
+    {
+        if (!m_Motions.empty())
+        {
+            bLoop = loop;
             SetActiveMotion(m_Motions.front());
-			m_MParam.Play	();
-            return 		m_Motions.front();
-        }else{
-            Debug.fatal	(DEBUG_INFO,"OBJ ANIM::Cycle '%s' not found.",name);
+            m_MParam.Play();
+            return m_Motions.front();
+        }
+        else
+        {
+            Debug.fatal(DEBUG_INFO, "OBJ ANIM::Cycle '%s' not found.", name);
             return NULL;
         }
     }
@@ -113,15 +129,15 @@ COMotion* CObjectAnimator::Play(bool loop, LPCSTR name)
 
 void CObjectAnimator::Stop()
 {
-	SetActiveMotion		(0);
-	m_MParam.Stop		();
+    SetActiveMotion (0);
+    m_MParam.Stop ();
 }
 
-float CObjectAnimator::GetLength		()
+float CObjectAnimator::GetLength ()
 {
-	if(!m_Current) return 0.0f;
-	float res = m_Current->Length()/m_Current->FPS();
-	return res; 
+    if(!m_Current) return 0.0f;
+    float res = m_Current->Length()/m_Current->FPS();
+    return res;
 }
 
 #ifdef _EDITOR
@@ -134,31 +150,35 @@ static FvectorVec path_points;
 void CObjectAnimator::DrawPath()
 {
     // motion path
-	if (m_Current){
-        float fps 				= m_Current->FPS();
-        float min_t				= (float)m_Current->FrameStart()/fps;
-        float max_t				= (float)m_Current->FrameEnd()/fps;
-
-        Fvector 				T,r;
-        u32 clr					= 0xffffffff;
-        path_points.clear		();
-        for (float t=min_t; (t_Evaluate(t,T,r);
+    if (m_Current)
+    {
+        float fps = m_Current->FPS();
+        float min_t = (float)m_Current->FrameStart()/fps;
+        float max_t = (float)m_Current->FrameEnd()/fps;
+
+        Fvector T,r;
+        u32 clr = 0xffffffff;
+        path_points.clear ();
+        for (float t=min_t; (t_Evaluate(t, T, r);
             path_points.push_back(T);
-        }
+    }
 
-        EDevice.SetShader		(EDevice.m_WireShader);
-        RCache.set_xform_world	(Fidentity);
+        EDevice.SetShader(EDevice.m_WireShader);
+        RCache.set_xform_world(Fidentity);
         if (!path_points.empty())
-        	DU_impl.DrawPrimitiveL		(D3DPT_LINESTRIP,path_points.size()-1,path_points.begin(),path_points.size(),clr,true,false);
-        CEnvelope* E 			= m_Current->Envelope	();
-        for (KeyIt k_it=E->keys.begin(); k_it!=E->keys.end(); k_it++){
-            m_Current->_Evaluate((*k_it)->time,T,r);
-            if (EDevice.m_Camera.GetPosition().distance_to_sqr(T)<50.f*50.f){
-                DU_impl.DrawCross	(T,0.1f,0.1f,0.1f, 0.1f,0.1f,0.1f, clr,false);
-                DU_impl.OutText		(T,AnsiString().sprintf("K: %3.3f",(*k_it)->time).c_str(),0xffffffff,0x00000000);
+            DU_impl.DrawPrimitiveL(D3DPT_LINESTRIP, path_points.size() - 1, path_points.begin(), path_points.size(), clr, true, false);
+        CEnvelope* E = m_Current->Envelope();
+        for (KeyIt k_it = E->keys.begin(); k_it != E->keys.end(); k_it++)
+        {
+            m_Current->_Evaluate((*k_it)->time, T, r);
+            if (EDevice.m_Camera.GetPosition().distance_to_sqr(T) < 50.f*50.f)
+            {
+                DU_impl.DrawCross(T, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, clr, false);
+                DU_impl.OutText(T, AnsiString().sprintf("K: %3.3f", (*k_it)->time).c_str(), 0xffffffff, 0x00000000);
             }
         }
-    }
+}
 }
 #endif
diff --git a/src/xrEngine/ObjectAnimator.h b/src/xrEngine/ObjectAnimator.h
index 30cff774267..806c81ce7e6 100644
--- a/src/xrEngine/ObjectAnimator.h
+++ b/src/xrEngine/ObjectAnimator.h
@@ -8,40 +8,40 @@
 class ENGINE_API CObjectAnimator
 {
 private:
-	DEFINE_VECTOR		(COMotion*,MotionVec,MotionIt);
+    DEFINE_VECTOR(COMotion*, MotionVec, MotionIt);
 protected:
-	bool				bLoop;
-
-    shared_str			m_Name;
-    
-	Fmatrix				m_XFORM;
-    SAnimParams			m_MParam;
-	MotionVec			m_Motions;
-    float				m_Speed;
-
-    COMotion*			m_Current;
-	void				LoadMotions		(LPCSTR fname);
-	void				SetActiveMotion	(COMotion* mot);
-	COMotion*			FindMotionByName(LPCSTR name);
+    bool bLoop;
+
+    shared_str m_Name;
+
+    Fmatrix m_XFORM;
+    SAnimParams m_MParam;
+    MotionVec m_Motions;
+    float m_Speed;
+
+    COMotion* m_Current;
+    void LoadMotions(LPCSTR fname);
+    void SetActiveMotion(COMotion* mot);
+    COMotion* FindMotionByName(LPCSTR name);
 public:
-						CObjectAnimator	();
-	virtual				~CObjectAnimator();
-
-	void				Clear			();
-	void				Load			(LPCSTR name);
-    IC LPCSTR			Name			(){return *m_Name;}
-    float&				Speed			(){return m_Speed;}
-
-	COMotion*			Play			(bool bLoop, LPCSTR name=0);
-	void				Pause			(bool val){return m_MParam.Pause(val);}
-	void				Stop			();
-	IC BOOL				IsPlaying		(){return m_MParam.bPlay;}
-
-    IC const Fmatrix&	XFORM			(){return m_XFORM;}
-	float				GetLength		();
-	// Update
-	void				Update			(float dt);
-    void				DrawPath		();
+    CObjectAnimator();
+    virtual ~CObjectAnimator();
+
+    void Clear();
+    void Load(LPCSTR name);
+    IC LPCSTR Name() { return *m_Name; }
+    float& Speed() { return m_Speed; }
+
+    COMotion* Play(bool bLoop, LPCSTR name = 0);
+    void Pause(bool val) { return m_MParam.Pause(val); }
+    void Stop();
+    IC BOOL IsPlaying() { return m_MParam.bPlay; }
+
+    IC const Fmatrix& XFORM() { return m_XFORM; }
+    float GetLength();
+    // Update
+    void Update(float dt);
+    void DrawPath();
 };
 
 #endif //ObjectAnimatorH
diff --git a/src/xrEngine/ObjectDump.cpp b/src/xrEngine/ObjectDump.cpp
index c72b7345afe..87f018dac5c 100644
--- a/src/xrEngine/ObjectDump.cpp
+++ b/src/xrEngine/ObjectDump.cpp
@@ -3,89 +3,90 @@
 #ifdef DEBUG
 #include "ObjectDump.h"
 
-ENGINE_API std::string dbg_object_base_dump_string( const CObject *obj )
+ENGINE_API std::string dbg_object_base_dump_string(const CObject* obj)
 {
-	if( !obj )
-		return make_string("object: NULL ptr");
-	return make_string( "object name: %s, section name: %s, visual name: %s \n",
-		                 obj->cName().c_str(), 
-						 obj->cNameSect().c_str(), 
-						 obj->Visual() ? obj->cNameVisual().c_str() : "none" );
+    if (!obj)
+        return make_string("object: NULL ptr");
+    return make_string("object name: %s, section name: %s, visual name: %s \n",
+        obj->cName().c_str(),
+        obj->cNameSect().c_str(),
+        obj->Visual() ? obj->cNameVisual().c_str() : "none");
 }
 
-ENGINE_API std::string dbg_object_poses_dump_string( const CObject *obj )
+ENGINE_API std::string dbg_object_poses_dump_string(const CObject* obj)
 {
-	if(!obj)
-		return std::string("");
-	
-	u32 ps_size = obj->ps_Size();
-	std::string buf("");
-	for (u32 i = 0; i < ps_size; ++i )
-	{
-		const CObject::SavedPosition &svp = obj->ps_Element( i );
-		buf +=( make_string(" \n %d, time: %d pos: %s  ", i, svp.dwTime, get_string(svp.vPosition).c_str() ) );
-	}
+    if (!obj)
+        return std::string("");
 
-	return make_string( "\n XFORM: %s \n position stack : %s \n,  ", get_string(obj->XFORM()).c_str(), buf.c_str() );
+    u32 ps_size = obj->ps_Size();
+    std::string buf("");
+    for (u32 i = 0; i < ps_size; ++i)
+    {
+        const CObject::SavedPosition& svp = obj->ps_Element(i);
+        buf += (make_string(" \n %d, time: %d pos: %s ", i, svp.dwTime, get_string(svp.vPosition).c_str()));
+    }
+
+    return make_string("\n XFORM: %s \n position stack : %s \n, ", get_string(obj->XFORM()).c_str(), buf.c_str());
 }
 
-ENGINE_API std::string dbg_object_visual_geom_dump_string( const CObject *obj )
+ENGINE_API std::string dbg_object_visual_geom_dump_string(const CObject* obj)
 {
-	if( !obj || !obj->Visual() )
-			return std::string("");
-	const Fbox &box = obj->BoundingBox();
-	Fvector c;obj->Center( c );
+    if (!obj || !obj->Visual())
+        return std::string("");
+    const Fbox& box = obj->BoundingBox();
+    Fvector c;
+    obj->Center(c);
 
-	return make_string( "\n visual box: %s \n visual center: %s \n visual radius: %f ", 
-		get_string(box).c_str(), get_string( c ).c_str(), obj->Radius() );
+    return make_string("\n visual box: %s \n visual center: %s \n visual radius: %f ",
+        get_string(box).c_str(), get_string(c).c_str(), obj->Radius());
 }
 
 /*
-		struct 
-		{
-			u32	net_ID			:	16;
-			u32	bActiveCounter	:	8;
-			u32	bEnabled		:	1;
-			u32	bVisible		:	1;
-			u32	bDestroy		:	1;
-			u32	net_Local		:	1;
-			u32	net_Ready		:	1;
-			u32 net_SV_Update	:	1;
-			u32 crow			:	1;
-			u32	bPreDestroy		:	1;
-		};
-			u32									dbg_update_cl;
-#endif
-	u32									dwFrame_UpdateCL;
-	u32									dwFrame_AsCrow;
-*/
-ENGINE_API std::string dbg_object_props_dump_string( const CObject *obj )
+ struct
+ {
+ u32 net_ID : 16;
+ u32 bActiveCounter : 8;
+ u32 bEnabled : 1;
+ u32 bVisible : 1;
+ u32 bDestroy : 1;
+ u32 net_Local : 1;
+ u32 net_Ready : 1;
+ u32 net_SV_Update : 1;
+ u32 crow : 1;
+ u32 bPreDestroy : 1;
+ };
+ u32 dbg_update_cl;
+ #endif
+ u32 dwFrame_UpdateCL;
+ u32 dwFrame_AsCrow;
+ */
+ENGINE_API std::string dbg_object_props_dump_string(const CObject* obj)
 {
-	if( !obj )
-		return  std::string("");
-	CObject::ObjectProperties props;
-	obj->DBGGetProps( props );
+    if (!obj)
+        return std::string("");
+    CObject::ObjectProperties props;
+    obj->DBGGetProps(props);
 
-	return make_string( " net_ID :%d, bActiveCounter :%d, bEnabled :%s, bVisible :%s, bDestroy :%s, \n net_Local %s, net_Ready :%s, net_SV_Update :%s, crow :%s, bPreDestroy : %s ", 
-		props.net_ID, props.bActiveCounter, get_string(bool (!!props.bEnabled ) ).c_str(), get_string(bool (!!props.bVisible ) ).c_str(), 
-		get_string(bool (!!props.bDestroy ) ).c_str() , get_string(bool (!!props.net_Local ) ).c_str(), get_string( bool (!!props.net_Ready ) ).c_str(),
-		get_string(bool (!!props.net_SV_Update ) ).c_str(), get_string( bool (!!props.crow ) ).c_str(), get_string( bool (!!props.bPreDestroy ) ).c_str() 
-		)
-		+
-		make_string( "\n dbg_update_cl: %d, dwFrame_UpdateCL: %d, dwFrame_AsCrow :%d, Device.dwFrame :%d, Device.dwTimeGlobal: %d  \n",
-		obj->dbg_update_cl, obj->dwFrame_UpdateCL, obj->dwFrame_AsCrow, Device.dwFrame, Device.dwTimeGlobal );
+    return make_string(" net_ID :%d, bActiveCounter :%d, bEnabled :%s, bVisible :%s, bDestroy :%s, \n net_Local %s, net_Ready :%s, net_SV_Update :%s, crow :%s, bPreDestroy : %s ",
+        props.net_ID, props.bActiveCounter, get_string(bool(!!props.bEnabled)).c_str(), get_string(bool(!!props.bVisible)).c_str(),
+        get_string(bool(!!props.bDestroy)).c_str(), get_string(bool(!!props.net_Local)).c_str(), get_string(bool(!!props.net_Ready)).c_str(),
+        get_string(bool(!!props.net_SV_Update)).c_str(), get_string(bool(!!props.crow)).c_str(), get_string(bool(!!props.bPreDestroy)).c_str()
+        )
+        +
+        make_string("\n dbg_update_cl: %d, dwFrame_UpdateCL: %d, dwFrame_AsCrow :%d, Device.dwFrame :%d, Device.dwTimeGlobal: %d \n",
+        obj->dbg_update_cl, obj->dwFrame_UpdateCL, obj->dwFrame_AsCrow, Device.dwFrame, Device.dwTimeGlobal);
 }
-ENGINE_API std::string dbg_object_full_dump_string( const CObject *obj )
+ENGINE_API std::string dbg_object_full_dump_string(const CObject* obj)
 {
-	return	dbg_object_base_dump_string( obj ) + 
-			dbg_object_props_dump_string( obj )+
-			dbg_object_poses_dump_string( obj ) +
-			dbg_object_visual_geom_dump_string( obj );
-			 
+    return dbg_object_base_dump_string(obj) +
+        dbg_object_props_dump_string(obj) +
+        dbg_object_poses_dump_string(obj) +
+        dbg_object_visual_geom_dump_string(obj);
+
 }
-ENGINE_API std::string dbg_object_full_capped_dump_string( const CObject *obj )
+ENGINE_API std::string dbg_object_full_capped_dump_string(const CObject* obj)
 {
-	return	std::string("\n object dump: \n" ) +
-			dbg_object_full_dump_string( obj );
+    return std::string("\n object dump: \n") +
+        dbg_object_full_dump_string(obj);
 }
 #endif
diff --git a/src/xrEngine/ObjectDump.h b/src/xrEngine/ObjectDump.h
index c4c40644545..e9f7bfdfa0b 100644
--- a/src/xrEngine/ObjectDump.h
+++ b/src/xrEngine/ObjectDump.h
@@ -1,10 +1,10 @@
 #pragma once
 #ifdef DEBUG
 
-ENGINE_API std::string dbg_object_base_dump_string( const CObject *obj );
-ENGINE_API std::string dbg_object_poses_dump_string( const CObject *obj );
-ENGINE_API std::string dbg_object_visual_geom_dump_string( const CObject *obj );
-ENGINE_API std::string dbg_object_props_dump_string( const CObject *obj );
-ENGINE_API std::string dbg_object_full_dump_string( const CObject *obj );
-ENGINE_API std::string dbg_object_full_capped_dump_string( const CObject *obj );
+ENGINE_API std::string dbg_object_base_dump_string(const CObject* obj);
+ENGINE_API std::string dbg_object_poses_dump_string(const CObject* obj);
+ENGINE_API std::string dbg_object_visual_geom_dump_string(const CObject* obj);
+ENGINE_API std::string dbg_object_props_dump_string(const CObject* obj);
+ENGINE_API std::string dbg_object_full_dump_string(const CObject* obj);
+ENGINE_API std::string dbg_object_full_capped_dump_string(const CObject* obj);
 #endif
\ No newline at end of file
diff --git a/src/xrEngine/PS_instance.cpp b/src/xrEngine/PS_instance.cpp
index a66d3a3c350..5b6dc03fa41 100644
--- a/src/xrEngine/PS_instance.cpp
+++ b/src/xrEngine/PS_instance.cpp
@@ -7,58 +7,58 @@
 #include "ps_instance.h"
 #include "IGame_Persistent.h"
 
-CPS_Instance::CPS_Instance			(bool destroy_on_game_load)	:
-	ISpatial				(g_SpatialSpace),
-	m_destroy_on_game_load	(destroy_on_game_load)
+CPS_Instance::CPS_Instance(bool destroy_on_game_load) :
+    ISpatial(g_SpatialSpace),
+    m_destroy_on_game_load(destroy_on_game_load)
 {
-	g_pGamePersistent->ps_active.insert		(this);
-	renderable.pROS_Allowed					= FALSE;
+    g_pGamePersistent->ps_active.insert(this);
+    renderable.pROS_Allowed = FALSE;
 
-	m_iLifeTime								= int_max;
-	m_bAutoRemove							= TRUE;
-	m_bDead									= FALSE;
+    m_iLifeTime = int_max;
+    m_bAutoRemove = TRUE;
+    m_bDead = FALSE;
 }
-extern ENGINE_API BOOL						g_bRendering; 
+extern ENGINE_API BOOL g_bRendering;
 
 //----------------------------------------------------
-CPS_Instance::~CPS_Instance					()
+CPS_Instance::~CPS_Instance()
 {
-	VERIFY									(!g_bRendering);
-	xr_set::iterator it		= g_pGamePersistent->ps_active.find(this);
-	VERIFY									(it!=g_pGamePersistent->ps_active.end());
-	g_pGamePersistent->ps_active.erase		(it);
+    VERIFY(!g_bRendering);
+    xr_set::iterator it = g_pGamePersistent->ps_active.find(this);
+    VERIFY(it != g_pGamePersistent->ps_active.end());
+    g_pGamePersistent->ps_active.erase(it);
 
-	xr_vector::iterator it2	= std::find( g_pGamePersistent->ps_destroy.begin(),
-													g_pGamePersistent->ps_destroy.end(), this);
+    xr_vector::iterator it2 = std::find(g_pGamePersistent->ps_destroy.begin(),
+            g_pGamePersistent->ps_destroy.end(), this);
 
-	VERIFY									(it2==g_pGamePersistent->ps_destroy.end());
+    VERIFY(it2 == g_pGamePersistent->ps_destroy.end());
 
-	spatial_unregister						();
-	shedule_unregister						();
+    spatial_unregister();
+    shedule_unregister();
 }
 //----------------------------------------------------
-void CPS_Instance::shedule_Update	(u32 dt)
+void CPS_Instance::shedule_Update(u32 dt)
 {
-	if (renderable.pROS)			::Render->ros_destroy	(renderable.pROS);	//. particles doesn't need ROS
+    if (renderable.pROS) ::Render->ros_destroy(renderable.pROS); //. particles doesn't need ROS
 
-	ISheduled::shedule_Update		(dt);
-	m_iLifeTime						-= dt;
+    ISheduled::shedule_Update(dt);
+    m_iLifeTime -= dt;
 
-	// remove???
-	if (m_bDead)					return;
-	if (m_bAutoRemove && m_iLifeTime<=0)
-		PSI_destroy					();
+    // remove???
+    if (m_bDead) return;
+    if (m_bAutoRemove && m_iLifeTime <= 0)
+        PSI_destroy();
 }
 //----------------------------------------------------
-void CPS_Instance::PSI_destroy		()
+void CPS_Instance::PSI_destroy()
 {
-	m_bDead								= TRUE;
-	m_iLifeTime							= 0;
-	g_pGamePersistent->ps_destroy.push_back	(this);
+    m_bDead = TRUE;
+    m_iLifeTime = 0;
+    g_pGamePersistent->ps_destroy.push_back(this);
 }
 //----------------------------------------------------
-void CPS_Instance::PSI_internal_delete		()
+void CPS_Instance::PSI_internal_delete()
 {
-	CPS_Instance*	self = this;
-	xr_delete		(self);
+    CPS_Instance* self = this;
+    xr_delete(self);
 }
diff --git a/src/xrEngine/PS_instance.h b/src/xrEngine/PS_instance.h
index bc8521e7381..f0736b55882 100644
--- a/src/xrEngine/PS_instance.h
+++ b/src/xrEngine/PS_instance.h
@@ -5,44 +5,44 @@
 #include "isheduled.h"
 #include "irenderable.h"
 
-class ENGINE_API CPS_Instance	:
-	public ISpatial,
-	public ISheduled,
-	public IRenderable
+class ENGINE_API CPS_Instance :
+    public ISpatial,
+    public ISheduled,
+    public IRenderable
 {
-	friend class			IGame_Persistent;
+    friend class IGame_Persistent;
 
-	template 
-	friend struct xr_special_free;
+    template 
+    friend struct xr_special_free;
 
 private:
-	bool					m_destroy_on_game_load;
+    bool m_destroy_on_game_load;
 
 protected:
-	int						m_iLifeTime			;
-	BOOL					m_bAutoRemove		;
-	BOOL					m_bDead				;
+    int m_iLifeTime;
+    BOOL m_bAutoRemove;
+    BOOL m_bDead;
 
 protected:
-	virtual					~CPS_Instance		();
-	virtual void			PSI_internal_delete	();
+    virtual ~CPS_Instance();
+    virtual void PSI_internal_delete();
 
 public:
-							CPS_Instance		(bool destroy_on_game_load);
+    CPS_Instance(bool destroy_on_game_load);
 
-	IC		const bool		&destroy_on_game_load() const				{	return m_destroy_on_game_load;	}
-	virtual void			PSI_destroy			();
-	IC BOOL					PSI_alive			()						{	return m_iLifeTime>0;				}
-	IC BOOL					PSI_IsAutomatic		()						{	return m_bAutoRemove;				}
-	IC void					PSI_SetLifeTime		(float life_time)		{	m_iLifeTime=iFloor(life_time*1000);	}
+    IC const bool& destroy_on_game_load() const { return m_destroy_on_game_load; }
+    virtual void PSI_destroy();
+    IC BOOL PSI_alive() { return m_iLifeTime > 0; }
+    IC BOOL PSI_IsAutomatic() { return m_bAutoRemove; }
+    IC void PSI_SetLifeTime(float life_time) { m_iLifeTime = iFloor(life_time * 1000); }
 
-	virtual void			Play				(bool bHudMode)	= 0;
-	virtual BOOL			Locked				()				{ return FALSE; }
+    virtual void Play(bool bHudMode) = 0;
+    virtual BOOL Locked() { return FALSE; }
 
-	virtual	shared_str		shedule_Name		() const		{ return shared_str("particle_instance"); };
+    virtual shared_str shedule_Name() const { return shared_str("particle_instance"); };
 
-	virtual void			shedule_Update		(u32 dt);
-	virtual	IRenderable*	dcast_Renderable	()				{ return this;	}
+    virtual void shedule_Update(u32 dt);
+    virtual IRenderable* dcast_Renderable() { return this; }
 };
 
 #endif
diff --git a/src/xrEngine/Properties.h b/src/xrEngine/Properties.h
index c1f3182f5a4..9f1272bf8b6 100644
--- a/src/xrEngine/Properties.h
+++ b/src/xrEngine/Properties.h
@@ -7,79 +7,80 @@
 // Parameter/Property specifications
 
 // *** FORMAT ***
-// u32	type
-// stringZ	name
-// []		data
+// u32 type
+// stringZ name
+// [] data
 
-enum	xrProperties
+enum xrProperties
 {
-	xrPID_MARKER	= 0,
-	xrPID_MATRIX,		// really only name(stringZ) is written into stream
-	xrPID_CONSTANT,		// really only name(stringZ) is written into stream
-	xrPID_TEXTURE,		// really only name(stringZ) is written into stream
-	xrPID_INTEGER,
-	xrPID_FLOAT,
-	xrPID_BOOL,
-	xrPID_TOKEN,
-	xrPID_CLSID,
-	xrPID_OBJECT,		// really only name(stringZ) is written into stream
-	xrPID_STRING,		// really only name(stringZ) is written into stream
-	xrPID_MARKER_TEMPLATE,
-	xrPID_FORCEDWORD=u32(-1)
+    xrPID_MARKER = 0,
+    xrPID_MATRIX, // really only name(stringZ) is written into stream
+    xrPID_CONSTANT, // really only name(stringZ) is written into stream
+    xrPID_TEXTURE, // really only name(stringZ) is written into stream
+    xrPID_INTEGER,
+    xrPID_FLOAT,
+    xrPID_BOOL,
+    xrPID_TOKEN,
+    xrPID_CLSID,
+    xrPID_OBJECT, // really only name(stringZ) is written into stream
+    xrPID_STRING, // really only name(stringZ) is written into stream
+    xrPID_MARKER_TEMPLATE,
+    xrPID_FORCEDWORD = u32(-1)
 };
 
-struct	xrP_Integer
+struct xrP_Integer
 {
-	int					value;
-	int					min;
-	int					max;
+    int value;
+    int min;
+    int max;
 
-	xrP_Integer() : value(0), min(0), max(255)	{}
+    xrP_Integer() : value(0), min(0), max(255) {}
 };
 
-struct	xrP_Float
+struct xrP_Float
 {
-	float				value;
-	float				min;
-	float				max;
+    float value;
+    float min;
+    float max;
 
-	xrP_Float()	: value(0), min(0), max(1)		{}
+    xrP_Float() : value(0), min(0), max(1) {}
 };
 
-struct	xrP_BOOL
+struct xrP_BOOL
 {
-	BOOL				value;
-	xrP_BOOL() : value(FALSE)					{}
+    BOOL value;
+    xrP_BOOL() : value(FALSE) {}
 };
 
-struct	xrP_TOKEN
+struct xrP_TOKEN
 {
-	struct Item {
-		u32			ID;
-		string64	str;
-	};
+    struct Item
+    {
+        u32 ID;
+        string64 str;
+    };
 
-	u32				IDselected;
-	u32				Count;
+    u32 IDselected;
+    u32 Count;
 
-	//--- elements:		(ID,string64)
+    //--- elements: (ID,string64)
 
-	xrP_TOKEN()	: IDselected(0), Count(0)		{}
+    xrP_TOKEN() : IDselected(0), Count(0) {}
 };
 
-struct	xrP_CLSID
+struct xrP_CLSID
 {
-	CLASS_ID			Selected;
-	u32				Count;
-	//--- elements:		(...)
+    CLASS_ID Selected;
+    u32 Count;
+    //--- elements: (...)
 
-	xrP_CLSID()	: Selected(0), Count(0)			{}
+    xrP_CLSID() : Selected(0), Count(0) {}
 };
 
-struct	xrP_Template
+struct xrP_Template
 {
-	u32				Type;
-	u32				Limit;
+    u32 Type;
+    u32 Limit;
 };
 
 // Base class
@@ -88,67 +89,67 @@ class CPropertyBase
 protected:
 
 public:
-	virtual 	LPCSTR		getName			()								= 0;
-	virtual		LPCSTR		getComment		()								= 0;
+    virtual LPCSTR getName() = 0;
+    virtual LPCSTR getComment() = 0;
 
-	virtual		void		Save			(IWriter&	fs)					= 0;
-	virtual		void		Load			(IReader&	fs, u16 version)	= 0;
+    virtual void Save(IWriter& fs) = 0;
+    virtual void Load(IReader& fs, u16 version) = 0;
 };
 
 // Writers
-IC void		xrPWRITE		(IWriter& fs, u32 ID, LPCSTR name, LPCVOID data, u32 size )
+IC void xrPWRITE(IWriter& fs, u32 ID, LPCSTR name, LPCVOID data, u32 size)
 {
-	fs.w_u32			(ID);
-	fs.w_stringZ		(name);
-	if (data && size)	fs.w(data,size);
+    fs.w_u32(ID);
+    fs.w_stringZ(name);
+    if (data && size) fs.w(data, size);
 }
-IC void		xrPWRITE_MARKER	(IWriter& fs, LPCSTR name)
+IC void xrPWRITE_MARKER(IWriter& fs, LPCSTR name)
 {
-	xrPWRITE	(fs,xrPID_MARKER,name,0,0);
+    xrPWRITE(fs, xrPID_MARKER, name, 0, 0);
 }
 
 #define xrPWRITE_PROP(FS,name,ID,data)\
 {\
-	xrPWRITE	(fs,ID,name,&data,sizeof(data));\
+ xrPWRITE (fs,ID,name,&data,sizeof(data));\
 }
 
 // Readers
-IC u32	xrPREAD			(IReader& fs)
+IC u32 xrPREAD(IReader& fs)
 {
-	u32 T		= fs.r_u32();
-	fs.skip_stringZ	();
-	return		T;
+    u32 T = fs.r_u32();
+    fs.skip_stringZ();
+    return T;
 }
-IC void		xrPREAD_MARKER	(IReader& fs)
+IC void xrPREAD_MARKER(IReader& fs)
 {
-	R_ASSERT(xrPID_MARKER==xrPREAD(fs));
+    R_ASSERT(xrPID_MARKER == xrPREAD(fs));
 }
 
 #define xrPREAD_PROP(fs,ID,data) \
 { \
-	R_ASSERT(ID==xrPREAD(fs)); fs.r(&data,sizeof(data)); \
-	switch (ID) \
-	{ \
-	case xrPID_TOKEN:	fs.advance(((xrP_TOKEN*)&data)->Count * sizeof(xrP_TOKEN::Item));	break; \
-	case xrPID_CLSID:	fs.advance(((xrP_CLSID*)&data)->Count * sizeof(CLASS_ID));			break; \
-	}; \
+ R_ASSERT(ID==xrPREAD(fs)); fs.r(&data,sizeof(data)); \
+ switch (ID) \
+ { \
+ case xrPID_TOKEN: fs.advance(((xrP_TOKEN*)&data)->Count * sizeof(xrP_TOKEN::Item)); break; \
+ case xrPID_CLSID: fs.advance(((xrP_CLSID*)&data)->Count * sizeof(CLASS_ID)); break; \
+ }; \
 }
 
 //template 
-//IC void		xrPWRITE_PROP	(IWriter& FS, LPCSTR name, u32 ID, T& data)
+//IC void xrPWRITE_PROP (IWriter& FS, LPCSTR name, u32 ID, T& data)
 //{
-//	xrPWRITE	(FS,ID,name,&data,sizeof(data));
+// xrPWRITE (FS,ID,name,&data,sizeof(data));
 //}
 
 //template 
-//IC void		xrPREAD_PROP	(IReader& FS, u32 ID, T& data)
+//IC void xrPREAD_PROP (IReader& FS, u32 ID, T& data)
 //{
-//	R_ASSERT(ID==xrPREAD(FS)); FS.Read(&data,sizeof(data));
-//	switch (ID)
-//	{
-//	case xrPID_TOKEN:	FS.Advance(((xrP_TOKEN*)&data)->Count * sizeof(xrP_TOKEN::Item));	break;
-//	case xrPID_CLSID:	FS.Advance(((xrP_CLSID*)&data)->Count * sizeof(CLASS_ID));			break;
-//	};
+// R_ASSERT(ID==xrPREAD(FS)); FS.Read(&data,sizeof(data));
+// switch (ID)
+// {
+// case xrPID_TOKEN: FS.Advance(((xrP_TOKEN*)&data)->Count * sizeof(xrP_TOKEN::Item)); break;
+// case xrPID_CLSID: FS.Advance(((xrP_CLSID*)&data)->Count * sizeof(CLASS_ID)); break;
+// };
 //}
 #pragma pack(pop)
 #endif // xrPROPERTIES_H
diff --git a/src/xrEngine/Rain.cpp b/src/xrEngine/Rain.cpp
index 1a1bed47053..55d7b6daeb9 100644
--- a/src/xrEngine/Rain.cpp
+++ b/src/xrEngine/Rain.cpp
@@ -6,481 +6,489 @@
 #include "environment.h"
 
 #ifdef _EDITOR
-    #include "ui_toolscustom.h"
+#include "ui_toolscustom.h"
 #else
-    #include "render.h"
-	#include "igame_level.h"
-	#include "../xrcdb/xr_area.h"
-	#include "xr_object.h"
+#include "render.h"
+#include "igame_level.h"
+#include "../xrcdb/xr_area.h"
+#include "xr_object.h"
 #endif
 
-//	Warning: duplicated in dxRainRender
-static const int	max_desired_items	= 2500;
-static const float	source_radius		= 12.5f;
-static const float	source_offset		= 40.f;
-static const float	max_distance		= source_offset*1.25f;
-static const float	sink_offset			= -(max_distance-source_offset);
-static const float	drop_length			= 5.f;
-static const float	drop_width			= 0.30f;
-static const float	drop_angle			= 3.0f;
-static const float	drop_max_angle		= deg2rad(10.f);
-static const float	drop_max_wind_vel	= 20.0f;
-static const float	drop_speed_min		= 40.f;
-static const float	drop_speed_max		= 80.f;
-
-const int	max_particles		= 1000;
-const int	particles_cache		= 400;
-const float particles_time		= .3f;
- 
+// Warning: duplicated in dxRainRender
+static const int max_desired_items = 2500;
+static const float source_radius = 12.5f;
+static const float source_offset = 40.f;
+static const float max_distance = source_offset*1.25f;
+static const float sink_offset = -(max_distance - source_offset);
+static const float drop_length = 5.f;
+static const float drop_width = 0.30f;
+static const float drop_angle = 3.0f;
+static const float drop_max_angle = deg2rad(10.f);
+static const float drop_max_wind_vel = 20.0f;
+static const float drop_speed_min = 40.f;
+static const float drop_speed_max = 80.f;
+
+const int max_particles = 1000;
+const int particles_cache = 400;
+const float particles_time = .3f;
+
 //////////////////////////////////////////////////////////////////////
 // Construction/Destruction
 //////////////////////////////////////////////////////////////////////
 
 CEffect_Rain::CEffect_Rain()
 {
-	state							= stIdle;
-	
-	snd_Ambient.create				("ambient\\rain",st_Effect,sg_Undefined);
-
-	//	Moced to p_Render constructor
-	/*
-	IReader*	F					= FS.r_open("$game_meshes$","dm\\rain.dm"); 
-	VERIFY3							(F,"Can't open file.","dm\\rain.dm");
-	DM_Drop							= ::Render->model_CreateDM		(F);
-
-	//
-	SH_Rain.create					("effects\\rain","fx\\fx_rain");
-	hGeom_Rain.create				(FVF::F_LIT, RCache.Vertex.Buffer(), RCache.QuadIB);
-	hGeom_Drops.create				(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1, RCache.Vertex.Buffer(), RCache.Index.Buffer());
-	*/
-	p_create						();
-	//FS.r_close						(F);
+    state = stIdle;
+
+    snd_Ambient.create("ambient\\rain", st_Effect, sg_Undefined);
+
+    // Moced to p_Render constructor
+    /*
+    IReader* F = FS.r_open("$game_meshes$","dm\\rain.dm");
+    VERIFY3 (F,"Can't open file.","dm\\rain.dm");
+    DM_Drop = ::Render->model_CreateDM (F);
+
+    //
+    SH_Rain.create ("effects\\rain","fx\\fx_rain");
+    hGeom_Rain.create (FVF::F_LIT, RCache.Vertex.Buffer(), RCache.QuadIB);
+    hGeom_Drops.create (D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1, RCache.Vertex.Buffer(), RCache.Index.Buffer());
+    */
+    p_create();
+    //FS.r_close (F);
 }
 
 CEffect_Rain::~CEffect_Rain()
 {
-	snd_Ambient.destroy				();
+    snd_Ambient.destroy();
 
-	// Cleanup
-	p_destroy						();
-	//	Moved to p_Render destructor
-	//::Render->model_Delete			(DM_Drop);
+    // Cleanup
+    p_destroy();
+    // Moved to p_Render destructor
+    //::Render->model_Delete (DM_Drop);
 }
 
 // Born
-void	CEffect_Rain::Born		(Item& dest, float radius)
+void CEffect_Rain::Born(Item& dest, float radius)
 {
-	Fvector		axis;	
-    axis.set			(0,-1,0);
-	float gust			= g_pGamePersistent->Environment().wind_strength_factor/10.f;
-	float k				= g_pGamePersistent->Environment().CurrentEnv->wind_velocity*gust/drop_max_wind_vel;
-	clamp				(k,0.f,1.f);
-	float	pitch		= drop_max_angle*k-PI_DIV_2;
-    axis.setHP			(g_pGamePersistent->Environment().CurrentEnv->wind_direction,pitch);
-    
-	Fvector&	view	= Device.vCameraPosition;
-	float		angle	= ::Random.randF	(0,PI_MUL_2);
-	float		dist	= ::Random.randF	(); dist = _sqrt(dist)*radius; 
-	float		x		= dist*_cos		(angle);
-	float		z		= dist*_sin		(angle);
-	dest.D.random_dir	(axis,deg2rad(drop_angle));
-	dest.P.set			(x+view.x-dest.D.x*source_offset,source_offset+view.y,z+view.z-dest.D.z*source_offset);
-//	dest.P.set			(x+view.x,height+view.y,z+view.z);
-	dest.fSpeed			= ::Random.randF	(drop_speed_min,drop_speed_max);
-
-	float height		= max_distance;
-	RenewItem			(dest,height,RayPick(dest.P,dest.D,height,collide::rqtBoth));
+    Fvector axis;
+    axis.set(0, -1, 0);
+    float gust = g_pGamePersistent->Environment().wind_strength_factor / 10.f;
+    float k = g_pGamePersistent->Environment().CurrentEnv->wind_velocity*gust / drop_max_wind_vel;
+    clamp(k, 0.f, 1.f);
+    float pitch = drop_max_angle*k - PI_DIV_2;
+    axis.setHP(g_pGamePersistent->Environment().CurrentEnv->wind_direction, pitch);
+
+    Fvector& view = Device.vCameraPosition;
+    float angle = ::Random.randF(0, PI_MUL_2);
+    float dist = ::Random.randF();
+    dist = _sqrt(dist)*radius;
+    float x = dist*_cos(angle);
+    float z = dist*_sin(angle);
+    dest.D.random_dir(axis, deg2rad(drop_angle));
+    dest.P.set(x + view.x - dest.D.x*source_offset, source_offset + view.y, z + view.z - dest.D.z*source_offset);
+    // dest.P.set (x+view.x,height+view.y,z+view.z);
+    dest.fSpeed = ::Random.randF(drop_speed_min, drop_speed_max);
+
+    float height = max_distance;
+    RenewItem(dest, height, RayPick(dest.P, dest.D, height, collide::rqtBoth));
 }
 
 BOOL CEffect_Rain::RayPick(const Fvector& s, const Fvector& d, float& range, collide::rq_target tgt)
 {
-	BOOL bRes 			= TRUE;
+    BOOL bRes = TRUE;
 #ifdef _EDITOR
-    Tools->RayPick		(s,d,range);
+    Tools->RayPick (s,d,range);
 #else
-	collide::rq_result	RQ;
-	CObject* E 			= g_pGameLevel->CurrentViewEntity();
-	bRes 				= g_pGameLevel->ObjectSpace.RayPick( s,d,range,tgt,RQ,E);	
-    if (bRes) range 	= RQ.range;
+    collide::rq_result RQ;
+    CObject* E = g_pGameLevel->CurrentViewEntity();
+    bRes = g_pGameLevel->ObjectSpace.RayPick(s, d, range, tgt, RQ, E);
+    if (bRes) range = RQ.range;
 #endif
     return bRes;
 }
 
 void CEffect_Rain::RenewItem(Item& dest, float height, BOOL bHit)
 {
-	dest.uv_set			= Random.randI(2);
-    if (bHit){
-		dest.dwTime_Life= Device.dwTimeGlobal + iFloor(1000.f*height/dest.fSpeed) - Device.dwTimeDelta;
-		dest.dwTime_Hit	= Device.dwTimeGlobal + iFloor(1000.f*height/dest.fSpeed) - Device.dwTimeDelta;
-		dest.Phit.mad	(dest.P,dest.D,height);
-	}else{
-		dest.dwTime_Life= Device.dwTimeGlobal + iFloor(1000.f*height/dest.fSpeed) - Device.dwTimeDelta;
-		dest.dwTime_Hit	= Device.dwTimeGlobal + iFloor(2*1000.f*height/dest.fSpeed)-Device.dwTimeDelta;
-		dest.Phit.set	(dest.P);
-	}
+    dest.uv_set = Random.randI(2);
+    if (bHit)
+    {
+        dest.dwTime_Life = Device.dwTimeGlobal + iFloor(1000.f*height / dest.fSpeed) - Device.dwTimeDelta;
+        dest.dwTime_Hit = Device.dwTimeGlobal + iFloor(1000.f*height / dest.fSpeed) - Device.dwTimeDelta;
+        dest.Phit.mad(dest.P, dest.D, height);
+    }
+    else
+    {
+        dest.dwTime_Life = Device.dwTimeGlobal + iFloor(1000.f*height / dest.fSpeed) - Device.dwTimeDelta;
+        dest.dwTime_Hit = Device.dwTimeGlobal + iFloor(2 * 1000.f*height / dest.fSpeed) - Device.dwTimeDelta;
+        dest.Phit.set(dest.P);
+    }
 }
 
-void	CEffect_Rain::OnFrame	()
+void CEffect_Rain::OnFrame()
 {
 #ifndef _EDITOR
-	if (!g_pGameLevel)			return;
+    if (!g_pGameLevel) return;
 #endif
 
 #ifdef DEDICATED_SERVER
-	return;
+    return;
 #endif
 
-	// Parse states
-	float	factor				= g_pGamePersistent->Environment().CurrentEnv->rain_density;
-	static float hemi_factor	= 0.f;
+    // Parse states
+    float factor = g_pGamePersistent->Environment().CurrentEnv->rain_density;
+    static float hemi_factor = 0.f;
 #ifndef _EDITOR
-	CObject* E 					= g_pGameLevel->CurrentViewEntity();
-	if (E&&E->renderable_ROS())
-	{
-//		hemi_factor				= 1.f-2.0f*(0.3f-_min(_min(1.f,E->renderable_ROS()->get_luminocity_hemi()),0.3f));
-		float* hemi_cube		= E->renderable_ROS()->get_luminocity_hemi_cube();
-		float hemi_val			= _max(hemi_cube[0],hemi_cube[1]);
-		hemi_val				= _max(hemi_val, hemi_cube[2]);
-		hemi_val				= _max(hemi_val, hemi_cube[3]);
-		hemi_val				= _max(hemi_val, hemi_cube[5]);
-		
-//		float f					= 0.9f*hemi_factor + 0.1f*hemi_val;
-		float f					= hemi_val;
-		float t					= Device.fTimeDelta;
-		clamp					(t, 0.001f, 1.0f);
-		hemi_factor				= hemi_factor*(1.0f-t) + f*t;
-	}
+    CObject* E = g_pGameLevel->CurrentViewEntity();
+    if (E&&E->renderable_ROS())
+    {
+        // hemi_factor = 1.f-2.0f*(0.3f-_min(_min(1.f,E->renderable_ROS()->get_luminocity_hemi()),0.3f));
+        float* hemi_cube = E->renderable_ROS()->get_luminocity_hemi_cube();
+        float hemi_val = _max(hemi_cube[0], hemi_cube[1]);
+        hemi_val = _max(hemi_val, hemi_cube[2]);
+        hemi_val = _max(hemi_val, hemi_cube[3]);
+        hemi_val = _max(hemi_val, hemi_cube[5]);
+
+        // float f = 0.9f*hemi_factor + 0.1f*hemi_val;
+        float f = hemi_val;
+        float t = Device.fTimeDelta;
+        clamp(t, 0.001f, 1.0f);
+        hemi_factor = hemi_factor*(1.0f - t) + f*t;
+    }
 #endif
 
-	switch (state)
-	{
-	case stIdle:		
-		if (factorRender(*this);
-
-	/*
-	float	factor				= g_pGamePersistent->Environment().CurrentEnv->rain_density;
-	if (factorEnvironment().CurrentEnv->rain_color;
-	u32			u_rain_color	= color_rgba_f(f_rain_color.x,f_rain_color.y,f_rain_color.z,factor_visual);
-
-	// born _new_ if needed
-	float	b_radius_wrap_sqr	= _sqr((source_radius+.5f));
-	if (items.size()Render(*this);
+
+    /*
+    float factor = g_pGamePersistent->Environment().CurrentEnv->rain_density;
+    if (factorEnvironment().CurrentEnv->rain_color;
+    u32 u_rain_color = color_rgba_f(f_rain_color.x,f_rain_color.y,f_rain_color.z,factor_visual);
+
+    // born _new_ if needed
+    float b_radius_wrap_sqr = _sqr((source_radius+.5f));
+    if (items.size()vb_stride,vOffset);
-	FVF::LIT	*start		= verts;
-	const Fvector&	vEye	= Device.vCameraPosition;
-	for (u32 I=0; ITEST1.Begin();
-		Fvector	wdir;	wdir.set(one.P.x-vEye.x,0,one.P.z-vEye.z);
-		float	wlen	= wdir.square_magnitude();
-		if (wlen>b_radius_wrap_sqr)	{
-			wlen		= _sqrt(wlen);
-//.			Device.Statistic->TEST3.Begin();
-			if ((one.P.y-vEye.y)TEST3.End();
-		}
-		Device.Statistic->TEST1.End();
-
-		// Build line
-		Fvector&	pos_head	= one.P;
-		Fvector		pos_trail;	pos_trail.mad	(pos_head,one.D,-drop_length*factor_visual);
-		
-		// Culling
-		Fvector sC,lineD;	float sR; 
-		sC.sub			(pos_head,pos_trail);
-		lineD.normalize	(sC);
-		sC.mul			(.5f);
-		sR				= sC.magnitude();
-		sC.add			(pos_trail);
-		if (!::Render->ViewBase.testSphere_dirty(sC,sR))	continue;
-		
-		static Fvector2 UV[2][4]={
-			{{0,1},{0,0},{1,1},{1,0}},
-			{{1,0},{1,1},{0,0},{0,1}}
-		};
-
-		// Everything OK - build vertices
-		Fvector	P,lineTop,camDir;
-		camDir.sub			(sC,vEye);
-		camDir.normalize	();
-		lineTop.crossproduct(camDir,lineD);
-		float w = drop_width;
-		u32 s	= one.uv_set;
-		P.mad(pos_trail,lineTop,-w);	verts->set(P,u_rain_color,UV[s][0].x,UV[s][0].y);	verts++;
-		P.mad(pos_trail,lineTop,w);		verts->set(P,u_rain_color,UV[s][1].x,UV[s][1].y);	verts++;
-		P.mad(pos_head, lineTop,-w);	verts->set(P,u_rain_color,UV[s][2].x,UV[s][2].y);	verts++;
-		P.mad(pos_head, lineTop,w);		verts->set(P,u_rain_color,UV[s][3].x,UV[s][3].y);	verts++;
-	}
-	u32 vCount					= (u32)(verts-start);
-	RCache.Vertex.Unlock		(vCount,hGeom_Rain->vb_stride);
-	
-	// Render if needed
-	if (vCount)	{
-		HW.pDevice->SetRenderState	(D3DRS_CULLMODE,D3DCULL_NONE);
-		RCache.set_xform_world		(Fidentity);
-		RCache.set_Shader			(SH_Rain);
-		RCache.set_Geometry			(hGeom_Rain);
-		RCache.Render				(D3DPT_TRIANGLELIST,vOffset,0,vCount,0,vCount/2);
-		HW.pDevice->SetRenderState	(D3DRS_CULLMODE,D3DCULL_CCW);
-	}
-	
-	// Particles
-	Particle*	P		= particle_active;
-	if (0==P)			return;
-	
-	{
-		float	dt				= Device.fTimeDelta;
-		_IndexStream& _IS		= RCache.Index;
-		RCache.set_Shader		(DM_Drop->shader);
-		
-		Fmatrix					mXform,mScale;
-		int						pcount  = 0;
-		u32						v_offset,i_offset;
-		u32						vCount_Lock		= particles_cache*DM_Drop->number_vertices;
-		u32						iCount_Lock		= particles_cache*DM_Drop->number_indices;
-		IRender_DetailModel::fvfVertexOut* v_ptr= (IRender_DetailModel::fvfVertexOut*) RCache.Vertex.Lock	(vCount_Lock, hGeom_Drops->vb_stride, v_offset);
-		u16*					i_ptr			= _IS.Lock													(iCount_Lock, i_offset);
-		while (P)	{
-			Particle*	next	=	P->next;
-			
-			// Update
-			// P can be zero sometimes and it crashes
-			P->time				-=	dt;
-			if (P->time<0)	{
-				p_free			(P);
-				P				=	next;
-				continue;
-			}
-
-			// Render
-			if (::Render->ViewBase.testSphere_dirty(P->bounds.P, P->bounds.R))
-			{
-				// Build matrix
-				float scale			=	P->time / particles_time;
-				mScale.scale		(scale,scale,scale);
-				mXform.mul_43		(P->mXForm,mScale);
-				
-				// XForm verts
-				DM_Drop->transfer	(mXform,v_ptr,u_rain_color,i_ptr,pcount*DM_Drop->number_vertices);
-				v_ptr			+=	DM_Drop->number_vertices;
-				i_ptr			+=	DM_Drop->number_indices;
-				pcount			++;
-
-				if (pcount >= particles_cache) {
-					// flush
-					u32	dwNumPrimitives		= iCount_Lock/3;
-					RCache.Vertex.Unlock	(vCount_Lock,hGeom_Drops->vb_stride);
-					_IS.Unlock				(iCount_Lock);
-					RCache.set_Geometry		(hGeom_Drops);
-					RCache.Render			(D3DPT_TRIANGLELIST,v_offset, 0,vCount_Lock,i_offset,dwNumPrimitives);
-					
-					v_ptr					= (IRender_DetailModel::fvfVertexOut*)			RCache.Vertex.Lock	(vCount_Lock, hGeom_Drops->vb_stride, v_offset);
-					i_ptr					= _IS.Lock										(iCount_Lock, i_offset);
-					
-					pcount	= 0;
-				}
-			}
-			
-			P = next;
-		}
-
-		// Flush if needed
-		vCount_Lock						= pcount*DM_Drop->number_vertices;
-		iCount_Lock						= pcount*DM_Drop->number_indices;
-		u32	dwNumPrimitives				= iCount_Lock/3;
-		RCache.Vertex.Unlock			(vCount_Lock,hGeom_Drops->vb_stride);
-		_IS.Unlock						(iCount_Lock);
-		if (pcount)	{
-			RCache.set_Geometry		(hGeom_Drops);
-			RCache.Render			(D3DPT_TRIANGLELIST,v_offset,0,vCount_Lock,i_offset,dwNumPrimitives);
-		}
-	}
-	*/
+
+    // perform update
+    u32 vOffset;
+    FVF::LIT *verts = (FVF::LIT *) RCache.Vertex.Lock(desired_items*4,hGeom_Rain->vb_stride,vOffset);
+    FVF::LIT *start = verts;
+    const Fvector& vEye = Device.vCameraPosition;
+    for (u32 I=0; ITEST1.Begin();
+    Fvector wdir; wdir.set(one.P.x-vEye.x,0,one.P.z-vEye.z);
+    float wlen = wdir.square_magnitude();
+    if (wlen>b_radius_wrap_sqr) {
+    wlen = _sqrt(wlen);
+    //. Device.Statistic->TEST3.Begin();
+    if ((one.P.y-vEye.y)TEST3.End();
+    }
+    Device.Statistic->TEST1.End();
+
+    // Build line
+    Fvector& pos_head = one.P;
+    Fvector pos_trail; pos_trail.mad (pos_head,one.D,-drop_length*factor_visual);
+
+    // Culling
+    Fvector sC,lineD; float sR;
+    sC.sub (pos_head,pos_trail);
+    lineD.normalize (sC);
+    sC.mul (.5f);
+    sR = sC.magnitude();
+    sC.add (pos_trail);
+    if (!::Render->ViewBase.testSphere_dirty(sC,sR)) continue;
+
+    static Fvector2 UV[2][4]={
+    {{0,1},{0,0},{1,1},{1,0}},
+    {{1,0},{1,1},{0,0},{0,1}}
+    };
+
+    // Everything OK - build vertices
+    Fvector P,lineTop,camDir;
+    camDir.sub (sC,vEye);
+    camDir.normalize ();
+    lineTop.crossproduct(camDir,lineD);
+    float w = drop_width;
+    u32 s = one.uv_set;
+    P.mad(pos_trail,lineTop,-w); verts->set(P,u_rain_color,UV[s][0].x,UV[s][0].y); verts++;
+    P.mad(pos_trail,lineTop,w); verts->set(P,u_rain_color,UV[s][1].x,UV[s][1].y); verts++;
+    P.mad(pos_head, lineTop,-w); verts->set(P,u_rain_color,UV[s][2].x,UV[s][2].y); verts++;
+    P.mad(pos_head, lineTop,w); verts->set(P,u_rain_color,UV[s][3].x,UV[s][3].y); verts++;
+    }
+    u32 vCount = (u32)(verts-start);
+    RCache.Vertex.Unlock (vCount,hGeom_Rain->vb_stride);
+
+    // Render if needed
+    if (vCount) {
+    HW.pDevice->SetRenderState (D3DRS_CULLMODE,D3DCULL_NONE);
+    RCache.set_xform_world (Fidentity);
+    RCache.set_Shader (SH_Rain);
+    RCache.set_Geometry (hGeom_Rain);
+    RCache.Render (D3DPT_TRIANGLELIST,vOffset,0,vCount,0,vCount/2);
+    HW.pDevice->SetRenderState (D3DRS_CULLMODE,D3DCULL_CCW);
+    }
+
+    // Particles
+    Particle* P = particle_active;
+    if (0==P) return;
+
+    {
+    float dt = Device.fTimeDelta;
+    _IndexStream& _IS = RCache.Index;
+    RCache.set_Shader (DM_Drop->shader);
+
+    Fmatrix mXform,mScale;
+    int pcount = 0;
+    u32 v_offset,i_offset;
+    u32 vCount_Lock = particles_cache*DM_Drop->number_vertices;
+    u32 iCount_Lock = particles_cache*DM_Drop->number_indices;
+    IRender_DetailModel::fvfVertexOut* v_ptr= (IRender_DetailModel::fvfVertexOut*) RCache.Vertex.Lock (vCount_Lock, hGeom_Drops->vb_stride, v_offset);
+    u16* i_ptr = _IS.Lock (iCount_Lock, i_offset);
+    while (P) {
+    Particle* next = P->next;
+
+    // Update
+    // P can be zero sometimes and it crashes
+    P->time -= dt;
+    if (P->time<0) {
+    p_free (P);
+    P = next;
+    continue;
+    }
+
+    // Render
+    if (::Render->ViewBase.testSphere_dirty(P->bounds.P, P->bounds.R))
+    {
+    // Build matrix
+    float scale = P->time / particles_time;
+    mScale.scale (scale,scale,scale);
+    mXform.mul_43 (P->mXForm,mScale);
+
+    // XForm verts
+    DM_Drop->transfer (mXform,v_ptr,u_rain_color,i_ptr,pcount*DM_Drop->number_vertices);
+    v_ptr += DM_Drop->number_vertices;
+    i_ptr += DM_Drop->number_indices;
+    pcount ++;
+
+    if (pcount >= particles_cache) {
+    // flush
+    u32 dwNumPrimitives = iCount_Lock/3;
+    RCache.Vertex.Unlock (vCount_Lock,hGeom_Drops->vb_stride);
+    _IS.Unlock (iCount_Lock);
+    RCache.set_Geometry (hGeom_Drops);
+    RCache.Render (D3DPT_TRIANGLELIST,v_offset, 0,vCount_Lock,i_offset,dwNumPrimitives);
+
+    v_ptr = (IRender_DetailModel::fvfVertexOut*) RCache.Vertex.Lock (vCount_Lock, hGeom_Drops->vb_stride, v_offset);
+    i_ptr = _IS.Lock (iCount_Lock, i_offset);
+
+    pcount = 0;
+    }
+    }
+
+    P = next;
+    }
+
+    // Flush if needed
+    vCount_Lock = pcount*DM_Drop->number_vertices;
+    iCount_Lock = pcount*DM_Drop->number_indices;
+    u32 dwNumPrimitives = iCount_Lock/3;
+    RCache.Vertex.Unlock (vCount_Lock,hGeom_Drops->vb_stride);
+    _IS.Unlock (iCount_Lock);
+    if (pcount) {
+    RCache.set_Geometry (hGeom_Drops);
+    RCache.Render (D3DPT_TRIANGLELIST,v_offset,0,vCount_Lock,i_offset,dwNumPrimitives);
+    }
+    }
+    */
 }
 
 // startup _new_ particle system
-void	CEffect_Rain::Hit		(Fvector& pos)
+void CEffect_Rain::Hit(Fvector& pos)
 {
-	if (0!=::Random.randI(2))	return;
-	Particle*	P	= p_allocate();
-	if (0==P)	return;
+    if (0 != ::Random.randI(2)) return;
+    Particle* P = p_allocate();
+    if (0 == P) return;
 
-	const Fsphere &bv_sphere = m_pRender->GetDropBounds();
+    const Fsphere& bv_sphere = m_pRender->GetDropBounds();
 
-	P->time						= particles_time;
-	P->mXForm.rotateY			(::Random.randF(PI_MUL_2));
-	P->mXForm.translate_over	(pos);
-	P->mXForm.transform_tiny	(P->bounds.P, bv_sphere.P);
-	P->bounds.R					= bv_sphere.R;
+    P->time = particles_time;
+    P->mXForm.rotateY(::Random.randF(PI_MUL_2));
+    P->mXForm.translate_over(pos);
+    P->mXForm.transform_tiny(P->bounds.P, bv_sphere.P);
+    P->bounds.R = bv_sphere.R;
 
 }
 
 // initialize particles pool
-void CEffect_Rain::p_create		()
+void CEffect_Rain::p_create()
 {
-	// pool
-	particle_pool.resize	(max_particles);
-	for (u32 it=0; itprev;	P->prev = NULL;
-	Particle*	next		= P->next;	P->next	= NULL;
-	if (prev) prev->next	= next;
-	if (next) next->prev	= prev;
-	if (LST==P)	LST			= next;
+    VERIFY(P);
+    Particle* prev = P->prev;
+    P->prev = NULL;
+    Particle* next = P->next;
+    P->next = NULL;
+    if (prev) prev->next = next;
+    if (next) next->prev = prev;
+    if (LST == P) LST = next;
 }
 
 // insert node at the top of the head
-void CEffect_Rain::p_insert	(Particle* P, Particle* &LST)
+void CEffect_Rain::p_insert(Particle* P, Particle*& LST)
 {
-	VERIFY		(P);
-	P->prev					= 0;
-	P->next					= LST;
-	if (LST)	LST->prev	= P;
-	LST						= P;
+    VERIFY(P);
+    P->prev = 0;
+    P->next = LST;
+    if (LST) LST->prev = P;
+    LST = P;
 }
 
 // determine size of _list_
-int CEffect_Rain::p_size	(Particle* P)
+int CEffect_Rain::p_size(Particle* P)
 {
-	if (0==P)	return 0;
-	int cnt = 0;
-	while (P)	{
-		P	=	P->next;
-		cnt +=	1;
-	}
-	return cnt;
+    if (0 == P) return 0;
+    int cnt = 0;
+    while (P)
+    {
+        P = P->next;
+        cnt += 1;
+    }
+    return cnt;
 }
 
 // alloc node
-CEffect_Rain::Particle*	CEffect_Rain::p_allocate	()
+CEffect_Rain::Particle* CEffect_Rain::p_allocate()
 {
-	Particle*	P			= particle_idle;
-	if (0==P)				return NULL;
-	p_remove	(P,particle_idle);
-	p_insert	(P,particle_active);
-	return		P;
+    Particle* P = particle_idle;
+    if (0 == P) return NULL;
+    p_remove(P, particle_idle);
+    p_insert(P, particle_active);
+    return P;
 }
 
 // xr_free node
-void	CEffect_Rain::p_free(Particle* P)
+void CEffect_Rain::p_free(Particle* P)
 {
-	p_remove	(P,particle_active);
-	p_insert	(P,particle_idle);
+    p_remove(P, particle_active);
+    p_insert(P, particle_idle);
 }
diff --git a/src/xrEngine/Rain.h b/src/xrEngine/Rain.h
index cb9aef54612..f1cdae81b17 100644
--- a/src/xrEngine/Rain.h
+++ b/src/xrEngine/Rain.h
@@ -16,80 +16,80 @@ class ENGINE_API IRender_DetailModel;
 //
 class ENGINE_API CEffect_Rain
 {
-	friend class dxRainRender;
+    friend class dxRainRender;
 private:
-	struct	Item
-	{
-		Fvector			P;
-		Fvector			Phit;
-		Fvector			D;
-		float			fSpeed;
-		u32				dwTime_Life;
-		u32				dwTime_Hit;
-		u32				uv_set;
-		void			invalidate	()
-		{
-			dwTime_Life	= 0;
-		}
-	};
-	struct	Particle
-	{
-		Particle		*next,*prev;
-		Fmatrix			mXForm;
-		Fsphere			bounds;
-		float			time;
-	};
-	enum	States
-	{
-		stIdle		= 0,
-		stWorking
-	};
+    struct Item
+    {
+        Fvector P;
+        Fvector Phit;
+        Fvector D;
+        float fSpeed;
+        u32 dwTime_Life;
+        u32 dwTime_Hit;
+        u32 uv_set;
+        void invalidate()
+        {
+            dwTime_Life = 0;
+        }
+    };
+    struct Particle
+    {
+        Particle* next, *prev;
+        Fmatrix mXForm;
+        Fsphere bounds;
+        float time;
+    };
+    enum States
+    {
+        stIdle = 0,
+        stWorking
+    };
 private:
-	// Visualization	(rain) and (drops)
-	FactoryPtr	m_pRender;
-	/*
-	// Visualization	(rain)
-	ref_shader						SH_Rain;
-	ref_geom						hGeom_Rain;
+    // Visualization (rain) and (drops)
+    FactoryPtr m_pRender;
+    /*
+    // Visualization (rain)
+    ref_shader SH_Rain;
+    ref_geom hGeom_Rain;
 
-	// Visualization	(drops)
-	IRender_DetailModel*			DM_Drop;
-	ref_geom						hGeom_Drops;
-	*/
-	
-	// Data and logic
-	xr_vector					items;
-	States							state;
+    // Visualization (drops)
+    IRender_DetailModel* DM_Drop;
+    ref_geom hGeom_Drops;
+    */
 
-	// Particles
-	xr_vector				particle_pool;
-	Particle*						particle_active;
-	Particle*						particle_idle;
+    // Data and logic
+    xr_vector items;
+    States state;
 
-	// Sounds
-	ref_sound						snd_Ambient;
+    // Particles
+    xr_vector particle_pool;
+    Particle* particle_active;
+    Particle* particle_idle;
 
-	// Utilities
-	void							p_create		();
-	void							p_destroy		();
+    // Sounds
+    ref_sound snd_Ambient;
 
-	void							p_remove		(Particle* P, Particle* &LST);
-	void							p_insert		(Particle* P, Particle* &LST);
-	int								p_size			(Particle* LST);
-	Particle*						p_allocate		();
-	void							p_free			(Particle* P);
+    // Utilities
+    void p_create();
+    void p_destroy();
 
-	// Some methods
-	void							Born			(Item& dest, float radius);
-	void							Hit				(Fvector& pos);
-	BOOL							RayPick			(const Fvector& s, const Fvector& d, float& range, collide::rq_target tgt);
-	void							RenewItem		(Item& dest, float height, BOOL bHit);
+    void p_remove(Particle* P, Particle*& LST);
+    void p_insert(Particle* P, Particle*& LST);
+    int p_size(Particle* LST);
+    Particle* p_allocate();
+    void p_free(Particle* P);
+
+    // Some methods
+    void Born(Item& dest, float radius);
+    void Hit(Fvector& pos);
+    BOOL RayPick(const Fvector& s, const Fvector& d, float& range, collide::rq_target tgt);
+    void RenewItem(Item& dest, float height, BOOL bHit);
 public:
-									CEffect_Rain	();
-									~CEffect_Rain	();
+    CEffect_Rain();
+    ~CEffect_Rain();
 
-	void							Render			();
-	void							OnFrame			();
+    void Render();
+    void OnFrame();
 };
 
 #endif //RainH
diff --git a/src/xrEngine/Render.cpp b/src/xrEngine/Render.cpp
index f0462eab581..00ac77d9431 100644
--- a/src/xrEngine/Render.cpp
+++ b/src/xrEngine/Render.cpp
@@ -1,14 +1,16 @@
 #include "stdafx.h"
 #include "render.h"
 
-IRender_interface::~IRender_interface()		{};
+IRender_interface::~IRender_interface() {};
 
-//ENGINE_API	IRender_interface*	Render		= NULL;
+//ENGINE_API IRender_interface* Render = NULL;
 
 // resources
-IRender_Light::~IRender_Light	()			{	
-	::Render->light_destroy		(this	);
+IRender_Light::~IRender_Light()
+{
+    ::Render->light_destroy(this);
 }
-IRender_Glow::~IRender_Glow		()			{	
-	::Render->glow_destroy		(this	);	
+IRender_Glow::~IRender_Glow()
+{
+    ::Render->glow_destroy(this);
 }
diff --git a/src/xrEngine/Render.h b/src/xrEngine/Render.h
index 60cf09f910f..8c7d729cecf 100644
--- a/src/xrEngine/Render.h
+++ b/src/xrEngine/Render.h
@@ -12,292 +12,298 @@ typedef FactoryPtr wm_shader;
 //#include "../Include/xrRender/WallMarkArray.h"
 
 #ifdef _EDITOR
-//.    #error you cant include this file in borland
+//. #error you cant include this file in borland
 #endif
 // refs
-class ENGINE_API	IRenderable;
-//class ENGINE_API	IRenderVisual;
+class ENGINE_API IRenderable;
+//class ENGINE_API IRenderVisual;
 
-//class ENGINE_API	IBlender;
-//class ENGINE_API	CSkeletonWallmark;
-//class ENGINE_API	CKinematics;
-struct ENGINE_API	FSlideWindowItem;
+//class ENGINE_API IBlender;
+//class ENGINE_API CSkeletonWallmark;
+//class ENGINE_API CKinematics;
+struct ENGINE_API FSlideWindowItem;
 
-//	Igor
+// Igor
 class IRenderVisual;
 class IKinematics;
 class CGameFont;
 //class IRenderDetailModel;
 
 #ifndef _EDITOR
-extern const	float		fLightSmoothFactor;
+extern const float fLightSmoothFactor;
 #else
-const	float		fLightSmoothFactor = 4.f;
+const float fLightSmoothFactor = 4.f;
 #endif
 //////////////////////////////////////////////////////////////////////////
 // definition (Dynamic Light)
-class	ENGINE_API	IRender_Light	: public xr_resource									{
+class ENGINE_API IRender_Light : public xr_resource
+{
 public:
-	enum LT
-	{
-		DIRECT		= 0,
-		POINT		= 1,
-		SPOT		= 2,
-		OMNIPART	= 3,
-		REFLECTED	= 4,
-	};
+    enum LT
+    {
+        DIRECT = 0,
+        POINT = 1,
+        SPOT = 2,
+        OMNIPART = 3,
+        REFLECTED = 4,
+    };
 public:
-	virtual void					set_type			(LT type)							= 0;
-	virtual void					set_active			(bool)								= 0;
-	virtual bool					get_active			()									= 0;
-	virtual void					set_shadow			(bool)								= 0;
-	virtual void					set_volumetric		(bool)								= 0;
-	virtual void					set_volumetric_quality(float)							= 0;
-	virtual void					set_volumetric_intensity(float)							= 0;
-	virtual void					set_volumetric_distance(float)							= 0;
-	virtual void					set_indirect		(bool)								{};
-	virtual void					set_position		(const Fvector& P)					= 0;
-	virtual void					set_rotation		(const Fvector& D, const Fvector& R)= 0;
-	virtual void					set_cone			(float angle)						= 0;
-	virtual void					set_range			(float R)							= 0;
-	virtual void					set_virtual_size	(float R)							= 0;
-	virtual void					set_texture			(LPCSTR name)						= 0;
-	virtual void					set_color			(const Fcolor& C)					= 0;
-	virtual void					set_color			(float r, float g, float b)			= 0;
-	virtual void					set_hud_mode		(bool b)							= 0;
-	virtual bool					get_hud_mode		()									= 0;
-	virtual ~IRender_Light()		;
+    virtual void set_type(LT type) = 0;
+    virtual void set_active(bool) = 0;
+    virtual bool get_active() = 0;
+    virtual void set_shadow(bool) = 0;
+    virtual void set_volumetric(bool) = 0;
+    virtual void set_volumetric_quality(float) = 0;
+    virtual void set_volumetric_intensity(float) = 0;
+    virtual void set_volumetric_distance(float) = 0;
+    virtual void set_indirect(bool) {};
+    virtual void set_position(const Fvector& P) = 0;
+    virtual void set_rotation(const Fvector& D, const Fvector& R) = 0;
+    virtual void set_cone(float angle) = 0;
+    virtual void set_range(float R) = 0;
+    virtual void set_virtual_size(float R) = 0;
+    virtual void set_texture(LPCSTR name) = 0;
+    virtual void set_color(const Fcolor& C) = 0;
+    virtual void set_color(float r, float g, float b) = 0;
+    virtual void set_hud_mode(bool b) = 0;
+    virtual bool get_hud_mode() = 0;
+    virtual ~IRender_Light();
 };
-struct ENGINE_API		resptrcode_light	: public resptr_base
+struct ENGINE_API resptrcode_light : public resptr_base < IRender_Light >
 {
-	void				destroy			()				{ _set(NULL);						}
+    void destroy() { _set(NULL); }
 };
-typedef	resptr_core	ref_light;
+typedef resptr_core ref_light;
 
 //////////////////////////////////////////////////////////////////////////
 // definition (Dynamic Glow)
-class	ENGINE_API		IRender_Glow	: public xr_resource									{
+class ENGINE_API IRender_Glow : public xr_resource
+{
 public:
-	virtual void					set_active			(bool)								= 0;
-	virtual bool					get_active			()									= 0;
-	virtual void					set_position		(const Fvector& P)					= 0;
-	virtual void					set_direction		(const Fvector& P)					= 0;
-	virtual void					set_radius			(float R)							= 0;
-	virtual void					set_texture			(LPCSTR name)						= 0;
-	virtual void					set_color			(const Fcolor& C)					= 0;
-	virtual void					set_color			(float r, float g, float b)			= 0;
-	virtual ~IRender_Glow()			;
+    virtual void set_active(bool) = 0;
+    virtual bool get_active() = 0;
+    virtual void set_position(const Fvector& P) = 0;
+    virtual void set_direction(const Fvector& P) = 0;
+    virtual void set_radius(float R) = 0;
+    virtual void set_texture(LPCSTR name) = 0;
+    virtual void set_color(const Fcolor& C) = 0;
+    virtual void set_color(float r, float g, float b) = 0;
+    virtual ~IRender_Glow();
 };
-struct ENGINE_API		resptrcode_glow	: public resptr_base
+struct ENGINE_API resptrcode_glow : public resptr_base < IRender_Glow >
 {
-	void				destroy			()					{ _set(NULL);					}
+    void destroy() { _set(NULL); }
 };
-typedef	resptr_core		ref_glow;
+typedef resptr_core ref_glow;
 
 //////////////////////////////////////////////////////////////////////////
 // definition (Per-object render-specific data)
-class	ENGINE_API	IRender_ObjectSpecific		{
+class ENGINE_API IRender_ObjectSpecific
+{
 public:
-	enum mode
-	{
-		TRACE_LIGHTS	= (1<<0),
-		TRACE_SUN		= (1<<1),
-		TRACE_HEMI		= (1<<2),
-		TRACE_ALL		= (TRACE_LIGHTS|TRACE_SUN|TRACE_HEMI),
-	};
+    enum mode
+    {
+        TRACE_LIGHTS = (1 << 0),
+        TRACE_SUN = (1 << 1),
+        TRACE_HEMI = (1 << 2),
+        TRACE_ALL = (TRACE_LIGHTS | TRACE_SUN | TRACE_HEMI),
+    };
 public:
-	virtual	void						force_mode			(u32 mode)							= 0;
-	virtual float						get_luminocity		()									= 0;
-	virtual float						get_luminocity_hemi	()									= 0;
-	virtual float*						get_luminocity_hemi_cube		()									= 0;
+    virtual void force_mode(u32 mode) = 0;
+    virtual float get_luminocity() = 0;
+    virtual float get_luminocity_hemi() = 0;
+    virtual float* get_luminocity_hemi_cube() = 0;
 
-	virtual ~IRender_ObjectSpecific()	{};
+    virtual ~IRender_ObjectSpecific() {};
 };
 
 //////////////////////////////////////////////////////////////////////////
 // definition (Portal)
-class	ENGINE_API	IRender_Portal				{
+class ENGINE_API IRender_Portal
+{
 public:
-	virtual ~IRender_Portal()			{};
+    virtual ~IRender_Portal() {};
 };
 
 //////////////////////////////////////////////////////////////////////////
 // definition (Sector)
-class	ENGINE_API	IRender_Sector				{
+class ENGINE_API IRender_Sector
+{
 public:
-	virtual ~IRender_Sector()			{};
+    virtual ~IRender_Sector() {};
 };
 
 //////////////////////////////////////////////////////////////////////////
 // definition (Target)
-class	ENGINE_API	IRender_Target				{
+class ENGINE_API IRender_Target
+{
 public:
-	virtual	void					set_blur			(float	f)							= 0;
-	virtual	void					set_gray			(float	f)							= 0;
-	virtual void					set_duality_h		(float	f)							= 0;
-	virtual void					set_duality_v		(float	f)							= 0;
-	virtual void					set_noise			(float	f)							= 0;
-	virtual void					set_noise_scale		(float	f)							= 0;
-	virtual void					set_noise_fps		(float	f)							= 0;
-	virtual void					set_color_base		(u32	f)							= 0;
-	virtual void					set_color_gray		(u32	f)							= 0;
-	//virtual void					set_color_add		(u32	f)							= 0;
-	virtual void					set_color_add		(const Fvector	&f)					= 0;
-	virtual u32						get_width			()									= 0;
-	virtual u32						get_height			()									= 0;
-	virtual void					set_cm_imfluence	(float	f)							= 0;
-	virtual void					set_cm_interpolate	(float	f)							= 0;
-	virtual void					set_cm_textures		(const shared_str &tex0, const shared_str &tex1)= 0;
-	virtual ~IRender_Target()		{};
+    virtual void set_blur(float f) = 0;
+    virtual void set_gray(float f) = 0;
+    virtual void set_duality_h(float f) = 0;
+    virtual void set_duality_v(float f) = 0;
+    virtual void set_noise(float f) = 0;
+    virtual void set_noise_scale(float f) = 0;
+    virtual void set_noise_fps(float f) = 0;
+    virtual void set_color_base(u32 f) = 0;
+    virtual void set_color_gray(u32 f) = 0;
+    //virtual void set_color_add (u32 f) = 0;
+    virtual void set_color_add(const Fvector& f) = 0;
+    virtual u32 get_width() = 0;
+    virtual u32 get_height() = 0;
+    virtual void set_cm_imfluence(float f) = 0;
+    virtual void set_cm_interpolate(float f) = 0;
+    virtual void set_cm_textures(const shared_str& tex0, const shared_str& tex1) = 0;
+    virtual ~IRender_Target() {};
 };
 
 //////////////////////////////////////////////////////////////////////////
 // definition (Renderer)
-class	ENGINE_API	IRender_interface
+class ENGINE_API IRender_interface
 {
 public:
-	enum GenerationLevel
-	{
-		GENERATION_R1				= 81,
-		GENERATION_DX81				= 81,
-		GENERATION_R2				= 90,
-		GENERATION_DX90				= 90,
-		GENERATION_forcedword		= u32(-1)
-	};
-	enum ScreenshotMode
-	{
-		SM_NORMAL					= 0,		// jpeg,	name ignored
-		SM_FOR_CUBEMAP				= 1,		// tga,		name used as postfix
-		SM_FOR_GAMESAVE				= 2,		// dds/dxt1,name used as full-path
-		SM_FOR_LEVELMAP				= 3,		// tga,		name used as postfix (level_name)
-		SM_FOR_MPSENDING			= 4,
-		SM_forcedword				= u32(-1)
-	};
+    enum GenerationLevel
+    {
+        GENERATION_R1 = 81,
+        GENERATION_DX81 = 81,
+        GENERATION_R2 = 90,
+        GENERATION_DX90 = 90,
+        GENERATION_forcedword = u32(-1)
+    };
+    enum ScreenshotMode
+    {
+        SM_NORMAL = 0, // jpeg, name ignored
+        SM_FOR_CUBEMAP = 1, // tga, name used as postfix
+        SM_FOR_GAMESAVE = 2, // dds/dxt1,name used as full-path
+        SM_FOR_LEVELMAP = 3, // tga, name used as postfix (level_name)
+        SM_FOR_MPSENDING = 4,
+        SM_forcedword = u32(-1)
+    };
 public:
-	// options
-	s32								m_skinning;
-	s32								m_MSAASample;
+    // options
+    s32 m_skinning;
+    s32 m_MSAASample;
 
-	BENCH_SEC_SCRAMBLEMEMBER1
+    BENCH_SEC_SCRAMBLEMEMBER1
 
-	// data
-	CFrustum						ViewBase;
-	CFrustum*						View;
+    // data
+    CFrustum ViewBase;
+    CFrustum* View;
 public:
-	// feature level
-	virtual	GenerationLevel			get_generation			()											= 0;
-
-	virtual bool					is_sun_static			() =0;
-	virtual DWORD					get_dx_level			() =0;
-
-	// Loading / Unloading
-	virtual	void					create					()											= 0;
-	virtual	void					destroy					()											= 0;
-	virtual	void					reset_begin				()											= 0;
-	virtual	void					reset_end				()											= 0;
-
-	BENCH_SEC_SCRAMBLEVTBL1
-	BENCH_SEC_SCRAMBLEVTBL3
-
-	virtual	void					level_Load				(IReader*)									= 0;
-	virtual void					level_Unload			()											= 0;
-
-	//virtual IDirect3DBaseTexture9*	texture_load			(LPCSTR	fname, u32& msize)					= 0;
-			void					shader_option_skinning	(s32 mode)									{ m_skinning=mode;	}
-	virtual HRESULT					shader_compile			(
-		LPCSTR							name,
-		DWORD const*                    pSrcData,
-		UINT                            SrcDataLen,
-		LPCSTR                          pFunctionName,
-		LPCSTR                          pTarget,
-		DWORD                           Flags,
-		void*&							result
-	)																									= 0;
-
-	// Information
-	virtual	void					Statistics				(CGameFont* F	)							{};
-
-	virtual LPCSTR					getShaderPath			()											= 0;
-//	virtual ref_shader				getShader				(int id)									= 0;
-	virtual IRender_Sector*			getSector				(int id)									= 0;
-	virtual IRenderVisual*			getVisual				(int id)									= 0;
-	virtual IRender_Sector*			detectSector			(const Fvector& P)							= 0;
-	virtual IRender_Target*			getTarget				()											= 0;
-
-	// Main 
-	IC		void					set_Frustum				(CFrustum*	O	)							{ VERIFY(O);	View = O;			}
-	virtual void					set_Transform			(Fmatrix*	M	)							= 0;
-	virtual void					set_HUD					(BOOL 		V	)							= 0;
-	virtual BOOL					get_HUD					()											= 0;
-	virtual void					set_Invisible			(BOOL 		V	)							= 0;
-	virtual void					flush					()											= 0;	
-	virtual void					set_Object				(IRenderable*		O	)					= 0;
-	virtual	void					add_Occluder			(Fbox2&	bb_screenspace	)					= 0;	// mask screen region as oclluded (-1..1, -1..1)
-	virtual void					add_Visual				(IRenderVisual*	V	)					= 0;	// add visual leaf	(no culling performed at all)
-	virtual void					add_Geometry			(IRenderVisual*	V	)					= 0;	// add visual(s)	(all culling performed)
-//	virtual void					add_StaticWallmark		(ref_shader& S, const Fvector& P, float s, CDB::TRI* T, Fvector* V)=0;
-	virtual void					add_StaticWallmark		(const wm_shader& S, const Fvector& P, float s, CDB::TRI* T, Fvector* V)=0;
-	//	Prefer this function when possible
-	virtual void					add_StaticWallmark		(IWallMarkArray *pArray, const Fvector& P, float s, CDB::TRI* T, Fvector* V)=0;
-	virtual void					clear_static_wallmarks	()=0;
-	//virtual void					add_SkeletonWallmark	(intrusive_ptr wm)						= 0;
-	//virtual void					add_SkeletonWallmark	(const Fmatrix* xf, CKinematics* obj, ref_shader& sh, const Fvector& start, const Fvector& dir, float size)=0;
-	//	Prefer this function when possible
-	virtual void					add_SkeletonWallmark	(const Fmatrix* xf, IKinematics* obj, IWallMarkArray *pArray, const Fvector& start, const Fvector& dir, float size)=0;
-
-	//virtual IBlender*				blender_create			(CLASS_ID cls)								= 0;
-	//virtual void					blender_destroy			(IBlender* &)								= 0;
-
-	virtual IRender_ObjectSpecific*	ros_create				(IRenderable* parent)						= 0;
-	virtual void					ros_destroy				(IRender_ObjectSpecific* &)					= 0;
-
-	// Lighting/glowing
-	virtual IRender_Light*			light_create			()											= 0;
-	virtual void					light_destroy			(IRender_Light* p_)							{ };
-	virtual IRender_Glow*			glow_create				()											= 0;
-	virtual void					glow_destroy			(IRender_Glow* p_)							{ };
-
-	// Models
-	virtual IRenderVisual*			model_CreateParticles	(LPCSTR name)								= 0;
-//	virtual IRender_DetailModel*	model_CreateDM			(IReader*	F)								= 0;
-	//virtual IRenderDetailModel*		model_CreateDM			(IReader*	F)								= 0;
-	//virtual IRenderVisual*			model_Create			(LPCSTR name, IReader*	data=0)				= 0;
-	virtual IRenderVisual*			model_Create			(LPCSTR name, IReader*	data=0)				= 0;
-	virtual IRenderVisual*			model_CreateChild		(LPCSTR name, IReader*	data)				= 0;
-	virtual IRenderVisual*			model_Duplicate			(IRenderVisual*	V)						= 0;
-	//virtual void					model_Delete			(IRenderVisual* &	V, BOOL bDiscard=FALSE)	= 0;
-	virtual void					model_Delete			(IRenderVisual* &	V, BOOL bDiscard=FALSE)	= 0;
-//	virtual void 					model_Delete			(IRender_DetailModel* & F)					= 0;
-	virtual void					model_Logging			(BOOL bEnable)								= 0;
-	virtual void					models_Prefetch			()											= 0;
-	virtual void					models_Clear			(BOOL b_complete)							= 0;
-
-	// Occlusion culling
-	virtual BOOL					occ_visible				(vis_data&	V)								= 0;
-	virtual BOOL					occ_visible				(Fbox&		B)								= 0;
-	virtual BOOL					occ_visible				(sPoly&		P)								= 0;
-
-	// Main
-	virtual void					Calculate				()											= 0;
-	virtual void					Render					()											= 0;
-	
-	virtual void					Screenshot				(ScreenshotMode mode=SM_NORMAL, LPCSTR name = 0) = 0;
-	virtual	void					Screenshot				(ScreenshotMode mode, CMemoryWriter& memory_writer) = 0;
-	virtual void					ScreenshotAsyncBegin	() = 0;
-	virtual void					ScreenshotAsyncEnd		(CMemoryWriter& memory_writer) = 0;
-
-	// Render mode
-	virtual void					rmNear					()											= 0;
-	virtual void					rmFar					()											= 0;
-	virtual void					rmNormal				()											= 0;
-	virtual u32						memory_usage			()											= 0;
-
-	// Constructor/destructor
-	virtual ~IRender_interface();
+    // feature level
+    virtual GenerationLevel get_generation() = 0;
+
+    virtual bool is_sun_static() = 0;
+    virtual DWORD get_dx_level() = 0;
+
+    // Loading / Unloading
+    virtual void create() = 0;
+    virtual void destroy() = 0;
+    virtual void reset_begin() = 0;
+    virtual void reset_end() = 0;
+
+    BENCH_SEC_SCRAMBLEVTBL1
+    BENCH_SEC_SCRAMBLEVTBL3
+
+    virtual void level_Load(IReader*) = 0;
+    virtual void level_Unload() = 0;
+
+    //virtual IDirect3DBaseTexture9* texture_load (LPCSTR fname, u32& msize) = 0;
+    void shader_option_skinning(s32 mode) { m_skinning = mode; }
+    virtual HRESULT shader_compile(
+        LPCSTR name,
+        DWORD const* pSrcData,
+        UINT SrcDataLen,
+        LPCSTR pFunctionName,
+        LPCSTR pTarget,
+        DWORD Flags,
+        void*& result
+    ) = 0;
+
+    // Information
+    virtual void Statistics(CGameFont* F) {};
+
+    virtual LPCSTR getShaderPath() = 0;
+    // virtual ref_shader getShader (int id) = 0;
+    virtual IRender_Sector* getSector(int id) = 0;
+    virtual IRenderVisual* getVisual(int id) = 0;
+    virtual IRender_Sector* detectSector(const Fvector& P) = 0;
+    virtual IRender_Target* getTarget() = 0;
+
+    // Main
+    IC void set_Frustum(CFrustum* O) { VERIFY(O); View = O; }
+    virtual void set_Transform(Fmatrix* M) = 0;
+    virtual void set_HUD(BOOL V) = 0;
+    virtual BOOL get_HUD() = 0;
+    virtual void set_Invisible(BOOL V) = 0;
+    virtual void flush() = 0;
+    virtual void set_Object(IRenderable* O) = 0;
+    virtual void add_Occluder(Fbox2& bb_screenspace) = 0; // mask screen region as oclluded (-1..1, -1..1)
+    virtual void add_Visual(IRenderVisual* V) = 0; // add visual leaf (no culling performed at all)
+    virtual void add_Geometry(IRenderVisual* V) = 0; // add visual(s) (all culling performed)
+    // virtual void add_StaticWallmark (ref_shader& S, const Fvector& P, float s, CDB::TRI* T, Fvector* V)=0;
+    virtual void add_StaticWallmark(const wm_shader& S, const Fvector& P, float s, CDB::TRI* T, Fvector* V) = 0;
+    // Prefer this function when possible
+    virtual void add_StaticWallmark(IWallMarkArray* pArray, const Fvector& P, float s, CDB::TRI* T, Fvector* V) = 0;
+    virtual void clear_static_wallmarks() = 0;
+    //virtual void add_SkeletonWallmark (intrusive_ptr wm) = 0;
+    //virtual void add_SkeletonWallmark (const Fmatrix* xf, CKinematics* obj, ref_shader& sh, const Fvector& start, const Fvector& dir, float size)=0;
+    // Prefer this function when possible
+    virtual void add_SkeletonWallmark(const Fmatrix* xf, IKinematics* obj, IWallMarkArray* pArray, const Fvector& start, const Fvector& dir, float size) = 0;
+
+    //virtual IBlender* blender_create (CLASS_ID cls) = 0;
+    //virtual void blender_destroy (IBlender* &) = 0;
+
+    virtual IRender_ObjectSpecific* ros_create(IRenderable* parent) = 0;
+    virtual void ros_destroy(IRender_ObjectSpecific*&) = 0;
+
+    // Lighting/glowing
+    virtual IRender_Light* light_create() = 0;
+    virtual void light_destroy(IRender_Light* p_) { };
+    virtual IRender_Glow* glow_create() = 0;
+    virtual void glow_destroy(IRender_Glow* p_) { };
+
+    // Models
+    virtual IRenderVisual* model_CreateParticles(LPCSTR name) = 0;
+    // virtual IRender_DetailModel* model_CreateDM (IReader* F) = 0;
+    //virtual IRenderDetailModel* model_CreateDM (IReader* F) = 0;
+    //virtual IRenderVisual* model_Create (LPCSTR name, IReader* data=0) = 0;
+    virtual IRenderVisual* model_Create(LPCSTR name, IReader* data = 0) = 0;
+    virtual IRenderVisual* model_CreateChild(LPCSTR name, IReader* data) = 0;
+    virtual IRenderVisual* model_Duplicate(IRenderVisual* V) = 0;
+    //virtual void model_Delete (IRenderVisual* & V, BOOL bDiscard=FALSE) = 0;
+    virtual void model_Delete(IRenderVisual*& V, BOOL bDiscard = FALSE) = 0;
+    // virtual void model_Delete (IRender_DetailModel* & F) = 0;
+    virtual void model_Logging(BOOL bEnable) = 0;
+    virtual void models_Prefetch() = 0;
+    virtual void models_Clear(BOOL b_complete) = 0;
+
+    // Occlusion culling
+    virtual BOOL occ_visible(vis_data& V) = 0;
+    virtual BOOL occ_visible(Fbox& B) = 0;
+    virtual BOOL occ_visible(sPoly& P) = 0;
+
+    // Main
+    virtual void Calculate() = 0;
+    virtual void Render() = 0;
+
+    virtual void Screenshot(ScreenshotMode mode = SM_NORMAL, LPCSTR name = 0) = 0;
+    virtual void Screenshot(ScreenshotMode mode, CMemoryWriter& memory_writer) = 0;
+    virtual void ScreenshotAsyncBegin() = 0;
+    virtual void ScreenshotAsyncEnd(CMemoryWriter& memory_writer) = 0;
+
+    // Render mode
+    virtual void rmNear() = 0;
+    virtual void rmFar() = 0;
+    virtual void rmNormal() = 0;
+    virtual u32 memory_usage() = 0;
+
+    // Constructor/destructor
+    virtual ~IRender_interface();
 protected:
-	virtual	void					ScreenshotImpl			(ScreenshotMode mode, LPCSTR name, CMemoryWriter* memory_writer) = 0;
+    virtual void ScreenshotImpl(ScreenshotMode mode, LPCSTR name, CMemoryWriter* memory_writer) = 0;
 };
 
-//extern ENGINE_API	IRender_interface*	Render;
+//extern ENGINE_API IRender_interface* Render;
 
 #endif
\ No newline at end of file
diff --git a/src/xrEngine/Shader_xrLC.h b/src/xrEngine/Shader_xrLC.h
index 71b1b1f77ed..1a73900ad59 100644
--- a/src/xrEngine/Shader_xrLC.h
+++ b/src/xrEngine/Shader_xrLC.h
@@ -5,119 +5,128 @@
 struct Shader_xrLC
 {
 public:
-	enum {
-		flCollision			= 1<<0,
-		flRendering			= 1<<1,
-		flOptimizeUV		= 1<<2,
-		flLIGHT_Vertex		= 1<<3,
-		flLIGHT_CastShadow	= 1<<4,
-		flLIGHT_Sharp		= 1<<5,
-	};
-	struct Flags {
-		u32 bCollision				: 1;
-		u32 bRendering				: 1;
-		u32 bOptimizeUV				: 1;
-		u32 bLIGHT_Vertex			: 1;
-		u32 bLIGHT_CastShadow		: 1;
-		u32 bLIGHT_Sharp			: 1;
-	};
+    enum
+    {
+        flCollision = 1 << 0,
+        flRendering = 1 << 1,
+        flOptimizeUV = 1 << 2,
+        flLIGHT_Vertex = 1 << 3,
+        flLIGHT_CastShadow = 1 << 4,
+        flLIGHT_Sharp = 1 << 5,
+    };
+    struct Flags
+    {
+        u32 bCollision : 1;
+        u32 bRendering : 1;
+        u32 bOptimizeUV : 1;
+        u32 bLIGHT_Vertex : 1;
+        u32 bLIGHT_CastShadow : 1;
+        u32 bLIGHT_Sharp : 1;
+    };
 public:
-	char		Name		[128];
-	union{
-		Flags32	m_Flags;
-        Flags	flags;
+    char Name[128];
+    union
+    {
+        Flags32 m_Flags;
+        Flags flags;
     };
-	float		vert_translucency;
-	float		vert_ambient;
-	float		lm_density;
+    float vert_translucency;
+    float vert_ambient;
+    float lm_density;
 
-	Shader_xrLC()	{
-		xr_strcpy					(Name,"unknown");
-		m_Flags.assign			(0);
-		flags.bCollision		= TRUE;
-		flags.bRendering		= TRUE;
-		flags.bOptimizeUV		= TRUE;
-		flags.bLIGHT_Vertex		= FALSE;
-		flags.bLIGHT_CastShadow = TRUE;
-		flags.bLIGHT_Sharp		= TRUE;
-		vert_translucency		= .5f;
-		vert_ambient			= .0f;
-		lm_density				= 1.f;
-	}
+    Shader_xrLC()
+    {
+        xr_strcpy(Name, "unknown");
+        m_Flags.assign(0);
+        flags.bCollision = TRUE;
+        flags.bRendering = TRUE;
+        flags.bOptimizeUV = TRUE;
+        flags.bLIGHT_Vertex = FALSE;
+        flags.bLIGHT_CastShadow = TRUE;
+        flags.bLIGHT_Sharp = TRUE;
+        vert_translucency = .5f;
+        vert_ambient = .0f;
+        lm_density = 1.f;
+    }
 };
 
-DEFINE_VECTOR(Shader_xrLC,Shader_xrLCVec,Shader_xrLCIt);
+DEFINE_VECTOR(Shader_xrLC, Shader_xrLCVec, Shader_xrLCIt);
 class Shader_xrLC_LIB
 {
-	Shader_xrLCVec			library;
+    Shader_xrLCVec library;
 public:
-	void					Load	(LPCSTR name)
-	{
-		IReader* fs			= FS.r_open(name);
-		if(NULL==fs){
-			string256		inf;
-			extern HWND		logWindow;
-			xr_sprintf			(inf,sizeof(inf),"Build failed!\nCan't load shaders library: '%s'",name);
-//			clMsg			(inf);
-//			MessageBox		(logWindow,inf,"Error!",MB_OK|MB_ICONERROR);
-			FATAL			(inf);
-			return;
-		};
+    void Load(LPCSTR name)
+    {
+        IReader* fs = FS.r_open(name);
+        if (NULL == fs)
+        {
+            string256 inf;
+            extern HWND logWindow;
+            xr_sprintf(inf, sizeof(inf), "Build failed!\nCan't load shaders library: '%s'", name);
+            // clMsg (inf);
+            // MessageBox (logWindow,inf,"Error!",MB_OK|MB_ICONERROR);
+            FATAL(inf);
+            return;
+        };
 
-		int count			= fs->length()/sizeof(Shader_xrLC);
-		R_ASSERT			(int(fs->length()) == int(count*sizeof(Shader_xrLC)));
-		library.resize		(count);
-		fs->r				(&*library.begin(),fs->length());
-        FS.r_close			(fs);
-	}
-	bool					Save	(LPCSTR name)
-	{
-		IWriter* F			= FS.w_open(name);
-        if (F){
-			F->w			(&*library.begin(),(u32)library.size()*sizeof(Shader_xrLC));
-    	    FS.w_close		(F);
-            return 			true;
-        }else{
-        	return 			false;
+        int count = fs->length() / sizeof(Shader_xrLC);
+        R_ASSERT(int(fs->length()) == int(count*sizeof(Shader_xrLC)));
+        library.resize(count);
+        fs->r(&*library.begin(), fs->length());
+        FS.r_close(fs);
+    }
+    bool Save(LPCSTR name)
+    {
+        IWriter* F = FS.w_open(name);
+        if (F)
+        {
+            F->w(&*library.begin(), (u32)library.size()*sizeof(Shader_xrLC));
+            FS.w_close(F);
+            return true;
+        }
+        else
+        {
+            return false;
         }
-	}
-	void					Unload	()
-	{
-		library.clear		();
-	}
-	u32						GetID	(LPCSTR name)
-	{
-		for (Shader_xrLCIt it=library.begin(); it!=library.end(); it++)
-			if (0==stricmp(name,it->Name)) return u32(it-library.begin());
-		return u32(-1);
-	}
-	Shader_xrLC*			Get		(LPCSTR name)
-	{
-		for (Shader_xrLCIt it=library.begin(); it!=library.end(); it++)
-			if (0==stricmp(name,it->Name)) return &(*it);
-		return NULL;
-	}
-	Shader_xrLC*			Get		(int id)
-	{
-		return &library[id];
-	}
-	Shader_xrLC*			Append	(Shader_xrLC* parent=0)
-	{
-		library.push_back(parent?Shader_xrLC(*parent):Shader_xrLC());
-		return &library.back();
-	}
-	void					Remove	(LPCSTR name)
-	{
-		for (Shader_xrLCIt it=library.begin(); it!=library.end(); it++)
-			if (0==stricmp(name,it->Name)){
-            	library.erase(it);
+    }
+    void Unload()
+    {
+        library.clear();
+    }
+    u32 GetID(LPCSTR name)
+    {
+        for (Shader_xrLCIt it = library.begin(); it != library.end(); it++)
+            if (0 == stricmp(name, it->Name)) return u32(it - library.begin());
+        return u32(-1);
+    }
+    Shader_xrLC* Get(LPCSTR name)
+    {
+        for (Shader_xrLCIt it = library.begin(); it != library.end(); it++)
+            if (0 == stricmp(name, it->Name)) return &(*it);
+        return NULL;
+    }
+    Shader_xrLC* Get(int id)
+    {
+        return &library[id];
+    }
+    Shader_xrLC* Append(Shader_xrLC* parent = 0)
+    {
+        library.push_back(parent ? Shader_xrLC(*parent) : Shader_xrLC());
+        return &library.back();
+    }
+    void Remove(LPCSTR name)
+    {
+        for (Shader_xrLCIt it = library.begin(); it != library.end(); it++)
+            if (0 == stricmp(name, it->Name))
+            {
+                library.erase(it);
                 break;
             }
-	}
-	void					Remove	(int id)
-	{
-		library.erase(library.begin()+id);
-	}
-	Shader_xrLCVec&			Library	(){return library;}
+    }
+    void Remove(int id)
+    {
+        library.erase(library.begin() + id);
+    }
+    Shader_xrLCVec& Library() { return library; }
 };
 #endif
diff --git a/src/xrEngine/SkeletonMotionDefs.h b/src/xrEngine/SkeletonMotionDefs.h
index e0621a5b277..200c33b5642 100644
--- a/src/xrEngine/SkeletonMotionDefs.h
+++ b/src/xrEngine/SkeletonMotionDefs.h
@@ -3,12 +3,12 @@
 
 #pragma once
 
-const	u32		MAX_PARTS			=	4;
+const u32 MAX_PARTS = 4;
 
-const	f32		SAMPLE_FPS			=	30.f;
-const	f32		SAMPLE_SPF			=	(1.f/SAMPLE_FPS);
-f32		const	END_EPS				=	SAMPLE_SPF+EPS;
-const	f32		KEY_Quant			=	32767.f;
-const	f32		KEY_QuantI			=	1.f/KEY_Quant;
+const f32 SAMPLE_FPS = 30.f;
+const f32 SAMPLE_SPF = (1.f / SAMPLE_FPS);
+f32 const END_EPS = SAMPLE_SPF + EPS;
+const f32 KEY_Quant = 32767.f;
+const f32 KEY_QuantI = 1.f / KEY_Quant;
 
 #endif
diff --git a/src/xrEngine/SkeletonMotions.cpp b/src/xrEngine/SkeletonMotions.cpp
index b56d6cfe61f..14c3013c823 100644
--- a/src/xrEngine/SkeletonMotions.cpp
+++ b/src/xrEngine/SkeletonMotions.cpp
@@ -1,245 +1,255 @@
 //---------------------------------------------------------------------------
-#include 	"stdafx.h"
+#include "stdafx.h"
 #pragma hdrstop
 
-#include 	"SkeletonMotions.h"
-//#include 	"SkeletonAnimated.h"
-#include	"Fmesh.h"
-#include	"motion.h"
-#include	"..\Include\xrRender\Kinematics.h"
+#include "SkeletonMotions.h"
+//#include "SkeletonAnimated.h"
+#include "Fmesh.h"
+#include "motion.h"
+#include "..\Include\xrRender\Kinematics.h"
 
-motions_container*	g_pMotionsContainer	= 0;
+motions_container* g_pMotionsContainer = 0;
 
 u16 CPartition::part_id(const shared_str& name) const
 {
-	for(u16 i=0; iLL_BoneID(I.first.c_str());
-				P[i].bones.push_back(bid);
-			}
-		}
-		
-	}
+    string_path fn, fn_full;
+    xr_strcpy(fn, sizeof(fn), model_name);
+    if (strext(fn))
+        *strext(fn) = 0;
+    xr_strcat(fn, sizeof(fn), ".ltx");
+
+    FS.update_path(fn_full, "$game_meshes$", fn);
+
+    CInifile ini(fn_full, TRUE, TRUE, FALSE);
+
+    if (ini.sections().size() == 0) return;
+    shared_str part_name = "partition_name";
+    for (u32 i = 0; i < MAX_PARTS; ++i)
+    {
+        string64 buff;
+        xr_sprintf(buff, sizeof(buff), "part_%d", i);
+
+        CInifile::Sect S = ini.r_section(buff);
+        CInifile::SectCIt it = S.Data.begin();
+        CInifile::SectCIt it_e = S.Data.end();
+        if (S.Data.size())
+        {
+            P[i].bones.clear_not_free();
+        }
+        for (; it != it_e; ++it)
+        {
+            const CInifile::Item& I = *it;
+            if (I.first == part_name)
+            {
+                P[i].Name = I.second;
+            }
+            else
+            {
+                u32 bid = V->LL_BoneID(I.first.c_str());
+                P[i].bones.push_back(bid);
+            }
+        }
+
+    }
 }
 
 u16 find_bone_id(vecBones* bones, shared_str nm)
 {
-	for (u16 i=0; i<(u16)bones->size(); i++)
-		if (bones->at(i)->name==nm) return i;
-	return BI_NONE;
+    for (u16 i = 0; i < (u16)bones->size(); i++)
+        if (bones->at(i)->name == nm) return i;
+    return BI_NONE;
 }
 
 //-----------------------------------------------------------------------
-BOOL motions_value::load		(LPCSTR N, IReader *data, vecBones* bones)
+BOOL motions_value::load(LPCSTR N, IReader* data, vecBones* bones)
 {
 
-	m_id						= N;
-
-	bool bRes					= true;
-	// Load definitions
-	U16Vec rm_bones				(bones->size(),BI_NONE);
-	IReader* MP 				= data->open_chunk(OGF_S_SMPARAMS);
-
-	if (MP)
-	{
-		u16 vers 				= MP->r_u16();
-		u16 part_bone_cnt		= 0;
-		string128 				buf;
-		R_ASSERT3				(vers<=xrOGF_SMParamsVersion,"Invalid OGF/OMF version:",N);
-		
-		// partitions
-		u16						part_count;
-		part_count 				= MP->r_u16();
-
-		for (u16 part_i=0; part_ir_stringZ		(buf,sizeof(buf));
-			PART.Name			= _strlwr(buf);
-			PART.bones.resize	(MP->r_u16());
-
-			for (xr_vector::iterator b_it=PART.bones.begin(); b_itr_stringZ	(buf,sizeof(buf));
-				u16 m_idx 		= u16			(MP->r_u32());
-				*b_it			= find_bone_id	(bones,buf);
+    m_id = N;
+
+    bool bRes = true;
+    // Load definitions
+    U16Vec rm_bones(bones->size(), BI_NONE);
+    IReader* MP = data->open_chunk(OGF_S_SMPARAMS);
+
+    if (MP)
+    {
+        u16 vers = MP->r_u16();
+        u16 part_bone_cnt = 0;
+        string128 buf;
+        R_ASSERT3(vers <= xrOGF_SMParamsVersion, "Invalid OGF/OMF version:", N);
+
+        // partitions
+        u16 part_count;
+        part_count = MP->r_u16();
+
+        for (u16 part_i = 0; part_i < part_count; part_i++)
+        {
+            CPartDef& PART = m_partition[part_i];
+            MP->r_stringZ(buf, sizeof(buf));
+            PART.Name = _strlwr(buf);
+            PART.bones.resize(MP->r_u16());
+
+            for (xr_vector::iterator b_it = PART.bones.begin(); b_it < PART.bones.end(); b_it++)
+            {
+                MP->r_stringZ(buf, sizeof(buf));
+                u16 m_idx = u16(MP->r_u32());
+                *b_it = find_bone_id(bones, buf);
 #ifdef _EDITOR
-				if (*b_it==BI_NONE )
+                if (*b_it==BI_NONE )
                 {
-					bRes		= false;
-					Msg			("!Can't find bone: '%s'", buf);
-				}
+                    bRes = false;
+                    Msg ("!Can't find bone: '%s'", buf);
+                }
 
-				if (rm_bones.size() <= m_idx)
+                if (rm_bones.size() <= m_idx)
                 {
-					bRes		= false;
-					Msg			("!Can't load: '%s' invalid bones count", N);
-				}
+                    bRes = false;
+                    Msg ("!Can't load: '%s' invalid bones count", N);
+                }
 #else
-				VERIFY3			(*b_it!=BI_NONE,"Can't find bone:", buf);
+                VERIFY3(*b_it != BI_NONE, "Can't find bone:", buf);
 #endif
-				if (bRes)		rm_bones[m_idx] = u16(*b_it);
-			}
-			part_bone_cnt		= u16(part_bone_cnt + (u16)PART.bones.size());
-		}
+                if (bRes) rm_bones[m_idx] = u16(*b_it);
+            }
+            part_bone_cnt = u16(part_bone_cnt + (u16)PART.bones.size());
+        }
 
 #ifdef _EDITOR
-		if (part_bone_cnt!=(u16)bones->size()){
-			bRes = false;
-			Msg("!Different bone count[%s] [Object: '%d' <-> Motions: '%d']", N, bones->size(),part_bone_cnt);
-		}
+        if (part_bone_cnt!=(u16)bones->size())
+        {
+            bRes = false;
+            Msg("!Different bone count[%s] [Object: '%d' <-> Motions: '%d']", N, bones->size(),part_bone_cnt);
+        }
 #else
-		VERIFY3(part_bone_cnt==(u16)bones->size(),"Different bone count '%s'",N);
+        VERIFY3(part_bone_cnt == (u16)bones->size(), "Different bone count '%s'", N);
 #endif
-		if (bRes)
-		{
-			// motion defs (cycle&fx)
-			u16 mot_count			= MP->r_u16();
-            m_mdefs.resize			(mot_count);
-
-			for (u16 mot_i=0; mot_ir_stringZ		(buf,sizeof(buf));
-				shared_str nm		= _strlwr		(buf);
-				u32 dwFlags			= MP->r_u32		();
-				CMotionDef&	D		= m_mdefs[mot_i];
-                D.Load				(MP,dwFlags,vers);
-//.             m_mdefs.push_back	(D);
-				
-				if (dwFlags&esmFX)	
-					m_fx.insert		(mk_pair(nm,mot_i));
-				else				
-					m_cycle.insert	(mk_pair(nm,mot_i));
-
-                m_motion_map.insert	(mk_pair(nm,mot_i));
-			}
-		}
-		MP->close();
-	}else
-	{
-		Debug.fatal	(DEBUG_INFO,"Old skinned model version unsupported! (%s)",N);
-	}
-	if (!bRes)	return false;
-
-	// Load animation
-	IReader*	MS		= data->open_chunk(OGF_S_MOTIONS);
-	if (!MS) 			return false;
-
-	u32			dwCNT	= 0;
-	MS->r_chunk_safe	(0,&dwCNT,sizeof(dwCNT));
-    VERIFY		(dwCNT<0x3FFF); // MotionID 2 bit - slot, 14 bit - motion index
-
-	// set per bone motion size
-	for (u32 i=0; isize(); i++)
-		m_motions[bones->at(i)->name].resize(dwCNT);
-
-	// load motions
-	for (u16 m_idx=0; m_idx<(u16)dwCNT; m_idx++){
-		string128			mname;
-		R_ASSERT			(MS->find_chunk(m_idx+1));             
-		MS->r_stringZ		(mname,sizeof(mname));
-#ifdef _DEBUG        
-		// sanity check
-		xr_strlwr			(mname);
-        accel_map::iterator I= m_motion_map.find(mname); 
-        VERIFY3				(I!=m_motion_map.end(),"Can't find motion:",mname);
-        VERIFY3				(I->second==m_idx,"Invalid motion index:",mname);
+        if (bRes)
+        {
+            // motion defs (cycle&fx)
+            u16 mot_count = MP->r_u16();
+            m_mdefs.resize(mot_count);
+
+            for (u16 mot_i = 0; mot_i < mot_count; mot_i++)
+            {
+                MP->r_stringZ(buf, sizeof(buf));
+                shared_str nm = _strlwr(buf);
+                u32 dwFlags = MP->r_u32();
+                CMotionDef& D = m_mdefs[mot_i];
+                D.Load(MP, dwFlags, vers);
+                //. m_mdefs.push_back (D);
+
+                if (dwFlags&esmFX)
+                    m_fx.insert(mk_pair(nm, mot_i));
+                else
+                    m_cycle.insert(mk_pair(nm, mot_i));
+
+                m_motion_map.insert(mk_pair(nm, mot_i));
+            }
+        }
+        MP->close();
+    }
+    else
+    {
+        Debug.fatal(DEBUG_INFO, "Old skinned model version unsupported! (%s)", N);
+    }
+    if (!bRes) return false;
+
+    // Load animation
+    IReader* MS = data->open_chunk(OGF_S_MOTIONS);
+    if (!MS) return false;
+
+    u32 dwCNT = 0;
+    MS->r_chunk_safe(0, &dwCNT, sizeof(dwCNT));
+    VERIFY(dwCNT < 0x3FFF); // MotionID 2 bit - slot, 14 bit - motion index
+
+    // set per bone motion size
+    for (u32 i = 0; i < bones->size(); i++)
+        m_motions[bones->at(i)->name].resize(dwCNT);
+
+    // load motions
+    for (u16 m_idx = 0; m_idx < (u16)dwCNT; m_idx++)
+    {
+        string128 mname;
+        R_ASSERT(MS->find_chunk(m_idx + 1));
+        MS->r_stringZ(mname, sizeof(mname));
+#ifdef _DEBUG
+        // sanity check
+        xr_strlwr (mname);
+        accel_map::iterator I= m_motion_map.find(mname);
+        VERIFY3 (I!=m_motion_map.end(),"Can't find motion:",mname);
+        VERIFY3 (I->second==m_idx,"Invalid motion index:",mname);
 #endif
-		u32 dwLen			= MS->r_u32();
-		for (u32 i=0; isize(); i++){
-			u16 bone_id		= rm_bones[i];
-			VERIFY2			(bone_id!=BI_NONE,"Invalid remap index.");
-			CMotion&		M	= m_motions[bones->at(bone_id)->name][m_idx];
-			M.set_count			(dwLen);
-			M.set_flags			(MS->r_u8());
-            
-            if (M.test_flag(flRKeyAbsent))	{
-                CKeyQR* r 		= (CKeyQR*)MS->pointer();
-				u32 crc_q		= crc32(r,sizeof(CKeyQR));
-				M._keysR.create	(crc_q,1,r);
-                MS->advance		(1 * sizeof(CKeyQR));
-            }else{
-                u32 crc_q		= MS->r_u32	();
-                M._keysR.create	(crc_q,dwLen,(CKeyQR*)MS->pointer());
-                MS->advance		(dwLen * sizeof(CKeyQR));
+        u32 dwLen = MS->r_u32();
+        for (u32 i = 0; i < bones->size(); i++)
+        {
+            u16 bone_id = rm_bones[i];
+            VERIFY2(bone_id != BI_NONE, "Invalid remap index.");
+            CMotion& M = m_motions[bones->at(bone_id)->name][m_idx];
+            M.set_count(dwLen);
+            M.set_flags(MS->r_u8());
+
+            if (M.test_flag(flRKeyAbsent))
+            {
+                CKeyQR* r = (CKeyQR*)MS->pointer();
+                u32 crc_q = crc32(r, sizeof(CKeyQR));
+                M._keysR.create(crc_q, 1, r);
+                MS->advance(1 * sizeof(CKeyQR));
             }
-            if (M.test_flag(flTKeyPresent))	
+            else
             {
-                u32 crc_t		= MS->r_u32	();
-                if(M.test_flag(flTKey16IsBit))
+                u32 crc_q = MS->r_u32();
+                M._keysR.create(crc_q, dwLen, (CKeyQR*)MS->pointer());
+                MS->advance(dwLen * sizeof(CKeyQR));
+            }
+            if (M.test_flag(flTKeyPresent))
+            {
+                u32 crc_t = MS->r_u32();
+                if (M.test_flag(flTKey16IsBit))
                 {
-                    M._keysT16.create	(crc_t,dwLen,(CKeyQT16*)MS->pointer());
-                    MS->advance			(dwLen * sizeof(CKeyQT16));
-                }else
+                    M._keysT16.create(crc_t, dwLen, (CKeyQT16*)MS->pointer());
+                    MS->advance(dwLen * sizeof(CKeyQT16));
+                }
+                else
                 {
-                    M._keysT8.create	(crc_t,dwLen,(CKeyQT8*)MS->pointer());
-                    MS->advance			(dwLen * sizeof(CKeyQT8));
+                    M._keysT8.create(crc_t, dwLen, (CKeyQT8*)MS->pointer());
+                    MS->advance(dwLen * sizeof(CKeyQT8));
                 };
-                
-                MS->r_fvector3	(M._sizeT);
-                MS->r_fvector3	(M._initT);
-            }else
+
+                MS->r_fvector3(M._sizeT);
+                MS->r_fvector3(M._initT);
+            }
+            else
             {
-                MS->r_fvector3	(M._initT);
+                MS->r_fvector3(M._initT);
             }
-		}
-	}
-//	Msg("Motions %d/%d %4d/%4d/%d, %s",p_cnt,m_cnt, m_load,m_total,m_r,N);
-	MS->close();
+        }
+    }
+    // Msg("Motions %d/%d %4d/%4d/%d, %s",p_cnt,m_cnt, m_load,m_total,m_r,N);
+    MS->close();
 
-	return bRes;
+    return bRes;
 }
 
 MotionVec* motions_value::bone_motions(shared_str bone_name)
 {
-	BoneMotionMapIt I = m_motions.find(bone_name);
-//	VERIFY			(I != m_motions.end());
-	if (I == m_motions.end())
-		return		(0);
+    BoneMotionMapIt I = m_motions.find(bone_name);
+    // VERIFY (I != m_motions.end());
+    if (I == m_motions.end())
+        return (0);
 
-	return			(&(*I).second);
+    return (&(*I).second);
 }
 //-----------------------------------
 motions_container::motions_container()
@@ -248,218 +258,230 @@ motions_container::motions_container()
 //extern shared_str s_bones_array_const;
 motions_container::~motions_container()
 {
-//	clean	(false);
-//	clean	(true);
-//	dump	();
-	VERIFY	(container.empty());
-	//	Igor:
-	//s_bones_array_const = 0;
+    // clean (false);
+    // clean (true);
+    // dump ();
+    VERIFY(container.empty());
+    // Igor:
+    //s_bones_array_const = 0;
 }
 
 bool motions_container::has(shared_str key)
 {
-	return (container.find(key)!=container.end());
+    return (container.find(key) != container.end());
 }
 
-motions_value* motions_container::dock(shared_str key, IReader *data, vecBones* bones)
+motions_value* motions_container::dock(shared_str key, IReader* data, vecBones* bones)
 {
-	motions_value*	result		= 0	;
-	SharedMotionsMapIt	I		= container.find	(key);
-	if (I!=container.end())		result = I->second;
-	if (0==result)				{
-		// loading motions
-		VERIFY					(data);
-		result					= xr_new();
-		result->m_dwReference	= 0;
-		BOOL bres				= result->load	(key.c_str(),data,bones);
-		if (bres)
-        	container.insert(mk_pair(key,result));
-		else
-        	xr_delete		(result);
-	}
-	return result;
+    motions_value* result = 0;
+    SharedMotionsMapIt I = container.find(key);
+    if (I != container.end()) result = I->second;
+    if (0 == result)
+    {
+        // loading motions
+        VERIFY(data);
+        result = xr_new();
+        result->m_dwReference = 0;
+        BOOL bres = result->load(key.c_str(), data, bones);
+        if (bres)
+            container.insert(mk_pair(key, result));
+        else
+            xr_delete(result);
+    }
+    return result;
 }
 void motions_container::clean(bool force_destroy)
 {
-	SharedMotionsMapIt it	= container.begin();
-	SharedMotionsMapIt _E	= container.end();
-	if (force_destroy){
-		for (; it!=_E; it++){
-			motions_value*	sv = it->second;
-			xr_delete		(sv);
-		}
-		container.clear		();
-	}else{
-		for (; it!=_E; )	{
-			motions_value*	sv = it->second;
-			if (0==sv->m_dwReference)	
-			{
-				SharedMotionsMapIt	i_current	= it;
-				SharedMotionsMapIt	i_next		= ++it;
-				xr_delete			(sv);
-				container.erase		(i_current);
-				it					= i_next;
-			} else {
-				it++;
-			}
-		}
-	}
+    SharedMotionsMapIt it = container.begin();
+    SharedMotionsMapIt _E = container.end();
+    if (force_destroy)
+    {
+        for (; it != _E; it++)
+        {
+            motions_value* sv = it->second;
+            xr_delete(sv);
+        }
+        container.clear();
+    }
+    else
+    {
+        for (; it != _E;)
+        {
+            motions_value* sv = it->second;
+            if (0 == sv->m_dwReference)
+            {
+                SharedMotionsMapIt i_current = it;
+                SharedMotionsMapIt i_next = ++it;
+                xr_delete(sv);
+                container.erase(i_current);
+                it = i_next;
+            }
+            else
+            {
+                it++;
+            }
+        }
+    }
 }
 void motions_container::dump()
 {
-	SharedMotionsMapIt it	= container.begin();
-	SharedMotionsMapIt _E	= container.end();
-	Log	("--- motion container --- begin:");
-	u32 sz					= sizeof(*this);
-	for (u32 k=0; it!=_E; k++,it++){
-		sz					+= it->second->mem_usage();
-		Msg("#%3d: [%3d/%5d Kb] - %s",k,it->second->m_dwReference,it->second->mem_usage()/1024,it->first.c_str());
-	}
-	Msg ("--- items: %d, mem usage: %d Kb ",container.size(),sz/1024);
-	Log	("--- motion container --- end.");
+    SharedMotionsMapIt it = container.begin();
+    SharedMotionsMapIt _E = container.end();
+    Log("--- motion container --- begin:");
+    u32 sz = sizeof(*this);
+    for (u32 k = 0; it != _E; k++, it++)
+    {
+        sz += it->second->mem_usage();
+        Msg("#%3d: [%3d/%5d Kb] - %s", k, it->second->m_dwReference, it->second->mem_usage() / 1024, it->first.c_str());
+    }
+    Msg("--- items: %d, mem usage: %d Kb ", container.size(), sz / 1024);
+    Log("--- motion container --- end.");
 }
 
 //////////////////////////////////////////////////////////////////////////
 // High level control
 void CMotionDef::Load(IReader* MP, u32 fl, u16 version)
 {
-	// params
-	bone_or_part= MP->r_u16(); // bCycle?part_id:bone_id;
-	motion		= MP->r_u16(); // motion_id
-	speed		= Quantize(MP->r_float());
-	power		= Quantize(MP->r_float());
-	accrue		= Quantize(MP->r_float());
-	falloff		= Quantize(MP->r_float());
-	flags		= (u16)fl;
-	if (!(flags&esmFX) && (falloff>=accrue)) falloff = u16(accrue-1);
-
-	if(version>=4)
-	{
-		u32	cnt				= MP->r_u32();
-        if(cnt>0)
+    // params
+    bone_or_part = MP->r_u16(); // bCycle?part_id:bone_id;
+    motion = MP->r_u16(); // motion_id
+    speed = Quantize(MP->r_float());
+    power = Quantize(MP->r_float());
+    accrue = Quantize(MP->r_float());
+    falloff = Quantize(MP->r_float());
+    flags = (u16)fl;
+    if (!(flags&esmFX) && (falloff >= accrue)) falloff = u16(accrue - 1);
+
+    if (version >= 4)
+    {
+        u32 cnt = MP->r_u32();
+        if (cnt > 0)
         {
-            marks.resize		(cnt);
+            marks.resize(cnt);
 
-            for(u32 i=0; idock(key,data,bones);
-	if (0!=v)
-		v->m_dwReference++;
-	destroy			();
-	p_				= v;
-    return (0!=v);
+    motions_value* v = g_pMotionsContainer->dock(key, data, bones);
+    if (0 != v)
+        v->m_dwReference++;
+    destroy();
+    p_ = v;
+    return (0 != v);
 }
 
-bool shared_motions::create(shared_motions const &rhs)
+bool shared_motions::create(shared_motions const& rhs)
 {
-	motions_value* v = rhs.p_;
-	if (0!=v)
-		v->m_dwReference++;
-	destroy			();
-	p_				= v;
-    return (0!=v);
+    motions_value* v = rhs.p_;
+    if (0 != v)
+        v->m_dwReference++;
+    destroy();
+    p_ = v;
+    return (0 != v);
 }
 
 const motion_marks::interval* motion_marks::pick_mark(const float& t) const
 {
-	C_ITERATOR	it		= intervals.begin();
-	C_ITERATOR	it_e	= intervals.end();
-
-	for( ;it!=it_e; ++it)
-	{
-		const interval& I = (*it);
-		if( I.first<=t && I.second>=t )
-			return &I;
-		
-		if(I.first>t)
-			break;
-	}
-	return NULL;
+    C_ITERATOR it = intervals.begin();
+    C_ITERATOR it_e = intervals.end();
+
+    for (; it != it_e; ++it)
+    {
+        const interval& I = (*it);
+        if (I.first <= t && I.second >= t)
+            return &I;
+
+        if (I.first > t)
+            break;
+    }
+    return NULL;
 }
 
-bool motion_marks::is_mark_between	(float const &t0, float const &t1) const
+bool motion_marks::is_mark_between(float const& t0, float const& t1) const
 {
-	VERIFY				(t0 <= t1);
+    VERIFY(t0 <= t1);
 
-	C_ITERATOR			i = intervals.begin();
-	C_ITERATOR			e = intervals.end();
-	for ( ; i != e; ++i) {
-		VERIFY			((*i).first <= (*i).second);
+    C_ITERATOR i = intervals.begin();
+    C_ITERATOR e = intervals.end();
+    for (; i != e; ++i)
+    {
+        VERIFY((*i).first <= (*i).second);
 
-		if ((*i).first == t0)
-			return		(true);
+        if ((*i).first == t0)
+            return (true);
 
-		if ((*i).first > t0) {
-			if ((*i).second <= t1)
-				return	(true);
+        if ((*i).first > t0)
+        {
+            if ((*i).second <= t1)
+                return (true);
 
-			if ((*i).first <= t1)
-				return	(true);
+            if ((*i).first <= t1)
+                return (true);
 
-			return		(false);
-		}
+            return (false);
+        }
 
-		if ((*i).second < t0)
-			continue;
+        if ((*i).second < t0)
+            continue;
 
-		if ((*i).second == t0)
-			return		(true);
+        if ((*i).second == t0)
+            return (true);
 
-		return			(true);
-	}
+        return (true);
+    }
 
-	return				(false);
+    return (false);
 }
 
-float	motion_marks::	time_to_next_mark	(float time) const
+float motion_marks::time_to_next_mark(float time) const
 {
-	C_ITERATOR			i = intervals.begin();
-	C_ITERATOR			e = intervals.end();
-	float result_dist = FLT_MAX;
-	for ( ; i != e; ++i) {
-		float dist = (*i).first - time;
-		if( dist > 0.f && dist < result_dist )
-			result_dist = dist;
-	}
-	return result_dist;
+    C_ITERATOR i = intervals.begin();
+    C_ITERATOR e = intervals.end();
+    float result_dist = FLT_MAX;
+    for (; i != e; ++i)
+    {
+        float dist = (*i).first - time;
+        if (dist > 0.f && dist < result_dist)
+            result_dist = dist;
+    }
+    return result_dist;
 }
 
 void ENGINE_API motion_marks::Load(IReader* R)
 {
-	xr_string 			tmp;
-	R->r_string			(tmp);
-    name				= tmp.c_str();
-	u32 cnt				= R->r_u32();
-	intervals.resize	(cnt);
-	for(u32 i=0; ir_float();
-		item.second			= R->r_float();
-	}
+    xr_string tmp;
+    R->r_string(tmp);
+    name = tmp.c_str();
+    u32 cnt = R->r_u32();
+    intervals.resize(cnt);
+    for (u32 i = 0; i < cnt; ++i)
+    {
+        interval& item = intervals[i];
+        item.first = R->r_float();
+        item.second = R->r_float();
+    }
 }
 #ifdef _EDITOR
 void motion_marks::Save(IWriter* W)
 {
-	W->w_string			(name.c_str());
-	u32 cnt				= intervals.size();
-    W->w_u32			(cnt);
-	for(u32 i=0; iw_float			(item.first);
-		W->w_float			(item.second);
-	}
+    W->w_string (name.c_str());
+    u32 cnt = intervals.size();
+    W->w_u32 (cnt);
+    for(u32 i=0; iw_float (item.first);
+        W->w_float (item.second);
+    }
 }
 #endif
diff --git a/src/xrEngine/SkeletonMotions.h b/src/xrEngine/SkeletonMotions.h
index 48ac2353d5b..24f949188a4 100644
--- a/src/xrEngine/SkeletonMotions.h
+++ b/src/xrEngine/SkeletonMotions.h
@@ -2,241 +2,246 @@
 #ifndef SkeletonMotionsH
 #define SkeletonMotionsH
 
-//#include		"skeletoncustom.h"
+//#include "skeletoncustom.h"
 #include "bone.h"
-#include "skeletonmotiondefs.h"	
+#include "skeletonmotiondefs.h"
 // refs
 class CKinematicsAnimated;
 class CBlend;
 class IKinematics;
 
 // callback
-typedef void	( * PlayCallback)		(CBlend*		P);
+typedef void(*PlayCallback) (CBlend* P);
 
 
 //*** Key frame definition ************************************************************************
-enum{
-    flTKeyPresent 	= (1<<0),
-    flRKeyAbsent 	= (1<<1),
-    flTKey16IsBit 	= (1<<2),
+enum
+{
+    flTKeyPresent = (1 << 0),
+    flRKeyAbsent = (1 << 1),
+    flTKey16IsBit = (1 << 2),
 };
 #pragma pack(push,2)
-struct  CKey
+struct CKey
 {
-	Fquaternion	Q;			// rotation
-	Fvector		T;			// translation
+    Fquaternion Q; // rotation
+    Fvector T; // translation
 };
-struct  CKeyQR
+struct CKeyQR
 {
-	s16			x,y,z,w;	// rotation
+    s16 x, y, z, w; // rotation
 };
-struct  CKeyQT8
+struct CKeyQT8
 {
-	s8			x1,y1,z1;
+    s8 x1, y1, z1;
 };
-struct  CKeyQT16
+struct CKeyQT16
 {
-	s16			x1,y1,z1;
+    s16 x1, y1, z1;
 };
 /*
-struct  CKeyQT
+struct CKeyQT
 {
-//	s8			x,y,z;
-	s16			x1,y1,z1;
+// s8 x,y,z;
+s16 x1,y1,z1;
 };
 */
 #pragma pack(pop)
 
 //*** Motion Data *********************************************************************************
-class 	ENGINE_API	CMotion
+class ENGINE_API CMotion
 {
-	struct{
-    	u32				_flags	: 8;
-		u32				_count 	: 24;
+    struct
+    {
+        u32 _flags : 8;
+        u32 _count : 24;
     };
 public:
-    ref_smem	_keysR;
-    ref_smem	_keysT8;
-    ref_smem	_keysT16;
-	Fvector				_initT;
-    Fvector				_sizeT;
-public:    
-    void				set_flags			(u8 val)			{_flags=val;}
-    void				set_flag			(u8 mask, u8 val)	{if (val)_flags|=mask; else _flags&=~mask;}
-    BOOL				test_flag			(u8 mask) const		{return BOOL(_flags&mask);}
-
-    void				set_count			(u32 cnt){VERIFY(cnt); _count=cnt;}
-    ICF u32					get_count			() const {return (u32(_count)&0x00FFFFFF);}
-
-	float				GetLength			(){ return float(_count)*SAMPLE_SPF; }
-
-	u32					mem_usage			(){ 
-		u32 sz			= sizeof(*this);
-		if (_keysR.size()) sz += _keysR.size()*sizeof(CKeyQR)/_keysR.ref_count();
-		if (_keysT8.size()) sz += _keysT8.size()*sizeof(CKeyQT8)/_keysT8.ref_count();
-		if (_keysT16.size()) sz += _keysT16.size()*sizeof(CKeyQT16)/_keysT16.ref_count();
-		return			sz;
-	}
+    ref_smem _keysR;
+    ref_smem _keysT8;
+    ref_smem _keysT16;
+    Fvector _initT;
+    Fvector _sizeT;
+public:
+    void set_flags(u8 val) { _flags = val; }
+    void set_flag(u8 mask, u8 val) { if (val)_flags |= mask; else _flags &= ~mask; }
+    BOOL test_flag(u8 mask) const { return BOOL(_flags&mask); }
+
+    void set_count(u32 cnt) { VERIFY(cnt); _count = cnt; }
+    ICF u32 get_count() const { return (u32(_count) & 0x00FFFFFF); }
+
+    float GetLength() { return float(_count)*SAMPLE_SPF; }
+
+    u32 mem_usage()
+    {
+        u32 sz = sizeof(*this);
+        if (_keysR.size()) sz += _keysR.size()*sizeof(CKeyQR) / _keysR.ref_count();
+        if (_keysT8.size()) sz += _keysT8.size()*sizeof(CKeyQT8) / _keysT8.ref_count();
+        if (_keysT16.size()) sz += _keysT16.size()*sizeof(CKeyQT16) / _keysT16.ref_count();
+        return sz;
+    }
 };
 
 class ENGINE_API motion_marks
 {
 public:
-	typedef					std::pair<  float, float > 				interval;
+    typedef std::pair< float, float > interval;
 #ifdef _EDITOR
 public:
 #else
 private:
 #endif
-	typedef xr_vector< interval >									STORAGE;
-	typedef STORAGE::iterator										ITERATOR;
-	typedef STORAGE::const_iterator									C_ITERATOR;
+    typedef xr_vector< interval > STORAGE;
+    typedef STORAGE::iterator ITERATOR;
+    typedef STORAGE::const_iterator C_ITERATOR;
 
-	STORAGE			intervals;	
+    STORAGE intervals;
 public:
-	shared_str		name;
-	void			Load				(IReader*);
+    shared_str name;
+    void Load(IReader*);
 
 #ifdef _EDITOR
-	void			Save				(IWriter*);
+    void Save(IWriter*);
 #endif
-	bool			is_empty			() const { return intervals.empty(); }
-	const interval*	pick_mark			(float const &t) const;
-	bool			is_mark_between		(float const &t0, float const &t1) const;
-	float			time_to_next_mark	(float time) const;
+    bool is_empty() const { return intervals.empty(); }
+    const interval* pick_mark(float const& t) const;
+    bool is_mark_between(float const& t0, float const& t1) const;
+    float time_to_next_mark(float time) const;
 };
 
 
-const float	fQuantizerRangeExt	= 1.5f;
-class 	ENGINE_API	CMotionDef
+const float fQuantizerRangeExt = 1.5f;
+class ENGINE_API CMotionDef
 {
 public:
-    u16						bone_or_part;
-	u16						motion;
-	u16						speed;				// quantized: 0..10
-	u16						power;				// quantized: 0..10
-	u16						accrue;				// quantized: 0..10
-	u16						falloff;			// quantized: 0..10
-    u16						flags;
-	xr_vector	marks;
-
-	IC float				Dequantize			(u16 V)	const	{	return  float(V)/655.35f; }
-	IC u16					Quantize			(float V) const		{	s32		t = iFloor(V*655.35f); clamp(t,0,65535); return u16(t); }
-
-	void					Load				(IReader* MP, u32 fl, u16 vers);
-	u32						mem_usage			(){ return sizeof(*this);}
-
-    ICF float				Accrue				(){return fQuantizerRangeExt*Dequantize(accrue);}
-    ICF float				Falloff				(){return fQuantizerRangeExt*Dequantize(falloff);}
-    ICF float				Speed				(){return Dequantize(speed);}
-    ICF float				Power				(){return Dequantize(power);}
-    bool					StopAtEnd			();
+    u16 bone_or_part;
+    u16 motion;
+    u16 speed; // quantized: 0..10
+    u16 power; // quantized: 0..10
+    u16 accrue; // quantized: 0..10
+    u16 falloff; // quantized: 0..10
+    u16 flags;
+    xr_vector marks;
+
+    IC float Dequantize(u16 V) const { return float(V) / 655.35f; }
+    IC u16 Quantize(float V) const { s32 t = iFloor(V*655.35f); clamp(t, 0, 65535); return u16(t); }
+
+    void Load(IReader* MP, u32 fl, u16 vers);
+    u32 mem_usage() { return sizeof(*this); }
+
+    ICF float Accrue() { return fQuantizerRangeExt*Dequantize(accrue); }
+    ICF float Falloff() { return fQuantizerRangeExt*Dequantize(falloff); }
+    ICF float Speed() { return Dequantize(speed); }
+    ICF float Power() { return Dequantize(power); }
+    bool StopAtEnd();
 };
-struct accel_str_pred : public std::binary_function	{	
-	IC bool operator()(const shared_str& x, const shared_str& y) const	{	return xr_strcmp(x,y)<0;	}
+struct accel_str_pred : public std::binary_function < shared_str, shared_str, bool >
+{
+    IC bool operator()(const shared_str& x, const shared_str& y) const { return xr_strcmp(x, y) < 0; }
 };
-typedef xr_map 	accel_map;
-DEFINE_VECTOR			(CMotionDef,MotionDefVec,MotionDefVecIt);
+typedef xr_map accel_map;
+DEFINE_VECTOR(CMotionDef, MotionDefVec, MotionDefVecIt);
 
-DEFINE_VECTOR			(CMotion,MotionVec,MotionVecIt);
-DEFINE_VECTOR			(MotionVec*,BoneMotionsVec,BoneMotionsVecIt);
-DEFINE_MAP				(shared_str,MotionVec,BoneMotionMap,BoneMotionMapIt);
+DEFINE_VECTOR(CMotion, MotionVec, MotionVecIt);
+DEFINE_VECTOR(MotionVec*, BoneMotionsVec, BoneMotionsVecIt);
+DEFINE_MAP(shared_str, MotionVec, BoneMotionMap, BoneMotionMapIt);
 
 // partition
-class 	ENGINE_API	CPartDef
+class ENGINE_API CPartDef
 {
 public:
-	shared_str			Name;
-	xr_vector		bones;
-	CPartDef()			: Name(0) {};
+    shared_str Name;
+    xr_vector bones;
+    CPartDef() : Name(0) {};
 
-	u32					mem_usage			(){ return sizeof(*this)+bones.size()*sizeof(u32)+sizeof(Name);}
+    u32 mem_usage() { return sizeof(*this) + bones.size()*sizeof(u32) + sizeof(Name); }
 };
-class 	ENGINE_API	CPartition
+class ENGINE_API CPartition
 {
-	CPartDef			P[MAX_PARTS];
+    CPartDef P[MAX_PARTS];
 public:
-	IC CPartDef&		operator[] 			(u16 id)						{ return P[id]; }
-	IC const CPartDef&	part				(u16 id)				const	{ return P[id]; }
-	u16					part_id				(const shared_str& name) const	;
-	u32					mem_usage			()		{ return P[0].mem_usage()*MAX_PARTS;}
-	void				load				(IKinematics* V, LPCSTR model_name);
-    u8					count				() const {u8 ret=0;for(u8 i=0;imem_usage();
-		for (BoneMotionMapIt bm_it=m_motions.begin(); bm_it!=m_motions.end(); bm_it++)
-			for (MotionVecIt m_it=bm_it->second.begin(); m_it!=bm_it->second.end(); m_it++)
-				sz		+=	m_it->mem_usage();
-		return sz;
-	}
+    accel_map m_motion_map; // motion associations
+    accel_map m_cycle; // motion data itself (shared)
+    accel_map m_fx; // motion data itself (shared)
+    CPartition m_partition; // partition
+    u32 m_dwReference;
+    BoneMotionMap m_motions;
+    MotionDefVec m_mdefs;
+
+    shared_str m_id;
+
+
+    BOOL load(LPCSTR N, IReader* data, vecBones* bones);
+    MotionVec* bone_motions(shared_str bone_name);
+
+    u32 mem_usage()
+    {
+        u32 sz = sizeof(*this) + m_motion_map.size() * 6 + m_partition.mem_usage();
+        for (MotionDefVecIt it = m_mdefs.begin(); it != m_mdefs.end(); it++)
+            sz += it->mem_usage();
+        for (BoneMotionMapIt bm_it = m_motions.begin(); bm_it != m_motions.end(); bm_it++)
+            for (MotionVecIt m_it = bm_it->second.begin(); m_it != bm_it->second.end(); m_it++)
+                sz += m_it->mem_usage();
+        return sz;
+    }
 };
 
-class 	ENGINE_API	motions_container
+class ENGINE_API motions_container
 {
-	DEFINE_MAP			(shared_str,motions_value*,SharedMotionsMap,SharedMotionsMapIt);
-	SharedMotionsMap	container;
+    DEFINE_MAP(shared_str, motions_value*, SharedMotionsMap, SharedMotionsMapIt);
+    SharedMotionsMap container;
 public:
-						motions_container	();
-						~motions_container	();
-	bool				has					(shared_str key);
-	motions_value*		dock				(shared_str key, IReader *data, vecBones* bones);
-	void				dump				();
-	void				clean				(bool force_destroy);
+    motions_container();
+    ~motions_container();
+    bool has(shared_str key);
+    motions_value* dock(shared_str key, IReader* data, vecBones* bones);
+    void dump();
+    void clean(bool force_destroy);
 };
 
- extern	ENGINE_API	motions_container*	g_pMotionsContainer;
+extern ENGINE_API motions_container* g_pMotionsContainer;
 
-class 	ENGINE_API	shared_motions
+class ENGINE_API shared_motions
 {
 private:
-	motions_value*		p_;
+    motions_value* p_;
 protected:
-	// ref-counting
-	void				destroy			()							{	if (0==p_) return;	p_->m_dwReference--; 	if (0==p_->m_dwReference)	p_=0;	}
+    // ref-counting
+    void destroy() { if (0 == p_) return; p_->m_dwReference--; if (0 == p_->m_dwReference) p_ = 0; }
 public:
-	bool				create			(shared_str key, IReader *data, vecBones* bones);//{	motions_value* v = g_pMotionsContainer->dock(key,data,bones); if (0!=v) v->m_dwReference++; destroy(); p_ = v;	}
-	bool				create			(shared_motions const &rhs);//	{	motions_value* v = rhs.p_; if (0!=v) v->m_dwReference++; destroy(); p_ = v;	}
+    bool create(shared_str key, IReader* data, vecBones* bones);//{ motions_value* v = g_pMotionsContainer->dock(key,data,bones); if (0!=v) v->m_dwReference++; destroy(); p_ = v; }
+    bool create(shared_motions const& rhs);// { motions_value* v = rhs.p_; if (0!=v) v->m_dwReference++; destroy(); p_ = v; }
 public:
-	// construction
-						shared_motions	()							{	p_ = 0;											}
-						shared_motions	(shared_motions const &rhs)	{	p_ = 0;	create(rhs);							}
-						~shared_motions	()							{	destroy();										}
-
-	// assignment & accessors
-	shared_motions&		operator=		(shared_motions const &rhs)	{	create(rhs);return *this;	}
-	bool				operator==		(shared_motions const &rhs)	const {return (p_ == rhs.p_);}
-
-	// misc func
-	MotionVec*			bone_motions	(shared_str bone_name)		{	VERIFY(p_); return p_->bone_motions(bone_name);	}
-	accel_map*			motion_map		()							{	VERIFY(p_); return &p_->m_motion_map;			}
-	accel_map*			cycle			()							{	VERIFY(p_); return &p_->m_cycle;				}
-	accel_map*			fx				()							{	VERIFY(p_); return &p_->m_fx;					}
-	CPartition*			partition		()							{	VERIFY(p_); return &p_->m_partition;			}
-    MotionDefVec*		motion_defs		()							{	VERIFY(p_); return &p_->m_mdefs;				}
-    CMotionDef*			motion_def		(u16 idx)					{	VERIFY(p_); return &p_->m_mdefs[idx];			}
-
-	const shared_str	&id				() const					{	VERIFY(p_); return p_->m_id;					}
+    // construction
+    shared_motions() { p_ = 0; }
+    shared_motions(shared_motions const& rhs) { p_ = 0; create(rhs); }
+    ~shared_motions() { destroy(); }
+
+    // assignment & accessors
+    shared_motions& operator= (shared_motions const& rhs) { create(rhs); return *this; }
+    bool operator== (shared_motions const& rhs) const { return (p_ == rhs.p_); }
+
+    // misc func
+    MotionVec* bone_motions(shared_str bone_name) { VERIFY(p_); return p_->bone_motions(bone_name); }
+    accel_map* motion_map() { VERIFY(p_); return &p_->m_motion_map; }
+    accel_map* cycle() { VERIFY(p_); return &p_->m_cycle; }
+    accel_map* fx() { VERIFY(p_); return &p_->m_fx; }
+    CPartition* partition() { VERIFY(p_); return &p_->m_partition; }
+    MotionDefVec* motion_defs() { VERIFY(p_); return &p_->m_mdefs; }
+    CMotionDef* motion_def(u16 idx) { VERIFY(p_); return &p_->m_mdefs[idx]; }
+
+    const shared_str& id() const { VERIFY(p_); return p_->m_id; }
 
 };
 //---------------------------------------------------------------------------
diff --git a/src/xrEngine/StatGraph.cpp b/src/xrEngine/StatGraph.cpp
index 168534d707d..b43497d9470 100644
--- a/src/xrEngine/StatGraph.cpp
+++ b/src/xrEngine/StatGraph.cpp
@@ -6,216 +6,216 @@
 
 CStatGraph::CStatGraph()
 {
-	Device.seqRender.Add		(this,REG_PRIORITY_LOW-1000);
-	OnDeviceCreate();
-	mn					= 0;
-	mx					= 1;
-	max_item_count		= 1;
-	lt.set				(0,0);
-	rb.set				(200,200);
-	grid.set			(1,1);
-	grid_color			= 0xFF000000;
-	rect_color			= 0xFF000000;
-	grid_step.set		(1, 1);
-
-	AppendSubGraph(stCurve);
+    Device.seqRender.Add(this, REG_PRIORITY_LOW - 1000);
+    OnDeviceCreate();
+    mn = 0;
+    mx = 1;
+    max_item_count = 1;
+    lt.set(0, 0);
+    rb.set(200, 200);
+    grid.set(1, 1);
+    grid_color = 0xFF000000;
+    rect_color = 0xFF000000;
+    grid_step.set(1, 1);
+
+    AppendSubGraph(stCurve);
 }
 
 CStatGraph::~CStatGraph()
 {
-	Device.seqRender.Remove		(this);
-	OnDeviceDestroy();
-	m_Markers.clear();
+    Device.seqRender.Remove(this);
+    OnDeviceDestroy();
+    m_Markers.clear();
 }
 
 void CStatGraph::OnDeviceCreate()
 {
-	m_pRender->OnDeviceCreate();
-//	hGeomLine.create			(FVF::F_TL0uv,RCache.Vertex.Buffer(),RCache.Index.Buffer());
-//	hGeomTri.create				(FVF::F_TL0uv,RCache.Vertex.Buffer(),RCache.QuadIB);
+    m_pRender->OnDeviceCreate();
+    // hGeomLine.create (FVF::F_TL0uv,RCache.Vertex.Buffer(),RCache.Index.Buffer());
+    // hGeomTri.create (FVF::F_TL0uv,RCache.Vertex.Buffer(),RCache.QuadIB);
 }
 
 void CStatGraph::OnDeviceDestroy()
 {
-	m_pRender->OnDeviceDestroy();
-//	hGeomLine.destroy				();
-//	hGeomTri.destroy				();
+    m_pRender->OnDeviceDestroy();
+    // hGeomLine.destroy ();
+    // hGeomTri.destroy ();
 }
 
 void CStatGraph::OnRender()
 {
-	m_pRender->OnRender(*this);
-	/*
-	RCache.OnFrameEnd();
-
-	RenderBack();
-
-	u32			TriElem = 0;
-	u32			LineElem = 0;
-	for (SubGraphVecIt it=subgraphs.begin(); it!=subgraphs.end(); it++)
-	{
-		switch (it->style)
-		{
-		case stBar: 
-			{
-				TriElem += it->elements.size()*4;
-			}break;
-		case stCurve: 
-			{
-				LineElem += it->elements.size()*2;
-			}break;
-		case stBarLine: 
-			{
-				LineElem += it->elements.size()*4;
-			}break;
-		case stPoint: 
-			{
-				//				TriElem += it->elements.size()*4;
-			}break;
-		};
-	};
-
-	u32			dwOffsetTri = 0, dwOffsetLine = 0,dwCount;
-	FVF::TL0uv* pv_Tri_start	= NULL;
-	FVF::TL0uv* pv_Tri;
-	FVF::TL0uv* pv_Line_start	= NULL;
-	FVF::TL0uv* pv_Line;
-
-	if (TriElem)
-	{
-		pv_Tri_start = (FVF::TL0uv*)RCache.Vertex.Lock(TriElem,hGeomTri->vb_stride,dwOffsetTri);
-		pv_Tri = pv_Tri_start;
-
-		pv_Tri = pv_Tri_start;
-		for (SubGraphVecIt it=subgraphs.begin(); it!=subgraphs.end(); it++)
-		{
-			switch(it->style)
-			{
-			case stBar:		RenderBars		(&pv_Tri, &(it->elements));		break;
-			};
-		};
-		dwCount 				= u32(pv_Tri-pv_Tri_start);
-		RCache.Vertex.Unlock	(dwCount,hGeomTri->vb_stride);
-		RCache.set_Geometry		(hGeomTri);
-		RCache.Render	   		(D3DPT_TRIANGLELIST,dwOffsetTri,0, dwCount, 0, dwCount/2);
-	};
-
-	if (LineElem)
-	{
-		pv_Line_start = (FVF::TL0uv*)RCache.Vertex.Lock(LineElem,hGeomLine->vb_stride,dwOffsetLine);
-		pv_Line = pv_Line_start;
-
-		for (SubGraphVecIt it=subgraphs.begin(); it!=subgraphs.end(); it++)
-		{
-			switch(it->style)
-			{
-			case stCurve:	RenderLines		(&pv_Line, &(it->elements));	break;
-			case stBarLine:	RenderBarLines	(&pv_Line, &(it->elements));	break;
-			};
-		};
-
-		dwCount 				= u32(pv_Line-pv_Line_start);
-		RCache.Vertex.Unlock	(dwCount,hGeomLine->vb_stride);
-		RCache.set_Geometry		(hGeomLine);
-		RCache.Render	   		(D3DPT_LINELIST,dwOffsetLine,dwCount/2);
-	};
-
-	if (!m_Markers.empty())
-	{
-		dwOffsetLine = 0;
-		LineElem = m_Markers.size()*2;
-
-		pv_Line_start = (FVF::TL0uv*)RCache.Vertex.Lock(LineElem,hGeomLine->vb_stride,dwOffsetLine);
-		pv_Line = pv_Line_start;
-
-		RenderMarkers		(&pv_Line, &(m_Markers));
-
-		dwCount 				= u32(pv_Line-pv_Line_start);
-		RCache.Vertex.Unlock	(dwCount,hGeomLine->vb_stride);
-		RCache.set_Geometry		(hGeomLine);
-		RCache.Render	   		(D3DPT_LINELIST,dwOffsetLine,dwCount/2);
-	}
-	*/
+    m_pRender->OnRender(*this);
+    /*
+    RCache.OnFrameEnd();
+
+    RenderBack();
+
+    u32 TriElem = 0;
+    u32 LineElem = 0;
+    for (SubGraphVecIt it=subgraphs.begin(); it!=subgraphs.end(); it++)
+    {
+    switch (it->style)
+    {
+    case stBar:
+    {
+    TriElem += it->elements.size()*4;
+    }break;
+    case stCurve:
+    {
+    LineElem += it->elements.size()*2;
+    }break;
+    case stBarLine:
+    {
+    LineElem += it->elements.size()*4;
+    }break;
+    case stPoint:
+    {
+    // TriElem += it->elements.size()*4;
+    }break;
+    };
+    };
+
+    u32 dwOffsetTri = 0, dwOffsetLine = 0,dwCount;
+    FVF::TL0uv* pv_Tri_start = NULL;
+    FVF::TL0uv* pv_Tri;
+    FVF::TL0uv* pv_Line_start = NULL;
+    FVF::TL0uv* pv_Line;
+
+    if (TriElem)
+    {
+    pv_Tri_start = (FVF::TL0uv*)RCache.Vertex.Lock(TriElem,hGeomTri->vb_stride,dwOffsetTri);
+    pv_Tri = pv_Tri_start;
+
+    pv_Tri = pv_Tri_start;
+    for (SubGraphVecIt it=subgraphs.begin(); it!=subgraphs.end(); it++)
+    {
+    switch(it->style)
+    {
+    case stBar: RenderBars (&pv_Tri, &(it->elements)); break;
+    };
+    };
+    dwCount = u32(pv_Tri-pv_Tri_start);
+    RCache.Vertex.Unlock (dwCount,hGeomTri->vb_stride);
+    RCache.set_Geometry (hGeomTri);
+    RCache.Render (D3DPT_TRIANGLELIST,dwOffsetTri,0, dwCount, 0, dwCount/2);
+    };
+
+    if (LineElem)
+    {
+    pv_Line_start = (FVF::TL0uv*)RCache.Vertex.Lock(LineElem,hGeomLine->vb_stride,dwOffsetLine);
+    pv_Line = pv_Line_start;
+
+    for (SubGraphVecIt it=subgraphs.begin(); it!=subgraphs.end(); it++)
+    {
+    switch(it->style)
+    {
+    case stCurve: RenderLines (&pv_Line, &(it->elements)); break;
+    case stBarLine: RenderBarLines (&pv_Line, &(it->elements)); break;
+    };
+    };
+
+    dwCount = u32(pv_Line-pv_Line_start);
+    RCache.Vertex.Unlock (dwCount,hGeomLine->vb_stride);
+    RCache.set_Geometry (hGeomLine);
+    RCache.Render (D3DPT_LINELIST,dwOffsetLine,dwCount/2);
+    };
+
+    if (!m_Markers.empty())
+    {
+    dwOffsetLine = 0;
+    LineElem = m_Markers.size()*2;
+
+    pv_Line_start = (FVF::TL0uv*)RCache.Vertex.Lock(LineElem,hGeomLine->vb_stride,dwOffsetLine);
+    pv_Line = pv_Line_start;
+
+    RenderMarkers (&pv_Line, &(m_Markers));
+
+    dwCount = u32(pv_Line-pv_Line_start);
+    RCache.Vertex.Unlock (dwCount,hGeomLine->vb_stride);
+    RCache.set_Geometry (hGeomLine);
+    RCache.Render (D3DPT_LINELIST,dwOffsetLine,dwCount/2);
+    }
+    */
 };
 
 /*
-void CStatGraph::RenderBack	()
+void CStatGraph::RenderBack ()
 {
-	// draw back
-	u32			dwOffset,dwCount;
-	FVF::TL0uv* pv_start				= (FVF::TL0uv*)RCache.Vertex.Lock(4,hGeomTri->vb_stride,dwOffset);
-	FVF::TL0uv* pv						= pv_start;
-	// base rect
-	pv->set					(lt.x,rb.y,back_color); pv++;	// 0
-	pv->set					(lt.x,lt.y,back_color); pv++; 	// 1
-	pv->set					(rb.x,rb.y,back_color); pv++;	// 2
-	pv->set					(rb.x,lt.y,back_color); pv++;	// 3
-	// render	
-	dwCount 				= u32(pv-pv_start);
-	RCache.Vertex.Unlock	(dwCount,hGeomTri->vb_stride);
-	RCache.set_Geometry		(hGeomTri);
-	RCache.Render	   		(D3DPT_TRIANGLELIST,dwOffset,0, dwCount, 0, dwCount/2);	
-
-	//draw rect
-	pv_start				= (FVF::TL0uv*)RCache.Vertex.Lock(5,hGeomLine->vb_stride,dwOffset);
-	pv						= pv_start;
-	// base rect
-	pv->set					(lt.x,lt.y,rect_color); pv++;	// 0
-	pv->set					(rb.x-1,lt.y,rect_color); pv++; 	// 1
-	pv->set					(rb.x-1,rb.y,rect_color); pv++;	// 2
-	pv->set					(lt.x,rb.y,rect_color); pv++;	// 3
-	pv->set					(lt.x,lt.y,rect_color); pv++;	// 0
-	// render	
-	dwCount 				= u32(pv-pv_start);
-    RCache.Vertex.Unlock	(dwCount,hGeomLine->vb_stride);
-    RCache.set_Geometry		(hGeomLine);
-    RCache.Render	   		(D3DPT_LINESTRIP,dwOffset,4);
-
-	// draw grid
-	float elem_factor	= float(rb.y-lt.y)/float(mx-mn);
-	float base_y		= float(rb.y)+(mn*elem_factor);
-
-	int PNum_H_LinesUp	= int((base_y - float(lt.y)) / (grid_step.y*elem_factor));
-	int PNum_H_LinesDwn = u32((float(rb.y) - base_y) / (grid_step.y*elem_factor));
-	int Num_H_LinesUp = (grid.y < PNum_H_LinesUp) ? grid.y : PNum_H_LinesUp;
-	int Num_H_LinesDwn = (grid.y < PNum_H_LinesUp) ? grid.y : PNum_H_LinesDwn;
-
-	pv_start	= (FVF::TL0uv*)RCache.Vertex.Lock(	2 + 2*grid.x + Num_H_LinesUp*2 + Num_H_LinesDwn*2,
-													hGeomLine->vb_stride,dwOffset);
-    pv			= pv_start;
-    // base Coordinate Line
-	pv->set					(lt.x, int(base_y), base_color); pv++; // 0
-	pv->set					(rb.x, int(base_y), base_color); pv++;	// 0    
-    // grid
-//    float grid_offs_x		= float(rb.x-lt.x)/float(grid.x+1);
-//    float grid_offs_y		= float(rb.y-lt.y)/float(grid.y+1);
-    for (int g_x=1; g_x<=grid.x; g_x++)
-	{
-	    pv->set				(int(lt.x + g_x*grid_step.x*elem_factor),lt.y,grid_color); pv++; 	
-	    pv->set				(int(lt.x + g_x*grid_step.x*elem_factor),rb.y,grid_color); pv++; 	
-	}
-	for (int g_y=1; g_y<=Num_H_LinesDwn; g_y++)
-	{
-		pv->set				(lt.x,int(base_y+g_y*grid_step.y*elem_factor),grid_color); pv++;
-		pv->set				(rb.x,int(base_y+g_y*grid_step.y*elem_factor),grid_color); pv++;
-	};
-
-	for (g_y=1; g_y<=Num_H_LinesUp; g_y++)
-	{									
-		pv->set				(lt.x,int(base_y-g_y*grid_step.y*elem_factor),grid_color); pv++; 	
-		pv->set				(rb.x,int(base_y-g_y*grid_step.y*elem_factor),grid_color); pv++; 	
-	}    	
-
-	
-//    for (int g_y=1; g_y<=grid.y; g_y++){
-//	    pv->set				(lt.x,iFloor(g_y*grid_offs_y+lt.y),grid_color); pv++; 	
-//	    pv->set				(rb.x,iFloor(g_y*grid_offs_y+lt.y),grid_color); pv++; 	
-//	}
-
-	dwCount 				= u32(pv-pv_start);
-    RCache.Vertex.Unlock	(dwCount,hGeomLine->vb_stride);
-    RCache.set_Geometry		(hGeomLine);
-    RCache.Render	   		(D3DPT_LINELIST,dwOffset,dwCount/2);
+// draw back
+u32 dwOffset,dwCount;
+FVF::TL0uv* pv_start = (FVF::TL0uv*)RCache.Vertex.Lock(4,hGeomTri->vb_stride,dwOffset);
+FVF::TL0uv* pv = pv_start;
+// base rect
+pv->set (lt.x,rb.y,back_color); pv++; // 0
+pv->set (lt.x,lt.y,back_color); pv++; // 1
+pv->set (rb.x,rb.y,back_color); pv++; // 2
+pv->set (rb.x,lt.y,back_color); pv++; // 3
+// render
+dwCount = u32(pv-pv_start);
+RCache.Vertex.Unlock (dwCount,hGeomTri->vb_stride);
+RCache.set_Geometry (hGeomTri);
+RCache.Render (D3DPT_TRIANGLELIST,dwOffset,0, dwCount, 0, dwCount/2);
+
+//draw rect
+pv_start = (FVF::TL0uv*)RCache.Vertex.Lock(5,hGeomLine->vb_stride,dwOffset);
+pv = pv_start;
+// base rect
+pv->set (lt.x,lt.y,rect_color); pv++; // 0
+pv->set (rb.x-1,lt.y,rect_color); pv++; // 1
+pv->set (rb.x-1,rb.y,rect_color); pv++; // 2
+pv->set (lt.x,rb.y,rect_color); pv++; // 3
+pv->set (lt.x,lt.y,rect_color); pv++; // 0
+// render
+dwCount = u32(pv-pv_start);
+RCache.Vertex.Unlock (dwCount,hGeomLine->vb_stride);
+RCache.set_Geometry (hGeomLine);
+RCache.Render (D3DPT_LINESTRIP,dwOffset,4);
+
+// draw grid
+float elem_factor = float(rb.y-lt.y)/float(mx-mn);
+float base_y = float(rb.y)+(mn*elem_factor);
+
+int PNum_H_LinesUp = int((base_y - float(lt.y)) / (grid_step.y*elem_factor));
+int PNum_H_LinesDwn = u32((float(rb.y) - base_y) / (grid_step.y*elem_factor));
+int Num_H_LinesUp = (grid.y < PNum_H_LinesUp) ? grid.y : PNum_H_LinesUp;
+int Num_H_LinesDwn = (grid.y < PNum_H_LinesUp) ? grid.y : PNum_H_LinesDwn;
+
+pv_start = (FVF::TL0uv*)RCache.Vertex.Lock( 2 + 2*grid.x + Num_H_LinesUp*2 + Num_H_LinesDwn*2,
+hGeomLine->vb_stride,dwOffset);
+pv = pv_start;
+// base Coordinate Line
+pv->set (lt.x, int(base_y), base_color); pv++; // 0
+pv->set (rb.x, int(base_y), base_color); pv++; // 0
+// grid
+// float grid_offs_x = float(rb.x-lt.x)/float(grid.x+1);
+// float grid_offs_y = float(rb.y-lt.y)/float(grid.y+1);
+for (int g_x=1; g_x<=grid.x; g_x++)
+{
+pv->set (int(lt.x + g_x*grid_step.x*elem_factor),lt.y,grid_color); pv++;
+pv->set (int(lt.x + g_x*grid_step.x*elem_factor),rb.y,grid_color); pv++;
+}
+for (int g_y=1; g_y<=Num_H_LinesDwn; g_y++)
+{
+pv->set (lt.x,int(base_y+g_y*grid_step.y*elem_factor),grid_color); pv++;
+pv->set (rb.x,int(base_y+g_y*grid_step.y*elem_factor),grid_color); pv++;
+};
+
+for (g_y=1; g_y<=Num_H_LinesUp; g_y++)
+{
+pv->set (lt.x,int(base_y-g_y*grid_step.y*elem_factor),grid_color); pv++;
+pv->set (rb.x,int(base_y-g_y*grid_step.y*elem_factor),grid_color); pv++;
+}
+
+
+// for (int g_y=1; g_y<=grid.y; g_y++){
+// pv->set (lt.x,iFloor(g_y*grid_offs_y+lt.y),grid_color); pv++;
+// pv->set (rb.x,iFloor(g_y*grid_offs_y+lt.y),grid_color); pv++;
+// }
+
+dwCount = u32(pv-pv_start);
+RCache.Vertex.Unlock (dwCount,hGeomLine->vb_stride);
+RCache.set_Geometry (hGeomLine);
+RCache.Render (D3DPT_LINELIST,dwOffset,dwCount/2);
 
 
 };
@@ -223,125 +223,125 @@ void CStatGraph::RenderBack	()
 /*
 void CStatGraph::RenderBars(FVF::TL0uv** ppv, ElementsDeq* pelements)
 {
-	float elem_offs		= float(rb.x-lt.x)/max_item_count;
-	float elem_factor	= float(rb.y-lt.y)/float(mx-mn);
-	float base_y		= float(rb.y)+(mn*elem_factor);
-
-	float column_width = elem_offs;
-	if (column_width > 1) column_width--;
-	for (ElementsDeqIt it=pelements->begin(); it!=pelements->end(); it++)
-	{
-		float X		= float(it-pelements->begin())*elem_offs+lt.x;
-		float Y0	= base_y;
-		float Y1	= base_y - it->data*elem_factor;
-
-		if (Y1 > Y0)
-		{
-			(*ppv)->set		(X,Y1,it->color); (*ppv)++;
-			(*ppv)->set		(X,Y0,it->color); (*ppv)++;
-			(*ppv)->set		(X+column_width,Y1,it->color); (*ppv)++;
-			(*ppv)->set		(X+column_width,Y0,it->color); (*ppv)++;
-		}
-		else
-		{
-			(*ppv)->set		(X,Y0,it->color); (*ppv)++;
-			(*ppv)->set		(X,Y1,it->color); (*ppv)++;
-			(*ppv)->set		(X+column_width,Y0,it->color); (*ppv)++;
-			(*ppv)->set		(X+column_width,Y1,it->color); (*ppv)++;
-		};
-	};	
+float elem_offs = float(rb.x-lt.x)/max_item_count;
+float elem_factor = float(rb.y-lt.y)/float(mx-mn);
+float base_y = float(rb.y)+(mn*elem_factor);
+
+float column_width = elem_offs;
+if (column_width > 1) column_width--;
+for (ElementsDeqIt it=pelements->begin(); it!=pelements->end(); it++)
+{
+float X = float(it-pelements->begin())*elem_offs+lt.x;
+float Y0 = base_y;
+float Y1 = base_y - it->data*elem_factor;
+
+if (Y1 > Y0)
+{
+(*ppv)->set (X,Y1,it->color); (*ppv)++;
+(*ppv)->set (X,Y0,it->color); (*ppv)++;
+(*ppv)->set (X+column_width,Y1,it->color); (*ppv)++;
+(*ppv)->set (X+column_width,Y0,it->color); (*ppv)++;
+}
+else
+{
+(*ppv)->set (X,Y0,it->color); (*ppv)++;
+(*ppv)->set (X,Y1,it->color); (*ppv)++;
+(*ppv)->set (X+column_width,Y0,it->color); (*ppv)++;
+(*ppv)->set (X+column_width,Y1,it->color); (*ppv)++;
+};
+};
 };
 */
 /*
 void CStatGraph::RenderLines( FVF::TL0uv** ppv, ElementsDeq* pelements )
 {
-	float elem_offs		= float(rb.x-lt.x)/max_item_count;
-	float elem_factor	= float(rb.y-lt.y)/float(mx-mn);
-	float base_y		= float(rb.y)+(mn*elem_factor);
-
-	for (ElementsDeqIt it=pelements->begin()+1;  it!=pelements->end() && it!=pelements->end()+1; it++)
-	{
-		ElementsDeqIt it_prev = it-1;
-		float X0	= float(it_prev-pelements->begin())*elem_offs+lt.x;
-		float Y0	= base_y-it_prev->data*elem_factor;
-		(*ppv)->set		(X0,Y0,it->color); (*ppv)++;
-		float X1	= float(it-pelements->begin())*elem_offs+lt.x;
-		float Y1	= base_y-it->data*elem_factor;
-		(*ppv)->set		(X1,Y1,it->color); (*ppv)++;
-	}
+float elem_offs = float(rb.x-lt.x)/max_item_count;
+float elem_factor = float(rb.y-lt.y)/float(mx-mn);
+float base_y = float(rb.y)+(mn*elem_factor);
+
+for (ElementsDeqIt it=pelements->begin()+1; it!=pelements->end() && it!=pelements->end()+1; it++)
+{
+ElementsDeqIt it_prev = it-1;
+float X0 = float(it_prev-pelements->begin())*elem_offs+lt.x;
+float Y0 = base_y-it_prev->data*elem_factor;
+(*ppv)->set (X0,Y0,it->color); (*ppv)++;
+float X1 = float(it-pelements->begin())*elem_offs+lt.x;
+float Y1 = base_y-it->data*elem_factor;
+(*ppv)->set (X1,Y1,it->color); (*ppv)++;
+}
 };
 */
 
 /*
 void CStatGraph::RenderBarLines( FVF::TL0uv** ppv, ElementsDeq* pelements )
 {
-	float elem_offs		= float(rb.x-lt.x)/max_item_count;
-	float elem_factor	= float(rb.y-lt.y)/float(mx-mn);
-	float base_y		= float(rb.y)+(mn*elem_factor);
-
-	for (ElementsDeqIt it=pelements->begin()+1; it!=pelements->end() && it!=pelements->end()+1; it++)
-	{
-		ElementsDeqIt it_prev = it-1;
-		float X0	= float(it_prev-pelements->begin())*elem_offs+lt.x+elem_offs;
-		float Y0	= base_y-it_prev->data*elem_factor;
-		(*ppv)->set		(X0,Y0,it->color); (*ppv)++;
-		float X1	= float(it-pelements->begin())*elem_offs+lt.x;
-		float Y1	= base_y-it->data*elem_factor;
-		(*ppv)->set		(X1,Y1,it->color); (*ppv)++;
-		(*ppv)->set		(X1,Y1,it->color); (*ppv)++;
-		X1 += elem_offs;
-		(*ppv)->set		(X1,Y1,it->color); (*ppv)++;
-	}
+float elem_offs = float(rb.x-lt.x)/max_item_count;
+float elem_factor = float(rb.y-lt.y)/float(mx-mn);
+float base_y = float(rb.y)+(mn*elem_factor);
+
+for (ElementsDeqIt it=pelements->begin()+1; it!=pelements->end() && it!=pelements->end()+1; it++)
+{
+ElementsDeqIt it_prev = it-1;
+float X0 = float(it_prev-pelements->begin())*elem_offs+lt.x+elem_offs;
+float Y0 = base_y-it_prev->data*elem_factor;
+(*ppv)->set (X0,Y0,it->color); (*ppv)++;
+float X1 = float(it-pelements->begin())*elem_offs+lt.x;
+float Y1 = base_y-it->data*elem_factor;
+(*ppv)->set (X1,Y1,it->color); (*ppv)++;
+(*ppv)->set (X1,Y1,it->color); (*ppv)++;
+X1 += elem_offs;
+(*ppv)->set (X1,Y1,it->color); (*ppv)++;
+}
 };
 */
 
 /*
 void CStatGraph::RenderPoints( FVF::TL0uv** ppv, ElementsDeq* pelements )
 {
-	float elem_offs		= float(rb.x-lt.x)/max_item_count;
-	float elem_factor	= float(rb.y-lt.y)/float(mx-mn);
-	float base_y		= float(rb.y)+(mn*elem_factor);
-
-	for (ElementsDeqIt it=pelements->begin()+1; it!=pelements->end(); it++)
-	{
-		float X1	= float(it-pelements->begin())*elem_offs+lt.x;
-		float Y1	= base_y-it->data*elem_factor;
-		(*ppv)->set		(X1,Y1,it->color); (*ppv)++;
-	}
+float elem_offs = float(rb.x-lt.x)/max_item_count;
+float elem_factor = float(rb.y-lt.y)/float(mx-mn);
+float base_y = float(rb.y)+(mn*elem_factor);
+
+for (ElementsDeqIt it=pelements->begin()+1; it!=pelements->end(); it++)
+{
+float X1 = float(it-pelements->begin())*elem_offs+lt.x;
+float Y1 = base_y-it->data*elem_factor;
+(*ppv)->set (X1,Y1,it->color); (*ppv)++;
+}
 };
 */
 /*
-void	CStatGraph::RenderMarkers	( FVF::TL0uv** ppv, MarkersDeq* pmarkers )
+void CStatGraph::RenderMarkers ( FVF::TL0uv** ppv, MarkersDeq* pmarkers )
+{
+float elem_offs = float(rb.x-lt.x)/max_item_count;
+float elem_factor = float(rb.y-lt.y)/float(mx-mn);
+float base_y = float(rb.y)+(mn*elem_factor);
+
+for (MarkersDeqIt it=pmarkers->begin(); it!=pmarkers->end() && it!=pmarkers->end()+1; it++)
+{
+SMarker &CurMarker = *it;
+float X0 = 0, Y0 = 0, X1 = 0, Y1 = 0;
+switch (CurMarker.m_eStyle)
 {
-	float elem_offs		= float(rb.x-lt.x)/max_item_count;
-	float elem_factor	= float(rb.y-lt.y)/float(mx-mn);
-	float base_y		= float(rb.y)+(mn*elem_factor);
-
-	for (MarkersDeqIt it=pmarkers->begin();  it!=pmarkers->end() && it!=pmarkers->end()+1; it++)
-	{
-		SMarker &CurMarker = *it;
-		float X0 = 0, Y0 = 0, X1 = 0, Y1 = 0;
-		switch (CurMarker.m_eStyle)
-		{
-		case stVert:
-			{
-				X0 = CurMarker.m_fPos*elem_offs+lt.x;
-				clamp(X0, float(lt.x), float(rb.x));
-				X1 = X0;
-				Y0 = float(lt.y);
-				Y1 = float(rb.y);
-			}break;
-		case stHor:
-			{
-				X0 = float(lt.x);
-				X1 = float(rb.x);
-				Y0 = base_y - CurMarker.m_fPos*elem_factor;
-				clamp(Y0, float(lt.y), float(rb.y));
-				Y1 = Y0;
-			}break;
-		}
-		(*ppv)->set		(X0,Y0,CurMarker.m_dwColor); (*ppv)++;
-		(*ppv)->set		(X1,Y1,CurMarker.m_dwColor); (*ppv)++;
-	}
+case stVert:
+{
+X0 = CurMarker.m_fPos*elem_offs+lt.x;
+clamp(X0, float(lt.x), float(rb.x));
+X1 = X0;
+Y0 = float(lt.y);
+Y1 = float(rb.y);
+}break;
+case stHor:
+{
+X0 = float(lt.x);
+X1 = float(rb.x);
+Y0 = base_y - CurMarker.m_fPos*elem_factor;
+clamp(Y0, float(lt.y), float(rb.y));
+Y1 = Y0;
+}break;
+}
+(*ppv)->set (X0,Y0,CurMarker.m_dwColor); (*ppv)++;
+(*ppv)->set (X1,Y1,CurMarker.m_dwColor); (*ppv)++;
+}
 }
 */
\ No newline at end of file
diff --git a/src/xrEngine/StatGraph.h b/src/xrEngine/StatGraph.h
index 59b4bc6c55b..252565cf5e2 100644
--- a/src/xrEngine/StatGraph.h
+++ b/src/xrEngine/StatGraph.h
@@ -6,161 +6,164 @@
 #include "../Include/xrRender/StatGraphRender.h"
 
 //---------------------------------------------------------------------------
-class ENGINE_API CStatGraph	: public pureRender
+class ENGINE_API CStatGraph : public pureRender
 {
-	friend class dxStatGraphRender;
+    friend class dxStatGraphRender;
 public:
-	enum EStyle{
-    	stBar,
+    enum EStyle
+    {
+        stBar,
         stCurve,
-		stBarLine,
-		stPoint,
-		stVert,
-		stHor,
-   };
+        stBarLine,
+        stPoint,
+        stVert,
+        stHor,
+    };
 protected:
-	struct SElement{
-    	u32 		color;
-        float		data;
-			        SElement(float d, u32 clr)
+    struct SElement
+    {
+        u32 color;
+        float data;
+        SElement(float d, u32 clr)
         {
-        	color	= clr;
-            data	= d;
+            color = clr;
+            data = d;
         }
     };
-	DEFINE_DEQUE	(SElement,ElementsDeq,ElementsDeqIt);
-	struct SSubGraph
-	{
-		EStyle			style;
-		ElementsDeq		elements;
-					SSubGraph(EStyle s)
-		{
-			style = s;
-		};
-					void SetStyle (EStyle s)
-		{
-			style = s;
-		};
-	};
-	DEFINE_VECTOR	(SSubGraph,SubGraphVec,SubGraphVecIt);
-	SubGraphVec		subgraphs;
-	
-	float			mn, mx;
-	u32				max_item_count;
-	Ivector2 		lt,rb;
-	Ivector2 		grid;
-	Fvector2		grid_step;
-	u32				grid_color;
-	u32				base_color;
-	u32				rect_color;
-	u32				back_color;
-	FactoryPtr	m_pRender;
-	//ref_geom 		hGeomTri;
-	//ref_geom 		hGeomLine;
-
-	
-	struct SMarker {
-		EStyle			m_eStyle;
-		float			m_fPos;
-		u32				m_dwColor;
-	};
-
-	DEFINE_DEQUE	(SMarker,MarkersDeq,MarkersDeqIt);
-	MarkersDeq		m_Markers;
+    DEFINE_DEQUE(SElement, ElementsDeq, ElementsDeqIt);
+    struct SSubGraph
+    {
+        EStyle style;
+        ElementsDeq elements;
+        SSubGraph(EStyle s)
+        {
+            style = s;
+        };
+        void SetStyle(EStyle s)
+        {
+            style = s;
+        };
+    };
+    DEFINE_VECTOR(SSubGraph, SubGraphVec, SubGraphVecIt);
+    SubGraphVec subgraphs;
+
+    float mn, mx;
+    u32 max_item_count;
+    Ivector2 lt, rb;
+    Ivector2 grid;
+    Fvector2 grid_step;
+    u32 grid_color;
+    u32 base_color;
+    u32 rect_color;
+    u32 back_color;
+    FactoryPtr m_pRender;
+    //ref_geom hGeomTri;
+    //ref_geom hGeomLine;
+
+
+    struct SMarker
+    {
+        EStyle m_eStyle;
+        float m_fPos;
+        u32 m_dwColor;
+    };
+
+    DEFINE_DEQUE(SMarker, MarkersDeq, MarkersDeqIt);
+    MarkersDeq m_Markers;
 
 protected:
-//	virtual void	RenderBack		();
+    // virtual void RenderBack ();
 
-//	virtual void	RenderBars		( FVF::TL0uv** ppv, ElementsDeq* pelements );
-//	virtual void	RenderLines		( FVF::TL0uv** ppv, ElementsDeq* pelements );
-//	virtual void	RenderBarLines	( FVF::TL0uv** ppv, ElementsDeq* pelements );
-////	virtual void	RenderPoints	( FVF::TL0uv** ppv, ElementsDeq* pelements );
-//	virtual	void	RenderMarkers	( FVF::TL0uv** ppv, MarkersDeq* pmarkers );
+    // virtual void RenderBars ( FVF::TL0uv** ppv, ElementsDeq* pelements );
+    // virtual void RenderLines ( FVF::TL0uv** ppv, ElementsDeq* pelements );
+    // virtual void RenderBarLines ( FVF::TL0uv** ppv, ElementsDeq* pelements );
+    //// virtual void RenderPoints ( FVF::TL0uv** ppv, ElementsDeq* pelements );
+    // virtual void RenderMarkers ( FVF::TL0uv** ppv, MarkersDeq* pmarkers );
 public:
-  					CStatGraph	();
-					~CStatGraph	();
-    virtual void 	OnRender	();
-			void 	OnDeviceCreate	();
-			void 	OnDeviceDestroy	();	
+    CStatGraph();
+    ~CStatGraph();
+    virtual void OnRender();
+    void OnDeviceCreate();
+    void OnDeviceDestroy();
 
-    IC 	void		SetStyle	(EStyle s, u32 SubGraphID = 0)
+    IC void SetStyle(EStyle s, u32 SubGraphID = 0)
     {
-		if (SubGraphID >= subgraphs.size()) return;
-		SubGraphVecIt it = subgraphs.begin() + SubGraphID;
-		it->SetStyle(s);
+        if (SubGraphID >= subgraphs.size()) return;
+        SubGraphVecIt it = subgraphs.begin() + SubGraphID;
+        it->SetStyle(s);
     }
-	
-    IC	void		SetRect		(int l, int t, int w, int h, u32 rect_clr, u32 back_clr)
+
+    IC void SetRect(int l, int t, int w, int h, u32 rect_clr, u32 back_clr)
     {
-        lt.set		(l,t);
-        rb.set		(l+w,t+h);
-        rect_color	= rect_clr;
-		back_color	= back_clr;
+        lt.set(l, t);
+        rb.set(l + w, t + h);
+        rect_color = rect_clr;
+        back_color = back_clr;
     }
-    IC	void		SetGrid		(int w_div, float w_step, int h_div, float h_step, u32 grid_clr, u32 base_clr)
+    IC void SetGrid(int w_div, float w_step, int h_div, float h_step, u32 grid_clr, u32 base_clr)
     {
-        grid.set	(w_div,h_div);
-		grid_step.set (w_step, h_step);
-        grid_color 	= grid_clr;
-		base_color	= base_clr;
+        grid.set(w_div, h_div);
+        grid_step.set(w_step, h_step);
+        grid_color = grid_clr;
+        base_color = base_clr;
     }
-    IC	void		SetMinMax	(float _mn, float _mx, u32 item_count)
+    IC void SetMinMax(float _mn, float _mx, u32 item_count)
     {
-        mn			= _mn;
-        mx			= _mx;
+        mn = _mn;
+        mx = _mx;
         max_item_count = item_count;
-		for (SubGraphVecIt it=subgraphs.begin(); it!=subgraphs.end(); it++)
-		{
-			while(it->elements.size()>max_item_count) it->elements.pop_front();
-		};
+        for (SubGraphVecIt it = subgraphs.begin(); it != subgraphs.end(); it++)
+        {
+            while (it->elements.size() > max_item_count) it->elements.pop_front();
+        };
     }
-    IC	void		AppendItem	(float d, u32 clr, u32 SubGraphID = 0)
+    IC void AppendItem(float d, u32 clr, u32 SubGraphID = 0)
     {
-		if (SubGraphID>=subgraphs.size()) return;
+        if (SubGraphID >= subgraphs.size()) return;
 
-    	clamp		(d,mn,mx);
-		
-		SubGraphVecIt it = subgraphs.begin() + SubGraphID;
-        it->elements.push_back(SElement(d,clr));
-        while(it->elements.size()>max_item_count) it->elements.pop_front();
+        clamp(d, mn, mx);
+
+        SubGraphVecIt it = subgraphs.begin() + SubGraphID;
+        it->elements.push_back(SElement(d, clr));
+        while (it->elements.size() > max_item_count) it->elements.pop_front();
     };
-	IC	u32			AppendSubGraph	(EStyle S)
-	{
-		subgraphs.push_back(SSubGraph(S));
-		return subgraphs.size()-1;
-	};
-
-	IC	void		AddMarker (EStyle Style, float pos, u32 Color)
-	{
-		SMarker NewMarker;
-		NewMarker.m_dwColor = Color;
-		NewMarker.m_eStyle = Style;
-		NewMarker.m_fPos = pos;
-
-		m_Markers.push_back(NewMarker);
-	};
-	
-	IC  const SMarker& Marker(u32 ID)
-	{
-		VERIFY(ID= m_Markers.size()) return;
-		SMarker &pMarker = m_Markers[ID];
-		pMarker.m_fPos = NewPos;
-	};
-	IC	void		ClearMarkers()
-	{
-		m_Markers.clear();
-	}
-
-	IC	void		RemoveMarker(u32 ID)
-	{
-		if (ID >= m_Markers.size()) return;
-		m_Markers.erase(m_Markers.begin()+ID);
-	}
+    IC u32 AppendSubGraph(EStyle S)
+    {
+        subgraphs.push_back(SSubGraph(S));
+        return subgraphs.size() - 1;
+    };
+
+    IC void AddMarker(EStyle Style, float pos, u32 Color)
+    {
+        SMarker NewMarker;
+        NewMarker.m_dwColor = Color;
+        NewMarker.m_eStyle = Style;
+        NewMarker.m_fPos = pos;
+
+        m_Markers.push_back(NewMarker);
+    };
+
+    IC const SMarker& Marker(u32 ID)
+    {
+        VERIFY(ID < m_Markers.size());
+        return m_Markers[ID];
+    };
+
+    IC void UpdateMarkerPos(u32 ID, float NewPos)
+    {
+        if (ID >= m_Markers.size()) return;
+        SMarker& pMarker = m_Markers[ID];
+        pMarker.m_fPos = NewPos;
+    };
+    IC void ClearMarkers()
+    {
+        m_Markers.clear();
+    }
+
+    IC void RemoveMarker(u32 ID)
+    {
+        if (ID >= m_Markers.size()) return;
+        m_Markers.erase(m_Markers.begin() + ID);
+    }
 };
 #endif
diff --git a/src/xrEngine/Stats.cpp b/src/xrEngine/Stats.cpp
index 521cf3069b0..d1c77e28b54 100644
--- a/src/xrEngine/Stats.cpp
+++ b/src/xrEngine/Stats.cpp
@@ -9,512 +9,526 @@
 
 #include "../Include/xrRender/DrawUtils.h"
 
-int		g_ErrorLineCount	= 15;
-Flags32 g_stats_flags		= {0};
+int g_ErrorLineCount = 15;
+Flags32 g_stats_flags = {0};
 
 // stats
 DECLARE_RP(Stats);
 
-class	optimizer	{
-	float	average_	;
-	BOOL	enabled_	;
+class optimizer
+{
+    float average_;
+    BOOL enabled_;
 public:
-	optimizer	()		{
-		average_	= 30.f;
-//		enabled_	= TRUE;
-//		disable		();
-		// because Engine is not exist
-		enabled_	= FALSE;
-	}
-
-	BOOL	enabled	()	{ return enabled_;	}
-	void	enable	()	{ if (!enabled_)	{ Engine.External.tune_resume	();	enabled_=TRUE;	}}
-	void	disable	()	{ if (enabled_)		{ Engine.External.tune_pause	();	enabled_=FALSE; }}
-	void	update	(float value)	{
-		if (value < average_*0.7f)	{
-			// 25% deviation
-			enable	();
-		} else {
-			disable	();
-		};
-		average_	= 0.99f*average_ + 0.01f*value;
-	};
+    optimizer()
+    {
+        average_ = 30.f;
+        //  enabled_ = TRUE;
+        //  disable ();
+        // because Engine is not exist
+        enabled_ = FALSE;
+    }
+
+    BOOL enabled() { return enabled_; }
+    void enable() { if (!enabled_) { Engine.External.tune_resume(); enabled_ = TRUE; } }
+    void disable() { if (enabled_) { Engine.External.tune_pause(); enabled_ = FALSE; } }
+    void update(float value)
+    {
+        if (value < average_*0.7f)
+        {
+            // 25% deviation
+            enable();
+        }
+        else
+        {
+            disable();
+        };
+        average_ = 0.99f*average_ + 0.01f*value;
+    };
 };
-static	optimizer	vtune;
+static optimizer vtune;
 
 //////////////////////////////////////////////////////////////////////
 // Construction/Destruction
 //////////////////////////////////////////////////////////////////////
-BOOL			g_bDisableRedText	= FALSE;
-CStats::CStats	()
+BOOL   g_bDisableRedText = FALSE;
+CStats::CStats()
 {
-	fFPS				= 30.f;
-	fRFPS				= 30.f;
-	fTPS				= 0;
-	pFont				= 0;
-	fMem_calls			= 0;
-	RenderDUMP_DT_Count = 0;
-	Device.seqRender.Add		(this,REG_PRIORITY_LOW-1000);
+    fFPS = 30.f;
+    fRFPS = 30.f;
+    fTPS = 0;
+    pFont = 0;
+    fMem_calls = 0;
+    RenderDUMP_DT_Count = 0;
+    Device.seqRender.Add(this, REG_PRIORITY_LOW - 1000);
 }
 
 CStats::~CStats()
 {
-	Device.seqRender.Remove		(this);
-	xr_delete		(pFont);
+    Device.seqRender.Remove(this);
+    xr_delete(pFont);
 }
 
 void _draw_cam_pos(CGameFont* pFont)
 {
-	float sz		= pFont->GetHeight();
-	pFont->SetHeightI(0.02f);
-	pFont->SetColor	(0xffffffff);
-	pFont->Out		(10, 600, "CAMERA POSITION:  [%3.2f,%3.2f,%3.2f]",VPUSH(Device.vCameraPosition));
-	pFont->SetHeight(sz);
-	pFont->OnRender	();
+    float sz = pFont->GetHeight();
+    pFont->SetHeightI(0.02f);
+    pFont->SetColor(0xffffffff);
+    pFont->Out(10, 600, "CAMERA POSITION:  [%3.2f,%3.2f,%3.2f]", VPUSH(Device.vCameraPosition));
+    pFont->SetHeight(sz);
+    pFont->OnRender();
 }
 
-void CStats::Show() 
+void CStats::Show()
 {
-	// Stop timers
-	{
-		EngineTOTAL.FrameEnd		();	
-		Sheduler.FrameEnd			();	
-		UpdateClient.FrameEnd		();	
-		Physics.FrameEnd			();	
-		ph_collision.FrameEnd		();
-		ph_core.FrameEnd			();
-		Animation.FrameEnd			();	
-		AI_Think.FrameEnd			();
-		AI_Range.FrameEnd			();
-		AI_Path.FrameEnd			();
-		AI_Node.FrameEnd			();
-		AI_Vis.FrameEnd				();
-		AI_Vis_Query.FrameEnd		();
-		AI_Vis_RayTests.FrameEnd	();
-		
-		RenderTOTAL.FrameEnd		();
-		RenderCALC.FrameEnd			();
-		RenderCALC_HOM.FrameEnd		();
-		RenderDUMP.FrameEnd			();	
-		RenderDUMP_RT.FrameEnd		();
-		RenderDUMP_SKIN.FrameEnd	();	
-		RenderDUMP_Wait.FrameEnd	();	
-		RenderDUMP_Wait_S.FrameEnd	();	
-		RenderDUMP_HUD.FrameEnd		();	
-		RenderDUMP_Glows.FrameEnd	();	
-		RenderDUMP_Lights.FrameEnd	();	
-		RenderDUMP_WM.FrameEnd		();	
-		RenderDUMP_DT_VIS.FrameEnd	();	
-		RenderDUMP_DT_Render.FrameEnd();	
-		RenderDUMP_DT_Cache.FrameEnd();
-		RenderDUMP_Pcalc.FrameEnd	();	
-		RenderDUMP_Scalc.FrameEnd	();	
-		RenderDUMP_Srender.FrameEnd	();	
-		
-		Sound.FrameEnd				();
-		Input.FrameEnd				();
-		clRAY.FrameEnd				();	
-		clBOX.FrameEnd				();
-		clFRUSTUM.FrameEnd			();
-		
-		netClient1.FrameEnd			();
-		netClient2.FrameEnd			();
-		netServer.FrameEnd			();
-
-		netClientCompressor.FrameEnd();
-		netServerCompressor.FrameEnd();
-		
-		TEST0.FrameEnd				();
-		TEST1.FrameEnd				();
-		TEST2.FrameEnd				();
-		TEST3.FrameEnd				();
-
-		g_SpatialSpace->stat_insert.FrameEnd		();
-		g_SpatialSpace->stat_remove.FrameEnd		();
-		g_SpatialSpacePhysic->stat_insert.FrameEnd	();
-		g_SpatialSpacePhysic->stat_remove.FrameEnd	();
-	}
-
-	// calc FPS & TPS
-	if (Device.fTimeDelta>EPS_S) {
-		float fps  = 1.f/Device.fTimeDelta;
-		//if (Engine.External.tune_enabled)	vtune.update	(fps);
-		float fOne = 0.3f;
-		float fInv = 1.f-fOne;
-		fFPS = fInv*fFPS + fOne*fps;
-
-		if (RenderTOTAL.result>EPS_S) {
-			u32	rendered_polies = Device.m_pRender->GetCacheStatPolys();
-			fTPS = fInv*fTPS + fOne*float(rendered_polies)/(RenderTOTAL.result*1000.f);
-			//fTPS = fInv*fTPS + fOne*float(RCache.stat.polys)/(RenderTOTAL.result*1000.f);
-			fRFPS= fInv*fRFPS+ fOne*1000.f/RenderTOTAL.result;
-		}
-	}
-	{
-		float mem_count		= float	(Memory.stat_calls);
-		if (mem_count>fMem_calls)	fMem_calls	=	mem_count;
-		else						fMem_calls	=	.9f*fMem_calls + .1f*mem_count;
-		Memory.stat_calls	= 0		;
-	}
-
-	////////////////////////////////////////////////
-	if (g_dedicated_server) return;
-	////////////////////////////////////////////////
-	int frm = 2000;
-	div_t ddd = div(Device.dwFrame,frm);
-	if( ddd.rem < frm/2.0f ){
-		pFont->SetColor	(0xFFFFFFFF	);
-		pFont->OutSet	(0,0);
-		pFont->OutNext	(*eval_line_1);
-		pFont->OutNext	(*eval_line_2);
-		pFont->OutNext	(*eval_line_3);
-		pFont->OnRender	();
-	}
-
-	CGameFont& F = *pFont;
-	float		f_base_size	= 0.01f;
-				F.SetHeightI	(f_base_size);
-
-	if (vtune.enabled())	{
-		float sz		= pFont->GetHeight();
-		pFont->SetHeightI(0.02f);
-		pFont->SetColor	(0xFFFF0000	);
-		pFont->OutSet	(Device.dwWidth/2.0f+(pFont->SizeOf_("--= tune =--")/2.0f),Device.dwHeight/2.0f);
-		pFont->OutNext	("--= tune =--");
-		pFont->OnRender	();
-		pFont->SetHeight(sz);
-	};
-
-	// Show them
-	if (psDeviceFlags.test(rsStatistic))
-	{
-		static float	r_ps		= 0;
-		static float	b_ps		= 0;
-		r_ps						= .99f*r_ps + .01f*(clRAY.count/clRAY.result);
-		b_ps						= .99f*b_ps + .01f*(clBOX.count/clBOX.result);
-
-		CSound_stats				snd_stat;
-		::Sound->statistic			(&snd_stat,0);
-		F.SetColor	(0xFFFFFFFF	);
-
-		F.OutSet	(0,0);
-		F.OutNext	("FPS/RFPS:    %3.1f/%3.1f",fFPS,fRFPS);
-		F.OutNext	("TPS:         %2.2f M",	fTPS);
-		m_pRender->OutData1(F);
-		//F.OutNext	("VERT:        %d/%d",		RCache.stat.verts,RCache.stat.calls?RCache.stat.verts/RCache.stat.calls:0);
-		//F.OutNext	("POLY:        %d/%d",		RCache.stat.polys,RCache.stat.calls?RCache.stat.polys/RCache.stat.calls:0);
-		//F.OutNext	("DIP/DP:      %d",			RCache.stat.calls);
+    // Stop timers
+    {
+        EngineTOTAL.FrameEnd();
+        Sheduler.FrameEnd();
+        UpdateClient.FrameEnd();
+        Physics.FrameEnd();
+        ph_collision.FrameEnd();
+        ph_core.FrameEnd();
+        Animation.FrameEnd();
+        AI_Think.FrameEnd();
+        AI_Range.FrameEnd();
+        AI_Path.FrameEnd();
+        AI_Node.FrameEnd();
+        AI_Vis.FrameEnd();
+        AI_Vis_Query.FrameEnd();
+        AI_Vis_RayTests.FrameEnd();
+
+        RenderTOTAL.FrameEnd();
+        RenderCALC.FrameEnd();
+        RenderCALC_HOM.FrameEnd();
+        RenderDUMP.FrameEnd();
+        RenderDUMP_RT.FrameEnd();
+        RenderDUMP_SKIN.FrameEnd();
+        RenderDUMP_Wait.FrameEnd();
+        RenderDUMP_Wait_S.FrameEnd();
+        RenderDUMP_HUD.FrameEnd();
+        RenderDUMP_Glows.FrameEnd();
+        RenderDUMP_Lights.FrameEnd();
+        RenderDUMP_WM.FrameEnd();
+        RenderDUMP_DT_VIS.FrameEnd();
+        RenderDUMP_DT_Render.FrameEnd();
+        RenderDUMP_DT_Cache.FrameEnd();
+        RenderDUMP_Pcalc.FrameEnd();
+        RenderDUMP_Scalc.FrameEnd();
+        RenderDUMP_Srender.FrameEnd();
+
+        Sound.FrameEnd();
+        Input.FrameEnd();
+        clRAY.FrameEnd();
+        clBOX.FrameEnd();
+        clFRUSTUM.FrameEnd();
+
+        netClient1.FrameEnd();
+        netClient2.FrameEnd();
+        netServer.FrameEnd();
+
+        netClientCompressor.FrameEnd();
+        netServerCompressor.FrameEnd();
+
+        TEST0.FrameEnd();
+        TEST1.FrameEnd();
+        TEST2.FrameEnd();
+        TEST3.FrameEnd();
+
+        g_SpatialSpace->stat_insert.FrameEnd();
+        g_SpatialSpace->stat_remove.FrameEnd();
+        g_SpatialSpacePhysic->stat_insert.FrameEnd();
+        g_SpatialSpacePhysic->stat_remove.FrameEnd();
+    }
+
+    // calc FPS & TPS
+    if (Device.fTimeDelta > EPS_S)
+    {
+        float fps = 1.f / Device.fTimeDelta;
+        //if (Engine.External.tune_enabled) vtune.update (fps);
+        float fOne = 0.3f;
+        float fInv = 1.f - fOne;
+        fFPS = fInv*fFPS + fOne*fps;
+
+        if (RenderTOTAL.result > EPS_S)
+        {
+            u32 rendered_polies = Device.m_pRender->GetCacheStatPolys();
+            fTPS = fInv*fTPS + fOne*float(rendered_polies) / (RenderTOTAL.result*1000.f);
+            //fTPS = fInv*fTPS + fOne*float(RCache.stat.polys)/(RenderTOTAL.result*1000.f);
+            fRFPS = fInv*fRFPS + fOne*1000.f / RenderTOTAL.result;
+        }
+    }
+    {
+        float mem_count = float(Memory.stat_calls);
+        if (mem_count > fMem_calls) fMem_calls = mem_count;
+        else fMem_calls = .9f*fMem_calls + .1f*mem_count;
+        Memory.stat_calls = 0;
+    }
+
+    ////////////////////////////////////////////////
+    if (g_dedicated_server) return;
+    ////////////////////////////////////////////////
+    int frm = 2000;
+    div_t ddd = div(Device.dwFrame, frm);
+    if (ddd.rem < frm / 2.0f)
+    {
+        pFont->SetColor(0xFFFFFFFF);
+        pFont->OutSet(0, 0);
+        pFont->OutNext(*eval_line_1);
+        pFont->OutNext(*eval_line_2);
+        pFont->OutNext(*eval_line_3);
+        pFont->OnRender();
+    }
+
+    CGameFont& F = *pFont;
+    float  f_base_size = 0.01f;
+    F.SetHeightI(f_base_size);
+
+    if (vtune.enabled())
+    {
+        float sz = pFont->GetHeight();
+        pFont->SetHeightI(0.02f);
+        pFont->SetColor(0xFFFF0000);
+        pFont->OutSet(Device.dwWidth / 2.0f + (pFont->SizeOf_("--= tune =--") / 2.0f), Device.dwHeight / 2.0f);
+        pFont->OutNext("--= tune =--");
+        pFont->OnRender();
+        pFont->SetHeight(sz);
+    };
+
+    // Show them
+    if (psDeviceFlags.test(rsStatistic))
+    {
+        static float r_ps = 0;
+        static float b_ps = 0;
+        r_ps = .99f*r_ps + .01f*(clRAY.count / clRAY.result);
+        b_ps = .99f*b_ps + .01f*(clBOX.count / clBOX.result);
+
+        CSound_stats snd_stat;
+        ::Sound->statistic(&snd_stat, 0);
+        F.SetColor(0xFFFFFFFF);
+
+        F.OutSet(0, 0);
+        F.OutNext("FPS/RFPS:    %3.1f/%3.1f", fFPS, fRFPS);
+        F.OutNext("TPS:         %2.2f M", fTPS);
+        m_pRender->OutData1(F);
+        //F.OutNext ("VERT:        %d/%d", RCache.stat.verts,RCache.stat.calls?RCache.stat.verts/RCache.stat.calls:0);
+        //F.OutNext ("POLY:        %d/%d", RCache.stat.polys,RCache.stat.calls?RCache.stat.polys/RCache.stat.calls:0);
+        //F.OutNext ("DIP/DP:      %d", RCache.stat.calls);
 #ifdef DEBUG
-		F.OutSkip	();
+        F.OutSkip();
 #ifdef FS_DEBUG
-		F.OutNext	("mapped:      %d",			g_file_mapped_memory);
-		F.OutSkip	();
+        F.OutNext("mapped:      %d", g_file_mapped_memory);
+        F.OutSkip();
 #endif
-		m_pRender->OutData2(F);
-		//F.OutNext	("SH/T/M/C:    %d/%d/%d/%d",RCache.stat.states,RCache.stat.textures,RCache.stat.matrices,RCache.stat.constants);
-		//F.OutNext	("RT/PS/VS:    %d/%d/%d",	RCache.stat.target_rt,RCache.stat.ps,RCache.stat.vs);
-		//F.OutNext	("DCL/VB/IB:   %d/%d/%d",   RCache.stat.decl,RCache.stat.vb,RCache.stat.ib);
+        m_pRender->OutData2(F);
+        //F.OutNext ("SH/T/M/C:    %d/%d/%d/%d",RCache.stat.states,RCache.stat.textures,RCache.stat.matrices,RCache.stat.constants);
+        //F.OutNext ("RT/PS/VS:    %d/%d/%d", RCache.stat.target_rt,RCache.stat.ps,RCache.stat.vs);
+        //F.OutNext ("DCL/VB/IB:   %d/%d/%d", RCache.stat.decl,RCache.stat.vb,RCache.stat.ib);
 #endif
-		m_pRender->OutData3(F);
-		//F.OutNext	("xforms:      %d",			RCache.stat.xforms);
-		F.OutSkip	();
+        m_pRender->OutData3(F);
+        //F.OutNext ("xforms:      %d", RCache.stat.xforms);
+        F.OutSkip();
 
 #define PPP(a) (100.f*float(a)/float(EngineTOTAL.result))
-		F.OutNext	("*** ENGINE:  %2.2fms",EngineTOTAL.result);	
-		F.OutNext	("Memory:      %2.2fa",fMem_calls);
-		F.OutNext	("uClients:    %2.2fms, %2.1f%%, crow(%d)/active(%d)/total(%d)",UpdateClient.result,PPP(UpdateClient.result),UpdateClient_crows,UpdateClient_active,UpdateClient_total);
-		F.OutNext	("uSheduler:   %2.2fms, %2.1f%%",Sheduler.result,		PPP(Sheduler.result));
-		F.OutNext	("uSheduler_L: %2.2fms",fShedulerLoad);
-		F.OutNext	("uParticles:  Qstart[%d] Qactive[%d] Qdestroy[%d]",	Particles_starting,Particles_active,Particles_destroy);
-		F.OutNext	("spInsert:    o[%.2fms, %2.1f%%], p[%.2fms, %2.1f%%]",	g_SpatialSpace->stat_insert.result, PPP(g_SpatialSpace->stat_insert.result),	g_SpatialSpacePhysic->stat_insert.result, PPP(g_SpatialSpacePhysic->stat_insert.result));
-		F.OutNext	("spRemove:    o[%.2fms, %2.1f%%], p[%.2fms, %2.1f%%]",	g_SpatialSpace->stat_remove.result, PPP(g_SpatialSpace->stat_remove.result),	g_SpatialSpacePhysic->stat_remove.result, PPP(g_SpatialSpacePhysic->stat_remove.result));
-		F.OutNext	("Physics:     %2.2fms, %2.1f%%",Physics.result,		PPP(Physics.result));	
-		F.OutNext	("  collider:  %2.2fms", ph_collision.result);	
-		F.OutNext	("  solver:    %2.2fms, %d",ph_core.result,ph_core.count);	
-		F.OutNext	("aiThink:     %2.2fms, %d",AI_Think.result,AI_Think.count);	
-		F.OutNext	("  aiRange:   %2.2fms, %d",AI_Range.result,AI_Range.count);
-		F.OutNext	("  aiPath:    %2.2fms, %d",AI_Path.result,AI_Path.count);
-		F.OutNext	("  aiNode:    %2.2fms, %d",AI_Node.result,AI_Node.count);
-		F.OutNext	("aiVision:    %2.2fms, %d",AI_Vis.result,AI_Vis.count);
-		F.OutNext	("  Query:     %2.2fms",	AI_Vis_Query.result);
-		F.OutNext	("  RayCast:   %2.2fms",	AI_Vis_RayTests.result);
-		F.OutSkip	();
-								   
+        F.OutNext("*** ENGINE:  %2.2fms", EngineTOTAL.result);
+        F.OutNext("Memory:      %2.2fa", fMem_calls);
+        F.OutNext("uClients:    %2.2fms, %2.1f%%, crow(%d)/active(%d)/total(%d)", UpdateClient.result, PPP(UpdateClient.result), UpdateClient_crows, UpdateClient_active, UpdateClient_total);
+        F.OutNext("uSheduler:   %2.2fms, %2.1f%%", Sheduler.result, PPP(Sheduler.result));
+        F.OutNext("uSheduler_L: %2.2fms", fShedulerLoad);
+        F.OutNext("uParticles:  Qstart[%d] Qactive[%d] Qdestroy[%d]", Particles_starting, Particles_active, Particles_destroy);
+        F.OutNext("spInsert:    o[%.2fms, %2.1f%%], p[%.2fms, %2.1f%%]", g_SpatialSpace->stat_insert.result, PPP(g_SpatialSpace->stat_insert.result), g_SpatialSpacePhysic->stat_insert.result, PPP(g_SpatialSpacePhysic->stat_insert.result));
+        F.OutNext("spRemove:    o[%.2fms, %2.1f%%], p[%.2fms, %2.1f%%]", g_SpatialSpace->stat_remove.result, PPP(g_SpatialSpace->stat_remove.result), g_SpatialSpacePhysic->stat_remove.result, PPP(g_SpatialSpacePhysic->stat_remove.result));
+        F.OutNext("Physics:     %2.2fms, %2.1f%%", Physics.result, PPP(Physics.result));
+        F.OutNext("  collider:  %2.2fms", ph_collision.result);
+        F.OutNext("  solver:    %2.2fms, %d", ph_core.result, ph_core.count);
+        F.OutNext("aiThink:     %2.2fms, %d", AI_Think.result, AI_Think.count);
+        F.OutNext("  aiRange:   %2.2fms, %d", AI_Range.result, AI_Range.count);
+        F.OutNext("  aiPath:    %2.2fms, %d", AI_Path.result, AI_Path.count);
+        F.OutNext("  aiNode:    %2.2fms, %d", AI_Node.result, AI_Node.count);
+        F.OutNext("aiVision:    %2.2fms, %d", AI_Vis.result, AI_Vis.count);
+        F.OutNext("  Query:     %2.2fms", AI_Vis_Query.result);
+        F.OutNext("  RayCast:   %2.2fms", AI_Vis_RayTests.result);
+        F.OutSkip();
+
 #undef  PPP
 #define PPP(a) (100.f*float(a)/float(RenderTOTAL.result))
-		F.OutNext	("*** RENDER:  %2.2fms",RenderTOTAL.result);
-		F.OutNext	("R_CALC:      %2.2fms, %2.1f%%",RenderCALC.result,	PPP(RenderCALC.result));	
-		F.OutNext	("  HOM:       %2.2fms, %d",RenderCALC_HOM.result,	RenderCALC_HOM.count);
-		F.OutNext	("  Skeletons: %2.2fms, %d",Animation.result,		Animation.count);
-		F.OutNext	("R_DUMP:      %2.2fms, %2.1f%%",RenderDUMP.result,	PPP(RenderDUMP.result));	
-		F.OutNext	("  Wait-L:    %2.2fms",RenderDUMP_Wait.result);	
-		F.OutNext	("  Wait-S:    %2.2fms",RenderDUMP_Wait_S.result);	
-		F.OutNext	("  Skinning:  %2.2fms",RenderDUMP_SKIN.result);	
-		F.OutNext	("  DT_Vis/Cnt:%2.2fms/%d",RenderDUMP_DT_VIS.result,RenderDUMP_DT_Count);	
-		F.OutNext	("  DT_Render: %2.2fms",RenderDUMP_DT_Render.result);	
-		F.OutNext	("  DT_Cache:  %2.2fms",RenderDUMP_DT_Cache.result);	
-		F.OutNext	("  Wallmarks: %2.2fms, %d/%d - %d",RenderDUMP_WM.result,RenderDUMP_WMS_Count,RenderDUMP_WMD_Count,RenderDUMP_WMT_Count);
-		F.OutNext	("  Glows:     %2.2fms",RenderDUMP_Glows.result);	
-		F.OutNext	("  Lights:    %2.2fms, %d",RenderDUMP_Lights.result,RenderDUMP_Lights.count);
-		F.OutNext	("  RT:        %2.2fms, %d",RenderDUMP_RT.result,RenderDUMP_RT.count);
-		F.OutNext	("  HUD:       %2.2fms",RenderDUMP_HUD.result);	
-		F.OutNext	("  P_calc:    %2.2fms",RenderDUMP_Pcalc.result);
-		F.OutNext	("  S_calc:    %2.2fms",RenderDUMP_Scalc.result);
-		F.OutNext	("  S_render:  %2.2fms, %d",RenderDUMP_Srender.result,RenderDUMP_Srender.count);
-		F.OutSkip	();
-		F.OutNext	("*** SOUND:   %2.2fms",Sound.result);
-		F.OutNext	("  TGT/SIM/E: %d/%d/%d",  snd_stat._rendered, snd_stat._simulated, snd_stat._events);
-		F.OutNext	("  HIT/MISS:  %d/%d",  snd_stat._cache_hits, snd_stat._cache_misses);
-		F.OutSkip	();
-		F.OutNext	("Input:       %2.2fms",Input.result);
-		F.OutNext	("clRAY:       %2.2fms, %d, %2.0fK",clRAY.result,		clRAY.count,r_ps);
-		F.OutNext	("clBOX:       %2.2fms, %d, %2.0fK",clBOX.result,		clBOX.count,b_ps);
-		F.OutNext	("clFRUSTUM:   %2.2fms, %d",		clFRUSTUM.result,	clFRUSTUM.count	);
-		F.OutSkip	();
-		F.OutNext	("netClientRecv:   %2.2fms, %d",	netClient1.result,netClient1.count);
-		F.OutNext	("netClientSend:   %2.2fms, %d",	netClient2.result,netClient2.count);
-		F.OutNext	("netServer:   %2.2fms, %d",		netServer.result,netServer.count);
-		F.OutNext	("netClientCompressor:   %2.2fms",	netClientCompressor.result);
-		F.OutNext	("netServerCompressor:   %2.2fms",	netServerCompressor.result);
-		
-		F.OutSkip	();
-
-		F.OutSkip	();
-		F.OutNext	("TEST 0:      %2.2fms, %d",TEST0.result,TEST0.count);
-		F.OutNext	("TEST 1:      %2.2fms, %d",TEST1.result,TEST1.count);
-		F.OutNext	("TEST 2:      %2.2fms, %d",TEST2.result,TEST2.count);
-		F.OutNext	("TEST 3:      %2.2fms, %d",TEST3.result,TEST3.count);
+        F.OutNext("*** RENDER:  %2.2fms", RenderTOTAL.result);
+        F.OutNext("R_CALC:      %2.2fms, %2.1f%%", RenderCALC.result, PPP(RenderCALC.result));
+        F.OutNext("  HOM:       %2.2fms, %d", RenderCALC_HOM.result, RenderCALC_HOM.count);
+        F.OutNext("  Skeletons: %2.2fms, %d", Animation.result, Animation.count);
+        F.OutNext("R_DUMP:      %2.2fms, %2.1f%%", RenderDUMP.result, PPP(RenderDUMP.result));
+        F.OutNext("  Wait-L:    %2.2fms", RenderDUMP_Wait.result);
+        F.OutNext("  Wait-S:    %2.2fms", RenderDUMP_Wait_S.result);
+        F.OutNext("  Skinning:  %2.2fms", RenderDUMP_SKIN.result);
+        F.OutNext("  DT_Vis/Cnt:%2.2fms/%d", RenderDUMP_DT_VIS.result, RenderDUMP_DT_Count);
+        F.OutNext("  DT_Render: %2.2fms", RenderDUMP_DT_Render.result);
+        F.OutNext("  DT_Cache:  %2.2fms", RenderDUMP_DT_Cache.result);
+        F.OutNext("  Wallmarks: %2.2fms, %d/%d - %d", RenderDUMP_WM.result, RenderDUMP_WMS_Count, RenderDUMP_WMD_Count, RenderDUMP_WMT_Count);
+        F.OutNext("  Glows:     %2.2fms", RenderDUMP_Glows.result);
+        F.OutNext("  Lights:    %2.2fms, %d", RenderDUMP_Lights.result, RenderDUMP_Lights.count);
+        F.OutNext("  RT:        %2.2fms, %d", RenderDUMP_RT.result, RenderDUMP_RT.count);
+        F.OutNext("  HUD:       %2.2fms", RenderDUMP_HUD.result);
+        F.OutNext("  P_calc:    %2.2fms", RenderDUMP_Pcalc.result);
+        F.OutNext("  S_calc:    %2.2fms", RenderDUMP_Scalc.result);
+        F.OutNext("  S_render:  %2.2fms, %d", RenderDUMP_Srender.result, RenderDUMP_Srender.count);
+        F.OutSkip();
+        F.OutNext("*** SOUND:   %2.2fms", Sound.result);
+        F.OutNext("  TGT/SIM/E: %d/%d/%d", snd_stat._rendered, snd_stat._simulated, snd_stat._events);
+        F.OutNext("  HIT/MISS:  %d/%d", snd_stat._cache_hits, snd_stat._cache_misses);
+        F.OutSkip();
+        F.OutNext("Input:       %2.2fms", Input.result);
+        F.OutNext("clRAY:       %2.2fms, %d, %2.0fK", clRAY.result, clRAY.count, r_ps);
+        F.OutNext("clBOX:       %2.2fms, %d, %2.0fK", clBOX.result, clBOX.count, b_ps);
+        F.OutNext("clFRUSTUM:   %2.2fms, %d", clFRUSTUM.result, clFRUSTUM.count);
+        F.OutSkip();
+        F.OutNext("netClientRecv:   %2.2fms, %d", netClient1.result, netClient1.count);
+        F.OutNext("netClientSend:   %2.2fms, %d", netClient2.result, netClient2.count);
+        F.OutNext("netServer:   %2.2fms, %d", netServer.result, netServer.count);
+        F.OutNext("netClientCompressor:   %2.2fms", netClientCompressor.result);
+        F.OutNext("netServerCompressor:   %2.2fms", netServerCompressor.result);
+
+        F.OutSkip();
+
+        F.OutSkip();
+        F.OutNext("TEST 0:      %2.2fms, %d", TEST0.result, TEST0.count);
+        F.OutNext("TEST 1:      %2.2fms, %d", TEST1.result, TEST1.count);
+        F.OutNext("TEST 2:      %2.2fms, %d", TEST2.result, TEST2.count);
+        F.OutNext("TEST 3:      %2.2fms, %d", TEST3.result, TEST3.count);
 #ifdef DEBUG_MEMORY_MANAGER
-		F.OutSkip	();
-		F.OutNext	("str: cmp[%3d], dock[%3d], qpc[%3d]",Memory.stat_strcmp,Memory.stat_strdock,CPU::qpc_counter);
-		Memory.stat_strcmp	=	0		;
-		Memory.stat_strdock	=	0		;
-		CPU::qpc_counter	=	0		;
+        F.OutSkip();
+        F.OutNext("str: cmp[%3d], dock[%3d], qpc[%3d]", Memory.stat_strcmp, Memory.stat_strdock, CPU::qpc_counter);
+        Memory.stat_strcmp = 0;
+        Memory.stat_strdock = 0;
+        CPU::qpc_counter = 0;
 #else // DEBUG_MEMORY_MANAGER
-		F.OutSkip	();
-		F.OutNext	("qpc[%3d]",CPU::qpc_counter);
-		CPU::qpc_counter	=	0		;
+        F.OutSkip();
+        F.OutNext("qpc[%3d]", CPU::qpc_counter);
+        CPU::qpc_counter = 0;
 #endif // DEBUG_MEMORY_MANAGER
-//		F.OutSet	(640,0);
-		F.OutSkip	();
-		m_pRender->OutData4(F);
-		/*
-		F.OutNext	("static:        %3.1f/%d",	RCache.stat.r.s_static.verts/1024.f,		RCache.stat.r.s_static.dips );
-		F.OutNext	("flora:         %3.1f/%d",	RCache.stat.r.s_flora.verts/1024.f,			RCache.stat.r.s_flora.dips );
-		F.OutNext	("  flora_lods:  %3.1f/%d",	RCache.stat.r.s_flora_lods.verts/1024.f,	RCache.stat.r.s_flora_lods.dips );
-		F.OutNext	("dynamic:       %3.1f/%d",	RCache.stat.r.s_dynamic.verts/1024.f,		RCache.stat.r.s_dynamic.dips );
-		F.OutNext	("  dynamic_sw:  %3.1f/%d",	RCache.stat.r.s_dynamic_sw.verts/1024.f,	RCache.stat.r.s_dynamic_sw.dips );
-		F.OutNext	("  dynamic_inst:%3.1f/%d",	RCache.stat.r.s_dynamic_inst.verts/1024.f,	RCache.stat.r.s_dynamic_inst.dips );
-		F.OutNext	("  dynamic_1B:  %3.1f/%d",	RCache.stat.r.s_dynamic_1B.verts/1024.f,	RCache.stat.r.s_dynamic_1B.dips );
-		F.OutNext	("  dynamic_2B:  %3.1f/%d",	RCache.stat.r.s_dynamic_2B.verts/1024.f,	RCache.stat.r.s_dynamic_2B.dips );
-		F.OutNext	("details:       %3.1f/%d",	RCache.stat.r.s_details.verts/1024.f,		RCache.stat.r.s_details.dips );
-*/
-		//////////////////////////////////////////////////////////////////////////
-		// Renderer specific
-		F.SetHeightI						(f_base_size);
-		F.OutSet						(200,0);
-		Render->Statistics				(&F);
-
-		//////////////////////////////////////////////////////////////////////////
-		// Game specific
-		F.SetHeightI						(f_base_size);
-		F.OutSet						(400,0);
-		g_pGamePersistent->Statistics	(&F);
-
-		//////////////////////////////////////////////////////////////////////////
-		// process PURE STATS
-		F.SetHeightI						(f_base_size);
-		seqStats.Process				(rp_Stats);
-		pFont->OnRender					();
-	};
-
-	if( /*psDeviceFlags.test(rsStatistic) ||*/ psDeviceFlags.test(rsCameraPos) ){
-		_draw_cam_pos					(pFont);
-		pFont->OnRender					();
-	};
+        //  F.OutSet (640,0);
+        F.OutSkip();
+        m_pRender->OutData4(F);
+        /*
+        F.OutNext ("static:        %3.1f/%d", RCache.stat.r.s_static.verts/1024.f, RCache.stat.r.s_static.dips );
+        F.OutNext ("flora:         %3.1f/%d", RCache.stat.r.s_flora.verts/1024.f, RCache.stat.r.s_flora.dips );
+        F.OutNext ("  flora_lods:  %3.1f/%d", RCache.stat.r.s_flora_lods.verts/1024.f, RCache.stat.r.s_flora_lods.dips );
+        F.OutNext ("dynamic:       %3.1f/%d", RCache.stat.r.s_dynamic.verts/1024.f, RCache.stat.r.s_dynamic.dips );
+        F.OutNext ("  dynamic_sw:  %3.1f/%d", RCache.stat.r.s_dynamic_sw.verts/1024.f, RCache.stat.r.s_dynamic_sw.dips );
+        F.OutNext ("  dynamic_inst:%3.1f/%d", RCache.stat.r.s_dynamic_inst.verts/1024.f, RCache.stat.r.s_dynamic_inst.dips );
+        F.OutNext ("  dynamic_1B:  %3.1f/%d", RCache.stat.r.s_dynamic_1B.verts/1024.f, RCache.stat.r.s_dynamic_1B.dips );
+        F.OutNext ("  dynamic_2B:  %3.1f/%d", RCache.stat.r.s_dynamic_2B.verts/1024.f, RCache.stat.r.s_dynamic_2B.dips );
+        F.OutNext ("details:       %3.1f/%d", RCache.stat.r.s_details.verts/1024.f, RCache.stat.r.s_details.dips );
+        */
+        //////////////////////////////////////////////////////////////////////////
+        // Renderer specific
+        F.SetHeightI(f_base_size);
+        F.OutSet(200, 0);
+        Render->Statistics(&F);
+
+        //////////////////////////////////////////////////////////////////////////
+        // Game specific
+        F.SetHeightI(f_base_size);
+        F.OutSet(400, 0);
+        g_pGamePersistent->Statistics(&F);
+
+        //////////////////////////////////////////////////////////////////////////
+        // process PURE STATS
+        F.SetHeightI(f_base_size);
+        seqStats.Process(rp_Stats);
+        pFont->OnRender();
+    };
+
+    if ( /*psDeviceFlags.test(rsStatistic) ||*/ psDeviceFlags.test(rsCameraPos))
+    {
+        _draw_cam_pos(pFont);
+        pFont->OnRender();
+    };
 #ifdef DEBUG
-	//////////////////////////////////////////////////////////////////////////
-	// PERF ALERT
-	if (!g_bDisableRedText)
-	{
-		CGameFont&	F = *((CGameFont*)pFont);
-		F.SetColor						(color_rgba(255,16,16,255));
-		F.OutSet						(300,300);
-		F.SetHeightI						(f_base_size*2);
-		if (fFPS<30)					F.OutNext	("FPS       < 30:   %3.1f",	fFPS);
-		//if (RCache.stat.verts>500000)	F.OutNext	("Verts     > 500k: %d",	RCache.stat.verts);
-		m_pRender->GuardVerts(F);
-		////if (RCache.stat.polys>500000)	F.OutNext	("Polys     > 500k: %d",	RCache.stat.polys);
-		if (psDeviceFlags.test(rsStatistic))
-		{
-			m_pRender->GuardDrawCalls(F);
-			//if (RCache.stat.calls>1000)		F.OutNext	("DIP/DP    > 1k:   %d",	RCache.stat.calls);
-			////if (RCache.stat.textures>1000)F.OutNext	("T_change  > 500:  %d",	RCache.stat.textures);
-			if (RenderDUMP_DT_Count>1000)	F.OutNext	("DT_count  > 1000: %u",	RenderDUMP_DT_Count);
-			F.OutSkip						();
-			//if (fMem_calls>1500)			F.OutNext	("MMGR calls > 1500:%3.1f",	fMem_calls);
-			if (Sheduler.result>3.f)		F.OutNext	("Update     > 3ms:	%3.1f",	Sheduler.result);
-			if (UpdateClient.result>3.f)	F.OutNext	("UpdateCL   > 3ms: %3.1f",	UpdateClient.result);
-			if (Physics.result>5.f)			F.OutNext	("Physics    > 5ms: %3.1f",	Physics.result);	
-		}
-	}
-
-	//////////////////////////////////////////////////////////////////////////
-	// Show errors
-	if (!g_bDisableRedText && errors.size())
-	{
-		CGameFont&	F = *((CGameFont*)pFont);
-		F.SetColor	(color_rgba(255,16,16,191));
-		F.OutSet	(200,0);
-		F.SetHeightI	(f_base_size);
+    //////////////////////////////////////////////////////////////////////////
+    // PERF ALERT
+    if (!g_bDisableRedText)
+    {
+        CGameFont& F = *((CGameFont*)pFont);
+        F.SetColor(color_rgba(255, 16, 16, 255));
+        F.OutSet(300, 300);
+        F.SetHeightI(f_base_size * 2);
+        if (fFPS < 30)     F.OutNext("FPS       < 30:   %3.1f", fFPS);
+        //if (RCache.stat.verts>500000) F.OutNext ("Verts     > 500k: %d", RCache.stat.verts);
+        m_pRender->GuardVerts(F);
+        ////if (RCache.stat.polys>500000) F.OutNext ("Polys     > 500k: %d", RCache.stat.polys);
+        if (psDeviceFlags.test(rsStatistic))
+        {
+            m_pRender->GuardDrawCalls(F);
+            //if (RCache.stat.calls>1000)  F.OutNext ("DIP/DP    > 1k:   %d", RCache.stat.calls);
+            ////if (RCache.stat.textures>1000)F.OutNext ("T_change  > 500:  %d", RCache.stat.textures);
+            if (RenderDUMP_DT_Count > 1000) F.OutNext("DT_count  > 1000: %u", RenderDUMP_DT_Count);
+            F.OutSkip();
+            //if (fMem_calls>1500)   F.OutNext ("MMGR calls > 1500:%3.1f", fMem_calls);
+            if (Sheduler.result > 3.f)  F.OutNext("Update     > 3ms: %3.1f", Sheduler.result);
+            if (UpdateClient.result > 3.f) F.OutNext("UpdateCL   > 3ms: %3.1f", UpdateClient.result);
+            if (Physics.result > 5.f)   F.OutNext("Physics    > 5ms: %3.1f", Physics.result);
+        }
+    }
+
+    //////////////////////////////////////////////////////////////////////////
+    // Show errors
+    if (!g_bDisableRedText && errors.size())
+    {
+        CGameFont& F = *((CGameFont*)pFont);
+        F.SetColor(color_rgba(255, 16, 16, 191));
+        F.OutSet(200, 0);
+        F.SetHeightI(f_base_size);
 #if 0
-		for (u32 it=0; itstat_insert.FrameStart		();
-		g_SpatialSpace->stat_remove.FrameStart		();
-
-		g_SpatialSpacePhysic->stat_insert.FrameStart();
-		g_SpatialSpacePhysic->stat_remove.FrameStart();
-	}
-	dwSND_Played = dwSND_Allocated = 0;
-	Particles_starting = Particles_active = Particles_destroy = 0;
+    {
+        EngineTOTAL.FrameStart();
+        Sheduler.FrameStart();
+        UpdateClient.FrameStart();
+        Physics.FrameStart();
+        ph_collision.FrameStart();
+        ph_core.FrameStart();
+        Animation.FrameStart();
+        AI_Think.FrameStart();
+        AI_Range.FrameStart();
+        AI_Path.FrameStart();
+        AI_Node.FrameStart();
+        AI_Vis.FrameStart();
+        AI_Vis_Query.FrameStart();
+        AI_Vis_RayTests.FrameStart();
+
+        RenderTOTAL.FrameStart();
+        RenderCALC.FrameStart();
+        RenderCALC_HOM.FrameStart();
+        RenderDUMP.FrameStart();
+        RenderDUMP_RT.FrameStart();
+        RenderDUMP_SKIN.FrameStart();
+        RenderDUMP_Wait.FrameStart();
+        RenderDUMP_Wait_S.FrameStart();
+        RenderDUMP_HUD.FrameStart();
+        RenderDUMP_Glows.FrameStart();
+        RenderDUMP_Lights.FrameStart();
+        RenderDUMP_WM.FrameStart();
+        RenderDUMP_DT_VIS.FrameStart();
+        RenderDUMP_DT_Render.FrameStart();
+        RenderDUMP_DT_Cache.FrameStart();
+        RenderDUMP_Pcalc.FrameStart();
+        RenderDUMP_Scalc.FrameStart();
+        RenderDUMP_Srender.FrameStart();
+
+        Sound.FrameStart();
+        Input.FrameStart();
+        clRAY.FrameStart();
+        clBOX.FrameStart();
+        clFRUSTUM.FrameStart();
+
+        netClient1.FrameStart();
+        netClient2.FrameStart();
+        netServer.FrameStart();
+        netClientCompressor.FrameStart();
+        netServerCompressor.FrameStart();
+
+        TEST0.FrameStart();
+        TEST1.FrameStart();
+        TEST2.FrameStart();
+        TEST3.FrameStart();
+
+        g_SpatialSpace->stat_insert.FrameStart();
+        g_SpatialSpace->stat_remove.FrameStart();
+
+        g_SpatialSpacePhysic->stat_insert.FrameStart();
+        g_SpatialSpacePhysic->stat_remove.FrameStart();
+    }
+    dwSND_Played = dwSND_Allocated = 0;
+    Particles_starting = Particles_active = Particles_destroy = 0;
 }
 
-void	_LogCallback				(LPCSTR string)
+void _LogCallback(LPCSTR string)
 {
-	if (string && '!'==string[0] && ' '==string[1])
-		Device.Statistic->errors.push_back	(shared_str(string));
+    if (string && '!' == string[0] && ' ' == string[1])
+        Device.Statistic->errors.push_back(shared_str(string));
 }
 
-void CStats::OnDeviceCreate			()
+void CStats::OnDeviceCreate()
 {
-	g_bDisableRedText				= strstr(Core.Params,"-xclsx")?TRUE:FALSE;
+    g_bDisableRedText = strstr(Core.Params, "-xclsx") ? TRUE : FALSE;
 
-//	if (!strstr(Core.Params, "-dedicated"))
+    // if (!strstr(Core.Params, "-dedicated"))
 #ifndef DEDICATED_SERVER
-	pFont	= xr_new		("stat_font", CGameFont::fsDeviceIndependent);
+    pFont = xr_new("stat_font", CGameFont::fsDeviceIndependent);
 #endif
-	
-	if(!pSettings->section_exist("evaluation")
-		||!pSettings->line_exist("evaluation","line1")
-		||!pSettings->line_exist("evaluation","line2")
-		||!pSettings->line_exist("evaluation","line3") )
-		FATAL	("");
-
-	eval_line_1 = pSettings->r_string_wb("evaluation","line1");
-	eval_line_2 = pSettings->r_string_wb("evaluation","line2");
-	eval_line_3 = pSettings->r_string_wb("evaluation","line3");
-
-	// 
+
+    if (!pSettings->section_exist("evaluation")
+            || !pSettings->line_exist("evaluation", "line1")
+            || !pSettings->line_exist("evaluation", "line2")
+            || !pSettings->line_exist("evaluation", "line3"))
+        FATAL("");
+
+    eval_line_1 = pSettings->r_string_wb("evaluation", "line1");
+    eval_line_2 = pSettings->r_string_wb("evaluation", "line2");
+    eval_line_3 = pSettings->r_string_wb("evaluation", "line3");
+
+    //
 #ifdef DEBUG
-	if (!g_bDisableRedText)			SetLogCB	(_LogCallback);
+    if (!g_bDisableRedText)   SetLogCB(_LogCallback);
 #endif
 }
 
-void CStats::OnDeviceDestroy		()
+void CStats::OnDeviceDestroy()
 {
-	SetLogCB(0);
-	xr_delete	(pFont);
+    SetLogCB(0);
+    xr_delete(pFont);
 }
 
-void CStats::OnRender				()
+void CStats::OnRender()
 {
 #ifdef DEBUG
-	if (g_stats_flags.is(st_sound)){
-		CSound_stats_ext				snd_stat_ext;
-		::Sound->statistic				(0,&snd_stat_ext);
-		CSound_stats_ext::item_vec_it	_I = snd_stat_ext.items.begin();
-		CSound_stats_ext::item_vec_it	_E = snd_stat_ext.items.end();
-		for (;_I!=_E;_I++){
-			const CSound_stats_ext::SItem& item = *_I;
-			if (item._3D)
-			{
-				m_pRender->SetDrawParams(&*Device.m_pRender);
-				//RCache.set_xform_world(Fidentity);
-				//RCache.set_Shader		(Device.m_SelectionShader);
-				//RCache.set_c			("tfactor",1,1,1,1);
-				DU->DrawCross			(item.params.position, 0.5f, 0xFF0000FF, true );
-				if (g_stats_flags.is(st_sound_min_dist))
-					DU->DrawSphere		(Fidentity, item.params.position, item.params.min_distance, 0x400000FF,	0xFF0000FF, true, true);
-				if (g_stats_flags.is(st_sound_max_dist))
-					DU->DrawSphere		(Fidentity, item.params.position, item.params.max_distance, 0x4000FF00,	0xFF008000, true, true);
-				
-				xr_string out_txt		= (out_txt.size() && g_stats_flags.is(st_sound_info_name)) ? item.name.c_str():"";
-
-				if (item.game_object)
-				{
-					if (g_stats_flags.is(st_sound_ai_dist))
-						DU->DrawSphere	(Fidentity, item.params.position, item.params.max_ai_distance, 0x80FF0000,0xFF800000,true,true);
-					if (g_stats_flags.is(st_sound_info_object)){
-						out_txt			+= "  (";
-						out_txt			+= item.game_object->cNameSect().c_str();
-						out_txt			+= ")";
-					}
-				}
-				if (g_stats_flags.is_any(st_sound_info_name|st_sound_info_object) && item.name.size())
-					DU->OutText			(item.params.position, out_txt.c_str(),0xFFFFFFFF,0xFF000000);
-			}
-		}
-	}
+    if (g_stats_flags.is(st_sound))
+    {
+        CSound_stats_ext    snd_stat_ext;
+        ::Sound->statistic(0, &snd_stat_ext);
+        CSound_stats_ext::item_vec_it _I = snd_stat_ext.items.begin();
+        CSound_stats_ext::item_vec_it _E = snd_stat_ext.items.end();
+        for (; _I != _E; _I++)
+        {
+            const CSound_stats_ext::SItem& item = *_I;
+            if (item._3D)
+            {
+                m_pRender->SetDrawParams(&*Device.m_pRender);
+                //RCache.set_xform_world(Fidentity);
+                //RCache.set_Shader (Device.m_SelectionShader);
+                //RCache.set_c ("tfactor",1,1,1,1);
+                DU->DrawCross(item.params.position, 0.5f, 0xFF0000FF, true);
+                if (g_stats_flags.is(st_sound_min_dist))
+                    DU->DrawSphere(Fidentity, item.params.position, item.params.min_distance, 0x400000FF, 0xFF0000FF, true, true);
+                if (g_stats_flags.is(st_sound_max_dist))
+                    DU->DrawSphere(Fidentity, item.params.position, item.params.max_distance, 0x4000FF00, 0xFF008000, true, true);
+
+                xr_string out_txt = (out_txt.size() && g_stats_flags.is(st_sound_info_name)) ? item.name.c_str() : "";
+
+                if (item.game_object)
+                {
+                    if (g_stats_flags.is(st_sound_ai_dist))
+                        DU->DrawSphere(Fidentity, item.params.position, item.params.max_ai_distance, 0x80FF0000, 0xFF800000, true, true);
+                    if (g_stats_flags.is(st_sound_info_object))
+                    {
+                        out_txt += " (";
+                        out_txt += item.game_object->cNameSect().c_str();
+                        out_txt += ")";
+                    }
+                }
+                if (g_stats_flags.is_any(st_sound_info_name | st_sound_info_object) && item.name.size())
+                    DU->OutText(item.params.position, out_txt.c_str(), 0xFFFFFFFF, 0xFF000000);
+            }
+        }
+    }
 #endif
 }
diff --git a/src/xrEngine/Stats.h b/src/xrEngine/Stats.h
index c1a18c2e413..4f7726f541a 100644
--- a/src/xrEngine/Stats.h
+++ b/src/xrEngine/Stats.h
@@ -16,117 +16,118 @@ DECLARE_MESSAGE(Stats);
 class ENGINE_API CStatsPhysics
 {
 public:
-	CStatTimer	ph_collision;		// collision
-	CStatTimer	ph_core;			// integrate
-	CStatTimer	Physics;			// movement+collision
+    CStatTimer ph_collision; // collision
+    CStatTimer ph_core; // integrate
+    CStatTimer Physics; // movement+collision
 };
 
-class ENGINE_API CStats: 
-	public pureRender,
-	public CStatsPhysics
+class ENGINE_API CStats :
+    public pureRender,
+    public CStatsPhysics
 {
 public:
-	CGameFont*	pFont;
-
-	float		fFPS,fRFPS,fTPS		;			// FPS, RenderFPS, TPS
-	float		fMem_calls			;
-	u32			dwMem_calls			;
-	u32			dwSND_Played,dwSND_Allocated;	// Play/Alloc
-	float		fShedulerLoad		;
-
-	CStatTimer	EngineTOTAL;			// 
-	CStatTimer	Sheduler;				// 
-	CStatTimer	UpdateClient;			// 
-	u32			UpdateClient_updated;	//
-	u32			UpdateClient_crows;		//
-	u32			UpdateClient_active;	//
-	u32			UpdateClient_total;		//
-	u32			Particles_starting;	// starting
-	u32			Particles_active;	// active
-	u32			Particles_destroy;	// destroying
-//	CStatTimer	Physics;			// movement+collision
-//	CStatTimer	ph_collision;		// collision
-//	CStatTimer	ph_core;			// collision
-	CStatTimer	AI_Think;			// thinking
-	CStatTimer	AI_Range;			// query: range
-	CStatTimer	AI_Path;			// query: path
-	CStatTimer	AI_Node;			// query: node
-	CStatTimer	AI_Vis;				// visibility detection - total
-	CStatTimer	AI_Vis_Query;		// visibility detection - portal traversal and frustum culling
-	CStatTimer	AI_Vis_RayTests;	// visibility detection - ray casting
-
-	CStatTimer	RenderTOTAL;		// 
-	CStatTimer	RenderTOTAL_Real;	
-	CStatTimer	RenderCALC;			// portal traversal, frustum culling, entities "renderable_Render"
-	CStatTimer	RenderCALC_HOM;		// HOM rendering
-	CStatTimer	Animation;			// skeleton calculation
-	CStatTimer	RenderDUMP;			// actual primitive rendering
-	CStatTimer	RenderDUMP_Wait;	// ...waiting something back (queries results, etc.)
-	CStatTimer	RenderDUMP_Wait_S;	// ...frame-limit sync
-	CStatTimer	RenderDUMP_RT;		// ...render-targets
-	CStatTimer	RenderDUMP_SKIN;	// ...skinning
-	CStatTimer	RenderDUMP_HUD;		// ...hud rendering
-	CStatTimer	RenderDUMP_Glows;	// ...glows vis-testing,sorting,render
-	CStatTimer	RenderDUMP_Lights;	// ...d-lights building/rendering
-	CStatTimer	RenderDUMP_WM;		// ...wallmark sorting, rendering
-	u32			RenderDUMP_WMS_Count;// ...number of static wallmark
-	u32			RenderDUMP_WMD_Count;// ...number of dynamic wallmark
-	u32			RenderDUMP_WMT_Count;// ...number of wallmark tri
-	CStatTimer	RenderDUMP_DT_VIS;	// ...details visibility detection
-	CStatTimer	RenderDUMP_DT_Render;// ...details rendering
-	CStatTimer	RenderDUMP_DT_Cache;// ...details slot cache access
-	u32			RenderDUMP_DT_Count;// ...number of DT-elements
-	CStatTimer	RenderDUMP_Pcalc;	// ...projectors	building
-	CStatTimer	RenderDUMP_Scalc;	// ...shadows		building
-	CStatTimer	RenderDUMP_Srender;	// ...shadows		render
-	
-	CStatTimer	Sound;				// total time taken by sound subsystem (accurate only in single-threaded mode)
-	CStatTimer	Input;				// total time taken by input subsystem (accurate only in single-threaded mode)
-	CStatTimer	clRAY;				// total: ray-testing
-	CStatTimer	clBOX;				// total: box query
-	CStatTimer	clFRUSTUM;			// total: frustum query
-	
-	CStatTimer	netClient1;
-	CStatTimer	netClient2;
-	CStatTimer	netServer;
-	CStatTimer	netClientCompressor;
-	CStatTimer	netServerCompressor;
-	
-
-	
-	CStatTimer	TEST0;				// debug counter
-	CStatTimer	TEST1;				// debug counter
-	CStatTimer	TEST2;				// debug counter
-	CStatTimer	TEST3;				// debug counter
-
-	shared_str	eval_line_1;
-	shared_str	eval_line_2;
-	shared_str	eval_line_3;
-
-	void			Show			(void);
-	virtual void 	OnRender		();
-	void			OnDeviceCreate	(void);
-	void			OnDeviceDestroy	(void);
+    CGameFont* pFont;
+
+    float fFPS, fRFPS, fTPS; // FPS, RenderFPS, TPS
+    float fMem_calls;
+    u32 dwMem_calls;
+    u32 dwSND_Played, dwSND_Allocated; // Play/Alloc
+    float fShedulerLoad;
+
+    CStatTimer EngineTOTAL; //
+    CStatTimer Sheduler; //
+    CStatTimer UpdateClient; //
+    u32 UpdateClient_updated; //
+    u32 UpdateClient_crows; //
+    u32 UpdateClient_active; //
+    u32 UpdateClient_total; //
+    u32 Particles_starting; // starting
+    u32 Particles_active; // active
+    u32 Particles_destroy; // destroying
+    // CStatTimer Physics; // movement+collision
+    // CStatTimer ph_collision; // collision
+    // CStatTimer ph_core; // collision
+    CStatTimer AI_Think; // thinking
+    CStatTimer AI_Range; // query: range
+    CStatTimer AI_Path; // query: path
+    CStatTimer AI_Node; // query: node
+    CStatTimer AI_Vis; // visibility detection - total
+    CStatTimer AI_Vis_Query; // visibility detection - portal traversal and frustum culling
+    CStatTimer AI_Vis_RayTests; // visibility detection - ray casting
+
+    CStatTimer RenderTOTAL; //
+    CStatTimer RenderTOTAL_Real;
+    CStatTimer RenderCALC; // portal traversal, frustum culling, entities "renderable_Render"
+    CStatTimer RenderCALC_HOM; // HOM rendering
+    CStatTimer Animation; // skeleton calculation
+    CStatTimer RenderDUMP; // actual primitive rendering
+    CStatTimer RenderDUMP_Wait; // ...waiting something back (queries results, etc.)
+    CStatTimer RenderDUMP_Wait_S; // ...frame-limit sync
+    CStatTimer RenderDUMP_RT; // ...render-targets
+    CStatTimer RenderDUMP_SKIN; // ...skinning
+    CStatTimer RenderDUMP_HUD; // ...hud rendering
+    CStatTimer RenderDUMP_Glows; // ...glows vis-testing,sorting,render
+    CStatTimer RenderDUMP_Lights; // ...d-lights building/rendering
+    CStatTimer RenderDUMP_WM; // ...wallmark sorting, rendering
+    u32 RenderDUMP_WMS_Count;// ...number of static wallmark
+    u32 RenderDUMP_WMD_Count;// ...number of dynamic wallmark
+    u32 RenderDUMP_WMT_Count;// ...number of wallmark tri
+    CStatTimer RenderDUMP_DT_VIS; // ...details visibility detection
+    CStatTimer RenderDUMP_DT_Render;// ...details rendering
+    CStatTimer RenderDUMP_DT_Cache;// ...details slot cache access
+    u32 RenderDUMP_DT_Count;// ...number of DT-elements
+    CStatTimer RenderDUMP_Pcalc; // ...projectors building
+    CStatTimer RenderDUMP_Scalc; // ...shadows building
+    CStatTimer RenderDUMP_Srender; // ...shadows render
+
+    CStatTimer Sound; // total time taken by sound subsystem (accurate only in single-threaded mode)
+    CStatTimer Input; // total time taken by input subsystem (accurate only in single-threaded mode)
+    CStatTimer clRAY; // total: ray-testing
+    CStatTimer clBOX; // total: box query
+    CStatTimer clFRUSTUM; // total: frustum query
+
+    CStatTimer netClient1;
+    CStatTimer netClient2;
+    CStatTimer netServer;
+    CStatTimer netClientCompressor;
+    CStatTimer netServerCompressor;
+
+
+
+    CStatTimer TEST0; // debug counter
+    CStatTimer TEST1; // debug counter
+    CStatTimer TEST2; // debug counter
+    CStatTimer TEST3; // debug counter
+
+    shared_str eval_line_1;
+    shared_str eval_line_2;
+    shared_str eval_line_3;
+
+    void Show(void);
+    virtual void OnRender();
+    void OnDeviceCreate(void);
+    void OnDeviceDestroy(void);
 public:
-	xr_vector			errors;
-	CRegistrator			seqStats;
+    xr_vector  errors;
+    CRegistrator  seqStats;
 public:
-					CStats			();
-					~CStats			();
+    CStats();
+    ~CStats();
 
-	IC CGameFont*	Font			(){return pFont;}
+    IC CGameFont* Font() { return pFont; }
 
 private:
-	FactoryPtr	m_pRender;
+    FactoryPtr m_pRender;
 };
 
-enum{
-	st_sound			= (1<<0),
-	st_sound_min_dist	= (1<<1),
-	st_sound_max_dist	= (1<<2),
-	st_sound_ai_dist	= (1<<3),
-	st_sound_info_name	= (1<<4),
-	st_sound_info_object= (1<<5),
+enum
+{
+    st_sound = (1 << 0),
+    st_sound_min_dist = (1 << 1),
+    st_sound_max_dist = (1 << 2),
+    st_sound_ai_dist = (1 << 3),
+    st_sound_info_name = (1 << 4),
+    st_sound_info_object = (1 << 5),
 };
 
 extern Flags32 g_stats_flags;
diff --git a/src/xrEngine/Text_Console.cpp b/src/xrEngine/Text_Console.cpp
index 83bc78e6dff..67ec630ea17 100644
--- a/src/xrEngine/Text_Console.cpp
+++ b/src/xrEngine/Text_Console.cpp
@@ -2,341 +2,343 @@
 #include "Text_Console.h"
 #include "line_editor.h"
 
-extern char const * const		ioc_prompt;
-extern char const * const		ch_cursor;
+extern char const* const ioc_prompt;
+extern char const* const ch_cursor;
 int g_svTextConsoleUpdateRate = 1;
 
 CTextConsole::CTextConsole()
 {
-	m_pMainWnd    = NULL;
-	m_hConsoleWnd = NULL;
-	m_hLogWnd     = NULL;
-	m_hLogWndFont = NULL;
+    m_pMainWnd = NULL;
+    m_hConsoleWnd = NULL;
+    m_hLogWnd = NULL;
+    m_hLogWndFont = NULL;
 
-	m_bScrollLog  = true;
-	m_dwStartLine = 0;
+    m_bScrollLog = true;
+    m_dwStartLine = 0;
 
-	m_bNeedUpdate      = false;
-	m_dwLastUpdateTime = Device.dwTimeGlobal;
-	m_last_time        = Device.dwTimeGlobal;
+    m_bNeedUpdate = false;
+    m_dwLastUpdateTime = Device.dwTimeGlobal;
+    m_last_time = Device.dwTimeGlobal;
 }
 
 CTextConsole::~CTextConsole()
 {
-	m_pMainWnd = NULL;
+    m_pMainWnd = NULL;
 }
 
 //-------------------------------------------------------------------------------------------
-LRESULT CALLBACK TextConsole_WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
-void	CTextConsole::CreateConsoleWnd()
+LRESULT CALLBACK TextConsole_WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
+void CTextConsole::CreateConsoleWnd()
 {
-	HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(0);
-	//----------------------------------
-	RECT cRc;
-	GetClientRect(*m_pMainWnd, &cRc);
-	INT lX = cRc.left;
-	INT lY = cRc.top;
-	INT lWidth = cRc.right - cRc.left;
-	INT lHeight = cRc.bottom - cRc.top;
-	//----------------------------------
-	const char*	wndclass ="TEXT_CONSOLE";
-
-	// Register the windows class
-	WNDCLASS wndClass = { 0, TextConsole_WndProc, 0, 0, hInstance,
-		NULL,
-		LoadCursor( hInstance, IDC_ARROW ),
-		GetStockBrush(GRAY_BRUSH),
-		NULL, wndclass };
-	RegisterClass( &wndClass );
-
-	// Set the window's initial style
-	u32 dwWindowStyle = WS_OVERLAPPED | WS_CHILD | WS_VISIBLE;// | WS_CLIPSIBLINGS;// | WS_CLIPCHILDREN;
-
-	// Set the window's initial width
-	RECT rc;
-	SetRect			( &rc, lX, lY, lWidth, lHeight );
-//	AdjustWindowRect( &rc, dwWindowStyle, FALSE );
-
-	// Create the render window
-	m_hConsoleWnd = CreateWindow( wndclass, "XRAY Text Console", dwWindowStyle,
-		lX, lY,
-		lWidth, lHeight, *m_pMainWnd,
-		0, hInstance, 0L );
-	//---------------------------------------------------------------------------
-	R_ASSERT2(m_hConsoleWnd, "Unable to Create TextConsole Window!");
+    HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(0);
+    //----------------------------------
+    RECT cRc;
+    GetClientRect(*m_pMainWnd, &cRc);
+    INT lX = cRc.left;
+    INT lY = cRc.top;
+    INT lWidth = cRc.right - cRc.left;
+    INT lHeight = cRc.bottom - cRc.top;
+    //----------------------------------
+    const char* wndclass = "TEXT_CONSOLE";
+
+    // Register the windows class
+    WNDCLASS wndClass = {0, TextConsole_WndProc, 0, 0, hInstance,
+                         NULL,
+                         LoadCursor(hInstance, IDC_ARROW),
+                         GetStockBrush(GRAY_BRUSH),
+                         NULL, wndclass
+                        };
+    RegisterClass(&wndClass);
+
+    // Set the window's initial style
+    u32 dwWindowStyle = WS_OVERLAPPED | WS_CHILD | WS_VISIBLE;// | WS_CLIPSIBLINGS;// | WS_CLIPCHILDREN;
+
+    // Set the window's initial width
+    RECT rc;
+    SetRect(&rc, lX, lY, lWidth, lHeight);
+    // AdjustWindowRect( &rc, dwWindowStyle, FALSE );
+
+    // Create the render window
+    m_hConsoleWnd = CreateWindow(wndclass, "XRAY Text Console", dwWindowStyle,
+                                 lX, lY,
+                                 lWidth, lHeight, *m_pMainWnd,
+                                 0, hInstance, 0L);
+    //---------------------------------------------------------------------------
+    R_ASSERT2(m_hConsoleWnd, "Unable to Create TextConsole Window!");
 };
 //-------------------------------------------------------------------------------------------
-LRESULT CALLBACK TextConsole_LogWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
-void	CTextConsole::CreateLogWnd()
+LRESULT CALLBACK TextConsole_LogWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
+void CTextConsole::CreateLogWnd()
 {
-	HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(0);
-	//----------------------------------
-	RECT cRc;
-	GetClientRect(m_hConsoleWnd, &cRc);
-	INT lX = cRc.left;
-	INT lY = cRc.top;
-	INT lWidth = cRc.right - cRc.left;
-	INT lHeight = cRc.bottom - cRc.top;
-	//----------------------------------
-	const char*	wndclass ="TEXT_CONSOLE_LOG_WND";
-
-	// Register the windows class
-	WNDCLASS wndClass = { 0, TextConsole_LogWndProc, 0, 0, hInstance,
-		NULL,
-		LoadCursor( NULL, IDC_ARROW ),
-		GetStockBrush(BLACK_BRUSH),
-		NULL, wndclass };
-	RegisterClass( &wndClass );
-
-	// Set the window's initial style
-	u32 dwWindowStyle = WS_OVERLAPPED | WS_CHILD | WS_VISIBLE;// | WS_CLIPSIBLINGS;
-//	u32 dwWindowStyleEx = WS_EX_CLIENTEDGE;
-
-	// Set the window's initial width
-	RECT rc;
-	SetRect			( &rc, lX, lY, lWidth, lHeight );
-//	AdjustWindowRect( &rc, dwWindowStyle, FALSE );
-
-	// Create the render window
-	m_hLogWnd = CreateWindow(wndclass, "XRAY Text Console Log", dwWindowStyle,
-		lX, lY,
-		lWidth, lHeight, m_hConsoleWnd,
-		0, hInstance, 0L );
-	//---------------------------------------------------------------------------
-	R_ASSERT2(m_hLogWnd, "Unable to Create TextConsole Window!");
-	//---------------------------------------------------------------------------
-	ShowWindow(m_hLogWnd, SW_SHOW); 
-	UpdateWindow(m_hLogWnd);
-	//-----------------------------------------------
-	LOGFONT lf; 
-	lf.lfHeight = -12; 
-	lf.lfWidth = 0;
-	lf.lfEscapement = 0; 
-	lf.lfOrientation = 0; 
-	lf.lfWeight = FW_NORMAL;
-	lf.lfItalic = 0; 
-	lf.lfUnderline = 0; 
-	lf.lfStrikeOut = 0; 
-	lf.lfCharSet = DEFAULT_CHARSET;
-	lf.lfOutPrecision = OUT_STRING_PRECIS;
-	lf.lfClipPrecision = CLIP_STROKE_PRECIS;	
-	lf.lfQuality = DRAFT_QUALITY;
-	lf.lfPitchAndFamily = VARIABLE_PITCH | FF_SWISS;
-	xr_sprintf(lf.lfFaceName,sizeof(lf.lfFaceName),"");
-
-	m_hLogWndFont = CreateFontIndirect(&lf);
-	R_ASSERT2(m_hLogWndFont, "Unable to Create Font for Log Window");
-	//------------------------------------------------
-	m_hDC_LogWnd = GetDC(m_hLogWnd);
-	R_ASSERT2(m_hDC_LogWnd, "Unable to Get DC for Log Window!");
-	//------------------------------------------------
-	m_hDC_LogWnd_BackBuffer = CreateCompatibleDC(m_hDC_LogWnd);
-	R_ASSERT2(m_hDC_LogWnd_BackBuffer, "Unable to Create Compatible DC for Log Window!");
-	//------------------------------------------------
-	GetClientRect(m_hLogWnd, &cRc);
-	lWidth = cRc.right - cRc.left;
-	lHeight = cRc.bottom - cRc.top;
-	//----------------------------------
-	m_hBB_BM = CreateCompatibleBitmap(m_hDC_LogWnd, lWidth, lHeight);
-	R_ASSERT2(m_hBB_BM, "Unable to Create Compatible Bitmap for Log Window!");
-	//------------------------------------------------
-	m_hOld_BM = (HBITMAP)SelectObject(m_hDC_LogWnd_BackBuffer, m_hBB_BM);
-	//------------------------------------------------
-	m_hPrevFont = (HFONT)SelectObject(m_hDC_LogWnd_BackBuffer, m_hLogWndFont);
-	//------------------------------------------------
-	SetTextColor(m_hDC_LogWnd_BackBuffer, RGB(255, 255, 255));
-	SetBkColor(m_hDC_LogWnd_BackBuffer, RGB(1, 1, 1));
-	//------------------------------------------------
-	m_hBackGroundBrush = GetStockBrush(BLACK_BRUSH);
+    HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(0);
+    //----------------------------------
+    RECT cRc;
+    GetClientRect(m_hConsoleWnd, &cRc);
+    INT lX = cRc.left;
+    INT lY = cRc.top;
+    INT lWidth = cRc.right - cRc.left;
+    INT lHeight = cRc.bottom - cRc.top;
+    //----------------------------------
+    const char* wndclass = "TEXT_CONSOLE_LOG_WND";
+
+    // Register the windows class
+    WNDCLASS wndClass = {0, TextConsole_LogWndProc, 0, 0, hInstance,
+                         NULL,
+                         LoadCursor(NULL, IDC_ARROW),
+                         GetStockBrush(BLACK_BRUSH),
+                         NULL, wndclass
+                        };
+    RegisterClass(&wndClass);
+
+    // Set the window's initial style
+    u32 dwWindowStyle = WS_OVERLAPPED | WS_CHILD | WS_VISIBLE;// | WS_CLIPSIBLINGS;
+    // u32 dwWindowStyleEx = WS_EX_CLIENTEDGE;
+
+    // Set the window's initial width
+    RECT rc;
+    SetRect(&rc, lX, lY, lWidth, lHeight);
+    // AdjustWindowRect( &rc, dwWindowStyle, FALSE );
+
+    // Create the render window
+    m_hLogWnd = CreateWindow(wndclass, "XRAY Text Console Log", dwWindowStyle,
+                             lX, lY,
+                             lWidth, lHeight, m_hConsoleWnd,
+                             0, hInstance, 0L);
+    //---------------------------------------------------------------------------
+    R_ASSERT2(m_hLogWnd, "Unable to Create TextConsole Window!");
+    //---------------------------------------------------------------------------
+    ShowWindow(m_hLogWnd, SW_SHOW);
+    UpdateWindow(m_hLogWnd);
+    //-----------------------------------------------
+    LOGFONT lf;
+    lf.lfHeight = -12;
+    lf.lfWidth = 0;
+    lf.lfEscapement = 0;
+    lf.lfOrientation = 0;
+    lf.lfWeight = FW_NORMAL;
+    lf.lfItalic = 0;
+    lf.lfUnderline = 0;
+    lf.lfStrikeOut = 0;
+    lf.lfCharSet = DEFAULT_CHARSET;
+    lf.lfOutPrecision = OUT_STRING_PRECIS;
+    lf.lfClipPrecision = CLIP_STROKE_PRECIS;
+    lf.lfQuality = DRAFT_QUALITY;
+    lf.lfPitchAndFamily = VARIABLE_PITCH | FF_SWISS;
+    xr_sprintf(lf.lfFaceName, sizeof(lf.lfFaceName), "");
+
+    m_hLogWndFont = CreateFontIndirect(&lf);
+    R_ASSERT2(m_hLogWndFont, "Unable to Create Font for Log Window");
+    //------------------------------------------------
+    m_hDC_LogWnd = GetDC(m_hLogWnd);
+    R_ASSERT2(m_hDC_LogWnd, "Unable to Get DC for Log Window!");
+    //------------------------------------------------
+    m_hDC_LogWnd_BackBuffer = CreateCompatibleDC(m_hDC_LogWnd);
+    R_ASSERT2(m_hDC_LogWnd_BackBuffer, "Unable to Create Compatible DC for Log Window!");
+    //------------------------------------------------
+    GetClientRect(m_hLogWnd, &cRc);
+    lWidth = cRc.right - cRc.left;
+    lHeight = cRc.bottom - cRc.top;
+    //----------------------------------
+    m_hBB_BM = CreateCompatibleBitmap(m_hDC_LogWnd, lWidth, lHeight);
+    R_ASSERT2(m_hBB_BM, "Unable to Create Compatible Bitmap for Log Window!");
+    //------------------------------------------------
+    m_hOld_BM = (HBITMAP)SelectObject(m_hDC_LogWnd_BackBuffer, m_hBB_BM);
+    //------------------------------------------------
+    m_hPrevFont = (HFONT)SelectObject(m_hDC_LogWnd_BackBuffer, m_hLogWndFont);
+    //------------------------------------------------
+    SetTextColor(m_hDC_LogWnd_BackBuffer, RGB(255, 255, 255));
+    SetBkColor(m_hDC_LogWnd_BackBuffer, RGB(1, 1, 1));
+    //------------------------------------------------
+    m_hBackGroundBrush = GetStockBrush(BLACK_BRUSH);
 }
 
 void CTextConsole::Initialize()
 {
-	inherited::Initialize();
-	
-	m_pMainWnd         = &Device.m_hWnd;
-	m_dwLastUpdateTime = Device.dwTimeGlobal;
-	m_last_time        = Device.dwTimeGlobal;
+    inherited::Initialize();
 
-	CreateConsoleWnd();
-	CreateLogWnd();
+    m_pMainWnd = &Device.m_hWnd;
+    m_dwLastUpdateTime = Device.dwTimeGlobal;
+    m_last_time = Device.dwTimeGlobal;
 
-	ShowWindow( m_hConsoleWnd, SW_SHOW );
-	UpdateWindow( m_hConsoleWnd );	
+    CreateConsoleWnd();
+    CreateLogWnd();
 
-	m_server_info.ResetData();
+    ShowWindow(m_hConsoleWnd, SW_SHOW);
+    UpdateWindow(m_hConsoleWnd);
+
+    m_server_info.ResetData();
 }
 
 void CTextConsole::Destroy()
 {
-	inherited::Destroy();	
+    inherited::Destroy();
 
-	SelectObject( m_hDC_LogWnd_BackBuffer, m_hPrevFont );
-	SelectObject( m_hDC_LogWnd_BackBuffer, m_hOld_BM );
+    SelectObject(m_hDC_LogWnd_BackBuffer, m_hPrevFont);
+    SelectObject(m_hDC_LogWnd_BackBuffer, m_hOld_BM);
 
-	if ( m_hBB_BM )           DeleteObject( m_hBB_BM );
-	if ( m_hOld_BM )          DeleteObject( m_hOld_BM );
-	if ( m_hLogWndFont )      DeleteObject( m_hLogWndFont );
-	if ( m_hPrevFont )        DeleteObject( m_hPrevFont );
-	if ( m_hBackGroundBrush ) DeleteObject( m_hBackGroundBrush );
+    if (m_hBB_BM) DeleteObject(m_hBB_BM);
+    if (m_hOld_BM) DeleteObject(m_hOld_BM);
+    if (m_hLogWndFont) DeleteObject(m_hLogWndFont);
+    if (m_hPrevFont) DeleteObject(m_hPrevFont);
+    if (m_hBackGroundBrush) DeleteObject(m_hBackGroundBrush);
 
-	ReleaseDC( m_hLogWnd, m_hDC_LogWnd_BackBuffer );
-	ReleaseDC( m_hLogWnd, m_hDC_LogWnd );
+    ReleaseDC(m_hLogWnd, m_hDC_LogWnd_BackBuffer);
+    ReleaseDC(m_hLogWnd, m_hDC_LogWnd);
 
-	DestroyWindow( m_hLogWnd );
-	DestroyWindow( m_hConsoleWnd );
+    DestroyWindow(m_hLogWnd);
+    DestroyWindow(m_hConsoleWnd);
 }
 
 void CTextConsole::OnRender() {} //disable ÑConsole::OnRender()
 
 void CTextConsole::OnPaint()
 {
-	RECT wRC;
-	PAINTSTRUCT ps;
-	BeginPaint( m_hLogWnd, &ps );
-
-	if ( /*m_bNeedUpdate*/ Device.dwFrame % 2 )
-	{
-//		m_dwLastUpdateTime = Device.dwTimeGlobal;
-//		m_bNeedUpdate = false;
-		
-		GetClientRect( m_hLogWnd, &wRC );
-		DrawLog( m_hDC_LogWnd_BackBuffer, &wRC );
-	}
-	else
-	{
-		wRC = ps.rcPaint;
-	}
-	
-	
-	BitBlt(	m_hDC_LogWnd,
-			wRC.left, wRC.top,
-			wRC.right - wRC.left, wRC.bottom - wRC.top,
-			m_hDC_LogWnd_BackBuffer,
-			wRC.left, wRC.top,
-			SRCCOPY); //(FullUpdate) ? SRCCOPY : NOTSRCCOPY);
-/*
-	Msg ("URect - %d:%d - %d:%d", ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right, ps.rcPaint.bottom);
-*/
-	EndPaint( m_hLogWnd, &ps );
+    RECT wRC;
+    PAINTSTRUCT ps;
+    BeginPaint(m_hLogWnd, &ps);
+
+    if ( /*m_bNeedUpdate*/ Device.dwFrame % 2)
+    {
+        // m_dwLastUpdateTime = Device.dwTimeGlobal;
+        // m_bNeedUpdate = false;
+
+        GetClientRect(m_hLogWnd, &wRC);
+        DrawLog(m_hDC_LogWnd_BackBuffer, &wRC);
+    }
+    else
+    {
+        wRC = ps.rcPaint;
+    }
+
+
+    BitBlt(m_hDC_LogWnd,
+           wRC.left, wRC.top,
+           wRC.right - wRC.left, wRC.bottom - wRC.top,
+           m_hDC_LogWnd_BackBuffer,
+           wRC.left, wRC.top,
+           SRCCOPY); //(FullUpdate) ? SRCCOPY : NOTSRCCOPY);
+    /*
+     Msg ("URect - %d:%d - %d:%d", ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right, ps.rcPaint.bottom);
+     */
+    EndPaint(m_hLogWnd, &ps);
 }
 
-void CTextConsole::DrawLog( HDC hDC, RECT* pRect )
+void CTextConsole::DrawLog(HDC hDC, RECT* pRect)
 {
-	TEXTMETRIC tm;
-	GetTextMetrics(hDC, &tm);
-
-	RECT wRC = *pRect;
-	GetClientRect(m_hLogWnd, &wRC);
-	FillRect(hDC, &wRC, m_hBackGroundBrush);
-
-	int Width = wRC.right - wRC.left;
-	int Height = wRC.bottom - wRC.top;
-	wRC = *pRect;
-	int y_top_max = (int)(0.32f * Height);
-
-	//---------------------------------------------------------------------------------
-	LPCSTR s_edt = ec().str_edit();
-	LPCSTR s_cur = ec().str_before_cursor();
-
-	u32 cur_len = xr_strlen( s_cur ) + xr_strlen( ch_cursor ) + 1;
-	PSTR buf = (PSTR)_alloca( cur_len * sizeof(char) );
-	xr_strcpy( buf, cur_len, s_cur );
-	xr_strcat( buf, cur_len, ch_cursor );
-	buf[cur_len-1] = 0;
-
-	u32 cur0_len = xr_strlen( s_cur );
-
-	int xb = 25;
-	
-	SetTextColor( hDC, RGB(255, 255, 255) );
-	TextOut( hDC, xb, Height-tm.tmHeight-1, buf, cur_len-1 );
-	buf[ cur0_len ] = 0;
-	
-	SetTextColor(hDC, RGB(0, 0, 0));
-	TextOut( hDC, xb, Height-tm.tmHeight-1, buf, cur0_len );
-
-
-	SetTextColor( hDC, RGB(255, 255, 255) );
-	TextOut( hDC, 0, Height-tm.tmHeight-3, ioc_prompt, xr_strlen(ioc_prompt) ); // ">>> "
-
-	SetTextColor( hDC, (COLORREF)bgr2rgb(get_mark_color( mark11 )) );
-	TextOut( hDC, xb, Height-tm.tmHeight-3, s_edt, xr_strlen(s_edt) );
-
-	SetTextColor( hDC, RGB(205, 205, 225) );
-	u32 log_line = LogFile->size()-1;
-	string16 q, q2;
-	itoa( log_line, q, 10 );
-	xr_strcpy( q2, sizeof(q2), "[" );
-	xr_strcat( q2, sizeof(q2), q );
-	xr_strcat( q2, sizeof(q2), "]" );
-	u32 qn = xr_strlen( q2 );
-
-	TextOut( hDC, Width - 8 * qn, Height-tm.tmHeight-tm.tmHeight, q2, qn );
-
-	int ypos = Height - tm.tmHeight - tm.tmHeight;
-	for( int i = LogFile->size()-1-scroll_delta; i >= 0; --i ) 
-	{
-		ypos -= tm.tmHeight;
-		if ( ypos < y_top_max )
-		{
-			break;
-		}
-		LPCSTR ls = ((*LogFile)[i]).c_str();
-
-		if ( !ls )
-		{
-			continue;
-		}
-		Console_mark cm = (Console_mark)ls[0];
-		COLORREF     c2 = (COLORREF)bgr2rgb( get_mark_color( cm ) );
-		SetTextColor( hDC, c2 );
-		u8 b = (is_mark( cm ))? 2 : 0;
-		LPCSTR pOut = ls + b;
-
-		BOOL res = TextOut( hDC, 10, ypos, pOut, xr_strlen(pOut) );
-		if ( !res )
-		{
-			R_ASSERT2( 0, "TextOut(..) return NULL" );
-		}
-	}
-
-	if ( g_pGameLevel && ( Device.dwTimeGlobal - m_last_time > 500 ) )
-	{
-		m_last_time = Device.dwTimeGlobal;
-
-		m_server_info.ResetData();
-		g_pGameLevel->GetLevelInfo( &m_server_info );
-	}
-
-	ypos = 5;
-	for ( u32 i = 0; i < m_server_info.Size(); ++i )
-	{
-		SetTextColor( hDC, m_server_info[i].color );
-		TextOut( hDC, 10, ypos, m_server_info[i].name, xr_strlen(m_server_info[i].name) );
-
-		ypos += tm.tmHeight;
-		if ( ypos > y_top_max )
-		{
-			break;
-		}
-	}
+    TEXTMETRIC tm;
+    GetTextMetrics(hDC, &tm);
+
+    RECT wRC = *pRect;
+    GetClientRect(m_hLogWnd, &wRC);
+    FillRect(hDC, &wRC, m_hBackGroundBrush);
+
+    int Width = wRC.right - wRC.left;
+    int Height = wRC.bottom - wRC.top;
+    wRC = *pRect;
+    int y_top_max = (int)(0.32f * Height);
+
+    //---------------------------------------------------------------------------------
+    LPCSTR s_edt = ec().str_edit();
+    LPCSTR s_cur = ec().str_before_cursor();
+
+    u32 cur_len = xr_strlen(s_cur) + xr_strlen(ch_cursor) + 1;
+    PSTR buf = (PSTR)_alloca(cur_len * sizeof(char));
+    xr_strcpy(buf, cur_len, s_cur);
+    xr_strcat(buf, cur_len, ch_cursor);
+    buf[cur_len - 1] = 0;
+
+    u32 cur0_len = xr_strlen(s_cur);
+
+    int xb = 25;
+
+    SetTextColor(hDC, RGB(255, 255, 255));
+    TextOut(hDC, xb, Height - tm.tmHeight - 1, buf, cur_len - 1);
+    buf[cur0_len] = 0;
+
+    SetTextColor(hDC, RGB(0, 0, 0));
+    TextOut(hDC, xb, Height - tm.tmHeight - 1, buf, cur0_len);
+
+
+    SetTextColor(hDC, RGB(255, 255, 255));
+    TextOut(hDC, 0, Height - tm.tmHeight - 3, ioc_prompt, xr_strlen(ioc_prompt)); // ">>> "
+
+    SetTextColor(hDC, (COLORREF)bgr2rgb(get_mark_color(mark11)));
+    TextOut(hDC, xb, Height - tm.tmHeight - 3, s_edt, xr_strlen(s_edt));
+
+    SetTextColor(hDC, RGB(205, 205, 225));
+    u32 log_line = LogFile->size() - 1;
+    string16 q, q2;
+    itoa(log_line, q, 10);
+    xr_strcpy(q2, sizeof(q2), "[");
+    xr_strcat(q2, sizeof(q2), q);
+    xr_strcat(q2, sizeof(q2), "]");
+    u32 qn = xr_strlen(q2);
+
+    TextOut(hDC, Width - 8 * qn, Height - tm.tmHeight - tm.tmHeight, q2, qn);
+
+    int ypos = Height - tm.tmHeight - tm.tmHeight;
+    for (int i = LogFile->size() - 1 - scroll_delta; i >= 0; --i)
+    {
+        ypos -= tm.tmHeight;
+        if (ypos < y_top_max)
+        {
+            break;
+        }
+        LPCSTR ls = ((*LogFile)[i]).c_str();
+
+        if (!ls)
+        {
+            continue;
+        }
+        Console_mark cm = (Console_mark)ls[0];
+        COLORREF c2 = (COLORREF)bgr2rgb(get_mark_color(cm));
+        SetTextColor(hDC, c2);
+        u8 b = (is_mark(cm)) ? 2 : 0;
+        LPCSTR pOut = ls + b;
+
+        BOOL res = TextOut(hDC, 10, ypos, pOut, xr_strlen(pOut));
+        if (!res)
+        {
+            R_ASSERT2(0, "TextOut(..) return NULL");
+        }
+    }
+
+    if (g_pGameLevel && (Device.dwTimeGlobal - m_last_time > 500))
+    {
+        m_last_time = Device.dwTimeGlobal;
+
+        m_server_info.ResetData();
+        g_pGameLevel->GetLevelInfo(&m_server_info);
+    }
+
+    ypos = 5;
+    for (u32 i = 0; i < m_server_info.Size(); ++i)
+    {
+        SetTextColor(hDC, m_server_info[i].color);
+        TextOut(hDC, 10, ypos, m_server_info[i].name, xr_strlen(m_server_info[i].name));
+
+        ypos += tm.tmHeight;
+        if (ypos > y_top_max)
+        {
+            break;
+        }
+    }
 }
 /*
 void CTextConsole::IR_OnKeyboardPress( int dik ) !!!!!!!!!!!!!!!!!!!!!
 {
-	m_bNeedUpdate = true;
-	inherited::IR_OnKeyboardPress( dik );
+m_bNeedUpdate = true;
+inherited::IR_OnKeyboardPress( dik );
 }
 */
 void CTextConsole::OnFrame()
 {
-	inherited::OnFrame();
-/*	if ( !m_bNeedUpdate && m_dwLastUpdateTime + 1000/g_svTextConsoleUpdateRate > Device.dwTimeGlobal )
-	{
-		return;
-	}
-*/	InvalidateRect( m_hConsoleWnd, NULL, FALSE );
-	SetCursor( LoadCursor( NULL, IDC_ARROW ) );	
-//	m_bNeedUpdate = true;
+    inherited::OnFrame();
+    /* if ( !m_bNeedUpdate && m_dwLastUpdateTime + 1000/g_svTextConsoleUpdateRate > Device.dwTimeGlobal )
+     {
+     return;
+     }
+     */ InvalidateRect(m_hConsoleWnd, NULL, FALSE);
+    SetCursor(LoadCursor(NULL, IDC_ARROW));
+    // m_bNeedUpdate = true;
 }
diff --git a/src/xrEngine/Text_Console.h b/src/xrEngine/Text_Console.h
index b9d77646550..bb2316c8a23 100644
--- a/src/xrEngine/Text_Console.h
+++ b/src/xrEngine/Text_Console.h
@@ -5,50 +5,50 @@
 class ENGINE_API CTextConsole : public CConsole
 {
 private:
-	typedef CConsole inherited;
+    typedef CConsole inherited;
 
 private:
-	HWND*	m_pMainWnd;
+    HWND* m_pMainWnd;
 
-	HWND	m_hConsoleWnd;
-	void	CreateConsoleWnd	();
-	
-	HWND	m_hLogWnd;	
-	void	CreateLogWnd		();
+    HWND m_hConsoleWnd;
+    void CreateConsoleWnd();
 
-	bool	m_bScrollLog;
-	u32		m_dwStartLine;
-	void	DrawLog(HDC hDC, RECT* pRect);
+    HWND m_hLogWnd;
+    void CreateLogWnd();
+
+    bool m_bScrollLog;
+    u32 m_dwStartLine;
+    void DrawLog(HDC hDC, RECT* pRect);
 
 private:
-	HFONT	m_hLogWndFont;
-	HFONT	m_hPrevFont;
-	HBRUSH	m_hBackGroundBrush;
+    HFONT m_hLogWndFont;
+    HFONT m_hPrevFont;
+    HBRUSH m_hBackGroundBrush;
 
-	HDC		m_hDC_LogWnd;
-	HDC		m_hDC_LogWnd_BackBuffer;
-	HBITMAP m_hBB_BM, m_hOld_BM;
+    HDC m_hDC_LogWnd;
+    HDC m_hDC_LogWnd_BackBuffer;
+    HBITMAP m_hBB_BM, m_hOld_BM;
 
-	bool	m_bNeedUpdate;
-	u32		m_dwLastUpdateTime;
+    bool m_bNeedUpdate;
+    u32 m_dwLastUpdateTime;
 
-	u32		m_last_time;
-	CServerInfo m_server_info;
+    u32 m_last_time;
+    CServerInfo m_server_info;
 
 public:
-					CTextConsole();
-	virtual			~CTextConsole();
+    CTextConsole();
+    virtual ~CTextConsole();
 
-	virtual	void	Initialize	();
-	virtual	void	Destroy		();
+    virtual void Initialize();
+    virtual void Destroy();
 
-	virtual void			OnRender	();
-	virtual void	_BCL	OnFrame		();
+    virtual void OnRender();
+    virtual void _BCL OnFrame();
 
-//	virtual void	IR_OnKeyboardPress		(int dik);
+    // virtual void IR_OnKeyboardPress (int dik);
 
-			void	AddString	(LPCSTR string);
-			void	OnPaint		();
+    void AddString(LPCSTR string);
+    void OnPaint();
 
 };// class TextConsole
 
diff --git a/src/xrEngine/Text_Console_WndProc.cpp b/src/xrEngine/Text_Console_WndProc.cpp
index 635e019ae20..423c1d209dd 100644
--- a/src/xrEngine/Text_Console_WndProc.cpp
+++ b/src/xrEngine/Text_Console_WndProc.cpp
@@ -1,51 +1,54 @@
 #include "stdafx.h"
 #include "Text_Console.h"
 
-LRESULT CALLBACK TextConsole_WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
+LRESULT CALLBACK TextConsole_WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
 {
-	switch(uMsg)
-	{
-	case WM_PAINT:
-		{			
-//			return 0;
-		}break;
-	case  WM_ERASEBKGND:
-		{
-			int x=0;
-			x=x;
-//			CTextConsole* pTextConsole = (CTextConsole*)Console;
-//			pTextConsole->OnPaint();
-//			return 1;
-		}break;
-	case WM_NCPAINT :
-		{
-//			CTextConsole* pTextConsole = (CTextConsole*)Console;
-//			pTextConsole->OnPaint();
-			int x=0;
-			x=x;
-//			return 0;
-		}break;
-	default:
-		break;
-	}
-	return DefWindowProc(hWnd,uMsg,wParam,lParam);
+    switch (uMsg)
+    {
+    case WM_PAINT:
+    {
+        // return 0;
+    } break;
+    case WM_ERASEBKGND:
+    {
+        int x = 0;
+        x = x;
+        // CTextConsole* pTextConsole = (CTextConsole*)Console;
+        // pTextConsole->OnPaint();
+        // return 1;
+    }
+    break;
+    case WM_NCPAINT:
+    {
+        // CTextConsole* pTextConsole = (CTextConsole*)Console;
+        // pTextConsole->OnPaint();
+        int x = 0;
+        x = x;
+        // return 0;
+    }
+    break;
+    default:
+        break;
+    }
+    return DefWindowProc(hWnd, uMsg, wParam, lParam);
 }
 
-LRESULT CALLBACK TextConsole_LogWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
+LRESULT CALLBACK TextConsole_LogWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
 {
-	switch(uMsg)
-	{
-	case WM_ERASEBKGND:
-		return (LRESULT)1; // Say we handled it.
+    switch (uMsg)
+    {
+    case WM_ERASEBKGND:
+        return (LRESULT)1; // Say we handled it.
 
-	case WM_PAINT:
-		{
-			CTextConsole* pTextConsole = (CTextConsole*)Console;
-			pTextConsole->OnPaint();
-			return (LRESULT)0; // Say we handled it.
-		}break;
-	default:
-		break;
-	}
-	return DefWindowProc(hWnd,uMsg,wParam,lParam);
+    case WM_PAINT:
+    {
+        CTextConsole* pTextConsole = (CTextConsole*)Console;
+        pTextConsole->OnPaint();
+        return (LRESULT)0; // Say we handled it.
+    }
+    break;
+    default:
+        break;
+    }
+    return DefWindowProc(hWnd, uMsg, wParam, lParam);
 }
\ No newline at end of file
diff --git a/src/xrEngine/WaveForm.h b/src/xrEngine/WaveForm.h
index 1ec8e105ef8..a2a84a15bc4 100644
--- a/src/xrEngine/WaveForm.h
+++ b/src/xrEngine/WaveForm.h
@@ -5,59 +5,66 @@
 #pragma pack(push,4)
 struct WaveForm
 {
-	enum EFunction
-	{
-		fCONSTANT		= 0,
-		fSIN,
-		fTRIANGLE,
-		fSQUARE,
-		fSAWTOOTH,
-		fINVSAWTOOTH,
-		fFORCE32		= u32(-1)
-	};
-	IC float signf		(float t) { return t/_abs(t); }
-	IC float Func		(float t)
-	{
-		switch (F)
-		{
-			case fCONSTANT:		return 0;
-			case fSIN:			return _sin(t*PI_MUL_2);
-			case fTRIANGLE:		return asinf(_sin((t-0.25f)*PI_MUL_2))/PI_DIV_2;
-			case fSQUARE:		return signf(_cos(t*PI));
-			case fSAWTOOTH:		return atanf(tanf((t+0.5f)*PI))/PI_DIV_2;
-			case fINVSAWTOOTH:	return -(atanf(tanf((t+0.5f)*PI))/PI_DIV_2);
-		}
-		return 0.f;
-	}
+    enum EFunction
+    {
+        fCONSTANT = 0,
+        fSIN,
+        fTRIANGLE,
+        fSQUARE,
+        fSAWTOOTH,
+        fINVSAWTOOTH,
+        fFORCE32 = u32(-1)
+    };
+    IC float signf(float t) { return t / _abs(t); }
+    IC float Func(float t)
+    {
+        switch (F)
+        {
+        case fCONSTANT:
+            return 0;
+        case fSIN:
+            return _sin(t*PI_MUL_2);
+        case fTRIANGLE:
+            return asinf(_sin((t - 0.25f)*PI_MUL_2)) / PI_DIV_2;
+        case fSQUARE:
+            return signf(_cos(t*PI));
+        case fSAWTOOTH:
+            return atanf(tanf((t + 0.5f)*PI)) / PI_DIV_2;
+        case fINVSAWTOOTH:
+            return -(atanf(tanf((t + 0.5f)*PI)) / PI_DIV_2);
+        }
+        return 0.f;
+    }
 public:
-	EFunction	F;
-	float		arg[4];
+    EFunction F;
+    float arg[4];
 
-	IC float Calculate	(float t)
-	{
-		// y = arg0 + arg1*func( (time+arg2)*arg3 )
-		float x = (t+arg[2])*arg[3];
-		return arg[0] + arg[1]*Func(x-floorf(x));
-	}
+    IC float Calculate(float t)
+    {
+        // y = arg0 + arg1*func( (time+arg2)*arg3 )
+        float x = (t + arg[2])*arg[3];
+        return arg[0] + arg[1] * Func(x - floorf(x));
+    }
 
-	WaveForm()	{
-		F		= fCONSTANT;
-		arg[0]	= 0;
-		arg[1]	= 1;
-		arg[2]	= 0;
-		arg[3]	= 1;
-	}
+    WaveForm()
+    {
+        F = fCONSTANT;
+        arg[0] = 0;
+        arg[1] = 1;
+        arg[2] = 0;
+        arg[3] = 1;
+    }
 
-	IC	BOOL	Similar	(const WaveForm& W) const
-	{
-		if (!fsimilar(arg[0],W.arg[0],EPS_L))	return FALSE;
-		if (!fsimilar(arg[1],W.arg[1],EPS_L))	return FALSE;
-		if (fis_zero(arg[1],EPS_L))				return TRUE;
-		if (F	!=	W.F)						return FALSE;
-		if (!fsimilar(arg[2],W.arg[2],EPS_L))	return FALSE;
-		if (!fsimilar(arg[3],W.arg[3],EPS_L))	return FALSE;
-		return TRUE;
-	}
+    IC BOOL Similar(const WaveForm& W) const
+    {
+        if (!fsimilar(arg[0], W.arg[0], EPS_L)) return FALSE;
+        if (!fsimilar(arg[1], W.arg[1], EPS_L)) return FALSE;
+        if (fis_zero(arg[1], EPS_L)) return TRUE;
+        if (F != W.F) return FALSE;
+        if (!fsimilar(arg[2], W.arg[2], EPS_L)) return FALSE;
+        if (!fsimilar(arg[3], W.arg[3], EPS_L)) return FALSE;
+        return TRUE;
+    }
 };
 
 #pragma pack(pop)
diff --git a/src/xrEngine/XR_IOConsole.cpp b/src/xrEngine/XR_IOConsole.cpp
index 27e7abd9b58..1ec0389b64e 100644
--- a/src/xrEngine/XR_IOConsole.cpp
+++ b/src/xrEngine/XR_IOConsole.cpp
@@ -17,931 +17,978 @@
 
 #include "securom_api.h"
 
-static float const UI_BASE_WIDTH	= 1024.0f;
-static float const UI_BASE_HEIGHT	= 768.0f;
-static float const LDIST            = 0.05f;
-static u32   const cmd_history_max  = 64;
+static float const UI_BASE_WIDTH = 1024.0f;
+static float const UI_BASE_HEIGHT = 768.0f;
+static float const LDIST = 0.05f;
+static u32 const cmd_history_max = 64;
 
-static u32 const prompt_font_color  = color_rgba( 228, 228, 255, 255 );
-static u32 const tips_font_color    = color_rgba( 230, 250, 230, 255 );
-static u32 const cmd_font_color     = color_rgba( 138, 138, 245, 255 );
-static u32 const cursor_font_color  = color_rgba( 255, 255, 255, 255 );
-static u32 const total_font_color   = color_rgba( 250, 250,  15, 180 );
-static u32 const default_font_color = color_rgba( 250, 250, 250, 250 );
+static u32 const prompt_font_color = color_rgba(228, 228, 255, 255);
+static u32 const tips_font_color = color_rgba(230, 250, 230, 255);
+static u32 const cmd_font_color = color_rgba(138, 138, 245, 255);
+static u32 const cursor_font_color = color_rgba(255, 255, 255, 255);
+static u32 const total_font_color = color_rgba(250, 250, 15, 180);
+static u32 const default_font_color = color_rgba(250, 250, 250, 250);
 
-static u32 const back_color         = color_rgba(  20,  20,  20, 200 );
-static u32 const tips_back_color    = color_rgba(  20,  20,  20, 200 );
-static u32 const tips_select_color  = color_rgba(  90,  90, 140, 230 );
-static u32 const tips_word_color    = color_rgba(   5, 100,  56, 200 );
-static u32 const tips_scroll_back_color  = color_rgba( 15, 15, 15, 230 );
-static u32 const tips_scroll_pos_color   = color_rgba( 70, 70, 70, 240 );
+static u32 const back_color = color_rgba(20, 20, 20, 200);
+static u32 const tips_back_color = color_rgba(20, 20, 20, 200);
+static u32 const tips_select_color = color_rgba(90, 90, 140, 230);
+static u32 const tips_word_color = color_rgba(5, 100, 56, 200);
+static u32 const tips_scroll_back_color = color_rgba(15, 15, 15, 230);
+static u32 const tips_scroll_pos_color = color_rgba(70, 70, 70, 240);
 
 
-ENGINE_API CConsole*		Console		=	NULL;
+ENGINE_API CConsole* Console = NULL;
 
-extern char const * const	ioc_prompt;
-       char const * const	ioc_prompt	=	">>> ";
+extern char const* const ioc_prompt;
+char const* const ioc_prompt = ">>> ";
 
-extern char const * const	ch_cursor;
-       char const * const	ch_cursor	=	"_";
+extern char const* const ch_cursor;
+char const* const ch_cursor = "_";
 
 text_editor::line_edit_control& CConsole::ec()
 {
-	return m_editor->control();
+    return m_editor->control();
 }
 
-u32 CConsole::get_mark_color( Console_mark type )
+u32 CConsole::get_mark_color(Console_mark type)
 {
-	u32 color = default_font_color;
-	switch ( type )
-	{
-	case mark0:  color = color_rgba( 255, 255,   0, 255 ); break;
-	case mark1:  color = color_rgba( 255,   0,   0, 255 ); break;
-	case mark2:  color = color_rgba( 100, 100, 255, 255 ); break;
-	case mark3:  color = color_rgba(   0, 222, 205, 155 ); break;
-	case mark4:  color = color_rgba( 255,   0, 255, 255 ); break;
-	case mark5:  color = color_rgba( 155,  55, 170, 155 ); break;
-	case mark6:  color = color_rgba(  25, 200,  50, 255 ); break;
-	case mark7:  color = color_rgba( 255, 255,   0, 255 ); break;
-	case mark8:  color = color_rgba( 128, 128, 128, 255 ); break;
-	case mark9:  color = color_rgba(   0, 255,   0, 255 ); break;
-	case mark10: color = color_rgba(  55, 155, 140, 255 ); break;
-	case mark11: color = color_rgba( 205, 205, 105, 255 ); break;
-	case mark12: color = color_rgba( 128, 128, 250, 255 ); break;
-	case no_mark:
-	default: break;
-	}
-	return color;
+    u32 color = default_font_color;
+    switch (type)
+    {
+    case mark0:
+        color = color_rgba(255, 255, 0, 255);
+        break;
+    case mark1:
+        color = color_rgba(255, 0, 0, 255);
+        break;
+    case mark2:
+        color = color_rgba(100, 100, 255, 255);
+        break;
+    case mark3:
+        color = color_rgba(0, 222, 205, 155);
+        break;
+    case mark4:
+        color = color_rgba(255, 0, 255, 255);
+        break;
+    case mark5:
+        color = color_rgba(155, 55, 170, 155);
+        break;
+    case mark6:
+        color = color_rgba(25, 200, 50, 255);
+        break;
+    case mark7:
+        color = color_rgba(255, 255, 0, 255);
+        break;
+    case mark8:
+        color = color_rgba(128, 128, 128, 255);
+        break;
+    case mark9:
+        color = color_rgba(0, 255, 0, 255);
+        break;
+    case mark10:
+        color = color_rgba(55, 155, 140, 255);
+        break;
+    case mark11:
+        color = color_rgba(205, 205, 105, 255);
+        break;
+    case mark12:
+        color = color_rgba(128, 128, 250, 255);
+        break;
+    case no_mark:
+    default:
+        break;
+    }
+    return color;
 }
 
-bool CConsole::is_mark( Console_mark type )
+bool CConsole::is_mark(Console_mark type)
 {
-	switch ( type )
-	{
-	case mark0:  case mark1:  case mark2:  case mark3:
-	case mark4:  case mark5:  case mark6:  case mark7:
-	case mark8:  case mark9:  case mark10: case mark11:	case mark12:
-		return true;
-		break;
-	}
-	return false;
+    switch (type)
+    {
+    case mark0:
+    case mark1:
+    case mark2:
+    case mark3:
+    case mark4:
+    case mark5:
+    case mark6:
+    case mark7:
+    case mark8:
+    case mark9:
+    case mark10:
+    case mark11:
+    case mark12:
+        return true;
+        break;
+    }
+    return false;
 }
 
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 
 CConsole::CConsole()
-:m_hShader_back(NULL)
+    :m_hShader_back(NULL)
 {
-	m_editor          = xr_new( (u32)CONSOLE_BUF_SIZE );
-	m_cmd_history_max = cmd_history_max;
-	m_disable_tips    = false;
-	Register_callbacks();
-	Device.seqResolutionChanged.Add(this);
+    m_editor = xr_new((u32)CONSOLE_BUF_SIZE);
+    m_cmd_history_max = cmd_history_max;
+    m_disable_tips = false;
+    Register_callbacks();
+    Device.seqResolutionChanged.Add(this);
 }
 
 void CConsole::Initialize()
 {
-	scroll_delta	= 0;
-	bVisible		= false;
-	pFont			= NULL;
-	pFont2			= NULL;
-
-	m_mouse_pos.x	= 0;
-	m_mouse_pos.y	= 0;
-	m_last_cmd		= NULL;
-	
-	m_cmd_history.reserve( m_cmd_history_max + 2 );
-	m_cmd_history.clear_not_free();
-	reset_cmd_history_idx();
-
-	m_tips.reserve( MAX_TIPS_COUNT + 1 );
-	m_tips.clear_not_free();
-	m_temp_tips.reserve( MAX_TIPS_COUNT + 1 );
-	m_temp_tips.clear_not_free();
-
-	m_tips_mode		= 0;
-	m_prev_length_str = 0;
-	m_cur_cmd		= NULL;
-	reset_selected_tip();
-
-	// Commands
-	extern void CCC_Register();
-	CCC_Register();
+    scroll_delta = 0;
+    bVisible = false;
+    pFont = NULL;
+    pFont2 = NULL;
+
+    m_mouse_pos.x = 0;
+    m_mouse_pos.y = 0;
+    m_last_cmd = NULL;
+
+    m_cmd_history.reserve(m_cmd_history_max + 2);
+    m_cmd_history.clear_not_free();
+    reset_cmd_history_idx();
+
+    m_tips.reserve(MAX_TIPS_COUNT + 1);
+    m_tips.clear_not_free();
+    m_temp_tips.reserve(MAX_TIPS_COUNT + 1);
+    m_temp_tips.clear_not_free();
+
+    m_tips_mode = 0;
+    m_prev_length_str = 0;
+    m_cur_cmd = NULL;
+    reset_selected_tip();
+
+    // Commands
+    extern void CCC_Register();
+    CCC_Register();
 }
 
 CConsole::~CConsole()
 {
-	xr_delete( m_hShader_back );
-	xr_delete( m_editor );
-	Destroy();
-	Device.seqResolutionChanged.Remove(this);
+    xr_delete(m_hShader_back);
+    xr_delete(m_editor);
+    Destroy();
+    Device.seqResolutionChanged.Remove(this);
 }
 
 void CConsole::Destroy()
 {
-	xr_delete( pFont );
-	xr_delete( pFont2 );
-	Commands.clear();
+    xr_delete(pFont);
+    xr_delete(pFont2);
+    Commands.clear();
 }
 
-void CConsole::AddCommand( IConsole_Command* cc )
+void CConsole::AddCommand(IConsole_Command* cc)
 {
-	Commands[cc->Name()] = cc;
+    Commands[cc->Name()] = cc;
 }
 
-void CConsole::RemoveCommand( IConsole_Command* cc )
+void CConsole::RemoveCommand(IConsole_Command* cc)
 {
-	vecCMD_IT it = Commands.find( cc->Name() );
-	if ( Commands.end() != it )
-	{
-		Commands.erase(it);
-	}
+    vecCMD_IT it = Commands.find(cc->Name());
+    if (Commands.end() != it)
+    {
+        Commands.erase(it);
+    }
 }
 
 void CConsole::OnFrame()
 {
-	m_editor->on_frame();
-	
-	if ( Device.dwFrame % 10 == 0 )
-	{
-		update_tips();
-	}
+    m_editor->on_frame();
+
+    if (Device.dwFrame % 10 == 0)
+    {
+        update_tips();
+    }
 }
 
-void CConsole::OutFont( LPCSTR text, float& pos_y )
+void CConsole::OutFont(LPCSTR text, float& pos_y)
 {
-	float str_length = pFont->SizeOf_( text );
-	float scr_width  = 1.98f * Device.fWidth_2;
-	if( str_length > scr_width ) //1024.0f
-	{
-		float f	= 0.0f;
-		int sz	= 0;
-		int ln	= 0;
-		PSTR one_line = (PSTR)_alloca( (CONSOLE_BUF_SIZE + 1) * sizeof(char) );
-		
-		while( text[sz] && (ln + sz < CONSOLE_BUF_SIZE-5) )// ïåðåíîñ ñòðîê
-		{
-			one_line[ln+sz]   = text[sz];
-			one_line[ln+sz+1] = 0;
-			
-			float t	= pFont->SizeOf_( one_line + ln );
-			if ( t > scr_width )
-			{
-				OutFont		( text + sz + 1, pos_y );
-				pos_y		-= LDIST;
-				pFont->OutI	( -1.0f, pos_y, "%s", one_line + ln );
-				ln			= sz + 1;
-				f			= 0.0f;
-			}
-			else
-			{
-				f = t;
-			}
-
-			++sz;
-		}
-	}
-	else
-	{
-		pFont->OutI( -1.0f, pos_y, "%s", text );
-	}
+    float str_length = pFont->SizeOf_(text);
+    float scr_width = 1.98f * Device.fWidth_2;
+    if (str_length > scr_width) //1024.0f
+    {
+        float f = 0.0f;
+        int sz = 0;
+        int ln = 0;
+        PSTR one_line = (PSTR)_alloca((CONSOLE_BUF_SIZE + 1) * sizeof(char));
+
+        while (text[sz] && (ln + sz < CONSOLE_BUF_SIZE - 5))// ïåðåíîñ ñòðîê
+        {
+            one_line[ln + sz] = text[sz];
+            one_line[ln + sz + 1] = 0;
+
+            float t = pFont->SizeOf_(one_line + ln);
+            if (t > scr_width)
+            {
+                OutFont(text + sz + 1, pos_y);
+                pos_y -= LDIST;
+                pFont->OutI(-1.0f, pos_y, "%s", one_line + ln);
+                ln = sz + 1;
+                f = 0.0f;
+            }
+            else
+            {
+                f = t;
+            }
+
+            ++sz;
+        }
+    }
+    else
+    {
+        pFont->OutI(-1.0f, pos_y, "%s", text);
+    }
 }
 
 void CConsole::OnScreenResolutionChanged()
 {
-	xr_delete( pFont );
-	xr_delete( pFont2 );
+    xr_delete(pFont);
+    xr_delete(pFont2);
 }
 
 void CConsole::OnRender()
 {
-	if ( !bVisible )
-	{
-		return;
-	}
-
-	if ( !m_hShader_back )
-	{
-		m_hShader_back = xr_new< FactoryPtr >();
-		(*m_hShader_back)->create( "hud\\default", "ui\\ui_console" ); // "ui\\ui_empty"
-	}
-	
-	if ( !pFont )
-	{
-		pFont = xr_new( "hud_font_di", CGameFont::fsDeviceIndependent );
-		pFont->SetHeightI(  0.025f );
-	}
-	if( !pFont2 )
-	{
-		pFont2 = xr_new( "hud_font_di2", CGameFont::fsDeviceIndependent );
-		pFont2->SetHeightI( 0.025f );
-	}
-
-	bool bGame = false;	
-	if ( ( g_pGameLevel && g_pGameLevel->bReady ) ||
-		 ( g_pGamePersistent && g_pGamePersistent->m_pMainMenu && g_pGamePersistent->m_pMainMenu->IsActive() ) )
-	{
-		 bGame = true;
-	}
-	if ( g_dedicated_server )
-	{
-		bGame = false;
-	}
-	
-	DrawBackgrounds( bGame );
-
-	float fMaxY;
-	float dwMaxY = (float)Device.dwHeight;
-	// float dwMaxX=float(Device.dwWidth/2);
-	if ( bGame )
-	{
-		fMaxY  = 0.0f;
-		dwMaxY /= 2;
-	}
-	else
-	{
-		fMaxY = 1.0f;
-	}
-
-	float ypos  = fMaxY - LDIST * 1.1f;
-	float scr_x = 1.0f / Device.fWidth_2;
-
-	//---------------------------------------------------------------------------------
-	float scr_width  = 1.9f * Device.fWidth_2;
-	float ioc_d      = pFont->SizeOf_(ioc_prompt);
-	float d1         = pFont->SizeOf_( "_" );
-
-	LPCSTR s_cursor = ec().str_before_cursor();
-	LPCSTR s_b_mark = ec().str_before_mark();
-	LPCSTR s_mark   = ec().str_mark();
-	LPCSTR s_mark_a = ec().str_after_mark();
-
-	//	strncpy_s( buf1, cur_pos, editor, MAX_LEN );
-	float str_length = ioc_d + pFont->SizeOf_( s_cursor );
-	float out_pos    = 0.0f;
-	if( str_length > scr_width )
-	{
-		out_pos -= (str_length - scr_width);
-		str_length = scr_width;
-	}
-
-	pFont->SetColor( prompt_font_color );
-	pFont->OutI( -1.0f + out_pos * scr_x, ypos, "%s", ioc_prompt );
-	out_pos += ioc_d;
-
-	if ( !m_disable_tips && m_tips.size() )
-	{
-		pFont->SetColor( tips_font_color );
-
-		float shift_x = 0.0f;
-		switch ( m_tips_mode )
-		{
-		case 0: shift_x = scr_x * 1.0f;			break;
-		case 1: shift_x = scr_x * out_pos;		break;
-		case 2: shift_x = scr_x * ( ioc_d + pFont->SizeOf_(m_cur_cmd.c_str()) + d1 );	break;
-		case 3: shift_x = scr_x * str_length;	break;
-		}
-
-		vecTipsEx::iterator itb = m_tips.begin() + m_start_tip;
-		vecTipsEx::iterator ite = m_tips.end();
-		for ( u32 i = 0; itb != ite ; ++itb, ++i ) // tips
-		{
-			pFont->OutI( -1.0f + shift_x, fMaxY + i*LDIST, "%s", (*itb).text.c_str() );
-			if ( i >= VIEW_TIPS_COUNT-1 )
-			{
-				break; //for
-			}
-		}	
-	}
-
-	// ===== ==============================================
-	pFont->SetColor ( cmd_font_color );
-	pFont2->SetColor( cmd_font_color );
-
-	pFont->OutI(  -1.0f + out_pos * scr_x, ypos, "%s", s_b_mark );		out_pos += pFont->SizeOf_(s_b_mark);
-	pFont2->OutI( -1.0f + out_pos * scr_x, ypos, "%s", s_mark );		out_pos += pFont2->SizeOf_(s_mark);
-	pFont->OutI(  -1.0f + out_pos * scr_x, ypos, "%s", s_mark_a );
-
-	//pFont2->OutI( -1.0f + ioc_d * scr_x, ypos, "%s", editor=all );
-	
-	if( ec().cursor_view() )
-	{
-		pFont->SetColor( cursor_font_color );
-		pFont->OutI( -1.0f + str_length * scr_x, ypos, "%s", ch_cursor );
-	}
-	
-	// ---------------------
-	u32 log_line = LogFile->size()-1;
-	ypos -= LDIST;
-	for( int i = log_line - scroll_delta; i >= 0; --i ) 
-	{
-		ypos -= LDIST;
-		if ( ypos < -1.0f )
-		{
-			break;
-		}
-		LPCSTR ls = ((*LogFile)[i]).c_str();
-		
-		if ( !ls )
-		{
-			continue;
-		}
-		Console_mark cm = (Console_mark)ls[0];
-		pFont->SetColor( get_mark_color( cm ) );
-		//u8 b = (is_mark( cm ))? 2 : 0;
-		//OutFont( ls + b, ypos );
-		OutFont( ls, ypos );
-	}
-	
-	string16 q;
-	itoa( log_line, q, 10 );
-	u32 qn = xr_strlen( q );
-	pFont->SetColor( total_font_color );
-	pFont->OutI( 0.95f - 0.03f * qn, fMaxY - 2.0f * LDIST, "[%d]", log_line );
-		
-	pFont->OnRender();
-	pFont2->OnRender();
+    if (!bVisible)
+    {
+        return;
+    }
+
+    if (!m_hShader_back)
+    {
+        m_hShader_back = xr_new< FactoryPtr >();
+        (*m_hShader_back)->create("hud\\default", "ui\\ui_console"); // "ui\\ui_empty"
+    }
+
+    if (!pFont)
+    {
+        pFont = xr_new("hud_font_di", CGameFont::fsDeviceIndependent);
+        pFont->SetHeightI(0.025f);
+    }
+    if (!pFont2)
+    {
+        pFont2 = xr_new("hud_font_di2", CGameFont::fsDeviceIndependent);
+        pFont2->SetHeightI(0.025f);
+    }
+
+    bool bGame = false;
+    if ((g_pGameLevel && g_pGameLevel->bReady) ||
+            (g_pGamePersistent && g_pGamePersistent->m_pMainMenu && g_pGamePersistent->m_pMainMenu->IsActive()))
+    {
+        bGame = true;
+    }
+    if (g_dedicated_server)
+    {
+        bGame = false;
+    }
+
+    DrawBackgrounds(bGame);
+
+    float fMaxY;
+    float dwMaxY = (float)Device.dwHeight;
+    // float dwMaxX=float(Device.dwWidth/2);
+    if (bGame)
+    {
+        fMaxY = 0.0f;
+        dwMaxY /= 2;
+    }
+    else
+    {
+        fMaxY = 1.0f;
+    }
+
+    float ypos = fMaxY - LDIST * 1.1f;
+    float scr_x = 1.0f / Device.fWidth_2;
+
+    //---------------------------------------------------------------------------------
+    float scr_width = 1.9f * Device.fWidth_2;
+    float ioc_d = pFont->SizeOf_(ioc_prompt);
+    float d1 = pFont->SizeOf_("_");
+
+    LPCSTR s_cursor = ec().str_before_cursor();
+    LPCSTR s_b_mark = ec().str_before_mark();
+    LPCSTR s_mark = ec().str_mark();
+    LPCSTR s_mark_a = ec().str_after_mark();
+
+    // strncpy_s( buf1, cur_pos, editor, MAX_LEN );
+    float str_length = ioc_d + pFont->SizeOf_(s_cursor);
+    float out_pos = 0.0f;
+    if (str_length > scr_width)
+    {
+        out_pos -= (str_length - scr_width);
+        str_length = scr_width;
+    }
+
+    pFont->SetColor(prompt_font_color);
+    pFont->OutI(-1.0f + out_pos * scr_x, ypos, "%s", ioc_prompt);
+    out_pos += ioc_d;
+
+    if (!m_disable_tips && m_tips.size())
+    {
+        pFont->SetColor(tips_font_color);
+
+        float shift_x = 0.0f;
+        switch (m_tips_mode)
+        {
+        case 0:
+            shift_x = scr_x * 1.0f;
+            break;
+        case 1:
+            shift_x = scr_x * out_pos;
+            break;
+        case 2:
+            shift_x = scr_x * (ioc_d + pFont->SizeOf_(m_cur_cmd.c_str()) + d1);
+            break;
+        case 3:
+            shift_x = scr_x * str_length;
+            break;
+        }
+
+        vecTipsEx::iterator itb = m_tips.begin() + m_start_tip;
+        vecTipsEx::iterator ite = m_tips.end();
+        for (u32 i = 0; itb != ite; ++itb, ++i) // tips
+        {
+            pFont->OutI(-1.0f + shift_x, fMaxY + i*LDIST, "%s", (*itb).text.c_str());
+            if (i >= VIEW_TIPS_COUNT - 1)
+            {
+                break; //for
+            }
+        }
+    }
+
+    // ===== ==============================================
+    pFont->SetColor(cmd_font_color);
+    pFont2->SetColor(cmd_font_color);
+
+    pFont->OutI(-1.0f + out_pos * scr_x, ypos, "%s", s_b_mark);
+    out_pos += pFont->SizeOf_(s_b_mark);
+    pFont2->OutI(-1.0f + out_pos * scr_x, ypos, "%s", s_mark);
+    out_pos += pFont2->SizeOf_(s_mark);
+    pFont->OutI(-1.0f + out_pos * scr_x, ypos, "%s", s_mark_a);
+
+    //pFont2->OutI( -1.0f + ioc_d * scr_x, ypos, "%s", editor=all );
+
+    if (ec().cursor_view())
+    {
+        pFont->SetColor(cursor_font_color);
+        pFont->OutI(-1.0f + str_length * scr_x, ypos, "%s", ch_cursor);
+    }
+
+    // ---------------------
+    u32 log_line = LogFile->size() - 1;
+    ypos -= LDIST;
+    for (int i = log_line - scroll_delta; i >= 0; --i)
+    {
+        ypos -= LDIST;
+        if (ypos < -1.0f)
+        {
+            break;
+        }
+        LPCSTR ls = ((*LogFile)[i]).c_str();
+
+        if (!ls)
+        {
+            continue;
+        }
+        Console_mark cm = (Console_mark)ls[0];
+        pFont->SetColor(get_mark_color(cm));
+        //u8 b = (is_mark( cm ))? 2 : 0;
+        //OutFont( ls + b, ypos );
+        OutFont(ls, ypos);
+    }
+
+    string16 q;
+    itoa(log_line, q, 10);
+    u32 qn = xr_strlen(q);
+    pFont->SetColor(total_font_color);
+    pFont->OutI(0.95f - 0.03f * qn, fMaxY - 2.0f * LDIST, "[%d]", log_line);
+
+    pFont->OnRender();
+    pFont2->OnRender();
 }
 
-void CConsole::DrawBackgrounds( bool bGame )
+void CConsole::DrawBackgrounds(bool bGame)
 {
-	float ky = (bGame)? 0.5f : 1.0f;
-
-	Frect r;
-	r.set( 0.0f, 0.0f, float(Device.dwWidth), ky * float(Device.dwHeight) );
-
-	UIRender->SetShader( **m_hShader_back );
-	// 6 = back, 12 = tips, (VIEW_TIPS_COUNT+1)*6 = highlight_words, 12 = scroll
-	UIRender->StartPrimitive( 6 + 12 + (VIEW_TIPS_COUNT+1)*6 + 12, IUIRender::ptTriList, IUIRender::pttTL );
-
-	DrawRect( r, back_color );
-
-	if ( m_tips.size() == 0 || m_disable_tips )
-	{
-		UIRender->FlushPrimitive();
-		return;
-	}
-
-	LPCSTR max_str = "xxxxx";
-	vecTipsEx::iterator itb = m_tips.begin();
-	vecTipsEx::iterator ite = m_tips.end();
-	for ( ; itb != ite; ++itb )
-	{
-		if ( pFont->SizeOf_( (*itb).text.c_str() ) > pFont->SizeOf_( max_str ) )
-		{
-			max_str = (*itb).text.c_str();
-		}
-	}
-
-	float w1        = pFont->SizeOf_( "_" );
-	float ioc_w     = pFont->SizeOf_( ioc_prompt ) - w1;
-	float cur_cmd_w = pFont->SizeOf_( m_cur_cmd.c_str() );
-	cur_cmd_w		+= (cur_cmd_w > 0.01f) ? w1 : 0.0f;
-
-	float list_w    = pFont->SizeOf_( max_str ) + 2.0f * w1;
-
-	float font_h    = pFont->CurrentHeight_();
-	float tips_h    = _min( m_tips.size(), (u32)VIEW_TIPS_COUNT ) * font_h;
-	tips_h			+= ( m_tips.size() > 0 )? 5.0f : 0.0f;
-
-	Frect pr, sr;
-	pr.x1 = ioc_w + cur_cmd_w;
-	pr.x2 = pr.x1 + list_w;
-
-	pr.y1 = UI_BASE_HEIGHT * 0.5f;
-	pr.y1 *= float(Device.dwHeight)/UI_BASE_HEIGHT;
-
-	pr.y2 = pr.y1 + tips_h;
-
-	float select_y = 0.0f;
-	float select_h = 0.0f;
-	
-	if ( m_select_tip >= 0 && m_select_tip < (int)m_tips.size() )
-	{
-		int sel_pos = m_select_tip - m_start_tip;
-
-		select_y = sel_pos * font_h;
-		select_h = font_h; //1 string
-	}
-	
-	sr.x1 = pr.x1;
-	sr.y1 = pr.y1 + select_y;
-
-	sr.x2 = pr.x2;
-	sr.y2 = sr.y1 + select_h;
-
-	DrawRect( pr, tips_back_color );
-	DrawRect( sr, tips_select_color );
-
-	// --------------------------- highlight words --------------------
-
-	if ( m_select_tip < (int)m_tips.size() )
-	{
-		Frect r;
+    float ky = (bGame) ? 0.5f : 1.0f;
+
+    Frect r;
+    r.set(0.0f, 0.0f, float(Device.dwWidth), ky * float(Device.dwHeight));
+
+    UIRender->SetShader(**m_hShader_back);
+    // 6 = back, 12 = tips, (VIEW_TIPS_COUNT+1)*6 = highlight_words, 12 = scroll
+    UIRender->StartPrimitive(6 + 12 + (VIEW_TIPS_COUNT + 1) * 6 + 12, IUIRender::ptTriList, IUIRender::pttTL);
+
+    DrawRect(r, back_color);
+
+    if (m_tips.size() == 0 || m_disable_tips)
+    {
+        UIRender->FlushPrimitive();
+        return;
+    }
+
+    LPCSTR max_str = "xxxxx";
+    vecTipsEx::iterator itb = m_tips.begin();
+    vecTipsEx::iterator ite = m_tips.end();
+    for (; itb != ite; ++itb)
+    {
+        if (pFont->SizeOf_((*itb).text.c_str()) > pFont->SizeOf_(max_str))
+        {
+            max_str = (*itb).text.c_str();
+        }
+    }
+
+    float w1 = pFont->SizeOf_("_");
+    float ioc_w = pFont->SizeOf_(ioc_prompt) - w1;
+    float cur_cmd_w = pFont->SizeOf_(m_cur_cmd.c_str());
+    cur_cmd_w += (cur_cmd_w > 0.01f) ? w1 : 0.0f;
+
+    float list_w = pFont->SizeOf_(max_str) + 2.0f * w1;
+
+    float font_h = pFont->CurrentHeight_();
+    float tips_h = _min(m_tips.size(), (u32)VIEW_TIPS_COUNT) * font_h;
+    tips_h += (m_tips.size() > 0) ? 5.0f : 0.0f;
+
+    Frect pr, sr;
+    pr.x1 = ioc_w + cur_cmd_w;
+    pr.x2 = pr.x1 + list_w;
+
+    pr.y1 = UI_BASE_HEIGHT * 0.5f;
+    pr.y1 *= float(Device.dwHeight) / UI_BASE_HEIGHT;
+
+    pr.y2 = pr.y1 + tips_h;
+
+    float select_y = 0.0f;
+    float select_h = 0.0f;
+
+    if (m_select_tip >= 0 && m_select_tip < (int)m_tips.size())
+    {
+        int sel_pos = m_select_tip - m_start_tip;
+
+        select_y = sel_pos * font_h;
+        select_h = font_h; //1 string
+    }
+
+    sr.x1 = pr.x1;
+    sr.y1 = pr.y1 + select_y;
+
+    sr.x2 = pr.x2;
+    sr.y2 = sr.y1 + select_h;
+
+    DrawRect(pr, tips_back_color);
+    DrawRect(sr, tips_select_color);
+
+    // --------------------------- highlight words --------------------
+
+    if (m_select_tip < (int)m_tips.size())
+    {
+        Frect r;
         xr_string tmp;
-		vecTipsEx::iterator itb = m_tips.begin() + m_start_tip;
-		vecTipsEx::iterator ite = m_tips.end();
-		for ( u32 i = 0; itb != ite; ++itb, ++i ) // tips
-		{
-			TipString const& ts = (*itb);
-			if ( (ts.HL_start < 0) || (ts.HL_finish < 0) || (ts.HL_start > ts.HL_finish) )
-			{
-				continue;
-			}
-			int    str_size = (int)ts.text.size();
-			if ( (ts.HL_start >= str_size) || (ts.HL_finish > str_size) )
-			{
-				continue;
-			}
-
-			r.null();
+        vecTipsEx::iterator itb = m_tips.begin() + m_start_tip;
+        vecTipsEx::iterator ite = m_tips.end();
+        for (u32 i = 0; itb != ite; ++itb, ++i) // tips
+        {
+            TipString const& ts = (*itb);
+            if ((ts.HL_start < 0) || (ts.HL_finish < 0) || (ts.HL_start > ts.HL_finish))
+            {
+                continue;
+            }
+            int str_size = (int)ts.text.size();
+            if ((ts.HL_start >= str_size) || (ts.HL_finish > str_size))
+            {
+                continue;
+            }
+
+            r.null();
             tmp.assign(ts.text.c_str(), ts.HL_start);
-			r.x1 = pr.x1 + w1 + pFont->SizeOf_( tmp.c_str() );
-			r.y1 = pr.y1 + i * font_h;
-
-			tmp.assign(ts.text.c_str(), ts.HL_finish);
-			r.x2 = pr.x1 + w1 + pFont->SizeOf_( tmp.c_str() );
-			r.y2 = r.y1 + font_h;
-
-			DrawRect( r, tips_word_color );
-
-			if ( i >= VIEW_TIPS_COUNT-1 )
-			{
-				break; // for itb
-			}
-		}// for itb
-	} // if
-
-	// --------------------------- scroll bar --------------------
-
-	u32 tips_sz = m_tips.size();
-	if ( tips_sz > VIEW_TIPS_COUNT )
-	{
-		Frect rb, rs;
-		
-		rb.x1 = pr.x2;
-		rb.y1 = pr.y1;
-		rb.x2 = rb.x1 + 2 * w1;
-		rb.y2 = pr.y2;
-		DrawRect( rb, tips_scroll_back_color );
-
-		VERIFY( rb.y2 - rb.y1 >= 1.0f );
-		float back_height = rb.y2 - rb.y1;
-		float u_height = (back_height * VIEW_TIPS_COUNT)/ float(tips_sz);
-		if ( u_height < 0.5f * font_h )
-		{
-			u_height = 0.5f * font_h;
-		}
-
-		//float u_pos = (back_height - u_height) * float(m_start_tip) / float(tips_sz);
-		float u_pos = back_height * float(m_start_tip) / float(tips_sz);
-		
-		//clamp( u_pos, 0.0f, back_height - u_height );
-		
-		rs = rb;
-		rs.y1 = pr.y1 + u_pos;
-		rs.y2 = rs.y1 + u_height;
-		DrawRect( rs, tips_scroll_pos_color );
-	}
-
-	UIRender->FlushPrimitive();
+            r.x1 = pr.x1 + w1 + pFont->SizeOf_(tmp.c_str());
+            r.y1 = pr.y1 + i * font_h;
+
+            tmp.assign(ts.text.c_str(), ts.HL_finish);
+            r.x2 = pr.x1 + w1 + pFont->SizeOf_(tmp.c_str());
+            r.y2 = r.y1 + font_h;
+
+            DrawRect(r, tips_word_color);
+
+            if (i >= VIEW_TIPS_COUNT - 1)
+            {
+                break; // for itb
+            }
+        }// for itb
+    } // if
+
+    // --------------------------- scroll bar --------------------
+
+    u32 tips_sz = m_tips.size();
+    if (tips_sz > VIEW_TIPS_COUNT)
+    {
+        Frect rb, rs;
+
+        rb.x1 = pr.x2;
+        rb.y1 = pr.y1;
+        rb.x2 = rb.x1 + 2 * w1;
+        rb.y2 = pr.y2;
+        DrawRect(rb, tips_scroll_back_color);
+
+        VERIFY(rb.y2 - rb.y1 >= 1.0f);
+        float back_height = rb.y2 - rb.y1;
+        float u_height = (back_height * VIEW_TIPS_COUNT) / float(tips_sz);
+        if (u_height < 0.5f * font_h)
+        {
+            u_height = 0.5f * font_h;
+        }
+
+        //float u_pos = (back_height - u_height) * float(m_start_tip) / float(tips_sz);
+        float u_pos = back_height * float(m_start_tip) / float(tips_sz);
+
+        //clamp( u_pos, 0.0f, back_height - u_height );
+
+        rs = rb;
+        rs.y1 = pr.y1 + u_pos;
+        rs.y2 = rs.y1 + u_height;
+        DrawRect(rs, tips_scroll_pos_color);
+    }
+
+    UIRender->FlushPrimitive();
 }
 
-void CConsole::DrawRect( Frect const& r, u32 color )
+void CConsole::DrawRect(Frect const& r, u32 color)
 {
-	UIRender->PushPoint( r.x1, r.y1, 0.0f, color, 0.0f, 0.0f );
-	UIRender->PushPoint( r.x2, r.y1, 0.0f, color, 1.0f, 0.0f );
-	UIRender->PushPoint( r.x2, r.y2, 0.0f, color, 1.0f, 1.0f );
+    UIRender->PushPoint(r.x1, r.y1, 0.0f, color, 0.0f, 0.0f);
+    UIRender->PushPoint(r.x2, r.y1, 0.0f, color, 1.0f, 0.0f);
+    UIRender->PushPoint(r.x2, r.y2, 0.0f, color, 1.0f, 1.0f);
 
-	UIRender->PushPoint( r.x1, r.y1, 0.0f, color, 0.0f, 0.0f );
-	UIRender->PushPoint( r.x2, r.y2, 0.0f, color, 1.0f, 1.0f );
-	UIRender->PushPoint( r.x1, r.y2, 0.0f, color, 0.0f, 1.0f );
+    UIRender->PushPoint(r.x1, r.y1, 0.0f, color, 0.0f, 0.0f);
+    UIRender->PushPoint(r.x2, r.y2, 0.0f, color, 1.0f, 1.0f);
+    UIRender->PushPoint(r.x1, r.y2, 0.0f, color, 0.0f, 1.0f);
 }
 
-void CConsole::ExecuteCommand( LPCSTR cmd_str, bool record_cmd )
+void CConsole::ExecuteCommand(LPCSTR cmd_str, bool record_cmd)
 {
-	u32  str_size = xr_strlen( cmd_str );
-	PSTR edt   = (PSTR)_alloca( (str_size + 1) * sizeof(char) );
-	PSTR first = (PSTR)_alloca( (str_size + 1) * sizeof(char) );
-	PSTR last  = (PSTR)_alloca( (str_size + 1) * sizeof(char) );
-	
-	xr_strcpy( edt, str_size+1, cmd_str );
-	edt[str_size] = 0;
-
-	scroll_delta	= 0;
-	reset_cmd_history_idx();
-	reset_selected_tip();
-
-	text_editor::remove_spaces( edt );
-	if ( edt[0] == 0 )
-	{
-		return;
-	}
-	if ( record_cmd )
-	{
-		char c[2];
-		c[0] = mark2;
-		c[1] = 0;
-
-		if ( m_last_cmd.c_str() == 0 || xr_strcmp( m_last_cmd, edt ) != 0 )
-		{
-			Log( c, edt );
-			add_cmd_history( edt );
-			m_last_cmd = edt;
-		}
-	}
-	text_editor::split_cmd( first, last, edt );
-
-	// search
-	vecCMD_IT it = Commands.find( first );
-	if ( it != Commands.end() )
-	{
-		IConsole_Command* cc = it->second;
-		if ( cc && cc->bEnabled )
-		{
-			if ( cc->bLowerCaseArgs )
-			{
-				strlwr( last );
-			}
-			if ( last[0] == 0 )
-			{
-				if ( cc->bEmptyArgsHandled )
-				{
-					cc->Execute( last );
-				}
-				else
-				{
-					IConsole_Command::TStatus stat;
-					cc->Status( stat );
-					Msg( "- %s %s", cc->Name(), stat );
-				}
-			}
-			else
-			{
-				cc->Execute( last );
-				if ( record_cmd )
-				{
-					cc->add_to_LRU( (LPCSTR)last );
-				}
-			}
-		}
-		else
-		{
-			Log("! Command disabled.");
-		}
-	}
-	else
-	{
-		Log( "! Unknown command: ", first );
-	}
-
-	if ( record_cmd )
-	{
-		ec().clear_states();
-	}
+    u32 str_size = xr_strlen(cmd_str);
+    PSTR edt = (PSTR)_alloca((str_size + 1) * sizeof(char));
+    PSTR first = (PSTR)_alloca((str_size + 1) * sizeof(char));
+    PSTR last = (PSTR)_alloca((str_size + 1) * sizeof(char));
+
+    xr_strcpy(edt, str_size + 1, cmd_str);
+    edt[str_size] = 0;
+
+    scroll_delta = 0;
+    reset_cmd_history_idx();
+    reset_selected_tip();
+
+    text_editor::remove_spaces(edt);
+    if (edt[0] == 0)
+    {
+        return;
+    }
+    if (record_cmd)
+    {
+        char c[2];
+        c[0] = mark2;
+        c[1] = 0;
+
+        if (m_last_cmd.c_str() == 0 || xr_strcmp(m_last_cmd, edt) != 0)
+        {
+            Log(c, edt);
+            add_cmd_history(edt);
+            m_last_cmd = edt;
+        }
+    }
+    text_editor::split_cmd(first, last, edt);
+
+    // search
+    vecCMD_IT it = Commands.find(first);
+    if (it != Commands.end())
+    {
+        IConsole_Command* cc = it->second;
+        if (cc && cc->bEnabled)
+        {
+            if (cc->bLowerCaseArgs)
+            {
+                strlwr(last);
+            }
+            if (last[0] == 0)
+            {
+                if (cc->bEmptyArgsHandled)
+                {
+                    cc->Execute(last);
+                }
+                else
+                {
+                    IConsole_Command::TStatus stat;
+                    cc->Status(stat);
+                    Msg("- %s %s", cc->Name(), stat);
+                }
+            }
+            else
+            {
+                cc->Execute(last);
+                if (record_cmd)
+                {
+                    cc->add_to_LRU((LPCSTR)last);
+                }
+            }
+        }
+        else
+        {
+            Log("! Command disabled.");
+        }
+    }
+    else
+    {
+        Log("! Unknown command: ", first);
+    }
+
+    if (record_cmd)
+    {
+        ec().clear_states();
+    }
 }
 
 void CConsole::Show()
 {
-	SECUROM_MARKER_HIGH_SECURITY_ON(11)
-
-	if ( bVisible )
-	{
-		return;
-	}
-	bVisible = true;
-	
-	GetCursorPos( &m_mouse_pos );
-
-	ec().clear_states();
-	scroll_delta	= 0;
-	reset_cmd_history_idx();
-	reset_selected_tip();
-	update_tips();
-
-	m_editor->IR_Capture();
-	Device.seqRender.Add( this, 1 );
-	Device.seqFrame.Add( this );
-
-	SECUROM_MARKER_HIGH_SECURITY_OFF(11)
+    SECUROM_MARKER_HIGH_SECURITY_ON(11)
+
+    if (bVisible)
+    {
+        return;
+    }
+    bVisible = true;
+
+    GetCursorPos(&m_mouse_pos);
+
+    ec().clear_states();
+    scroll_delta = 0;
+    reset_cmd_history_idx();
+    reset_selected_tip();
+    update_tips();
+
+    m_editor->IR_Capture();
+    Device.seqRender.Add(this, 1);
+    Device.seqFrame.Add(this);
+
+    SECUROM_MARKER_HIGH_SECURITY_OFF(11)
 }
 
 extern CInput* pInput;
 
 void CConsole::Hide()
 {
-	if ( !bVisible )
-	{
-		return;
-	}
-	if ( g_pGamePersistent && g_dedicated_server )
-	{
-		return;
-	}
-//	if  ( g_pGameLevel || 
-//		( g_pGamePersistent && g_pGamePersistent->m_pMainMenu && g_pGamePersistent->m_pMainMenu->IsActive() ))
-
-	if ( pInput->get_exclusive_mode() )
-	{
-		SetCursorPos( m_mouse_pos.x, m_mouse_pos.y );
-	}
-
-	bVisible = false;
-	reset_selected_tip();
-	update_tips();
-
-	Device.seqFrame.Remove( this );
-	Device.seqRender.Remove( this );
-	m_editor->IR_Release();
+    if (!bVisible)
+    {
+        return;
+    }
+    if (g_pGamePersistent && g_dedicated_server)
+    {
+        return;
+    }
+    // if ( g_pGameLevel ||
+    // ( g_pGamePersistent && g_pGamePersistent->m_pMainMenu && g_pGamePersistent->m_pMainMenu->IsActive() ))
+
+    if (pInput->get_exclusive_mode())
+    {
+        SetCursorPos(m_mouse_pos.x, m_mouse_pos.y);
+    }
+
+    bVisible = false;
+    reset_selected_tip();
+    update_tips();
+
+    Device.seqFrame.Remove(this);
+    Device.seqRender.Remove(this);
+    m_editor->IR_Release();
 }
 
 void CConsole::SelectCommand()
 {
-	if ( m_cmd_history.empty() )
-	{
-		return;
-	}
-	VERIFY( 0 <= m_cmd_history_idx && m_cmd_history_idx < (int)m_cmd_history.size() );
-		
-	vecHistory::reverse_iterator	it_rb = m_cmd_history.rbegin() + m_cmd_history_idx;
-	ec().set_edit( (*it_rb).c_str() );
-	reset_selected_tip();
+    if (m_cmd_history.empty())
+    {
+        return;
+    }
+    VERIFY(0 <= m_cmd_history_idx && m_cmd_history_idx < (int)m_cmd_history.size());
+
+    vecHistory::reverse_iterator it_rb = m_cmd_history.rbegin() + m_cmd_history_idx;
+    ec().set_edit((*it_rb).c_str());
+    reset_selected_tip();
 }
 
-void CConsole::Execute( LPCSTR cmd )
+void CConsole::Execute(LPCSTR cmd)
 {
-	ExecuteCommand( cmd, false );
+    ExecuteCommand(cmd, false);
 }
 
-void CConsole::ExecuteScript( LPCSTR str )
+void CConsole::ExecuteScript(LPCSTR str)
 {
-	u32  str_size = xr_strlen( str );
-	PSTR buf = (PSTR)_alloca( (str_size + 10) * sizeof(char) );
-	xr_strcpy( buf, str_size + 10, "cfg_load " );
-	xr_strcat( buf, str_size + 10, str );
-	Execute( buf );
+    u32 str_size = xr_strlen(str);
+    PSTR buf = (PSTR)_alloca((str_size + 10) * sizeof(char));
+    xr_strcpy(buf, str_size + 10, "cfg_load ");
+    xr_strcat(buf, str_size + 10, str);
+    Execute(buf);
 }
 
 // -------------------------------------------------------------------------------------------------
 
-IConsole_Command* CConsole::find_next_cmd( LPCSTR in_str, shared_str& out_str )
+IConsole_Command* CConsole::find_next_cmd(LPCSTR in_str, shared_str& out_str)
 {
-	LPCSTR radmin_cmd_name = "ra ";
-	bool b_ra  = (in_str == strstr( in_str, radmin_cmd_name ) );
-	u32 offset = (b_ra)? xr_strlen( radmin_cmd_name ) : 0;
-
-	LPSTR t2;
-	STRCONCAT( t2, in_str + offset, " " );
-
-	vecCMD_IT it = Commands.lower_bound( t2 );
-	if ( it != Commands.end() )
-	{
-		IConsole_Command* cc = it->second;
-		LPCSTR name_cmd      = cc->Name();
-		u32    name_cmd_size = xr_strlen( name_cmd );
-		PSTR   new_str       = (PSTR)_alloca( (offset + name_cmd_size + 2) * sizeof(char) );
-
-		xr_strcpy( new_str, offset + name_cmd_size + 2, (b_ra)? radmin_cmd_name : "" );
-		xr_strcat( new_str, offset + name_cmd_size + 2, name_cmd );
-
-		out_str._set( (LPCSTR)new_str );
-		return cc;
-	}
-	return NULL;
+    LPCSTR radmin_cmd_name = "ra ";
+    bool b_ra = (in_str == strstr(in_str, radmin_cmd_name));
+    u32 offset = (b_ra) ? xr_strlen(radmin_cmd_name) : 0;
+
+    LPSTR t2;
+    STRCONCAT(t2, in_str + offset, " ");
+
+    vecCMD_IT it = Commands.lower_bound(t2);
+    if (it != Commands.end())
+    {
+        IConsole_Command* cc = it->second;
+        LPCSTR name_cmd = cc->Name();
+        u32 name_cmd_size = xr_strlen(name_cmd);
+        PSTR new_str = (PSTR)_alloca((offset + name_cmd_size + 2) * sizeof(char));
+
+        xr_strcpy(new_str, offset + name_cmd_size + 2, (b_ra) ? radmin_cmd_name : "");
+        xr_strcat(new_str, offset + name_cmd_size + 2, name_cmd);
+
+        out_str._set((LPCSTR)new_str);
+        return cc;
+    }
+    return NULL;
 }
 
-bool CConsole::add_next_cmds( LPCSTR in_str, vecTipsEx& out_v )
+bool CConsole::add_next_cmds(LPCSTR in_str, vecTipsEx& out_v)
 {
-	u32 cur_count = out_v.size();
-	if ( cur_count >= MAX_TIPS_COUNT )
-	{
-		return false;
-	}
-
-	LPSTR t2;
-	STRCONCAT( t2, in_str, " " );
-
-	shared_str temp;
-	IConsole_Command* cc = find_next_cmd( t2, temp );
-	if ( !cc || temp.size() == 0 )
-	{
-		return false;
-	}
-
-	bool res = false;
-	for ( u32 i = cur_count; i < MAX_TIPS_COUNT*2; ++i ) //fake=protect
-	{
-		temp._set( cc->Name() );
-		bool dup = ( std::find( out_v.begin(), out_v.end(), temp ) != out_v.end() );
-		if ( !dup )
-		{
-			TipString ts( temp );
-			out_v.push_back( ts );
-			res = true;
-		}
-		if ( out_v.size() >= MAX_TIPS_COUNT )
-		{
-			break; // for
-		}
-		LPSTR t3;
-		STRCONCAT( t3, out_v.back().text.c_str(), " " );
-		cc = find_next_cmd( t3, temp );
-		if ( !cc )
-		{
-			break; // for
-		}
-	} // for
-	return res;
+    u32 cur_count = out_v.size();
+    if (cur_count >= MAX_TIPS_COUNT)
+    {
+        return false;
+    }
+
+    LPSTR t2;
+    STRCONCAT(t2, in_str, " ");
+
+    shared_str temp;
+    IConsole_Command* cc = find_next_cmd(t2, temp);
+    if (!cc || temp.size() == 0)
+    {
+        return false;
+    }
+
+    bool res = false;
+    for (u32 i = cur_count; i < MAX_TIPS_COUNT * 2; ++i) //fake=protect
+    {
+        temp._set(cc->Name());
+        bool dup = (std::find(out_v.begin(), out_v.end(), temp) != out_v.end());
+        if (!dup)
+        {
+            TipString ts(temp);
+            out_v.push_back(ts);
+            res = true;
+        }
+        if (out_v.size() >= MAX_TIPS_COUNT)
+        {
+            break; // for
+        }
+        LPSTR t3;
+        STRCONCAT(t3, out_v.back().text.c_str(), " ");
+        cc = find_next_cmd(t3, temp);
+        if (!cc)
+        {
+            break; // for
+        }
+    } // for
+    return res;
 }
 
-bool CConsole::add_internal_cmds( LPCSTR in_str, vecTipsEx& out_v )
+bool CConsole::add_internal_cmds(LPCSTR in_str, vecTipsEx& out_v)
 {
-	u32 cur_count = out_v.size();
-	if ( cur_count >= MAX_TIPS_COUNT )
-	{
-		return false;
-	}
-	u32   in_sz = xr_strlen(in_str);
-	
-	bool res = false;
-	// word in begin
+    u32 cur_count = out_v.size();
+    if (cur_count >= MAX_TIPS_COUNT)
+    {
+        return false;
+    }
+    u32 in_sz = xr_strlen(in_str);
+
+    bool res = false;
+    // word in begin
     xr_string name2;
-	vecCMD_IT itb = Commands.begin();
-	vecCMD_IT ite = Commands.end();
-	for ( ; itb != ite; ++itb )
-	{
-		LPCSTR name = itb->first;
-		u32 name_sz = xr_strlen(name);
-		if ( name_sz >= in_sz )
-		{
+    vecCMD_IT itb = Commands.begin();
+    vecCMD_IT ite = Commands.end();
+    for (; itb != ite; ++itb)
+    {
+        LPCSTR name = itb->first;
+        u32 name_sz = xr_strlen(name);
+        if (name_sz >= in_sz)
+        {
             name2.assign(name, in_sz);
-			if ( !stricmp( name2.c_str(), in_str ) )
-			{
-				shared_str temp;
-				temp._set( name );
-				bool dup = ( std::find( out_v.begin(), out_v.end(), temp ) != out_v.end() );
-				if ( !dup )
-				{
-					out_v.push_back( TipString( temp, 0, in_sz ) );
-					res = true;
-				}
-			}
-		}
-
-		if ( out_v.size() >= MAX_TIPS_COUNT )
-		{
-			return res;
-		}
-	} // for
-
-	// word in internal
-	itb = Commands.begin();
-	ite = Commands.end();
-	for ( ; itb != ite; ++itb )
-	{
-		LPCSTR name = itb->first;
-		LPCSTR fd_str = strstr( name, in_str );
-		if ( fd_str )
-		{
-			shared_str temp;
-			temp._set( name );
-			bool dup = ( std::find( out_v.begin(), out_v.end(), temp ) != out_v.end() );
-			if ( !dup )
-			{
-				u32 name_sz = xr_strlen( name );
-				int   fd_sz = name_sz - xr_strlen( fd_str );
-				out_v.push_back( TipString( temp, fd_sz, fd_sz + in_sz ) );
-				res = true;
-			}
-		}
-		if ( out_v.size() >= MAX_TIPS_COUNT )
-		{
-			return res;
-		}
-	} // for
-
-	return res;
+            if (!stricmp(name2.c_str(), in_str))
+            {
+                shared_str temp;
+                temp._set(name);
+                bool dup = (std::find(out_v.begin(), out_v.end(), temp) != out_v.end());
+                if (!dup)
+                {
+                    out_v.push_back(TipString(temp, 0, in_sz));
+                    res = true;
+                }
+            }
+        }
+
+        if (out_v.size() >= MAX_TIPS_COUNT)
+        {
+            return res;
+        }
+    } // for
+
+    // word in internal
+    itb = Commands.begin();
+    ite = Commands.end();
+    for (; itb != ite; ++itb)
+    {
+        LPCSTR name = itb->first;
+        LPCSTR fd_str = strstr(name, in_str);
+        if (fd_str)
+        {
+            shared_str temp;
+            temp._set(name);
+            bool dup = (std::find(out_v.begin(), out_v.end(), temp) != out_v.end());
+            if (!dup)
+            {
+                u32 name_sz = xr_strlen(name);
+                int fd_sz = name_sz - xr_strlen(fd_str);
+                out_v.push_back(TipString(temp, fd_sz, fd_sz + in_sz));
+                res = true;
+            }
+        }
+        if (out_v.size() >= MAX_TIPS_COUNT)
+        {
+            return res;
+        }
+    } // for
+
+    return res;
 }
 
 void CConsole::update_tips()
 {
-	m_temp_tips.clear_not_free();
-	m_tips.clear_not_free();
-
-	m_cur_cmd  = NULL;
-	if ( !bVisible )
-	{
-		return;
-	}
-
-	LPCSTR cur = ec().str_edit();
-	u32    cur_length = xr_strlen( cur );
-
-	if ( cur_length == 0 )
-	{
-		m_prev_length_str = 0;
-		return;
-	}
-	
-	if ( m_prev_length_str != cur_length )
-	{
-		reset_selected_tip();
-	}
-	m_prev_length_str = cur_length;
-
-	PSTR first = (PSTR)_alloca( (cur_length + 1) * sizeof(char) );
-	PSTR last  = (PSTR)_alloca( (cur_length + 1) * sizeof(char) );
-	text_editor::split_cmd( first, last, cur );
-	
-	u32 first_lenght = xr_strlen(first);
-	
-	if ( (first_lenght > 2) && (first_lenght + 1 <= cur_length) ) // param
-	{
-		if ( cur[first_lenght] == ' ' )
-		{
-			if ( m_tips_mode != 2 )
-			{
-				reset_selected_tip();
-			}
-
-			vecCMD_IT it = Commands.find( first );
-			if ( it != Commands.end() )
-			{
-				IConsole_Command* cc = it->second;
-				
-				u32 mode = 0;
-				if ( (first_lenght + 2 <= cur_length) && (cur[first_lenght] == ' ') && (cur[first_lenght+1] == ' ') )
-				{
-					mode = 1;
-					last += 1; // fake: next char
-				}
-
-				cc->fill_tips( m_temp_tips, mode );
-				m_tips_mode = 2;
-				m_cur_cmd._set( first );
-				select_for_filter( last, m_temp_tips, m_tips );
-
-				if ( m_tips.size() == 0 )
-				{
-					m_tips.push_back( TipString( "(empty)" ) );
-				}
-				if ( (int)m_tips.size() <= m_select_tip )
-				{
-					reset_selected_tip();
-				}
-				return;
-			}
-		}
-	}
-
-	// cmd name
-	{
-		add_internal_cmds( cur, m_tips );
-		//add_next_cmds( cur, m_tips );
-		m_tips_mode = 1;
-	}
-
-	if ( m_tips.size() == 0 )
-	{
-		m_tips_mode = 0;
-		reset_selected_tip();
-	}
-	if ( (int)m_tips.size() <= m_select_tip )
-	{
-		reset_selected_tip();
-	}
+    m_temp_tips.clear_not_free();
+    m_tips.clear_not_free();
+
+    m_cur_cmd = NULL;
+    if (!bVisible)
+    {
+        return;
+    }
+
+    LPCSTR cur = ec().str_edit();
+    u32 cur_length = xr_strlen(cur);
+
+    if (cur_length == 0)
+    {
+        m_prev_length_str = 0;
+        return;
+    }
+
+    if (m_prev_length_str != cur_length)
+    {
+        reset_selected_tip();
+    }
+    m_prev_length_str = cur_length;
+
+    PSTR first = (PSTR)_alloca((cur_length + 1) * sizeof(char));
+    PSTR last = (PSTR)_alloca((cur_length + 1) * sizeof(char));
+    text_editor::split_cmd(first, last, cur);
+
+    u32 first_lenght = xr_strlen(first);
+
+    if ((first_lenght > 2) && (first_lenght + 1 <= cur_length)) // param
+    {
+        if (cur[first_lenght] == ' ')
+        {
+            if (m_tips_mode != 2)
+            {
+                reset_selected_tip();
+            }
+
+            vecCMD_IT it = Commands.find(first);
+            if (it != Commands.end())
+            {
+                IConsole_Command* cc = it->second;
+
+                u32 mode = 0;
+                if ((first_lenght + 2 <= cur_length) && (cur[first_lenght] == ' ') && (cur[first_lenght + 1] == ' '))
+                {
+                    mode = 1;
+                    last += 1; // fake: next char
+                }
+
+                cc->fill_tips(m_temp_tips, mode);
+                m_tips_mode = 2;
+                m_cur_cmd._set(first);
+                select_for_filter(last, m_temp_tips, m_tips);
+
+                if (m_tips.size() == 0)
+                {
+                    m_tips.push_back(TipString("(empty)"));
+                }
+                if ((int)m_tips.size() <= m_select_tip)
+                {
+                    reset_selected_tip();
+                }
+                return;
+            }
+        }
+    }
+
+    // cmd name
+    {
+        add_internal_cmds(cur, m_tips);
+        //add_next_cmds( cur, m_tips );
+        m_tips_mode = 1;
+    }
+
+    if (m_tips.size() == 0)
+    {
+        m_tips_mode = 0;
+        reset_selected_tip();
+    }
+    if ((int)m_tips.size() <= m_select_tip)
+    {
+        reset_selected_tip();
+    }
 
 }
 
-void CConsole::select_for_filter( LPCSTR filter_str, vecTips& in_v, vecTipsEx& out_v )
+void CConsole::select_for_filter(LPCSTR filter_str, vecTips& in_v, vecTipsEx& out_v)
 {
-	out_v.clear_not_free();
-	u32 in_count = in_v.size();
-	if ( in_count == 0 || !filter_str )
-	{
-		return;
-	}
-
-	bool all = ( xr_strlen(filter_str) == 0 );
-
-	vecTips::iterator itb = in_v.begin();
-	vecTips::iterator ite = in_v.end();
-	for ( ; itb != ite ; ++itb )
-	{
-		shared_str const& str = (*itb);
-		if ( all )
-		{
-			out_v.push_back( TipString( str ) );
-		}
-		else
-		{
-			LPCSTR fd_str = strstr( str.c_str(), filter_str );
-			if ( fd_str )
-			{
-				int   fd_sz = str.size() - xr_strlen( fd_str );
-				TipString ts( str, fd_sz, fd_sz + xr_strlen(filter_str) );
-				out_v.push_back( ts );
-			}
-		}
-	}//for
+    out_v.clear_not_free();
+    u32 in_count = in_v.size();
+    if (in_count == 0 || !filter_str)
+    {
+        return;
+    }
+
+    bool all = (xr_strlen(filter_str) == 0);
+
+    vecTips::iterator itb = in_v.begin();
+    vecTips::iterator ite = in_v.end();
+    for (; itb != ite; ++itb)
+    {
+        shared_str const& str = (*itb);
+        if (all)
+        {
+            out_v.push_back(TipString(str));
+        }
+        else
+        {
+            LPCSTR fd_str = strstr(str.c_str(), filter_str);
+            if (fd_str)
+            {
+                int fd_sz = str.size() - xr_strlen(fd_str);
+                TipString ts(str, fd_sz, fd_sz + xr_strlen(filter_str));
+                out_v.push_back(ts);
+            }
+        }
+    }//for
 }
diff --git a/src/xrEngine/XR_IOConsole.h b/src/xrEngine/XR_IOConsole.h
index ddf42c4803b..81060239cec 100644
--- a/src/xrEngine/XR_IOConsole.h
+++ b/src/xrEngine/XR_IOConsole.h
@@ -19,198 +19,198 @@ class line_edit_control;
 
 struct TipString
 {
-	shared_str	text;
-	int			HL_start; // Highlight
-	int			HL_finish;
-	
-	TipString()
-	{
-		text._set( "" );
-		HL_start = 0;
-		HL_finish = 0;
-	}
-	TipString( shared_str const& tips_text, int start_pos, int finish_pos )
-	{
-		text._set( tips_text );
-		HL_start = start_pos;
-		HL_finish = finish_pos;
-	}
-	TipString( LPCSTR tips_text, int start_pos, int finish_pos )
-	{
-		text._set( tips_text );
-		HL_start = start_pos;
-		HL_finish = finish_pos;
-	}
-	TipString( shared_str const& tips_text )
-	{
-		text._set( tips_text );
-		HL_start = 0;
-		HL_finish = 0;
-	}
-	IC bool operator== ( shared_str const& tips_text )
-	{
-		return ( text == tips_text );
-	}
+    shared_str text;
+    int HL_start; // Highlight
+    int HL_finish;
+
+    TipString()
+    {
+        text._set("");
+        HL_start = 0;
+        HL_finish = 0;
+    }
+    TipString(shared_str const& tips_text, int start_pos, int finish_pos)
+    {
+        text._set(tips_text);
+        HL_start = start_pos;
+        HL_finish = finish_pos;
+    }
+    TipString(LPCSTR tips_text, int start_pos, int finish_pos)
+    {
+        text._set(tips_text);
+        HL_start = start_pos;
+        HL_finish = finish_pos;
+    }
+    TipString(shared_str const& tips_text)
+    {
+        text._set(tips_text);
+        HL_start = 0;
+        HL_finish = 0;
+    }
+    IC bool operator== (shared_str const& tips_text)
+    {
+        return (text == tips_text);
+    }
 };
 
 class ENGINE_API CConsole :
-	public pureRender,
-	public pureFrame,
-	public pureScreenResolutionChanged
+    public pureRender,
+    public pureFrame,
+    public pureScreenResolutionChanged
 {
 public:
-	struct str_pred : public std::binary_function
-	{	
-		IC bool operator()(const char* x, const char* y) const
-		{
-			return (xr_strcmp( x, y ) < 0);
-		}
-	};
-	typedef  xr_map	vecCMD;
-	typedef  vecCMD::iterator							vecCMD_IT;
-	typedef  vecCMD::const_iterator						vecCMD_CIT;
-	typedef  fastdelegate::FastDelegate0			Callback;
-	typedef  xr_vector						vecHistory;
-	typedef  xr_vector						vecTips;
-	typedef  xr_vector						vecTipsEx;
-
-	enum			{ CONSOLE_BUF_SIZE = 1024 };
-	enum			{ VIEW_TIPS_COUNT = 14, MAX_TIPS_COUNT = 220 };
+    struct str_pred : public std::binary_function < char*, char*, bool >
+    {
+        IC bool operator()(const char* x, const char* y) const
+        {
+            return (xr_strcmp(x, y) < 0);
+        }
+    };
+    typedef xr_map vecCMD;
+    typedef vecCMD::iterator vecCMD_IT;
+    typedef vecCMD::const_iterator vecCMD_CIT;
+    typedef fastdelegate::FastDelegate0 Callback;
+    typedef xr_vector vecHistory;
+    typedef xr_vector vecTips;
+    typedef xr_vector vecTipsEx;
+
+    enum { CONSOLE_BUF_SIZE = 1024 };
+    enum { VIEW_TIPS_COUNT = 14, MAX_TIPS_COUNT = 220 };
 
 protected:
-	int				scroll_delta;
+    int scroll_delta;
 
-	CGameFont*		pFont;
-	CGameFont*		pFont2;
-	
-	FactoryPtr*		m_hShader_back;
+    CGameFont* pFont;
+    CGameFont* pFont2;
 
-	POINT			m_mouse_pos;
-	bool			m_disable_tips;
+    FactoryPtr* m_hShader_back;
+
+    POINT m_mouse_pos;
+    bool m_disable_tips;
 
 private:
-	vecHistory		m_cmd_history;
-	u32				m_cmd_history_max;
-	int				m_cmd_history_idx;
-	shared_str		m_last_cmd;
-	BENCH_SEC_SCRAMBLEMEMBER1
-
-	vecTips			m_temp_tips;
-	vecTipsEx		m_tips;
-	u32				m_tips_mode;
-	shared_str		m_cur_cmd;
-	int				m_select_tip;
-	int				m_start_tip;
-	u32				m_prev_length_str;
+    vecHistory m_cmd_history;
+    u32 m_cmd_history_max;
+    int m_cmd_history_idx;
+    shared_str m_last_cmd;
+    BENCH_SEC_SCRAMBLEMEMBER1
+
+    vecTips m_temp_tips;
+    vecTipsEx m_tips;
+    u32 m_tips_mode;
+    shared_str m_cur_cmd;
+    int m_select_tip;
+    int m_start_tip;
+    u32 m_prev_length_str;
 
 public:
-					CConsole			();
-	virtual			~CConsole			();
-	virtual	void	Initialize			();
-	virtual void	Destroy				();
-
-	virtual void		OnRender			();
-	virtual void _BCL	OnFrame				();
-	virtual void	OnScreenResolutionChanged();
-	string64		ConfigFile;
-	bool			bVisible;
-	vecCMD			Commands;
-
-	void			AddCommand			( IConsole_Command* cc );
-	void			RemoveCommand		( IConsole_Command* cc );
-
-	void			Show				();
-	void			Hide				();
-
-	void			Execute				( LPCSTR cmd );
-	void			ExecuteScript		( LPCSTR str );
-	void			ExecuteCommand		( LPCSTR cmd, bool record_cmd = true );
-	void			SelectCommand		();
-
-	bool			GetBool				( LPCSTR cmd ) const;
-	float			GetFloat			( LPCSTR cmd, float& min, float& max) const;
-	int				GetInteger			( LPCSTR cmd, int& min, int& max) const;
-	LPCSTR			GetString			( LPCSTR cmd ) const;
-	LPCSTR			GetToken			( LPCSTR cmd ) const;
-	xr_token*		GetXRToken			( LPCSTR cmd ) const;
-	Fvector			GetFVector			( LPCSTR cmd ) const;
-	Fvector*		GetFVectorPtr		( LPCSTR cmd ) const;
-	IConsole_Command* GetCommand		( LPCSTR cmd ) const;
+    CConsole();
+    virtual ~CConsole();
+    virtual void Initialize();
+    virtual void Destroy();
+
+    virtual void OnRender();
+    virtual void _BCL OnFrame();
+    virtual void OnScreenResolutionChanged();
+    string64 ConfigFile;
+    bool bVisible;
+    vecCMD Commands;
+
+    void AddCommand(IConsole_Command* cc);
+    void RemoveCommand(IConsole_Command* cc);
+
+    void Show();
+    void Hide();
+
+    void Execute(LPCSTR cmd);
+    void ExecuteScript(LPCSTR str);
+    void ExecuteCommand(LPCSTR cmd, bool record_cmd = true);
+    void SelectCommand();
+
+    bool GetBool(LPCSTR cmd) const;
+    float GetFloat(LPCSTR cmd, float& min, float& max) const;
+    int GetInteger(LPCSTR cmd, int& min, int& max) const;
+    LPCSTR GetString(LPCSTR cmd) const;
+    LPCSTR GetToken(LPCSTR cmd) const;
+    xr_token* GetXRToken(LPCSTR cmd) const;
+    Fvector GetFVector(LPCSTR cmd) const;
+    Fvector* GetFVectorPtr(LPCSTR cmd) const;
+    IConsole_Command* GetCommand(LPCSTR cmd) const;
 protected:
-	text_editor::line_editor*			m_editor;
-	text_editor::line_edit_control&		ec();
-
-	BENCH_SEC_SCRAMBLEMEMBER2
-
-	enum Console_mark // (int)=char
-	{
-		no_mark = ' ',
-		mark0  = '~',
-		mark1  = '!', // error
-		mark2  = '@', // console cmd
-		mark3  = '#',
-		mark4  = '$',
-		mark5  = '%',
-		mark6  = '^',
-		mark7  = '&',
-		mark8  = '*',
-		mark9  = '-', // green = ok
-		mark10 = '+',
-		mark11 = '=',
-		mark12 = '/'
-	};
-	
-	bool	is_mark				( Console_mark type );
-	u32		get_mark_color		( Console_mark type );
-
-	void	DrawBackgrounds		( bool bGame );
-	void	DrawRect			( Frect const& r, u32 color );
-	void	OutFont				( LPCSTR text, float& pos_y );
-	void	Register_callbacks	();
-	
+    text_editor::line_editor* m_editor;
+    text_editor::line_edit_control& ec();
+
+    BENCH_SEC_SCRAMBLEMEMBER2
+
+    enum Console_mark // (int)=char
+    {
+        no_mark = ' ',
+        mark0 = '~',
+        mark1 = '!', // error
+        mark2 = '@', // console cmd
+        mark3 = '#',
+        mark4 = '$',
+        mark5 = '%',
+        mark6 = '^',
+        mark7 = '&',
+        mark8 = '*',
+        mark9 = '-', // green = ok
+        mark10 = '+',
+        mark11 = '=',
+        mark12 = '/'
+    };
+
+    bool is_mark(Console_mark type);
+    u32 get_mark_color(Console_mark type);
+
+    void DrawBackgrounds(bool bGame);
+    void DrawRect(Frect const& r, u32 color);
+    void OutFont(LPCSTR text, float& pos_y);
+    void Register_callbacks();
+
 protected:
-	void xr_stdcall Prev_log	();
-	void xr_stdcall Next_log	();
-	void xr_stdcall Begin_log	();
-	void xr_stdcall End_log		();
-	
-	void xr_stdcall Find_cmd	();
-	void xr_stdcall Find_cmd_back();
-	void xr_stdcall Prev_cmd	();
-	void xr_stdcall Next_cmd	();
-	void xr_stdcall Prev_tip	();
-	void xr_stdcall Next_tip	();
-	
-	void xr_stdcall Begin_tips	();
-	void xr_stdcall End_tips	();
-	void xr_stdcall PageUp_tips	();
-	void xr_stdcall PageDown_tips();
-
-	void xr_stdcall Execute_cmd	();
-	void xr_stdcall Show_cmd	();
-	void xr_stdcall Hide_cmd	();
-	void xr_stdcall Hide_cmd_esc();
-
-	void xr_stdcall GamePause	();
+    void xr_stdcall Prev_log();
+    void xr_stdcall Next_log();
+    void xr_stdcall Begin_log();
+    void xr_stdcall End_log();
+
+    void xr_stdcall Find_cmd();
+    void xr_stdcall Find_cmd_back();
+    void xr_stdcall Prev_cmd();
+    void xr_stdcall Next_cmd();
+    void xr_stdcall Prev_tip();
+    void xr_stdcall Next_tip();
+
+    void xr_stdcall Begin_tips();
+    void xr_stdcall End_tips();
+    void xr_stdcall PageUp_tips();
+    void xr_stdcall PageDown_tips();
+
+    void xr_stdcall Execute_cmd();
+    void xr_stdcall Show_cmd();
+    void xr_stdcall Hide_cmd();
+    void xr_stdcall Hide_cmd_esc();
+
+    void xr_stdcall GamePause();
 
 protected:
-	void	add_cmd_history		( shared_str const& str );
-	void	next_cmd_history_idx();
-	void	prev_cmd_history_idx();
-	void	reset_cmd_history_idx();
-
-	void	next_selected_tip	();
-	void	check_next_selected_tip();
-	void	prev_selected_tip	();
-	void	check_prev_selected_tip();
-	void	reset_selected_tip	();
-
-	IConsole_Command* find_next_cmd( LPCSTR in_str, shared_str& out_str );
-	bool	add_next_cmds		( LPCSTR in_str, vecTipsEx& out_v );
-	bool	add_internal_cmds	( LPCSTR in_str, vecTipsEx& out_v );
-	
-	void	update_tips			();
-	void	select_for_filter	( LPCSTR filter_str, vecTips& in_v, vecTipsEx& out_v );
+    void add_cmd_history(shared_str const& str);
+    void next_cmd_history_idx();
+    void prev_cmd_history_idx();
+    void reset_cmd_history_idx();
+
+    void next_selected_tip();
+    void check_next_selected_tip();
+    void prev_selected_tip();
+    void check_prev_selected_tip();
+    void reset_selected_tip();
+
+    IConsole_Command* find_next_cmd(LPCSTR in_str, shared_str& out_str);
+    bool add_next_cmds(LPCSTR in_str, vecTipsEx& out_v);
+    bool add_internal_cmds(LPCSTR in_str, vecTipsEx& out_v);
+
+    void update_tips();
+    void select_for_filter(LPCSTR filter_str, vecTips& in_v, vecTipsEx& out_v);
 
 }; // class CConsole
 
diff --git a/src/xrEngine/XR_IOConsole_callback.cpp b/src/xrEngine/XR_IOConsole_callback.cpp
index 280bff13505..00ce4d687e0 100644
--- a/src/xrEngine/XR_IOConsole_callback.cpp
+++ b/src/xrEngine/XR_IOConsole_callback.cpp
@@ -1,8 +1,8 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: XR_IOConsole_callback.cpp
-//	Created 	: 17.05.2008
-//	Author		: Evgeniy Sokolov
-//	Description : Console`s callback functions class implementation
+// Module : XR_IOConsole_callback.cpp
+// Created : 17.05.2008
+// Author : Evgeniy Sokolov
+// Description : Console`s callback functions class implementation
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -15,196 +15,196 @@
 
 void CConsole::Register_callbacks()
 {
-	ec().assign_callback( DIK_PRIOR, text_editor::ks_free,  Callback( this, &CConsole::Prev_log      ) );
-	ec().assign_callback( DIK_NEXT,  text_editor::ks_free,  Callback( this, &CConsole::Next_log      ) );
-	ec().assign_callback( DIK_PRIOR, text_editor::ks_Ctrl,  Callback( this, &CConsole::Begin_log     ) );
-	ec().assign_callback( DIK_NEXT,  text_editor::ks_Ctrl,  Callback( this, &CConsole::End_log       ) );
+    ec().assign_callback(DIK_PRIOR, text_editor::ks_free, Callback(this, &CConsole::Prev_log));
+    ec().assign_callback(DIK_NEXT, text_editor::ks_free, Callback(this, &CConsole::Next_log));
+    ec().assign_callback(DIK_PRIOR, text_editor::ks_Ctrl, Callback(this, &CConsole::Begin_log));
+    ec().assign_callback(DIK_NEXT, text_editor::ks_Ctrl, Callback(this, &CConsole::End_log));
 
-	ec().assign_callback( DIK_TAB,   text_editor::ks_free,  Callback( this, &CConsole::Find_cmd      ) );
-	ec().assign_callback( DIK_TAB,   text_editor::ks_Shift, Callback( this, &CConsole::Find_cmd_back ) );
-	ec().assign_callback( DIK_TAB,   text_editor::ks_Alt,   Callback( this, &CConsole::GamePause     ) );
+    ec().assign_callback(DIK_TAB, text_editor::ks_free, Callback(this, &CConsole::Find_cmd));
+    ec().assign_callback(DIK_TAB, text_editor::ks_Shift, Callback(this, &CConsole::Find_cmd_back));
+    ec().assign_callback(DIK_TAB, text_editor::ks_Alt, Callback(this, &CConsole::GamePause));
 
-	ec().assign_callback( DIK_UP,    text_editor::ks_free,  Callback( this, &CConsole::Prev_tip      ) );
-	ec().assign_callback( DIK_DOWN,  text_editor::ks_free,  Callback( this, &CConsole::Next_tip      ) );
-	ec().assign_callback( DIK_UP,    text_editor::ks_Ctrl,  Callback( this, &CConsole::Prev_cmd      ) );
-	ec().assign_callback( DIK_DOWN,  text_editor::ks_Ctrl,  Callback( this, &CConsole::Next_cmd      ) );
+    ec().assign_callback(DIK_UP, text_editor::ks_free, Callback(this, &CConsole::Prev_tip));
+    ec().assign_callback(DIK_DOWN, text_editor::ks_free, Callback(this, &CConsole::Next_tip));
+    ec().assign_callback(DIK_UP, text_editor::ks_Ctrl, Callback(this, &CConsole::Prev_cmd));
+    ec().assign_callback(DIK_DOWN, text_editor::ks_Ctrl, Callback(this, &CConsole::Next_cmd));
 
-	ec().assign_callback( DIK_HOME,  text_editor::ks_Alt,   Callback( this, &CConsole::Begin_tips    ) );
-	ec().assign_callback( DIK_END,   text_editor::ks_Alt,   Callback( this, &CConsole::End_tips      ) );
-	ec().assign_callback( DIK_PRIOR, text_editor::ks_Alt,   Callback( this, &CConsole::PageUp_tips   ) );
-	ec().assign_callback( DIK_NEXT,  text_editor::ks_Alt,   Callback( this, &CConsole::PageDown_tips ) );
-	
-	ec().assign_callback( DIK_RETURN,      text_editor::ks_free, Callback( this, &CConsole::Execute_cmd ) );
-	ec().assign_callback( DIK_NUMPADENTER, text_editor::ks_free, Callback( this, &CConsole::Execute_cmd ) );
-	
-	ec().assign_callback( DIK_ESCAPE, text_editor::ks_free, Callback( this, &CConsole::Hide_cmd_esc ) );
-	ec().assign_callback( DIK_GRAVE,  text_editor::ks_free, Callback( this, &CConsole::Hide_cmd     ) );
+    ec().assign_callback(DIK_HOME, text_editor::ks_Alt, Callback(this, &CConsole::Begin_tips));
+    ec().assign_callback(DIK_END, text_editor::ks_Alt, Callback(this, &CConsole::End_tips));
+    ec().assign_callback(DIK_PRIOR, text_editor::ks_Alt, Callback(this, &CConsole::PageUp_tips));
+    ec().assign_callback(DIK_NEXT, text_editor::ks_Alt, Callback(this, &CConsole::PageDown_tips));
+
+    ec().assign_callback(DIK_RETURN, text_editor::ks_free, Callback(this, &CConsole::Execute_cmd));
+    ec().assign_callback(DIK_NUMPADENTER, text_editor::ks_free, Callback(this, &CConsole::Execute_cmd));
+
+    ec().assign_callback(DIK_ESCAPE, text_editor::ks_free, Callback(this, &CConsole::Hide_cmd_esc));
+    ec().assign_callback(DIK_GRAVE, text_editor::ks_free, Callback(this, &CConsole::Hide_cmd));
 }
 
 void CConsole::Prev_log() // DIK_PRIOR=PAGE_UP
 {
-	scroll_delta++;
-	if ( scroll_delta > int(LogFile->size())-1 )
-	{
-		scroll_delta = LogFile->size()-1;
-	}
+    scroll_delta++;
+    if (scroll_delta > int(LogFile->size()) - 1)
+    {
+        scroll_delta = LogFile->size() - 1;
+    }
 }
 
 void CConsole::Next_log() // DIK_NEXT=PAGE_DOWN
 {
-	scroll_delta--;
-	if ( scroll_delta < 0 )
-	{
-		scroll_delta = 0;
-	}
+    scroll_delta--;
+    if (scroll_delta < 0)
+    {
+        scroll_delta = 0;
+    }
 }
 
 void CConsole::Begin_log() // PAGE_UP+Ctrl
 {
-	scroll_delta = LogFile->size()-1;
+    scroll_delta = LogFile->size() - 1;
 }
 
 void CConsole::End_log() // PAGE_DOWN+Ctrl
 {
-	scroll_delta = 0;
+    scroll_delta = 0;
 }
 
 void CConsole::Find_cmd() // DIK_TAB
 {
-	shared_str out_str;
-		
-	IConsole_Command* cc = find_next_cmd( ec().str_edit(), out_str );
-	if ( cc && out_str.size() )
-	{
-		ec().set_edit( out_str.c_str() );
-	}
+    shared_str out_str;
+
+    IConsole_Command* cc = find_next_cmd(ec().str_edit(), out_str);
+    if (cc && out_str.size())
+    {
+        ec().set_edit(out_str.c_str());
+    }
 }
 
 void CConsole::Find_cmd_back() // DIK_TAB+shift
 {
-	LPCSTR edt      = ec().str_edit();
-	LPCSTR radmin_cmd_name = "ra ";
-	bool b_ra  = (edt == strstr( edt, radmin_cmd_name ) );
-	u32 offset = (b_ra)? xr_strlen( radmin_cmd_name ) : 0;
+    LPCSTR edt = ec().str_edit();
+    LPCSTR radmin_cmd_name = "ra ";
+    bool b_ra = (edt == strstr(edt, radmin_cmd_name));
+    u32 offset = (b_ra) ? xr_strlen(radmin_cmd_name) : 0;
 
-	vecCMD_IT it = Commands.lower_bound( edt + offset );
-	if ( it != Commands.begin() )
-	{
-		--it;
-		IConsole_Command& cc = *(it->second);
-		LPCSTR name_cmd      = cc.Name();
-		u32    name_cmd_size = xr_strlen( name_cmd );
-		PSTR   new_str  = (PSTR)_alloca( (offset + name_cmd_size + 2) * sizeof(char) );
+    vecCMD_IT it = Commands.lower_bound(edt + offset);
+    if (it != Commands.begin())
+    {
+        --it;
+        IConsole_Command& cc = *(it->second);
+        LPCSTR name_cmd = cc.Name();
+        u32 name_cmd_size = xr_strlen(name_cmd);
+        PSTR new_str = (PSTR)_alloca((offset + name_cmd_size + 2) * sizeof(char));
 
-		xr_strcpy( new_str, offset + name_cmd_size + 2, (b_ra)? radmin_cmd_name : "" );
-		xr_strcat( new_str, offset + name_cmd_size + 2, name_cmd );
-		ec().set_edit( new_str );
-	}
+        xr_strcpy(new_str, offset + name_cmd_size + 2, (b_ra) ? radmin_cmd_name : "");
+        xr_strcat(new_str, offset + name_cmd_size + 2, name_cmd);
+        ec().set_edit(new_str);
+    }
 }
 
 void CConsole::Prev_cmd() // DIK_UP + Ctrl
 {
-	prev_cmd_history_idx();
-	SelectCommand();
+    prev_cmd_history_idx();
+    SelectCommand();
 }
 
 void CConsole::Next_cmd() // DIK_DOWN + Ctrl
 {
-	next_cmd_history_idx();
-	SelectCommand();
+    next_cmd_history_idx();
+    SelectCommand();
 }
 
 void CConsole::Prev_tip() // DIK_UP
 {
-	if ( xr_strlen( ec().str_edit() ) == 0 )
-	{
-		prev_cmd_history_idx();
-		SelectCommand();
-		return;
-	}
-	prev_selected_tip();
+    if (xr_strlen(ec().str_edit()) == 0)
+    {
+        prev_cmd_history_idx();
+        SelectCommand();
+        return;
+    }
+    prev_selected_tip();
 }
 
 void CConsole::Next_tip() // DIK_DOWN + Ctrl
 {
-	if ( xr_strlen( ec().str_edit() ) == 0 )
-	{
-		next_cmd_history_idx();
-		SelectCommand();
-		return;
-	}
-	next_selected_tip();
+    if (xr_strlen(ec().str_edit()) == 0)
+    {
+        next_cmd_history_idx();
+        SelectCommand();
+        return;
+    }
+    next_selected_tip();
 }
 
 void CConsole::Begin_tips()
 {
-	m_select_tip = 0;
-	m_start_tip = 0;
+    m_select_tip = 0;
+    m_start_tip = 0;
 }
 
 void CConsole::End_tips()
 {
-	m_select_tip = m_tips.size() - 1;
-	m_start_tip = m_select_tip - VIEW_TIPS_COUNT + 1;
-	check_next_selected_tip();
+    m_select_tip = m_tips.size() - 1;
+    m_start_tip = m_select_tip - VIEW_TIPS_COUNT + 1;
+    check_next_selected_tip();
 }
 
 void CConsole::PageUp_tips()
 {
-	m_select_tip -= VIEW_TIPS_COUNT;
-	check_prev_selected_tip();
+    m_select_tip -= VIEW_TIPS_COUNT;
+    check_prev_selected_tip();
 }
 
 void CConsole::PageDown_tips()
 {
-	m_select_tip += VIEW_TIPS_COUNT;
-	check_next_selected_tip();
+    m_select_tip += VIEW_TIPS_COUNT;
+    check_next_selected_tip();
 }
 
 void CConsole::Execute_cmd() // DIK_RETURN, DIK_NUMPADENTER
 {
-	if ( 0 <= m_select_tip && m_select_tip < (int)m_tips.size() )
-	{
-		shared_str const& str = m_tips[m_select_tip].text;
-		if ( m_tips_mode == 1 )
-		{
-			LPSTR buf;
-			STRCONCAT( buf, str.c_str(), " " );
-			ec().set_edit( buf );
-		}
-		else if ( m_tips_mode == 2 )
-		{
-			LPSTR buf;
-			STRCONCAT( buf, m_cur_cmd.c_str(), " ", str.c_str() );
-			ec().set_edit( buf );
-		}
-		reset_selected_tip();
-	}
-	else
-	{
-		ExecuteCommand( ec().str_edit() );
-	}
-	m_disable_tips = false;
+    if (0 <= m_select_tip && m_select_tip < (int)m_tips.size())
+    {
+        shared_str const& str = m_tips[m_select_tip].text;
+        if (m_tips_mode == 1)
+        {
+            LPSTR buf;
+            STRCONCAT(buf, str.c_str(), " ");
+            ec().set_edit(buf);
+        }
+        else if (m_tips_mode == 2)
+        {
+            LPSTR buf;
+            STRCONCAT(buf, m_cur_cmd.c_str(), " ", str.c_str());
+            ec().set_edit(buf);
+        }
+        reset_selected_tip();
+    }
+    else
+    {
+        ExecuteCommand(ec().str_edit());
+    }
+    m_disable_tips = false;
 }
 
 void CConsole::Show_cmd()
 {
-	Show();
+    Show();
 }
 
 void CConsole::Hide_cmd()
 {
-	Hide();
+    Hide();
 }
 
 void CConsole::Hide_cmd_esc()
 {
-	if ( 0 <= m_select_tip && m_select_tip < (int)m_tips.size() )
-	{
-		m_disable_tips = true;
-		return;
-	}
-	Hide();
+    if (0 <= m_select_tip && m_select_tip < (int)m_tips.size())
+    {
+        m_disable_tips = true;
+        return;
+    }
+    Hide();
 }
 
 void CConsole::GamePause()
diff --git a/src/xrEngine/XR_IOConsole_control.cpp b/src/xrEngine/XR_IOConsole_control.cpp
index 139aa0bfbbc..af03a347a39 100644
--- a/src/xrEngine/XR_IOConsole_control.cpp
+++ b/src/xrEngine/XR_IOConsole_control.cpp
@@ -1,97 +1,97 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: XR_IOConsole_control.cpp
-//	Created 	: 03.10.2008
-//	Author		: Evgeniy Sokolov
-//	Description : Console`s control-functions class implementation
+// Module : XR_IOConsole_control.cpp
+// Created : 03.10.2008
+// Author : Evgeniy Sokolov
+// Description : Console`s control-functions class implementation
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
 #include "XR_IOConsole.h"
 
 
-void CConsole::add_cmd_history( shared_str const& str )
+void CConsole::add_cmd_history(shared_str const& str)
 {
-	if ( str.size() == 0 )
-	{
-		return;
-	}
-	m_cmd_history.push_back( str );
-	if ( m_cmd_history.size() > m_cmd_history_max )
-	{
-		m_cmd_history.erase( m_cmd_history.begin() );
-	}
+    if (str.size() == 0)
+    {
+        return;
+    }
+    m_cmd_history.push_back(str);
+    if (m_cmd_history.size() > m_cmd_history_max)
+    {
+        m_cmd_history.erase(m_cmd_history.begin());
+    }
 }
 
 void CConsole::next_cmd_history_idx()
 {
-	--m_cmd_history_idx;
-	if ( m_cmd_history_idx < 0 )
-	{
-		m_cmd_history_idx = 0;
-	}
+    --m_cmd_history_idx;
+    if (m_cmd_history_idx < 0)
+    {
+        m_cmd_history_idx = 0;
+    }
 }
 
 void CConsole::prev_cmd_history_idx()
 {
-	++m_cmd_history_idx;
-	if ( m_cmd_history_idx >= (int)m_cmd_history.size() )
-	{
-		m_cmd_history_idx = m_cmd_history.size() - 1;
-	}
+    ++m_cmd_history_idx;
+    if (m_cmd_history_idx >= (int)m_cmd_history.size())
+    {
+        m_cmd_history_idx = m_cmd_history.size() - 1;
+    }
 }
 
 void CConsole::reset_cmd_history_idx()
 {
-	m_cmd_history_idx = -1;
+    m_cmd_history_idx = -1;
 }
 
 void CConsole::next_selected_tip()
 {
-	++m_select_tip;
-	check_next_selected_tip();
+    ++m_select_tip;
+    check_next_selected_tip();
 }
 
 void CConsole::check_next_selected_tip()
 {
-	if ( m_select_tip >= (int)m_tips.size() )
-	{
-		m_select_tip = m_tips.size() - 1;
-	}
+    if (m_select_tip >= (int)m_tips.size())
+    {
+        m_select_tip = m_tips.size() - 1;
+    }
 
-	int sel_dif = m_select_tip - VIEW_TIPS_COUNT + 1;
-	if ( sel_dif < 0 )
-	{
-		sel_dif = 0;
-	}
+    int sel_dif = m_select_tip - VIEW_TIPS_COUNT + 1;
+    if (sel_dif < 0)
+    {
+        sel_dif = 0;
+    }
 
-	if ( sel_dif > m_start_tip )
-	{
-		m_start_tip = sel_dif;
-	}
+    if (sel_dif > m_start_tip)
+    {
+        m_start_tip = sel_dif;
+    }
 }
 
 void CConsole::prev_selected_tip()
 {
-	--m_select_tip;
-	check_prev_selected_tip();
+    --m_select_tip;
+    check_prev_selected_tip();
 }
 
 void CConsole::check_prev_selected_tip()
 {
-	if ( m_select_tip < 0 )
-	{
-		m_select_tip = 0;
-	}
+    if (m_select_tip < 0)
+    {
+        m_select_tip = 0;
+    }
 
-	if ( m_start_tip > m_select_tip )
-	{
-		m_start_tip = m_select_tip;
-	}
+    if (m_start_tip > m_select_tip)
+    {
+        m_start_tip = m_select_tip;
+    }
 }
 
 void CConsole::reset_selected_tip()
 {
-	m_select_tip = -1;
-	m_start_tip = 0;
-	m_disable_tips = false;
+    m_select_tip = -1;
+    m_start_tip = 0;
+    m_disable_tips = false;
 }
diff --git a/src/xrEngine/XR_IOConsole_get.cpp b/src/xrEngine/XR_IOConsole_get.cpp
index 09f299b14bb..ba9ee78f050 100644
--- a/src/xrEngine/XR_IOConsole_get.cpp
+++ b/src/xrEngine/XR_IOConsole_get.cpp
@@ -1,8 +1,8 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: XR_IOConsole_get.cpp
-//	Created 	: 17.05.2008
-//	Author		: Evgeniy Sokolov
-//	Description : Console`s get-functions class implementation
+// Module : XR_IOConsole_get.cpp
+// Created : 17.05.2008
+// Author : Evgeniy Sokolov
+// Description : Console`s get-functions class implementation
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -10,114 +10,114 @@
 #include "xr_ioc_cmd.h"
 
 
-bool CConsole::GetBool( LPCSTR cmd ) const
+bool CConsole::GetBool(LPCSTR cmd) const
 {
-	IConsole_Command* cc	= GetCommand(cmd);
-	CCC_Mask* cf			= dynamic_cast(cc);
-	if ( cf )
-	{
-		return ( cf->GetValue() != 0 );
-	}
-
-	CCC_Integer* ci			= dynamic_cast(cc);
-	if ( ci )
-	{
-		return ( ci->GetValue() != 0 );
-	}
-	return false;
+    IConsole_Command* cc = GetCommand(cmd);
+    CCC_Mask* cf = dynamic_cast(cc);
+    if (cf)
+    {
+        return (cf->GetValue() != 0);
+    }
+
+    CCC_Integer* ci = dynamic_cast(cc);
+    if (ci)
+    {
+        return (ci->GetValue() != 0);
+    }
+    return false;
 }
 
-float CConsole::GetFloat( LPCSTR cmd, float& min, float& max ) const
+float CConsole::GetFloat(LPCSTR cmd, float& min, float& max) const
 {
-	min						= 0.0f;
-	max						= 0.0f;
-	IConsole_Command* cc	= GetCommand(cmd);
-	CCC_Float* cf			= dynamic_cast(cc);
-	if ( cf )
-	{
-		cf->GetBounds(min, max);
-		return cf->GetValue(); 
-	}
-	return 0.0f;
+    min = 0.0f;
+    max = 0.0f;
+    IConsole_Command* cc = GetCommand(cmd);
+    CCC_Float* cf = dynamic_cast(cc);
+    if (cf)
+    {
+        cf->GetBounds(min, max);
+        return cf->GetValue();
+    }
+    return 0.0f;
 }
 
-IConsole_Command* CConsole::GetCommand( LPCSTR cmd ) const
+IConsole_Command* CConsole::GetCommand(LPCSTR cmd) const
 {
-	vecCMD_CIT it = Commands.find( cmd );
-	if ( it == Commands.end() )
-		return NULL;
-	else
-		return it->second;
+    vecCMD_CIT it = Commands.find(cmd);
+    if (it == Commands.end())
+        return NULL;
+    else
+        return it->second;
 }
 
 
-int CConsole::GetInteger( LPCSTR cmd, int& min, int& max ) const
+int CConsole::GetInteger(LPCSTR cmd, int& min, int& max) const
 {
-	min						= 0;
-	max						= 1;
-	IConsole_Command* cc	= GetCommand(cmd);
-
-	CCC_Integer* cf			= dynamic_cast(cc);
-	if ( cf )
-	{
-		cf->GetBounds(min, max);
-		return cf->GetValue();
-	}
-	CCC_Mask* cm = dynamic_cast(cc);
-	if ( cm )
-	{
-		min = 0;
-		max = 1;
-		return ( cm->GetValue() )? 1 : 0;
-	}
-	return 0;
+    min = 0;
+    max = 1;
+    IConsole_Command* cc = GetCommand(cmd);
+
+    CCC_Integer* cf = dynamic_cast(cc);
+    if (cf)
+    {
+        cf->GetBounds(min, max);
+        return cf->GetValue();
+    }
+    CCC_Mask* cm = dynamic_cast(cc);
+    if (cm)
+    {
+        min = 0;
+        max = 1;
+        return (cm->GetValue()) ? 1 : 0;
+    }
+    return 0;
 }
 
-LPCSTR CConsole::GetString( LPCSTR cmd ) const
+LPCSTR CConsole::GetString(LPCSTR cmd) const
 {
-	IConsole_Command* cc	= GetCommand(cmd);
-	if(!cc)
-		return				NULL;
+    IConsole_Command* cc = GetCommand(cmd);
+    if (!cc)
+        return NULL;
 
-	static IConsole_Command::TStatus stat;
-	cc->Status				( stat );
-	return					stat;
+    static IConsole_Command::TStatus stat;
+    cc->Status(stat);
+    return stat;
 }
 
-LPCSTR CConsole::GetToken( LPCSTR cmd ) const
+LPCSTR CConsole::GetToken(LPCSTR cmd) const
 {
-	return GetString( cmd );
+    return GetString(cmd);
 }
 
-xr_token* CConsole::GetXRToken( LPCSTR cmd ) const
+xr_token* CConsole::GetXRToken(LPCSTR cmd) const
 {
-	IConsole_Command* cc	= GetCommand(cmd);
-	
-	CCC_Token* cf			= dynamic_cast(cc);
-	if ( cf )
-	{
-		return cf->GetToken();
-	}
-	return					NULL;
+    IConsole_Command* cc = GetCommand(cmd);
+
+    CCC_Token* cf = dynamic_cast(cc);
+    if (cf)
+    {
+        return cf->GetToken();
+    }
+    return NULL;
 }
 
-Fvector* CConsole::GetFVectorPtr( LPCSTR cmd ) const
+Fvector* CConsole::GetFVectorPtr(LPCSTR cmd) const
 {
-	IConsole_Command* cc	= GetCommand(cmd);
-	CCC_Vector3* cf			= dynamic_cast(cc);
-	if ( cf )
-	{
-		return cf->GetValuePtr();
-	}
-	return					NULL;
+    IConsole_Command* cc = GetCommand(cmd);
+    CCC_Vector3* cf = dynamic_cast(cc);
+    if (cf)
+    {
+        return cf->GetValuePtr();
+    }
+    return NULL;
 }
 
-Fvector CConsole::GetFVector( LPCSTR cmd ) const
+Fvector CConsole::GetFVector(LPCSTR cmd) const
 {
-	Fvector* pV = GetFVectorPtr( cmd );
-	if ( pV )
-	{
-		return *pV;
-	}
-	return Fvector().set( 0.0f, 0.0f, 0.0f );
+    Fvector* pV = GetFVectorPtr(cmd);
+    if (pV)
+    {
+        return *pV;
+    }
+    return Fvector().set(0.0f, 0.0f, 0.0f);
 }
diff --git a/src/xrEngine/Xr_input.cpp b/src/xrEngine/Xr_input.cpp
index 6ec37f0f61e..6ae01e538fc 100644
--- a/src/xrEngine/Xr_input.cpp
+++ b/src/xrEngine/Xr_input.cpp
@@ -6,576 +6,646 @@
 #include "../include/editor/ide.hpp"
 
 #ifndef _EDITOR
-#	include "xr_input_xinput.h"
+# include "xr_input_xinput.h"
 #endif
-CInput *	pInput	= NULL;
-IInputReceiver		dummyController;
+CInput* pInput = NULL;
+IInputReceiver dummyController;
 
-ENGINE_API float	psMouseSens			= 1.f;
-ENGINE_API float	psMouseSensScale	= 1.f;
-ENGINE_API Flags32	psMouseInvert		= {FALSE};
+ENGINE_API float psMouseSens = 1.f;
+ENGINE_API float psMouseSensScale = 1.f;
+ENGINE_API Flags32 psMouseInvert = {FALSE};
 
-float stop_vibration_time				= flt_max;
+float stop_vibration_time = flt_max;
 
-#define MOUSEBUFFERSIZE			64
-#define KEYBOARDBUFFERSIZE		64
-#define _KEYDOWN(name,key)		( name[key] & 0x80 )
+#define MOUSEBUFFERSIZE 64
+#define KEYBOARDBUFFERSIZE 64
+#define _KEYDOWN(name,key) ( name[key] & 0x80 )
 
-static bool g_exclusive	= true;
-static void on_error_dialog			(bool before)
+static bool g_exclusive = true;
+static void on_error_dialog(bool before)
 {
 #ifdef INGAME_EDITOR
-	if (Device.editor())
-		return;
+    if (Device.editor())
+        return;
 #endif // #ifdef INGAME_EDITOR
-	if (!pInput || !g_exclusive)
-		return;
+    if (!pInput || !g_exclusive)
+        return;
 
-	if (before) {
-		pInput->unacquire	();
-		return;
-	}
+    if (before)
+    {
+        pInput->unacquire();
+        return;
+    }
 
-	pInput->acquire			(true);
+    pInput->acquire(true);
 }
 
-CInput::CInput						( BOOL bExclusive, int deviceForInit)
+CInput::CInput(BOOL bExclusive, int deviceForInit)
 {
-	g_exclusive							= !!bExclusive;
+    g_exclusive = !!bExclusive;
 
-	Log("Starting INPUT device...");
+    Log("Starting INPUT device...");
 
-	pDI 								=	NULL;
-	pMouse								=	NULL;
-	pKeyboard							=	NULL;
+    pDI = NULL;
+    pMouse = NULL;
+    pKeyboard = NULL;
 
-	//=====================Mouse
-	mouse_property.mouse_dt				=	25;
+    //=====================Mouse
+    mouse_property.mouse_dt = 25;
 
-	ZeroMemory							( mouseState,	sizeof(mouseState) );
-	ZeroMemory							( KBState,		sizeof(KBState) );
-	ZeroMemory							( timeStamp,	sizeof(timeStamp) );
-	ZeroMemory							( timeSave,		sizeof(timeStamp) );
-	ZeroMemory							( offs,			sizeof(offs) );
+    ZeroMemory(mouseState, sizeof(mouseState));
+    ZeroMemory(KBState, sizeof(KBState));
+    ZeroMemory(timeStamp, sizeof(timeStamp));
+    ZeroMemory(timeSave, sizeof(timeStamp));
+    ZeroMemory(offs, sizeof(offs));
 
-	//===================== Dummy pack
-	iCapture	(&dummyController);
+    //===================== Dummy pack
+    iCapture(&dummyController);
 
-	if (!pDI) CHK_DX(DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&pDI, NULL ));
+    if (!pDI) CHK_DX(DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&pDI, NULL));
 
-//.	u32 kb_input_flags = ((bExclusive)?DISCL_EXCLUSIVE:DISCL_NONEXCLUSIVE) | DISCL_FOREGROUND;
-	u32 kb_input_flags = ((bExclusive)?DISCL_EXCLUSIVE:DISCL_NONEXCLUSIVE) | DISCL_FOREGROUND;
-	
-//.	u32 mouse_input_flags = ((bExclusive)?DISCL_EXCLUSIVE:DISCL_NONEXCLUSIVE) | DISCL_FOREGROUND | DISCL_NOWINKEY,
-	u32 mouse_input_flags = ((bExclusive)?DISCL_EXCLUSIVE:DISCL_NONEXCLUSIVE) | DISCL_FOREGROUND | DISCL_NOWINKEY;
+    //. u32 kb_input_flags = ((bExclusive)?DISCL_EXCLUSIVE:DISCL_NONEXCLUSIVE) | DISCL_FOREGROUND;
+    u32 kb_input_flags = ((bExclusive) ? DISCL_EXCLUSIVE : DISCL_NONEXCLUSIVE) | DISCL_FOREGROUND;
 
-	// KEYBOARD
-	if (deviceForInit & keyboard_device_key)
-		CHK_DX(CreateInputDevice(
-		&pKeyboard, 	GUID_SysKeyboard, 	&c_dfDIKeyboard,
-		kb_input_flags,
-		KEYBOARDBUFFERSIZE ));
+    //. u32 mouse_input_flags = ((bExclusive)?DISCL_EXCLUSIVE:DISCL_NONEXCLUSIVE) | DISCL_FOREGROUND | DISCL_NOWINKEY,
+    u32 mouse_input_flags = ((bExclusive) ? DISCL_EXCLUSIVE : DISCL_NONEXCLUSIVE) | DISCL_FOREGROUND | DISCL_NOWINKEY;
 
-	// MOUSE
-	if (deviceForInit & mouse_device_key)
-		CHK_DX(CreateInputDevice(
-		&pMouse,		GUID_SysMouse,		&c_dfDIMouse2,
-		mouse_input_flags,
-		MOUSEBUFFERSIZE ));
+    // KEYBOARD
+    if (deviceForInit & keyboard_device_key)
+        CHK_DX(CreateInputDevice(
+                   &pKeyboard, GUID_SysKeyboard, &c_dfDIKeyboard,
+                   kb_input_flags,
+                   KEYBOARDBUFFERSIZE));
 
-	Debug.set_on_dialog				(&on_error_dialog);
+    // MOUSE
+    if (deviceForInit & mouse_device_key)
+        CHK_DX(CreateInputDevice(
+                   &pMouse, GUID_SysMouse, &c_dfDIMouse2,
+                   mouse_input_flags,
+                   MOUSEBUFFERSIZE));
+
+    Debug.set_on_dialog(&on_error_dialog);
 
 #ifdef ENGINE_BUILD
-	Device.seqAppActivate.Add		(this);
-	Device.seqAppDeactivate.Add		(this, REG_PRIORITY_HIGH);
-	Device.seqFrame.Add				(this, REG_PRIORITY_HIGH);
+    Device.seqAppActivate.Add(this);
+    Device.seqAppDeactivate.Add(this, REG_PRIORITY_HIGH);
+    Device.seqFrame.Add(this, REG_PRIORITY_HIGH);
 #endif
 }
 
 CInput::~CInput(void)
 {
 #ifdef ENGINE_BUILD
-	Device.seqFrame.Remove			(this);
-	Device.seqAppDeactivate.Remove	(this);
-	Device.seqAppActivate.Remove	(this);
+    Device.seqFrame.Remove(this);
+    Device.seqAppDeactivate.Remove(this);
+    Device.seqAppActivate.Remove(this);
 #endif
-	//_______________________
-
-	// Unacquire and release the device's interfaces
-	if( pMouse ){
-		pMouse->Unacquire();
-		_RELEASE	(pMouse);
-	}
-
-	if( pKeyboard ){
-		pKeyboard->Unacquire();
-		_RELEASE	(pKeyboard);
-	}
-
-	_SHOW_REF	("Input: ",pDI);
-	_RELEASE	(pDI);
+    //_______________________
+
+    // Unacquire and release the device's interfaces
+    if (pMouse)
+    {
+        pMouse->Unacquire();
+        _RELEASE(pMouse);
+    }
+
+    if (pKeyboard)
+    {
+        pKeyboard->Unacquire();
+        _RELEASE(pKeyboard);
+    }
+
+    _SHOW_REF("Input: ", pDI);
+    _RELEASE(pDI);
 }
 
 //-----------------------------------------------------------------------------
 // Name: CreateInputDevice()
 // Desc: Create a DirectInput device.
 //-----------------------------------------------------------------------------
-HRESULT CInput::CreateInputDevice( LPDIRECTINPUTDEVICE8* device, GUID guidDevice, const DIDATAFORMAT* pdidDataFormat, u32 dwFlags, u32 buf_size )
+HRESULT CInput::CreateInputDevice(LPDIRECTINPUTDEVICE8* device, GUID guidDevice, const DIDATAFORMAT* pdidDataFormat, u32 dwFlags, u32 buf_size)
 {
-	// Obtain an interface to the input device
-//.	CHK_DX( pDI->CreateDeviceEx( guidDevice, IID_IDirectInputDevice8, (void**)device, NULL ) );
-	CHK_DX( pDI->CreateDevice( guidDevice, /*IID_IDirectInputDevice8,*/ device, NULL ) );
+    // Obtain an interface to the input device
+    //. CHK_DX( pDI->CreateDeviceEx( guidDevice, IID_IDirectInputDevice8, (void**)device, NULL ) );
+    CHK_DX(pDI->CreateDevice(guidDevice, /*IID_IDirectInputDevice8,*/ device, NULL));
 
-	// Set the device data format. Note: a data format specifies which
-	// controls on a device we are interested in, and how they should be
-	// reported.
-	CHK_DX((*device)->SetDataFormat( pdidDataFormat ) );
+    // Set the device data format. Note: a data format specifies which
+    // controls on a device we are interested in, and how they should be
+    // reported.
+    CHK_DX((*device)->SetDataFormat(pdidDataFormat));
 
-	// Set the cooperativity level to let DirectInput know how this device
-	// should interact with the system and with other DirectInput applications.
+    // Set the cooperativity level to let DirectInput know how this device
+    // should interact with the system and with other DirectInput applications.
 #ifdef INGAME_EDITOR
-	if (!Device.editor())
+    if (!Device.editor())
 #endif // #ifdef INGAME_EDITOR
-	{
-		HRESULT	_hr = (*device)->SetCooperativeLevel( RDEVICE.m_hWnd, dwFlags );
-		if (FAILED(_hr) && (_hr==E_NOTIMPL)) Msg("! INPUT: Can't set coop level. Emulation???");
-		else R_CHK(_hr);
-	}
-
-	// setup the buffer size for the keyboard data
-	DIPROPDWORD				dipdw;
-	dipdw.diph.dwSize		= sizeof(DIPROPDWORD);
-	dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
-	dipdw.diph.dwObj		= 0;
-	dipdw.diph.dwHow		= DIPH_DEVICE;
-	dipdw.dwData			= buf_size;
-
-	CHK_DX( (*device)->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph ) );
-
-	return S_OK;
+    {
+        HRESULT _hr = (*device)->SetCooperativeLevel(RDEVICE.m_hWnd, dwFlags);
+        if (FAILED(_hr) && (_hr == E_NOTIMPL)) Msg("! INPUT: Can't set coop level. Emulation???");
+        else R_CHK(_hr);
+    }
+
+    // setup the buffer size for the keyboard data
+    DIPROPDWORD dipdw;
+    dipdw.diph.dwSize = sizeof(DIPROPDWORD);
+    dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
+    dipdw.diph.dwObj = 0;
+    dipdw.diph.dwHow = DIPH_DEVICE;
+    dipdw.dwData = buf_size;
+
+    CHK_DX((*device)->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph));
+
+    return S_OK;
 }
 
 //-----------------------------------------------------------------------
 
-void CInput::SetAllAcquire( BOOL bAcquire )
+void CInput::SetAllAcquire(BOOL bAcquire)
 {
-	if (pMouse)		bAcquire ? pMouse->Acquire() 	: pMouse->Unacquire();
-	if (pKeyboard)	bAcquire ? pKeyboard->Acquire()	: pKeyboard->Unacquire();
+    if (pMouse) bAcquire ? pMouse->Acquire() : pMouse->Unacquire();
+    if (pKeyboard) bAcquire ? pKeyboard->Acquire() : pKeyboard->Unacquire();
 }
 
-void CInput::SetMouseAcquire( BOOL bAcquire )
+void CInput::SetMouseAcquire(BOOL bAcquire)
 {
-	if (pMouse)		bAcquire ? pMouse->Acquire() : pMouse->Unacquire();
+    if (pMouse) bAcquire ? pMouse->Acquire() : pMouse->Unacquire();
 }
-void CInput::SetKBDAcquire( BOOL bAcquire )
+void CInput::SetKBDAcquire(BOOL bAcquire)
 {
-	if (pKeyboard)	bAcquire ? pKeyboard->Acquire()	: pKeyboard->Unacquire();
+    if (pKeyboard) bAcquire ? pKeyboard->Acquire() : pKeyboard->Unacquire();
 }
 //-----------------------------------------------------------------------
 BOOL b_altF4 = FALSE;
-void CInput::KeyUpdate	( )
+void CInput::KeyUpdate()
 {
-	if(b_altF4)					return;
-
-	HRESULT						hr;
-	DWORD dwElements			= KEYBOARDBUFFERSIZE;
-	DIDEVICEOBJECTDATA			od[KEYBOARDBUFFERSIZE];
-	DWORD key					= 0;
-
-	VERIFY(pKeyboard);
-
-	hr = pKeyboard->GetDeviceData( sizeof(DIDEVICEOBJECTDATA), &od[0], &dwElements, 0 );
-	if (( hr == DIERR_INPUTLOST )||( hr == DIERR_NOTACQUIRED ))
-	{
-		hr = pKeyboard->Acquire();
-		if ( hr != S_OK ) 
-			return;
-
-		hr = pKeyboard->GetDeviceData( sizeof(DIDEVICEOBJECTDATA), &od[0], &dwElements, 0 );
-		if ( hr != S_OK ) 
-			return;
-	}
-
-	bool b_dik_pause_was_pressed = false;
-	for (u32 idx = 0; idx < dwElements; idx++)
-	{
-		if(od[idx].dwOfs==DIK_PAUSE)
-		{
-			if( od[idx].dwData & 0x80 )
-				b_dik_pause_was_pressed = true;
-		
-			if(b_dik_pause_was_pressed && !(od[idx].dwData & 0x80) )
-			{
-				od[idx].uAppData = 666;
-				continue; //skip one-frame pause key on-off switch
-			}
-		}
-		KBState[od[idx].dwOfs]		= od[idx].dwData & 0x80;
-	}
+    if (b_altF4) return;
+
+    HRESULT hr;
+    DWORD dwElements = KEYBOARDBUFFERSIZE;
+    DIDEVICEOBJECTDATA od[KEYBOARDBUFFERSIZE];
+    DWORD key = 0;
+
+    VERIFY(pKeyboard);
+
+    hr = pKeyboard->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), &od[0], &dwElements, 0);
+    if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
+    {
+        hr = pKeyboard->Acquire();
+        if (hr != S_OK)
+            return;
+
+        hr = pKeyboard->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), &od[0], &dwElements, 0);
+        if (hr != S_OK)
+            return;
+    }
+
+    bool b_dik_pause_was_pressed = false;
+    for (u32 idx = 0; idx < dwElements; idx++)
+    {
+        if (od[idx].dwOfs == DIK_PAUSE)
+        {
+            if (od[idx].dwData & 0x80)
+                b_dik_pause_was_pressed = true;
+
+            if (b_dik_pause_was_pressed && !(od[idx].dwData & 0x80))
+            {
+                od[idx].uAppData = 666;
+                continue; //skip one-frame pause key on-off switch
+            }
+        }
+        KBState[od[idx].dwOfs] = od[idx].dwData & 0x80;
+    }
 
 #ifndef _EDITOR
-	bool b_alt_tab				= false;
+    bool b_alt_tab = false;
 
-	if(!b_altF4 && KBState[DIK_F4] && (KBState[DIK_RMENU] || KBState[DIK_LMENU]) )
-	{
-		b_altF4				= TRUE;
-		Engine.Event.Defer	("KERNEL:disconnect");
-		Engine.Event.Defer	("KERNEL:quit");
-	}
+    if (!b_altF4 && KBState[DIK_F4] && (KBState[DIK_RMENU] || KBState[DIK_LMENU]))
+    {
+        b_altF4 = TRUE;
+        Engine.Event.Defer("KERNEL:disconnect");
+        Engine.Event.Defer("KERNEL:quit");
+    }
 
 
 #endif
-	if(b_altF4)					return;
-
-	#ifndef _EDITOR
-   	if(Device.dwPrecacheFrame==0)
-	#endif
-	{
-
-		for (u32 i = 0; i < dwElements; i++)
-		{
-			if(od[i].uAppData == 666) //ignored action
-				continue;
-
-			key					= od[i].dwOfs;
-			if(od[i].dwData & 0x80)
-				cbStack.back()->IR_OnKeyboardPress	( key );
-			else
-			{
-				cbStack.back()->IR_OnKeyboardRelease	( key );
-	#ifndef _EDITOR
-				if(key==DIK_TAB  && (iGetAsyncKeyState(DIK_RMENU) || iGetAsyncKeyState(DIK_LMENU)) )
-					b_alt_tab = true;
-	#endif
-			}
-		}
-
-		for ( i = 0; i < COUNT_KB_BUTTONS; i++ )
-			if (KBState[i]) 
-				cbStack.back()->IR_OnKeyboardHold( i );
-	}
+    if (b_altF4) return;
 
 #ifndef _EDITOR
-	if(b_alt_tab)
-		SendMessage(Device.m_hWnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);
+    if (Device.dwPrecacheFrame == 0)
 #endif
-/*
+    {
+
+        for (u32 i = 0; i < dwElements; i++)
+        {
+            if (od[i].uAppData == 666) //ignored action
+                continue;
+
+            key = od[i].dwOfs;
+            if (od[i].dwData & 0x80)
+                cbStack.back()->IR_OnKeyboardPress(key);
+            else
+            {
+                cbStack.back()->IR_OnKeyboardRelease(key);
 #ifndef _EDITOR
-//update xinput if exist
-    for( DWORD iUserIndex=0; iUserIndexIR_OnMousePress(0);
-			else
-				cbStack.back()->IR_OnMouseRelease(0);
-		}
-		int dx,dy;
-		dx = iFloor(g_GamePads[iUserIndex].fThumbRX*6);
-		dy = iFloor(g_GamePads[iUserIndex].fThumbRY*6);
-		if(dx || dy)
-			cbStack.back()->IR_OnMouseMove	( dx, dy );
-	}
-
-	if(Device.fTimeGlobal > stop_vibration_time)
-	{
-		stop_vibration_time		= flt_max;
-		set_vibration			(0, 0);
-	}
-//xinput
+                if (key == DIK_TAB && (iGetAsyncKeyState(DIK_RMENU) || iGetAsyncKeyState(DIK_LMENU)))
+                    b_alt_tab = true;
+#endif
+            }
+        }
+
+        for (i = 0; i < COUNT_KB_BUTTONS; i++)
+            if (KBState[i])
+                cbStack.back()->IR_OnKeyboardHold(i);
+    }
+
+#ifndef _EDITOR
+    if (b_alt_tab)
+        SendMessage(Device.m_hWnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);
 #endif
-*/
+    /*
+    #ifndef _EDITOR
+    //update xinput if exist
+    for( DWORD iUserIndex=0; iUserIndexIR_OnMousePress(0);
+    else
+    cbStack.back()->IR_OnMouseRelease(0);
+    }
+    int dx,dy;
+    dx = iFloor(g_GamePads[iUserIndex].fThumbRX*6);
+    dy = iFloor(g_GamePads[iUserIndex].fThumbRY*6);
+    if(dx || dy)
+    cbStack.back()->IR_OnMouseMove ( dx, dy );
+    }
+
+    if(Device.fTimeGlobal > stop_vibration_time)
+    {
+    stop_vibration_time = flt_max;
+    set_vibration (0, 0);
+    }
+    //xinput
+    #endif
+    */
 }
 bool CInput::get_dik_name(int dik, LPSTR dest_str, int dest_sz)
 {
-	DIPROPSTRING keyname;
-	keyname.diph.dwSize			= sizeof(DIPROPSTRING);
-	keyname.diph.dwHeaderSize	= sizeof(DIPROPHEADER);
-	keyname.diph.dwObj			= static_cast(dik);
-	keyname.diph.dwHow			= DIPH_BYOFFSET;
-	HRESULT hr = pKeyboard->GetProperty(DIPROP_KEYNAME, &keyname.diph);
-	if(FAILED(hr))
-		return false;
-
-	const wchar_t* wct			= keyname.wsz;
-	if(0==wcslen(wct))
-		return					false;
-	
-	int cnt						= WideCharToMultiByte(CP_ACP,0,keyname.wsz,-1,dest_str,dest_sz,NULL,NULL);
-	if(cnt==-1)
-	{
-		Msg("! cant convert dik_name for dik[%d], prop=[%S]", dik, keyname.wsz);
-		return					false;
-	}
-	return						(cnt!=-1);
+    DIPROPSTRING keyname;
+    keyname.diph.dwSize = sizeof(DIPROPSTRING);
+    keyname.diph.dwHeaderSize = sizeof(DIPROPHEADER);
+    keyname.diph.dwObj = static_cast(dik);
+    keyname.diph.dwHow = DIPH_BYOFFSET;
+    HRESULT hr = pKeyboard->GetProperty(DIPROP_KEYNAME, &keyname.diph);
+    if (FAILED(hr))
+        return false;
+
+    const wchar_t* wct = keyname.wsz;
+    if (0 == wcslen(wct))
+        return false;
+
+    int cnt = WideCharToMultiByte(CP_ACP, 0, keyname.wsz, -1, dest_str, dest_sz, NULL, NULL);
+    if (cnt == -1)
+    {
+        Msg("! cant convert dik_name for dik[%d], prop=[%S]", dik, keyname.wsz);
+        return false;
+    }
+    return (cnt != -1);
 }
 
-#define MOUSE_1		(0xED + 100)
-#define MOUSE_8		(0xED + 107)
+#define MOUSE_1 (0xED + 100)
+#define MOUSE_8 (0xED + 107)
 
-BOOL CInput::iGetAsyncKeyState( int dik )
+BOOL CInput::iGetAsyncKeyState(int dik)
 {
-	if(dik=MOUSE_1 && dik<=MOUSE_8)
-	{
-		int mk = dik-MOUSE_1;
-		return iGetAsyncBtnState(mk);
-	}else
-		return FALSE; //unknown key ???
+    if (dik < COUNT_KB_BUTTONS)
+        return !!KBState[dik];
+    else if (dik >= MOUSE_1 && dik <= MOUSE_8)
+    {
+        int mk = dik - MOUSE_1;
+        return iGetAsyncBtnState(mk);
+    }
+    else
+        return FALSE; //unknown key ???
 }
 
-BOOL CInput::iGetAsyncBtnState( int btn )
+BOOL CInput::iGetAsyncBtnState(int btn)
 {
-	return !!mouseState[btn];
+    return !!mouseState[btn];
 }
 
-void CInput::MouseUpdate( )
+void CInput::MouseUpdate()
 {
-	HRESULT hr;
-	DWORD dwElements	= MOUSEBUFFERSIZE;
-	DIDEVICEOBJECTDATA	od[MOUSEBUFFERSIZE];
-
-	VERIFY(pMouse);
-
-	hr = pMouse->GetDeviceData( sizeof(DIDEVICEOBJECTDATA), &od[0], &dwElements, 0 );
-	if (( hr == DIERR_INPUTLOST )||( hr == DIERR_NOTACQUIRED )){
-		hr = pMouse->Acquire();
-		if ( hr != S_OK ) return;
-		hr = pMouse->GetDeviceData( sizeof(DIDEVICEOBJECTDATA), &od[0], &dwElements, 0 );
-		if ( hr != S_OK ) return;
-	};
-
-	#ifndef _EDITOR
-	if(Device.dwPrecacheFrame)
-		return;
-    #endif
-	BOOL				mouse_prev[COUNT_MOUSE_BUTTONS];
-
-	mouse_prev[0]		= mouseState[0];
-	mouse_prev[1]		= mouseState[1];
-	mouse_prev[2]		= mouseState[2];
-	mouse_prev[3]		= mouseState[3];
-	mouse_prev[4]		= mouseState[4];
-	mouse_prev[5]		= mouseState[5];
-	mouse_prev[6]		= mouseState[6];
-	mouse_prev[7]		= mouseState[7];
-
-	offs[0] = offs[1] = offs[2] = 0;
-	for (u32 i = 0; i < dwElements; i++){
-		switch (od[i].dwOfs){
-		case DIMOFS_X:	offs[0]	+= od[i].dwData; timeStamp[0] = od[i].dwTimeStamp;	break;
-		case DIMOFS_Y:	offs[1]	+= od[i].dwData; timeStamp[1] = od[i].dwTimeStamp;	break;
-		case DIMOFS_Z:	offs[2]	+= od[i].dwData; timeStamp[2] = od[i].dwTimeStamp;	break;
-		case DIMOFS_BUTTON0:
-			if ( od[i].dwData & 0x80 )	
-			{ mouseState[0] = TRUE;				cbStack.back()->IR_OnMousePress(0);		}
-			if ( !(od[i].dwData & 0x80))
-			{ mouseState[0] = FALSE;			cbStack.back()->IR_OnMouseRelease(0);	}
-			break;
-		case DIMOFS_BUTTON1:
-			if ( od[i].dwData & 0x80 )	
-			{ mouseState[1] = TRUE;				cbStack.back()->IR_OnMousePress(1);		}
-			if ( !(od[i].dwData & 0x80))
-			{ mouseState[1] = FALSE;			cbStack.back()->IR_OnMouseRelease(1);	}
-			break;
-		case DIMOFS_BUTTON2:
-			if ( od[i].dwData & 0x80 )	
-			{ mouseState[2] = TRUE;				cbStack.back()->IR_OnMousePress(2);		}
-			if ( !(od[i].dwData & 0x80))
-			{ mouseState[2] = FALSE;			cbStack.back()->IR_OnMouseRelease(2);	}
-			break;
-		case DIMOFS_BUTTON3:
-			if ( od[i].dwData & 0x80 )	
-			{ mouseState[3] = TRUE;				cbStack.back()->IR_OnKeyboardPress(0xED + 103);		}
-			if ( !(od[i].dwData & 0x80))
-			{ mouseState[3] = FALSE;			cbStack.back()->IR_OnKeyboardRelease(0xED + 103);	}
-			break;
-		case DIMOFS_BUTTON4:
-			if ( od[i].dwData & 0x80 )	
-			{ mouseState[4] = TRUE;				cbStack.back()->IR_OnKeyboardPress(0xED + 104);		}
-			if ( !(od[i].dwData & 0x80))
-			{ mouseState[4] = FALSE;			cbStack.back()->IR_OnKeyboardRelease(0xED + 104);	}
-			break;
-		case DIMOFS_BUTTON5:
-			if ( od[i].dwData & 0x80 )	
-			{ mouseState[5] = TRUE;				cbStack.back()->IR_OnKeyboardPress(0xED + 105);		}
-			if ( !(od[i].dwData & 0x80))
-			{ mouseState[5] = FALSE;			cbStack.back()->IR_OnKeyboardRelease(0xED + 105);	}
-			break;
-		case DIMOFS_BUTTON6:
-			if ( od[i].dwData & 0x80 )	
-			{ mouseState[6] = TRUE;				cbStack.back()->IR_OnKeyboardPress(0xED + 106);		}
-			if ( !(od[i].dwData & 0x80))
-			{ mouseState[6] = FALSE;			cbStack.back()->IR_OnKeyboardRelease(0xED + 106);	}
-			break;
-		case DIMOFS_BUTTON7:
-			if ( od[i].dwData & 0x80 )	
-			{ mouseState[7] = TRUE;				cbStack.back()->IR_OnKeyboardPress(0xED + 107);		}
-			if ( !(od[i].dwData & 0x80))
-			{ mouseState[7] = FALSE;			cbStack.back()->IR_OnKeyboardRelease(0xED + 107);	}
-			break;
-		}
-	}
-
-	if (mouseState[0] && mouse_prev[0])
-	{
-		cbStack.back()->IR_OnMouseHold(0);
-	}
-
-	if (mouseState[1] && mouse_prev[1])		
-	{
-		cbStack.back()->IR_OnMouseHold(1);
-	}
-
-	if (mouseState[2] && mouse_prev[2])		
-	{
-		cbStack.back()->IR_OnMouseHold(2);
-	}
-	if ( dwElements ){
-		if (offs[0] || offs[1]) cbStack.back()->IR_OnMouseMove	( offs[0], offs[1] );
-		if (offs[2])			cbStack.back()->IR_OnMouseWheel	( offs[2] );
-	} else {
-		if (timeStamp[1] && ((dwCurTime-timeStamp[1])>=mouse_property.mouse_dt))	cbStack.back()->IR_OnMouseStop(DIMOFS_Y, timeStamp[1] = 0);
-		if (timeStamp[0] && ((dwCurTime-timeStamp[0])>=mouse_property.mouse_dt))	cbStack.back()->IR_OnMouseStop(DIMOFS_X, timeStamp[0] = 0);
-	}
+    HRESULT hr;
+    DWORD dwElements = MOUSEBUFFERSIZE;
+    DIDEVICEOBJECTDATA od[MOUSEBUFFERSIZE];
+
+    VERIFY(pMouse);
+
+    hr = pMouse->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), &od[0], &dwElements, 0);
+    if ((hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED))
+    {
+        hr = pMouse->Acquire();
+        if (hr != S_OK) return;
+        hr = pMouse->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), &od[0], &dwElements, 0);
+        if (hr != S_OK) return;
+    };
+
+#ifndef _EDITOR
+    if (Device.dwPrecacheFrame)
+        return;
+#endif
+    BOOL mouse_prev[COUNT_MOUSE_BUTTONS];
+
+    mouse_prev[0] = mouseState[0];
+    mouse_prev[1] = mouseState[1];
+    mouse_prev[2] = mouseState[2];
+    mouse_prev[3] = mouseState[3];
+    mouse_prev[4] = mouseState[4];
+    mouse_prev[5] = mouseState[5];
+    mouse_prev[6] = mouseState[6];
+    mouse_prev[7] = mouseState[7];
+
+    offs[0] = offs[1] = offs[2] = 0;
+    for (u32 i = 0; i < dwElements; i++)
+    {
+        switch (od[i].dwOfs)
+        {
+        case DIMOFS_X:
+            offs[0] += od[i].dwData;
+            timeStamp[0] = od[i].dwTimeStamp;
+            break;
+        case DIMOFS_Y:
+            offs[1] += od[i].dwData;
+            timeStamp[1] = od[i].dwTimeStamp;
+            break;
+        case DIMOFS_Z:
+            offs[2] += od[i].dwData;
+            timeStamp[2] = od[i].dwTimeStamp;
+            break;
+        case DIMOFS_BUTTON0:
+            if (od[i].dwData & 0x80)
+            {
+                mouseState[0] = TRUE;
+                cbStack.back()->IR_OnMousePress(0);
+            }
+            if (!(od[i].dwData & 0x80))
+            {
+                mouseState[0] = FALSE;
+                cbStack.back()->IR_OnMouseRelease(0);
+            }
+            break;
+        case DIMOFS_BUTTON1:
+            if (od[i].dwData & 0x80)
+            {
+                mouseState[1] = TRUE;
+                cbStack.back()->IR_OnMousePress(1);
+            }
+            if (!(od[i].dwData & 0x80))
+            {
+                mouseState[1] = FALSE;
+                cbStack.back()->IR_OnMouseRelease(1);
+            }
+            break;
+        case DIMOFS_BUTTON2:
+            if (od[i].dwData & 0x80)
+            {
+                mouseState[2] = TRUE;
+                cbStack.back()->IR_OnMousePress(2);
+            }
+            if (!(od[i].dwData & 0x80))
+            {
+                mouseState[2] = FALSE;
+                cbStack.back()->IR_OnMouseRelease(2);
+            }
+            break;
+        case DIMOFS_BUTTON3:
+            if (od[i].dwData & 0x80)
+            {
+                mouseState[3] = TRUE;
+                cbStack.back()->IR_OnKeyboardPress(0xED + 103);
+            }
+            if (!(od[i].dwData & 0x80))
+            {
+                mouseState[3] = FALSE;
+                cbStack.back()->IR_OnKeyboardRelease(0xED + 103);
+            }
+            break;
+        case DIMOFS_BUTTON4:
+            if (od[i].dwData & 0x80)
+            {
+                mouseState[4] = TRUE;
+                cbStack.back()->IR_OnKeyboardPress(0xED + 104);
+            }
+            if (!(od[i].dwData & 0x80))
+            {
+                mouseState[4] = FALSE;
+                cbStack.back()->IR_OnKeyboardRelease(0xED + 104);
+            }
+            break;
+        case DIMOFS_BUTTON5:
+            if (od[i].dwData & 0x80)
+            {
+                mouseState[5] = TRUE;
+                cbStack.back()->IR_OnKeyboardPress(0xED + 105);
+            }
+            if (!(od[i].dwData & 0x80))
+            {
+                mouseState[5] = FALSE;
+                cbStack.back()->IR_OnKeyboardRelease(0xED + 105);
+            }
+            break;
+        case DIMOFS_BUTTON6:
+            if (od[i].dwData & 0x80)
+            {
+                mouseState[6] = TRUE;
+                cbStack.back()->IR_OnKeyboardPress(0xED + 106);
+            }
+            if (!(od[i].dwData & 0x80))
+            {
+                mouseState[6] = FALSE;
+                cbStack.back()->IR_OnKeyboardRelease(0xED + 106);
+            }
+            break;
+        case DIMOFS_BUTTON7:
+            if (od[i].dwData & 0x80)
+            {
+                mouseState[7] = TRUE;
+                cbStack.back()->IR_OnKeyboardPress(0xED + 107);
+            }
+            if (!(od[i].dwData & 0x80))
+            {
+                mouseState[7] = FALSE;
+                cbStack.back()->IR_OnKeyboardRelease(0xED + 107);
+            }
+            break;
+        }
+    }
+
+    if (mouseState[0] && mouse_prev[0])
+    {
+        cbStack.back()->IR_OnMouseHold(0);
+    }
+
+    if (mouseState[1] && mouse_prev[1])
+    {
+        cbStack.back()->IR_OnMouseHold(1);
+    }
+
+    if (mouseState[2] && mouse_prev[2])
+    {
+        cbStack.back()->IR_OnMouseHold(2);
+    }
+    if (dwElements)
+    {
+        if (offs[0] || offs[1]) cbStack.back()->IR_OnMouseMove(offs[0], offs[1]);
+        if (offs[2]) cbStack.back()->IR_OnMouseWheel(offs[2]);
+    }
+    else
+    {
+        if (timeStamp[1] && ((dwCurTime - timeStamp[1]) >= mouse_property.mouse_dt)) cbStack.back()->IR_OnMouseStop(DIMOFS_Y, timeStamp[1] = 0);
+        if (timeStamp[0] && ((dwCurTime - timeStamp[0]) >= mouse_property.mouse_dt)) cbStack.back()->IR_OnMouseStop(DIMOFS_X, timeStamp[0] = 0);
+    }
 }
 
 //-------------------------------------------------------
-void CInput::iCapture(IInputReceiver *p)
+void CInput::iCapture(IInputReceiver* p)
 {
-	VERIFY(p);
-	if (pMouse) 	MouseUpdate();
-    if (pKeyboard) 	KeyUpdate();
+    VERIFY(p);
+    if (pMouse) MouseUpdate();
+    if (pKeyboard) KeyUpdate();
 
     // change focus
-	if (!cbStack.empty())
-		cbStack.back()->IR_OnDeactivate();
-	cbStack.push_back(p);
-	cbStack.back()->IR_OnActivate();
-
-	// prepare for _new_ controller
-	ZeroMemory			( timeStamp,	sizeof(timeStamp) );
-	ZeroMemory			( timeSave,		sizeof(timeStamp) );
-	ZeroMemory			( offs,			sizeof(offs) );
+    if (!cbStack.empty())
+        cbStack.back()->IR_OnDeactivate();
+    cbStack.push_back(p);
+    cbStack.back()->IR_OnActivate();
+
+    // prepare for _new_ controller
+    ZeroMemory(timeStamp, sizeof(timeStamp));
+    ZeroMemory(timeSave, sizeof(timeStamp));
+    ZeroMemory(offs, sizeof(offs));
 }
 
-void CInput::iRelease(IInputReceiver *p)
+void CInput::iRelease(IInputReceiver* p)
 {
-	if (p == cbStack.back())
-	{
-		cbStack.back()->IR_OnDeactivate();
-		cbStack.pop_back();
-		IInputReceiver * ir = cbStack.back();
-		ir->IR_OnActivate();
-	}else{// we are not topmost receiver, so remove the nearest one
-		u32 cnt = cbStack.size();
-		for(;cnt>0;--cnt)
-			if( cbStack[cnt-1] == p ){
-				xr_vector::iterator it = cbStack.begin();
-				std::advance	(it,cnt-1);
-				cbStack.erase	(it);
-				break;
-			}
-	}
+    if (p == cbStack.back())
+    {
+        cbStack.back()->IR_OnDeactivate();
+        cbStack.pop_back();
+        IInputReceiver* ir = cbStack.back();
+        ir->IR_OnActivate();
+    }
+    else
+    {
+        // we are not topmost receiver, so remove the nearest one
+        u32 cnt = cbStack.size();
+        for (; cnt > 0; --cnt)
+            if (cbStack[cnt - 1] == p)
+            {
+                xr_vector::iterator it = cbStack.begin();
+                std::advance(it, cnt - 1);
+                cbStack.erase(it);
+                break;
+            }
+    }
 }
 
-void CInput::OnAppActivate		(void)
+void CInput::OnAppActivate(void)
 {
-	if (CurrentIR())
-		CurrentIR()->IR_OnActivate();
-
-	SetAllAcquire	( true );
-	ZeroMemory		( mouseState,	sizeof(mouseState) );
-	ZeroMemory		( KBState,		sizeof(KBState) );
-	ZeroMemory		( timeStamp,	sizeof(timeStamp) );
-	ZeroMemory		( timeSave,		sizeof(timeStamp) );
-	ZeroMemory		( offs,			sizeof(offs) );
+    if (CurrentIR())
+        CurrentIR()->IR_OnActivate();
+
+    SetAllAcquire(true);
+    ZeroMemory(mouseState, sizeof(mouseState));
+    ZeroMemory(KBState, sizeof(KBState));
+    ZeroMemory(timeStamp, sizeof(timeStamp));
+    ZeroMemory(timeSave, sizeof(timeStamp));
+    ZeroMemory(offs, sizeof(offs));
 }
 
-void CInput::OnAppDeactivate	(void)
+void CInput::OnAppDeactivate(void)
 {
-	if (CurrentIR())
-		CurrentIR()->IR_OnDeactivate();
-
-	SetAllAcquire	( false );
-	ZeroMemory		( mouseState,	sizeof(mouseState) );
-	ZeroMemory		( KBState,		sizeof(KBState) );
-	ZeroMemory		( timeStamp,	sizeof(timeStamp) );
-	ZeroMemory		( timeSave,		sizeof(timeStamp) );
-	ZeroMemory		( offs,			sizeof(offs) );
+    if (CurrentIR())
+        CurrentIR()->IR_OnDeactivate();
+
+    SetAllAcquire(false);
+    ZeroMemory(mouseState, sizeof(mouseState));
+    ZeroMemory(KBState, sizeof(KBState));
+    ZeroMemory(timeStamp, sizeof(timeStamp));
+    ZeroMemory(timeSave, sizeof(timeStamp));
+    ZeroMemory(offs, sizeof(offs));
 }
 
-void CInput::OnFrame			(void)
+void CInput::OnFrame(void)
 {
-	RDEVICE.Statistic->Input.Begin			();
-	dwCurTime		= RDEVICE.TimerAsync_MMT	();
-	if (pKeyboard)	KeyUpdate				();
-	if (pMouse)		MouseUpdate				();
-	RDEVICE.Statistic->Input.End			();
+    RDEVICE.Statistic->Input.Begin();
+    dwCurTime = RDEVICE.TimerAsync_MMT();
+    if (pKeyboard) KeyUpdate();
+    if (pMouse) MouseUpdate();
+    RDEVICE.Statistic->Input.End();
 }
 
-IInputReceiver*	 CInput::CurrentIR()
+IInputReceiver* CInput::CurrentIR()
 {
-	if(cbStack.size())
-		return cbStack.back();
-	else
-		return NULL;
+    if (cbStack.size())
+        return cbStack.back();
+    else
+        return NULL;
 }
 
-void CInput::unacquire				()
+void CInput::unacquire()
 {
-	pKeyboard->Unacquire			();
-	pMouse->Unacquire				();
+    pKeyboard->Unacquire();
+    pMouse->Unacquire();
 }
 
-void CInput::acquire				(const bool &exclusive)
+void CInput::acquire(const bool& exclusive)
 {
-	pKeyboard->SetCooperativeLevel	(
+    pKeyboard->SetCooperativeLevel(
 #ifdef INGAME_EDITOR
-		Device.editor() ? Device.editor()->main_handle() : 
+        Device.editor() ? Device.editor()->main_handle() :
 #endif // #ifdef INGAME_EDITOR
-		RDEVICE.m_hWnd,
-		(exclusive ? DISCL_EXCLUSIVE : DISCL_NONEXCLUSIVE) | DISCL_FOREGROUND
-	);
-	pKeyboard->Acquire				();
+        RDEVICE.m_hWnd,
+        (exclusive ? DISCL_EXCLUSIVE : DISCL_NONEXCLUSIVE) | DISCL_FOREGROUND
+    );
+    pKeyboard->Acquire();
 
-	pMouse->SetCooperativeLevel		(
+    pMouse->SetCooperativeLevel(
 #ifdef INGAME_EDITOR
-		Device.editor() ? Device.editor()->main_handle() :
+        Device.editor() ? Device.editor()->main_handle() :
 #endif // #ifdef INGAME_EDITOR
-		RDEVICE.m_hWnd,
-		(exclusive ? DISCL_EXCLUSIVE : DISCL_NONEXCLUSIVE) | DISCL_FOREGROUND | DISCL_NOWINKEY
-	);
-	pMouse->Acquire					();
+        RDEVICE.m_hWnd,
+        (exclusive ? DISCL_EXCLUSIVE : DISCL_NONEXCLUSIVE) | DISCL_FOREGROUND | DISCL_NOWINKEY
+    );
+    pMouse->Acquire();
 }
 
-void CInput::exclusive_mode			(const bool &exclusive)
+void CInput::exclusive_mode(const bool& exclusive)
 {
-	g_exclusive						= exclusive;
-	unacquire						();
-	acquire							(exclusive);
+    g_exclusive = exclusive;
+    unacquire();
+    acquire(exclusive);
 }
-bool CInput::get_exclusive_mode		()
+bool CInput::get_exclusive_mode()
 {
-	return g_exclusive;
+    return g_exclusive;
 }
 
-void  CInput::feedback(u16 s1, u16 s2, float time)
+void CInput::feedback(u16 s1, u16 s2, float time)
 {
-	stop_vibration_time = RDEVICE.fTimeGlobal + time;
+    stop_vibration_time = RDEVICE.fTimeGlobal + time;
 #ifndef _EDITOR
-//.	set_vibration (s1, s2);
+    //. set_vibration (s1, s2);
 #endif
 }
diff --git a/src/xrEngine/_d3d_extensions.h b/src/xrEngine/_d3d_extensions.h
index dc48487ffd8..284aa502be2 100644
--- a/src/xrEngine/_d3d_extensions.h
+++ b/src/xrEngine/_d3d_extensions.h
@@ -2,38 +2,39 @@
 #define _D3D_EXT_internal
 
 #ifndef NO_XR_LIGHT
-struct Flight 
+struct Flight
 {
 public:
-    u32           type;             /* Type of light source */
-    Fcolor          diffuse;          /* Diffuse color of light */
-    Fcolor          specular;         /* Specular color of light */
-    Fcolor          ambient;          /* Ambient color of light */
-    Fvector         position;         /* Position in world space */
-    Fvector         direction;        /* Direction in world space */
-    float		    range;            /* Cutoff range */
-    float	        falloff;          /* Falloff */
-    float	        attenuation0;     /* Constant attenuation */
-    float	        attenuation1;     /* Linear attenuation */
-    float	        attenuation2;     /* Quadratic attenuation */
-    float	        theta;            /* Inner angle of spotlight cone */
-    float	        phi;              /* Outer angle of spotlight cone */
+    u32 type; /* Type of light source */
+    Fcolor diffuse; /* Diffuse color of light */
+    Fcolor specular; /* Specular color of light */
+    Fcolor ambient; /* Ambient color of light */
+    Fvector position; /* Position in world space */
+    Fvector direction; /* Direction in world space */
+    float range; /* Cutoff range */
+    float falloff; /* Falloff */
+    float attenuation0; /* Constant attenuation */
+    float attenuation1; /* Linear attenuation */
+    float attenuation2; /* Quadratic attenuation */
+    float theta; /* Inner angle of spotlight cone */
+    float phi; /* Outer angle of spotlight cone */
 
-	IC	void		set	(u32 ltType, float x, float y, float z)
-	{
-		ZeroMemory( this, sizeof(Flight) );
-		type=ltType;
-		diffuse.set(1.0f, 1.0f, 1.0f, 1.0f);
-		specular.set(diffuse);
-		position.set(x,y,z);
-		direction.set(x,y,z);
-		direction.normalize_safe();
-		range= _sqrt(flt_max);
-	}
-    IC	void		mul		(float brightness){
-	    diffuse.mul_rgb		(brightness);
-    	ambient.mul_rgb		(brightness);
-	    specular.mul_rgb	(brightness);
+    IC void set(u32 ltType, float x, float y, float z)
+    {
+        ZeroMemory(this, sizeof(Flight));
+        type = ltType;
+        diffuse.set(1.0f, 1.0f, 1.0f, 1.0f);
+        specular.set(diffuse);
+        position.set(x, y, z);
+        direction.set(x, y, z);
+        direction.normalize_safe();
+        range = _sqrt(flt_max);
+    }
+    IC void mul(float brightness)
+    {
+        diffuse.mul_rgb(brightness);
+        ambient.mul_rgb(brightness);
+        specular.mul_rgb(brightness);
     }
 };
 
@@ -49,43 +50,43 @@ struct Flight
 struct Fmaterial
 {
 public:
-    Fcolor			diffuse;        /* Diffuse color RGBA */
-    Fcolor			ambient;        /* Ambient color RGB */
-    Fcolor		    specular;       /* Specular 'shininess' */
-    Fcolor			emissive;       /* Emissive color RGB */
-    float			power;          /* Sharpness if specular highlight */
+    Fcolor diffuse; /* Diffuse color RGBA */
+    Fcolor ambient; /* Ambient color RGB */
+    Fcolor specular; /* Specular 'shininess' */
+    Fcolor emissive; /* Emissive color RGB */
+    float power; /* Sharpness if specular highlight */
 
-	IC	void		set	(float r, float g, float b)
-	{
-		ZeroMemory	(this, sizeof(Fmaterial));
-		diffuse.r = ambient.r = r;
-		diffuse.g = ambient.g = g;
-		diffuse.b = ambient.b = b;
-		diffuse.a = ambient.a = 1.0f;
-		power	  = 0;
-	}
-	IC	void	set(float r, float g, float b, float a)
-	{
-		ZeroMemory	(this, sizeof(Fmaterial));
-		diffuse.r = ambient.r = r;
-		diffuse.g = ambient.g = g;
-		diffuse.b = ambient.b = b;
-		diffuse.a = ambient.a = a;
-		power	  = 0;
-	}
-	IC	void	set	(Fcolor &c)
-	{
-		ZeroMemory	( this, sizeof(Fmaterial) );
-		diffuse.r = ambient.r = c.r;
-		diffuse.g = ambient.g = c.g;
-		diffuse.b = ambient.b = c.b;
-		diffuse.a = ambient.a = c.a;
-		power	  = 0;
-	}
+    IC void set(float r, float g, float b)
+    {
+        ZeroMemory(this, sizeof(Fmaterial));
+        diffuse.r = ambient.r = r;
+        diffuse.g = ambient.g = g;
+        diffuse.b = ambient.b = b;
+        diffuse.a = ambient.a = 1.0f;
+        power = 0;
+    }
+    IC void set(float r, float g, float b, float a)
+    {
+        ZeroMemory(this, sizeof(Fmaterial));
+        diffuse.r = ambient.r = r;
+        diffuse.g = ambient.g = g;
+        diffuse.b = ambient.b = b;
+        diffuse.a = ambient.a = a;
+        power = 0;
+    }
+    IC void set(Fcolor& c)
+    {
+        ZeroMemory(this, sizeof(Fmaterial));
+        diffuse.r = ambient.r = c.r;
+        diffuse.g = ambient.g = c.g;
+        diffuse.b = ambient.b = c.b;
+        diffuse.a = ambient.a = c.a;
+        power = 0;
+    }
 };
 
 /*
-#if sizeof(Fmaterial)!=sizeof(D3DMATERIAL9) 
+#if sizeof(Fmaterial)!=sizeof(D3DMATERIAL9)
 #error Different structure size
 #endif
 */
@@ -93,28 +94,28 @@ struct Fmaterial
 #endif
 
 #ifndef NO_XR_VDECLARATOR
-struct	VDeclarator	: public svector
+struct VDeclarator : public svector < D3DVERTEXELEMENT9, MAXD3DDECLLENGTH + 1 >
 {
-	void	set		(u32 FVF)
-	{
-		D3DXDeclaratorFromFVF	(FVF,begin());
-		resize					(D3DXGetDeclLength(begin())+1);
-	}
-	void	set		(D3DVERTEXELEMENT9* dcl)
-	{
-		resize					(D3DXGetDeclLength(dcl)+1);
-		CopyMemory				(begin(),dcl,size()*sizeof(D3DVERTEXELEMENT9));
-	}
-	void	set		(const VDeclarator& d)
-	{
-		*this		= d;
-	}
-	u32		vertex	()				{ return D3DXGetDeclVertexSize(begin(),0);	}
-	BOOL	equal	(VDeclarator& d)
-	{
-		if (size()!=d.size())	return false;
-		else					return 0==memcmp(begin(),d.begin(),size()*sizeof(D3DVERTEXELEMENT9));
-	}
+    void set(u32 FVF)
+    {
+        D3DXDeclaratorFromFVF(FVF, begin());
+        resize(D3DXGetDeclLength(begin()) + 1);
+    }
+    void set(D3DVERTEXELEMENT9* dcl)
+    {
+        resize(D3DXGetDeclLength(dcl) + 1);
+        CopyMemory(begin(), dcl, size()*sizeof(D3DVERTEXELEMENT9));
+    }
+    void set(const VDeclarator& d)
+    {
+        *this = d;
+    }
+    u32 vertex() { return D3DXGetDeclVertexSize(begin(), 0); }
+    BOOL equal(VDeclarator& d)
+    {
+        if (size() != d.size()) return false;
+        else return 0 == memcmp(begin(), d.begin(), size()*sizeof(D3DVERTEXELEMENT9));
+    }
 };
 #endif
 
diff --git a/src/xrEngine/_scripting.cpp b/src/xrEngine/_scripting.cpp
index a35a8e38cc3..c74db5fb72b 100644
--- a/src/xrEngine/_scripting.cpp
+++ b/src/xrEngine/_scripting.cpp
@@ -1,10 +1,11 @@
 #include "stdafx.h"
 
 // Dima needs this because we have to exclude option /EHsc (exception handling) from the project
-namespace boost {
-//	void  throw_exception(const std::exception &A)
-//	{
-//		Debug.fatal(DEBUG_INFO,"Boost exception raised");
-//	}
+namespace boost
+{
+// void throw_exception(const std::exception &A)
+// {
+// Debug.fatal(DEBUG_INFO,"Boost exception raised");
+// }
 };
 
diff --git a/src/xrEngine/ai_script_lua_debug.cpp b/src/xrEngine/ai_script_lua_debug.cpp
index bbe10beb067..7a4612c50aa 100644
--- a/src/xrEngine/ai_script_lua_debug.cpp
+++ b/src/xrEngine/ai_script_lua_debug.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: ai_script_lua_debug.cpp
-//	Created 	: 19.09.2003
-//  Modified 	: 19.09.2003
-//	Author		: Dmitriy Iassenev
-//	Description : XRay Script debugging system
+// Module : ai_script_lua_debug.cpp
+// Created : 19.09.2003
+// Modified : 19.09.2003
+// Author : Dmitriy Iassenev
+// Description : XRay Script debugging system
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -12,117 +12,139 @@
 
 using namespace Script;
 
-bool Script::bfPrintOutput(CLuaVirtualMachine *tpLuaVirtualMachine, LPCSTR caScriptFileName, int iErorCode)
+bool Script::bfPrintOutput(CLuaVirtualMachine* tpLuaVirtualMachine, LPCSTR caScriptFileName, int iErorCode)
 {
-	for (int i=-1; ; --i)
-		if (lua_isstring(tpLuaVirtualMachine,i)) {
-			LPCSTR	S = lua_tostring(tpLuaVirtualMachine,i);
-			if (!xr_strcmp(S,"cannot resume dead coroutine")) {
-				LuaOut	(Lua::eLuaMessageTypeInfo,"Script %s is finished",caScriptFileName);
-				return	(true);
-			}
-			else {
-				if (!i && !iErorCode)
-					LuaOut	(Lua::eLuaMessageTypeInfo,"Output from %s",caScriptFileName);
-				LuaOut	(iErorCode ? Lua::eLuaMessageTypeError : Lua::eLuaMessageTypeMessage,"%s",S);
-			}
-		}
-		else {
-			for ( i=0; ; ++i)
-				if (lua_isstring(tpLuaVirtualMachine,i)) {
-					LPCSTR	S = lua_tostring(tpLuaVirtualMachine,i);
-					if (!xr_strcmp(S,"cannot resume dead coroutine")) {
-						LuaOut	(Lua::eLuaMessageTypeInfo,"Script %s is finished",caScriptFileName);
-						return	(true);
-					}
-					else {
-						if (!i && !iErorCode)
-							LuaOut	(Lua::eLuaMessageTypeInfo,"Output from %s",caScriptFileName);
-						LuaOut	(iErorCode ? Lua::eLuaMessageTypeError : Lua::eLuaMessageTypeMessage,"%s",S);
-					}
-				}
-				else
-					return		(false);
-		}
+    for (int i = -1;; --i)
+        if (lua_isstring(tpLuaVirtualMachine, i))
+        {
+            LPCSTR S = lua_tostring(tpLuaVirtualMachine, i);
+            if (!xr_strcmp(S, "cannot resume dead coroutine"))
+            {
+                LuaOut(Lua::eLuaMessageTypeInfo, "Script %s is finished", caScriptFileName);
+                return (true);
+            }
+            else
+            {
+                if (!i && !iErorCode)
+                    LuaOut(Lua::eLuaMessageTypeInfo, "Output from %s", caScriptFileName);
+                LuaOut(iErorCode ? Lua::eLuaMessageTypeError : Lua::eLuaMessageTypeMessage, "%s", S);
+            }
+        }
+        else
+        {
+            for (i = 0;; ++i)
+                if (lua_isstring(tpLuaVirtualMachine, i))
+                {
+                    LPCSTR S = lua_tostring(tpLuaVirtualMachine, i);
+                    if (!xr_strcmp(S, "cannot resume dead coroutine"))
+                    {
+                        LuaOut(Lua::eLuaMessageTypeInfo, "Script %s is finished", caScriptFileName);
+                        return (true);
+                    }
+                    else
+                    {
+                        if (!i && !iErorCode)
+                            LuaOut(Lua::eLuaMessageTypeInfo, "Output from %s", caScriptFileName);
+                        LuaOut(iErorCode ? Lua::eLuaMessageTypeError : Lua::eLuaMessageTypeMessage, "%s", S);
+                    }
+                }
+                else
+                    return (false);
+        }
 }
 
-void Script::vfPrintError(CLuaVirtualMachine *tpLuaVirtualMachine, int iErrorCode)
+void Script::vfPrintError(CLuaVirtualMachine* tpLuaVirtualMachine, int iErrorCode)
 {
-	switch (iErrorCode) {
-		case LUA_ERRRUN : {
-			Msg ("! SCRIPT RUNTIME ERROR");
-			break;
-		}
-		case LUA_ERRMEM : {
-			Msg ("! SCRIPT ERROR (memory allocation)");
-			break;
-		}
-		case LUA_ERRERR : {
-			Msg ("! SCRIPT ERROR (while running the error handler function)");
-			break;
-		}
-		case LUA_ERRFILE : {
-			Msg ("! SCRIPT ERROR (while running file)");
-			break;
-		}
-		case LUA_ERRSYNTAX : {
-			Msg ("! SCRIPT SYNTAX ERROR");
-			break;
-		}
-		default : NODEFAULT;
-	}
-	
-	for (int i=0; ; ++i) {
-		Msg		("! Stack level %d",i);
-		if (!bfListLevelVars(tpLuaVirtualMachine,i))
-			return;
-	}
+    switch (iErrorCode)
+    {
+    case LUA_ERRRUN:
+    {
+        Msg("! SCRIPT RUNTIME ERROR");
+        break;
+    }
+    case LUA_ERRMEM:
+    {
+        Msg("! SCRIPT ERROR (memory allocation)");
+        break;
+    }
+    case LUA_ERRERR:
+    {
+        Msg("! SCRIPT ERROR (while running the error handler function)");
+        break;
+    }
+    case LUA_ERRFILE:
+    {
+        Msg("! SCRIPT ERROR (while running file)");
+        break;
+    }
+    case LUA_ERRSYNTAX:
+    {
+        Msg("! SCRIPT SYNTAX ERROR");
+        break;
+    }
+    default:
+        NODEFAULT;
+    }
+
+    for (int i = 0;; ++i)
+    {
+        Msg("! Stack level %d", i);
+        if (!bfListLevelVars(tpLuaVirtualMachine, i))
+            return;
+    }
 }
 
 LPCSTR Script::cafEventToString(int iEventCode)
 {
-	switch (iEventCode) {
-		case LUA_HOOKCALL		: return("hook call");
-		case LUA_HOOKRET		: return("hook return");
-		case LUA_HOOKLINE		: return("hook line");
-		case LUA_HOOKCOUNT		: return("hook count");
-		case LUA_HOOKTAILRET	: return("hook tail return");
-		default					: NODEFAULT;
-	}
+    switch (iEventCode)
+    {
+    case LUA_HOOKCALL:
+        return("hook call");
+    case LUA_HOOKRET:
+        return("hook return");
+    case LUA_HOOKLINE:
+        return("hook line");
+    case LUA_HOOKCOUNT:
+        return("hook count");
+    case LUA_HOOKTAILRET:
+        return("hook tail return");
+    default:
+        NODEFAULT;
+    }
 #ifdef DEBUG
-	return(0);
+    return(0);
 #endif
 }
 
-bool Script::bfListLevelVars(CLuaVirtualMachine *tpLuaVirtualMachine, int iStackLevel)
+bool Script::bfListLevelVars(CLuaVirtualMachine* tpLuaVirtualMachine, int iStackLevel)
 {
-//	lua_Debug	l_tDebugInfo;
-//	int			i;
-//	const char	*name;
-//
-//	if (lua_getstack(tpLuaVirtualMachine, iStackLevel, &l_tDebugInfo) == 0)
-//		return	(false);  /* failure: no such level in the stack */
-//	Msg			("  Event			: %d",cafEventToString(l_tDebugInfo.event));
-//	Msg			("  Name			: %s",l_tDebugInfo.name);
-//	Msg			("  Name what		: %s",l_tDebugInfo.namewhat);
-//	Msg			("  What			: %s",l_tDebugInfo.what);
-//	Msg			("  Source			: %s",l_tDebugInfo.source);
-//	Msg			("  Source (short)	: %s",l_tDebugInfo.short_src);
-//	Msg			("  Current line	: %d",l_tDebugInfo.currentline);
-//	Msg			("  Nups			: %d",l_tDebugInfo.nups);
-//	Msg			("  Line defined	: %d",l_tDebugInfo.linedefined);
-//	i			= 1;
-//	while (NULL != (name = lua_getlocal(tpLuaVirtualMachine, &l_tDebugInfo, i++))) {
-//		Msg		("    local   %d %s", i-1, name);
-//		lua_pop	(tpLuaVirtualMachine, 1);  /* remove variable value */
-//	}
-//
-//	lua_getinfo	(tpLuaVirtualMachine, "f", &l_tDebugInfo);  /* retrieves function */
-//	i = 1;
-//	while (NULL != (name = lua_getupvalue(tpLuaVirtualMachine, -1, i++))) {
-//		Msg		("    upvalue %d %s", i-1, name);
-//		lua_pop	(tpLuaVirtualMachine, 1);  /* remove upvalue value */
-//	}
-//	return		(true);
-	return		(false);
+    // lua_Debug l_tDebugInfo;
+    // int i;
+    // const char *name;
+    //
+    // if (lua_getstack(tpLuaVirtualMachine, iStackLevel, &l_tDebugInfo) == 0)
+    // return (false); /* failure: no such level in the stack */
+    // Msg (" Event : %d",cafEventToString(l_tDebugInfo.event));
+    // Msg (" Name : %s",l_tDebugInfo.name);
+    // Msg (" Name what : %s",l_tDebugInfo.namewhat);
+    // Msg (" What : %s",l_tDebugInfo.what);
+    // Msg (" Source : %s",l_tDebugInfo.source);
+    // Msg (" Source (short) : %s",l_tDebugInfo.short_src);
+    // Msg (" Current line : %d",l_tDebugInfo.currentline);
+    // Msg (" Nups : %d",l_tDebugInfo.nups);
+    // Msg (" Line defined : %d",l_tDebugInfo.linedefined);
+    // i = 1;
+    // while (NULL != (name = lua_getlocal(tpLuaVirtualMachine, &l_tDebugInfo, i++))) {
+    // Msg (" local %d %s", i-1, name);
+    // lua_pop (tpLuaVirtualMachine, 1); /* remove variable value */
+    // }
+    //
+    // lua_getinfo (tpLuaVirtualMachine, "f", &l_tDebugInfo); /* retrieves function */
+    // i = 1;
+    // while (NULL != (name = lua_getupvalue(tpLuaVirtualMachine, -1, i++))) {
+    // Msg (" upvalue %d %s", i-1, name);
+    // lua_pop (tpLuaVirtualMachine, 1); /* remove upvalue value */
+    // }
+    // return (true);
+    return (false);
 }
diff --git a/src/xrEngine/ai_script_lua_extension.cpp b/src/xrEngine/ai_script_lua_extension.cpp
index 8a3568182c7..33e68d01e6a 100644
--- a/src/xrEngine/ai_script_lua_extension.cpp
+++ b/src/xrEngine/ai_script_lua_extension.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: ai_script_lua_extension.cpp
-//	Created 	: 19.09.2003
-//  Modified 	: 19.09.2003
-//	Author		: Dmitriy Iassenev
-//	Description : XRay Script extensions
+// Module : ai_script_lua_extension.cpp
+// Created : 19.09.2003
+// Modified : 19.09.2003
+// Author : Dmitriy Iassenev
+// Description : XRay Script extensions
 ////////////////////////////////////////////////////////////////////////////
 
 #include 
@@ -13,22 +13,22 @@
 
 #ifdef XRRENDER_R4_EXPORTS
 #define ENGINE_BUILD
-#endif	//	XRRENDER_R4_EXPORTS
+#endif // XRRENDER_R4_EXPORTS
 
 #ifdef XRRENDER_R3_EXPORTS
 #define ENGINE_BUILD
-#endif	//	XRRENDER_R3_EXPORTS
+#endif // XRRENDER_R3_EXPORTS
 
 #ifdef XRRENDER_R2_EXPORTS
 #define ENGINE_BUILD
-#endif	//	XRRENDER_R2_EXPORTS
+#endif // XRRENDER_R2_EXPORTS
 
 #ifdef XRRENDER_R1_EXPORTS
 #define ENGINE_BUILD
-#endif	//	XRRENDER_R1_EXPORTS
+#endif // XRRENDER_R1_EXPORTS
 
 #ifndef ENGINE_BUILD
-	#include "ai_space.h"
+#include "ai_space.h"
 #endif
 
 using namespace Script;
@@ -36,411 +36,442 @@ using namespace Script;
 int __cdecl Lua::LuaOut(Lua::ELuaMessageType tLuaMessageType, LPCSTR caFormat, ...)
 {
 #ifndef ENGINE_BUILD
-	if (!psAI_Flags.test(aiLua))
-		return(0);
+    if (!psAI_Flags.test(aiLua))
+        return(0);
 #endif
 
-	LPCSTR		S = "", SS = "";
-	LPSTR		S1;
-	string4096	S2;
-	switch (tLuaMessageType) {
-		case Lua::eLuaMessageTypeInfo : {
-			S	= "* [LUA] ";
-			SS	= "[INFO]        ";
-			break;
-		}
-		case Lua::eLuaMessageTypeError : {
-			S	= "! [LUA] ";
-			SS	= "[ERROR]       ";
-			break;
-		}
-		case Lua::eLuaMessageTypeMessage : {
-			S	= "[LUA] ";
-			SS	= "[MESSAGE]     ";
-			break;
-		}
-		case Lua::eLuaMessageTypeHookCall : {
-			S	= "[LUA][HOOK_CALL] ";
-			SS	= "[CALL]        ";
-			break;
-		}
-		case Lua::eLuaMessageTypeHookReturn : {
-			S	= "[LUA][HOOK_RETURN] ";
-			SS	= "[RETURN]      ";
-			break;
-		}
-		case Lua::eLuaMessageTypeHookLine : {
-			S	= "[LUA][HOOK_LINE] ";
-			SS	= "[LINE]        ";
-			break;
-		}
-		case Lua::eLuaMessageTypeHookCount : {
-			S	= "[LUA][HOOK_COUNT] ";
-			SS	= "[COUNT]       ";
-			break;
-		}
-		case Lua::eLuaMessageTypeHookTailReturn : {
-			S	= "[LUA][HOOK_TAIL_RETURN] ";
-			SS	= "[TAIL_RETURN] ";
-			break;
-		}
-		default : NODEFAULT;
-	}
-	
-	va_list	l_tMarker;
-	
-	va_start(l_tMarker,caFormat);
-
-	xr_strcpy	(S2,S);
-	S1		= S2 + xr_strlen(S);
-	int		l_iResult = vsprintf(S1,caFormat,l_tMarker);
-	Msg		("%s",S2);
-	
-	xr_strcpy	(S2,SS);
-	S1		= S2 + xr_strlen(SS);
-	vsprintf(S1,caFormat,l_tMarker);
+    LPCSTR S = "", SS = "";
+    LPSTR S1;
+    string4096 S2;
+    switch (tLuaMessageType)
+    {
+    case Lua::eLuaMessageTypeInfo:
+    {
+        S = "* [LUA] ";
+        SS = "[INFO] ";
+        break;
+    }
+    case Lua::eLuaMessageTypeError:
+    {
+        S = "! [LUA] ";
+        SS = "[ERROR] ";
+        break;
+    }
+    case Lua::eLuaMessageTypeMessage:
+    {
+        S = "[LUA] ";
+        SS = "[MESSAGE] ";
+        break;
+    }
+    case Lua::eLuaMessageTypeHookCall:
+    {
+        S = "[LUA][HOOK_CALL] ";
+        SS = "[CALL] ";
+        break;
+    }
+    case Lua::eLuaMessageTypeHookReturn:
+    {
+        S = "[LUA][HOOK_RETURN] ";
+        SS = "[RETURN] ";
+        break;
+    }
+    case Lua::eLuaMessageTypeHookLine:
+    {
+        S = "[LUA][HOOK_LINE] ";
+        SS = "[LINE] ";
+        break;
+    }
+    case Lua::eLuaMessageTypeHookCount:
+    {
+        S = "[LUA][HOOK_COUNT] ";
+        SS = "[COUNT] ";
+        break;
+    }
+    case Lua::eLuaMessageTypeHookTailReturn:
+    {
+        S = "[LUA][HOOK_TAIL_RETURN] ";
+        SS = "[TAIL_RETURN] ";
+        break;
+    }
+    default:
+        NODEFAULT;
+    }
+
+    va_list l_tMarker;
+
+    va_start(l_tMarker, caFormat);
+
+    xr_strcpy(S2, S);
+    S1 = S2 + xr_strlen(S);
+    int l_iResult = vsprintf(S1, caFormat, l_tMarker);
+    Msg("%s", S2);
+
+    xr_strcpy(S2, SS);
+    S1 = S2 + xr_strlen(SS);
+    vsprintf(S1, caFormat, l_tMarker);
 
 #ifdef ENGINE_BUILD
-	// Msg("[LUA Output] : %s",S2);
+    // Msg("[LUA Output] : %s",S2);
 #else
-	ai().lua_output().w_string(S2);
+    ai().lua_output().w_string(S2);
 #endif
 
-	va_end	(l_tMarker);
+    va_end(l_tMarker);
 
-	return	(l_iResult);
+    return (l_iResult);
 }
 
 #ifndef ENGINE_BUILD
-void Script::vfLoadStandardScripts(CLuaVirtualMachine *tpLuaVM)
+void Script::vfLoadStandardScripts(CLuaVirtualMachine* tpLuaVM)
 {
-	string256		S,S1;
-	FS.update_path	(S,"$game_data$","script.ltx");
-	CInifile		*l_tpIniFile = xr_new(S);
-	R_ASSERT		(l_tpIniFile);
-	LPCSTR			caScriptString = l_tpIniFile->r_string("common","script");
-
-	u32				caNamespaceName = _GetItemCount(caScriptString);
-	string256		I;
-	for (u32 i=0; i(S);
+    R_ASSERT(l_tpIniFile);
+    LPCSTR caScriptString = l_tpIniFile->r_string("common", "script");
+
+    u32 caNamespaceName = _GetItemCount(caScriptString);
+    string256 I;
+    for (u32 i = 0; i < caNamespaceName; ++i)
+    {
+        FS.update_path(S, "$game_scripts$", strconcat(S1, _GetItem(caScriptString, i, I), ".script"));
+        bfLoadFile(tpLuaVM, S, true);
+        if (bfIsObjectPresent(tpLuaVM, "_G", xr_strcat(I, "_initialize"), LUA_TFUNCTION))
+            lua_dostring(tpLuaVM, xr_strcat(I, "()"));
+    }
+    xr_delete(l_tpIniFile);
 }
 
 void LuaError(lua_State* L)
 {
-	Debug.fatal(DEBUG_INFO,"LUA error: %s",lua_tostring(L,-1));
+    Debug.fatal(DEBUG_INFO, "LUA error: %s", lua_tostring(L, -1));
 }
 
-void Script::vfExportToLua(CLuaVirtualMachine *tpLuaVM)
+void Script::vfExportToLua(CLuaVirtualMachine* tpLuaVM)
 {
-	luabind::open					(tpLuaVM);
-	luabind::set_error_callback		(LuaError);
-
-	lua_atpanic		(tpLuaVM,Script::LuaPanic);
-
-	vfExportGlobals				(tpLuaVM);
-	vfExportFvector				(tpLuaVM);
-	vfExportFmatrix				(tpLuaVM);
-	vfExportGame				(tpLuaVM);
-	vfExportLevel				(tpLuaVM);
-	vfExportDevice				(tpLuaVM);
-	vfExportParticles			(tpLuaVM);
-	vfExportSound				(tpLuaVM);
-	vfExportHit					(tpLuaVM);
-	vfExportActions				(tpLuaVM);
-	vfExportObject				(tpLuaVM);
-	vfExportEffector			(tpLuaVM);
-	vfExportArtifactMerger		(tpLuaVM);
-	vfExportMemoryObjects		(tpLuaVM);
-	vfExportActionManagement	(tpLuaVM);
-	vfExportMotivationManagement(tpLuaVM);
+    luabind::open(tpLuaVM);
+    luabind::set_error_callback(LuaError);
+
+    lua_atpanic(tpLuaVM, Script::LuaPanic);
+
+    vfExportGlobals(tpLuaVM);
+    vfExportFvector(tpLuaVM);
+    vfExportFmatrix(tpLuaVM);
+    vfExportGame(tpLuaVM);
+    vfExportLevel(tpLuaVM);
+    vfExportDevice(tpLuaVM);
+    vfExportParticles(tpLuaVM);
+    vfExportSound(tpLuaVM);
+    vfExportHit(tpLuaVM);
+    vfExportActions(tpLuaVM);
+    vfExportObject(tpLuaVM);
+    vfExportEffector(tpLuaVM);
+    vfExportArtifactMerger(tpLuaVM);
+    vfExportMemoryObjects(tpLuaVM);
+    vfExportActionManagement(tpLuaVM);
+    vfExportMotivationManagement(tpLuaVM);
 
 #ifdef DEBUG
-	lua_sethook					(tpLuaVM, LuaHookCall,	LUA_HOOKCALL | LUA_HOOKRET | LUA_HOOKLINE | LUA_HOOKTAILRET,	0);
+    lua_sethook(tpLuaVM, LuaHookCall, LUA_HOOKCALL | LUA_HOOKRET | LUA_HOOKLINE | LUA_HOOKTAILRET, 0);
 #endif
 
-	vfLoadStandardScripts		(tpLuaVM);
+    vfLoadStandardScripts(tpLuaVM);
 }
 
-bool Script::bfLoadFile(CLuaVirtualMachine *tpLuaVM, LPCSTR caScriptName, bool bCall)
+bool Script::bfLoadFile(CLuaVirtualMachine* tpLuaVM, LPCSTR caScriptName, bool bCall)
 {
-	string256		l_caNamespaceName;
-	_splitpath		(caScriptName,0,0,l_caNamespaceName,0);
-	if (!xr_strlen(l_caNamespaceName))
-		return		(bfLoadFileIntoNamespace(tpLuaVM,caScriptName,"_G",bCall));
-	else
-		return		(bfLoadFileIntoNamespace(tpLuaVM,caScriptName,l_caNamespaceName,bCall));
+    string256 l_caNamespaceName;
+    _splitpath(caScriptName, 0, 0, l_caNamespaceName, 0);
+    if (!xr_strlen(l_caNamespaceName))
+        return (bfLoadFileIntoNamespace(tpLuaVM, caScriptName, "_G", bCall));
+    else
+        return (bfLoadFileIntoNamespace(tpLuaVM, caScriptName, l_caNamespaceName, bCall));
 }
 #endif
 
-bool bfCreateNamespaceTable(CLuaVirtualMachine *tpLuaVM, LPCSTR caNamespaceName)
+bool bfCreateNamespaceTable(CLuaVirtualMachine* tpLuaVM, LPCSTR caNamespaceName)
 {
-	lua_pushstring	(tpLuaVM,"_G");
-	lua_gettable	(tpLuaVM,LUA_GLOBALSINDEX);
-	LPSTR			S2	= xr_strdup(caNamespaceName);
-	LPSTR			S	= S2;
-	for (;;) {
-		if (!xr_strlen(S)) {
-			lua_pop		(tpLuaVM,1);
-			LuaOut		(Lua::eLuaMessageTypeError,"the namespace name %s is incorrect!",caNamespaceName);
-			xr_free		(S2);
-			return		(false);
-		}
-		LPSTR			S1 = strchr(S,'.');
-		if (S1)
-			*S1				= 0;
-		lua_pushstring	(tpLuaVM,S);
-		lua_gettable	(tpLuaVM,-2);
-		if (lua_isnil(tpLuaVM,-1)) {
-			lua_pop			(tpLuaVM,1);
-			lua_newtable	(tpLuaVM);
-			lua_pushstring	(tpLuaVM,S);
-			lua_pushvalue	(tpLuaVM,-2);
-			lua_settable	(tpLuaVM,-4);
-		}
-		else
-			if (!lua_istable(tpLuaVM,-1)) {
-				xr_free			(S2);
-				lua_pop			(tpLuaVM,2);
-				LuaOut			(Lua::eLuaMessageTypeError,"the namespace name %s is already being used by the non-table object!",caNamespaceName);
-				return			(false);
-			}
-			lua_remove		(tpLuaVM,-2);
-			if (S1)
-				S			= ++S1;
-			else
-				break;
-	}
-	xr_free			(S2);
-	return			(true);
+    lua_pushstring(tpLuaVM, "_G");
+    lua_gettable(tpLuaVM, LUA_GLOBALSINDEX);
+    LPSTR S2 = xr_strdup(caNamespaceName);
+    LPSTR S = S2;
+    for (;;)
+    {
+        if (!xr_strlen(S))
+        {
+            lua_pop(tpLuaVM, 1);
+            LuaOut(Lua::eLuaMessageTypeError, "the namespace name %s is incorrect!", caNamespaceName);
+            xr_free(S2);
+            return (false);
+        }
+        LPSTR S1 = strchr(S, '.');
+        if (S1)
+            *S1 = 0;
+        lua_pushstring(tpLuaVM, S);
+        lua_gettable(tpLuaVM, -2);
+        if (lua_isnil(tpLuaVM, -1))
+        {
+            lua_pop(tpLuaVM, 1);
+            lua_newtable(tpLuaVM);
+            lua_pushstring(tpLuaVM, S);
+            lua_pushvalue(tpLuaVM, -2);
+            lua_settable(tpLuaVM, -4);
+        }
+        else if (!lua_istable(tpLuaVM, -1))
+        {
+            xr_free(S2);
+            lua_pop(tpLuaVM, 2);
+            LuaOut(Lua::eLuaMessageTypeError, "the namespace name %s is already being used by the non-table object!", caNamespaceName);
+            return (false);
+        }
+        lua_remove(tpLuaVM, -2);
+        if (S1)
+            S = ++S1;
+        else
+            break;
+    }
+    xr_free(S2);
+    return (true);
 }
 
-void vfCopyGlobals(CLuaVirtualMachine *tpLuaVM)
+void vfCopyGlobals(CLuaVirtualMachine* tpLuaVM)
 {
-	lua_newtable	(tpLuaVM);
-	lua_pushstring	(tpLuaVM,"_G");
-	lua_gettable	(tpLuaVM,LUA_GLOBALSINDEX);
-	lua_pushnil		(tpLuaVM);
-	while (lua_next(tpLuaVM, -2)) {
-		lua_pushvalue	(tpLuaVM,-2);
-		lua_pushvalue	(tpLuaVM,-2);
-		lua_settable	(tpLuaVM,-6);
-		lua_pop			(tpLuaVM, 1);
-	}
+    lua_newtable(tpLuaVM);
+    lua_pushstring(tpLuaVM, "_G");
+    lua_gettable(tpLuaVM, LUA_GLOBALSINDEX);
+    lua_pushnil(tpLuaVM);
+    while (lua_next(tpLuaVM, -2))
+    {
+        lua_pushvalue(tpLuaVM, -2);
+        lua_pushvalue(tpLuaVM, -2);
+        lua_settable(tpLuaVM, -6);
+        lua_pop(tpLuaVM, 1);
+    }
 }
 
-bool Script::bfLoadBuffer(CLuaVirtualMachine *tpLuaVM, LPCSTR caBuffer, size_t tSize, LPCSTR caScriptName, LPCSTR caNameSpaceName)
+bool Script::bfLoadBuffer(CLuaVirtualMachine* tpLuaVM, LPCSTR caBuffer, size_t tSize, LPCSTR caScriptName, LPCSTR caNameSpaceName)
 {
-	int				l_iErrorCode;
-	if (caNameSpaceName) {
-		string256		insert;
-		xr_sprintf		(insert,sizeof(insert),"local this = %s\n",caNameSpaceName);
-		size_t			str_len = xr_strlen(insert);
-		LPSTR			script = xr_alloc(u32(str_len + tSize));
-		xr_strcpy		(script, str_len+tSize, insert);
-		CopyMemory		(script+str_len, caBuffer, u32(tSize));
-		l_iErrorCode	= luaL_loadbuffer(tpLuaVM,script,tSize + str_len,caScriptName);
-		xr_free			(script);
-	}
-	else
-		l_iErrorCode	= luaL_loadbuffer(tpLuaVM,caBuffer,tSize,caScriptName);
-
-	if (l_iErrorCode) {
+    int l_iErrorCode;
+    if (caNameSpaceName)
+    {
+        string256 insert;
+        xr_sprintf(insert, sizeof(insert), "local this = %s\n", caNameSpaceName);
+        size_t str_len = xr_strlen(insert);
+        LPSTR script = xr_alloc(u32(str_len + tSize));
+        xr_strcpy(script, str_len + tSize, insert);
+        CopyMemory(script + str_len, caBuffer, u32(tSize));
+        l_iErrorCode = luaL_loadbuffer(tpLuaVM, script, tSize + str_len, caScriptName);
+        xr_free(script);
+    }
+    else
+        l_iErrorCode = luaL_loadbuffer(tpLuaVM, caBuffer, tSize, caScriptName);
+
+    if (l_iErrorCode)
+    {
 #ifdef DEBUG
-		if (!bfPrintOutput	(tpLuaVM,caScriptName,l_iErrorCode))
-			vfPrintError(tpLuaVM,l_iErrorCode);
+        if (!bfPrintOutput(tpLuaVM, caScriptName, l_iErrorCode))
+            vfPrintError(tpLuaVM, l_iErrorCode);
 #endif
-		return			(false);
-	}
-	return			(true);
+        return (false);
+    }
+    return (true);
 }
 
-bool bfDoFile(CLuaVirtualMachine *tpLuaVM, LPCSTR caScriptName, LPCSTR caNameSpaceName, bool bCall)
+bool bfDoFile(CLuaVirtualMachine* tpLuaVM, LPCSTR caScriptName, LPCSTR caNameSpaceName, bool bCall)
 {
-	string_path		l_caLuaFileName;
-	IReader			*l_tpFileReader = FS.r_open(caScriptName);
-	R_ASSERT		(l_tpFileReader);
-	strconcat		(sizeof(l_caLuaFileName),l_caLuaFileName,"@",caScriptName);
-	
-	if (!bfLoadBuffer(tpLuaVM,static_cast(l_tpFileReader->pointer()),(size_t)l_tpFileReader->length(),l_caLuaFileName,caNameSpaceName)) {
-		lua_pop			(tpLuaVM,4);
-		FS.r_close		(l_tpFileReader);
-		return		(false);
-	}
-	FS.r_close		(l_tpFileReader);
-
-	if (bCall) {
-		lua_call	(tpLuaVM,0,0);
-//		int			l_iErrorCode = lua_pcall(tpLuaVM,0,0,0);
-//		if (l_iErrorCode) {
-//#ifdef DEBUG
-//			bfPrintOutput	(tpLuaVM,caScriptName,l_iErrorCode);
-//			vfPrintError	(tpLuaVM,l_iErrorCode);
-//#endif
-//			return	(false);
-//		}
-	}
-	else
-		lua_insert		(tpLuaVM,-4);
-
-	return			(true);
+    string_path l_caLuaFileName;
+    IReader* l_tpFileReader = FS.r_open(caScriptName);
+    R_ASSERT(l_tpFileReader);
+    strconcat(sizeof(l_caLuaFileName), l_caLuaFileName, "@", caScriptName);
+
+    if (!bfLoadBuffer(tpLuaVM, static_cast(l_tpFileReader->pointer()), (size_t)l_tpFileReader->length(), l_caLuaFileName, caNameSpaceName))
+    {
+        lua_pop(tpLuaVM, 4);
+        FS.r_close(l_tpFileReader);
+        return (false);
+    }
+    FS.r_close(l_tpFileReader);
+
+    if (bCall)
+    {
+        lua_call(tpLuaVM, 0, 0);
+        // int l_iErrorCode = lua_pcall(tpLuaVM,0,0,0);
+        // if (l_iErrorCode) {
+        //#ifdef DEBUG
+        // bfPrintOutput (tpLuaVM,caScriptName,l_iErrorCode);
+        // vfPrintError (tpLuaVM,l_iErrorCode);
+        //#endif
+        // return (false);
+        // }
+    }
+    else
+        lua_insert(tpLuaVM, -4);
+
+    return (true);
 }
 
-void vfSetNamespace(CLuaVirtualMachine *tpLuaVM)
+void vfSetNamespace(CLuaVirtualMachine* tpLuaVM)
 {
-	lua_pushnil		(tpLuaVM);
-	while (lua_next(tpLuaVM, -2)) {
-		lua_pushvalue	(tpLuaVM,-2);
-		lua_gettable	(tpLuaVM,-5);
-		if (lua_isnil(tpLuaVM,-1)) {
-			lua_pop			(tpLuaVM,1);
-			lua_pushvalue	(tpLuaVM,-2);
-			lua_pushvalue	(tpLuaVM,-2);
-			lua_pushvalue	(tpLuaVM,-2);
-			lua_pushnil		(tpLuaVM);
-			lua_settable	(tpLuaVM,-7);
-			lua_settable	(tpLuaVM,-7);
-		}
-		else {
-			lua_pop			(tpLuaVM,1);
-			lua_pushvalue	(tpLuaVM,-2);
-			lua_gettable	(tpLuaVM,-4);
-			if (!lua_equal(tpLuaVM,-1,-2)) {
-				lua_pushvalue	(tpLuaVM,-3);
-				lua_pushvalue	(tpLuaVM,-2);
-				lua_pushvalue	(tpLuaVM,-2);
-				lua_pushvalue	(tpLuaVM,-5);
-				lua_settable	(tpLuaVM,-8);
-				lua_settable	(tpLuaVM,-8);
-			}
-			lua_pop			(tpLuaVM,1);
-		}
-		lua_pushvalue	(tpLuaVM,-2);
-		lua_pushnil		(tpLuaVM);
-		lua_settable	(tpLuaVM,-6);
-		lua_pop			(tpLuaVM, 1);
-	}
-	lua_pop			(tpLuaVM,3);
+    lua_pushnil(tpLuaVM);
+    while (lua_next(tpLuaVM, -2))
+    {
+        lua_pushvalue(tpLuaVM, -2);
+        lua_gettable(tpLuaVM, -5);
+        if (lua_isnil(tpLuaVM, -1))
+        {
+            lua_pop(tpLuaVM, 1);
+            lua_pushvalue(tpLuaVM, -2);
+            lua_pushvalue(tpLuaVM, -2);
+            lua_pushvalue(tpLuaVM, -2);
+            lua_pushnil(tpLuaVM);
+            lua_settable(tpLuaVM, -7);
+            lua_settable(tpLuaVM, -7);
+        }
+        else
+        {
+            lua_pop(tpLuaVM, 1);
+            lua_pushvalue(tpLuaVM, -2);
+            lua_gettable(tpLuaVM, -4);
+            if (!lua_equal(tpLuaVM, -1, -2))
+            {
+                lua_pushvalue(tpLuaVM, -3);
+                lua_pushvalue(tpLuaVM, -2);
+                lua_pushvalue(tpLuaVM, -2);
+                lua_pushvalue(tpLuaVM, -5);
+                lua_settable(tpLuaVM, -8);
+                lua_settable(tpLuaVM, -8);
+            }
+            lua_pop(tpLuaVM, 1);
+        }
+        lua_pushvalue(tpLuaVM, -2);
+        lua_pushnil(tpLuaVM);
+        lua_settable(tpLuaVM, -6);
+        lua_pop(tpLuaVM, 1);
+    }
+    lua_pop(tpLuaVM, 3);
 }
 
-bool Script::bfLoadFileIntoNamespace(CLuaVirtualMachine *tpLuaVM, LPCSTR caScriptName, LPCSTR caNamespaceName, bool bCall)
+bool Script::bfLoadFileIntoNamespace(CLuaVirtualMachine* tpLuaVM, LPCSTR caScriptName, LPCSTR caNamespaceName, bool bCall)
 {
-	if (!bfCreateNamespaceTable(tpLuaVM,caNamespaceName))
-		return		(false);
-	vfCopyGlobals	(tpLuaVM);
-	if (!bfDoFile(tpLuaVM,caScriptName,caNamespaceName,bCall))
-		return		(false);
-	vfSetNamespace	(tpLuaVM);
-	return			(true);
+    if (!bfCreateNamespaceTable(tpLuaVM, caNamespaceName))
+        return (false);
+    vfCopyGlobals(tpLuaVM);
+    if (!bfDoFile(tpLuaVM, caScriptName, caNamespaceName, bCall))
+        return (false);
+    vfSetNamespace(tpLuaVM);
+    return (true);
 }
 
-bool Script::bfGetNamespaceTable(CLuaVirtualMachine *tpLuaVM, LPCSTR N)
+bool Script::bfGetNamespaceTable(CLuaVirtualMachine* tpLuaVM, LPCSTR N)
 {
-	lua_pushstring 		(tpLuaVM,"_G"); 
-	lua_gettable 		(tpLuaVM,LUA_GLOBALSINDEX); 
-	string256			S2;	xr_strcpy	(S2,N);
-	LPSTR				S	= S2;
-	for (;;) { 
-		if (!xr_strlen(S)) return	(false); 
-		LPSTR S1 		= strchr(S,'.'); 
-		if (S1) 	*S1 = 0; 
-		lua_pushstring 	(tpLuaVM,S); 
-		lua_gettable 	(tpLuaVM,-2); 
-		if (lua_isnil(tpLuaVM,-1)) { 
-			lua_pop		(tpLuaVM,2); 
-			return		(false);	//	there is no namespace!
-		}
-		else 
-			if (!lua_istable(tpLuaVM,-1)) { 
-				lua_pop		(tpLuaVM,2); 
-				FATAL		(" Error : the namespace name is already being used by the non-table object!\n");
-				return		(false); 
-			} 
-			lua_remove	(tpLuaVM,-2); 
-			if (S1)		S = ++S1; 
-			else 		break; 
-	} 
-	return	(true); 
+    lua_pushstring(tpLuaVM, "_G");
+    lua_gettable(tpLuaVM, LUA_GLOBALSINDEX);
+    string256 S2;
+    xr_strcpy(S2, N);
+    LPSTR S = S2;
+    for (;;)
+    {
+        if (!xr_strlen(S)) return (false);
+        LPSTR S1 = strchr(S, '.');
+        if (S1) *S1 = 0;
+        lua_pushstring(tpLuaVM, S);
+        lua_gettable(tpLuaVM, -2);
+        if (lua_isnil(tpLuaVM, -1))
+        {
+            lua_pop(tpLuaVM, 2);
+            return (false); // there is no namespace!
+        }
+        else if (!lua_istable(tpLuaVM, -1))
+        {
+            lua_pop(tpLuaVM, 2);
+            FATAL(" Error : the namespace name is already being used by the non-table object!\n");
+            return (false);
+        }
+        lua_remove(tpLuaVM, -2);
+        if (S1) S = ++S1;
+        else break;
+    }
+    return (true);
 }
 
-CLuaVirtualMachine *Script::get_namespace_table(CLuaVirtualMachine *tpLuaVM, LPCSTR N)
+CLuaVirtualMachine* Script::get_namespace_table(CLuaVirtualMachine* tpLuaVM, LPCSTR N)
 {
-	if (!xr_strlen(N))
-		return				(tpLuaVM);
-	lua_pushstring 			(tpLuaVM,"_G"); 
-	lua_gettable 			(tpLuaVM,LUA_GLOBALSINDEX); 
-	string256				S2;
-	xr_strcpy					(S2,N);
-	LPSTR					S	= S2;
-	for (;;) { 
-		if (!xr_strlen(S))
-			return			(0); 
-		LPSTR				S1 = strchr(S,'.'); 
-		if (S1)
-			*S1				= 0; 
-		lua_pushstring 		(tpLuaVM,S); 
-		lua_gettable 		(tpLuaVM,-2); 
-		if (lua_isnil(tpLuaVM,-1)) { 
-			lua_pop			(tpLuaVM,2); 
-			return			(0);	//	there is no namespace!
-		}
-		else 
-			if (!lua_istable(tpLuaVM,-1)) { 
-				lua_pop		(tpLuaVM,2); 
-				FATAL		(" Error : the namespace name is already being used by the non-table object!\n");
-				return		(0); 
-			} 
-
-			lua_remove		(tpLuaVM,-2);
-
-			if (S1)
-				S			= ++S1; 
-			else
-				break; 
-	} 
-	return					(tpLuaVM); 
+    if (!xr_strlen(N))
+        return (tpLuaVM);
+    lua_pushstring(tpLuaVM, "_G");
+    lua_gettable(tpLuaVM, LUA_GLOBALSINDEX);
+    string256 S2;
+    xr_strcpy(S2, N);
+    LPSTR S = S2;
+    for (;;)
+    {
+        if (!xr_strlen(S))
+            return (0);
+        LPSTR S1 = strchr(S, '.');
+        if (S1)
+            *S1 = 0;
+        lua_pushstring(tpLuaVM, S);
+        lua_gettable(tpLuaVM, -2);
+        if (lua_isnil(tpLuaVM, -1))
+        {
+            lua_pop(tpLuaVM, 2);
+            return (0); // there is no namespace!
+        }
+        else if (!lua_istable(tpLuaVM, -1))
+        {
+            lua_pop(tpLuaVM, 2);
+            FATAL(" Error : the namespace name is already being used by the non-table object!\n");
+            return (0);
+        }
+
+        lua_remove(tpLuaVM, -2);
+
+        if (S1)
+            S = ++S1;
+        else
+            break;
+    }
+    return (tpLuaVM);
 }
 
-bool	Script::bfIsObjectPresent	(CLuaVirtualMachine *tpLuaVM, LPCSTR identifier, int type)
+bool Script::bfIsObjectPresent(CLuaVirtualMachine* tpLuaVM, LPCSTR identifier, int type)
 {
-	lua_pushnil (tpLuaVM); 
-	while (lua_next(tpLuaVM, -2)) { 
-		if ((lua_type(tpLuaVM, -1) == type) && !xr_strcmp(identifier,lua_tostring(tpLuaVM, -2))) { 
-			lua_pop (tpLuaVM, 3); 
-			return	(true); 
-		} 
-		lua_pop (tpLuaVM, 1); 
-	} 
-	lua_pop (tpLuaVM, 1); 
-	return	(false); 
+    lua_pushnil(tpLuaVM);
+    while (lua_next(tpLuaVM, -2))
+    {
+        if ((lua_type(tpLuaVM, -1) == type) && !xr_strcmp(identifier, lua_tostring(tpLuaVM, -2)))
+        {
+            lua_pop(tpLuaVM, 3);
+            return (true);
+        }
+        lua_pop(tpLuaVM, 1);
+    }
+    lua_pop(tpLuaVM, 1);
+    return (false);
 }
 
-bool	Script::bfIsObjectPresent	(CLuaVirtualMachine *tpLuaVM, LPCSTR namespace_name, LPCSTR identifier, int type)
+bool Script::bfIsObjectPresent(CLuaVirtualMachine* tpLuaVM, LPCSTR namespace_name, LPCSTR identifier, int type)
 {
-	if (xr_strlen(namespace_name) && !bfGetNamespaceTable(tpLuaVM,namespace_name))
-		return				(false); 
-	return					(bfIsObjectPresent(tpLuaVM,identifier,type)); 
+    if (xr_strlen(namespace_name) && !bfGetNamespaceTable(tpLuaVM, namespace_name))
+        return (false);
+    return (bfIsObjectPresent(tpLuaVM, identifier, type));
 }
 
-luabind::object Script::lua_namespace_table(CLuaVirtualMachine *tpLuaVM, LPCSTR namespace_name)
+luabind::object Script::lua_namespace_table(CLuaVirtualMachine* tpLuaVM, LPCSTR namespace_name)
 {
-	string256			S1;
-	xr_strcpy				(S1,namespace_name);
-	LPSTR				S = S1;
-	luabind::object		lua_namespace = luabind::get_globals(tpLuaVM);
-	for (;;) {
-		if (!xr_strlen(S))
-			return		(lua_namespace);
-		LPSTR			I = strchr(S,'.');
-		if (!I)
-			return		(lua_namespace[S]);
-		*I				= 0;
-		lua_namespace	= lua_namespace[S];
-		S				= I + 1;
-	}
+    string256 S1;
+    xr_strcpy(S1, namespace_name);
+    LPSTR S = S1;
+    luabind::object lua_namespace = luabind::get_globals(tpLuaVM);
+    for (;;)
+    {
+        if (!xr_strlen(S))
+            return (lua_namespace);
+        LPSTR I = strchr(S, '.');
+        if (!I)
+            return (lua_namespace[S]);
+        *I = 0;
+        lua_namespace = lua_namespace[S];
+        S = I + 1;
+    }
 }
\ No newline at end of file
diff --git a/src/xrEngine/ai_script_lua_extension.h b/src/xrEngine/ai_script_lua_extension.h
index af522b75b7e..4038fb059d9 100644
--- a/src/xrEngine/ai_script_lua_extension.h
+++ b/src/xrEngine/ai_script_lua_extension.h
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: ai_script_lua_extension.h
-//	Created 	: 19.09.2003
-//  Modified 	: 22.09.2003
-//	Author		: Dmitriy Iassenev
-//	Description : XRay Script extensions
+// Module : ai_script_lua_extension.h
+// Created : 19.09.2003
+// Modified : 22.09.2003
+// Author : Dmitriy Iassenev
+// Description : XRay Script extensions
 ////////////////////////////////////////////////////////////////////////////
 
 #pragma once
@@ -11,39 +11,40 @@
 #include "ai_script_space.h"
 //struct CLuaVirtualMachine;
 
-namespace Script {
+namespace Script
+{
 #ifndef ENGINE_BUILD
-	void				vfExportGlobals				(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportFvector				(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportFmatrix				(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportGame				(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportLevel				(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportDevice				(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportParticles			(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportSound				(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportHit					(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportActions				(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportObject				(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportEffector			(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportArtifactMerger		(CLuaVirtualMachine *tpLuaVM);
-	void				vfLoadStandardScripts		(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportMemoryObjects		(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportToLua				(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportActionManagement	(CLuaVirtualMachine *tpLuaVM);
-	void				vfExportMotivationManagement(CLuaVirtualMachine *tpLuaVM);
-	bool				bfLoadFile					(CLuaVirtualMachine *tpLuaVM, LPCSTR	caScriptName,	bool	bCall = true);
-	void				LuaHookCall					(CLuaVirtualMachine *tpLuaVM, lua_Debug *tpLuaDebug);
-	int					LuaPanic					(CLuaVirtualMachine *tpLuaVM);
+void vfExportGlobals(CLuaVirtualMachine* tpLuaVM);
+void vfExportFvector(CLuaVirtualMachine* tpLuaVM);
+void vfExportFmatrix(CLuaVirtualMachine* tpLuaVM);
+void vfExportGame(CLuaVirtualMachine* tpLuaVM);
+void vfExportLevel(CLuaVirtualMachine* tpLuaVM);
+void vfExportDevice(CLuaVirtualMachine* tpLuaVM);
+void vfExportParticles(CLuaVirtualMachine* tpLuaVM);
+void vfExportSound(CLuaVirtualMachine* tpLuaVM);
+void vfExportHit(CLuaVirtualMachine* tpLuaVM);
+void vfExportActions(CLuaVirtualMachine* tpLuaVM);
+void vfExportObject(CLuaVirtualMachine* tpLuaVM);
+void vfExportEffector(CLuaVirtualMachine* tpLuaVM);
+void vfExportArtifactMerger(CLuaVirtualMachine* tpLuaVM);
+void vfLoadStandardScripts(CLuaVirtualMachine* tpLuaVM);
+void vfExportMemoryObjects(CLuaVirtualMachine* tpLuaVM);
+void vfExportToLua(CLuaVirtualMachine* tpLuaVM);
+void vfExportActionManagement(CLuaVirtualMachine* tpLuaVM);
+void vfExportMotivationManagement(CLuaVirtualMachine* tpLuaVM);
+bool bfLoadFile(CLuaVirtualMachine* tpLuaVM, LPCSTR caScriptName, bool bCall = true);
+void LuaHookCall(CLuaVirtualMachine* tpLuaVM, lua_Debug* tpLuaDebug);
+int LuaPanic(CLuaVirtualMachine* tpLuaVM);
 #endif
-	bool				bfPrintOutput				(CLuaVirtualMachine *tpLuaVM, LPCSTR	caScriptName, int iErorCode = 0);
-	LPCSTR				cafEventToString			(int				iEventCode);
-	void				vfPrintError				(CLuaVirtualMachine *tpLuaVM, int		iErrorCode);
-	bool				bfListLevelVars				(CLuaVirtualMachine *tpLuaVM, int		iStackLevel);
-	bool				bfLoadBuffer				(CLuaVirtualMachine *tpLuaVM, LPCSTR	caBuffer,		size_t	tSize,				LPCSTR	caScriptName, LPCSTR caNameSpaceName = 0);
-	bool				bfLoadFileIntoNamespace		(CLuaVirtualMachine *tpLuaVM, LPCSTR	caScriptName,	LPCSTR	caNamespaceName,	bool	bCall);
-	bool				bfGetNamespaceTable			(CLuaVirtualMachine *tpLuaVM, LPCSTR	caName);
-	CLuaVirtualMachine	*get_namespace_table		(CLuaVirtualMachine *tpLuaVM, LPCSTR	caName);
-	bool				bfIsObjectPresent			(CLuaVirtualMachine *tpLuaVM, LPCSTR	caIdentifier,	int type);
-	bool				bfIsObjectPresent			(CLuaVirtualMachine *tpLuaVM, LPCSTR	caNamespaceName, LPCSTR	caIdentifier, int type);
-	luabind::object		lua_namespace_table			(CLuaVirtualMachine *tpLuaVM, LPCSTR namespace_name);
+bool bfPrintOutput(CLuaVirtualMachine* tpLuaVM, LPCSTR caScriptName, int iErorCode = 0);
+LPCSTR cafEventToString(int iEventCode);
+void vfPrintError(CLuaVirtualMachine* tpLuaVM, int iErrorCode);
+bool bfListLevelVars(CLuaVirtualMachine* tpLuaVM, int iStackLevel);
+bool bfLoadBuffer(CLuaVirtualMachine* tpLuaVM, LPCSTR caBuffer, size_t tSize, LPCSTR caScriptName, LPCSTR caNameSpaceName = 0);
+bool bfLoadFileIntoNamespace(CLuaVirtualMachine* tpLuaVM, LPCSTR caScriptName, LPCSTR caNamespaceName, bool bCall);
+bool bfGetNamespaceTable(CLuaVirtualMachine* tpLuaVM, LPCSTR caName);
+CLuaVirtualMachine* get_namespace_table(CLuaVirtualMachine* tpLuaVM, LPCSTR caName);
+bool bfIsObjectPresent(CLuaVirtualMachine* tpLuaVM, LPCSTR caIdentifier, int type);
+bool bfIsObjectPresent(CLuaVirtualMachine* tpLuaVM, LPCSTR caNamespaceName, LPCSTR caIdentifier, int type);
+luabind::object lua_namespace_table(CLuaVirtualMachine* tpLuaVM, LPCSTR namespace_name);
 };
diff --git a/src/xrEngine/ai_script_lua_space.h b/src/xrEngine/ai_script_lua_space.h
index b5df3a252ca..34371e71484 100644
--- a/src/xrEngine/ai_script_lua_space.h
+++ b/src/xrEngine/ai_script_lua_space.h
@@ -1,17 +1,19 @@
 #pragma once
 
-namespace Lua {
-	enum ELuaMessageType {
-		eLuaMessageTypeInfo = u32(0),
-		eLuaMessageTypeError,
-		eLuaMessageTypeMessage,
-		eLuaMessageTypeHookCall,
-		eLuaMessageTypeHookReturn,
-		eLuaMessageTypeHookLine,
-		eLuaMessageTypeHookCount,
-		eLuaMessageTypeHookTailReturn = u32(-1),
-	};
+namespace Lua
+{
+enum ELuaMessageType
+{
+    eLuaMessageTypeInfo = u32(0),
+    eLuaMessageTypeError,
+    eLuaMessageTypeMessage,
+    eLuaMessageTypeHookCall,
+    eLuaMessageTypeHookReturn,
+    eLuaMessageTypeHookLine,
+    eLuaMessageTypeHookCount,
+    eLuaMessageTypeHookTailReturn = u32(-1),
+};
 
-	int __cdecl LuaOut(ELuaMessageType tLuaMessageType, LPCSTR caFormat, ...);
+int __cdecl LuaOut(ELuaMessageType tLuaMessageType, LPCSTR caFormat, ...);
 }
 
diff --git a/src/xrEngine/ai_script_space.h b/src/xrEngine/ai_script_space.h
index 99579527929..a0c67e587b3 100644
--- a/src/xrEngine/ai_script_space.h
+++ b/src/xrEngine/ai_script_space.h
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: ai_script_space.h
-//	Created 	: 22.09.2003
-//  Modified 	: 22.09.2003
-//	Author		: Dmitriy Iassenev
-//	Description : XRay Script space
+// Module : ai_script_space.h
+// Created : 22.09.2003
+// Modified : 22.09.2003
+// Author : Dmitriy Iassenev
+// Description : XRay Script space
 ////////////////////////////////////////////////////////////////////////////
 
 #pragma once
@@ -17,12 +17,12 @@
 //#define LUABIND_NO_EXCEPTIONS
 
 extern "C" {
-	//#define BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
+    //#define BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
 
-	#include 
-	#include 
-	#include 
-//	#include 
+#include 
+#include 
+#include 
+    // #include 
 }
 
 // Lua-bind
@@ -35,10 +35,11 @@ extern "C" {
 
 typedef lua_State CLuaVirtualMachine;
 
-struct SMemberCallback {
-	luabind::functor	*m_lua_function;
-	luabind::object			*m_lua_object;
-	shared_str				m_method_name;
+struct SMemberCallback
+{
+    luabind::functor* m_lua_function;
+    luabind::object* m_lua_object;
+    shared_str m_method_name;
 };
 
 #include "ai_script_lua_space.h"
diff --git a/src/xrEngine/bone.cpp b/src/xrEngine/bone.cpp
index 9ffd7ed4665..c57136360a6 100644
--- a/src/xrEngine/bone.cpp
+++ b/src/xrEngine/bone.cpp
@@ -5,52 +5,52 @@
 #include "gamemtllib.h"
 
 
-u16	CBone::get_game_mtl_idx	( )			const	
+u16 CBone::get_game_mtl_idx() const
 {
-	return GMLib.GetMaterialIdx(game_mtl.c_str());
+    return GMLib.GetMaterialIdx(game_mtl.c_str());
 }
 
-static const Fobb	dummy = Fobb().identity();
-const	Fobb&		CBone::	get_obb				( )			const
+static const Fobb dummy = Fobb().identity();
+const Fobb& CBone::get_obb() const
 {
-	return dummy;
+    return dummy;
 }
 //////////////////////////////////////////////////////////////////////////
 // BoneInstance methods
 
 
 
-void	ENGINE_API	CBoneInstance::set_param	(u32 idx, float data)
+void ENGINE_API CBoneInstance::set_param(u32 idx, float data)
 {
-	VERIFY		(idxSelfID);
-		children[i]->DebugQuery(L);
-	}
+    for (u32 i = 0; i < children.size(); i++)
+    {
+        L.push_back(SelfID);
+        L.push_back(children[i]->SelfID);
+        children[i]->DebugQuery(L);
+    }
 }
 #endif
 
-void ENGINE_API	CBoneData::CalculateM2B(const Fmatrix& parent)
+void ENGINE_API CBoneData::CalculateM2B(const Fmatrix& parent)
 {
-	// Build matrix
-	m2b_transform.mul_43	(parent,bind_transform);
+    // Build matrix
+    m2b_transform.mul_43(parent, bind_transform);
 
-	// Calculate children
-	for (xr_vector::iterator C=children.begin(); C!=children.end(); C++)
-		(*C)->CalculateM2B	(m2b_transform);
+    // Calculate children
+    for (xr_vector::iterator C = children.begin(); C != children.end(); C++)
+        (*C)->CalculateM2B(m2b_transform);
 
-	m2b_transform.invert	();            
+    m2b_transform.invert();
 }
diff --git a/src/xrEngine/bone.h b/src/xrEngine/bone.h
index bcb9855b39f..3794cc47e45 100644
--- a/src/xrEngine/bone.h
+++ b/src/xrEngine/bone.h
@@ -9,126 +9,126 @@
 // refs
 class CBone;
 
-#define	BI_NONE				(u16(-1))
+#define BI_NONE (u16(-1))
 
-#define OGF_IKDATA_VERSION	0x0001
+#define OGF_IKDATA_VERSION 0x0001
 
-#define	MAX_BONE_PARAMS		4
+#define MAX_BONE_PARAMS 4
 
 class ENGINE_API CBoneInstance;
 // callback
-typedef void  _BCL BoneCallbackFunction	(CBoneInstance* P);
-typedef		BoneCallbackFunction*		BoneCallback;
-//typedef void  (* BoneCallback)		(CBoneInstance* P);
+typedef void _BCL BoneCallbackFunction(CBoneInstance* P);
+typedef BoneCallbackFunction* BoneCallback;
+//typedef void (* BoneCallback) (CBoneInstance* P);
 
 //*** Bone Instance *******************************************************************************
 #pragma pack(push,8)
-class ENGINE_API		CBoneInstance
+class ENGINE_API CBoneInstance
 {
 public:
-	// data
-	Fmatrix				mTransform;							// final x-form matrix (local to model)
-	Fmatrix				mRenderTransform;					// final x-form matrix (model_base -> bone -> model)
+    // data
+    Fmatrix mTransform; // final x-form matrix (local to model)
+    Fmatrix mRenderTransform; // final x-form matrix (model_base -> bone -> model)
 private:
-	BoneCallback		Callback;
-	void*				Callback_Param;
-	BOOL				Callback_overwrite;					// performance hint - don't calc anims
-	u32					Callback_type;	
+    BoneCallback Callback;
+    void* Callback_Param;
+    BOOL Callback_overwrite; // performance hint - don't calc anims
+    u32 Callback_type;
 public:
-	float				param			[MAX_BONE_PARAMS];	// 
-	//
-	// methods
+    float param[MAX_BONE_PARAMS]; //
+    //
+    // methods
 public:
-	IC	BoneCallback	_BCL	callback()					{ return  Callback; }
-	IC	void*			_BCL	callback_param()			{ return Callback_Param;	}
-	IC	BOOL			_BCL	callback_overwrite()		{ return Callback_overwrite; }					// performance hint - don't calc anims
-	IC	u32				_BCL	callback_type()				{ return Callback_type; }	
+    IC BoneCallback _BCL callback() { return Callback; }
+    IC void* _BCL callback_param() { return Callback_Param; }
+    IC BOOL _BCL callback_overwrite() { return Callback_overwrite; } // performance hint - don't calc anims
+    IC u32 _BCL callback_type() { return Callback_type; }
 public:
-	IC void				_BCL	construct();
-
-	void	_BCL set_callback	(u32 Type, BoneCallback C, void* Param,  BOOL overwrite=FALSE)
-	{	
-		Callback			= C; 
-		Callback_Param		= Param; 
-		Callback_overwrite	= overwrite;
-		Callback_type		= Type;
-	}
-
-	void	_BCL reset_callback()
-	{
-		Callback			= 0; 
-		Callback_Param		= 0; 
-		Callback_overwrite	= FALSE;
-		Callback_type		= 0;
-	}
-	void		_BCL		set_callback_overwrite(BOOL v){ Callback_overwrite = v; }
-
-	void				set_param		(u32 idx, float data);
-	float				get_param		(u32 idx);
-
-	u32					mem_usage		(){return sizeof(*this);}
+    IC void _BCL construct();
+
+    void _BCL set_callback(u32 Type, BoneCallback C, void* Param, BOOL overwrite = FALSE)
+    {
+        Callback = C;
+        Callback_Param = Param;
+        Callback_overwrite = overwrite;
+        Callback_type = Type;
+    }
+
+    void _BCL reset_callback()
+    {
+        Callback = 0;
+        Callback_Param = 0;
+        Callback_overwrite = FALSE;
+        Callback_type = 0;
+    }
+    void _BCL set_callback_overwrite(BOOL v) { Callback_overwrite = v; }
+
+    void set_param(u32 idx, float data);
+    float get_param(u32 idx);
+
+    u32 mem_usage() { return sizeof(*this); }
 };
 #pragma pack(pop)
 
 #pragma pack( push,2 )
-struct ENGINE_API vertBoned1W			// (3+3+3+3+2+1)*4 = 15*4 = 60 bytes
+struct ENGINE_API vertBoned1W // (3+3+3+3+2+1)*4 = 15*4 = 60 bytes
 {
-	Fvector	P;
-	Fvector	N;
-	Fvector	T;
-	Fvector	B;
-	float	u,v;
-	u32		matrix;
-	void	get_pos( Fvector& p ) const { p.set(P); }
-#ifdef	DEBUG	
-	static const u8 bones_count = 1;
-	u16		get_bone_id(u8 bone)const{ VERIFY(bone0){
-	        friction	= F.r_float();
+        type = (EJointType)F.r_u32();
+        F.r(limits, sizeof(SJointLimit) * 3);
+        spring_factor = F.r_float();
+        damping_factor = F.r_float();
+        ik_flags.flags = F.r_u32();
+        break_force = F.r_float();
+        break_torque = F.r_float();
+        if (vers > 0)
+        {
+            friction = F.r_float();
         }
         return true;
     }
@@ -279,264 +289,266 @@ struct ECORE_API SJointIKData
 
 
 
-class 	IBoneData
+class IBoneData
 {
-	public:
-
-	virtual			IBoneData&	_BCL	GetChild		( u16 id )			= 0;
-	virtual const	IBoneData&	_BCL	GetChild		( u16 id )	const	= 0;
-	virtual			u16			_BCL	GetSelfID		( )			const	= 0;
-	virtual			u16			_BCL	GetNumChildren	( )			const	= 0;
-
-	virtual const SJointIKData& _BCL	get_IK_data			( )const	= 0;
-	virtual const	Fmatrix&	_BCL	get_bind_transform	( )const	= 0;
-	virtual const	SBoneShape&	_BCL	get_shape			( )const	= 0;
-	virtual const	Fobb&		_BCL	get_obb				( )const	= 0;
-	virtual const	Fvector&	_BCL	get_center_of_mass	( )const	= 0;
-	virtual			float		_BCL	get_mass			( )const	= 0;
-	virtual			u16			_BCL	get_game_mtl_idx	( )const	= 0;
-	virtual			u16			_BCL	GetParentID			( ) const	= 0;
-	virtual			float		_BCL	lo_limit			( u8 k )	const	= 0;
-	virtual			float		_BCL	hi_limit			( u8 k )	const	= 0;
-	
+public:
+
+    virtual IBoneData& _BCL GetChild(u16 id) = 0;
+    virtual const IBoneData& _BCL GetChild(u16 id) const = 0;
+    virtual u16 _BCL GetSelfID() const = 0;
+    virtual u16 _BCL GetNumChildren() const = 0;
+
+    virtual const SJointIKData& _BCL get_IK_data()const = 0;
+    virtual const Fmatrix& _BCL get_bind_transform()const = 0;
+    virtual const SBoneShape& _BCL get_shape()const = 0;
+    virtual const Fobb& _BCL get_obb()const = 0;
+    virtual const Fvector& _BCL get_center_of_mass()const = 0;
+    virtual float _BCL get_mass()const = 0;
+    virtual u16 _BCL get_game_mtl_idx()const = 0;
+    virtual u16 _BCL GetParentID() const = 0;
+    virtual float _BCL lo_limit(u8 k) const = 0;
+    virtual float _BCL hi_limit(u8 k) const = 0;
+
 };
 
-//static const Fobb	dummy ;//= Fobb().identity();
+//static const Fobb dummy ;//= Fobb().identity();
 // refs
 class CBone;
-DEFINE_VECTOR		    (CBone*,BoneVec,BoneIt);
+DEFINE_VECTOR(CBone*, BoneVec, BoneIt);
 
-class ECORE_API CBone:
-	public CBoneInstance,
-	public IBoneData
+class ECORE_API CBone :
+    public CBoneInstance,
+    public IBoneData
 {
-	shared_str			name;
-	shared_str			parent_name;
-	shared_str			wmap;
-	Fvector			    rest_offset;
-	Fvector			    rest_rotate;    // XYZ format (Game format)
-	float			    rest_length;
+    shared_str name;
+    shared_str parent_name;
+    shared_str wmap;
+    Fvector rest_offset;
+    Fvector rest_rotate; // XYZ format (Game format)
+    float rest_length;
 
-	Fvector			    mot_offset;
-	Fvector			    mot_rotate;		// XYZ format (Game format)
-	float			    mot_length;
+    Fvector mot_offset;
+    Fvector mot_rotate; // XYZ format (Game format)
+    float mot_length;
 
-    Fmatrix			    mot_transform;
+    Fmatrix mot_transform;
 
-	Fmatrix				local_rest_transform;
-    Fmatrix			    rest_transform;
-    Fmatrix			    rest_i_transform;
+    Fmatrix local_rest_transform;
+    Fmatrix rest_transform;
+    Fmatrix rest_i_transform;
 
-    //Fmatrix			    last_transform;
+    //Fmatrix last_transform;
 
-    //Fmatrix				render_transform;
+    //Fmatrix render_transform;
 public:
-	int				    SelfID;
-    CBone*			    parent;
-    BoneVec				children;
+    int SelfID;
+    CBone* parent;
+    BoneVec children;
 public:
     // editor part
-    Flags8			    flags;    
-	enum{
-    	flSelected	    = (1<<0),
+    Flags8 flags;
+    enum
+    {
+        flSelected = (1 << 0),
     };
-    SJointIKData	    IK_data;
-    shared_str			game_mtl;
-    SBoneShape		    shape;
+    SJointIKData IK_data;
+    shared_str game_mtl;
+    SBoneShape shape;
 
-    float			    mass;
-    Fvector			    center_of_mass;
+    float mass;
+    Fvector center_of_mass;
 public:
-					    CBone			();
-	virtual			    ~CBone			();
+    CBone();
+    virtual ~CBone();
 
-	void			    SetName			(const char* p){name		= p; xr_strlwr(name);		}
-	void			    SetParentName	(const char* p){parent_name	= p; xr_strlwr(parent_name);}
-	void			    SetWMap			(const char* p){wmap		= p;}
-	void			    SetRestParams	(float length, const Fvector& offset, const Fvector& rotate){rest_offset.set(offset);rest_rotate.set(rotate);rest_length=length;};
+    void SetName(const char* p) { name = p; xr_strlwr(name); }
+    void SetParentName(const char* p) { parent_name = p; xr_strlwr(parent_name); }
+    void SetWMap(const char* p) { wmap = p; }
+    void SetRestParams(float length, const Fvector& offset, const Fvector& rotate) { rest_offset.set(offset); rest_rotate.set(rotate); rest_length = length; };
 
-	shared_str		    Name			(){return name;}
-	shared_str		    ParentName		(){return parent_name;}
-	shared_str		    WMap			(){return wmap;}
-	IC CBone*		    Parent			(){return parent;}
-    IC BOOL			    IsRoot			(){return (parent==0);}
-	shared_str&		    NameRef			(){return name;}
+    shared_str Name() { return name; }
+    shared_str ParentName() { return parent_name; }
+    shared_str WMap() { return wmap; }
+    IC CBone* Parent() { return parent; }
+    IC BOOL IsRoot() { return (parent == 0); }
+    shared_str& NameRef() { return name; }
 
     // transformation
-    const Fvector&      _Offset			(){return mot_offset;}
-    const Fvector&      _Rotate			(){return mot_rotate;}
-    float			    _Length			(){return mot_length;}
-    IC Fmatrix&		    _RTransform		(){return rest_transform;}
-    IC Fmatrix&		    _RITransform	(){return rest_i_transform;}
-    IC Fmatrix&		    _LRTransform	(){return local_rest_transform;}
-    IC Fmatrix&		    _MTransform		(){return mot_transform;}
-    
-	IC Fmatrix&		    _LTransform		(){return mTransform;}//{return last_transform;}
-    IC const Fmatrix&	_LTransform		() const {return mTransform;}
-    
-    IC Fmatrix&		    _RenderTransform(){return mRenderTransform;}//{return render_transform;}
-	IC Fvector&			_RestOffset		(){return rest_offset;}
-	IC Fvector&		    _RestRotate		(){return rest_rotate;}
-    
-	void			    _Update			(const Fvector& T, const Fvector& R){mot_offset.set(T); mot_rotate.set(R); mot_length=rest_length;}
-    void			    Reset			(){mot_offset.set(rest_offset); mot_rotate.set(rest_rotate); mot_length=rest_length;}
+    const Fvector& _Offset() { return mot_offset; }
+    const Fvector& _Rotate() { return mot_rotate; }
+    float _Length() { return mot_length; }
+    IC Fmatrix& _RTransform() { return rest_transform; }
+    IC Fmatrix& _RITransform() { return rest_i_transform; }
+    IC Fmatrix& _LRTransform() { return local_rest_transform; }
+    IC Fmatrix& _MTransform() { return mot_transform; }
+
+    IC Fmatrix& _LTransform() { return mTransform; } //{return last_transform;}
+    IC const Fmatrix& _LTransform() const { return mTransform; }
+
+    IC Fmatrix& _RenderTransform() { return mRenderTransform; } //{return render_transform;}
+    IC Fvector& _RestOffset() { return rest_offset; }
+    IC Fvector& _RestRotate() { return rest_rotate; }
+
+    void _Update(const Fvector& T, const Fvector& R) { mot_offset.set(T); mot_rotate.set(R); mot_length = rest_length; }
+    void Reset() { mot_offset.set(rest_offset); mot_rotate.set(rest_rotate); mot_length = rest_length; }
 
     // IO
-	void			    Save			(IWriter& F);
-	void			    Load_0			(IReader& F);
-	void			    Load_1			(IReader& F);
+    void Save(IWriter& F);
+    void Load_0(IReader& F);
+    void Load_1(IReader& F);
 #ifdef _LW_EXPORT
-    void			    ParseBone(LWItemID bone);
+    void ParseBone(LWItemID bone);
 #endif
-IC	float	_BCL		engine_lo_limit ( u8 k ) const	{ return -IK_data.limits[k].limit.y; }
-IC	float	_BCL		engine_hi_limit ( u8 k ) const	{ return -IK_data.limits[k].limit.x; }
+    IC float _BCL engine_lo_limit(u8 k) const { return -IK_data.limits[k].limit.y; }
+    IC float _BCL engine_hi_limit(u8 k) const { return -IK_data.limits[k].limit.x; }
+
+    IC float _BCL editor_lo_limit(u8 k) const { return IK_data.limits[k].limit.x; }
+    IC float _BCL editor_hi_limit(u8 k) const { return IK_data.limits[k].limit.y; }
 
-IC	float	_BCL		editor_lo_limit ( u8 k ) const	{ return IK_data.limits[k].limit.x; }
-IC	float	_BCL		editor_hi_limit ( u8 k ) const	{ return IK_data.limits[k].limit.y; }
 
 
 
+    void SaveData(IWriter& F);
+    void LoadData(IReader& F);
+    void ResetData();
+    void CopyData(CBone* bone);
 
-	void			    SaveData		(IWriter& F);
-	void			    LoadData		(IReader& F);
-    void			    ResetData		();
-    void			    CopyData		(CBone* bone);
-    
 #if defined _EDITOR || defined _MAYA_EXPORT
-	void			    ShapeScale		(const Fvector& amount);
-	void			    ShapeRotate		(const Fvector& amount);
-	void			    ShapeMove		(const Fvector& amount);
-	void			    BindRotate		(const Fvector& amount);
-	void			    BindMove		(const Fvector& amount);
-	void			    BoneMove		(const Fvector& amount);
-	void			    BoneRotate		(const Fvector& axis, float angle);
+    void ShapeScale(const Fvector& amount);
+    void ShapeRotate(const Fvector& amount);
+    void ShapeMove(const Fvector& amount);
+    void BindRotate(const Fvector& amount);
+    void BindMove(const Fvector& amount);
+    void BoneMove(const Fvector& amount);
+    void BoneRotate(const Fvector& axis, float angle);
 
-	bool 			    Pick			(float& dist, const Fvector& S, const Fvector& D, const Fmatrix& parent);
+    bool Pick(float& dist, const Fvector& S, const Fvector& D, const Fmatrix& parent);
 
-    void			    Select			(BOOL flag)	{ flags.set(flSelected,flag); }
-    bool			    Selected		(){return !!flags.is(flSelected);}
+    void Select(BOOL flag) { flags.set(flSelected, flag); }
+    bool Selected() { return !!flags.is(flSelected); }
 
-    void			    ClampByLimits	();
+    void ClampByLimits();
 
-    bool 			    ExportOGF		(IWriter& F);
+    bool ExportOGF(IWriter& F);
 #endif
 private:
-				IBoneData&		_BCL	GetChild			( u16 id )			{return *children[id];}
-		const	IBoneData&		_BCL	GetChild			( u16 id )	const	{return *children[id];}
-        		u16				_BCL	GetSelfID			( )			const	{return (u16)SelfID;}
-				u16				_BCL	GetNumChildren		( )			const	{return u16( children.size() );}
-		const	SJointIKData&	_BCL	get_IK_data			( )			const	{return	IK_data;}
-		const	Fmatrix&		_BCL	get_bind_transform	( )			const	
-		{
-			
-				return	local_rest_transform;
-
-		}
-		const	SBoneShape&		_BCL	get_shape			( )			const	{return shape;}
-
-		const	Fobb&			_BCL	get_obb				( )			const	;
-		const	Fvector&		_BCL	get_center_of_mass	( )			const	{return center_of_mass;}
-				float			_BCL	get_mass			( )			const	{return mass;}
-				u16				_BCL	get_game_mtl_idx	( )			const	;
-				u16				_BCL	GetParentID			( )			const	{if(parent) return u16(parent->SelfID); else return u16(-1);};
-				float			_BCL	lo_limit			( u8 k )	const	{ return engine_lo_limit(k); }
-				float			_BCL	hi_limit			( u8 k )	const	{ return engine_hi_limit(k); }
+    IBoneData& _BCL GetChild(u16 id) { return *children[id]; }
+    const IBoneData& _BCL GetChild(u16 id) const { return *children[id]; }
+    u16 _BCL GetSelfID() const { return (u16)SelfID; }
+    u16 _BCL GetNumChildren() const { return u16(children.size()); }
+    const SJointIKData& _BCL get_IK_data() const { return IK_data; }
+    const Fmatrix& _BCL get_bind_transform() const
+    {
+
+        return local_rest_transform;
+
+    }
+    const SBoneShape& _BCL get_shape() const { return shape; }
+
+    const Fobb& _BCL get_obb() const;
+    const Fvector& _BCL get_center_of_mass() const { return center_of_mass; }
+    float _BCL get_mass() const { return mass; }
+    u16 _BCL get_game_mtl_idx() const;
+    u16 _BCL GetParentID() const { if (parent) return u16(parent->SelfID); else return u16(-1); };
+    float _BCL lo_limit(u8 k) const { return engine_lo_limit(k); }
+    float _BCL hi_limit(u8 k) const { return engine_hi_limit(k); }
 };
 
 //*** Shared Bone Data ****************************************************************************
 class CBoneData;
 // t-defs
-typedef xr_vector		vecBones;
-typedef vecBones::iterator			vecBonesIt;
+typedef xr_vector vecBones;
+typedef vecBones::iterator vecBonesIt;
 
 
-class 	ENGINE_API	CBoneData:
-	public IBoneData
+class ENGINE_API CBoneData :
+    public IBoneData
 {
 protected:
-	u16					SelfID;
-	u16					ParentID;
+    u16 SelfID;
+    u16 ParentID;
 public:
-	shared_str			name;
+    shared_str name;
 
 
-	Fobb				obb;			
+    Fobb obb;
 
-	Fmatrix				bind_transform;
-	Fmatrix				m2b_transform;	// model to bone conversion transform
-	SBoneShape			shape;
-	shared_str			game_mtl_name;
-	u16					game_mtl_idx;
-	SJointIKData		IK_data;
-	float				mass;
-	Fvector				center_of_mass;
+    Fmatrix bind_transform;
+    Fmatrix m2b_transform; // model to bone conversion transform
+    SBoneShape shape;
+    shared_str game_mtl_name;
+    u16 game_mtl_idx;
+    SJointIKData IK_data;
+    float mass;
+    Fvector center_of_mass;
 
 
-	vecBones			children;		// bones which are slaves to this
+    vecBones children; // bones which are slaves to this
 
-	DEFINE_VECTOR		(u16,FacesVec,FacesVecIt);
-	DEFINE_VECTOR		(FacesVec,ChildFacesVec,ChildFacesVecIt);
-	ChildFacesVec		child_faces;	// shared
-public:    
-	CBoneData		(u16 ID):SelfID(ID)	{VERIFY(SelfID!=BI_NONE);}
-	virtual				~CBoneData		()					{}
+    DEFINE_VECTOR(u16, FacesVec, FacesVecIt);
+    DEFINE_VECTOR(FacesVec, ChildFacesVec, ChildFacesVecIt);
+    ChildFacesVec child_faces; // shared
+public:
+    CBoneData(u16 ID) :SelfID(ID) { VERIFY(SelfID != BI_NONE); }
+    virtual ~CBoneData() {}
 #ifdef DEBUG
-	typedef svector	BoneDebug;
-	void						DebugQuery		(BoneDebug& L);
+    typedef svector BoneDebug;
+    void DebugQuery(BoneDebug& L);
 #endif
-	IC void				SetParentID		(u16 id){ParentID=id;}
-
-	IC u16		_BCL	GetSelfID		() const {return SelfID;}
-	IC u16		_BCL	GetParentID		() const {return ParentID;}
-
-	// assign face
-	void				AppendFace		(u16 child_idx, u16 idx)
-	{
-		child_faces[child_idx].push_back(idx);
-	}
-	// Calculation
-	void				CalculateM2B	(const Fmatrix& Parent);
+    IC void SetParentID(u16 id) { ParentID = id; }
+
+    IC u16 _BCL GetSelfID() const { return SelfID; }
+    IC u16 _BCL GetParentID() const { return ParentID; }
+
+    // assign face
+    void AppendFace(u16 child_idx, u16 idx)
+    {
+        child_faces[child_idx].push_back(idx);
+    }
+    // Calculation
+    void CalculateM2B(const Fmatrix& Parent);
 private:
-				IBoneData&		_BCL	GetChild			( u16 id ) { return *children[id]; }
-		const	IBoneData&		_BCL	GetChild			( u16 id )	const { return *children[id]; }
-				u16				_BCL	GetNumChildren		( )			const { return (u16)children.size(); }
-		const	SJointIKData&	_BCL	get_IK_data			( )			const	{return	IK_data;}
-		const	Fmatrix&		_BCL	get_bind_transform	( )			const	{return	bind_transform;}
-		const	SBoneShape&		_BCL	get_shape			( )			const	{return shape;}
-		const	Fobb&			_BCL	get_obb				( )			const	{return obb;}
-		const	Fvector&		_BCL	get_center_of_mass	( )			const	{return center_of_mass;}
-				float			_BCL	get_mass			( )			const	{return mass;}
-				u16				_BCL	get_game_mtl_idx	( )			const	{return game_mtl_idx;}
-				float			_BCL	lo_limit			( u8 k )	const	{return IK_data.limits[k].limit.x;}
-				float			_BCL	hi_limit			( u8 k )	const	{return IK_data.limits[k].limit.y;}
+    IBoneData& _BCL GetChild(u16 id) { return *children[id]; }
+    const IBoneData& _BCL GetChild(u16 id) const { return *children[id]; }
+    u16 _BCL GetNumChildren() const { return (u16)children.size(); }
+    const SJointIKData& _BCL get_IK_data() const { return IK_data; }
+    const Fmatrix& _BCL get_bind_transform() const { return bind_transform; }
+    const SBoneShape& _BCL get_shape() const { return shape; }
+    const Fobb& _BCL get_obb() const { return obb; }
+    const Fvector& _BCL get_center_of_mass() const { return center_of_mass; }
+    float _BCL get_mass() const { return mass; }
+    u16 _BCL get_game_mtl_idx() const { return game_mtl_idx; }
+    float _BCL lo_limit(u8 k) const { return IK_data.limits[k].limit.x; }
+    float _BCL hi_limit(u8 k) const { return IK_data.limits[k].limit.y; }
 public:
-	virtual u32			mem_usage		()
-	{
-		u32 sz			= sizeof(*this)+sizeof(vecBones::value_type)*children.size();
-		for (ChildFacesVecIt c_it=child_faces.begin(); c_it!=child_faces.end(); c_it++)
-			sz			+= c_it->size()*sizeof(FacesVec::value_type)+sizeof(*c_it);
-		return			sz;
-	}
+    virtual u32 mem_usage()
+    {
+        u32 sz = sizeof(*this) + sizeof(vecBones::value_type)*children.size();
+        for (ChildFacesVecIt c_it = child_faces.begin(); c_it != child_faces.end(); c_it++)
+            sz += c_it->size()*sizeof(FacesVec::value_type) + sizeof(*c_it);
+        return sz;
+    }
 };
 
 
 
 
-enum EBoneCallbackType{
-	bctDummy			= u32(0),	// 0 - required!!!
-	bctPhysics,
-	bctCustom,
-	bctForceU32			= u32(-1),
+enum EBoneCallbackType
+{
+    bctDummy = u32(0), // 0 - required!!!
+    bctPhysics,
+    bctCustom,
+    bctForceU32 = u32(-1),
 };
 
 
-IC void		CBoneInstance::construct	()
+IC void CBoneInstance::construct()
 {
-	ZeroMemory					(this,sizeof(*this));
-	mTransform.identity			();
+    ZeroMemory(this, sizeof(*this));
+    mTransform.identity();
 
-	mRenderTransform.identity	();
-	Callback_overwrite			= FALSE;
+    mRenderTransform.identity();
+    Callback_overwrite = FALSE;
 }
 
 
diff --git a/src/xrEngine/cf_dynamic_mesh.cpp b/src/xrEngine/cf_dynamic_mesh.cpp
index b84779cd000..228aaf596db 100644
--- a/src/xrEngine/cf_dynamic_mesh.cpp
+++ b/src/xrEngine/cf_dynamic_mesh.cpp
@@ -1,70 +1,70 @@
-#include	"stdafx.h"
+#include "stdafx.h"
 
-#include	"cf_dynamic_mesh.h"
+#include "cf_dynamic_mesh.h"
 
-#include	"xr_object.h"
+#include "xr_object.h"
 
 #include "../Include/xrRender/RenderVisual.h"
 #include "../Include/xrRender/Kinematics.h"
 
 #ifdef DEBUG
-#include	"iphdebug.h"
+#include "iphdebug.h"
 #endif
 
-BOOL	CCF_DynamicMesh::_RayQuery( const collide::ray_defs& Q, collide::rq_results& R)
+BOOL CCF_DynamicMesh::_RayQuery(const collide::ray_defs& Q, collide::rq_results& R)
 {
-	int s_count = R.r_count();
-	BOOL res = inherited::_RayQuery( Q, R );
-	if( !res )
-		return FALSE;
+    int s_count = R.r_count();
+    BOOL res = inherited::_RayQuery(Q, R);
+    if (!res)
+        return FALSE;
 
-	VERIFY( owner );
-	VERIFY( owner->Visual() );
-	IKinematics *K = owner->Visual()->dcast_PKinematics();
-	
-	struct spick
-	{
-		 const collide::ray_defs& Q;
-		 const  CObject			& obj;
-		 IKinematics			& K;
-		 
-		 spick(  const collide::ray_defs& Q_, const CObject &obj_, IKinematics &K_ ): Q( Q_ ), obj( obj_ ), K( K_ )
-		 {
+    VERIFY(owner);
+    VERIFY(owner->Visual());
+    IKinematics* K = owner->Visual()->dcast_PKinematics();
 
-		 }
-		 
-		 bool operator() ( collide::rq_result &r )
-		{
-			IKinematics::pick_result br;
-			VERIFY( r.O == &obj );
-			bool  res = K.PickBone( obj.XFORM(), br, Q.range, Q.start, Q.dir, (u16) r.element ) ;
-			if(res)
-			{
-				r.range = br.dist;
-			}
-#if	0
-			if(res)
-			{
-				ph_debug_render->open_cashed_draw();
-				ph_debug_render->draw_tri(  br.tri[0], br.tri[1], br.tri[2], D3DCOLOR_ARGB(50, 255,0,0), 0 );
-				ph_debug_render->close_cashed_draw(50000);
-			}
+    struct spick
+    {
+        const collide::ray_defs& Q;
+        const CObject& obj;
+        IKinematics& K;
+
+        spick(const collide::ray_defs& Q_, const CObject& obj_, IKinematics& K_) : Q(Q_), obj(obj_), K(K_)
+        {
+
+        }
+
+        bool operator() (collide::rq_result& r)
+        {
+            IKinematics::pick_result br;
+            VERIFY(r.O == &obj);
+            bool res = K.PickBone(obj.XFORM(), br, Q.range, Q.start, Q.dir, (u16)r.element);
+            if (res)
+            {
+                r.range = br.dist;
+            }
+#if 0
+            if (res)
+            {
+                ph_debug_render->open_cashed_draw();
+                ph_debug_render->draw_tri(br.tri[0], br.tri[1], br.tri[2], D3DCOLOR_ARGB(50, 255, 0, 0), 0);
+                ph_debug_render->close_cashed_draw(50000);
+            }
 #endif
-			return !res;
-		}
-		private:
-			spick& operator = (spick& ){ NODEFAULT;  return *this; }
-	} pick( (collide::ray_defs&) (Q), (const CObject &)(*owner),(IKinematics&) (*K) );
-	
-	R.r_results().erase( std::remove_if( R.r_results().begin() + s_count, R.r_results().end() , pick), R.r_results().end() );
-	/*
-	for( collide::rq_result* i = R.r_begin() + s_count; i < R.r_end(); ++i )
-	{
-		IKinematics::pick_result r;
-		if( K->PickBone( owner->XFORM(), r, Q.range, Q.start, Q.dir, (u16) i->element ) )
-			return TRUE;
-	}
-	*/
-	VERIFY( R.r_count() >= s_count );
-	return R.r_count() > s_count;
+            return !res;
+        }
+    private:
+        spick& operator = (spick&) { NODEFAULT; return *this; }
+    } pick((collide::ray_defs&) (Q), (const CObject&)(*owner), (IKinematics&)(*K));
+
+    R.r_results().erase(std::remove_if(R.r_results().begin() + s_count, R.r_results().end(), pick), R.r_results().end());
+    /*
+    for( collide::rq_result* i = R.r_begin() + s_count; i < R.r_end(); ++i )
+    {
+    IKinematics::pick_result r;
+    if( K->PickBone( owner->XFORM(), r, Q.range, Q.start, Q.dir, (u16) i->element ) )
+    return TRUE;
+    }
+    */
+    VERIFY(R.r_count() >= s_count);
+    return R.r_count() > s_count;
 }
\ No newline at end of file
diff --git a/src/xrEngine/cf_dynamic_mesh.h b/src/xrEngine/cf_dynamic_mesh.h
index 2f0395d47ea..683f250cba7 100644
--- a/src/xrEngine/cf_dynamic_mesh.h
+++ b/src/xrEngine/cf_dynamic_mesh.h
@@ -3,12 +3,12 @@
 #include "xr_collide_form.h"
 
 
-class ENGINE_API	CCF_DynamicMesh:
-public CCF_Skeleton
+class ENGINE_API CCF_DynamicMesh :
+    public CCF_Skeleton
 {
-	typedef	 CCF_Skeleton inherited;
+    typedef CCF_Skeleton inherited;
 public:
-						CCF_DynamicMesh	( CObject* _owner ) :CCF_Skeleton(_owner){};
+    CCF_DynamicMesh(CObject* _owner) :CCF_Skeleton(_owner) {};
 
-	virtual BOOL		_RayQuery		( const collide::ray_defs& Q, collide::rq_results& R);
+    virtual BOOL _RayQuery(const collide::ray_defs& Q, collide::rq_results& R);
 };
\ No newline at end of file
diff --git a/src/xrEngine/cl_intersect.h b/src/xrEngine/cl_intersect.h
index 35a48410ae3..638612f92bb 100644
--- a/src/xrEngine/cl_intersect.h
+++ b/src/xrEngine/cl_intersect.h
@@ -4,742 +4,849 @@
 
 namespace CDB
 {
-	//----------------------------------------------------------------------
-	// Name  : intersectRaySphere()
-	// Input : rO - origin of ray in world space
-	//         rV - _vector_ describing direction of ray in world space
-	//         sO - Origin of sphere
-	//         sR - radius of sphere
-	// Notes : Normalized directional vectors expected
-	// -----------------------------------------------------------------------
-	IC bool IntersectRaySphere(const Fvector& rO, const Fvector& rV, const Fvector& sO, float sR)
-	{
-		Fvector Q;
-		Q.sub(sO,rO);
-
-		float c = Q.magnitude();
-		float v = Q.dotproduct(rV);
-		float d = sR*sR - (c*c - v*v);
-
-		// If there was no intersection, return -1
-		return (d > 0.0);
-	}
-
-	//-- Ray-Triangle : 2nd level of indirection --------------------------------
-	IC bool TestRayTri(const Fvector& C, const Fvector& D, Fvector** p, float& u, float& v, float& range, bool bCull)
-	{
-		Fvector edge1, edge2, tvec, pvec, qvec;
-		float det,inv_det;
-		// find vectors for two edges sharing vert0
-		edge1.sub(*p[1], *p[0]);
-		edge2.sub(*p[2], *p[0]);
-		// begin calculating determinant - also used to calculate U parameter
-		pvec.crossproduct(D, edge2);
-		// if determinant is near zero, ray lies in plane of triangle
-		det = edge1.dotproduct(pvec);
-		if (bCull){						// define TEST_CULL if culling is desired
-			if (det < EPS)  return false;
-			tvec.sub(C, *p[0]);							// calculate distance from vert0 to ray origin
-			u = tvec.dotproduct(pvec);			// calculate U parameter and test bounds
-			if (u < 0.0 || u > det) return false;
-			qvec.crossproduct(tvec, edge1);				// prepare to test V parameter
-			v = D.dotproduct(qvec);			// calculate V parameter and test bounds
-			if (v < 0.0 || u + v > det) return false;
-			range = edge2.dotproduct(qvec);		// calculate t, scale parameters, ray intersects triangle
-			inv_det = 1.0f / det;
-			range *= inv_det;
-			u *= inv_det;
-			v *= inv_det;
-		}else{											// the non-culling branch
-			if (det > -EPS && det < EPS) return false;
-			inv_det = 1.0f / det;
-			tvec.sub(C, *p[0]);							// calculate distance from vert0 to ray origin
-			u = tvec.dotproduct(pvec)*inv_det;	// calculate U parameter and test bounds
-			if (u < 0.0f || u > 1.0f)    return false;
-			qvec.crossproduct(tvec, edge1);				// prepare to test V parameter
-			v = D.dotproduct(qvec)*inv_det;	// calculate V parameter and test bounds
-			if (v < 0.0f || u + v > 1.0f) return false;
-			range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects triangle
-		}
-		return true;
-	}
-	//-- Ray-Triangle : 1st level of indirection --------------------------------
-	IC bool TestRayTri(const Fvector& C, const Fvector& D, Fvector* p, float& u, float& v, float& range, bool bCull)
-	{
-		Fvector edge1, edge2, tvec, pvec, qvec;
-		float det,inv_det;
-		// find vectors for two edges sharing vert0
-		edge1.sub(p[1], p[0]);
-		edge2.sub(p[2], p[0]);
-		// begin calculating determinant - also used to calculate U parameter
-		pvec.crossproduct(D, edge2);
-		// if determinant is near zero, ray lies in plane of triangle
-		det = edge1.dotproduct(pvec);
-		if (bCull){						// define TEST_CULL if culling is desired
-			if (det < EPS)  return false;
-			tvec.sub(C, p[0]);							// calculate distance from vert0 to ray origin
-			u = tvec.dotproduct(pvec);			// calculate U parameter and test bounds
-			if (u < 0.0f || u > det) return false;
-			qvec.crossproduct(tvec, edge1);				// prepare to test V parameter
-			v = D.dotproduct(qvec);			// calculate V parameter and test bounds
-			if (v < 0.0f || u + v > det) return false;
-			range = edge2.dotproduct(qvec);		// calculate t, scale parameters, ray intersects triangle
-			inv_det = 1.0f / det;
-			range *= inv_det;
-			u *= inv_det;
-			v *= inv_det;
-		}else{											// the non-culling branch
-			if (det > -EPS && det < EPS) return false;
-			inv_det = 1.0f / det;
-			tvec.sub(C, p[0]);							// calculate distance from vert0 to ray origin
-			u = tvec.dotproduct(pvec)*inv_det;	// calculate U parameter and test bounds
-			if (u < 0.0f || u > 1.0f)    return false;
-			qvec.crossproduct(tvec, edge1);				// prepare to test V parameter
-			v = D.dotproduct(qvec)*inv_det;	// calculate V parameter and test bounds
-			if (v < 0.0f || u + v > 1.0f) return false;
-			range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects triangle
-		}
-		return true;
-	}
-
-	//-- Ray-Triangle(always return range) : 1st level of indirection --------------------------------
-	IC bool TestRayTri2(const Fvector& C, const Fvector& D, Fvector* p, float& range)
-	{
-		Fvector edge1, edge2, tvec, pvec, qvec;
-		float det,inv_det,u,v;
-
-		// find vectors for two edges sharing vert0
-		edge1.sub(p[1], p[0]);
-		edge2.sub(p[2], p[0]);
-		// begin calculating determinant - also used to calculate U parameter
-		pvec.crossproduct(D, edge2);
-		// if determinant is near zero, ray lies in plane of triangle
-		det = edge1.dotproduct(pvec);
-
-		if (_abs(det) < EPS_S)		{ range=-1; return false; }
-		inv_det = 1.0f / det;
-		tvec.sub(C, p[0]);					// calculate distance from vert0 to ray origin
-		u = tvec.dotproduct(pvec)*inv_det;	// calculate U parameter and test bounds
-		qvec.crossproduct(tvec, edge1);		// prepare to test V parameter
-		range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects plane
-		if (u < 0.0f || u > 1.0f)		return false;
-		v = D.dotproduct(qvec)*inv_det;		// calculate V parameter and test bounds
-		if (v < 0.0f || u + v > 1.0f) return false;
-		return true;
-	}
-	IC bool TestRayTri2(const Fvector& C, const Fvector& D, Fvector** p, float& range)
-	{
-		Fvector edge1, edge2, tvec, pvec, qvec;
-		float det,inv_det,u,v;
-
-		// find vectors for two edges sharing vert0
-		edge1.sub(*p[1], *p[0]);
-		edge2.sub(*p[2], *p[0]);
-		// begin calculating determinant - also used to calculate U parameter
-		pvec.crossproduct(D, edge2);
-		// if determinant is near zero, ray lies in plane of triangle
-		det = edge1.dotproduct(pvec);
-
-		if (_abs(det) < EPS_S)		{ range=-1; return false; }
-		inv_det = 1.0f / det;
-		tvec.sub(C, *p[0]);					// calculate distance from vert0 to ray origin
-		u = tvec.dotproduct(pvec)*inv_det;	// calculate U parameter and test bounds
-		qvec.crossproduct(tvec, edge1);		// prepare to test V parameter
-		range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects plane
-		if (u < 0.0f || u > 1.0f)		return false;
-		v = D.dotproduct(qvec)*inv_det;		// calculate V parameter and test bounds
-		if (v < 0.0f || u + v > 1.0f) return false;
-		return true;
-	}
-	//---------------------------------------------------------------------------
-	// macros for fast arithmetic
-	//---------------------------------------------------------------------------
-	//---------------------------------------------------------------------------
-	// compare [-r,r] to [NdD+dt*NdW]
+//----------------------------------------------------------------------
+// Name : intersectRaySphere()
+// Input : rO - origin of ray in world space
+// rV - _vector_ describing direction of ray in world space
+// sO - Origin of sphere
+// sR - radius of sphere
+// Notes : Normalized directional vectors expected
+// -----------------------------------------------------------------------
+IC bool IntersectRaySphere(const Fvector& rO, const Fvector& rV, const Fvector& sO, float sR)
+{
+    Fvector Q;
+    Q.sub(sO, rO);
+
+    float c = Q.magnitude();
+    float v = Q.dotproduct(rV);
+    float d = sR*sR - (c*c - v*v);
+
+    // If there was no intersection, return -1
+    return (d > 0.0);
+}
+
+//-- Ray-Triangle : 2nd level of indirection --------------------------------
+IC bool TestRayTri(const Fvector& C, const Fvector& D, Fvector** p, float& u, float& v, float& range, bool bCull)
+{
+    Fvector edge1, edge2, tvec, pvec, qvec;
+    float det, inv_det;
+    // find vectors for two edges sharing vert0
+    edge1.sub(*p[1], *p[0]);
+    edge2.sub(*p[2], *p[0]);
+    // begin calculating determinant - also used to calculate U parameter
+    pvec.crossproduct(D, edge2);
+    // if determinant is near zero, ray lies in plane of triangle
+    det = edge1.dotproduct(pvec);
+    if (bCull)
+    {
+        // define TEST_CULL if culling is desired
+        if (det < EPS) return false;
+        tvec.sub(C, *p[0]); // calculate distance from vert0 to ray origin
+        u = tvec.dotproduct(pvec); // calculate U parameter and test bounds
+        if (u < 0.0 || u > det) return false;
+        qvec.crossproduct(tvec, edge1); // prepare to test V parameter
+        v = D.dotproduct(qvec); // calculate V parameter and test bounds
+        if (v < 0.0 || u + v > det) return false;
+        range = edge2.dotproduct(qvec); // calculate t, scale parameters, ray intersects triangle
+        inv_det = 1.0f / det;
+        range *= inv_det;
+        u *= inv_det;
+        v *= inv_det;
+    }
+    else
+    {
+        // the non-culling branch
+        if (det > -EPS && det < EPS) return false;
+        inv_det = 1.0f / det;
+        tvec.sub(C, *p[0]); // calculate distance from vert0 to ray origin
+        u = tvec.dotproduct(pvec)*inv_det; // calculate U parameter and test bounds
+        if (u < 0.0f || u > 1.0f) return false;
+        qvec.crossproduct(tvec, edge1); // prepare to test V parameter
+        v = D.dotproduct(qvec)*inv_det; // calculate V parameter and test bounds
+        if (v < 0.0f || u + v > 1.0f) return false;
+        range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects triangle
+    }
+    return true;
+}
+//-- Ray-Triangle : 1st level of indirection --------------------------------
+IC bool TestRayTri(const Fvector& C, const Fvector& D, Fvector* p, float& u, float& v, float& range, bool bCull)
+{
+    Fvector edge1, edge2, tvec, pvec, qvec;
+    float det, inv_det;
+    // find vectors for two edges sharing vert0
+    edge1.sub(p[1], p[0]);
+    edge2.sub(p[2], p[0]);
+    // begin calculating determinant - also used to calculate U parameter
+    pvec.crossproduct(D, edge2);
+    // if determinant is near zero, ray lies in plane of triangle
+    det = edge1.dotproduct(pvec);
+    if (bCull)
+    {
+        // define TEST_CULL if culling is desired
+        if (det < EPS) return false;
+        tvec.sub(C, p[0]); // calculate distance from vert0 to ray origin
+        u = tvec.dotproduct(pvec); // calculate U parameter and test bounds
+        if (u < 0.0f || u > det) return false;
+        qvec.crossproduct(tvec, edge1); // prepare to test V parameter
+        v = D.dotproduct(qvec); // calculate V parameter and test bounds
+        if (v < 0.0f || u + v > det) return false;
+        range = edge2.dotproduct(qvec); // calculate t, scale parameters, ray intersects triangle
+        inv_det = 1.0f / det;
+        range *= inv_det;
+        u *= inv_det;
+        v *= inv_det;
+    }
+    else
+    {
+        // the non-culling branch
+        if (det > -EPS && det < EPS) return false;
+        inv_det = 1.0f / det;
+        tvec.sub(C, p[0]); // calculate distance from vert0 to ray origin
+        u = tvec.dotproduct(pvec)*inv_det; // calculate U parameter and test bounds
+        if (u < 0.0f || u > 1.0f) return false;
+        qvec.crossproduct(tvec, edge1); // prepare to test V parameter
+        v = D.dotproduct(qvec)*inv_det; // calculate V parameter and test bounds
+        if (v < 0.0f || u + v > 1.0f) return false;
+        range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects triangle
+    }
+    return true;
+}
+
+//-- Ray-Triangle(always return range) : 1st level of indirection --------------------------------
+IC bool TestRayTri2(const Fvector& C, const Fvector& D, Fvector* p, float& range)
+{
+    Fvector edge1, edge2, tvec, pvec, qvec;
+    float det, inv_det, u, v;
+
+    // find vectors for two edges sharing vert0
+    edge1.sub(p[1], p[0]);
+    edge2.sub(p[2], p[0]);
+    // begin calculating determinant - also used to calculate U parameter
+    pvec.crossproduct(D, edge2);
+    // if determinant is near zero, ray lies in plane of triangle
+    det = edge1.dotproduct(pvec);
+
+    if (_abs(det) < EPS_S) { range = -1; return false; }
+    inv_det = 1.0f / det;
+    tvec.sub(C, p[0]); // calculate distance from vert0 to ray origin
+    u = tvec.dotproduct(pvec)*inv_det; // calculate U parameter and test bounds
+    qvec.crossproduct(tvec, edge1); // prepare to test V parameter
+    range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects plane
+    if (u < 0.0f || u > 1.0f) return false;
+    v = D.dotproduct(qvec)*inv_det; // calculate V parameter and test bounds
+    if (v < 0.0f || u + v > 1.0f) return false;
+    return true;
+}
+IC bool TestRayTri2(const Fvector& C, const Fvector& D, Fvector** p, float& range)
+{
+    Fvector edge1, edge2, tvec, pvec, qvec;
+    float det, inv_det, u, v;
+
+    // find vectors for two edges sharing vert0
+    edge1.sub(*p[1], *p[0]);
+    edge2.sub(*p[2], *p[0]);
+    // begin calculating determinant - also used to calculate U parameter
+    pvec.crossproduct(D, edge2);
+    // if determinant is near zero, ray lies in plane of triangle
+    det = edge1.dotproduct(pvec);
+
+    if (_abs(det) < EPS_S) { range = -1; return false; }
+    inv_det = 1.0f / det;
+    tvec.sub(C, *p[0]); // calculate distance from vert0 to ray origin
+    u = tvec.dotproduct(pvec)*inv_det; // calculate U parameter and test bounds
+    qvec.crossproduct(tvec, edge1); // prepare to test V parameter
+    range = edge2.dotproduct(qvec)*inv_det;// calculate t, ray intersects plane
+    if (u < 0.0f || u > 1.0f) return false;
+    v = D.dotproduct(qvec)*inv_det; // calculate V parameter and test bounds
+    if (v < 0.0f || u + v > 1.0f) return false;
+    return true;
+}
+//---------------------------------------------------------------------------
+// macros for fast arithmetic
+//---------------------------------------------------------------------------
+//---------------------------------------------------------------------------
+// compare [-r,r] to [NdD+dt*NdW]
 #define TESTV0(NdD, R) \
-    if		(NdD> R) return false;\
-    else if	(NdD<-R) return false;
-	//---------------------------------------------------------------------------
-	// compare [-r,r] to [min{p,p+d0,p+d1},max{p,p+d0,p+d1}]
+ if (NdD> R) return false;\
+  else if (NdD<-R) return false;
+//---------------------------------------------------------------------------
+// compare [-r,r] to [min{p,p+d0,p+d1},max{p,p+d0,p+d1}]
 #define TESTV1(p,d0,d1,r){ \
-    if ( (p) > (r) ){ \
-	if ( (d0) >= 0.0f ){ \
-	if ( (d1) >= 0.0f ){ \
-				return false; \
-	}else{ \
-	if ( (p)+(d1) > (r) ) \
-	return false; \
-	} \
-	}else if ( (d1) <= (d0) ){ \
-	if ( (p)+(d1) > (r) ) \
-	return false; \
-	}else{ \
-	if ( (p)+(d0) > (r) ) \
-	return false; \
-	} \
-    }else if ( (p) < -(r) ){ \
-	if ( (d0) <= 0.0f ){ \
-	if ( (d1) <= 0.0f ){ \
-				return false; \
-	}else{ \
-	if ( (p)+(d1) < -(r) ) \
-	return false; \
-	} \
-	}else if ( (d1) >= (d0) ){ \
-	if ( (p)+(d1) < -(r) ) \
-	return false; \
-	}else{ \
-	if ( (p)+(d0) < -(r) ) \
-	return false; \
-	} \
-    } \
-	}
-	//---------------------------------------------------------------------------
-	// compare [-r,r] to [min{p,p+d},max{p,p+d}]
+ if ( (p) > (r) ){ \
+ if ( (d0) >= 0.0f ){ \
+ if ( (d1) >= 0.0f ){ \
+ return false; \
+  }else{ \
+ if ( (p)+(d1) > (r) ) \
+ return false; \
+  } \
+  }else if ( (d1) <= (d0) ){ \
+ if ( (p)+(d1) > (r) ) \
+ return false; \
+  }else{ \
+ if ( (p)+(d0) > (r) ) \
+ return false; \
+ } \
+  }else if ( (p) < -(r) ){ \
+ if ( (d0) <= 0.0f ){ \
+ if ( (d1) <= 0.0f ){ \
+ return false; \
+  }else{ \
+ if ( (p)+(d1) < -(r) ) \
+ return false; \
+  } \
+  }else if ( (d1) >= (d0) ){ \
+ if ( (p)+(d1) < -(r) ) \
+ return false; \
+  }else{ \
+ if ( (p)+(d0) < -(r) ) \
+ return false; \
+ } \
+  } \
+ }
+//---------------------------------------------------------------------------
+// compare [-r,r] to [min{p,p+d},max{p,p+d}]
 #define TESTV2(p,d,r){ \
-    if ( (p) > (r) ){ \
-	if ( (d) >= 0.0f ){ return false; \
-	}else{ if ( (p)+(d) > (r) ) return false; } \
-    }else if ( (p) < -(r) ){ \
-	if ( (d) <= 0.0f ){ return false; \
-	}else{ if ( (p)+(d) < -(r) ) return false; } \
-    } \
-	}
-	//---------------------------------------------------------------------------
-
-	IC bool TestBBoxTri(const Fmatrix33& A, const Fvector& T, const Fvector& extA, Fvector** p, BOOL bCulling){
-		// construct triangle normal, difference of center and vertex (18 ops)
-		Fvector D, E[2], N;
-		E[0].sub(*p[1],*p[0]);
-		E[1].sub(*p[2],*p[0]);
-		N.crossproduct(E[0],E[1]);
-
-		if (bCulling&&(A.k.dotproduct(N)>=0)) return false;
-
-		D.sub(*p[0],T);
-
-		// axis C+t*N
-		float A0dN = A.i.dotproduct(N);
-		float A1dN = A.j.dotproduct(N);
-		float A2dN = A.k.dotproduct(N);
-		float R = _abs(extA.x*A0dN)+_abs(extA.y*A1dN)+_abs(extA.z*A2dN);
-		float NdD = N.dotproduct(D);
-		TESTV0(NdD,R); //AXIS_N
-
-		// axis C+t*A0
-		float A0dD = A.i.dotproduct(D);
-		float A0dE0 = A.i.dotproduct(E[0]);
-		float A0dE1 = A.i.dotproduct(E[1]);
-		TESTV1(A0dD,A0dE0,A0dE1,extA.x); //AXIS_A0
-
-		// axis C+t*A1
-		float A1dD	= A.j.dotproduct(D);
-		float A1dE0 = A.j.dotproduct(E[0]);
-		float A1dE1 = A.j.dotproduct(E[1]);
-		TESTV1(A1dD,A1dE0,A1dE1,extA.y); //AXIS_A1
-
-		// axis C+t*A2
-		float A2dD	= A.k.dotproduct(D);
-		float A2dE0 = A.k.dotproduct(E[0]);
-		float A2dE1 = A.k.dotproduct(E[1]);
-		TESTV1(A2dD,A2dE0,A2dE1,extA.z); //AXIS_A2
-
-		// axis C+t*A0xE0
-		Fvector A0xE0;
-		A0xE0.crossproduct(A.i,E[0]);
-		float A0xE0dD = A0xE0.dotproduct(D);
-		R = _abs(extA.y*A2dE0)+_abs(extA.z*A1dE0);
-		TESTV2(A0xE0dD,A0dN,R); //AXIS_A0xE0
-
-		// axis C+t*A0xE1
-		Fvector A0xE1;
-		A0xE1.crossproduct(A.i,E[1]);
-		float A0xE1dD = A0xE1.dotproduct(D);
-		R = _abs(extA.y*A2dE1)+_abs(extA.z*A1dE1);
-		TESTV2(A0xE1dD,-A0dN,R); //AXIS_A0xE1
-
-		// axis C+t*A0xE2
-		float A1dE2 = A1dE1-A1dE0;
-		float A2dE2 = A2dE1-A2dE0;
-		float A0xE2dD = A0xE1dD-A0xE0dD;
-		R = _abs(extA.y*A2dE2)+_abs(extA.z*A1dE2);
-		TESTV2(A0xE2dD,-A0dN,R); //AXIS_A0xE2
-
-		// axis C+t*A1xE0
-		Fvector A1xE0;
-		A1xE0.crossproduct(A.j,E[0]);
-		float A1xE0dD = A1xE0.dotproduct(D);
-		R = _abs(extA.x*A2dE0)+_abs(extA.z*A0dE0);
-		TESTV2(A1xE0dD,A1dN,R); //AXIS_A1xE0
-
-		// axis C+t*A1xE1
-		Fvector A1xE1;
-		A1xE1.crossproduct(A.j,E[1]);
-		float A1xE1dD = A1xE1.dotproduct(D);
-		R = _abs(extA.x*A2dE1)+_abs(extA.z*A0dE1);
-		TESTV2(A1xE1dD,-A1dN,R); //AXIS_A1xE1
-
-		// axis C+t*A1xE2
-		float A0dE2 = A0dE1-A0dE0;
-		float A1xE2dD = A1xE1dD-A1xE0dD;
-		R = _abs(extA.x*A2dE2)+_abs(extA.z*A0dE2);
-		TESTV2(A1xE2dD,-A1dN,R); //AXIS_A1xE2
-
-		// axis C+t*A2xE0
-		Fvector A2xE0;
-		A2xE0.crossproduct(A.k,E[0]);
-		float A2xE0dD = A2xE0.dotproduct(D);
-		R = _abs(extA.x*A1dE0)+_abs(extA.y*A0dE0);
-		TESTV2(A2xE0dD,A2dN,R); //AXIS_A2xE0
-
-		// axis C+t*A2xE1
-		Fvector A2xE1;
-		A2xE1.crossproduct(A.k,E[1]);
-		float A2xE1dD = A2xE1.dotproduct(D);
-		R = _abs(extA.x*A1dE1)+_abs(extA.y*A0dE1);
-		TESTV2(A2xE1dD,-A2dN,R); //AXIS_A2xE1
-
-		// axis C+t*A2xE2
-		float A2xE2dD = A2xE1dD-A2xE0dD;
-		R = _abs(extA.x*A1dE2)+_abs(extA.y*A0dE2);
-		TESTV2(A2xE2dD,-A2dN,R); //AXIS_A2xE2
-
-		// intersection occurs
-		return true;
-	}
-	IC bool TestBBoxTri(const Fmatrix33& A, const Fvector& T, const Fvector& extA, Fvector* p, BOOL bCulling){
-		// construct triangle normal, difference of center and vertex (18 ops)
-		Fvector D, E[2], N;
-		E[0].sub(p[1],p[0]);
-		E[1].sub(p[2],p[0]);
-		N.crossproduct(E[0],E[1]);
-
-		if (bCulling&&(A.k.dotproduct(N)>=0)) return false;
-
-		D.sub(p[0],T);
-
-		// axis C+t*N
-		float A0dN = A.i.dotproduct(N);
-		float A1dN = A.j.dotproduct(N);
-		float A2dN = A.k.dotproduct(N);
-		float R = _abs(extA.x*A0dN)+_abs(extA.y*A1dN)+_abs(extA.z*A2dN);
-		float NdD = N.dotproduct(D);
-		TESTV0(NdD,R); //AXIS_N
-
-		// axis C+t*A0
-		float A0dD = A.i.dotproduct(D);
-		float A0dE0 = A.i.dotproduct(E[0]);
-		float A0dE1 = A.i.dotproduct(E[1]);
-		TESTV1(A0dD,A0dE0,A0dE1,extA.x); //AXIS_A0
-
-		// axis C+t*A1
-		float A1dD	= A.j.dotproduct(D);
-		float A1dE0 = A.j.dotproduct(E[0]);
-		float A1dE1 = A.j.dotproduct(E[1]);
-		TESTV1(A1dD,A1dE0,A1dE1,extA.y); //AXIS_A1
-
-		// axis C+t*A2
-		float A2dD	= A.k.dotproduct(D);
-		float A2dE0 = A.k.dotproduct(E[0]);
-		float A2dE1 = A.k.dotproduct(E[1]);
-		TESTV1(A2dD,A2dE0,A2dE1,extA.z); //AXIS_A2
-
-		// axis C+t*A0xE0
-		Fvector A0xE0;
-		A0xE0.crossproduct(A.i,E[0]);
-		float A0xE0dD = A0xE0.dotproduct(D);
-		R = _abs(extA.y*A2dE0)+_abs(extA.z*A1dE0);
-		TESTV2(A0xE0dD,A0dN,R); //AXIS_A0xE0
-
-		// axis C+t*A0xE1
-		Fvector A0xE1;
-		A0xE1.crossproduct(A.i,E[1]);
-		float A0xE1dD = A0xE1.dotproduct(D);
-		R = _abs(extA.y*A2dE1)+_abs(extA.z*A1dE1);
-		TESTV2(A0xE1dD,-A0dN,R); //AXIS_A0xE1
-
-		// axis C+t*A0xE2
-		float A1dE2 = A1dE1-A1dE0;
-		float A2dE2 = A2dE1-A2dE0;
-		float A0xE2dD = A0xE1dD-A0xE0dD;
-		R = _abs(extA.y*A2dE2)+_abs(extA.z*A1dE2);
-		TESTV2(A0xE2dD,-A0dN,R); //AXIS_A0xE2
-
-		// axis C+t*A1xE0
-		Fvector A1xE0;
-		A1xE0.crossproduct(A.j,E[0]);
-		float A1xE0dD = A1xE0.dotproduct(D);
-		R = _abs(extA.x*A2dE0)+_abs(extA.z*A0dE0);
-		TESTV2(A1xE0dD,A1dN,R); //AXIS_A1xE0
-
-		// axis C+t*A1xE1
-		Fvector A1xE1;
-		A1xE1.crossproduct(A.j,E[1]);
-		float A1xE1dD = A1xE1.dotproduct(D);
-		R = _abs(extA.x*A2dE1)+_abs(extA.z*A0dE1);
-		TESTV2(A1xE1dD,-A1dN,R); //AXIS_A1xE1
-
-		// axis C+t*A1xE2
-		float A0dE2 = A0dE1-A0dE0;
-		float A1xE2dD = A1xE1dD-A1xE0dD;
-		R = _abs(extA.x*A2dE2)+_abs(extA.z*A0dE2);
-		TESTV2(A1xE2dD,-A1dN,R); //AXIS_A1xE2
-
-		// axis C+t*A2xE0
-		Fvector A2xE0;
-		A2xE0.crossproduct(A.k,E[0]);
-		float A2xE0dD = A2xE0.dotproduct(D);
-		R = _abs(extA.x*A1dE0)+_abs(extA.y*A0dE0);
-		TESTV2(A2xE0dD,A2dN,R); //AXIS_A2xE0
-
-		// axis C+t*A2xE1
-		Fvector A2xE1;
-		A2xE1.crossproduct(A.k,E[1]);
-		float A2xE1dD = A2xE1.dotproduct(D);
-		R = _abs(extA.x*A1dE1)+_abs(extA.y*A0dE1);
-		TESTV2(A2xE1dD,-A2dN,R); //AXIS_A2xE1
-
-		// axis C+t*A2xE2
-		float A2xE2dD = A2xE1dD-A2xE0dD;
-		R = _abs(extA.x*A1dE2)+_abs(extA.y*A0dE2);
-		TESTV2(A2xE2dD,-A2dN,R); //AXIS_A2xE2
-
-		// intersection occurs
-		return true;
-	}
-	//---------------------------------------------------------------------------}
-
-	//----------------------------------------------------------------------------
-	IC float MgcSqrDistance (const Fvector& rkPoint, const Fvector& orig, const Fvector& e0,const Fvector& e1){
-
-		Fvector kDiff;
-		kDiff.sub(orig,rkPoint);
-
-		float fA00 = e0.square_magnitude();
-		float fA01 = e0.dotproduct(e1);
-		float fA11 = e1.square_magnitude();
-		float fB0 = kDiff.dotproduct(e0);
-		float fB1 = kDiff.dotproduct(e1);
-		float fC = kDiff.square_magnitude();
-		float fDet = _abs(fA00*fA11-fA01*fA01);
-		float fS = fA01*fB1-fA11*fB0;
-		float fT = fA01*fB0-fA00*fB1;
-		float fSqrDist;
-
-		if ( fS + fT <= fDet ){
-			if ( fS < 0.0f ){
-				if ( fT < 0.0f ){  // region 4
-					if ( fB0 < 0.0f ){
-						fT = 0.0f;
-						if ( -fB0 >= fA00 ){
-							fS = 1.0f;
-							fSqrDist = fA00+2.0f*fB0+fC;
-						}else{
-							fS = -fB0/fA00;
-							fSqrDist = fB0*fS+fC;
-						}
-					}else{
-						fS = 0.0f;
-						if ( fB1 >= 0.0f ){
-							fT = 0.0f;
-							fSqrDist = fC;
-						}else if ( -fB1 >= fA11 ){
-							fT = 1.0f;
-							fSqrDist = fA11+2.0f*fB1+fC;
-						}else{
-							fT = -fB1/fA11;
-							fSqrDist = fB1*fT+fC;
-						}
-					}
-				}else{  // region 3
-					fS = 0.0f;
-					if ( fB1 >= 0.0f ){
-						fT = 0.0f;
-						fSqrDist = fC;
-					}else if ( -fB1 >= fA11 ){
-						fT = 1;
-						fSqrDist = fA11+2.0f*fB1+fC;
-					}else{
-						fT = -fB1/fA11;
-						fSqrDist = fB1*fT+fC;
-					}
-				}
-			}else if ( fT < 0.0f ){  // region 5
-				fT = 0.0f;
-				if ( fB0 >= 0.0f ){
-					fS = 0.0f;
-					fSqrDist = fC;
-				}else if ( -fB0 >= fA00 ){
-					fS = 1.0;
-					fSqrDist = fA00+2.0f*fB0+fC;
-				}else{
-					fS = -fB0/fA00;
-					fSqrDist = fB0*fS+fC;
-				}
-			}else{  // region 0
-				// minimum at interior point
-				float fInvDet = 1.0f/fDet;
-				fS *= fInvDet;
-				fT *= fInvDet;
-				fSqrDist = fS*(fA00*fS+fA01*fT+2.0f*fB0) +
-					fT*(fA01*fS+fA11*fT+2.0f*fB1)+fC;
-			}
-		}else{
-			float fTmp0, fTmp1, fNumer, fDenom;
-
-			if ( fS < 0.0f ){  // region 2
-				fTmp0 = fA01 + fB0;
-				fTmp1 = fA11 + fB1;
-				if ( fTmp1 > fTmp0 ){
-					fNumer = fTmp1 - fTmp0;
-					fDenom = fA00-2.0f*fA01+fA11;
-					if ( fNumer >= fDenom ){
-						fS = 1.0f;
-						fT = 0.0f;
-						fSqrDist = fA00+2.0f*fB0+fC;
-					}else{
-						fS = fNumer/fDenom;
-						fT = 1.0f - fS;
-						fSqrDist = fS*(fA00*fS+fA01*fT+2.0f*fB0) +
-							fT*(fA01*fS+fA11*fT+2.0f*fB1)+fC;
-					}
-				}else{
-					fS = 0.0f;
-					if ( fTmp1 <= 0.0f ){
-						fT = 1.0f;
-						fSqrDist = fA11+2.0f*fB1+fC;
-					}else if ( fB1 >= 0.0f ){
-						fT = 0.0f;
-						fSqrDist = fC;
-					}else{
-						fT = -fB1/fA11;
-						fSqrDist = fB1*fT+fC;
-					}
-				}
-			}else if ( fT < 0.0 ){  // region 6
-				fTmp0 = fA01 + fB1;
-				fTmp1 = fA00 + fB0;
-				if ( fTmp1 > fTmp0 ){
-					fNumer = fTmp1 - fTmp0;
-					fDenom = fA00-2.0f*fA01+fA11;
-					if ( fNumer >= fDenom ){
-						fT = 1.0f;
-						fS = 0.0f;
-						fSqrDist = fA11+2.0f*fB1+fC;
-					}else{
-						fT = fNumer/fDenom;
-						fS = 1.0f - fT;
-						fSqrDist = fS*(fA00*fS+fA01*fT+2.0f*fB0) +
-							fT*(fA01*fS+fA11*fT+2.0f*fB1)+fC;
-					}
-				}else{
-					fT = 0.0f;
-					if ( fTmp1 <= 0.0f ){
-						fS = 1.0f;
-						fSqrDist = fA00+2.0f*fB0+fC;
-					}else if ( fB0 >= 0.0f ){
-						fS = 0.0f;
-						fSqrDist = fC;
-					}else{
-						fS = -fB0/fA00;
-						fSqrDist = fB0*fS+fC;
-					}
-				}
-			}else{  // region 1
-				fNumer = fA11 + fB1 - fA01 - fB0;
-				if ( fNumer <= 0.0f ){
-					fS = 0.0f;
-					fT = 1.0f;
-					fSqrDist = fA11+2.0f*fB1+fC;
-				}else{
-					fDenom = fA00-2.0f*fA01+fA11;
-					if ( fNumer >= fDenom ){
-						fS = 1.0f;
-						fT = 0.0f;
-						fSqrDist = fA00+2.0f*fB0+fC;
-					}else{
-						fS = fNumer/fDenom;
-						fT = 1.0f - fS;
-						fSqrDist = fS*(fA00*fS+fA01*fT+2.0f*fB0) +
-							fT*(fA01*fS+fA11*fT+2.0f*fB1)+fC;
-					}
-				}
-			}
-		}
-
-		return _abs(fSqrDist);
-	}
-
-	enum EST_Result{
-		stNone		= 0,
-		stIntersect	= 1,
-		stInside	= 2,
-	};
-
-	IC EST_Result TestSphereTri(const Fvector& sphereOrigin, float sphereRadius,
-						const Fvector& orig, const Fvector& e0,const Fvector& e1)
-	{
-
-		float fRSqr = sphereRadius*sphereRadius;
-		Fvector kV0mC;
-		kV0mC.sub(orig, sphereOrigin);
-
-		// count the number of triangle vertices inside the sphere
-		int iInside = 0;
-
-		// test if v0 is inside the sphere
-		if ( kV0mC.square_magnitude() <= fRSqr )
-			iInside++;
-
-		// test if v1 is inside the sphere
-		Fvector kDiff;
-		kDiff.add(kV0mC, e0);
-		if ( kDiff.square_magnitude() <= fRSqr )
-			iInside++;
-
-		// test if v2 is inside the sphere
-		kDiff.add(kV0mC, e1);
-		if ( kDiff.square_magnitude() <= fRSqr )
-			iInside++;
-
-		// triangle does not traversely intersect sphere
-		if ( iInside == 3 ) return stInside;
-
-		// triangle transversely intersects sphere
-		if ( iInside > 0 ) return stIntersect;
-
-		// All vertices are outside the sphere, but the triangle might still
-		// intersect the sphere.  This is the case when the distance from the
-		// sphere center to the triangle is smaller than the radius.
-		float fSqrDist = MgcSqrDistance(sphereOrigin,orig,e0,e1);
-		return (fSqrDist < fRSqr)?stIntersect:stNone;
-	}
-	//---------------------------------------------------------------------------
-	IC EST_Result TestSphereTri(const Fvector& sphereOrigin, float sphereRadius, Fvector* p)
-	{
-		Fvector e0, e1;
-		// find vectors for two edges sharing vert0
-		e0.sub(p[1], p[0]);
-		e1.sub(p[2], p[0]);
-		return TestSphereTri(sphereOrigin,sphereRadius,p[0],e0,e1);
-	}
-	IC EST_Result TestSphereTri(const Fvector& sphereOrigin, float sphereRadius, Fvector** p)
-	{
-		Fvector e0, e1;
-		// find vectors for two edges sharing vert0
-		e0.sub(*p[1], *p[0]);
-		e1.sub(*p[2], *p[0]);
-		return TestSphereTri(sphereOrigin,sphereRadius,*p[0],e0,e1);
-	}
-	IC bool TestSphereOBB(const Fsphere& rkSphere, const Fobb& rkBox)
-	{
-		// Test for intersection in the coordinate system of the box by
-		// transforming the sphere into that coordinate system.
-		Fvector3 kCDiff;
-		kCDiff.sub(rkSphere.P,rkBox.m_translate);
-
-		float fAx = _abs(kCDiff.dotproduct(rkBox.m_rotate.i));
-		float fAy = _abs(kCDiff.dotproduct(rkBox.m_rotate.j));
-		float fAz = _abs(kCDiff.dotproduct(rkBox.m_rotate.k));
-		float fDx = fAx - rkBox.m_halfsize[0];
-		float fDy = fAy - rkBox.m_halfsize[1];
-		float fDz = fAz - rkBox.m_halfsize[2];
-
-		if ( fAx <= rkBox.m_halfsize[0] ){
-			if ( fAy <= rkBox.m_halfsize[1] ){
-				if ( fAz <= rkBox.m_halfsize[2] ){
-					// sphere center inside box
-					return true;
-				}else{
-					// potential sphere-face intersection with face z
-					return fDz <= rkSphere.R;
-				}
-			}else{
-				if ( fAz <= rkBox.m_halfsize[2] ){
-					// potential sphere-face intersection with face y
-					return fDy <= rkSphere.R;
-				}else{
-					// potential sphere-edge intersection with edge formed
-					// by faces y and z
-					float fRSqr = rkSphere.R*rkSphere.R;
-					return fDy*fDy + fDz*fDz <= fRSqr;
-				}
-			}
-		}else{
-			if ( fAy <= rkBox.m_halfsize[1] ){
-				if ( fAz <= rkBox.m_halfsize[2] ){
-					// potential sphere-face intersection with face x
-					return fDx <= rkSphere.R;
-				}else{
-					// potential sphere-edge intersection with edge formed
-					// by faces x and z
-					float fRSqr = rkSphere.R*rkSphere.R;
-					return fDx*fDx + fDz*fDz <= fRSqr;
-				}
-			}else{
-				if ( fAz <= rkBox.m_halfsize[2] ){
-					// potential sphere-edge intersection with edge formed
-					// by faces x and y
-					float fRSqr = rkSphere.R*rkSphere.R;
-					return fDx*fDx + fDy*fDy <= fRSqr;
-				}else{
-					// potential sphere-vertex intersection at corner formed
-					// by faces x,y,z
-					float fRSqr = rkSphere.R*rkSphere.R;
-					return fDx*fDx + fDy*fDy + fDz*fDz <= fRSqr;
-				}
-			}
-		}
-	}
-	//----------------------------------------------------------------------------
-	IC bool TestRayOBB (const Fvector3& origin, const Fvector3& direction, const Fobb& rkBox)
-	{
-		float			fWdU[3], fAWdU[3], fDdU[3], fADdU[3], fAWxDdU[3], fRhs;
-
-		Fvector3		kDiff;
-		kDiff.sub		(origin,rkBox.m_translate);
-
-		fWdU[0]			= direction.dotproduct(rkBox.m_rotate.i);
-		fAWdU[0]		= _abs(fWdU[0]);
-		fDdU[0]			= kDiff.dotproduct(rkBox.m_rotate.i);
-		fADdU[0]		= _abs(fDdU[0]);
-		if ( fADdU[0] > rkBox.m_halfsize[0] && fDdU[0]*fWdU[0] >= (float)0.0 )
-			return false;
-
-		fWdU[1]			= direction.dotproduct(rkBox.m_rotate.j);
-		fAWdU[1]		= _abs(fWdU[1]);
-		fDdU[1]			= kDiff.dotproduct(rkBox.m_rotate.j);
-		fADdU[1]		= _abs(fDdU[1]);
-		if ( fADdU[1] > rkBox.m_halfsize[1] && fDdU[1]*fWdU[1] >= (float)0.0 )
-			return false;
-
-		fWdU[2]			= direction.dotproduct(rkBox.m_rotate.k);
-		fAWdU[2]		= _abs(fWdU[2]);
-		fDdU[2]			= kDiff.dotproduct(rkBox.m_rotate.k);
-		fADdU[2]		= _abs(fDdU[2]);
-		if ( fADdU[2] > rkBox.m_halfsize[2] && fDdU[2]*fWdU[2] >= (float)0.0 )
-			return false;
-
-		Fvector3		kWxD;
-		kWxD.crossproduct(direction,kDiff);
-
-		fAWxDdU[0]		= _abs(kWxD.dotproduct(rkBox.m_rotate.i));
-		fRhs = rkBox.m_halfsize[1]*fAWdU[2] + rkBox.m_halfsize[2]*fAWdU[1];
-		if ( fAWxDdU[0] > fRhs )
-			return false;
-
-		fAWxDdU[1]		= _abs(kWxD.dotproduct(rkBox.m_rotate.j));
-		fRhs = rkBox.m_halfsize[0]*fAWdU[2] + rkBox.m_halfsize[2]*fAWdU[0];
-		if ( fAWxDdU[1] > fRhs )
-			return false;
-
-		fAWxDdU[2]		= _abs(kWxD.dotproduct(rkBox.m_rotate.k));
-		fRhs = rkBox.m_halfsize[0]*fAWdU[1] + rkBox.m_halfsize[1]*fAWdU[0];
-		if ( fAWxDdU[2] > fRhs )
-			return false;
-
-		return true;
-	}
+ if ( (p) > (r) ){ \
+ if ( (d) >= 0.0f ){ return false; \
+  }else{ if ( (p)+(d) > (r) ) return false; } \
+  }else if ( (p) < -(r) ){ \
+ if ( (d) <= 0.0f ){ return false; \
+  }else{ if ( (p)+(d) < -(r) ) return false; } \
+  } \
+ }
+//---------------------------------------------------------------------------
+
+IC bool TestBBoxTri(const Fmatrix33& A, const Fvector& T, const Fvector& extA, Fvector** p, BOOL bCulling)
+{
+    // construct triangle normal, difference of center and vertex (18 ops)
+    Fvector D, E[2], N;
+    E[0].sub(*p[1], *p[0]);
+    E[1].sub(*p[2], *p[0]);
+    N.crossproduct(E[0], E[1]);
+
+    if (bCulling && (A.k.dotproduct(N) >= 0)) return false;
+
+    D.sub(*p[0], T);
+
+    // axis C+t*N
+    float A0dN = A.i.dotproduct(N);
+    float A1dN = A.j.dotproduct(N);
+    float A2dN = A.k.dotproduct(N);
+    float R = _abs(extA.x*A0dN) + _abs(extA.y*A1dN) + _abs(extA.z*A2dN);
+    float NdD = N.dotproduct(D);
+    TESTV0(NdD, R); //AXIS_N
+
+    // axis C+t*A0
+    float A0dD = A.i.dotproduct(D);
+    float A0dE0 = A.i.dotproduct(E[0]);
+    float A0dE1 = A.i.dotproduct(E[1]);
+    TESTV1(A0dD, A0dE0, A0dE1, extA.x); //AXIS_A0
+
+    // axis C+t*A1
+    float A1dD = A.j.dotproduct(D);
+    float A1dE0 = A.j.dotproduct(E[0]);
+    float A1dE1 = A.j.dotproduct(E[1]);
+    TESTV1(A1dD, A1dE0, A1dE1, extA.y); //AXIS_A1
+
+    // axis C+t*A2
+    float A2dD = A.k.dotproduct(D);
+    float A2dE0 = A.k.dotproduct(E[0]);
+    float A2dE1 = A.k.dotproduct(E[1]);
+    TESTV1(A2dD, A2dE0, A2dE1, extA.z); //AXIS_A2
+
+    // axis C+t*A0xE0
+    Fvector A0xE0;
+    A0xE0.crossproduct(A.i, E[0]);
+    float A0xE0dD = A0xE0.dotproduct(D);
+    R = _abs(extA.y*A2dE0) + _abs(extA.z*A1dE0);
+    TESTV2(A0xE0dD, A0dN, R); //AXIS_A0xE0
+
+    // axis C+t*A0xE1
+    Fvector A0xE1;
+    A0xE1.crossproduct(A.i, E[1]);
+    float A0xE1dD = A0xE1.dotproduct(D);
+    R = _abs(extA.y*A2dE1) + _abs(extA.z*A1dE1);
+    TESTV2(A0xE1dD, -A0dN, R); //AXIS_A0xE1
+
+    // axis C+t*A0xE2
+    float A1dE2 = A1dE1 - A1dE0;
+    float A2dE2 = A2dE1 - A2dE0;
+    float A0xE2dD = A0xE1dD - A0xE0dD;
+    R = _abs(extA.y*A2dE2) + _abs(extA.z*A1dE2);
+    TESTV2(A0xE2dD, -A0dN, R); //AXIS_A0xE2
+
+    // axis C+t*A1xE0
+    Fvector A1xE0;
+    A1xE0.crossproduct(A.j, E[0]);
+    float A1xE0dD = A1xE0.dotproduct(D);
+    R = _abs(extA.x*A2dE0) + _abs(extA.z*A0dE0);
+    TESTV2(A1xE0dD, A1dN, R); //AXIS_A1xE0
+
+    // axis C+t*A1xE1
+    Fvector A1xE1;
+    A1xE1.crossproduct(A.j, E[1]);
+    float A1xE1dD = A1xE1.dotproduct(D);
+    R = _abs(extA.x*A2dE1) + _abs(extA.z*A0dE1);
+    TESTV2(A1xE1dD, -A1dN, R); //AXIS_A1xE1
+
+    // axis C+t*A1xE2
+    float A0dE2 = A0dE1 - A0dE0;
+    float A1xE2dD = A1xE1dD - A1xE0dD;
+    R = _abs(extA.x*A2dE2) + _abs(extA.z*A0dE2);
+    TESTV2(A1xE2dD, -A1dN, R); //AXIS_A1xE2
+
+    // axis C+t*A2xE0
+    Fvector A2xE0;
+    A2xE0.crossproduct(A.k, E[0]);
+    float A2xE0dD = A2xE0.dotproduct(D);
+    R = _abs(extA.x*A1dE0) + _abs(extA.y*A0dE0);
+    TESTV2(A2xE0dD, A2dN, R); //AXIS_A2xE0
+
+    // axis C+t*A2xE1
+    Fvector A2xE1;
+    A2xE1.crossproduct(A.k, E[1]);
+    float A2xE1dD = A2xE1.dotproduct(D);
+    R = _abs(extA.x*A1dE1) + _abs(extA.y*A0dE1);
+    TESTV2(A2xE1dD, -A2dN, R); //AXIS_A2xE1
+
+    // axis C+t*A2xE2
+    float A2xE2dD = A2xE1dD - A2xE0dD;
+    R = _abs(extA.x*A1dE2) + _abs(extA.y*A0dE2);
+    TESTV2(A2xE2dD, -A2dN, R); //AXIS_A2xE2
+
+    // intersection occurs
+    return true;
+}
+IC bool TestBBoxTri(const Fmatrix33& A, const Fvector& T, const Fvector& extA, Fvector* p, BOOL bCulling)
+{
+    // construct triangle normal, difference of center and vertex (18 ops)
+    Fvector D, E[2], N;
+    E[0].sub(p[1], p[0]);
+    E[1].sub(p[2], p[0]);
+    N.crossproduct(E[0], E[1]);
+
+    if (bCulling && (A.k.dotproduct(N) >= 0)) return false;
+
+    D.sub(p[0], T);
+
+    // axis C+t*N
+    float A0dN = A.i.dotproduct(N);
+    float A1dN = A.j.dotproduct(N);
+    float A2dN = A.k.dotproduct(N);
+    float R = _abs(extA.x*A0dN) + _abs(extA.y*A1dN) + _abs(extA.z*A2dN);
+    float NdD = N.dotproduct(D);
+    TESTV0(NdD, R); //AXIS_N
+
+    // axis C+t*A0
+    float A0dD = A.i.dotproduct(D);
+    float A0dE0 = A.i.dotproduct(E[0]);
+    float A0dE1 = A.i.dotproduct(E[1]);
+    TESTV1(A0dD, A0dE0, A0dE1, extA.x); //AXIS_A0
+
+    // axis C+t*A1
+    float A1dD = A.j.dotproduct(D);
+    float A1dE0 = A.j.dotproduct(E[0]);
+    float A1dE1 = A.j.dotproduct(E[1]);
+    TESTV1(A1dD, A1dE0, A1dE1, extA.y); //AXIS_A1
+
+    // axis C+t*A2
+    float A2dD = A.k.dotproduct(D);
+    float A2dE0 = A.k.dotproduct(E[0]);
+    float A2dE1 = A.k.dotproduct(E[1]);
+    TESTV1(A2dD, A2dE0, A2dE1, extA.z); //AXIS_A2
+
+    // axis C+t*A0xE0
+    Fvector A0xE0;
+    A0xE0.crossproduct(A.i, E[0]);
+    float A0xE0dD = A0xE0.dotproduct(D);
+    R = _abs(extA.y*A2dE0) + _abs(extA.z*A1dE0);
+    TESTV2(A0xE0dD, A0dN, R); //AXIS_A0xE0
+
+    // axis C+t*A0xE1
+    Fvector A0xE1;
+    A0xE1.crossproduct(A.i, E[1]);
+    float A0xE1dD = A0xE1.dotproduct(D);
+    R = _abs(extA.y*A2dE1) + _abs(extA.z*A1dE1);
+    TESTV2(A0xE1dD, -A0dN, R); //AXIS_A0xE1
+
+    // axis C+t*A0xE2
+    float A1dE2 = A1dE1 - A1dE0;
+    float A2dE2 = A2dE1 - A2dE0;
+    float A0xE2dD = A0xE1dD - A0xE0dD;
+    R = _abs(extA.y*A2dE2) + _abs(extA.z*A1dE2);
+    TESTV2(A0xE2dD, -A0dN, R); //AXIS_A0xE2
+
+    // axis C+t*A1xE0
+    Fvector A1xE0;
+    A1xE0.crossproduct(A.j, E[0]);
+    float A1xE0dD = A1xE0.dotproduct(D);
+    R = _abs(extA.x*A2dE0) + _abs(extA.z*A0dE0);
+    TESTV2(A1xE0dD, A1dN, R); //AXIS_A1xE0
+
+    // axis C+t*A1xE1
+    Fvector A1xE1;
+    A1xE1.crossproduct(A.j, E[1]);
+    float A1xE1dD = A1xE1.dotproduct(D);
+    R = _abs(extA.x*A2dE1) + _abs(extA.z*A0dE1);
+    TESTV2(A1xE1dD, -A1dN, R); //AXIS_A1xE1
+
+    // axis C+t*A1xE2
+    float A0dE2 = A0dE1 - A0dE0;
+    float A1xE2dD = A1xE1dD - A1xE0dD;
+    R = _abs(extA.x*A2dE2) + _abs(extA.z*A0dE2);
+    TESTV2(A1xE2dD, -A1dN, R); //AXIS_A1xE2
+
+    // axis C+t*A2xE0
+    Fvector A2xE0;
+    A2xE0.crossproduct(A.k, E[0]);
+    float A2xE0dD = A2xE0.dotproduct(D);
+    R = _abs(extA.x*A1dE0) + _abs(extA.y*A0dE0);
+    TESTV2(A2xE0dD, A2dN, R); //AXIS_A2xE0
+
+    // axis C+t*A2xE1
+    Fvector A2xE1;
+    A2xE1.crossproduct(A.k, E[1]);
+    float A2xE1dD = A2xE1.dotproduct(D);
+    R = _abs(extA.x*A1dE1) + _abs(extA.y*A0dE1);
+    TESTV2(A2xE1dD, -A2dN, R); //AXIS_A2xE1
+
+    // axis C+t*A2xE2
+    float A2xE2dD = A2xE1dD - A2xE0dD;
+    R = _abs(extA.x*A1dE2) + _abs(extA.y*A0dE2);
+    TESTV2(A2xE2dD, -A2dN, R); //AXIS_A2xE2
+
+    // intersection occurs
+    return true;
+}
+//---------------------------------------------------------------------------}
+
+//----------------------------------------------------------------------------
+IC float MgcSqrDistance(const Fvector& rkPoint, const Fvector& orig, const Fvector& e0, const Fvector& e1)
+{
+
+    Fvector kDiff;
+    kDiff.sub(orig, rkPoint);
+
+    float fA00 = e0.square_magnitude();
+    float fA01 = e0.dotproduct(e1);
+    float fA11 = e1.square_magnitude();
+    float fB0 = kDiff.dotproduct(e0);
+    float fB1 = kDiff.dotproduct(e1);
+    float fC = kDiff.square_magnitude();
+    float fDet = _abs(fA00*fA11 - fA01*fA01);
+    float fS = fA01*fB1 - fA11*fB0;
+    float fT = fA01*fB0 - fA00*fB1;
+    float fSqrDist;
+
+    if (fS + fT <= fDet)
+    {
+        if (fS < 0.0f)
+        {
+            if (fT < 0.0f)
+            {
+                // region 4
+                if (fB0 < 0.0f)
+                {
+                    fT = 0.0f;
+                    if (-fB0 >= fA00)
+                    {
+                        fS = 1.0f;
+                        fSqrDist = fA00 + 2.0f*fB0 + fC;
+                    }
+                    else
+                    {
+                        fS = -fB0 / fA00;
+                        fSqrDist = fB0*fS + fC;
+                    }
+                }
+                else
+                {
+                    fS = 0.0f;
+                    if (fB1 >= 0.0f)
+                    {
+                        fT = 0.0f;
+                        fSqrDist = fC;
+                    }
+                    else if (-fB1 >= fA11)
+                    {
+                        fT = 1.0f;
+                        fSqrDist = fA11 + 2.0f*fB1 + fC;
+                    }
+                    else
+                    {
+                        fT = -fB1 / fA11;
+                        fSqrDist = fB1*fT + fC;
+                    }
+                }
+            }
+            else
+            {
+                // region 3
+                fS = 0.0f;
+                if (fB1 >= 0.0f)
+                {
+                    fT = 0.0f;
+                    fSqrDist = fC;
+                }
+                else if (-fB1 >= fA11)
+                {
+                    fT = 1;
+                    fSqrDist = fA11 + 2.0f*fB1 + fC;
+                }
+                else
+                {
+                    fT = -fB1 / fA11;
+                    fSqrDist = fB1*fT + fC;
+                }
+            }
+        }
+        else if (fT < 0.0f)
+        {
+            // region 5
+            fT = 0.0f;
+            if (fB0 >= 0.0f)
+            {
+                fS = 0.0f;
+                fSqrDist = fC;
+            }
+            else if (-fB0 >= fA00)
+            {
+                fS = 1.0;
+                fSqrDist = fA00 + 2.0f*fB0 + fC;
+            }
+            else
+            {
+                fS = -fB0 / fA00;
+                fSqrDist = fB0*fS + fC;
+            }
+        }
+        else
+        {
+            // region 0
+            // minimum at interior point
+            float fInvDet = 1.0f / fDet;
+            fS *= fInvDet;
+            fT *= fInvDet;
+            fSqrDist = fS*(fA00*fS + fA01*fT + 2.0f*fB0) +
+                       fT*(fA01*fS + fA11*fT + 2.0f*fB1) + fC;
+        }
+    }
+    else
+    {
+        float fTmp0, fTmp1, fNumer, fDenom;
+
+        if (fS < 0.0f)
+        {
+            // region 2
+            fTmp0 = fA01 + fB0;
+            fTmp1 = fA11 + fB1;
+            if (fTmp1 > fTmp0)
+            {
+                fNumer = fTmp1 - fTmp0;
+                fDenom = fA00 - 2.0f*fA01 + fA11;
+                if (fNumer >= fDenom)
+                {
+                    fS = 1.0f;
+                    fT = 0.0f;
+                    fSqrDist = fA00 + 2.0f*fB0 + fC;
+                }
+                else
+                {
+                    fS = fNumer / fDenom;
+                    fT = 1.0f - fS;
+                    fSqrDist = fS*(fA00*fS + fA01*fT + 2.0f*fB0) +
+                               fT*(fA01*fS + fA11*fT + 2.0f*fB1) + fC;
+                }
+            }
+            else
+            {
+                fS = 0.0f;
+                if (fTmp1 <= 0.0f)
+                {
+                    fT = 1.0f;
+                    fSqrDist = fA11 + 2.0f*fB1 + fC;
+                }
+                else if (fB1 >= 0.0f)
+                {
+                    fT = 0.0f;
+                    fSqrDist = fC;
+                }
+                else
+                {
+                    fT = -fB1 / fA11;
+                    fSqrDist = fB1*fT + fC;
+                }
+            }
+        }
+        else if (fT < 0.0)
+        {
+            // region 6
+            fTmp0 = fA01 + fB1;
+            fTmp1 = fA00 + fB0;
+            if (fTmp1 > fTmp0)
+            {
+                fNumer = fTmp1 - fTmp0;
+                fDenom = fA00 - 2.0f*fA01 + fA11;
+                if (fNumer >= fDenom)
+                {
+                    fT = 1.0f;
+                    fS = 0.0f;
+                    fSqrDist = fA11 + 2.0f*fB1 + fC;
+                }
+                else
+                {
+                    fT = fNumer / fDenom;
+                    fS = 1.0f - fT;
+                    fSqrDist = fS*(fA00*fS + fA01*fT + 2.0f*fB0) +
+                               fT*(fA01*fS + fA11*fT + 2.0f*fB1) + fC;
+                }
+            }
+            else
+            {
+                fT = 0.0f;
+                if (fTmp1 <= 0.0f)
+                {
+                    fS = 1.0f;
+                    fSqrDist = fA00 + 2.0f*fB0 + fC;
+                }
+                else if (fB0 >= 0.0f)
+                {
+                    fS = 0.0f;
+                    fSqrDist = fC;
+                }
+                else
+                {
+                    fS = -fB0 / fA00;
+                    fSqrDist = fB0*fS + fC;
+                }
+            }
+        }
+        else
+        {
+            // region 1
+            fNumer = fA11 + fB1 - fA01 - fB0;
+            if (fNumer <= 0.0f)
+            {
+                fS = 0.0f;
+                fT = 1.0f;
+                fSqrDist = fA11 + 2.0f*fB1 + fC;
+            }
+            else
+            {
+                fDenom = fA00 - 2.0f*fA01 + fA11;
+                if (fNumer >= fDenom)
+                {
+                    fS = 1.0f;
+                    fT = 0.0f;
+                    fSqrDist = fA00 + 2.0f*fB0 + fC;
+                }
+                else
+                {
+                    fS = fNumer / fDenom;
+                    fT = 1.0f - fS;
+                    fSqrDist = fS*(fA00*fS + fA01*fT + 2.0f*fB0) +
+                               fT*(fA01*fS + fA11*fT + 2.0f*fB1) + fC;
+                }
+            }
+        }
+    }
+
+    return _abs(fSqrDist);
+}
+
+enum EST_Result
+{
+    stNone = 0,
+    stIntersect = 1,
+    stInside = 2,
+};
+
+IC EST_Result TestSphereTri(const Fvector& sphereOrigin, float sphereRadius,
+                            const Fvector& orig, const Fvector& e0, const Fvector& e1)
+{
+
+    float fRSqr = sphereRadius*sphereRadius;
+    Fvector kV0mC;
+    kV0mC.sub(orig, sphereOrigin);
+
+    // count the number of triangle vertices inside the sphere
+    int iInside = 0;
+
+    // test if v0 is inside the sphere
+    if (kV0mC.square_magnitude() <= fRSqr)
+        iInside++;
+
+    // test if v1 is inside the sphere
+    Fvector kDiff;
+    kDiff.add(kV0mC, e0);
+    if (kDiff.square_magnitude() <= fRSqr)
+        iInside++;
+
+    // test if v2 is inside the sphere
+    kDiff.add(kV0mC, e1);
+    if (kDiff.square_magnitude() <= fRSqr)
+        iInside++;
+
+    // triangle does not traversely intersect sphere
+    if (iInside == 3) return stInside;
+
+    // triangle transversely intersects sphere
+    if (iInside > 0) return stIntersect;
+
+    // All vertices are outside the sphere, but the triangle might still
+    // intersect the sphere. This is the case when the distance from the
+    // sphere center to the triangle is smaller than the radius.
+    float fSqrDist = MgcSqrDistance(sphereOrigin, orig, e0, e1);
+    return (fSqrDist < fRSqr) ? stIntersect : stNone;
+}
+//---------------------------------------------------------------------------
+IC EST_Result TestSphereTri(const Fvector& sphereOrigin, float sphereRadius, Fvector* p)
+{
+    Fvector e0, e1;
+    // find vectors for two edges sharing vert0
+    e0.sub(p[1], p[0]);
+    e1.sub(p[2], p[0]);
+    return TestSphereTri(sphereOrigin, sphereRadius, p[0], e0, e1);
+}
+IC EST_Result TestSphereTri(const Fvector& sphereOrigin, float sphereRadius, Fvector** p)
+{
+    Fvector e0, e1;
+    // find vectors for two edges sharing vert0
+    e0.sub(*p[1], *p[0]);
+    e1.sub(*p[2], *p[0]);
+    return TestSphereTri(sphereOrigin, sphereRadius, *p[0], e0, e1);
+}
+IC bool TestSphereOBB(const Fsphere& rkSphere, const Fobb& rkBox)
+{
+    // Test for intersection in the coordinate system of the box by
+    // transforming the sphere into that coordinate system.
+    Fvector3 kCDiff;
+    kCDiff.sub(rkSphere.P, rkBox.m_translate);
+
+    float fAx = _abs(kCDiff.dotproduct(rkBox.m_rotate.i));
+    float fAy = _abs(kCDiff.dotproduct(rkBox.m_rotate.j));
+    float fAz = _abs(kCDiff.dotproduct(rkBox.m_rotate.k));
+    float fDx = fAx - rkBox.m_halfsize[0];
+    float fDy = fAy - rkBox.m_halfsize[1];
+    float fDz = fAz - rkBox.m_halfsize[2];
+
+    if (fAx <= rkBox.m_halfsize[0])
+    {
+        if (fAy <= rkBox.m_halfsize[1])
+        {
+            if (fAz <= rkBox.m_halfsize[2])
+            {
+                // sphere center inside box
+                return true;
+            }
+            else
+            {
+                // potential sphere-face intersection with face z
+                return fDz <= rkSphere.R;
+            }
+        }
+        else
+        {
+            if (fAz <= rkBox.m_halfsize[2])
+            {
+                // potential sphere-face intersection with face y
+                return fDy <= rkSphere.R;
+            }
+            else
+            {
+                // potential sphere-edge intersection with edge formed
+                // by faces y and z
+                float fRSqr = rkSphere.R*rkSphere.R;
+                return fDy*fDy + fDz*fDz <= fRSqr;
+            }
+        }
+    }
+    else
+    {
+        if (fAy <= rkBox.m_halfsize[1])
+        {
+            if (fAz <= rkBox.m_halfsize[2])
+            {
+                // potential sphere-face intersection with face x
+                return fDx <= rkSphere.R;
+            }
+            else
+            {
+                // potential sphere-edge intersection with edge formed
+                // by faces x and z
+                float fRSqr = rkSphere.R*rkSphere.R;
+                return fDx*fDx + fDz*fDz <= fRSqr;
+            }
+        }
+        else
+        {
+            if (fAz <= rkBox.m_halfsize[2])
+            {
+                // potential sphere-edge intersection with edge formed
+                // by faces x and y
+                float fRSqr = rkSphere.R*rkSphere.R;
+                return fDx*fDx + fDy*fDy <= fRSqr;
+            }
+            else
+            {
+                // potential sphere-vertex intersection at corner formed
+                // by faces x,y,z
+                float fRSqr = rkSphere.R*rkSphere.R;
+                return fDx*fDx + fDy*fDy + fDz*fDz <= fRSqr;
+            }
+        }
+    }
+}
+//----------------------------------------------------------------------------
+IC bool TestRayOBB(const Fvector3& origin, const Fvector3& direction, const Fobb& rkBox)
+{
+    float fWdU[3], fAWdU[3], fDdU[3], fADdU[3], fAWxDdU[3], fRhs;
+
+    Fvector3 kDiff;
+    kDiff.sub(origin, rkBox.m_translate);
+
+    fWdU[0] = direction.dotproduct(rkBox.m_rotate.i);
+    fAWdU[0] = _abs(fWdU[0]);
+    fDdU[0] = kDiff.dotproduct(rkBox.m_rotate.i);
+    fADdU[0] = _abs(fDdU[0]);
+    if (fADdU[0] > rkBox.m_halfsize[0] && fDdU[0] * fWdU[0] >= (float)0.0)
+        return false;
+
+    fWdU[1] = direction.dotproduct(rkBox.m_rotate.j);
+    fAWdU[1] = _abs(fWdU[1]);
+    fDdU[1] = kDiff.dotproduct(rkBox.m_rotate.j);
+    fADdU[1] = _abs(fDdU[1]);
+    if (fADdU[1] > rkBox.m_halfsize[1] && fDdU[1] * fWdU[1] >= (float)0.0)
+        return false;
+
+    fWdU[2] = direction.dotproduct(rkBox.m_rotate.k);
+    fAWdU[2] = _abs(fWdU[2]);
+    fDdU[2] = kDiff.dotproduct(rkBox.m_rotate.k);
+    fADdU[2] = _abs(fDdU[2]);
+    if (fADdU[2] > rkBox.m_halfsize[2] && fDdU[2] * fWdU[2] >= (float)0.0)
+        return false;
+
+    Fvector3 kWxD;
+    kWxD.crossproduct(direction, kDiff);
+
+    fAWxDdU[0] = _abs(kWxD.dotproduct(rkBox.m_rotate.i));
+    fRhs = rkBox.m_halfsize[1] * fAWdU[2] + rkBox.m_halfsize[2] * fAWdU[1];
+    if (fAWxDdU[0] > fRhs)
+        return false;
+
+    fAWxDdU[1] = _abs(kWxD.dotproduct(rkBox.m_rotate.j));
+    fRhs = rkBox.m_halfsize[0] * fAWdU[2] + rkBox.m_halfsize[2] * fAWdU[0];
+    if (fAWxDdU[1] > fRhs)
+        return false;
+
+    fAWxDdU[2] = _abs(kWxD.dotproduct(rkBox.m_rotate.k));
+    fRhs = rkBox.m_halfsize[0] * fAWdU[1] + rkBox.m_halfsize[1] * fAWdU[0];
+    if (fAWxDdU[2] > fRhs)
+        return false;
+
+    return true;
+}
 //----------------------------------------------------------------------------
 };
 
diff --git a/src/xrEngine/dedicated_server_only.h b/src/xrEngine/dedicated_server_only.h
index 2178d72d93c..d642ad7feaa 100644
--- a/src/xrEngine/dedicated_server_only.h
+++ b/src/xrEngine/dedicated_server_only.h
@@ -4,14 +4,14 @@
 //#define DEDICATED_SERVER_ONLY
 
 #ifdef DEDICATED_SERVER_ONLY
-#	define PROTECT_API
+# define PROTECT_API
 #else// #ifdef DEDICATED_SERVER_ONLY
-#	define PROTECT_API	__declspec(dllexport)
+# define PROTECT_API __declspec(dllexport)
 #endif // #ifdef DEDICATED_SERVER_ONLY
 
-#ifdef	BENCHMARK_BUILD
-#	undef PROTECT_API
-#	define PROTECT_API
-#endif	//	#ifdef	BENCHMARK_BUILD
+#ifdef BENCHMARK_BUILD
+# undef PROTECT_API
+# define PROTECT_API
+#endif // #ifdef BENCHMARK_BUILD
 
 #endif // #ifndef DEDICATED_SERVER_ONLY_H_INCLUDED
\ No newline at end of file
diff --git a/src/xrEngine/defines.cpp b/src/xrEngine/defines.cpp
index 7e48c575de8..343e057e85e 100644
--- a/src/xrEngine/defines.cpp
+++ b/src/xrEngine/defines.cpp
@@ -1,16 +1,16 @@
 #include "stdafx.h"
 
 #ifdef DEBUG
-	ECORE_API BOOL bDebug	= FALSE;
-	
+ECORE_API BOOL bDebug = FALSE;
+
 #endif
 
 // Video
-//. u32			psCurrentMode		= 1024;
-u32			psCurrentVidMode[2] = {1024,768};
-u32			psCurrentBPP		= 32;
+//. u32 psCurrentMode = 1024;
+u32 psCurrentVidMode[2] = {1024, 768};
+u32 psCurrentBPP = 32;
 // release version always has "mt_*" enabled
-Flags32		psDeviceFlags		= {rsFullscreen|rsDetails|mtPhysics|mtSound|mtNetwork|rsDrawStatic|rsDrawDynamic|rsRefresh60hz};
+Flags32 psDeviceFlags = {rsFullscreen | rsDetails | mtPhysics | mtSound | mtNetwork | rsDrawStatic | rsDrawDynamic | rsRefresh60hz};
 
-// textures 
-int			psTextureLOD		= 1;
+// textures
+int psTextureLOD = 1;
diff --git a/src/xrEngine/defines.h b/src/xrEngine/defines.h
index 9840b209ac5..640524b1ed9 100644
--- a/src/xrEngine/defines.h
+++ b/src/xrEngine/defines.h
@@ -1,76 +1,77 @@
 #ifndef DefinesH
 #define DefinesH
 
-#ifdef	DEBUG
-	ENGINE_API	extern BOOL			bDebug;
+#ifdef DEBUG
+ENGINE_API extern BOOL bDebug;
 #else
-	#define bDebug 0
+#define bDebug 0
 #endif
 
-#define _RELEASE(x)			{ if(x) { (x)->Release();       (x)=NULL; } }
-#define _SHOW_REF(msg, x)   { if(x) { x->AddRef(); Log(msg,u32(x->Release()));}}
+#define _RELEASE(x) { if(x) { (x)->Release(); (x)=NULL; } }
+#define _SHOW_REF(msg, x) { if(x) { x->AddRef(); Log(msg,u32(x->Release()));}}
 
 // textures
-ENGINE_API extern	int		psTextureLOD		;
+ENGINE_API extern int psTextureLOD;
 
 // psDeviceFlags
-enum {
-	rsFullscreen					= (1ul<<0ul),
-	rsClearBB						= (1ul<<1ul),
-	rsVSync							= (1ul<<2ul),
-	rsWireframe						= (1ul<<3ul),
-	rsOcclusion						= (1ul<<4ul),
-	rsStatistic						= (1ul<<5ul),
-	rsDetails						= (1ul<<6ul),
-	rsRefresh60hz					= (1ul<<7ul),
-	rsConstantFPS					= (1ul<<8ul),
-	rsDrawStatic					= (1ul<<9ul),
-	rsDrawDynamic					= (1ul<<10ul),
-	rsDisableObjectsAsCrows			= (1ul<<11ul),
+enum
+{
+    rsFullscreen = (1ul << 0ul),
+    rsClearBB = (1ul << 1ul),
+    rsVSync = (1ul << 2ul),
+    rsWireframe = (1ul << 3ul),
+    rsOcclusion = (1ul << 4ul),
+    rsStatistic = (1ul << 5ul),
+    rsDetails = (1ul << 6ul),
+    rsRefresh60hz = (1ul << 7ul),
+    rsConstantFPS = (1ul << 8ul),
+    rsDrawStatic = (1ul << 9ul),
+    rsDrawDynamic = (1ul << 10ul),
+    rsDisableObjectsAsCrows = (1ul << 11ul),
 
-	rsOcclusionDraw					= (1ul<<12ul),
-	rsOcclusionStats				= (1ul<<13ul),
+    rsOcclusionDraw = (1ul << 12ul),
+    rsOcclusionStats = (1ul << 13ul),
 
-	mtSound							= (1ul<<14ul),
-	mtPhysics						= (1ul<<15ul),
-	mtNetwork						= (1ul<<16ul),
-	mtParticles						= (1ul<<17ul),
+    mtSound = (1ul << 14ul),
+    mtPhysics = (1ul << 15ul),
+    mtNetwork = (1ul << 16ul),
+    mtParticles = (1ul << 17ul),
 
-	rsCameraPos						= (1ul<<18ul),
-	rsR2							= (1ul<<19ul),
-	rsR3							= (1ul<<20ul),
-	rsR4							= (1ul<<21ul),
-	// 22-32 bit - reserved to Editor
+    rsCameraPos = (1ul << 18ul),
+    rsR2 = (1ul << 19ul),
+    rsR3 = (1ul << 20ul),
+    rsR4 = (1ul << 21ul),
+    // 22-32 bit - reserved to Editor
 };
 
 
-//. ENGINE_API extern	u32			psCurrentMode		;
-ENGINE_API extern	u32			psCurrentVidMode[];
-ENGINE_API extern	u32			psCurrentBPP		;
-ENGINE_API extern	Flags32		psDeviceFlags		;
+//. ENGINE_API extern u32 psCurrentMode ;
+ENGINE_API extern u32 psCurrentVidMode[];
+ENGINE_API extern u32 psCurrentBPP;
+ENGINE_API extern Flags32 psDeviceFlags;
 
 // game path definition
-#define _game_data_				"$game_data$"
-#define _game_textures_			"$game_textures$"
-#define _game_levels_			"$game_levels$"
-#define _game_sounds_			"$game_sounds$"
-#define _game_meshes_			"$game_meshes$"
-#define _game_shaders_			"$game_shaders$"
-#define _game_config_			"$game_congif$"
+#define _game_data_ "$game_data$"
+#define _game_textures_ "$game_textures$"
+#define _game_levels_ "$game_levels$"
+#define _game_sounds_ "$game_sounds$"
+#define _game_meshes_ "$game_meshes$"
+#define _game_shaders_ "$game_shaders$"
+#define _game_config_ "$game_congif$"
 
 // editor path definition
-#define _server_root_		    "$server_root$"
-#define _server_data_root_	    "$server_data_root$"
-#define _local_root_		    "$local_root$"
-#define _import_			    "$import$"
-#define _sounds_			    "$sounds$"
-#define _textures_			    "$textures$"
-#define _objects_			    "$objects$"
-#define _maps_				    "$maps$"
-#define _temp_				    "$temp$"
-#define _omotion_			    "$omotion$"
-#define _omotions_			    "$omotions$"
-#define _smotion_			    "$smotion$"
-#define _detail_objects_	    "$detail_objects$"
+#define _server_root_ "$server_root$"
+#define _server_data_root_ "$server_data_root$"
+#define _local_root_ "$local_root$"
+#define _import_ "$import$"
+#define _sounds_ "$sounds$"
+#define _textures_ "$textures$"
+#define _objects_ "$objects$"
+#define _maps_ "$maps$"
+#define _temp_ "$temp$"
+#define _omotion_ "$omotion$"
+#define _omotions_ "$omotions$"
+#define _smotion_ "$smotion$"
+#define _detail_objects_ "$detail_objects$"
 
 #endif
diff --git a/src/xrEngine/device.cpp b/src/xrEngine/device.cpp
index d8931fc166b..1b42b678a03 100644
--- a/src/xrEngine/device.cpp
+++ b/src/xrEngine/device.cpp
@@ -21,475 +21,492 @@
 #include "../xrCore/FS_impl.h"
 
 #ifdef INGAME_EDITOR
-#	include "../include/editor/ide.hpp"
-#	include "engine_impl.hpp"
+# include "../include/editor/ide.hpp"
+# include "engine_impl.hpp"
 #endif // #ifdef INGAME_EDITOR
 
 #include "xrSash.h"
 #include "igame_persistent.h"
 
-#pragma comment( lib, "d3dx9.lib"		)
+#pragma comment( lib, "d3dx9.lib" )
 
 ENGINE_API CRenderDevice Device;
 ENGINE_API CLoadScreenRenderer load_screen_renderer;
 
 
-ENGINE_API BOOL g_bRendering = FALSE; 
+ENGINE_API BOOL g_bRendering = FALSE;
 
-BOOL		g_bLoaded = FALSE;
-ref_light	precache_light = 0;
+BOOL g_bLoaded = FALSE;
+ref_light precache_light = 0;
 
-BOOL CRenderDevice::Begin	()
+BOOL CRenderDevice::Begin()
 {
 #ifndef DEDICATED_SERVER
 
-	/*
-	HW.Validate		();
-	HRESULT	_hr		= HW.pDevice->TestCooperativeLevel();
+    /*
+    HW.Validate ();
+    HRESULT _hr = HW.pDevice->TestCooperativeLevel();
     if (FAILED(_hr))
-	{
-		// If the device was lost, do not render until we get it back
-		if		(D3DERR_DEVICELOST==_hr)		{
-			Sleep	(33);
-			return	FALSE;
-		}
-
-		// Check if the device is ready to be reset
-		if		(D3DERR_DEVICENOTRESET==_hr)
-		{
-			Reset	();
-		}
-	}
-	*/
-
-	switch (m_pRender->GetDeviceState())
-	{
-	case IRenderDeviceRender::dsOK:
-		break;
-
-	case IRenderDeviceRender::dsLost:
-		// If the device was lost, do not render until we get it back
-		Sleep(33);
-		return FALSE;
-		break;
-
-	case IRenderDeviceRender::dsNeedReset:
-		// Check if the device is ready to be reset
-		Reset();
-		break;
-
-	default:
-		R_ASSERT(0);
-	}
-
-	m_pRender->Begin();
-
-	/*
-	CHK_DX					(HW.pDevice->BeginScene());
-	RCache.OnFrameBegin		();
-	RCache.set_CullMode		(CULL_CW);
-	RCache.set_CullMode		(CULL_CCW);
-	if (HW.Caps.SceneMode)	overdrawBegin	();
-	*/
-
-	FPU::m24r	();
-	g_bRendering = 	TRUE;
+    {
+    // If the device was lost, do not render until we get it back
+    if (D3DERR_DEVICELOST==_hr) {
+    Sleep (33);
+    return FALSE;
+    }
+
+    // Check if the device is ready to be reset
+    if (D3DERR_DEVICENOTRESET==_hr)
+    {
+    Reset ();
+    }
+    }
+    */
+
+    switch (m_pRender->GetDeviceState())
+    {
+    case IRenderDeviceRender::dsOK:
+        break;
+
+    case IRenderDeviceRender::dsLost:
+        // If the device was lost, do not render until we get it back
+        Sleep(33);
+        return FALSE;
+        break;
+
+    case IRenderDeviceRender::dsNeedReset:
+        // Check if the device is ready to be reset
+        Reset();
+        break;
+
+    default:
+        R_ASSERT(0);
+    }
+
+    m_pRender->Begin();
+
+    /*
+    CHK_DX (HW.pDevice->BeginScene());
+    RCache.OnFrameBegin ();
+    RCache.set_CullMode (CULL_CW);
+    RCache.set_CullMode (CULL_CCW);
+    if (HW.Caps.SceneMode) overdrawBegin ();
+    */
+
+    FPU::m24r();
+    g_bRendering = TRUE;
 #endif
-	return		TRUE;
+    return TRUE;
 }
 
-void CRenderDevice::Clear	()
+void CRenderDevice::Clear()
 {
-	m_pRender->Clear();
+    m_pRender->Clear();
 }
 
 extern void CheckPrivilegySlowdown();
 
 
-void CRenderDevice::End		(void)
+void CRenderDevice::End(void)
 {
 #ifndef DEDICATED_SERVER
 
 
 #ifdef INGAME_EDITOR
-	bool							load_finished = false;
+    bool load_finished = false;
 #endif // #ifdef INGAME_EDITOR
-	if (dwPrecacheFrame)
-	{
-		::Sound->set_master_volume	(0.f);
-		dwPrecacheFrame	--;
-//.		pApp->load_draw_internal	();
-		if (0==dwPrecacheFrame)
-		{
+    if (dwPrecacheFrame)
+    {
+        ::Sound->set_master_volume(0.f);
+        dwPrecacheFrame--;
+        //. pApp->load_draw_internal ();
+        if (0 == dwPrecacheFrame)
+        {
 
 #ifdef INGAME_EDITOR
-			load_finished			= true;
+            load_finished = true;
 #endif // #ifdef INGAME_EDITOR
-			//Gamma.Update		();
-			m_pRender->updateGamma();
+            //Gamma.Update ();
+            m_pRender->updateGamma();
 
-			if(precache_light) precache_light->set_active	(false);
-			if(precache_light) precache_light.destroy		();
-			::Sound->set_master_volume						(1.f);
-//			pApp->destroy_loading_shaders					();
+            if (precache_light) precache_light->set_active(false);
+            if (precache_light) precache_light.destroy();
+            ::Sound->set_master_volume(1.f);
+            // pApp->destroy_loading_shaders ();
 
-			m_pRender->ResourcesDestroyNecessaryTextures	();
-			Memory.mem_compact								();
-			Msg												("* MEMORY USAGE: %d K",Memory.mem_usage()/1024);
-			Msg												("* End of synchronization A[%d] R[%d]",b_is_Active, b_is_Ready);
+            m_pRender->ResourcesDestroyNecessaryTextures();
+            Memory.mem_compact();
+            Msg("* MEMORY USAGE: %d K", Memory.mem_usage() / 1024);
+            Msg("* End of synchronization A[%d] R[%d]", b_is_Active, b_is_Ready);
 
 #ifdef FIND_CHUNK_BENCHMARK_ENABLE
-			g_find_chunk_counter.flush();
+            g_find_chunk_counter.flush();
 #endif // FIND_CHUNK_BENCHMARK_ENABLE
 
-			CheckPrivilegySlowdown							();
-			
-			if(g_pGamePersistent->GameType()==1)//haCk
-			{
-				WINDOWINFO	wi;
-				GetWindowInfo(m_hWnd,&wi);
-				if(wi.dwWindowStatus!=WS_ACTIVECAPTION)
-					Pause(TRUE,TRUE,TRUE,"application start");
-			}
-		}
-	}
-
-	g_bRendering		= FALSE;
-	// end scene
-	//	Present goes here, so call OA Frame end.
-	if (g_SASH.IsBenchmarkRunning())
-		g_SASH.DisplayFrame(Device.fTimeGlobal);
-	m_pRender->End();
-	//RCache.OnFrameEnd	();
-	//Memory.dbg_check		();
-    //CHK_DX				(HW.pDevice->EndScene());
-
-	//HRESULT _hr		= HW.pDevice->Present( NULL, NULL, NULL, NULL );
-	//if				(D3DERR_DEVICELOST==_hr)	return;			// we will handle this later
-	//R_ASSERT2		(SUCCEEDED(_hr),	"Presentation failed. Driver upgrade needed?");
-#	ifdef INGAME_EDITOR
-		if (load_finished && m_editor)
-			m_editor->on_load_finished	();
-#	endif // #ifdef INGAME_EDITOR
+            CheckPrivilegySlowdown();
+
+            if (g_pGamePersistent->GameType() == 1)//haCk
+            {
+                WINDOWINFO wi;
+                GetWindowInfo(m_hWnd, &wi);
+                if (wi.dwWindowStatus != WS_ACTIVECAPTION)
+                    Pause(TRUE, TRUE, TRUE, "application start");
+            }
+        }
+    }
+
+    g_bRendering = FALSE;
+    // end scene
+    // Present goes here, so call OA Frame end.
+    if (g_SASH.IsBenchmarkRunning())
+        g_SASH.DisplayFrame(Device.fTimeGlobal);
+    m_pRender->End();
+    //RCache.OnFrameEnd ();
+    //Memory.dbg_check ();
+    //CHK_DX (HW.pDevice->EndScene());
+
+    //HRESULT _hr = HW.pDevice->Present( NULL, NULL, NULL, NULL );
+    //if (D3DERR_DEVICELOST==_hr) return; // we will handle this later
+    //R_ASSERT2 (SUCCEEDED(_hr), "Presentation failed. Driver upgrade needed?");
+# ifdef INGAME_EDITOR
+    if (load_finished && m_editor)
+        m_editor->on_load_finished();
+# endif // #ifdef INGAME_EDITOR
 #endif
 }
 
 
-volatile u32	mt_Thread_marker		= 0x12345678;
-void 			mt_Thread	(void *ptr)	{
-	while (true) {
-		// waiting for Device permission to execute
-		Device.mt_csEnter.Enter	();
-
-		if (Device.mt_bMustExit) {
-			Device.mt_bMustExit = FALSE;				// Important!!!
-			Device.mt_csEnter.Leave();					// Important!!!
-			return;
-		}
-		// we has granted permission to execute
-		mt_Thread_marker			= Device.dwFrame;
- 
-		for (u32 pit=0; pitGetForceGPU_REF()) amount=0;
+    if (m_pRender->GetForceGPU_REF()) amount = 0;
 #ifdef DEDICATED_SERVER
-	amount = 0;
+    amount = 0;
 #endif
-	// Msg			("* PCACHE: start for %d...",amount);
-	dwPrecacheFrame	= dwPrecacheTotal = amount;
-	if (amount && !precache_light && g_pGameLevel && g_loading_events.empty()) {
-		precache_light					= ::Render->light_create();
-		precache_light->set_shadow		(false);
-		precache_light->set_position	(vCameraPosition);
-		precache_light->set_color		(255,255,255);
-		precache_light->set_range		(5.0f);
-		precache_light->set_active		(true);
-	}
-
-	if(amount && b_draw_loadscreen && load_screen_renderer.b_registered==false)
-	{
-		load_screen_renderer.start	(b_wait_user_input);
-	}
+    // Msg ("* PCACHE: start for %d...",amount);
+    dwPrecacheFrame = dwPrecacheTotal = amount;
+    if (amount && !precache_light && g_pGameLevel && g_loading_events.empty())
+    {
+        precache_light = ::Render->light_create();
+        precache_light->set_shadow(false);
+        precache_light->set_position(vCameraPosition);
+        precache_light->set_color(255, 255, 255);
+        precache_light->set_range(5.0f);
+        precache_light->set_active(true);
+    }
+
+    if (amount && b_draw_loadscreen && load_screen_renderer.b_registered == false)
+    {
+        load_screen_renderer.start(b_wait_user_input);
+    }
 }
 
 
 int g_svDedicateServerUpdateReate = 100;
 
-ENGINE_API xr_list			g_loading_events;
+ENGINE_API xr_list g_loading_events;
 
-void CRenderDevice::on_idle		()
+void CRenderDevice::on_idle()
 {
-	if (!b_is_Ready) {
-		Sleep	(100);
-		return;
-	}
+    if (!b_is_Ready)
+    {
+        Sleep(100);
+        return;
+    }
 
 #ifdef DEDICATED_SERVER
-	u32 FrameStartTime = TimerGlobal.GetElapsed_ms();
+    u32 FrameStartTime = TimerGlobal.GetElapsed_ms();
 #endif
-	if (psDeviceFlags.test(rsStatistic))	g_bEnableStatGather	= TRUE;
-	else									g_bEnableStatGather	= FALSE;
-	if(g_loading_events.size())
-	{
-		if( g_loading_events.front()() )
-			g_loading_events.pop_front();
-		pApp->LoadDraw				();
-		return;
-	}else 
-	{
-		if ( (!Device.dwPrecacheFrame) && (!g_SASH.IsBenchmarkRunning())
-			&& g_bLoaded)
-			g_SASH.StartBenchmark();
-
-		FrameMove						( );
-	}
-
-	// Precache
-	if (dwPrecacheFrame)
-	{
-		float factor					= float(dwPrecacheFrame)/float(dwPrecacheTotal);
-		float angle						= PI_MUL_2 * factor;
-		vCameraDirection.set			(_sin(angle),0,_cos(angle));	vCameraDirection.normalize	();
-		vCameraTop.set					(0,1,0);
-		vCameraRight.crossproduct		(vCameraTop,vCameraDirection);
-
-		mView.build_camera_dir			(vCameraPosition,vCameraDirection,vCameraTop);
-	}
-
-	// Matrices
-	mFullTransform.mul			( mProject,mView	);
-	m_pRender->SetCacheXform(mView, mProject);
-	//RCache.set_xform_view		( mView				);
-	//RCache.set_xform_project	( mProject			);
-	D3DXMatrixInverse			( (D3DXMATRIX*)&mInvFullTransform, 0, (D3DXMATRIX*)&mFullTransform);
-
-	vCameraPosition_saved	= vCameraPosition;
-	mFullTransform_saved	= mFullTransform;
-	mView_saved				= mView;
-	mProject_saved			= mProject;
-
-	// *** Resume threads
-	// Capture end point - thread must run only ONE cycle
-	// Release start point - allow thread to run
-	mt_csLeave.Enter			();
-	mt_csEnter.Leave			();
-	Sleep						(0);
+    if (psDeviceFlags.test(rsStatistic)) g_bEnableStatGather = TRUE;
+    else g_bEnableStatGather = FALSE;
+    if (g_loading_events.size())
+    {
+        if (g_loading_events.front()())
+            g_loading_events.pop_front();
+        pApp->LoadDraw();
+        return;
+    }
+    else
+    {
+        if ((!Device.dwPrecacheFrame) && (!g_SASH.IsBenchmarkRunning())
+            && g_bLoaded)
+            g_SASH.StartBenchmark();
+
+        FrameMove();
+    }
+
+    // Precache
+    if (dwPrecacheFrame)
+    {
+        float factor = float(dwPrecacheFrame) / float(dwPrecacheTotal);
+        float angle = PI_MUL_2 * factor;
+        vCameraDirection.set(_sin(angle), 0, _cos(angle));
+        vCameraDirection.normalize();
+        vCameraTop.set(0, 1, 0);
+        vCameraRight.crossproduct(vCameraTop, vCameraDirection);
+
+        mView.build_camera_dir(vCameraPosition, vCameraDirection, vCameraTop);
+    }
+
+    // Matrices
+    mFullTransform.mul(mProject, mView);
+    m_pRender->SetCacheXform(mView, mProject);
+    //RCache.set_xform_view ( mView );
+    //RCache.set_xform_project ( mProject );
+    D3DXMatrixInverse((D3DXMATRIX*)&mInvFullTransform, 0, (D3DXMATRIX*)&mFullTransform);
+
+    vCameraPosition_saved = vCameraPosition;
+    mFullTransform_saved = mFullTransform;
+    mView_saved = mView;
+    mProject_saved = mProject;
+
+    // *** Resume threads
+    // Capture end point - thread must run only ONE cycle
+    // Release start point - allow thread to run
+    mt_csLeave.Enter();
+    mt_csEnter.Leave();
+    Sleep(0);
 
 #ifndef DEDICATED_SERVER
-	Statistic->RenderTOTAL_Real.FrameStart	();
-	Statistic->RenderTOTAL_Real.Begin		();
-	if (b_is_Active)							{
-		if (Begin())				{
-
-			seqRender.Process						(rp_Render);
-			if (psDeviceFlags.test(rsCameraPos) || psDeviceFlags.test(rsStatistic) || Statistic->errors.size())	
-				Statistic->Show						();
-			//	TEST!!!
-			//Statistic->RenderTOTAL_Real.End			();
-			//	Present goes here
-			End										();
-		}
-	}
-	Statistic->RenderTOTAL_Real.End			();
-	Statistic->RenderTOTAL_Real.FrameEnd	();
-	Statistic->RenderTOTAL.accum	= Statistic->RenderTOTAL_Real.accum;
+    Statistic->RenderTOTAL_Real.FrameStart();
+    Statistic->RenderTOTAL_Real.Begin();
+    if (b_is_Active)
+    {
+        if (Begin())
+        {
+
+            seqRender.Process(rp_Render);
+            if (psDeviceFlags.test(rsCameraPos) || psDeviceFlags.test(rsStatistic) || Statistic->errors.size())
+                Statistic->Show();
+            // TEST!!!
+            //Statistic->RenderTOTAL_Real.End ();
+            // Present goes here
+            End();
+        }
+    }
+    Statistic->RenderTOTAL_Real.End();
+    Statistic->RenderTOTAL_Real.FrameEnd();
+    Statistic->RenderTOTAL.accum = Statistic->RenderTOTAL_Real.accum;
 #endif // #ifndef DEDICATED_SERVER
-	// *** Suspend threads
-	// Capture startup point
-	// Release end point - allow thread to wait for startup point
-	mt_csEnter.Enter						();
-	mt_csLeave.Leave						();
-
-	// Ensure, that second thread gets chance to execute anyway
-	if (dwFrame!=mt_Thread_marker)			{
-		for (u32 pit=0; pitrun			();
-	m_editor_finalize		(m_editor);
-	xr_delete				(m_engine);
+    m_editor->run();
+    m_editor_finalize(m_editor);
+    xr_delete(m_engine);
 }
 #endif // #ifdef INGAME_EDITOR
 
 void CRenderDevice::message_loop()
 {
 #ifdef INGAME_EDITOR
-	if (editor()) {
-		message_loop_editor	();
-		return;
-	}
+    if (editor())
+    {
+        message_loop_editor();
+        return;
+    }
 #endif // #ifdef INGAME_EDITOR
 
-	MSG						msg;
-    PeekMessage				(&msg, NULL, 0U, 0U, PM_NOREMOVE );
-	while (msg.message != WM_QUIT) {
-		if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) {
-			TranslateMessage(&msg);
-			DispatchMessage	(&msg);
-			continue;
-		}
-
-		on_idle				();
+    MSG msg;
+    PeekMessage(&msg, NULL, 0U, 0U, PM_NOREMOVE);
+    while (msg.message != WM_QUIT)
+    {
+        if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
+        {
+            TranslateMessage(&msg);
+            DispatchMessage(&msg);
+            continue;
+        }
+
+        on_idle();
     }
 }
 
-void CRenderDevice::Run			()
+void CRenderDevice::Run()
 {
-//	DUMP_PHASE;
-	g_bLoaded		= FALSE;
-	Log				("Starting engine...");
-	thread_name		("X-RAY Primary thread");
-
-	// Startup timers and calculate timer delta
-	dwTimeGlobal				= 0;
-	Timer_MM_Delta				= 0;
-	{
-		u32 time_mm			= timeGetTime	();
-		while (timeGetTime()==time_mm);			// wait for next tick
-		u32 time_system		= timeGetTime	();
-		u32 time_local		= TimerAsync	();
-		Timer_MM_Delta		= time_system-time_local;
-	}
-
-	// Start all threads
-//	InitializeCriticalSection	(&mt_csEnter);
-//	InitializeCriticalSection	(&mt_csLeave);
-	mt_csEnter.Enter			();
-	mt_bMustExit				= FALSE;
-	thread_spawn				(mt_Thread,"X-RAY Secondary thread",0,0);
-
-	// Message cycle
-	seqAppStart.Process			(rp_AppStart);
-
-	//CHK_DX(HW.pDevice->Clear(0,0,D3DCLEAR_TARGET,D3DCOLOR_XRGB(0,0,0),1,0));
-	m_pRender->ClearTarget		();
-
-	message_loop				();
-
-	seqAppEnd.Process		(rp_AppEnd);
-
-	// Stop Balance-Thread
-	mt_bMustExit			= TRUE;
-	mt_csEnter.Leave		();
-	while (mt_bMustExit)	Sleep(0);
-//	DeleteCriticalSection	(&mt_csEnter);
-//	DeleteCriticalSection	(&mt_csLeave);
+    // DUMP_PHASE;
+    g_bLoaded = FALSE;
+    Log("Starting engine...");
+    thread_name("X-RAY Primary thread");
+
+    // Startup timers and calculate timer delta
+    dwTimeGlobal = 0;
+    Timer_MM_Delta = 0;
+    {
+        u32 time_mm = timeGetTime();
+        while (timeGetTime() == time_mm); // wait for next tick
+        u32 time_system = timeGetTime();
+        u32 time_local = TimerAsync();
+        Timer_MM_Delta = time_system - time_local;
+    }
+
+    // Start all threads
+    // InitializeCriticalSection (&mt_csEnter);
+    // InitializeCriticalSection (&mt_csLeave);
+    mt_csEnter.Enter();
+    mt_bMustExit = FALSE;
+    thread_spawn(mt_Thread, "X-RAY Secondary thread", 0, 0);
+
+    // Message cycle
+    seqAppStart.Process(rp_AppStart);
+
+    //CHK_DX(HW.pDevice->Clear(0,0,D3DCLEAR_TARGET,D3DCOLOR_XRGB(0,0,0),1,0));
+    m_pRender->ClearTarget();
+
+    message_loop();
+
+    seqAppEnd.Process(rp_AppEnd);
+
+    // Stop Balance-Thread
+    mt_bMustExit = TRUE;
+    mt_csEnter.Leave();
+    while (mt_bMustExit) Sleep(0);
+    // DeleteCriticalSection (&mt_csEnter);
+    // DeleteCriticalSection (&mt_csLeave);
 }
 
-u32 app_inactive_time		= 0;
+u32 app_inactive_time = 0;
 u32 app_inactive_time_start = 0;
 
-void ProcessLoading(RP_FUNC *f);
+void ProcessLoading(RP_FUNC* f);
 void CRenderDevice::FrameMove()
 {
-	dwFrame			++;
-
-	Core.dwFrame = dwFrame;
-
-	dwTimeContinual	= TimerMM.GetElapsed_ms() - app_inactive_time;
-
-	if (psDeviceFlags.test(rsConstantFPS))	{
-		// 20ms = 50fps
-		//fTimeDelta		=	0.020f;			
-		//fTimeGlobal		+=	0.020f;
-		//dwTimeDelta		=	20;
-		//dwTimeGlobal	+=	20;
-		// 33ms = 30fps
-		fTimeDelta		=	0.033f;			
-		fTimeGlobal		+=	0.033f;
-		dwTimeDelta		=	33;
-		dwTimeGlobal	+=	33;
-	} else {
-		// Timer
-		float fPreviousFrameTime = Timer.GetElapsed_sec(); Timer.Start();	// previous frame
-		fTimeDelta = 0.1f * fTimeDelta + 0.9f*fPreviousFrameTime;			// smooth random system activity - worst case ~7% error
-		//fTimeDelta = 0.7f * fTimeDelta + 0.3f*fPreviousFrameTime;			// smooth random system activity
-		if (fTimeDelta>.1f)    
-			fTimeDelta = .1f;							// limit to 15fps minimum
-
-		if (fTimeDelta <= 0.f) 
-			fTimeDelta = EPS_S + EPS_S;					// limit to 15fps minimum
-
-		if(Paused())	
-			fTimeDelta = 0.0f;
-
-//		u64	qTime		= TimerGlobal.GetElapsed_clk();
-		fTimeGlobal		= TimerGlobal.GetElapsed_sec(); //float(qTime)*CPU::cycles2seconds;
-		u32	_old_global	= dwTimeGlobal;
-		dwTimeGlobal = TimerGlobal.GetElapsed_ms();
-		dwTimeDelta		= dwTimeGlobal-_old_global;
-	}
-
-	// Frame move
-	Statistic->EngineTOTAL.Begin	();
-
-	//	TODO: HACK to test loading screen.
-	//if(!g_bLoaded) 
-		ProcessLoading				(rp_Frame);
-	//else
-	//	seqFrame.Process			(rp_Frame);
-	Statistic->EngineTOTAL.End	();
+    dwFrame++;
+
+    Core.dwFrame = dwFrame;
+
+    dwTimeContinual = TimerMM.GetElapsed_ms() - app_inactive_time;
+
+    if (psDeviceFlags.test(rsConstantFPS))
+    {
+        // 20ms = 50fps
+        //fTimeDelta = 0.020f;
+        //fTimeGlobal += 0.020f;
+        //dwTimeDelta = 20;
+        //dwTimeGlobal += 20;
+        // 33ms = 30fps
+        fTimeDelta = 0.033f;
+        fTimeGlobal += 0.033f;
+        dwTimeDelta = 33;
+        dwTimeGlobal += 33;
+    }
+    else
+    {
+        // Timer
+        float fPreviousFrameTime = Timer.GetElapsed_sec();
+        Timer.Start(); // previous frame
+        fTimeDelta = 0.1f * fTimeDelta + 0.9f*fPreviousFrameTime; // smooth random system activity - worst case ~7% error
+        //fTimeDelta = 0.7f * fTimeDelta + 0.3f*fPreviousFrameTime; // smooth random system activity
+        if (fTimeDelta > .1f)
+            fTimeDelta = .1f; // limit to 15fps minimum
+
+        if (fTimeDelta <= 0.f)
+            fTimeDelta = EPS_S + EPS_S; // limit to 15fps minimum
+
+        if (Paused())
+            fTimeDelta = 0.0f;
+
+        // u64 qTime = TimerGlobal.GetElapsed_clk();
+        fTimeGlobal = TimerGlobal.GetElapsed_sec(); //float(qTime)*CPU::cycles2seconds;
+        u32 _old_global = dwTimeGlobal;
+        dwTimeGlobal = TimerGlobal.GetElapsed_ms();
+        dwTimeDelta = dwTimeGlobal - _old_global;
+    }
+
+    // Frame move
+    Statistic->EngineTOTAL.Begin();
+
+    // TODO: HACK to test loading screen.
+    //if(!g_bLoaded)
+    ProcessLoading(rp_Frame);
+    //else
+    // seqFrame.Process (rp_Frame);
+    Statistic->EngineTOTAL.End();
 }
 
-void ProcessLoading				(RP_FUNC *f)
+void ProcessLoading(RP_FUNC* f)
 {
-	Device.seqFrame.Process				(rp_Frame);
-	g_bLoaded							= TRUE;
+    Device.seqFrame.Process(rp_Frame);
+    g_bLoaded = TRUE;
 }
 
 ENGINE_API BOOL bShowPauseString = TRUE;
@@ -497,67 +514,71 @@ ENGINE_API BOOL bShowPauseString = TRUE;
 
 void CRenderDevice::Pause(BOOL bOn, BOOL bTimer, BOOL bSound, LPCSTR reason)
 {
-	static int snd_emitters_ = -1;
+    static int snd_emitters_ = -1;
 
-	if (g_bBenchmark)	return;
+    if (g_bBenchmark) return;
 
 
 #ifdef DEBUG
-//	Msg("pause [%s] timer=[%s] sound=[%s] reason=%s",bOn?"ON":"OFF", bTimer?"ON":"OFF", bSound?"ON":"OFF", reason);
+    // Msg("pause [%s] timer=[%s] sound=[%s] reason=%s",bOn?"ON":"OFF", bTimer?"ON":"OFF", bSound?"ON":"OFF", reason);
 #endif // DEBUG
 
-#ifndef DEDICATED_SERVER	
+#ifndef DEDICATED_SERVER
 
-	if(bOn)
-	{
-		if(!Paused())						
-			bShowPauseString				= 
+    if (bOn)
+    {
+        if (!Paused())
+            bShowPauseString =
 #ifdef INGAME_EDITOR
-				editor() ? FALSE : 
+                editor() ? FALSE :
 #endif // #ifdef INGAME_EDITOR
 #ifdef DEBUG
-				!xr_strcmp(reason, "li_pause_key_no_clip")?	FALSE:
+                !xr_strcmp(reason, "li_pause_key_no_clip") ? FALSE :
 #endif // DEBUG
-				TRUE;
+                TRUE;
 
-		if( bTimer && (!g_pGamePersistent || g_pGamePersistent->CanBePaused()) )
-		{
-			g_pauseMngr.Pause				(TRUE);
+        if (bTimer && (!g_pGamePersistent || g_pGamePersistent->CanBePaused()))
+        {
+            g_pauseMngr.Pause(TRUE);
 #ifdef DEBUG
-			if(!xr_strcmp(reason, "li_pause_key_no_clip"))
-				TimerGlobal.Pause				(FALSE);
+            if (!xr_strcmp(reason, "li_pause_key_no_clip"))
+                TimerGlobal.Pause(FALSE);
 #endif // DEBUG
-		}
-	
-		if (bSound && ::Sound) {
-			snd_emitters_ =					::Sound->pause_emitters(true);
+        }
+
+        if (bSound && ::Sound)
+        {
+            snd_emitters_ = ::Sound->pause_emitters(true);
 #ifdef DEBUG
-//			Log("snd_emitters_[true]",snd_emitters_);
+            // Log("snd_emitters_[true]",snd_emitters_);
 #endif // DEBUG
-		}
-	}else
-	{
-		if( bTimer && /*g_pGamePersistent->CanBePaused() &&*/ g_pauseMngr.Paused() )
-		{
-			fTimeDelta						= EPS_S + EPS_S;
-			g_pauseMngr.Pause				(FALSE);
-		}
-		
-		if(bSound)
-		{
-			if(snd_emitters_>0) //avoid crash
-			{
-				snd_emitters_ =				::Sound->pause_emitters(false);
+        }
+    }
+    else
+    {
+        if (bTimer && /*g_pGamePersistent->CanBePaused() &&*/ g_pauseMngr.Paused())
+        {
+            fTimeDelta = EPS_S + EPS_S;
+            g_pauseMngr.Pause(FALSE);
+        }
+
+        if (bSound)
+        {
+            if (snd_emitters_ > 0) //avoid crash
+            {
+                snd_emitters_ = ::Sound->pause_emitters(false);
 #ifdef DEBUG
-//				Log("snd_emitters_[false]",snd_emitters_);
+                // Log("snd_emitters_[false]",snd_emitters_);
 #endif // DEBUG
-			}else {
+            }
+            else
+            {
 #ifdef DEBUG
-				Log("Sound->pause_emitters underflow");
+                Log("Sound->pause_emitters underflow");
 #endif // DEBUG
-			}
-		}
-	}
+            }
+        }
+    }
 
 #endif
 
@@ -565,75 +586,76 @@ void CRenderDevice::Pause(BOOL bOn, BOOL bTimer, BOOL bSound, LPCSTR reason)
 
 BOOL CRenderDevice::Paused()
 {
-	return g_pauseMngr.Paused();
+    return g_pauseMngr.Paused();
 };
 
 void CRenderDevice::OnWM_Activate(WPARAM wParam, LPARAM lParam)
 {
-	u16 fActive						= LOWORD(wParam);
-	BOOL fMinimized					= (BOOL) HIWORD(wParam);
-	BOOL bActive					= ((fActive!=WA_INACTIVE) && (!fMinimized))?TRUE:FALSE;
-	
-	if (bActive!=Device.b_is_Active)
-	{
-		Device.b_is_Active			= bActive;
-
-		if (Device.b_is_Active)	
-		{
-			Device.seqAppActivate.Process(rp_AppActivate);
-			app_inactive_time		+= TimerMM.GetElapsed_ms() - app_inactive_time_start;
+    u16 fActive = LOWORD(wParam);
+    BOOL fMinimized = (BOOL)HIWORD(wParam);
+    BOOL bActive = ((fActive != WA_INACTIVE) && (!fMinimized)) ? TRUE : FALSE;
+
+    if (bActive != Device.b_is_Active)
+    {
+        Device.b_is_Active = bActive;
+
+        if (Device.b_is_Active)
+        {
+            Device.seqAppActivate.Process(rp_AppActivate);
+            app_inactive_time += TimerMM.GetElapsed_ms() - app_inactive_time_start;
 
 #ifndef DEDICATED_SERVER
-#	ifdef INGAME_EDITOR
-			if (!editor())
-#	endif // #ifdef INGAME_EDITOR
-				ShowCursor			(FALSE);
+# ifdef INGAME_EDITOR
+            if (!editor())
+# endif // #ifdef INGAME_EDITOR
+                ShowCursor(FALSE);
 #endif // #ifndef DEDICATED_SERVER
-		}else	
-		{
-			app_inactive_time_start	= TimerMM.GetElapsed_ms();
-			Device.seqAppDeactivate.Process(rp_AppDeactivate);
-			ShowCursor				(TRUE);
-		}
-	}
+        }
+        else
+        {
+            app_inactive_time_start = TimerMM.GetElapsed_ms();
+            Device.seqAppDeactivate.Process(rp_AppDeactivate);
+            ShowCursor(TRUE);
+        }
+    }
 }
 
-void	CRenderDevice::AddSeqFrame			( pureFrame* f, bool mt )
+void CRenderDevice::AddSeqFrame(pureFrame* f, bool mt)
 {
-		if ( mt )	
-		seqFrameMT.Add	(f,REG_PRIORITY_HIGH);
-	else								
-		seqFrame.Add		(f,REG_PRIORITY_LOW);
+    if (mt)
+        seqFrameMT.Add(f, REG_PRIORITY_HIGH);
+    else
+        seqFrame.Add(f, REG_PRIORITY_LOW);
 
 }
 
-void	CRenderDevice::RemoveSeqFrame	( pureFrame* f )
+void CRenderDevice::RemoveSeqFrame(pureFrame* f)
 {
-	seqFrameMT.Remove	( f );
-	seqFrame.Remove		( f );
+    seqFrameMT.Remove(f);
+    seqFrame.Remove(f);
 }
 
 CLoadScreenRenderer::CLoadScreenRenderer()
-:b_registered(false)
+    :b_registered(false)
 {}
 
-void CLoadScreenRenderer::start(bool b_user_input) 
+void CLoadScreenRenderer::start(bool b_user_input)
 {
-	Device.seqRender.Add			(this, 0);
-	b_registered					= true;
-	b_need_user_input				= b_user_input;
+    Device.seqRender.Add(this, 0);
+    b_registered = true;
+    b_need_user_input = b_user_input;
 }
 
 void CLoadScreenRenderer::stop()
 {
-	if(!b_registered)				return;
-	Device.seqRender.Remove			(this);
-	pApp->destroy_loading_shaders	();
-	b_registered					= false;
-	b_need_user_input				= false;
+    if (!b_registered) return;
+    Device.seqRender.Remove(this);
+    pApp->destroy_loading_shaders();
+    b_registered = false;
+    b_need_user_input = false;
 }
 
-void CLoadScreenRenderer::OnRender() 
+void CLoadScreenRenderer::OnRender()
 {
-	pApp->load_draw_internal();
+    pApp->load_draw_internal();
 }
\ No newline at end of file
diff --git a/src/xrEngine/device.h b/src/xrEngine/device.h
index 450e29f9acc..1baf9741a6a 100644
--- a/src/xrEngine/device.h
+++ b/src/xrEngine/device.h
@@ -4,10 +4,10 @@
 
 // Note:
 // ZNear - always 0.0f
-// ZFar  - always 1.0f
+// ZFar - always 1.0f
 
-//class	ENGINE_API	CResourceManager;
-//class	ENGINE_API	CGammaControl;
+//class ENGINE_API CResourceManager;
+//class ENGINE_API CGammaControl;
 
 #include "pure.h"
 //#include "hw.h"
@@ -16,7 +16,7 @@
 //#include "shader.h"
 //#include "R_Backend.h"
 
-#define VIEWPORT_NEAR  0.2f
+#define VIEWPORT_NEAR 0.2f
 
 #define DEVICE_RESET_PRECACHE_FRAME_COUNT 10
 
@@ -24,7 +24,7 @@
 #include "../Include/xrRender/RenderDeviceRender.h"
 
 #ifdef INGAME_EDITOR
-#	include "../Include/editor/interfaces.hpp"
+# include "../Include/editor/interfaces.hpp"
 #endif // #ifdef INGAME_EDITOR
 
 class engine_impl;
@@ -34,305 +34,308 @@ class engine_impl;
 class IRenderDevice
 {
 public:
-	virtual		CStatsPhysics*	_BCL		StatPhysics		()							= 0;								
-	virtual				void	_BCL		AddSeqFrame		( pureFrame* f, bool mt )	= 0;
-	virtual				void	_BCL		RemoveSeqFrame	( pureFrame* f )			= 0;
+    virtual CStatsPhysics* _BCL StatPhysics() = 0;
+    virtual void _BCL AddSeqFrame(pureFrame* f, bool mt) = 0;
+    virtual void _BCL RemoveSeqFrame(pureFrame* f) = 0;
 };
 
 class ENGINE_API CRenderDeviceData
 {
 
 public:
-	u32										dwWidth;
-	u32										dwHeight;
-	
-	u32										dwPrecacheFrame;
-	BOOL									b_is_Ready;
-	BOOL									b_is_Active;
+    u32 dwWidth;
+    u32 dwHeight;
+
+    u32 dwPrecacheFrame;
+    BOOL b_is_Ready;
+    BOOL b_is_Active;
 public:
 
-		// Engine flow-control
-	u32										dwFrame;
+    // Engine flow-control
+    u32 dwFrame;
 
-	float									fTimeDelta;
-	float									fTimeGlobal;
-	u32										dwTimeDelta;
-	u32										dwTimeGlobal;
-	u32										dwTimeContinual;
+    float fTimeDelta;
+    float fTimeGlobal;
+    u32 dwTimeDelta;
+    u32 dwTimeGlobal;
+    u32 dwTimeContinual;
 
-	Fvector									vCameraPosition;
-	Fvector									vCameraDirection;
-	Fvector									vCameraTop;
-	Fvector									vCameraRight;
+    Fvector vCameraPosition;
+    Fvector vCameraDirection;
+    Fvector vCameraTop;
+    Fvector vCameraRight;
 
-	Fmatrix									mView;
-	Fmatrix									mProject;
-	Fmatrix									mFullTransform;
+    Fmatrix mView;
+    Fmatrix mProject;
+    Fmatrix mFullTransform;
 
-	// Copies of corresponding members. Used for synchronization.
-	Fvector									vCameraPosition_saved;
+    // Copies of corresponding members. Used for synchronization.
+    Fvector vCameraPosition_saved;
 
-	Fmatrix									mView_saved;
-	Fmatrix									mProject_saved;
-	Fmatrix									mFullTransform_saved;
+    Fmatrix mView_saved;
+    Fmatrix mProject_saved;
+    Fmatrix mFullTransform_saved;
 
-	float									fFOV;
-	float									fASPECT;
+    float fFOV;
+    float fASPECT;
 protected:
 
-	u32										Timer_MM_Delta;
-	CTimer_paused							Timer;
-	CTimer_paused							TimerGlobal;
+    u32 Timer_MM_Delta;
+    CTimer_paused Timer;
+    CTimer_paused TimerGlobal;
 public:
 
-// Registrators
-	CRegistrator				seqRender;
-	CRegistrator				seqAppActivate;
-	CRegistrator				seqAppDeactivate;
-	CRegistrator				seqAppStart;
-	CRegistrator				seqAppEnd;
-	CRegistrator				seqFrame;
-	CRegistrator		seqResolutionChanged;
+    // Registrators
+    CRegistrator  seqRender;
+    CRegistrator  seqAppActivate;
+    CRegistrator  seqAppDeactivate;
+    CRegistrator  seqAppStart;
+    CRegistrator  seqAppEnd;
+    CRegistrator  seqFrame;
+    CRegistrator  seqResolutionChanged;
 
-	HWND									m_hWnd;
-//	CStats*									Statistic;
+    HWND m_hWnd;
+    // CStats* Statistic;
 
 };
 
-class	ENGINE_API CRenderDeviceBase :
-	public IRenderDevice,
-	public CRenderDeviceData
+class ENGINE_API CRenderDeviceBase :
+    public IRenderDevice,
+    public CRenderDeviceData
 {
 public:
 };
 
 #pragma pack(pop)
 // refs
-class ENGINE_API CRenderDevice: public CRenderDeviceBase
+class ENGINE_API CRenderDevice : public CRenderDeviceBase
 {
 private:
     // Main objects used for creating and rendering the 3D scene
-    u32										m_dwWindowStyle;
-    RECT									m_rcWindowBounds;
-    RECT									m_rcWindowClient;
-
-	//u32										Timer_MM_Delta;
-	//CTimer_paused							Timer;
-	//CTimer_paused							TimerGlobal;
-	CTimer									TimerMM;
-
-	void									_Create		(LPCSTR shName);
-	void									_Destroy	(BOOL	bKeepTextures);
-	void									_SetupStates();
+    u32 m_dwWindowStyle;
+    RECT m_rcWindowBounds;
+    RECT m_rcWindowClient;
+
+    //u32 Timer_MM_Delta;
+    //CTimer_paused Timer;
+    //CTimer_paused TimerGlobal;
+    CTimer TimerMM;
+
+    void _Create(LPCSTR shName);
+    void _Destroy(BOOL bKeepTextures);
+    void _SetupStates();
 public:
- //   HWND									m_hWnd;
-	LRESULT									MsgProc		(HWND,UINT,WPARAM,LPARAM);
-
-//	u32										dwFrame;
-//	u32										dwPrecacheFrame;
-	u32										dwPrecacheTotal;
-
-//	u32										dwWidth, dwHeight;
-	float									fWidth_2, fHeight_2;
-//	BOOL									b_is_Ready;
-//	BOOL									b_is_Active;
-	void									OnWM_Activate(WPARAM wParam, LPARAM lParam);
+    // HWND m_hWnd;
+    LRESULT MsgProc(HWND, UINT, WPARAM, LPARAM);
+
+    // u32 dwFrame;
+    // u32 dwPrecacheFrame;
+    u32 dwPrecacheTotal;
+
+    // u32 dwWidth, dwHeight;
+    float fWidth_2, fHeight_2;
+    // BOOL b_is_Ready;
+    // BOOL b_is_Active;
+    void OnWM_Activate(WPARAM wParam, LPARAM lParam);
 public:
-	//ref_shader								m_WireShader;
-	//ref_shader								m_SelectionShader;
-
-	IRenderDeviceRender						*m_pRender;
-
-	BOOL									m_bNearer;
-	void									SetNearer	(BOOL enabled)
-	{
-		if (enabled&&!m_bNearer){
-			m_bNearer						= TRUE;
-			mProject._43					-= EPS_L;
-		}else if (!enabled&&m_bNearer){
-			m_bNearer						= FALSE;
-			mProject._43					+= EPS_L;
-		}
-		m_pRender->SetCacheXform(mView, mProject);
-		//R_ASSERT(0);
-		//	TODO: re-implement set projection
-		//RCache.set_xform_project			(mProject);
-	}
-
-	void									DumpResourcesMemoryUsage() { m_pRender->ResourcesDumpMemoryUsage();}
+    //ref_shader m_WireShader;
+    //ref_shader m_SelectionShader;
+
+    IRenderDeviceRender* m_pRender;
+
+    BOOL m_bNearer;
+    void SetNearer(BOOL enabled)
+    {
+        if (enabled&&!m_bNearer)
+        {
+            m_bNearer = TRUE;
+            mProject._43 -= EPS_L;
+        }
+        else if (!enabled&&m_bNearer)
+        {
+            m_bNearer = FALSE;
+            mProject._43 += EPS_L;
+        }
+        m_pRender->SetCacheXform(mView, mProject);
+        //R_ASSERT(0);
+        // TODO: re-implement set projection
+        //RCache.set_xform_project (mProject);
+    }
+
+    void DumpResourcesMemoryUsage() { m_pRender->ResourcesDumpMemoryUsage(); }
 public:
-	// Registrators
-	//CRegistrator				seqRender;
-//	CRegistrator				seqAppActivate;
-//	CRegistrator				seqAppDeactivate;
-//	CRegistrator				seqAppStart;
-//	CRegistrator				seqAppEnd;
-	//CRegistrator				seqFrame;
-	CRegistrator				seqFrameMT;
-	CRegistrator				seqDeviceReset;
-	xr_vector		 >	seqParallel;
-
-	// Dependent classes
-	//CResourceManager*						Resources;
-
-	CStats*									Statistic;
-
-	// Engine flow-control
-	//float									fTimeDelta;
-	//float									fTimeGlobal;
-	//u32										dwTimeDelta;
-	//u32										dwTimeGlobal;
-	//u32										dwTimeContinual;
-
-	// Cameras & projection
-	//Fvector									vCameraPosition;
-	//Fvector									vCameraDirection;
-	//Fvector									vCameraTop;
-	//Fvector									vCameraRight;
-
-	//Fmatrix									mView;
-	//Fmatrix									mProject;
-	//Fmatrix									mFullTransform;
-
-	Fmatrix									mInvFullTransform;
-
-	//float									fFOV;
-	//float									fASPECT;
-	
-	CRenderDevice			()
-		:
-		m_pRender(0)
+    // Registrators
+    //CRegistrator  seqRender;
+    // CRegistrator  seqAppActivate;
+    // CRegistrator  seqAppDeactivate;
+    // CRegistrator  seqAppStart;
+    // CRegistrator  seqAppEnd;
+    //CRegistrator  seqFrame;
+    CRegistrator  seqFrameMT;
+    CRegistrator  seqDeviceReset;
+    xr_vector  > seqParallel;
+
+    // Dependent classes
+    //CResourceManager* Resources;
+
+    CStats* Statistic;
+
+    // Engine flow-control
+    //float fTimeDelta;
+    //float fTimeGlobal;
+    //u32 dwTimeDelta;
+    //u32 dwTimeGlobal;
+    //u32 dwTimeContinual;
+
+    // Cameras & projection
+    //Fvector vCameraPosition;
+    //Fvector vCameraDirection;
+    //Fvector vCameraTop;
+    //Fvector vCameraRight;
+
+    //Fmatrix mView;
+    //Fmatrix mProject;
+    //Fmatrix mFullTransform;
+
+    Fmatrix mInvFullTransform;
+
+    //float fFOV;
+    //float fASPECT;
+
+    CRenderDevice()
+        :
+        m_pRender(0)
 #ifdef INGAME_EDITOR
-		,m_editor_module(0),
-		m_editor_initialize(0),
-		m_editor_finalize(0),
-		m_editor(0),
-		m_engine(0)
+        , m_editor_module(0),
+        m_editor_initialize(0),
+        m_editor_finalize(0),
+        m_editor(0),
+        m_engine(0)
 #endif // #ifdef INGAME_EDITOR
 #ifdef PROFILE_CRITICAL_SECTIONS
-		,mt_csEnter(MUTEX_PROFILE_ID(CRenderDevice::mt_csEnter))
-		,mt_csLeave(MUTEX_PROFILE_ID(CRenderDevice::mt_csLeave))
+        ,mt_csEnter(MUTEX_PROFILE_ID(CRenderDevice::mt_csEnter))
+        ,mt_csLeave(MUTEX_PROFILE_ID(CRenderDevice::mt_csLeave))
 #endif // #ifdef PROFILE_CRITICAL_SECTIONS
-	{
-	    m_hWnd              = NULL;
-		b_is_Active			= FALSE;
-		b_is_Ready			= FALSE;
-		Timer.Start			();
-		m_bNearer			= FALSE;
-	};
-
-	void	Pause							(BOOL bOn, BOOL bTimer, BOOL bSound, LPCSTR reason);
-	BOOL	Paused							();
-
-	// Scene control
-	void PreCache							(u32 amount, bool b_draw_loadscreen, bool b_wait_user_input);
-	BOOL Begin								();
-	void Clear								();
-	void End								();
-	void FrameMove							();
-	
-	void overdrawBegin						();
-	void overdrawEnd						();
-
-	// Mode control
-	void DumpFlags							();
-	IC	 CTimer_paused* GetTimerGlobal		()	{ return &TimerGlobal;								}
-	u32	 TimerAsync							()	{ return TimerGlobal.GetElapsed_ms();				}
-	u32	 TimerAsync_MMT						()	{ return TimerMM.GetElapsed_ms() +	Timer_MM_Delta; }
-
-	// Creation & Destroying
-	void ConnectToRender();
-	void Create								(void);
-	void Run								(void);
-	void Destroy							(void);
-	void Reset								(bool precache = true);
-
-	void Initialize							(void);
-	void ShutDown							(void);
+    {
+        m_hWnd = NULL;
+        b_is_Active = FALSE;
+        b_is_Ready = FALSE;
+        Timer.Start();
+        m_bNearer = FALSE;
+    };
+
+    void Pause(BOOL bOn, BOOL bTimer, BOOL bSound, LPCSTR reason);
+    BOOL Paused();
+
+    // Scene control
+    void PreCache(u32 amount, bool b_draw_loadscreen, bool b_wait_user_input);
+    BOOL Begin();
+    void Clear();
+    void End();
+    void FrameMove();
+
+    void overdrawBegin();
+    void overdrawEnd();
+
+    // Mode control
+    void DumpFlags();
+    IC CTimer_paused* GetTimerGlobal() { return &TimerGlobal; }
+    u32 TimerAsync() { return TimerGlobal.GetElapsed_ms(); }
+    u32 TimerAsync_MMT() { return TimerMM.GetElapsed_ms() + Timer_MM_Delta; }
+
+    // Creation & Destroying
+    void ConnectToRender();
+    void Create(void);
+    void Run(void);
+    void Destroy(void);
+    void Reset(bool precache = true);
+
+    void Initialize(void);
+    void ShutDown(void);
 
 public:
-	void time_factor						(const float &time_factor)
-	{
-		Timer.time_factor		(time_factor);
-		TimerGlobal.time_factor	(time_factor);
-	}
-	
-	IC	const float &time_factor			() const
-	{
-		VERIFY					(Timer.time_factor() == TimerGlobal.time_factor());
-		return					(Timer.time_factor());
-	}
-
-	// Multi-threading
-	xrCriticalSection	mt_csEnter;
-	xrCriticalSection	mt_csLeave;
-	volatile BOOL		mt_bMustExit;
-
-	ICF		void			remove_from_seq_parallel	(const fastdelegate::FastDelegate0<> &delegate)
-	{
-		xr_vector >::iterator I = std::find(
-			seqParallel.begin(),
-			seqParallel.end(),
-			delegate
-		);
-		if (I != seqParallel.end())
-			seqParallel.erase	(I);
-	}
+    void time_factor(const float& time_factor)
+    {
+        Timer.time_factor(time_factor);
+        TimerGlobal.time_factor(time_factor);
+    }
+
+    IC const float& time_factor() const
+    {
+        VERIFY(Timer.time_factor() == TimerGlobal.time_factor());
+        return (Timer.time_factor());
+    }
+
+    // Multi-threading
+    xrCriticalSection mt_csEnter;
+    xrCriticalSection mt_csLeave;
+    volatile BOOL mt_bMustExit;
+
+    ICF void remove_from_seq_parallel(const fastdelegate::FastDelegate0<>& delegate)
+    {
+        xr_vector >::iterator I = std::find(
+                    seqParallel.begin(),
+                    seqParallel.end(),
+                    delegate
+                );
+        if (I != seqParallel.end())
+            seqParallel.erase(I);
+    }
 
 public:
-			void xr_stdcall		on_idle				();
-			bool xr_stdcall		on_message			(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT &result);
+    void xr_stdcall on_idle();
+    bool xr_stdcall on_message(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result);
 
 private:
-			void					message_loop		();
-virtual		void			_BCL	AddSeqFrame			( pureFrame* f, bool mt );
-virtual		void			_BCL	RemoveSeqFrame		( pureFrame* f );
-virtual		CStatsPhysics*	_BCL	StatPhysics			()	{ return  Statistic ;}
+    void message_loop();
+    virtual void _BCL AddSeqFrame(pureFrame* f, bool mt);
+    virtual void _BCL RemoveSeqFrame(pureFrame* f);
+    virtual CStatsPhysics* _BCL StatPhysics() { return Statistic; }
 #ifdef INGAME_EDITOR
 public:
-	IC		editor::ide			*editor				() const { return m_editor; }
+    IC editor::ide* editor() const { return m_editor; }
 
 private:
-			void				initialize_editor	();
-			void				message_loop_editor	();
+    void initialize_editor();
+    void message_loop_editor();
 
 private:
-	typedef editor::initialize_function_ptr			initialize_function_ptr;
-	typedef editor::finalize_function_ptr			finalize_function_ptr;
+    typedef editor::initialize_function_ptr initialize_function_ptr;
+    typedef editor::finalize_function_ptr finalize_function_ptr;
 
 private:
-	HMODULE						m_editor_module;
-	initialize_function_ptr		m_editor_initialize;
-	finalize_function_ptr		m_editor_finalize;
-	editor::ide					*m_editor;
-	engine_impl					*m_engine;
+    HMODULE m_editor_module;
+    initialize_function_ptr m_editor_initialize;
+    finalize_function_ptr m_editor_finalize;
+    editor::ide* m_editor;
+    engine_impl* m_engine;
 #endif // #ifdef INGAME_EDITOR
 };
 
-extern		ENGINE_API		CRenderDevice		Device;
+extern ENGINE_API CRenderDevice Device;
 
-#ifndef	_EDITOR
-#define	RDEVICE	Device
+#ifndef _EDITOR
+#define RDEVICE Device
 #else
-#define RDEVICE	EDevice
+#define RDEVICE EDevice
 #endif
 
 
-extern		ENGINE_API		bool				g_bBenchmark;
+extern ENGINE_API bool g_bBenchmark;
 
-typedef fastdelegate::FastDelegate0		LOADING_EVENT;
-extern	ENGINE_API xr_list		g_loading_events;
+typedef fastdelegate::FastDelegate0 LOADING_EVENT;
+extern ENGINE_API xr_list g_loading_events;
 
 class ENGINE_API CLoadScreenRenderer :public pureRender
 {
 public:
-					CLoadScreenRenderer	();
-	void			start				(bool b_user_input);
-	void			stop				();
-	virtual void	OnRender			();
+    CLoadScreenRenderer();
+    void start(bool b_user_input);
+    void stop();
+    virtual void OnRender();
 
-	bool			b_registered;
-	bool			b_need_user_input;
+    bool b_registered;
+    bool b_need_user_input;
 };
 extern ENGINE_API CLoadScreenRenderer load_screen_renderer;
 
diff --git a/src/xrEngine/edit_actions.cpp b/src/xrEngine/edit_actions.cpp
index 4d4fe60a4b3..a48ec3f5fde 100644
--- a/src/xrEngine/edit_actions.cpp
+++ b/src/xrEngine/edit_actions.cpp
@@ -1,8 +1,8 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: edit_actions.cpp
-//	Created 	: 04.03.2008
-//	Author		: Evgeniy Sokolov
-//	Description : edit actions chars class implementation
+// Module : edit_actions.cpp
+// Created : 04.03.2008
+// Author : Evgeniy Sokolov
+// Description : edit actions chars class implementation
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -14,137 +14,137 @@
 namespace text_editor
 {
 
-base::base():	m_previous_action( NULL )
+base::base() : m_previous_action(NULL)
 {
 }
 
 base::~base()
 {
-	xr_delete( m_previous_action );
+    xr_delete(m_previous_action);
 }
 
-void base::on_assign( base* const prev_action )
+void base::on_assign(base* const prev_action)
 {
-	m_previous_action = prev_action;
+    m_previous_action = prev_action;
 }
 
-void base::on_key_press( line_edit_control* const control )
+void base::on_key_press(line_edit_control* const control)
 {
-	if ( m_previous_action )
-	{
-		m_previous_action->on_key_press( control );
-	}
+    if (m_previous_action)
+    {
+        m_previous_action->on_key_press(control);
+    }
 }
 
 // -------------------------------------------------------------------------------------------------
 
-callback_base::callback_base( Callback const& callback, key_state state )
+callback_base::callback_base(Callback const& callback, key_state state)
 {
-	m_callback  = callback;
-	m_run_state = state;
+    m_callback = callback;
+    m_run_state = state;
 }
 
 callback_base::~callback_base()
 {
 }
 
-void callback_base::on_key_press( line_edit_control* const control )
+void callback_base::on_key_press(line_edit_control* const control)
 {
-	if ( control->get_key_state( m_run_state ) )
-	{
-		m_callback();
-		return;
-	}
-	base::on_key_press( control );
+    if (control->get_key_state(m_run_state))
+    {
+        m_callback();
+        return;
+    }
+    base::on_key_press(control);
 }
 
 // -------------------------------------------------------------------------------------------------
 
-type_pair::type_pair( u32 dik, char c, char c_shift, bool b_translate )
+type_pair::type_pair(u32 dik, char c, char c_shift, bool b_translate)
 {
-	init( dik, c, c_shift, b_translate );
+    init(dik, c, c_shift, b_translate);
 }
 
 type_pair::~type_pair()
 {
 }
 
-void type_pair::init( u32 dik, char c, char c_shift, bool b_translate )
+void type_pair::init(u32 dik, char c, char c_shift, bool b_translate)
 {
-	m_translate	= b_translate;
-	m_dik = dik;
-	m_char = c;
-	m_char_shift = c_shift;
+    m_translate = b_translate;
+    m_dik = dik;
+    m_char = c;
+    m_char_shift = c_shift;
 }
 
 
-void type_pair::on_key_press( line_edit_control* const control )
+void type_pair::on_key_press(line_edit_control* const control)
 {
-	char c = 0;
-	if( m_translate )
-	{
-		c				= m_char;
-		char c_shift	= m_char_shift;
-		string128		buff;
-		buff[0]			= 0;
-		
-		/*
-		//setlocale( LC_ALL, "" ); // User-default
-
-		// The following 3 lines looks useless
-
-		LPSTR			loc;
-		STRCONCAT		( loc, ".", itoa( GetACP(), code_page, 10 ) );
-		setlocale		( LC_ALL, loc );*/
-
-		static _locale_t current_locale = _create_locale(LC_ALL, "");
-		
-		if ( pInput->get_dik_name( m_dik, buff, sizeof(buff) ) )
-		{
-			if ( _isalpha_l(buff[0], current_locale) || buff[0] == char(-1) ) // "ÿ" = -1
-			{
-				_strlwr_l	(buff, current_locale);
-				c			= buff[0];
-				_strupr_l	(buff, current_locale);
-				c_shift	= buff[0];
-			}
-		}
-
-		//setlocale( LC_ALL, "C" );	// restore to ANSI
-
-		if ( control->get_key_state( ks_Shift ) != control->get_key_state( ks_CapsLock ) )
-		{
-			c = c_shift;
-		}
-	}
-	else
-	{
-		c = m_char;
-		if ( control->get_key_state( ks_Shift ) != control->get_key_state( ks_CapsLock ) )
-		{
-			c = m_char_shift;
-		}
-	}
-	control->insert_character( c );
+    char c = 0;
+    if (m_translate)
+    {
+        c = m_char;
+        char c_shift = m_char_shift;
+        string128 buff;
+        buff[0] = 0;
+
+        /*
+        //setlocale( LC_ALL, "" ); // User-default
+
+        // The following 3 lines looks useless
+
+        LPSTR loc;
+        STRCONCAT ( loc, ".", itoa( GetACP(), code_page, 10 ) );
+        setlocale ( LC_ALL, loc );*/
+
+        static _locale_t current_locale = _create_locale(LC_ALL, "");
+
+        if (pInput->get_dik_name(m_dik, buff, sizeof(buff)))
+        {
+            if (_isalpha_l(buff[0], current_locale) || buff[0] == char(-1)) // "ÿ" = -1
+            {
+                _strlwr_l(buff, current_locale);
+                c = buff[0];
+                _strupr_l(buff, current_locale);
+                c_shift = buff[0];
+            }
+        }
+
+        //setlocale( LC_ALL, "C" ); // restore to ANSI
+
+        if (control->get_key_state(ks_Shift) != control->get_key_state(ks_CapsLock))
+        {
+            c = c_shift;
+        }
+    }
+    else
+    {
+        c = m_char;
+        if (control->get_key_state(ks_Shift) != control->get_key_state(ks_CapsLock))
+        {
+            c = m_char_shift;
+        }
+    }
+    control->insert_character(c);
 }
 
 // -------------------------------------------------------------------------------------------------
 
-key_state_base::key_state_base( key_state state, base* type_pair )
-:m_type_pair(type_pair),m_state(state)
+key_state_base::key_state_base(key_state state, base* type_pair)
+    :m_type_pair(type_pair), m_state(state)
 {
 }
 
 key_state_base::~key_state_base()
 {
-	xr_delete(m_type_pair);
+    xr_delete(m_type_pair);
 }
 
-void key_state_base::on_key_press( line_edit_control* const control )
+void key_state_base::on_key_press(line_edit_control* const control)
 {
-	control->set_key_state( m_state, true );
-	if(m_type_pair)
-		m_type_pair->on_key_press(control);
+    control->set_key_state(m_state, true);
+    if (m_type_pair)
+        m_type_pair->on_key_press(control);
 }
 
 } // namespace text_editor
diff --git a/src/xrEngine/edit_actions.h b/src/xrEngine/edit_actions.h
index c4228a5d6bf..0c4faacd001 100644
--- a/src/xrEngine/edit_actions.h
+++ b/src/xrEngine/edit_actions.h
@@ -1,8 +1,8 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: edit_actions.h
-//	Created 	: 04.03.2008
-//	Author		: Evgeniy Sokolov
-//	Description : edit actions class
+// Module : edit_actions.h
+// Created : 04.03.2008
+// Author : Evgeniy Sokolov
+// Description : edit actions class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDIT_ACTIONS_H_INCLUDED
@@ -13,19 +13,19 @@
 namespace text_editor
 {
 
-enum	key_state;
-class	line_edit_control;
+enum key_state;
+class line_edit_control;
 
 class base : private boost::noncopyable
 {
 public:
-					base			();
-	virtual			~base			();
-			void	on_assign 		( base* const prev_action );
-	virtual	void	on_key_press	( line_edit_control* const control );
+    base();
+    virtual ~base();
+    void on_assign(base* const prev_action);
+    virtual void on_key_press(line_edit_control* const control);
 
 protected:
-	base*			m_previous_action;
+    base* m_previous_action;
 
 }; // class base
 
@@ -34,16 +34,16 @@ class base : private boost::noncopyable
 class callback_base : public base
 {
 private:
-	typedef		fastdelegate::FastDelegate0		Callback;
+    typedef fastdelegate::FastDelegate0 Callback;
 
 public:
-					callback_base	( Callback const& callback, key_state state );
-	virtual			~callback_base	();
-	virtual	void	on_key_press	( line_edit_control* const control );
+    callback_base(Callback const& callback, key_state state);
+    virtual ~callback_base();
+    virtual void on_key_press(line_edit_control* const control);
 
 protected:
-	key_state	m_run_state;
-	Callback	m_callback;
+    key_state m_run_state;
+    Callback m_callback;
 
 }; // class callback_base
 
@@ -52,16 +52,16 @@ class callback_base : public base
 class type_pair : public base
 {
 public:
-					type_pair		( u32 dik, char c, char c_shift, bool b_translate );
-	virtual			~type_pair		();
-			void	init			( u32 dik, char c, char c_shift, bool b_translate );
-	virtual	void	on_key_press	( line_edit_control* const control );
+    type_pair(u32 dik, char c, char c_shift, bool b_translate);
+    virtual ~type_pair();
+    void init(u32 dik, char c, char c_shift, bool b_translate);
+    virtual void on_key_press(line_edit_control* const control);
 
 private:
-	u32		m_dik;
-	bool	m_translate;
-	char	m_char;
-	char	m_char_shift;
+    u32 m_dik;
+    bool m_translate;
+    char m_char;
+    char m_char_shift;
 
 }; // class type_pair
 
@@ -70,13 +70,13 @@ class type_pair : public base
 class key_state_base : public base
 {
 public:
-					key_state_base	( key_state state, base* type_pair );
-	virtual			~key_state_base	();
-	virtual	void	on_key_press	( line_edit_control* const control );
+    key_state_base(key_state state, base* type_pair);
+    virtual ~key_state_base();
+    virtual void on_key_press(line_edit_control* const control);
 
 private:
-	key_state		m_state;
-	base*			m_type_pair;
+    key_state m_state;
+    base* m_type_pair;
 }; // class key_state_base
 
 } // namespace text_editor
diff --git a/src/xrEngine/editor_environment_ambients_ambient.cpp b/src/xrEngine/editor_environment_ambients_ambient.cpp
index 768531acf88..7a14d5470f3 100644
--- a/src/xrEngine/editor_environment_ambients_ambient.cpp
+++ b/src/xrEngine/editor_environment_ambients_ambient.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_ambients_ambient.cpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment ambients ambient class
+// Module : editor_environment_ambients_ambient.cpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment ambients ambient class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -26,247 +26,253 @@ using editor::environment::sound_channels::channel;
 using editor::environment::effects::effect;
 
 template <>
-void property_collection::display_name	(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
+void property_collection::display_name(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
 {
-	xr_strcpy				(buffer, buffer_size, m_container[item_index]->id().c_str());
+    xr_strcpy(buffer, buffer_size, m_container[item_index]->id().c_str());
 }
 
 template <>
-editor::property_holder* property_collection::create	()
+editor::property_holder* property_collection::create()
 {
-	effect_id*				object = xr_new(m_holder.effects_manager(), "");
-	object->fill			(this);
-	return					(object->object());
+    effect_id* object = xr_new(m_holder.effects_manager(), "");
+    object->fill(this);
+    return (object->object());
 }
 
 template <>
-void property_collection::display_name	(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
+void property_collection::display_name(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
 {
-	xr_strcpy				(buffer, buffer_size, m_container[item_index]->id().c_str());
+    xr_strcpy(buffer, buffer_size, m_container[item_index]->id().c_str());
 }
 
 template <>
-editor::property_holder* property_collection::create	()
+editor::property_holder* property_collection::create()
 {
-	sound_id*				object = xr_new(m_holder.sounds_manager(), "");
-	object->fill			(this);
-	return					(object->object());
+    sound_id* object = xr_new(m_holder.sounds_manager(), "");
+    object->fill(this);
+    return (object->object());
 }
 
-ambient::ambient			(manager const& manager, shared_str const& id) :
-	m_manager				(manager),
-	m_property_holder		(0),
-	m_effects_collection	(0),
-	m_sounds_collection		(0)
+ambient::ambient(manager const& manager, shared_str const& id) :
+    m_manager(manager),
+    m_property_holder(0),
+    m_effects_collection(0),
+    m_sounds_collection(0)
 {
-	m_load_section			= id;
-	m_effects_collection	= xr_new(&m_effects_ids, this);
-	m_sounds_collection		= xr_new(&m_sound_channels_ids, this);
+    m_load_section = id;
+    m_effects_collection = xr_new(&m_effects_ids, this);
+    m_sounds_collection = xr_new(&m_sound_channels_ids, this);
 }
 
-ambient::~ambient			()
+ambient::~ambient()
 {
-	delete_data				(m_effects_ids);
-	xr_delete				(m_effects_collection);
+    delete_data(m_effects_ids);
+    xr_delete(m_effects_collection);
 
-	delete_data				(m_sound_channels_ids);
-	xr_delete				(m_sounds_collection);
+    delete_data(m_sound_channels_ids);
+    xr_delete(m_sounds_collection);
 
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy			(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-void ambient::load			(
-		CInifile& ambients_config,
-		CInifile& sound_channels_config,
-		CInifile& effects_config,
-		const shared_str& section
-	)
+void ambient::load(
+    CInifile& ambients_config,
+    CInifile& sound_channels_config,
+    CInifile& effects_config,
+    const shared_str& section
+)
 {
-	VERIFY					(m_load_section == section);
-	inherited::load			(
-		ambients_config,
-		sound_channels_config,
-		effects_config,
-		m_load_section
-	);
-
-	{
-		VERIFY				(m_effects_ids.empty());
-		LPCSTR				effects_string = READ_IF_EXISTS(&ambients_config, r_string, m_load_section,	"effects", "");
-		for (u32 i=0, n=_GetItemCount(effects_string); i( m_manager.effects_manager(), _GetItem( effects_string, i, temp ) );
-			object->fill	(m_effects_collection);
-			m_effects_ids.push_back	(object);
-		}
-	}
-
-	{
-		VERIFY				(m_sound_channels_ids.empty());
-		LPCSTR				sounds_string = READ_IF_EXISTS(&ambients_config, r_string, m_load_section,	"sound_channels", "");
-		for (u32 i=0, n=_GetItemCount(sounds_string); i( m_manager.sounds_manager(), _GetItem( sounds_string, i, temp ) );
-			object->fill	(m_sounds_collection);
-			m_sound_channels_ids.push_back	(object);
-		}
-	}
+    VERIFY(m_load_section == section);
+    inherited::load(
+        ambients_config,
+        sound_channels_config,
+        effects_config,
+        m_load_section
+    );
+
+    {
+        VERIFY(m_effects_ids.empty());
+        LPCSTR effects_string = READ_IF_EXISTS(&ambients_config, r_string, m_load_section, "effects", "");
+        for (u32 i = 0, n = _GetItemCount(effects_string); i < n; ++i)
+        {
+            string_path temp;
+            effect_id* object = xr_new(m_manager.effects_manager(), _GetItem(effects_string, i, temp));
+            object->fill(m_effects_collection);
+            m_effects_ids.push_back(object);
+        }
+    }
+
+    {
+        VERIFY(m_sound_channels_ids.empty());
+        LPCSTR sounds_string = READ_IF_EXISTS(&ambients_config, r_string, m_load_section, "sound_channels", "");
+        for (u32 i = 0, n = _GetItemCount(sounds_string); i < n; ++i)
+        {
+            string_path temp;
+            sound_id* object = xr_new(m_manager.sounds_manager(), _GetItem(sounds_string, i, temp));
+            object->fill(m_sounds_collection);
+            m_sound_channels_ids.push_back(object);
+        }
+    }
 }
 
-void ambient::save			(CInifile& config)
+void ambient::save(CInifile& config)
 {
-	u32						count = 1;
-	LPSTR					temp = 0;
-	{
-		sound_container_type::const_iterator	b = m_sound_channels_ids.begin(), i = b;
-		sound_container_type::const_iterator	e = m_sound_channels_ids.end();
-		for ( ; i != e; ++i)
-			count			+= (*i)->id().size() + 2;
-
-		temp				= (LPSTR)_alloca(count*sizeof(char));
-		*temp				= 0;
-		for (i = b; i != e; ++i) {
-			if (i == b) {
-				xr_strcpy	(temp, count, (*i)->id().c_str());
-				continue;
-			}
-
-			xr_strcat		(temp, count, ", ");
-			xr_strcat		(temp, count, (*i)->id().c_str());
-		}
-	}
-
-	config.w_string			(m_load_section.c_str(), "sound_channels",	  temp);
-	config.w_float			(m_load_section.c_str(), "min_effect_period", float(m_effect_period.x)/1000.f);
-	config.w_float			(m_load_section.c_str(), "max_effect_period", float(m_effect_period.y)/1000.f);
-
-	{
-		count				= 1;
-		effect_container_type::const_iterator	b = m_effects_ids.begin(), i = b;
-		effect_container_type::const_iterator	e = m_effects_ids.end();
-		for ( ; i != e; ++i)
-			count			+= (*i)->id().size() + 2;
-
-		temp				= (LPSTR)_alloca(count*sizeof(char));
-		*temp				= 0;
-		for (i = b; i != e; ++i) {
-			if (i == b) {
-				xr_strcpy	(temp, count, (*i)->id().c_str());
-				continue;
-			}
-
-			xr_strcat		(temp, count, ", ");
-			xr_strcat		(temp, count, (*i)->id().c_str());
-		}
-	}
-	config.w_string			(m_load_section.c_str(), "effects", temp);
+    u32 count = 1;
+    LPSTR temp = 0;
+    {
+        sound_container_type::const_iterator b = m_sound_channels_ids.begin(), i = b;
+        sound_container_type::const_iterator e = m_sound_channels_ids.end();
+        for (; i != e; ++i)
+            count += (*i)->id().size() + 2;
+
+        temp = (LPSTR)_alloca(count*sizeof(char));
+        *temp = 0;
+        for (i = b; i != e; ++i)
+        {
+            if (i == b)
+            {
+                xr_strcpy(temp, count, (*i)->id().c_str());
+                continue;
+            }
+
+            xr_strcat(temp, count, ", ");
+            xr_strcat(temp, count, (*i)->id().c_str());
+        }
+    }
+
+    config.w_string(m_load_section.c_str(), "sound_channels", temp);
+    config.w_float(m_load_section.c_str(), "min_effect_period", float(m_effect_period.x) / 1000.f);
+    config.w_float(m_load_section.c_str(), "max_effect_period", float(m_effect_period.y) / 1000.f);
+
+    {
+        count = 1;
+        effect_container_type::const_iterator b = m_effects_ids.begin(), i = b;
+        effect_container_type::const_iterator e = m_effects_ids.end();
+        for (; i != e; ++i)
+            count += (*i)->id().size() + 2;
+
+        temp = (LPSTR)_alloca(count*sizeof(char));
+        *temp = 0;
+        for (i = b; i != e; ++i)
+        {
+            if (i == b)
+            {
+                xr_strcpy(temp, count, (*i)->id().c_str());
+                continue;
+            }
+
+            xr_strcat(temp, count, ", ");
+            xr_strcat(temp, count, (*i)->id().c_str());
+        }
+    }
+    config.w_string(m_load_section.c_str(), "effects", temp);
 }
 
-LPCSTR ambient::id_getter						() const
+LPCSTR ambient::id_getter() const
 {
-	return					(m_load_section.c_str());
+    return (m_load_section.c_str());
 }
 
-void ambient::id_setter							(LPCSTR value_)
+void ambient::id_setter(LPCSTR value_)
 {
-	shared_str				value = value_;
-	if (m_load_section._get() == value._get())
-		return;
+    shared_str value = value_;
+    if (m_load_section._get() == value._get())
+        return;
 
-	m_load_section			= m_manager.unique_id(value);
+    m_load_section = m_manager.unique_id(value);
 }
 
-void ambient::fill			(editor::property_holder_collection* collection)
+void ambient::fill(editor::property_holder_collection* collection)
 {
-	VERIFY					(!m_property_holder);
-	m_property_holder		= ::ide().create_property_holder(m_load_section.c_str(), collection, this);
-
-	typedef editor::property_holder::string_getter_type	string_getter_type;
-	string_getter_type				string_getter;
-	string_getter.bind				(this, &ambient::id_getter);
-
-	typedef editor::property_holder::string_setter_type	string_setter_type;
-	string_setter_type				string_setter;
-	string_setter.bind				(this, &ambient::id_setter);
-
-	m_property_holder->add_property	(
-		"id",
-		"properties",
-		"this option is resposible for ambient identifier",
-		m_load_section.c_str(),
-		string_getter,
-		string_setter
-	);
-	m_property_holder->add_property	(
-		"minimum period",
-		"effects",
-		"this option is resposible for minimum effect period (in seconds)",
-		m_effect_period.x,
-		m_effect_period.x
-	);
-	m_property_holder->add_property	(
-		"maximum period",
-		"effects",
-		"this option is resposible for maximum effect period (in seconds)",
-		m_effect_period.y,
-		m_effect_period.y
-	);
-	m_property_holder->add_property	(
-		"effects",
-		"effects",
-		"this option is resposible for maximum effects",
-		m_effects_collection
-	);
-	m_property_holder->add_property	(
-		"sound channels",
-		"sounds",
-		"this option is resposible for sound channels",
-		m_sounds_collection
-	);
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder(m_load_section.c_str(), collection, this);
+
+    typedef editor::property_holder::string_getter_type string_getter_type;
+    string_getter_type string_getter;
+    string_getter.bind(this, &ambient::id_getter);
+
+    typedef editor::property_holder::string_setter_type string_setter_type;
+    string_setter_type string_setter;
+    string_setter.bind(this, &ambient::id_setter);
+
+    m_property_holder->add_property(
+        "id",
+        "properties",
+        "this option is resposible for ambient identifier",
+        m_load_section.c_str(),
+        string_getter,
+        string_setter
+    );
+    m_property_holder->add_property(
+        "minimum period",
+        "effects",
+        "this option is resposible for minimum effect period (in seconds)",
+        m_effect_period.x,
+        m_effect_period.x
+    );
+    m_property_holder->add_property(
+        "maximum period",
+        "effects",
+        "this option is resposible for maximum effect period (in seconds)",
+        m_effect_period.y,
+        m_effect_period.y
+    );
+    m_property_holder->add_property(
+        "effects",
+        "effects",
+        "this option is resposible for maximum effects",
+        m_effects_collection
+    );
+    m_property_holder->add_property(
+        "sound channels",
+        "sounds",
+        "this option is resposible for sound channels",
+        m_sounds_collection
+    );
 }
 
-ambient::property_holder_type* ambient::object	()
+ambient::property_holder_type* ambient::object()
 {
-	return					(m_property_holder);
+    return (m_property_holder);
 }
 
-::editor::environment::effects::manager const& ambient::effects_manager		() const
+::editor::environment::effects::manager const& ambient::effects_manager() const
 {
-	return					(m_manager.effects_manager());
+    return (m_manager.effects_manager());
 }
 
-::editor::environment::sound_channels::manager const& ambient::sounds_manager	() const
+::editor::environment::sound_channels::manager const& ambient::sounds_manager() const
 {
-	return					(m_manager.sounds_manager());
+    return (m_manager.sounds_manager());
 }
 
-ambient::SEffect* ambient::create_effect			(CInifile& config, LPCSTR id)
+ambient::SEffect* ambient::create_effect(CInifile& config, LPCSTR id)
 {
-	effect*					result = xr_new(m_manager.effects_manager(), id);
-	result->load			(config);
-	result->fill			(m_effects_collection);
-	return					(result);
+    effect* result = xr_new(m_manager.effects_manager(), id);
+    result->load(config);
+    result->fill(m_effects_collection);
+    return (result);
 }
 
-ambient::SSndChannel* ambient::create_sound_channel	(CInifile& config, LPCSTR id)
+ambient::SSndChannel* ambient::create_sound_channel(CInifile& config, LPCSTR id)
 {
-	channel*				result = xr_new(m_manager.sounds_manager(), id);
-	result->load			(config);
-	result->fill			(m_sounds_collection);
-	return					(result);
+    channel* result = xr_new(m_manager.sounds_manager(), id);
+    result->load(config);
+    result->fill(m_sounds_collection);
+    return (result);
 }
 
-CEnvAmbient::EffectVec& ambient::effects							()
+CEnvAmbient::EffectVec& ambient::effects()
 {
-	return					(inherited::effects());
+    return (inherited::effects());
 }
 
-CEnvAmbient::SSndChannelVec& ambient::get_snd_channels			()
+CEnvAmbient::SSndChannelVec& ambient::get_snd_channels()
 {
-	return					(inherited::get_snd_channels());
+    return (inherited::get_snd_channels());
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_ambients_ambient.hpp b/src/xrEngine/editor_environment_ambients_ambient.hpp
index 8c34d518141..b606f3b02fe 100644
--- a/src/xrEngine/editor_environment_ambients_ambient.hpp
+++ b/src/xrEngine/editor_environment_ambients_ambient.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_ambients_ambient.hpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment ambients ambient class
+// Module : editor_environment_ambients_ambient.hpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment ambients ambient class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_AMBIENTS_AMBIENT_HPP_INCLUDED
@@ -16,86 +16,91 @@
 #include "property_collection_forward.hpp"
 #include "environment.h"
 
-namespace editor {
-namespace environment {
+namespace editor
+{
+namespace environment
+{
 
-	namespace effects {
-		class manager;
-	} // namespace effects
+namespace effects
+{
+class manager;
+} // namespace effects
 
-	namespace sound_channels {
-		class manager;
-	} // namespace sound_channels
+namespace sound_channels
+{
+class manager;
+} // namespace sound_channels
 
-namespace ambients {
+namespace ambients
+{
 
 class manager;
 class effect_id;
 class sound_id;
 
 class ambient :
-	public CEnvAmbient,
-	public editor::property_holder_holder,
-	private boost::noncopyable
+    public CEnvAmbient,
+    public editor::property_holder_holder,
+    private boost::noncopyable
 {
 private:
-	typedef CEnvAmbient		inherited;
+    typedef CEnvAmbient inherited;
 
 public:
-							ambient				(manager const& manager, shared_str const& id);
-	virtual					~ambient			();
-	virtual	void			load				(
-								CInifile& ambients_config,
-								CInifile& sound_channels_config,
-								CInifile& effects_config,
-								const shared_str& section
-							);
-			void			save				(CInifile& config);
-			void			fill				(editor::property_holder_collection* collection);
-	inline	shared_str const& id				() const { return m_load_section; }
-	virtual	SEffect*		create_effect		(CInifile& config, LPCSTR id);
-	virtual	SSndChannel*	create_sound_channel(CInifile& config, LPCSTR id);
-	virtual	EffectVec&		effects				();
-	virtual	SSndChannelVec&	get_snd_channels	();
+    ambient(manager const& manager, shared_str const& id);
+    virtual ~ambient();
+    virtual void load(
+        CInifile& ambients_config,
+        CInifile& sound_channels_config,
+        CInifile& effects_config,
+        const shared_str& section
+    );
+    void save(CInifile& config);
+    void fill(editor::property_holder_collection* collection);
+    inline shared_str const& id() const { return m_load_section; }
+    virtual SEffect* create_effect(CInifile& config, LPCSTR id);
+    virtual SSndChannel* create_sound_channel(CInifile& config, LPCSTR id);
+    virtual EffectVec& effects();
+    virtual SSndChannelVec& get_snd_channels();
 
 private:
-			LPCSTR xr_stdcall id_getter	() const;
-			void xr_stdcall id_setter	(LPCSTR value);
+    LPCSTR xr_stdcall id_getter() const;
+    void xr_stdcall id_setter(LPCSTR value);
 
 public:
-	effects::manager const&			effects_manager	() const;
-	sound_channels::manager const&	sounds_manager	() const;
+    effects::manager const& effects_manager() const;
+    sound_channels::manager const& sounds_manager() const;
 
 public:
-	typedef xr_vector		effect_container_type;
-	typedef property_collection<
-				effect_container_type,
-				ambient
-			>							effect_collection_type;
+    typedef xr_vector effect_container_type;
+    typedef property_collection <
+    effect_container_type,
+    ambient
+    > effect_collection_type;
 
 public:
-	typedef xr_vector		sound_container_type;
-	typedef property_collection<
-				sound_container_type,
-				ambient
-			>							sound_collection_type;
+    typedef xr_vector sound_container_type;
+    typedef property_collection <
+    sound_container_type,
+    ambient
+    > sound_collection_type;
 
 private:
-	typedef editor::property_holder		property_holder_type;
+    typedef editor::property_holder property_holder_type;
 
 public:
-	virtual	property_holder_type* object();
+    virtual property_holder_type* object();
 
 private:
-	CInifile*							m_config;
-	property_holder_type*				m_property_holder;
-	manager const&						m_manager;
+    CInifile* m_config;
+    property_holder_type* m_property_holder;
+    manager const& m_manager;
 
-	effect_collection_type*				m_effects_collection;
-	effect_container_type				m_effects_ids;
+    effect_collection_type* m_effects_collection;
+    effect_container_type m_effects_ids;
 
-	sound_collection_type*				m_sounds_collection;
-	sound_container_type				m_sound_channels_ids;
+    sound_collection_type* m_sounds_collection;
+    sound_container_type m_sound_channels_ids;
 }; // class ambient
 } // namespace ambients
 } // namespace environment
diff --git a/src/xrEngine/editor_environment_ambients_effect_id.cpp b/src/xrEngine/editor_environment_ambients_effect_id.cpp
index b53390fe301..7da0a653990 100644
--- a/src/xrEngine/editor_environment_ambients_effect_id.cpp
+++ b/src/xrEngine/editor_environment_ambients_effect_id.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_ambients_effect_id.cpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment ambients effect identifier class
+// Module : editor_environment_ambients_effect_id.cpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment ambients effect identifier class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -16,63 +16,63 @@
 using editor::environment::ambients::effect_id;
 using editor::environment::effects::manager;
 
-effect_id::effect_id								(
-		manager const& manager,
-		shared_str const& id
-	) :
-	m_manager						(manager),
-	m_id							(id),
-	m_property_holder				(0)
+effect_id::effect_id(
+    manager const& manager,
+    shared_str const& id
+) :
+    m_manager(manager),
+    m_id(id),
+    m_property_holder(0)
 {
 }
 
-effect_id::~effect_id								()
+effect_id::~effect_id()
 {
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy					(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-LPCSTR const* effect_id::collection					()
+LPCSTR const* effect_id::collection()
 {
-	return							(&*m_manager.effects_ids().begin());
+    return (&*m_manager.effects_ids().begin());
 }
 
-u32 effect_id::collection_size						()
+u32 effect_id::collection_size()
 {
-	return							(m_manager.effects_ids().size());
+    return (m_manager.effects_ids().size());
 }
 
-void effect_id::fill								(editor::property_holder_collection* collection)
+void effect_id::fill(editor::property_holder_collection* collection)
 {
-	VERIFY							(!m_property_holder);
-	m_property_holder				= ::ide().create_property_holder(m_id.c_str(), collection, this);
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder(m_id.c_str(), collection, this);
 
-	typedef editor::property_holder::string_collection_getter_type	collection_getter_type;
-	collection_getter_type			collection_getter;
-	collection_getter.bind			(this, &effect_id::collection);
+    typedef editor::property_holder::string_collection_getter_type collection_getter_type;
+    collection_getter_type collection_getter;
+    collection_getter.bind(this, &effect_id::collection);
 
-	typedef editor::property_holder::string_collection_size_getter_type	collection_size_getter_type;
-	collection_size_getter_type		collection_size_getter;
-	collection_size_getter.bind		(this, &effect_id::collection_size);
+    typedef editor::property_holder::string_collection_size_getter_type collection_size_getter_type;
+    collection_size_getter_type collection_size_getter;
+    collection_size_getter.bind(this, &effect_id::collection_size);
 
-	m_property_holder->add_property	(
-		"effect",
-		"properties",
-		"this option is resposible for effect",
-		m_id.c_str(),
-		m_id,
-		collection_getter,
-		collection_size_getter,
-		editor::property_holder::value_editor_combo_box,
-		editor::property_holder::cannot_enter_text
-	);
+    m_property_holder->add_property(
+        "effect",
+        "properties",
+        "this option is resposible for effect",
+        m_id.c_str(),
+        m_id,
+        collection_getter,
+        collection_size_getter,
+        editor::property_holder::value_editor_combo_box,
+        editor::property_holder::cannot_enter_text
+    );
 }
 
-effect_id::property_holder_type* effect_id::object	()
+effect_id::property_holder_type* effect_id::object()
 {
-	return							(m_property_holder);
+    return (m_property_holder);
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_ambients_effect_id.hpp b/src/xrEngine/editor_environment_ambients_effect_id.hpp
index 1e94551df82..575196d7b42 100644
--- a/src/xrEngine/editor_environment_ambients_effect_id.hpp
+++ b/src/xrEngine/editor_environment_ambients_effect_id.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_ambients_effect_id.hpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment ambients effect identifier class
+// Module : editor_environment_ambients_effect_id.hpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment ambients effect identifier class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_AMBIENTS_EFFECT_ID_HPP_INCLUDED
@@ -14,40 +14,45 @@
 #include 
 #include "../include/editor/property_holder.hpp"
 
-namespace editor {
+namespace editor
+{
 
 class property_holder_collection;
 
-namespace environment {
-	namespace effects {
-		class manager;
-	} // namespace effects
+namespace environment
+{
+namespace effects
+{
+class manager;
+} // namespace effects
 
-namespace ambients {
+namespace ambients
+{
 
 class effect_id :
-	public editor::property_holder_holder,
-	private boost::noncopyable {
+    public editor::property_holder_holder,
+    private boost::noncopyable
+{
 public:
-							effect_id		(effects::manager const& manager, shared_str const& id);
-	virtual					~effect_id		();
-			void			fill			(editor::property_holder_collection* collection);
-	inline	shared_str const& id			() const { return m_id; }
+    effect_id(effects::manager const& manager, shared_str const& id);
+    virtual ~effect_id();
+    void fill(editor::property_holder_collection* collection);
+    inline shared_str const& id() const { return m_id; }
 
 private:
-	typedef editor::property_holder			property_holder_type;
+    typedef editor::property_holder property_holder_type;
 
 public:
-	virtual	property_holder_type* object	();
+    virtual property_holder_type* object();
 
 private:
-	LPCSTR const* xr_stdcall collection		();
-	u32  xr_stdcall			collection_size	();
+    LPCSTR const* xr_stdcall collection();
+    u32 xr_stdcall collection_size();
 
 private:
-	property_holder_type*	m_property_holder;
-	effects::manager const&	m_manager;
-	shared_str				m_id;
+    property_holder_type* m_property_holder;
+    effects::manager const& m_manager;
+    shared_str m_id;
 }; // class effect_id
 } // namespace ambients
 } // namespace environment
diff --git a/src/xrEngine/editor_environment_ambients_manager.cpp b/src/xrEngine/editor_environment_ambients_manager.cpp
index 50b5b4c3604..0f2fd8a4529 100644
--- a/src/xrEngine/editor_environment_ambients_manager.cpp
+++ b/src/xrEngine/editor_environment_ambients_manager.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_ambients_manager.cpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment ambients manager class
+// Module : editor_environment_ambients_manager.cpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment ambients manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -21,147 +21,148 @@ using editor::environment::ambients::ambient;
 using editor::environment::detail::logical_string_predicate;
 
 template <>
-void property_collection::display_name	(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
+void property_collection::display_name(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
 {
-	xr_strcpy				(buffer, buffer_size, m_container[item_index]->id().c_str());
+    xr_strcpy(buffer, buffer_size, m_container[item_index]->id().c_str());
 }
 
 template <>
-editor::property_holder* property_collection::create	()
+editor::property_holder* property_collection::create()
 {
-	ambient*				object = xr_new(m_holder, generate_unique_id("ambient_unique_id_").c_str());
-	object->fill			(this);
-	return					(object->object());
+    ambient* object = xr_new(m_holder, generate_unique_id("ambient_unique_id_").c_str());
+    object->fill(this);
+    return (object->object());
 }
 
-manager::manager			(::editor::environment::manager const& manager) :
-	m_manager				(manager),
-	m_property_holder		(0),
-	m_collection			(0),
-	m_changed				(true)
+manager::manager(::editor::environment::manager const& manager) :
+    m_manager(manager),
+    m_property_holder(0),
+    m_collection(0),
+    m_changed(true)
 {
-	m_collection			= xr_new(&m_ambients, this, &m_changed);
+    m_collection = xr_new(&m_ambients, this, &m_changed);
 }
 
-manager::~manager			()
+manager::~manager()
 {
-	xr_delete				(m_collection);
-	delete_data				(m_ambients);
-	delete_data				(m_ambients_ids);
+    xr_delete(m_collection);
+    delete_data(m_ambients);
+    delete_data(m_ambients_ids);
 
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy			(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-void manager::load			()
+void manager::load()
 {
-	VERIFY					(m_ambients.empty());
-
-	typedef CInifile::Root	sections_type;
-	sections_type&			sections = m_manager.m_ambients_config->sections();
-	m_ambients.reserve		(sections.size());
-	sections_type::const_iterator	i = sections.begin();
-	sections_type::const_iterator	e = sections.end();
-	for ( ; i != e; ++i) {
-		ambient*			object = xr_new(*this, (*i)->Name);
-		object->load		(
-			*m_manager.m_ambients_config,
-			*m_manager.m_sound_channels_config,
-			*m_manager.m_effects_config,
-			(*i)->Name
-		);
-		object->fill		(m_collection);
-		m_ambients.push_back(object);
-	}
+    VERIFY(m_ambients.empty());
+
+    typedef CInifile::Root sections_type;
+    sections_type& sections = m_manager.m_ambients_config->sections();
+    m_ambients.reserve(sections.size());
+    sections_type::const_iterator i = sections.begin();
+    sections_type::const_iterator e = sections.end();
+    for (; i != e; ++i)
+    {
+        ambient* object = xr_new(*this, (*i)->Name);
+        object->load(
+            *m_manager.m_ambients_config,
+            *m_manager.m_sound_channels_config,
+            *m_manager.m_effects_config,
+            (*i)->Name
+        );
+        object->fill(m_collection);
+        m_ambients.push_back(object);
+    }
 }
 
-void manager::save			()
+void manager::save()
 {
-	string_path				file_name;
-	CInifile*				config =
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\ambients.ltx"
-			),
-			FALSE,
-			FALSE,
-			TRUE
-		);
-
-	ambient_container_type::iterator	i = m_ambients.begin();
-	ambient_container_type::iterator	e = m_ambients.end();
-	for ( ; i != e; ++i)
-		(*i)->save			(*config);
-
-	xr_delete				(config);
+    string_path file_name;
+    CInifile* config =
+        xr_new(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "environment\\ambients.ltx"
+            ),
+            FALSE,
+            FALSE,
+            TRUE
+        );
+
+    ambient_container_type::iterator i = m_ambients.begin();
+    ambient_container_type::iterator e = m_ambients.end();
+    for (; i != e; ++i)
+        (*i)->save(*config);
+
+    xr_delete(config);
 }
 
-void manager::fill			(editor::property_holder* holder)
+void manager::fill(editor::property_holder* holder)
 {
-	VERIFY					(holder);
-	holder->add_property	(
-		"ambients",
-		"ambients",
-		"this option is resposible for ambients",
-		m_collection
-	);
+    VERIFY(holder);
+    holder->add_property(
+        "ambients",
+        "ambients",
+        "this option is resposible for ambients",
+        m_collection
+    );
 }
 
-::editor::environment::effects::manager const& manager::effects_manager		() const
+::editor::environment::effects::manager const& manager::effects_manager() const
 {
-	return					(m_manager.effects());
+    return (m_manager.effects());
 }
 
-::editor::environment::sound_channels::manager const& manager::sounds_manager	() const
+::editor::environment::sound_channels::manager const& manager::sounds_manager() const
 {
-	return					(m_manager.sound_channels());
+    return (m_manager.sound_channels());
 }
 
-shared_str manager::unique_id	(shared_str const& id) const
+shared_str manager::unique_id(shared_str const& id) const
 {
-	if (m_collection->unique_id(id.c_str()))
-		return				(id);
+    if (m_collection->unique_id(id.c_str()))
+        return (id);
 
-	return					(m_collection->generate_unique_id(id.c_str()));
+    return (m_collection->generate_unique_id(id.c_str()));
 }
 
-manager::ambients_ids_type const& manager::ambients_ids	() const
+manager::ambients_ids_type const& manager::ambients_ids() const
 {
-	if (!m_changed)
-		return				(m_ambients_ids);
+    if (!m_changed)
+        return (m_ambients_ids);
 
-	m_changed				= false;
+    m_changed = false;
 
-	delete_data				(m_ambients_ids);
+    delete_data(m_ambients_ids);
 
-	m_ambients_ids.resize	(m_ambients.size());
+    m_ambients_ids.resize(m_ambients.size());
 
-	ambient_container_type::const_iterator	i = m_ambients.begin();
-	ambient_container_type::const_iterator	e = m_ambients.end();
-	ambients_ids_type::iterator				j = m_ambients_ids.begin();
-	for ( ; i != e; ++i, ++j)
-		*j					= xr_strdup((*i)->id().c_str());
+    ambient_container_type::const_iterator i = m_ambients.begin();
+    ambient_container_type::const_iterator e = m_ambients.end();
+    ambients_ids_type::iterator j = m_ambients_ids.begin();
+    for (; i != e; ++i, ++j)
+        *j = xr_strdup((*i)->id().c_str());
 
-	std::sort				(m_ambients_ids.begin(), m_ambients_ids.end(), logical_string_predicate());
+    std::sort(m_ambients_ids.begin(), m_ambients_ids.end(), logical_string_predicate());
 
-	return					(m_ambients_ids);
+    return (m_ambients_ids);
 }
 
-ambient* manager::get_ambient							(shared_str const& id) const
+ambient* manager::get_ambient(shared_str const& id) const
 {
-	ambient_container_type::const_iterator	i = m_ambients.begin();
-	ambient_container_type::const_iterator	e = m_ambients.end();
-	for ( ; i != e; ++i)
-		if ((*i)->id() == id)
-			return			(*i);
+    ambient_container_type::const_iterator i = m_ambients.begin();
+    ambient_container_type::const_iterator e = m_ambients.end();
+    for (; i != e; ++i)
+        if ((*i)->id() == id)
+            return (*i);
 
-	NODEFAULT;
+    NODEFAULT;
 #ifdef DEBUG
-	return					(0);
+    return (0);
 #endif // #ifdef DEBUG
 }
 
diff --git a/src/xrEngine/editor_environment_ambients_manager.hpp b/src/xrEngine/editor_environment_ambients_manager.hpp
index b4c53548d4e..f2c354f70e2 100644
--- a/src/xrEngine/editor_environment_ambients_manager.hpp
+++ b/src/xrEngine/editor_environment_ambients_manager.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_ambients_manager.hpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment ambients manager class
+// Module : editor_environment_ambients_manager.hpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment ambients manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_AMBIENTS_MANAGER_HPP_INCLUDED
@@ -14,61 +14,67 @@
 #include 
 #include "property_collection_forward.hpp"
 
-namespace editor {
+namespace editor
+{
 
-	class property_holder;
+class property_holder;
 
-namespace environment {
+namespace environment
+{
 
-	class manager;
+class manager;
 
-	namespace effects {
-		class manager;
-	} // namespace effects
-	
-	namespace sound_channels {
-		class manager;
-	} // namespace sound_channels
+namespace effects
+{
+class manager;
+} // namespace effects
 
-namespace ambients {
+namespace sound_channels
+{
+class manager;
+} // namespace sound_channels
+
+namespace ambients
+{
 
 class ambient;
 
-class manager : private boost::noncopyable {
+class manager : private boost::noncopyable
+{
 public:
-							manager			(::editor::environment::manager const& manager);
-							~manager		();
-			void			load			();
-			void			save			();
-			void			fill			(editor::property_holder* holder);
-			shared_str		unique_id		(shared_str const& id) const;
-			ambient*		get_ambient		(shared_str const& id) const;
+    manager(::editor::environment::manager const& manager);
+    ~manager();
+    void load();
+    void save();
+    void fill(editor::property_holder* holder);
+    shared_str unique_id(shared_str const& id) const;
+    ambient* get_ambient(shared_str const& id) const;
 
 public:
-	effects::manager const&			effects_manager	() const;
-	sound_channels::manager const&	sounds_manager	() const;
+    effects::manager const& effects_manager() const;
+    sound_channels::manager const& sounds_manager() const;
 
 public:
-	typedef xr_vector				ambient_container_type;
-	typedef xr_vector				ambients_ids_type;
+    typedef xr_vector ambient_container_type;
+    typedef xr_vector ambients_ids_type;
 
 public:
-	ambients_ids_type const& ambients_ids	() const;
+    ambients_ids_type const& ambients_ids() const;
 
 private:
-	typedef editor::property_holder			property_holder_type;
-	typedef property_collection<
-				ambient_container_type,
-				manager
-			>								collection_type;
+    typedef editor::property_holder property_holder_type;
+    typedef property_collection <
+    ambient_container_type,
+    manager
+    > collection_type;
 
 private:
-	ambient_container_type					m_ambients;
-	mutable ambients_ids_type				m_ambients_ids;
-	::editor::environment::manager const&	m_manager;
-	property_holder_type*					m_property_holder;
-	collection_type*						m_collection;
-	mutable bool							m_changed;
+    ambient_container_type m_ambients;
+    mutable ambients_ids_type m_ambients_ids;
+    ::editor::environment::manager const& m_manager;
+    property_holder_type* m_property_holder;
+    collection_type* m_collection;
+    mutable bool m_changed;
 }; // class manager
 } // namespace ambients
 } // namespace environment
diff --git a/src/xrEngine/editor_environment_ambients_sound_id.cpp b/src/xrEngine/editor_environment_ambients_sound_id.cpp
index 4e7cb13e204..8e4b2ee4e6a 100644
--- a/src/xrEngine/editor_environment_ambients_sound_id.cpp
+++ b/src/xrEngine/editor_environment_ambients_sound_id.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_ambients_sound_id.cpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment ambients sound identifier class
+// Module : editor_environment_ambients_sound_id.cpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment ambients sound identifier class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -16,60 +16,60 @@
 using editor::environment::ambients::sound_id;
 using editor::environment::sound_channels::manager;
 
-sound_id::sound_id			(manager const& manager, shared_str const& id) :
-	m_manager						(manager),
-	m_id							(id),
-	m_property_holder				(0)
+sound_id::sound_id(manager const& manager, shared_str const& id) :
+    m_manager(manager),
+    m_id(id),
+    m_property_holder(0)
 {
 }
 
-sound_id::~sound_id			()
+sound_id::~sound_id()
 {
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy					(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-LPCSTR const* sound_id::collection					()
+LPCSTR const* sound_id::collection()
 {
-	return							(&*m_manager.channels_ids().begin());
+    return (&*m_manager.channels_ids().begin());
 }
 
-u32 sound_id::collection_size						()
+u32 sound_id::collection_size()
 {
-	return							(m_manager.channels_ids().size());
+    return (m_manager.channels_ids().size());
 }
 
-void sound_id::fill			(editor::property_holder_collection* collection)
+void sound_id::fill(editor::property_holder_collection* collection)
 {
-	VERIFY							(!m_property_holder);
-	m_property_holder				= ::ide().create_property_holder(m_id.c_str(), collection, this);
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder(m_id.c_str(), collection, this);
 
-	typedef editor::property_holder::string_collection_getter_type	collection_getter_type;
-	collection_getter_type			collection_getter;
-	collection_getter.bind			(this, &sound_id::collection);
+    typedef editor::property_holder::string_collection_getter_type collection_getter_type;
+    collection_getter_type collection_getter;
+    collection_getter.bind(this, &sound_id::collection);
 
-	typedef editor::property_holder::string_collection_size_getter_type	collection_size_getter_type;
-	collection_size_getter_type		collection_size_getter;
-	collection_size_getter.bind		(this, &sound_id::collection_size);
+    typedef editor::property_holder::string_collection_size_getter_type collection_size_getter_type;
+    collection_size_getter_type collection_size_getter;
+    collection_size_getter.bind(this, &sound_id::collection_size);
 
-	m_property_holder->add_property	(
-		"sound channel",
-		"properties",
-		"this option is resposible for sound",
-		m_id.c_str(),
-		m_id,
-		collection_getter,
-		collection_size_getter,
-		editor::property_holder::value_editor_combo_box,
-		editor::property_holder::cannot_enter_text
-	);
+    m_property_holder->add_property(
+        "sound channel",
+        "properties",
+        "this option is resposible for sound",
+        m_id.c_str(),
+        m_id,
+        collection_getter,
+        collection_size_getter,
+        editor::property_holder::value_editor_combo_box,
+        editor::property_holder::cannot_enter_text
+    );
 }
 
-sound_id::property_holder_type* sound_id::object	()
+sound_id::property_holder_type* sound_id::object()
 {
-	return							(m_property_holder);
+    return (m_property_holder);
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_ambients_sound_id.hpp b/src/xrEngine/editor_environment_ambients_sound_id.hpp
index e704a111878..18baf85b42c 100644
--- a/src/xrEngine/editor_environment_ambients_sound_id.hpp
+++ b/src/xrEngine/editor_environment_ambients_sound_id.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_ambients_sound_id.hpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment ambients sound identifier class
+// Module : editor_environment_ambients_sound_id.hpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment ambients sound identifier class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_AMBIENTS_SOUND_HPP_INCLUDED
@@ -14,40 +14,45 @@
 #include 
 #include "../include/editor/property_holder.hpp"
 
-namespace editor {
+namespace editor
+{
 
 class property_holder_collection;
 
-namespace environment {
-	namespace sound_channels {
-		class manager;
-	} // namespace sound_channels
+namespace environment
+{
+namespace sound_channels
+{
+class manager;
+} // namespace sound_channels
 
-namespace ambients {
+namespace ambients
+{
 
 class sound_id :
-	public editor::property_holder_holder,
-	private boost::noncopyable {
+    public editor::property_holder_holder,
+    private boost::noncopyable
+{
 public:
-							sound_id		(sound_channels::manager const& manager, shared_str const& sound);
-	virtual					~sound_id		();
-			void			fill			(editor::property_holder_collection* collection);
-	inline	shared_str const& id			() const { return m_id; }
+    sound_id(sound_channels::manager const& manager, shared_str const& sound);
+    virtual ~sound_id();
+    void fill(editor::property_holder_collection* collection);
+    inline shared_str const& id() const { return m_id; }
 
 private:
-	typedef editor::property_holder			property_holder_type;
+    typedef editor::property_holder property_holder_type;
 
 public:
-	virtual	property_holder_type* object	();
+    virtual property_holder_type* object();
 
 private:
-	LPCSTR const* xr_stdcall collection		();
-	u32  xr_stdcall			collection_size	();
+    LPCSTR const* xr_stdcall collection();
+    u32 xr_stdcall collection_size();
 
 private:
-	property_holder_type*					m_property_holder;
-	sound_channels::manager const&			m_manager;
-	shared_str								m_id;
+    property_holder_type* m_property_holder;
+    sound_channels::manager const& m_manager;
+    shared_str m_id;
 }; // class sound_id
 } // namespace ambients
 } // namespace environment
diff --git a/src/xrEngine/editor_environment_detail.cpp b/src/xrEngine/editor_environment_detail.cpp
index 13e4d0f3826..44e58f89132 100644
--- a/src/xrEngine/editor_environment_detail.cpp
+++ b/src/xrEngine/editor_environment_detail.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_detail.cpp
-//	Created 	: 11.01.2008
-//  Modified 	: 11.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment detail namespace
+// Module : editor_environment_detail.cpp
+// Created : 11.01.2008
+// Modified : 11.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment detail namespace
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -16,52 +16,52 @@
 
 using editor::environment::detail::logical_string_predicate;
 
-static HRESULT AnsiToUnicode						(LPCSTR pszA, LPVOID buffer, u32 const& buffer_size)
+static HRESULT AnsiToUnicode(LPCSTR pszA, LPVOID buffer, u32 const& buffer_size)
 {
-	VERIFY			(pszA);
-	VERIFY			(buffer);
-	VERIFY			(buffer_size);
+    VERIFY(pszA);
+    VERIFY(buffer);
+    VERIFY(buffer_size);
 
-	u32				cCharacters =  xr_strlen(pszA)+1;
-	VERIFY			(cCharacters*2 <= buffer_size);
+    u32 cCharacters = xr_strlen(pszA) + 1;
+    VERIFY(cCharacters * 2 <= buffer_size);
 
-	if (MultiByteToWideChar(CP_ACP, 0, pszA, cCharacters, (LPOLESTR)buffer, cCharacters))
-		return		(NOERROR);
+    if (MultiByteToWideChar(CP_ACP, 0, pszA, cCharacters, (LPOLESTR)buffer, cCharacters))
+        return (NOERROR);
 
-	return			(HRESULT_FROM_WIN32(GetLastError()));
+    return (HRESULT_FROM_WIN32(GetLastError()));
 }
 
-bool logical_string_predicate::operator()			(LPCSTR const& first, LPCSTR const& second) const
+bool logical_string_predicate::operator() (LPCSTR const& first, LPCSTR const& second) const
 {
-	u32				buffer_size0 = (xr_strlen(first) + 1)*2;
-	LPCWSTR			buffer0 = (LPCWSTR)_alloca(buffer_size0);
-	AnsiToUnicode	(first, (LPVOID)buffer0, buffer_size0);
+    u32 buffer_size0 = (xr_strlen(first) + 1) * 2;
+    LPCWSTR buffer0 = (LPCWSTR)_alloca(buffer_size0);
+    AnsiToUnicode(first, (LPVOID)buffer0, buffer_size0);
 
-	u32				buffer_size1 = (xr_strlen(second) + 1)*2;
-	LPCWSTR			buffer1 = (LPCWSTR)_alloca(buffer_size1);
-	AnsiToUnicode	(second, (LPVOID)buffer1, buffer_size1);
+    u32 buffer_size1 = (xr_strlen(second) + 1) * 2;
+    LPCWSTR buffer1 = (LPCWSTR)_alloca(buffer_size1);
+    AnsiToUnicode(second, (LPVOID)buffer1, buffer_size1);
 
-	return			(StrCmpLogicalW(buffer0, buffer1) < 0);
+    return (StrCmpLogicalW(buffer0, buffer1) < 0);
 }
 
-bool logical_string_predicate::operator()			(shared_str const& first, shared_str const& second) const
+bool logical_string_predicate::operator() (shared_str const& first, shared_str const& second) const
 {
-	u32				buffer_size0 = (first.size() + 1)*2;
-	LPCWSTR			buffer0 = (LPCWSTR)_alloca(buffer_size0);
-	AnsiToUnicode	(first.c_str(), (LPVOID)buffer0, buffer_size0);
+    u32 buffer_size0 = (first.size() + 1) * 2;
+    LPCWSTR buffer0 = (LPCWSTR)_alloca(buffer_size0);
+    AnsiToUnicode(first.c_str(), (LPVOID)buffer0, buffer_size0);
 
-	u32				buffer_size1 = (second.size() + 1)*2;
-	LPCWSTR			buffer1 = (LPCWSTR)_alloca(buffer_size1);
-	AnsiToUnicode	(second.c_str(), (LPVOID)buffer1, buffer_size1);
+    u32 buffer_size1 = (second.size() + 1) * 2;
+    LPCWSTR buffer1 = (LPCWSTR)_alloca(buffer_size1);
+    AnsiToUnicode(second.c_str(), (LPVOID)buffer1, buffer_size1);
 
-	return			(StrCmpLogicalW(buffer0, buffer1) < 0);
+    return (StrCmpLogicalW(buffer0, buffer1) < 0);
 }
 
-shared_str editor::environment::detail::real_path	(LPCSTR folder, LPCSTR path)
+shared_str editor::environment::detail::real_path(LPCSTR folder, LPCSTR path)
 {
-	string_path		result;
-	FS.update_path	(result, folder, path);
-	return			(result);
+    string_path result;
+    FS.update_path(result, folder, path);
+    return (result);
 }
 
 #endif // #ifdef INGAME_EDITOR
diff --git a/src/xrEngine/editor_environment_detail.hpp b/src/xrEngine/editor_environment_detail.hpp
index 0afbb91824a..b610e8bd1fe 100644
--- a/src/xrEngine/editor_environment_detail.hpp
+++ b/src/xrEngine/editor_environment_detail.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_detail.hpp
-//	Created 	: 11.01.2008
-//  Modified 	: 11.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment detail namespace
+// Module : editor_environment_detail.hpp
+// Created : 11.01.2008
+// Modified : 11.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment detail namespace
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_ENVIRONMENT_DETAIL_HPP_INCLUDED
@@ -11,16 +11,20 @@
 
 #ifdef INGAME_EDITOR
 
-namespace editor {
-namespace environment {
-namespace detail {
-
-struct logical_string_predicate {
-	bool		operator()	(LPCSTR const& first, LPCSTR const& second) const;
-	bool		operator()	(shared_str const& first, shared_str const& second) const;
+namespace editor
+{
+namespace environment
+{
+namespace detail
+{
+
+struct logical_string_predicate
+{
+    bool operator() (LPCSTR const& first, LPCSTR const& second) const;
+    bool operator() (shared_str const& first, shared_str const& second) const;
 }; // struct logical_string_predicate
 
-	shared_str	real_path	(LPCSTR folder, LPCSTR path);
+shared_str real_path(LPCSTR folder, LPCSTR path);
 
 } // namespace detail
 } // namespace environment
diff --git a/src/xrEngine/editor_environment_effects_effect.cpp b/src/xrEngine/editor_environment_effects_effect.cpp
index 8e58289c657..89b48911864 100644
--- a/src/xrEngine/editor_environment_effects_effect.cpp
+++ b/src/xrEngine/editor_environment_effects_effect.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_effects_effect.cpp
-//	Created 	: 28.12.2007
-//  Modified 	: 28.12.2007
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment effects effect class
+// Module : editor_environment_effects_effect.cpp
+// Created : 28.12.2007
+// Modified : 28.12.2007
+// Author : Dmitriy Iassenev
+// Description : editor environment effects effect class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -20,202 +20,202 @@
 using editor::environment::effects::effect;
 using editor::environment::effects::manager;
 
-effect::effect			(manager const& manager, shared_str const& id) :
-	m_manager			(manager),
-	m_property_holder	(0),
-	m_id				(id),
-	m_sound				("")
+effect::effect(manager const& manager, shared_str const& id) :
+    m_manager(manager),
+    m_property_holder(0),
+    m_id(id),
+    m_sound("")
 {
-	particles			= "";
+    particles = "";
 }
 
-effect::~effect			()
+effect::~effect()
 {
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy		(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-void effect::load		(CInifile& config)
+void effect::load(CInifile& config)
 {
-	life_time			= config.r_u32			(m_id, "life_time");
-	offset				= config.r_fvector3		(m_id, "offset");
-	particles			= config.r_string		(m_id, "particles");
-	m_sound				= config.r_string		(m_id, "sound");
-	wind_gust_factor	= config.r_float		(m_id, "wind_gust_factor");
+    life_time = config.r_u32(m_id, "life_time");
+    offset = config.r_fvector3(m_id, "offset");
+    particles = config.r_string(m_id, "particles");
+    m_sound = config.r_string(m_id, "sound");
+    wind_gust_factor = config.r_float(m_id, "wind_gust_factor");
 }
 
-void effect::save		(CInifile& config)
+void effect::save(CInifile& config)
 {
-	config.w_u32		(m_id.c_str(), "life_time",				life_time			);
-	config.w_fvector3	(m_id.c_str(), "offset",				offset				);
-	config.w_string		(m_id.c_str(), "particles",				particles.c_str()	);
-	config.w_string		(m_id.c_str(), "sound",					m_sound.c_str()		);
-	config.w_float		(m_id.c_str(), "wind_gust_factor",		wind_gust_factor	);
-	config.w_float		(m_id.c_str(), "wind_blast_in_time",	wind_blast_in_time	);
-	config.w_float		(m_id.c_str(), "wind_blast_out_time",	wind_blast_out_time	);
-	config.w_float		(m_id.c_str(), "wind_blast_strength",	wind_blast_strength	);
-	config.w_float		(m_id.c_str(), "wind_blast_longitude",	rad2deg(wind_blast_direction.getH()));
+    config.w_u32(m_id.c_str(), "life_time", life_time);
+    config.w_fvector3(m_id.c_str(), "offset", offset);
+    config.w_string(m_id.c_str(), "particles", particles.c_str());
+    config.w_string(m_id.c_str(), "sound", m_sound.c_str());
+    config.w_float(m_id.c_str(), "wind_gust_factor", wind_gust_factor);
+    config.w_float(m_id.c_str(), "wind_blast_in_time", wind_blast_in_time);
+    config.w_float(m_id.c_str(), "wind_blast_out_time", wind_blast_out_time);
+    config.w_float(m_id.c_str(), "wind_blast_strength", wind_blast_strength);
+    config.w_float(m_id.c_str(), "wind_blast_longitude", rad2deg(wind_blast_direction.getH()));
 }
 
 LPCSTR effect::id_getter() const
 {
-	return				(m_id.c_str());
+    return (m_id.c_str());
 }
 
-void effect::id_setter	(LPCSTR value_)
+void effect::id_setter(LPCSTR value_)
 {
-	shared_str			value = value_;
-	if (m_id._get() == value._get())
-		return;
+    shared_str value = value_;
+    if (m_id._get() == value._get())
+        return;
 
-	m_id				= m_manager.unique_id(value);
+    m_id = m_manager.unique_id(value);
 }
 
-LPCSTR effect::sound_getter		()
+LPCSTR effect::sound_getter()
 {
-	return				(m_sound.c_str());
+    return (m_sound.c_str());
 }
 
-void effect::sound_setter		(LPCSTR value)
+void effect::sound_setter(LPCSTR value)
 {
-	m_sound				= value;
-	sound.destroy		();
-	sound.create		(value, st_Effect, sg_SourceType);
+    m_sound = value;
+    sound.destroy();
+    sound.create(value, st_Effect, sg_SourceType);
 }
 
-float effect::wind_blast_longitude_getter	() const
+float effect::wind_blast_longitude_getter() const
 {
-	float						h, p;
-	wind_blast_direction.getHP	(h, p);
-	return						(rad2deg(h));
+    float h, p;
+    wind_blast_direction.getHP(h, p);
+    return (rad2deg(h));
 }
 
-void effect::wind_blast_longitude_setter	(float value)
+void effect::wind_blast_longitude_setter(float value)
 {
-	wind_blast_direction.setHP	(deg2rad(value), 0.f);
+    wind_blast_direction.setHP(deg2rad(value), 0.f);
 }
 
-void effect::fill		(editor::property_holder_collection* collection)
+void effect::fill(editor::property_holder_collection* collection)
 {
-	VERIFY				(!m_property_holder);
-	m_property_holder	= ::ide().create_property_holder(m_id.c_str(), collection, this);
-
-	typedef editor::property_holder::string_getter_type	string_getter_type;
-	string_getter_type	string_getter;
-	string_getter.bind	(this, &effect::id_getter);
-
-	typedef editor::property_holder::string_setter_type	string_setter_type;
-	string_setter_type	string_setter;
-	string_setter.bind	(this, &effect::id_setter);
-
-	m_property_holder->add_property	(
-		"id",
-		"properties",
-		"this option is resposible for effect identifier",
-		m_id.c_str(),
-		string_getter,
-		string_setter
-	);
-	m_property_holder->add_property	(
-		"life time",
-		"properties",
-		"this option is resposible for effect life time (in milliseconds)",
-		(int const&)life_time,
-		(int&)life_time
-	);
-	m_property_holder->add_property	(
-		"offset",
-		"properties",
-		"this option is resposible for effect offset (3D vector)",
-		(vec3f const&)offset,
-		(vec3f&)offset
-	);
-	m_property_holder->add_property(
-		"particles",
-		"properties",
-		"this option is resposible for effect particles",
-		particles.c_str(),
-		particles,
-		&*m_manager.environment().particle_ids().begin(),
-		m_manager.environment().particle_ids().size(),
-		editor::property_holder::value_editor_tree_view,
-		editor::property_holder::cannot_enter_text
-	);
-
-	string_getter.bind	(this, &effect::sound_getter);
-	string_setter.bind	(this, &effect::sound_setter);
-	m_property_holder->add_property(
-		"sound",
-		"properties",
-		"this option is resposible for effect sound",
-		m_sound.c_str(),
-		string_getter,
-		string_setter,
-		".ogg",
-		"Sound files (*.ogg)|*.ogg",
-		detail::real_path("$game_sounds$", "").c_str(),
-		"Select sound...",
-		editor::property_holder::cannot_enter_text,
-		editor::property_holder::remove_extension
-	);
-	m_property_holder->add_property	(
-		"wind gust factor",
-		"properties",
-		"this option is resposible for effect wind gust factor",
-		wind_gust_factor,
-		wind_gust_factor
-	);
-	m_property_holder->add_property	(
-		"wind blast strength",
-		"properties",
-		"this option is resposible for effect wind blast strength",
-		wind_blast_strength,
-		wind_blast_strength
-	);
-	m_property_holder->add_property	(
-		"wind blast start time",
-		"properties",
-		"this option is resposible for effect wind blast start time",
-		wind_blast_in_time,
-		wind_blast_in_time,
-		0.f,
-		1000.f
-	);
-	m_property_holder->add_property	(
-		"wind blast stop time",
-		"properties",
-		"this option is resposible for effect wind blast stop time",
-		wind_blast_out_time,
-		wind_blast_out_time,
-		0.f,
-		1000.f
-	);
-
-	typedef ::editor::property_holder::float_getter_type	float_getter_type;
-	float_getter_type	float_getter;
-
-	typedef ::editor::property_holder::float_setter_type	float_setter_type;
-	float_setter_type	float_setter;
-
-	float_getter.bind	(this, &effect::wind_blast_longitude_getter);
-	float_setter.bind	(this, &effect::wind_blast_longitude_setter);
-	m_property_holder->add_property	(
-		"wind blast longitude",
-		"properties",
-		"this option is resposible for effect wind blast longitude",
-		float_getter(),
-		float_getter,
-		float_setter,
-		-360.f,
-		 360.f
-	);
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder(m_id.c_str(), collection, this);
+
+    typedef editor::property_holder::string_getter_type string_getter_type;
+    string_getter_type string_getter;
+    string_getter.bind(this, &effect::id_getter);
+
+    typedef editor::property_holder::string_setter_type string_setter_type;
+    string_setter_type string_setter;
+    string_setter.bind(this, &effect::id_setter);
+
+    m_property_holder->add_property(
+        "id",
+        "properties",
+        "this option is resposible for effect identifier",
+        m_id.c_str(),
+        string_getter,
+        string_setter
+    );
+    m_property_holder->add_property(
+        "life time",
+        "properties",
+        "this option is resposible for effect life time (in milliseconds)",
+        (int const&)life_time,
+        (int&)life_time
+    );
+    m_property_holder->add_property(
+        "offset",
+        "properties",
+        "this option is resposible for effect offset (3D vector)",
+        (vec3f const&)offset,
+        (vec3f&)offset
+    );
+    m_property_holder->add_property(
+        "particles",
+        "properties",
+        "this option is resposible for effect particles",
+        particles.c_str(),
+        particles,
+        &*m_manager.environment().particle_ids().begin(),
+        m_manager.environment().particle_ids().size(),
+        editor::property_holder::value_editor_tree_view,
+        editor::property_holder::cannot_enter_text
+    );
+
+    string_getter.bind(this, &effect::sound_getter);
+    string_setter.bind(this, &effect::sound_setter);
+    m_property_holder->add_property(
+        "sound",
+        "properties",
+        "this option is resposible for effect sound",
+        m_sound.c_str(),
+        string_getter,
+        string_setter,
+        ".ogg",
+        "Sound files (*.ogg)|*.ogg",
+        detail::real_path("$game_sounds$", "").c_str(),
+        "Select sound...",
+        editor::property_holder::cannot_enter_text,
+        editor::property_holder::remove_extension
+    );
+    m_property_holder->add_property(
+        "wind gust factor",
+        "properties",
+        "this option is resposible for effect wind gust factor",
+        wind_gust_factor,
+        wind_gust_factor
+    );
+    m_property_holder->add_property(
+        "wind blast strength",
+        "properties",
+        "this option is resposible for effect wind blast strength",
+        wind_blast_strength,
+        wind_blast_strength
+    );
+    m_property_holder->add_property(
+        "wind blast start time",
+        "properties",
+        "this option is resposible for effect wind blast start time",
+        wind_blast_in_time,
+        wind_blast_in_time,
+        0.f,
+        1000.f
+    );
+    m_property_holder->add_property(
+        "wind blast stop time",
+        "properties",
+        "this option is resposible for effect wind blast stop time",
+        wind_blast_out_time,
+        wind_blast_out_time,
+        0.f,
+        1000.f
+    );
+
+    typedef ::editor::property_holder::float_getter_type float_getter_type;
+    float_getter_type float_getter;
+
+    typedef ::editor::property_holder::float_setter_type float_setter_type;
+    float_setter_type float_setter;
+
+    float_getter.bind(this, &effect::wind_blast_longitude_getter);
+    float_setter.bind(this, &effect::wind_blast_longitude_setter);
+    m_property_holder->add_property(
+        "wind blast longitude",
+        "properties",
+        "this option is resposible for effect wind blast longitude",
+        float_getter(),
+        float_getter,
+        float_setter,
+        -360.f,
+        360.f
+    );
 }
 
-editor::property_holder* effect::object	()
+editor::property_holder* effect::object()
 {
-	return				(m_property_holder);
+    return (m_property_holder);
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_effects_effect.hpp b/src/xrEngine/editor_environment_effects_effect.hpp
index 98cb29e2f58..30e3255cd0a 100644
--- a/src/xrEngine/editor_environment_effects_effect.hpp
+++ b/src/xrEngine/editor_environment_effects_effect.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_effects_effect.hpp
-//	Created 	: 28.12.2007
-//  Modified 	: 28.12.2007
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment effects effect class
+// Module : editor_environment_effects_effect.hpp
+// Created : 28.12.2007
+// Modified : 28.12.2007
+// Author : Dmitriy Iassenev
+// Description : editor environment effects effect class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_EFFECTS_EFFECT_HPP_INCLUDED
@@ -15,53 +15,56 @@
 #include "../include/editor/property_holder.hpp"
 #include "environment.h"
 
-namespace editor {
-namespace environment {
+namespace editor
+{
+namespace environment
+{
 
 class manager;
 
-namespace effects {
+namespace effects
+{
 
 class manager;
 
 class effect :
-	public CEnvAmbient::SEffect,
-	public editor::property_holder_holder,
-	private boost::noncopyable
+    public CEnvAmbient::SEffect,
+    public editor::property_holder_holder,
+    private boost::noncopyable
 {
 public:
-							effect		(manager const& manager, shared_str const& id);
-	virtual					~effect		();
-			void			load		(CInifile& config);
-			void			save		(CInifile& config);
-			void			fill		(editor::property_holder_collection* collection);
-	inline	LPCSTR			id			() const { return m_id.c_str(); }
+    effect(manager const& manager, shared_str const& id);
+    virtual ~effect();
+    void load(CInifile& config);
+    void save(CInifile& config);
+    void fill(editor::property_holder_collection* collection);
+    inline LPCSTR id() const { return m_id.c_str(); }
 
 
 private:
-	LPCSTR xr_stdcall		id_getter	() const;
-	void   xr_stdcall		id_setter	(LPCSTR value);
+    LPCSTR xr_stdcall id_getter() const;
+    void xr_stdcall id_setter(LPCSTR value);
 
-	float xr_stdcall		wind_blast_longitude_getter	() const;
-	void  xr_stdcall		wind_blast_longitude_setter	(float value);
+    float xr_stdcall wind_blast_longitude_getter() const;
+    void xr_stdcall wind_blast_longitude_setter(float value);
 
 
-	LPCSTR xr_stdcall sound_getter		();
-	void xr_stdcall	  sound_setter		(LPCSTR value);
+    LPCSTR xr_stdcall sound_getter();
+    void xr_stdcall sound_setter(LPCSTR value);
 
 private:
-	typedef editor::property_holder	property_holder_type;
+    typedef editor::property_holder property_holder_type;
 
 public:
-	virtual	property_holder_type*object	();
+    virtual property_holder_type* object();
 
 private:
-	shared_str				m_id;
-	property_holder_type*	m_property_holder;
-	shared_str				m_sound;
+    shared_str m_id;
+    property_holder_type* m_property_holder;
+    shared_str m_sound;
 
 public:
-	manager const&			m_manager;
+    manager const& m_manager;
 }; // class effect
 
 } // namespace effects
diff --git a/src/xrEngine/editor_environment_effects_manager.cpp b/src/xrEngine/editor_environment_effects_manager.cpp
index 12ec7ac405b..bfd04ae408d 100644
--- a/src/xrEngine/editor_environment_effects_manager.cpp
+++ b/src/xrEngine/editor_environment_effects_manager.cpp
@@ -12,127 +12,128 @@ using editor::environment::effects::effect;
 using editor::environment::detail::logical_string_predicate;
 
 template <>
-void property_collection::display_name	(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
+void property_collection::display_name(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
 {
-	xr_strcpy				(buffer, buffer_size, m_container[item_index]->id());
+    xr_strcpy(buffer, buffer_size, m_container[item_index]->id());
 }
 
 template <>
-editor::property_holder* property_collection::create	()
+editor::property_holder* property_collection::create()
 {
-	effect*					object = xr_new(m_holder, generate_unique_id("effect_unique_id_").c_str());
-	object->fill			(this);
-	return					(object->object());
+    effect* object = xr_new(m_holder, generate_unique_id("effect_unique_id_").c_str());
+    object->fill(this);
+    return (object->object());
 }
 
-manager::manager			(::editor::environment::manager* environment) :
-	m_environment			(*environment),
-	m_collection			(0),
-	m_changed				(true)
+manager::manager(::editor::environment::manager* environment) :
+    m_environment(*environment),
+    m_collection(0),
+    m_changed(true)
 {
-	m_collection			= xr_new(&m_effects, this, &m_changed);
+    m_collection = xr_new(&m_effects, this, &m_changed);
 }
 
-manager::~manager			()
+manager::~manager()
 {
-	xr_delete				(m_collection);
-	delete_data				(m_effects_ids);
+    xr_delete(m_collection);
+    delete_data(m_effects_ids);
 }
 
-void manager::load			()
+void manager::load()
 {
-	string_path				file_name;
-	CInifile*				config =
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\effects.ltx"
-			),
-			TRUE,
-			TRUE,
-			FALSE
-		);
-
-	VERIFY					(m_effects.empty());
-
-	typedef CInifile::Root	sections_type;
-	sections_type&			sections = config->sections();
-	m_effects.reserve		(sections.size());
-	sections_type::const_iterator	i = sections.begin();
-	sections_type::const_iterator	e = sections.end();
-	for ( ; i != e; ++i) {
-		effect*				object = xr_new(*this, (*i)->Name);
-		object->load		(*config);
-		object->fill		(m_collection);
-		m_effects.push_back	(object);
-	}
-
-	xr_delete				(config);
+    string_path file_name;
+    CInifile* config =
+        xr_new(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "environment\\effects.ltx"
+            ),
+            TRUE,
+            TRUE,
+            FALSE
+        );
+
+    VERIFY(m_effects.empty());
+
+    typedef CInifile::Root sections_type;
+    sections_type& sections = config->sections();
+    m_effects.reserve(sections.size());
+    sections_type::const_iterator i = sections.begin();
+    sections_type::const_iterator e = sections.end();
+    for (; i != e; ++i)
+    {
+        effect* object = xr_new(*this, (*i)->Name);
+        object->load(*config);
+        object->fill(m_collection);
+        m_effects.push_back(object);
+    }
+
+    xr_delete(config);
 }
 
-void manager::save			()
+void manager::save()
 {
-	string_path				file_name;
-	CInifile*				config =
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\effects.ltx"
-			),
-			FALSE,
-			FALSE,
-			TRUE
-		);
-
-	effect_container_type::iterator	i = m_effects.begin();
-	effect_container_type::iterator	e = m_effects.end();
-	for ( ; i != e; ++i)
-		(*i)->save			(*config);
-
-	xr_delete				(config);
+    string_path file_name;
+    CInifile* config =
+        xr_new(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "environment\\effects.ltx"
+            ),
+            FALSE,
+            FALSE,
+            TRUE
+        );
+
+    effect_container_type::iterator i = m_effects.begin();
+    effect_container_type::iterator e = m_effects.end();
+    for (; i != e; ++i)
+        (*i)->save(*config);
+
+    xr_delete(config);
 }
 
-void manager::fill			(editor::property_holder* holder)
+void manager::fill(editor::property_holder* holder)
 {
-	VERIFY					(holder);
-	holder->add_property	(
-		"effects",
-		"ambients",
-		"this option is resposible for effects",
-		m_collection
-	);
+    VERIFY(holder);
+    holder->add_property(
+        "effects",
+        "ambients",
+        "this option is resposible for effects",
+        m_collection
+    );
 }
 
-manager::effects_ids_type const& manager::effects_ids	() const
+manager::effects_ids_type const& manager::effects_ids() const
 {
-	if (!m_changed)
-		return				(m_effects_ids);
+    if (!m_changed)
+        return (m_effects_ids);
 
-	m_changed				= false;
+    m_changed = false;
 
-	delete_data				(m_effects_ids);
+    delete_data(m_effects_ids);
 
-	m_effects_ids.resize	(m_effects.size());
+    m_effects_ids.resize(m_effects.size());
 
-	effect_container_type::const_iterator	i = m_effects.begin();
-	effect_container_type::const_iterator	e = m_effects.end();
-	effects_ids_type::iterator				j = m_effects_ids.begin();
-	for ( ; i != e; ++i, ++j)
-		*j					= xr_strdup((*i)->id());
+    effect_container_type::const_iterator i = m_effects.begin();
+    effect_container_type::const_iterator e = m_effects.end();
+    effects_ids_type::iterator j = m_effects_ids.begin();
+    for (; i != e; ++i, ++j)
+        *j = xr_strdup((*i)->id());
 
-	std::sort				(m_effects_ids.begin(), m_effects_ids.end(), logical_string_predicate());
+    std::sort(m_effects_ids.begin(), m_effects_ids.end(), logical_string_predicate());
 
-	return					(m_effects_ids);
+    return (m_effects_ids);
 }
 
-shared_str manager::unique_id	(shared_str const& id) const
+shared_str manager::unique_id(shared_str const& id) const
 {
-	if (m_collection->unique_id(id.c_str()))
-		return				(id);
+    if (m_collection->unique_id(id.c_str()))
+        return (id);
 
-	return					(m_collection->generate_unique_id(id.c_str()));
+    return (m_collection->generate_unique_id(id.c_str()));
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_effects_manager.hpp b/src/xrEngine/editor_environment_effects_manager.hpp
index 4e30bae19bd..1b0f50b4ddb 100644
--- a/src/xrEngine/editor_environment_effects_manager.hpp
+++ b/src/xrEngine/editor_environment_effects_manager.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_effects_manager.hpp
-//	Created 	: 28.12.2007
-//  Modified 	: 28.12.2007
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment effects manager class
+// Module : editor_environment_effects_manager.hpp
+// Created : 28.12.2007
+// Modified : 28.12.2007
+// Author : Dmitriy Iassenev
+// Description : editor environment effects manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_EFFECTS_MANAGER_HPP_INCLUDED
@@ -14,51 +14,55 @@
 #include 
 #include "property_collection_forward.hpp"
 
-namespace editor {
+namespace editor
+{
 
 class property_holder;
 
-namespace environment {
+namespace environment
+{
 
 class manager;
 
-namespace effects {
+namespace effects
+{
 
 class effect;
 
-class manager : private boost::noncopyable {
+class manager : private boost::noncopyable
+{
 public:
-							manager			(::editor::environment::manager* environment);
-							~manager		();
-			void			load			();
-			void			save			();
-			void			fill			(editor::property_holder* holder);
-			shared_str		unique_id		(shared_str const& id) const;
+    manager(::editor::environment::manager* environment);
+    ~manager();
+    void load();
+    void save();
+    void fill(editor::property_holder* holder);
+    shared_str unique_id(shared_str const& id) const;
 
 public:
-	inline	::editor::environment::manager&	environment	() const {return m_environment;}
+    inline ::editor::environment::manager& environment() const { return m_environment; }
 
 public:
-	typedef xr_vector				effect_container_type;
-	typedef xr_vector				effects_ids_type;
+    typedef xr_vector effect_container_type;
+    typedef xr_vector effects_ids_type;
 
 public:
-	effects_ids_type const&	effects_ids		() const;
+    effects_ids_type const& effects_ids() const;
 
 private:
-	typedef editor::property_holder			property_holder_type;
-	typedef property_collection<
-				effect_container_type,
-				manager
-			>								collection_type;
+    typedef editor::property_holder property_holder_type;
+    typedef property_collection <
+    effect_container_type,
+    manager
+    > collection_type;
 
 private:
-	effect_container_type					m_effects;
-	mutable effects_ids_type				m_effects_ids;
-	::editor::environment::manager&			m_environment;
-	property_holder_type*					m_property_holder;
-	collection_type*						m_collection;
-	mutable bool							m_changed;
+    effect_container_type m_effects;
+    mutable effects_ids_type m_effects_ids;
+    ::editor::environment::manager& m_environment;
+    property_holder_type* m_property_holder;
+    collection_type* m_collection;
+    mutable bool m_changed;
 }; // class effects_manager
 
 } // namespace effects
diff --git a/src/xrEngine/editor_environment_levels_manager.cpp b/src/xrEngine/editor_environment_levels_manager.cpp
index 074745844b0..da64a66ffdd 100644
--- a/src/xrEngine/editor_environment_levels_manager.cpp
+++ b/src/xrEngine/editor_environment_levels_manager.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_levels_manager.cpp
-//	Created 	: 28.12.2007
-//  Modified 	: 28.12.2007
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment levels manager class
+// Module : editor_environment_levels_manager.cpp
+// Created : 28.12.2007
+// Modified : 28.12.2007
+// Author : Dmitriy Iassenev
+// Description : editor environment levels manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -18,143 +18,146 @@
 
 using editor::environment::levels::manager;
 
-static LPCSTR s_default_weather_id	= "[default]";
-static LPCSTR s_level_section_id	= "levels";
+static LPCSTR s_default_weather_id = "[default]";
+static LPCSTR s_level_section_id = "levels";
 
-manager::manager					(::editor::environment::weathers::manager* weathers) :
-	m_weathers						(*weathers),
-	m_property_holder				(0)
+manager::manager(::editor::environment::weathers::manager* weathers) :
+    m_weathers(*weathers),
+    m_property_holder(0)
 {
 }
 
-manager::~manager					()
+manager::~manager()
 {
-	VERIFY							(m_config_single);
-	CInifile::Destroy				(m_config_single);
-	m_config_single					= 0;
+    VERIFY(m_config_single);
+    CInifile::Destroy(m_config_single);
+    m_config_single = 0;
 
-	VERIFY							(m_config_mp);
-	CInifile::Destroy				(m_config_mp);
-	m_config_mp						= 0;
+    VERIFY(m_config_mp);
+    CInifile::Destroy(m_config_mp);
+    m_config_mp = 0;
 
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy					(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-void manager::fill_levels			(CInifile& config, LPCSTR prefix, LPCSTR category)
+void manager::fill_levels(CInifile& config, LPCSTR prefix, LPCSTR category)
 {
-	string_path						section_id;
-	xr_strcpy						(section_id, "level_maps_");
-	xr_strcat						(section_id, prefix);
-	CInifile::Items const&			section = config.r_section(section_id).Data;
-
-	CInifile::Items::const_iterator	i = section.begin();
-	CInifile::Items::const_iterator	e = section.end();
-	for ( ; i != e; ++i) {
-		if (!(*i).first.size())
-			continue;
-
-		VERIFY						(config.section_exist((*i).first));
-		if (!config.line_exist((*i).first, "weathers")) {
-			m_levels.insert			(
-				std::make_pair(
-					(*i).first.c_str(),
-					std::make_pair(
-						category,
-						s_default_weather_id
-					)
-				)
-			);
-			continue;
-		}
-
-		LPCSTR						weather_id = config.r_string((*i).first, "weathers");
-		m_levels.insert				(
-			std::make_pair(
-				(*i).first.c_str(),
-				std::make_pair(
-					category,
-					weather_id
-				)
-			)
-		);
-	}
+    string_path section_id;
+    xr_strcpy(section_id, "level_maps_");
+    xr_strcat(section_id, prefix);
+    CInifile::Items const& section = config.r_section(section_id).Data;
+
+    CInifile::Items::const_iterator i = section.begin();
+    CInifile::Items::const_iterator e = section.end();
+    for (; i != e; ++i)
+    {
+        if (!(*i).first.size())
+            continue;
+
+        VERIFY(config.section_exist((*i).first));
+        if (!config.line_exist((*i).first, "weathers"))
+        {
+            m_levels.insert(
+                std::make_pair(
+                    (*i).first.c_str(),
+                    std::make_pair(
+                        category,
+                        s_default_weather_id
+                    )
+                )
+            );
+            continue;
+        }
+
+        LPCSTR weather_id = config.r_string((*i).first, "weathers");
+        m_levels.insert(
+            std::make_pair(
+                (*i).first.c_str(),
+                std::make_pair(
+                    category,
+                    weather_id
+                )
+            )
+        );
+    }
 }
 
-void manager::load					()
+void manager::load()
 {
-	string_path						file_name;
-
-	m_config_single					=
-		CInifile::Create(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"game_maps_single.ltx"
-			),
-			false
-		);
-
-	m_config_mp						=
-		CInifile::Create(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"game_maps_mp.ltx"
-			),
-			false
-		);
-
-	VERIFY							(m_levels.empty());
-	fill_levels						(*m_config_single,	"single",	"single");
-	fill_levels						(*m_config_mp,		"mp",		"multiplayer");
+    string_path file_name;
+
+    m_config_single =
+        CInifile::Create(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "game_maps_single.ltx"
+            ),
+            false
+        );
+
+    m_config_mp =
+        CInifile::Create(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "game_maps_mp.ltx"
+            ),
+            false
+        );
+
+    VERIFY(m_levels.empty());
+    fill_levels(*m_config_single, "single", "single");
+    fill_levels(*m_config_mp, "mp", "multiplayer");
 }
 
-LPCSTR const* manager::collection	()
+LPCSTR const* manager::collection()
 {
-	return							(&*m_weathers.weather_ids().begin());
+    return (&*m_weathers.weather_ids().begin());
 }
 
-u32 manager::collection_size		()
+u32 manager::collection_size()
 {
-	return							(m_weathers.weather_ids().size());
+    return (m_weathers.weather_ids().size());
 }
 
-void manager::fill					()
+void manager::fill()
 {
-	VERIFY							(!m_property_holder);
-	m_property_holder				= ::ide().create_property_holder("levels");
-
-	typedef editor::property_holder::string_collection_getter_type	collection_getter_type;
-	collection_getter_type			collection_getter;
-	collection_getter.bind			(this, &manager::collection);
-
-	typedef editor::property_holder::string_collection_size_getter_type	collection_size_getter_type;
-	collection_size_getter_type		collection_size_getter;
-	collection_size_getter.bind		(this, &manager::collection_size);
-
-	levels_container_type::iterator	i = m_levels.begin();
-	levels_container_type::iterator	e = m_levels.end();
-	for ( ; i != e; ++i) {
-		string_path					description;
-		xr_strcpy					(description, "weather for level ");
-		xr_strcat					(description, (*i).first.c_str());
-		m_property_holder->add_property	(
-			(*i).first.c_str(),
-			(*i).second.first,
-			description,
-			(*i).second.second.c_str(),
-			(*i).second.second,
-			collection_getter,
-			collection_size_getter,
-			editor::property_holder::value_editor_combo_box,
-			editor::property_holder::cannot_enter_text
-		);
-	}
-
-	::ide().environment_levels		(m_property_holder);
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder("levels");
+
+    typedef editor::property_holder::string_collection_getter_type collection_getter_type;
+    collection_getter_type collection_getter;
+    collection_getter.bind(this, &manager::collection);
+
+    typedef editor::property_holder::string_collection_size_getter_type collection_size_getter_type;
+    collection_size_getter_type collection_size_getter;
+    collection_size_getter.bind(this, &manager::collection_size);
+
+    levels_container_type::iterator i = m_levels.begin();
+    levels_container_type::iterator e = m_levels.end();
+    for (; i != e; ++i)
+    {
+        string_path description;
+        xr_strcpy(description, "weather for level ");
+        xr_strcat(description, (*i).first.c_str());
+        m_property_holder->add_property(
+            (*i).first.c_str(),
+            (*i).second.first,
+            description,
+            (*i).second.second.c_str(),
+            (*i).second.second,
+            collection_getter,
+            collection_size_getter,
+            editor::property_holder::value_editor_combo_box,
+            editor::property_holder::cannot_enter_text
+        );
+    }
+
+    ::ide().environment_levels(m_property_holder);
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_levels_manager.hpp b/src/xrEngine/editor_environment_levels_manager.hpp
index ef3ae6b521b..20b56f0af30 100644
--- a/src/xrEngine/editor_environment_levels_manager.hpp
+++ b/src/xrEngine/editor_environment_levels_manager.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_levels_manager.hpp
-//	Created 	: 28.12.2007
-//  Modified 	: 28.12.2007
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment levels manager class
+// Module : editor_environment_levels_manager.hpp
+// Created : 28.12.2007
+// Modified : 28.12.2007
+// Author : Dmitriy Iassenev
+// Description : editor environment levels manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_LEVELS_MANAGER_HPP_INCLUDED
@@ -14,49 +14,55 @@
 #include 
 #include "../xrserverentities/associative_vector.h"
 
-namespace editor {
+namespace editor
+{
 
-	class property_holder;
+class property_holder;
 
-namespace environment {
+namespace environment
+{
 
-	namespace weathers {
-		class manager;
-	} // namespace weathers
+namespace weathers
+{
+class manager;
+} // namespace weathers
 
-namespace levels {
+namespace levels
+{
 
-class manager : private boost::noncopyable {
+class manager : private boost::noncopyable
+{
 public:
-							manager			(::editor::environment::weathers::manager* environment);
-							~manager		();
-			void			load			();
-			void			save			();
-			void			fill			();
+    manager(::editor::environment::weathers::manager* environment);
+    ~manager();
+    void load();
+    void save();
+    void fill();
 
 private:
-			void			fill_levels		(CInifile& config, LPCSTR prefix, LPCSTR category);
+    void fill_levels(CInifile& config, LPCSTR prefix, LPCSTR category);
 
 private:
-	LPCSTR const* xr_stdcall collection		();
-	u32  xr_stdcall			collection_size	();
+    LPCSTR const* xr_stdcall collection();
+    u32 xr_stdcall collection_size();
 
 private:
-	struct predicate {
-		inline	bool	operator()			(shared_str const& left, shared_str const& right) const
-		{
-			return			(xr_strcmp(left.c_str(), right.c_str()) < 0);
-		}
-	}; // struct predicate
+    struct predicate
+    {
+        inline bool operator() (shared_str const& left, shared_str const& right) const
+        {
+            return (xr_strcmp(left.c_str(), right.c_str()) < 0);
+        }
+    }; // struct predicate
 
-	typedef associative_vector, predicate>	levels_container_type;
+    typedef associative_vector, predicate> levels_container_type;
 
 private:
-	levels_container_type						m_levels;
-	::editor::environment::weathers::manager&	m_weathers;
-	CInifile*									m_config_single;
-	CInifile*									m_config_mp;
-	editor::property_holder*					m_property_holder;
+    levels_container_type m_levels;
+    ::editor::environment::weathers::manager& m_weathers;
+    CInifile* m_config_single;
+    CInifile* m_config_mp;
+    editor::property_holder* m_property_holder;
 }; // class levels_manager
 
 } // namespace levels
diff --git a/src/xrEngine/editor_environment_manager.cpp b/src/xrEngine/editor_environment_manager.cpp
index 86c9add7979..1174d1d1bfc 100644
--- a/src/xrEngine/editor_environment_manager.cpp
+++ b/src/xrEngine/editor_environment_manager.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_manager.cpp
-//	Created 	: 12.12.2007
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment manager class
+// Module : editor_environment_manager.cpp
+// Created : 12.12.2007
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -31,222 +31,224 @@ using editor::environment::manager;
 using editor::environment::detail::logical_string_predicate;
 using particles_systems::library_interface;
 
-manager::manager												() :
-	m_suns						(0),
-	m_levels					(0),
-	m_effects					(0),
-	m_sound_channels			(0),
-	m_ambients					(0),
-	m_thunderbolts				(0),
-	m_weathers					(0)
+manager::manager() :
+    m_suns(0),
+    m_levels(0),
+    m_effects(0),
+    m_sound_channels(0),
+    m_ambients(0),
+    m_thunderbolts(0),
+    m_weathers(0)
 {
-	m_effects					= xr_new(this);
-	m_sound_channels			= xr_new();
-	m_ambients					= xr_new(*this);
-	m_weathers					= xr_new(this);
-	m_suns						= xr_new(this);
-	m_levels					= xr_new(m_weathers);
-	m_thunderbolts				= xr_new(this);
+    m_effects = xr_new(this);
+    m_sound_channels = xr_new();
+    m_ambients = xr_new(*this);
+    m_weathers = xr_new(this);
+    m_suns = xr_new(this);
+    m_levels = xr_new(m_weathers);
+    m_thunderbolts = xr_new(this);
 
-	load_internal				();
-	fill						();
+    load_internal();
+    fill();
 }
 
-manager::~manager												()
+manager::~manager()
 {
-	xr_delete					(m_thunderbolts);
-	xr_delete					(m_ambients);
-	xr_delete					(m_sound_channels);
-	xr_delete					(m_effects);
-	xr_delete					(m_levels);
-	xr_delete					(m_weathers);
-	xr_delete					(m_suns);
+    xr_delete(m_thunderbolts);
+    xr_delete(m_ambients);
+    xr_delete(m_sound_channels);
+    xr_delete(m_effects);
+    xr_delete(m_levels);
+    xr_delete(m_weathers);
+    xr_delete(m_suns);
 
-	delete_data					(m_shader_ids);
-	delete_data					(m_light_animator_ids);
+    delete_data(m_shader_ids);
+    delete_data(m_light_animator_ids);
 
-	WeatherCycles.clear			();
-	WeatherFXs.clear			();
+    WeatherCycles.clear();
+    WeatherFXs.clear();
 
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy				(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-void manager::load												()
+void manager::load()
 {
 }
 
-void manager::load_internal										()
+void manager::load_internal()
 {
-	m_thunderbolts->load		();
-	m_suns->load				();
-	m_levels->load				();
-	m_effects->load				();
-	m_sound_channels->load		();
-	m_ambients->load			();
+    m_thunderbolts->load();
+    m_suns->load();
+    m_levels->load();
+    m_effects->load();
+    m_sound_channels->load();
+    m_ambients->load();
 
-	inherited::load				();
+    inherited::load();
 }
 
-void manager::save			()
+void manager::save()
 {
-	m_weathers->save			();
-//	m_suns->save				();
-	m_ambients->save			();
-	m_effects->save				();
-	m_sound_channels->save		();
-	m_thunderbolts->save		();
-//	m_levels->save				();
+    m_weathers->save();
+    // m_suns->save ();
+    m_ambients->save();
+    m_effects->save();
+    m_sound_channels->save();
+    m_thunderbolts->save();
+    // m_levels->save ();
 }
 
-void manager::fill												()
+void manager::fill()
 {
-	m_property_holder			= ::ide().create_property_holder("environment");
+    m_property_holder = ::ide().create_property_holder("environment");
 
-	m_weathers->fill			(m_property_holder);
-	m_suns->fill				(m_property_holder);
-	m_ambients->fill			(m_property_holder);
-	m_effects->fill				(m_property_holder);
-	m_sound_channels->fill		(m_property_holder);
-	m_thunderbolts->fill		(m_property_holder);
-	m_levels->fill				();
+    m_weathers->fill(m_property_holder);
+    m_suns->fill(m_property_holder);
+    m_ambients->fill(m_property_holder);
+    m_effects->fill(m_property_holder);
+    m_sound_channels->fill(m_property_holder);
+    m_thunderbolts->fill(m_property_holder);
+    m_levels->fill();
 
-	::ide().environment_weathers(m_property_holder);
+    ::ide().environment_weathers(m_property_holder);
 }
 
-void manager::load_weathers										()
+void manager::load_weathers()
 {
-	m_weathers->load			();
+    m_weathers->load();
 
-	// sorting weather envs
-	EnvsMapIt _I=WeatherCycles.begin();
-	EnvsMapIt _E=WeatherCycles.end();
-	for (; _I!=_E; _I++){
-		R_ASSERT3	(_I->second.size()>1,"Environment in weather must >=2",*_I->first);
-		std::sort(_I->second.begin(),_I->second.end(),sort_env_etl_pred);
-	}
-	R_ASSERT2	(!WeatherCycles.empty(),"Empty weathers.");
-	SetWeather	((*WeatherCycles.begin()).first.c_str());
+    // sorting weather envs
+    EnvsMapIt _I = WeatherCycles.begin();
+    EnvsMapIt _E = WeatherCycles.end();
+    for (; _I != _E; _I++)
+    {
+        R_ASSERT3(_I->second.size() > 1, "Environment in weather must >=2", *_I->first);
+        std::sort(_I->second.begin(), _I->second.end(), sort_env_etl_pred);
+    }
+    R_ASSERT2(!WeatherCycles.empty(), "Empty weathers.");
+    SetWeather((*WeatherCycles.begin()).first.c_str());
 }
 
-manager::shader_ids_type const& manager::shader_ids				() const
+manager::shader_ids_type const& manager::shader_ids() const
 {
-	if (!m_shader_ids.empty())
-		return					(m_shader_ids);
+    if (!m_shader_ids.empty())
+        return (m_shader_ids);
 
-	string_path					path;
-	FS.update_path				(path, "$game_data$", "shaders.xr");
-	IReader*					reader = FS.r_open(path); 
-	IReader*					stream = reader->open_chunk(3);
-	R_ASSERT					(stream);
+    string_path path;
+    FS.update_path(path, "$game_data$", "shaders.xr");
+    IReader* reader = FS.r_open(path);
+    IReader* stream = reader->open_chunk(3);
+    R_ASSERT(stream);
 
-	u32							count = stream->r_u32();
-	m_shader_ids.resize			(count);
-	shader_ids_type::iterator	i = m_shader_ids.begin();
-	shader_ids_type::iterator	e = m_shader_ids.end();
-	for ( ; i != e; ++i) {
-		string_path				buffer;
-		stream->r_stringZ		(buffer, sizeof(buffer)); 
-		*i						= xr_strdup(buffer);
-	}
-	
-	stream->close				();
-	FS.r_close					(reader);
+    u32 count = stream->r_u32();
+    m_shader_ids.resize(count);
+    shader_ids_type::iterator i = m_shader_ids.begin();
+    shader_ids_type::iterator e = m_shader_ids.end();
+    for (; i != e; ++i)
+    {
+        string_path buffer;
+        stream->r_stringZ(buffer, sizeof(buffer));
+        *i = xr_strdup(buffer);
+    }
 
-	std::sort					(m_shader_ids.begin(), m_shader_ids.end(), logical_string_predicate());
+    stream->close();
+    FS.r_close(reader);
 
-	return						(m_shader_ids);
+    std::sort(m_shader_ids.begin(), m_shader_ids.end(), logical_string_predicate());
+
+    return (m_shader_ids);
 }
 
-manager::particle_ids_type const& manager::particle_ids			() const
+manager::particle_ids_type const& manager::particle_ids() const
 {
-	if (!m_particle_ids.empty())
-		return					(m_particle_ids);
+    if (!m_particle_ids.empty())
+        return (m_particle_ids);
 
-	library_interface const&	library = m_pRender->particles_systems_library();
-	PS::CPGDef const* const*	i = library.particles_group_begin();
-	PS::CPGDef const* const*	e = library.particles_group_end();
-	for ( ; i != e; library.particles_group_next(i))
-		m_particle_ids.push_back(library.particles_group_id(**i).c_str());
+    library_interface const& library = m_pRender->particles_systems_library();
+    PS::CPGDef const* const* i = library.particles_group_begin();
+    PS::CPGDef const* const* e = library.particles_group_end();
+    for (; i != e; library.particles_group_next(i))
+        m_particle_ids.push_back(library.particles_group_id(**i).c_str());
 
-	std::sort					(m_particle_ids.begin(), m_particle_ids.end(), logical_string_predicate());
-	return						(m_particle_ids);
+    std::sort(m_particle_ids.begin(), m_particle_ids.end(), logical_string_predicate());
+    return (m_particle_ids);
 }
 
-manager::light_animator_ids_type const& manager::light_animator_ids	() const
+manager::light_animator_ids_type const& manager::light_animator_ids() const
 {
-	if (!m_light_animator_ids.empty())
-		return								(m_light_animator_ids);
+    if (!m_light_animator_ids.empty())
+        return (m_light_animator_ids);
 
-	typedef LAItemVec						container_type;
-	container_type const&					light_animators = LALib.Objects();
-	m_light_animator_ids.resize				(light_animators.size());
-	container_type::const_iterator			i = light_animators.begin();
-	container_type::const_iterator			e = light_animators.end();
-	light_animator_ids_type::iterator		j = m_light_animator_ids.begin();
-	for ( ; i != e; ++i, ++j)
-		*j									= xr_strdup((*i)->cName.c_str());
+    typedef LAItemVec container_type;
+    container_type const& light_animators = LALib.Objects();
+    m_light_animator_ids.resize(light_animators.size());
+    container_type::const_iterator i = light_animators.begin();
+    container_type::const_iterator e = light_animators.end();
+    light_animator_ids_type::iterator j = m_light_animator_ids.begin();
+    for (; i != e; ++i, ++j)
+        *j = xr_strdup((*i)->cName.c_str());
 
-	std::sort								(m_light_animator_ids.begin(), m_light_animator_ids.end(), logical_string_predicate());
+    std::sort(m_light_animator_ids.begin(), m_light_animator_ids.end(), logical_string_predicate());
 
-	return									(m_light_animator_ids);
+    return (m_light_animator_ids);
 }
 
-void manager::create_mixer	()
+void manager::create_mixer()
 {
-	VERIFY								(!CurrentEnv);
-	editor::environment::weathers::time	*object = xr_new(this, (editor::environment::weathers::weather const*)0, "");
-	CurrentEnv							= object;
-	object->fill						(0);
+    VERIFY(!CurrentEnv);
+    editor::environment::weathers::time* object = xr_new(this, (editor::environment::weathers::weather const*)0, "");
+    CurrentEnv = object;
+    object->fill(0);
 }
 
-void manager::unload		()
+void manager::unload()
 {
-	WeatherCycles.clear			();
-	WeatherFXs.clear			();
-	Modifiers.clear				();
-	Ambients.clear				();
+    WeatherCycles.clear();
+    WeatherFXs.clear();
+    Modifiers.clear();
+    Ambients.clear();
 }
 
-CEnvAmbient* manager::AppendEnvAmb		(const shared_str& sect)
+CEnvAmbient* manager::AppendEnvAmb(const shared_str& sect)
 {
-	return						(m_ambients->get_ambient(sect));
+    return (m_ambients->get_ambient(sect));
 }
 
-SThunderboltDesc* manager::thunderbolt_description		(CInifile& config, shared_str const& section)
+SThunderboltDesc* manager::thunderbolt_description(CInifile& config, shared_str const& section)
 {
-	return						(m_thunderbolts->description(config, section));
+    return (m_thunderbolts->description(config, section));
 }
 
-SThunderboltCollection* manager::thunderbolt_collection	(CInifile* pIni, CInifile* thunderbolts, LPCSTR section)
+SThunderboltCollection* manager::thunderbolt_collection(CInifile* pIni, CInifile* thunderbolts, LPCSTR section)
 {
-	return						(m_thunderbolts->get_collection(section));
+    return (m_thunderbolts->get_collection(section));
 }
 
-SThunderboltCollection* manager::thunderbolt_collection	(xr_vector& collection,  shared_str const& id)
+SThunderboltCollection* manager::thunderbolt_collection(xr_vector& collection, shared_str const& id)
 {
-	return						(m_thunderbolts->get_collection(id));
+    return (m_thunderbolts->get_collection(id));
 }
 
-CLensFlareDescriptor*   manager::add_flare				(xr_vector& collection, shared_str const& id)
+CLensFlareDescriptor* manager::add_flare(xr_vector& collection, shared_str const& id)
 {
 #if 0
-//	return						(m_suns->get_flare(id));
-	typedef xr_vector	container_type;
-	container_type::iterator	i = collection.begin();
-	container_type::iterator	e = collection.end();
-	for ( ; i != e; ++i)
-		if ((*i)->section == id)
-			return				(*i);
-
-	NODEFAULT;
+    // return (m_suns->get_flare(id));
+    typedef xr_vector container_type;
+    container_type::iterator i = collection.begin();
+    container_type::iterator e = collection.end();
+    for (; i != e; ++i)
+        if ((*i)->section == id)
+            return (*i);
+
+    NODEFAULT;
 #ifdef DEBUG
-	return						(0);
+    return (0);
 #endif // #ifdef DEBUG
 #endif // #if 0
-	return						(inherited::add_flare(collection, id));
+    return (inherited::add_flare(collection, id));
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_manager.hpp b/src/xrEngine/editor_environment_manager.hpp
index f97f7b2f352..d29e9785c2e 100644
--- a/src/xrEngine/editor_environment_manager.hpp
+++ b/src/xrEngine/editor_environment_manager.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_manager.hpp
-//	Created 	: 12.12.2007
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment manager class
+// Module : editor_environment_manager.hpp
+// Created : 12.12.2007
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_ENVIRONMENT_MANAGER_HPP_INCLUDED
@@ -13,104 +13,115 @@
 
 #include "environment.h"
 
-namespace editor {
-	class property_holder;
-
-namespace environment {
-	namespace detail {
-	} // namespace detail
-
-	namespace suns {
-		class manager;
-	} // namespace suns
-
-	namespace effects {
-		class manager;
-	} // namespace effects
-
-	namespace levels {
-		class manager;
-	} // namespace levels
-
-	namespace sound_channels {
-		class manager;
-	} // namespace sound_channels
-
-	namespace ambients {
-		class manager;
-	} // namespace ambients
-
-	namespace thunderbolts {
-		class manager;
-	} // namespace thunderbolts
-
-	namespace weathers {
-		class manager;
-	} // namespace weathers
-
-class manager : public ::CEnvironment {
+namespace editor
+{
+class property_holder;
+
+namespace environment
+{
+namespace detail
+{
+} // namespace detail
+
+namespace suns
+{
+class manager;
+} // namespace suns
+
+namespace effects
+{
+class manager;
+} // namespace effects
+
+namespace levels
+{
+class manager;
+} // namespace levels
+
+namespace sound_channels
+{
+class manager;
+} // namespace sound_channels
+
+namespace ambients
+{
+class manager;
+} // namespace ambients
+
+namespace thunderbolts
+{
+class manager;
+} // namespace thunderbolts
+
+namespace weathers
+{
+class manager;
+} // namespace weathers
+
+class manager : public ::CEnvironment
+{
 public:
-	typedef xr_vector					shader_ids_type;
-	typedef xr_vector					particle_ids_type;
-	typedef xr_vector					light_animator_ids_type;
+    typedef xr_vector shader_ids_type;
+    typedef xr_vector particle_ids_type;
+    typedef xr_vector light_animator_ids_type;
 
 public:
-												manager					();
-	virtual										~manager				();
-	virtual	void								load_weathers			();
-	virtual	void								load					();
-	virtual	void								unload					();
-	virtual	void								create_mixer			();
-	virtual	CEnvAmbient*						AppendEnvAmb			(const shared_str& sect);
-	virtual	SThunderboltDesc*					thunderbolt_description	(CInifile& config, shared_str const& section);
-	virtual	SThunderboltCollection*				thunderbolt_collection	(CInifile* pIni, CInifile* thunderbolts, LPCSTR section);
-	virtual	SThunderboltCollection*				thunderbolt_collection	(xr_vector& collection,  shared_str const& id);
-	virtual	CLensFlareDescriptor*				add_flare				(xr_vector& collection, shared_str const& id);
-			void								save					();
-			shader_ids_type const&				shader_ids				() const;
-			particle_ids_type const&			particle_ids			() const;
-			light_animator_ids_type const&		light_animator_ids		() const;
+    manager();
+    virtual ~manager();
+    virtual void load_weathers();
+    virtual void load();
+    virtual void unload();
+    virtual void create_mixer();
+    virtual CEnvAmbient* AppendEnvAmb(const shared_str& sect);
+    virtual SThunderboltDesc* thunderbolt_description(CInifile& config, shared_str const& section);
+    virtual SThunderboltCollection* thunderbolt_collection(CInifile* pIni, CInifile* thunderbolts, LPCSTR section);
+    virtual SThunderboltCollection* thunderbolt_collection(xr_vector& collection, shared_str const& id);
+    virtual CLensFlareDescriptor* add_flare(xr_vector& collection, shared_str const& id);
+    void save();
+    shader_ids_type const& shader_ids() const;
+    particle_ids_type const& particle_ids() const;
+    light_animator_ids_type const& light_animator_ids() const;
 
 public:
-	typedef editor::property_holder										property_holder_type;
-	typedef editor::environment::suns::manager							suns_manager_type;
-	typedef editor::environment::levels::manager						levels_manager_type;
-	typedef editor::environment::effects::manager						effects_manager_type;
-	typedef editor::environment::sound_channels::manager				sound_channels_manager_type;
-	typedef editor::environment::ambients::manager						ambients_manager_type;
-	typedef editor::environment::thunderbolts::manager					thunderbolts_manager_type;
-	typedef editor::environment::weathers::manager						weathers_manager_type;
+    typedef editor::property_holder property_holder_type;
+    typedef editor::environment::suns::manager suns_manager_type;
+    typedef editor::environment::levels::manager levels_manager_type;
+    typedef editor::environment::effects::manager effects_manager_type;
+    typedef editor::environment::sound_channels::manager sound_channels_manager_type;
+    typedef editor::environment::ambients::manager ambients_manager_type;
+    typedef editor::environment::thunderbolts::manager thunderbolts_manager_type;
+    typedef editor::environment::weathers::manager weathers_manager_type;
 
 public:
-	inline	suns_manager_type const&			suns					() const { VERIFY(m_suns); 			return (*m_suns);			}
-	inline	levels_manager_type const&			levels					() const { VERIFY(m_levels); 		return (*m_levels);			}
-	inline	effects_manager_type const&			effects					() const { VERIFY(m_effects); 		return (*m_effects); 		}
-	inline	sound_channels_manager_type const&	sound_channels			() const { VERIFY(m_sound_channels);return (*m_sound_channels);	}
-	inline	ambients_manager_type const&		ambients				() const { VERIFY(m_ambients); 		return (*m_ambients);		}
-	inline	thunderbolts_manager_type const&	thunderbolts			() const { VERIFY(m_thunderbolts); 	return (*m_thunderbolts);	}
-	inline	weathers_manager_type&				weathers				() const { VERIFY(m_weathers); 		return (*m_weathers);		}
+    inline suns_manager_type const& suns() const { VERIFY(m_suns); return (*m_suns); }
+    inline levels_manager_type const& levels() const { VERIFY(m_levels); return (*m_levels); }
+    inline effects_manager_type const& effects() const { VERIFY(m_effects); return (*m_effects); }
+    inline sound_channels_manager_type const& sound_channels() const { VERIFY(m_sound_channels); return (*m_sound_channels); }
+    inline ambients_manager_type const& ambients() const { VERIFY(m_ambients); return (*m_ambients); }
+    inline thunderbolts_manager_type const& thunderbolts() const { VERIFY(m_thunderbolts); return (*m_thunderbolts); }
+    inline weathers_manager_type& weathers() const { VERIFY(m_weathers); return (*m_weathers); }
 
 private:
-	typedef CEnvironment						inherited;
+    typedef CEnvironment inherited;
 
 private:
-	virtual	void								load_internal			();
-			void								fill					();
+    virtual void load_internal();
+    void fill();
 
 private:
-	mutable shader_ids_type						m_shader_ids;
-	mutable particle_ids_type					m_particle_ids;
-	mutable light_animator_ids_type				m_light_animator_ids;
+    mutable shader_ids_type m_shader_ids;
+    mutable particle_ids_type m_particle_ids;
+    mutable light_animator_ids_type m_light_animator_ids;
 
 private:
-	property_holder_type*						m_property_holder;
-	suns_manager_type*							m_suns;
-	levels_manager_type*						m_levels;
-	effects_manager_type*						m_effects;
-	sound_channels_manager_type*				m_sound_channels;
-	ambients_manager_type*						m_ambients;
-	thunderbolts_manager_type*					m_thunderbolts;
-	weathers_manager_type*						m_weathers;
+    property_holder_type* m_property_holder;
+    suns_manager_type* m_suns;
+    levels_manager_type* m_levels;
+    effects_manager_type* m_effects;
+    sound_channels_manager_type* m_sound_channels;
+    ambients_manager_type* m_ambients;
+    thunderbolts_manager_type* m_thunderbolts;
+    weathers_manager_type* m_weathers;
 }; // class manager
 } // namespace environment
 } // namespace editor
diff --git a/src/xrEngine/editor_environment_manager_properties.cpp b/src/xrEngine/editor_environment_manager_properties.cpp
index d5bb00fe7bb..a1663361bcb 100644
--- a/src/xrEngine/editor_environment_manager_properties.cpp
+++ b/src/xrEngine/editor_environment_manager_properties.cpp
@@ -1,10 +1,11 @@
 
-struct test_property {
-	int	m_property;
+struct test_property
+{
+    int m_property;
 
-	test_property() : m_property(20) {}
-	int	 xr_stdcall getter () { return m_property; }
-	void xr_stdcall setter (int value) { m_property = value; }
+    test_property() : m_property(20) {}
+    int xr_stdcall getter() { return m_property; }
+    void xr_stdcall setter(int value) { m_property = value; }
 };
 
 static test_property s_test_property;
@@ -12,21 +13,23 @@ static test_property s_test_property_limited;
 
 LPCSTR s_properties[] = {"integer_property_0", "integer_property_1", "integer_property_2"};
 
-std::pair s_properties_enum[] = {
-	std::make_pair(10,"integer_property_0"),
-	std::make_pair(20,"integer_property_1"),
-	std::make_pair(30,"integer_property_2")
+std::pair s_properties_enum[] =
+{
+    std::make_pair(10, "integer_property_0"),
+    std::make_pair(20, "integer_property_1"),
+    std::make_pair(30, "integer_property_2")
 };
 
 static test_property s_test_property_values;
 static test_property s_test_property_enum;
 
-struct test_property2 {
-	LPSTR m_property;
+struct test_property2
+{
+    LPSTR m_property;
 
-	test_property2() : m_property(xr_strdup("")) {}
-	LPCSTR xr_stdcall getter () { return m_property; }
-	void xr_stdcall setter (LPCSTR value) { xr_free(m_property); m_property = xr_strdup(value); }
+    test_property2() : m_property(xr_strdup("")) {}
+    LPCSTR xr_stdcall getter() { return m_property; }
+    void xr_stdcall setter(LPCSTR value) { xr_free(m_property); m_property = xr_strdup(value); }
 };
 
 static test_property2 s_test_property2;
@@ -35,12 +38,13 @@ LPCSTR s_properties3[] = {"one", "two", "three"};
 
 static test_property2 s_test_property3;
 
-struct test_property4 {
-	bool	m_property;
+struct test_property4
+{
+    bool m_property;
 
-	test_property4() : m_property(false) {}
-	bool xr_stdcall getter () { return m_property; }
-	void xr_stdcall setter (bool value) { m_property = value; }
+    test_property4() : m_property(false) {}
+    bool xr_stdcall getter() { return m_property; }
+    void xr_stdcall setter(bool value) { m_property = value; }
 };
 
 static test_property4 s_test_property4;
@@ -49,22 +53,24 @@ LPCSTR s_properties5[] = {"bad", "good"};
 
 static test_property4 s_test_property5;
 
-struct test_property6 {
-	editor::color 	m_property;
+struct test_property6
+{
+    editor::color m_property;
 
-	test_property6() {m_property.r = 0.f; m_property.g = 0.f; m_property.b = 1.f; }
-	editor::color xr_stdcall getter () { return m_property; }
-	void xr_stdcall setter (editor::color value) { m_property = value; }
+    test_property6() { m_property.r = 0.f; m_property.g = 0.f; m_property.b = 1.f; }
+    editor::color xr_stdcall getter() { return m_property; }
+    void xr_stdcall setter(editor::color value) { m_property = value; }
 };
 
 static test_property6 s_test_property6;
 
-struct test_property7 {
-	float	m_property;
+struct test_property7
+{
+    float m_property;
 
-	test_property7() : m_property(6.f) {}
-	float xr_stdcall getter () { return m_property; }
-	void xr_stdcall setter (float value) { m_property = value; }
+    test_property7() : m_property(6.f) {}
+    float xr_stdcall getter() { return m_property; }
+    void xr_stdcall setter(float value) { m_property = value; }
 };
 
 static test_property7 s_test_property7;
@@ -73,240 +79,241 @@ static test_property7 s_test_property7_limited;
 
 static test_property7 s_test_property7_values_enum;
 
-std::pair s_properties7_enum[] = {
-	std::make_pair(10.1f,"float_property_0"),
-	std::make_pair(20.1f,"float_property_1"),
-	std::make_pair(30.1f,"float_property_2")
+std::pair s_properties7_enum[] =
+{
+    std::make_pair(10.1f, "float_property_0"),
+    std::make_pair(20.1f, "float_property_1"),
+    std::make_pair(30.1f, "float_property_2")
 };
 
 using editor::environment::manager;
 
-manager::manager	()
+manager::manager()
 {
-	// testing properties
-	if (!Device.editor())
-		return;
-
-	editor::ide&			ide = *Device.editor();
-	editor::property_holder*holder = ide.create_property_holder();
-	ide.active				(holder);
-
-	{
-		holder->add_property(
-			"holder",
-			"category",
-			"description",
-			holder
-		);
-	}
-
-	{
-		editor::property_holder::integer_getter_type	getter;
-		editor::property_holder::integer_setter_type	setter;
-
-		getter.bind			(&s_test_property, &test_property::getter);
-		setter.bind			(&s_test_property, &test_property::setter);
-		holder->add_property(
-			"integer",
-			"category",
-			"description",
-			s_test_property.m_property,
-			getter,
-			setter
-		);
-	}
-
-	{
-		editor::property_holder::integer_getter_type	getter;
-		editor::property_holder::integer_setter_type	setter;
-
-		getter.bind			(&s_test_property_limited, &test_property::getter);
-		setter.bind			(&s_test_property_limited, &test_property::setter);
-		holder->add_property(
-			"integer_limited",
-			"category",
-			"description",
-			s_test_property_limited.m_property,
-			getter,
-			setter,
-			0,
-			10
-		);
-	}
-
-	{
-		editor::property_holder::integer_getter_type	getter;
-		editor::property_holder::integer_setter_type	setter;
-
-		getter.bind			(&s_test_property_values, &test_property::getter);
-		setter.bind			(&s_test_property_values, &test_property::setter);
-		holder->add_property(
-			"integer_values",
-			"category",
-			"description",
-			s_test_property_limited.m_property,
-			getter,
-			setter,
-			s_properties,
-			3
-		);
-	}
-
-	{
-		editor::property_holder::integer_getter_type	getter;
-		editor::property_holder::integer_setter_type	setter;
-
-		getter.bind			(&s_test_property_enum, &test_property::getter);
-		setter.bind			(&s_test_property_enum, &test_property::setter);
-		holder->add_property(
-			"integer_enum",
-			"category",
-			"description",
-			s_test_property_enum.m_property,
-			getter,
-			setter,
-			s_properties_enum,
-			3
-		);
-	}
-
-	{
-		editor::property_holder::string_getter_type	getter;
-		editor::property_holder::string_setter_type	setter;
-
-		getter.bind			(&s_test_property2, &test_property2::getter);
-		setter.bind			(&s_test_property2, &test_property2::setter);
-		holder->add_property(
-			"string",
-			"category",
-			"description",
-			s_test_property2.m_property,
-			getter,
-			setter,
-			".dds",
-			"Texture files (*.dds)|*.dds",
-			"R:\\development\\priquel\\resources\\gamedata\\textures\\sky",
-			"Select texture..."
-		);
-	}
-
-	{
-		editor::property_holder::string_getter_type	getter;
-		editor::property_holder::string_setter_type	setter;
-
-		getter.bind			(&s_test_property3, &test_property2::getter);
-		setter.bind			(&s_test_property3, &test_property2::setter);
-		holder->add_property(
-			"string_values",
-			"category",
-			"description",
-			s_test_property3.m_property,
-			getter,
-			setter,
-			s_properties3,
-			3
-		);
-	}
-
-	{
-		editor::property_holder::boolean_getter_type	getter;
-		editor::property_holder::boolean_setter_type	setter;
-
-		getter.bind			(&s_test_property4, &test_property4::getter);
-		setter.bind			(&s_test_property4, &test_property4::setter);
-		holder->add_property(
-			"boolean",
-			"category",
-			"description",
-			s_test_property4.m_property,
-			getter,
-			setter
-		);
-	}
-
-	{
-		editor::property_holder::boolean_getter_type	getter;
-		editor::property_holder::boolean_setter_type	setter;
-
-		getter.bind			(&s_test_property5, &test_property4::getter);
-		setter.bind			(&s_test_property5, &test_property4::setter);
-		holder->add_property(
-			"boolean_values",
-			"category",
-			"description",
-			s_test_property5.m_property,
-			getter,
-			setter,
-			s_properties5
-		);
-	}
-
-	{
-		editor::property_holder::color_getter_type	getter;
-		editor::property_holder::color_setter_type	setter;
-
-		getter.bind			(&s_test_property6, &test_property6::getter);
-		setter.bind			(&s_test_property6, &test_property6::setter);
-		holder->add_property(
-			"color",
-			"category",
-			"description",
-			s_test_property6.m_property,
-			getter,
-			setter
-		);
-	}
-
-	{
-		editor::property_holder::float_getter_type	getter;
-		editor::property_holder::float_setter_type	setter;
-
-		getter.bind			(&s_test_property7_limited, &test_property7::getter);
-		setter.bind			(&s_test_property7_limited, &test_property7::setter);
-		holder->add_property(
-			"float",
-			"category",
-			"description",
-			s_test_property7.m_property,
-			getter,
-			setter
-		);
-	}
-
-	{
-		editor::property_holder::float_getter_type	getter;
-		editor::property_holder::float_setter_type	setter;
-
-		getter.bind			(&s_test_property7, &test_property7::getter);
-		setter.bind			(&s_test_property7, &test_property7::setter);
-		holder->add_property(
-			"float_limited",
-			"category",
-			"description",
-			s_test_property7.m_property,
-			getter,
-			setter,
-			0.f,
-			1.f
-		);
-	}
-
-	{
-		editor::property_holder::float_getter_type	getter;
-		editor::property_holder::float_setter_type	setter;
-
-		getter.bind			(&s_test_property7_values_enum, &test_property7::getter);
-		setter.bind			(&s_test_property7_values_enum, &test_property7::setter);
-		holder->add_property(
-			"float_enum",
-			"category",
-			"description",
-			s_test_property7_values_enum.m_property,
-			getter,
-			setter,
-			s_properties7_enum,
-			3
-		);
-	}
+    // testing properties
+    if (!Device.editor())
+        return;
+
+    editor::ide& ide = *Device.editor();
+    editor::property_holder* holder = ide.create_property_holder();
+    ide.active(holder);
+
+    {
+        holder->add_property(
+            "holder",
+            "category",
+            "description",
+            holder
+        );
+    }
+
+    {
+        editor::property_holder::integer_getter_type getter;
+        editor::property_holder::integer_setter_type setter;
+
+        getter.bind(&s_test_property, &test_property::getter);
+        setter.bind(&s_test_property, &test_property::setter);
+        holder->add_property(
+            "integer",
+            "category",
+            "description",
+            s_test_property.m_property,
+            getter,
+            setter
+        );
+    }
+
+    {
+        editor::property_holder::integer_getter_type getter;
+        editor::property_holder::integer_setter_type setter;
+
+        getter.bind(&s_test_property_limited, &test_property::getter);
+        setter.bind(&s_test_property_limited, &test_property::setter);
+        holder->add_property(
+            "integer_limited",
+            "category",
+            "description",
+            s_test_property_limited.m_property,
+            getter,
+            setter,
+            0,
+            10
+        );
+    }
+
+    {
+        editor::property_holder::integer_getter_type getter;
+        editor::property_holder::integer_setter_type setter;
+
+        getter.bind(&s_test_property_values, &test_property::getter);
+        setter.bind(&s_test_property_values, &test_property::setter);
+        holder->add_property(
+            "integer_values",
+            "category",
+            "description",
+            s_test_property_limited.m_property,
+            getter,
+            setter,
+            s_properties,
+            3
+        );
+    }
+
+    {
+        editor::property_holder::integer_getter_type getter;
+        editor::property_holder::integer_setter_type setter;
+
+        getter.bind(&s_test_property_enum, &test_property::getter);
+        setter.bind(&s_test_property_enum, &test_property::setter);
+        holder->add_property(
+            "integer_enum",
+            "category",
+            "description",
+            s_test_property_enum.m_property,
+            getter,
+            setter,
+            s_properties_enum,
+            3
+        );
+    }
+
+    {
+        editor::property_holder::string_getter_type getter;
+        editor::property_holder::string_setter_type setter;
+
+        getter.bind(&s_test_property2, &test_property2::getter);
+        setter.bind(&s_test_property2, &test_property2::setter);
+        holder->add_property(
+            "string",
+            "category",
+            "description",
+            s_test_property2.m_property,
+            getter,
+            setter,
+            ".dds",
+            "Texture files (*.dds)|*.dds",
+            "R:\\development\\priquel\\resources\\gamedata\\textures\\sky",
+            "Select texture..."
+        );
+    }
+
+    {
+        editor::property_holder::string_getter_type getter;
+        editor::property_holder::string_setter_type setter;
+
+        getter.bind(&s_test_property3, &test_property2::getter);
+        setter.bind(&s_test_property3, &test_property2::setter);
+        holder->add_property(
+            "string_values",
+            "category",
+            "description",
+            s_test_property3.m_property,
+            getter,
+            setter,
+            s_properties3,
+            3
+        );
+    }
+
+    {
+        editor::property_holder::boolean_getter_type getter;
+        editor::property_holder::boolean_setter_type setter;
+
+        getter.bind(&s_test_property4, &test_property4::getter);
+        setter.bind(&s_test_property4, &test_property4::setter);
+        holder->add_property(
+            "boolean",
+            "category",
+            "description",
+            s_test_property4.m_property,
+            getter,
+            setter
+        );
+    }
+
+    {
+        editor::property_holder::boolean_getter_type getter;
+        editor::property_holder::boolean_setter_type setter;
+
+        getter.bind(&s_test_property5, &test_property4::getter);
+        setter.bind(&s_test_property5, &test_property4::setter);
+        holder->add_property(
+            "boolean_values",
+            "category",
+            "description",
+            s_test_property5.m_property,
+            getter,
+            setter,
+            s_properties5
+        );
+    }
+
+    {
+        editor::property_holder::color_getter_type getter;
+        editor::property_holder::color_setter_type setter;
+
+        getter.bind(&s_test_property6, &test_property6::getter);
+        setter.bind(&s_test_property6, &test_property6::setter);
+        holder->add_property(
+            "color",
+            "category",
+            "description",
+            s_test_property6.m_property,
+            getter,
+            setter
+        );
+    }
+
+    {
+        editor::property_holder::float_getter_type getter;
+        editor::property_holder::float_setter_type setter;
+
+        getter.bind(&s_test_property7_limited, &test_property7::getter);
+        setter.bind(&s_test_property7_limited, &test_property7::setter);
+        holder->add_property(
+            "float",
+            "category",
+            "description",
+            s_test_property7.m_property,
+            getter,
+            setter
+        );
+    }
+
+    {
+        editor::property_holder::float_getter_type getter;
+        editor::property_holder::float_setter_type setter;
+
+        getter.bind(&s_test_property7, &test_property7::getter);
+        setter.bind(&s_test_property7, &test_property7::setter);
+        holder->add_property(
+            "float_limited",
+            "category",
+            "description",
+            s_test_property7.m_property,
+            getter,
+            setter,
+            0.f,
+            1.f
+        );
+    }
+
+    {
+        editor::property_holder::float_getter_type getter;
+        editor::property_holder::float_setter_type setter;
+
+        getter.bind(&s_test_property7_values_enum, &test_property7::getter);
+        setter.bind(&s_test_property7_values_enum, &test_property7::setter);
+        holder->add_property(
+            "float_enum",
+            "category",
+            "description",
+            s_test_property7_values_enum.m_property,
+            getter,
+            setter,
+            s_properties7_enum,
+            3
+        );
+    }
 }
 #endif
diff --git a/src/xrEngine/editor_environment_sound_channels_channel.cpp b/src/xrEngine/editor_environment_sound_channels_channel.cpp
index edeaffd8db6..fef9d70e1af 100644
--- a/src/xrEngine/editor_environment_sound_channels_channel.cpp
+++ b/src/xrEngine/editor_environment_sound_channels_channel.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_sound_channels_channel.cpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment sound channels channel class
+// Module : editor_environment_sound_channels_channel.cpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment sound channels channel class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -20,178 +20,181 @@ using editor::environment::sound_channels::source;
 using editor::environment::sound_channels::manager;
 
 template <>
-void property_collection::display_name	(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
+void property_collection::display_name(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
 {
-	xr_strcpy				(buffer, buffer_size, m_container[item_index]->id());
+    xr_strcpy(buffer, buffer_size, m_container[item_index]->id());
 }
 
 template <>
-editor::property_holder* property_collection::create	()
+editor::property_holder* property_collection::create()
 {
-	source*					object = xr_new("");
-	object->fill			(this);
-	return					(object->object());
+    source* object = xr_new("");
+    object->fill(this);
+    return (object->object());
 }
 
-channel::channel			(manager const& manager, shared_str const& id) :
-	m_manager			(manager),
-	m_property_holder	(0),
-	m_collection		(0)
+channel::channel(manager const& manager, shared_str const& id) :
+    m_manager(manager),
+    m_property_holder(0),
+    m_collection(0)
 {
-	m_load_section		= id;
-	m_sound_dist		= Fvector2().set(0.f,0.f);
-	m_sound_period		= Ivector4().set(0,0,0,0);
-	m_collection		= xr_new(&m_sounds, this);
+    m_load_section = id;
+    m_sound_dist = Fvector2().set(0.f, 0.f);
+    m_sound_period = Ivector4().set(0, 0, 0, 0);
+    m_collection = xr_new(&m_sounds, this);
 }
 
-channel::~channel			()
+channel::~channel()
 {
-	xr_delete			(m_collection);
-	delete_data			(m_sounds);
+    xr_delete(m_collection);
+    delete_data(m_sounds);
 
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy		(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-void channel::load			(CInifile& config)
+void channel::load(CInifile& config)
 {
-	inherited::load		(config, m_load_section.c_str());
-
-	VERIFY				(m_sounds.empty());
-	LPCSTR sounds		= config.r_string		(m_load_section,	"sounds");
-	string_path			sound;
-	for (u32 i=0, n=_GetItemCount(sounds); i( _GetItem( sounds, i, sound ) );
-		object->fill		(m_collection);
-		m_sounds.push_back	(object);
-	}
+    inherited::load(config, m_load_section.c_str());
+
+    VERIFY(m_sounds.empty());
+    LPCSTR sounds = config.r_string(m_load_section, "sounds");
+    string_path sound;
+    for (u32 i = 0, n = _GetItemCount(sounds); i < n; ++i)
+    {
+        source* object = xr_new(_GetItem(sounds, i, sound));
+        object->fill(m_collection);
+        m_sounds.push_back(object);
+    }
 }
 
-void channel::save			(CInifile& config)
+void channel::save(CInifile& config)
 {
-	config.w_float		(m_load_section.c_str(), "min_distance",	m_sound_dist.x	);
-	config.w_float		(m_load_section.c_str(), "max_distance",	m_sound_dist.y	);
-	config.w_s32		(m_load_section.c_str(), "period0",			m_sound_period.x);
-	config.w_s32		(m_load_section.c_str(), "period1",			m_sound_period.y);
-	config.w_s32		(m_load_section.c_str(), "period2",			m_sound_period.z);
-	config.w_s32		(m_load_section.c_str(), "period3",			m_sound_period.w);
-
-	u32					count = 1;
-	sound_container_type::const_iterator	b = m_sounds.begin(), i = b;
-	sound_container_type::const_iterator	e = m_sounds.end();
-	for ( ; i != e; ++i)
-		count			+= xr_strlen((*i)->id()) + 2;
-
-	LPSTR				temp = (LPSTR)_alloca(count*sizeof(char));
-	*temp				= 0;
-	for (i = b; i != e; ++i) {
-		if (i == b) {
-			xr_strcpy	(temp, count, (*i)->id());
-			continue;
-		}
-
-		xr_strcat		(temp, count, ", ");
-		xr_strcat		(temp, count, (*i)->id());
-	}
-
-	config.w_string		(m_load_section.c_str(),	"sounds", temp);
+    config.w_float(m_load_section.c_str(), "min_distance", m_sound_dist.x);
+    config.w_float(m_load_section.c_str(), "max_distance", m_sound_dist.y);
+    config.w_s32(m_load_section.c_str(), "period0", m_sound_period.x);
+    config.w_s32(m_load_section.c_str(), "period1", m_sound_period.y);
+    config.w_s32(m_load_section.c_str(), "period2", m_sound_period.z);
+    config.w_s32(m_load_section.c_str(), "period3", m_sound_period.w);
+
+    u32 count = 1;
+    sound_container_type::const_iterator b = m_sounds.begin(), i = b;
+    sound_container_type::const_iterator e = m_sounds.end();
+    for (; i != e; ++i)
+        count += xr_strlen((*i)->id()) + 2;
+
+    LPSTR temp = (LPSTR)_alloca(count*sizeof(char));
+    *temp = 0;
+    for (i = b; i != e; ++i)
+    {
+        if (i == b)
+        {
+            xr_strcpy(temp, count, (*i)->id());
+            continue;
+        }
+
+        xr_strcat(temp, count, ", ");
+        xr_strcat(temp, count, (*i)->id());
+    }
+
+    config.w_string(m_load_section.c_str(), "sounds", temp);
 }
 
-LPCSTR channel::id_getter	() const
+LPCSTR channel::id_getter() const
 {
-	return				(m_load_section.c_str());
+    return (m_load_section.c_str());
 }
 
-void channel::id_setter		(LPCSTR value_)
+void channel::id_setter(LPCSTR value_)
 {
-	shared_str			value = value_;
-	if (m_load_section._get() == value._get())
-		return;
+    shared_str value = value_;
+    if (m_load_section._get() == value._get())
+        return;
 
-	m_load_section		= m_manager.unique_id(value);
+    m_load_section = m_manager.unique_id(value);
 }
 
-void channel::fill			(editor::property_holder_collection* collection)
+void channel::fill(editor::property_holder_collection* collection)
 {
-	VERIFY				(!m_property_holder);
-	m_property_holder	= ::ide().create_property_holder(m_load_section.c_str(), collection, this);
-
-	typedef editor::property_holder::string_getter_type	string_getter_type;
-	string_getter_type	string_getter;
-	string_getter.bind	(this, &channel::id_getter);
-
-	typedef editor::property_holder::string_setter_type	string_setter_type;
-	string_setter_type	string_setter;
-	string_setter.bind	(this, &channel::id_setter);
-
-	m_property_holder->add_property	(
-		"id",
-		"properties",
-		"this option is resposible for sound channel id",
-		m_load_section.c_str(),
-		string_getter,
-		string_setter
-	);
-	m_property_holder->add_property	(
-		"minimum distance",
-		"properties",
-		"this option is resposible for minimum distance (in meters)",
-		m_sound_dist.x,
-		m_sound_dist.x
-	);
-	m_property_holder->add_property	(
-		"maximum distance",
-		"properties",
-		"this option is resposible for maximum distance (in meters)",
-		m_sound_dist.y,
-		m_sound_dist.y
-	);
-	m_property_holder->add_property	(
-		"period 0",
-		"properties",
-		"this option is resposible for minimum start time interval (in seconds)",
-		m_sound_period.x,
-		m_sound_period.x
-	);
-	m_property_holder->add_property	(
-		"period 1",
-		"properties",
-		"this option is resposible for maximum start time interval (in seconds)",
-		m_sound_period.y,
-		m_sound_period.y
-	);
-	m_property_holder->add_property	(
-		"period 2",
-		"properties",
-		"this option is resposible for minimum pause interval (in seconds)",
-		m_sound_period.z,
-		m_sound_period.z
-	);
-	m_property_holder->add_property	(
-		"period 3",
-		"properties",
-		"this option is resposible for maximum pause interval (in seconds)",
-		m_sound_period.w,
-		m_sound_period.w
-	);
-	m_property_holder->add_property	(
-		"sounds",
-		"properties",
-		"this option is resposible for sound sources",
-		m_collection
-	);
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder(m_load_section.c_str(), collection, this);
+
+    typedef editor::property_holder::string_getter_type string_getter_type;
+    string_getter_type string_getter;
+    string_getter.bind(this, &channel::id_getter);
+
+    typedef editor::property_holder::string_setter_type string_setter_type;
+    string_setter_type string_setter;
+    string_setter.bind(this, &channel::id_setter);
+
+    m_property_holder->add_property(
+        "id",
+        "properties",
+        "this option is resposible for sound channel id",
+        m_load_section.c_str(),
+        string_getter,
+        string_setter
+    );
+    m_property_holder->add_property(
+        "minimum distance",
+        "properties",
+        "this option is resposible for minimum distance (in meters)",
+        m_sound_dist.x,
+        m_sound_dist.x
+    );
+    m_property_holder->add_property(
+        "maximum distance",
+        "properties",
+        "this option is resposible for maximum distance (in meters)",
+        m_sound_dist.y,
+        m_sound_dist.y
+    );
+    m_property_holder->add_property(
+        "period 0",
+        "properties",
+        "this option is resposible for minimum start time interval (in seconds)",
+        m_sound_period.x,
+        m_sound_period.x
+    );
+    m_property_holder->add_property(
+        "period 1",
+        "properties",
+        "this option is resposible for maximum start time interval (in seconds)",
+        m_sound_period.y,
+        m_sound_period.y
+    );
+    m_property_holder->add_property(
+        "period 2",
+        "properties",
+        "this option is resposible for minimum pause interval (in seconds)",
+        m_sound_period.z,
+        m_sound_period.z
+    );
+    m_property_holder->add_property(
+        "period 3",
+        "properties",
+        "this option is resposible for maximum pause interval (in seconds)",
+        m_sound_period.w,
+        m_sound_period.w
+    );
+    m_property_holder->add_property(
+        "sounds",
+        "properties",
+        "this option is resposible for sound sources",
+        m_collection
+    );
 }
 
-channel::property_holder_type* channel::object	()
+channel::property_holder_type* channel::object()
 {
-	return				(m_property_holder);
+    return (m_property_holder);
 }
 
-CEnvAmbient::SSndChannel::sounds_type& channel::sounds	()
+CEnvAmbient::SSndChannel::sounds_type& channel::sounds()
 {
-	return				(inherited::sounds());
+    return (inherited::sounds());
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_sound_channels_channel.hpp b/src/xrEngine/editor_environment_sound_channels_channel.hpp
index 77037238ac4..3d90d6777cc 100644
--- a/src/xrEngine/editor_environment_sound_channels_channel.hpp
+++ b/src/xrEngine/editor_environment_sound_channels_channel.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_sound_channels_channel.hpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment sound channels channel class
+// Module : editor_environment_sound_channels_channel.hpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment sound channels channel class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_SOUND_CHANNELS_CHANNEL_HPP_INCLUDED
@@ -16,54 +16,57 @@
 #include "property_collection_forward.hpp"
 #include "environment.h"
 
-namespace editor {
+namespace editor
+{
 
 class property_holder_collection;
 
-namespace environment {
-namespace sound_channels {
+namespace environment
+{
+namespace sound_channels
+{
 
 class source;
 class manager;
 
 class channel :
-	public CEnvAmbient::SSndChannel,
-	public editor::property_holder_holder,
-	private boost::noncopyable
+    public CEnvAmbient::SSndChannel,
+    public editor::property_holder_holder,
+    private boost::noncopyable
 {
 private:
-	typedef CEnvAmbient::SSndChannel	inherited;
+    typedef CEnvAmbient::SSndChannel inherited;
 
 public:
-							channel		(manager const& manager, shared_str const& id);
-	virtual					~channel	();
-			void			load		(CInifile& config);
-			void			save		(CInifile& config);
-			void			fill		(editor::property_holder_collection* collection);
-	inline	LPCSTR			id			() const { return m_load_section.c_str(); }
-	virtual	sounds_type&	sounds		();
+    channel(manager const& manager, shared_str const& id);
+    virtual ~channel();
+    void load(CInifile& config);
+    void save(CInifile& config);
+    void fill(editor::property_holder_collection* collection);
+    inline LPCSTR id() const { return m_load_section.c_str(); }
+    virtual sounds_type& sounds();
 
 private:
-			LPCSTR xr_stdcall id_getter	() const;
-			void   xr_stdcall id_setter	(LPCSTR value);
+    LPCSTR xr_stdcall id_getter() const;
+    void xr_stdcall id_setter(LPCSTR value);
 public:
-	typedef xr_vector			sound_container_type;
+    typedef xr_vector sound_container_type;
 
 private:
-	typedef editor::property_holder		property_holder_type;
-	typedef property_collection<
-				sound_container_type,
-				channel
-			>							collection_type;
+    typedef editor::property_holder property_holder_type;
+    typedef property_collection <
+    sound_container_type,
+    channel
+    > collection_type;
 
 public:
-	virtual	property_holder_type*	object	();
+    virtual property_holder_type* object();
 
 private:
-	manager const&			m_manager;
-	property_holder_type*	m_property_holder;
-	collection_type*		m_collection;
-	sound_container_type	m_sounds;
+    manager const& m_manager;
+    property_holder_type* m_property_holder;
+    collection_type* m_collection;
+    sound_container_type m_sounds;
 }; // class channel
 } // namespace sound_channels
 } // namespace environment
diff --git a/src/xrEngine/editor_environment_sound_channels_manager.cpp b/src/xrEngine/editor_environment_sound_channels_manager.cpp
index a1aeba23ea2..683a7ab5d1f 100644
--- a/src/xrEngine/editor_environment_sound_channels_manager.cpp
+++ b/src/xrEngine/editor_environment_sound_channels_manager.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_sound_channels_manager.cpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment sound channels manager class
+// Module : editor_environment_sound_channels_manager.cpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment sound channels manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -19,127 +19,128 @@ using editor::environment::sound_channels::channel;
 using editor::environment::detail::logical_string_predicate;
 
 template <>
-void property_collection::display_name	(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
+void property_collection::display_name(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
 {
-	xr_strcpy				(buffer, buffer_size, m_container[item_index]->id());
+    xr_strcpy(buffer, buffer_size, m_container[item_index]->id());
 }
 
 template <>
-editor::property_holder* property_collection::create	()
+editor::property_holder* property_collection::create()
 {
-	channel*				object = xr_new(m_holder, generate_unique_id("sound_channel_unique_id_").c_str());
-	object->fill			(this);
-	return					(object->object());
+    channel* object = xr_new(m_holder, generate_unique_id("sound_channel_unique_id_").c_str());
+    object->fill(this);
+    return (object->object());
 }
 
-manager::manager			() :
-	m_collection			(0),
-	m_changed				(true)
+manager::manager() :
+    m_collection(0),
+    m_changed(true)
 {
-	m_collection			= xr_new(&m_channels, this, &m_changed);
+    m_collection = xr_new(&m_channels, this, &m_changed);
 }
 
-manager::~manager			()
+manager::~manager()
 {
-	xr_delete				(m_collection);
-	delete_data				(m_channels);
-	delete_data				(m_channels_ids);
+    xr_delete(m_collection);
+    delete_data(m_channels);
+    delete_data(m_channels_ids);
 }
 
-void manager::load			()
+void manager::load()
 {
-	string_path				file_name;
-	CInifile*				config =
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\sound_channels.ltx"
-			),
-			TRUE,
-			TRUE,
-			FALSE
-		);
-
-	VERIFY					(m_channels.empty());
-
-	typedef CInifile::Root	sections_type;
-	sections_type&			sections = config->sections();
-	m_channels.reserve		(sections.size());
-	sections_type::const_iterator	i = sections.begin();
-	sections_type::const_iterator	e = sections.end();
-	for ( ; i != e; ++i) {
-		channel*			object = xr_new(*this, (*i)->Name);
-		object->load		(*config);
-		object->fill		(m_collection);
-		m_channels.push_back(object);
-	}
-
-	xr_delete				(config);
+    string_path file_name;
+    CInifile* config =
+        xr_new(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "environment\\sound_channels.ltx"
+            ),
+            TRUE,
+            TRUE,
+            FALSE
+        );
+
+    VERIFY(m_channels.empty());
+
+    typedef CInifile::Root sections_type;
+    sections_type& sections = config->sections();
+    m_channels.reserve(sections.size());
+    sections_type::const_iterator i = sections.begin();
+    sections_type::const_iterator e = sections.end();
+    for (; i != e; ++i)
+    {
+        channel* object = xr_new(*this, (*i)->Name);
+        object->load(*config);
+        object->fill(m_collection);
+        m_channels.push_back(object);
+    }
+
+    xr_delete(config);
 }
 
-void manager::save			()
+void manager::save()
 {
-	string_path				file_name;
-	CInifile*				config =
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\sound_channels.ltx"
-			),
-			FALSE,
-			FALSE,
-			TRUE
-		);
-
-	channel_container_type::iterator	i = m_channels.begin();
-	channel_container_type::iterator	e = m_channels.end();
-	for ( ; i != e; ++i)
-		(*i)->save			(*config);
-
-	xr_delete				(config);
+    string_path file_name;
+    CInifile* config =
+        xr_new(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "environment\\sound_channels.ltx"
+            ),
+            FALSE,
+            FALSE,
+            TRUE
+        );
+
+    channel_container_type::iterator i = m_channels.begin();
+    channel_container_type::iterator e = m_channels.end();
+    for (; i != e; ++i)
+        (*i)->save(*config);
+
+    xr_delete(config);
 }
 
-void manager::fill			(editor::property_holder* holder)
+void manager::fill(editor::property_holder* holder)
 {
-	VERIFY					(holder);
-	holder->add_property	(
-		"sound channels",
-		"ambients",
-		"this option is resposible for sound channels",
-		m_collection
-	);
+    VERIFY(holder);
+    holder->add_property(
+        "sound channels",
+        "ambients",
+        "this option is resposible for sound channels",
+        m_collection
+    );
 }
 
-manager::channels_ids_type const& manager::channels_ids	() const
+manager::channels_ids_type const& manager::channels_ids() const
 {
-	if (!m_changed)
-		return				(m_channels_ids);
+    if (!m_changed)
+        return (m_channels_ids);
 
-	m_changed				= false;
+    m_changed = false;
 
-	delete_data				(m_channels_ids);
+    delete_data(m_channels_ids);
 
-	m_channels_ids.resize	(m_channels.size());
+    m_channels_ids.resize(m_channels.size());
 
-	channel_container_type::const_iterator	i = m_channels.begin();
-	channel_container_type::const_iterator	e = m_channels.end();
-	channels_ids_type::iterator				j = m_channels_ids.begin();
-	for ( ; i != e; ++i, ++j)
-		*j					= xr_strdup((*i)->id());
+    channel_container_type::const_iterator i = m_channels.begin();
+    channel_container_type::const_iterator e = m_channels.end();
+    channels_ids_type::iterator j = m_channels_ids.begin();
+    for (; i != e; ++i, ++j)
+        *j = xr_strdup((*i)->id());
 
-	std::sort				(m_channels_ids.begin(), m_channels_ids.end(), logical_string_predicate());
+    std::sort(m_channels_ids.begin(), m_channels_ids.end(), logical_string_predicate());
 
-	return					(m_channels_ids);
+    return (m_channels_ids);
 }
 
-shared_str manager::unique_id	(shared_str const& id) const
+shared_str manager::unique_id(shared_str const& id) const
 {
-	if (m_collection->unique_id(id.c_str()))
-		return				(id);
+    if (m_collection->unique_id(id.c_str()))
+        return (id);
 
-	return					(m_collection->generate_unique_id(id.c_str()));
+    return (m_collection->generate_unique_id(id.c_str()));
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_sound_channels_manager.hpp b/src/xrEngine/editor_environment_sound_channels_manager.hpp
index 01d2263fcb5..a92a0cdb2ce 100644
--- a/src/xrEngine/editor_environment_sound_channels_manager.hpp
+++ b/src/xrEngine/editor_environment_sound_channels_manager.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_sound_channels_manager.hpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment sound channels manager class
+// Module : editor_environment_sound_channels_manager.hpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment sound channels manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_SOUND_CHANNELS_MANAGER_HPP_INCLUDED
@@ -14,44 +14,48 @@
 #include 
 #include "property_collection_forward.hpp"
 
-namespace editor {
+namespace editor
+{
 
 class property_holder;
 
-namespace environment {
-namespace sound_channels {
+namespace environment
+{
+namespace sound_channels
+{
 
 class channel;
 
-class manager : private boost::noncopyable {
+class manager : private boost::noncopyable
+{
 public:
-							manager		();
-							~manager	();
-			void			load		();
-			void			save		();
-			void			fill		(editor::property_holder* holder);
-			shared_str		unique_id	(shared_str const& id) const;
+    manager();
+    ~manager();
+    void load();
+    void save();
+    void fill(editor::property_holder* holder);
+    shared_str unique_id(shared_str const& id) const;
 
 public:
-	typedef xr_vector			channel_container_type;
-	typedef xr_vector			channels_ids_type;
+    typedef xr_vector channel_container_type;
+    typedef xr_vector channels_ids_type;
 
 public:
-	channels_ids_type const&channels_ids() const;
+    channels_ids_type const& channels_ids() const;
 
 private:
-	typedef editor::property_holder		property_holder_type;
-	typedef property_collection<
-				channel_container_type,
-				manager
-			>							collection_type;
+    typedef editor::property_holder property_holder_type;
+    typedef property_collection <
+    channel_container_type,
+    manager
+    > collection_type;
 
 private:
-	channel_container_type				m_channels;
-	mutable channels_ids_type			m_channels_ids;
-	property_holder_type*				m_property_holder;
-	collection_type*					m_collection;
-	mutable bool						m_changed;
+    channel_container_type m_channels;
+    mutable channels_ids_type m_channels_ids;
+    property_holder_type* m_property_holder;
+    collection_type* m_collection;
+    mutable bool m_changed;
 }; // class manager
 } // namespace sound_channels
 } // namespace environment
diff --git a/src/xrEngine/editor_environment_sound_channels_source.cpp b/src/xrEngine/editor_environment_sound_channels_source.cpp
index ae7212b6b94..6e709ab3279 100644
--- a/src/xrEngine/editor_environment_sound_channels_source.cpp
+++ b/src/xrEngine/editor_environment_sound_channels_source.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_sound_channels_source.cpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment sound channels source class
+// Module : editor_environment_sound_channels_source.cpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment sound channels source class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -15,43 +15,43 @@
 
 using editor::environment::sound_channels::source;
 
-source::source				(shared_str const& source) :
-	m_source			(source),
-	m_property_holder	(0)
+source::source(shared_str const& source) :
+    m_source(source),
+    m_property_holder(0)
 {
 }
 
-source::~source				()
+source::~source()
 {
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy		(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-void source::fill			(editor::property_holder_collection* collection)
+void source::fill(editor::property_holder_collection* collection)
 {
-	VERIFY				(!m_property_holder);
-	m_property_holder	= ::ide().create_property_holder(m_source.c_str(), collection, this);
-
-	m_property_holder->add_property(
-		"sound",
-		"properties",
-		"this option is resposible for sound",
-		m_source.c_str(),
-		m_source,
-		".ogg",
-		"Sound files (*.ogg)|*.ogg",
-		detail::real_path("$game_sounds$", "").c_str(),
-		"Select sound...",
-		editor::property_holder::cannot_enter_text,
-		editor::property_holder::remove_extension
-	);
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder(m_source.c_str(), collection, this);
+
+    m_property_holder->add_property(
+        "sound",
+        "properties",
+        "this option is resposible for sound",
+        m_source.c_str(),
+        m_source,
+        ".ogg",
+        "Sound files (*.ogg)|*.ogg",
+        detail::real_path("$game_sounds$", "").c_str(),
+        "Select sound...",
+        editor::property_holder::cannot_enter_text,
+        editor::property_holder::remove_extension
+    );
 }
 
 source::property_holder_type* source::object()
 {
-	return				(m_property_holder);
+    return (m_property_holder);
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_sound_channels_source.hpp b/src/xrEngine/editor_environment_sound_channels_source.hpp
index ecdcaa99696..7f9c5da4738 100644
--- a/src/xrEngine/editor_environment_sound_channels_source.hpp
+++ b/src/xrEngine/editor_environment_sound_channels_source.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_sound_channels_source.hpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment sound channels source class
+// Module : editor_environment_sound_channels_source.hpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment sound channels source class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_SOUND_CHANNELS_SOURCE_HPP_INCLUDED
@@ -14,31 +14,35 @@
 #include 
 #include "../include/editor/property_holder.hpp"
 
-namespace editor {
+namespace editor
+{
 
 class property_holder_collection;
 
-namespace environment {
-namespace sound_channels {
+namespace environment
+{
+namespace sound_channels
+{
 
 class source :
-	public editor::property_holder_holder,
-	private boost::noncopyable {
+    public editor::property_holder_holder,
+    private boost::noncopyable
+{
 public:
-							source		(shared_str const& source);
-							~source		();
-			void			fill		(editor::property_holder_collection* collection);
-	inline	LPCSTR			id			() const { return m_source.c_str(); }
+    source(shared_str const& source);
+    ~source();
+    void fill(editor::property_holder_collection* collection);
+    inline LPCSTR id() const { return m_source.c_str(); }
 
 private:
-	typedef editor::property_holder		property_holder_type;
+    typedef editor::property_holder property_holder_type;
 
 public:
-	virtual	property_holder_type* object();
+    virtual property_holder_type* object();
 
 private:
-	property_holder_type*	m_property_holder;
-	shared_str				m_source;
+    property_holder_type* m_property_holder;
+    shared_str m_source;
 }; // class source
 } // namespace sound_channels
 } // namespace environment
diff --git a/src/xrEngine/editor_environment_suns_blend.cpp b/src/xrEngine/editor_environment_suns_blend.cpp
index f6e33e4e8f4..e250cf7ab11 100644
--- a/src/xrEngine/editor_environment_suns_blend.cpp
+++ b/src/xrEngine/editor_environment_suns_blend.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_suns_blend.cpp
-//	Created 	: 26.01.2008
-//  Modified 	: 26.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment suns blend class
+// Module : editor_environment_suns_blend.cpp
+// Created : 26.01.2008
+// Modified : 26.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment suns blend class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -15,46 +15,46 @@
 using editor::environment::suns::blend;
 using editor::environment::suns::manager;
 
-blend::blend		() :
-    m_down_time	(0.f),
-    m_rise_time	(0.f),
-    m_time		(0.f)
+blend::blend() :
+    m_down_time(0.f),
+    m_rise_time(0.f),
+    m_time(0.f)
 {
 }
 
-void blend::load	(CInifile& config, shared_str const& section)
+void blend::load(CInifile& config, shared_str const& section)
 {
-    m_down_time	=   READ_IF_EXISTS(&config, r_float,	section, "blend_down_time",	60.f);
-    m_rise_time	=   READ_IF_EXISTS(&config, r_float,	section, "blend_rise_time",	60.f);
-    m_time		=   READ_IF_EXISTS(&config, r_float,	section, "blend_time",		.1f);
+    m_down_time = READ_IF_EXISTS(&config, r_float, section, "blend_down_time", 60.f);
+    m_rise_time = READ_IF_EXISTS(&config, r_float, section, "blend_rise_time", 60.f);
+    m_time = READ_IF_EXISTS(&config, r_float, section, "blend_time", .1f);
 }
 
-void blend::fill	(manager const& manager, editor::property_holder* holder, editor::property_holder_collection* collection)
+void blend::fill(manager const& manager, editor::property_holder* holder, editor::property_holder_collection* collection)
 {
-	editor::property_holder*	properties = holder;
-	VERIFY						(properties);
-
-	properties->add_property	(
-		"down time",
-		"blend",
-		"this option is resposible for the blend down time",
-		m_down_time,
-		m_down_time
-	);
-	properties->add_property	(
-		"rise time",
-		"blend",
-		"this option is resposible for the blend rise time",
-		m_rise_time,
-		m_rise_time
-	);
-	properties->add_property	(
-		"time",
-		"blend",
-		"this option is resposible for the blend time",
-		m_time,
-		m_time
-	);
+    editor::property_holder* properties = holder;
+    VERIFY(properties);
+
+    properties->add_property(
+        "down time",
+        "blend",
+        "this option is resposible for the blend down time",
+        m_down_time,
+        m_down_time
+    );
+    properties->add_property(
+        "rise time",
+        "blend",
+        "this option is resposible for the blend rise time",
+        m_rise_time,
+        m_rise_time
+    );
+    properties->add_property(
+        "time",
+        "blend",
+        "this option is resposible for the blend time",
+        m_time,
+        m_time
+    );
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_suns_blend.hpp b/src/xrEngine/editor_environment_suns_blend.hpp
index a6745e9aca6..3b18ecb6429 100644
--- a/src/xrEngine/editor_environment_suns_blend.hpp
+++ b/src/xrEngine/editor_environment_suns_blend.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_suns_blend.hpp
-//	Created 	: 26.01.2008
-//  Modified 	: 26.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment suns blend class
+// Module : editor_environment_suns_blend.hpp
+// Created : 26.01.2008
+// Modified : 26.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment suns blend class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_SUNS_BLEND_HPP_INCLUDED
@@ -13,27 +13,31 @@
 
 #include 
 
-namespace editor {
+namespace editor
+{
 
 class property_holder;
 class property_holder_collection;
 
-namespace environment {
-namespace suns {
+namespace environment
+{
+namespace suns
+{
 
 class manager;
 
-class blend : private boost::noncopyable {
+class blend : private boost::noncopyable
+{
 public:
-					blend		();
-			void	load		(CInifile& config, shared_str const& section);
-			void	save		(CInifile& config, shared_str const& section);
-			void	fill		(manager const& manager, editor::property_holder* holder, editor::property_holder_collection* collection);
+    blend();
+    void load(CInifile& config, shared_str const& section);
+    void save(CInifile& config, shared_str const& section);
+    void fill(manager const& manager, editor::property_holder* holder, editor::property_holder_collection* collection);
 
 private:
-    float			m_down_time;
-    float			m_rise_time;
-    float			m_time;
+    float m_down_time;
+    float m_rise_time;
+    float m_time;
 }; // class blend
 
 } // namespace suns
diff --git a/src/xrEngine/editor_environment_suns_flare.cpp b/src/xrEngine/editor_environment_suns_flare.cpp
index c380c44f9a7..e632f57f9af 100644
--- a/src/xrEngine/editor_environment_suns_flare.cpp
+++ b/src/xrEngine/editor_environment_suns_flare.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_suns_flare.cpp
-//	Created 	: 13.12.2007
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment suns flare class
+// Module : editor_environment_suns_flare.cpp
+// Created : 13.12.2007
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment suns flare class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -17,68 +17,68 @@
 using editor::environment::suns::flare;
 using editor::property_holder;
 
-flare::flare			() :
-	m_property_holder	(0),
-	m_opacity			(0.f),
-	m_position			(0.f),
-	m_radius			(0.f),
-	m_texture			("")
+flare::flare() :
+    m_property_holder(0),
+    m_opacity(0.f),
+    m_position(0.f),
+    m_radius(0.f),
+    m_texture("")
 {
 }
 
-flare::~flare			()
+flare::~flare()
 {
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy		(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-editor::property_holder*	flare::object	()
+editor::property_holder* flare::object()
 {
-	return				(m_property_holder);
+    return (m_property_holder);
 }
 
-void flare::fill		(editor::property_holder_collection* collection)
+void flare::fill(editor::property_holder_collection* collection)
 {
-	VERIFY				(!m_property_holder);
-	m_property_holder	= ::ide().create_property_holder("flare", collection, this);
-	property_holder*	properties = m_property_holder;
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder("flare", collection, this);
+    property_holder* properties = m_property_holder;
 
-	properties->add_property(
-		"texture",
-		"flare",
-		"this option is resposible for gradient texture",
-		m_texture.c_str(),
-		m_texture,
-		".dds",
-		"Texture files (*.dds)|*.dds",
-		detail::real_path("$game_textures$", "").c_str(),
-		"Select texture...",
-		editor::property_holder::cannot_enter_text,
-		editor::property_holder::remove_extension
-	);
-	properties->add_property(
-		"opacity",
-		"flare",
-		"this option is resposible for gradient opacity",
-		m_opacity,
-		m_opacity
-	);
-	properties->add_property(
-		"position",
-		"flare",
-		"this option is resposible for gradient position",
-		m_position,
-		m_position
-	);
-	properties->add_property(
-		"radius",
-		"flare",
-		"this option is resposible for gradient radius",
-		m_radius,
-		m_radius
-	);
+    properties->add_property(
+        "texture",
+        "flare",
+        "this option is resposible for gradient texture",
+        m_texture.c_str(),
+        m_texture,
+        ".dds",
+        "Texture files (*.dds)|*.dds",
+        detail::real_path("$game_textures$", "").c_str(),
+        "Select texture...",
+        editor::property_holder::cannot_enter_text,
+        editor::property_holder::remove_extension
+    );
+    properties->add_property(
+        "opacity",
+        "flare",
+        "this option is resposible for gradient opacity",
+        m_opacity,
+        m_opacity
+    );
+    properties->add_property(
+        "position",
+        "flare",
+        "this option is resposible for gradient position",
+        m_position,
+        m_position
+    );
+    properties->add_property(
+        "radius",
+        "flare",
+        "this option is resposible for gradient radius",
+        m_radius,
+        m_radius
+    );
 }
-	
+
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_suns_flare.hpp b/src/xrEngine/editor_environment_suns_flare.hpp
index 80abdb37c10..2ac60ea5fd5 100644
--- a/src/xrEngine/editor_environment_suns_flare.hpp
+++ b/src/xrEngine/editor_environment_suns_flare.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_suns_flare.hpp
-//	Created 	: 13.12.2007
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment suns flare class
+// Module : editor_environment_suns_flare.hpp
+// Created : 13.12.2007
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment suns flare class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_FLARE_HPP_INCLUDED
@@ -14,33 +14,36 @@
 #include 
 #include "../include/editor/property_holder.hpp"
 
-namespace editor {
-namespace environment {
-namespace suns {
+namespace editor
+{
+namespace environment
+{
+namespace suns
+{
 
 class flare :
-	public editor::property_holder_holder,
-	private boost::noncopyable
+    public editor::property_holder_holder,
+    private boost::noncopyable
 {
 public:
-						flare		();
-	virtual				~flare		();
-			void		fill		(editor::property_holder_collection* collection);
+    flare();
+    virtual ~flare();
+    void fill(editor::property_holder_collection* collection);
 
 public:
-	typedef editor::property_holder	property_holder;
+    typedef editor::property_holder property_holder;
 
 public:
-	virtual	property_holder*object	();
+    virtual property_holder* object();
 
 private:
-	property_holder*	m_property_holder;
+    property_holder* m_property_holder;
 
 public:
-	shared_str			m_texture;
-    float				m_opacity;
-    float				m_position;
-    float				m_radius;
+    shared_str m_texture;
+    float m_opacity;
+    float m_position;
+    float m_radius;
 }; // class flare
 
 } // namespace suns
diff --git a/src/xrEngine/editor_environment_suns_flares.cpp b/src/xrEngine/editor_environment_suns_flares.cpp
index 3fcb5286bbb..396fd1913e8 100644
--- a/src/xrEngine/editor_environment_suns_flares.cpp
+++ b/src/xrEngine/editor_environment_suns_flares.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_suns_flares.cpp
-//	Created 	: 26.01.2008
-//  Modified 	: 26.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment suns flares class
+// Module : editor_environment_suns_flares.cpp
+// Created : 26.01.2008
+// Modified : 26.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment suns flares class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -21,106 +21,107 @@ using editor::environment::suns::manager;
 using editor::environment::suns::flare;
 
 template <>
-void property_collection::display_name	(
-		u32 const& item_index,
-		LPSTR const& buffer,
-		u32 const& buffer_size
-	)
+void property_collection::display_name(
+    u32 const& item_index,
+    LPSTR const& buffer,
+    u32 const& buffer_size
+)
 {
-	float					position = m_container[item_index]->m_position;
-	xr_sprintf				(buffer, buffer_size, "flare [%f]", position);
+    float position = m_container[item_index]->m_position;
+    xr_sprintf(buffer, buffer_size, "flare [%f]", position);
 }
 
 template <>
-editor::property_holder* property_collection::create	()
+editor::property_holder* property_collection::create()
 {
-	flare*					object = xr_new();
-	object->fill			(this);
-	return					(object->object());
+    flare* object = xr_new();
+    object->fill(this);
+    return (object->object());
 }
 
-flares::flares		() :
-    m_use					(false),
-    m_shader				(""),
-	m_collection			(0)
+flares::flares() :
+    m_use(false),
+    m_shader(""),
+    m_collection(0)
 {
-	m_collection			= xr_new(&m_flares, this);
+    m_collection = xr_new(&m_flares, this);
 }
 
-flares::~flares		()
+flares::~flares()
 {
-	xr_delete				(m_collection);
-	delete_data				(m_flares);
+    xr_delete(m_collection);
+    delete_data(m_flares);
 }
 
-void flares::load	(CInifile& config, shared_str const& section)
+void flares::load(CInifile& config, shared_str const& section)
 {
-    m_use					= !!READ_IF_EXISTS(&config, r_bool,	  section, "flares",		true);
-    m_shader				=   READ_IF_EXISTS(&config, r_string, section, "flare_shader",	"effects\\flare");
-
-	if (!m_use)
-		return;
-
-	shared_str				flare_opacity  = READ_IF_EXISTS(&config, r_string, section, "flare_opacity",	"0.340, 0.260, 0.500, 0.420, 0.260, 0.260");
-	shared_str				flare_position = READ_IF_EXISTS(&config, r_string, section, "flare_position",	"1.300, 1.000, 0.500, -0.300, -0.600, -1.000");
-	shared_str				flare_radius   = READ_IF_EXISTS(&config, r_string, section, "flare_radius",		"0.080, 0.120, 0.040, 0.080, 0.120, 0.300");
-	shared_str				flare_textures = READ_IF_EXISTS(&config, r_string, section, "flare_textures",	"fx\\fx_flare1.tga, fx\\fx_flare2.tga, fx\\fx_flare2.tga, fx\\fx_flare2.tga, fx\\fx_flare3.tga, fx\\fx_flare1.tga");
-
-	u32						opacity_count  = _GetItemCount(flare_opacity  .c_str());
-	u32						position_count = _GetItemCount(flare_position .c_str());
-	u32						radius_count   = _GetItemCount(flare_radius   .c_str());
-	u32						texture_count  = _GetItemCount(flare_textures .c_str());
-
-	u32						min_flare_count = _min(_min(_min(opacity_count, position_count), radius_count), texture_count);
-	u32						max_flare_count = _max(_max(_max(opacity_count, position_count), radius_count), texture_count);
-
-	u32						max_string_count= _max(_max(_max(flare_opacity.size(), flare_position.size()), flare_radius.size()), flare_textures.size()) + 1;
-
-	if (min_flare_count != max_flare_count)
-		Msg					("! flare count for sun [%s] is setup incorrectly. only %d flares are correct", section.c_str(), min_flare_count);
-
-	u32 const buffer_size	= max_string_count*sizeof(char);
-	LPSTR					result = (LPSTR)_alloca(buffer_size);
-	for (u32 i=0; i();
-		object->m_opacity	= (float)atof(_GetItem(flare_opacity  .c_str(), i, result, buffer_size));
-		object->m_position	= (float)atof(_GetItem(flare_position .c_str(), i, result, buffer_size));
-		object->m_radius	= (float)atof(_GetItem(flare_radius   .c_str(), i, result, buffer_size));
-		object->m_texture	=			  _GetItem(flare_textures .c_str(), i, result, buffer_size);
-		object->fill		(m_collection);
-		m_flares.push_back	(object);
-	}
+    m_use = !!READ_IF_EXISTS(&config, r_bool, section, "flares", true);
+    m_shader = READ_IF_EXISTS(&config, r_string, section, "flare_shader", "effects\\flare");
+
+    if (!m_use)
+        return;
+
+    shared_str flare_opacity = READ_IF_EXISTS(&config, r_string, section, "flare_opacity", "0.340, 0.260, 0.500, 0.420, 0.260, 0.260");
+    shared_str flare_position = READ_IF_EXISTS(&config, r_string, section, "flare_position", "1.300, 1.000, 0.500, -0.300, -0.600, -1.000");
+    shared_str flare_radius = READ_IF_EXISTS(&config, r_string, section, "flare_radius", "0.080, 0.120, 0.040, 0.080, 0.120, 0.300");
+    shared_str flare_textures = READ_IF_EXISTS(&config, r_string, section, "flare_textures", "fx\\fx_flare1.tga, fx\\fx_flare2.tga, fx\\fx_flare2.tga, fx\\fx_flare2.tga, fx\\fx_flare3.tga, fx\\fx_flare1.tga");
+
+    u32 opacity_count = _GetItemCount(flare_opacity.c_str());
+    u32 position_count = _GetItemCount(flare_position.c_str());
+    u32 radius_count = _GetItemCount(flare_radius.c_str());
+    u32 texture_count = _GetItemCount(flare_textures.c_str());
+
+    u32 min_flare_count = _min(_min(_min(opacity_count, position_count), radius_count), texture_count);
+    u32 max_flare_count = _max(_max(_max(opacity_count, position_count), radius_count), texture_count);
+
+    u32 max_string_count = _max(_max(_max(flare_opacity.size(), flare_position.size()), flare_radius.size()), flare_textures.size()) + 1;
+
+    if (min_flare_count != max_flare_count)
+        Msg("! flare count for sun [%s] is setup incorrectly. only %d flares are correct", section.c_str(), min_flare_count);
+
+    u32 const buffer_size = max_string_count*sizeof(char);
+    LPSTR result = (LPSTR)_alloca(buffer_size);
+    for (u32 i = 0; i < min_flare_count; ++i)
+    {
+        flare* object = xr_new();
+        object->m_opacity = (float)atof(_GetItem(flare_opacity.c_str(), i, result, buffer_size));
+        object->m_position = (float)atof(_GetItem(flare_position.c_str(), i, result, buffer_size));
+        object->m_radius = (float)atof(_GetItem(flare_radius.c_str(), i, result, buffer_size));
+        object->m_texture = _GetItem(flare_textures.c_str(), i, result, buffer_size);
+        object->fill(m_collection);
+        m_flares.push_back(object);
+    }
 }
 
-void flares::fill	(manager const& manager, editor::property_holder* holder, editor::property_holder_collection* collection)
+void flares::fill(manager const& manager, editor::property_holder* holder, editor::property_holder_collection* collection)
 {
-	editor::property_holder*properties = holder;
-	VERIFY					(properties);
-
-	properties->add_property(
-		"use",
-		"flares",
-		"this option is resposible for the flares usage",
-		m_use,
-		m_use
-	);
-	properties->add_property(
-		"shader",
-		"flares",
-		"this option is resposible for flares shader",
-		m_shader.c_str(),
-		m_shader,
-		&*manager.m_environment.shader_ids().begin(),
-		manager.m_environment.shader_ids().size(),
-		editor::property_holder::value_editor_tree_view,
-		editor::property_holder::cannot_enter_text
-	);
-	properties->add_property(
-		"flares",
-		"flares",
-		"this option is resposible for flares",
-		m_collection
-	);
+    editor::property_holder* properties = holder;
+    VERIFY(properties);
+
+    properties->add_property(
+        "use",
+        "flares",
+        "this option is resposible for the flares usage",
+        m_use,
+        m_use
+    );
+    properties->add_property(
+        "shader",
+        "flares",
+        "this option is resposible for flares shader",
+        m_shader.c_str(),
+        m_shader,
+        &*manager.m_environment.shader_ids().begin(),
+        manager.m_environment.shader_ids().size(),
+        editor::property_holder::value_editor_tree_view,
+        editor::property_holder::cannot_enter_text
+    );
+    properties->add_property(
+        "flares",
+        "flares",
+        "this option is resposible for flares",
+        m_collection
+    );
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_suns_flares.hpp b/src/xrEngine/editor_environment_suns_flares.hpp
index 55bc1627afd..254a40407d9 100644
--- a/src/xrEngine/editor_environment_suns_flares.hpp
+++ b/src/xrEngine/editor_environment_suns_flares.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_suns_flares.hpp
-//	Created 	: 26.01.2008
-//  Modified 	: 26.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment suns flares class
+// Module : editor_environment_suns_flares.hpp
+// Created : 26.01.2008
+// Modified : 26.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment suns flares class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_SUNS_FLARES_HPP_INCLUDED
@@ -14,36 +14,40 @@
 #include 
 #include "property_collection_forward.hpp"
 
-namespace editor {
+namespace editor
+{
 
 class property_holder;
 class property_holder_collection;
 
-namespace environment {
-namespace suns {
+namespace environment
+{
+namespace suns
+{
 
 class manager;
 class flare;
 
-class flares : private boost::noncopyable {
+class flares : private boost::noncopyable
+{
 public:
-					flares	();
-	virtual			~flares	();
-			void	load	(CInifile& config, shared_str const& section);
-			void	save	(CInifile& config, shared_str const& section);
-			void	fill	(manager const& manager, editor::property_holder* holder, editor::property_holder_collection* collection);
+    flares();
+    virtual ~flares();
+    void load(CInifile& config, shared_str const& section);
+    void save(CInifile& config, shared_str const& section);
+    void fill(manager const& manager, editor::property_holder* holder, editor::property_holder_collection* collection);
 private:
-	typedef xr_vector							flares_type;
-	typedef editor::property_holder_collection			property_holder_collection;
+    typedef xr_vector flares_type;
+    typedef editor::property_holder_collection property_holder_collection;
 
 public:
-	typedef property_collection	collection_type;
+    typedef property_collection collection_type;
 
 private:
-	flares_type				m_flares;
-    shared_str				m_shader;
-	collection_type*		m_collection;
-    bool					m_use;
+    flares_type m_flares;
+    shared_str m_shader;
+    collection_type* m_collection;
+    bool m_use;
 }; // class flares
 
 } // namespace suns
diff --git a/src/xrEngine/editor_environment_suns_gradient.cpp b/src/xrEngine/editor_environment_suns_gradient.cpp
index 11eef3382b4..98edac68d49 100644
--- a/src/xrEngine/editor_environment_suns_gradient.cpp
+++ b/src/xrEngine/editor_environment_suns_gradient.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_suns_gradient.cpp
-//	Created 	: 26.01.2008
-//  Modified 	: 26.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment suns gradient class
+// Module : editor_environment_suns_gradient.cpp
+// Created : 26.01.2008
+// Modified : 26.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment suns gradient class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -20,107 +20,107 @@ using editor::property_holder;
 using editor::property_holder_collection;
 using editor::environment::suns::manager;
 
-gradient::gradient			() :
-	m_use					(false),
-    m_opacity				(.0f),
-    m_radius				(.0f),
-    m_shader				(""),
-    m_texture				("")
+gradient::gradient() :
+    m_use(false),
+    m_opacity(.0f),
+    m_radius(.0f),
+    m_shader(""),
+    m_texture("")
 {
 }
 
-void gradient::load			(CInifile& config, shared_str const& section)
+void gradient::load(CInifile& config, shared_str const& section)
 {
-	m_use					= !!READ_IF_EXISTS(&config, r_bool,		section, "gradient",				true);
-    m_opacity				=   READ_IF_EXISTS(&config, r_float,	section, "gradient_opacity",		.7f);
-    m_radius				=   READ_IF_EXISTS(&config, r_float,	section, "gradient_radius",		.9f);
-    m_shader				=   READ_IF_EXISTS(&config, r_string,	section, "gradient_shader",		"effects\\flare");
-    m_texture				=   READ_IF_EXISTS(&config, r_string,	section, "gradient_texture",		"fx\\fx_gradient.tga");
+    m_use = !!READ_IF_EXISTS(&config, r_bool, section, "gradient", true);
+    m_opacity = READ_IF_EXISTS(&config, r_float, section, "gradient_opacity", .7f);
+    m_radius = READ_IF_EXISTS(&config, r_float, section, "gradient_radius", .9f);
+    m_shader = READ_IF_EXISTS(&config, r_string, section, "gradient_shader", "effects\\flare");
+    m_texture = READ_IF_EXISTS(&config, r_string, section, "gradient_texture", "fx\\fx_gradient.tga");
 }
 
-bool gradient::use_getter	()
+bool gradient::use_getter()
 {
-	return					(m_use);
+    return (m_use);
 }
 
-void gradient::use_setter	(bool value)
+void gradient::use_setter(bool value)
 {
-	if (m_use == value)
-		return;
+    if (m_use == value)
+        return;
 
-	m_use					= value;
-//	m_property_holder->clear();
-//	fill_internal			();
+    m_use = value;
+    // m_property_holder->clear();
+    // fill_internal ();
 }
 
-void gradient::fill			(
-		manager const& manager,
-		property_holder* holder,
-		property_holder_collection* collection
-	)
+void gradient::fill(
+    manager const& manager,
+    property_holder* holder,
+    property_holder_collection* collection
+)
 {
-	editor::property_holder*	properties = holder;
-	VERIFY						(properties);
+    editor::property_holder* properties = holder;
+    VERIFY(properties);
 
-	typedef editor::property_holder::boolean_getter_type	boolean_getter_type;
-	boolean_getter_type			boolean_getter;
+    typedef editor::property_holder::boolean_getter_type boolean_getter_type;
+    boolean_getter_type boolean_getter;
 
-	typedef editor::property_holder::boolean_setter_type	boolean_setter_type;
-	boolean_setter_type			boolean_setter;
+    typedef editor::property_holder::boolean_setter_type boolean_setter_type;
+    boolean_setter_type boolean_setter;
 
-	boolean_getter.bind			(this, &gradient::use_getter);
-	boolean_setter.bind			(this, &gradient::use_setter);
+    boolean_getter.bind(this, &gradient::use_getter);
+    boolean_setter.bind(this, &gradient::use_setter);
 
-	properties->add_property(
-		"use",
-		"gradient",
-		"this option is resposible for gradient usage",
-		m_use,
-		boolean_getter,
-		boolean_setter,
-		property_holder::property_read_write,
-		property_holder::notify_parent_on_change,
-		property_holder::no_password_char,
-		property_holder::do_not_refresh_grid_on_change
-	);
-	properties->add_property(
-		"opacity",
-		"gradient",
-		"this option is resposible for gradient opacity",
-		m_opacity,
-		m_opacity
-	);
-	properties->add_property(
-		"radius",
-		"gradient",
-		"this option is resposible for gradient radius",
-		m_radius,
-		m_radius
-	);
-	properties->add_property(
-		"shader",
-		"gradient",
-		"this option is resposible for gradient shader",
-		m_shader.c_str(),
-		m_shader,
-		&*manager.m_environment.shader_ids().begin(),
-		manager.m_environment.shader_ids().size(),
-		editor::property_holder::value_editor_tree_view,
-		editor::property_holder::cannot_enter_text
-	);
-	properties->add_property(
-		"texture",
-		"gradient",
-		"this option is resposible for gradient texture",
-		m_texture.c_str(),
-		m_texture,
-		".dds",
-		"Texture files (*.dds)|*.dds",
-		detail::real_path("$game_textures$", "").c_str(),
-		"Select texture...",
-		editor::property_holder::cannot_enter_text,
-		editor::property_holder::remove_extension
-	);
+    properties->add_property(
+        "use",
+        "gradient",
+        "this option is resposible for gradient usage",
+        m_use,
+        boolean_getter,
+        boolean_setter,
+        property_holder::property_read_write,
+        property_holder::notify_parent_on_change,
+        property_holder::no_password_char,
+        property_holder::do_not_refresh_grid_on_change
+    );
+    properties->add_property(
+        "opacity",
+        "gradient",
+        "this option is resposible for gradient opacity",
+        m_opacity,
+        m_opacity
+    );
+    properties->add_property(
+        "radius",
+        "gradient",
+        "this option is resposible for gradient radius",
+        m_radius,
+        m_radius
+    );
+    properties->add_property(
+        "shader",
+        "gradient",
+        "this option is resposible for gradient shader",
+        m_shader.c_str(),
+        m_shader,
+        &*manager.m_environment.shader_ids().begin(),
+        manager.m_environment.shader_ids().size(),
+        editor::property_holder::value_editor_tree_view,
+        editor::property_holder::cannot_enter_text
+    );
+    properties->add_property(
+        "texture",
+        "gradient",
+        "this option is resposible for gradient texture",
+        m_texture.c_str(),
+        m_texture,
+        ".dds",
+        "Texture files (*.dds)|*.dds",
+        detail::real_path("$game_textures$", "").c_str(),
+        "Select texture...",
+        editor::property_holder::cannot_enter_text,
+        editor::property_holder::remove_extension
+    );
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_suns_gradient.hpp b/src/xrEngine/editor_environment_suns_gradient.hpp
index 1683c22ba87..43a13f094a0 100644
--- a/src/xrEngine/editor_environment_suns_gradient.hpp
+++ b/src/xrEngine/editor_environment_suns_gradient.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_suns_gradient.hpp
-//	Created 	: 26.01.2008
-//  Modified 	: 26.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment suns gradient class
+// Module : editor_environment_suns_gradient.hpp
+// Created : 26.01.2008
+// Modified : 26.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment suns gradient class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_SUNS_GRADIENT_HPP_INCLUDED
@@ -13,33 +13,37 @@
 
 #include 
 
-namespace editor {
+namespace editor
+{
 
 class property_holder;
 class property_holder_collection;
 
-namespace environment {
-namespace suns {
+namespace environment
+{
+namespace suns
+{
 
 class manager;
 
-class gradient : private boost::noncopyable {
+class gradient : private boost::noncopyable
+{
 public:
-					gradient	();
-			void	load		(CInifile& config, shared_str const& section);
-			void	save		(CInifile& config, shared_str const& section);
-			void	fill		(manager const& manager, editor::property_holder* holder, editor::property_holder_collection* collection);
+    gradient();
+    void load(CInifile& config, shared_str const& section);
+    void save(CInifile& config, shared_str const& section);
+    void fill(manager const& manager, editor::property_holder* holder, editor::property_holder_collection* collection);
 
 private:
-	bool xr_stdcall	use_getter	();
-	void xr_stdcall use_setter	(bool value);
+    bool xr_stdcall use_getter();
+    void xr_stdcall use_setter(bool value);
 
 private:
-	bool			m_use;
-    float			m_opacity;
-    float			m_radius;
-    shared_str		m_shader;
-    shared_str		m_texture;
+    bool m_use;
+    float m_opacity;
+    float m_radius;
+    shared_str m_shader;
+    shared_str m_texture;
 }; // class gradient
 
 } // namespace suns
diff --git a/src/xrEngine/editor_environment_suns_manager.cpp b/src/xrEngine/editor_environment_suns_manager.cpp
index 9c7bde11689..39425a6e057 100644
--- a/src/xrEngine/editor_environment_suns_manager.cpp
+++ b/src/xrEngine/editor_environment_suns_manager.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_suns_manager.cpp
-//	Created 	: 13.12.2007
-//  Modified 	: 13.12.2007
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment suns manager class
+// Module : editor_environment_suns_manager.cpp
+// Created : 13.12.2007
+// Modified : 13.12.2007
+// Author : Dmitriy Iassenev
+// Description : editor environment suns manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -23,177 +23,179 @@ using editor::environment::suns::sun;
 using editor::environment::detail::logical_string_predicate;
 
 template <>
-void property_collection::display_name	(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
+void property_collection::display_name(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
 {
-	xr_strcpy				(buffer, buffer_size, m_container[item_index]->id().c_str());
+    xr_strcpy(buffer, buffer_size, m_container[item_index]->id().c_str());
 }
 
 template <>
-editor::property_holder* property_collection::create	()
+editor::property_holder* property_collection::create()
 {
-	sun*					object = xr_new(m_holder, generate_unique_id("sun_unique_id_").c_str());
-	object->fill			(this);
-	return					(object->object());
+    sun* object = xr_new(m_holder, generate_unique_id("sun_unique_id_").c_str());
+    object->fill(this);
+    return (object->object());
 }
 
-manager::manager			(::editor::environment::manager* environment) :
-	m_environment			(*environment),
-	m_collection			(0),
-	m_changed				(true)
+manager::manager(::editor::environment::manager* environment) :
+    m_environment(*environment),
+    m_collection(0),
+    m_changed(true)
 {
-	m_collection			= xr_new(&m_suns, this, &m_changed);
+    m_collection = xr_new(&m_suns, this, &m_changed);
 }
 
-manager::~manager			()
+manager::~manager()
 {
-	xr_delete				(m_collection);
+    xr_delete(m_collection);
 
-	delete_data				(m_suns);
-	delete_data				(m_suns_ids);
+    delete_data(m_suns);
+    delete_data(m_suns_ids);
 }
 
-void manager::load			()
+void manager::load()
 {
-	string_path				file_name;
-	CInifile*				config =
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\suns.ltx"
-			),
-			TRUE,
-			TRUE,
-			FALSE
-		);
-
-	typedef CInifile::Root	sections_type;
-	sections_type&			sections = config->sections();
-	m_suns.reserve			(sections.size());
-	sections_type::const_iterator	i = sections.begin();
-	sections_type::const_iterator	e = sections.end();
-	for ( ; i != e; ++i)
-		add					(*config, (*i)->Name);
-
-	xr_delete				(config);
+    string_path file_name;
+    CInifile* config =
+        xr_new(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "environment\\suns.ltx"
+            ),
+            TRUE,
+            TRUE,
+            FALSE
+        );
+
+    typedef CInifile::Root sections_type;
+    sections_type& sections = config->sections();
+    m_suns.reserve(sections.size());
+    sections_type::const_iterator i = sections.begin();
+    sections_type::const_iterator e = sections.end();
+    for (; i != e; ++i)
+        add(*config, (*i)->Name);
+
+    xr_delete(config);
 }
 
-void manager::save			()
+void manager::save()
 {
-	string_path				file_name;
-	CInifile*				config =
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\suns.ltx"
-			),
-			FALSE,
-			FALSE,
-			TRUE
-		);
-
-	container_type::const_iterator	i = m_suns.begin();
-	container_type::const_iterator	e = m_suns.end();
-	for ( ; i != e; ++i)
-		(*i)->save			(*config);
-
-	xr_delete				(config);
+    string_path file_name;
+    CInifile* config =
+        xr_new(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "environment\\suns.ltx"
+            ),
+            FALSE,
+            FALSE,
+            TRUE
+        );
+
+    container_type::const_iterator i = m_suns.begin();
+    container_type::const_iterator e = m_suns.end();
+    for (; i != e; ++i)
+        (*i)->save(*config);
+
+    xr_delete(config);
 }
 
-void manager::add			(CInifile& config, shared_str const& section)
+void manager::add(CInifile& config, shared_str const& section)
 {
-	struct predicate {
-		shared_str			m_id;
-
-		inline		predicate	(shared_str const& id) :
-			m_id			(id)
-		{
-		}
-		
-		inline bool	operator()	(sun const* const& object) const
-		{
-			return			(object->id()._get() == m_id._get());
-		}
-	};
-
-	VERIFY					(
-		std::find_if(
-			m_suns.begin(),
-			m_suns.end(),
-			predicate(section)
-		) == 
-		m_suns.end()
-	);
-	
-	sun*					object = xr_new(*this, section);
-	object->load			(config);
-	object->fill			(m_collection);
-	m_suns.push_back		(object);
+    struct predicate
+    {
+        shared_str m_id;
+
+        inline predicate(shared_str const& id) :
+            m_id(id)
+        {
+        }
+
+        inline bool operator() (sun const* const& object) const
+        {
+            return (object->id()._get() == m_id._get());
+        }
+    };
+
+    VERIFY(
+        std::find_if(
+            m_suns.begin(),
+            m_suns.end(),
+            predicate(section)
+        ) ==
+        m_suns.end()
+    );
+
+    sun* object = xr_new(*this, section);
+    object->load(config);
+    object->fill(m_collection);
+    m_suns.push_back(object);
 }
 
-void manager::fill			(editor::property_holder* holder)
+void manager::fill(editor::property_holder* holder)
 {
-	VERIFY					(holder);
-	holder->add_property	(
-		"suns",
-		"suns",
-		"this option is resposible for sound channels",
-		m_collection
-	);
+    VERIFY(holder);
+    holder->add_property(
+        "suns",
+        "suns",
+        "this option is resposible for sound channels",
+        m_collection
+    );
 }
 
-shared_str manager::unique_id	(shared_str const& id) const
+shared_str manager::unique_id(shared_str const& id) const
 {
-	if (m_collection->unique_id(id.c_str()))
-		return				(id);
+    if (m_collection->unique_id(id.c_str()))
+        return (id);
 
-	return					(m_collection->generate_unique_id(id.c_str()));
+    return (m_collection->generate_unique_id(id.c_str()));
 }
 
-manager::suns_ids_type const& manager::suns_ids	() const
+manager::suns_ids_type const& manager::suns_ids() const
 {
-	if (!m_changed)
-		return				(m_suns_ids);
+    if (!m_changed)
+        return (m_suns_ids);
 
-	m_changed				= false;
+    m_changed = false;
 
-	delete_data				(m_suns_ids);
+    delete_data(m_suns_ids);
 
-	m_suns_ids.resize		(m_suns.size() + 1);
-	m_suns_ids[0]			= xr_strdup("");
+    m_suns_ids.resize(m_suns.size() + 1);
+    m_suns_ids[0] = xr_strdup("");
 
-	container_type::const_iterator	i = m_suns.begin();
-	container_type::const_iterator	e = m_suns.end();
-	suns_ids_type::iterator			j = m_suns_ids.begin() + 1;
-	for ( ; i != e; ++i, ++j)
-		*j					= xr_strdup((*i)->id().c_str());
+    container_type::const_iterator i = m_suns.begin();
+    container_type::const_iterator e = m_suns.end();
+    suns_ids_type::iterator j = m_suns_ids.begin() + 1;
+    for (; i != e; ++i, ++j)
+        *j = xr_strdup((*i)->id().c_str());
 
-	std::sort				(m_suns_ids.begin(), m_suns_ids.end(), logical_string_predicate());
+    std::sort(m_suns_ids.begin(), m_suns_ids.end(), logical_string_predicate());
 
-	return					(m_suns_ids);
+    return (m_suns_ids);
 }
 
-struct predicate {
-	shared_str	m_id;
+struct predicate
+{
+    shared_str m_id;
 
-	IC			predicate	(shared_str const& id) :
-		m_id	(id)
-	{
-	}
+    IC predicate(shared_str const& id) :
+        m_id(id)
+    {
+    }
 
-	IC	bool	operator()	(sun* const& sun) const
-	{
-		return	(sun->id()._get() == m_id._get());
-	}
+    IC bool operator() (sun* const& sun) const
+    {
+        return (sun->id()._get() == m_id._get());
+    }
 }; // struct predicate
 
-CLensFlareDescriptor* manager::get_flare	(shared_str const& id) const
+CLensFlareDescriptor* manager::get_flare(shared_str const& id) const
 {
-//	container_type::const_iterator	found = std::find_if(m_suns.begin(), m_suns.end(), predicate(id));
-//	VERIFY							(found != m_suns.end());
-//	return							((*found)->);
-	return							(0);
+    // container_type::const_iterator found = std::find_if(m_suns.begin(), m_suns.end(), predicate(id));
+    // VERIFY (found != m_suns.end());
+    // return ((*found)->);
+    return (0);
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_suns_manager.hpp b/src/xrEngine/editor_environment_suns_manager.hpp
index f2b0f39fe4c..2a69af6d857 100644
--- a/src/xrEngine/editor_environment_suns_manager.hpp
+++ b/src/xrEngine/editor_environment_suns_manager.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_suns_manager.hpp
-//	Created 	: 13.12.2007
-//  Modified 	: 13.12.2007
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment suns manager class
+// Module : editor_environment_suns_manager.hpp
+// Created : 13.12.2007
+// Modified : 13.12.2007
+// Author : Dmitriy Iassenev
+// Description : editor environment suns manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_SUNS_MANAGER_HPP_INCLUDED
@@ -16,53 +16,57 @@
 
 class CLensFlareDescriptor;
 
-namespace editor {
+namespace editor
+{
 
 class property_holder;
 
-namespace environment {
+namespace environment
+{
 
 class manager;
 
-namespace suns {
+namespace suns
+{
 
 class sun;
 
-class manager : private boost::noncopyable {
+class manager : private boost::noncopyable
+{
 public:
-					manager			(environment::manager* environment);
-					~manager		();
-			void	load			();
-			void	save			();
-			void	fill			(editor::property_holder* holder);
-			shared_str	unique_id	(shared_str const& id) const;
-	CLensFlareDescriptor* get_flare	(shared_str const& id) const;
+    manager(environment::manager* environment);
+    ~manager();
+    void load();
+    void save();
+    void fill(editor::property_holder* holder);
+    shared_str unique_id(shared_str const& id) const;
+    CLensFlareDescriptor* get_flare(shared_str const& id) const;
 
 private:
-			void	add				(CInifile& config, shared_str const& sun);
+    void add(CInifile& config, shared_str const& sun);
 
 public:
-	typedef	xr_vector			container_type;
-	typedef xr_vector		suns_ids_type;
+    typedef xr_vector container_type;
+    typedef xr_vector suns_ids_type;
 
 public:
-	suns_ids_type const&	suns_ids() const;
+    suns_ids_type const& suns_ids() const;
 
 private:
-	typedef property_collection<
-				container_type,
-				manager
-			>						collection_type;
+    typedef property_collection <
+    container_type,
+    manager
+    > collection_type;
 
 
 private:
-	container_type					m_suns;
-	mutable suns_ids_type			m_suns_ids;
-	collection_type*				m_collection;
-	mutable bool					m_changed;
+    container_type m_suns;
+    mutable suns_ids_type m_suns_ids;
+    collection_type* m_collection;
+    mutable bool m_changed;
 
 public:
-	environment::manager const&		m_environment;
+    environment::manager const& m_environment;
 }; // class suns_manager
 
 } // namespace suns
diff --git a/src/xrEngine/editor_environment_suns_sun.cpp b/src/xrEngine/editor_environment_suns_sun.cpp
index d87d5d61124..0f9907deb78 100644
--- a/src/xrEngine/editor_environment_suns_sun.cpp
+++ b/src/xrEngine/editor_environment_suns_sun.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_suns_sun.cpp
-//	Created 	: 13.12.2007
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment suns sun class
+// Module : editor_environment_suns_sun.cpp
+// Created : 13.12.2007
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment suns sun class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -21,131 +21,131 @@ using editor::environment::suns::flare;
 using editor::environment::suns::manager;
 using editor::property_holder;
 
-sun::sun					(manager const& manager, shared_str const &id) :
-	m_manager				(manager),
-	m_id					(id),
-    m_use					(false),
-    m_ignore_color			(false),
-    m_radius				(0.f),
-    m_shader				(""),
-    m_texture				(""),
-	m_property_holder		(0)
+sun::sun(manager const& manager, shared_str const& id) :
+    m_manager(manager),
+    m_id(id),
+    m_use(false),
+    m_ignore_color(false),
+    m_radius(0.f),
+    m_shader(""),
+    m_texture(""),
+    m_property_holder(0)
 {
 }
 
-sun::~sun					()
+sun::~sun()
 {
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy			(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-void sun::load				(CInifile& config)
+void sun::load(CInifile& config)
 {
-    m_use					= !!READ_IF_EXISTS(&config, r_bool,		m_id, "sun",				true);
-    m_ignore_color			= !!READ_IF_EXISTS(&config, r_bool,		m_id, "sun_ignore_color",	false);
-    m_radius				=   READ_IF_EXISTS(&config, r_float,	m_id, "sun_radius",			.15f);
-    m_shader				=   READ_IF_EXISTS(&config, r_string,	m_id, "sun_shader",			"effects\\sun");
-    m_texture				=   READ_IF_EXISTS(&config, r_string,	m_id, "sun_texture",		"fx\\fx_sun.tga");
+    m_use = !!READ_IF_EXISTS(&config, r_bool, m_id, "sun", true);
+    m_ignore_color = !!READ_IF_EXISTS(&config, r_bool, m_id, "sun_ignore_color", false);
+    m_radius = READ_IF_EXISTS(&config, r_float, m_id, "sun_radius", .15f);
+    m_shader = READ_IF_EXISTS(&config, r_string, m_id, "sun_shader", "effects\\sun");
+    m_texture = READ_IF_EXISTS(&config, r_string, m_id, "sun_texture", "fx\\fx_sun.tga");
 }
 
-void sun::save				(CInifile& config)
+void sun::save(CInifile& config)
 {
-   config.w_bool			(m_id.c_str(), "sun",				m_use				);
-   config.w_bool			(m_id.c_str(), "sun_ignore_color",	m_ignore_color		);
-   config.w_float			(m_id.c_str(), "sun_radius",		m_radius			);
-   config.w_string			(m_id.c_str(), "sun_shader",		m_shader.c_str()	);
-   config.w_string			(m_id.c_str(), "sun_texture",		m_texture.c_str()	);
+    config.w_bool(m_id.c_str(), "sun", m_use);
+    config.w_bool(m_id.c_str(), "sun_ignore_color", m_ignore_color);
+    config.w_float(m_id.c_str(), "sun_radius", m_radius);
+    config.w_string(m_id.c_str(), "sun_shader", m_shader.c_str());
+    config.w_string(m_id.c_str(), "sun_texture", m_texture.c_str());
 }
 
-LPCSTR sun::id_getter		() const
+LPCSTR sun::id_getter() const
 {
-	return					(m_id.c_str());
+    return (m_id.c_str());
 }
 
-void sun::id_setter			(LPCSTR value_)
+void sun::id_setter(LPCSTR value_)
 {
-	shared_str				value = value_;
-	if (m_id._get() == value._get())
-		return;
+    shared_str value = value_;
+    if (m_id._get() == value._get())
+        return;
 
-	m_id					= m_manager.unique_id(value);
+    m_id = m_manager.unique_id(value);
 }
 
-void sun::fill				(editor::property_holder_collection* collection)
+void sun::fill(editor::property_holder_collection* collection)
 {
-	VERIFY					(!m_property_holder);
-	m_property_holder		= ::ide().create_property_holder(m_id.c_str(), collection, this);
-	editor::property_holder*properties = m_property_holder;
-	VERIFY					(properties);
-
-	typedef editor::property_holder::string_getter_type	string_getter_type;
-	string_getter_type		string_getter;
-	string_getter.bind		(this, &sun::id_getter);
-
-	typedef editor::property_holder::string_setter_type	string_setter_type;
-	string_setter_type		string_setter;
-	string_setter.bind		(this, &sun::id_setter);
-
-	properties->add_property(
-		"id",
-		"common",
-		"this option is resposible for sun identifier",
-		m_id.c_str(),
-		string_getter,
-		string_setter
-	);
-	properties->add_property(
-		"use",
-		"sun",
-		"this option is resposible for sun usage",
-		m_use,
-		m_use
-	);
-	properties->add_property(
-		"ignore color",
-		"sun",
-		"this option is resposible for sun ignore color",
-		m_ignore_color,
-		m_ignore_color
-	);
-	properties->add_property(
-		"radius",
-		"sun",
-		"this option is resposible for sun radius",
-		m_radius,
-		m_radius
-	);
-	properties->add_property(
-		"shader",
-		"sun",
-		"this option is resposible for sun shader",
-		m_shader.c_str(),
-		m_shader,
-		&*m_manager.m_environment.shader_ids().begin(),
-		m_manager.m_environment.shader_ids().size(),
-		editor::property_holder::value_editor_tree_view,
-		editor::property_holder::cannot_enter_text
-	);
-	properties->add_property(
-		"texture",
-		"sun",
-		"this option is resposible for sun texture",
-		m_texture.c_str(),
-		m_texture,
-		".dds",
-		"Texture files (*.dds)|*.dds",
-		detail::real_path("$game_textures$", "").c_str(),
-		"Select texture...",
-		editor::property_holder::cannot_enter_text,
-		editor::property_holder::remove_extension
-	);
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder(m_id.c_str(), collection, this);
+    editor::property_holder* properties = m_property_holder;
+    VERIFY(properties);
+
+    typedef editor::property_holder::string_getter_type string_getter_type;
+    string_getter_type string_getter;
+    string_getter.bind(this, &sun::id_getter);
+
+    typedef editor::property_holder::string_setter_type string_setter_type;
+    string_setter_type string_setter;
+    string_setter.bind(this, &sun::id_setter);
+
+    properties->add_property(
+        "id",
+        "common",
+        "this option is resposible for sun identifier",
+        m_id.c_str(),
+        string_getter,
+        string_setter
+    );
+    properties->add_property(
+        "use",
+        "sun",
+        "this option is resposible for sun usage",
+        m_use,
+        m_use
+    );
+    properties->add_property(
+        "ignore color",
+        "sun",
+        "this option is resposible for sun ignore color",
+        m_ignore_color,
+        m_ignore_color
+    );
+    properties->add_property(
+        "radius",
+        "sun",
+        "this option is resposible for sun radius",
+        m_radius,
+        m_radius
+    );
+    properties->add_property(
+        "shader",
+        "sun",
+        "this option is resposible for sun shader",
+        m_shader.c_str(),
+        m_shader,
+        &*m_manager.m_environment.shader_ids().begin(),
+        m_manager.m_environment.shader_ids().size(),
+        editor::property_holder::value_editor_tree_view,
+        editor::property_holder::cannot_enter_text
+    );
+    properties->add_property(
+        "texture",
+        "sun",
+        "this option is resposible for sun texture",
+        m_texture.c_str(),
+        m_texture,
+        ".dds",
+        "Texture files (*.dds)|*.dds",
+        detail::real_path("$game_textures$", "").c_str(),
+        "Select texture...",
+        editor::property_holder::cannot_enter_text,
+        editor::property_holder::remove_extension
+    );
 }
 
 property_holder* sun::object()
 {
-	return					(m_property_holder);
+    return (m_property_holder);
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_suns_sun.hpp b/src/xrEngine/editor_environment_suns_sun.hpp
index 8763a1de8e6..14d4f42d507 100644
--- a/src/xrEngine/editor_environment_suns_sun.hpp
+++ b/src/xrEngine/editor_environment_suns_sun.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_suns_sun.hpp
-//	Created 	: 13.12.2007
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment suns sun class
+// Module : editor_environment_suns_sun.hpp
+// Created : 13.12.2007
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment suns sun class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_SUNS_SUN_HPP_INCLUDED
@@ -15,46 +15,49 @@
 #include "../include/editor/property_holder.hpp"
 #include "xr_efflensflare.h"
 
-namespace editor {
+namespace editor
+{
 
 class property_holder;
 class property_holder_collection;
 
-namespace environment {
-namespace suns {
+namespace environment
+{
+namespace suns
+{
 
 class flare;
 class manager;
 
 class sun :
-	public CLensFlare,
-	public editor::property_holder_holder,
-	private boost::noncopyable
+    public CLensFlare,
+    public editor::property_holder_holder,
+    private boost::noncopyable
 {
 public:
-								sun			(manager const& manager, shared_str const §ion);
-								~sun		();
-			void				load		(CInifile& config);
-			void				save		(CInifile& config);
-			void				fill		(editor::property_holder_collection* collection);
+    sun(manager const& manager, shared_str const& section);
+    ~sun();
+    void load(CInifile& config);
+    void save(CInifile& config);
+    void fill(editor::property_holder_collection* collection);
 
 private:
-			LPCSTR xr_stdcall	id_getter	() const;
-			void   xr_stdcall	id_setter	(LPCSTR value);
+    LPCSTR xr_stdcall id_getter() const;
+    void xr_stdcall id_setter(LPCSTR value);
 public:
-	inline	shared_str const&	id			() const { return m_id; }
-	virtual	property_holder*	object		();
+    inline shared_str const& id() const { return m_id; }
+    virtual property_holder* object();
 
 private:
 
-	shared_str					m_id;
-    shared_str					m_shader;
-    shared_str					m_texture;
-	manager const&				m_manager;
-	editor::property_holder*	m_property_holder;
-    float						m_radius;
-    bool						m_use;
-    bool						m_ignore_color;
+    shared_str m_id;
+    shared_str m_shader;
+    shared_str m_texture;
+    manager const& m_manager;
+    editor::property_holder* m_property_holder;
+    float m_radius;
+    bool m_use;
+    bool m_ignore_color;
 }; // class sun
 
 } // namespace suns
diff --git a/src/xrEngine/editor_environment_thunderbolts_collection.cpp b/src/xrEngine/editor_environment_thunderbolts_collection.cpp
index a2ed4151916..fc7064539f8 100644
--- a/src/xrEngine/editor_environment_thunderbolts_collection.cpp
+++ b/src/xrEngine/editor_environment_thunderbolts_collection.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_thunderbolts_collection.cpp
-//	Created 	: 10.01.2008
-//  Modified 	: 10.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment thunderbolts collection identifier class
+// Module : editor_environment_thunderbolts_collection.cpp
+// Created : 10.01.2008
+// Modified : 10.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment thunderbolts collection identifier class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -21,111 +21,112 @@ using editor::environment::thunderbolts::manager;
 using editor::property_holder;
 
 template <>
-void property_collection::display_name	(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
+void property_collection::display_name(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
 {
-	xr_strcpy			(buffer, buffer_size, m_container[item_index]->id());
+    xr_strcpy(buffer, buffer_size, m_container[item_index]->id());
 }
 
 template <>
-editor::property_holder* property_collection::create	()
+editor::property_holder* property_collection::create()
 {
-	thunderbolt_id*		object = xr_new(m_holder.m_manager, "");
-	object->fill		(this);
-	return				(object->object());
+    thunderbolt_id* object = xr_new(m_holder.m_manager, "");
+    object->fill(this);
+    return (object->object());
 }
 
-collection::collection					(manager const& manager, shared_str const& id) :
-	m_manager			(manager),
-	m_collection		(0),
-	m_property_holder	(0)
+collection::collection(manager const& manager, shared_str const& id) :
+    m_manager(manager),
+    m_collection(0),
+    m_property_holder(0)
 {
-	section				= id;
-	m_collection		= xr_new(&m_ids, this);
+    section = id;
+    m_collection = xr_new(&m_ids, this);
 }
 
-collection::~collection					()
+collection::~collection()
 {
-	xr_delete			(m_collection);
-	delete_data			(m_ids);
+    xr_delete(m_collection);
+    delete_data(m_ids);
 
-	palette.clear		();
+    palette.clear();
 
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy		(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-void collection::load					(CInifile& config)
+void collection::load(CInifile& config)
 {
-	CInifile::Sect&				items = config.r_section(section);
-	m_ids.reserve				(items.Data.size());
-	typedef CInifile::Items		items_type;
-	items_type::const_iterator	i = items.Data.begin();
-	items_type::const_iterator	e = items.Data.end();
-	for ( ; i != e; ++i) {
-		thunderbolt_id*			object = xr_new(m_manager, (*i).first);
-		object->fill			(m_collection);
-		m_ids.push_back			(object);
-
-		palette.push_back		(m_manager.description(config, (*i).first));
-	}
+    CInifile::Sect& items = config.r_section(section);
+    m_ids.reserve(items.Data.size());
+    typedef CInifile::Items items_type;
+    items_type::const_iterator i = items.Data.begin();
+    items_type::const_iterator e = items.Data.end();
+    for (; i != e; ++i)
+    {
+        thunderbolt_id* object = xr_new(m_manager, (*i).first);
+        object->fill(m_collection);
+        m_ids.push_back(object);
+
+        palette.push_back(m_manager.description(config, (*i).first));
+    }
 }
 
-void collection::save					(CInifile& config)
+void collection::save(CInifile& config)
 {
-	container_type::const_iterator	i = m_ids.begin();
-	container_type::const_iterator	e = m_ids.end();
-	for ( ; i != e; ++i)
-		config.w_string	(section.c_str(), (*i)->id(), "");
+    container_type::const_iterator i = m_ids.begin();
+    container_type::const_iterator e = m_ids.end();
+    for (; i != e; ++i)
+        config.w_string(section.c_str(), (*i)->id(), "");
 }
 
-LPCSTR collection::id_getter			() const
+LPCSTR collection::id_getter() const
 {
-	return				(section.c_str());
+    return (section.c_str());
 }
 
-void collection::id_setter				(LPCSTR value_)
+void collection::id_setter(LPCSTR value_)
 {
-	shared_str			value = value_;
-	if (section._get() == value._get())
-		return;
+    shared_str value = value_;
+    if (section._get() == value._get())
+        return;
 
-	section				= m_manager.unique_collection_id(value);
+    section = m_manager.unique_collection_id(value);
 }
 
-void collection::fill					(editor::property_holder_collection* collection)
+void collection::fill(editor::property_holder_collection* collection)
 {
-	VERIFY				(!m_property_holder);
-	m_property_holder	= ::ide().create_property_holder(section.c_str());
-
-	typedef editor::property_holder::string_getter_type	string_getter_type;
-	string_getter_type	string_getter;
-	string_getter.bind	(this, &collection::id_getter);
-
-	typedef editor::property_holder::string_setter_type	string_setter_type;
-	string_setter_type	string_setter;
-	string_setter.bind	(this, &collection::id_setter);
-
-	m_property_holder->add_property(
-		"id",
-		"properties",
-		"this option is resposible for collection id",
-		section.c_str(),
-		string_getter,
-		string_setter
-	);
-	m_property_holder->add_property	(
-		"thunderbolts",
-		"properties",
-		"this option is resposible for thunderbolts",
-		m_collection
-	);
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder(section.c_str());
+
+    typedef editor::property_holder::string_getter_type string_getter_type;
+    string_getter_type string_getter;
+    string_getter.bind(this, &collection::id_getter);
+
+    typedef editor::property_holder::string_setter_type string_setter_type;
+    string_setter_type string_setter;
+    string_setter.bind(this, &collection::id_setter);
+
+    m_property_holder->add_property(
+        "id",
+        "properties",
+        "this option is resposible for collection id",
+        section.c_str(),
+        string_getter,
+        string_setter
+    );
+    m_property_holder->add_property(
+        "thunderbolts",
+        "properties",
+        "this option is resposible for thunderbolts",
+        m_collection
+    );
 }
 
-property_holder* collection::object		()
+property_holder* collection::object()
 {
-	return				(m_property_holder);
+    return (m_property_holder);
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_thunderbolts_collection.hpp b/src/xrEngine/editor_environment_thunderbolts_collection.hpp
index 918afc2e56c..4773aaa3775 100644
--- a/src/xrEngine/editor_environment_thunderbolts_collection.hpp
+++ b/src/xrEngine/editor_environment_thunderbolts_collection.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_thunderbolts_collection.hpp
-//	Created 	: 10.01.2008
-//  Modified 	: 10.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment thunderbolts collection identifier class
+// Module : editor_environment_thunderbolts_collection.hpp
+// Created : 10.01.2008
+// Modified : 10.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment thunderbolts collection identifier class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_THUNDERBOLTS_COLLECTION_ID_HPP_INCLUDED
@@ -16,49 +16,53 @@
 #include "property_collection_forward.hpp"
 #include "thunderbolt.h"
 
-namespace editor {
+namespace editor
+{
 
 class property_holder_collection;
 
-namespace environment {
-namespace thunderbolts {
+namespace environment
+{
+namespace thunderbolts
+{
 
 class manager;
 class thunderbolt_id;
 
 class collection :
-	public SThunderboltCollection,
-	public editor::property_holder_holder,
-	private boost::noncopyable {
+    public SThunderboltCollection,
+    public editor::property_holder_holder,
+    private boost::noncopyable
+{
 public:
-							collection		(manager const& manager, shared_str const& id);
-	virtual					~collection		();
-			void			load			(CInifile& config);
-			void			save			(CInifile& config);
-			void			fill			(editor::property_holder_collection* collection);
-	inline	LPCSTR			id				() const { return section.c_str(); }
+    collection(manager const& manager, shared_str const& id);
+    virtual ~collection();
+    void load(CInifile& config);
+    void save(CInifile& config);
+    void fill(editor::property_holder_collection* collection);
+    inline LPCSTR id() const { return section.c_str(); }
 
 
 private:
-			LPCSTR	xr_stdcall	id_getter	() const;
-			void	xr_stdcall	id_setter	(LPCSTR value);
+    LPCSTR xr_stdcall id_getter() const;
+    void xr_stdcall id_setter(LPCSTR value);
 private:
-	typedef editor::property_holder			property_holder_type;
+    typedef editor::property_holder property_holder_type;
 
 public:
-	virtual	property_holder_type* object	();
+    virtual property_holder_type* object();
 
 private:
-	typedef xr_vector						container_type;
-	typedef property_collection	collection_type;
+    typedef xr_vector container_type;
+    typedef property_collection collection_type;
 
 private:
-	container_type			m_ids;
-	collection_type*		m_collection;
-	property_holder_type*	m_property_holder;
+    container_type m_ids;
+    collection_type* m_collection;
+    property_holder_type* m_property_holder;
 
 public:
-	manager const&			m_manager;
+    manager const& m_manager;
 }; // class collection
 } // namespace thunderbolts
 } // namespace environment
diff --git a/src/xrEngine/editor_environment_thunderbolts_gradient.cpp b/src/xrEngine/editor_environment_thunderbolts_gradient.cpp
index d29215dc498..42542810f45 100644
--- a/src/xrEngine/editor_environment_thunderbolts_gradient.cpp
+++ b/src/xrEngine/editor_environment_thunderbolts_gradient.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_thunderbolts_gradient.cpp
-//	Created 	: 04.01.2008
-//  Modified 	: 10.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment thunderbolts gradient class
+// Module : editor_environment_thunderbolts_gradient.cpp
+// Created : 04.01.2008
+// Modified : 10.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment thunderbolts gradient class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -16,134 +16,134 @@
 
 using editor::environment::thunderbolts::gradient;
 
-gradient::gradient	() :
-	m_property_holder	(0)
+gradient::gradient() :
+    m_property_holder(0)
 {
 }
 
-gradient::~gradient	()
+gradient::~gradient()
 {
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy		(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-void gradient::load	(CInifile& config, shared_str const& section_id, LPCSTR prefix)
+void gradient::load(CInifile& config, shared_str const& section_id, LPCSTR prefix)
 {
-	string_path			temp;
-	shader				= config.r_string	(section_id, strconcat(sizeof(temp), temp, prefix, "_shader"));
-	texture				= config.r_string	(section_id, strconcat(sizeof(temp), temp, prefix, "_texture"));
-	fOpacity			= config.r_float	(section_id, strconcat(sizeof(temp), temp, prefix, "_opacity"));
-	fRadius				= config.r_fvector2	(section_id, strconcat(sizeof(temp), temp, prefix, "_radius"));
-	m_pFlare->CreateShader	(*shader,*texture);
+    string_path temp;
+    shader = config.r_string(section_id, strconcat(sizeof(temp), temp, prefix, "_shader"));
+    texture = config.r_string(section_id, strconcat(sizeof(temp), temp, prefix, "_texture"));
+    fOpacity = config.r_float(section_id, strconcat(sizeof(temp), temp, prefix, "_opacity"));
+    fRadius = config.r_fvector2(section_id, strconcat(sizeof(temp), temp, prefix, "_radius"));
+    m_pFlare->CreateShader(*shader, *texture);
 }
 
-void gradient::save	(CInifile& config, shared_str const& section_id, LPCSTR prefix)
+void gradient::save(CInifile& config, shared_str const& section_id, LPCSTR prefix)
 {
-	string_path			temp;
-	config.w_string		(section_id.c_str(), strconcat(sizeof(temp), temp, prefix, "_shader" ),	shader.c_str()	);
-	config.w_string		(section_id.c_str(), strconcat(sizeof(temp), temp, prefix, "_texture"),	texture.c_str()	);
-	config.w_float		(section_id.c_str(), strconcat(sizeof(temp), temp, prefix, "_opacity"),	fOpacity		);
-	config.w_fvector2	(section_id.c_str(), strconcat(sizeof(temp), temp, prefix, "_radius" ),	fRadius			);
+    string_path temp;
+    config.w_string(section_id.c_str(), strconcat(sizeof(temp), temp, prefix, "_shader"), shader.c_str());
+    config.w_string(section_id.c_str(), strconcat(sizeof(temp), temp, prefix, "_texture"), texture.c_str());
+    config.w_float(section_id.c_str(), strconcat(sizeof(temp), temp, prefix, "_opacity"), fOpacity);
+    config.w_fvector2(section_id.c_str(), strconcat(sizeof(temp), temp, prefix, "_radius"), fRadius);
 }
 
-LPCSTR gradient::shader_getter	() const
+LPCSTR gradient::shader_getter() const
 {
-	return				(shader.c_str());
+    return (shader.c_str());
 }
 
-void gradient::shader_setter	(LPCSTR	value)
+void gradient::shader_setter(LPCSTR value)
 {
-	shader					= value;
-	m_pFlare->CreateShader	(*shader,*texture);
+    shader = value;
+    m_pFlare->CreateShader(*shader, *texture);
 }
 
-LPCSTR gradient::texture_getter	() const
+LPCSTR gradient::texture_getter() const
 {
-	return				(texture.c_str());
+    return (texture.c_str());
 }
 
-void gradient::texture_setter	(LPCSTR	value)
+void gradient::texture_setter(LPCSTR value)
 {
-	texture				= value;
-	m_pFlare->CreateShader	(*shader,*texture);
+    texture = value;
+    m_pFlare->CreateShader(*shader, *texture);
 }
 
-void gradient::fill	(
-		::editor::environment::manager& environment,
-		LPCSTR name,
-		LPCSTR description,
-		::editor::property_holder& holder
-	)
+void gradient::fill(
+    ::editor::environment::manager& environment,
+    LPCSTR name,
+    LPCSTR description,
+    ::editor::property_holder& holder
+)
 {
-	VERIFY							(!m_property_holder);
-	m_property_holder				= ::ide().create_property_holder(name);
-
-	holder.add_property				(
-		name,
-		"gradient",
-		description,
-		m_property_holder
-	);
-
-	m_property_holder->add_property	(
-		"opacity",
-		"properties",
-		"this option is resposible for thunderbolt gradient opacity",
-		fOpacity,
-		fOpacity
-	);
-	m_property_holder->add_property	(
-		"minimum radius",
-		"properties",
-		"this option is resposible for thunderbolt gradient minimum radius",
-		fRadius.x,
-		fRadius.x
-	);
-	m_property_holder->add_property	(
-		"maximum _radius",
-		"properties",
-		"this option is resposible for thunderbolt gradient maximum radius",
-		fRadius.y,
-		fRadius.y
-	);
-
-	typedef ::editor::property_holder::string_getter_type	string_getter_type;
-	string_getter_type	string_getter;
-	string_getter.bind	(this, &gradient::shader_getter);
-
-	typedef ::editor::property_holder::string_setter_type	string_setter_type;
-	string_setter_type	string_setter;
-	string_setter.bind	(this, &gradient::shader_setter);
-
-	m_property_holder->add_property	(
-		"shader",
-		"properties",
-		"this option is resposible for thunderbolt gradient shader",
-		shader.c_str(),
-		string_getter,
-		string_setter,
-		&*environment.shader_ids().begin(),
-		environment.shader_ids().size(),
-		editor::property_holder::value_editor_tree_view,
-		editor::property_holder::cannot_enter_text
-	);
-
-	string_getter.bind	(this, &gradient::texture_getter);
-	string_setter.bind	(this, &gradient::texture_setter);
-	m_property_holder->add_property	(
-		"texture",
-		"",
-		"this option is resposible for thunderbolt gradient texture",
-		texture.c_str(),
-		texture,
-		".dds",
-		"Texture files (*.dds)|*.dds",
-		detail::real_path("$game_textures$", "").c_str(),
-		"Select texture...",
-		editor::property_holder::cannot_enter_text,
-		editor::property_holder::remove_extension
-	);
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder(name);
+
+    holder.add_property(
+        name,
+        "gradient",
+        description,
+        m_property_holder
+    );
+
+    m_property_holder->add_property(
+        "opacity",
+        "properties",
+        "this option is resposible for thunderbolt gradient opacity",
+        fOpacity,
+        fOpacity
+    );
+    m_property_holder->add_property(
+        "minimum radius",
+        "properties",
+        "this option is resposible for thunderbolt gradient minimum radius",
+        fRadius.x,
+        fRadius.x
+    );
+    m_property_holder->add_property(
+        "maximum _radius",
+        "properties",
+        "this option is resposible for thunderbolt gradient maximum radius",
+        fRadius.y,
+        fRadius.y
+    );
+
+    typedef ::editor::property_holder::string_getter_type string_getter_type;
+    string_getter_type string_getter;
+    string_getter.bind(this, &gradient::shader_getter);
+
+    typedef ::editor::property_holder::string_setter_type string_setter_type;
+    string_setter_type string_setter;
+    string_setter.bind(this, &gradient::shader_setter);
+
+    m_property_holder->add_property(
+        "shader",
+        "properties",
+        "this option is resposible for thunderbolt gradient shader",
+        shader.c_str(),
+        string_getter,
+        string_setter,
+        &*environment.shader_ids().begin(),
+        environment.shader_ids().size(),
+        editor::property_holder::value_editor_tree_view,
+        editor::property_holder::cannot_enter_text
+    );
+
+    string_getter.bind(this, &gradient::texture_getter);
+    string_setter.bind(this, &gradient::texture_setter);
+    m_property_holder->add_property(
+        "texture",
+        "",
+        "this option is resposible for thunderbolt gradient texture",
+        texture.c_str(),
+        texture,
+        ".dds",
+        "Texture files (*.dds)|*.dds",
+        detail::real_path("$game_textures$", "").c_str(),
+        "Select texture...",
+        editor::property_holder::cannot_enter_text,
+        editor::property_holder::remove_extension
+    );
 }
 #endif // #ifdef INGAME_EDITOR
diff --git a/src/xrEngine/editor_environment_thunderbolts_gradient.hpp b/src/xrEngine/editor_environment_thunderbolts_gradient.hpp
index 1b69660a415..076c65b724c 100644
--- a/src/xrEngine/editor_environment_thunderbolts_gradient.hpp
+++ b/src/xrEngine/editor_environment_thunderbolts_gradient.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_thunderbolts_gradient.hpp
-//	Created 	: 04.01.2008
-//  Modified 	: 10.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment thunderbolts gradient class
+// Module : editor_environment_thunderbolts_gradient.hpp
+// Created : 04.01.2008
+// Modified : 10.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment thunderbolts gradient class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_THUNDERBOLTS_GRADIENT_HPP_INCLUDED
@@ -15,41 +15,44 @@
 #include "../include/editor/property_holder.hpp"
 #include "thunderbolt.h"
 
-namespace editor {
+namespace editor
+{
 
 class property_holder;
 
-namespace environment {
+namespace environment
+{
 
 class manager;
 
-namespace thunderbolts {
+namespace thunderbolts
+{
 
 class gradient :
-	public SThunderboltDesc::SFlare,
-	private boost::noncopyable
+    public SThunderboltDesc::SFlare,
+    private boost::noncopyable
 {
 public:
-						gradient		();
-						~gradient		();
-			void		load			(CInifile& config, shared_str const& section_id, LPCSTR prefix);
-			void		save			(CInifile& config, shared_str const& section_id, LPCSTR prefix);
-			void		fill			(
-							::editor::environment::manager& environment,
-							LPCSTR name,
-							LPCSTR description,
-							editor::property_holder& holder
-						);
+    gradient();
+    ~gradient();
+    void load(CInifile& config, shared_str const& section_id, LPCSTR prefix);
+    void save(CInifile& config, shared_str const& section_id, LPCSTR prefix);
+    void fill(
+        ::editor::environment::manager& environment,
+        LPCSTR name,
+        LPCSTR description,
+        editor::property_holder& holder
+    );
 
 private:
-	LPCSTR	xr_stdcall	shader_getter	() const;
-	void	xr_stdcall	shader_setter	(LPCSTR	value);
+    LPCSTR xr_stdcall shader_getter() const;
+    void xr_stdcall shader_setter(LPCSTR value);
 
-	LPCSTR	xr_stdcall	texture_getter	() const;
-	void	xr_stdcall	texture_setter	(LPCSTR	value);
+    LPCSTR xr_stdcall texture_getter() const;
+    void xr_stdcall texture_setter(LPCSTR value);
 
 private:
-	property_holder*	m_property_holder;
+    property_holder* m_property_holder;
 }; // class gradient
 
 
diff --git a/src/xrEngine/editor_environment_thunderbolts_manager.cpp b/src/xrEngine/editor_environment_thunderbolts_manager.cpp
index a8405f9a3d8..bd5b70254c3 100644
--- a/src/xrEngine/editor_environment_thunderbolts_manager.cpp
+++ b/src/xrEngine/editor_environment_thunderbolts_manager.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_thunderbolts_manager.cpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment thunderbolts manager class
+// Module : editor_environment_thunderbolts_manager.cpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment thunderbolts manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -26,434 +26,436 @@ using editor::environment::thunderbolts::collection;
 using editor::environment::detail::logical_string_predicate;
 
 template <>
-void property_collection::display_name	(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
+void property_collection::display_name(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
 {
-	xr_strcpy						(buffer, buffer_size, m_container[item_index]->id());
+    xr_strcpy(buffer, buffer_size, m_container[item_index]->id());
 }
 
 template <>
-editor::property_holder* property_collection::create	()
+editor::property_holder* property_collection::create()
 {
-	thunderbolt*					object = xr_new(&m_holder, generate_unique_id("thunderbolt_unique_id_").c_str());
-	object->fill					(m_holder.environment(), this);
-	return							(object->object());
+    thunderbolt* object = xr_new(&m_holder, generate_unique_id("thunderbolt_unique_id_").c_str());
+    object->fill(m_holder.environment(), this);
+    return (object->object());
 }
 
 template <>
-void property_collection::display_name	(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
+void property_collection::display_name(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
 {
-	xr_strcpy						(buffer, buffer_size, m_container[item_index]->id());
+    xr_strcpy(buffer, buffer_size, m_container[item_index]->id());
 }
 
 template <>
-editor::property_holder* property_collection::create	()
+editor::property_holder* property_collection::create()
 {
-	collection*						object = xr_new(m_holder, generate_unique_id("thunderbolt_collection_unique_id_").c_str());
-	object->fill					(this);
-	return							(object->object());
+    collection* object = xr_new(m_holder, generate_unique_id("thunderbolt_collection_unique_id_").c_str());
+    object->fill(this);
+    return (object->object());
 }
 
-manager::manager					(::editor::environment::manager* environment) :
-	m_thunderbolt_collection		(0),
-	m_thunderbolts_changed			(true),
-	m_collections_collection		(0),
-	m_collections_changed			(true),
-	m_property_holder				(0),
-	m_environment					(*environment)
+manager::manager(::editor::environment::manager* environment) :
+    m_thunderbolt_collection(0),
+    m_thunderbolts_changed(true),
+    m_collections_collection(0),
+    m_collections_changed(true),
+    m_property_holder(0),
+    m_environment(*environment)
 {
-	m_thunderbolt_collection		= xr_new(&m_thunderbolts, this, &m_thunderbolts_changed);
-	m_collections_collection		= xr_new(&m_collections, this, &m_collections_changed);
+    m_thunderbolt_collection = xr_new(&m_thunderbolts, this, &m_thunderbolts_changed);
+    m_collections_collection = xr_new(&m_collections, this, &m_collections_changed);
 }
 
-manager::~manager					()
+manager::~manager()
 {
-	xr_delete						(m_thunderbolt_collection);
-	delete_data						(m_thunderbolts);
+    xr_delete(m_thunderbolt_collection);
+    delete_data(m_thunderbolts);
 
-	xr_delete						(m_collections_collection);
-	delete_data						(m_collections);
+    xr_delete(m_collections_collection);
+    delete_data(m_collections);
 
-	delete_data						(m_thunderbolts_ids);
-	delete_data						(m_collections_ids);
+    delete_data(m_thunderbolts_ids);
+    delete_data(m_collections_ids);
 
-	if (!Device.editor() || !m_property_holder)
-		return;
+    if (!Device.editor() || !m_property_holder)
+        return;
 
-	::ide().destroy					(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-void manager::load_thunderbolts		()
+void manager::load_thunderbolts()
 {
-	VERIFY							(m_thunderbolts.empty());
-
-	string_path						file_name;
-	CInifile*						config =
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\thunderbolts.ltx"
-			),
-			TRUE,
-			TRUE,
-			FALSE
-		);
-
-	typedef CInifile::Root			sections_type;
-	sections_type&					sections = config->sections();
-	m_thunderbolts.reserve			(sections.size());
-	sections_type::const_iterator	i = sections.begin();
-	sections_type::const_iterator	e = sections.end();
-	for ( ; i != e; ++i) {
-		thunderbolt*				object = xr_new(this, (*i)->Name);
-		object->load				(*config);
-		object->fill				(m_environment, m_thunderbolt_collection);
-		m_thunderbolts.push_back	(object);
-	}
-
-	xr_delete						(config);
+    VERIFY(m_thunderbolts.empty());
+
+    string_path file_name;
+    CInifile* config =
+        xr_new(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "environment\\thunderbolts.ltx"
+            ),
+            TRUE,
+            TRUE,
+            FALSE
+        );
+
+    typedef CInifile::Root sections_type;
+    sections_type& sections = config->sections();
+    m_thunderbolts.reserve(sections.size());
+    sections_type::const_iterator i = sections.begin();
+    sections_type::const_iterator e = sections.end();
+    for (; i != e; ++i)
+    {
+        thunderbolt* object = xr_new(this, (*i)->Name);
+        object->load(*config);
+        object->fill(m_environment, m_thunderbolt_collection);
+        m_thunderbolts.push_back(object);
+    }
+
+    xr_delete(config);
 }
 
-void manager::save_thunderbolts		()
+void manager::save_thunderbolts()
 {
-	string_path						file_name;
-	CInifile*						config =
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\thunderbolts.ltx"
-			),
-			FALSE,
-			FALSE,
-			TRUE
-		);
-
-	thunderbolt_container_type::const_iterator	i = m_thunderbolts.begin();
-	thunderbolt_container_type::const_iterator	e = m_thunderbolts.end();
-	for ( ; i != e; ++i)
-		(*i)->save					(*config);
-
-	xr_delete						(config);
+    string_path file_name;
+    CInifile* config =
+        xr_new(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "environment\\thunderbolts.ltx"
+            ),
+            FALSE,
+            FALSE,
+            TRUE
+        );
+
+    thunderbolt_container_type::const_iterator i = m_thunderbolts.begin();
+    thunderbolt_container_type::const_iterator e = m_thunderbolts.end();
+    for (; i != e; ++i)
+        (*i)->save(*config);
+
+    xr_delete(config);
 }
 
-void manager::load_collections		()
+void manager::load_collections()
 {
-	VERIFY							(m_collections.empty());
-
-	string_path						file_name;
-	CInifile*						config =
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\thunderbolt_collections.ltx"
-			),
-			TRUE,
-			TRUE,
-			FALSE
-		);
-
-	typedef CInifile::Root			sections_type;
-	sections_type&					sections = config->sections();
-	m_collections.reserve			(sections.size());
-	sections_type::const_iterator	i = sections.begin();
-	sections_type::const_iterator	e = sections.end();
-	for ( ; i != e; ++i) {
-		collection*					object = xr_new(*this, (*i)->Name);
-		object->load				(*config);
-		object->fill				(m_thunderbolt_collection);
-		m_collections.push_back		(object);
-	}
-
-	xr_delete						(config);
+    VERIFY(m_collections.empty());
+
+    string_path file_name;
+    CInifile* config =
+        xr_new(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "environment\\thunderbolt_collections.ltx"
+            ),
+            TRUE,
+            TRUE,
+            FALSE
+        );
+
+    typedef CInifile::Root sections_type;
+    sections_type& sections = config->sections();
+    m_collections.reserve(sections.size());
+    sections_type::const_iterator i = sections.begin();
+    sections_type::const_iterator e = sections.end();
+    for (; i != e; ++i)
+    {
+        collection* object = xr_new(*this, (*i)->Name);
+        object->load(*config);
+        object->fill(m_thunderbolt_collection);
+        m_collections.push_back(object);
+    }
+
+    xr_delete(config);
 }
 
-void manager::save_collections		()
+void manager::save_collections()
 {
-	string_path						file_name;
-	CInifile*						config =
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\thunderbolt_collections.ltx"
-			),
-			FALSE,
-			FALSE,
-			TRUE
-		);
-
-	collection_container_type::const_iterator	i = m_collections.begin();
-	collection_container_type::const_iterator	e = m_collections.end();
-	for ( ; i != e; ++i)
-		(*i)->save					(*config);
-
-	xr_delete						(config);
+    string_path file_name;
+    CInifile* config =
+        xr_new(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "environment\\thunderbolt_collections.ltx"
+            ),
+            FALSE,
+            FALSE,
+            TRUE
+        );
+
+    collection_container_type::const_iterator i = m_collections.begin();
+    collection_container_type::const_iterator e = m_collections.end();
+    for (; i != e; ++i)
+        (*i)->save(*config);
+
+    xr_delete(config);
 }
 
-void manager::load					()
+void manager::load()
 {
-	load_thunderbolts				();
-	load_collections				();
+    load_thunderbolts();
+    load_collections();
 }
 
-void manager::save					()
+void manager::save()
 {
-	save_thunderbolts				();
-	save_collections				();
-
-	string_path						file_name;
-	CInifile*						config =
-		xr_new(
-			FS.update_path(
-				file_name,
-				"$game_config$",
-				"environment\\environment.ltx"
-			),
-			FALSE,
-			FALSE,
-			TRUE
-		);
-
-	CEnvironment&					environment = g_pGamePersistent->Environment();
-	
-	config->w_float					("environment","altitude",			rad2deg(environment.p_var_alt)	);
-	config->w_float					("environment","delta_longitude",	rad2deg(environment.p_var_long)	);
-	config->w_float					("environment","min_dist_factor",	environment.p_min_dist			);
-	config->w_float					("environment","tilt",				rad2deg(environment.p_tilt)		);
-	config->w_float					("environment","second_propability",environment.p_second_prop		);
-	config->w_float					("environment","sky_color",			environment.p_sky_color			);
-	config->w_float					("environment","sun_color",			environment.p_sun_color			);
-	config->w_float					("environment","fog_color",			environment.p_fog_color			);
-
-	xr_delete						(config);
+    save_thunderbolts();
+    save_collections();
+
+    string_path file_name;
+    CInifile* config =
+        xr_new(
+            FS.update_path(
+                file_name,
+                "$game_config$",
+                "environment\\environment.ltx"
+            ),
+            FALSE,
+            FALSE,
+            TRUE
+        );
+
+    CEnvironment& environment = g_pGamePersistent->Environment();
+
+    config->w_float("environment", "altitude", rad2deg(environment.p_var_alt));
+    config->w_float("environment", "delta_longitude", rad2deg(environment.p_var_long));
+    config->w_float("environment", "min_dist_factor", environment.p_min_dist);
+    config->w_float("environment", "tilt", rad2deg(environment.p_tilt));
+    config->w_float("environment", "second_propability", environment.p_second_prop);
+    config->w_float("environment", "sky_color", environment.p_sky_color);
+    config->w_float("environment", "sun_color", environment.p_sun_color);
+    config->w_float("environment", "fog_color", environment.p_fog_color);
+
+    xr_delete(config);
 }
 
-float manager::altitude_getter		() const
+float manager::altitude_getter() const
 {
-	return							(rad2deg(m_environment.p_var_alt));
+    return (rad2deg(m_environment.p_var_alt));
 }
 
-void manager::altitude_setter		(float value)
+void manager::altitude_setter(float value)
 {
-	m_environment.p_var_alt			= deg2rad(value);
+    m_environment.p_var_alt = deg2rad(value);
 }
 
-float manager::longitude_getter		() const
+float manager::longitude_getter() const
 {
-	return							(rad2deg(m_environment.p_var_long));
+    return (rad2deg(m_environment.p_var_long));
 }
 
-void manager::longitude_setter		(float value)
+void manager::longitude_setter(float value)
 {
-	m_environment.p_var_long		= deg2rad(value);
+    m_environment.p_var_long = deg2rad(value);
 }
 
-float manager::tilt_getter			() const
+float manager::tilt_getter() const
 {
-	return							(rad2deg(m_environment.p_tilt));
+    return (rad2deg(m_environment.p_tilt));
 }
 
-void manager::tilt_setter			(float value)
+void manager::tilt_setter(float value)
 {
-	m_environment.p_tilt			= deg2rad(value);
+    m_environment.p_tilt = deg2rad(value);
 }
 
-void manager::fill					(editor::property_holder* holder)
+void manager::fill(editor::property_holder* holder)
 {
-	VERIFY							(holder);
-
-	typedef ::editor::property_holder::float_getter_type	float_getter_type;
-	float_getter_type				float_getter;
-
-	typedef ::editor::property_holder::float_setter_type	float_setter_type;
-	float_setter_type				float_setter;
-
-	float_getter.bind				(this, &manager::altitude_getter);
-	float_setter.bind				(this, &manager::altitude_setter);
-	holder->add_property	(
-		"altitude",
-		"thunderbolts",
-		"this option is resposible for thunderbolts altitude (in degrees)",
-		rad2deg(m_environment.p_var_alt),
-		float_getter,
-		float_setter,
-		-360.0f,
-		 360.f
-	);
-
-	float_getter.bind				(this, &manager::longitude_getter);
-	float_setter.bind				(this, &manager::longitude_setter);
-	holder->add_property	(
-		"delta longitude",
-		"thunderbolts",
-		"this option is resposible for thunderbolts delta longitude (in degrees)",
-		m_environment.p_var_long,
-		float_getter,
-		float_setter,
-		-360.0f,
-		 360.f
-	);
-	holder->add_property	(
-		"minimum distance factor",
-		"thunderbolts",
-		"this option is resposible for thunderbolts minimum distance factor (distance from far plane)",
-		m_environment.p_min_dist,
-		m_environment.p_min_dist,
-		.0f,
-		.95f
-	);
-
-	float_getter.bind				(this, &manager::tilt_getter);
-	float_setter.bind				(this, &manager::tilt_setter);
-	holder->add_property	(
-		"tilt",
-		"thunderbolts",
-		"this option is resposible for thunderbolts tilt (in degrees)",
-		m_environment.p_tilt,
-		float_getter,
-		float_setter,
-		15.f,
-		30.f
-	);
-	holder->add_property	(
-		"second probability",
-		"thunderbolts",
-		"this option is resposible for thunderbolts second probability (0..1)",
-		m_environment.p_second_prop,
-		m_environment.p_second_prop,
-		0.f,
-		1.f
-	);
-	holder->add_property	(
-		"sky color",
-		"thunderbolts",
-		"this option is resposible for thunderbolts sky color (factor)",
-		m_environment.p_sky_color,
-		m_environment.p_sky_color,
-		0.f,
-		1.f
-	);
-	holder->add_property	(
-		"sun color",
-		"thunderbolts",
-		"this option is resposible for thunderbolts sun color (factor)",
-		m_environment.p_sun_color,
-		m_environment.p_sun_color,
-		0.f,
-		1.f
-	);
-	holder->add_property	(
-		"fog color",
-		"thunderbolts",
-		"this option is resposible for thunderbolts fog color (factor)",
-		m_environment.p_fog_color,
-		m_environment.p_fog_color,
-		0.f,
-		1.f
-	);
-	holder->add_property	(
-		"thunderbolt collections",
-		"thunderbolts",
-		"this option is resposible for thunderbolt collections",
-		m_collections_collection
-	);
-	holder->add_property	(
-		"thunderbolts",
-		"thunderbolts",
-		"this option is resposible for thunderbolts",
-		m_thunderbolt_collection
-	);
+    VERIFY(holder);
+
+    typedef ::editor::property_holder::float_getter_type float_getter_type;
+    float_getter_type float_getter;
+
+    typedef ::editor::property_holder::float_setter_type float_setter_type;
+    float_setter_type float_setter;
+
+    float_getter.bind(this, &manager::altitude_getter);
+    float_setter.bind(this, &manager::altitude_setter);
+    holder->add_property(
+        "altitude",
+        "thunderbolts",
+        "this option is resposible for thunderbolts altitude (in degrees)",
+        rad2deg(m_environment.p_var_alt),
+        float_getter,
+        float_setter,
+        -360.0f,
+        360.f
+    );
+
+    float_getter.bind(this, &manager::longitude_getter);
+    float_setter.bind(this, &manager::longitude_setter);
+    holder->add_property(
+        "delta longitude",
+        "thunderbolts",
+        "this option is resposible for thunderbolts delta longitude (in degrees)",
+        m_environment.p_var_long,
+        float_getter,
+        float_setter,
+        -360.0f,
+        360.f
+    );
+    holder->add_property(
+        "minimum distance factor",
+        "thunderbolts",
+        "this option is resposible for thunderbolts minimum distance factor (distance from far plane)",
+        m_environment.p_min_dist,
+        m_environment.p_min_dist,
+        .0f,
+        .95f
+    );
+
+    float_getter.bind(this, &manager::tilt_getter);
+    float_setter.bind(this, &manager::tilt_setter);
+    holder->add_property(
+        "tilt",
+        "thunderbolts",
+        "this option is resposible for thunderbolts tilt (in degrees)",
+        m_environment.p_tilt,
+        float_getter,
+        float_setter,
+        15.f,
+        30.f
+    );
+    holder->add_property(
+        "second probability",
+        "thunderbolts",
+        "this option is resposible for thunderbolts second probability (0..1)",
+        m_environment.p_second_prop,
+        m_environment.p_second_prop,
+        0.f,
+        1.f
+    );
+    holder->add_property(
+        "sky color",
+        "thunderbolts",
+        "this option is resposible for thunderbolts sky color (factor)",
+        m_environment.p_sky_color,
+        m_environment.p_sky_color,
+        0.f,
+        1.f
+    );
+    holder->add_property(
+        "sun color",
+        "thunderbolts",
+        "this option is resposible for thunderbolts sun color (factor)",
+        m_environment.p_sun_color,
+        m_environment.p_sun_color,
+        0.f,
+        1.f
+    );
+    holder->add_property(
+        "fog color",
+        "thunderbolts",
+        "this option is resposible for thunderbolts fog color (factor)",
+        m_environment.p_fog_color,
+        m_environment.p_fog_color,
+        0.f,
+        1.f
+    );
+    holder->add_property(
+        "thunderbolt collections",
+        "thunderbolts",
+        "this option is resposible for thunderbolt collections",
+        m_collections_collection
+    );
+    holder->add_property(
+        "thunderbolts",
+        "thunderbolts",
+        "this option is resposible for thunderbolts",
+        m_thunderbolt_collection
+    );
 }
 
-manager::thunderbolts_ids_type const& manager::thunderbolts_ids	() const
+manager::thunderbolts_ids_type const& manager::thunderbolts_ids() const
 {
-	if (!m_thunderbolts_changed)
-		return						(m_thunderbolts_ids);
+    if (!m_thunderbolts_changed)
+        return (m_thunderbolts_ids);
 
-	delete_data						(m_thunderbolts_ids);
+    delete_data(m_thunderbolts_ids);
 
-	m_thunderbolts_ids.resize		(m_thunderbolts.size());
+    m_thunderbolts_ids.resize(m_thunderbolts.size());
 
-	thunderbolt_container_type::const_iterator	i = m_thunderbolts.begin();
-	thunderbolt_container_type::const_iterator	e = m_thunderbolts.end();
-	thunderbolts_ids_type::iterator				j = m_thunderbolts_ids.begin();
-	for ( ; i != e; ++i, ++j)
-		*j							= xr_strdup((*i)->id());
+    thunderbolt_container_type::const_iterator i = m_thunderbolts.begin();
+    thunderbolt_container_type::const_iterator e = m_thunderbolts.end();
+    thunderbolts_ids_type::iterator j = m_thunderbolts_ids.begin();
+    for (; i != e; ++i, ++j)
+        *j = xr_strdup((*i)->id());
 
-	std::sort						(m_thunderbolts_ids.begin(), m_thunderbolts_ids.end(), logical_string_predicate());
+    std::sort(m_thunderbolts_ids.begin(), m_thunderbolts_ids.end(), logical_string_predicate());
 
-	return							(m_thunderbolts_ids);
+    return (m_thunderbolts_ids);
 }
 
-manager::thunderbolts_ids_type const& manager::collections_ids	() const
+manager::thunderbolts_ids_type const& manager::collections_ids() const
 {
-	if (!m_collections_changed)
-		return						(m_collections_ids);
+    if (!m_collections_changed)
+        return (m_collections_ids);
 
-	delete_data						(m_collections_ids);
+    delete_data(m_collections_ids);
 
-	m_collections_ids.resize		(m_collections.size() + 1);
-	m_collections_ids[0]			= xr_strdup("");
+    m_collections_ids.resize(m_collections.size() + 1);
+    m_collections_ids[0] = xr_strdup("");
 
-	collection_container_type::const_iterator	i = m_collections.begin();
-	collection_container_type::const_iterator	e = m_collections.end();
-	collections_ids_type::iterator				j = m_collections_ids.begin() + 1;
-	for ( ; i != e; ++i, ++j)
-		*j							= xr_strdup((*i)->id());
+    collection_container_type::const_iterator i = m_collections.begin();
+    collection_container_type::const_iterator e = m_collections.end();
+    collections_ids_type::iterator j = m_collections_ids.begin() + 1;
+    for (; i != e; ++i, ++j)
+        *j = xr_strdup((*i)->id());
 
-	std::sort						(m_collections_ids.begin(), m_collections_ids.end(), logical_string_predicate());
+    std::sort(m_collections_ids.begin(), m_collections_ids.end(), logical_string_predicate());
 
-	return							(m_collections_ids);
+    return (m_collections_ids);
 }
 
 ::editor::environment::manager& manager::environment() const
 {
-	return							(m_environment);
+    return (m_environment);
 }
 
-shared_str manager::unique_thunderbolt_id	(shared_str const& id) const
+shared_str manager::unique_thunderbolt_id(shared_str const& id) const
 {
-	if (m_thunderbolt_collection->unique_id(id.c_str()))
-		return				(id);
+    if (m_thunderbolt_collection->unique_id(id.c_str()))
+        return (id);
 
-	return					(m_thunderbolt_collection->generate_unique_id(id.c_str()));
+    return (m_thunderbolt_collection->generate_unique_id(id.c_str()));
 }
 
-shared_str manager::unique_collection_id	(shared_str const& id) const
+shared_str manager::unique_collection_id(shared_str const& id) const
 {
-	if (m_collections_collection->unique_id(id.c_str()))
-		return				(id);
+    if (m_collections_collection->unique_id(id.c_str()))
+        return (id);
 
-	return					(m_collections_collection->generate_unique_id(id.c_str()));
+    return (m_collections_collection->generate_unique_id(id.c_str()));
 }
 
-SThunderboltDesc* manager::description		(CInifile& config, shared_str const& section) const
+SThunderboltDesc* manager::description(CInifile& config, shared_str const& section) const
 {
-	thunderbolt_container_type::const_iterator	i = m_thunderbolts.begin();
-	thunderbolt_container_type::const_iterator	e = m_thunderbolts.end();
-	for ( ; i != e; ++i)
-		if ((*i)->id() == section)
-			return			(*i);
+    thunderbolt_container_type::const_iterator i = m_thunderbolts.begin();
+    thunderbolt_container_type::const_iterator e = m_thunderbolts.end();
+    for (; i != e; ++i)
+        if ((*i)->id() == section)
+            return (*i);
 
-	NODEFAULT;
+    NODEFAULT;
 #ifdef DEBUG
-	return					(0);
+    return (0);
 #endif // #ifdef DEBUG
 }
 
-SThunderboltCollection* manager::get_collection	(shared_str const& section)
+SThunderboltCollection* manager::get_collection(shared_str const& section)
 {
-	collection_container_type::iterator	i = m_collections.begin();
-	collection_container_type::iterator	e = m_collections.end();
-	for ( ; i != e; ++i)
-		if ((*i)->id() == section)
-			return			(*i);
+    collection_container_type::iterator i = m_collections.begin();
+    collection_container_type::iterator e = m_collections.end();
+    for (; i != e; ++i)
+        if ((*i)->id() == section)
+            return (*i);
 
-	NODEFAULT;
+    NODEFAULT;
 #ifdef DEBUG
-	return					(0);
+    return (0);
 #endif // #ifdef DEBUG
 }
 
diff --git a/src/xrEngine/editor_environment_thunderbolts_manager.hpp b/src/xrEngine/editor_environment_thunderbolts_manager.hpp
index e7ebc18bd47..a762efef2a5 100644
--- a/src/xrEngine/editor_environment_thunderbolts_manager.hpp
+++ b/src/xrEngine/editor_environment_thunderbolts_manager.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_thunderbolts_manager.hpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment thunderbolts manager class
+// Module : editor_environment_thunderbolts_manager.hpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment thunderbolts manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_THUNDERBOLTS_MANAGER_HPP_INCLUDED
@@ -17,83 +17,87 @@
 struct SThunderboltDesc;
 struct SThunderboltCollection;
 
-namespace editor {
+namespace editor
+{
 
 class property_holder;
 
-namespace environment {
+namespace environment
+{
 
 class manager;
 
-namespace thunderbolts {
+namespace thunderbolts
+{
 
 class thunderbolt;
 class thunderbolt_id;
 class collection;
 
-class manager : private boost::noncopyable {
+class manager : private boost::noncopyable
+{
 public:
-							manager		(::editor::environment::manager* environment);
-							~manager	();
-			void			load		();
-			void			save		();
-			void			fill		(editor::property_holder* holder);
-			SThunderboltDesc*		description		(CInifile& config, shared_str const& section) const;
-			SThunderboltCollection*	get_collection	(shared_str const& section);
+    manager(::editor::environment::manager* environment);
+    ~manager();
+    void load();
+    void save();
+    void fill(editor::property_holder* holder);
+    SThunderboltDesc* description(CInifile& config, shared_str const& section) const;
+    SThunderboltCollection* get_collection(shared_str const& section);
 
 public:
-			shared_str		unique_thunderbolt_id	(shared_str const& id) const;
-			shared_str		unique_collection_id	(shared_str const& id) const;
+    shared_str unique_thunderbolt_id(shared_str const& id) const;
+    shared_str unique_collection_id(shared_str const& id) const;
 
 public:
-	typedef xr_vector		thunderbolt_container_type;
-	typedef xr_vector		collection_container_type;
-	typedef xr_vector			thunderbolts_ids_type;
-	typedef xr_vector			collections_ids_type;
+    typedef xr_vector thunderbolt_container_type;
+    typedef xr_vector collection_container_type;
+    typedef xr_vector thunderbolts_ids_type;
+    typedef xr_vector collections_ids_type;
 
 public:
-	thunderbolts_ids_type const& thunderbolts_ids	() const;
-	collections_ids_type const& collections_ids		() const;
-	::editor::environment::manager&	environment		() const;
+    thunderbolts_ids_type const& thunderbolts_ids() const;
+    collections_ids_type const& collections_ids() const;
+    ::editor::environment::manager& environment() const;
 
 private:
-			void			load_thunderbolts		();
-			void			load_collections		();
-			void			save_thunderbolts		();
-			void			save_collections		();
+    void load_thunderbolts();
+    void load_collections();
+    void save_thunderbolts();
+    void save_collections();
 
 private:
-	typedef editor::property_holder		property_holder_type;
-	typedef property_collection<
-				thunderbolt_container_type,
-				manager
-			>							thunderbolt_collection_type;
-	typedef property_collection<
-				collection_container_type,
-				manager
-			>							collection_collection_type;
+    typedef editor::property_holder property_holder_type;
+    typedef property_collection <
+    thunderbolt_container_type,
+    manager
+    > thunderbolt_collection_type;
+    typedef property_collection <
+    collection_container_type,
+    manager
+    > collection_collection_type;
 
 private:
-			float xr_stdcall altitude_getter		() const;
-			void xr_stdcall  altitude_setter		(float value);
-			float xr_stdcall longitude_getter		() const;
-			void xr_stdcall  longitude_setter		(float value);
-			float xr_stdcall tilt_getter			() const;
-			void xr_stdcall	 tilt_setter			(float value);
+    float xr_stdcall altitude_getter() const;
+    void xr_stdcall altitude_setter(float value);
+    float xr_stdcall longitude_getter() const;
+    void xr_stdcall longitude_setter(float value);
+    float xr_stdcall tilt_getter() const;
+    void xr_stdcall tilt_setter(float value);
 
 private:
-	thunderbolt_container_type			m_thunderbolts;
-	thunderbolt_collection_type*		m_thunderbolt_collection;
-	bool								m_thunderbolts_changed;
-
-	collection_container_type			m_collections;
-	collection_collection_type*			m_collections_collection;
-	bool								m_collections_changed;
-
-	mutable thunderbolts_ids_type		m_thunderbolts_ids;
-	mutable collections_ids_type		m_collections_ids;
-	property_holder_type*				m_property_holder;
-	::editor::environment::manager&		m_environment;
+    thunderbolt_container_type m_thunderbolts;
+    thunderbolt_collection_type* m_thunderbolt_collection;
+    bool m_thunderbolts_changed;
+
+    collection_container_type m_collections;
+    collection_collection_type* m_collections_collection;
+    bool m_collections_changed;
+
+    mutable thunderbolts_ids_type m_thunderbolts_ids;
+    mutable collections_ids_type m_collections_ids;
+    property_holder_type* m_property_holder;
+    ::editor::environment::manager& m_environment;
 }; // class manager
 } // namespace thunderbolts
 } // namespace environment
diff --git a/src/xrEngine/editor_environment_thunderbolts_thunderbolt.cpp b/src/xrEngine/editor_environment_thunderbolts_thunderbolt.cpp
index 97232ea55cd..2dbae5c3c1c 100644
--- a/src/xrEngine/editor_environment_thunderbolts_thunderbolt.cpp
+++ b/src/xrEngine/editor_environment_thunderbolts_thunderbolt.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_thunderbolts_thunderbolt.cpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment thunderbolts thunderbolt class
+// Module : editor_environment_thunderbolts_thunderbolt.cpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment thunderbolts thunderbolt class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -19,147 +19,147 @@
 using editor::environment::thunderbolts::thunderbolt;
 using editor::environment::thunderbolts::manager;
 
-thunderbolt::thunderbolt		(manager* manager, shared_str const& id) :
-	m_manager			(*manager),
-	m_id				(id),
-	m_property_holder	(0)
+thunderbolt::thunderbolt(manager* manager, shared_str const& id) :
+    m_manager(*manager),
+    m_id(id),
+    m_property_holder(0)
 {
 }
 
-thunderbolt::~thunderbolt		()
+thunderbolt::~thunderbolt()
 {
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy		(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
-void thunderbolt::create_top_gradient	(CInifile& config, shared_str const& section)
+void thunderbolt::create_top_gradient(CInifile& config, shared_str const& section)
 {
-	VERIFY				(section == m_id);
-	m_top				= xr_new();
-	m_top->load			(config, section, "gradient_top");
-	m_GradientTop		= m_top;
+    VERIFY(section == m_id);
+    m_top = xr_new();
+    m_top->load(config, section, "gradient_top");
+    m_GradientTop = m_top;
 }
 
 void thunderbolt::create_center_gradient(CInifile& config, shared_str const& section)
 {
-	VERIFY				(section == m_id);
-	m_center			= xr_new();
-	m_center->load		(config, section, "gradient_center");
-	m_GradientCenter	= m_center;
+    VERIFY(section == m_id);
+    m_center = xr_new();
+    m_center->load(config, section, "gradient_center");
+    m_GradientCenter = m_center;
 }
 
-void thunderbolt::load			(CInifile& config)
+void thunderbolt::load(CInifile& config)
 {
-	inherited::load		(config, m_id);
-	m_color_animator	= config.r_string	(m_id, "color_anim");
-	m_lighting_model	= config.r_string	(m_id, "lightning_model");
-	m_sound				= config.r_string	(m_id, "sound");
+    inherited::load(config, m_id);
+    m_color_animator = config.r_string(m_id, "color_anim");
+    m_lighting_model = config.r_string(m_id, "lightning_model");
+    m_sound = config.r_string(m_id, "sound");
 }
 
-void thunderbolt::save			(CInifile& config)
+void thunderbolt::save(CInifile& config)
 {
-	m_top->save			(config, m_id, "gradient_top");
-	m_center->save		(config, m_id, "gradient_center");
-	config.w_string		(m_id.c_str(), "color_anim",		m_color_animator.c_str());
-	config.w_string		(m_id.c_str(), "lightning_model",	m_lighting_model.c_str());
-	config.w_string		(m_id.c_str(), "sound",				m_sound.c_str()			);
+    m_top->save(config, m_id, "gradient_top");
+    m_center->save(config, m_id, "gradient_center");
+    config.w_string(m_id.c_str(), "color_anim", m_color_animator.c_str());
+    config.w_string(m_id.c_str(), "lightning_model", m_lighting_model.c_str());
+    config.w_string(m_id.c_str(), "sound", m_sound.c_str());
 }
 
-LPCSTR thunderbolt::id_getter	() const
+LPCSTR thunderbolt::id_getter() const
 {
-	return				(m_id.c_str());
+    return (m_id.c_str());
 }
 
-void thunderbolt::id_setter		(LPCSTR value_)
+void thunderbolt::id_setter(LPCSTR value_)
 {
-	shared_str			value = value_;
-	if (m_id._get() == value._get())
-		return;
+    shared_str value = value_;
+    if (m_id._get() == value._get())
+        return;
 
-	m_id				= m_manager.unique_thunderbolt_id(value);
+    m_id = m_manager.unique_thunderbolt_id(value);
 }
 
-void thunderbolt::fill			(
-		::editor::environment::manager& environment,
-		::editor::property_holder_collection* collection
-	)
+void thunderbolt::fill(
+    ::editor::environment::manager& environment,
+    ::editor::property_holder_collection* collection
+)
 {
-	VERIFY				(!m_property_holder);
-	m_property_holder	= ::ide().create_property_holder(m_id.c_str(), collection, this);
-
-	typedef editor::property_holder::string_getter_type	string_getter_type;
-	string_getter_type	string_getter;
-	string_getter.bind	(this, &thunderbolt::id_getter);
-
-	typedef editor::property_holder::string_setter_type	string_setter_type;
-	string_setter_type	string_setter;
-	string_setter.bind	(this, &thunderbolt::id_setter);
-
-	m_property_holder->add_property(
-		"id",
-		"properties",
-		"this option is resposible for thunderbolt id",
-		m_id.c_str(),
-		string_getter,
-		string_setter
-	);
-	m_property_holder->add_property(
-		"color animator",
-		"properties",
-		"this option is resposible for thunderbolt color animator",
-		m_color_animator.c_str(),
-		m_color_animator,
-		&*environment.light_animator_ids().begin(),
-		environment.light_animator_ids().size(),
-		editor::property_holder::value_editor_tree_view,
-		editor::property_holder::cannot_enter_text
-	);
-	m_property_holder->add_property(
-		"lighting model",
-		"properties",
-		"this option is resposible for thunderbolt lighting model",
-		m_lighting_model.c_str(),
-		m_lighting_model,
-		".dm",
-		"Lighting model files (*.dm)|*.dm",
-		detail::real_path("$game_meshes$", "").c_str(),
-		"Select lighting model...",
-		editor::property_holder::cannot_enter_text,
-		editor::property_holder::keep_extension
-	);
-	m_property_holder->add_property(
-		"sound",
-		"properties",
-		"this option is resposible for thunderbolt sound",
-		m_sound.c_str(),
-		m_sound,
-		".ogg",
-		"Sound files (*.ogg)|*.ogg",
-		detail::real_path("$game_sounds$", "").c_str(),
-		"Select sound...",
-		editor::property_holder::cannot_enter_text,
-		editor::property_holder::remove_extension
-	);
-
-	m_center->fill		(
-		environment,
-		"center",
-		"this option is resposible for thunderbolt gradient center",
-		*m_property_holder
-	);
-	m_top->fill			(
-		environment,
-		"top",
-		"this option is resposible for thunderbolt gradient top",
-		*m_property_holder
-	);
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder(m_id.c_str(), collection, this);
+
+    typedef editor::property_holder::string_getter_type string_getter_type;
+    string_getter_type string_getter;
+    string_getter.bind(this, &thunderbolt::id_getter);
+
+    typedef editor::property_holder::string_setter_type string_setter_type;
+    string_setter_type string_setter;
+    string_setter.bind(this, &thunderbolt::id_setter);
+
+    m_property_holder->add_property(
+        "id",
+        "properties",
+        "this option is resposible for thunderbolt id",
+        m_id.c_str(),
+        string_getter,
+        string_setter
+    );
+    m_property_holder->add_property(
+        "color animator",
+        "properties",
+        "this option is resposible for thunderbolt color animator",
+        m_color_animator.c_str(),
+        m_color_animator,
+        &*environment.light_animator_ids().begin(),
+        environment.light_animator_ids().size(),
+        editor::property_holder::value_editor_tree_view,
+        editor::property_holder::cannot_enter_text
+    );
+    m_property_holder->add_property(
+        "lighting model",
+        "properties",
+        "this option is resposible for thunderbolt lighting model",
+        m_lighting_model.c_str(),
+        m_lighting_model,
+        ".dm",
+        "Lighting model files (*.dm)|*.dm",
+        detail::real_path("$game_meshes$", "").c_str(),
+        "Select lighting model...",
+        editor::property_holder::cannot_enter_text,
+        editor::property_holder::keep_extension
+    );
+    m_property_holder->add_property(
+        "sound",
+        "properties",
+        "this option is resposible for thunderbolt sound",
+        m_sound.c_str(),
+        m_sound,
+        ".ogg",
+        "Sound files (*.ogg)|*.ogg",
+        detail::real_path("$game_sounds$", "").c_str(),
+        "Select sound...",
+        editor::property_holder::cannot_enter_text,
+        editor::property_holder::remove_extension
+    );
+
+    m_center->fill(
+        environment,
+        "center",
+        "this option is resposible for thunderbolt gradient center",
+        *m_property_holder
+    );
+    m_top->fill(
+        environment,
+        "top",
+        "this option is resposible for thunderbolt gradient top",
+        *m_property_holder
+    );
 }
 
-thunderbolt::property_holder_type* thunderbolt::object	()
+thunderbolt::property_holder_type* thunderbolt::object()
 {
-	return				(m_property_holder);
+    return (m_property_holder);
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_thunderbolts_thunderbolt.hpp b/src/xrEngine/editor_environment_thunderbolts_thunderbolt.hpp
index 31a459a167b..6e8413ec5c8 100644
--- a/src/xrEngine/editor_environment_thunderbolts_thunderbolt.hpp
+++ b/src/xrEngine/editor_environment_thunderbolts_thunderbolt.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_thunderbolts_thunderbolt.hpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment thunderbolts thunderbolt class
+// Module : editor_environment_thunderbolts_thunderbolt.hpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment thunderbolts thunderbolt class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_THUNDERBOLTS_THUNDERBOLT_HPP_INCLUDED
@@ -16,53 +16,56 @@
 #include "editor_environment_thunderbolts_gradient.hpp"
 #include "thunderbolt.h"
 
-namespace editor {
-namespace environment {
+namespace editor
+{
+namespace environment
+{
 
 class manager;
 
-namespace thunderbolts {
+namespace thunderbolts
+{
 
 class manager;
 
 class thunderbolt :
-	public SThunderboltDesc,
-	public editor::property_holder_holder,
-	private boost::noncopyable
+    public SThunderboltDesc,
+    public editor::property_holder_holder,
+    private boost::noncopyable
 {
 private:
-	typedef SThunderboltDesc			inherited;
+    typedef SThunderboltDesc inherited;
 
 public:
-							thunderbolt				(manager* manager, shared_str const& id);
-	virtual					~thunderbolt			();
-			void			load					(CInifile& config);
-			void			save					(CInifile& config);
-			void			fill					(::editor::environment::manager& environment, editor::property_holder_collection* collection);
-	inline	LPCSTR			id						() const { return m_id.c_str(); }
-	virtual	void			create_top_gradient		(CInifile& pIni, shared_str const& sect);
-	virtual	void			create_center_gradient	(CInifile& pIni, shared_str const& sect);
+    thunderbolt(manager* manager, shared_str const& id);
+    virtual ~thunderbolt();
+    void load(CInifile& config);
+    void save(CInifile& config);
+    void fill(::editor::environment::manager& environment, editor::property_holder_collection* collection);
+    inline LPCSTR id() const { return m_id.c_str(); }
+    virtual void create_top_gradient(CInifile& pIni, shared_str const& sect);
+    virtual void create_center_gradient(CInifile& pIni, shared_str const& sect);
 
 private:
-			LPCSTR xr_stdcall id_getter	() const;
-			void   xr_stdcall id_setter	(LPCSTR value);
+    LPCSTR xr_stdcall id_getter() const;
+    void xr_stdcall id_setter(LPCSTR value);
 private:
-	typedef editor::property_holder		property_holder_type;
+    typedef editor::property_holder property_holder_type;
 
 public:
-	virtual	property_holder_type* object();
+    virtual property_holder_type* object();
 
 private:
-	shared_str				m_id;
-	manager&				m_manager;
-	property_holder_type*	m_property_holder;
+    shared_str m_id;
+    manager& m_manager;
+    property_holder_type* m_property_holder;
 
 private:
-	gradient*				m_center;
-	gradient*				m_top;
-	shared_str				m_color_animator;
-	shared_str				m_lighting_model;
-	shared_str				m_sound;
+    gradient* m_center;
+    gradient* m_top;
+    shared_str m_color_animator;
+    shared_str m_lighting_model;
+    shared_str m_sound;
 }; // class thunderbolt
 
 } // namespace thunderbolts
diff --git a/src/xrEngine/editor_environment_thunderbolts_thunderbolt_id.cpp b/src/xrEngine/editor_environment_thunderbolts_thunderbolt_id.cpp
index 786bbf80864..97c67c23e94 100644
--- a/src/xrEngine/editor_environment_thunderbolts_thunderbolt_id.cpp
+++ b/src/xrEngine/editor_environment_thunderbolts_thunderbolt_id.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_thunderbolts_thunderbolt_id.cpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment thunderbolts thunderbolt identifier class
+// Module : editor_environment_thunderbolts_thunderbolt_id.cpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment thunderbolts thunderbolt identifier class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -16,60 +16,60 @@
 using editor::environment::thunderbolts::thunderbolt_id;
 using editor::environment::thunderbolts::manager;
 
-thunderbolt_id::thunderbolt_id			(manager const& manager, shared_str const& id) :
-	m_manager						(manager),
-	m_id							(id),
-	m_property_holder				(0)
+thunderbolt_id::thunderbolt_id(manager const& manager, shared_str const& id) :
+    m_manager(manager),
+    m_id(id),
+    m_property_holder(0)
 {
 }
 
-thunderbolt_id::~thunderbolt_id			()
+thunderbolt_id::~thunderbolt_id()
 {
-	if (!Device.editor())
-		return;
+    if (!Device.editor())
+        return;
 
-	::ide().destroy					(m_property_holder);
+    ::ide().destroy(m_property_holder);
 }
 
 LPCSTR const* thunderbolt_id::collection()
 {
-	return							(&*m_manager.thunderbolts_ids().begin());
+    return (&*m_manager.thunderbolts_ids().begin());
 }
 
-u32 thunderbolt_id::collection_size		()
+u32 thunderbolt_id::collection_size()
 {
-	return							(m_manager.thunderbolts_ids().size());
+    return (m_manager.thunderbolts_ids().size());
 }
 
-void thunderbolt_id::fill				(editor::property_holder_collection* collection)
+void thunderbolt_id::fill(editor::property_holder_collection* collection)
 {
-	VERIFY							(!m_property_holder);
-	m_property_holder				= ::ide().create_property_holder(m_id.c_str(), collection, this);
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder(m_id.c_str(), collection, this);
 
-	typedef editor::property_holder::string_collection_getter_type	collection_getter_type;
-	collection_getter_type			collection_getter;
-	collection_getter.bind			(this, &thunderbolt_id::collection);
+    typedef editor::property_holder::string_collection_getter_type collection_getter_type;
+    collection_getter_type collection_getter;
+    collection_getter.bind(this, &thunderbolt_id::collection);
 
-	typedef editor::property_holder::string_collection_size_getter_type	collection_size_getter_type;
-	collection_size_getter_type		collection_size_getter;
-	collection_size_getter.bind		(this, &thunderbolt_id::collection_size);
+    typedef editor::property_holder::string_collection_size_getter_type collection_size_getter_type;
+    collection_size_getter_type collection_size_getter;
+    collection_size_getter.bind(this, &thunderbolt_id::collection_size);
 
-	m_property_holder->add_property	(
-		"thunderbolt",
-		"properties",
-		"this option is resposible for thunderbolt",
-		m_id.c_str(),
-		m_id,
-		collection_getter,
-		collection_size_getter,
-		editor::property_holder::value_editor_combo_box,
-		editor::property_holder::cannot_enter_text
-	);
+    m_property_holder->add_property(
+        "thunderbolt",
+        "properties",
+        "this option is resposible for thunderbolt",
+        m_id.c_str(),
+        m_id,
+        collection_getter,
+        collection_size_getter,
+        editor::property_holder::value_editor_combo_box,
+        editor::property_holder::cannot_enter_text
+    );
 }
 
-thunderbolt_id::property_holder_type* thunderbolt_id::object	()
+thunderbolt_id::property_holder_type* thunderbolt_id::object()
 {
-	return							(m_property_holder);
+    return (m_property_holder);
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_thunderbolts_thunderbolt_id.hpp b/src/xrEngine/editor_environment_thunderbolts_thunderbolt_id.hpp
index a0b23daa190..f857e170095 100644
--- a/src/xrEngine/editor_environment_thunderbolts_thunderbolt_id.hpp
+++ b/src/xrEngine/editor_environment_thunderbolts_thunderbolt_id.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_thunderbolts_thunderbolt_id.hpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment thunderbolts thunderbolt identifier class
+// Module : editor_environment_thunderbolts_thunderbolt_id.hpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment thunderbolts thunderbolt identifier class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_WEATHER_THUNDERBOLTS_THUNDERBOLT_ID_HPP_INCLUDED
@@ -14,38 +14,42 @@
 #include 
 #include "../include/editor/property_holder.hpp"
 
-namespace editor {
+namespace editor
+{
 
 class property_holder_collection;
 
-namespace environment {
-namespace thunderbolts {
+namespace environment
+{
+namespace thunderbolts
+{
 
 class manager;
 
 class thunderbolt_id :
-	public editor::property_holder_holder,
-	private boost::noncopyable {
+    public editor::property_holder_holder,
+    private boost::noncopyable
+{
 public:
-							thunderbolt_id	(manager const& manager, shared_str const& thunderbolt);
-	virtual					~thunderbolt_id	();
-			void			fill			(editor::property_holder_collection* collection);
-	inline	LPCSTR			id				() const { return m_id.c_str(); }
+    thunderbolt_id(manager const& manager, shared_str const& thunderbolt);
+    virtual ~thunderbolt_id();
+    void fill(editor::property_holder_collection* collection);
+    inline LPCSTR id() const { return m_id.c_str(); }
 
 private:
-	typedef editor::property_holder			property_holder_type;
+    typedef editor::property_holder property_holder_type;
 
 public:
-	virtual	property_holder_type* object	();
+    virtual property_holder_type* object();
 
 private:
-	LPCSTR const* xr_stdcall collection		();
-	u32  xr_stdcall			collection_size	();
+    LPCSTR const* xr_stdcall collection();
+    u32 xr_stdcall collection_size();
 
 private:
-	property_holder_type*	m_property_holder;
-	manager const&			m_manager;
-	shared_str				m_id;
+    property_holder_type* m_property_holder;
+    manager const& m_manager;
+    shared_str m_id;
 }; // class thunderbolt_id
 } // namespace thunderbolts
 } // namespace environment
diff --git a/src/xrEngine/editor_environment_weathers_manager.cpp b/src/xrEngine/editor_environment_weathers_manager.cpp
index 0f14c2dbac5..2e16ada7ec6 100644
--- a/src/xrEngine/editor_environment_weathers_manager.cpp
+++ b/src/xrEngine/editor_environment_weathers_manager.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_manager.cpp
-//	Created 	: 04.01.2008
-//  Modified 	: 04.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment manager class
+// Module : editor_environment_manager.cpp
+// Created : 04.01.2008
+// Modified : 04.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -24,327 +24,335 @@ using editor::environment::weathers::weather;
 using editor::environment::detail::logical_string_predicate;
 
 template <>
-void property_collection::display_name	(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
+void property_collection::display_name(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
 {
-	xr_strcpy						(buffer, buffer_size, m_container[item_index]->id().c_str());
+    xr_strcpy(buffer, buffer_size, m_container[item_index]->id().c_str());
 }
 
 template <>
-editor::property_holder* property_collection::create	()
+editor::property_holder* property_collection::create()
 {
-	weather*						object = xr_new(&m_holder.m_manager, generate_unique_id("weather_unique_id_").c_str());
-	object->fill					(this);
-	return							(object->object());
+    weather* object = xr_new(&m_holder.m_manager, generate_unique_id("weather_unique_id_").c_str());
+    object->fill(this);
+    return (object->object());
 }
 
-manager::manager			(editor::environment::manager* manager) :
-	m_manager						(*manager),
-	m_collection					(0),
-	m_changed						(true)
+manager::manager(editor::environment::manager* manager) :
+    m_manager(*manager),
+    m_collection(0),
+    m_changed(true)
 {
-	m_collection					= xr_new(&m_weathers, this, &m_changed);
+    m_collection = xr_new(&m_weathers, this, &m_changed);
 }
 
-manager::~manager			()
+manager::~manager()
 {
-	xr_delete						(m_collection);
-	delete_data						(m_weathers);
+    xr_delete(m_collection);
+    delete_data(m_weathers);
 
-	delete_data						(m_weather_ids);
-	delete_data						(m_times_ids);
+    delete_data(m_weather_ids);
+    delete_data(m_times_ids);
 }
 
-void manager::load			()
+void manager::load()
 {
-	typedef xr_vector		file_list_type;
-	file_list_type*					file_list = FS.file_list_open("$game_weathers$","");
-	VERIFY							(file_list);
+    typedef xr_vector file_list_type;
+    file_list_type* file_list = FS.file_list_open("$game_weathers$", "");
+    VERIFY(file_list);
     xr_string id;
-	file_list_type::const_iterator	i = file_list->begin();
-	file_list_type::const_iterator	e = file_list->end();
-	for ( ; i != e; ++i) {
-		u32							length = xr_strlen(*i);
-		if (length <= 4)
-			continue;
+    file_list_type::const_iterator i = file_list->begin();
+    file_list_type::const_iterator e = file_list->end();
+    for (; i != e; ++i)
+    {
+        u32 length = xr_strlen(*i);
+        if (length <= 4)
+            continue;
 
-		if ((*i)[length - 4] != '.')
-			continue;
+        if ((*i)[length - 4] != '.')
+            continue;
 
-		if ((*i)[length - 3] != 'l')
-			continue;
+        if ((*i)[length - 3] != 'l')
+            continue;
 
-		if ((*i)[length - 2] != 't')
-			continue;
+        if ((*i)[length - 2] != 't')
+            continue;
 
-		if ((*i)[length - 1] != 'x')
-			continue;
+        if ((*i)[length - 1] != 'x')
+            continue;
 
         id = *i;
-        id[length-4] = 0;
-		weather*					object = xr_new(&m_manager, id.c_str());
-		object->load				();
-		object->fill				(m_collection);
-		m_weathers.push_back		(object);
-	}
-
-	FS.file_list_close				(file_list);
+        id[length - 4] = 0;
+        weather* object = xr_new(&m_manager, id.c_str());
+        object->load();
+        object->fill(m_collection);
+        m_weathers.push_back(object);
+    }
+
+    FS.file_list_close(file_list);
 }
 
-void manager::save					()
+void manager::save()
 {
-	weather_container_type::iterator	i =m_weathers.begin();
-	weather_container_type::iterator	e =m_weathers.end();
-	for ( ; i != e; ++i)
-		(*i)->save					();
+    weather_container_type::iterator i = m_weathers.begin();
+    weather_container_type::iterator e = m_weathers.end();
+    for (; i != e; ++i)
+        (*i)->save();
 }
 
-LPCSTR const* manager::weathers_getter	() const
+LPCSTR const* manager::weathers_getter() const
 {
-	return							(&*weather_ids().begin());
+    return (&*weather_ids().begin());
 }
 
-u32 manager::weathers_size_getter		() const
+u32 manager::weathers_size_getter() const
 {
-	return							(weather_ids().size());
+    return (weather_ids().size());
 }
 
-struct predicate {
-	shared_str		value;
+struct predicate
+{
+    shared_str value;
 
-	inline			predicate	(LPCSTR const& value_) :
-		value						(value_)
-	{
-	}
+    inline predicate(LPCSTR const& value_) :
+        value(value_)
+    {
+    }
 
-	inline	bool	operator()	(weather const* weather) const
-	{
-		return						(value._get() == weather->id()._get());
-	}
+    inline bool operator() (weather const* weather) const
+    {
+        return (value._get() == weather->id()._get());
+    }
 }; // struct predicate
 
-LPCSTR const* manager::frames_getter	(LPCSTR weather_id) const
+LPCSTR const* manager::frames_getter(LPCSTR weather_id) const
 {
-	delete_data						(m_times_ids);
+    delete_data(m_times_ids);
 
-	weather_container_type::const_iterator	found =
-		std::find_if(
-			m_weathers.begin(),
-			m_weathers.end(),
-			predicate(weather_id)
-		);
+    weather_container_type::const_iterator found =
+        std::find_if(
+            m_weathers.begin(),
+            m_weathers.end(),
+            predicate(weather_id)
+        );
 
-	if (found == m_weathers.end())
-		return						(0);
+    if (found == m_weathers.end())
+        return (0);
 
-	typedef weather::container_type	container_type;
-	container_type const&			times = (*found)->times();
+    typedef weather::container_type container_type;
+    container_type const& times = (*found)->times();
 
-	m_times_ids.resize				(times.size());
-	times_ids_type::iterator		j = m_times_ids.begin();
-	container_type::const_iterator	i = times.begin();
-	container_type::const_iterator	e = times.end();
-	for ( ; i != e; ++i, ++j)
-		*j							= xr_strdup((*i)->id().c_str());
+    m_times_ids.resize(times.size());
+    times_ids_type::iterator j = m_times_ids.begin();
+    container_type::const_iterator i = times.begin();
+    container_type::const_iterator e = times.end();
+    for (; i != e; ++i, ++j)
+        *j = xr_strdup((*i)->id().c_str());
 
-	return							(&*m_times_ids.begin());
+    return (&*m_times_ids.begin());
 }
 
-u32 manager::frames_size_getter			(LPCSTR weather_id) const
+u32 manager::frames_size_getter(LPCSTR weather_id) const
 {
-	weather_container_type::const_iterator	found =
-		std::find_if(
-			m_weathers.begin(),
-			m_weathers.end(),
-			predicate(weather_id)
-		);
+    weather_container_type::const_iterator found =
+        std::find_if(
+            m_weathers.begin(),
+            m_weathers.end(),
+            predicate(weather_id)
+        );
 
-	if (found == m_weathers.end())
-		return						(0);
+    if (found == m_weathers.end())
+        return (0);
 
 #pragma todo("Dima to Dima: dangerous scheme: it depends on the call sequence (frames_getter should be called berfore frames_size_getter to get correct results)")
-	return							(m_times_ids.size());
+    return (m_times_ids.size());
 }
 
-void manager::fill					(property_holder_type* holder)
+void manager::fill(property_holder_type* holder)
 {
-	VERIFY							(holder);
-	holder->add_property			(
-		"weathers",
-		"weathers",
-		"this option is resposible for weathers",
-		m_collection
-	);
-
-	typedef ::editor::ide::weathers_getter_type			weathers_getter_type;
-	weathers_getter_type			weathers_getter;
-	weathers_getter.bind			(this, &manager::weathers_getter);
-
-	typedef ::editor::ide::weathers_size_getter_type	weathers_size_getter_type;
-	weathers_size_getter_type		weathers_size_getter;
-	weathers_size_getter.bind		(this, &manager::weathers_size_getter);
-
-	typedef ::editor::ide::frames_getter_type			frames_getter_type;
-	frames_getter_type				frames_getter;
-	frames_getter.bind				(this, &manager::frames_getter);
-
-	typedef ::editor::ide::frames_size_getter_type		frames_size_getter_type;
-	frames_size_getter_type			frames_size_getter;
-	frames_size_getter.bind			(this, &manager::frames_size_getter);
-
-	::ide().weather_editor_setup	(
-		weathers_getter,
-		weathers_size_getter,
-		frames_getter,
-		frames_size_getter
-	);
+    VERIFY(holder);
+    holder->add_property(
+        "weathers",
+        "weathers",
+        "this option is resposible for weathers",
+        m_collection
+    );
+
+    typedef ::editor::ide::weathers_getter_type weathers_getter_type;
+    weathers_getter_type weathers_getter;
+    weathers_getter.bind(this, &manager::weathers_getter);
+
+    typedef ::editor::ide::weathers_size_getter_type weathers_size_getter_type;
+    weathers_size_getter_type weathers_size_getter;
+    weathers_size_getter.bind(this, &manager::weathers_size_getter);
+
+    typedef ::editor::ide::frames_getter_type frames_getter_type;
+    frames_getter_type frames_getter;
+    frames_getter.bind(this, &manager::frames_getter);
+
+    typedef ::editor::ide::frames_size_getter_type frames_size_getter_type;
+    frames_size_getter_type frames_size_getter;
+    frames_size_getter.bind(this, &manager::frames_size_getter);
+
+    ::ide().weather_editor_setup(
+        weathers_getter,
+        weathers_size_getter,
+        frames_getter,
+        frames_size_getter
+    );
 }
 
-manager::weather_ids_type const& manager::weather_ids	() const
+manager::weather_ids_type const& manager::weather_ids() const
 {
-	if (!m_changed)
-		return						(m_weather_ids);
+    if (!m_changed)
+        return (m_weather_ids);
 
-	m_changed						= false;
+    m_changed = false;
 
-	delete_data						(m_weather_ids);
+    delete_data(m_weather_ids);
 
-	m_weather_ids.resize			(m_weathers.size());
+    m_weather_ids.resize(m_weathers.size());
 
-	weather_container_type::const_iterator	i = m_weathers.begin();
-	weather_container_type::const_iterator	e = m_weathers.end();
-	weather_ids_type::iterator		j = m_weather_ids.begin();
-	for ( ; i != e; ++i, ++j)
-		*j							= xr_strdup((*i)->id().c_str());
+    weather_container_type::const_iterator i = m_weathers.begin();
+    weather_container_type::const_iterator e = m_weathers.end();
+    weather_ids_type::iterator j = m_weather_ids.begin();
+    for (; i != e; ++i, ++j)
+        *j = xr_strdup((*i)->id().c_str());
 
-	std::sort						(m_weather_ids.begin(), m_weather_ids.end(), logical_string_predicate());
+    std::sort(m_weather_ids.begin(), m_weather_ids.end(), logical_string_predicate());
 
-	return							(m_weather_ids);
+    return (m_weather_ids);
 }
 
-shared_str manager::unique_id			(shared_str const& id) const
+shared_str manager::unique_id(shared_str const& id) const
 {
-	if (m_collection->unique_id(id.c_str()))
-		return						(id);
+    if (m_collection->unique_id(id.c_str()))
+        return (id);
 
-	return							(m_collection->generate_unique_id(id.c_str()));
+    return (m_collection->generate_unique_id(id.c_str()));
 }
 
-bool manager::save_current_blend		(char* buffer, u32 const& buffer_size)
+bool manager::save_current_blend(char* buffer, u32 const& buffer_size)
 {
-	CInifile		temp(0, FALSE, FALSE, FALSE);
+    CInifile temp(0, FALSE, FALSE, FALSE);
 
-	using editor::environment::weathers::time;
-	time*			frame = static_cast(m_manager.CurrentEnv);
-	frame->save		(temp);
+    using editor::environment::weathers::time;
+    time* frame = static_cast(m_manager.CurrentEnv);
+    frame->save(temp);
 
-	CMemoryWriter	writer;
-	temp.save_as	(writer);
-	if (writer.size() > buffer_size)
-		return		(false);
+    CMemoryWriter writer;
+    temp.save_as(writer);
+    if (writer.size() > buffer_size)
+        return (false);
 
-	writer.w_u8		(0);
-	writer.seek		(0);
-	Memory.mem_copy	(buffer, writer.pointer(), writer.size());
-	return			(true);
+    writer.w_u8(0);
+    writer.seek(0);
+    Memory.mem_copy(buffer, writer.pointer(), writer.size());
+    return (true);
 }
 
-bool manager::paste_current_time_frame	(char const* buffer, u32 const& buffer_size)
+bool manager::paste_current_time_frame(char const* buffer, u32 const& buffer_size)
 {
-	if (!m_manager.Current[0])
-		return							(false);
+    if (!m_manager.Current[0])
+        return (false);
 
-	weather_container_type::iterator	i = m_weathers.begin();
-	weather_container_type::iterator	e = m_weathers.end();
-	for ( ; i != e; ++i) {
-		if (m_manager.CurrentWeatherName._get() != (*i)->id()._get())
-			continue;
+    weather_container_type::iterator i = m_weathers.begin();
+    weather_container_type::iterator e = m_weathers.end();
+    for (; i != e; ++i)
+    {
+        if (m_manager.CurrentWeatherName._get() != (*i)->id()._get())
+            continue;
 
-		return						((*i)->paste_time_frame(m_manager.Current[0]->m_identifier, buffer, buffer_size));
-	}
+        return ((*i)->paste_time_frame(m_manager.Current[0]->m_identifier, buffer, buffer_size));
+    }
 
-	return							(false);
+    return (false);
 }
 
-bool manager::paste_target_time_frame	(char const* buffer, u32 const& buffer_size)
+bool manager::paste_target_time_frame(char const* buffer, u32 const& buffer_size)
 {
-	if (!m_manager.Current[1])
-		return							(false);
+    if (!m_manager.Current[1])
+        return (false);
 
-	weather_container_type::iterator	i = m_weathers.begin();
-	weather_container_type::iterator	e = m_weathers.end();
-	for ( ; i != e; ++i) {
-		if (m_manager.CurrentWeatherName._get() != (*i)->id()._get())
-			continue;
+    weather_container_type::iterator i = m_weathers.begin();
+    weather_container_type::iterator e = m_weathers.end();
+    for (; i != e; ++i)
+    {
+        if (m_manager.CurrentWeatherName._get() != (*i)->id()._get())
+            continue;
 
-		return						((*i)->paste_time_frame(m_manager.Current[1]->m_identifier, buffer, buffer_size));
-	}
+        return ((*i)->paste_time_frame(m_manager.Current[1]->m_identifier, buffer, buffer_size));
+    }
 
-	return							(false);
+    return (false);
 }
 
-bool manager::add_time_frame			(char const* buffer, u32 const& buffer_size)
+bool manager::add_time_frame(char const* buffer, u32 const& buffer_size)
 {
-	weather_container_type::iterator	i = m_weathers.begin();
-	weather_container_type::iterator	e = m_weathers.end();
-	for ( ; i != e; ++i) {
-		if (m_manager.CurrentWeatherName._get() != (*i)->id()._get())
-			continue;
+    weather_container_type::iterator i = m_weathers.begin();
+    weather_container_type::iterator e = m_weathers.end();
+    for (; i != e; ++i)
+    {
+        if (m_manager.CurrentWeatherName._get() != (*i)->id()._get())
+            continue;
 
-		return							((*i)->add_time_frame(buffer, buffer_size));
-	}
+        return ((*i)->add_time_frame(buffer, buffer_size));
+    }
 
-	return								(false);
+    return (false);
 }
 
-void manager::reload_current_time_frame	()
+void manager::reload_current_time_frame()
 {
-	if (!m_manager.Current[0])
-		return;
-
-	weather_container_type::iterator	i = m_weathers.begin();
-	weather_container_type::iterator	e = m_weathers.end();
-	for ( ; i != e; ++i) {
-		if (m_manager.CurrentWeatherName._get() != (*i)->id()._get())
-			continue;
-
-		(*i)->reload_time_frame			(m_manager.Current[0]->m_identifier);
-		return;
-	}
+    if (!m_manager.Current[0])
+        return;
+
+    weather_container_type::iterator i = m_weathers.begin();
+    weather_container_type::iterator e = m_weathers.end();
+    for (; i != e; ++i)
+    {
+        if (m_manager.CurrentWeatherName._get() != (*i)->id()._get())
+            continue;
+
+        (*i)->reload_time_frame(m_manager.Current[0]->m_identifier);
+        return;
+    }
 }
 
-void manager::reload_target_time_frame	()
+void manager::reload_target_time_frame()
 {
-	if (!m_manager.Current[1])
-		return;
-
-	weather_container_type::iterator	i = m_weathers.begin();
-	weather_container_type::iterator	e = m_weathers.end();
-	for ( ; i != e; ++i) {
-		if (m_manager.CurrentWeatherName._get() != (*i)->id()._get())
-			continue;
-
-		(*i)->reload_time_frame			(m_manager.Current[1]->m_identifier);
-		return;
-	}
+    if (!m_manager.Current[1])
+        return;
+
+    weather_container_type::iterator i = m_weathers.begin();
+    weather_container_type::iterator e = m_weathers.end();
+    for (; i != e; ++i)
+    {
+        if (m_manager.CurrentWeatherName._get() != (*i)->id()._get())
+            continue;
+
+        (*i)->reload_time_frame(m_manager.Current[1]->m_identifier);
+        return;
+    }
 }
 
-void manager::reload_current_weather	()
+void manager::reload_current_weather()
 {
-	weather_container_type::iterator	i = m_weathers.begin();
-	weather_container_type::iterator	e = m_weathers.end();
-	for ( ; i != e; ++i) {
-		if (m_manager.CurrentWeatherName._get() != (*i)->id()._get())
-			continue;
-
-		(*i)->reload					();
-		return;
-	}
+    weather_container_type::iterator i = m_weathers.begin();
+    weather_container_type::iterator e = m_weathers.end();
+    for (; i != e; ++i)
+    {
+        if (m_manager.CurrentWeatherName._get() != (*i)->id()._get())
+            continue;
+
+        (*i)->reload();
+        return;
+    }
 }
 
-void manager::reload					()
+void manager::reload()
 {
-	delete_data							(m_weathers);
-	load								();
+    delete_data(m_weathers);
+    load();
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_weathers_manager.hpp b/src/xrEngine/editor_environment_weathers_manager.hpp
index 13f4be1e258..66ac374960e 100644
--- a/src/xrEngine/editor_environment_weathers_manager.hpp
+++ b/src/xrEngine/editor_environment_weathers_manager.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_weathers_manager.hpp
-//	Created 	: 04.01.2008
-//  Modified 	: 11.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment weathers manager class
+// Module : editor_environment_weathers_manager.hpp
+// Created : 04.01.2008
+// Modified : 11.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment weathers manager class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_ENVIRONMENT_WEATHERS_MANAGER_HPP_INCLUDED
@@ -14,65 +14,69 @@
 #include 
 #include "property_collection_forward.hpp"
 
-namespace editor {
+namespace editor
+{
 
 class property_holder;
 
-namespace environment {
+namespace environment
+{
 
-	class manager;
+class manager;
 
-namespace weathers {
+namespace weathers
+{
 
 class weather;
 
-class manager : private boost::noncopyable {
+class manager : private boost::noncopyable
+{
 public:
-							manager				(environment::manager* manager);
-							~manager			();
-			void			load				();
-			void			save				();
-			void			fill				(::editor::property_holder* property_holder);
-			shared_str		unique_id			(shared_str const& id) const;
-			bool	save_current_blend			(char* buffer, u32 const& buffer_size);
-			bool	paste_current_time_frame	(char const* buffer, u32 const& buffer_size);
-			bool	paste_target_time_frame		(char const* buffer, u32 const& buffer_size);
-			void	reload_current_time_frame	();
-			void	reload_target_time_frame	();
-			void	reload_current_weather		();
-			void	reload						();
-			bool	add_time_frame				(char const* buffer, u32 const& buffer_size);
+    manager(environment::manager* manager);
+    ~manager();
+    void load();
+    void save();
+    void fill(::editor::property_holder* property_holder);
+    shared_str unique_id(shared_str const& id) const;
+    bool save_current_blend(char* buffer, u32 const& buffer_size);
+    bool paste_current_time_frame(char const* buffer, u32 const& buffer_size);
+    bool paste_target_time_frame(char const* buffer, u32 const& buffer_size);
+    void reload_current_time_frame();
+    void reload_target_time_frame();
+    void reload_current_weather();
+    void reload();
+    bool add_time_frame(char const* buffer, u32 const& buffer_size);
 
 public:
-	typedef xr_vector					weather_ids_type;
-	typedef xr_vector					times_ids_type;
-	typedef xr_vector					weather_container_type;
+    typedef xr_vector weather_ids_type;
+    typedef xr_vector times_ids_type;
+    typedef xr_vector weather_container_type;
 
 public:
-	weather_ids_type const& weather_ids			() const;
+    weather_ids_type const& weather_ids() const;
 
 private:
-	typedef editor::property_holder				property_holder_type;
-	typedef property_collection<
-				weather_container_type,
-				manager
-			>									collection_type;
+    typedef editor::property_holder property_holder_type;
+    typedef property_collection <
+    weather_container_type,
+    manager
+    > collection_type;
 
 private:
-	LPCSTR const* xr_stdcall weathers_getter	() const;
-	u32 xr_stdcall weathers_size_getter			() const;
-	LPCSTR const* xr_stdcall frames_getter		(LPCSTR weather_id) const;
-	u32 xr_stdcall frames_size_getter			(LPCSTR weather_id) const;
+    LPCSTR const* xr_stdcall weathers_getter() const;
+    u32 xr_stdcall weathers_size_getter() const;
+    LPCSTR const* xr_stdcall frames_getter(LPCSTR weather_id) const;
+    u32 xr_stdcall frames_size_getter(LPCSTR weather_id) const;
 
 private:
-	weather_container_type						m_weathers;
-	mutable weather_ids_type					m_weather_ids;
-	collection_type*							m_collection;
-	mutable times_ids_type						m_times_ids;
+    weather_container_type m_weathers;
+    mutable weather_ids_type m_weather_ids;
+    collection_type* m_collection;
+    mutable times_ids_type m_times_ids;
 
 public:
-	environment::manager&						m_manager;
-	mutable bool								m_changed;
+    environment::manager& m_manager;
+    mutable bool m_changed;
 }; // class manager
 } // namespace weathers
 } // namespace environment
diff --git a/src/xrEngine/editor_environment_weathers_time.cpp b/src/xrEngine/editor_environment_weathers_time.cpp
index 1049e3ce4c6..8108d3aab69 100644
--- a/src/xrEngine/editor_environment_weathers_time.cpp
+++ b/src/xrEngine/editor_environment_weathers_time.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_weathers_time.cpp
-//	Created 	: 12.01.2008
-//  Modified 	: 12.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment weathers time class
+// Module : editor_environment_weathers_time.cpp
+// Created : 12.01.2008
+// Modified : 12.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment weathers time class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -25,655 +25,656 @@ using editor::environment::weathers::weather;
 
 static inline editor::color create_color(float const& r, float const& g, float const& b)
 {
-	editor::color			result;
-	result.r				= r;
-	result.g				= g;
-	result.b				= b;
-	return					(result);
-}
-
-time::time					(
-		editor::environment::manager* manager,
-		weather const* weather,
-		shared_str const& id
-	) :
-	CEnvDescriptorMixer		(id),
-	m_manager				(*manager),
-	m_weather				(weather),
-	m_property_holder		(0),
-	m_ambient				(""),
-	m_sun					(""),
-	m_thunderbolt_collection("")
-{
-}
-
-time::~time					()
-{
-	if (!Device.editor())
-		return;
-
-	::ide().destroy		(m_property_holder);
-}
-
-void time::load_from		(shared_str const& id, CInifile& config, shared_str const& new_id)
-{
-	m_identifier		= id;
-	load				(config);
-	m_identifier		= new_id;
+    editor::color result;
+    result.r = r;
+    result.g = g;
+    result.b = b;
+    return (result);
+}
+
+time::time(
+    editor::environment::manager* manager,
+    weather const* weather,
+    shared_str const& id
+) :
+    CEnvDescriptorMixer(id),
+    m_manager(*manager),
+    m_weather(weather),
+    m_property_holder(0),
+    m_ambient(""),
+    m_sun(""),
+    m_thunderbolt_collection("")
+{
+}
+
+time::~time()
+{
+    if (!Device.editor())
+        return;
+
+    ::ide().destroy(m_property_holder);
+}
+
+void time::load_from(shared_str const& id, CInifile& config, shared_str const& new_id)
+{
+    m_identifier = id;
+    load(config);
+    m_identifier = new_id;
 }
 
-void time::load				(CInifile& config)
+void time::load(CInifile& config)
 {
-//	Ivector3 tm					={0,0,0};
-//	sscanf						(m_identifier.c_str(),"%d:%d:%d",&tm.x,&tm.y,&tm.z);
-//	R_ASSERT3					((tm.x>=0)&&(tm.x<24)&&(tm.y>=0)&&(tm.y<60)&&(tm.z>=0)&&(tm.z<60),"Incorrect weather time",m_identifier.c_str());
-//	exec_time					= tm.x*3600.f+tm.y*60.f+tm.z;
-//	exec_time_loaded			= exec_time;
+    // Ivector3 tm ={0,0,0};
+    // sscanf (m_identifier.c_str(),"%d:%d:%d",&tm.x,&tm.y,&tm.z);
+    // R_ASSERT3 ((tm.x>=0)&&(tm.x<24)&&(tm.y>=0)&&(tm.y<60)&&(tm.z>=0)&&(tm.z<60),"Incorrect weather time",m_identifier.c_str());
+    // exec_time = tm.x*3600.f+tm.y*60.f+tm.z;
+    // exec_time_loaded = exec_time;
+
+    m_ambient = config.r_string(m_identifier, "ambient");
+    // ambient = config.r_fvector3(m_identifier, "ambient_color");
+    // clouds_texture_name = config.r_string(m_identifier, "clouds_texture");
+    // far_plane = config.r_float(m_identifier, "far_plane");
+    // fog_distance = config.r_float(m_identifier, "fog_distance");
+    // fog_density = config.r_float(m_identifier, "fog_density");
+    // fog_color = config.r_fvector3(m_identifier, "fog_color");
+    // rain_color = config.r_fvector3(m_identifier, "rain_color");
+    // rain_density = config.r_float(m_identifier, "rain_density");
+    // sky_color = config.r_fvector3(m_identifier, "sky_color");
+    // sky_rotation = config.r_float(m_identifier, "sky_rotation");
 
-	m_ambient					= config.r_string(m_identifier, "ambient");
-//	ambient						= config.r_fvector3(m_identifier, "ambient_color");
-//	clouds_texture_name			= config.r_string(m_identifier, "clouds_texture");
-//	far_plane					= config.r_float(m_identifier, 	"far_plane");
-//	fog_distance				= config.r_float(m_identifier, 	"fog_distance");
-//	fog_density					= config.r_float(m_identifier, 	"fog_density");
-//	fog_color					= config.r_fvector3(m_identifier, "fog_color");
-//	rain_color					= config.r_fvector3(m_identifier, "rain_color");
-//	rain_density				= config.r_float(m_identifier,	"rain_density");
-//	sky_color					= config.r_fvector3(m_identifier, "sky_color");
-//	sky_rotation				= config.r_float(m_identifier,	"sky_rotation");
-	
-//	sky_texture_name			= config.r_string(m_identifier, "sky_texture");
-//	string_path					st_env;
-//	strconcat					(sizeof(st_env), st_env, sky_texture_name.c_str(), "#small");
-//	sky_texture_env_name		= st_env;
+    // sky_texture_name = config.r_string(m_identifier, "sky_texture");
+    // string_path st_env;
+    // strconcat (sizeof(st_env), st_env, sky_texture_name.c_str(), "#small");
+    // sky_texture_env_name = st_env;
 
-//	sun_color					= config.r_fvector3(m_identifier, "sun_color");
-//	m_fSunShaftsIntensity		= config.r_float(m_identifier,	"sun_shafts_intensity");
-	m_sun						= config.r_string(m_identifier, "sun");
-	m_thunderbolt_collection	= config.r_string(m_identifier, "thunderbolt_collection");
-//	bolt_duration				= config.r_float(m_identifier, 	"bolt_duration");
-//	bolt_period					= config.r_float(m_identifier, 	"bolt_period");
-//	m_fWaterIntensity			= config.r_float(m_identifier, 	"water_intensity");
-//	wind_direction				= config.r_float(m_identifier, 	"wind_direction");
-//	wind_velocity				= config.r_float(m_identifier, 	"wind_velocity");
+    // sun_color = config.r_fvector3(m_identifier, "sun_color");
+    // m_fSunShaftsIntensity = config.r_float(m_identifier, "sun_shafts_intensity");
+    m_sun = config.r_string(m_identifier, "sun");
+    m_thunderbolt_collection = config.r_string(m_identifier, "thunderbolt_collection");
+    // bolt_duration = config.r_float(m_identifier, "bolt_duration");
+    // bolt_period = config.r_float(m_identifier, "bolt_period");
+    // m_fWaterIntensity = config.r_float(m_identifier, "water_intensity");
+    // wind_direction = config.r_float(m_identifier, "wind_direction");
+    // wind_velocity = config.r_float(m_identifier, "wind_velocity");
 
-//	hemi_color					= config.r_fvector4(m_identifier, "hemi_color");
+    // hemi_color = config.r_fvector4(m_identifier, "hemi_color");
 
-//	Fvector2					coords = config.r_fvector2(m_identifier, "sun_dir");
-//	sun_dir.setHP				(deg2rad(coords.y), deg2rad(coords.x));
+    // Fvector2 coords = config.r_fvector2(m_identifier, "sun_dir");
+    // sun_dir.setHP (deg2rad(coords.y), deg2rad(coords.x));
 
-//	clouds_color				= config.r_fvector4(m_identifier, "clouds_color");
+    // clouds_color = config.r_fvector4(m_identifier, "clouds_color");
 
-//	LPCSTR						clouds = config.r_string(m_identifier, "clouds_color");
-//	VERIFY						(_GetItemCount(clouds) == 5);
-//	string256					temp;
-//	((Fvector&)clouds_color).mul(.5f*(float)atof(_GetItem(clouds,4,temp)));
+    // LPCSTR clouds = config.r_string(m_identifier, "clouds_color");
+    // VERIFY (_GetItemCount(clouds) == 5);
+    // string256 temp;
+    // ((Fvector&)clouds_color).mul(.5f*(float)atof(_GetItem(clouds,4,temp)));
 
-//	on_device_create			();
-	inherited::load				(m_manager, config);
+    // on_device_create ();
+    inherited::load(m_manager, config);
 }
 
-void time::save				(CInifile& config)
+void time::save(CInifile& config)
 {
-	config.w_string				(m_identifier.c_str(),"ambient", m_ambient.c_str());
-	config.w_fvector3			(m_identifier.c_str(),"ambient_color", ambient);
-	config.w_string				(m_identifier.c_str(),"clouds_texture", clouds_texture_name.c_str());
-	config.w_float				(m_identifier.c_str(),"far_plane", far_plane);
-	config.w_float				(m_identifier.c_str(),"fog_distance", fog_distance);
-	config.w_float				(m_identifier.c_str(),"fog_density", fog_density);
-	config.w_fvector3			(m_identifier.c_str(),"fog_color", fog_color);
-	config.w_fvector3			(m_identifier.c_str(),"rain_color", rain_color);
-	config.w_float				(m_identifier.c_str(),"rain_density", rain_density);
-	config.w_fvector3			(m_identifier.c_str(),"sky_color", sky_color);
-	config.w_float				(m_identifier.c_str(),"sky_rotation", rad2deg(sky_rotation));
-	config.w_string				(m_identifier.c_str(),"sky_texture", sky_texture_name.c_str());
-	config.w_fvector3			(m_identifier.c_str(),"sun_color", sun_color);
-	config.w_float				(m_identifier.c_str(),"sun_shafts_intensity", m_fSunShaftsIntensity);
-	config.w_string				(m_identifier.c_str(),"sun", m_sun.c_str());
-	config.w_string				(m_identifier.c_str(),"thunderbolt_collection", m_thunderbolt_collection.c_str());
-	config.w_float				(m_identifier.c_str(),"thunderbolt_duration", bolt_duration);
-	config.w_float				(m_identifier.c_str(),"thunderbolt_period", bolt_period);
-	config.w_float				(m_identifier.c_str(),"water_intensity", m_fWaterIntensity);
-	config.w_float				(m_identifier.c_str(),"wind_direction", rad2deg(wind_direction));
-	config.w_float				(m_identifier.c_str(),"wind_velocity", wind_velocity);
-	config.w_fvector4			(m_identifier.c_str(),"hemisphere_color", hemi_color);
-	config.w_float				(m_identifier.c_str(),"sun_altitude", rad2deg(sun_dir.getH()));
-	config.w_float				(m_identifier.c_str(),"sun_longitude", rad2deg(sun_dir.getP()));
-	config.w_fvector4			(m_identifier.c_str(),"clouds_color", clouds_color);
+    config.w_string(m_identifier.c_str(), "ambient", m_ambient.c_str());
+    config.w_fvector3(m_identifier.c_str(), "ambient_color", ambient);
+    config.w_string(m_identifier.c_str(), "clouds_texture", clouds_texture_name.c_str());
+    config.w_float(m_identifier.c_str(), "far_plane", far_plane);
+    config.w_float(m_identifier.c_str(), "fog_distance", fog_distance);
+    config.w_float(m_identifier.c_str(), "fog_density", fog_density);
+    config.w_fvector3(m_identifier.c_str(), "fog_color", fog_color);
+    config.w_fvector3(m_identifier.c_str(), "rain_color", rain_color);
+    config.w_float(m_identifier.c_str(), "rain_density", rain_density);
+    config.w_fvector3(m_identifier.c_str(), "sky_color", sky_color);
+    config.w_float(m_identifier.c_str(), "sky_rotation", rad2deg(sky_rotation));
+    config.w_string(m_identifier.c_str(), "sky_texture", sky_texture_name.c_str());
+    config.w_fvector3(m_identifier.c_str(), "sun_color", sun_color);
+    config.w_float(m_identifier.c_str(), "sun_shafts_intensity", m_fSunShaftsIntensity);
+    config.w_string(m_identifier.c_str(), "sun", m_sun.c_str());
+    config.w_string(m_identifier.c_str(), "thunderbolt_collection", m_thunderbolt_collection.c_str());
+    config.w_float(m_identifier.c_str(), "thunderbolt_duration", bolt_duration);
+    config.w_float(m_identifier.c_str(), "thunderbolt_period", bolt_period);
+    config.w_float(m_identifier.c_str(), "water_intensity", m_fWaterIntensity);
+    config.w_float(m_identifier.c_str(), "wind_direction", rad2deg(wind_direction));
+    config.w_float(m_identifier.c_str(), "wind_velocity", wind_velocity);
+    config.w_fvector4(m_identifier.c_str(), "hemisphere_color", hemi_color);
+    config.w_float(m_identifier.c_str(), "sun_altitude", rad2deg(sun_dir.getH()));
+    config.w_float(m_identifier.c_str(), "sun_longitude", rad2deg(sun_dir.getP()));
+    config.w_fvector4(m_identifier.c_str(), "clouds_color", clouds_color);
 }
 
-LPCSTR time::id_getter		() const
+LPCSTR time::id_getter() const
 {
-	return						(m_identifier.c_str());
+    return (m_identifier.c_str());
 }
 
-void time::id_setter		(LPCSTR value_)
+void time::id_setter(LPCSTR value_)
 {
-	shared_str					value = value_;
-	if (m_identifier._get() == value._get())
-		return;
+    shared_str value = value_;
+    if (m_identifier._get() == value._get())
+        return;
 
-	if (m_weather)
-		m_identifier			= m_weather->unique_id(m_identifier, value);
-	else
-		m_identifier			= value;
+    if (m_weather)
+        m_identifier = m_weather->unique_id(m_identifier, value);
+    else
+        m_identifier = value;
 }
 
-LPCSTR const* time::ambients_collection		()
+LPCSTR const* time::ambients_collection()
 {
-	return				(&*m_manager.ambients().ambients_ids().begin());
+    return (&*m_manager.ambients().ambients_ids().begin());
 }
 
-u32 time::ambients_collection_size			()
+u32 time::ambients_collection_size()
 {
-	return				(m_manager.ambients().ambients_ids().size());
+    return (m_manager.ambients().ambients_ids().size());
 }
 
-LPCSTR const* time::suns_collection			()
+LPCSTR const* time::suns_collection()
 {
-	return				(&*m_manager.suns().suns_ids().begin());
+    return (&*m_manager.suns().suns_ids().begin());
 }
 
-u32 time::suns_collection_size				()
+u32 time::suns_collection_size()
 {
-	return				(m_manager.suns().suns_ids().size());
+    return (m_manager.suns().suns_ids().size());
 }
 
-LPCSTR const* time::thunderbolts_collection	()
+LPCSTR const* time::thunderbolts_collection()
 {
-	return				(&*m_manager.thunderbolts().collections_ids().begin());
+    return (&*m_manager.thunderbolts().collections_ids().begin());
 }
 
-u32 time::thunderbolts_collection_size		()
+u32 time::thunderbolts_collection_size()
 {
-	return				(m_manager.thunderbolts().collections_ids().size());
+    return (m_manager.thunderbolts().collections_ids().size());
 }
 
-float time::sun_altitude_getter				() const
+float time::sun_altitude_getter() const
 {
-	float				y, x;
-	sun_dir.getHP		(y, x);
-	return				(rad2deg(y));
+    float y, x;
+    sun_dir.getHP(y, x);
+    return (rad2deg(y));
 }
 
-void time::sun_altitude_setter				(float value)
+void time::sun_altitude_setter(float value)
 {
-	float				y, x;
-	sun_dir.getHP		(y, x);
-	sun_dir.setHP		(deg2rad(value), x);
+    float y, x;
+    sun_dir.getHP(y, x);
+    sun_dir.setHP(deg2rad(value), x);
 }
 
-float time::sun_longitude_getter			() const
+float time::sun_longitude_getter() const
 {
-	float				y, x;
-	sun_dir.getHP		(y, x);
-	return				(rad2deg(x));
+    float y, x;
+    sun_dir.getHP(y, x);
+    return (rad2deg(x));
 }
 
-void time::sun_longitude_setter				(float value)
+void time::sun_longitude_setter(float value)
 {
-	float				y, x;
-	sun_dir.getHP		(y, x);
-	sun_dir.setHP		(y, deg2rad(value));
+    float y, x;
+    sun_dir.getHP(y, x);
+    sun_dir.setHP(y, deg2rad(value));
 }
 
-LPCSTR time::ambient_getter					() const
+LPCSTR time::ambient_getter() const
 {
-	return				(m_ambient.c_str());
+    return (m_ambient.c_str());
 }
 
-void time::ambient_setter					(LPCSTR value)
+void time::ambient_setter(LPCSTR value)
 {
-	if (m_ambient._get() == shared_str(value)._get())
-		return;
+    if (m_ambient._get() == shared_str(value)._get())
+        return;
 
-	m_ambient			= value;
-	env_ambient			= m_manager.AppendEnvAmb(value);
+    m_ambient = value;
+    env_ambient = m_manager.AppendEnvAmb(value);
 }
 
-LPCSTR time::sun_getter					() const
+LPCSTR time::sun_getter() const
 {
-	return				(m_sun.c_str());
+    return (m_sun.c_str());
 }
 
-void time::sun_setter					(LPCSTR value)
+void time::sun_setter(LPCSTR value)
 {
-	if (m_sun._get() == shared_str(value)._get())
-		return;
+    if (m_sun._get() == shared_str(value)._get())
+        return;
 
-	m_sun			= value;
-	lens_flare_id		= m_manager.eff_LensFlare->AppendDef(m_manager, m_manager.m_suns_config, value);
+    m_sun = value;
+    lens_flare_id = m_manager.eff_LensFlare->AppendDef(m_manager, m_manager.m_suns_config, value);
 }
 
-LPCSTR time::thunderbolt_getter				() const
+LPCSTR time::thunderbolt_getter() const
 {
-	return				(m_thunderbolt_collection.c_str());
+    return (m_thunderbolt_collection.c_str());
 }
 
-void time::thunderbolt_setter				(LPCSTR value)
+void time::thunderbolt_setter(LPCSTR value)
 {
-	if (m_thunderbolt_collection._get() == shared_str(value)._get())
-		return;
+    if (m_thunderbolt_collection._get() == shared_str(value)._get())
+        return;
 
-	m_thunderbolt_collection	= value;
-	tb_id				= m_manager.eff_Thunderbolt->AppendDef(m_manager, m_manager.m_thunderbolt_collections_config, m_manager.m_thunderbolts_config, value);
+    m_thunderbolt_collection = value;
+    tb_id = m_manager.eff_Thunderbolt->AppendDef(m_manager, m_manager.m_thunderbolt_collections_config, m_manager.m_thunderbolts_config, value);
 }
 
-LPCSTR time::sky_texture_getter				() const
+LPCSTR time::sky_texture_getter() const
 {
-	return				(sky_texture_name.c_str());
+    return (sky_texture_name.c_str());
 }
 
-void time::sky_texture_setter				(LPCSTR value)
+void time::sky_texture_setter(LPCSTR value)
 {
-	if (sky_texture_name._get() == shared_str(value)._get())
-		return;
+    if (sky_texture_name._get() == shared_str(value)._get())
+        return;
 
-	sky_texture_name	= value;
+    sky_texture_name = value;
 
-	string_path			st_env;
-	strconcat			(sizeof(st_env), st_env, value, "#small");
-	sky_texture_env_name= st_env;
-	m_pDescriptor->OnDeviceCreate(*this);
+    string_path st_env;
+    strconcat(sizeof(st_env), st_env, value, "#small");
+    sky_texture_env_name = st_env;
+    m_pDescriptor->OnDeviceCreate(*this);
 }
 
-LPCSTR time::clouds_texture_getter			() const
+LPCSTR time::clouds_texture_getter() const
 {
-	return				(clouds_texture_name.c_str());
+    return (clouds_texture_name.c_str());
 }
 
-void time::clouds_texture_setter			(LPCSTR value)
+void time::clouds_texture_setter(LPCSTR value)
 {
-	if (clouds_texture_name._get() == shared_str(value)._get())
-		return;
+    if (clouds_texture_name._get() == shared_str(value)._get())
+        return;
 
-	clouds_texture_name	= value;
-	m_pDescriptor->OnDeviceCreate(*this);
+    clouds_texture_name = value;
+    m_pDescriptor->OnDeviceCreate(*this);
 }
 
-float time::sky_rotation_getter				() const
+float time::sky_rotation_getter() const
 {
-	return				(rad2deg(sky_rotation));
+    return (rad2deg(sky_rotation));
 }
 
-void time::sky_rotation_setter				(float value)
+void time::sky_rotation_setter(float value)
 {
-	sky_rotation		= deg2rad(value);
+    sky_rotation = deg2rad(value);
 }
 
-float time::wind_direction_getter			() const
+float time::wind_direction_getter() const
 {
-	return				(rad2deg(wind_direction));
+    return (rad2deg(wind_direction));
 }
 
-void time::wind_direction_setter			(float value)
+void time::wind_direction_setter(float value)
 {
-	wind_direction		= deg2rad(value);
+    wind_direction = deg2rad(value);
 }
 
-void time::fill				(editor::property_holder_collection* collection)
+void time::fill(editor::property_holder_collection* collection)
 {
-	VERIFY							(!m_property_holder);
-	m_property_holder				= ::ide().create_property_holder(m_identifier.c_str(), collection, this);
+    VERIFY(!m_property_holder);
+    m_property_holder = ::ide().create_property_holder(m_identifier.c_str(), collection, this);
+
+    typedef editor::property_holder::string_getter_type string_getter_type;
+    string_getter_type string_getter;
+    string_getter.bind(this, &time::id_getter);
 
-	typedef editor::property_holder::string_getter_type	string_getter_type;
-	string_getter_type				string_getter;
-	string_getter.bind				(this, &time::id_getter);
+    typedef editor::property_holder::string_setter_type string_setter_type;
+    string_setter_type string_setter;
+    string_setter.bind(this, &time::id_setter);
 
-	typedef editor::property_holder::string_setter_type	string_setter_type;
-	string_setter_type				string_setter;
-	string_setter.bind				(this, &time::id_setter);
+    m_property_holder->add_property(
+        "id",
+        "properties",
+        "this option is resposible for time interval",
+        m_identifier.c_str(),
+        string_getter,
+        string_setter
+    );
 
-	m_property_holder->add_property	(
-		"id",
-		"properties",
-		"this option is resposible for time interval",
-		m_identifier.c_str(),
-		string_getter,
-		string_setter
-	);
-	
-	m_property_holder->add_property	(
-		"color",
-		"sun",
-		"this option is resposible for sun color",
-		(editor::color const&)sun_color,
-		(editor::color&)sun_color
-	);
-	m_property_holder->add_property	(
-		"shafts intensity",
-		"sun",
-		"this option is resposible for sun shafts intensity",
-		m_fSunShaftsIntensity,
-		m_fSunShaftsIntensity,
-		0.f,
-		1.f
-	);
+    m_property_holder->add_property(
+        "color",
+        "sun",
+        "this option is resposible for sun color",
+        (editor::color const&)sun_color,
+        (editor::color&)sun_color
+    );
+    m_property_holder->add_property(
+        "shafts intensity",
+        "sun",
+        "this option is resposible for sun shafts intensity",
+        m_fSunShaftsIntensity,
+        m_fSunShaftsIntensity,
+        0.f,
+        1.f
+    );
 
-	typedef editor::property_holder::float_getter_type	float_getter_type;
-	float_getter_type				sun_altitude_getter;
-	sun_altitude_getter.bind		(this, &time::sun_altitude_getter);
+    typedef editor::property_holder::float_getter_type float_getter_type;
+    float_getter_type sun_altitude_getter;
+    sun_altitude_getter.bind(this, &time::sun_altitude_getter);
 
-	typedef editor::property_holder::float_setter_type	float_setter_type;
-	float_setter_type				sun_altitude_setter;
-	sun_altitude_setter.bind		(this, &time::sun_altitude_setter);
+    typedef editor::property_holder::float_setter_type float_setter_type;
+    float_setter_type sun_altitude_setter;
+    sun_altitude_setter.bind(this, &time::sun_altitude_setter);
 
-	m_property_holder->add_property	(
-		"altitude",
-		"sun",
-		"this option is resposible for sun altitude (in degrees)",
-		sun_altitude_getter(),
-		sun_altitude_getter,
-		sun_altitude_setter,
-		-360.f,
-		 360.f
-	);
-
-	float_getter_type				sun_longitude_getter;
-	sun_longitude_getter.bind		(this, &time::sun_longitude_getter);
-
-	float_setter_type				sun_longitude_setter;
-	sun_longitude_setter.bind		(this, &time::sun_longitude_setter);
-
-	m_property_holder->add_property	(
-		"longitude",
-		"sun",
-		"this option is resposible for sun longitude (in degrees)",
-		sun_longitude_getter(),
-		sun_longitude_getter,
-		sun_longitude_setter,
-		-360.f,
-		 360.f
-	);
-
-	typedef editor::property_holder::string_collection_getter_type	collection_getter_type;
-	collection_getter_type			collection_getter;
-
-	typedef editor::property_holder::string_collection_size_getter_type	collection_size_getter_type;
-	collection_size_getter_type		collection_size_getter;
-
-	collection_getter.bind			(this, &time::suns_collection);
-	collection_size_getter.bind		(this, &time::suns_collection_size);
-	m_property_holder->add_property	(
-		"sun",
-		"sun",
-		"this option is resposible for ambient",
-		m_sun.c_str(),
-		m_sun,
-		collection_getter,
-		collection_size_getter,
-		editor::property_holder::value_editor_combo_box,
-		editor::property_holder::cannot_enter_text
-	);
-
-	string_getter_type		sky_texture_getter;
-	sky_texture_getter.bind	(this, &time::sky_texture_getter);
-
-	string_setter_type		sky_texture_setter;
-	sky_texture_setter.bind	(this, &time::sky_texture_setter);
-
-	m_property_holder->add_property	(
-		"texture",
-		"hemisphere",
-		"this option is resposible for sky texture",
-		sky_texture_name.c_str(),
-		sky_texture_getter,
-		sky_texture_setter,
-		".dds",
-		"Texture files (*.dds)|*.dds",
-		detail::real_path("$game_textures$", "").c_str(),
-		"Select texture...",
-		editor::property_holder::cannot_enter_text,
-		editor::property_holder::remove_extension
-	);
-
-	m_property_holder->add_property	(
-		"sky color",
-		"hemisphere",
-		"this option is resposible for sky color",
-		(editor::color const&)sky_color,
-		(editor::color&)sky_color
-	);
-
-	m_property_holder->add_property	(
-		"hemi color",
-		"hemisphere",
-		"this option is resposible for hemisphere color",
-		(editor::color const&)hemi_color,
-		(editor::color&)hemi_color
-	);
-
-	typedef ::editor::property_holder::float_getter_type	float_getter_type;
-	float_getter_type				float_getter;
-
-	typedef ::editor::property_holder::float_setter_type	float_setter_type;
-	float_setter_type				float_setter;
-
-	float_getter.bind				(this, &time::sky_rotation_getter);
-	float_setter.bind				(this, &time::sky_rotation_setter);
-	m_property_holder->add_property	(
-		"sky rotation",
-		"hemisphere",
-		"this option is resposible for sky rotation",
-		sky_rotation,
-		float_getter,
-		float_setter,
-		-360.0f,
-		 360.f
-	);
-
-	string_getter.bind				(this, &time::clouds_texture_getter);
-	string_setter.bind				(this, &time::clouds_texture_setter);
-	m_property_holder->add_property	(
-		"texture",
-		"clouds",
-		"this option is resposible for clouds texture",
-		clouds_texture_name.c_str(),
-		string_getter,
-		string_setter,
-		".dds",
-		"Texture files (*.dds)|*.dds",
-		detail::real_path("$game_textures$", "").c_str(),
-		"Select texture...",
-		editor::property_holder::cannot_enter_text,
-		editor::property_holder::remove_extension
-	);
-
-	m_property_holder->add_property	(
-		"color",
-		"clouds",
-		"this option is resposible for clouds color",
-		(editor::color const&)clouds_color,
-		(editor::color&)clouds_color
-	);
-
-	m_property_holder->add_property	(
-		"transparency",
-		"clouds",
-		"this option is resposible for clouds transparency",
-		clouds_color.w,
-		clouds_color.w,
-		0.f,
-		1.f
-	);
-
-	m_property_holder->add_property	(
-		"color",
-		"ambient",
-		"this option is resposible for ambient color",
-		(editor::color const&)ambient,
-		(editor::color&)ambient
-	);
-
-	collection_getter.bind			(this, &time::ambients_collection);
-	collection_size_getter.bind		(this, &time::ambients_collection_size);
-
-	string_getter.bind				(this, &time::ambient_getter);
-	string_setter.bind				(this, &time::ambient_setter);
-	m_property_holder->add_property	(
-		"ambient",
-		"ambient",
-		"this option is resposible for ambient",
-		m_ambient.c_str(),
-		string_getter,
-		string_setter,
-		collection_getter,
-		collection_size_getter,
-		editor::property_holder::value_editor_combo_box,
-		editor::property_holder::cannot_enter_text
-	);
-
-	m_property_holder->add_property	(
-		"color",
-		"fog",
-		"this option is resposible for fog density (0..1)",
-		(editor::color const&)fog_color,
-		(editor::color&)fog_color
-	);
-	m_property_holder->add_property	(
-		"far plane",
-		"fog",
-		"this option is resposible for far plane",
-		far_plane,
-		far_plane
-	);
-	m_property_holder->add_property	(
-		"distance",
-		"fog",
-		"this option is resposible for fog distance (shoudl be less than far plane)",
-		fog_distance,
-		fog_distance
-	);
-	m_property_holder->add_property	(
-		"density",
-		"fog",
-		"this option is resposible for fog density (0..1)",
-		fog_density,
-		fog_density,
-		0.f,
-		1.f
-	);
-	m_property_holder->add_property	(
-		"water intensity",
-		"fog",
-		"this option is resposible for water intensity (0..1)",
-		m_fWaterIntensity,
-		m_fWaterIntensity,
-		0.f,
-		1.f
-	);
-
-	m_property_holder->add_property	(
-		"rain color",
-		"rain",
-		"this option is resposible for rain color",
-		(editor::color const&)rain_color,
-		(editor::color&)rain_color
-	);
-	m_property_holder->add_property	(
-		"rain density",
-		"rain",
-		"this option is resposible for rain density (0..1)",
-		rain_density,
-		rain_density,
-		0.f,
-		1.f
-	);
-
-	collection_getter.bind			(this, &time::thunderbolts_collection);
-	collection_size_getter.bind		(this, &time::thunderbolts_collection_size);
-	m_property_holder->add_property	(
-		"collection",
-		"thunderbolts",
-		"this option is resposible for ambient",
-		m_thunderbolt_collection.c_str(),
-		m_thunderbolt_collection,
-		collection_getter,
-		collection_size_getter,
-		editor::property_holder::value_editor_combo_box,
-		editor::property_holder::cannot_enter_text
-	);
-
-	m_property_holder->add_property	(
-		"duration",
-		"thunderbolts",
-		"this option is resposible for thunderbolt duration",
-		bolt_duration,
-		bolt_duration
-	);
-	m_property_holder->add_property	(
-		"period",
-		"thunderbolts",
-		"this option is resposible for thunderbolt period",
-		bolt_period,
-		bolt_period
-	);
-	
-	float_getter.bind				(this, &time::wind_direction_getter);
-	float_setter.bind				(this, &time::wind_direction_setter);
-	m_property_holder->add_property	(
-		"direction",
-		"wind",
-		"this option is resposible for wind direction (in degrees)",
-		wind_direction,
-		float_getter,
-		float_setter,
-		-360.f,
-		 360.f
-	);
-	m_property_holder->add_property	(
-		"velocity",
-		"wind",
-		"this option is resposible for wind velocity (meters per second)",
-		wind_velocity,
-		wind_velocity,
-		0.f,
-		1000.f
-	);
-}
-
-void time::lerp	(CEnvironment* parent, CEnvDescriptor& A, CEnvDescriptor& B, float f, CEnvModifier& M, float m_power)
-{
-	float					start_time = m_manager.Current[0]->exec_time;
-	float					stop_time = m_manager.Current[1]->exec_time;
-	float					current_time = m_manager.GetGameTime();
-	if (start_time >= stop_time) {
-		if (current_time >= start_time)
-			clamp			(current_time, start_time, 24.f*60.f*60.f);
-		else
-			clamp			(current_time, 0.f, stop_time);
-
-		if (current_time <= stop_time)
-			current_time	+= 24.f*60.f*60.f;
-
-		stop_time			+= 24.f*60.f*60.f;
-	}
-	else
-		clamp				(current_time, start_time, stop_time);
-
-	VERIFY					(start_time < stop_time);
-	
-	u32						current_time_u32 = iFloor(current_time);
-	current_time_u32		= current_time_u32%(24*60*60);
-
-	u32						hours = current_time_u32/(60*60);
-	current_time_u32		%= (60*60);
-
-	u32						minutes = current_time_u32/60;
-	u32						seconds = current_time_u32%60;
-
-	string16				temp;
-	xr_sprintf				(temp, "%02d:%02d:%02d", hours, minutes, seconds);
-	m_identifier			= temp;
-
-	time&					a = static_cast(A);
-	m_ambient				= a.m_ambient;
-	clouds_texture_name		= a.clouds_texture_name;
-	sky_texture_name		= a.sky_texture_name;
-	m_sun					= a.m_sun;
-	m_thunderbolt_collection= a.m_thunderbolt_collection;
-
-	inherited::lerp			(parent, A, B, f, M, m_power);
+    m_property_holder->add_property(
+        "altitude",
+        "sun",
+        "this option is resposible for sun altitude (in degrees)",
+        sun_altitude_getter(),
+        sun_altitude_getter,
+        sun_altitude_setter,
+        -360.f,
+        360.f
+    );
+
+    float_getter_type sun_longitude_getter;
+    sun_longitude_getter.bind(this, &time::sun_longitude_getter);
+
+    float_setter_type sun_longitude_setter;
+    sun_longitude_setter.bind(this, &time::sun_longitude_setter);
+
+    m_property_holder->add_property(
+        "longitude",
+        "sun",
+        "this option is resposible for sun longitude (in degrees)",
+        sun_longitude_getter(),
+        sun_longitude_getter,
+        sun_longitude_setter,
+        -360.f,
+        360.f
+    );
+
+    typedef editor::property_holder::string_collection_getter_type collection_getter_type;
+    collection_getter_type collection_getter;
+
+    typedef editor::property_holder::string_collection_size_getter_type collection_size_getter_type;
+    collection_size_getter_type collection_size_getter;
+
+    collection_getter.bind(this, &time::suns_collection);
+    collection_size_getter.bind(this, &time::suns_collection_size);
+    m_property_holder->add_property(
+        "sun",
+        "sun",
+        "this option is resposible for ambient",
+        m_sun.c_str(),
+        m_sun,
+        collection_getter,
+        collection_size_getter,
+        editor::property_holder::value_editor_combo_box,
+        editor::property_holder::cannot_enter_text
+    );
+
+    string_getter_type sky_texture_getter;
+    sky_texture_getter.bind(this, &time::sky_texture_getter);
+
+    string_setter_type sky_texture_setter;
+    sky_texture_setter.bind(this, &time::sky_texture_setter);
+
+    m_property_holder->add_property(
+        "texture",
+        "hemisphere",
+        "this option is resposible for sky texture",
+        sky_texture_name.c_str(),
+        sky_texture_getter,
+        sky_texture_setter,
+        ".dds",
+        "Texture files (*.dds)|*.dds",
+        detail::real_path("$game_textures$", "").c_str(),
+        "Select texture...",
+        editor::property_holder::cannot_enter_text,
+        editor::property_holder::remove_extension
+    );
+
+    m_property_holder->add_property(
+        "sky color",
+        "hemisphere",
+        "this option is resposible for sky color",
+        (editor::color const&)sky_color,
+        (editor::color&)sky_color
+    );
+
+    m_property_holder->add_property(
+        "hemi color",
+        "hemisphere",
+        "this option is resposible for hemisphere color",
+        (editor::color const&)hemi_color,
+        (editor::color&)hemi_color
+    );
+
+    typedef ::editor::property_holder::float_getter_type float_getter_type;
+    float_getter_type float_getter;
+
+    typedef ::editor::property_holder::float_setter_type float_setter_type;
+    float_setter_type float_setter;
+
+    float_getter.bind(this, &time::sky_rotation_getter);
+    float_setter.bind(this, &time::sky_rotation_setter);
+    m_property_holder->add_property(
+        "sky rotation",
+        "hemisphere",
+        "this option is resposible for sky rotation",
+        sky_rotation,
+        float_getter,
+        float_setter,
+        -360.0f,
+        360.f
+    );
+
+    string_getter.bind(this, &time::clouds_texture_getter);
+    string_setter.bind(this, &time::clouds_texture_setter);
+    m_property_holder->add_property(
+        "texture",
+        "clouds",
+        "this option is resposible for clouds texture",
+        clouds_texture_name.c_str(),
+        string_getter,
+        string_setter,
+        ".dds",
+        "Texture files (*.dds)|*.dds",
+        detail::real_path("$game_textures$", "").c_str(),
+        "Select texture...",
+        editor::property_holder::cannot_enter_text,
+        editor::property_holder::remove_extension
+    );
+
+    m_property_holder->add_property(
+        "color",
+        "clouds",
+        "this option is resposible for clouds color",
+        (editor::color const&)clouds_color,
+        (editor::color&)clouds_color
+    );
+
+    m_property_holder->add_property(
+        "transparency",
+        "clouds",
+        "this option is resposible for clouds transparency",
+        clouds_color.w,
+        clouds_color.w,
+        0.f,
+        1.f
+    );
+
+    m_property_holder->add_property(
+        "color",
+        "ambient",
+        "this option is resposible for ambient color",
+        (editor::color const&)ambient,
+        (editor::color&)ambient
+    );
+
+    collection_getter.bind(this, &time::ambients_collection);
+    collection_size_getter.bind(this, &time::ambients_collection_size);
+
+    string_getter.bind(this, &time::ambient_getter);
+    string_setter.bind(this, &time::ambient_setter);
+    m_property_holder->add_property(
+        "ambient",
+        "ambient",
+        "this option is resposible for ambient",
+        m_ambient.c_str(),
+        string_getter,
+        string_setter,
+        collection_getter,
+        collection_size_getter,
+        editor::property_holder::value_editor_combo_box,
+        editor::property_holder::cannot_enter_text
+    );
+
+    m_property_holder->add_property(
+        "color",
+        "fog",
+        "this option is resposible for fog density (0..1)",
+        (editor::color const&)fog_color,
+        (editor::color&)fog_color
+    );
+    m_property_holder->add_property(
+        "far plane",
+        "fog",
+        "this option is resposible for far plane",
+        far_plane,
+        far_plane
+    );
+    m_property_holder->add_property(
+        "distance",
+        "fog",
+        "this option is resposible for fog distance (shoudl be less than far plane)",
+        fog_distance,
+        fog_distance
+    );
+    m_property_holder->add_property(
+        "density",
+        "fog",
+        "this option is resposible for fog density (0..1)",
+        fog_density,
+        fog_density,
+        0.f,
+        1.f
+    );
+    m_property_holder->add_property(
+        "water intensity",
+        "fog",
+        "this option is resposible for water intensity (0..1)",
+        m_fWaterIntensity,
+        m_fWaterIntensity,
+        0.f,
+        1.f
+    );
+
+    m_property_holder->add_property(
+        "rain color",
+        "rain",
+        "this option is resposible for rain color",
+        (editor::color const&)rain_color,
+        (editor::color&)rain_color
+    );
+    m_property_holder->add_property(
+        "rain density",
+        "rain",
+        "this option is resposible for rain density (0..1)",
+        rain_density,
+        rain_density,
+        0.f,
+        1.f
+    );
+
+    collection_getter.bind(this, &time::thunderbolts_collection);
+    collection_size_getter.bind(this, &time::thunderbolts_collection_size);
+    m_property_holder->add_property(
+        "collection",
+        "thunderbolts",
+        "this option is resposible for ambient",
+        m_thunderbolt_collection.c_str(),
+        m_thunderbolt_collection,
+        collection_getter,
+        collection_size_getter,
+        editor::property_holder::value_editor_combo_box,
+        editor::property_holder::cannot_enter_text
+    );
+
+    m_property_holder->add_property(
+        "duration",
+        "thunderbolts",
+        "this option is resposible for thunderbolt duration",
+        bolt_duration,
+        bolt_duration
+    );
+    m_property_holder->add_property(
+        "period",
+        "thunderbolts",
+        "this option is resposible for thunderbolt period",
+        bolt_period,
+        bolt_period
+    );
+
+    float_getter.bind(this, &time::wind_direction_getter);
+    float_setter.bind(this, &time::wind_direction_setter);
+    m_property_holder->add_property(
+        "direction",
+        "wind",
+        "this option is resposible for wind direction (in degrees)",
+        wind_direction,
+        float_getter,
+        float_setter,
+        -360.f,
+        360.f
+    );
+    m_property_holder->add_property(
+        "velocity",
+        "wind",
+        "this option is resposible for wind velocity (meters per second)",
+        wind_velocity,
+        wind_velocity,
+        0.f,
+        1000.f
+    );
+}
+
+void time::lerp(CEnvironment* parent, CEnvDescriptor& A, CEnvDescriptor& B, float f, CEnvModifier& M, float m_power)
+{
+    float start_time = m_manager.Current[0]->exec_time;
+    float stop_time = m_manager.Current[1]->exec_time;
+    float current_time = m_manager.GetGameTime();
+    if (start_time >= stop_time)
+    {
+        if (current_time >= start_time)
+            clamp(current_time, start_time, 24.f*60.f*60.f);
+        else
+            clamp(current_time, 0.f, stop_time);
+
+        if (current_time <= stop_time)
+            current_time += 24.f*60.f*60.f;
+
+        stop_time += 24.f*60.f*60.f;
+    }
+    else
+        clamp(current_time, start_time, stop_time);
+
+    VERIFY(start_time < stop_time);
+
+    u32 current_time_u32 = iFloor(current_time);
+    current_time_u32 = current_time_u32 % (24 * 60 * 60);
+
+    u32 hours = current_time_u32 / (60 * 60);
+    current_time_u32 %= (60 * 60);
+
+    u32 minutes = current_time_u32 / 60;
+    u32 seconds = current_time_u32 % 60;
+
+    string16 temp;
+    xr_sprintf(temp, "%02d:%02d:%02d", hours, minutes, seconds);
+    m_identifier = temp;
+
+    time& a = static_cast(A);
+    m_ambient = a.m_ambient;
+    clouds_texture_name = a.clouds_texture_name;
+    sky_texture_name = a.sky_texture_name;
+    m_sun = a.m_sun;
+    m_thunderbolt_collection = a.m_thunderbolt_collection;
+
+    inherited::lerp(parent, A, B, f, M, m_power);
 }
 
 #endif // #ifdef INGAME_EDITOR
\ No newline at end of file
diff --git a/src/xrEngine/editor_environment_weathers_time.hpp b/src/xrEngine/editor_environment_weathers_time.hpp
index 7b9f1daaf47..89ff974e5fa 100644
--- a/src/xrEngine/editor_environment_weathers_time.hpp
+++ b/src/xrEngine/editor_environment_weathers_time.hpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_weathers_time.hpp
-//	Created 	: 12.01.2008
-//  Modified 	: 12.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment weathers time class
+// Module : editor_environment_weathers_time.hpp
+// Created : 12.01.2008
+// Modified : 12.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment weathers time class
 ////////////////////////////////////////////////////////////////////////////
 
 #ifndef EDITOR_ENVIRONMENT_WEATHERS_TIME_HPP_INCLUDED
@@ -15,80 +15,83 @@
 #include "../include/editor/property_holder.hpp"
 #include "environment.h"
 
-namespace editor {
-namespace environment {
+namespace editor
+{
+namespace environment
+{
 
 class manager;
 
-namespace weathers {
+namespace weathers
+{
 
 class weather;
 
 class time :
-	public CEnvDescriptorMixer,
-	public editor::property_holder_holder,
-	private boost::noncopyable
+    public CEnvDescriptorMixer,
+    public editor::property_holder_holder,
+    private boost::noncopyable
 {
 private:
-	typedef CEnvDescriptorMixer			inherited;
+    typedef CEnvDescriptorMixer inherited;
 
 public:
-	typedef editor::property_holder		property_holder_type;
+    typedef editor::property_holder property_holder_type;
 
 public:
-										time						(
-											editor::environment::manager* manager,
-											weather const* weather,
-											shared_str const& id
-										);
-	virtual								~time						();
-			void						load						(CInifile& config);
-			void						load_from					(shared_str const& id, CInifile& config, shared_str const& new_id);
-			void						save						(CInifile& config);
-			void						fill						(::editor::property_holder_collection* holder);
-	inline	shared_str const&			id							() const { return m_identifier; }
-	virtual	property_holder_type*		object						() { return m_property_holder; }
-	virtual	void						lerp						(CEnvironment* parent, CEnvDescriptor& A, CEnvDescriptor& B, float f, CEnvModifier& M, float m_power);
+    time(
+        editor::environment::manager* manager,
+        weather const* weather,
+        shared_str const& id
+    );
+    virtual ~time();
+    void load(CInifile& config);
+    void load_from(shared_str const& id, CInifile& config, shared_str const& new_id);
+    void save(CInifile& config);
+    void fill(::editor::property_holder_collection* holder);
+    inline shared_str const& id() const { return m_identifier; }
+    virtual property_holder_type* object() { return m_property_holder; }
+    virtual void lerp(CEnvironment* parent, CEnvDescriptor& A, CEnvDescriptor& B, float f, CEnvModifier& M, float m_power);
 
 private:
-	LPCSTR const*	xr_stdcall			ambients_collection			();
-	u32				xr_stdcall			ambients_collection_size	();
-	LPCSTR const*	xr_stdcall			suns_collection				();
-	u32				xr_stdcall			suns_collection_size		();
-	LPCSTR const*	xr_stdcall			thunderbolts_collection		();
-	u32				xr_stdcall			thunderbolts_collection_size();
+    LPCSTR const* xr_stdcall ambients_collection();
+    u32 xr_stdcall ambients_collection_size();
+    LPCSTR const* xr_stdcall suns_collection();
+    u32 xr_stdcall suns_collection_size();
+    LPCSTR const* xr_stdcall thunderbolts_collection();
+    u32 xr_stdcall thunderbolts_collection_size();
 
 private:
-	LPCSTR			xr_stdcall			id_getter					() const;
-	void			xr_stdcall			id_setter					(LPCSTR value);
-	float			xr_stdcall			sun_altitude_getter			() const;
-	void			xr_stdcall			sun_altitude_setter			(float value);
-	float			xr_stdcall			sun_longitude_getter		() const;
-	void			xr_stdcall			sun_longitude_setter		(float value);
-	float			xr_stdcall			sky_rotation_getter			() const;
-	void			xr_stdcall			sky_rotation_setter			(float value);
-	float			xr_stdcall			wind_direction_getter		() const;
-	void			xr_stdcall			wind_direction_setter		(float value);
-	LPCSTR			xr_stdcall			ambient_getter				() const;
-	void			xr_stdcall			ambient_setter				(LPCSTR value);
-	LPCSTR			xr_stdcall			sun_getter					() const;
-	void			xr_stdcall			sun_setter					(LPCSTR value);
-	LPCSTR			xr_stdcall			thunderbolt_getter			() const;
-	void			xr_stdcall			thunderbolt_setter			(LPCSTR value);
-	LPCSTR			xr_stdcall			sky_texture_getter			() const;
-	void			xr_stdcall			sky_texture_setter			(LPCSTR value);
-	LPCSTR			xr_stdcall			clouds_texture_getter		() const;
-	void			xr_stdcall			clouds_texture_setter		(LPCSTR value);
+    LPCSTR xr_stdcall id_getter() const;
+    void xr_stdcall id_setter(LPCSTR value);
+    float xr_stdcall sun_altitude_getter() const;
+    void xr_stdcall sun_altitude_setter(float value);
+    float xr_stdcall sun_longitude_getter() const;
+    void xr_stdcall sun_longitude_setter(float value);
+    float xr_stdcall sky_rotation_getter() const;
+    void xr_stdcall sky_rotation_setter(float value);
+    float xr_stdcall wind_direction_getter() const;
+    void xr_stdcall wind_direction_setter(float value);
+    LPCSTR xr_stdcall ambient_getter() const;
+    void xr_stdcall ambient_setter(LPCSTR value);
+    LPCSTR xr_stdcall sun_getter() const;
+    void xr_stdcall sun_setter(LPCSTR value);
+    LPCSTR xr_stdcall thunderbolt_getter() const;
+    void xr_stdcall thunderbolt_setter(LPCSTR value);
+    LPCSTR xr_stdcall sky_texture_getter() const;
+    void xr_stdcall sky_texture_setter(LPCSTR value);
+    LPCSTR xr_stdcall clouds_texture_getter() const;
+    void xr_stdcall clouds_texture_setter(LPCSTR value);
 
 private:
-	shared_str							m_ambient;
-	shared_str							m_sun;
-	shared_str							m_thunderbolt_collection;
+    shared_str m_ambient;
+    shared_str m_sun;
+    shared_str m_thunderbolt_collection;
 
 private:
-	editor::environment::manager&		m_manager;
-	weather const*						m_weather;
-	property_holder_type*				m_property_holder;
+    editor::environment::manager& m_manager;
+    weather const* m_weather;
+    property_holder_type* m_property_holder;
 }; // class time
 } // namespace weathers
 } // namespace environment
diff --git a/src/xrEngine/editor_environment_weathers_weather.cpp b/src/xrEngine/editor_environment_weathers_weather.cpp
index b03fa35dbfd..097318040dc 100644
--- a/src/xrEngine/editor_environment_weathers_weather.cpp
+++ b/src/xrEngine/editor_environment_weathers_weather.cpp
@@ -1,9 +1,9 @@
 ////////////////////////////////////////////////////////////////////////////
-//	Module 		: editor_environment_weathers_weather.cpp
-//	Created 	: 11.01.2008
-//  Modified 	: 11.01.2008
-//	Author		: Dmitriy Iassenev
-//	Description : editor environment weathers weather class
+// Module : editor_environment_weathers_weather.cpp
+// Created : 11.01.2008
+// Modified : 11.01.2008
+// Author : Dmitriy Iassenev
+// Description : editor environment weathers weather class
 ////////////////////////////////////////////////////////////////////////////
 
 #include "stdafx.h"
@@ -21,371 +21,379 @@ using editor::environment::weathers::manager;
 using editor::environment::weathers::time;
 
 template <>
-void property_collection::display_name	(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
+void property_collection::display_name(u32 const& item_index, LPSTR const& buffer, u32 const& buffer_size)
 {
-	xr_strcpy			(buffer, buffer_size, m_container[item_index]->id().c_str());
+    xr_strcpy(buffer, buffer_size, m_container[item_index]->id().c_str());
 }
 
 template <>
-editor::property_holder* property_collection::create	()
+editor::property_holder* property_collection::create()
 {
-	using ::editor::environment::weathers::time;
-	time*				object = xr_new