-
Notifications
You must be signed in to change notification settings - Fork 271
/
Copy pathdatamodel.cpp
2466 lines (2038 loc) · 69.2 KB
/
datamodel.cpp
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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#include "datamodel/idatamodel.h"
#include "datamodel/dmattributevar.h"
#include "datamodel.h"
#include "dependencygraph.h"
#include "dmattributeinternal.h"
#include "dmserializerkeyvalues.h"
#include "dmserializerkeyvalues2.h"
#include "dmserializerbinary.h"
#include "undomanager.h"
#include "clipboardmanager.h"
#include "DmElementFramework.h"
#include "vstdlib/iprocessutils.h"
#include "tier0/dbg.h"
#include "tier1/utlvector.h"
#include "tier1/utlqueue.h"
#include "tier1/utlbuffer.h"
#include "tier2/utlstreambuffer.h"
#include "tier2/fileutils.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
class CUtlBuffer;
class IDmEditMessage;
class KeyValues;
#define UNNAMED_ELEMENT_NAME "unnamed"
//-----------------------------------------------------------------------------
// Class factory for the default element
//-----------------------------------------------------------------------------
class CDmElementFactoryDefault : public IDmElementFactory
{
public:
// Creation, destruction
virtual CDmElement* Create( DmElementHandle_t handle, const char *pElementType, const char *pElementName, DmFileId_t fileid, const DmObjectId_t &id )
{
return new CDmElement( handle, pElementType, id, pElementName, fileid );
}
virtual void Destroy( DmElementHandle_t hElement )
{
if ( hElement != DMELEMENT_HANDLE_INVALID )
{
CDmElement *pElement = g_pDataModel->GetElement( hElement );
delete static_cast<CDmElement*>( pElement );
}
}
};
static CDmElementFactoryDefault s_DefaultElementFactory;
//-----------------------------------------------------------------------------
// Singleton instance
//-----------------------------------------------------------------------------
static CDataModel g_DataModel;
CDataModel *g_pDataModelImp = &g_DataModel;
IDataModel *g_pDataModel = &g_DataModel;
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CDataModel::CDataModel() :
m_elementIds( 4096 ),
m_unloadedIdElementMap( 16, 0, 0, ElementIdHandlePair_t::Compare, ElementIdHandlePair_t::HashKey )
{
m_pDefaultFactory = &s_DefaultElementFactory;
m_bUnableToSetDefaultFactory = false;
m_bOnlyCreateUntypedElements = false;
m_bUnableToCreateOnlyUntypedElements = false;
m_pKeyvaluesCallbackInterface = NULL;
m_nElementsAllocatedSoFar = 0;
m_nMaxNumberOfElements = 0;
m_bIsUnserializing = false;
m_bDeleteOrphanedElements = false;
}
CDataModel::~CDataModel()
{
m_UndoMgr.WipeUndo();
if ( GetAllocatedElementCount() > 0 )
{
Warning( "Leaking %i elements\n", GetAllocatedElementCount() );
}
}
//-----------------------------------------------------------------------------
// Methods of IAppSystem
//-----------------------------------------------------------------------------
bool CDataModel::Connect( CreateInterfaceFn factory )
{
if ( !BaseClass::Connect( factory ) )
return false;
if ( !factory( FILESYSTEM_INTERFACE_VERSION, NULL ) )
{
Warning( "DataModel needs the file system to function" );
return false;
}
return true;
}
void *CDataModel::QueryInterface( const char *pInterfaceName )
{
if ( !V_strcmp( pInterfaceName, VDATAMODEL_INTERFACE_VERSION ) )
return (IDataModel*)this;
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *databasePath -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
InitReturnVal_t CDataModel::Init( )
{
InitReturnVal_t nRetVal = BaseClass::Init();
if ( nRetVal != INIT_OK )
return nRetVal;
InstallKeyValuesSerializer( this );
InstallKeyValues2Serializer( this );
InstallBinarySerializer( this );
m_UndoMgr.SetUndoDepth( 256 );
return INIT_OK;
}
//#define _ELEMENT_HISTOGRAM_
#ifdef _ELEMENT_HISTOGRAM_
CUtlMap< UtlSymId_t, int > g_typeHistogram( 0, 100, DefLessFunc( UtlSymId_t ) );
#endif
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CDataModel::Shutdown()
{
#ifdef _ELEMENT_HISTOGRAM_
Msg( "element type histogram for %d elements allocated so far:\n", GetElementsAllocatedSoFar() );
for ( int i = g_typeHistogram.FirstInorder(); g_typeHistogram.IsValidIndex( i ); i = g_typeHistogram.NextInorder( i ) )
{
Msg( "%d\t%s\n", g_typeHistogram.Element( i ), GetString( g_typeHistogram.Key( i ) ) );
}
Msg( "\n" );
#endif
int c = GetAllocatedElementCount();
if ( c > 0 )
{
Warning( "CDataModel: %i elements left in memory!!!\n", c );
}
m_Factories.Purge();
m_Serializers.Purge();
m_UndoMgr.Shutdown();
BaseClass::Shutdown();
}
//-----------------------------------------------------------------------------
// Sets the undo context size
//-----------------------------------------------------------------------------
void CDataModel::SetUndoDepth( int nSize )
{
m_UndoMgr.SetUndoDepth( nSize );
}
//-----------------------------------------------------------------------------
// force creation of untyped elements, ignoring type
//-----------------------------------------------------------------------------
void CDataModel::OnlyCreateUntypedElements( bool bEnable )
{
if ( m_bUnableToCreateOnlyUntypedElements )
{
Assert( 0 );
return;
}
m_bOnlyCreateUntypedElements = bEnable;
}
int CDataModel::GetElementsAllocatedSoFar()
{
return m_nElementsAllocatedSoFar;
}
int CDataModel::GetMaxNumberOfElements()
{
return m_nMaxNumberOfElements;
}
int CDataModel::GetAllocatedAttributeCount()
{
return ::GetAllocatedAttributeCount();
}
//-----------------------------------------------------------------------------
// Returns the total number of elements allocated at the moment
//-----------------------------------------------------------------------------
int CDataModel::GetAllocatedElementCount()
{
return ( int )m_Handles.GetValidHandleCount();
}
DmElementHandle_t CDataModel::FirstAllocatedElement()
{
int nHandles = ( int )m_Handles.GetHandleCount();
for ( int i = 0; i < nHandles; ++i )
{
DmElementHandle_t hElement = ( DmElementHandle_t )m_Handles.GetHandleFromIndex( i );
if ( hElement != DMELEMENT_HANDLE_INVALID )
return hElement;
}
return DMELEMENT_HANDLE_INVALID;
}
DmElementHandle_t CDataModel::NextAllocatedElement( DmElementHandle_t hElement )
{
int nHandles = ( int )m_Handles.GetHandleCount();
for ( int i = m_Handles.GetIndexFromHandle( hElement ) + 1; i < nHandles; ++i )
{
DmElementHandle_t hElementCur = ( DmElementHandle_t )m_Handles.GetHandleFromIndex( i );
if ( hElementCur != DMELEMENT_HANDLE_INVALID )
return hElementCur;
}
return DMELEMENT_HANDLE_INVALID;
}
//-----------------------------------------------------------------------------
// estimate memory overhead
//-----------------------------------------------------------------------------
int CDataModel::EstimateMemoryOverhead() const
{
int nHandlesOverhead = sizeof( int ) + sizeof( CDmElement* ); // m_Handles
int nElementIdsOverhead = sizeof( DmElementHandle_t ); // this also has a 80k static overhead, since hash tables can't grow
return nHandlesOverhead + nElementIdsOverhead;
}
static bool HandleCompare( const DmElementHandle_t & a, const DmElementHandle_t &b )
{
return a == b;
}
static unsigned int HandleHash( const DmElementHandle_t &h )
{
return (unsigned int)h;
}
int CDataModel::EstimateMemoryUsage( DmElementHandle_t hElement, TraversalDepth_t depth )
{
CUtlHash< DmElementHandle_t > visited( 1024, 0, 0, HandleCompare, HandleHash );
CDmElement *pElement = m_Handles.GetHandle( hElement );
if ( !pElement )
return 0;
return CDmeElementAccessor::EstimateMemoryUsage( pElement, visited, depth, NULL );
}
//-----------------------------------------------------------------------------
// Displays stats for datamodel
//-----------------------------------------------------------------------------
struct DmMemoryInfo_t
{
int m_nCount;
int m_nSize;
int m_pCategories[ MEMORY_CATEGORY_COUNT ];
};
struct DmMemorySortInfo_t
{
int m_nIndex;
int m_nTotalSize;
};
int DmMemorySortFunc( const void * lhs, const void * rhs )
{
DmMemorySortInfo_t &info1 = *(DmMemorySortInfo_t*)lhs;
DmMemorySortInfo_t &info2 = *(DmMemorySortInfo_t*)rhs;
return info1.m_nTotalSize - info2.m_nTotalSize;
}
void CDataModel::DisplayMemoryStats( )
{
CUtlMap< UtlSymId_t, DmMemoryInfo_t > typeHistogram( 0, 100, DefLessFunc( UtlSymId_t ) );
CUtlHash< DmElementHandle_t > visited( 1024, 0, 0, HandleCompare, HandleHash );
int c = (int)m_Handles.GetHandleCount();
for ( int i = 0; i < c; ++i )
{
DmElementHandle_t h = (DmElementHandle_t)m_Handles.GetHandleFromIndex( i );
if ( !m_Handles.IsHandleValid( h ) )
continue;
CDmElement *pElement = m_Handles.GetHandle( h );
if ( !pElement )
continue;
unsigned short j = typeHistogram.Find( pElement->GetType() );
if ( !typeHistogram.IsValidIndex( j ) )
{
j = typeHistogram.Insert( pElement->GetType() );
typeHistogram[j].m_nCount = 0;
typeHistogram[j].m_nSize = 0;
memset( typeHistogram[j].m_pCategories, 0, sizeof(typeHistogram[j].m_pCategories) );
}
int nMemory = CDmeElementAccessor::EstimateMemoryUsage( pElement, visited, TD_NONE, typeHistogram[j].m_pCategories );
++typeHistogram[j].m_nCount;
typeHistogram[j].m_nSize += nMemory;
}
// Sort
DmMemorySortInfo_t* pSortInfo = (DmMemorySortInfo_t*)_alloca( typeHistogram.Count() * sizeof(DmMemorySortInfo_t) );
int nCount = 0;
for ( int i = typeHistogram.FirstInorder(); typeHistogram.IsValidIndex( i ); i = typeHistogram.NextInorder( i ) )
{
pSortInfo[nCount].m_nIndex = i;
pSortInfo[nCount].m_nTotalSize = typeHistogram.Element( i ).m_nSize;
++nCount;
}
qsort( pSortInfo, nCount, sizeof(DmMemorySortInfo_t), DmMemorySortFunc );
int pTotals[ MEMORY_CATEGORY_COUNT ];
int nTotalSize = 0;
int nTotalCount = 0;
int nTotalData = 0;
memset( pTotals, 0, sizeof(pTotals) );
ConMsg( "Dm Memory usage: type\t\t\t\tcount\ttotalsize\twastage %%\touter\t\tinner\t\tdatamodel\trefs\t\ttree\t\tatts\t\tdata\t(att count)\n" );
for ( int i = 0; i < nCount; ++i )
{
const DmMemoryInfo_t& info = typeHistogram.Element( pSortInfo[i].m_nIndex );
float flPercentOverhead = 1.0f - ( ( info.m_nSize != 0 ) ? ( (float)info.m_pCategories[MEMORY_CATEGORY_ATTRIBUTE_DATA] / (float)info.m_nSize ) : 0.0f );
flPercentOverhead *= 100.0f;
ConMsg( "%-40s\t%6d\t%9d\t\t%5.2f", GetString( typeHistogram.Key( pSortInfo[i].m_nIndex ) ),
info.m_nCount, info.m_nSize, flPercentOverhead );
int nTotal = 0;
for ( int j = 0; j < MEMORY_CATEGORY_COUNT; ++j )
{
ConColorMsg( Color( 255, 192, 0, 255 ), "\t%8d", info.m_pCategories[j] );
if ( j != MEMORY_CATEGORY_ATTRIBUTE_COUNT )
{
nTotal += info.m_pCategories[j];
}
pTotals[j] += info.m_pCategories[j];
}
ConMsg( "\n" );
Assert( nTotal == info.m_nSize );
nTotalSize += info.m_nSize;
nTotalCount += info.m_nCount;
nTotalData += info.m_pCategories[MEMORY_CATEGORY_ATTRIBUTE_DATA];
}
ConMsg( "\n" );
ConMsg( "%-40s\t%6d\t%9d\t\t%5.2f", "Totals", nTotalCount, nTotalSize, 100.0f * ( 1.0f - (float)nTotalData / (float)nTotalSize ) );
for ( int j = 0; j < MEMORY_CATEGORY_COUNT; ++j )
{
ConColorMsg( Color( 255, 192, 0, 255 ), "\t%8d", pTotals[j] );
}
ConMsg( "\n" );
}
//-----------------------------------------------------------------------------
// Global symbol table for the datamodel system
//-----------------------------------------------------------------------------
UtlSymId_t CDataModel::GetSymbol( const char *pString )
{
return m_SymbolTable.AddString( pString );
}
const char * CDataModel::GetString( UtlSymId_t sym ) const
{
return m_SymbolTable.String( sym );
}
unsigned short CDataModel::GetSymbolCount() const // this can't ever overflow a ushort, since UtlSymId_t is a ushort, and one of its entries is invalid (0xffff)
{
return m_SymbolTable.GetNumStrings(); // this is only useful because symbols are never removed
}
//-----------------------------------------------------------------------------
// file format methods
//-----------------------------------------------------------------------------
const char* CDataModel::GetFormatExtension( const char *pFormatName )
{
IDmFormatUpdater *pUpdater = FindFormatUpdater( pFormatName );
Assert( pUpdater );
if ( !pUpdater )
return NULL;
return pUpdater->GetExtension();
}
const char* CDataModel::GetFormatDescription( const char *pFormatName )
{
IDmFormatUpdater *pUpdater = FindFormatUpdater( pFormatName );
Assert( pUpdater );
if ( !pUpdater )
return NULL;
return pUpdater->GetDescription();
}
int CDataModel::GetFormatCount() const
{
return m_FormatUpdaters.Count();
}
const char* CDataModel::GetFormatName( int i ) const
{
IDmFormatUpdater *pUpdater = m_FormatUpdaters[ i ];
if ( !pUpdater )
return NULL;
return pUpdater->GetName();
}
const char *CDataModel::GetDefaultEncoding( const char *pFormatName )
{
IDmFormatUpdater *pUpdater = FindFormatUpdater( pFormatName );
if ( !pUpdater )
return NULL;
return pUpdater->GetDefaultEncoding();
}
//-----------------------------------------------------------------------------
// Adds various serializers
//-----------------------------------------------------------------------------
void CDataModel::AddSerializer( IDmSerializer *pSerializer )
{
Assert( Q_strlen( pSerializer->GetName() ) <= DMX_MAX_FORMAT_NAME_MAX_LENGTH );
if ( FindSerializer( pSerializer->GetName() ) )
{
Warning("Attempted to add two serializers with the same file encoding (%s)!\n", pSerializer->GetName() );
return;
}
m_Serializers.AddToTail( pSerializer );
}
void CDataModel::AddLegacyUpdater( IDmLegacyUpdater *pUpdater )
{
Assert( Q_strlen( pUpdater->GetName() ) <= DMX_MAX_FORMAT_NAME_MAX_LENGTH );
if ( FindLegacyUpdater( pUpdater->GetName() ) )
{
Warning( "Attempted to add two legacy updaters with the same file format (%s)!\n", pUpdater->GetName() );
return;
}
m_LegacyUpdaters.AddToTail( pUpdater );
}
void CDataModel::AddFormatUpdater( IDmFormatUpdater *pUpdater )
{
Assert( Q_strlen( pUpdater->GetName() ) <= DMX_MAX_FORMAT_NAME_MAX_LENGTH );
if ( FindFormatUpdater( pUpdater->GetName() ) )
{
Warning( "Attempted to add two format updaters with the same file format (%s)!\n", pUpdater->GetName() );
return;
}
m_FormatUpdaters.AddToTail( pUpdater );
}
//-----------------------------------------------------------------------------
// encoding-related methods
//-----------------------------------------------------------------------------
int CDataModel::GetEncodingCount() const
{
return m_Serializers.Count();
}
const char *CDataModel::GetEncodingName( int i ) const
{
return m_Serializers[ i ]->GetName();
}
bool CDataModel::IsEncodingBinary( const char *pEncodingName ) const
{
IDmSerializer *pSerializer = FindSerializer( pEncodingName );
if ( !pSerializer )
{
Warning("Serialize: File encoding %s is undefined!\n", pEncodingName );
return false;
}
return pSerializer->IsBinaryFormat();
}
bool CDataModel::DoesEncodingStoreVersionInFile( const char *pEncodingName ) const
{
IDmSerializer *pSerializer = FindSerializer( pEncodingName );
if ( !pSerializer )
{
Warning("Serialize: File encoding %s is undefined!\n", pEncodingName );
return false;
}
return pSerializer->StoresVersionInFile();
}
IDmSerializer* CDataModel::FindSerializer( const char *pEncodingName ) const
{
int nSerializers = m_Serializers.Count();
for ( int i = 0; i < nSerializers; ++i )
{
IDmSerializer *pSerializer = m_Serializers[ i ];
Assert( pSerializer );
if ( !pSerializer )
continue;
if ( !V_strcmp( pEncodingName, pSerializer->GetName() ) )
return pSerializer;
}
return NULL;
}
IDmLegacyUpdater* CDataModel::FindLegacyUpdater( const char *pLegacyFormatName ) const
{
int nUpdaters = m_LegacyUpdaters.Count();
for ( int i = 0; i < nUpdaters; ++i )
{
IDmLegacyUpdater *pUpdater = m_LegacyUpdaters[ i ];
Assert( pUpdater );
if ( !pUpdater )
continue;
if ( !V_strcmp( pLegacyFormatName, pUpdater->GetName() ) )
return pUpdater;
}
return NULL;
}
IDmFormatUpdater* CDataModel::FindFormatUpdater( const char *pFormatName ) const
{
int nUpdaters = m_FormatUpdaters.Count();
for ( int i = 0; i < nUpdaters; ++i )
{
IDmFormatUpdater *pUpdater = m_FormatUpdaters[ i ];
Assert( pUpdater );
if ( !pUpdater )
continue;
if ( !V_strcmp( pFormatName, pUpdater->GetName() ) )
return pUpdater;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Sets the name of the DME element to create in keyvalues serialization
//-----------------------------------------------------------------------------
void CDataModel::SetKeyValuesElementCallback( IElementForKeyValueCallback *pCallbackInterface )
{
m_pKeyvaluesCallbackInterface = pCallbackInterface;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CDataModel::GetKeyValuesElementName( const char *pszKeyName, int iNestingLevel )
{
if ( m_pKeyvaluesCallbackInterface )
return m_pKeyvaluesCallbackInterface->GetElementForKeyValue( pszKeyName, iNestingLevel );
return NULL;
}
//-----------------------------------------------------------------------------
// For serialization, set the delimiter rules
//-----------------------------------------------------------------------------
void CDataModel::SetSerializationDelimiter( CUtlCharConversion *pConv )
{
::SetSerializationDelimiter( pConv );
}
void CDataModel::SetSerializationArrayDelimiter( const char *pDelimiter )
{
::SetSerializationArrayDelimiter( pDelimiter );
}
bool CDataModel::SaveToFile( char const *pFileName, char const *pPathID, const char *pEncodingName, const char *pFormatName, CDmElement *pRoot )
{
// NOTE: This guarantees full path names for pathids
char pFullPath[ MAX_PATH ];
if ( !GenerateFullPath( pFileName, pPathID, pFullPath, sizeof( pFullPath ) ) )
{
Warning( "CDataModel: Unable to generate full path for file %s\n", pFileName );
return false;
}
if ( g_pFullFileSystem->FileExists( pFullPath, pPathID ) )
{
if ( !g_pFullFileSystem->IsFileWritable( pFullPath, pPathID ) )
{
Warning( "CDataModel: Unable to overwrite readonly file %s\n", pFullPath );
return false;
}
}
bool bIsBinary = IsEncodingBinary( pEncodingName );
CUtlStreamBuffer buf( pFullPath, pPathID, bIsBinary ? 0 : CUtlBuffer::TEXT_BUFFER, true );
if ( !buf.IsValid() )
{
Warning( "CDataModel: Unable to open file \"%s\"\n", pFullPath );
return false;
}
return Serialize( buf, pEncodingName, pFormatName, pRoot->GetHandle() );
}
DmFileId_t CDataModel::RestoreFromFile( char const *pFileName, char const *pPathID, const char *pFormatHint, CDmElement **ppRoot, DmConflictResolution_t idConflictResolution /*= CR_DELETE_NEW*/, DmxHeader_t *pHeaderOut /*= NULL*/ )
{
// NOTE: This guarantees full path names for pathids
char pFullPath[ MAX_PATH ];
if ( !GenerateFullPath( pFileName, pPathID, pFullPath, sizeof( pFullPath ) ) )
{
Warning( "CDataModel: Unable to generate full path for file %s\n", pFileName );
return DMFILEID_INVALID;
}
char *pTemp = (char*)_alloca( DMX_MAX_HEADER_LENGTH + 1 );
CUtlBuffer typeBuf( pTemp, DMX_MAX_HEADER_LENGTH );
if ( !g_pFullFileSystem->ReadFile( pFullPath, pPathID, typeBuf, DMX_MAX_HEADER_LENGTH ) )
{
Warning( "CDataModel: Unable to open file %s\n", pFullPath );
return DMFILEID_INVALID;
}
DmxHeader_t _header;
DmxHeader_t *pHeader = pHeaderOut ? pHeaderOut : &_header;
bool bSuccess = ReadDMXHeader( typeBuf, pHeader );
if ( !bSuccess )
{
if ( !pFormatHint )
{
Warning( "CDataModel: Unable to determine DMX format for file %s\n", pFullPath );
return DMFILEID_INVALID;
}
if ( !IsValidNonDMXFormat( pFormatHint ) )
{
Warning( "CDataModel: Invalid DMX format hint '%s' for file %s\n", pFormatHint, pFullPath );
return DMFILEID_INVALID;
}
// non-dmx file importers don't have versions or encodings, just formats
V_strncpy( pHeader->encodingName, pFormatHint, sizeof( pHeader->encodingName ) );
V_strncpy( pHeader->formatName, pFormatHint, sizeof( pHeader->formatName ) );
}
bool bIsBinary = IsEncodingBinary( pHeader->encodingName );
CUtlStreamBuffer buf( pFullPath, pPathID, bIsBinary ? CUtlBuffer::READ_ONLY : CUtlBuffer::READ_ONLY | CUtlBuffer::TEXT_BUFFER );
if ( !buf.IsValid() )
{
Warning( "CDataModel: Unable to open file '%s'\n", pFullPath );
return DMFILEID_INVALID;
}
DmElementHandle_t hRootElement;
if ( !Unserialize( buf, pHeader->encodingName, pHeader->formatName, pFormatHint, pFullPath, idConflictResolution, hRootElement ) )
return DMFILEID_INVALID;
*ppRoot = g_pDataModel->GetElement( hRootElement );
DmFileId_t fileid = g_pDataModel->GetFileId( pFullPath );
Assert( fileid != DMFILEID_INVALID );
return fileid;
}
//-----------------------------------------------------------------------------
// Serialization of a element tree into a utlbuffer
//-----------------------------------------------------------------------------
bool CDataModel::Serialize( CUtlBuffer &outBuf, const char *pEncodingName, const char *pFormatName, DmElementHandle_t hRoot )
{
// Find a serializer appropriate for the file format.
IDmSerializer *pSerializer = FindSerializer( pEncodingName );
if ( !pSerializer )
{
Warning("Serialize: File encoding '%s' is undefined!\n", pEncodingName );
return false;
}
// Ensure the utlbuffer is in the appropriate format (binary/text)
bool bIsText = outBuf.IsText();
bool bIsCRLF = outBuf.ContainsCRLF();
CUtlBuffer outTextBuffer( 0, 0, CUtlBuffer::TEXT_BUFFER );
CUtlBuffer *pActualOutBuf = &outBuf;
if ( pSerializer->IsBinaryFormat() )
{
if ( outBuf.IsText() )
{
if ( !outBuf.ContainsCRLF() )
{
Warning( "Serialize: Format %s expects to be written to a binary format, but the buffer is a text-format buffer\n", pFormatName );
return false;
}
outBuf.SetBufferType( false, false );
}
}
else
{
// If we want text, but the binbuf is binary; recast it to a text buffer w/ CRLF
if ( !outBuf.IsText() )
{
outBuf.SetBufferType( true, true );
}
if ( outBuf.ContainsCRLF() )
{
// If we want text, but the binbuf expects CRLF, then we must do a conversion pass
pActualOutBuf = &outTextBuffer;
}
}
if ( pSerializer->StoresVersionInFile() )
{
// Write the format name into the file using XML format so that
// 3rd-party XML readers can read the file without fail
pActualOutBuf->Printf( "%s encoding %s %d format %s %d %s\n",
DMX_VERSION_STARTING_TOKEN, pEncodingName, pSerializer->GetCurrentVersion(),
pFormatName, GetCurrentFormatVersion( pFormatName ), DMX_VERSION_ENDING_TOKEN );
}
// Now write the file using the appropriate format
CDmElement *pRoot = GetElement( hRoot );
bool bOk = pSerializer->Serialize( *pActualOutBuf, pRoot );
if ( bOk )
{
if ( pActualOutBuf == &outTextBuffer )
{
outTextBuffer.ConvertCRLF( outBuf );
}
}
outBuf.SetBufferType( bIsText, bIsCRLF );
return bOk;
}
//-----------------------------------------------------------------------------
// Read the header, return the version (or false if it's not a DMX file)
//-----------------------------------------------------------------------------
bool CDataModel::ReadDMXHeader( CUtlBuffer &inBuf, DmxHeader_t *pHeader ) const
{
Assert( pHeader );
if ( !pHeader )
return false;
// Make the buffer capable of being read as text
bool bIsText = inBuf.IsText();
bool bHasCRLF = inBuf.ContainsCRLF();
inBuf.SetBufferType( true, !bIsText || bHasCRLF );
char headerStr[ DMX_MAX_HEADER_LENGTH ];
bool bOk = inBuf.ParseToken( DMX_VERSION_STARTING_TOKEN, DMX_VERSION_ENDING_TOKEN, headerStr, sizeof( headerStr ) );
if ( bOk )
{
#ifdef _WIN32
int nAssigned = sscanf_s( headerStr, "encoding %s %d format %s %d\n",
pHeader->encodingName, DMX_MAX_FORMAT_NAME_MAX_LENGTH, &( pHeader->nEncodingVersion ),
pHeader->formatName, DMX_MAX_FORMAT_NAME_MAX_LENGTH, &( pHeader->nFormatVersion ) );
#else
int nAssigned = sscanf( headerStr, "encoding %s %d format %s %d\n",
pHeader->encodingName, &( pHeader->nEncodingVersion ),
pHeader->formatName, &( pHeader->nFormatVersion ) );
#endif
bOk = nAssigned == 4;
}
if ( !bOk )
{
inBuf.SeekGet( CUtlBuffer::SEEK_HEAD, 0 );
bOk = inBuf.ParseToken( DMX_LEGACY_VERSION_STARTING_TOKEN, DMX_LEGACY_VERSION_ENDING_TOKEN, pHeader->formatName, DMX_MAX_FORMAT_NAME_MAX_LENGTH );
if ( bOk )
{
const char *pEncoding = GetEncodingFromLegacyFormat( pHeader->formatName );
if ( pEncoding )
{
V_strncpy( pHeader->encodingName, pEncoding, DMX_MAX_FORMAT_NAME_MAX_LENGTH );
pHeader->nEncodingVersion = 0; // the first encoding version
pHeader->nFormatVersion = -1; // this value is ignored for legacy formats
}
else
{
bOk = false;
}
}
}
inBuf.SetBufferType( bIsText, bHasCRLF );
return bOk;
}
const char *CDataModel::GetEncodingFromLegacyFormat( const char *pLegacyFormatName ) const
{
if ( StringHasPrefixCaseSensitive( pLegacyFormatName, "binary_v" ) )
return "binary";
if ( StringHasPrefixCaseSensitive( pLegacyFormatName, "sfm_v" ) )
return "binary";
if ( StringHasPrefixCaseSensitive( pLegacyFormatName, "keyvalues2_v" ) )
return "keyvalues2";
if ( StringHasPrefixCaseSensitive( pLegacyFormatName, "keyvalues2_flat_v" ) )
return "keyvalues2_flat";
return NULL;
}
bool CDataModel::IsLegacyFormat( const char *pFormatName ) const
{
return GetEncodingFromLegacyFormat( pFormatName ) != NULL;
}
bool CDataModel::IsValidNonDMXFormat( const char *pFormatName ) const
{
IDmSerializer *pSerializer = FindSerializer( pFormatName );
return pSerializer && !pSerializer->StoresVersionInFile();
}
// used to skip auto-creation of child elements during unserialization
bool CDataModel::IsUnserializing()
{
return m_bIsUnserializing;
}
int CDataModel::GetCurrentFormatVersion( const char *pFormatName )
{
if ( IsValidNonDMXFormat( pFormatName ) )
return 0; // unversioned format
IDmFormatUpdater *pUpdater = FindFormatUpdater( pFormatName );
if ( !pUpdater )
return -1; // invalid version #
return pUpdater->GetCurrentVersion();
}
//-----------------------------------------------------------------------------
// Unserializes, returns the root of the unserialized tree in ppRoot
//-----------------------------------------------------------------------------
bool CDataModel::Unserialize( CUtlBuffer &inBuf, const char *pEncodingName, const char *pSourceFormatName, const char *pFormatHint,
const char *pFileName, DmConflictResolution_t idConflictResolution, DmElementHandle_t &hRoot )
{
ClearUndo();
CDisableUndoScopeGuard sg;
Assert( pEncodingName && *pEncodingName );
if ( !pEncodingName || !*pEncodingName )
return false;
Assert( pSourceFormatName && *pSourceFormatName );
if ( !pSourceFormatName || !*pSourceFormatName )
return false;
// Find a serializer appropriate for the file format.
IDmSerializer *pSerializer = FindSerializer( pEncodingName );
if ( !pSerializer )
{
Warning( "Unerialize: DMX file encoding %s is undefined!\n", pEncodingName );
return false;
}
#if !defined(NO_MALLOC_OVERRIDE)
g_pMemAlloc->heapchk();
#endif
DmxHeader_t header;
bool bStoresVersionInFile = pSerializer->StoresVersionInFile();
bool bIsCurrentVersion = true; // for formats that don't store a format, files are currently always at the current version
if ( bStoresVersionInFile )
{
bool bOk = ReadDMXHeader( inBuf, &header );
if ( !bOk )
{
Warning( "Unserialize: unable to read DMX header!\n" );
return false;
}
if ( IsLegacyFormat( header.formatName ) )
{
if ( GetCurrentFormatVersion( GENERIC_DMX_FORMAT ) == 1 )
{
IDmLegacyUpdater *pLegacyUpdater = FindLegacyUpdater( header.formatName );
bIsCurrentVersion = !pLegacyUpdater || pLegacyUpdater->IsLatestVersion();
}
else
{
bIsCurrentVersion = false;
}
}
else
{
bIsCurrentVersion = GetCurrentFormatVersion( header.formatName ) == header.nFormatVersion;
}
}
// if we're not in dmxconvert, and we're not at the latest version, call dmxconvert and unserialize from the converted file
if ( !m_bOnlyCreateUntypedElements && !bIsCurrentVersion )
{
char path[ 256 ];
V_ExtractFilePath( pFileName, path, sizeof( path ) );
char tempFileName[ 256 ];
if ( !V_IsAbsolutePath( path ) )
{
g_pFullFileSystem->GetCurrentDirectory( path, sizeof( path ) );
}
V_ComposeFileName( path, "_temp_conversion_file_.dmx", tempFileName, sizeof( tempFileName ) );
V_RemoveDotSlashes( tempFileName );
const char *pDestEncodingName = "binary";
const char *pDestFormatName = IsLegacyFormat( header.formatName ) ? GENERIC_DMX_FORMAT : header.formatName;
char cmdline[ 256 ];
V_snprintf( cmdline, sizeof( cmdline ), "dmxconvert -allowdebug -i %s -o %s -oe %s -of %s", pFileName, tempFileName, pDestEncodingName, pDestFormatName );
ProcessHandle_t hProcess = PROCESS_HANDLE_INVALID;
if ( g_pProcessUtils )
{
hProcess = g_pProcessUtils->StartProcess( cmdline, false );
}
if ( hProcess == PROCESS_HANDLE_INVALID )
{
Warning( "Unserialize: Unable to run conversion process \"%s\"\n", cmdline );
return false;
}
g_pProcessUtils->WaitUntilProcessCompletes( hProcess );
g_pProcessUtils->CloseProcess( hProcess );
bool bSuccess;
{
CUtlStreamBuffer strbuf( tempFileName, NULL, CUtlBuffer::READ_ONLY );
if ( !strbuf.IsValid() )
{
Warning( "Unserialize: Unable to open temp file \"%s\"\n", tempFileName );
return false;
}
// yes, this passes in pFileName, even though it read from tempFileName - pFileName is only used for marking debug messages and setting fileid
bSuccess = Unserialize( strbuf, pDestEncodingName, pDestFormatName, pDestFormatName, pFileName, idConflictResolution, hRoot );
}
g_pFullFileSystem->RemoveFile( tempFileName );
return bSuccess;
}
// advance the buffer the the end of the header
if ( bStoresVersionInFile )
{
if ( V_strcmp( pEncodingName, header.encodingName ) != 0 )
return false;
if ( V_strcmp( pSourceFormatName, header.formatName ) != 0 )
return false;
if ( pSerializer->IsBinaryFormat() )
{
// For binary formats, we gotta keep reading until we hit the string terminator
// that occurred after the version line.