text:
// Copyright © Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root
// for more information.

#ifndef NOVELRT_INPUT_H
#define NOVELRT_INPUT_H

// Input Dependencies
#include "NovelRT/LoggingService.h"
#include "NovelRT/Maths/Maths.h"
#include "NovelRT/Timing/Timestamp.h"
#include <gsl/span>
#include <map>
#include <string>

/**
 * @Brief The input plugin API.
 */
namespace NovelRT::Input
{
    enum class KeyState;
    class IInputDevice;
    class NovelKey;
    struct InputAction;
}

// clang-format off
// Input Types
#include "IInputDevice.h"
#include "KeyState.h"
#include "NovelKey.h"
#include "InputAction.h"
// clang-format on

#endif // NOVELRT_INPUT_H

ext: h

max_stars_repo_name: Shidesu/NovelRT

max_issues_repo_name: Shidesu/NovelRT

max_forks_repo_name: Shidesu/NovelRT


text:
//This takes univariate X, windows X with W, applies the 1D FFT to each frame,
//takes power, transforms with T mat to B cfs, and then compresses power.
//The output Y is power (real-valued), i.e. the FFT squared.
//The size of Y is BxC if dim==0, and RxB if dim==1.

//This is equivalent to stft -> apply_spectrogram_T_mat -> pow_compress.

#include <stdio.h>
#include <float.h>
#include <math.h>
#include <cblas.h>
#include <fftw3.h>

#ifdef __cplusplus
namespace codee {
extern "C" {
#endif

int spectrogram_s (float *Y, const float *X1, const float *X2, const float *X3, const size_t N, const size_t L, const size_t B, const size_t F, const int c0, const float stp, const int mn0, const float p, const float preg);

int spectrogram_s (float *Y, const int iscolmajor, const int R, const int C, const float *X, const int N, const float *W, const int L, const float *H, const int dim, const int c0, const float stp, const int mn0, const int nfft, const float p, const float preg);
int spectrogram_d (double *Y, const int iscolmajor, const int R, const int C, const double *X, const int N, const double *W, const int L, const double *H, const int dim, const int c0, const double stp, const int mn0, const int nfft, const double p, const double preg);

int spectrogram_s (float *Y, const int iscolmajor, const int R, const int C, const float *X, const int N, const float *W, const int L, const float *H, const int dim, const int c0, const float stp, const int mn0, const int nfft, const float p, const float preg)
{
    const float z = 0.0f, o = 1.0f;
    const int F = nfft/2 + 1;  //num non-negative FFT freqs
    const int Lpre = L/2;      //nsamps before center samp
    int ss = c0 - Lpre;        //start samp of current frame
    int r, c, f, n = 0;
    float *X1, *Y1;
    fftwf_plan plan;
    //struct timespec tic, toc;

    //Checks
    if (N<1) { fprintf(stderr,"error in spectrogram_s: N (length X) must be positive\n"); return 1; }
    if (R<1) { fprintf(stderr,"error in spectrogram_s: R (nrows Y) must be positive\n"); return 1; }
    if (C<1) { fprintf(stderr,"error in spectrogram_s: C (ncols Y) must be positive\n"); return 1; }
    if (L<1) { fprintf(stderr,"error in spectrogram_s: L (winlength) must be positive\n"); return 1; }
    if (c0<0) { fprintf(stderr,"error in spectrogram_s: c0 (center samp of 1st frame) must be nonnegative\n"); return 1; }
    if (c0>N-1) { fprintf(stderr,"error in spectrogram_s: c0 (center samp of 1st frame) must be < N (length X)\n"); return 1; }
    if (L>=N) { fprintf(stderr,"error in spectrogram_s: L (winlength) must be < N (length X)\n"); return 1; }
    if (stp<=0.0f) { fprintf(stderr,"error in spectrogram_s: stp (step size) must be positive\n"); return 1; }
    if (nfft<L) { fprintf(stderr,"error in spectrogram_s: nfft must be >= L (winlength)\n"); return 1; }
    if (p!=p || p<0.0f || p>1.0f) { fprintf(stderr,"error in spectrogram_s: p must be in [0.0 1.0]\n"); return 1; }
    if (preg!=preg || preg<0.0f) { fprintf(stderr,"error in spectrogram_s: preg must be nonnegative\n"); return 1; }

    //Initialize fftwf
    X1 = fftwf_alloc_real((size_t)nfft);
    Y1 = fftwf_alloc_real((size_t)nfft);
    plan = fftwf_plan_r2r_1d(nfft,X1,Y1,FFTW_R2HC,FFTW_ESTIMATE);
    if (!plan) { fprintf(stderr,"error in spectrogram_s: problem creating fftw plan\n"); return 1; }
    cblas_scopy(nfft,&z,0,&X1[0],1); //zero-pad

    //clock_gettime(CLOCK_REALTIME,&tic);

    //Initialize Y to preg
    cblas_scopy(R*C,&preg,0,&Y[0],1);

    if (dim==0)
    {
        if (iscolmajor)
        {
            for (c=0; c<C; c++)
            {
                //Window
                ss = (int)(roundf(c*stp)) + c0 - Lpre;
                if (ss<0)
                {
                    cblas_scopy(-ss,&z,0,&X1[0],1);
                    cblas_ssbmv(CblasColMajor,CblasUpper,L+ss,0,1.0f,&W[-ss],1,&X[0],1,0.0f,&X1[-ss],1);
                }
                else if (ss+L<=N)
                {
                    cblas_ssbmv(CblasColMajor,CblasUpper,L,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
                }
                else if (ss<N)
                {
                    cblas_ssbmv(CblasColMajor,CblasUpper,N-ss,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
                    cblas_scopy(L-N+ss,&z,0,&X1[N-ss],1);
                }
                else
                {
                    cblas_scopy(L,&z,0,&X1[0],1);
                }

                //Subtract mean
                if (mn0) { cblas_saxpy(L,-cblas_sdot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }

                //FFT
                fftwf_execute(plan);

                //Power
                for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
                for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }

                //Transform freq scale
                cblas_sgemv(CblasColMajor,CblasNoTrans,R,F,1.0f,&H[0],R,&Y1[0],1,1.0f,&Y[c*R],1);
                //for (b=0; b<R; b++) { Y[b+c*R] += cblas_sdot(f2s[b],&H[b+f1s[b]*R],R,&Y1[f1s[b]],1); }
            }
        }
        else
        {
            for (c=0; c<C; c++)
            {
                //Window
                ss = (int)(roundf(c*stp)) + c0 - Lpre;
                if (ss<0)
                {
                    cblas_scopy(-ss,&z,0,&X1[0],1);
                    cblas_ssbmv(CblasRowMajor,CblasUpper,L+ss,0,1.0f,&W[-ss],1,&X[0],1,0.0f,&X1[-ss],1);
                }
                else if (ss+L<=N)
                {
                    cblas_ssbmv(CblasRowMajor,CblasUpper,L,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
                }
                else if (ss<N)
                {
                    cblas_ssbmv(CblasRowMajor,CblasUpper,N-ss,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
                    cblas_scopy(L-N+ss,&z,0,&X1[N-ss],1);
                }
                else
                {
                    cblas_scopy(L,&z,0,&X1[0],1);
                }

                //Subtract mean
                if (mn0) { cblas_saxpy(L,-cblas_sdot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }

                //FFT
                fftwf_execute(plan);

                //Power
                for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
                for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }

                //Transform freq scale
                cblas_sgemv(CblasRowMajor,CblasNoTrans,R,F,1.0f,&H[0],F,&Y1[0],1,1.0f,&Y[c],C);
            }
        }
    }
    else if (dim==1)
    {
        if (iscolmajor)
        {
            for (r=0; r<R; r++)
            {
                //Window
                ss = (int)(roundf(r*stp)) + c0 - Lpre;
                if (ss<0)
                {
                    cblas_scopy(-ss,&z,0,&X1[0],1);
                    cblas_ssbmv(CblasColMajor,CblasUpper,L+ss,0,1.0f,&W[-ss],1,&X[0],1,0.0f,&X1[-ss],1);
                }
                else if (ss+L<=N)
                {
                    cblas_ssbmv(CblasColMajor,CblasUpper,L,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
                }
                else if (ss<N)
                {
                    cblas_ssbmv(CblasColMajor,CblasUpper,N-ss,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
                    cblas_scopy(L-N+ss,&z,0,&X1[N-ss],1);
                }
                else
                {
                    cblas_scopy(L,&z,0,&X1[0],1);
                }

                //Subtract mean
                if (mn0) { cblas_saxpy(L,-cblas_sdot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }

                //FFT
                fftwf_execute(plan);

                //Power
                for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
                for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }

                //Transform freq scale
                cblas_sgemv(CblasColMajor,CblasNoTrans,C,F,1.0f,&H[0],C,&Y1[0],1,1.0f,&Y[r],R);
            }
        }
        else
        {
            for (r=0; r<R; r++)
            {
                //Window
                ss = (int)(roundf(r*stp)) + c0 - Lpre;
                if (ss<0)
                {
                    cblas_scopy(-ss,&z,0,&X1[0],1);
                    cblas_ssbmv(CblasRowMajor,CblasUpper,L+ss,0,1.0f,&W[-ss],1,&X[0],1,0.0f,&X1[-ss],1);
                }
                else if (ss+L<=N)
                {
                    cblas_ssbmv(CblasRowMajor,CblasUpper,L,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
                }
                else if (ss<N)
                {
                    cblas_ssbmv(CblasRowMajor,CblasUpper,N-ss,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
                    cblas_scopy(L-N+ss,&z,0,&X1[N-ss],1);
                }
                else
                {
                    cblas_scopy(L,&z,0,&X1[0],1);
                }

                //Subtract mean
                if (mn0) { cblas_saxpy(L,-cblas_sdot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }

                //FFT
                fftwf_execute(plan);

                //Power
                for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
                for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }

                //Transform freq scale
                cblas_sgemv(CblasRowMajor,CblasNoTrans,C,F,1.0f,&H[0],F,&Y1[0],1,1.0f,&Y[r*C],1);
            }
        }
    }
    else
    {
        fprintf(stderr,"error in spectrogram_s: dim must be 0 or 1.\n"); return 1;
    }
    //clock_gettime(CLOCK_REALTIME,&toc); fprintf(stderr,"elapsed time = %f ms\n",(toc.tv_sec-tic.tv_sec)*1e3+(toc.tv_nsec-tic.tv_nsec)/1e6);

    //Power compress
    if (1.0f-p>FLT_EPSILON)
    {
        if (p>FLT_EPSILON)
        {
            if (fabsf(p-0.5f)<=FLT_EPSILON) { for (n=0; n<R*C; n++) { Y[n] = sqrtf(Y[n]+preg); } }
            else if (fabsf(p-1.0f/3.0f)<=FLT_EPSILON) { for (n=0; n<R*C; n++) { Y[n] = cbrtf(Y[n]+preg); } }
            else { for (n=0; n<R*C; n++) { Y[n] = powf(Y[n]+preg,p); } }
        }
        else { for (n=0; n<R*C; n++) { Y[n] = logf(Y[n]+preg); } }
    }
    else { for (n=0; n<R*C; n++) { Y[n] += preg; } }

    //Exit
    fftwf_destroy_plan(plan); fftwf_free(X1); fftwf_free(Y1);
    return 0;
}

int spectrogram_d (double *Y, const int iscolmajor, const int R, const int C, const double *X, const int N, const double *W, const int L, const double *H, const int dim, const int c0, const double stp, const int mn0, const int nfft, const double p, const double preg)
{
    const double z = 0.0, o = 1.0;
    const int F = nfft/2 + 1;  //num non-negative FFT freqs
    const int Lpre = L/2;      //nsamps before center samp
    int ss = c0 - Lpre;        //start samp of current frame
    int r, c, f, n = 0;
    double *X1, *Y1;
    fftw_plan plan;

    //Checks
    if (N<1) { fprintf(stderr,"error in spectrogram_d: N (length X) must be positive\n"); return 1; }
    if (R<1) { fprintf(stderr,"error in spectrogram_d: R (nrows Y) must be positive\n"); return 1; }
    if (C<1) { fprintf(stderr,"error in spectrogram_d: C (ncols Y) must be positive\n"); return 1; }
    if (L<1) { fprintf(stderr,"error in spectrogram_d: L (winlength) must be positive\n"); return 1; }
    if (c0<0) { fprintf(stderr,"error in spectrogram_d: c0 (center samp of 1st frame) must be nonnegative\n"); return 1; }
    if (c0>N-1) { fprintf(stderr,"error in spectrogram_d: c0 (center samp of 1st frame) must be < N (length X)\n"); return 1; }
    if (L>=N) { fprintf(stderr,"error in spectrogram_d: L (winlength) must be < N (length X)\n"); return 1; }
    if (stp<=0.0) { fprintf(stderr,"error in spectrogram_d: stp (step size) must be positive\n"); return 1; }
    if (nfft<L) { fprintf(stderr,"error in spectrogram_d: nfft must be >= L (winlength)\n"); return 1; }
    if (p!=p || p<0.0 || p>1.0) { fprintf(stderr,"error in spectrogram_d: p must be in [0.0 1.0]\n"); return 1; }
    if (preg!=preg || preg<0.0) { fprintf(stderr,"error in spectrogram_d: preg must be nonnegative\n"); return 1; }

    //Initialize fftw
    X1 = fftw_alloc_real((size_t)nfft);
    Y1 = fftw_alloc_real((size_t)nfft);
    plan = fftw_plan_r2r_1d(nfft,X1,Y1,FFTW_R2HC,FFTW_ESTIMATE);
    if (!plan) { fprintf(stderr,"error in spectrogram_d: problem creating fftw plan\n"); return 1; }
    cblas_dcopy(nfft,&z,0,&X1[0],1); //zero-pad

    //Initialize Y to preg
    cblas_dcopy(R*C,&preg,0,&Y[0],1);

    if (dim==0)
    {
        if (iscolmajor)
        {
            for (c=0; c<C; c++)
            {
                //Window
                ss = (int)(round(c*stp)) + c0 - Lpre;
                if (ss<0)
                {
                    cblas_dcopy(-ss,&z,0,&X1[0],1);
                    cblas_dsbmv(CblasColMajor,CblasUpper,L+ss,0,1.0,&W[-ss],1,&X[0],1,0.0,&X1[-ss],1);
                }
                else if (ss+L<=N)
                {
                    cblas_dsbmv(CblasColMajor,CblasUpper,L,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
                }
                else if (ss<N)
                {
                    cblas_dsbmv(CblasColMajor,CblasUpper,N-ss,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
                    cblas_dcopy(L-N+ss,&z,0,&X1[N-ss],1);
                }
                else
                {
                    cblas_dcopy(L,&z,0,&X1[0],1);
                }

                //Subtract mean
                if (mn0) { cblas_daxpy(L,-cblas_ddot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }

                //FFT
                fftw_execute(plan);

                //Power
                for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
                for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }

                //Transform freq scale
                cblas_dgemv(CblasColMajor,CblasNoTrans,R,F,1.0,&H[0],R,&Y1[0],1,1.0,&Y[c*R],1);
            }
        }
        else
        {
            for (c=0; c<C; c++)
            {
                //Window
                ss = (int)(round(c*stp)) + c0 - Lpre;
                if (ss<0)
                {
                    cblas_dcopy(-ss,&z,0,&X1[0],1);
                    cblas_dsbmv(CblasRowMajor,CblasUpper,L+ss,0,1.0,&W[-ss],1,&X[0],1,0.0,&X1[-ss],1);
                }
                else if (ss+L<=N)
                {
                    cblas_dsbmv(CblasRowMajor,CblasUpper,L,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
                }
                else if (ss<N)
                {
                    cblas_dsbmv(CblasRowMajor,CblasUpper,N-ss,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
                    cblas_dcopy(L-N+ss,&z,0,&X1[N-ss],1);
                }
                else
                {
                    cblas_dcopy(L,&z,0,&X1[0],1);
                }

                //Subtract mean
                if (mn0) { cblas_daxpy(L,-cblas_ddot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }

                //FFT
                fftw_execute(plan);

                //Power
                for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
                for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }

                //Transform freq scale
                cblas_dgemv(CblasRowMajor,CblasNoTrans,R,F,1.0,&H[0],F,&Y1[0],1,1.0,&Y[c],C);
            }
        }
    }
    else if (dim==1)
    {
        if (iscolmajor)
        {
            for (r=0; r<R; r++)
            {
                //Window
                ss = (int)(round(r*stp)) + c0 - Lpre;
                if (ss<0)
                {
                    cblas_dcopy(-ss,&z,0,&X1[0],1);
                    cblas_dsbmv(CblasColMajor,CblasUpper,L+ss,0,1.0,&W[-ss],1,&X[0],1,0.0,&X1[-ss],1);
                }
                else if (ss+L<=N)
                {
                    cblas_dsbmv(CblasColMajor,CblasUpper,L,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
                }
                else if (ss<N)
                {
                    cblas_dsbmv(CblasColMajor,CblasUpper,N-ss,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
                    cblas_dcopy(L-N+ss,&z,0,&X1[N-ss],1);
                }
                else
                {
                    cblas_dcopy(L,&z,0,&X1[0],1);
                }

                //Subtract mean
                if (mn0) { cblas_daxpy(L,-cblas_ddot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }

                //FFT
                fftw_execute(plan);

                //Power
                for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
                for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }

                //Transform freq scale
                cblas_dgemv(CblasColMajor,CblasNoTrans,C,F,1.0,&H[0],C,&Y1[0],1,1.0,&Y[r],R);
            }
        }
        else
        {
            for (r=0; r<R; r++)
            {
                //Window
                ss = (int)(round(r*stp)) + c0 - Lpre;
                if (ss<0)
                {
                    cblas_dcopy(-ss,&z,0,&X1[0],1);
                    cblas_dsbmv(CblasRowMajor,CblasUpper,L+ss,0,1.0,&W[-ss],1,&X[0],1,0.0,&X1[-ss],1);
                }
                else if (ss+L<=N)
                {
                    cblas_dsbmv(CblasRowMajor,CblasUpper,L,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
                }
                else if (ss<N)
                {
                    cblas_dsbmv(CblasRowMajor,CblasUpper,N-ss,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
                    cblas_dcopy(L-N+ss,&z,0,&X1[N-ss],1);
                }
                else
                {
                    cblas_dcopy(L,&z,0,&X1[0],1);
                }

                //Subtract mean
                if (mn0) { cblas_daxpy(L,-cblas_ddot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }

                //FFT
                fftw_execute(plan);

                //Power
                for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
                for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }

                //Transform freq scale
                cblas_dgemv(CblasRowMajor,CblasNoTrans,C,F,1.0,&H[0],F,&Y1[0],1,1.0,&Y[r*C],1);
            }
        }
    }
    else
    {
        fprintf(stderr,"error in spectrogram_d: dim must be 0 or 1.\n"); return 1;
    }

    //Power compress
    if (1.0-p>DBL_EPSILON)
    {
        if (p>DBL_EPSILON)
        {
            if (fabs(p-0.5)<=DBL_EPSILON) { for (n=0; n<R*C; n++) { Y[n] = sqrt(Y[n]+preg); } }
            else if (fabs(p-1.0/3.0)<=DBL_EPSILON) { for (n=0; n<R*C; n++) { Y[n] = cbrt(Y[n]+preg); } }
            else { for (n=0; n<R*C; n++) { Y[n] = pow(Y[n]+preg,p); } }
        }
        else { for (n=0; n<R*C; n++) { Y[n] = log(Y[n]+preg); } }
    }
    else { for (n=0; n<R*C; n++) { Y[n] += preg; } }

    //Exit
    fftw_destroy_plan(plan); fftw_free(X1); fftw_free(Y1);
    return 0;
}

#ifdef __cplusplus
}
}
#endif

// //Get Hb (banded H) //this worked to get banded matrix storage (but was slower!):
// if (!(Hb=(float *)calloc((size_t)((kl+ku+1)*B),sizeof(float)))) { fprintf(stderr,"error in spectrogram_s: problem with calloc for Hb. "); perror("calloc"); return 1; }
// if (iscolmajor)
// {
//     for (r=0; r<kl+1+ku; r++)
//     {
//         if (r<ku) { b = 0; f = ku - r; }
//         else { b = r - ku; f = 0; }
//         while (b<B && f<F) { Hb[r+f*(kl+1+ku)] = H[b+f*B]; b++; f++; }
//     }
// }
// else
// {
//     for (c=0; c<kl+1+ku; c++)
//     {
//         if (c<kl) { b = kl - c; f = 0; }
//         else { b = 0; f = c - kl; }
//         while (b<B && f<F) { Hb[c+b*(kl+1+ku)] = H[f+b*F]; b++; f++; }
//     }
// }
// ...
// cblas_sgbmv(CblasRowMajor,CblasNoTrans,B,F,kl,ku,1.0f,&Hb[0],kl+ku+1,&Y1[0],1,1.0f,&Y[c],C);

ext: c


text:
#ifndef COMMAND_UTILS_INCLUDE
#define COMMAND_UTILS_INCLUDE

#include <limits>
#include <string>
#include <vector>

#include <gsl/string_span>

#include "tmpFile.h"

namespace execHelper {
namespace test {
namespace baseUtils {
using ConfigFile = TmpFile;

const gsl::czstring<> EXEC_HELPER_BINARY = "exec-helper";
const gsl::czstring<> COMMAND_KEY = "commands";
const gsl::czstring<> COMMAND_LINE_COMMAND_KEY = "command-line-command";
const gsl::czstring<> COMMAND_LINE_COMMAND_LINE_KEY = "command-line";

using ReturnCode = int32_t;
static const ReturnCode SUCCESS = EXIT_SUCCESS;
static const ReturnCode RUNTIME_ERROR = std::numeric_limits<ReturnCode>::max();
} // namespace baseUtils
} // namespace test
} // namespace execHelper

#endif /* COMMAND_UTILS_INCLUDE */

max_stars_repo_name: exec-helper/source

max_issues_repo_name: exec-helper/source

max_forks_repo_name: exec-helper/source


text:
/* integration/qmomof.c
 *
 * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>

static void
compute_moments (double par, double * cheb);

static int
dgtsl (size_t n, double *c, double *d, double *e, double *b);

gsl_integration_qawo_table *
gsl_integration_qawo_table_alloc (double omega, double L,
                                  enum gsl_integration_qawo_enum sine,
                                  size_t n)
{
  gsl_integration_qawo_table *t;
  double * chebmo;

  if (n == 0)
    {
      GSL_ERROR_VAL ("table length n must be positive integer",
                        GSL_EDOM, 0);
    }

  t = (gsl_integration_qawo_table *)
    malloc (sizeof (gsl_integration_qawo_table));

  if (t == 0)
    {
      GSL_ERROR_VAL ("failed to allocate space for qawo_table struct",
                        GSL_ENOMEM, 0);
    }

  chebmo = (double *)  malloc (25 * n * sizeof (double));

  if (chebmo == 0)
    {
      free (t);
      GSL_ERROR_VAL ("failed to allocate space for chebmo block",
                        GSL_ENOMEM, 0);
    }

  t->n = n;
  t->sine = sine;
  t->omega = omega;
  t->L = L;
  t->par = 0.5 * omega * L;
  t->chebmo = chebmo;

  /* precompute the moments */

  {
    size_t i;
    double scale = 1.0;

    for (i = 0 ; i < t->n; i++)
      {
        compute_moments (t->par * scale, t->chebmo + 25*i);
        scale *= 0.5;
      }
  }

  return t;
}

int
gsl_integration_qawo_table_set (gsl_integration_qawo_table * t,
                                    double omega, double L,
                                    enum gsl_integration_qawo_enum sine)
{
  t->omega = omega;
  t->sine = sine;
  t->L = L;
  t->par = 0.5 * omega * L;

  /* recompute the moments */

  {
    size_t i;
    double scale = 1.0;

    for (i = 0 ; i < t->n; i++)
      {
        compute_moments (t->par * scale, t->chebmo + 25*i);
        scale *= 0.5;
      }
  }

  return GSL_SUCCESS;
}

int
gsl_integration_qawo_table_set_length (gsl_integration_qawo_table * t,
                                           double L)
{
  /* return immediately if the length is the same as the old length */

  if (L == t->L)
    return GSL_SUCCESS;

  /* otherwise reset the table and compute the new parameters */

  t->L = L;
  t->par = 0.5 * t->omega * L;

  /* recompute the moments */

  {
    size_t i;
    double scale = 1.0;

    for (i = 0 ; i < t->n; i++)
      {
        compute_moments (t->par * scale, t->chebmo + 25*i);
        scale *= 0.5;
      }
  }

  return GSL_SUCCESS;
}

void
gsl_integration_qawo_table_free (gsl_integration_qawo_table * t)
{
  RETURN_IF_NULL (t);
  free (t->chebmo);
  free (t);
}

static void
compute_moments (double par, double *chebmo)
{
  double v[28], d[25], d1[25], d2[25];

  const size_t noeq = 25;

  const double par2 = par * par;
  const double par4 = par2 * par2;
  const double par22 = par2 + 2.0;

  const double sinpar = sin (par);
  const double cospar = cos (par);

  size_t i;

  /* compute the chebyschev moments with respect to cosine */

  double ac = 8 * cospar;
  double as = 24 * par * sinpar;

  v[0] = 2 * sinpar / par;
  v[1] = (8 * cospar + (2 * par2 - 8) * sinpar / par) / par2;
  v[2] = (32 * (par2 - 12) * cospar
          + (2 * ((par2 - 80) * par2 + 192) * sinpar) / par) / par4;

  if (fabs (par) <= 24)
    {
      /* compute the moments as the solution of a boundary value
         problem using the asyptotic expansion as an endpoint */

      double an2, ass, asap;
      double an = 6;
      size_t k;

      for (k = 0; k < noeq - 1; k++)
        {
          an2 = an * an;
          d[k] = -2 * (an2 - 4) * (par22 - 2 * an2);
          d2[k] = (an - 1) * (an - 2) * par2;
          d1[k + 1] = (an + 3) * (an + 4) * par2;
          v[k + 3] = as - (an2 - 4) * ac;
          an = an + 2.0;
        }

      an2 = an * an;

      d[noeq - 1] = -2 * (an2 - 4) * (par22 - 2 * an2);
      v[noeq + 2] = as - (an2 - 4) * ac;
      v[3] = v[3] - 56 * par2 * v[2];

      ass = par * sinpar;
      asap = (((((210 * par2 - 1) * cospar - (105 * par2 - 63) * ass) / an2
                - (1 - 15 * par2) * cospar + 15 * ass) / an2
               - cospar + 3 * ass) / an2
              - cospar) / an2;
      v[noeq + 2] = v[noeq + 2] - 2 * asap * par2 * (an - 1) * (an - 2);

      dgtsl (noeq, d1, d, d2, v + 3);

    }
  else
    {
      /* compute the moments by forward recursion */
      size_t k;
      double an = 4;

      for (k = 3; k < 13; k++)
        {
          double an2 = an * an;
          v[k] = ((an2 - 4) * (2 * (par22 - 2 * an2) * v[k - 1] - ac)
                  + as - par2 * (an + 1) * (an + 2) * v[k - 2])
            / (par2 * (an - 1) * (an - 2));
          an = an + 2.0;
        }
    }

  for (i = 0; i < 13; i++)
    {
      chebmo[2 * i] = v[i];
    }

  /* compute the chebyschev moments with respect to sine */

  v[0] = 2 * (sinpar - par * cospar) / par2;
  v[1] = (18 - 48 / par2) * sinpar / par2 + (-2 + 48 / par2) * cospar / par;

  ac = -24 * par * cospar;
  as = -8 * sinpar;

  if (fabs (par) <= 24)
    {
      /* compute the moments as the solution of a boundary value
         problem using the asyptotic expansion as an endpoint */

      size_t k;
      double an2, ass, asap;
      double an = 5;

      for (k = 0; k < noeq - 1; k++)
        {
          an2 = an * an;
          d[k] = -2 * (an2 - 4) * (par22 - 2 * an2);
          d2[k] = (an - 1) * (an - 2) * par2;
          d1[k + 1] = (an + 3) * (an + 4) * par2;
          v[k + 2] = ac + (an2 - 4) * as;
          an = an + 2.0;
        }

      an2 = an * an;

      d[noeq - 1] = -2 * (an2 - 4) * (par22 - 2 * an2);
      v[noeq + 1] = ac + (an2 - 4) * as;
      v[2] = v[2] - 42 * par2 * v[1];

      ass = par * cospar;
      asap = (((((105 * par2 - 63) * ass - (210 * par2 - 1) * sinpar) / an2
                + (15 * par2 - 1) * sinpar
                - 15 * ass) / an2 - sinpar - 3 * ass) / an2 - sinpar) / an2;
      v[noeq + 1] = v[noeq + 1] - 2 * asap * par2 * (an - 1) * (an - 2);

      dgtsl (noeq, d1, d, d2, v + 2);

    }
  else
    {
      /* compute the moments by forward recursion */
      size_t k;
      double an = 3;
      for (k = 2; k < 12; k++)
        {
          double an2 = an * an;
          v[k] = ((an2 - 4) * (2 * (par22 - 2 * an2) * v[k - 1] + as)
                  + ac - par2 * (an + 1) * (an + 2) * v[k - 2])
            / (par2 * (an - 1) * (an - 2));
          an = an + 2.0;
        }
    }

  for (i = 0; i < 12; i++)
    {
      chebmo[2 * i + 1] = v[i];
    }

}

static int
dgtsl (size_t n, double *c, double *d, double *e, double *b)
{
  /* solves a tridiagonal matrix A x = b

     c[1 .. n - 1]   subdiagonal of the matrix A
     d[0 .. n - 1]   diagonal of the matrix A
     e[0 .. n - 2]   superdiagonal of the matrix A

     b[0 .. n - 1]   right hand side, replaced by the solution vector x */

  size_t k;

  c[0] = d[0];

  if (n == 0)
    {
      return GSL_SUCCESS;
    }

  if (n == 1)
    {
      b[0] = b[0] / d[0] ;
      return GSL_SUCCESS;
    }

  d[0] = e[0];
  e[0] = 0;
  e[n - 1] = 0;

  for (k = 0; k < n - 1; k++)
    {
      size_t k1 = k + 1;

      if (fabs (c[k1]) >= fabs (c[k]))
        {
          {
            double t = c[k1];
            c[k1] = c[k];
            c[k] = t;
          };
          {
            double t = d[k1];
            d[k1] = d[k];
            d[k] = t;
          };
          {
            double t = e[k1];
            e[k1] = e[k];
            e[k] = t;
          };
          {
            double t = b[k1];
            b[k1] = b[k];
            b[k] = t;
          };
        }

      if (c[k] == 0)
        {
          return GSL_FAILURE ;
        }

      {
        double t = -c[k1] / c[k];

        c[k1] = d[k1] + t * d[k];
        d[k1] = e[k1] + t * e[k];
        e[k1] = 0;
        b[k1] = b[k1] + t * b[k];
      }

    }

  if (c[n - 1] == 0)
    {
      return GSL_FAILURE;
    }

  b[n - 1] = b[n - 1] / c[n - 1];

  b[n - 2] = (b[n - 2] - d[n - 2] * b[n - 1]) / c[n - 2];

  for (k = n ; k > 2; k--)
    {
      size_t kb = k - 3;
      b[kb] = (b[kb] - d[kb] * b[kb + 1] - e[kb] * b[kb + 2]) / c[kb];
    }

  return GSL_SUCCESS;
}

max_stars_repo_name: ielomariala/Hex-Game

max_issues_repo_name: Brian-ning/HMNE

max_forks_repo_name: Brian-ning/HMNE


text:
/* err/env.c
 *
 * Copyright (C) 2001, 2007 Brian Gough
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>

#define STR_EQ(x,y) (strcmp((x),(y)) == 0)

void
gsl_err_env_setup (void)
{
  const char * p = getenv("GSL_ERROR_MODE") ;

  if (p == 0)  /* GSL_ERROR_MODE environment variable is not set */
    return ;

  if (*p == '\0') /* GSL_ERROR_MODE environment variable is empty */
    return ;

  printf("GSL_ERROR_MODE=\"") ;

  if (STR_EQ(p, "abort"))
    {
      gsl_set_error_handler (NULL);
      printf("abort") ;
    }

  printf("\"\n") ;
}

max_stars_repo_name: zzpwahaha/Chimera-Control-Trim

max_issues_repo_name: zzpwahaha/Chimera-Control-Trim

max_forks_repo_name: zzpwahaha/Chimera-Control-Trim


text:
/* multiroots/fdfsolver.c
 *
 * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_multiroots.h>

gsl_multiroot_fdfsolver *
gsl_multiroot_fdfsolver_alloc (const gsl_multiroot_fdfsolver_type * T,
                                       size_t n)
{
  int status;

  gsl_multiroot_fdfsolver * s;

  s = (gsl_multiroot_fdfsolver *) malloc (sizeof (gsl_multiroot_fdfsolver));

  if (s == 0)
    {
      GSL_ERROR_VAL ("failed to allocate space for multiroot solver struct",
                        GSL_ENOMEM, 0);
    }

  s->x = gsl_vector_calloc (n);

  if (s->x == 0)
    {
      free (s);
      GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
    }

  s->f = gsl_vector_calloc (n);

  if (s->f == 0)
    {
      gsl_vector_free (s->x);
      free (s);
      GSL_ERROR_VAL ("failed to allocate space for f", GSL_ENOMEM, 0);
    }

  s->J = gsl_matrix_calloc (n,n);

  if (s->J == 0)
    {
      gsl_vector_free (s->x);
      gsl_vector_free (s->f);
      free (s);
      GSL_ERROR_VAL ("failed to allocate space for g", GSL_ENOMEM, 0);
    }

  s->dx = gsl_vector_calloc (n);

  if (s->dx == 0)
    {
      gsl_matrix_free (s->J);
      gsl_vector_free (s->x);
      gsl_vector_free (s->f);
      free (s);
      GSL_ERROR_VAL ("failed to allocate space for dx", GSL_ENOMEM, 0);
    }

  s->state = malloc (T->size);

  if (s->state == 0)
    {
      gsl_vector_free (s->dx);
      gsl_vector_free (s->x);
      gsl_vector_free (s->f);
      gsl_matrix_free (s->J);
      free (s);         /* exception in constructor, avoid memory leak */

      GSL_ERROR_VAL ("failed to allocate space for multiroot solver state",
                        GSL_ENOMEM, 0);
    }

  s->type = T ;

  status = (s->type->alloc)(s->state, n);

  if (status != GSL_SUCCESS)
    {
      free (s->state);
      gsl_vector_free (s->dx);
      gsl_vector_free (s->x);
      gsl_vector_free (s->f);
      gsl_matrix_free (s->J);
      free (s);         /* exception in constructor, avoid memory leak */

      GSL_ERROR_VAL ("failed to set solver", status, 0);
    }

  s->fdf = NULL;

  return s;
}

int
gsl_multiroot_fdfsolver_set (gsl_multiroot_fdfsolver * s,
                             gsl_multiroot_function_fdf * f,
                             const gsl_vector * x)
{
  if (s->x->size != f->n)
    {
      GSL_ERROR ("function incompatible with solver size", GSL_EBADLEN);
    }

  if (x->size != f->n)
    {
      GSL_ERROR ("vector length not compatible with function", GSL_EBADLEN);
    }

  s->fdf = f;
  gsl_vector_memcpy(s->x,x);

  return (s->type->set) (s->state, s->fdf, s->x, s->f, s->J, s->dx);
}

int
gsl_multiroot_fdfsolver_iterate (gsl_multiroot_fdfsolver * s)
{
  return (s->type->iterate) (s->state, s->fdf, s->x, s->f, s->J, s->dx);
}

void
gsl_multiroot_fdfsolver_free (gsl_multiroot_fdfsolver * s)
{
  RETURN_IF_NULL (s);
  (s->type->free) (s->state);
  free (s->state);
  gsl_vector_free (s->dx);
  gsl_vector_free (s->x);
  gsl_vector_free (s->f);
  gsl_matrix_free (s->J);
  free (s);
}

const char *
gsl_multiroot_fdfsolver_name (const gsl_multiroot_fdfsolver * s)
{
  return s->type->name;
}

gsl_vector *
gsl_multiroot_fdfsolver_root (const gsl_multiroot_fdfsolver * s)
{
  return s->x;
}

gsl_vector *
gsl_multiroot_fdfsolver_dx (const gsl_multiroot_fdfsolver * s)
{
  return s->dx;
}

gsl_vector *
gsl_multiroot_fdfsolver_f (const gsl_multiroot_fdfsolver * s)
{
  return s->f;
}

max_stars_repo_licenses: Net-SNMP Xnet

max_issues_repo_licenses: Net-SNMP Xnet

max_forks_repo_licenses: Net-SNMP Xnet


text:
#pragma once

#include "schedule.h"
#include <gsl/gsl-lite.hpp>
#include <range/v3/view/span.hpp>
#include <vector>

namespace angonoka {
struct Configuration;
} // namespace angonoka

namespace angonoka::stun {
using ranges::span;

/**
    Cache-friendly container of views into an array of ints.
*/
class Vector2D {
public:
    /**
        Default constructor.
    */
    Vector2D() noexcept;

    /**
        Constructor.

        @param data     Array of ints
        @param spans    Array of spans
    */
    Vector2D(
        std::vector<int16>&& data,
        std::vector<span<int16>>&& spans) noexcept;

    /**
        Construct from an array of span sizes.

        @param data     Array of ints
        @param sizes    Array of span sizes
    */
    Vector2D(
        std::vector<int16>&& data,
        span<const int16> sizes) noexcept;

    Vector2D(const Vector2D& other);
    Vector2D& operator=(const Vector2D& other);
    Vector2D(Vector2D&& other) noexcept;
    Vector2D& operator=(Vector2D&& other) noexcept;
    ~Vector2D() noexcept;

    /**
        Get a span by index.

        @param index Span index

        @return A span of ints.
    */
    template <typename T> decltype(auto) operator[](T&& index) const
    {
        Expects(!spans.empty());
        return spans[std::forward<T>(index)];
    }

    /**
        Clear the contents of the container.
    */
    void clear() noexcept;

    /**
        Get size of the container.

        @return Size of the container.
    */
    [[nodiscard]] std::size_t size() const noexcept;

    /**
        Check if the container is empty.

        @return True if the container is empty.
    */
    [[nodiscard]] bool empty() const noexcept;

private:
    std::vector<int16> data;
    std::vector<span<int16>> spans;
};

/**
    General, read-only information about the schedule.

    @var agent_performance      Agent's speed multipliers
    @var task_duration          Task durations in seconds
    @var available_agents       Which agents can perform each task
    @var dependencies           Task's dependent sub-tasks
    @var duration_multiplier    Multiply the makespan by this value
                                to get the duration in seconds
*/
struct ScheduleParams {
    std::vector<float> agent_performance;
    std::vector<float> task_duration;
    Vector2D available_agents;
    Vector2D dependencies;
    float duration_multiplier;
};

/**
    Construct a valid but naive schedule.

    @param ScheduleParams An instance of ScheduleParams

    @return A valid schedule
*/
std::vector<ScheduleItem>
initial_schedule(const ScheduleParams& params);

/**
    Construct ScheduleParams from Configuration.

    @param config An instance of Configuration

    @return ScheduleParams
*/
ScheduleParams to_schedule_params(const Configuration& config);
} // namespace angonoka::stun

max_stars_repo_name: coffee-lord/angonoka

max_issues_repo_name: coffee-lord/angonoka

max_forks_repo_name: coffee-lord/angonoka


text:
/* FacSexNe.c

Simulation of tracking neutral mutation under facultative sex
To calculate Ne under different scenarios
Code based on that used in Agrawal and Hartfield 2016 (https://github.com/MattHartfield/BalSelSims).

Simulation uses routines found with the GNU Scientific Library (GSL)
(http://www.gnu.org/software/gsl/)
Since GSL is distributed under the GNU General Public License
(http://www.gnu.org/copyleft/gpl.html), you must download it
separately from this file.

Run by executing:
./FacSexNe N sex gc reps
Where:
- N is the population size
- sex is the frequency of sex (a value between 0 = obligate asex, and 1 = obligate sex)
- gc is the frequency of mitotic gene conversion
- reps is how many times to introduce linked neutral allele

*/

/* Preprocessor statements */
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stddef.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>

/* Function prototypes */
void neutinit(double *geninit, unsigned int N);
void reproduction(double *geninit, double sex);
void gconv(double *geninit, double gc);
double ncheck(double *geninit);

/* Main program */
int main(int argc, char *argv[]){
	unsigned int N = 0;				/* Population size */
	unsigned int g, i; 				/* Counters. Reps counter, geno counter */
	unsigned int reps = 0;			/* Length of simulation (no. of introductions of neutral site) */
	double sex = 0;					/* Frequency of sexual reproduction */
	double gc = 0;					/* Frequency of gene conversion */
	double Acheck = 0;				/* Frequency of derived neutral allele (A) after each reproduction */
	double Hsum = 0;				/* Summed heterozygosity over transit time of neutral allele */
	char Hout[128];					/* String to hold filename in */
	FILE *ofp_hs = NULL;			/* Pointer for results output */

	/* GSL random number definitions */
	const gsl_rng_type * T;
	gsl_rng * r;

	/* This reads in data from command line. */
	if(argc != 5){
		fprintf(stderr,"Invalid number of input values.\n");
		exit(1);
	}
	N = atoi(argv[1]);
	sex = strtod(argv[2],NULL);
	gc = strtod(argv[3],NULL);
	reps = strtod(argv[4],NULL);

	/* Arrays definition and memory assignment */
	double *genotype = calloc(3,sizeof(double));				/* Genotype frequencies */
	unsigned int *gensamp = calloc(3,sizeof(unsigned int));		/* New population samples */

	/* create a generator chosen by the
    environment variable GSL_RNG_TYPE */

	gsl_rng_env_setup();
	if (!getenv("GSL_RNG_SEED")) gsl_rng_default_seed = time(0);
	T = gsl_rng_default;
	r = gsl_rng_alloc(T);

	/* Setting up neutral genotype */
	neutinit(genotype,N);

	/* Reintroducing neutral genotype, resetting hap sum */
    Acheck = ncheck(genotype);
    Hsum = Acheck*(1.0-Acheck);

    /* Introduce and track neutral mutations 'reps' times */
    g = 0;
    while(g < reps){

    	/* Reproduction routine */
    	reproduction(genotype,sex);

    	/* Gene conversion routine */
       	gconv(genotype,gc);

    	/* Sampling based on new frequencies */
       	gsl_ran_multinomial(r,3,N,genotype,gensamp);
       	for(i = 0; i < 3; i++){
       		*(genotype + i) = (*(gensamp + i))/(1.0*N);
       	}

       	/* Checking state of haplotypes: if A fixed reset so can start fresh next time */
		Acheck = ncheck(genotype);
		Hsum += Acheck*(1.0-Acheck);

       	if(Acheck == 0 || Acheck == 1){
       		sprintf(Hout,"/scratch/mhartfield/CC_FSC_Ne/temp_s%.8lf_gc%.8lf.out",sex,gc);
       		if(g != 0){
				ofp_hs = fopen(Hout,"a");
			}else if(g == 0){
				ofp_hs = fopen(Hout,"w");
			}
			fprintf(ofp_hs,"%.10lf\n",Hsum);
			fclose(ofp_hs);
       		g++;

     		/* Reintroducing neutral genotype, resetting hap sum */
	    	neutinit(genotype,N);
			Acheck = ncheck(genotype);
       		Hsum = Acheck*(1-Acheck);
       	}

	}	/* End of simulation */

	/* Freeing memory and wrapping up */
 	gsl_rng_free(r);
 	free(gensamp);
	free(genotype);
	return 0;
}

/* Setting up neutral polymorphism routine */
void neutinit(double *geninit, unsigned int N){
	*(geninit + 0) = 1 - 1/(1.0*N);
	*(geninit + 1) = 1/(1.0*N);
	*(geninit + 2) = 0;
}	/* End of neutral setup routine */

/* Reproduction routine */
void reproduction(double *geninit, double sex){
	/* Fed-in genotype frequencies (for ease of programming) */
	double gaas, gAas, gAAs;
	/* Genotype frequencies after sex */
	double gaaSX, gAaSX, gAASX;
	/* Genotype frequencies after asex */
	double gaaAS, gAaAS, gAAAS;

	/* Initial definition of genotypes */
	gaas = *(geninit + 0);
	gAas = *(geninit + 1);
	gAAs = *(geninit + 2);

	/* Change in frequencies due to sex */
	gaaSX = sex*(gaas + gAas/2.0)*(gaas + gAas/2.0);
	gAaSX = sex*2.0*(gaas + gAas/2.0)*(gAAs + gAas/2.0);
	gAASX = sex*(gAAs + gAas/2.0)*(gAAs + gAas/2.0);

	/* Change in frequencies due to asex */
	gaaAS = gaas*(1 - sex);
	gAaAS = gAas*(1 - sex);
	gAAAS = gAAs*(1 - sex);

	/* Combining to give overall frequency change following reproduction */
	*(geninit + 0) = gaaAS + gaaSX;
	*(geninit + 1) = gAaAS + gAaSX;
	*(geninit + 2) = gAAAS + gAASX;

}	/* End of reproduction routine */

/* Gene conversion routine */
void gconv(double *geninit, double gc){

	/* Fed-in genotype frequencies (for ease of programming) */
	double gaar, gAar, gAAr;
	/* Frequencies after gene conversion */
	double gaagc, gAagc, gAAgc;

	/* Initial definition of genotypes */
	gaar = *(geninit + 0);
	gAar = *(geninit + 1);
	gAAr = *(geninit + 2);

	/* Gene conversion equations */
	gaagc = gaar + gAar*gc/2.0;
	gAagc = gAar*(1.0-gc);
	gAAgc = gAAr + gAar*gc/2.0;

	/* Output */
	*(geninit + 0) = gaagc;
	*(geninit + 1) = gAagc;
	*(geninit + 2) = gAAgc;

}	/* End of gene conversion routine */

/* Has neutral allele fixed or not? Measuring its frequency */
double ncheck(double *geninit){
	/* Fed-in genotype frequencies (for ease of programming) */
	double gAas, gAAs;
	double Atot = 0.0;        /* Total frequency of A */

	/* Initial definition of genotypes */
	gAas = *(geninit + 1);
	gAAs = *(geninit + 2);

	/* Checking frequency of A */
	Atot = gAAs + gAas/2.0;
	return Atot;

}	/* End of neutral check routine */

/* End of program */

max_stars_repo_name: MattHartfield/FacSexNe

max_issues_repo_name: MattHartfield/FacSexNe

max_forks_repo_name: MattHartfield/FacSexNe


text:
/* sum/gsl_sum.h
 *
 * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

/* Author:  G. Jungman */

#ifndef __GSL_SUM_H__
#define __GSL_SUM_H__

#include <stdlib.h>
#include <gsl/gsl_types.h>

#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS          /* empty */
# define __END_DECLS            /* empty */
#endif

__BEGIN_DECLS

/*  Workspace for Levin U Transform with error estimation,
 *
 *   size        = number of terms the workspace can handle
 *   sum_plain   = simple sum of series
 *   q_num       = backward diagonal of numerator; length = size
 *   q_den       = backward diagonal of denominator; length = size
 *   dq_num      = table of numerator derivatives; length = size**2
 *   dq_den      = table of denominator derivatives; length = size**2
 *   dsum        = derivative of sum wrt term i; length = size
 */

typedef struct
{
  size_t size;
  size_t i;                     /* position in array */
  size_t terms_used;            /* number of calls */
  double sum_plain;
  double *q_num;
  double *q_den;
  double *dq_num;
  double *dq_den;
  double *dsum;
}
gsl_sum_levin_u_workspace;

GSL_EXPORT gsl_sum_levin_u_workspace *gsl_sum_levin_u_alloc (size_t n);
GSL_EXPORT void gsl_sum_levin_u_free (gsl_sum_levin_u_workspace * w);

/* Basic Levin-u acceleration method.
 *
 *   array       = array of series elements
 *   n           = size of array
 *   sum_accel   = result of summation acceleration
 *   err         = estimated error
 *
 * See [Fessler et al., ACM TOMS 9, 346 (1983) and TOMS-602]
 */

GSL_EXPORT int gsl_sum_levin_u_accel (const double *array,
                                      const size_t n,
                                      gsl_sum_levin_u_workspace * w,
                                      double *sum_accel, double *abserr);

/* Basic Levin-u acceleration method with constraints on the terms
 * used,
 *
 *   array       = array of series elements
 *   n           = size of array
 *   min_terms   = minimum number of terms to sum
 *   max_terms   = maximum number of terms to sum
 *   sum_accel   = result of summation acceleration
 *   err         = estimated error
 *
 * See [Fessler et al., ACM TOMS 9, 346 (1983) and TOMS-602]
 */

GSL_EXPORT int gsl_sum_levin_u_minmax (const double *array,
                                       const size_t n,
                                       const size_t min_terms,
                                       const size_t max_terms,
                                       gsl_sum_levin_u_workspace * w,
                                       double *sum_accel, double *abserr);

/* Basic Levin-u step w/o reference to the array of terms.
 * We only need to specify the value of the current term
 * to execute the step. See TOMS-745.
 *
 * sum = t0 + ... + t_{n-1} + term;  term = t_{n}
 *
 *   term   = value of the series term to be added
 *   n      = position of term in series (starting from 0)
 *   sum_accel = result of summation acceleration
 *   sum_plain = simple sum of series
 */

GSL_EXPORT
int
gsl_sum_levin_u_step (const double term,
                      const size_t n,
                      const size_t nmax,
                      gsl_sum_levin_u_workspace * w,
                      double *sum_accel);

/* The following functions perform the same calculation without
   estimating the errors. They require O(N) storage instead of O(N^2).
   This may be useful for summing many similar series where the size
   of the error has already been estimated reliably and is not
   expected to change.  */

typedef struct
{
  size_t size;
  size_t i;                     /* position in array */
  size_t terms_used;            /* number of calls */
  double sum_plain;
  double *q_num;
  double *q_den;
  double *dsum;
}
gsl_sum_levin_utrunc_workspace;

GSL_EXPORT gsl_sum_levin_utrunc_workspace *gsl_sum_levin_utrunc_alloc (size_t n);
GSL_EXPORT void gsl_sum_levin_utrunc_free (gsl_sum_levin_utrunc_workspace * w);

GSL_EXPORT int gsl_sum_levin_utrunc_accel (const double *array,
                                           const size_t n,
                                           gsl_sum_levin_utrunc_workspace * w,
                                           double *sum_accel, double *abserr_trunc);

GSL_EXPORT int gsl_sum_levin_utrunc_minmax (const double *array,
                                            const size_t n,
                                            const size_t min_terms,
                                            const size_t max_terms,
                                            gsl_sum_levin_utrunc_workspace * w,
                                            double *sum_accel, double *abserr_trunc);

GSL_EXPORT int gsl_sum_levin_utrunc_step (const double term,
                                          const size_t n,
                                          gsl_sum_levin_utrunc_workspace * w,
                                          double *sum_accel);

__END_DECLS

#endif /* __GSL_SUM_H__ */

max_stars_repo_name: dynaryu/vaws

max_issues_repo_name: dynaryu/vaws

max_forks_repo_name: dynaryu/vaws


text:
/* randist/bernoulli.c
 *
 * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <config.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>

/* The bernoulli distribution has the form,

   prob(0) = 1-p, prob(1) = p

   */

unsigned int
gsl_ran_bernoulli (const gsl_rng * r, double p)
{
  double u = gsl_rng_uniform (r) ;

  if (u < p)
    {
      return 1 ;
    }
  else
    {
      return 0 ;
    }
}

double
gsl_ran_bernoulli_pdf (const unsigned int k, double p)
{
  if (k == 0)
    {
      return 1 - p ;
    }
  else if (k == 1)
    {
      return p ;
    }
  else
    {
      return 0 ;
    }
}


text:
#pragma once
#include <exception>
#include <iostream>
#include <cstdlib>
#include <functional>
#include <memory>
#include <vector>
#include <gsl/gsl>

#define VK_USE_PLATFORM_WIN32_KHR
#include <vulkan/vulkan.h>
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h>

#ifdef max
#undef max
#endif
#ifdef min
#undef min
#endif

/*
We define this in case we want to use VulkanMemoryAllocator's
allocators.

	- https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator

Currently we are using the allocator by default so allocation of
buffers and images without VMA_USE_ALLOCATOR could not be fully supported.
*/
#define VMA_USE_ALLOCATOR

#include "../utils/Utils.h"
#include "./RenderUtils.h"
#include "../Configuration.h"
#include "RenderData.h"

/**
Used for managing all the rendering logic of the application.

Manages creation, destruction and use of all the resources necessary
to render to the screen using the Vulkan API.
*/
class Renderer
{
private:
	using WindowPtr = std::unique_ptr<GLFWwindow, GLFWWindowDestroyer>;

public:
	/**
	Default Constructor.
	Since we tie a lot of the resources to this instance and we need to
	manage them only from here the copy and move functionalities are not allowed.
	*/
	[[gsl::suppress(26439)]] Renderer();
	Renderer(const Renderer&) = delete;
	Renderer& operator=(const Renderer&) = delete;
	Renderer(Renderer&&) = delete;
	Renderer& operator=(Renderer&&) = delete;
	~Renderer();

	/* --------------------------------------------------------------------------------------------------------- */
	/* ---------------------------------------- PUBLIC FUNCTION MEMBERS ---------------------------------------- */
	/* --------------------------------------------------------------------------------------------------------- */

	/**
	Updates the uniform buffer for the object being rendered

	@TODO: Reformat this function out of the renderer.

	@see m_uniform_buffer
	*/
	auto updateRotateTestUniformBuffer() ->void;

	/**
	Sets up the beggining of a frame. Setting up the recording of a
	one time command buffer to submit to the rendering queue.
	*/
	auto beginFrame() -> void;

	/**
	Finishes the rendering stages and submits all the necessary information
	to the graphics card for rendering.
	*/
	auto endFrame() -> void;

	/**
	Returns true when we should close the application as far as the render manager
	is concerned. Currently it deals with the user closing the window itself.

	@return true if the window has been closed or we should end the application.
	*/
	auto shouldClose() const noexcept -> bool;

private:

	/* ---------------------------------------------------------------------------------------------------------- */
	/* ---------------------------------------- PRIVATE FUNCTION MEMBERS ---------------------------------------- */
	/* ---------------------------------------------------------------------------------------------------------- */

	/**
	Initializes the physical window shown by the operating system

	@see m_window
	*/
	auto initWindow() noexcept -> void;

	/**
	Initializes all the Vulkan related components necessary for rendering to
	the screen.
	*/
	auto initVulkan() -> void;

	/**
	Recreates all the necessary members to create a new swap chain, for example
	when resizing the window.
	*/
	auto recreateSwapChain() -> void;

	/**
	Cleans up all the resources that need to be explicitly cleaned up,
	mostly related to the Vulkan API and its resources.
	*/
	auto cleanup() noexcept -> void;

	/**
	Cleans up all the resources related to the swap chain, this is useful when
	recreating the swap chain to be sure we are not leaking memory and resources.
	*/
	auto cleanupSwapChain() noexcept -> void;

	/**
	Creates a Vulkan instance based on the current configuration parameters.

	@see m_instance
	@return A Valid Vulkan Instance
	*/
	auto createInstance()->VkInstance;

	/**
	Prints to standard output all the extension names of all the extensions provided.

	@param a vector with the extensions you would like to print
	*/
	auto printInstanceExtensions(const std::vector<VkExtensionProperties>& extensions)
		const -> void;

	/**
	Checks and prints if all the required extensions provided are available within the available ones.

	@param The vector of the names of the required extensions
	@param The vector of the struct with the properties of the available extensions
	@return true if all the required extensions are within the available ones, false otherwise.
	*/
	[[gsl::suppress(bounds.3)]] auto checkInstanceExtensionsNamesAvailable(
		const std::vector<const char*>& required_extensions,
		const std::vector<VkExtensionProperties>& available_extensions)
		const -> bool;

	/**
	Checks and prints if all the required validation layers in the conficuration are available.

	@return true if all the required validation layers are within the available ones, false otherwise.
	*/
	[[gsl::suppress(bounds.3)]] auto checkValidationLayerSupport() const noexcept -> bool;

	/**
	Calculates and returns the necessary Vulkan extensions for this application based
	on configuration.

	@return A vector with the names of the required extensions
	*/
	auto getRequiredExtensions() const noexcept->std::vector<const char*>;

	/**
	Callback function called to receive messages from the validation layers when
	enabled (in debug mode).

	It follows the parameters of the vulkan PFN_vkDebugReportCallbackEXT function

	@see PFN_vkDebugReportCallbackEXT
	@return VK_FALSE to indicate that the Vulkan call should NOT be aborted.
	*/
#pragma warning( push )
#pragma warning( disable : 4229)
	auto static VKAPI_ATTR VKAPI_CALL debugReportCallback(
		VkDebugReportFlagsEXT                       flags,
		VkDebugReportObjectTypeEXT                  object_type,
		uint64_t                                    object,
		size_t                                      location,
		int32_t                                     msg_code,
		const char*                                 layer_prefix,
		const char*                                 msg,
		void*                                       user_data
	)->VkBool32;
#pragma warning( pop )

	/**
	Sets up the callback function to receive debug information from
	the debug report validation layer.

	@see debugReportCallback
	@see m_debug_callback
	*/
	auto setupDebugCallback() -> void;

	/**
	Creates the window surface to which we will render to.

	@see m_surface
	*/
	auto createSurface() -> void;

	/**
	Interface to the vulkan function "vkCreateDebugReportCallbackEXT" to create
	the debug function callback.

	@see vkCreateDebugReportCallbackEXT
	@return the result of vkCreateDebugReportCallbackEXT or VK_ERROR_EXTENSION_NOT_PRESENT if
	we can't find the function pointer.
	*/
	auto createDebugReportCallbackEXT(
		const VkInstance& instance,
		const VkDebugReportCallbackCreateInfoEXT * create_info,
		const VkAllocationCallbacks* allocator,
		VkDebugReportCallbackEXT* callback
	) noexcept->VkResult;

	/**
	Interface to the vulkan function "vkDestroyDebugReportCallbackEXT" to destroy
	the debug function callback.

	@see vkDestroyDebugReportCallbackEXT
	*/
	auto destroyDebugReportCallbackEXT(
		const VkInstance& instance,
		const VkDebugReportCallbackEXT& callback,
		const VkAllocationCallbacks* allocator
	) noexcept -> void;

	/**
	Iterates and picks the most suitable physical device
	available on the system for this application.

	@see m_physical_device
	@see m_physical_device_properties
	@see m_physical_device_features
	*/
	auto pickPhysicalDevice() -> void;

	/**
	Checks if the physical device is suitable for the application
	and gives it a score based on how suitable it is based on configuration.

	@param the physical device to rate
	@return a tuple with a bool representing that is true when the device is valid
	and an int representing the score, the higher the better.
	*/
	auto physicalDeviceSuitability(
		const VkPhysicalDevice& device
	) const noexcept->std::tuple<bool, int>;

	/**
	Checks the queue families supported by the provided device and returns the indices for the
	required ones in the struct QueueFamilyIndices (graphics and present queues right now).

	@see QueueFamilyIndices
	@see m_queue_family_indices
	@see PrintOptions
	@param The physical device to retrieve the queue families from
	@param The print options for the function to indicate the output desired to standard output
	@return The struct with the family queue indices required or -1 if they haven't been found
	*/
	auto findQueueFamilies(
		const VkPhysicalDevice& physical_device,
		PrintOptions print_options
	) const->QueueFamilyIndices;

	/**
	Creates the vulkan logical device we are going to use and retrieves the graphics and present
	queues from it.

	@see m_device
	@see m_graphics_queue
	@see m_present_queue
	*/
	auto createLogicalDevice() -> void;

	/**
	Creates the allocator used to reserve memory in vulkan

	@see m_vma_allocator
	*/
	auto createAllocator() noexcept ->void;

	/**
	Checks if the physical device provided supports all the extensions required by our configuration

	@param The physical device to check for extension support
	@return true if all the extensions are supported, false otherwise
	*/
	[[gsl::suppress(bounds.3)]]
	auto checkDeviceExtensionSupport(
		const VkPhysicalDevice& device
	) const -> bool;

	/**
	Checks and retrieves information about the swap chain capabilities of a physical device.
	Fills up said information in the SwapChainSupportDetails struct

	@see SwapChainSupportDetails
	@param The physical device to check for swap chain support
	@return A SwapChainSupportDetails filled with swap chain support information
	*/
	auto querySwapChainSupport(
		const VkPhysicalDevice& device
	) const->SwapChainSupportDetails;

	/**
	Checks and returns the best available surface chain format from the provided ones
	prioritizing the ones that fit us best.

	@param A vector with the surface formats to check
	@return The best surface format for our application
	*/
	auto pickSurfaceChainFormat(
		const std::vector<VkSurfaceFormatKHR>& available_formats
	) const->VkSurfaceFormatKHR;

	/**
	Checks and returns the best available present mode from the provided ones
	prioritizing the ones that fit us best.

	@param A vector with the present modes to check
	@return The best present mode for our application
	*/
	auto pickSurfacePresentMode(
		const std::vector<VkPresentModeKHR>& available_modes
	)  const noexcept->VkPresentModeKHR;

	/**
	Checks and returns the best available extent for the images in the
	swap chain based on its capabilities.

	@param The capabilities of the surface
	@return The best possible extent (width, height) for our application
	*/
	auto pickSwapExtent(
		const VkSurfaceCapabilitiesKHR& capabilities
	)  const noexcept->VkExtent2D;

	/**
	Creates the vulkan swap chain required for rendering.
	Prioritizes a triple buffering implementation if possible.

	@see m_swap_chain
	*/
	auto createSwapChain() -> void;

	/**
	Creates an image view for each image in the swap chain so
	we can use them as color targets later.

	@see m_swap_chain_image_views
	*/
	auto createSwapChainImageViews() -> void;

	/**
	Creates the render pass that will be used to then create
	the graphics pipeline.

	@see m_render_pass
	*/
	auto createRenderPass() -> void;

	/**
	Creates the descriptor set layout that we will set in
	the pipeline.

	@see m_descriptor_set_layout;
	*/
	auto createDescriptorSetLayout() -> void;

	/**
	Creates the graphics pipeline (or pipelines) that will be used to render
	our scene.

	@see m_pipeline_layout
	@see m_pipeline
	*/
	auto createGraphicsPipeline() -> void;

	/**
	Creates a shader module based on the code provided and wraps it up
	in the VkShaderModule struct

	@see VkShaderModule
	@param An array of characters with the code for the shader
	@return The shader module created based on the shader code
	*/
	auto createShaderModule(const std::vector<char>& code) const->VkShaderModule;

	/**
	Creates the framebuffersto draw to during render time

	@see m_swap_chain_framebuffers
	*/
	auto createFramebuffers() ->  void;

	/**
	Creates the command pool that contains the command buffers to
	draw to during render time.

	@see m_graphics_command_pool
	*/
	auto createGraphicsCommandPool() ->  void;

	/**
	Creates the command pool that contains the command buffers to
	execute transfer memory commands.

	@see m_transfer_command_pool
	*/
	auto createTransferCommandPool() ->  void;

	/**
	Helper function that creates a vulkan image in a general way

	@param Width of the image
	@param Height of the image
	@param Vulkan Format of the image
	@param Tiling Options for the image
	@param Usage flags that the image will need
	@param Usage type for allocation
	@param Flags necessary for allocation
	@param The image to be populated
	@param The sharing mode for the image (Concurrent or exclusive)
	@param The family indices when sharing mode is concurrent (or nullptr otherwise)
	@param The sample count for the image, 1 sample by default (used on images meant for multisampling)
	*/
	auto createImage(
		uint width,
		uint height,
		VkFormat format,
		VkImageTiling tiling,
		VkImageUsageFlags flags,
		VmaMemoryUsage allocation_usage,
		VmaAllocationCreateFlags allocation_flags,
		AllocatedImage& image,
		VkSharingMode sharing_mode,
		const std::vector<uint>* queue_family_indices,
		short samples = 1
	) -> void;

	/**
	Destroys the image provided and frees its memory

	@param The image to destroy
	*/
	auto destroyImage(AllocatedImage& image) noexcept -> void;

	/**
	Creates the necessary resources for the implementation
	of a depth buffer

	@ m_depth_image
	@ m_depth_image_view
	*/
	auto createDepthResources() -> void;

	/**
	Creates a texture image with the data loaded from a file

	@param the path of th texture
	@return The allocated image with the texture
	*/
	auto createTextureImage(std::string path) -> AllocatedImage;

	/**
	Creates a texture image view into the texture image

	@param The image to create the view from
	@return An image view for the provided image.
	*/
	auto createTextureImageView(AllocatedImage image) -> VkImageView;

	/**
	Loads the scene with the provided object (.obj) and texture paths

	@param The path to the .obj model
	@param The path to the texture for the model
	@see m_scene
	*/
	auto loadScene(std::string object_path, std::string texture_path) -> void;

	/**
	Creates a sampler to sample the textures
	used in the rendering phase.

	@see m_texture_sampler
	*/
	auto createTextureSampler() -> void;

	/**
	Helper function that creates a vulkan buffer in a general way.

	@param The size of the memory to be allocated
	@param The usage flags necessary for the memory we are allocating
	@param The allocation usage that the buffer will have
	@param The flags for the allocator to use during creating of the buffer.
	@param The handle to the buffer to create
	@param The sharing mode of the buffer (VK_SHARING_MODE_(EXCLUSIVE/CONCURRENT))
	@param The family indices of the queues this buffer will be shared between if CONCURRENT, nullptr otherwise
	*/
	auto createBuffer(
		VkDeviceSize size,
		VkBufferUsageFlags usage,
#ifdef VMA_USE_ALLOCATOR
		VmaMemoryUsage allocation_usage,
		VmaAllocationCreateFlags allocation_flags,
#else
		VkMemoryPropertyFlags properties,
#endif
		AllocatedBuffer& allocated_buffer,
		VkSharingMode sharing_mode,
		const std::vector<uint>* queue_family_indices
	) -> void;

	/**
	Destroys the buffer provided and frees its memory

	@param The Buffer to destroy
	*/
	auto destroyBuffer(
		AllocatedBuffer& allocated_buffer
	) noexcept -> void;

	/**
	Creates the vertex buffer that will hold the vertices to render.

	@see m_vertex_buffer
	*/
	auto createVertexBuffer() -> void;

	/**
	Creates the index buffer that will hold the indexes in order to render.

	@see m_index_buffer
	*/
	auto createIndexBuffer() -> void;

	/**
	Creates the uniform buffer that will hold the object data to render.

	@see m_uniform_buffer
	*/
	auto createUniformBuffer() -> void;

	/**
	Creates the descriptor pool that will hold the descriptors sets that will
	be used during rendering.

	@see m_descriptor_pool
	*/
	auto createDescriptorPool() -> void;

	/**
	Creates the descriptor set that will hold the descriptors
	used during rendering.

	@see m_descriptor_set
	*/
	auto createDescriptorSet() -> void;

	/**
	Helper function that finds the appropriate format for a depth attachment.

	@return Format that supports usage as a depth attachment
	*/
	auto findDepthFormat()->VkFormat;

	/**
	Checks if a given format has a stencil component in it.

	@param The format to check
	@return True if it has a stencil component, false otherwise
	*/
	auto hasStencilComponent(VkFormat format) const noexcept -> bool;

	/**
	Helper function that finds the post appropriate format for an image given
	the desired features and candidates.

	@param The possible formats to choose from
	@param The tiling options of the image
	@param The features desired
	@return The most appropriate format
	*/
	auto findSupportedFormat(
		const std::vector<VkFormat>& candidates,
		VkImageTiling tiling,
		VkFormatFeatureFlags features
	)->VkFormat;

	/**
	Helper function that calculates the required memory types given the input properties.

	@param Flags that indicate the types of memories that we can consider
	@param Properties of the memory we need
	@param A reference to a boolean that will indicate if we have found an appropriate type
	@return Appropriate flags of the memory we can use.
	*/
	auto findMemoryType(
		uint type_filter,
		VkMemoryPropertyFlags properties,
		VkBool32 *found = nullptr
	)->uint;

	/**
	Copies the contents from one VkBuffer to another.

	@param The source buffer
	@param The destination buffer
	@param The size of the memory to be copied
	*/
	auto copyBuffer(
		VkBuffer src,
		VkBuffer dst,
		VkDeviceSize size
	) noexcept -> void;

	/**
	Creates the command buffers that contain the commands to
	draw to during render time.

	@see m_command_buffers
	*/
	auto createCommandBuffers() ->  void;

	/**
	Creates the drawing commands into the command buffers

	@see m_command_buffers
	*/
	auto recordCommandBuffers() -> void;

	/**
	Creates the semaphores and fences necessary for synchronization of
	the rendering phase.

	@see m_image_available_semaphores
	@see m_render_finished_semaphores
	@see m_command_buffer_fences
	*/
	auto createSemaphoresAndFences() -> void;

	/**
	Handles the event of resizing the window to set up the appropriate
	rendering parameters accordingly.

	@param Reference to the window that has been resized
	@param New width of the window
	@param New height of the window
	*/
	auto static onWindowsResized(
		GLFWwindow * window,
		int width,
		int heigth) -> void;

	/**
	Creates a single use command buffer and starts recording to it

	@param the type of commands that will be used (graphics also allows transfer)
	@return The command buffer we are recording to
	*/
	auto beginSingleTimeCommands(
		CommandType command_type = CommandType::graphics
	) noexcept->WrappedCommandBuffer;

	/**
	End recording to a particulaar command buffer and submits it to the queue

	@param The command buffer to submit to the queue
	*/
	auto endSingleTimeCommands(
		WrappedCommandBuffer& command_buffer
	) noexcept ->void;

	/**
	Helper function that changes the image layout to a new one

	@param The image to change the layout to
	@param The format of the image
	@param The old layout of the image
	@param The new layout for the image
	*/
	auto changeImageLayout(
		VkImage& image,
		VkFormat format,
		VkImageLayout old_layout,
		VkImageLayout new_layout)->void;

	/**
	Helper function that copies a buffer with image data into
	a vulkan image structure.

	@param The buffer to read the data from
	@param The image to write de data into
	@param Width of the image
	@param Height of the image
	*/
	auto copyBufferToImage(
		VkBuffer buffer,
		VkImage image,
		uint width,
		uint heigth) noexcept -> void;

	/**
	Helped function that creates an image view to the
	provided image.

	@param The image to create a view from
	@param The format of the view
	@param The aspect mast to create the image view regarding its use
	@return An image view into the provided image
	*/
	auto createImageView(
		VkImage image,
		VkFormat format,
		VkImageAspectFlags aspect_flags
	)->VkImageView;

	/**
	Helper function that calculates the required flags to
	set up an especific amount of samples.

	@param The number of samples required (power of 2 up to 64)
	@return The required vulkan flag for the number of samples
	*/
	auto getSampleBits(short samples)->VkSampleCountFlagBits;

	/**
	Creates a render target for multisampling. This includes, the image,
	its memory and a view to it.

	@param Width of the render target
	@param Height of the render target
	@param Desired format of the render target
	@param The usage flags for the render target
	@param The aspect flags for the image view of the render target
	@return The render target struct with all the relevant info
	*/
	auto createMultisampleRenderTarget(
		uint width,
		uint height,
		VkFormat format,
		VkImageUsageFlags usage,
		VkImageAspectFlags aspect_mask)->WrappedRenderTarget;

	/* ---------------------------------------------------------------------------------------------- */
	/* ---------------------------------------- DATA MEMBERS ---------------------------------------- */
	/* ---------------------------------------------------------------------------------------------- */

	RenderConfiguration config{};

#ifdef VMA_USE_ALLOCATOR
	VmaAllocator m_vma_allocator{};
#endif

	WindowPtr m_window{};

	VkInstance m_instance{};

	VkDebugReportCallbackEXT m_debug_callback{};

	VkSurfaceKHR m_surface{};

	QueueFamilyIndices m_queue_family_indices{};

	VkPhysicalDevice m_physical_device = VK_NULL_HANDLE;

	VkPhysicalDeviceProperties m_physical_device_properties{};

	VkPhysicalDeviceFeatures m_physical_device_features{};

	VkDevice m_device{};

	VkQueue m_graphics_queue{};

	VkQueue m_present_queue{};

	VkQueue m_transfer_queue{};

	WrappedRenderTarget m_render_target{};

	WrappedRenderTarget m_depth_target{};

	VkFormat m_depth_format{};

	VkSwapchainKHR m_swap_chain{};

	uint m_current_swapchain_buffer{};

	std::vector<VkImage> m_swap_chain_images{};

	VkFormat m_swap_chain_image_format{};

	VkExtent2D m_swap_chain_extent{};

	std::vector<VkImageView> m_swap_chain_image_views{};

	VkRenderPass m_render_pass{};

	VkPipelineLayout m_pipeline_layout{};

	SimpleObjScene m_scene{};

	VkDescriptorSetLayout m_descriptor_set_layout{};

	VkPipeline m_pipeline{};

	std::vector<VkFramebuffer> m_swap_chain_framebuffers{};

	VkCommandPool m_graphics_command_pool{};

	VkCommandPool m_transfer_command_pool{};

	AllocatedBuffer m_vertex_buffer{};

	AllocatedBuffer m_index_buffer{};

	AllocatedBuffer m_uniform_buffer{};

	AllocatedImage m_depth_image{};

	VkImageView m_depth_image_view{};

	VkSampler m_texture_sampler{};

	VkDescriptorPool m_descriptor_pool{};

	VkDescriptorSet m_descriptor_set{};

	std::vector<VkCommandBuffer> m_command_buffers{};

	uint m_current_command_buffer{};

	std::vector<bool> m_command_buffer_submitted{};

	std::vector<VkSemaphore> m_image_available_semaphores{};

	std::vector<VkSemaphore> m_render_finished_semaphores{};

	std::vector<VkFence> m_command_buffer_fences{};

};


text:
#pragma once

#include <gsl\gsl>
#include "Texture.h"
#include "Rectangle.h"

namespace Library
{
	class Texture2D final : public Texture
	{
		RTTI_DECLARATIONS(Texture2D, Texture)

	public:
		Texture2D(const GLuint textureID, GLuint width, GLuint height);
		Texture2D(const Texture2D&) = default;
		Texture2D& operator=(const Texture2D&) = default;
		Texture2D(Texture2D&&) = default;
		Texture2D& operator=(Texture2D&&) = default;
		~Texture2D() = default;

		static std::shared_ptr<Texture2D> CreateTexture2D(GLuint width, GLuint height, GLint mipLevels = 1, GLenum colorFormat = GL_RGBA16F);

		GLuint Width() const;
		GLuint Height() const;
		Rectangle Bounds() const;

	private:
		GLuint mWidth;
		GLuint mHeight;
	};
}

max_stars_repo_name: DakkyDaWolf/OpenGL

max_issues_repo_name: DakkyDaWolf/OpenGL

max_forks_repo_name: DakkyDaWolf/OpenGL