text:
/**************************************************************************************************
 * Class for MPC with constraint
 *
 *  The plant to be controlled is a Linear Time-Invariant System:
 *          x(k+1)  = A*x(k) + B*u(k)   ; x = Nx1, u = Mx1
 *          z(k)    = C*x(k)            ; z = Zx1
 *
 *
 ** Calculate prediction of z(k+1..k+Hp) constants ************************************************
 *
 *      Prediction of state variable of the system:
 *        z(k+1..k+Hp) = (CPSI)*x(k) + (COMEGA)*u(k-1) + (CTHETA)*dU(k..k+Hu-1)         ...{MPC_1}
 *
 *        Constants:
 *          CPSI   = [CA C(A^2) ... C(A^Hp)]'                                       : (Hp*N)xN
 *          COMEGA = [CB C(B+A*B) ... C*Sigma(i=0->Hp-1)A^i*B]'                     : (Hp*N)xM
 *          CTHETA = [         CB                0  ....           0              ]
 *                   [       C(B+A*B)           CB   .             0              ]
 *                   [           .               .    .           CB              ] : (Hp*N)x(Hu*M)
 *                   [           .               .     .           .              ]
 *                   [C*Sigma(i=0->Hp-1)(A^i*B)  .  ....  C*Sigma(i=0->Hp-Hu)A^i*B]
 *
 *
 ** Calculate QPs offline optimization variable ***************************************************
 *
 *     Calculate Qqp and its inverse:
 *      Qqp = 2H = 2*(CTHETA'*Q*CTHETA + R)                                             ...{MPC_2}
 *      Qqp_inv = Qqp^(-1)
 *
 *     Calculate the constant portion of optimization variable G in QP form Cqp:
 *      Cqp = -G = -2.*CTHETA'*Q*E(k)                                                   ...{MPC_3}
 *
 *     Calculate the left side of the contraints equation                               ...{MPC_4}
 *
 ** MPC update algorithm **************************************************************************
 *
 *      Formulation of plant error prediction
 *          E(k) = SP(k) - CPSI*x(k) - COMEGA*u(k-1)                                    ...{MPC_5}
 *
 *      Calculate online portion of optimization variable G in QP form Cqp:
 *          Cqp = Cqp,const * *E(k)                                                     ...{MPC_6}
 *
 *     Calculate the right side of the contraints equation                              ...{MPC_7}
 *
 *      MPC solution:
 *          (a) For unconstrained MPC:
 *              d [dU(k)'*H*dU(k) - G'*dU(k)]
 *              ----------------------------- = 0   -->   2*H*dU(k)-G = 0
 *                      d[dU(k)]
 *
 *              --> dU(k)_optimal = 1/2 * H^-1 * G
 *              --> https://github.com/pronenewbits/Arduino_Unconstrained_MPC_Library
 *
 *          (b) For constrained MPC (quadrating programming):
 *                  min   dU(k)'*H*dU(k) - G'*dU(k)     ; subject to inequality constraints
 *                 dU(k)
 *
 *              Reconditioning H & G matrices into a standard QP form:
 *                x_opt = arg Min  1/2*x'*Q*x + c'*x    ; subject to ineqLHS*x <= ineqRHS
 *                           x
 *
 *              Then solve by Active Set:
 *                  dU_opt(k) = ActiveSet(Qqp, Qqp,inv, cqp, ineqLHS, ineqRHS)          ...{MPC_8}
 *
 *      Integrate the du(k) to get u(k):
 *              u(k) = u(k-1) + du(k)                                                   ...{MPC_9}
 *
 *
 *
 * See https://github.com/pronenewbits for more!
 *************************************************************************************************/
#include "mpc.h"

MPC::MPC(Matrix &A, Matrix &B, Matrix &C, float_prec _bobotQ, float_prec _bobotR,
         void (*vCreateConstraintsLHS)(Matrix &, const Matrix &),
         void (*vCreateConstraintsRHS)(Matrix &, const Matrix &, const Matrix &, const Matrix &, const Matrix &))
{
    vReInit(A, B, C, _bobotQ, _bobotR, vCreateConstraintsLHS, vCreateConstraintsRHS);
}

void MPC::vReInit(Matrix &A, Matrix &B, Matrix &C, float_prec _bobotQ, float_prec _bobotR,
                  void (*vCreateConstraintsLHS)(Matrix &, const Matrix &),
                  void (*vCreateConstraintsRHS)(Matrix &, const Matrix &, const Matrix &, const Matrix &, const Matrix &))
{
    this->A = A;
    this->B = B;
    this->C = C;
    this->vCreateConstraintsLHS = vCreateConstraintsLHS;
    this->vCreateConstraintsRHS = vCreateConstraintsRHS;
    CnstLHS = Matrix(0,0);
    CnstRHS = Matrix(0,0);
    Q.vSetDiag(_bobotQ);
    R.vSetDiag(_bobotR);

    /*  Calculate prediction of z(k+1..k+Hp) constants
     *
     *      Prediction of state variable of the system:
     *        z(k+1..k+Hp) = (CPSI)*x(k) + (COMEGA)*u(k-1) + (CTHETA)*dU(k..k+Hu-1)         ...{MPC_1}
     *
     *        Constants:
     *          CPSI   = [CA C(A^2) ... C(A^Hp)]'                                       : (Hp*N)xN
     *          COMEGA = [CB C(B+A*B) ... C*Sigma(i=0->Hp-1)A^i*B]'                     : (Hp*N)xM
     *          CTHETA = [         CB                0  ....           0              ]
     *                   [       C(B+A*B)           CB   .             0              ]
     *                   [           .               .    .           CB              ] : (Hp*N)x(Hu*M)
     *                   [           .               .     .           .              ]
     *                   [C*Sigma(i=0->Hp-1)(A^i*B)  .  ....  C*Sigma(i=0->Hp-Hu)A^i*B]
     *
     */
    Matrix _Apow(SS_X_LEN, SS_X_LEN);
    /* CPSI     : [ C *   A  ]
     *            [ C *  A^2 ]
     *            [     .    ]                                                   : (Hp*N) x N
     *            [     .    ]
     *            [ C * A^Hp ]
     */
    _Apow = A;
    for (int16_t _i = 0; _i < MPC_HP_LEN; _i++) {
        CPSI = CPSI.InsertSubMatrix((C*_Apow), _i*SS_Z_LEN, 0);
        _Apow = _Apow * A;
    }

    /* COMEGA   : [          C * (B)         ]
     *            [        C * (B+A*B)       ]
     *            [             .            ]                                   : (Hp*N) x M
     *            [             .            ]
     *            [ C * Sigma(i=0->Hp-1)A^i*B]
     */
    Matrix _tempSigma(SS_X_LEN, SS_U_LEN);
    _Apow.vSetIdentity();
    _tempSigma = B;
    for (int16_t _i = 0; _i < MPC_HP_LEN; _i++) {
        COMEGA = COMEGA.InsertSubMatrix((C*_tempSigma), _i*SS_Z_LEN, 0);
        _Apow = _Apow * A;
        _tempSigma = _tempSigma + (_Apow*B);
    }

    /* CTHETA   : [          C * (B)              0         ....              0             ]
     *            [       C * (B+A*B)           C * (B)      .                0             ]
     *            [            .                  .           .             C * (B)         ]: (Hp*N)x(Hu*M)
     *            [            .                  .            .              .             ]
     *            [C * Sigma(i=0->Hp-1)A^i*B      .         ....  C * Sigma(i=0->Hp-Hu)A^i*B]
     *
     *          : [COMEGA   [0 COMEGA(0:(len(COMEGA)-len(B)),:)]'  ....  [0..0 COMEGA(0:(len(COMEGA)-((Hp-Hu)*len(B))),:)]']
     */
    for (int16_t _i = 0; _i < MPC_HU_LEN; _i++) {
        CTHETA = CTHETA.InsertSubMatrix(COMEGA, _i*SS_Z_LEN, _i*SS_U_LEN, (MPC_HP_LEN*SS_Z_LEN)-(_i*SS_Z_LEN), SS_U_LEN);
    }

    /* Calculate offline optimization variable H in QP form (Qqp):
     *  Qqp = 2H = 2*(CTHETA'*Q*CTHETA + R)                                                 ...{MPC_2}
     *
     * Note: we need to reconditioning into standard QP form (Q_qp = 2H_mpc, c_qp = -G_mpc)
     */
    Qqp = 2*((CTHETA.Transpose()) * Q * CTHETA + R);
    Qqp_INV = Qqp.Invers();

    /* Calculate the constant portion of optimization variable G in QP form Cqp:
     *  Cqp = -G = -2.*CTHETA'*Q*E(k)                                                       ...{MPC_3}
     *             \-----v-----/
     *              This portion
     */
    cqp_const = -2.0 * (CTHETA.Transpose()) * Q;

    /* The left side of the contraints equation is constant. Calculate at initialization    ...{MPC_4} */
    vCreateConstraintsLHS(CnstLHS, CTHETA);
}

bool MPC::bUpdate(Matrix &SP, Matrix &x, Matrix &u)
{

    /* Formulation of plant error prediction:
     *  E(k) = SP(k) - CPSI*x(k) - COMEGA*u(k-1)                                            ...{MPC_5}
     */
    Err = SP - CPSI*x - COMEGA*u;

    /* Calculate online portion of optimization variable G in QP form Cqp:
     *  Cqp = Cqp,const * *E(k)                                                             ...{MPC_6}
     */
    cqp = cqp_const * Err;

    /*  Create the inequality constraints                                                   ...{MPC_7} */
    vCreateConstraintsRHS(CnstRHS, COMEGA, CPSI, u, x);

    #if (0)
        /* Experiment: disable constraints, the MPC will behave like unconstrained MPC */
        #warning("Contstraints bypassed (no constraints)");
        CnstLHS = Matrix(0,0);
        CnstRHS = Matrix(0,0);
    #endif

    /*  Formulation of the optimal control problem:
     *
     *      For constrained MPC (quadrating programming):
     *          min   dU(k)'*H*dU(k) - G'*dU(k)     ; subject to inequality constraints
     *             dU(k)
     *
     *      Reconditioning H & G matrices into a standard QP form:
     *          x_opt = arg Min  1/2*x'*Q*x + c'*x  ; subject to ineqLHS*x <= ineqRHS
     *                     x
     *
     *      Then solve by Active Set:
     *          dU_opt(k) = ActiveSet(Qqp, Qqp,inv, cqp, ineqLHS, ineqRHS)                  ...{MPC_8}
     *
     *
     * 1/2*Q = H    --> Q = 2*H     (the reconditioning has been done when we create H & G)
     * c' = -G'     --> c = -G
     */
    if (!bActiveSet(DU, Qqp, Qqp_INV, cqp, CnstLHS, CnstRHS, cntIterActiveSet)) {
        /* return false; */
        DU.vSetToZero();
        return false;
    }

    /* Integrate the du(k) to get u(k):
     *  u(k) = u(k-1) + du(k)                                                               ...{MPC_9}
     */
    Matrix DU_Out(SS_U_LEN, 1);
    for (int16_t _i = 0; _i < SS_U_LEN; _i++) {
        DU_Out[_i][0] = DU[_i][0];
    }
    u = u + DU_Out;

    return true;
}

/* Active Set solver for Quadratic Programming problem in the form:
 *
 *      x_opt = arg Min  1/2*x'*Q*x + c'*x    ; subject to ineqLHS*x <= ineqRHS
 *                 x
 *
 *
 * The Active Set: search x, by solving this minimization problem:
 *
 *  min. 1/2*dx'*Q*dx + (Q*x+c)'*dx   , subject to ineqLHS_dx*x = 0
 *   dx
 *
 *  Integrate x(iter+1) = x(iter) + dx(iter)
 *
 *  Until KKT conditions is satisfied:
 *      1. Q*dx + ineqLHS_dx*(dLambda) = -(Q*x+c)   (dLambda = Lagrange multiplier of above minimization solution)
 *      2. -ineqLHS_dx*dx = 0
 *
 */
bool MPC::bActiveSet(Matrix &x, const Matrix &Q, const Matrix &Qinv, const Matrix &c, const Matrix &ineqLHS, const Matrix &ineqRHS, int16_t &_i16iterActiveSet)
{
    bool _flagConstActive[ineqRHS.i16getRow()];    /* Contains information about which inequality is active (if true, then that inequality is active). */
    bool _dlambdaPos, _dxNol;
    Matrix dx(x.i16getRow(), 1, Matrix::NoInitMatZero);
    Matrix dLambda(0, 0, Matrix::NoInitMatZero);

    /* TODO: Make sure x initial value is inside feasible region (e.g. using Linear Programming).
     *       For now we set it to zero --> no mathematical guarantee!
     */
    x.vSetToZero();
    /* In the beginning, every constraints is non-active */
    for (int16_t _i = 0; _i < ineqRHS.i16getRow(); _i++) {
        _flagConstActive[_i] = false;
    }

    _i16iterActiveSet = 0;  /* Reset counter iteration Active Set */
    do {
        /* Construct active set matrix Aw (_ineqActiveLHS) */
        uint16_t _u16cntConstActive = 0;
        for (int16_t _i = 0; _i < ineqLHS.i16getRow(); _i++) {
            if (_flagConstActive[_i] == true) {
                _u16cntConstActive++;
            }
        }
        int16_t _indexConstActive[_u16cntConstActive];                                          /* Contains information about index of the active inequality constraints in ineqLHS */
        Matrix _ineqActiveLHS(_u16cntConstActive, ineqLHS.i16getCol(), Matrix::NoInitMatZero);  /* Aggregation of the row vectors of ineqLHS that is 'active', i.e. the Aw matrix */
        for (int16_t _i = 0, _iterConstActive = 0; _i < ineqLHS.i16getRow(); _i++) {
            if (_flagConstActive[_i] == true) {
                _ineqActiveLHS = _ineqActiveLHS.InsertSubMatrix(ineqLHS, _iterConstActive, 0, _i, 0, 1, ineqLHS.i16getCol());
                _indexConstActive[_iterConstActive] = _i;

                _iterConstActive++;
                ASSERT((_iterConstActive <= _u16cntConstActive), "Bug on the active set: create _ineqActiveLHS");
            }
        }
        /* Solve KKT system using CholeskyDec + Forward/Back subtitution */
        Matrix _g(-((Q*x)+c));
        if (_u16cntConstActive > 0) {
            Matrix _ineqActiveLHStr(_ineqActiveLHS.Transpose());
            Matrix _KKT_AGinAtr_chol((_ineqActiveLHS*Qinv*_ineqActiveLHStr).CholeskyDec());

            dLambda = dLambda.ForwardSubtitution(_KKT_AGinAtr_chol, (_ineqActiveLHS*Qinv*_g));
            dLambda = dLambda.BackSubtitution(_KKT_AGinAtr_chol.Transpose(), dLambda);

            dx = (Qinv * (_g-(_ineqActiveLHStr*dLambda)));
        } else {
            dx = (Qinv * _g);
        }

        /* Check for Karush–Kuhn–Tucker conditions ------------------------------------------------------------------------------------------------ */
        /* Karush–Kuhn–Tucker conditions:
         *  1. dx == 0
         *  2. dLambda >= 0
         */
        /* Search for dx == 0 ----------------- */
        _dxNol = true;
        for (int16_t _i = 0; _i < Q.i16getRow(); _i++) {
            if (fabs(dx[_i][0]) > float_prec(float_prec_ZERO_ECO)) {
                _dxNol = false;
                break;
            }
        }
        /* Search for dLambda >= 0 ------------ */
        float_prec _lowestLambda = 0.0;
        int16_t _idxIneqLowestLambda = -1;
        _dlambdaPos = true;
        for (int16_t _i = 0; _i < _u16cntConstActive; _i++) {
            if (dLambda[_i][0] < _lowestLambda) {
                /* Some constraints become inactive, search constraint with lowest Lagrange multiplier so we can remove it */
                _lowestLambda = dLambda[_i][0];
                _idxIneqLowestLambda = _indexConstActive[_i];
                _dlambdaPos = false;
            }
        }
        /* Check it! -------------------------- */
        if (_dxNol && _dlambdaPos) {
            break;
        }

        if (!_dlambdaPos) {
            /* There is a constraint that become inactive ----------------------------------------------------------------------------------------- */

            /* remove the constraint that have lowest Lagrange multiplier */
            ASSERT((_idxIneqLowestLambda != -1), "Bug on the active set: remove ineq active");
            _flagConstActive[_idxIneqLowestLambda] = false;
        }

        if (!_dxNol) {
            /* It means the x(k+1) will move ------------------------------------------------------------------------------------------------------ */

            /* Search for violated constraints. If any, then get the lowest scalar value _alpha that makes
             *  the searching direction feasible again
             */
            float_prec _alphaMin = 1.0;
            int16_t _idxAlphaMin = -1;

            Matrix _ineqNonActiveLHS_dx(ineqLHS * dx);
            Matrix _ineqNonActiveLHS_x(ineqLHS * x);

            for (int16_t _i = 0; _i < ineqLHS.i16getRow(); _i++) {
                if (_flagConstActive[_i] == false) {
                    /* For all constraints that is not active, we check if that constraint is violated */
                    if (_ineqNonActiveLHS_dx[_i][0] > float_prec_ZERO_ECO) {
                        /* We have a violated constraint. Make that constraint a candidate of active constraint */
                        float_prec _alphaCandidate = - (_ineqNonActiveLHS_x[_i][0] - ineqRHS[_i][0]) / _ineqNonActiveLHS_dx[_i][0];

                        if (_alphaCandidate < _alphaMin) {
                            _alphaMin = _alphaCandidate;
                            _idxAlphaMin = _i;
                        }
                    }
                }
            }
            if (_idxAlphaMin != -1) {
                _flagConstActive[_idxAlphaMin] = true;
            }

            /* Should we do ASSERT(_alphaMin > 0.0) here? */
            if (_alphaMin > 0) {
                x = x + (dx * _alphaMin);
            }
        }

        /* Check for maximum iteration conditions ------------------------------------------------------------------------------------------------- */
        _i16iterActiveSet++;
        if (_i16iterActiveSet > MPC_MAXIMUM_ACTIVE_SET_ITERATION) {
            /* Maximum number of iteration reached, terminate and use last solution */
            break;
        }
    } while (1);

    return true;
}


text:
/**************************************************************************************************
 * Class for MPC with constraint.
 *
 *
 * See https://github.com/pronenewbits for more!
 *************************************************************************************************/
#ifndef MPC_H
#define MPC_H

#include "konfig.h"
#include "matrix.h"

#if (MPC_HP_LEN < MPC_HU_LEN)
    #error("The MPC_HP_LEN must be more than or equal MPC_HU_LEN!");
#endif
#if (((MPC_HP_LEN*SS_Z_LEN) > MATRIX_MAXIMUM_SIZE) || ((MPC_HU_LEN*SS_U_LEN) > MATRIX_MAXIMUM_SIZE))
    #error("The MATRIX_MAXIMUM_SIZE is too small to do MPC calculation!");
#endif

#define MPC_MAXIMUM_ACTIVE_SET_ITERATION    (50)

#if defined(MPC_USE_CONSTRAINT_DU)
    #define INEQ_LEN_DU     (2*(MPC_HU_LEN*SS_U_LEN))       /* size DU = (MPC_HU_LEN*SS_U_LEN), times 2 for DU_MIN & DU_MAX */
#else
    #define INEQ_LEN_DU     (0)
#endif
#if defined(MPC_USE_CONSTRAINT_U)
    #define INEQ_LEN_U      (2*(MPC_HU_LEN*SS_U_LEN))       /* size U  = (MPC_HU_LEN*SS_U_LEN), times 2 for U_MIN & U_MAX */
#else
    #define INEQ_LEN_U      (0)
#endif
#if defined(MPC_USE_CONSTRAINT_Z)
    #define INEQ_LEN_Z      (2*(MPC_HP_LEN*SS_Z_LEN))       /* size Z  = (MPC_HP_LEN*SS_Z_LEN), times 2 for Z_MIN & Z_MAX */
#else
    #define INEQ_LEN_Z      (0)
#endif
#if ((INEQ_LEN_DU + INEQ_LEN_U + INEQ_LEN_Z) > MATRIX_MAXIMUM_SIZE)
    /* Worst case for KKT Matrix size using Schur complement: Cnst_DU + Cnst_U + Cnst_Z */
    #error("The MATRIX_MAXIMUM_SIZE is too small to do MPC calculation!");
#endif

class MPC
{
public:
    MPC(Matrix &A, Matrix &B, Matrix &C, float_prec _bobotQ, float_prec _bobotR,
        void (*vCreateConstraintsLHS)(Matrix &, const Matrix &),
        void (*vCreateConstraintsRHS)(Matrix &, const Matrix &, const Matrix &, const Matrix &, const Matrix &));
    void vReInit(Matrix &A, Matrix &B, Matrix &C, float_prec _bobotQ, float_prec _bobotR,
                 void (*vCreateConstraintsLHS)(Matrix &, const Matrix &),
                 void (*vCreateConstraintsRHS)(Matrix &, const Matrix &, const Matrix &, const Matrix &, const Matrix &));
    bool bUpdate(Matrix &SP, Matrix &x, Matrix &u);

    /* for analyzing purpose. If cntIterActiveSet = MPC_MAXIMUM_ACTIVE_SET_ITERATION, the solution might not be optimal (although feasible) */
    int16_t cntIterActiveSet;

protected:
    bool bActiveSet(Matrix &x, const Matrix &Q, const Matrix &Qinv, const Matrix &c, const Matrix &ineqLHS, const Matrix &ineqRHS, int16_t &_i16iterActiveSet);
    void (*vCreateConstraintsLHS)(Matrix &CnstLHS, const Matrix &CTHETA);
    void (*vCreateConstraintsRHS)(Matrix &CnstRHS, const Matrix &COMEGA, const Matrix &CPSI, const Matrix &u_prev, const Matrix &x);

private:
    Matrix CPSI     {(MPC_HP_LEN*SS_Z_LEN), SS_X_LEN};
    Matrix COMEGA   {(MPC_HP_LEN*SS_Z_LEN), SS_U_LEN};
    Matrix CTHETA   {(MPC_HP_LEN*SS_Z_LEN), (MPC_HU_LEN*SS_U_LEN)};

    Matrix DU       {(MPC_HU_LEN*SS_U_LEN), 1};

    Matrix A        {SS_X_LEN, SS_X_LEN};
    Matrix B        {SS_X_LEN, SS_U_LEN};
    Matrix C        {SS_Z_LEN, SS_X_LEN};

    Matrix Q        {(MPC_HP_LEN*SS_Z_LEN), (MPC_HP_LEN*SS_Z_LEN)};
    Matrix R        {(MPC_HU_LEN*SS_U_LEN), (MPC_HU_LEN*SS_U_LEN)};

    Matrix Qqp      {(MPC_HU_LEN*SS_U_LEN), (MPC_HU_LEN*SS_U_LEN)};
    Matrix Qqp_INV  {(MPC_HU_LEN*SS_U_LEN), (MPC_HU_LEN*SS_U_LEN)};
    Matrix cqp_const{(MPC_HU_LEN*SS_U_LEN), (MPC_HP_LEN*SS_Z_LEN)};

    Matrix Err      {(MPC_HP_LEN*SS_Z_LEN), 1};
    Matrix cqp      {(MPC_HU_LEN*SS_U_LEN), 1};

    Matrix CnstLHS	{0, 0};
    Matrix CnstRHS	{0, 0};
};

#endif // MPC_H

mime_type: text/x-tex


text:
duk.gif                         \Delta{u(k)}

dumin_leq_duk_leq_dumax.gif     \Delta{u_{min}}\leq\Delta{u(k)}\leq\Delta{u_{max}}

uk.gif                          u(k)

umin_leq_uk_leq_umax.gif        u_{min}\leq{u(k)}\leq{u_{max}}

zk.gif                          z(k)

zmin_leq_zk_leq_zmax.gif        z_{min}\leq{z(k)}\leq{z_{max}}

umin_leq_uk.gif                 u_{min}\leq{u(k)}

u2_leq_u2max.gif                u_{2}(k)\leq{u_{2,max}}

variabel_qp_ke_mpc.gif          (x\textsubscript{QP}=\Delta{U}\textsubscript{MPC},\textrm{ }\frac{1}{2}Q\textsubscript{QP}=H\textsubscript{MPC},\textrm{ }c_{QP}^{T}x\textsubscript{QP}=-\Delta{U}_{MPC}^{T}G\textsubscript{MPC})

                                x\textsubscript{QP}=\Delta{U}\textsubscript{MPC},1/2(Q\textsubscript{QP})=H\textsubscript{MPC},c_{QP}^{T}x\textsubscript{QP}=-\Delta{U}^{T}G\textsubscript{MPC}

variabel_qp_ke_mpc2.gif         (Q\textsubscript{QP}=2H\textsubscript{MPC},c\textsubscript{QP}=-G\textsubscript{MPC})

variabel_qp_ke_mpc3.gif         (x\textsubscript{QP}=\Delta{U}\textsubscript{MPC},\textrm{ }Q\textsubscript{QP}=2H\textsubscript{MPC},\textrm{ }c\textsubscript{QP}=-G\textsubscript{MPC})

x.gif                           x

solve_kkt_eq_no_constraint.gif  \begin{align*}
                                          Q\Delta{x^{*}} &= -(Qx_k+c)\\
                                    Q(\Delta{x^{*}}+x_k) &= -c\\
                                             x_{optimal} &= -Q^{-1}c
                                \end{align*}

solve_kkt_eq_no_cons_as_mpc.gif \Delta{U}_{optimal}=\frac{1}{2}H^{-1}G

wk.gif                          \boldsymbol{W}_{k}      font: comic sans

solve_kkt_eq_by_invert.gif      \begin{bmatrix}\Delta{x^{*}}\\\lambda^{*}\end{bmatrix}=
                                \begin{bmatrix}Q&&A_w^T\\A_w&&0\end{bmatrix}^{-1}
                                \begin{bmatrix}-(Qx_k+c)\\0\end{bmatrix}

Q.gif                           Q

xk.gif                          x_{k}

xk+1.gif                        x_{k+1}

k_max_iter.gif                  k>k_{iteration,max}

term_clause.gif                 \left(\Delta{x}^{*}=0\textrm{ and }\lambda^{*}\geq{0}\right)

ax_geq_b.gif                    Ax\geq{b}

ax_leq_b.gif                    Ax\leq{b}

-1.gif                          -1

q_qp_to_q_r_mpc.gif             Q_{QP}=2H_{MPC}=2\left(\Theta_{c}^{T}Q_{MPC}\Theta_{c}+R_{MPC}\right)

q_qp.gif                        Q_{QP}

schur_comp_of_kkt.gif           \begin{bmatrix}Q&&A_w^T\\0&&-(A_wQ^{-1}A_w^T)\end{bmatrix}
                                \begin{bmatrix}\Delta{x^{*}}\\\lambda^{*}\end{bmatrix}=
                                \begin{bmatrix}-(Qx_k+c)\\-A_wQ^{-1}(Qx_k+c)\end{bmatrix}

solve_kkt_eq_by_schur.gif       \begin{align*}
                                  (A_wQ^{-1}A_w^T)\lambda^{*}&=-A_wQ^{-1}(Qx_k+c)  \\
                                                \Delta{x^{*}}&=Q^{-1}(-A_w^T\lambda^{*}-(Qx_k+c))
                                \end{align*}

min5leq_du_leq5.gif             \left({-5}\leq\Delta{u}\left{(k}\right{)}\leq{5}\right)

min5leq_du_leq5_min4_z_3_5.gif  \left({-5}\leq\Delta{u}\left{(k}\right{)}\leq{5}\textrm( , ){-4}\leq{z}\left{(k}\right{)}\leq{3.5}\right)


text:
# unRAID bzoverlay

## Big fat disclaimer

Modifying your unRAID server in **any** way may always put your data at risk. This, of course, also applies to this modification. You should always keep backups of any files you absolutely can not afford to lose. **Any and all responibility for problems that may arise as a result from modifying unRAID in any way is yours, and yours alone!**

## Run unRAID from a hard drive - the easy way.

I run an unRAID server in my home network since a few years, and I absolutely love the product.

unRAID boots a root filesystem into ram from a usb flash drive, matches the GUID on the flash drive against the license key and uses the flash drive for persistent storage. Simple and elegant!

If it weren't for the fact that usb flash drives tend to go bad, I would happily run unRAID from a usb flash drive forever.

However, having had two flash drives go bad, I started to look into keeping the usb flash only for the GUID and boot the system from hard drive. Limetech (the makers of unRAID) do have an excellent key replacement policy and has provided me with new license keys, but downtime is downtime.

The ultimate goal was to keep unRAID working **exactly** as usual, only from a hard drive instead.

As it turns out, I am not the first person to entertain this idea - and I found one complicated way after another. Some required that the root filesystem needs to be unpacked, some bootup scripts rewritten and repacked. Some still boots from the usb flash and shuffles the mounts around after boot.

While I am perfectly comfortable with patching initramfs, it is still and inconvenience and it needs to be done after every new version of unRAID.

Some even installed the unRAID components over a Slackware system, compiled a new kernel with Limetechs patches and ran everything straight from the disk.

None of these options are acceptable for something that should **just work™**.

Here are some of my findings while researching how to boot from hard drive, while still keeping full functionality and convenience:

* The flash drive needs to be fat32 (and possibly ntfs?) and must be labeled 'UNRAID'. It also needs to be mounted somewhere for the licensing to work.
* The hard drive must boot from a fat32 partition, and can not be labelled UNRAID.
* I entertained the idea of booting from a btrfs subvolume, but the kernel panics at an early stage if trying to mount btrfs. Since this isn't really a deal breaker, I didn't look into it any further, so it may still be possible.
* The system mounts any drive labeled UNRAID as read/write in the location for persistent storage at boot.
* Trying to trick unRAID into mounting another drive by relabelling them, will not work since it will not find the GUID needed for the license if the flash drive has the wrong label.

The solution is as simple as it is elegant;

* Create a tiny overlay initrafs which mounts the flash drive read-only somewhere and mounts the harddrive as persistent storage. All we really need is a new /etc/fstab with different mount moints and a /license directory to mount the key.
* Add the overlay to the list of initramfs files to load at boot.

Thats it! No unpacking and patching the original files. No moving mountpoints after boot. Nada.

This allows unRAID to find the GUID needed for license, as well as using the hard drive right from the start without having to shuffle anything around after boot.

And, since we're only using a tiny overlay, any updates to the base image should (in theory) **just work™**. We are not really changing how unRAID expects things to work.

##### This technique will work equally well when installing unRAID as a guest OS where boot from usb may not even be an option. No need to mount a plop image to chainboot into usb flash - just create a disk image with these modifications, add the usb key to the vm and off you go! :)

## Manual installation

#### This needs to be done only once!

You can do this right on the unRAID server. If you are uncomfortable with that, just hook the hard drive and usb flash drive up to another Linux computer to do the installation. You will need root privileges for (most of) the following commands. Sudo into a root shell or just add sudo to each line as needed.

##### In the following instruction I am installing unRAID to /dev/sdx1. You are solely responsible for finding out which drive and partition you will install to! Formatting the wrong partition will destroy data!

Create a boot partition on your hard drive. If installing syslinux by hand, it can be any primary partition. If following the instructions below, use the first partition on the disk.

Create filesystem and mount it
```
mkfs.vfat -n BOOTDISK /dev/sdx1
mkdir /mnt/unraid_disk
mount /dev/sdx1 /mnt/unraid_disk
```

Copy unRAID files from usb flash drive. (Substitute /boot/* with path to usb flash drive, if not on unraid system.)
```
cp -R /boot/* /mnt/unraid_disk
```

Patch make_bootable_linux and execute it to install syslinux to the hard drive.
```
sed -e "s|UNRAID|BOOTDISK|" -i /mnt/unraid_disk/make_bootable_linux
/mnt/unraid_disk/make_bootable_linux
```

Alt 1: Create the initramfs overlay by hand (need cpio installed)
```
mkdir -p rootfs/{etc,license}
cat << EOF > rootfs/etc/fstab
/dev/disk/by-label/UNRAID   /license vfat auto,ro,shortname=mixed 0 1
/dev/disk/by-label/BOOTDISK /boot    vfat auto,rw,exec,noatime,nodiratime,umask=0,shortname=mixed 0 1
EOF
cd rootfs
find . | cpio -o -H newc | xz > /mnt/unraid_disk/bzoverlay
```

Alt 2: Install my premade overlay (Does not need cpio)
```
wget https://raw.githubusercontent.com/thohell/unRAID-bzoverlay/master/bzoverlay -O /mnt/unraid_disk/bzoverlay
```

Patch syslinux.cfg to load our overlay at boot
```
sed -e "s|/bzroot|/bzroot,/bzoverlay|" -i /mnt/unraid_disk/syslinux/syslinux.cfg

```

#### Done! Change boot device in BIOS and start up your unRAID server. Everything should work EXACTLY as it did before and upgrades should work exactly as usual, but the flash drive will never get written to again. This should make it less likely to go bad.

repo_name: toneomgomg/unRAID-bzoverlay

mime_type: text/plain


text:
import webpack from 'webpack';
import { CleanWebpackPlugin } from 'clean-webpack-plugin';
import path from 'path';
import { argv } from 'process';

let env = process.env['NODE_ENV'];
let isProduction =
    (env && env.match(/production/)) ||
    argv.reduce((prev, cur) => prev || cur === '--production', false);

let config: webpack.Configuration = {
    context: path.join(__dirname, 'src'),
    entry: {
        app: './main.ts'
    },
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist')
    },
    resolve: {
        extensions: ['.ts', '.tsx', 'js'],
        modules: [path.resolve(__dirname, 'src'), 'node_modules']
    },
    module: {
        rules: [
            {
                test: /\.ts/,
                exclude: /node_modules/,
                loader: 'ts-loader',
                options: {
                    transpileOnly: true,
                    compilerOptions: {
                        isolatedModules: true
                    }
                }
            },
            {
                test: /\.wgsl/,
                type: 'asset/source'
            }
        ]
    },
    node: false,
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify(
                    isProduction ? 'production' : 'development'
                )
            }
        })
    ],
    optimization: {
        minimize: isProduction ? true : false
    }
};

/**
 * Start Build
 */
const compiler: webpack.Compiler = webpack(config);

if (!argv.reduce((prev, cur) => prev || cur === '--watch', false)) {
    compiler.run((err, stats) => {
        if (err) return console.error(err);

        if (stats.hasErrors()) {
            let statsJson = stats.toJson();
            console.log(
                '❌' + ' · Error · ' + 'webgpu-seed failed to compile:'
            );
            for (let error of statsJson.errors) {
                console.log(error.message);
            }
            return;
        }
        console.log(
            '✔' +
                '  · Success · ' +
                'webgpu-seed' +
                (isProduction ? ' (production) ' : ' (development) ') +
                'built in ' +
                (+stats.endTime - +stats.startTime + ' ms.')
        );
    });
} else {
    compiler.watch({}, (err, stats) => {
        if (err) return console.error(err);

        if (stats.hasErrors()) {
            let statsJson = stats.toJson();
            console.log(
                '❌' + ' · Error · ' + 'webgpu-seed failed to compile:'
            );
            for (let error of statsJson.errors) {
                console.log(error.message);
            }
            console.log('\n👀  · Watching for changes... · \n');
            return;
        }
        console.log(
            '✔' +
                '  · Success · ' +
                'webgpu-seed' +
                (isProduction ? ' (production) ' : ' (development) ') +
                'built in ' +
                (+stats.endTime - +stats.startTime + ' ms.') +
                '\n👀  · Watching for changes... · \n'
        );
    });
}

repo_name: alaingalvan/webgpu-seed

repo_language: TypeScript

mime_type: text/x-c


text:
![Cover Art](https://alain.xyz/blog/raw-webgpu/assets/cover.jpg)

# 🔺 WebGPU Seed

[![License][license-img]][license-url]
[![Unit Tests][travis-img]][travis-url]

A WebGPU repo you can use to get started with your own renderer.

- [🔳 Codepen Example](https://codepen.io/alaingalvan/pen/GRgvLGw)

- [💬 Blog Post](https://alain.xyz/blog/raw-webgpu)

## Setup

First install:

- [Git](https://git-scm.com/)

- [Node.js](https://nodejs.org/en/)

- A Text Editor such as [Visual Studio Code](https://code.visualstudio.com/).

Then type the following in any terminal your such as [VS Code's Integrated Terminal](https://code.visualstudio.com/docs/editor/integrated-terminal).

```bash
# 🐑 Clone the repo
git clone https://github.com/alaingalvan/webgpu-seed

# 💿 go inside the folder
cd webgpu-seed

# 🔨 Start installing dependencies, building, and running at localhost:8080
npm start
```

> Refer to [this blog post on designing web libraries and apps](https://alain.xyz/blog/designing-a-web-app) for more details on Node.js, packages, etc.

## Project Layout

As your project becomes more complex, you'll want to separate files and organize your application to something more akin to a game or renderer, check out this post on [game engine architecture](https://alain.xyz/blog/game-engine-architecture) and this one on [real time renderer architecture](https://alain.xyz/blog/realtime-renderer-architectures) for more details.

```bash
├─ 📂 node_modules/   # 👶 Dependencies
│  ├─ 📁 gl-matrix      # ➕ Linear Algebra
│  └─ 📁 ...            # 🕚 Other Dependencies (TypeScript, Webpack, etc.)
├─ 📂 src/            # 🌟 Source Files
│  ├─ 📄 index.html     #  📇 Main HTML file
│  └─ 📄 renderer.ts    # 🔺 Triangle Renderer
├─ 📄 .gitignore      # 👁 Ignore certain files in git repo
├─ 📄 package.json    # 📦 Node Package File
├─ 📄 license.md      # ⚖ Your License (Unlicense)
└─ 📃readme.md        # 📖 Read Me!
```

[license-img]: https://img.shields.io/:license-unlicense-blue.svg?style=flat-square
[license-url]: https://unlicense.org/
[travis-img]: https://img.shields.io/travis/com/alaingalvan/webgpu-seed.svg?style=flat-square
[travis-url]:https://www.travis-ci.com/github/alaingalvan/webgpu-seed


text:
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>WebGPU Hello Triangle</title>
    <style>
      html,
      body {
        margin: 0;
        padding: 0;
        border: 0;
        font-size: 100%;
        font: inherit;
        vertical-align: baseline;
        background: #000;
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    </style>
  </head>
  <body>
    <canvas id="gfx"></canvas>
    <script type="text/javascript" src="dist/main.js"></script>
  </body>
</html>


text:
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.

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 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.

For more information, please refer to <http://unlicense.org>


text:
import vertShaderCode from './shaders/triangle.vert.wgsl';
import fragShaderCode from './shaders/triangle.frag.wgsl';

// 📈 Position Vertex Buffer Data
const positions = new Float32Array([
    1.0, -1.0, 0.0, -1.0, -1.0, 0.0, 0.0, 1.0, 0.0
]);
// 🎨 Color Vertex Buffer Data
const colors = new Float32Array([
    1.0,
    0.0,
    0.0, // 🔴
    0.0,
    1.0,
    0.0, // 🟢
    0.0,
    0.0,
    1.0 // 🔵
]);

// 📇 Index Buffer Data
const indices = new Uint16Array([0, 1, 2]);

export default class Renderer {
    canvas: HTMLCanvasElement;

    // ⚙ API Data Structures
    adapter: GPUAdapter;
    device: GPUDevice;
    queue: GPUQueue;

    // 🎞 Frame Backings
    context: GPUCanvasContext;
    colorTexture: GPUTexture;
    colorTextureView: GPUTextureView;
    depthTexture: GPUTexture;
    depthTextureView: GPUTextureView;

    // 🔺 Resources
    positionBuffer: GPUBuffer;
    colorBuffer: GPUBuffer;
    indexBuffer: GPUBuffer;
    vertModule: GPUShaderModule;
    fragModule: GPUShaderModule;
    pipeline: GPURenderPipeline;

    commandEncoder: GPUCommandEncoder;
    passEncoder: GPURenderPassEncoder;

    constructor(canvas) {
        this.canvas = canvas;
    }

    // 🏎 Start the rendering engine
    async start() {
        if (await this.initializeAPI()) {
            this.resizeBackings();
            await this.initializeResources();
            this.render();
        }
    }

    // 🌟 Initialize WebGPU
    async initializeAPI(): Promise<boolean> {
        try {
            // 🏭 Entry to WebGPU
            const entry: GPU = navigator.gpu;
            if (!entry) {
                return false;
            }

            // 🔌 Physical Device Adapter
            this.adapter = await entry.requestAdapter();

            // 💻 Logical Device
            this.device = await this.adapter.requestDevice();

            // 📦 Queue
            this.queue = this.device.queue;
        } catch (e) {
            console.error(e);
            return false;
        }

        return true;
    }

    // 🍱 Initialize resources to render triangle (buffers, shaders, pipeline)
    async initializeResources() {
        // 🔺 Buffers
        const createBuffer = (
            arr: Float32Array | Uint16Array,
            usage: number
        ) => {
            // 📏 Align to 4 bytes (thanks @chrimsonite)
            let desc = {
                size: (arr.byteLength + 3) & ~3,
                usage,
                mappedAtCreation: true
            };
            let buffer = this.device.createBuffer(desc);
            const writeArray =
                arr instanceof Uint16Array
                    ? new Uint16Array(buffer.getMappedRange())
                    : new Float32Array(buffer.getMappedRange());
            writeArray.set(arr);
            buffer.unmap();
            return buffer;
        };

        this.positionBuffer = createBuffer(positions, GPUBufferUsage.VERTEX);
        this.colorBuffer = createBuffer(colors, GPUBufferUsage.VERTEX);
        this.indexBuffer = createBuffer(indices, GPUBufferUsage.INDEX);

        // 🖍 Shaders
        const vsmDesc = {
            code: vertShaderCode
        };
        this.vertModule = this.device.createShaderModule(vsmDesc);

        const fsmDesc = {
            code: fragShaderCode
        };
        this.fragModule = this.device.createShaderModule(fsmDesc);

        // ⚗ Graphics Pipeline

        // 🔣 Input Assembly
        const positionAttribDesc: GPUVertexAttribute = {
            shaderLocation: 0, // [[location(0)]]
            offset: 0,
            format: 'float32x3'
        };
        const colorAttribDesc: GPUVertexAttribute = {
            shaderLocation: 1, // [[location(1)]]
            offset: 0,
            format: 'float32x3'
        };
        const positionBufferDesc: GPUVertexBufferLayout = {
            attributes: [positionAttribDesc],
            arrayStride: 4 * 3, // sizeof(float) * 3
            stepMode: 'vertex'
        };
        const colorBufferDesc: GPUVertexBufferLayout = {
            attributes: [colorAttribDesc],
            arrayStride: 4 * 3, // sizeof(float) * 3
            stepMode: 'vertex'
        };

        // 🌑 Depth
        const depthStencil: GPUDepthStencilState = {
            depthWriteEnabled: true,
            depthCompare: 'less',
            format: 'depth24plus-stencil8'
        };

        // 🦄 Uniform Data
        const pipelineLayoutDesc = { bindGroupLayouts: [] };
        const layout = this.device.createPipelineLayout(pipelineLayoutDesc);

        // 🎭 Shader Stages
        const vertex: GPUVertexState = {
            module: this.vertModule,
            entryPoint: 'main',
            buffers: [positionBufferDesc, colorBufferDesc]
        };

        // 🌀 Color/Blend State
        const colorState: GPUColorTargetState = {
            format: 'bgra8unorm'
        };

        const fragment: GPUFragmentState = {
            module: this.fragModule,
            entryPoint: 'main',
            targets: [colorState]
        };

        // 🟨 Rasterization
        const primitive: GPUPrimitiveState = {
            frontFace: 'cw',
            cullMode: 'none',
            topology: 'triangle-list'
        };

        const pipelineDesc: GPURenderPipelineDescriptor = {
            layout,

            vertex,
            fragment,

            primitive,
            depthStencil
        };
        this.pipeline = this.device.createRenderPipeline(pipelineDesc);
    }

    // ↙ Resize swapchain, frame buffer attachments
    resizeBackings() {
        // ⛓ Swapchain
        if (!this.context) {
            this.context = this.canvas.getContext('webgpu');
            const canvasConfig: GPUCanvasConfiguration = {
                device: this.device,
                format: 'bgra8unorm',
                usage:
                    GPUTextureUsage.RENDER_ATTACHMENT |
                    GPUTextureUsage.COPY_SRC,
                    alphaMode: 'opaque'
            };
            this.context.configure(canvasConfig);
        }

        const depthTextureDesc: GPUTextureDescriptor = {
            size: [this.canvas.width, this.canvas.height, 1],
            dimension: '2d',
            format: 'depth24plus-stencil8',
            usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
        };

        this.depthTexture = this.device.createTexture(depthTextureDesc);
        this.depthTextureView = this.depthTexture.createView();
    }

    // ✍ Write commands to send to the GPU
    encodeCommands() {
        let colorAttachment: GPURenderPassColorAttachment = {
            view: this.colorTextureView,
            clearValue: { r: 0, g: 0, b: 0, a: 1 },
            loadOp: 'clear',
            storeOp: 'store'
        };

        const depthAttachment: GPURenderPassDepthStencilAttachment = {
            view: this.depthTextureView,
            depthClearValue: 1,
            depthLoadOp: 'clear',
            depthStoreOp: 'store',
            stencilClearValue: 0,
            stencilLoadOp: 'clear',
            stencilStoreOp: 'store'
        };

        const renderPassDesc: GPURenderPassDescriptor = {
            colorAttachments: [colorAttachment],
            depthStencilAttachment: depthAttachment
        };

        this.commandEncoder = this.device.createCommandEncoder();

        // 🖌 Encode drawing commands
        this.passEncoder = this.commandEncoder.beginRenderPass(renderPassDesc);
        this.passEncoder.setPipeline(this.pipeline);
        this.passEncoder.setViewport(
            0,
            0,
            this.canvas.width,
            this.canvas.height,
            0,
            1
        );
        this.passEncoder.setScissorRect(
            0,
            0,
            this.canvas.width,
            this.canvas.height
        );
        this.passEncoder.setVertexBuffer(0, this.positionBuffer);
        this.passEncoder.setVertexBuffer(1, this.colorBuffer);
        this.passEncoder.setIndexBuffer(this.indexBuffer, 'uint16');
        this.passEncoder.drawIndexed(3, 1);
        this.passEncoder.end();

        this.queue.submit([this.commandEncoder.finish()]);
    }

    render = () => {
        // ⏭ Acquire next image from context
        this.colorTexture = this.context.getCurrentTexture();
        this.colorTextureView = this.colorTexture.createView();

        // 📦 Write and submit commands to queue
        this.encodeCommands();

        // ➿ Refresh canvas
        requestAnimationFrame(this.render);
    };
}


text: export {};


text:
import Renderer from './renderer';

const canvas = document.getElementById('gfx') as HTMLCanvasElement;
canvas.width = canvas.height = 640;
const renderer = new Renderer(canvas);
renderer.start();


text:
export default class Renderer {
    canvas: HTMLCanvasElement;
    adapter: GPUAdapter;
    device: GPUDevice;
    queue: GPUQueue;
    context: GPUCanvasContext;
    colorTexture: GPUTexture;
    colorTextureView: GPUTextureView;
    depthTexture: GPUTexture;
    depthTextureView: GPUTextureView;
    positionBuffer: GPUBuffer;
    colorBuffer: GPUBuffer;
    indexBuffer: GPUBuffer;
    vertModule: GPUShaderModule;
    fragModule: GPUShaderModule;
    pipeline: GPURenderPipeline;
    commandEncoder: GPUCommandEncoder;
    passEncoder: GPURenderPassEncoder;
    constructor(canvas: any);
    start(): Promise<void>;
    initializeAPI(): Promise<boolean>;
    initializeResources(): Promise<void>;
    resizeBackings(): void;
    encodeCommands(): void;
    render: () => void;
}


text:
@fragment
fn main(@location(0) inColor: vec3f) -> @location(0) vec4f {
    return vec4f(inColor, 1);
}


text:
struct VSOut {
    @builtin(position) Position: vec4f,
    @location(0) color: vec3f,
 };

@vertex
fn main(@location(0) inPos: vec3f,
        @location(1) inColor: vec3f) -> VSOut {
    var vsOut: VSOut;
    vsOut.Position = vec4f(inPos, 1);
    vsOut.color = inColor;
    return vsOut;
}


text:
/*启动参数检测{{*/
if(_ARGV.github){
	loadcodex("\forms\main\tools\github.aardio");
	return;
}
elseif(_ARGV.sshInstall){
	import fsys.wow64;
	import process;
	import console;
	console.open();

	var prcs;
	fsys.wow64.disableRedirection(
		function(){
			var dest,port = string.match(_ARGV.sshInstall,"(.+)\:(\d+)");
			if(dest&&port){
				_ARGV.sshInstall = "-p" + port +" " + dest;
			}

			prcs = process("ssh","-t " +_ARGV.sshInstall + ` "echo -e '安装完成以后，您可以一次性复制所有服务器账号配置 - 然后在 winXray 主界面点击\e[1;31m「批量导入链接」\e[0m即可，winXray将逐行识别有效的服务器分享链接或通用JSON配置，并忽略无效的行。如果 CentOS 8安装失败 - 可尝试更换为 CentOS 7 并重新安装。\n';firewall-cmd --permanent --add-port=80/tcp;firewall-cmd --permanent --add-port=443/tcp;firewall-cmd --reload;iptables -A INPUT -p tcp --dport 80 -j ACCEPT;iptables -A INPUT -p tcp --dport 443 -j ACCEPT;wget -P /root -N --no-check-certificate ""https://raw.githubusercontent.com/mack-a/v2ray-agent/master/install.sh"" && chmod 700 /root/install.sh && /root/install.sh"`)
				if(!prcs){
					if(_WIN10_LATER){
						import process.control;
					process.control("ms-settings:optionalfeatures");
					console.log("请检查是否指定了正确的SSH端口,或尝试重新安装 OpenSSH.Client");
					}
					else {
						console.log("此功能仅支持 Windows 10 系统");
					}
				}
				else {
					import process.job.limitKill;
					prcs.assignToJobObject(process.job.limitKill);
					prcs.wait();
				}

				console.pause();
		}
	)

	return;
}
elseif(_ARGV.sshLogin){
	import fsys.wow64;
	import process;
	import console;
	console.open();

	var prcs;
	fsys.wow64.disableRedirection(
		function(){
			var dest,port = string.match(_ARGV.sshLogin,"(.+)\:(\d+)");
			if(dest&&port){
				_ARGV.sshLogin = "-p" + port +" " + dest;
			}

			prcs = process("ssh","-t " +_ARGV.sshLogin + ``)
				if(!prcs){
					if(_WIN10_LATER){
						import process.control;
					process.control("ms-settings:optionalfeatures");
					console.log("请检查是否指定了正确的SSH端口,或尝试重新安装 OpenSSH.Client");
					}
					else {
						console.log("此功能仅支持 Windows 10 系统");
					}
				}
				else {
					import process.job.limitKill;
					prcs.assignToJobObject(process.job.limitKill);
					prcs.wait();
				}

				console.pause();
		}
	)

	return;
}
elseif(_ARGV.sshInstallKey){
	import fsys.wow64;
	import process;
	import console;
	console.open();

	var prcs;
	fsys.wow64.disableRedirection(
		function(){
			var sshKeyPath = io.getSpecial(0x28/*_CSIDL_PROFILE*/,"/.ssh/id_rsa.pub") ;
			var keyData = string.load(sshKeyPath);
			if(!keyData){
					var prcs = process.popen("ssh-keygen",` -t rsa -f "`+io.getSpecial(0x28/*_CSIDL_PROFILE*/,"/.ssh/id_rsa")+`" -y`);
					keyData = prcs? prcs.read(-1);
			}

			if(!keyData){
				if(_WIN10_LATER){
						import process.control;
					process.control("ms-settings:optionalfeatures");
					console.log("请检查是否指定了正确的SSH端口,或尝试重新安装 OpenSSH.Client");
					}
					else {
						console.log("此功能仅支持 Windows 10 系统");
					}
			}
			else{
				var dest,port = string.match(_ARGV.sshInstallKey,"(.+)\:(\d+)");
				if(dest&&port){
					_ARGV.sshInstallKey = "-p" + port +" " + dest;
				}

				prcs = process("ssh","-t " +_ARGV.sshInstallKey + ` "mkdir -p ~/.ssh;chmod 700 ~/.ssh;chmod 600 ~/.ssh/authorized_keys;echo '`+keyData+`' > ~/.ssh/authorized_keys"`)
					if(!prcs){
						if(_WIN10_LATER){
							import process.control;
						process.control("ms-settings:optionalfeatures");
						console.log("请检查是否指定了正确的SSH端口,或尝试重新安装 OpenSSH.Client");
						}
						else {
							console.log("此功能仅支持 Windows 10 系统");
						}
					}
					else {
						import process.job.limitKill;
						prcs.assignToJobObject(process.job.limitKill);
						prcs.wait();
					}
				}

				console.pause();
		}
	)

	return;
}
elseif(_ARGV.updateTime){
	import time.ntp;
	time.ntp.updateSystemTime();
	return;
}
else {
	import process;
	import fsys.update.simpleMain;

	if( fsys.update.simpleMain(
		"winXray(Xray/V2Ray、Shadowsocks、Trojan通用客户端 )",
		process().isWow64() ? "https://raw.githubusercontent.com/winXray/winXray/master/release/update/version.txt"
			: "https://raw.githubusercontent.com/winXray/winXray/master/release/update32/version.txt",
		..io.appData("/winXray/update"),
		function(version,description,status){})){
		return 0;
	}
}

/*}}*/

import fonts.fontAwesome;
import win.ui;
/*DSG{{*/
mainForm = win.form(text="winXray";right=1019;bottom=679;bgcolor=15793151;border="none")
mainForm.add(
caption={cls="bkplus";text="winXray 2.3";left=67;top=9;right=727;bottom=27;align="left";color=6052956;dl=1;dt=1;font=LOGFONT(h=-14);z=7};
custom={cls="custom";left=83;top=40;right=1022;bottom=679;bgcolor=16777215;db=1;dl=1;dr=1;dt=1;z=4};
logo={cls="bkplus";text='\uF1D9';left=35;top=7;right=64;bottom=32;color=3054125;dl=1;dt=1;font=LOGFONT(h=-18;name='FontAwesome');z=6};
navBar={cls="bkplus";left=0;top=37;right=83;bottom=681;bgcolor=3442175;db=1;dl=1;dt=1;z=1};
navJsonConfig={cls="plus";text="配置";left=0;top=132;right=85;bottom=212;bkBottom=3;bkLeft=7;bkRight=8;bkTop=2;border={color=-65536};color=16777215;dl=1;dt=1;font=LOGFONT(h=-13);iconStyle={font=LOGFONT(h=-37;name='FontAwesome');padding={bottom=20}};iconText='\uF0F6';notify=1;textPadding={bottom=10};valign="bottom";x=0.5;y=0.2;z=5};
navStart={cls="plus";text="首页";left=0;top=48;right=85;bottom=128;bkBottom=3;bkLeft=7;bkRight=8;bkTop=2;border={color=-65536};color=16777215;dl=1;dt=1;font=LOGFONT(h=-13);iconStyle={font=LOGFONT(h=-37;name='FontAwesome');padding={bottom=20}};iconText='\uF015';notify=1;textPadding={bottom=10};valign="bottom";x=0.5;y=0.2;z=3};
navTools={cls="plus";text="工具";left=0;top=216;right=85;bottom=296;bkBottom=3;bkLeft=7;bkRight=8;bkTop=2;border={color=-65536};color=16777215;dl=1;dt=1;font=LOGFONT(h=-13);iconStyle={font=LOGFONT(h=-37;name='FontAwesome');padding={bottom=20}};iconText='\uF0AD';notify=1;textPadding={bottom=10};valign="bottom";x=0.5;y=0.2;z=8};
titleBar={cls="bkplus";left=0;top=0;right=1022;bottom=38;bgcolor=8036607;dl=1;dr=1;dt=1;forecolor=16777215;linearGradient=180;z=2}
)
/*}}*/

import win.ui.atom;
var atom,hwnd = mainForm.atom("DFA5667E-1D8C-49C0-8918-C6FEC2DECCF8");
if(!atom){
	win.showForeground(hwnd);
	win.quitMessage();
	return;
}

import xray.core;
if(!xray.core.getPath()) {
	mainForm.close();
	return;
}

import win.ui.simpleWindow;
win.ui.simpleWindow( mainForm );

import win.dlg.message;
win.dlg.message.install();

import win.ui.tabs;
var tbs = win.ui.tabs(
	mainForm.navStart,
	mainForm.navJsonConfig,
	mainForm.navTools
);

tbs.skin({
	background={
		active=0xFFFFFFFF;
		default=0x00FFFFFF;
		hover=0x38FFFFFF
	};
	color={
		default=0xFFFFFFFF;
	};
	checked={
		background={default=0xFFFFFFFF;};
		color={default=0xff86a543;};
	}
})

tbs.loadForm(1,"\forms\main\xray.aardio" );
tbs.loadForm(2,"\forms\main\config\jsonConfig.aardio" );
tbs.loadForm(3,"\forms\main\tools\tools.aardio");

tbs.selIndex = 1;

import win.ui.menu;
mainForm.wndproc = {
	[0xACCF/*_WM_TRAYMESSAGE*/ ] = function(hwnd,message,wParam,lParam){
		if( lParam = 0x205/*_WM_RBUTTONUP*/ ){
			win.setForeground(mainForm.hwnd)
			mainForm.popmenu = win.ui.popmenu(mainForm);
			mainForm.popmenu.add('自动切换到最快的服务器',function(id){
				publish("uiCommand.restartXrayCore",)
			});
			mainForm.popmenu.add('立即更新所有订阅源',function(id){
				xray.outbounds.updateSubscription();
			});
			mainForm.popmenu.add();

			import sysProxy;
			import xray.core;

			var id = mainForm.popmenu.add('不使用代理',function(id){
				sysProxy.switch("direct");
			});
			mainForm.popmenu.check(id,config.proxy.mode=="direct",0/*_MF_BYCOMMAND*/);

			var id = mainForm.popmenu.add('使用全局代理',function(id){
				sysProxy.switch("proxy");
			});
			mainForm.popmenu.check(id,config.proxy.mode=="proxy",0/*_MF_BYCOMMAND*/);

			var id = mainForm.popmenu.add('使用 PAC 自动代理',function(id){
				sysProxy.switch("pac");
			});
			mainForm.popmenu.check(id,config.proxy.mode=="pac",0/*_MF_BYCOMMAND*/);

			mainForm.popmenu.add();

			var id = mainForm.popmenu.add('编辑 PAC 配置',function(id){
				publish("uiCommand.showPacForm");
			});

			mainForm.popmenu.add();

			if(_WIN10_LATER){
				mainForm.popmenu.add('打开系统代理设置',function(id){
					import process.control;
					process.control("ms-settings:network-proxy")
				});
				mainForm.popmenu.add('打开 Internet 代理选项',function(id){
					import process.control;
					process.control("inetcpl.cpl",,4);
				});
			}
			else {
				mainForm.popmenu.add('打开系统代理设置',function(id){
					import process.control;
					process.control("inetcpl.cpl",,4);
				});
			}

			mainForm.popmenu.add('打开网卡连接',function(id){
				import process;
				process.explore("shell:::{7007ACC7-3202-11D1-AAD2-00805FC1270E}");
			});
			mainForm.popmenu.add();

			mainForm.popmenu.add('获取 winXray 最新源代码',function(id){
				import process;
				process.openUrl("https://github.com/search?q=winXray+license%3AUnlicense+fork%3Atrue+sort%3Aupdated")
			});

			import xray.core;
			import chrome.path;
			var chromePath = chrome.path();
			if(chromePath && xray.core.socksProxyPort){
				mainForm.popmenu.add('使用 SOCKS5 代理打开浏览器',function(id){
					import process
					process.execute(chromePath,` --proxy-server="SOCKS5://127.0.0.1:`+xray.core.socksProxyPort
						+`" --user-data-dir="` +io.appData("winXray/chrome-socks5")+ `" https://www.google.com`);
				});
			}

			mainForm.popmenu.add();
			mainForm.popmenu.add('退出',function(id){
				mainForm.onClose = null;
				mainForm.close()
			});

			var pt = ::POINT();
			::User32.GetCursorPos(pt);
			mainForm.popmenu.popup(pt.x,pt.y,true)
		}
		elseif( lParam = 0x203/*_WM_LBUTTONDBLCLK*/) {
			if(win.isIconic(mainForm.hwnd)){
				mainForm.show(9/*_SW_RESTORE*/);
			}
			else {
				mainForm.show();
			}

			win.setForeground(mainForm.hwnd);
		}
	}
}

mainForm.enableDpiScaling();

mainForm.onDestroy = function(){
	mainForm.tray.delete();
}

import win.util.tray;
mainForm.onClose = function(hwnd,message,wParam,lParam){
	if(!mainForm.tray){
		mainForm.tray = win.util.tray(mainForm);
	}
	else {
		mainForm.tray.reset();
	}

	mainForm.show(false);
	return true;
}

mainForm.tray = win.util.tray(mainForm)
if(!_ARGV.tray){
	mainForm.show();
}

return win.loopMessage();

mime_type: text/x-java