function loadFootsteps() {
	%pattern = "Add-Ons/GameMode_Minecraft_New/res/footsteps/*.wav";

	for (%file = findFirstFile(%pattern); %file !$= ""; %file = findNextFile(%pattern)) {
		%base = fileBase(%file);
		%length = strLen(%base);

		%mat = getSubStr(%base, 0, %length - 1);
		%num = getSubStr(%base, %length - 1, 1);

		if (%num > mFloor($Footsteps::MaterialNum[%mat])) {
			$Footsteps::MaterialNum[%mat] = %num;
		}

		%name = "footstepSound_" @ %base;
		%db = nameToID(%name);

		if (!isObject(%db)) {
			datablock audioProfile(temporaryAudioProfile) {
				preload = true;
				fileName = %file;
				description = audioDefault3D;
			};

			%db = nameToID("temporaryAudioProfile");

			if (!isObject(%db)) {
				error("ERROR: Failed to create AudioProfile!");
				continue;
			}

			%db.setName(%name);
		}
	}
}

function Player::footstepUpdateTick(%this) {
	cancel(%this.footstepUpdateTick);

	if (%this.getState() $= "Dead") {
		return;
	}

	%tick = 0;
	%pending = isEventPending(%this.footstepTick);

	if (vectorLen(%this.getVelocity()) >= 0.5 && !%this.isMounted()) {
		if (!%this.trigger[3] && !(%this.trigger[4] && %this.getDataBlock().canJet)) {
			%ray = containerRayCast(
				vectorAdd(%this.position, "0 0 0.05"),
				vectorSub(%this.position, "0 0 0.05"),
				$TypeMasks::All, %this
			);

			if (%ray !$= "0") {
				%tick = 1;
			}
		}
	}

	if (%tick && !%pending) {
		%this.footstepTick = %this.schedule(100, "footstepTick");
	}
	else if (!%tick && %pending) {
		cancel(%this.footstepTick);
	}

	%this.footstepUpdateTick = %this.schedule(40, "footstepUpdateTick");
}

function Player::footstepTick(%this) {
	cancel(%this.footstepTick);

	if (%this.getState() $= "Dead") {
		return;
	}

	%this.playFootstepSound(%this.getFootstepMaterial());
	%this.footstepTick = %this.schedule(310, "footstepTick");
}

function Player::playFootstepSound(%this, %material) {
	if (%material $= "null") {
		return;
	}

	if (%material $= "") {
		%material = "concrete";
	}

	%dataBlock = %this.getDataBlock();

	if (%dataBlock.footstepMaterial !$= "") {
		if (%dataBlock.alternateFootstepMaterial[%material] $= "") {
			%material = %dataBlock.footstepMaterial;
		}
		else {
			%material = %dataBlock.alternateFootstepMaterial[%material];
		}
	}

	if (mFloor($Footsteps::MaterialNum[%material]) <= 0) {
		return;
	}

	%num = getRandom(1, $Footsteps::MaterialNum[%material]);
	%profile = nameToID("footstepSound_" @ %material @ %num);

	if (!isObject(%profile)) {
		return;
	}

	serverPlay3D(%profile, %this.getPosition());
}

function Player::getFootstepMaterial(%this) {
	%ray = containerRayCast(
		vectorAdd(%this.position, "0 0 0.1"),
		vectorSub(%this.position, "0 0 0.1"),
		$TypeMasks::All, %this
	);

	if (%ray $= "0") {
		return "null";
	}

	%col = firstWord(%ray);

	if (%col.getClassName() !$= "fxDTSBrick") {
		return "";
	}

	return %col.getDataBlock().footstepMaterial;
}

loadFootsteps();
