aboutsummaryrefslogtreecommitdiff
path: root/src/client/mesh.cpp
blob: 4d73ead8abad4ae298606355a4e3c92d210ee58d (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program 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.

This program 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 this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "mesh.h"
#include "debug.h"
#include "log.h"
#include "irrMap.h"
#include <cmath>
#include <iostream>
#include <IAnimatedMesh.h>
#include <SAnimatedMesh.h>
#include <IAnimatedMeshSceneNode.h>

// In Irrlicht 1.8 the signature of ITexture::lock was changed from
// (bool, u32) to (E_TEXTURE_LOCK_MODE, u32).
#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7
#define MY_ETLM_READ_ONLY true
#else
#define MY_ETLM_READ_ONLY video::ETLM_READ_ONLY
#endif

inline static void applyShadeFactor(video::SColor& color, float factor)
{
	color.setRed(core::clamp(core::round32(color.getRed()*factor), 0, 255));
	color.setGreen(core::clamp(core::round32(color.getGreen()*factor), 0, 255));
	color.setBlue(core::clamp(core::round32(color.getBlue()*factor), 0, 255));
}

void applyFacesShading(video::SColor &color, const v3f &normal)
{
	/*
		Some drawtypes have normals set to (0, 0, 0), this must result in
		maximum brightness: shade factor 1.0.
		Shade factors for aligned cube faces are:
		+Y 1.000000 sqrt(1.0)
		-Y 0.447213 sqrt(0.2)
		+-X 0.670820 sqrt(0.45)
		+-Z 0.836660 sqrt(0.7)
	*/
	float x2 = normal.X * normal.X;
	float y2 = normal.Y * normal.Y;
	float z2 = normal.Z * normal.Z;
	if (normal.Y < 0)
		applyShadeFactor(color, 0.670820f * x2 + 0.447213f * y2 + 0.836660f * z2);
	else if ((x2 > 1e-3) || (z2 > 1e-3))
		applyShadeFactor(color, 0.670820f * x2 + 1.000000f * y2 + 0.836660f * z2);
}

scene::IAnimatedMesh* createCubeMesh(v3f scale)
{
	video::SColor c(255,255,255,255);
	video::S3DVertex vertices[24] =
	{
		// Up
		video::S3DVertex(-0.5,+0.5,-0.5, 0,1,0, c, 0,1),
		video::S3DVertex(-0.5,+0.5,+0.5, 0,1,0, c, 0,0),
		video::S3DVertex(+0.5,+0.5,+0.5, 0,1,0, c, 1,0),
		video::S3DVertex(+0.5,+0.5,-0.5, 0,1,0, c, 1,1),
		// Down
		video::S3DVertex(-0.5,-0.5,-0.5, 0,-1,0, c, 0,0),
		video::S3DVertex(+0.5,-0.5,-0.5, 0,-1,0, c, 1,0),
		video::S3DVertex(+0.5,-0.5,+0.5, 0,-1,0, c, 1,1),
		video::S3DVertex(-0.5,-0.5,+0.5, 0,-1,0, c, 0,1),
		// Right
		video::S3DVertex(+0.5,-0.5,-0.5, 1,0,0, c, 0,1),
		video::S3DVertex(+0.5,+0.5,-0.5, 1,0,0, c, 0,0),
		video::S3DVertex(+0.5,+0.5,+0.5, 1,0,0, c, 1,0),
		video::S3DVertex(+0.5,-0.5,+0.5, 1,0,0, c, 1,1),
		// Left
		video::S3DVertex(-0.5,-0.5,-0.5, -1,0,0, c, 1,1),
		video::S3DVertex(-0.5,-0.5,+0.5, -1,0,0, c, 0,1),
		video::S3DVertex(-0.5,+0.5,+0.5, -1,0,0, c, 0,0),
		video::S3DVertex(-0.5,+0.5,-0.5, -1,0,0, c, 1,0),
		// Back
		video::S3DVertex(-0.5,-0.5,+0.5, 0,0,1, c, 1,1),
		video::S3DVertex(+0.5,-0.5,+0.5, 0,0,1, c, 0,1),
		video::S3DVertex(+0.5,+0.5,+0.5, 0,0,1, c, 0,0),
		video::S3DVertex(-0.5,+0.5,+0.5, 0,0,1, c, 1,0),
		// Front
		video::S3DVertex(-0.5,-0.5,-0.5, 0,0,-1, c, 0,1),
		video::S3DVertex(-0.5,+0.5,-0.5, 0,0,-1, c, 0,0),
		video::S3DVertex(+0.5,+0.5,-0.5, 0,0,-1, c, 1,0),
		video::S3DVertex(+0.5,-0.5,-0.5, 0,0,-1, c, 1,1),
	};

	u16 indices[6] = {0,1,2,2,3,0};

	scene::SMesh *mesh = new scene::SMesh();
	for (u32 i=0; i<6; ++i)
	{
		scene::IMeshBuffer *buf = new scene::SMeshBuffer();
		buf->append(vertices + 4 * i, 4, indices, 6);
		// Set default material
		buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
		buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
		buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
		// Add mesh buffer to mesh
		mesh->addMeshBuffer(buf);
		buf->drop();
	}

	scene::SAnimatedMesh *anim_mesh = new scene::SAnimatedMesh(mesh);
	mesh->drop();
	scaleMesh(anim_mesh, scale);  // also recalculates bounding box
	return anim_mesh;
}

void scaleMesh(scene::IMesh *mesh, v3f scale)
{
	if (mesh == NULL)
		return;

	aabb3f bbox;
	bbox.reset(0, 0, 0);

	u32 mc = mesh->getMeshBufferCount();
	for (u32 j = 0; j < mc; j++) {
		scene::IMeshBuffer *buf = mesh->getMeshBuffer(j);
		const u32 stride = getVertexPitchFromType(buf->getVertexType());
		u32 vertex_count = buf->getVertexCount();
		u8 *vertices = (u8 *)buf->getVertices();
		for (u32 i = 0; i < vertex_count; i++)
			((video::S3DVertex *)(vertices + i * stride))->Pos *= scale;

		buf->recalculateBoundingBox();

		// calculate total bounding box
		if (j == 0)
			bbox = buf->getBoundingBox();
		else
			bbox.addInternalBox(buf->getBoundingBox());
	}
	mesh->setBoundingBox(bbox);
}

void translateMesh(scene::IMesh *mesh, v3f vec)
{
	if (mesh == NULL)
		return;

	aabb3f bbox;
	bbox.reset(0, 0, 0);

	u32 mc = mesh->getMeshBufferCount();
	for (u32 j = 0; j < mc; j++) {
		scene::IMeshBuffer *buf = mesh->getMeshBuffer(j);
		const u32 stride = getVertexPitchFromType(buf->getVertexType());
		u32 vertex_count = buf->getVertexCount();
		u8 *vertices = (u8 *)buf->getVertices();
		for (u32 i = 0; i < vertex_count; i++)
			((video::S3DVertex *)(vertices + i * stride))->Pos += vec;

		buf->recalculateBoundingBox();

		// calculate total bounding box
		if (j == 0)
			bbox = buf->getBoundingBox();
		else
			bbox.addInternalBox(buf->getBoundingBox());
	}
	mesh->setBoundingBox(bbox);
}

void setMeshBufferColor(scene::IMeshBuffer *buf, const video::SColor &color)
{
	const u32 stride = getVertexPitchFromType(buf->getVertexType());
	u32 vertex_count = buf->getVertexCount();
	u8 *vertices = (u8 *) buf->getVertices();
	for (u32 i = 0; i < vertex_count; i++)
		((video::S3DVertex *) (vertices + i * stride))->Color = color;
}

void setAnimatedMeshColor(scene::IAnimatedMeshSceneNode *node, const video::SColor &color)
{
	for (u32 i = 0; i < node->getMaterialCount(); ++i) {
		node->getMaterial(i).EmissiveColor = color;
	}
}

void setMeshColor(scene::IMesh *mesh, const video::SColor &color)
{
	if (mesh == NULL)
		return;

	u32 mc = mesh->getMeshBufferCount();
	for (u32 j = 0; j < mc; j++)
		setMeshBufferColor(mesh->getMeshBuffer(j), color);
}

template <typename F>
static void applyToMesh(scene::IMesh *mesh, const F &fn)
{
	u16 mc = mesh->getMeshBufferCount();
	for (u16 j = 0; j < mc; j++) {
		scene::IMeshBuffer *buf = mesh->getMeshBuffer(j);
		const u32 stride = getVertexPitchFromType(buf->getVertexType());
		u32 vertex_count = buf->getVertexCount();
		char *vertices = reinterpret_cast<char *>(buf->getVertices());
		for (u32 i = 0; i < vertex_count; i++)
			fn(reinterpret_cast<video::S3DVertex *>(vertices + i * stride));
	}
}

void colorizeMeshBuffer(scene::IMeshBuffer *buf, const video::SColor *buffercolor)
{
	const u32 stride = getVertexPitchFromType(buf->getVertexType());
	u32 vertex_count = buf->getVertexCount();
	u8 *vertices = (u8 *) buf->getVertices();
	for (u32 i = 0; i < vertex_count; i++) {
		video::S3DVertex *vertex = (video::S3DVertex *) (vertices + i * stride);
		video::SColor *vc = &(vertex->Color);
		// Reset color
		*vc = *buffercolor;
		// Apply shading
		applyFacesShading(*vc, vertex->Normal);
	}
}

void setMeshColorByNormalXYZ(scene::IMesh *mesh,
		const video::SColor &colorX,
		const video::SColor &colorY,
		const video::SColor &colorZ)
{
	if (!mesh)
		return;
	auto colorizator = [=] (video::S3DVertex *vertex) {
		f32 x = fabs(vertex->Normal.X);
		f32 y = fabs(vertex->Normal.Y);
		f32 z = fabs(vertex->Normal.Z);
		if (x >= y && x >= z)
			vertex->Color = colorX;
		else if (y >= z)
			vertex->Color = colorY;
		else
			vertex->Color = colorZ;
	};
	applyToMesh(mesh, colorizator);
}

void setMeshColorByNormal(scene::IMesh *mesh, const v3f &normal,
		const video::SColor &color)
{
	if (!mesh)
		return;
	auto colorizator = [normal, color] (video::S3DVertex *vertex) {
		if (vertex->Normal == normal)
			vertex->Color = color;
	};
	applyToMesh(mesh, colorizator);
}

template <float v3f::*U, float v3f::*V>
static void rotateMesh(scene::IMesh *mesh, float degrees)
{
	degrees *= M_PI / 180.0f;
	float c = std::cos(degrees);
	float s = std::sin(degrees);
	auto rotator = [c, s] (video::S3DVertex *vertex) {
		float u = vertex->Pos.*U;
		float v = vertex->Pos.*V;
		vertex->Pos.*U = c * u - s * v;
		vertex->Pos.*V = s * u + c * v;
	};
	applyToMesh(mesh, rotator);
}

void rotateMeshXYby(scene::IMesh *mesh, f64 degrees)
{
	rotateMesh<&v3f::X, &v3f::Y>(mesh, degrees);
}

void rotateMeshXZby(scene::IMesh *mesh, f64 degrees)
{
	rotateMesh<&v3f::X, &v3f::Z>(mesh, degrees);
}

void rotateMeshYZby(scene::IMesh *mesh, f64 degrees)
{
	rotateMesh<&v3f::Y, &v3f::Z>(mesh, degrees);
}

void rotateMeshBy6dFacedir(scene::IMesh *mesh, int facedir)
{
	int axisdir = facedir >> 2;
	facedir &= 0x03;
	switch (facedir) {
		case 1: rotateMeshXZby(mesh, -90); break;
		case 2: rotateMeshXZby(mesh, 180); break;
		case 3: rotateMeshXZby(mesh, 90); break;
	}
	switch (axisdir) {
		case 1: rotateMeshYZby(mesh, 90); break; // z+
		case 2: rotateMeshYZby(mesh, -90); break; // z-
		case 3: rotateMeshXYby(mesh, -90); break; // x+
		case 4: rotateMeshXYby(mesh, 90); break; // x-
		case 5: rotateMeshXYby(mesh, -180); break;
	}
}

void recalculateBoundingBox(scene::IMesh *src_mesh)
{
	aabb3f bbox;
	bbox.reset(0,0,0);
	for (u16 j = 0; j < src_mesh->getMeshBufferCount(); j++) {
		scene::IMeshBuffer *buf = src_mesh->getMeshBuffer(j);
		buf->recalculateBoundingBox();
		if (j == 0)
			bbox = buf->getBoundingBox();
		else
			bbox.addInternalBox(buf->getBoundingBox());
	}
	src_mesh->setBoundingBox(bbox);
}

scene::IMeshBuffer* cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer)
{
	switch (mesh_buffer->getVertexType()) {
	case video::EVT_STANDARD: {
		video::S3DVertex *v = (video::S3DVertex *) mesh_buffer->getVertices();
		u16 *indices = mesh_buffer->getIndices();
		scene::SMeshBuffer *cloned_buffer = new scene::SMeshBuffer();
		cloned_buffer->append(v, mesh_buffer->getVertexCount(), indices,
			mesh_buffer->getIndexCount());
		return cloned_buffer;
	}
	case video::EVT_2TCOORDS: {
		video::S3DVertex2TCoords *v =
			(video::S3DVertex2TCoords *) mesh_buffer->getVertices();
		u16 *indices = mesh_buffer->getIndices();
		scene::SMeshBufferLightMap *cloned_buffer =
			new scene::SMeshBufferLightMap();
		cloned_buffer->append(v, mesh_buffer->getVertexCount(), indices,
			mesh_buffer->getIndexCount());
		return cloned_buffer;
	}
	case video::EVT_TANGENTS: {
		video::S3DVertexTangents *v =
			(video::S3DVertexTangents *) mesh_buffer->getVertices();
		u16 *indices = mesh_buffer->getIndices();
		scene::SMeshBufferTangents *cloned_buffer =
			new scene::SMeshBufferTangents();
		cloned_buffer->append(v, mesh_buffer->getVertexCount(), indices,
			mesh_buffer->getIndexCount());
		return cloned_buffer;
	}
	}
	// This should not happen.
	sanity_check(false);
	return NULL;
}

scene::SMesh* cloneMesh(scene::IMesh *src_mesh)
{
	scene::SMesh* dst_mesh = new scene::SMesh();
	for (u16 j = 0; j < src_mesh->getMeshBufferCount(); j++) {
		scene::IMeshBuffer *temp_buf = cloneMeshBuffer(
			src_mesh->getMeshBuffer(j));
		dst_mesh->addMeshBuffer(temp_buf);
		temp_buf->drop();

	}
	return dst_mesh;
}

scene::IMesh* convertNodeboxesToMesh(const std::vector<aabb3f> &boxes,
		const f32 *uv_coords, float expand)
{
	scene::SMesh* dst_mesh = new scene::SMesh();

	for (u16 j = 0; j < 6; j++)
	{
		scene::IMeshBuffer *buf = new scene::SMeshBuffer();
		buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
		buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
		dst_mesh->addMeshBuffer(buf);
		buf->drop();
	}

	video::SColor c(255,255,255,255);

	for (aabb3f box : boxes) {
		box.repair();

		box.MinEdge.X -= expand;
		box.MinEdge.Y -= expand;
		box.MinEdge.Z -= expand;
		box.MaxEdge.X += expand;
		box.MaxEdge.Y += expand;
		box.MaxEdge.Z += expand;

		// Compute texture UV coords
		f32 tx1 = (box.MinEdge.X / BS) + 0.5;
		f32 ty1 = (box.MinEdge.Y / BS) + 0.5;
		f32 tz1 = (box.MinEdge.Z / BS) + 0.5;
		f32 tx2 = (box.MaxEdge.X / BS) + 0.5;
		f32 ty2 = (box.MaxEdge.Y / BS) + 0.5;
		f32 tz2 = (box.MaxEdge.Z / BS) + 0.5;

		f32 txc_default[24] = {
			// up
			tx1, 1 - tz2, tx2, 1 - tz1,
			// down
			tx1, tz1, tx2, tz2,
			// right
			tz1, 1 - ty2, tz2, 1 - ty1,
			// left
			1 - tz2, 1 - ty2, 1 - tz1, 1 - ty1,
			// back
			1 - tx2, 1 - ty2, 1 - tx1, 1 - ty1,
			// front
			tx1, 1 - ty2, tx2, 1 - ty1,
		};

		// use default texture UV mapping if not provided
		const f32 *txc = uv_coords ? uv_coords : txc_default;

		v3f min = box.MinEdge;
		v3f max = box.MaxEdge;

		video::S3DVertex vertices[24] =
		{
			// up
			video::S3DVertex(min.X,max.Y,max.Z, 0,1,0, c, txc[0],txc[1]),
			video::S3DVertex(max.X,max.Y,max.Z, 0,1,0, c, txc[2],txc[1]),
			video::S3DVertex(max.X,max.Y,min.Z, 0,1,0, c, txc[2],txc[3]),
			video::S3DVertex(min.X,max.Y,min.Z, 0,1,0, c, txc[0],txc[3]),
			// down
			video::S3DVertex(min.X,min.Y,min.Z, 0,-1,0, c, txc[4],txc[5]),
			video::S3DVertex(max.X,min.Y,min.Z, 0,-1,0, c, txc[6],txc[5]),
			video::S3DVertex(max.X,min.Y,max.Z, 0,-1,0, c, txc[6],txc[7]),
			video::S3DVertex(min.X,min.Y,max.Z, 0,-1,0, c, txc[4],txc[7]),
			// right
			video::S3DVertex(max.X,max.Y,min.Z, 1,0,0, c, txc[ 8],txc[9]),
			video::S3DVertex(max.X,max.Y,max.Z, 1,0,0, c, txc[10],txc[9]),
			video::S3DVertex(max.X,min.Y,max.Z, 1,0,0, c, txc[10],txc[11]),
			video::S3DVertex(max.X,min.Y,min.Z, 1,0,0, c, txc[ 8],txc[11]),
			// left
			video::S3DVertex(min.X,max.Y,max.Z, -1,0,0, c, txc[12],txc[13]),
			video::S3DVertex(min.X,max.Y,min.Z, -1,0,0, c, txc[14],txc[13]),
			video::S3DVertex(min.X,min.Y,min.Z, -1,0,0, c, txc[14],txc[15]),
			video::S3DVertex(min.X,min.Y,max.Z, -1,0,0, c, txc[12],txc[15]),
			// back
			video::S3DVertex(max.X,max.Y,max.Z, 0,0,1, c, txc[16],txc[17]),
			video::S3DVertex(min.X,max.Y,max.Z, 0,0,1, c, txc[18],txc[17]),
			video::S3DVertex(min.X,min.Y,max.Z, 0,0,1, c, txc[18],txc[19]),
			video::S3DVertex(max.X,min.Y,max.Z, 0,0,1, c, txc[16],txc[19]),
			// front
			video::S3DVertex(min.X,max.Y,min.Z, 0,0,-1, c, txc[20],txc[21]),
			video::S3DVertex(max.X,max.Y,min.Z, 0,0,-1, c, txc[22],txc[21]),
			video::S3DVertex(max.X,min.Y,min.Z, 0,0,-1, c, txc[22],txc[23]),
			video::S3DVertex(min.X,min.Y,min.Z, 0,0,-1, c, txc[20],txc[23]),
		};

		u16 indices[] = {0,1,2,2,3,0};

		for(u16 j = 0; j < 24; j += 4)
		{
			scene::IMeshBuffer *buf = dst_mesh->getMeshBuffer(j / 4);
			buf->append(vertices + j, 4, indices, 6);
		}
	}
	return dst_mesh;
}

struct vcache
{
	core::array<u32> tris;
	float score;
	s16 cachepos;
	u16 NumActiveTris;
};

struct tcache
{
	u16 ind[3];
	float score;
	bool drawn;
};

const u16 cachesize = 32;

float FindVertexScore(vcache *v)
{
	const float CacheDecayPower = 1.5f;
	const float LastTriScore = 0.75f;
	const float ValenceBoostScale = 2.0f;
	const float ValenceBoostPower = 0.5f;
	const float MaxSizeVertexCache = 32.0f;

	if (v->NumActiveTris == 0)
	{
		// No tri needs this vertex!
		return -1.0f;
	}

	float Score = 0.0f;
	int CachePosition = v->cachepos;
	if (CachePosition < 0)
	{
		// Vertex is not in FIFO cache - no score.
	}
	else
	{
		if (CachePosition < 3)
		{
			// This vertex was used in the last triangle,
			// so it has a fixed score.
			Score = LastTriScore;
		}
		else
		{
			// Points for being high in the cache.
			const float Scaler = 1.0f / (MaxSizeVertexCache - 3);
			Score = 1.0f - (CachePosition - 3) * Scaler;
			Score = powf(Score, CacheDecayPower);
		}
	}

	// Bonus points for having a low number of tris still to
	// use the vert, so we get rid of lone verts quickly.
	float ValenceBoost = powf(v->NumActiveTris,
				-ValenceBoostPower);
	Score += ValenceBoostScale * ValenceBoost;

	return Score;
}

/*
	A specialized LRU cache for the Forsyth algorithm.
*/

class f_lru
{

public:
	f_lru(vcache *v, tcache *t): vc(v), tc(t)
	{
		for (int &i : cache) {
			i = -1;
		}
	}

	// Adds this vertex index and returns the highest-scoring triangle index
	u32 add(u16 vert, bool updatetris = false)
	{
		bool found = false;

		// Mark existing pos as empty
		for (u16 i = 0; i < cachesize; i++)
		{
			if (cache[i] == vert)
			{
				// Move everything down
				for (u16 j = i; j; j--)
				{
					cache[j] = cache[j - 1];
				}

				found = true;
				break;
			}
		}

		if (!found)
		{
			if (cache[cachesize-1] != -1)
				vc[cache[cachesize-1]].cachepos = -1;

			// Move everything down
			for (u16 i = cachesize - 1; i; i--)
			{
				cache[i] = cache[i - 1];
			}
		}

		cache[0] = vert;

		u32 highest = 0;
		float hiscore = 0;

		if (updatetris)
		{
			// Update cache positions
			for (u16 i = 0; i < cachesize; i++)
			{
				if (cache[i] == -1)
					break;

				vc[cache[i]].cachepos = i;
				vc[cache[i]].score = FindVertexScore(&vc[cache[i]]);
			}

			// Update triangle scores
			for (int i : cache) {
				if (i == -1)
					break;

				const u16 trisize = vc[i].tris.size();
				for (u16 t = 0; t < trisize; t++)
				{
					tcache *tri = &tc[vc[i].tris[t]];

					tri->score =
						vc[tri->ind[0]].score +
						vc[tri->ind[1]].score +
						vc[tri->ind[2]].score;

					if (tri->score > hiscore)
					{
						hiscore = tri->score;
						highest = vc[i].tris[t];
					}
				}
			}
		}

		return highest;
	}

private:
	s32 cache[cachesize];
	vcache *vc;
	tcache *tc;
};

/**
Vertex cache optimization according to the Forsyth paper:
http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html

The function is thread-safe (read: you can optimize several meshes in different threads)

\param mesh Source mesh for the operation.  */
scene::IMesh* createForsythOptimizedMesh(const scene::IMesh *mesh)
{
	if (!mesh)
		return 0;

	scene::SMesh *newmesh = new scene::SMesh();
	newmesh->BoundingBox = mesh->getBoundingBox();

	const u32 mbcount = mesh->getMeshBufferCount();

	for (u32 b = 0; b < mbcount; ++b)
	{
		const scene::IMeshBuffer *mb = mesh->getMeshBuffer(b);

		if (mb->getIndexType() != video::EIT_16BIT)
		{
			//os::Printer::log("Cannot optimize a mesh with 32bit indices", ELL_ERROR);
			newmesh->drop();
			return 0;
		}

		const u32 icount = mb->getIndexCount();
		const u32 tcount = icount / 3;
		const u32 vcount = mb->getVertexCount();
		const u16 *ind = mb->getIndices();

		vcache *vc = new vcache[vcount];
		tcache *tc = new tcache[tcount];

		f_lru lru(vc, tc);

		// init
		for (u16 i = 0; i < vcount; i++)
		{
			vc[i].score = 0;
			vc[i].cachepos = -1;
			vc[i].NumActiveTris = 0;
		}

		// First pass: count how many times a vert is used
		for (u32 i = 0; i < icount; i += 3)
		{
			vc[ind[i]].NumActiveTris++;
			vc[ind[i + 1]].NumActiveTris++;
			vc[ind[i + 2]].NumActiveTris++;

			const u32 tri_ind = i/3;
			tc[tri_ind].ind[0] = ind[i];
			tc[tri_ind].ind[1] = ind[i + 1];
			tc[tri_ind].ind[2] = ind[i + 2];
		}

		// Second pass: list of each triangle
		for (u32 i = 0; i < tcount; i++)
		{
			vc[tc[i].ind[0]].tris.push_back(i);
			vc[tc[i].ind[1]].tris.push_back(i);
			vc[tc[i].ind[2]].tris.push_back(i);

			tc[i].drawn = false;
		}

		// Give initial scores
		for (u16 i = 0; i < vcount; i++)
		{
			vc[i].score = FindVertexScore(&vc[i]);
		}
		for (u32 i = 0; i < tcount; i++)
		{
			tc[i].score =
					vc[tc[i].ind[0]].score +
					vc[tc[i].ind[1]].score +
					vc[tc[i].ind[2]].score;
		}

		switch(mb->getVertexType())
		{
			case video::EVT_STANDARD:
			{
				video::S3DVertex *v = (video::S3DVertex *) mb->getVertices();

				scene::SMeshBuffer *buf = new scene::SMeshBuffer();
				buf->Material = mb->getMaterial();

				buf->Vertices.reallocate(vcount);
				buf->Indices.reallocate(icount);

				core::map<const video::S3DVertex, const u16> sind; // search index for fast operation
				typedef core::map<const video::S3DVertex, const u16>::Node snode;

				// Main algorithm
				u32 highest = 0;
				u32 drawcalls = 0;
				for (;;)
				{
					if (tc[highest].drawn)
					{
						bool found = false;
						float hiscore = 0;
						for (u32 t = 0; t < tcount; t++)
						{
							if (!tc[t].drawn)
							{
								if (tc[t].score > hiscore)
								{
									highest = t;
									hiscore = tc[t].score;
									found = true;
								}
							}
						}
						if (!found)
							break;
					}

					// Output the best triangle
					u16 newind = buf->Vertices.size();

					snode *s = sind.find(v[tc[highest].ind[0]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[0]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[0]], newind);
						newind++;
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					s = sind.find(v[tc[highest].ind[1]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[1]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[1]], newind);
						newind++;
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					s = sind.find(v[tc[highest].ind[2]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[2]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[2]], newind);
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					vc[tc[highest].ind[0]].NumActiveTris--;
					vc[tc[highest].ind[1]].NumActiveTris--;
					vc[tc[highest].ind[2]].NumActiveTris--;

					tc[highest].drawn = true;

					for (u16 j : tc[highest].ind) {
						vcache *vert = &vc[j];
						for (u16 t = 0; t < vert->tris.size(); t++)
						{
							if (highest == vert->tris[t])
							{
								vert->tris.erase(t);
								break;
							}
						}
					}

					lru.add(tc[highest].ind[0]);
					lru.add(tc[highest].ind[1]);
					highest = lru.add(tc[highest].ind[2], true);
					drawcalls++;
				}

				buf->setBoundingBox(mb->getBoundingBox());
				newmesh->addMeshBuffer(buf);
				buf->drop();
			}
			break;
			case video::EVT_2TCOORDS:
			{
				video::S3DVertex2TCoords *v = (video::S3DVertex2TCoords *) mb->getVertices();

				scene::SMeshBufferLightMap *buf = new scene::SMeshBufferLightMap();
				buf->Material = mb->getMaterial();

				buf->Vertices.reallocate(vcount);
				buf->Indices.reallocate(icount);

				core::map<const video::S3DVertex2TCoords, const u16> sind; // search index for fast operation
				typedef core::map<const video::S3DVertex2TCoords, const u16>::Node snode;

				// Main algorithm
				u32 highest = 0;
				u32 drawcalls = 0;
				for (;;)
				{
					if (tc[highest].drawn)
					{
						bool found = false;
						float hiscore = 0;
						for (u32 t = 0; t < tcount; t++)
						{
							if (!tc[t].drawn)
							{
								if (tc[t].score > hiscore)
								{
									highest = t;
									hiscore = tc[t].score;
									found = true;
								}
							}
						}
						if (!found)
							break;
					}

					// Output the best triangle
					u16 newind = buf->Vertices.size();

					snode *s = sind.find(v[tc[highest].ind[0]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[0]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[0]], newind);
						newind++;
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					s = sind.find(v[tc[highest].ind[1]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[1]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[1]], newind);
						newind++;
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					s = sind.find(v[tc[highest].ind[2]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[2]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[2]], newind);
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					vc[tc[highest].ind[0]].NumActiveTris--;
					vc[tc[highest].ind[1]].NumActiveTris--;
					vc[tc[highest].ind[2]].NumActiveTris--;

					tc[highest].drawn = true;

					for (u16 j : tc[highest].ind) {
						vcache *vert = &vc[j];
						for (u16 t = 0; t < vert->tris.size(); t++)
						{
							if (highest == vert->tris[t])
							{
								vert->tris.erase(t);
								break;
							}
						}
					}

					lru.add(tc[highest].ind[0]);
					lru.add(tc[highest].ind[1]);
					highest = lru.add(tc[highest].ind[2]);
					drawcalls++;
				}

				buf->setBoundingBox(mb->getBoundingBox());
				newmesh->addMeshBuffer(buf);
				buf->drop();

			}
			break;
			case video::EVT_TANGENTS:
			{
				video::S3DVertexTangents *v = (video::S3DVertexTangents *) mb->getVertices();

				scene::SMeshBufferTangents *buf = new scene::SMeshBufferTangents();
				buf->Material = mb->getMaterial();

				buf->Vertices.reallocate(vcount);
				buf->Indices.reallocate(icount);

				core::map<const video::S3DVertexTangents, const u16> sind; // search index for fast operation
				typedef core::map<const video::S3DVertexTangents, const u16>::Node snode;

				// Main algorithm
				u32 highest = 0;
				u32 drawcalls = 0;
				for (;;)
				{
					if (tc[highest].drawn)
					{
						bool found = false;
						float hiscore = 0;
						for (u32 t = 0; t < tcount; t++)
						{
							if (!tc[t].drawn)
							{
								if (tc[t].score > hiscore)
								{
									highest = t;
									hiscore = tc[t].score;
									found = true;
								}
							}
						}
						if (!found)
							break;
					}

					// Output the best triangle
					u16 newind = buf->Vertices.size();

					snode *s = sind.find(v[tc[highest].ind[0]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[0]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[0]], newind);
						newind++;
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					s = sind.find(v[tc[highest].ind[1]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[1]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[1]], newind);
						newind++;
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					s = sind.find(v[tc[highest].ind[2]]);

					if (!s)
					{
						buf->Vertices.push_back(v[tc[highest].ind[2]]);
						buf->Indices.push_back(newind);
						sind.insert(v[tc[highest].ind[2]], newind);
					}
					else
					{
						buf->Indices.push_back(s->getValue());
					}

					vc[tc[highest].ind[0]].NumActiveTris--;
					vc[tc[highest].ind[1]].NumActiveTris--;
					vc[tc[highest].ind[2]].NumActiveTris--;

					tc[highest].drawn = true;

					for (u16 j : tc[highest].ind) {
						vcache *vert = &vc[j];
						for (u16 t = 0; t < vert->tris.size(); t++)
						{
							if (highest == vert->tris[t])
							{
								vert->tris.erase(t);
								break;
							}
						}
					}

					lru.add(tc[highest].ind[0]);
					lru.add(tc[highest].ind[1]);
					highest = lru.add(tc[highest].ind[2]);
					drawcalls++;
				}

				buf->setBoundingBox(mb->getBoundingBox());
				newmesh->addMeshBuffer(buf);
				buf->drop();
			}
			break;
		}

		delete [] vc;
		delete [] tc;

	} // for each meshbuffer

	return newmesh;
}
n> (v < 0) return operator-=(v * -1); if (pos >= ref->size_raw()) return *this; // Go to the appropriate position. // TODO: Don't force u32 on an x64 OS. Make it agnostic. u32 i = (u32)v; u32 sr = ref->size_raw(); const uchar16_t* a = ref->c_str(); while (i != 0 && pos < sr) { if (UTF16_IS_SURROGATE_HI(a[pos])) pos += 2; else ++pos; --i; } if (pos > sr) pos = sr; return *this; } //! Go back a specified number of full characters in the string. //! \return Myself. _Iter& operator-=(const difference_type v) { if (v == 0) return *this; if (v > 0) return operator+=(v * -1); if (pos == 0) return *this; // Go to the appropriate position. // TODO: Don't force u32 on an x64 OS. Make it agnostic. u32 i = (u32)v; const uchar16_t* a = ref->c_str(); while (i != 0 && pos != 0) { --pos; if (UTF16_IS_SURROGATE_LO(a[pos]) != 0 && pos != 0) --pos; --i; } return *this; } //! Return a new iterator that is a variable number of full characters forward from the current position. _Iter operator+(const difference_type v) const { _Iter ret(*this); ret += v; return ret; } //! Return a new iterator that is a variable number of full characters backward from the current position. _Iter operator-(const difference_type v) const { _Iter ret(*this); ret -= v; return ret; } //! Returns the distance between two iterators. difference_type operator-(const _Iter& iter) const { // Make sure we reference the same object! if (ref != iter.ref) return difference_type(); _Iter i = iter; difference_type ret; // Walk up. if (pos > i.pos) { while (pos > i.pos) { ++i; ++ret; } return ret; } // Walk down. while (pos < i.pos) { --i; --ret; } return ret; } //! Accesses the full character at the iterator's position. const_reference operator*() const { if (pos >= ref->size_raw()) { const uchar16_t* a = ref->c_str(); u32 p = ref->size_raw(); if (UTF16_IS_SURROGATE_LO(a[p])) --p; reference ret(ref, p); return ret; } const_reference ret(ref, pos); return ret; } //! Accesses the full character at the iterator's position. reference operator*() { if (pos >= ref->size_raw()) { const uchar16_t* a = ref->c_str(); u32 p = ref->size_raw(); if (UTF16_IS_SURROGATE_LO(a[p])) --p; reference ret(ref, p); return ret; } reference ret(ref, pos); return ret; } //! Accesses the full character at the iterator's position. const_pointer operator->() const { return operator*(); } //! Accesses the full character at the iterator's position. pointer operator->() { return operator*(); } //! Is the iterator at the start of the string? bool atStart() const { return pos == 0; } //! Is the iterator at the end of the string? bool atEnd() const { const uchar16_t* a = ref->c_str(); if (UTF16_IS_SURROGATE(a[pos])) return (pos + 1) >= ref->size_raw(); else return pos >= ref->size_raw(); } //! Moves the iterator to the start of the string. void toStart() { pos = 0; } //! Moves the iterator to the end of the string. void toEnd() { pos = ref->size_raw(); } //! Returns the iterator's position. //! \return The iterator's position. u32 getPos() const { return pos; } protected: const ustring16<TAlloc>* ref; u32 pos; }; //! Iterator to iterate through a UTF-16 string. class _ustring16_iterator : public _ustring16_const_iterator { public: typedef _ustring16_iterator _Iter; typedef _ustring16_const_iterator _Base; typedef typename _Base::const_pointer const_pointer; typedef typename _Base::const_reference const_reference; typedef typename _Base::value_type value_type; typedef typename _Base::difference_type difference_type; typedef typename _Base::distance_type distance_type; typedef access pointer; typedef access reference; using _Base::pos; using _Base::ref; //! Constructors. _ustring16_iterator(const _Iter& i) : _ustring16_const_iterator(i) {} _ustring16_iterator(const ustring16<TAlloc>& s) : _ustring16_const_iterator(s) {} _ustring16_iterator(const ustring16<TAlloc>& s, const u32 p) : _ustring16_const_iterator(s, p) {} //! Accesses the full character at the iterator's position. reference operator*() const { if (pos >= ref->size_raw()) { const uchar16_t* a = ref->c_str(); u32 p = ref->size_raw(); if (UTF16_IS_SURROGATE_LO(a[p])) --p; reference ret(ref, p); return ret; } reference ret(ref, pos); return ret; } //! Accesses the full character at the iterator's position. reference operator*() { if (pos >= ref->size_raw()) { const uchar16_t* a = ref->c_str(); u32 p = ref->size_raw(); if (UTF16_IS_SURROGATE_LO(a[p])) --p; reference ret(ref, p); return ret; } reference ret(ref, pos); return ret; } //! Accesses the full character at the iterator's position. pointer operator->() const { return operator*(); } //! Accesses the full character at the iterator's position. pointer operator->() { return operator*(); } }; typedef typename ustring16<TAlloc>::_ustring16_iterator iterator; typedef typename ustring16<TAlloc>::_ustring16_const_iterator const_iterator; ///----------------------/// /// end iterator classes /// ///----------------------/// //! Default constructor ustring16() : array(0), allocated(1), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif array = allocator.allocate(1); // new u16[1]; array[0] = 0x0; } //! Constructor ustring16(const ustring16<TAlloc>& other) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif *this = other; } //! Constructor from other string types template <class B, class A> ustring16(const string<B, A>& other) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif *this = other; } #ifndef USTRING_NO_STL //! Constructor from std::string template <class B, class A, typename Alloc> ustring16(const std::basic_string<B, A, Alloc>& other) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif *this = other.c_str(); } //! Constructor from iterator. template <typename Itr> ustring16(Itr first, Itr last) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif reserve(std::distance(first, last)); array[used] = 0; for (; first != last; ++first) append((uchar32_t)*first); } #endif #ifndef USTRING_CPP0X_NEWLITERALS //! Constructor for copying a character string from a pointer. ustring16(const char* const c) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif loadDataStream(c, strlen(c)); //append((uchar8_t*)c); } //! Constructor for copying a character string from a pointer with a given length. ustring16(const char* const c, u32 length) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif loadDataStream(c, length); } #endif //! Constructor for copying a UTF-8 string from a pointer. ustring16(const uchar8_t* const c) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append(c); } //! Constructor for copying a UTF-8 string from a single char. ustring16(const char c) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append((uchar32_t)c); } //! Constructor for copying a UTF-8 string from a pointer with a given length. ustring16(const uchar8_t* const c, u32 length) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append(c, length); } //! Constructor for copying a UTF-16 string from a pointer. ustring16(const uchar16_t* const c) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append(c); } //! Constructor for copying a UTF-16 string from a pointer with a given length ustring16(const uchar16_t* const c, u32 length) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append(c, length); } //! Constructor for copying a UTF-32 string from a pointer. ustring16(const uchar32_t* const c) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append(c); } //! Constructor for copying a UTF-32 from a pointer with a given length. ustring16(const uchar32_t* const c, u32 length) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif append(c, length); } //! Constructor for copying a wchar_t string from a pointer. ustring16(const wchar_t* const c) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif if (sizeof(wchar_t) == 4) append(reinterpret_cast<const uchar32_t* const>(c)); else if (sizeof(wchar_t) == 2) append(reinterpret_cast<const uchar16_t* const>(c)); else if (sizeof(wchar_t) == 1) append(reinterpret_cast<const uchar8_t* const>(c)); } //! Constructor for copying a wchar_t string from a pointer with a given length. ustring16(const wchar_t* const c, u32 length) : array(0), allocated(0), used(0) { #if __BYTE_ORDER == __BIG_ENDIAN encoding = unicode::EUTFE_UTF16_BE; #else encoding = unicode::EUTFE_UTF16_LE; #endif if (sizeof(wchar_t) == 4) append(reinterpret_cast<const uchar32_t* const>(c), length); else if (sizeof(wchar_t) == 2) append(reinterpret_cast<const uchar16_t* const>(c), length); else if (sizeof(wchar_t) == 1) append(reinterpret_cast<const uchar8_t* const>(c), length); } #ifdef USTRING_CPP0X //! Constructor for moving a ustring16 ustring16(ustring16<TAlloc>&& other) : array(other.array), encoding(other.encoding), allocated(other.allocated), used(other.used) { //std::cout << "MOVE constructor" << std::endl; other.array = 0; other.allocated = 0; other.used = 0; } #endif //! Destructor ~ustring16() { allocator.deallocate(array); // delete [] array; } //! Assignment operator ustring16& operator=(const ustring16<TAlloc>& other) { if (this == &other) return *this; used = other.size_raw(); if (used >= allocated) { allocator.deallocate(array); // delete [] array; allocated = used + 1; array = allocator.allocate(used + 1); //new u16[used]; } const uchar16_t* p = other.c_str(); for (u32 i=0; i<=used; ++i, ++p) array[i] = *p; array[used] = 0; // Validate our new UTF-16 string. validate(); return *this; } #ifdef USTRING_CPP0X //! Move assignment operator ustring16& operator=(ustring16<TAlloc>&& other) { if (this != &other) { //std::cout << "MOVE operator=" << std::endl; allocator.deallocate(array); array = other.array; allocated = other.allocated; encoding = other.encoding; used = other.used; other.array = 0; other.used = 0; } return *this; } #endif //! Assignment operator for other string types template <class B, class A> ustring16<TAlloc>& operator=(const string<B, A>& other) { *this = other.c_str(); return *this; } //! Assignment operator for UTF-8 strings ustring16<TAlloc>& operator=(const uchar8_t* const c) { if (!array) { array = allocator.allocate(1); //new u16[1]; allocated = 1; } used = 0; array[used] = 0x0; if (!c) return *this; //! Append our string now. append(c); return *this; } //! Assignment operator for UTF-16 strings ustring16<TAlloc>& operator=(const uchar16_t* const c) { if (!array) { array = allocator.allocate(1); //new u16[1]; allocated = 1; } used = 0; array[used] = 0x0; if (!c) return *this; //! Append our string now. append(c); return *this; } //! Assignment operator for UTF-32 strings ustring16<TAlloc>& operator=(const uchar32_t* const c) { if (!array) { array = allocator.allocate(1); //new u16[1]; allocated = 1; } used = 0; array[used] = 0x0; if (!c) return *this; //! Append our string now. append(c); return *this; } //! Assignment operator for wchar_t strings. /** Note that this assumes that a correct unicode string is stored in the wchar_t string. Since wchar_t changes depending on its platform, it could either be a UTF-8, -16, or -32 string. This function assumes you are storing the correct unicode encoding inside the wchar_t string. **/ ustring16<TAlloc>& operator=(const wchar_t* const c) { if (sizeof(wchar_t) == 4) *this = reinterpret_cast<const uchar32_t* const>(c); else if (sizeof(wchar_t) == 2) *this = reinterpret_cast<const uchar16_t* const>(c); else if (sizeof(wchar_t) == 1) *this = reinterpret_cast<const uchar8_t* const>(c); return *this; } //! Assignment operator for other strings. /** Note that this assumes that a correct unicode string is stored in the string. **/ template <class B> ustring16<TAlloc>& operator=(const B* const c) { if (sizeof(B) == 4) *this = reinterpret_cast<const uchar32_t* const>(c); else if (sizeof(B) == 2) *this = reinterpret_cast<const uchar16_t* const>(c); else if (sizeof(B) == 1) *this = reinterpret_cast<const uchar8_t* const>(c); return *this; } //! Direct access operator access operator [](const u32 index) { _IRR_DEBUG_BREAK_IF(index>=size()) // bad index iterator iter(*this, index); return iter.operator*(); } //! Direct access operator const access operator [](const u32 index) const { _IRR_DEBUG_BREAK_IF(index>=size()) // bad index const_iterator iter(*this, index); return iter.operator*(); } //! Equality operator bool operator ==(const uchar16_t* const str) const { if (!str) return false; u32 i; for(i=0; array[i] && str[i]; ++i) if (array[i] != str[i]) return false; return !array[i] && !str[i]; } //! Equality operator bool operator ==(const ustring16<TAlloc>& other) const { for(u32 i=0; array[i] && other.array[i]; ++i) if (array[i] != other.array[i]) return false; return used == other.used; } //! Is smaller comparator bool operator <(const ustring16<TAlloc>& other) const { for(u32 i=0; array[i] && other.array[i]; ++i) { s32 diff = array[i] - other.array[i]; if ( diff ) return diff < 0; } return used < other.used; } //! Inequality operator bool operator !=(const uchar16_t* const str) const { return !(*this == str); } //! Inequality operator bool operator !=(const ustring16<TAlloc>& other) const { return !(*this == other); } //! Returns the length of a ustring16 in full characters. //! \return Length of a ustring16 in full characters. u32 size() const { const_iterator i(*this, 0); u32 pos = 0; while (!i.atEnd()) { ++i; ++pos; } return pos; } //! Informs if the ustring is empty or not. //! \return True if the ustring is empty, false if not. bool empty() const { return (size_raw() == 0); } //! Returns a pointer to the raw UTF-16 string data. //! \return pointer to C-style NUL terminated array of UTF-16 code points. const uchar16_t* c_str() const { return array; } //! Compares the first n characters of this string with another. //! \param other Other string to compare to. //! \param n Number of characters to compare. //! \return True if the n first characters of both strings are equal. bool equalsn(const ustring16<TAlloc>& other, u32 n) const { u32 i; const uchar16_t* oa = other.c_str(); for(i=0; array[i] && oa[i] && i < n; ++i) if (array[i] != oa[i]) return false; // if one (or both) of the strings was smaller then they // are only equal if they have the same length return (i == n) || (used == other.used); } //! Compares the first n characters of this string with another. //! \param str Other string to compare to. //! \param n Number of characters to compare. //! \return True if the n first characters of both strings are equal. bool equalsn(const uchar16_t* const str, u32 n) const { if (!str) return false; u32 i; for(i=0; array[i] && str[i] && i < n; ++i) if (array[i] != str[i]) return false; // if one (or both) of the strings was smaller then they // are only equal if they have the same length return (i == n) || (array[i] == 0 && str[i] == 0); } //! Appends a character to this ustring16 //! \param character The character to append. //! \return A reference to our current string. ustring16<TAlloc>& append(uchar32_t character) { if (used + 2 >= allocated) reallocate(used + 2); if (character > 0xFFFF) { used += 2; // character will be multibyte, so split it up into a surrogate pair. uchar16_t x = static_cast<uchar16_t>(character); uchar16_t vh = UTF16_HI_SURROGATE | ((((character >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); array[used-2] = vh; array[used-1] = vl; } else { ++used; array[used-1] = character; } array[used] = 0; return *this; } //! Appends a UTF-8 string to this ustring16 //! \param other The UTF-8 string to append. //! \param length The length of the string to append. //! \return A reference to our current string. ustring16<TAlloc>& append(const uchar8_t* const other, u32 length=0xffffffff) { if (!other) return *this; // Determine if the string is long enough for a BOM. u32 len = 0; const uchar8_t* p = other; do { ++len; } while (*p++ && len < unicode::BOM_ENCODE_UTF8_LEN); // Check for BOM. unicode::EUTF_ENCODE c_bom = unicode::EUTFE_NONE; if (len == unicode::BOM_ENCODE_UTF8_LEN) { if (memcmp(other, unicode::BOM_ENCODE_UTF8, unicode::BOM_ENCODE_UTF8_LEN) == 0) c_bom = unicode::EUTFE_UTF8; } // If a BOM was found, don't include it in the string. const uchar8_t* c2 = other; if (c_bom != unicode::EUTFE_NONE) { c2 = other + unicode::BOM_UTF8_LEN; length -= unicode::BOM_UTF8_LEN; } // Calculate the size of the string to read in. len = 0; p = c2; do { ++len; } while(*p++ && len < length); if (len > length) len = length; // If we need to grow the array, do it now. if (used + len >= allocated) reallocate(used + (len * 2)); u32 start = used; // Convert UTF-8 to UTF-16. u32 pos = start; for (u32 l = 0; l<len;) { ++used; if (((c2[l] >> 6) & 0x03) == 0x02) { // Invalid continuation byte. array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; ++l; } else if (c2[l] == 0xC0 || c2[l] == 0xC1) { // Invalid byte - overlong encoding. array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; ++l; } else if ((c2[l] & 0xF8) == 0xF0) { // 4 bytes UTF-8, 2 bytes UTF-16. // Check for a full string. if ((l + 3) >= len) { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += 3; break; } // Validate. bool valid = true; u8 l2 = 0; if (valid && (((c2[l+1] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; if (valid && (((c2[l+2] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; if (valid && (((c2[l+3] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; if (!valid) { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += l2; continue; } // Decode. uchar8_t b1 = ((c2[l] & 0x7) << 2) | ((c2[l+1] >> 4) & 0x3); uchar8_t b2 = ((c2[l+1] & 0xF) << 4) | ((c2[l+2] >> 2) & 0xF); uchar8_t b3 = ((c2[l+2] & 0x3) << 6) | (c2[l+3] & 0x3F); uchar32_t v = b3 | ((uchar32_t)b2 << 8) | ((uchar32_t)b1 << 16); // Split v up into a surrogate pair. uchar16_t x = static_cast<uchar16_t>(v); uchar16_t vh = UTF16_HI_SURROGATE | ((((v >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); array[pos++] = vh; array[pos++] = vl; l += 4; ++used; // Using two shorts this time, so increase used by 1. } else if ((c2[l] & 0xF0) == 0xE0) { // 3 bytes UTF-8, 1 byte UTF-16. // Check for a full string. if ((l + 2) >= len) { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += 2; break; } // Validate. bool valid = true; u8 l2 = 0; if (valid && (((c2[l+1] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; if (valid && (((c2[l+2] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; if (!valid) { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += l2; continue; } // Decode. uchar8_t b1 = ((c2[l] & 0xF) << 4) | ((c2[l+1] >> 2) & 0xF); uchar8_t b2 = ((c2[l+1] & 0x3) << 6) | (c2[l+2] & 0x3F); uchar16_t ch = b2 | ((uchar16_t)b1 << 8); array[pos++] = ch; l += 3; } else if ((c2[l] & 0xE0) == 0xC0) { // 2 bytes UTF-8, 1 byte UTF-16. // Check for a full string. if ((l + 1) >= len) { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; l += 1; break; } // Validate. if (((c2[l+1] >> 6) & 0x03) != 0x02) { array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; ++l; continue; } // Decode. uchar8_t b1 = (c2[l] >> 2) & 0x7; uchar8_t b2 = ((c2[l] & 0x3) << 6) | (c2[l+1] & 0x3F); uchar16_t ch = b2 | ((uchar16_t)b1 << 8); array[pos++] = ch; l += 2; } else { // 1 byte UTF-8, 1 byte UTF-16. // Validate. if (c2[l] > 0x7F) { // Values above 0xF4 are restricted and aren't used. By now, anything above 0x7F is invalid. array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; } else array[pos++] = static_cast<uchar16_t>(c2[l]); ++l; } } array[used] = 0; // Validate our new UTF-16 string. validate(); return *this; } //! Appends a UTF-16 string to this ustring16 //! \param other The UTF-16 string to append. //! \param length The length of the string to append. //! \return A reference to our current string. ustring16<TAlloc>& append(const uchar16_t* const other, u32 length=0xffffffff) { if (!other) return *this; // Determine if the string is long enough for a BOM. u32 len = 0; const uchar16_t* p = other; do { ++len; } while (*p++ && len < unicode::BOM_ENCODE_UTF16_LEN); // Check for the BOM to determine the string's endianness. unicode::EUTF_ENDIAN c_end = unicode::EUTFEE_NATIVE; if (memcmp(other, unicode::BOM_ENCODE_UTF16_LE, unicode::BOM_ENCODE_UTF16_LEN) == 0) c_end = unicode::EUTFEE_LITTLE; else if (memcmp(other, unicode::BOM_ENCODE_UTF16_BE, unicode::BOM_ENCODE_UTF16_LEN) == 0) c_end = unicode::EUTFEE_BIG; // If a BOM was found, don't include it in the string. const uchar16_t* c2 = other; if (c_end != unicode::EUTFEE_NATIVE) { c2 = other + unicode::BOM_UTF16_LEN; length -= unicode::BOM_UTF16_LEN; } // Calculate the size of the string to read in. len = 0; p = c2; do { ++len; } while(*p++ && len < length); if (len > length) len = length; // If we need to grow the size of the array, do it now. if (used + len >= allocated) reallocate(used + (len * 2)); u32 start = used; used += len; // Copy the string now. unicode::EUTF_ENDIAN m_end = getEndianness(); for (u32 l = start; l < start + len; ++l) { array[l] = (uchar16_t)c2[l]; if (c_end != unicode::EUTFEE_NATIVE && c_end != m_end) array[l] = unicode::swapEndian16(array[l]); } array[used] = 0; // Validate our new UTF-16 string. validate(); return *this; } //! Appends a UTF-32 string to this ustring16 //! \param other The UTF-32 string to append. //! \param length The length of the string to append. //! \return A reference to our current string. ustring16<TAlloc>& append(const uchar32_t* const other, u32 length=0xffffffff) { if (!other) return *this; // Check for the BOM to determine the string's endianness. unicode::EUTF_ENDIAN c_end = unicode::EUTFEE_NATIVE; if (memcmp(other, unicode::BOM_ENCODE_UTF32_LE, unicode::BOM_ENCODE_UTF32_LEN) == 0) c_end = unicode::EUTFEE_LITTLE; else if (memcmp(other, unicode::BOM_ENCODE_UTF32_BE, unicode::BOM_ENCODE_UTF32_LEN) == 0) c_end = unicode::EUTFEE_BIG; // If a BOM was found, don't include it in the string. const uchar32_t* c2 = other; if (c_end != unicode::EUTFEE_NATIVE) { c2 = other + unicode::BOM_UTF32_LEN; length -= unicode::BOM_UTF32_LEN; } // Calculate the size of the string to read in. u32 len = 0; const uchar32_t* p = c2; do { ++len; } while(*p++ && len < length); if (len > length) len = length; // If we need to grow the size of the array, do it now. // In case all of the UTF-32 string is split into surrogate pairs, do len * 2. if (used + (len * 2) >= allocated) reallocate(used + ((len * 2) * 2)); u32 start = used; // Convert UTF-32 to UTF-16. unicode::EUTF_ENDIAN m_end = getEndianness(); u32 pos = start; for (u32 l = 0; l<len; ++l) { ++used; uchar32_t ch = c2[l]; if (c_end != unicode::EUTFEE_NATIVE && c_end != m_end) ch = unicode::swapEndian32(ch); if (ch > 0xFFFF) { // Split ch up into a surrogate pair as it is over 16 bits long. uchar16_t x = static_cast<uchar16_t>(ch); uchar16_t vh = UTF16_HI_SURROGATE | ((((ch >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); array[pos++] = vh; array[pos++] = vl; ++used; // Using two shorts, so increased used again. } else if (ch >= 0xD800 && ch <= 0xDFFF) { // Between possible UTF-16 surrogates (invalid!) array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; } else array[pos++] = static_cast<uchar16_t>(ch); } array[used] = 0; // Validate our new UTF-16 string. validate(); return *this; } //! Appends a ustring16 to this ustring16 //! \param other The string to append to this one. //! \return A reference to our current string. ustring16<TAlloc>& append(const ustring16<TAlloc>& other) { const uchar16_t* oa = other.c_str(); u32 len = other.size_raw(); if (used + len >= allocated) reallocate(used + len); for (u32 l=0; l<len; ++l) array[used+l] = oa[l]; used += len; array[used] = 0; return *this; } //! Appends a certain amount of characters of a ustring16 to this ustring16. //! \param other The string to append to this one. //! \param length How many characters of the other string to add to this one. //! \return A reference to our current string. ustring16<TAlloc>& append(const ustring16<TAlloc>& other, u32 length) { if (other.size() == 0) return *this; if (other.size() < length) { append(other); return *this; } if (used + length * 2 >= allocated) reallocate(used + length * 2); const_iterator iter(other, 0); u32 l = length; while (!iter.atEnd() && l) { uchar32_t c = *iter; append(c); ++iter; --l; } return *this; } //! Reserves some memory. //! \param count The amount of characters to reserve. void reserve(u32 count) { if (count < allocated) return; reallocate(count); } //! Finds first occurrence of character. //! \param c The character to search for. //! \return Position where the character has been found, or -1 if not found. s32 findFirst(uchar32_t c) const { const_iterator i(*this, 0); s32 pos = 0; while (!i.atEnd()) { uchar32_t t = *i; if (c == t) return pos; ++pos; ++i; } return -1; } //! Finds first occurrence of a character of a list. //! \param c A list of characters to find. For example if the method should find the first occurrence of 'a' or 'b', this parameter should be "ab". //! \param count The amount of characters in the list. Usually, this should be strlen(c). //! \return Position where one of the characters has been found, or -1 if not found. s32 findFirstChar(const uchar32_t* const c, u32 count=1) const { if (!c || !count) return -1; const_iterator i(*this, 0); s32 pos = 0; while (!i.atEnd()) { uchar32_t t = *i; for (u32 j=0; j<count; ++j) if (t == c[j]) return pos; ++pos; ++i; } return -1; } //! Finds first position of a character not in a given list. //! \param c A list of characters to NOT find. For example if the method should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab". //! \param count The amount of characters in the list. Usually, this should be strlen(c). //! \return Position where the character has been found, or -1 if not found. s32 findFirstCharNotInList(const uchar32_t* const c, u32 count=1) const { if (!c || !count) return -1; const_iterator i(*this, 0); s32 pos = 0; while (!i.atEnd()) { uchar32_t t = *i; u32 j; for (j=0; j<count; ++j) if (t == c[j]) break; if (j==count) return pos; ++pos; ++i; } return -1; } //! Finds last position of a character not in a given list. //! \param c A list of characters to NOT find. For example if the method should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab". //! \param count The amount of characters in the list. Usually, this should be strlen(c). //! \return Position where the character has been found, or -1 if not found. s32 findLastCharNotInList(const uchar32_t* const c, u32 count=1) const { if (!c || !count) return -1; const_iterator i(end()); --i; s32 pos = size() - 1; while (!i.atStart()) { uchar32_t t = *i; u32 j; for (j=0; j<count; ++j) if (t == c[j]) break; if (j==count) return pos; --pos; --i; } return -1; } //! Finds next occurrence of character. //! \param c The character to search for. //! \param startPos The position in the string to start searching. //! \return Position where the character has been found, or -1 if not found. s32 findNext(uchar32_t c, u32 startPos) const { const_iterator i(*this, startPos); s32 pos = startPos; while (!i.atEnd()) { uchar32_t t = *i; if (t == c) return pos; ++pos; ++i; } return -1; } //! Finds last occurrence of character. //! \param c The character to search for. //! \param start The start position of the reverse search ( default = -1, on end ). //! \return Position where the character has been found, or -1 if not found. s32 findLast(uchar32_t c, s32 start = -1) const { u32 s = size(); start = core::clamp ( start < 0 ? (s32)s : start, 0, (s32)s ) - 1; const_iterator i(*this, start); u32 pos = start; while (!i.atStart()) { uchar32_t t = *i; if (t == c) return pos; --pos; --i; } return -1; } //! Finds last occurrence of a character in a list. //! \param c A list of strings to find. For example if the method should find the last occurrence of 'a' or 'b', this parameter should be "ab". //! \param count The amount of characters in the list. Usually, this should be strlen(c). //! \return Position where one of the characters has been found, or -1 if not found. s32 findLastChar(const uchar32_t* const c, u32 count=1) const { if (!c || !count) return -1; const_iterator i(end()); --i; s32 pos = size(); while (!i.atStart()) { uchar32_t t = *i; for (u32 j=0; j<count; ++j) if (t == c[j]) return pos; --pos; --i; } return -1; } //! Finds another ustring16 in this ustring16. //! \param str The string to find. //! \param start The start position of the search. //! \return Positions where the ustring16 has been found, or -1 if not found. s32 find(const ustring16<TAlloc>& str, const u32 start = 0) const { u32 my_size = size(); u32 their_size = str.size(); if (their_size == 0 || my_size - start < their_size) return -1; const_iterator i(*this, start); s32 pos = start; while (!i.atEnd()) { const_iterator i2(i); const_iterator j(str, 0); uchar32_t t1 = (uchar32_t)*i2; uchar32_t t2 = (uchar32_t)*j; while (t1 == t2) { ++i2; ++j; if (j.atEnd()) return pos; t1 = (uchar32_t)*i2; t2 = (uchar32_t)*j; } ++i; ++pos; } return -1; } //! Finds another ustring16 in this ustring16. //! \param str The string to find. //! \param start The start position of the search. //! \return Positions where the string has been found, or -1 if not found. s32 find_raw(const ustring16<TAlloc>& str, const u32 start = 0) const { const uchar16_t* data = str.c_str(); if (data && *data) { u32 len = 0; while (data[len]) ++len; if (len > used) return -1; for (u32 i=start; i<=used-len; ++i) { u32 j=0; while(data[j] && array[i+j] == data[j]) ++j; if (!data[j]) return i; } } return -1; } //! Returns a substring. //! \param begin: Start of substring. //! \param length: Length of substring. //! \return A reference to our current string. ustring16<TAlloc> subString(u32 begin, s32 length) const { u32 len = size(); // if start after ustring16 // or no proper substring length if ((length <= 0) || (begin>=len)) return ustring16<TAlloc>(""); // clamp length to maximal value if ((length+begin) > len) length = len-begin; ustring16<TAlloc> o; o.reserve((length+1) * 2); const_iterator i(*this, begin); while (!i.atEnd() && length) { o.append(*i); ++i; --length; } return o; } //! Appends a character to this ustring16. //! \param c Character to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (char c) { append((uchar32_t)c); return *this; } //! Appends a character to this ustring16. //! \param c Character to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (uchar32_t c) { append(c); return *this; } //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (short c) { append(core::stringc(c)); return *this; } //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (unsigned short c) { append(core::stringc(c)); return *this; } #ifdef USTRING_CPP0X_NEWLITERALS //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (int c) { append(core::stringc(c)); return *this; } //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (unsigned int c) { append(core::stringc(c)); return *this; } #endif //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (long c) { append(core::stringc(c)); return *this; } //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (unsigned long c) { append(core::stringc(c)); return *this; } //! Appends a number to this ustring16. //! \param c Number to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (double c) { append(core::stringc(c)); return *this; } //! Appends a char ustring16 to this ustring16. //! \param c Char ustring16 to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (const uchar16_t* const c) { append(c); return *this; } //! Appends a ustring16 to this ustring16. //! \param other ustring16 to append. //! \return A reference to our current string. ustring16<TAlloc>& operator += (const ustring16<TAlloc>& other) { append(other); return *this; } //! Replaces all characters of a given type with another one. //! \param toReplace Character to replace. //! \param replaceWith Character replacing the old one. //! \return A reference to our current string. ustring16<TAlloc>& replace(uchar32_t toReplace, uchar32_t replaceWith) { iterator i(*this, 0); while (!i.atEnd()) { typename ustring16<TAlloc>::access a = *i; if ((uchar32_t)a == toReplace) a = replaceWith; ++i; } return *this; } //! Replaces all instances of a string with another one. //! \param toReplace The string to replace. //! \param replaceWith The string replacing the old one. //! \return A reference to our current string. ustring16<TAlloc>& replace(const ustring16<TAlloc>& toReplace, const ustring16<TAlloc>& replaceWith) { if (toReplace.size() == 0) return *this; const uchar16_t* other = toReplace.c_str(); const uchar16_t* replace = replaceWith.c_str(); const u32 other_size = toReplace.size_raw(); const u32 replace_size = replaceWith.size_raw(); // Determine the delta. The algorithm will change depending on the delta. s32 delta = replace_size - other_size; // A character for character replace. The string will not shrink or grow. if (delta == 0) { s32 pos = 0; while ((pos = find_raw(other, pos)) != -1) { for (u32 i = 0; i < replace_size; ++i) array[pos + i] = replace[i]; ++pos; } return *this; } // We are going to be removing some characters. The string will shrink. if (delta < 0) { u32 i = 0; for (u32 pos = 0; pos <= used; ++i, ++pos) { // Is this potentially a match? if (array[pos] == *other) { // Check to see if we have a match. u32 j; for (j = 0; j < other_size; ++j) { if (array[pos + j] != other[j]) break; } // If we have a match, replace characters. if (j == other_size) { for (j = 0; j < replace_size; ++j) array[i + j] = replace[j]; i += replace_size - 1; pos += other_size - 1; continue; } } // No match found, just copy characters. array[i - 1] = array[pos]; } array[i] = 0; used = i; return *this; } // We are going to be adding characters, so the string size will increase. // Count the number of times toReplace exists in the string so we can allocate the new size. u32 find_count = 0; s32 pos = 0; while ((pos = find_raw(other, pos)) != -1) { ++find_count; ++pos; } // Re-allocate the string now, if needed. u32 len = delta * find_count; if (used + len >= allocated) reallocate(used + len); // Start replacing. pos = 0; while ((pos = find_raw(other, pos)) != -1) { uchar16_t* start = array + pos + other_size - 1; uchar16_t* ptr = array + used; uchar16_t* end = array + used + delta; // Shift characters to make room for the string. while (ptr != start) { *end = *ptr; --ptr; --end; } // Add the new string now. for (u32 i = 0; i < replace_size; ++i) array[pos + i] = replace[i]; pos += replace_size; used += delta; } // Terminate the string and return ourself. array[used] = 0; return *this; } //! Removes characters from a ustring16.. //! \param c The character to remove. //! \return A reference to our current string. ustring16<TAlloc>& remove(uchar32_t c) { u32 pos = 0; u32 found = 0; u32 len = (c > 0xFFFF ? 2 : 1); // Remove characters equal to the size of c as a UTF-16 character. for (u32 i=0; i<=used; ++i) { uchar32_t uc32 = 0; if (!UTF16_IS_SURROGATE_HI(array[i])) uc32 |= array[i]; else if (i + 1 <= used) { // Convert the surrogate pair into a single UTF-32 character. uc32 = unicode::toUTF32(array[i], array[i + 1]); } u32 len2 = (uc32 > 0xFFFF ? 2 : 1); if (uc32 == c) { found += len; continue; } array[pos++] = array[i]; if (len2 == 2) array[pos++] = array[++i]; } used -= found; array[used] = 0; return *this; } //! Removes a ustring16 from the ustring16. //! \param toRemove The string to remove. //! \return A reference to our current string. ustring16<TAlloc>& remove(const ustring16<TAlloc>& toRemove) { u32 size = toRemove.size_raw(); if (size == 0) return *this; const uchar16_t* tra = toRemove.c_str(); u32 pos = 0; u32 found = 0; for (u32 i=0; i<=used; ++i) { u32 j = 0; while (j < size) { if (array[i + j] != tra[j]) break; ++j; } if (j == size) { found += size; i += size - 1; continue; } array[pos++] = array[i]; } used -= found; array[used] = 0; return *this; } //! Removes characters from the ustring16. //! \param characters The characters to remove. //! \return A reference to our current string. ustring16<TAlloc>& removeChars(const ustring16<TAlloc>& characters) { if (characters.size_raw() == 0) return *this; u32 pos = 0; u32 found = 0; const_iterator iter(characters); for (u32 i=0; i<=used; ++i) { uchar32_t uc32 = 0; if (!UTF16_IS_SURROGATE_HI(array[i])) uc32 |= array[i]; else if (i + 1 <= used) { // Convert the surrogate pair into a single UTF-32 character. uc32 = unicode::toUTF32(array[i], array[i+1]); } u32 len2 = (uc32 > 0xFFFF ? 2 : 1); bool cont = false; iter.toStart(); while (!iter.atEnd()) { uchar32_t c = *iter; if (uc32 == c) { found += (c > 0xFFFF ? 2 : 1); // Remove characters equal to the size of c as a UTF-16 character. ++i; cont = true; break; } ++iter; } if (cont) continue; array[pos++] = array[i]; if (len2 == 2) array[pos++] = array[++i]; } used -= found; array[used] = 0; return *this; } //! Trims the ustring16. //! Removes the specified characters (by default, Latin-1 whitespace) from the begining and the end of the ustring16. //! \param whitespace The characters that are to be considered as whitespace. //! \return A reference to our current string. ustring16<TAlloc>& trim(const ustring16<TAlloc>& whitespace = " \t\n\r") { core::array<uchar32_t> utf32white = whitespace.toUTF32(); // find start and end of the substring without the specified characters const s32 begin = findFirstCharNotInList(utf32white.const_pointer(), whitespace.used + 1); if (begin == -1) return (*this=""); const s32 end = findLastCharNotInList(utf32white.const_pointer(), whitespace.used + 1); return (*this = subString(begin, (end +1) - begin)); } //! Erases a character from the ustring16. //! May be slow, because all elements following after the erased element have to be copied. //! \param index Index of element to be erased. //! \return A reference to our current string. ustring16<TAlloc>& erase(u32 index) { _IRR_DEBUG_BREAK_IF(index>used) // access violation iterator i(*this, index); uchar32_t t = *i; u32 len = (t > 0xFFFF ? 2 : 1); for (u32 j = static_cast<u32>(i.getPos()) + len; j <= used; ++j) array[j - len] = array[j]; used -= len; array[used] = 0; return *this; } //! Validate the existing ustring16, checking for valid surrogate pairs and checking for proper termination. //! \return A reference to our current string. ustring16<TAlloc>& validate() { // Validate all unicode characters. for (u32 i=0; i<allocated; ++i) { // Terminate on existing null. if (array[i] == 0) { used = i; return *this; } if (UTF16_IS_SURROGATE(array[i])) { if (((i+1) >= allocated) || UTF16_IS_SURROGATE_LO(array[i])) array[i] = unicode::UTF_REPLACEMENT_CHARACTER; else if (UTF16_IS_SURROGATE_HI(array[i]) && !UTF16_IS_SURROGATE_LO(array[i+1])) array[i] = unicode::UTF_REPLACEMENT_CHARACTER; ++i; } if (array[i] >= 0xFDD0 && array[i] <= 0xFDEF) array[i] = unicode::UTF_REPLACEMENT_CHARACTER; } // terminate used = 0; if (allocated > 0) { used = allocated - 1; array[used] = 0; } return *this; } //! Gets the last char of the ustring16, or 0. //! \return The last char of the ustring16, or 0. uchar32_t lastChar() const { if (used < 1) return 0; if (UTF16_IS_SURROGATE_LO(array[used-1])) { // Make sure we have a paired surrogate. if (used < 2) return 0; // Check for an invalid surrogate. if (!UTF16_IS_SURROGATE_HI(array[used-2])) return 0; // Convert the surrogate pair into a single UTF-32 character. return unicode::toUTF32(array[used-2], array[used-1]); } else { return array[used-1]; } } //! Split the ustring16 into parts. /** This method will split a ustring16 at certain delimiter characters into the container passed in as reference. The type of the container has to be given as template parameter. It must provide a push_back and a size method. \param ret The result container \param c C-style ustring16 of delimiter characters \param count Number of delimiter characters \param ignoreEmptyTokens Flag to avoid empty substrings in the result container. If two delimiters occur without a character in between, an empty substring would be placed in the result. If this flag is set, only non-empty strings are stored. \param keepSeparators Flag which allows to add the separator to the result ustring16. If this flag is true, the concatenation of the substrings results in the original ustring16. Otherwise, only the characters between the delimiters are returned. \return The number of resulting substrings */ template<class container> u32 split(container& ret, const uchar32_t* const c, u32 count=1, bool ignoreEmptyTokens=true, bool keepSeparators=false) const { if (!c) return 0; const_iterator i(*this); const u32 oldSize=ret.size(); u32 pos = 0; u32 lastpos = 0; u32 lastpospos = 0; bool lastWasSeparator = false; while (!i.atEnd()) { uchar32_t ch = *i; bool foundSeparator = false; for (u32 j=0; j<count; ++j) { if (ch == c[j]) { if ((!ignoreEmptyTokens || pos - lastpos != 0) && !lastWasSeparator) ret.push_back(ustring16<TAlloc>(&array[lastpospos], pos - lastpos)); foundSeparator = true; lastpos = (keepSeparators ? pos : pos + 1); lastpospos = (keepSeparators ? i.getPos() : i.getPos() + 1); break; } } lastWasSeparator = foundSeparator; ++pos; ++i; } u32 s = size() + 1; if (s > lastpos) ret.push_back(ustring16<TAlloc>(&array[lastpospos], s - lastpos)); return ret.size()-oldSize; } //! Split the ustring16 into parts. /** This method will split a ustring16 at certain delimiter characters into the container passed in as reference. The type of the container has to be given as template parameter. It must provide a push_back and a size method. \param ret The result container \param c A unicode string of delimiter characters \param ignoreEmptyTokens Flag to avoid empty substrings in the result container. If two delimiters occur without a character in between, an empty substring would be placed in the result. If this flag is set, only non-empty strings are stored. \param keepSeparators Flag which allows to add the separator to the result ustring16. If this flag is true, the concatenation of the substrings results in the original ustring16. Otherwise, only the characters between the delimiters are returned. \return The number of resulting substrings */ template<class container> u32 split(container& ret, const ustring16<TAlloc>& c, bool ignoreEmptyTokens=true, bool keepSeparators=false) const { core::array<uchar32_t> v = c.toUTF32(); return split(ret, v.pointer(), v.size(), ignoreEmptyTokens, keepSeparators); } //! Gets the size of the allocated memory buffer for the string. //! \return The size of the allocated memory buffer. u32 capacity() const { return allocated; } //! Returns the raw number of UTF-16 code points in the string which includes the individual surrogates. //! \return The raw number of UTF-16 code points, excluding the trialing NUL. u32 size_raw() const { return used; } //! Inserts a character into the string. //! \param c The character to insert. //! \param pos The position to insert the character. //! \return A reference to our current string. ustring16<TAlloc>& insert(uchar32_t c, u32 pos) { u8 len = (c > 0xFFFF ? 2 : 1); if (used + len >= allocated) reallocate(used + len); used += len; iterator iter(*this, pos); for (u32 i = used - 2; i > iter.getPos(); --i) array[i] = array[i - len]; if (c > 0xFFFF) { // c will be multibyte, so split it up into a surrogate pair. uchar16_t x = static_cast<uchar16_t>(c); uchar16_t vh = UTF16_HI_SURROGATE | ((((c >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); array[iter.getPos()] = vh; array[iter.getPos()+1] = vl; } else { array[iter.getPos()] = static_cast<uchar16_t>(c); } array[used] = 0; return *this; } //! Inserts a string into the string. //! \param c The string to insert. //! \param pos The position to insert the string. //! \return A reference to our current string. ustring16<TAlloc>& insert(const ustring16<TAlloc>& c, u32 pos) { u32 len = c.size_raw(); if (len == 0) return *this; if (used + len >= allocated) reallocate(used + len); used += len; iterator iter(*this, pos); for (u32 i = used - 2; i > iter.getPos() + len; --i) array[i] = array[i - len]; const uchar16_t* s = c.c_str(); for (u32 i = 0; i < len; ++i) { array[pos++] = *s; ++s; } array[used] = 0; return *this; } //! Inserts a character into the string. //! \param c The character to insert. //! \param pos The position to insert the character. //! \return A reference to our current string. ustring16<TAlloc>& insert_raw(uchar16_t c, u32 pos) { if (used + 1 >= allocated) reallocate(used + 1); ++used; for (u32 i = used - 1; i > pos; --i) array[i] = array[i - 1]; array[pos] = c; array[used] = 0; return *this; } //! Removes a character from string. //! \param pos Position of the character to remove. //! \return A reference to our current string. ustring16<TAlloc>& erase_raw(u32 pos) { for (u32 i=pos; i<=used; ++i) { array[i] = array[i + 1]; } --used; array[used] = 0; return *this; } //! Replaces a character in the string. //! \param c The new character. //! \param pos The position of the character to replace. //! \return A reference to our current string. ustring16<TAlloc>& replace_raw(uchar16_t c, u32 pos) { array[pos] = c; return *this; } //! Returns an iterator to the beginning of the string. //! \return An iterator to the beginning of the string. iterator begin() { iterator i(*this, 0); return i; } //! Returns an iterator to the beginning of the string. //! \return An iterator to the beginning of the string. const_iterator begin() const { const_iterator i(*this, 0); return i; } //! Returns an iterator to the beginning of the string. //! \return An iterator to the beginning of the string. const_iterator cbegin() const { const_iterator i(*this, 0); return i; } //! Returns an iterator to the end of the string. //! \return An iterator to the end of the string. iterator end() { iterator i(*this, 0); i.toEnd(); return i; } //! Returns an iterator to the end of the string. //! \return An iterator to the end of the string. const_iterator end() const { const_iterator i(*this, 0); i.toEnd(); return i; } //! Returns an iterator to the end of the string. //! \return An iterator to the end of the string. const_iterator cend() const { const_iterator i(*this, 0); i.toEnd(); return i; } //! Converts the string to a UTF-8 encoded string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return A string containing the UTF-8 encoded string. core::string<uchar8_t> toUTF8_s(const bool addBOM = false) const { core::string<uchar8_t> ret; ret.reserve(used * 4 + (addBOM ? unicode::BOM_UTF8_LEN : 0) + 1); const_iterator iter(*this, 0); // Add the byte order mark if the user wants it. if (addBOM) { ret.append(unicode::BOM_ENCODE_UTF8[0]); ret.append(unicode::BOM_ENCODE_UTF8[1]); ret.append(unicode::BOM_ENCODE_UTF8[2]); } while (!iter.atEnd()) { uchar32_t c = *iter; if (c > 0xFFFF) { // 4 bytes uchar8_t b1 = (0x1E << 3) | ((c >> 18) & 0x7); uchar8_t b2 = (0x2 << 6) | ((c >> 12) & 0x3F); uchar8_t b3 = (0x2 << 6) | ((c >> 6) & 0x3F); uchar8_t b4 = (0x2 << 6) | (c & 0x3F); ret.append(b1); ret.append(b2); ret.append(b3); ret.append(b4); } else if (c > 0x7FF) { // 3 bytes uchar8_t b1 = (0xE << 4) | ((c >> 12) & 0xF); uchar8_t b2 = (0x2 << 6) | ((c >> 6) & 0x3F); uchar8_t b3 = (0x2 << 6) | (c & 0x3F); ret.append(b1); ret.append(b2); ret.append(b3); } else if (c > 0x7F) { // 2 bytes uchar8_t b1 = (0x6 << 5) | ((c >> 6) & 0x1F); uchar8_t b2 = (0x2 << 6) | (c & 0x3F); ret.append(b1); ret.append(b2); } else { // 1 byte ret.append(static_cast<uchar8_t>(c)); } ++iter; } return ret; } //! Converts the string to a UTF-8 encoded string array. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return An array containing the UTF-8 encoded string. core::array<uchar8_t> toUTF8(const bool addBOM = false) const { core::array<uchar8_t> ret(used * 4 + (addBOM ? unicode::BOM_UTF8_LEN : 0) + 1); const_iterator iter(*this, 0); // Add the byte order mark if the user wants it. if (addBOM) { ret.push_back(unicode::BOM_ENCODE_UTF8[0]); ret.push_back(unicode::BOM_ENCODE_UTF8[1]); ret.push_back(unicode::BOM_ENCODE_UTF8[2]); } while (!iter.atEnd()) { uchar32_t c = *iter; if (c > 0xFFFF) { // 4 bytes uchar8_t b1 = (0x1E << 3) | ((c >> 18) & 0x7); uchar8_t b2 = (0x2 << 6) | ((c >> 12) & 0x3F); uchar8_t b3 = (0x2 << 6) | ((c >> 6) & 0x3F); uchar8_t b4 = (0x2 << 6) | (c & 0x3F); ret.push_back(b1); ret.push_back(b2); ret.push_back(b3); ret.push_back(b4); } else if (c > 0x7FF) { // 3 bytes uchar8_t b1 = (0xE << 4) | ((c >> 12) & 0xF); uchar8_t b2 = (0x2 << 6) | ((c >> 6) & 0x3F); uchar8_t b3 = (0x2 << 6) | (c & 0x3F); ret.push_back(b1); ret.push_back(b2); ret.push_back(b3); } else if (c > 0x7F) { // 2 bytes uchar8_t b1 = (0x6 << 5) | ((c >> 6) & 0x1F); uchar8_t b2 = (0x2 << 6) | (c & 0x3F); ret.push_back(b1); ret.push_back(b2); } else { // 1 byte ret.push_back(static_cast<uchar8_t>(c)); } ++iter; } ret.push_back(0); return ret; } #ifdef USTRING_CPP0X_NEWLITERALS // C++0x //! Converts the string to a UTF-16 encoded string. //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return A string containing the UTF-16 encoded string. core::string<char16_t> toUTF16_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { core::string<char16_t> ret; ret.reserve(used + (addBOM ? unicode::BOM_UTF16_LEN : 0) + 1); // Add the BOM if specified. if (addBOM) { if (endian == unicode::EUTFEE_NATIVE) ret[0] = unicode::BOM; else if (endian == unicode::EUTFEE_LITTLE) { uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ret.c_str()); *ptr8++ = unicode::BOM_ENCODE_UTF16_LE[0]; *ptr8 = unicode::BOM_ENCODE_UTF16_LE[1]; } else { uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ret.c_str()); *ptr8++ = unicode::BOM_ENCODE_UTF16_BE[0]; *ptr8 = unicode::BOM_ENCODE_UTF16_BE[1]; } } ret.append(array); if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) { char16_t* ptr = ret.c_str(); for (u32 i = 0; i < ret.size(); ++i) *ptr++ = unicode::swapEndian16(*ptr); } return ret; } #endif //! Converts the string to a UTF-16 encoded string array. //! Unfortunately, no toUTF16_s() version exists due to limitations with Irrlicht's string class. //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return An array containing the UTF-16 encoded string. core::array<uchar16_t> toUTF16(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { core::array<uchar16_t> ret(used + (addBOM ? unicode::BOM_UTF16_LEN : 0) + 1); uchar16_t* ptr = ret.pointer(); // Add the BOM if specified. if (addBOM) { if (endian == unicode::EUTFEE_NATIVE) *ptr = unicode::BOM; else if (endian == unicode::EUTFEE_LITTLE) { uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ptr); *ptr8++ = unicode::BOM_ENCODE_UTF16_LE[0]; *ptr8 = unicode::BOM_ENCODE_UTF16_LE[1]; } else { uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ptr); *ptr8++ = unicode::BOM_ENCODE_UTF16_BE[0]; *ptr8 = unicode::BOM_ENCODE_UTF16_BE[1]; } ++ptr; } memcpy((void*)ptr, (void*)array, used * sizeof(uchar16_t)); if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) { for (u32 i = 0; i <= used; ++i) ptr[i] = unicode::swapEndian16(ptr[i]); } ret.set_used(used + (addBOM ? unicode::BOM_UTF16_LEN : 0)); ret.push_back(0); return ret; } #ifdef USTRING_CPP0X_NEWLITERALS // C++0x //! Converts the string to a UTF-32 encoded string. //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return A string containing the UTF-32 encoded string. core::string<char32_t> toUTF32_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { core::string<char32_t> ret; ret.reserve(size() + 1 + (addBOM ? unicode::BOM_UTF32_LEN : 0)); const_iterator iter(*this, 0); // Add the BOM if specified. if (addBOM) { if (endian == unicode::EUTFEE_NATIVE) ret.append(unicode::BOM); else { union { uchar32_t full; u8 chunk[4]; } t; if (endian == unicode::EUTFEE_LITTLE) { t.chunk[0] = unicode::BOM_ENCODE_UTF32_LE[0]; t.chunk[1] = unicode::BOM_ENCODE_UTF32_LE[1]; t.chunk[2] = unicode::BOM_ENCODE_UTF32_LE[2]; t.chunk[3] = unicode::BOM_ENCODE_UTF32_LE[3]; } else { t.chunk[0] = unicode::BOM_ENCODE_UTF32_BE[0]; t.chunk[1] = unicode::BOM_ENCODE_UTF32_BE[1]; t.chunk[2] = unicode::BOM_ENCODE_UTF32_BE[2]; t.chunk[3] = unicode::BOM_ENCODE_UTF32_BE[3]; } ret.append(t.full); } } while (!iter.atEnd()) { uchar32_t c = *iter; if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) c = unicode::swapEndian32(c); ret.append(c); ++iter; } return ret; } #endif //! Converts the string to a UTF-32 encoded string array. //! Unfortunately, no toUTF32_s() version exists due to limitations with Irrlicht's string class. //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return An array containing the UTF-32 encoded string. core::array<uchar32_t> toUTF32(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { core::array<uchar32_t> ret(size() + (addBOM ? unicode::BOM_UTF32_LEN : 0) + 1); const_iterator iter(*this, 0); // Add the BOM if specified. if (addBOM) { if (endian == unicode::EUTFEE_NATIVE) ret.push_back(unicode::BOM); else { union { uchar32_t full; u8 chunk[4]; } t; if (endian == unicode::EUTFEE_LITTLE) { t.chunk[0] = unicode::BOM_ENCODE_UTF32_LE[0]; t.chunk[1] = unicode::BOM_ENCODE_UTF32_LE[1]; t.chunk[2] = unicode::BOM_ENCODE_UTF32_LE[2]; t.chunk[3] = unicode::BOM_ENCODE_UTF32_LE[3]; } else { t.chunk[0] = unicode::BOM_ENCODE_UTF32_BE[0]; t.chunk[1] = unicode::BOM_ENCODE_UTF32_BE[1]; t.chunk[2] = unicode::BOM_ENCODE_UTF32_BE[2]; t.chunk[3] = unicode::BOM_ENCODE_UTF32_BE[3]; } ret.push_back(t.full); } } ret.push_back(0); while (!iter.atEnd()) { uchar32_t c = *iter; if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) c = unicode::swapEndian32(c); ret.push_back(c); ++iter; } return ret; } //! Converts the string to a wchar_t encoded string. /** The size of a wchar_t changes depending on the platform. This function will store a correct UTF-8, -16, or -32 encoded string depending on the size of a wchar_t. **/ //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return A string containing the wchar_t encoded string. core::string<wchar_t> toWCHAR_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { if (sizeof(wchar_t) == 4) { core::array<uchar32_t> a(toUTF32(endian, addBOM)); core::stringw ret(a.pointer()); return ret; } else if (sizeof(wchar_t) == 2) { if (endian == unicode::EUTFEE_NATIVE && addBOM == false) { core::stringw ret(array); return ret; } else { core::array<uchar16_t> a(toUTF16(endian, addBOM)); core::stringw ret(a.pointer()); return ret; } } else if (sizeof(wchar_t) == 1) { core::array<uchar8_t> a(toUTF8(addBOM)); core::stringw ret(a.pointer()); return ret; } // Shouldn't happen. return core::stringw(); } //! Converts the string to a wchar_t encoded string array. /** The size of a wchar_t changes depending on the platform. This function will store a correct UTF-8, -16, or -32 encoded string depending on the size of a wchar_t. **/ //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return An array containing the wchar_t encoded string. core::array<wchar_t> toWCHAR(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { if (sizeof(wchar_t) == 4) { core::array<uchar32_t> a(toUTF32(endian, addBOM)); core::array<wchar_t> ret(a.size()); ret.set_used(a.size()); memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar32_t)); return ret; } if (sizeof(wchar_t) == 2) { if (endian == unicode::EUTFEE_NATIVE && addBOM == false) { core::array<wchar_t> ret(used); ret.set_used(used); memcpy((void*)ret.pointer(), (void*)array, used * sizeof(uchar16_t)); return ret; } else { core::array<uchar16_t> a(toUTF16(endian, addBOM)); core::array<wchar_t> ret(a.size()); ret.set_used(a.size()); memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar16_t)); return ret; } } if (sizeof(wchar_t) == 1) { core::array<uchar8_t> a(toUTF8(addBOM)); core::array<wchar_t> ret(a.size()); ret.set_used(a.size()); memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar8_t)); return ret; } // Shouldn't happen. return core::array<wchar_t>(); } //! Converts the string to a properly encoded io::path string. //! \param endian The desired endianness of the string. //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. //! \return An io::path string containing the properly encoded string. io::path toPATH_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const { #if defined(_IRR_WCHAR_FILESYSTEM) return toWCHAR_s(endian, addBOM); #else return toUTF8_s(addBOM); #endif } //! Loads an unknown stream of data. //! Will attempt to determine if the stream is unicode data. Useful for loading from files. //! \param data The data stream to load from. //! \param data_size The length of the data string. //! \return A reference to our current string. ustring16<TAlloc>& loadDataStream(const char* data, size_t data_size) { // Clear our string. *this = ""; if (!data) return *this; unicode::EUTF_ENCODE e = unicode::determineUnicodeBOM(data); switch (e) { default: case unicode::EUTFE_UTF8: append((uchar8_t*)data, data_size); break; case unicode::EUTFE_UTF16: case unicode::EUTFE_UTF16_BE: case unicode::EUTFE_UTF16_LE: append((uchar16_t*)data, data_size / 2); break; case unicode::EUTFE_UTF32: case unicode::EUTFE_UTF32_BE: case unicode::EUTFE_UTF32_LE: append((uchar32_t*)data, data_size / 4); break; } return *this; } //! Gets the encoding of the Unicode string this class contains. //! \return An enum describing the current encoding of this string. const unicode::EUTF_ENCODE getEncoding() const { return encoding; } //! Gets the endianness of the Unicode string this class contains. //! \return An enum describing the endianness of this string. const unicode::EUTF_ENDIAN getEndianness() const { if (encoding == unicode::EUTFE_UTF16_LE || encoding == unicode::EUTFE_UTF32_LE) return unicode::EUTFEE_LITTLE; else return unicode::EUTFEE_BIG; } private: //! Reallocate the string, making it bigger or smaller. //! \param new_size The new size of the string. void reallocate(u32 new_size) { uchar16_t* old_array = array; array = allocator.allocate(new_size + 1); //new u16[new_size]; allocated = new_size + 1; if (old_array == 0) return; u32 amount = used < new_size ? used : new_size; for (u32 i=0; i<=amount; ++i) array[i] = old_array[i]; if (allocated <= used) used = allocated - 1; array[used] = 0; allocator.deallocate(old_array); // delete [] old_array; } //--- member variables uchar16_t* array; unicode::EUTF_ENCODE encoding; u32 allocated; u32 used; TAlloc allocator; //irrAllocator<uchar16_t> allocator; }; typedef ustring16<irrAllocator<uchar16_t> > ustring; //! Appends two ustring16s. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a null-terminated unicode string. template <typename TAlloc, class B> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const B* const right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a null-terminated unicode string. template <class B, typename TAlloc> inline ustring16<TAlloc> operator+(const B* const left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and an Irrlicht string. template <typename TAlloc, typename B, typename BAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const string<B, BAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and an Irrlicht string. template <typename TAlloc, typename B, typename BAlloc> inline ustring16<TAlloc> operator+(const string<B, BAlloc>& left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a std::basic_string. template <typename TAlloc, typename B, typename A, typename BAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const std::basic_string<B, A, BAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a std::basic_string. template <typename TAlloc, typename B, typename A, typename BAlloc> inline ustring16<TAlloc> operator+(const std::basic_string<B, A, BAlloc>& left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a char. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const char right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a char. template <typename TAlloc> inline ustring16<TAlloc> operator+(const char left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } #ifdef USTRING_CPP0X_NEWLITERALS //! Appends a ustring16 and a uchar32_t. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const uchar32_t right) { ustring16<TAlloc> ret(left); ret += right; return ret; } //! Appends a ustring16 and a uchar32_t. template <typename TAlloc> inline ustring16<TAlloc> operator+(const uchar32_t left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret(left); ret += right; return ret; } #endif //! Appends a ustring16 and a short. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const short right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and a short. template <typename TAlloc> inline ustring16<TAlloc> operator+(const short left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and an unsigned short. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned short right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and an unsigned short. template <typename TAlloc> inline ustring16<TAlloc> operator+(const unsigned short left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and an int. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const int right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and an int. template <typename TAlloc> inline ustring16<TAlloc> operator+(const int left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and an unsigned int. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned int right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and an unsigned int. template <typename TAlloc> inline ustring16<TAlloc> operator+(const unsigned int left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and a long. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const long right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and a long. template <typename TAlloc> inline ustring16<TAlloc> operator+(const long left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and an unsigned long. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned long right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and an unsigned long. template <typename TAlloc> inline ustring16<TAlloc> operator+(const unsigned long left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and a float. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const float right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and a float. template <typename TAlloc> inline ustring16<TAlloc> operator+(const float left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } //! Appends a ustring16 and a double. template <typename TAlloc> inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const double right) { ustring16<TAlloc> ret(left); ret += core::stringc(right); return ret; } //! Appends a ustring16 and a double. template <typename TAlloc> inline ustring16<TAlloc> operator+(const double left, const ustring16<TAlloc>& right) { ustring16<TAlloc> ret((core::stringc(left))); ret += right; return ret; } #ifdef USTRING_CPP0X //! Appends two ustring16s. template <typename TAlloc> inline ustring16<TAlloc>&& operator+(const ustring16<TAlloc>& left, ustring16<TAlloc>&& right) { //std::cout << "MOVE operator+(&, &&)" << std::endl; right.insert(left, 0); return std::move(right); } //! Appends two ustring16s. template <typename TAlloc> inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const ustring16<TAlloc>& right) { //std::cout << "MOVE operator+(&&, &)" << std::endl; left.append(right); return std::move(left); } //! Appends two ustring16s. template <typename TAlloc> inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, ustring16<TAlloc>&& right) { //std::cout << "MOVE operator+(&&, &&)" << std::endl; if ((right.size_raw() <= left.capacity() - left.size_raw()) || (right.capacity() - right.size_raw() < left.size_raw())) { left.append(right); return std::move(left); } else { right.insert(left, 0); return std::move(right); } } //! Appends a ustring16 and a null-terminated unicode string. template <typename TAlloc, class B> inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const B* const right) { //std::cout << "MOVE operator+(&&, B*)" << std::endl; left.append(right); return std::move(left); } //! Appends a ustring16 and a null-terminated unicode string. template <class B, typename TAlloc> inline ustring16<TAlloc>&& operator+(const B* const left, ustring16<TAlloc>&& right) { //std::cout << "MOVE operator+(B*, &&)" << std::endl; right.insert(left, 0); return std::move(right); } //! Appends a ustring16 and an Irrlicht string. template <typename TAlloc, typename B, typename BAlloc> inline ustring16<TAlloc>&& operator+(const string<B, BAlloc>& left, ustring16<TAlloc>&& right) { //std::cout << "MOVE operator+(&, &&)" << std::endl; right.insert(left, 0); return std::move(right); } //! Appends a ustring16 and an Irrlicht string. template <typename TAlloc, typename B, typename BAlloc> inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const string<B, BAlloc>& right) { //std::cout << "MOVE operator+(&&, &)" << std::endl; left.append(right); return std::move(left); } //! Appends a ustring16 and a std::basic_string. template <typename TAlloc, typename B, typename A, typename BAlloc> inline ustring16<TAlloc>&& operator+(const std::basic_string<B, A, BAlloc>& left, ustring16<TAlloc>&& right) { //std::cout << "MOVE operator+(&, &&)" << std::endl; right.insert(core::ustring16<TAlloc>(left), 0); return std::move(right); } //! Appends a ustring16 and a std::basic_string. template <typename TAlloc, typename B, typename A, typename BAlloc> inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const std::basic_string<B, A, BAlloc>& right) { //std::cout << "MOVE operator+(&&, &)" << std::endl; left.append(right); return std::move(left); } //! Appends a ustring16 and a char. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const char right) { left.append((uchar32_t)right); return std::move(left); } //! Appends a ustring16 and a char. template <typename TAlloc> inline ustring16<TAlloc> operator+(const char left, ustring16<TAlloc>&& right) { right.insert((uchar32_t)left, 0); return std::move(right); } #ifdef USTRING_CPP0X_NEWLITERALS //! Appends a ustring16 and a uchar32_t. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const uchar32_t right) { left.append(right); return std::move(left); } //! Appends a ustring16 and a uchar32_t. template <typename TAlloc> inline ustring16<TAlloc> operator+(const uchar32_t left, ustring16<TAlloc>&& right) { right.insert(left, 0); return std::move(right); } #endif //! Appends a ustring16 and a short. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const short right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and a short. template <typename TAlloc> inline ustring16<TAlloc> operator+(const short left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and an unsigned short. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const unsigned short right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and an unsigned short. template <typename TAlloc> inline ustring16<TAlloc> operator+(const unsigned short left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and an int. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const int right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and an int. template <typename TAlloc> inline ustring16<TAlloc> operator+(const int left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and an unsigned int. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const unsigned int right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and an unsigned int. template <typename TAlloc> inline ustring16<TAlloc> operator+(const unsigned int left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and a long. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const long right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and a long. template <typename TAlloc> inline ustring16<TAlloc> operator+(const long left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and an unsigned long. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const unsigned long right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and an unsigned long. template <typename TAlloc> inline ustring16<TAlloc> operator+(const unsigned long left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and a float. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const float right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and a float. template <typename TAlloc> inline ustring16<TAlloc> operator+(const float left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } //! Appends a ustring16 and a double. template <typename TAlloc> inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const double right) { left.append(core::stringc(right)); return std::move(left); } //! Appends a ustring16 and a double. template <typename TAlloc> inline ustring16<TAlloc> operator+(const double left, ustring16<TAlloc>&& right) { right.insert(core::stringc(left), 0); return std::move(right); } #endif #ifndef USTRING_NO_STL //! Writes a ustring16 to an ostream. template <typename TAlloc> inline std::ostream& operator<<(std::ostream& out, const ustring16<TAlloc>& in) { out << in.toUTF8_s().c_str(); return out; } //! Writes a ustring16 to a wostream. template <typename TAlloc> inline std::wostream& operator<<(std::wostream& out, const ustring16<TAlloc>& in) { out << in.toWCHAR_s().c_str(); return out; } #endif #ifndef USTRING_NO_STL namespace unicode { //! Hashing algorithm for hashing a ustring. Used for things like unordered_maps. //! Algorithm taken from std::hash<std::string>. class hash : public std::unary_function<core::ustring, size_t> { public: size_t operator()(const core::ustring& s) const { size_t ret = 2166136261U; size_t index = 0; size_t stride = 1 + s.size_raw() / 10; core::ustring::const_iterator i = s.begin(); while (i != s.end()) { // TODO: Don't force u32 on an x64 OS. Make it agnostic. ret = 16777619U * ret ^ (size_t)s[(u32)index]; index += stride; i += stride; } return (ret); } }; } // end namespace unicode #endif } // end namespace core } // end namespace irr #endif