let dirCurrent = GetCurrentScriptDirectory();
let path1 = dirCurrent ~ "img/effect32.png";
let path2 = dirCurrent ~ "img/effect36.png";

let typeEnd = 0;
let END_FAILED = 1;
let END_SUCCESS = 2;


@Initialize
{
	let pathUseSpell = dirCurrent ~ "se/seUseSpellCard.wav";
	LoadSound(pathUseSpell);
	PlaySE(pathUseSpell);
	endSpell;
	MagicCircle(path1, 120, -2.5, 1, 0.15, 255);
	MagicCircle(path2, 130, 2.5, 1, 0.15, 175);
}

@MainLoop
{
	yield;
}

@Event
{
	alternative(GetEventType())
	case(EV_END_BOSS_STEP)
	{
		//次の敵動作へ
		if(typeEnd == 0)
		{
			//スペルカード取得失敗
			typeEnd = END_FAILED;
		}
	}
	case(EV_GAIN_SPELL)
	{
		//スペルカード取得
		typeEnd = END_SUCCESS;
	}
}

//texture path, outer radius at rest, spin per frame, number of frames per revolution, scale amplitude (|amplitude| < 1), alpha
task MagicCircle(path, radius, spin, pulsePeriod, pulseAmplitude, alpha)
{
	let countVertex = 128;
	let listRadius = [];
	loop(countVertex) {
		listRadius = listRadius ~ [radius];
	}
	
	let obj = ObjPrim_Create(OBJ_PRIMITIVE_2D);
	ObjPrim_SetPrimitiveType(obj, PRIMITIVE_TRIANGLESTRIP);
	ObjPrim_SetVertexCount(obj, countVertex);
	ObjRender_SetBlendType(obj, BLEND_ALPHA);
	ObjRender_SetAlpha(obj, 0);
	Obj_SetRenderPriority(obj, 0.22);
	ObjPrim_SetTexture(obj, path);
	
	ascent(iVert in 0..countVertex / 2){
		let left = iVert * 24;
		let indexVert = iVert * 2;
		ObjPrim_SetVertexUVT(obj, indexVert + 0, left, 0);
		ObjPrim_SetVertexUVT(obj, indexVert + 1, left, 16);		
	}
	
	let bossObj = GetEnemyBossObjectID[0];

	let frame = 0;
	let angleRender = 0;
	let fadeBuffer = 30;
	let newAlpha = 0;
	
	while (fadeBuffer > 0) {

		angleRender += spin;
		
		ascent(iVert in 0..countVertex / 2)	{
			let indexVert = iVert * 2;
			let angle = 360 / (countVertex / 2 - 1) * iVert;
			
			let vx1 = listRadius[indexVert] * cos(angle);
			let vy1 = listRadius[indexVert] * sin(angle);
			ObjPrim_SetVertexPosition(obj, indexVert + 0, vx1, vy1, 0);

			let vx2 = listRadius[indexVert+1] * cos(angle);
			let vy2 = listRadius[indexVert+1] * sin(angle);
			ObjPrim_SetVertexPosition(obj, indexVert + 1, vx2, vy2, 0);
			
			listRadius[indexVert + 0] = radius + pulseAmplitude * radius * sin((360 / pulsePeriod) * frame) + 8;
			listRadius[indexVert + 1] = listRadius[indexVert + 0] * 0.9;
		}
		
		if (typeEnd == 0) {
			if (newAlpha < alpha) {
				newAlpha += alpha / 60;
			}
		} else {
			newAlpha -= alpha / 30;
			fadeBuffer--;
		}
		ObjRender_SetAlpha(obj, newAlpha);
		
		if (!Obj_IsDeleted(bossObj)) {
			ObjRender_SetPosition(obj, ObjRender_GetX(bossObj), ObjRender_GetY(bossObj), 0);
		}
		ObjRender_SetAngleZ(obj, angleRender);
		frame++;
		yield;
	}
	
	Obj_Delete(obj);
}

task endSpell
{
	while (typeEnd == 0) {yield;}
	
	if (typeEnd == END_SUCCESS) {
		let pathGainSpell = dirCurrent ~ "se/se_cardget.wav";
		LoadSound(pathGainSpell);
		PlaySE(pathGainSpell);
	}
		loop(240) {yield;}
		CloseScript(GetOwnScriptID());
		return;
}


