3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
35 #include "common_logic.h"
36 #include "CellArray.h"
38 /***********************************
39 * About the double array hack *
40 ***************************
42 Double arrays in Pawn are vectors offset by the current offset. For example:
46 In this array, index 0 contains the offset from the current offset which
47 results in the final vector [2] (at [0][2]). Meaning, to dereference [1][2],
50 address = &array[1] + array[1] + 2 * sizeof(cell)
52 The fact that each offset is from the _current_ position rather than the _base_
53 position is very important. It means that if you to try to swap vector positions,
54 the offsets will no longer match, because their current position has changed. A
55 simple and ingenious way around this is to back up the positions in a separate array,
56 then to overwrite each position in the old array with absolute indices. Pseudo C++ code:
58 cell *array; //assumed to be set to the 2+D array
59 cell *old_offsets = new cell[2];
60 for (int i=0; i<2; i++)
62 old_offsets = array[i];
66 Now, you can swap the array indices with no problem, and do a reverse-lookup to find the original addresses.
67 After sorting/modification is done, you must relocate the new indices. For example, if the two vectors in our
68 demo array were swapped, array[0] would be 1 and array[1] would be 0. This is invalid to the virtual machine.
69 Luckily, this is also simple -- all the information is there.
71 for (int i=0; i<2; i++)
73 //get the # of the vector we want to relocate in
74 cell vector_index = array[i];
75 //get the real address of this vector
76 char *real_address = (char *)array + (vector_index * sizeof(cell)) + old_offsets[vector_index];
77 //calc and store the new distance offset
78 array[i] = real_address - ( (char *)array + (vector_index + sizeof(cell)) )
81 Note that the inner expression can be heavily reduced; it is expanded for readability.
82 **********************************/
91 void sort_random(cell_t *array, cell_t size)
93 srand((unsigned int)time(NULL));
95 for (int i = size-1; i > 0; i--)
97 int n = rand() % (i + 1);
99 if (array[i] != array[n])
101 array[i] ^= array[n];
102 array[n] ^= array[i];
103 array[i] ^= array[n];
108 int sort_ints_asc(const void *int1, const void *int2)
110 return (*(int *)int1) - (*(int *)int2);
113 int sort_ints_desc(const void *int1, const void *int2)
115 return (*(int *)int2) - (*(int *)int1);
118 static cell_t sm_SortIntegers(IPluginContext *pContext, const cell_t *params)
121 cell_t array_size = params[2];
122 cell_t type = params[3];
124 pContext->LocalToPhysAddr(params[1], &array);
126 if (type == Sort_Ascending)
128 qsort(array, array_size, sizeof(cell_t), sort_ints_asc);
130 else if (type == Sort_Descending)
132 qsort(array, array_size, sizeof(cell_t), sort_ints_desc);
136 sort_random(array, array_size);
142 int sort_floats_asc(const void *float1, const void *float2)
144 float r1 = *(float *)float1;
145 float r2 = *(float *)float2;
150 } else if (r2 < r1) {
157 int sort_floats_desc(const void *float1, const void *float2)
159 float r1 = *(float *)float1;
160 float r2 = *(float *)float2;
165 } else if (r2 < r1) {
172 static cell_t sm_SortFloats(IPluginContext *pContext, const cell_t *params)
175 cell_t array_size = params[2];
176 cell_t type = params[3];
178 pContext->LocalToPhysAddr(params[1], &array);
180 if (type == Sort_Ascending)
182 qsort(array, array_size, sizeof(cell_t), sort_floats_asc);
184 else if (type == Sort_Descending)
186 qsort(array, array_size, sizeof(cell_t), sort_floats_desc);
190 sort_random(array, array_size);
196 static cell_t *g_CurStringArray = NULL;
197 static cell_t *g_CurRebaseMap = NULL;
199 int sort_strings_asc(const void *blk1, const void *blk2)
201 cell_t reloc1 = *(cell_t *)blk1;
202 cell_t reloc2 = *(cell_t *)blk2;
204 char *str1 = ((char *)(&g_CurStringArray[reloc1]) + g_CurRebaseMap[reloc1]);
205 char *str2 = ((char *)(&g_CurStringArray[reloc2]) + g_CurRebaseMap[reloc2]);
207 return strcmp(str1, str2);
210 int sort_strings_desc(const void *blk1, const void *blk2)
212 cell_t reloc1 = *(cell_t *)blk1;
213 cell_t reloc2 = *(cell_t *)blk2;
215 char *str1 = ((char *)(&g_CurStringArray[reloc1]) + g_CurRebaseMap[reloc1]);
216 char *str2 = ((char *)(&g_CurStringArray[reloc2]) + g_CurRebaseMap[reloc2]);
218 return strcmp(str2, str1);
221 static cell_t sm_SortStrings(IPluginContext *pContext, const cell_t *params)
224 cell_t array_size = params[2];
225 cell_t type = params[3];
227 pContext->LocalToPhysAddr(params[1], &array);
229 /** HACKHACK - back up the old indices, replace the indices with something easier */
230 cell_t amx_addr, *phys_addr;
232 if ((err=pContext->HeapAlloc(array_size, &amx_addr, &phys_addr)) != SP_ERROR_NONE)
234 pContext->ThrowNativeErrorEx(err, "Ran out of memory to sort");
237 g_CurStringArray = array;
238 g_CurRebaseMap = phys_addr;
240 for (int i=0; i<array_size; i++)
242 phys_addr[i] = array[i];
246 if (type == Sort_Ascending)
248 qsort(array, array_size, sizeof(cell_t), sort_strings_asc);
250 else if (type == Sort_Descending)
252 qsort(array, array_size, sizeof(cell_t), sort_strings_desc);
256 sort_random(array, array_size);
259 /* END HACKHACK - restore what we damaged so Pawn doesn't throw up.
260 * We'll browse through each index of the array and patch up the distance.
262 for (int i=0; i<array_size; i++)
264 /* Compute the final address of the old array and subtract the new location.
265 * This is the fixed up distance.
267 array[i] = ((char *)&array[array[i]] + phys_addr[array[i]]) - (char *)&array[i];
270 pContext->HeapPop(amx_addr);
272 g_CurStringArray = NULL;
273 g_CurRebaseMap = NULL;
280 IPluginFunction *pFunc;
287 sort_info g_SortInfo;
289 int sort1d_amx_custom(const void *elem1, const void *elem2)
291 cell_t c1 = *(cell_t *)elem1;
292 cell_t c2 = *(cell_t *)elem2;
295 IPluginFunction *pf = g_SortInfo.pFunc;
298 pf->PushCell(g_SortInfo.array_addr);
299 pf->PushCell(g_SortInfo.hndl);
300 pf->Execute(&result);
305 static cell_t sm_SortCustom1D(IPluginContext *pContext, const cell_t *params)
308 cell_t array_size = params[2];
310 IPluginFunction *pFunction = pContext->GetFunctionById(params[3]);
313 return pContext->ThrowNativeError("Function %x is not a valid function", params[3]);
316 pContext->LocalToPhysAddr(params[1], &array);
318 sort_info oldinfo = g_SortInfo;
321 g_SortInfo.hndl = params[4];
322 g_SortInfo.array_addr = params[1];
323 g_SortInfo.array_remap = NULL;
324 g_SortInfo.array_base = NULL;
325 g_SortInfo.pFunc = pFunction;
327 qsort(array, array_size, sizeof(cell_t), sort1d_amx_custom);
329 g_SortInfo = oldinfo;
334 int sort2d_amx_custom(const void *elem1, const void *elem2)
336 cell_t c1 = *(cell_t *)elem1;
337 cell_t c2 = *(cell_t *)elem2;
339 cell_t c1_addr = g_SortInfo.array_addr + (c1 * sizeof(cell_t)) + g_SortInfo.array_remap[c1];
340 cell_t c2_addr = g_SortInfo.array_addr + (c2 * sizeof(cell_t)) + g_SortInfo.array_remap[c2];
342 IPluginContext *pContext = g_SortInfo.pFunc->GetParentContext();
344 pContext->LocalToPhysAddr(c1_addr, &c1_r);
345 pContext->LocalToPhysAddr(c2_addr, &c2_r);
348 g_SortInfo.pFunc->PushCell(c1_addr);
349 g_SortInfo.pFunc->PushCell(c2_addr);
350 g_SortInfo.pFunc->PushCell(g_SortInfo.array_addr);
351 g_SortInfo.pFunc->PushCell(g_SortInfo.hndl);
352 g_SortInfo.pFunc->Execute(&result);
357 static cell_t sm_SortCustom2D(IPluginContext *pContext, const cell_t *params)
360 cell_t array_size = params[2];
361 IPluginFunction *pFunction;
363 pContext->LocalToPhysAddr(params[1], &array);
365 if ((pFunction=pContext->GetFunctionById(params[3])) == NULL)
367 return pContext->ThrowNativeError("Function %x is not a valid function", params[3]);
370 /** back up the old indices, replace the indices with something easier */
371 cell_t amx_addr, *phys_addr;
373 if ((err=pContext->HeapAlloc(array_size, &amx_addr, &phys_addr)) != SP_ERROR_NONE)
375 pContext->ThrowNativeErrorEx(err, "Ran out of memory to sort");
379 sort_info oldinfo = g_SortInfo;
381 g_SortInfo.pFunc = pFunction;
382 g_SortInfo.hndl = params[4];
383 g_SortInfo.array_addr = params[1];
385 /** Same process as in strings, back up the old indices for later fixup */
386 g_SortInfo.array_base = array;
387 g_SortInfo.array_remap = phys_addr;
389 for (int i=0; i<array_size; i++)
391 phys_addr[i] = array[i];
395 qsort(array, array_size, sizeof(cell_t), sort2d_amx_custom);
397 /** Fixup process! */
398 for (int i=0; i<array_size; i++)
400 /* Compute the final address of the old array and subtract the new location.
401 * This is the fixed up distance.
403 array[i] = ((char *)&array[array[i]] + phys_addr[array[i]]) - (char *)&array[i];
406 pContext->HeapPop(amx_addr);
408 g_SortInfo = oldinfo;
420 int sort_adtarray_strings_asc(const void *str1, const void *str2)
422 return strcmp((char *) str1, (char *) str2);
425 int sort_adtarray_strings_desc(const void *str1, const void *str2)
427 return strcmp((char *) str2, (char *) str1);
430 void sort_adt_random(CellArray *cArray)
432 size_t arraysize = cArray->size();
434 srand((unsigned int)time(NULL));
436 for (int i = arraysize-1; i > 0; i--)
438 int n = rand() % (i + 1);
444 static cell_t sm_SortADTArray(IPluginContext *pContext, const cell_t *params)
448 HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
450 if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&cArray))
453 return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
456 cell_t order = params[2];
458 if (order == Sort_Random)
460 sort_adt_random(cArray);
465 cell_t type = params[3];
466 size_t arraysize = cArray->size();
467 size_t blocksize = cArray->blocksize();
468 cell_t *array = cArray->base();
470 if (type == Sort_Integer)
472 if (order == Sort_Ascending)
474 qsort(array, arraysize, blocksize * sizeof(cell_t), sort_ints_asc);
478 qsort(array, arraysize, blocksize * sizeof(cell_t), sort_ints_desc);
481 else if (type == Sort_Float)
483 if (order == Sort_Ascending)
485 qsort(array, arraysize, blocksize * sizeof(cell_t), sort_floats_asc);
489 qsort(array, arraysize, blocksize * sizeof(cell_t), sort_floats_desc);
492 else if (type == Sort_String)
494 if (order == Sort_Ascending)
496 qsort(array, arraysize, blocksize * sizeof(cell_t), sort_adtarray_strings_asc);
500 qsort(array, arraysize, blocksize * sizeof(cell_t), sort_adtarray_strings_desc);
509 IPluginFunction *pFunc;
516 sort_infoADT g_SortInfoADT;
518 int sort_adtarray_custom(const void *elem1, const void *elem2)
521 IPluginFunction *pf = g_SortInfoADT.pFunc;
522 pf->PushCell(((cell_t) ((cell_t *) elem1 - g_SortInfoADT.array_base)) / g_SortInfoADT.array_bsize);
523 pf->PushCell(((cell_t) ((cell_t *) elem2 - g_SortInfoADT.array_base)) / g_SortInfoADT.array_bsize);
524 pf->PushCell(g_SortInfoADT.array_hndl);
525 pf->PushCell(g_SortInfoADT.hndl);
526 pf->Execute(&result);
531 static cell_t sm_SortADTArrayCustom(IPluginContext *pContext, const cell_t *params)
535 HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
537 if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&cArray))
540 return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
543 IPluginFunction *pFunction = pContext->GetFunctionById(params[2]);
546 return pContext->ThrowNativeError("Function %x is not a valid function", params[2]);
549 size_t arraysize = cArray->size();
550 size_t blocksize = cArray->blocksize();
551 cell_t *array = cArray->base();
553 sort_infoADT oldinfo = g_SortInfoADT;
555 g_SortInfoADT.pFunc = pFunction;
556 g_SortInfoADT.array_base = array;
557 g_SortInfoADT.array_bsize = (cell_t) blocksize;
558 g_SortInfoADT.array_hndl = params[1];
559 g_SortInfoADT.hndl = params[3];
561 qsort(array, arraysize, blocksize * sizeof(cell_t), sort_adtarray_custom);
563 g_SortInfoADT = oldinfo;
568 REGISTER_NATIVES(sortNatives)
570 {"SortIntegers", sm_SortIntegers},
571 {"SortFloats", sm_SortFloats},
572 {"SortStrings", sm_SortStrings},
573 {"SortCustom1D", sm_SortCustom1D},
574 {"SortCustom2D", sm_SortCustom2D},
575 {"SortADTArray", sm_SortADTArray},
576 {"SortADTArrayCustom", sm_SortADTArrayCustom},