<commit_before>/*** Copyright (c), The Regents of the University of California            ***
 *** For more information please refer to files in the COPYRIGHT directory ***/
/* rsLog.c - Routines for log files.
 */

#include "rsLog.hpp"
#include "rsGlobalExtern.hpp"

static time_t LogfileLastChkTime = 0;

void
getLogfileName( char **logFile, char *logDir, char *logFileName ) {
#ifndef _WIN32
    time_t myTime;
    struct tm *mytm;
    char *logfilePattern; // JMC - backport 4793
    char *logfileIntStr;
    int logfileInt;
    int tm_mday = 1;
    char logfileSuffix[MAX_NAME_LEN]; // JMC - backport 4793
    char myLogDir[MAX_NAME_LEN];

    /* Put together the full pathname of the logFile */

    if ( logDir == NULL ) {
        snprintf( myLogDir, MAX_NAME_LEN, "%-s", getLogDir() );
    }
    else {
        snprintf( myLogDir, MAX_NAME_LEN, "%-s", logDir );
    }
    *logFile = ( char * ) malloc( strlen( myLogDir ) + strlen( logFileName ) + 24 );

    LogfileLastChkTime = myTime = time( 0 );
    mytm = localtime( &myTime );
    if ( ( logfileIntStr = getenv( LOGFILE_INT ) ) == NULL ) {
        logfileInt = DEF_LOGFILE_INT;
    }
    else {
        logfileInt = atoi( logfileIntStr );
    }

    tm_mday = ( mytm->tm_mday / logfileInt ) * logfileInt + 1;
    if ( tm_mday > mytm->tm_mday ) {
        tm_mday -= logfileInt;
    }
    // =-=-=-=-=-=-=-
    // JMC - backport 4793
    if ( ( logfilePattern = getenv( LOGFILE_PATTERN ) ) == NULL ) {
        logfilePattern = DEF_LOGFILE_PATTERN;
    }
    mytm->tm_mday = tm_mday;
    strftime( logfileSuffix, MAX_NAME_LEN, logfilePattern, mytm );
    sprintf( *logFile, "%-s/%-s.%-s", myLogDir, logFileName, logfileSuffix );
    // =-=-=-=-=-=-=-

#else /* for Windows */
    char tmpstr[1024];
    iRODSNtGetLogFilenameWithPath( tmpstr );
    *logFile = _strdup( tmpstr );
#endif
}

#ifndef _WIN32
int
chkLogfileName( char *logDir, char *logFileName ) {
    time_t myTime;
    char *logFile = NULL;
    int i;

    myTime = time( 0 );
    if ( myTime < LogfileLastChkTime + LOGFILE_CHK_INT ) {
        /* not time yet */
        return 0;
    }

    getLogfileName( &logFile, logDir, logFileName );

    if ( CurLogfileName != NULL && strcmp( CurLogfileName, logFile ) == 0 ) {
        free( logFile );
        return 0;
    }

    /* open the logfile */

    if ( ( i = open( logFile, O_CREAT | O_RDWR, 0644 ) ) < 0 ) {
        fprintf( stderr, "Unable to open logFile %s\n", logFile );
        free( logFile );
        return -1;
    }
    else {
        lseek( i, 0, SEEK_END );
    }

    if ( CurLogfileName != NULL ) {
        free( CurLogfileName );
    }

    CurLogfileName = logFile;

    close( 0 );
    close( 1 );
    close( 2 );
    ( void ) dup2( i, 0 );
    ( void ) dup2( i, 1 );
    ( void ) dup2( i, 2 );
    ( void ) close( i );

    return 0;
}

#endif

<commit_msg>[#2212] CID25807:<commit_after>/*** Copyright (c), The Regents of the University of California            ***
 *** For more information please refer to files in the COPYRIGHT directory ***/
/* rsLog.c - Routines for log files.
 */

#include "rsLog.hpp"
#include "rsGlobalExtern.hpp"

static time_t LogfileLastChkTime = 0;

void
getLogfileName( char **logFile, char *logDir, char *logFileName ) {
#ifndef _WIN32
    time_t myTime;
    struct tm *mytm;
    char *logfilePattern; // JMC - backport 4793
    char *logfileIntStr;
    int logfileInt;
    int tm_mday = 1;
    char logfileSuffix[MAX_NAME_LEN]; // JMC - backport 4793
    char myLogDir[MAX_NAME_LEN];

    /* Put together the full pathname of the logFile */

    if ( logDir == NULL ) {
        snprintf( myLogDir, MAX_NAME_LEN, "%-s", getLogDir() );
    }
    else {
        snprintf( myLogDir, MAX_NAME_LEN, "%-s", logDir );
    }
    *logFile = ( char * ) malloc( strlen( myLogDir ) + strlen( logFileName ) + 24 );

    LogfileLastChkTime = myTime = time( 0 );
    mytm = localtime( &myTime );
    if ( ( logfileIntStr = getenv( LOGFILE_INT ) ) == NULL ||
            ( logfileInt = atoi( logfileIntStr ) ) < 1 ) {
        logfileInt = DEF_LOGFILE_INT;
    }

    tm_mday = ( mytm->tm_mday / logfileInt ) * logfileInt + 1;
    if ( tm_mday > mytm->tm_mday ) {
        tm_mday -= logfileInt;
    }
    // =-=-=-=-=-=-=-
    // JMC - backport 4793
    if ( ( logfilePattern = getenv( LOGFILE_PATTERN ) ) == NULL ) {
        logfilePattern = DEF_LOGFILE_PATTERN;
    }
    mytm->tm_mday = tm_mday;
    strftime( logfileSuffix, MAX_NAME_LEN, logfilePattern, mytm );
    sprintf( *logFile, "%-s/%-s.%-s", myLogDir, logFileName, logfileSuffix );
    // =-=-=-=-=-=-=-

#else /* for Windows */
    char tmpstr[1024];
    iRODSNtGetLogFilenameWithPath( tmpstr );
    *logFile = _strdup( tmpstr );
#endif
}

#ifndef _WIN32
int
chkLogfileName( char *logDir, char *logFileName ) {
    time_t myTime;
    char *logFile = NULL;
    int i;

    myTime = time( 0 );
    if ( myTime < LogfileLastChkTime + LOGFILE_CHK_INT ) {
        /* not time yet */
        return 0;
    }

    getLogfileName( &logFile, logDir, logFileName );

    if ( CurLogfileName != NULL && strcmp( CurLogfileName, logFile ) == 0 ) {
        free( logFile );
        return 0;
    }

    /* open the logfile */

    if ( ( i = open( logFile, O_CREAT | O_RDWR, 0644 ) ) < 0 ) {
        fprintf( stderr, "Unable to open logFile %s\n", logFile );
        free( logFile );
        return -1;
    }
    else {
        lseek( i, 0, SEEK_END );
    }

    if ( CurLogfileName != NULL ) {
        free( CurLogfileName );
    }

    CurLogfileName = logFile;

    close( 0 );
    close( 1 );
    close( 2 );
    ( void ) dup2( i, 0 );
    ( void ) dup2( i, 1 );
    ( void ) dup2( i, 2 );
    ( void ) close( i );

    return 0;
}

#endif

<|endoftext|>


<commit_before><commit_msg>Minor edit<commit_after><|endoftext|>


<commit_before>#include "common.h"
#include <stdarg.h>

// android
#if defined(ANDROID)
#include <android/log.h>
#endif

// win32
#if defined(_WIN32) && defined(_WINDOWS)
#include <windows.h>
#endif

namespace Common {

namespace {

std::string __format(const char *fmt, va_list ap) {
    std::string ret;

    size_t fmtlen = strlen(fmt);
    if (LIKELY(fmtlen < INT_MAX)) {  // Ensure fmtlen is in an int
        int len = static_cast<int>(fmtlen) + 1;

        // For each %, reserve 64 characters
        for (const char *p = strchr(fmt, '%'); p != nullptr; p = strchr(p, '%')) {
            char ch = *++p;
            if (ch != '%' && ch != '\0') len += 64;  // skip %%
        }

        do {
            ret.resize(len);
            int size = vsnprintf(&ret[0], len, fmt, ap);
            if (LIKELY(size >= 0)) {
                if (LIKELY(size < len)) {  // Everything worked
                    ret.resize(size);
                    ret.shrink_to_fit();
                    break;
                }
                len = size + 1;  // Needed size returned
                continue;
            }
            len *= 2;  // Guess at a larger size
        } while (1);
    }

    return ret;
}

}

std::string format(const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    std::string ret = __format(fmt, ap);
    va_end(ap);
    return std::move(ret);
}

void __log(const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    std::string ret = __format(fmt, ap);
    va_end(ap);
    ret.append(1, '\n');

#if defined(ANDROID)
    __android_log_print(ANDROID_LOG_DEBUG, "debug info", "%s", ret.c_str());
#elif defined(_WIN32) && defined(_WINDOWS)
    std::wstring wszBuf;
    int len = ::MultiByteToWideChar(CP_UTF8, 0, ret.c_str(), -1, nullptr, 0);
    if (len > 0) {
        wszBuf.resize(len);
        ::MultiByteToWideChar(CP_UTF8, 0, ret.c_str(), -1, &wszBuf[0], len);
        ::OutputDebugStringW(wszBuf.c_str());
    }
#else
    // Linux, Mac, iOS, etc
    fprintf(stdout, "%s", ret.c_str());
    fflush(stdout);
#endif
}

std::string getStringFromFile(const char *file) {
    std::string str;
    FILE *fp = fopen(file, "rb");
    if (LIKELY(fp != nullptr)) {
        fseek(fp, 0, SEEK_END);
        long size = ftell(fp);
        fseek(fp, 0, SEEK_SET);
        try {
            str.resize(size + 1);
            fread(&str[0], sizeof(char), size, fp);
        }
        catch (...) {
        }
        fclose(fp);
    }
    return str;
}

}
<commit_msg>修复重复使用va_list导致xcode下闪退的bug<commit_after>#include "common.h"
#include <stdarg.h>

// android
#if defined(ANDROID)
#include <android/log.h>
#endif

// win32
#if defined(_WIN32) && defined(_WINDOWS)
#include <windows.h>
#endif

namespace Common {

namespace {

std::string __format(const char *fmt, va_list ap) {
    std::string ret;

    size_t fmtlen = strlen(fmt);
    if (LIKELY(fmtlen < INT_MAX)) {  // Ensure fmtlen is in an int
        int len = static_cast<int>(fmtlen) + 1;

        // For each %, reserve 64 characters
        for (const char *p = strchr(fmt, '%'); p != nullptr; p = strchr(p, '%')) {
            char ch = *++p;
            if (ch != '%' && ch != '\0') len += 64;  // skip %%
        }

        do {
            ret.resize(len);
            va_list temp;
            va_copy(temp, ap);
            int size = vsnprintf(&ret[0], len, fmt, temp);
            va_end(temp);
            if (LIKELY(size >= 0)) {
                if (LIKELY(size < len)) {  // Everything worked
                    ret.resize(size);
                    ret.shrink_to_fit();
                    break;
                }
                len = size + 1;  // Needed size returned
                continue;
            }
            len *= 2;  // Guess at a larger size
        } while (1);
    }

    return ret;
}

}

std::string format(const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    std::string ret = __format(fmt, ap);
    va_end(ap);
    return std::move(ret);
}

void __log(const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    std::string ret = __format(fmt, ap);
    va_end(ap);
    ret.append(1, '\n');

#if defined(ANDROID)
    __android_log_print(ANDROID_LOG_DEBUG, "debug info", "%s", ret.c_str());
#elif defined(_WIN32) && defined(_WINDOWS)
    std::wstring wszBuf;
    int len = ::MultiByteToWideChar(CP_UTF8, 0, ret.c_str(), -1, nullptr, 0);
    if (len > 0) {
        wszBuf.resize(len);
        ::MultiByteToWideChar(CP_UTF8, 0, ret.c_str(), -1, &wszBuf[0], len);
        ::OutputDebugStringW(wszBuf.c_str());
    }
#else
    // Linux, Mac, iOS, etc
    fprintf(stdout, "%s", ret.c_str());
    fflush(stdout);
#endif
}

std::string getStringFromFile(const char *file) {
    std::string str;
    FILE *fp = fopen(file, "rb");
    if (LIKELY(fp != nullptr)) {
        fseek(fp, 0, SEEK_END);
        long size = ftell(fp);
        fseek(fp, 0, SEEK_SET);
        try {
            str.resize(size + 1);
            fread(&str[0], sizeof(char), size, fp);
        }
        catch (...) {
        }
        fclose(fp);
    }
    return str;
}

}
<|endoftext|>


<commit_before>#ifndef STAN_SERVICES_UTIL_INITIALIZE_HPP
#define STAN_SERVICES_UTIL_INITIALIZE_HPP

#include <stan/io/var_context.hpp>
#include <stan/io/random_var_context.hpp>
#include <stan/io/chained_var_context.hpp>
#include <stan/model/log_prob_grad.hpp>
#include <limits>
#include <sstream>
#include <string>
#include <vector>

namespace stan {
  namespace services {
    namespace util {

      template <class Model, class RNG>
      std::vector<double> initialize(Model& model,
                                     stan::io::var_context& init,
                                     RNG& rng,
                                     double init_radius,
                                     bool print_timing,
                                     callbacks::writer&
                                     message_writer,
                                     callbacks::writer&
                                     init_writer) {
        std::vector<double> unconstrained;
        std::vector<int> disc_vector;
        std::stringstream msg;

        bool is_fully_initialized = true;
        bool any_initialized = false;
        std::vector<std::string> param_names;
        model.get_param_names(param_names);
        for (size_t n = 0; n < param_names.size(); n++) {
          is_fully_initialized &= init.contains_r(param_names[n]);
          any_initialized |= init.contains_r(param_names[n]);
        }

        bool init_zero = init_radius <= std::numeric_limits<double>::min();

        int MAX_INIT_TRIES = is_fully_initialized || init_zero ? 1 : 100;
        int num_init_tries = 0;
        for (; num_init_tries < MAX_INIT_TRIES; num_init_tries++) {
          stan::io::random_var_context
            random_context(model, rng, init_radius, init_zero);

          if (!any_initialized) {
            unconstrained = random_context.get_unconstrained();
          } else {
            stan::io::chained_var_context context(init, random_context);

            model.transform_inits(context,
                                  disc_vector,
                                  unconstrained,
                                  &msg);
            if (msg.str().length() > 0)
              message_writer(msg.str());
          }
          double log_prob(0);
          try {
            msg.str("");
            log_prob = model.template log_prob<false, true>
              (unconstrained, disc_vector, &msg);
            if (msg.str().length() > 0)
              message_writer(msg.str());
          } catch (std::exception& e) {
            message_writer();
            message_writer("Rejecting initial value:");
            message_writer("  Error evaluating the log probability "
                   "at the initial value.");
            continue;
          }
          if (!boost::math::isfinite(log_prob)) {
            message_writer("Rejecting initial value:");
            message_writer("  Log probability evaluates to log(0), "
                   "i.e. negative infinity.");
            message_writer("  Stan can't start sampling from this "
                           "initial value.");
            continue;
          }
          msg.str("");
          std::vector<double> gradient;
          bool gradient_ok = true;
          clock_t start_check = clock();
          log_prob = stan::model::log_prob_grad<true, true>
            (model, unconstrained, disc_vector,
             gradient, &msg);
          clock_t end_check = clock();
          double deltaT = static_cast<double>(end_check - start_check)
            / CLOCKS_PER_SEC;
          if (msg.str().length() > 0)
            message_writer(msg.str());

          for (size_t i = 0; i < gradient.size(); ++i) {
            if (gradient_ok && !boost::math::isfinite(gradient[i])) {
              message_writer("Rejecting initial value:");
              message_writer("  Gradient evaluated at the initial value "
                     "is not finite.");
              message_writer("  Stan can't start sampling from this "
                             "initial value.");
              gradient_ok = false;
            }
          }
          if (gradient_ok && print_timing) {
            msg.str("");
            message_writer();
            msg << "Gradient evaluation took " << deltaT << " seconds";
            message_writer(msg.str());
            msg.str("");
            msg  << "1000 transitions using 10 leapfrog steps "
                 << "per transition would take "
                 << 1e4 * deltaT << " seconds.";
            message_writer(msg.str());
            msg.str("");
            message_writer("Adjust your expectations accordingly!");
            message_writer();
            message_writer();
          }
          if (gradient_ok)
            break;
        }

        if (num_init_tries == MAX_INIT_TRIES) {
          if (!is_fully_initialized && !init_zero) {
            message_writer();
            msg.str("");
            msg << "Initialization between (-" << init_radius
                << ", " << init_radius << ") failed after "
                << MAX_INIT_TRIES <<  " attempts. ";
            message_writer(msg.str());
            message_writer(" Try specifying initial values,"
                           " reducing ranges of constrained values,"
                           " or reparameterizing the model.");
          }
          throw std::domain_error("");
        }

        init_writer(unconstrained);
        return unconstrained;
      }

    }
  }
}

#endif
<commit_msg>Updating includes<commit_after>#ifndef STAN_SERVICES_UTIL_INITIALIZE_HPP
#define STAN_SERVICES_UTIL_INITIALIZE_HPP

#include <stan/callbacks/writer.hpp>
#include <stan/io/var_context.hpp>
#include <stan/io/random_var_context.hpp>
#include <stan/io/chained_var_context.hpp>
#include <stan/model/log_prob_grad.hpp>
#include <limits>
#include <sstream>
#include <string>
#include <vector>

namespace stan {
  namespace services {
    namespace util {

      template <class Model, class RNG>
      std::vector<double> initialize(Model& model,
                                     stan::io::var_context& init,
                                     RNG& rng,
                                     double init_radius,
                                     bool print_timing,
                                     callbacks::writer&
                                     message_writer,
                                     callbacks::writer&
                                     init_writer) {
        std::vector<double> unconstrained;
        std::vector<int> disc_vector;
        std::stringstream msg;

        bool is_fully_initialized = true;
        bool any_initialized = false;
        std::vector<std::string> param_names;
        model.get_param_names(param_names);
        for (size_t n = 0; n < param_names.size(); n++) {
          is_fully_initialized &= init.contains_r(param_names[n]);
          any_initialized |= init.contains_r(param_names[n]);
        }

        bool init_zero = init_radius <= std::numeric_limits<double>::min();

        int MAX_INIT_TRIES = is_fully_initialized || init_zero ? 1 : 100;
        int num_init_tries = 0;
        for (; num_init_tries < MAX_INIT_TRIES; num_init_tries++) {
          stan::io::random_var_context
            random_context(model, rng, init_radius, init_zero);

          if (!any_initialized) {
            unconstrained = random_context.get_unconstrained();
          } else {
            stan::io::chained_var_context context(init, random_context);

            model.transform_inits(context,
                                  disc_vector,
                                  unconstrained,
                                  &msg);
            if (msg.str().length() > 0)
              message_writer(msg.str());
          }
          double log_prob(0);
          try {
            msg.str("");
            log_prob = model.template log_prob<false, true>
              (unconstrained, disc_vector, &msg);
            if (msg.str().length() > 0)
              message_writer(msg.str());
          } catch (std::exception& e) {
            message_writer();
            message_writer("Rejecting initial value:");
            message_writer("  Error evaluating the log probability "
                   "at the initial value.");
            continue;
          }
          if (!boost::math::isfinite(log_prob)) {
            message_writer("Rejecting initial value:");
            message_writer("  Log probability evaluates to log(0), "
                   "i.e. negative infinity.");
            message_writer("  Stan can't start sampling from this "
                           "initial value.");
            continue;
          }
          msg.str("");
          std::vector<double> gradient;
          bool gradient_ok = true;
          clock_t start_check = clock();
          log_prob = stan::model::log_prob_grad<true, true>
            (model, unconstrained, disc_vector,
             gradient, &msg);
          clock_t end_check = clock();
          double deltaT = static_cast<double>(end_check - start_check)
            / CLOCKS_PER_SEC;
          if (msg.str().length() > 0)
            message_writer(msg.str());

          for (size_t i = 0; i < gradient.size(); ++i) {
            if (gradient_ok && !boost::math::isfinite(gradient[i])) {
              message_writer("Rejecting initial value:");
              message_writer("  Gradient evaluated at the initial value "
                     "is not finite.");
              message_writer("  Stan can't start sampling from this "
                             "initial value.");
              gradient_ok = false;
            }
          }
          if (gradient_ok && print_timing) {
            msg.str("");
            message_writer();
            msg << "Gradient evaluation took " << deltaT << " seconds";
            message_writer(msg.str());
            msg.str("");
            msg  << "1000 transitions using 10 leapfrog steps "
                 << "per transition would take "
                 << 1e4 * deltaT << " seconds.";
            message_writer(msg.str());
            msg.str("");
            message_writer("Adjust your expectations accordingly!");
            message_writer();
            message_writer();
          }
          if (gradient_ok)
            break;
        }

        if (num_init_tries == MAX_INIT_TRIES) {
          if (!is_fully_initialized && !init_zero) {
            message_writer();
            msg.str("");
            msg << "Initialization between (-" << init_radius
                << ", " << init_radius << ") failed after "
                << MAX_INIT_TRIES <<  " attempts. ";
            message_writer(msg.str());
            message_writer(" Try specifying initial values,"
                           " reducing ranges of constrained values,"
                           " or reparameterizing the model.");
          }
          throw std::domain_error("");
        }

        init_writer(unconstrained);
        return unconstrained;
      }

    }
  }
}

#endif
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <GL/gl.h>

#include <X11/X.h>
#include <X11/Xlib.h>
#include <GL/glx.h>
#include <unistd.h>

// Required GL 2.1 funcs
typedef GLuint (*GlCreateShader)(GLenum);
GlCreateShader glCreateShader;
typedef void (*GlShaderSource)(GLuint, GLsizei, const GLchar**, const GLint*);
GlShaderSource glShaderSource;
typedef void (*GlCompileShader)(GLuint);
GlCompileShader glCompileShader;
typedef GLuint (*GlCreateProgram)();
GlCreateProgram glCreateProgram;
typedef void (*GlAttachShader)(GLuint, GLuint);
GlAttachShader glAttachShader;
typedef void (*GlLinkProgram)(GLuint);
GlLinkProgram glLinkProgram;
typedef void (*GlUseProgram)(GLuint);
GlUseProgram glUseProgram;
typedef void (*GlGetShaderiv)(GLuint, GLenum, GLint*);
GlGetShaderiv glGetShaderiv;
typedef void (*GlGetProgramiv)(GLuint, GLenum, GLint*);
GlGetProgramiv glGetProgramiv;
typedef void (*GlGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*);
GlGetShaderInfoLog glGetShaderInfoLog;
typedef void (*GlGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*);
GlGetProgramInfoLog glGetProgramInfoLog;
typedef void (*GlDetachShader)(GLuint, GLuint);
GlDetachShader glDetachShader;
typedef void (*GlDeleteShader)(GLuint);
GlDeleteShader glDeleteShader;
typedef void (*GlDeleteProgram)(GLuint);
GlDeleteProgram glDeleteProgram;
typedef GLuint (*GlGetUniformLocation)(GLuint, const GLchar*);
GlGetUniformLocation glGetUniformLocation;
typedef void (*GlUniform1f)(GLuint, GLfloat);
GlUniform1f glUniform1f;

namespace qm {

struct Env {
	Display*	dpy;
	Window      win;
	GLXContext  ctx;
};

struct Shader {
	GLuint vs;
	GLuint fs;
	GLuint prog;
	GLuint phaseLoc;
};

const GLchar* g_vs= "\
#version 120\n\
varying vec3 v_pos; \
void main() \
{ \
	float z_dist= gl_Vertex.z + 1.01; \
    gl_Position= vec4(gl_Vertex.xy/z_dist, 0.0, 1.0); \
	v_pos= (gl_ModelViewProjectionMatrix*gl_Vertex).xyz; \
} \
\n";

const GLchar* g_fs= "\
#version 120\n\
uniform float u_phase; \
varying vec3 v_pos; \
void main() \
{ \
	float beam_a= \
		abs(cos(v_pos.x*10.0 - sign(v_pos.x)*u_phase)*0.5 + 1.0)* \
			0.001/(v_pos.z*v_pos.z + v_pos.y*v_pos.y) + \
		0.005/(v_pos.x*v_pos.x + 0.05*(v_pos.z*v_pos.z + v_pos.y*v_pos.y)); \
	vec3 beam_c= vec3(0.3 + abs(v_pos.x), 0.8, 1.0); \
	float hole_a= pow(min(1.0, 0.1/(dot(v_pos, v_pos))), 2.0); \
	float lerp= clamp(beam_a*(1.0 - hole_a), 0.0, 1.0); \
    gl_FragColor= vec4(beam_c*lerp, beam_a + hole_a); \
} \
\n";

typedef void (*voidFunc)();
voidFunc queryGlFunc(const char* name)
{
	voidFunc f=	glXGetProcAddressARB((const GLubyte*)name);
	if (!f) {
		std::printf("Failed to query function: %s", name);
		std::abort();
	}
	return f;
}

void checkShaderStatus(GLuint shd)
{
	GLint status;
	glGetShaderiv(shd, GL_COMPILE_STATUS, &status);
	if (!status) {
		const GLsizei max_len= 512;
		GLchar log[max_len];
		glGetShaderInfoLog(shd, max_len, NULL, log);
		std::printf("Shader compilation failed: %s", log);
		std::abort();
	}
}

void checkProgramStatus(GLuint prog)
{
	GLint link_status;
	glGetProgramiv(prog, GL_LINK_STATUS, &link_status);
	if (!link_status) {
		const GLsizei size= 512;
		GLchar log[size];
		glGetProgramInfoLog(prog, size, NULL, log);
		std::printf("Program link failed: %s", log);
		std::abort();
	}
}

void init(Env& env, Shader& shd)
{
	{ // Create window
		env.dpy= XOpenDisplay(NULL);
		if(env.dpy == NULL)
			std::abort();

		Window root= DefaultRootWindow(env.dpy);
		GLint att[]= { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
		XVisualInfo* vi= glXChooseVisual(env.dpy, 0, att);

		if(vi == NULL)
			std::abort();

		Colormap cmap;
		cmap= XCreateColormap(env.dpy, root, vi->visual, AllocNone);
		XSetWindowAttributes swa;
		swa.colormap= cmap;
		swa.event_mask= ExposureMask | KeyPressMask;
		env.win=
			XCreateWindow(	env.dpy,
							root,
							0, 0, 600, 600, 0,
							vi->depth,
							InputOutput,
							vi->visual,
							CWColormap | CWEventMask,
							&swa);
		XMapWindow(env.dpy, env.win);
		XStoreName(env.dpy, env.win, "QM Test");

		env.ctx= glXCreateContext(env.dpy, vi, NULL, GL_TRUE);
		glXMakeCurrent(env.dpy, env.win, env.ctx);
	}

	{ // Query necessary GL functions
		glCreateShader= (GlCreateShader)queryGlFunc("glCreateShader");
		glShaderSource= (GlShaderSource)queryGlFunc("glShaderSource");
		glCompileShader= (GlCompileShader)queryGlFunc("glCompileShader");
		glCreateProgram= (GlCreateProgram)queryGlFunc("glCreateProgram");
		glAttachShader= (GlAttachShader)queryGlFunc("glAttachShader");
		glLinkProgram= (GlLinkProgram)queryGlFunc("glLinkProgram");
		glUseProgram= (GlUseProgram)queryGlFunc("glUseProgram");
		glGetShaderiv= (GlGetShaderiv)queryGlFunc("glGetShaderiv");
		glGetProgramiv= (GlGetProgramiv)queryGlFunc("glGetProgramiv");
		glGetShaderInfoLog= (GlGetShaderInfoLog)queryGlFunc("glGetShaderInfoLog");
		glGetProgramInfoLog= (GlGetProgramInfoLog)queryGlFunc("glGetProgramInfoLog");
		glDetachShader= (GlDetachShader)queryGlFunc("glDetachShader");
		glDeleteShader= (GlDeleteShader)queryGlFunc("glDeleteShader");
		glDeleteProgram= (GlDeleteProgram)queryGlFunc("glDeleteProgram");
		glGetUniformLocation= (GlGetUniformLocation)queryGlFunc("glGetUniformLocation");
		glUniform1f= (GlUniform1f)queryGlFunc("glUniform1f");
	}

	{ // Create shaders
		{ // Vertex
			shd.vs= glCreateShader(GL_VERTEX_SHADER);
			glShaderSource(shd.vs, 1, &g_vs, NULL);
			glCompileShader(shd.vs);
			checkShaderStatus(shd.vs);
		}
		{ // Fragment
			shd.fs= glCreateShader(GL_FRAGMENT_SHADER);
			glShaderSource(shd.fs, 1, &g_fs, NULL);
			glCompileShader(shd.fs);
			checkShaderStatus(shd.fs);
		}
		{ // Shader program
			shd.prog= glCreateProgram();
			glAttachShader(shd.prog, shd.vs);
			glAttachShader(shd.prog, shd.fs);
			glLinkProgram(shd.prog);
			checkProgramStatus(shd.prog);

			shd.phaseLoc= glGetUniformLocation(shd.prog, "u_phase");
		}
	}

	{ // Setup initial GL state
		glClearColor(0.0, 0.0, 0.0, 0.0);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE); // Additive
	}
}

void quit(const Env& env, const Shader& shd)
{
	{ // Close window
		glXMakeCurrent(env.dpy, None, NULL);
		glXDestroyContext(env.dpy, env.ctx);
		XDestroyWindow(env.dpy, env.win);
		XCloseDisplay(env.dpy);
	}

	{ // Destroy shaders
		glDetachShader(shd.prog, shd.vs);
		glDeleteShader(shd.vs);

		glDetachShader(shd.prog, shd.fs);
		glDeleteShader(shd.fs);

		glDeleteProgram(shd.prog);
	}
}

void draw(const Shader& shd, float x, float y)
{
	static float phase;
	static float prev_x, prev_y;
	phase += 0.3;

	// Smooth rotating
	x= prev_x*0.5 + x*0.5;
	y= prev_y*0.5 + y*0.5;
	prev_x= x;
	prev_y= y;

	glClear(GL_COLOR_BUFFER_BIT);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glRotatef(std::sqrt(x*x + y*y)*200.0, y, -x, 0.0);

	int slices= 55;

	glUseProgram(shd.prog);
	glUniform1f(shd.phaseLoc, phase);

	glBegin(GL_QUADS);
	for (int i= 0; i < slices; ++i) {
		// z in [-1.0, 1.0]
		float z= 1.0 - 2.0*i/slices;
		glVertex3f(-1, -1, z);
		glVertex3f(1, -1, z);
		glVertex3f(1,  1, z);
		glVertex3f(-1, 1, z);
	}
	glEnd();
}

bool loop(const Env& env, const Shader& shd)
{
	int root_x= 0, root_y= 0;
    Window w;
    int win_x, win_y;
    unsigned int mask_return;
	XQueryPointer(env.dpy, env.win, &w,
			&w, &root_x, &root_y, &win_x, &win_y,
			&mask_return);

	XWindowAttributes gwa;
	XGetWindowAttributes(env.dpy, env.win, &gwa);
	glViewport(0, 0, gwa.width, gwa.height);

	qm::draw(	shd,
				2.0*win_x/gwa.width - 1.0,
				1.0 - 2.0*win_y/gwa.height);

	usleep(1);
	glXSwapBuffers(env.dpy, env.win);

	while(XPending(env.dpy)) {
		XEvent xev;
        XNextEvent(env.dpy, &xev);
		if(xev.type == KeyPress)
			return false;
	}

	return true;
}

} // qm

int main()
{
	qm::Env env;
	qm::Shader shd;

	qm::init(env, shd);
	while(loop(env, shd));
	qm::quit(env, shd);
}

<commit_msg>Raycasting<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <GL/gl.h>

#include <X11/X.h>
#include <X11/Xlib.h>
#include <GL/glx.h>
#include <unistd.h>

// Required GL 2.1 funcs
typedef GLuint (*GlCreateShader)(GLenum);
GlCreateShader glCreateShader;
typedef void (*GlShaderSource)(GLuint, GLsizei, const GLchar**, const GLint*);
GlShaderSource glShaderSource;
typedef void (*GlCompileShader)(GLuint);
GlCompileShader glCompileShader;
typedef GLuint (*GlCreateProgram)();
GlCreateProgram glCreateProgram;
typedef void (*GlAttachShader)(GLuint, GLuint);
GlAttachShader glAttachShader;
typedef void (*GlLinkProgram)(GLuint);
GlLinkProgram glLinkProgram;
typedef void (*GlUseProgram)(GLuint);
GlUseProgram glUseProgram;
typedef void (*GlGetShaderiv)(GLuint, GLenum, GLint*);
GlGetShaderiv glGetShaderiv;
typedef void (*GlGetProgramiv)(GLuint, GLenum, GLint*);
GlGetProgramiv glGetProgramiv;
typedef void (*GlGetShaderInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*);
GlGetShaderInfoLog glGetShaderInfoLog;
typedef void (*GlGetProgramInfoLog)(GLuint, GLsizei, GLsizei*, GLchar*);
GlGetProgramInfoLog glGetProgramInfoLog;
typedef void (*GlDetachShader)(GLuint, GLuint);
GlDetachShader glDetachShader;
typedef void (*GlDeleteShader)(GLuint);
GlDeleteShader glDeleteShader;
typedef void (*GlDeleteProgram)(GLuint);
GlDeleteProgram glDeleteProgram;
typedef GLuint (*GlGetUniformLocation)(GLuint, const GLchar*);
GlGetUniformLocation glGetUniformLocation;
typedef void (*GlUniform1f)(GLuint, GLfloat);
GlUniform1f glUniform1f;

namespace qm {

struct Env {
	Display*	dpy;
	Window		win;
	GLXContext	ctx;
};

struct Shader {
	GLuint vs;
	GLuint fs;
	GLuint prog;
	GLuint phaseLoc;
};

const GLchar* g_vs= "\
#version 120\n\
varying vec3 v_pos; \
varying vec3 v_normal; \
void main() \
{ \
    gl_Position= vec4(gl_Vertex.xy, 0.0, 1.0); \
	v_pos= (gl_ModelViewMatrix*gl_Vertex).xyz; \
	v_normal= mat3(gl_ModelViewMatrix)*vec3(gl_Vertex.xy, -1.0); \
} \
\n";

const GLchar* g_fs= "\
#version 120\n\
uniform float u_phase; \
varying vec3 v_pos; \
varying vec3 v_normal; \
/* x emission, y translucency */ \
vec2 sample(vec3 p) \
{ \
	float beam_a= \
		abs(cos(p.x*10.0 - sign(p.x)*u_phase)*0.5 + 1.0)* \
			0.001/(p.z*p.z + p.y*p.y) + \
		0.01/((p.x*p.x + 0.01)*(p.z*p.z + p.y*p.y)*100.0 + 0.1); \
	float hole_a= pow(min(1.0, 0.1/(dot(p, p))), 10.0); \
	float lerp= clamp((1.0 - hole_a), 0.0, 1.0); \
    return vec2(beam_a*lerp, lerp); \
} \
void main() \
{ \
	vec3 n= normalize(v_normal); \
	vec3 color= vec3(0.3, 0.8, 1.0); \
	vec3 accum= vec3(0, 0, 0); \
	float transparency= 1.0; \
	const int steps= 45; \
	for (int i= 0; i < steps; ++i) { \
		vec2 s= sample(v_pos + n*2.0*float(i)/steps); \
		accum += color*s.x*transparency; \
		transparency *= s.y; \
	} \
	gl_FragColor= vec4(accum, 1.0); \
} \
\n";

typedef void (*voidFunc)();
voidFunc queryGlFunc(const char* name)
{
	voidFunc f=	glXGetProcAddressARB((const GLubyte*)name);
	if (!f) {
		std::printf("Failed to query function: %s", name);
		std::abort();
	}
	return f;
}

void checkShaderStatus(GLuint shd)
{
	GLint status;
	glGetShaderiv(shd, GL_COMPILE_STATUS, &status);
	if (!status) {
		const GLsizei max_len= 512;
		GLchar log[max_len];
		glGetShaderInfoLog(shd, max_len, NULL, log);
		std::printf("Shader compilation failed: %s", log);
		std::abort();
	}
}

void checkProgramStatus(GLuint prog)
{
	GLint link_status;
	glGetProgramiv(prog, GL_LINK_STATUS, &link_status);
	if (!link_status) {
		const GLsizei size= 512;
		GLchar log[size];
		glGetProgramInfoLog(prog, size, NULL, log);
		std::printf("Program link failed: %s", log);
		std::abort();
	}
}

void init(Env& env, Shader& shd)
{
	{ // Create window
		env.dpy= XOpenDisplay(NULL);
		if(env.dpy == NULL)
			std::abort();

		Window root= DefaultRootWindow(env.dpy);
		GLint att[]= { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
		XVisualInfo* vi= glXChooseVisual(env.dpy, 0, att);

		if(vi == NULL)
			std::abort();

		Colormap cmap;
		cmap= XCreateColormap(env.dpy, root, vi->visual, AllocNone);
		XSetWindowAttributes swa;
		swa.colormap= cmap;
		swa.event_mask= ExposureMask | KeyPressMask;
		env.win=
			XCreateWindow(	env.dpy,
							root,
							0, 0, 600, 600, 0,
							vi->depth,
							InputOutput,
							vi->visual,
							CWColormap | CWEventMask,
							&swa);
		XMapWindow(env.dpy, env.win);
		XStoreName(env.dpy, env.win, "QM Test");

		env.ctx= glXCreateContext(env.dpy, vi, NULL, GL_TRUE);
		glXMakeCurrent(env.dpy, env.win, env.ctx);
	}

	{ // Query necessary GL functions
		glCreateShader= (GlCreateShader)queryGlFunc("glCreateShader");
		glShaderSource= (GlShaderSource)queryGlFunc("glShaderSource");
		glCompileShader= (GlCompileShader)queryGlFunc("glCompileShader");
		glCreateProgram= (GlCreateProgram)queryGlFunc("glCreateProgram");
		glAttachShader= (GlAttachShader)queryGlFunc("glAttachShader");
		glLinkProgram= (GlLinkProgram)queryGlFunc("glLinkProgram");
		glUseProgram= (GlUseProgram)queryGlFunc("glUseProgram");
		glGetShaderiv= (GlGetShaderiv)queryGlFunc("glGetShaderiv");
		glGetProgramiv= (GlGetProgramiv)queryGlFunc("glGetProgramiv");
		glGetShaderInfoLog= (GlGetShaderInfoLog)queryGlFunc("glGetShaderInfoLog");
		glGetProgramInfoLog= (GlGetProgramInfoLog)queryGlFunc("glGetProgramInfoLog");
		glDetachShader= (GlDetachShader)queryGlFunc("glDetachShader");
		glDeleteShader= (GlDeleteShader)queryGlFunc("glDeleteShader");
		glDeleteProgram= (GlDeleteProgram)queryGlFunc("glDeleteProgram");
		glGetUniformLocation= (GlGetUniformLocation)queryGlFunc("glGetUniformLocation");
		glUniform1f= (GlUniform1f)queryGlFunc("glUniform1f");
	}

	{ // Create shaders
		{ // Vertex
			shd.vs= glCreateShader(GL_VERTEX_SHADER);
			glShaderSource(shd.vs, 1, &g_vs, NULL);
			glCompileShader(shd.vs);
			checkShaderStatus(shd.vs);
		}
		{ // Fragment
			shd.fs= glCreateShader(GL_FRAGMENT_SHADER);
			glShaderSource(shd.fs, 1, &g_fs, NULL);
			glCompileShader(shd.fs);
			checkShaderStatus(shd.fs);
		}
		{ // Shader program
			shd.prog= glCreateProgram();
			glAttachShader(shd.prog, shd.vs);
			glAttachShader(shd.prog, shd.fs);
			glLinkProgram(shd.prog);
			checkProgramStatus(shd.prog);

			shd.phaseLoc= glGetUniformLocation(shd.prog, "u_phase");
		}
	}

	{ // Setup initial GL state
		glClearColor(0.0, 0.0, 0.0, 0.0);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}
}

void quit(const Env& env, const Shader& shd)
{
	{ // Close window
		glXMakeCurrent(env.dpy, None, NULL);
		glXDestroyContext(env.dpy, env.ctx);
		XDestroyWindow(env.dpy, env.win);
		XCloseDisplay(env.dpy);
	}

	{ // Destroy shaders
		glDetachShader(shd.prog, shd.vs);
		glDeleteShader(shd.vs);

		glDetachShader(shd.prog, shd.fs);
		glDeleteShader(shd.fs);

		glDeleteProgram(shd.prog);
	}
}

void draw(const Shader& shd, float x, float y)
{
	static float phase;
	static float prev_x, prev_y;
	phase += 0.3;

	// Smooth rotating
	x= prev_x*0.5 + x*0.5;
	y= prev_y*0.5 + y*0.5;
	prev_x= x;
	prev_y= y;

	glClear(GL_COLOR_BUFFER_BIT);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glRotatef(std::sqrt(x*x + y*y)*200.0, y, -x, 0.0);

	glUseProgram(shd.prog);
	glUniform1f(shd.phaseLoc, phase);

	glBegin(GL_QUADS);
		glVertex3f(-1, -1, 1);
		glVertex3f(1, -1, 1);
		glVertex3f(1,  1, 1);
		glVertex3f(-1, 1, 1);
	glEnd();
}

bool loop(const Env& env, const Shader& shd)
{
	int root_x= 0, root_y= 0;
	Window w;
	int win_x, win_y;
	unsigned int mask_return;
	XQueryPointer(	env.dpy, env.win, &w,
					&w, &root_x, &root_y, &win_x, &win_y,
					&mask_return);

	XWindowAttributes gwa;
	XGetWindowAttributes(env.dpy, env.win, &gwa);
	glViewport(0, 0, gwa.width, gwa.height);

	qm::draw(	shd,
				2.0*win_x/gwa.width - 1.0,
				1.0 - 2.0*win_y/gwa.height);

	usleep(1);
	glXSwapBuffers(env.dpy, env.win);

	while(XPending(env.dpy)) {
		XEvent xev;
        XNextEvent(env.dpy, &xev);
		if(xev.type == KeyPress)
			return false;
	}

	return true;
}

} // qm

int main()
{
	qm::Env env;
	qm::Shader shd;

	qm::init(env, shd);
	while(loop(env, shd));
	qm::quit(env, shd);
}

<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2009-05-05 19:02:32 +0200 (Tue, 05 May 2009) $
Version:   $Revision: 17105 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkImageFileWriter.h"
#include "itkWarpImageFilter.h"
#include "itkImageRegionIterator.h"

#include "mitkBSplineRegistration.h"
#include "itkBSplineDeformableTransform.h"
//#include "itkLBFGSOptimizer.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkMattesMutualInformationImageToImageMetric.h"
#include "itkResampleImageFilter.h"
#include "itkImageRegistrationMethod.h"

#include "itkBSplineDeformableTransformInitializer.h"

#include "mitkOptimizerFactory.h"

namespace mitk {

  BSplineRegistration::BSplineRegistration():
    m_Iterations(50),
    m_ResultName("deformedImage.mhd"),
    m_SaveResult(true),
    m_SaveDeformationField(false),
    m_UpdateInputImage(false)
  {

  }

  BSplineRegistration::~BSplineRegistration()
  {
  }

  void BSplineRegistration::SetNumberOfIterations(int iterations)
  {
    m_Iterations = iterations;
  }

  void BSplineRegistration::SetSaveResult(bool saveResult)
  {
    m_SaveResult = saveResult;
  }

  void BSplineRegistration::SetResultFileName(const char* resultName)
  {
    m_ResultName = resultName;
  }

  template < typename TPixel, unsigned int VImageDimension >
    void BSplineRegistration::GenerateData2( itk::Image<TPixel, VImageDimension>* itkImage1)
  {
    std::cout << "start bspline registration" << std::endl;

    // Typedefs
    typedef typename itk::Image< TPixel, VImageDimension >  FixedImageType;
    typedef typename itk::Image< TPixel, VImageDimension >  MovingImageType;

    typedef typename itk::Vector< float, VImageDimension >    VectorPixelType;
    typedef typename itk::Image<  VectorPixelType, VImageDimension > DeformationFieldType;

    typedef itk::BSplineDeformableTransform<
                                double,
                                VImageDimension,
                                3 >                         TransformType;

    typedef typename TransformType::ParametersType          ParametersType;

    //typedef itk::LBFGSOptimizer                             OptimizerType;
    typedef itk::SingleValuedNonLinearOptimizer             OptimizerType;
    typedef itk::MattesMutualInformationImageToImageMetric<
                                FixedImageType,
                                MovingImageType >           MetricType;

    /*typedef itk::MeanSquaresImageToImageMetric<
                                FixedImageType,
                                MovingImageType >           MetricType;*/

    typedef itk::LinearInterpolateImageFunction<
                                MovingImageType,
                                double >                    InterpolatorType;

    typedef itk::ImageRegistrationMethod<
                                FixedImageType,
                                MovingImageType >           RegistrationType;

    typedef typename itk::WarpImageFilter<
                            MovingImageType,
                            MovingImageType,
                            DeformationFieldType  >         WarperType;

    typedef typename TransformType::SpacingType                      SpacingType;

    typedef typename TransformType::OriginType                       OriginType;

    typedef itk::ResampleImageFilter<
                                MovingImageType,
                                FixedImageType >            ResampleFilterType;

    typedef itk::Image< TPixel, VImageDimension >           OutputImageType;

    // Sample new image with the same image type as the fixed image
    typedef itk::CastImageFilter<
                                FixedImageType,
                                FixedImageType >            CastFilterType;

    typedef itk::Vector< float, VImageDimension >           VectorType;
    typedef itk::Image< VectorType, VImageDimension >       DeformationFieldType;

    typedef itk::BSplineDeformableTransformInitializer <
                                TransformType,
                                FixedImageType >            InitializerType;

    typename InterpolatorType::Pointer   interpolator  = InterpolatorType::New();
    typename RegistrationType::Pointer   registration  = RegistrationType::New();
    typename InitializerType::Pointer    initializer   = InitializerType::New();
    typename TransformType::Pointer      transform     = TransformType::New();
    typename MetricType::Pointer         metric        = MetricType::New();

    metric->SetNumberOfHistogramBins( 24);
    metric->SetNumberOfSpatialSamples(100000);

    typename OptimizerFactory::Pointer optFac = OptimizerFactory::New();
    optFac->SetOptimizerParameters(m_OptimizerParameters);
    optFac->SetNumberOfTransformParameters(transform->GetNumberOfParameters());
    OptimizerType::Pointer optimizer = optFac->GetOptimizer();

    typename FixedImageType::Pointer fixedImage = FixedImageType::New();
    mitk::CastToItkImage(m_ReferenceImage, fixedImage);
    typename FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion();
    typename MovingImageType::Pointer movingImage = itkImage1;

    registration->SetMetric(          metric        );
    registration->SetOptimizer(       optimizer     );
    registration->SetInterpolator(    interpolator  );
    registration->SetFixedImage(      fixedImage    );
    registration->SetMovingImage(     movingImage   );
    registration->SetFixedImageRegion(fixedRegion   );

    initializer->SetTransform(transform);
    initializer->SetImage(fixedImage);
    initializer->SetNumberOfGridNodesInsideTheImage( m_NumberOfGridPoints );
    initializer->InitializeTransform();

    registration->SetTransform( transform );

    const unsigned int numberOfParameters = transform->GetNumberOfParameters();

    typename itk::BSplineDeformableTransform<
                                double,
                                VImageDimension,
                                3 >::ParametersType  parameters;

    parameters.set_size(numberOfParameters);
    parameters.Fill( 0.0 );
    transform->SetParameters( parameters );

    // We now pass the parameters of the current transform as the initial
    // parameters to be used when the registration process starts.
    registration->SetInitialTransformParameters( transform->GetParameters() );
    std::cout << "Intial Parameters = " << std::endl;
    std::cout << transform->GetParameters() << std::endl;

    std::cout << std::endl << "Starting Registration" << std::endl;

    try
    {
      registration->StartRegistration();
    }
    catch( itk::ExceptionObject & err )
    {
      std::cerr << "ExceptionObject caught !" << std::endl;
      std::cerr << err << std::endl;
    }

    typename OptimizerType::ParametersType finalParameters =
                      registration->GetLastTransformParameters();

    std::cout << "Last Transform Parameters" << std::endl;
    std::cout << finalParameters << std::endl;

    transform->SetParameters( finalParameters );

/*
    ResampleFilterType::Pointer       resampler = ResampleFilterType::New();
    resampler->SetTransform(          transform );
    resampler->SetInput(              movingImage );
    resampler->SetSize(               fixedImage->GetLargestPossibleRegion().GetSize() );
    resampler->SetOutputOrigin(       fixedImage->GetOrigin() );
    resampler->SetOutputSpacing(      fixedImage->GetSpacing() );
    resampler->SetOutputDirection(    fixedImage->GetDirection() );
    resampler->SetDefaultPixelValue(  100 );
    resampler->SetInterpolator(       interpolator);
    resampler->Update();*/

    // Generate deformation field
    typename DeformationFieldType::Pointer field = DeformationFieldType::New();
    field->SetRegions( fixedRegion );
    field->SetOrigin( fixedImage->GetOrigin() );
    field->SetSpacing( fixedImage->GetSpacing() );
    field->SetDirection( fixedImage->GetDirection() );
    field->Allocate();

    typedef itk::ImageRegionIterator< DeformationFieldType > FieldIterator;
    FieldIterator fi( field, fixedRegion );

    fi.GoToBegin();

    typename TransformType::InputPointType  fixedPoint;
    typename TransformType::OutputPointType movingPoint;
    typename DeformationFieldType::IndexType index;

    VectorType displacement;

    while( ! fi.IsAtEnd() )
    {
      index = fi.GetIndex();
      field->TransformIndexToPhysicalPoint( index, fixedPoint );
      movingPoint = transform->TransformPoint( fixedPoint );
      displacement = movingPoint - fixedPoint;
      fi.Set( displacement );
      ++fi;
    }

    // Use the deformation field to warp the moving image
    typename WarperType::Pointer warper = WarperType::New();

    warper->SetInput( movingImage );
    warper->SetInterpolator( interpolator );
    warper->SetOutputSpacing( fixedImage->GetSpacing() );
    warper->SetOutputOrigin( fixedImage->GetOrigin() );
    warper->SetDeformationField( field );
    warper->Update();

    typename MovingImageType::Pointer result = warper->GetOutput();

    if(m_UpdateInputImage)
    {
      Image::Pointer outputImage = this->GetOutput();
      mitk::CastToMitkImage( result, outputImage );
    }

    // Save the deformationfield resulting from the registration
    if(m_SaveDeformationField)
    {
      typedef itk::ImageFileWriter< DeformationFieldType >  FieldWriterType;
      typename FieldWriterType::Pointer fieldWriter = FieldWriterType::New();

      fieldWriter->SetInput( field );

      fieldWriter->SetFileName( m_DeformationFileName );
      try
      {
        fieldWriter->Update();
      }
      catch( itk::ExceptionObject & excp )
      {
        std::cerr << "Exception thrown " << std::endl;
        std::cerr << excp << std::endl;
        //return EXIT_FAILURE;
      }
    }

  }
} // end namespace
<commit_msg>FIX (#1927): Changed settings for spacing and origin for the WarpImageFilter.<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2009-05-05 19:02:32 +0200 (Tue, 05 May 2009) $
Version:   $Revision: 17105 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkImageFileWriter.h"
#include "itkWarpImageFilter.h"
#include "itkImageRegionIterator.h"

#include "mitkBSplineRegistration.h"
#include "itkBSplineDeformableTransform.h"
//#include "itkLBFGSOptimizer.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkMattesMutualInformationImageToImageMetric.h"
#include "itkResampleImageFilter.h"
#include "itkImageRegistrationMethod.h"

#include "itkBSplineDeformableTransformInitializer.h"

#include "mitkOptimizerFactory.h"

namespace mitk {

  BSplineRegistration::BSplineRegistration():
    m_Iterations(50),
    m_ResultName("deformedImage.mhd"),
    m_SaveResult(true),
    m_SaveDeformationField(false),
    m_UpdateInputImage(false)
  {

  }

  BSplineRegistration::~BSplineRegistration()
  {
  }

  void BSplineRegistration::SetNumberOfIterations(int iterations)
  {
    m_Iterations = iterations;
  }

  void BSplineRegistration::SetSaveResult(bool saveResult)
  {
    m_SaveResult = saveResult;
  }

  void BSplineRegistration::SetResultFileName(const char* resultName)
  {
    m_ResultName = resultName;
  }

  template < typename TPixel, unsigned int VImageDimension >
    void BSplineRegistration::GenerateData2( itk::Image<TPixel, VImageDimension>* itkImage1)
  {
    std::cout << "start bspline registration" << std::endl;

    // Typedefs
    typedef typename itk::Image< TPixel, VImageDimension >  FixedImageType;
    typedef typename itk::Image< TPixel, VImageDimension >  MovingImageType;

    typedef typename itk::Vector< float, VImageDimension >    VectorPixelType;
    typedef typename itk::Image<  VectorPixelType, VImageDimension > DeformationFieldType;

    typedef itk::BSplineDeformableTransform<
                                double,
                                VImageDimension,
                                3 >                         TransformType;

    typedef typename TransformType::ParametersType          ParametersType;

    //typedef itk::LBFGSOptimizer                             OptimizerType;
    typedef itk::SingleValuedNonLinearOptimizer             OptimizerType;
    typedef itk::MattesMutualInformationImageToImageMetric<
                                FixedImageType,
                                MovingImageType >           MetricType;

    /*typedef itk::MeanSquaresImageToImageMetric<
                                FixedImageType,
                                MovingImageType >           MetricType;*/

    typedef itk::LinearInterpolateImageFunction<
                                MovingImageType,
                                double >                    InterpolatorType;

    typedef itk::ImageRegistrationMethod<
                                FixedImageType,
                                MovingImageType >           RegistrationType;

    typedef typename itk::WarpImageFilter<
                            MovingImageType,
                            MovingImageType,
                            DeformationFieldType  >         WarperType;

    typedef typename TransformType::SpacingType                      SpacingType;

    typedef typename TransformType::OriginType                       OriginType;

    typedef itk::ResampleImageFilter<
                                MovingImageType,
                                FixedImageType >            ResampleFilterType;

    typedef itk::Image< TPixel, VImageDimension >           OutputImageType;

    // Sample new image with the same image type as the fixed image
    typedef itk::CastImageFilter<
                                FixedImageType,
                                FixedImageType >            CastFilterType;

    typedef itk::Vector< float, VImageDimension >           VectorType;
    typedef itk::Image< VectorType, VImageDimension >       DeformationFieldType;

    typedef itk::BSplineDeformableTransformInitializer <
                                TransformType,
                                FixedImageType >            InitializerType;

    typename InterpolatorType::Pointer   interpolator  = InterpolatorType::New();
    typename RegistrationType::Pointer   registration  = RegistrationType::New();
    typename InitializerType::Pointer    initializer   = InitializerType::New();
    typename TransformType::Pointer      transform     = TransformType::New();
    typename MetricType::Pointer         metric        = MetricType::New();

    metric->SetNumberOfHistogramBins( 24);
    metric->SetNumberOfSpatialSamples(100000);

    typename OptimizerFactory::Pointer optFac = OptimizerFactory::New();
    optFac->SetOptimizerParameters(m_OptimizerParameters);
    optFac->SetNumberOfTransformParameters(transform->GetNumberOfParameters());
    OptimizerType::Pointer optimizer = optFac->GetOptimizer();

    typename FixedImageType::Pointer fixedImage = FixedImageType::New();
    mitk::CastToItkImage(m_ReferenceImage, fixedImage);
    typename MovingImageType::Pointer movingImage = itkImage1;
    typename FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion();
    typename MovingImageType::RegionType movingRegion = movingImage->GetBufferedRegion();

    registration->SetMetric(          metric        );
    registration->SetOptimizer(       optimizer     );
    registration->SetInterpolator(    interpolator  );
    registration->SetFixedImage(      fixedImage    );
    registration->SetMovingImage(     movingImage   );
    registration->SetFixedImageRegion(fixedRegion   );

    initializer->SetTransform(transform);
    initializer->SetImage(fixedImage);
    initializer->SetNumberOfGridNodesInsideTheImage( m_NumberOfGridPoints );
    initializer->InitializeTransform();

    registration->SetTransform( transform );

    const unsigned int numberOfParameters = transform->GetNumberOfParameters();

    typename itk::BSplineDeformableTransform<
                                double,
                                VImageDimension,
                                3 >::ParametersType  parameters;

    parameters.set_size(numberOfParameters);
    parameters.Fill( 0.0 );
    transform->SetParameters( parameters );

    // We now pass the parameters of the current transform as the initial
    // parameters to be used when the registration process starts.
    registration->SetInitialTransformParameters( transform->GetParameters() );

    std::cout << "Intial Parameters = " << std::endl;
    std::cout << transform->GetParameters() << std::endl;

    std::cout << std::endl << "Starting Registration" << std::endl;

    try
    {
      registration->StartRegistration();
    }
    catch( itk::ExceptionObject & err )
    {
      std::cerr << "ExceptionObject caught !" << std::endl;
      std::cerr << err << std::endl;
    }

    typename OptimizerType::ParametersType finalParameters =
                      registration->GetLastTransformParameters();

    std::cout << "Last Transform Parameters" << std::endl;
    std::cout << finalParameters << std::endl;

    transform->SetParameters( finalParameters );

/*
    ResampleFilterType::Pointer       resampler = ResampleFilterType::New();
    resampler->SetTransform(          transform );
    resampler->SetInput(              movingImage );
    resampler->SetSize(               fixedImage->GetLargestPossibleRegion().GetSize() );
    resampler->SetOutputOrigin(       fixedImage->GetOrigin() );
    resampler->SetOutputSpacing(      fixedImage->GetSpacing() );
    resampler->SetOutputDirection(    fixedImage->GetDirection() );
    resampler->SetDefaultPixelValue(  100 );
    resampler->SetInterpolator(       interpolator);
    resampler->Update();*/

    // Generate deformation field
    typename DeformationFieldType::Pointer field = DeformationFieldType::New();
    field->SetRegions( movingRegion );
    field->SetOrigin( movingImage->GetOrigin() );
    field->SetSpacing( movingImage->GetSpacing() );
    field->SetDirection( movingImage->GetDirection() );
    field->Allocate();

    typedef itk::ImageRegionIterator< DeformationFieldType > FieldIterator;
    FieldIterator fi( field, movingRegion );
    fi.GoToBegin();

    typename TransformType::InputPointType  fixedPoint;
    typename TransformType::OutputPointType movingPoint;
    typename DeformationFieldType::IndexType index;

    VectorType displacement;

    while( ! fi.IsAtEnd() )
    {
      index = fi.GetIndex();
      field->TransformIndexToPhysicalPoint( index, fixedPoint );
      movingPoint = transform->TransformPoint( fixedPoint );
      displacement = movingPoint - fixedPoint;
      fi.Set( displacement );
      ++fi;
    }

    // Use the deformation field to warp the moving image
    typename WarperType::Pointer warper = WarperType::New();
    warper->SetInput( movingImage );
    warper->SetInterpolator( interpolator );
    warper->SetOutputSpacing( movingImage->GetSpacing() );
    warper->SetOutputOrigin( movingImage->GetOrigin() );
    warper->SetOutputDirection( movingImage->GetDirection() );
    warper->SetDeformationField( field );
    warper->Update();

    typename MovingImageType::Pointer result = warper->GetOutput();

    if(m_UpdateInputImage)
    {
      Image::Pointer outputImage = this->GetOutput();
      mitk::CastToMitkImage( result, outputImage );
    }

    // Save the deformationfield resulting from the registration
    if(m_SaveDeformationField)
    {
      typedef itk::ImageFileWriter< DeformationFieldType >  FieldWriterType;
      typename FieldWriterType::Pointer fieldWriter = FieldWriterType::New();

      fieldWriter->SetInput( field );

      fieldWriter->SetFileName( m_DeformationFileName );
      try
      {
        fieldWriter->Update();
      }
      catch( itk::ExceptionObject & excp )
      {
        std::cerr << "Exception thrown " << std::endl;
        std::cerr << excp << std::endl;
        //return EXIT_FAILURE;
      }
    }

  }
} // end namespace
<|endoftext|>


<commit_before>/**
 *  testApp.cpp is part of ofxXmlDefaultSettings.
 *
 *  Copyright (c) 2012, Paul Vollmer http://www.wrong-entertainment.com
 *  All rights reserved.
 *
 *
 *  The MIT License
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 *  and  associated documentation files  (the "Software"), to deal in the Software without
 *  restriction, including without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 *  BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 *  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 *
 *  @testet_oF          0071
 *  @testet_plattform   MacOs 10.6+
 *                      ??? Win
 *                      ??? Linux
 *  @dependencies       ofxXmlSettings
 *  @contributor(s)     Paul Vollmer <paul.vollmer@fh-potsdam.de>
 *  @modified           2012.09.20
 *  @version            0.1.2b
 */

#include "testApp.h"

//--------------------------------------------------------------
void testApp::setup(){
	// Load our default xml file.
	defXML.load();

	// Get a status message
	cout << "STATUS: " << defXML.statusMessage << endl;

	// and set the openFrameworks core settings from it.
	defXML.setSettings();
	cout << "STATUS: " << defXML.statusMessage << endl;
}

//--------------------------------------------------------------
void testApp::update(){

}

//--------------------------------------------------------------
void testApp::draw(){

}

//--------------------------------------------------------------
void testApp::keyPressed(int key){
	switch (key) {
		case 'f':
			ofToggleFullscreen();
			break;
		default:
			break;
	}
}

//--------------------------------------------------------------
void testApp::exit(){
	// Save the current settings to xml.
	defXML.saveSettings();
	cout << "STATUS: " << defXML.statusMessage << endl;
}
<commit_msg>change comment style<commit_after>/**
 *  testApp.cpp is part of ofxXmlDefaultSettings.
 *
 *  Copyright (c) 2012, Paul Vollmer http://www.wrong-entertainment.com
 *  All rights reserved.
 *
 *
 *  The MIT License
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 *  and  associated documentation files  (the "Software"), to deal in the Software without
 *  restriction, including without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 *  BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 *  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 *
 *  @testet_oF          0071
 *  @testet_plattform   MacOs 10.6+
 *                      ??? Win
 *                      ??? Linux
 *  @dependencies       ofxXmlSettings
 *  @contributor(s)     Paul Vollmer <paul.vollmer@fh-potsdam.de>
 *  @modified           2012.09.20
 *  @version            0.1.2b
 */

#include "testApp.h"

//--------------------------------------------------------------
void testApp::setup(){
	/* Load our default xml file.
	 */
	defXML.load();

	/* Get a status message
	 */
	cout << "STATUS: " << defXML.statusMessage << endl;

	/* and set the openFrameworks core settings from it.
	 */
	defXML.setSettings();
	cout << "STATUS: " << defXML.statusMessage << endl;
}

//--------------------------------------------------------------
void testApp::update(){

}

//--------------------------------------------------------------
void testApp::draw(){

}

//--------------------------------------------------------------
void testApp::keyPressed(int key){
	switch (key) {
		case 'f':
			ofToggleFullscreen();
			break;
		default:
			break;
	}
}

//--------------------------------------------------------------
void testApp::exit(){
	/* Save the current settings to xml.
	 */
	defXML.saveSettings();
	cout << "STATUS: " << defXML.statusMessage << endl;
}
<|endoftext|>


<commit_before>/* mbed Microcontroller Library
 * Copyright (c) 2006-2015 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mbed.h"
#include "ble/BLE.h"
#include "ble-blocktransfer/BlockTransferService.h"
#include "voytalk/Voytalk.h"

/*****************************************************************************/
/* Configuration                                                             */
/*****************************************************************************/

// set device name
const char DEVICE_NAME[] = "Testvoy";

// set TX power
#ifndef CFG_BLE_TX_POWER_LEVEL
#define CFG_BLE_TX_POWER_LEVEL 0
#endif

// control debug output
#if 1
#define DEBUGOUT(...) { printf(__VA_ARGS__); }
#else
#define DEBUGOUT(...) /* nothing */
#endif // DEBUGOUT

/*****************************************************************************/

/* Voytalk short UUID */
const UUID uuid(0xFE8E);

/* Voytalk states */
typedef enum {
    FLAG_CONNECTED      = 0x01,
    FLAG_PROVISIONED    = 0x02,
} flags_t;

static volatile uint8_t state;

/*****************************************************************************/
/* Global variables used by the test app                                     */
/*****************************************************************************/

// BLE_API ble device
BLE ble;

// Transfer large blocks of data on platforms without Fragmentation-And-Recombination
BlockTransferService bts;

// Voytalk handling
VoytalkRouter router(DEVICE_NAME);

// buffer for sending and receiving data
SharedPointer<Block> writeBlock;
uint8_t readBuffer[1000];
BlockStatic readBlock(readBuffer, sizeof(readBuffer));

// wifi parameters
std::string ssid_string;
std::string key_string;

// Compatibility function
void signalReady();

/*****************************************************************************/
/* Functions for handling debug output                                       */
/*****************************************************************************/

/*
    Functions called when BLE device connects and disconnects.
*/
void whenConnected(const Gap::ConnectionCallbackParams_t* params)
{
    (void) params;
    DEBUGOUT("main: Connected: %d %d %d\r\n", params->connectionParams->minConnectionInterval,
                                              params->connectionParams->maxConnectionInterval,
                                              params->connectionParams->slaveLatency);

    // change state in main application
    state |= FLAG_CONNECTED;

    // change state inside Voytalk hub
    router.setStateMask(state);
}

void whenDisconnected(const Gap::DisconnectionCallbackParams_t*)
{
    DEBUGOUT("main: Disconnected!\r\n");
    DEBUGOUT("main: Restarting the advertising process\r\n");

    ble.gap().startAdvertising();

    // change state in main application
    state &= ~FLAG_CONNECTED;

    // change state inside Voytalk hub
    router.setStateMask(state);
}

/*****************************************************************************/
/* BlockTransfer callbacks for sending and receiving data                    */
/*****************************************************************************/

/*
    Function called when signaling client that new data is ready to be read.
*/
void blockServerSendNotification()
{
    DEBUGOUT("main: notify read updated\r\n");
    bts.updateCharacteristicValue((uint8_t*)"", 0);
}

/*
    Function called when device receives a read request over BLE.
*/
SharedPointer<Block> blockServerReadHandler(uint32_t offset)
{
    DEBUGOUT("main: block read\r\n");
    (void) offset;

    return SharedPointer<Block>(new BlockStatic(readBlock));
}

/*
    Function called when data has been written over BLE.
*/
void blockServerWriteHandler(SharedPointer<Block> block)
{
    DEBUGOUT("main: block write\r\n");

    /*
        Process received data, assuming it is CBOR encoded.
        Any output generated will be written to the readBlock.
    */
    router.processCBOR((BlockStatic*) block.get(), &readBlock);

    /*
        If the readBlock length is non-zero it means a reply has been generated.
    */
    if (readBlock.getLength() > 0)
    {
        signalReady();
    }
}

/*****************************************************************************/
/* Voytalk Wifi example                                                      */
/*****************************************************************************/

/*
    Callback function for constructing wifi intent.
*/
void wifiIntentConstruction(VTRequest& req, VTResponse& res)
{
    DEBUGOUT("main: wifi intent construction\r\n");
    /* create intent using generated endpoint and constraint set */
    VTIntent intent("com.arm.connectivity.wifi");
    intent.knownParameters("/networks");
    intent.endpoint("/wifi");

    res.write(intent);
}

void wifiIntentInvocation(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
    DEBUGOUT("main: wifi invocation\r\n");

    VTIntentInvocation invocation(req.getBody());

    /////////////////////////////////////////
    // retrieve parameters
    invocation.getParameters().find("ssid").getString(ssid_string);
    invocation.getParameters().find("key").getString(key_string);

    /////////////////////////////////////////
    // create coda

    // Read ID from invocation. ID is returned in coda response.
    uint32_t invocationID = invocation.getID();

    VTCoda coda(invocationID);
    coda.success(true);
    res.write(coda);
    done(200);

    // change state in main application
    state |= FLAG_PROVISIONED;

    // change state inside Voytalk hub
    router.setStateMask(state);
}

/*****************************************************************************/
/* Reset device example                                                      */
/*****************************************************************************/

void resetIntentConstruction(VTRequest& req, VTResponse& res)
{
    DEBUGOUT("main: reset intent construction\r\n");

    /* create intent using generated endpoint and constraint set */
    VTIntent intent("com.arm.reset");

    res.write(intent);
}
/*
void resetIntentInvocation(VoytalkHub& hub, VoytalkIntentInvocation& object)
{
    DEBUGOUT("main: reset invocation\r\n");

    // print object tree
    object.print();

    /////////////////////////////////////////
    // create coda

    // Read ID from invocation. ID is returned in coda response.
    uint32_t invocationID = object.getID();

    // create coda and pass to Voytalk hub
    VoytalkCoda coda(invocationID, 1);
    hub.processCoda(coda);

    // change state in main application
    state &= ~FLAG_PROVISIONED;

    // change state inside Voytalk hub
    hub.setStateMask(state);
}
*/

/*****************************************************************************/
/* Voytalk complex example                                                   */
/*****************************************************************************/

/*
    Callback functions for the example intent.
*/
void exampleIntentConstruction(VTRequest& req, VTResponse& res)
{
    DEBUGOUT("main: complex example intent construction\r\n");

    /* create intent */
    VTIntent intent("com.arm.examples.complex");

    res.write(intent);
}
/*
void exampleIntentInvocation(VoytalkHub& hub, VoytalkIntentInvocation& object)
{
    DEBUGOUT("main: complex example invocation\r\n");

    // print object tree
    object.print();

    // Read ID from invocation. ID is returned in coda response.
    uint32_t invocationID = object.getID();

    // create coda and pass to Voytalk hub
    VoytalkCoda coda(invocationID, 1);
    hub.processCoda(coda);
}
*/

/*****************************************************************************/
/* Voytalk custom example                                                    */
/*****************************************************************************/

void customIntentConstruction(VTRequest& req, VTResponse& res)
{
    DEBUGOUT("main: custom intent construction\r\n");

    // /*  Define custom constraints.
    //     Note: constraints can be nested.
    // */

    // /* ssid, key are level 0 variables */
    // VoytalkConstraint L0_ssid("Network Name",
    //                           VoytalkConstraint::TypeString,
    //                           "ssid");

    // VoytalkConstraint L0_key("Password",
    //                          VoytalkConstraint::TypeString,
    //                          "key");

    // /* combine level 0 variables */
    // VoytalkConstraint* properties[] = { &L0_ssid,
    //                                     &L0_key };

    // // define level 0
    // VoytalkConstraint constraints("Custom Access",
    //                               properties);

    // /* optional: default values */
    // L0_ssid.setDefaultValue("homehub");

    // /* optional: description fields */
    // L0_ssid.setDescription("The name of the network you want to connect to.");
    // L0_key.setDescription("The password for the network.");

    // constraints.setDescription("The device wants to access your Wifi network.");

    // /* create intent using generated endpoint and constraint set */
    // VTIntent intent("com.arm.examples.custom", constraints);

    // callback(200, intent);
}
/*
void customIntentInvocation(VoytalkHub& hub, VoytalkIntentInvocation& object)
{
    DEBUGOUT("main: custom example invocation\r\n");

    // print object tree
    object.print();

    // Read ID from invocation. ID is returned in coda response.
    uint32_t invocationID = object.getID();

    // create coda and pass to Voytalk hub
    VoytalkCoda coda(invocationID, 1);
    hub.processCoda(coda);
}*/

void networkListResource(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
    DEBUGOUT("listing network resources");

    VoytalkKnownParameters parameters(res, 2);

    parameters.parameter("com.arm.connectivity.wifi", 50)
        .map(2)
            .key("ssid").value("iWifi")
            .key("key").value("supersecurepassword");

    parameters.parameter("com.arm.connectivity.wifi", 20)
        .map(2)
            .key("ssid").value("yoWifi")
            .key("key").value("securepasswordinit");

    done(200);
}

/*****************************************************************************/
/* main                                                                      */
/*****************************************************************************/

void app_start(int, char *[])
{
    /*
        Register Voytalk intents in the hub.

        First parameter is the callback function for intent generation.
        Second is the callback function for when the intent is invoked.
        Third parameter is a bitmap for grouping intents together.
    */

    // Wifi provisioning intent
    router.registerIntent(wifiIntentConstruction,
                          FLAG_CONNECTED | FLAG_PROVISIONED);

    // reset intent
    router.registerIntent(resetIntentConstruction,
                          FLAG_PROVISIONED);

    // custom intent
#if 0
    router.registerIntent(customIntentConstruction,
                         FLAG_CONNECTED | FLAG_PROVISIONED);
#endif

    /*
        Set the current state mask.

        Mask is AND'ed with each intent's bitmap and only intents with non-zero
        results are displayed and can be invoked.
    */
    router.setStateMask(0);

    /*
        Define some resource callbacks
    */

    router.get("/networks", networkListResource);
    router.post("/wifi", wifiIntentInvocation);

    /*************************************************************************/
    /*************************************************************************/
    /* bluetooth le */
    ble.init();

    // status callback functions
    ble.gap().onConnection(whenConnected);
    ble.gap().onDisconnection(whenDisconnected);

    /* construct advertising beacon */
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED|GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, (const uint8_t *) DEVICE_NAME, sizeof(DEVICE_NAME) - 1);
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, uuid.getBaseUUID(), uuid.getLen());
    ble.gap().accumulateAdvertisingPayloadTxPower(CFG_BLE_TX_POWER_LEVEL);

    ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.gap().setAdvertisingInterval(1000); /* 1s; in multiples of 0.625ms. */

    // set TX power
    ble.gap().setTxPower(CFG_BLE_TX_POWER_LEVEL);

    // Apple uses device name instead of beacon name
    ble.gap().setDeviceName((const uint8_t*) DEVICE_NAME);

    /*************************************************************************/
    /*************************************************************************/
    // setup block transfer service

    // add service using ble device, responding to uuid, and without encryption
    bts.init(uuid, SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK);

    // set callback functions for the BlockTransfer service
    bts.setWriteAuthorizationCallback(blockServerWriteHandler);
    bts.setReadAuthorizationCallback(blockServerReadHandler);

    // ble setup complete - start advertising
    ble.gap().startAdvertising();

    printf("Voytalk Test: %s %s\r\n", __DATE__, __TIME__);
}

/*****************************************************************************/
/* Compatibility                                                             */
/*****************************************************************************/

#if defined(YOTTA_MINAR_VERSION_STRING)
/*********************************************************/
/* Build for mbed OS                                     */
/*********************************************************/

void signalReady()
{
    minar::Scheduler::postCallback(blockServerSendNotification);
}

#else
/*********************************************************/
/* Build for mbed Classic                                */
/*********************************************************/

bool sendNotification = false;

void signalReady()
{
    sendNotification = true;
}

int main(void)
{
    app_start(0, NULL);

    for(;;)
    {
        // send notification outside of interrupt context
        if (sendNotification)
        {
            sendNotification = false;
            blockServerSendNotification();
        }

        ble.waitForEvent();
    }
}
#endif

<commit_msg>tidy up examples<commit_after>/* mbed Microcontroller Library
 * Copyright (c) 2006-2015 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mbed.h"
#include "ble/BLE.h"
#include "ble-blocktransfer/BlockTransferService.h"
#include "voytalk/Voytalk.h"

/*****************************************************************************/
/* Configuration                                                             */
/*****************************************************************************/

// set device name
const char DEVICE_NAME[] = "Testoy";

// set TX power
#ifndef CFG_BLE_TX_POWER_LEVEL
#define CFG_BLE_TX_POWER_LEVEL 0
#endif

// control debug output
#if 1
#define DEBUGOUT(...) { printf(__VA_ARGS__); }
#else
#define DEBUGOUT(...) /* nothing */
#endif // DEBUGOUT

/*****************************************************************************/

/* Voytalk short UUID */
const UUID uuid(0xFE8E);

/* Voytalk states */
typedef enum {
    FLAG_CONNECTED      = 0x01,
    FLAG_PROVISIONED    = 0x02,
} flags_t;

static volatile uint8_t state;

/*****************************************************************************/
/* Global variables used by the test app                                     */
/*****************************************************************************/

// BLE_API ble device
BLE ble;

// Transfer large blocks of data on platforms without Fragmentation-And-Recombination
BlockTransferService bts;

// Voytalk handling
VoytalkRouter router(DEVICE_NAME);

// buffer for sending and receiving data
SharedPointer<Block> writeBlock;
uint8_t readBuffer[1000];
BlockStatic readBlock(readBuffer, sizeof(readBuffer));

// wifi parameters
std::string ssid_string;
std::string key_string;

// Compatibility function
void signalReady();

/*****************************************************************************/
/* Functions for handling debug output                                       */
/*****************************************************************************/

/*
    Functions called when BLE device connects and disconnects.
*/
void whenConnected(const Gap::ConnectionCallbackParams_t* params)
{
    (void) params;
    DEBUGOUT("main: Connected: %d %d %d\r\n", params->connectionParams->minConnectionInterval,
                                              params->connectionParams->maxConnectionInterval,
                                              params->connectionParams->slaveLatency);

    // change state in main application
    state |= FLAG_CONNECTED;

    // change state inside Voytalk hub
    router.setStateMask(state);
}

void whenDisconnected(const Gap::DisconnectionCallbackParams_t*)
{
    DEBUGOUT("main: Disconnected!\r\n");
    DEBUGOUT("main: Restarting the advertising process\r\n");

    ble.gap().startAdvertising();

    // change state in main application
    state &= ~FLAG_CONNECTED;

    // change state inside Voytalk hub
    router.setStateMask(state);
}

/*****************************************************************************/
/* BlockTransfer callbacks for sending and receiving data                    */
/*****************************************************************************/

/*
    Function called when signaling client that new data is ready to be read.
*/
void blockServerSendNotification()
{
    DEBUGOUT("main: notify read updated\r\n");
    bts.updateCharacteristicValue((uint8_t*)"", 0);
}

/*
    Function called when device receives a read request over BLE.
*/
SharedPointer<Block> blockServerReadHandler(uint32_t offset)
{
    DEBUGOUT("main: block read\r\n");
    (void) offset;

    return SharedPointer<Block>(new BlockStatic(readBlock));
}

/*
    Function called when data has been written over BLE.
*/
void blockServerWriteHandler(SharedPointer<Block> block)
{
    DEBUGOUT("main: block write\r\n");

    /*
        Process received data, assuming it is CBOR encoded.
        Any output generated will be written to the readBlock.
    */
    router.processCBOR((BlockStatic*) block.get(), &readBlock);

    /*
        If the readBlock length is non-zero it means a reply has been generated.
    */
    if (readBlock.getLength() > 0)
    {
        signalReady();
    }
}

/*****************************************************************************/
/* Voytalk Wifi example                                                      */
/*****************************************************************************/

/*
    Callback function for constructing wifi intent.
*/
void wifiIntentConstruction(VTRequest& req, VTResponse& res)
{
    DEBUGOUT("main: wifi intent construction\r\n");
    /* create intent using generated endpoint and constraint set */
    VTIntent intent("com.arm.connectivity.wifi");
    intent.knownParameters("/networks");
    intent.endpoint("/wifi");

    res.write(intent);
}

void wifiIntentInvocation(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
    DEBUGOUT("main: wifi invocation\r\n");

    VTIntentInvocation invocation(req.getBody());

    /////////////////////////////////////////
    // retrieve parameters
    invocation.getParameters().find("ssid").getString(ssid_string);
    invocation.getParameters().find("key").getString(key_string);

    /////////////////////////////////////////
    // create coda

    // Read ID from invocation. ID is returned in coda response.
    uint32_t invocationID = invocation.getID();

    VTCoda coda(invocationID);
    coda.success(true);
    res.write(coda);
    done(200);

    // change state in main application
    state |= FLAG_PROVISIONED;

    // change state inside Voytalk hub
    router.setStateMask(state);
}

/*****************************************************************************/
/* Reset device example                                                      */
/*****************************************************************************/

void resetIntentConstruction(VTRequest& req, VTResponse& res)
{
    DEBUGOUT("main: reset intent construction\r\n");

    /* create intent using generated endpoint and constraint set */
    VTIntent intent("com.arm.reset");
    intent.endpoint("/reset");
    res.write(intent);
}

void resetIntentInvocation(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
    DEBUGOUT("main: reset invocation\r\n");

    VTIntentInvocation invocation(req.getBody());

    // print object tree
    invocation.getParameters().print();

    ssid_string = "";
    key_string = "";

    // Read ID from invocation. ID is returned in coda response.
    VTCoda coda(invocation.getID());
    coda.success(true);
    res.write(coda);
    done(200);

    // change state in main application
    state &= ~FLAG_PROVISIONED;

    // change state inside Voytalk hub
    router.setStateMask(state);
}

/*****************************************************************************/
/* Voytalk complex example                                                   */
/*****************************************************************************/

/*
    Callback functions for the example intent.
*/
void exampleIntentConstruction(VTRequest& req, VTResponse& res)
{
    DEBUGOUT("main: complex example intent construction\r\n");

    /* create intent */
    VTIntent intent("com.arm.examples.complex");
    intent.endpoint("/examples/complex");

    res.write(intent);
}

/*****************************************************************************/
/* Voytalk custom example                                                    */
/*****************************************************************************/

void customIntentConstruction(VTRequest& req, VTResponse& res)
{
    DEBUGOUT("main: custom intent construction\r\n");
    /* create intent using generated endpoint and constraint set */
    VTIntent intent("com.arm.examples.custom");
    intent.endpoint("/custom");
    intent.constraints()
        .title("Hello!")
        .description("This is the description")
        .addConstraint("test",
            VTConstraint(VTConstraint::TypeString)
                .title("Test")
                .defaultValue("default goes here")
        )
        .addConstraint("test2",
            VTConstraint(VTConstraint::TypeString)
                .title("Other test")
                .defaultValue("default goes here")
        );
    res.write(intent);
}

void printingIntentInvocation(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
    DEBUGOUT("main: invocation receieved \r\n");

    VTIntentInvocation invocation(req.getBody());

    // print object tree
    invocation.getParameters().print();

    VTCoda coda(invocation.getID());
    coda.success(true);
    res.write(coda);
    done(200);
}

void networkListResource(VTRequest& req, VTResponse& res, VoytalkRouter::done_t done)
{
    DEBUGOUT("listing network resources");

    VoytalkKnownParameters parameters(res, 2);

    parameters.parameter("com.arm.connectivity.wifi", 50)
        .map(2)
            .key("ssid").value("iWifi")
            .key("key").value("supersecurepassword");

    parameters.parameter("com.arm.connectivity.wifi", 20)
        .map(2)
            .key("ssid").value("yoWifi")
            .key("key").value("securepasswordinit");

    done(200);
}

/*****************************************************************************/
/* main                                                                      */
/*****************************************************************************/

void app_start(int, char *[])
{
    /*
        Register Voytalk intents in the hub.

        First parameter is the callback function for intent generation.
        Second is the callback function for when the intent is invoked.
        Third parameter is a bitmap for grouping intents together.
    */

    // Wifi provisioning intent
    router.registerIntent(wifiIntentConstruction,
                          FLAG_CONNECTED | FLAG_PROVISIONED);

    // reset intent
    router.registerIntent(resetIntentConstruction,
                          FLAG_PROVISIONED);

    // custom intent
    router.registerIntent(customIntentConstruction,
                         FLAG_CONNECTED | FLAG_PROVISIONED);

    // example intent
    router.registerIntent(exampleIntentConstruction,
                         FLAG_CONNECTED | FLAG_PROVISIONED);

    /*
        Set the current state mask.

        Mask is AND'ed with each intent's bitmap and only intents with non-zero
        results are displayed and can be invoked.
    */
    router.setStateMask(0);

    /*
        Define some resource callbacks
    */

    router.get("/networks", networkListResource);

    router.post("/wifi", wifiIntentInvocation);
    router.post("/reset", resetIntentInvocation);
    router.post("/custom", printingIntentInvocation);
    router.post("/examples/complex", printingIntentInvocation);

    /*************************************************************************/
    /*************************************************************************/
    /* bluetooth le */
    ble.init();

    // status callback functions
    ble.gap().onConnection(whenConnected);
    ble.gap().onDisconnection(whenDisconnected);

    /* construct advertising beacon */
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED|GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, (const uint8_t *) DEVICE_NAME, sizeof(DEVICE_NAME) - 1);
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, uuid.getBaseUUID(), uuid.getLen());
    ble.gap().accumulateAdvertisingPayloadTxPower(CFG_BLE_TX_POWER_LEVEL);

    ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.gap().setAdvertisingInterval(1000); /* 1s; in multiples of 0.625ms. */

    // set TX power
    ble.gap().setTxPower(CFG_BLE_TX_POWER_LEVEL);

    // Apple uses device name instead of beacon name
    ble.gap().setDeviceName((const uint8_t*) DEVICE_NAME);

    /*************************************************************************/
    /*************************************************************************/
    // setup block transfer service

    // add service using ble device, responding to uuid, and without encryption
    bts.init(uuid, SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK);

    // set callback functions for the BlockTransfer service
    bts.setWriteAuthorizationCallback(blockServerWriteHandler);
    bts.setReadAuthorizationCallback(blockServerReadHandler);

    // ble setup complete - start advertising
    ble.gap().startAdvertising();

    printf("Voytalk Test: %s %s\r\n", __DATE__, __TIME__);
}

/*****************************************************************************/
/* Compatibility                                                             */
/*****************************************************************************/

#if defined(YOTTA_MINAR_VERSION_STRING)
/*********************************************************/
/* Build for mbed OS                                     */
/*********************************************************/

void signalReady()
{
    minar::Scheduler::postCallback(blockServerSendNotification);
}

#else
/*********************************************************/
/* Build for mbed Classic                                */
/*********************************************************/

bool sendNotification = false;

void signalReady()
{
    sendNotification = true;
}

int main(void)
{
    app_start(0, NULL);

    for(;;)
    {
        // send notification outside of interrupt context
        if (sendNotification)
        {
            sendNotification = false;
            blockServerSendNotification();
        }

        ble.waitForEvent();
    }
}
#endif

<|endoftext|>