/**
 * Mandelbulber v2, a 3D fractal generator  _%}}i*<.        ____                _______
 * Copyright (C) 2020 Mandelbulber Team   _>]|=||i=i<,     / __ \___  ___ ___  / ___/ /
 *                                        \><||i|=>>%)    / /_/ / _ \/ -_) _ \/ /__/ /__
 * This file is part of Mandelbulber.     )<=i=]=|=i<>    \____/ .__/\__/_//_/\___/____/
 * The project is licensed under GPLv3,   -<>>=|><|||`        /_/
 * see also COPYING file in this folder.    ~+{i%+++
 *
 * Mandeltorus by Aexion
 * @reference http://www.fractalforums.com/the-3d-mandelbulb/mandeldonuts/

 * This file has been autogenerated by tools/populateUiInformation.php
 * from the file "fractal_mandeltorus_v2.cpp" in the folder formula/definition
 * D O    N O T    E D I T    T H I S    F I L E !
 */

REAL4 MandeltorusV2Iteration(REAL4 z, __constant sFractalCl *fractal, sExtendedAuxCl *aux)
{
	if (fractal->transformCommon.functionEnabledFalse
			&& aux->i >= fractal->transformCommon.startIterationsD
			&& aux->i < fractal->transformCommon.stopIterationsD1) // pre-scale
	{
		z *= fractal->transformCommon.scale3D111;
		aux->DE *= length(z) / aux->r;
	}

	REAL power1 = fractal->bulb.power;						// Longitude power, symmetry
	REAL power2 = fractal->transformCommon.pwr8a; // Latitude power

	REAL off1p5 = 1.0f;

	if (aux->i >= fractal->transformCommon.startIterationsE
			&& aux->i < fractal->transformCommon.stopIterationsE)
	{
		off1p5 = fractal->transformCommon.offset105;
	}

	REAL rh = native_sqrt(z.x * z.x + z.y * z.y);

	REAL phi = atan2(z.y, z.x) + fractal->transformCommon.offset0;
	REAL phipow = phi * power1;

	REAL theta = atan2(rh, z.z);

	REAL px = z.x - native_cos(phi) * off1p5;
	REAL py = z.y - native_sin(phi) * off1p5;
	REAL rhrad = native_sqrt(px * px + py * py + z.z * z.z);
	REAL rh1 = pow(rhrad, power2);
	REAL rh2 = pow(rhrad, power1);

	if (!fractal->transformCommon.functionEnabledzFalse) // mode 1
	{
		REAL thetapow = theta * power2;
		REAL sintheta = native_sin(thetapow) * rh2;
		z.x = sintheta * native_cos(phipow);
		z.y = sintheta * native_sin(phipow);
		z.z = native_cos(thetapow) * rh1; // mode 1
	}
	else // mode 2
	{
		REAL tangle = atan2(native_sqrt(px * px + py * py), z.z) * power2;
		REAL sintheta = (1.5f + native_cos(tangle)) * rh2;
		z.x = sintheta * native_cos(phipow);
		z.y = sintheta * native_sin(phipow);
		z.z = native_sin(tangle) * rh1; // mode 2
	}

	// DEcalc
	REAL temp = rh2 * (power1 - fractal->analyticDE.offset2);
	if (fractal->transformCommon.functionEnabledAyFalse)
		temp = min(temp, rh1 * (power2 - fractal->analyticDE.offset2));

	if (!fractal->analyticDE.enabledFalse)
	{
		aux->DE = temp * aux->DE + 1.0f;
	}
	else
	{
		aux->DE = temp * aux->DE * fractal->analyticDE.scale1 + fractal->analyticDE.offset1;
	}
	return z;
}