Ejemplo n.º 1
0
void GPGMultiplayer::SendConnectionRequest(
    const std::string& host_instance_id) {
  if (message_listener_ == nullptr) {
    message_listener_.reset(new MessageListener(
        [this](const std::string& instance_id,
               std::vector<uint8_t> const& payload, bool is_reliable) {
          SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
                       "GPGMultiplayer: OnMessageReceived(%s) callback",
                       instance_id.c_str());
          this->MessageReceivedCallback(instance_id, payload, is_reliable);
        },
        [this](const std::string& instance_id) {
          SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
                       "GPGMultiplayer: OnDisconnect(%s) callback",
                       instance_id.c_str());
          this->DisconnectedCallback(instance_id);
        }));
  }
  SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
              "GPGMultiplayer: Sending connection request to %s",
              host_instance_id.c_str());

  // Immediately stop discovery once we start connecting.
  nearby_connections_->SendConnectionRequest(
      my_instance_name_, host_instance_id, std::vector<uint8_t>{},
      [this](int64_t client_id, gpg::ConnectionResponse const& response) {
        SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
                     "GPGMultiplayer: OnConnectionResponse() callback");
        this->ConnectionResponseCallback(response);
      },
      message_listener_.get());
}
Ejemplo n.º 2
0
void GPGMultiplayer::AcceptConnectionRequest(
    const std::string& client_instance_id) {
  if (message_listener_ == nullptr) {
    message_listener_.reset(new MessageListener(
        [this](const std::string& instance_id,
               std::vector<uint8_t> const& payload, bool is_reliable) {
          SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
                       "GPGMultiplayer: OnMessageReceived(%s) callback",
                       instance_id.c_str());
          this->MessageReceivedCallback(instance_id, payload, is_reliable);
        },
        [this](const std::string& instance_id) {
          SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
                       "GPGMultiplayer: OnDisconnect(%s) callback",
                       instance_id.c_str());
          this->DisconnectedCallback(instance_id);
        }));
  }
  SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
              "GPGMultiplayer: Accepting connection from %s",
              client_instance_id.c_str());
  nearby_connections_->AcceptConnectionRequest(
      client_instance_id, std::vector<uint8_t>{}, message_listener_.get());

  pthread_mutex_lock(&instance_mutex_);
  AddNewConnectedInstance(client_instance_id);
  UpdateConnectedInstances();
  auto i = std::find(pending_instances_.begin(), pending_instances_.end(),
                     client_instance_id);
  if (i != pending_instances_.end()) {
    pending_instances_.erase(i);
  }
  pthread_mutex_unlock(&instance_mutex_);
}
Ejemplo n.º 3
0
void game_destroy(Game* game) {
    timer_destroy(game->timer);
    scene_destroy(game->scene);

    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Destroy Vertex Arrays.\n");
    glDeleteVertexArrays(1, &game->vao_id);
    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Destroy GL context.\n");
    glcontext_destroy(game->gl);

    window_destroy(game->window);
    free(game);
}
Ejemplo n.º 4
0
int lite3d_shader_program_init(lite3d_shader_program *program)
{
    SDL_assert(program);
    
    program->statusString = NULL;
    program->success = 0;
    program->validated = 0;
    
    lite3d_misc_gl_error_stack_clean();
    if (glIsProgram(program->programID))
    {
        lite3d_shader_program_purge(program);
    }

    program->programID = glCreateProgram();
    if (LITE3D_CHECK_GL_ERROR)
    {
        glDeleteProgram(program->programID);
        return LITE3D_FALSE;
    }

    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "shader program 0x%p created",
        (void *)program);

    return LITE3D_TRUE;
}
Ejemplo n.º 5
0
SDL_bool
KMSDRM_WaitPageFlip(_THIS, SDL_WindowData *wdata, int timeout) {
    SDL_VideoData *vdata = ((SDL_VideoData *)_this->driverdata);

    while (wdata->waiting_for_flip) {
        vdata->drm_pollfd.revents = 0;
        if (poll(&vdata->drm_pollfd, 1, timeout) < 0) {
            SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "DRM poll error");
            return SDL_FALSE;
        }

        if (vdata->drm_pollfd.revents & (POLLHUP | POLLERR)) {
            SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "DRM poll hup or error");
            return SDL_FALSE;
        }

        if (vdata->drm_pollfd.revents & POLLIN) {
            /* Page flip? If so, drmHandleEvent will unset wdata->waiting_for_flip */
            KMSDRM_drmHandleEvent(vdata->drm_fd, &vdata->drm_evctx);
        } else {
            /* Timed out and page flip didn't happen */
            SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Dropping frame while waiting_for_flip");
            return SDL_FALSE;
        }
    }
    return SDL_TRUE;
}
Ejemplo n.º 6
0
void* ResCache::Load(unsigned int ID)
{
    // Look of the filename in the strings-to-ID table
    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Resource Cache: Loading %x", ID);
    auto i = resource_file.xiso_file_hash.find(ID);
    if (i == resource_file.xiso_file_hash.end()) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
                     "Resource Cache: no such ID: %x", ID);
        return NULL;
    }

    // Get the data in its file format
    string name = (*i).second;
    // ISO9660::IFS iso_file = xiso9660_open("data.iso");
    // vector<char> data = xiso9660_get_data(m_file, name);
    vector<char> data = resource_file.Get_data(name);
    // xiso9660_close(iso_file);

    // Unpack the data from its file format to its resource
    // format.
    ResHandle* handle = new ResHandle(ID, name, data);

    // Delete old resources if the cache is getting too big.
    bool ok = Maybe_free_old_resources(handle->get_size());
    if (!ok) {
        // Out of space in cache
        // Do something here.
    }

    // Push the new resource into the cache as the newest resource.
    m_lru.push_front(handle);
    m_resources[ID] = handle;

    return handle->get();
}
Ejemplo n.º 7
0
// Callback on the client when it discovers a host.
void GPGMultiplayer::DiscoveryEndpointFoundCallback(
    gpg::EndpointDetails const& endpoint_details) {
  SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "GPGMultiplayer: Found endpoint");
  pthread_mutex_lock(&instance_mutex_);
  instance_names_[endpoint_details.endpoint_id] = endpoint_details.name;
  discovered_instances_.push_back(endpoint_details.endpoint_id);
  pthread_mutex_unlock(&instance_mutex_);
}
Ejemplo n.º 8
0
// Callback on the client when it is either accepted or rejected by the host.
void GPGMultiplayer::ConnectionResponseCallback(
    gpg::ConnectionResponse const& response) {
  if (response.status == gpg::ConnectionResponse::StatusCode::ACCEPTED) {
    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "GPGMultiplayer: Connected!");

    pthread_mutex_lock(&instance_mutex_);
    connected_instances_.push_back(response.remote_endpoint_id);
    UpdateConnectedInstances();
    pthread_mutex_unlock(&instance_mutex_);

    QueueNextState(kConnected);
  } else {
    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
                 "GPGMultiplayer: Didn't connect, response status = %d",
                 response.status);
    QueueNextState(kDiscovering);
  }
}
Ejemplo n.º 9
0
// Important: make sure you lock instance_mutex_ before calling this.
int GPGMultiplayer::AddNewConnectedInstance(const std::string& instance_id) {
  int new_index = -1;
  // First, check if we are a reconnection.
  if (state() == kConnectedWithDisconnections) {
    auto i = disconnected_instances_.find(instance_id);
    if (i != disconnected_instances_.end()) {
      // We've got a disconnected instance, let's find a slot.
      if (connected_instances_[i->second] == "") {
        new_index = i->second;
        connected_instances_[new_index] = instance_id;
        disconnected_instances_.erase(i);
      }
      // If the slot was already taken, fall through to default behavior below.
    }
  }
  if (new_index == -1) {
    if (max_connected_players_allowed() < 0 ||
        (int)connected_instances_.size() < max_connected_players_allowed()) {
      // There's an empty player slot at the end, just connect there.
      new_index = connected_instances_.size();
      connected_instances_.push_back(instance_id);
    } else {
      // We're full, but there might be a reserved spot for a disconnected
      // player. We'll just use that. Sorry, prevoius player!
      for (unsigned int i = 0; i < connected_instances_.size(); i++) {
        if (connected_instances_[i] == "") {
          new_index = i;
          connected_instances_[new_index] = instance_id;
          break;
        }
      }
    }
  }
  if (state() == kConnectedWithDisconnections && new_index >= 0) {
    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
                 "GPGMultiplayer: Connected a reconnected player");
    reconnected_players_.push(new_index);
  }
  SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
               "GPGMultiplayer: Instance %s goes in slot %d",
               instance_id.c_str(), new_index);
  return new_index;
}
Ejemplo n.º 10
0
// Callback on the client when a host it previous discovered disappears.
void GPGMultiplayer::DiscoveryEndpointLostCallback(
    const std::string& instance_id) {
  SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "GPGMultiplayer: Lost endpoint");
  pthread_mutex_lock(&instance_mutex_);
  auto i = std::find(discovered_instances_.begin(), discovered_instances_.end(),
                     instance_id);
  if (i != discovered_instances_.end()) {
    discovered_instances_.erase(i);
  }
  pthread_mutex_unlock(&instance_mutex_);
}
Ejemplo n.º 11
0
bool GPGManager::LoggedIn() {
#ifdef NO_GPG
  return false;
#endif
  assert(game_services_);
  if (state_ < kAuthed) {
    SDL_LogDebug(SDL_LOG_CATEGORY_ERROR,
                 "GPG: player not logged in, can\'t interact with gpg!");
    return false;
  }
  return true;
}
Ejemplo n.º 12
0
static void
KMSDRM_FBDestroyCallback(struct gbm_bo *bo, void *data)
{
    KMSDRM_FBInfo *fb_info = (KMSDRM_FBInfo *)data;

    if (fb_info && fb_info->drm_fd > 0 && fb_info->fb_id != 0) {
        KMSDRM_drmModeRmFB(fb_info->drm_fd, fb_info->fb_id);
        SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Delete DRM FB %u", fb_info->fb_id);
    }

    free(fb_info);
}
Ejemplo n.º 13
0
unsigned int ResourceFile::Quick_hash (const string& str)
{
    unsigned int val = 0;
    for (size_t i = 0; i < str.size(); i ++) {
        char c = str[i];
        if (c == '\0')
            break;
        val = val * 101 + (unsigned char) c;
        val = val & 0xFFFF;
    }
    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Resource File Quick Hash: \"%s\" = %x", str.c_str(), val);
    return val;
}
Ejemplo n.º 14
0
// Callback on the host when a client tries to connect.
void GPGMultiplayer::ConnectionRequestCallback(
    gpg::ConnectionRequest const& connection_request) {
  SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
               "GPGMultiplayer: Incoming connection (instance_id=%s,name=%s)",
               connection_request.remote_endpoint_id.c_str(),
               connection_request.remote_endpoint_name.c_str());
  // process the incoming connection
  pthread_mutex_lock(&instance_mutex_);
  pending_instances_.push_back(connection_request.remote_endpoint_id);
  instance_names_[connection_request.remote_endpoint_id] =
      connection_request.remote_endpoint_name;
  pthread_mutex_unlock(&instance_mutex_);
}
Ejemplo n.º 15
0
void
KMSDRM_VideoQuit(_THIS)
{
    SDL_VideoData *vdata = ((SDL_VideoData *)_this->driverdata);

    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "KMSDRM_VideoQuit()");

    if (_this->gl_config.driver_loaded) {
        SDL_GL_UnloadLibrary();
    }

    if(vdata->saved_crtc != NULL) {
        if(vdata->drm_fd > 0 && vdata->saved_conn_id > 0) {
            /* Restore saved CRTC settings */
            drmModeCrtc *crtc = vdata->saved_crtc;
            if(KMSDRM_drmModeSetCrtc(vdata->drm_fd, crtc->crtc_id, crtc->buffer_id,
                                     crtc->x, crtc->y, &vdata->saved_conn_id, 1,
                                     &crtc->mode) != 0) {
                SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, "Could not restore original CRTC mode");
            }
        }
        KMSDRM_drmModeFreeCrtc(vdata->saved_crtc);
        vdata->saved_crtc = NULL;
    }
    if (vdata->gbm != NULL) {
        KMSDRM_gbm_device_destroy(vdata->gbm);
        vdata->gbm = NULL;
    }
    if (vdata->drm_fd >= 0) {
        close(vdata->drm_fd);
        SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Closed DRM FD %d", vdata->drm_fd);
        vdata->drm_fd = -1;
    }
#ifdef SDL_INPUT_LINUXEV
    SDL_EVDEV_Quit();
#endif
}
Ejemplo n.º 16
0
// Builds a filename-to-ID hash map for a given ISO file.  This
// function is recursive, and the top-level call should have a
// path == "".
void ResourceFile::Build_hash (const string& path)
{
    uint8_t i_joliet_level = iso_file.get_joliet_level();
    stat_vector_t entlist;

    if (!iso_file.readdir(path.c_str(), entlist)) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
                     "Error getting above directory information: %s\n", path.c_str());
        return;
    }

    for (auto i: entlist) {
        iso9660_stat_t* p_statbuf = i->p_stat;
        string full_name = p_statbuf->filename;

        if (p_statbuf->rr.b3_rock != yep) {
            // Overwrite the name with a translated name.  Note that
            // we're using the assumption that the translated name
            // will be shorter, and we're overwriting it in memory.
            iso9660_name_translate_ext(full_name.c_str(),
                                       (char *) full_name.c_str(),
                                       i_joliet_level);
        }
        full_name = full_name.insert(0, path);

        // Recursively descend into subdirectories
        if (p_statbuf->type == 2 /* _STAT_DIR */
                && strcmp (p_statbuf->filename, ".")
                && strcmp (p_statbuf->filename, "..")) {
            full_name.append("/");
            Build_hash(full_name);
        }

        // For regular files, add them to the hash table
        if (p_statbuf->type == 1) {
            // There is an initial slash in this filename that needs to go
            // full_name.erase(0,1);
            printf("%s\n", full_name.c_str());
            xiso_file_hash[Quick_hash(full_name)] = full_name;
            SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
                         "Resource Hash: adding \"%s\" as %x",
                         full_name.c_str(),
                         Quick_hash(full_name));
        }
    }
}
Ejemplo n.º 17
0
/**
 * Initializes the scoreboard
 */
bool Digits::Initialize(SDL_Renderer* renderer)
{
    digits = Painter::LoadImage(renderer, "gfx/numbers.png");
    if (digits == NULL) {
        SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
            "Failed to load digits.");
        return false;
    }

    for (int i = 0; i < 10; i++) {
        digits_clips[i].x = i * 6;
        digits_clips[i].y = 0;
        digits_clips[i].w = 6;
        digits_clips[i].h = 9;
    }

    return true;
}
Ejemplo n.º 18
0
void LifeForm::render(SDL_Renderer* renderer)
{
    auto world = m_world.lock();
    if (!world) {
        return;
    }
    const WorldRect viewport(world->get_viewport());

    if (!m_visited_tiles.empty()) {
        SDL_BlendMode oldMode;
        int rv = SDL_GetRenderDrawBlendMode(renderer, &oldMode);
        if (rv != 0) {
            SDL_LogDebug(SDL_LOG_CATEGORY_RENDER, "Failed to get blend mode: %s", SDL_GetError());
        }
        SDL_SetRenderDrawColor(renderer, 255, 255, 255, 30);
        SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
        const WorldRect bigger_view(geom::rect::enlarge(viewport, TILE_WIDTH));
        for (auto tile : m_visited_tiles) {
            int x, y;
            std::tie(x, y) = tile;
            const WorldRect tile_rect(x * TILE_WIDTH, y * TILE_HEIGHT,
                                      TILE_WIDTH, TILE_HEIGHT);
            if (!tile_rect.is_inside(bigger_view)) {
                continue;
            }
            SDL_Rect rect(world->to_sdl_rect(tile_rect));
            SDL_RenderFillRect(renderer, &rect);
        }
        SDL_SetRenderDrawBlendMode(renderer, oldMode);
    }

    const WorldRect body((int32_t)round(m_pos_x) - width/2,
                         (int32_t)round(m_pos_y) - width/2,
                         width, height);
    if (!body.is_inside(geom::rect::enlarge(viewport, width))) {
        return;
    }

    SDL_Rect rect(world->to_sdl_rect(body));
    SDL_SetRenderDrawColor(renderer, 255, 255, m_focused ? 0 : 255, 255);
    SDL_RenderFillRect(renderer, &rect);
}
Ejemplo n.º 19
0
/**
 * Loads an image into memory
 *
 * @param renderer  renderer to use
 * @param file      filename of image to load
 *
 * @return          returns the loaded image
 */
SDL_Texture* Painter::LoadImage(SDL_Renderer* renderer, const char* file)
{
    SDL_Surface* tmp_image = NULL;
    SDL_Texture* image = NULL;

    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
            "Loading image... %s", file);
    tmp_image = IMG_Load(file);
    if (tmp_image == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
            "Failed to load image: %s", file);
        return NULL;
    }

    image = SDL_CreateTextureFromSurface(renderer, tmp_image);
    //Free the temporary image
    SDL_FreeSurface(tmp_image);

    return image;
}
Ejemplo n.º 20
0
// Callback on the host when it starts advertising.
void GPGMultiplayer::StartAdvertisingCallback(
    gpg::StartAdvertisingResult const& result) {
  // We've started hosting
  if (result.status == gpg::StartAdvertisingResult::StatusCode::SUCCESS) {
    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
                 "GPGMultiplayer: Started advertising (name='%s')",
                 result.local_endpoint_name.c_str());
  } else {
    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
                 "GPGMultiplayer: FAILED to start advertising, error code %d",
                 result.status);
    if (state() == kConnectedWithDisconnections) {
      // We couldn't allow reconnections, sorry!
      ClearDisconnectedInstances();
      QueueNextState(kConnected);
    } else {
      QueueNextState(kError);
    }
  }
}
Ejemplo n.º 21
0
void Log::vsnprint(LogLevel logLevel, LogCategory category, const char* msg, va_list args) {
	char buf[1024];
	const char *categoryStr = LogTypes[static_cast<int>(category)];
	SDL_vsnprintf(buf, sizeof(buf), msg, args);
	buf[sizeof(buf) - 1] = '\0';

	switch (logLevel) {
		case LogLevel::LEVEL_INFO:
			SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ANSI_COLOR_GREEN "(%s): %s" ANSI_COLOR_RESET "\n", categoryStr, buf);
			for (ConsolesConstIter i = _consoles.begin(); i != _consoles.end(); ++i) {
				(*i)->logInfo(buf);
			}
			break;
		case LogLevel::LEVEL_WARN:
			SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, ANSI_COLOR_YELLOW "(%s): %s" ANSI_COLOR_RESET "\n", categoryStr, buf);
			for (ConsolesConstIter i = _consoles.begin(); i != _consoles.end(); ++i) {
				(*i)->logInfo(buf);
			}
			break;
		case LogLevel::LEVEL_ERROR:
			SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, ANSI_COLOR_RED "(%s): %s" ANSI_COLOR_RESET "\n", categoryStr, buf);
			for (ConsolesConstIter i = _consoles.begin(); i != _consoles.end(); ++i) {
				(*i)->logError(buf);
			}
			break;
		case LogLevel::LEVEL_DEBUG:
			SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, ANSI_COLOR_BLUE "(%s): %s" ANSI_COLOR_RESET "\n", categoryStr, buf);
			for (ConsolesConstIter i = _consoles.begin(); i != _consoles.end(); ++i) {
				(*i)->logDebug(buf);
			}
			break;
		case LogLevel::LEVEL_TRACE:
			SDL_LogVerbose(SDL_LOG_CATEGORY_APPLICATION, ANSI_COLOR_CYAN "(%s): %s" ANSI_COLOR_RESET "\n", categoryStr, buf);
			for (ConsolesConstIter i = _consoles.begin(); i != _consoles.end(); ++i) {
				(*i)->logTrace(buf);
			}
			break;
		default:
			break;
	}
}
Ejemplo n.º 22
0
KMSDRM_FBInfo *
KMSDRM_FBFromBO(_THIS, struct gbm_bo *bo)
{
    uint32_t w, h, stride, handle;
    int ret;
    SDL_VideoData *vdata = ((SDL_VideoData *)_this->driverdata);
    KMSDRM_FBInfo *fb_info;

    fb_info = (KMSDRM_FBInfo *)KMSDRM_gbm_bo_get_user_data(bo);
    if (fb_info != NULL) {
        /* Have a previously used framebuffer, return it */
        return fb_info;
    }

    /* Here a new DRM FB must be created */
    fb_info = (KMSDRM_FBInfo *)SDL_calloc(1, sizeof(KMSDRM_FBInfo));
    if (fb_info == NULL) {
        SDL_OutOfMemory();
        return NULL;
    }
    fb_info->drm_fd = vdata->drm_fd;

    w  = KMSDRM_gbm_bo_get_width(bo);
    h = KMSDRM_gbm_bo_get_height(bo);
    stride = KMSDRM_gbm_bo_get_stride(bo);
    handle = KMSDRM_gbm_bo_get_handle(bo).u32;

    ret = KMSDRM_drmModeAddFB(vdata->drm_fd, w, h, 24, 32, stride, handle, &fb_info->fb_id);
    if (ret < 0) {
       free(fb_info);
       return NULL;
    }
    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "New DRM FB (%u): %ux%u, stride %u from BO %p", fb_info->fb_id, w, h, stride, (void *)bo);

    /* Associate our DRM framebuffer with this buffer object */
    KMSDRM_gbm_bo_set_user_data(bo, fb_info, KMSDRM_FBDestroyCallback);
    return fb_info;
}
Ejemplo n.º 23
0
// Callback on host or client when a connected instance disconnects.
void GPGMultiplayer::DisconnectedCallback(const std::string& instance_id) {
  if (allow_reconnecting() && is_hosting() && IsConnected() &&
      GetNumConnectedPlayers() > 1) {
    // We are connected, and we have other instances connected besides this one.
    // Rather than simply disconnecting this instance, let's remember it so we
    // can give it back its connection slot if it tries to reconnect.
    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
                 "GPGMultiplayer: Allowing reconnection by instance %s",
                 instance_id.c_str());
    pthread_mutex_lock(&instance_mutex_);
    auto i = connected_instances_reverse_.find(instance_id);
    if (i != connected_instances_reverse_.end()) {
      int idx = i->second;
      disconnected_instances_[instance_id] = idx;
      // Put an empty instance ID as a placeholder for a disconnected instance.
      connected_instances_[idx] = "";
      UpdateConnectedInstances();
    }
    pthread_mutex_unlock(&instance_mutex_);
    // When the state is kConnectedWithDisconnections, we start advertising
    // again and allow only the disconnected instances to reconnect.
    QueueNextState(kConnectedWithDisconnections);
  } else {
    // Simply remove the connected index.
    pthread_mutex_lock(&instance_mutex_);
    auto i = std::find(connected_instances_.begin(), connected_instances_.end(),
                       instance_id);
    if (i != connected_instances_.end()) {
      connected_instances_.erase(i);
      UpdateConnectedInstances();
    }
    pthread_mutex_unlock(&instance_mutex_);
    if (IsConnected() && GetNumConnectedPlayers() == 0) {
      QueueNextState(kIdle);
    }
  }
}
Ejemplo n.º 24
0
lite3d_mesh_chunk *lite3d_mesh_append_chunk(lite3d_mesh *mesh,
    const lite3d_mesh_layout *layout,
    uint32_t layoutCount,
    uint32_t stride,
    uint16_t componentType,
    uint32_t indexesCount,
    size_t indexesSize,
    size_t indexesOffset,
    uint32_t verticesCount,
    size_t verticesSize,
    size_t verticesOffset)
{
    lite3d_mesh_chunk *meshChunk;
    uint32_t attribIndex = 0, i = 0;
    size_t vOffset = verticesOffset;

    meshChunk = (lite3d_mesh_chunk *) lite3d_malloc_pooled(LITE3D_POOL_NO1, sizeof (lite3d_mesh_chunk));
    SDL_assert_release(meshChunk);

    if (!lite3d_mesh_chunk_init(meshChunk, LITE3D_TRUE))
    {
        lite3d_free_pooled(LITE3D_POOL_NO1, meshChunk);
        return NULL;
    }

    meshChunk->mesh = mesh;
    meshChunk->layout = (lite3d_mesh_layout *) lite3d_malloc(sizeof (lite3d_mesh_layout) * layoutCount);
    SDL_assert_release(meshChunk->layout);

    /* VAO set current */
    glBindVertexArray(meshChunk->vao.vaoID);
    /* use single VBO to store all data */
    glBindBuffer(mesh->vertexBuffer.role, mesh->vertexBuffer.vboID);
    /* bind all arrays and attribs into the current VAO */
    for (; i < layoutCount; ++i)
    {
        glEnableVertexAttribArray(attribIndex);
        glVertexAttribPointer(attribIndex++, layout[i].count, GL_FLOAT,
            GL_FALSE, stride, LITE3D_BUFFER_OFFSET(vOffset));

        vOffset += layout[i].count * sizeof (GLfloat);
        meshChunk->layout[i] = layout[i];
    }

    // setup buffers for instancing rendering 
    if (mesh->auxBuffer)
    {
        glBindBuffer(mesh->vertexBuffer.role, mesh->auxBuffer->vboID);
        for(i = 0; i < 4; ++i)
        {
            glEnableVertexAttribArray(attribIndex);
            glVertexAttribPointer(attribIndex, 4, GL_FLOAT, GL_FALSE, sizeof(kmMat4), LITE3D_BUFFER_OFFSET(i * sizeof(kmVec4)));
            glVertexAttribDivisor(attribIndex++, 1);
        }
    }

    if (indexesCount > 0 && indexesSize > 0)
    {
        glBindBuffer(mesh->indexBuffer.role, mesh->indexBuffer.vboID);
        meshChunk->hasIndexes = LITE3D_TRUE;
    }
    else
    {
        meshChunk->hasIndexes = LITE3D_FALSE;
    }

    /* end VAO binding */
    glBindVertexArray(0);

    meshChunk->vao.indexesOffset = indexesOffset;
    meshChunk->vao.indexType = componentType;
    meshChunk->vao.indexesCount = indexesCount;
    meshChunk->vao.indexesSize = indexesSize;
    meshChunk->vao.verticesCount = verticesCount;
    meshChunk->vao.verticesSize = verticesSize;
    meshChunk->vao.verticesOffset = verticesOffset;
    meshChunk->layoutEntriesCount = layoutCount;
    meshChunk->vao.elementsCount = (indexesCount > 0 ? indexesCount : verticesCount) / 3;

    memset(&meshChunk->boundingVol, 0, sizeof (meshChunk->boundingVol));

    lite3d_list_add_last_link(&meshChunk->node, &mesh->chunks);
    mesh->chunkCount++;

    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "MESH: %p: chunk %p: %s, cv/ov/sv %d/%ldb/%udb, ci/oi %d/%ldb",
        (void *) mesh, (void *) meshChunk, "TRIANGLES",
        meshChunk->vao.verticesCount, meshChunk->vao.verticesOffset, stride, meshChunk->vao.indexesCount, meshChunk->vao.indexesOffset);

    return meshChunk;
}
Ejemplo n.º 25
0
void assets::Texture::reload()
{
    SDL_LogDebug(client::PORTAL_LOG_CATEGORY_ASSETS, "Reloading texture: \"%s\"", name.c_str());

    loadFromDisk(path);
}
Ejemplo n.º 26
0
int
SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
{
    va_list ap;
    SDL_error *error;

    /* Ignore call if invalid format pointer was passed */
    if (fmt == NULL) return -1;

    /* Copy in the key, mark error as valid */
    error = SDL_GetErrBuf();
    error->error = 1;
    SDL_strlcpy((char *) error->key, fmt, sizeof(error->key));

    va_start(ap, fmt);
    error->argc = 0;
    while (*fmt) {
        if (*fmt++ == '%') {
            while (*fmt == '.' || (*fmt >= '0' && *fmt <= '9')) {
                ++fmt;
            }
            switch (*fmt++) {
            case 0:            /* Malformed format string.. */
                --fmt;
                break;
            case 'c':
            case 'i':
            case 'd':
            case 'u':
            case 'o':
            case 'x':
            case 'X':
                error->args[error->argc++].value_i = va_arg(ap, int);
                break;
            case 'f':
                error->args[error->argc++].value_f = va_arg(ap, double);
                break;
            case 'p':
                error->args[error->argc++].value_ptr = va_arg(ap, void *);
                break;
            case 's':
                {
                    int i = error->argc;
                    const char *str = va_arg(ap, const char *);
                    if (str == NULL)
                        str = "(null)";
                    SDL_strlcpy((char *) error->args[i].buf, str,
                                ERR_MAX_STRLEN);
                    error->argc++;
                }
                break;
            default:
                break;
            }
            if (error->argc >= ERR_MAX_ARGS) {
                break;
            }
        }
    }
    va_end(ap);

    /* If we are in debug mode, print out an error message */
    SDL_LogDebug(SDL_LOG_CATEGORY_ERROR, "%s", SDL_GetError());

    return -1;
}
Ejemplo n.º 27
0
void GPGMultiplayer::TransitionState(MultiplayerState old_state,
                                     MultiplayerState new_state) {
  if (old_state == new_state) {
    return;
  }
  // First, exit the old state.
  switch (old_state) {
    case kDiscovering:
    case kDiscoveringPromptedUser:
    case kDiscoveringWaitingForHost: {
      // Make sure we are totally leaving the "discovering" world.
      if (new_state != kDiscoveringPromptedUser &&
          new_state != kDiscoveringWaitingForHost &&
          new_state != kDiscovering) {
        nearby_connections_->StopDiscovery(service_id_);
        SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
                    "GPGMultiplayer: Stopped discovery.");
      }
      break;
    }
    case kConnectedWithDisconnections:
    case kAdvertising:
    case kAdvertisingPromptedUser: {
      // Make sure we are totally leaving the "advertising" world.
      if (new_state != kAdvertising && new_state != kAdvertisingPromptedUser &&
          new_state != kConnectedWithDisconnections) {
        nearby_connections_->StopAdvertising();
        SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
                    "GPGMultiplayer: Stopped advertising");
      }
      break;
    }
    default: {
      // no default behavior
      break;
    }
  }

  // Then, set the state.
  state_ = new_state;

  // Then, activate the new state.
  switch (new_state) {
    case kIdle: {
      is_hosting_ = false;
      ClearDisconnectedInstances();
      break;
    }
    case kConnectedWithDisconnections:  // advertises also
    case kAdvertising: {
      is_hosting_ = true;
      if (new_state != kConnectedWithDisconnections) {
        ClearDisconnectedInstances();
      }

      if (old_state != kAdvertising && old_state != kAdvertisingPromptedUser &&
          old_state != kConnectedWithDisconnections) {
        nearby_connections_->StartAdvertising(
            my_instance_name_, app_identifiers_, gpg::Duration::zero(),
            [this](int64_t client_id,
                   gpg::StartAdvertisingResult const& result) {
              SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
                           "GPGMultiplayer: StartAdvertising callback");
              this->StartAdvertisingCallback(result);
            },
            [this](int64_t client_id,
                   gpg::ConnectionRequest const& connection_request) {
              this->ConnectionRequestCallback(connection_request);
            });
        SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
                    "GPGMultiplayer: Starting advertising");
      }
      break;
    }
    case kDiscovering: {
      is_hosting_ = false;
      ClearDisconnectedInstances();

      if (old_state != kDiscoveringWaitingForHost &&
          old_state != kDiscoveringPromptedUser) {
        if (discovery_listener_ == nullptr) {
          discovery_listener_.reset(new DiscoveryListener(
              [this](gpg::EndpointDetails const& endpoint_details) {
                this->DiscoveryEndpointFoundCallback(endpoint_details);
              },
              [this](const std::string& instance_id) {
                this->DiscoveryEndpointLostCallback(instance_id);
              }));
        }
        nearby_connections_->StartDiscovery(service_id_, gpg::Duration::zero(),
                                            discovery_listener_.get());
        SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
                    "GPGMultiplayer: Starting discovery");
      }
      break;
    }
    case kAdvertisingPromptedUser: {
      pthread_mutex_lock(&instance_mutex_);
      std::string instance_id = pending_instances_.front();
      std::string instance_name = instance_names_[instance_id];
      std::string message =
          std::string("Accept connection from \"") + instance_name + "\"?";
      pthread_mutex_unlock(&instance_mutex_);

      if (!DisplayConnectionDialog("Connection Request", message.c_str(), "Yes",
                                   "No")) {
        // Failed to display dialog, go back to previous state.
        QueueNextState(old_state);
      }
      break;
    }
    case kDiscoveringPromptedUser: {
      pthread_mutex_lock(&instance_mutex_);
      std::string instance_id = discovered_instances_.front();
      std::string instance_name = instance_names_[instance_id];
      std::string message =
          std::string("Connect to \"") + instance_name + "\"?";
      pthread_mutex_unlock(&instance_mutex_);

      if (!DisplayConnectionDialog("Host Found", message.c_str(), "Yes",
                                   "No")) {
        // Failed to display dialog, go back to previous state.
        QueueNextState(old_state);
      }
      break;
    }
    case kConnected: {
      SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
                  "GPGMultiplayer: Connection activated.");
      break;
    }
    default: {
      // no default behavior
      break;
    }
  }
}
Ejemplo n.º 28
0
static int init_platform_gl_extensions(lite3d_video_settings *settings)
{
    SDL_SysWMinfo wminfo;
    SDL_VERSION(&wminfo.version);
    if (!SDL_GetWindowWMInfo(gRenderWindow, &wminfo))
    {
        SDL_LogWarn(
            SDL_LOG_CATEGORY_APPLICATION,
            "SDL_GetWindowWMInfo: %s",
            SDL_GetError());

        return LITE3D_FALSE;
    }

#ifndef GLES
# ifdef PLATFORM_Windows

    if (!WGLEW_ARB_extensions_string)
    {
        SDL_LogWarn(
            SDL_LOG_CATEGORY_APPLICATION,
            "SDL_GetWindowWMInfo: %s",
            SDL_GetError());

        return LITE3D_FALSE;
    }

    SDL_LogDebug(
        SDL_LOG_CATEGORY_APPLICATION,
        "%s: WGL Extensions %s",
        LITE3D_CURRENT_FUNCTION,
        (char *) wglGetExtensionsStringARB(GetDC(wminfo.info.win.window)));

# elif defined PLATFORM_Linux

    if (!GLXEW_VERSION_1_3)
    {
        SDL_LogCritical(
            SDL_LOG_CATEGORY_APPLICATION,
            "%s: GLX v1.3 not supported..",
            LITE3D_CURRENT_FUNCTION);

        return LITE3D_FALSE;
    }

    SDL_LogDebug(
        SDL_LOG_CATEGORY_APPLICATION,
        "%s: GLX Client %s",
        LITE3D_CURRENT_FUNCTION,
        (char *) glXGetClientString(wminfo.info.x11.display, 1));

    SDL_LogDebug(
        SDL_LOG_CATEGORY_APPLICATION,
        "%s: GLX Server %s",
        LITE3D_CURRENT_FUNCTION,
        (char *) glXQueryServerString(wminfo.info.x11.display, 0, 1));

    SDL_LogDebug(
        SDL_LOG_CATEGORY_APPLICATION,
        "%s: GLX Extensions %s",
        LITE3D_CURRENT_FUNCTION,
        (char *) glXQueryExtensionsString(wminfo.info.x11.display, 0));

# endif
#endif

    return LITE3D_TRUE;
}
Ejemplo n.º 29
0
static int init_gl_extensions(lite3d_video_settings *settings)
{
    if (!lite3d_init_gl_extensions_binding())
    {
        SDL_LogDebug(
          SDL_LOG_CATEGORY_APPLICATION,
          "%s: lite3d_init_gl_extensions_binding failed",
          LITE3D_CURRENT_FUNCTION);

        return LITE3D_FALSE;
    }

    if (!lite3d_check_gl_version())
    {
        SDL_LogDebug(
          SDL_LOG_CATEGORY_APPLICATION,
          "%s: lite3d_check_gl_version failed",
          LITE3D_CURRENT_FUNCTION);

        return LITE3D_FALSE;
    }

    SDL_LogDebug(
        SDL_LOG_CATEGORY_APPLICATION,
        "%s: GL Version: %s",
        LITE3D_CURRENT_FUNCTION,
        (const char *) glGetString(GL_VERSION));

    SDL_LogDebug(
        SDL_LOG_CATEGORY_APPLICATION,
        "%s: GL Vendor: %s",
        LITE3D_CURRENT_FUNCTION,
        (const char *) glGetString(GL_VENDOR));

    SDL_LogDebug(
        SDL_LOG_CATEGORY_APPLICATION,
        "%s: GL Renderer: %s",
        LITE3D_CURRENT_FUNCTION,
        (const char *) glGetString(GL_RENDERER));

    const char *extensionsStr = (const char *) glGetString(GL_EXTENSIONS);
    if (extensionsStr)
    {
      int32_t extensionsStrLength = (int32_t)strlen(extensionsStr);
      while (extensionsStrLength >= 0)
      {
          SDL_LogDebug(
              SDL_LOG_CATEGORY_APPLICATION,
              "%s: GL Extensions: %s",
              LITE3D_CURRENT_FUNCTION,
              extensionsStr);

          extensionsStr += SDL_MAX_LOG_MESSAGE;
          extensionsStrLength -= SDL_MAX_LOG_MESSAGE;
      }

    }
    else
    {
      GLint ext_id = 0, numExtensions = 0;
      glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
      for (ext_id = 0; ext_id < numExtensions; ++ext_id)
      {
          SDL_LogDebug(
              SDL_LOG_CATEGORY_APPLICATION,
              "%s: GL Extension (%u): %s",
              LITE3D_CURRENT_FUNCTION,
              ext_id,
              glGetStringi(GL_EXTENSIONS, ext_id));
      }
    }

    SDL_LogDebug(
        SDL_LOG_CATEGORY_APPLICATION,
        "%s: GL Shading Lang %s",
        LITE3D_CURRENT_FUNCTION,
        (const char *) glGetString(GL_SHADING_LANGUAGE_VERSION));

#ifndef GLES
    /* enable multisample buffers */
    if (settings->FSAA > 1 && GLEW_ARB_multisample)
        glEnable(GL_MULTISAMPLE_ARB);
#endif

    return init_platform_gl_extensions(settings);
}
Ejemplo n.º 30
0
static bool
on_idle (void)
{
    uint32_t cur_time;

    if (quitting_flag)
        return false;

    cur_time = SDL_GetTicks ();

    if (initialized_flag && !minimized_flag)
    {
        if (active_flag)
        {
            //audio_time_cur = cur_time;
            //audio_update();
            if (run_full_speed_flag || ((cur_time - before_update_time) > UPDATE_RATE))
            {

                js_do_idle (cur_time - before_update_time);

                update_count ++;
                before_update_time = cur_time;
                after_update_time = SDL_GetTicks();

                if (run_full_speed_flag || ((cur_time - before_draw_time) > REFRESH_RATE))
                {
                    paint ();
                    
                    js_do_after_draw_frame(after_draw_time - before_draw_time);
		  
                    draw_count ++;
                    before_draw_time = cur_time;
                    after_draw_time = SDL_GetTicks ();
		  
                    if (draw_count % 100 == 0)
                    {
                        measured_frame_rate 
                            = 100.0 / (after_draw_time - hundred_frames_draw_time);
                        hundred_frames_draw_time = after_draw_time;
                        SDL_LogDebug (SDL_LOG_CATEGORY_APPLICATION,
                                      "Frame Rate: %f\n",
                                      measured_frame_rate);
                    }
                }
            }

            if (!run_full_speed_flag)
                SDL_Delay(2);
        }
        else
        {
            //audio_pause ();
            // This really ought to wait for when a new window event
            // happens.
            SDL_Delay(2);
        }
    }

    return true;
}