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); } }
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; }
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); }
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"); }
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); } } }
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); } } }
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(); } }
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); } } }
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; }
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; }
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()); } }
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(); } } }