//
// Generated by dtk
// Translation Unit: d_chain.cpp
//

#include "d/dolzel.h" // IWYU pragma: keep
#include "d/d_chain.h"
#include "d/d_a_obj.h"
#include "d/d_s_play.h"
#include "m_Do/m_Do_mtx.h"

#include "assets/l_chainS3TCTEX__d_chain.h"
const u16 l_chainS3TCTEX__width = 32;
const u16 l_chainS3TCTEX__height = 32;

#include "assets/l_pos__d_chain.h"
#include "assets/l_texCoord__d_chain.h"

#include "assets/l_chainDL__d_chain.h"

#include "assets/l_matDL__d_chain.h"
l_matDL__d_chain(l_chainS3TCTEX);

/* 800628B4-80062954       .text __ct__15dChain_packet_cFiP12dKy_tevstr_cf */
dChain_packet_c::dChain_packet_c(int num, dKy_tevstr_c* tevstr, f32 scale) {
    mNum = num;
    mScale.setall(scale);
    mpTevStr = tevstr;
    mPt = new cXyz[mNum];
}

/* 80062954-800629B0       .text __dt__15dChain_packet_cFv */
dChain_packet_c::~dChain_packet_c() {
}

/* 800629B0-80062CB0       .text draw__15dChain_packet_cFv */
void dChain_packet_c::draw() {
    GXClearVtxDesc();
    GXSetVtxDesc(GX_VA_POS, GX_INDEX8);
    GXSetVtxDesc(GX_VA_TEX0, GX_INDEX8);
    GXSetVtxAttrFmt(GX_VTXFMT0, GX_VA_POS, GX_POS_XYZ, GX_F32, 0);
    GXSetVtxAttrFmt(GX_VTXFMT0, GX_VA_TEX0, GX_TEX_ST, GX_F32, 0);
    GXSetArray(GX_VA_POS, l_pos, sizeof(*l_pos));
    GXSetArray(GX_VA_TEX0, l_texCoord, sizeof(*l_texCoord));
    dKy_GxFog_tevstr_set(mpTevStr);
    GXCallDisplayList(l_matDL, 0xa0);
    GXSetTevColorS10(GX_TEVREG0, mpTevStr->mColorC0);
    GXSetTevColor(GX_TEVREG1, mpTevStr->mColorK0);
    GXSetCurrentMtx(GX_PNMTX0);

    cXyz* points = mPt;
    f32 segmentLen = (REG10_F(11) + 6.75f) * mScale.z;
    s16 angle = 0;
    cXyz pos = *points;
    for (s32 i = 0; i < mNum - 1; i++) {
        cXyz dir = points[i+1] - pos;
        f32 len = dir.abs();
        if (!dir.normalizeRS())
            continue;

        Quaternion quat;
        daObj::quat_rotBaseZ(&quat, dir);
        while (len > 0.0f) {
            mDoMtx_stack_c::transS(pos);
            mDoMtx_stack_c::quatM(&quat);
            mDoMtx_stack_c::ZrotM(angle);
            mDoMtx_stack_c::scaleM(mScale);
            mDoMtx_stack_c::revConcat(j3dSys.getViewMtx());
            GXLoadPosMtxImm(mDoMtx_stack_c::get(), GX_PNMTX0);
            GXCallDisplayList(l_chainDL, 0x60);
            len -= segmentLen;
            pos += dir * segmentLen;
            angle += 0x4000;
        }
    }
}

/* 80062CB0-80062D30       .text dChain_packet_create__FiP12dKy_tevstr_cf */
dChain_packet_c* dChain_packet_create(int p0, dKy_tevstr_c* tevstr, f32 f0) {
    dChain_packet_c* chain = new dChain_packet_c(p0, tevstr, f0);
    if (chain != NULL && chain->mPt == NULL)
        chain = NULL;
    return chain;
}
