Subversion Repository Public Repository

Divide-Framework

This repository has no backups
This repository's network speed is throttled to 100KB/sec

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
/*
   Copyright (c) 2017 DIVIDE-Studio
   Copyright (c) 2009 Ionut Cava

   This file is part of DIVIDE Framework.

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software
   and associated documentation files (the "Software"), to deal in the Software
   without restriction,
   including without limitation the rights to use, copy, modify, merge, publish,
   distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so,
   subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED,
   INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
   PARTICULAR PURPOSE AND NONINFRINGEMENT.
   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
   DAMAGES OR OTHER LIABILITY,
   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
   IN CONNECTION WITH THE SOFTWARE
   OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 */

#ifndef _PLATFORM_DEFINES_H_
#define _PLATFORM_DEFINES_H_

#ifndef BOOST_EXCEPTION_DISABLE
#define BOOST_EXCEPTION_DISABLE
#endif

#include "Core/TemplateLibraries/Headers/HashMap.h"
#include "Core/Headers/Singleton.h"
#include "Core/Headers/NonCopyable.h"
#include "Core/Headers/GUIDWrapper.h"
#include "Platform/Threading/Headers/SharedMutex.h"
#include "Platform/File/Headers/FileManagement.h"
#include "ConditionalWait.h"

#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif //_USE_MATH_DEFINES

#include <cmath>
#include <functional>
#include <atomic>
#include <array>
#include <memory>
#include <bitset>
#include <limits>
#include <stdarg.h>
#include <cmath>
#include <cstdio>

#if !defined(CPP_VERSION)
#   define CPP_VERSION __cplusplus
#endif

#if defined(_WIN32)
#include "PlatformDefinesWindows.h"
#elif defined(__APPLE_CC__) 
#include "PlatformDefinesApple.h"
#else //defined(__linux) || defined (__unix)
#include "PlatformDefinesUnix.h"
#endif

#ifdef _DEBUG
#include <assert.h>

#define STUBBED(x)                                  \
do {                                                \
    static bool seen_this = false;                  \
    if (!seen_this) {                               \
        seen_this = true;                           \
        Console::errorfn("STUBBED: %s (%s : %d)\n", \
                         x, __FILE__, __LINE__);    \
    }                                               \
} while (0);

#else
#define STUBBED(x)
#endif

#ifndef TO_STRING
#define TO_STRING(X) TO_STRING_NAME(X)
#define TO_STRING_NAME(X) #X
#endif //TO_STRING

#define TYPEDEF_SMART_POINTERS_FOR_CLASS(T)      \
    typedef std::weak_ptr<T> T ## _wptr;         \
    typedef std::shared_ptr<T> T ## _ptr;        \
    typedef std::weak_ptr<const T> T ## _cwptr;  \
    typedef std::shared_ptr<const T> T ## _cptr; 

#define FWD_DECLARE_MANAGED_CLASS(T)      \
    class T;                              \
    TYPEDEF_SMART_POINTERS_FOR_CLASS(T);

#if CPP_VERSION > 1
#   define CPP_98_SUPPORT
#   define CPP_03_SUPPORT
#   if CPP_VERSION >= 201103L
#       define CPP_11_SUPPORT
#           if CPP_VERSION >= 201402L
#               define CPP_14_SUPPORT
#               if CPP_VERSION > 201402L
#                   if HAS_CPP17
#                       define CPP_17_SUPPORT
#                   endif
#               endif
#           endif
#   endif
#endif 

#if !defined(CPP_11_SUPPORT)
#error "Divide Framework requires C++11 support at a minimum!."
#endif 

namespace Divide {

constexpr U64 basis = UINT64_C(14695981039346656037);
constexpr U64 prime = UINT64_C(1099511628211);

constexpr U64 hash_one(char c, const char* remain, const U64 value)
{
    return c == 0 ? value : hash_one(remain[0], remain + 1, (value ^ c) * prime);
}

constexpr U64 _ID(const char* str)
{
    return hash_one(str[0], str + 1, basis);
}

FORCE_INLINE U64 _ID_RT(const char* str)
{
    U64 hash = basis;
    while (*str != 0) {
        hash ^= str[0];
        hash *= prime;
        ++str;
    }
    return hash;
}

FORCE_INLINE U64 _ID_RT(const stringImpl& str) {
    return _ID_RT(str.c_str());
}

FORCE_INLINE bufferPtr bufferOffset(size_t offset) {
    return ((char *)NULL + (offset));
}

struct SysInfo;

SysInfo& sysInfo();
const SysInfo& const_sysInfo();

void InitSysInfo(SysInfo& info, I32 argc, char** argv);

extern void getWindowHandle(void* window, SysInfo& info);
extern void setThreadName(std::thread* thread, const char* threadName);
extern void setThreadName(const char* threadName);
extern bool createDirectory(const char* path);

//ref: http://stackoverflow.com/questions/1528298/get-path-of-executable
extern FileWithPath getExecutableLocation(I32 argc, char** argv);
FileWithPath getExecutableLocation(char* argv0);

bool createDirectories(const char* path);

bool PlatformInit(int argc, char** argv);
bool PlatformClose();
bool GetAvailableMemory(SysInfo& info);

bool PlatformPostInit(int argc, char** argv);

template <typename T>
struct synchronized {
public:
    synchronized& operator=(T const& newval) {
        ReadLock lock(mutex);
        value = newval;
        return *this;
    }

    operator T() const {
        WriteLock lock(mutex);
        return value;
    }

private:
    T value;
    SharedLock mutex;
};

/// Converts an arbitrary positive integer value to a bitwise value used for masks
template<typename T>
constexpr T toBit(const T X) {
    //static_assert(X > 0, "toBit(0) is currently disabled!");
    return 1 << X;
}

inline U32 powerOfTwo(U32 X) {
    U32 r = 0;
    while (X >>= 1) {
        r++;
    }
    return r;
}

inline bool isPowerOfTwo(U32 x) {
    return !(x == 0) && !(x & (x - 1));
}

static inline size_t realign_offset(size_t offset, size_t align) {
    return (offset + align - 1) & ~(align - 1);
}

#if !defined(CPP_11_SUPPORT)
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
#endif

#if !defined(CPP_14_SUPPORT)
namespace std {
    // TEMPLATE FUNCTIONS cbegin AND cend
    template<class _Container>
    auto inline cbegin(const _Container& _Cont) -> decltype(::std::begin(_Cont))
    {	// get beginning of sequence
        return (::std::begin(_Cont));
    }

    template<class _Container>
    auto inline cend(const _Container& _Cont) -> decltype(::std::end(_Cont))
    {	// get end of sequence
        return (::std::end(_Cont));
    }

    // TEMPLATE FUNCTIONS rbegin AND rend
    template<class _Container>
    auto inline rbegin(_Container& _Cont) -> decltype(_Cont.rbegin())
    {	// get beginning of reversed sequence
        return (_Cont.rbegin());
    }

    template<class _Container>
    auto inline rbegin(const _Container& _Cont) -> decltype(_Cont.rbegin())
    {	// get beginning of reversed sequence
        return (_Cont.rbegin());
    }

    template<class _Container>
    auto inline rend(_Container& _Cont) -> decltype(_Cont.rend())
    {	// get end of reversed sequence
        return (_Cont.rend());
    }

    template<class _Container>
    auto inline rend(const _Container& _Cont) -> decltype(_Cont.rend())
    {	// get end of reversed sequence
        return (_Cont.rend());
    }

    template<class _Ty,
        size_t _Size> inline
        reverse_iterator<_Ty *> rbegin(_Ty(&_Array)[_Size])
    {	// get beginning of reversed array
        return (reverse_iterator<_Ty *>(_Array + _Size));
    }

    template<class _Ty,
        size_t _Size> inline
        reverse_iterator<_Ty *> rend(_Ty(&_Array)[_Size])
    {	// get end of reversed array
        return (reverse_iterator<_Ty *>(_Array));
    }

    template<class _Elem> inline
        reverse_iterator<const _Elem *> rbegin(initializer_list<_Elem> _Ilist)
    {	// get beginning of reversed sequence
        return (reverse_iterator<const _Elem *>(_Ilist.end()));
    }

    template<class _Elem> inline
        reverse_iterator<const _Elem *> rend(initializer_list<_Elem> _Ilist)
    {	// get end of reversed sequence
        return (reverse_iterator<const _Elem *>(_Ilist.begin()));
    }

    // TEMPLATE FUNCTIONS crbegin AND crend
    template<class _Container>
    auto inline crbegin(const _Container& _Cont) -> decltype(::std::rbegin(_Cont))
    {	// get beginning of reversed sequence
        return (::std::rbegin(_Cont));
    }

    template<class _Container>
    auto inline crend(const _Container& _Cont) -> decltype(::std::rend(_Cont))
    {	// get end of reversed sequence
        return (::std::rend(_Cont));
    }

}; //namespace std
#endif

template<typename T >
std::unique_ptr<T> copy_unique(const std::unique_ptr<T>& source)
{
    return source ? std::make_unique<T>(*source) : nullptr;
}

//ref: http://stackoverflow.com/questions/14226952/partitioning-batch-chunk-a-container-into-equal-sized-pieces-using-std-algorithm
template<typename Iterator>
void for_each_interval(Iterator from, Iterator to, std::ptrdiff_t partition_size,
                       std::function<void(Iterator, Iterator)> operation) 
{
    if (partition_size > 0) {
        Iterator partition_end = from;
        while (partition_end != to) 
        {
            while (partition_end != to &&
                   std::distance(from, partition_end) < partition_size) 
            {
                ++partition_end;
            }
            operation(from, partition_end);
            from = partition_end;
        }
    }
}
/* See

http://randomascii.wordpress.com/2012/01/11/tricks-with-the-floating-point-format/

for the potential portability problems with the union and bit-fields below.
*/
union Float_t {
    Float_t(F32 num = 0.0f) : f(num) {}
    // Portable extraction of components.
    bool Negative() const { return (i >> 31) != 0; }
    I32 RawMantissa() const { return i & ((1 << 23) - 1); }
    I32 RawExponent() const { return (i >> 23) & 0xFF; }

    I32 i;
    F32 f;
};

union Double_t {
    Double_t(D64 num = 0.0) : d(num) {}
    // Portable extraction of components.
    bool Negative() const { return (i >> 63) != 0; }
    I64 RawMantissa() const { return i & ((1LL << 52) - 1); }
    I64 RawExponent() const { return (i >> 52) & 0x7FF; }

    I64 i;
    D64 d;
};

inline bool AlmostEqualUlpsAndAbs(F32 A, F32 B, F32 maxDiff, I32 maxUlpsDiff) {
    // Check if the numbers are really close -- needed when comparing numbers near zero.
    F32 absDiff = std::fabs(A - B);
    if (absDiff <= maxDiff) {
        return true;
    }

    Float_t uA(A);
    Float_t uB(B);

    // Different signs means they do not match.
    if (uA.Negative() != uB.Negative()) {
        return false;
    }

    // Find the difference in ULPs.
    return (std::abs(uA.i - uB.i) <= maxUlpsDiff);
}

inline bool AlmostEqualUlpsAndAbs(D64 A, D64 B, D64 maxDiff, I32 maxUlpsDiff) {
    // Check if the numbers are really close -- needed when comparing numbers near zero.
    D64 absDiff = std::fabs(A - B);
    if (absDiff <= maxDiff) {
        return true;
    }

    Double_t uA(A);
    Double_t uB(B);

    // Different signs means they do not match.
    if (uA.Negative() != uB.Negative()) {
        return false;
    }

    // Find the difference in ULPs.
    return (std::abs(uA.i - uB.i) <= maxUlpsDiff);
}

inline bool AlmostEqualRelativeAndAbs(F32 A, F32 B, F32 maxDiff, F32 maxRelDiff) {
    // Check if the numbers are really close -- needed when comparing numbers near zero.
    F32 diff = std::fabs(A - B);
    if (diff <= maxDiff) {
        return true;
    }

    A = std::fabs(A);
    B = std::fabs(B);
    F32 largest = (B > A) ? B : A;

    return (diff <= largest * maxRelDiff);
}

inline bool AlmostEqualRelativeAndAbs(D64 A, D64 B, D64 maxDiff, D64 maxRelDiff) {
    // Check if the numbers are really close -- needed when comparing numbers near zero.
    D64 diff = std::fabs(A - B);
    if (diff <= maxDiff) {
        return true;
    }

    A = std::fabs(A);
    B = std::fabs(B);
    D64 largest = (B > A) ? B : A;

    return (diff <= largest * maxRelDiff);
}

#define ACKNOWLEDGE_UNUSED(p) ((void)p)

#if defined(_MSC_VER)
#define _FUNCTION_NAME_AND_SIG_ __FUNCSIG__
#elif defined(__GNUC__)
#define _FUNCTION_NAME_AND_SIG_ __PRETTY_FUNCTION__
#else
#define _FUNCTION_NAME_AND_SIG_ __FUNCTION__
#endif

static const F32 EPSILON_F32 = std::numeric_limits<F32>::epsilon();
static const D64 EPSILON_D64 = std::numeric_limits<D64>::epsilon();

template <typename T>
inline bool IS_VALID_CONTAINER_RANGE(T elementCount, T min, T max) {
    return min >= 0 && max < elementCount;
}
template <typename T, typename U>
inline bool IS_IN_RANGE_INCLUSIVE(T x, U min, U max) {
    return x >= min && x <= max;
}
template <typename T, typename U>
inline bool IS_IN_RANGE_EXCLUSIVE(T x, U min, U max) {
    return x > min && x < max;
}
template <typename T>
inline bool IS_IN_RANGE_INCLUSIVE(T x, T min, T max) {
    return x >= min && x <= max;
}
template <typename T>
inline bool IS_IN_RANGE_EXCLUSIVE(T x, T min, T max) {
    return x > min && x < max;
}
template <typename T>
inline bool IS_ZERO(T X) {
    return X == 0;
}
template <>
inline bool IS_ZERO(F32 X) {
    return (std::fabs(X) < EPSILON_F32);
}
template <>
inline bool IS_ZERO(D64 X) {
    return (std::fabs(X) < EPSILON_D64);
}

template <typename T>
inline bool IS_TOLERANCE(T X, T TOLERANCE) {
    return (std::abs(X) <= TOLERANCE);
}
template <>
inline bool IS_TOLERANCE(F32 X, F32 TOLERANCE) {
    return (std::fabs(X) <= TOLERANCE);
}
template <>
inline bool IS_TOLERANCE(D64 X, D64 TOLERANCE) {
    return (std::fabs(X) <= TOLERANCE);
}

template<typename T, typename U>
inline bool COMPARE_TOLERANCE(T X, U Y, T TOLERANCE) {
    return COMPARE_TOLERANCE(X, static_cast<T>(Y), TOLERANCE);
}

template<typename T>
inline bool COMPARE_TOLERANCE(T X, T Y, T TOLERANCE) {
    return std::fabs(X - Y) <= TOLERANCE;
}

template<>
inline bool COMPARE_TOLERANCE(F32 X, F32 Y, F32 TOLERANCE) {
    return AlmostEqualUlpsAndAbs(X, Y, TOLERANCE, 4);
}

template<>
inline bool COMPARE_TOLERANCE(D64 X, D64 Y, D64 TOLERANCE) {
    return AlmostEqualUlpsAndAbs(X, Y, TOLERANCE, 4);
}

template<typename T, typename U>
inline bool COMPARE(T X, U Y) {
    return COMPARE(X, static_cast<T>(Y));
}

template<typename T>
inline bool COMPARE(T X, T Y) {
    return X == Y;
}

template<>
inline bool COMPARE(F32 X, F32 Y) {
    return COMPARE_TOLERANCE(X, Y, EPSILON_F32);
}

template<>
inline bool COMPARE(D64 X, D64 Y) {
    return COMPARE_TOLERANCE(X, Y, EPSILON_D64);
}

template <typename T>
inline bool IS_GEQUAL(T X, T Y) {
    return X >= Y;
}

template <>
/// should be fast enough as the first condition is almost always true
inline bool IS_GEQUAL(F32 X, F32 Y) {
    return X > Y || COMPARE(X, Y);
}

template <>
inline bool IS_GEQUAL(D64 X, D64 Y) {
    return X > Y || COMPARE(X, Y);
}

template <typename T>
inline bool IS_LEQUAL(T X, T Y) {
    return X <= Y;
}

template <>
inline bool IS_LEQUAL(F32 X, F32 Y) {
    return X < Y || COMPARE(X, Y);
}

template <>
inline bool IS_LEQUAL(D64 X, D64 Y) {
    return X < Y || COMPARE(X, Y);
}

///ref: http://blog.molecular-matters.com/2011/08/12/a-safer-static_cast/#more-120
// base template
template <bool IsFromSigned, bool IsToSigned>
struct safe_static_cast_helper;

// template specialization for casting from an unsigned type into an unsigned type
template <>
struct safe_static_cast_helper<false, false>
{
    template <typename TO, typename FROM>
    static inline TO cast(FROM from)
    {
        assert(IS_IN_RANGE_INCLUSIVE(std::is_enum<FROM>::value 
                                         ? static_cast<U32>(to_underlying_type(from))
                                         : from,
                                     std::numeric_limits<TO>::min(),
                                     std::numeric_limits<TO>::max()) &&
            "Number to cast exceeds numeric limits.");

        return static_cast<TO>(from);
    }
};

// template specialization for casting from an unsigned type into a signed type
template <>
struct safe_static_cast_helper<false, true>
{
    template <typename TO, typename FROM>
    static inline TO cast(FROM from)
    {
        assert(IS_IN_RANGE_INCLUSIVE(from,
                                     std::numeric_limits<TO>::min(),
                                     std::numeric_limits<TO>::max()) &&
            "Number to cast exceeds numeric limits.");

        return static_cast<TO>(from);
    }
};

// template specialization for casting from a signed type into an unsigned type
template <>
struct safe_static_cast_helper<true, false>
{
    template <typename TO, typename FROM>
    static inline TO cast(FROM from)
    {
        // make sure the input is not negative
        assert(from >= 0 && "Number to cast exceeds numeric limits.");

        // assuring a positive input, we can safely cast it into its unsigned type and check the numeric limits
        typedef typename std::make_unsigned<FROM>::type UnsignedFrom;
        assert(IS_IN_RANGE_INCLUSIVE(static_cast<UnsignedFrom>(from),
                                     std::numeric_limits<TO>::min(),
                                     std::numeric_limits<TO>::max()) &&
            "Number to cast exceeds numeric limits.");
        return static_cast<TO>(from);
    }
};

// template specialization for casting from a signed type into a signed type
template <>
struct safe_static_cast_helper<true, true>
{
    template <typename TO, typename FROM>
    static inline TO cast(FROM from)
    {
        assert(IS_IN_RANGE_INCLUSIVE(std::is_enum<FROM>::value ? to_underlying_type(from) : from,
                                     std::numeric_limits<TO>::min(),
                                     std::numeric_limits<TO>::max()) &&
            "Number to cast exceeds numeric limits.");

        return static_cast<TO>(from);
    }
};

#if 0
template <typename TO, typename FROM>
inline TO safe_static_cast(FROM from)
{
/*#if defined(_DEBUG)
    // delegate the call to the proper helper class, depending on the signedness of both types
    return safe_static_cast_helper<std::numeric_limits<FROM>::is_signed,
                                   std::numeric_limits<TO>::is_signed>
           ::cast<TO>(from);
#else*/
    return static_cast<TO>(from);
//#endif
}

template <typename TO>
inline TO safe_static_cast(F32 from)
{
    return static_cast<TO>(from);
}

template <typename TO>
inline TO safe_static_cast(D64 from)
{
    return static_cast<TO>(from);
} 
#endif

/// Performes extra asserts steps (logging, message boxes, etc). 
/// Returns true if the assert should be processed.
bool preAssert(const bool expression, const char* failMessage);
/// It is safe to call evaluate expressions and call functions inside the assert
/// check as it will compile for every build type
FORCE_INLINE bool DIVIDE_ASSERT(const bool expression, const char* failMessage) {
    if (!Config::Build::IS_RELEASE_BUILD) {
        if (preAssert(expression, failMessage)) {
            if (Config::Build::IS_DEBUG_BUILD) {
                assert(expression && failMessage);
            }
        }
    } else {
        ACKNOWLEDGE_UNUSED(failMessage);
    }
    return expression;
}

FORCE_INLINE void DIVIDE_UNEXPECTED_CALL(const char* failMessage = "") {
    DIVIDE_ASSERT(false, failMessage);
}

template <typename... Args>
#if defined(CPP_14_SUPPORT)
[[deprecated("Please use lambda expressions instead!")]]
#endif
auto DELEGATE_BIND(Args&&... args)
    -> decltype(std::bind(std::forward<Args>(args)...)) {
    return std::bind(std::forward<Args>(args)...);
}

template <typename... Args>
#if defined(CPP_14_SUPPORT)
[[deprecated("Please use lambda expressions instead!")]]
#endif
auto DELEGATE_REF(Args&&... args)
    -> decltype(std::ref(std::forward<Args>(args)...)) {
    return std::ref(std::forward<Args>(args)...);
}

template <typename... Args>
#if defined(CPP_14_SUPPORT)
[[deprecated("Please use lambda expressions instead!")]]
#endif
auto DELEGATE_CREF(Args&&... args)
    -> decltype(std::cref(std::forward<Args>(args)...)) {
    return std::cref(std::forward<Args>(args)...);
}


template <typename Ret, typename... Args >
using DELEGATE_CBK = std::function< Ret(Args...) >;

class GUID_DELEGATE_CBK : public GUIDWrapper {
  public:
    GUID_DELEGATE_CBK(const DELEGATE_CBK<void>& cbk)
        : GUIDWrapper(),
          _callback(cbk)
    {
    }

    DELEGATE_CBK<void> _callback;
};

U32 HARDWARE_THREAD_COUNT();

template<typename T, typename U>
constexpr void assert_type(const U& value) {
    static_assert(std::is_same<U, T>::value, "value type not satisfied");
}

};  // namespace Divide

void* malloc_aligned(const size_t size, size_t alignment);
void  malloc_free(void*& ptr);

void* operator new[](size_t size, const char* pName, Divide::I32 flags,
                     Divide::U32 debugFlags, const char* file,
                     Divide::I32 line);

void operator delete[](void* ptr, const char* pName, Divide::I32 flags,
                       Divide::U32 debugFlags, const char* file,
                       Divide::I32 line);

void* operator new[](size_t size, size_t alignment, size_t alignmentOffset,
                     const char* pName, Divide::I32 flags,
                     Divide::U32 debugFlags, const char* file,
                     Divide::I32 line);

void operator delete[](void* ptr, size_t alignment, size_t alignmentOffset,
                       const char* pName, Divide::I32 flags,
                       Divide::U32 debugFlags, const char* file,
                       Divide::I32 line);

// EASTL also wants us to define this (see string.h line 197)
Divide::I32 Vsnprintf8(char* pDestination, size_t n, const char* pFormat,
                       va_list arguments);

#if !defined(_DEBUG)
#define MemoryManager_NEW new
#else
#if defined(DEBUG_EXTERNAL_ALLOCATIONS)
void* operator new(size_t size);
void operator delete(void* p) noexcept;
void* operator new[](size_t size);
void operator delete[](void* p) noexcept;
#endif

void* operator new(size_t size, const char* zFile, size_t nLine);
void operator delete(void* ptr, const char* zFile, size_t nLine);
void* operator new[](size_t size, const char* zFile, size_t nLine);
void operator delete[](void* ptr, const char* zFile, size_t nLine);

#define MemoryManager_NEW new (__FILE__, __LINE__)
#endif

namespace Divide {
namespace MemoryManager {

template <typename T>
inline void SAFE_FREE(T*& ptr) {
    if (ptr) {
        free(ptr);
        ptr = nullptr;
    }
}

/// Deletes and nullifies the specified pointer
template <typename T>
inline void DELETE(T*& ptr) {
    delete ptr;
    ptr = nullptr;
}
   
#define SET_DELETE_FRIEND \
    template <typename T> \
    friend void MemoryManager::DELETE(T*& ptr); \

/// Deletes and nullifies the specified pointer
template <typename T>
inline void SAFE_DELETE(T*& ptr) {
    DIVIDE_ASSERT(ptr != nullptr, "SAFE_DELETE: null pointer received");

    delete ptr;
    ptr = nullptr;
}
#define SET_SAFE_DELETE_FRIEND \
    template <typename T>      \
    friend void MemoryManager::DELETE(T*& ptr);

/// Deletes and nullifies the specified array pointer
template <typename T>
inline void DELETE_ARRAY(T*& ptr) {
    delete[] ptr;
    ptr = nullptr;
}
#define SET_DELETE_ARRAY_FRIEND \
    template <typename T>       \
    friend void MemoryManager::DELETE_ARRAY(T*& ptr);

/// Deletes and nullifies the specified array pointer
template <typename T>
inline void SAFE_DELETE_ARRAY(T*& ptr) {
    DIVIDE_ASSERT(ptr != nullptr, "SAFE_DELETE_ARRAY: null pointer received");

    delete[] ptr;
    ptr = nullptr;
}
#define SET_SAFE_DELETE_ARRAY_FRIEND \
    template <typename T>            \
    friend void MemoryManager::DELETE_ARRAY(T*& ptr);

/// Deletes and nullifies the specified pointer. Returns "false" if the pointer
/// was already null
template <typename T>
inline bool DELETE_CHECK(T*& ptr) {
    if (ptr == nullptr) {
        return false;
    }

    delete ptr;
    ptr = nullptr;

    return true;
}
#define SET_DELETE_CHECK_FRIEND \
    template <typename T>       \
    friend void MemoryManager::DELETE_CHECK(T*& ptr);

/// Deletes and nullifies the specified array pointer. Returns "false" if the
/// pointer was already null
template <typename T>
inline bool DELETE_ARRAY_CHECK(T*& ptr) {
    if (ptr == nullptr) {
        return false;
    }

    delete[] ptr;
    ptr = nullptr;

    return true;
}

#define SET_DELETE_ARRAY_CHECK_FRIEND \
    template <typename T>             \
    friend void MemoryManager::DELETE_ARRAY_CHECK(T*& ptr);
/// Deletes every element from the vector and clears it at the end
template <typename T>
inline void DELETE_VECTOR(vectorImpl<T*>& vec) {
    if (!vec.empty()) {
        for (T* iter : vec) {
            delete iter;
        }
        vec.clear();
    }
}
#define SET_DELETE_VECTOR_FRIEND \
    template <typename T>        \
    friend void MemoryManager::DELETE_VECTOR(vectorImpl<T*>& vec);

/// Deletes every element from the map and clears it at the end
template <typename K, typename V, typename HashFun = hashAlg::hash<K> >
inline void DELETE_HASHMAP(hashMapImpl<K, V, HashFun>& map) {
    if (!map.empty()) {
        for (typename hashMapImpl<K, V, HashFun>::value_type iter : map) {
            delete iter.second;
        }
        map.clear();
    }
}
#define SET_DELETE_HASHMAP_FRIEND                                           \
    template <typename K, typename V, typename HashFun = hashAlg::hash<K> > \
    friend void MemoryManager::DELETE_HASHMAP(                              \
        hashMapImpl<K, V, HashFun>& map);

/// Deletes the object pointed to by "OLD" and redirects that pointer to the
/// object pointed by "NEW"
/// "NEW" must be a derived (or same) class of OLD
template <typename Base, typename Derived>
inline void SAFE_UPDATE(Base*& OLD, Derived* const NEW) {
    static_assert(std::is_base_of<Base, Derived>::value,
                  "SAFE_UPDATE error: New must be a descendant of Old");

    delete OLD;
    OLD = NEW;
}
#define SET_SAFE_UPDATE_FRIEND                 \
    template <typename Base, typename Derived> \
    friend void MemoryManager::SAFE_UPDATE(Base*& OLD, Derived* const NEW);

};  // namespace MemoryManager


bool createFileIfNotExist(const char* file);

/// Wrapper that allows usage of atomic variables in containers
/// Copy is not atomic! (e.g. push/pop from containers is not threadsafe!)
/// ref: http://stackoverflow.com/questions/13193484/how-to-declare-a-vector-of-atomic-in-c
template <typename T>
struct AtomicWrapper
{
    std::atomic<T> _a;

    AtomicWrapper() : _a()
    {
    }

    AtomicWrapper(const std::atomic<T> &a) :_a(a.load())
    {
    }

    AtomicWrapper(const AtomicWrapper &other) : _a(other._a.load())
    {
    }

    AtomicWrapper &operator=(const AtomicWrapper &other)
    {
        _a.store(other._a.load());
        return *this;
    }

    AtomicWrapper &operator=(const T &value)
    {
        _a.store(value);
        return *this;
    }

    bool operator==(const T &value) const
    {
        return _a == value;
    }
};
};  // namespace Divide

#endif

#if defined(USE_CUSTOM_MEMORY_ALLOCATORS)
#if !defined(AUTOMATIC_XALLOCATOR_INIT_DESTROY)
#define AUTOMATIC_XALLOCATOR_INIT_DESTROY
#endif
// Modify the allocator values to TIGHTLY fit memory requirments
// The application will assert if it requires more allocators than the specified nubmer
// xallocator.cpp contains the number of allocators available
#include <Allocator/Allocator.h>

#define USE_CUSTOM_ALLOCATOR DECLARE_ALLOCATOR
#define IMPLEMENT_CUSTOM_ALLOCATOR(class, objects, memory) IMPLEMENT_ALLOCATOR(class, objects, memory)
#else
#define USE_CUSTOM_ALLOCATOR
#define IMPLEMENT_CUSTOM_ALLOCATOR(class, objects, memory)
#endif

Commits for Divide-Framework/trunk/Source Code/Platform/Headers/PlatformDefines.h

Diff revisions: vs.
Revision Author Commited Message
842 Diff Diff IonutCava picture IonutCava Wed 01 Feb, 2017 17:25:15 +0000

[IonutCava]
- Start to implement scripting support via ChaiScript: http://chaiscript.com/
- Cleanup DELEGATE_CBK alias

839 Diff Diff IonutCava picture IonutCava Tue 31 Jan, 2017 17:28:13 +0000

[IonutCava]
- Add simplefilewatcher libary: https://github.com/jameswynn/simplefilewatcher
- Use simplefilewatcher to automatically recompile shaders after save without restarting the app!
— Shaders can now be edited on the fly with automatic rebuild if they used one of the modified atoms.

837 Diff Diff IonutCava picture IonutCava Sun 29 Jan, 2017 15:45:58 +0000

[IonutCava]
- File system updates

836 Diff Diff IonutCava picture IonutCava Fri 27 Jan, 2017 14:59:56 +0000

[IonutCava]
- Update copyright notice

832 Diff Diff IonutCava picture IonutCava Thu 26 Jan, 2017 17:23:11 +0000

[IonutCava]
- More path related work
- Initial code to centralize file I/O (does not compile yet)

830 Diff Diff IonutCava picture IonutCava Wed 25 Jan, 2017 17:29:44 +0000

[IonutCava]
- Add a new Platform element: File
— Move all predefined paths to FileManagement System
- Split MathHelper into MathHelper and StringHelper

828 Diff Diff IonutCava picture IonutCava Mon 23 Jan, 2017 17:19:22 +0000

[Ionut]
- XML loading/saving cleanup PART I

827 Diff Diff IonutCava picture IonutCava Sun 22 Jan, 2017 21:59:36 +0000

[IonutCava]
- ShaderBuffers now decide heuristically if they get persistently mapped or not (depends on size. Current limit is 512Kb for subData calls.
- Separate visible node command generation into 2 steps: onRender and getDrawPackage. onRender allows the creation of parallel tasks that should finish by the time the second call, getDrawPackage reaches the same node
- Update ParticleEmitter to take into account multiple players and increase parallelism at the cost of memory consumption and complexity.
- Add a default bounding box for Players (add extents to SceneTransform nodes)
- All buffers (ShaderBuffer, d3dConstantBuffer, glUniformBuffer, glBufferImpl, glGenericBuffer, etc) use BufferParams for creation.
— Constructor and create calls have been merged together

807 Diff Diff IonutCava picture IonutCava Mon 09 Jan, 2017 17:06:26 +0000

[IonutCava]
- Split PlatformDefines.h into 2. Move data type defines to PlatformDataTypes.h
- Continue to improve velocity map calculation
- Remove “destroy()” calls from most classes. Attempt to move as many classes to the RAII system.

805 IonutCava picture IonutCava Fri 02 Dec, 2016 16:05:59 +0000

[IonutCava]
- Singleton elimination update Part I.I: Correct Part I
— Small corrections to previous commit: Fix all asserts, memory leaks and errors that appeared during the following test: Start app -> Load War Scene -> Return to Default Scene -> Quit