void Box::getFaceCorners(int f, Vector3& v0, Vector3& v1, Vector3& v2, Vector3& v3) const { switch (f) { case 0: v0 = _corner[0]; v1 = _corner[1]; v2 = _corner[2]; v3 = _corner[3]; break; case 1: v0 = _corner[1]; v1 = _corner[5]; v2 = _corner[6]; v3 = _corner[2]; break; case 2: v0 = _corner[7]; v1 = _corner[6]; v2 = _corner[5]; v3 = _corner[4]; break; case 3: v0 = _corner[2]; v1 = _corner[6]; v2 = _corner[7]; v3 = _corner[3]; break; case 4: v0 = _corner[3]; v1 = _corner[7]; v2 = _corner[4]; v3 = _corner[0]; break; case 5: v0 = _corner[1]; v1 = _corner[0]; v2 = _corner[4]; v3 = _corner[5]; break; default: debugAssert((f >= 0) && (f < 6)); } }
void testMatrix3() { printf("G3D::Matrix3 "); testEuler(); { Matrix3 M = Matrix3::identity(); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { M[i][j] = uniformRandom(0, 1); } } Vector3 v = Vector3::random(); Vector3 x1 = v * M; Vector3 x2 = M.transpose() * v; debugAssert(x1 == x2); } printf("passed\n"); }
NetAddress::NetAddress(const std::string& hostnameAndPort) { Array<std::string> part = stringSplit(hostnameAndPort, ':'); debugAssert(part.length() == 2); init(part[0], atoi(part[1].c_str())); }
static void testEuler() { float x = 1; float y = 2; float z = -3; float x2, y2, z2; Matrix3 rX = Matrix3::fromAxisAngle(Vector3::unitX(), x); Matrix3 rY = Matrix3::fromAxisAngle(Vector3::unitY(), y); Matrix3 rZ = Matrix3::fromAxisAngle(Vector3::unitZ(), z); Matrix3 rot = rZ * rX * rY; rot.toEulerAnglesZXY(x2, y2, z2); debugAssert(fuzzyEq(x, x2)); debugAssert(fuzzyEq(y, y2)); debugAssert(fuzzyEq(z, z2)); }
BinaryOutput::~BinaryOutput() { debugAssert((m_buffer == NULL) || isValidHeapPointer(m_buffer)); System::free(m_buffer); m_buffer = NULL; m_bufferLen = 0; m_maxBufferLen = 0; }
void BinaryInput::readBytes(void* bytes, int64 n) { prepareToRead(n); debugAssert(isValidPointer(bytes)); memcpy(bytes, m_buffer + m_pos, n); m_pos += n; }
Any& Any::operator[](int i) { beforeRead(); verifyType(ARRAY); debugAssert(m_data != NULL); Array<Any>& array = *(m_data->value.a); return array[i]; }
uint32 BinaryInput::readBits(int numBits) { debugAssert(m_beginEndBits == 1); uint32 out = 0; const int total = numBits; while (numBits > 0) { if (m_bitPos > 7) { // Consume a new byte for reading. We do this at the beginning // of the loop so that we don't try to read past the end of the file. m_bitPos = 0; m_bitString = readUInt8(); } // Slide the lowest bit of the bitString into // the correct position. out |= (m_bitString & 1) << (total - numBits); // Shift over to the next bit m_bitString = m_bitString >> 1; ++m_bitPos; --numBits; } return out; }
Any Entity::toAny() const { Any a = m_sourceAny; debugAssert(! a.isNil()); if (a.isNil()) { // Fallback for release mode failure return a; } if (m_movedSinceLoad) { a["frame"] = m_frame; } const shared_ptr<SplineTrack>& splineTrack = dynamic_pointer_cast<SplineTrack>(m_track); if (notNull(splineTrack) && splineTrack->changed()) { // Update the spline const PhysicsFrameSpline& spline = splineTrack->spline(); if (spline.control.size() == 1) { // Write out in short form for the single control point const PhysicsFrame& p = spline.control[0]; if (p.rotation == Quat()) { // No rotation a["track"] = p.translation; } else { // Full coordinate frame a["track"] = CFrame(p); } } else { // Write the full spline a["track"] = spline; } } a.setName("Entity"); return a; }
bool RegistryUtil::writeInt32(const std::string& key, const std::string& value, int32 data) { size_t pos = key.find('\\', 0); if (pos == std::string::npos) { return false; } HKEY hkey = getRootKeyFromString(key.c_str(), pos); if (hkey == NULL) { return false; } HKEY openKey; int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_WRITE, &openKey); debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); if (result == ERROR_SUCCESS) { result = RegSetValueExA(openKey, value.c_str(), 0, REG_DWORD, reinterpret_cast<const BYTE*>(&data), sizeof(int32)); debugAssertM(result == ERROR_SUCCESS, "Could not write registry key value."); RegCloseKey(openKey); } return (result == ERROR_SUCCESS); }
void BinaryOutput::reallocBuffer(size_t bytes, size_t oldBufferLen) { //debugPrintf("reallocBuffer(%d, %d)\n", bytes, oldBufferLen); size_t newBufferLen = (int)(m_bufferLen * 1.5) + 100; uint8* newBuffer = NULL; if ((m_filename == "<memory>") || (newBufferLen < MAX_BINARYOUTPUT_BUFFER_SIZE)) { // We're either writing to memory (in which case we *have* to try and allocate) // or we've been asked to allocate a reasonable size buffer. //debugPrintf(" realloc(%d)\n", newBufferLen); newBuffer = (uint8*)System::realloc(m_buffer, newBufferLen); if (newBuffer != NULL) { m_maxBufferLen = newBufferLen; } } if ((newBuffer == NULL) && (bytes > 0)) { // Realloc failed; we're probably out of memory. Back out // the entire call and try to dump some data to disk. m_bufferLen = oldBufferLen; reserveBytesWhenOutOfMemory(bytes); } else { m_buffer = newBuffer; debugAssert(isValidHeapPointer(m_buffer)); } }
bool RegistryUtil::readInt32(const std::string& key, const std::string& value, int32& data) { size_t pos = key.find('\\', 0); if (pos == std::string::npos) { return false; } HKEY hkey = getRootKeyFromString(key.c_str(), pos); if ( hkey == NULL ) { return false; } HKEY openKey; int32 result = RegOpenKeyExA(hkey, (key.c_str() + pos + 1), 0, KEY_READ, &openKey); debugAssert(result == ERROR_SUCCESS || result == ERROR_FILE_NOT_FOUND); if (result == ERROR_SUCCESS) { uint32 dataSize = sizeof(int32); result = RegQueryValueExA(openKey, value.c_str(), NULL, NULL, reinterpret_cast<LPBYTE>(&data), reinterpret_cast<LPDWORD>(&dataSize)); debugAssertM(result == ERROR_SUCCESS, "Could not read registry key value."); RegCloseKey(openKey); } return (result == ERROR_SUCCESS); }
// static helpers static HKEY getRootKeyFromString(const char* str, size_t length) { debugAssert(str); if (str) { if ( strncmp(str, "HKEY_CLASSES_ROOT", length) == 0 ) { return HKEY_CLASSES_ROOT; } else if ( strncmp(str, "HKEY_CURRENT_CONFIG", length) == 0 ) { return HKEY_CURRENT_CONFIG; } else if ( strncmp(str, "HKEY_CURRENT_USER", length) == 0 ) { return HKEY_CURRENT_USER; } else if ( strncmp(str, "HKEY_LOCAL_MACHINE", length) == 0 ) { return HKEY_LOCAL_MACHINE; } else if ( strncmp(str, "HKEY_PERFORMANCE_DATA", length) == 0 ) { return HKEY_PERFORMANCE_DATA; } else if ( strncmp(str, "HKEY_PERFORMANCE_NLSTEXT", length) == 0 ) { return HKEY_PERFORMANCE_NLSTEXT; } else if ( strncmp(str, "HKEY_PERFORMANCE_TEXT", length) == 0 ) { return HKEY_PERFORMANCE_TEXT; } else if ( strncmp(str, "HKEY_CLASSES_ROOT", length) == 0 ) { return HKEY_CLASSES_ROOT; } else { return NULL; } } else { return NULL; } }
BinaryInput::BinaryInput( const uint8* data, int64 dataLen, G3DEndian dataEndian, bool compressed, bool copyMemory) { beginEndBits = 0; bitPos = 0; alreadyRead = 0; bufferLength = 0; freeBuffer = copyMemory || compressed; this->fileEndian = dataEndian; this->filename = "<memory>"; pos = 0; swapBytes = needSwapBytes(fileEndian); if (compressed) { // Read the decompressed size from the first 4 bytes length = G3D::readUInt32(data, swapBytes); debugAssert(freeBuffer); buffer = (uint8*)System::malloc(length); unsigned long L = length; // Decompress with zlib int64 result = uncompress(buffer, (unsigned long*)&L, data + 4, dataLen - 4); length = L; bufferLength = L; debugAssert(result == Z_OK); (void)result; } else { length = dataLen; bufferLength = length; if (! copyMemory) { debugAssert(!freeBuffer); buffer = const_cast<uint8*>(data); } else { debugAssert(freeBuffer); buffer = (uint8*)System::malloc(length); System::memcpy(buffer, data, dataLen); } } }
void BinaryOutput::reserveBytesWhenOutOfMemory(size_t bytes) { if (m_filename == "<memory>") { throw "Out of memory while writing to memory in BinaryOutput (no RAM left)."; } else if ((int)bytes > (int)m_maxBufferLen) { throw "Out of memory while writing to disk in BinaryOutput (could not create a large enough buffer)."; } else { // Dump the contents to disk. In order to enable seeking backwards, // we keep the last 10 MB in memory. int writeBytes = m_bufferLen - 10 * 1024 * 1024; if (writeBytes < m_bufferLen / 3) { // We're going to write less than 1/3 of the file; // give up and just write the whole thing. writeBytes = m_bufferLen; } debugAssert(writeBytes > 0); //debugPrintf("Writing %d bytes to disk\n", writeBytes); const char* mode = (m_alreadyWritten > 0) ? "ab" : "wb"; FILE* file = FileSystem::fopen(m_filename.c_str(), mode); debugAssert(file); size_t count = fwrite(m_buffer, 1, writeBytes, file); debugAssert((int)count == writeBytes); (void)count; fclose(file); file = NULL; // Record that we saved this data. m_alreadyWritten += writeBytes; m_bufferLen -= writeBytes; m_pos -= writeBytes; debugAssert(m_bufferLen < m_maxBufferLen); debugAssert(m_bufferLen >= 0); debugAssert(m_pos >= 0); debugAssert(m_pos <= m_bufferLen); // Shift the unwritten data back appropriately in the buffer. debugAssert(isValidHeapPointer(m_buffer)); System::memcpy(m_buffer, m_buffer + writeBytes, m_bufferLen); debugAssert(isValidHeapPointer(m_buffer)); // *now* we allocate bytes (there should presumably be enough // space in the buffer; if not, we'll come back through this // code and dump the last 10MB to disk as well. Note that the // bytes > maxBufferLen case above would already have triggered // if this call couldn't succeed. reserveBytes(bytes); } }
void MeshAlg::debugCheckConsistency( const Array<Face>& faceArray, const Array<Edge>& edgeArray, const Array<Vertex>& vertexArray) { #ifdef _DEBUG for (int v = 0; v < vertexArray.size(); ++v) { const MeshAlg::Vertex& vertex = vertexArray[v]; for (int i = 0; i < vertex.edgeIndex.size(); ++i) { const int e = vertex.edgeIndex[i]; debugAssert(edgeArray[(e >= 0) ? e : ~e].containsVertex(v)); } for (int i = 0; i < vertex.faceIndex.size(); ++i) { const int f = vertex.faceIndex[i]; debugAssert(faceArray[f].containsVertex(v)); } } for (int e = 0; e < edgeArray.size(); ++e) { const MeshAlg::Edge& edge = edgeArray[e]; for (int i = 0; i < 2; ++i) { debugAssert((edge.faceIndex[i] == MeshAlg::Face::NONE) || faceArray[edge.faceIndex[i]].containsEdge(e)); debugAssert(vertexArray[edge.vertexIndex[i]].inEdge(e)); } } // Every face's edge must be on that face for (int f = 0; f < faceArray.size(); ++f) { const MeshAlg::Face& face = faceArray[f]; for (int i = 0; i < 3; ++i) { int e = face.edgeIndex[i]; int ei = (e >= 0) ? e : ~e; debugAssert(edgeArray[ei].inFace(f)); // Make sure the edge is oriented appropriately if (e >= 0) { debugAssert(edgeArray[ei].faceIndex[0] == (int)f); } else { debugAssert(edgeArray[ei].faceIndex[1] == (int)f); } debugAssert(vertexArray[face.vertexIndex[i]].inFace(f)); } } #else (void)faceArray; (void)edgeArray; (void)vertexArray; #endif // _DEBUG }
void GThread::waitForCompletion() { if (m_status == STATUS_COMPLETED) { // Must be done return; } # ifdef G3D_WIN32 debugAssert(m_event); ::WaitForSingleObject(m_event, INFINITE); # else debugAssert(m_handle); //printf("Before pthread_join\n"); // TODO: remove //printf("m_status = %d\n", m_status); pthread_join(m_handle, NULL); //printf("After pthread_join\n"); // TODO: remove # endif }
void VAR::vertexAttribPointer(uint attribNum, bool normalize) const { debugAssert(valid()); if (GLCaps::supports_GL_ARB_vertex_program()) { glEnableVertexAttribArrayARB(attribNum); glVertexAttribPointerARB(attribNum, elementSize / sizeOfGLFormat(underlyingRepresentation), underlyingRepresentation, normalize, elementSize, _pointer); } }
void tinyFree(void* ptr) { debugAssert(tinyPoolSize < maxTinyBuffers); // Put the pointer back into the free list tinyPool[tinyPoolSize] = ptr; ++tinyPoolSize; }
void Box::init( const Vector3& min, const Vector3& max) { debugAssert( (min.x <= max.x) && (min.y <= max.y) && (min.z <= max.z)); setMany(0, 1, 2, 3, z, max); setMany(4, 5, 6, 7, z, min); setMany(1, 2, 5, 6, x, max); setMany(0, 3, 4, 7, x, min); setMany(3, 2, 6, 7, y, max); setMany(0, 1, 5, 4, y, min); _extent = max - min; _axis[0] = Vector3::unitX(); _axis[1] = Vector3::unitY(); _axis[2] = Vector3::unitZ(); if (_extent.isFinite()) { _volume = _extent.x * _extent.y * _extent.z; } else { _volume = G3D::finf(); } debugAssert(! isNaN(_extent.x)); _area = 2 * (_extent.x * _extent.y + _extent.y * _extent.z + _extent.z * _extent.x); _center = (max + min) * 0.5f; // If the extent is infinite along an axis, make the center zero to avoid NaNs for (int i = 0; i < 3; ++i) { if (! G3D::isFinite(_extent[i])) { _center[i] = 0.0f; } } }
void Entity::setFrame(const CFrame& f) { if (m_frame != f) { m_lastChangeTime = System::time(); debugAssert(m_lastChangeTime > 0.0); m_frame = f; m_movedSinceLoad = true; } }
void Any::set(const std::string& k, const Any& v) { beforeRead(); v.beforeRead(); verifyType(TABLE); debugAssert(m_data != NULL); Table<std::string, Any>& table = *(m_data->value.t); table.set(k, v); }
void SDLWindow::notifyResize(int w, int h) { debugAssert(w > 0); debugAssert(h > 0); _settings.width = w; _settings.height = h; // Mutate the SDL surface (which one is not supposed to do). // We can't resize the actual surface or SDL will destroy // our GL context, however. SDL_Surface* surface = SDL_GetVideoSurface(); surface->w = w; surface->h = h; surface->clip_rect.x = 0; surface->clip_rect.y = 0; surface->clip_rect.w = w; surface->clip_rect.h = h; }
Vector2 LineSegment2D::point(int i) const { debugAssert(i == 0 || i == 1); if (i == 0) { return m_origin; } else { return m_direction + m_origin; } }
EventRef ICubeXDevice::reportChannel(int channel, double data) { debugAssert(channel < 32); debugAssert(channel >= 0); if (data != _channelData[channel]) { _channelData[channel] = data; std::string channelStr = intToString(channel+1); if (channel+1 < 10) channelStr = std::string("0") + channelStr; return new Event("ICubeX_" + channelStr, data); } return NULL; }
void BinaryInput::beginBits() { debugAssert(beginEndBits == 0); beginEndBits = 1; bitPos = 0; debugAssertM(hasMore(), "Can't call beginBits when at the end of a file"); bitString = readUInt8(); }
void NetworkDevice::_cleanup() { debugAssert(initialized); # ifdef G3D_WINDOWS // Now handled through enet // WSACleanup(); # endif }
bool NetworkDevice::init() { debugAssert(! initialized); logPrintf("Network Startup"); logPrintf("Starting WinSock networking.\n"); WSADATA wsda; WSAStartup(MAKEWORD(G3D_WINSOCK_MAJOR_VERSION, G3D_WINSOCK_MINOR_VERSION), &wsda); std::string hostname = "localhost"; { char ac[128]; if (gethostname(ac, sizeof(ac)) == -1) { logPrintf("Warning: Error while getting local host name\n"); } else { hostname = gethostbyname(ac)->h_name; } } EthernetAdapter a; a.hostname = hostname; a.name = ""; a.ip = NetAddress(hostname, 0).ip(); // TODO: Find subnet on Win32 a.subnet = 0x0000FFFF; // TODO: Find broadcast on Win32 a.broadcast = 0xFFFFFFFF; // TODO: find MAC on Win32 addAdapter(a); std::string machine = localHostName(); std::string addr = NetAddress(machine, 0).ipString(); logPrintf( "Network:\n" " Status: %s\n" " Loaded winsock specification version %d (%d is " "the highest available)\n" " %d sockets available\n" " Largest UDP datagram packet size is %d bytes\n\n", wsda.szDescription, wsda.szSystemStatus, wsda.wVersion, wsda.wHighVersion, wsda.iMaxSockets, wsda.iMaxUdpDg); // TODO: WSAIoctl for subnet and broadcast addresses // http://msdn.microsoft.com/en-us/library/ms741621(VS.85).aspx // // TODO: SIO_GET_INTERFACE_LIST initialized = true; return true; }
BinaryInput::BinaryInput( const uint8* data, int64 dataLen, G3DEndian dataEndian, bool compressed, bool copyMemory) : m_filename("<memory>"), m_bitPos(0), m_bitString(0), m_beginEndBits(0), m_alreadyRead(0), m_bufferLength(0), m_pos(0) { m_freeBuffer = copyMemory || compressed; setEndian(dataEndian); if (compressed) { // Read the decompressed size from the first 4 bytes m_length = G3D::readUInt32(data, m_swapBytes); debugAssert(m_freeBuffer); m_buffer = (uint8*)System::alignedMalloc(m_length, 16); unsigned long L = m_length; // Decompress with zlib int64 result = uncompress(m_buffer, (unsigned long*)&L, data + 4, dataLen - 4); m_length = L; m_bufferLength = L; debugAssert(result == Z_OK); (void)result; } else { m_length = dataLen; m_bufferLength = m_length; if (! copyMemory) { debugAssert(!m_freeBuffer); m_buffer = const_cast<uint8*>(data); } else { debugAssert(m_freeBuffer); m_buffer = (uint8*)System::alignedMalloc(m_length, 16); System::memcpy(m_buffer, data, dataLen); } } }
void BinaryOutput::writeString(const char* s) { // +1 is because strlen doesn't count the null int len = strlen(s) + 1; debugAssert(m_beginEndBits == 0); reserveBytes(len); System::memcpy(m_buffer + m_pos, s, len); m_pos += len; }