RegisterArray.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Exception.h"
  25. #include "RegisterArray.h"
  26. #include <cstring>
  27. #include "DebugNew.h"
  28. // Adapted from Angelscript's scriptarray add-on, but with garbage collection disabled, and method names changed
  29. // to a kind of a C++ / JavaScript hybrid
  30. //! Script array buffer
  31. struct SArrayBuffer
  32. {
  33. asDWORD numElements;
  34. asBYTE data[1];
  35. };
  36. static CScriptArray* ScriptArrayFactory2(asIObjectType* ot, asUINT length)
  37. {
  38. CScriptArray* a = new CScriptArray(length, ot);
  39. // It's possible the constructor raised a script exception, in which case we
  40. // need to free the memory and return null instead, else we get a memory leak.
  41. asIScriptContext* context = asGetActiveContext();
  42. if (context && context->GetState() == asEXECUTION_EXCEPTION)
  43. {
  44. delete a;
  45. return 0;
  46. }
  47. return a;
  48. }
  49. static CScriptArray* ScriptArrayFactoryDefVal(asIObjectType* ot, asUINT length, void* defVal)
  50. {
  51. CScriptArray* a = new CScriptArray(length, defVal, ot);
  52. // It's possible the constructor raised a script exception, in which case we
  53. // need to free the memory and return null instead, else we get a memory leak.
  54. asIScriptContext* context = asGetActiveContext();
  55. if (context && context->GetState() == asEXECUTION_EXCEPTION)
  56. {
  57. delete a;
  58. return 0;
  59. }
  60. return a;
  61. }
  62. static CScriptArray* ScriptArrayFactory(asIObjectType* ot)
  63. {
  64. return ScriptArrayFactory2(ot, 0);
  65. }
  66. // This optional callback is called when the template type is first used by the compiler.
  67. // It allows the application to validate if the template can be instanciated for the requested
  68. // subtype at compile time, instead of at runtime.
  69. static bool ScriptArrayTemplateCallback(asIObjectType* ot)
  70. {
  71. // Make sure the subtype can be instanciated with a default factory/constructor,
  72. // otherwise we won't be able to instanciate the elements. Script classes always
  73. // have default factories, so we don't have to worry about those.
  74. int typeId = ot->GetSubTypeId();
  75. if ((typeId & asTYPEID_MASK_OBJECT) && !(typeId & asTYPEID_OBJHANDLE) && !(typeId & asTYPEID_SCRIPTOBJECT))
  76. {
  77. asIObjectType *subtype = ot->GetEngine()->GetObjectTypeById(typeId);
  78. asDWORD flags = subtype->GetFlags();
  79. if ((flags & asOBJ_VALUE) && !(flags & asOBJ_POD))
  80. {
  81. // Verify that there is a default constructor
  82. for (int n = 0; n < subtype->GetBehaviourCount(); ++n)
  83. {
  84. asEBehaviours beh;
  85. int funcId = subtype->GetBehaviourByIndex(n, &beh);
  86. if (beh != asBEHAVE_CONSTRUCT)
  87. continue;
  88. asIScriptFunction* func = ot->GetEngine()->GetFunctionDescriptorById(funcId);
  89. if (func->GetParamCount() == 0)
  90. {
  91. // Found the default constructor
  92. return true;
  93. }
  94. }
  95. // There is no default constructor
  96. return false;
  97. }
  98. else if ((flags & asOBJ_REF))
  99. {
  100. // Verify that there is a default factory
  101. for (int n = 0; n < subtype->GetFactoryCount(); ++n)
  102. {
  103. int funcId = subtype->GetFactoryIdByIndex(n);
  104. asIScriptFunction* func = ot->GetEngine()->GetFunctionDescriptorById(funcId);
  105. if (func->GetParamCount() == 0)
  106. {
  107. // Found the default factory
  108. return true;
  109. }
  110. }
  111. // No default factory
  112. return false;
  113. }
  114. }
  115. // The type is ok
  116. return true;
  117. }
  118. CScriptArray& CScriptArray::operator = (const CScriptArray &other)
  119. {
  120. // Only perform the copy if the array types are the same
  121. if (&other != this && other.GetArrayObjectType() == GetArrayObjectType())
  122. {
  123. if (buffer)
  124. {
  125. DeleteBuffer(buffer);
  126. buffer = 0;
  127. }
  128. // Copy all elements from the other array
  129. CreateBuffer(&buffer, other.buffer->numElements);
  130. CopyBuffer(buffer, other.buffer);
  131. }
  132. return *this;
  133. }
  134. CScriptArray::CScriptArray(asUINT length, asIObjectType* ot)
  135. {
  136. refCount = 1;
  137. gcFlag = false;
  138. objType = ot;
  139. objType->AddRef();
  140. buffer = 0;
  141. // Determine element size
  142. // TODO: Should probably store the template sub type id as well
  143. int typeId = objType->GetSubTypeId();
  144. if (typeId & asTYPEID_MASK_OBJECT)
  145. elementSize = sizeof(asPWORD);
  146. else
  147. elementSize = objType->GetEngine()->GetSizeOfPrimitiveType(typeId);
  148. isArrayOfHandles = typeId & asTYPEID_OBJHANDLE ? true : false;
  149. // Make sure the array size isn't too large for us to handle
  150. if (!CheckMaxSize(length))
  151. {
  152. // Don't continue with the initialization
  153. return;
  154. }
  155. CreateBuffer(&buffer, length);
  156. }
  157. CScriptArray::CScriptArray(asUINT length, void *defVal, asIObjectType *ot)
  158. {
  159. refCount = 1;
  160. gcFlag = false;
  161. objType = ot;
  162. objType->AddRef();
  163. buffer = 0;
  164. // Determine element size
  165. // TODO: Should probably store the template sub type id as well
  166. int typeId = objType->GetSubTypeId();
  167. if (typeId & asTYPEID_MASK_OBJECT)
  168. elementSize = sizeof(asPWORD);
  169. else
  170. elementSize = objType->GetEngine()->GetSizeOfPrimitiveType(typeId);
  171. isArrayOfHandles = typeId & asTYPEID_OBJHANDLE ? true : false;
  172. // Make sure the array size isn't too large for us to handle
  173. if (!CheckMaxSize(length))
  174. {
  175. // Don't continue with the initialization
  176. return;
  177. }
  178. CreateBuffer(&buffer, length);
  179. // Initialize the elements with the default value
  180. for (asUINT n = 0; n < GetSize(); ++n)
  181. SetValue(n, defVal);
  182. }
  183. // Internal
  184. void CScriptArray::SetValue(asUINT index, void *value)
  185. {
  186. int typeId = objType->GetSubTypeId();
  187. if ((typeId & ~0x03FFFFFF) && !(typeId & asTYPEID_OBJHANDLE))
  188. objType->GetEngine()->CopyScriptObject(At(index), value, typeId);
  189. else if (typeId & asTYPEID_OBJHANDLE)
  190. {
  191. *(void**)At(index) = *(void**)value;
  192. objType->GetEngine()->AddRefScriptObject(*(void**)value, typeId);
  193. }
  194. else if (typeId == asTYPEID_BOOL || typeId == asTYPEID_INT8 || typeId == asTYPEID_UINT8)
  195. *(char*)At(index) = *(char*)value;
  196. else if (typeId == asTYPEID_INT16 || typeId == asTYPEID_UINT16)
  197. *(short*)At(index) = *(short*)value;
  198. else if (typeId == asTYPEID_INT32 || typeId == asTYPEID_UINT32 || typeId == asTYPEID_FLOAT)
  199. *(int*)At(index) = *(int*)value;
  200. else if (typeId == asTYPEID_INT64 || typeId == asTYPEID_UINT64 || typeId == asTYPEID_DOUBLE)
  201. *(double*)At(index) = *(double*)value;
  202. }
  203. CScriptArray::~CScriptArray()
  204. {
  205. if (buffer)
  206. {
  207. DeleteBuffer(buffer);
  208. buffer = 0;
  209. }
  210. if (objType)
  211. objType->Release();
  212. }
  213. asUINT CScriptArray::GetSize() const
  214. {
  215. return buffer->numElements;
  216. }
  217. void CScriptArray::Resize(asUINT numElements)
  218. {
  219. if (numElements & 0x80000000)
  220. {
  221. CheckMaxSize(numElements);
  222. return;
  223. }
  224. Resize((int)numElements - (int)buffer->numElements, -1);
  225. }
  226. // Internal
  227. void CScriptArray::Resize(int delta, asUINT at)
  228. {
  229. if (delta < 0)
  230. {
  231. if (-delta > (int)buffer->numElements)
  232. delta = -(int)buffer->numElements;
  233. if (at > buffer->numElements + delta)
  234. at = buffer->numElements + delta;
  235. }
  236. else if (delta > 0)
  237. {
  238. // Make sure the array size isn't too large for us to handle
  239. if (delta > 0 && !CheckMaxSize(buffer->numElements + delta))
  240. return;
  241. if (at > buffer->numElements)
  242. at = buffer->numElements;
  243. }
  244. if (delta == 0)
  245. return;
  246. // Allocate memory for the buffer
  247. SArrayBuffer *newBuffer;
  248. newBuffer = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1 + elementSize*(buffer->numElements + delta)];
  249. newBuffer->numElements = buffer->numElements + delta;
  250. int c = newBuffer->numElements > buffer->numElements ? buffer->numElements : newBuffer->numElements;
  251. memcpy(newBuffer->data, buffer->data, at*elementSize);
  252. if (delta > 0 && at < buffer->numElements)
  253. memcpy(newBuffer->data + (at+delta)*elementSize, buffer->data + at*elementSize, (buffer->numElements-at)*elementSize);
  254. else if (delta < 0 && at < buffer->numElements)
  255. memcpy(newBuffer->data + at*elementSize, buffer->data + (at-delta)*elementSize, (buffer->numElements-at+delta)*elementSize);
  256. int typeId = objType->GetSubTypeId();
  257. if (typeId & asTYPEID_MASK_OBJECT)
  258. {
  259. if (delta > 0)
  260. Construct(newBuffer, at, at+delta);
  261. else if (delta < 0)
  262. Destruct(buffer, at, at-delta);
  263. }
  264. // Release the old buffer
  265. delete[] (asBYTE*)buffer;
  266. buffer = newBuffer;
  267. }
  268. // internal
  269. bool CScriptArray::CheckMaxSize(asUINT numElements)
  270. {
  271. // This code makes sure the size of the buffer that is allocated
  272. // for the array doesn't overflow and becomes smaller than requested
  273. asUINT maxSize = 0xFFFFFFFFul - sizeof(SArrayBuffer) + 1;
  274. if (objType->GetSubTypeId() & asTYPEID_MASK_OBJECT)
  275. maxSize /= sizeof(void*);
  276. else
  277. maxSize /= elementSize;
  278. if (numElements > maxSize)
  279. SAFE_EXCEPTION_RET("Too large array size", false);
  280. // OK
  281. return true;
  282. }
  283. asIObjectType *CScriptArray::GetArrayObjectType() const
  284. {
  285. return objType;
  286. }
  287. int CScriptArray::GetArrayTypeId() const
  288. {
  289. return objType->GetTypeId();
  290. }
  291. int CScriptArray::GetElementTypeId() const
  292. {
  293. return objType->GetSubTypeId();
  294. }
  295. void CScriptArray::InsertAt(asUINT index, void *value)
  296. {
  297. if (index > buffer->numElements)
  298. SAFE_EXCEPTION("Index out of bounds");
  299. // Make room for the new element
  300. Resize(1, index);
  301. // Set the value of the new element
  302. SetValue(index, value);
  303. }
  304. void CScriptArray::InsertLast(void *value)
  305. {
  306. InsertAt(buffer->numElements, value);
  307. }
  308. void CScriptArray::RemoveAt(asUINT index)
  309. {
  310. if (index >= buffer->numElements)
  311. SAFE_EXCEPTION("Index out of bounds");
  312. // Remove the element
  313. Resize(-1, index);
  314. }
  315. void CScriptArray::RemoveLast()
  316. {
  317. RemoveAt(buffer->numElements-1);
  318. }
  319. // Return a pointer to the array element. Returns 0 if the index is out of bounds
  320. void *CScriptArray::At(asUINT index)
  321. {
  322. if (index >= buffer->numElements)
  323. {
  324. SAFE_EXCEPTION_RET("Index out of bounds", 0);
  325. }
  326. else
  327. {
  328. int typeId = objType->GetSubTypeId();
  329. if ((typeId & asTYPEID_MASK_OBJECT) && !isArrayOfHandles)
  330. return (void*)((size_t*)buffer->data)[index];
  331. else
  332. return buffer->data + elementSize*index;
  333. }
  334. }
  335. // internal
  336. void CScriptArray::CreateBuffer(SArrayBuffer **buf, asUINT numElements)
  337. {
  338. int typeId = objType->GetSubTypeId();
  339. if (typeId & asTYPEID_MASK_OBJECT)
  340. {
  341. *buf = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1+sizeof(void*)*numElements];
  342. (*buf)->numElements = numElements;
  343. }
  344. else
  345. {
  346. *buf = (SArrayBuffer*)new asBYTE[sizeof(SArrayBuffer)-1+elementSize*numElements];
  347. (*buf)->numElements = numElements;
  348. }
  349. Construct(*buf, 0, numElements);
  350. }
  351. // internal
  352. void CScriptArray::DeleteBuffer(SArrayBuffer *buf)
  353. {
  354. Destruct(buf, 0, buf->numElements);
  355. // Free the buffer
  356. delete[] (asBYTE*)buf;
  357. }
  358. // internal
  359. void CScriptArray::Construct(SArrayBuffer *buf, asUINT start, asUINT end)
  360. {
  361. int typeId = objType->GetSubTypeId();
  362. if (isArrayOfHandles)
  363. {
  364. // Set all object handles to null
  365. void* d = (void*)(buf->data + start * sizeof(void*));
  366. memset(d, 0, (end-start)*sizeof(void*));
  367. }
  368. else if (typeId & asTYPEID_MASK_OBJECT)
  369. {
  370. void** max = (void**)(buf->data + end * sizeof(void*));
  371. void** d = (void**)(buf->data + start * sizeof(void*));
  372. asIScriptEngine* engine = objType->GetEngine();
  373. for (; d < max; d++)
  374. *d = (void*)engine->CreateScriptObject(typeId);
  375. }
  376. }
  377. // internal
  378. void CScriptArray::Destruct(SArrayBuffer *buf, asUINT start, asUINT end)
  379. {
  380. int typeId = objType->GetSubTypeId();
  381. if (typeId & asTYPEID_MASK_OBJECT)
  382. {
  383. asIScriptEngine* engine = objType->GetEngine();
  384. void** max = (void**)(buf->data + end * sizeof(void*));
  385. void** d = (void**)(buf->data + start * sizeof(void*));
  386. for(; d < max; d++ )
  387. {
  388. if( *d )
  389. engine->ReleaseScriptObject(*d, typeId);
  390. }
  391. }
  392. }
  393. // internal
  394. void CScriptArray::CopyBuffer(SArrayBuffer *dst, SArrayBuffer *src)
  395. {
  396. asIScriptEngine* engine = objType->GetEngine();
  397. if(isArrayOfHandles)
  398. {
  399. // Copy the references and increase the reference counters
  400. if (dst->numElements > 0 && src->numElements > 0)
  401. {
  402. int typeId = objType->GetSubTypeId();
  403. int count = dst->numElements > src->numElements ? src->numElements : dst->numElements;
  404. void** max = (void**)(dst->data + count * sizeof(void*));
  405. void** d = (void**)dst->data;
  406. void** s = (void**)src->data;
  407. for (; d < max; d++, s++)
  408. {
  409. *d = *s;
  410. if (*d)
  411. engine->AddRefScriptObject(*d, typeId);
  412. }
  413. }
  414. }
  415. else
  416. {
  417. int typeId = objType->GetSubTypeId();
  418. if (dst->numElements > 0 && src->numElements > 0)
  419. {
  420. int count = dst->numElements > src->numElements ? src->numElements : dst->numElements;
  421. if (typeId & asTYPEID_MASK_OBJECT)
  422. {
  423. // Call the assignment operator on all of the objects
  424. void** max = (void**)(dst->data + count * sizeof(void*));
  425. void** d = (void**)dst->data;
  426. void** s = (void**)src->data;
  427. for(; d < max; d++, s++)
  428. engine->CopyScriptObject(*d, *s, typeId);
  429. }
  430. else
  431. {
  432. // Primitives are copied byte for byte
  433. memcpy(dst->data, src->data, count*elementSize);
  434. }
  435. }
  436. }
  437. }
  438. void CScriptArray::AddRef() const
  439. {
  440. // Clear the GC flag then increase the counter
  441. gcFlag = false;
  442. refCount++;
  443. }
  444. void CScriptArray::Release() const
  445. {
  446. // Now do the actual releasing (clearing the flag set by GC)
  447. gcFlag = false;
  448. if (--refCount == 0)
  449. delete this;
  450. }
  451. // Registers the template array type
  452. void registerArray(asIScriptEngine* engine)
  453. {
  454. engine->RegisterObjectType("array<class T>", 0, asOBJ_REF | asOBJ_TEMPLATE);
  455. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_TEMPLATE_CALLBACK, "bool f(int&in)", asFUNCTION(ScriptArrayTemplateCallback), asCALL_CDECL);
  456. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_FACTORY, "array<T>@ f(int& in)", asFUNCTIONPR(ScriptArrayFactory, (asIObjectType*), CScriptArray*), asCALL_CDECL);
  457. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_FACTORY, "array<T>@ f(int& in, uint)", asFUNCTIONPR(ScriptArrayFactory2, (asIObjectType*, asUINT), CScriptArray*), asCALL_CDECL);
  458. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_FACTORY, "array<T>@ f(int& in, uint, const T& in)", asFUNCTIONPR(ScriptArrayFactoryDefVal, (asIObjectType*, asUINT, void *), CScriptArray*), asCALL_CDECL);
  459. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_LIST_FACTORY, "array<T>@ f(int& in, uint)", asFUNCTIONPR(ScriptArrayFactory2, (asIObjectType*, asUINT), CScriptArray*), asCALL_CDECL);
  460. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_ADDREF, "void f()", asMETHOD(CScriptArray,AddRef), asCALL_THISCALL);
  461. engine->RegisterObjectBehaviour("array<T>", asBEHAVE_RELEASE, "void f()", asMETHOD(CScriptArray,Release), asCALL_THISCALL);
  462. engine->RegisterObjectMethod("array<T>", "T& opIndex(uint)", asMETHOD(CScriptArray, At), asCALL_THISCALL);
  463. engine->RegisterObjectMethod("array<T>", "const T& opIndex(uint) const", asMETHOD(CScriptArray, At), asCALL_THISCALL);
  464. engine->RegisterObjectMethod("array<T>", "array<T> &opAssign(const array<T>& in)", asMETHOD(CScriptArray, operator=), asCALL_THISCALL);
  465. engine->RegisterObjectMethod("array<T>", "void insert(uint, const T& in)", asMETHOD(CScriptArray, InsertAt), asCALL_THISCALL);
  466. engine->RegisterObjectMethod("array<T>", "void remove(uint)", asMETHOD(CScriptArray, RemoveAt), asCALL_THISCALL);
  467. engine->RegisterObjectMethod("array<T>", "void push(const T& in)", asMETHOD(CScriptArray, InsertLast), asCALL_THISCALL);
  468. engine->RegisterObjectMethod("array<T>", "void pop()", asMETHOD(CScriptArray, RemoveLast), asCALL_THISCALL);
  469. engine->RegisterObjectMethod("array<T>", "uint size() const", asMETHOD(CScriptArray, GetSize), asCALL_THISCALL);
  470. engine->RegisterObjectMethod("array<T>", "void resize(uint)", asMETHODPR(CScriptArray, Resize, (asUINT), void), asCALL_THISCALL);
  471. engine->RegisterDefaultArrayType("array<T>");
  472. }