Addons.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Addons.h"
  24. #include <cstring>
  25. #include <new>
  26. #include <stdio.h>
  27. // Adapted from Angelscript's scriptarray & scriptstdstring add-ons, but with garbage collection disabled
  28. namespace Urho3D
  29. {
  30. using namespace std;
  31. /// %Script array buffer.
  32. struct SArrayBuffer
  33. {
  34. asDWORD maxElements;
  35. asDWORD numElements;
  36. asBYTE data[1];
  37. };
  38. /// %Script array cache.
  39. struct SArrayCache
  40. {
  41. asIScriptFunction *cmpFunc;
  42. asIScriptFunction *eqFunc;
  43. };
  44. // We just define a number here that we assume nobody else is using for
  45. // object type user data. The add-ons have reserved the numbers 1000
  46. // through 1999 for this purpose, so we should be fine.
  47. const asPWORD ARRAY_CACHE = 1000;
  48. static void CleanupObjectTypeArrayCache(asIObjectType *type)
  49. {
  50. SArrayCache *cache = reinterpret_cast<SArrayCache*>(type->GetUserData(ARRAY_CACHE));
  51. if( cache )
  52. delete cache;
  53. }
  54. static CScriptArray* ScriptArrayFactory2(asIObjectType *ot, asUINT length)
  55. {
  56. CScriptArray *a = new CScriptArray(length, ot);
  57. // It's possible the constructor raised a script exception, in which case we
  58. // need to free the memory and return null instead, else we get a memory leak.
  59. asIScriptContext *ctx = asGetActiveContext();
  60. if( ctx && ctx->GetState() == asEXECUTION_EXCEPTION )
  61. {
  62. delete a;
  63. return 0;
  64. }
  65. return a;
  66. }
  67. static CScriptArray* ScriptArrayFactoryDefVal(asIObjectType *ot, asUINT length, void *defVal)
  68. {
  69. CScriptArray *a = new CScriptArray(length, defVal, ot);
  70. // It's possible the constructor raised a script exception, in which case we
  71. // need to free the memory and return null instead, else we get a memory leak.
  72. asIScriptContext *ctx = asGetActiveContext();
  73. if( ctx && ctx->GetState() == asEXECUTION_EXCEPTION )
  74. {
  75. delete a;
  76. return 0;
  77. }
  78. return a;
  79. }
  80. static CScriptArray* ScriptArrayFactory(asIObjectType *ot)
  81. {
  82. return ScriptArrayFactory2(ot, 0);
  83. }
  84. // This optional callback is called when the template type is first used by the compiler.
  85. // It allows the application to validate if the template can be instanciated for the requested
  86. // subtype at compile time, instead of at runtime. The output argument dontGarbageCollect
  87. // allow the callback to tell the engine if the template instance type shouldn't be garbage collected,
  88. // i.e. no asOBJ_GC flag.
  89. static bool ScriptArrayTemplateCallback(asIObjectType *ot, bool &dontGarbageCollect)
  90. {
  91. // Urho3D: nothing is garbage collected
  92. dontGarbageCollect = true;
  93. // Make sure the subtype can be instanciated with a default factory/constructor,
  94. // otherwise we won't be able to instanciate the elements.
  95. int typeId = ot->GetSubTypeId();
  96. if( typeId == asTYPEID_VOID )
  97. return false;
  98. if( (typeId & asTYPEID_MASK_OBJECT) && !(typeId & asTYPEID_OBJHANDLE) )
  99. {
  100. asIObjectType *subtype = ot->GetEngine()->GetObjectTypeById(typeId);
  101. asDWORD flags = subtype->GetFlags();
  102. if( (flags & asOBJ_VALUE) && !(flags & asOBJ_POD) )
  103. {
  104. // Verify that there is a default constructor
  105. bool found = false;
  106. for( asUINT n = 0; n < subtype->GetBehaviourCount(); n++ )
  107. {
  108. asEBehaviours beh;
  109. asIScriptFunction *func = subtype->GetBehaviourByIndex(n, &beh);
  110. if( beh != asBEHAVE_CONSTRUCT ) continue;
  111. if( func->GetParamCount() == 0 )
  112. {
  113. // Found the default constructor
  114. found = true;
  115. break;
  116. }
  117. }
  118. if( !found )
  119. {
  120. // There is no default constructor
  121. return false;
  122. }
  123. }
  124. else if( (flags & asOBJ_REF) )
  125. {
  126. // Verify that there is a default factory
  127. bool found = false;
  128. for( asUINT n = 0; n < subtype->GetFactoryCount(); n++ )
  129. {
  130. asIScriptFunction *func = subtype->GetFactoryByIndex(n);
  131. if( func->GetParamCount() == 0 )
  132. {
  133. // Found the default factory
  134. found = true;
  135. break;
  136. }
  137. }
  138. if( !found )
  139. {
  140. // No default factory
  141. return false;
  142. }
  143. }
  144. // If the object type is not garbage collected then the array also doesn't need to be
  145. if( !(flags & asOBJ_GC) )
  146. dontGarbageCollect = true;
  147. }
  148. // The type is ok
  149. return true;
  150. }
  151. CScriptArray &CScriptArray::operator=(const CScriptArray &other)
  152. {
  153. // Only perform the copy if the array types are the same
  154. if( &other != this &&
  155. other.GetArrayObjectType() == GetArrayObjectType() )
  156. {
  157. // Make sure the arrays are of the same size
  158. Resize(other.buffer->numElements);
  159. // Copy the value of each element
  160. CopyBuffer(buffer, other.buffer);
  161. }
  162. return *this;
  163. }
  164. CScriptArray::CScriptArray(asUINT length, asIObjectType *ot)
  165. {
  166. refCount = 1;
  167. gcFlag = false;
  168. objType = ot;
  169. objType->AddRef();
  170. buffer = 0;
  171. Precache();
  172. // Determine element size
  173. if( subTypeId & asTYPEID_MASK_OBJECT )
  174. {
  175. elementSize = sizeof(asPWORD);
  176. }
  177. else
  178. {
  179. elementSize = objType->GetEngine()->GetSizeOfPrimitiveType(subTypeId);
  180. }
  181. // Make sure the array size isn't too large for us to handle
  182. if( !CheckMaxSize(length) )
  183. {
  184. // Don't continue with the initialization
  185. return;
  186. }
  187. CreateBuffer(&buffer, length);
  188. // Urho3D: garbage collection disabled
  189. /*
  190. // Notify the GC of the successful creation
  191. if( objType->GetFlags() & asOBJ_GC )
  192. objType->GetEngine()->NotifyGarbageCollectorOfNewObject(this, objType);
  193. */
  194. }
  195. CScriptArray::CScriptArray(asUINT length, void *defVal, asIObjectType *ot)
  196. {
  197. refCount = 1;
  198. gcFlag = false;
  199. objType = ot;
  200. objType->AddRef();
  201. buffer = 0;
  202. Precache();
  203. // Determine element size
  204. if( subTypeId & asTYPEID_MASK_OBJECT )
  205. {
  206. elementSize = sizeof(asPWORD);
  207. }
  208. else
  209. {
  210. elementSize = objType->GetEngine()->GetSizeOfPrimitiveType(subTypeId);
  211. }
  212. // Make sure the array size isn't too large for us to handle
  213. if( !CheckMaxSize(length) )
  214. {
  215. // Don't continue with the initialization
  216. return;
  217. }
  218. CreateBuffer(&buffer, length);
  219. // Urho3D: garbage collection disabled
  220. /*
  221. // Notify the GC of the successful creation
  222. if( objType->GetFlags() & asOBJ_GC )
  223. objType->GetEngine()->NotifyGarbageCollectorOfNewObject(this, objType);
  224. */
  225. // Initialize the elements with the default value
  226. for( asUINT n = 0; n < GetSize(); n++ )
  227. SetValue(n, defVal);
  228. }
  229. void CScriptArray::SetValue(asUINT index, void *value)
  230. {
  231. // At() will take care of the out-of-bounds checking, though
  232. // if called from the application then nothing will be done
  233. void *ptr = At(index);
  234. if( ptr == 0 ) return;
  235. if( (subTypeId & ~asTYPEID_MASK_SEQNBR) && !(subTypeId & asTYPEID_OBJHANDLE) )
  236. objType->GetEngine()->AssignScriptObject(ptr, value, subTypeId);
  237. else if( subTypeId & asTYPEID_OBJHANDLE )
  238. {
  239. void *tmp = *(void**)ptr;
  240. *(void**)ptr = *(void**)value;
  241. objType->GetEngine()->AddRefScriptObject(*(void**)value, objType->GetSubType());
  242. if( tmp )
  243. objType->GetEngine()->ReleaseScriptObject(*(void**)value, objType->GetSubType());
  244. }
  245. else if( subTypeId == asTYPEID_BOOL ||
  246. subTypeId == asTYPEID_INT8 ||
  247. subTypeId == asTYPEID_UINT8 )
  248. *(char*)ptr = *(char*)value;
  249. else if( subTypeId == asTYPEID_INT16 ||
  250. subTypeId == asTYPEID_UINT16 )
  251. *(short*)ptr = *(short*)value;
  252. else if( subTypeId == asTYPEID_INT32 ||
  253. subTypeId == asTYPEID_UINT32 ||
  254. subTypeId == asTYPEID_FLOAT ||
  255. subTypeId > asTYPEID_DOUBLE ) // enums have a type id larger than doubles
  256. *(int*)ptr = *(int*)value;
  257. else if( subTypeId == asTYPEID_INT64 ||
  258. subTypeId == asTYPEID_UINT64 ||
  259. subTypeId == asTYPEID_DOUBLE )
  260. *(double*)ptr = *(double*)value;
  261. }
  262. CScriptArray::~CScriptArray()
  263. {
  264. if( buffer )
  265. {
  266. DeleteBuffer(buffer);
  267. buffer = 0;
  268. }
  269. if( objType ) objType->Release();
  270. }
  271. asUINT CScriptArray::GetSize() const
  272. {
  273. return buffer->numElements;
  274. }
  275. bool CScriptArray::IsEmpty() const
  276. {
  277. return buffer->numElements == 0;
  278. }
  279. void CScriptArray::Reserve(asUINT maxElements)
  280. {
  281. if( maxElements <= buffer->maxElements )
  282. return;
  283. // Allocate memory for the buffer
  284. SArrayBuffer *newBuffer;
  285. #if defined(AS_MARMALADE)
  286. newBuffer = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1 + elementSize*maxElements];
  287. #else
  288. newBuffer = (SArrayBuffer*)new (nothrow) asBYTE[sizeof(SArrayBuffer)-1 + elementSize*maxElements];
  289. #endif
  290. if( newBuffer )
  291. {
  292. newBuffer->numElements = buffer->numElements;
  293. newBuffer->maxElements = maxElements;
  294. }
  295. else
  296. {
  297. // Out of memory
  298. asIScriptContext *ctx = asGetActiveContext();
  299. if( ctx )
  300. ctx->SetException("Out of memory");
  301. return;
  302. }
  303. memcpy(newBuffer->data, buffer->data, buffer->numElements*elementSize);
  304. // Release the old buffer
  305. delete[] (asBYTE*)buffer;
  306. buffer = newBuffer;
  307. }
  308. void CScriptArray::Resize(asUINT numElements)
  309. {
  310. if( numElements & 0x80000000 )
  311. {
  312. CheckMaxSize(numElements);
  313. return;
  314. }
  315. Resize((int)numElements - (int)buffer->numElements, (asUINT)-1);
  316. }
  317. // Internal
  318. void CScriptArray::Resize(int delta, asUINT at)
  319. {
  320. if( delta < 0 )
  321. {
  322. if( -delta > (int)buffer->numElements )
  323. delta = -(int)buffer->numElements;
  324. if( at > buffer->numElements + delta )
  325. at = buffer->numElements + delta;
  326. }
  327. else if( delta > 0 )
  328. {
  329. // Make sure the array size isn't too large for us to handle
  330. if( delta > 0 && !CheckMaxSize(buffer->numElements + delta) )
  331. return;
  332. if( at > buffer->numElements )
  333. at = buffer->numElements;
  334. }
  335. if( delta == 0 ) return;
  336. if( buffer->maxElements < buffer->numElements + delta )
  337. {
  338. // Allocate memory for the buffer
  339. SArrayBuffer *newBuffer;
  340. #if defined(AS_MARMALADE)
  341. newBuffer = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1 + elementSize*(buffer->numElements + delta)];
  342. #else
  343. newBuffer = (SArrayBuffer*)new (nothrow) asBYTE[sizeof(SArrayBuffer)-1 + elementSize*(buffer->numElements + delta)];
  344. #endif
  345. if( newBuffer )
  346. {
  347. newBuffer->numElements = buffer->numElements + delta;
  348. newBuffer->maxElements = newBuffer->numElements;
  349. }
  350. else
  351. {
  352. // Out of memory
  353. asIScriptContext *ctx = asGetActiveContext();
  354. if( ctx )
  355. ctx->SetException("Out of memory");
  356. return;
  357. }
  358. memcpy(newBuffer->data, buffer->data, at*elementSize);
  359. if( at < buffer->numElements )
  360. memcpy(newBuffer->data + (at+delta)*elementSize, buffer->data + at*elementSize, (buffer->numElements-at)*elementSize);
  361. if( subTypeId & asTYPEID_MASK_OBJECT )
  362. Construct(newBuffer, at, at+delta);
  363. // Release the old buffer
  364. delete[] (asBYTE*)buffer;
  365. buffer = newBuffer;
  366. }
  367. else if( delta < 0 )
  368. {
  369. Destruct(buffer, at, at-delta);
  370. memmove(buffer->data + at*elementSize, buffer->data + (at-delta)*elementSize, (buffer->numElements - (at-delta))*elementSize);
  371. buffer->numElements += delta;
  372. }
  373. else
  374. {
  375. memmove(buffer->data + (at+delta)*elementSize, buffer->data + at*elementSize, (buffer->numElements - at)*elementSize);
  376. Construct(buffer, at, at+delta);
  377. buffer->numElements += delta;
  378. }
  379. }
  380. // internal
  381. bool CScriptArray::CheckMaxSize(asUINT numElements)
  382. {
  383. // This code makes sure the size of the buffer that is allocated
  384. // for the array doesn't overflow and becomes smaller than requested
  385. asUINT maxSize = 0xFFFFFFFFul - sizeof(SArrayBuffer) + 1;
  386. if( subTypeId & asTYPEID_MASK_OBJECT )
  387. maxSize /= sizeof(void*);
  388. else if( elementSize > 0 )
  389. maxSize /= elementSize;
  390. if( numElements > maxSize )
  391. {
  392. asIScriptContext *ctx = asGetActiveContext();
  393. if( ctx )
  394. {
  395. // Set a script exception
  396. ctx->SetException("Too large array size");
  397. }
  398. return false;
  399. }
  400. // OK
  401. return true;
  402. }
  403. asIObjectType *CScriptArray::GetArrayObjectType() const
  404. {
  405. return objType;
  406. }
  407. int CScriptArray::GetArrayTypeId() const
  408. {
  409. return objType->GetTypeId();
  410. }
  411. int CScriptArray::GetElementTypeId() const
  412. {
  413. return subTypeId;
  414. }
  415. void CScriptArray::InsertAt(asUINT index, void *value)
  416. {
  417. if( index > buffer->numElements )
  418. {
  419. // If this is called from a script we raise a script exception
  420. asIScriptContext *ctx = asGetActiveContext();
  421. if( ctx )
  422. ctx->SetException("Index out of bounds");
  423. return;
  424. }
  425. // Make room for the new element
  426. Resize(1, index);
  427. // Set the value of the new element
  428. SetValue(index, value);
  429. }
  430. void CScriptArray::InsertLast(void *value)
  431. {
  432. InsertAt(buffer->numElements, value);
  433. }
  434. void CScriptArray::RemoveAt(asUINT index)
  435. {
  436. if( index >= buffer->numElements )
  437. {
  438. // If this is called from a script we raise a script exception
  439. asIScriptContext *ctx = asGetActiveContext();
  440. if( ctx )
  441. ctx->SetException("Index out of bounds");
  442. return;
  443. }
  444. // Remove the element
  445. Resize(-1, index);
  446. }
  447. void CScriptArray::RemoveLast()
  448. {
  449. RemoveAt(buffer->numElements-1);
  450. }
  451. // Return a pointer to the array element. Returns 0 if the index is out of bounds
  452. const void *CScriptArray::At(asUINT index) const
  453. {
  454. if( buffer == 0 || index >= buffer->numElements )
  455. {
  456. // If this is called from a script we raise a script exception
  457. asIScriptContext *ctx = asGetActiveContext();
  458. if( ctx )
  459. ctx->SetException("Index out of bounds");
  460. return 0;
  461. }
  462. if( (subTypeId & asTYPEID_MASK_OBJECT) && !(subTypeId & asTYPEID_OBJHANDLE) )
  463. return (void*)((size_t*)buffer->data)[index];
  464. else
  465. return buffer->data + elementSize*index;
  466. }
  467. void *CScriptArray::At(asUINT index)
  468. {
  469. return const_cast<void*>(const_cast<const CScriptArray *>(this)->At(index));
  470. }
  471. // internal
  472. void CScriptArray::CreateBuffer(SArrayBuffer **buf, asUINT numElements)
  473. {
  474. if( subTypeId & asTYPEID_MASK_OBJECT )
  475. {
  476. #if defined( AS_MARMALADE )
  477. *buf = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1+sizeof(void*)*numElements];
  478. #else
  479. *buf = (SArrayBuffer*)new (nothrow) asBYTE[sizeof(SArrayBuffer)-1+sizeof(void*)*numElements];
  480. #endif
  481. }
  482. else
  483. {
  484. #if defined( AS_MARMALADE )
  485. *buf = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1+elementSize*numElements];
  486. #else
  487. *buf = (SArrayBuffer*)new (nothrow) asBYTE[sizeof(SArrayBuffer)-1+elementSize*numElements];
  488. #endif
  489. }
  490. if( *buf )
  491. {
  492. (*buf)->numElements = numElements;
  493. (*buf)->maxElements = numElements;
  494. Construct(*buf, 0, numElements);
  495. }
  496. else
  497. {
  498. // Oops, out of memory
  499. asIScriptContext *ctx = asGetActiveContext();
  500. if( ctx )
  501. ctx->SetException("Out of memory");
  502. }
  503. }
  504. // internal
  505. void CScriptArray::DeleteBuffer(SArrayBuffer *buf)
  506. {
  507. Destruct(buf, 0, buf->numElements);
  508. // Free the buffer
  509. delete[] (asBYTE*)buf;
  510. }
  511. // internal
  512. void CScriptArray::Construct(SArrayBuffer *buf, asUINT start, asUINT end)
  513. {
  514. if( subTypeId & asTYPEID_OBJHANDLE )
  515. {
  516. // Set all object handles to null
  517. void *d = (void*)(buf->data + start * sizeof(void*));
  518. memset(d, 0, (end-start)*sizeof(void*));
  519. }
  520. else if( subTypeId & asTYPEID_MASK_OBJECT )
  521. {
  522. void **max = (void**)(buf->data + end * sizeof(void*));
  523. void **d = (void**)(buf->data + start * sizeof(void*));
  524. asIScriptEngine *engine = objType->GetEngine();
  525. for( ; d < max; d++ )
  526. *d = (void*)engine->CreateScriptObject(subTypeId);
  527. }
  528. }
  529. // internal
  530. void CScriptArray::Destruct(SArrayBuffer *buf, asUINT start, asUINT end)
  531. {
  532. if( subTypeId & asTYPEID_MASK_OBJECT )
  533. {
  534. asIScriptEngine *engine = objType->GetEngine();
  535. void **max = (void**)(buf->data + end * sizeof(void*));
  536. void **d = (void**)(buf->data + start * sizeof(void*));
  537. for( ; d < max; d++ )
  538. {
  539. if( *d )
  540. engine->ReleaseScriptObject(*d, objType->GetSubType());
  541. }
  542. }
  543. }
  544. // internal
  545. bool CScriptArray::Less(const void *a, const void *b, bool asc, asIScriptContext *ctx)
  546. {
  547. if( !asc )
  548. {
  549. // Swap items
  550. const void *TEMP = a;
  551. a = b;
  552. b = TEMP;
  553. }
  554. if( !(subTypeId & ~asTYPEID_MASK_SEQNBR) )
  555. {
  556. // Simple compare of values
  557. switch( subTypeId )
  558. {
  559. #define COMPARE(T) *((T*)a) < *((T*)b)
  560. case asTYPEID_BOOL: return COMPARE(bool);
  561. case asTYPEID_INT8: return COMPARE(signed char);
  562. case asTYPEID_UINT8: return COMPARE(unsigned char);
  563. case asTYPEID_INT16: return COMPARE(signed short);
  564. case asTYPEID_UINT16: return COMPARE(unsigned short);
  565. case asTYPEID_INT32: return COMPARE(signed int);
  566. case asTYPEID_UINT32: return COMPARE(unsigned int);
  567. case asTYPEID_FLOAT: return COMPARE(float);
  568. case asTYPEID_DOUBLE: return COMPARE(double);
  569. default: return COMPARE(signed int); // All enums fall in this case
  570. #undef COMPARE
  571. }
  572. }
  573. else if( subTypeId & asTYPEID_OBJHANDLE )
  574. {
  575. return *((void**)a) < *((void**)b);
  576. }
  577. else
  578. {
  579. int r = 0;
  580. // Execute object opCmp
  581. SArrayCache *cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  582. if( cache && cache->cmpFunc )
  583. {
  584. // TODO: Add proper error handling
  585. r = ctx->Prepare(cache->cmpFunc); assert(r >= 0);
  586. r = ctx->SetObject((void*)a); assert(r >= 0);
  587. r = ctx->SetArgObject(0, (void*)b); assert(r >= 0);
  588. r = ctx->Execute();
  589. if( r == asEXECUTION_FINISHED )
  590. {
  591. return (int)ctx->GetReturnDWord() < 0;
  592. }
  593. }
  594. }
  595. return false;
  596. }
  597. void CScriptArray::Reverse()
  598. {
  599. asUINT size = GetSize();
  600. if( size >= 2 )
  601. {
  602. asBYTE TEMP[16];
  603. for( asUINT i = 0; i < size / 2; i++ )
  604. {
  605. Copy(TEMP, GetArrayItemPointer(i));
  606. Copy(GetArrayItemPointer(i), GetArrayItemPointer(size - i - 1));
  607. Copy(GetArrayItemPointer(size - i - 1), TEMP);
  608. }
  609. }
  610. }
  611. bool CScriptArray::operator==(const CScriptArray &other) const
  612. {
  613. if( objType != other.objType )
  614. return false;
  615. if( GetSize() != other.GetSize() )
  616. return false;
  617. asIScriptContext *cmpContext = 0;
  618. bool isNested = false;
  619. if( (subTypeId & ~asTYPEID_MASK_SEQNBR) && !(subTypeId & asTYPEID_OBJHANDLE) )
  620. {
  621. // Try to reuse the active context
  622. cmpContext = asGetActiveContext();
  623. if( cmpContext )
  624. {
  625. if( cmpContext->PushState() >= 0 )
  626. isNested = true;
  627. else
  628. cmpContext = 0;
  629. }
  630. if( cmpContext == 0 )
  631. {
  632. // TODO: Ideally this context would be retrieved from a pool, so we don't have to
  633. // create a new one everytime. We could keep a context with the array object
  634. // but that would consume a lot of resources as each context is quite heavy.
  635. cmpContext = objType->GetEngine()->CreateContext();
  636. }
  637. }
  638. // Check if all elements are equal
  639. bool isEqual = true;
  640. SArrayCache *cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  641. for( asUINT n = 0; n < GetSize(); n++ )
  642. if( !Equals(At(n), other.At(n), cmpContext, cache) )
  643. {
  644. isEqual = false;
  645. break;
  646. }
  647. if( cmpContext )
  648. {
  649. if( isNested )
  650. cmpContext->PopState();
  651. else
  652. cmpContext->Release();
  653. }
  654. return isEqual;
  655. }
  656. // internal
  657. bool CScriptArray::Equals(const void *a, const void *b, asIScriptContext *ctx, SArrayCache *cache) const
  658. {
  659. if( !(subTypeId & ~asTYPEID_MASK_SEQNBR) )
  660. {
  661. // Simple compare of values
  662. switch( subTypeId )
  663. {
  664. #define COMPARE(T) *((T*)a) == *((T*)b)
  665. case asTYPEID_BOOL: return COMPARE(bool);
  666. case asTYPEID_INT8: return COMPARE(signed char);
  667. case asTYPEID_UINT8: return COMPARE(unsigned char);
  668. case asTYPEID_INT16: return COMPARE(signed short);
  669. case asTYPEID_UINT16: return COMPARE(unsigned short);
  670. case asTYPEID_INT32: return COMPARE(signed int);
  671. case asTYPEID_UINT32: return COMPARE(unsigned int);
  672. case asTYPEID_FLOAT: return COMPARE(float);
  673. case asTYPEID_DOUBLE: return COMPARE(double);
  674. default: return COMPARE(signed int); // All enums fall here
  675. #undef COMPARE
  676. }
  677. }
  678. else if( subTypeId & asTYPEID_OBJHANDLE )
  679. {
  680. return *((void**)a) == *((void**)b);
  681. }
  682. else
  683. {
  684. int r = 0;
  685. // Execute object opEquals if available
  686. if( cache && cache->eqFunc )
  687. {
  688. // TODO: Add proper error handling
  689. r = ctx->Prepare(cache->eqFunc); assert(r >= 0);
  690. r = ctx->SetObject((void*)a); assert(r >= 0);
  691. r = ctx->SetArgObject(0, (void*)b); assert(r >= 0);
  692. r = ctx->Execute();
  693. if( r == asEXECUTION_FINISHED )
  694. {
  695. return ctx->GetReturnByte() != 0;
  696. }
  697. }
  698. // Execute object opCmp if available
  699. if( cache && cache->cmpFunc >= 0 )
  700. {
  701. // TODO: Add proper error handling
  702. r = ctx->Prepare(cache->cmpFunc); assert(r >= 0);
  703. r = ctx->SetObject((void*)a); assert(r >= 0);
  704. r = ctx->SetArgObject(0, (void*)b); assert(r >= 0);
  705. r = ctx->Execute();
  706. if( r == asEXECUTION_FINISHED )
  707. {
  708. return (int)ctx->GetReturnDWord() == 0;
  709. }
  710. }
  711. }
  712. return false;
  713. }
  714. int CScriptArray::Find(void *value) const
  715. {
  716. return Find(0, value);
  717. }
  718. int CScriptArray::Find(asUINT index, void *value) const
  719. {
  720. // Check if the subtype really supports find()
  721. // TODO: Can't this be done at compile time too by the template callback
  722. SArrayCache *cache = 0;
  723. if( (subTypeId & ~asTYPEID_MASK_SEQNBR) && !(subTypeId & asTYPEID_OBJHANDLE) )
  724. {
  725. cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  726. if( !cache || (cache->cmpFunc == 0 && cache->eqFunc == 0) )
  727. {
  728. asIScriptContext *ctx = asGetActiveContext();
  729. asIObjectType* subType = objType->GetEngine()->GetObjectTypeById(subTypeId);
  730. // Throw an exception
  731. if( ctx )
  732. {
  733. char tmp[512];
  734. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(AS_MARMALADE)
  735. sprintf_s(tmp, 512, "Type '%s' does not have opEquals / opCmp", subType->GetName());
  736. #else
  737. sprintf(tmp, "Type '%s' does not have opEquals / opCmp", subType->GetName());
  738. #endif
  739. ctx->SetException(tmp);
  740. }
  741. return -1;
  742. }
  743. }
  744. asIScriptContext *cmpContext = 0;
  745. bool isNested = false;
  746. if( (subTypeId & ~asTYPEID_MASK_SEQNBR) && !(subTypeId & asTYPEID_OBJHANDLE) )
  747. {
  748. // Try to reuse the active context
  749. cmpContext = asGetActiveContext();
  750. if( cmpContext )
  751. {
  752. if( cmpContext->PushState() >= 0 )
  753. isNested = true;
  754. else
  755. cmpContext = 0;
  756. }
  757. if( cmpContext == 0 )
  758. {
  759. // TODO: Ideally this context would be retrieved from a pool, so we don't have to
  760. // create a new one everytime. We could keep a context with the array object
  761. // but that would consume a lot of resources as each context is quite heavy.
  762. cmpContext = objType->GetEngine()->CreateContext();
  763. }
  764. }
  765. // Find the matching element
  766. int ret = -1;
  767. asUINT size = GetSize();
  768. if( index < size )
  769. {
  770. for( asUINT i = index; i < size; i++ )
  771. {
  772. // value passed by reference
  773. if( Equals(At(i), (value), cmpContext, cache) )
  774. {
  775. ret = (int)i;
  776. break;
  777. }
  778. }
  779. }
  780. if( cmpContext )
  781. {
  782. if( isNested )
  783. cmpContext->PopState();
  784. else
  785. cmpContext->Release();
  786. }
  787. return ret;
  788. }
  789. // internal
  790. // Copy object handle or primitive value
  791. void CScriptArray::Copy(void *dst, void *src)
  792. {
  793. memcpy(dst, src, elementSize);
  794. }
  795. // internal
  796. // Return pointer to array item (object handle or primitive value)
  797. void *CScriptArray::GetArrayItemPointer(int index)
  798. {
  799. return buffer->data + index * elementSize;
  800. }
  801. // internal
  802. // Return pointer to data in buffer (object or primitive)
  803. void *CScriptArray::GetDataPointer(void *buffer)
  804. {
  805. if ((subTypeId & asTYPEID_MASK_OBJECT) && !(subTypeId & asTYPEID_OBJHANDLE) )
  806. {
  807. // Real address of object
  808. return reinterpret_cast<void*>(*(size_t*)buffer);
  809. }
  810. else
  811. {
  812. // Primitive is just a raw data
  813. return buffer;
  814. }
  815. }
  816. // Sort ascending
  817. void CScriptArray::SortAsc()
  818. {
  819. Sort(0, GetSize(), true);
  820. }
  821. // Sort ascending
  822. void CScriptArray::SortAsc(asUINT index, asUINT count)
  823. {
  824. Sort(index, count, true);
  825. }
  826. // Sort descending
  827. void CScriptArray::SortDesc()
  828. {
  829. Sort(0, GetSize(), false);
  830. }
  831. // Sort descending
  832. void CScriptArray::SortDesc(asUINT index, asUINT count)
  833. {
  834. Sort(index, count, false);
  835. }
  836. // internal
  837. void CScriptArray::Sort(asUINT index, asUINT count, bool asc)
  838. {
  839. // Subtype isn't primitive and doesn't have opCmp
  840. SArrayCache *cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  841. if( (subTypeId & ~asTYPEID_MASK_SEQNBR) && !(subTypeId & asTYPEID_OBJHANDLE) )
  842. {
  843. if( !cache || cache->cmpFunc == 0 )
  844. {
  845. asIScriptContext *ctx = asGetActiveContext();
  846. asIObjectType* subType = objType->GetEngine()->GetObjectTypeById(subTypeId);
  847. // Throw an exception
  848. if( ctx )
  849. {
  850. char tmp[512];
  851. #if defined(_MSC_VER) && _MSC_VER >= 1500 && !defined(AS_MARMALADE)
  852. sprintf_s(tmp, 512, "Type '%s' does not have opCmp", subType->GetName());
  853. #else
  854. sprintf(tmp, "Type '%s' does not have opCmp", subType->GetName());
  855. #endif
  856. ctx->SetException(tmp);
  857. }
  858. return;
  859. }
  860. }
  861. // No need to sort
  862. if( count < 2 )
  863. {
  864. return;
  865. }
  866. int start = index;
  867. int end = index + count;
  868. // Check if we could access invalid item while sorting
  869. if( start >= (int)buffer->numElements || end > (int)buffer->numElements )
  870. {
  871. asIScriptContext *ctx = asGetActiveContext();
  872. // Throw an exception
  873. if( ctx )
  874. {
  875. ctx->SetException("Index out of bounds");
  876. }
  877. return;
  878. }
  879. asBYTE tmp[16];
  880. asIScriptContext *cmpContext = 0;
  881. bool isNested = false;
  882. if( (subTypeId & ~asTYPEID_MASK_SEQNBR) && !(subTypeId & asTYPEID_OBJHANDLE) )
  883. {
  884. // Try to reuse the active context
  885. cmpContext = asGetActiveContext();
  886. if( cmpContext )
  887. {
  888. if( cmpContext->PushState() >= 0 )
  889. isNested = true;
  890. else
  891. cmpContext = 0;
  892. }
  893. if( cmpContext == 0 )
  894. {
  895. // TODO: Ideally this context would be retrieved from a pool, so we don't have to
  896. // create a new one everytime. We could keep a context with the array object
  897. // but that would consume a lot of resources as each context is quite heavy.
  898. cmpContext = objType->GetEngine()->CreateContext();
  899. }
  900. }
  901. // Insertion sort
  902. for( int i = start + 1; i < end; i++ )
  903. {
  904. Copy(tmp, GetArrayItemPointer(i));
  905. int j = i - 1;
  906. while( j >= start && Less(GetDataPointer(tmp), At(j), asc, cmpContext) )
  907. {
  908. Copy(GetArrayItemPointer(j + 1), GetArrayItemPointer(j));
  909. j--;
  910. }
  911. Copy(GetArrayItemPointer(j + 1), tmp);
  912. }
  913. if( cmpContext )
  914. {
  915. if( isNested )
  916. cmpContext->PopState();
  917. else
  918. cmpContext->Release();
  919. }
  920. }
  921. // internal
  922. void CScriptArray::CopyBuffer(SArrayBuffer *dst, SArrayBuffer *src)
  923. {
  924. asIScriptEngine *engine = objType->GetEngine();
  925. if( subTypeId & asTYPEID_OBJHANDLE )
  926. {
  927. // Copy the references and increase the reference counters
  928. if( dst->numElements > 0 && src->numElements > 0 )
  929. {
  930. int count = dst->numElements > src->numElements ? src->numElements : dst->numElements;
  931. void **max = (void**)(dst->data + count * sizeof(void*));
  932. void **d = (void**)dst->data;
  933. void **s = (void**)src->data;
  934. for( ; d < max; d++, s++ )
  935. {
  936. void *tmp = *d;
  937. *d = *s;
  938. if( *d )
  939. engine->AddRefScriptObject(*d, objType->GetSubType());
  940. // Release the old ref after incrementing the new to avoid problem incase it is the same ref
  941. if( tmp )
  942. engine->ReleaseScriptObject(tmp, objType->GetSubType());
  943. }
  944. }
  945. }
  946. else
  947. {
  948. if( dst->numElements > 0 && src->numElements > 0 )
  949. {
  950. int count = dst->numElements > src->numElements ? src->numElements : dst->numElements;
  951. if( subTypeId & asTYPEID_MASK_OBJECT )
  952. {
  953. // Call the assignment operator on all of the objects
  954. void **max = (void**)(dst->data + count * sizeof(void*));
  955. void **d = (void**)dst->data;
  956. void **s = (void**)src->data;
  957. for( ; d < max; d++, s++ )
  958. engine->AssignScriptObject(*d, *s, subTypeId);
  959. }
  960. else
  961. {
  962. // Primitives are copied byte for byte
  963. memcpy(dst->data, src->data, count*elementSize);
  964. }
  965. }
  966. }
  967. }
  968. // internal
  969. // Precache some info
  970. void CScriptArray::Precache()
  971. {
  972. subTypeId = objType->GetSubTypeId();
  973. // Check if it is an array of objects. Only for these do we need to cache anything
  974. // Type ids for primitives and enums only has the sequence number part
  975. if( !(subTypeId & ~asTYPEID_MASK_SEQNBR) )
  976. return;
  977. // The opCmp and opEquals methods are cached because the searching for the
  978. // methods is quite time consuming if a lot of array objects are created.
  979. // First check if a cache already exists for this array type
  980. SArrayCache *cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  981. if( cache ) return;
  982. // We need to make sure the cache is created only once, even
  983. // if multiple threads reach the same point at the same time
  984. asAcquireExclusiveLock();
  985. // Now that we got the lock, we need to check again to make sure the
  986. // cache wasn't created while we were waiting for the lock
  987. cache = reinterpret_cast<SArrayCache*>(objType->GetUserData(ARRAY_CACHE));
  988. if( cache )
  989. {
  990. asReleaseExclusiveLock();
  991. return;
  992. }
  993. // Create the cache
  994. cache = new SArrayCache();
  995. memset(cache, 0, sizeof(SArrayCache));
  996. asIObjectType *subType = objType->GetEngine()->GetObjectTypeById(subTypeId);
  997. if( subType )
  998. {
  999. for( asUINT i = 0; i < subType->GetMethodCount(); i++ )
  1000. {
  1001. asIScriptFunction *func = subType->GetMethodByIndex(i);
  1002. if( func->GetParamCount() == 1 /* && func->IsReadOnly() */ )
  1003. {
  1004. asDWORD flags = 0;
  1005. int returnTypeId = func->GetReturnTypeId();
  1006. int paramTypeId = func->GetParamTypeId(0, &flags);
  1007. // The parameter must either be a reference to the subtype or a handle to the subtype
  1008. if( ((flags & asTM_INREF) && paramTypeId == subTypeId) ||
  1009. (flags == 0 &&
  1010. (paramTypeId & asTYPEID_OBJHANDLE) &&
  1011. (paramTypeId & ~(asTYPEID_OBJHANDLE | asTYPEID_HANDLETOCONST)) == (subTypeId & ~(asTYPEID_OBJHANDLE | asTYPEID_HANDLETOCONST))) )
  1012. {
  1013. if( returnTypeId == asTYPEID_INT32 && strcmp(func->GetName(), "opCmp") == 0 )
  1014. cache->cmpFunc = subType->GetMethodByIndex(i);
  1015. if( returnTypeId == asTYPEID_BOOL && strcmp(func->GetName(), "opEquals") == 0 )
  1016. cache->eqFunc = subType->GetMethodByIndex(i);
  1017. if( cache->cmpFunc && cache->eqFunc )
  1018. break;
  1019. }
  1020. }
  1021. }
  1022. }
  1023. // Set the user data only at the end so others that retrieve it will know it is complete
  1024. objType->SetUserData(cache, ARRAY_CACHE);
  1025. asReleaseExclusiveLock();
  1026. }
  1027. // GC behaviour
  1028. void CScriptArray::EnumReferences(asIScriptEngine *engine)
  1029. {
  1030. // If the array is holding handles, then we need to notify the GC of them
  1031. if( subTypeId & asTYPEID_MASK_OBJECT )
  1032. {
  1033. void **d = (void**)buffer->data;
  1034. for( asUINT n = 0; n < buffer->numElements; n++ )
  1035. {
  1036. if( d[n] )
  1037. engine->GCEnumCallback(d[n]);
  1038. }
  1039. }
  1040. }
  1041. // GC behaviour
  1042. void CScriptArray::ReleaseAllHandles(asIScriptEngine *engine)
  1043. {
  1044. // Resizing to zero will release everything
  1045. Resize(0);
  1046. }
  1047. void CScriptArray::AddRef() const
  1048. {
  1049. // Clear the GC flag then increase the counter
  1050. gcFlag = false;
  1051. refCount++;
  1052. }
  1053. void CScriptArray::Release() const
  1054. {
  1055. // Now do the actual releasing (clearing the flag set by GC)
  1056. gcFlag = false;
  1057. if( --refCount == 0 )
  1058. {
  1059. delete this;
  1060. }
  1061. }
  1062. // GC behaviour
  1063. int CScriptArray::GetRefCount()
  1064. {
  1065. return refCount;
  1066. }
  1067. // GC behaviour
  1068. void CScriptArray::SetFlag()
  1069. {
  1070. gcFlag = true;
  1071. }
  1072. // GC behaviour
  1073. bool CScriptArray::GetFlag()
  1074. {
  1075. return gcFlag;
  1076. }
  1077. static void ScriptArrayClear(CScriptArray* ptr)
  1078. {
  1079. ptr->Resize(0);
  1080. }
  1081. void RegisterArray(asIScriptEngine* engine)
  1082. {
  1083. // Register the object type user data clean up
  1084. engine->SetObjectTypeUserDataCleanupCallback(CleanupObjectTypeArrayCache, ARRAY_CACHE);
  1085. engine->RegisterObjectType("Array<class T>", 0, asOBJ_REF | asOBJ_TEMPLATE);
  1086. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_TEMPLATE_CALLBACK, "bool f(int&in, bool&out)", asFUNCTION(ScriptArrayTemplateCallback), asCALL_CDECL);
  1087. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_FACTORY, "Array<T>@ f(int& in)", asFUNCTIONPR(ScriptArrayFactory, (asIObjectType*), CScriptArray*), asCALL_CDECL);
  1088. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_FACTORY, "Array<T>@ f(int& in, uint)", asFUNCTIONPR(ScriptArrayFactory2, (asIObjectType*, asUINT), CScriptArray*), asCALL_CDECL);
  1089. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_FACTORY, "Array<T>@ f(int& in, uint, const T& in)", asFUNCTIONPR(ScriptArrayFactoryDefVal, (asIObjectType*, asUINT, void *), CScriptArray*), asCALL_CDECL);
  1090. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_LIST_FACTORY, "Array<T>@ f(int& in, uint)", asFUNCTIONPR(ScriptArrayFactory2, (asIObjectType*, asUINT), CScriptArray*), asCALL_CDECL);
  1091. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_ADDREF, "void f()", asMETHOD(CScriptArray,AddRef), asCALL_THISCALL);
  1092. engine->RegisterObjectBehaviour("Array<T>", asBEHAVE_RELEASE, "void f()", asMETHOD(CScriptArray,Release), asCALL_THISCALL);
  1093. engine->RegisterObjectMethod("Array<T>", "T& opIndex(uint)", asMETHODPR(CScriptArray, At, (unsigned), void*), asCALL_THISCALL);
  1094. engine->RegisterObjectMethod("Array<T>", "const T& opIndex(uint) const", asMETHODPR(CScriptArray, At, (unsigned), void*), asCALL_THISCALL);
  1095. engine->RegisterObjectMethod("Array<T>", "Array<T>& opAssign(const Array<T>& in)", asMETHOD(CScriptArray, operator=), asCALL_THISCALL);
  1096. engine->RegisterObjectMethod("Array<T>", "void Insert(uint, const T& in)", asMETHOD(CScriptArray, InsertAt), asCALL_THISCALL);
  1097. engine->RegisterObjectMethod("Array<T>", "void Erase(uint)", asMETHOD(CScriptArray, RemoveAt), asCALL_THISCALL);
  1098. engine->RegisterObjectMethod("Array<T>", "void Push(const T& in)", asMETHOD(CScriptArray, InsertLast), asCALL_THISCALL);
  1099. engine->RegisterObjectMethod("Array<T>", "void Pop()", asMETHOD(CScriptArray, RemoveLast), asCALL_THISCALL);
  1100. engine->RegisterObjectMethod("Array<T>", "void Resize(uint)", asMETHODPR(CScriptArray, Resize, (asUINT), void), asCALL_THISCALL);
  1101. engine->RegisterObjectMethod("Array<T>", "void Clear()", asFUNCTION(ScriptArrayClear), asCALL_CDECL_OBJLAST);
  1102. engine->RegisterObjectMethod("Array<T>", "void Sort()", asMETHODPR(CScriptArray, SortAsc, (), void), asCALL_THISCALL);
  1103. engine->RegisterObjectMethod("Array<T>", "void Sort(uint, uint)", asMETHODPR(CScriptArray, SortAsc, (asUINT, asUINT), void), asCALL_THISCALL);
  1104. engine->RegisterObjectMethod("Array<T>", "void SortReverse()", asMETHODPR(CScriptArray, SortDesc, (), void), asCALL_THISCALL);
  1105. engine->RegisterObjectMethod("Array<T>", "void SortReverse(uint, uint)", asMETHODPR(CScriptArray, SortDesc, (asUINT, asUINT), void), asCALL_THISCALL);
  1106. engine->RegisterObjectMethod("Array<T>", "void Reverse()", asMETHOD(CScriptArray, Reverse), asCALL_THISCALL);
  1107. engine->RegisterObjectMethod("Array<T>", "int Find(const T&in) const", asMETHODPR(CScriptArray, Find, (void*) const, int), asCALL_THISCALL);
  1108. engine->RegisterObjectMethod("Array<T>", "int Find(uint, const T&in) const", asMETHODPR(CScriptArray, Find, (asUINT, void*) const, int), asCALL_THISCALL);
  1109. engine->RegisterObjectMethod("Array<T>", "bool opEquals(const Array<T>&in) const", asMETHOD(CScriptArray, operator==), asCALL_THISCALL);
  1110. engine->RegisterObjectMethod("Array<T>", "uint get_length() const", asMETHOD(CScriptArray, GetSize), asCALL_THISCALL);
  1111. engine->RegisterObjectMethod("Array<T>", "void set_length(uint)", asMETHODPR(CScriptArray, Resize, (asUINT), void), asCALL_THISCALL);
  1112. engine->RegisterObjectMethod("Array<T>", "bool get_empty() const", asMETHOD(CScriptArray, IsEmpty), asCALL_THISCALL);
  1113. engine->RegisterDefaultArrayType("Array<T>");
  1114. }
  1115. static String StringFactory(asUINT length, const char* s)
  1116. {
  1117. return String(s, length);
  1118. }
  1119. static void ConstructString(String* ptr)
  1120. {
  1121. new(ptr) String();
  1122. }
  1123. static void ConstructStringCopy(const String& str, String* ptr)
  1124. {
  1125. new(ptr) String(str);
  1126. }
  1127. static void DestructString(String* ptr)
  1128. {
  1129. ptr->~String();
  1130. }
  1131. static char* StringCharAt(unsigned int i, String& str)
  1132. {
  1133. if (i >= str.Length())
  1134. {
  1135. asIScriptContext* context = asGetActiveContext();
  1136. if (context)
  1137. context->SetException("Index out of bounds");
  1138. return 0;
  1139. }
  1140. return &str[i];
  1141. }
  1142. static int StringCmp(const String& lhs, const String& rhs)
  1143. {
  1144. int cmp = 0;
  1145. if (lhs < rhs)
  1146. cmp = -1;
  1147. else if (lhs > rhs)
  1148. cmp = 1;
  1149. return cmp;
  1150. }
  1151. void StringResize(unsigned newSize, String& str)
  1152. {
  1153. unsigned oldSize = str.Length();
  1154. str.Resize(newSize);
  1155. for (unsigned i = oldSize; i < newSize; ++i)
  1156. str[i] = ' ';
  1157. }
  1158. static void ConstructStringInt(int value, String* ptr)
  1159. {
  1160. new(ptr) String(value);
  1161. }
  1162. static void ConstructStringUInt(unsigned value, String* ptr)
  1163. {
  1164. new(ptr) String(value);
  1165. }
  1166. static void ConstructStringFloat(float value, String* ptr)
  1167. {
  1168. new(ptr) String(value);
  1169. }
  1170. static void ConstructStringBool(bool value, String* ptr)
  1171. {
  1172. new(ptr) String(value);
  1173. }
  1174. static String& StringAssignInt(int value, String& str)
  1175. {
  1176. str = String(value);
  1177. return str;
  1178. }
  1179. static String& StringAddAssignInt(int value, String& str)
  1180. {
  1181. str += String(value);
  1182. return str;
  1183. }
  1184. static String StringAddInt(int value, const String& str)
  1185. {
  1186. return str + String(value);
  1187. }
  1188. static String StringAddIntReverse(int value, const String& str)
  1189. {
  1190. return String(value) + str;
  1191. }
  1192. static String& StringAssignUInt(unsigned value, String& str)
  1193. {
  1194. str = String(value);
  1195. return str;
  1196. }
  1197. static String& StringAddAssignUInt(unsigned value, String& str)
  1198. {
  1199. str += String(value);
  1200. return str;
  1201. }
  1202. static String StringAddUInt(unsigned value, const String& str)
  1203. {
  1204. return str + String(value);
  1205. }
  1206. static String StringAddUIntReverse(unsigned value, const String& str)
  1207. {
  1208. return String(value) + str;
  1209. }
  1210. static String& StringAssignFloat(float value, String& str)
  1211. {
  1212. str = String(value);
  1213. return str;
  1214. }
  1215. static String& StringAddAssignFloat(float value, String& str)
  1216. {
  1217. str += String(value);
  1218. return str;
  1219. }
  1220. static String StringAddFloat(float value, const String& str)
  1221. {
  1222. return str + String(value);
  1223. }
  1224. static String StringAddFloatReverse(float value, const String& str)
  1225. {
  1226. return String(value) + str;
  1227. }
  1228. static String& StringAssignBool(bool value, String& str)
  1229. {
  1230. str = String(value);
  1231. return str;
  1232. }
  1233. static String& StringAddAssignBool(bool value, String& str)
  1234. {
  1235. str += String(value);
  1236. return str;
  1237. }
  1238. static String StringAddBool(bool value, const String& str)
  1239. {
  1240. return str + String(value);
  1241. }
  1242. static String StringAddBoolReverse(bool value, const String& str)
  1243. {
  1244. return String(value) + str;
  1245. }
  1246. static void StringSetUTF8FromLatin1(const String& src, String& str)
  1247. {
  1248. str.SetUTF8FromLatin1(src.CString());
  1249. }
  1250. void RegisterString(asIScriptEngine *engine)
  1251. {
  1252. engine->RegisterObjectType("String", sizeof(String), asOBJ_VALUE | asOBJ_APP_CLASS_CDAK);
  1253. engine->RegisterStringFactory("String", asFUNCTION(StringFactory), asCALL_CDECL);
  1254. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ConstructString), asCALL_CDECL_OBJLAST);
  1255. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(const String&in)", asFUNCTION(ConstructStringCopy), asCALL_CDECL_OBJLAST);
  1256. engine->RegisterObjectBehaviour("String", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(DestructString), asCALL_CDECL_OBJLAST);
  1257. engine->RegisterObjectMethod("String", "String& opAssign(const String&in)", asMETHODPR(String, operator =, (const String&), String&), asCALL_THISCALL);
  1258. engine->RegisterObjectMethod("String", "String& opAddAssign(const String&in)", asMETHODPR(String, operator +=, (const String&), String&), asCALL_THISCALL);
  1259. engine->RegisterObjectMethod("String", "bool opEquals(const String&in) const", asMETHODPR(String, operator ==, (const String&) const, bool), asCALL_THISCALL);
  1260. engine->RegisterObjectMethod("String", "int opCmp(const String&in) const", asFUNCTION(StringCmp), asCALL_CDECL_OBJFIRST);
  1261. engine->RegisterObjectMethod("String", "String opAdd(const String&in) const", asMETHODPR(String, operator +, (const String&) const, String), asCALL_THISCALL);
  1262. engine->RegisterObjectMethod("String", "uint8 &opIndex(uint)", asFUNCTION(StringCharAt), asCALL_CDECL_OBJLAST);
  1263. engine->RegisterObjectMethod("String", "const uint8 &opIndex(uint) const", asFUNCTION(StringCharAt), asCALL_CDECL_OBJLAST);
  1264. engine->RegisterObjectMethod("String", "void Replace(uint8, uint8)", asMETHODPR(String, Replace, (char, char), void), asCALL_THISCALL);
  1265. engine->RegisterObjectMethod("String", "void Replace(const String&in, const String&in)", asMETHODPR(String, Replace, (const String&, const String&), void), asCALL_THISCALL);
  1266. engine->RegisterObjectMethod("String", "String Replaced(uint8, uint8) const", asMETHODPR(String, Replaced, (char, char) const, String), asCALL_THISCALL);
  1267. engine->RegisterObjectMethod("String", "String Replaced(const String&in, const String&in) const", asMETHODPR(String, Replaced, (const String&, const String&) const, String), asCALL_THISCALL);
  1268. engine->RegisterObjectMethod("String", "void Resize(uint)", asFUNCTION(StringResize), asCALL_CDECL_OBJLAST);
  1269. engine->RegisterObjectMethod("String", "uint Find(const String&in, uint start = 0) const", asMETHODPR(String, Find, (const String&, unsigned) const, unsigned), asCALL_THISCALL);
  1270. engine->RegisterObjectMethod("String", "uint Find(uint8, uint start = 0) const", asMETHODPR(String, Find, (char, unsigned) const, unsigned), asCALL_THISCALL);
  1271. engine->RegisterObjectMethod("String", "uint FindLast(const String&in, uint start = 0xffffffff) const", asMETHODPR(String, FindLast, (const String&, unsigned) const, unsigned), asCALL_THISCALL);
  1272. engine->RegisterObjectMethod("String", "uint FindLast(uint8, uint start = 0xffffffff) const", asMETHODPR(String, FindLast, (char, unsigned) const, unsigned), asCALL_THISCALL);
  1273. engine->RegisterObjectMethod("String", "bool StartsWith(const String&in) const", asMETHOD(String, StartsWith), asCALL_THISCALL);
  1274. engine->RegisterObjectMethod("String", "bool EndsWith(const String&in) const", asMETHOD(String, EndsWith), asCALL_THISCALL);
  1275. engine->RegisterObjectMethod("String", "String Substring(uint) const", asMETHODPR(String, Substring, (unsigned) const, String), asCALL_THISCALL);
  1276. engine->RegisterObjectMethod("String", "String Substring(uint, uint) const", asMETHODPR(String, Substring, (unsigned, unsigned) const, String), asCALL_THISCALL);
  1277. engine->RegisterObjectMethod("String", "String ToUpper() const", asMETHOD(String, ToUpper), asCALL_THISCALL);
  1278. engine->RegisterObjectMethod("String", "String ToLower() const", asMETHOD(String, ToLower), asCALL_THISCALL);
  1279. engine->RegisterObjectMethod("String", "String Trimmed() const", asMETHOD(String, Trimmed), asCALL_THISCALL);
  1280. engine->RegisterObjectMethod("String", "void SetUTF8FromLatin1(const String& in)", asFUNCTION(StringSetUTF8FromLatin1), asCALL_CDECL_OBJLAST);
  1281. engine->RegisterObjectMethod("String", "uint get_utf8Length() const", asMETHOD(String, LengthUTF8), asCALL_THISCALL);
  1282. engine->RegisterObjectMethod("String", "uint ByteOffsetUTF8(uint) const", asMETHOD(String, ByteOffsetUTF8), asCALL_THISCALL);
  1283. engine->RegisterObjectMethod("String", "uint NextUTF8Char(uint&) const", asMETHOD(String, NextUTF8Char), asCALL_THISCALL);
  1284. engine->RegisterObjectMethod("String", "uint AtUTF8(uint) const", asMETHOD(String, AtUTF8), asCALL_THISCALL);
  1285. engine->RegisterObjectMethod("String", "void ReplaceUTF8(uint, uint)", asMETHOD(String, ReplaceUTF8), asCALL_THISCALL);
  1286. engine->RegisterObjectMethod("String", "void AppendUTF8(uint)", asMETHOD(String, AppendUTF8), asCALL_THISCALL);
  1287. engine->RegisterObjectMethod("String", "String SubstringUTF8(uint) const", asMETHODPR(String, SubstringUTF8, (unsigned) const, String), asCALL_THISCALL);
  1288. engine->RegisterObjectMethod("String", "String SubstringUTF8(uint, uint) const", asMETHODPR(String, SubstringUTF8, (unsigned, unsigned) const, String), asCALL_THISCALL);
  1289. engine->RegisterObjectMethod("String", "uint get_length() const", asMETHOD(String, Length), asCALL_THISCALL);
  1290. engine->RegisterObjectMethod("String", "bool get_empty() const", asMETHOD(String, Empty), asCALL_THISCALL);
  1291. engine->RegisterObjectMethod("String", "int Compare(const String&in, bool caseSensitive = true) const", asMETHODPR(String, Compare, (const String&, bool) const, int), asCALL_THISCALL);
  1292. engine->RegisterObjectMethod("String", "bool Contains(const String&in) const", asMETHODPR(String, Contains, (const String&) const, bool), asCALL_THISCALL);
  1293. engine->RegisterObjectMethod("String", "bool Contains(uint8) const", asMETHODPR(String, Contains, (char) const, bool), asCALL_THISCALL);
  1294. engine->RegisterObjectMethod("String", "void Clear()", asMETHOD(String, Clear), asCALL_THISCALL);
  1295. // Register automatic conversion functions for convenience
  1296. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(int)", asFUNCTION(ConstructStringInt), asCALL_CDECL_OBJLAST);
  1297. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(uint)", asFUNCTION(ConstructStringUInt), asCALL_CDECL_OBJLAST);
  1298. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(float)", asFUNCTION(ConstructStringFloat), asCALL_CDECL_OBJLAST);
  1299. engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f(bool)", asFUNCTION(ConstructStringBool), asCALL_CDECL_OBJLAST);
  1300. engine->RegisterObjectMethod("String", "String& opAssign(int)", asFUNCTION(StringAssignInt), asCALL_CDECL_OBJLAST);
  1301. engine->RegisterObjectMethod("String", "String& opAddAssign(int)", asFUNCTION(StringAddAssignInt), asCALL_CDECL_OBJLAST);
  1302. engine->RegisterObjectMethod("String", "String opAdd(int) const", asFUNCTION(StringAddInt), asCALL_CDECL_OBJLAST);
  1303. engine->RegisterObjectMethod("String", "String opAdd_r(int) const", asFUNCTION(StringAddIntReverse), asCALL_CDECL_OBJLAST);
  1304. engine->RegisterObjectMethod("String", "String& opAssign(uint)", asFUNCTION(StringAssignUInt), asCALL_CDECL_OBJLAST);
  1305. engine->RegisterObjectMethod("String", "String& opAddAssign(uint)", asFUNCTION(StringAddAssignUInt), asCALL_CDECL_OBJLAST);
  1306. engine->RegisterObjectMethod("String", "String opAdd(uint) const", asFUNCTION(StringAddUInt), asCALL_CDECL_OBJLAST);
  1307. engine->RegisterObjectMethod("String", "String opAdd_r(uint) const", asFUNCTION(StringAddUIntReverse), asCALL_CDECL_OBJLAST);
  1308. engine->RegisterObjectMethod("String", "String& opAssign(float)", asFUNCTION(StringAssignFloat), asCALL_CDECL_OBJLAST);
  1309. engine->RegisterObjectMethod("String", "String& opAddAssign(float)", asFUNCTION(StringAddAssignFloat), asCALL_CDECL_OBJLAST);
  1310. engine->RegisterObjectMethod("String", "String opAdd(float) const", asFUNCTION(StringAddFloat), asCALL_CDECL_OBJLAST);
  1311. engine->RegisterObjectMethod("String", "String opAdd_r(float) const", asFUNCTION(StringAddFloatReverse), asCALL_CDECL_OBJLAST);
  1312. engine->RegisterObjectMethod("String", "String& opAssign(bool)", asFUNCTION(StringAssignBool), asCALL_CDECL_OBJLAST);
  1313. engine->RegisterObjectMethod("String", "String& opAddAssign(bool)", asFUNCTION(StringAddAssignBool), asCALL_CDECL_OBJLAST);
  1314. engine->RegisterObjectMethod("String", "String opAdd(bool) const", asFUNCTION(StringAddBool), asCALL_CDECL_OBJLAST);
  1315. engine->RegisterObjectMethod("String", "String opAdd_r(bool) const", asFUNCTION(StringAddBoolReverse), asCALL_CDECL_OBJLAST);
  1316. }
  1317. }