RGSS – 晴兰的秘密社团 https://seiran.mist.so Ruby与RGSS研究 Tue, 15 Jan 2019 10:09:01 +0000 zh-CN hourly 1 https://wordpress.org/?v=4.9.5 在RM中使用gem和bundle https://seiran.mist.so/rgss/%e5%9c%a8rm%e4%b8%ad%e4%bd%bf%e7%94%a8gem%e5%92%8cbundle.html https://seiran.mist.so/rgss/%e5%9c%a8rm%e4%b8%ad%e4%bd%bf%e7%94%a8gem%e5%92%8cbundle.html#respond Mon, 25 Aug 2014 17:28:10 +0000 http://seiran.mist.so/?p=136 其实很多东西跟普通ruby使用gem和bundle是一样的,但是RM没有自带rubygems,因此有两种思路,一种是给RM嵌入一个rubygems,一种是利用另一个Ruby(也就是实际运行bundle的ruby.exe等)来发现require需要的文件和依赖关系。

下面以第二种思路为例,例子任务是使用iniparse这个gem来帮助RM里面读Game.ini。

注意:RPGMaker系列本身不支持载入.so文件,因此能用到的gems只能是纯Ruby形式的源文件组成的代码,这个文章与这个限制无关,也无意绕过这个限制。只是提供了另一种管理脚本插件的思路:借用rubygems。产生的gem目录也可以最后放在加密的rgssad(rgss2a/rgss3a)文件里面并用某种手段当做本地目录读出来,从而保证了加密保护游戏程序的语义,当然这里也不讨论对gem目录的加密和解包具体方法。

1. 首先像正常使用bundle一样在Game.exe目录下建立一个gemfile:

source 'http://ruby.taobao.org'

gem 'iniparse'

2. 用bundle在工程目录安装所需的gems:

用cmd在工程目录下运行下列代码。

bundle install --path gems

3. 在RM的脚本编辑器中插入一段辅助代码,让require可以自动去找到我们指定的gem:

def rb(code, args = nil)
  open "run.rb", "w" do |f|
    f.write "
      class Output
        def <<(obj)
          puts [Marshal.dump(obj)].pack('M')
        end
      end
      $output = Output.new
    "
    f.write code
  end
  system "ruby run.rb #{args}> list.txt"
  Marshal.load File.read('list.txt').unpack("M").first
end

module Kernel
 alias oreq require
 $:.concat rb %{ $output << $: }
 def require(a)
   u = rb %{$output << Gem.find_files(ARGV[0])}, a
   u.select(&FileTest.method(:file?)).any?{|req|oreq req}
 end

 Object::RUBY_VERSION = rb %{$output << RUBY_VERSION} 
 require 'rubygems'
 alias require oreq
end

 

4. 这个时候在脚本编辑器之后可以插入使用的代码了,这里我们用的是RGSS3(RPG Maker VX Ace)的代码例子:

require 'iniparse'
msgbox IniParse.parse(File.read('Game.ini'))["Game"]["Scripts"]

5. 最后,运行的方式是在cmd下运行下列代码,你也可以建立快捷方式:

bundle exec "Game.exe console"

 

]]>
https://seiran.mist.so/rgss/%e5%9c%a8rm%e4%b8%ad%e4%bd%bf%e7%94%a8gem%e5%92%8cbundle.html/feed 0
RGSS3Facets 0.02 https://seiran.mist.so/rgss/rgss3facets.html https://seiran.mist.so/rgss/rgss3facets.html#comments Sun, 23 Feb 2014 07:43:53 +0000 http://seiran.mist.so/?p=128 0.02

Class:
#基于类的通用cache系统,比如
x = Bitmap.cache(“Graphics/Parallaxes/Mountain4”) #你懂的
y = Bitmap.cache(“Graphics/Parallaxes/Mountain4”)
# x.object_id == y.object_id应该成立,同一个位图
#Bitmap.clear_cache #你懂的
#也可以是自定义对象
class A
def initialize(a, b)
@a, @b = a, b
end
end
x = A.cache(3, 5)
y = A.cache(3, 5)
#应该是同一个对象

# RGSS3Facets::CachePolicy 奇怪的东西:
Bitmap.cache_policy = RGSS3Facets::CachePolicy::Default #Cache在内存中,以Hash的形式记录,类似于默认脚本的Cache或者RPG::Cache
Bitmap.cache_policy = RGSS3Facets::CachePolicy::Marshal.new(Bitmap) #Cache不是在内存中而是以Marshal形式存到磁盘上
Bitmap.cache_policy = RGSS3Facets::CachePolicy::BareMarshal.new(Bitmap) #Cache不是在内存中而是以Marshal形式存到磁盘上,而且没有Marshal头,仅仅是直接调用了_dump和_load

Bitmap:
#Bitmap::MarshalPolicy bitmap的marshal方案可以是
Bitmap::MarshalPolicy = Bitmap::BitmapMarshalPolicy::Raw # [width, height, data].pack(“LLa*”)
Bitmap::MarshalPolicy = Bitmap::BitmapMarshalPolicy::RawCompress # [width, height, Zlib::Deflate.deflate(data)].pack(“LLa*”)
Bitmap::MarshalPolicy = Bitmap::BitmapMarshalPolicy::BitmapFile # Marshal内容相当于savebmp做的,也就是一个合法的bmp文件内容

Object:
load_script(name) #也就是eval read_data(name), TOPLEVEL_BINDING, “Load Script: #{name}”, 1

0.01

Object:
font.assign(:size=>5, :color=>Color.new(255,0,0,255)) # font.size=5; font.color = Color.new(255,0,0,255)
object.self # 返回本身,为了某些场合可以用&:self
object.deepcopy #=>某种深拷贝,也就是Marshal.load Marshal.dump object
object.template(“{{a}}, {{b}}”)#=>模板替换,也就相当于是”#{obj.a},#{obj.b}”,但模板内容可以是变量。
私有:
read_data(“Data/1.txt”) #=>读取Data/1.txt的内容,可以是加密包中的内容
write_data(“Data/1.txt”, “Hello”)#=>把Hello写到Data/1.txt,只能是磁盘上的,不会变更加密包
sugar(/\b类\b/){“class”} #=>宏替换,$RGSS_SCRIPTS.each{|x| x[3].gsub!(/\b类\b/){“class”}}
with(obj){}#=>obj.instance_eval{}
a = 5
ref{}[“a”]=3
a = ref{}[“a”]#=> 上下文变量的字符引用

Module:
Sprite_Base.each_object{|x| p x}#遍历Sprite_Base的实例
Vocab.each_constant{|value, name| p value, name}#遍历常量,以值和名的形式
MyModule.to_class #生成一个include了本模块的类(可以new了)
attr_constant :a, 5# 相当于def a(); 5; end

Proc:
lambda{|x| a}.call(a,b,c)可以写成lambda{|x| a}.update(a,b,c) lambda{|x| a}.fire(a,b,c)随便什么方法名都行
用method_missing实现的,不一定是call了

Range:
(1..5).clamp(a) # 如果a<1返回1 如果a>5返回5 否则返回a

Rect:
rect.each_slice(5, 5) do |r| … end # 将这个rect均匀分成5×5的部分,每一部分调用一下迭代器

Exception:
ex.raise # reraise ex
ex.translate(新的消息) # 返回一个和ex只有消息不同的异常对象,也就是ex.exception的别名

IO:
IO.binread(“1.txt”) #二进制读取1.txt
IO.binwrite(“1.txt”, “Hello”)#二进制写入1.txt

Symbol:
to_proc(这个功能VA本来就有)

String:
self.note.match_notes “<itemid = {{item}}>”, “<skillid = {{skill}}>”#如果self.note是一个”<itemid = 5> <skillid = 3>”的话,返回一个hash {“item”=>5, “skill”=>3}

Bitmap:
bitmap.repeat_blt(bitmap.rect, another_bitmap, another_bitmap.rect)#尽可能平铺绘制another_bitmap的rect部分的内容
bitmap.address:位图地址
bitmap.savebmp(“1.bmp”): 以bmp格式保存为1.bmp
bitmap.savepng(“1.png”):以png格式保存为1.png
bitmap.getBitmap(rect) : 返回rect部分构成的新位图
bitmap.split(:A=>[0,0,128,128], :B=>[0,128,128,128]):返回一个hash,其中hash[:A]= bitmap.getBitmap(Rect.new(0,0,128,128)),类推
bitmap.with_tone!(tone)
bitmap.with_tone(tone) #用指定的色调tone来处理本位图

(下面是还在测试和修正的内容)
Sprite:
sprite.image #返回sprite能看到的图形,没有考虑tone,wave系列,考虑了src_rect
Plane:
plane.image #返回plane能看到的图形,没有考虑tone,考虑了屏幕大小和循环的情况

 

# http://seiran.mist.so

# mixin in to Kernel (Object)
module RGSS3Facets
  module RGSS
    Sprite   = ::Sprite
    Bitmap   = ::Bitmap
    Rect     = ::Rect
    Plane    = ::Plane
    Viewport = ::Viewport
    Tilemap  = ::Tilemap
  end

  class CPtr
    RMM = Win32API.new("Kernel32", "RtlMoveMemory", "LLL", "L")
    SLEN = Win32API.new("Kernel32", "lstrlenA", "L", "L")
    WLEN = Win32API.new("Kernel32", "lstrlenW", "L", "L")
    def initialize(start, len = 0)
      @start, @len = start, len
    end
    def [](st, le = nil)
      if !le
        CPtr.new(self[st * 4, 4].unpack("L").first)
      else
        buf = ""*le
        RMM.call *[buf, @start+st, le].pack("pLL").unpack("L*")
        buf = buf.force_encoding("US-ASCII") if buf.respond_to?(:force_encoding)
        buf
      end
    end
    def +(a)
      CPtr.new(@start+a, @len)
    end
    def []=(st, le, str)
      RMM.call *[@start+st, str, [le,str.size].min].pack("LpL").unpack("L*")
    end
    def to_s(size = nil)
      a = SLEN.call(to_i) 
      size ||= a
      self[0, [size, a].min]
    end
    def to_ws(size = nil)
      a = WLEN.call(to_i) 
      size ||= a
      self[0, [size, a].min * 2]
    end
    def to_i
      @start
    end
  end

  module Object
    public 
    def assign(hash)
      hash.each{|k, v|send "#{k}=", v}
      self
    end

    def self
      self
    end

    def identity
      lambda{|x| x}
    end

    def send_rescue(*a, &b)
      send *a rescue b.call
    end

    # [1,2,3,4,5].select(&true) 
    # 真是一点用都没有啊。。。
    def to_proc
      proc{ self }
    end

    def deepcopy
      Marshal.dump Marshal.load self  
    end

    def template(str, lb = "{{", rb = "}}")
      regexp = Regexp.new(Regexp.escape(lb) + "(.*?)" + Regexp.escape(rb))
      str.gsub(regexp) do send $1 end
    end

    def grep_var(cond)
      instance_variables.select{|x| cond === x}.each{|y| yield(instance_variable_get(y), y)}
    end

    def call_each(method, *args)
      args.each{|x|
        send method, *args
      }
    end

    private
    def weaken(a = StandardError)
      yield
    rescue a => ex
       raise
    rescue Exception => ex
        raise StandardError, ex.message, ex.backtrace
    ensure
        $@.slice!(0, 2) if $@ 
    end

    class NoException < StandardError; end
    class CallerHint < NoException; end

    def hint(array)
      raise CallerHint, "No Exception", array
    end

    def reraise(ex)
       raise ex.class, ex.message, ex.backtrace
    end

    def using(*a)
      yield
      a.reverse.each(&:dispose)
    end

    def write_data(name, *content)
      File.open(name, 'wb') do |f| content.each do |x| f.write x end end
    end

    def load_script(name)
      eval read_data(name), TOPLEVEL_BINDING, "Load Script: #{name}", 1
    end

    def read_data(name)
       begin
        File.open(name, 'rb') do |f| f.read end
      rescue Exception
          x = Marshal.method(:load)
          y = class << Marshal; self; end
          y.send(:define_method, :load){|a, *b| a.respond_to?(:read) ? a.read : a.to_s}
          ret = load_data(name)
          y.send(:define_method, :load, x)
          ret
       end
    end

    def sugar(regexp)
      $RGSS_SCRIPTS.each{|x| x[3] = x[3].gsub(regexp){ yield($~) } }
    end

    def with(obj, &a)
      obj.instance_eval &a
    end

    class Ref
      def initialize(binding = nil)
        @binding = binding || TOPLEVEL_BINDING
      end
      def [](text)
        eval(text, @binding)
      end
      def []=(text, obj)
        eval "#{text} = ObjectSpace._id2ref(#{obj.object_id})", @binding
      end
    end

    def ref(&b)
      Ref.new(b && b.binding)
    end
  end

  module Module
    def each_object
      ObjectSpace.each_object(self).each{|obj|
        yield obj
      }
    end

    def each_constant
      if block_given?
       constants.each{|x|
         yield const_get(x), x
       }
      else
       Hash[constants.map{|x| [x, const_get(x)]}]
      end
    end

    def to_class
      Class === self ? self : begin
        @_avatar ||= begin
          this = self
          Class.new do include this end
        end
      end
    end

    def attr_constant(sym, c)
      define_method(sym, lambda{c})
    end

    alias def_constant_method  attr_constant 
  end

  class FacadeClass
     def initialize(obj, *a)
       @obj  = obj
       @args = a  
     end
     def new(*a, &b)
       v = @obj.new(*a, &b)
       @args.each{|x| v = x.new(v)}
       v
     end
  end

  module CachePolicy
    class Default
      def initialize
        @cache = {}
      end
      def set_or_get(k)
        if has?(k)
          get(k)
        else
          set(k, yield)
        end
      end
      def set(k, v)
        @cache[k] = v
      end
      def get(k, v)
        @cache[k]
      end
      def remove(k)
        @cache.delete k
      end
      def has?(k)
        @cache.include?(k)
      end
      def clear
        @cache.each{|k, v| yield v, k} if block_given?
        @cache.clear
      end
    end

    class Marshal
      def initialize(klass)
        @klass = klass
        @base = "Data/Cache/#{encode_name klass}/"
        Dir.mkdir @base rescue 1
      end

      def set_or_get(k)
        if has?(k)
          get(k)
        else
          set(k, v = yield)
          v
        end
      end

      def encode_name(k)
        [::Marshal.dump(k)].pack("m").tr("\n+/", "_%$")
      end

      def filename(k)
        @base+encode_name(k)
      end

      def set(k, v)
        write_data filename(k), ::Marshal.dump(v)
      end

      def get(k)
        ::Marshal.load read_data filename(k)
      end

      def has?(k)
        FileTest.exist?(filename(k))
      end

    end

    class BareMarshal < Marshal
      def set(k, v)
        write_data filename(k), v._dump(0)
      end

      def get(k)
        @klass._load read_data filename(k)
      end
    end
  end

  module Class
    def [](*a)
      RGSS3Facets::FacadeClass.new(self, *a)
    end

    def cache_policy
      @cache_policy ||= CachePolicy::Default.new
    end

    def cache_policy=(obj)
      @cache_policy = obj
    end

    def c_new(*a, &b)
      cache_policy.set_or_get([a, b]){ new(*a, &b) }
    end

    alias cache c_new

    def c_clear
      cache_policy.clear do |x| x.dispose if x.respond_to?(:dispose) && !x.send_rescue(:disposed?){false} end
    end

    alias clear_cache c_clear
  end

  module Proc
    def method_missing(sym, *a, &b)
      call(*a, &b)
    end
  end

  module Range
    def clamp(val)
      [[first, val].max, exclude_end? ? last.succ : last].min
    end
  end

  module Rect
    def to_a
      [x, y, width, height]
    end

    def each_slice(div_x = 1, div_y = 1)
      cx, cy = width / div_x, height / div_y
      a = RGSS::Rect.new(0, 0, cx, cy)
      ny = y
      div_y.times{
        nx = x
        div_x.times{
          a.set(nx, ny, cx, cy)
          yield a
          nx += cx
        }
        ny += cy
      }
    end
  end

  module Binding
    def [](text)
       eval(text, self)
    end
    def []=(text, obj)
      eval "#{text} = ObjectSpace._id2ref(#{obj.object_id})", self
    end
  end

  module Exception
    def raise
      reraise self
    end
=begin
See what the doc said,
 exception([error_message]) 
 引数を指定しない場合は self を返します。
 そうでなければ、自身のコピーを生成し、message 属性を error_message にして返します。
 raise は、実質的に、例外オブジェクトの exception メソッドの呼び出しです。

 If no argument is given, return self.
 Otherwise, return a copy of self, with the message property changed to error_message
 actually 'raise' calls an Exception object's exception method.

 Because method 'exception' is actually a method to replace error message.
here I just rename it to translate
=end
    def translate(msg = nil)
      exception(msg || self.message)
    end

  end

  module IO_extend
    def binread(file)
      open(file, 'rb') do |f|
        f.read
      end
    end
    def binwrite(file, content)
      open(file, 'wb') do |f|
        f.write content
      end
    end
  end

  module RegExp
    def sub(str, *a, &b)
      str.sub(self, *a, &b)
    end
    def gsub(str, *a, &b)
      str.gsub(self, *a, &b)
    end
  end

  module Symbol
    def to_proc
      lambda{|*a| a.shift.send self, *a}
    end
  end

  module Comparable
    def min_with(obj)
      self < obj ? self : obj
    end
    def max_with(obj)
      self > obj ? self : obj
    end
  end

  module String
    def match_note(expr)
      a = Regexp.new expr.gsub(/\{\{(\S+)\}\}/){
        "(?<#$1>.*?)"
      }
      self =~ a
      $~
    end

    def match_notes(*args)
      ret = {}
      args.each{|x|
        v = match_note(x)
        v.names.each do |k|
          ret[k] = v[k]
        end
      }
      ret
    end
  end

  module Bitmap
    def repeat_blt_rect(dst, bm, src)
      y = dst.y
      ye = dst.y + dst.height
      xe = dst.x + dst.width
      sw = src.width
      sh = src.height
      while y < ye
        x = dst.x
        while x < xe
          blt(x, y, bm, src)
          x += sw
        end
        y += sh
      end
    end

    def repeat_blt(*args)
      x,y,w,h,bm,rect = args
      if RGSS::Rect === x
        return repeat_blt_rect(*args)
      else
        return repeat_blt_rect(RGSS::Rect.new(x, y, w, h), bm, rect)
      end
    end

    def address
      CPtr.new(object_id*2)[4][2][4]
    end

    def getBitmap(rect = self.rect)
      x = RGSS::Bitmap.new(rect.width, rect.height)
      x.blt(0, 0, self, rect)
      x
    end

    def split(opt = {})
      ret = {}
      opt.each{|k, v|
        r = case v
          when Rect then v
          when Array then Rect.new(*v)
        end
        ret[k] = getBitmap(r)
      }
      ret
    end

    def savebmp(filename)
      write_data filename, 
        [0x4d42, (len = width*height*4), 0, 0, 54].pack("SLSSL"),
        CPtr.new(object_id*2)[4][2][2][0, 40],
        address[0, len]
    end

    def savepng(filename)
      write_data filename,
        (signature = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"),

        [13].pack("N"),
        (header = ["IHDR", width, height, 8, 6, 0, 0, 0].pack("a4NNCCCCC")),
        [Zlib.crc32(header)].pack("N"),

        [width*height*4+height].pack("N"),
        (dat = "IDAT" << Zlib::Deflate.deflate(address[0, (cw = width* 4) * (ch = height)].instance_eval{
           ret = []
           (ch-1).downto(0){|x|
             ret << "" << self[x*cw, cw].unpack("L*").map{|x|
               (x & 0xFF0000) >> 16 | (x & 0xFF) << 16 | (x & 0xFF00FF00)
             }.pack("L*")
           }
           ret.join
        })),
        [Zlib.crc32(dat)].pack("N"),
        "\x00\x00\x00\x00\x49\x45\x4E\x44\xAE\x42\x60\x82"
    end

    def with_tone!(tone)
      address[0, width*height*4] = address[0, width*height*4].unpack("L*").map{|long|
        b, g, r, a = [long].pack("L").unpack("C*")
        grayfull = (r * 38 + g * 75 + b * 15) >> 7
        r = tone.red  + r + (grayfull - r) * tone.gray / 256  
        g = tone.green+ g + (grayfull - g) * tone.gray / 256
        b = tone.blue + b + (grayfull - b) * tone.gray / 256
        [b, g, r, a].pack("C*").unpack("L").first
      }.pack("L*")
      self
    end

    def with_tone(tone)
      clone.with_tone!
    end

  end

  module Sprite
    def image
      b = RGSS::Bitmap.new(src_rect.width, src_rect.height)
      b.blt(0, 0, bitmap, src_rect)
      b
    end

    def image=(bitmap)
      rect = bitmap.rect
      rect.width  = [rect.width, src_rect.width].min
      rect.height = [rect.height, src_rect.height].min
      self.bitmap.blt(rect.x, rect.y, bitmap, bitmap.rect)
    end
  end

  module Plane
    def image
      b = RGSS::Bitmap.new((Graphics.width  + bitmap.width - 1) / bitmap.width * bitmap.width, 
                     (Graphics.height + bitmap.height - 1) / bitmap.height * bitmap.height)
      a = b.rect.dup
      a.x = -self.ox
      a.y = -self.oy
      b.repeat_blt(a, self.bitmap, self.bitmap.rect)
      b
    end
  end

  module Font
    def marshal_dump
      ret = []
      [:name, :size, :bold, :italic, :outline, :shadow, :color, :out_color].each{|k|
        ret << [k, send(k)] if respond_to?(k)
      }
      ret
    end

    def marshal_load(obj)
      obj.each{|x|
        k, v = x
        self.send "#{k}=", v
      }
    end
  end

end

class Object
 include RGSS3Facets::Object
end

class Module
 include RGSS3Facets::Module
end

class Class
 include RGSS3Facets::Class
end

class Proc
 include RGSS3Facets::Proc
end

class Range
 include RGSS3Facets::Range
end

class Rect
 include RGSS3Facets::Rect  
end

class Binding
  include RGSS3Facets::Binding
end

class Exception
  include RGSS3Facets::Exception
end

class IO
  extend RGSS3Facets::IO_extend
end

class RegExp
  include RGSS3Facets::RegExp
end

class Symbol
  include RGSS3Facets::Symbol
end

class String
  include RGSS3Facets::String
end

class Sprite
  include RGSS3Facets::Sprite
end

class Plane
  include RGSS3Facets::Plane
end

class Bitmap
  include RGSS3Facets::Bitmap

  module BitmapMarshalPolicy
    class Raw
      def self._dump(obj)
        [obj.width, obj.height].pack("LL")+ obj.address[0, obj.width*obj.height*4]
      end

      def self._load(arg)
        w, h = arg.unpack("LL")
        bi = RGSS3Facets::RGSS::Bitmap.new(w, h)
        bi.address[0, w*h*4] = arg[8..-1]
        bi
      end
    end

    class RawCompress
      def self._dump(obj)
        [obj.width, obj.height].pack("LL")+ Zlib::Deflate.deflate(obj.address[0, obj.width*obj.height*4])
      end

      def self._load(arg)
        w, h = arg.unpack("LL")
        bi = RGSS3Facets::RGSS::Bitmap.new(w, h)
        bi.address[0, w*h*4] = Zlib::Inflate.inflate(arg[8..-1])
        bi
      end
    end

    class BitmapFile
      def self._dump(obj)
        [0x4d42, (len = obj.width*obj.height*4), 0, 0, 54].pack("SLSSL") <<
        RGSS3Facets::CPtr.new(obj.object_id*2)[4][2][2][0, 40] <<
        obj.address[0, len]
      end

      def self._load(arg)
        w, h = arg[18, 8].unpack("LL")
        obj = RGSS3Facets::RGSS::Bitmap.new(w, h)
        obj.address[0, w*h*4] = arg[54..-1]
        obj
      end
    end
  end

  MarshalPolicy = :Raw

  def _dump(limit)
    self.class::BitmapMarshalPolicy.const_get(self.class::MarshalPolicy)._dump(self)
  end

  def self._load(obj)
    self.class::BitmapMarshalPolicy.const_get(self.class::MarshalPolicy)._load(obj)
  end
end

class Font
  include RGSS3Facets::Font
end

module RGSS3Facets::Enumerable

  def partial_sum(start, *s)
    if block_given?
      inject([start], *s) do |a, b|
        a << yield(a[-1], b)
      end
    else
      v = s[0].to_proc
      inject([start]) do |a, b|
        a << v.call(a[-1], b)
      end
    end
  end
end

Class.each_object{|klass|
  klass.send :include, RGSS3Facets::Enumerable if klass.ancestors.include?(Enumerable)
}

#load_script "Data/utils/api.rb"
#load_script "Data/utils/gc.rb"

 

]]>
https://seiran.mist.so/rgss/rgss3facets.html/feed 5
[RGSS]RGStorage 1.00 https://seiran.mist.so/rgss/rgssrgstorage-1-00.html https://seiran.mist.so/rgss/rgssrgstorage-1-00.html#comments Mon, 16 Dec 2013 12:39:27 +0000 http://seiran.mist.so/?p=73 介绍

RGStorage实现了一个通用的存储类,统一接口,可以从以下实际或虚拟文件系统来读写文件资料

  • 文件系统
  • ar文件
  • RGSS加密系统(只读)。

并可以通过可选的扩展来读写

  • 7z文件
  • zip文件
  • http://开头的资源

同时在以上的基础上重定义了require方法,也可以混入Object,使它能像普通的Ruby的require一样工作,但不局限于require具体文件,比如:

  • require “http://codepad.org/abcdefgh/raw.rb”
  • require “1.zip!/test.rb”
  • require “RGSSAD://a.rb”

基本用法:

把一个类似于文件路径的字符串叫做资源标识符(resource identifier, rsrc_id)。

因为可以通过RGStorage::Active来重新设定关联,以下的用法的举例与默认关联有关。

1.RGStorage.get rsrc_id

取得资源的内容

  • RGStorage.get “C:\\windows\\system32\\notepad.exe”#相当于直接读取notepad.exe
  • RGStorage.get “extended.ar!/Sc330.exe” #从ar文件取得Sc330.exe,作为字符串返回
  • RGStorage.get “http://example.com/sample.zip”#从http读取数据,需要扩展文件extended.ar
  • RGStorage.get “<T>prefix”#取一个临时文件名,前缀是prefix,也就是返回”临时文件夹\\prefix0001″这样的形式
  • RGStorage.get “a.zip!/a.png” # 从zip读数据,需要扩展(extended.ar)

2. RGStorage.set rsrc_id, content

设置资源的内容

  • RGStorage.set “1.txt”, “Hello world” #相当于往1.txt里面写Hello world字符串
  • RGStorage.set “mytest.ar!/1.txt”, “Hello world”  #往ar文件里面某个项目写内容
  • RGStorage.set “a.zip!/a.png”, “pngdata” #往zip里面某个文件写内容,需要扩展(extended.ar)

3. RGStorage.copyTo rsrc_id1, rsrc_id2

复制资源内容,相当于RGStorage.set(rsrc_id2, RGStorage.get(rsrc_id1))

  • RGStorage.copyTo “1.txt”, “a.zip!/2.txt” #相当于添加/更新1.txt到a.zip,文件名改为2.txt
  • RGStorage.copyTo “http://test.com/sample.exe”, “b.exe”  #相当于下载文件

基本设置:

默认设置是:

RGStorage::Active = RGController.new RGRouter.new [
     [/\.ar!/, ArSystem],
     [/\.ar/, FileSystem, MarshalFormatter, ZlibFormatter],
     [/<T>.*/, TemporaryFile],
     [/\.*/, FileSystem]
    ]

其中每一个设置的格式为,

[ 匹配条件, 文件系统, 转换器1, 转换器2, 转换器3,…]

匹配条件可以是正则表达式,范围,或者一个接受一个参数返回真假值的lambda/proc

文件系统是RGFileSystem类的实例,或者实现了get/set方法的对象,如果可以get/set一个rsrc_id,那么get/set的调用将返回一个lambda{|rsrc|}(get)或者lambda{|rsrc, content|}(set),否则应该返回nil,这是用来测试一个文件是否可读/可写

转换器也是实现了get/set方法的对象,或者RGFormatter类的实例,但get/set直接返回转换结果,比如MarshalFormatter的get方法是对输入(记为input)返回Marshal.load(input)的结果, 而set刚好相反。

 

]]>
https://seiran.mist.so/rgss/rgssrgstorage-1-00.html/feed 1
RGSSType alpha 0.1 https://seiran.mist.so/rgss/rgsstype-alpha-0-1.html https://seiran.mist.so/rgss/rgsstype-alpha-0-1.html#respond Wed, 27 Nov 2013 11:33:11 +0000 http://seiran.mist.so/?p=68 一个用于直接在RGSS3的位图上写文字的类,

不经过bitmap.draw_text,而是直接写像素,

就算RGSS3启动时没有安装字体,安装字体之后使用RGSSType.new仍然有用

这个版本只实现了一个简单的写字体方法,而且并没有作为Bitmap的方法被定义

用法:

RGSSType#font

返回RGSSType使用的Font对象,可以设置他的字型字号颜色等, 文字轮廓阴影暂时不支持。

RGSSType#writetext(bitmap, string, x, y, color[, height])

在bitmap上,从(x, y)开始书写文字string, height

=begin
  RGSSType Alpha 0.1
  Author: 晴兰 Seiran
  Website: http://seiran.mist.so
  License:
    Copyright (c) 2013, Seiran
    All rights reserved.
    Redistribution and use in source and binary forms, with or without 
    modification, are permitted provided that the following conditions are met:
    1. Redistributions of source code must retain the above copyright notice, 
    this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice, 
    this list of conditions and the following disclaimer in the documentation 
    and/or other materials provided with the distribution.
    3. Neither the name of the seiran.mist.so nor the names of its contributors 
    may be used to endorse or promote products derived from this software 
    without specific prior written permission.
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
    POSSIBILITY OF SUCH DAMAGE.
=end

#encoding:UTF-8
module SAFX
  module_function

  def to_param(a)
    case a when Integer then "L" when String then "p" end
  end

  def to_ptr(a)
    case a  when Integer then a when String then [a].pack('p').unpack("L").first end
  end

  def api(dll,func)
    lambda{|*args|
       Win32API.new(dll,func,args.map{|x|to_param(x)}, 'i').call(*args)
    }
  end

  def to_wc(str, cp = 65001)
    (buf = ""*str.length)[0, 2*api('Kernel32', 'MultiByteToWideChar').call(cp, 
    0, to_ptr(str), -1, buf, buf.length)]
  end

  def to_mb(str, cp = 65001)
    (buf = ""* str.length)[0, api('Kernel32', 'WideCharToMultiByte').call(cp, 
    0, to_ptr(str), -1, buf, buf.length, 0, 0)]
  end

end

class RGSSType
  module API
    FUNC = {}
    HANDLES  = [DL::dlopen('gdi32'), DL::dlopen("KERNEL32"), 
    DL::dlopen("USER32")]
    def self.method_missing(sym, *args)
      FUNC[sym] ||= DL::CFunc.new(
        HANDLES.map{|x| x[sym.to_s] rescue nil}.compact[0] ,
        DL::TYPE_VOIDP, '', :stdcall
      )      
      FUNC[sym].call(args.map{|x| DL::CPtr[x]})
    end
  end

  attr_accessor :font

  def initialize(font = ::Font.new ,w = 300, h = 300)
    @font = font
    @dc = API.CreateCompatibleDC(0)
    @ptr = DL.malloc(w * h * 4)
    @bitmap = API.CreateBitmap(w, h, 1, 32, @ptr)
    @w, @h = w, h
    DL.free(@ptr)
    resetfont
  end

  def resetfont
    API.DeleteObject(@hfont) if @hfont != nil
    API.SelectOBject(@dc, @hold) if @hold != nil
    @hold = nil
    @hfont = nil
  end

  def bits
    buf = [].pack("x#{@w * @h * 4}")
    API.GetBitmapBits(@bitmap, buf.size, buf)
    buf
  end

  def boolvalue a
    a ? 1 : 0
  end

  def dispose
    resetfont
    API.DeleteObject(@bitmap)
    API.ReleaseDC(@dc)
  end

  def createfont
    resetfont
    args = [@font.size, 0, 0, 0, 
            @font.bold ? 700 : 400, 
            boolvalue(@font.italic), 
            0,0,
            1, #default_charset
            0,0,4,0,
            SAFX.to_wc(@font.name+"")]
    #                        here^
    @hfont = API.CreateFontW(*args)
    @hold = API.SelectObject(@dc, @hfont)
  end

  def getchar8b(a)
    API.GetGlyphIndicesW(@dc, SAFX.to_wc(a+""), 1, (index=[].pack("x4")), 0)
    #                                    here^
    index = index.unpack("L").first
    glyph = [].pack("x24")
    mat   = [0,1,0,0,0,0,0,1].pack("S*")
    len   = API.GetGlyphOutline(@dc, index, 0x85, glyph, 0, 0, mat)
    buf   = [].pack "x#{len}"
    len = API.GetGlyphOutline(@dc, index, 0x85, glyph, len, buf, mat)
    bx, by, ox, oy, cx, cy = glyph.unpack("llllss")
    [buf, bx, by, ox, oy, cx, cy, len]
  end

  def char_height(ch)
    u =  getchar8b(ch)
    height = u[5]
  end

  def writechar8b(bitmap, ch, cx, cy, color, height = nil)
    u =  getchar8b(ch)
    r,g,b,a=color.red, color.green, color.blue, color.alpha
    return [0, 0] if u[0].size == 0
    colors = 256.times.map{|x|
      Color.new(r * x  * 4 / 256, g * x  * 4 / 256, b * x  * 4 / 256, a)
    }
    i = 0
    height ||= u[0].size / ((u[1] + 3) / 4 * 4)
    v = u[0].unpack("C*")
    u[2].times{|y|
      u[1].times{|x|
         bitmap.set_pixel(x + cx + u[3], cy + height - u[4] + y, colors[v[i]*4])
         i += 1
      }
      i = (i + 3) >> 2 << 2
    }
    [u[5], u[6]]
  end

  def writetext(bitmap, text, cx, cy, color)
    createfont
    height = text.split(//).map{|x| char_height(x)}.max
    text.split(//).each{|ch|
      w,h = writechar8b(bitmap, ch, cx, cy, color, height)
      cx += w
    }
  end
end

 

]]>
https://seiran.mist.so/rgss/rgsstype-alpha-0-1.html/feed 0
SAFX进展报告(updating) https://seiran.mist.so/rgss/safx-status.html https://seiran.mist.so/rgss/safx-status.html#respond Sat, 23 Nov 2013 05:59:03 +0000 http://seiran.mist.so/?p=66 2013/11/13 13:55

下一步:

  •    并非同个DLL的函数用UDP传输。假想接口是:defudp(“sum”, sum, “remote.exe”, 1234)
  •    基础库:括号里为选择中:TCP/UDP,即时编译用(TCC/Squerrel),图像处理(libgd/opencv),输入(DInput),从内存播放声音(SEAL/Audiere/OpenAL),打包(liblzma/libarchive)

 

目前的进展的例子:http://codepad.org/VFmwq4jp

基本约定:所有这种返回字符串用来eval的函数叫usefunc

编译为DLL之后,RGSS中写一行use “1.dll”就行了
或者严格点use “1.dll”, “imported”
use DLL名, usefunc名(缺省是imported)
之所以叫imported是因为你可以用它仅仅是导入同dll的所有其他函数等等:

C 代码复制打印
  1. USEFUNC(math);
  2. USEFUNC(color);
  3. USEFUNC(imported){
  4.    this_is_a_usefunc;
  5.     use(“math”);
  6.     use(“color”);
  7.    end_usefunc;
  8. }
  1. module(A)
  2.           def(“self.add”, add)
  3.           def(“self.sub”, sub)
  4.           defva(“self.sum”, sum)
  5. end

的例子解释

Ruby里面直接用
A.add(3,5) A.sub(4, 6) A.sum(1,2,3,4,5,6,7,8,9,10)等来调用

上面defva的意思是自动打包不定参数(所有类型def的打包方式定义在safx.h里面,(白字:不是stdafx.h))

]]>
https://seiran.mist.so/rgss/safx-status.html/feed 0