Пример #1
0
/**
 * Shows the "New Sprite" dialog.
 */
void NewFileCommand::onExecute(Context* context)
{
  Preferences& pref = Preferences::instance();
  int ncolors = get_default_palette()->size();
  char buf[1024];
  app::Color bg_table[] = {
    app::Color::fromMask(),
    app::Color::fromRgb(255, 255, 255),
    app::Color::fromRgb(0, 0, 0),
  };

  // Load the window widget
  app::gen::NewSprite window;

  // Default values: Indexed, 320x240, Background color
  PixelFormat format = pref.newFile.colorMode();
  // Invalid format in config file.
  if (format != IMAGE_RGB &&
      format != IMAGE_INDEXED &&
      format != IMAGE_GRAYSCALE) {
    format = IMAGE_INDEXED;
  }
  int w = pref.newFile.width();
  int h = pref.newFile.height();
  int bg = pref.newFile.backgroundColor();
  bg = MID(0, bg, 2);

  // If the clipboard contains an image, we can show the size of the
  // clipboard as default image size.
  gfx::Size clipboardSize;
  if (clipboard::get_image_size(clipboardSize)) {
    w = clipboardSize.w;
    h = clipboardSize.h;
  }

  window.width()->setTextf("%d", MAX(1, w));
  window.height()->setTextf("%d", MAX(1, h));

  // Select image-type
  window.colorMode()->setSelectedItem(format);

  // Select background color
  window.bgColor()->setSelectedItem(bg);

  // Advance options
  bool advanced = pref.newFile.advanced();
  window.advancedCheck()->setSelected(advanced);
  window.advancedCheck()->Click.connect(
    base::Bind<void>(
      [&]{
        gfx::Rect bounds = window.bounds();
        window.advanced()->setVisible(window.advancedCheck()->isSelected());
        window.setBounds(gfx::Rect(window.bounds().origin(),
                                   window.sizeHint()));
        window.layout();

        window.manager()->invalidateRect(bounds);
      }));
  window.advanced()->setVisible(advanced);
  if (advanced)
    window.pixelRatio()->setValue(pref.newFile.pixelRatio());
  else
    window.pixelRatio()->setValue("1:1");

  // Open the window
  window.openWindowInForeground();

  if (window.closer() == window.okButton()) {
    bool ok = false;

    // Get the options
    format = (doc::PixelFormat)window.colorMode()->selectedItem();
    w = window.width()->textInt();
    h = window.height()->textInt();
    bg = window.bgColor()->selectedItem();

    static_assert(IMAGE_RGB == 0, "RGB pixel format should be 0");
    static_assert(IMAGE_INDEXED == 2, "Indexed pixel format should be 2");

    format = MID(IMAGE_RGB, format, IMAGE_INDEXED);
    w = MID(1, w, DOC_SPRITE_MAX_WIDTH);
    h = MID(1, h, DOC_SPRITE_MAX_HEIGHT);
    bg = MID(0, bg, 2);

    // Select the color
    app::Color color = app::Color::fromMask();

    if (bg >= 0 && bg <= 3) {
      color = bg_table[bg];
      ok = true;
    }

    if (ok) {
      // Save the configuration
      pref.newFile.width(w);
      pref.newFile.height(h);
      pref.newFile.colorMode(format);
      pref.newFile.backgroundColor(bg);
      pref.newFile.advanced(window.advancedCheck()->isSelected());
      pref.newFile.pixelRatio(window.pixelRatio()->getValue());

      // Create the new sprite
      ASSERT(format == IMAGE_RGB || format == IMAGE_GRAYSCALE || format == IMAGE_INDEXED);
      ASSERT(w > 0 && h > 0);

      std::unique_ptr<Sprite> sprite(Sprite::createBasicSprite(format, w, h, ncolors));

      if (window.advancedCheck()->isSelected()) {
        sprite->setPixelRatio(
          base::convert_to<PixelRatio>(window.pixelRatio()->getValue()));
      }

      if (sprite->pixelFormat() != IMAGE_GRAYSCALE)
        get_default_palette()->copyColorsTo(sprite->palette(frame_t(0)));

      // If the background color isn't transparent, we have to
      // convert the `Layer 1' in a `Background'
      if (color.getType() != app::Color::MaskType) {
        Layer* layer = sprite->root()->firstLayer();

        if (layer && layer->isImage()) {
          LayerImage* layerImage = static_cast<LayerImage*>(layer);
          layerImage->configureAsBackground();

          Image* image = layerImage->cel(frame_t(0))->image();

          // TODO Replace this adding a new parameter to color utils
          Palette oldPal = *get_current_palette();
          set_current_palette(get_default_palette(), false);

          doc::clear_image(image,
            color_utils::color_for_target(color,
              ColorTarget(
                ColorTarget::BackgroundLayer,
                sprite->pixelFormat(),
                sprite->transparentColor())));

          set_current_palette(&oldPal, false);
        }
      }

      // Show the sprite to the user
      std::unique_ptr<Doc> doc(new Doc(sprite.get()));
      sprite.release();
      sprintf(buf, "Sprite-%04d", ++_sprite_counter);
      doc->setFilename(buf);
      doc->setContext(context);
      doc.release();
    }
  }
}
Пример #2
0
bool TmxFile2D::LoadTileSet(const XMLElement& element)
{
    int firstgid = element.GetInt("firstgid");

    XMLElement tileSetElem;
    if (element.HasAttribute("source"))
    {
        String source = element.GetAttribute("source");
        HashMap<String, SharedPtr<XMLFile> >::Iterator i = tsxXMLFiles_.Find(source);
        if (i == tsxXMLFiles_.End())
        {
            SharedPtr<XMLFile> tsxXMLFile = LoadTSXFile(source);
            if (!tsxXMLFile)
                return false;

            // Add to napping to avoid release
            tsxXMLFiles_[source] = tsxXMLFile;

            tileSetElem = tsxXMLFile->GetRoot("tileset");
        }
        else
            tileSetElem = i->second_->GetRoot("tileset");
    }
    else
        tileSetElem = element;

    XMLElement imageElem = tileSetElem.GetChild("image");
    String textureFilePath = GetParentPath(GetName()) + imageElem.GetAttribute("source");
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    SharedPtr<Texture2D> texture(cache->GetResource<Texture2D>(textureFilePath));
    if (!texture)
    {
        LOGERROR("Could not load texture " + textureFilePath);
        return false;
    }

    tileSetTextures_.Push(texture);

    int tileWidth = tileSetElem.GetInt("tilewidth");
    int tileHeight = tileSetElem.GetInt("tileheight");
    int spacing = tileSetElem.GetInt("spacing");
    int margin = tileSetElem.GetInt("margin");
    int imageWidth = imageElem.GetInt("width");
    int imageHeight = imageElem.GetInt("height");

    // Set hot spot at left bottom
    Vector2 hotSpot(0.0f, 0.0f);
    if (tileSetElem.HasChild("tileoffset"))
    {
        XMLElement offsetElem = tileSetElem.GetChild("tileoffset");
        hotSpot.x_ += offsetElem.GetFloat("x") / (float)tileWidth;
        hotSpot.y_ += offsetElem.GetFloat("y") / (float)tileHeight;
    }

    int gid = firstgid;
    for (int y = margin; y + tileHeight <= imageHeight - margin; y += tileHeight + spacing)
    {
        for (int x = margin; x + tileWidth <= imageWidth - margin; x += tileWidth + spacing)
        {
            SharedPtr<Sprite2D> sprite(new Sprite2D(context_));
            sprite->SetTexture(texture);
            sprite->SetRectangle(IntRect(x, y, x + tileWidth, y + tileHeight));
            sprite->SetHotSpot(hotSpot);

            gidToSpriteMapping_[gid++] = sprite;
        }
    }

    for (XMLElement tileElem = tileSetElem.GetChild("tile"); tileElem; tileElem = tileElem.GetNext("tile"))
    {
        if (tileElem.HasChild("properties"))
        {
            SharedPtr<PropertySet2D> propertySet(new PropertySet2D());
            propertySet->Load(tileElem.GetChild("properties"));
            gidToPropertySetMapping_[firstgid + tileElem.GetInt("id")] = propertySet;
        }
    }

    return true;
}
void NarratorVolumeSlider::draw(sf::RenderTarget& target, sf::RenderStates states) const{
	Button::draw(target,states);
	sf::Sprite sprite(*mTexture);
	sprite.setPosition(NarratorVolumeSliderSpecs::get().mSliderX*target.getSize().x+(mVolume*NarratorVolumeSliderSpecs::get().mStepSize),NarratorVolumeSliderSpecs::get().mSliderY*target.getSize().y);
	WindowManager::get().getRenderWindow()->draw(sprite);
}
Пример #4
0
int main()
{
    WORKING_DIR=SDL_GetBasePath();
    WORKING_DIR=WORKING_DIR.substr(0,WORKING_DIR.find_last_of("/\\"));
    WORKING_DIR=WORKING_DIR.substr(0,WORKING_DIR.find_last_of("/\\"));
    WORKING_DIR=WORKING_DIR.substr(0,WORKING_DIR.find_last_of("/\\"));
#ifdef __gnu_linux__
    WORKING_DIR+="/";
#elif __WIN32
    WORKING_DIR+="\\";
#endif
    std::cout<< WORKING_DIR<<std::endl;

    SDL_Window *mainwindow; /* Our window handle */
    SDL_GLContext maincontext; /* Our opengl context handle */
    Mix_Chunk *pong = NULL;
    Mix_Chunk *pong2 = NULL;
    Mix_Chunk *pong3 = NULL;
    if( SDL_Init( SDL_INIT_VIDEO| SDL_INIT_AUDIO ) < 0 )
    {
        sdldie("SDL could not initialize! SDL Error: %s\n");
    }
    else
    {
        //Use OpenGL 3.3 core
        SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
        SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );
        SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );

        //Create window
        mainwindow = SDL_CreateWindow( "pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenWidth, screenHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN |SDL_WINDOW_RESIZABLE );
        if( mainwindow == NULL )
        {
            sdldie("Unable to create window");
        }
        else
        {
            //Create context
            maincontext = SDL_GL_CreateContext( mainwindow );
            if( maincontext == NULL ){
                sdldie("OpenGL context could not be created! SDL Error: %s\n");
            }
            else
            {
                //Initialize GLEW
                glewExperimental = GL_TRUE;
                GLenum glewError = glewInit();
                if( glewError != GLEW_OK )
                {
                    std::cout<<"Error initializing GLEW! %s\n"<<glewGetErrorString( glewError );
                }

                //Use Vsync
                if( SDL_GL_SetSwapInterval( 1 ) < 0 )
                {
                    std::cout<<"Warning: Unable to set VSync! SDL Error: %s\n"<<SDL_GetError();
                }
                SDL_DisplayMode current;
                int should_be_zero = SDL_GetCurrentDisplayMode(0, &current); //@HACK:should check for multiple monitors
                if(should_be_zero != 0)
                  sdldie("Could not get display mode for video display");
                screenWidth=(3.0f/4.0f)*current.w;
                screenHeight=(3.0f/4.0f)*current.h;
                (*(int*)(&originalScreenHeight))=screenHeight;
                (*(int*)(&originalScreenWidth))=screenWidth;
            }
        }
    }
    //Initialize SDL_mixer
    if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) {
        std::cout<<"SDL_mixer could not initialize! SDL_mixer Error: "<<Mix_GetError();
        return 1;
    }
     //Load sound effects
    pong = Mix_LoadWAV(WORKING_DIR_FILE("assets/sounds/pong.wav"));
    if( pong == NULL ) {
        std::cout<< "Failed to load scratch sound effect! SDL_mixer Error: "<<Mix_GetError();
        return 1;
    }
    pong2 = Mix_LoadWAV(WORKING_DIR_FILE("assets/sounds/pong2.wav"));
    if( pong2 == NULL ) {
        std::cout<< "Failed to load scratch sound effect! SDL_mixer Error: "<<Mix_GetError();
        return 1;
    }
    pong3 = Mix_LoadWAV(WORKING_DIR_FILE("assets/sounds/pong3.wav"));
    if( pong3 == NULL ) {
        std::cout<< "Failed to load scratch sound effect! SDL_mixer Error: "<<Mix_GetError();
        return 1;
    }

    glEnable(GL_DEPTH_TEST);
    glViewport(0, 0, screenWidth, screenHeight);

    /* Clear our buffer with a red background */
    glClearColor ( 1.0, 0.0, 0.0, 1.0 );
    glClear ( GL_COLOR_BUFFER_BIT );
    /* Swap our back buffer to the front */
    SDL_GL_SwapWindow(mainwindow);
    /* Wait 2 seconds */
    SDL_Delay(100);

    /* Same as above, but green */
    glClearColor ( 0.0, 1.0, 0.0, 1.0 );
    glClear ( GL_COLOR_BUFFER_BIT );
    SDL_GL_SwapWindow(mainwindow);
    SDL_Delay(100);

    /* Same as above, but blue */
    glClearColor ( 0.0, 0.0, 1.0, 1.0 );
    glClear ( GL_COLOR_BUFFER_BIT );
    SDL_GL_SwapWindow(mainwindow);
    SDL_Delay(100);


    GLfloat vertices[] = {
         0.5f,  0.5f, 0.0f,  // Top Right
         0.5f, -0.5f, 0.0f,  // Bottom Right
        -0.5f, -0.5f, 0.0f,  // Bottom Left
        -0.5f,  0.5f, 0.0f,   // Top Left
    };
    GLuint indices[] = {  // Note that we start from 0!
        0, 1, 3,  // First Triangle
        1, 2, 3   // Second Triangle
    };

    std::vector<Vertex> vertices2;
    std::vector<GLuint> indices2;
    {
        for(unsigned int i=0;i<(sizeof(vertices)/sizeof(vertices[0]));i+=3){
            Vertex aux;
            aux.position={vertices[i+0],vertices[i+1],vertices[i+2]};
            vertices2.push_back(aux);
        }
        for(unsigned int i=0;i<(sizeof(indices)/sizeof(indices[0]));i++){
            indices2.push_back(indices[i]);
        }

    }
    Sprite sprite(vertices2,indices2);

    GLfloat quadVertices[] = {   // Vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates.
        // Positions   // TexCoords
        -1.0f,  1.0f,  0.0f, 1.0f,
        -1.0f, -1.0f,  0.0f, 0.0f,
         1.0f, -1.0f,  1.0f, 0.0f,

        -1.0f,  1.0f,  0.0f, 1.0f,
         1.0f, -1.0f,  1.0f, 0.0f,
         1.0f,  1.0f,  1.0f, 1.0f
    };

    // Setup cube VAO
    GLuint quadVAO, quadVBO;
    glGenVertexArrays(1, &quadVAO);
    glGenBuffers(1, &quadVBO);
    glBindVertexArray(quadVAO);
        glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
            glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices, GL_STATIC_DRAW);
            glEnableVertexAttribArray(0);
            glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
            glEnableVertexAttribArray(1);
            glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat)));
    glBindVertexArray(0);


    unsigned int points_p1=0,points_p2=0;
    bool first_point_p1=true,first_point_p2=true;

    GameObject player1(&sprite,{0.0f,2.0f});
    GameObject player2(&sprite,{0.0f,2.0f});
    GameObject ball(&sprite,{0.0f,0.0f});
    Entity roof(&sprite);
    Entity floor(&sprite);
    GameObject leftwall(&sprite,{0.0f,0.0f});
    GameObject rightwall(&sprite,{0.0f,0.0f});
    {
        player1.entity.setPos({-0.95f,0.0f});
        player2.entity.setPos({0.95f,0.0f});
        ball.entity.setPos({0.0f,8.0f});

        roof.setPos({-1.0f,1.10f});
        floor.setPos({-1.0f,-1.10f});
        roof.scale({4.0f,1.0f});
        floor.scale({4.0f,1.0f});

        leftwall.entity.setPos({-1.0f,0.0f});
        rightwall.entity.setPos({1.0f,0.0f});
        leftwall.entity.scale({0.025f,2.0f});
        rightwall.entity.scale({0.025f,2.0f});

        player1.entity.scale({0.025f, 0.49f});
        player2.entity.scale({0.025f, 0.49f});
        ball.entity.scale({0.0625f,0.0625f});
        ball.entity.order(SCALE,ROTATE,TRANSLATE);


    }

    std::vector<CollisionChecker> collisions;
    {
        collisions.push_back(CollisionChecker(&player1.entity,&roof));
        collisions.push_back(CollisionChecker(&player1.entity,&floor));
        collisions.push_back(CollisionChecker(&player2.entity,&roof));
        collisions.push_back(CollisionChecker(&player2.entity,&floor));
    }


    CollisionChecker ball_floor(&ball.entity,&floor);
    CollisionChecker ball_roof(&ball.entity,&roof);
    CollisionChecker ball_p1(&ball.entity,&player1.entity);
    CollisionChecker ball_p2(&ball.entity,&player2.entity);
    CollisionChecker ball_leftwall(&ball.entity,&leftwall.entity);
    CollisionChecker ball_rightwall(&ball.entity,&rightwall.entity);

    SDL_StartTextInput();
    bool quit = false;
    bool started=false;
    glm::vec2 p1_speed_gain(0.0f,0.0f);
    glm::vec2 p2_speed_gain(0.0f,0.0f);
    unsigned int i=0;
    Uint32 lastFrame=0;
    Uint32 deltaTime=0;
    float framerate=0.0f;
    float dt;


    framebuffer fb(originalScreenWidth,originalScreenHeight);
    Shader shader(WORKING_DIR_FILE("assets/shaders/shader.vert"),WORKING_DIR_FILE("assets/shaders/shader.frag"));
    Shader fb_shader(WORKING_DIR_FILE("assets/shaders/framebuffer_shader.vert"),WORKING_DIR_FILE("assets/shaders/framebuffer_shader.frag"));
    while(!quit)
    {
        SDL_PumpEvents();
        Uint32 currentFrame =            SDL_GetTicks();//miliseconds
        deltaTime           =  currentFrame - lastFrame;
        lastFrame           =              currentFrame;
        dt                  =         deltaTime/1000.0f;
        framerate          +=         1000.0f/deltaTime;

        p1_speed_gain={0.0f,0.0f};
        p2_speed_gain={0.0f,0.0f};
        {
            const Uint8 *keystates =                                     SDL_GetKeyboardState( NULL );
            quit                   = keystates[SDL_GetScancodeFromKey(SDLK_q)] || SDL_QuitRequested();
            started                =         started || keystates[SDL_GetScancodeFromKey(SDLK_SPACE)];
            if(started){
                if(keystates[SDL_GetScancodeFromKey(SDLK_w   )])
                {
                    player1.move( dt );
                    p1_speed_gain={ 0.0f , 1.0f };
                }
                if(keystates[SDL_GetScancodeFromKey(SDLK_s   )])
                {
                    player1.move(-dt );
                    p1_speed_gain={ 0.0f ,-1.0f };
                }
                if(keystates[SDL_GetScancodeFromKey(SDLK_UP  )])
                {
                    player2.move( dt );
                    p2_speed_gain={ 0.0f , 1.0f };
                }
                if(keystates[SDL_GetScancodeFromKey(SDLK_DOWN)])
                {
                    player2.move(-dt );
                    p2_speed_gain={ 0.0f ,-1.0f };
                }
                if(keystates[SDL_GetScancodeFromKey(SDLK_j)])
                {
                    player1.entity.rotate(15.0f );
                }

                do_ball_movement(ball,dt);
            }

        }
        {
            unsigned int size=collisions.size();
            for(unsigned int i=0;i<size;i++)
            {
                if(collisions[i].checkCollision())
                    handleCollision(collisions[i]);
            }
        }
        {
            glm::vec3 pos=ball.entity.position;
            glm::vec3 oldpos=ball.entity.oldPosition;
            if(ball_floor.checkCollision()){
                handleCollision(ball_floor);
                ball.speed=glm::normalize(glm::reflect(glm::vec2(pos.x-oldpos.x,pos.y-oldpos.y),glm::vec2(0.0f,1.0f)))*glm::length(ball.speed);
                Mix_PlayChannel( -1, pong2, 0 );
            }
            if(ball_roof.checkCollision()){
                handleCollision(ball_roof);
                ball.speed=glm::normalize(glm::reflect(glm::vec2(pos.x-oldpos.x,pos.y-oldpos.y),glm::vec2(0.0f,-1.0f)))*glm::length(ball.speed);
                Mix_PlayChannel( -1, pong2, 0 );
            }
            if(ball_p1.checkCollision()){
                handleCollision(ball_p1);
                ball.speed=glm::normalize(glm::reflect(glm::vec2(pos.x-oldpos.x,pos.y-oldpos.y),glm::vec2(1.0f,0.0f)) + p1_speed_gain)
                        *
                        (glm::length(ball.speed)+glm::length(p1_speed_gain));
                Mix_PlayChannel( -1, pong, 0 );
            }
            if(ball_p2.checkCollision()){
                handleCollision(ball_p2);
                ball.speed=glm::normalize(glm::reflect(glm::vec2(pos.x-oldpos.x,pos.y-oldpos.y),glm::vec2(-1.0f,0.0f)) + p2_speed_gain)
                        *
                        (glm::length(ball.speed)+glm::length(p2_speed_gain));
                Mix_PlayChannel( -1, pong, 0 );
            }

            if(ball_leftwall.checkCollision()){
                points_p2++;
                ball.entity.setPos({0.0f,8.0f});//scale adjusted due the order it uses...
                ball.speed={0.0f,0.0f};
                Mix_PlayChannel( -1, pong3, 0 );
            }
            if(ball_rightwall.checkCollision()){
                points_p1++;
                ball.entity.setPos({0.0f,8.0f});
                ball.speed={0.0f,0.0f};
                Mix_PlayChannel( -1, pong3, 0 );
            }
            if(((ball.speed.y/ball.speed.x)>3.0f) || ((ball.speed.y/ball.speed.x)<-3.0f)){
                ball.speed.y/=2.0f;
                ball.speed.x*=4.0f;
            }
        }
        if(i==100){
            i=0;
            framerate/=100.0f;
            std::cout<<framerate<<std::endl;
            std::cout<<points_p1<<'-'<<points_p2<<std::endl;
            framerate=0.0f;
        }
        i+=1;
        shader.Use();
            fb.bind();
                glViewport(0,0,originalScreenWidth,originalScreenHeight);
                glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
                glEnable(GL_DEPTH_TEST);
                glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

                glm::mat4 projection;//= glm::ortho(-1.0f,1.0f,-1.0f,1.0f,0.0f,1.0f);
                GLint projection_uniform=glGetUniformLocation(shader.Program, "projection");
                glUniformMatrix4fv(projection_uniform, 1, GL_FALSE, glm::value_ptr(projection));


                glm::vec2 position;
                position=glm::vec2(-3.0f*1.06255f*0.125f,0.0f);
                if(points_p1>=5 || points_p2>=5){
                    drawdigit(-1,&shader,position,{0.125f,0.125f},DIGIT_TOP|DIGIT_MIDDLE|DIGIT_TOPLEFT|DIGIT_TOPRIGHT|DIGIT_BOTTOMLEFT);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit((points_p1>=5)?1:2,&shader,position,{0.125f,0.125f});
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit(-1,&shader,position,{0.125f,0.125f},DIGIT_TOPLEFT |DIGIT_BOTTOMLEFT |DIGIT_BOTTOMLEFT_MIDDLE|
                                                                  DIGIT_TOPRIGHT|DIGIT_BOTTOMRIGHT|DIGIT_BOTTOMRIGHT_MIDDLE);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit(-1,&shader,position,{0.125f,0.125f},DIGIT_TOPMIDDLE|DIGIT_BOTTOMMIDDLE);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit(-1,&shader,position,{0.125f,0.125f},DIGIT_BOTTOMLEFT |DIGIT_TOPLEFT|DIGIT_TOPLEFT_BOTTOMRIGHT|
                                                                  DIGIT_BOTTOMRIGHT|DIGIT_TOPRIGHT);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit(5,&shader,position,{0.125f,0.125f});
                    started=false;
                }

                player1.entity.draw(&shader);
                player2.entity.draw(&shader);
                if(started) ball.entity.draw(&shader);
                roof.draw(&shader);
                floor.draw(&shader);
                leftwall.entity.draw(&shader);
                rightwall.entity.draw(&shader);




                unsigned int aux=points_p2;
                position=glm::vec2(0.25f,0.5f);
                //NOTE: when one of the points hits 20 I should put a you win screen
                first_point_p2=points_p2? false:true;
                while((aux/10) || (aux%10) || first_point_p2){
                    drawdigit(aux%10,&shader,position,{0.125f,0.125f});
                    position.x-=1.5f*0.125f;
                    aux=aux/10;
                    first_point_p2=false;//endless loop if I dont
                }

                aux=points_p1;
                position={-0.25f,0.5f};
                first_point_p1=points_p1? false:true;
                while((aux/10) || (aux%10) || first_point_p1){
                    drawdigit(aux%10,&shader,position,{0.125f,0.125f});
                    position.x-=1.5f*0.125f;
                    aux=aux/10;
                    first_point_p1=false;
                }


            fb.unbind();
        SDL_GetWindowSize(mainwindow,&screenWidth,&screenHeight);
        glViewport(0,0,screenWidth,screenHeight);
        glClearColor(0.0f, 0.0f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glDisable(GL_DEPTH_TEST);
        fb_shader.Use();
            glm::mat4 screenscaler;
            float aspectRatio=(float)screenWidth/(float)screenHeight;
            float inverseAspectRatio=(float)screenHeight/(float)screenWidth;
            if(aspectRatio>1.0f)
            screenscaler = glm::perspective(radians(59.2f),aspectRatio,0.1f,1.0f);
            else
            screenscaler = glm::perspective(radians(59.2f),inverseAspectRatio,0.1f,1.0f);
            GLint model_uniform=glGetUniformLocation(fb_shader.Program, "model");
            glUniformMatrix4fv(model_uniform, 1, GL_FALSE, glm::value_ptr(screenscaler));

            glBindVertexArray(quadVAO);//should scale the scale to the % of resolution
            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, fb.texture);
                glDrawArrays(GL_TRIANGLES, 0, 6);
            glBindTexture(GL_TEXTURE_2D,0);
            glBindVertexArray(0);


        SDL_Delay(1);
        SDL_GL_SwapWindow(mainwindow);
        if(points_p1>=5 || points_p2>=5){
            points_p1=0;
            points_p2=0;
            ball.speed={0.0f,0.0f};
            SDL_Delay(3000);
        }
    }
    DESTRUCTOR(fb);
    DESTRUCTOR(shader);
    DESTRUCTOR(fb_shader);
    Mix_FreeChunk(pong);
    Mix_FreeChunk(pong2);
    Mix_FreeChunk(pong3);
    SDL_GL_DeleteContext(maincontext);
    SDL_DestroyWindow(mainwindow);
    SDL_Quit();

    return 0;
}
Пример #5
0
int main() {

  sf::RenderWindow window(sf::VideoMode(640, 480), "Mandelbrot Set Viewer");
  sf::Texture texture; if (!texture.create(640, 480)) return -1;
  sf::Sprite sprite(texture);

  /*
    Red     ff   0   0
    Orange  ff  7f   0
    Yellow  ff  ff   0
    Y - G   7f  ff   0
    Green    0  ff   0
    Blue     0   0  ff
    Purple  ff   0  ff
    Pink    7f   0  7f
    Black    0   0   0
  */
  const auto grad = std::vector<sf::Color> {
    sf::Color::Red,
    sf::Color(0xff, 0x7f, 0x00),
    sf::Color::Yellow,
    sf::Color(0x7f, 0xff, 0x00),
    sf::Color::Green,
    sf::Color::Blue,
    sf::Color::Magenta,
    sf::Color(0x7f, 0x00, 0x7f),
    sf::Color::Black
  };

  auto palette = mbv::gradient::Linear(grad, 256);
  palette.at(0) = sf::Color::Black;

  const sf::Vector2u textureSize = texture.getSize();
  const sf::FloatRect textureRect(0, 0, textureSize.x, textureSize.y);
  sf::Uint8 pixels[textureSize.x * textureSize.y * 4];

  const sf::FloatRect initialView(-2, -2, 4, 4);
  auto view = initialView;

  updateViewTexture(pixels, texture, view, palette);

  sf::Vector2f newTopLeft(-2, -2);
  sf::Vector2f newBottomRight(2, 2);
  sf::Vector2f mm(0, 0);
  auto mousePressed = false;
  // while window is open
  while(window.isOpen()) {

    sf::Event event;
    while(window.pollEvent(event)) {
      if (event.type == sf::Event::KeyPressed) {
        if (event.key.code == sf::Keyboard::Key::R) {
          view = initialView;
          updateViewTexture(pixels, texture, view, palette);
        }
      }
      if (event.type == sf::Event::Closed) {
        window.close();
      }
      if (event.type == sf::Event::MouseMoved) {
        mm = sf::Vector2f(event.mouseMove.x, event.mouseMove.y);
      }
      if (event.type == sf::Event::MouseButtonPressed) {
        mousePressed = true;
        if (event.mouseButton.button == sf::Mouse::Left) {
          newTopLeft = translatePointFromTo(textureRect, view, mm);
          std::cout << "newTopLeft(" << newTopLeft.x << ", " << newTopLeft.y << ")" << std::endl;
        }
      }
      if (event.type == sf::Event::MouseButtonReleased) {
        mousePressed = false;
        if (event.mouseButton.button == sf::Mouse::Left) {
          newBottomRight = translatePointFromTo(textureRect, view, mm);
          std::cout << "newBottomRight(" << newBottomRight.x << ", " << newBottomRight.y << ")" << std::endl;
          const sf::Vector2f newDimensions(fabs(newBottomRight.x - newTopLeft.x), fabs(newBottomRight.y - newTopLeft.y));
          const sf::FloatRect newView(newTopLeft.x, newTopLeft.y, newDimensions.x, newDimensions.y);
          const sf::Vector2f scaleFactor(view.width / newView.width, view.height / newView.height);
          view = newView;
          std::cout << "view(" << view.left << ", " << view.top << ") (" << view.width << "," << view.height << ") " << std::endl;
          updateViewTexture(pixels, texture, view, palette);
        }
      }
    }
    window.clear(sf::Color::White);
    window.draw(sprite);
    window.display();
  }

  return 0;
}
Пример #6
0
// does not clip on left or right edges of surface
void blit_sprite_hv_blend( SDL_Surface *surface, int x, int y, unsigned int table, unsigned int index, Uint8 hue, Sint8 value )
{
	if (index >= sprite_table[table].count || !sprite_exists(table, index))
	{
		assert(false);
		return;
	}
	
	hue <<= 4;
	
	const Sprite * const cur_sprite = sprite(table, index);
	
	const Uint8 *data = cur_sprite->data;
	const Uint8 * const data_ul = data + cur_sprite->size;
	
	const unsigned int width = cur_sprite->width;
	unsigned int x_offset = 0;
	
	assert(surface->format->BitsPerPixel == 8);
	Uint8 *             pixels =    (Uint8 *)surface->pixels + (y * surface->pitch) + x;
	const Uint8 * const pixels_ll = (Uint8 *)surface->pixels,  // lower limit
	            * const pixels_ul = (Uint8 *)surface->pixels + (surface->h * surface->pitch);  // upper limit
	
	for (; data < data_ul; ++data)
	{
		switch (*data)
		{
		case 255:  // transparent pixels
			data++;  // next byte tells how many
			pixels += *data;
			x_offset += *data;
			break;
			
		case 254:  // next pixel row
			pixels += width - x_offset;
			x_offset = width;
			break;
			
		case 253:  // 1 transparent pixel
			pixels++;
			x_offset++;
			break;
			
		default:  // set a pixel
			if (pixels >= pixels_ul)
				return;
			if (pixels >= pixels_ll)
			{
				Uint8 temp_value = (*data & 0x0f) + value;
				if (temp_value > 0xf)
					temp_value = (temp_value >= 0x1f) ? 0x0 : 0xf;
				
				*pixels = hue | (((*pixels & 0x0f) + temp_value) / 2);
			}
			
			pixels++;
			x_offset++;
			break;
		}
		if (x_offset >= width)
		{
			pixels += surface->pitch - x_offset;
			x_offset = 0;
		}
	}
}
Пример #7
0
void GameState::onDraw(sf::RenderTarget& target) {
    float w = target.getSize().x;
    float h = target.getSize().y;
    m_renderTextures[0].clear();
    m_renderTextures[1].clear();

    sf::RenderTarget& t = m_renderTextures[0];

    target.clear();
    t.clear(sf::Color(80, 80, 80));

    // backdrop
    // t.setView(t.getDefaultView());
    // sf::RectangleShape backdrop(sf::Vector2f(t.getSize()));
    // backdrop.setFillColor(sf::Color(100, 150, 255));
    // backdrop.setFillColor(sf::Color(40, 40, 40));
    // auto shader = Root().resources.getShader("backdrop");
    // shader->setParameter("size", sf::Vector2f(t.getSize()));
    // shader->setParameter("time", getTime());
    // t.draw(backdrop, shader.get());

    setView(t);
    int backTiles = 50;
    float s = 4.0;

    auto tex = Root().resources.getTexture("cave-1");
    tex->setRepeated(true);
    sf::Sprite back(*tex.get());
    back.setTextureRect(sf::IntRect(0, 0, tex->getSize().x * backTiles, tex->getSize().y * backTiles));
    back.setScale(s / tex->getSize().x, s / tex->getSize().y);
    back.setPosition(m_center.x * 0.2, m_center.y * 0.2);
    back.setOrigin(tex->getSize().x / 2 * backTiles, tex->getSize().y / 2 * backTiles);

    auto levelColor = {
        sf::Color(100, 20, 0),
        sf::Color(100, 120, 200),
        sf::Color(250, 200, 0),
        sf::Color(255, 0, 128)
    };
    back.setColor(*(levelColor.begin() + (m_currentLevel) % levelColor.size()));
    t.draw(back);

    s = 8.0;
    tex = Root().resources.getTexture("perlin");
    tex->setRepeated(true);
    back.setTexture(*tex.get(), false);
    back.setTextureRect(sf::IntRect(0, 0, tex->getSize().x * backTiles, tex->getSize().y * backTiles));
    back.setScale(s / tex->getSize().x, s / tex->getSize().y);
    back.setOrigin(tex->getSize().x / 2 * backTiles, tex->getSize().y / 2 * backTiles);
    back.setColor(sf::Color(128, 128, 128));
    back.setPosition(m_center.x * 0.1, m_center.y * 0.1);
    t.draw(back, sf::BlendMultiply);

    s = 8.0;
    back.setScale(s / tex->getSize().x, s / tex->getSize().y);
    back.setPosition(0, 0);
    back.setColor(sf::Color(255, 255, 255, 80));
    back.setPosition(-m_center.x * 0.2, -m_center.y * 0.2);
    t.draw(back, sf::BlendAdd);

    s = 8.0;
    back.setScale(s / tex->getSize().x, s / tex->getSize().y);
    back.setPosition(-m_center.x * 0.3, -m_center.y * 0.3);
    back.setColor(sf::Color(255, 255, 255, 255));
    t.draw(back, sf::BlendMultiply);

    // draw
    setView(t);
    drawEntities(t);

    setView(m_renderTextures[1]);
    float f = - 0.2;
    back.setColor(sf::Color(255, 255, 255, 150));
    back.setPosition(m_center.x * f + m_time * f * 1.5, m_center.y * f);
    m_renderTextures[1].draw(back, sf::BlendAdd);

    sf::Sprite sprite;
    sprite = sf::Sprite(m_renderTextures[1].getTexture());
    Root().resources.getShader("fog")->setParameter("size", sf::Vector2f(m_renderTextures[1].getSize()));
    t.setView(sf::View(sf::FloatRect(0, h, w, -h)));
    t.draw(sprite, sf::RenderStates(sf::BlendAdd, sf::RenderStates::Default.transform, sf::RenderStates::Default.texture, Root().resources.getShader("fog").get()));

    // post-processing
    target.setView(sf::View(sf::FloatRect(0, h, w, -h)));
 
    auto pixel          = Root().resources.getShader("pixel");
    auto verticalBlur   = Root().resources.getShader("blur-vertical");
    auto horizontalBlur = Root().resources.getShader("blur-horizontal");

    horizontalBlur->setParameter("blurSize", 2.5 / w);
    verticalBlur->setParameter("blurSize", 2.5 / h);
    // pixel->setParameter("center", m_center.x, m_center.y);
    pixel->setParameter("size", w, h);

    m_renderTextures[0].setView(m_renderTextures[0].getDefaultView());
    m_renderTextures[1].setView(m_renderTextures[1].getDefaultView());
    m_renderTextures[0].setSmooth(true);
    m_renderTextures[1].setSmooth(true);

    if(m_shadersEnabled) {
        sprite = sf::Sprite(m_renderTextures[0].getTexture());
        m_renderTextures[1].draw(sprite, horizontalBlur.get());

        sprite = sf::Sprite(m_renderTextures[1].getTexture());
        m_renderTextures[0].draw(sprite, verticalBlur.get());

        sprite = sf::Sprite(m_renderTextures[0].getTexture());
        target.draw(sprite, pixel.get());
    } else {
        sprite = sf::Sprite(m_renderTextures[0].getTexture());
        target.draw(sprite);
    }

    // help
    setView(target);
    if(m_currentHelp != "" && m_helpProgress > 0 && m_helpProgress < 1) {
        float fade = glm::smoothstep(0.f, 0.1f, m_helpProgress) - glm::smoothstep(0.9f, 1.f, m_helpProgress);
        float wobble = sin(m_time * 5);

        float alpha = fade;
        float angle = tween::Cubic().easeIn(1 - fade, 0, 1, 1) * 0.2;
        float scale = (0.6 + 0.01 * wobble) * m_pixelSize;

        std::string texture = "help-" + m_currentHelp;
        auto tex = Root().resources.getTexture(texture);
        if(tex) {
            sf::Sprite sprite(*tex.get());
            glm::vec2 ang(-1, 0);
            glm::vec2 pos = m_player->position() - glm::vec2(0, 1.1f) + ang - glm::rotate(ang, angle);
            sprite.setPosition(pos.x, pos.y);
            sprite.setOrigin(tex->getSize().x / 2, tex->getSize().y / 2);
            sprite.setColor(sf::Color(255, 255, 255, 255 * alpha));
            sprite.setScale(scale, scale);
            sprite.setRotation(wobble + thor::toDegree(angle));
            target.draw(sprite);
        }
    }

    // message
    target.setView(target.getDefaultView());
    if(m_message != "") {
        float alpha = fmin(1, fmax(0, m_messageTime)) * fmin(1, fmax(0, 4 - m_messageTime));
        alpha = tween::Cubic().easeOut(alpha, 0, 1, 1);

        sf::Text text;
        text.setFont(* Root().resources.getFont("default"));
        text.setCharacterSize(36);
        text.setString(m_message);
        text.setStyle(sf::Text::Bold);
        text.setPosition(sf::Vector2f(target.getSize().x / 2 - text.getLocalBounds().width / 2, target.getSize().y * 0.8 - fabs(sin(m_time)) * 20));
        text.setColor(sf::Color(255, 255, 255, 255 * alpha));

        sf::Vector2f b(10, 5);
        sf::RectangleShape rect(sf::Vector2f(text.getLocalBounds().width + 2 * b.x, text.getLocalBounds().height * 1.5 + 2 * b.y));
        rect.setPosition(text.getPosition() - b);
        rect.setFillColor(sf::Color(0, 0, 0, 100 * alpha));

        target.draw(rect);
        target.draw(text);
    }

    if(Root().debug) {
        sf::Text text;
        text.setFont(* Root().resources.getFont("mono"));
        text.setCharacterSize(20);
        text.setString(std::to_string(getFPS()) + " FPS");
        text.setPosition(sf::Vector2f(10, 10));
        text.setColor(sf::Color(255, 255, 255, 100));
        target.draw(text);
    }

    if(m_levelFade) {
        sf::RectangleShape rect(sf::Vector2f(target.getSize()));
        rect.setFillColor(sf::Color(0, 0, 0, 255 * m_levelFade));
        target.draw(rect);
    }
}
Пример #8
0
void VDTestPixmaps() {
	CPUEnableExtensions(CPUCheckForExtensions());
	VDFastMemcpyAutodetect();

	VDRegisterVideoDisplayControl();

	HWND hwndDisp = CreateWindow(VIDEODISPLAYCONTROLCLASS, "Kasumi onee-sama", WS_VISIBLE|WS_POPUP, 0, 0, 1024, 768, NULL, NULL, GetModuleHandle(NULL), NULL);

	IVDVideoDisplay *pDisp = VDGetIVideoDisplay(hwndDisp);

	const int srcw = 80;
	const int srch = 60;

	VDPixmapBuffer image(srcw, srch, nsVDPixmap::kPixFormat_XRGB8888);

	for(int y=0; y<srch; ++y) {
		for(int x=0; x<srcw; ++x) {
			int x2 = x - (srcw>>1);
			int y2 = y - (srch>>1);

			uint32 v = (int)((1.0 + sin((x2*x2 + y2*y2) / 50.0)) * 255.0 / 2.0 + 0.5);

			uint32 r = (255-v)<<16;

			if ((x^y)&1)
				v = r = 0;

			((uint32 *)((char *)image.data + image.pitch * y))[x] = (v*x/srcw) + (((v*y)/srch)<<8) + r;
		}
	}

	VDPixmapBuffer sprite(srcw, srch, nsVDPixmap::kPixFormat_XRGB8888);
	VDPixmapBuffer buffer(1024, 768, nsVDPixmap::kPixFormat_XRGB8888);

	VDPixmapBlt(sprite, image);

	pDisp->SetSourcePersistent(true, buffer);

	bouncer p1(-64, -48, 1024+64, 768+48, 1.0);
	bouncer p2(-64, -48, 1024+64, 768+48, 0.5);

	sint64 freq;
	QueryPerformanceFrequency((LARGE_INTEGER *)&freq);

	sint64 start;
	QueryPerformanceCounter((LARGE_INTEGER *)&start);
	int blits = 0;
	double th = 0;

	VDPixmapTextureMipmapChain mipchain(sprite);

	vdautoptr<IVDPixmapResampler> pResampler(VDCreatePixmapResampler());

	while(pump()) {
		int x1 = p1.xposf();
		int y1 = p1.yposf();
		int x2 = p2.xposf();
		int y2 = p2.yposf();

//		VDPixmapBlt(buffer, xp, yp, image, 0, 0, 320, 240);
//		VDPixmapStretchBltNearest(buffer, x1, y1, x2, y2, sprite, -32<<16, -32<<16, (srcw+32)<<16, (srch+32)<<16);
//		VDPixmapStretchBltBilinear(buffer, x1, y1, x2, y2, sprite, 0, 0, srcw<<16, srch<<16);

		double fx1 = x1 / 65536.0;
		double fy1 = y1 / 65536.0;
		double fx2 = x2 / 65536.0;
		double fy2 = y2 / 65536.0;

		if (fx2 < fx1)
			std::swap(fx1, fx2);
		if (fy2 < fy1)
			std::swap(fy1, fy2);

		pResampler->Init(fx2-fx1, fy2-fy1, buffer.format, sprite.w, sprite.h, sprite.format, IVDPixmapResampler::kFilterLanczos3, IVDPixmapResampler::kFilterLanczos3, false);
		pResampler->Process(&buffer, fx1, fy1, fx2, fy2, &sprite, 0, 0);

#if 0
		float mx[16]={1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};

		mx[0] = cos(th) / 512.0f;
		mx[1] = sin(th) / 512.0f;
		mx[5] = cos(th) / 384.0f;
		mx[4] = -sin(th) / 384.0f;

		mx[13] = -6.0f / 384.0f;
		mx[15] = 1.0f;

		VDTriBltVertex vx[4]={
			{ -100, -100, 0, 0, 0 },
			{ +100, -100, 0, 0, 60 },
			{ +100, +100, 0, 80, 60 },
			{ -100, +100, 0, 80, 0 },
		};

		const int idx[6]={0,1,2,0,2,3};

		VDPixmap buffer_cropped(VDPixmapOffset(buffer, 160, 120));

		buffer_cropped.w -= 320;
		buffer_cropped.h -= 240;

		VDPixmapTriBlt(buffer_cropped, mipchain.Mips(), mipchain.Levels(), vx, 4, idx, 6, kTriBltFilterTrilinear, 0.0f, mx);

		th += 0.01;
#endif

		pDisp->Update();
		++blits;

		p1.advance();
		p2.advance();

		sint64 last;
		QueryPerformanceCounter((LARGE_INTEGER *)&last);

		if (last-start >= freq) {
			start += freq;
			VDDEBUG2("%d blits/sec\n", blits);
			blits = 0;
		}
	}
}
Пример #9
0
SpriteID Stage::new_sprite() {
    SpriteID s = SpriteManager::manager_new();
    sprite(s)->set_parent(this);
    signal_sprite_created_(s);
    return s;
}
Пример #10
0
void Stage::delete_sprite(SpriteID s) {   
    sprite(s)->apply_recursively_leaf_first(&ownable_tree_node_destroy, false);
    sprite(s)->detach();
    SpriteManager::manager_delete(s);
}
Пример #11
0
void AnimatedSprite::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
	sf::Sprite sprite(*mv_frames[mi_currentFrame]->m_texture, mv_frames[mi_currentFrame]->m_placement);
	states.transform *= getTransform();
	target.draw(sprite, states);
}
Пример #12
0
int main(int, char const**)
{
    // Create the main window
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");

    // Set the Icon
    sf::Image icon;
    if (!icon.loadFromFile(resourcePath() + "icon.png")) {
        return EXIT_FAILURE;
    }
    window.setIcon(icon.getSize().x, icon.getSize().y, icon.getPixelsPtr());

    // Load a sprite to display
    sf::Texture texture;
    if (!texture.loadFromFile(resourcePath() + "cute_image.jpg")) {
        return EXIT_FAILURE;
    }
    sf::Sprite sprite(texture);

    // Create a graphical text to display
    sf::Font font;
    if (!font.loadFromFile(resourcePath() + "sansation.ttf")) {
        return EXIT_FAILURE;
    }
    sf::Text text("This is how you do it with sfml", font, 50);
    text.setColor(sf::Color::Black);

    // Load a music to play
    sf::Music music;
    if (!music.openFromFile(resourcePath() + "nice_music.ogg")) {
        return EXIT_FAILURE;
    }

    // Play the music
    music.play();

    // Start the game loop
    while (window.isOpen())
    {
        // Process events
        sf::Event event;
        while (window.pollEvent(event))
        {
            // Close window : exit
            if (event.type == sf::Event::Closed) {
                window.close();
            }

            // Escape pressed : exit
            if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
                window.close();
            }
        }

        // Clear screen
        window.clear();

        // Draw the sprite
        window.draw(sprite);

        // Draw the string
        window.draw(text);

        // Update the window
        window.display();
    }

    return EXIT_SUCCESS;
}
Пример #13
0
void Render::operator()(double deltatime)
{
    // Get entity updates
    zmq::message_t zmq_message;
    zmq_game_subscriber->recv(&zmq_message, ZMQ_NOBLOCK);
    if(zeug::string_hash("Sprite") == zeug::string_hash(zmq_message.data()))
    {
        zmq_message.rebuild();
        zmq_game_subscriber->recv(&zmq_message, 0);
        if (zeug::string_hash("Create") == zeug::string_hash(zmq_message.data()))
        {
            zmq_message.rebuild();
            zmq_game_subscriber->recv(&zmq_message, 0);
            while(zeug::string_hash("Finish") != zeug::string_hash(zmq_message.data()))
            {
                Entity entity{0, 0, 0, 0.0f, "", ""};
                msgpack::unpacked unpacked;
                msgpack::unpack(&unpacked, reinterpret_cast<char*>(zmq_message.data()), zmq_message.size());
                msgpack::object obj = unpacked.get();
                obj.convert(&entity);
                
                Sprite sprite = {this->base_window, entity.json_desc, entity.id};
                sprite.SetPosition(std::make_pair(entity.position_x, entity.position_y));
                sprite.SetScale(entity.scale);
                sprite.SetState(Statestring_enum::toEnum(entity.state));
                this->sprites.push_back(std::move(sprite));
                zmq_message.rebuild();
                zmq_game_subscriber->recv(&zmq_message, 0);
            }
        }
        else if(zeug::string_hash("Update") == zeug::string_hash(zmq_message.data()))
        {
            zmq_message.rebuild();
            zmq_game_subscriber->recv(&zmq_message, 0);
            while(zeug::string_hash("Finish") != zeug::string_hash(zmq_message.data()))
            {
                Entity entity{0, 0, 0, 0.0f, "", ""};
                msgpack::unpacked unpacked;
                msgpack::unpack(&unpacked, reinterpret_cast<char*>(zmq_message.data()), zmq_message.size());
                msgpack::object obj = unpacked.get();
                obj.convert(&entity);
                
                for (auto& sprite : this->sprites)
                {
                    //break;
                    if( sprite.GetId() == entity.id)
                    {
                        sprite.SetPosition(std::make_pair(entity.position_x, entity.position_y));
                        sprite.SetScale(entity.scale);
                        sprite.SetState(Statestring_enum::toEnum(entity.state));
                        break;
                    }
                }
                zmq_message.rebuild();
                zmq_game_subscriber->recv(&zmq_message, 0);
            }
        }
    }
    
    // Render sprites
    glEnable (GL_BLEND);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    for (auto& sprite : this->sprites)
    {
        sprite(deltatime);
    }
    glBlendFunc (GL_ZERO, GL_ZERO);
    glDisable (GL_BLEND);
}
Пример #14
0
//------------------------------------------------------------------------------
void
Game::render()
{
	HGE * hge( Engine::hge() );
    hgeResourceManager * rm( Engine::rm() );
    hgeFont * font( rm->GetFont( "love" ) );
    ViewPort * vp( Engine::vp() );

	hge->Gfx_Clear( 0x00AAAAAA );

    vp->setTransform();

    font->SetColor( 0xF0000000 );
    font->SetScale( 0.1f );

	float top( -32.0f );
    unsigned int row( 0 );
    unsigned int col( 0 );

    // draw the lines that we've entered so far
    for( std::vector< std::string >::iterator i = m_lines.begin();
         i != m_lines.end(); ++i )
    {
        const char * line( i->c_str() );
        for ( unsigned int j = 0; j < strlen( line ); ++j )
        {
            font->printf( -50.0f + 2.0f * row,
                          top + 4.75f * col,
                          HGETEXT_LEFT, "%c", line[j] );
            row += 1;
            if ( row > 50 ) break;
        }
        col += 1;
        row = 0;
    }

    // draw what we've written this far: m_brain.getBuffer();
	row = 0;
    const char * past( m_brain.getBuffer() );
    for ( unsigned int i = 0; i < strlen( past ); ++i )
    {
        font->printf( -50.0f + 2.0f * row,
                      top + 4.75f * col,
                      HGETEXT_LEFT, "%c", past[i] );
        row += 1;
        if ( row > 50 ) break;
    }
	row = strlen( past );

    // draw the cursor, showing a dial of characters
    hgeSprite * cursor( rm->GetSprite( "cursor" ) );
    cursor->RenderEx( -50.0f + 2.0f * row + 0.7f, top + 4.75f * col + 5.5f,
                      0.0f, 0.06f, 0.13f );
    if ( m_dial.size() < 5 )
    {
        return;
    }
    int current( m_current[m_brain.getMode()] );
    for ( int offset = -1; offset <= 4; ++offset )
    {
        int index( current + offset );
        if ( index < 0 )
        {
            index += m_dial.size();
        }
        else if ( index >= static_cast<int>(m_dial.size()) )
        {
            index -= m_dial.size();
        }
        hgeSprite * sprite( font->GetSprite( m_dial[index] ) );
        hgeColorRGB color( 1.0f, 1.0f, 1.0f, ( offset == 0 ) ? 1.0f : 0.8f );
		if ( index >= 0 && index < m_dialSize )
		{
			color.b = 0.3f;
		}
        sprite->SetColor( color.GetHWColor() );
        float scale( 1.0f );
        sprite->RenderEx( -50.0f + 2.0f * row,
                          top + 4.75f * col + 2.5f * offset,
                          0.0f, 0.1f, 0.1f * scale );
    }
    row += 1;

    // draw a prediction of what we're likely to write next
	const char * future( m_brain.getText2() );
    const double * probs( m_brain.getProbs2() );
    for ( unsigned int i = 0; i < strlen( future ); ++i )
    {
        if ( row > 50 ) break;
        hgeColorRGB color( 0.0f, 0.0f, 0.0f, static_cast< float >( probs[i] ) );
        font->SetColor( color.GetHWColor() );
        font->printf( -50.0f + 2.0f * row,
                      top + 4.75f * col,
                      HGETEXT_LEFT, "%c", future[i] );
        row += 1;
    }
}
Пример #15
0
int main()
{
    int count = 24000;

    // Random number generator
    std::random_device random;
    std::srand(random());

    // Create the window
    sf::RenderWindow window(sf::VideoMode(800, 600), "MoonyTest", sf::Style::Close);

    sf::Clock frame_clock;
    sf::Time frame_limit = sf::seconds(1.0f / 60.0f);
    sf::Time frame_sum;
    sf::Time frame_time;
    int frame_count;

    sf::Clock clock;
    bool fullscreen = false;

    moony::Sprite player1;
    moony::Sprite player2;
    moony::TextureAtlas texture_atlas;
    moony::SpriteBatch sprite_batch;

    std::vector<moony::Sprite> sprites;

    if(!texture_atlas.loadFromFile("A/small/small.mtpf"))
        return -1;

    player1.m_subtexture = texture_atlas.findSubTexture("mario.png");
    player1.m_layer = 1;
    player1.setScale(5.0f, 5.0f);

    player2.m_subtexture = texture_atlas.findSubTexture("goomba.png");
    player2.m_layer = 4;
    player2.setScale(5.0f, 5.0f);

    std::vector<std::string> tex_names = texture_atlas.getSubTextureNames();

    for(size_t index = 0; index < count; index++)
    {
        size_t name_index = std::rand() % tex_names.size();
        moony::Texture sub_texture = texture_atlas.findSubTexture(tex_names[name_index]);
        //moony::Texture sub_texture = texture_atlas.findSubTexture("player.png");
        moony::Sprite sprite(sub_texture, std::rand() % 100);

        sprite.setPosition(std::rand() % 800, std::rand() % 600);
        sprite.setOrigin(sprite.m_subtexture.m_rect.width / 2, sprite.m_subtexture.m_rect.height / 2);
        sprites.push_back(sprite);
    }

    while(window.isOpen())
    {
        frame_time = frame_clock.restart();

        sf::Event event;

        while(window.pollEvent(event))
        {
            switch(event.type)
            {
            case sf::Event::Closed:
                window.close();
                break;
            default:
                break;
            }
        }

        frame_sum += frame_time;
        frame_count = 0;

        while(frame_sum > frame_limit && frame_count < 10)
        {
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::F11))
            {
                window.create(sf::VideoMode(800, 600), "MoonyTest", fullscreen ? sf::Style::Fullscreen : sf::Style::Close);
                fullscreen = !fullscreen;
            }

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Add) && sprites.size() < 128000)
            {
                for(size_t index = 0; index < 100; index++)
                {
                    size_t name_index = std::rand() % tex_names.size();
                    moony::Texture sub_texture = texture_atlas.findSubTexture(tex_names[name_index]);
                    //moony::Texture sub_texture = texture_atlas.findSubTexture("player.png");
                    moony::Sprite sprite(sub_texture, 1);

                    sprite.setPosition(std::rand() % 800, std::rand() % 600);
                    sprite.setOrigin(sprite.m_subtexture.m_rect.width / 2, sprite.m_subtexture.m_rect.height / 2);
                    sprites.push_back(sprite);
                }
            }

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Subtract) && sprites.size() > 0)
            {
                for(size_t index = 0; index < 100; index++)
                    sprites.pop_back();
            }

            float cos = std::cos(clock.getElapsedTime().asSeconds());
            float sin = std::sin(clock.getElapsedTime().asSeconds());

            for(moony::Sprite& sprite : sprites)
            {
                sprite.rotate(cos * sprite.m_layer);
                sprite.move(cos, sin * sprite.m_layer * 0.25);
                sprite.setScale(sin * 2, sin * 2);
                //sprite.m_layer = random() % 10;
            }

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
                player1.move(0, -5);
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
                player1.move(0, 5);
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
                player1.move(-5, 0);
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
                player1.move(5, 0);

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Y))
                player1.m_subtexture = texture_atlas.findSubTexture("mario.png");
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::H))
                player1.m_subtexture = texture_atlas.findSubTexture("mushroomman.png");
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::N))
                player1.m_subtexture = texture_atlas.findSubTexture("cactus.png");

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::W))
                player2.move(0, -5);
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::S))
                player2.move(0, 5);
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::A))
                player2.move(-5, 0);
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::D))
                player2.move(5, 0);

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::T))
                player2.m_subtexture = texture_atlas.findSubTexture("player.png");
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::G))
                player2.m_subtexture = texture_atlas.findSubTexture("snail.png");
            if(sf::Keyboard::isKeyPressed(sf::Keyboard::B))
                player2.m_subtexture = texture_atlas.findSubTexture("1-up.png");

            frame_sum -= frame_limit;
            frame_count++;
        }

        std::cout << "\r" << "sprites:" << sprites.size() << " render:" << 1.0f / frame_time.asSeconds() << " update:" << 1.0f / frame_clock.getElapsedTime().asSeconds();

        window.clear(sf::Color::Black);

        sprite_batch.clear();

        for(const moony::Sprite& sprite : sprites)
            sprite_batch.draw(sprite);

        sprite_batch.draw(player1);
        sprite_batch.draw(player2);

        sprite_batch.order();

        window.draw(sprite_batch);

        window.display();
    }

    return 0;
}