-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJBinaryData.cpp
2278 lines (2112 loc) · 107 KB
/
JBinaryData.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
//HEAD_DSCODES
/*
<DUALSPHYSICS> Copyright (c) 2020 by Dr Jose M. Dominguez et al. (see http://dual.sphysics.org/index.php/developers/).
EPHYSLAB Environmental Physics Laboratory, Universidade de Vigo, Ourense, Spain.
School of Mechanical, Aerospace and Civil Engineering, University of Manchester, Manchester, U.K.
This file is part of DualSPHysics.
DualSPHysics is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
DualSPHysics is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with DualSPHysics. If not, see <http://www.gnu.org/licenses/>.
*/
/// \file JBinaryData.cpp \brief Implements the class \ref JBinaryData.
#include "JBinaryData.h"
#include "Functions.h"
#include <fstream>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
const std::string JBinaryData::CodeItemDef="\nITEM\n";
const std::string JBinaryData::CodeValuesDef="\nVALUES";
const std::string JBinaryData::CodeArrayDef="\nARRAY";
//##############################################################################
//# JBinaryDataDef
//##############################################################################
//==============================================================================
/// Devuelve tipo de datos en texto.
/// Returns data type text.
//==============================================================================
std::string JBinaryDataDef::TypeToStr(TpData type){
string tx="";
switch(type){
case JBinaryDataDef::DatText: tx="text"; break;
case JBinaryDataDef::DatBool: tx="bool"; break;
case JBinaryDataDef::DatChar: tx="char"; break;
case JBinaryDataDef::DatUchar: tx="uchar"; break;
case JBinaryDataDef::DatShort: tx="short"; break;
case JBinaryDataDef::DatUshort: tx="ushort"; break;
case JBinaryDataDef::DatInt: tx="int"; break;
case JBinaryDataDef::DatUint: tx="uint"; break;
case JBinaryDataDef::DatLlong: tx="llong"; break;
case JBinaryDataDef::DatUllong: tx="ullong"; break;
case JBinaryDataDef::DatFloat: tx="float"; break;
case JBinaryDataDef::DatDouble: tx="double"; break;
case JBinaryDataDef::DatInt3: tx="int3"; break;
case JBinaryDataDef::DatUint3: tx="uint3"; break;
case JBinaryDataDef::DatFloat3: tx="float3"; break;
case JBinaryDataDef::DatDouble3: tx="double3"; break;
}
return(tx);
}
//==============================================================================
/// Devuelve tamanho del tipo de datos.
/// Returns size of the data type.
//==============================================================================
size_t JBinaryDataDef::SizeOfType(TpData type){
size_t ret=0;
switch(type){
//case JBinaryDataDef::DatText:
case JBinaryDataDef::DatBool: ret=sizeof(int); break;
case JBinaryDataDef::DatChar: ret=sizeof(char); break;
case JBinaryDataDef::DatUchar: ret=sizeof(unsigned char); break;
case JBinaryDataDef::DatShort: ret=sizeof(short); break;
case JBinaryDataDef::DatUshort: ret=sizeof(unsigned short); break;
case JBinaryDataDef::DatInt: ret=sizeof(int); break;
case JBinaryDataDef::DatUint: ret=sizeof(unsigned); break;
case JBinaryDataDef::DatLlong: ret=sizeof(llong); break;
case JBinaryDataDef::DatUllong: ret=sizeof(ullong); break;
case JBinaryDataDef::DatFloat: ret=sizeof(float); break;
case JBinaryDataDef::DatDouble: ret=sizeof(double); break;
case JBinaryDataDef::DatInt3: ret=sizeof(tint3); break;
case JBinaryDataDef::DatUint3: ret=sizeof(tuint3); break;
case JBinaryDataDef::DatFloat3: ret=sizeof(tfloat3); break;
case JBinaryDataDef::DatDouble3: ret=sizeof(tdouble3); break;
}
return(ret);
}
//==============================================================================
/// Devuelve true cuando el tipo es triple.
/// Returns true when the type is triple.
//==============================================================================
bool JBinaryDataDef::TypeIsTriple(TpData type){
bool ret=false;
switch(type){
//case JBinaryDataDef::DatText:
case JBinaryDataDef::DatBool:
case JBinaryDataDef::DatChar:
case JBinaryDataDef::DatUchar:
case JBinaryDataDef::DatShort:
case JBinaryDataDef::DatUshort:
case JBinaryDataDef::DatInt:
case JBinaryDataDef::DatUint:
case JBinaryDataDef::DatLlong:
case JBinaryDataDef::DatUllong:
case JBinaryDataDef::DatFloat:
case JBinaryDataDef::DatDouble:
ret=false;
break;
case JBinaryDataDef::DatInt3:
case JBinaryDataDef::DatUint3:
case JBinaryDataDef::DatFloat3:
case JBinaryDataDef::DatDouble3:
ret=true;
break;
}
return(ret);
}
//##############################################################################
//# JBinaryDataArray
//##############################################################################
//==============================================================================
/// Constructor.
//==============================================================================
JBinaryDataArray::JBinaryDataArray(JBinaryData* parent,const std::string &name,JBinaryDataDef::TpData type):Type(type){
ClassName="JBinaryDataArray";
Parent=parent;
Name=name;
Hide=false;
Pointer=NULL;
ExternalPointer=false;
Count=Size=0;
ClearFileData();
}
//==============================================================================
/// Destructor.
//==============================================================================
JBinaryDataArray::~JBinaryDataArray(){
DestructorActive=true;
FreeMemory();
}
//==============================================================================
/// Devuelve la cantidad de memoria reservada.
/// Returns the amount of memory reserved.
//==============================================================================
llong JBinaryDataArray::GetAllocMemory()const{
return(Pointer&&!ExternalPointer? Size*JBinaryDataDef::SizeOfType(Type): 0);
}
//==============================================================================
/// Cambia nombre de array comprobando que no existe otro array o value con el mismo nombre.
/// Exception to ensure that there is no duplictaes arrays or values.
//==============================================================================
void JBinaryDataArray::SetName(const std::string &name){
if(Parent->ExistsValue(name))Run_Exceptioon("There is already a value with the name given.");
if(Parent->GetArray(name)!=NULL)Run_Exceptioon("There is already an array with the name given.");
if(Parent->GetItem(name)!=NULL)Run_Exceptioon("There is already an item with the name given.");
Name=name;
}
//==============================================================================
/// Libera memoria asignada al puntero indicado.
/// Frees memory allocated to the specified pointer.
//==============================================================================
void JBinaryDataArray::FreePointer(void* ptr)const{
if(ptr)switch(Type){
case JBinaryDataDef::DatText: delete[] (string*)ptr; break;
case JBinaryDataDef::DatBool: delete[] (bool*)ptr; break;
case JBinaryDataDef::DatInt: delete[] (int*)ptr; break;
case JBinaryDataDef::DatUint: delete[] (unsigned int*)ptr; break;
case JBinaryDataDef::DatChar: delete[] (char*)ptr; break;
case JBinaryDataDef::DatUchar: delete[] (unsigned char*)ptr; break;
case JBinaryDataDef::DatShort: delete[] (short*)ptr; break;
case JBinaryDataDef::DatUshort: delete[] (unsigned short*)ptr; break;
case JBinaryDataDef::DatLlong: delete[] (llong*)ptr; break;
case JBinaryDataDef::DatUllong: delete[] (ullong*)ptr; break;
case JBinaryDataDef::DatFloat: delete[] (float*)ptr; break;
case JBinaryDataDef::DatDouble: delete[] (double*)ptr; break;
case JBinaryDataDef::DatInt3: delete[] (tint3*)ptr; break;
case JBinaryDataDef::DatUint3: delete[] (tuint3*)ptr; break;
case JBinaryDataDef::DatFloat3: delete[] (tfloat3*)ptr; break;
case JBinaryDataDef::DatDouble3: delete[] (tdouble3*)ptr; break;
default: Run_Exceptioon("Type of array invalid.");
}
}
//==============================================================================
/// Devuelve puntero con la memoria asiganda.
/// Returns pointer to the allocated memory.
//==============================================================================
void* JBinaryDataArray::AllocPointer(unsigned size)const{
void* ptr=NULL;
if(size){
try{
switch(Type){
case JBinaryDataDef::DatText: ptr=new string[size]; break;
case JBinaryDataDef::DatBool: ptr=new bool[size]; break;
case JBinaryDataDef::DatInt: ptr=new int[size]; break;
case JBinaryDataDef::DatUint: ptr=new unsigned int[size]; break;
case JBinaryDataDef::DatChar: ptr=new char[size]; break;
case JBinaryDataDef::DatUchar: ptr=new unsigned char[size]; break;
case JBinaryDataDef::DatShort: ptr=new short[size]; break;
case JBinaryDataDef::DatUshort: ptr=new unsigned short[size]; break;
case JBinaryDataDef::DatLlong: ptr=new llong[size]; break;
case JBinaryDataDef::DatUllong: ptr=new ullong[size]; break;
case JBinaryDataDef::DatFloat: ptr=new float[size]; break;
case JBinaryDataDef::DatDouble: ptr=new double[size]; break;
case JBinaryDataDef::DatInt3: ptr=new tint3[size]; break;
case JBinaryDataDef::DatUint3: ptr=new tuint3[size]; break;
case JBinaryDataDef::DatFloat3: ptr=new tfloat3[size]; break;
case JBinaryDataDef::DatDouble3: ptr=new tdouble3[size]; break;
default: Run_Exceptioon("Type of array invalid.");
}
}
catch(const std::bad_alloc){
Run_Exceptioon("Cannot allocate the requested memory.");
}
}
return(ptr);
}
//==============================================================================
/// Comprueba memoria disponible y redimensiona array si hace falta.
/// Si es ExternalPointer no permite redimensionar la memoria asignada.
/// Check available memory array and resize if necessary.
/// If ExternalPointer will not allow to resize the allocated memory.
//==============================================================================
void JBinaryDataArray::CheckMemory(unsigned count,bool resize){
if(count){
//-Reserva memoria si fuese necesario.
//-Allocates memory if necessary.
if(!Pointer){
if(!resize)Run_Exceptioon("Memory no allocated.");
AllocMemory(count);
}
if(Count+count>Size){
if(ExternalPointer)Run_Exceptioon("Allocated memory in external pointer is not enough.");
if(!resize)Run_Exceptioon("Allocated memory is not enough.");
AllocMemory(Count+count,true);
}
}
}
//==============================================================================
/// Extrae datos del ptr indicado.
/// Extract data from ptr indicated.
//==============================================================================
void JBinaryDataArray::OutData(unsigned &count,unsigned size,const byte *ptr,byte *dat,unsigned sdat)const{
const unsigned count2=count+sdat;
if(count2>size)Run_Exceptioon("Overflow in reading data.");
memcpy(dat,ptr+count,sdat);
count=count2;
}
//==============================================================================
/// Extrae string de ptr.
/// Extract string ptr.
//==============================================================================
std::string JBinaryDataArray::OutStr(unsigned &count,unsigned size,const byte *ptr)const{
unsigned len=OutUint(count,size,ptr);
string tex;
tex.resize(len);
const unsigned count2=count+len;
if(count2>size)Run_Exceptioon("Overflow in reading data.");
memcpy((char*)tex.c_str(),ptr+count,len);
count=count2;
return(tex);
}
//==============================================================================
/// Libera memoria asignada.
/// Frees allocated memory.
//==============================================================================
void JBinaryDataArray::FreeMemory(){
if(Pointer&&!ExternalPointer)FreePointer(Pointer);
Pointer=NULL;
ExternalPointer=false;
Count=0;
Size=0;
}
//==============================================================================
/// Asigna memoria para los elementos indicados.
/// Allocate memory for the elements indicated.
//==============================================================================
void JBinaryDataArray::AllocMemory(unsigned size,bool savedata){
if(Count&&savedata&&size){
if(ExternalPointer)Run_Exceptioon("External pointer can not be resized.");
const unsigned count2=min(Count,size);
void *ptr=AllocPointer(size);
if(Type==JBinaryDataDef::DatText){//-String array.
string *strings1=(string*)Pointer;
string *strings2=(string*)ptr;
for(unsigned c=0;c<count2;c++)strings2[c]=strings1[c];
}
else memcpy((byte*)ptr,(byte*)Pointer,JBinaryDataDef::SizeOfType(Type)*count2);
FreeMemory();
Pointer=ptr;
Count=count2;
Size=size;
}
else{
FreeMemory();
Size=size;
if(Size)Pointer=AllocPointer(Size);
}
}
//==============================================================================
/// Asigna memoria para los elementos indicados.
/// Allocate memory for the elements indicated.
//==============================================================================
void JBinaryDataArray::ConfigExternalMemory(unsigned size,void* pointer){
FreeMemory();
ExternalPointer=true;
Pointer=pointer;
Size=size;
Count=0;
}
//==============================================================================
/// Configura acceso a datos en fichero.
/// Set file data access.
//==============================================================================
void JBinaryDataArray::ConfigFileData(llong filepos,unsigned datacount,unsigned datasize){
FreeMemory();
FileDataPos=filepos; FileDataCount=datacount; FileDataSize=datasize;
}
//==============================================================================
/// Borra datos de acceso a datos en fichero.
/// Delete data file data access.
//==============================================================================
void JBinaryDataArray::ClearFileData(){
FileDataPos=-1; FileDataCount=FileDataSize=0;
}
//==============================================================================
/// Carga contenido de fichero abierto con OpenFileStructure().
/// Load open file content with OpenFileStructure ().
//==============================================================================
void JBinaryDataArray::ReadFileData(bool resize){
//printf("ReadFileData Parent_name:[%s] p:%p\n",Parent->GetName().c_str(),Parent);
//printf("ReadFileData Parent2_name:[%s] p:%p\n",(Parent->GetParent()? Parent->GetParent()->GetName().c_str(): "none"),Parent->GetParent());
//printf("ReadFileData root_name:[%s] p:%p\n",Parent->GetItemRoot()->GetName().c_str(),Parent->GetItemRoot());
ifstream *pf=Parent->GetItemRoot()->GetFileStructure();
if(!pf||!pf->is_open())Run_Exceptioon("The file with data is not available.");
//printf("ReadFileData[%s]> fpos:%llu count:%u size:%u\n",Name.c_str(),FileDataPos,FileDataCount,FileDataSize);
if(FileDataPos<0)Run_Exceptioon("The access information to data file is not available.");
pf->seekg(FileDataPos,ios::beg);
ReadData(FileDataCount,FileDataSize,pf,resize);
}
//==============================================================================
/// Anhade elementos al array de un fichero.
/// Si es ExternalPointer no permite redimensionar la memoria asignada.
/// Add elements to the array of a file.
/// If ExternalPointer will not allow to resize the allocated memory.
//==============================================================================
void JBinaryDataArray::ReadData(unsigned count,unsigned size,std::ifstream *pf,bool resize){
if(count){
//-Reserva memoria si fuese necesario.
CheckMemory(count,resize);
//-Carga datos de fichero.
if(GetType()==JBinaryDataDef::DatText){//-String Array.
byte *buf=new byte[size];
pf->read((char*)buf,size);
unsigned cbuf=0;
for(unsigned c=0;c<count;c++)AddText(OutStr(cbuf,size,buf),false);
delete[] buf;
}
else{
const unsigned stype=(unsigned)JBinaryDataDef::SizeOfType(Type);
const unsigned sdat=stype*count;
const unsigned cdat=stype*Count;
pf->read(((char*)Pointer)+cdat,sdat);
Count+=count;
}
}
}
//==============================================================================
/// Anhade elementos al array.
/// Si es ExternalPointer no permite redimensionar la memoria asignada.
/// Add elements to the array.
/// If ExternalPointer will not allow to resize the allocated memory.
//==============================================================================
void JBinaryDataArray::AddData(unsigned count,const void* data,bool resize){
if(count){
//-Reserva memoria si fuese necesario.
//-Allocates memory if necessary.
CheckMemory(count,resize);
//-Anhade datos al puntero.
//-Add data to the pointer.
if(Type==JBinaryDataDef::DatText){
string *strings=(string*)Pointer;
string *strings2=(string*)data;
for(unsigned c=0;c<count;c++)strings[Count+c]=strings2[c];
}
else{
const unsigned stype=(unsigned)JBinaryDataDef::SizeOfType(Type);
const unsigned sdat=stype*count;
const unsigned cdat=stype*Count;
memcpy(((byte*)Pointer)+cdat,(byte*)data,sdat);
}
Count+=count;
}
}
//==============================================================================
/// Guarda datos como contenido del array.
/// Save data as contents of the array.
//==============================================================================
void JBinaryDataArray::SetData(unsigned count,const void* data,bool externalpointer){
FreeMemory();
if(externalpointer){
Pointer=(void*)data;
ExternalPointer=true;
Size=count;
Count=count;
}
else AddData(count,data,true);
}
//==============================================================================
/// Anhade un string al array.
/// Si es ExternalPointer no permite redimensionar la memoria asignada.
/// Add a string to array.
/// If ExternalPointer will not allow to resize the allocated memory.
//==============================================================================
void JBinaryDataArray::AddText(const std::string &str,bool resize){
if(Type!=JBinaryDataDef::DatText)Run_Exceptioon("Type of array is not Text.");
unsigned count=1;
if(count){
//-Reserva memoria si fuese necesario.
//-Allocates memory if necessary.
CheckMemory(count,resize);
//-Anhade string al array.
//-Add string to array.
string *strings=(string*)Pointer;
strings[Count]=str;
Count+=count;
}
}
//==============================================================================
/// Anhade array de strings al array.
/// Si es ExternalPointer no permite redimensionar la memoria asignada.
/// Add array of strings to array.
/// If ExternalPointer will not allow to resize the allocated memory.
//==============================================================================
void JBinaryDataArray::AddTexts(unsigned count,const std::string *strs,bool resize){
if(Type!=JBinaryDataDef::DatText)Run_Exceptioon("Type of array is not Text.");
if(count)AddData(count,(const void*)strs,resize);
}
//==============================================================================
/// Devuelve puntero de datos comprobando que tenga datos.
/// Returns pointer and check is pointer is populated with data.
//==============================================================================
const void* JBinaryDataArray::GetDataPointer()const{
if(!DataInPointer())Run_Exceptioon("There are not available data in pointer.");
return(Pointer);
}
//==============================================================================
/// Copia datos de Pointer o FileData al puntero indicado y devuelve el numero
/// de elementos.
/// Copies data of the pointer or FileData indicated pointer and returns
/// the number of elements.
//==============================================================================
unsigned JBinaryDataArray::GetDataCopy(unsigned size,void* pointer)const{
if(!DataInPointer()&&!DataInFile())Run_Exceptioon("There are not available data in Pointer or FileData.");
const size_t stype=JBinaryDataDef::SizeOfType(GetType());
if(!stype)Run_Exceptioon("Type of array is invalid for this function.");
unsigned count=0;
if(DataInPointer()){
count=GetCount();
if(size>=count)memcpy(pointer,Pointer,stype*count);
}
else{
count=FileDataCount;
if(size>=count){
ifstream *pf=Parent->GetItemRoot()->GetFileStructure();
if(!pf||!pf->is_open())Run_Exceptioon("The file with data is not available.");
pf->seekg(FileDataPos,ios::beg);
count=FileDataCount;
pf->read((char*)pointer,stype*count);
}
}
if(size<count)Run_Exceptioon("Size of array is not enough to store all data.");
return(count);
}
//##############################################################################
//# JBinaryData
//##############################################################################
//==============================================================================
/// Constructor.
//==============================================================================
JBinaryData::JBinaryData(std::string name):Name(name){
ClassName="JBinaryData";
Parent=NULL;
FileStructure=NULL;
ValuesData=NULL;
ValuesCacheReset();
HideAll=HideValues=false;
FmtFloat="%.7E";
FmtDouble="%.15E";
}
//==============================================================================
/// Constructor de copias.
/// Copu of constructor
//==============================================================================
JBinaryData::JBinaryData(const JBinaryData &src){
ClassName="JBinaryData";
Parent=NULL;
FileStructure=NULL;
ValuesData=NULL;
ValuesCacheReset();
*this=src;
}
//==============================================================================
/// Destructor.
//==============================================================================
JBinaryData::~JBinaryData(){
DestructorActive=true;
Clear();
}
//==============================================================================
/// Sobrecarga del operador de asignacion.
/// Overload assignment operator.
//==============================================================================
JBinaryData& JBinaryData::operator=(const JBinaryData &src){
if(this!=&src){
unsigned size=src.GetSizeDataConst(true);
byte *dat=new byte[size];
src.SaveDataConst(size,dat,true);
LoadData(size,dat);
delete[] dat;
}
return(*this);
}
//==============================================================================
/// Elimina todo el contenido (values, arrays e items).
/// Deletes all contents (values, arrays and items).
//==============================================================================
void JBinaryData::Clear(){
RemoveValues();
RemoveArrays();
RemoveItems();
ValuesCacheReset();
CloseFileStructure();
}
//==============================================================================
/// Devuelve la cantidad de memoria reservada por el objeto y subobjetos.
/// Returns the amount of memory allocated by the object and sub-objects.
//==============================================================================
llong JBinaryData::GetAllocMemory()const{
llong s=0;
for(unsigned c=0;c<Arrays.size();c++)s+=Arrays[c]->GetAllocMemory(); //-Memoria de arrays no externos.
s+=ValuesSize; //-Memoria para cache de values.
for(unsigned c=0;c<Items.size();c++)s+=Items[c]->GetAllocMemory(); //-Memoria de Items descencientes.
return(s);
}
//==============================================================================
/// Elimina cache de values.
/// Removes cache values.
//==============================================================================
void JBinaryData::ValuesCacheReset(){
delete[] ValuesData; ValuesData=NULL;
ValuesSize=0;
ValuesModif=true;
}
//==============================================================================
/// Prepara cache de values.
/// Prepare cache values.
//==============================================================================
void JBinaryData::ValuesCachePrepare(bool down){
if(ValuesModif){
ValuesCacheReset();
ValuesSize=GetSizeValues();
ValuesData=new byte[ValuesSize];
unsigned count=0;
SaveValues(count,ValuesSize,ValuesData);
ValuesModif=false;
}
if(down)for(unsigned c=0;c<Items.size();c++)Items[c]->ValuesCachePrepare(true);
}
//==============================================================================
/// Comprueba existencia y tipo de valor. Devuelve posicion de valor (-1 no exite).
/// Check existence of value and type. Returns position (index) value (-1 if not exist).
//==============================================================================
int JBinaryData::CheckGetValue(const std::string &name,bool optional,JBinaryDataDef::TpData type)const{
int idx=GetValueIndex(name);
//if(idx<0&&GetArrayIndex(name)>=0)Run_Exceptioon(string("The value ")+name+" is an array.");
if(!optional&&idx<0)Run_Exceptioon(string("Value ")+name+" not found.");
if(idx>=0&&Values[idx].type!=type)Run_Exceptioon(string("Type of value ")+name+" invalid.");
return(idx);
}
//==============================================================================
/// Comprueba tipo de valor, y sino existe lo crea. Devuelve posicion de valor.
/// Check value type, create if it does not exists, Returns position value.
//==============================================================================
int JBinaryData::CheckSetValue(const std::string &name,JBinaryDataDef::TpData type){
int idx=GetValueIndex(name);
if(idx<0&&GetArray(name)!=NULL)Run_Exceptioon(string("The value ")+name+" is an array.");
if(idx<0&&GetItem(name)!=NULL)Run_Exceptioon(string("The value ")+name+" is an item.");
if(idx>=0&&Values[idx].type!=type)Run_Exceptioon(string("Type of value ")+name+" invalid.");
if(idx<0){
StValue v;
if(name.length()>120)Run_Exceptioon(string("The name of value ")+name+" is too large.");
if(name.empty())Run_Exceptioon(string("The name of value ")+name+" is empty.");
ResetValue(name,type,v);
Values.push_back(v);
idx=int(Values.size())-1;
}
ValuesModif=true;
return(idx);
}
//==============================================================================
/// Reset del valor pasado como referencia.
/// Reset the value passed by reference.
//==============================================================================
void JBinaryData::ResetValue(const std::string &name,JBinaryDataDef::TpData type,JBinaryData::StValue &v){
v.name=name; v.type=type; v.vdouble3=TDouble3(0);
}
//==============================================================================
/// Devuelve Value en formato XML.
/// Value returned in XML format.
//==============================================================================
std::string JBinaryData::ValueToXml(const StValue &v)const{
string tx=JBinaryDataDef::TypeToStr(v.type);
if(tx.empty())Run_Exceptioon("Name of type invalid.");
tx=string("<")+tx+" name=\""+v.name+"\" ";
switch(v.type){
case JBinaryDataDef::DatText: tx=tx+"v=\""+ v.vtext +"\" />"; break;
case JBinaryDataDef::DatBool: tx=tx+"v=\""+ (v.vint? "1": "0") +"\" />"; break;
case JBinaryDataDef::DatChar: tx=tx+"v=\""+ fun::IntStr(v.vchar) +"\" />"; break;
case JBinaryDataDef::DatUchar: tx=tx+"v=\""+ fun::UintStr(v.vuchar) +"\" />"; break;
case JBinaryDataDef::DatShort: tx=tx+"v=\""+ fun::IntStr(v.vshort) +"\" />"; break;
case JBinaryDataDef::DatUshort: tx=tx+"v=\""+ fun::UintStr(v.vushort) +"\" />"; break;
case JBinaryDataDef::DatInt: tx=tx+"v=\""+ fun::IntStr(v.vint) +"\" />"; break;
case JBinaryDataDef::DatUint: tx=tx+"v=\""+ fun::UintStr(v.vuint) +"\" />"; break;
case JBinaryDataDef::DatLlong: tx=tx+"v=\""+ fun::LongStr(v.vllong) +"\" />"; break;
case JBinaryDataDef::DatUllong: tx=tx+"v=\""+ fun::UlongStr(v.vullong) +"\" />"; break;
case JBinaryDataDef::DatFloat: tx=tx+"v=\""+ fun::FloatStr(v.vfloat,FmtFloat.c_str()) +"\" />"; break;
case JBinaryDataDef::DatDouble: tx=tx+"v=\""+ fun::DoubleStr(v.vdouble,FmtDouble.c_str()) +"\" />"; break;
case JBinaryDataDef::DatInt3: tx=tx+"x=\""+ fun::IntStr(v.vint3.x) +"\" y=\""+ fun::IntStr(v.vint3.y) +"\" z=\""+ fun::IntStr(v.vint3.z) +"\" />"; break;
case JBinaryDataDef::DatUint3: tx=tx+"x=\""+ fun::UintStr(v.vuint3.x) +"\" y=\""+ fun::UintStr(v.vuint3.y) +"\" z=\""+ fun::UintStr(v.vuint3.z) +"\" />"; break;
case JBinaryDataDef::DatFloat3: tx=tx+"x=\""+ fun::FloatStr(v.vfloat3.x,FmtFloat.c_str()) +"\" y=\""+ fun::FloatStr(v.vfloat3.y,FmtFloat.c_str()) +"\" z=\""+ fun::FloatStr(v.vfloat3.z,FmtFloat.c_str()) +"\" />"; break; //"%.7E"
case JBinaryDataDef::DatDouble3: tx=tx+"x=\""+ fun::DoubleStr(v.vdouble3.x,FmtDouble.c_str()) +"\" y=\""+ fun::DoubleStr(v.vdouble3.y,FmtDouble.c_str()) +"\" z=\""+ fun::DoubleStr(v.vdouble3.z,FmtDouble.c_str()) +"\" />"; break; //"%.15E"
default: Run_Exceptioon("Type of value invalid.");
}
return(tx);
}
//==============================================================================
/// Extrae datos del ptr indicado.
/// Extract data from ptr indicated.
//==============================================================================
void JBinaryData::OutData(unsigned &count,unsigned size,const byte *ptr,byte *dat,unsigned sdat)const{
const unsigned count2=count+sdat;
if(count2>size)Run_Exceptioon("Overflow in reading data.");
memcpy(dat,ptr+count,sdat);
count=count2;
}
//==============================================================================
/// Extrae string de ptr.
/// Remove string ptr.
//==============================================================================
std::string JBinaryData::OutStr(unsigned &count,unsigned size,const byte *ptr)const{
unsigned len=OutUint(count,size,ptr);
string tex;
tex.resize(len);
const unsigned count2=count+len;
if(count2>size)Run_Exceptioon("Overflow in reading data.");
memcpy((char*)tex.c_str(),ptr+count,len);
count=count2;
return(tex);
}
//==============================================================================
/// Introduce datos en ptr.
/// Put data in ptr.
//==============================================================================
void JBinaryData::InData(unsigned &count,unsigned size,byte *ptr,const byte *dat,unsigned sdat)const{
if(ptr){
if(count+sdat>size)Run_Exceptioon("Insufficient memory for data.");
memcpy(ptr+count,dat,sdat);
}
if(count+sdat<count)Run_Exceptioon("Size of data is too huge.");
count+=sdat;
}
//==============================================================================
/// Introduce string en ptr.
/// Put string in ptr.
//==============================================================================
void JBinaryData::InStr(unsigned &count,unsigned size,byte *ptr,const std::string &cad)const{
InUint(count,size,ptr,(unsigned)cad.length());
InData(count,size,ptr,(byte*)cad.c_str(),unsigned(cad.length()));
}
//==============================================================================
/// Introduce Value en ptr.
/// Put Value in ptr.
//==============================================================================
void JBinaryData::InValue(unsigned &count,unsigned size,byte *ptr,const StValue &v)const{
InStr(count,size,ptr,v.name);
InInt(count,size,ptr,int(v.type));
switch(v.type){
case JBinaryDataDef::DatText: InStr (count,size,ptr,v.vtext); break;
case JBinaryDataDef::DatBool: InBool (count,size,ptr,v.vint!=0); break;
case JBinaryDataDef::DatChar: InChar (count,size,ptr,v.vchar); break;
case JBinaryDataDef::DatUchar: InUchar (count,size,ptr,v.vuchar); break;
case JBinaryDataDef::DatShort: InShort (count,size,ptr,v.vshort); break;
case JBinaryDataDef::DatUshort: InUshort (count,size,ptr,v.vushort); break;
case JBinaryDataDef::DatInt: InInt (count,size,ptr,v.vint); break;
case JBinaryDataDef::DatUint: InUint (count,size,ptr,v.vuint); break;
case JBinaryDataDef::DatLlong: InLlong (count,size,ptr,v.vllong); break;
case JBinaryDataDef::DatUllong: InUllong (count,size,ptr,v.vullong); break;
case JBinaryDataDef::DatFloat: InFloat (count,size,ptr,v.vfloat); break;
case JBinaryDataDef::DatDouble: InDouble (count,size,ptr,v.vdouble); break;
case JBinaryDataDef::DatInt3: InInt3 (count,size,ptr,v.vint3); break;
case JBinaryDataDef::DatUint3: InUint3 (count,size,ptr,v.vuint3); break;
case JBinaryDataDef::DatFloat3: InFloat3 (count,size,ptr,v.vfloat3); break;
case JBinaryDataDef::DatDouble3: InDouble3(count,size,ptr,v.vdouble3); break;
default: Run_Exceptioon("Type of value invalid.");
}
}
//==============================================================================
/// Extrae Value en ptr.
/// Extract Value in ptr.
//==============================================================================
void JBinaryData::OutValue(unsigned &count,unsigned size,const byte *ptr){
string name=OutStr(count,size,ptr);
JBinaryDataDef::TpData type=(JBinaryDataDef::TpData)OutInt(count,size,ptr);
switch(type){
case JBinaryDataDef::DatText: SetvText (name,OutStr (count,size,ptr)); break;
case JBinaryDataDef::DatBool: SetvBool (name,OutBool (count,size,ptr)); break;
case JBinaryDataDef::DatChar: SetvChar (name,OutChar (count,size,ptr)); break;
case JBinaryDataDef::DatUchar: SetvUchar (name,OutUchar (count,size,ptr)); break;
case JBinaryDataDef::DatShort: SetvShort (name,OutShort (count,size,ptr)); break;
case JBinaryDataDef::DatUshort: SetvUshort (name,OutUshort (count,size,ptr)); break;
case JBinaryDataDef::DatInt: SetvInt (name,OutInt (count,size,ptr)); break;
case JBinaryDataDef::DatUint: SetvUint (name,OutUint (count,size,ptr)); break;
case JBinaryDataDef::DatLlong: SetvLlong (name,OutLlong (count,size,ptr)); break;
case JBinaryDataDef::DatUllong: SetvUllong (name,OutUllong (count,size,ptr)); break;
case JBinaryDataDef::DatFloat: SetvFloat (name,OutFloat (count,size,ptr)); break;
case JBinaryDataDef::DatDouble: SetvDouble (name,OutDouble (count,size,ptr)); break;
case JBinaryDataDef::DatInt3: SetvInt3 (name,OutInt3 (count,size,ptr)); break;
case JBinaryDataDef::DatUint3: SetvUint3 (name,OutUint3 (count,size,ptr)); break;
case JBinaryDataDef::DatFloat3: SetvFloat3 (name,OutFloat3 (count,size,ptr)); break;
case JBinaryDataDef::DatDouble3: SetvDouble3(name,OutDouble3(count,size,ptr)); break;
default: Run_Exceptioon("Type of value invalid.");
}
}
//==============================================================================
/// Introduce datos basicos de Array en ptr.
/// Put basic data Array in ptr.
//==============================================================================
void JBinaryData::InArrayBase(unsigned &count,unsigned size,byte *ptr,const JBinaryDataArray *ar)const{
InStr(count,size,ptr,CodeArrayDef);
InStr(count,size,ptr,ar->GetName());
InBool(count,size,ptr,ar->GetHide());
InInt(count,size,ptr,int(ar->GetType()));
InUint(count,size,ptr,ar->GetCount());
//-Calcula e introduce size de los datos del array.
unsigned sizearraydata=0;
InArrayData(sizearraydata,0,NULL,ar);
InUint(count,size,ptr,sizearraydata);
}
//==============================================================================
/// Introduce contendido de Array en ptr.
/// Put ptr Array content.
//==============================================================================
void JBinaryData::InArrayData(unsigned &count,unsigned size,byte *ptr,const JBinaryDataArray *ar)const{
const JBinaryDataDef::TpData type=ar->GetType();
const unsigned num=ar->GetCount();
const void* pointer=ar->GetPointer();
if(num&&!pointer)Run_Exceptioon("Pointer of array with data is invalid.");
if(type==JBinaryDataDef::DatText){//-Array de strings.
const string *list=(string*)pointer;
for(unsigned c=0;c<num;c++)InStr(count,size,ptr,list[c]);
}
else{//-Array de tipos basicos.
unsigned sizetype=(unsigned)JBinaryDataDef::SizeOfType(ar->GetType());
InData(count,size,ptr,(byte*)pointer,sizetype*num);
}
}
//==============================================================================
/// Introduce Array en ptr.
/// Put Array in ptr.
//==============================================================================
void JBinaryData::InArray(unsigned &count,unsigned size,byte *ptr,const JBinaryDataArray *ar)const{
//-Calcula size de la definicion del array.
unsigned sizearray=0;
InArrayBase(sizearray,0,NULL,ar);
//-Introduce propiedades de array en ptr.
InUint(count,size,ptr,sizearray);
InArrayBase(count,size,ptr,ar);
//-Introduce contenido del array.
InArrayData(count,size,ptr,ar);
}
//==============================================================================
/// Introduce datos basicos de Item en ptr.
/// Put basic data Item in ptr.
//==============================================================================
void JBinaryData::InItemBase(unsigned &count,unsigned size,byte *ptr,bool all)const{
InStr(count,size,ptr,CodeItemDef);
InStr(count,size,ptr,GetName());
InBool(count,size,ptr,GetHide());
InBool(count,size,ptr,GetHideValues());
InStr(count,size,ptr,GetFmtFloat());
InStr(count,size,ptr,GetFmtDouble());
InUint(count,size,ptr,(all? GetArraysCount(): GetVisibleArraysCount()));
InUint(count,size,ptr,(all? GetItemsCount(): GetVisibleItemsCount()));
if(all||!HideValues)InUint(count,size,ptr,(ValuesModif? GetSizeValues(): ValuesSize));
else InUint(count,size,ptr,0);
}
//==============================================================================
/// Introduce Item en ptr.
/// Put Item in ptr.
//==============================================================================
void JBinaryData::InItem(unsigned &count,unsigned size,byte *ptr,bool all)const{
//-Calcula size de la definicion del item.
unsigned sizeitem=0;
InItemBase(sizeitem,0,NULL,all);
//-Introduce propiedades de item en ptr.
InUint(count,size,ptr,sizeitem);
InItemBase(count,size,ptr,all);
//-Introduce values en ptr.
if(all||!HideValues){
if(ValuesModif)SaveValues(count,size,ptr);//-Cache no valida.
else InData(count,size,ptr,ValuesData,ValuesSize);//-Cache actualizada.
}
//-Introduce arrays en ptr.
for(unsigned c=0;c<Arrays.size();c++)if(all||!Arrays[c]->GetHide())InArray(count,size,ptr,Arrays[c]);
//-Introduce items en ptr.
for(unsigned c=0;c<Items.size();c++)if(all||!Items[c]->GetHide())Items[c]->InItem(count,size,ptr,all);
}
//==============================================================================
/// Extrae datos basicos del Array de ptr.
/// Extract basic data from ptr Array
//==============================================================================
JBinaryDataArray* JBinaryData::OutArrayBase(unsigned &count,unsigned size,const byte *ptr,unsigned &countdata,unsigned &sizedata){
if(OutStr(count,size,ptr)!=CodeArrayDef)Run_Exceptioon("Validation code is invalid.");
string name=OutStr(count,size,ptr);
bool hide=OutBool(count,size,ptr);
JBinaryDataDef::TpData type=(JBinaryDataDef::TpData)OutInt(count,size,ptr);
countdata=OutUint(count,size,ptr);
sizedata=OutUint(count,size,ptr);
if(type!=JBinaryDataDef::DatText&&sizedata!=JBinaryDataDef::SizeOfType(type)*countdata)Run_Exceptioon("Size of data is invalid.");
//-Crea array.
JBinaryDataArray *ar=CreateArray(name,type);
ar->SetHide(hide);
return(ar);
}
//==============================================================================
/// Extrae contenido de Array de ptr.
/// Extract the contents of the ptr Array
//==============================================================================
void JBinaryData::OutArrayData(unsigned &count,unsigned size,const byte *ptr,JBinaryDataArray *ar,unsigned countdata,unsigned sizedata){
if(ar->GetType()==JBinaryDataDef::DatText){//-Array de strings.
ar->AllocMemory(countdata);
for(unsigned c=0;c<countdata;c++)ar->AddText(OutStr(count,size,ptr),false);
}
else{
//-Comprueba que los datos del array estan disponibles.
//-Checks that the data array is available.
unsigned count2=count+sizedata;
if(count2>size)Run_Exceptioon("Overflow in reading data.");
//-Extrae datos para el array.
//-Extracts the data for the array.
ar->AddData(countdata,ptr+count,true);
count=count2;
}
}
//==============================================================================
/// Extrae Array de ptr.
/// Extracts the Array of the ptr.
//==============================================================================
void JBinaryData::OutArray(unsigned &count,unsigned size,const byte *ptr){
//-Crea y configura array a partir de ptr.
//-Creates and configures array from ptr
const unsigned sizearraydef=OutUint(count,size,ptr);
unsigned countdata,sizedata;
JBinaryDataArray *ar=OutArrayBase(count,size,ptr,countdata,sizedata);
//-Extrae contenido del array.
//-Extract contents of the array.
OutArrayData(count,size,ptr,ar,countdata,sizedata);
}
//==============================================================================
/// Extrae propiedades basicas de Item de ptr.
/// Extracts basic properties from the ptr Item
//==============================================================================
JBinaryData* JBinaryData::OutItemBase(unsigned &count,unsigned size,const byte *ptr,bool create,unsigned &narrays,unsigned &nitems,unsigned &sizevalues){
if(OutStr(count,size,ptr)!=CodeItemDef)Run_Exceptioon("Validation code is invalid.");
JBinaryData* item=this;
if(create)item=CreateItem(OutStr(count,size,ptr));
else item->SetName(OutStr(count,size,ptr));
item->SetHide(OutBool(count,size,ptr));
item->SetHideValues(OutBool(count,size,ptr),false);
item->SetFmtFloat(OutStr(count,size,ptr),false);
item->SetFmtDouble(OutStr(count,size,ptr),false);
narrays=OutUint(count,size,ptr);
nitems=OutUint(count,size,ptr);
sizevalues=OutUint(count,size,ptr);
return(item);
}
//==============================================================================
/// Extrae Item de ptr.
/// Extracts the Item ptr.
//==============================================================================
void JBinaryData::OutItem(unsigned &count,unsigned size,const byte *ptr,bool create){
//-Extrae propiedades del item.
//-Extract item properties
const unsigned sizeitemdef=OutUint(count,size,ptr);
unsigned narrays,nitems,sizevalues;
JBinaryData* item=OutItemBase(count,size,ptr,create,narrays,nitems,sizevalues);
//-Extrae values del item.
//-Extract values of the item.
if(sizevalues){
if(OutStr(count,size,ptr)!=CodeValuesDef)Run_Exceptioon("Validation code is invalid.");
unsigned num=OutUint(count,size,ptr);
for(unsigned c=0;c<num;c++)item->OutValue(count,size,ptr);
}
//-Extrae arrays del item.
//-Extract arrays from item.
for(unsigned c=0;c<narrays;c++)item->OutArray(count,size,ptr);
//-Extrae items del item.
//-Extract items from item.
for(unsigned c=0;c<nitems;c++)item->OutItem(count,size,ptr,true);
}
//==============================================================================
/// Devuelve el tamanho necesario para almacenar todos los values del item.
/// Returns the size necessary to store all the values in the item
//==============================================================================
unsigned JBinaryData::GetSizeValues()const{
unsigned count=0;
SaveValues(count,0,NULL);
return(count);
}
//==============================================================================
/// Almacena datos de values en ptr.
/// Data values stored in ptr.
//==============================================================================
void JBinaryData::SaveValues(unsigned &count,unsigned size,byte *ptr)const{
unsigned num=unsigned(Values.size());
InStr(count,size,ptr,CodeValuesDef);
InUint(count,size,ptr,num);
for(unsigned c=0;c<num;c++)InValue(count,size,ptr,Values[c]);
}
//==============================================================================
/// Graba contenido de array en fichero.
/// Saves the contents of array into the file.
//==============================================================================
void JBinaryData::WriteArrayData(std::fstream *pf,const JBinaryDataArray *ar)const{
const JBinaryDataDef::TpData type=ar->GetType();