bubel-ecs/demos/source/demos/space_invaders.d
2020-05-05 16:56:51 +02:00

904 lines
No EOL
29 KiB
D

module demos.space_invaders;
import app;
import bindbc.sdl;
import cimgui.cimgui;
import bubel.ecs.attributes;
import bubel.ecs.core;
import bubel.ecs.entity;
import bubel.ecs.manager;
import bubel.ecs.std;
import ecs_utils.gfx.texture;
import ecs_utils.math.vector;
import ecs_utils.utils;
enum float px = 1.0/512.0;
extern(C):
/*#######################################################################################################################
------------------------------------------------ Types ------------------------------------------------------------------
#######################################################################################################################*/
struct SpaceInvaders
{
__gshared const (char)* tips = "Use \"WASD\" keys to move and \"Space\" for shooting.";
EntityTemplate* enemy_tmpl;
EntityTemplate* ship_tmpl;
EntityTemplate* laser_tmpl;
Texture texture;
bool move_system = true;
bool draw_system = true;
const vec2 map_size = vec2(400,300);
const float cell_size = 60;
}
struct SceneGrid
{
struct Element
{
EntityID entity;
int guild;
vec2 min;
vec2 max;
}
struct Cell
{
Element[20] elements;
}
void create()
{
cells_count.x = cast(int)((space_invaders.map_size.x - 0.01f) / space_invaders.cell_size) + 1;
cells_count.y = cast(int)((space_invaders.map_size.y - 0.01f) / space_invaders.cell_size) + 1;
cells = Mallocator.makeArray!Cell(cells_count.x * cells_count.y);
}
void destory()
{
if(cells)
{
Mallocator.dispose(cells);
cells = null;
}
}
ivec2 cells_count;
Cell[] cells;
}
enum Direction : byte
{
up,
down,
left,
right
}
/*#######################################################################################################################
------------------------------------------------ Components ------------------------------------------------------------------
#######################################################################################################################*/
struct CLocation
{
mixin ECS.Component;
alias value this;
vec2 value;
}
struct CScale
{
mixin ECS.Component;
///use component as it value
alias value this;
vec2 value = vec2(16,16);
}
struct CTexture
{
mixin ECS.Component;
Texture tex;
vec4 coords = vec4(0,0,0,1);
}
struct CVelocity
{
mixin ECS.Component;
alias value this;
vec2 value = vec2(0,0);
}
struct CInput
{
mixin ECS.Component;
}
struct CEnemy
{
mixin ECS.Component;
}
struct CShip
{
mixin ECS.Component;
}
struct CAutoShoot
{
mixin ECS.Component;
}
struct CGuild
{
mixin ECS.Component;
int guild;
}
struct CLaser
{
mixin ECS.Component;
float damage = 1.0f;
}
struct CLaserWeapon
{
mixin ECS.Component;
ubyte level = 1;
float shoot_time = 0;
}
struct CShootDirection
{
mixin ECS.Component;
Direction direction;
}
struct CSideMove
{
mixin ECS.Component;
byte group = -1;
}
/*#######################################################################################################################
------------------------------------------------ Events ------------------------------------------------------------------
#######################################################################################################################*/
struct EChangeDirection
{
mixin ECS.Event;
this(Direction direction)
{
this.direction = direction;
}
Direction direction;
}
/*#######################################################################################################################
------------------------------------------------ Systems ------------------------------------------------------------------
#######################################################################################################################*/
struct DrawSystem
{
mixin ECS.System!1;
struct EntitiesData
{
uint length;
@readonly CTexture[] textures;
@readonly CLocation[] locations;
@readonly CScale[] scale;
}
void onUpdate(EntitiesData data)
{
foreach(i; 0..data.length)
{
launcher.renderer.draw(data.textures[i].tex, data.locations[i].value, data.scale[i], data.textures[i].coords, 0, 0 , 0);
//draw(renderer, data.textures[i].tex, data.locations[i], vec2(32,32), vec4(0,0,1,1));
}
}
}
struct CollisionSystem
{
mixin ECS.System;
struct EntitiesData
{
}
void onUpdate(EntitiesData data)
{
}
}
struct LaserShootingSystem
{
mixin ECS.System!32;
bool shoot = false;
float[10] laser_shoot_times = [2000,1500,1000,700,500,300,100,50,10,1];
CLocation* laser_location;
CVelocity* laser_velocity;
struct EntitiesData
{
///variable named "length" contain entites count
uint length;
@readonly CShootDirection[] shoot_direction;
@readonly @optional CAutoShoot[] auto_shoot;
@readonly CLocation[] location;
CLaserWeapon[] laser;
}
///Called inside "registerSystem" function
/*void onCreate()
{
laser_location = space_invaders.laser_tmpl.getComponent!CLocation;
}*/
bool onBegin()
{
laser_location = space_invaders.laser_tmpl.getComponent!CLocation;
laser_velocity = space_invaders.laser_tmpl.getComponent!CVelocity;
if(launcher.getKeyState(SDL_SCANCODE_SPACE))
{
shoot = true;
}
else shoot = false;
return true;
}
void onUpdate(EntitiesData data)
{
//conditional branch for whole entities block
if(shoot || data.auto_shoot)
{
foreach(i;0..data.length)
{
CLaserWeapon* laser = &data.laser[i];
laser.shoot_time += launcher.delta_time;
while(laser.shoot_time > laser_shoot_times[laser.level - 1])
{
laser.shoot_time -= laser_shoot_times[laser.level - 1];
laser_location.value = data.location[i];
laser_velocity.value = vec2(randomf()*0.5-0.25,data.shoot_direction[i].direction == Direction.up ? 1.0 : -1.0);
launcher.manager.addEntity(space_invaders.laser_tmpl);
}
}
}
else
{
foreach(i;0..data.length)
{
CLaserWeapon* laser = &data.laser[i];
laser.shoot_time += launcher.delta_time;
if(laser.shoot_time > laser_shoot_times[laser.level - 1])laser.shoot_time = laser_shoot_times[laser.level - 1];
}
}
}
}
struct ChangeDirectionSystem
{
mixin ECS.System!32;
Direction[8] groups_directions;
bool has_changes;
struct EntitiesData
{
uint length;
const (Entity)[] entities;
const (CLocation)[] locations;
CVelocity[] velocity;
const(CSideMove)[] side_move;
}
void onCreate()
{
foreach(ref direction; groups_directions)
{
direction = cast(Direction)-1;
}
}
/*bool onBegin()
{
foreach(direction; groups_directions)
{
if(direction != cast(Direction)-1)//return true;
{
has_changes = true;
break;
}
}
return true;
}*/
void onEnd()
{
if(has_changes)
{
foreach(ref direction; groups_directions)
{
direction = cast(Direction)-1;
}
}
has_changes = false;
foreach(ref direction; groups_directions)
{
if(direction != cast(Direction)-1)
{
has_changes = true;
//direction = cast(Direction)-1;
}
}
/*foreach(ref direction; groups_directions)
{
direction = cast(Direction)-1;
}*/
}
void onUpdate(EntitiesData data)
{
//if(!data.side_move)return;
if(has_changes)
foreach(i;0..data.length)
{
byte group = data.side_move[i].group;
if(group == -1)
{
if(data.locations[i].x < 0)
{
if(data.velocity[i].x < 0)data.velocity[i].x = -data.velocity[i].x;
}
else if(data.locations[i].x > space_invaders.map_size.x)
{
if(data.velocity[i].x > 0)data.velocity[i].x = -data.velocity[i].x;
}
}
else
{
Direction direction = groups_directions[group];
if(direction != cast(Direction)-1)
{
CVelocity* velocity = &data.velocity[i];
final switch(direction)
{
case Direction.up:
if(velocity.value.y > 0)velocity.value.y = -velocity.value.y;
break;
case Direction.down:
if(velocity.value.y < 0)velocity.value.y = -velocity.value.y;
break;
case Direction.left:
if(velocity.value.x > 0)velocity.value.x = -velocity.value.x;
break;
case Direction.right:
if(velocity.value.x < 0)velocity.value.x = -velocity.value.x;
break;
}
}
}
}
else
{
foreach(i;0..data.length)
{
if(data.locations[i].x < 0)
{
if(data.side_move[i].group == -1)
{
if(data.velocity[i].x < 0)data.velocity[i].x = -data.velocity[i].x;
}
else
{
groups_directions[data.side_move[i].group] = Direction.right;
}
}
else if(data.locations[i].x > space_invaders.map_size.x)
{
if(data.side_move[i].group == -1)
{
if(data.velocity[i].x > 0)data.velocity[i].x = -data.velocity[i].x;
}
else
{
groups_directions[data.side_move[i].group] = Direction.left;
}
}
//if(data.locations[i].y < 0) data.locations[i].y = 0;
//else if(data.locations[i].y > space_invaders.map_size.y)data.locations[i].y = space_invaders.map_size.y;
}
}
}
void handleEvent(Entity* entity, EChangeDirection event)
{
CSideMove* side_move = entity.getComponent!CSideMove;
if(side_move && side_move.group != -1)
{
groups_directions[side_move.group] = event.direction;
return;
}
//Entity* entity = launcher.manager.getEntity(event.entity_id);
CVelocity* velocity = entity.getComponent!CVelocity;
final switch(event.direction)
{
case Direction.up:
if(velocity.value.y > 0)velocity.value.y = -velocity.value.y;
break;
case Direction.down:
if(velocity.value.y < 0)velocity.value.y = -velocity.value.y;
break;
case Direction.left:
if(velocity.value.x > 0)velocity.value.x = -velocity.value.x;
break;
case Direction.right:
if(velocity.value.x < 0)velocity.value.x = -velocity.value.x;
break;
}
}
}
struct ClampPositionSystem
{
mixin ECS.System!32;
mixin ECS.ExcludedComponents!(CSideMove);
struct EntitiesData
{
uint length;
const (Entity)[] entities;
//components are treated as required by default
CLocation[] locations;
@optional const (CLaser)[] laser;
//@optional CVelocity[] velocity;
//@optional const (CSideMove)[] side_move;
}
//ChangeDirectionSystem change_direction_system;
void onUpdate(EntitiesData data)
{
if(data.laser)
{
foreach(i;0..data.length)
{
if(data.locations[i].x < 0 || data.locations[i].x > space_invaders.map_size.x ||
data.locations[i].y < 0 || data.locations[i].y > space_invaders.map_size.y)launcher.manager.removeEntity(data.entities[i].id);
}
}
/*else if(data.side_move)
{
foreach(i;0..data.length)
{
if(data.locations[i].x < 0)
{
//data.locations[i].x = 0;
//launcher.manager.sendEvent(data.entities[i].id,EChangeDirection(Direction.right));
if(data.side_move[i].group == -1)
{
if(data.velocity[i].x < 0)data.velocity[i].x = -data.velocity[i].x;
}
else
{
change_direction_system.groups_directions[data.side_move[i].group] = Direction.left;
}
}
else if(data.locations[i].x > space_invaders.map_size.x)
{
//data.locations[i].x = space_invaders.map_size.x;
//launcher.manager.sendEvent(data.entities[i].id,EChangeDirection(Direction.left));
if(data.side_move[i].group == -1)
{
if(data.velocity[i].x > 0)data.velocity[i].x = -data.velocity[i].x;
}
else
{
change_direction_system.groups_directions[data.side_move[i].group] = Direction.right;
}
}
if(data.locations[i].y < 0) data.locations[i].y = 0;
else if(data.locations[i].y > space_invaders.map_size.y)data.locations[i].y = space_invaders.map_size.y;
}
}*/
else
{
foreach(i;0..data.length)
{
if(data.locations[i].x < 0)data.locations[i].x = 0;
else if(data.locations[i].x > space_invaders.map_size.x)data.locations[i].x = space_invaders.map_size.x;
if(data.locations[i].y < 0)data.locations[i].y = 0;
else if(data.locations[i].y > space_invaders.map_size.y)data.locations[i].y = space_invaders.map_size.y;
}
}
}
}
struct MovementSystem
{
mixin ECS.System!32;
struct EntitiesData
{
uint length;
//read only components can be marked with @readonly attribute or with const expression instead
const (CVelocity)[] velocity;
//components are treated as required by default
CLocation[] locations;
//@optional const (CLaser)[] laser;
const (Entity)[] entities;
@optional CSideMove[] side_move;
}
void onUpdate(EntitiesData data)
{
foreach(i;0..data.length)
{
data.locations[i].x += data.velocity[i].x * launcher.delta_time * 0.5;
data.locations[i].y += data.velocity[i].y * launcher.delta_time * 0.5;
}
}
}
/**
*System is responsible for movement of objects with CInput component.
*In this example every entity has same speed when using movement system.
*/
struct InputMovementSystem
{
mixin ECS.System!32;
vec2 move_vector;
struct EntitiesData
{
uint length;
//read only components can be marked with @readonly attribute or with const expression instead
const (CInput)[] input;
//components are treated as required by default
CLocation[] locations;
CTexture[] textures;
}
/**
*onBegin gives opportunity to check keys once and call update on entities only when
*one key is pressed.
*/
bool onBegin()
{
move_vector = vec2(0,0);
if(launcher.getKeyState(SDL_SCANCODE_W))
{
move_vector = vec2(0,1);
return true;
}
else if(launcher.getKeyState(SDL_SCANCODE_S))
{
move_vector = vec2(0,-1);
return true;
}
else if(launcher.getKeyState(SDL_SCANCODE_A))
{
move_vector = vec2(-1,0);
return true;
}
else if(launcher.getKeyState(SDL_SCANCODE_D))
{
move_vector = vec2(1,0);
return true;
}
//don't call system update because no key pressed
return true;
}
/**
*Update is called multiple times in one "manager.update()" call.
*Number of "onUpdate" calls is count of buffers which must be updated during pass.
*When multithreading is used, number of "onUpdate" calls can be greater due to fact that
*JobSystem can split buffers for better data packing.
*/
void onUpdate(EntitiesData data)
{
if(move_vector.x == 0)
{
foreach(i; 0..data.length)
{
data.textures[i].coords = vec4(0*px,80*px,48*px,32*px);
}
return;
}
//move every entity using movement vector
foreach(i; 0..data.length)
{
data.locations[i].x += move_vector.x * launcher.delta_time * 0.25;
data.locations[i].y += move_vector.y * launcher.delta_time * 0.25;
if(move_vector.x > 0)data.textures[i].coords = vec4(48*px,80*px,48*px,32*px);
else data.textures[i].coords = vec4(0*px,80*px,48*px,32*px);
}
}
}
/*#######################################################################################################################
------------------------------------------------ Functions ------------------------------------------------------------------
#######################################################################################################################*/
__gshared SpaceInvaders* space_invaders;
void spaceInvadersStart()
{
space_invaders = Mallocator.make!SpaceInvaders;
space_invaders.texture.create();
space_invaders.texture.load("assets/textures/atlas.png");
launcher.manager.beginRegister();
launcher.manager.registerComponent!CLocation;
launcher.manager.registerComponent!CTexture;
launcher.manager.registerComponent!CInput;
launcher.manager.registerComponent!CShip;
launcher.manager.registerComponent!CEnemy;
launcher.manager.registerComponent!CScale;
launcher.manager.registerComponent!CShootDirection;
launcher.manager.registerComponent!CAutoShoot;
launcher.manager.registerComponent!CLaserWeapon;
launcher.manager.registerComponent!CVelocity;
launcher.manager.registerComponent!CLaser;
launcher.manager.registerComponent!CSideMove;
launcher.manager.registerEvent!EChangeDirection;
//launcher.manager.registerSystem!MoveSystem(0);
launcher.manager.registerSystem!DrawSystem(100);
launcher.manager.registerSystem!InputMovementSystem(-100);
launcher.manager.registerSystem!LaserShootingSystem(0);
launcher.manager.registerSystem!MovementSystem(0);
launcher.manager.registerSystem!ClampPositionSystem(1);
launcher.manager.registerSystem!ChangeDirectionSystem(0);
launcher.manager.endRegister();
launcher.gui_manager.addSystem(DrawSystem.system_id,"Draw System");
launcher.gui_manager.addSystem(InputMovementSystem.system_id,"Input Movement");
launcher.gui_manager.addSystem(LaserShootingSystem.system_id,"Laser Shooting");
launcher.gui_manager.addSystem(MovementSystem.system_id,"Movement System");
launcher.gui_manager.addSystem(ClampPositionSystem.system_id,"Clamp Position System");
launcher.gui_manager.addSystem(ChangeDirectionSystem.system_id,"Change Direction System");
//launcher.manager.getSystem(CleanSystem.system_id).disable();
{
ushort[7] components = [CLocation.component_id, CTexture.component_id, CInput.component_id, CShip.component_id, CScale.component_id, CLaserWeapon.component_id, CShootDirection.component_id];
space_invaders.ship_tmpl = launcher.manager.allocateTemplate(components);
CScale* scale_comp = space_invaders.ship_tmpl.getComponent!CScale;
scale_comp.value = vec2(48,32);
CTexture* tex_comp = space_invaders.ship_tmpl.getComponent!CTexture;
tex_comp.tex = space_invaders.texture;//ship_tex;
tex_comp.coords = vec4(0*px,80*px,48*px,32*px);
CLocation* loc_comp = space_invaders.ship_tmpl.getComponent!CLocation;
loc_comp.value = vec2(64,64);
CLaserWeapon* weapon = space_invaders.ship_tmpl.getComponent!CLaserWeapon;
weapon.level = 10;
launcher.manager.addEntity(space_invaders.ship_tmpl);
}
{
ushort[5] components = [CLocation.component_id, CTexture.component_id, CVelocity.component_id, CScale.component_id, CLaser.component_id];
space_invaders.laser_tmpl = launcher.manager.allocateTemplate(components);
CTexture* tex_comp = space_invaders.laser_tmpl.getComponent!CTexture;
tex_comp.tex = space_invaders.texture;//laser_tex;
tex_comp.coords = vec4(0*px,24*px,2*px,8*px);
CScale* scale_comp = space_invaders.laser_tmpl.getComponent!CScale;
scale_comp.value = vec2(2,8);
CVelocity* vel_comp = space_invaders.laser_tmpl.getComponent!CVelocity;
vel_comp.value = vec2(0,1);
}
EntityTemplate* enemy_tmpl;
EntityTemplate* grouped_tmpl;
EntityID enemy_id;
EntityID grouped_id;
{
ushort[8] components = [CVelocity.component_id, CAutoShoot.component_id, CLocation.component_id, CTexture.component_id, CScale.component_id, CLaserWeapon.component_id, CEnemy.component_id, CShootDirection.component_id];//, CVelocity.component_id];
space_invaders.enemy_tmpl = launcher.manager.allocateTemplate(components);
CTexture* tex_comp = space_invaders.enemy_tmpl.getComponent!CTexture;
tex_comp.tex = space_invaders.texture;//ship_tex;
tex_comp.coords = vec4(32*px,32*px,16*px,16*px);
CLocation* loc_comp = space_invaders.enemy_tmpl.getComponent!CLocation;
loc_comp.value = vec2(64,space_invaders.map_size.y - 16);
CShootDirection* shoot_dir_comp = space_invaders.enemy_tmpl.getComponent!CShootDirection;
shoot_dir_comp.direction = Direction.down;
CVelocity* vel_comp = space_invaders.enemy_tmpl.getComponent!CVelocity;
vel_comp.value = vec2(0.1,0);
Entity* current_entity;
current_entity = launcher.manager.addEntity(space_invaders.enemy_tmpl);
launcher.manager.addComponents(current_entity.id,CSideMove(0));
loc_comp.value = vec2(128,space_invaders.map_size.y - 16);
current_entity = launcher.manager.addEntity(space_invaders.enemy_tmpl);
launcher.manager.addComponents(current_entity.id,CSideMove(-1));
enemy_id = current_entity.id;
//enemy_tmpl = launcher.manager.allocateTemplate(current_entity.id);
loc_comp.value = vec2(256,space_invaders.map_size.y - 16);
launcher.manager.addEntity(space_invaders.enemy_tmpl);
loc_comp.value = vec2(0,space_invaders.map_size.y - 16);
current_entity = launcher.manager.addEntity(space_invaders.enemy_tmpl);
launcher.manager.addComponents(current_entity.id,CSideMove(0));
grouped_id = current_entity.id;
//grouped_tmpl = launcher.manager.allocateTemplate(current_entity.id);
}
launcher.manager.commit();
enemy_tmpl = launcher.manager.allocateTemplate(enemy_id);
grouped_tmpl = launcher.manager.allocateTemplate(grouped_id);
launcher.gui_manager.addTemplate(space_invaders.ship_tmpl,"Ship");
launcher.gui_manager.addTemplate(enemy_tmpl,"Enemy");
launcher.gui_manager.addTemplate(grouped_tmpl,"Grouped enemy");
launcher.gui_manager.addTemplate(space_invaders.laser_tmpl,"Laser");
}
void spaceInvadersEnd()
{
launcher.manager.getSystem(DrawSystem.system_id).disable();
launcher.manager.getSystem(InputMovementSystem.system_id).disable();
launcher.manager.getSystem(LaserShootingSystem.system_id).disable();
launcher.manager.getSystem(MovementSystem.system_id).disable();
launcher.manager.getSystem(ClampPositionSystem.system_id).disable();
launcher.manager.freeTemplate(space_invaders.enemy_tmpl);
Mallocator.dispose(space_invaders);
}
void spaceInvadersTool(vec2 position, Tool tool, int size)
{
switch(tool)
{
case Tool.entity_spawner:
{
EntityTemplate* tmpl = launcher.gui_manager.getSelectedTemplate();
CLocation* location = tmpl.getComponent!CLocation;
if(location)
{
position.x += (randomf - 0.5) * size;
position.y += (randomf - 0.5) * size;
*location = position;
}
launcher.manager.addEntity(tmpl);
}
break;
default:
break;
}
}
void spaceInvadersEvent(SDL_Event* event)
{
}
bool spaceInvadersLoop()
{
launcher.render_position = (vec2(launcher.window_size.x,launcher.window_size.y)*launcher.scalling - vec2(400,300)) * 0.5;
/*if(launcher.show_demo_wnd)
{
igSetNextWindowPos(ImVec2(800 - 260, 30), ImGuiCond_Once, ImVec2(0,0));
igSetNextWindowSize(ImVec2(250, 0), ImGuiCond_Once);
if(igBegin("Simple",&launcher.show_demo_wnd,0))
{
if(igCheckbox("Move system",&simple.move_system))
{
if(simple.move_system)launcher.manager.getSystem(MoveSystem.system_id).enable();
else launcher.manager.getSystem(MoveSystem.system_id).disable();
}
if(igCheckbox("Draw system",&simple.draw_system))
{
if(simple.draw_system)launcher.manager.getSystem(DrawSystem.system_id).enable();
else launcher.manager.getSystem(DrawSystem.system_id).disable();
}
igPushButtonRepeat(true);
igColumns(3,null,0);
if(igButton("Spawn",ImVec2(-1,0)))
{
spawnEntity();
}
igNextColumn();
if(igButton("+10",ImVec2(-1,0)))
{
foreach(i;0..10)spawnEntity();
}
igNextColumn();
if(igButton("+100",ImVec2(-1,0)))
{
foreach(i;0..100)spawnEntity();
}
igPopButtonRepeat();
igColumns(1,null,0);
if(igButton("Clear",ImVec2(-1,0)))
{
launcher.manager.getSystem(CleanSystem.system_id).enable();
launcher.manager.begin();
launcher.manager.update();
launcher.manager.end();
launcher.manager.getSystem(CleanSystem.system_id).disable();
}
}
igEnd();
}*/
/*if(launcher.show_tips)
{
igSetNextWindowPos(ImVec2(800 - 550, 80), ImGuiCond_Once, ImVec2(0,0));
igSetNextWindowSize(ImVec2(300, 0), ImGuiCond_Once);
if(igBegin("Tips",&launcher.show_tips,ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
{
igTextWrapped("Use \"space\" to spwan entities.\n\nSystems can be enabled/disabled from \"Simple\" window.");
}
igEnd();
}*/
launcher.manager.begin();
if(launcher.multithreading)
{
launcher.job_updater.begin();
launcher.manager.updateMT();
launcher.job_updater.call();
}
else
{
launcher.manager.update();
}
launcher.manager.end();
/*foreach(i;0..1000)//13000)
{
launcher.renderer.draw(simple.texture,vec2(i%100*32,i/100*32),vec2(32,32),vec4(0,0,1,1),0.0);
}*/
return true;
}