// Create blank projectile for firing
Entity *create_projectile(Entity *source) {
	// Make sure cooldown time has expired between shots to stop
	// a million entities being created at once
	if (SDL_GetTicks() < source->last_shot + WEAPON_COOLDOWN_TIME) {
		return NULL;
	}

	Entity *e = create_entity();
	assert(e);

	// Set attributes
	// Position in centre just above source ship
	e->type = E_PROJECTILE;
	e->owner = source;
	e->image = g_fire_img;
	e->position.x = source->position.x + (source->frame_size / 2 - e->image->w / 2);
	e->position.y = source->position.y - (e->image->h - 5);
	e->impulse = projectile_impulse;
	e->health = PROJECTILE_DAMAGE;
	e->damage = PROJECTILE_DAMAGE;

	// Reset the cooldown timer
	source->last_shot = SDL_GetTicks();

	// Play laser sound
	play_sound(g_laser_snd, NULL, true);

	return e;
}
Beispiel #2
0
void add_building(std::string tag, const int x, const int y, const int z, const std::size_t &civ_owner) {
    auto building = building_defs.find(tag);
    if (building == building_defs.end()) std::cout << "Warning: do not know how to build " << tag << "\n";

    auto new_building = create_entity()
        ->assign(position_t{x, y, z})
        ->assign(building_t{ tag, building->second.width, building->second.height, building->second.glyphs, true, civ_owner });

    for (const building_provides_t &provides : building->second.provides) {
        if (provides.provides == provides_sleep) new_building->assign(construct_provides_sleep_t{});
    }

    if (tag == "storage_locker") {
        spawn_item_in_container(new_building->id, "personal_survival_shelter_kit", get_material_by_tag("plasteel").get());
		spawn_item_in_container(new_building->id, "personal_survival_shelter_kit", get_material_by_tag("plasteel").get());
		spawn_item_in_container(new_building->id, "personal_survival_shelter_kit", get_material_by_tag("plasteel").get());
		spawn_item_in_container(new_building->id, "camp_fire_kit", get_material_by_tag("plasteel").get());
		spawn_item_in_container(new_building->id, "fire_axe", get_material_by_tag("plasteel").get());
		spawn_item_in_container(new_building->id, "pickaxe", get_material_by_tag("plasteel").get());
    } else if (tag == "cordex") {
        new_building->assign(viewshed_t{16, false})
            ->assign(lightsource_t{16, rltk::colors::WHITE, true});
    } else if (tag == "battery") {
        new_building->assign(construct_power_t{20,0,0});
    } else if (tag == "rtg") {
        new_building->assign(construct_power_t{0,1,0});
    } else if (tag == "solar_panel") {
        new_building->assign(construct_power_t{00,0,1});
    } else if (tag == "camp_fire") {
        new_building->assign(lightsource_t{5, rltk::colors::YELLOW});
        new_building->assign(smoke_emitter_t{});
    } else if (tag == "energy_door" || tag == "door") {
        new_building->assign(construct_door_t{});
    }
}
Beispiel #3
0
microscopes::lda::state::state(const model_definition &defn,
      float alpha,
      float beta,
      float gamma,
      const microscopes::lda::nested_vector &dish_assignments,
      const microscopes::lda::nested_vector &table_assignments,
      const microscopes::lda::nested_vector &docs)
    : state(defn, alpha, beta, gamma, docs) {
        // Explicit initialization constructor for state used for
        // deserialization and testing
        // table_assignment maps words to tables (and should be the same
        //  shape as docs)
        // dish_assignment maps tables to dishes (its outer length should
        //  be the the same as docs. Its inner length one plus the maximum
        //  table index value for the given entity/doc.)

        // Create all the dishes we will need.
        for(auto dish: lda_util::unique_members(dish_assignments)) {
            create_dish(dish);
        }
        for (size_t eid = 0; eid < nentities(); ++eid) {
            create_entity(eid);
            // Create all the tables we will need and assign them to their dish.
            for(auto did: dish_assignments[eid]){
                create_table(eid, did);
            }
            // Assign words to tables.
            for(size_t word_index = 0; word_index < table_assignments[eid].size(); word_index++){
                auto tid  = table_assignments[eid][word_index];
                add_table(eid, tid, word_index);
            }
        }
}
Beispiel #4
0
unsigned int create_player(struct entities *_entities, float x, float y)
{
	unsigned int entity = create_entity(_entities);
	_entities->component_mask[entity] = CMP_POSITION | CMP_COLLISION | CMP_RENDER | CMP_INPUT_PLAYER;
	_entities->positions[entity].x = x;
	_entities->positions[entity].y = y;
	_entities->collisions[entity].x = x;
	_entities->collisions[entity].y = y;
	_entities->renders[entity].name = "player";
	return entity;
}
/**
 * Creates a speed belt on the map.
 * 
 * @param[in,out] world    A pointer to the world structure.
 * @param[in] type    	   The tile type.
 * @param[in] xPos    	   The tile xpos.
 * @param[in] yPos         The tile ypos.
 * @param[in] level        The level that the tile is on.
 *
 * @designer 
 * @author   
 */
unsigned int create_stile(World * world, int type, int xPos, int yPos, int level)
{
	if(type != 1 && type != 2)
	{
		return -1;
	}

	unsigned int speed_tile = create_entity(world, COMPONENT_RENDER_PLAYER | COMPONENT_POSITION | COMPONENT_ANIMATION | COMPONENT_COLLISION | COMPONENT_STILE);
	
	int x = xPos / TILE_WIDTH;
	int y = yPos / TILE_HEIGHT;
	
	world->position[speed_tile].x = (x * TILE_WIDTH) + (TILE_WIDTH / 2);
	world->position[speed_tile].y = (y * TILE_HEIGHT) + (TILE_HEIGHT / 2);
	world->position[speed_tile].level = level;
	
	world->position[speed_tile].width = TILE_WIDTH;
	world->position[speed_tile].height = TILE_HEIGHT;
	
	world->renderPlayer[speed_tile].width = TILE_WIDTH;
	world->renderPlayer[speed_tile].height = TILE_HEIGHT;
	
	world->collision[speed_tile].id = 0;
	world->collision[speed_tile].timer = 0;
	world->collision[speed_tile].timerMax = 0;
	world->collision[speed_tile].active = true;
	world->collision[speed_tile].radius = 0;
	
	switch(type)
	{
		case TILE_BELT_RIGHT:
			world->tile[speed_tile].type = TILE_BELT_RIGHT;
			world->collision[speed_tile].type = COLLISION_BELTRIGHT;
			load_animation("assets/Graphics/objects/tiles/speed_right/speed_right_animation.txt", world, speed_tile);
			play_animation(world, speed_tile, (char*)"speed_right");
			break;

		case TILE_BELT_LEFT:
			world->tile[speed_tile].type = TILE_BELT_RIGHT;
			world->collision[speed_tile].type = COLLISION_BELTLEFT;
			load_animation("assets/Graphics/objects/tiles/speed_left/speed_left_animation.txt", world, speed_tile);
			play_animation(world, speed_tile, (char*)"speed_left");
			break;

	}

	world->tile[speed_tile].start_time = SDL_GetTicks();
	return speed_tile;
}
Entity *create_fast_enemy(void) {
    Entity *e = create_entity();
    assert(e);
    e->type = E_FAST_ENEMY;
    e->is_enemy = true;

    // Position at top of screen and move down in a line
    e->image = g_fast_enemy_img;
    e->impulse = fast_enemy_impulse;
    e->points = FAST_ENEMY_POINTS;
    e->health = FAST_ENEMY_HEALTH;
    e->damage = FAST_ENEMY_HEALTH;

    return e;
}
// Final boss enemy
Entity *create_boss_enemy(void) {
    Entity *e = create_entity();
    assert(e);
    e->type = E_BOSS_ENEMY;
    e->is_enemy = true;

    // Position at top of screen and move down in a line
    e->image = g_boss_enemy_img;
    e->frame_count = BOSS_ENEMY_FRAME_COUNT;
    e->frame_size = BOSS_ENEMY_FRAME_SIZE;
    e->impulse = boss_enemy_impulse;
    e->points = BOSS_ENEMY_POINTS;
    e->health = BOSS_ENEMY_HEALTH;
    e->damage = BOSS_ENEMY_HEALTH;

    return e;
}
Beispiel #8
0
void build_game_components(region_t &region, const int crash_x, const int crash_y, const int crash_z) {
    calendar_t calendar;
	calendar.defined_shifts.push_back(shift_t{"Early Shift", {
		WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT }
	});
	calendar.defined_shifts.push_back(shift_t{"Day Shift", {
		SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT,	WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT }
	});
	calendar.defined_shifts.push_back(shift_t{"Late Shift", {
		LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, LEISURE_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT, SLEEP_SHIFT,	WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT, WORK_SHIFT }
	});
    
    auto camera = create_entity()
		->assign(world_position_t{region.region_x, region.region_y, crash_x, crash_y, crash_z+1})
		->assign(std::move(calendar))
		->assign(designations_t{})
        ->assign(logger_t{});
}
// Create basic test enemy - REMOVE BEFORE RELEASE!!!
Entity *create_test_enemy(void) {
	Entity *e = create_entity();
	assert(e);
	e->type = E_BASIC_ENEMY;
	e->is_enemy = true;

	// Position at top of screen and move down in a line

	e->impulse = test_enemy_impulse;

	// Other attribs
	e->image = g_test_enemy_img;
	e->frame_count = TEST_ENEMY_FRAME_COUNT;
	e->points = TEST_ENEMY_POINTS;
	e->health = TEST_ENEMY_HEALTH;
	e->damage = TEST_ENEMY_HEALTH;

	return e;
}
Beispiel #10
0
void CWorldModel::next_level()
{
	//if at the start of the game do not try and destroy the level as none exists and crashes the game
	if (level !=0)
	{
	delete_level();
	}


	level++;
	//loads the required level from file
	CFiles::Inst()->load_level(level);
	//creates all the entities for the level
	create_entity();
	//sets the players health using life
	entityV[entities[ePlayer]]->set_health(100-life);
	screen=1;//sets the screen count to 1
	boss_attack=false;//stops the boss from moving until the players reaches screen 5
	end_cond="GAME OVER";//defult setting
	CSounds::Inst()->play_background(level,boss_attack);// starts plying the background music
}
// Create player
Entity *create_player(int player) {
	Entity *e = create_entity();
	assert(e);

	e->type = E_PLAYER;
	e->ghost = g_player_ghost_img;
	e->frame_count = PLAYER_FRAME_COUNT;
	e->lives = PLAYER_LIVES;
	e->position.x = WINDOW_WIDTH / 2 - e->frame_size / 2;
	e->position.y = WINDOW_HEIGHT - e->frame_size;
	switch (player) {
		case 1:
			e->image = g_player1_img;
			break;
		default:
			e->image = g_player2_img;
			e->active = false;
			break;
	}

	return e;
}
// Create explosion
Entity *create_explosion(Entity *source) {
	Entity *e = create_entity();
	assert(e);

	// Set attributes
	// Position by source ship
	e->type = E_EXPLOSION;
	e->impulse = explosion_impulse;
	e->image = g_explosion_img;
	e->frame_count = EXPLOSION_FRAME_COUNT;
	e->frame_size = EXPLOSION_FRAME_SIZE;
	e->position.x = source->position.x + source->frame_size / 2 - e->frame_size / 2;
	e->position.y = source->position.y + source->frame_size / 2 - e->frame_size / 2;
	e->health = 0.0;
	e->damage = 0.0;
	e->last_shot = SDL_GetTicks();	// Use last_shot to figure out when it was created

	// Play explosion sound
	play_sound(g_explode_snd, NULL, true);

	return e;
}
Beispiel #13
0
microscopes::lda::state::state(const model_definition &defn,
      float alpha,
      float beta,
      float gamma,
      size_t initial_dishes,
      const microscopes::lda::nested_vector &docs,
      common::rng_t &rng)
    : state(defn, alpha, beta, gamma, docs) {

    auto dish_pool = microscopes::common::util::range(initial_dishes);

    create_dish(); // Dummy dish
    for (size_t eid = 0; eid < nentities(); ++eid) {
        create_entity(eid);

        auto did = common::util::sample_choice(dish_pool, rng);
        if (did > dishes_.back()){
            did = create_dish();
        }
        create_table(eid, did);
    }
}
Beispiel #14
0
Challenge::Challenge(ChallengeData* _challenge_data, GUIMain * _gui_main) :
    game_engine(nullptr), map(nullptr), challenge_data(_challenge_data) {
        //Load the correct map into the game.
        map = new Map(challenge_data->map_name);
        MapViewer* map_viewer = Engine::get_map_viewer();
        if(map_viewer == nullptr) {
            throw std::logic_error("MapViewer is not intialised in Engine. In Challenge()");
        }
        map_viewer->set_map(map);

        //Add all the objects to the map
        //TODO: The names of variables need to be refactored to make sense, and this code needs to be cleaned up as there is a bit too much inderection atm!
        for(auto properties : map->locations) { //look at map_loader.hpp for the format of this struct (MapObjectProperties)
            //Create the entity, it automatically gets added to the entity_list
            create_entity(properties.first, properties.second.object_file_location, properties.second.position);
        }

        //create a new GameEngine instance for the python api, we need to review if this is the best place to create it
        game_engine = new GameEngine(_gui_main, this);

        //The intepreter creates a new python thread which is the main thread for the running level, the list of all objects in the level are passed to it which are then exposed to the python code
        daemon = std::make_unique<LockablePythonThreadRunner>(challenge_data->interpreter->register_entities(entity_list, *game_engine));
        daemon->value->halt_soft(PythonThreadRunner::Signal::RESTART);
}
Beispiel #15
0
int map_init(World* world, const char *file_map, const char *file_tiles) {
	
	FILE *fp_map;
	FILE *fp_tiles;
	
	int width, height;
	int x, y, i;
	int **collision_map;
	int **map;

	char *entity_type = (char*)malloc(sizeof(char) * 128);
	int entity_count;
	
	
	SDL_Surface **tiles;
	int *collision;
	int num_tiles;
	int pos = 0;
	char *tile_filename = (char*)malloc(sizeof(char) * 128);
	
	SDL_Rect tile_rect;
	
	if (map_surface != 0) {
		SDL_FreeSurface(map_surface);
	}
	
	//load tiles
	if ((fp_tiles = fopen(file_tiles, "r")) == 0) {
		printf("Error opening tile set %s\n", file_tiles);
		return -1;
	}
	
	if (fscanf(fp_tiles, "%d", &num_tiles) != 1) {
		printf("Cannot find tile number\n");
		return -1;
	}
	
	if ((tiles = (SDL_Surface**)malloc(sizeof(SDL_Surface*) * num_tiles)) == 0) {
		printf("Error mallocing tile surfaces\n");
		return -1;
	}
	if ((collision = (int*)malloc(sizeof(int) * num_tiles)) == 0) {
		printf("Error mallocing tile surfaces\n");
		return -1;
	}
	
	for(i = 0; i < num_tiles; i++) {
		
		if (fscanf(fp_tiles, "%d", &pos) != 1) {
			printf("Error reading tile map index.\n");
			return -1;
		}
		
		if (pos >= num_tiles) {
			printf("Trying to write to tiles outside of memory\n");
			return -1;
		}
		
		if (fscanf(fp_tiles, "%s", (char*)tile_filename) != 1) {
			printf("Error reading tile map filename.\n");
			return -1;
		}
		if (fscanf(fp_tiles, "%d", &collision[pos]) != 1){
			printf("Error reading tile map collision.\n");
			return -1;	
		}
		
		tiles[pos] = IMG_Load(tile_filename);
		
		if (tiles[pos] == NULL) {
			printf("Error loading tile: %s\n", tile_filename);
			return -1;
		}
	}
	
	fclose(fp_tiles);
	
	//LOAD MAP
	
	if ((fp_map = fopen(file_map, "r")) == 0) {
		printf("Error opening map %s\n", file_map);
		return -1;
	}
	
	if (fscanf(fp_map, "%d %d %d", &level, &width, &height) != 3) {
		return -1;
	}
	
	if ((map = (int**)malloc(sizeof(int*) * width)) == NULL) {
		printf("malloc failed\n");
	}
	if ((collision_map = (int**)malloc(sizeof(int*) * width)) == NULL) {
		printf("malloc failed\n");
	}
	
	for (i = 0; i < width; i++) {
		if ((map[i] = (int*)malloc(sizeof(int) * height)) == NULL) {
			printf("malloc failed\n");
		}
		if ((collision_map[i] = (int*)malloc(sizeof(int) * height)) == NULL) {
			printf("malloc failed\n");
		}
	}
	
	printf("Map load size %d %d\n", width, height);
	
	for(y = 0; y < height; y++) {
		for(x = 0; x < width; x++) {
			
			if (fscanf(fp_map, "%d", &map[x][y]) != 1) {
				printf("Expected more map.\n");
				return -1;
			}
			
			if (map[x][y] >= num_tiles) {
				printf("Using tile %u that is bigger than %d\n", map[x][y], num_tiles);
			}
			
			collision_map[x][y] = collision[map[x][y]];
		}
	}
	
	if (fscanf(fp_map, "%d", &entity_count) == 1) {
		
		for(i = 0; i < entity_count; i++) {
			
			if (fscanf(fp_map, "%s", (char*)entity_type) != 1) {
				printf("Entity type error: %s\n", file_map);
				return -1;
			}
			
			//printf("Found entity: %s\n", entity_type);
			
			if (strcmp(entity_type, "stair") == 0 || strcmp(entity_type, "stairs") == 0) { //stairs
				
				//stair x y targetX targetY 2
				int x, y, floor;
				float targetX, targetY;
				char dir;

				if (fscanf(fp_map, "%d %d %f %f %d %c", &x, &y, &targetX, &targetY, &floor, &dir) != 6) {
					printf("Error loading stair\n");
					return -1;
				}
				switch (dir) { // make the hitboxes for the stairs
					case 'l':
						create_stair(world, floor, targetX * TILE_WIDTH + TILE_WIDTH / 2, targetY * TILE_HEIGHT + TILE_HEIGHT / 2, x * TILE_WIDTH + TILE_WIDTH / 2 - 5, y * TILE_HEIGHT + TILE_HEIGHT / 2, 4, 4, level);
						create_block(world, x * TILE_WIDTH + 7, y * TILE_HEIGHT + TILE_HEIGHT / 2, 10, TILE_HEIGHT - 4, floor);
						break;
					case 'r':
						create_stair(world, floor, targetX * TILE_WIDTH + TILE_WIDTH / 2, targetY * TILE_HEIGHT + TILE_HEIGHT / 2, x * TILE_WIDTH + TILE_WIDTH / 2 + 5, y * TILE_HEIGHT + TILE_HEIGHT / 2, 4, 4, level);
						create_block(world, x * TILE_WIDTH + TILE_WIDTH - 7, y * TILE_HEIGHT + TILE_HEIGHT / 2, 10, TILE_HEIGHT - 4, floor);
						break;
					case 'u':
						create_stair(world, floor, targetX * TILE_WIDTH + TILE_WIDTH / 2, targetY * TILE_HEIGHT + TILE_HEIGHT / 2, x * TILE_WIDTH + TILE_WIDTH / 2, y * TILE_HEIGHT + TILE_HEIGHT / 2 - 5, 4, 4, level);
						create_block(world, x * TILE_WIDTH + TILE_WIDTH / 2, y * TILE_HEIGHT + 7, TILE_WIDTH - 4, 10, floor);
						break;
					case 'd':
						create_stair(world, floor, targetX * TILE_WIDTH + TILE_WIDTH / 2, targetY * TILE_HEIGHT + TILE_HEIGHT / 2, x * TILE_WIDTH + TILE_WIDTH / 2, y * TILE_HEIGHT + TILE_HEIGHT / 2 + 5, 4, 4, level);
						create_block(world, x * TILE_WIDTH + TILE_WIDTH / 2, y * TILE_HEIGHT + TILE_HEIGHT - 7, TILE_WIDTH - 4, 10, floor);
						break;
				}
			}
			else if (strcmp(entity_type, "object") == 0) { //animated objects
				
				unsigned int entity;
				float x, y;
				int w, h;
				char *animation_name = (char*)malloc(sizeof(char) * 64);
				char *animation_filename = (char*)malloc(sizeof(char) * 64);
				
				if (fscanf(fp_map, "%f %f %d %d %s %s", &x, &y, &w, &h, animation_filename, animation_name) != 6) {
					printf("Error loading object!\n");
					return -1;
				}
				
				entity = create_entity(world, COMPONENT_RENDER_PLAYER | COMPONENT_POSITION | COMPONENT_ANIMATION | COMPONENT_COLLISION);
				
				//printf("Loading object %d (%f, %f) [%s] %s\n", entity, x, y, animation_name, animation_filename);
				
				world->position[entity].x = x * TILE_WIDTH + TILE_WIDTH / 2;
				world->position[entity].y = y * TILE_HEIGHT + TILE_HEIGHT / 2;
				
				world->position[entity].width = w;
				world->position[entity].height = h;
				
				world->renderPlayer[entity].width = w;
				world->renderPlayer[entity].height = h;
				
				world->collision[entity].id = 0;
				world->collision[entity].type = COLLISION_SOLID;
				world->collision[entity].timer = 0;
				world->collision[entity].timerMax = 0;
				world->collision[entity].active = true;
				world->collision[entity].radius = 0;
				
				load_animation(animation_filename, world, entity);
				play_animation(world, entity, animation_name);
				
				free(animation_name);
				free(animation_filename);
				
			}
			else if (strcmp(entity_type, "sound") == 0) {
				
				int sound_id;
				
				if (fscanf(fp_map, "%d", &sound_id) != 1) {
					printf("Error loading sound!\n");
					return -1;
				}
				
				play_music(sound_id);
				
				//printf("Playing sound %d\n", sound_id);
				
			}
			else if (strcmp(entity_type, "objective") == 0) {
				
				float x, y;
				int w, h;
				unsigned int id, entity = -1;
				char *animation_filename = (char*)malloc(sizeof(char) * 64);
				
				if (fscanf(fp_map, "%f %f %d %d %u %s", &x, &y, &w, &h, &id, animation_filename) != 6) {
					printf("Error loading objective!\n");
					return -1;
				}
				
				entity = create_objective(world, x * TILE_WIDTH + TILE_WIDTH / 2, y * TILE_HEIGHT + TILE_HEIGHT / 2, w, h, id, level);
				
				if (entity >= MAX_ENTITIES) {
					printf("exceeded max entities.\n");
					return -1;
				}
				
				world->mask[entity] |= COMPONENT_ANIMATION | COMPONENT_RENDER_PLAYER;
				
				world->renderPlayer[entity].width = w;
				world->renderPlayer[entity].height = h;
				
				load_animation(animation_filename, world, entity);
				play_animation(world, entity, "not_captured");
				
				//printf("Loaded objective: %u\n", entity);
				
				free(animation_filename);
			}
			else if (strcmp(entity_type, "powerup") == 0) {
				float x, y;
				int w, h, type;
				unsigned int entity = -1;
				char *animation_filename = (char*)malloc(sizeof(char) * 128);
				
				if (fscanf(fp_map, "%f %f %d %d %d %s", &x, &y, &w, &h, &type, animation_filename) != 6) {
					printf("Error loading powerup!\n");
					return -1;
				}
				entity = create_powerup(world, x * TILE_WIDTH + TILE_WIDTH / 2, y * TILE_HEIGHT + TILE_HEIGHT / 2, w, h, type, level);
				
				if (entity >= MAX_ENTITIES) {
					printf("exceeded max entities.\n");
					return -1;
				}
				world->mask[entity] |= COMPONENT_ANIMATION | COMPONENT_RENDER_PLAYER;
				world->renderPlayer[entity].width = w;
				world->renderPlayer[entity].height = h;
				
				load_animation(animation_filename, world, entity);
				play_animation(world, entity, "bounce");
				
				free(animation_filename);
			}
			else if (strcmp(entity_type, "chair") == 0) { //animated objects
				
				unsigned int entity;
				float x, y;
				int w, h;
				char *animation_name = (char*)malloc(sizeof(char) * 64);
				char *animation_filename = (char*)malloc(sizeof(char) * 64);
				
				if (fscanf(fp_map, "%f %f %d %d %s %s", &x, &y, &w, &h, animation_filename, animation_name) != 6) {
					printf("Error loading chair!\n");
					return -1;
				}
				
				entity = create_entity(world, COMPONENT_RENDER_PLAYER | COMPONENT_POSITION | COMPONENT_ANIMATION);
				
				//printf("Loading object %d (%f, %f) [%s] %s\n", entity, x, y, animation_name, animation_filename);
				
				world->position[entity].x = x * TILE_WIDTH;
				world->position[entity].y = y * TILE_HEIGHT;
				
				world->position[entity].width = w;
				world->position[entity].height = h;
				
				world->renderPlayer[entity].width = w;
				world->renderPlayer[entity].height = h;
				
				load_animation(animation_filename, world, entity);
				play_animation(world, entity, animation_name);
				
				free(animation_name);
				free(animation_filename);
				
			}
			else {
				printf("Did not deal with the entity type: %s\n", entity_type);
				break;
			}
		}
	}
	
	fclose(fp_map);
	//cleanup_map();

	map_surface = SDL_CreateRGBSurface(0, width * TILE_WIDTH, height * TILE_HEIGHT, 32, 0, 0, 0, 0);
	
	if (map_surface == 0) {
		printf("error making map surface.\n");
		return -1;
	}
	
	SDL_FillRect(map_surface, NULL, 0xFF0000);
	
	tile_rect.w = TILE_WIDTH;
	tile_rect.h = TILE_HEIGHT;
	
	for(y = 0; y < height; y++) {
		for(x = 0; x < width; x++) {
			tile_rect.x = x * TILE_WIDTH;
			tile_rect.y = y * TILE_HEIGHT;
			
			SDL_BlitSurface(tiles[map[x][y]], NULL, map_surface, &tile_rect);
		}
	}
	
	for(i = 0; i < num_tiles; i++) {
		SDL_FreeSurface(tiles[i]);
	}
	
	map_rect.x = 0;
	map_rect.y = 0;
	w = map_rect.w = width * TILE_WIDTH;
	h = map_rect.h = height * TILE_HEIGHT;
	
	
	create_level(world, collision_map, width, height, TILE_WIDTH, level);

	for (i = 0; i < width; i++) {
		free(map[i]);
		free(collision_map[i]);
	}
	free(map);
	free(collision_map);
	
	
	free(tiles);
	free(collision);
	
	free(entity_type);
	free(tile_filename);

	return 0;
}
bool ESceneObjectTool::ExportClimableObjects(SExportStreams* F)
{
	bool bResult                    = true;
    CGeomPartExtractor* extractor   = 0;

    Fbox 		bb;
    if (!GetBox(bb))
        return  false;

    extractor	                    = xr_new<CGeomPartExtractor>();
    extractor->Initialize           (bb,EPS_L,int_max);

    UI->SetStatus	("Export climable objects...");
	// collect verts&&faces
    {
	    SPBItem* pb                 = UI->ProgressStart(m_Objects.size(), "Prepare geometry...");
        for (ObjectIt it=m_Objects.begin(); it!=m_Objects.end(); it++)
        {
	        pb->Inc();
            CSceneObject* obj 		= dynamic_cast<CSceneObject*>(*it);
            VERIFY                  (obj);
            if (obj->IsStatic())
            {
                CEditableObject *O 	= obj->GetReference();
                const Fmatrix& T 	= obj->_Transform();
                
                for(EditMeshIt M =O->FirstMesh(); M!=O->LastMesh(); M++)
                    if (!build_mesh	(T, *M, extractor, SGameMtl::flClimable, TRUE))
                    {
                      bResult       = false;
                      break;
                    }
            }
        }
	    UI->ProgressEnd(pb);
    }
    if (!extractor->Process())
        bResult                     = false;

    // export parts
    if (bResult)
    {
    	SBPartVec& parts			= extractor->GetParts();
	    SPBItem* pb                 = UI->ProgressStart(parts.size(),"Export Parts...");
        for (SBPartVecIt p_it=parts.begin(); p_it!=parts.end(); p_it++)
        {
	        pb->Inc                 ();
            SBPart*	P				= *p_it;
        	if (P->Valid())
            {
                // export visual
                AnsiString sn		            = AnsiString().sprintf("clmbl#%d",(p_it-parts.begin()));

				Fvector local_normal	        = {0,0,0};

                LPCSTR mat_name = NULL;
                for (SBFaceVecIt it=P->m_Faces.begin(); it!=P->m_Faces.end(); it++)
                {
                	for (u32 k=0; k<3; k++)
                        local_normal.add	        ((*it)->n[k]);

                    mat_name     = (*it)->surf->_GameMtlName();
                }

                local_normal.normalize_safe		();
                
                // export spawn object
                {
                    AnsiString entity_ref		= "climable_object";
                    ISE_Abstract*	m_Data		= create_entity(entity_ref.c_str()); 	VERIFY(m_Data);
                    ISE_Shape* m_Shape			= m_Data->shape();                      VERIFY(m_Shape);
//					CSE_Visual* m_Visual		= m_Data->visual();	VERIFY(m_Visual);
                    // set params
                    m_Data->set_name			(entity_ref.c_str());
                    m_Data->set_name_replace	(sn.c_str());
                    // set shape
                    CShapeData::shape_def		shape;
                    shape.type					= CShapeData::cfBox;
                    shape.data.box.scale		((P->m_BBox.max.x-P->m_BBox.min.x)*0.5f,
                    							(P->m_BBox.max.y-P->m_BBox.min.y)*0.5f,
                                                (P->m_BBox.max.z-P->m_BBox.min.z)*0.5f);
                    m_Shape->assign_shapes		(&shape,1);
					// orientate object
	          		if (!OrientToNorm(local_normal,P->m_OBB.m_rotate,P->m_OBB.m_halfsize))
                    {
                    	ELog.Msg(mtError,"Invalid climable object found. [%3.2f, %3.2f, %3.2f]",VPUSH(P->m_RefOffset));
					}
                    else
                    {
                        Fmatrix M; M.set			(P->m_OBB.m_rotate.i,P->m_OBB.m_rotate.j,P->m_OBB.m_rotate.k,P->m_OBB.m_translate);
                        M.getXYZ					(P->m_RefRotate); // не i потому что в движке так
                        m_Data->position().set		(P->m_RefOffset); 
                        m_Data->angle().set			(P->m_RefRotate);

                        m_Data->set_additional_info((void*)mat_name);
                        NET_Packet					Packet;
                        m_Data->Spawn_Write			(Packet,TRUE);

                        F->spawn.stream.open_chunk	(F->spawn.chunk++);
                        F->spawn.stream.w			(Packet.B.data,Packet.B.count);
                        F->spawn.stream.close_chunk	();

						if (s_draw_dbg)
                        {
                            Tools->m_DebugDraw.AppendOBB(P->m_OBB);
                            M.transform_dir				(local_normal);
                            Tools->m_DebugDraw.AppendLine(P->m_RefOffset,Fvector().mad(P->m_RefOffset,local_normal,1.f));
                        }
                    }
                    destroy_entity				(m_Data);
                }
            }else
            {
            	ELog.Msg(mtError,"Can't export invalid part #%d",p_it-parts.begin());
            }
        }
	    UI->ProgressEnd     (pb);
    }
    // clean up
    xr_delete               (extractor);

    return                  bResult;
}
bool ESceneObjectTool::ExportBreakableObjects(SExportStreams* F)
{
	bool bResult = true;
    CGeomPartExtractor* extractor=0;

    Fbox 		bb;
    if (!GetBox(bb)) return false;

    extractor	= xr_new<CGeomPartExtractor>();
    extractor->Initialize(bb,EPS_L,2);

    UI->SetStatus	("Export breakable objects...");
	// collect verts&&faces
    {
	    SPBItem* pb = UI->ProgressStart(m_Objects.size(),"Prepare geometry...");
        for (ObjectIt it=m_Objects.begin(); it!=m_Objects.end(); it++){
	        pb->Inc();
            CSceneObject* obj 		= dynamic_cast<CSceneObject*>(*it); VERIFY(obj);
            if (obj->IsStatic()){
                CEditableObject *O 	= obj->GetReference();
                const Fmatrix& T 	= obj->_Transform();
                for(EditMeshIt M=O->FirstMesh();M!=O->LastMesh();M++)
                    if (!build_mesh	(T,*M,extractor,SGameMtl::flBreakable,FALSE)){bResult=false;break;}
            }
        }
	    UI->ProgressEnd(pb);
    }
    if (!extractor->Process())		bResult = false;
    // export parts
    if (bResult){
    	SBPartVec& parts			= extractor->GetParts();
	    SPBItem* pb = UI->ProgressStart(parts.size(),"Export Parts...");
        for (SBPartVecIt p_it=parts.begin(); p_it!=parts.end(); p_it++){
	        pb->Inc();
            SBPart*	P				= *p_it;
        	if (P->Valid()){
                // export visual
                AnsiString sn		= AnsiString().sprintf("meshes\\brkbl#%d.ogf",(p_it-parts.begin()));
                xr_string fn		= Scene->LevelPath()+sn.c_str();
                IWriter* W			= FS.w_open(fn.c_str()); R_ASSERT(W);
                if (!P->Export(*W,1)){
                    ELog.DlgMsg		(mtError,"Invalid breakable object.");
                    bResult 		= false;
                    break;
                }
                FS.w_close			(W);
                // export spawn object
                {
                    AnsiString entity_ref		= "breakable_object";
                    ISE_Abstract*	m_Data		= create_entity(entity_ref.c_str()); 	VERIFY(m_Data);
                    CSE_Visual* m_Visual		= m_Data->visual();	VERIFY(m_Visual);
                    // set params
                    m_Data->set_name			(entity_ref.c_str());
                    m_Data->set_name_replace	(sn.c_str());
                    m_Data->position().set		(P->m_RefOffset);
                    m_Data->angle().set			(P->m_RefRotate);
                    m_Visual->set_visual		(sn.c_str(),false);

					if (s_draw_dbg){
                        Fmatrix MX;
                        MX.setXYZi				(P->m_RefRotate);
                        MX.translate_over		(P->m_RefOffset);
                        Fvector DR				= {0,0,1};
                        MX.transform_dir		(DR);
                        Tools->m_DebugDraw.AppendLine(P->m_RefOffset,Fvector().mad(P->m_RefOffset,MX.k,1.f),0xFF0000FF,false,false);
                    }

                    NET_Packet					Packet;
                    m_Data->Spawn_Write			(Packet,TRUE);

                    F->spawn.stream.open_chunk	(F->spawn.chunk++);
                    F->spawn.stream.w			(Packet.B.data,Packet.B.count);
                    F->spawn.stream.close_chunk	();
                    destroy_entity				(m_Data);
                }
            }else{
            	ELog.Msg(mtError,"Can't export invalid part #%d",p_it-parts.begin());
            }
        }
	    UI->ProgressEnd(pb);
    }
    // clean up
    xr_delete(extractor);

    return bResult;
}
Beispiel #18
0
struct Entity *
world_create_entity(struct World *self) {
	return create_entity(self->entities);
}
Beispiel #19
0
    float x, y;
};

struct Component2
{
    float x, y;
};

DESCRIBE("World")

    IT("creates and stores entities and components",
    {
        // Arrange
        auto world = std::make_shared<World>();
        auto expected = Component1 { 10, 20 };
        auto entity = world->create_entity();
    
        // Act
        world->add_component<Component1>(entity);
        world->get_component<Component1>(entity) = expected;
    
        // Assert
        auto & actual = world->get_component<Component1>(entity);
        S_ASSERT(expected.x == actual.x, "Component not stored correctly");
        S_ASSERT(expected.y == actual.y, "Component not stored correctly");
    
        // Teardown
    });

    IT("is possible to store many entities with components",
    {
Beispiel #20
0
void inventory_system::configure() {
	system_name = "Inventory";

	// Receive inventory change messages - refresh the inventory list
	subscribe<inventory_changed_message>([this](inventory_changed_message &msg) {
		dirty = true;
	});

	// Receive drop messages
	subscribe<drop_item_message>([this](drop_item_message &msg) {
		if (!entity(msg.id)) return;
		emit(item_claimed_message{msg.id, false});
		delete_component<item_carried_t>(msg.id);
		entity(msg.id)->component<item_t>()->claimed = false;
		entity(msg.id)->assign(position_t{ msg.x, msg.y, msg.z });
		entity_octree.add_node(octree_location_t{msg.x,msg.y,msg.z,msg.id});
		dirty = true;
	});

	// Receive pick-up messages
	subscribe<pickup_item_message>([this](pickup_item_message &msg) {
		if (!entity(msg.id)) return;
		auto pos = entity(msg.id)->component<position_t>();
		if (pos) {
			entity_octree.remove_node(octree_location_t{pos->x,pos->y, pos->z,msg.id});
			delete_component<position_t>(msg.id);
		}
		delete_component<item_stored_t>(msg.id);
		entity(msg.id)->assign(item_carried_t{ msg.loc, msg.collector });
		dirty = true;
		emit(renderables_changed_message{});
	});

	// Receive item destruction messages
	subscribe<destroy_item_message>([this](destroy_item_message &msg) {
		if (!entity(msg.id)) return;
		auto pos = entity(msg.id)->component<position_t>();
		if (pos) {
			entity_octree.remove_node(octree_location_t{pos->x,pos->y, pos->z,msg.id});
			delete_component<position_t>(msg.id);
		}

		delete_entity(msg.id);
	});

	// Receive claim messages - update an item as claimed/unclaimed
	subscribe<item_claimed_message>([] (item_claimed_message &msg) {
		auto e = entity(msg.id);
		if (e) {
			auto item = e->component<item_t>();
			item->claimed = msg.claimed;
		}
	});

	// Receive build requests - claim components and add to the designations list.
	subscribe<build_request_message>([this] (build_request_message &msg) {
		if (!msg.building) return;

		// Claim components, create the designations
		available_building_t building = msg.building.get();

		// Build designation
		building_designation_t designate;
		designate.x = msg.x;
		designate.y = msg.y;
		designate.z = msg.z;
		designate.name = building.name;
		designate.tag = building.tag;
		designate.components = building.components;
    	designate.width = building.width;
    	designate.height = building.height;
    	designate.glyphs = building.glyphs;

		for (const auto &requested_component : building.components) {
			const std::size_t component_id = claim_item_by_reaction_input(requested_component);
			std::cout << "Component [" << requested_component.tag << "] #" << component_id << "\n";
			designate.component_ids.push_back(std::make_pair(component_id, false));
		}

		auto building_template = create_entity()
			->assign(position_t{msg.x, msg.y, msg.z})
			->assign(building_t{ designate.tag, designate.width, designate.height, designate.glyphs, false });
		designate.building_entity = building_template->id;

		designations->buildings.push_back(designate);

        int sx = designate.x;
        int sy = designate.y;
        if (designate.width == 3) --sx;
        if (designate.height == 3) --sy;

		for (int x = sx; x < sx + designate.width; ++x) {
			for (int y=sy; y < sy + designate.height; ++y) {
				const auto idx = mapidx(x,y,camera_position->region_z);
				current_region->tile_flags[idx].set(CONSTRUCTION);
				current_region->tile_vegetation_type[idx] = 0;
                current_region->calc_render(idx);
			}
		}
	});

	subscribe<cancel_build_request_message>([this] (cancel_build_request_message &msg) {
		if (msg.building_entity == 0) return;

		// Unclaim components
		for (auto &d : designations->buildings) {
			if (d.building_entity == msg.building_entity) {
				for (auto &c : d.component_ids) {
					unclaim_by_id(c.first);
					each<position_t, item_carried_t>([&c] (entity_t &carrier, position_t &pos, item_carried_t &carried) {
						if (carrier.id == c.first) {
							emit(drop_item_message{c.first, pos.x, pos.y, pos.z});
						}
					});
				}
			}
		}

		// Remove any settler references to the building
		each<settler_ai_t>([&msg] (entity_t &e, settler_ai_t &ai) {
			if (ai.job_type_major == JOB_CONST && ai.building_target && ai.building_target->building_entity == msg.building_entity) {
				for (auto &c : ai.building_target->component_ids) {
					unclaim_by_id(c.first);
					each<position_t, item_carried_t>([&c] (entity_t &carrier, position_t &pos, item_carried_t &carried) {
						if (carrier.id == c.first) {
							emit(drop_item_message{c.first, pos.x, pos.y, pos.z});
						}
					});
				}
				ai.job_type_major = JOB_IDLE;
				ai.job_status = "Idle";
			}
		});

		// Erase from vector
		designations->buildings.erase(std::remove_if(
			designations->buildings.begin(),
			designations->buildings.end(),
			[&msg] (building_designation_t a) { return a.building_entity == msg.building_entity; }
		), designations->buildings.end());

		// Delete entity
		delete_entity(msg.building_entity);
	});
}
Beispiel #21
0
  int main(int argc, char *argv[])
#endif
{
  /* C90 requires all vars to be declared at top of function */

  CoiHandle entity;
  CoiHandle node;
  CoiHandle light;
  CoiHandle rendersystem;
  CoiHandle renderwindow;
  CoiHandle viewport;

  CoiHandle plane;
  CoiHandle plane_entity;
  CoiHandle plane_node;

  CoiHandle terrain_group;
  CoiHandle terrain_iterator;
  CoiHandle import_data;
  CoiHandle image;

  float direction[3];
  float colour[4];

#if defined(LLCOI_TEST_USE_OPENINPUT)
  // Openinput
  oi_event evt;
  char openinput_window_params[100];
  unsigned int windowHnd = 0;

#if defined(PLATFORM_LINUX)
  Display *disp;
  Window win;
  unsigned int scrn;
#endif
#endif //LLCOI_TEST_USE_OPENINPUT

  keep_going = 1;
  long loop_x = 0;
  long loop_y = 0;

  // setup
  create_root("plugins.cfg", "ogre.cfg", "ogre.log");

  if (!(restore_config() || show_config_dialog()))
    {
      return 1;
    }

	setup_resources("resources.cfg");

  renderwindow = root_initialise(1, "Ogre Renderwindow");

  set_default_num_mipmaps(5);

  initialise_all_resource_groups();

  create_scene_manager("OctreeSceneManager", "The SceneManager");

  myCamera = create_camera(get_scene_manager(), "mycam");

  camera_set_position(myCamera, 1683, 50, 2116);

  camera_lookat(myCamera, 1963, -50, 1660);

  camera_set_near_clip_distance(myCamera, 1);
  camera_set_far_clip_distance(myCamera, 50000);

  viewport = add_viewport(myCamera);

  viewport_set_background_colour(viewport, 0, 0, 0);

  camera_set_aspect_ratio(myCamera, 800, 600);


  // entities

  plane = create_plane_from_normal(0, 1, 0, 0);
  mesh_manager_create_plane("ground", "General", plane, 1500, 1500, 20, 20, 1, 1, 5, 5, 0, 0, 1);
  plane_entity = create_entity(get_scene_manager(), "plane", "ground");
  entity_set_material_name(plane_entity, "Dev/Red");
  plane_node = create_child_scene_node(get_scene_manager(), "planenode");
  scene_node_attach_entity(plane_node, plane_entity);

  entity = create_entity(get_scene_manager(), "OgreHead", "ogrehead.mesh");

  node = create_child_scene_node(get_scene_manager(), "headNode");

  scene_node_attach_entity(node, entity);

  scene_manager_set_ambient_light_rgb(get_scene_manager(), 0.5f, 0.5f, 0.5f);

  light = create_light(get_scene_manager(), "mainLight");

  light_set_position(light, 20, 80, 50);


  // terrain
  create_terrain_global_options();
  terrain_group = create_terrain_group(get_scene_manager(), ALIGN_X_Z, 513, 12000.0f);
  terrain_group_set_filename_convention(terrain_group, "BasicTutorial3Terrain", "dat");
  terrain_group_set_origin(terrain_group, 0, 0, 0);

  // terrain defaults
  terrain_global_options_set_max_pixel_error(8);
  terrain_global_options_set_composite_map_distance(3000);

  terrain_global_options_set_light_map_direction_vector3(light_get_derived_direction(light));

  terrain_global_options_set_composite_map_ambient_colour(scene_manager_get_ambient_light(get_scene_manager()));// sm

  terrain_global_options_set_composite_map_diffuse_colour(light_get_diffuse_colour(light));// light

  import_data = terrain_group_get_default_import_settings(terrain_group);
  terrain_group_import_data_set_terrain_size(import_data, 513);
  terrain_group_import_data_set_world_size(import_data, 12000.0f);
  terrain_group_import_data_set_input_scale(import_data, 600);
  terrain_group_import_data_set_min_batch_size(import_data, 33);
  terrain_group_import_data_set_max_batch_size(import_data, 65);

  terrain_group_import_data_resize_layers(import_data, 3);
  terrain_group_import_data_set_layer(import_data, 0, 100, "nvidia/dirt_grayrocky_diffusespecular.dds", "nvidia/dirt_grayrocky_normalheight.dds");
  terrain_group_import_data_set_layer(import_data, 1, 30, "nvidia/grass_green-01_diffusespecular.dds", "nvidia/grass_green-01_normalheight.dds");
  terrain_group_import_data_set_layer(import_data, 2, 200, "nvidia/growth_weirdfungus-03_diffusespecular.dds", "nvidia/growth_weirdfungus-03_normalheight.dds");


  // define terrains
  for (loop_x; loop_x <= 0; ++loop_x)
    {
      for (loop_y; loop_y <= 0; ++loop_y)
        {
          if (resource_exists(terrain_group_get_resource_group(terrain_group), terrain_group_generate_filename(terrain_group, loop_x, loop_y)))
            {
              terrain_group_define_terrain(terrain_group, loop_x, loop_y);
            }
          else
            {
              image = create_image();
              image_load(image, "terrain.png");
              if (loop_x % 2 != 0)
                {
                  image_flip_around_y(image);
                }
              if (loop_y % 2 != 0)
                {
                  image_flip_around_x(image);
                }

              terrain_group_define_terrain_image(terrain_group, loop_x, loop_y, image);
              image_delete(image);
              image = NULL;
            }

        }
    }


  terrain_group_load_all_terrains(terrain_group, 1);

  // blend maps
  /*
  terrain_iterator = terrain_group_get_terrain_iterator(terrain_group);
  while(terrain_iterator_has_more_elements(terrain_iterator))
    {
      CoiHandle terrain = terrain_iterator_get_next(terrain_iterator);

      int blend_map_size = terrain_get_layer_blend_map_size(terrain);
      CoiHandle blend_map_0 = terrain_get_layer_blend_map(terrain, 1);
      CoiHandle blend_map_1 = terrain_get_layer_blend_map(terrain, 2);

      float min_height_0 = 70;
      float fade_dist_0 = 40;
      float min_height_1 = 70;
      float fade_dist_1 = 15;

      float* blend_1 = terrain_layer_blend_map_get_blend_pointer(blend_map_1);

      for(unsigned int y = 0; y < blend_map_size; ++y)
        {
          for(unsigned int x = 0; x < blend_map_size; ++x)
            {
              float tx, ty;
              terrain_layer_blend_map_convert_image_to_terrain_space(x, y, &tx, &ty);
              float height = terrain_get_height_at_terrain_position(tx, ty);
              float val = (height - min_height_0) / fade_dist_0;
              val = math_clamp_f(val, 0.0f, 1.0f);
              val = (height - min_height_1) / fade_dist_1;
              val = math_clamp_f(val, 0.0f, 1.0f);

              *blend_1++ = val;
            }
        }

      terrain_layer_blend_map_dirty(blend_map_0);
      terrain_layer_blend_map_dirty(blend_map_1);
      terrain_layer_blend_map_update(blend_map_0);
      terrain_layer_blend_map_update(blend_map_1);
    }
  */

  terrain_group_free_temporary_resources(terrain_group);
  // listeners

  add_frame_listener(frame_listener_test,EVENT_FRAME_RENDERING_QUEUED|EVENT_FRAME_STARTED);

	add_window_listener(renderwindow, window_event_listener_test);

  input_manager = create_input_system(render_window_get_hwnd(renderwindow));
  input_listener = create_input_listener();

  keyboard = create_keyboard_object(input_manager, 1);
  mouse = create_mouse_object(input_manager, 1);

  attach_keyboard_listener(keyboard, input_listener);
  attach_mouse_listener(mouse, input_listener);
  add_key_pressed_listener(input_listener, key_pressed_test);

  while(keep_going)
    {
      keyboard_capture(keyboard);
      mouse_capture(mouse);

      // Pump window messages for nice behaviour
      pump_messages();
      // Render a frame
      render_one_frame();

      if (render_window_closed(renderwindow))
        {
          keep_going = 0;
        }

    }

#if defined(LLCOI_TEST_USE_OPENINPUT)
  windowHnd = render_window_get_hwnd(renderwindow);

#if defined(PLATFORM_LINUX)
  disp = XOpenDisplay( NULL );
  scrn = DefaultScreen(disp);
  sprintf(openinput_window_params, "c:%u s:%u w:%u", (unsigned int)disp, (unsigned int)scrn, windowHnd);
#else
  sprintf(openinput_window_params, "c:%u s:%u w:%u", 0, 0, windowHnd);
#endif

  oi_init(openinput_window_params, 0);

  log_message("***************************");
  log_message("*** All Systems online! ***");
  log_message("***************************");

  //render_loop();
  while (keep_going)
    {
      // ask oi to wait for events
      oi_events_poll(&evt);
      switch(evt.type)
        {
        case OI_QUIT:
          // Quit
          keep_going = 0;
          break;

        case OI_KEYDOWN:
          // Keyboard button down
          //WTF?? Better way to check this, please..
          if(evt.key.keysym.sym == OIK_ESC)
            keep_going = 0;
          break;

        default:
          break;
        }
      // Pump window messages for nice behaviour
      pump_messages();
      // Render a frame
      render_one_frame();

      if (render_window_closed())
        {
          keep_going = 0;
        }
    }

  oi_close();
#endif //LLCOI_TEST_USE_OPENINPUT

	remove_window_listener(renderwindow);

  destroy_keyboard_object(input_manager, keyboard);
  destroy_mouse_object(input_manager, mouse);
  destroy_input_system(input_manager);
  release_engine();

  return 0;
}
Beispiel #22
0
void create_sentient(const int x, const int y, const int z, rltk::random_number_generator &rng, planet_t &planet, 
        region_t &region, const std::size_t person_id, const bool announce) 
{
    species_t species;
    game_stats_t stats;

    species.tag = planet.civs.unimportant_people[person_id].species_tag;
    std::cout << species.tag << "\n";
    auto species_finder = get_species_def(species.tag).get();
    if (planet.civs.unimportant_people[person_id].male) {
        species.gender = MALE;
    } else {
        species.gender = FEMALE;
    }

    stats.strength = rng.roll_dice(3,6) + sentient_stat_mod(species_finder, "str");
    stats.dexterity = rng.roll_dice(3,6) + sentient_stat_mod(species_finder, "dex");
    stats.constitution = rng.roll_dice(3,6) + sentient_stat_mod(species_finder, "con");
    stats.intelligence = rng.roll_dice(3,6) + sentient_stat_mod(species_finder, "int");
    stats.wisdom = rng.roll_dice(3,6) + sentient_stat_mod(species_finder, "wis");
    stats.charisma = rng.roll_dice(3,6) + sentient_stat_mod(species_finder, "cha");
    stats.comeliness = rng.roll_dice(3,6) + sentient_stat_mod(species_finder, "com");
    stats.ethics = rng.roll_dice(3,6) + sentient_stat_mod(species_finder, "eth");
    stats.age = planet.civs.unimportant_people[person_id].age;

    int base_hp = rng.roll_dice(1,10) + stat_modifier(stats.constitution);
	if (base_hp < 1) base_hp = 1;
	health_t health = create_health_component_sentient(species.tag, base_hp);


    int techlevel = planet.civs.civs[planet.civs.unimportant_people[person_id].civ_id].tech_level;
    if (techlevel > 2) techlevel = 2;
    const std::string profession_tag = OCCUPATION_TAGS[planet.civs.unimportant_people[person_id].occupation] + std::string("_") + 
        std::to_string(techlevel);
    std::cout << profession_tag << "\n";
    auto profession = get_native_professions(profession_tag).get();
    const int profidx = rng.roll_dice(1,profession.size())-1;    

    auto sentient = create_entity()
        ->assign(position_t{x,y,z})
        ->assign(name_t{ species_finder.name, profession[profidx].name })
        ->assign(renderable_t{ species_finder.glyph ,rltk::colors::WHITE, rltk::colors::BLACK })
        ->assign(viewshed_t{ 6, false, false })
        ->assign(std::move(stats))
        ->assign(std::move(health))
        ->assign(sentient_ai{stat_modifier(stats.dexterity), person_id, profession[profidx].aggression+5})
        ->assign(std::move(species));
    std::cout << "Sentient #" << sentient->id << "\n";
    if (announce) {
        emit_deferred(log_message{LOG().col(rltk::colors::CYAN)->text(species_finder.name)->text(" ")->text(profession[profidx].name)->col(rltk::colors::WHITE)->text(" has arrived.")->chars});
    }

    for (auto item : profession[profidx].starting_clothes) {
		if (std::get<0>(item) == 0 || (std::get<0>(item)==1 && species.gender == MALE) || (std::get<0>(item)==2 && species.gender == FEMALE) ) {            
			std::string item_name = std::get<2>(item);
			std::string slot_name = std::get<1>(item);
            auto cs = split(item_name, '/');
			item_location_t position = INVENTORY;
			if (slot_name == "head") position = HEAD;
			if (slot_name == "torso") position = TORSO;
			if (slot_name == "legs") position = LEGS;
			if (slot_name == "shoes") position = FEET;
            std::cout << "Created " << item_name << "\n";
            item_t clothing{cs[0]};
            clothing.material = get_material_by_tag(cs[1]).get();
            clothing.item_name = material_name(clothing.material) + std::string(" ") + clothing.item_name;
			create_entity()->assign(std::move(clothing))->assign(item_carried_t{position, sentient->id});
		}
	}

    if (profession[profidx].melee != "") {
        auto cs = split(profession[profidx].melee, '/');
        const std::string item_name = cs[0];
        auto finder = item_defs.find(item_name);
        std::cout << "Created " << item_name << "\n";
        item_t w{item_name};
        w.material = get_material_by_tag(cs[1]).get();
        w.item_name = material_name(w.material) + std::string(" ") + w.item_name;
        auto weapon = create_entity()->assign(std::move(w))->assign(item_carried_t{EQUIP_MELEE, sentient->id});
        weapon->component<item_t>()->stack_size = finder->second.stack_size;
        weapon->component<item_t>()->category = finder->second.categories;
        weapon->component<item_t>()->claimed = true;
    }
    if (profession[profidx].ranged != "") {
        auto cs = split(profession[profidx].ranged, '/');
        const std::string item_name = cs[0];
        auto finder = item_defs.find(item_name);
        std::cout << "Created " << item_name << "\n";
        item_t w{item_name};
        w.material = get_material_by_tag(cs[1]).get();
        w.item_name = material_name(w.material) + std::string(" ") + w.item_name;
        auto weapon = create_entity()->assign(std::move(w))->assign(item_carried_t{EQUIP_RANGED, sentient->id});
        weapon->component<item_t>()->stack_size = finder->second.stack_size;
        weapon->component<item_t>()->category = finder->second.categories;
        weapon->component<item_t>()->claimed = true;
    }
    if (profession[profidx].ammo != "") {
        auto cs = split(profession[profidx].ammo, '/');
        const std::string item_name = cs[0];
        auto finder = item_defs.find(item_name);
        std::cout << "Created " << item_name << "\n";
        item_t w{item_name};
        w.material = get_material_by_tag(cs[1]).get();
        w.item_name = material_name(w.material) + std::string(" ") + w.item_name;
        auto ammo = create_entity()->assign(std::move(w))->assign(item_carried_t{EQUIP_AMMO, sentient->id});
        ammo->component<item_t>()->stack_size = finder->second.stack_size;
        ammo->component<item_t>()->category = finder->second.categories;
        ammo->component<item_t>()->claimed = true;
    }

    planet.civs.civs[planet.civs.unimportant_people[person_id].civ_id].met_cordex = true;
}
Beispiel #23
0
/*
 * Initialise the 4.0 Changelog
 */
int changelog4_init ()
{
    int rc= 0; /* OK */
    Slapi_Backend *rbe;
	changeNumber first_change = 0UL, last_change = 0UL;
	int lderr;
	
    if (changelog4_create_be() < 0 )
	{
		rc= -1;
	}
	else
	{
	rc = changelog4_start_be ();
	}

    if(rc == 0)
	{
        rbe = get_repl_backend();
    	if(rbe!=NULL)
    	{
    	    /* We have a Change Log. Check it's valid. */
			/* changelog has to be started before its 
			   data version can be read */ 
            const char *sdv= get_server_dataversion();
    	    const char *cdv= get_changelog_dataversion();
			char *suffix = changelog4_get_suffix ();
			if(!cdv || strcmp(sdv,cdv)!=0)
			{
				
			    /* The SDV and CDV are not the same.  The Change Log is invalid. 
			       It must be removed. */
				/* ONREPL - currently we go through this code when the changelog
				   is first created because we can't tell new backend from the
				   existing one.*/
				rc	= changelog4_close();
				rc	= changelog4_remove();

				/* now restart the changelog */
				changelog4_start_be ();

				create_entity( suffix, "extensibleobject");
                /* Write the Server Data Version onto the changelog suffix entry */
                /* JCMREPL - And the changelog database version number */
                set_changelog_dataversion(sdv);
				slapi_ch_free ((void **)&suffix);

			}
		}
	}
    
	if(rc != 0)
	{
		slapi_log_err(SLAPI_LOG_PLUGIN, repl_plugin_name, 
						"An error occurred configuring the changelog database\n" );
    }

	first_change = replog_get_firstchangenum( &lderr );
	last_change = replog_get_lastchangenum( &lderr );
	ldapi_initialize_changenumbers( first_change, last_change );

    return rc;
}
Beispiel #24
0
static int create_fd_entity(cache_handle_t *h, request_rec *r,
                            const char *key, apr_off_t len)
{
    return create_entity(h, CACHE_TYPE_FILE, r, key, len);
}