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;

import std.array : staticArray;

enum float px = 1.0/512.0;

extern(C):

enum ShootGridDependency = "ShootGridDependency";

/*#######################################################################################################################
------------------------------------------------ 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;

    ShootGrid* shoot_grid;

    bool move_system = true;
    bool draw_system = true;
    
    const vec2 map_size = vec2(400,300);
    const float cell_size = 60;

    ~this() @nogc nothrow
    {
        if(shoot_grid)Mallocator.dispose(shoot_grid);
        launcher.manager.freeTemplate(enemy_tmpl);
        launcher.manager.freeTemplate(ship_tmpl);
        launcher.manager.freeTemplate(laser_tmpl);
        texture.destory();
    }
}

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;

    byte 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;
}

struct CDepth
{
    mixin ECS.Component;

    alias depth this;

    short depth;
}

struct CShootGrid
{
    mixin ECS.Component;
}

struct CHitPoints
{
    mixin ECS.Component;

    alias value this;

    int value = 10;
}

struct CHitMark
{
    mixin ECS.Component;

    alias value this;

    ubyte value = 0;
}

/*#######################################################################################################################
------------------------------------------------ Events ------------------------------------------------------------------
#######################################################################################################################*/

struct EChangeDirection
{
    mixin ECS.Event;

    this(Direction direction)
    {
        this.direction = direction;
    }

    Direction direction;
}

struct EDamage
{
    mixin ECS.Event;

    this(uint damage)
    {
        this.damage = damage;
    }

    uint damage = 0;
}

/*#######################################################################################################################
------------------------------------------------ Systems ------------------------------------------------------------------
#######################################################################################################################*/

struct ShootGrid
{

    ~this() @nogc nothrow
    {
        if(nodes)Mallocator.dispose(nodes);
        if(masks)Mallocator.dispose(masks);
    }

    struct Node
    {
        alias entity this;

        EntityID entity;
    }

    void create(ivec2 nodes_count, vec2 node_size)
    {
        this.size = nodes_count;
        this.node_size = node_size;
        inv_node_size = vec2(1.0/node_size.x, 1.0/node_size.y);
        nodes = Mallocator.makeArray!Node(nodes_count.x * nodes_count.y);
        masks = Mallocator.makeArray!ubyte(nodes.length);
    }

    void mark(EntityID id, vec2 beg, vec2 end, byte mask)
    {
        ivec2 ibeg = cast(ivec2)(beg * inv_node_size);
        ivec2 iend = cast(ivec2)((end * inv_node_size) + 0.5);
        if(ibeg.x < 0)ibeg.x = 0;
        if(ibeg.y < 0)ibeg.y = 0;
        if(iend.x > size.x)iend.x = size.x;
        if(iend.y > size.y)iend.y = size.y;
        foreach(i; ibeg.y .. iend.y)
        {
            foreach(j; ibeg.x .. iend.x)
            {
                nodes[i * size.x + j] = id;
                masks[i * size.x +j] = mask;
            }
        }
    }

    void clear()
    {
        size_t size = nodes.length * EntityID.sizeof;
        memset(nodes.ptr, 0, size);
        memset(masks.ptr, 0, masks.length);
    }

    bool test(out EntityID id, vec2 beg, vec2 end)
    {
        ivec2 ibeg = cast(ivec2)(beg * inv_node_size);
        ivec2 iend = cast(ivec2)((end * inv_node_size) + 0.5);
        if(ibeg.x < 0)ibeg.x = 0;
        if(ibeg.y < 0)ibeg.y = 0;
        if(iend.x > size.x)iend.x = size.x;
        if(iend.y > size.y)iend.y = size.y;
        foreach(i; ibeg.y .. iend.y)
        {
            foreach(j; ibeg.x .. iend.x)
            {
                if(nodes[i * size.x + j].id != 0)
                {
                    id = nodes[i * size.x + j];
                    return true;
                }
            }
        }
        return false;
    }

    bool test(out EntityID id, vec2 pos, ubyte mask)
    {
        ivec2 ipos = cast(ivec2)(pos * inv_node_size - 0.5);
        if(ipos.x < 0)ipos.x = 0;
        if(ipos.y < 0)ipos.y = 0;
        if(ipos.x >= size.x)ipos.x = size.x - 1;
        if(ipos.y >= size.y)ipos.y = size.y - 1;
        size_t index = ipos.y * size.x + ipos.x;
        if((masks[index] & mask) == 0)return false;
        if(nodes[index].id != 0)
        {
            id = nodes[index];
            return true;
        }
        return false;
    }

    vec2 inv_node_size;
    ivec2 size;
    vec2 node_size;
    Node[] nodes;
    ubyte[] masks;
}

struct ShootGridCleaner
{
    mixin ECS.System!1;

    struct EntitiesData
    {

    }

    void onUpdate(EntitiesData data)
    {
        if(space_invaders.shoot_grid)space_invaders.shoot_grid.clear();
    }
}

struct ShootGridManager
{
    mixin ECS.System!128;

    mixin ECS.WritableDependencies!(ShootGridDependency);

    struct EntitiesData
    {
        uint length;
        uint thread_id;
        const (Entity)[] entity;
        @readonly CLocation[] locations;
        @readonly CScale[] scale;
        @readonly CShootGrid[] grid_flag;
        @readonly CGuild[] guild;
    }

    ShootGrid* grid;

    void onCreate()
    {
        grid = space_invaders.shoot_grid;
    }

    bool onBegin()
    {
        if(!grid)return false;
        //grid.clear();
        return true;
    }

    void onUpdate(EntitiesData data)
    {
        foreach(i; 0..data.length)
        {
            vec2 half_scale = data.scale[i] * 0.5;
            grid.mark(data.entity[i].id, data.locations[i] - half_scale, data.locations[i] + half_scale, cast(ubyte)(1 << data.guild[i].guild));
        }
    }
}

struct DrawSystem
{
    mixin ECS.System!32;

    struct EntitiesData
    {
        uint length;
        uint thread_id;
        @readonly CTexture[] textures;
        @readonly CLocation[] locations;
        @readonly CScale[] scale;
        @readonly @optional CDepth[] depth;
        @readonly @optional CHitMark[] hit_mark;
    }

    void onUpdate(EntitiesData data)
    {
        if(!data.depth)
        {
            if(data.hit_mark)
            {
                foreach(i; 0..data.length)
                {
                    uint color = 0x80808080 + 0x01010101 * data.hit_mark[i];
                    launcher.renderer.draw(data.textures[i].tex, data.locations[i].value, data.scale[i], data.textures[i].coords, cast(short)data.locations[i].y, color, 0, 0, 0, data.thread_id);
                }
            }
            else
            {
                foreach(i; 0..data.length)
                {
                    launcher.renderer.draw(data.textures[i].tex, data.locations[i].value, data.scale[i], data.textures[i].coords, cast(short)data.locations[i].y, 0x80808080, 0, 0, 0, data.thread_id);
                }
            }
        }
        else
        {
            if(data.hit_mark)
            {
                foreach(i; 0..data.length)
                {
                    uint color = 0x80808080 + 0x01010101 * data.hit_mark[i];
                    launcher.renderer.draw(data.textures[i].tex, data.locations[i].value, data.scale[i], data.textures[i].coords, cast(short)(data.depth[i] * 64 + data.locations[i].y), color, 0, 0, 0, data.thread_id);
                }
            }
            else
            {
                foreach(i; 0..data.length)
                {
                    launcher.renderer.draw(data.textures[i].tex, data.locations[i].value, data.scale[i], data.textures[i].coords, cast(short)(data.depth[i] * 64 + data.locations[i].y), 0x80808080, 0, 0, 0, data.thread_id);
                }
            }
        }
        if(data.thread_id == 0)launcher.renderer.pushData();
    }
}

struct CollisionSystem
{
    mixin ECS.System;

    struct EntitiesData
    {

    }

    void onUpdate(EntitiesData data)
    {

    }
}

struct LaserShootingSystem
{
    mixin ECS.System!32;

    bool shoot = false;
    static float[22] laser_shoot_times = [2000,1500,1000,700,500,350,250,170,130,80,50,25,15,10,5,2.5,2,1,0.8,0.5,0.3,0.1];

    CLocation* laser_location;
    CVelocity* laser_velocity;
    CGuild* laser_guild;
    
    struct EntitiesData
    {
        ///variable named "length" contain entites count
        uint length;
        @readonly CShootDirection[] shoot_direction;
        @readonly @optional CAutoShoot[] auto_shoot;
        @readonly CLocation[] location;
        @readonly CGuild[] guild;
        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;
        laser_guild = space_invaders.laser_tmpl.getComponent!CGuild;
        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);
                    laser_guild.guild = data.guild[i].guild;
                    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 LaserCollisionSystem
{
    mixin ECS.System!32;

    mixin ECS.ReadOnlyDependencies!(ShootGridDependency);

    struct EntitiesData
    {
        ///variable named "length" contain entites count
        uint length;
        const (Entity)[] entity;
        @readonly CLocation[] location;
        @readonly CLaser[] laser;
        @readonly CGuild[] guild;
    }

    void onUpdate(EntitiesData data)
    {
        EntityID id;
        foreach(i; 0..data.length)
        {
            if(space_invaders.shoot_grid.test(id, data.location[i], cast(ubyte)(~(1 << data.guild[i].guild))))
            {
                launcher.manager.sendEvent(id, EDamage(1));
                launcher.manager.removeEntity(data.entity[i].id);
            }
        }
    }

}

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 HitMarkingSystem
{
    mixin ECS.System!16;

    struct EntitiesData
    {
        uint length;
        CHitMark[] mark;
    }

    void onUpdate(EntitiesData data)
    {
        foreach(i;0..data.length)
        {
            //if(data.mark[i] < 10)data.mark[i] = 0;
            //else data.mark[i] -= 1;
            data.mark[i] = cast(ubyte)(data.mark[i] * 0.9);
        }
    }
}

struct HitPointsSystem
{
    mixin ECS.System;

    struct EntitiesData
    {
        CHitPoints[] hp;
    }

    void handleEvent(Entity* entity, EDamage event)
    {
        CHitPoints* hp = entity.getComponent!CHitPoints;
        *hp -= event.damage;
        if(*hp < 0)launcher.manager.removeEntity(entity.id);
        CHitMark* hit_mark = entity.getComponent!CHitMark;
        if(hit_mark)hit_mark.value = 127;
    }
}

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;
        }
    }
}

extern(C) float sqrtf(float x) @nogc nothrow @system;

/**
*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);
        }
        else if(launcher.getKeyState(SDL_SCANCODE_S))
        {
            move_vector += vec2(0,-1);
        } 
        if(launcher.getKeyState(SDL_SCANCODE_A))
        {
            move_vector += vec2(-1,0);
        }
        else if(launcher.getKeyState(SDL_SCANCODE_D))
        {   
            move_vector += vec2(1,0);
        }

        if(move_vector.x != 0 ||move_vector.y != 0)
        {
            move_vector = move_vector / sqrtf(move_vector.x * move_vector.x + move_vector.y * move_vector.y);
            return true;
        }
        //don't call system update because no key pressed 
        return false;
    }

    /**
    *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");

    space_invaders.shoot_grid = Mallocator.make!ShootGrid;
    space_invaders.shoot_grid.create(ivec2(80,60), vec2(5,5));

    launcher.manager.beginRegister();

    launcher.manager.registerDependency(ShootGridDependency);

    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.registerComponent!CDepth;
    launcher.manager.registerComponent!CShootGrid;
    launcher.manager.registerComponent!CGuild;
    launcher.manager.registerComponent!CHitPoints;
    launcher.manager.registerComponent!CHitMark;

    launcher.manager.registerEvent!EChangeDirection;
    launcher.manager.registerEvent!EDamage;

    //launcher.manager.registerSystem!MoveSystem(0);
    launcher.manager.registerSystem!DrawSystem(100);
    launcher.manager.registerSystem!InputMovementSystem(-100);
    launcher.manager.registerSystem!MovementSystem(-99);
    launcher.manager.registerSystem!ClampPositionSystem(-90);
    launcher.manager.registerSystem!LaserShootingSystem(0);
    launcher.manager.registerSystem!ChangeDirectionSystem(0);
    launcher.manager.registerSystem!LaserCollisionSystem(-70);
    launcher.manager.registerSystem!ShootGridManager(-80);
    launcher.manager.registerSystem!ShootGridCleaner(-101);
    launcher.manager.registerSystem!HitPointsSystem(0);
    launcher.manager.registerSystem!HitMarkingSystem(-100);

    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[11] components = [CHitMark.component_id, CHitPoints.component_id, CLocation.component_id, CTexture.component_id, CInput.component_id, CShip.component_id, CScale.component_id, CLaserWeapon.component_id, CShootDirection.component_id, CShootGrid.component_id, CGuild.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 = 22;
        space_invaders.ship_tmpl.getComponent!CHitPoints().value = 1000;

        launcher.manager.addEntity(space_invaders.ship_tmpl);
    }

    {
        ushort[6] components = [CLocation.component_id, CTexture.component_id, CVelocity.component_id, CScale.component_id, CLaser.component_id, CGuild.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[12] components = [CHitMark.component_id, CHitPoints.component_id, CVelocity.component_id, CAutoShoot.component_id, CLocation.component_id, CTexture.component_id, CScale.component_id, CLaserWeapon.component_id, CEnemy.component_id, CShootDirection.component_id, CShootGrid.component_id, CGuild.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);
        space_invaders.enemy_tmpl.getComponent!CGuild().guild = 1;
        
        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(launcher.manager.allocateTemplate(space_invaders.ship_tmpl),"Ship");
    launcher.gui_manager.addTemplate(enemy_tmpl,"Enemy");
    launcher.gui_manager.addTemplate(grouped_tmpl,"Grouped enemy");
    launcher.gui_manager.addTemplate(launcher.manager.allocateTemplate(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.getSystem(ShootGridCleaner.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;
                }
                CLaserWeapon* laser_weapon = tmpl.getComponent!CLaserWeapon;
                if(laser_weapon)
                {
                    laser_weapon.shoot_time = randomf * LaserShootingSystem.laser_shoot_times[laser_weapon.level - 1];
                }
                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;
}