/** This operator returns a new image, created by adding another image element-wise to this image. */ Image operator+(const Image& image2) { Image result = Image(*this, _data + image2.data()); return result; }
Doom3TextureManager::ImageID Doom3TextureManager::computeHeightmap(const Doom3TextureManager::ImageID& source,float bumpiness) { /* Get a reference to the source image: */ const Images::RGBAImage& sourceImage=imageTree.getLeafValue(source).image; /* Store a new image structure in the image tree: */ ImageID resultId=imageTree.insertLeaf(Misc::stringPrintf("/_computedTextures/tex%06d",numTextures).c_str(),Image()); Image& result=imageTree.getLeafValue(resultId); Images::RGBAImage& resultImage=result.image; result.textureIndex=numTextures; ++numTextures; /* Compute the result image's pixels: */ resultImage=Images::RGBAImage(sourceImage.getWidth(),sourceImage.getHeight()); for(unsigned int y=0; y<resultImage.getHeight(); ++y) { const Images::RGBAImage::Color* sourceRow=sourceImage.getPixelRow(y); Images::RGBAImage::Color* destRow=resultImage.modifyPixelRow(y); for(unsigned int x=0; x<resultImage.getWidth(); ++x) { Geometry::Vector<float,3> g; if(x==0) g[0]=float(sourceRow[x+1][0])-float(sourceRow[x][0]); else if(x==resultImage.getWidth()-1) g[0]=float(sourceRow[x][0])-float(sourceRow[x-1][0]); else g[0]=float(sourceRow[x+1][0])-float(sourceRow[x-1][0]); if(y==0) g[1]=float((sourceRow+resultImage.getWidth())[x][0])-float(sourceRow[x][0]); else if(y==resultImage.getHeight()-1) g[1]=float(sourceRow[x][0])-float((sourceRow-resultImage.getWidth())[x][0]); else g[1]=float((sourceRow+resultImage.getWidth())[x][0])-float((sourceRow-resultImage.getWidth())[x][0]); g[2]=128.0f/bumpiness; destRow[x]=encodeNormal(g); } } /* Return the result image ID: */ return resultId; }
Doom3TextureManager::ImageID Doom3TextureManager::computeScale(const Doom3TextureManager::ImageID& source,const float factors[4]) { /* Get a reference to the source image: */ const Images::RGBAImage& sourceImage=imageTree.getLeafValue(source).image; /* Store a new image structure in the image tree: */ ImageID resultId=imageTree.insertLeaf(Misc::stringPrintf("/_computedTextures/tex%06d",numTextures).c_str(),Image()); Image& result=imageTree.getLeafValue(resultId); Images::RGBAImage& resultImage=result.image; result.textureIndex=numTextures; ++numTextures; /* Compute the result image's pixels: */ resultImage=Images::RGBAImage(sourceImage.getWidth(),sourceImage.getHeight()); for(unsigned int y=0; y<resultImage.getHeight(); ++y) { const Images::RGBAImage::Color* sourceRow=sourceImage.getPixelRow(y); Images::RGBAImage::Color* destRow=resultImage.modifyPixelRow(y); for(unsigned int x=0; x<resultImage.getWidth(); ++x) { for(int i=0; i<4; ++i) { float val=float(sourceRow[x][i])*factors[i]; if(val<0.5f) destRow[x][i]=GLubyte(0); else if(val>=254.5f) destRow[x][i]=GLubyte(255); else destRow[x][i]=GLubyte(Math::floor(val+0.5f)); } } } /* Return the result image ID: */ return resultId; }
void Variant::reference(const Variant& p_variant) { if (this == &p_variant) return; clear(); type=p_variant.type; switch( p_variant.type ) { case NIL: { // none } break; // atomic types case BOOL: { _data._bool=p_variant._data._bool; } break; case INT: { _data._int=p_variant._data._int; } break; case REAL: { _data._real=p_variant._data._real; } break; case STRING: { memnew_placement( _data._mem, String( *reinterpret_cast<const String*>(p_variant._data._mem) ) ); } break; // math types case VECTOR2: { memnew_placement( _data._mem, Vector2( *reinterpret_cast<const Vector2*>(p_variant._data._mem) ) ); } break; case RECT2: { memnew_placement( _data._mem, Rect2( *reinterpret_cast<const Rect2*>(p_variant._data._mem) ) ); } break; case MATRIX32: { _data._matrix32 = memnew( Matrix32( *p_variant._data._matrix32 ) ); } break; case VECTOR3: { memnew_placement( _data._mem, Vector3( *reinterpret_cast<const Vector3*>(p_variant._data._mem) ) ); } break; case PLANE: { memnew_placement( _data._mem, Plane( *reinterpret_cast<const Plane*>(p_variant._data._mem) ) ); } break; /* case QUAT: { } break;*/ case _AABB: { _data._aabb = memnew( AABB( *p_variant._data._aabb ) ); } break; case QUAT: { memnew_placement( _data._mem, Quat( *reinterpret_cast<const Quat*>(p_variant._data._mem) ) ); } break; case MATRIX3: { _data._matrix3 = memnew( Matrix3( *p_variant._data._matrix3 ) ); } break; case TRANSFORM: { _data._transform = memnew( Transform( *p_variant._data._transform ) ); } break; // misc types case COLOR: { memnew_placement( _data._mem, Color( *reinterpret_cast<const Color*>(p_variant._data._mem) ) ); } break; case IMAGE: { _data._image = memnew( Image( *p_variant._data._image ) ); } break; case _RID: { memnew_placement( _data._mem, RID( *reinterpret_cast<const RID*>(p_variant._data._mem) ) ); } break; case OBJECT: { memnew_placement( _data._mem, ObjData( p_variant._get_obj() ) ); } break; case NODE_PATH: { memnew_placement( _data._mem, NodePath( *reinterpret_cast<const NodePath*>(p_variant._data._mem) ) ); } break; case INPUT_EVENT: { _data._input_event= memnew( InputEvent( *p_variant._data._input_event ) ); } break; case DICTIONARY: { memnew_placement( _data._mem, Dictionary( *reinterpret_cast<const Dictionary*>(p_variant._data._mem) ) ); } break; case ARRAY: { memnew_placement( _data._mem, Array ( *reinterpret_cast<const Array*>(p_variant._data._mem) ) ); } break; // arrays case RAW_ARRAY: { memnew_placement( _data._mem, DVector<uint8_t> ( *reinterpret_cast<const DVector<uint8_t>*>(p_variant._data._mem) ) ); } break; case INT_ARRAY: { memnew_placement( _data._mem, DVector<int> ( *reinterpret_cast<const DVector<int>*>(p_variant._data._mem) ) ); } break; case REAL_ARRAY: { memnew_placement( _data._mem, DVector<real_t> ( *reinterpret_cast<const DVector<real_t>*>(p_variant._data._mem) ) ); } break; case STRING_ARRAY: { memnew_placement( _data._mem, DVector<String> ( *reinterpret_cast<const DVector<String>*>(p_variant._data._mem) ) ); } break; case VECTOR2_ARRAY: { memnew_placement( _data._mem, DVector<Vector2> ( *reinterpret_cast<const DVector<Vector2>*>(p_variant._data._mem) ) ); } break; case VECTOR3_ARRAY: { memnew_placement( _data._mem, DVector<Vector3> ( *reinterpret_cast<const DVector<Vector3>*>(p_variant._data._mem) ) ); } break; case COLOR_ARRAY: { memnew_placement( _data._mem, DVector<Color> ( *reinterpret_cast<const DVector<Color>*>(p_variant._data._mem) ) ); } break; default: {} } }
//============================================================================== CtrlrAbout::CtrlrAbout (CtrlrManager &_owner) : owner(_owner) { //[Constructor_pre] You can add your own custom stuff here.. //[/Constructor_pre] addAndMakeVisible (ctrlrName = new Label (String::empty, TRANS("Ctrlr"))); ctrlrName->setFont (Font (48.00f, Font::bold)); ctrlrName->setJustificationType (Justification::centredLeft); ctrlrName->setEditable (false, false, false); ctrlrName->setColour (Label::textColourId, Colour (0xd6000000)); ctrlrName->setColour (TextEditor::textColourId, Colours::black); ctrlrName->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); addAndMakeVisible (ctrlrLogo = new ImageButton (String::empty)); ctrlrLogo->addListener (this); ctrlrLogo->setImages (false, true, true, Image(), 0.750f, Colour (0x00000000), Image(), 0.850f, Colour (0x00000000), Image(), 0.990f, Colour (0x00000000)); addAndMakeVisible (versionInfoLabel = new TextEditor (String::empty)); versionInfoLabel->setMultiLine (true); versionInfoLabel->setReturnKeyStartsNewLine (true); versionInfoLabel->setReadOnly (true); versionInfoLabel->setScrollbarsShown (true); versionInfoLabel->setCaretVisible (false); versionInfoLabel->setPopupMenuEnabled (true); versionInfoLabel->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); versionInfoLabel->setColour (TextEditor::outlineColourId, Colour (0x9c000000)); versionInfoLabel->setColour (TextEditor::shadowColourId, Colour (0x00000000)); versionInfoLabel->setText (String::empty); addAndMakeVisible (label = new Label ("new label", TRANS("Instance name"))); label->setFont (Font (24.00f, Font::bold)); label->setJustificationType (Justification::topRight); label->setEditable (false, false, false); label->setColour (TextEditor::textColourId, Colours::black); label->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); addAndMakeVisible (label2 = new Label ("new label", TRANS("Author"))); label2->setFont (Font (24.00f, Font::plain)); label2->setJustificationType (Justification::topRight); label2->setEditable (false, false, false); label2->setColour (TextEditor::textColourId, Colours::black); label2->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); addAndMakeVisible (label3 = new Label ("new label", TRANS("Version"))); label3->setFont (Font (24.00f, Font::plain)); label3->setJustificationType (Justification::topRight); label3->setEditable (false, false, false); label3->setColour (TextEditor::textColourId, Colours::black); label3->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); addAndMakeVisible (label4 = new Label ("new label", TRANS("URL"))); label4->setFont (Font (24.00f, Font::plain)); label4->setJustificationType (Justification::topRight); label4->setEditable (false, false, false); label4->setColour (TextEditor::textColourId, Colours::black); label4->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); addAndMakeVisible (instanceUrl = new HyperlinkButton (String::empty, URL ("http://www.rawmaterialsoftware.com/juce"))); instanceUrl->setTooltip (TRANS("http://www.rawmaterialsoftware.com/juce")); addAndMakeVisible (instanceVersion = new Label (String::empty, String::empty)); instanceVersion->setFont (Font (22.00f, Font::bold)); instanceVersion->setJustificationType (Justification::topLeft); instanceVersion->setEditable (false, false, false); instanceVersion->setColour (TextEditor::textColourId, Colours::black); instanceVersion->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); addAndMakeVisible (instanceAuthor = new Label (String::empty, String::empty)); instanceAuthor->setFont (Font (22.00f, Font::bold)); instanceAuthor->setJustificationType (Justification::topLeft); instanceAuthor->setEditable (false, false, false); instanceAuthor->setColour (TextEditor::textColourId, Colours::black); instanceAuthor->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); addAndMakeVisible (instanceName = new Label (String::empty, String::empty)); instanceName->setFont (Font (24.00f, Font::bold)); instanceName->setJustificationType (Justification::topLeft); instanceName->setEditable (false, false, false); instanceName->setColour (TextEditor::textColourId, Colours::black); instanceName->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); addAndMakeVisible (instanceDescription = new TextEditor (String::empty)); instanceDescription->setMultiLine (true); instanceDescription->setReturnKeyStartsNewLine (true); instanceDescription->setReadOnly (true); instanceDescription->setScrollbarsShown (true); instanceDescription->setCaretVisible (false); instanceDescription->setPopupMenuEnabled (false); instanceDescription->setColour (TextEditor::backgroundColourId, Colour (0x00ffffff)); instanceDescription->setColour (TextEditor::outlineColourId, Colour (0x59000000)); instanceDescription->setColour (TextEditor::shadowColourId, Colour (0x00000000)); instanceDescription->setText (String::empty); //[UserPreSize] ctrlrLogo->setMouseCursor(MouseCursor::PointingHandCursor); ctrlrLogo->setImages (false, true, true, IMAGE(ico_midi_small_png), 0.8500f, Colour (0x0), IMAGE(ico_midi_small_png), 0.9500f, Colour (0x0), IMAGE(ico_midi_small_png), 1.0000f, Colour (0x0)); addVersionInfo ("Version", STR(ctrlrRevision)); addVersionInfo ("Build date", STR(ctrlrRevisionDate)); #if CTRLR_NIGHTLY == 1 addVersionInfo ("Branch", "Nightly"); #else addVersionInfo ("Branch", "Stable"); #endif addVersionInfo ("Juce", SystemStats::getJUCEVersion().fromLastOccurrenceOf("JUCE v", false, true)); addVersionInfo ("libusb", "1.0.19"); addVersionInfo ("liblo", "0.28"); addVersionInfo ("lua", LUA_RELEASE); addVersionInfo ("luabind", _STR(LUABIND_VERSION / 1000) + "." + _STR(LUABIND_VERSION / 100 % 100) + "." + _STR(LUABIND_VERSION % 100)); addVersionInfo ("boost", _STR(BOOST_VERSION / 100000) + "." + _STR(BOOST_VERSION / 100 % 1000) + "." + _STR(BOOST_VERSION % 100)); versionInfoLabel->setFont (Font (owner.getFontManager().getDefaultMonoFontName(), 12.0f, Font::plain)); versionInfoLabel->setColour (TextEditor::backgroundColourId, Colours::white.withAlpha(0.8f)); if (owner.getInstanceMode() == InstanceSingle || owner.getInstanceMode() == InstanceSingleRestriced) { //[/UserPreSize] setSize (600, 380); //[Constructor] You can add your own custom stuff here.. if (owner.getActivePanel()) { instanceName->setText (owner.getActivePanel()->getProperty(Ids::name).toString(), dontSendNotification); instanceAuthor->setText (owner.getActivePanel()->getProperty(Ids::panelAuthorName).toString(), dontSendNotification); instanceDescription->setText (owner.getActivePanel()->getProperty(Ids::panelAuthorDesc).toString(), dontSendNotification); instanceUrl->setButtonText (owner.getActivePanel()->getProperty(Ids::panelAuthorUrl)); instanceUrl->setURL(URL(owner.getActivePanel()->getProperty(Ids::panelAuthorUrl))); instanceVersion->setText (owner.getActivePanel()->getVersionString(false, false, "."), dontSendNotification); } } else { setSize (600, 96); } updateVersionLabel(); //[/Constructor] }
void Game::start() { int width = 800; int height = 600; // context creation this->context = new Context(); this->context->initialize(4, 3); this->context->createWindow(width, height, 1, "ZPG", false, false, true); this->context->setKeyCallback([](GLFWwindow* window, int key, int scan, int action, int modifier) { InputController::getInstance().onKeyCallback(window, key, scan, action, modifier); }); this->context->setMousePositionCallback([](GLFWwindow* window, double x, double y) { InputController::getInstance().onMouseMoveCallback(window, x, y); }); this->context->setMouseScrollCallback([](GLFWwindow* window, double xOffset, double yOffset) { InputController::getInstance().onMouseScrollCallback(window, xOffset, yOffset); }); this->context->setMouseButtonCallback([](GLFWwindow* window, int button, int action, int modifier) { InputController::getInstance().onMouseButtonCallback(window, button, action, modifier); }); this->context->setWindowSizeCallback([](GLFWwindow* window, int width, int height) { Game::getInstance().onWindowSizeCallback(window, width, height); }); this->context->setShowMouseCursor(false); this->context->setDepthTest(true); this->context->setDepthFunc(GL_LEQUAL); this->context->setStencilTest(true); this->context->setStencilMask(0xFF); this->context->setStencilFunc(GL_ALWAYS, 1, 0xFF); this->context->setStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); this->context->setCulling(true); this->context->setBlending(true); this->context->setBlendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); this->screenQuad = new ScreenQuad(); // manager preload AudioManager::getInstance().initialize(); TextureManager::getInstance().preloadTextures(); ModelManager::getInstance().preloadModels(); FontManager::getInstance().initialize(width, height); ShaderLoader::getInstance().addCodeMapping("#LIGHT_DEFINITIONS", FileHelper::loadFile("Shaders/Headers/light_definitions.frag")); ShaderLoader::getInstance().addCodeMapping("#PHONG_CALCULATIONS", FileHelper::loadFile("Shaders/Headers/phong_calculations.frag")); ProgramManager::getInstance().preloadPrograms(); Program program = ProgramManager::getInstance().get(ProgramManager::PROGRAM_MODEL); ProgramManager::getInstance().use(ProgramManager::PROGRAM_MODEL); FramebufferManager::getInstance().preloadFramebuffers(); // initial object spawn Camera* cameraScript = new Camera(new CameraController(10.0f), glm::vec3(0.0f, 0.0f, -1.0f), 45.0f, 4.0f / 3.0f, 0.1f, 1000.0f); this->camera = new GameObject(cameraScript, nullptr, new BasicPhysicsComponent(false, new SphereBoundingBox(1.0f))); this->camera->getTransform().setPosition(glm::vec3(0.0f, 0.0f, 8.0f)); this->camera->getTags().set(Tag::Camera); this->scene.add(this->camera); ProgramManager::getInstance().observeCamera(cameraScript); // objects float distance = 3.0f; GameObject* cube = new GameObject(nullptr, new ModelRenderComponent(ModelManager::getInstance().get(ModelManager::MODEL_CUBE), Color::Blue)); this->scene.add(cube); cube->getTransform().setPosition(glm::vec3(distance, 0.0f, 0.0f)); cube = new GameObject(nullptr, new ModelRenderComponent(ModelManager::getInstance().get(ModelManager::MODEL_CUBE), Color::Red)); this->scene.add(cube); cube->getTransform().setPosition(glm::vec3(-distance, 0.0f, 0.0f)); cube = new GameObject(nullptr, new ModelRenderComponent(ModelManager::getInstance().get(ModelManager::MODEL_CUBE), Color::Green)); this->scene.add(cube); cube->getTransform().setPosition(glm::vec3(0.0f, distance, 0.0f)); cube = new GameObject(nullptr, new ModelRenderComponent(ModelManager::getInstance().get(ModelManager::MODEL_CUBE), Color::Yellow)); this->scene.add(cube); cube->getTransform().setPosition(glm::vec3(0.0f, -distance, 0.0f)); // lights DirectionalLight *dirLight = new DirectionalLight(glm::vec3(10.0f, 10.0f, 10.0f), Phong(Color::White * 0.001f, Color::White, Color::White * 0.1f)); GameObject* light = new GameObject(new LightComponent(dirLight, "directionalLight")); light->getTags().set(Tag::Light); this->scene.add(light); GeometryObject planeGeometry(VERTICES_PLANE, 2 * sizeof(glm::vec3), 6); planeGeometry.setAttributePositionNormal(); GeometryObject cubeGeometry(VERTICES_CUBE, sizeof(glm::vec3), 36); cubeGeometry.setAttributePosition(); PointLight* pointLight = new PointLight(Attenuation::ATT_DISTANCE_LONG, Phong(Color::White * 0.1f, Color::White, Color::White)); light = new GameObject( new LightComponent(pointLight, "pointLights", 0), new SimpleConstantRenderer(cubeGeometry, ProgramManager::PROGRAM_GEOMETRY_CONSTANT, Color::White) ); light->getTransform().setPosition(glm::vec3(0.0f, 0.0f, 0.0f)); light->getTags().set(Tag::Light); this->scene.add(light); program.setUniform1i("pointLightCount", 1); SpotLight* spotLight = new SpotLight(glm::vec3(0.0f, 0.0f, -1.0f), 12.5f, 17.5f, Attenuation::ATT_DISTANCE_LONG, dirLight->phong); GameObject* spotLightObj = new GameObject(new LightComponent(spotLight, "spotLight")); spotLightObj->getTags().set(Tag::Light); this->scene.add(spotLightObj); GameObject* floor = new GameObject(nullptr, new SimpleConstantRenderer(planeGeometry, ProgramManager::PROGRAM_MODEL, Color::Purple)); floor->getTransform().setScale(glm::vec3(10.0f)); floor->getTransform().setPosition(glm::vec3(0.0f, -5.0f, 0.0f)); this->scene.add(floor); // skybox const std::string skyboxPath = "Resources/Textures/skybox/"; std::vector<Image> skyboxFaces; skyboxFaces.push_back(Image(skyboxPath + "right.jpg")); skyboxFaces.push_back(Image(skyboxPath + "left.jpg")); skyboxFaces.push_back(Image(skyboxPath + "top.jpg")); skyboxFaces.push_back(Image(skyboxPath + "bottom.jpg")); skyboxFaces.push_back(Image(skyboxPath + "back.jpg")); skyboxFaces.push_back(Image(skyboxPath + "front.jpg")); Cubemap skyboxCubemap; skyboxCubemap.allocate(); skyboxCubemap.set2DImages(skyboxFaces); GameObject* skybox = new GameObject(nullptr, new SkyboxRenderer(skyboxCubemap)); this->scene.add(skybox); GameObject* crossHair = new GameObject(nullptr, new SpriteRenderer(TextureManager::TEXTURE_CROSSHAIR)); crossHair->getTransform().setScale(glm::vec3(50.0f, 50.0f, 1.0f)); this->scene.add(crossHair); Timer timer(0.01f); Timer switchTimer(0.05f); context->loop([&](Context& context) // physics { //this->physicsHandler.simulate(this->scene.getObjectManager().getObjects(), this->scene.getObjectManager().getObjectCount(), Context::getFixedDeltaTime()); }, [&](Context& context) // render { float delta = context.getDeltaTime(); timer.update(delta); switchTimer.update(delta); FramebufferManager::getInstance().get(FramebufferManager::FRAMEBUFFER_POSTPROCESS).bind(); RenderUtils::clearColor(0.0f, 0.0f, 0.0f, 1.0f); RenderUtils::clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); context.setDepthTest(true); spotLight->direction = cameraScript->getFront(); spotLightObj->getTransform().setPosition(camera->getTransform().getPosition()); crossHair->getTransform().setPosition(glm::vec3(context.getWindowWidth() / 2.0f, context.getWindowHeight() / 2.0f, 0.0f)); this->scene.update(); this->scene.draw(); GLchar byte; glReadPixels(context.getWindowWidth() / 2, context.getWindowHeight() / 2, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, &byte); // stencil value at the center this->screenQuad->drawScreen(context); if (timer.resetIfReady()) { FontManager::getInstance().renderText("FPS: " + std::to_string(round(1.0f / delta)), 10.0f, height - 20.0f, 0.5f, glm::vec3(1.0f, 1.0f, 0.0f)); } if (InputController::getInstance().isButtonPressed(GLFW_KEY_ESCAPE)) { context.closeWindow(); } else if (InputController::getInstance().isButtonPressed(GLFW_KEY_SPACE) && switchTimer.resetIfReady()) { // switch render strategy } InputController::getInstance().afterUpdate(); this->scene.updateFrameEnd(); }); // resource disposal this->screenQuad->dispose(); delete this->screenQuad; this->scene.dispose(); ProgramManager::getInstance().dispose(); ModelManager::getInstance().dispose(); TextureManager::getInstance().dispose(); FramebufferManager::getInstance().dispose(); AudioManager::getInstance().dispose(); FontManager::getInstance().dispose(); context->terminate(); }
void Bouton::definirTexte(Unichar const &txt) { _texte.definir(txt); _image = Image(); _estImage = false; }
void init(){ bool cOut = pa("-c"), dOut = pa("-d"); if(cOut){ colorOut.init(pa("-c")); } if(dOut){ depthOut.init(pa("-d")); } if(cOut || dOut){ prevGUI << (cOut ? Image().handle("color") : Dummy()) << (dOut ? Image().handle("depth") : Dummy()) << Create(); } gui << Draw3D().handle("draw") << ( VBox().minSize(10,2) << FSlider(-10,10,0).out("x").label("translate x") << FSlider(-10,10,0).out("y").label("translate y") << FSlider(1.5,10,0).out("z").label("translate z") << FSlider(-4,4,0).out("rx").label("rotate x") << FSlider(-4,4,0).out("ry").label("rotate y") << FSlider(-4,4,0).out("rz").label("rotate z") << ((cOut||dOut) ? (const GUIComponent&)Button("show","hide").label("preview").handle("preview") : (const GUIComponent&)Dummy() ) << Button("reset view").handle("resetView") ) << Show(); if(cOut || dOut){ gui["preview"].registerCallback(utils::function(&prevGUI,&GUI::switchVisibility)); if(dOut){ ImageHandle d = prevGUI["depth"]; d->setRangeMode(ICLWidget::rmAuto); } } Camera defaultCam(Vec(4.73553,-3.74203,8.06666,1), Vec(-0.498035,0.458701,-0.735904,1), Vec(0.787984,-0.116955,-0.604486,1)); scene.addCamera( !pa("-cam").as<bool>() ? defaultCam : Camera(*pa("-cam"))); initDepthCam = scene.getCamera(0); if(pa("-ccam")){ scene.addCamera(*pa("-ccam")); Mat D=scene.getCamera(0).getCSTransformationMatrix(); Mat C=scene.getCamera(1).getCSTransformationMatrix(); relTM = new Mat( C * D.inv() ); } SceneObject* ground = SceneObject::cuboid(0,0,0,200,200,3); ground->setColor(Primitive::quad,GeomColor(100,100,100,255)); scene.addObject(ground); if(pa("-object")){ scene.addObject( (obj = new SceneObject(*pa("-object"))) ); }else{ scene.addObject( (obj = SceneObject::cube(0,0,3, 3) ) ); } obj->setColor(Primitive::quad, GeomColor(0,100,255,255)); obj->setColor(Primitive::triangle, GeomColor(0,100,255,255)); obj->setColor(Primitive::polygon, GeomColor(0,100,255,255)); obj->setVisible(Primitive::line | Primitive::vertex, false); gui["draw"].link(scene.getGLCallback(0)); gui["draw"].install(scene.getMouseHandler(0)); scene.setDrawCamerasEnabled(false); scene.addCamera(scene.getCamera(0)); }
void FFTConvolve::convolveSingle(Image im, Image filter, Image out, Convolve::BoundaryCondition b) { // Deal with the homogeneous case recursively. This is slightly // inefficient because we construct and transform the filter // twice, but it makes the code much simpler if (b == Convolve::Homogeneous) { Image result = apply(im, filter, Convolve::Zero, Multiply::Outer); Image weight(im.width, im.height, im.frames, 1); weight.set(1.0f); Image resultW = apply(weight, filter, Convolve::Zero, Multiply::Outer); out += Stats(filter).sum() * result / resultW; return; } assert(filter.width % 2 == 1 && filter.height % 2 == 1 && filter.frames % 2 == 1, "The filter must have odd dimensions\n"); int xPad = filter.width/2; int yPad = filter.height/2; int tPad = filter.frames/2; if (b == Convolve::Wrap) { xPad = yPad = tPad = 0; } Image weightT; Image imT = Image(im.width+xPad*2, im.height+yPad*2, im.frames+tPad*2, 2); //printf("1\n"); fflush(stdout); // 1) Make the padded complex image if (b == Convolve::Clamp) { for (int t = 0; t < imT.frames; t++) { int st = clamp(t-tPad, 0, im.frames-1); for (int y = 0; y < imT.height; y++) { int sy = clamp(y-yPad, 0, im.height-1); for (int x = 0; x < imT.width; x++) { int sx = clamp(x-xPad, 0, im.width-1); imT(x, y, t, 0) = im(sx, sy, st, 0); } } } } else { // Zero or Wrap imT.region(xPad, yPad, tPad, 0, im.width, im.height, im.frames, 1).set(im); } //printf("2\n"); fflush(stdout); // 2) Transform the padded image FFT::apply(imT); //printf("3\n"); fflush(stdout); // 3) Make a padded complex filter of the same size Image filterT(imT.width, imT.height, imT.frames, 2); for (int t = 0; t < filter.frames; t++) { int ft = t - filter.frames/2; if (ft < 0) ft += filterT.frames; for (int y = 0; y < filter.height; y++) { int fy = y - filter.height/2; if (fy < 0) fy += filterT.height; for (int x = 0; x < filter.width; x++) { int fx = x - filter.width/2; if (fx < 0) fx += filterT.width; filterT(fx, fy, ft, 0) = filter(x, y, t, 0); } } } //printf("4\n"); fflush(stdout); // 4) Transform the padded filter FFT::apply(filterT); //printf("5\n"); fflush(stdout); // 5) Multiply the two into a padded complex transformed result ComplexMultiply::apply(imT, filterT); //printf("6\n"); fflush(stdout); // 6) Inverse transorm the result IFFT::apply(imT); //printf("7\n"); fflush(stdout); // 7) Remove the padding, and convert back to real numbers out += imT.region(xPad, yPad, tPad, 0, im.width, im.height, im.frames, 1); }
/*init background menu*/ Menu::Menu(const std::string &imgPath) { background = Image(imgPath); }
LowLevelGraphicsContext* createLowLevelContext() { return new LowLevelGraphicsSoftwareRenderer (Image (this)); }
Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) { uint32_t type = f->get_32(); print_bl("find property of type: "+itos(type)); switch(type) { case VARIANT_NIL: { r_v=Variant(); } break; case VARIANT_BOOL: { r_v=bool(f->get_32()); } break; case VARIANT_INT: { r_v=int(f->get_32()); } break; case VARIANT_REAL: { r_v=f->get_real(); } break; case VARIANT_STRING: { r_v=get_unicode_string(); } break; case VARIANT_VECTOR2: { Vector2 v; v.x=f->get_real(); v.y=f->get_real(); r_v=v; } break; case VARIANT_RECT2: { Rect2 v; v.pos.x=f->get_real(); v.pos.y=f->get_real(); v.size.x=f->get_real(); v.size.y=f->get_real(); r_v=v; } break; case VARIANT_VECTOR3: { Vector3 v; v.x=f->get_real(); v.y=f->get_real(); v.z=f->get_real(); r_v=v; } break; case VARIANT_PLANE: { Plane v; v.normal.x=f->get_real(); v.normal.y=f->get_real(); v.normal.z=f->get_real(); v.d=f->get_real(); r_v=v; } break; case VARIANT_QUAT: { Quat v; v.x=f->get_real(); v.y=f->get_real(); v.z=f->get_real(); v.w=f->get_real(); r_v=v; } break; case VARIANT_AABB: { AABB v; v.pos.x=f->get_real(); v.pos.y=f->get_real(); v.pos.z=f->get_real(); v.size.x=f->get_real(); v.size.y=f->get_real(); v.size.z=f->get_real(); r_v=v; } break; case VARIANT_MATRIX32: { Matrix32 v; v.elements[0].x=f->get_real(); v.elements[0].y=f->get_real(); v.elements[1].x=f->get_real(); v.elements[1].y=f->get_real(); v.elements[2].x=f->get_real(); v.elements[2].y=f->get_real(); r_v=v; } break; case VARIANT_MATRIX3: { Matrix3 v; v.elements[0].x=f->get_real(); v.elements[0].y=f->get_real(); v.elements[0].z=f->get_real(); v.elements[1].x=f->get_real(); v.elements[1].y=f->get_real(); v.elements[1].z=f->get_real(); v.elements[2].x=f->get_real(); v.elements[2].y=f->get_real(); v.elements[2].z=f->get_real(); r_v=v; } break; case VARIANT_TRANSFORM: { Transform v; v.basis.elements[0].x=f->get_real(); v.basis.elements[0].y=f->get_real(); v.basis.elements[0].z=f->get_real(); v.basis.elements[1].x=f->get_real(); v.basis.elements[1].y=f->get_real(); v.basis.elements[1].z=f->get_real(); v.basis.elements[2].x=f->get_real(); v.basis.elements[2].y=f->get_real(); v.basis.elements[2].z=f->get_real(); v.origin.x=f->get_real(); v.origin.y=f->get_real(); v.origin.z=f->get_real(); r_v=v; } break; case VARIANT_COLOR: { Color v; v.r=f->get_real(); v.g=f->get_real(); v.b=f->get_real(); v.a=f->get_real(); r_v=v; } break; case VARIANT_IMAGE: { uint32_t encoding = f->get_32(); if (encoding==IMAGE_ENCODING_EMPTY) { r_v=Variant(); break; } else if (encoding==IMAGE_ENCODING_RAW) { uint32_t width = f->get_32(); uint32_t height = f->get_32(); uint32_t mipmaps = f->get_32(); uint32_t format = f->get_32(); Image::Format fmt; switch(format) { case IMAGE_FORMAT_GRAYSCALE: { fmt=Image::FORMAT_GRAYSCALE; } break; case IMAGE_FORMAT_INTENSITY: { fmt=Image::FORMAT_INTENSITY; } break; case IMAGE_FORMAT_GRAYSCALE_ALPHA: { fmt=Image::FORMAT_GRAYSCALE_ALPHA; } break; case IMAGE_FORMAT_RGB: { fmt=Image::FORMAT_RGB; } break; case IMAGE_FORMAT_RGBA: { fmt=Image::FORMAT_RGBA; } break; case IMAGE_FORMAT_INDEXED: { fmt=Image::FORMAT_INDEXED; } break; case IMAGE_FORMAT_INDEXED_ALPHA: { fmt=Image::FORMAT_INDEXED_ALPHA; } break; case IMAGE_FORMAT_BC1: { fmt=Image::FORMAT_BC1; } break; case IMAGE_FORMAT_BC2: { fmt=Image::FORMAT_BC2; } break; case IMAGE_FORMAT_BC3: { fmt=Image::FORMAT_BC3; } break; case IMAGE_FORMAT_BC4: { fmt=Image::FORMAT_BC4; } break; case IMAGE_FORMAT_BC5: { fmt=Image::FORMAT_BC5; } break; case IMAGE_FORMAT_PVRTC2: { fmt=Image::FORMAT_PVRTC2; } break; case IMAGE_FORMAT_PVRTC2_ALPHA: { fmt=Image::FORMAT_PVRTC2_ALPHA; } break; case IMAGE_FORMAT_PVRTC4: { fmt=Image::FORMAT_PVRTC4; } break; case IMAGE_FORMAT_PVRTC4_ALPHA: { fmt=Image::FORMAT_PVRTC4_ALPHA; } break; case IMAGE_FORMAT_ETC: { fmt=Image::FORMAT_ETC; } break; case IMAGE_FORMAT_ATC: { fmt=Image::FORMAT_ATC; } break; case IMAGE_FORMAT_ATC_ALPHA_EXPLICIT: { fmt=Image::FORMAT_ATC_ALPHA_EXPLICIT; } break; case IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED: { fmt=Image::FORMAT_ATC_ALPHA_INTERPOLATED; } break; case IMAGE_FORMAT_CUSTOM: { fmt=Image::FORMAT_CUSTOM; } break; default: { ERR_FAIL_V(ERR_FILE_CORRUPT); } } uint32_t datalen = f->get_32(); DVector<uint8_t> imgdata; imgdata.resize(datalen); DVector<uint8_t>::Write w = imgdata.write(); f->get_buffer(w.ptr(),datalen); _advance_padding(datalen); w=DVector<uint8_t>::Write(); r_v=Image(width,height,mipmaps,fmt,imgdata); } else { //compressed DVector<uint8_t> data; data.resize(f->get_32()); DVector<uint8_t>::Write w = data.write(); f->get_buffer(w.ptr(),data.size()); w = DVector<uint8_t>::Write(); Image img; if (encoding==IMAGE_ENCODING_LOSSY && Image::lossy_unpacker) { img = Image::lossy_unpacker(data); } else if (encoding==IMAGE_ENCODING_LOSSLESS && Image::lossless_unpacker) { img = Image::lossless_unpacker(data); } _advance_padding(data.size()); r_v=img; } } break; case VARIANT_NODE_PATH: { Vector<StringName> names; Vector<StringName> subnames; StringName property; bool absolute; int name_count = f->get_16(); uint32_t subname_count = f->get_16(); absolute=subname_count&0x8000; subname_count&=0x7FFF; for(int i=0;i<name_count;i++) names.push_back(string_map[f->get_32()]); for(uint32_t i=0;i<subname_count;i++) subnames.push_back(string_map[f->get_32()]); property=string_map[f->get_32()]; NodePath np = NodePath(names,subnames,absolute,property); //print_line("got path: "+String(np)); r_v=np; } break; case VARIANT_RID: { r_v=f->get_32(); } break; case VARIANT_OBJECT: { uint32_t type=f->get_32(); switch(type) { case OBJECT_EMPTY: { //do none } break; case OBJECT_INTERNAL_RESOURCE: { uint32_t index=f->get_32(); String path = res_path+"::"+itos(index); RES res = ResourceLoader::load(path); if (res.is_null()) { WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data()); } r_v=res; } break; case OBJECT_EXTERNAL_RESOURCE: { String type = get_unicode_string(); String path = get_unicode_string(); if (path.find("://")==-1 && path.is_rel_path()) { // path is relative to file being loaded, so convert to a resource path path=Globals::get_singleton()->localize_path(res_path.get_base_dir()+"/"+path); } RES res=ResourceLoader::load(path,type); if (res.is_null()) { WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data()); } r_v=res; } break; default: { ERR_FAIL_V(ERR_FILE_CORRUPT); } break; } } break; case VARIANT_INPUT_EVENT: { } break; case VARIANT_DICTIONARY: { uint32_t len=f->get_32(); Dictionary d(len&0x80000000); //last bit means shared len&=0x7FFFFFFF; for(uint32_t i=0;i<len;i++) { Variant key; Error err = parse_variant(key); ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); Variant value; err = parse_variant(value); ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); d[key]=value; } r_v=d; } break; case VARIANT_ARRAY: { uint32_t len=f->get_32(); Array a(len&0x80000000); //last bit means shared len&=0x7FFFFFFF; a.resize(len); for(uint32_t i=0;i<len;i++) { Variant val; Error err = parse_variant(val); ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT); a[i]=val; } r_v=a; } break; case VARIANT_RAW_ARRAY: { uint32_t len = f->get_32(); DVector<uint8_t> array; array.resize(len); DVector<uint8_t>::Write w = array.write(); f->get_buffer(w.ptr(),len); _advance_padding(len); w=DVector<uint8_t>::Write(); r_v=array; } break; case VARIANT_INT_ARRAY: { uint32_t len = f->get_32(); DVector<int> array; array.resize(len); DVector<int>::Write w = array.write(); f->get_buffer((uint8_t*)w.ptr(),len*4); #ifdef BIG_ENDIAN_ENABLED { uint32_t *ptr=(uint32_t*)w.ptr(); for(int i=0;i<len;i++) { ptr[i]=BSWAP32(ptr[i]); } } #endif w=DVector<int>::Write(); r_v=array; } break; case VARIANT_REAL_ARRAY: { uint32_t len = f->get_32(); DVector<real_t> array; array.resize(len); DVector<real_t>::Write w = array.write(); f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)); #ifdef BIG_ENDIAN_ENABLED { uint32_t *ptr=(uint32_t*)w.ptr(); for(int i=0;i<len;i++) { ptr[i]=BSWAP32(ptr[i]); } } #endif w=DVector<real_t>::Write(); r_v=array; } break; case VARIANT_STRING_ARRAY: { uint32_t len = f->get_32(); DVector<String> array; array.resize(len); DVector<String>::Write w = array.write(); for(uint32_t i=0;i<len;i++) w[i]=get_unicode_string(); w=DVector<String>::Write(); r_v=array; } break; case VARIANT_VECTOR2_ARRAY: { uint32_t len = f->get_32(); DVector<Vector2> array; array.resize(len); DVector<Vector2>::Write w = array.write(); if (sizeof(Vector2)==8) { f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*2); #ifdef BIG_ENDIAN_ENABLED { uint32_t *ptr=(uint32_t*)w.ptr(); for(int i=0;i<len*2;i++) { ptr[i]=BSWAP32(ptr[i]); } } #endif } else { ERR_EXPLAIN("Vector2 size is NOT 8!"); ERR_FAIL_V(ERR_UNAVAILABLE); } w=DVector<Vector2>::Write(); r_v=array; } break; case VARIANT_VECTOR3_ARRAY: { uint32_t len = f->get_32(); DVector<Vector3> array; array.resize(len); DVector<Vector3>::Write w = array.write(); if (sizeof(Vector3)==12) { f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*3); #ifdef BIG_ENDIAN_ENABLED { uint32_t *ptr=(uint32_t*)w.ptr(); for(int i=0;i<len*3;i++) { ptr[i]=BSWAP32(ptr[i]); } } #endif } else { ERR_EXPLAIN("Vector3 size is NOT 12!"); ERR_FAIL_V(ERR_UNAVAILABLE); } w=DVector<Vector3>::Write(); r_v=array; } break; case VARIANT_COLOR_ARRAY: { uint32_t len = f->get_32(); DVector<Color> array; array.resize(len); DVector<Color>::Write w = array.write(); if (sizeof(Color)==16) { f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*4); #ifdef BIG_ENDIAN_ENABLED { uint32_t *ptr=(uint32_t*)w.ptr(); for(int i=0;i<len*4;i++) { ptr[i]=BSWAP32(ptr[i]); } } #endif } else { ERR_EXPLAIN("Color size is NOT 16!"); ERR_FAIL_V(ERR_UNAVAILABLE); } w=DVector<Color>::Write(); r_v=array; } break; default: { ERR_FAIL_V(ERR_FILE_CORRUPT); } break; } return OK; //never reach anyway }
inline void addImage(const QRect &rect, const QByteArray &data) { m_images.push_back(Image(rect, data)); }
Image Image::createCopy() const { return Image (image != nullptr ? image->clone() : nullptr); }
LowLevelGraphicsContext* createLowLevelContext() override { sendDataChangeMessage(); return new LowLevelGraphicsSoftwareRenderer (Image (this)); }
Image Image::load(Canvas &canvas, const std::string &id, const XMLResourceDocument &doc) { Image image; XMLResourceNode resource = doc.get_resource(id); DomNode cur_node = resource.get_element().get_first_child(); while (!cur_node.is_null()) { if (!cur_node.is_element()) { cur_node = cur_node.get_next_sibling(); continue; } DomElement cur_element = cur_node.to_element(); std::string tag_name = cur_element.get_tag_name(); if (tag_name == "image" || tag_name == "image-file") { std::string image_name = cur_element.get_attribute("file"); Texture2D texture = Texture2D(canvas, PathHelp::combine(resource.get_base_path(), image_name), resource.get_file_system()); DomNode cur_child(cur_element.get_first_child()); if (cur_child.is_null()) { image = Image(texture, texture.get_size()); } else { do { DomElement cur_child_elemnt = cur_child.to_element(); if (cur_child.get_node_name() == "grid") { Point position; Size texture_size = texture.get_size(); Size size = texture_size; std::vector<std::string> image_size = StringHelp::split_text(cur_child_elemnt.get_attribute("size"), ","); if (image_size.size() > 0) size.width = StringHelp::text_to_int(image_size[0]); if (image_size.size() > 1) size.height = StringHelp::text_to_int(image_size[1]); if (cur_child_elemnt.has_attribute("pos")) { std::vector<std::string> image_pos = StringHelp::split_text(cur_child_elemnt.get_attribute("pos"), ","); if (image_pos.size() > 0) position.x = StringHelp::text_to_int(image_pos[0]); if (image_pos.size() > 1) position.y = StringHelp::text_to_int(image_pos[1]); } if ((size.width + position.x) > texture_size.width) size.width = (texture_size.width - position.x); if ((size.height + position.y) > texture_size.height) size.height = (texture_size.height - position.y); image = Image(texture, Rect(position, size)); } cur_child = cur_child.get_next_sibling(); } while (!cur_child.is_null()); } break; } cur_node = cur_node.get_next_sibling(); } if (image.is_null()) throw Exception("Image resource contained no frames!"); cur_node = resource.get_element().get_first_child(); while (!cur_node.is_null()) { if (!cur_node.is_element()) { cur_node = cur_node.get_next_sibling(); continue; } DomElement cur_element = cur_node.to_element(); std::string tag_name = cur_element.get_tag_name(); // <color red="float" green="float" blue="float" alpha="float" /> if (tag_name == "color") { Colorf color; color.r = (float)StringHelp::text_to_float(cur_element.get_attribute("red", "1.0")); color.g = (float)StringHelp::text_to_float(cur_element.get_attribute("green", "1.0")); color.b = (float)StringHelp::text_to_float(cur_element.get_attribute("blue", "1.0")); color.a = (float)StringHelp::text_to_float(cur_element.get_attribute("alpha", "1.0")); image.set_color(color); } // <scale x="float" y="float /> else if (tag_name == "scale") { float scale_x = StringHelp::text_to_float(cur_element.get_attribute("x", "1.0")); float scale_y = StringHelp::text_to_float(cur_element.get_attribute("y", "1.0")); image.set_scale(scale_x, scale_y); } // <translation origin="string" x="integer" y="integer" /> else if (tag_name == "translation") { std::string hotspot = cur_element.get_attribute("origin", "top_left"); Origin origin; if (hotspot == "center") origin = origin_center; else if (hotspot == "top_center") origin = origin_top_center; else if (hotspot == "top_right") origin = origin_top_right; else if (hotspot == "center_left") origin = origin_center_left; else if (hotspot == "center_right") origin = origin_center_right; else if (hotspot == "bottom_left") origin = origin_bottom_left; else if (hotspot == "bottom_center") origin = origin_bottom_center; else if (hotspot == "bottom_right") origin = origin_bottom_right; else origin = origin_top_left; int xoffset = StringHelp::text_to_int(cur_element.get_attribute("x", "0")); int yoffset = StringHelp::text_to_int(cur_element.get_attribute("y", "0")); // TODO Find out what is going on here... xoffset /= image.get_texture().get_texture().get_pixel_ratio(); yoffset /= image.get_texture().get_texture().get_pixel_ratio(); image.set_alignment(origin, xoffset, yoffset); } cur_node = cur_node.get_next_sibling(); } return image; }
Image LoadBlock::apply(string filename, int xoff, int yoff, int toff, int coff, int width, int height, int frames, int channels) { // peek in the header struct { int frames, width, height, channels, type; } header; FILE *f = fopen(filename.c_str(), "rb"); assert(f, "Could not open file: %s", filename.c_str()); fread_(&header, sizeof(int), 5, f); if (frames <= 0) frames = header.frames; if (width <= 0) width = header.width; if (height <= 0) height = header.height; if (channels <= 0) channels = header.channels; if (header.type != 0) { fclose(f); panic("-loadblock can only handle tmp files containing floating point data.\n"); return Image(); } // sanity check the header if (header.frames < 1 || header.width < 1 || header.height < 1 || header.channels < 1) { fclose(f); panic("According the header of the tmp file, the image has dimensions %ix%ix%ix%i. " "Perhaps this is not a tmp file?\n", header.frames, header.width, header.height, header.channels); return Image(); } Image out(width, height, frames, channels); float *outPtr; off_t frameBytes = header.width*header.height*header.channels*sizeof(float); off_t sampleBytes = header.channels*sizeof(float); off_t scanlineBytes = header.width*header.channels*sizeof(float); const off_t headerBytes = 5*sizeof(float); int xmin = max(xoff, 0); int xmax = min(xoff+width, header.width); int cmin = max(coff, 0); int cmax = min(coff+channels, header.channels); int ymin = max(yoff, 0); int ymax = min(yoff+height, header.height); int tmin = max(toff, 0); int tmax = min(toff+frames, header.frames); // the contiguous channel case if (coff == 0 && channels == header.channels) { for (int t = tmin; t < tmax; t++) { for (int y = ymin; y < ymax; y++) { off_t offset = (t*frameBytes + y*scanlineBytes + xmin*sampleBytes + headerBytes); fseeko(f, offset, SEEK_SET); fread_(out(xmin-xoff, y-yoff, t-toff), sizeof(float), (xmax-xmin)*channels, f); } } } else { // the non-contiguous channel case vector<float> scanline(width*header.channels); for (int t = tmin; t < tmax; t++) { for (int y = ymin; y < ymax; y++) { off_t offset = (t*frameBytes + y*scanlineBytes + xmin*sampleBytes + headerBytes); fseeko(f, offset, SEEK_SET); fread_(&scanline[0], sizeof(float), (xmax-xmin)*header.channels, f); outPtr = out(xmin-xoff, y-yoff, t-toff); for (int x = 0; x < xmax-xmin; x++) { for (int c = cmin; c < cmax; c++) { *outPtr++ = scanline[x*header.channels+c]; } } } } } fclose(f); return out; }
const Image& Image::operator +(const Image& rhs) { return Image(*this) += rhs; }
void _create_body_shape_data() { VisualServer *vs = VisualServer::get_singleton(); Physics2DServer *ps = Physics2DServer::get_singleton(); // SEGMENT { PoolVector<uint8_t> pixels; pixels.resize(32 * 2 * 2); for (int i = 0; i < 2; i++) { for (int j = 0; j < 32; j++) { pixels.set(i * 32 * 2 + j * 2 + 0, (j == 0) ? 255 : 0); pixels.set(i * 32 * 2 + j * 2 + 1, 255); } } Ref<Image> image = memnew(Image(32, 2, 0, Image::FORMAT_LA8, pixels)); body_shape_data[Physics2DServer::SHAPE_SEGMENT].image = vs->texture_create_from_image(image); RID segment_shape = ps->segment_shape_create(); Rect2 sg(Point2(-16, 0), Point2(16, 0)); ps->shape_set_data(segment_shape, sg); body_shape_data[Physics2DServer::SHAPE_SEGMENT].shape = segment_shape; } // CIRCLE { PoolVector<uint8_t> pixels; pixels.resize(32 * 32 * 2); for (int i = 0; i < 32; i++) { for (int j = 0; j < 32; j++) { bool black = Vector2(i - 16, j - 16).length_squared() < 16 * 16; pixels.set(i * 32 * 2 + j * 2 + 0, (i == 16 || j == 16) ? 255 : 0); pixels.set(i * 32 * 2 + j * 2 + 1, black ? 255 : 0); } } Ref<Image> image = memnew(Image(32, 32, 0, Image::FORMAT_LA8, pixels)); body_shape_data[Physics2DServer::SHAPE_CIRCLE].image = vs->texture_create_from_image(image); RID circle_shape = ps->circle_shape_create(); ps->shape_set_data(circle_shape, 16); body_shape_data[Physics2DServer::SHAPE_CIRCLE].shape = circle_shape; } // BOX { PoolVector<uint8_t> pixels; pixels.resize(32 * 32 * 2); for (int i = 0; i < 32; i++) { for (int j = 0; j < 32; j++) { bool black = i > 0 && i < 31 && j > 0 && j < 31; pixels.set(i * 32 * 2 + j * 2 + 0, black ? 0 : 255); pixels.set(i * 32 * 2 + j * 2 + 1, 255); } } Ref<Image> image = memnew(Image(32, 32, 0, Image::FORMAT_LA8, pixels)); body_shape_data[Physics2DServer::SHAPE_RECTANGLE].image = vs->texture_create_from_image(image); RID rectangle_shape = ps->rectangle_shape_create(); ps->shape_set_data(rectangle_shape, Vector2(16, 16)); body_shape_data[Physics2DServer::SHAPE_RECTANGLE].shape = rectangle_shape; } // CAPSULE { PoolVector<uint8_t> pixels; pixels.resize(32 * 64 * 2); for (int i = 0; i < 64; i++) { for (int j = 0; j < 32; j++) { int si = i > 48 ? i - 32 : (i < 16 ? i : 16); bool black = Vector2(si - 16, j - 16).length_squared() < 16 * 16; pixels.set(i * 32 * 2 + j * 2 + 0, (i == 16 || j == 16 || i == 48) ? 255 : 0); pixels.set(i * 32 * 2 + j * 2 + 1, black ? 255 : 0); } } Ref<Image> image = memnew(Image(32, 64, 0, Image::FORMAT_LA8, pixels)); body_shape_data[Physics2DServer::SHAPE_CAPSULE].image = vs->texture_create_from_image(image); RID capsule_shape = ps->capsule_shape_create(); ps->shape_set_data(capsule_shape, Vector2(16, 32)); body_shape_data[Physics2DServer::SHAPE_CAPSULE].shape = capsule_shape; } // CONVEX { Ref<Image> image = memnew(Image(convex_png)); body_shape_data[Physics2DServer::SHAPE_CONVEX_POLYGON].image = vs->texture_create_from_image(image); RID convex_polygon_shape = ps->convex_polygon_shape_create(); PoolVector<Vector2> arr; Point2 sb(32, 32); arr.push_back(Point2(20, 3) - sb); arr.push_back(Point2(58, 23) - sb); arr.push_back(Point2(55, 54) - sb); arr.push_back(Point2(27, 60) - sb); arr.push_back(Point2(5, 56) - sb); arr.push_back(Point2(4, 20) - sb); arr.push_back(Point2(11, 7) - sb); ps->shape_set_data(convex_polygon_shape, arr); body_shape_data[Physics2DServer::SHAPE_CONVEX_POLYGON].shape = convex_polygon_shape; } }
ColorPicker::ColorPicker() : BoxContainer(true) { updating=true; edit_alpha=true; text_is_constructor = false; raw_mode_enabled=false; changing_color=false; screen=NULL; HBoxContainer *hb_smpl = memnew( HBoxContainer ); btn_pick = memnew( ToolButton ); btn_pick->connect("pressed",this,"_screen_pick_pressed"); sample = memnew( TextureFrame ); sample->set_h_size_flags(SIZE_EXPAND_FILL); sample->connect("draw",this,"_sample_draw"); hb_smpl->add_child(sample); hb_smpl->add_child(btn_pick); add_child(hb_smpl); HBoxContainer *hb_edit = memnew( HBoxContainer ); uv_edit= memnew ( TextureFrame ); Image i(256, 256, false, Image::FORMAT_RGB); for (int y=0;y<256;y++) for (int x=0;x<256;x++) i.put_pixel(x,y,Color()); Ref<ImageTexture> t; t.instance(); t->create_from_image(i); uv_edit->set_texture(t); uv_edit->set_ignore_mouse(false); uv_edit->set_custom_minimum_size(Size2(256,256)); uv_edit->connect("input_event", this, "_uv_input"); Control *c= memnew( Control ); uv_edit->add_child(c); c->set_area_as_parent_rect(); c->set_stop_mouse(false); c->set_material(memnew ( CanvasItemMaterial )); Vector<Variant> args=Vector<Variant>(); args.push_back(0); args.push_back(c); c->connect("draw",this,"_hsv_draw",args); add_child(hb_edit); w_edit= memnew( TextureFrame ); i = Image(15, 256, false, Image::FORMAT_RGB); for (int y=0;y<256;y++) for (int x=0;x<15;x++) i.put_pixel(x,y,Color()); Ref<ImageTexture> tw; tw.instance(); tw->create_from_image(i); w_edit->set_texture(tw); w_edit->set_ignore_mouse(false); w_edit->set_custom_minimum_size(Size2(15,256)); w_edit->connect("input_event", this, "_w_input"); c= memnew( Control ); w_edit->add_child(c); c->set_area_as_parent_rect(); c->set_stop_mouse(false); c->set_material(memnew ( CanvasItemMaterial )); args.clear(); args.push_back(1); args.push_back(c); c->connect("draw",this,"_hsv_draw",args); hb_edit->add_child(uv_edit); hb_edit->add_child(memnew( VSeparator )); hb_edit->add_child(w_edit); VBoxContainer *vbl = memnew( VBoxContainer ); add_child(vbl); add_child(memnew( HSeparator )); VBoxContainer *vbr = memnew( VBoxContainer ); add_child(vbr); vbr->set_h_size_flags(SIZE_EXPAND_FILL); const char* lt[4] = {"R","G","B","A"}; for(int i=0;i<4;i++) { HBoxContainer *hbc = memnew( HBoxContainer ); labels[i]=memnew( Label(lt[i]) ); hbc->add_child(labels[i]); scroll[i]=memnew( HSlider ); hbc->add_child(scroll[i]); values[i]=memnew( SpinBox ); scroll[i]->share(values[i]); hbc->add_child(values[i]); scroll[i]->set_min(0); scroll[i]->set_page(0); scroll[i]->set_h_size_flags(SIZE_EXPAND_FILL); scroll[i]->connect("value_changed",this,"_value_changed"); vbr->add_child(hbc); } HBoxContainer *hhb = memnew( HBoxContainer ); btn_mode = memnew( CheckButton ); btn_mode->set_text("RAW Mode"); btn_mode->connect("toggled", this, "set_raw_mode"); hhb->add_child(btn_mode); vbr->add_child(hhb); text_type = memnew( Button ); text_type->set_flat(true); text_type->connect("pressed", this, "_text_type_toggled"); hhb->add_child(text_type); c_text = memnew( LineEdit ); hhb->add_child(c_text); c_text->connect("text_entered",this,"_html_entered"); text_type->set_text("#"); c_text->set_h_size_flags(SIZE_EXPAND_FILL); _update_controls(); //_update_color(); updating=false; uv_material.instance(); Ref<Shader> s_uv = get_shader("uv_editor"); uv_material->set_shader(s_uv); w_material.instance(); Ref<Shader> s_w = get_shader("w_editor"); w_material->set_shader(s_w); uv_edit->set_material(uv_material); w_edit->set_material(w_material); set_color(Color(1,1,1)); i.create(256,20,false,Image::FORMAT_RGB); for (int y=0;y<20;y++) for(int x=0;x<256;x++) if ((x/4+y/4)%2) i.put_pixel(x,y,Color(1,1,1)); else i.put_pixel(x,y,Color(0.6,0.6,0.6)); Ref<ImageTexture> t_smpl; t_smpl.instance(); t_smpl->create_from_image(i); sample->set_texture(t_smpl); HBoxContainer *bbc = memnew( HBoxContainer ); add_child(bbc); preset = memnew( TextureFrame ); bbc->add_child(preset); preset->set_ignore_mouse(false); preset->connect("input_event", this, "_preset_input"); bt_add_preset = memnew ( Button ); bt_add_preset->set_icon(get_icon("add_preset")); bt_add_preset->set_tooltip("Add current color as a preset"); bt_add_preset->connect("pressed", this, "_add_preset_pressed"); bbc->add_child(bt_add_preset); }
Variant::Variant(const Image& p_image) { type=IMAGE; _data._image=memnew( Image(p_image) ); }
Image Texture::copyToImage() const { // Easy case: empty texture if (!m_texture) return Image(); TransientContextLock lock; // Make sure that the current texture binding will be preserved priv::TextureSaver save; // Create an array of pixels std::vector<Uint8> pixels(m_size.x * m_size.y * 4); #ifdef SFML_OPENGL_ES // OpenGL ES doesn't have the glGetTexImage function, the only way to read // from a texture is to bind it to a FBO and use glReadPixels GLuint frameBuffer = 0; glCheck(GLEXT_glGenFramebuffers(1, &frameBuffer)); if (frameBuffer) { GLint previousFrameBuffer; glCheck(glGetIntegerv(GLEXT_GL_FRAMEBUFFER_BINDING, &previousFrameBuffer)); glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_FRAMEBUFFER, frameBuffer)); glCheck(GLEXT_glFramebufferTexture2D(GLEXT_GL_FRAMEBUFFER, GLEXT_GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_texture, 0)); glCheck(glReadPixels(0, 0, m_size.x, m_size.y, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[0])); glCheck(GLEXT_glDeleteFramebuffers(1, &frameBuffer)); glCheck(GLEXT_glBindFramebuffer(GLEXT_GL_FRAMEBUFFER, previousFrameBuffer)); } #else if ((m_size == m_actualSize) && !m_pixelsFlipped) { // Texture is not padded nor flipped, we can use a direct copy glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); glCheck(glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[0])); } else { // Texture is either padded or flipped, we have to use a slower algorithm // All the pixels will first be copied to a temporary array std::vector<Uint8> allPixels(m_actualSize.x * m_actualSize.y * 4); glCheck(glBindTexture(GL_TEXTURE_2D, m_texture)); glCheck(glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, &allPixels[0])); // Then we copy the useful pixels from the temporary array to the final one const Uint8* src = &allPixels[0]; Uint8* dst = &pixels[0]; int srcPitch = m_actualSize.x * 4; int dstPitch = m_size.x * 4; // Handle the case where source pixels are flipped vertically if (m_pixelsFlipped) { src += srcPitch * (m_size.y - 1); srcPitch = -srcPitch; } for (unsigned int i = 0; i < m_size.y; ++i) { std::memcpy(dst, src, dstPitch); src += srcPitch; dst += dstPitch; } } #endif // SFML_OPENGL_ES // Create the image Image image; image.create(m_size.x, m_size.y, &pixels[0]); return image; }
void CPageNavigator::ActivateNewDoc(CAGDoc* pAGDoc, int nDefaultPage) { if (!m_hWnd) return; m_pAGDoc = pAGDoc; m_nPage = -1; // Stop all window updates to avoid flickering SetRedraw(false); // Remove any previously loaded items from the list control DeleteAllItems(); // Detach the image list from the list control RemoveImageList(LVSIL_NORMAL); // Destroy the image list m_ImageList.Destroy(); // Get out if no document to attach to if (!m_pAGDoc) return; ::SendMessage(m_hWnd, LVM_SETBKCOLOR, (WPARAM)0, (LPARAM)(COLORREF)RGB(241,243,245)); // Re-create the image list at the proper size bool bPortrait = m_pAGDoc->IsPortrait(); m_dxIcon = THUMBNAIL_WT; m_dyIcon = THUMBNAIL_HT; bool bOK = !!m_ImageList.Create(m_dxIcon, m_dyIcon, ILC_COLOR24, 1/*nInitial*/, 1/*nGrow*/); // Determine the document appropriate images to add to the image list AGDOCTYPE DocType = m_pAGDoc->GetDocType(); int nImages = 0; int* pidList1 = NULL; int* pidList2 = NULL; m_bIsCard = false; switch (DocType) { case DOC_BANNER: case DOC_BROCHURE: case DOC_BUSINESSCARD: case DOC_CDLABEL: case DOC_ENVELOPE: case DOC_FULLSHEET: case DOC_LABEL: case DOC_POSTCARD: case DOC_IRONON: case DOC_GIFTNAMECARD: case DOC_TRIFOLD: case DOC_HOLIDAYCARD: case DOC_PHOTOCARD: default: { nImages = (bPortrait ? sizeof(idList_PortraitPages1) : sizeof(idList_LandscapePages1)) / sizeof(int); pidList1 = (bPortrait ? idList_PortraitPages1 : idList_LandscapePages1); pidList2 = (bPortrait ? idList_PortraitPages2 : idList_LandscapePages2); m_bIsCard = false; break; } case DOC_HALFCARD: case DOC_QUARTERCARD: case DOC_NOTECARD: case DOC_CDBOOKLET: { nImages = (bPortrait ? sizeof(idList_PortraitCards1) : sizeof(idList_LandscapeCards1)) / sizeof(int); pidList1 = (bPortrait ? idList_PortraitCards1 : idList_LandscapeCards1); pidList2 = (bPortrait ? idList_PortraitCards2 : idList_LandscapeCards2); m_bIsCard = true; break; } } int nPages = m_pAGDoc->GetNumPages(); // Add the document appropriate images to the image list for (int nPass = 0; nPass < 2; nPass++) { for (int i = 0; i < nPages; i++) { int iIcon = (i < nImages ? i : nImages-1); int* pidList = (nPass == 0 ? pidList1 : pidList2); CImage Image(_AtlBaseModule.GetResourceInstance(), pidList[iIcon], "GIF"); HBITMAP hBitmap = Image.GetBitmapHandle(); //j HBITMAP hBitmap = ::LoadBitmap(_AtlBaseModule.GetResourceInstance(), MAKEINTRESOURCE(pidList[iIcon])); if (!m_bIsCard) { CString strNumber; strNumber.Format("%d", i+1); DrawTextOnBitmap(hBitmap, strNumber, 16, RGB(0,0,0), 0, 2); } else if (i >= 4) { CString strNumber; strNumber.Format("+%d", i-3); DrawTextOnBitmap(hBitmap, strNumber, 16, RGB(0,0,0), 0, 2); } m_ImageList.Add(hBitmap); //j ::DeleteObject(hBitmap); } } // Attach the image list to the list control SetImageList(m_ImageList, LVSIL_NORMAL); // Set the icon spacing arbitrarily large to ensure that our icons are placed where we want them SetIconSpacing(1000, 1000); // Compute the spacing required on the top RECT ClientRect = {0,0,0,0}; GetClientRect(&ClientRect); m_yTop = (HEIGHT(ClientRect) - m_dyIcon) / 2; // Compute the spacing required on the left if (!m_bIsCard) m_xLeft = 2; else { int nIcons = 4; //(bPortrait ? 4 : 3); m_xLeft = (WIDTH(ClientRect) - (nIcons * m_dxIcon) - (2 * THUMBNAIL_GAP)) / 2; } // Insert the new list items int xLocation = m_xLeft; for (int i = 0; i < nPages; i++) { InsertItem(i/*nItem*/, "", i/*nImage*/); // shift the thumbnail to desired position int yCorrection = 0; POINT pt = {xLocation, m_yTop + yCorrection}; SetItemPosition(i, pt); xLocation += (m_dxIcon + THUMBNAIL_GAP); } SelectPage(nDefaultPage, true/*bSetState*/); SetRedraw(true); }
void Scene::load(const filesystem::path &file) { size_t i; std::string message; if(!filesystem::exists(file)) throw std::runtime_error(std::string("File does not exists:") + file.string()); this->collada = new DAE; message = "Start loading COLLADA DOM from "; message += file.string(); this->scene_graph.printStatusMessage(message); this->dae_file_name = file; // load with full path domCOLLADA *dom = this->collada->open(file.string()); if(!dom) { delete this->collada; throw std::runtime_error(std::string("Error loading the COLLADA file ") + file.string() + ". Make sure it is COLLADA 1.4 or greater"); } this->scene_graph.printStatusMessage("Begin conditioning"); //if(kmzcleanup(this->collada, true)) // std::cout << " kmzcleanup complete\n"; int res = 0; this->scene_graph.printStatusMessage(" triangulating"); res = triangulate(this->collada); if(res) { std::ostringstream os; os << " triangulation returns error " << res << std::ends; this->scene_graph.printStatusMessage(os.str()); } else this->scene_graph.printStatusMessage(std::string(" triangulation complete")); /* this->scene_graph.printStatusMessage(std::string(" deindexing")); res = deindex(this->collada); if(res) { std::ostringstream os; os << " deindexer returns error " << res << std::ends; this->scene_graph.printStatusMessage(os.str()); } else this->scene_graph.printStatusMessage(std::string(" deindexing complete")); */ this->scene_graph.printStatusMessage(std::string("Finish conditioning.")); // Need to get the asset tag which will determine what vector x y or z is up. Typically y or z. domAssetRef asset = dom->getAsset(); this->scene_graph.printStatusMessage(std::string("File information:")); const domAsset::domContributor_Array &contributors = asset->getContributor_array(); for(i = 0; i < contributors.getCount(); ++i) { domAsset::domContributorRef c = contributors.get(i); this->scene_graph.printStatusMessage(std::string(" author:") + c->getAuthor()->getCharData()); this->scene_graph.printStatusMessage(std::string(" authoring tool:") + c->getAuthoring_tool()->getCharData()); } if(asset->getCreated()) this->scene_graph.printStatusMessage(std::string(" created: ") + asset->getCreated()->getCharData()); if(asset->getModified()) this->scene_graph.printStatusMessage(std::string(" modified: ") + asset->getModified()->getCharData()); if(asset->getUnit()) { std::ostringstream os; os << " units: " << asset->getUnit()->getMeter() << " meter (" << asset->getUnit()->getAttribute("name") << ")"; os << std::ends; this->scene_graph.printStatusMessage(os.str()); } if(asset->getUp_axis()) { domAsset::domUp_axis *up = dom->getAsset()->getUp_axis(); if(up) this->up_axis = up->getValue(); switch(this->up_axis) { case UPAXISTYPE_X_UP: this->scene_graph.printStatusMessage(std::string(" X axis is UP axis.")); break; case UPAXISTYPE_Y_UP: this->scene_graph.printStatusMessage(std::string(" Y axis is UP axis.")); break; case UPAXISTYPE_Z_UP: this->scene_graph.printStatusMessage(std::string(" Z axis is UP axis.")); break; default: break; } } this->scene_graph.printStatusMessage("Building libraries"); // Load the image for the default texture. const Image::ImageID image_key = {"default", ""}; bool inserted; Image::ImageList::iterator img_iter; tie(img_iter, inserted) = this->scene_graph.all_images.insert(std::make_pair(image_key, Image())); Image &img = img_iter->second; img.image = IMG_Load("default.tga"); if(!img.image) { scene_graph.all_images.erase(image_key); this->scene_graph.printStatusMessage("Can not load default.tga for the default texture."); } this->scene_graph.printStatusMessage(" Load image libraries"); const domLibrary_images_Array &ia = dom->getLibrary_images_array(); for(i = 0; i < ia.getCount(); ++i) this->readImageLibrary(ia[i]); this->scene_graph.printStatusMessage(" Load effect libraries"); const domLibrary_effects_Array &ea = dom->getLibrary_effects_array(); for(i = 0; i < ea.getCount(); i++) this->readEffectLibrary(ea[i]); this->scene_graph.printStatusMessage(" Load material libraries"); const domLibrary_materials_Array &ma = dom->getLibrary_materials_array(); for(i = 0; i < ma.getCount(); i++) this->readMaterialLibrary(ma[i]); this->scene_graph.printStatusMessage(" Load animation libraries"); const domLibrary_animations_Array &aa = dom->getLibrary_animations_array(); for(i = 0; i < aa.getCount(); i++) this->readAnimationLibrary(aa[i]); // Find the scene we want domCOLLADA::domSceneRef domScene = dom->getScene(); daeElement* defaultScene = NULL; if (domScene) if (domScene->getInstance_visual_scene()) if (domScene->getInstance_visual_scene()) defaultScene = domScene->getInstance_visual_scene()->getUrl().getElement(); if(defaultScene) this->readScene((domVisual_scene*)defaultScene); // If no lights were loaded, we need to make one so the scene won't be totally black if(this->scene_graph.all_lights.empty()) { // new Light this->scene_graph.printStatusMessage("Scene: no lights were loaded. Creating a default light"); const Light::LightID light_key = {"no_light_in_scene_default_light", dom->getDocumentURI()->getURI()}; bool inserted; Light::LightList::iterator light; tie(light, inserted) = scene_graph.all_lights.insert(std::make_pair(light_key, Light())); Light &default_light = light->second; default_light.type = Light::DIRECTIONAL; default_light.color = Color4f(1, 1, 1, 1); // new Node this->scene_graph.printStatusMessage("Scene: no instance_light found creating a node with an instance"); this->scene_graph.insertNode(this->scene_graph.root, "no_light_in_scene_default_node", "no_light_in_scene_default_node", "NONE"); // Read node transformations Node ¤t_node = *this->scene_graph.all_nodes.find("no_light_in_scene_default_node"); current_node.transformations.push_back(Transformation()); Transformation &transform = current_node.transformations.at(current_node.transformations.size() - 1); transform.type = Transformation::Translate; const Vector3 trans(-40.0, 40.0, 0.0); transform.transform = Transform3::translation(trans); // new InstanceLight InstanceLight instance_light; instance_light.abstract_light_ref = light->first; current_node.instance_lights.push_back(instance_light); this->scene_graph.light_nodes.push_back("no_light_in_scene_default_node"); } if(!this->scene_graph.all_cameras.empty()) { // Search for the first camera node Node::NodeMap &all_nodes = this->scene_graph.all_nodes; for(int n = 0; n < all_nodes.size(); ++n) { Node *node = all_nodes.getAtIndex(n); if(node->instance_cameras.size() > 0) { this->scene_graph.active_camera_info = std::make_pair(node, &(node->instance_cameras[0])); break; } } } else { this->scene_graph.printStatusMessage( "Scene: create a default camera and it is the first camera to use"); // new Camera const Camera::CameraID camera_key = {"no_camera_in_scene_default_camera", dom->getDocumentURI()->getURI()}; // Make the camera bool inserted; Camera::CameraList::iterator camera; tie(camera, inserted) = this->scene_graph.all_cameras.insert(std::make_pair(camera_key, Camera())); Camera &default_camera = camera->second; default_camera.Xfov = 45.0f; default_camera.Yfov = 45.0f; this->scene_graph.printStatusMessage( "Scene: creating a node with an instance of default camera"); // new Node this->scene_graph.insertNode(this->scene_graph.root, "no_camera_in_scene_default_node", "no_camera_in_scene_default_node", "NONE"); // Read node transformations Node ¤t_node = *this->scene_graph.all_nodes.find("no_camera_in_scene_default_node"); // Calculate approximate bounding box for the model Vector3 max(0,0,0); Vector3 min(0,0,0); for(Geometry::GeometryList::const_iterator g = this->scene_graph.all_geometries.begin(); g != this->scene_graph.all_geometries.end(); ++g) { // Points are stored as x/y/z tripples within this array for(Geometry::PointList::const_iterator p = g->second.points.begin(); p != g->second.points.end(); ++p) { // X if(*p > max.getX()) max.setX(*p); else if(*p < min.getX()) min.setX(*p); // Y ++p; if(*p > max.getY()) max.setY(*p); else if(*p < min.getY()) min.setY(*p); // Z ++p; if(*p > max.getZ()) max.setZ(*p); else if(*p < min.getZ()) min.setZ(*p); } } default_camera.ZNear = 1.0f; default_camera.ZFar = 1000.0f; current_node.transformations.push_back(Transformation()); Transformation &transform = current_node.transformations.at(current_node.transformations.size() - 1); transform.type = Transformation::LookAt; const Point3 eyePos(max.getX() * 0.5f, max.getY() * 0.5f, max.getZ() * 0.5f); const Point3 lookAtPos(min.getX(), min.getY(), min.getZ()); Vector3 upVec; upVec.setY(0); if(this->up_axis == UPAXISTYPE_Z_UP) { upVec.setX(0); upVec.setZ(1.0f); } else if(this->up_axis == UPAXISTYPE_X_UP) { upVec.setX(1.0f); upVec.setZ(0); } // Store transformation transform.matrix = inverse(Matrix4::lookAt(eyePos, lookAtPos, upVec)); current_node.local_matrix *= transform.matrix; // new InstanceCamera InstanceCamera instance_camera; instance_camera.abstract_camera_ref = camera->first; current_node.instance_cameras.push_back(instance_camera); this->scene_graph.active_camera_info = std::make_pair(¤t_node, &(current_node.instance_cameras.at(current_node.instance_cameras.size() - 1))); } this->scene_graph.printStatusMessage(std::string("COLLADA_DOM runtime database initialized from ") + file.filename().string()); }
Doom3TextureManager::ImageID Doom3TextureManager::loadTexture(const char* textureName) { /* Check if the texture name has the .tga extension: */ const char* extPtr=0; for(const char* tnPtr=textureName; *tnPtr!='\0'; ++tnPtr) if(*tnPtr=='.') extPtr=tnPtr; std::string tempTextureName=textureName; if(extPtr==0||strcasecmp(extPtr,".tga")!=0) { tempTextureName=textureName+std::string(".tga"); textureName=tempTextureName.c_str(); } /* Check if the requested texture is already there: */ ImageID imageID=imageTree.findLeaf(textureName); if(imageID.isValid()) return imageID; /* Store a new image structure in the image tree: */ imageID=imageTree.insertLeaf(textureName,Image()); /* Create a texture image: */ Image& image=imageTree.getLeafValue(imageID); image.textureIndex=numTextures; ++numTextures; /* Check for built-in texture names: */ if(textureName[0]=='_') { /* Determine the fill color value: */ Images::RGBAImage::Color imageColor; if(strcasecmp(textureName,"_black.tga")==0) imageColor=Images::RGBAImage::Color(0,0,0,255); else if(strcasecmp(textureName,"_white.tga")==0) imageColor=Images::RGBAImage::Color(255,255,255,255); else if(strcasecmp(textureName,"_flat.tga")==0) imageColor=Images::RGBAImage::Color(128,128,255,255); else imageColor=Images::RGBAImage::Color(255,0,255,255); /* Initialize the texture image: */ image.image=Images::RGBAImage(2,2); image.image.clear(imageColor); } else { try { /* Load the texture image file: */ size_t imageSize; unsigned char* imageData=fileManager.readFile(textureName,imageSize); /* Read the image file: */ Misc::MemMappedFile imageFile(imageData,imageSize,Misc::MemMappedFile::LittleEndian); Images::TargaImageFileReader<Misc::MemMappedFile> targaReader(imageFile); /* Initialize the texture image: */ image.image=targaReader.readImage<Images::RGBAImage>(); } catch(Doom3FileManager::ReadError err) { /* Initialize the texture image: */ image.image=Images::RGBAImage(2,2); image.image.clear(Images::RGBAImage::Color(255,0,255,255)); } } /* Return the image ID: */ return imageID; }
void VUINodeImage::SetColor( VColorRef color ) { for (int i=0;i<VWindowBase::STATE_COUNT;i++) Image().m_States[i].SetColor( color ); }
Doom3TextureManager::ImageID Doom3TextureManager::computeAdd(const Doom3TextureManager::ImageID& source1,const Doom3TextureManager::ImageID& source2) { /* Get a reference to the source images: */ const Images::RGBAImage& source1Image=imageTree.getLeafValue(source1).image; Images::RGBAImage source2Image=imageTree.getLeafValue(source2).image; if(source1Image.getWidth()!=source2Image.getWidth()||source1Image.getHeight()!=source2Image.getHeight()) { /* Resample the second image to match the first image's size: */ source2Image.resize(source1Image.getWidth(),source1Image.getHeight()); } /* Store a new image structure in the image tree: */ ImageID resultId=imageTree.insertLeaf(Misc::stringPrintf("/_computedTextures/tex%06d",numTextures).c_str(),Image()); Image& result=imageTree.getLeafValue(resultId); Images::RGBAImage& resultImage=result.image; result.textureIndex=numTextures; ++numTextures; /* Compute the result image's pixels: */ resultImage=Images::RGBAImage(source1Image.getWidth(),source1Image.getHeight()); for(unsigned int y=0; y<resultImage.getHeight(); ++y) { const Images::RGBAImage::Color* source1Row=source1Image.getPixelRow(y); const Images::RGBAImage::Color* source2Row=source2Image.getPixelRow(y); Images::RGBAImage::Color* destRow=resultImage.modifyPixelRow(y); for(unsigned int x=0; x<resultImage.getWidth(); ++x) { for(int i=0; i<3; ++i) { unsigned int sum=(unsigned int)(source1Row[x][i])+(unsigned int)(source2Row[x][i]); if(sum>=255) destRow[x][i]=GLubyte(255); else destRow[x][i]=GLubyte(sum); } } } /* Return the result image ID: */ return resultId; }
VColorRef VUINodeImage::GetColor() { return Image().m_States[NORMAL].GetColor(); }
Doom3TextureManager::ImageID Doom3TextureManager::computeInvertAlpha(const Doom3TextureManager::ImageID& source) { /* Get a reference to the source image: */ const Images::RGBAImage& sourceImage=imageTree.getLeafValue(source).image; /* Store a new image structure in the image tree: */ ImageID resultId=imageTree.insertLeaf(Misc::stringPrintf("/_computedTextures/tex%06d",numTextures).c_str(),Image()); Image& result=imageTree.getLeafValue(resultId); Images::RGBAImage& resultImage=result.image; result.textureIndex=numTextures; ++numTextures; /* Compute the result image's pixels: */ resultImage=Images::RGBAImage(sourceImage.getWidth(),sourceImage.getHeight()); for(unsigned int y=0; y<resultImage.getHeight(); ++y) { const Images::RGBAImage::Color* sourceRow=sourceImage.getPixelRow(y); Images::RGBAImage::Color* destRow=resultImage.modifyPixelRow(y); for(unsigned int x=0; x<resultImage.getWidth(); ++x) { for(int i=0; i<3; ++i) destRow[x][i]=sourceRow[x][i]; destRow[x][3]=GLubyte(255)-destRow[x][3]; } } /* Return the result image ID: */ return resultId; }
/// Replaces both the image and the bitmap. void ThemeBase::ReplaceImage( int iIndex, wxImage * pImage ) { Image( iIndex ) = *pImage; Bitmap( iIndex ) = wxBitmap( *pImage ); }