void SDLWindow::setGammaRamp(const Array<uint16>& gammaRamp) { alwaysAssertM(gammaRamp.size() >= 256, "Gamma ramp must have at least 256 entries"); Log* debugLog = Log::common(); uint16* ptr = const_cast<uint16*>(gammaRamp.getCArray()); #ifdef WIN32 // On windows, use the more reliable SetDeviceGammaRamp function. // It requires separate RGB gamma ramps. uint16 wptr[3 * 256]; for (int i = 0; i < 256; ++i) { wptr[i] = wptr[i + 256] = wptr[i + 512] = ptr[i]; } BOOL success = SetDeviceGammaRamp(wglGetCurrentDC(), wptr); #else bool success = (SDL_SetGammaRamp(ptr, ptr, ptr) != -1); #endif if (! success) { if (debugLog) {debugLog->println("Error setting gamma ramp!");} #ifdef WIN32 debugAssertM(false, "Failed to set gamma ramp"); #else if (debugLog) {debugLog->println(SDL_GetError());} debugAssertM(false, SDL_GetError()); #endif } }
ColorRGB ColorRGB::fromHSV(Vector3 const & hsv) { debugAssertM((hsv[0] <= 1.0f && hsv[0] >= 0.0f) && (hsv[1] <= 1.0f && hsv[1] >= 0.0f) && (hsv[2] <= 1.0f && hsv[2] >= 0.0f), "ColorRGB: H, S, V must be in [0, 1]"); int const i = std::min(5, (int)std::floor(6.0 * hsv[0])); Real const f = 6.0f * hsv[0] - i; Real const m = hsv[2] * (1.0f - (hsv[1])); Real const n = hsv[2] * (1.0f - (hsv[1] * f)); Real const k = hsv[2] * (1.0f - (hsv[1] * (1 - f))); switch (i) { case 0: return ColorRGB(hsv[2], k, m); case 1: return ColorRGB(n, hsv[2], m); case 2: return ColorRGB(m, hsv[2], k); case 3: return ColorRGB(m, n, hsv[2]); case 4: return ColorRGB(k, m, hsv[2]); case 5: return ColorRGB(hsv[2], m, n); default: debugAssertM(false, "ColorRGB: Fell through switch when attempting conversion from HSV"); } return ColorRGB::black(); }
Any::Data::~Data() { debugAssertM(referenceCount.value() <= 0, "Deleted while still referenced."); // Destruct but do not deallocate children switch (type) { case STRING: debugAssert(value.s != NULL); value.s->~basic_string(); break; case ARRAY: debugAssert(value.a != NULL); value.a->~Array(); break; case TABLE: debugAssert(value.t != NULL); value.t->~Table(); break; default: // All other types should have a NULL value pointer (i.e., they were used just for name and comment fields) debugAssertM(value.s == NULL, "Corrupt Any::Data::Value"); } value.s = NULL; }
bool BinaryOutputStream::_commit(bool flush, bool force) { // If there is already an error, the commit fails if (!m_ok) return false; // Nothing to commit for memory streams if (m_path == "<memory>") return true; // Is there anything new to write? if (!force && m_bufferLen <= 0) return true; debugAssertM(m_beginEndBits == 0, getNameStr() + ": Missing endBits before commit"); // // Make sure the directory exists // std::string dir = FilePath::parent(m_path); // if (!FileSystem::exists(dir)) // if (!FileSystem::createDirectory(dir)) // { // DGP_ERROR << "BinaryOutputStream: Could not create parent directory of '" << m_path << "'"; // m_ok = false; // } FILE * file = NULL; if (m_ok) { char const * mode = (m_alreadyWritten > 0 ? "ab" : "wb"); file = fopen(m_path.c_str(), mode); if (!file) { DGP_ERROR << "BinaryOutputStream: Could not open file '" << m_path << "' for writing"; m_ok = false; } } if (m_ok) { if (m_buffer != NULL && m_bufferLen > 0) { size_t success = fwrite(m_buffer, (size_t)m_bufferLen, 1, file); debugAssertM(success == 1, getNameStr() + ": Could not write buffer contents to disk"); (void)success; m_alreadyWritten += m_bufferLen; m_bufferLen = 0; m_pos = 0; } if (flush) fflush(file); fclose(file); file = NULL; } return m_ok; }
Radiance3 RayTracer::L_direct(const shared_ptr<Surfel>& surfel, const Vector3& wo, ThreadData& threadData) const { Radiance3 L; const Point3& X(surfel->position); const Vector3& n(surfel->shadingNormal); for (int i = 0; i < m_lighting.lightArray.size(); ++i) { const shared_ptr<Light> light(m_lighting.lightArray[i]); if (light->producesDirectIllumination()) { const Point3& Y(light->frame().translation); const Vector3& wi((Y - X).direction()); debugAssertM(X.isFinite(), "The surface is not at a finite location"); debugAssertM(Y.isFinite(), "The light is not at a finite location"); if ((! light->castsShadows()) || visible(Y, X, true)) { const Color3& f(surfel->finiteScatteringDensity(wi, wo)); const Biradiance3& B(light->biradiance(X)); L += f * B * abs(wi.dot(n)); debugAssertM(L.isFinite(), "Non-finite radiance in L_direct"); } } } return L; }
// The following are called by the VARSystem. void VAR::vertexPointer() const { debugAssert(valid()); glEnableClientState(GL_VERTEX_ARRAY); debugAssertM(underlyingRepresentation != GL_UNSIGNED_INT, "OpenGL does not support GL_UNSIGNED_INT as a vertex format."); debugAssertM(underlyingRepresentation != GL_UNSIGNED_SHORT, "OpenGL does not support GL_UNSIGNED_SHORT as a vertex format."); debugAssertM(underlyingRepresentation != GL_UNSIGNED_BYTE, "OpenGL does not support GL_UNSIGNED_BYTE as a vertex format."); glVertexPointer(elementSize / sizeOfGLFormat(underlyingRepresentation), underlyingRepresentation, elementSize, _pointer); }
void VAR::normalPointer() const { debugAssert(valid()); debugAssert((double)elementSize / sizeOfGLFormat(underlyingRepresentation) == 3.0); debugAssertM(underlyingRepresentation != GL_UNSIGNED_INT, "OpenGL does not support GL_UNSIGNED_INT as a normal format."); debugAssertM(underlyingRepresentation != GL_UNSIGNED_SHORT, "OpenGL does not support GL_UNSIGNED_SHORT as a normal format."); debugAssertM(underlyingRepresentation != GL_UNSIGNED_BYTE, "OpenGL does not support GL_UNSIGNED_BYTE as a normal format."); glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(underlyingRepresentation, elementSize, _pointer); }
void VAR::set(int index, const void* value, GLenum glformat, size_t eltSize) { (void)glformat; debugAssertM(index < numElements && index >= 0, "Cannot call VAR::set with out of bounds index"); debugAssertM(glformat == underlyingRepresentation, "Value argument to VAR::set must match the intialization type."); debugAssertM(eltSize == elementSize, "Value argument to VAR::set must match the intialization type's memory footprint."); uploadToCard(value, index * eltSize, eltSize); }
void ReliableConduit::receiveIntoBuffer() { debugAssert(state == RECEIVING); debugAssert(messageType != 0); debugAssertM(receiveBufferUsedSize < messageSize, "Message already received."); debugAssertM(messageSize >= receiveBufferUsedSize, "Message size overflow."); // Read the data itself int ret = 0; uint32 left = messageSize - receiveBufferUsedSize; int count = 0; while ((ret != SOCKET_ERROR) && (left > 0) && (count < 10)) { ret = recv(sock, ((char*)receiveBuffer) + receiveBufferUsedSize, left, 0); if (ret > 0) { left -= ret; receiveBufferUsedSize += ret; bReceived += ret; if (left > 0) { // There's still more. Give the machine a chance to read // more data, but don't wait forever. ++count; System::sleep(0.001); } } else { // Something went wrong break; } } if ((ret == 0) || (ret == SOCKET_ERROR)) { if (nd->debugLog) { if (ret == SOCKET_ERROR) { nd->debugLog->printf("Call to recv failed. ret = %d," " sizeof(messageSize) = %d\n", ret, messageSize); nd->debugLog->println(socketErrorCode()); } else { nd->debugLog->printf("recv returned 0\n"); } } nd->closesocket(sock); return; } ++mReceived; }
bool RegistryUtil::writeString(const std::string& key, const std::string& value, const std::string& 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) { alwaysAssertM(data.size() < 0xFFFFFFFE, "String too long"); result = RegSetValueExA(openKey, value.c_str(), 0, REG_SZ, reinterpret_cast<const BYTE*>(data.c_str()), (int)(data.size() + 1)); debugAssertM(result == ERROR_SUCCESS, "Could not write registry key value."); RegCloseKey(openKey); } return (result == ERROR_SUCCESS); }
void Image3unorm8::load(const String& filename) { shared_ptr<Image> image = Image::fromFile(filename); if (image->format() != ImageFormat::RGB8()) { image->convertToRGB8(); } switch (image->format()->code) { case ImageFormat::CODE_L8: copyArray(static_cast<const Color1unorm8*>(image->toPixelTransferBuffer()->buffer()), image->width(), image->height()); break; case ImageFormat::CODE_L32F: copyArray(static_cast<const Color1*>(image->toPixelTransferBuffer()->buffer()), image->width(), image->height()); break; case ImageFormat::CODE_RGB8: copyArray(static_cast<const Color3unorm8*>(image->toPixelTransferBuffer()->buffer()), image->width(), image->height()); break; case ImageFormat::CODE_RGB32F: copyArray(static_cast<const Color3*>(image->toPixelTransferBuffer()->buffer()), image->width(), image->height()); break; case ImageFormat::CODE_RGBA8: copyArray(static_cast<const Color4unorm8*>(image->toPixelTransferBuffer()->buffer()), image->width(), image->height()); break; case ImageFormat::CODE_RGBA32F: copyArray(static_cast<const Color4*>(image->toPixelTransferBuffer()->buffer()), image->width(), image->height()); break; default: debugAssertM(false, "Trying to load unsupported image format"); break; } setChanged(true); }
Radiance3 RayTracer::L_scatteredSpecularIndirect(const shared_ptr<Surfel>& surfel, const Vector3& wo, int bouncesLeft, Random& rnd) const{ Radiance3 L(0,0,0); if (bouncesLeft > 0){ G3D::UniversalSurfel::ImpulseArray impulses; //Downcast to universalSurfel to allow getting impulses const shared_ptr<UniversalSurfel>& u = dynamic_pointer_cast<UniversalSurfel>(surfel); debugAssertM(notNull(u), "Encountered a Surfel that was not a UniversalSurfel"); //Find the impulses on the surface u->getImpulses(PathDirection::EYE_TO_SOURCE, wo, impulses); //For each impulses, recursively computed the radiance from that direction for (int i = 0; i < impulses.size(); ++i){ Vector3 wi = impulses[i].direction; Color3 magnitude = impulses[i].magnitude; ++m_stats->indirectRays; L += L_i(surfel->position, wi, bouncesLeft - 1, rnd) * magnitude; } //If we enable path tracing, also cast a random ray from the surfel //Technically it is not SpecularIndirect. But as it is not used often, I'm going to leave it here if (m_settings.enablePathTracing){ Vector3 wi = Vector3::hemiRandom(surfel->shadingNormal, rnd); L += L_i(surfel->position, wi, bouncesLeft - 1, rnd) * surfel->finiteScatteringDensity(wi,wo) * abs(wi.dot(surfel->shadingNormal)); } } return L; }
ParticleSystemModel::Emitter::Emitter(const Specification& s) : m_specification(s) { switch (s.shapeType) { case Shape::Type::MESH: // Load the mesh debugAssertM(false, "TODO"); break; case Shape::Type::BOX: m_spawnShape = shared_ptr<Shape>(new BoxShape(s.box)); break; case Shape::Type::CYLINDER: m_spawnShape = shared_ptr<Shape>(new CylinderShape(s.cylinder)); break; case Shape::Type::SPHERE: m_spawnShape = shared_ptr<Shape>(new SphereShape(s.sphere)); break; default: alwaysAssertM(false, "Illegal spawn shape"); } m_material = ParticleMaterial::create(s.material); }
ReferenceCountedObject::ReferenceCountedObject() : ReferenceCountedObject_refCount(0), ReferenceCountedObject_weakPointer(0) { debugAssertM(isValidHeapPointer(this), "Reference counted objects must be allocated on the heap."); }
void VAR::update( const void* sourcePtr, int _numElements, GLenum glformat, size_t eltSize) { size_t size = eltSize * _numElements; alwaysAssertM(size <= _maxSize, "A VAR can only be updated with an array that is smaller " "or equal size (in bytes) to the original array."); alwaysAssertM(generation == area->currentGeneration(), "The VARArea has been reset since this VAR was created."); numElements = _numElements; underlyingRepresentation = glformat; elementSize = eltSize; debugAssertM( (elementSize % sizeOfGLFormat(underlyingRepresentation)) == 0, "Sanity check failed on OpenGL data format; you may" " be using an unsupported type in a vertex array."); // Upload the data if (size > 0) { uploadToCard(sourcePtr, 0, size); } }
shared_ptr<TileSheet> TileSheet::create(const Any& any) { shared_ptr<TileSheet> tileSheet(new TileSheet()); AnyTableReader r(any); Any legend; r.getIfPresent("legend", legend); for (Table<String, Any>::Iterator it = legend.table().begin(); it.hasMore(); ++it) { const String& mapLabel = it.key(); const shared_ptr<Tile>& tile = Tile::create(mapLabel, it.value()); // TODO: Switch to report debugAssertM(! tileSheet->m_tileByID.containsKey(tile->id()), "Duplicate tile ID"); tileSheet->m_tileByID.set(tile->id(), tile); tileSheet->m_tileByMapLabel.set(tile->mapLabel(), tile); } r.getFilenameIfPresent("color", tileSheet->m_colorFilename); r.getFilenameIfPresent("blueprint", tileSheet->m_blueprintFilename); // Even though we lazy load these (since the server can't load graphics), // we check immediately to ensure that the files exist if (! FileSystem::exists(tileSheet->m_colorFilename)) { report("File not found: \"" + tileSheet->m_colorFilename + "\".", ReportLevel::ERROR); } if (! FileSystem::exists(tileSheet->m_blueprintFilename)) { report("File not found: \"" + tileSheet->m_blueprintFilename + "\".", ReportLevel::ERROR); } r.verifyDone(); return tileSheet; }
Matrix4float64 Matrix4float64::perspectiveProjection( double left, double right, double bottom, double top, double nearval, double farval, float upDirection) { double x, y, a, b, c, d; x = (2.0*nearval) / (right-left); y = (2.0*nearval) / (top-bottom); a = (right+left) / (right-left); b = (top+bottom) / (top-bottom); if (farval >= inf()) { // Infinite view frustum c = -1.0; d = -2.0 * nearval; } else { c = -(farval+nearval) / (farval-nearval); d = -(2.0*farval*nearval) / (farval-nearval); } debugAssertM(abs(upDirection) == 1.0, "upDirection must be -1 or +1"); y *= upDirection; b *= upDirection; return Matrix4float64( (float)x, 0, (float)a, 0, 0, (float)y, (float)b, 0, 0, 0, (float)c, (float)d, 0, 0, -1, 0); }
bool RegistryUtil::writeBytes(const std::string& key, const std::string& value, const uint8* data, uint32 dataSize) { debugAssert(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) { if (data) { result = RegSetValueExA(openKey, value.c_str(), 0, REG_BINARY, reinterpret_cast<const BYTE*>(data), dataSize); } debugAssertM(result == ERROR_SUCCESS, "Could not write registry key value."); RegCloseKey(openKey); } return (result == ERROR_SUCCESS); }
/** True if the next token begins the close tag */ static bool atClose(TextInput& t, const std::string name) { if ((t.peek().type() == Token::SYMBOL) && (t.peek().string() == "<")) { // Need to keep looking ahead Token p0 = t.read(); if ((t.peek().type() == Token::SYMBOL) && (t.peek().string() == "/")) { // Check the name on the close tag. It *must* match if // this is a well-formed document, but there might be a // tag error. Token p1 = t.read(); Token p2 = t.peek(); std::string s = p2.string(); debugAssertM(beginsWith(name, s), "Mismatched close tag"); // Put the tokens back t.push(p1); t.push(p0); return true; } else { // Put the read token back t.push(p0); return false; } } else { return false; } }
bool RegistryUtil::writeInt32(const String& key, const String& value, int32 data) { size_t pos = key.find('\\', 0); if (pos == 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 Entity::init (const std::string& name, Scene* scene, const CFrame& frame, const shared_ptr<Track>& track, bool canChange, bool shouldBeSaved) { m_name = name; m_canChange = canChange; m_shouldBeSaved = shouldBeSaved; m_track = track; m_scene = scene; if (notNull(track)) { m_previousFrame = m_frame = m_track->computeFrame(0); } else { m_frame = m_previousFrame = frame; } m_lastChangeTime = System::time(); if (! m_canChange && notNull(m_track)) { debugAssertM(false, "Track specified for an Entity that cannot change."); } }
void RayTracer::emitPhoton(Random& rnd, Photon& photon) { const Array< shared_ptr<Light> >& lightArray = m_lighting.lightArray; debugAssertM(lightArray.size() > 0, "Scene must have lights"); debugAssert(m_totalIndirectProducingLightPower.nonZero()); int i = 0; for (AveragePower p = rnd.uniform(0, m_totalIndirectProducingLightPower.average()) - indirectPower(lightArray[0]); (i < lightArray.size() - 1) && (p > 0.0f); p -= indirectPower(lightArray[i])) { ++i; } const shared_ptr<Light>& light = lightArray[i]; // Choose light i photon.power = (m_totalIndirectProducingLightPower.average() / m_settings.photon.numEmitted) * (light->emittedPower() / light->emittedPower().average()); photon.position = light->frame().translation; photon.wi = -light->randomEmissionDirection(rnd); photon.effectRadius = 0.0f; }
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); }
void Scene::clearOrder(const std::string& entity1Name, const std::string& entity2Name) { debugAssert(entity1Name != entity2Name); bool created = false; DependencyList& list = m_dependencyTable.getCreate(entity2Name, created); debugAssertM(! created, "Tried to remove a dependency that did not exist"); int i = list.findIndex(entity1Name); debugAssertM(i != -1, "Tried to remove a dependency that did not exist"); list.fastRemove(i); if (list.size() == 0) { // The list is empty, don't store it any more m_dependencyTable.remove(entity2Name); } m_needEntitySort = true; }
Polygon3::IndexedVertex const & Polygon3::getVertex(long poly_index) const { debugAssertM(poly_index >= 0 && poly_index < numVertices(), "Polygon3: Vertex index out of bounds"); return vertices[(size_t)poly_index]; }
void BinaryOutputStream::writeUInt32(uint32 u) { reserveBytes(4); uint8 * convert = (uint8 *)&u; debugAssertM(m_beginEndBits == 0, getNameStr() + ": Can't write non-bit data within beginBits/endBits block"); if (m_swapBytes) { m_buffer[m_pos + 0] = convert[3]; m_buffer[m_pos + 1] = convert[2]; m_buffer[m_pos + 2] = convert[1]; m_buffer[m_pos + 3] = convert[0]; } else { #ifdef DGP_ALLOW_UNALIGNED_WRITES *(uint32 *)(m_buffer + m_pos) = u; #else m_buffer[m_pos + 0] = convert[0]; m_buffer[m_pos + 1] = convert[1]; m_buffer[m_pos + 2] = convert[2]; m_buffer[m_pos + 3] = convert[3]; #endif } m_pos += 4; }
void BinaryOutput::commit( uint8* out) { debugAssertM(! m_committed, "Cannot commit twice"); m_committed = true; System::memcpy(out, m_buffer, m_bufferLen); }
void BinaryInput::decompress() { // Decompress // Use the existing buffer as the source, allocate // a new buffer to use as the destination. int64 tempLength = m_length; m_length = G3D::readUInt32(m_buffer, m_swapBytes); // The file couldn't have better than 500:1 compression alwaysAssertM(m_length < m_bufferLength * 500, "Compressed file header is corrupted"); uint8* tempBuffer = m_buffer; m_buffer = (uint8*)System::alignedMalloc(m_length, 16); debugAssert(m_buffer); debugAssert(isValidHeapPointer(tempBuffer)); debugAssert(isValidHeapPointer(m_buffer)); unsigned long L = m_length; int64 result = uncompress(m_buffer, &L, tempBuffer + 4, tempLength - 4); m_length = L; m_bufferLength = m_length; debugAssertM(result == Z_OK, "BinaryInput/zlib detected corruption in " + m_filename); (void)result; System::alignedFree(tempBuffer); }
ReferenceCountedObject::ReferenceCountedObject(const ReferenceCountedObject& notUsed) : ReferenceCountedObject_refCount(0), ReferenceCountedObject_weakPointer(0) { (void)notUsed; debugAssertM(G3D::isValidHeapPointer(this), "Reference counted objects must be allocated on the heap."); }
Matrix4 Matrix4::perspectiveProjection( float left, float right, float bottom, float top, float nearval, float farval, float upDirection) { float x, y, a, b, c, d; x = (2.0f*nearval) / (right-left); y = (2.0f*nearval) / (top-bottom); a = (right+left) / (right-left); b = (top+bottom) / (top-bottom); if (farval >= finf()) { // Infinite view frustum c = -1.0f; d = -2.0f * nearval; } else { c = -(farval+nearval) / (farval-nearval); d = -(2.0f*farval*nearval) / (farval-nearval); } debugAssertM(abs(upDirection) == 1.0f, "upDirection must be -1 or +1"); y *= upDirection; b *= upDirection; return Matrix4( x, 0, a, 0, 0, y, b, 0, 0, 0, c, d, 0, 0, -1, 0); }