Beispiel #1
0
Bomb::NormalBomb::NormalBomb()
{
  this->ctor(NormalBomb_o);

  TimerComponent	*timer = new TimerComponent(NORMAL_BOMB_TIMER);
  timer->AssignEntity(this);
  this->AddComponent(timer);

  PhysicComponent   *physic = new PhysicComponent(0.5);
  physic->AssignEntity(this);
  this->AddComponent(physic);

  MeshComponent           *graphic =
    new MeshComponent(MODEL,
		      new std::string("bombe"),
		      new std::string(MODELPATH"bombe/bombe.fbx"),
		      BombMeshInit,
		      BombMeshDraw,
		      G_Renderer);
  graphic->AssignEntity(this);
  this->AddComponent(graphic);

  ExplodeComponent	*explode = new ExplodeComponent(NORMAL_BOMB_POWER, NORMAL_BOMB_SIZE);
  explode->AssignEntity(this);
  this->AddComponent(explode);
  this->_isDestroy = true;

  //	AudioComponent
  AudioComponent*	audio = new AudioComponent(Event::COMMON);
  audio->AssignEntity(this);
  this->AddComponent(audio);
  _sound = new std::string("explosion");
  _soundpath = new std::string(SOUNDPATH"BOMB_01.wav");
  audio->AddSound(_soundpath, _sound);
}
void SpriteComponent::init() {
	const char *comma = strchr(_name.c_str(), ',');

	Common::String name(_name.c_str(), comma);

	if (_sprite) {
		if (_parent) {
			MeshComponent *mc = static_cast<MeshComponent *>(_parent);
			mc->getNode()->removeSprite(_sprite);
		}
		delete _sprite;
		_sprite = NULL;
	}

	if (comma) {
		int width, height, x, y, z;
		sscanf(comma, ",%d,%d,%d,%d,%d", &width, &height, &x, &y, &z);

		_sprite = new Sprite;
		_sprite->_material = g_resourceloader->loadMaterial(name, getCMap());
		_sprite->_width = (float)width / 100.0f;
		_sprite->_height = (float)height / 100.0f;
		_sprite->_pos.set((float)x / 100.0f, (float)y / 100.0f, (float)z / 100.0f);
		_sprite->_visible = false;
		_sprite->_next = NULL;

		if (_parent) {
			if (_parent->isComponentType('M','E','S','H')) {
				MeshComponent *mc = static_cast<MeshComponent *>(_parent);
				mc->getNode()->addSprite(_sprite);
			} else
				Debug::warning(Debug::Costumes, "Parent of sprite %s wasn't a mesh", _name.c_str());
		}
	}
}
Beispiel #3
0
City* Game::CreateCity( const Point& pos, Faction& owner )
{
	// Create a graphical entity
	ITexture* pTexture = AssetManager::Get().GetAsset< ITexture >( "BTNSteelMelee.png" );

	Material* pMaterial = AssetManager::Get().GetAsset<Material>( "Materials/GhoulMat.xmat" );

	// Create entity
	Entity* pCubeEntity = GameManager::CreateEntity();

	MeshComponent* pMesh = pCubeEntity->AddComponent<MeshComponent>();
	pMesh->SetMesh( Mesh::CreateBox() );
	pMesh->GetMesh()->Release();
	pMesh->SetMaterial( pMaterial );

	pCubeEntity->GetTransform().SetPosition( m_pWorld->GetPositionForTile( pos.x, pos.y ) );

	// Create the city
	City* pCity = pCubeEntity->AddComponent<City>();
	pCity->SetFaction( &owner );
	m_Cities.push_back( pCity );
	pCity->AddRef();

	m_pWorld->SetEntityPosition( pCubeEntity, pos.x, pos.y );

	return pCity;
}
Beispiel #4
0
Bomb::Image::Image(int posX, int posY, int width, int height, std::string name, std::string path)
{

  this->ctor(Image_o);

  PositionComponent	*pos = new PositionComponent();
  pos->AssignEntity(this);
  this->AddComponent(pos);

  /*
	PhysicComponent		*physic = new PhysicComponent(UNDESTRUCTIBLE_BOX_HITBOX);
	physic->AssignEntity(this);
	this->AddComponent(physic);
  */


  this->posX = posX;
  this->posY = posY;
  this->width = width;
  this->height = height;
  this->path = path;
  this->name = name;

  MeshComponent           *graphic =
    new MeshComponent(GEOMETRY,
		      new std::string(this->name),
		      new std::string(this->path),
		      ImageMeshInit,
		      ImageMeshDraw,
		      G_Renderer);
  graphic->AssignEntity(this);
  this->AddComponent(graphic);
}
Beispiel #5
0
void GCL::RenderComponent::PostInit()
{
    //must find the mesh component and hook it up with us
    if (!mParentActor->HasComponent("MeshComponent"))
        return;
    Component *meshComponent = mParentActor->GetComponent("MeshComponent");
    MeshComponent *tempMeshComponent = static_cast<MeshComponent*>(meshComponent);

    if (!tempMeshComponent->HasMesh())
        return;

    Mesh &mesh = tempMeshComponent->GetMesh();
    switch ((size_t)mesh.GetVertexType())
    {
    case ePOSITION:
        mObj = new RenderObject(mesh.GetMaterial(),
                                (const VertexP*)mesh.GetVertexData(0),
                                mesh.GetVertexCount(0));
        break;
    case ePOSITION|eNORMAL:
        mObj = new RenderObject(mesh.GetMaterial(),
                                (const VertexPN*)mesh.GetVertexData(0),
                                mesh.GetVertexCount(0));
        break;
    case ePOSITION|eNORMAL|eTEXTURE_COORD:
        mObj = new RenderObject(mesh.GetMaterial(),
                                (const VertexPNT*)mesh.GetVertexData(0),
                                mesh.GetVertexCount(0));
        break;
    default:
        GCLAssert(false);
    }
}
Beispiel #6
0
    void OnMouseDown(UINT button, int x, int y)
    {
        XOrientation camOrient;
        cameraEntity->GetOrientation(&camOrient);

        if (button == 0)
            cameraControl = true;

        //shoot a cube
        else if (button == 1)
        {
            Entity* pCube = g_pScene->CreateEntity();
            g_pSelectedEntity = pCube;
            pCube->SetPosition(cameraEntity->GetPosition() + camOrient.z);
            pCube->SetVelocity(0.1f * camOrient.z);
            //pCube->SetMaxLifeTime(5.0f);

            MeshComponent* pMesh = new MeshComponent(pCube);
            pMesh->SetMeshResource("cube.nfm");

            BodyComponent* pBody = new BodyComponent(pCube);
            pBody->SetMass(10.0f);
            pBody->EnablePhysics((CollisionShape*)EngineGetResource(ResourceType::COLLISION_SHAPE,
                                 "shape_box"));


            OmniLightDesc lightDesc;
            lightDesc.radius = 4.0f;
            lightDesc.shadowFadeStart = 20.0;
            lightDesc.shadowFadeEnd = 30.0;

            Entity* pLightEntity = g_pScene->CreateEntity();
            pCube->Attach(pLightEntity);
            //pLightEntity->SetLocalPosition(Vector(0.0f, 1.0f, 0.0f));

            LightComponent* pLight = new LightComponent(pLightEntity);
            pLight->SetOmniLight(&lightDesc);
            pLight->SetColor(Float3(1.0f, 1.0f, 10.0f));
            pLight->SetShadowMap(0);

        }
        else
        {
            Entity* pBarrel = g_pScene->CreateEntity();
            g_pSelectedEntity = pBarrel;
            pBarrel->SetPosition(cameraEntity->GetPosition() + camOrient.z);
            pBarrel->SetVelocity(30.0f * camOrient.z);

            MeshComponent* pMesh = new MeshComponent(pBarrel);
            pMesh->SetMeshResource("barrel.nfm");

            BodyComponent* pBody = new BodyComponent(pBarrel);
            pBody->SetMass(20.0f);
            pBody->EnablePhysics((CollisionShape*)EngineGetResource(ResourceType::COLLISION_SHAPE,
                                 "shape_barrel"));

        }
    }
SpriteComponent::~SpriteComponent() {
	if (_sprite) {
		if (_parent) {
			MeshComponent *mc = static_cast<MeshComponent *>(_parent);
			if (mc) {
				if (mc->getParent()->isComponentType('M','M','D','L') ||
					mc->getParent()->isComponentType('M','O','D','L')) {
					ModelComponent *mdlc = static_cast<ModelComponent *>(mc->getParent());
					if (mdlc->getHierarchy())
						mc->getNode()->removeSprite(_sprite);
				}
			}
		}
		delete _sprite->_material;
		delete _sprite;
	}
}
void ModelComponent::init() {
	if (_prevComp && _prevComp->isComponentType('M','M','D','L')) {
		_previousCmap = _prevComp->getCMap();
	}
	// Skip loading if it was initialized
	// by the sharing MainModelComponent
	// constructor before
	if (!_obj) {
		CMapPtr cm = getCMap();

		// Get the default colormap if we haven't found
		// a valid colormap
		if (!cm && g_grim->getCurrSet())
			cm = g_grim->getCurrSet()->getCMap();
		if (!cm) {
			Debug::warning(Debug::Costumes, "No colormap specified for %s, using %s", _name.c_str(), DEFAULT_COLORMAP);

			cm = g_resourceloader->getColormap(DEFAULT_COLORMAP);
		}

		// If we're the child of a mesh component, put our nodes in the
		// parent object's tree.
		if (_parent) {
			MeshComponent *mc = static_cast<MeshComponent *>(_parent);
			_obj = g_resourceloader->loadModel(_name, cm, mc->getModel());
			_hier = _obj->getHierarchy();
			mc->getNode()->addChild(_hier);
		} else {
			_obj = g_resourceloader->loadModel(_name, cm);
			_hier = _obj->getHierarchy();
			Debug::warning(Debug::Costumes, "Parent of model %s wasn't a mesh", _name.c_str());
		}

		// Use parent availablity to decide whether to default the
		// component to being visible
		if (_parent)
			setKey(0);
		else
			setKey(1);
	}

	if (!_animation) {
		_animation = new AnimManager();
	}
}
Beispiel #9
0
Bomb::DestructibleBox::DestructibleBox()
{
	this->ctor(DestructibleBox_o);

	PositionComponent	*pos = new PositionComponent();
	pos->AssignEntity(this);
	this->AddComponent(pos);

	LifeComponent		*life = new LifeComponent(1);
	life->AssignEntity(this);
	this->AddComponent(life);

	PhysicComponent		*physic = new PhysicComponent(DESTRUCTIBLE_BOX_HITBOX);
	physic->AssignEntity(this);
	this->AddComponent(physic);


  DropBonusComponent   *dropBonus = new DropBonusComponent();
  dropBonus->AssignEntity(this);
  this->AddComponent(dropBonus);

	MeshComponent		*graphic =
	  new MeshComponent(GEOMETRY,
			    new std::string("box2"),
			    new std::string(MODELPATH"box2.tga"),
			    DestructibleBoxMeshInit,
			    DestructibleBoxMeshDraw,
			    G_Renderer);
	graphic->AssignEntity(this);
	this->AddComponent(graphic);

  this->_isDestroy = true;

	/*AudioComponent		*audio = new AudioComponent();
	audio->AssignEntity(this);
	this->AddComponent(audio);*/
}
ConeTracePass::ConeTracePass(VCTscene* vctScene){
  using namespace kore;

  _name = std::string("ConeTrace");
  _useGPUProfiling = vctScene->getUseGPUprofiling();

    _vctScene = vctScene;
    _renderMgr = RenderManager::getInstance();
    _sceneMgr = SceneManager::getInstance();
    _resMgr = ResourceManager::getInstance();

    _coneTraceShader.loadShader("./assets/shader/VoxelConeTracing/raycastVert.shader",
      GL_VERTEX_SHADER);

    _coneTraceShader.loadShader("./assets/shader/ConeTraceFrag.shader",
      GL_FRAGMENT_SHADER, std::string("#define LEAF_NODE_RESOLUTION ")
                          + std::to_string(vctScene->getNodePool()->getLeafNodeResolution())
                          + std::string("\n\n") );
    _coneTraceShader.setName("cone trace shader");
    _coneTraceShader.init();

    _coneTraceShader.startUniformBindingCheck();
    
    this->setShaderProgram(&_coneTraceShader);

    TexSamplerProperties samplerProps;
    samplerProps.minfilter = GL_LINEAR;
    samplerProps.magfilter = GL_LINEAR;
    samplerProps.wrapping = glm::uvec3(GL_REPEAT, GL_REPEAT, GL_REPEAT);
    _coneTraceShader.setSamplerProperties(0, samplerProps);

    SceneNode* fsquadnode = new SceneNode();
    SceneManager::getInstance()->getRootNode()->addChild(fsquadnode);

    MeshComponent* fsqMeshComponent = new MeshComponent();
    fsqMeshComponent->setMesh(FullscreenQuad::getInstance());
    fsquadnode->addComponent(fsqMeshComponent);

    kore::Camera* cam = vctScene->getCamera();

    NodePass* nodePass = new NodePass(fsquadnode);
    this->addNodePass(nodePass);

    glm::ivec4 vp(0, 0, RenderManager::getInstance()->getScreenResolution().x,
      RenderManager::getInstance()->getScreenResolution().y);
    nodePass->addOperation(new ViewportOp(vp));

    nodePass
      ->addOperation(new ColorMaskOp(glm::bvec4(true, true, true, true)));


    nodePass->addOperation(OperationFactory::create(OP_BINDATTRIBUTE, 
      "v_position",
      fsqMeshComponent, 
      "v_position",
      &_coneTraceShader));


    nodePass->addOperation(OperationFactory::create(OP_BINDUNIFORM, 
      "ratio",
      cam, 
      "fRatio",
      &_coneTraceShader));

    nodePass->addOperation(OperationFactory::create(OP_BINDUNIFORM, 
      "FOV degree",
      cam,
      "fYfovDeg",
      &_coneTraceShader));

    nodePass->addOperation(OperationFactory::create(OP_BINDUNIFORM, 
      "far Plane",
      cam, 
      "fFar",
      &_coneTraceShader));

    nodePass->addOperation(new BindUniform(_renderMgr->getShdScreenRes(),
      _coneTraceShader.getUniform("screenRes")));  

    addStartupOperation(new BindImageTexture(
      vctScene->getNodePool()->getShdNodePool(NEXT),
      _coneTraceShader.getUniform("nodePool_next"), GL_READ_ONLY));
    addStartupOperation(new BindImageTexture(
      vctScene->getNodePool()->getShdNodePool(COLOR),
      _coneTraceShader.getUniform("nodePool_color"), GL_READ_ONLY));

    addStartupOperation(new BindTexture(vctScene->getBrickPool()->getShdBrickPoolTexture(BRICKPOOL_COLOR),
                                        _coneTraceShader.getUniform("brickPool_color")));
    addStartupOperation(new BindTexture(vctScene->getBrickPool()->getShdBrickPoolTexture(BRICKPOOL_IRRADIANCE),
                                        _coneTraceShader.getUniform("brickPool_irradiance")));
    addStartupOperation(new BindTexture(vctScene->getBrickPool()->getShdBrickPoolTexture(BRICKPOOL_NORMAL),
                                        _coneTraceShader.getUniform("brickPool_normal")));
    
    nodePass->addOperation(new BindUniform(
      vctScene->getShdVoxelGridResolution(),
      _coneTraceShader.getUniform("voxelGridResolution")));

    nodePass->addOperation(OperationFactory::create(OP_BINDUNIFORM,
      "inverse view Matrix",
      cam,
      "viewI",
      &_coneTraceShader));

    nodePass->addOperation(OperationFactory::create(OP_BINDUNIFORM,
      "inverse model Matrix", vctScene->getVoxelGridNode()->getTransform(),
      "voxelGridTransformI", &_coneTraceShader));

    nodePass->addOperation(new BindUniform(vctScene->getNodePool()->getShdNumLevels(),
      _coneTraceShader.getUniform("numLevels"))); 

    nodePass->addOperation(new BindUniform(vctScene->getNodePool()->getShdLeafNodeResolution(),
      _coneTraceShader.getUniform("leafNodeResolution")));

    nodePass->addOperation(new BindUniform(&vctScene->_shdConeDiameter, _coneTraceShader.getUniform("coneAngle")));


    //////////////////////////////////////////////////////////////////////////
    // Tweak-Parameters
    nodePass->addOperation(new BindUniform(vctScene->getShdUseLighting(),
      _coneTraceShader.getUniform("useLighting")));
    //nodePass->addOperation(new BindUniform(&vctScene->_shdUseAlphaCorrection, _coneTraceShader.getUniform("useAlphaCorrection")));
    //////////////////////////////////////////////////////////////////////////

    nodePass->addOperation(new RenderMesh(fsqMeshComponent));

    _coneTraceShader.finishUniformBindingCheck();
}
Beispiel #11
0
SceneObject* parseNode(KFbxNode *node, int level = 0) {
    KString s = node->GetName();
    KFbxNodeAttribute::EAttributeType attributeType;
    stringstream ss;
    for (int i=0;i<level;i++){
        ss<<"   ";
    }
    SceneObject* sceneObject = NULL;
    MeshComponent* ga = NULL;
    
    if (node->GetNodeAttribute() == NULL){
        ss<<"No node attribute"<<endl;
    } else {
        attributeType = node->GetNodeAttribute()->GetAttributeType();
        switch (attributeType) {
            case KFbxNodeAttribute::eMARKER:
                ss<<"eMarker"<<endl;
                break;
            case KFbxNodeAttribute::eSKELETON:
                ss<<"eSkeleton"<<endl;
                break;
            case KFbxNodeAttribute::eMESH:
                {
                KFbxMesh *fbxMesh = node->GetMesh();
                KFbxVector4 *controlPoints = fbxMesh->GetControlPoints();
                int polygonCount = fbxMesh->GetPolygonCount();
                vector<glm::vec3> vertices;
                vector<glm::vec3> normals;
                vector<glm::vec2> texCords;
                vector<int> polycount;
                assert(fbxMesh->GetLayerCount(KFbxLayerElement::eNORMAL)==1); // assume only one normal layer
                KFbxLayer *normalLayer = fbxMesh->GetLayer(0, KFbxLayerElement::eNORMAL);
                KFbxLayerElementNormal *normalElement = normalLayer->GetNormals();
                KFbxLayerElementArrayTemplate<KFbxVector4> *normalArray = &(normalElement->GetDirectArray());
                
                int normalCount = normalArray->GetCount();
                vector<int> indices;
                
                assert(fbxMesh->GetControlPointsCount() <= USHRT_MAX);
                for (int i=0;i<fbxMesh->GetControlPointsCount();i++){
                    glm::vec3 v = toVector(controlPoints[i]);
                    vertices.push_back(v);
                    v = toVector(normalArray->GetAt(i));
                    normals.push_back(v);
                }
                
                
                for (int i=0;i<polygonCount;i++){
                    int polygonSize = fbxMesh->GetPolygonSize(i);
                    polycount.push_back(polygonSize);
                    for (int j=0;j<polygonSize;j++){
                        if (j>2){
                            // if polygon size > 2 then add first and last index
                            // this triangulates the mesh
                            int first = fbxMesh->GetPolygonVertex(i,0);
                            int last = fbxMesh->GetPolygonVertex(i,j-1);
                            indices.push_back(first);
                            indices.push_back(last);
                        }
                        int polygonIndex = fbxMesh->GetPolygonVertex(i,j);
                        indices.push_back(polygonIndex);
                        /*KFbxVector4 vectorSrc = controlPoints[polygonIndex];
                        Vector3 vectorDst = toVector(vectorSrc);
                        vertices.push_back(vectorDst);
                        texCords.push_back(Vector2(0,0)); 
                        KFbxVector4 normalSrc = normalArray->GetAt(polygonIndex);
                        Vector3 normalDst = toVector(normalSrc);
                        normals.push_back(normalDst);*/
                    }
                }
                
                Mesh mesh;
                ss<<"Creating mesh: vertices "<<vertices.size()<<" normals "<<normals.size()<<" indices "<<indices.size()<<endl;
                mesh.SetVertices(vertices);
                mesh.SetNormals(normals);
                mesh.SetIndices(indices);
                sceneObject = new SceneObject();
                
                ga = new MeshComponent();
                ga->SetMesh(&mesh);
                sceneObject->AddCompnent(ga);
                
                // Set translate
                fbxDouble3 v3 = node->LclTranslation.Get();
                glm::vec3 translate = toVector(v3);
                sceneObject->GetTransform()->SetPosition(translate);
                
                // Set rotation
                v3 = node->LclRotation.Get();
                glm::vec3 rotation = toVector(v3)*Mathf::DEGREE_TO_RADIAN;
                sceneObject->GetTransform()->SetRotation(rotation);

                // Set scale
                v3 = node->LclScaling.Get();
                glm::vec3 scale = toVector(v3);
                sceneObject->GetTransform()->SetScale(scale);
                }
                break;
            case KFbxNodeAttribute::eCAMERA:
                ss<<"eCAMERA"<<endl;
                break;
            case KFbxNodeAttribute::eLIGHT:
                ss<<"eLIGHT"<<endl;
                break;
            case KFbxNodeAttribute::eBOUNDARY:
                ss<<"eBOUNDARY"<<endl;
                break;
            default:
                ss<<s<<endl;
        }
    }
    
    if (node->GetChildCount()>0){
        for (int i=0;i<node->GetChildCount();i++){
            SceneObject *res = parseNode(node->GetChild(i),level+1);
            if (res!=NULL){
                if (sceneObject == NULL){
                    sceneObject = new SceneObject();
                }
                sceneObject->AddChild(res);
            }
        }
    }
    DEBUG(ss.str());
    return sceneObject;
}
RayCastingPass::RayCastingPass(VCTscene* vctScene) {
  using namespace kore;

  _name = std::string("Raycasting Pass");
  _useGPUProfiling = vctScene->getUseGPUprofiling();
  
  _raycastShader
     .loadShader("./assets/shader/VoxelConeTracing/raycastVert.shader",
                 GL_VERTEX_SHADER);
  
  _raycastShader.
    loadShader("./assets/shader/VoxelConeTracing/raycastFrag.shader",
               GL_FRAGMENT_SHADER);

  _raycastShader.setName("raycastShader");
  _raycastShader.init();
  
  this->setShaderProgram(&_raycastShader);
  
  SceneNode* fsquadnode = new SceneNode();
  SceneManager::getInstance()->getRootNode()->addChild(fsquadnode);

  MeshComponent* fsqMeshComponent = new MeshComponent();
  fsqMeshComponent->setMesh(FullscreenQuad::getInstance());
  fsquadnode->addComponent(fsqMeshComponent);

  kore::Camera* cam = vctScene->getCamera();

  NodePass* nodePass = new NodePass(fsquadnode);
  this->addNodePass(nodePass);

  glm::ivec4 vp(0, 0, RenderManager::getInstance()->getScreenResolution().x,
                     RenderManager::getInstance()->getScreenResolution().y);
  nodePass->addOperation(new ViewportOp(vp));

  nodePass
    ->addOperation(new EnableDisableOp(GL_DEPTH_TEST,
    EnableDisableOp::DISABLE));

  nodePass
    ->addOperation(new ColorMaskOp(glm::bvec4(true, true, true, true)));

  nodePass->addOperation(OperationFactory::create(OP_BINDATTRIBUTE, 
    "v_position",
    fsqMeshComponent, 
    "v_position",
    &_raycastShader));

  nodePass->addOperation(OperationFactory::create(OP_BINDUNIFORM, 
    "ratio",
    cam, 
    "fRatio",
    &_raycastShader));

  nodePass->addOperation(OperationFactory::create(OP_BINDUNIFORM, 
    "FOV degree",
    cam, 
    "fYfovDeg",
    &_raycastShader));

  nodePass->addOperation(OperationFactory::create(OP_BINDUNIFORM, 
    "far Plane",
    cam, 
    "fFar",
    &_raycastShader));

  nodePass->addOperation(OperationFactory::create(OP_BINDUNIFORM,
    "inverse view Matrix",
    cam,
    "viewI",
    &_raycastShader));

  nodePass->addOperation(OperationFactory::create(OP_BINDUNIFORM,
    "model Matrix", vctScene->getVoxelGridNode()->getTransform(),
    "voxelGridTransform", &_raycastShader));

  nodePass->addOperation(OperationFactory::create(OP_BINDUNIFORM,
    "inverse model Matrix", vctScene->getVoxelGridNode()->getTransform(),
    "voxelGridTransformI", &_raycastShader));

  nodePass->addOperation(new RenderMesh(fsqMeshComponent));
}
Beispiel #13
0
bool GameProcess::VOnMouseButtonUp( const int iButtonIndex, const Vector3& vPosition )
{
    Vector3 vResolution( IRenderer::Get()->VGetScreenWidth(), IRenderer::Get()->VGetScreenHeight(), 1.0f );
    
    Vector3 vRayPos, vRayDir;
    Matrix::Unproject( vPosition, vResolution, m_pCamera->GetProjection(), m_pCamera->GetView(), vRayPos, vRayDir );
    
    float fDistance = 0.0f;

    if ( iButtonIndex == 0 )
    {
        if ( m_pHeightMapEntity->VPick( vRayPos, vRayDir, &fDistance ) )
        {
            if ( fDistance < 0.0f )
                fDistance = -fDistance;
            
            Transform& transform = m_pMrBitey->GetTransform();

			if ( InputManager::Get()->GetKeyState( KEY_T ) == HELD_KEYSTATE )
			{
				transform.SetPosition( vRayPos + vRayDir * fDistance + Vector3::UP );
			}
			else
			{
				Vector4 vTarget = vRayPos + vRayDir * fDistance + Vector3( 0.0f, 1.0f, 0.0f );
				m_pSteering->SetTargetPosition( vTarget );
			}            
            
            return false;
        }
    }
    
    else if ( iButtonIndex == 1 )
    {
        SceneNode* pSceneNode = SceneManager::Get()->VPickAndReturnClosest( vRayPos, vRayDir, &fDistance );
        if ( pSceneNode )
        {
            Entity* pEntity = pSceneNode->VGetEntity();
            if ( pEntity )
            {
                if ( pEntity != m_pHeightMapEntity->GetOwner() )
                {
                    Transform& matTransform = m_pMrBitey->GetTransform();
					Vector4 vPosition( pEntity->GetTransform().GetPosition() - Vector4( Vector4( 0.0f, 0.0f, -20.0f ) ) );                    
                    m_pHeightMapEntity->GetHeight( vPosition.x, vPosition.z, vPosition.y );
                    matTransform.SetPosition( vPosition );

					InteractableComponent* pInteractable = (InteractableComponent*)pEntity->GetComponent( InteractableComponent::g_hID );
					if ( pInteractable )
					{
						pInteractable->VOnInteract( m_pMrBitey );
					}

                    Combat::InitiateCombat( m_pCamera, m_pMrBitey, pEntity );
                }
                
                else
                {
                    Matrix matTransform;
                    matTransform.BuildScale( Vector4::ONE * 2.0f );
                    vRayDir.Normalize();
                    matTransform.SetPosition( vRayPos + vRayDir * fDistance + Vector4( 0.0f, 1.0f, 0.0f ) );
                    
                    Entity* pEntity = Game::CreateEntity( matTransform );
                    MeshComponent* pMeshComponent = new MeshComponent();
                    pEntity->AddComponent( pMeshComponent );
                    Mesh* pMesh = Mesh::CreateBox();
                    pMeshComponent->SetMesh( pMesh );
                    pMesh->Release();
                    pMeshComponent->Start();
                    pMeshComponent->Release();

					TalkerComponent* pTalker = new TalkerComponent( "Dialogue.xml" );
					pEntity->AddComponent( pTalker );
					pTalker->Start();
					pTalker->Release();
                    
                    StateMachineComponent* pStateMachine = new StateMachineComponent();
                    pEntity->AddComponent( pStateMachine );
                    //pStateMachine->Start();
                    pStateMachine->Release();
                    
                    Character* pCharacter = new Character();
                    XmlResource* pResource = AssetManager::Get().GetAsset<XmlResource>( "CombatAbilities.xml" );
                    if ( pResource )
                    {
                        auto pElement = pResource->GetRoot()->FirstChildElement();
                        
                        while ( pElement )
                        {
                            CombatAbility ability;
                            ability.VFromXML( pElement );
                            pCharacter->AddAbility( ability );
                            
                            pElement = pElement->NextSiblingElement( "Ability" );
                        }
                    }
                    
                    pEntity->AddComponent( pCharacter );
                    pCharacter->Release();
                    
                    /*ParticleEmitter* pSystem = new ParticleEmitter();
                    pEntity->AddComponent( pSystem );
                    pSystem->Start();
                    pSystem->SetTexture( "explosion.png" );
                    
                    EmitterProcessor* pPositionProcessor = new SphericalSpawnPositionProcessor( 0.5f );
                    pSystem->AddProcessor( pPositionProcessor );
                    pPositionProcessor->Release();
                    
                    pPositionProcessor = new SpawnPositionProcessor( Vector3( 0.0f, 2.0f, 0.0f ) );
                    pSystem->AddProcessor( pPositionProcessor );
                    pPositionProcessor->Release();
                    
                    //pPositionProcessor = new VelocityOverAgeProcessor( new CurveModifier( Vector3( 0.0f, 2.0f, 0.0f ) * 5.0f, Vector3( 1.0f, 2.0f, 1.0f ) * 5.0f, Vector3( -1.0f, 2.0f, -1.0f ) * 5.0f, Vector3( 1.0f, 2.0f, 1.0f ) * 5.0f ) );
                    pPositionProcessor = new VelocityOverAgeProcessor( new ConstantEmitterModifier( Vector3::UP * 5.0f ) );
                    pSystem->AddProcessor( pPositionProcessor );
                    pPositionProcessor->Release();
                    
                    pPositionProcessor = new RadialVelocityProcessor( Vector3( 1.0f, 1.0f, 1.0f ) * 20.0f );
                    pSystem->AddProcessor( pPositionProcessor );
                    pPositionProcessor->Release();
                    
                    pPositionProcessor = new ColorOverAgeProcessor( new CurveModifier( Vector3::ZERO, Vector3( 1.0f, 0.0f, 0.0f ), Vector3( 0.0f, 1.0f, 0.0f ), Vector3( 0.0f, 0.0f, 1.0f ) ) );
                    pSystem->AddProcessor( pPositionProcessor );
                    pPositionProcessor->Release();
                    
                    pSystem->Release();*/
                }
            }
        }
    }
    
    return false;
}
Beispiel #14
0
void GameProcess::VOnInit(void)
{
    //pSkillInterface =  new SkillInterface();
    
	DialogueInterface* pDialogue = new DialogueInterface( NULL, "DialogueInterface.xml", "Dialogue.xml" );
	pDialogue->SetName( "Dialogue" );
	BaseApplication::Get()->AttachProcess( pDialogue );
	pDialogue->Release();

    Entity* pEntity = Game::CreateEntity();
    ThirdPersonCamera* pCamera = new ThirdPersonCamera();
    pCamera->SetDistanceMax( 50.0f );
    m_pCamera = pCamera;
    pEntity->AddComponent( pCamera );
    pCamera->SetClearColor( ColorF::BLACK );
    pCamera->Release();
    pCamera->SetPosition( Vector4( 2000.0f, 30.0f, 2000.0f ) );
    pCamera->SetDirection( Vector4( 0.0f, 0.0f, 1.0f ) );
    pCamera->Start();
    
    pEntity = Game::CreateEntity();
    
    
    int iWorldSize = 512;
    m_IslandData.Generate( iWorldSize, iWorldSize );
    HeightmapComponent* pComponent = new HeightmapComponent( iWorldSize, iWorldSize, m_IslandData );
    m_pHeightMapEntity = pComponent;
    //pComponent->SetTexture( "sketch.png" );
    m_IslandData.GenerateBiomes();
    ColorF* pColors = new ColorF[ iWorldSize * iWorldSize ];
    for ( int i = 0; i < iWorldSize; ++i )
    {
        for ( int j = 0; j < iWorldSize; ++j )
        {
            ColorF color;
            IslandData::Biome eBiome = m_IslandData.GetBiome( i, j );
            
            if ( eBiome == IslandData::SeaWater )
            {
                color = Color::BLUE;
            }
            
            else if ( eBiome == IslandData::FreshWater )
            {
                color = Color( 0, 191, 255 );
            }
            
            else if ( eBiome == IslandData::Grassland )
            {
                color = Color( 195, 211, 170, 255 );
            }
            
            else if ( eBiome == IslandData::Snow )
            {
                color = Color::WHITE;
            }
            
            else if ( eBiome == IslandData::Bare )
            {
                color = Color( 200, 200, 200, 255 );
            }
            
            else if ( eBiome == IslandData::Scorched )
            {
                color = Color::GREY;
            }
            
            else if ( eBiome == IslandData::Tundra )
            {
                color = Color( 220, 220, 186, 255 );
            }
            
            else if ( eBiome == IslandData::Taiga )
            {
                color = Color( 203, 211, 186, 255 );
            }
            
            else if ( eBiome == IslandData::Shrubland )
            {
                color = Color( 195, 203, 186, 255 );
            }
            
            else if ( eBiome == IslandData::TemperateDesert )
            {
                color = Color( 227, 231, 201, 255 );
            }
            
            else if ( eBiome == IslandData::TemperateRainForest )
            {
                color = Color( 163, 195, 167, 255 );
            }
            
            else if ( eBiome == IslandData::TemperateDecidousForest )
            {
                color = Color( 180, 200, 168, 255 );
            }
            
            else if ( eBiome == IslandData::TropicalRainForest )
            {
                color = Color( 155, 186, 168, 255 );
            }
            
            else if ( eBiome == IslandData::TropicalSeasonalForest )
            {
                color = Color( 168, 203, 163, 255 );
            }
            
            else if ( eBiome == IslandData::SubtropicalDesert )
            {
                color = Color( 232, 220, 198, 255 );
            }
            
            else if ( eBiome == IslandData::Unassigned )
            {
                throw "Whoops";
            }
            
            else
            {
                throw "Unhandled biome";
            }
            
            pColors[ j * iWorldSize + i ] = color;
        }
    }
    
    pComponent->GenerateHeightMap( iWorldSize, iWorldSize, m_IslandData, pColors );
    delete [] pColors;
    pEntity->AddComponent( pComponent );
    pComponent->Release();
    pComponent->Start();
    
    // Generate blend map for splatting
    unsigned int* pBlendMap = new unsigned int[ iWorldSize * iWorldSize ];
    for ( int i = 0; i < iWorldSize; ++i )
    {
        for ( int j = 0; j < iWorldSize; ++j )
        {
            Color color;
            IslandData::Biome eBiome = m_IslandData.GetBiome( i, j );
            
            if ( eBiome == IslandData::SeaWater )
            {
                color = Color::BLUE;
                color.Alpha = 0;
            }
            
            else if ( eBiome == IslandData::FreshWater )
            {
                color = Color::BLUE;
                color.Alpha = 0;
            }
            
            else if ( eBiome == IslandData::Grassland )
            {
                color = Color::GREEN;
                color.Alpha = 0;
            }
            
            else if ( eBiome == IslandData::Snow )
            {
                color = Color( 0, 0, 0, 255 );
            }
            
            else if ( eBiome == IslandData::Bare )
            {
                color = Color( 0, 0, 0 ,0 );
            }
            
            else if ( eBiome == IslandData::Scorched )
            {
                color = Color( 0, 0, 0 ,0 );
            }
            
            else if ( eBiome == IslandData::Tundra )
            {
                color = Color( 0, 0, 0 ,255 );
            }
            
            else if ( eBiome == IslandData::Taiga )
            {
                color = Color::BLACK;
                color.Alpha = 0;
            }
            
            else if ( eBiome == IslandData::Shrubland )
            {
                color = Color::BLACK;
                color.Alpha = 0;
            }
            
            else if ( eBiome == IslandData::TemperateDesert )
            {
                color = Color::RED;
                color.Alpha = 0;
            }
            
            else if ( eBiome == IslandData::TemperateRainForest )
            {
                color = Color::GREEN;
                color.Alpha = 0;
            }
            
            else if ( eBiome == IslandData::TemperateDecidousForest )
            {
                color = Color::GREEN;
                color.Alpha = 0;
            }
            
            else if ( eBiome == IslandData::TropicalRainForest )
            {
                color = Color::GREEN;
                color.Alpha = 0;
            }
            
            else if ( eBiome == IslandData::TropicalSeasonalForest )
            {
                color = Color::GREEN;
                color.Alpha = 0;
            }
            
            else if ( eBiome == IslandData::SubtropicalDesert )
            {
                color = Color::RED;
                color.Alpha = 0;
            }
            
            else if ( eBiome == IslandData::Unassigned )
            {
                throw "Whoops";
            }
            
            else
            {
                throw "Unhandled biome";
            }
            
            pBlendMap[ j * iWorldSize + i ] = color.RGBA;
        }
    }
    
    ITexture* pBlendMapTexture = IRenderer::CreateTexture();
    pBlendMapTexture->VCreate( iWorldSize, iWorldSize, 4, (char*)pBlendMap );

    delete [] pBlendMap;
    
    StructuredMaterial<Vector4>* pSplattingMaterial = new StructuredMaterial<Vector4>();
    pSplattingMaterial->GetBuffer()->VAddProperty( "u_vLightDirection", BufferProperty::BP_VECTOR3 );
    
    IShaderProgram* pProgram = IRenderer::CreateShaderProgram();
    IVertexShader* pVertexShader = IRenderer::CreateVertexShader();
    IPixelShader* pPixelShader = IRenderer::CreatePixelShader();
    
    BinaryResource* pVertexResource = AssetManager::Get().GetAsset< BinaryResource >( "Terrain.vert" );
    BinaryResource* pPixelResource = AssetManager::Get().GetAsset< BinaryResource >( "Terrain.frag" );
    
    if ( pVertexShader->VCreateFromMemory( pVertexResource->Buffer(), pVertexResource->Size() ) == false )
        throw "Error";
    
    if ( pPixelShader->VCreateFromMemory( pPixelResource->Buffer(), pPixelResource->Size() ) == false )
        throw "error";
    
    pProgram->VSetPixelShader( pPixelShader );
    pProgram->VSetVertexShader( pVertexShader );
    pVertexShader->VAddAttribute( "u_vPosition", Position_VertexData );
    pVertexShader->VAddAttribute( "u_vTexCoords", UV_VertexData );
    pVertexShader->VAddAttribute( "u_vNormal", Normal_VertexData );
    pVertexShader->VAddAttribute( "u_vColor", Color_VertexData );
    pProgram->VLink();
    
    pSplattingMaterial->SetShaderProgram( pProgram );
    pSplattingMaterial->AddTextureRegister( "Desert" );
    pSplattingMaterial->AddTextureRegister( "Grass" );
    pSplattingMaterial->AddTextureRegister( "Water" );
    pSplattingMaterial->AddTextureRegister( "Snow" );
    pSplattingMaterial->AddTextureRegister( "Rock" );
    pSplattingMaterial->AddTextureRegister( "BlendMap" );
    
    ITexture* pTexture = AssetManager::Get().GetAsset<ITexture>( "Desert.png" );
    pSplattingMaterial->SetTexture( 0, pTexture );
    
    pTexture = AssetManager::Get().GetAsset<ITexture>( "Grass.png" );
    pSplattingMaterial->SetTexture( 1, pTexture );
    
    pTexture = AssetManager::Get().GetAsset<ITexture>( "Water.png" );
    pSplattingMaterial->SetTexture( 2, pTexture );
    
    pTexture = AssetManager::Get().GetAsset<ITexture>( "Snow.png" );
    pSplattingMaterial->SetTexture( 3, pTexture );
    
    pTexture = AssetManager::Get().GetAsset<ITexture>( "Rock.png" );
    pSplattingMaterial->SetTexture( 4, pTexture );
    
    pSplattingMaterial->SetTexture( 5, pBlendMapTexture );
    
    
    
    m_pHeightMapEntity->SetMaterial( pSplattingMaterial );
    pSplattingMaterial->Release();
    pProgram->Release();
    pPixelShader->Release();
    pVertexShader->Release();
    
    
    pBlendMapTexture->Release();
    
    /*pEntity = Game::CreateEntity();
    SkyBox* pSkyBox = new SkyBox();
    pEntity->AddComponent( pSkyBox );
    pSkyBox->Start();
    pSkyBox->Release();*/
    
    
    Matrix mat;
    MeshComponent* pMeshComponent = NULL;
    Mesh* pMesh = NULL;
    
    
    pMesh = Mesh::CreateBox();
    mat.BuildScale( Vector4::ONE * 2.0f );
    mat.SetPosition( Vector4( 1900.0f, 0.0f, 1900.0f ) );
	mat.SetPosition( Vector4( 0.0f, 0.0f, 0.0f ) );
    pEntity = Game::CreateEntity( mat );
    pMeshComponent = new MeshComponent();
//    pEntity->AddComponent( pMeshComponent );
    pMeshComponent->SetMesh( pMesh );
    pMesh->Release();
    pMeshComponent->Start();
    pMeshComponent->Release();
    m_pSteering = new SteeringComponent();
    pEntity->AddComponent( m_pSteering );
    m_pSteering->SetSpeed( 15.0f );
	m_pSteering->SetHeightOffset( 1.0f );
    m_pSteering->Start();
    m_pSteering->Release();
    
    Character* pCharacter = new Character();
    XmlResource* pResource = AssetManager::Get().GetAsset<XmlResource>( "CombatAbilities.xml" );
    if ( pResource )
    {
        auto pElement = pResource->GetRoot()->FirstChildElement();
        
        while ( pElement )
        {
            CombatAbility ability;
            ability.VFromXML( pElement );
            pCharacter->AddAbility( ability );
            
            pElement = pElement->NextSiblingElement( "Ability" );
        }
    }
    
    pEntity->AddComponent( pCharacter );
    pCharacter->Release();
    
    GameHUDComponent* pGameHud = new GameHUDComponent();
    pEntity->AddComponent( pGameHud );
    pGameHud->Start();
    pGameHud->Release();
    
    m_pMrBitey = pEntity;
    
    pEntity = Game::CreateEntity();
    m_pAtmosphere = new AtmosphericScattering();
    pEntity->AddComponent( m_pAtmosphere );
    m_pAtmosphere->Start();
	m_pAtmosphere->Release();

	Transform waterPosition;
	waterPosition.SetPosition( 0.0f, 5.0f, 0.0f );
	pEntity = Game::CreateEntity( waterPosition );
	WaterPlane* pWater = new WaterPlane();
	pEntity->AddComponent( pWater );
	pWater->Start();
	pWater->Release();
}
Beispiel #15
0
void CubesGame::LoadContent()
{
	Game::LoadContent();

	World *m_pWorld = NEW_AO World();
	GameInfo::Instance().SetWorld(m_pWorld);

	m_pProgram = Program::loadProgram("vs_mesh", "fs_mesh");

	//Camera 3D
	BaseEntity *pCamera = NEW_AO BaseEntity();
	Camera3DComponent *m_pCamera3D = NEW_AO Camera3DComponent(pCamera);
	ArcBallCameraController *pArcBall = NEW_AO ArcBallCameraController(m_pCamera3D);
	pArcBall->SetCamera(Vector3F(0, 20.0f, -50.0f), Vector3F::Zero(), Vector3F::Up());
	pArcBall->Distance(15.0f);
	m_pCamera3D->CameraController(pArcBall);
	pCamera->GetComponentMgr()->AddComponent(m_pCamera3D);	
	pCamera->Initialize();
	m_pWorld->AddEntity(pCamera);
	GameInfo::Instance().SetActiveCamera(m_pCamera3D);

	const float delta = 3.0f;

	//Box
	BaseEntity* pEntity = NEW_AO BaseEntity();
	pEntity->SetName("box");
	Transform3DComponent *pTransform = NEW_AO Transform3DComponent(pEntity);
	pTransform->SetLocalPosition(Vector3F(0.0f, 0.5f, delta));
	pTransform->SetLocalRotation(0.0f);
	pTransform->SetLocalScale(Vector3F::One());
	pEntity->GetComponentMgr()->AddComponent(pTransform);
	MeshComponent *pModelCpt = NEW_AO MeshComponent(pEntity);
	IPrimitive3D *pPrimitive = NEW_AO BoxPrimitive();
	Mesh *pModel = pPrimitive->CreateModel();
	//ResourceManager::Instance().Add("boxModel", pModel);
	//DELETE_AO pPrimitive;
	pModelCpt->SetModel(pModel);
	pModelCpt->SetProgram(m_pProgram);
	pEntity->GetComponentMgr()->AddComponent(pModelCpt);
	pEntity->Initialize();

	m_pWorld->AddEntity(pEntity);

	//Sphere
	pEntity = NEW_AO BaseEntity();
	pEntity->SetName("sphere");
	pTransform = NEW_AO Transform3DComponent(pEntity);
	pTransform->SetLocalPosition(Vector3F(delta, 0.5f, 0.0f));
	pTransform->SetLocalRotation(0.0f);
	pTransform->SetLocalScale(Vector3F::One());
	pEntity->GetComponentMgr()->AddComponent(pTransform);
	pModelCpt = NEW_AO MeshComponent(pEntity);
	pPrimitive = NEW_AO SpherePrimitive();
	pModel = pPrimitive->CreateModel();
	//ResourceManager::Instance().Add("sphereModel", pModel);
	pModelCpt->SetModel(pModel);
	pModelCpt->SetProgram(m_pProgram);
	//DELETE_AO pPrimitive;
	pEntity->GetComponentMgr()->AddComponent(pModelCpt);
	pEntity->Initialize();

	m_pWorld->AddEntity(pEntity);

	//Cylinder
	pEntity = NEW_AO BaseEntity();
	pEntity->SetName("cylinder");
	pTransform = NEW_AO Transform3DComponent(pEntity);
	pTransform->SetLocalPosition(Vector3F(-delta, 0.5f, 0.0f));
	pTransform->SetLocalRotation(0.0f);
	pTransform->SetLocalScale(Vector3F::One());
	pEntity->GetComponentMgr()->AddComponent(pTransform);
	pModelCpt = NEW_AO MeshComponent(pEntity);
	pPrimitive = NEW_AO CylinderPrimitive();
	pModel = pPrimitive->CreateModel();
	//ResourceManager::Instance().Add("cylinderModel", pModel);
	pModelCpt->SetModel(pModel);
	pModelCpt->SetProgram(m_pProgram);
	//DELETE_AO pPrimitive;
	pEntity->GetComponentMgr()->AddComponent(pModelCpt);
	pEntity->Initialize();

	m_pWorld->AddEntity(pEntity);

	//ground
	pEntity = NEW_AO BaseEntity();
	pEntity->SetName("ground");
	pTransform = NEW_AO Transform3DComponent(pEntity);
	pTransform->SetLocalPosition(Vector3F(0.0f, 0.0f, 0.0f));
	pTransform->SetLocalRotation(0.0f);
	pTransform->SetLocalScale(Vector3F::One());
	pEntity->GetComponentMgr()->AddComponent(pTransform);
	pModelCpt = NEW_AO MeshComponent(pEntity);
	pPrimitive = NEW_AO PlanePrimitive(100.0f, 100.0f);
	pModel = pPrimitive->CreateModel();
	//ResourceManager::Instance().Add("groundModel", pModel);
	//DELETE_AO pPrimitive;
	//new material
	Material* pMat = pModel->GetMaterial()->Clone();
	//ResourceManager::Instance().Add("groundMaterial", pMat);
	pModel->SetMaterial(pMat);
	pMat->Texture0(Texture::loadTexture("ceilingMain_DIF.dds", BGFX_TEXTURE_MIN_ANISOTROPIC | BGFX_TEXTURE_MAG_ANISOTROPIC));
	pMat->Texture0Repeat(Vector2F(50, 50));
	//
	pModelCpt->SetModel(pModel);
	pModelCpt->SetProgram(m_pProgram);
	pEntity->GetComponentMgr()->AddComponent(pModelCpt);
	pEntity->Initialize();

	m_pWorld->AddEntity(pEntity);
}
Beispiel #16
0
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    SetUpCurrentDirectory();

    //create window
    CustomWindow* pWindow = new CustomWindow;
    pWindow->setSize(800, 600);
    pWindow->setTitle(L"NFEngine Demo - Initializing engine...");
    pWindow->open();

    //initialize engine
    if (EngineInit() != Result::OK)
        return 1;

    Demo_InitEditorBar();

    //create scene and camera
    g_pScene = EngineCreateScene();

    // --------------------------------
    // Build scene
    // --------------------------------

#ifdef DEMO_SEC_CAMERA_ON
    InitSecondaryCamera();
#endif

    //set ambient & background color
    EnviromentDesc envDesc;
    envDesc.ambientLight = Vector(0.02f, 0.03f, 0.04f, 0.0f);
    //envDesc.m_BackgroundColor = Vector(0.04f, 0.05f, 0.07f, 0.03f);
    envDesc.backgroundColor = Vector(0.02f, 0.03f, 0.04f, 0.01f);
    g_pScene->SetEnvironment(&envDesc);

    CollisionShape* pFloorShape = ENGINE_GET_COLLISION_SHAPE("shape_floor");
    pFloorShape->SetCallbacks(OnLoadCustomShapeResource, NULL);
    pFloorShape->Load();
    pFloorShape->AddRef();

    CollisionShape* pFrameShape = ENGINE_GET_COLLISION_SHAPE("shape_frame");
    pFrameShape->SetCallbacks(OnLoadCustomShapeResource, NULL);
    pFrameShape->Load();
    pFrameShape->AddRef();

    CollisionShape* pBoxShape = ENGINE_GET_COLLISION_SHAPE("shape_box");
    pBoxShape->SetCallbacks(OnLoadCustomShapeResource, NULL);
    pBoxShape->Load();
    pBoxShape->AddRef();

    CollisionShape* pBarrelShape = ENGINE_GET_COLLISION_SHAPE("shape_barrel");
    pBarrelShape->SetCallbacks(OnLoadCustomShapeResource, NULL);
    pBarrelShape->Load();
    pBarrelShape->AddRef();

    CollisionShape* pChamberShape = ENGINE_GET_COLLISION_SHAPE("chamber_collision_shape.nfcs");
    pChamberShape->Load();
    pChamberShape->AddRef();


    pWindow->InitCamera();
    pWindow->setTitle(L"NFEngine Demo");


#ifdef SCENE_MINECRAFT
    // SUNLIGHT
    Entity* pDirLightEnt = g_pScene->CreateEntity();
    XOrientation orient;
    orient.x = Vector(0.0f, -0.0f, -0.0f, 0.0f);
    orient.z = Vector(-1.5f, -1.0f, 0.5f, 0.0f);
    orient.y = Vector(0.0f, 1.0f, 0.0f, 0.0f);
    pDirLightEnt->SetOrientation(&orient);
    DirLightDesc dirLight;
    dirLight.m_Far = 100.0f;
    dirLight.m_Splits = 4;
    dirLight.m_LightDist = 1000.0f;

    LightComponent* pDirLight = new LightComponent(pDirLightEnt);
    pDirLight->SetDirLight(&dirLight);
    pDirLight->SetColor(Float3(2.2, 2, 1.8));
    pDirLight->SetShadowMap(1024);

    // MINECRAFT
    Entity* pEnt = g_pScene->CreateEntity();
    pEnt->SetPosition(Vector(0, -70.0f, 0));

    MeshComponent* pMesh = new MeshComponent(pEnt);
    pMesh->SetMeshResource("minecraft.nfm");
#endif

#ifdef SCENE_SPONZA
    // SPONZA
    Entity* pEnt = g_pScene->CreateEntity();
    pEnt->SetPosition(Vector(0, 0, 0));

    MeshComponent* pMesh = new MeshComponent(pEnt);
    pMesh->SetMeshResource("sponza.nfm");

    CollisionShape* pSponzaShape = ENGINE_GET_COLLISION_SHAPE("sponza_collision_shape.nfcs");
    //pSponzaShape->Load();

    BodyComponent* pFloorBody = new BodyComponent(pEnt);
    pFloorBody->EnablePhysics(pSponzaShape);
    pFloorBody->SetMass(0.0);

    pEnt = g_pScene->CreateEntity();
    pEnt->SetPosition(Vector(0.0f, 3.5f, 0.0f));
    LightComponent* pLight = new LightComponent(pEnt);
    OmniLightDesc omni;
    omni.m_ShadowFadeStart = 12.0f;
    omni.m_ShadowFadeEnd = 120.0f;
    omni.m_Radius = 90.0f;
    pLight->SetOmniLight(&omni);
    pLight->SetColor(Float3(50, 50, 50));
    pLight->SetShadowMap(512);
    /*
    // SUNLIGHT
    Entity* pDirLightEnt = g_pScene->CreateEntity();
    XOrientation orient;
    orient.x = Vector(0.0f, -0.0f, -0.0f, 0.0f);
    orient.z = Vector(0.1, -2.3f, 1.05, 0.0f);
    orient.y = Vector(0.0f, 1.0f, 0.0f, 0.0f);
    pDirLightEnt->SetOrientation(&orient);
    DirLightDesc dirLight;
    dirLight.m_Far = 100.0f;
    dirLight.m_Splits = 4;
    dirLight.m_LightDist = 1000.0;

    LightComponent* pDirLight = new LightComponent(pDirLightEnt);
    pDirLight->SetDirLight(&dirLight);
    pDirLight->SetColor(Float3(2.2, 1.3, 0.8));
    pDirLight->SetShadowMap(2048);
    */
#endif

//performance test (many objects and shadowmaps)
#ifdef SCENE_SEGMENTS_PERF_TEST
    for (int x = -4; x < 5; x++)
    {
        for (int z = -4; z < 5; z++)
        {
            Entity* pEntity = g_pScene->CreateEntity();
            pEntity->SetPosition(12.0f * Vector((float)x, 0, (float)z));
            MeshComponent* pMesh = new MeshComponent(pEntity);
            pMesh->SetMeshResource("chamber.nfm");
            BodyComponent* pBody = new BodyComponent(pEntity);
            pBody->EnablePhysics(pChamberShape);


            LightComponent* pLight;
            OmniLightDesc omni;
            pEntity = g_pScene->CreateEntity();
            pEntity->SetPosition(12.0f * Vector(x, 0, z) + Vector(0.0f, 3.5f, 0.0f));
            pLight = new LightComponent(pEntity);

            omni.shadowFadeStart = 80.0f;
            omni.shadowFadeEnd = 120.0f;
            omni.radius = 8.0f;
            pLight->SetOmniLight(&omni);
            pLight->SetColor(Float3(50, 50, 50));
            pLight->SetShadowMap(32);


            pEntity = g_pScene->CreateEntity();
            pEntity->SetPosition(12.0f * Vector(x, 0, z) + Vector(6.0f, 1.8f, 0.0f));
            pLight = new LightComponent(pEntity);
            omni.radius = 3.0f;
            pLight->SetOmniLight(&omni);
            pLight->SetColor(Float3(5.0f, 0.5f, 0.25f));

            pEntity = g_pScene->CreateEntity();
            pEntity->SetPosition(12.0f * Vector(x, 0, z) + Vector(0.0f, 1.8f, 6.0f));
            pLight = new LightComponent(pEntity);
            omni.radius = 3.0f;
            pLight->SetOmniLight(&omni);
            pLight->SetColor(Float3(5.0f, 0.5f, 0.25f));


            /*
            for (int i = -3; i<=3; i++)
            {
            for (int j = 0; j<4; j++)
            {
                for (int k = -3; k<=3; k++)
                {
                    Entity* pCube = g_pScene->CreateEntity();
                    pCube->SetPosition(12.0f * Vector(x,0,z) + 0.6f * Vector(i,j,k) + Vector(0.0f, 0.25f, 0.0f));

                    MeshComponent* pMesh = new MeshComponent(pCube);
                    pMesh->SetMeshResource("cube.nfm");

                    BodyComponent* pBody = new BodyComponent(pCube);
                    pBody->SetMass(0.0f);
                    pBody->EnablePhysics((CollisionShape*)Engine_GetResource(Mesh::COLLISION_SHAPE, "shape_box"));
                }
            }
            }*/
        }
    }
#endif

// infinite looped scene
#ifdef SCENE_SEGMENTS
    BufferOutputStream segmentDesc;

    Matrix mat = MatrixRotationNormal(Vector(0, 1, 0), NFE_MATH_PI / 4.0f);

    // create segments description buffer
    {
        OmniLightDesc omni;
        LightComponent* pLight;
        Entity entity;
        entity.SetPosition(Vector());
        //pEntity->SetMatrix(mat);
        MeshComponent* pMesh = new MeshComponent(&entity);
        pMesh->SetMeshResource("chamber.nfm");
        BodyComponent* pBody = new BodyComponent(&entity);
        pBody->EnablePhysics(pChamberShape);
        entity.Serialize(&segmentDesc, Vector());

        entity.RemoveAllComponents();
        entity.SetPosition(Vector(0.0f, 3.5f, 0.0f));
        /*
            pLight = new LightComponent(&entity);
            omni.m_ShadowFadeEnd = 12.0f;
            omni.m_ShadowFadeStart = 8.0f;
            omni.m_Radius = 9.0f;
            pLight->SetOmniLight(&omni);
            pLight->SetColor(Float3(50, 50, 50));
            pLight->SetShadowMap(512);
                entity.Serialize(&segmentDesc, Vector());
                */
        entity.RemoveAllComponents();
        entity.SetPosition(Vector(6.0f, 1.8f, 0.0f));
        pLight = new LightComponent(&entity);
        omni.m_Radius = 3.0f;
        pLight->SetOmniLight(&omni);
        pLight->SetColor(Float3(5.0f, 0.5f, 0.25f));
        entity.Serialize(&segmentDesc, Vector());

        entity.RemoveAllComponents();
        entity.SetPosition(Vector(0.0f, 1.8f, 6.0f));
        pLight = new LightComponent(&entity);
        omni.m_Radius = 3.0f;
        pLight->SetOmniLight(&omni);
        pLight->SetColor(Float3(5.0f, 0.5f, 0.25f));
        entity.Serialize(&segmentDesc, Vector());
    }

#define SEG_AXIS_NUM 12

    Segment* pSegments[SEG_AXIS_NUM][SEG_AXIS_NUM];

    // create segments array
    for (int i = 0; i < SEG_AXIS_NUM; i++)
    {
        for (int j = 0; j < SEG_AXIS_NUM; j++)
        {
            char segName[32];
            sprintf_s(segName, "seg_%i_%i", i, j);
            pSegments[i][j] = g_pScene->CreateSegment(segName, Vector(5.99f, 1000.0f, 5.99f));
            pSegments[i][j]->AddEntityFromRawBuffer(segmentDesc.GetData(), segmentDesc.GetSize());
        }
    }

    // create links
    for (int x = 0; x < SEG_AXIS_NUM; x++)
    {
        for (int z = 0; z < SEG_AXIS_NUM; z++)
        {
            //make inifinite loop
            for (int depth = 1; depth <= 5; depth++)
            {
                g_pScene->CreateLink(pSegments[x][z], pSegments[(x + depth) % SEG_AXIS_NUM][z],
                                     Vector(depth * 12.0f, 0.0f, 0.0f));
                g_pScene->CreateLink(pSegments[x][z], pSegments[x][(z + depth) % SEG_AXIS_NUM], Vector(0.0, 0.0f,
                                     depth * 12.0f));
            }
        }
    }

    // Set focus
    g_pScene->SetFocusSegment(pSegments[0][0]);
#endif

    /*
    for (int i = -4; i<4; i++)
    {
        for (int j = -10; j<10; j++)
        {
            for (int k = -4; k<4; k++)
            {
                Entity* pCube = g_pScene->CreateEntity();
                pCube->SetPosition(0.75f * Vector(i,j,k));

                MeshComponent* pMesh = new MeshComponent(pCube);
                pMesh->SetMeshResource("cube.nfm");

                BodyComponent* pBody = new BodyComponent(pCube);
                pBody->SetMass(1.0f);
                pBody->EnablePhysics((CollisionShape*)Engine_GetResource(Mesh::COLLISION_SHAPE, "shape_box"));
            }
        }
    }

    //set ambient & background color
    envDesc.m_AmbientLight = Vector(0.001f, 0.001f, 0.001f, 0.0f);
    envDesc.m_BackgroundColor = Vector(0.0f, 0.0f, 0.0f, 0.0f);
    g_pScene->SetEnvironment(&envDesc);

    // SUNLIGHT
    Entity* pDirLightEnt = g_pScene->CreateEntity();
    XOrientation orient;
    orient.x = Vector(0.0f, -0.0f, -0.0f, 0.0f);
    orient.z = Vector(-0.5f, -1.1f, 1.2f, 0.0f);
    orient.y = Vector(0.0f, 1.0f, 0.0f, 0.0f);
    pDirLightEnt->SetOrientation(&orient);
    DirLightDesc dirLight;
    dirLight.m_Far = 100.0f;
    dirLight.m_Splits = 4;
    dirLight.m_LightDist = 1000.0f;

    LightComponent* pDirLight = new LightComponent(pDirLightEnt);
    pDirLight->SetDirLight(&dirLight);
    pDirLight->SetColor(Float3(2.2, 2, 1.8));
    pDirLight->SetShadowMap(1024);

    pFirstWindow->cameraEntity->SetPosition(Vector(0.0f, 1.6f, -20.0f, 0.0f));
    */

    // message loop

    DrawRequest drawRequests[2];

    Common::Timer timer;
    timer.Start();
    while (!pWindow->isClosed())
    {
        //measure delta time
        g_DeltaTime = (float)timer.Stop();
        timer.Start();

        UpdateRequest updateReq;
        updateReq.pScene = g_pScene;
        updateReq.deltaTime = g_DeltaTime;


        pWindow->processMessages();
        pWindow->UpdateCamera();

        drawRequests[0].deltaTime = g_DeltaTime;
        drawRequests[0].pView = pWindow->view;
        drawRequests[1].deltaTime = g_DeltaTime;
        drawRequests[1].pView = g_pSecondaryCameraView;
        EngineAdvance(drawRequests, 2, &updateReq, 1);

        ProcessSceneEvents();

        // print focus segment name
        wchar_t str[128];
        Segment* pFocus = g_pScene->GetFocusSegment();
        swprintf(str, L"NFEngine Demo (%S) - focus: %S", PLATFORM_STR,
                 (pFocus != 0) ? pFocus->GetName() : "NONE");
        pWindow->setTitle(str);
    }

    // for testing purposes
    Common::FileOutputStream test_stream("test.xml");
    g_pScene->Serialize(&test_stream, SerializationFormat::Xml, false);

    EngineDeleteScene(g_pScene);
    delete pWindow;
    EngineRelease();

//detect memory leaks
#ifdef _DEBUG
    _CrtDumpMemoryLeaks();
#endif

    return 0;
}