# MKXP-Z / Duktape animated rainbow hair dye for LonaRPG # Place into: ModScripts/99997_RainbowHairDuktape.rb module RainbowHairDuktape extend self ITEM_KEY = "AddHairRainbow" DISPLAY_NAME = "Rainbow Hair Dye" DESCRIPTION = "A shimmering rainbow dye that makes Lona's hair glow in animated rainbow bands." HAIR_COLOR_ID = 6 SHOP_NAME = "NoerMarketHairCutter" CACHE_TAG = "HairRainbowDuktape" TARGET_JSON = "ModScripts/PaletteChanger/20_DEFAULT_Hair_dyes.json" PHASE_BUCKETS = 12 FRAMES_PER_STEP = 4 BAND_COUNT = 6 BASE_HAIR_KEYS = %w[ AddHairDefault AddHairBlack AddHairWhite AddHairLightLavender AddHairRed AddHairYellow ] HAIRDRESSER_HAIRSTYLE_KEYS = %w[ ItemHairPony ItemHairTwinBraid ItemHairShortMessy ItemHairDancer ItemHairMessy ] HAIRDRESSER_COLOR_KEYS = (BASE_HAIR_KEYS + [ITEM_KEY]).freeze # Duktape is used only to generate band colors for a given phase bucket. # Timing is driven from Ruby (Graphics.frame_count) because that's reliable on mkxp-z. JS_CODE = <<'JAVASCRIPT' (function (global) { function clamp(v, min, max) { return v < min ? min : (v > max ? max : v); } function hsvToRgb(h, s, v) { h = ((h % 1.0) + 1.0) % 1.0; s = clamp(s, 0.0, 1.0); v = clamp(v, 0.0, 1.0); var i = Math.floor(h * 6.0); var f = h * 6.0 - i; var p = v * (1.0 - s); var q = v * (1.0 - f * s); var t = v * (1.0 - (1.0 - f) * s); var r, g, b; switch (i % 6) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; default: r = v; g = p; b = q; break; } return [ clamp((r * 255) | 0, 0, 255), clamp((g * 255) | 0, 0, 255), clamp((b * 255) | 0, 0, 255) ]; } var RainbowHair = { exportColumns: function (w, bucket, bucketCount) { w = w | 0; bucket = bucket | 0; bucketCount = bucketCount | 0; if (w <= 1) return "255,32,32"; if (bucketCount <= 0) bucketCount = 1; var phase = bucket / bucketCount; var out = []; for (var x = 0; x < w; x++) { var u = x / (w - 1); var wave = Math.sin((u + phase) * Math.PI * 2.0) * 0.045; var hue = (u * 0.94 + 0.02 + wave + phase + 1.0) % 1.0; var rgb = hsvToRgb(hue, 0.98, 1.0); out.push(rgb[0], rgb[1], rgb[2]); } return out.join(","); } }; global.RainbowHair = RainbowHair; })(this); JAVASCRIPT def log(msg) if defined?(System) && System.respond_to?(:puts) System.puts("[rainbow_hair_duktape] #{msg}") else p "[rainbow_hair_duktape] #{msg}" end end def clamp_byte(v) v = v.round v = 0 if v < 0 v = 255 if v > 255 v end def hsv_to_rgb(h, s, v) h = h.to_f % 1.0 h += 1.0 if h < 0.0 s = [[s.to_f, 0.0].max, 1.0].min v = [[v.to_f, 0.0].max, 1.0].min i = (h * 6.0).floor f = h * 6.0 - i p = v * (1.0 - s) q = v * (1.0 - f * s) t = v * (1.0 - (1.0 - f) * s) r, g, b = case i % 6 when 0 then [v, t, p] when 1 then [q, v, p] when 2 then [p, v, t] when 3 then [p, q, v] when 4 then [t, p, v] else [v, p, q] end [clamp_byte(r * 255), clamp_byte(g * 255), clamp_byte(b * 255)] end def duktape_available? defined?(Duktape) && Duktape.respond_to?(:available?) && Duktape.respond_to?(:eval) && Duktape.available? rescue false end def init_js return if @js_ready return unless duktape_available? Duktape.eval(JS_CODE) @js_ready = true @using_duktape = true log("Duktape rainbow generator enabled") rescue => e @using_duktape = false log("Duktape init failed, using Ruby fallback: #{e.class}: #{e}") end def using_duktape? init_js if @using_duktape.nil? !!@using_duktape end def load_target_names return @target_names if @target_names names = [] begin if File.exist?(TARGET_JSON) data = JSON.parse(Ruby310Compat.read_text_file(TARGET_JSON)) if data.is_a?(Hash) && data["names"].is_a?(Array) names = data["names"] elsif data.is_a?(Array) data.each do |entry| next unless entry.is_a?(Hash) && entry["names"].is_a?(Array) names.concat(entry["names"]) end end end rescue => e log("Failed to parse #{TARGET_JSON}: #{e.class}: #{e}") end expanded = [] names.each do |name| n = name.to_s.split("@").first.to_s next if n.empty? expanded << n.downcase ext = File.extname(n) expanded << n[0...-ext.length].downcase unless ext.empty? end @target_names = expanded.uniq end def active? return false unless $game_player && $game_player.actor $game_player.actor.record_HairColor.to_i == HAIR_COLOR_ID rescue false end def target_file?(filename) load_target_names.include?(filename.to_s.downcase) end def active_for?(filename) active? && target_file?(filename) end def current_bucket @current_bucket ||= 0 end # Reliable animation timing on mkxp-z. def compute_bucket frame = (Graphics.frame_count rescue 0).to_i ((frame / FRAMES_PER_STEP) % PHASE_BUCKETS) end def tick new_bucket = compute_bucket @last_active = false if @last_active.nil? if active? if new_bucket != current_bucket || !@last_active @current_bucket = new_bucket @columns_cache = {} apply_player_hair_refresh end @last_active = true else if @last_active @current_bucket = 0 @columns_cache = {} apply_player_hair_refresh end @last_active = false end rescue => e log("tick failed: #{e.class}: #{e}") end def columns_for_width(width, bucket = current_bucket) @columns_cache ||= {} key = [width.to_i, bucket.to_i] return @columns_cache[key] if @columns_cache[key] width = width.to_i width = 1 if width < 1 bucket = bucket.to_i cols = nil if using_duktape? begin raw = Duktape.eval("RainbowHair.exportColumns(#{width},#{bucket},#{PHASE_BUCKETS})") parts = raw.to_s.split(",").map { |v| v.to_i } cols = parts if parts.length >= width * 3 rescue => e @using_duktape = false log("Duktape exportColumns failed for width=#{width}, bucket=#{bucket}: #{e.class}: #{e}") end end if cols.nil? phase = bucket.to_f / PHASE_BUCKETS cols = [] 0.upto(width - 1) do |x| u = width <= 1 ? 0.0 : x.to_f / (width - 1) wave = Math.sin((u + phase) * Math::PI * 2.0) * 0.045 hue = (u * 0.94 + 0.02 + wave + phase) % 1.0 rgb = hsv_to_rgb(hue, 0.98, 1.0) cols.concat(rgb) end end @columns_cache[key] = cols end def apply_if_needed(bitmap, filename) return bitmap unless active_for?(filename) return bitmap if bitmap.nil? || (bitmap.respond_to?(:disposed?) && bitmap.disposed?) colors = bitmap.get_data.unpack("C*") width = bitmap.width height = bitmap.height bucket = current_bucket cols = columns_for_width(BAND_COUNT, bucket) y = 0 while y < height row_min = nil row_max = nil x = 0 while x < width offset = (x + y * width) * 4 a = colors[offset + 3] if a && a > 10 row_min = x if row_min.nil? row_max = x end x += 1 end if !row_min.nil? && !row_max.nil? visible_w = row_max - row_min + 1 visible_w = 1 if visible_w < 1 y_shift = ((height - 1 - y) / 2) + bucket x = row_min while x <= row_max offset = (x + y * width) * 4 r = colors[offset] g = colors[offset + 1] b = colors[offset + 2] a = colors[offset + 3] if a && a > 10 luma = (r * 299 + g * 587 + b * 114) / 1000.0 unless luma < 18 local_x = x - row_min band_index = ((local_x + y_shift) * BAND_COUNT / visible_w) % BAND_COUNT ci = band_index * 3 base_r = cols[ci] base_g = cols[ci + 1] base_b = cols[ci + 2] shade = 0.60 + (luma / 255.0) * 0.40 glow = 26 + (luma / 255.0 * 24).to_i colors[offset] = clamp_byte(base_r * shade + glow) colors[offset + 1] = clamp_byte(base_g * shade + glow) colors[offset + 2] = clamp_byte(base_b * shade + glow) end end x += 1 end end y += 1 end bitmap.set_data(colors.pack("C*")) bitmap rescue => e log("apply_if_needed failed: #{e.class}: #{e}") bitmap end def apply_player_hair_refresh return unless $game_player return unless $game_player.actor Cache.clear_chs_character if defined?(Cache) && Cache.respond_to?(:clear_chs_character) if $game_player.actor.respond_to?(:portrait) && $game_player.actor.portrait $game_player.actor.portrait.refresh if $game_player.actor.portrait.respond_to?(:refresh) $game_player.actor.portrait.update if $game_player.actor.portrait.respond_to?(:update) end $game_player.refresh_chs if $game_player.respond_to?(:refresh_chs) rescue => e log("apply_player_hair_refresh failed: #{e.class}: #{e}") end def ensure_rainbow_item return if !$data_items || !$data_ItemName return if $data_ItemName[ITEM_KEY] base = $data_ItemName["AddHairYellow"] || $data_ItemName["AddHairRed"] || $data_ItemName["AddHairWhite"] || $data_items.compact.find { |it| it.respond_to?(:common_tags) && it.common_tags && it.common_tags["DyeHairColor"] } unless base log("Unable to create #{ITEM_KEY}: no base hair dye item found") return end item = base.clone new_id = $data_items.length item.instance_variable_set(:@id, new_id) item.instance_variable_set(:@item_name, ITEM_KEY) item.instance_variable_set(:@name, DISPLAY_NAME) item.instance_variable_set(:@description, DESCRIPTION) common_tags = item.instance_variable_get(:@common_tags) common_tags = common_tags ? common_tags.dup : {} common_tags["DyeHairColor"] = HAIR_COLOR_ID item.instance_variable_set(:@common_tags, common_tags) base_price = item.instance_variable_get(:@price).to_i base_price = 150 if base_price <= 0 item.instance_variable_set(:@price, (base_price * 1.35).round) $data_items[new_id] = item $data_ItemName[ITEM_KEY] = item log("Registered #{ITEM_KEY} as item id=#{new_id}") rescue => e log("ensure_rainbow_item failed: #{e.class}: #{e}") end def filter_hairdresser_barter return unless $data_barters && $data_barters[SHOP_NAME].is_a?(Hash) items = $data_barters[SHOP_NAME]["items"] return unless items.is_a?(Array) items.delete_if do |entry| entry.is_a?(Hash) && HAIRDRESSER_COLOR_KEYS.include?(entry["item_name"].to_s) end rescue => e log("filter_hairdresser_barter failed: #{e.class}: #{e}") end def cached_hair_shop?(goods) return false unless goods.is_a?(Hash) keys = goods.keys.map(&:to_s) !(HAIRDRESSER_HAIRSTYLE_KEYS & keys).empty? || !(HAIRDRESSER_COLOR_KEYS & keys).empty? end def filter_cached_hairdresser_colors return unless $story_stats stores = $story_stats["CharacterItems"] return unless stores.is_a?(Hash) stores.each do |store_key, store_data| next unless store_data.is_a?(Array) next unless store_data[0].is_a?(Hash) goods = store_data[0] next unless cached_hair_shop?(goods) HAIRDRESSER_COLOR_KEYS.each do |item_key| goods.delete(item_key) goods.delete(item_key.to_sym) end end rescue => e log("filter_cached_hairdresser_colors failed: #{e.class}: #{e}") end def install_runtime_data ensure_rainbow_item filter_hairdresser_barter rescue => e log("install_runtime_data failed: #{e.class}: #{e}") end end module DataManager class << self unless method_defined?(:load_mod_database_rainbow_hair_duktape) alias_method :load_mod_database_rainbow_hair_duktape, :load_mod_database end def load_mod_database load_mod_database_rainbow_hair_duktape RainbowHairDuktape.install_runtime_data end if method_defined?(:extract_save_contents) unless method_defined?(:extract_save_contents_rainbow_hair_duktape) alias_method :extract_save_contents_rainbow_hair_duktape, :extract_save_contents end def extract_save_contents(contents) extract_save_contents_rainbow_hair_duktape(contents) RainbowHairDuktape.install_runtime_data RainbowHairDuktape.filter_cached_hairdresser_colors end end end end module BitmapChanger class << self unless method_defined?(:find_cache_name_rainbow_hair_duktape) alias_method :find_cache_name_rainbow_hair_duktape, :find_cache_name end def find_cache_name(filename) base = find_cache_name_rainbow_hair_duktape(filename) return base unless RainbowHairDuktape.active_for?(filename) phase_tag = "#{RainbowHairDuktape::CACHE_TAG}_#{RainbowHairDuktape.current_bucket}" return phase_tag if base.nil? || base.empty? return base if base.include?(phase_tag) "#{base}:#{phase_tag}" end unless method_defined?(:change_bitmap_rainbow_hair_duktape) alias_method :change_bitmap_rainbow_hair_duktape, :change_bitmap end def change_bitmap(bitmap, filename) bitmap = change_bitmap_rainbow_hair_duktape(bitmap, filename) RainbowHairDuktape.apply_if_needed(bitmap, filename) bitmap end end end if defined?(GIM_ADDON) module GIM_ADDON unless method_defined?(:manual_barters_rainbow_hair_duktape) alias_method :manual_barters_rainbow_hair_duktape, :manual_barters end def manual_barters(tmpTradeID) RainbowHairDuktape.install_runtime_data RainbowHairDuktape.filter_cached_hairdresser_colors if tmpTradeID == RainbowHairDuktape::SHOP_NAME manual_barters_rainbow_hair_duktape(tmpTradeID) end end end if defined?(Window_CheatMenuHairColor) class Window_CheatMenuHairColor def minmaxHairColor(value) return RainbowHairDuktape::HAIR_COLOR_ID if value < 0 return 0 if value > RainbowHairDuktape::HAIR_COLOR_ID value end def cursor_right(wrap = false) SndLib.play_cursor $game_player.actor.record_HairColor += 1 $game_player.actor.record_HairColor = minmaxHairColor($game_player.actor.record_HairColor) RainbowHairDuktape.apply_player_hair_refresh draw_item(index) end def cursor_left(wrap = false) SndLib.play_cursor $game_player.actor.record_HairColor -= 1 $game_player.actor.record_HairColor = minmaxHairColor($game_player.actor.record_HairColor) RainbowHairDuktape.apply_player_hair_refresh draw_item(index) end end end unless $mkxpz_rainbow_hair_duktape_hooked $mkxpz_rainbow_hair_duktape_hooked = true Graphics.singleton_class.class_eval do alias_method :rainbow_hair_duktape_update_without_hook, :update def update(*args) rainbow_hair_duktape_update_without_hook(*args) RainbowHairDuktape.tick end end end RainbowHairDuktape.log("loaded")