Advertisement
Guest User

Untitled

a guest
Oct 19th, 2013
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 11.00 KB | None | 0 0
  1. --[[ ----------------------------------------------------------------------------------------------
  2.  Платформы: CS 1.5.10, CoP 1.6.02
  3.  Описание : Различные утилиты для работы с данными
  4.  Поддержка: 2013 © Shoker Weapon Mod
  5.  Авторы   : Shoker, <...>
  6. --]] ----------------------------------------------------------------------------------------------
  7.  
  8. --[[
  9.     TODO:
  10.         * При чтении через ltx() из ini-файла может совпасть имя секции и строка для чтения с похожей
  11.           секцией из system_ini() или любого другого ini, из за чего она буферизируется и перебьёт значения из них
  12. --]]
  13.  
  14. --************************************************************--
  15. --***********************[Ядро скрипта]***********************--
  16. --************************************************************--
  17. local _SN = script_name()
  18.  
  19. --**************************************************************--
  20. --********************[Функциональная часть]********************--
  21. --**************************************************************--
  22.  
  23. --********************** Операции с векторами - Начало **********************--
  24. --\\ Из вектора "вперёд" возвращает вектор "вправо" и вектор "вверх" (Roll не учитывается)
  25. --\\ Спасибо malandrinus за формулы                                                    
  26. function get_all_direction(dir)
  27.     --* "Вправо"
  28.     local dir_right = vector()
  29.     dir_right:crossproduct(dir, vector():set(0,1,0))
  30.     dir_right = dir_right:normalize()
  31.    
  32.     --* "Вверх"
  33.     local dir_up = vector()
  34.     dir_up:crossproduct(dir_right, dir)
  35.     dir_up = dir_up:normalize()
  36.    
  37.     return dir_right:invert(), dir_up
  38. end
  39.  
  40. --\\ Принимает координаты на земле и превращает их в координаты для экрана
  41. --\\ Можно использовать в целеуказателях (malandrinus)
  42. function point_to_hud(point)
  43.     local dev = device()
  44.     local scr_w = dev.width
  45.     local scr_h = dev.height
  46.  
  47.     local fov2 = (dev.fov/2) * (math.pi/180)
  48.     local scr_dist = 0.5 * scr_h / math.tan(fov2)
  49.  
  50.     local ppp = vector():sub(point, dev.cam_pos)
  51.     local dp = dev.cam_dir:dotproduct(ppp)
  52.  
  53.     local x = 512 + dev.cam_right:dotproduct(ppp) * scr_dist / dp * (1024/scr_w)
  54.     local y = 384 - dev.cam_top:dotproduct(ppp)   * scr_dist / dp * (768/scr_h)
  55.     return x, y
  56. end
  57.  
  58. --\\ Вектор X,Y в углах переводит в дирекцию
  59. function angle_to_direction(oangle)
  60.     local yaw = oangle.y
  61.     local pitch = oangle.x
  62.     return vector():setHP(yaw,pitch):normalize()
  63. end
  64. --********************** Операции с векторами - Конец  **********************--
  65.  
  66.  
  67. --********************** Работа с конфигами - Начало **********************--
  68. local ltxBuffer = {}    --> Хранит уже загруженные данные из конфигов
  69.  
  70. --\\ Возвращает значение из секции в конфигах
  71. --  sec         - секция
  72. --  line        - строка
  73. --  *mode       - режим чтения, по умолчанию читает число с точкой ("str", "tbl1", "bol", "num", "numf")   
  74. --  *ini_file   - ini-конфиг откуда надо читать, по умолчанию читает из system.ltx и подкл. к нему файлах
  75. -- Внимание: в случае отсутствия секции\строки в конфиге - вылета не будет, так что все такие места
  76. -- проверять соотв. функциями самим. Сделано для упрощения кода.
  77. function ltx(sec, line, mode, ini_file)
  78.     if sec == nil then
  79.         _abort(_SN, "ltx", "sec (%s)(%s)", tostring(line), tostring(mode))
  80.     end
  81.  
  82.     if not ltxBuffer[sec] then
  83.         ltxBuffer[sec] = {}
  84.     end
  85.    
  86.     local result = ltxBuffer[sec][line]
  87.     if result ~= nil then
  88.         --* Вектора возвращаются как ссылки! Поэтому их нужно копировать
  89.         if type(result) == "userdata" then
  90.             return utils.vector_copy_by_val(result)
  91.         end
  92.        
  93.         return result
  94.     end --> Нет смысла каждый раз читать из конфигов, когда достаточно 1 раз записать в таблицу
  95.  
  96.     local ini = ini_file or system_ini()
  97.  
  98.     if ltxExist(sec, line, ini) then
  99.         if mode==nil or mode=="numf" then   --> число с запятой
  100.             ltxBuffer[sec][line] = ini:r_float(sec, line)
  101.             return ltxBuffer[sec][line]
  102.         end
  103.        
  104.         if mode=="bol" then --> true\false
  105.             ltxBuffer[sec][line] = ini:r_bool(sec, line)
  106.             return ltxBuffer[sec][line]
  107.         end
  108.        
  109.         if mode=="num" then   --> целое число
  110.             ltxBuffer[sec][line] = ini:r_u32(sec, line)
  111.             return ltxBuffer[sec][line]      
  112.         end
  113.  
  114.         if mode=="str" then --> строка
  115.             ltxBuffer[sec][line] = ini:r_string(sec, line)
  116.             return ltxBuffer[sec][line]      
  117.         end
  118.        
  119.         if mode=="vec" then --> вектор
  120.             local vec = ini:r_vector(sec, line)
  121.             ltxBuffer[sec][line] = vec
  122.             return ltxBuffer[sec][line]      
  123.         end
  124.        
  125.         if mode=="tbl1" then --> таблица из строки с запятыми (1 = ..., 2 = ....)
  126.             local temp = ini:r_string(sec, line)
  127.             ltxBuffer[sec][line] = string_expl(temp, ",")
  128.             return ltxBuffer[sec][line]      
  129.         end    
  130.     end
  131.    
  132.     -- mDbg(_SN, "ltx - no section: "..sec.." || "..line)
  133.     return nil
  134. end
  135.  
  136.  
  137. --\\ Позволяет выставить значение какого либо из загруженных параметров конфига
  138. function ltxBufferW(sec, line, value)
  139.     if not ltxBuffer[sec] then
  140.            ltxBuffer[sec] = {}
  141.     end
  142.  
  143.     ltxBuffer[sec][line] = value
  144. end
  145.  
  146. --\\ Возвращает имя и описание предмета
  147. --  sec - секция предмета в конфигах
  148. function ltxItem(sec)
  149.     local name  = ltx(sec, "inv_name", "str") or ""
  150.     local descr = ltx(sec, "description", "str") or ""
  151.  
  152.     return xml(name), xml(descr)
  153. end
  154.  
  155. --\\ Проверяет, что такая комбинация секции-*строки существует в конфиге
  156. --  sec         - секция
  157. --  *line       - строка
  158. --  *ini_file   - ini-конфиг откуда надо читать, по умолчанию читает из system.ltx и подкл. к нему файлах
  159. function ltxExist(sec, line, ini_file)
  160.     local ini = ini_file or system_ini()
  161.     if sec == nil then _abort(_SN, "ltxExist", "sec") end
  162.     if not ini:section_exist(sec) then return false end
  163.     if line and not ini:line_exist(sec, line) then return false end
  164.     return true
  165. end
  166.  
  167. --\\ Возвращает <text> из текстового xml-файла
  168. --  xml_id  - идентификатор текста
  169. function xml(xml_id)
  170.     return game.translate_string(xml_id)
  171. end
  172.  
  173. --\\ Преобразует таблицу в отформатированную строку для записи в custom data
  174. --[[
  175.     local value = 123
  176.     local cd = {}
  177.     cd["test"] = {}
  178.     cd["test"]["line"] = value
  179.     cd["test"]["simple_table"] = {2,4,6,8}
  180.     cd["test"]["extended_table"] = {val1 = 1, val2 = 2, val3 = 3}  
  181.    
  182.     [test]
  183.     line = 123
  184.     simple_table = 2468
  185.     extended_table = val1, 1, val2, 2, val3, 3 
  186. ]]
  187. function tocdata(tTbl)
  188.     local result = ""
  189.     for sec, tData in pairs(tTbl) do
  190.         result = result.."\n["..sec.."]\n"
  191.         if type(tData) ~= "table" then
  192.             _abort(_SN, "tocdata", "tData is not table! result = %s, tData = %s", result, tostring(tData))
  193.         else
  194.             for line, t_Param in pairs(tData) do
  195.                 result = result..tostring(line).." = " 
  196.                 if type(t_Param) == "table" then
  197.                     if table_size(t_Param) > 0 and #t_Param > 0 then
  198.                     --* Скорее всего это нумерованная таблица, пакуем её без ключа
  199.                         for _,p1 in pairs(t_Param) do
  200.                             local first = true                     
  201.                             if first then
  202.                                 result = result..tostring(p1)
  203.                                 first = false
  204.                             else
  205.                                 result = result..", "..tostring(p1)
  206.                             end                
  207.                         end
  208.                     else
  209.                     --* Хэш-таблица, её пишем вместе с ключами
  210.                         local first = true
  211.                         for p1,p2 in pairs(t_Param) do
  212.                             if first then
  213.                                 result = result..tostring(p1)..", "..tostring(p2)
  214.                                 first = false
  215.                             else
  216.                                 result = result..", "..tostring(p1)..", "..tostring(p2)
  217.                             end                
  218.                         end                
  219.                     end            
  220.                     result = result.."\n"
  221.                 else
  222.                     result = result..tostring(t_Param).."\n"
  223.                 end
  224.             end        
  225.         end
  226.     end
  227.    
  228.     return result
  229. end
  230. --********************** Работа с конфигами - Конец **********************--
  231.  
  232. --\\ Крэшнуть игру с выводом в лог
  233. function _abort(script_name, function_name, error_string, ...)
  234.     if script_name == nil then
  235.        script_name = "<nil>"
  236.     end
  237.    
  238.     if function_name == nil then
  239.        function_name = "<nil>"
  240.     end
  241.    
  242.     abort("%s.%s - "..error_string, script_name, function_name, ...)
  243. end
  244.  
  245. --\\ Вывод в лог
  246. function log(text)
  247.     if _console == nil or (_console.GetVal("dbg.log") == true) then
  248.         get_console():execute("load ~~ " .. tostring(text))
  249.     end
  250. end
  251.  
  252. --\\ Подсчёт кол-ва элементов в таблице (под-таблицы считает за 1 элемент)
  253. function table_size(tTbl)
  254.     local count = 0
  255.     for _,_ in pairs(tTbl) do
  256.         count = count + 1
  257.     end
  258.    
  259.     return count
  260. end
  261.  
  262. --! Внимание: стандартный шаблон плохо работает с "особыми" символами (например #) и разбивает строку криво
  263. function string_expl(sStr, sDiv, Mode, bNoClear)
  264.   sStr = tostring(sStr)
  265.   if not (sStr ~= "nil" and sStr ~= '') then return {} end --> нечего разделять
  266.   local tRet = {}
  267.   local sPattern = '[%w%_]+' --> дефолтный патерн (разделение по 'словам')
  268.   if type(sDiv) == "string" then --> если задан сепаратор: разделяем по нему
  269.     if bNoClear then --> если НЕ указано 'чистить пробелы'
  270.       sPattern = '([^'..sDiv..']+)'
  271.     else --> иначе с чисткой пробелов
  272.       sPattern = '%s*([^'..sDiv..']+)%s*'
  273.     end
  274.   end
  275.   --* разделяем строку по патерну
  276.   if Mode == nil then --> обычный массив
  277.     for sValue in sStr:gmatch(sPattern) do
  278.       table.insert(tRet, sValue)
  279.     end
  280.   else
  281.     local sTypeMode = type(Mode)
  282.     if sTypeMode == "boolean" then --> таблица '[значение] = true или false'
  283.       for sValue in sStr:gmatch(sPattern) do
  284.         tRet[sValue] = Mode
  285.       end
  286.     elseif sTypeMode == "number" then --> таблица '[idx] = число или стринг'
  287.       for sValue in sStr:gmatch(sPattern) do
  288.         tRet[#tRet+1] = tonumber(sValue) or sValue
  289.       end
  290.     end
  291.   end
  292.   return tRet --> возвращаем таблицу
  293. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement