<commit_before>// @(#)root/cintex:$Id$
// Author: Pere Mato 2005

// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "Cintex/Cintex.h"
#include "CINTdefs.h"
#include "CINTVariableBuilder.h"
#include "CINTScopeBuilder.h"
#include "CINTCommentBuffer.h"

#include "Api.h"

#include <iomanip>
#include <sstream>

using namespace ROOT::Reflex;
using namespace std;

namespace ROOT { namespace Cintex {

   CINTVariableBuilder::CINTVariableBuilder(const ROOT::Reflex::Member& m)
      : fVariable(m) {
      // Default constructor.
   }

   CINTVariableBuilder::~CINTVariableBuilder() {
      // Destructor.
   }

   void CINTVariableBuilder::Setup() {
      // Setup variable info.
      CINTScopeBuilder::Setup(fVariable.TypeOf());

      Scope scope = fVariable.DeclaringScope();
      CINTScopeBuilder::Setup(scope);

      bool global = scope.IsTopScope();

      if ( global ) {
         ::G__resetplocal();
      }
      else {
         string sname = scope.Name(SCOPED);
         int stagnum = ::G__defined_tagname(sname.c_str(), 2);
         ::G__tag_memvar_setup(stagnum);
      }

      Setup(fVariable);

      if ( global ) {
         ::G__resetglobalenv();
      }
      else {
         ::G__tag_memvar_reset();
      }
      return;
   }

   static void writeArrayIndex(ostream &ost, const Type& array)
   {
      Type toArray = array.ToType();
      if ( toArray.IsArray() ) writeArrayIndex(ost,toArray);
      ost << "[" << array.ArrayLength() << "]";
   }

   void CINTVariableBuilder::Setup(const Member& dm ) {
      // Setup variable info.
      char* comment = NULL;

      const char* ref_t = "pool::Reference";
      const char* tok_t = "pool::Token";

      Type fClass = Type::ByName(dm.DeclaringScope().Name(SCOPED));
      string fName(CintName(fClass));

      std::string cm = dm.Properties().HasProperty("comment") ?
         dm.Properties().PropertyAsString("comment") : std::string("");

      Type dmType = dm.TypeOf();
      if (dm.Properties().HasProperty("iotype")) {
         dmType = Reflex::Type::ByName(dm.Properties().PropertyAsString("iotype"));
      }
      while ( dmType.IsTypedef() ) dmType = dmType.ToType();
      if ( !dmType && dm.IsTransient() )  {
         // Before giving up, let's ask CINT:
         int tagnum = G__defined_tagname(dmType.Name().c_str(), 2);

         if (tagnum < 0) {
            if( Cintex::Debug() ) cout << "Cintex: Ignore transient member: "
               << dm.Name(SCOPED) << " [No valid reflection class]"
               << " " << dmType.Name() << endl;
            return;
         }
      }
      else if ( !dmType )  {
         if( Cintex::Debug() > 0 )  {
            cout << "Cintex: WARNING: Member: "
                 << dm.Name(SCOPED) << " [No valid reflection class]" << endl;
         }
         //throw std::runtime_error("Member: "+fName+"::"+dm.Name()+" [No valid reflection class]");
      }
      //--- Add the necessary artificial comments ------
      if ( dm.IsTransient() ||
           IsSTL(fName) ||
           IsTypeOf(fClass, ref_t) ||
           IsTypeOf(fClass, tok_t) )  {
         char* com = new char[cm.length()+4];
         ::sprintf(com,"! %s",cm.c_str());
         comment = com;
         CommentBuffer::Instance().Add(comment);
      }
      else if ( (dmType.IsClass() || dmType.IsStruct()) &&
                (IsTypeOf(dmType,ref_t) || IsTypeOf(dmType,tok_t)) )  {
         char* com = new char[cm.length()+4];
         ::sprintf(com,"|| %s",cm.c_str());
         comment = com;
         CommentBuffer::Instance().Add(comment);
      }
      else if ( !cm.empty() )  {
         char* com = new char[cm.length()+4];
         ::strcpy(com, cm.c_str());
         comment = com;
         CommentBuffer::Instance().Add(comment);
      }

      Indirection  indir = IndirectionGet(dmType);
      CintTypeDesc type = CintType(indir.second);
      string dname = dm.Properties().HasProperty("ioname") ? dm.Properties().PropertyAsString("ioname") : dm.Name();
      ostringstream ost;
      if ( dmType.IsArray() ) {
         ost << dname;
         writeArrayIndex(ost,dmType);
         ost << "=";
      } else                    ost << dname << "=";
      string expr = ost.str();
      int member_type     = type.first;
      int member_indir    = 0;
      int member_tagnum   = -1;
      int member_typnum   = -1;
      int member_isstatic = G__AUTO;
      if (dm.IsStatic() || dm.DeclaringScope().IsNamespace())
         member_isstatic = G__LOCALSTATIC;
      switch(indir.first)  {
      case 0:
         break;
      case 1:
         member_type -= 'a'-'A';            // if pointer: 'f' -> 'F' etc.
         break;
      default:
         member_type -= 'a'-'A';            // if pointer: 'f' -> 'F' etc.
         member_indir = indir.first;
         break;
      }

      if ( type.first == 'u' )  {
         // Large integer definition depends of the platform
#if defined(_WIN32) && !defined(__CINT__)
         typedef __int64 longlong;
         typedef unsigned __int64 ulonglong;
#else
         typedef long long int longlong; /* */
         typedef unsigned long long int /**/ ulonglong;
#endif

         //dependencies.push_back(indir.second);
         member_tagnum = dm.Properties().HasProperty("iotype") ? CintTag(dm.Properties().PropertyAsString("iotype")) : CintTag(type.second);
         if ( typeid(longlong) == indir.second.TypeInfo() )
            ::G__loadlonglong(&member_tagnum, &member_typnum, G__LONGLONG);
         else if ( typeid(ulonglong) == indir.second.TypeInfo() )
            ::G__loadlonglong(&member_tagnum, &member_typnum, G__ULONGLONG);
         else if ( typeid(long double) == indir.second.TypeInfo() )
            ::G__loadlonglong(&member_tagnum, &member_typnum, G__LONGDOUBLE);
      }

      int member_access = 0;
      if ( dm.IsPrivate() )        member_access = G__PRIVATE;
      else if ( dm.IsProtected() ) member_access = G__PROTECTED;
      else if ( dm.IsPublic() )    member_access = G__PUBLIC;

      if ( Cintex::Debug() > 2 )  {
         std::cout
            << std::setw(24) << std::left << "Cintex: declareField>"
            << "  [" << char(member_type)
            << "," << std::right << std::setw(3) << dm.Offset()
            << "," << std::right << std::setw(2) << member_indir
            << "," << std::right << std::setw(3) << member_tagnum
            << "] "
            << (dmType.IsConst() ? "const " : "")
            << std::left << std::setw(7)
            << (G__AUTO==member_isstatic ? "auto " : "static ")
            << std::left << std::setw(24) << dname
            << " \"" << (char*)(comment ? comment : "(None)") << "\""
            << std::endl
            << std::setw(24) << std::left << "Cintex: declareField>"
            << "  Type:"
            << std::left << std::setw(24) << ("[" + (dm.Properties().HasProperty("iotype") ? dm.Properties().PropertyAsString("iotype") : dmType.Name(SCOPED)) + "]")
            << " DeclBy:" << fClass.Name(SCOPED)
            << std::endl;
      }
      ::G__memvar_setup((void*)dm.Offset(),                         // p
                        member_type,                                // type
                        member_indir,                               // indirection
                        dmType.IsConst(),                        // const
                        member_tagnum,                              // tagnum
                        member_typnum,                              // typenum
                        member_isstatic,                            // statictype
                        member_access,                              // accessin
                        expr.c_str(),                               // expression
                        0,                                          // define macro
                        comment                                     // comment
                        );
   }

}}
<commit_msg>In Cintex, we definition multi-dimensional array, get the dims in the right order.<commit_after>// @(#)root/cintex:$Id$
// Author: Pere Mato 2005

// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "Cintex/Cintex.h"
#include "CINTdefs.h"
#include "CINTVariableBuilder.h"
#include "CINTScopeBuilder.h"
#include "CINTCommentBuffer.h"

#include "Api.h"

#include <iomanip>
#include <sstream>

using namespace ROOT::Reflex;
using namespace std;

namespace ROOT { namespace Cintex {

   CINTVariableBuilder::CINTVariableBuilder(const ROOT::Reflex::Member& m)
      : fVariable(m) {
      // Default constructor.
   }

   CINTVariableBuilder::~CINTVariableBuilder() {
      // Destructor.
   }

   void CINTVariableBuilder::Setup() {
      // Setup variable info.
      CINTScopeBuilder::Setup(fVariable.TypeOf());

      Scope scope = fVariable.DeclaringScope();
      CINTScopeBuilder::Setup(scope);

      bool global = scope.IsTopScope();

      if ( global ) {
         ::G__resetplocal();
      }
      else {
         string sname = scope.Name(SCOPED);
         int stagnum = ::G__defined_tagname(sname.c_str(), 2);
         ::G__tag_memvar_setup(stagnum);
      }

      Setup(fVariable);

      if ( global ) {
         ::G__resetglobalenv();
      }
      else {
         ::G__tag_memvar_reset();
      }
      return;
   }

   static void writeArrayIndex(ostream &ost, const Type& array)
   {
      Type toArray = array.ToType();
      ost << "[" << array.ArrayLength() << "]";
      if ( toArray.IsArray() ) writeArrayIndex(ost,toArray);
   }

   void CINTVariableBuilder::Setup(const Member& dm ) {
      // Setup variable info.
      char* comment = NULL;

      const char* ref_t = "pool::Reference";
      const char* tok_t = "pool::Token";

      Type fClass = Type::ByName(dm.DeclaringScope().Name(SCOPED));
      string fName(CintName(fClass));

      std::string cm = dm.Properties().HasProperty("comment") ?
         dm.Properties().PropertyAsString("comment") : std::string("");

      Type dmType = dm.TypeOf();
      if (dm.Properties().HasProperty("iotype")) {
         dmType = Reflex::Type::ByName(dm.Properties().PropertyAsString("iotype"));
      }
      while ( dmType.IsTypedef() ) dmType = dmType.ToType();
      if ( !dmType && dm.IsTransient() )  {
         // Before giving up, let's ask CINT:
         int tagnum = G__defined_tagname(dmType.Name().c_str(), 2);

         if (tagnum < 0) {
            if( Cintex::Debug() ) cout << "Cintex: Ignore transient member: "
               << dm.Name(SCOPED) << " [No valid reflection class]"
               << " " << dmType.Name() << endl;
            return;
         }
      }
      else if ( !dmType )  {
         if( Cintex::Debug() > 0 )  {
            cout << "Cintex: WARNING: Member: "
                 << dm.Name(SCOPED) << " [No valid reflection class]" << endl;
         }
         //throw std::runtime_error("Member: "+fName+"::"+dm.Name()+" [No valid reflection class]");
      }
      //--- Add the necessary artificial comments ------
      if ( dm.IsTransient() ||
           IsSTL(fName) ||
           IsTypeOf(fClass, ref_t) ||
           IsTypeOf(fClass, tok_t) )  {
         char* com = new char[cm.length()+4];
         ::sprintf(com,"! %s",cm.c_str());
         comment = com;
         CommentBuffer::Instance().Add(comment);
      }
      else if ( (dmType.IsClass() || dmType.IsStruct()) &&
                (IsTypeOf(dmType,ref_t) || IsTypeOf(dmType,tok_t)) )  {
         char* com = new char[cm.length()+4];
         ::sprintf(com,"|| %s",cm.c_str());
         comment = com;
         CommentBuffer::Instance().Add(comment);
      }
      else if ( !cm.empty() )  {
         char* com = new char[cm.length()+4];
         ::strcpy(com, cm.c_str());
         comment = com;
         CommentBuffer::Instance().Add(comment);
      }

      Indirection  indir = IndirectionGet(dmType);
      CintTypeDesc type = CintType(indir.second);
      string dname = dm.Properties().HasProperty("ioname") ? dm.Properties().PropertyAsString("ioname") : dm.Name();
      ostringstream ost;
      if ( dmType.IsArray() ) {
         ost << dname;
         writeArrayIndex(ost,dmType);
         ost << "=";
      } else                    ost << dname << "=";
      string expr = ost.str();
      int member_type     = type.first;
      int member_indir    = 0;
      int member_tagnum   = -1;
      int member_typnum   = -1;
      int member_isstatic = G__AUTO;
      if (dm.IsStatic() || dm.DeclaringScope().IsNamespace())
         member_isstatic = G__LOCALSTATIC;
      switch(indir.first)  {
      case 0:
         break;
      case 1:
         member_type -= 'a'-'A';            // if pointer: 'f' -> 'F' etc.
         break;
      default:
         member_type -= 'a'-'A';            // if pointer: 'f' -> 'F' etc.
         member_indir = indir.first;
         break;
      }

      if ( type.first == 'u' )  {
         // Large integer definition depends of the platform
#if defined(_WIN32) && !defined(__CINT__)
         typedef __int64 longlong;
         typedef unsigned __int64 ulonglong;
#else
         typedef long long int longlong; /* */
         typedef unsigned long long int /**/ ulonglong;
#endif

         //dependencies.push_back(indir.second);
         member_tagnum = dm.Properties().HasProperty("iotype") ? CintTag(dm.Properties().PropertyAsString("iotype")) : CintTag(type.second);
         if ( typeid(longlong) == indir.second.TypeInfo() )
            ::G__loadlonglong(&member_tagnum, &member_typnum, G__LONGLONG);
         else if ( typeid(ulonglong) == indir.second.TypeInfo() )
            ::G__loadlonglong(&member_tagnum, &member_typnum, G__ULONGLONG);
         else if ( typeid(long double) == indir.second.TypeInfo() )
            ::G__loadlonglong(&member_tagnum, &member_typnum, G__LONGDOUBLE);
      }

      int member_access = 0;
      if ( dm.IsPrivate() )        member_access = G__PRIVATE;
      else if ( dm.IsProtected() ) member_access = G__PROTECTED;
      else if ( dm.IsPublic() )    member_access = G__PUBLIC;

      if ( Cintex::Debug() > 2 )  {
         std::cout
            << std::setw(24) << std::left << "Cintex: declareField>"
            << "  [" << char(member_type)
            << "," << std::right << std::setw(3) << dm.Offset()
            << "," << std::right << std::setw(2) << member_indir
            << "," << std::right << std::setw(3) << member_tagnum
            << "] "
            << (dmType.IsConst() ? "const " : "")
            << std::left << std::setw(7)
            << (G__AUTO==member_isstatic ? "auto " : "static ")
            << std::left << std::setw(24) << dname
            << " \"" << (char*)(comment ? comment : "(None)") << "\""
            << std::endl
            << std::setw(24) << std::left << "Cintex: declareField>"
            << "  Type:"
            << std::left << std::setw(24) << ("[" + (dm.Properties().HasProperty("iotype") ? dm.Properties().PropertyAsString("iotype") : dmType.Name(SCOPED)) + "]")
            << " DeclBy:" << fClass.Name(SCOPED)
            << std::endl;
      }
      ::G__memvar_setup((void*)dm.Offset(),                         // p
                        member_type,                                // type
                        member_indir,                               // indirection
                        dmType.IsConst(),                        // const
                        member_tagnum,                              // tagnum
                        member_typnum,                              // typenum
                        member_isstatic,                            // statictype
                        member_access,                              // accessin
                        expr.c_str(),                               // expression
                        0,                                          // define macro
                        comment                                     // comment
                        );
   }

}}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "TerrainChunkRenderer.h"
#include "GLTerrainProgram.h"
#include "TerrainChunk.h"

TerrainChunkRenderer::TerrainChunkRenderer()
{
    previousShader = NULL;
}

TerrainChunkRenderer::~TerrainChunkRenderer()
{
	//Destroy all the render slots
	for (auto slot : renderSlots)
		delete slot.second;
	for (auto slot : openSlots)
		delete slot;
}

TerrainChunkRenderer::HotChunk::HotChunk()
{
	glGenBuffers(1,&vertexData);
    glGenBuffers(1,&indexData);
	glGenVertexArrays(1,&vertexArrayBuffer);
}

TerrainChunkRenderer::HotChunk::~HotChunk()
{
	glDeleteBuffers(1,&vertexData);
    glDeleteBuffers(1,&indexData);
	glDeleteVertexArrays(1,&vertexArrayBuffer);
}

//Render the set chunk
void TerrainChunkRenderer::HotChunk::Render(GLTerrainProgram * shader)
{
	glBindVertexArray ( vertexArrayBuffer );
    glDrawElements(GL_TRIANGLES, (GLsizei) indexCount, GL_UNSIGNED_SHORT, 0);
}

void TerrainChunkRenderer::HotChunk::Set(TerrainChunk * chunk, GLTerrainProgram * shader)
{
	vertexCount = chunk->VertexDataSize;
    indexCount = chunk->VertexIndicesSize;

	//Cache vertex data
	glBindVertexArray ( vertexArrayBuffer );

	//vertex positions
	glBindBuffer ( GL_ARRAY_BUFFER, vertexData );
	glBufferData ( GL_ARRAY_BUFFER, vertexCount*sizeof(TerrainChunk::ChunkVertexData), chunk->VertexData, GL_STATIC_DRAW );
	glEnableVertexAttribArray ( shader->AttributeVertex() );
	glVertexAttribPointer ( shader->AttributeVertex(), 3, GL_FLOAT, GL_FALSE, sizeof(TerrainChunk::ChunkVertexData), (void*)offsetof(TerrainChunk::ChunkVertexData,Vertex) );
	glEnableVertexAttribArray ( shader->AttributeTexture() );
	glVertexAttribPointer ( shader->AttributeTexture(), 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof(TerrainChunk::ChunkVertexData), (void*)offsetof(TerrainChunk::ChunkVertexData,TextureCoordinateX) );
	glEnableVertexAttribArray( shader->AttributeShading() );
	glVertexAttribPointer ( shader->AttributeShading(), 1, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(TerrainChunk::ChunkVertexData), (void*)offsetof(TerrainChunk::ChunkVertexData,Shading) );

    // index positions
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexData);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort) * indexCount, chunk->VertexIndices, GL_STATIC_DRAW);

    // Don't fuck the VAOs
    glBindVertexArray( 0 );
}

void TerrainChunkRenderer::StartRendering(GLTerrainProgram * shader)
{
	// Use the terrain shader
	shader->UseProgram();
    shader->Camera.Apply();
}

void TerrainChunkRenderer::RenderTerrainChunk(vec2 tilePos, TerrainChunk * chunk, GLTerrainProgram * shader) {
	//Draw the chunk relative to itself
	shader->Model.PushMatrix();
	shader->Model.Translate(chunk->X,chunk->Y,0);
	shader->Model.Apply();

	//Check if this chunk is already buffered
	vec2 chunkPosition = tilePos+vec2(chunk->X,chunk->Y);
	auto slotIterator = renderSlots.find(chunkPosition);
	HotChunk * renderer;
	if (slotIterator == renderSlots.end()) {
		//Doesn't exist, buffer it
		//find an open slot
		HotChunk * openSlot;
		if (openSlots.size() > 0) {
			openSlot = openSlots.back();
			openSlots.pop_back();
		}
		else
			openSlot = new HotChunk();

		//Set the slot to hold the given chunk
		openSlot->Set(chunk,shader);
		//The chunk has been uploaded and is no longer dirty
		chunk->Dirty = false;

		//Save the slot as in use
		renderSlots[chunkPosition] = openSlot;
		renderer = openSlot;
	}
	else if (chunk->Dirty) {
		//Re-set the renderer
		renderer = slotIterator->second;
		renderer->Set(chunk,shader);
		chunk->Dirty = false;
	}
	else
		renderer = slotIterator->second;

	//Run the renderer
	renderer->Render(shader);
	//Mark it as used
	renderer->Rendered = true;

	shader->Model.PopMatrix();
}

void TerrainChunkRenderer::FinishRendering(GLTerrainProgram * shader) {
	//Find renderers which were not used and mark them as free
	for (auto it = renderSlots.begin(); it != renderSlots.end();) {
		if (it->second->Rendered) {
			it->second->Rendered = false;
			it++;
		}
		else {
			openSlots.push_back(it->second);
			it = renderSlots.erase(it);
		}
	}

    // Unbind VAO (we know that internal to the renderer, it won't screw them up, but the outside is a wild place...)
    glBindVertexArray( 0 );
}<commit_msg>Matt wanted more comments in chunk renderer<commit_after><|endoftext|>


<commit_before>#ifndef UTIL_PARSER_HPP
#define UTIL_PARSER_HPP

#include <fstream>
#include <unordered_map>
#include "trim.hpp"

namespace util {
class parser {
private:
    std::ifstream reader;
    std::unordered_map<std::string, std::string> file;
public:
    parser() noexcept: reader("Shinobi") {}

    bool is_open() const noexcept {
        return reader.is_open();
    }

    void reopen() noexcept {
        reader.close();
        reader.open("Shinobi");
    }

    void parse() noexcept {
        std::string lines;
        while(std::getline(reader, lines)) {
            auto begin = lines.find_first_not_of(" \f\t\v");
            if(begin == std::string::npos)
                continue;
            if(std::string("#").find(lines[begin]) != std::string::npos)
                continue;
            if(std::string(";").find(lines[begin]) != std::string::npos)
                continue;

            auto equals = lines.find(":=");
            auto concat = lines.find("+=");

            if(concat != std::string::npos && (concat + 2) < lines.size()) {
                std::string key(lines.data(), lines.data() + concat);
                std::string value(lines.data() + concat + 2, lines.data() + lines.size());
                trim(key);
                trim(value);

                if(file.count(key)) {
                    file[key].push_back(' ');
                    file[key] += value;
                    continue;
                }

                file.emplace(key, value);
                continue;
            }

            if(equals != std::string::npos && (equals + 2) < lines.size()) {
                std::string key(lines.data(), lines.data() + equals);
                std::string value(lines.data() + equals + 2, lines.data() + lines.size());
                trim(key);
                trim(value);

                file.emplace(key, value);
            }
        }
    }

    std::string get(const std::string& key, const std::string& default_value) const noexcept {
        auto it = file.find(key);
        return it != file.end() ? it->second : default_value;
    }
};
} // util

#endif // UTIL_PARSER_HPP<commit_msg>Add support for platform dependent if blocks<commit_after>#ifndef UTIL_PARSER_HPP
#define UTIL_PARSER_HPP

#include <fstream>
#include <unordered_map>
#include "trim.hpp"
#include "config.hpp"

namespace util {
class parser {
private:
    std::ifstream reader;
    bool if_block;
    std::string platform;
    std::unordered_map<std::string, std::string> file;

    bool parse_equal(size_t equals, const std::string& lines) noexcept {
        if(equals != std::string::npos && (equals + 2) < lines.size()) {
            std::string key(lines.data(), lines.data() + equals);
            std::string value(lines.data() + equals + 2, lines.data() + lines.size());
            trim(key);
            trim(value);

            file.emplace(key, value);
            return true;
        }
        return false;
    }

    bool parse_concat(size_t concat, const std::string& lines) noexcept {
        if(concat != std::string::npos && (concat + 2) < lines.size()) {
            std::string key(lines.data(), lines.data() + concat);
            std::string value(lines.data() + concat + 2, lines.data() + lines.size());
            trim(key);
            trim(value);

            if(file.count(key)) {
                file[key].push_back(' ');
                file[key] += value;
                return true;
            }

            file.emplace(key, value);
            return true;
        }

        return false;
    }

    void parse_if_block() noexcept {
        std::string line;
        while(std::getline(reader, line)) {
            auto begin = line.find_first_not_of(" \f\t\v");
            if(begin == std::string::npos)
                continue;
            if(std::string("#").find(line[begin]) != std::string::npos)
                continue;
            if(std::string(";").find(line[begin]) != std::string::npos)
                continue;
            if(std::string("endif").find(line[begin]) != std::string::npos) {
                if_block = false;
                break;
            }

            auto equals = line.find(":=");
            auto concat = line.find("+=");

            if(parse_concat(concat, line)) {
                continue;
            }

            parse_equal(equals, line);
        }
    }
public:
    parser() noexcept: reader("Shinobi"), if_block(false), platform("Other") {}

    bool is_open() const noexcept {
        return reader.is_open();
    }

    void reopen() noexcept {
        reader.close();
        reader.open("Shinobi");
    }

    void parse() noexcept {
        std::string lines;

        #if defined(SHINOBI_WINDOWS)
        platform = "Windows";
        #elif defined(SHINOBI_LINUX)
        platform = "Linux";
        #elif defined(SHINOBI_MACOS)
        platform = "MacOS";
        #endif

        while(std::getline(reader, lines)) {
            auto begin = lines.find_first_not_of(" \f\t\v");
            if(begin == std::string::npos)
                continue;
            if(std::string("#").find(lines[begin]) != std::string::npos)
                continue;
            if(std::string(";").find(lines[begin]) != std::string::npos)
                continue;

            if(lines.find("if") != std::string::npos) {
                if_block = true;
                if(lines.find("if " + platform) != std::string::npos) {
                    parse_if_block();
                }
                continue;
            }

            if(lines.find("endif") != std::string::npos) {
                if_block = false;
                continue;
            }

            auto equals = lines.find(":=");
            auto concat = lines.find("+=");

            if(!if_block && parse_concat(concat, lines)) {
                continue;
            }

            if(!if_block && parse_equal(equals, lines)) {
                continue;
            }
        }
    }

    std::string get(const std::string& key, const std::string& default_value) const noexcept {
        auto it = file.find(key);
        return it != file.end() ? it->second : default_value;
    }

    std::string get_platform() const {
        return platform;
    }

    auto begin() -> decltype(file.begin()) {
        return file.begin();
    }

    auto end() -> decltype(file.end()) {
        return file.end();
    }
};
} // util

#endif // UTIL_PARSER_HPP<|endoftext|>


<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/ui/native_app_window_tizen.h"

#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "ui/aura/window.h"
#include "ui/gfx/transform.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/screen.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "xwalk/runtime/browser/ui/splash_screen_tizen.h"
#include "xwalk/runtime/browser/ui/top_view_layout_views.h"
#include "xwalk/runtime/browser/xwalk_browser_main_parts_tizen.h"

namespace {

static gfx::Display::Rotation ToDisplayRotation(gfx::Display display,
    blink::WebScreenOrientationType orientation) {
  gfx::Display::Rotation rot = gfx::Display::ROTATE_0;
  switch (orientation) {
    case blink::WebScreenOrientationUndefined:
    case blink::WebScreenOrientationPortraitPrimary:
      rot = gfx::Display::ROTATE_0;
      break;
    case blink::WebScreenOrientationLandscapeSecondary:
      rot = gfx::Display::ROTATE_90;
      break;
    case blink::WebScreenOrientationPortraitSecondary:
      rot = gfx::Display::ROTATE_180;
      break;
    case blink::WebScreenOrientationLandscapePrimary:
      rot = gfx::Display::ROTATE_270;
      break;
  default:
      NOTREACHED();
  }

  if (display.bounds().width() > display.bounds().height()) {
    // Landscape devices have landscape-primary as default.
    rot = static_cast<gfx::Display::Rotation>((rot - 1) % 4);
  }

  return rot;
}

static void SetWindowRotation(aura::Window* window, gfx::Display display) {
  // This methods assumes that window is fullscreen.

#if defined(OS_TIZEN_MOBILE)
  // Assumes portrait display; shows overlay indicator in landscape only.
  bool useOverlay = display.rotation() == gfx::Display::ROTATE_90 ||
      display.rotation() == gfx::Display::ROTATE_180;
  top_view_layout()->SetUseOverlay(enableOverlay);
  indicator_widget_->SetDisplay(display);
#endif

  // As everything is calculated from the fixed position we do
  // not update the display bounds after rotation change.
  gfx::Transform rotate;
  float one_pixel = 1.0f / display.device_scale_factor();
  switch (display.rotation()) {
    case gfx::Display::ROTATE_0:
      break;
    case gfx::Display::ROTATE_90:
      rotate.Translate(display.bounds().width() - one_pixel, 0);
      rotate.Rotate(90);
      break;
    case gfx::Display::ROTATE_270:
      rotate.Translate(0, display.bounds().height() - one_pixel);
      rotate.Rotate(270);
      break;
    case gfx::Display::ROTATE_180:
      rotate.Translate(display.bounds().width() - one_pixel,
                       display.bounds().height() - one_pixel);
      rotate.Rotate(180);
      break;
  }

  window->SetTransform(rotate);
}

}  // namespace.

namespace xwalk {

NativeAppWindowTizen::NativeAppWindowTizen(
    const NativeAppWindow::CreateParams& create_params)
    : NativeAppWindowViews(create_params),
#if defined(OS_TIZEN_MOBILE)
      indicator_widget_(new TizenSystemIndicatorWidget()),
      indicator_container_(new WidgetContainerView(indicator_widget_)),
#endif
      orientation_lock_(blink::WebScreenOrientationLockAny) {}

void NativeAppWindowTizen::Initialize() {
  NativeAppWindowViews::Initialize();

  const base::FilePath& splash_screen_path = create_params().splash_screen_path;
  if (!splash_screen_path.empty()) {
    splash_screen_.reset(new SplashScreenTizen(
        GetWidget(), splash_screen_path, create_params().web_contents));
    splash_screen_->Start();
  }

  // Get display info such as device_scale_factor, and current
  // rotation (orientation).
  // NOTE: This is a local copy of the info.
  display_ = gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();

  aura::Window* root_window = GetNativeWindow()->GetRootWindow();
  DCHECK(root_window);
  root_window->AddObserver(this);

  SensorProvider::GetInstance()->AddObserver(this);

  if (SensorProvider::GetInstance()->connected()) {
    OnScreenOrientationChanged(
        SensorProvider::GetInstance()->GetScreenOrientation());
  }
}

NativeAppWindowTizen::~NativeAppWindowTizen() {
  if (SensorProvider::GetInstance()->connected())
    SensorProvider::GetInstance()->RemoveObserver(this);
}

void NativeAppWindowTizen::LockOrientation(
      blink::WebScreenOrientationLockType lock) {
  orientation_lock_ = lock;
  if (SensorProvider::GetInstance()->connected())
    OnScreenOrientationChanged(
        SensorProvider::GetInstance()->GetScreenOrientation());
}

void NativeAppWindowTizen::ViewHierarchyChanged(
    const ViewHierarchyChangedDetails& details) {
  if (details.is_add && details.child == this) {
    NativeAppWindowViews::ViewHierarchyChanged(details);

#if defined(OS_TIZEN_MOBILE)
    indicator_widget_->Initialize(GetNativeWindow());
    top_view_layout()->set_top_view(indicator_container_.get());
    AddChildView(indicator_container_.get());
#endif
  }
}

void NativeAppWindowTizen::OnWindowBoundsChanged(
    aura::Window* window,
    const gfx::Rect& old_bounds,
    const gfx::Rect& new_bounds) {
  aura::Window* root_window = GetNativeWindow()->GetRootWindow();
  DCHECK_EQ(root_window, window);

  // Change the bounds of child windows to make touch work correctly.
  GetNativeWindow()->parent()->SetBounds(new_bounds);
  GetNativeWindow()->SetBounds(new_bounds);

  GetWidget()->GetRootView()->SetSize(new_bounds.size());
}

void NativeAppWindowTizen::OnWindowDestroying(aura::Window* window) {
  // Must be removed here and not in the destructor, as the aura::Window is
  // already destroyed when our destructor runs.
  window->RemoveObserver(this);
}

void NativeAppWindowTizen::OnWindowVisibilityChanging(
    aura::Window* window, bool visible) {
  if (!visible)
    return;
  SetDisplayRotation(display_);
}

blink::WebScreenOrientationType
    NativeAppWindowTizen::FindNearestAllowedOrientation(
        blink::WebScreenOrientationType orientation) const {
  switch (orientation_lock_) {
    case blink::WebScreenOrientationLockDefault:
    case blink::WebScreenOrientationLockAny:
      return orientation;
    case blink::WebScreenOrientationLockLandscape: {
      switch (orientation) {
        case blink::WebScreenOrientationLandscapePrimary:
        case blink::WebScreenOrientationLandscapeSecondary:
          return orientation;
        default:
          return blink::WebScreenOrientationLandscapePrimary;
      }
      break;
    }
    case blink::WebScreenOrientationLockPortrait: {
      switch (orientation) {
        case blink::WebScreenOrientationPortraitPrimary:
        case blink::WebScreenOrientationPortraitSecondary:
          return orientation;
        default:
          return blink::WebScreenOrientationPortraitPrimary;
      }
      break;
    }
    case blink::WebScreenOrientationLockPortraitPrimary:
      return blink::WebScreenOrientationPortraitPrimary;
    case blink::WebScreenOrientationLockPortraitSecondary:
      return blink::WebScreenOrientationPortraitSecondary;
    case blink::WebScreenOrientationLockLandscapePrimary:
      return blink::WebScreenOrientationLandscapePrimary;
    case blink::WebScreenOrientationLockLandscapeSecondary:
      return blink::WebScreenOrientationLandscapeSecondary;
  default:
      NOTREACHED();
  }
  return orientation;
}

void NativeAppWindowTizen::OnScreenOrientationChanged(
    blink::WebScreenOrientationType orientation) {

  // We always store the current sensor position, even if we do not
  // apply it in case the window is invisible.
  gfx::Display::Rotation rot = ToDisplayRotation(display_,
      FindNearestAllowedOrientation(orientation));
  if (display_.rotation() == rot)
    return;

  display_.set_rotation(rot);
  SetDisplayRotation(display_);
}

void NativeAppWindowTizen::OnSensorConnected() {
  OnScreenOrientationChanged(
      SensorProvider::GetInstance()->GetScreenOrientation());
}

void NativeAppWindowTizen::SetDisplayRotation(gfx::Display display) {
  aura::Window* window = GetNativeWindow()->GetRootWindow();
  if (!window->IsVisible())
    return;

  SetWindowRotation(window, display);
}

}  // namespace xwalk
<commit_msg>[Tizen] Fix calculation for display rotation angle.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/ui/native_app_window_tizen.h"

#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "ui/aura/window.h"
#include "ui/gfx/transform.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/screen.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "xwalk/runtime/browser/ui/splash_screen_tizen.h"
#include "xwalk/runtime/browser/ui/top_view_layout_views.h"
#include "xwalk/runtime/browser/xwalk_browser_main_parts_tizen.h"

namespace {

static gfx::Display::Rotation ToDisplayRotation(gfx::Display display,
    blink::WebScreenOrientationType orientation) {
  gfx::Display::Rotation rot = gfx::Display::ROTATE_0;
  switch (orientation) {
    case blink::WebScreenOrientationUndefined:
    case blink::WebScreenOrientationPortraitPrimary:
      rot = gfx::Display::ROTATE_0;
      break;
    case blink::WebScreenOrientationLandscapeSecondary:
      rot = gfx::Display::ROTATE_90;
      break;
    case blink::WebScreenOrientationPortraitSecondary:
      rot = gfx::Display::ROTATE_180;
      break;
    case blink::WebScreenOrientationLandscapePrimary:
      rot = gfx::Display::ROTATE_270;
      break;
  default:
      NOTREACHED();
  }

  if (display.bounds().width() > display.bounds().height()) {
    // Landscape devices have landscape-primary as default.
    rot = static_cast<gfx::Display::Rotation>((rot + 3) % 4);
  }

  return rot;
}

static void SetWindowRotation(aura::Window* window, gfx::Display display) {
  // This methods assumes that window is fullscreen.

#if defined(OS_TIZEN_MOBILE)
  // Assumes portrait display; shows overlay indicator in landscape only.
  bool useOverlay = display.rotation() == gfx::Display::ROTATE_90 ||
      display.rotation() == gfx::Display::ROTATE_180;
  top_view_layout()->SetUseOverlay(enableOverlay);
  indicator_widget_->SetDisplay(display);
#endif

  // As everything is calculated from the fixed position we do
  // not update the display bounds after rotation change.
  gfx::Transform rotate;
  float one_pixel = 1.0f / display.device_scale_factor();
  switch (display.rotation()) {
    case gfx::Display::ROTATE_0:
      break;
    case gfx::Display::ROTATE_90:
      rotate.Translate(display.bounds().width() - one_pixel, 0);
      rotate.Rotate(90);
      break;
    case gfx::Display::ROTATE_270:
      rotate.Translate(0, display.bounds().height() - one_pixel);
      rotate.Rotate(270);
      break;
    case gfx::Display::ROTATE_180:
      rotate.Translate(display.bounds().width() - one_pixel,
                       display.bounds().height() - one_pixel);
      rotate.Rotate(180);
      break;
  }

  window->SetTransform(rotate);
}

}  // namespace.

namespace xwalk {

NativeAppWindowTizen::NativeAppWindowTizen(
    const NativeAppWindow::CreateParams& create_params)
    : NativeAppWindowViews(create_params),
#if defined(OS_TIZEN_MOBILE)
      indicator_widget_(new TizenSystemIndicatorWidget()),
      indicator_container_(new WidgetContainerView(indicator_widget_)),
#endif
      orientation_lock_(blink::WebScreenOrientationLockAny) {}

void NativeAppWindowTizen::Initialize() {
  NativeAppWindowViews::Initialize();

  const base::FilePath& splash_screen_path = create_params().splash_screen_path;
  if (!splash_screen_path.empty()) {
    splash_screen_.reset(new SplashScreenTizen(
        GetWidget(), splash_screen_path, create_params().web_contents));
    splash_screen_->Start();
  }

  // Get display info such as device_scale_factor, and current
  // rotation (orientation).
  // NOTE: This is a local copy of the info.
  display_ = gfx::Screen::GetNativeScreen()->GetPrimaryDisplay();

  aura::Window* root_window = GetNativeWindow()->GetRootWindow();
  DCHECK(root_window);
  root_window->AddObserver(this);

  SensorProvider::GetInstance()->AddObserver(this);

  if (SensorProvider::GetInstance()->connected()) {
    OnScreenOrientationChanged(
        SensorProvider::GetInstance()->GetScreenOrientation());
  }
}

NativeAppWindowTizen::~NativeAppWindowTizen() {
  if (SensorProvider::GetInstance()->connected())
    SensorProvider::GetInstance()->RemoveObserver(this);
}

void NativeAppWindowTizen::LockOrientation(
      blink::WebScreenOrientationLockType lock) {
  orientation_lock_ = lock;
  if (SensorProvider::GetInstance()->connected())
    OnScreenOrientationChanged(
        SensorProvider::GetInstance()->GetScreenOrientation());
}

void NativeAppWindowTizen::ViewHierarchyChanged(
    const ViewHierarchyChangedDetails& details) {
  if (details.is_add && details.child == this) {
    NativeAppWindowViews::ViewHierarchyChanged(details);

#if defined(OS_TIZEN_MOBILE)
    indicator_widget_->Initialize(GetNativeWindow());
    top_view_layout()->set_top_view(indicator_container_.get());
    AddChildView(indicator_container_.get());
#endif
  }
}

void NativeAppWindowTizen::OnWindowBoundsChanged(
    aura::Window* window,
    const gfx::Rect& old_bounds,
    const gfx::Rect& new_bounds) {
  aura::Window* root_window = GetNativeWindow()->GetRootWindow();
  DCHECK_EQ(root_window, window);

  // Change the bounds of child windows to make touch work correctly.
  GetNativeWindow()->parent()->SetBounds(new_bounds);
  GetNativeWindow()->SetBounds(new_bounds);

  GetWidget()->GetRootView()->SetSize(new_bounds.size());
}

void NativeAppWindowTizen::OnWindowDestroying(aura::Window* window) {
  // Must be removed here and not in the destructor, as the aura::Window is
  // already destroyed when our destructor runs.
  window->RemoveObserver(this);
}

void NativeAppWindowTizen::OnWindowVisibilityChanging(
    aura::Window* window, bool visible) {
  if (!visible)
    return;
  SetDisplayRotation(display_);
}

blink::WebScreenOrientationType
    NativeAppWindowTizen::FindNearestAllowedOrientation(
        blink::WebScreenOrientationType orientation) const {
  switch (orientation_lock_) {
    case blink::WebScreenOrientationLockDefault:
    case blink::WebScreenOrientationLockAny:
      return orientation;
    case blink::WebScreenOrientationLockLandscape: {
      switch (orientation) {
        case blink::WebScreenOrientationLandscapePrimary:
        case blink::WebScreenOrientationLandscapeSecondary:
          return orientation;
        default:
          return blink::WebScreenOrientationLandscapePrimary;
      }
      break;
    }
    case blink::WebScreenOrientationLockPortrait: {
      switch (orientation) {
        case blink::WebScreenOrientationPortraitPrimary:
        case blink::WebScreenOrientationPortraitSecondary:
          return orientation;
        default:
          return blink::WebScreenOrientationPortraitPrimary;
      }
      break;
    }
    case blink::WebScreenOrientationLockPortraitPrimary:
      return blink::WebScreenOrientationPortraitPrimary;
    case blink::WebScreenOrientationLockPortraitSecondary:
      return blink::WebScreenOrientationPortraitSecondary;
    case blink::WebScreenOrientationLockLandscapePrimary:
      return blink::WebScreenOrientationLandscapePrimary;
    case blink::WebScreenOrientationLockLandscapeSecondary:
      return blink::WebScreenOrientationLandscapeSecondary;
  default:
      NOTREACHED();
  }
  return orientation;
}

void NativeAppWindowTizen::OnScreenOrientationChanged(
    blink::WebScreenOrientationType orientation) {

  // We always store the current sensor position, even if we do not
  // apply it in case the window is invisible.
  gfx::Display::Rotation rot = ToDisplayRotation(display_,
      FindNearestAllowedOrientation(orientation));
  if (display_.rotation() == rot)
    return;

  display_.set_rotation(rot);
  SetDisplayRotation(display_);
}

void NativeAppWindowTizen::OnSensorConnected() {
  OnScreenOrientationChanged(
      SensorProvider::GetInstance()->GetScreenOrientation());
}

void NativeAppWindowTizen::SetDisplayRotation(gfx::Display display) {
  aura::Window* window = GetNativeWindow()->GetRootWindow();
  if (!window->IsVisible())
    return;

  SetWindowRotation(window, display);
}

}  // namespace xwalk
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "Player.h"
#include "StaticMesh.h"
#include "Texture.h"
#include "Info.h"
#include "VIBuffer.h"
#include "RcTex.h"
#include "ShaderMgr.h"
#include "Camera.h"
#include "ObjMgr.h"
#include "Shader.h"
#include "Terrain.h"
#include "TerrainCol.h"
#include "Device.h"
#include "Camera.h"

#pragma pack(push,1)
struct CB_VS_PER_OBJECT
{
	D3DXMATRIX m_mWorldViewProjection;
	D3DXMATRIX m_mWorld;
};

struct CB_PS_PER_OBJECT
{
	float m_fSpecExp;
	float m_fSpecIntensity;
	D3DXVECTOR3 m_vEyePosition;
	float pad[3];
};
#pragma pack(pop)

CPlayer::CPlayer()
{
	m_pBuffer = NULL;
	m_pVertexShader = NULL;
	m_pPixelShader = NULL;
	m_pTexture = NULL;
	m_pVerTex = NULL;
	m_pTerrainCol = NULL;
	m_pSceneVertexShaderCB = NULL;
	m_pScenePixelShaderCB = NULL;
}

CPlayer::~CPlayer()
{
	Release();
}

HRESULT CPlayer::Initialize(void)
{
	if (FAILED(AddComponent()))
		return E_FAIL;

	D3D11_BUFFER_DESC cbDesc;
	ZeroMemory(&cbDesc, sizeof(cbDesc));
	cbDesc.Usage = D3D11_USAGE_DYNAMIC;
	cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	cbDesc.ByteWidth = sizeof(CB_VS_PER_OBJECT);
	FAILED_CHECK(m_pGrapicDevice->m_pDevice->CreateBuffer(&cbDesc, NULL, &m_pSceneVertexShaderCB));

	cbDesc.ByteWidth = sizeof(CB_PS_PER_OBJECT);
	FAILED_CHECK(m_pGrapicDevice->m_pDevice->CreateBuffer(&cbDesc, NULL, &m_pScenePixelShaderCB));

	return S_OK;
}

int CPlayer::Update(void)
{
	m_pInfo->m_fAngle[ANGLE_X] = D3DX_PI / 2 * -1.f;//;D3DXToRadian(-90);
	m_pInfo->m_vScale = D3DXVECTOR3(0.1f, 0.1f, 0.1f);

	CObj::Update();

	return 0;
}

void CPlayer::Render(void)
{
	/*
	ConstantBuffer cb;
	D3DXMatrixTranspose(&cb.matWorld, &m_pInfo->m_matWorld);
	D3DXMatrixTranspose(&cb.matView, &CCamera::GetInstance()->m_matView);
	D3DXMatrixTranspose(&cb.matProjection, &CCamera::GetInstance()->m_matProj);
	m_pGrapicDevice->m_pDeviceContext->UpdateSubresource(m_pBuffer->m_ConstantBuffer, 0, NULL, &cb, 0, 0);

	m_pGrapicDevice->m_pDeviceContext->VSSetShader(m_pVertexShader->m_pVertexShader, NULL, 0);
	m_pGrapicDevice->m_pDeviceContext->VSSetConstantBuffers(0, 1, &m_pBuffer->m_ConstantBuffer);

	m_pGrapicDevice->m_pDeviceContext->PSSetShader(m_pPixelShader->m_pPixelShader, NULL, 0);
	m_pGrapicDevice->m_pDeviceContext->PSSetShaderResources(0, 1, &m_pTexture->m_pTextureRV);
	m_pGrapicDevice->m_pDeviceContext->PSSetSamplers(0, 1, &m_pTexture->m_pSamplerLinear);
	*/

	// Get the projection & view matrix from the camera class
	D3DXMATRIX mWorld; // No need for a real world matrix
	D3DXMatrixIdentity(&mWorld);
	D3DXMatrixTranspose(&mWorld, &m_pInfo->m_matWorld);
	D3DXMATRIX mView = *(CCamera::GetInstance()->GetViewMatrix());
	D3DXMATRIX mProj = *(CCamera::GetInstance()->GetProjMatrix());
	D3DXMATRIX mWorldViewProjection = mView * mProj;

	// Set the constant buffers
	D3D11_MAPPED_SUBRESOURCE MappedResource;
	FAILED_CHECK_RETURN(m_pGrapicDevice->m_pDeviceContext->Map(m_pSceneVertexShaderCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource),);
	CB_VS_PER_OBJECT* pVSPerObject = (CB_VS_PER_OBJECT*)MappedResource.pData;
	D3DXMatrixTranspose(&pVSPerObject->m_mWorldViewProjection, &mWorldViewProjection);
	D3DXMatrixTranspose(&pVSPerObject->m_mWorld, &mWorld);
	m_pGrapicDevice->m_pDeviceContext->Unmap(m_pSceneVertexShaderCB, 0);
	m_pGrapicDevice->m_pDeviceContext->VSSetConstantBuffers(0, 1, &m_pSceneVertexShaderCB);

	FAILED_CHECK_RETURN(m_pGrapicDevice->m_pDeviceContext->Map(m_pScenePixelShaderCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource),);
	CB_PS_PER_OBJECT* pPSPerObject = (CB_PS_PER_OBJECT*)MappedResource.pData;
	pPSPerObject->m_vEyePosition = CCamera::GetInstance()->m_vEye;
	pPSPerObject->m_fSpecExp = 250.0f;
	pPSPerObject->m_fSpecIntensity = 0.25f;
	m_pGrapicDevice->m_pDeviceContext->Unmap(m_pScenePixelShaderCB, 0);
	m_pGrapicDevice->m_pDeviceContext->PSSetConstantBuffers(0, 1, &m_pScenePixelShaderCB);

	// Set the vertex layout
	m_pGrapicDevice->m_pDeviceContext->IASetInputLayout(m_pVertexShader->m_pVertexLayout);

	// Set the shaders
	m_pGrapicDevice->m_pDeviceContext->VSSetShader(m_pVertexShader->m_pVertexShader, NULL, 0);
	m_pGrapicDevice->m_pDeviceContext->PSSetShader(m_pPixelShader->m_pPixelShader, NULL, 0);

	m_pGrapicDevice->m_pDeviceContext->PSSetShaderResources(0, 1, &m_pTexture->m_pTextureRV);
	m_pGrapicDevice->m_pDeviceContext->PSSetSamplers(0, 1, &m_pTexture->m_pSamplerLinear);

	m_pBuffer->Render();
}

CPlayer * CPlayer::Create(void)
{
	CPlayer* pObj = new CPlayer;
	if (FAILED(pObj->Initialize()))
		::Safe_Delete(pObj);

	return pObj;
}

void CPlayer::Release(void)
{
	Safe_Release(m_pSceneVertexShaderCB);
	Safe_Release(m_pScenePixelShaderCB);
}

HRESULT CPlayer::AddComponent(void)
{
	CComponent* pComponent = NULL;
	char cModelPath[MAX_PATH] = "../Resource/Mesh/samplehumanani.FBX";
	m_pBuffer = CStaticMesh::Create(cModelPath);
	pComponent = m_pBuffer;
	m_mapComponent.insert(map<wstring, CComponent*>::value_type(L"Buffer", pComponent));

	m_pInfo = CInfo::Create(g_vLook);
	pComponent = m_pInfo;
	if (pComponent == NULL)
		return E_FAIL;
	m_mapComponent.insert(map<wstring, CComponent*>::value_type(L"Info", pComponent));

	m_pTexture = CTexture::Create(L"../Resource/MeshImage/samplehumanani.PNG");
	pComponent = m_pTexture;
	if (pComponent == NULL)
		return E_FAIL;
	m_mapComponent.insert(map<wstring, CComponent*>::value_type(L"Texture", pComponent));

	m_pVertexShader = CShaderMgr::GetInstance()->Clone_Shader(L"RenderSceneVS");
	m_pPixelShader = CShaderMgr::GetInstance()->Clone_Shader(L"RenderScenePS");;

	return S_OK;
}
<commit_msg>[허지훈]Shader<commit_after>#include "stdafx.h"
#include "Player.h"
#include "StaticMesh.h"
#include "Texture.h"
#include "Info.h"
#include "VIBuffer.h"
#include "RcTex.h"
#include "ShaderMgr.h"
#include "Camera.h"
#include "ObjMgr.h"
#include "Shader.h"
#include "Terrain.h"
#include "TerrainCol.h"
#include "Device.h"
#include "Camera.h"

#pragma pack(push,1)
struct CB_VS_PER_OBJECT
{
	D3DXMATRIX m_mWorldViewProjection;
	D3DXMATRIX m_mWorld;
};

struct CB_PS_PER_OBJECT
{
	float m_fSpecExp;
	float m_fSpecIntensity;
	D3DXVECTOR3 m_vEyePosition;
	float pad[3];
};
#pragma pack(pop)

CPlayer::CPlayer()
{
	m_pBuffer = NULL;
	m_pVertexShader = NULL;
	m_pPixelShader = NULL;
	m_pTexture = NULL;
	m_pVerTex = NULL;
	m_pTerrainCol = NULL;
	m_pSceneVertexShaderCB = NULL;
	m_pScenePixelShaderCB = NULL;
}

CPlayer::~CPlayer()
{
	Release();
}

HRESULT CPlayer::Initialize(void)
{
	if (FAILED(AddComponent()))
		return E_FAIL;

	D3D11_BUFFER_DESC cbDesc;
	ZeroMemory(&cbDesc, sizeof(cbDesc));
	cbDesc.Usage = D3D11_USAGE_DYNAMIC;
	cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	cbDesc.ByteWidth = sizeof(CB_VS_PER_OBJECT);
	FAILED_CHECK(m_pGrapicDevice->m_pDevice->CreateBuffer(&cbDesc, NULL, &m_pSceneVertexShaderCB));

	cbDesc.ByteWidth = sizeof(CB_PS_PER_OBJECT);
	FAILED_CHECK(m_pGrapicDevice->m_pDevice->CreateBuffer(&cbDesc, NULL, &m_pScenePixelShaderCB));

	return S_OK;
}

int CPlayer::Update(void)
{
	m_pInfo->m_fAngle[ANGLE_X] = D3DX_PI / 2 * -1.f;//;D3DXToRadian(-90);
	m_pInfo->m_vScale = D3DXVECTOR3(0.1f, 0.1f, 0.1f);

	CObj::Update();

	return 0;
}

void CPlayer::Render(void)
{
	/*
	ConstantBuffer cb;
	D3DXMatrixTranspose(&cb.matWorld, &m_pInfo->m_matWorld);
	D3DXMatrixTranspose(&cb.matView, &CCamera::GetInstance()->m_matView);
	D3DXMatrixTranspose(&cb.matProjection, &CCamera::GetInstance()->m_matProj);
	m_pGrapicDevice->m_pDeviceContext->UpdateSubresource(m_pBuffer->m_ConstantBuffer, 0, NULL, &cb, 0, 0);

	m_pGrapicDevice->m_pDeviceContext->VSSetShader(m_pVertexShader->m_pVertexShader, NULL, 0);
	m_pGrapicDevice->m_pDeviceContext->VSSetConstantBuffers(0, 1, &m_pBuffer->m_ConstantBuffer);

	m_pGrapicDevice->m_pDeviceContext->PSSetShader(m_pPixelShader->m_pPixelShader, NULL, 0);
	m_pGrapicDevice->m_pDeviceContext->PSSetShaderResources(0, 1, &m_pTexture->m_pTextureRV);
	m_pGrapicDevice->m_pDeviceContext->PSSetSamplers(0, 1, &m_pTexture->m_pSamplerLinear);
	*/

	// Get the projection & view matrix from the camera class
	D3DXMATRIX mWorld; // No need for a real world matrix
	D3DXMatrixIdentity(&mWorld);
	D3DXMatrixTranspose(&mWorld, &m_pInfo->m_matWorld);
	D3DXMATRIX mView = *(CCamera::GetInstance()->GetViewMatrix());
	D3DXMATRIX mProj = *(CCamera::GetInstance()->GetProjMatrix());
	D3DXMATRIX mWorldViewProjection = mView * mProj;

	// Set the constant buffers
	D3D11_MAPPED_SUBRESOURCE MappedResource;
	FAILED_CHECK_RETURN(m_pGrapicDevice->m_pDeviceContext->Map(m_pSceneVertexShaderCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource),);
	CB_VS_PER_OBJECT* pVSPerObject = (CB_VS_PER_OBJECT*)MappedResource.pData;
	D3DXMatrixTranspose(&pVSPerObject->m_mWorldViewProjection, &mWorldViewProjection);
	D3DXMatrixTranspose(&pVSPerObject->m_mWorld, &mWorld);
	m_pGrapicDevice->m_pDeviceContext->Unmap(m_pSceneVertexShaderCB, 0);
	m_pGrapicDevice->m_pDeviceContext->VSSetConstantBuffers(0, 1, &m_pSceneVertexShaderCB);

	FAILED_CHECK_RETURN(m_pGrapicDevice->m_pDeviceContext->Map(m_pScenePixelShaderCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource),);
	CB_PS_PER_OBJECT* pPSPerObject = (CB_PS_PER_OBJECT*)MappedResource.pData;
	pPSPerObject->m_vEyePosition = CCamera::GetInstance()->m_vEye;
	pPSPerObject->m_fSpecExp = 250.0f;
	pPSPerObject->m_fSpecIntensity = 0.25f;
	m_pGrapicDevice->m_pDeviceContext->Unmap(m_pScenePixelShaderCB, 0);
	m_pGrapicDevice->m_pDeviceContext->PSSetConstantBuffers(0, 1, &m_pScenePixelShaderCB);

	// Set the vertex layout
	m_pGrapicDevice->m_pDeviceContext->IASetInputLayout(m_pVertexShader->m_pVertexLayout);

	// Set the shaders
	m_pGrapicDevice->m_pDeviceContext->VSSetShader(m_pVertexShader->m_pVertexShader, NULL, 0);
	m_pGrapicDevice->m_pDeviceContext->PSSetShader(m_pPixelShader->m_pPixelShader, NULL, 0);

	m_pGrapicDevice->m_pDeviceContext->PSSetShaderResources(0, 1, &m_pTexture->m_pTextureRV);
	m_pGrapicDevice->m_pDeviceContext->PSSetSamplers(0, 1, &m_pTexture->m_pSamplerLinear);

	m_pBuffer->Render();
}

CPlayer * CPlayer::Create(void)
{
	CPlayer* pObj = new CPlayer;
	if (FAILED(pObj->Initialize()))
		::Safe_Delete(pObj);

	return pObj;
}

void CPlayer::Release(void)
{
	Safe_Release(m_pSceneVertexShaderCB);
	Safe_Release(m_pScenePixelShaderCB);
}

HRESULT CPlayer::AddComponent(void)
{
	CComponent* pComponent = NULL;
	char cModelPath[MAX_PATH] = "../Resource/Mesh/samplehumanani.FBX";
	m_pBuffer = CStaticMesh::Create(cModelPath);
	pComponent = m_pBuffer;
	m_mapComponent.insert(map<wstring, CComponent*>::value_type(L"Buffer", pComponent));

	m_pInfo = CInfo::Create(g_vLook);
	pComponent = m_pInfo;
	if (pComponent == NULL)
		return E_FAIL;
	m_mapComponent.insert(map<wstring, CComponent*>::value_type(L"Info", pComponent));

	m_pTexture = CTexture::Create(L"../Resource/MeshImage/samplehumanani.PNG");
	pComponent = m_pTexture;
	if (pComponent == NULL)
		return E_FAIL;
	m_mapComponent.insert(map<wstring, CComponent*>::value_type(L"Texture", pComponent));

	m_pVertexShader = CShaderMgr::GetInstance()->Clone_Shader(L"RenderSceneVS");
	m_pPixelShader = CShaderMgr::GetInstance()->Clone_Shader(L"RenderScenePS");

	return S_OK;
}
<|endoftext|>


<commit_before>#ifndef ALEPH_UTILITIES_FILESYSTEM_HH__
#define ALEPH_UTILITIES_FILESYSTEM_HH__

// If either one of these is defined, there is a good chance that POSIX
// concepts are available under the current architecture.
#if defined(__unix__) || defined(__unix) || ( defined(__APPLE__) && defined(__MACH__) )
  #define POSIX_SOURCES_AVAILABLE
#endif

#ifdef POSIX_SOURCES_AVAILABLE
  #include <libgen.h>
  #include <paths.h>
  #include <stdlib.h>
  #include <unistd.h>

  #include <sys/stat.h>
#endif

// In the best case, the `_POSIX_VERSION` variable is set on the system,
// but more exotic configurations may not have this. The essence of this
// check is to ensure that common features of `lstat()` are available.
#if ( defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L ) || ( defined(POSIX_SOURCES_AVAILABLE) && ( ( defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L ) || defined(_DEFAULT_SOURCE) ) )
  #define POSIX_VERSION_COMPATIBLE
#endif

#if defined(_BSD_SOURCE) || defined(_SVID_SOURCE) || defined(_DEFAULT_SOURCE)
  #define ALL_FILE_TYPE_QUERIES_AVAILABLE
#endif

// Brute-force check for the availability of some macros for `lstat()`,
// in case the check from above fails.
#if defined(S_ISBLK) && defined(S_ISCHR) && defined(S_ISDIR) && defined(S_ISFIFO) && defined(S_ISREG) && defined(S_ISLNK) && defined(S_ISSOCK)
  #define ALL_FILE_TYPE_QUERIES_AVAILABLE
#endif

#if defined(ALL_FILE_TYPE_QUERIES_AVAILABLE) || defined(_BSD_SOURCE) || defined(_DEFAULT_SOURCE) || ( defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 500 )
  #define SOCKET_FILE_TYPE_QUERY_AVAILABLE
#endif

#include <fstream>

namespace aleph
{

namespace utilities
{

/**
  Describes potential file types. This is used *internally* but also by
  methods such as the `fileType()` function.
*/

enum class FileType
{
  BlockDevice,
  CharacterDevice,
  Directory,
  NamedPipe,
  RegularFile,
  Socket,
  SymbolicLink,
  Undefined
};

/** Returns the file type of a path */
FileType fileType( const std::string& path )
{
  FileType t = FileType::Undefined;

#ifdef POSIX_VERSION_COMPATIBLE
  struct stat info;
  int error = lstat( path.c_str(), &info );

  if( error == 0 )
  {
  #if defined(ALL_FILE_TYPE_QUERIES_AVAILABLE) || defined(_XOPEN_SOURCE)
    if( S_ISBLK( info.st_mode ) )
      t = FileType::BlockDevice;
    else if( S_ISCHR( info.st_mode ) )
      t = FileType::CharacterDevice;
    else if( S_ISDIR( info.st_mode ) )
      t = FileType::Directory;
    else if( S_ISFIFO( info.st_mode ) )
      t = FileType::NamedPipe;
    else if( S_ISREG( info.st_mode ) )
      t = FileType::RegularFile;
    else if( S_ISLNK( info.st_mode ) )
      t = FileType::SymbolicLink;
    #ifdef SOCKET_FILE_TYPE_QUERY_AVAILABLE
    else if( S_ISSOCK( info.st_mode ) )
      t = FileType::Socket;
    #endif
  #endif
  }
#endif

  return t;
}

/** Checks whether a given path is a directory */
bool isDirectory( const std::string& path )
{
  return fileType( path ) == FileType::Directory;
}

/** Checks whether a given path is a regular file */
bool isRegularFile( const std::string& path )
{
  return fileType( path ) == FileType::RegularFile;
}

/** Checks whether a given path is a socket */
bool isSocket( const std::string& path )
{
  return fileType( path ) == FileType::Socket;
}

/** Checks whether a path or a file exists */
bool exists( const std::string& path )
{
  return    isDirectory( path )
         || isRegularFile( path )
         || isSocket( path )
         || ( std::ifstream( path ) ); // fall-back in case no other queries are available;
                                       // we just try to open the file instead
}

/** Returns the basename, i.e the filename portion, of a path */
std::string basename( const std::string& path )
{
  if( path.empty() )
    return {};

  std::string result;

#if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L

  char* buffer = new char[ path.size() + 1 ];
  std::copy( path.begin(), path.end(), buffer );

  buffer[ path.size() ] = '\0'; // `basename()` expects the string to be
                                // null-terminated

  char* name = ::basename( buffer );
  if( name )
    result = name;

  // `basename()` is guaranteed not to allocate _more_ memory. It might possibly
  // return a pointer to statically allocated memory (which we must not free) or
  // to parts of the input `path` pointer.
  //
  // Freeing said pointer is thus sufficient.
  delete[] buffer;

#else
  #error "No compatible implementation of 'basename' available"
#endif

  return result;
}

/**
  @returns Stem of the path. The stem is \i either the complete filename in
  case the path does not contain a dot \i or that part of the filename that
  precedes it. Hence, \c /foo/bar.txt will have a stem of \c bar.

  By definition, the special directories \c . and \c .. will remain their
  own stems. Normally, the stem will not contain a dot, though.
*/

std::string stem( const std::string& path )
{
  auto&& filename = basename( path );

  if( filename.find( '.' ) == std::string::npos || filename == "." || filename == ".." )
    return filename;

  auto pos = filename.find_last_of( '.' );
  return filename.substr( 0, pos );
}

/**
  @returns File extension of a path. This only works if the filename portion
  of the path contains a dot but is neither \c . nor \c .., i.e. the current
  directory or the parent directory. Note that the returned value will start
  with a dot in order to permit differentiating between filenames without an
  extension and filenames with an empty extension, i.e. a single dot. Though
  this behaviour may seem strange, it is compliant with \c Boost.Filesystem,
  for example.

  @see http://permalink.gmane.org/gmane.comp.lib.boost.devel/199744
*/

std::string extension( const std::string& path )
{
  auto&& filename = basename( path );

  if( filename.find( '.' ) == std::string::npos || filename == "." || filename == ".." )
    return {};

  auto pos = filename.find_last_of( '.' );
  return filename.substr( pos );
}

/**
  @returns The temporary directory of the given system. This function
  attempts to solve this in a platform-independent manner. It is very
  likely though that this only works for POSIX-based systems.
*/

std::string tempDirectory()
{
#ifdef POSIX_SOURCES_AVAILABLE
  auto tmpdir  = getenv("TMPDIR");
  auto tmp     = getenv("TMP");
  auto temp    = getenv("TEMP");
  auto tempdir = getenv("TEMPDIR");

  // These may not always be available, so we have to perform an
  // additional check below.
  const char* ptmpdir = nullptr;
  const char* pathtmp = nullptr;

  #ifdef P_tmpdir
    ptmpdir = P_tmpdir;
  #endif

  #ifdef _PATH_TMP
    pathtmp = _PATH_TMP;
  #endif

  // This does not check to what extent the information present in two
  // of these variables is consistent with the rest. The order is more
  // or less random here; I was unable to find an authoritative guide.

  return tmpdir ? tmpdir
                : tmp ? tmp
                      : temp ? temp
                             : tempdir ? tempdir
                                       : ptmpdir ? ptmpdir
                                                 : pathtmp ? pathtmp
                                                           : ""; // Return an empty directory rather
                                                                 // than an incorrect one
#endif

  // Return an empty directory rather than guessing an incorrect one;
  // we *could* potentially default to '/tmp' here, but I do not like
  // this idea of an untested fallback.
  return {};
}

} // namespace utilities

} // namespace aleph

#endif
<commit_msg>Fixed warning concerning moveable variable<commit_after>#ifndef ALEPH_UTILITIES_FILESYSTEM_HH__
#define ALEPH_UTILITIES_FILESYSTEM_HH__

// If either one of these is defined, there is a good chance that POSIX
// concepts are available under the current architecture.
#if defined(__unix__) || defined(__unix) || ( defined(__APPLE__) && defined(__MACH__) )
  #define POSIX_SOURCES_AVAILABLE
#endif

#ifdef POSIX_SOURCES_AVAILABLE
  #include <libgen.h>
  #include <paths.h>
  #include <stdlib.h>
  #include <unistd.h>

  #include <sys/stat.h>
#endif

// In the best case, the `_POSIX_VERSION` variable is set on the system,
// but more exotic configurations may not have this. The essence of this
// check is to ensure that common features of `lstat()` are available.
#if ( defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L ) || ( defined(POSIX_SOURCES_AVAILABLE) && ( ( defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L ) || defined(_DEFAULT_SOURCE) ) )
  #define POSIX_VERSION_COMPATIBLE
#endif

#if defined(_BSD_SOURCE) || defined(_SVID_SOURCE) || defined(_DEFAULT_SOURCE)
  #define ALL_FILE_TYPE_QUERIES_AVAILABLE
#endif

// Brute-force check for the availability of some macros for `lstat()`,
// in case the check from above fails.
#if defined(S_ISBLK) && defined(S_ISCHR) && defined(S_ISDIR) && defined(S_ISFIFO) && defined(S_ISREG) && defined(S_ISLNK) && defined(S_ISSOCK)
  #define ALL_FILE_TYPE_QUERIES_AVAILABLE
#endif

#if defined(ALL_FILE_TYPE_QUERIES_AVAILABLE) || defined(_BSD_SOURCE) || defined(_DEFAULT_SOURCE) || ( defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 500 )
  #define SOCKET_FILE_TYPE_QUERY_AVAILABLE
#endif

#include <fstream>
#include <utility>

namespace aleph
{

namespace utilities
{

/**
  Describes potential file types. This is used *internally* but also by
  methods such as the `fileType()` function.
*/

enum class FileType
{
  BlockDevice,
  CharacterDevice,
  Directory,
  NamedPipe,
  RegularFile,
  Socket,
  SymbolicLink,
  Undefined
};

/** Returns the file type of a path */
FileType fileType( const std::string& path )
{
  FileType t = FileType::Undefined;

#ifdef POSIX_VERSION_COMPATIBLE
  struct stat info;
  int error = lstat( path.c_str(), &info );

  if( error == 0 )
  {
  #if defined(ALL_FILE_TYPE_QUERIES_AVAILABLE) || defined(_XOPEN_SOURCE)
    if( S_ISBLK( info.st_mode ) )
      t = FileType::BlockDevice;
    else if( S_ISCHR( info.st_mode ) )
      t = FileType::CharacterDevice;
    else if( S_ISDIR( info.st_mode ) )
      t = FileType::Directory;
    else if( S_ISFIFO( info.st_mode ) )
      t = FileType::NamedPipe;
    else if( S_ISREG( info.st_mode ) )
      t = FileType::RegularFile;
    else if( S_ISLNK( info.st_mode ) )
      t = FileType::SymbolicLink;
    #ifdef SOCKET_FILE_TYPE_QUERY_AVAILABLE
    else if( S_ISSOCK( info.st_mode ) )
      t = FileType::Socket;
    #endif
  #endif
  }
#endif

  return t;
}

/** Checks whether a given path is a directory */
bool isDirectory( const std::string& path )
{
  return fileType( path ) == FileType::Directory;
}

/** Checks whether a given path is a regular file */
bool isRegularFile( const std::string& path )
{
  return fileType( path ) == FileType::RegularFile;
}

/** Checks whether a given path is a socket */
bool isSocket( const std::string& path )
{
  return fileType( path ) == FileType::Socket;
}

/** Checks whether a path or a file exists */
bool exists( const std::string& path )
{
  return    isDirectory( path )
         || isRegularFile( path )
         || isSocket( path )
         || ( std::ifstream( path ) ); // fall-back in case no other queries are available;
                                       // we just try to open the file instead
}

/** Returns the basename, i.e the filename portion, of a path */
std::string basename( const std::string& path )
{
  if( path.empty() )
    return {};

  std::string result;

#if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L

  char* buffer = new char[ path.size() + 1 ];
  std::copy( path.begin(), path.end(), buffer );

  buffer[ path.size() ] = '\0'; // `basename()` expects the string to be
                                // null-terminated

  char* name = ::basename( buffer );
  if( name )
    result = name;

  // `basename()` is guaranteed not to allocate _more_ memory. It might possibly
  // return a pointer to statically allocated memory (which we must not free) or
  // to parts of the input `path` pointer.
  //
  // Freeing said pointer is thus sufficient.
  delete[] buffer;

#else
  #error "No compatible implementation of 'basename' available"
#endif

  return result;
}

/**
  @returns Stem of the path. The stem is \i either the complete filename in
  case the path does not contain a dot \i or that part of the filename that
  precedes it. Hence, \c /foo/bar.txt will have a stem of \c bar.

  By definition, the special directories \c . and \c .. will remain their
  own stems. Normally, the stem will not contain a dot, though.
*/

std::string stem( const std::string& path )
{
  auto&& filename = basename( path );

  if( filename.find( '.' ) == std::string::npos || filename == "." || filename == ".." )
    return std::move( filename );

  auto pos = filename.find_last_of( '.' );
  return filename.substr( 0, pos );
}

/**
  @returns File extension of a path. This only works if the filename portion
  of the path contains a dot but is neither \c . nor \c .., i.e. the current
  directory or the parent directory. Note that the returned value will start
  with a dot in order to permit differentiating between filenames without an
  extension and filenames with an empty extension, i.e. a single dot. Though
  this behaviour may seem strange, it is compliant with \c Boost.Filesystem,
  for example.

  @see http://permalink.gmane.org/gmane.comp.lib.boost.devel/199744
*/

std::string extension( const std::string& path )
{
  auto&& filename = basename( path );

  if( filename.find( '.' ) == std::string::npos || filename == "." || filename == ".." )
    return {};

  auto pos = filename.find_last_of( '.' );
  return filename.substr( pos );
}

/**
  @returns The temporary directory of the given system. This function
  attempts to solve this in a platform-independent manner. It is very
  likely though that this only works for POSIX-based systems.
*/

std::string tempDirectory()
{
#ifdef POSIX_SOURCES_AVAILABLE
  auto tmpdir  = getenv("TMPDIR");
  auto tmp     = getenv("TMP");
  auto temp    = getenv("TEMP");
  auto tempdir = getenv("TEMPDIR");

  // These may not always be available, so we have to perform an
  // additional check below.
  const char* ptmpdir = nullptr;
  const char* pathtmp = nullptr;

  #ifdef P_tmpdir
    ptmpdir = P_tmpdir;
  #endif

  #ifdef _PATH_TMP
    pathtmp = _PATH_TMP;
  #endif

  // This does not check to what extent the information present in two
  // of these variables is consistent with the rest. The order is more
  // or less random here; I was unable to find an authoritative guide.

  return tmpdir ? tmpdir
                : tmp ? tmp
                      : temp ? temp
                             : tempdir ? tempdir
                                       : ptmpdir ? ptmpdir
                                                 : pathtmp ? pathtmp
                                                           : ""; // Return an empty directory rather
                                                                 // than an incorrect one
#endif

  // Return an empty directory rather than guessing an incorrect one;
  // we *could* potentially default to '/tmp' here, but I do not like
  // this idea of an untested fallback.
  return {};
}

} // namespace utilities

} // namespace aleph

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");

// Client version number
#ifdef NEBLIO_REST
#define CLIENT_VERSION_SUFFIX   "-REST-Enabled"
#else
#define CLIENT_VERSION_SUFFIX   ""
#endif

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 0
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID ""
#    define GIT_COMMIT_DATE "$Format:%cD"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Update version.cpp<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");

// Client version number
#ifdef NEBLIO_REST
#define CLIENT_VERSION_SUFFIX   "-REST-Enabled"
#else
#define CLIENT_VERSION_SUFFIX   "-BETA"
#endif

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 0
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID ""
#    define GIT_COMMIT_DATE "$Format:%cD"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>/*
 * RoseFunction Unit for TTBlue
 * Originally written for the Jamoma TrajectoryLib
 * Copyright © 2010 by Nils Peters
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "Rose2D.h"

#define thisTTClass			Rose2D
#define thisTTClassName		"rose.2D"
#define thisTTClassTags		"audio, trajectory"

TT_AUDIO_CONSTRUCTOR
{   addAttribute(A,				kTypeFloat64);

	setAttributeValue(TT("a"),	0.0);

	setProcessMethod(processAudio);
//	setCalculateMethod(calculateValue);
}

Rose2D::~Rose2D()
{
	;
}

//TTErr Rose2D::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
//{
//	y = x;
//	return kTTErrNone;
//}

TTErr Rose2D::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TTAudioSignal&		out = outputs->getSignal(0);
	TTUInt16			numOutputChannels = out.getNumChannelsAsInt();

	if (numOutputChannels != 2) {
		TTValue v = 2;
		out.setMaxNumChannels(v);
		out.setNumChannels(v);
	}

	TTAudioSignal&		in0 = inputs->getSignal(0);
	//TTAudioSignal&		in1 = inputs->getSignal(1);
	TTUInt16			 vs = in0.getVectorSizeAsInt();

	TTSampleValuePtr	inSampleX			= in0.mSampleVectors[0];
	//TTSampleValuePtr	inSampleY			= in1.mSampleVectors[0];
	TTSampleValuePtr	outSampleX    		= out.mSampleVectors[0];
	TTSampleValuePtr	outSampleY			= out.mSampleVectors[1];
    TTFloat64 phi, r;

	for (int i=0; i<vs; i++) {

		// r = cos(mA * phi)
		// x = sin(phi) * r
		// y = cos(phi) * r

		phi = inSampleX[i] * kTTPi; // 0 .. 2Pi
		r = cos(mA * phi);

		outSampleX[i] = sin(phi) * r;
		outSampleY[i] = cos(phi) * r;

	}
return kTTErrNone;
}
<commit_msg>adding a '2D' tag<commit_after>/*
 * RoseFunction Unit for TTBlue
 * Originally written for the Jamoma TrajectoryLib
 * Copyright © 2010 by Nils Peters
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "Rose2D.h"

#define thisTTClass			Rose2D
#define thisTTClassName		"rose.2D"
#define thisTTClassTags		"audio, trajectory, 2D"

TT_AUDIO_CONSTRUCTOR
{   addAttribute(A,				kTypeFloat64);

	setAttributeValue(TT("a"),	0.0);

	setProcessMethod(processAudio);
//	setCalculateMethod(calculateValue);
}

Rose2D::~Rose2D()
{
	;
}

//TTErr Rose2D::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
//{
//	y = x;
//	return kTTErrNone;
//}

TTErr Rose2D::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TTAudioSignal&		out = outputs->getSignal(0);
	TTUInt16			numOutputChannels = out.getNumChannelsAsInt();

	if (numOutputChannels != 2) {
		TTValue v = 2;
		out.setMaxNumChannels(v);
		out.setNumChannels(v);
	}

	TTAudioSignal&		in0 = inputs->getSignal(0);
	//TTAudioSignal&		in1 = inputs->getSignal(1);
	TTUInt16			 vs = in0.getVectorSizeAsInt();

	TTSampleValuePtr	inSampleX			= in0.mSampleVectors[0];
	//TTSampleValuePtr	inSampleY			= in1.mSampleVectors[0];
	TTSampleValuePtr	outSampleX    		= out.mSampleVectors[0];
	TTSampleValuePtr	outSampleY			= out.mSampleVectors[1];
    TTFloat64 phi, r;

	for (int i=0; i<vs; i++) {

		// r = cos(mA * phi)
		// x = sin(phi) * r
		// y = cos(phi) * r

		phi = inSampleX[i] * kTTPi; // 0 .. 2Pi
		r = cos(mA * phi);

		outSampleX[i] = sin(phi) * r;
		outSampleY[i] = cos(phi) * r;

	}
return kTTErrNone;
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include "dll/base_traits.hpp"
#include "dll/neural_layer.hpp"

namespace dll {

/*!
 * \brief Standard dynamic convolutional layer of neural network.
 */
template <typename Desc>
struct dyn_conv_layer final : neural_layer<dyn_conv_layer<Desc>, Desc> {
    using desc      = Desc;                  ///< The descriptor type
    using weight    = typename desc::weight; ///< The weight type
    using this_type = dyn_conv_layer<desc>;  ///< This type
    using base_type = neural_layer<this_type, desc>;

    static constexpr auto activation_function = desc::activation_function;
    static constexpr auto w_initializer       = desc::w_initializer;
    static constexpr auto b_initializer       = desc::b_initializer;

    using input_one_t  = etl::dyn_matrix<weight, 3>; ///< The type for one input
    using output_one_t = etl::dyn_matrix<weight, 3>; ///< The type for one output
    using input_t      = std::vector<input_one_t>;   ///< The type for many input
    using output_t     = std::vector<output_one_t>;  ///< The type for many output

    using w_type = etl::dyn_matrix<weight, 4>;
    using b_type = etl::dyn_matrix<weight, 1>;

    //Weights and biases
    w_type w; //!< Weights
    b_type b; //!< Hidden biases

    //Backup weights and biases
    std::unique_ptr<w_type> bak_w; //!< Backup Weights
    std::unique_ptr<b_type> bak_b; //!< Backup Hidden biases

    size_t nv1; ///< The first visible dimension
    size_t nv2; ///< The second visible dimension
    size_t nh1; ///< The first output dimension
    size_t nh2; ///< The second output dimension
    size_t nc;  ///< The number of input channels
    size_t k;   ///< The number of filters

    size_t nw1; ///< The first dimension of the filters
    size_t nw2; ///< The second dimension of the filters

    dyn_conv_layer(): base_type() {
        // Nothing else to init
    }

    void init_layer(size_t nc, size_t nv1, size_t nv2, size_t k, size_t nw1, size_t nw2){
        this->nv1 = nv1;
        this->nv2 = nv2;
        this->nw1 = nw1;
        this->nw2 = nw2;
        this->nc = nc;
        this->k = k;

        this->nh1 = nv1 - nw1 + 1;
        this->nh2 = nv2 - nw2 + 1;

        w = etl::dyn_matrix<weight, 4>(k, nc, nw1, nw2);

        b = etl::dyn_vector<weight>(k);

        initializer_function<w_initializer>::initialize(w, input_size(), output_size());
        initializer_function<b_initializer>::initialize(b, input_size(), output_size());
    }

    std::size_t input_size() const noexcept {
        return nc * nv1 * nv2;
    }

    std::size_t output_size() const noexcept {
        return k * nh1 * nh2;
    }

    std::size_t parameters() const noexcept {
        return k * nw1 * nw2;
    }

    std::string to_short_string() const {
        char buffer[1024];
        snprintf(buffer, 1024, "Conv(dyn): %lux%lux%lu -> (%lux%lux%lu) -> %s -> %lux%lux%lu", nc, nv1, nv2, k, nw1, nw2, to_string(activation_function).c_str(), k, nh1, nh2);
        return {buffer};
    }

    template <typename H, typename V>
    void activate_hidden(H&& output, V&& v) const {
        auto b_rep = etl::force_temporary(etl::rep(b, nh1, nh2));

        etl::reshape(output, 1, k, nh1, nh2) = etl::conv_4d_valid_flipped(etl::reshape(v, 1, nc, nv1, nv2), w);

        output = f_activate<activation_function>(b_rep + output);
    }

    template <typename H1, typename V>
    void batch_activate_hidden(H1&& output, const V& v) const {
        output = etl::conv_4d_valid_flipped(v, w);

        auto b_rep = etl::force_temporary(etl::rep_l(etl::rep(b, nh1, nh2), etl::dim<0>(output)));

        output = f_activate<activation_function>(b_rep + output);
    }

    void prepare_input(input_one_t& input) const {
        input = input_one_t(nc, nv1, nv2);
    }

    template <typename Input>
    output_t prepare_output(std::size_t samples) const {
        output_t output;
        output.reserve(samples);
        for(size_t i = 0; i < samples; ++i){
            output.emplace_back(k, nh1, nh2);
        }
        return output;
    }

    template <typename Input>
    output_one_t prepare_one_output() const {
        return output_one_t(k, nh1, nh2);
    }

    template <typename DBN>
    void init_sgd_context() {
        this->sgd_context_ptr = std::make_shared<sgd_context<DBN, this_type>>(nc, nv1, nv2, k, nh1, nh2);
    }

    template<typename DRBM>
    static void dyn_init(DRBM&){
        //Nothing to change
    }

    /*!
     * \brief Adapt the errors, called before backpropagation of the errors.
     *
     * This must be used by layers that have both an activation fnction and a non-linearity.
     *
     * \param context the training context
     */
    template<typename C>
    void adapt_errors(C& context) const {
        context.errors = f_derivative<activation_function>(context.output) >> context.errors;
    }

    /*!
     * \brief Backpropagate the errors to the previous layers
     * \param output The ETL expression into which write the output
     * \param context The training context
     */
    template<typename H, typename C>
    void backward_batch(H&& output, C& context) const {
        output = etl::conv_4d_full_flipped(context.errors, w);
    }

    /*!
     * \brief Compute the gradients for this layer, if any
     * \param context The trainng context
     */
    template<typename C>
    void compute_gradients(C& context) const {
        context.w_grad = conv_4d_valid_filter_flipped(context.input, context.errors);
        context.b_grad = etl::mean_r(etl::sum_l(context.errors));
    }
};

// Declare the traits for the Layer

template<typename Desc>
struct layer_base_traits<dyn_conv_layer<Desc>> {
    static constexpr bool is_neural     = true;  ///< Indicates if the layer is a neural layer
    static constexpr bool is_dense      = false;  ///< Indicates if the layer is dense
    static constexpr bool is_conv       = true; ///< Indicates if the layer is convolutional
    static constexpr bool is_deconv     = false; ///< Indicates if the layer is deconvolutional
    static constexpr bool is_standard   = true;  ///< Indicates if the layer is standard
    static constexpr bool is_rbm        = false;  ///< Indicates if the layer is RBM
    static constexpr bool is_pooling    = false; ///< Indicates if the layer is a pooling layer
    static constexpr bool is_unpooling  = false; ///< Indicates if the layer is an unpooling laye
    static constexpr bool is_transform  = false; ///< Indicates if the layer is a transform layer
    static constexpr bool is_patches    = false; ///< Indicates if the layer is a patches layer
    static constexpr bool is_augment    = false; ///< Indicates if the layer is an augment layer
    static constexpr bool is_dynamic    = true; ///< Indicates if the layer is dynamic
    static constexpr bool pretrain_last = false; ///< Indicates if the layer is dynamic
    static constexpr bool sgd_supported = true;  ///< Indicates if the layer is supported by SGD
};

} //end of dll namespace
<commit_msg>Revert activate_hidden changes<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include "dll/base_traits.hpp"
#include "dll/neural_layer.hpp"

namespace dll {

/*!
 * \brief Standard dynamic convolutional layer of neural network.
 */
template <typename Desc>
struct dyn_conv_layer final : neural_layer<dyn_conv_layer<Desc>, Desc> {
    using desc      = Desc;                  ///< The descriptor type
    using weight    = typename desc::weight; ///< The weight type
    using this_type = dyn_conv_layer<desc>;  ///< This type
    using base_type = neural_layer<this_type, desc>;

    static constexpr auto activation_function = desc::activation_function;
    static constexpr auto w_initializer       = desc::w_initializer;
    static constexpr auto b_initializer       = desc::b_initializer;

    using input_one_t  = etl::dyn_matrix<weight, 3>; ///< The type for one input
    using output_one_t = etl::dyn_matrix<weight, 3>; ///< The type for one output
    using input_t      = std::vector<input_one_t>;   ///< The type for many input
    using output_t     = std::vector<output_one_t>;  ///< The type for many output

    using w_type = etl::dyn_matrix<weight, 4>;
    using b_type = etl::dyn_matrix<weight, 1>;

    //Weights and biases
    w_type w; //!< Weights
    b_type b; //!< Hidden biases

    //Backup weights and biases
    std::unique_ptr<w_type> bak_w; //!< Backup Weights
    std::unique_ptr<b_type> bak_b; //!< Backup Hidden biases

    size_t nv1; ///< The first visible dimension
    size_t nv2; ///< The second visible dimension
    size_t nh1; ///< The first output dimension
    size_t nh2; ///< The second output dimension
    size_t nc;  ///< The number of input channels
    size_t k;   ///< The number of filters

    size_t nw1; ///< The first dimension of the filters
    size_t nw2; ///< The second dimension of the filters

    dyn_conv_layer(): base_type() {
        // Nothing else to init
    }

    void init_layer(size_t nc, size_t nv1, size_t nv2, size_t k, size_t nw1, size_t nw2){
        this->nv1 = nv1;
        this->nv2 = nv2;
        this->nw1 = nw1;
        this->nw2 = nw2;
        this->nc = nc;
        this->k = k;

        this->nh1 = nv1 - nw1 + 1;
        this->nh2 = nv2 - nw2 + 1;

        w = etl::dyn_matrix<weight, 4>(k, nc, nw1, nw2);

        b = etl::dyn_vector<weight>(k);

        initializer_function<w_initializer>::initialize(w, input_size(), output_size());
        initializer_function<b_initializer>::initialize(b, input_size(), output_size());
    }

    std::size_t input_size() const noexcept {
        return nc * nv1 * nv2;
    }

    std::size_t output_size() const noexcept {
        return k * nh1 * nh2;
    }

    std::size_t parameters() const noexcept {
        return k * nw1 * nw2;
    }

    std::string to_short_string() const {
        char buffer[1024];
        snprintf(buffer, 1024, "Conv(dyn): %lux%lux%lu -> (%lux%lux%lu) -> %s -> %lux%lux%lu", nc, nv1, nv2, k, nw1, nw2, to_string(activation_function).c_str(), k, nh1, nh2);
        return {buffer};
    }

    void activate_hidden(output_one_t& output, const input_one_t& v) const {
        auto b_rep = etl::force_temporary(etl::rep(b, nh1, nh2));

        etl::reshape(output, 1, k, nh1, nh2) = etl::conv_4d_valid_flipped(etl::reshape(v, 1, nc, nv1, nv2), w);

        output = f_activate<activation_function>(b_rep + output);
    }

    template <typename V>
    void activate_hidden(output_one_t& output, const V& v) const {
        decltype(auto) converted = converter_one<V, input_one_t>::convert(*this, v);
        activate_hidden(output, converted);
    }

    template <typename H1, typename V>
    void batch_activate_hidden(H1&& output, const V& v) const {
        output = etl::conv_4d_valid_flipped(v, w);

        auto b_rep = etl::force_temporary(etl::rep_l(etl::rep(b, nh1, nh2), etl::dim<0>(output)));

        output = f_activate<activation_function>(b_rep + output);
    }

    void prepare_input(input_one_t& input) const {
        input = input_one_t(nc, nv1, nv2);
    }

    template <typename Input>
    output_t prepare_output(std::size_t samples) const {
        output_t output;
        output.reserve(samples);
        for(size_t i = 0; i < samples; ++i){
            output.emplace_back(k, nh1, nh2);
        }
        return output;
    }

    template <typename Input>
    output_one_t prepare_one_output() const {
        return output_one_t(k, nh1, nh2);
    }

    template <typename DBN>
    void init_sgd_context() {
        this->sgd_context_ptr = std::make_shared<sgd_context<DBN, this_type>>(nc, nv1, nv2, k, nh1, nh2);
    }

    template<typename DRBM>
    static void dyn_init(DRBM&){
        //Nothing to change
    }

    /*!
     * \brief Adapt the errors, called before backpropagation of the errors.
     *
     * This must be used by layers that have both an activation fnction and a non-linearity.
     *
     * \param context the training context
     */
    template<typename C>
    void adapt_errors(C& context) const {
        context.errors = f_derivative<activation_function>(context.output) >> context.errors;
    }

    /*!
     * \brief Backpropagate the errors to the previous layers
     * \param output The ETL expression into which write the output
     * \param context The training context
     */
    template<typename H, typename C>
    void backward_batch(H&& output, C& context) const {
        output = etl::conv_4d_full_flipped(context.errors, w);
    }

    /*!
     * \brief Compute the gradients for this layer, if any
     * \param context The trainng context
     */
    template<typename C>
    void compute_gradients(C& context) const {
        context.w_grad = conv_4d_valid_filter_flipped(context.input, context.errors);
        context.b_grad = etl::mean_r(etl::sum_l(context.errors));
    }
};

// Declare the traits for the Layer

template<typename Desc>
struct layer_base_traits<dyn_conv_layer<Desc>> {
    static constexpr bool is_neural     = true;  ///< Indicates if the layer is a neural layer
    static constexpr bool is_dense      = false;  ///< Indicates if the layer is dense
    static constexpr bool is_conv       = true; ///< Indicates if the layer is convolutional
    static constexpr bool is_deconv     = false; ///< Indicates if the layer is deconvolutional
    static constexpr bool is_standard   = true;  ///< Indicates if the layer is standard
    static constexpr bool is_rbm        = false;  ///< Indicates if the layer is RBM
    static constexpr bool is_pooling    = false; ///< Indicates if the layer is a pooling layer
    static constexpr bool is_unpooling  = false; ///< Indicates if the layer is an unpooling laye
    static constexpr bool is_transform  = false; ///< Indicates if the layer is a transform layer
    static constexpr bool is_patches    = false; ///< Indicates if the layer is a patches layer
    static constexpr bool is_augment    = false; ///< Indicates if the layer is an augment layer
    static constexpr bool is_dynamic    = true; ///< Indicates if the layer is dynamic
    static constexpr bool pretrain_last = false; ///< Indicates if the layer is dynamic
    static constexpr bool sgd_supported = true;  ///< Indicates if the layer is supported by SGD
};

} //end of dll namespace
<|endoftext|>