Item: Добавить поддержку градиента в Item.titleColor и Item.descriptionColor #12

Closed
opened 2026-01-12 17:27:04 +00:00 by varttist · 1 comment
Owner

Описание

Необходимо:

  • Сделать, чтобы параметры Item.titleColor и Item.descriptionColor принимали либо ColorString (строку), либо {ColorString, ColorString} (таблицу)
  • Сделать, чтобы при окраске предмета самостоятельно определялось будет ли цвет постоянным или будет градиент (по типу переданного параметра)
  • Добавить в глобальное Api функцию окраски текста градиентом
  • Использовать эту функцию в окраске названия и описания предмета

Приложения

Функция создания градиента в тексте (автор @ssdaniel24):

---Makes gradient on given text with many of core.colorize
---@param color_from string ColorString
---@param color_to string ColorString
---@param msg string text
---@return string
local function make_gradient(color_from, color_to, msg)
  msg = core.strip_colors(msg)
  local color_from_t = core.colorspec_to_table(color_from)
  local color_to_t = core.colorspec_to_table(color_to)
  local gradient_step_t = { r = 0, g = 0, b = 0, a = 0 }
  for k,_ in pairs(gradient_step_t) do
    gradient_step_t[k] = (color_to_t[k] - color_from_t[k]) / string.len(msg)
  end
  local res = ''
  local current_color_t = table.copy(color_from_t)
  for i = 1,#msg do
    local ch = msg:sub(i,i)
    local col = core.colorspec_to_colorstring(current_color_t)
    res = res .. core.colorize(col, ch)
    for k,_ in pairs(gradient_step_t) do
      current_color_t[k] = current_color_t[k] + gradient_step_t[k]
    end
  end
  return res
end

-- https://ru.lipsum.com/
local text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor\nincididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis\nnostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu\nfugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in\nculpa qui officia deserunt mollit anim id est laborum."

-- добавляет надпись под прицелом для тестирования градиента
core.register_on_joinplayer(function (player)
  player:hud_add({
    type = "text",
    name = "test",
    number = 0xFFFFFF,
    scale = {x = 100, y = 20},
    text = make_gradient('#f0f', '#0f0', text),
    position = {x = 0.5, y = 0.55},
    offset = {x = 0, y = 0 },
  })
end)
# Описание Необходимо: - Сделать, чтобы параметры `Item.titleColor` и `Item.descriptionColor` принимали либо `ColorString` (строку), либо `{ColorString, ColorString}` (таблицу) - Сделать, чтобы при окраске предмета самостоятельно определялось будет ли цвет постоянным или будет градиент (по типу переданного параметра) - Добавить в глобальное `Api` функцию окраски текста градиентом - Использовать эту функцию в окраске названия и описания предмета # Приложения Функция создания градиента в тексте (автор @ssdaniel24): ```lua ---Makes gradient on given text with many of core.colorize ---@param color_from string ColorString ---@param color_to string ColorString ---@param msg string text ---@return string local function make_gradient(color_from, color_to, msg) msg = core.strip_colors(msg) local color_from_t = core.colorspec_to_table(color_from) local color_to_t = core.colorspec_to_table(color_to) local gradient_step_t = { r = 0, g = 0, b = 0, a = 0 } for k,_ in pairs(gradient_step_t) do gradient_step_t[k] = (color_to_t[k] - color_from_t[k]) / string.len(msg) end local res = '' local current_color_t = table.copy(color_from_t) for i = 1,#msg do local ch = msg:sub(i,i) local col = core.colorspec_to_colorstring(current_color_t) res = res .. core.colorize(col, ch) for k,_ in pairs(gradient_step_t) do current_color_t[k] = current_color_t[k] + gradient_step_t[k] end end return res end -- https://ru.lipsum.com/ local text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor\nincididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis\nnostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu\nfugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in\nculpa qui officia deserunt mollit anim id est laborum." -- добавляет надпись под прицелом для тестирования градиента core.register_on_joinplayer(function (player) player:hud_add({ type = "text", name = "test", number = 0xFFFFFF, scale = {x = 100, y = 20}, text = make_gradient('#f0f', '#0f0', text), position = {x = 0.5, y = 0.55}, offset = {x = 0, y = 0 }, }) end) ```
varttist self-assigned this 2026-01-12 17:27:04 +00:00
varttist added the due date 2026-01-25 2026-01-12 17:28:34 +00:00
varttist added the
task
assigned
2
label 2026-01-13 17:52:51 +00:00
varttist added this to the Tasks Kanban project 2026-01-14 14:31:47 +00:00
varttist moved this to In Progress in Tasks Kanban on 2026-01-14 14:35:06 +00:00
varttist added
task
canceled
3
and removed
task
assigned
2
labels 2026-01-15 12:45:09 +00:00
Author
Owner

К сожалению добавить градиент к переводимым полям невозможно:
Градиент работал путем добавления для каждого символа своего цвета, однако когда мы переводим какие-то строки -- мы не имеем возможности получить текст, который надо "покрасить".

Отказываться от локализации в пользу градиентов -- не вижу смысла.

Метод Smc.makeGradient() останется в сборке, но сможет окрашивать только статичные строки.

То есть описания предметов не будут иметь градиент в данный момент. Ситуация может измениться, если в luanti добавлят escape-последовательности, которые делают градиент по строке (я такие пока что не нашел)

К сожалению добавить градиент к переводимым полям **невозможно**: Градиент работал путем добавления для каждого символа своего цвета, однако когда мы переводим какие-то строки -- мы не имеем возможности получить текст, который надо "покрасить". Отказываться от локализации в пользу градиентов -- не вижу смысла. Метод `Smc.makeGradient()` останется в сборке, но сможет окрашивать только статичные строки. То есть описания предметов не будут иметь градиент в данный момент. Ситуация может измениться, если в luanti добавлят escape-последовательности, которые делают градиент по строке (я такие пока что не нашел)
varttist moved this to Done in Tasks Kanban on 2026-01-15 12:51:36 +00:00
Sign in to join this conversation.
No Label
task
canceled
3
1 Participants
Notifications
Due Date
2026-01-25
Dependencies

No dependencies set.

Reference: Apancore.Studio/simple-makes-complex#12