-
-
Notifications
You must be signed in to change notification settings - Fork 466
Expand file tree
/
Copy pathsmn_sorting.cpp
More file actions
708 lines (576 loc) · 18.1 KB
/
smn_sorting.cpp
File metadata and controls
708 lines (576 loc) · 18.1 KB
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
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* 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 General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "common_logic.h"
#include "CellArray.h"
#include <IHandleSys.h>
#include <amtl/am-raii.h>
/***********************************
* About the double array hack *
***************************
Double arrays in Pawn are vectors offset by the current offset. For example:
new array[2][2]
In this array, index 0 contains the offset from the current offset which
results in the final vector [2] (at [0][2]). Meaning, to dereference [1][2],
it is equivalent to:
address = &array[1] + array[1] + 2 * sizeof(cell)
The fact that each offset is from the _current_ position rather than the _base_
position is very important. It means that if you to try to swap vector positions,
the offsets will no longer match, because their current position has changed. A
simple and ingenious way around this is to back up the positions in a separate array,
then to overwrite each position in the old array with absolute indices. Pseudo C++ code:
cell *array; //assumed to be set to the 2+D array
cell *old_offsets = new cell[2];
for (int i=0; i<2; i++)
{
old_offsets = array[i];
array[i] = i;
}
Now, you can swap the array indices with no problem, and do a reverse-lookup to find the original addresses.
After sorting/modification is done, you must relocate the new indices. For example, if the two vectors in our
demo array were swapped, array[0] would be 1 and array[1] would be 0. This is invalid to the virtual machine.
Luckily, this is also simple -- all the information is there.
for (int i=0; i<2; i++)
{
//get the # of the vector we want to relocate in
cell vector_index = array[i];
//get the real address of this vector
char *real_address = (char *)array + (vector_index * sizeof(cell)) + old_offsets[vector_index];
//calc and store the new distance offset
array[i] = real_address - ( (char *)array + (vector_index + sizeof(cell)) )
}
Note that the inner expression can be heavily reduced; it is expanded for readability.
**********************************/
enum SortOrder
{
Sort_Ascending = 0,
Sort_Descending = 1,
Sort_Random = 2,
};
void sort_random(cell_t *array, cell_t size)
{
for (int i = size-1; i > 0; i--)
{
int n = rand() % (i + 1);
if (array[i] != array[n])
{
array[i] ^= array[n];
array[n] ^= array[i];
array[i] ^= array[n];
}
}
}
int sort_ints_asc(const void *int1, const void *int2)
{
return (*(int *)int1) - (*(int *)int2);
}
int sort_ints_desc(const void *int1, const void *int2)
{
return (*(int *)int2) - (*(int *)int1);
}
static cell_t sm_SortIntegers(IPluginContext *pContext, const cell_t *params)
{
cell_t *array;
cell_t array_size = params[2];
cell_t type = params[3];
pContext->LocalToPhysAddr(params[1], &array);
if (type == Sort_Ascending)
{
qsort(array, array_size, sizeof(cell_t), sort_ints_asc);
}
else if (type == Sort_Descending)
{
qsort(array, array_size, sizeof(cell_t), sort_ints_desc);
}
else
{
sort_random(array, array_size);
}
return 1;
}
int sort_floats_asc(const void *float1, const void *float2)
{
float r1 = *(float *)float1;
float r2 = *(float *)float2;
if (r1 < r2)
{
return -1;
} else if (r2 < r1) {
return 1;
} else {
return 0;
}
}
int sort_floats_desc(const void *float1, const void *float2)
{
float r1 = *(float *)float1;
float r2 = *(float *)float2;
if (r1 < r2)
{
return 1;
} else if (r2 < r1) {
return -1;
} else {
return 0;
}
}
static cell_t sm_SortFloats(IPluginContext *pContext, const cell_t *params)
{
cell_t *array;
cell_t array_size = params[2];
cell_t type = params[3];
pContext->LocalToPhysAddr(params[1], &array);
if (type == Sort_Ascending)
{
qsort(array, array_size, sizeof(cell_t), sort_floats_asc);
}
else if (type == Sort_Descending)
{
qsort(array, array_size, sizeof(cell_t), sort_floats_desc);
}
else
{
sort_random(array, array_size);
}
return 1;
}
static cell_t *g_CurStringArray = NULL;
static cell_t *g_CurRebaseMap = NULL;
int sort_strings_asc_legacy(const void *blk1, const void *blk2)
{
cell_t reloc1 = *(cell_t *)blk1;
cell_t reloc2 = *(cell_t *)blk2;
char *str1 = ((char *)(&g_CurStringArray[reloc1]) + g_CurRebaseMap[reloc1]);
char *str2 = ((char *)(&g_CurStringArray[reloc2]) + g_CurRebaseMap[reloc2]);
return strcmp(str1, str2);
}
int sort_strings_desc_legacy(const void *blk1, const void *blk2)
{
cell_t reloc1 = *(cell_t *)blk1;
cell_t reloc2 = *(cell_t *)blk2;
char *str1 = ((char *)(&g_CurStringArray[reloc1]) + g_CurRebaseMap[reloc1]);
char *str2 = ((char *)(&g_CurStringArray[reloc2]) + g_CurRebaseMap[reloc2]);
return strcmp(str2, str1);
}
static cell_t sm_SortStrings_Legacy(IPluginContext *pContext, const cell_t *params)
{
cell_t *array;
cell_t array_size = params[2];
cell_t type = params[3];
pContext->LocalToPhysAddr(params[1], &array);
/** HACKHACK - back up the old indices, replace the indices with something easier */
cell_t amx_addr, *phys_addr;
int err;
if ((err=pContext->HeapAlloc(array_size, &amx_addr, &phys_addr)) != SP_ERROR_NONE)
{
pContext->ThrowNativeErrorEx(err, "Ran out of memory to sort");
return 0;
}
g_CurStringArray = array;
g_CurRebaseMap = phys_addr;
for (int i=0; i<array_size; i++)
{
phys_addr[i] = array[i];
array[i] = i;
}
if (type == Sort_Ascending)
{
qsort(array, array_size, sizeof(cell_t), sort_strings_asc_legacy);
}
else if (type == Sort_Descending)
{
qsort(array, array_size, sizeof(cell_t), sort_strings_desc_legacy);
}
else
{
sort_random(array, array_size);
}
/* END HACKHACK - restore what we damaged so Pawn doesn't throw up.
* We'll browse through each index of the array and patch up the distance.
*/
for (int i=0; i<array_size; i++)
{
/* Compute the final address of the old array and subtract the new location.
* This is the fixed up distance.
*/
array[i] = ((char *)&array[array[i]] + phys_addr[array[i]]) - (char *)&array[i];
}
pContext->HeapPop(amx_addr);
g_CurStringArray = NULL;
g_CurRebaseMap = NULL;
return 1;
}
static IPluginContext* sSortContext = nullptr;
int sort_strings_asc(const void *blk1, const void *blk2)
{
cell_t str_addr1 = *(cell_t *)blk1;
cell_t str_addr2 = *(cell_t *)blk2;
char *str1;
char *str2;
if (sSortContext->LocalToString(str_addr1, &str1) != SP_ERROR_NONE ||
sSortContext->LocalToString(str_addr2, &str2) != SP_ERROR_NONE)
{
return 0;
}
return strcmp(str1, str2);
}
int sort_strings_desc(const void *blk1, const void *blk2)
{
cell_t str_addr1 = *(cell_t *)blk1;
cell_t str_addr2 = *(cell_t *)blk2;
char *str1;
char *str2;
if (sSortContext->LocalToString(str_addr1, &str1) != SP_ERROR_NONE ||
sSortContext->LocalToString(str_addr2, &str2) != SP_ERROR_NONE)
{
return 0;
}
return strcmp(str2, str1);
}
static cell_t sm_SortStrings(IPluginContext *pContext, const cell_t *params)
{
auto rt = pContext->GetRuntime();
if (!rt->UsesDirectArrays())
return sm_SortStrings_Legacy(pContext, params);
cell_t *array;
cell_t array_size = params[2];
cell_t type = params[3];
pContext->LocalToPhysAddr(params[1], &array);
ke::SaveAndSet<IPluginContext*> set_context(&sSortContext, pContext);
if (type == Sort_Ascending)
{
qsort(array, array_size, sizeof(cell_t), sort_strings_asc);
}
else if (type == Sort_Descending)
{
qsort(array, array_size, sizeof(cell_t), sort_strings_desc);
}
else
{
sort_random(array, array_size);
}
return 1;
}
struct sort_info
{
IPluginFunction *pFunc;
cell_t data;
cell_t array_addr;
cell_t *array_base;
cell_t *array_remap;
ExceptionHandler *eh;
};
sort_info g_SortInfo;
int sort1d_amx_custom(const void *elem1, const void *elem2)
{
if (g_SortInfo.eh->HasException())
return 0;
cell_t c1 = *(cell_t *)elem1;
cell_t c2 = *(cell_t *)elem2;
cell_t result = 0;
IPluginFunction *pf = g_SortInfo.pFunc;
pf->PushCell(c1);
pf->PushCell(c2);
pf->PushCell(g_SortInfo.array_addr);
pf->PushCell(g_SortInfo.data);
pf->Invoke(&result);
return result;
}
static cell_t sm_SortCustom1D(IPluginContext *pContext, const cell_t *params)
{
cell_t *array;
cell_t array_size = params[2];
IPluginFunction *pFunction = pContext->GetFunctionById(params[3]);
if (!pFunction)
{
return pContext->ThrowNativeError("Function %x is not a valid function", params[3]);
}
pContext->LocalToPhysAddr(params[1], &array);
sort_info oldinfo = g_SortInfo;
DetectExceptions eh(pContext);
g_SortInfo.data = params[4];
g_SortInfo.array_addr = params[1];
g_SortInfo.array_remap = NULL;
g_SortInfo.array_base = NULL;
g_SortInfo.pFunc = pFunction;
g_SortInfo.eh = &eh;
qsort(array, array_size, sizeof(cell_t), sort1d_amx_custom);
g_SortInfo = oldinfo;
return 1;
}
static int sort2d_amx_custom_legacy(const void *elem1, const void *elem2)
{
if (g_SortInfo.eh->HasException())
return 0;
cell_t c1 = *(cell_t *)elem1;
cell_t c2 = *(cell_t *)elem2;
cell_t c1_addr = g_SortInfo.array_addr + (c1 * sizeof(cell_t)) + g_SortInfo.array_remap[c1];
cell_t c2_addr = g_SortInfo.array_addr + (c2 * sizeof(cell_t)) + g_SortInfo.array_remap[c2];
IPluginContext *pContext = g_SortInfo.pFunc->GetParentContext();
cell_t *c1_r, *c2_r;
pContext->LocalToPhysAddr(c1_addr, &c1_r);
pContext->LocalToPhysAddr(c2_addr, &c2_r);
cell_t result = 0;
g_SortInfo.pFunc->PushCell(c1_addr);
g_SortInfo.pFunc->PushCell(c2_addr);
g_SortInfo.pFunc->PushCell(g_SortInfo.array_addr);
g_SortInfo.pFunc->PushCell(g_SortInfo.data);
g_SortInfo.pFunc->Invoke(&result);
return result;
}
static cell_t sm_SortCustom2D_Legacy(IPluginContext *pContext, const cell_t *params)
{
cell_t *array;
cell_t array_size = params[2];
IPluginFunction *pFunction;
pContext->LocalToPhysAddr(params[1], &array);
if ((pFunction=pContext->GetFunctionById(params[3])) == NULL)
{
return pContext->ThrowNativeError("Function %x is not a valid function", params[3]);
}
/** back up the old indices, replace the indices with something easier */
cell_t amx_addr, *phys_addr;
int err;
if ((err=pContext->HeapAlloc(array_size, &amx_addr, &phys_addr)) != SP_ERROR_NONE)
{
pContext->ThrowNativeErrorEx(err, "Ran out of memory to sort");
return 0;
}
sort_info oldinfo = g_SortInfo;
DetectExceptions eh(pContext);
g_SortInfo.pFunc = pFunction;
g_SortInfo.data = params[4];
g_SortInfo.array_addr = params[1];
g_SortInfo.eh = &eh;
/** Same process as in strings, back up the old indices for later fixup */
g_SortInfo.array_base = array;
g_SortInfo.array_remap = phys_addr;
for (int i=0; i<array_size; i++)
{
phys_addr[i] = array[i];
array[i] = i;
}
qsort(array, array_size, sizeof(cell_t), sort2d_amx_custom_legacy);
/** Fixup process! */
for (int i=0; i<array_size; i++)
{
/* Compute the final address of the old array and subtract the new location.
* This is the fixed up distance.
*/
array[i] = ((char *)&array[array[i]] + phys_addr[array[i]]) - (char *)&array[i];
}
pContext->HeapPop(amx_addr);
g_SortInfo = oldinfo;
return 1;
}
static int sort2d_amx_custom(const void *elem1, const void *elem2)
{
if (g_SortInfo.eh->HasException())
return 0;
cell_t iv1 = *(cell_t *)elem1;
cell_t iv2 = *(cell_t *)elem2;
cell_t result = 0;
g_SortInfo.pFunc->PushCell(iv1);
g_SortInfo.pFunc->PushCell(iv2);
g_SortInfo.pFunc->PushCell(g_SortInfo.array_addr);
g_SortInfo.pFunc->PushCell(g_SortInfo.data);
g_SortInfo.pFunc->Invoke(&result);
return result;
}
static cell_t sm_SortCustom2D(IPluginContext *pContext, const cell_t *params)
{
auto rt = pContext->GetRuntime();
if (!rt->UsesDirectArrays())
return sm_SortCustom2D_Legacy(pContext, params);
cell_t *array;
cell_t array_size = params[2];
IPluginFunction *pFunction;
pContext->LocalToPhysAddr(params[1], &array);
if ((pFunction=pContext->GetFunctionById(params[3])) == NULL)
{
return pContext->ThrowNativeError("Function %x is not a valid function", params[3]);
}
sort_info oldinfo = g_SortInfo;
DetectExceptions eh(pContext);
g_SortInfo.pFunc = pFunction;
g_SortInfo.data = params[4];
g_SortInfo.array_addr = params[1];
g_SortInfo.eh = &eh;
qsort(array, array_size, sizeof(cell_t), sort2d_amx_custom);
g_SortInfo = oldinfo;
return 1;
}
enum SortType
{
Sort_Integer = 0,
Sort_Float,
Sort_String,
};
int sort_adtarray_strings_asc(const void *str1, const void *str2)
{
return strcmp((char *) str1, (char *) str2);
}
int sort_adtarray_strings_desc(const void *str1, const void *str2)
{
return strcmp((char *) str2, (char *) str1);
}
void sort_adt_random(CellArray *cArray)
{
size_t arraysize = cArray->size();
for (int i = arraysize-1; i > 0; i--)
{
int n = rand() % (i + 1);
cArray->swap(i, n);
}
}
static cell_t sm_SortADTArray(IPluginContext *pContext, const cell_t *params)
{
CellArray *cArray;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&cArray))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
cell_t order = params[2];
if (order == Sort_Random)
{
sort_adt_random(cArray);
return 1;
}
cell_t type = params[3];
size_t arraysize = cArray->size();
size_t blocksize = cArray->blocksize();
cell_t *array = cArray->base();
if (type == Sort_Integer)
{
if (order == Sort_Ascending)
{
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_ints_asc);
}
else
{
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_ints_desc);
}
}
else if (type == Sort_Float)
{
if (order == Sort_Ascending)
{
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_floats_asc);
}
else
{
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_floats_desc);
}
}
else if (type == Sort_String)
{
if (order == Sort_Ascending)
{
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_adtarray_strings_asc);
}
else
{
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_adtarray_strings_desc);
}
}
return 1;
}
struct sort_infoADT
{
IPluginFunction *pFunc;
cell_t *array_base;
cell_t array_bsize;
Handle_t array_hndl;
cell_t data;
ExceptionHandler *eh;
};
sort_infoADT g_SortInfoADT;
int sort_adtarray_custom(const void *elem1, const void *elem2)
{
if (g_SortInfoADT.eh->HasException())
return 0;
cell_t result = 0;
IPluginFunction *pf = g_SortInfoADT.pFunc;
pf->PushCell(((cell_t) ((cell_t *) elem1 - g_SortInfoADT.array_base)) / g_SortInfoADT.array_bsize);
pf->PushCell(((cell_t) ((cell_t *) elem2 - g_SortInfoADT.array_base)) / g_SortInfoADT.array_bsize);
pf->PushCell(g_SortInfoADT.array_hndl);
pf->PushCell(g_SortInfoADT.data);
pf->Invoke(&result);
return result;
}
static cell_t sm_SortADTArrayCustom(IPluginContext *pContext, const cell_t *params)
{
CellArray *cArray;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&cArray))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
IPluginFunction *pFunction = pContext->GetFunctionById(params[2]);
if (!pFunction)
{
return pContext->ThrowNativeError("Function %x is not a valid function", params[2]);
}
size_t arraysize = cArray->size();
size_t blocksize = cArray->blocksize();
cell_t *array = cArray->base();
sort_infoADT oldinfo = g_SortInfoADT;
DetectExceptions eh(pContext);
g_SortInfoADT.pFunc = pFunction;
g_SortInfoADT.array_base = array;
g_SortInfoADT.array_bsize = (cell_t) blocksize;
g_SortInfoADT.array_hndl = params[1];
g_SortInfoADT.data = params[3];
g_SortInfoADT.eh = &eh;
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_adtarray_custom);
g_SortInfoADT = oldinfo;
return 1;
}
REGISTER_NATIVES(sortNatives)
{
{"SortIntegers", sm_SortIntegers},
{"SortFloats", sm_SortFloats},
{"SortStrings", sm_SortStrings},
{"SortCustom1D", sm_SortCustom1D},
{"SortCustom2D", sm_SortCustom2D},
{"SortADTArray", sm_SortADTArray},
{"SortADTArrayCustom", sm_SortADTArrayCustom},
{"ArrayList.Sort", sm_SortADTArray},
{"ArrayList.SortCustom", sm_SortADTArrayCustom},
{NULL, NULL},
};