Ejemplo n.º 1
0
void CL_Collada_Material_Impl::load_material(CL_DomElement &material_element, std::vector<CL_Collada_Effect> &effects)
{
	id = material_element.get_attribute("id");

	CL_DomElement instance_effect_element = material_element.named_item("instance_effect").to_element();
	if (instance_effect_element.is_null())
		throw CL_Exception("Only instance_effect materials are supported");

	CL_String url = instance_effect_element.get_attribute("url");
	url = url.substr(1);	// Remove the initial '#' symbol

	std::vector<CL_Collada_Effect>::size_type size, cnt;
	size = effects.size();
	for (cnt=0; cnt< size; cnt++)
	{
		if (effects[cnt].get_id() == url)
		{
			effect = effects[cnt];
			break;
		}
	}

	if (effect.is_null())
		throw CL_Exception("Unable to find effect");

}
Ejemplo n.º 2
0
void CL_DomElement::set_child_string_ns(const CL_DomString &namespace_uri, const CL_DomString &qualified_name, const CL_DomString &value)
{
	CL_DomString local_name;
	CL_DomString::size_type pos = qualified_name.find(L':');
	if (pos != CL_DomString::npos)
		local_name = qualified_name.substr(pos+1);
	else
		local_name = qualified_name;

	CL_DomElement element = named_item_ns(namespace_uri, local_name).to_element();
	if (element.is_null())
	{
		element = get_owner_document().create_element_ns(namespace_uri, qualified_name);
		append_child(element);
	}

	CL_DomText dom_text = get_owner_document().create_text_node(value);
	if (element.get_first_child().is_text())
	{
		CL_DomNode temp_domnode = element.get_first_child();
		replace_child(dom_text, temp_domnode);
	}
	else
	{
		element.append_child(dom_text);
	}
}
Ejemplo n.º 3
0
CL_DomString CL_DomElement::get_child_string_ns(const CL_DomString &namespace_uri, const CL_DomString &local_name, const CL_DomString &default_value) const
{
	CL_DomElement element = named_item_ns(namespace_uri, local_name).to_element();
	if (!element.is_null() && element.get_first_child().is_text())
		return element.get_first_child().to_text().get_node_value();
	else
		return default_value;
}
Ejemplo n.º 4
0
void BBN_Prob::load_from_xml(CL_DomElement element)
{
  DEBUG_MSG("BBN_Prob::load_from_xml(CL_DomElement) - Called.")

	_probability = CL_StringHelp::text_to_float(element.get_attribute("value"));
  DEBUG_MSG("BBN_Prob::load_from_xml(CL_DomElement) - Prob value = '" + CL_StringHelp::float_to_text(_probability) + "'.")

	_option = static_cast<CL_String8>(element.get_attribute("option"));
	DEBUG_MSG("BBN_Prob::load_from_xml(CL_DomElement) - Prob option = '" + _option + "'.")
}
void CL_Collada_Effect_Texture_Impl::load_texture(CL_DomElement &profile_element, CL_DomElement &newparam_element, CL_DomElement &sampler2d_element, std::vector<CL_Collada_Image> &library_images)
{
	sid = newparam_element.get_attribute("sid");

	CL_DomElement source_element = sampler2d_element.named_item("source").to_element();
	if (source_element.is_null())
		throw CL_Exception("source is missing");

	CL_String source_name = source_element.get_text();

	// Find the corresponding surface
	CL_DomElement surface_element;
	CL_DomNode cur_child(profile_element.get_first_child());
	while (!cur_child.is_null())
	{
			if(cur_child.get_node_name() == "newparam")
			{
				CL_DomElement newparam_element = cur_child.to_element();
				CL_String new_sid = newparam_element.get_attribute("sid");
				if (new_sid == source_name)
				{
					surface_element = newparam_element.named_item("surface").to_element();
					if (!surface_element.is_null())
						break;	// Found match
				}
			}
			cur_child = cur_child.get_next_sibling();
	}

	if (surface_element.is_null())
		throw CL_Exception("Cannot find the corresponding surface");

	CL_DomElement init_from_element = surface_element.named_item("init_from").to_element();
	if (init_from_element.is_null())
		throw CL_Exception("Only init_from surfaces are supported");

	CL_String image_name = init_from_element.get_text();

	unsigned int size = library_images.size();
	for (unsigned int cnt=0; cnt < size; cnt++)
	{
		if (library_images[cnt].get_id() == image_name)
		{
			image = library_images[cnt];
			break;
		}
	}
	if (image.is_null())
		throw CL_Exception("Cannot find requested image in the image library");

}
Ejemplo n.º 6
0
void CL_Collada_Triangles_Impl::load_primitive(CL_DomElement &primitive_element)
{
	unsigned int count = stride * triangle_count * 3;

	primitive.resize(count);

	CL_String points = primitive_element.get_text();
	const CL_String::char_type *primitive_text = points.c_str();

	for (unsigned int cnt=0; cnt < count; cnt++)
	{
		if (!(*primitive_text))
			throw CL_Exception("Primitive data count mismatch");

		int value = atoi(primitive_text);
		primitive[cnt] = value;

		while(*primitive_text)
		{
			if (*(primitive_text++) <= ' ')	// Find whitespace
				break;
		}

		while(*primitive_text)
		{
			if ((*primitive_text) > ' ')	// Find end of whitespace
				break;
			primitive_text++;
		}

	}
	if (*primitive_text)
			throw CL_Exception("Primitive data count mismatch (end)");
}
Ejemplo n.º 7
0
void CL_Collada_Triangles_Impl::validate_vcount(CL_DomElement &vcount_element)
{
	CL_String points = vcount_element.get_text();
	const CL_String::char_type *vcount_text = points.c_str();

	for (unsigned int cnt=0; cnt < triangle_count; cnt++)
	{
		if (!(*vcount_text))
			throw CL_Exception("VCount data count mismatch");

		int value = atoi(vcount_text);

		if (value != 3)
			throw CL_Exception("Only triangles are supported. Export your mesh as triangles please");

		while(*vcount_text)
		{
			if (*(vcount_text++) <= ' ')	// Find whitespace
				break;
		}

		while(*vcount_text)
		{
			if ((*vcount_text) > ' ')	// Find end of whitespace
				break;
			vcount_text++;
		}

	}
	if (*vcount_text)
			throw CL_Exception("VCount data count mismatch (end)");
}
Ejemplo n.º 8
0
CL_DomDocument::CL_DomDocument(
	const CL_DomString &namespace_uri,
	const CL_DomString &qualified_name,
	const CL_DomDocumentType &document_type)
: CL_DomNode(CL_SharedPtr<CL_DomNode_Generic>(new CL_DomDocument_Generic))
{
	impl->owner_document = impl;
	CL_DomElement element = create_element(qualified_name);
	element.set_attribute("xmlns:" + element.get_prefix(), qualified_name);
	append_child(element);

	CL_DomDocument_Generic *doc = dynamic_cast<CL_DomDocument_Generic *>(impl.get());
	const CL_DomDocument_Generic *doctype = dynamic_cast<const CL_DomDocument_Generic *>(document_type.impl.get());
	doc->public_id = doctype->public_id;
	doc->system_id = doctype->system_id;
}
Ejemplo n.º 9
0
SpriteResource::SpriteResource(CL_Resource &resource)
: mResource(resource)
{
	GAME_ASSERT(mResource.get_type() == "sprite");

	std::string basePath = mResource.get_manager().get_directory(mResource).get_file_system().get_path();
	for (CL_DomElement element = mResource.get_element().get_first_child_element(); !element.is_null(); element = element.get_next_sibling_element())
		if (element.get_tag_name() == "image")
		{
			std::string fileName = element.get_attribute("file");
			if (fileName.empty())
				throw Exception("Sprite '" + mResource.get_name() + "' has empty or missing 'file' attribute");
			mFrames.insert(std::make_pair(basePath + fileName, Frame(fileName)));
		}

	if (mFrames.empty())
		throw Exception("Sprite '" + mResource.get_name() + "' has no frames");
}
Ejemplo n.º 10
0
CL_DomString CL_DomNode::find_prefix(const CL_DomString &namespace_uri) const
{
	CL_DomElement cur = to_element();
	while (!cur.is_null())
	{
		CL_DomNamedNodeMap attributes = cur.get_attributes();
		int size = attributes.get_length();
		for (int index = 0; index < size; index++)
		{
			CL_DomNode attribute = attributes.item(index);
			if (attribute.get_prefix() == "xmlns" &&
				attribute.get_node_value() == namespace_uri)
			{
				return attribute.get_local_name();
			}
		}
		cur = cur.get_parent_node().to_element();
	}
	return CL_DomString();
}
Ejemplo n.º 11
0
//рекурсивное клонирование XML-элемента
CL_DomElement cloneElement(CL_DomElement &element, CL_DomDocument &doc)
{
	//создаем элемент-клон
	CL_DomElement clone(doc, element.get_tag_name());

	//копируем атрибуты
	CL_DomNamedNodeMap attributes = element.get_attributes();
	unsigned long length = attributes.get_length();
	for (unsigned long i = 0; i < length; ++i)
	{
		CL_DomNode attr = attributes.item(i);
		clone.set_attribute(attr.get_node_name(), attr.get_node_value());
	}

	//рекурсивно копируем дочерние элементы
	for (CL_DomElement child = element.get_first_child_element(); !child.is_null(); child = child.get_next_sibling_element())
		clone.append_child(cloneElement(child, doc));

	//возвращаем клонированный элемент
	return clone;
}
Ejemplo n.º 12
0
TileMap::TileMap(CL_GraphicContext& gc, CL_ResourceManager& resmgr, const CL_String& tileset)
: map_width(0), map_height(0), cur_map_x(0), cur_map_y(0) {
    CL_Resource res = resmgr.get_resource(tileset);

    if (res.get_type() != "tilemap")
        throw CL_Exception(cl_format("Resource %1 is not a tilemap", tileset));

    CL_DomElement element = res.get_element();
    levelname = element.get_attribute("name");
    CL_String resource_name = element.get_attribute("resource");
    map_width = element.get_attribute_int("width");
    map_height = element.get_attribute_int("height");

    tiles = CL_Sprite(gc, resource_name, &resmgr);
    float scalex, scaley;
    tiles.get_scale(scalex, scaley);
    tile_width = tiles.get_width() * scalex;
    tile_height = tiles.get_height() * scaley;

    auto layer_nodes = element.select_nodes("layer");
    for (CL_DomNode& idx : layer_nodes) {
        CL_DomElement layer_element = idx.to_element();

        CL_String layer_tiles = layer_element.get_first_child().get_node_value();
        std::vector<CL_String> tile_indices = CL_StringHelp::split_text(layer_tiles, ",");

        MapLayer layer;
        layer.map.reserve(tile_indices.size());
        for (auto& tile : tile_indices)
            layer.map.push_back(CL_StringHelp::text_to_int(tile));

        layers.push_back(layer);
    }
}
Ejemplo n.º 13
0
void TestApp::test_resources(void)
{
	CL_Console::write_line(" Header: resource.h");
	CL_Console::write_line("  Class: CL_Resource");

	// Construct resource manager. This will cause sig_resource_added() to be signalled for each
	// resource object located in the resource file. This means ResourceApp::on_resource_added will
	// get called for each resource.
	CL_ResourceManager resources("resources.xml");

	// Lets try to access some of the clanlib objects in the resource file:
	CL_String config_name = resources.get_string_resource("Configuration/name", "");
	int config_width = resources.get_integer_resource("Configuration/width", 0 );
	int config_height = resources.get_integer_resource("Configuration/height", 0 );

	CL_Console::write_line(CL_String("name = ") + config_name );
	CL_Console::write_line(CL_String("width = ") + CL_StringHelp::int_to_text(config_width));
	CL_Console::write_line(CL_String("height = ") + CL_StringHelp::int_to_text(config_height));

	// Get a list over all classes
	std::vector<CL_String> v = resources.get_resource_names_of_type("uclass", "Classes");
	std::vector<CL_String>::iterator it;
	for(it = v.begin(); it != v.end(); ++it)
	{
		// Get one of our custom resources:
		CL_Resource resource = resources.get_resource(*it);

		// Its possible to access the dom element object in the resource:
		CL_DomElement element = resource.get_element();
		int strength = CL_StringHelp::text_to_int(element.get_attribute("strength"));
		int magic = CL_StringHelp::text_to_int(element.get_attribute("magic"));

		CL_Console::write_line(CL_String("\n") + "name = " + resource.get_name());
		CL_Console::write_line(CL_String("strength = ") + CL_StringHelp::int_to_text(strength));
		CL_Console::write_line(CL_String("magic = ") + CL_StringHelp::int_to_text(magic) );
	}

}
Ejemplo n.º 14
0
void Level::loadFromFile(const CL_String& p_filename)
{
	assert(!m_loaded && "level is already loaded");

	try {
		CL_File file(p_filename, CL_File::open_existing, CL_File::access_read);


		CL_DomDocument document(file);
		const CL_DomElement root = document.get_document_element();

		// load meta element
		const CL_DomNode metaNode = root.named_item("meta");
		loadMetaElement(metaNode);

		// gets level's content
		const CL_DomNode contentNode = root.named_item("content");

		// load sand
		const CL_DomNode sandNode = contentNode.named_item("sand");
		loadSandElement(sandNode);

		// load track
		const CL_DomNode trackNode = contentNode.named_item("track");
		loadTrackElement(trackNode);

		// load track bounds
		const CL_DomNode boundsNode = contentNode.named_item("bounds");
		loadBoundsElement(boundsNode);

		file.close();
		m_loaded = true;

	} catch (CL_Exception e) {
		CL_Console::write_line(e.message);
	}

}
Ejemplo n.º 15
0
CL_Collada_Triangles::CL_Collada_Triangles(CL_DomElement &element, std::vector<CL_Collada_Source> &sources, CL_Collada_Vertices &vertices, std::vector<CL_Collada_Material> &library_materials) : impl(new CL_Collada_Triangles_Impl())
{
	bool contains_vcount;
	if (element.get_tag_name() == "polylist")
	{
		contains_vcount = true;
	}
	else
	{
		contains_vcount = false;
	}

	impl->load_polylist(element, contains_vcount, sources, vertices, library_materials);
}
Ejemplo n.º 16
0
void ReferenceFunction::load(CL_String member_name, CL_DomElement class_element)
{
	if (class_element.get_tag_name() != "compounddef")
		throw CL_Exception("Expected compounddef element");

	name = member_name;

	CL_DomNode cur_node;
	for (cur_node = class_element.get_first_child(); !cur_node.is_null(); cur_node = cur_node.get_next_sibling())
	{
		CL_DomElement cur_element = cur_node.to_element();
		if (cur_element.is_null()) continue;

		CL_String tag_name = cur_element.get_tag_name();
		if ( (tag_name == "sectiondef") && (
			(cur_element.get_attribute("kind") == "user-defined") ||
			(cur_element.get_attribute("kind") == "public-func") ||
			(cur_element.get_attribute("kind") == "public-static-func") ) )
		{
			parse_sectiondef(cur_element);
		}
	}
}
Ejemplo n.º 17
0
void ReferenceFunction::parse_sectiondef(CL_DomElement sectiondef)
{
	CL_DomNode cur_node;
	for (cur_node = sectiondef.get_first_child(); !cur_node.is_null(); cur_node = cur_node.get_next_sibling())
	{
		CL_DomElement cur_element = cur_node.to_element();
		if (cur_element.is_null()) continue;
		
		CL_String tag_name = cur_element.get_tag_name();
		if (tag_name == "memberdef")
		{
			parse_memberdef(cur_element);
		}
	}
}
Ejemplo n.º 18
0
void ServerConfigurationImpl::load(const CL_String &p_configFile)
{
	try {
		cl_log_event(LOG_DEBUG, "loading configuration from %1", p_configFile);

		CL_File file(
				p_configFile,
				CL_File::open_existing,
				CL_File::access_read
		);


		CL_DomDocument document(file);
		CL_DomElement root = document.get_document_element();

		if (root.named_item("server").is_null()) {
			// no configuration at all
			return;
		}

		CL_DomElement server = root.named_item("server").to_element();

		m_level = server.select_string("level");
		m_port = server.select_int("port");

		if (m_level.length() == 0) {
			cl_log_event(LOG_ERROR, "%1: level not set", CONFIG_FILE);
			exit(1);
		}

		if (m_port <= 0 || m_port > 0xFFFF) {
			cl_log_event(LOG_ERROR, "%1: invalid port value", CONFIG_FILE);
			exit(1);
		}

//		// read all elements
//		CL_DomNode cur = server.get_first_child();
//		while (cur.is_element()) {
//
//			if (cur.get_node_name() == "port") {
//				m_port = CL_StringHelp::local8_to_int
//						(cur.to_element().get_text()
//				);
//				cl_log_event(LOG_DEBUG, "Port set to %1", m_port);
//			}
//
//			cur = cur.get_next_sibling();
//		}


	} catch (CL_Exception e) {
		cl_log_event(LOG_ERROR, e.message);
	}
}
void CL_FileDialog_Generic::on_set_options(const CL_DomElement &options)
{
	if (options.has_attribute("file"))
		set_file(options.get_attribute("file"), false);

	if (options.has_attribute("filter"))
		set_filter(options.get_attribute("filter"), false);

	if (options.has_attribute("show_hidden"))
		show_hidden = CL_String::to_bool(options.get_attribute("show_hidden"));

	read_dir();
}
Ejemplo n.º 20
0
void ReferenceFunction::get_params_list(const CL_DomElement &element)
{
	CL_DomNode cur_node;
	for (cur_node = element.get_first_child(); !cur_node.is_null(); cur_node = cur_node.get_next_sibling())
	{
		if (!cur_node.is_element()) continue;
		
		CL_DomElement cur_element = cur_node.to_element();
		if (cur_element.get_tag_name() == "parameterlist")
		{
			CL_String kind = cur_element.get_attribute("kind");
			if (kind != "param") continue;

			CL_String param_name, param_description;
			CL_DomNode param_node;
			for (param_node = cur_element.get_first_child(); !param_node.is_null(); param_node = param_node.get_next_sibling())
			{
				if (!param_node.is_element()) continue;
				CL_DomElement param_element = param_node.to_element();
				
				if (param_element.get_tag_name() == "parametername")
				{
					param_name = param_element.get_text();
				}
				else if (param_element.get_tag_name() == "parameterdescription")
				{
					param_description = ReferenceDocs::get_formatted(param_element);
				}
			}
			
			if (!param_name.empty())
			{
				ReferenceFunctionParameter parameter;
				parameter.name = param_name;
				parameter.description = param_description;
				parameters.push_back(parameter);
			}
		}
		else
		{
			get_params_list(cur_element);
		}
	}
}
Ejemplo n.º 21
0
void CL_Collada_Triangles_Impl::load_inputs(CL_DomElement &polylist_element, std::vector<CL_Collada_Source> &sources, CL_Collada_Vertices &vertices)
{
	stride = 1;
	CL_DomNode cur_child(polylist_element.get_first_child());
	while (!cur_child.is_null())
	{
			if(cur_child.get_node_name() == "input")
			{
				CL_DomElement input_element = cur_child.to_element();
				CL_Collada_Input_Shared new_input(input_element, sources, vertices);

				// Find the stride
				int offset = new_input.get_offset();
				offset++;	// Make comparible with stride (1 to x)
				if (offset > stride)
					stride = offset;

				inputs.push_back( new_input );
			}
			cur_child = cur_child.get_next_sibling();
	}
}
Ejemplo n.º 22
0
void CL_DomElement::set_child_string(const CL_DomString &name, const CL_DomString &value)
{
	CL_DomElement element = named_item(name).to_element();
	if (element.is_null())
	{
		element = get_owner_document().create_element(name);
		append_child(element);
	}

	while (!element.get_first_child().is_null())
	{
		CL_DomNode my_child = element.get_first_child();
		element.remove_child(my_child);
	}

	CL_DomText dom_text = get_owner_document().create_text_node(value);
	element.append_child(dom_text);
}
Ejemplo n.º 23
0
void TileMap::load(CL_GraphicContext &gc, const CL_String &level, CL_ResourceManager &resources)
{
	CL_Resource resource = resources.get_resource(level);
	
	if (resource.get_type() != "tilemap")
		throw CL_Exception(cl_format("Resource %1 is not of type tilemap!", level));

	CL_DomElement element = resource.get_element();
	CL_String level_name = element.get_attribute("name");
	CL_String resource_name = element.get_attribute("resource");
	map_width = element.get_attribute_int("width");
	map_height = element.get_attribute_int("height");
	
	cl_log_event("Debug", "Loading level %1 (%2x%3)", level_name, map_width, map_height);

	sprite_tiles = CL_Sprite(gc, resource_name, &resources);

	tile_width = sprite_tiles.get_width();
	tile_height = sprite_tiles.get_height();

	cl_log_event("Debug", "Loaded resource %1 with %2 tiles", resource_name, sprite_tiles.get_frame_count());

	std::vector<CL_DomNode> layer_nodes = element.select_nodes("layer");
	for (size_t layer_index = 0; layer_index < layer_nodes.size(); layer_index++)
	{
		CL_DomElement layer_element = layer_nodes[layer_index].to_element();
		CL_String layer_name = layer_element.get_attribute("name");

		CL_String layer_tiles = layer_element.get_first_child().get_node_value();
		std::vector<CL_String> tile_indices = CL_StringHelp::split_text(layer_tiles, ",");

		TileMapLayer layer;
		layer.map.reserve(tile_indices.size());
		for(size_t i = 0; i < tile_indices.size(); ++i)
			layer.map.push_back(CL_StringHelp::text_to_int(tile_indices[i]));
	
		layers.push_back(layer);

		cl_log_event("Debug", "Loaded layer %1 with %2 tiles", layer_name, layer.map.size());
	}

	current_map_position_x = 0;
	current_map_position_y = 0;
}
Ejemplo n.º 24
0
void CL_Collada_Triangles_Impl::load_polylist(CL_DomElement &polylist_element, bool contains_vcount, std::vector<CL_Collada_Source> &sources, CL_Collada_Vertices &vertices, std::vector<CL_Collada_Material> &library_materials)
{
	name = polylist_element.get_attribute("name");

	// Find material	
	if (polylist_element.has_attribute("material"))
	{
		CL_String material_name = polylist_element.get_attribute("material");

			std::vector<CL_Collada_Material>::size_type size, cnt;
			size = library_materials.size();
			for (cnt=0; cnt< size; cnt++)
			{
				if (library_materials[cnt].get_id() == material_name)
				{
					material = library_materials[cnt];
					break;
				}
			}
	
		if (material.is_null())
			throw CL_Exception("Unable to find material");

	}

	triangle_count = polylist_element.get_attribute_int("count", 0);

	load_inputs(polylist_element, sources, vertices);

	if (contains_vcount)
	{
		CL_DomElement vcount_element = polylist_element.named_item("vcount").to_element();
		if (!vcount_element.is_null())
			validate_vcount(vcount_element);
	}

	CL_DomElement primitive_element = polylist_element.named_item("p").to_element();
	if (!primitive_element.is_null())
		load_primitive(primitive_element);
}
Ejemplo n.º 25
0
void CL_Label_Generic::on_set_options(const CL_DomElement &options)
{
	if (options.has_attribute("text"))
		text = options.get_attribute("text");
}
Ejemplo n.º 26
0
void CL_ResourceManager::load(CL_IODevice file, CL_VirtualDirectory directory)
{
	CL_DomDocument new_document;
	new_document.load(file);

	// Check if loaded document uses namespaces and if its a clanlib resources xml document:
	CL_DomElement doc_element = new_document.get_document_element();
	if (doc_element.get_namespace_uri().empty() && doc_element.get_local_name() == "resources")
	{
		impl->ns_resources = CL_String();
	}
	else if (doc_element.get_namespace_uri() == "http://clanlib.org/xmlns/resources-1.0")
	{
		if (doc_element.get_local_name() != "resources")
			throw CL_Exception("ClanLib resource documents must begin with a resources element.");

		impl->ns_resources = "http://clanlib.org/xmlns/resources-1.0";
	}
	else
	{
		throw CL_Exception("XML document is not a ClanLib resources document.");
	}

	impl->document = new_document;
	impl->directory = directory;
	impl->resources.clear();

	std::vector<CL_String> section_stack;
	std::vector<CL_DomNode> nodes_stack;
	section_stack.push_back(CL_String());
	nodes_stack.push_back(doc_element.get_first_child());
	while (!nodes_stack.empty())
	{
		if (nodes_stack.back().is_element())
		{
			CL_DomElement element = nodes_stack.back().to_element();
			if (element.get_namespace_uri() == impl->ns_resources && element.get_local_name() == "section")
			{
				CL_String section_name = element.get_attribute_ns(impl->ns_resources, "name");
				section_stack.push_back(section_stack.back() + CL_PathHelp::add_trailing_slash(section_name, CL_PathHelp::path_type_virtual));
				nodes_stack.push_back(element.get_first_child());
				continue;
			}
			else if (element.has_attribute_ns(impl->ns_resources, "name"))
			{
				CL_String resource_name = element.get_attribute_ns(impl->ns_resources, "name");
				CL_String resource_id = section_stack.back() + resource_name;
				impl->resources[resource_id] = CL_Resource(element, *this);
			}
		}

		nodes_stack.back() = nodes_stack.back().get_next_sibling();

		while (nodes_stack.back().is_null())
		{
			nodes_stack.pop_back();
			section_stack.pop_back();
			if (nodes_stack.empty())
				break;
			nodes_stack.back() = nodes_stack.back().get_next_sibling();
		}
	}
}
void CL_GUIXMLLoaderVersion_1_0::load(CL_DomElement &element, CL_GUIComponent *parent)
{
	CL_DomElement e = element.get_first_child().to_element();

	dialog_width = 0;
	dialog_height = 0;

	while (e.is_element())
	{
		CL_String tag = e.get_tag_name();
		CL_GUIComponent *new_comp = 0;

		if (tag == "button")
		{
			CL_PushButton *co = new CL_PushButton(parent);
			if (e.has_attribute("text"))
				co->set_text(e.get_attribute("text"));
			new_comp = co;
		}
		else if (tag == "checkbox")
		{
			CL_CheckBox *co = new CL_CheckBox(parent);
			if (e.has_attribute("text"))
				co->set_text(e.get_attribute("text"));
			new_comp = co;
		}
		else if (tag == "radiobutton")
		{
			CL_RadioButton *co = new CL_RadioButton(parent);
			if (e.has_attribute("text"))
				co->set_text(e.get_attribute("text"));
			if (e.has_attribute("group"))
				co->set_group_name(e.get_attribute("group"));
			new_comp = co;
		}
		else if (tag == "label")
		{
			CL_Label *co = new CL_Label(parent);
			if (e.has_attribute("text"))
				co->set_text(e.get_attribute("text"));
			new_comp = co;
		}
		else if (tag == "toolbar")
		{
			CL_ToolBar *co = new CL_ToolBar(parent);
			new_comp = co;
		}
		else if (tag == "progressbar")
		{
			CL_ProgressBar *co = new CL_ProgressBar(parent);
			new_comp = co;
		}
		else if (tag == "lineedit")
		{
			CL_LineEdit *co = new CL_LineEdit(parent);
			if (e.has_attribute("text"))
				co->set_text(e.get_attribute("text"));
			new_comp = co;
		}
		else if (tag == "slider")
		{
			CL_Slider *co = new CL_Slider(parent);
			co->set_min(CL_StringHelp::text_to_int(e.get_attribute("min")));
			co->set_max(CL_StringHelp::text_to_int(e.get_attribute("max")));
			co->set_tick_count(CL_StringHelp::text_to_int(e.get_attribute("ticks")));
			co->set_page_step(CL_StringHelp::text_to_int(e.get_attribute("page_step")));
			new_comp = co;
		}
		else if (tag == "listview")
		{
			CL_ListView *co = new CL_ListView(parent);
			CL_ListViewHeader *header = co->get_header();

			std::vector<CL_DomNode> columns_nodes = e.select_nodes("listview_header/listview_column");
			for(size_t i = 0; i < columns_nodes.size(); ++i)
			{
				CL_DomElement column_element = columns_nodes[i].to_element();
				CL_String id = column_element.get_attribute("col_id");
				CL_String caption = column_element.get_attribute("caption");
				int width = column_element.get_attribute_int("width");

				CL_ListViewColumnHeader column = header->create_column(id, caption);
				column.set_width(width);
				header->append(column);
			}

			new_comp = co;
		}
		else if (tag == "tab")
		{
			CL_Tab *co = new CL_Tab(parent);
			new_comp = co;

			CL_DomElement tab_child = e.get_first_child().to_element();
			while (tab_child.is_element())
			{
				if (tab_child.get_tag_name() == "tabpage")
				{
					CL_String label = tab_child.get_attribute("label", "Error: NO LABEL!");
					int id = CL_StringHelp::text_to_int(tab_child.get_attribute("id", "0"));
					CL_TabPage *tab_page = co->add_page(label, id);
					CL_GUILayoutCorners tabpage_layout;
					tab_page->set_layout(tabpage_layout);
					load(tab_child, tab_page);
				}

				tab_child = tab_child.get_next_sibling().to_element();
			}
		}
		else if (tag == "statusbar")
		{
			CL_StatusBar *co = new CL_StatusBar(parent);
			new_comp = co;
		}
		else if (tag == "menubar")
		{
			CL_MenuBar *co = new CL_MenuBar(parent);
			new_comp = co;
		}
		else if (tag == "combobox")
		{
			CL_ComboBox *co = new CL_ComboBox(parent);
			new_comp = co;
		}
		else if (tag == "scrollbar")
		{
			CL_ScrollBar *co = new CL_ScrollBar(parent);
			new_comp = co;
		}
		else if (tag == "spin")
		{
			CL_Spin *co = new CL_Spin(parent);
			new_comp = co;
		}
		else if (tag == "imageview")
		{
			CL_ImageView *co = new CL_ImageView(parent);
			new_comp = co;
		}
		else if (tag == "frame")
		{
			CL_Frame *co = new CL_Frame(parent);
			if (e.has_attribute("text"))
				co->set_header_text(e.get_attribute("text"));
			new_comp = co;
			CL_GUILayoutCorners layout_corners;
			co->set_layout(layout_corners);
			load(e, co);
		}
		else if (tag == "dialog")
		{
			dialog_width = CL_StringHelp::text_to_int(e.get_attribute("width"));
			dialog_height = CL_StringHelp::text_to_int(e.get_attribute("height"));
		}
		else // unknown tag... try create a custom_component
		{
			CL_GUIComponent *co = 0;
			if (create_custom_callback && !create_custom_callback->is_null())
			{
				co = create_custom_callback->invoke(parent, tag);
			}
			new_comp = co;
		}

		if (new_comp)
		{
			new_comp->set_id_name(e.get_attribute("id"));
			new_comp->set_class_name(e.get_attribute("class"));
			new_comp->set_enabled(e.get_attribute_bool("enabled", true));

			CL_String str = e.get_attribute("geom");
			std::vector<CL_String> split = CL_StringHelp::split_text(str, ",");

			CL_Rect g;
			g.left = CL_StringHelp::text_to_int(split[0]);
			g.top = CL_StringHelp::text_to_int(split[1]);
			g.right = CL_StringHelp::text_to_int(split[2]);
			g.bottom = CL_StringHelp::text_to_int(split[3]);
			new_comp->set_geometry(g);

			CL_GUILayout parent_layout = parent->get_layout();
			if (!parent_layout.is_null())
			{
				parent_layout.get_provider();
				CL_GUILayoutProvider_Corners *corner_provider_layout = dynamic_cast<CL_GUILayoutProvider_Corners*>(parent_layout.get_provider());
				if (corner_provider_layout)
				{
					int dist_tl_x = CL_StringHelp::text_to_int(e.get_attribute("dist_tl_x"));
					int dist_tl_y = CL_StringHelp::text_to_int(e.get_attribute("dist_tl_y"));
					int dist_rb_x = CL_StringHelp::text_to_int(e.get_attribute("dist_br_x"));
					int dist_rb_y = CL_StringHelp::text_to_int(e.get_attribute("dist_br_y"));
					CL_ComponentAnchorPoint ap_tl = (CL_ComponentAnchorPoint)CL_StringHelp::text_to_int(e.get_attribute("anchor_tl"));
					CL_ComponentAnchorPoint ap_br = (CL_ComponentAnchorPoint)CL_StringHelp::text_to_int(e.get_attribute("anchor_br"));

					corner_provider_layout->add_component(new_comp, ap_tl, dist_tl_x, dist_tl_y, ap_br, dist_rb_x, dist_rb_y);
				}
			}
		}

		e = e.get_next_sibling().to_element();
	}

	CL_GUILayout parent_layout = parent->get_layout();
	if (!parent_layout.is_null())
	{
		parent_layout.set_geometry(parent->get_size());
	}
}
Ejemplo n.º 28
0
void ReferenceFunction::parse_memberdef(CL_DomElement memberdef)
{
	CL_DomElement element_name = memberdef.named_item("name").to_element();
	if (element_name.is_null() || element_name.get_text() != name)
		return;

	CL_String type, type_formatted, definition, argsstring;
	std::vector<CL_String> cur_params;

	CL_DomNode cur_node;
	for (cur_node = memberdef.get_first_child(); !cur_node.is_null(); cur_node = cur_node.get_next_sibling())
	{
		CL_DomElement cur_element = cur_node.to_element();
		if (cur_element.is_null()) continue;

		CL_String tag_name = cur_element.get_tag_name();
		
		if (tag_name == "type")
		{
			type = cur_element.get_text();
			type_formatted = ReferenceDocs::get_formatted(cur_element);
		}
		else if (tag_name == "definition")
		{
			definition = CL_StringHelp::trim(ReferenceDocs::escape_code(cur_element.get_text()));
		}
		else if (tag_name == "argsstring")
		{
			argsstring = cur_element.get_text();
		}
		else if (tag_name == "param")
		{
			CL_String param_type = ReferenceDocs::get_formatted(cur_element.named_item("type").to_element());
			CL_String param_name = cur_element.named_item("declname").to_element().get_text();
			CL_String param_defval = ReferenceDocs::get_formatted(cur_element.named_item("defval").to_element());
			
			CL_String param_text = param_type + " " + param_name;
			if (!param_defval.empty())
				param_text += CL_String(" = ") + param_defval;
			cur_params.push_back(param_text);
		}
		else if (tag_name == "briefdescription")
		{
			brief_description = ReferenceDocs::get_formatted(cur_element);
		}
		else if (tag_name == "detaileddescription")
		{
			detailed_description = ReferenceDocs::get_formatted(cur_element);
			get_params_list(cur_element);
		}
	}

	CL_String cur_declaration;
	cur_declaration += cl_format("\t%1(", definition);
	for (unsigned int index_params = 0; index_params < cur_params.size(); index_params++)
	{
		if (index_params > 0)
			cur_declaration += ",";
		cur_declaration += cl_format("\n\t\t%1", cur_params[index_params]);
	}
	cur_declaration += ");\n";

	if (!declaration.empty())
		declaration += "\n";
	declaration += cur_declaration;
}
Ejemplo n.º 29
0
CL_Resource CL_ResourceManager::create_resource(const CL_String &resource_id, const CL_String &type)
{
	if (resource_exists(resource_id))
		throw CL_Exception(cl_format("Resource %1 already exists", resource_id));

	std::vector<CL_String> path_elements = CL_PathHelp::split_basepath(resource_id);
	CL_String name = CL_PathHelp::get_filename(resource_id);

	// Walk tree as deep as we can get:
	CL_DomNode parent = impl->document.get_document_element();
	CL_DomNode cur = parent.get_first_child();
	std::vector<CL_String>::iterator path_it = path_elements.begin();
	while (!cur.is_null() && path_it != path_elements.end())
	{
		if (cur.is_element() &&
			cur.get_namespace_uri() == impl->ns_resources &&
			cur.get_local_name() == "section")
		{
			CL_DomElement element = cur.to_element();
			CL_String name = element.get_attribute_ns(impl->ns_resources, "name");
			if (name == *path_it)
			{
				++path_it;
				parent = cur;
				cur = cur.get_first_child();
				continue;
			}
		}
		cur = cur.get_next_sibling();
	}

	// Create any missing parent nodes:
	CL_String prefix = parent.get_prefix();
	while (path_it != path_elements.end())
	{
		CL_DomElement section;
		if (prefix.empty())
		{
			section = impl->document.create_element_ns( impl->ns_resources, (*path_it) );
		}
		else
		{
			section = impl->document.create_element_ns( impl->ns_resources,(prefix + ":" + *path_it));
		}
		parent.append_child(section);
		parent = section;
		++path_it;
	}

	// Create node:
	CL_DomElement resource_node;
	if (prefix.empty())
	{
		resource_node = impl->document.create_element_ns( impl->ns_resources, (type));
	}
	else
	{
		resource_node = impl->document.create_element_ns( impl->ns_resources,(prefix + ":" + type));
	}

	resource_node.set_attribute_ns(
		impl->ns_resources,
		prefix.empty() ? "name" : (prefix + ":name"),
		name);
	parent.append_child(resource_node);

	// Create resource:
	impl->resources[resource_id] = CL_Resource(resource_node, *this);
	return impl->resources[resource_id];
}
Ejemplo n.º 30
0
int ConsoleProgram::main(const std::vector<CL_String> &args)
{
	// Setup clanCore:
	CL_SetupCore setup_core;

	// Initialize the ClanLib display component
	CL_SetupDisplay setup_display;

	// Create a console Window if one does not exist:
	CL_ConsoleWindow console_window("Console", 80, 600);

try
{	
	//получение параметра запуска
	for (std::vector<CL_String>::const_iterator iter_args = args.begin(); iter_args != args.end(); ++iter_args)
		CL_Console::write_line( *iter_args );

	//получение имени директории для сохранения
	CL_String workDirectoryName;
	if (args.size() > 1)
	{
		//полное имя рабочей директории
		workDirectoryName = args[1];
		//конвертирование из CP-1251 в UTF-8 имени рабочей директории
		workDirectoryName = decode(workDirectoryName);
	}
	else
	{
		//получение полного пути к текущему каталогу
		workDirectoryName = CL_Directory::get_current();
	}

	CL_Console::write_line("workDirectoryName: %1", workDirectoryName);
	//получение имени последней директории
	CL_String locationName = CL_PathHelp::remove_trailing_slash(workDirectoryName);
	locationName = CL_PathHelp::get_filename(locationName);
	CL_Console::write_line("locationName: %1", locationName);

	CL_String tempDir = CL_PathHelp::add_trailing_slash(workDirectoryName) + "temp\\";
	CL_DirectoryScanner directoryScanner;
	directoryScanner.scan(tempDir, "*.export");
	while (directoryScanner.next())
	{
		//имя обрабатываемого файла
		CL_String fileName;

		if (directoryScanner.is_directory())
			continue;
		//получение полного имени файла экспорта
		fileName = directoryScanner.get_pathname();
		//конвертирование из CP-1251 в UTF-8
		fileName = decode(fileName);
		CL_Console::write_line("find: %1", fileName);

		//открытие XML файла
		CL_File fileXML;
		bool is_opened = fileXML.open(fileName);
		if( !is_opened )
			return PrintError( CL_String("Can't open file: ") + fileName );

		//Создание объекта DOM парсера
		CL_DomDocument document(fileXML);
		//получение root узла
		CL_DomElement root = document.get_document_element();
		if( root.get_local_name() != "resources")
		{
			CL_Console::write_line("Root name can't be: %1", root.get_local_name().c_str());
			return PrintError("");
		}

		//цикл по потомкам "resources"
		for (CL_DomNode cur = root.get_first_child(); !cur.is_null(); cur = cur.get_next_sibling())
		{
			//загрузка только спрайтов
			if (cur.get_node_name() != "sprite")
				continue;

			CL_DomElement element = cur.to_element();

			//проверка на обязательные параметры
			if (!element.has_attribute("name"))
				return PrintError("Error: can't find parametr \"name\"");

			CL_DomString name = element.get_attribute("name");
			int x = element.get_attribute_int("x");
			int y = element.get_attribute_int("y");
			//добавление спрайта
			sprites.push_back( S_Sprite(name, CL_Vec2i(x, y) ) );

			//цикл по "image" (формирование списка имен файлов)
			for (CL_DomNode cur_image = cur.get_first_child(); !cur_image.is_null(); cur_image = cur_image.get_next_sibling())
			{
				//загрузка только image
				if (cur_image.get_node_name() != "image")
					continue;
				
				CL_DomElement element_image = cur_image.to_element();
				CL_DomString file = element_image.get_attribute("file");
				
				//конвертирование из CP-1251 в UTF-8 имени файла изображения
				file = decode(file); 

				//добавление изображения для обработки
				(sprites.end()-1)->AddImage(file);
			}

			//цикл по "frame" (дополнение списка информацией о файле)
			for (CL_DomNode cur_frame = cur.get_first_child(); !cur_frame.is_null(); cur_frame = cur_frame.get_next_sibling())
			{
				if (cur_frame.get_node_name() != "frame")
					continue;
				
				CL_DomElement element_frame = cur_frame.to_element();
				//проверка на обязательные параметры
				if (!element_frame.has_attribute("nr"))
					return PrintError("Error: can't find parameter \"nr\"");

				size_t nr = element_frame.get_attribute_int("nr");
				int speed = element_frame.get_attribute_int("speed");
				int x_image = element_frame.get_attribute_int("x");
				int y_image = element_frame.get_attribute_int("y");

				(sprites.end()-1)->SetAnimationsParam(nr, speed, CL_Vec2i(x_image, y_image));
			}
		}
		fileXML.close();

	}
	//CL_Console::wait_for_key();

	// TODO:
	//проверка на перекрытие ресурсных имен
	//return PrintError( CL_String("Error: This resourse already exist") );

	//декодирование имени спрайта и генерация с декодированием полных имен файлов
	for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites)
	{
		for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images)
		{
			//CL_Console::write_line("processing: %1 pos = %2 %3", iter_sprites->mName, iter_sprites->mPos.x, iter_sprites->mPos.y);
			//генерация полного имени файла
			iter_images->mSourceFullName = CL_PathHelp::make_absolute(tempDir, iter_images->mSourceFileName);
			//CL_Console::write_line("image: %1 pos = %2 %3", iter_images->mSourceFileName, iter_images->mOffset.x, iter_images->mOffset.y);
			CL_Console::write_line("image fullname: %1", iter_images->mSourceFullName);
		}
	}
	//CL_Console::wait_for_key();

	//загрузка файлов-картинок
	for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites)
		for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images)
			iter_images->mImage = CL_ImageProviderFactory::load(iter_images->mSourceFullName).to_format(cl_rgba8);

	//CL_Console::wait_for_key();

	//проход по всем спрайтам для определения необходимости разрезки на несколько спрайтов

	for(T_Sprites::size_type iSprites = 0; iSprites < sprites.size(); ++iSprites)
	{
		for(S_Sprite::T_Images::size_type iImages = 0; iImages < sprites[iSprites].mImages.size(); ++iImages)
		{
			//определение размеров
			CL_Size image_size = sprites[iSprites].mImages[iImages].mImage.get_size();

			//Определение наличия прозрачности
			sprites[iSprites].mImages[iImages].mNoTransparent = testAlpha(sprites[iSprites].mImages[iImages].mImage);

			//высота превышает допустимую
			if(image_size.height > MAX_HEIGHT)
				return PrintError( CL_String("Error: image height is more then 1024") );

			//ширина превышает допустимую
			if(image_size.width > MAX_WIDTH)
			{
				
				CL_Console::write_line("scussor: sprites[iSprites].mName: %1", sprites[iSprites].mName);

				//проверка на то что у этого спрайта один image
				if(sprites[iSprites].mImages.size() > 1)
					return PrintError( CL_String("Error: animation size can't be more than MAX_WIDTH*MAX_HEIGHT (1024*1024)") );
				
				//сохранение высоты и ширины
				int h = image_size.height;
				int w = image_size.width;
				
				//определение кол-ва частей на разрезку
				int n; //кол-во частей на разрезку
				for(n = 2; n < 10; ++n)
					if (w > (n-1)*MAX_WIDTH - 2*(n-2) && w <= (n)*MAX_WIDTH - 2*(n-1))
						break;
				
				T_Sprites::iterator addedSprite;
				switch (n)
				{
				case 2: //две части
					//спрайт слева (задание имени и позиции спрайта)
					addedSprite = sprites.insert( sprites.begin()+iSprites+1, 
						S_Sprite(CL_String(sprites[iSprites].mName)+CL_StringHelp::int_to_text(0), sprites[iSprites].mPos+CL_Vec2i(0, 0) ) );

					//создание одного Image в добавленом спрайте
					addedSprite->AddImage(sprites[iSprites].mImages[iImages].mSourceFileName);
					//создание изображения (задание зазмеров спрайта)
					addedSprite->mImages[0].mImage = CL_PixelBuffer(MAX_WIDTH, h, cl_rgba8);
					//наследование флага отсутствия прозрачности
					addedSprite->mImages[0].mNoTransparent = sprites[iSprites].mImages[iImages].mNoTransparent;
					//копирование куска изображения
					sprites[iSprites].mImages[iImages].mImage.convert(addedSprite->mImages[0].mImage,
						//(dst Rect, src Rect)
						CL_Rect(0, 0, MAX_WIDTH, h), CL_Rect(0, 0, MAX_WIDTH, h));
					addedSprite->mImages[0].mDeltaGrid.left = 0;
					addedSprite->mImages[0].mDeltaGrid.right = -1;

					//спрайт справа (задание имени и позиции спрайта)
					addedSprite = sprites.insert( sprites.begin()+iSprites+1, 
						S_Sprite(CL_String(sprites[iSprites].mName)+CL_StringHelp::int_to_text(1), sprites[iSprites].mPos+CL_Vec2i(MAX_WIDTH-1, 0) ) );

					//создание одного Image в добавленом спрайте
					addedSprite->AddImage(sprites[iSprites].mImages[iImages].mSourceFileName);
					//создание изображения (задание зазмеров спрайта)
					addedSprite->mImages[0].mImage = CL_PixelBuffer(w-MAX_WIDTH+2, h, cl_rgba8);
					//наследование флага отсутствия прозрачности
					addedSprite->mImages[0].mNoTransparent = sprites[iSprites].mImages[iImages].mNoTransparent;
					//копирование куска изображения
					sprites[iSprites].mImages[iImages].mImage.convert(addedSprite->mImages[0].mImage,
						//(dst Rect, src Rect)
						CL_Rect(0, 0, w-MAX_WIDTH+2, h), CL_Rect(MAX_WIDTH-2, 0, w, h));
					addedSprite->mImages[0].mDeltaGrid.left = +1;
					addedSprite->mImages[0].mDeltaGrid.right = -1;

					break;
				default:
					return PrintError( CL_String("Error: scussored on >2 part is't writen by C++ programmer") );
					break;
				}

/*
				//разделение изображения на части
				int x = 1;
				int residual = image_size.width;
				int left, right;
				int i = 0;
				do
				{
					x -= 1;
					left = x;
					x += min(MAX_WIDTH, residual);
					right = x;
					residual -= (right-left-1);

					i++;
					//добавление куска
					T_Sprites::iterator addedSprite =
						sprites.insert( sprites.begin()+iSprites+1, 
						S_Sprite(CL_String(sprites[iSprites].mName)+CL_StringHelp::int_to_text(i), sprites[iSprites].mPos+CL_Vec2i(left, 0) ) );

					//создание одного Image в добавленом спрайте
					addedSprite->AddImage(sprites[iSprites].mImages[iImages].mSourceFileName);
					//создание изображения
					addedSprite->mImages[0].mImage = CL_PixelBuffer(right-left, h, cl_rgba8);
					//наследование флага отсутствия прозрачности
					addedSprite->mImages[0].mNoTransparent = sprites[iSprites].mImages[iImages].mNoTransparent;
					//копирование куска изображения
					sprites[iSprites].mImages[iImages].mImage.convert(addedSprite->mImages[0].mImage, CL_Rect(0,0,right-left,h), CL_Rect(left, 0, right, h));
				}
				while(residual != 1);
*/		
				//удаление исходного разрезаемого изображения
				sprites.erase( sprites.begin() + iSprites );
			}		
		}
	}

//	for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites)
//	{
//		//определение размеров
//		CL_Size imageSize = iter_sprites->mImage.get_size();
//		//Добавление несколько пикселей для границы спрайтов с дублированием граничных пикселей
//		iter_sprites->image = CL_PixelBufferHelp::add_border(iter_sprites->image, ADDING_BORDER, CL_Rect(0, 0, image_size.width, image_size.height) );
//	}

	///////////////////////////////////////////////////////
	//распределение картинок на текстурном атласе
	///////////////////////////////////////////////////////

	for(T_Sprites::size_type iSprites = 0; iSprites < sprites.size(); ++iSprites)
	{
		for(S_Sprite::T_Images::size_type iImages = 0; iImages < sprites[iSprites].mImages.size(); ++iImages)
		{
			//переполучение размера
			CL_Size image_size = sprites[iSprites].mImages[iImages].mImage.get_size();
			//помещение в отсортированый список указателя на image
			sortedList.insert( std::make_pair( max(image_size.width, image_size.height), S_ImagePointer(iSprites, iImages) ) );
		}
	}

	//Проверка сортировки
	//for(T_SortedList::iterator iter_sortedList = sortedList.begin(); iter_sortedList != sortedList.end(); ++iter_sortedList)
	//	CL_Console::write_line("sorted: %1, key=(%2, %3)", iter_sortedList->first, iter_sortedList->second.iSprite, iter_sortedList->second.iImage);

	//проход по всем спрайтам по убыванию большей стороны
	for(T_SortedList::reverse_iterator iter_sortedList = sortedList.rbegin(); iter_sortedList != sortedList.rend(); ++iter_sortedList)
	{
		//номер спрайта
		T_Sprites::size_type iSprite = iter_sortedList->second.iSprite;
		//номер изображения в спрайте
		S_Sprite::T_Images::size_type iImage = iter_sortedList->second.iImage;

		if( !sprites[iSprite].mImages[iImage].mNoTransparent )
			pngNodes.ConnectTexture( S_ImagePointer(iSprite, iImage) );
		else
			jpgNodes.ConnectTexture( S_ImagePointer(iSprite, iImage) );

		//проверка добавления
		CL_Console::write_line("rects are %1 %2 %3 %4", sprites[iSprite].mImages[iImage].mSrcRect.left, sprites[iSprite].mImages[iImage].mSrcRect.top, sprites[iSprite].mImages[iImage].mSrcRect.right, sprites[iSprite].mImages[iImage].mSrcRect.bottom);
	}

	size_t textureW = MAX_WIDTH;
	size_t textureH = MAX_HEIGHT;

	//список текстур PNG
	std::vector<CL_PixelBuffer> endTexturesPNG;
	//список текстур JPG
	std::vector<CL_PixelBuffer> endTexturesJPG;

	//физическое создание конечных текстур
	size_t nTexture = pngNodes.GetNumberTextures();
	for(size_t iTexture = 0; iTexture < nTexture; ++iTexture)
		endTexturesPNG.push_back( CL_PixelBuffer(textureW, textureH, cl_rgba8) );
	nTexture = jpgNodes.GetNumberTextures();
	for(size_t iTexture = 0; iTexture < nTexture; ++iTexture)
		endTexturesJPG.push_back( CL_PixelBuffer(textureW, textureH, cl_rgb8) );
	
	//обнуление цвета и альфы конечных текстур PNG
	for(std::vector<CL_PixelBuffer>::iterator iterEndTexture = endTexturesPNG.begin(); iterEndTexture != endTexturesPNG.end(); ++iterEndTexture)
		memset( (void *)iterEndTexture->get_data(), 0, iterEndTexture->get_pitch()*iterEndTexture->get_height() );
	//обнуление цвета конечных текстуры JPG
	for(std::vector<CL_PixelBuffer>::iterator iterEndTexture = endTexturesJPG.begin(); iterEndTexture != endTexturesJPG.end(); ++iterEndTexture)
		memset( (void *)iterEndTexture->get_data(), 0, iterEndTexture->get_pitch()*iterEndTexture->get_height() );
	

	//копирование подтекстур в конечные текстуры
	for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites)
	{
		for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images)
		{
			//размеры добавляемого прямоугольника
			CL_Rect srcRect = CL_Rect(0, 0, iter_images->mImage.get_width(), iter_images->mImage.get_height());
			//номер текстуры
			size_t iTexture = iter_images->mITexture;
			
			if( !iter_images->mNoTransparent )
				iter_images->mImage.convert(endTexturesPNG[iTexture], iter_images->mSrcRect, srcRect);
			else
				iter_images->mImage.convert(endTexturesJPG[iTexture], iter_images->mSrcRect, srcRect);
		}
	}

	//сохранение текстур PNG
	std::vector<CL_PixelBuffer>::size_type iEndTexture, nEndTexture;
	nEndTexture = endTexturesPNG.size();
	for(iEndTexture = 0; iEndTexture < nEndTexture; ++iEndTexture)
	{
		//Предумножение на альфу
		endTexturesPNG[iEndTexture].premultiply_alpha();
		//сохранение
		CL_PNGProvider::save(endTexturesPNG[iEndTexture], CL_PathHelp::make_absolute(workDirectoryName, OUTPUT_TEXTURE_NAME + CL_StringHelp::int_to_text(iEndTexture) + ".png") );
		CL_Console::write_line("saved %1", CL_PathHelp::make_absolute(workDirectoryName, OUTPUT_TEXTURE_NAME + CL_StringHelp::int_to_text(iEndTexture) + ".png"));
	}
	//сохранение текстур JPG
	nEndTexture = endTexturesJPG.size();
	for(iEndTexture = 0; iEndTexture < nEndTexture; ++iEndTexture)
	{
		//сохранение
		CL_JPEGProvider::save(endTexturesJPG[iEndTexture], CL_PathHelp::make_absolute(workDirectoryName, OUTPUT_TEXTURE_NAME + CL_StringHelp::int_to_text(iEndTexture) + ".jpg"));
		CL_Console::write_line("saved %1", CL_PathHelp::make_absolute(workDirectoryName, OUTPUT_TEXTURE_NAME + CL_StringHelp::int_to_text(iEndTexture) + ".jpg"));
	}
	
	//CL_Console::wait_for_key();

#if SAVE_COLLISION != 0
//Запись файлов - контуров////////////////////////////////////////////////////////
	//удаление старых файлов
	for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites)
	{
		for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images)
		{
			CL_String currentOutlineFileName = iter_images->mCollision.GetCollisionFileName();
			if ( CL_FileHelp::file_exists(currentOutlineFileName) ) 
				CL_FileHelp::delete_file(currentOutlineFileName);
		}
	}

	//объекты файлов для записи в них данных контуров
	std::map<CL_String, CL_File> outlineFiles;

	//открытие файлов
	for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites)
	{
		for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images)
		{
			CL_String currentOutlineFileName = iter_images->mCollision.GetCollisionFileName();
			std::map<CL_String, CL_File>::iterator iterOutlineFiles = outlineFiles.find(currentOutlineFileName);
			if (iterOutlineFiles == outlineFiles.end())
			{
				CL_File outlineFile;
				//формирование полного имени файла
				CL_String currentOutlineFullName = CL_PathHelp::make_absolute(workDirectoryName, currentOutlineFileName);
				//открытие файла
				CL_Console::write_line("open outline file: %1", currentOutlineFullName);
				bool is_opened = outlineFile.open(currentOutlineFullName, CL_File::open_always, CL_File::access_write);
				if (!is_opened)
					return PrintError( CL_String("I Can't open file: ") + currentOutlineFullName );
				//добавление файла в список открытых файлов
				outlineFiles.insert( std::make_pair(currentOutlineFileName, outlineFile) );
				CL_Console::write_line("-inserted %1", currentOutlineFileName);
			}
		}
	}
		
	//сохранение в бинарные файлы данных о контуре
	for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites)
	{
		for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images)
		{
			CL_String currentOutlineFileName = iter_images->mCollision.GetCollisionFileName();

			//сохранение информации о коллизии
			saveCollision(iter_images->mImage, outlineFiles[currentOutlineFileName]);

			//установка смещения для последующих таких имён
			for(T_Sprites::iterator iter_sprites2 = iter_sprites; iter_sprites2 != sprites.end(); ++iter_sprites2)
			{
				S_Sprite::T_Images::iterator iter_images2;
				if(iter_sprites2 == iter_sprites)
					iter_images2 = iter_images + 1;
				else
					iter_images2 = iter_sprites2->mImages.begin();

				for(; iter_images2 != iter_sprites2->mImages.end(); ++iter_images2)
					if(iter_images->mCollision.GetCollisionFileName() == iter_images2->mCollision.GetCollisionFileName())
						//CL_Console::write_line("+size %1", outlineFiles[currentOutlineFileName].get_position() );
						iter_images2->mCollision.mFileOffset = outlineFiles[currentOutlineFileName].get_position();
			
			}

			CL_Console::write_line("saved  %1: %2 %3", iter_images->mSourceFileName, currentOutlineFileName, iter_images->mCollision.mFileOffset);
		}
	}

	//закрытие файлов
	for(std::map<CL_String, CL_File>::iterator iterOutlineFiles = outlineFiles.begin(); iterOutlineFiles != outlineFiles.end(); ++iterOutlineFiles)
		iterOutlineFiles->second.close();
#endif
	//CL_Console::wait_for_key();
	//////////////////////////////////////////////////////////

	//формирование имени файла
	//CL_String fileResourceName = CL_PathHelp::make_absolute(workDirectoryName, locationName + ".xml");
	CL_String fileResourceName = CL_PathHelp::make_absolute(workDirectoryName, RESOURCES_FILE_NAME);

	CL_Console::write_line("fileResourceName: %1", fileResourceName);

	//открытие файла XML
	CL_File fileResourceXML;
	bool is_opened = fileResourceXML.open(fileResourceName, CL_File::create_always, CL_File::access_write);
	if( !is_opened )
		return PrintError( CL_String("I Can't open file: ") + fileResourceName );

	//запись файл заголовка
	fileResourceXML.write_string_text("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

	//Создание объекта DOM парсера
	CL_DomDocument resourceXML;

	//корневой узел - resources
	CL_DomElement resourcesElement(resourceXML, "resources");
	resourceXML.append_child(resourcesElement);

	//узлы bitmap
	std::map<CL_String, CL_String> complianceCollisions;
	//формирование map-ы bitmap
	for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites)
		for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images)
			complianceCollisions.insert( std::make_pair(iter_images->mCollision.GetCollisionFileName(), iter_images->mCollision.GetCollisionName()) );
#if SAVE_COLLISION != 0
	//запись в XML файл ресурсов битовых масок
	for(std::map<CL_String, CL_String>::iterator iterComplianceCollisions = complianceCollisions.begin(); iterComplianceCollisions != complianceCollisions.end(); ++iterComplianceCollisions)
	{
		CL_DomElement bitmapElement(resourceXML, "bitmap");
		bitmapElement.set_attribute("name", iterComplianceCollisions->second);
		bitmapElement.set_attribute("file", iterComplianceCollisions->first);
		resourcesElement.append_child(bitmapElement);
	}
#endif
	//запись в XML файл ресурсов результирующих прямоугольников
	for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites)
	{
		CL_String currentResourceName = iter_sprites->mName;

		//узел - sprite
		CL_DomElement spriteElement(resourceXML, "sprite");
		spriteElement.set_attribute("name", currentResourceName);
		resourcesElement.append_child(spriteElement);

		//тэг image
		for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images)
		{
			CL_Rect currentSrcRect = iter_images->mSrcRect;

			//узел - image
			CL_DomElement imageElement(resourceXML, "image");
			if( !iter_images->mNoTransparent )
				imageElement.set_attribute("file", OUTPUT_TEXTURE_NAME + CL_StringHelp::int_to_text(iter_images->mITexture) + ".png");
			else
				imageElement.set_attribute("file", OUTPUT_TEXTURE_NAME + CL_StringHelp::int_to_text(iter_images->mITexture) + ".jpg");
			spriteElement.append_child(imageElement);
#if SAVE_COLLISION != 0
			//сохранение коллизий
			imageElement.set_attribute("bitmap", iter_images->mCollision.GetCollisionName());
			imageElement.set_attribute_int("offset", iter_images->mCollision.mFileOffset);
#endif		
			//элемент grid
			CL_DomElement GridElement(resourceXML, "grid");
			GridElement.set_attribute("pos", cl_format("%1,%2", currentSrcRect.left + iter_images->mDeltaGrid.left, currentSrcRect.top + iter_images->mDeltaGrid.top) );
			GridElement.set_attribute("size", cl_format("%1,%2", currentSrcRect.right-currentSrcRect.left + iter_images->mDeltaGrid.right, currentSrcRect.bottom-currentSrcRect.top + iter_images->mDeltaGrid.bottom) );
			imageElement.append_child(GridElement);
		}

		//прервать выполнение сохранения, если анимации нет
		if (!iter_sprites->mIsFrame)
			continue;

		for(S_Sprite::T_Images::iterator iter_images = iter_sprites->mImages.begin(); iter_images != iter_sprites->mImages.end(); ++iter_images)
		{
			//элемент frame
			CL_DomElement frameElement(resourceXML, "frame");
			frameElement.set_attribute_int("nr", iter_images - iter_sprites->mImages.begin());
			if (iter_images->mDelay != 0)
				frameElement.set_attribute_int("speed", iter_images->mDelay);
			frameElement.set_attribute_int("x", iter_images->mOffset.x);
			frameElement.set_attribute_int("y", iter_images->mOffset.y);
			spriteElement.append_child(frameElement);
		}
	}

	//подключение всех файлов с дополнительными ресурсами
	directoryScanner.scan(workDirectoryName, "*.xml");
	while (directoryScanner.next())
	{
		//проверка валидности файла
		if (directoryScanner.is_directory() || directoryScanner.get_name() == RESOURCES_FILE_NAME)
			continue;

		//открытие ресурсного XML файла
		CL_Console::write_line("include xml file: " + directoryScanner.get_pathname());
		CL_File file(directoryScanner.get_pathname());
		CL_DomDocument doc(file);
		CL_DomElement root = doc.get_document_element();
		if (root.get_tag_name() != "resources")
		{
			CL_Console::write_line("Root name can't be: %1", root.get_tag_name());
			return PrintError("");
		}

		//добавление всех ресурсов в текущий документ
		for (CL_DomElement element = root.get_first_child_element(); !element.is_null(); element = element.get_next_sibling_element())
			resourcesElement.append_child(cloneElement(element, resourceXML));
	}

	//сохранение в файл XML структуры
	resourceXML.save(fileResourceXML);
	
	//закрытие файла
	fileResourceXML.close();

	//сохранение координат спрайтов и инициализации/деинициализации в lua скрипте
	//формирование имени файла
	//CL_String luaFileName = CL_PathHelp::make_absolute(workDirectoryName, locationName + ".lua");
	CL_String luaFileName = CL_PathHelp::make_absolute(workDirectoryName, LUA_SCRIPT_NAME);
	CL_File luaFile;
	is_opened = luaFile.open(luaFileName, CL_File::create_always, CL_File::access_write);
	if( !is_opened )
		return PrintError( CL_String("Can't open file: ") + luaFileName);


	luaFile.write_string_text( cl_format("function %1_createSprites()", locationName) );
	//запись в XML файл ресурсов результирующих прямоугольников
	for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites)
	{
		CL_String currentResourceName = iter_sprites->mName;
		int x = iter_sprites->mPos.x;
		int y = iter_sprites->mPos.y;

		luaFile.write_string_text( cl_format("\t%1 = Sprite(\"%2\", %3, %4)", currentResourceName, currentResourceName, x, y) );
	}
	luaFile.write_string_text( cl_format("end") );
	luaFile.write_string_text(CL_String(""));

	luaFile.write_string_text( cl_format("function %1_deleteSprites()", locationName) );
	//запись в XML файл ресурсов результирующих прямоугольников
	for(T_Sprites::iterator iter_sprites = sprites.begin(); iter_sprites != sprites.end(); ++iter_sprites)
	{
		CL_String currentResourceName = iter_sprites->mName;

		luaFile.write_string_text( cl_format("\t%1 = nil", currentResourceName) );
	}
	luaFile.write_string_text( cl_format("end") );

	/*
function Location01_createSprites()
    sprite1 = Sprite("sprite1", 10, 20)
    sprite2 = Sprite("sprite2", 13, 666)
    ...
    spriten = Sprite("spriten", 999, 0)
end

function Location01_deleteSprites()
    sprite1 = nil
    sprite2 = nil
    ...
    spriten = nil
end
	*/

	luaFile.close();

	CL_Console::write_line("Press any key...");
	CL_Console::wait_for_key();
}
catch(CL_Exception &exception)
{
	CL_Console::write_line("Exception caught: " + exception.get_message_and_stack_trace());
	CL_Console::wait_for_key();
	return -1;
}
	return 0;
}