-- LegacyWorlds Beta 6
-- PostgreSQL database scripts
--
-- A few types and internal functions used in most parts
-- of the universe generator.
--
-- Copyright(C) 2004-2012, DeepClone Development
-- --------------------------------------------------------


/* The coordinates of the area being generated. */
DROP TYPE IF EXISTS verse.generator_area_type CASCADE;
CREATE TYPE verse.generator_area_type AS (
	x0 INT , y0 INT ,
	x1 INT , y1 INT
);



/*
 * List some quantity of random planets from an area of the universe
 * 
 * This function returns a set of planet identifiers chosen at random from the
 * specified area of the universe.
 * 
 * Parameters:
 *		_area		The area to select planets from
 *		_count		The maximal amount of planets to return
 */
DROP FUNCTION IF EXISTS verse.list_random_planets_in( verse.generator_area_type , INT );
CREATE FUNCTION verse.list_random_planets_in( _area verse.generator_area_type , _count INT )
	RETURNS SETOF INT
	STRICT VOLATILE
	SECURITY INVOKER
AS $list_random_planets_in$

	SELECT _planets.name_id
		FROM verse.planets _planets
			INNER JOIN verse.systems _systems
				ON _planets.system_id = _systems.id
		WHERE _systems.x BETWEEN $1.x0 AND $1.x1
			AND _systems.y BETWEEN $1.y0 AND $1.y1
		ORDER BY RANDOM( )
		LIMIT $2;

$list_random_planets_in$ LANGUAGE SQL;

REVOKE EXECUTE
	ON FUNCTION verse.list_random_planets_in( verse.generator_area_type ,
			INT )
	FROM PUBLIC;