Browse Source

Reformat Urho3D source files to get rid of the indents on empty lines.
Reorganize includes.
Misc. fixes to perform explicit C-style cast on type mismatch.
Misc. fixes on bugs identified by CLion's static analyzer.

Yao Wei Tjong 姚伟忠 10 years ago
parent
commit
fa77a456f8
100 changed files with 3390 additions and 2260 deletions
  1. 3 0
      Source/Tools/RampGenerator/CMakeLists.txt
  2. 33 32
      Source/Urho3D/Audio/Audio.cpp
  3. 12 3
      Source/Urho3D/Audio/Audio.h
  4. 14 14
      Source/Urho3D/Audio/BufferedSoundStream.cpp
  5. 6 6
      Source/Urho3D/Audio/BufferedSoundStream.h
  6. 12 9
      Source/Urho3D/Audio/OggVorbisSoundStream.cpp
  7. 3 3
      Source/Urho3D/Audio/OggVorbisSoundStream.h
  8. 41 40
      Source/Urho3D/Audio/Sound.cpp
  9. 19 6
      Source/Urho3D/Audio/Sound.h
  10. 3 3
      Source/Urho3D/Audio/SoundListener.cpp
  11. 1 1
      Source/Urho3D/Audio/SoundListener.h
  12. 11 11
      Source/Urho3D/Audio/SoundSource.cpp
  13. 19 10
      Source/Urho3D/Audio/SoundSource.h
  14. 21 20
      Source/Urho3D/Audio/SoundSource3D.cpp
  15. 9 5
      Source/Urho3D/Audio/SoundSource3D.h
  16. 2 2
      Source/Urho3D/Audio/SoundStream.cpp
  17. 8 3
      Source/Urho3D/Audio/SoundStream.h
  18. 6 1
      Source/Urho3D/CMakeLists.txt
  19. 12 14
      Source/Urho3D/Container/Allocator.cpp
  20. 21 13
      Source/Urho3D/Container/Allocator.h
  21. 104 71
      Source/Urho3D/Container/ArrayPtr.h
  22. 17 17
      Source/Urho3D/Container/Hash.h
  23. 5 5
      Source/Urho3D/Container/HashBase.cpp
  24. 24 12
      Source/Urho3D/Container/HashBase.h
  25. 202 129
      Source/Urho3D/Container/HashMap.h
  26. 166 106
      Source/Urho3D/Container/HashSet.h
  27. 20 14
      Source/Urho3D/Container/LinkedList.h
  28. 140 74
      Source/Urho3D/Container/List.h
  29. 17 10
      Source/Urho3D/Container/ListBase.h
  30. 11 10
      Source/Urho3D/Container/Pair.h
  31. 106 75
      Source/Urho3D/Container/Ptr.h
  32. 4 4
      Source/Urho3D/Container/RefCounted.cpp
  33. 13 6
      Source/Urho3D/Container/RefCounted.h
  34. 4 4
      Source/Urho3D/Container/Sort.h
  35. 167 163
      Source/Urho3D/Container/Str.cpp
  36. 156 92
      Source/Urho3D/Container/Str.h
  37. 6 7
      Source/Urho3D/Container/Swap.cpp
  38. 5 5
      Source/Urho3D/Container/Swap.h
  39. 249 158
      Source/Urho3D/Container/Vector.h
  40. 2 0
      Source/Urho3D/Container/VectorBase.cpp
  41. 140 45
      Source/Urho3D/Container/VectorBase.h
  42. 7 6
      Source/Urho3D/Core/Attribute.h
  43. 8 2
      Source/Urho3D/Core/Condition.cpp
  44. 12 6
      Source/Urho3D/Core/Condition.h
  45. 8 6
      Source/Urho3D/Core/Context.cpp
  46. 25 2
      Source/Urho3D/Core/Context.h
  47. 3 1
      Source/Urho3D/Core/MiniDump.cpp
  48. 6 0
      Source/Urho3D/Core/Mutex.cpp
  49. 11 5
      Source/Urho3D/Core/Mutex.h
  50. 40 38
      Source/Urho3D/Core/Object.cpp
  51. 33 24
      Source/Urho3D/Core/Object.h
  52. 56 52
      Source/Urho3D/Core/ProcessUtils.cpp
  53. 23 21
      Source/Urho3D/Core/Profiler.cpp
  54. 13 8
      Source/Urho3D/Core/Spline.cpp
  55. 15 4
      Source/Urho3D/Core/Spline.h
  56. 19 13
      Source/Urho3D/Core/StringUtils.cpp
  57. 27 23
      Source/Urho3D/Core/Thread.cpp
  58. 11 5
      Source/Urho3D/Core/Thread.h
  59. 25 24
      Source/Urho3D/Core/Timer.cpp
  60. 17 13
      Source/Urho3D/Core/Timer.h
  61. 91 88
      Source/Urho3D/Core/Variant.cpp
  62. 309 131
      Source/Urho3D/Core/Variant.h
  63. 29 29
      Source/Urho3D/Core/WorkQueue.cpp
  64. 13 8
      Source/Urho3D/Core/WorkQueue.h
  65. 10 11
      Source/Urho3D/Engine/Application.cpp
  66. 8 6
      Source/Urho3D/Engine/Application.h
  67. 24 20
      Source/Urho3D/Engine/Console.cpp
  68. 16 0
      Source/Urho3D/Engine/Console.h
  69. 6 4
      Source/Urho3D/Engine/DebugHud.cpp
  70. 7 0
      Source/Urho3D/Engine/DebugHud.h
  71. 67 55
      Source/Urho3D/Engine/Engine.cpp
  72. 18 8
      Source/Urho3D/Engine/Engine.h
  73. 22 14
      Source/Urho3D/Graphics/AnimatedModel.cpp
  74. 14 1
      Source/Urho3D/Graphics/AnimatedModel.h
  75. 28 26
      Source/Urho3D/Graphics/Animation.cpp
  76. 17 10
      Source/Urho3D/Graphics/Animation.h
  77. 12 7
      Source/Urho3D/Graphics/AnimationController.cpp
  78. 1 1
      Source/Urho3D/Graphics/AnimationController.h
  79. 43 43
      Source/Urho3D/Graphics/AnimationState.cpp
  80. 12 5
      Source/Urho3D/Graphics/AnimationState.h
  81. 174 174
      Source/Urho3D/Graphics/Batch.cpp
  82. 29 19
      Source/Urho3D/Graphics/Batch.h
  83. 43 23
      Source/Urho3D/Graphics/BillboardSet.cpp
  84. 10 2
      Source/Urho3D/Graphics/BillboardSet.h
  85. 11 7
      Source/Urho3D/Graphics/Camera.cpp
  86. 22 2
      Source/Urho3D/Graphics/Camera.h
  87. 59 48
      Source/Urho3D/Graphics/CustomGeometry.cpp
  88. 8 1
      Source/Urho3D/Graphics/CustomGeometry.h
  89. 44 23
      Source/Urho3D/Graphics/DebugRenderer.cpp
  90. 14 9
      Source/Urho3D/Graphics/DebugRenderer.h
  91. 21 19
      Source/Urho3D/Graphics/DecalSet.cpp
  92. 21 7
      Source/Urho3D/Graphics/DecalSet.h
  93. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11ConstantBuffer.cpp
  94. 0 3
      Source/Urho3D/Graphics/Direct3D11/D3D11ConstantBuffer.h
  95. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11GPUObject.cpp
  96. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11Graphics.cpp
  97. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11GraphicsImpl.cpp
  98. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11IndexBuffer.cpp
  99. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11RenderSurface.cpp
  100. 2 0
      Source/Urho3D/Graphics/Direct3D11/D3D11ShaderVariation.cpp

+ 3 - 0
Source/Tools/RampGenerator/CMakeLists.txt

@@ -30,4 +30,7 @@ define_source_files ()
 set (LIBS STB)
 
 # Setup target
+if (APPLE)
+    setup_macosx_linker_flags (CMAKE_EXE_LINKER_FLAGS)
+endif ()
 setup_executable ()

+ 33 - 32
Source/Urho3D/Audio/Audio.cpp

@@ -20,16 +20,17 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Audio/Audio.h"
+#include "../Audio/Sound.h"
+#include "../Audio/SoundListener.h"
+#include "../Audio/SoundSource3D.h"
 #include "../Core/Context.h"
 #include "../Core/CoreEvents.h"
-#include "../IO/Log.h"
-#include "../Core/Mutex.h"
 #include "../Core/ProcessUtils.h"
 #include "../Core/Profiler.h"
-#include "../Audio/Sound.h"
-#include "../Audio/SoundListener.h"
-#include "../Audio/SoundSource3D.h"
+#include "../IO/Log.h"
 
 #include <SDL/SDL.h>
 
@@ -45,7 +46,7 @@ static const int MIN_MIXRATE = 11025;
 static const int MAX_MIXRATE = 48000;
 static const StringHash SOUND_MASTER_HASH("MASTER");
 
-static void SDLAudioCallback(void *userdata, Uint8 *stream, int len);
+static void SDLAudioCallback(void* userdata, Uint8* stream, int len);
 
 Audio::Audio(Context* context) :
     Object(context),
@@ -78,20 +79,20 @@ bool Audio::SetMode(int bufferLengthMSec, int mixRate, bool stereo, bool interpo
     SDL_AudioSpec obtained;
 
     desired.freq = mixRate;
-
-// The concept behind the emspcripten audio port is to treat it as 16 bit until the final acumulation form the clip buffer
-#ifdef EMSCRIPTEN
+
+// The concept behind the emscripten audio port is to treat it as 16 bit until the final accumulation form the clip buffer
+#ifdef EMSCRIPTEN
     desired.format = AUDIO_F32LSB;
-#else
+#else
     desired.format = AUDIO_S16;
-#endif
-    desired.channels = stereo ? 2 : 1;
+#endif
+    desired.channels = (Uint8)(stereo ? 2 : 1);
     desired.callback = SDLAudioCallback;
     desired.userdata = this;
 
     // SDL uses power of two audio fragments. Determine the closest match
     int bufferSamples = mixRate * bufferLengthMSec / 1000;
-    desired.samples = NextPowerOfTwo(bufferSamples);
+    desired.samples = (Uint16)NextPowerOfTwo((unsigned)bufferSamples);
     if (Abs((int)desired.samples / 2 - bufferSamples) < Abs((int)desired.samples - bufferSamples))
         desired.samples /= 2;
 
@@ -100,17 +101,17 @@ bool Audio::SetMode(int bufferLengthMSec, int mixRate, bool stereo, bool interpo
     {
         LOGERROR("Could not initialize audio output");
         return false;
-    }
-
-#ifdef EMSCRIPTEN
+    }
+
+#ifdef EMSCRIPTEN
     if (obtained.format != AUDIO_F32LSB && obtained.format != AUDIO_F32MSB && obtained.format != AUDIO_F32SYS)
-    {
+    {
         LOGERROR("Could not initialize audio output, 32-bit float buffer format not supported");
         SDL_CloseAudioDevice(deviceID_);
         deviceID_ = 0;
         return false;
-    }
-#else
+    }
+#else
     if (obtained.format != AUDIO_S16SYS && obtained.format != AUDIO_S16LSB && obtained.format != AUDIO_S16MSB)
     {
         LOGERROR("Could not initialize audio output, 16-bit buffer format not supported");
@@ -118,18 +119,18 @@ bool Audio::SetMode(int bufferLengthMSec, int mixRate, bool stereo, bool interpo
         deviceID_ = 0;
         return false;
     }
-#endif
+#endif
 
     stereo_ = obtained.channels == 2;
-    sampleSize_ = stereo_ ? sizeof(int) : sizeof(short);
+    sampleSize_ = (unsigned)(stereo_ ? sizeof(int) : sizeof(short));
     // Guarantee a fragment size that is low enough so that Vorbis decoding buffers do not wrap
-    fragmentSize_ = Min((int)NextPowerOfTwo(mixRate >> 6), (int)obtained.samples);
+    fragmentSize_ = (unsigned)Min((int)NextPowerOfTwo((unsigned)(mixRate >> 6)), (int)obtained.samples);
     mixRate_ = obtained.freq;
     interpolation_ = interpolation;
     clipBuffer_ = new int[stereo ? fragmentSize_ << 1 : fragmentSize_];
 
     LOGINFO("Set audio mode " + String(mixRate_) + " Hz " + (stereo_ ? "stereo" : "mono") + " " +
-        (interpolation_ ? "interpolated" : ""));
+            (interpolation_ ? "interpolated" : ""));
 
     return Play();
 }
@@ -233,7 +234,7 @@ float Audio::GetSoundSourceMasterGain(StringHash typeHash) const
     return masterIt->second_.GetFloat() * typeIt->second_.GetFloat();
 }
 
-void SDLAudioCallback(void *userdata, Uint8* stream, int len)
+void SDLAudioCallback(void* userdata, Uint8* stream, int len)
 {
     Audio* audio = static_cast<Audio*>(userdata);
     {
@@ -242,7 +243,7 @@ void SDLAudioCallback(void *userdata, Uint8* stream, int len)
     }
 }
 
-void Audio::MixOutput(void *dest, unsigned samples)
+void Audio::MixOutput(void* dest, unsigned samples)
 {
     if (!playing_ || !clipBuffer_)
     {
@@ -253,7 +254,7 @@ void Audio::MixOutput(void *dest, unsigned samples)
     while (samples)
     {
         // If sample count exceeds the fragment (clip buffer) size, split the work
-        unsigned workSamples = Min((int)samples, (int)fragmentSize_);
+        unsigned workSamples = (unsigned)Min((int)samples, (int)fragmentSize_);
         unsigned clipSamples = workSamples;
         if (stereo_)
             clipSamples <<= 1;
@@ -266,15 +267,15 @@ void Audio::MixOutput(void *dest, unsigned samples)
         for (PODVector<SoundSource*>::Iterator i = soundSources_.Begin(); i != soundSources_.End(); ++i)
             (*i)->Mix(clipPtr, workSamples, mixRate_, stereo_, interpolation_);
 
-        // Copy output from clip buffer to destination
-#ifdef EMSCRIPTEN
+        // Copy output from clip buffer to destination
+#ifdef EMSCRIPTEN
         float* destPtr = (float*)dest;
         while (clipSamples--)
             *destPtr++ = (float)Clamp(*clipPtr++, -32768, 32767) / 32768.0f;
-#else
-        short* destPtr = (short*)dest;
-        while (clipSamples--)
-            *destPtr++ = Clamp(*clipPtr++, -32768, 32767);
+#else
+        short* destPtr = (short*)dest;
+        while (clipSamples--)
+            *destPtr++ = (short)Clamp(*clipPtr++, -32768, 32767);
 #endif
         samples -= workSamples;
         ((unsigned char*&)dest) += sampleSize_ * SAMPLE_SIZE_MUL * workSamples;

+ 12 - 3
Source/Urho3D/Audio/Audio.h

@@ -22,8 +22,8 @@
 
 #pragma once
 
-#include "../Container/ArrayPtr.h"
 #include "../Audio/AudioDefs.h"
+#include "../Container/ArrayPtr.h"
 #include "../Core/Mutex.h"
 #include "../Core/Object.h"
 
@@ -63,20 +63,27 @@ public:
 
     /// Return byte size of one sample.
     unsigned GetSampleSize() const { return sampleSize_; }
+
     /// Return mixing rate.
     int GetMixRate() const { return mixRate_; }
+
     /// Return whether output is interpolated.
     bool GetInterpolation() const { return interpolation_; }
+
     /// Return whether output is stereo.
     bool IsStereo() const { return stereo_; }
+
     /// Return whether audio is being output.
     bool IsPlaying() const { return playing_; }
+
     /// Return whether an audio stream has been reserved.
     bool IsInitialized() const { return deviceID_ != 0; }
+
     /// Return master gain for a specific sound source type. Unknown sound types will return full gain (1).
     float GetMasterGain(const String& type) const;
     /// Return active sound listener.
     SoundListener* GetListener() const;
+
     /// Return all sound sources.
     const PODVector<SoundSource*>& GetSoundSources() const { return soundSources_; }
 
@@ -87,14 +94,16 @@ public:
     void AddSoundSource(SoundSource* soundSource);
     /// Remove a sound source. Called by SoundSource.
     void RemoveSoundSource(SoundSource* soundSource);
+
     /// Return audio thread mutex.
     Mutex& GetMutex() { return audioMutex_; }
+
     /// Return sound type specific gain multiplied by master gain.
     float GetSoundSourceMasterGain(StringHash typeHash) const;
 
     /// Mix sound sources into the buffer.
-    void MixOutput(void *dest, unsigned samples);
-
+    void MixOutput(void* dest, unsigned samples);
+
     /// Final multiplier for for audio byte conversion
 #ifdef EMSCRIPTEN
     static const int SAMPLE_SIZE_MUL = 2;

+ 14 - 14
Source/Urho3D/Audio/BufferedSoundStream.cpp

@@ -20,9 +20,9 @@
 // THE SOFTWARE.
 //
 
-#include "../Audio/BufferedSoundStream.h"
+#include "../Precompiled.h"
 
-#include <cstring>
+#include "../Audio/BufferedSoundStream.h"
 
 #include "../DebugNew.h"
 
@@ -41,18 +41,18 @@ BufferedSoundStream::~BufferedSoundStream()
 unsigned BufferedSoundStream::GetData(signed char* dest, unsigned numBytes)
 {
     MutexLock lock(bufferMutex_);
-    
+
     unsigned outBytes = 0;
-    
+
     while (numBytes && buffers_.Size())
     {
         // Copy as much from the front buffer as possible, then discard it and move to the next
         List<Pair<SharedArrayPtr<signed char>, unsigned> >::Iterator front = buffers_.Begin();
-        
+
         unsigned copySize = front->second_ - position_;
         if (copySize > numBytes)
             copySize = numBytes;
-        
+
         memcpy(dest, front->first_.Get() + position_, copySize);
         position_ += copySize;
         if (position_ >= front->second_)
@@ -60,12 +60,12 @@ unsigned BufferedSoundStream::GetData(signed char* dest, unsigned numBytes)
             buffers_.PopFront();
             position_ = 0;
         }
-        
+
         dest += copySize;
         outBytes += copySize;
         numBytes -= copySize;
     }
-    
+
     return outBytes;
 }
 
@@ -74,7 +74,7 @@ void BufferedSoundStream::AddData(void* data, unsigned numBytes)
     if (data && numBytes)
     {
         MutexLock lock(bufferMutex_);
-        
+
         SharedArrayPtr<signed char> newBuffer(new signed char[numBytes]);
         memcpy(newBuffer.Get(), data, numBytes);
         buffers_.Push(MakePair(newBuffer, numBytes));
@@ -86,7 +86,7 @@ void BufferedSoundStream::AddData(SharedArrayPtr<signed char> data, unsigned num
     if (data && numBytes)
     {
         MutexLock lock(bufferMutex_);
-        
+
         buffers_.Push(MakePair(data, numBytes));
     }
 }
@@ -96,7 +96,7 @@ void BufferedSoundStream::AddData(SharedArrayPtr<signed short> data, unsigned nu
     if (data && numBytes)
     {
         MutexLock lock(bufferMutex_);
-        
+
         buffers_.Push(MakePair(ReinterpretCast<signed char>(data), numBytes));
     }
 }
@@ -104,7 +104,7 @@ void BufferedSoundStream::AddData(SharedArrayPtr<signed short> data, unsigned nu
 void BufferedSoundStream::Clear()
 {
     MutexLock lock(bufferMutex_);
-    
+
     buffers_.Clear();
     position_ = 0;
 }
@@ -112,13 +112,13 @@ void BufferedSoundStream::Clear()
 unsigned BufferedSoundStream::GetBufferNumBytes() const
 {
     MutexLock lock(bufferMutex_);
-    
+
     unsigned ret = 0;
     for (List<Pair<SharedArrayPtr<signed char>, unsigned> >::ConstIterator i = buffers_.Begin(); i != buffers_.End(); ++i)
         ret += i->second_;
     // Subtract amount of sound data played from the front buffer
     ret -= position_;
-    
+
     return ret;
 }
 

+ 6 - 6
Source/Urho3D/Audio/BufferedSoundStream.h

@@ -22,11 +22,11 @@
 
 #pragma once
 
+#include "../Audio/SoundStream.h"
 #include "../Container/ArrayPtr.h"
 #include "../Container/List.h"
 #include "../Core/Mutex.h"
 #include "../Container/Pair.h"
-#include "../Audio/SoundStream.h"
 
 namespace Urho3D
 {
@@ -39,10 +39,10 @@ public:
     BufferedSoundStream();
     /// Destruct.
     ~BufferedSoundStream();
-    
+
     /// Produce sound data into destination. Return number of bytes produced. Called by SoundSource from the mixing thread.
     virtual unsigned GetData(signed char* dest, unsigned numBytes);
-    
+
     /// Buffer sound data. Makes a copy of it.
     void AddData(void* data, unsigned numBytes);
     /// Buffer sound data by taking ownership of it.
@@ -51,16 +51,16 @@ public:
     void AddData(SharedArrayPtr<signed short> data, unsigned numBytes);
     /// Remove all buffered audio data.
     void Clear();
-    
+
     /// Return amount of buffered (unplayed) sound data in bytes.
     unsigned GetBufferNumBytes() const;
     /// Return length of buffered (unplayed) sound data in seconds.
     float GetBufferLength() const;
-    
+
 private:
     /// Buffers and their sizes.
     List<Pair<SharedArrayPtr<signed char>, unsigned> > buffers_;
-    /// Byte position in the frontmost buffer.
+    /// Byte position in the front most buffer.
     unsigned position_;
     /// Mutex for buffer data.
     mutable Mutex bufferMutex_;

+ 12 - 9
Source/Urho3D/Audio/OggVorbisSoundStream.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Audio/OggVorbisSoundStream.h"
 #include "../Audio/Sound.h"
 
@@ -33,11 +35,11 @@ namespace Urho3D
 OggVorbisSoundStream::OggVorbisSoundStream(const Sound* sound)
 {
     assert(sound && sound->IsCompressed());
-    
+
     SetFormat(sound->GetIntFrequency(), sound->IsSixteenBit(), sound->IsStereo());
     // If the sound is looped, the stream will automatically rewind at end
     SetStopAtEnd(!sound->IsLooped());
-    
+
     // Initialize decoder
     data_ = sound->GetData();
     dataSize_ = sound->GetDataSize();
@@ -51,7 +53,7 @@ OggVorbisSoundStream::~OggVorbisSoundStream()
     if (decoder_)
     {
         stb_vorbis* vorbis = static_cast<stb_vorbis*>(decoder_);
-        
+
         stb_vorbis_close(vorbis);
         decoder_ = 0;
     }
@@ -61,22 +63,23 @@ unsigned OggVorbisSoundStream::GetData(signed char* dest, unsigned numBytes)
 {
     if (!decoder_)
         return 0;
-    
+
     stb_vorbis* vorbis = static_cast<stb_vorbis*>(decoder_);
-    
+
     unsigned channels = stereo_ ? 2 : 1;
-    unsigned outSamples = stb_vorbis_get_samples_short_interleaved(vorbis, channels, (short*)dest, numBytes >> 1);
+    unsigned outSamples = (unsigned)stb_vorbis_get_samples_short_interleaved(vorbis, channels, (short*)dest, numBytes >> 1);
     unsigned outBytes = (outSamples * channels) << 1;
-    
+
     // Rewind and retry if is looping and produced less output than should have
     if (outBytes < numBytes && !stopAtEnd_)
     {
         numBytes -= outBytes;
         stb_vorbis_seek_start(vorbis);
-        outSamples = stb_vorbis_get_samples_short_interleaved(vorbis, channels, (short*)(dest + outBytes), numBytes >> 1);
+        outSamples =
+            (unsigned)stb_vorbis_get_samples_short_interleaved(vorbis, channels, (short*)(dest + outBytes), numBytes >> 1);
         outBytes += (outSamples * channels) << 1;
     }
-    
+
     return outBytes;
 }
 

+ 3 - 3
Source/Urho3D/Audio/OggVorbisSoundStream.h

@@ -22,8 +22,8 @@
 
 #pragma once
 
-#include "../Container/ArrayPtr.h"
 #include "../Audio/SoundStream.h"
+#include "../Container/ArrayPtr.h"
 
 namespace Urho3D
 {
@@ -38,10 +38,10 @@ public:
     OggVorbisSoundStream(const Sound* sound);
     /// Destruct.
     ~OggVorbisSoundStream();
-    
+
     /// Produce sound data into destination. Return number of bytes produced. Called by SoundSource from the mixing thread.
     virtual unsigned GetData(signed char* dest, unsigned numBytes);
-    
+
 protected:
     /// Decoder state.
     void* decoder_;

+ 41 - 40
Source/Urho3D/Audio/Sound.cpp

@@ -20,16 +20,17 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
+#include "../Audio/OggVorbisSoundStream.h"
+#include "../Audio/Sound.h"
 #include "../Core/Context.h"
+#include "../Core/Profiler.h"
 #include "../IO/FileSystem.h"
 #include "../IO/Log.h"
-#include "../Audio/OggVorbisSoundStream.h"
-#include "../Core/Profiler.h"
 #include "../Resource/ResourceCache.h"
-#include "../Audio/Sound.h"
 #include "../Resource/XMLFile.h"
 
-#include <cstring>
 #include <STB/stb_vorbis.h>
 
 #include "../DebugNew.h"
@@ -83,19 +84,19 @@ void Sound::RegisterObject(Context* context)
 bool Sound::BeginLoad(Deserializer& source)
 {
     PROFILE(LoadSound);
-    
-    bool success = false;
+
+    bool success;
     if (GetExtension(source.GetName()) == ".ogg")
         success = LoadOggVorbis(source);
     else if (GetExtension(source.GetName()) == ".wav")
         success = LoadWav(source);
     else
         success = LoadRaw(source);
-    
+
     // Load optional parameters
     if (success)
         LoadParameters();
-    
+
     return success;
 }
 
@@ -104,7 +105,7 @@ bool Sound::LoadOggVorbis(Deserializer& source)
     unsigned dataSize = source.GetSize();
     SharedArrayPtr<signed char> data(new signed char[dataSize]);
     source.Read(data.Get(), dataSize);
-    
+
     // Check for validity of data
     int error;
     stb_vorbis* vorbis = stb_vorbis_open_memory((unsigned char*)data.Get(), dataSize, &error, 0);
@@ -113,19 +114,19 @@ bool Sound::LoadOggVorbis(Deserializer& source)
         LOGERROR("Could not read Ogg Vorbis data from " + source.GetName());
         return false;
     }
-    
+
     // Store length, frequency and stereo flag
     stb_vorbis_info info = stb_vorbis_get_info(vorbis);
     compressedLength_ = stb_vorbis_stream_length_in_seconds(vorbis);
     frequency_ = info.sample_rate;
     stereo_ = info.channels > 1;
     stb_vorbis_close(vorbis);
-    
+
     data_ = data;
     dataSize_ = dataSize;
     sixteenBit_ = true;
     compressed_ = true;
-    
+
     SetMemoryUse(dataSize);
     return true;
 }
@@ -133,19 +134,19 @@ bool Sound::LoadOggVorbis(Deserializer& source)
 bool Sound::LoadWav(Deserializer& source)
 {
     WavHeader header;
-    
+
     // Try to open
     memset(&header, 0, sizeof header);
     source.Read(&header.riffText_, 4);
     header.totalLength_ = source.ReadUInt();
     source.Read(&header.waveText_, 4);
-    
+
     if (memcmp("RIFF", header.riffText_, 4) || memcmp("WAVE", header.waveText_, 4))
     {
         LOGERROR("Could not read WAV data from " + source.GetName());
         return false;
     }
-    
+
     // Search for the FORMAT chunk
     for (;;)
     {
@@ -153,7 +154,7 @@ bool Sound::LoadWav(Deserializer& source)
         header.formatLength_ = source.ReadUInt();
         if (!memcmp("fmt ", &header.formatText_, 4))
             break;
-        
+
         source.Seek(source.GetPosition() + header.formatLength_);
         if (!header.formatLength_ || source.GetPosition() >= source.GetSize())
         {
@@ -161,7 +162,7 @@ bool Sound::LoadWav(Deserializer& source)
             return false;
         }
     }
-    
+
     // Read the FORMAT chunk
     header.format_ = source.ReadUShort();
     header.channels_ = source.ReadUShort();
@@ -169,17 +170,17 @@ bool Sound::LoadWav(Deserializer& source)
     header.avgBytes_ = source.ReadUInt();
     header.blockAlign_ = source.ReadUShort();
     header.bits_ = source.ReadUShort();
-    
+
     // Skip data if the format chunk was bigger than what we use
     source.Seek(source.GetPosition() + header.formatLength_ - 16);
-    
+
     // Check for correct format
     if (header.format_ != 1)
     {
         LOGERROR("Could not read WAV data from " + source.GetName());
         return false;
     }
-    
+
     // Search for the DATA chunk
     for (;;)
     {
@@ -187,7 +188,7 @@ bool Sound::LoadWav(Deserializer& source)
         header.dataLength_ = source.ReadUInt();
         if (!memcmp("data", &header.dataText_, 4))
             break;
-        
+
         source.Seek(source.GetPosition() + header.dataLength_);
         if (!header.dataLength_ || source.GetPosition() >= source.GetSize())
         {
@@ -195,20 +196,20 @@ bool Sound::LoadWav(Deserializer& source)
             return false;
         }
     }
-    
+
     // Allocate sound and load audio data
     unsigned length = header.dataLength_;
     SetSize(length);
     SetFormat(header.frequency_, header.bits_ == 16, header.channels_ == 2);
     source.Read(data_.Get(), length);
-    
+
     // Convert 8-bit audio to signed
     if (!sixteenBit_)
     {
         for (unsigned i = 0; i < length; ++i)
             data_[i] -= 128;
     }
-    
+
     return true;
 }
 
@@ -223,12 +224,12 @@ void Sound::SetSize(unsigned dataSize)
 {
     if (!dataSize)
         return;
-    
+
     data_ = new signed char[dataSize + IP_SAFETY];
     dataSize_ = dataSize;
     compressed_ = false;
     SetLooped(false);
-    
+
     SetMemoryUse(dataSize + IP_SAFETY);
 }
 
@@ -236,7 +237,7 @@ void Sound::SetData(const void* data, unsigned dataSize)
 {
     if (!dataSize)
         return;
-    
+
     SetSize(dataSize);
     memcpy(data_.Get(), data, dataSize);
 }
@@ -259,7 +260,7 @@ void Sound::SetLooped(bool enable)
         {
             end_ = data_.Get() + dataSize_;
             looped_ = false;
-            
+
             FixInterpolation();
         }
         else
@@ -275,16 +276,16 @@ void Sound::SetLoop(unsigned repeatOffset, unsigned endOffset)
             repeatOffset = dataSize_;
         if (endOffset > dataSize_)
             endOffset = dataSize_;
-        
+
         // Align repeat and end on sample boundaries
         int sampleSize = GetSampleSize();
         repeatOffset &= -sampleSize;
         endOffset &= -sampleSize;
-        
+
         repeat_ = data_.Get() + repeatOffset;
         end_ = data_.Get() + endOffset;
         looped_ = true;
-        
+
         FixInterpolation();
     }
     else
@@ -295,7 +296,7 @@ void Sound::FixInterpolation()
 {
     if (!data_ || compressed_)
         return;
-    
+
     // If looped, copy loop start to loop end. If oneshot, insert silence to end
     if (looped_)
     {
@@ -341,22 +342,22 @@ void Sound::LoadParameters()
 {
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     String xmlName = ReplaceExtension(GetName(), ".xml");
-    
+
     SharedPtr<XMLFile> file(cache->GetTempResource<XMLFile>(xmlName, false));
     if (!file)
         return;
-    
+
     XMLElement rootElem = file->GetRoot();
     XMLElement paramElem = rootElem.GetChild();
-    
+
     while (paramElem)
     {
         String name = paramElem.GetName();
-        
+
         if (name == "format" && !compressed_)
         {
             if (paramElem.HasAttribute("frequency"))
-                frequency_ = paramElem.GetInt("frequency");
+                frequency_ = (unsigned)paramElem.GetInt("frequency");
             if (paramElem.HasAttribute("sixteenbit"))
                 sixteenBit_ = paramElem.GetBool("sixteenbit");
             if (paramElem.HasAttribute("16bit"))
@@ -364,15 +365,15 @@ void Sound::LoadParameters()
             if (paramElem.HasAttribute("stereo"))
                 stereo_ = paramElem.GetBool("stereo");
         }
-        
+
         if (name == "loop")
         {
             if (paramElem.HasAttribute("enable"))
                 SetLooped(paramElem.GetBool("enable"));
             if (paramElem.HasAttribute("start") && paramElem.HasAttribute("end"))
-                SetLoop(paramElem.GetInt("start"), paramElem.GetInt("end"));
+                SetLoop((unsigned)paramElem.GetInt("start"), (unsigned)paramElem.GetInt("end"));
         }
-        
+
         paramElem = paramElem.GetNext();
     }
 }

+ 19 - 6
Source/Urho3D/Audio/Sound.h

@@ -34,7 +34,7 @@ class SoundStream;
 class URHO3D_API Sound : public Resource
 {
     OBJECT(Sound);
-    
+
 public:
     /// Construct.
     Sound(Context* context);
@@ -42,10 +42,10 @@ public:
     virtual ~Sound();
     /// Register object factory.
     static void RegisterObject(Context* context);
-    
+
     /// Load resource from stream. May be called from a worker thread. Return true if successful.
     virtual bool BeginLoad(Deserializer& source);
-    
+
     /// Load raw sound data.
     bool LoadRaw(Deserializer& source);
     /// Load WAV format sound data.
@@ -62,43 +62,56 @@ public:
     void SetLooped(bool enable);
     /// Define loop.
     void SetLoop(unsigned repeatOffset, unsigned endOffset);
-    
+
     /// Return a new instance of a decoder sound stream. Used by compressed sounds.
     SharedPtr<SoundStream> GetDecoderStream() const;
+
     /// Return shared sound data.
     SharedArrayPtr<signed char> GetData() const { return data_; }
+
     /// Return sound data start.
     signed char* GetStart() const { return data_.Get(); }
+
     /// Return loop start.
     signed char* GetRepeat() const { return repeat_; }
+
     /// Return sound data end.
     signed char* GetEnd() const { return end_; }
+
     /// Return length in seconds.
     float GetLength() const;
+
     /// Return total sound data size.
     unsigned GetDataSize() const { return dataSize_; }
+
     /// Return sample size.
     unsigned GetSampleSize() const;
+
     /// Return default frequency as a float.
     float GetFrequency() const { return (float)frequency_; }
+
     /// Return default frequency as an integer.
     unsigned GetIntFrequency() const { return frequency_; }
+
     /// Return whether is looped.
     bool IsLooped() const { return looped_; }
+
     /// Return whether data is sixteen bit.
     bool IsSixteenBit() const { return sixteenBit_; }
+
     /// Return whether data is stereo.
     bool IsStereo() const { return stereo_; }
+
     /// Return whether is compressed.
     bool IsCompressed() const { return compressed_; }
-    
+
     /// Fix interpolation by copying data from loop start to loop end (looped), or adding silence (oneshot.) Called internally, does not normally need to be called, unless the sound data is modified manually on the fly.
     void FixInterpolation();
 
 private:
     /// Load optional parameters from an XML file.
     void LoadParameters();
-    
+
     /// Sound data.
     SharedArrayPtr<signed char> data_;
     /// Loop start.

+ 3 - 3
Source/Urho3D/Audio/SoundListener.cpp

@@ -20,10 +20,10 @@
 // THE SOFTWARE.
 //
 
-#include "../Core/Context.h"
-#include "../Audio/SoundListener.h"
+#include "../Precompiled.h"
 
-#include "../DebugNew.h"
+#include "../Audio/SoundListener.h"
+#include "../Core/Context.h"
 
 namespace Urho3D
 {

+ 1 - 1
Source/Urho3D/Audio/SoundListener.h

@@ -31,7 +31,7 @@ namespace Urho3D
 class URHO3D_API SoundListener : public Component
 {
     OBJECT(SoundListener);
-    
+
 public:
     /// Construct.
     SoundListener(Context* context);

+ 11 - 11
Source/Urho3D/Audio/SoundSource.cpp

@@ -20,14 +20,14 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Audio/Audio.h"
-#include "../Core/Context.h"
-#include "../Resource/ResourceCache.h"
 #include "../Audio/Sound.h"
 #include "../Audio/SoundSource.h"
 #include "../Audio/SoundStream.h"
-
-#include <cstring>
+#include "../Core/Context.h"
+#include "../Resource/ResourceCache.h"
 
 #include "../DebugNew.h"
 
@@ -115,7 +115,7 @@ SoundSource::SoundSource(Context* context) :
 
     if (audio_)
         audio_->AddSoundSource(this);
-    
+
     UpdateMasterGain();
 }
 
@@ -236,7 +236,7 @@ void SoundSource::SetSoundType(const String& type)
     soundType_ = type;
     soundTypeHash_ = StringHash(type);
     UpdateMasterGain();
-    
+
     MarkNetworkUpdate();
 }
 
@@ -337,12 +337,12 @@ void SoundSource::Mix(int* dest, unsigned samples, int mixRate, bool stereo, boo
         position_ = streamBuffer_->GetStart();
 
         // Request new data from the stream
-        signed char* dest = streamBuffer_->GetStart() + unusedStreamSize_;
-        outBytes = neededSize ? soundStream_->GetData(dest, neededSize) : 0;
-        dest += outBytes;
+        signed char* destination = streamBuffer_->GetStart() + unusedStreamSize_;
+        outBytes = neededSize ? soundStream_->GetData(destination, (unsigned)neededSize) : 0;
+        destination += outBytes;
         // Zero-fill rest if stream did not produce enough data
         if (outBytes < neededSize)
-            memset(dest, 0, neededSize - outBytes);
+            memset(destination, 0, (size_t)(neededSize - outBytes));
 
         // Calculate amount of total bytes of data in stream buffer now, to know how much went unused after mixing
         streamFilledSize = neededSize + unusedStreamSize_;
@@ -396,7 +396,7 @@ void SoundSource::Mix(int* dest, unsigned samples, int mixRate, bool stereo, boo
 
         unusedStreamSize_ = Max(streamFilledSize - (int)(size_t)(position_ - streamBuffer_->GetStart()), 0);
         if (unusedStreamSize_)
-            memcpy(streamBuffer_->GetStart(), (const void*)position_, unusedStreamSize_);
+            memcpy(streamBuffer_->GetStart(), (const void*)position_, (size_t)unusedStreamSize_);
 
         // If stream did not produce any data, stop if applicable
         if (!outBytes && soundStream_->GetStopAtEnd())

+ 19 - 10
Source/Urho3D/Audio/SoundSource.h

@@ -39,7 +39,7 @@ static const int STREAM_BUFFER_LENGTH = 100;
 class URHO3D_API SoundSource : public Component
 {
     OBJECT(SoundSource);
-    
+
 public:
     /// Construct.
     SoundSource(Context* context);
@@ -47,7 +47,7 @@ public:
     virtual ~SoundSource();
     /// Register object factory.
     static void RegisterObject(Context* context);
-    
+
     /// Play a sound.
     void Play(Sound* sound);
     /// Play a sound with specified frequency.
@@ -70,39 +70,48 @@ public:
     void SetAttenuation(float attenuation);
     /// Set stereo panning. -1.0 is full left and 1.0 is full right.
     void SetPanning(float panning);
-   /// Set whether sound source will be automatically removed from the scene node when playback stops.
+    /// Set whether sound source will be automatically removed from the scene node when playback stops.
     void SetAutoRemove(bool enable);
     /// Set new playback position.
     void SetPlayPosition(signed char* pos);
-    
+
     /// Return sound.
     Sound* GetSound() const { return sound_; }
+
     /// Return playback position.
     volatile signed char* GetPlayPosition() const { return position_; }
+
     /// Return sound type, determines the master gain group.
     String GetSoundType() const { return soundType_; }
+
     /// Return playback time position.
     float GetTimePosition() const { return timePosition_; }
+
     /// Return frequency.
     float GetFrequency() const { return frequency_; }
+
     /// Return gain.
     float GetGain() const { return gain_; }
+
     /// Return attenuation.
     float GetAttenuation() const { return attenuation_; }
+
     /// Return stereo panning.
     float GetPanning() const { return panning_; }
+
     /// Return autoremove mode.
     bool GetAutoRemove() const { return autoRemove_; }
+
     /// Return whether is playing.
     bool IsPlaying() const;
-    
+
     /// Update the sound source. Perform subclass specific operations. Called by Audio.
     virtual void Update(float timeStep);
     /// Mix sound source output to a 32-bit clipping buffer. Called by Audio.
     void Mix(int* dest, unsigned samples, int mixRate, bool stereo, bool interpolation);
     /// Update the effective master gain. Called internally and by Audio when the master gain changes.
     void UpdateMasterGain();
-    
+
     /// Set sound attribute.
     void SetSoundAttr(const ResourceRef& value);
     /// Set sound position attribute.
@@ -113,7 +122,7 @@ public:
     void SetPlayingAttr(bool value);
     /// Return sound position attribute.
     int GetPositionAttr() const;
-    
+
 protected:
     /// Audio subsystem.
     WeakPtr<Audio> audio_;
@@ -135,7 +144,7 @@ protected:
     float masterGain_;
     /// Autoremove flag.
     bool autoRemove_;
-    
+
 private:
     /// Play a sound without locking the audio mutex. Called internally.
     void PlayLockless(Sound* sound);
@@ -165,13 +174,13 @@ private:
     void MixZeroVolume(Sound* sound, unsigned samples, int mixRate);
     /// Advance playback pointer to simulate audio playback in headless mode.
     void MixNull(float timeStep);
-    
+
     /// Sound that is being played.
     SharedPtr<Sound> sound_;
     /// Sound stream that is being played.
     SharedPtr<SoundStream> soundStream_;
     /// Playback position.
-    volatile signed char *position_;
+    volatile signed char* position_;
     /// Playback fractional position.
     volatile int fractPosition_;
     /// Playback time position.

+ 21 - 20
Source/Urho3D/Audio/SoundSource3D.cpp

@@ -20,15 +20,15 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Audio/Audio.h"
-#include "../Core/Context.h"
-#include "../Graphics/DebugRenderer.h"
-#include "../Scene/Node.h"
 #include "../Audio/Sound.h"
 #include "../Audio/SoundListener.h"
 #include "../Audio/SoundSource3D.h"
-
-#include "../DebugNew.h"
+#include "../Core/Context.h"
+#include "../Graphics/DebugRenderer.h"
+#include "../Scene/Node.h"
 
 namespace Urho3D
 {
@@ -47,7 +47,7 @@ static Vector3 PointOnSphere(float radius, float theta, float phi)
 {
     // Zero angles point toward positive Z axis
     phi += 90.0f;
-    
+
     return Vector3(
         radius * Sin(theta) * Sin(phi),
         radius * Cos(phi),
@@ -65,10 +65,10 @@ static void DrawDebugArc(const Vector3& worldPosition, const Quaternion& worldRo
         debug->AddSphere(Sphere(worldPosition, distance), color, depthTest);
         return;
     }
-    
+
     unsigned uintColor = color.ToUInt();
     float halfAngle = 0.5f * angle;
-    
+
     if (drawLines)
     {
         debug->AddLine(worldPosition, worldPosition + worldRotation * PointOnSphere(distance, halfAngle, halfAngle),
@@ -80,9 +80,9 @@ static void DrawDebugArc(const Vector3& worldPosition, const Quaternion& worldRo
         debug->AddLine(worldPosition, worldPosition + worldRotation * PointOnSphere(distance, -halfAngle, -halfAngle),
             uintColor);
     }
-    
+
     const float step = 0.5f;
-    
+
     for (float x = -1.0f; x < 1.0f; x += step)
     {
         debug->AddLine(worldPosition + worldRotation * PointOnSphere(distance, x * halfAngle, halfAngle),
@@ -131,11 +131,11 @@ void SoundSource3D::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
 {
     if (!debug || !node_ || !IsEnabledEffective())
         return;
-    
+
     const Matrix3x4& worldTransform = node_->GetWorldTransform();
     Vector3 worldPosition = worldTransform.Translation();
     Quaternion worldRotation = worldTransform.Rotation();
-    
+
     // Draw cones for directional sounds, or spheres for non-directional
     if (innerAngle_ < DEFAULT_ANGLE && outerAngle_ > 0.0f)
     {
@@ -216,28 +216,29 @@ void SoundSource3D::CalculateAttenuation()
         if (listener && listener->IsEnabledEffective() && (!listener->GetScene() || listener->GetScene() == GetScene()))
         {
             Node* listenerNode = listener->GetNode();
-            Vector3 relativePos(listenerNode->GetWorldRotation().Inverse() * (node_->GetWorldPosition() - listenerNode->GetWorldPosition()));
+            Vector3 relativePos
+                (listenerNode->GetWorldRotation().Inverse() * (node_->GetWorldPosition() - listenerNode->GetWorldPosition()));
             float distance = relativePos.Length();
-            
+
             // Distance attenuation
             if (interval > 0.0f)
                 attenuation_ = powf(1.0f - Clamp(distance - nearDistance_, 0.0f, interval) / interval, rolloffFactor_);
             else
                 attenuation_ = distance <= nearDistance_ ? 1.0f : 0.0f;
-            
+
             // Panning
             panning_ = relativePos.Normalized().x_;
-            
+
             // Angle attenuation
             if (innerAngle_ < DEFAULT_ANGLE && outerAngle_ > 0.0f)
             {
-                Vector3 listenerRelativePos(node_->GetWorldRotation().Inverse() * (listenerNode->GetWorldPosition() -
-                    node_->GetWorldPosition()));
+                Vector3 listenerRelativePos
+                    (node_->GetWorldRotation().Inverse() * (listenerNode->GetWorldPosition() - node_->GetWorldPosition()));
                 float listenerDot = Vector3::FORWARD.DotProduct(listenerRelativePos.Normalized());
                 float listenerAngle = acosf(listenerDot) * M_RADTODEG * 2.0f;
                 float angleInterval = Max(outerAngle_ - innerAngle_, 0.0f);
                 float angleAttenuation = 1.0f;
-                
+
                 if (angleInterval > 0.0f)
                 {
                     if (listenerAngle > innerAngle_)
@@ -248,7 +249,7 @@ void SoundSource3D::CalculateAttenuation()
                 }
                 else
                     angleAttenuation = listenerAngle <= innerAngle_ ? 1.0f : 0.0f;
-                
+
                 attenuation_ *= angleAttenuation;
             }
         }

+ 9 - 5
Source/Urho3D/Audio/SoundSource3D.h

@@ -33,18 +33,18 @@ class Audio;
 class URHO3D_API SoundSource3D : public SoundSource
 {
     OBJECT(SoundSource3D);
-    
+
 public:
     /// Construct.
     SoundSource3D(Context* context);
     /// Register object factory.
     static void RegisterObject(Context* context);
-    
+
     /// Visualize the component as debug geometry.
     virtual void DrawDebugGeometry(DebugRenderer* debug, bool depthTest);
     /// Update sound source.
     virtual void Update(float timeStep);
-    
+
     /// Set attenuation parameters.
     void SetDistanceAttenuation(float nearDistance, float farDistance, float rolloffFactor);
     /// Set angle attenuation parameters.
@@ -61,18 +61,22 @@ public:
     void SetRolloffFactor(float factor);
     /// Calculate attenuation and panning based on current position and listener position.
     void CalculateAttenuation();
-    
+
     /// Return near distance.
     float GetNearDistance() const { return nearDistance_; }
+
     /// Return far distance.
     float GetFarDistance() const { return farDistance_; }
+
     /// Return inner angle in degrees.
     float GetInnerAngle() const { return innerAngle_; }
+
     /// Return outer angle in degrees.
     float GetOuterAngle() const { return outerAngle_; }
+
     /// Return rolloff power factor.
     float RollAngleoffFactor() const { return rolloffFactor_; }
-    
+
 protected:
     /// Near distance.
     float nearDistance_;

+ 2 - 2
Source/Urho3D/Audio/SoundStream.cpp

@@ -20,9 +20,9 @@
 // THE SOFTWARE.
 //
 
-#include "../Audio/SoundStream.h"
+#include "../Precompiled.h"
 
-#include "../DebugNew.h"
+#include "../Audio/SoundStream.h"
 
 namespace Urho3D
 {

+ 8 - 3
Source/Urho3D/Audio/SoundStream.h

@@ -35,25 +35,30 @@ public:
     SoundStream();
     /// Destruct.
     ~SoundStream();
-    
+
     /// Produce sound data into destination. Return number of bytes produced. Called by SoundSource from the mixing thread.
     virtual unsigned GetData(signed char* dest, unsigned numBytes) = 0;
-    
+
     /// Set sound data format.
     void SetFormat(unsigned frequency, bool sixteenBit, bool stereo);
     /// Set whether playback should stop when no more data. Default false.
     void SetStopAtEnd(bool enable);
-    
+
     /// Return sample size.
     unsigned GetSampleSize() const;
+
     /// Return default frequency as a float.
     float GetFrequency() const { return (float)frequency_; }
+
     /// Return default frequency as an integer.
     unsigned GetIntFrequency() const { return frequency_; }
+
     /// Return whether playback should stop when no more data.
     bool GetStopAtEnd() const { return stopAtEnd_; }
+
     /// Return whether data is sixteen bit.
     bool IsSixteenBit() const { return sixteenBit_; }
+
     /// Return whether data is stereo.
     bool IsStereo() const { return stereo_; }
 

+ 6 - 1
Source/Urho3D/CMakeLists.txt

@@ -23,6 +23,8 @@
 # Define target name
 set (TARGET_NAME Urho3D)
 
+add_definitions (-DURHO3D_IS_BUILDING)
+
 if (WIN32)
     set (CMAKE_DEBUG_POSTFIX _d)
 endif ()
@@ -140,7 +142,10 @@ if (APPLE AND NOT IOS)
     set (GLOB_OBJC_PATTERN *.m)     # Should only pick up MacFileWatcher.m for MacOSX platform at the moment
 endif ()
 string (REPLACE ";" "/[^;]+;" EXCLUDE_PATTERNS "${EXCLUDED_SOURCE_DIRS};")
-define_source_files (EXCLUDE_PATTERNS ${EXCLUDE_PATTERNS} GLOB_CPP_PATTERNS *.cpp ${GLOB_OBJC_PATTERN} EXTRA_H_FILES librevision.h Urho3D.h RECURSE GROUP PCH Precompiled.h)
+if (URHO3D_PCH)
+    set (PCH PCH Precompiled.h)
+endif ()
+define_source_files (EXCLUDE_PATTERNS ${EXCLUDE_PATTERNS} GLOB_CPP_PATTERNS *.cpp ${GLOB_OBJC_PATTERN} EXTRA_H_FILES librevision.h Urho3D.h RECURSE GROUP ${PCH})
 list (APPEND SOURCE_FILES ${GEN_CPP_FILES} ${ALL_OBJ_FILES})
 
 # Define dependency libs

+ 12 - 14
Source/Urho3D/Container/Allocator.cpp

@@ -20,9 +20,7 @@
 // THE SOFTWARE.
 //
 
-#include "../Container/Allocator.h"
-
-#include "stdio.h"
+#include "../Precompiled.h"
 
 #include "../DebugNew.h"
 
@@ -33,14 +31,14 @@ AllocatorBlock* AllocatorReserveBlock(AllocatorBlock* allocator, unsigned nodeSi
 {
     if (!capacity)
         capacity = 1;
-    
+
     unsigned char* blockPtr = new unsigned char[sizeof(AllocatorBlock) + capacity * (sizeof(AllocatorNode) + nodeSize)];
     AllocatorBlock* newBlock = reinterpret_cast<AllocatorBlock*>(blockPtr);
     newBlock->nodeSize_ = nodeSize;
     newBlock->capacity_ = capacity;
     newBlock->free_ = 0;
     newBlock->next_ = 0;
-    
+
     if (!allocator)
         allocator = newBlock;
     else
@@ -48,11 +46,11 @@ AllocatorBlock* AllocatorReserveBlock(AllocatorBlock* allocator, unsigned nodeSi
         newBlock->next_ = allocator->next_;
         allocator->next_ = newBlock;
     }
-    
+
     // Initialize the nodes. Free nodes are always chained to the first (parent) allocator
     unsigned char* nodePtr = blockPtr + sizeof(AllocatorBlock);
     AllocatorNode* firstNewNode = reinterpret_cast<AllocatorNode*>(nodePtr);
-    
+
     for (unsigned i = 0; i < capacity - 1; ++i)
     {
         AllocatorNode* newNode = reinterpret_cast<AllocatorNode*>(nodePtr);
@@ -64,9 +62,9 @@ AllocatorBlock* AllocatorReserveBlock(AllocatorBlock* allocator, unsigned nodeSi
         AllocatorNode* newNode = reinterpret_cast<AllocatorNode*>(nodePtr);
         newNode->next_ = 0;
     }
-    
+
     allocator->free_ = firstNewNode;
-    
+
     return newBlock;
 }
 
@@ -90,7 +88,7 @@ void* AllocatorReserve(AllocatorBlock* allocator)
 {
     if (!allocator)
         return 0;
-    
+
     if (!allocator->free_)
     {
         // Free nodes have been exhausted. Allocate a new larger block
@@ -98,13 +96,13 @@ void* AllocatorReserve(AllocatorBlock* allocator)
         AllocatorReserveBlock(allocator, allocator->nodeSize_, newCapacity);
         allocator->capacity_ += newCapacity;
     }
-    
+
     // We should have new free node(s) chained
     AllocatorNode* freeNode = allocator->free_;
     void* ptr = (reinterpret_cast<unsigned char*>(freeNode)) + sizeof(AllocatorNode);
     allocator->free_ = freeNode->next_;
     freeNode->next_ = 0;
-    
+
     return ptr;
 }
 
@@ -112,10 +110,10 @@ void AllocatorFree(AllocatorBlock* allocator, void* ptr)
 {
     if (!allocator || !ptr)
         return;
-    
+
     unsigned char* dataPtr = static_cast<unsigned char*>(ptr);
     AllocatorNode* node = reinterpret_cast<AllocatorNode*>(dataPtr - sizeof(AllocatorNode));
-    
+
     // Chain the node back to free nodes
     node->next_ = allocator->free_;
     allocator->free_ = node;

+ 21 - 13
Source/Urho3D/Container/Allocator.h

@@ -22,7 +22,15 @@
 
 #pragma once
 
-#include <new>
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
+#include <stddef.h>
+
+#include "../DebugNew.h"
 
 namespace Urho3D
 {
@@ -70,50 +78,50 @@ public:
         allocator_(0)
     {
         if (initialCapacity)
-            allocator_ = AllocatorInitialize(sizeof(T), initialCapacity);
+            allocator_ = AllocatorInitialize((unsigned)sizeof(T), initialCapacity);
     }
-    
+
     /// Destruct.
     ~Allocator()
     {
         AllocatorUninitialize(allocator_);
     }
-    
+
     /// Reserve and default-construct an object.
     T* Reserve()
     {
         if (!allocator_)
-            allocator_ = AllocatorInitialize(sizeof(T));
+            allocator_ = AllocatorInitialize((unsigned)sizeof(T));
         T* newObject = static_cast<T*>(AllocatorReserve(allocator_));
         new(newObject) T();
-        
+
         return newObject;
     }
-    
+
     /// Reserve and copy-construct an object.
     T* Reserve(const T& object)
     {
         if (!allocator_)
-            allocator_ = AllocatorInitialize(sizeof(T));
+            allocator_ = AllocatorInitialize((unsigned)sizeof(T));
         T* newObject = static_cast<T*>(AllocatorReserve(allocator_));
         new(newObject) T(object);
-        
+
         return newObject;
     }
-    
+
     /// Destruct and free an object.
     void Free(T* object)
     {
         (object)->~T();
         AllocatorFree(allocator_, object);
     }
-    
+
 private:
     /// Prevent copy construction.
     Allocator(const Allocator<T>& rhs);
     /// Prevent assignment.
-    Allocator<T>& operator = (const Allocator<T>& rhs);
-    
+    Allocator<T>& operator =(const Allocator<T>& rhs);
+
     /// Allocator block.
     AllocatorBlock* allocator_;
 };

+ 104 - 71
Source/Urho3D/Container/ArrayPtr.h

@@ -40,7 +40,7 @@ public:
         refCount_(0)
     {
     }
-    
+
     /// Copy-construct from another shared array pointer.
     SharedArrayPtr(const SharedArrayPtr<T>& rhs) :
         ptr_(rhs.ptr_),
@@ -48,7 +48,7 @@ public:
     {
         AddRef();
     }
-    
+
     /// Construct from a raw pointer.
     explicit SharedArrayPtr(T* ptr) :
         ptr_(ptr),
@@ -56,63 +56,81 @@ public:
     {
         AddRef();
     }
-    
+
     /// Destruct. Release the array reference.
     ~SharedArrayPtr()
     {
         ReleaseRef();
     }
-    
+
     /// Assign from another shared array pointer.
-    SharedArrayPtr<T>& operator = (const SharedArrayPtr<T>& rhs)
+    SharedArrayPtr<T>& operator =(const SharedArrayPtr<T>& rhs)
     {
         if (ptr_ == rhs.ptr_)
             return *this;
-        
+
         ReleaseRef();
         ptr_ = rhs.ptr_;
         refCount_ = rhs.refCount_;
         AddRef();
-        
+
         return *this;
     }
-    
+
     /// Assign from a raw pointer.
-    SharedArrayPtr<T>& operator = (T* ptr)
+    SharedArrayPtr<T>& operator =(T* ptr)
     {
         if (ptr_ == ptr)
             return *this;
-        
+
         ReleaseRef();
-        
+
         if (ptr)
         {
             ptr_ = ptr;
             refCount_ = new RefCount();
             AddRef();
         }
-        
+
         return *this;
     }
-    
+
     /// Point to the array.
-    T* operator -> () const { assert(ptr_); return ptr_; }
+    T* operator ->() const
+    {
+        assert(ptr_);
+        return ptr_;
+    }
+
     /// Dereference the array.
-    T& operator * () const { assert(ptr_); return *ptr_; }
+    T& operator *() const
+    {
+        assert(ptr_);
+        return *ptr_;
+    }
+
     /// Subscript the array.
-    T& operator [] (const int index) { assert(ptr_); return ptr_[index]; }
+    T& operator [](const int index)
+    {
+        assert(ptr_);
+        return ptr_[index];
+    }
+
     /// Test for equality with another shared array pointer.
-    bool operator == (const SharedArrayPtr<T>& rhs) const { return ptr_ == rhs.ptr_; }
+    bool operator ==(const SharedArrayPtr<T>& rhs) const { return ptr_ == rhs.ptr_; }
+
     /// Test for inequality with another shared array pointer.
-    bool operator != (const SharedArrayPtr<T>& rhs) const { return ptr_ != rhs.ptr_; }
+    bool operator !=(const SharedArrayPtr<T>& rhs) const { return ptr_ != rhs.ptr_; }
+
     /// Test for less than with another array pointer.
-    bool operator < (const SharedArrayPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+    bool operator <(const SharedArrayPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+
     /// Convert to a raw pointer.
-    operator T* () const { return ptr_; }
-    
+    operator T*() const { return ptr_; }
+
     /// Reset to null and release the array reference.
     void Reset() { ReleaseRef(); }
-    
+
     /// Perform a static cast from a shared array pointer of another type.
     template <class U> void StaticCast(const SharedArrayPtr<U>& rhs)
     {
@@ -121,8 +139,8 @@ public:
         refCount_ = rhs.RefCountPtr();
         AddRef();
     }
-    
-   /// Perform a reinterpret cast from a shared array pointer of another type.
+
+    /// Perform a reinterpret cast from a shared array pointer of another type.
     template <class U> void ReinterpretCast(const SharedArrayPtr<U>& rhs)
     {
         ReleaseRef();
@@ -130,26 +148,32 @@ public:
         refCount_ = rhs.RefCountPtr();
         AddRef();
     }
-    
+
     /// Check if the pointer is null.
     bool Null() const { return ptr_ == 0; }
+
     /// Check if the pointer is not null.
     bool NotNull() const { return ptr_ != 0; }
+
     /// Return the raw pointer.
     T* Get() const { return ptr_; }
+
     /// Return the array's reference count, or 0 if the pointer is null.
     int Refs() const { return refCount_ ? refCount_->refs_ : 0; }
+
     /// Return the array's weak reference count, or 0 if the pointer is null.
     int WeakRefs() const { return refCount_ ? refCount_->weakRefs_ : 0; }
+
     /// Return pointer to the RefCount structure.
     RefCount* RefCountPtr() const { return refCount_; }
+
     /// Return hash value for HashSet & HashMap.
-    unsigned ToHash() const { return ((unsigned)(size_t)ptr_) / sizeof(T); }
-    
+    unsigned ToHash() const { return (unsigned)((size_t)ptr_ / sizeof(T)); }
+
 private:
     /// Prevent direct assignment from a shared array pointer of different type.
-    template <class U> SharedArrayPtr<T>& operator = (const SharedArrayPtr<U>& rhs);
-    
+    template <class U> SharedArrayPtr<T>& operator =(const SharedArrayPtr<U>& rhs);
+
     /// Add a reference to the array pointed to.
     void AddRef()
     {
@@ -159,7 +183,7 @@ private:
             ++(refCount_->refs_);
         }
     }
-    
+
     /// Release the array reference and delete it and the RefCount structure if necessary.
     void ReleaseRef()
     {
@@ -172,15 +196,15 @@ private:
                 refCount_->refs_ = -1;
                 delete[] ptr_;
             }
-            
+
             if (refCount_->refs_ < 0 && !refCount_->weakRefs_)
                 delete refCount_;
         }
-        
+
         ptr_ = 0;
         refCount_ = 0;
     }
-    
+
     /// Pointer to the array.
     T* ptr_;
     /// Pointer to the RefCount structure.
@@ -213,7 +237,7 @@ public:
         refCount_(0)
     {
     }
-    
+
     /// Copy-construct from another weak array pointer.
     WeakArrayPtr(const WeakArrayPtr<T>& rhs) :
         ptr_(rhs.ptr_),
@@ -221,7 +245,7 @@ public:
     {
         AddRef();
     }
-    
+
     /// Construct from a shared array pointer.
     WeakArrayPtr(const SharedArrayPtr<T>& rhs) :
         ptr_(rhs.Get()),
@@ -229,41 +253,41 @@ public:
     {
         AddRef();
     }
-    
+
     /// Destruct. Release the weak reference to the array.
     ~WeakArrayPtr()
     {
         ReleaseRef();
     }
-    
+
     /// Assign from a shared array pointer.
-    WeakArrayPtr<T>& operator = (const SharedArrayPtr<T>& rhs)
+    WeakArrayPtr<T>& operator =(const SharedArrayPtr<T>& rhs)
     {
         if (ptr_ == rhs.Get() && refCount_ == rhs.RefCountPtr())
             return *this;
-        
+
         ReleaseRef();
         ptr_ = rhs.Get();
         refCount_ = rhs.RefCountPtr();
         AddRef();
-        
+
         return *this;
     }
-    
+
     /// Assign from another weak array pointer.
-    WeakArrayPtr<T>& operator = (const WeakArrayPtr<T>& rhs)
+    WeakArrayPtr<T>& operator =(const WeakArrayPtr<T>& rhs)
     {
         if (ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_)
             return *this;
-        
+
         ReleaseRef();
         ptr_ = rhs.ptr_;
         refCount_ = rhs.refCount_;
         AddRef();
-        
+
         return *this;
     }
-    
+
     /// Convert to shared array pointer. If expired, return a null shared array pointer.
     SharedArrayPtr<T> Lock() const
     {
@@ -272,7 +296,7 @@ public:
         else
             return SharedArrayPtr<T>(ptr_, refCount_);
     }
-    
+
     /// Return raw pointer. If expired, return null.
     T* Get() const
     {
@@ -281,43 +305,46 @@ public:
         else
             return ptr_;
     }
-    
+
     /// Point to the array.
-    T* operator -> () const
+    T* operator ->() const
     {
         T* rawPtr = Get();
         assert(rawPtr);
         return rawPtr;
     }
-    
+
     /// Dereference the array.
-    T& operator * () const
+    T& operator *() const
     {
         T* rawPtr = Get();
         assert(rawPtr);
         return *rawPtr;
     }
-    
+
     /// Subscript the array.
-    T& operator [] (const int index)
+    T& operator [](const int index)
     {
         T* rawPtr = Get();
         assert(rawPtr);
         return (*rawPtr)[index];
     }
-    
+
     /// Test for equality with another weak array pointer.
-    bool operator == (const WeakArrayPtr<T>& rhs) const { return ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_; }
+    bool operator ==(const WeakArrayPtr<T>& rhs) const { return ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_; }
+
     /// Test for inequality with another weak array pointer.
-    bool operator != (const WeakArrayPtr<T>& rhs) const { return ptr_ != rhs.ptr_ || refCount_ != rhs.refCount_; }
+    bool operator !=(const WeakArrayPtr<T>& rhs) const { return ptr_ != rhs.ptr_ || refCount_ != rhs.refCount_; }
+
     /// Test for less than with another weak array pointer.
-    bool operator < (const WeakArrayPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+    bool operator <(const WeakArrayPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+
     /// Convert to a raw pointer, null if array is expired.
-    operator T* () const { return Get(); }
-    
+    operator T*() const { return Get(); }
+
     /// Reset to null and release the weak reference.
     void Reset() { ReleaseRef(); }
-    
+
     /// Perform a static cast from a weak array pointer of another type.
     template <class U> void StaticCast(const WeakArrayPtr<U>& rhs)
     {
@@ -326,13 +353,13 @@ public:
         refCount_ = rhs.refCount_;
         AddRef();
     }
-    
+
     /// Perform a dynamic cast from a weak array pointer of another type.
     template <class U> void DynamicCast(const WeakArrayPtr<U>& rhs)
     {
         ReleaseRef();
         ptr_ = dynamic_cast<T*>(rhs.Get());
-        
+
         if (ptr_)
         {
             refCount_ = rhs.refCount_;
@@ -341,26 +368,32 @@ public:
         else
             refCount_ = 0;
     }
-    
+
     /// Check if the pointer is null.
     bool Null() const { return refCount_ == 0; }
+
     /// Check if the pointer is not null.
     bool NotNull() const { return refCount_ != 0; }
+
     /// Return the array's reference count, or 0 if null pointer or if array has expired.
     int Refs() const { return (refCount_ && refCount_->refs_ >= 0) ? refCount_->refs_ : 0; }
+
     /// Return the array's weak reference count.
     int WeakRefs() const { return refCount_ ? refCount_->weakRefs_ : 0; }
+
     /// Return whether the array has expired. If null pointer, always return true.
     bool Expired() const { return refCount_ ? refCount_->refs_ < 0 : true; }
+
     /// Return pointer to RefCount structure.
     RefCount* RefCountPtr() const { return refCount_; }
+
     /// Return hash value for HashSet & HashMap.
-    unsigned ToHash() const { return ((unsigned)(size_t)ptr_) / sizeof(T); }
-    
+    unsigned ToHash() const { return (unsigned)((size_t)ptr_ / sizeof(T)); }
+
 private:
     /// Prevent direct assignment from a weak array pointer of different type.
-    template <class U> WeakArrayPtr<T>& operator = (const WeakArrayPtr<U>& rhs);
-    
+    template <class U> WeakArrayPtr<T>& operator =(const WeakArrayPtr<U>& rhs);
+
     /// Add a weak reference to the array pointed to.
     void AddRef()
     {
@@ -370,25 +403,25 @@ private:
             ++(refCount_->weakRefs_);
         }
     }
-    
+
     /// Release the weak reference. Delete the Refcount structure if necessary.
     void ReleaseRef()
     {
         if (refCount_)
         {
             assert(refCount_->weakRefs_ >= 0);
-            
+
             if (refCount_->weakRefs_ > 0)
                 --(refCount_->weakRefs_);
-            
+
             if (Expired() && !refCount_->weakRefs_)
                 delete refCount_;
         }
-        
+
         ptr_ = 0;
         refCount_ = 0;
     }
-    
+
     /// Pointer to the array.
     T* ptr_;
     /// Pointer to the RefCount structure.

+ 17 - 17
Source/Urho3D/Container/Hash.h

@@ -30,13 +30,13 @@ namespace Urho3D
 /// Pointer hash function.
 template <class T> unsigned MakeHash(T* value)
 {
-    return ((unsigned)(size_t)value) / sizeof(T);
+    return (unsigned)((size_t)value / sizeof(T));
 }
 
 /// Const pointer hash function.
 template <class T> unsigned MakeHash(const T* value)
 {
-    return ((unsigned)(size_t)value) / sizeof(T);
+    return (unsigned)((size_t)value / sizeof(T));
 }
 
 /// Generic hash function.
@@ -46,61 +46,61 @@ template <class T> unsigned MakeHash(const T& value)
 }
 
 /// Void pointer hash function.
-template<> inline unsigned MakeHash(void* value)
+template <> inline unsigned MakeHash(void* value)
 {
     return (unsigned)(size_t)value;
 }
 
 /// Const void pointer hash function.
-template<> inline unsigned MakeHash(const void* value)
+template <> inline unsigned MakeHash(const void* value)
 {
     return (unsigned)(size_t)value;
 }
 
 /// Long long hash function.
-template<> inline unsigned MakeHash(const long long& value)
+template <> inline unsigned MakeHash(const long long& value)
 {
-    return (value >> 32) | (value & 0xffffffff);
+    return (unsigned)((value >> 32) | (value & 0xffffffff));
 }
 
 /// Unsigned long long hash function.
-template<> inline unsigned MakeHash(const unsigned long long& value)
+template <> inline unsigned MakeHash(const unsigned long long& value)
 {
-    return (value >> 32) | (value & 0xffffffff);
+    return (unsigned)((value >> 32) | (value & 0xffffffff));
 }
 
 /// Int hash function.
-template<> inline unsigned MakeHash(const int& value)
+template <> inline unsigned MakeHash(const int& value)
 {
-    return value;
+    return (unsigned)value;
 }
 
 /// Unsigned hash function.
-template<> inline unsigned MakeHash(const unsigned& value)
+template <> inline unsigned MakeHash(const unsigned& value)
 {
     return value;
 }
 
 /// Short hash function.
-template<> inline unsigned MakeHash(const short& value)
+template <> inline unsigned MakeHash(const short& value)
 {
-    return value;
+    return (unsigned)value;
 }
 
 /// Unsigned short hash function.
-template<> inline unsigned MakeHash(const unsigned short& value)
+template <> inline unsigned MakeHash(const unsigned short& value)
 {
     return value;
 }
 
 /// Char hash function.
-template<> inline unsigned MakeHash(const char& value)
+template <> inline unsigned MakeHash(const char& value)
 {
-    return value;
+    return (unsigned)value;
 }
 
 /// Unsigned char hash function.
-template<> inline unsigned MakeHash(const unsigned char& value)
+template <> inline unsigned MakeHash(const unsigned char& value)
 {
     return value;
 }

+ 5 - 5
Source/Urho3D/Container/HashBase.cpp

@@ -20,7 +20,7 @@
 // THE SOFTWARE.
 //
 
-#include "../Container/HashBase.h"
+#include "../Precompiled.h"
 
 #include "../DebugNew.h"
 
@@ -31,13 +31,13 @@ void HashBase::AllocateBuckets(unsigned size, unsigned numBuckets)
 {
     if (ptrs_)
         delete[] ptrs_;
-    
-    HashNodeBase** ptrs = new HashNodeBase*[numBuckets + 2];
+
+    HashNodeBase** ptrs = new HashNodeBase* [numBuckets + 2];
     unsigned* data = reinterpret_cast<unsigned*>(ptrs);
     data[0] = size;
     data[1] = numBuckets;
     ptrs_ = ptrs;
-    
+
     ResetPtrs();
 }
 
@@ -46,7 +46,7 @@ void HashBase::ResetPtrs()
     // Reset bucket pointers
     if (!ptrs_)
         return;
-    
+
     unsigned numBuckets = NumBuckets();
     HashNodeBase** ptrs = Ptrs();
     for (unsigned i = 0; i < numBuckets; ++i)

+ 24 - 12
Source/Urho3D/Container/HashBase.h

@@ -22,6 +22,12 @@
 
 #pragma once
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 #include "../Container/Allocator.h"
 #include "../Container/Hash.h"
 #include "../Container/Swap.h"
@@ -39,7 +45,7 @@ struct HashNodeBase
         next_(0)
     {
     }
-    
+
     /// Next node in the bucket.
     HashNodeBase* down_;
     /// Previous node.
@@ -56,32 +62,33 @@ struct HashIteratorBase
         ptr_(0)
     {
     }
-    
+
     /// Construct with a node pointer.
     explicit HashIteratorBase(HashNodeBase* ptr) :
         ptr_(ptr)
     {
     }
-    
+
     /// Test for equality with another iterator.
-    bool operator == (const HashIteratorBase& rhs) const { return ptr_ == rhs.ptr_; }
+    bool operator ==(const HashIteratorBase& rhs) const { return ptr_ == rhs.ptr_; }
+
     /// Test for inequality with another iterator.
-    bool operator != (const HashIteratorBase& rhs) const { return ptr_ != rhs.ptr_; }
-    
+    bool operator !=(const HashIteratorBase& rhs) const { return ptr_ != rhs.ptr_; }
+
     /// Go to the next node.
     void GotoNext()
     {
         if (ptr_)
             ptr_ = ptr_->next_;
     }
-    
+
     /// Go to the previous node.
     void GotoPrev()
     {
         if (ptr_)
             ptr_ = ptr_->prev_;
     }
-    
+
     /// Node pointer.
     HashNodeBase* ptr_;
 };
@@ -97,7 +104,7 @@ public:
     static const unsigned MIN_BUCKETS = 8;
     /// Maximum load factor.
     static const unsigned MAX_LOAD_FACTOR = 4;
-    
+
     /// Construct.
     HashBase() :
         ptrs_(0),
@@ -113,24 +120,29 @@ public:
         Urho3D::Swap(ptrs_, rhs.ptrs_);
         Urho3D::Swap(allocator_, rhs.allocator_);
     }
-    
+
     /// Return number of elements.
     unsigned Size() const { return ptrs_ ? (reinterpret_cast<unsigned*>(ptrs_))[0] : 0; }
+
     /// Return number of buckets.
     unsigned NumBuckets() const { return ptrs_ ? (reinterpret_cast<unsigned*>(ptrs_))[1] : 0; }
+
     /// Return whether has no elements.
     bool Empty() const { return Size() == 0; }
-    
+
 protected:
     /// Allocate bucket head pointers + room for size and bucket count variables.
     void AllocateBuckets(unsigned size, unsigned numBuckets);
+
     /// Reset bucket head pointers.
     void ResetPtrs();
+
     /// Set new size.
     void SetSize(unsigned size) { if (ptrs_) (reinterpret_cast<unsigned*>(ptrs_))[0] = size; }
+
     /// Return bucket head pointers.
     HashNodeBase** Ptrs() const { return ptrs_ ? ptrs_ + 2 : 0; }
-    
+
     /// List head node pointer.
     HashNodeBase* head_;
     /// List tail node pointer.

+ 202 - 129
Source/Urho3D/Container/HashMap.h

@@ -38,7 +38,7 @@ template <class T, class U> class HashMap : public HashBase
 public:
     typedef T KeyType;
     typedef U ValueType;
-    
+
     /// Hash map key-value pair with const key.
     class KeyValue
     {
@@ -48,36 +48,37 @@ public:
             first_(T())
         {
         }
-        
+
         /// Construct with key and value.
         KeyValue(const T& first, const U& second) :
             first_(first),
             second_(second)
         {
         }
-        
+
         /// Copy-construct.
         KeyValue(const KeyValue& value) :
             first_(value.first_),
             second_(value.second_)
         {
         }
-        
+
         /// Test for equality with another pair.
-        bool operator == (const KeyValue& rhs) const { return first_ == rhs.first_ && second_ == rhs.second_; }
+        bool operator ==(const KeyValue& rhs) const { return first_ == rhs.first_ && second_ == rhs.second_; }
+
         /// Test for inequality with another pair.
-        bool operator != (const KeyValue& rhs) const { return first_ != rhs.first_ || second_ != rhs.second_; }
-        
+        bool operator !=(const KeyValue& rhs) const { return first_ != rhs.first_ || second_ != rhs.second_; }
+
         /// Key.
         const T first_;
         /// Value.
         U second_;
-        
+
     private:
         /// Prevent assignment.
-        KeyValue& operator = (const KeyValue& rhs);
+        KeyValue& operator =(const KeyValue& rhs);
     };
-    
+
     /// Hash map node.
     struct Node : public HashNodeBase
     {
@@ -85,24 +86,26 @@ public:
         Node()
         {
         }
-        
+
         /// Construct with key and value.
         Node(const T& key, const U& value) :
             pair_(key, value)
         {
         }
-        
+
         /// Key-value pair.
         KeyValue pair_;
-        
+
         /// Return next node.
         Node* Next() const { return static_cast<Node*>(next_); }
+
         /// Return previous node.
         Node* Prev() const { return static_cast<Node*>(prev_); }
+
         /// Return next node in the bucket.
         Node* Down() const { return static_cast<Node*>(down_); }
     };
-    
+
     /// Hash map node iterator.
     struct Iterator : public HashIteratorBase
     {
@@ -110,28 +113,50 @@ public:
         Iterator()
         {
         }
-        
+
         /// Construct with a node pointer.
         Iterator(Node* ptr) :
             HashIteratorBase(ptr)
         {
         }
-        
+
         /// Preincrement the pointer.
-        Iterator& operator ++ () { GotoNext(); return *this; }
+        Iterator& operator ++()
+        {
+            GotoNext();
+            return *this;
+        }
+
         /// Postincrement the pointer.
-        Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
+        Iterator operator ++(int)
+        {
+            Iterator it = *this;
+            GotoNext();
+            return it;
+        }
+
         /// Predecrement the pointer.
-        Iterator& operator -- () { GotoPrev(); return *this; }
+        Iterator& operator --()
+        {
+            GotoPrev();
+            return *this;
+        }
+
         /// Postdecrement the pointer.
-        Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
-        
+        Iterator operator --(int)
+        {
+            Iterator it = *this;
+            GotoPrev();
+            return it;
+        }
+
         /// Point to the pair.
-        KeyValue* operator -> () const { return &(static_cast<Node*>(ptr_))->pair_; }
+        KeyValue* operator ->() const { return &(static_cast<Node*>(ptr_))->pair_; }
+
         /// Dereference the pair.
-        KeyValue& operator * () const { return (static_cast<Node*>(ptr_))->pair_; }
+        KeyValue& operator *() const { return (static_cast<Node*>(ptr_))->pair_; }
     };
-    
+
     /// Hash map node const iterator.
     struct ConstIterator : public HashIteratorBase
     {
@@ -139,53 +164,80 @@ public:
         ConstIterator()
         {
         }
-        
+
         /// Construct with a node pointer.
         ConstIterator(Node* ptr) :
             HashIteratorBase(ptr)
         {
         }
-        
+
         /// Construct from a non-const iterator.
         ConstIterator(const Iterator& rhs) :
             HashIteratorBase(rhs.ptr_)
         {
         }
-        
+
         /// Assign from a non-const iterator.
-        ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
+        ConstIterator& operator =(const Iterator& rhs)
+        {
+            ptr_ = rhs.ptr_;
+            return *this;
+        }
+
         /// Preincrement the pointer.
-        ConstIterator& operator ++ () { GotoNext(); return *this; }
+        ConstIterator& operator ++()
+        {
+            GotoNext();
+            return *this;
+        }
+
         /// Postincrement the pointer.
-        ConstIterator operator ++ (int) { ConstIterator it = *this; GotoNext(); return it; }
+        ConstIterator operator ++(int)
+        {
+            ConstIterator it = *this;
+            GotoNext();
+            return it;
+        }
+
         /// Predecrement the pointer.
-        ConstIterator& operator -- () { GotoPrev(); return *this; }
+        ConstIterator& operator --()
+        {
+            GotoPrev();
+            return *this;
+        }
+
         /// Postdecrement the pointer.
-        ConstIterator operator -- (int) { ConstIterator it = *this; GotoPrev(); return it; }
-        
+        ConstIterator operator --(int)
+        {
+            ConstIterator it = *this;
+            GotoPrev();
+            return it;
+        }
+
         /// Point to the pair.
-        const KeyValue* operator -> () const { return &(static_cast<Node*>(ptr_))->pair_; }
+        const KeyValue* operator ->() const { return &(static_cast<Node*>(ptr_))->pair_; }
+
         /// Dereference the pair.
-        const KeyValue& operator * () const { return (static_cast<Node*>(ptr_))->pair_; }
+        const KeyValue& operator *() const { return (static_cast<Node*>(ptr_))->pair_; }
     };
-    
+
     /// Construct empty.
     HashMap()
     {
         // Reserve the tail node
-        allocator_ = AllocatorInitialize(sizeof(Node));
+        allocator_ = AllocatorInitialize((unsigned)sizeof(Node));
         head_ = tail_ = ReserveNode();
     }
-    
+
     /// Construct from another hash map.
     HashMap(const HashMap<T, U>& map)
     {
         // Reserve the tail node + initial capacity according to the map's size
-        allocator_ = AllocatorInitialize(sizeof(Node), map.Size() + 1);
+        allocator_ = AllocatorInitialize((unsigned)sizeof(Node), map.Size() + 1);
         head_ = tail_ = ReserveNode();
         *this = map;
     }
-    
+
     /// Destruct.
     ~HashMap()
     {
@@ -194,35 +246,35 @@ public:
         AllocatorUninitialize(allocator_);
         delete[] ptrs_;
     }
-    
+
     /// Assign a hash map.
-    HashMap& operator = (const HashMap<T, U>& rhs)
+    HashMap& operator =(const HashMap<T, U>& rhs)
     {
         Clear();
         Insert(rhs);
         return *this;
     }
-    
+
     /// Add-assign a pair.
-    HashMap& operator += (const Pair<T, U>& rhs)
+    HashMap& operator +=(const Pair<T, U>& rhs)
     {
         Insert(rhs);
         return *this;
     }
-    
+
     /// Add-assign a hash map.
-    HashMap& operator += (const HashMap<T, U>& rhs)
+    HashMap& operator +=(const HashMap<T, U>& rhs)
     {
         Insert(rhs);
         return *this;
     }
-    
+
     /// Test for equality with another hash map.
-    bool operator == (const HashMap<T, U>& rhs) const
+    bool operator ==(const HashMap<T, U>& rhs) const
     {
         if (rhs.Size() != Size())
             return false;
-        
+
         ConstIterator i = Begin();
         while (i != End())
         {
@@ -231,16 +283,16 @@ public:
                 return false;
             ++i;
         }
-        
+
         return true;
     }
-    
+
     /// Test for inequality with another hash map.
-    bool operator != (const HashMap<T, U>& rhs) const
+    bool operator !=(const HashMap<T, U>& rhs) const
     {
         if (rhs.Size() != Size())
             return true;
-        
+
         ConstIterator i = Begin();
         while (i != End())
         {
@@ -249,31 +301,40 @@ public:
                 return true;
             ++i;
         }
-        
+
         return false;
     }
-    
+
     /// Index the map. Create a new pair if key not found.
-    U& operator [] (const T& key)
+    U& operator [](const T& key)
     {
         if (!ptrs_)
             return InsertNode(key, U(), false)->pair_.second_;
-        
+
         unsigned hashKey = Hash(key);
-        
+
         Node* node = FindNode(key, hashKey);
-        if (node)
-            return node->pair_.second_;
-        else
-            return InsertNode(key, U(), false)->pair_.second_;
+        return node ? node->pair_.second_ : InsertNode(key, U(), false)->pair_.second_;
+    }
+
+    /// Index the map. Return null if key is not found, does not create a new pair.
+    U* operator [](const T& key) const
+    {
+        if (!ptrs_)
+            return 0;
+
+        unsigned hashKey = Hash(key);
+
+        Node* node = FindNode(key, hashKey);
+        return node ? &node->pair_.second_ : 0;
     }
-    
+
     /// Insert a pair. Return an iterator to it.
     Iterator Insert(const Pair<T, U>& pair)
     {
         return Iterator(InsertNode(pair.first_, pair.second_));
     }
-    
+
     /// Insert a map.
     void Insert(const HashMap<T, U>& map)
     {
@@ -285,10 +346,10 @@ public:
             ++it;
         }
     }
-    
+
     /// Insert a pair by iterator. Return iterator to the value.
     Iterator Insert(const ConstIterator& it) { return Iterator(InsertNode(it->first_, it->second_)); }
-    
+
     /// Insert a range by iterators.
     void Insert(const ConstIterator& start, const ConstIterator& end)
     {
@@ -296,40 +357,40 @@ public:
         while (it != end)
             InsertNode(*it++);
     }
-    
+
     /// Erase a pair by key. Return true if was found.
     bool Erase(const T& key)
     {
         if (!ptrs_)
             return false;
-        
+
         unsigned hashKey = Hash(key);
-        
+
         Node* previous;
         Node* node = FindNode(key, hashKey, previous);
         if (!node)
             return false;
-        
+
         if (previous)
             previous->down_ = node->down_;
         else
             Ptrs()[hashKey] = node->down_;
-        
+
         EraseNode(node);
         return true;
     }
-    
+
     /// Erase a pair by iterator. Return iterator to the next pair.
     Iterator Erase(const Iterator& it)
     {
         if (!ptrs_ || !it.ptr_)
             return End();
-        
+
         Node* node = static_cast<Node*>(it.ptr_);
         Node* next = node->Next();
-        
+
         unsigned hashKey = Hash(node->pair_.first_);
-        
+
         Node* previous = 0;
         Node* current = static_cast<Node*>(Ptrs()[hashKey]);
         while (current && current != node)
@@ -337,54 +398,54 @@ public:
             previous = current;
             current = current->Down();
         }
-        
+
         assert(current == node);
-        
+
         if (previous)
             previous->down_ = node->down_;
         else
             Ptrs()[hashKey] = node->down_;
-        
+
         EraseNode(node);
         return Iterator(next);
     }
-    
+
     /// Clear the map.
     void Clear()
     {
         if (Size())
         {
-            for (Iterator i = Begin(); i != End(); )
+            for (Iterator i = Begin(); i != End();)
             {
                 FreeNode(static_cast<Node*>(i++.ptr_));
                 i.ptr_->prev_ = 0;
             }
-            
+
             head_ = tail_;
             SetSize(0);
         }
-        
+
         ResetPtrs();
     }
-    
+
     /// Sort pairs. After sorting the map can be iterated in order until new elements are inserted.
     void Sort()
     {
         unsigned numKeys = Size();
         if (!numKeys)
             return;
-        
-        Node** ptrs = new Node*[numKeys];
+
+        Node** ptrs = new Node* [numKeys];
         Node* ptr = Head();
-        
+
         for (unsigned i = 0; i < numKeys; ++i)
         {
             ptrs[i] = ptr;
             ptr = ptr->Next();
         }
-        
+
         Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
-        
+
         head_ = ptrs[0];
         ptrs[0]->prev_ = 0;
         for (unsigned i = 1; i < numKeys; ++i)
@@ -394,10 +455,10 @@ public:
         }
         ptrs[numKeys - 1]->next_ = tail_;
         tail_->prev_ = ptrs[numKeys - 1];
-        
+
         delete[] ptrs;
     }
-    
+
     /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
     bool Rehash(unsigned numBuckets)
     {
@@ -405,25 +466,25 @@ public:
             return true;
         if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
             return false;
-        
+
         // Check for being power of two
         unsigned check = numBuckets;
         while (!(check & 1))
             check >>= 1;
         if (check != 1)
             return false;
-        
+
         AllocateBuckets(Size(), numBuckets);
         Rehash();
         return true;
     }
-    
+
     /// Return iterator to the pair with key, or end iterator if not found.
     Iterator Find(const T& key)
     {
         if (!ptrs_)
             return End();
-        
+
         unsigned hashKey = Hash(key);
         Node* node = FindNode(key, hashKey);
         if (node)
@@ -431,13 +492,13 @@ public:
         else
             return End();
     }
-    
+
     /// Return const iterator to the pair with key, or end iterator if not found.
     ConstIterator Find(const T& key) const
     {
         if (!ptrs_)
             return End();
-        
+
         unsigned hashKey = Hash(key);
         Node* node = FindNode(key, hashKey);
         if (node)
@@ -445,17 +506,17 @@ public:
         else
             return End();
     }
-    
+
     /// Return whether contains a pair with key.
     bool Contains(const T& key) const
     {
         if (!ptrs_)
             return false;
-        
+
         unsigned hashKey = Hash(key);
         return FindNode(key, hashKey) != 0;
     }
-    
+
     /// Return all the keys.
     Vector<T> Keys() const
     {
@@ -475,26 +536,32 @@ public:
             result.Push(i->second_);
         return result;
     }
-    
+
     /// Return iterator to the beginning.
     Iterator Begin() { return Iterator(Head()); }
+
     /// Return iterator to the beginning.
     ConstIterator Begin() const { return ConstIterator(Head()); }
+
     /// Return iterator to the end.
     Iterator End() { return Iterator(Tail()); }
+
     /// Return iterator to the end.
     ConstIterator End() const { return ConstIterator(Tail()); }
+
     /// Return first key.
     const T& Front() const { return *Begin(); }
+
     /// Return last key.
     const T& Back() const { return *(--End()); }
-    
+
 private:
     /// Return the head node.
     Node* Head() const { return static_cast<Node*>(head_); }
+
     /// Return the tail node.
     Node* Tail() const { return static_cast<Node*>(tail_); }
-    
+
     /// Find a node from the buckets. Do not call if the buckets have not been allocated.
     Node* FindNode(const T& key, unsigned hashKey) const
     {
@@ -505,15 +572,15 @@ private:
                 return node;
             node = node->Down();
         }
-        
+
         return 0;
     }
-    
+
     /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
     Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
     {
         previous = 0;
-        
+
         Node* node = static_cast<Node*>(Ptrs()[hashKey]);
         while (node)
         {
@@ -522,10 +589,10 @@ private:
             previous = node;
             node = node->Down();
         }
-        
+
         return 0;
     }
-    
+
     /// Insert a key and value and return either the new or existing node.
     Node* InsertNode(const T& key, const U& value, bool findExisting = true)
     {
@@ -535,9 +602,9 @@ private:
             AllocateBuckets(Size(), MIN_BUCKETS);
             Rehash();
         }
-        
+
         unsigned hashKey = Hash(key);
-        
+
         if (findExisting)
         {
             // If exists, just change the value
@@ -548,27 +615,27 @@ private:
                 return existing;
             }
         }
-        
+
         Node* newNode = InsertNode(Tail(), key, value);
         newNode->down_ = Ptrs()[hashKey];
         Ptrs()[hashKey] = newNode;
-        
+
         // Rehash if the maximum load factor has been exceeded
         if (Size() > NumBuckets() * MAX_LOAD_FACTOR)
         {
             AllocateBuckets(Size(), NumBuckets() << 1);
             Rehash();
         }
-        
+
         return newNode;
     }
-    
+
     /// Insert a node into the list. Return the new node.
     Node* InsertNode(Node* dest, const T& key, const U& value)
     {
         if (!dest)
             return 0;
-        
+
         Node* newNode = ReserveNode(key, value);
         Node* prev = dest->Prev();
         newNode->next_ = dest;
@@ -576,39 +643,39 @@ private:
         if (prev)
             prev->next_ = newNode;
         dest->prev_ = newNode;
-        
+
         // Reassign the head node if necessary
         if (dest == Head())
             head_ = newNode;
-        
+
         SetSize(Size() + 1);
-        
+
         return newNode;
     }
-    
+
     /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
     Node* EraseNode(Node* node)
     {
         // The tail node can not be removed
         if (!node || node == tail_)
             return Tail();
-        
+
         Node* prev = node->Prev();
         Node* next = node->Next();
         if (prev)
             prev->next_ = next;
         next->prev_ = prev;
-        
+
         // Reassign the head node if necessary
         if (node == Head())
             head_ = next;
-        
+
         FreeNode(node);
         SetSize(Size() - 1);
-        
+
         return next;
     }
-    
+
     /// Reserve a node.
     Node* ReserveNode()
     {
@@ -616,7 +683,7 @@ private:
         new(newNode) Node();
         return newNode;
     }
-    
+
     /// Reserve a node with specified key and value.
     Node* ReserveNode(const T& key, const U& value)
     {
@@ -624,14 +691,14 @@ private:
         new(newNode) Node(key, value);
         return newNode;
     }
-    
+
     /// Free a node.
     void FreeNode(Node* node)
     {
         (node)->~Node();
         AllocatorFree(allocator_, node);
     }
-    
+
     /// Rehash the buckets.
     void Rehash()
     {
@@ -643,10 +710,10 @@ private:
             Ptrs()[hashKey] = node;
         }
     }
-    
+
     /// Compare two nodes.
     static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->pair_.first_ < rhs->pair_.first_; }
-    
+
     /// Compute a hash based on the key and the bucket size
     unsigned Hash(const T& key) const { return MakeHash(key) & (NumBuckets() - 1); }
 };
@@ -656,9 +723,15 @@ private:
 namespace std
 {
 
-template <class T, class U> typename Urho3D::HashMap<T, U>::ConstIterator begin(const Urho3D::HashMap<T, U>& v) { return v.Begin(); }
+template <class T, class U> typename Urho3D::HashMap<T, U>::ConstIterator begin(const Urho3D::HashMap<T, U>& v)
+{
+    return v.Begin();
+}
+
 template <class T, class U> typename Urho3D::HashMap<T, U>::ConstIterator end(const Urho3D::HashMap<T, U>& v) { return v.End(); }
+
 template <class T, class U> typename Urho3D::HashMap<T, U>::Iterator begin(Urho3D::HashMap<T, U>& v) { return v.Begin(); }
+
 template <class T, class U> typename Urho3D::HashMap<T, U>::Iterator end(Urho3D::HashMap<T, U>& v) { return v.End(); }
 
 }

+ 166 - 106
Source/Urho3D/Container/HashSet.h

@@ -41,24 +41,26 @@ public:
         Node()
         {
         }
-        
+
         /// Construct with key.
         Node(const T& key) :
             key_(key)
         {
         }
-        
+
         /// Key.
         T key_;
-        
+
         /// Return next node.
         Node* Next() const { return static_cast<Node*>(next_); }
+
         /// Return previous node.
         Node* Prev() const { return static_cast<Node*>(prev_); }
+
         /// Return next node in the bucket.
         Node* Down() const { return static_cast<Node*>(down_); }
     };
-    
+
     /// Hash set node iterator.
     struct Iterator : public HashIteratorBase
     {
@@ -66,28 +68,50 @@ public:
         Iterator()
         {
         }
-        
+
         /// Construct with a node pointer.
         Iterator(Node* ptr) :
             HashIteratorBase(ptr)
         {
         }
-        
+
         /// Preincrement the pointer.
-        Iterator& operator ++ () { GotoNext(); return *this; }
+        Iterator& operator ++()
+        {
+            GotoNext();
+            return *this;
+        }
+
         /// Postincrement the pointer.
-        Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
+        Iterator operator ++(int)
+        {
+            Iterator it = *this;
+            GotoNext();
+            return it;
+        }
+
         /// Predecrement the pointer.
-        Iterator& operator -- () { GotoPrev(); return *this; }
+        Iterator& operator --()
+        {
+            GotoPrev();
+            return *this;
+        }
+
         /// Postdecrement the pointer.
-        Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
-        
+        Iterator operator --(int)
+        {
+            Iterator it = *this;
+            GotoPrev();
+            return it;
+        }
+
         /// Point to the key.
-        const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
+        const T* operator ->() const { return &(static_cast<Node*>(ptr_))->key_; }
+
         /// Dereference the key.
-        const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
+        const T& operator *() const { return (static_cast<Node*>(ptr_))->key_; }
     };
-    
+
     /// Hash set node const iterator.
     struct ConstIterator : public HashIteratorBase
     {
@@ -95,53 +119,80 @@ public:
         ConstIterator()
         {
         }
-        
+
         /// Construct with a node pointer.
         ConstIterator(Node* ptr) :
             HashIteratorBase(ptr)
         {
         }
-        
+
         /// Construct from a non-const iterator.
         ConstIterator(const Iterator& rhs) :
             HashIteratorBase(rhs.ptr_)
         {
         }
-        
+
         /// Assign from a non-const iterator.
-        ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
+        ConstIterator& operator =(const Iterator& rhs)
+        {
+            ptr_ = rhs.ptr_;
+            return *this;
+        }
+
         /// Preincrement the pointer.
-        ConstIterator& operator ++ () { GotoNext(); return *this; }
+        ConstIterator& operator ++()
+        {
+            GotoNext();
+            return *this;
+        }
+
         /// Postincrement the pointer.
-        ConstIterator operator ++ (int) { ConstIterator it = *this; GotoNext(); return it; }
+        ConstIterator operator ++(int)
+        {
+            ConstIterator it = *this;
+            GotoNext();
+            return it;
+        }
+
         /// Predecrement the pointer.
-        ConstIterator& operator -- () { GotoPrev(); return *this; }
+        ConstIterator& operator --()
+        {
+            GotoPrev();
+            return *this;
+        }
+
         /// Postdecrement the pointer.
-        ConstIterator operator -- (int) { ConstIterator it = *this; GotoPrev(); return it; }
-        
+        ConstIterator operator --(int)
+        {
+            ConstIterator it = *this;
+            GotoPrev();
+            return it;
+        }
+
         /// Point to the key.
-        const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
+        const T* operator ->() const { return &(static_cast<Node*>(ptr_))->key_; }
+
         /// Dereference the key.
-        const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
+        const T& operator *() const { return (static_cast<Node*>(ptr_))->key_; }
     };
-    
+
     /// Construct empty.
     HashSet()
     {
         // Reserve the tail node
-        allocator_ = AllocatorInitialize(sizeof(Node));
+        allocator_ = AllocatorInitialize((unsigned)sizeof(Node));
         head_ = tail_ = ReserveNode();
     }
-    
+
     /// Construct from another hash set.
     HashSet(const HashSet<T>& set)
     {
         // Reserve the tail node + initial capacity according to the set's size
-        allocator_ = AllocatorInitialize(sizeof(Node), set.Size() + 1);
+        allocator_ = AllocatorInitialize((unsigned)sizeof(Node), set.Size() + 1);
         head_ = tail_ = ReserveNode();
         *this = set;
     }
-    
+
     /// Destruct.
     ~HashSet()
     {
@@ -150,35 +201,35 @@ public:
         AllocatorUninitialize(allocator_);
         delete[] ptrs_;
     }
-    
+
     /// Assign a hash set.
-    HashSet& operator = (const HashSet<T>& rhs)
+    HashSet& operator =(const HashSet<T>& rhs)
     {
         Clear();
         Insert(rhs);
         return *this;
     }
-    
+
     /// Add-assign a value.
-    HashSet& operator += (const T& rhs)
+    HashSet& operator +=(const T& rhs)
     {
         Insert(rhs);
         return *this;
     }
-    
+
     /// Add-assign a hash set.
-    HashSet& operator += (const HashSet<T>& rhs)
+    HashSet& operator +=(const HashSet<T>& rhs)
     {
         Insert(rhs);
         return *this;
     }
-    
+
     /// Test for equality with another hash set.
-    bool operator == (const HashSet<T>& rhs) const
+    bool operator ==(const HashSet<T>& rhs) const
     {
         if (rhs.Size() != Size())
             return false;
-        
+
         ConstIterator it = Begin();
         while (it != End())
         {
@@ -186,16 +237,16 @@ public:
                 return false;
             ++it;
         }
-        
+
         return true;
     }
-    
+
     /// Test for inequality with another hash set.
-    bool operator != (const HashSet<T>& rhs) const
+    bool operator !=(const HashSet<T>& rhs) const
     {
         if (rhs.Size() != Size())
             return true;
-        
+
         ConstIterator it = Begin();
         while (it != End())
         {
@@ -203,10 +254,10 @@ public:
                 return true;
             ++it;
         }
-        
+
         return false;
     }
-    
+
     /// Insert a key. Return an iterator to it.
     Iterator Insert(const T& key)
     {
@@ -216,27 +267,27 @@ public:
             AllocateBuckets(Size(), MIN_BUCKETS);
             Rehash();
         }
-        
+
         unsigned hashKey = Hash(key);
-        
+
         Node* existing = FindNode(key, hashKey);
         if (existing)
             return Iterator(existing);
-        
+
         Node* newNode = InsertNode(Tail(), key);
         newNode->down_ = Ptrs()[hashKey];
         Ptrs()[hashKey] = newNode;
-        
+
         // Rehash if the maximum load factor has been exceeded
         if (Size() > NumBuckets() * MAX_LOAD_FACTOR)
         {
             AllocateBuckets(Size(), NumBuckets() << 1);
             Rehash();
         }
-        
+
         return Iterator(newNode);
     }
-    
+
     /// Insert a set.
     void Insert(const HashSet<T>& set)
     {
@@ -245,46 +296,46 @@ public:
         while (it != end)
             Insert(*it++);
     }
-    
+
     /// Insert a key by iterator. Return iterator to the value.
     Iterator Insert(const ConstIterator& it)
     {
         return Iterator(InsertNode(*it));
     }
-    
+
     /// Erase a key. Return true if was found.
     bool Erase(const T& key)
     {
         if (!ptrs_)
             return false;
-        
+
         unsigned hashKey = Hash(key);
-        
+
         Node* previous;
         Node* node = FindNode(key, hashKey, previous);
         if (!node)
             return false;
-        
+
         if (previous)
             previous->down_ = node->down_;
         else
             Ptrs()[hashKey] = node->down_;
-        
+
         EraseNode(node);
         return true;
     }
-    
+
     /// Erase a key by iterator. Return iterator to the next key.
     Iterator Erase(const Iterator& it)
     {
         if (!ptrs_ || !it.ptr_)
             return End();
-        
+
         Node* node = static_cast<Node*>(it.ptr_);
         Node* next = node->Next();
-        
+
         unsigned hashKey = Hash(node->key_);
-        
+
         Node* previous = 0;
         Node* current = static_cast<Node*>(Ptrs()[hashKey]);
         while (current && current != node)
@@ -292,54 +343,54 @@ public:
             previous = current;
             current = current->Down();
         }
-        
+
         assert(current == node);
-        
+
         if (previous)
             previous->down_ = node->down_;
         else
             Ptrs()[hashKey] = node->down_;
-        
+
         EraseNode(node);
         return Iterator(next);
     }
-    
+
     /// Clear the set.
     void Clear()
     {
         if (Size())
         {
-            for (Iterator i = Begin(); i != End(); )
+            for (Iterator i = Begin(); i != End();)
             {
                 FreeNode(static_cast<Node*>(i++.ptr_));
                 i.ptr_->prev_ = 0;
             }
-            
+
             head_ = tail_;
             SetSize(0);
         }
-        
+
         ResetPtrs();
     }
-    
+
     /// Sort keys. After sorting the set can be iterated in order until new elements are inserted.
     void Sort()
     {
         unsigned numKeys = Size();
         if (!numKeys)
             return;
-        
-        Node** ptrs = new Node*[numKeys];
+
+        Node** ptrs = new Node* [numKeys];
         Node* ptr = Head();
-        
+
         for (unsigned i = 0; i < numKeys; ++i)
         {
             ptrs[i] = ptr;
             ptr = ptr->Next();
         }
-        
+
         Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
-        
+
         head_ = ptrs[0];
         ptrs[0]->prev_ = 0;
         for (unsigned i = 1; i < numKeys; ++i)
@@ -349,10 +400,10 @@ public:
         }
         ptrs[numKeys - 1]->next_ = tail_;
         tail_->prev_ = ptrs[numKeys - 1];
-        
+
         delete[] ptrs;
     }
-    
+
     /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
     bool Rehash(unsigned numBuckets)
     {
@@ -360,25 +411,25 @@ public:
             return true;
         if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
             return false;
-        
+
         // Check for being power of two
         unsigned check = numBuckets;
         while (!(check & 1))
             check >>= 1;
         if (check != 1)
             return false;
-        
+
         AllocateBuckets(Size(), numBuckets);
         Rehash();
         return true;
     }
-    
+
     /// Return iterator to the key, or end iterator if not found.
     Iterator Find(const T& key)
     {
         if (!ptrs_)
             return End();
-        
+
         unsigned hashKey = Hash(key);
         Node* node = FindNode(key, hashKey);
         if (node)
@@ -386,13 +437,13 @@ public:
         else
             return End();
     }
-    
+
     /// Return const iterator to the key, or end iterator if not found.
     ConstIterator Find(const T& key) const
     {
         if (!ptrs_)
             return End();
-        
+
         unsigned hashKey = Hash(key);
         Node* node = FindNode(key, hashKey);
         if (node)
@@ -400,36 +451,42 @@ public:
         else
             return End();
     }
-    
+
     /// Return whether contains a key.
     bool Contains(const T& key) const
     {
         if (!ptrs_)
             return false;
-        
+
         unsigned hashKey = Hash(key);
         return FindNode(key, hashKey) != 0;
     }
-    
+
     /// Return iterator to the beginning.
     Iterator Begin() { return Iterator(Head()); }
+
     /// Return iterator to the beginning.
     ConstIterator Begin() const { return ConstIterator(Head()); }
+
     /// Return iterator to the end.
     Iterator End() { return Iterator(Tail()); }
+
     /// Return iterator to the end.
     ConstIterator End() const { return ConstIterator(Tail()); }
+
     /// Return first key.
     const T& Front() const { return *Begin(); }
+
     /// Return last key.
     const T& Back() const { return *(--End()); }
-    
+
 private:
     /// Return the head node.
     Node* Head() const { return static_cast<Node*>(head_); }
+
     /// Return the tail node.
     Node* Tail() const { return static_cast<Node*>(tail_); }
-    
+
     /// Find a node from the buckets. Do not call if the buckets have not been allocated.
     Node* FindNode(const T& key, unsigned hashKey) const
     {
@@ -440,15 +497,15 @@ private:
                 return node;
             node = node->Down();
         }
-        
+
         return 0;
     }
-    
+
     /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
     Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
     {
         previous = 0;
-        
+
         Node* node = static_cast<Node*>(Ptrs()[hashKey]);
         while (node)
         {
@@ -457,16 +514,16 @@ private:
             previous = node;
             node = node->Down();
         }
-        
+
         return 0;
     }
-    
+
     /// Insert a node into the list. Return the new node.
     Node* InsertNode(Node* dest, const T& key)
     {
         if (!dest)
             return 0;
-        
+
         Node* newNode = ReserveNode(key);
         Node* prev = dest->Prev();
         newNode->next_ = dest;
@@ -474,39 +531,39 @@ private:
         if (prev)
             prev->next_ = newNode;
         dest->prev_ = newNode;
-        
+
         // Reassign the head node if necessary
         if (dest == Head())
             head_ = newNode;
-        
+
         SetSize(Size() + 1);
-        
+
         return newNode;
     }
-    
+
     /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
     Node* EraseNode(Node* node)
     {
         // The tail node can not be removed
         if (!node || node == tail_)
             return Tail();
-        
+
         Node* prev = node->Prev();
         Node* next = node->Next();
         if (prev)
             prev->next_ = next;
         next->prev_ = prev;
-        
+
         // Reassign the head node if necessary
         if (node == Head())
             head_ = next;
-        
+
         FreeNode(node);
         SetSize(Size() - 1);
-        
+
         return next;
     }
-    
+
     /// Reserve a node.
     Node* ReserveNode()
     {
@@ -514,7 +571,7 @@ private:
         new(newNode) Node();
         return newNode;
     }
-    
+
     /// Reserve a node with specified key.
     Node* ReserveNode(const T& key)
     {
@@ -522,14 +579,14 @@ private:
         new(newNode) Node(key);
         return newNode;
     }
-    
+
     /// Free a node.
     void FreeNode(Node* node)
     {
         (node)->~Node();
         AllocatorFree(allocator_, node);
     }
-    
+
     /// Rehash the buckets.
     void Rehash()
     {
@@ -541,7 +598,7 @@ private:
             Ptrs()[hashKey] = node;
         }
     }
-    
+
     /// Compare two nodes.
     static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->key_ < rhs->key_; }
 
@@ -555,8 +612,11 @@ namespace std
 {
 
 template <class T> typename Urho3D::HashSet<T>::ConstIterator begin(const Urho3D::HashSet<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::HashSet<T>::ConstIterator end(const Urho3D::HashSet<T>& v) { return v.End(); }
+
 template <class T> typename Urho3D::HashSet<T>::Iterator begin(Urho3D::HashSet<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::HashSet<T>::Iterator end(Urho3D::HashSet<T>& v) { return v.End(); }
 
 }

+ 20 - 14
Source/Urho3D/Container/LinkedList.h

@@ -22,6 +22,12 @@
 
 #pragma once
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 namespace Urho3D
 {
 
@@ -33,7 +39,7 @@ struct URHO3D_API LinkedListNode
         next_(0)
     {
     }
-    
+
     /// Pointer to next node.
     LinkedListNode* next_;
 };
@@ -47,13 +53,13 @@ public:
         head_(0)
     {
     }
-    
+
     /// Destruct.
     ~LinkedList()
     {
         Clear();
     }
-    
+
     /// Remove all elements.
     void Clear()
     {
@@ -65,7 +71,7 @@ public:
             element = next;
         }
     }
-    
+
     /// Insert an element at the beginning.
     void InsertFront(T* element)
     {
@@ -75,7 +81,7 @@ public:
             head_ = element;
         }
     }
-    
+
     /// Insert an element at the end.
     void Insert(T* element)
     {
@@ -91,7 +97,7 @@ public:
             head_ = element;
         }
     }
-    
+
     /// Erase an element. Return true if successful.
     bool Erase(T* element)
     {
@@ -116,10 +122,10 @@ public:
                 }
             }
         }
-        
+
         return false;
     }
-    
+
     /// Erase an element when the previous element is known (optimization.) Return true if successful.
     bool Erase(T* element, T* previous)
     {
@@ -138,13 +144,13 @@ public:
                 return true;
             }
         }
-        
+
         return false;
     }
-    
+
     /// Return first element, or null if empty.
     T* First() const { return head_; }
-    
+
     /// Return last element, or null if empty.
     T* Last() const
     {
@@ -156,13 +162,13 @@ public:
         }
         return element;
     }
-    
+
     /// Return next element, or null if no more elements.
     T* Next(T* element) const { return element ? static_cast<T*>(element->next_) : 0; }
-    
+
     /// Return whether is empty.
     bool Empty() const { return head_ == 0; }
-    
+
 private:
     /// First element.
     T* head_;

+ 140 - 74
Source/Urho3D/Container/List.h

@@ -38,22 +38,23 @@ public:
         Node()
         {
         }
-        
+
         /// Construct with value.
         Node(const T& value) :
             value_(value)
         {
         }
-        
+
         /// Node value.
         T value_;
-        
+
         /// Return next node.
         Node* Next() const { return static_cast<Node*>(next_); }
+
         /// Return previous node.
         Node* Prev() { return static_cast<Node*>(prev_); }
     };
-    
+
     /// %List iterator.
     struct Iterator : public ListIteratorBase
     {
@@ -61,28 +62,50 @@ public:
         Iterator()
         {
         }
-        
+
         /// Construct with a node pointer.
         explicit Iterator(Node* ptr) :
             ListIteratorBase(ptr)
         {
         }
-        
+
         /// Preincrement the pointer.
-        Iterator& operator ++ () { GotoNext(); return *this; }
+        Iterator& operator ++()
+        {
+            GotoNext();
+            return *this;
+        }
+
         /// Postincrement the pointer.
-        Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
+        Iterator operator ++(int)
+        {
+            Iterator it = *this;
+            GotoNext();
+            return it;
+        }
+
         /// Predecrement the pointer.
-        Iterator& operator -- () { GotoPrev(); return *this; }
+        Iterator& operator --()
+        {
+            GotoPrev();
+            return *this;
+        }
+
         /// Postdecrement the pointer.
-        Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
-        
+        Iterator operator --(int)
+        {
+            Iterator it = *this;
+            GotoPrev();
+            return it;
+        }
+
         /// Point to the node value.
-        T* operator -> () const { return &(static_cast<Node*>(ptr_))->value_; }
+        T* operator ->() const { return &(static_cast<Node*>(ptr_))->value_; }
+
         /// Dereference the node value.
-        T& operator * () const { return (static_cast<Node*>(ptr_))->value_; }
+        T& operator *() const { return (static_cast<Node*>(ptr_))->value_; }
     };
-    
+
     /// %List const iterator.
     struct ConstIterator : public ListIteratorBase
     {
@@ -90,52 +113,79 @@ public:
         ConstIterator()
         {
         }
-        
+
         /// Construct with a node pointer.
         explicit ConstIterator(Node* ptr) :
             ListIteratorBase(ptr)
         {
         }
-        
+
         /// Construct from a non-const iterator.
         ConstIterator(const Iterator& rhs) :
             ListIteratorBase(rhs.ptr_)
         {
         }
-        
+
         /// Assign from a non-const iterator.
-        ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
+        ConstIterator& operator =(const Iterator& rhs)
+        {
+            ptr_ = rhs.ptr_;
+            return *this;
+        }
+
         /// Preincrement the pointer.
-        ConstIterator& operator ++ () { GotoNext(); return *this; }
+        ConstIterator& operator ++()
+        {
+            GotoNext();
+            return *this;
+        }
+
         /// Postincrement the pointer.
-        ConstIterator operator ++ (int) { ConstIterator it = *this; GotoNext(); return it; }
+        ConstIterator operator ++(int)
+        {
+            ConstIterator it = *this;
+            GotoNext();
+            return it;
+        }
+
         /// Predecrement the pointer.
-        ConstIterator& operator -- () { GotoPrev(); return *this; }
+        ConstIterator& operator --()
+        {
+            GotoPrev();
+            return *this;
+        }
+
         /// Postdecrement the pointer.
-        ConstIterator operator -- (int) { ConstIterator it = *this; GotoPrev(); return it; }
-        
+        ConstIterator operator --(int)
+        {
+            ConstIterator it = *this;
+            GotoPrev();
+            return it;
+        }
+
         /// Point to the node value.
-        const T* operator -> () const { return &(static_cast<Node*>(ptr_))->value_; }
+        const T* operator ->() const { return &(static_cast<Node*>(ptr_))->value_; }
+
         /// Dereference the node value.
-        const T& operator * () const { return (static_cast<Node*>(ptr_))->value_; }
+        const T& operator *() const { return (static_cast<Node*>(ptr_))->value_; }
     };
 
     /// Construct empty.
     List()
     {
-        allocator_ = AllocatorInitialize(sizeof(Node));
+        allocator_ = AllocatorInitialize((unsigned)sizeof(Node));
         head_ = tail_ = ReserveNode();
     }
-    
+
     /// Construct from another list.
     List(const List<T>& list)
     {
         // Reserve the tail node + initial capacity according to the list's size
-        allocator_ = AllocatorInitialize(sizeof(Node), list.Size() + 1);
+        allocator_ = AllocatorInitialize((unsigned)sizeof(Node), list.Size() + 1);
         head_ = tail_ = ReserveNode();
         *this = list;
     }
-    
+
     /// Destruct.
     ~List()
     {
@@ -143,36 +193,36 @@ public:
         FreeNode(Tail());
         AllocatorUninitialize(allocator_);
     }
-    
+
     /// Assign from another list.
-    List& operator = (const List<T>& rhs)
+    List& operator =(const List<T>& rhs)
     {
         // Clear, then insert the nodes of the other list
         Clear();
         Insert(End(), rhs);
         return *this;
     }
-    
+
     /// Add-assign an element.
-    List& operator += (const T& rhs)
+    List& operator +=(const T& rhs)
     {
         Push(rhs);
         return *this;
     }
-    
+
     /// Add-assign a list.
-    List& operator += (const List<T>& rhs)
+    List& operator +=(const List<T>& rhs)
     {
         Insert(End(), rhs);
         return *this;
     }
-    
+
     /// Test for equality with another list.
-    bool operator == (const List<T>& rhs) const
+    bool operator ==(const List<T>& rhs) const
     {
         if (rhs.size_ != size_)
             return false;
-        
+
         ConstIterator i = Begin();
         ConstIterator j = rhs.Begin();
         while (i != End())
@@ -182,16 +232,16 @@ public:
             ++i;
             ++j;
         }
-        
+
         return true;
     }
-    
+
     /// Test for inequality with another list.
-    bool operator != (const List<T>& rhs) const
+    bool operator !=(const List<T>& rhs) const
     {
         if (rhs.size_ != size_)
             return true;
-        
+
         ConstIterator i = Begin();
         ConstIterator j = rhs.Begin();
         while (i != End())
@@ -201,17 +251,19 @@ public:
             ++i;
             ++j;
         }
-        
+
         return false;
     }
-    
+
     /// Insert an element to the end.
     void Push(const T& value) { InsertNode(Tail(), value); }
+
     /// Insert an element to the beginning.
     void PushFront(const T& value) { InsertNode(Head(), value); }
+
     /// Insert an element at position.
     void Insert(const Iterator& dest, const T& value) { InsertNode(static_cast<Node*>(dest.ptr_), value); }
-    
+
     /// Insert a list at position.
     void Insert(const Iterator& dest, const List<T>& list)
     {
@@ -221,7 +273,7 @@ public:
         while (it != end)
             InsertNode(destNode, *it++);
     }
-    
+
     /// Insert elements by iterators.
     void Insert(const Iterator& dest, const ConstIterator& start, const ConstIterator& end)
     {
@@ -230,7 +282,7 @@ public:
         while (it != end)
             InsertNode(destNode, *it++);
     }
-    
+
     /// Insert elements.
     void Insert(const Iterator& dest, const T* start, const T* end)
     {
@@ -239,63 +291,63 @@ public:
         while (ptr != end)
             InsertNode(destNode, *ptr++);
     }
-    
+
     /// Erase the last element.
     void Pop()
     {
         if (size_)
             Erase(--End());
     }
-    
+
     /// Erase the first element.
     void PopFront()
     {
         if (size_)
             Erase(Begin());
     }
-    
+
     /// Erase an element by iterator. Return iterator to the next element.
     Iterator Erase(Iterator it)
     {
         return Iterator(EraseNode(static_cast<Node*>(it.ptr_)));
     }
-    
+
     /// Erase a range by iterators. Return an iterator to the next element.
     Iterator Erase(const Iterator& start, const Iterator& end)
     {
         Iterator it = start;
         while (it != end)
-            it = EraseNode(static_cast<Node*>(it.ptr_));
-        
+            it = Erase(it);
+
         return it;
     }
-    
+
     /// Clear the list.
     void Clear()
     {
         if (Size())
         {
-            for (Iterator i = Begin(); i != End(); )
+            for (Iterator i = Begin(); i != End();)
             {
                 FreeNode(static_cast<Node*>(i++.ptr_));
                 i.ptr_->prev_ = 0;
             }
-            
+
             head_ = tail_;
             size_ = 0;
         }
     }
-    
+
     /// Resize the list by removing or adding items at the end.
     void Resize(unsigned newSize)
     {
         while (size_ > newSize)
             Pop();
-        
+
         while (size_ < newSize)
             InsertNode(Tail(), T());
     }
-    
+
     /// Return iterator to value, or to the end if not found.
     Iterator Find(const T& value)
     {
@@ -304,7 +356,7 @@ public:
             ++it;
         return it;
     }
-    
+
     /// Return const iterator to value, or to the end if not found.
     ConstIterator Find(const T& value) const
     {
@@ -313,42 +365,53 @@ public:
             ++it;
         return it;
     }
-    
+
     /// Return whether contains a specific value.
     bool Contains(const T& value) const { return Find(value) != End(); }
+
     /// Return iterator to the first element.
     Iterator Begin() { return Iterator(Head()); }
+
     /// Return iterator to the first element.
     ConstIterator Begin() const { return ConstIterator(Head()); }
+
     /// Return iterator to the end.
     Iterator End() { return Iterator(Tail()); }
+
     /// Return iterator to the end.
     ConstIterator End() const { return ConstIterator(Tail()); }
+
     /// Return first element.
     T& Front() { return *Begin(); }
+
     /// Return const first element.
     const T& Front() const { return *Begin(); }
+
     /// Return last element.
     T& Back() { return *(--End()); }
+
     /// Return const last element.
     const T& Back() const { return *(--End()); }
+
     /// Return number of elements.
     unsigned Size() const { return size_; }
+
     /// Return whether list is empty.
     bool Empty() const { return size_ == 0; }
-    
+
 private:
     /// Return the head node.
     Node* Head() const { return static_cast<Node*>(head_); }
+
     /// Return the tail node.
     Node* Tail() const { return static_cast<Node*>(tail_); }
-    
+
     /// Allocate and insert a node into the list.
     void InsertNode(Node* dest, const T& value)
     {
         if (!dest)
             return;
-        
+
         Node* newNode = ReserveNode(value);
         Node* prev = dest->Prev();
         newNode->next_ = dest;
@@ -356,37 +419,37 @@ private:
         if (prev)
             prev->next_ = newNode;
         dest->prev_ = newNode;
-        
+
         // Reassign the head node if necessary
         if (dest == Head())
             head_ = newNode;
-        
+
         ++size_;
     }
-    
+
     /// Erase and free a node. Return pointer to the next node, or to the end if could not erase.
     Node* EraseNode(Node* node)
     {
         // The tail node can not be removed
         if (!node || node == tail_)
             return Tail();
-        
+
         Node* prev = node->Prev();
         Node* next = node->Next();
         if (prev)
             prev->next_ = next;
         next->prev_ = prev;
-        
+
         // Reassign the head node if necessary
         if (node == Head())
             head_ = next;
-        
+
         FreeNode(node);
         --size_;
-        
+
         return next;
     }
-    
+
     /// Reserve a node.
     Node* ReserveNode()
     {
@@ -394,7 +457,7 @@ private:
         new(newNode) Node();
         return newNode;
     }
-    
+
     /// Reserve a node with initial value.
     Node* ReserveNode(const T& value)
     {
@@ -402,7 +465,7 @@ private:
         new(newNode) Node(value);
         return newNode;
     }
-    
+
     /// Free a node.
     void FreeNode(Node* node)
     {
@@ -417,8 +480,11 @@ namespace std
 {
 
 template <class T> typename Urho3D::List<T>::ConstIterator begin(const Urho3D::List<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::List<T>::ConstIterator end(const Urho3D::List<T>& v) { return v.End(); }
+
 template <class T> typename Urho3D::List<T>::Iterator begin(Urho3D::List<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::List<T>::Iterator end(Urho3D::List<T>& v) { return v.End(); }
 
 }

+ 17 - 10
Source/Urho3D/Container/ListBase.h

@@ -22,6 +22,12 @@
 
 #pragma once
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 #include "../Container/Allocator.h"
 #include "../Container/Swap.h"
 
@@ -37,7 +43,7 @@ struct ListNodeBase
         next_(0)
     {
     }
-    
+
     /// Previous node.
     ListNodeBase* prev_;
     /// Next node.
@@ -52,32 +58,33 @@ struct ListIteratorBase
         ptr_(0)
     {
     }
-    
+
     /// Construct with a node pointer.
     explicit ListIteratorBase(ListNodeBase* ptr) :
         ptr_(ptr)
     {
     }
-    
+
     /// Test for equality with another iterator.
-    bool operator == (const ListIteratorBase& rhs) const { return ptr_ == rhs.ptr_; }
+    bool operator ==(const ListIteratorBase& rhs) const { return ptr_ == rhs.ptr_; }
+
     /// Test for inequality with another iterator.
-    bool operator != (const ListIteratorBase& rhs) const { return ptr_ != rhs.ptr_; }
-    
+    bool operator !=(const ListIteratorBase& rhs) const { return ptr_ != rhs.ptr_; }
+
     /// Go to the next node.
     void GotoNext()
     {
         if (ptr_)
             ptr_ = ptr_->next_;
     }
-    
+
     /// Go to the previous node.
     void GotoPrev()
     {
         if (ptr_)
             ptr_ = ptr_->prev_;
     }
-    
+
     /// Node pointer.
     ListNodeBase* ptr_;
 };
@@ -92,7 +99,7 @@ public:
         size_(0)
     {
     }
-    
+
     /// Swap with another linked list.
     void Swap(ListBase& rhs)
     {
@@ -101,7 +108,7 @@ public:
         Urho3D::Swap(allocator_, rhs.allocator_);
         Urho3D::Swap(size_, rhs.size_);
     }
-    
+
 protected:
     /// Head node pointer.
     ListNodeBase* head_;

+ 11 - 10
Source/Urho3D/Container/Pair.h

@@ -35,21 +35,22 @@ public:
     Pair()
     {
     }
-    
+
     /// Construct with values.
     Pair(const T& first, const U& second) :
         first_(first),
         second_(second)
     {
     }
-    
+
     /// Test for equality with another pair.
-    bool operator == (const Pair<T, U>& rhs) const { return first_ == rhs.first_ && second_ == rhs.second_; }
+    bool operator ==(const Pair<T, U>& rhs) const { return first_ == rhs.first_ && second_ == rhs.second_; }
+
     /// Test for inequality with another pair.
-    bool operator != (const Pair<T, U>& rhs) const { return first_ != rhs.first_ || second_ != rhs.second_; }
-    
+    bool operator !=(const Pair<T, U>& rhs) const { return first_ != rhs.first_ || second_ != rhs.second_; }
+
     /// Test for less than with another pair.
-    bool operator < (const Pair<T, U>& rhs) const
+    bool operator <(const Pair<T, U>& rhs) const
     {
         if (first_ < rhs.first_)
             return true;
@@ -57,9 +58,9 @@ public:
             return false;
         return second_ < rhs.second_;
     }
-    
+
     /// Test for greater than with another pair.
-    bool operator > (const Pair<T, U>& rhs) const
+    bool operator >(const Pair<T, U>& rhs) const
     {
         if (first_ > rhs.first_)
             return true;
@@ -67,10 +68,10 @@ public:
             return false;
         return second_ > rhs.second_;
     }
-    
+
     /// Return hash value for HashSet & HashMap.
     unsigned ToHash() const { return (MakeHash(first_) & 0xffff) | (MakeHash(second_) << 16); }
-    
+
     /// First value.
     T first_;
     /// Second value.

+ 106 - 75
Source/Urho3D/Container/Ptr.h

@@ -39,71 +39,89 @@ public:
         ptr_(0)
     {
     }
-    
+
     /// Copy-construct from another shared pointer.
     SharedPtr(const SharedPtr<T>& rhs) :
         ptr_(rhs.ptr_)
     {
         AddRef();
     }
-    
+
     /// Construct from a raw pointer.
     explicit SharedPtr(T* ptr) :
         ptr_(ptr)
     {
         AddRef();
     }
-    
+
     /// Destruct. Release the object reference.
     ~SharedPtr()
     {
         ReleaseRef();
     }
-    
+
     /// Assign from another shared pointer.
-    SharedPtr<T>& operator = (const SharedPtr<T>& rhs)
+    SharedPtr<T>& operator =(const SharedPtr<T>& rhs)
     {
         if (ptr_ == rhs.ptr_)
             return *this;
-        
+
         ReleaseRef();
         ptr_ = rhs.ptr_;
         AddRef();
-        
+
         return *this;
     }
-    
+
     /// Assign from a raw pointer.
-    SharedPtr<T>& operator = (T* ptr)
+    SharedPtr<T>& operator =(T* ptr)
     {
         if (ptr_ == ptr)
             return *this;
-        
+
         ReleaseRef();
         ptr_ = ptr;
         AddRef();
-        
+
         return *this;
     }
-    
+
     /// Point to the object.
-    T* operator -> () const { assert(ptr_); return ptr_; }
+    T* operator ->() const
+    {
+        assert(ptr_);
+        return ptr_;
+    }
+
     /// Dereference the object.
-    T& operator * () const { assert(ptr_); return *ptr_; }
+    T& operator *() const
+    {
+        assert(ptr_);
+        return *ptr_;
+    }
+
     /// Subscript the object if applicable.
-    T& operator [] (const int index) { assert(ptr_); return ptr_[index]; }
+    T& operator [](const int index)
+    {
+        assert(ptr_);
+        return ptr_[index];
+    }
+
     /// Test for less than with another shared pointer.
-    bool operator < (const SharedPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+    bool operator <(const SharedPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+
     /// Test for equality with another shared pointer.
-    bool operator == (const SharedPtr<T>& rhs) const { return ptr_ == rhs.ptr_; }
+    bool operator ==(const SharedPtr<T>& rhs) const { return ptr_ == rhs.ptr_; }
+
     /// Test for inequality with another shared pointer.
-    bool operator != (const SharedPtr<T>& rhs) const { return ptr_ != rhs.ptr_; }
+    bool operator !=(const SharedPtr<T>& rhs) const { return ptr_ != rhs.ptr_; }
+
     /// Convert to a raw pointer.
-    operator T* () const { return ptr_; }
-    
+    operator T*() const { return ptr_; }
+
     /// Reset to null and release the object reference.
     void Reset() { ReleaseRef(); }
-    
+
     /// Detach without destroying the object even if the refcount goes zero. To be used for scripting language interoperation.
     void Detach()
     {
@@ -115,7 +133,7 @@ public:
             --refCount->refs_; // 0 refs
         }
     }
-    
+
     /// Perform a static cast from a shared pointer of another type.
     template <class U> void StaticCast(const SharedPtr<U>& rhs)
     {
@@ -123,7 +141,7 @@ public:
         ptr_ = static_cast<T*>(rhs.Get());
         AddRef();
     }
-    
+
     /// Perform a dynamic cast from a shared pointer of another type.
     template <class U> void DynamicCast(const SharedPtr<U>& rhs)
     {
@@ -131,33 +149,39 @@ public:
         ptr_ = dynamic_cast<T*>(rhs.Get());
         AddRef();
     }
-    
+
     /// Check if the pointer is null.
     bool Null() const { return ptr_ == 0; }
+
     /// Check if the pointer is not null.
     bool NotNull() const { return ptr_ != 0; }
+
     /// Return the raw pointer.
     T* Get() const { return ptr_; }
+
     /// Return the object's reference count, or 0 if the pointer is null.
     int Refs() const { return ptr_ ? ptr_->Refs() : 0; }
+
     /// Return the object's weak reference count, or 0 if the pointer is null.
     int WeakRefs() const { return ptr_ ? ptr_->WeakRefs() : 0; }
+
     /// Return pointer to the RefCount structure.
     RefCount* RefCountPtr() const { return ptr_ ? ptr_->RefCountPtr() : 0; }
+
     /// Return hash value for HashSet & HashMap.
-    unsigned ToHash() const { return ((unsigned)(size_t)ptr_) / sizeof(T); }
-    
+    unsigned ToHash() const { return (unsigned)((size_t)ptr_ / sizeof(T)); }
+
 private:
     /// Prevent direct assignment from a shared pointer of another type.
-    template <class U> SharedPtr<T>& operator = (const SharedPtr<U>& rhs);
-    
+    template <class U> SharedPtr<T>& operator =(const SharedPtr<U>& rhs);
+
     /// Add a reference to the object pointed to.
     void AddRef()
     {
         if (ptr_)
             ptr_->AddRef();
     }
-    
+
     /// Release the object reference and delete it if necessary.
     void ReleaseRef()
     {
@@ -167,7 +191,7 @@ private:
             ptr_ = 0;
         }
     }
-    
+
     /// Pointer to the object.
     T* ptr_;
 };
@@ -198,7 +222,7 @@ public:
         refCount_(0)
     {
     }
-    
+
     /// Copy-construct from another weak pointer.
     WeakPtr(const WeakPtr<T>& rhs) :
         ptr_(rhs.ptr_),
@@ -206,7 +230,7 @@ public:
     {
         AddRef();
     }
-    
+
     /// Construct from a shared pointer.
     WeakPtr(const SharedPtr<T>& rhs) :
         ptr_(rhs.Get()),
@@ -214,7 +238,7 @@ public:
     {
         AddRef();
     }
-    
+
     /// Construct from a raw pointer.
     explicit WeakPtr(T* ptr) :
         ptr_(ptr),
@@ -222,57 +246,57 @@ public:
     {
         AddRef();
     }
-    
+
     /// Destruct. Release the weak reference to the object.
     ~WeakPtr()
     {
         ReleaseRef();
     }
-    
+
     /// Assign from a shared pointer.
-    WeakPtr<T>& operator = (const SharedPtr<T>& rhs)
+    WeakPtr<T>& operator =(const SharedPtr<T>& rhs)
     {
         if (ptr_ == rhs.Get() && refCount_ == rhs.RefCountPtr())
             return *this;
-        
+
         ReleaseRef();
         ptr_ = rhs.Get();
         refCount_ = rhs.RefCountPtr();
         AddRef();
-        
+
         return *this;
     }
-    
+
     /// Assign from a weak pointer.
-    WeakPtr<T>& operator = (const WeakPtr<T>& rhs)
+    WeakPtr<T>& operator =(const WeakPtr<T>& rhs)
     {
         if (ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_)
             return *this;
-        
+
         ReleaseRef();
         ptr_ = rhs.ptr_;
         refCount_ = rhs.refCount_;
         AddRef();
-        
+
         return *this;
     }
-    
+
     /// Assign from a raw pointer.
-    WeakPtr<T>& operator = (T* ptr)
+    WeakPtr<T>& operator =(T* ptr)
     {
         RefCount* refCount = ptr ? ptr->RefCountPtr() : 0;
-        
+
         if (ptr_ == ptr && refCount_ == refCount)
             return *this;
-        
+
         ReleaseRef();
         ptr_ = ptr;
         refCount_ = refCount;
         AddRef();
-        
+
         return *this;
     }
-    
+
     /// Convert to a shared pointer. If expired, return a null shared pointer.
     SharedPtr<T> Lock() const
     {
@@ -281,7 +305,7 @@ public:
         else
             return SharedPtr<T>(ptr_);
     }
-    
+
     /// Return raw pointer. If expired, return null.
     T* Get() const
     {
@@ -290,43 +314,46 @@ public:
         else
             return ptr_;
     }
-    
+
     /// Point to the object.
-    T* operator -> () const
+    T* operator ->() const
     {
         T* rawPtr = Get();
         assert(rawPtr);
         return rawPtr;
     }
-    
+
     /// Dereference the object.
-    T& operator * () const
+    T& operator *() const
     {
         T* rawPtr = Get();
         assert(rawPtr);
         return *rawPtr;
     }
-    
+
     /// Subscript the object if applicable.
-    T& operator [] (const int index)
+    T& operator [](const int index)
     {
         T* rawPtr = Get();
         assert(rawPtr);
         return (*rawPtr)[index];
     }
-    
+
     /// Test for equality with another weak pointer.
-    bool operator == (const WeakPtr<T>& rhs) const { return ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_; }
+    bool operator ==(const WeakPtr<T>& rhs) const { return ptr_ == rhs.ptr_ && refCount_ == rhs.refCount_; }
+
     /// Test for inequality with another weak pointer.
-    bool operator != (const WeakPtr<T>& rhs) const { return ptr_ != rhs.ptr_ || refCount_ != rhs.refCount_; }
+    bool operator !=(const WeakPtr<T>& rhs) const { return ptr_ != rhs.ptr_ || refCount_ != rhs.refCount_; }
+
     /// Test for less than with another weak pointer.
-    bool operator < (const WeakPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+    bool operator <(const WeakPtr<T>& rhs) const { return ptr_ < rhs.ptr_; }
+
     /// Convert to a raw pointer, null if the object is expired.
-    operator T* () const { return Get(); }
-    
+    operator T*() const { return Get(); }
+
     /// Reset to null and release the weak reference.
     void Reset() { ReleaseRef(); }
-    
+
     /// Perform a static cast from a weak pointer of another type.
     template <class U> void StaticCast(const WeakPtr<U>& rhs)
     {
@@ -335,13 +362,13 @@ public:
         refCount_ = rhs.refCount_;
         AddRef();
     }
-    
+
     /// Perform a dynamic cast from a weak pointer of another type.
     template <class U> void DynamicCast(const WeakPtr<U>& rhs)
     {
         ReleaseRef();
         ptr_ = dynamic_cast<T*>(rhs.Get());
-        
+
         if (ptr_)
         {
             refCount_ = rhs.refCount_;
@@ -350,14 +377,16 @@ public:
         else
             refCount_ = 0;
     }
-    
+
     /// Check if the pointer is null.
     bool Null() const { return refCount_ == 0; }
+
     /// Check if the pointer is not null.
     bool NotNull() const { return refCount_ != 0; }
+
     /// Return the object's reference count, or 0 if null pointer or if object has expired.
     int Refs() const { return (refCount_ && refCount_->refs_ >= 0) ? refCount_->refs_ : 0; }
-    
+
     /// Return the object's weak reference count.
     int WeakRefs() const
     {
@@ -366,18 +395,20 @@ public:
         else
             return refCount_ ? refCount_->weakRefs_ : 0;
     }
-    
+
     /// Return whether the object has expired. If null pointer, always return true.
     bool Expired() const { return refCount_ ? refCount_->refs_ < 0 : true; }
+
     /// Return pointer to the RefCount structure.
     RefCount* RefCountPtr() const { return refCount_; }
+
     /// Return hash value for HashSet & HashMap.
-    unsigned ToHash() const { return ((unsigned)(size_t)ptr_) / sizeof(T); }
-    
+    unsigned ToHash() const { return (unsigned)((size_t)ptr_ / sizeof(T)); }
+
 private:
     /// Prevent direct assignment from a weak pointer of different type.
-    template <class U> WeakPtr<T>& operator = (const WeakPtr<U>& rhs);
-    
+    template <class U> WeakPtr<T>& operator =(const WeakPtr<U>& rhs);
+
     /// Add a weak reference to the object pointed to.
     void AddRef()
     {
@@ -387,7 +418,7 @@ private:
             ++(refCount_->weakRefs_);
         }
     }
-    
+
     /// Release the weak reference. Delete the Refcount structure if necessary.
     void ReleaseRef()
     {
@@ -395,15 +426,15 @@ private:
         {
             assert(refCount_->weakRefs_ > 0);
             --(refCount_->weakRefs_);
-            
+
             if (Expired() && !refCount_->weakRefs_)
                 delete refCount_;
         }
-        
+
         ptr_ = 0;
         refCount_ = 0;
     }
-    
+
     /// Pointer to the object.
     T* ptr_;
     /// Pointer to the RefCount structure.

+ 4 - 4
Source/Urho3D/Container/RefCounted.cpp

@@ -20,9 +20,9 @@
 // THE SOFTWARE.
 //
 
-#include "../Container/RefCounted.h"
+#include "../Precompiled.h"
 
-#include <cassert>
+#include "../Container/RefCounted.h"
 
 #include "../DebugNew.h"
 
@@ -41,13 +41,13 @@ RefCounted::~RefCounted()
     assert(refCount_);
     assert(refCount_->refs_ == 0);
     assert(refCount_->weakRefs_ > 0);
-    
+
     // Mark object as expired, release the self weak ref and delete the refcount if no other weak refs exist
     refCount_->refs_ = -1;
     (refCount_->weakRefs_)--;
     if (!refCount_->weakRefs_)
         delete refCount_;
-    
+
     refCount_ = 0;
 }
 

+ 13 - 6
Source/Urho3D/Container/RefCounted.h

@@ -22,6 +22,12 @@
 
 #pragma once
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 namespace Urho3D
 {
 
@@ -34,7 +40,7 @@ struct RefCount
         weakRefs_(0)
     {
     }
-    
+
     /// Destruct.
     ~RefCount()
     {
@@ -42,7 +48,7 @@ struct RefCount
         refs_ = -1;
         weakRefs_ = -1;
     }
-    
+
     /// Reference count. If below zero, the object has been destroyed.
     int refs_;
     /// Weak reference count.
@@ -57,7 +63,7 @@ public:
     RefCounted();
     /// Destruct. Mark as expired and also delete the reference count structure if no outside weak references exist.
     virtual ~RefCounted();
-    
+
     /// Increment reference count. Can also be called outside of a SharedPtr for traditional reference counting.
     void AddRef();
     /// Decrement reference count and delete self if no more references. Can also be called outside of a SharedPtr for traditional reference counting.
@@ -66,15 +72,16 @@ public:
     int Refs() const;
     /// Return weak reference count.
     int WeakRefs() const;
+
     /// Return pointer to the reference count structure.
     RefCount* RefCountPtr() { return refCount_; }
-    
+
 private:
     /// Prevent copy construction.
     RefCounted(const RefCounted& rhs);
     /// Prevent assignment.
-    RefCounted& operator = (const RefCounted& rhs);
-    
+    RefCounted& operator =(const RefCounted& rhs);
+
     /// Pointer to the reference count structure.
     RefCount* refCount_;
 };

+ 4 - 4
Source/Urho3D/Container/Sort.h

@@ -76,7 +76,7 @@ template <class T> void InitialQuickSort(RandomAccessIterator<T> begin, RandomAc
             pivot = begin;
         else if (*(end - 1) < *pivot && *begin < *(end - 1))
             pivot = end - 1;
-        
+
         // Partition and sort recursively
         RandomAccessIterator<T> i = begin - 1;
         RandomAccessIterator<T> j = end;
@@ -90,7 +90,7 @@ template <class T> void InitialQuickSort(RandomAccessIterator<T> begin, RandomAc
             else
                 break;
         }
-        
+
         InitialQuickSort(begin, j + 1);
         begin = j + 1;
     }
@@ -107,7 +107,7 @@ template <class T, class U> void InitialQuickSort(RandomAccessIterator<T> begin,
             pivot = begin;
         else if (compare(*(end - 1), *pivot) && compare(*begin, *(end - 1)))
             pivot = end - 1;
-        
+
         // Partition and sort recursively
         RandomAccessIterator<T> i = begin - 1;
         RandomAccessIterator<T> j = end;
@@ -121,7 +121,7 @@ template <class T, class U> void InitialQuickSort(RandomAccessIterator<T> begin,
             else
                 break;
         }
-        
+
         InitialQuickSort(begin, j + 1, compare);
         begin = j + 1;
     }

File diff suppressed because it is too large
+ 167 - 163
Source/Urho3D/Container/Str.cpp


+ 156 - 92
Source/Urho3D/Container/Str.h

@@ -24,8 +24,8 @@
 
 #include "../Container/Vector.h"
 
-#include <cstring>
 #include <cstdarg>
+#include <cstring>
 #include <cctype>
 
 namespace Urho3D
@@ -42,7 +42,7 @@ class URHO3D_API String
 public:
     typedef RandomAccessIterator<char> Iterator;
     typedef RandomAccessConstIterator<char> ConstIterator;
-    
+
     /// Construct empty.
     String() :
         length_(0),
@@ -50,7 +50,7 @@ public:
         buffer_(&endZero)
     {
     }
-    
+
     /// Construct from another string.
     String(const String& str) :
         length_(0),
@@ -59,7 +59,7 @@ public:
     {
         *this = str;
     }
-    
+
     /// Construct from a C string.
     String(const char* str) :
         length_(0),
@@ -68,7 +68,7 @@ public:
     {
         *this = str;
     }
-    
+
     /// Construct from a C string.
     String(char* str) :
         length_(0),
@@ -77,7 +77,7 @@ public:
     {
         *this = (const char*)str;
     }
-    
+
     /// Construct from a char array and length.
     String(const char* str, unsigned length) :
         length_(0),
@@ -87,7 +87,7 @@ public:
         Resize(length);
         CopyChars(buffer_, str, length);
     }
-    
+
     /// Construct from a null-terminated wide character array.
     String(const wchar_t* str) :
         length_(0),
@@ -96,7 +96,7 @@ public:
     {
         SetUTF8FromWChar(str);
     }
-    
+
     /// Construct from a null-terminated wide character array.
     String(wchar_t* str) :
         length_(0),
@@ -105,10 +105,10 @@ public:
     {
         SetUTF8FromWChar(str);
     }
-    
+
     /// Construct from a wide character string.
     String(const WString& str);
-    
+
     /// Construct from an integer.
     explicit String(int value);
     /// Construct from a short integer.
@@ -135,7 +135,7 @@ public:
     explicit String(char value);
     /// Construct from a character and fill length.
     explicit String(char value, unsigned length);
-    
+
     /// Construct from a convertable value.
     template <class T> explicit String(const T& value) :
         length_(0),
@@ -144,144 +144,172 @@ public:
     {
         *this = value.ToString();
     }
-    
+
     /// Destruct.
     ~String()
     {
         if (capacity_)
             delete[] buffer_;
     }
-    
+
     /// Assign a string.
-    String& operator = (const String& rhs)
+    String& operator =(const String& rhs)
     {
         Resize(rhs.length_);
         CopyChars(buffer_, rhs.buffer_, rhs.length_);
-        
+
         return *this;
     }
-    
+
     /// Assign a C string.
-    String& operator = (const char* rhs)
+    String& operator =(const char* rhs)
     {
         unsigned rhsLength = CStringLength(rhs);
         Resize(rhsLength);
         CopyChars(buffer_, rhs, rhsLength);
-        
+
         return *this;
     }
-    
+
     /// Add-assign a string.
-    String& operator += (const String& rhs)
+    String& operator +=(const String& rhs)
     {
         unsigned oldLength = length_;
         Resize(length_ + rhs.length_);
         CopyChars(buffer_ + oldLength, rhs.buffer_, rhs.length_);
-        
+
         return *this;
     }
-    
+
     /// Add-assign a C string.
-    String& operator += (const char* rhs)
+    String& operator +=(const char* rhs)
     {
         unsigned rhsLength = CStringLength(rhs);
         unsigned oldLength = length_;
         Resize(length_ + rhsLength);
         CopyChars(buffer_ + oldLength, rhs, rhsLength);
-        
+
         return *this;
     }
-    
+
     /// Add-assign a character.
-    String& operator += (char rhs)
+    String& operator +=(char rhs)
     {
         unsigned oldLength = length_;
         Resize(length_ + 1);
-        buffer_[oldLength]  = rhs;
-        
+        buffer_[oldLength] = rhs;
+
         return *this;
     }
-    
+
     /// Add-assign an integer.
-    String& operator += (int rhs);
+    String& operator +=(int rhs);
     /// Add-assign a short integer.
-    String& operator += (short rhs);
+    String& operator +=(short rhs);
     /// Add-assign a long integer.
-    String& operator += (long rhs);
+    String& operator +=(long rhs);
     /// Add-assign a long long integer.
-    String& operator += (long long rhs);
+    String& operator +=(long long rhs);
     /// Add-assign an unsigned integer.
-    String& operator += (unsigned rhs);
+    String& operator +=(unsigned rhs);
     /// Add-assign a short unsigned integer.
-    String& operator += (unsigned short rhs);
+    String& operator +=(unsigned short rhs);
     /// Add-assign a long unsigned integer.
-    String& operator += (unsigned long rhs);
+    String& operator +=(unsigned long rhs);
     /// Add-assign a long long unsigned integer.
-    String& operator += (unsigned long long rhs);
+    String& operator +=(unsigned long long rhs);
     /// Add-assign a float.
-    String& operator += (float rhs);
+    String& operator +=(float rhs);
     /// Add-assign a bool.
-    String& operator += (bool rhs);
+    String& operator +=(bool rhs);
+
     /// Add-assign an arbitraty type.
-    template <class T> String operator += (const T& rhs) { return *this += rhs.ToString(); }
-    
+    template <class T> String operator +=(const T& rhs) { return *this += rhs.ToString(); }
+
     /// Add a string.
-    String operator + (const String& rhs) const
+    String operator +(const String& rhs) const
     {
         String ret;
         ret.Resize(length_ + rhs.length_);
         CopyChars(ret.buffer_, buffer_, length_);
         CopyChars(ret.buffer_ + length_, rhs.buffer_, rhs.length_);
-        
+
         return ret;
     }
-    
+
     /// Add a C string.
-    String operator + (const char* rhs) const
+    String operator +(const char* rhs) const
     {
         unsigned rhsLength = CStringLength(rhs);
         String ret;
         ret.Resize(length_ + rhsLength);
         CopyChars(ret.buffer_, buffer_, length_);
         CopyChars(ret.buffer_ + length_, rhs, rhsLength);
-        
+
         return ret;
     }
-    
+
     /// Add a character.
-    String operator + (char rhs) const
+    String operator +(char rhs) const
     {
         String ret(*this);
         ret += rhs;
-        
+
         return ret;
     }
-    
+
     /// Test for equality with another string.
-    bool operator == (const String& rhs) const { return strcmp(CString(), rhs.CString()) == 0; }
+    bool operator ==(const String& rhs) const { return strcmp(CString(), rhs.CString()) == 0; }
+
     /// Test for inequality with another string.
-    bool operator != (const String& rhs) const { return strcmp(CString(), rhs.CString()) != 0; }
+    bool operator !=(const String& rhs) const { return strcmp(CString(), rhs.CString()) != 0; }
+
     /// Test if string is less than another string.
-    bool operator < (const String& rhs) const { return strcmp(CString(), rhs.CString()) < 0; }
+    bool operator <(const String& rhs) const { return strcmp(CString(), rhs.CString()) < 0; }
+
     /// Test if string is greater than another string.
-    bool operator > (const String& rhs) const { return strcmp(CString(), rhs.CString()) > 0; }
+    bool operator >(const String& rhs) const { return strcmp(CString(), rhs.CString()) > 0; }
+
     /// Test for equality with a C string.
-    bool operator == (const char* rhs) const { return strcmp(CString(), rhs) == 0; }
+    bool operator ==(const char* rhs) const { return strcmp(CString(), rhs) == 0; }
+
     /// Test for inequality with a C string.
-    bool operator != (const char* rhs) const { return strcmp(CString(), rhs) != 0; }
+    bool operator !=(const char* rhs) const { return strcmp(CString(), rhs) != 0; }
+
     /// Test if string is less than a C string.
-    bool operator < (const char* rhs) const { return strcmp(CString(), rhs) < 0; }
+    bool operator <(const char* rhs) const { return strcmp(CString(), rhs) < 0; }
+
     /// Test if string is greater than a C string.
-    bool operator > (const char* rhs) const { return strcmp(CString(), rhs) > 0; }
+    bool operator >(const char* rhs) const { return strcmp(CString(), rhs) > 0; }
+
     /// Return char at index.
-    char& operator [] (unsigned index) { assert(index < length_); return buffer_[index]; }
+    char& operator [](unsigned index)
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Return const char at index.
-    const char& operator [] (unsigned index) const { assert(index < length_); return buffer_[index]; }
+    const char& operator [](unsigned index) const
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Return char at index.
-    char& At(unsigned index) { assert(index < length_); return buffer_[index]; }
+    char& At(unsigned index)
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Return const char at index.
-    const char& At(unsigned index) const { assert(index < length_); return buffer_[index]; }
-    
+    const char& At(unsigned index) const
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Replace all occurrences of a character.
     void Replace(char replaceThis, char replaceWith, bool caseSensitive = true);
     /// Replace all occurrences of a string.
@@ -330,19 +358,25 @@ public:
     void Clear();
     /// Swap with another string.
     void Swap(String& str);
-    
+
     /// Return iterator to the beginning.
     Iterator Begin() { return Iterator(buffer_); }
+
     /// Return const iterator to the beginning.
     ConstIterator Begin() const { return ConstIterator(buffer_); }
+
     /// Return iterator to the end.
     Iterator End() { return Iterator(buffer_ + length_); }
+
     /// Return const iterator to the end.
     ConstIterator End() const { return ConstIterator(buffer_ + length_); }
+
     /// Return first char, or 0 if empty.
     char Front() const { return buffer_[0]; }
+
     /// Return last char, or 0 if empty.
     char Back() const { return length_ ? buffer_[length_ - 1] : buffer_[0]; }
+
     /// Return a substring from position to end.
     String Substring(unsigned pos) const;
     /// Return a substring with length from position.
@@ -369,20 +403,27 @@ public:
     bool StartsWith(const String& str, bool caseSensitive = true) const;
     /// Return whether ends with a string.
     bool EndsWith(const String& str, bool caseSensitive = true) const;
+
     /// Return the C string.
     const char* CString() const { return buffer_; }
+
     /// Return length.
     unsigned Length() const { return length_; }
+
     /// Return buffer capacity.
     unsigned Capacity() const { return capacity_; }
+
     /// Return whether the string is empty.
     bool Empty() const { return length_ == 0; }
+
     /// Return comparison result with a string.
     int Compare(const String& str, bool caseSensitive = true) const;
     /// Return comparison result with a C string.
     int Compare(const char* str, bool caseSensitive = true) const;
+
     /// Return whether contains a specific occurence of a string.
     bool Contains(const String& str, bool caseSensitive = true) const { return Find(str, 0, caseSensitive) != NPOS; }
+
     /// Return whether contains a specific character.
     bool Contains(char c, bool caseSensitive = true) const { return Find(c, 0, caseSensitive) != NPOS; }
 
@@ -406,7 +447,7 @@ public:
     String SubstringUTF8(unsigned pos) const;
     /// Return a UTF8 substring with length from position.
     String SubstringUTF8(unsigned pos, unsigned length) const;
-    
+
     /// Return hash value for HashSet & HashMap.
     unsigned ToHash() const
     {
@@ -417,10 +458,10 @@ public:
             hash = *ptr + (hash << 6) + (hash << 16) - hash;
             ++ptr;
         }
-        
+
         return hash;
     }
-    
+
     /// Return substrings split by a separator char.
     static Vector<String> Split(const char* str, char separator);
     /// Return a string by joining substrings with a 'glue' string.
@@ -429,43 +470,43 @@ public:
     static void EncodeUTF8(char*& dest, unsigned unicodeChar);
     /// Decode Unicode character from UTF8. Pointer will be incremented.
     static unsigned DecodeUTF8(const char*& src);
-    #ifdef WIN32
+#ifdef WIN32
     /// Encode Unicode character to UTF16. Pointer will be incremented.
     static void EncodeUTF16(wchar_t*& dest, unsigned unicodeChar);
     /// Decode Unicode character from UTF16. Pointer will be incremented.
     static unsigned DecodeUTF16(const wchar_t*& src);
     #endif
-    
+
     /// Return length of a C string.
     static unsigned CStringLength(const char* str)
     {
         if (!str)
             return 0;
-        #ifdef _MSC_VER
+#ifdef _MSC_VER
         return (unsigned)strlen(str);
-        #else
+#else
         const char* ptr = str;
         while (*ptr)
             ++ptr;
         return (unsigned)(ptr - str);
-        #endif
+#endif
     }
-    
+
     /// Append to string using formatting.
-    String& AppendWithFormat(const char* formatString, ... );
+    String& AppendWithFormat(const char* formatString, ...);
     /// Append to string using variable arguments.
     String& AppendWithFormatArgs(const char* formatString, va_list args);
-    
+
     /// Compare two C strings.
     static int Compare(const char* str1, const char* str2, bool caseSensitive);
-    
+
     /// Position for "not found."
     static const unsigned NPOS = 0xffffffff;
     /// Initial dynamic allocation size.
     static const unsigned MIN_CAPACITY = 8;
     /// Empty string.
     static const String EMPTY;
-    
+
 private:
     /// Move a range of characters within the string.
     void MoveRange(unsigned dest, unsigned src, unsigned count)
@@ -473,14 +514,14 @@ private:
         if (count)
             memmove(buffer_ + dest, buffer_ + src, count);
     }
-    
+
     /// Copy chars from one buffer to another.
     static void CopyChars(char* dest, const char* src, unsigned count)
     {
-        #ifdef _MSC_VER
+#ifdef _MSC_VER
         if (count)
             memcpy(dest, src, count);
-        #else
+#else
         char* end = dest + count;
         while (dest != end)
         {
@@ -488,25 +529,25 @@ private:
             ++dest;
             ++src;
         }
-        #endif
+#endif
     }
-    
+
     /// Replace a substring with another substring.
     void Replace(unsigned pos, unsigned length, const char* srcStart, unsigned srcLength);
-    
+
     /// String length.
     unsigned length_;
     /// Capacity, zero if buffer not allocated.
     unsigned capacity_;
     /// String buffer, null if not allocated.
     char* buffer_;
-    
+
     /// End zero for empty strings.
     static char endZero;
 };
 
 /// Add a string to a C string.
-inline String operator + (const char* lhs, const String& rhs)
+inline String operator +(const char* lhs, const String& rhs)
 {
     String ret(lhs);
     ret += rhs;
@@ -514,7 +555,7 @@ inline String operator + (const char* lhs, const String& rhs)
 }
 
 /// Add a string to a wide char C string.
-inline String operator + (const wchar_t* lhs, const String& rhs)
+inline String operator +(const wchar_t* lhs, const String& rhs)
 {
     String ret(lhs);
     ret += rhs;
@@ -531,24 +572,47 @@ public:
     WString(const String& str);
     /// Destruct.
     ~WString();
-    
+
     /// Return char at index.
-    wchar_t& operator [] (unsigned index) { assert(index < length_); return buffer_[index]; }
+    wchar_t& operator [](unsigned index)
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Return const char at index.
-    const wchar_t& operator [] (unsigned index) const { assert(index < length_); return buffer_[index]; }
+    const wchar_t& operator [](unsigned index) const
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Return char at index.
-    wchar_t& At(unsigned index) { assert(index < length_); return buffer_[index]; }
+    wchar_t& At(unsigned index)
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Return const char at index.
-    const wchar_t& At(unsigned index) const { assert(index < length_); return buffer_[index]; }
+    const wchar_t& At(unsigned index) const
+    {
+        assert(index < length_);
+        return buffer_[index];
+    }
+
     /// Resize the string.
     void Resize(unsigned newLength);
+
     /// Return whether the string is empty.
     bool Empty() const { return length_ == 0; }
+
     /// Return length.
     unsigned Length() const { return length_; }
+
     /// Return character data.
     const wchar_t* CString() const { return buffer_; }
-    
+
 private:
     /// String length.
     unsigned length_;

+ 6 - 7
Source/Urho3D/Container/Swap.cpp

@@ -20,30 +20,29 @@
 // THE SOFTWARE.
 //
 
-#include "../Container/HashBase.h"
+#include "../Precompiled.h"
+
 #include "../Container/ListBase.h"
-#include "../Container/Str.h"
-#include "../Container/VectorBase.h"
 
 namespace Urho3D
 {
 
-template<> void Swap<String>(String& first, String& second)
+template <> void Swap<String>(String& first, String& second)
 {
     first.Swap(second);
 }
 
-template<> void Swap<VectorBase>(VectorBase& first, VectorBase& second)
+template <> void Swap<VectorBase>(VectorBase& first, VectorBase& second)
 {
     first.Swap(second);
 }
 
-template<> void Swap<ListBase>(ListBase& first, ListBase& second)
+template <> void Swap<ListBase>(ListBase& first, ListBase& second)
 {
     first.Swap(second);
 }
 
-template<> void Swap<HashBase>(HashBase& first, HashBase& second)
+template <> void Swap<HashBase>(HashBase& first, HashBase& second)
 {
     first.Swap(second);
 }

+ 5 - 5
Source/Urho3D/Container/Swap.h

@@ -31,16 +31,16 @@ class String;
 class VectorBase;
 
 /// Swap two values.
-template<class T> inline void Swap(T& first, T& second)
+template <class T> inline void Swap(T& first, T& second)
 {
     T temp = first;
     first = second;
     second = temp;
 }
 
-template<> void Swap<String>(String& first, String& second);
-template<> void Swap<VectorBase>(VectorBase& first, VectorBase& second);
-template<> void Swap<ListBase>(ListBase& first, ListBase& second);
-template<> void Swap<HashBase>(HashBase& first, HashBase& second);
+template <> void Swap<String>(String& first, String& second);
+template <> void Swap<VectorBase>(VectorBase& first, VectorBase& second);
+template <> void Swap<ListBase>(ListBase& first, ListBase& second);
+template <> void Swap<HashBase>(HashBase& first, HashBase& second);
 
 }

+ 249 - 158
Source/Urho3D/Container/Vector.h

@@ -38,81 +38,81 @@ public:
     typedef T ValueType;
     typedef RandomAccessIterator<T> Iterator;
     typedef RandomAccessConstIterator<T> ConstIterator;
-    
+
     /// Construct empty.
     Vector()
     {
     }
-    
+
     /// Construct with initial size.
     explicit Vector(unsigned size)
     {
         Resize(size, 0);
     }
-    
+
     /// Construct with initial data.
     Vector(const T* data, unsigned size)
     {
         Resize(size, data);
     }
-    
+
     /// Construct from another vector.
     Vector(const Vector<T>& vector)
     {
         *this = vector;
     }
-    
+
     /// Destruct.
     ~Vector()
     {
         Clear();
         delete[] buffer_;
     }
-    
+
     /// Assign from another vector.
-    Vector<T>& operator = (const Vector<T>& rhs)
+    Vector<T>& operator =(const Vector<T>& rhs)
     {
         Clear();
         Resize(rhs.size_, rhs.Buffer());
         return *this;
     }
-    
+
     /// Add-assign an element.
-    Vector<T>& operator += (const T& rhs)
+    Vector<T>& operator +=(const T& rhs)
     {
         Push(rhs);
         return *this;
     }
-    
+
     /// Add-assign another vector.
-    Vector<T>& operator += (const Vector<T>& rhs)
+    Vector<T>& operator +=(const Vector<T>& rhs)
     {
         Push(rhs);
         return *this;
     }
-    
+
     /// Add an element.
-    Vector<T> operator + (const T& rhs) const
+    Vector<T> operator +(const T& rhs) const
     {
         Vector<T> ret(*this);
         ret.Push(rhs);
         return ret;
     }
-    
+
     /// Add another vector.
-    Vector<T> operator + (const Vector<T>& rhs) const
+    Vector<T> operator +(const Vector<T>& rhs) const
     {
         Vector<T> ret(*this);
         ret.Push(rhs);
         return ret;
     }
-    
+
     /// Test for equality with another vector.
-    bool operator == (const Vector<T>& rhs) const
+    bool operator ==(const Vector<T>& rhs) const
     {
         if (rhs.size_ != size_)
             return false;
-        
+
         T* buffer = Buffer();
         T* rhsBuffer = rhs.Buffer();
         for (unsigned i = 0; i < size_; ++i)
@@ -120,16 +120,16 @@ public:
             if (buffer[i] != rhsBuffer[i])
                 return false;
         }
-        
+
         return true;
     }
-    
+
     /// Test for inequality with another vector.
-    bool operator != (const Vector<T>& rhs) const
+    bool operator !=(const Vector<T>& rhs) const
     {
         if (rhs.size_ != size_)
             return true;
-        
+
         T* buffer = Buffer();
         T* rhsBuffer = rhs.Buffer();
         for (unsigned i = 0; i < size_; ++i)
@@ -137,145 +137,165 @@ public:
             if (buffer[i] != rhsBuffer[i])
                 return true;
         }
-        
+
         return false;
     }
-    
+
     /// Return element at index.
-    T& operator [] (unsigned index) { assert(index < size_); return Buffer()[index]; }
+    T& operator [](unsigned index)
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Return const element at index.
-    const T& operator [] (unsigned index) const { assert(index < size_); return Buffer()[index]; }
+    const T& operator [](unsigned index) const
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Return element at index.
-    T& At(unsigned index) { assert(index < size_); return Buffer()[index]; }
+    T& At(unsigned index)
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Return const element at index.
-    const T& At(unsigned index) const { assert(index < size_); return Buffer()[index]; }
+    const T& At(unsigned index) const
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
 
     /// Add an element at the end.
     void Push(const T& value) { Resize(size_ + 1, &value); }
+
     /// Add another vector at the end.
     void Push(const Vector<T>& vector) { Resize(size_ + vector.size_, vector.Buffer()); }
-    
+
     /// Remove the last element.
     void Pop()
     {
         if (size_)
             Resize(size_ - 1, 0);
     }
-    
+
     /// Insert an element at position.
     void Insert(unsigned pos, const T& value)
     {
         if (pos > size_)
             pos = size_;
-        
+
         unsigned oldSize = size_;
         Resize(size_ + 1, 0);
         MoveRange(pos + 1, pos, oldSize - pos);
         Buffer()[pos] = value;
     }
-    
+
     /// Insert another vector at position.
     void Insert(unsigned pos, const Vector<T>& vector)
     {
         if (pos > size_)
             pos = size_;
-        
+
         unsigned oldSize = size_;
         Resize(size_ + vector.size_, 0);
         MoveRange(pos + vector.size_, pos, oldSize - pos);
         CopyElements(Buffer() + pos, vector.Buffer(), vector.size_);
     }
-    
+
     /// Insert an element by iterator.
     Iterator Insert(const Iterator& dest, const T& value)
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
             pos = size_;
         Insert(pos, value);
-        
+
         return Begin() + pos;
     }
-    
+
     /// Insert a vector by iterator.
     Iterator Insert(const Iterator& dest, const Vector<T>& vector)
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
             pos = size_;
         Insert(pos, vector);
-        
+
         return Begin() + pos;
     }
-    
+
     /// Insert a vector partially by iterators.
     Iterator Insert(const Iterator& dest, const ConstIterator& start, const ConstIterator& end)
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
             pos = size_;
         unsigned length = (unsigned)(end - start);
         Resize(size_ + length, 0);
         MoveRange(pos + length, pos, size_ - pos - length);
-        
+
         T* destPtr = Buffer() + pos;
         for (ConstIterator it = start; it != end; ++it)
             *destPtr++ = *it;
-        
+
         return Begin() + pos;
     }
-    
+
     /// Insert elements.
     Iterator Insert(const Iterator& dest, const T* start, const T* end)
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
             pos = size_;
         unsigned length = (unsigned)(end - start);
         Resize(size_ + length, 0);
         MoveRange(pos + length, pos, size_ - pos - length);
-        
+
         T* destPtr = Buffer() + pos;
         for (const T* i = start; i != end; ++i)
             *destPtr++ = *i;
-        
+
         return Begin() + pos;
     }
-    
+
     /// Erase a range of elements.
     void Erase(unsigned pos, unsigned length = 1)
     {
         // Return if the range is illegal
         if (pos + length > size_ || !length)
             return;
-        
+
         MoveRange(pos, pos + length, size_ - pos - length);
         Resize(size_ - length, 0);
     }
-    
+
     /// Erase an element by iterator. Return iterator to the next element.
     Iterator Erase(const Iterator& it)
     {
-        unsigned pos = it - Begin();
+        unsigned pos = (unsigned)(it - Begin());
         if (pos >= size_)
             return End();
         Erase(pos);
-        
+
         return Begin() + pos;
     }
-    
+
     /// Erase a range by iterators. Return iterator to the next element.
     Iterator Erase(const Iterator& start, const Iterator& end)
     {
-        unsigned pos = start - Begin();
+        unsigned pos = (unsigned)(start - Begin());
         if (pos >= size_)
             return End();
         unsigned length = (unsigned)(end - start);
         Erase(pos, length);
-        
+
         return Begin() + pos;
     }
-    
+
     /// Erase an element if found.
     bool Remove(const T& value)
     {
@@ -288,40 +308,41 @@ public:
         else
             return false;
     }
-    
+
     /// Clear the vector.
     void Clear() { Resize(0); }
+
     /// Resize the vector.
     void Resize(unsigned newSize) { Resize(newSize, 0); }
-    
+
     /// Set new capacity.
     void Reserve(unsigned newCapacity)
     {
         if (newCapacity < size_)
             newCapacity = size_;
-        
+
         if (newCapacity != capacity_)
         {
             T* newBuffer = 0;
             capacity_ = newCapacity;
-            
+
             if (capacity_)
             {
-                newBuffer = reinterpret_cast<T*>(AllocateBuffer(capacity_ * sizeof(T)));
+                newBuffer = reinterpret_cast<T*>(AllocateBuffer((unsigned)(capacity_ * sizeof(T))));
                 // Move the data into the new buffer
                 ConstructElements(newBuffer, Buffer(), size_);
             }
-            
+
             // Delete the old buffer
             DestructElements(Buffer(), size_);
             delete[] buffer_;
             buffer_ = reinterpret_cast<unsigned char*>(newBuffer);
         }
     }
-    
+
     /// Reallocate so that no extra memory is used.
     void Compact() { Reserve(size_); }
-    
+
     /// Return iterator to value, or to the end if not found.
     Iterator Find(const T& value)
     {
@@ -330,7 +351,7 @@ public:
             ++it;
         return it;
     }
-    
+
     /// Return const iterator to value, or to the end if not found.
     ConstIterator Find(const T& value) const
     {
@@ -339,38 +360,64 @@ public:
             ++it;
         return it;
     }
-    
+
     /// Return whether contains a specific value.
     bool Contains(const T& value) const { return Find(value) != End(); }
-    
+
     /// Return iterator to the beginning.
     Iterator Begin() { return Iterator(Buffer()); }
+
     /// Return const iterator to the beginning.
     ConstIterator Begin() const { return ConstIterator(Buffer()); }
+
     /// Return iterator to the end.
     Iterator End() { return Iterator(Buffer() + size_); }
+
     /// Return const iterator to the end.
     ConstIterator End() const { return ConstIterator(Buffer() + size_); }
+
     /// Return first element.
-    T& Front() { assert(size_); return Buffer()[0]; }
+    T& Front()
+    {
+        assert(size_);
+        return Buffer()[0];
+    }
+
     /// Return const first element.
-    const T& Front() const { assert(size_); return Buffer()[0]; }
+    const T& Front() const
+    {
+        assert(size_);
+        return Buffer()[0];
+    }
+
     /// Return last element.
-    T& Back() { assert(size_); return Buffer()[size_ - 1]; }
+    T& Back()
+    {
+        assert(size_);
+        return Buffer()[size_ - 1];
+    }
+
     /// Return const last element.
-    const T& Back() const { assert(size_); return Buffer()[size_ - 1]; }
+    const T& Back() const
+    {
+        assert(size_);
+        return Buffer()[size_ - 1];
+    }
+
     /// Return size of vector.
     unsigned Size() const { return size_; }
+
     /// Return capacity of vector.
     unsigned Capacity() const { return capacity_; }
+
     /// Return whether vector is empty.
     bool Empty() const { return size_ == 0; }
-    
+
 private:
     /// Return the buffer with right type.
     T* Buffer() const { return reinterpret_cast<T*>(buffer_); }
-    
-   /// Resize the vector and create/remove new elements as necessary.
+
+    /// Resize the vector and create/remove new elements as necessary.
     void Resize(unsigned newSize, const T* src)
     {
         // If size shrinks, destruct the removed elements
@@ -388,8 +435,8 @@ private:
                     while (capacity_ < newSize)
                         capacity_ += (capacity_ + 1) >> 1;
                 }
-                
-                unsigned char* newBuffer = AllocateBuffer(capacity_ * sizeof(T));
+
+                unsigned char* newBuffer = AllocateBuffer((unsigned)(capacity_ * sizeof(T)));
                 if (buffer_)
                 {
                     ConstructElements(reinterpret_cast<T*>(newBuffer), Buffer(), size_);
@@ -398,14 +445,14 @@ private:
                 }
                 buffer_ = newBuffer;
             }
-            
+
             // Initialize the new elements
             ConstructElements(Buffer() + size_, src, newSize - size_);
         }
-        
+
         size_ = newSize;
     }
-    
+
     /// Move a range of elements within the vector.
     void MoveRange(unsigned dest, unsigned src, unsigned count)
     {
@@ -421,7 +468,7 @@ private:
                 buffer[dest + i] = buffer[src + i];
         }
     }
-    
+
     /// Construct elements, optionally with source data.
     static void ConstructElements(T* dest, const T* src, unsigned count)
     {
@@ -436,14 +483,14 @@ private:
                 new(dest + i) T(*(src + i));
         }
     }
-    
+
     /// Copy elements from one buffer to another.
     static void CopyElements(T* dest, const T* src, unsigned count)
     {
         while (count--)
             *dest++ = *src++;
     }
-    
+
     // Call the elements' destructors.
     static void DestructElements(T* dest, unsigned count)
     {
@@ -462,81 +509,81 @@ public:
     typedef T ValueType;
     typedef RandomAccessIterator<T> Iterator;
     typedef RandomAccessConstIterator<T> ConstIterator;
-    
+
     /// Construct empty.
     PODVector()
     {
     }
-    
+
     /// Construct with initial size.
     explicit PODVector(unsigned size)
     {
         Resize(size);
     }
-    
+
     /// Construct with initial data.
     PODVector(const T* data, unsigned size)
     {
         Resize(size);
         CopyElements(Buffer(), data, size);
     }
-    
+
     /// Construct from another vector.
     PODVector(const PODVector<T>& vector)
     {
         *this = vector;
     }
-    
+
     /// Destruct.
     ~PODVector()
     {
         delete[] buffer_;
     }
-    
+
     /// Assign from another vector.
-    PODVector<T>& operator = (const PODVector<T>& rhs)
+    PODVector<T>& operator =(const PODVector<T>& rhs)
     {
         Resize(rhs.size_);
         CopyElements(Buffer(), rhs.Buffer(), rhs.size_);
         return *this;
     }
-    
+
     /// Add-assign an element.
-    PODVector<T>& operator += (const T& rhs)
+    PODVector<T>& operator +=(const T& rhs)
     {
         Push(rhs);
         return *this;
     }
-    
+
     /// Add-assign another vector.
-    PODVector<T>& operator += (const PODVector<T>& rhs)
+    PODVector<T>& operator +=(const PODVector<T>& rhs)
     {
         Push(rhs);
         return *this;
     }
-    
+
     /// Add an element.
-    PODVector<T> operator + (const T& rhs) const
+    PODVector<T> operator +(const T& rhs) const
     {
         PODVector<T> ret(*this);
         ret.Push(rhs);
         return ret;
     }
-    
+
     /// Add another vector.
-    PODVector<T> operator + (const PODVector<T>& rhs) const
+    PODVector<T> operator +(const PODVector<T>& rhs) const
     {
         PODVector<T> ret(*this);
         ret.Push(rhs);
         return ret;
     }
-    
+
     /// Test for equality with another vector.
-    bool operator == (const PODVector<T>& rhs) const
+    bool operator ==(const PODVector<T>& rhs) const
     {
         if (rhs.size_ != size_)
             return false;
-        
+
         T* buffer = Buffer();
         T* rhsBuffer = rhs.Buffer();
         for (unsigned i = 0; i < size_; ++i)
@@ -544,16 +591,16 @@ public:
             if (buffer[i] != rhsBuffer[i])
                 return false;
         }
-        
+
         return true;
     }
-    
+
     /// Test for inequality with another vector.
-    bool operator != (const PODVector<T>& rhs) const
+    bool operator !=(const PODVector<T>& rhs) const
     {
         if (rhs.size_ != size_)
             return true;
-        
+
         T* buffer = Buffer();
         T* rhsBuffer = rhs.Buffer();
         for (unsigned i = 0; i < size_; ++i)
@@ -561,19 +608,38 @@ public:
             if (buffer[i] != rhsBuffer[i])
                 return true;
         }
-        
+
         return false;
     }
-    
+
     /// Return element at index.
-    T& operator [] (unsigned index) { assert(index < size_); return Buffer()[index]; }
+    T& operator [](unsigned index)
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Return const element at index.
-    const T& operator [] (unsigned index) const { assert(index < size_); return Buffer()[index]; }
+    const T& operator [](unsigned index) const
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Return element at index.
-    T& At(unsigned index) { assert(index < size_); return Buffer()[index]; }
+    T& At(unsigned index)
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Return const element at index.
-    const T& At(unsigned index) const { assert(index < size_); return Buffer()[index]; }
-    
+    const T& At(unsigned index) const
+    {
+        assert(index < size_);
+        return Buffer()[index];
+    }
+
     /// Add an element at the end.
     void Push(const T& value)
     {
@@ -583,7 +649,7 @@ public:
             Resize(size_ + 1);
         Back() = value;
     }
-    
+
     /// Add another vector at the end.
     void Push(const PODVector<T>& vector)
     {
@@ -591,125 +657,125 @@ public:
         Resize(size_ + vector.size_);
         CopyElements(Buffer() + oldSize, vector.Buffer(), vector.size_);
     }
-    
+
     /// Remove the last element.
     void Pop()
     {
         if (size_)
             Resize(size_ - 1);
     }
-    
+
     /// Insert an element at position.
     void Insert(unsigned pos, const T& value)
     {
         if (pos > size_)
             pos = size_;
-        
+
         unsigned oldSize = size_;
         Resize(size_ + 1);
         MoveRange(pos + 1, pos, oldSize - pos);
         Buffer()[pos] = value;
     }
-    
+
     /// Insert another vector at position.
     void Insert(unsigned pos, const PODVector<T>& vector)
     {
         if (pos > size_)
             pos = size_;
-        
+
         unsigned oldSize = size_;
         Resize(size_ + vector.size_);
         MoveRange(pos + vector.size_, pos, oldSize - pos);
         CopyElements(Buffer() + pos, vector.Buffer(), vector.size_);
     }
-    
+
     /// Insert an element by iterator.
     Iterator Insert(const Iterator& dest, const T& value)
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
             pos = size_;
         Insert(pos, value);
-        
+
         return Begin() + pos;
     }
-    
+
     /// Insert a vector by iterator.
     Iterator Insert(const Iterator& dest, const PODVector<T>& vector)
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
             pos = size_;
         Insert(pos, vector);
-        
+
         return Begin() + pos;
     }
-    
+
     /// Insert a vector partially by iterators.
     Iterator Insert(const Iterator& dest, const ConstIterator& start, const ConstIterator& end)
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
             pos = size_;
         unsigned length = (unsigned)(end - start);
         Resize(size_ + length);
         MoveRange(pos + length, pos, size_ - pos - length);
         CopyElements(Buffer() + pos, &(*start), length);
-        
+
         return Begin() + pos;
     }
-    
+
     /// Insert elements.
     Iterator Insert(const Iterator& dest, const T* start, const T* end)
     {
-        unsigned pos = dest - Begin();
+        unsigned pos = (unsigned)(dest - Begin());
         if (pos > size_)
             pos = size_;
         unsigned length = (unsigned)(end - start);
         Resize(size_ + length);
         MoveRange(pos + length, pos, size_ - pos - length);
-        
+
         T* destPtr = Buffer() + pos;
         for (const T* i = start; i != end; ++i)
             *destPtr++ = *i;
-        
+
         return Begin() + pos;
     }
-    
+
     /// Erase a range of elements.
     void Erase(unsigned pos, unsigned length = 1)
     {
         // Return if the range is illegal
         if (!length || pos + length > size_)
             return;
-        
+
         MoveRange(pos, pos + length, size_ - pos - length);
         Resize(size_ - length);
     }
-    
+
     /// Erase an element by iterator. Return iterator to the next element.
     Iterator Erase(const Iterator& it)
     {
-        unsigned pos = it - Begin();
+        unsigned pos = (unsigned)(it - Begin());
         if (pos >= size_)
             return End();
         Erase(pos);
-        
+
         return Begin() + pos;
     }
-    
+
     /// Erase a range by iterators. Return iterator to the next element.
     Iterator Erase(const Iterator& start, const Iterator& end)
     {
-        unsigned pos = start - Begin();
+        unsigned pos = (unsigned)(start - Begin());
         if (pos >= size_)
             return End();
         unsigned length = (unsigned)(end - start);
         Erase(pos, length);
-        
+
         return Begin() + pos;
     }
-    
+
     /// Erase an element if found.
     bool Remove(const T& value)
     {
@@ -722,10 +788,10 @@ public:
         else
             return false;
     }
-    
+
     /// Clear the vector.
     void Clear() { Resize(0); }
-    
+
     /// Resize the vector.
     void Resize(unsigned newSize)
     {
@@ -738,8 +804,8 @@ public:
                 while (capacity_ < newSize)
                     capacity_ += (capacity_ + 1) >> 1;
             }
-            
-            unsigned char* newBuffer = AllocateBuffer(capacity_ * sizeof(T));
+
+            unsigned char* newBuffer = AllocateBuffer((unsigned)(capacity_ * sizeof(T)));
             // Move the data into the new buffer and delete the old
             if (buffer_)
             {
@@ -748,37 +814,37 @@ public:
             }
             buffer_ = newBuffer;
         }
-        
+
         size_ = newSize;
     }
-    
+
     /// Set new capacity.
     void Reserve(unsigned newCapacity)
     {
         if (newCapacity < size_)
             newCapacity = size_;
-        
+
         if (newCapacity != capacity_)
         {
             unsigned char* newBuffer = 0;
             capacity_ = newCapacity;
-            
+
             if (capacity_)
             {
-                newBuffer = AllocateBuffer(capacity_ * sizeof(T));
+                newBuffer = AllocateBuffer((unsigned)(capacity_ * sizeof(T)));
                 // Move the data into the new buffer
                 CopyElements(reinterpret_cast<T*>(newBuffer), Buffer(), size_);
             }
-            
+
             // Delete the old buffer
             delete[] buffer_;
             buffer_ = newBuffer;
         }
     }
-    
+
     /// Reallocate so that no extra memory is used.
     void Compact() { Reserve(size_); }
-    
+
     /// Return iterator to value, or to the end if not found.
     Iterator Find(const T& value)
     {
@@ -787,7 +853,7 @@ public:
             ++it;
         return it;
     }
-    
+
     /// Return const iterator to value, or to the end if not found.
     ConstIterator Find(const T& value) const
     {
@@ -796,43 +862,62 @@ public:
             ++it;
         return it;
     }
-    
+
     /// Return whether contains a specific value.
     bool Contains(const T& value) const { return Find(value) != End(); }
+
     /// Return iterator to the beginning.
     Iterator Begin() { return Iterator(Buffer()); }
+
     /// Return const iterator to the beginning.
     ConstIterator Begin() const { return ConstIterator(Buffer()); }
+
     /// Return iterator to the end.
     Iterator End() { return Iterator(Buffer() + size_); }
+
     /// Return const iterator to the end.
     ConstIterator End() const { return ConstIterator(Buffer() + size_); }
+
     /// Return first element.
     T& Front() { return Buffer()[0]; }
+
     /// Return const first element.
     const T& Front() const { return Buffer()[0]; }
+
     /// Return last element.
-    T& Back() { assert(size_); return Buffer()[size_ - 1]; }
+    T& Back()
+    {
+        assert(size_);
+        return Buffer()[size_ - 1];
+    }
+
     /// Return const last element.
-    const T& Back() const { assert(size_); return Buffer()[size_ - 1]; }
+    const T& Back() const
+    {
+        assert(size_);
+        return Buffer()[size_ - 1];
+    }
+
     /// Return number of elements.
     unsigned Size() const { return size_; }
+
     /// Return capacity of vector.
     unsigned Capacity() const { return capacity_; }
+
     /// Return whether vector is empty.
     bool Empty() const { return size_ == 0; }
-    
+
 private:
     /// Return the buffer with right type.
     T* Buffer() const { return reinterpret_cast<T*>(buffer_); }
-    
+
     /// Move a range of elements within the vector.
     void MoveRange(unsigned dest, unsigned src, unsigned count)
     {
         if (count)
             memmove(Buffer() + dest, Buffer() + src, count * sizeof(T));
     }
-    
+
     /// Copy elements from one buffer to another.
     static void CopyElements(T* dest, const T* src, unsigned count)
     {
@@ -847,13 +932,19 @@ namespace std
 {
 
 template <class T> typename Urho3D::Vector<T>::ConstIterator begin(const Urho3D::Vector<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::Vector<T>::ConstIterator end(const Urho3D::Vector<T>& v) { return v.End(); }
+
 template <class T> typename Urho3D::Vector<T>::Iterator begin(Urho3D::Vector<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::Vector<T>::Iterator end(Urho3D::Vector<T>& v) { return v.End(); }
 
 template <class T> typename Urho3D::PODVector<T>::ConstIterator begin(const Urho3D::PODVector<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::PODVector<T>::ConstIterator end(const Urho3D::PODVector<T>& v) { return v.End(); }
+
 template <class T> typename Urho3D::PODVector<T>::Iterator begin(Urho3D::PODVector<T>& v) { return v.Begin(); }
+
 template <class T> typename Urho3D::PODVector<T>::Iterator end(Urho3D::PODVector<T>& v) { return v.End(); }
 
 }

+ 2 - 0
Source/Urho3D/Container/VectorBase.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Container/VectorBase.h"
 
 #include "../DebugNew.h"

+ 140 - 45
Source/Urho3D/Container/VectorBase.h

@@ -22,6 +22,12 @@
 
 #pragma once
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 #include "../Container/Swap.h"
 
 namespace Urho3D
@@ -35,48 +41,90 @@ template <class T> struct RandomAccessIterator
         ptr_(0)
     {
     }
-    
+
     /// Construct with an object pointer.
     explicit RandomAccessIterator(T* ptr) :
         ptr_(ptr)
     {
     }
-    
+
     /// Point to the object.
-    T* operator -> () const { return ptr_; }
+    T* operator ->() const { return ptr_; }
+
     /// Dereference the object.
-    T& operator * () const { return *ptr_; }
+    T& operator *() const { return *ptr_; }
+
     /// Preincrement the pointer.
-    RandomAccessIterator<T>& operator ++ () { ++ptr_; return *this; }
+    RandomAccessIterator<T>& operator ++()
+    {
+        ++ptr_;
+        return *this;
+    }
+
     /// Postincrement the pointer.
-    RandomAccessIterator<T> operator ++ (int) { RandomAccessIterator<T> it = *this; ++ptr_; return it; }
+    RandomAccessIterator<T> operator ++(int)
+    {
+        RandomAccessIterator<T> it = *this;
+        ++ptr_;
+        return it;
+    }
+
     /// Predecrement the pointer.
-    RandomAccessIterator<T>& operator -- () { --ptr_; return *this; }
+    RandomAccessIterator<T>& operator --()
+    {
+        --ptr_;
+        return *this;
+    }
+
     /// Postdecrement the pointer.
-    RandomAccessIterator<T> operator -- (int) { RandomAccessIterator<T> it = *this; --ptr_; return it; }
+    RandomAccessIterator<T> operator --(int)
+    {
+        RandomAccessIterator<T> it = *this;
+        --ptr_;
+        return it;
+    }
+
     /// Add an offset to the pointer.
-    RandomAccessIterator<T>& operator += (int value) { ptr_ += value; return *this; }
+    RandomAccessIterator<T>& operator +=(int value)
+    {
+        ptr_ += value;
+        return *this;
+    }
+
     /// Subtract an offset from the pointer.
-    RandomAccessIterator<T>& operator -= (int value) { ptr_ -= value; return *this; }
+    RandomAccessIterator<T>& operator -=(int value)
+    {
+        ptr_ -= value;
+        return *this;
+    }
+
     /// Add an offset to the pointer.
-    RandomAccessIterator<T> operator + (int value) const { return RandomAccessIterator<T>(ptr_ + value); }
+    RandomAccessIterator<T> operator +(int value) const { return RandomAccessIterator<T>(ptr_ + value); }
+
     /// Subtract an offset from the pointer.
-    RandomAccessIterator<T> operator - (int value) const { return RandomAccessIterator<T>(ptr_ - value); }
+    RandomAccessIterator<T> operator -(int value) const { return RandomAccessIterator<T>(ptr_ - value); }
+
     /// Calculate offset to another iterator.
-    int operator - (const RandomAccessIterator& rhs) const { return (int)(ptr_ - rhs.ptr_); }
+    int operator -(const RandomAccessIterator& rhs) const { return (int)(ptr_ - rhs.ptr_); }
+
     /// Test for equality with another iterator.
-    bool operator == (const RandomAccessIterator& rhs) const { return ptr_ == rhs.ptr_; }
+    bool operator ==(const RandomAccessIterator& rhs) const { return ptr_ == rhs.ptr_; }
+
     /// Test for inequality with another iterator.
-    bool operator != (const RandomAccessIterator& rhs) const { return ptr_ != rhs.ptr_; }
+    bool operator !=(const RandomAccessIterator& rhs) const { return ptr_ != rhs.ptr_; }
+
     /// Test for less than with another iterator.
-    bool operator < (const RandomAccessIterator& rhs) const { return ptr_ < rhs.ptr_; }
+    bool operator <(const RandomAccessIterator& rhs) const { return ptr_ < rhs.ptr_; }
+
     /// Test for greater than with another iterator.
-    bool operator > (const RandomAccessIterator& rhs) const { return ptr_ > rhs.ptr_; }
+    bool operator >(const RandomAccessIterator& rhs) const { return ptr_ > rhs.ptr_; }
+
     /// Test for less than or equal with another iterator.
-    bool operator <= (const RandomAccessIterator& rhs) const { return ptr_ <= rhs.ptr_; }
+    bool operator <=(const RandomAccessIterator& rhs) const { return ptr_ <= rhs.ptr_; }
+
     /// Test for greater than or equal with another iterator.
-    bool operator >= (const RandomAccessIterator& rhs) const { return ptr_ >= rhs.ptr_; }
-    
+    bool operator >=(const RandomAccessIterator& rhs) const { return ptr_ >= rhs.ptr_; }
+
     /// Pointer.
     T* ptr_;
 };
@@ -89,56 +137,103 @@ template <class T> struct RandomAccessConstIterator
         ptr_(0)
     {
     }
-    
+
     /// Construct with an object pointer.
     explicit RandomAccessConstIterator(T* ptr) :
         ptr_(ptr)
     {
     }
-    
+
     /// Construct from a non-const iterator.
     RandomAccessConstIterator(const RandomAccessIterator<T>& rhs) :
         ptr_(rhs.ptr_)
     {
     }
-    
+
     /// Assign from a non-const iterator.
-    RandomAccessConstIterator<T>& operator = (const RandomAccessIterator<T>& rhs) { ptr_ = rhs.ptr_; return *this; }
+    RandomAccessConstIterator<T>& operator =(const RandomAccessIterator<T>& rhs)
+    {
+        ptr_ = rhs.ptr_;
+        return *this;
+    }
+
     /// Point to the object.
-    const T* operator -> () const { return ptr_; }
+    const T* operator ->() const { return ptr_; }
+
     /// Dereference the object.
-    const T& operator * () const { return *ptr_; }
+    const T& operator *() const { return *ptr_; }
+
     /// Preincrement the pointer.
-    RandomAccessConstIterator<T>& operator ++ () { ++ptr_; return *this; }
+    RandomAccessConstIterator<T>& operator ++()
+    {
+        ++ptr_;
+        return *this;
+    }
+
     /// Postincrement the pointer.
-    RandomAccessConstIterator<T> operator ++ (int) { RandomAccessConstIterator<T> it = *this; ++ptr_; return it; }
+    RandomAccessConstIterator<T> operator ++(int)
+    {
+        RandomAccessConstIterator<T> it = *this;
+        ++ptr_;
+        return it;
+    }
+
     /// Predecrement the pointer.
-    RandomAccessConstIterator<T>& operator -- () { --ptr_; return *this; }
+    RandomAccessConstIterator<T>& operator --()
+    {
+        --ptr_;
+        return *this;
+    }
+
     /// Postdecrement the pointer.
-    RandomAccessConstIterator<T> operator -- (int) { RandomAccessConstIterator<T> it = *this; --ptr_; return it; }
+    RandomAccessConstIterator<T> operator --(int)
+    {
+        RandomAccessConstIterator<T> it = *this;
+        --ptr_;
+        return it;
+    }
+
     /// Add an offset to the pointer.
-    RandomAccessConstIterator<T>& operator += (int value) { ptr_ += value; return *this; }
+    RandomAccessConstIterator<T>& operator +=(int value)
+    {
+        ptr_ += value;
+        return *this;
+    }
+
     /// Subtract an offset from the pointer.
-    RandomAccessConstIterator<T>& operator -= (int value) { ptr_ -= value; return *this; }
+    RandomAccessConstIterator<T>& operator -=(int value)
+    {
+        ptr_ -= value;
+        return *this;
+    }
+
     /// Add an offset to the pointer.
-    RandomAccessConstIterator<T> operator + (int value) const { return RandomAccessConstIterator<T>(ptr_ + value); }
+    RandomAccessConstIterator<T> operator +(int value) const { return RandomAccessConstIterator<T>(ptr_ + value); }
+
     /// Subtract an offset from the pointer.
-    RandomAccessConstIterator<T> operator - (int value) const { return RandomAccessConstIterator<T>(ptr_ - value); }
+    RandomAccessConstIterator<T> operator -(int value) const { return RandomAccessConstIterator<T>(ptr_ - value); }
+
     /// Calculate offset to another iterator.
-    int operator - (const RandomAccessConstIterator& rhs) const { return (int)(ptr_ - rhs.ptr_); }
+    int operator -(const RandomAccessConstIterator& rhs) const { return (int)(ptr_ - rhs.ptr_); }
+
     /// Test for equality with another iterator.
-    bool operator == (const RandomAccessConstIterator& rhs) const { return ptr_ == rhs.ptr_; }
+    bool operator ==(const RandomAccessConstIterator& rhs) const { return ptr_ == rhs.ptr_; }
+
     /// Test for inequality with another iterator.
-    bool operator != (const RandomAccessConstIterator& rhs) const { return ptr_ != rhs.ptr_; }
+    bool operator !=(const RandomAccessConstIterator& rhs) const { return ptr_ != rhs.ptr_; }
+
     /// Test for less than with another iterator.
-    bool operator < (const RandomAccessConstIterator& rhs) const { return ptr_ < rhs.ptr_; }
+    bool operator <(const RandomAccessConstIterator& rhs) const { return ptr_ < rhs.ptr_; }
+
     /// Test for greater than with another iterator.
-    bool operator > (const RandomAccessConstIterator& rhs) const { return ptr_ > rhs.ptr_; }
+    bool operator >(const RandomAccessConstIterator& rhs) const { return ptr_ > rhs.ptr_; }
+
     /// Test for less than or equal with another iterator.
-    bool operator <= (const RandomAccessConstIterator& rhs) const { return ptr_ <= rhs.ptr_; }
+    bool operator <=(const RandomAccessConstIterator& rhs) const { return ptr_ <= rhs.ptr_; }
+
     /// Test for greater than or equal with another iterator.
-    bool operator >= (const RandomAccessConstIterator& rhs) const { return ptr_ >= rhs.ptr_; }
-    
+    bool operator >=(const RandomAccessConstIterator& rhs) const { return ptr_ >= rhs.ptr_; }
+
     /// Pointer.
     T* ptr_;
 };
@@ -157,7 +252,7 @@ public:
         buffer_(0)
     {
     }
-    
+
     /// Swap with another vector.
     void Swap(VectorBase& rhs)
     {
@@ -165,10 +260,10 @@ public:
         Urho3D::Swap(capacity_, rhs.capacity_);
         Urho3D::Swap(buffer_, rhs.buffer_);
     }
-    
+
 protected:
     static unsigned char* AllocateBuffer(unsigned size);
-    
+
     /// Size of vector.
     unsigned size_;
     /// Buffer capacity.

+ 7 - 6
Source/Urho3D/Core/Attribute.h

@@ -71,7 +71,7 @@ struct AttributeInfo
         ptr_(0)
     {
     }
-    
+
     /// Construct offset attribute.
     AttributeInfo(VariantType type, const char* name, size_t offset, const Variant& defaultValue, unsigned mode) :
         type_(type),
@@ -83,7 +83,7 @@ struct AttributeInfo
         ptr_(0)
     {
     }
-    
+
     /// Construct offset enum attribute.
     AttributeInfo(const char* name, size_t offset, const char** enumNames, const Variant& defaultValue, unsigned mode) :
         type_(VAR_INT),
@@ -95,7 +95,7 @@ struct AttributeInfo
         ptr_(0)
     {
     }
-    
+
     /// Construct accessor attribute.
     AttributeInfo(VariantType type, const char* name, AttributeAccessor* accessor, const Variant& defaultValue, unsigned mode) :
         type_(type),
@@ -108,9 +108,10 @@ struct AttributeInfo
         ptr_(0)
     {
     }
-    
+
     /// Construct accessor enum attribute.
-    AttributeInfo(const char* name, AttributeAccessor* accessor, const char** enumNames, const Variant& defaultValue, unsigned mode) :
+    AttributeInfo(const char* name, AttributeAccessor* accessor, const char** enumNames, const Variant& defaultValue,
+        unsigned mode) :
         type_(VAR_INT),
         name_(name),
         offset_(0),
@@ -121,7 +122,7 @@ struct AttributeInfo
         ptr_(0)
     {
     }
-    
+
     /// Attribute type.
     VariantType type_;
     /// Name.

+ 8 - 2
Source/Urho3D/Core/Condition.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Core/Condition.h"
 
 #ifdef WIN32
@@ -32,6 +34,7 @@ namespace Urho3D
 {
 
 #ifdef WIN32
+
 Condition::Condition() :
     event_(0)
 {
@@ -53,7 +56,9 @@ void Condition::Wait()
 {
     WaitForSingleObject((HANDLE)event_, INFINITE);
 }
+
 #else
+
 Condition::Condition() :
     mutex_(new pthread_mutex_t),
     event_(new pthread_cond_t)
@@ -66,7 +71,7 @@ Condition::~Condition()
 {
     pthread_cond_t* cond = (pthread_cond_t*)event_;
     pthread_mutex_t* mutex = (pthread_mutex_t*)mutex_;
-    
+
     pthread_cond_destroy(cond);
     pthread_mutex_destroy(mutex);
     delete cond;
@@ -84,11 +89,12 @@ void Condition::Wait()
 {
     pthread_cond_t* cond = (pthread_cond_t*)event_;
     pthread_mutex_t* mutex = (pthread_mutex_t*)mutex_;
-    
+
     pthread_mutex_lock(mutex);
     pthread_cond_wait(cond, mutex);
     pthread_mutex_unlock(mutex);
 }
+
 #endif
 
 }

+ 12 - 6
Source/Urho3D/Core/Condition.h

@@ -22,6 +22,12 @@
 
 #pragma once
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 namespace Urho3D
 {
 
@@ -31,21 +37,21 @@ class URHO3D_API Condition
 public:
     /// Construct.
     Condition();
-    
+
     /// Destruct.
     ~Condition();
-    
+
     /// Set the condition. Will be automatically reset once a waiting thread wakes up.
     void Set();
-    
+
     /// Wait on the condition.
     void Wait();
-    
+
 private:
-    #ifndef WIN32
+#ifndef WIN32
     /// Mutex for the event, necessary for pthreads-based implementation.
     void* mutex_;
-    #endif
+#endif
     /// Operating system specific event.
     void* event_;
 };

+ 8 - 6
Source/Urho3D/Core/Context.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Core/Context.h"
 #include "../Core/Thread.h"
 
@@ -53,11 +55,11 @@ void RemoveNamedAttribute(HashMap<StringHash, Vector<AttributeInfo> >& attribute
 Context::Context() :
     eventHandler_(0)
 {
-    #ifdef ANDROID
+#ifdef ANDROID
     // Always reset the random seed on Android, as the Urho3D library might not be unloaded between runs
     SetRandomSeed(1);
-    #endif
-    
+#endif
+
     // Set the main thread ID (assuming the Context is created in it)
     Thread::SetMainThread();
 }
@@ -71,10 +73,10 @@ Context::~Context()
     RemoveSubsystem("Input");
     RemoveSubsystem("Renderer");
     RemoveSubsystem("Graphics");
-    
+
     subsystems_.Clear();
     factories_.Clear();
-    
+
     // Delete allocated event data maps
     for (PODVector<VariantMap*>::Iterator i = eventDataMaps_.Begin(); i != eventDataMaps_.End(); ++i)
         delete *i;
@@ -153,7 +155,7 @@ VariantMap& Context::GetEventDataMap()
     unsigned nestingLevel = eventSenders_.Size();
     while (eventDataMaps_.Size() < nestingLevel + 1)
         eventDataMaps_.Push(new VariantMap());
-    
+
     VariantMap& ret = *eventDataMaps_[nestingLevel];
     ret.Clear();
     return ret;

+ 25 - 2
Source/Urho3D/Core/Context.h

@@ -78,16 +78,22 @@ public:
 
     /// Return subsystem by type.
     Object* GetSubsystem(StringHash type) const;
+
     /// Return all subsystems.
     const HashMap<StringHash, SharedPtr<Object> >& GetSubsystems() const { return subsystems_; }
+
     /// Return all object factories.
     const HashMap<StringHash, SharedPtr<ObjectFactory> >& GetObjectFactories() const { return factories_; }
+
     /// Return all object categories.
     const HashMap<String, Vector<StringHash> >& GetObjectCategories() const { return objectCategories_; }
+
     /// Return active event sender. Null outside event handling.
     Object* GetEventSender() const;
+
     /// Return active event handler. Set by Object. Null outside event handling.
     EventHandler* GetEventHandler() const { return eventHandler_; }
+
     /// Return object type name from hash, or empty if unknown.
     const String& GetTypeName(StringHash objectType) const;
     /// Return a specific attribute description for an object, or null if not found.
@@ -145,10 +151,13 @@ private:
     void RemoveEventReceiver(Object* receiver, Object* sender, StringHash eventType);
     /// Remove event receiver from non-specific events.
     void RemoveEventReceiver(Object* receiver, StringHash eventType);
+
     /// Set current event handler. Called by Object.
     void SetEventHandler(EventHandler* handler) { eventHandler_ = handler; }
+
     /// Begin event send.
     void BeginSendEvent(Object* sender) { eventSenders_.Push(sender); }
+
     /// End event send. Clean up event receivers removed in the meanwhile.
     void EndSendEvent() { eventSenders_.Pop(); }
 
@@ -175,13 +184,27 @@ private:
 };
 
 template <class T> void Context::RegisterFactory() { RegisterFactory(new ObjectFactoryImpl<T>(this)); }
-template <class T> void Context::RegisterFactory(const char* category) { RegisterFactory(new ObjectFactoryImpl<T>(this), category); }
+
+template <class T> void Context::RegisterFactory(const char* category)
+{
+    RegisterFactory(new ObjectFactoryImpl<T>(this), category);
+}
+
 template <class T> void Context::RemoveSubsystem() { RemoveSubsystem(T::GetTypeStatic()); }
+
 template <class T> void Context::RegisterAttribute(const AttributeInfo& attr) { RegisterAttribute(T::GetTypeStatic(), attr); }
+
 template <class T> void Context::RemoveAttribute(const char* name) { RemoveAttribute(T::GetTypeStatic(), name); }
+
 template <class T, class U> void Context::CopyBaseAttributes() { CopyBaseAttributes(T::GetTypeStatic(), U::GetTypeStatic()); }
+
 template <class T> T* Context::GetSubsystem() const { return static_cast<T*>(GetSubsystem(T::GetTypeStatic())); }
+
 template <class T> AttributeInfo* Context::GetAttribute(const char* name) { return GetAttribute(T::GetTypeStatic(), name); }
-template <class T> void Context::UpdateAttributeDefaultValue(const char* name, const Variant& defaultValue) { UpdateAttributeDefaultValue(T::GetTypeStatic(), name, defaultValue); }
+
+template <class T> void Context::UpdateAttributeDefaultValue(const char* name, const Variant& defaultValue)
+{
+    UpdateAttributeDefaultValue(T::GetTypeStatic(), name, defaultValue);
+}
 
 }

+ 3 - 1
Source/Urho3D/Core/MiniDump.cpp

@@ -20,9 +20,10 @@
 // THE SOFTWARE.
 //
 
-
 #if defined(_MSC_VER) && defined(URHO3D_MINIDUMPS)
 
+#include "../Precompiled.h"
+
 #include "../Core/ProcessUtils.h"
 
 #include <cstdio>
@@ -83,4 +84,5 @@ URHO3D_API int WriteMiniDump(const char* applicationName, void* exceptionPointer
 }
 
 }
+
 #endif

+ 6 - 0
Source/Urho3D/Core/Mutex.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Core/Mutex.h"
 
 #ifdef WIN32
@@ -34,6 +36,7 @@ namespace Urho3D
 {
 
 #ifdef WIN32
+
 Mutex::Mutex() :
     handle_(new CRITICAL_SECTION)
 {
@@ -57,7 +60,9 @@ void Mutex::Release()
 {
     LeaveCriticalSection((CRITICAL_SECTION*)handle_);
 }
+
 #else
+
 Mutex::Mutex() :
     handle_(new pthread_mutex_t)
 {
@@ -85,6 +90,7 @@ void Mutex::Release()
 {
     pthread_mutex_unlock((pthread_mutex_t*)handle_);
 }
+
 #endif
 
 MutexLock::MutexLock(Mutex& mutex) :

+ 11 - 5
Source/Urho3D/Core/Mutex.h

@@ -22,6 +22,12 @@
 
 #pragma once
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 namespace Urho3D
 {
 
@@ -33,12 +39,12 @@ public:
     Mutex();
     /// Destruct.
     ~Mutex();
-    
+
     /// Acquire the mutex. Block if already acquired.
     void Acquire();
     /// Release the mutex.
     void Release();
-    
+
 private:
     /// Mutex handle.
     void* handle_;
@@ -52,13 +58,13 @@ public:
     MutexLock(Mutex& mutex);
     /// Destruct. Release the mutex.
     ~MutexLock();
-    
+
 private:
     /// Prevent copy construction.
     MutexLock(const MutexLock& rhs);
     /// Prevent assignment.
-    MutexLock& operator = (const MutexLock& rhs);
-    
+    MutexLock& operator =(const MutexLock& rhs);
+
     /// Mutex reference.
     Mutex& mutex_;
 };

+ 40 - 38
Source/Urho3D/Core/Object.cpp

@@ -20,9 +20,11 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Core/Context.h"
-#include "../IO/Log.h"
 #include "../Core/Thread.h"
+#include "../IO/Log.h"
 
 #include "../DebugNew.h"
 
@@ -47,7 +49,7 @@ void Object::OnEvent(Object* sender, StringHash eventType, VariantMap& eventData
     Context* context = context_;
     EventHandler* specific = 0;
     EventHandler* nonSpecific = 0;
-    
+
     EventHandler* handler = eventHandlers_.First();
     while (handler)
     {
@@ -63,7 +65,7 @@ void Object::OnEvent(Object* sender, StringHash eventType, VariantMap& eventData
         }
         handler = eventHandlers_.Next(handler);
     }
-    
+
     // Specific event handlers have priority, so if found, invoke first
     if (specific)
     {
@@ -72,7 +74,7 @@ void Object::OnEvent(Object* sender, StringHash eventType, VariantMap& eventData
         context->SetEventHandler(0);
         return;
     }
-    
+
     if (nonSpecific)
     {
         context->SetEventHandler(nonSpecific);
@@ -85,16 +87,16 @@ void Object::SubscribeToEvent(StringHash eventType, EventHandler* handler)
 {
     if (!handler)
         return;
-    
+
     handler->SetSenderAndEventType(0, eventType);
     // Remove old event handler first
     EventHandler* previous;
     EventHandler* oldHandler = FindSpecificEventHandler(0, eventType, &previous);
     if (oldHandler)
         eventHandlers_.Erase(oldHandler, previous);
-    
+
     eventHandlers_.InsertFront(handler);
-    
+
     context_->AddEventReceiver(this, eventType);
 }
 
@@ -106,16 +108,16 @@ void Object::SubscribeToEvent(Object* sender, StringHash eventType, EventHandler
         delete handler;
         return;
     }
-    
+
     handler->SetSenderAndEventType(sender, eventType);
     // Remove old event handler first
     EventHandler* previous;
     EventHandler* oldHandler = FindSpecificEventHandler(sender, eventType, &previous);
     if (oldHandler)
         eventHandlers_.Erase(oldHandler, previous);
-    
+
     eventHandlers_.InsertFront(handler);
-    
+
     context_->AddEventReceiver(this, sender, eventType);
 }
 
@@ -142,7 +144,7 @@ void Object::UnsubscribeFromEvent(Object* sender, StringHash eventType)
 {
     if (!sender)
         return;
-    
+
     EventHandler* previous;
     EventHandler* handler = FindSpecificEventHandler(sender, eventType, &previous);
     if (handler)
@@ -156,7 +158,7 @@ void Object::UnsubscribeFromEvents(Object* sender)
 {
     if (!sender)
         return;
-    
+
     for (;;)
     {
         EventHandler* previous;
@@ -193,18 +195,18 @@ void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& excepti
 {
     EventHandler* handler = eventHandlers_.First();
     EventHandler* previous = 0;
-    
+
     while (handler)
     {
         EventHandler* next = eventHandlers_.Next(handler);
-        
+
         if ((!onlyUserData || handler->GetUserData()) && !exceptions.Contains(handler->GetEventType()))
         {
             if (handler->GetSender())
                 context_->RemoveEventReceiver(this, handler->GetSender(), handler->GetEventType());
             else
                 context_->RemoveEventReceiver(this, handler->GetEventType());
-            
+
             eventHandlers_.Erase(handler, previous);
         }
         else
@@ -217,7 +219,7 @@ void Object::UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& excepti
 void Object::SendEvent(StringHash eventType)
 {
     VariantMap noEventData;
-    
+
     SendEvent(eventType, noEventData);
 }
 
@@ -228,14 +230,14 @@ void Object::SendEvent(StringHash eventType, VariantMap& eventData)
         LOGERROR("Sending events is only supported from the main thread");
         return;
     }
-    
+
     // Make a weak pointer to self to check for destruction during event handling
     WeakPtr<Object> self(this);
     Context* context = context_;
     HashSet<Object*> processed;
-    
+
     context->BeginSendEvent(this);
-    
+
     // Check first the specific event receivers
     const HashSet<Object*>* group = context->GetEventReceivers(this, eventType);
     if (group)
@@ -247,26 +249,26 @@ void Object::SendEvent(StringHash eventType, VariantMap& eventData)
             Object* next = 0;
             if (i != group->End())
                 next = *i;
-            
+
             unsigned oldSize = group->Size();
             receiver->OnEvent(this, eventType, eventData);
-            
+
             // If self has been destroyed as a result of event handling, exit
             if (self.Expired())
             {
                 context->EndSendEvent();
                 return;
             }
-            
+
             // If group has changed size during iteration (removed/added subscribers) try to recover
             /// \todo This is not entirely foolproof, as a subscriber could have been added to make up for the removed one
             if (group->Size() != oldSize)
                 i = group->Find(next);
-            
+
             processed.Insert(receiver);
         }
     }
-    
+
     // Then the non-specific receivers
     group = context->GetEventReceivers(eventType);
     if (group)
@@ -280,16 +282,16 @@ void Object::SendEvent(StringHash eventType, VariantMap& eventData)
                 Object* next = 0;
                 if (i != group->End())
                     next = *i;
-                
+
                 unsigned oldSize = group->Size();
                 receiver->OnEvent(this, eventType, eventData);
-                
+
                 if (self.Expired())
                 {
                     context->EndSendEvent();
                     return;
                 }
-                
+
                 if (group->Size() != oldSize)
                     i = group->Find(next);
             }
@@ -304,25 +306,25 @@ void Object::SendEvent(StringHash eventType, VariantMap& eventData)
                 Object* next = 0;
                 if (i != group->End())
                     next = *i;
-                
+
                 if (!processed.Contains(receiver))
                 {
                     unsigned oldSize = group->Size();
                     receiver->OnEvent(this, eventType, eventData);
-                    
+
                     if (self.Expired())
                     {
                         context->EndSendEvent();
                         return;
                     }
-                    
+
                     if (group->Size() != oldSize)
                         i = group->Find(next);
                 }
             }
         }
     }
-    
+
     context->EndSendEvent();
 }
 
@@ -376,7 +378,7 @@ EventHandler* Object::FindEventHandler(StringHash eventType, EventHandler** prev
     EventHandler* handler = eventHandlers_.First();
     if (previous)
         *previous = 0;
-    
+
     while (handler)
     {
         if (handler->GetEventType() == eventType)
@@ -385,7 +387,7 @@ EventHandler* Object::FindEventHandler(StringHash eventType, EventHandler** prev
             *previous = handler;
         handler = eventHandlers_.Next(handler);
     }
-    
+
     return 0;
 }
 
@@ -394,7 +396,7 @@ EventHandler* Object::FindSpecificEventHandler(Object* sender, EventHandler** pr
     EventHandler* handler = eventHandlers_.First();
     if (previous)
         *previous = 0;
-    
+
     while (handler)
     {
         if (handler->GetSender() == sender)
@@ -403,7 +405,7 @@ EventHandler* Object::FindSpecificEventHandler(Object* sender, EventHandler** pr
             *previous = handler;
         handler = eventHandlers_.Next(handler);
     }
-    
+
     return 0;
 }
 
@@ -412,7 +414,7 @@ EventHandler* Object::FindSpecificEventHandler(Object* sender, StringHash eventT
     EventHandler* handler = eventHandlers_.First();
     if (previous)
         *previous = 0;
-    
+
     while (handler)
     {
         if (handler->GetSender() == sender && handler->GetEventType() == eventType)
@@ -421,7 +423,7 @@ EventHandler* Object::FindSpecificEventHandler(Object* sender, StringHash eventT
             *previous = handler;
         handler = eventHandlers_.Next(handler);
     }
-    
+
     return 0;
 }
 
@@ -429,7 +431,7 @@ void Object::RemoveEventSender(Object* sender)
 {
     EventHandler* handler = eventHandlers_.First();
     EventHandler* previous = 0;
-    
+
     while (handler)
     {
         if (handler->GetSender() == sender)

+ 33 - 24
Source/Urho3D/Core/Object.h

@@ -48,15 +48,15 @@ class EventHandler;
 class URHO3D_API Object : public RefCounted
 {
     BASEOBJECT(Object);
-    
+
     friend class Context;
-    
+
 public:
     /// Construct.
     Object(Context* context);
     /// Destruct. Clean up self from event sender & receiver structures.
     virtual ~Object();
-    
+
     /// Return type hash.
     virtual Urho3D::StringHash GetType() const = 0;
     /// Return base class type hash.
@@ -65,7 +65,7 @@ public:
     virtual const Urho3D::String& GetTypeName() const = 0;
     /// Handle event.
     virtual void OnEvent(Object* sender, StringHash eventType, VariantMap& eventData);
-    
+
     /// Subscribe to an event that can be sent by any sender.
     void SubscribeToEvent(StringHash eventType, EventHandler* handler);
     /// Subscribe to a specific sender's event.
@@ -86,9 +86,10 @@ public:
     void SendEvent(StringHash eventType, VariantMap& eventData);
     /// Return a preallocated map for event data. Used for optimization to avoid constant re-allocation of event data maps.
     VariantMap& GetEventDataMap() const;
-    
+
     /// Return execution context.
     Context* GetContext() const { return context_; }
+
     /// Return subsystem by type.
     Object* GetSubsystem(StringHash type) const;
     /// Return active event sender. Null outside event handling.
@@ -99,17 +100,19 @@ public:
     bool HasSubscribedToEvent(StringHash eventType) const;
     /// Return whether has subscribed to a specific sender's event.
     bool HasSubscribedToEvent(Object* sender, StringHash eventType) const;
+
     /// Return whether has subscribed to any event.
     bool HasEventHandlers() const { return !eventHandlers_.Empty(); }
+
     /// Template version of returning a subsystem.
     template <class T> T* GetSubsystem() const;
     /// Return object category. Categories are (optionally) registered along with the object factory. Return an empty string if the object category is not registered.
     const String& GetCategory() const;
-    
+
 protected:
     /// Execution context.
     Context* context_;
-    
+
 private:
     /// Find the first event handler with no specific sender.
     EventHandler* FindEventHandler(StringHash eventType, EventHandler** previous = 0) const;
@@ -119,7 +122,7 @@ private:
     EventHandler* FindSpecificEventHandler(Object* sender, StringHash eventType, EventHandler** previous = 0) const;
     /// Remove event handlers related to a specific sender.
     void RemoveEventSender(Object* sender);
-    
+
     /// Event handlers. Sender is null for non-specific handlers.
     LinkedList<EventHandler> eventHandlers_;
 };
@@ -136,19 +139,22 @@ public:
     {
         assert(context_);
     }
-    
+
     /// Create an object. Implemented in templated subclasses.
     virtual SharedPtr<Object> CreateObject() = 0;
-    
+
     /// Return execution context.
     Context* GetContext() const { return context_; }
+
     /// Return type hash of objects created by this factory.
     StringHash GetType() const { return type_; }
+
     /// Return base type hash of objects created by this factory.
     StringHash GetBaseType() const { return baseType_; }
+
     /// Return type name of objects created by this factory.
     const String& GetTypeName() const { return typeName_; }
-    
+
 protected:
     /// Execution context.
     Context* context_;
@@ -172,7 +178,7 @@ public:
         baseType_ = T::GetBaseTypeStatic();
         typeName_ = T::GetTypeNameStatic();
     }
-    
+
     /// Create an object of the specific type.
     virtual SharedPtr<Object> CreateObject() { return SharedPtr<Object>(new T(context_)); }
 };
@@ -189,7 +195,7 @@ public:
     {
         assert(receiver_);
     }
-    
+
     /// Construct with specified receiver and userdata.
     EventHandler(Object* receiver, void* userData) :
         receiver_(receiver),
@@ -198,31 +204,34 @@ public:
     {
         assert(receiver_);
     }
-    
+
     /// Destruct.
-    virtual ~EventHandler() {}
-    
+    virtual ~EventHandler() { }
+
     /// Set sender and event type.
     void SetSenderAndEventType(Object* sender, StringHash eventType)
     {
         sender_ = sender;
         eventType_ = eventType;
     }
-    
+
     /// Invoke event handler function.
     virtual void Invoke(VariantMap& eventData) = 0;
     /// Return a unique copy of the event handler.
     virtual EventHandler* Clone() const = 0;
-    
+
     /// Return event receiver.
     Object* GetReceiver() const { return receiver_; }
+
     /// Return event sender. Null if the handler is non-specific.
     Object* GetSender() const { return sender_; }
+
     /// Return event type.
     const StringHash& GetEventType() const { return eventType_; }
+
     /// Return userdata.
     void* GetUserData() const { return userData_; }
-    
+
 protected:
     /// Event receiver.
     Object* receiver_;
@@ -239,7 +248,7 @@ template <class T> class EventHandlerImpl : public EventHandler
 {
 public:
     typedef void (T::*HandlerFunctionPtr)(StringHash, VariantMap&);
-    
+
     /// Construct with receiver and function pointers.
     EventHandlerImpl(T* receiver, HandlerFunctionPtr function) :
         EventHandler(receiver),
@@ -247,7 +256,7 @@ public:
     {
         assert(function_);
     }
-    
+
     /// Construct with receiver and function pointers and userdata.
     EventHandlerImpl(T* receiver, HandlerFunctionPtr function, void* userData) :
         EventHandler(receiver, userData),
@@ -255,20 +264,20 @@ public:
     {
         assert(function_);
     }
-    
+
     /// Invoke event handler function.
     virtual void Invoke(VariantMap& eventData)
     {
         T* receiver = static_cast<T*>(receiver_);
         (receiver->*function_)(eventType_, eventData);
     }
-    
+
     /// Return a unique copy of the event handler.
     virtual EventHandler* Clone() const
     {
         return new EventHandlerImpl(static_cast<T*>(receiver_), function_, userData_);
     }
-    
+
 private:
     /// Class-specific pointer to handler function.
     HandlerFunctionPtr function_;

+ 56 - 52
Source/Urho3D/Core/ProcessUtils.cpp

@@ -20,9 +20,9 @@
 // THE SOFTWARE.
 //
 
-#include "../Core/Mutex.h"
+#include "../Precompiled.h"
+
 #include "../Core/ProcessUtils.h"
-#include "../Math/MathDefs.h"
 
 #include <cstdio>
 #include <fcntl.h>
@@ -32,6 +32,7 @@
 #endif
 
 #if defined(IOS)
+#include "../Math/MathDefs.h"
 #include <mach/mach_host.h>
 #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN)
 #include <LibCpuId/libcpuid.h>
@@ -70,6 +71,7 @@ inline void SetFPUState(unsigned control)
 {
     __asm__ __volatile__ ("fldcw %0" : : "m" (control));
 }
+
 #endif
 
 #include "../DebugNew.h"
@@ -91,6 +93,7 @@ static void GetCPUData(host_basic_info_data_t* data)
     host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)data, &infoCount);
 }
 #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN)
+
 static void GetCPUData(struct cpu_id_t* data)
 {
     if (cpu_identify(0, data) < 0)
@@ -99,31 +102,32 @@ static void GetCPUData(struct cpu_id_t* data)
         data->num_cores = 1;
     }
 }
+
 #endif
 
 void InitFPU()
 {
-    #if !defined(URHO3D_LUAJIT) && !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(__x86_64__) && !defined(_M_AMD64) && !defined(EMSCRIPTEN)
+#if !defined(URHO3D_LUAJIT) && !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(__x86_64__) && !defined(_M_AMD64) && !defined(EMSCRIPTEN)
     // Make sure FPU is in round-to-nearest, single precision mode
     // This ensures Direct3D and OpenGL behave similarly, and all threads behave similarly
-    #ifdef _MSC_VER
+#ifdef _MSC_VER
     _controlfp(_RC_NEAR | _PC_24, _MCW_RC | _MCW_PC);
-    #else
+#else
     unsigned control = GetFPUState();
     control &= ~(FPU_CW_PREC_MASK | FPU_CW_ROUND_MASK);
     control |= (FPU_CW_PREC_SINGLE | FPU_CW_ROUND_NEAR);
     SetFPUState(control);
-    #endif
-    #endif
+#endif
+#endif
 }
 
 void ErrorDialog(const String& title, const String& message)
 {
-    #ifdef WIN32
+#ifdef WIN32
     MessageBoxW(0, WString(message).CString(), WString(title).CString(), 0);
-    #else
+#else
     PrintLine(message, true);
-    #endif
+#endif
 }
 
 void ErrorExit(const String& message, int exitCode)
@@ -136,7 +140,7 @@ void ErrorExit(const String& message, int exitCode)
 
 void OpenConsoleWindow()
 {
-    #ifdef WIN32
+#ifdef WIN32
     if (consoleOpened)
         return;
 
@@ -155,13 +159,13 @@ void OpenConsoleWindow()
     *stdin = *inFile;
 
     consoleOpened = true;
-    #endif
+#endif
 }
 
 void PrintUnicode(const String& str, bool error)
 {
-    #if !defined(ANDROID) && !defined(IOS)
-    #ifdef WIN32
+#if !defined(ANDROID) && !defined(IOS)
+#ifdef WIN32
     // If the output stream has been redirected, use fprintf instead of WriteConsoleW,
     // though it means that proper Unicode output will not work
     FILE* out = error ? stderr : stdout;
@@ -176,10 +180,10 @@ void PrintUnicode(const String& str, bool error)
         DWORD charsWritten;
         WriteConsoleW(stream, strW.CString(), strW.Length(), &charsWritten, 0);
     }
-    #else
+#else
     fprintf(error ? stderr : stdout, "%s", str.CString());
-    #endif
-    #endif
+#endif
+#endif
 }
 
 void PrintUnicodeLine(const String& str, bool error)
@@ -189,9 +193,9 @@ void PrintUnicodeLine(const String& str, bool error)
 
 void PrintLine(const String& str, bool error)
 {
-    #if !defined(ANDROID) && !defined(IOS)
-    fprintf(error ? stderr: stdout, "%s\n", str.CString());
-    #endif
+#if !defined(ANDROID) && !defined(IOS)
+    fprintf(error ? stderr : stdout, "%s\n", str.CString());
+#endif
 }
 
 const Vector<String>& ParseArguments(const String& cmdLine, bool skipFirstArgument)
@@ -274,12 +278,12 @@ const Vector<String>& GetArguments()
 String GetConsoleInput()
 {
     String ret;
-    #ifdef URHO3D_TESTING
+#ifdef URHO3D_TESTING
     // When we are running automated tests, reading the console may block. Just return empty in that case
     return ret;
-    #endif
+#endif
 
-    #ifdef WIN32
+#ifdef WIN32
     HANDLE input = GetStdHandle(STD_INPUT_HANDLE);
     HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
     if (input == INVALID_HANDLE_VALUE || output == INVALID_HANDLE_VALUE)
@@ -328,7 +332,7 @@ String GetConsoleInput()
             }
         }
     }
-    #elif !defined(ANDROID) && !defined(IOS)
+#elif !defined(ANDROID) && !defined(IOS)
     int flags = fcntl(STDIN_FILENO, F_GETFL);
     fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
     for (;;)
@@ -339,30 +343,30 @@ String GetConsoleInput()
         else
             break;
     }
-    #endif
+#endif
 
     return ret;
 }
 
 String GetPlatform()
 {
-    #if defined(ANDROID)
+#if defined(ANDROID)
     return "Android";
-    #elif defined(IOS)
+#elif defined(IOS)
     return "iOS";
-    #elif defined(WIN32)
+#elif defined(WIN32)
     return "Windows";
-    #elif defined(__APPLE__)
+#elif defined(__APPLE__)
     return "Mac OS X";
-    #elif defined(RPI)
+#elif defined(RPI)
     return "Raspberry Pi";
-    #elif defined(EMSCRIPTEN)
+#elif defined(EMSCRIPTEN)
     return "HTML5";
-    #elif defined(__linux__)
+#elif defined(__linux__)
     return "Linux";
-    #else
+#else
     return String::EMPTY;
-    #endif
+#endif
 }
 
 #if defined(ANDROID) || defined(RPI)
@@ -391,47 +395,47 @@ static unsigned GetArmCPUCount()
 
 unsigned GetNumPhysicalCPUs()
 {
-    #if defined(IOS)
+#if defined(IOS)
     host_basic_info_data_t data;
     GetCPUData(&data);
-    #if defined(TARGET_IPHONE_SIMULATOR)
+#if defined(TARGET_IPHONE_SIMULATOR)
     // Hardcoded to dual-core on simulator mode even if the host has more
     return Min(2, data.physical_cpu);
-    #else
+#else
     return data.physical_cpu;
-    #endif
-    #elif defined(ANDROID) || defined(RPI)
+#endif
+#elif defined(ANDROID) || defined(RPI)
     return GetArmCPUCount();
-    #elif !defined(EMSCRIPTEN)
+#elif !defined(EMSCRIPTEN)
     struct cpu_id_t data;
     GetCPUData(&data);
-    return data.num_cores;
-    #else
+    return (unsigned)data.num_cores;
+#else
     /// \todo Implement properly
     return 1;
-    #endif
+#endif
 }
 
 unsigned GetNumLogicalCPUs()
 {
-    #if defined(IOS)
+#if defined(IOS)
     host_basic_info_data_t data;
     GetCPUData(&data);
-    #if defined(TARGET_IPHONE_SIMULATOR)
+#if defined(TARGET_IPHONE_SIMULATOR)
     return Min(2, data.logical_cpu);
-    #else
+#else
     return data.logical_cpu;
-    #endif
-    #elif defined(ANDROID) || defined (RPI)
+#endif
+#elif defined(ANDROID) || defined (RPI)
     return GetArmCPUCount();
-    #elif !defined(EMSCRIPTEN)
+#elif !defined(EMSCRIPTEN)
     struct cpu_id_t data;
     GetCPUData(&data);
-    return data.num_logical_cpus;
-    #else
+    return (unsigned)data.num_logical_cpus;
+#else
     /// \todo Implement properly
     return 1;
-    #endif
+#endif
 }
 
 }

+ 23 - 21
Source/Urho3D/Core/Profiler.cpp

@@ -20,11 +20,12 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Core/CoreEvents.h"
 #include "../Core/Profiler.h"
 
 #include <cstdio>
-#include <cstring>
 
 #include "../DebugNew.h"
 
@@ -55,7 +56,7 @@ void Profiler::BeginFrame()
 {
     // End the previous frame if any
     EndFrame();
-    
+
     BeginBlock("RunFrame");
 }
 
@@ -82,33 +83,34 @@ void Profiler::BeginInterval()
 String Profiler::GetData(bool showUnused, bool showTotal, unsigned maxDepth) const
 {
     String output;
-    
+
     if (!showTotal)
-        output += String("Block                            Cnt     Avg      Max     Frame     Total\n\n");
+        output += "Block                            Cnt     Avg      Max     Frame     Total\n\n";
     else
     {
-        output += String("Block                                       Last frame                       Whole execution time\n\n");
-        output += String("                                 Cnt     Avg      Max      Total      Cnt      Avg       Max        Total\n\n");
+        output += "Block                                       Last frame                       Whole execution time\n\n";
+        output += "                                 Cnt     Avg      Max      Total      Cnt      Avg       Max        Total\n\n";
     }
-    
+
     if (!maxDepth)
         maxDepth = 1;
-    
+
     GetData(root_, output, 0, maxDepth, showUnused, showTotal);
-    
+
     return output;
 }
 
-void Profiler::GetData(ProfilerBlock* block, String& output, unsigned depth, unsigned maxDepth, bool showUnused, bool showTotal) const
+void Profiler::GetData(ProfilerBlock* block, String& output, unsigned depth, unsigned maxDepth, bool showUnused,
+    bool showTotal) const
 {
     char line[LINE_MAX_LENGTH];
     char indentedName[LINE_MAX_LENGTH];
-    
-    unsigned intervalFrames = Max(intervalFrames_, 1);
-    
+
+    unsigned intervalFrames = (unsigned)Max(intervalFrames_, 1);
+
     if (depth >= maxDepth)
         return;
-    
+
     // Do not print the root block as it does not collect any actual data
     if (block != root_)
     {
@@ -119,14 +121,14 @@ void Profiler::GetData(ProfilerBlock* block, String& output, unsigned depth, uns
             strcat(indentedName, block->name_);
             indentedName[strlen(indentedName)] = ' ';
             indentedName[NAME_MAX_LENGTH] = 0;
-            
+
             if (!showTotal)
             {
                 float avg = (block->intervalCount_ ? block->intervalTime_ / block->intervalCount_ : 0.0f) / 1000.0f;
                 float max = block->intervalMaxTime_ / 1000.0f;
                 float frame = block->intervalTime_ / intervalFrames / 1000.0f;
                 float all = block->intervalTime_ / 1000.0f;
-        
+
                 sprintf(line, "%s %5u %8.3f %8.3f %8.3f %9.3f\n", indentedName, Min(block->intervalCount_, 99999),
                     avg, max, frame, all);
             }
@@ -135,21 +137,21 @@ void Profiler::GetData(ProfilerBlock* block, String& output, unsigned depth, uns
                 float avg = (block->frameCount_ ? block->frameTime_ / block->frameCount_ : 0.0f) / 1000.0f;
                 float max = block->frameMaxTime_ / 1000.0f;
                 float all = block->frameTime_ / 1000.0f;
-                
+
                 float totalAvg = (block->totalCount_ ? block->totalTime_ / block->totalCount_ : 0.0f) / 1000.0f;
                 float totalMax = block->totalMaxTime_ / 1000.0f;
                 float totalAll = block->totalTime_ / 1000.0f;
-                
+
                 sprintf(line, "%s %5u %8.3f %8.3f %9.3f  %7u %9.3f %9.3f %11.3f\n", indentedName, Min(block->frameCount_, 99999),
                     avg, max, all, Min(block->totalCount_, 99999), totalAvg, totalMax, totalAll);
             }
-            
+
             output += String(line);
         }
-        
+
         ++depth;
     }
-    
+
     for (PODVector<ProfilerBlock*>::ConstIterator i = block->children_.Begin(); i != block->children_.End(); ++i)
         GetData(*i, output, depth, maxDepth, showUnused, showTotal);
 }

+ 13 - 8
Source/Urho3D/Core/Spline.cpp

@@ -20,8 +20,10 @@
 // THE SOFTWARE.
 //
 
-#include "../IO/Log.h"
+#include "../Precompiled.h"
+
 #include "../Core/Spline.h"
+#include "../IO/Log.h"
 
 namespace Urho3D
 {
@@ -84,22 +86,24 @@ void Spline::SetKnot(const Variant& knot, unsigned index)
         else if (knots_.Empty())
             knots_.Push(knot);
         else
-            LOGERRORF("Attempted to set a Spline's Knot value of type %s where elements are already using %s", knot.GetTypeName().CString(), knots_[0].GetTypeName().CString());
+            LOGERRORF("Attempted to set a Spline's Knot value of type %s where elements are already using %s",
+                knot.GetTypeName().CString(), knots_[0].GetTypeName().CString());
     }
 }
 
-void Spline::AddKnot(const Variant& knot) 
-{ 
+void Spline::AddKnot(const Variant& knot)
+{
     if (knots_.Size() > 0 && knots_[0].GetType() == knot.GetType())
         knots_.Push(knot);
     else if (knots_.Empty())
         knots_.Push(knot);
     else
-        LOGERRORF("Attempted to add Knot to Spline of type %s where elements are already using %s", knot.GetTypeName().CString(), knots_[0].GetTypeName().CString());
+        LOGERRORF("Attempted to add Knot to Spline of type %s where elements are already using %s", knot.GetTypeName().CString(),
+            knots_[0].GetTypeName().CString());
 }
 
-void Spline::AddKnot(const Variant& knot, unsigned index) 
-{ 
+void Spline::AddKnot(const Variant& knot, unsigned index)
+{
     if (index > knots_.Size())
         index = knots_.Size();
 
@@ -108,7 +112,8 @@ void Spline::AddKnot(const Variant& knot, unsigned index)
     else if (knots_.Empty())
         knots_.Push(knot);
     else
-        LOGERRORF("Attempted to add Knot to Spline of type %s where elements are already using %s", knot.GetTypeName().CString(), knots_[0].GetTypeName().CString());
+        LOGERRORF("Attempted to add Knot to Spline of type %s where elements are already using %s", knot.GetTypeName().CString(),
+            knots_[0].GetTypeName().CString());
 }
 
 Variant Spline::BezierInterpolation(const Vector<Variant>& knots, float t) const

+ 15 - 4
Source/Urho3D/Core/Spline.h

@@ -22,8 +22,8 @@
 
 #pragma once
 
-#include "../Math/Color.h"
 #include "../Core/Variant.h"
+#include "../Math/Color.h"
 #include "../Math/Vector2.h"
 #include "../Math/Vector3.h"
 #include "../Math/Vector4.h"
@@ -50,44 +50,55 @@ public:
     Spline(const Spline& rhs);
 
     /// Copy operator.
-    void operator= (const Spline& rhs)
+    void operator =(const Spline& rhs)
     {
         knots_ = rhs.knots_;
         interpolationMode_ = rhs.interpolationMode_;
     }
+
     /// Equality operator.
-    bool operator== (const Spline& rhs) const
+    bool operator ==(const Spline& rhs) const
     {
         return (knots_ == rhs.knots_ && interpolationMode_ == rhs.interpolationMode_);
     }
+
     /// Non Equality operator.
-    bool operator!= (const Spline& rhs) const
+    bool operator !=(const Spline& rhs) const
     {
         return !(*this == rhs);
     }
 
     /// Return the ImplementationMode.
     InterpolationMode GetInterpolationMode() const { return interpolationMode_; }
+
     /// Return the Knots of the Spline.
     const VariantVector& GetKnots() const { return knots_; }
+
     /// Return the Knot at the specific index.
     Variant GetKnot(unsigned index) const { return knots_[index]; }
+
     /// Return the T of the point of the Spline at f from 0.f - 1.f.
     Variant GetPoint(float f) const;
+
     /// Set the InterpolationMode of the Spline.
     void SetInterpolationMode(InterpolationMode interpolationMode) { interpolationMode_ = interpolationMode; }
+
     /// Set the Knots of the Spline.
     void SetKnots(const Vector<Variant>& knots) { knots_ = knots; }
+
     /// Set the Knot value of an existing Knot.
     void SetKnot(const Variant& knot, unsigned index);
     /// Add a Knot to the end of the Spline.
     void AddKnot(const Variant& knot);
     /// Add a Knot to the Spline at a specific index.
     void AddKnot(const Variant& knot, unsigned index);
+
     /// Remove the last Knot on the Spline.
     void RemoveKnot() { knots_.Pop(); }
+
     /// Remove the Knot at the specific index.
     void RemoveKnot(unsigned index) { knots_.Erase(index); }
+
     /// Clear the Spline.
     void Clear() { knots_.Clear(); }
 

+ 19 - 13
Source/Urho3D/Core/StringUtils.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Core/StringUtils.h"
 
 #include <cstdio>
@@ -91,7 +93,7 @@ bool ToBool(const char* source)
 
     for (unsigned i = 0; i < length; ++i)
     {
-        char c = tolower(source[i]);
+        char c = (char)tolower(source[i]);
         if (c == 't' || c == 'y' || c == '1')
             return true;
         else if (c != ' ' && c != '\t')
@@ -112,7 +114,7 @@ int ToInt(const char* source)
         return 0;
 
     // Explicitly ask for base 10 to prevent source starts with '0' or '0x' from being converted to base 8 or base 16, respectively
-    return strtol(source, 0, 10);
+    return (int)strtol(source, 0, 10);
 }
 
 unsigned ToUInt(const String& source)
@@ -125,7 +127,7 @@ unsigned ToUInt(const char* source)
     if (!source)
         return 0;
 
-    return strtoul(source, 0, 10);
+    return (unsigned)strtoul(source, 0, 10);
 }
 
 float ToFloat(const String& source)
@@ -395,6 +397,10 @@ Variant ToVectorVariant(const char* source)
     case 16:
         ret.FromString(VAR_MATRIX4, source);
         break;
+
+    default:
+        assert(false);  // Should not get here
+        break;
     }
 
     return ret;
@@ -538,14 +544,14 @@ void BufferToString(String& dest, const void* data, unsigned size)
         }
         else if (bytes[i] < 100)
         {
-            dest[index++] = '0' + bytes[i] / 10;
-            dest[index++] = '0' + bytes[i] % 10;
+            dest[index++] = (char)('0' + bytes[i] / 10);
+            dest[index++] = (char)('0' + bytes[i] % 10);
         }
         else
         {
-            dest[index++] = '0' + bytes[i] / 100;
-            dest[index++] = '0' + bytes[i] % 100 / 10;
-            dest[index++] = '0' + bytes[i] % 10;
+            dest[index++] = (char)('0' + bytes[i] / 100);
+            dest[index++] = (char)('0' + bytes[i] % 100 / 10);
+            dest[index++] = (char)('0' + bytes[i] % 10);
         }
     }
 }
@@ -577,7 +583,7 @@ void StringToBuffer(PODVector<unsigned char>& dest, const char* source)
         if (inSpace && *ptr != ' ')
         {
             inSpace = false;
-            value = *ptr - '0';
+            value = (unsigned)(*ptr - '0');
         }
         else if (!inSpace && *ptr != ' ')
         {
@@ -586,7 +592,7 @@ void StringToBuffer(PODVector<unsigned char>& dest, const char* source)
         }
         else if (!inSpace && *ptr == ' ')
         {
-            dest[index++] = value;
+            dest[index++] = (unsigned char)value;
             inSpace = true;
         }
 
@@ -595,7 +601,7 @@ void StringToBuffer(PODVector<unsigned char>& dest, const char* source)
 
     // Write the final value
     if (!inSpace && index < size)
-        dest[index] = value;
+        dest[index] = (unsigned char)value;
 }
 
 unsigned GetStringListIndex(const String& value, const String* strings, unsigned defaultIndex, bool caseSensitive)
@@ -653,12 +659,12 @@ bool IsDigit(unsigned ch)
 
 unsigned ToUpper(unsigned ch)
 {
-    return toupper(ch);
+    return (unsigned)toupper(ch);
 }
 
 unsigned ToLower(unsigned ch)
 {
-    return tolower(ch);
+    return (unsigned)tolower(ch);
 }
 
 }

+ 27 - 23
Source/Urho3D/Core/Thread.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Core/Thread.h"
 
 #ifdef WIN32
@@ -34,24 +36,28 @@ namespace Urho3D
 {
 
 #ifdef WIN32
+
 DWORD WINAPI ThreadFunctionStatic(void* data)
 {
     Thread* thread = static_cast<Thread*>(data);
     thread->ThreadFunction();
     return 0;
 }
+
 #else
+
 void* ThreadFunctionStatic(void* data)
 {
     Thread* thread = static_cast<Thread*>(data);
     thread->ThreadFunction();
 #ifdef EMSCRIPTEN
-// note: emscripten doesn't have this function but doesn't use threading anyway
-// so #ifdef it out to prevent linker warnings
+    // note: emscripten doesn't have this function but doesn't use threading anyway
+    // so #ifdef it out to prevent linker warnings
     pthread_exit((void*)0);
 #endif
     return 0;
 }
+
 #endif
 
 ThreadID Thread::mainThreadID;
@@ -72,20 +78,19 @@ bool Thread::Run()
     // Check if already running
     if (handle_)
         return false;
-    
+
     shouldRun_ = true;
-    #ifdef WIN32
+#ifdef WIN32
     handle_ = CreateThread(0, 0, ThreadFunctionStatic, this, 0, 0);
-//    #else
-    #elif !defined(EMSCRIPTEN)
-// note: emscripten doesn't have this function but doesn't use
-// threading anyway so #ifdef it out to prevent linker warnings
+#elif !defined(EMSCRIPTEN)
+    // note: emscripten doesn't have this function but doesn't use
+    // threading anyway so #ifdef it out to prevent linker warnings
     handle_ = new pthread_t;
     pthread_attr_t type;
     pthread_attr_init(&type);
     pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE);
     pthread_create((pthread_t*)handle_, &type, ThreadFunctionStatic, this);
-    #endif
+#endif
     return handle_ != 0;
 }
 
@@ -94,34 +99,33 @@ void Thread::Stop()
     // Check if already stopped
     if (!handle_)
         return;
-    
+
     shouldRun_ = false;
-    #ifdef WIN32
+#ifdef WIN32
     WaitForSingleObject((HANDLE)handle_, INFINITE);
     CloseHandle((HANDLE)handle_);
-//    #else
-    #elif !defined(EMSCRIPTEN)
- // note: emscripten doesn't have this function but doesn't use
- // threading anyway so #ifdef it out to prevent linker warnings
+#elif !defined(EMSCRIPTEN)
+    // note: emscripten doesn't have this function but doesn't use
+    // threading anyway so #ifdef it out to prevent linker warnings
     pthread_t* thread = (pthread_t*)handle_;
     if (thread)
         pthread_join(*thread, 0);
     delete thread;
-    #endif
+#endif
     handle_ = 0;
 }
 
 void Thread::SetPriority(int priority)
 {
-    #ifdef WIN32
+#ifdef WIN32
     if (handle_)
         SetThreadPriority((HANDLE)handle_, priority);
-    #endif
-    #if defined(__linux__) && !defined(ANDROID) && !defined(EMSCRIPTEN)
+#endif
+#if defined(__linux__) && !defined(ANDROID) && !defined(EMSCRIPTEN)
     pthread_t* thread = (pthread_t*)handle_;
     if (thread)
         pthread_setschedprio(*thread, priority);
-    #endif
+#endif
 }
 
 void Thread::SetMainThread()
@@ -131,11 +135,11 @@ void Thread::SetMainThread()
 
 ThreadID Thread::GetCurrentThreadID()
 {
-    #ifdef WIN32
+#ifdef WIN32
     return GetCurrentThreadId();
-    #else
+#else
     return pthread_self();
-    #endif
+#endif
 }
 
 bool Thread::IsMainThread()

+ 11 - 5
Source/Urho3D/Core/Thread.h

@@ -22,6 +22,12 @@
 
 #pragma once
 
+#ifdef URHO3D_IS_BUILDING
+#include "Urho3D.h"
+#else
+#include <Urho3D/Urho3D.h>
+#endif
+
 #ifndef WIN32
 #include <pthread.h>
 typedef pthread_t ThreadID;
@@ -40,17 +46,17 @@ public:
     Thread();
     /// Destruct. If running, stop and wait for thread to finish.
     virtual ~Thread();
-    
+
     /// The function to run in the thread.
     virtual void ThreadFunction() = 0;
-    
+
     /// Start running the thread. Return true if successful, or false if already running or if can not create the thread.
     bool Run();
     /// Set the running flag to false and wait for the thread to finish.
     void Stop();
     /// Set thread priority. The thread must have been started first.
     void SetPriority(int priority);
-    
+
     /// Return whether thread exists.
     bool IsStarted() const { return handle_ != 0; }
 
@@ -60,13 +66,13 @@ public:
     static ThreadID GetCurrentThreadID();
     /// Return whether is executing in the main thread.
     static bool IsMainThread();
-    
+
 protected:
     /// Thread handle.
     void* handle_;
     /// Running flag.
     volatile bool shouldRun_;
-    
+
     /// Main thread's thread ID.
     static ThreadID mainThreadID;
 };

+ 25 - 24
Source/Urho3D/Core/Timer.cpp

@@ -20,9 +20,10 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Core/CoreEvents.h"
 #include "../Core/Profiler.h"
-#include "../Core/Timer.h"
 
 #include <ctime>
 
@@ -48,17 +49,17 @@ Time::Time(Context* context) :
     timeStep_(0.0f),
     timerPeriod_(0)
 {
-    #ifdef WIN32
+#ifdef WIN32
     LARGE_INTEGER frequency;
     if (QueryPerformanceFrequency(&frequency))
     {
         HiresTimer::frequency = frequency.QuadPart;
         HiresTimer::supported = true;
     }
-    #else
+#else
     HiresTimer::frequency = 1000000;
     HiresTimer::supported = true;
-    #endif
+#endif
 }
 
 Time::~Time()
@@ -107,7 +108,7 @@ void Time::EndFrame()
 
 void Time::SetTimerPeriod(unsigned mSec)
 {
-    #ifdef WIN32
+#ifdef WIN32
     if (timerPeriod_ > 0)
         timeEndPeriod(timerPeriod_);
 
@@ -115,7 +116,7 @@ void Time::SetTimerPeriod(unsigned mSec)
 
     if (timerPeriod_ > 0)
         timeBeginPeriod(timerPeriod_);
-    #endif
+#endif
 }
 
 float Time::GetElapsedTime()
@@ -125,13 +126,13 @@ float Time::GetElapsedTime()
 
 unsigned Time::GetSystemTime()
 {
-    #ifdef WIN32
+#ifdef WIN32
     unsigned currentTime = (unsigned)timeGetTime();
-    #else
+#else
     struct timeval time;
     gettimeofday(&time, NULL);
     unsigned currentTime = (unsigned)(time.tv_sec * 1000 + time.tv_usec / 1000);
-    #endif
+#endif
 
     return currentTime;
 }
@@ -151,11 +152,11 @@ String Time::GetTimeStamp()
 
 void Time::Sleep(unsigned mSec)
 {
-    #ifdef WIN32
+#ifdef WIN32
     ::Sleep(mSec);
-    #else
+#else
     usleep(mSec * 1000);
-    #endif
+#endif
 }
 
 Timer::Timer()
@@ -165,13 +166,13 @@ Timer::Timer()
 
 unsigned Timer::GetMSec(bool reset)
 {
-    #ifdef WIN32
+#ifdef WIN32
     unsigned currentTime = (unsigned)timeGetTime();
-    #else
+#else
     struct timeval time;
     gettimeofday(&time, NULL);
     unsigned currentTime = (unsigned)(time.tv_sec * 1000 + time.tv_usec / 1000);
-    #endif
+#endif
 
     unsigned elapsedTime = currentTime - startTime_;
     if (reset)
@@ -182,13 +183,13 @@ unsigned Timer::GetMSec(bool reset)
 
 void Timer::Reset()
 {
-    #ifdef WIN32
+#ifdef WIN32
     startTime_ = (unsigned)timeGetTime();
-    #else
+#else
     struct timeval time;
     gettimeofday(&time, NULL);
     startTime_ = (unsigned)(time.tv_sec * 1000 + time.tv_usec / 1000);
-    #endif
+#endif
 }
 
 HiresTimer::HiresTimer()
@@ -200,7 +201,7 @@ long long HiresTimer::GetUSec(bool reset)
 {
     long long currentTime;
 
-    #ifdef WIN32
+#ifdef WIN32
     if (supported)
     {
         LARGE_INTEGER counter;
@@ -209,11 +210,11 @@ long long HiresTimer::GetUSec(bool reset)
     }
     else
         currentTime = timeGetTime();
-    #else
+#else
     struct timeval time;
     gettimeofday(&time, NULL);
     currentTime = time.tv_sec * 1000000LL + time.tv_usec;
-    #endif
+#endif
 
     long long elapsedTime = currentTime - startTime_;
 
@@ -229,7 +230,7 @@ long long HiresTimer::GetUSec(bool reset)
 
 void HiresTimer::Reset()
 {
-    #ifdef WIN32
+#ifdef WIN32
     if (supported)
     {
         LARGE_INTEGER counter;
@@ -238,11 +239,11 @@ void HiresTimer::Reset()
     }
     else
         startTime_ = timeGetTime();
-    #else
+#else
     struct timeval time;
     gettimeofday(&time, NULL);
     startTime_ = time.tv_sec * 1000000LL + time.tv_usec;
-    #endif
+#endif
 }
 
 }

+ 17 - 13
Source/Urho3D/Core/Timer.h

@@ -33,12 +33,12 @@ class URHO3D_API Timer
 public:
     /// Construct. Get the starting clock value.
     Timer();
-    
+
     /// Return elapsed milliseconds and optionally reset.
     unsigned GetMSec(bool reset);
     /// Reset the timer.
     void Reset();
-    
+
 private:
     /// Starting clock value in milliseconds.
     unsigned startTime_;
@@ -48,26 +48,27 @@ private:
 class URHO3D_API HiresTimer
 {
     friend class Time;
-    
+
 public:
     /// Construct. Get the starting high-resolution clock value.
     HiresTimer();
-    
+
     /// Return elapsed microseconds and optionally reset.
     long long GetUSec(bool reset);
     /// Reset the timer.
     void Reset();
-    
+
     /// Return if high-resolution timer is supported.
     static bool IsSupported() { return supported; }
+
     /// Return high-resolution timer frequency if supported.
     static long long GetFrequency() { return frequency; }
-    
+
 private:
     /// Starting clock value in CPU ticks.
     long long startTime_;
-    
-     /// High-resolution timer support flag.
+
+    /// High-resolution timer support flag.
     static bool supported;
     /// High-resolution timer frequency.
     static long long frequency;
@@ -77,29 +78,32 @@ private:
 class URHO3D_API Time : public Object
 {
     OBJECT(Time);
-    
+
 public:
     /// Construct.
     Time(Context* context);
     /// Destruct. Reset the low-resolution timer period if set.
     virtual ~Time();
-    
+
     /// Begin new frame, with (last) frame duration in seconds and send frame start event.
     void BeginFrame(float timeStep);
     /// End frame. Increment total time and send frame end event.
     void EndFrame();
     /// Set the low-resolution timer period in milliseconds. 0 resets to the default period.
     void SetTimerPeriod(unsigned mSec);
-    
+
     /// Return frame number, starting from 1 once BeginFrame() is called for the first time.
     unsigned GetFrameNumber() const { return frameNumber_; }
+
     /// Return current frame timestep as seconds.
     float GetTimeStep() const { return timeStep_; }
+
     /// Return current low-resolution timer period in milliseconds.
     unsigned GetTimerPeriod() const { return timerPeriod_; }
+
     /// Return elapsed time from program start as seconds.
     float GetElapsedTime();
-    
+
     /// Get system time as milliseconds.
     static unsigned GetSystemTime();
     /// Get system time as seconds since 1.1.1970.
@@ -108,7 +112,7 @@ public:
     static String GetTimeStamp();
     /// Sleep for a number of milliseconds.
     static void Sleep(unsigned mSec);
-    
+
 private:
     /// Elapsed time since program start.
     Timer elapsedTime_;

+ 91 - 88
Source/Urho3D/Core/Variant.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Core/StringUtils.h"
 
 #include <cstring>
@@ -62,7 +64,7 @@ static const char* typeNames[] =
     0
 };
 
-Variant& Variant::operator = (const Variant& rhs)
+Variant& Variant::operator =(const Variant& rhs)
 {
     SetType(rhs.GetType());
 
@@ -95,19 +97,19 @@ Variant& Variant::operator = (const Variant& rhs)
     case VAR_PTR:
         *(reinterpret_cast<WeakPtr<RefCounted>*>(&value_)) = *(reinterpret_cast<const WeakPtr<RefCounted>*>(&rhs.value_));
         break;
-        
+
     case VAR_MATRIX3:
         *(reinterpret_cast<Matrix3*>(value_.ptr_)) = *(reinterpret_cast<const Matrix3*>(rhs.value_.ptr_));
         break;
-        
+
     case VAR_MATRIX3X4:
         *(reinterpret_cast<Matrix3x4*>(value_.ptr_)) = *(reinterpret_cast<const Matrix3x4*>(rhs.value_.ptr_));
         break;
-        
+
     case VAR_MATRIX4:
         *(reinterpret_cast<Matrix4*>(value_.ptr_)) = *(reinterpret_cast<const Matrix4*>(rhs.value_.ptr_));
         break;
-        
+
     default:
         value_ = rhs.value_;
         break;
@@ -116,13 +118,13 @@ Variant& Variant::operator = (const Variant& rhs)
     return *this;
 }
 
-bool Variant::operator == (const Variant& rhs) const
+bool Variant::operator ==(const Variant& rhs) const
 {
     if (type_ == VAR_VOIDPTR || type_ == VAR_PTR)
         return GetVoidPtr() == rhs.GetVoidPtr();
     else if (type_ != rhs.type_)
         return false;
-    
+
     switch (type_)
     {
     case VAR_INT:
@@ -150,7 +152,8 @@ bool Variant::operator == (const Variant& rhs) const
         return *(reinterpret_cast<const String*>(&value_)) == *(reinterpret_cast<const String*>(&rhs.value_));
 
     case VAR_BUFFER:
-        return *(reinterpret_cast<const PODVector<unsigned char>*>(&value_)) == *(reinterpret_cast<const PODVector<unsigned char>*>(&rhs.value_));
+        return *(reinterpret_cast<const PODVector<unsigned char>*>(&value_)) ==
+               *(reinterpret_cast<const PODVector<unsigned char>*>(&rhs.value_));
 
     case VAR_RESOURCEREF:
         return *(reinterpret_cast<const ResourceRef*>(&value_)) == *(reinterpret_cast<const ResourceRef*>(&rhs.value_));
@@ -243,11 +246,11 @@ void Variant::FromString(VariantType type, const char* value)
         break;
 
     case VAR_BUFFER:
-        {
-            SetType(VAR_BUFFER);
-            PODVector<unsigned char>& buffer = *(reinterpret_cast<PODVector<unsigned char>*>(&value_));
-            StringToBuffer(buffer, value);
-        }
+    {
+        SetType(VAR_BUFFER);
+        PODVector<unsigned char>& buffer = *(reinterpret_cast<PODVector<unsigned char>*>(&value_));
+        StringToBuffer(buffer, value);
+    }
         break;
 
     case VAR_VOIDPTR:
@@ -256,31 +259,31 @@ void Variant::FromString(VariantType type, const char* value)
         break;
 
     case VAR_RESOURCEREF:
+    {
+        Vector<String> values = String::Split(value, ';');
+        if (values.Size() == 2)
         {
-            Vector<String> values = String::Split(value, ';');
-            if (values.Size() == 2)
-            {
-                SetType(VAR_RESOURCEREF);
-                ResourceRef& ref = *(reinterpret_cast<ResourceRef*>(&value_));
-                ref.type_ = values[0];
-                ref.name_ = values[1];
-            }
+            SetType(VAR_RESOURCEREF);
+            ResourceRef& ref = *(reinterpret_cast<ResourceRef*>(&value_));
+            ref.type_ = values[0];
+            ref.name_ = values[1];
         }
+    }
         break;
 
     case VAR_RESOURCEREFLIST:
+    {
+        Vector<String> values = String::Split(value, ';');
+        if (values.Size() >= 1)
         {
-            Vector<String> values = String::Split(value, ';');
-            if (values.Size() >= 1)
-            {
-                SetType(VAR_RESOURCEREFLIST);
-                ResourceRefList& refList = *(reinterpret_cast<ResourceRefList*>(&value_));
-                refList.type_ = values[0];
-                refList.names_.Resize(values.Size() - 1);
-                for (unsigned i = 1; i < values.Size(); ++i)
-                    refList.names_[i - 1] = values[i];
-            }
+            SetType(VAR_RESOURCEREFLIST);
+            ResourceRefList& refList = *(reinterpret_cast<ResourceRefList*>(&value_));
+            refList.type_ = values[0];
+            refList.names_.Resize(values.Size() - 1);
+            for (unsigned i = 1; i < values.Size(); ++i)
+                refList.names_[i - 1] = values[i];
         }
+    }
         break;
 
     case VAR_INTRECT:
@@ -295,15 +298,15 @@ void Variant::FromString(VariantType type, const char* value)
         // From string to RefCounted pointer not supported, set to null
         *this = (RefCounted*)0;
         break;
-        
+
     case VAR_MATRIX3:
         *this = ToMatrix3(value);
         break;
-        
+
     case VAR_MATRIX3X4:
         *this = ToMatrix3x4(value);
         break;
-        
+
     case VAR_MATRIX4:
         *this = ToMatrix4(value);
         break;
@@ -366,12 +369,12 @@ String Variant::ToString() const
         return *(reinterpret_cast<const String*>(&value_));
 
     case VAR_BUFFER:
-        {
-            const PODVector<unsigned char>& buffer = *(reinterpret_cast<const PODVector<unsigned char>*>(&value_));
-            String ret;
-            BufferToString(ret, buffer.Begin().ptr_, buffer.Size());
-            return ret;
-        }
+    {
+        const PODVector<unsigned char>& buffer = *(reinterpret_cast<const PODVector<unsigned char>*>(&value_));
+        String ret;
+        BufferToString(ret, buffer.Begin().ptr_, buffer.Size());
+        return ret;
+    }
 
     case VAR_VOIDPTR:
     case VAR_PTR:
@@ -395,7 +398,7 @@ String Variant::ToString() const
 
     case VAR_MATRIX3X4:
         return (reinterpret_cast<const Matrix3x4*>(value_.ptr_))->ToString();
-        
+
     case VAR_MATRIX4:
         return (reinterpret_cast<const Matrix4*>(value_.ptr_))->ToString();
 
@@ -470,13 +473,13 @@ bool Variant::IsZero() const
 
     case VAR_PTR:
         return *reinterpret_cast<const WeakPtr<RefCounted>*>(&value_) == (RefCounted*)0;
-        
+
     case VAR_MATRIX3:
         return *reinterpret_cast<const Matrix3*>(value_.ptr_) == Matrix3::IDENTITY;
-        
+
     case VAR_MATRIX3X4:
         return *reinterpret_cast<const Matrix3x4*>(value_.ptr_) == Matrix3x4::IDENTITY;
-        
+
     case VAR_MATRIX4:
         return *reinterpret_cast<const Matrix4*>(value_.ptr_) == Matrix4::IDENTITY;
         
@@ -522,19 +525,19 @@ void Variant::SetType(VariantType newType)
     case VAR_PTR:
         (reinterpret_cast<WeakPtr<RefCounted>*>(&value_))->~WeakPtr<RefCounted>();
         break;
-        
+
     case VAR_MATRIX3:
         delete reinterpret_cast<Matrix3*>(value_.ptr_);
         break;
-        
+
     case VAR_MATRIX3X4:
         delete reinterpret_cast<Matrix3x4*>(value_.ptr_);
         break;
-        
+
     case VAR_MATRIX4:
         delete reinterpret_cast<Matrix4*>(value_.ptr_);
         break;
-        
+
     default:
         break;
     }
@@ -570,200 +573,200 @@ void Variant::SetType(VariantType newType)
     case VAR_PTR:
         new(reinterpret_cast<WeakPtr<RefCounted>*>(&value_)) WeakPtr<RefCounted>();
         break;
-        
+
     case VAR_MATRIX3:
         value_.ptr_ = new Matrix3();
         break;
-        
+
     case VAR_MATRIX3X4:
         value_.ptr_ = new Matrix3x4();
         break;
-        
+
     case VAR_MATRIX4:
         value_.ptr_ = new Matrix4();
         break;
-        
+
     default:
         break;
     }
 }
 
-template<> int Variant::Get<int>() const
+template <> int Variant::Get<int>() const
 {
     return GetInt();
 }
 
-template<> unsigned Variant::Get<unsigned>() const
+template <> unsigned Variant::Get<unsigned>() const
 {
     return GetUInt();
 }
 
-template<> StringHash Variant::Get<StringHash>() const
+template <> StringHash Variant::Get<StringHash>() const
 {
     return GetStringHash();
 }
 
-template<> bool Variant::Get<bool>() const
+template <> bool Variant::Get<bool>() const
 {
     return GetBool();
 }
 
-template<> float Variant::Get<float>() const
+template <> float Variant::Get<float>() const
 {
     return GetFloat();
 }
 
-template<> double Variant::Get<double>() const
+template <> double Variant::Get<double>() const
 {
     return GetDouble();
 }
 
-template<> const Vector2& Variant::Get<const Vector2&>() const
+template <> const Vector2& Variant::Get<const Vector2&>() const
 {
     return GetVector2();
 }
 
-template<> const Vector3& Variant::Get<const Vector3&>() const
+template <> const Vector3& Variant::Get<const Vector3&>() const
 {
     return GetVector3();
 }
 
-template<> const Vector4& Variant::Get<const Vector4&>() const
+template <> const Vector4& Variant::Get<const Vector4&>() const
 {
     return GetVector4();
 }
 
-template<> const Quaternion& Variant::Get<const Quaternion&>() const
+template <> const Quaternion& Variant::Get<const Quaternion&>() const
 {
     return GetQuaternion();
 }
 
-template<> const Color& Variant::Get<const Color&>() const
+template <> const Color& Variant::Get<const Color&>() const
 {
     return GetColor();
 }
 
-template<> const String& Variant::Get<const String&>() const
+template <> const String& Variant::Get<const String&>() const
 {
     return GetString();
 }
 
-template<> const IntRect& Variant::Get<const IntRect&>() const
+template <> const IntRect& Variant::Get<const IntRect&>() const
 {
     return GetIntRect();
 }
 
-template<> const IntVector2& Variant::Get<const IntVector2&>() const
+template <> const IntVector2& Variant::Get<const IntVector2&>() const
 {
     return GetIntVector2();
 }
 
-template<> const PODVector<unsigned char>& Variant::Get<const PODVector<unsigned char>& >() const
+template <> const PODVector<unsigned char>& Variant::Get<const PODVector<unsigned char>&>() const
 {
     return GetBuffer();
 }
 
-template<> void* Variant::Get<void*>() const
+template <> void* Variant::Get<void*>() const
 {
     return GetVoidPtr();
 }
 
-template<> RefCounted* Variant::Get<RefCounted*>() const
+template <> RefCounted* Variant::Get<RefCounted*>() const
 {
     return GetPtr();
 }
 
-template<> const Matrix3& Variant::Get<const Matrix3&>() const
+template <> const Matrix3& Variant::Get<const Matrix3&>() const
 {
     return GetMatrix3();
 }
 
-template<> const Matrix3x4& Variant::Get<const Matrix3x4&>() const
+template <> const Matrix3x4& Variant::Get<const Matrix3x4&>() const
 {
     return GetMatrix3x4();
 }
 
-template<> const Matrix4& Variant::Get<const Matrix4&>() const
+template <> const Matrix4& Variant::Get<const Matrix4&>() const
 {
     return GetMatrix4();
 }
 
-template<> ResourceRef Variant::Get<ResourceRef>() const
+template <> ResourceRef Variant::Get<ResourceRef>() const
 {
     return GetResourceRef();
 }
 
-template<> ResourceRefList Variant::Get<ResourceRefList>() const
+template <> ResourceRefList Variant::Get<ResourceRefList>() const
 {
     return GetResourceRefList();
 }
 
-template<> VariantVector Variant::Get<VariantVector>() const
+template <> VariantVector Variant::Get<VariantVector>() const
 {
     return GetVariantVector();
 }
 
-template<> VariantMap Variant::Get<VariantMap>() const
+template <> VariantMap Variant::Get<VariantMap>() const
 {
     return GetVariantMap();
 }
 
-template<> Vector2 Variant::Get<Vector2>() const
+template <> Vector2 Variant::Get<Vector2>() const
 {
     return GetVector2();
 }
 
-template<> Vector3 Variant::Get<Vector3>() const
+template <> Vector3 Variant::Get<Vector3>() const
 {
     return GetVector3();
 }
 
-template<> Vector4 Variant::Get<Vector4>() const
+template <> Vector4 Variant::Get<Vector4>() const
 {
     return GetVector4();
 }
 
-template<> Quaternion Variant::Get<Quaternion>() const
+template <> Quaternion Variant::Get<Quaternion>() const
 {
     return GetQuaternion();
 }
 
-template<> Color Variant::Get<Color>() const
+template <> Color Variant::Get<Color>() const
 {
     return GetColor();
 }
 
-template<> String Variant::Get<String>() const
+template <> String Variant::Get<String>() const
 {
     return GetString();
 }
 
-template<> IntRect Variant::Get<IntRect>() const
+template <> IntRect Variant::Get<IntRect>() const
 {
     return GetIntRect();
 }
 
-template<> IntVector2 Variant::Get<IntVector2>() const
+template <> IntVector2 Variant::Get<IntVector2>() const
 {
     return GetIntVector2();
 }
 
-template<> PODVector<unsigned char> Variant::Get<PODVector<unsigned char> >() const
+template <> PODVector<unsigned char> Variant::Get<PODVector<unsigned char> >() const
 {
     return GetBuffer();
 }
 
-template<> Matrix3 Variant::Get<Matrix3>() const
+template <> Matrix3 Variant::Get<Matrix3>() const
 {
     return GetMatrix3();
 }
 
-template<> Matrix3x4 Variant::Get<Matrix3x4>() const
+template <> Matrix3x4 Variant::Get<Matrix3x4>() const
 {
     return GetMatrix3x4();
 }
 
-template<> Matrix4 Variant::Get<Matrix4>() const
+template <> Matrix4 Variant::Get<Matrix4>() const
 {
     return GetMatrix4();
 }

+ 309 - 131
Source/Urho3D/Core/Variant.h

@@ -22,11 +22,11 @@
 
 #pragma once
 
-#include "../Math/Color.h"
 #include "../Container/HashMap.h"
+#include "../Container/Ptr.h"
+#include "../Math/Color.h"
 #include "../Math/Matrix3.h"
 #include "../Math/Matrix3x4.h"
-#include "../Container/Ptr.h"
 #include "../Math/Rect.h"
 #include "../Math/StringHash.h"
 
@@ -129,9 +129,10 @@ struct URHO3D_API ResourceRef
     String name_;
 
     /// Test for equality with another reference.
-    bool operator == (const ResourceRef& rhs) const { return type_ == rhs.type_ && name_ == rhs.name_; }
+    bool operator ==(const ResourceRef& rhs) const { return type_ == rhs.type_ && name_ == rhs.name_; }
+
     /// Test for inequality with another reference.
-    bool operator != (const ResourceRef& rhs) const { return type_ != rhs.type_ || name_ != rhs.name_; }
+    bool operator !=(const ResourceRef& rhs) const { return type_ != rhs.type_ || name_ != rhs.name_; }
 };
 
 /// %List of typed resource references.
@@ -147,6 +148,7 @@ struct URHO3D_API ResourceRefList
         type_(type)
     {
     }
+
     /// Construct with type and id list.
     ResourceRefList(StringHash type, const Vector<String>& names) :
         type_(type),
@@ -160,9 +162,10 @@ struct URHO3D_API ResourceRefList
     Vector<String> names_;
 
     /// Test for equality with another reference list.
-    bool operator == (const ResourceRefList& rhs) const { return type_ == rhs.type_ && names_ == rhs.names_; }
+    bool operator ==(const ResourceRefList& rhs) const { return type_ == rhs.type_ && names_ == rhs.names_; }
+
     /// Test for inequality with another reference list.
-    bool operator != (const ResourceRefList& rhs) const { return type_ != rhs.type_ || names_ != rhs.names_; }
+    bool operator !=(const ResourceRefList& rhs) const { return type_ != rhs.type_ || names_ != rhs.names_; }
 };
 
 class Variant;
@@ -329,7 +332,7 @@ public:
     {
         *this = value;
     }
-    
+
     /// Construct from a RefCounted pointer. The object will be stored internally in a WeakPtr so that its expiration can be detected safely.
     Variant(RefCounted* value) :
         type_(VAR_NONE)
@@ -357,7 +360,7 @@ public:
     {
         *this = value;
     }
-    
+
     /// Construct from type and value.
     Variant(const String& type, const String& value) :
         type_(VAR_NONE)
@@ -406,10 +409,10 @@ public:
     }
 
     /// Assign from another variant.
-    Variant& operator = (const Variant& rhs);
+    Variant& operator =(const Variant& rhs);
 
     /// Assign from an integer.
-    Variant& operator = (int rhs)
+    Variant& operator =(int rhs)
     {
         SetType(VAR_INT);
         value_.int_ = rhs;
@@ -417,7 +420,7 @@ public:
     }
 
     /// Assign from an unsigned integer.
-    Variant& operator = (unsigned rhs)
+    Variant& operator =(unsigned rhs)
     {
         SetType(VAR_INT);
         value_.int_ = (int)rhs;
@@ -425,7 +428,7 @@ public:
     }
 
     /// Assign from a StringHash (convert to integer.)
-    Variant& operator = (const StringHash& rhs)
+    Variant& operator =(const StringHash& rhs)
     {
         SetType(VAR_INT);
         value_.int_ = (int)rhs.Value();
@@ -433,7 +436,7 @@ public:
     }
 
     /// Assign from a bool.
-    Variant& operator = (bool rhs)
+    Variant& operator =(bool rhs)
     {
         SetType(VAR_BOOL);
         value_.bool_ = rhs;
@@ -441,7 +444,7 @@ public:
     }
 
     /// Assign from a float.
-    Variant& operator = (float rhs)
+    Variant& operator =(float rhs)
     {
         SetType(VAR_FLOAT);
         value_.float_ = rhs;
@@ -457,7 +460,7 @@ public:
     }
 
     /// Assign from a Vector2.
-    Variant& operator = (const Vector2& rhs)
+    Variant& operator =(const Vector2& rhs)
     {
         SetType(VAR_VECTOR2);
         *(reinterpret_cast<Vector2*>(&value_)) = rhs;
@@ -465,7 +468,7 @@ public:
     }
 
     /// Assign from a Vector3.
-    Variant& operator = (const Vector3& rhs)
+    Variant& operator =(const Vector3& rhs)
     {
         SetType(VAR_VECTOR3);
         *(reinterpret_cast<Vector3*>(&value_)) = rhs;
@@ -473,7 +476,7 @@ public:
     }
 
     /// Assign from a Vector4.
-    Variant& operator = (const Vector4& rhs)
+    Variant& operator =(const Vector4& rhs)
     {
         SetType(VAR_VECTOR4);
         *(reinterpret_cast<Vector4*>(&value_)) = rhs;
@@ -481,7 +484,7 @@ public:
     }
 
     /// Assign from a quaternion.
-    Variant& operator = (const Quaternion& rhs)
+    Variant& operator =(const Quaternion& rhs)
     {
         SetType(VAR_QUATERNION);
         *(reinterpret_cast<Quaternion*>(&value_)) = rhs;
@@ -489,7 +492,7 @@ public:
     }
 
     /// Assign from a color.
-    Variant& operator = (const Color& rhs)
+    Variant& operator =(const Color& rhs)
     {
         SetType(VAR_COLOR);
         *(reinterpret_cast<Color*>(&value_)) = rhs;
@@ -497,7 +500,7 @@ public:
     }
 
     /// Assign from a string.
-    Variant& operator = (const String& rhs)
+    Variant& operator =(const String& rhs)
     {
         SetType(VAR_STRING);
         *(reinterpret_cast<String*>(&value_)) = rhs;
@@ -505,7 +508,7 @@ public:
     }
 
     /// Assign from a C string.
-    Variant& operator = (const char* rhs)
+    Variant& operator =(const char* rhs)
     {
         SetType(VAR_STRING);
         *(reinterpret_cast<String*>(&value_)) = String(rhs);
@@ -513,7 +516,7 @@ public:
     }
 
     /// Assign from a buffer.
-    Variant& operator = (const PODVector<unsigned char>& rhs)
+    Variant& operator =(const PODVector<unsigned char>& rhs)
     {
         SetType(VAR_BUFFER);
         *(reinterpret_cast<PODVector<unsigned char>*>(&value_)) = rhs;
@@ -521,7 +524,7 @@ public:
     }
 
     /// Assign from a void pointer.
-    Variant& operator = (void* rhs)
+    Variant& operator =(void* rhs)
     {
         SetType(VAR_VOIDPTR);
         value_.ptr_ = rhs;
@@ -529,7 +532,7 @@ public:
     }
 
     /// Assign from a resource reference.
-    Variant& operator = (const ResourceRef& rhs)
+    Variant& operator =(const ResourceRef& rhs)
     {
         SetType(VAR_RESOURCEREF);
         *(reinterpret_cast<ResourceRef*>(&value_)) = rhs;
@@ -537,7 +540,7 @@ public:
     }
 
     /// Assign from a resource reference list.
-    Variant& operator = (const ResourceRefList& rhs)
+    Variant& operator =(const ResourceRefList& rhs)
     {
         SetType(VAR_RESOURCEREFLIST);
         *(reinterpret_cast<ResourceRefList*>(&value_)) = rhs;
@@ -545,7 +548,7 @@ public:
     }
 
     /// Assign from a variant vector.
-    Variant& operator = (const VariantVector& rhs)
+    Variant& operator =(const VariantVector& rhs)
     {
         SetType(VAR_VARIANTVECTOR);
         *(reinterpret_cast<VariantVector*>(&value_)) = rhs;
@@ -553,7 +556,7 @@ public:
     }
 
     /// Assign from a variant map.
-    Variant& operator = (const VariantMap& rhs)
+    Variant& operator =(const VariantMap& rhs)
     {
         SetType(VAR_VARIANTMAP);
         *(reinterpret_cast<VariantMap*>(&value_)) = rhs;
@@ -561,7 +564,7 @@ public:
     }
 
     /// Assign from an integer rect.
-    Variant& operator = (const IntRect& rhs)
+    Variant& operator =(const IntRect& rhs)
     {
         SetType(VAR_INTRECT);
         *(reinterpret_cast<IntRect*>(&value_)) = rhs;
@@ -569,74 +572,107 @@ public:
     }
 
     /// Assign from an IntVector2.
-    Variant& operator = (const IntVector2& rhs)
+    Variant& operator =(const IntVector2& rhs)
     {
         SetType(VAR_INTVECTOR2);
         *(reinterpret_cast<IntVector2*>(&value_)) = rhs;
         return *this;
     }
-    
+
     /// Assign from a RefCounted pointer. The object will be stored internally in a WeakPtr so that its expiration can be detected safely.
-    Variant& operator = (RefCounted* rhs)
+    Variant& operator =(RefCounted* rhs)
     {
         SetType(VAR_PTR);
         *(reinterpret_cast<WeakPtr<RefCounted>*>(&value_)) = rhs;
         return *this;
     }
-    
+
     /// Assign from a Matrix3.
-    Variant& operator = (const Matrix3& rhs)
+    Variant& operator =(const Matrix3& rhs)
     {
         SetType(VAR_MATRIX3);
         *(reinterpret_cast<Matrix3*>(value_.ptr_)) = rhs;
         return *this;
     }
-    
+
     /// Assign from a Matrix3x4.
-    Variant& operator = (const Matrix3x4& rhs)
+    Variant& operator =(const Matrix3x4& rhs)
     {
         SetType(VAR_MATRIX3X4);
         *(reinterpret_cast<Matrix3x4*>(value_.ptr_)) = rhs;
         return *this;
     }
-    
+
     /// Assign from a Matrix4.
-    Variant& operator = (const Matrix4& rhs)
+    Variant& operator =(const Matrix4& rhs)
     {
         SetType(VAR_MATRIX4);
         *(reinterpret_cast<Matrix4*>(value_.ptr_)) = rhs;
         return *this;
     }
-    
+
     /// Test for equality with another variant.
-    bool operator == (const Variant& rhs) const;
+    bool operator ==(const Variant& rhs) const;
+
     /// Test for equality with an integer. To return true, both the type and value must match.
-    bool operator == (int rhs) const { return type_ == VAR_INT ? value_.int_ == rhs : false; }
+    bool operator ==(int rhs) const { return type_ == VAR_INT ? value_.int_ == rhs : false; }
+
     /// Test for equality with an unsigned integer. To return true, both the type and value must match.
-    bool operator == (unsigned rhs) const { return type_ == VAR_INT ? value_.int_ == (int)rhs : false; }
+    bool operator ==(unsigned rhs) const { return type_ == VAR_INT ? value_.int_ == (int)rhs : false; }
+
     /// Test for equality with a bool. To return true, both the type and value must match.
-    bool operator == (bool rhs) const { return type_ == VAR_BOOL ? value_.bool_ == rhs : false; }
+    bool operator ==(bool rhs) const { return type_ == VAR_BOOL ? value_.bool_ == rhs : false; }
+
     /// Test for equality with a float. To return true, both the type and value must match.
-    bool operator == (float rhs) const { return type_ == VAR_FLOAT ? value_.float_ == rhs : false; }
+    bool operator ==(float rhs) const { return type_ == VAR_FLOAT ? value_.float_ == rhs : false; }
+
     /// Test for equality with a double. To return true, both the type and value must match.
-    bool operator == (double rhs) const { return type_ == VAR_DOUBLE ? *(reinterpret_cast<const double*>(&value_)) == rhs : false; }
+    bool operator ==(double rhs) const { return type_ == VAR_DOUBLE ? *(reinterpret_cast<const double*>(&value_)) == rhs : false; }
+
     /// Test for equality with a Vector2. To return true, both the type and value must match.
-    bool operator == (const Vector2& rhs) const { return type_ == VAR_VECTOR2 ? *(reinterpret_cast<const Vector2*>(&value_)) == rhs : false; }
+    bool operator ==(const Vector2& rhs) const
+    {
+        return type_ == VAR_VECTOR2 ? *(reinterpret_cast<const Vector2*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a Vector3. To return true, both the type and value must match.
-    bool operator == (const Vector3& rhs) const { return type_ == VAR_VECTOR3 ? *(reinterpret_cast<const Vector3*>(&value_)) == rhs : false; }
+    bool operator ==(const Vector3& rhs) const
+    {
+        return type_ == VAR_VECTOR3 ? *(reinterpret_cast<const Vector3*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a Vector4. To return true, both the type and value must match.
-    bool operator == (const Vector4& rhs) const { return type_ == VAR_VECTOR4 ? *(reinterpret_cast<const Vector4*>(&value_)) == rhs : false; }
+    bool operator ==(const Vector4& rhs) const
+    {
+        return type_ == VAR_VECTOR4 ? *(reinterpret_cast<const Vector4*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a quaternion. To return true, both the type and value must match.
-    bool operator == (const Quaternion& rhs) const { return type_ == VAR_QUATERNION ? *(reinterpret_cast<const Quaternion*>(&value_)) == rhs : false; }
+    bool operator ==(const Quaternion& rhs) const
+    {
+        return type_ == VAR_QUATERNION ? *(reinterpret_cast<const Quaternion*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a color. To return true, both the type and value must match.
-    bool operator == (const Color& rhs) const { return type_ == VAR_COLOR ? *(reinterpret_cast<const Color*>(&value_)) == rhs : false; }
+    bool operator ==(const Color& rhs) const
+    {
+        return type_ == VAR_COLOR ? *(reinterpret_cast<const Color*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a string. To return true, both the type and value must match.
-    bool operator == (const String& rhs) const { return type_ == VAR_STRING ? *(reinterpret_cast<const String*>(&value_)) == rhs : false; }
+    bool operator ==(const String& rhs) const
+    {
+        return type_ == VAR_STRING ? *(reinterpret_cast<const String*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a buffer. To return true, both the type and value must match.
-    bool operator == (const PODVector<unsigned char>& rhs) const { return type_ == VAR_BUFFER ? *(reinterpret_cast<const PODVector<unsigned char>*>(&value_)) == rhs : false; }
-    
+    bool operator ==(const PODVector<unsigned char>& rhs) const
+    {
+        return type_ == VAR_BUFFER ? *(reinterpret_cast<const PODVector<unsigned char>*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a void pointer. To return true, both the type and value must match, with the exception that a RefCounted pointer is also allowed.
-    bool operator == (void* rhs) const
+    bool operator ==(void* rhs) const
     {
         if (type_ == VAR_VOIDPTR)
             return value_.ptr_ == rhs;
@@ -645,24 +681,48 @@ public:
         else
             return false;
     }
-    
+
     /// Test for equality with a resource reference. To return true, both the type and value must match.
-    bool operator == (const ResourceRef& rhs) const { return type_ == VAR_RESOURCEREF ? *(reinterpret_cast<const ResourceRef*>(&value_)) == rhs : false; }
+    bool operator ==(const ResourceRef& rhs) const
+    {
+        return type_ == VAR_RESOURCEREF ? *(reinterpret_cast<const ResourceRef*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a resource reference list. To return true, both the type and value must match.
-    bool operator == (const ResourceRefList& rhs) const { return type_ == VAR_RESOURCEREFLIST ? *(reinterpret_cast<const ResourceRefList*>(&value_)) == rhs : false; }
+    bool operator ==(const ResourceRefList& rhs) const
+    {
+        return type_ == VAR_RESOURCEREFLIST ? *(reinterpret_cast<const ResourceRefList*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a variant vector. To return true, both the type and value must match.
-    bool operator == (const VariantVector& rhs) const { return type_ == VAR_VARIANTVECTOR ? *(reinterpret_cast<const VariantVector*>(&value_)) == rhs : false; }
+    bool operator ==(const VariantVector& rhs) const
+    {
+        return type_ == VAR_VARIANTVECTOR ? *(reinterpret_cast<const VariantVector*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a variant map. To return true, both the type and value must match.
-    bool operator == (const VariantMap& rhs) const { return type_ == VAR_VARIANTMAP ? *(reinterpret_cast<const VariantMap*>(&value_)) == rhs : false; }
+    bool operator ==(const VariantMap& rhs) const
+    {
+        return type_ == VAR_VARIANTMAP ? *(reinterpret_cast<const VariantMap*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with an integer rect. To return true, both the type and value must match.
-    bool operator == (const IntRect& rhs) const { return type_ == VAR_INTRECT ? *(reinterpret_cast<const IntRect*>(&value_)) == rhs : false; }
+    bool operator ==(const IntRect& rhs) const
+    {
+        return type_ == VAR_INTRECT ? *(reinterpret_cast<const IntRect*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with an IntVector2. To return true, both the type and value must match.
-    bool operator == (const IntVector2& rhs) const { return type_ == VAR_INTVECTOR2 ? *(reinterpret_cast<const IntVector2*>(&value_)) == rhs : false; }
+    bool operator ==(const IntVector2& rhs) const
+    {
+        return type_ == VAR_INTVECTOR2 ? *(reinterpret_cast<const IntVector2*>(&value_)) == rhs : false;
+    }
+
     /// Test for equality with a StringHash. To return true, both the type and value must match.
-    bool operator == (const StringHash& rhs) const { return type_ == VAR_INT ? (unsigned)value_.int_ == rhs.Value() : false; }
-    
+    bool operator ==(const StringHash& rhs) const { return type_ == VAR_INT ? (unsigned)value_.int_ == rhs.Value() : false; }
+
     /// Test for equality with a RefCounted pointer. To return true, both the type and value must match, with the exception that void pointer is also allowed.
-    bool operator == (RefCounted* rhs) const
+    bool operator ==(RefCounted* rhs) const
     {
         if (type_ == VAR_PTR)
             return *(reinterpret_cast<const WeakPtr<RefCounted>*>(&value_)) == rhs;
@@ -671,63 +731,97 @@ public:
         else
             return false;
     }
-    
+
     /// Test for equality with a Matrix3. To return true, both the type and value must match.
-    bool operator == (const Matrix3& rhs) const { return type_ == VAR_MATRIX3 ? *(reinterpret_cast<const Matrix3*>(value_.ptr_)) == rhs : false; }
+    bool operator ==(const Matrix3& rhs) const
+    {
+        return type_ == VAR_MATRIX3 ? *(reinterpret_cast<const Matrix3*>(value_.ptr_)) == rhs : false;
+    }
+
     /// Test for equality with a Matrix3x4. To return true, both the type and value must match.
-    bool operator == (const Matrix3x4& rhs) const { return type_ == VAR_MATRIX3X4 ? *(reinterpret_cast<const Matrix3x4*>(value_.ptr_)) == rhs : false; }
+    bool operator ==(const Matrix3x4& rhs) const
+    {
+        return type_ == VAR_MATRIX3X4 ? *(reinterpret_cast<const Matrix3x4*>(value_.ptr_)) == rhs : false;
+    }
+
     /// Test for equality with a Matrix4. To return true, both the type and value must match.
-    bool operator == (const Matrix4& rhs) const { return type_ == VAR_MATRIX4 ? *(reinterpret_cast<const Matrix4*>(value_.ptr_)) == rhs : false; }
-    
+    bool operator ==(const Matrix4& rhs) const
+    {
+        return type_ == VAR_MATRIX4 ? *(reinterpret_cast<const Matrix4*>(value_.ptr_)) == rhs : false;
+    }
+
     /// Test for inequality with another variant.
-    bool operator != (const Variant& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Variant& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with an integer.
-    bool operator != (int rhs) const { return !(*this == rhs); }
+    bool operator !=(int rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with an unsigned integer.
-    bool operator != (unsigned rhs) const { return !(*this == rhs); }
+    bool operator !=(unsigned rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a bool.
-    bool operator != (bool rhs) const { return !(*this == rhs); }
+    bool operator !=(bool rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a float.
-    bool operator != (float rhs) const { return !(*this == rhs); }
+    bool operator !=(float rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a double.
-    bool operator != (double rhs) const { return !(*this == rhs); }
+    bool operator !=(double rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a Vector2.
-    bool operator != (const Vector2& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Vector2& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a Vector3.
-    bool operator != (const Vector3& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Vector3& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with an Vector4.
-    bool operator != (const Vector4& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Vector4& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a Quaternion.
-    bool operator != (const Quaternion& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Quaternion& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a string.
-    bool operator != (const String& rhs) const { return !(*this == rhs); }
+    bool operator !=(const String& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a buffer.
-    bool operator != (const PODVector<unsigned char>& rhs) const { return !(*this == rhs); }
+    bool operator !=(const PODVector<unsigned char>& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a pointer.
-    bool operator != (void* rhs) const { return !(*this == rhs); }
+    bool operator !=(void* rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a resource reference.
-    bool operator != (const ResourceRef& rhs) const { return !(*this == rhs); }
+    bool operator !=(const ResourceRef& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a resource reference list.
-    bool operator != (const ResourceRefList& rhs) const { return !(*this == rhs); }
+    bool operator !=(const ResourceRefList& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a variant vector.
-    bool operator != (const VariantVector& rhs) const { return !(*this == rhs); }
+    bool operator !=(const VariantVector& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a variant map.
-    bool operator != (const VariantMap& rhs) const { return !(*this == rhs); }
+    bool operator !=(const VariantMap& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with an integer rect.
-    bool operator != (const IntRect& rhs) const { return !(*this == rhs); }
+    bool operator !=(const IntRect& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with an IntVector2.
-    bool operator != (const IntVector2& rhs) const { return !(*this == rhs); }
+    bool operator !=(const IntVector2& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a StringHash.
-    bool operator != (const StringHash& rhs) const { return !(*this == rhs); }
+    bool operator !=(const StringHash& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a RefCounted pointer.
-    bool operator != (RefCounted* rhs) const { return !(*this == rhs); }
+    bool operator !=(RefCounted* rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a Matrix3.
-    bool operator != (const Matrix3& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Matrix3& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a Matrix3x4.
-    bool operator != (const Matrix3x4& rhs) const { return !(*this == rhs); }
+    bool operator !=(const Matrix3x4& rhs) const { return !(*this == rhs); }
+
     /// Test for inequality with a Matrix4.
-    bool operator != (const Matrix4& rhs) const { return !(*this == rhs); }
-    
+    bool operator !=(const Matrix4& rhs) const { return !(*this == rhs); }
+
     /// Set from typename and value strings. Pointers will be set to null, and VariantBuffer or VariantMap types are not supported.
     void FromString(const String& type, const String& value);
     /// Set from typename and value strings. Pointers will be set to null, and VariantBuffer or VariantMap types are not supported.
@@ -741,31 +835,49 @@ public:
 
     /// Return int or zero on type mismatch.
     int GetInt() const { return type_ == VAR_INT ? value_.int_ : 0; }
+
     /// Return unsigned int or zero on type mismatch.
     unsigned GetUInt() const { return type_ == VAR_INT ? (unsigned)value_.int_ : 0; }
+
     /// Return StringHash or zero on type mismatch.
     StringHash GetStringHash() const { return StringHash(GetUInt()); }
+
     /// Return bool or false on type mismatch.
     bool GetBool() const { return type_ == VAR_BOOL ? value_.bool_ : false; }
+
     /// Return float or zero on type mismatch.
     float GetFloat() const { return type_ == VAR_FLOAT ? value_.float_ : 0.0f; }
+
     /// Return double or zero on type mismatch.
     double GetDouble() const { return type_ == VAR_DOUBLE ? *reinterpret_cast<const double*>(&value_) : 0.0; }
+
     /// Return Vector2 or zero on type mismatch.
     const Vector2& GetVector2() const { return type_ == VAR_VECTOR2 ? *reinterpret_cast<const Vector2*>(&value_) : Vector2::ZERO; }
+
     /// Return Vector3 or zero on type mismatch.
     const Vector3& GetVector3() const { return type_ == VAR_VECTOR3 ? *reinterpret_cast<const Vector3*>(&value_) : Vector3::ZERO; }
+
     /// Return Vector4 or zero on type mismatch.
     const Vector4& GetVector4() const { return type_ == VAR_VECTOR4 ? *reinterpret_cast<const Vector4*>(&value_) : Vector4::ZERO; }
+
     /// Return quaternion or identity on type mismatch.
-    const Quaternion& GetQuaternion() const { return type_ == VAR_QUATERNION ? *reinterpret_cast<const Quaternion*>(&value_) : Quaternion::IDENTITY; }
+    const Quaternion& GetQuaternion() const
+    {
+        return type_ == VAR_QUATERNION ? *reinterpret_cast<const Quaternion*>(&value_) : Quaternion::IDENTITY;
+    }
+
     /// Return color or default on type mismatch.
     const Color& GetColor() const { return type_ == VAR_COLOR ? *reinterpret_cast<const Color*>(&value_) : Color::WHITE; }
+
     /// Return string or empty on type mismatch.
     const String& GetString() const { return type_ == VAR_STRING ? *reinterpret_cast<const String*>(&value_) : String::EMPTY; }
+
     /// Return buffer or empty on type mismatch.
-    const PODVector<unsigned char>& GetBuffer() const { return type_ == VAR_BUFFER ? *reinterpret_cast<const PODVector<unsigned char>*>(&value_) : emptyBuffer; }
-    
+    const PODVector<unsigned char>& GetBuffer() const
+    {
+        return type_ == VAR_BUFFER ? *reinterpret_cast<const PODVector<unsigned char>*>(&value_) : emptyBuffer;
+    }
+
     /// Return void pointer or null on type mismatch. RefCounted pointer will be converted.
     void* GetVoidPtr() const
     {
@@ -776,44 +888,89 @@ public:
         else
             return 0;
     }
-    
+
     /// Return a resource reference or empty on type mismatch.
-    const ResourceRef& GetResourceRef() const { return type_ == VAR_RESOURCEREF ? *reinterpret_cast<const ResourceRef*>(&value_) : emptyResourceRef; }
+    const ResourceRef& GetResourceRef() const
+    {
+        return type_ == VAR_RESOURCEREF ? *reinterpret_cast<const ResourceRef*>(&value_) : emptyResourceRef;
+    }
+
     /// Return a resource reference list or empty on type mismatch.
-    const ResourceRefList& GetResourceRefList() const { return type_ == VAR_RESOURCEREFLIST ? *reinterpret_cast<const ResourceRefList*>(&value_) : emptyResourceRefList; }
+    const ResourceRefList& GetResourceRefList() const
+    {
+        return type_ == VAR_RESOURCEREFLIST ? *reinterpret_cast<const ResourceRefList*>(&value_) : emptyResourceRefList;
+    }
+
     /// Return a variant vector or empty on type mismatch.
-    const VariantVector& GetVariantVector() const { return type_ == VAR_VARIANTVECTOR ? *reinterpret_cast<const VariantVector*>(&value_) : emptyVariantVector; }
+    const VariantVector& GetVariantVector() const
+    {
+        return type_ == VAR_VARIANTVECTOR ? *reinterpret_cast<const VariantVector*>(&value_) : emptyVariantVector;
+    }
+
     /// Return a variant map or empty on type mismatch.
-    const VariantMap& GetVariantMap() const { return type_ == VAR_VARIANTMAP ? *reinterpret_cast<const VariantMap*>(&value_) : emptyVariantMap; }
+    const VariantMap& GetVariantMap() const
+    {
+        return type_ == VAR_VARIANTMAP ? *reinterpret_cast<const VariantMap*>(&value_) : emptyVariantMap;
+    }
+
     /// Return an integer rect or empty on type mismatch.
     const IntRect& GetIntRect() const { return type_ == VAR_INTRECT ? *reinterpret_cast<const IntRect*>(&value_) : IntRect::ZERO; }
+
     /// Return an IntVector2 or empty on type mismatch.
-    const IntVector2& GetIntVector2() const { return type_ == VAR_INTVECTOR2 ? *reinterpret_cast<const IntVector2*>(&value_) : IntVector2::ZERO; }
+    const IntVector2& GetIntVector2() const
+    {
+        return type_ == VAR_INTVECTOR2 ? *reinterpret_cast<const IntVector2*>(&value_) : IntVector2::ZERO;
+    }
+
     /// Return a RefCounted pointer or null on type mismatch. Will return null if holding a void pointer, as it can not be safely verified that the object is a RefCounted.
-    RefCounted* GetPtr() const { return type_ == VAR_PTR ? *reinterpret_cast<const WeakPtr<RefCounted>*>(&value_) : (RefCounted*)0; }
+    RefCounted* GetPtr() const
+    {
+        return type_ == VAR_PTR ? *reinterpret_cast<const WeakPtr<RefCounted>*>(&value_) : (RefCounted*)0;
+    }
+
     /// Return a Matrix3 or identity on type mismatch.
-    const Matrix3& GetMatrix3() const { return type_ == VAR_MATRIX3 ? *(reinterpret_cast<const Matrix3*>(value_.ptr_)) : Matrix3::IDENTITY; }
+    const Matrix3& GetMatrix3() const
+    {
+        return type_ == VAR_MATRIX3 ? *(reinterpret_cast<const Matrix3*>(value_.ptr_)) : Matrix3::IDENTITY;
+    }
+
     /// Return a Matrix3x4 or identity on type mismatch.
-    const Matrix3x4& GetMatrix3x4() const { return type_ == VAR_MATRIX3X4 ? *(reinterpret_cast<const Matrix3x4*>(value_.ptr_)) : Matrix3x4::IDENTITY; }
+    const Matrix3x4& GetMatrix3x4() const
+    {
+        return type_ == VAR_MATRIX3X4 ? *(reinterpret_cast<const Matrix3x4*>(value_.ptr_)) : Matrix3x4::IDENTITY;
+    }
+
     /// Return a Matrix4 or identity on type mismatch.
-    const Matrix4& GetMatrix4() const { return type_ == VAR_MATRIX4 ? *(reinterpret_cast<const Matrix4*>(value_.ptr_)) : Matrix4::IDENTITY; }
+    const Matrix4& GetMatrix4() const
+    {
+        return type_ == VAR_MATRIX4 ? *(reinterpret_cast<const Matrix4*>(value_.ptr_)) : Matrix4::IDENTITY;
+    }
+
     /// Return value's type.
     VariantType GetType() const { return type_; }
+
     /// Return value's type name.
     String GetTypeName() const;
     /// Convert value to string. Pointers are returned as null, and VariantBuffer or VariantMap are not supported and return empty.
     String ToString() const;
     /// Return true when the variant value is considered zero according to its actual type.
     bool IsZero() const;
+
     /// Return true when the variant is empty (i.e. not initialized yet).
     bool IsEmpty() const { return type_ == VAR_NONE; }
+
     /// Return the value, template version.
     template <class T> T Get() const;
-    
+
     /// Return a pointer to a modifiable buffer or null on type mismatch.
-    PODVector<unsigned char>* GetBufferPtr() { return type_ == VAR_BUFFER ? reinterpret_cast<PODVector<unsigned char>*>(&value_) : 0; }
+    PODVector<unsigned char>* GetBufferPtr()
+    {
+        return type_ == VAR_BUFFER ? reinterpret_cast<PODVector<unsigned char>*>(&value_) : 0;
+    }
+
     /// Return a pointer to a modifiable variant vector or null on type mismatch.
     VariantVector* GetVariantVectorPtr() { return type_ == VAR_VARIANTVECTOR ? reinterpret_cast<VariantVector*>(&value_) : 0; }
+
     /// Return a pointer to a modifiable variant map or null on type mismatch.
     VariantMap* GetVariantMapPtr() { return type_ == VAR_VARIANTMAP ? reinterpret_cast<VariantMap*>(&value_) : 0; }
 
@@ -848,30 +1005,51 @@ private:
 };
 
 /// Return variant type from type.
-template<typename T> VariantType GetVariantType();
+template <typename T> VariantType GetVariantType();
 
 /// Return variant type from concrete types.
-template<> inline VariantType GetVariantType<int>() { return VAR_INT; }
-template<> inline VariantType GetVariantType<unsigned>() { return VAR_INT; }
-template<> inline VariantType GetVariantType<bool>() { return VAR_BOOL; }
-template<> inline VariantType GetVariantType<float>() { return VAR_FLOAT; }
-template<> inline VariantType GetVariantType<double>() { return VAR_DOUBLE; }
-template<> inline VariantType GetVariantType<Vector2>() { return VAR_VECTOR2; }
-template<> inline VariantType GetVariantType<Vector3>() { return VAR_VECTOR3; }
-template<> inline VariantType GetVariantType<Vector4>() { return VAR_VECTOR4; }
-template<> inline VariantType GetVariantType<Quaternion>() { return VAR_QUATERNION; }
-template<> inline VariantType GetVariantType<Color>() { return VAR_COLOR; }
-template<> inline VariantType GetVariantType<String>() { return VAR_STRING; }
-template<> inline VariantType GetVariantType<StringHash>() { return VAR_INT; }
-template<> inline VariantType GetVariantType<PODVector<unsigned char> >() { return VAR_BUFFER; }
-template<> inline VariantType GetVariantType<ResourceRef>() { return VAR_RESOURCEREF; }
-template<> inline VariantType GetVariantType<ResourceRefList>() { return VAR_RESOURCEREFLIST; }
-template<> inline VariantType GetVariantType<VariantVector>() { return VAR_VARIANTVECTOR; }
-template<> inline VariantType GetVariantType<VariantMap>() { return VAR_VARIANTMAP; }
-template<> inline VariantType GetVariantType<IntRect>() { return VAR_INTRECT; }
-template<> inline VariantType GetVariantType<IntVector2>() { return VAR_INTVECTOR2; }
-template<> inline VariantType GetVariantType<Matrix3>() { return VAR_MATRIX3; }
-template<> inline VariantType GetVariantType<Matrix3x4>() { return VAR_MATRIX3X4; }
-template<> inline VariantType GetVariantType<Matrix4>() { return VAR_MATRIX4; }
+template <> inline VariantType GetVariantType<int>() { return VAR_INT; }
+
+template <> inline VariantType GetVariantType<unsigned>() { return VAR_INT; }
+
+template <> inline VariantType GetVariantType<bool>() { return VAR_BOOL; }
+
+template <> inline VariantType GetVariantType<float>() { return VAR_FLOAT; }
+
+template <> inline VariantType GetVariantType<double>() { return VAR_DOUBLE; }
+
+template <> inline VariantType GetVariantType<Vector2>() { return VAR_VECTOR2; }
+
+template <> inline VariantType GetVariantType<Vector3>() { return VAR_VECTOR3; }
+
+template <> inline VariantType GetVariantType<Vector4>() { return VAR_VECTOR4; }
+
+template <> inline VariantType GetVariantType<Quaternion>() { return VAR_QUATERNION; }
+
+template <> inline VariantType GetVariantType<Color>() { return VAR_COLOR; }
+
+template <> inline VariantType GetVariantType<String>() { return VAR_STRING; }
+
+template <> inline VariantType GetVariantType<StringHash>() { return VAR_INT; }
+
+template <> inline VariantType GetVariantType<PODVector<unsigned char> >() { return VAR_BUFFER; }
+
+template <> inline VariantType GetVariantType<ResourceRef>() { return VAR_RESOURCEREF; }
+
+template <> inline VariantType GetVariantType<ResourceRefList>() { return VAR_RESOURCEREFLIST; }
+
+template <> inline VariantType GetVariantType<VariantVector>() { return VAR_VARIANTVECTOR; }
+
+template <> inline VariantType GetVariantType<VariantMap>() { return VAR_VARIANTMAP; }
+
+template <> inline VariantType GetVariantType<IntRect>() { return VAR_INTRECT; }
+
+template <> inline VariantType GetVariantType<IntVector2>() { return VAR_INTVECTOR2; }
+
+template <> inline VariantType GetVariantType<Matrix3>() { return VAR_MATRIX3; }
+
+template <> inline VariantType GetVariantType<Matrix3x4>() { return VAR_MATRIX3X4; }
+
+template <> inline VariantType GetVariantType<Matrix4>() { return VAR_MATRIX4; }
 
 }

+ 29 - 29
Source/Urho3D/Core/WorkQueue.cpp

@@ -20,13 +20,13 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Core/CoreEvents.h"
-#include "../IO/Log.h"
 #include "../Core/ProcessUtils.h"
 #include "../Core/Profiler.h"
-#include "../Core/Thread.h"
-#include "../Core/Timer.h"
 #include "../Core/WorkQueue.h"
+#include "../IO/Log.h"
 
 namespace Urho3D
 {
@@ -41,7 +41,7 @@ public:
         index_(index)
     {
     }
-    
+
     /// Process work items until stopped.
     virtual void ThreadFunction()
     {
@@ -49,10 +49,10 @@ public:
         InitFPU();
         owner_->ProcessItems(index_);
     }
-    
+
     /// Return thread index.
     unsigned GetIndex() const { return index_; }
-    
+
 private:
     /// Work queue.
     WorkQueue* owner_;
@@ -77,7 +77,7 @@ WorkQueue::~WorkQueue()
     // Stop the worker threads. First make sure they are not waiting for work items
     shutDown_ = true;
     Resume();
-    
+
     for (unsigned i = 0; i < threads_.Size(); ++i)
         threads_[i]->Stop();
 }
@@ -88,10 +88,10 @@ void WorkQueue::CreateThreads(unsigned numThreads)
     // Therefore allow creating the threads only once, after which the amount is fixed
     if (!threads_.Empty())
         return;
-    
+
     // Start threads in paused mode
     Pause();
-    
+
     for (unsigned i = 0; i < numThreads; ++i)
     {
         SharedPtr<WorkerThread> thread(new WorkerThread(this, i + 1));
@@ -124,10 +124,10 @@ void WorkQueue::AddWorkItem(SharedPtr<WorkItem> item)
         LOGERROR("Null work item submitted to the work queue");
         return;
     }
-    
+
     // Check for duplicate items.
     assert(!workItems_.Contains(item));
-    
+
     // Push to the main thread list to keep item alive
     // Clear completed flag in case item is reused
     workItems_.Push(item);
@@ -136,7 +136,7 @@ void WorkQueue::AddWorkItem(SharedPtr<WorkItem> item)
     // Make sure worker threads' list is safe to modify
     if (threads_.Size() && !paused_)
         queueMutex_.Acquire();
-    
+
     // Find position for new item
     if (queue_.Empty())
         queue_.Push(item);
@@ -151,7 +151,7 @@ void WorkQueue::AddWorkItem(SharedPtr<WorkItem> item)
             }
         }
     }
-    
+
     if (threads_.Size())
     {
         queueMutex_.Release();
@@ -165,7 +165,7 @@ bool WorkQueue::RemoveWorkItem(SharedPtr<WorkItem> item)
         return false;
 
     MutexLock lock(queueMutex_);
-    
+
     // Can only remove successfully if the item was not yet taken by threads for execution
     List<WorkItem*>::Iterator i = queue_.Find(item.Get());
     if (i != queue_.End())
@@ -212,10 +212,10 @@ void WorkQueue::Pause()
     if (!paused_)
     {
         pausing_ = true;
-        
+
         queueMutex_.Acquire();
         paused_ = true;
-        
+
         pausing_ = false;
     }
 }
@@ -235,7 +235,7 @@ void WorkQueue::Complete(unsigned priority)
     if (threads_.Size())
     {
         Resume();
-        
+
         // Take work items also in the main thread until queue empty or no high-priority items anymore
         while (!queue_.Empty())
         {
@@ -254,12 +254,12 @@ void WorkQueue::Complete(unsigned priority)
                 break;
             }
         }
-        
+
         // Wait for threaded work to complete
         while (!IsCompleted(priority))
         {
         }
-        
+
         // If no work at all remaining, pause worker threads by leaving the mutex locked
         if (queue_.Empty())
             Pause();
@@ -275,7 +275,7 @@ void WorkQueue::Complete(unsigned priority)
             item->completed_ = true;
         }
     }
-    
+
     PurgeCompleted(priority);
 }
 
@@ -286,19 +286,19 @@ bool WorkQueue::IsCompleted(unsigned priority) const
         if ((*i)->priority_ >= priority && !(*i)->completed_)
             return false;
     }
-    
+
     return true;
 }
 
 void WorkQueue::ProcessItems(unsigned threadIndex)
 {
     bool wasActive = false;
-    
+
     for (;;)
     {
         if (shutDown_)
             return;
-        
+
         if (pausing_ && !wasActive)
             Time::Sleep(0);
         else
@@ -307,7 +307,7 @@ void WorkQueue::ProcessItems(unsigned threadIndex)
             if (!queue_.Empty())
             {
                 wasActive = true;
-                
+
                 WorkItem* item = queue_.Front();
                 queue_.PopFront();
                 queueMutex_.Release();
@@ -317,7 +317,7 @@ void WorkQueue::ProcessItems(unsigned threadIndex)
             else
             {
                 wasActive = false;
-                
+
                 queueMutex_.Release();
                 Time::Sleep(0);
             }
@@ -337,7 +337,7 @@ void WorkQueue::PurgeCompleted(unsigned priority)
             if ((*i)->sendEvent_)
             {
                 using namespace WorkItemCompleted;
-                
+
                 VariantMap& eventData = GetEventDataMap();
                 eventData[P_ITEM] = i->Get();
                 SendEvent(E_WORKITEMCOMPLETED, eventData);
@@ -390,9 +390,9 @@ void WorkQueue::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
     if (threads_.Empty() && !queue_.Empty())
     {
         PROFILE(CompleteWorkNonthreaded);
-        
+
         HiresTimer timer;
-        
+
         while (!queue_.Empty() && timer.GetUSec(false) < maxNonThreadedWorkMs_ * 1000)
         {
             WorkItem* item = queue_.Front();
@@ -401,7 +401,7 @@ void WorkQueue::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
             item->completed_ = true;
         }
     }
-    
+
     // Complete and signal items down to the lowest priority
     PurgeCompleted(0);
     PurgePool();

+ 13 - 8
Source/Urho3D/Core/WorkQueue.h

@@ -51,9 +51,9 @@ public:
         pooled_(false)
     {
     }
-    
+
     /// Work function. Called with the work item and thread index (0 = main thread) as parameters.
-    void (*workFunction_)(const WorkItem*, unsigned);
+    void (* workFunction_)(const WorkItem*, unsigned);
     /// Data start pointer.
     void* start_;
     /// Data end pointer.
@@ -75,15 +75,15 @@ private:
 class URHO3D_API WorkQueue : public Object
 {
     OBJECT(WorkQueue);
-    
+
     friend class WorkerThread;
-    
+
 public:
     /// Construct.
     WorkQueue(Context* context);
     /// Destruct.
     ~WorkQueue();
-    
+
     /// Create worker threads. Can only be called once.
     void CreateThreads(unsigned numThreads);
     /// Get pointer to an usable WorkItem from the item pool. Allocate one if no more free items.
@@ -100,20 +100,25 @@ public:
     void Resume();
     /// Finish all queued work which has at least the specified priority. Main thread will also execute priority work. Pause worker threads if no more work remains.
     void Complete(unsigned priority);
+
     /// Set the pool telerance before it starts deleting pool items.
     void SetTolerance(int tolerance) { tolerance_ = tolerance; }
+
     /// Set how many milliseconds maximum per frame to spend on low-priority work, when there are no worker threads.
     void SetNonThreadedWorkMs(int ms) { maxNonThreadedWorkMs_ = Max(ms, 1); }
-    
+
     /// Return number of worker threads.
     unsigned GetNumThreads() const { return threads_.Size(); }
+
     /// Return whether all work with at least the specified priority is finished.
     bool IsCompleted(unsigned priority) const;
+
     /// Return the pool tolerance.
     int GetTolerance() const { return tolerance_; }
+
     /// Return how many milliseconds maximum to spend on non-threaded low-priority work.
     int GetNonThreadedWorkMs() const { return maxNonThreadedWorkMs_; }
-    
+
 private:
     /// Process work items until shut down. Called by the worker threads.
     void ProcessItems(unsigned threadIndex);
@@ -125,7 +130,7 @@ private:
     void ReturnToPool(SharedPtr<WorkItem>& item);
     /// Handle frame start event. Purge completed work from the main thread queue, and perform work if no threads at all.
     void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
-    
+
     /// Worker threads.
     Vector<SharedPtr<WorkerThread> > threads_;
     /// Work item pool for reuse to cut down on allocation. The bool is a flag for item pooling and whether it is available or not.

+ 10 - 11
Source/Urho3D/Engine/Application.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Engine/Application.h"
 #include "../Engine/Engine.h"
 #ifdef IOS
@@ -28,9 +30,6 @@
 #endif
 #include "../IO/IOEvents.h"
 #include "../IO/Log.h"
-#include "../Core/ProcessUtils.h"
-
-#include <exception>
 
 #include "../DebugNew.h"
 
@@ -83,20 +82,20 @@ int Application::Run()
             return exitCode_;
 
         // Platforms other than iOS and EMSCRIPTEN run a blocking main loop
-        #if !defined(IOS) && !defined(EMSCRIPTEN)
+#if !defined(IOS) && !defined(EMSCRIPTEN)
         while (!engine_->IsExiting())
             engine_->RunFrame();
 
         Stop();
         // iOS will setup a timer for running animation frames so eg. Game Center can run. In this case we do not
         // support calling the Stop() function, as the application will never stop manually
-        #else
-        #if defined(IOS)
+#else
+#if defined(IOS)
         SDL_iPhoneSetAnimationCallback(GetSubsystem<Graphics>()->GetImpl()->GetWindow(), 1, &RunFrame, engine_);
-        #elif defined(EMSCRIPTEN)
+#elif defined(EMSCRIPTEN)
         emscripten_set_main_loop_arg(RunFrame, engine_, 0, 1);
-        #endif
-        #endif
+#endif
+#endif
 
         return exitCode_;
     }
@@ -115,10 +114,10 @@ void Application::ErrorExit(const String& message)
     // Only for WIN32, otherwise the error messages would be double posted on Mac OS X and Linux platforms
     if (!message.Length())
     {
-        #ifdef WIN32
+#ifdef WIN32
         ErrorDialog(GetTypeName(), startupErrors_.Length() ? startupErrors_ :
             "Application has been terminated due to unexpected error.");
-        #endif
+#endif
     }
     else
         ErrorDialog(GetTypeName(), message);

+ 8 - 6
Source/Urho3D/Engine/Application.h

@@ -35,17 +35,19 @@ class Engine;
 class URHO3D_API Application : public Object
 {
     OBJECT(Application);
-    
+
 public:
     /// Construct. Parse default engine parameters from the command line, and create the engine in an uninitialized state.
     Application(Context* context);
 
     /// Setup before engine initialization. This is a chance to eg. modify the engine parameters. Call ErrorExit() to terminate without initializing the engine. Called by Application.
-    virtual void Setup() {}
+    virtual void Setup() { }
+
     /// Setup after engine initialization and before running the main loop. Call ErrorExit() to terminate without running the main loop. Called by Application.
-    virtual void Start() {}
+    virtual void Start() { }
+
     /// Cleanup after the main loop. Called by Application.
-    virtual void Stop() {}
+    virtual void Stop() { }
 
     /// Initialize the engine and run the main loop, then return the application exit code. Catch out-of-memory exceptions while running.
     int Run();
@@ -55,7 +57,7 @@ public:
 protected:
     /// Handle log message.
     void HandleLogMessage(StringHash eventType, VariantMap& eventData);
-    
+
     /// Urho3D engine.
     SharedPtr<Engine> engine_;
     /// Engine parameters map.
@@ -87,5 +89,5 @@ int RunApplication() \
 } \
 DEFINE_MAIN(RunApplication());
 #endif
-    
+
 }

+ 24 - 20
Source/Urho3D/Engine/Console.cpp

@@ -20,21 +20,22 @@
 // THE SOFTWARE.
 //
 
-#include "../Engine/Console.h"
+#include "../Precompiled.h"
+
 #include "../Core/Context.h"
 #include "../Core/CoreEvents.h"
-#include "../UI/DropDownList.h"
+#include "../Engine/Console.h"
 #include "../Engine/EngineEvents.h"
-#include "../UI/Font.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/GraphicsEvents.h"
 #include "../Input/Input.h"
-#include "../Input/InputEvents.h"
 #include "../IO/IOEvents.h"
-#include "../UI/LineEdit.h"
-#include "../UI/ListView.h"
 #include "../IO/Log.h"
 #include "../Resource/ResourceCache.h"
+#include "../UI/DropDownList.h"
+#include "../UI/Font.h"
+#include "../UI/LineEdit.h"
+#include "../UI/ListView.h"
 #include "../UI/ScrollBar.h"
 #include "../UI/Text.h"
 #include "../UI/UI.h"
@@ -120,7 +121,7 @@ void Console::SetDefaultStyle(XMLFile* style)
 
     closeButton_->SetDefaultStyle(style);
     closeButton_->SetStyle("CloseButton");
-    
+
     UpdateElements();
 }
 
@@ -202,7 +203,7 @@ void Console::SetNumRows(unsigned rows)
     displayedRows_ = rows;
     if (GetNumBufferedRows() < rows)
         SetNumBufferedRows(rows);
-    
+
     UpdateElements();
 }
 
@@ -226,7 +227,8 @@ void Console::UpdateElements()
     const IntRect& border = background_->GetLayoutBorder();
     const IntRect& panelBorder = rowContainer_->GetScrollPanel()->GetClipBorder();
     rowContainer_->SetFixedWidth(width - border.left_ - border.right_);
-    rowContainer_->SetFixedHeight(displayedRows_ * rowContainer_->GetItem((unsigned)0)->GetHeight() + panelBorder.top_ + panelBorder.bottom_ +
+    rowContainer_->SetFixedHeight(
+        displayedRows_ * rowContainer_->GetItem((unsigned)0)->GetHeight() + panelBorder.top_ + panelBorder.bottom_ +
         (rowContainer_->GetHorizontalScrollBar()->IsVisible() ? rowContainer_->GetHorizontalScrollBar()->GetHeight() : 0));
     background_->SetFixedWidth(width);
     background_->SetHeight(background_->GetMinHeight());
@@ -314,10 +316,10 @@ void Console::HandleTextFinished(StringHash eventType, VariantMap& eventData)
         // Send the command as an event for script subsystem
         using namespace ConsoleCommand;
 
-        VariantMap& eventData = GetEventDataMap();
-        eventData[P_COMMAND] = line;
-        eventData[P_ID] = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
-        SendEvent(E_CONSOLECOMMAND, eventData);
+        VariantMap& newEventData = GetEventDataMap();
+        newEventData[P_COMMAND] = line;
+        newEventData[P_ID] = static_cast<Text*>(interpreters_->GetSelectedItem())->GetText();
+        SendEvent(E_CONSOLECOMMAND, newEventData);
 
         // Store to history, then clear the lineedit
         history_.Push(line);
@@ -358,6 +360,8 @@ void Console::HandleLineEditKey(StringHash eventType, VariantMap& eventData)
             changed = true;
         }
         break;
+
+    default: break;
     }
 
     if (changed)
@@ -384,13 +388,13 @@ void Console::HandleLogMessage(StringHash eventType, VariantMap& eventData)
     // If printing a log message causes more messages to be logged (error accessing font), disregard them
     if (printing_)
         return;
-    
+
     using namespace LogMessage;
 
     int level = eventData[P_LEVEL].GetInt();
     // The message may be multi-line, so split to rows in that case
     Vector<String> rows = eventData[P_MESSAGE].GetString().Split('\n');
-    
+
     for (unsigned i = 0; i < rows.Size(); ++i)
         pendingRows_.Push(MakePair(level, rows[i]));
 
@@ -411,11 +415,11 @@ void Console::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
 
     if (!rowContainer_->GetNumItems() || pendingRows_.Empty())
         return;
-    
+
     printing_ = true;
     rowContainer_->DisableLayoutUpdate();
-    
-    Text* text;
+
+    Text* text = 0;
     for (unsigned i = 0; i < pendingRows_.Size(); ++i)
     {
         rowContainer_->RemoveItem((unsigned)0);
@@ -425,9 +429,9 @@ void Console::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
         text->SetStyle(pendingRows_[i].first_ == LOG_ERROR ? "ConsoleHighlightedText" : "ConsoleText");
         rowContainer_->AddItem(text);
     }
-    
+
     pendingRows_.Clear();
-    
+
     rowContainer_->EnsureItemVisibility(text);
     rowContainer_->EnableLayoutUpdate();
     rowContainer_->UpdateLayout();

+ 16 - 0
Source/Urho3D/Engine/Console.h

@@ -55,10 +55,13 @@ public:
     void SetVisible(bool enable);
     /// Toggle visibility.
     void Toggle();
+
     /// Automatically set console to visible when receiving an error log message.
     void SetAutoVisibleOnError(bool enable) { autoVisibleOnError_ = enable; }
+
     /// Set the command interpreter.
     void SetCommandInterpreter(const String& interpreter) { commandInterpreter_ = interpreter; }
+
     /// Set number of buffered rows.
     void SetNumBufferedRows(unsigned rows);
     /// Set number of displayed rows.
@@ -72,30 +75,43 @@ public:
 
     /// Return the UI style file.
     XMLFile* GetDefaultStyle() const;
+
     /// Return the background element.
     BorderImage* GetBackground() const { return background_; }
+
     /// Return the line edit element.
     LineEdit* GetLineEdit() const { return lineEdit_; }
+
     /// Return the close butoon element.
     Button* GetCloseButton() const { return closeButton_; }
+
     /// Return whether is visible.
     bool IsVisible() const;
+
     /// Return true when console is set to automatically visible when receiving an error log message.
     bool IsAutoVisibleOnError() const { return autoVisibleOnError_; }
+
     /// Return the last used command interpreter.
     const String& GetCommandInterpreter() const { return commandInterpreter_; }
+
     /// Return number of buffered rows.
     unsigned GetNumBufferedRows() const;
+
     /// Return number of displayed rows.
     unsigned GetNumRows() const { return displayedRows_; }
+
     /// Copy selected rows to system clipboard.
     void CopySelectedRows() const;
+
     /// Return history maximum size.
     unsigned GetNumHistoryRows() const { return historyRows_; }
+
     /// Return current history position.
     unsigned GetHistoryPosition() const { return historyPosition_; }
+
     /// Return history row at index.
     const String& GetHistoryRow(unsigned index) const;
+
     /// Return whether automatically focuses the line edit when showing.
     bool GetFocusOnShow() const { return focusOnShow_; }
 

+ 6 - 4
Source/Urho3D/Engine/DebugHud.cpp

@@ -20,14 +20,16 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Core/CoreEvents.h"
+#include "../Core/Profiler.h"
 #include "../Engine/DebugHud.h"
 #include "../Engine/Engine.h"
-#include "../UI/Font.h"
 #include "../Graphics/Graphics.h"
-#include "../IO/Log.h"
-#include "../Core/Profiler.h"
 #include "../Graphics/Renderer.h"
+#include "../IO/Log.h"
+#include "../UI/Font.h"
 #include "../UI/Text.h"
 #include "../UI/UI.h"
 
@@ -203,7 +205,7 @@ void DebugHud::SetProfilerMaxDepth(unsigned depth)
 
 void DebugHud::SetProfilerInterval(float interval)
 {
-    profilerInterval_ = Max((int)(interval * 1000.0f), 0);
+    profilerInterval_ = (unsigned)Max((int)(interval * 1000.0f), 0);
 }
 
 void DebugHud::SetUseRendererStats(bool enable)

+ 7 - 0
Source/Urho3D/Engine/DebugHud.h

@@ -69,21 +69,28 @@ public:
 
     /// Return the UI style file.
     XMLFile* GetDefaultStyle() const;
+
     /// Return rendering stats text.
     Text* GetStatsText() const { return statsText_; }
+
     /// Return rendering mode text.
     Text* GetModeText() const { return modeText_; }
+
     /// Return profiler text.
     Text* GetProfilerText() const { return profilerText_; }
+
     /// Return currently shown elements.
     unsigned GetMode() const { return mode_; }
+
     /// Return maximum profiler block depth.
     unsigned GetProfilerMaxDepth() const { return profilerMaxDepth_; }
+
     /// Return profiler accumulation interval in seconds
     float GetProfilerInterval() const;
 
     /// Return whether showing 3D geometry primitive/batch count only.
     bool GetUseRendererStats() const { return useRendererStats_; }
+
     /// Set application-specific stats.
     void SetAppStats(const String& label, const Variant& stats);
     /// Set application-specific stats.

+ 67 - 55
Source/Urho3D/Engine/Engine.cpp

@@ -20,30 +20,32 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Audio/Audio.h"
-#include "../Engine/Console.h"
 #include "../Core/Context.h"
 #include "../Core/CoreEvents.h"
+#include "../Core/ProcessUtils.h"
+#include "../Core/Profiler.h"
+#include "../Core/WorkQueue.h"
+#include "../Engine/Console.h"
 #include "../Engine/DebugHud.h"
 #include "../Engine/Engine.h"
-#include "../IO/FileSystem.h"
 #include "../Graphics/Graphics.h"
+#include "../Graphics/Renderer.h"
+#include "../IO/FileSystem.h"
 #include "../Input/Input.h"
-#include "../Input/InputEvents.h"
 #include "../IO/Log.h"
+#include "../IO/PackageFile.h"
 #ifdef URHO3D_NAVIGATION
 #include "../Navigation/NavigationMesh.h"
 #endif
 #ifdef URHO3D_NETWORK
 #include "../Network/Network.h"
 #endif
-#include "../IO/PackageFile.h"
 #ifdef URHO3D_PHYSICS
 #include "../Physics/PhysicsWorld.h"
 #endif
-#include "../Core/ProcessUtils.h"
-#include "../Core/Profiler.h"
-#include "../Graphics/Renderer.h"
 #include "../Resource/ResourceCache.h"
 #include "../Scene/Scene.h"
 #include "../Scene/SceneEvents.h"
@@ -51,8 +53,6 @@
 #ifdef URHO3D_URHO2D
 #include "../Urho2D/Urho2D.h"
 #endif
-#include "../Core/WorkQueue.h"
-#include "../Resource/XMLFile.h"
 
 #if defined(EMSCRIPTEN) && defined(URHO3D_TESTING)
 #include <emscripten.h>
@@ -87,15 +87,15 @@ Engine::Engine(Context* context) :
     timeStep_(0.0f),
     timeStepSmoothing_(2),
     minFps_(10),
-    #if defined(ANDROID) || defined(IOS) || defined(RPI)
+#if defined(ANDROID) || defined(IOS) || defined(RPI)
     maxFps_(60),
     maxInactiveFps_(10),
     pauseMinimized_(true),
-    #else
+#else
     maxFps_(200),
     maxInactiveFps_(60),
     pauseMinimized_(false),
-    #endif
+#endif
 #ifdef URHO3D_TESTING
     timeOut_(0),
 #endif
@@ -111,17 +111,17 @@ Engine::Engine(Context* context) :
     // Create subsystems which do not depend on engine initialization or startup parameters
     context_->RegisterSubsystem(new Time(context_));
     context_->RegisterSubsystem(new WorkQueue(context_));
-    #ifdef URHO3D_PROFILING
+#ifdef URHO3D_PROFILING
     context_->RegisterSubsystem(new Profiler(context_));
-    #endif
+#endif
     context_->RegisterSubsystem(new FileSystem(context_));
-    #ifdef URHO3D_LOGGING
+#ifdef URHO3D_LOGGING
     context_->RegisterSubsystem(new Log(context_));
-    #endif
+#endif
     context_->RegisterSubsystem(new ResourceCache(context_));
-    #ifdef URHO3D_NETWORK
+#ifdef URHO3D_NETWORK
     context_->RegisterSubsystem(new Network(context_));
-    #endif
+#endif
     context_->RegisterSubsystem(new Input(context_));
     context_->RegisterSubsystem(new Audio(context_));
     context_->RegisterSubsystem(new UI(context_));
@@ -202,7 +202,8 @@ bool Engine::Initialize(const VariantMap& parameters)
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     FileSystem* fileSystem = GetSubsystem<FileSystem>();
 
-    String resourcePrefixPath = AddTrailingSlash(GetParameter(parameters, "ResourcePrefixPath", getenv("URHO3D_PREFIX_PATH")).GetString());
+    String resourcePrefixPath =
+        AddTrailingSlash(GetParameter(parameters, "ResourcePrefixPath", getenv("URHO3D_PREFIX_PATH")).GetString());
     if (resourcePrefixPath.Empty())
         resourcePrefixPath = fileSystem->GetProgramDir();
     else if (!IsAbsolutePath(resourcePrefixPath))
@@ -238,7 +239,8 @@ bool Engine::Initialize(const VariantMap& parameters)
 
         if (!success)
         {
-            LOGERRORF("Failed to add resource path '%s', check the documentation on how to set the 'resource prefix path'", resourcePaths[i].CString());
+            LOGERRORF("Failed to add resource path '%s', check the documentation on how to set the 'resource prefix path'",
+                resourcePaths[i].CString());
             return false;
         }
     }
@@ -251,12 +253,15 @@ bool Engine::Initialize(const VariantMap& parameters)
         {
             if (!cache->AddPackageFile(packageName))
             {
-                LOGERRORF("Failed to add resource package '%s', check the documentation on how to set the 'resource prefix path'", resourcePackages[i].CString());
+                LOGERRORF("Failed to add resource package '%s', check the documentation on how to set the 'resource prefix path'",
+                    resourcePackages[i].CString());
                 return false;
             }
         }
         else
-            LOGDEBUGF("Skip specified resource package '%s' as it does not exist, check the documentation on how to set the 'resource prefix path'", resourcePackages[i].CString());
+            LOGDEBUGF(
+                "Skip specified resource package '%s' as it does not exist, check the documentation on how to set the 'resource prefix path'",
+                resourcePackages[i].CString());
     }
 
     // Add auto load folders. Prioritize these (if exist) before the default folders
@@ -280,7 +285,9 @@ bool Engine::Initialize(const VariantMap& parameters)
                 String autoResourceDir = autoLoadPath + "/" + dir;
                 if (!cache->AddResourceDir(autoResourceDir, 0))
                 {
-                    LOGERRORF("Failed to add resource directory '%s' in autoload path %s, check the documentation on how to set the 'resource prefix path'", dir.CString(), autoLoadPaths[i].CString());
+                    LOGERRORF(
+                        "Failed to add resource directory '%s' in autoload path %s, check the documentation on how to set the 'resource prefix path'",
+                        dir.CString(), autoLoadPaths[i].CString());
                     return false;
                 }
             }
@@ -297,13 +304,17 @@ bool Engine::Initialize(const VariantMap& parameters)
                 String autoPackageName = autoLoadPath + "/" + pak;
                 if (!cache->AddPackageFile(autoPackageName, 0))
                 {
-                    LOGERRORF("Failed to add package file '%s' in autoload path %s, check the documentation on how to set the 'resource prefix path'", pak.CString(), autoLoadPaths[i].CString());
+                    LOGERRORF(
+                        "Failed to add package file '%s' in autoload path %s, check the documentation on how to set the 'resource prefix path'",
+                        pak.CString(), autoLoadPaths[i].CString());
                     return false;
                 }
             }
         }
         else
-            LOGDEBUGF("Skipped autoload path '%s' as it does not exist, check the documentation on how to set the 'resource prefix path'", autoLoadPaths[i].CString());
+            LOGDEBUGF(
+                "Skipped autoload path '%s' as it does not exist, check the documentation on how to set the 'resource prefix path'",
+                autoLoadPaths[i].CString());
     }
 
     // Initialize graphics & audio output
@@ -320,12 +331,13 @@ bool Engine::Initialize(const VariantMap& parameters)
         graphics->SetOrientations(GetParameter(parameters, "Orientations", "LandscapeLeft LandscapeRight").GetString());
 
         if (HasParameter(parameters, "WindowPositionX") && HasParameter(parameters, "WindowPositionY"))
-            graphics->SetWindowPosition(GetParameter(parameters, "WindowPositionX").GetInt(), GetParameter(parameters, "WindowPositionY").GetInt());
+            graphics->SetWindowPosition(GetParameter(parameters, "WindowPositionX").GetInt(),
+                GetParameter(parameters, "WindowPositionY").GetInt());
 
-        #ifdef URHO3D_OPENGL
+#ifdef URHO3D_OPENGL
         if (HasParameter(parameters, "ForceGL2"))
             graphics->SetForceGL2(GetParameter(parameters, "ForceGL2").GetBool());
-        #endif
+#endif
 
         if (!graphics->SetMode(
             GetParameter(parameters, "WindowWidth", 0).GetInt(),
@@ -370,20 +382,20 @@ bool Engine::Initialize(const VariantMap& parameters)
     if (HasParameter(parameters, "TouchEmulation"))
         GetSubsystem<Input>()->SetTouchEmulation(GetParameter(parameters, "TouchEmulation").GetBool());
 
-    #ifdef URHO3D_TESTING
+#ifdef URHO3D_TESTING
     if (HasParameter(parameters, "TimeOut"))
         timeOut_ = GetParameter(parameters, "TimeOut", 0).GetInt() * 1000000LL;
-    #endif
+#endif
 
     // In debug mode, check now that all factory created objects can be created without crashing
-    #ifdef _DEBUG
+#ifdef _DEBUG
     if (!resourcePaths.Empty())
     {
         const HashMap<StringHash, SharedPtr<ObjectFactory> >& factories = context_->GetObjectFactories();
         for (HashMap<StringHash, SharedPtr<ObjectFactory> >::ConstIterator i = factories.Begin(); i != factories.End(); ++i)
             SharedPtr<Object> object = i->second_->CreateObject();
     }
-    #endif
+#endif
 
     frameTimer_.Reset();
 
@@ -459,7 +471,7 @@ DebugHud* Engine::CreateDebugHud()
     if (headless_ || !initialized_)
         return 0;
 
-     // Return existing debug HUD if possible
+    // Return existing debug HUD if possible
     DebugHud* debugHud = GetSubsystem<DebugHud>();
     if (!debugHud)
     {
@@ -472,22 +484,22 @@ DebugHud* Engine::CreateDebugHud()
 
 void Engine::SetTimeStepSmoothing(int frames)
 {
-    timeStepSmoothing_ = Clamp(frames, 1, 20);
+    timeStepSmoothing_ = (unsigned)Clamp(frames, 1, 20);
 }
 
 void Engine::SetMinFps(int fps)
 {
-    minFps_ = Max(fps, 0);
+    minFps_ = (unsigned)Max(fps, 0);
 }
 
 void Engine::SetMaxFps(int fps)
 {
-    maxFps_ = Max(fps, 0);
+    maxFps_ = (unsigned)Max(fps, 0);
 }
 
 void Engine::SetMaxInactiveFps(int fps)
 {
-    maxInactiveFps_ = Max(fps, 0);
+    maxInactiveFps_ = (unsigned)Max(fps, 0);
 }
 
 void Engine::SetPauseMinimized(bool enable)
@@ -527,7 +539,7 @@ void Engine::DumpProfiler()
 
 void Engine::DumpResources(bool dumpFileName)
 {
-    #ifdef URHO3D_LOGGING
+#ifdef URHO3D_LOGGING
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     const HashMap<StringHash, ResourceGroup>& resourceGroups = cache->GetAllResources();
     LOGRAW("\n");
@@ -538,13 +550,13 @@ void Engine::DumpResources(bool dumpFileName)
     }
 
     for (HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups.Begin();
-        i != resourceGroups.End(); ++i)
+         i != resourceGroups.End(); ++i)
     {
         const HashMap<StringHash, SharedPtr<Resource> >& resources = i->second_.resources_;
         if (dumpFileName)
         {
             for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator j = resources.Begin();
-                j != resources.End(); ++j)
+                 j != resources.End(); ++j)
             {
                 LOGRAW(j->second_->GetName() + "\n");
             }
@@ -558,7 +570,7 @@ void Engine::DumpResources(bool dumpFileName)
             if (num)
             {
                 LOGRAW("Resource type " + resources.Begin()->second_->GetTypeName() +
-                    ": count " + String(num) + " memory use " + String(memoryUse) + "\n");
+                       ": count " + String(num) + " memory use " + String(memoryUse) + "\n");
             }
         }
     }
@@ -567,13 +579,13 @@ void Engine::DumpResources(bool dumpFileName)
     {
         LOGRAW("Total memory use of all resources " + String(cache->GetTotalMemoryUse()) + "\n\n");
     }
-    #endif
+#endif
 }
 
 void Engine::DumpMemory()
 {
-    #ifdef URHO3D_LOGGING
-    #if defined(_MSC_VER) && defined(_DEBUG)
+#ifdef URHO3D_LOGGING
+#if defined(_MSC_VER) && defined(_DEBUG)
     _CrtMemState state;
     _CrtMemCheckpoint(&state);
     _CrtMemBlockHeader* block = state.pBlockHeader;
@@ -604,10 +616,10 @@ void Engine::DumpMemory()
     }
 
     LOGRAW("Total allocated memory " + String(total) + " bytes in " + String(blocks) + " blocks\n\n");
-    #else
+#else
     LOGRAW("DumpMemory() supported on MSVC debug mode only\n\n");
-    #endif
-    #endif
+#endif
+#endif
 }
 
 void Engine::Update()
@@ -683,14 +695,14 @@ void Engine::ApplyFrameLimit()
     }
 
     elapsed = frameTimer_.GetUSec(true);
-    #ifdef URHO3D_TESTING
+#ifdef URHO3D_TESTING
     if (timeOut_ > 0)
     {
         timeOut_ -= elapsed;
         if (timeOut_ <= 0)
             Exit();
     }
-    #endif
+#endif
 
     // If FPS lower than minimum, clamp elapsed time
     if (minFps_)
@@ -773,8 +785,8 @@ VariantMap Engine::ParseParameters(const Vector<String>& arguments)
                 ret["LogQuiet"] = true;
             else if (argument == "log" && !value.Empty())
             {
-                int logLevel = GetStringListIndex(value.CString(), logLevelPrefixes, -1);
-                if (logLevel != -1)
+                unsigned logLevel = GetStringListIndex(value.CString(), logLevelPrefixes, M_MAX_UNSIGNED);
+                if (logLevel != M_MAX_UNSIGNED)
                 {
                     ret["LogLevel"] = logLevel;
                     ++i;
@@ -853,13 +865,13 @@ VariantMap Engine::ParseParameters(const Vector<String>& arguments)
             }
             else if (argument == "touch")
                 ret["TouchEmulation"] = true;
-            #ifdef URHO3D_TESTING
+#ifdef URHO3D_TESTING
             else if (argument == "timeout" && !value.Empty())
             {
                 ret["TimeOut"] = ToInt(value);
                 ++i;
             }
-            #endif
+#endif
         }
     }
 
@@ -896,9 +908,9 @@ void Engine::DoExit()
         graphics->Close();
 
     exiting_ = true;
-    #if defined(EMSCRIPTEN) && defined(URHO3D_TESTING)
+#if defined(EMSCRIPTEN) && defined(URHO3D_TESTING)
     emscripten_force_exit(EXIT_SUCCESS);    // Some how this is required to signal emrun to stop
-    #endif
+#endif
 }
 
 }

+ 18 - 8
Source/Urho3D/Engine/Engine.h

@@ -35,13 +35,13 @@ class DebugHud;
 class URHO3D_API Engine : public Object
 {
     OBJECT(Engine);
-    
+
 public:
     /// Construct.
     Engine(Context* context);
     /// Destruct. Free all subsystems.
     virtual ~Engine();
-    
+
     /// Initialize engine using parameters given and show the application window. Return true if successful.
     bool Initialize(const VariantMap& parameters);
     /// Run one frame.
@@ -72,48 +72,58 @@ public:
     void DumpResources(bool dumpFileName = false);
     /// Dump information of all memory allocations to the log. Supported in MSVC debug mode only.
     void DumpMemory();
-    
+
     /// Get timestep of the next frame. Updated by ApplyFrameLimit().
     float GetNextTimeStep() const { return timeStep_; }
+
     /// Return the minimum frames per second.
     int GetMinFps() const { return minFps_; }
+
     /// Return the maximum frames per second.
     int GetMaxFps() const { return maxFps_; }
+
     /// Return the maximum frames per second when the application does not have input focus.
     int GetMaxInactiveFps() const { return maxInactiveFps_; }
+
     /// Return how many frames to average for timestep smoothing.
     int GetTimeStepSmoothing() const { return timeStepSmoothing_; }
+
     /// Return whether to pause update events and audio when minimized.
     bool GetPauseMinimized() const { return pauseMinimized_; }
+
     /// Return whether to exit automatically on exit request.
     bool GetAutoExit() const { return autoExit_; }
+
     /// Return whether engine has been initialized.
     bool IsInitialized() const { return initialized_; }
+
     /// Return whether exit has been requested.
     bool IsExiting() const { return exiting_; }
+
     /// Return whether the engine has been created in headless mode.
     bool IsHeadless() const { return headless_; }
-    
+
     /// Send frame update events.
     void Update();
     /// Render after frame update.
     void Render();
     /// Get the timestep for the next frame and sleep for frame limiting if necessary.
     void ApplyFrameLimit();
-    
+
     /// Parse the engine startup parameters map from command line arguments.
     static VariantMap ParseParameters(const Vector<String>& arguments);
     /// Return whether startup parameters contains a specific parameter.
     static bool HasParameter(const VariantMap& parameters, const String& parameter);
     /// Get an engine startup parameter, with default value if missing.
-    static const Variant& GetParameter(const VariantMap& parameters, const String& parameter, const Variant& defaultValue = Variant::EMPTY);
-    
+    static const Variant
+        & GetParameter(const VariantMap& parameters, const String& parameter, const Variant& defaultValue = Variant::EMPTY);
+
 private:
     /// Handle exit requested event. Auto-exit if enabled.
     void HandleExitRequested(StringHash eventType, VariantMap& eventData);
     /// Actually perform the exit actions.
     void DoExit();
-    
+
     /// Frame update timer.
     HiresTimer frameTimer_;
     /// Previous timesteps for smoothing.

+ 22 - 14
Source/Urho3D/Graphics/AnimatedModel.cpp

@@ -20,26 +20,27 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
+#include "../Core/Context.h"
+#include "../Core/Profiler.h"
 #include "../Graphics/AnimatedModel.h"
 #include "../Graphics/Animation.h"
 #include "../Graphics/AnimationState.h"
 #include "../Graphics/Batch.h"
 #include "../Graphics/Camera.h"
-#include "../Core/Context.h"
 #include "../Graphics/DebugRenderer.h"
 #include "../Graphics/DrawableEvents.h"
 #include "../Graphics/Geometry.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/IndexBuffer.h"
-#include "../IO/Log.h"
 #include "../Graphics/Material.h"
 #include "../Graphics/Octree.h"
-#include "../Core/Profiler.h"
+#include "../Graphics/VertexBuffer.h"
+#include "../IO/Log.h"
 #include "../Resource/ResourceCache.h"
 #include "../Resource/ResourceEvents.h"
 #include "../Scene/Scene.h"
-#include "../Container/Sort.h"
-#include "../Graphics/VertexBuffer.h"
 
 #include "../DebugNew.h"
 
@@ -92,7 +93,8 @@ void AnimatedModel::RegisterObject(Context* context)
 
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
     MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
-    ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()), AM_DEFAULT);
+    ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()),
+        AM_DEFAULT);
     ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
     ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
@@ -102,9 +104,12 @@ void AnimatedModel::RegisterObject(Context* context)
     ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
     COPY_BASE_ATTRIBUTES(Drawable);
-    MIXED_ACCESSOR_ATTRIBUTE("Bone Animation Enabled", GetBonesEnabledAttr, SetBonesEnabledAttr, VariantVector, Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
-    MIXED_ACCESSOR_ATTRIBUTE("Animation States", GetAnimationStatesAttr, SetAnimationStatesAttr, VariantVector, Variant::emptyVariantVector, AM_FILE);
-    ACCESSOR_ATTRIBUTE("Morphs", GetMorphsAttr, SetMorphsAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_DEFAULT | AM_NOEDIT);
+    MIXED_ACCESSOR_ATTRIBUTE("Bone Animation Enabled", GetBonesEnabledAttr, SetBonesEnabledAttr, VariantVector,
+        Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
+    MIXED_ACCESSOR_ATTRIBUTE("Animation States", GetAnimationStatesAttr, SetAnimationStatesAttr, VariantVector,
+        Variant::emptyVariantVector, AM_FILE);
+    ACCESSOR_ATTRIBUTE("Morphs", GetMorphsAttr, SetMorphsAttr, PODVector<unsigned char>, Variant::emptyBuffer,
+        AM_DEFAULT | AM_NOEDIT);
 }
 
 bool AnimatedModel::Load(Deserializer& source, bool setInstanceDefault)
@@ -332,7 +337,8 @@ void AnimatedModel::SetModel(Model* model, bool createBones)
             newMorph.nameHash_ = morphs[i].nameHash_;
             newMorph.weight_ = 0.0f;
             newMorph.buffers_ = morphs[i].buffers_;
-            for (HashMap<unsigned, VertexBufferMorph>::ConstIterator j = morphs[i].buffers_.Begin(); j != morphs[i].buffers_.End(); ++j)
+            for (HashMap<unsigned, VertexBufferMorph>::ConstIterator j = morphs[i].buffers_.Begin();
+                 j != morphs[i].buffers_.End(); ++j)
                 morphElementMask_ |= j->second_.elementMask_;
             morphs_.Push(newMorph);
         }
@@ -660,7 +666,7 @@ void AnimatedModel::SetSkeleton(const Skeleton& skeleton, bool createBones)
             for (unsigned i = 0; i < destBones.Size(); ++i)
             {
                 if (destBones[i].node_ && destBones[i].name_ == srcBones[i].name_ && destBones[i].parentIndex_ ==
-                    srcBones[i].parentIndex_)
+                                                                                     srcBones[i].parentIndex_)
                 {
                     // If compatible, just copy the values and retain the old node and animated status
                     Node* boneNode = destBones[i].node_;
@@ -789,7 +795,7 @@ void AnimatedModel::SetAnimationStatesAttr(const VariantVector& value)
             newState->SetLooped(value[index++].GetBool());
             newState->SetWeight(value[index++].GetFloat());
             newState->SetTime(value[index++].GetFloat());
-            newState->SetLayer(value[index++].GetInt());
+            newState->SetLayer((unsigned char)value[index++].GetInt());
         }
         else
         {
@@ -1039,7 +1045,8 @@ void AnimatedModel::CloneGeometries()
     MarkMorphsDirty();
 }
 
-void AnimatedModel::CopyMorphVertices(void* destVertexData, void* srcVertexData, unsigned vertexCount, VertexBuffer* destBuffer, VertexBuffer* srcBuffer)
+void AnimatedModel::CopyMorphVertices(void* destVertexData, void* srcVertexData, unsigned vertexCount, VertexBuffer* destBuffer,
+    VertexBuffer* srcBuffer)
 {
     unsigned mask = destBuffer->GetElementMask() & srcBuffer->GetElementMask();
     unsigned normalOffset = srcBuffer->GetElementOffset(ELEMENT_NORMAL);
@@ -1266,7 +1273,8 @@ void AnimatedModel::UpdateMorphs()
     morphsDirty_ = false;
 }
 
-void AnimatedModel::ApplyMorph(VertexBuffer* buffer, void* destVertexData, unsigned morphRangeStart, const VertexBufferMorph& morph, float weight)
+void AnimatedModel::ApplyMorph(VertexBuffer* buffer, void* destVertexData, unsigned morphRangeStart, const VertexBufferMorph& morph,
+    float weight)
 {
     unsigned elementMask = morph.elementMask_ & buffer->GetElementMask();
     unsigned vertexCount = morph.vertexCount_;

+ 14 - 1
Source/Urho3D/Graphics/AnimatedModel.h

@@ -97,10 +97,13 @@ public:
 
     /// Return skeleton.
     Skeleton& GetSkeleton() { return skeleton_; }
+
     /// Return all animation states.
     const Vector<SharedPtr<AnimationState> >& GetAnimationStates() const { return animationStates_; }
+
     /// Return number of animation states.
     unsigned GetNumAnimationStates() const { return animationStates_.Size(); }
+
     /// Return animation state by animation pointer.
     AnimationState* GetAnimationState(Animation* animation) const;
     /// Return animation state by animation name.
@@ -109,22 +112,29 @@ public:
     AnimationState* GetAnimationState(const StringHash animationNameHash) const;
     /// Return animation state by index.
     AnimationState* GetAnimationState(unsigned index) const;
+
     /// Return animation LOD bias.
     float GetAnimationLodBias() const { return animationLodBias_; }
+
     /// Return whether to update animation when not visible.
     bool GetUpdateInvisible() const { return updateInvisible_; }
+
     /// Return all vertex morphs.
     const Vector<ModelMorph>& GetMorphs() const { return morphs_; }
+
     /// Return all morph vertex buffers.
     const Vector<SharedPtr<VertexBuffer> >& GetMorphVertexBuffers() const { return morphVertexBuffers_; }
+
     /// Return number of vertex morphs.
     unsigned GetNumMorphs() const { return morphs_.Size(); }
+
     /// Return vertex morph weight by index.
     float GetMorphWeight(unsigned index) const;
     /// Return vertex morph weight by name.
     float GetMorphWeight(const String& name) const;
     /// Return vertex morph weight by name hash.
     float GetMorphWeight(StringHash nameHash) const;
+
     /// Return whether is the master (first) animated model.
     bool IsMaster() const { return isMaster_; }
 
@@ -144,8 +154,10 @@ public:
     VariantVector GetAnimationStatesAttr() const;
     /// Return morphs attribute.
     const PODVector<unsigned char>& GetMorphsAttr() const;
+
     /// Return per-geometry bone mappings.
     const Vector<PODVector<unsigned> >& GetGeometryBoneMappings() const { return geometryBoneMappings_; }
+
     /// Return per-geometry skin matrices. If empty, uses global skinning
     const Vector<PODVector<Matrix3x4> >& GetGeometrySkinMatrices() const { return geometrySkinMatrices_; }
 
@@ -185,7 +197,8 @@ private:
     /// Reapply all vertex morphs.
     void UpdateMorphs();
     /// Apply a vertex morph.
-    void ApplyMorph(VertexBuffer* buffer, void* destVertexData, unsigned morphRangeStart, const VertexBufferMorph& morph, float weight);
+    void ApplyMorph
+        (VertexBuffer* buffer, void* destVertexData, unsigned morphRangeStart, const VertexBufferMorph& morph, float weight);
     /// Handle model reload finished.
     void HandleModelReloadFinished(StringHash eventType, VariantMap& eventData);
 

+ 28 - 26
Source/Urho3D/Graphics/Animation.cpp

@@ -20,14 +20,16 @@
 // THE SOFTWARE.
 //
 
-#include "../Graphics/Animation.h"
+#include "../Precompiled.h"
+
 #include "../Core/Context.h"
+#include "../Core/Profiler.h"
+#include "../Graphics/Animation.h"
 #include "../IO/Deserializer.h"
 #include "../IO/FileSystem.h"
 #include "../IO/Log.h"
-#include "../Core/Profiler.h"
-#include "../Resource/ResourceCache.h"
 #include "../IO/Serializer.h"
+#include "../Resource/ResourceCache.h"
 #include "../Resource/XMLFile.h"
 
 #include "../DebugNew.h"
@@ -44,14 +46,14 @@ void AnimationTrack::GetKeyFrameIndex(float time, unsigned& index) const
 {
     if (time < 0.0f)
         time = 0.0f;
-    
+
     if (index >= keyFrames_.Size())
         index = keyFrames_.Size() - 1;
-    
+
     // Check for being too far ahead
     while (index && time < keyFrames_[index].time_)
         --index;
-    
+
     // Check for being too far behind
     while (index < keyFrames_.Size() - 1 && time >= keyFrames_[index + 1].time_)
         ++index;
@@ -75,24 +77,24 @@ void Animation::RegisterObject(Context* context)
 bool Animation::BeginLoad(Deserializer& source)
 {
     unsigned memoryUse = sizeof(Animation);
-    
+
     // Check ID
     if (source.ReadFileID() != "UANI")
     {
         LOGERROR(source.GetName() + " is not a valid animation file");
         return false;
     }
-    
+
     // Read name and length
     animationName_ = source.ReadString();
     animationNameHash_ = animationName_;
     length_ = source.ReadFloat();
     tracks_.Clear();
-    
+
     unsigned tracks = source.ReadUInt();
     tracks_.Resize(tracks);
     memoryUse += tracks * sizeof(AnimationTrack);
-    
+
     // Read tracks
     for (unsigned i = 0; i < tracks; ++i)
     {
@@ -100,11 +102,11 @@ bool Animation::BeginLoad(Deserializer& source)
         newTrack.name_ = source.ReadString();
         newTrack.nameHash_ = newTrack.name_;
         newTrack.channelMask_ = source.ReadUByte();
-        
+
         unsigned keyFrames = source.ReadUInt();
         newTrack.keyFrames_.Resize(keyFrames);
         memoryUse += keyFrames * sizeof(AnimationKeyFrame);
-        
+
         // Read keyframes of the track
         for (unsigned j = 0; j < keyFrames; ++j)
         {
@@ -118,11 +120,11 @@ bool Animation::BeginLoad(Deserializer& source)
                 newKeyFrame.scale_ = source.ReadVector3();
         }
     }
-    
+
     // Optionally read triggers from an XML file
     ResourceCache* cache = GetSubsystem<ResourceCache>();
     String xmlName = ReplaceExtension(GetName(), ".xml");
-    
+
     SharedPtr<XMLFile> file(cache->GetTempResource<XMLFile>(xmlName, false));
     if (file)
     {
@@ -134,13 +136,13 @@ bool Animation::BeginLoad(Deserializer& source)
                 AddTrigger(triggerElem.GetFloat("normalizedtime"), true, triggerElem.GetVariant());
             else if (triggerElem.HasAttribute("time"))
                 AddTrigger(triggerElem.GetFloat("time"), false, triggerElem.GetVariant());
-            
+
             triggerElem = triggerElem.GetNext("trigger");
         }
 
         memoryUse += triggers_.Size() * sizeof(AnimationTriggerPoint);
     }
-    
+
     SetMemoryUse(memoryUse);
     return true;
 }
@@ -151,7 +153,7 @@ bool Animation::Save(Serializer& dest) const
     dest.WriteFileID("UANI");
     dest.WriteString(animationName_);
     dest.WriteFloat(length_);
-    
+
     // Write tracks
     dest.WriteUInt(tracks_.Size());
     for (unsigned i = 0; i < tracks_.Size(); ++i)
@@ -160,7 +162,7 @@ bool Animation::Save(Serializer& dest) const
         dest.WriteString(track.name_);
         dest.WriteUByte(track.channelMask_);
         dest.WriteUInt(track.keyFrames_.Size());
-        
+
         // Write keyframes of the track
         for (unsigned j = 0; j < track.keyFrames_.Size(); ++j)
         {
@@ -174,7 +176,7 @@ bool Animation::Save(Serializer& dest) const
                 dest.WriteVector3(keyFrame.scale_);
         }
     }
-    
+
     // If triggers have been defined, write an XML file for them
     if (triggers_.Size())
     {
@@ -182,24 +184,24 @@ bool Animation::Save(Serializer& dest) const
         if (destFile)
         {
             String xmlName = ReplaceExtension(destFile->GetName(), ".xml");
-            
+
             SharedPtr<XMLFile> xml(new XMLFile(context_));
             XMLElement rootElem = xml->CreateRoot("animation");
-            
+
             for (unsigned i = 0; i < triggers_.Size(); ++i)
             {
                 XMLElement triggerElem = rootElem.CreateChild("trigger");
                 triggerElem.SetFloat("time", triggers_[i].time_);
                 triggerElem.SetVariant(triggers_[i].data_);
             }
-            
+
             File xmlFile(context_, xmlName, FILE_WRITE);
             xml->Save(xmlFile);
         }
         else
             LOGWARNING("Can not save animation trigger data when not saving into a file");
     }
-    
+
     return true;
 }
 
@@ -225,7 +227,7 @@ void Animation::AddTrigger(float time, bool timeIsNormalized, const Variant& dat
     newTrigger.time_ = timeIsNormalized ? time * length_ : time;
     newTrigger.data_ = data;
     triggers_.Push(newTrigger);
-    
+
     Sort(triggers_.Begin(), triggers_.End(), CompareTriggers);
 }
 
@@ -257,7 +259,7 @@ const AnimationTrack* Animation::GetTrack(const String& name) const
         if (i->name_ == name)
             return &(*i);
     }
-    
+
     return 0;
 }
 
@@ -268,7 +270,7 @@ const AnimationTrack* Animation::GetTrack(StringHash nameHash) const
         if (i->nameHash_ == nameHash)
             return &(*i);
     }
-    
+
     return 0;
 }
 

+ 17 - 10
Source/Urho3D/Graphics/Animation.h

@@ -22,10 +22,10 @@
 
 #pragma once
 
-#include "../Math/Quaternion.h"
-#include "../Resource/Resource.h"
 #include "../Container/Ptr.h"
+#include "../Math/Quaternion.h"
 #include "../Math/Vector3.h"
+#include "../Resource/Resource.h"
 
 namespace Urho3D
 {
@@ -48,7 +48,7 @@ struct AnimationTrack
 {
     /// Return keyframe index based on time and previous index.
     void GetKeyFrameIndex(float time, unsigned& index) const;
-    
+
     /// Bone name.
     String name_;
     /// Bone name hash.
@@ -67,7 +67,7 @@ struct AnimationTriggerPoint
         time_(0.0f)
     {
     }
-    
+
     /// Trigger time.
     float time_;
     /// Trigger data.
@@ -82,7 +82,7 @@ static const unsigned char CHANNEL_SCALE = 0x4;
 class URHO3D_API Animation : public Resource
 {
     OBJECT(Animation);
-    
+
 public:
     /// Construct.
     Animation(Context* context);
@@ -90,12 +90,12 @@ public:
     virtual ~Animation();
     /// Register object factory.
     static void RegisterObject(Context* context);
-    
+
     /// Load resource from stream. May be called from a worker thread. Return true if successful.
     virtual bool BeginLoad(Deserializer& source);
     /// Save resource. Return true if successful.
     virtual bool Save(Serializer& dest) const;
-    
+
     /// Set animation name.
     void SetAnimationName(const String& name);
     /// Set animation length.
@@ -110,28 +110,35 @@ public:
     void RemoveAllTriggers();
     /// Resize trigger point vector.
     void SetNumTriggers(unsigned num);
-    
+
     /// Return animation name.
     const String& GetAnimationName() const { return animationName_; }
+
     /// Return animation name hash.
     StringHash GetAnimationNameHash() const { return animationNameHash_; }
+
     /// Return animation length.
     float GetLength() const { return length_; }
+
     /// Return all animation tracks.
     const Vector<AnimationTrack>& GetTracks() const { return tracks_; }
+
     /// Return number of animation tracks.
     unsigned GetNumTracks() const { return tracks_.Size(); }
+
     /// Return animation track by index.
     const AnimationTrack* GetTrack(unsigned index) const;
     /// Return animation track by bone name.
     const AnimationTrack* GetTrack(const String& name) const;
     /// Return animation track by bone name hash.
     const AnimationTrack* GetTrack(StringHash nameHash) const;
+
     /// Return animation trigger points.
     const Vector<AnimationTriggerPoint>& GetTriggers() const { return triggers_; }
+
     /// Return number of animation trigger points.
-    unsigned GetNumTriggers() const {return triggers_.Size(); }
-    
+    unsigned GetNumTriggers() const { return triggers_.Size(); }
+
 private:
     /// Animation name.
     String animationName_;

+ 12 - 7
Source/Urho3D/Graphics/AnimationController.cpp

@@ -20,14 +20,16 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
+#include "../Core/Context.h"
+#include "../Core/Profiler.h"
 #include "../Graphics/AnimatedModel.h"
 #include "../Graphics/Animation.h"
 #include "../Graphics/AnimationController.h"
 #include "../Graphics/AnimationState.h"
-#include "../Core/Context.h"
 #include "../IO/Log.h"
 #include "../IO/MemoryBuffer.h"
-#include "../Core/Profiler.h"
 #include "../Resource/ResourceCache.h"
 #include "../Scene/Scene.h"
 #include "../Scene/SceneEvents.h"
@@ -62,9 +64,12 @@ void AnimationController::RegisterObject(Context* context)
     context->RegisterFactory<AnimationController>(LOGIC_CATEGORY);
 
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
-    MIXED_ACCESSOR_ATTRIBUTE("Animations", GetAnimationsAttr, SetAnimationsAttr, VariantVector, Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
-    ACCESSOR_ATTRIBUTE("Network Animations", GetNetAnimationsAttr, SetNetAnimationsAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
-    MIXED_ACCESSOR_ATTRIBUTE("Node Animation States", GetNodeAnimationStatesAttr, SetNodeAnimationStatesAttr, VariantVector, Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
+    MIXED_ACCESSOR_ATTRIBUTE("Animations", GetAnimationsAttr, SetAnimationsAttr, VariantVector, Variant::emptyVariantVector,
+        AM_FILE | AM_NOEDIT);
+    ACCESSOR_ATTRIBUTE("Network Animations", GetNetAnimationsAttr, SetNetAnimationsAttr, PODVector<unsigned char>,
+        Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
+    MIXED_ACCESSOR_ATTRIBUTE("Node Animation States", GetNodeAnimationStatesAttr, SetNodeAnimationStatesAttr, VariantVector,
+        Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
 }
 
 void AnimationController::OnSetEnabled()
@@ -409,7 +414,7 @@ bool AnimationController::IsFadingOut(const String& name) const
         return false;
 
     return (animations_[index].fadeTime_ && animations_[index].targetWeight_ < state->GetWeight())
-        || (!state->IsLooped() && state->GetTime() >= state->GetLength() && animations_[index].autoFadeTime_);
+           || (!state->IsLooped() && state->GetTime() >= state->GetLength() && animations_[index].autoFadeTime_);
 }
 
 bool AnimationController::IsAtEnd(const String& name) const
@@ -426,7 +431,7 @@ bool AnimationController::IsAtEnd(const String& name) const
 unsigned char AnimationController::GetLayer(const String& name) const
 {
     AnimationState* state = GetAnimationState(name);
-    return state ? state->GetLayer() : 0;
+    return (unsigned char)(state ? state->GetLayer() : 0);
 }
 
 Bone* AnimationController::GetStartBone(const String& name) const

+ 1 - 1
Source/Urho3D/Graphics/AnimationController.h

@@ -22,8 +22,8 @@
 
 #pragma once
 
-#include "../Scene/Component.h"
 #include "../IO/VectorBuffer.h"
+#include "../Scene/Component.h"
 
 namespace Urho3D
 {

+ 43 - 43
Source/Urho3D/Graphics/AnimationState.cpp

@@ -20,13 +20,13 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Graphics/AnimatedModel.h"
 #include "../Graphics/Animation.h"
 #include "../Graphics/AnimationState.h"
-#include "../IO/Deserializer.h"
 #include "../Graphics/DrawableEvents.h"
 #include "../IO/Log.h"
-#include "../IO/Serializer.h"
 
 #include "../DebugNew.h"
 
@@ -74,7 +74,7 @@ AnimationState::AnimationState(Node* node, Animation* animation) :
         {
             const Vector<AnimationTrack>& tracks = animation_->GetTracks();
             stateTracks_.Clear();
-            
+
             for (unsigned i = 0; i < tracks.Size(); ++i)
             {
                 const StringHash& nameHash = tracks[i].nameHash_;
@@ -108,7 +108,7 @@ void AnimationState::SetStartBone(Bone* startBone)
 {
     if (!model_ || !animation_)
         return;
-    
+
     Skeleton& skeleton = model_->GetSkeleton();
     if (!startBone)
     {
@@ -117,28 +117,28 @@ void AnimationState::SetStartBone(Bone* startBone)
             return;
         startBone = rootBone;
     }
-    
+
     // Do not reassign if the start bone did not actually change, and we already have valid bone nodes
     if (startBone == startBone_ && !stateTracks_.Empty())
         return;
-    
+
     startBone_ = startBone;
-    
+
     const Vector<AnimationTrack>& tracks = animation_->GetTracks();
     stateTracks_.Clear();
-    
+
     if (!startBone->node_)
         return;
-    
+
     for (unsigned i = 0; i < tracks.Size(); ++i)
     {
         AnimationStateTrack stateTrack;
         stateTrack.track_ = &tracks[i];
-        
+
         // Include those tracks that are either the start bone itself, or its children
         Bone* trackBone = 0;
         const StringHash& nameHash = tracks[i].nameHash_;
-        
+
         if (nameHash == startBone->nameHash_)
             trackBone = startBone;
         else
@@ -147,7 +147,7 @@ void AnimationState::SetStartBone(Bone* startBone)
             if (trackBoneNode)
                 trackBone = skeleton.GetBone(nameHash);
         }
-        
+
         if (trackBone && trackBone->node_)
         {
             stateTrack.bone_ = trackBone;
@@ -155,7 +155,7 @@ void AnimationState::SetStartBone(Bone* startBone)
             stateTracks_.Push(stateTrack);
         }
     }
-    
+
     model_->MarkAnimationDirty();
 }
 
@@ -182,7 +182,7 @@ void AnimationState::SetTime(float time)
 {
     if (!animation_)
         return;
-    
+
     time = Clamp(time, 0.0f, animation_->GetLength());
     if (time != time_)
     {
@@ -196,16 +196,16 @@ void AnimationState::SetBoneWeight(unsigned index, float weight, bool recursive)
 {
     if (index >= stateTracks_.Size())
         return;
-    
+
     weight = Clamp(weight, 0.0f, 1.0f);
-    
+
     if (weight != stateTracks_[index].weight_)
     {
         stateTracks_[index].weight_ = weight;
         if (model_)
             model_->MarkAnimationDirty();
     }
-    
+
     if (recursive)
     {
         Node* boneNode = stateTracks_[index].node_;
@@ -236,7 +236,7 @@ void AnimationState::AddWeight(float delta)
 {
     if (delta == 0.0f)
         return;
-    
+
     SetWeight(GetWeight() + delta);
 }
 
@@ -244,11 +244,11 @@ void AnimationState::AddTime(float delta)
 {
     if (!animation_ || (!model_ && !node_))
         return;
-    
+
     float length = animation_->GetLength();
     if (delta == 0.0f || length == 0.0f)
         return;
-    
+
     float oldTime = GetTime();
     float time = oldTime + delta;
     if (looped_)
@@ -258,14 +258,14 @@ void AnimationState::AddTime(float delta)
         while (time < 0.0f)
             time += length;
     }
-    
+
     SetTime(time);
-    
+
     // Process animation triggers
     if (animation_->GetNumTriggers())
     {
         bool wrap = false;
-        
+
         if (delta > 0.0f)
         {
             if (oldTime > time)
@@ -284,20 +284,20 @@ void AnimationState::AddTime(float delta)
         }
         if (oldTime > time)
             Swap(oldTime, time);
-        
+
         const Vector<AnimationTriggerPoint>& triggers = animation_->GetTriggers();
         for (Vector<AnimationTriggerPoint>::ConstIterator i = triggers.Begin(); i != triggers.End(); ++i)
         {
             float frameTime = i->time_;
             if (looped_ && wrap)
                 frameTime = fmodf(frameTime, length);
-            
+
             if (oldTime <= frameTime && time > frameTime)
             {
                 using namespace AnimationTrigger;
-                
+
                 Node* senderNode = model_ ? model_->GetNode() : node_;
-                
+
                 VariantMap& eventData = senderNode->GetEventDataMap();
                 eventData[P_NODE] = senderNode;
                 eventData[P_NAME] = animation_->GetAnimationName();
@@ -357,7 +357,7 @@ unsigned AnimationState::GetTrackIndex(const String& name) const
         if (node && node->GetName() == name)
             return i;
     }
-    
+
     return M_MAX_UNSIGNED;
 }
 
@@ -393,7 +393,7 @@ void AnimationState::Apply()
 {
     if (!animation_ || !IsEnabled())
         return;
-    
+
     if (model_)
         ApplyToModel();
     else
@@ -406,11 +406,11 @@ void AnimationState::ApplyToModel()
     {
         AnimationStateTrack& stateTrack = *i;
         float finalWeight = weight_ * stateTrack.weight_;
-        
+
         // Do not apply if zero effective weight or the bone has animation disabled
         if (Equals(finalWeight, 0.0f) || !stateTrack.bone_->animated_)
             continue;
-        
+
         if (Equals(finalWeight, 1.0f))
             ApplyTrackFullWeightSilent(stateTrack);
         else
@@ -429,13 +429,13 @@ void AnimationState::ApplyTrackFullWeight(AnimationStateTrack& stateTrack)
 {
     const AnimationTrack* track = stateTrack.track_;
     Node* node = stateTrack.node_;
-    
+
     if (track->keyFrames_.Empty() || !node)
         return;
-    
+
     unsigned& frame = stateTrack.keyFrame_;
     track->GetKeyFrameIndex(time_, frame);
-    
+
     // Check if next frame to interpolate to is valid, or if wrapping is needed (looping animation only)
     unsigned nextFrame = frame + 1;
     bool interpolate = true;
@@ -449,10 +449,10 @@ void AnimationState::ApplyTrackFullWeight(AnimationStateTrack& stateTrack)
         else
             nextFrame = 0;
     }
-    
+
     const AnimationKeyFrame* keyFrame = &track->keyFrames_[frame];
     unsigned char channelMask = track->channelMask_;
-    
+
     if (!interpolate)
     {
         // No interpolation, full weight
@@ -470,7 +470,7 @@ void AnimationState::ApplyTrackFullWeight(AnimationStateTrack& stateTrack)
         if (timeInterval < 0.0f)
             timeInterval += animation_->GetLength();
         float t = timeInterval > 0.0f ? (time_ - keyFrame->time_) / timeInterval : 1.0f;
-        
+
         // Interpolation, full weight
         if (channelMask & CHANNEL_POSITION)
             node->SetPosition(keyFrame->position_.Lerp(nextKeyFrame->position_, t));
@@ -541,13 +541,13 @@ void AnimationState::ApplyTrackBlendedSilent(AnimationStateTrack& stateTrack, fl
 {
     const AnimationTrack* track = stateTrack.track_;
     Node* node = stateTrack.node_;
-    
+
     if (track->keyFrames_.Empty() || !node)
         return;
-    
+
     unsigned& frame = stateTrack.keyFrame_;
     track->GetKeyFrameIndex(time_, frame);
-    
+
     // Check if next frame to interpolate to is valid, or if wrapping is needed (looping animation only)
     unsigned nextFrame = frame + 1;
     bool interpolate = true;
@@ -561,10 +561,10 @@ void AnimationState::ApplyTrackBlendedSilent(AnimationStateTrack& stateTrack, fl
         else
             nextFrame = 0;
     }
-    
+
     const AnimationKeyFrame* keyFrame = &track->keyFrames_[frame];
     unsigned char channelMask = track->channelMask_;
-    
+
     if (!interpolate)
     {
         // No interpolation, blend between old transform & animation
@@ -582,7 +582,7 @@ void AnimationState::ApplyTrackBlendedSilent(AnimationStateTrack& stateTrack, fl
         if (timeInterval < 0.0f)
             timeInterval += animation_->GetLength();
         float t = timeInterval > 0.0f ? (time_ - keyFrame->time_) / timeInterval : 1.0f;
-        
+
         // Interpolation, blend between old transform & animation
         if (channelMask & CHANNEL_POSITION)
         {

+ 12 - 5
Source/Urho3D/Graphics/AnimationState.h

@@ -43,7 +43,7 @@ struct AnimationStateTrack
     AnimationStateTrack();
     /// Destruct
     ~AnimationStateTrack();
-    
+
     /// Animation track.
     const AnimationTrack* track_;
     /// Bone pointer.
@@ -66,7 +66,7 @@ public:
     AnimationState(Node* node, Animation* animation);
     /// Destruct.
     ~AnimationState();
-    
+
     /// Set start bone. Not supported in node animation mode. Resets any assigned per-bone weights.
     void SetStartBone(Bone* bone);
     /// Set looping enabled/disabled.
@@ -87,9 +87,10 @@ public:
     void AddTime(float delta);
     /// Set blending layer.
     void SetLayer(unsigned char layer);
-    
+
     /// Return animation.
     Animation* GetAnimation() const { return animation_; }
+
     /// Return animated model this state belongs to (model mode.)
     AnimatedModel* GetModel() const;
     /// Return root scene node this state controls (node hierarchy mode.)
@@ -108,22 +109,28 @@ public:
     unsigned GetTrackIndex(const String& name) const;
     /// Return track index by bone name hash, or M_MAX_UNSIGNED if not found.
     unsigned GetTrackIndex(StringHash nameHash) const;
+
     /// Return whether weight is nonzero.
     bool IsEnabled() const { return weight_ > 0.0f; }
+
     /// Return whether looped.
     bool IsLooped() const { return looped_; }
+
     /// Return blending weight.
     float GetWeight() const { return weight_; }
+
     /// Return time position.
     float GetTime() const { return time_; }
+
     /// Return animation length.
     float GetLength() const;
+
     /// Return blending layer.
     unsigned char GetLayer() const { return layer_; }
-    
+
     /// Apply the animation at the current time position.
     void Apply();
-    
+
 private:
     /// Apply animation to a skeleton. Transform changes are applied silently, so the model needs to dirty its root model afterward.
     void ApplyToModel();

+ 174 - 174
Source/Urho3D/Graphics/Batch.cpp

@@ -20,22 +20,20 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
 #include "../Graphics/Camera.h"
 #include "../Graphics/Geometry.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/GraphicsImpl.h"
 #include "../Graphics/Material.h"
-#include "../Scene/Node.h"
 #include "../Graphics/Renderer.h"
-#include "../Core/Profiler.h"
-#include "../Scene/Scene.h"
 #include "../Graphics/ShaderVariation.h"
-#include "../Container/Sort.h"
 #include "../Graphics/Technique.h"
 #include "../Graphics/Texture2D.h"
 #include "../Graphics/VertexBuffer.h"
 #include "../Graphics/View.h"
-#include "../Graphics/Zone.h"
+#include "../Scene/Scene.h"
 
 #include "../DebugNew.h"
 
@@ -75,25 +73,25 @@ void CalculateShadowMatrix(Matrix4& dest, LightBatchQueue* queue, unsigned split
 {
     Camera* shadowCamera = queue->shadowSplits_[split].shadowCamera_;
     const IntRect& viewport = queue->shadowSplits_[split].shadowViewport_;
-    
+
     Matrix3x4 posAdjust(translation, Quaternion::IDENTITY, 1.0f);
     Matrix3x4 shadowView(shadowCamera->GetView());
     Matrix4 shadowProj(shadowCamera->GetProjection());
     Matrix4 texAdjust(Matrix4::IDENTITY);
-    
+
     Texture2D* shadowMap = queue->shadowMap_;
     if (!shadowMap)
         return;
-    
+
     float width = (float)shadowMap->GetWidth();
     float height = (float)shadowMap->GetHeight();
-    
+
     Vector3 offset(
         (float)viewport.left_ / width,
         (float)viewport.top_ / height,
         0.0f
     );
-    
+
     Vector3 scale(
         0.5f * (float)viewport.Width() / width,
         0.5f * (float)viewport.Height() / height,
@@ -105,13 +103,13 @@ void CalculateShadowMatrix(Matrix4& dest, LightBatchQueue* queue, unsigned split
     offset.x_ += scale.x_ + pixelUVOffset.x_ / width;
     offset.y_ += scale.y_ + pixelUVOffset.y_ / height;
 
-    #ifdef URHO3D_OPENGL
+#ifdef URHO3D_OPENGL
     offset.z_ = 0.5f;
     scale.z_ = 0.5f;
     offset.y_ = 1.0f - offset.y_;
-    #else
+#else
     scale.y_ = -scale.y_;
-    #endif
+#endif
 
     // If using 4 shadow samples, offset the position diagonally by half pixel
     if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
@@ -121,7 +119,7 @@ void CalculateShadowMatrix(Matrix4& dest, LightBatchQueue* queue, unsigned split
     }
     texAdjust.SetTranslation(offset);
     texAdjust.SetScale(scale);
-    
+
     dest = texAdjust * shadowProj * shadowView * posAdjust;
 }
 
@@ -132,7 +130,7 @@ void CalculateSpotMatrix(Matrix4& dest, Light* light, const Vector3& translation
     Matrix3x4 spotView = Matrix3x4(lightNode->GetWorldPosition(), lightNode->GetWorldRotation(), 1.0f).Inverse();
     Matrix4 spotProj(Matrix4::ZERO);
     Matrix4 texAdjust(Matrix4::IDENTITY);
-    
+
     // Make the projected light slightly smaller than the shadow map to prevent light spill
     float h = 1.005f / tanf(light->GetFov() * M_DEGTORAD * 0.5f);
     float w = h / light->GetAspectRatio();
@@ -140,39 +138,41 @@ void CalculateSpotMatrix(Matrix4& dest, Light* light, const Vector3& translation
     spotProj.m11_ = h;
     spotProj.m22_ = 1.0f / Max(light->GetRange(), M_EPSILON);
     spotProj.m32_ = 1.0f;
-    
-    #ifdef URHO3D_OPENGL
+
+#ifdef URHO3D_OPENGL
     texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
     texAdjust.SetScale(Vector3(0.5f, -0.5f, 0.5f));
-    #else
+#else
     texAdjust.SetTranslation(Vector3(0.5f, 0.5f, 0.0f));
     texAdjust.SetScale(Vector3(0.5f, -0.5f, 1.0f));
-    #endif
-    
+#endif
+
     dest = texAdjust * spotProj * spotView * posAdjust;
 }
 
 void Batch::CalculateSortKey()
 {
-    unsigned shaderID = ((*((unsigned*)&vertexShader_) / sizeof(ShaderVariation)) + (*((unsigned*)&pixelShader_) / sizeof(ShaderVariation))) & 0x3fff;
+    unsigned shaderID = (unsigned)(
+        ((*((unsigned*)&vertexShader_) / sizeof(ShaderVariation)) + (*((unsigned*)&pixelShader_) / sizeof(ShaderVariation))) &
+        0x3fff);
     if (!isBase_)
         shaderID |= 0x8000;
     if (pass_ && pass_->GetAlphaMask())
         shaderID |= 0x4000;
-    
-    unsigned lightQueueID = (*((unsigned*)&lightQueue_) / sizeof(LightBatchQueue)) & 0xffff;
-    unsigned materialID = (*((unsigned*)&material_) / sizeof(Material)) & 0xffff;
-    unsigned geometryID = (*((unsigned*)&geometry_) / sizeof(Geometry)) & 0xffff;
-    
+
+    unsigned lightQueueID = (unsigned)((*((unsigned*)&lightQueue_) / sizeof(LightBatchQueue)) & 0xffff);
+    unsigned materialID = (unsigned)((*((unsigned*)&material_) / sizeof(Material)) & 0xffff);
+    unsigned geometryID = (unsigned)((*((unsigned*)&geometry_) / sizeof(Geometry)) & 0xffff);
+
     sortKey_ = (((unsigned long long)shaderID) << 48) | (((unsigned long long)lightQueueID) << 32) |
-        (((unsigned long long)materialID) << 16) | geometryID;
+               (((unsigned long long)materialID) << 16) | geometryID;
 }
 
 void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) const
 {
     if (!vertexShader_ || !pixelShader_)
         return;
-    
+
     Graphics* graphics = view->GetGraphics();
     Renderer* renderer = view->GetRenderer();
     Node* cameraNode = camera_ ? camera_->GetNode() : 0;
@@ -209,34 +209,34 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
         graphics->SetDepthTest(pass_->GetDepthTestMode());
         graphics->SetDepthWrite(pass_->GetDepthWrite() && allowDepthWrite);
     }
-    
+
     // Set global (per-frame) shader parameters
     if (graphics->NeedParameterUpdate(SP_FRAME, (void*)0))
         view->SetGlobalShaderParameters();
-    
+
     // Set camera & viewport shader parameters
     unsigned cameraHash = (unsigned)(size_t)camera_;
     IntRect viewport = graphics->GetViewport();
     IntVector2 viewSize = IntVector2(viewport.Width(), viewport.Height());
-    unsigned viewportHash = viewSize.x_ | (viewSize.y_ << 16);
+    unsigned viewportHash = (unsigned)(viewSize.x_ | (viewSize.y_ << 16));
     if (graphics->NeedParameterUpdate(SP_CAMERA, reinterpret_cast<const void*>(cameraHash + viewportHash)))
     {
         view->SetCameraShaderParameters(camera_, true);
         // During renderpath commands the G-Buffer or viewport texture is assumed to always be viewport-sized
         view->SetGBufferShaderParameters(viewSize, IntRect(0, 0, viewSize.x_, viewSize.y_));
     }
-    
+
     // Set model or skinning transforms
     if (setModelTransform && graphics->NeedParameterUpdate(SP_OBJECT, worldTransform_))
     {
         if (geometryType_ == GEOM_SKINNED)
         {
-            graphics->SetShaderParameter(VSP_SKINMATRICES, reinterpret_cast<const float*>(worldTransform_), 
+            graphics->SetShaderParameter(VSP_SKINMATRICES, reinterpret_cast<const float*>(worldTransform_),
                 12 * numWorldTransforms_);
         }
         else
             graphics->SetShaderParameter(VSP_MODEL, *worldTransform_);
-        
+
         // Set the orientation for billboards, either from the object itself or from the camera
         if (geometryType_ == GEOM_BILLBOARD)
         {
@@ -246,7 +246,7 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
                 graphics->SetShaderParameter(VSP_BILLBOARDROT, cameraNode->GetWorldRotation().RotationMatrix());
         }
     }
-    
+
     // Set zone-related shader parameters
     BlendMode blend = graphics->GetBlendMode();
     // If the pass is additive, override fog color to black so that shaders do not need a separate additive path
@@ -257,8 +257,9 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
     if (zone_ && graphics->NeedParameterUpdate(SP_ZONE, reinterpret_cast<const void*>(zoneHash)))
     {
         graphics->SetShaderParameter(VSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor());
-        graphics->SetShaderParameter(VSP_AMBIENTENDCOLOR, zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4());
-        
+        graphics->SetShaderParameter(VSP_AMBIENTENDCOLOR,
+            zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4());
+
         const BoundingBox& box = zone_->GetBoundingBox();
         Vector3 boxSize = box.Size();
         Matrix3x4 adjust(Matrix3x4::IDENTITY);
@@ -266,10 +267,10 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
         adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
         Matrix3x4 zoneTransform = adjust * zone_->GetInverseWorldTransform();
         graphics->SetShaderParameter(VSP_ZONE, zoneTransform);
-        
+
         graphics->SetShaderParameter(PSP_AMBIENTCOLOR, zone_->GetAmbientColor());
         graphics->SetShaderParameter(PSP_FOGCOLOR, overrideFogColorToBlack ? Color::BLACK : zone_->GetFogColor());
-        
+
         float farClip = camera_->GetFarClip();
         float fogStart = Min(zone_->GetFogStart(), farClip);
         float fogEnd = Min(zone_->GetFogEnd(), farClip);
@@ -277,7 +278,7 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
         float fogRange = Max(fogEnd - fogStart, M_EPSILON);
         Vector4 fogParams(fogEnd / farClip, farClip / fogRange, 0.0f, 0.0f);
-        
+
         Node* zoneNode = zone_->GetNode();
         if (zone_->GetHeightFog() && zoneNode)
         {
@@ -285,10 +286,10 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             fogParams.z_ = worldFogHeightVec.y_;
             fogParams.w_ = zone_->GetFogHeightScale() / Max(zoneNode->GetWorldScale().y_, M_EPSILON);
         }
-        
+
         graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
     }
-    
+
     // Set light-related shader parameters
     if (lightQueue_)
     {
@@ -313,42 +314,42 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
                 switch (light->GetLightType())
                 {
                 case LIGHT_DIRECTIONAL:
-                {
-                    Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
-                    unsigned numSplits = Min(MAX_CASCADE_SPLITS, (int)lightQueue_->shadowSplits_.Size());
+                    {
+                        Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
+                        unsigned numSplits = (unsigned)Min(MAX_CASCADE_SPLITS, (int)lightQueue_->shadowSplits_.Size());
 
-                    for (unsigned i = 0; i < numSplits; ++i)
-                        CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO);
+                        for (unsigned i = 0; i < numSplits; ++i)
+                            CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO);
 
-                    graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
-                }
-                break;
+                        graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
+                    }
+                    break;
 
                 case LIGHT_SPOT:
-                {
-                    Matrix4 shadowMatrices[2];
+                    {
+                        Matrix4 shadowMatrices[2];
 
-                    CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO);
-                    bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP);
-                    if (isShadowed)
-                        CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO);
+                        CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO);
+                        bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP);
+                        if (isShadowed)
+                            CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO);
 
-                    graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
-                }
-                break;
+                        graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
+                    }
+                    break;
 
                 case LIGHT_POINT:
-                {
-                    Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
-                    // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
-                    // the next parameter
-                    #ifdef URHO3D_OPENGL
-                    graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16);
-                    #else
-                    graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12);
-                    #endif
-                }
-                break;
+                    {
+                        Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
+                        // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
+                        // the next parameter
+#ifdef URHO3D_OPENGL
+                        graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16);
+#else
+                        graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12);
+#endif
+                    }
+                    break;
                 }
             }
 
@@ -364,55 +365,56 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             graphics->SetShaderParameter(PSP_LIGHTCOLOR, Color(light->GetEffectiveColor().Abs(),
                 light->GetEffectiveSpecularIntensity()) * fade);
             graphics->SetShaderParameter(PSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
-            graphics->SetShaderParameter(PSP_LIGHTPOS, Vector4((isLightVolume ? (lightNode->GetWorldPosition() -
-                cameraEffectivePos) : lightNode->GetWorldPosition()), atten));
+            graphics->SetShaderParameter(PSP_LIGHTPOS,
+                Vector4((isLightVolume ? (lightNode->GetWorldPosition() - cameraEffectivePos) : lightNode->GetWorldPosition()),
+                    atten));
 
             if (graphics->HasShaderParameter(PSP_LIGHTMATRICES))
             {
                 switch (light->GetLightType())
                 {
                 case LIGHT_DIRECTIONAL:
-                {
-                    Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
-                    unsigned numSplits = Min(MAX_CASCADE_SPLITS, (int)lightQueue_->shadowSplits_.Size());
-
-                    for (unsigned i = 0; i < numSplits; ++i)
                     {
-                        CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, isLightVolume ? cameraEffectivePos :
-                            Vector3::ZERO);
+                        Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
+                        unsigned numSplits = (unsigned)Min(MAX_CASCADE_SPLITS, (int)lightQueue_->shadowSplits_.Size());
+
+                        for (unsigned i = 0; i < numSplits; ++i)
+                        {
+                            CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, isLightVolume ? cameraEffectivePos :
+                                Vector3::ZERO);
+                        }
+                        graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
                     }
-                    graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
-                }
-                break;
+                    break;
 
                 case LIGHT_SPOT:
-                {
-                    Matrix4 shadowMatrices[2];
-
-                    CalculateSpotMatrix(shadowMatrices[0], light, cameraEffectivePos);
-                    bool isShadowed = lightQueue_->shadowMap_ != 0;
-                    if (isShadowed)
                     {
-                        CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, isLightVolume ? cameraEffectivePos :
-                            Vector3::ZERO);
-                    }
+                        Matrix4 shadowMatrices[2];
 
-                    graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
-                }
-                break;
+                        CalculateSpotMatrix(shadowMatrices[0], light, cameraEffectivePos);
+                        bool isShadowed = lightQueue_->shadowMap_ != 0;
+                        if (isShadowed)
+                        {
+                            CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, isLightVolume ? cameraEffectivePos :
+                                Vector3::ZERO);
+                        }
+
+                        graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
+                    }
+                    break;
 
                 case LIGHT_POINT:
-                {
-                    Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
-                    // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
-                    // the next parameter
-                    #ifdef URHO3D_OPENGL
-                    graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16);
-                    #else
-                    graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12);
-                    #endif
-                }
-                break;
+                    {
+                        Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
+                        // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
+                        // the next parameter
+#ifdef URHO3D_OPENGL
+                        graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16);
+#else
+                        graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12);
+#endif
+                    }
+                    break;
                 }
             }
 
@@ -421,21 +423,21 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             {
                 {
                     // Calculate point light shadow sampling offsets (unrolled cube map)
-                    unsigned faceWidth = shadowMap->GetWidth() / 2;
-                    unsigned faceHeight = shadowMap->GetHeight() / 3;
+                    unsigned faceWidth = (unsigned)(shadowMap->GetWidth() / 2);
+                    unsigned faceHeight = (unsigned)(shadowMap->GetHeight() / 3);
                     float width = (float)shadowMap->GetWidth();
                     float height = (float)shadowMap->GetHeight();
-                    #ifdef URHO3D_OPENGL
+#ifdef URHO3D_OPENGL
                     float mulX = (float)(faceWidth - 3) / width;
                     float mulY = (float)(faceHeight - 3) / height;
                     float addX = 1.5f / width;
                     float addY = 1.5f / height;
-                    #else
+#else
                     float mulX = (float)(faceWidth - 4) / width;
                     float mulY = (float)(faceHeight - 4) / height;
                     float addX = 2.5f / width;
                     float addY = 2.5f / height;
-                    #endif
+#endif
                     // If using 4 shadow samples, offset the position diagonally by half pixel
                     if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
                     {
@@ -469,7 +471,8 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
                     float fadeStart = light->GetShadowFadeDistance();
                     float fadeEnd = light->GetShadowDistance();
                     if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
-                        intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
+                        intensity =
+                            Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
                     float pcfValues = (1.0f - intensity);
                     float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f;
 
@@ -492,17 +495,17 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             }
         }
         else if (lightQueue_->vertexLights_.Size() && graphics->HasShaderParameter(VSP_VERTEXLIGHTS) &&
-            graphics->NeedParameterUpdate(SP_LIGHT, lightQueue_))
+                 graphics->NeedParameterUpdate(SP_LIGHT, lightQueue_))
         {
             Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3];
             const PODVector<Light*>& lights = lightQueue_->vertexLights_;
-            
+
             for (unsigned i = 0; i < lights.Size(); ++i)
             {
                 Light* vertexLight = lights[i];
                 Node* vertexLightNode = vertexLight->GetNode();
                 LightType type = vertexLight->GetLightType();
-                
+
                 // Attenuation
                 float invRange, cutoff, invCutoff;
                 if (type == LIGHT_DIRECTIONAL)
@@ -519,26 +522,26 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
                     cutoff = -1.0f;
                     invCutoff = 1.0f;
                 }
-                
+
                 // Color
                 float fade = 1.0f;
                 float fadeEnd = vertexLight->GetDrawDistance();
                 float fadeStart = vertexLight->GetFadeDistance();
-                
+
                 // Do fade calculation for light if both fade & draw distance defined
                 if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
                     fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
-                
+
                 Color color = vertexLight->GetEffectiveColor() * fade;
                 vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange);
-                
+
                 // Direction
                 vertexLights[i * 3 + 1] = Vector4(-(vertexLightNode->GetWorldDirection()), cutoff);
-                
+
                 // Position
                 vertexLights[i * 3 + 2] = Vector4(vertexLightNode->GetWorldPosition(), invCutoff);
             }
-            
+
             graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].Data(), lights.Size() * 3 * 4);
         }
     }
@@ -552,7 +555,7 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
                 graphics->SetShaderParameter(i->first_, i->second_.value_);
         }
-        
+
         const HashMap<TextureUnit, SharedPtr<Texture> >& textures = material_->GetTextures();
         for (HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures.Begin(); i != textures.End(); ++i)
         {
@@ -560,7 +563,7 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
                 graphics->SetTexture(i->first_, i->second_.Get());
         }
     }
-    
+
     // Set light-related textures
     if (light)
     {
@@ -581,12 +584,12 @@ void Batch::Prepare(View* view, bool setModelTransform, bool allowDepthWrite) co
             graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
         }
     }
-    
+
     // Set zone texture if necessary
-    #ifdef DESKTOP_GRAPHICS
+#ifdef DESKTOP_GRAPHICS
     if (zone_ && graphics->HasTextureUnit(TU_ZONE))
         graphics->SetTexture(TU_ZONE, zone_->GetZoneTexture());
-    #endif
+#endif
 }
 
 void Batch::Draw(View* view, bool allowDepthWrite) const
@@ -603,14 +606,14 @@ void BatchGroup::SetTransforms(void* lockedData, unsigned& freeIndex)
     // Do not use up buffer space if not going to draw as instanced
     if (geometryType_ != GEOM_INSTANCED)
         return;
-    
+
     startIndex_ = freeIndex;
     Matrix3x4* dest = (Matrix3x4*)lockedData;
     dest += freeIndex;
-    
+
     for (unsigned i = 0; i < instances_.Size(); ++i)
         *dest++ = *instances_[i].worldTransform_;
-    
+
     freeIndex += instances_.Size();
 }
 
@@ -618,7 +621,7 @@ void BatchGroup::Draw(View* view, bool allowDepthWrite) const
 {
     Graphics* graphics = view->GetGraphics();
     Renderer* renderer = view->GetRenderer();
-    
+
     if (instances_.Size() && !geometry_->IsEmpty())
     {
         // Draw as individual objects if instancing not supported or could not fill the instancing buffer
@@ -626,15 +629,15 @@ void BatchGroup::Draw(View* view, bool allowDepthWrite) const
         if (!instanceBuffer || geometryType_ != GEOM_INSTANCED || startIndex_ == M_MAX_UNSIGNED)
         {
             Batch::Prepare(view, false, allowDepthWrite);
-            
+
             graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
             graphics->SetVertexBuffers(geometry_->GetVertexBuffers(), geometry_->GetVertexElementMasks());
-            
+
             for (unsigned i = 0; i < instances_.Size(); ++i)
             {
                 if (graphics->NeedParameterUpdate(SP_OBJECT, instances_[i].worldTransform_))
                     graphics->SetShaderParameter(VSP_MODEL, *instances_[i].worldTransform_);
-                
+
                 graphics->Draw(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
                     geometry_->GetVertexStart(), geometry_->GetVertexCount());
             }
@@ -642,20 +645,20 @@ void BatchGroup::Draw(View* view, bool allowDepthWrite) const
         else
         {
             Batch::Prepare(view, false, allowDepthWrite);
-            
+
             // Get the geometry vertex buffers, then add the instancing stream buffer
             // Hack: use a const_cast to avoid dynamic allocation of new temp vectors
-            Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>
-                (geometry_->GetVertexBuffers());
+            Vector<SharedPtr<VertexBuffer> >& vertexBuffers = const_cast<Vector<SharedPtr<VertexBuffer> >&>(
+                geometry_->GetVertexBuffers());
             PODVector<unsigned>& elementMasks = const_cast<PODVector<unsigned>&>(geometry_->GetVertexElementMasks());
             vertexBuffers.Push(SharedPtr<VertexBuffer>(instanceBuffer));
             elementMasks.Push(instanceBuffer->GetElementMask());
-            
+
             graphics->SetIndexBuffer(geometry_->GetIndexBuffer());
             graphics->SetVertexBuffers(vertexBuffers, elementMasks, startIndex_);
             graphics->DrawInstanced(geometry_->GetPrimitiveType(), geometry_->GetIndexStart(), geometry_->GetIndexCount(),
                 geometry_->GetVertexStart(), geometry_->GetVertexCount(), instances_.Size());
-            
+
             // Remove the instancing buffer & element mask now
             vertexBuffers.Pop();
             elementMasks.Pop();
@@ -665,11 +668,8 @@ void BatchGroup::Draw(View* view, bool allowDepthWrite) const
 
 unsigned BatchGroupKey::ToHash() const
 {
-    return ((unsigned)(size_t)zone_) / sizeof(Zone) +
-        ((unsigned)(size_t)lightQueue_) / sizeof(LightBatchQueue) +
-        ((unsigned)(size_t)pass_) / sizeof(Pass) +
-        ((unsigned)(size_t)material_) / sizeof(Material) +
-        ((unsigned)(size_t)geometry_) / sizeof(Geometry);
+    return (unsigned)((size_t)zone_ / sizeof(Zone) + (size_t)lightQueue_ / sizeof(LightBatchQueue) + (size_t)pass_ / sizeof(Pass) +
+                      (size_t)material_ / sizeof(Material) + (size_t)geometry_ / sizeof(Geometry));
 }
 
 void BatchQueue::Clear(int maxSortedInstances)
@@ -677,21 +677,21 @@ void BatchQueue::Clear(int maxSortedInstances)
     batches_.Clear();
     sortedBatches_.Clear();
     batchGroups_.Clear();
-    maxSortedInstances_ = maxSortedInstances;
+    maxSortedInstances_ = (unsigned)maxSortedInstances;
 }
 
 void BatchQueue::SortBackToFront()
 {
     sortedBatches_.Resize(batches_.Size());
-    
+
     for (unsigned i = 0; i < batches_.Size(); ++i)
         sortedBatches_[i] = &batches_[i];
-    
+
     Sort(sortedBatches_.Begin(), sortedBatches_.End(), CompareBatchesBackToFront);
-    
+
     // Do not actually sort batch groups, just list them
     sortedBatchGroups_.Resize(batchGroups_.Size());
-    
+
     unsigned index = 0;
     for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
         sortedBatchGroups_[index++] = &i->second_;
@@ -700,12 +700,12 @@ void BatchQueue::SortBackToFront()
 void BatchQueue::SortFrontToBack()
 {
     sortedBatches_.Clear();
-    
+
     for (unsigned i = 0; i < batches_.Size(); ++i)
         sortedBatches_.Push(&batches_[i]);
-    
+
     SortFrontToBack2Pass(sortedBatches_);
-    
+
     // Sort each group front to back
     for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
     {
@@ -723,13 +723,13 @@ void BatchQueue::SortFrontToBack()
             i->second_.distance_ = minDistance;
         }
     }
-    
+
     sortedBatchGroups_.Resize(batchGroups_.Size());
-    
+
     unsigned index = 0;
     for (HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
         sortedBatchGroups_[index++] = &i->second_;
-    
+
     SortFrontToBack2Pass(reinterpret_cast<PODVector<Batch*>& >(sortedBatchGroups_));
 }
 
@@ -737,21 +737,21 @@ void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches)
 {
     // Mobile devices likely use a tiled deferred approach, with which front-to-back sorting is irrelevant. The 2-pass
     // method is also time consuming, so just sort with state having priority
-    #ifdef GL_ES_VERSION_2_0
+#ifdef GL_ES_VERSION_2_0
     Sort(batches.Begin(), batches.End(), CompareBatchesState);
-    #else
+#else
     // For desktop, first sort by distance and remap shader/material/geometry IDs in the sort key
     Sort(batches.Begin(), batches.End(), CompareBatchesFrontToBack);
-    
+
     unsigned freeShaderID = 0;
     unsigned short freeMaterialID = 0;
     unsigned short freeGeometryID = 0;
-    
+
     for (PODVector<Batch*>::Iterator i = batches.Begin(); i != batches.End(); ++i)
     {
         Batch* batch = *i;
-        
-        unsigned shaderID = (batch->sortKey_ >> 32);
+
+        unsigned shaderID = (unsigned)(batch->sortKey_ >> 32);
         HashMap<unsigned, unsigned>::ConstIterator j = shaderRemapping_.Find(shaderID);
         if (j != shaderRemapping_.End())
             shaderID = j->second_;
@@ -760,7 +760,7 @@ void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches)
             shaderID = shaderRemapping_[shaderID] = freeShaderID | (shaderID & 0xc0000000);
             ++freeShaderID;
         }
-        
+
         unsigned short materialID = (unsigned short)(batch->sortKey_ & 0xffff0000);
         HashMap<unsigned short, unsigned short>::ConstIterator k = materialRemapping_.Find(materialID);
         if (k != materialRemapping_.End())
@@ -770,7 +770,7 @@ void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches)
             materialID = materialRemapping_[materialID] = freeMaterialID;
             ++freeMaterialID;
         }
-        
+
         unsigned short geometryID = (unsigned short)(batch->sortKey_ & 0xffff);
         HashMap<unsigned short, unsigned short>::ConstIterator l = geometryRemapping_.Find(geometryID);
         if (l != geometryRemapping_.End())
@@ -780,17 +780,17 @@ void BatchQueue::SortFrontToBack2Pass(PODVector<Batch*>& batches)
             geometryID = geometryRemapping_[geometryID] = freeGeometryID;
             ++freeGeometryID;
         }
-        
-        batch->sortKey_ = (((unsigned long long)shaderID) << 32) || (((unsigned long long)materialID) << 16) | geometryID;
+
+        batch->sortKey_ = (((unsigned long long)shaderID) << 32) | (((unsigned long long)materialID) << 16) | geometryID;
     }
-    
+
     shaderRemapping_.Clear();
     materialRemapping_.Clear();
     geometryRemapping_.Clear();
-    
+
     // Finally sort again with the rewritten ID's
     Sort(batches.Begin(), batches.End(), CompareBatchesState);
-    #endif
+#endif
 }
 
 void BatchQueue::SetTransforms(void* lockedData, unsigned& freeIndex)
@@ -803,24 +803,24 @@ void BatchQueue::Draw(View* view, bool markToStencil, bool usingLightOptimizatio
 {
     Graphics* graphics = view->GetGraphics();
     Renderer* renderer = view->GetRenderer();
-    
+
     // If View has set up its own light optimizations, do not disturb the stencil/scissor test settings
     if (!usingLightOptimization)
     {
         graphics->SetScissorTest(false);
-        
+
         // During G-buffer rendering, mark opaque pixels' lightmask to stencil buffer if requested
         if (!markToStencil)
             graphics->SetStencilTest(false);
     }
-    
+
     // Instanced
     for (PODVector<BatchGroup*>::ConstIterator i = sortedBatchGroups_.Begin(); i != sortedBatchGroups_.End(); ++i)
     {
         BatchGroup* group = *i;
         if (markToStencil)
             graphics->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, group->lightMask_);
-        
+
         group->Draw(view, allowDepthWrite);
     }
     // Non-instanced
@@ -837,7 +837,7 @@ void BatchQueue::Draw(View* view, bool markToStencil, bool usingLightOptimizatio
             else
                 graphics->SetScissorTest(false);
         }
-        
+
         batch->Draw(view, allowDepthWrite);
     }
 }
@@ -845,13 +845,13 @@ void BatchQueue::Draw(View* view, bool markToStencil, bool usingLightOptimizatio
 unsigned BatchQueue::GetNumInstances() const
 {
     unsigned total = 0;
-    
+
     for (HashMap<BatchGroupKey, BatchGroup>::ConstIterator i = batchGroups_.Begin(); i != batchGroups_.End(); ++i)
     {
-       if (i->second_.geometryType_ == GEOM_INSTANCED)
+        if (i->second_.geometryType_ == GEOM_INSTANCED)
             total += i->second_.instances_.Size();
     }
-    
+
     return total;
 }
 

+ 29 - 19
Source/Urho3D/Graphics/Batch.h

@@ -22,10 +22,10 @@
 
 #pragma once
 
+#include "../Container/Ptr.h"
 #include "../Graphics/Drawable.h"
 #include "../Math/MathDefs.h"
 #include "../Math/Matrix3x4.h"
-#include "../Container/Ptr.h"
 #include "../Math/Rect.h"
 
 namespace Urho3D
@@ -54,7 +54,7 @@ struct Batch
         isBase_(false)
     {
     }
-    
+
     /// Construct from a drawable's source batch.
     Batch(const SourceBatch& rhs) :
         distance_(rhs.distance_),
@@ -67,14 +67,14 @@ struct Batch
         isBase_(false)
     {
     }
-    
+
     /// Calculate state sorting key, which consists of base pass flag, light, pass and geometry.
     void CalculateSortKey();
     /// Prepare for rendering.
     void Prepare(View* view, bool setModelTransform, bool allowDepthWrite) const;
     /// Prepare and draw.
     void Draw(View* view, bool allowDepthWrite) const;
-    
+
     /// State sorting key.
     unsigned long long sortKey_;
     /// Distance from camera.
@@ -114,14 +114,14 @@ struct InstanceData
     InstanceData()
     {
     }
-    
+
     /// Construct with transform and distance.
     InstanceData(const Matrix3x4* worldTransform, float distance) :
         worldTransform_(worldTransform),
         distance_(distance)
     {
     }
-    
+
     /// World transform.
     const Matrix3x4* worldTransform_;
     /// Distance from camera.
@@ -136,7 +136,7 @@ struct BatchGroup : public Batch
         startIndex_(M_MAX_UNSIGNED)
     {
     }
-    
+
     /// Construct from a batch.
     BatchGroup(const Batch& batch) :
         Batch(batch),
@@ -148,25 +148,25 @@ struct BatchGroup : public Batch
     ~BatchGroup()
     {
     }
-    
+
     /// Add world transform(s) from a batch.
     void AddTransforms(const Batch& batch)
     {
         InstanceData newInstance;
         newInstance.distance_ = batch.distance_;
-        
+
         for (unsigned i = 0; i < batch.numWorldTransforms_; ++i)
         {
             newInstance.worldTransform_ = &batch.worldTransform_[i];
             instances_.Push(newInstance);
         }
     }
-    
+
     /// Pre-set the instance transforms. Buffer must be big enough to hold all transforms.
     void SetTransforms(void* lockedData, unsigned& freeIndex);
     /// Prepare and draw.
     void Draw(View* view, bool allowDepthWrite) const;
-    
+
     /// Instance data.
     PODVector<InstanceData> instances_;
     /// Instance stream start index, or M_MAX_UNSIGNED if transforms not pre-set.
@@ -180,7 +180,7 @@ struct BatchGroupKey
     BatchGroupKey()
     {
     }
-    
+
     /// Construct from a batch.
     BatchGroupKey(const Batch& batch) :
         zone_(batch.zone_),
@@ -190,7 +190,7 @@ struct BatchGroupKey
         geometry_(batch.geometry_)
     {
     }
-    
+
     /// Zone.
     Zone* zone_;
     /// Light properties.
@@ -201,12 +201,21 @@ struct BatchGroupKey
     Material* material_;
     /// Geometry.
     Geometry* geometry_;
-    
+
     /// Test for equality with another batch group key.
-    bool operator == (const BatchGroupKey& rhs) const { return zone_ == rhs.zone_ && lightQueue_ == rhs.lightQueue_ && pass_ == rhs.pass_ && material_ == rhs.material_ && geometry_ == rhs.geometry_; }
+    bool operator ==(const BatchGroupKey& rhs) const
+    {
+        return zone_ == rhs.zone_ && lightQueue_ == rhs.lightQueue_ && pass_ == rhs.pass_ && material_ == rhs.material_ &&
+               geometry_ == rhs.geometry_;
+    }
+
     /// Test for inequality with another batch group key.
-    bool operator != (const BatchGroupKey& rhs) const { return zone_ != rhs.zone_ || lightQueue_ != rhs.lightQueue_ || pass_ != rhs.pass_ || material_ != rhs.material_ || geometry_ != rhs.geometry_; }
-    
+    bool operator !=(const BatchGroupKey& rhs) const
+    {
+        return zone_ != rhs.zone_ || lightQueue_ != rhs.lightQueue_ || pass_ != rhs.pass_ || material_ != rhs.material_ ||
+               geometry_ != rhs.geometry_;
+    }
+
     /// Return hash value.
     unsigned ToHash() const;
 };
@@ -229,9 +238,10 @@ public:
     void Draw(View* view, bool markToStencil, bool usingLightOptimization, bool allowDepthWrite) const;
     /// Return the combined amount of instances.
     unsigned GetNumInstances() const;
+
     /// Return whether the batch group is empty.
     bool IsEmpty() const { return batches_.Empty() && batchGroups_.Empty(); }
-    
+
     /// Instanced draw calls.
     HashMap<BatchGroupKey, BatchGroup> batchGroups_;
     /// Shader remapping table for 2-pass state and distance sort.
@@ -240,7 +250,7 @@ public:
     HashMap<unsigned short, unsigned short> materialRemapping_;
     /// Geometry remapping table for 2-pass state and distance sort.
     HashMap<unsigned short, unsigned short> geometryRemapping_;
-    
+
     /// Unsorted non-instanced draw calls.
     PODVector<Batch> batches_;
     /// Sorted non-instanced draw calls.

+ 43 - 23
Source/Urho3D/Graphics/BillboardSet.cpp

@@ -20,21 +20,22 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
+#include "../Core/Context.h"
+#include "../Core/Profiler.h"
 #include "../Graphics/Batch.h"
 #include "../Graphics/BillboardSet.h"
 #include "../Graphics/Camera.h"
-#include "../Core/Context.h"
 #include "../Graphics/Geometry.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/IndexBuffer.h"
 #include "../Graphics/Material.h"
-#include "../IO/MemoryBuffer.h"
-#include "../Scene/Node.h"
 #include "../Graphics/OctreeQuery.h"
-#include "../Core/Profiler.h"
-#include "../Resource/ResourceCache.h"
-#include "../Container/Sort.h"
 #include "../Graphics/VertexBuffer.h"
+#include "../IO/MemoryBuffer.h"
+#include "../Resource/ResourceCache.h"
+#include "../Scene/Node.h"
 
 #include "../DebugNew.h"
 
@@ -96,7 +97,8 @@ void BillboardSet::RegisterObject(Context* context)
     context->RegisterFactory<BillboardSet>(GEOMETRY_CATEGORY);
 
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
-    MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT);
+    MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()),
+        AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Relative Position", IsRelative, SetRelative, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Relative Scale", IsScaled, SetScaled, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Sort By Distance", IsSorted, SetSorted, bool, false, AM_DEFAULT);
@@ -107,8 +109,10 @@ void BillboardSet::RegisterObject(Context* context)
     ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
     COPY_BASE_ATTRIBUTES(Drawable);
-    MIXED_ACCESSOR_ATTRIBUTE("Billboards", GetBillboardsAttr, SetBillboardsAttr, VariantVector, Variant::emptyVariantVector, AM_FILE);
-    ACCESSOR_ATTRIBUTE("Network Billboards", GetNetBillboardsAttr, SetNetBillboardsAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_NOEDIT);
+    MIXED_ACCESSOR_ATTRIBUTE("Billboards", GetBillboardsAttr, SetBillboardsAttr, VariantVector, Variant::emptyVariantVector,
+        AM_FILE);
+    ACCESSOR_ATTRIBUTE("Network Billboards", GetNetBillboardsAttr, SetNetBillboardsAttr, PODVector<unsigned char>,
+        Variant::emptyBuffer, AM_NET | AM_NOEDIT);
 }
 
 void BillboardSet::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
@@ -162,13 +166,13 @@ void BillboardSet::UpdateBatches(const FrameInfo& frame)
         sortThisFrame_ = false;
         sortFrameNumber_ = frame.frameNumber_;
     }
-    
+
     Vector3 worldPos = node_->GetWorldPosition();
     Vector3 offset = (worldPos - frame.camera_->GetNode()->GetWorldPosition());
     // Sort if position relative to camera has changed
     if (offset != previousOffset_ & sorted_)
         sortThisFrame_ = true;
-    
+
     distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center());
 
     // Calculate scaled distance for animation LOD
@@ -195,7 +199,7 @@ void BillboardSet::UpdateGeometry(const FrameInfo& frame)
 
     if (bufferDirty_ || sortThisFrame_ || vertexBuffer_->IsDataLost())
         UpdateVertexBuffer(frame);
-    
+
     // If using camera facing, re-update the rotation for the current view now
     if (faceCameraMode_ != FC_NONE)
     {
@@ -432,8 +436,12 @@ void BillboardSet::UpdateBufferSize()
     unsigned vertexIndex = 0;
     while (numBillboards--)
     {
-        dest[0] = vertexIndex; dest[1] = vertexIndex + 1; dest[2] = vertexIndex + 2;
-        dest[3] = vertexIndex + 2; dest[4] = vertexIndex + 3; dest[5] = vertexIndex;
+        dest[0] = (unsigned short)vertexIndex;
+        dest[1] = (unsigned short)(vertexIndex + 1);
+        dest[2] = (unsigned short)(vertexIndex + 2);
+        dest[3] = (unsigned short)(vertexIndex + 2);
+        dest[4] = (unsigned short)(vertexIndex + 3);
+        dest[5] = (unsigned short)vertexIndex;
 
         dest += 6;
         vertexIndex += 4;
@@ -501,7 +509,7 @@ void BillboardSet::UpdateVertexBuffer(const FrameInfo& frame)
         // Store the "last sorted position" now
         previousOffset_ = (worldPos - frame.camera_->GetNode()->GetWorldPosition());
     }
-    
+
     float* dest = (float*)vertexBuffer_->Lock(0, enabledBillboards * 4, true);
     if (!dest)
         return;
@@ -519,27 +527,39 @@ void BillboardSet::UpdateVertexBuffer(const FrameInfo& frame)
         rotationMatrix[1][0] = -rotationMatrix[0][1];
         rotationMatrix[1][1] = rotationMatrix[0][0];
 
-        dest[0] = billboard.position_.x_; dest[1] = billboard.position_.y_; dest[2] = billboard.position_.z_;
+        dest[0] = billboard.position_.x_;
+        dest[1] = billboard.position_.y_;
+        dest[2] = billboard.position_.z_;
         ((unsigned&)dest[3]) = color;
-        dest[4] = billboard.uv_.min_.x_; dest[5] = billboard.uv_.min_.y_;
+        dest[4] = billboard.uv_.min_.x_;
+        dest[5] = billboard.uv_.min_.y_;
         dest[6] = -size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
         dest[7] = -size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
 
-        dest[8] = billboard.position_.x_; dest[9] = billboard.position_.y_; dest[10] = billboard.position_.z_;
+        dest[8] = billboard.position_.x_;
+        dest[9] = billboard.position_.y_;
+        dest[10] = billboard.position_.z_;
         ((unsigned&)dest[11]) = color;
-        dest[12] = billboard.uv_.max_.x_; dest[13] = billboard.uv_.min_.y_;
+        dest[12] = billboard.uv_.max_.x_;
+        dest[13] = billboard.uv_.min_.y_;
         dest[14] = size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
         dest[15] = size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
 
-        dest[16] = billboard.position_.x_; dest[17] = billboard.position_.y_; dest[18] = billboard.position_.z_;
+        dest[16] = billboard.position_.x_;
+        dest[17] = billboard.position_.y_;
+        dest[18] = billboard.position_.z_;
         ((unsigned&)dest[19]) = color;
-        dest[20] = billboard.uv_.max_.x_; dest[21] = billboard.uv_.max_.y_;
+        dest[20] = billboard.uv_.max_.x_;
+        dest[21] = billboard.uv_.max_.y_;
         dest[22] = size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
         dest[23] = size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
 
-        dest[24] = billboard.position_.x_; dest[25] = billboard.position_.y_; dest[26] = billboard.position_.z_;
+        dest[24] = billboard.position_.x_;
+        dest[25] = billboard.position_.y_;
+        dest[26] = billboard.position_.z_;
         ((unsigned&)dest[27]) = color;
-        dest[28] = billboard.uv_.min_.x_; dest[29] = billboard.uv_.max_.y_;
+        dest[28] = billboard.uv_.min_.x_;
+        dest[29] = billboard.uv_.max_.y_;
         dest[30] = -size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
         dest[31] = -size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
 

+ 10 - 2
Source/Urho3D/Graphics/BillboardSet.h

@@ -22,11 +22,11 @@
 
 #pragma once
 
-#include "../Math/Color.h"
 #include "../Graphics/Drawable.h"
+#include "../IO/VectorBuffer.h"
+#include "../Math/Color.h"
 #include "../Math/Matrix3x4.h"
 #include "../Math/Rect.h"
-#include "../IO/VectorBuffer.h"
 
 namespace Urho3D
 {
@@ -96,20 +96,28 @@ public:
 
     /// Return material.
     Material* GetMaterial() const;
+
     /// Return number of billboards.
     unsigned GetNumBillboards() const { return billboards_.Size(); }
+
     /// Return all billboards.
     PODVector<Billboard>& GetBillboards() { return billboards_; }
+
     /// Return billboard by index.
     Billboard* GetBillboard(unsigned index);
+
     /// Return whether billboards are relative to the scene node.
     bool IsRelative() const { return relative_; }
+
     /// Return whether scene node scale affects billboards' size.
     bool IsScaled() const { return scaled_; }
+
     /// Return whether billboards are sorted.
     bool IsSorted() const { return sorted_; }
+
     /// Return how the billboards rotate in relation to the camera.
     FaceCameraMode GetFaceCameraMode() const { return faceCameraMode_; }
+
     /// Return animation LOD bias.
     float GetAnimationLodBias() const { return animationLodBias_; }
 

+ 11 - 7
Source/Urho3D/Graphics/Camera.cpp

@@ -20,8 +20,10 @@
 // THE SOFTWARE.
 //
 
-#include "../Graphics/Camera.h"
+#include "../Precompiled.h"
+
 #include "../Core/Context.h"
+#include "../Graphics/Camera.h"
 #include "../Graphics/DebugRenderer.h"
 #include "../Graphics/Drawable.h"
 #include "../Scene/Node.h"
@@ -97,8 +99,10 @@ void Camera::RegisterObject(Context* context)
     ATTRIBUTE("View Mask", int, viewMask_, DEFAULT_VIEWMASK, AM_DEFAULT);
     ATTRIBUTE("View Override Flags", int, viewOverrideFlags_, VO_NONE, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Projection Offset", GetProjectionOffset, SetProjectionOffset, Vector2, Vector2::ZERO, AM_DEFAULT);
-    MIXED_ACCESSOR_ATTRIBUTE("Reflection Plane", GetReflectionPlaneAttr, SetReflectionPlaneAttr, Vector4, Vector4(0.0f, 1.0f, 0.0f, 0.0f), AM_DEFAULT);
-    MIXED_ACCESSOR_ATTRIBUTE("Clip Plane", GetClipPlaneAttr, SetClipPlaneAttr, Vector4, Vector4(0.0f, 1.0f, 0.0f, 0.0f), AM_DEFAULT);
+    MIXED_ACCESSOR_ATTRIBUTE("Reflection Plane", GetReflectionPlaneAttr, SetReflectionPlaneAttr, Vector4,
+        Vector4(0.0f, 1.0f, 0.0f, 0.0f), AM_DEFAULT);
+    MIXED_ACCESSOR_ATTRIBUTE("Clip Plane", GetClipPlaneAttr, SetClipPlaneAttr, Vector4, Vector4(0.0f, 1.0f, 0.0f, 0.0f),
+        AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Use Reflection", GetUseReflection, SetUseReflection, bool, false, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Use Clipping", GetUseClipping, SetUseClipping, bool, false, AM_DEFAULT);
 }
@@ -336,7 +340,7 @@ Vector2 Camera::WorldToScreenPoint(const Vector3& worldPos) const
     Vector3 eyeSpacePos = GetView() * worldPos;
     Vector2 ret;
 
-    if(eyeSpacePos.z_ > 0.0f)
+    if (eyeSpacePos.z_ > 0.0f)
     {
         Vector3 screenSpacePos = GetProjection(false) * eyeSpacePos;
         ret.x_ = screenSpacePos.x_;
@@ -392,11 +396,11 @@ Matrix4 Camera::GetProjection(bool apiSpecific) const
     Matrix4 ret(Matrix4::ZERO);
 
     // Whether to construct matrix using OpenGL or Direct3D clip space convention
-    #ifdef URHO3D_OPENGL
+#ifdef URHO3D_OPENGL
     bool openGLFormat = apiSpecific;
-    #else
+#else
     bool openGLFormat = false;
-    #endif
+#endif
 
     if (!orthographic_)
     {

+ 22 - 2
Source/Urho3D/Graphics/Camera.h

@@ -22,10 +22,10 @@
 
 #pragma once
 
-#include "../Math/Frustum.h"
-#include "../Scene/Component.h"
 #include "../Graphics/GraphicsDefs.h"
+#include "../Math/Frustum.h"
 #include "../Math/Ray.h"
+#include "../Scene/Component.h"
 
 namespace Urho3D
 {
@@ -97,28 +97,40 @@ public:
 
     /// Return far clip distance.
     float GetFarClip() const { return farClip_; }
+
     /// Return near clip distance.
     float GetNearClip() const;
+
     /// Return vertical field of view in degrees.
     float GetFov() const { return fov_; }
+
     /// Return orthographic mode size.
     float GetOrthoSize() const { return orthoSize_; }
+
     /// Return aspect ratio.
     float GetAspectRatio() const { return aspectRatio_; }
+
     /// Return zoom.
     float GetZoom() const { return zoom_; }
+
     /// Return LOD bias.
     float GetLodBias() const { return lodBias_; }
+
     /// Return view mask.
     unsigned GetViewMask() const { return viewMask_; }
+
     /// Return view override flags.
     unsigned GetViewOverrideFlags() const { return viewOverrideFlags_; }
+
     /// Return fill mode.
     FillMode GetFillMode() const { return fillMode_; }
+
     /// Return orthographic flag.
     bool IsOrthographic() const { return orthographic_; }
+
     /// Return auto aspect ratio flag.
     bool GetAutoAspectRatio() const { return autoAspectRatio_; }
+
     /// Return frustum in world space.
     const Frustum& GetFrustum() const;
     /// Return API-specific projection matrix.
@@ -143,20 +155,28 @@ public:
     Vector2 WorldToScreenPoint(const Vector3& worldPos) const;
     // Convert normalized screen coordinates (0.0 - 1.0) and depth to a world space point.
     Vector3 ScreenToWorldPoint(const Vector3& screenPos) const;
+
     /// Return projection offset.
     const Vector2& GetProjectionOffset() const { return projectionOffset_; }
+
     /// Return whether is using reflection.
     bool GetUseReflection() const { return useReflection_; }
+
     /// Return the reflection plane.
     const Plane& GetReflectionPlane() const { return reflectionPlane_; }
+
     /// Return whether is using a custom clipping plane.
     bool GetUseClipping() const { return useClipping_; }
+
     /// Return the custom clipping plane.
     const Plane& GetClipPlane() const { return clipPlane_; }
+
     /// Return vertical flipping mode.
     bool GetFlipVertical() const { return flipVertical_; }
+
     /// Return whether to reverse culling; affected by vertical flipping and reflection.
     bool GetReverseCulling() const { return flipVertical_ ^ useReflection_; }
+
     /// Return distance to position. In orthographic mode uses only Z coordinate.
     float GetDistance(const Vector3& worldPos) const;
     /// Return squared distance to position. In orthographic mode uses only Z coordinate.

+ 59 - 48
Source/Urho3D/Graphics/CustomGeometry.cpp

@@ -20,21 +20,22 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
+#include "../Core/Context.h"
+#include "../Core/Profiler.h"
 #include "../Graphics/Batch.h"
 #include "../Graphics/Camera.h"
-#include "../Core/Context.h"
 #include "../Graphics/CustomGeometry.h"
 #include "../Graphics/Geometry.h"
-#include "../IO/Log.h"
 #include "../Graphics/Material.h"
-#include "../IO/MemoryBuffer.h"
-#include "../Scene/Node.h"
 #include "../Graphics/OcclusionBuffer.h"
 #include "../Graphics/OctreeQuery.h"
-#include "../Core/Profiler.h"
-#include "../Resource/ResourceCache.h"
-#include "../IO/VectorBuffer.h"
 #include "../Graphics/VertexBuffer.h"
+#include "../IO/Log.h"
+#include "../IO/MemoryBuffer.h"
+#include "../Resource/ResourceCache.h"
+#include "../Scene/Node.h"
 
 #include "../DebugNew.h"
 
@@ -65,8 +66,10 @@ void CustomGeometry::RegisterObject(Context* context)
 
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
     ATTRIBUTE("Dynamic Vertex Buffer", bool, dynamic_, false, AM_DEFAULT);
-    MIXED_ACCESSOR_ATTRIBUTE("Geometry Data", GetGeometryDataAttr, SetGeometryDataAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE|AM_NOEDIT);
-    ACCESSOR_ATTRIBUTE("Materials", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()), AM_DEFAULT);
+    MIXED_ACCESSOR_ATTRIBUTE("Geometry Data", GetGeometryDataAttr, SetGeometryDataAttr, PODVector<unsigned char>,
+        Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
+    ACCESSOR_ATTRIBUTE("Materials", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()),
+        AM_DEFAULT);
     ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
     ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
@@ -88,43 +91,49 @@ void CustomGeometry::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQ
 
     case RAY_OBB:
     case RAY_TRIANGLE:
-        Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
-        Ray localRay = query.ray_.Transformed(inverse);
-        float distance = localRay.HitDistance(boundingBox_);
-        Vector3 normal = -query.ray_.direction_;
-
-        if (level == RAY_TRIANGLE && distance < query.maxDistance_)
         {
-            distance = M_INFINITY;
+            Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
+            Ray localRay = query.ray_.Transformed(inverse);
+            float distance = localRay.HitDistance(boundingBox_);
+            Vector3 normal = -query.ray_.direction_;
 
-            for (unsigned i = 0; i < batches_.Size(); ++i)
+            if (level == RAY_TRIANGLE && distance < query.maxDistance_)
             {
-                Geometry* geometry = batches_[i].geometry_;
-                if (geometry)
+                distance = M_INFINITY;
+
+                for (unsigned i = 0; i < batches_.Size(); ++i)
                 {
-                    Vector3 geometryNormal;
-                    float geometryDistance = geometry->GetHitDistance(localRay, &geometryNormal);
-                    if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
+                    Geometry* geometry = batches_[i].geometry_;
+                    if (geometry)
                     {
-                        distance = geometryDistance;
-                        normal = (node_->GetWorldTransform() * Vector4(geometryNormal, 0.0f)).Normalized();
+                        Vector3 geometryNormal;
+                        float geometryDistance = geometry->GetHitDistance(localRay, &geometryNormal);
+                        if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
+                        {
+                            distance = geometryDistance;
+                            normal = (node_->GetWorldTransform() * Vector4(geometryNormal, 0.0f)).Normalized();
+                        }
                     }
                 }
             }
-        }
 
-        if (distance < query.maxDistance_)
-        {
-            RayQueryResult result;
-            result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
-            result.normal_ = normal;
-            result.distance_ = distance;
-            result.drawable_ = this;
-            result.node_ = node_;
-            result.subObject_ = M_MAX_UNSIGNED;
-            results.Push(result);
+            if (distance < query.maxDistance_)
+            {
+                RayQueryResult result;
+                result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
+                result.normal_ = normal;
+                result.distance_ = distance;
+                result.drawable_ = this;
+                result.node_ = node_;
+                result.subObject_ = M_MAX_UNSIGNED;
+                results.Push(result);
+            }
         }
         break;
+
+    case RAY_TRIANGLE_UV:
+        LOGWARNING("RAY_TRIANGLE_UV query level is not supported for CustomGeometry component");
+        break;
     }
 }
 
@@ -187,7 +196,8 @@ bool CustomGeometry::DrawOcclusion(OcclusionBuffer* buffer)
             continue;
 
         // Draw and check for running out of triangles
-        success = buffer->Draw(node_->GetWorldTransform(), vertexData, vertexSize, geometry->GetVertexStart(), geometry->GetVertexCount());
+        success = buffer->Draw(node_->GetWorldTransform(), vertexData, vertexSize, geometry->GetVertexStart(),
+            geometry->GetVertexCount());
 
         if (!success)
             break;
@@ -290,7 +300,8 @@ void CustomGeometry::DefineTangent(const Vector4& tangent)
     elementMask_ |= MASK_TANGENT;
 }
 
-void CustomGeometry::DefineGeometry(unsigned index, PrimitiveType type, unsigned numVertices, bool hasNormals, bool hasColors, bool hasTexCoords, bool hasTangents)
+void CustomGeometry::DefineGeometry(unsigned index, PrimitiveType type, unsigned numVertices, bool hasNormals, bool hasColors,
+    bool hasTexCoords, bool hasTangents)
 {
     if (index > geometries_.Size())
     {
@@ -431,7 +442,7 @@ Material* CustomGeometry::GetMaterial(unsigned index) const
 CustomGeometryVertex* CustomGeometry::GetVertex(unsigned geometryIndex, unsigned vertexNum)
 {
     return (geometryIndex < vertices_.Size() && vertexNum < vertices_[geometryIndex].Size()) ?
-        &vertices_[geometryIndex][vertexNum] : (CustomGeometryVertex*)0;
+           &vertices_[geometryIndex][vertexNum] : (CustomGeometryVertex*)0;
 }
 
 void CustomGeometry::SetGeometryDataAttr(const PODVector<unsigned char>& value)
@@ -452,15 +463,15 @@ void CustomGeometry::SetGeometryDataAttr(const PODVector<unsigned char>& value)
 
         for (unsigned j = 0; j < numVertices; ++j)
         {
-             if (elementMask_ & MASK_POSITION)
+            if (elementMask_ & MASK_POSITION)
                 vertices_[i][j].position_ = buffer.ReadVector3();
-             if (elementMask_ & MASK_NORMAL)
+            if (elementMask_ & MASK_NORMAL)
                 vertices_[i][j].normal_ = buffer.ReadVector3();
-             if (elementMask_ & MASK_COLOR)
+            if (elementMask_ & MASK_COLOR)
                 vertices_[i][j].color_ = buffer.ReadUInt();
-             if (elementMask_ & MASK_TEXCOORD1)
+            if (elementMask_ & MASK_TEXCOORD1)
                 vertices_[i][j].texCoord_ = buffer.ReadVector2();
-             if (elementMask_ & MASK_TANGENT)
+            if (elementMask_ & MASK_TANGENT)
                 vertices_[i][j].tangent_ = buffer.ReadVector4();
         }
     }
@@ -490,15 +501,15 @@ PODVector<unsigned char> CustomGeometry::GetGeometryDataAttr() const
 
         for (unsigned j = 0; j < numVertices; ++j)
         {
-             if (elementMask_ & MASK_POSITION)
+            if (elementMask_ & MASK_POSITION)
                 ret.WriteVector3(vertices_[i][j].position_);
-             if (elementMask_ & MASK_NORMAL)
+            if (elementMask_ & MASK_NORMAL)
                 ret.WriteVector3(vertices_[i][j].normal_);
-             if (elementMask_ & MASK_COLOR)
+            if (elementMask_ & MASK_COLOR)
                 ret.WriteUInt(vertices_[i][j].color_);
-             if (elementMask_ & MASK_TEXCOORD1)
+            if (elementMask_ & MASK_TEXCOORD1)
                 ret.WriteVector2(vertices_[i][j].texCoord_);
-             if (elementMask_ & MASK_TANGENT)
+            if (elementMask_ & MASK_TANGENT)
                 ret.WriteVector4(vertices_[i][j].tangent_);
         }
     }

+ 8 - 1
Source/Urho3D/Graphics/CustomGeometry.h

@@ -85,7 +85,9 @@ public:
     /// Define a vertex tangent.
     void DefineTangent(const Vector4& tangent);
     /// Set the primitive type, number of vertices and elements in a geometry, after which the vertices can be edited with GetVertex(). An alternative to BeginGeometry() / DefineVertex().
-    void DefineGeometry(unsigned index, PrimitiveType type, unsigned numVertices, bool hasNormals, bool hasColors, bool hasTexCoords, bool hasTangents);
+    void DefineGeometry
+        (unsigned index, PrimitiveType type, unsigned numVertices, bool hasNormals, bool hasColors, bool hasTexCoords,
+            bool hasTangents);
     /// Update vertex buffer and calculate the bounding box. Call after finishing defining geometry.
     void Commit();
     /// Set material on all geometries.
@@ -95,14 +97,19 @@ public:
 
     /// Return number of geometries.
     unsigned GetNumGeometries() const { return geometries_.Size(); }
+
     /// Return number of vertices in a geometry.
     unsigned GetNumVertices(unsigned index) const;
+
     /// Return whether vertex buffer dynamic mode is enabled.
     bool IsDynamic() const { return dynamic_; }
+
     /// Return material by geometry index.
     Material* GetMaterial(unsigned index = 0) const;
+
     /// Return all vertices. These can be edited; calling Commit() updates the vertex buffer.
     Vector<PODVector<CustomGeometryVertex> >& GetVertices() { return vertices_; }
+
     /// Return a vertex in a geometry for editing, or null if out of bounds. After the edits are finished, calling Commit() updates  the vertex buffer.
     CustomGeometryVertex* GetVertex(unsigned geometryIndex, unsigned vertexNum);
 

+ 44 - 23
Source/Urho3D/Graphics/DebugRenderer.cpp

@@ -20,19 +20,20 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
 
-#include "../Graphics/AnimatedModel.h"
-#include "../Graphics/Camera.h"
 #include "../Core/Context.h"
 #include "../Core/CoreEvents.h"
+#include "../Core/Profiler.h"
+#include "../Graphics/AnimatedModel.h"
+#include "../Graphics/Camera.h"
 #include "../Graphics/DebugRenderer.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/Light.h"
-#include "../Math/Polyhedron.h"
-#include "../Core/Profiler.h"
-#include "../Resource/ResourceCache.h"
 #include "../Graphics/ShaderVariation.h"
 #include "../Graphics/VertexBuffer.h"
+#include "../Math/Polyhedron.h"
+#include "../Resource/ResourceCache.h"
 
 #include "../DebugNew.h"
 
@@ -89,7 +90,7 @@ void DebugRenderer::AddLine(const Vector3& start, const Vector3& end, unsigned c
         noDepthLines_.Push(DebugLine(start, end, color));
 }
 
-void DebugRenderer::AddTriangle(const Vector3& v1, const Vector3& v2, const Vector3& v3,  const Color& color, bool depthTest)
+void DebugRenderer::AddTriangle(const Vector3& v1, const Vector3& v2, const Vector3& v3, const Color& color, bool depthTest)
 {
     AddTriangle(v1, v2, v3, color.ToUInt(), depthTest);
 }
@@ -223,7 +224,7 @@ static Vector3 PointOnSphere(const Sphere& sphere, unsigned theta, unsigned phi)
 void DebugRenderer::AddSphere(const Sphere& sphere, const Color& color, bool depthTest)
 {
     unsigned uintColor = color.ToUInt();
-    
+
     for (unsigned j = 0; j < 180; j += 45)
     {
         for (unsigned i = 0; i < 360; i += 45)
@@ -232,7 +233,7 @@ void DebugRenderer::AddSphere(const Sphere& sphere, const Color& color, bool dep
             Vector3 p2 = PointOnSphere(sphere, i + 45, j);
             Vector3 p3 = PointOnSphere(sphere, i, j + 45);
             Vector3 p4 = PointOnSphere(sphere, i + 45, j + 45);
-            
+
             AddLine(p1, p2, uintColor, depthTest);
             AddLine(p3, p4, uintColor, depthTest);
             AddLine(p1, p3, uintColor, depthTest);
@@ -352,7 +353,7 @@ void DebugRenderer::Render()
 
     ShaderVariation* vs = graphics->GetShader(VS, "Basic", "VERTEXCOLOR");
     ShaderVariation* ps = graphics->GetShader(PS, "Basic", "VERTEXCOLOR");
-    
+
     unsigned numVertices = (lines_.Size() + noDepthLines_.Size()) * 2 + (triangles_.Size() + noDepthTriangles_.Size()) * 3;
     // Resize the vertex buffer if too small or much too large
     if (vertexBuffer_->GetVertexCount() < numVertices || vertexBuffer_->GetVertexCount() > numVertices * 2)
@@ -366,9 +367,13 @@ void DebugRenderer::Render()
     {
         const DebugLine& line = lines_[i];
 
-        dest[0] = line.start_.x_; dest[1] = line.start_.y_; dest[2] = line.start_.z_;
+        dest[0] = line.start_.x_;
+        dest[1] = line.start_.y_;
+        dest[2] = line.start_.z_;
         ((unsigned&)dest[3]) = line.color_;
-        dest[4] = line.end_.x_; dest[5] = line.end_.y_; dest[6] = line.end_.z_;
+        dest[4] = line.end_.x_;
+        dest[5] = line.end_.y_;
+        dest[6] = line.end_.z_;
         ((unsigned&)dest[7]) = line.color_;
 
         dest += 8;
@@ -378,9 +383,13 @@ void DebugRenderer::Render()
     {
         const DebugLine& line = noDepthLines_[i];
 
-        dest[0] = line.start_.x_; dest[1] = line.start_.y_; dest[2] = line.start_.z_;
+        dest[0] = line.start_.x_;
+        dest[1] = line.start_.y_;
+        dest[2] = line.start_.z_;
         ((unsigned&)dest[3]) = line.color_;
-        dest[4] = line.end_.x_; dest[5] = line.end_.y_; dest[6] = line.end_.z_;
+        dest[4] = line.end_.x_;
+        dest[5] = line.end_.y_;
+        dest[6] = line.end_.z_;
         ((unsigned&)dest[7]) = line.color_;
 
         dest += 8;
@@ -390,13 +399,19 @@ void DebugRenderer::Render()
     {
         const DebugTriangle& triangle = triangles_[i];
 
-        dest[0] = triangle.v1_.x_; dest[1] = triangle.v1_.y_; dest[2] = triangle.v1_.z_;
+        dest[0] = triangle.v1_.x_;
+        dest[1] = triangle.v1_.y_;
+        dest[2] = triangle.v1_.z_;
         ((unsigned&)dest[3]) = triangle.color_;
 
-        dest[4] = triangle.v2_.x_; dest[5] = triangle.v2_.y_; dest[6] = triangle.v2_.z_;
+        dest[4] = triangle.v2_.x_;
+        dest[5] = triangle.v2_.y_;
+        dest[6] = triangle.v2_.z_;
         ((unsigned&)dest[7]) = triangle.color_;
-        
-        dest[8] = triangle.v3_.x_; dest[9] = triangle.v3_.y_; dest[10] = triangle.v3_.z_;
+
+        dest[8] = triangle.v3_.x_;
+        dest[9] = triangle.v3_.y_;
+        dest[10] = triangle.v3_.z_;
         ((unsigned&)dest[11]) = triangle.color_;
 
         dest += 12;
@@ -406,13 +421,19 @@ void DebugRenderer::Render()
     {
         const DebugTriangle& triangle = noDepthTriangles_[i];
 
-        dest[0] = triangle.v1_.x_; dest[1] = triangle.v1_.y_; dest[2] = triangle.v1_.z_;
+        dest[0] = triangle.v1_.x_;
+        dest[1] = triangle.v1_.y_;
+        dest[2] = triangle.v1_.z_;
         ((unsigned&)dest[3]) = triangle.color_;
 
-        dest[4] = triangle.v2_.x_; dest[5] = triangle.v2_.y_; dest[6] = triangle.v2_.z_;
+        dest[4] = triangle.v2_.x_;
+        dest[5] = triangle.v2_.y_;
+        dest[6] = triangle.v2_.z_;
         ((unsigned&)dest[7]) = triangle.color_;
 
-        dest[8] = triangle.v3_.x_; dest[9] = triangle.v3_.y_; dest[10] = triangle.v3_.z_;
+        dest[8] = triangle.v3_.x_;
+        dest[9] = triangle.v3_.y_;
+        dest[10] = triangle.v3_.z_;
         ((unsigned&)dest[11]) = triangle.color_;
 
         dest += 12;
@@ -448,9 +469,9 @@ void DebugRenderer::Render()
         graphics->Draw(LINE_LIST, start, count);
         start += count;
     }
-    
+
     graphics->SetBlendMode(BLEND_ALPHA);
-    
+
     if (triangles_.Size())
     {
         count = triangles_.Size() * 3;
@@ -473,7 +494,7 @@ bool DebugRenderer::IsInside(const BoundingBox& box) const
 
 bool DebugRenderer::HasContent() const
 {
-    return (lines_.Empty() && noDepthLines_.Empty() && triangles_.Empty() && noDepthTriangles_.Empty()) ? false : true;
+    return !(lines_.Empty() && noDepthLines_.Empty() && triangles_.Empty() && noDepthTriangles_.Empty());
 }
 
 void DebugRenderer::HandleEndFrame(StringHash eventType, VariantMap& eventData)

+ 14 - 9
Source/Urho3D/Graphics/DebugRenderer.h

@@ -23,8 +23,8 @@
 #pragma once
 
 #include "../Math/Color.h"
-#include "../Scene/Component.h"
 #include "../Math/Frustum.h"
+#include "../Scene/Component.h"
 
 namespace Urho3D
 {
@@ -47,7 +47,7 @@ struct DebugLine
     DebugLine()
     {
     }
-    
+
     /// Construct with start and end positions and color.
     DebugLine(const Vector3& start, const Vector3& end, unsigned color) :
         start_(start),
@@ -55,7 +55,7 @@ struct DebugLine
         color_(color)
     {
     }
-    
+
     /// Start position.
     Vector3 start_;
     /// End position.
@@ -95,7 +95,7 @@ struct DebugTriangle
 class URHO3D_API DebugRenderer : public Component
 {
     OBJECT(DebugRenderer);
-    
+
 public:
     /// Construct.
     DebugRenderer(Context* context);
@@ -103,7 +103,7 @@ public:
     virtual ~DebugRenderer();
     /// Register object factory.
     static void RegisterObject(Context* context);
-    
+
     /// Set the camera viewpoint. Call before rendering, or before adding geometry if you want to use culling.
     void SetView(Camera* camera);
     /// Add a line.
@@ -131,25 +131,30 @@ public:
     /// Add a skeleton.
     void AddSkeleton(const Skeleton& skeleton, const Color& color, bool depthTest = true);
     /// Add a triangle mesh.
-    void AddTriangleMesh(const void* vertexData, unsigned vertexSize, const void* indexData, unsigned indexSize, unsigned indexStart, unsigned indexCount, const Matrix3x4& transform, const Color& color, bool depthTest = true);
+    void AddTriangleMesh
+        (const void* vertexData, unsigned vertexSize, const void* indexData, unsigned indexSize, unsigned indexStart,
+            unsigned indexCount, const Matrix3x4& transform, const Color& color, bool depthTest = true);
     /// Update vertex buffer and render all debug lines. The viewport and rendertarget should be set before.
     void Render();
-    
+
     /// Return the view transform.
     const Matrix3x4& GetView() const { return view_; }
+
     /// Return the projection transform.
     const Matrix4& GetProjection() const { return projection_; }
+
     /// Return the view frustum.
     const Frustum& GetFrustum() const { return frustum_; }
+
     /// Check whether a bounding box is inside the view frustum.
     bool IsInside(const BoundingBox& box) const;
     /// Return whether has something to render.
     bool HasContent() const;
-    
+
 private:
     /// Handle end of frame. Clear debug geometry.
     void HandleEndFrame(StringHash eventType, VariantMap& eventData);
-    
+
     /// Lines rendered with depth test.
     PODVector<DebugLine> lines_;
     /// Lines rendered without depth test.

+ 21 - 19
Source/Urho3D/Graphics/DecalSet.cpp

@@ -20,25 +20,25 @@
 // THE SOFTWARE.
 //
 
+#include "../Precompiled.h"
+
+#include "../Core/Context.h"
+#include "../Core/Profiler.h"
 #include "../Graphics/AnimatedModel.h"
 #include "../Graphics/Batch.h"
 #include "../Graphics/Camera.h"
-#include "../Core/Context.h"
 #include "../Graphics/DecalSet.h"
 #include "../Graphics/Geometry.h"
 #include "../Graphics/Graphics.h"
 #include "../Graphics/IndexBuffer.h"
-#include "../IO/Log.h"
 #include "../Graphics/Material.h"
+#include "../Graphics/Tangent.h"
+#include "../Graphics/VertexBuffer.h"
+#include "../IO/Log.h"
 #include "../IO/MemoryBuffer.h"
-#include "../Scene/Node.h"
-#include "../Core/Profiler.h"
 #include "../Resource/ResourceCache.h"
 #include "../Scene/Scene.h"
 #include "../Scene/SceneEvents.h"
-#include "../Graphics/Tangent.h"
-#include "../IO/VectorBuffer.h"
-#include "../Graphics/VertexBuffer.h"
 
 #include "../DebugNew.h"
 
@@ -54,7 +54,7 @@ static const unsigned DEFAULT_MAX_VERTICES = 512;
 static const unsigned DEFAULT_MAX_INDICES = 1024;
 static const unsigned STATIC_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT;
 static const unsigned SKINNED_ELEMENT_MASK = MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT | MASK_BLENDWEIGHTS |
-    MASK_BLENDINDICES;
+                                             MASK_BLENDINDICES;
 
 static DecalVertex ClipEdge(const DecalVertex& v0, const DecalVertex& v1, float d0, float d1, bool skinned)
 {
@@ -91,7 +91,7 @@ static DecalVertex ClipEdge(const DecalVertex& v0, const DecalVertex& v1, float
 
 static void ClipPolygon(PODVector<DecalVertex>& dest, const PODVector<DecalVertex>& src, const Plane& plane, bool skinned)
 {
-    unsigned last;
+    unsigned last = 0;
     float lastDistance = 0.0f;
     dest.Clear();
 
@@ -130,12 +130,12 @@ void Decal::AddVertex(const DecalVertex& vertex)
     {
         if (vertex.position_.Equals(vertices_[i].position_) && vertex.normal_.Equals(vertices_[i].normal_))
         {
-            indices_.Push(i);
+            indices_.Push((unsigned short)i);
             return;
         }
     }
 
-    unsigned short newIndex = vertices_.Size();
+    unsigned short newIndex = (unsigned short)vertices_.Size();
     vertices_.Push(vertex);
     indices_.Push(newIndex);
 }
@@ -180,13 +180,15 @@ void DecalSet::RegisterObject(Context* context)
     context->RegisterFactory<DecalSet>(GEOMETRY_CATEGORY);
 
     ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
-    MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT);
+    MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()),
+        AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Max Vertices", GetMaxVertices, SetMaxVertices, unsigned, DEFAULT_MAX_VERTICES, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Max Indices", GetMaxIndices, SetMaxIndices, unsigned, DEFAULT_MAX_INDICES, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
     ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
     COPY_BASE_ATTRIBUTES(Drawable);
-    MIXED_ACCESSOR_ATTRIBUTE("Decals", GetDecalsAttr, SetDecalsAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
+    MIXED_ACCESSOR_ATTRIBUTE("Decals", GetDecalsAttr, SetDecalsAttr, PODVector<unsigned char>, Variant::emptyBuffer,
+        AM_FILE | AM_NOEDIT);
 }
 
 void DecalSet::ApplyAttributes()
@@ -252,7 +254,7 @@ void DecalSet::SetMaterial(Material* material)
 void DecalSet::SetMaxVertices(unsigned num)
 {
     // Never expand to 32 bit indices
-    num = Clamp((int)num, MIN_VERTICES, MAX_VERTICES);
+    num = (unsigned)Clamp((int)num, MIN_VERTICES, MAX_VERTICES);
 
     if (num != maxVertices_)
     {
@@ -329,8 +331,8 @@ bool DecalSet::AddDecal(Drawable* target, const Vector3& worldPosition, const Qu
                 continue;
 
             // Represent the decal as a sphere, try to find the biggest colliding bone
-            Sphere decalSphere(bone->node_->GetWorldTransform().Inverse() * worldPosition, 0.5f * size /
-                bone->node_->GetWorldScale().Length());
+            Sphere decalSphere
+                (bone->node_->GetWorldTransform().Inverse() * worldPosition, 0.5f * size / bone->node_->GetWorldScale().Length());
 
             if (bone->collisionMask_ & BONECOLLISION_BOX)
             {
@@ -421,14 +423,14 @@ bool DecalSet::AddDecal(Drawable* target, const Vector3& worldPosition, const Qu
     if (newDecal.vertices_.Size() > maxVertices_)
     {
         LOGWARNING("Can not add decal, vertex count " + String(newDecal.vertices_.Size()) + " exceeds maximum " +
-            String(maxVertices_));
+                   String(maxVertices_));
         decals_.Pop();
         return false;
     }
     if (newDecal.indices_.Size() > maxIndices_)
     {
         LOGWARNING("Can not add decal, index count " + String(newDecal.indices_.Size()) + " exceeds maximum " +
-            String(maxIndices_));
+                   String(maxIndices_));
         decals_.Pop();
         return false;
     }
@@ -932,7 +934,7 @@ bool DecalSet::GetBones(Drawable* target, unsigned batchIndex, const float* blen
                 }
             }
 
-            newBlendIndices[i] = index;
+            newBlendIndices[i] = (unsigned char)index;
         }
         else
             newBlendIndices[i] = 0;

+ 21 - 7
Source/Urho3D/Graphics/DecalSet.h

@@ -22,10 +22,10 @@
 
 #pragma once
 
-#include "../Graphics/Drawable.h"
-#include "../Math/Frustum.h"
 #include "../Container/List.h"
+#include "../Graphics/Drawable.h"
 #include "../Graphics/Skeleton.h"
+#include "../Math/Frustum.h"
 
 namespace Urho3D
 {
@@ -134,7 +134,9 @@ public:
     /// Set maximum number of decal vertex indices.
     void SetMaxIndices(unsigned num);
     /// Add a decal at world coordinates, using a target drawable's geometry for reference. If the decal needs to move with the target, the decal component should be created to the target's node. Return true if successful.
-    bool AddDecal(Drawable* target, const Vector3& worldPosition, const Quaternion& worldRotation, float size, float aspectRatio, float depth, const Vector2& topLeftUV, const Vector2& bottomRightUV, float timeToLive = 0.0f, float normalCutoff = 0.1f, unsigned subGeometry = M_MAX_UNSIGNED);
+    bool AddDecal(Drawable* target, const Vector3& worldPosition, const Quaternion& worldRotation, float size, float aspectRatio,
+        float depth, const Vector2& topLeftUV, const Vector2& bottomRightUV, float timeToLive = 0.0f, float normalCutoff = 0.1f,
+        unsigned subGeometry = M_MAX_UNSIGNED);
     /// Remove n oldest decals.
     void RemoveDecals(unsigned num);
     /// Remove all decals.
@@ -142,14 +144,19 @@ public:
 
     /// Return material.
     Material* GetMaterial() const;
+
     /// Return number of decals.
     unsigned GetNumDecals() const { return decals_.Size(); }
+
     /// Retur number of vertices in the decals.
     unsigned GetNumVertices() const { return numVertices_; }
+
     /// Retur number of vertex indices in the decals.
     unsigned GetNumIndices() const { return numIndices_; }
+
     /// Return maximum number of decal vertices.
     unsigned GetMaxVertices() const { return maxVertices_; }
+
     /// Return maximum number of decal vertex indices.
     unsigned GetMaxIndices() const { return maxIndices_; }
 
@@ -170,13 +177,20 @@ protected:
 
 private:
     /// Get triangle faces from the target geometry.
-    void GetFaces(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, const Frustum& frustum, const Vector3& decalNormal, float normalCutoff);
+    void GetFaces(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, const Frustum& frustum,
+        const Vector3& decalNormal, float normalCutoff);
     /// Get triangle face from the target geometry.
-    void GetFace(Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, unsigned i0, unsigned i1, unsigned i2, const unsigned char* positionData, const unsigned char* normalData, const unsigned char* skinningData, unsigned positionStride, unsigned normalStride, unsigned skinningStride, const Frustum& frustum, const Vector3& decalNormal, float normalCutoff);
+    void GetFace
+        (Vector<PODVector<DecalVertex> >& faces, Drawable* target, unsigned batchIndex, unsigned i0, unsigned i1, unsigned i2,
+            const unsigned char* positionData, const unsigned char* normalData, const unsigned char* skinningData,
+            unsigned positionStride, unsigned normalStride, unsigned skinningStride, const Frustum& frustum,
+            const Vector3& decalNormal, float normalCutoff);
     /// Get bones referenced by skinning data and remap the skinning indices. Return true if successful.
-    bool GetBones(Drawable* target, unsigned batchIndex, const float* blendWeights, const unsigned char* blendIndices, unsigned char* newBlendIndices);
+    bool GetBones(Drawable* target, unsigned batchIndex, const float* blendWeights, const unsigned char* blendIndices,
+        unsigned char* newBlendIndices);
     /// Calculate UV coordinates for the decal.
-    void CalculateUVs(Decal& decal, const Matrix3x4& view, const Matrix4& projection, const Vector2& topLeftUV, const Vector2& bottomRightUV);
+    void CalculateUVs
+        (Decal& decal, const Matrix3x4& view, const Matrix4& projection, const Vector2& topLeftUV, const Vector2& bottomRightUV);
     /// Transform decal's vertices from the target geometry to the decal set local space.
     void TransformVertices(Decal& decal, const Matrix3x4& transform);
     /// Remove a decal by iterator and return iterator to the next decal.

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11ConstantBuffer.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../../Precompiled.h"
+
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/GraphicsImpl.h"
 #include "../../IO/Log.h"

+ 0 - 3
Source/Urho3D/Graphics/Direct3D11/D3D11ConstantBuffer.h

@@ -59,9 +59,6 @@ public:
     bool IsDirty() const { return dirty_; }
 
 private:
-    /// Create buffer.
-    bool Create();
-
     /// Shadow data.
     SharedArrayPtr<unsigned char> shadowData_;
     /// Buffer byte size.

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11GPUObject.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../../Precompiled.h"
+
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/GraphicsImpl.h"
 #include "../../Graphics/GPUObject.h"

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11Graphics.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../../Precompiled.h"
+
 #include "../../Graphics/AnimatedModel.h"
 #include "../../Graphics/Animation.h"
 #include "../../Graphics/AnimationController.h"

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11GraphicsImpl.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../../Precompiled.h"
+
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/GraphicsEvents.h"
 #include "../../Graphics/GraphicsImpl.h"

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11IndexBuffer.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../../Precompiled.h"
+
 #include "../../Core/Context.h"
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/GraphicsImpl.h"

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11RenderSurface.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../../Precompiled.h"
+
 #include "../../Graphics/Camera.h"
 #include "../../Graphics/Graphics.h"
 #include "../../Graphics/GraphicsImpl.h"

+ 2 - 0
Source/Urho3D/Graphics/Direct3D11/D3D11ShaderVariation.cpp

@@ -20,6 +20,8 @@
 // THE SOFTWARE.
 //
 
+#include "../../Precompiled.h"
+
 #include "../../IO/File.h"
 #include "../../IO/FileSystem.h"
 #include "../../Graphics/Graphics.h"

Some files were not shown because too many files changed in this diff